v0.6.0
Upgrading from v0.5.1 with fleet durability requires stopping the whole fleet
first. A fleet with bucket durability can use a rolling update.
- Each Durable Object facet has its own SQLite file and replication stream. A
facet write no longer copies the facet database into the root or joins a
root transaction. A facet can start from a class in `ctx.exports`. Facets
from v0.5.1 migrate on first open.
- `crypto.subtle` supports Ed25519 (also as `NODE-ED25519`) and X25519, with
`raw` import and export. (#221)
- Per-cell memory: the SQL statement cache is capped at 128 KiB of compiled
statements instead of 1 MiB of SQL text, which could hold tens of MB. A cell
shares one object store client instead of three, and operation timers no
longer leak one map entry per operation.
- Stricter workerd parity: `WorkerCode` requires `compatibilityDate`, a wasm
module in `modules` must be `{ wasm: bytes }`, `export const X = "..."` in
a main module fails the Worker's start, and the `transactionSync()` callback
receives no argument.
- `ctx.exports` holds `default` and each entrypoint, and `fetch()` on its
stubs sends an HTTP request.
- R2 keeps empty key segments, so `a/b`, `/a/b`, `a//b`, and `a/b/` are four
objects. An object v0.5.1 wrote as `photos/` stays at `photos`.
- Invalid UTF-8 in SQLite `TEXT` decodes as U+FFFD instead of failing.
- `Headers` accepts values above U+00FF and decodes response values as UTF-8.
- A WebSocket close is `wasClean: true` whenever the peer sent a close frame.
- `run_worker_first` accepts the root route `/`.
- Recovery waits for range evidence from a follower's log tail.
Issues fixed:
- #226: Nest `transactionSync()` calls through the root storage handle.
- #227: Resolve relative imports in Dynamic Worker subdirectories.
- #228: Fire a re-armed alarm on time despite the handler's pending timers.
- #229: Deliver WebSocket frames while `webSocketMessage()` runs.
- #232: R2 `list()` returns non-ASCII and `%` keys as `put()` received them.
Co-authored-by: Ryan Dahl <[email protected]>
Co-authored-by: Yusuke Tanaka <[email protected]>Bartek Iwańczuk authored signed1 parent 42269c1commit bad4649d01f0db84cdc9093527e72e64ca7a14bfBrowse files
59 files changed+39441−33716
Files (59)
- Cargo.lock+1−1
- crates/celld/Cargo.toml+1−1
- crates/celld/actor.rs+45−12
- crates/celld/bucket.rs+90−23
- crates/celld/cell_host.rs+208−0
- crates/celld/cell_runtime.rs+310−0
- crates/celld/clean_reload.rs+49−0
- crates/celld/deploy.rs+1−1
- crates/celld/engine_api.rs+877−0
- crates/celld/facet_streams.rs+313−0
- crates/celld/generation.rs+204−1
- crates/celld/host_channels.rs+282−0
- crates/celld/host_services.rs+23−0
- crates/celld/http_streams.rs+2105−0
- crates/celld/js.rs+0−0
- crates/celld/js/bootstrap.rs+32−263
- crates/celld/js/crypto.js+70−8
- crates/celld/js/crypto.rs+140−14
- crates/celld/js/harness.js+7693−8724
- crates/celld/js/headers.js+3−2
- crates/celld/js/modules.rs+83−9
- crates/celld/js/r2_ops.rs+21−735
- crates/celld/js/services/kv.js+1127−0
- crates/celld/js/storage_ops.rs+17−21
- crates/celld/js/websocket.rs+234−1014
- crates/celld/kv_blob.rs+180−0
- crates/celld/lib.rs+59−46
- crates/celld/local_store.rs+229−217
- crates/celld/ltx_repl.rs+4670−4441
- crates/celld/ltx_replication.rs+162−0
- crates/celld/main.rs+3756−3707
- crates/celld/main/websocket.rs+157−153
- crates/celld/node_log.rs+6276−5755
- crates/celld/ownership_store.rs+8−2
- crates/celld/pool.rs+787−820
- crates/celld/queue_policy.rs+465−0
- crates/celld/r2_store.rs+750−0
- crates/celld/runtime.rs+2915−3685
- crates/celld/storage.rs+3244−3534
- crates/celld/wake.rs+1−1
- crates/celld/wake_entry.rs+124−0
- crates/celld/ws_registry.rs+1069−0
- crates/logic/cron.rs+41−0
- docs/README.md+7−0
- docs/cloudflare-compat.md+6−0
- docs/guarantees.md+44−0
- docs/limitations.md+1−1
- docs/security.md+224−223
- docs/services/d1.md+3−2
- docs/services/durable-object-facets-flow.svg+123−124
- docs/services/durable-object-facets.md+87−95
- docs/services/durable-objects.md+71−63
- docs/services/dynamic-workers.md+10−6
- docs/services/r2.md+25−0
- docs/services/static-assets.md+2−2
- docs/services/workers.md+4−1
- docs/wasm.md+10−9
- examples/dynamic-worker-tails/index.js+1−0
- examples/facets/index.js+1−0
modifiedCargo.lock+1−1View file
| @@ -285,7 +285,7 @@ | ||
| 285 | 285 | |
| 286 | 286 | [[package]] |
| 287 | 287 | name = "celld" |
| 288 | -version = "0.5.1" | |
| 288 | +version = "0.6.0" | |
| 289 | 289 | dependencies = [ |
| 290 | 290 | "aes", |
| 291 | 291 | "aes-gcm", |
modifiedcrates/celld/Cargo.toml+1−1View file
| @@ -1,6 +1,6 @@ | ||
| 1 | 1 | [package] |
| 2 | 2 | name = "celld" |
| 3 | -version = "0.5.1" | |
| 3 | +version = "0.6.0" | |
| 4 | 4 | edition = "2021" |
| 5 | 5 | rust-version = "1.94.1" |
| 6 | 6 | license = "Apache-2.0" |
modifiedcrates/celld/actor.rs+45−12View file
| @@ -2,6 +2,7 @@ | ||
| 2 | 2 | |
| 3 | 3 | //! The serial lifecycle executor and its shell-side request drivers. |
| 4 | 4 | |
| 5 | +use crate::cell_host::CellHost; | |
| 5 | 6 | use crate::js::{HttpResponse, WsOut}; |
| 6 | 7 | use crate::machine::{ |
| 7 | 8 | ownership_on_evict_from_environment, pressure_config_from_environment, |
| @@ -10,7 +11,7 @@ | ||
| 10 | 11 | }; |
| 11 | 12 | use crate::ownership_store::{now_ms, BucketOwnership, LeaseCasError}; |
| 12 | 13 | use crate::peer_auth::{self, PeerAuth}; |
| 13 | -use crate::runtime::{CellHost, RuntimeManager}; | |
| 14 | +use crate::runtime::RuntimeManager; | |
| 14 | 15 | use anyhow::Context as _; |
| 15 | 16 | use celld_logic::{ |
| 16 | 17 | on_event, AdoptedCell, CapacityPeer, CasGuard, CasOutcome, CellId, Channel, Config, Effect, |
| @@ -94,33 +95,45 @@ | ||
| 94 | 95 | } |
| 95 | 96 | |
| 96 | 97 | /// The shared displacement discipline for production and deterministic timers. |
| 98 | +/// | |
| 99 | +/// `armed` is the only per-slot map, so what this holds is bounded by the | |
| 100 | +/// timers that are armed right now. A second map keyed by slot would not be: | |
| 101 | +/// `TimerSlot::OperationDeadline` names a unique `OpId`, and the Actor arms | |
| 102 | +/// one deadline for every watched effect, so a slot-keyed entry that outlives | |
| 103 | +/// its arm grows once per operation for the lifetime of the process. | |
| 97 | 104 | pub struct TimerSlots<V> { |
| 98 | 105 | armed: BTreeMap<TimerSlot, (u64, V)>, |
| 99 | - ordinals: BTreeMap<TimerSlot, u64>, | |
| 106 | + next_ordinal: u64, | |
| 100 | 107 | } |
| 101 | 108 | |
| 102 | 109 | impl<V> Default for TimerSlots<V> { |
| 103 | 110 | fn default() -> Self { |
| 104 | 111 | Self { |
| 105 | 112 | armed: BTreeMap::new(), |
| 106 | - ordinals: BTreeMap::new(), | |
| 113 | + next_ordinal: 0, | |
| 107 | 114 | } |
| 108 | 115 | } |
| 109 | 116 | } |
| 110 | 117 | |
| 111 | 118 | impl<V> TimerSlots<V> { |
| 112 | - /// Creates one arm, assigns its stable per-slot ordinal, and applies it. | |
| 119 | + /// Creates one arm, assigns its ordinal, and applies it. | |
| 120 | + /// | |
| 121 | + /// The ordinal counts arms of every slot together rather than arms of one | |
| 122 | + /// slot, so no slot-keyed counter has to outlive the arm it numbered. A | |
| 123 | + /// per-slot counter pruned when its slot leaves `armed` would restart at | |
| 124 | + /// zero, and [`fire`](Self::fire) would then accept a spent arm as the | |
| 125 | + /// arm that replaced it. | |
| 113 | 126 | pub fn arm(&mut self, timer: Timer, at_mono_ms: u64, value: V) -> (TimerArm, Option<V>) { |
| 114 | 127 | let slot = TimerSlot::of(&timer); |
| 115 | - let ordinal = self.ordinals.entry(slot.clone()).or_default(); | |
| 128 | + let ordinal = self.next_ordinal; | |
| 129 | + self.next_ordinal = ordinal.saturating_add(1); | |
| 116 | 130 | let arm = TimerArm { |
| 117 | 131 | slot: slot.clone(), |
| 118 | - ordinal: *ordinal, | |
| 132 | + ordinal, | |
| 119 | 133 | timer, |
| 120 | 134 | at_mono_ms, |
| 121 | 135 | }; |
| 122 | - *ordinal = ordinal.saturating_add(1); | |
| 123 | - let displaced = self.replace(&slot, arm.ordinal, value); | |
| 136 | + let displaced = self.replace(&slot, ordinal, value); | |
| 124 | 137 | (arm, displaced) |
| 125 | 138 | } |
| 126 | 139 | |
| @@ -157,6 +170,17 @@ | ||
| 157 | 170 | fn clear_slot(&mut self, slot: &TimerSlot) { |
| 158 | 171 | self.armed.remove(slot); |
| 159 | 172 | } |
| 173 | + | |
| 174 | + /// Every slot this map still retains, across all of its bookkeeping. | |
| 175 | + /// | |
| 176 | + /// `TimerSlot::OperationDeadline` carries a unique `OpId`, so a per-slot | |
| 177 | + /// entry that outlives its arm grows once per operation and never | |
| 178 | + /// shrinks. The count exists so a test can prove the map returns to the | |
| 179 | + /// armed set. A map added beside `armed` must be counted here. | |
| 180 | + #[cfg(all(test, celld_internal_tests))] | |
| 181 | + pub fn retained_slots(&self) -> usize { | |
| 182 | + self.armed.len() | |
| 183 | + } | |
| 160 | 184 | } |
| 161 | 185 | |
| 162 | 186 | pub struct MemoryOwnership { |
| @@ -1500,7 +1524,7 @@ | ||
| 1500 | 1524 | origin: &'static str, |
| 1501 | 1525 | ) -> ActivityGuard { |
| 1502 | 1526 | let cancellation = self.drain_pins.begin(request, request_id, origin); |
| 1503 | - let host = self.runtime.clone().map(CellHost::V8); | |
| 1527 | + let host = self.runtime.clone().map(CellHost::Engine); | |
| 1504 | 1528 | #[cfg(all(test, celld_internal_tests))] |
| 1505 | 1529 | let host = host.or_else(|| self.scripted_activity_host.clone().map(CellHost::Scripted)); |
| 1506 | 1530 | ActivityGuard { |
| @@ -2095,7 +2119,16 @@ | ||
| 2095 | 2119 | &body, |
| 2096 | 2120 | &peer.node, |
| 2097 | 2121 | )?; |
| 2098 | - let response = outbound.body(body).send().await?; | |
| 2122 | + let request = outbound.body(body).build()?; | |
| 2123 | + // Keep response decoding after transport selection so a test transport | |
| 2124 | + // cannot bypass the donor contract with an invented typed acceptance. | |
| 2125 | + #[cfg(all(test, celld_internal_tests))] | |
| 2126 | + let response = match crate::asyncrt::services().handoff_transport_for_test() { | |
| 2127 | + Some(transport) => transport.send(request).await?, | |
| 2128 | + None => http.execute(request).await?, | |
| 2129 | + }; | |
| 2130 | + #[cfg(not(all(test, celld_internal_tests)))] | |
| 2131 | + let response = http.execute(request).await?; | |
| 2099 | 2132 | peer_auth::validate_response(response.headers())?; |
| 2100 | 2133 | let status = response.status(); |
| 2101 | 2134 | let response: HandoffResponse = match response.json().await { |
| @@ -2200,7 +2233,7 @@ | ||
| 2200 | 2233 | fail_publish_once, |
| 2201 | 2234 | fence, |
| 2202 | 2235 | ActorHostServices { |
| 2203 | - host: runtime.map(CellHost::V8), | |
| 2236 | + host: runtime.map(CellHost::Engine), | |
| 2204 | 2237 | drain_pins: DrainPinRegistry::default(), |
| 2205 | 2238 | ownership, |
| 2206 | 2239 | peer_http: reqwest::Client::new(), |
| @@ -2232,7 +2265,7 @@ | ||
| 2232 | 2265 | fail_publish_once, |
| 2233 | 2266 | fence, |
| 2234 | 2267 | ActorHostServices { |
| 2235 | - host: runtime.map(CellHost::V8), | |
| 2268 | + host: runtime.map(CellHost::Engine), | |
| 2236 | 2269 | drain_pins, |
| 2237 | 2270 | ownership, |
| 2238 | 2271 | peer_http, |
modifiedcrates/celld/bucket.rs+90−23View file
| @@ -39,6 +39,7 @@ | ||
| 39 | 39 | use object_store::list::PaginatedListOptions; |
| 40 | 40 | use object_store::list::PaginatedListStore; |
| 41 | 41 | use object_store::path::Path; |
| 42 | +use object_store::path::PathPart; | |
| 42 | 43 | use object_store::Attribute; |
| 43 | 44 | use object_store::Attributes; |
| 44 | 45 | use object_store::ClientOptions; |
| @@ -63,6 +64,9 @@ | ||
| 63 | 64 | include!(env!("CELLD_INTERNAL_BUCKET_TESTS")); |
| 64 | 65 | } |
| 65 | 66 | |
| 67 | +/// The stored form of an empty blob key segment. See [`Bucket::blob_path`]. | |
| 68 | +const EMPTY_SEGMENT: &str = "%"; | |
| 69 | + | |
| 66 | 70 | /// Explicit credentials for a managed installation; everything else comes |
| 67 | 71 | /// from the standard `AWS_*` environment. |
| 68 | 72 | pub struct StaticCredentials { |
| @@ -856,6 +860,64 @@ | ||
| 856 | 860 | key.strip_prefix(self.prefix.as_str()).unwrap_or(key) |
| 857 | 861 | } |
| 858 | 862 | |
| 863 | + /// The location of a blob: the only way a blob key becomes a [`Path`], | |
| 864 | + /// and [`Self::listed_key`] is its inverse. | |
| 865 | + /// | |
| 866 | + /// Each segment is percent-encoded the way `Path::from` encodes it, so a | |
| 867 | + /// blob written before this mapping existed is still at its location. | |
| 868 | + /// `Path::from` also drops an empty segment, and that made `a/b`, `/a/b`, | |
| 869 | + /// `a//b`, and `a/b/` one object where R2 keeps four. An empty segment | |
| 870 | + /// is therefore stored as [`EMPTY_SEGMENT`], which `Path::from` never | |
| 871 | + /// produces because it encodes every `%`. | |
| 872 | + fn blob_path(&self, key: &str) -> Path { | |
| 873 | + let prefix = self | |
| 874 | + .prefix | |
| 875 | + .split('/') | |
| 876 | + .filter(|segment| !segment.is_empty()) | |
| 877 | + .map(PathPart::from); | |
| 878 | + // An empty key is the scope itself, not one empty segment below it. | |
| 879 | + let key = key | |
| 880 | + .split('/') | |
| 881 | + .filter(|_| !key.is_empty()) | |
| 882 | + .map(|segment| match segment { | |
| 883 | + "" => PathPart::parse(EMPTY_SEGMENT).expect("a lone % is a valid path part"), | |
| 884 | + segment => PathPart::from(segment), | |
| 885 | + }); | |
| 886 | + Path::from_iter(prefix.chain(key)) | |
| 887 | + } | |
| 888 | + | |
| 889 | + /// The key a caller wrote, recovered from a listed location. | |
| 890 | + /// | |
| 891 | + /// A listing answers with the encoded form [`Self::blob_path`] wrote, so | |
| 892 | + /// handing it back unchanged gives an R2 caller `p%C5%99ehled.html` for | |
| 893 | + /// `přehled.html`, and a `get` of it names no object | |
| 894 | + /// (denoland/celld#232). The encoding escapes `%` inside a segment, so | |
| 895 | + /// a lone `%` segment can only be an empty one. | |
| 896 | + /// | |
| 897 | + /// A location that celld did not write can decode to bytes that are not | |
| 898 | + /// UTF-8, such as `a%FF`, and that is an error. A lossy decode lists it | |
| 899 | + /// as `a\u{FFFD}`, which names no object, and the cursor re-encodes that | |
| 900 | + /// key as `a%EF%BF%BD`, which sorts before `a%FF`. A one-key page then | |
| 901 | + /// returns the same location again, and the listing never ends. | |
| 902 | + fn listed_key(&self, location: &Path) -> anyhow::Result<String> { | |
| 903 | + let segments = self | |
| 904 | + .unkey(location.as_ref()) | |
| 905 | + .split('/') | |
| 906 | + .map(|segment| match segment { | |
| 907 | + EMPTY_SEGMENT => Ok(std::borrow::Cow::Borrowed("")), | |
| 908 | + segment => percent_encoding::percent_decode_str(segment).decode_utf8(), | |
| 909 | + }) | |
| 910 | + .collect::<Result<Vec<_>, _>>() | |
| 911 | + .with_context(|| { | |
| 912 | + format!( | |
| 913 | + "list {}://{}/{location}: the key is not UTF-8", | |
| 914 | + self.scheme(), | |
| 915 | + self.name | |
| 916 | + ) | |
| 917 | + })?; | |
| 918 | + Ok(segments.join("/")) | |
| 919 | + } | |
| 920 | + | |
| 859 | 921 | /// Body and CAS token, or `None` when the key does not exist. |
| 860 | 922 | pub async fn get(&self, key: &str) -> anyhow::Result<Option<(Bytes, String)>> { |
| 861 | 923 | let key = self.key(key); |
| @@ -1033,13 +1095,26 @@ | ||
| 1033 | 1095 | /// Returns the keys that are now gone; an absent key counts as gone, |
| 1034 | 1096 | /// and a key that fails stays listed for the next pass. |
| 1035 | 1097 | pub async fn delete_many(&self, keys: &[String]) -> Vec<String> { |
| 1036 | - let locations = futures_util::stream::iter( | |
| 1098 | + self.delete_paths( | |
| 1037 | 1099 | keys.iter() |
| 1038 | - .map(|key| Ok(Path::from(self.key(key).as_str()))) | |
| 1039 | - .collect::<Vec<_>>(), | |
| 1100 | + .map(|key| Path::from(self.key(key).as_str())) | |
| 1101 | + .collect(), | |
| 1040 | 1102 | ) |
| 1041 | - .boxed(); | |
| 1042 | - let mut gone = Vec::with_capacity(keys.len()); | |
| 1103 | + .await | |
| 1104 | + } | |
| 1105 | + | |
| 1106 | + /// [`Self::delete_many`] for blob keys, which address their objects | |
| 1107 | + /// through [`Self::blob_path`]. Returns how many are now gone. | |
| 1108 | + pub async fn delete_blobs(&self, keys: &[String]) -> usize { | |
| 1109 | + self.delete_paths(keys.iter().map(|key| self.blob_path(key)).collect()) | |
| 1110 | + .await | |
| 1111 | + .len() | |
| 1112 | + } | |
| 1113 | + | |
| 1114 | + async fn delete_paths(&self, paths: Vec<Path>) -> Vec<String> { | |
| 1115 | + let count = paths.len(); | |
| 1116 | + let locations = futures_util::stream::iter(paths.into_iter().map(Ok)).boxed(); | |
| 1117 | + let mut gone = Vec::with_capacity(count); | |
| 1043 | 1118 | let mut results = self.store.delete_stream(locations); |
| 1044 | 1119 | while let Some(result) = results.next().await { |
| 1045 | 1120 | match result { |
| @@ -1220,16 +1295,13 @@ | ||
| 1220 | 1295 | /// does not exist. This is R2's `head`, and the read half of every |
| 1221 | 1296 | /// conditional write. |
| 1222 | 1297 | pub async fn head_blob(&self, key: &str) -> anyhow::Result<Option<BlobMeta>> { |
| 1298 | + let path = self.blob_path(key); | |
| 1223 | 1299 | let key = self.key(key); |
| 1224 | 1300 | let options = GetOptions { |
| 1225 | 1301 | head: true, |
| 1226 | 1302 | ..GetOptions::default() |
| 1227 | 1303 | }; |
| 1228 | - match self | |
| 1229 | - .store | |
| 1230 | - .get_opts(&Path::from(key.as_str()), options) | |
| 1231 | - .await | |
| 1232 | - { | |
| 1304 | + match self.store.get_opts(&path, options).await { | |
| 1233 | 1305 | Ok(result) => Ok(Some(self.blob_meta(&result.meta, &result.attributes))), |
| 1234 | 1306 | Err(Error::NotFound { .. }) => Ok(None), |
| 1235 | 1307 | Err(error) => { |
| @@ -1259,11 +1331,7 @@ | ||
| 1259 | 1331 | if_none_match: conditions.if_none_match.clone(), |
| 1260 | 1332 | ..GetOptions::default() |
| 1261 | 1333 | }; |
| 1262 | - let result = match self | |
| 1263 | - .store | |
| 1264 | - .get_opts(&Path::from(scoped.as_str()), options) | |
| 1265 | - .await | |
| 1266 | - { | |
| 1334 | + let result = match self.store.get_opts(&self.blob_path(key), options).await { | |
| 1267 | 1335 | Ok(result) => result, |
| 1268 | 1336 | // Only an absent key is a miss. A range that overshoots the end |
| 1269 | 1337 | // of the object is served short, as R2 serves it; a range that |
| @@ -1369,10 +1437,7 @@ | ||
| 1369 | 1437 | attributes: attributes.write(self.backend), |
| 1370 | 1438 | ..PutOptions::default() |
| 1371 | 1439 | }; |
| 1372 | - match store | |
| 1373 | - .put_opts(&Path::from(scoped.as_str()), body, options) | |
| 1374 | - .await | |
| 1375 | - { | |
| 1440 | + match store.put_opts(&self.blob_path(key), body, options).await { | |
| 1376 | 1441 | Ok(result) => Ok(Some(BlobMeta { |
| 1377 | 1442 | size, |
| 1378 | 1443 | cas: self |
| @@ -1416,11 +1481,11 @@ | ||
| 1416 | 1481 | delimiter: Option<&str>, |
| 1417 | 1482 | ) -> anyhow::Result<BlobPage> { |
| 1418 | 1483 | let directory = prefix.rsplit_once('/').map_or("", |(head, _)| head); |
| 1419 | - let path = Path::from(self.key(directory).as_str()); | |
| 1484 | + let path = self.blob_path(directory); | |
| 1420 | 1485 | let mut stream = match after { |
| 1421 | 1486 | Some(after) => self |
| 1422 | 1487 | .store |
| 1423 | - .list_with_offset(Some(&path), &Path::from(self.key(after).as_str())), | |
| 1488 | + .list_with_offset(Some(&path), &self.blob_path(after)), | |
| 1424 | 1489 | None => self.store.list(Some(&path)), |
| 1425 | 1490 | }; |
| 1426 | 1491 | let delimiter = delimiter.filter(|delimiter| !delimiter.is_empty()); |
| @@ -1440,7 +1505,8 @@ | ||
| 1440 | 1505 | while let Some(meta) = stream.next().await { |
| 1441 | 1506 | let meta = |
| 1442 | 1507 | meta.with_context(|| format!("list {}://{}/{path}", self.scheme(), self.name))?; |
| 1443 | - let key = self.unkey(meta.location.as_ref()); | |
| 1508 | + let key = self.listed_key(&meta.location)?; | |
| 1509 | + let key = key.as_str(); | |
| 1444 | 1510 | let Some(remainder) = key.strip_prefix(prefix) else { |
| 1445 | 1511 | continue; |
| 1446 | 1512 | }; |
| @@ -1490,13 +1556,14 @@ | ||
| 1490 | 1556 | key: &str, |
| 1491 | 1557 | attributes: &BlobAttributes, |
| 1492 | 1558 | ) -> anyhow::Result<Box<dyn MultipartUpload>> { |
| 1559 | + let path = self.blob_path(key); | |
| 1493 | 1560 | let key = self.key(key); |
| 1494 | 1561 | let options = PutMultipartOptions { |
| 1495 | 1562 | attributes: attributes.write(self.backend), |
| 1496 | 1563 | ..PutMultipartOptions::default() |
| 1497 | 1564 | }; |
| 1498 | 1565 | self.store |
| 1499 | - .put_multipart_opts(&Path::from(key.as_str()), options) | |
| 1566 | + .put_multipart_opts(&path, options) | |
| 1500 | 1567 | .await |
| 1501 | 1568 | .with_context(|| format!("begin multipart {}://{}/{key}", self.scheme(), self.name)) |
| 1502 | 1569 | } |
addedcrates/celld/cell_host.rs+208−0View file
| @@ -1,0 +1,208 @@ | ||
| 1 | +// Copyright 2026 Deno Land Inc. Apache-2.0 license. | |
| 2 | + | |
| 3 | +//! The Actor's one boundary to whichever engine runs cells. | |
| 4 | + | |
| 5 | +use crate::engine_api::StopMode; | |
| 6 | +use crate::generation::GenerationId; | |
| 7 | +use crate::runtime::RuntimeManager; | |
| 8 | + | |
| 9 | +/// The Actor's cell-runtime boundary: the engine's runtime, or the scripted | |
| 10 | +/// host the deterministic worlds drive. | |
| 11 | +#[derive(Clone)] | |
| 12 | +pub(crate) enum CellHost { | |
| 13 | + Engine(RuntimeManager), | |
| 14 | + #[cfg(all(test, celld_internal_tests))] | |
| 15 | + Scripted(crate::conformance_sim_cell_host::SimCellHost), | |
| 16 | +} | |
| 17 | + | |
| 18 | +impl From<RuntimeManager> for CellHost { | |
| 19 | + fn from(runtime: RuntimeManager) -> Self { | |
| 20 | + Self::Engine(runtime) | |
| 21 | + } | |
| 22 | +} | |
| 23 | + | |
| 24 | +impl CellHost { | |
| 25 | + pub(crate) fn local_reload_cells(&self) -> anyhow::Result<Vec<celld_logic::LocalCell>> { | |
| 26 | + match self { | |
| 27 | + Self::Engine(runtime) => runtime.local_reload_cells(), | |
| 28 | + #[cfg(all(test, celld_internal_tests))] | |
| 29 | + Self::Scripted(runtime) => runtime.local_reload_cells(), | |
| 30 | + } | |
| 31 | + } | |
| 32 | + | |
| 33 | + pub(crate) async fn restore_cell( | |
| 34 | + &self, | |
| 35 | + cell: &str, | |
| 36 | + spec: &celld_logic::RestoreSpec, | |
| 37 | + ) -> anyhow::Result<celld_logic::RestoreOutcome> { | |
| 38 | + match self { | |
| 39 | + Self::Engine(runtime) => runtime.restore_cell(cell, spec).await, | |
| 40 | + #[cfg(all(test, celld_internal_tests))] | |
| 41 | + Self::Scripted(runtime) => runtime.restore_cell(cell, spec).await, | |
| 42 | + } | |
| 43 | + } | |
| 44 | + | |
| 45 | + /// Start a cell's runtime, reporting the isolate that took its realm and | |
| 46 | + /// the application generation that isolate belongs to. | |
| 47 | + pub(crate) async fn start_cell( | |
| 48 | + &self, | |
| 49 | + cell: String, | |
| 50 | + epoch: u64, | |
| 51 | + fresh: bool, | |
| 52 | + ) -> anyhow::Result<(celld_logic::isolate::HeapId, GenerationId)> { | |
| 53 | + match self { | |
| 54 | + Self::Engine(runtime) => runtime.start_cell(cell, epoch, fresh).await, | |
| 55 | + // The scripted host maps its deterministic isolate pool to heap | |
| 56 | + // identities on the generation a node boots with; no scripted | |
| 57 | + // world adopts another. | |
| 58 | + #[cfg(all(test, celld_internal_tests))] | |
| 59 | + Self::Scripted(runtime) => runtime | |
| 60 | + .start_cell(cell, epoch, fresh) | |
| 61 | + .await | |
| 62 | + .map(|isolate| (isolate, crate::generation::FIRST_GENERATION)), | |
| 63 | + } | |
| 64 | + } | |
| 65 | + | |
| 66 | + /// Take a cell out of its isolate for a generation swap: close its | |
| 67 | + /// application database and give the placement back, and touch nothing | |
| 68 | + /// else. Ownership, the epoch, the replica, and the wake entry all stay. | |
| 69 | + pub(crate) async fn swap_out_cell(&self, cell: &str, epoch: u64) -> anyhow::Result<()> { | |
| 70 | + match self { | |
| 71 | + Self::Engine(runtime) => runtime.swap_out_cell(cell, epoch).await, | |
| 72 | + #[cfg(all(test, celld_internal_tests))] | |
| 73 | + Self::Scripted(runtime) => runtime.swap_out_cell(cell, epoch).await, | |
| 74 | + } | |
| 75 | + } | |
| 76 | + | |
| 77 | + pub(crate) fn publish_cell(&self, cell: &str, epoch: u64) -> anyhow::Result<()> { | |
| 78 | + match self { | |
| 79 | + Self::Engine(runtime) => runtime.publish_cell(cell, epoch), | |
| 80 | + #[cfg(all(test, celld_internal_tests))] | |
| 81 | + Self::Scripted(runtime) => runtime.publish_cell(cell, epoch), | |
| 82 | + } | |
| 83 | + } | |
| 84 | + | |
| 85 | + pub(crate) async fn ensure_durable( | |
| 86 | + &self, | |
| 87 | + cell: &str, | |
| 88 | + epoch: u64, | |
| 89 | + revocable: bool, | |
| 90 | + ) -> anyhow::Result<()> { | |
| 91 | + match self { | |
| 92 | + Self::Engine(runtime) => runtime.ensure_durable(cell, epoch, revocable).await, | |
| 93 | + // The scripted host owns a real replicator over a real object | |
| 94 | + // store, so it takes the same gate. Letting it skip the gate made | |
| 95 | + // the gate unreachable from the deterministic worlds, which is | |
| 96 | + // why no case noticed when the pre-close check was removed. | |
| 97 | + #[cfg(all(test, celld_internal_tests))] | |
| 98 | + Self::Scripted(runtime) => runtime.ensure_durable(cell, epoch, revocable).await, | |
| 99 | + } | |
| 100 | + } | |
| 101 | + | |
| 102 | + pub(crate) async fn await_durable( | |
| 103 | + &self, | |
| 104 | + cell: &str, | |
| 105 | + epoch: u64, | |
| 106 | + position: u64, | |
| 107 | + ) -> anyhow::Result<(u64, celld_logic::ProofSource)> { | |
| 108 | + match self { | |
| 109 | + Self::Engine(runtime) => runtime.await_durable(cell, epoch, position).await, | |
| 110 | + #[cfg(all(test, celld_internal_tests))] | |
| 111 | + Self::Scripted(runtime) => runtime.await_durable(cell, epoch, position).await, | |
| 112 | + } | |
| 113 | + } | |
| 114 | + | |
| 115 | + pub(crate) async fn stop_cell( | |
| 116 | + &self, | |
| 117 | + cell: &str, | |
| 118 | + epoch: u64, | |
| 119 | + mode: StopMode, | |
| 120 | + ) -> anyhow::Result<()> { | |
| 121 | + match self { | |
| 122 | + Self::Engine(runtime) => runtime.stop_cell(cell, epoch, mode).await, | |
| 123 | + #[cfg(all(test, celld_internal_tests))] | |
| 124 | + Self::Scripted(runtime) => runtime.stop_cell(cell, epoch, mode).await, | |
| 125 | + } | |
| 126 | + } | |
| 127 | + | |
| 128 | + pub(crate) fn abort_activity(&self, request_id: crate::js::RequestId) { | |
| 129 | + match self { | |
| 130 | + Self::Engine(_) => crate::js::abort_request_for_shutdown(request_id), | |
| 131 | + #[cfg(all(test, celld_internal_tests))] | |
| 132 | + Self::Scripted(_) => {} | |
| 133 | + } | |
| 134 | + } | |
| 135 | + | |
| 136 | + /// Keep the snapshot and its consumer under the host's reporter lock. | |
| 137 | + /// An activity completion sent after a newer report can otherwise erase it. | |
| 138 | + pub(crate) fn with_alarm<T>( | |
| 139 | + &self, | |
| 140 | + cell: &str, | |
| 141 | + f: impl FnOnce(celld_logic::wake::AlarmSnapshot, bool) -> T, | |
| 142 | + ) -> T { | |
| 143 | + match self { | |
| 144 | + Self::Engine(runtime) => runtime | |
| 145 | + .with_alarm_snapshot(cell, |alarm| f(alarm, runtime.alarm_covered(cell, alarm))), | |
| 146 | + #[cfg(all(test, celld_internal_tests))] | |
| 147 | + Self::Scripted(runtime) => runtime.with_alarm(cell, f), | |
| 148 | + } | |
| 149 | + } | |
| 150 | + | |
| 151 | + /// Legacy scripted drivers supply their own observations. A host connected | |
| 152 | + /// to the activity path supplies them through the same boundary as an engine. | |
| 153 | + pub(crate) fn alarm_observation( | |
| 154 | + &self, | |
| 155 | + cell: &str, | |
| 156 | + ) -> Option<(celld_logic::wake::AlarmSnapshot, bool)> { | |
| 157 | + match self { | |
| 158 | + Self::Engine(_) => Some(self.with_alarm(cell, |alarm, covered| (alarm, covered))), | |
| 159 | + #[cfg(all(test, celld_internal_tests))] | |
| 160 | + Self::Scripted(runtime) => runtime | |
| 161 | + .observes_activity_alarms() | |
| 162 | + .then(|| self.with_alarm(cell, |alarm, covered| (alarm, covered))), | |
| 163 | + } | |
| 164 | + } | |
| 165 | + | |
| 166 | + /// Make an armed alarm discoverable before a graceful handoff continues. | |
| 167 | + /// The runtime cache and the wake flusher share the reporter ordering, so | |
| 168 | + /// re-reading after the awaited reconcile gives the core one observation | |
| 169 | + /// that cannot overtake the bucket operation it describes. | |
| 170 | + pub(crate) async fn refresh_handoff_alarm_coverage( | |
| 171 | + &self, | |
| 172 | + cell: &str, | |
| 173 | + alarm: celld_logic::wake::AlarmSnapshot, | |
| 174 | + ) -> Option<(celld_logic::wake::AlarmSnapshot, bool)> { | |
| 175 | + #[cfg(all(test, celld_internal_tests))] | |
| 176 | + if matches!(self, Self::Scripted(host) if !host.observes_activity_alarms()) { | |
| 177 | + return None; | |
| 178 | + } | |
| 179 | + if crate::js::publish_observed_wake_entry(cell, alarm) | |
| 180 | + .await | |
| 181 | + .is_err() | |
| 182 | + { | |
| 183 | + return None; | |
| 184 | + } | |
| 185 | + self.alarm_observation(cell) | |
| 186 | + } | |
| 187 | + | |
| 188 | + pub(crate) async fn fire_alarm( | |
| 189 | + &self, | |
| 190 | + op: celld_logic::OpId, | |
| 191 | + cell: String, | |
| 192 | + scheduled_ms: i64, | |
| 193 | + ) -> anyhow::Result<(celld_logic::wake::AlarmSnapshot, bool, Option<u64>)> { | |
| 194 | + match self { | |
| 195 | + Self::Engine(runtime) => runtime.fire_alarm(op, cell, scheduled_ms).await, | |
| 196 | + #[cfg(all(test, celld_internal_tests))] | |
| 197 | + Self::Scripted(runtime) => runtime.fire_alarm(op, cell, scheduled_ms).await, | |
| 198 | + } | |
| 199 | + } | |
| 200 | + | |
| 201 | + pub(crate) fn abort_alarm(&self, cell: &str, op: celld_logic::OpId) { | |
| 202 | + match self { | |
| 203 | + Self::Engine(runtime) => runtime.abort_alarm(cell, op), | |
| 204 | + #[cfg(all(test, celld_internal_tests))] | |
| 205 | + Self::Scripted(_) => {} | |
| 206 | + } | |
| 207 | + } | |
| 208 | +} |
addedcrates/celld/cell_runtime.rs+310−0View file
| @@ -1,0 +1,310 @@ | ||
| 1 | +// Copyright 2026 Deno Land Inc. Apache-2.0 license. | |
| 2 | + | |
| 3 | +//! What a node's cell runtime holds whichever engine runs the cells: the | |
| 4 | +//! generations it resolves calls against, the data directory, replication, | |
| 5 | +//! wake discovery and facet streams. Each engine's `RuntimeManager` wraps one | |
| 6 | +//! and adds what only its engine knows: cells, isolates, requests. | |
| 7 | + | |
| 8 | +use std::path::Path; | |
| 9 | +use std::path::PathBuf; | |
| 10 | +use std::sync::Arc; | |
| 11 | + | |
| 12 | +use anyhow::anyhow; | |
| 13 | +use anyhow::Context; | |
| 14 | + | |
| 15 | +use crate::asyncrt; | |
| 16 | +use crate::engine_api::AlarmObserver; | |
| 17 | +use crate::generation::Generation; | |
| 18 | +use crate::generation::GenerationId; | |
| 19 | +use crate::ltx_replication::Replication; | |
| 20 | +use crate::wake::WakeFlusher; | |
| 21 | + | |
| 22 | +/// The generations a node can resolve a call against: the one it serves and | |
| 23 | +/// the superseded ones whose isolates are still draining. | |
| 24 | +/// | |
| 25 | +/// One value under one lock, because installing the new generation and | |
| 26 | +/// keeping the previous one resolvable are the same instant. Held apart, | |
| 27 | +/// the window between them resolved an in-flight call from the previous | |
| 28 | +/// generation against the new deployment graph. | |
| 29 | +pub(crate) struct Generations { | |
| 30 | + pub(crate) current: Arc<Generation>, | |
| 31 | + pub(crate) draining: Vec<Arc<Generation>>, | |
| 32 | +} | |
| 33 | + | |
| 34 | +#[derive(Clone)] | |
| 35 | +pub struct CellRuntime { | |
| 36 | + /// The generations a call can resolve against. A reader takes one | |
| 37 | + /// snapshot and never holds the lock across an await. | |
| 38 | + pub(crate) generations: Arc<std::sync::RwLock<Generations>>, | |
| 39 | + pub(crate) data_dir: Arc<PathBuf>, | |
| 40 | + pub(crate) replication: Option<Replication>, | |
| 41 | + pub(crate) wake: Option<Arc<WakeFlusher>>, | |
| 42 | + pub(crate) alarm_observer: AlarmObserver, | |
| 43 | + /// The facet streams of each resident root object. | |
| 44 | + pub(crate) facets: crate::facet_streams::FacetStreams, | |
| 45 | + pub(crate) node: Arc<str>, | |
| 46 | + pub(crate) region: Arc<str>, | |
| 47 | +} | |
| 48 | + | |
| 49 | +impl CellRuntime { | |
| 50 | + pub(crate) fn new( | |
| 51 | + generation: Arc<Generation>, | |
| 52 | + data_dir: PathBuf, | |
| 53 | + replication: Option<Replication>, | |
| 54 | + wake: Option<Arc<WakeFlusher>>, | |
| 55 | + alarm_observer: AlarmObserver, | |
| 56 | + node: String, | |
| 57 | + region: String, | |
| 58 | + ) -> anyhow::Result<Self> { | |
| 59 | + require_cell_scope_capacity(&data_dir)?; | |
| 60 | + Ok(Self { | |
| 61 | + generations: Arc::new(std::sync::RwLock::new(Generations { | |
| 62 | + current: generation, | |
| 63 | + draining: Vec::new(), | |
| 64 | + })), | |
| 65 | + data_dir: Arc::new(data_dir), | |
| 66 | + replication, | |
| 67 | + wake, | |
| 68 | + alarm_observer, | |
| 69 | + facets: Default::default(), | |
| 70 | + node: Arc::from(node), | |
| 71 | + region: Arc::from(region), | |
| 72 | + }) | |
| 73 | + } | |
| 74 | + | |
| 75 | + /// The generation this node serves now. | |
| 76 | + /// | |
| 77 | + /// A caller that makes more than one decision from it takes the snapshot | |
| 78 | + /// once and uses it throughout: the current generation can change between | |
| 79 | + /// two reads, and a request must see one deployment graph, not two. | |
| 80 | + pub fn generation(&self) -> Arc<Generation> { | |
| 81 | + self.generations | |
| 82 | + .read() | |
| 83 | + .expect("generation lock poisoned") | |
| 84 | + .current | |
| 85 | + .clone() | |
| 86 | + } | |
| 87 | + | |
| 88 | + /// The generation an isolate was built for: the current one when the id | |
| 89 | + /// matches, otherwise a superseded generation still draining. Zero — the | |
| 90 | + /// tag of an isolate built outside any generation — and an id whose | |
| 91 | + /// generation has finished draining both resolve to the current one. | |
| 92 | + pub fn generation_by_id(&self, id: GenerationId) -> Arc<Generation> { | |
| 93 | + // One lock over both halves: read separately, a caller from the | |
| 94 | + // previous generation could observe the new one as current before | |
| 95 | + // the previous one was resolvable, find neither, and fall through to | |
| 96 | + // the new graph -- the cross-generation call this exists to prevent. | |
| 97 | + let generations = self.generations.read().expect("generation lock poisoned"); | |
| 98 | + if id == 0 || generations.current.id == id { | |
| 99 | + return generations.current.clone(); | |
| 100 | + } | |
| 101 | + generations | |
| 102 | + .draining | |
| 103 | + .iter() | |
| 104 | + .find(|generation| generation.id == id) | |
| 105 | + .cloned() | |
| 106 | + .unwrap_or_else(|| generations.current.clone()) | |
| 107 | + } | |
| 108 | + | |
| 109 | + /// The id the next generation takes: one past the newest this node has | |
| 110 | + /// built, draining generations included, so an id is never reused while | |
| 111 | + /// an isolate still carries it. | |
| 112 | + pub fn next_generation_id(&self) -> GenerationId { | |
| 113 | + let generations = self.generations.read().expect("generation lock poisoned"); | |
| 114 | + let draining = generations | |
| 115 | + .draining | |
| 116 | + .iter() | |
| 117 | + .map(|generation| generation.id) | |
| 118 | + .max() | |
| 119 | + .unwrap_or(0); | |
| 120 | + generations.current.id.max(draining) + 1 | |
| 121 | + } | |
| 122 | + | |
| 123 | + /// The generations still draining, for `/state`. Each one holds its | |
| 124 | + /// isolates until the last cell in them moves, so the caller reads the | |
| 125 | + /// census from the generation and not only its version. | |
| 126 | + pub fn draining_generations(&self) -> Vec<Arc<Generation>> { | |
| 127 | + self.generations | |
| 128 | + .read() | |
| 129 | + .expect("generation lock poisoned") | |
| 130 | + .draining | |
| 131 | + .clone() | |
| 132 | + } | |
| 133 | + | |
| 134 | + /// Resolve a client-supplied cell id to a scope. | |
| 135 | + /// | |
| 136 | + /// The id arrives from the network, and the scope it becomes is used as a | |
| 137 | + /// path component and as an object-store key, so the charset gate runs | |
| 138 | + /// first. Without it a scope carries its own path segments and `db_path` | |
| 139 | + /// walks out of the data directory through them. | |
| 140 | + /// | |
| 141 | + /// The fleet-wide storage gate runs a second time on the composed scope. A | |
| 142 | + /// bare id takes a class prefix, so the scope that reaches storage is the | |
| 143 | + /// value that must fit. | |
| 144 | + pub fn cell_scope(&self, id: &str) -> anyhow::Result<String> { | |
| 145 | + if !celld_logic::cell::valid_cell_scope(id) { | |
| 146 | + return Err(anyhow!("cell id is not a well-formed scope")); | |
| 147 | + } | |
| 148 | + if id.contains(':') { | |
| 149 | + return Ok(id.to_string()); | |
| 150 | + } | |
| 151 | + let generation = self.generation(); | |
| 152 | + let class = generation.default_do_class().ok_or_else(|| { | |
| 153 | + anyhow!("a bare cell id requires exactly one configured Durable Object class") | |
| 154 | + })?; | |
| 155 | + let scope = format!("{class}:{id}"); | |
| 156 | + if !celld_logic::cell::valid_cell_scope(&scope) { | |
| 157 | + return Err(anyhow!("cell id is not a well-formed scope")); | |
| 158 | + } | |
| 159 | + Ok(scope) | |
| 160 | + } | |
| 161 | + | |
| 162 | + pub fn replication(&self) -> Option<Replication> { | |
| 163 | + self.replication.clone() | |
| 164 | + } | |
| 165 | + | |
| 166 | + /// Read the filesystem inventory after the core has replaced the exact | |
| 167 | + /// clean predecessor lease generation. | |
| 168 | + pub fn local_reload_cells(&self) -> anyhow::Result<Vec<celld_logic::LocalCell>> { | |
| 169 | + let replication = self | |
| 170 | + .replication | |
| 171 | + .as_ref() | |
| 172 | + .context("local reload requires replication")?; | |
| 173 | + Ok(replication.local_cells()) | |
| 174 | + } | |
| 175 | + | |
| 176 | + pub fn replication_status(&self) -> std::io::Result<Option<std::process::ExitStatus>> { | |
| 177 | + match &self.replication { | |
| 178 | + Some(replication) => replication.process_status(), | |
| 179 | + None => Ok(None), | |
| 180 | + } | |
| 181 | + } | |
| 182 | + | |
| 183 | + pub async fn ensure_durable( | |
| 184 | + &self, | |
| 185 | + cell: &str, | |
| 186 | + epoch: u64, | |
| 187 | + revocable: bool, | |
| 188 | + ) -> anyhow::Result<()> { | |
| 189 | + let Some(replication) = &self.replication else { | |
| 190 | + return Ok(()); | |
| 191 | + }; | |
| 192 | + for facet in self.facets.resident(cell, epoch) { | |
| 193 | + replication.ensure_durable(&facet, epoch, revocable).await?; | |
| 194 | + } | |
| 195 | + replication.ensure_durable(cell, epoch, revocable).await | |
| 196 | + } | |
| 197 | + | |
| 198 | + /// The output-gate durability wait (see `Replication::await_durable`). | |
| 199 | + /// Returns the proved durable position and its proof source; with no | |
| 200 | + /// replicator every position is trivially durable, and the fleet source | |
| 201 | + /// keeps the gate read-free exactly like the old immediate release. | |
| 202 | + pub async fn await_durable( | |
| 203 | + &self, | |
| 204 | + cell: &str, | |
| 205 | + epoch: u64, | |
| 206 | + position: u64, | |
| 207 | + ) -> anyhow::Result<(u64, celld_logic::ProofSource)> { | |
| 208 | + match &self.replication { | |
| 209 | + Some(replication) => replication.await_durable(cell, epoch, position).await, | |
| 210 | + None => Ok((position, celld_logic::ProofSource::Fleet)), | |
| 211 | + } | |
| 212 | + } | |
| 213 | + | |
| 214 | + /// Activate a facet's stream and answer its database file. | |
| 215 | + pub async fn open_facet( | |
| 216 | + &self, | |
| 217 | + root: &str, | |
| 218 | + epoch: u64, | |
| 219 | + names: &[String], | |
| 220 | + ) -> anyhow::Result<(PathBuf, bool)> { | |
| 221 | + self.facets | |
| 222 | + .open( | |
| 223 | + self.replication.as_ref(), | |
| 224 | + |cell, epoch| self.db_path(cell, epoch), | |
| 225 | + root, | |
| 226 | + epoch, | |
| 227 | + names, | |
| 228 | + ) | |
| 229 | + .await | |
| 230 | + } | |
| 231 | + | |
| 232 | + /// Delete a facet's stream and every stream below it. | |
| 233 | + pub async fn delete_facet( | |
| 234 | + &self, | |
| 235 | + root: &str, | |
| 236 | + epoch: u64, | |
| 237 | + names: &[String], | |
| 238 | + ) -> anyhow::Result<()> { | |
| 239 | + self.facets | |
| 240 | + .delete( | |
| 241 | + self.replication.as_ref(), | |
| 242 | + |cell| self.data_dir.join(cell), | |
| 243 | + root, | |
| 244 | + epoch, | |
| 245 | + names, | |
| 246 | + ) | |
| 247 | + .await | |
| 248 | + } | |
| 249 | + | |
| 250 | + /// Prove every committed write of a facet's stream durable. | |
| 251 | + pub async fn prove_facet(&self, stream: &str, epoch: u64) -> anyhow::Result<()> { | |
| 252 | + self.await_durable(stream, epoch, 0).await.map(|_| ()) | |
| 253 | + } | |
| 254 | + | |
| 255 | + pub(crate) fn db_path(&self, cell: &str, epoch: u64) -> PathBuf { | |
| 256 | + // A runtime without replication has no remote epoch namespace, so it | |
| 257 | + // keeps its only SQLite family at the existing e1 path across logical | |
| 258 | + // ownership epochs. The stable path survives a restart, needs no | |
| 259 | + // multi-file SQLite family move, and remains compatible with older | |
| 260 | + // releases. | |
| 261 | + let epoch = if self.replication.is_some() { epoch } else { 1 }; | |
| 262 | + self.data_dir | |
| 263 | + .join(cell) | |
| 264 | + .join("ltx") | |
| 265 | + .join(format!("e{epoch}")) | |
| 266 | + .join("db.sqlite") | |
| 267 | + } | |
| 268 | + | |
| 269 | + pub fn alarm_covered(&self, cell: &str, alarm: celld_logic::wake::AlarmSnapshot) -> bool { | |
| 270 | + match (alarm.at_ms(), &self.wake) { | |
| 271 | + (None, _) => true, | |
| 272 | + (Some(_), Some(wake)) if self.replication.is_some() => wake.covered(cell, alarm), | |
| 273 | + (Some(_), None) => false, | |
| 274 | + (Some(_), Some(_)) => false, | |
| 275 | + } | |
| 276 | + } | |
| 277 | + | |
| 278 | + pub fn node(&self) -> &str { | |
| 279 | + &self.node | |
| 280 | + } | |
| 281 | + | |
| 282 | + pub fn region(&self) -> &str { | |
| 283 | + &self.region | |
| 284 | + } | |
| 285 | +} | |
| 286 | + | |
| 287 | +fn require_cell_scope_capacity(data_dir: &Path) -> anyhow::Result<()> { | |
| 288 | + asyncrt::fs() | |
| 289 | + .create_dir_all(data_dir) | |
| 290 | + .with_context(|| format!("create data directory {}", data_dir.display()))?; | |
| 291 | + let reported = asyncrt::filesystem_name_max(data_dir) | |
| 292 | + .with_context(|| format!("read NAME_MAX for {}", data_dir.display()))? | |
| 293 | + .with_context(|| { | |
| 294 | + format!( | |
| 295 | + "the filesystem does not report NAME_MAX for {}", | |
| 296 | + data_dir.display() | |
| 297 | + ) | |
| 298 | + })?; | |
| 299 | + let name_max = usize::try_from(reported).context("NAME_MAX does not fit usize")?; | |
| 300 | + require_cell_scope_name_max(name_max) | |
| 301 | +} | |
| 302 | + | |
| 303 | +pub(crate) fn require_cell_scope_name_max(name_max: usize) -> anyhow::Result<()> { | |
| 304 | + anyhow::ensure!( | |
| 305 | + name_max >= celld_logic::cell::MAX_CELL_SCOPE, | |
| 306 | + "the data filesystem supports {name_max}-byte names, but celld requires {}", | |
| 307 | + celld_logic::cell::MAX_CELL_SCOPE | |
| 308 | + ); | |
| 309 | + Ok(()) | |
| 310 | +} |
addedcrates/celld/clean_reload.rs+49−0View file
| @@ -1,0 +1,49 @@ | ||
| 1 | +// Copyright 2026 Deno Land Inc. Apache-2.0 license. | |
| 2 | + | |
| 3 | +//! The clean-reload certificate a node leaves for its successor. | |
| 4 | + | |
| 5 | +use crate::asyncrt; | |
| 6 | +use serde::Deserialize; | |
| 7 | +use serde::Serialize; | |
| 8 | +use std::path::Path; | |
| 9 | + | |
| 10 | +const CLEAN_RELOAD_MARKER: &str = ".clean-reload.json"; | |
| 11 | + | |
| 12 | +#[derive(Deserialize, Serialize)] | |
| 13 | +struct CleanReloadMarker<'a> { | |
| 14 | + node: &'a str, | |
| 15 | + generation: &'a str, | |
| 16 | +} | |
| 17 | + | |
| 18 | +#[derive(Deserialize)] | |
| 19 | +struct OwnedCleanReloadMarker { | |
| 20 | + node: String, | |
| 21 | + generation: String, | |
| 22 | +} | |
| 23 | + | |
| 24 | +/// Read the fixed-size certificate left by a clean local shutdown. The node | |
| 25 | +/// lease state machine still decides whether the named generation is live and | |
| 26 | +/// can be replaced; this local value grants no authority by itself. | |
| 27 | +pub fn take_clean_reload_generation(data_dir: &Path, node: &str) -> Option<String> { | |
| 28 | + let path = data_dir.join(CLEAN_RELOAD_MARKER); | |
| 29 | + let filesystem = asyncrt::fs(); | |
| 30 | + let bytes = filesystem.read(&path).ok()?; | |
| 31 | + let _ = filesystem.remove_file(&path); | |
| 32 | + let marker: OwnedCleanReloadMarker = serde_json::from_slice(&bytes).ok()?; | |
| 33 | + (marker.node == node).then_some(marker.generation) | |
| 34 | +} | |
| 35 | + | |
| 36 | +pub fn write_clean_reload_marker( | |
| 37 | + data_dir: &Path, | |
| 38 | + node: &str, | |
| 39 | + generation: &str, | |
| 40 | +) -> anyhow::Result<()> { | |
| 41 | + let filesystem = asyncrt::fs(); | |
| 42 | + filesystem.create_dir_all(data_dir)?; | |
| 43 | + let marker = data_dir.join(CLEAN_RELOAD_MARKER); | |
| 44 | + let temporary = data_dir.join(".clean-reload.tmp"); | |
| 45 | + let body = serde_json::to_vec(&CleanReloadMarker { node, generation })?; | |
| 46 | + filesystem.write(&temporary, &body)?; | |
| 47 | + filesystem.rename(&temporary, &marker)?; | |
| 48 | + Ok(()) | |
| 49 | +} |
modifiedcrates/celld/deploy.rs+1−1View file
| @@ -2545,7 +2545,7 @@ | ||
| 2545 | 2545 | let mut positive = false; |
| 2546 | 2546 | let mut seen = std::collections::HashSet::new(); |
| 2547 | 2547 | for route in routes { |
| 2548 | - if route.len() <= 1 | |
| 2548 | + if route.is_empty() | |
| 2549 | 2549 | || route.len() > 100 |
| 2550 | 2550 | || route.contains(['\\', '\0']) |
| 2551 | 2551 | || (!route.starts_with('/') && !route.starts_with("!/")) |
addedcrates/celld/engine_api.rs+877−0View file
| @@ -1,0 +1,877 @@ | ||
| 1 | +// Copyright 2026 Deno Land Inc. Apache-2.0 license. | |
| 2 | + | |
| 3 | +//! Engine-neutral types and helpers that the cell runtimes and the host | |
| 4 | +//! share. Nothing here touches V8; `crate::js`, `crate::runtime` and | |
| 5 | +//! `crate::pool` re-export every item at its old path. | |
| 6 | +use crate::ws_registry::WorkerWebSocket; | |
| 7 | +use anyhow::Result; | |
| 8 | +use celld_logic::isolate::Refusal; | |
| 9 | +use std::cell::RefCell; | |
| 10 | +use std::collections::HashMap; | |
| 11 | +use std::pin::Pin; | |
| 12 | +use std::sync::atomic::AtomicU64; | |
| 13 | +use std::sync::atomic::Ordering; | |
| 14 | +use std::sync::Arc; | |
| 15 | +use std::sync::OnceLock; | |
| 16 | + | |
| 17 | +/// Bare Node builtin specifiers that the bundler leaves for the runtime. | |
| 18 | +/// Root entries also match subpaths in esbuild and in module resolution. | |
| 19 | +pub(crate) const BARE_NODE_BUILTINS: &[&str] = &[ | |
| 20 | + "assert", | |
| 21 | + "async_hooks", | |
| 22 | + "buffer", | |
| 23 | + "child_process", | |
| 24 | + "cluster", | |
| 25 | + "constants", | |
| 26 | + "crypto", | |
| 27 | + "dgram", | |
| 28 | + "diagnostics_channel", | |
| 29 | + "dns", | |
| 30 | + "events", | |
| 31 | + "fs", | |
| 32 | + "fs/promises", | |
| 33 | + "http", | |
| 34 | + "http2", | |
| 35 | + "https", | |
| 36 | + "inspector", | |
| 37 | + "module", | |
| 38 | + "net", | |
| 39 | + "os", | |
| 40 | + "path", | |
| 41 | + "perf_hooks", | |
| 42 | + "process", | |
| 43 | + "punycode", | |
| 44 | + "querystring", | |
| 45 | + "readline", | |
| 46 | + "sqlite", | |
| 47 | + "stream", | |
| 48 | + "string_decoder", | |
| 49 | + "timers", | |
| 50 | + "tls", | |
| 51 | + "tty", | |
| 52 | + "url", | |
| 53 | + "util", | |
| 54 | + "util/types", | |
| 55 | + "v8", | |
| 56 | + "vm", | |
| 57 | + "worker_threads", | |
| 58 | + "zlib", | |
| 59 | +]; | |
| 60 | + | |
| 61 | +pub type RequestId = u128; | |
| 62 | + | |
| 63 | +/// Allocate an id for an ingress or service-binding request so it can be | |
| 64 | +/// aborted mid-flight. | |
| 65 | +pub fn next_request_id() -> RequestId { | |
| 66 | + next_do_request_id() | |
| 67 | +} | |
| 68 | + | |
| 69 | +static NEXT_DO_REQUEST_ID: AtomicU64 = AtomicU64::new(1); | |
| 70 | +static DO_REQUEST_PROCESS_PREFIX: OnceLock<u64> = OnceLock::new(); | |
| 71 | + | |
| 72 | +#[doc(hidden)] | |
| 73 | +pub fn next_do_request_id() -> RequestId { | |
| 74 | + let prefix = *DO_REQUEST_PROCESS_PREFIX.get_or_init(|| { | |
| 75 | + let mut bytes = [0; 8]; | |
| 76 | + getrandom::fill(&mut bytes).expect("OS random source unavailable"); | |
| 77 | + u64::from_ne_bytes(bytes) | |
| 78 | + }); | |
| 79 | + let sequence = NEXT_DO_REQUEST_ID.fetch_add(1, Ordering::Relaxed); | |
| 80 | + (u128::from(prefix) << 64) | u128::from(sequence) | |
| 81 | +} | |
| 82 | + | |
| 83 | +pub fn request_id_string(request_id: RequestId) -> String { | |
| 84 | + format!("{request_id:032x}") | |
| 85 | +} | |
| 86 | + | |
| 87 | +pub fn parse_request_id(value: &str) -> Option<RequestId> { | |
| 88 | + u128::from_str_radix(value, 16).ok() | |
| 89 | +} | |
| 90 | + | |
| 91 | +/// An RPC payload crossing the host boundary. JS stubs marshal by V8 | |
| 92 | +/// structured clone (`V8`), and legacy callers use the JSON envelope (`Json`). | |
| 93 | +/// `__dispatchRpc` answers in the flavor it was asked in. | |
| 94 | +pub enum RpcData { | |
| 95 | + Json(String), | |
| 96 | + V8(bytes::Bytes), | |
| 97 | +} | |
| 98 | + | |
| 99 | +pub type HttpChunkStream = | |
| 100 | + Pin<Box<dyn futures_util::Stream<Item = Result<Vec<u8>, String>> + Send>>; | |
| 101 | + | |
| 102 | +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] | |
| 103 | +pub struct WsTarget { | |
| 104 | + pub id: u64, | |
| 105 | + pub scope: String, | |
| 106 | + /// A parked tunneled 101 on the calling node (`peer_tunnel::splice`). | |
| 107 | + /// The id is meaningful only in the process that parked it, but it must | |
| 108 | + /// survive the isolate round trip, so it serializes. | |
| 109 | + #[serde(default, skip_serializing_if = "Option::is_none")] | |
| 110 | + pub tunnel: Option<u64>, | |
| 111 | +} | |
| 112 | + | |
| 113 | +pub enum HttpResponseWebSocket { | |
| 114 | + Cell(WsTarget), | |
| 115 | + Worker(WorkerWebSocket), | |
| 116 | +} | |
| 117 | + | |
| 118 | +pub struct HttpResponse { | |
| 119 | + pub status: u16, | |
| 120 | + pub body: Vec<u8>, | |
| 121 | + /// A response body forwarded without materializing it in memory. | |
| 122 | + pub stream: Option<HttpChunkStream>, | |
| 123 | + pub headers: Vec<(String, String)>, | |
| 124 | + /// The one WebSocket target that owns this response, if it is an upgrade. | |
| 125 | + pub websocket: Option<HttpResponseWebSocket>, | |
| 126 | + /// The cell's committed-write position after the handler ran, for a local | |
| 127 | + /// Durable Object request. The shell gates the response on durability when | |
| 128 | + /// this advanced past the cell's last seen position. `None` for responses | |
| 129 | + /// with no cell storage (Worker, asset, or proxied remote). | |
| 130 | + pub write_position: Option<u64>, | |
| 131 | + /// The position the answer observed above the cell's published baseline | |
| 132 | + /// when the handler did not write, so the shell can hold a read-only | |
| 133 | + /// response behind the proof of another handler's commit. `None` when the | |
| 134 | + /// cell holds no handler write, or the response has no cell storage. | |
| 135 | + pub observed_position: Option<u64>, | |
| 136 | +} | |
| 137 | + | |
| 138 | +/// The encoding that the queue producer selected for one message body. | |
| 139 | +#[derive(Clone, Copy, Debug, Eq, PartialEq)] | |
| 140 | +pub enum QueueContentType { | |
| 141 | + Text, | |
| 142 | + Bytes, | |
| 143 | + Json, | |
| 144 | + V8, | |
| 145 | +} | |
| 146 | + | |
| 147 | +impl QueueContentType { | |
| 148 | + pub(crate) fn as_str(self) -> &'static str { | |
| 149 | + match self { | |
| 150 | + Self::Text => "text", | |
| 151 | + Self::Bytes => "bytes", | |
| 152 | + Self::Json => "json", | |
| 153 | + Self::V8 => "v8", | |
| 154 | + } | |
| 155 | + } | |
| 156 | +} | |
| 157 | + | |
| 158 | +/// One message handed from a queue cell to a consumer isolate. | |
| 159 | +pub struct QueueMessage { | |
| 160 | + pub id: String, | |
| 161 | + pub timestamp_ms: i64, | |
| 162 | + pub body: Vec<u8>, | |
| 163 | + pub content_type: QueueContentType, | |
| 164 | + pub attempts: u16, | |
| 165 | +} | |
| 166 | + | |
| 167 | +/// The queue state observed when a cell leases a batch. | |
| 168 | +pub struct QueueMetrics { | |
| 169 | + pub backlog_count: f64, | |
| 170 | + pub backlog_bytes: f64, | |
| 171 | + pub oldest_message_timestamp_ms: Option<i64>, | |
| 172 | +} | |
| 173 | + | |
| 174 | +/// One leased batch handed to the stateless isolate pool. | |
| 175 | +pub struct QueueBatch { | |
| 176 | + pub queue: String, | |
| 177 | + pub messages: Vec<QueueMessage>, | |
| 178 | + pub metrics: QueueMetrics, | |
| 179 | +} | |
| 180 | + | |
| 181 | +/// The batch-wide retry decision made by a queue handler. | |
| 182 | +#[derive(Debug, Eq, PartialEq)] | |
| 183 | +pub struct QueueRetryBatch { | |
| 184 | + pub retry: bool, | |
| 185 | + pub delay_seconds: Option<i32>, | |
| 186 | +} | |
| 187 | + | |
| 188 | +/// An explicit retry decision made for one message. | |
| 189 | +#[derive(Debug, Eq, PartialEq)] | |
| 190 | +pub struct QueueRetryMessage { | |
| 191 | + pub msg_id: String, | |
| 192 | + pub delay_seconds: Option<i32>, | |
| 193 | +} | |
| 194 | + | |
| 195 | +/// How the queue handler itself completed. Infrastructure failures still use | |
| 196 | +/// the outer `Result`, so a handler exception can preserve earlier acks. | |
| 197 | +#[derive(Clone, Copy, Debug, Eq, PartialEq)] | |
| 198 | +pub enum QueueOutcome { | |
| 199 | + Ok, | |
| 200 | + Exception, | |
| 201 | +} | |
| 202 | + | |
| 203 | +/// The handler outcome and the settlement instructions it made before return. | |
| 204 | +#[derive(Debug, Eq, PartialEq)] | |
| 205 | +pub struct QueueDispatchResult { | |
| 206 | + pub outcome: QueueOutcome, | |
| 207 | + pub error: Option<String>, | |
| 208 | + pub ack_all: bool, | |
| 209 | + pub retry_batch: QueueRetryBatch, | |
| 210 | + pub explicit_acks: Vec<String>, | |
| 211 | + pub retry_messages: Vec<QueueRetryMessage>, | |
| 212 | +} | |
| 213 | + | |
| 214 | +/// A cell event that the runtime refuses before application code starts. | |
| 215 | +/// | |
| 216 | +/// The type survives the Rust RPC path. Its display text also survives the V8 | |
| 217 | +/// promise boundary, so the public ingress can restore the HTTP overload | |
| 218 | +/// contract after a Worker forwards the refusal. | |
| 219 | +#[doc(hidden)] | |
| 220 | +#[derive(Debug)] | |
| 221 | +pub struct CellOverloaded; | |
| 222 | + | |
| 223 | +/// The V8 promise boundary preserves only an error string. Keep the public | |
| 224 | +/// overload phrase so a Worker can classify a caught Queue producer refusal. | |
| 225 | +/// Also include an opaque marker so unrelated application text cannot restore | |
| 226 | +/// an HTTP overload response, and keep the producer and ingress checks on one | |
| 227 | +/// value. | |
| 228 | +#[doc(hidden)] | |
| 229 | +pub const CELL_OVERLOAD_ERROR_MARKER: &str = | |
| 230 | + "celld-internal-cell-overload-7ec38c64-12d7-4ddc-9e77-b63f9dc14130"; | |
| 231 | + | |
| 232 | +impl std::fmt::Display for CellOverloaded { | |
| 233 | + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { | |
| 234 | + write!( | |
| 235 | + formatter, | |
| 236 | + "cell overload: admission refused ({CELL_OVERLOAD_ERROR_MARKER})" | |
| 237 | + ) | |
| 238 | + } | |
| 239 | +} | |
| 240 | + | |
| 241 | +impl std::error::Error for CellOverloaded {} | |
| 242 | + | |
| 243 | +/// Per-worker compatibility switches, derived from the manifest's | |
| 244 | +/// compatibility date and flags (Workerd compatibility-date.capnp). `Default` | |
| 245 | +/// is every switch off; production derives real values in `main`. | |
| 246 | +#[derive(Clone, Copy, Default)] | |
| 247 | +pub struct Compat { | |
| 248 | + pub delete_all_deletes_alarm: bool, | |
| 249 | + /// `js_rpc`: RPC on a Durable Object class that does not extend | |
| 250 | + /// `DurableObject` (Workerd worker-rpc.c++ getTargetInfo()). | |
| 251 | + pub js_rpc: bool, | |
| 252 | + /// `fetcher_has_get_put_delete` (off = `fetcher_no_get_put_delete`, | |
| 253 | + /// default on for dates >= 2024-03-26): the deprecated `get()`/`put()`/ | |
| 254 | + /// `delete()` HTTP helpers on stubs (Workerd http.c++ Fetcher). | |
| 255 | + pub fetcher_get_put_delete: bool, | |
| 256 | + /// `sqlite_vec`: expose the pre-v1 sqlite-vec extension to SQLite-backed | |
| 257 | + /// Durable Objects. This switch is explicit and has no date default. | |
| 258 | + pub sqlite_vec: bool, | |
| 259 | + /// `websocket_standard_binary_type`: `binaryType` defaults to `"blob"` and | |
| 260 | + /// a binary message arrives as a `Blob`, per the WHATWG default. Without | |
| 261 | + /// it celld keeps the historical `"arraybuffer"`. | |
| 262 | + pub websocket_standard_binary_type: bool, | |
| 263 | + /// Queue bodies default to JSON on compatibility dates after 2024-03-18; | |
| 264 | + /// older deployments retain the V8 structured-clone default. | |
| 265 | + pub queue_json_messages: bool, | |
| 266 | +} | |
| 267 | + | |
| 268 | +/// A non-main module the worker's main module may import, tagged by how the | |
| 269 | +/// runtime materializes it. | |
| 270 | +#[derive(Clone)] | |
| 271 | +pub enum ModuleSource { | |
| 272 | + /// UTF-8 content served as `export default "<content>"` (wrangler's Text | |
| 273 | + /// rule), registered under the given specifier verbatim. | |
| 274 | + Text(String), | |
| 275 | + /// JS source compiled as a sibling ES module (Worker Loader multi-module | |
| 276 | + /// bundles), registered under both `name` and `./name`. | |
| 277 | + EsModule(String), | |
| 278 | + /// Wasm bytes served as a module whose default export is the compiled | |
| 279 | + /// `WebAssembly.Module` (Wrangler's `CompiledWasm` rule), registered | |
| 280 | + /// under both `name` and `./name`. | |
| 281 | + Wasm(bytes::Bytes), | |
| 282 | +} | |
| 283 | + | |
| 284 | +/// A Workflow binding keeps the three names distinct across deployment | |
| 285 | +/// loading, environment construction, and runtime class injection. | |
| 286 | +pub struct WorkflowBinding { | |
| 287 | + pub environment: String, | |
| 288 | + pub workflow: String, | |
| 289 | + pub class: String, | |
| 290 | +} | |
| 291 | + | |
| 292 | +/// One Queue producer binding in a Worker environment. | |
| 293 | +#[derive(Clone)] | |
| 294 | +pub struct QueueBinding { | |
| 295 | + pub environment: String, | |
| 296 | + pub queue: String, | |
| 297 | + pub delivery_delay: u32, | |
| 298 | +} | |
| 299 | + | |
| 300 | +pub struct WorkerConfigOptions { | |
| 301 | + pub src: String, | |
| 302 | + pub script_name: String, | |
| 303 | + pub do_classes: Vec<String>, | |
| 304 | + pub bindings: Vec<(String, String)>, | |
| 305 | + pub r2_bindings: Vec<(String, String)>, | |
| 306 | + pub d1_bindings: Vec<(String, String)>, | |
| 307 | + pub kv_bindings: Vec<(String, String)>, | |
| 308 | + pub queue_bindings: Vec<QueueBinding>, | |
| 309 | + pub queue_consumers: Vec<crate::protocol::QueueConsumerConfig>, | |
| 310 | + pub workflow_bindings: Vec<WorkflowBinding>, | |
| 311 | + pub vars: Vec<(String, String)>, | |
| 312 | + pub node: String, | |
| 313 | + pub modules: Vec<(String, ModuleSource)>, | |
| 314 | + pub compat: Compat, | |
| 315 | +} | |
| 316 | + | |
| 317 | +/// A handler that failed inside its turn, with the positions that turn | |
| 318 | +/// sampled from the cell. | |
| 319 | +/// | |
| 320 | +/// A commit the handler made before it failed is as real as one a successful | |
| 321 | +/// handler made: it stays in the local database, unproven, and a read-only | |
| 322 | +/// output that followed would trail no barrier and reveal it while a crash can | |
| 323 | +/// still lose it. The error answer therefore takes the same write ticket a | |
| 324 | +/// success takes. | |
| 325 | +/// | |
| 326 | +/// A handler that committed nothing still reveals what it read, because the | |
| 327 | +/// message it throws with can quote it — "insufficient funds: balance is 90" | |
| 328 | +/// is an ordinary shape — and that value can be another event's commit that no | |
| 329 | +/// proof covers yet. An error answer reveals cell state exactly as a 200 does, | |
| 330 | +/// so a read-only failure carries the observed position and the gate holds it | |
| 331 | +/// behind the newest barrier, as it holds a read-only success. | |
| 332 | +/// | |
| 333 | +/// The failure the handler reported is the source; this wrapper displays its | |
| 334 | +/// message and continues its chain, so a client and a log see the handler's | |
| 335 | +/// own words. | |
| 336 | +#[derive(Debug)] | |
| 337 | +pub struct FailedInTurn { | |
| 338 | + pub(crate) write_position: Option<u64>, | |
| 339 | + pub(crate) observed_position: Option<u64>, | |
| 340 | + source: anyhow::Error, | |
| 341 | +} | |
| 342 | + | |
| 343 | +impl std::fmt::Display for FailedInTurn { | |
| 344 | + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { | |
| 345 | + write!(f, "{}", self.source) | |
| 346 | + } | |
| 347 | +} | |
| 348 | + | |
| 349 | +impl std::error::Error for FailedInTurn { | |
| 350 | + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { | |
| 351 | + // The wrapped error's own message is this wrapper's display, so the | |
| 352 | + // chain continues below it rather than repeating it. The wrapped | |
| 353 | + // error's own type is therefore not in the chain: a `downcast_ref` | |
| 354 | + // for it, or a `chain()` walk that looks for it, sees this wrapper | |
| 355 | + // instead. Every error that reaches `fail_in_turn_error` today is a | |
| 356 | + // plain message, so nothing looks; a typed handler failure would have | |
| 357 | + // to be matched through `failed_write_position` and its text. | |
| 358 | + let source: &(dyn std::error::Error + 'static) = self.source.as_ref(); | |
| 359 | + source.source() | |
| 360 | + } | |
| 361 | +} | |
| 362 | + | |
| 363 | +/// Attach the positions a failing handler's turn sampled, when it has either. | |
| 364 | +/// The pair comes from one `gate_positions` call, so an error cannot report a | |
| 365 | +/// write and an observation that disagree. | |
| 366 | +pub(crate) fn fail_in_turn_error( | |
| 367 | + error: anyhow::Error, | |
| 368 | + positions: (Option<u64>, Option<u64>), | |
| 369 | +) -> anyhow::Error { | |
| 370 | + let (write_position, observed_position) = positions; | |
| 371 | + if write_position.is_none() && observed_position.is_none() { | |
| 372 | + return error; | |
| 373 | + } | |
| 374 | + anyhow::Error::new(FailedInTurn { | |
| 375 | + write_position, | |
| 376 | + observed_position, | |
| 377 | + source: error, | |
| 378 | + }) | |
| 379 | +} | |
| 380 | + | |
| 381 | +/// The position a failed handler committed before it failed, when it did. | |
| 382 | +pub fn failed_write_position(error: &anyhow::Error) -> Option<u64> { | |
| 383 | + error | |
| 384 | + .downcast_ref::<FailedInTurn>() | |
| 385 | + .and_then(|failed| failed.write_position) | |
| 386 | +} | |
| 387 | + | |
| 388 | +/// How an incoming request body reaches the isolate. | |
| 389 | +/// | |
| 390 | +/// A small body crosses as bytes. This costs one copy and no asynchronous | |
| 391 | +/// operations, so a common request pays nothing for a stream that it does | |
| 392 | +/// not need. A large body, or a body of unknown length, crosses as a | |
| 393 | +/// stream id. The peak cost of that body is one chunk, not its length. | |
| 394 | +pub enum RequestBody { | |
| 395 | + Bytes(bytes::Bytes), | |
| 396 | + Stream(u64), | |
| 397 | +} | |
| 398 | + | |
| 399 | +impl RequestBody { | |
| 400 | + /// The bytes already in hand, for the paths that hold a whole body. | |
| 401 | + pub fn bytes(&self) -> &[u8] { | |
| 402 | + match self { | |
| 403 | + Self::Bytes(bytes) => bytes, | |
| 404 | + Self::Stream(_) => &[], | |
| 405 | + } | |
| 406 | + } | |
| 407 | + | |
| 408 | + pub fn stream_id(&self) -> Option<u64> { | |
| 409 | + match self { | |
| 410 | + Self::Bytes(_) => None, | |
| 411 | + Self::Stream(id) => Some(*id), | |
| 412 | + } | |
| 413 | + } | |
| 414 | + | |
| 415 | + pub(crate) fn into_held_bytes(self) -> Option<Vec<u8>> { | |
| 416 | + match self { | |
| 417 | + Self::Bytes(bytes) => Some(bytes.into()), | |
| 418 | + Self::Stream(_) => None, | |
| 419 | + } | |
| 420 | + } | |
| 421 | +} | |
| 422 | + | |
| 423 | +impl From<Vec<u8>> for RequestBody { | |
| 424 | + fn from(bytes: Vec<u8>) -> Self { | |
| 425 | + Self::Bytes(bytes.into()) | |
| 426 | + } | |
| 427 | +} | |
| 428 | + | |
| 429 | +thread_local! { | |
| 430 | + static DO_ID_KEYS: RefCell<HashMap<String, [u8; 32]>> = RefCell::new(HashMap::new()); | |
| 431 | +} | |
| 432 | + | |
| 433 | +pub(crate) fn durable_object_id_key(namespace_key: &str) -> [u8; 32] { | |
| 434 | + DO_ID_KEYS.with(|keys| { | |
| 435 | + if let Some(key) = keys.borrow().get(namespace_key) { | |
| 436 | + return *key; | |
| 437 | + } | |
| 438 | + use sha2::Digest; | |
| 439 | + let key: [u8; 32] = sha2::Sha256::digest(namespace_key.as_bytes()).into(); | |
| 440 | + keys.borrow_mut().insert(namespace_key.to_string(), key); | |
| 441 | + key | |
| 442 | + }) | |
| 443 | +} | |
| 444 | + | |
| 445 | +pub(crate) fn durable_object_id_hmac(key: &[u8; 32], input: &[u8]) -> hmac::Hmac<sha2::Sha256> { | |
| 446 | + use hmac::Mac; | |
| 447 | + let mut mac = <hmac::Hmac<sha2::Sha256> as hmac::Mac>::new_from_slice(key) | |
| 448 | + .expect("SHA-256 accepts any HMAC key"); | |
| 449 | + mac.update(input); | |
| 450 | + mac | |
| 451 | +} | |
| 452 | + | |
| 453 | +/// Ids already derived on this thread, keyed by namespace and name. | |
| 454 | +/// | |
| 455 | +/// `getByName` costs two HMAC-SHA256 rounds, and a profile of `/c/hello` | |
| 456 | +/// found them among the largest terms the stateless path does not have — | |
| 457 | +/// the same name resolving to the same id, recomputed on every request. | |
| 458 | +/// | |
| 459 | +/// Per thread and unsynchronised, which is sound because the derivation is | |
| 460 | +/// a pure function of its inputs: a worker that has not seen a name pays | |
| 461 | +/// for it once, and no answer can differ between threads. Bounded because | |
| 462 | +/// names come from the application, and cleared wholesale at the cap rather | |
| 463 | +/// than evicted one at a time — a cache this cheap to refill does not earn | |
| 464 | +/// an LRU. | |
| 465 | +const DO_ID_CACHE_MAX: usize = 4096; | |
| 466 | + | |
| 467 | +pub(crate) fn durable_object_id_for_name(namespace_key: &str, name: &str) -> [u8; 32] { | |
| 468 | + use hmac::Mac; | |
| 469 | + | |
| 470 | + thread_local! { | |
| 471 | + static IDS: RefCell<HashMap<(String, String), [u8; 32]>> = | |
| 472 | + RefCell::new(HashMap::new()); | |
| 473 | + } | |
| 474 | + let cached = IDS.with(|ids| { | |
| 475 | + ids.borrow() | |
| 476 | + .get(&(namespace_key.to_string(), name.to_string())) | |
| 477 | + .copied() | |
| 478 | + }); | |
| 479 | + if let Some(id) = cached { | |
| 480 | + return id; | |
| 481 | + } | |
| 482 | + | |
| 483 | + let key = durable_object_id_key(namespace_key); | |
| 484 | + let mut id = [0_u8; 32]; | |
| 485 | + let digest = durable_object_id_hmac(&key, name.as_bytes()) | |
| 486 | + .finalize() | |
| 487 | + .into_bytes(); | |
| 488 | + id[..16].copy_from_slice(&digest[..16]); | |
| 489 | + let digest = durable_object_id_hmac(&key, &id[..16]) | |
| 490 | + .finalize() | |
| 491 | + .into_bytes(); | |
| 492 | + id[16..].copy_from_slice(&digest[..16]); | |
| 493 | + | |
| 494 | + IDS.with(|ids| { | |
| 495 | + let mut ids = ids.borrow_mut(); | |
| 496 | + if ids.len() >= DO_ID_CACHE_MAX { | |
| 497 | + ids.clear(); | |
| 498 | + } | |
| 499 | + ids.insert((namespace_key.to_string(), name.to_string()), id); | |
| 500 | + }); | |
| 501 | + id | |
| 502 | +} | |
| 503 | + | |
| 504 | +/// The key a Durable Object namespace derives its IDs from. D1 uses one | |
| 505 | +/// fleet-wide namespace because the database is a resource that several | |
| 506 | +/// Workers can bind, and a Worker rename must not rename that database. | |
| 507 | +pub(crate) const D1_NAMESPACE_KEY: &str = "cells:v1:d1:__D1Database"; | |
| 508 | + | |
| 509 | +/// The same, for a KV namespace, and for the same reason: several Workers can | |
| 510 | +/// bind one namespace, and they must reach one set of cells. | |
| 511 | +/// | |
| 512 | +/// Written out rather than derived from the class name, because these two | |
| 513 | +/// strings are addresses. A scheme that computed them would be free to change, | |
| 514 | +/// and changing one renames every cell it ever addressed. | |
| 515 | +pub(crate) const KV_NAMESPACE_KEY: &str = "cells:v1:kv:__KvNamespace"; | |
| 516 | + | |
| 517 | +/// The fleet-wide namespace for Queue broker cells. The queue name is the | |
| 518 | +/// durable resource identity, so a producer and a consumer in different | |
| 519 | +/// scripts must derive the same cell id. | |
| 520 | +pub(crate) const QUEUE_NAMESPACE_KEY: &str = "cells:v1:queue:__Queue"; | |
| 521 | + | |
| 522 | +/// A shared reserved class addresses one set of cells for the whole fleet; every | |
| 523 | +/// other class, reserved or not, is scoped to the script that exports it. | |
| 524 | +/// | |
| 525 | +/// The question is asked once, through `deploy::is_shared_reserved_class`, and | |
| 526 | +/// not as a chain of `==` against class names. A reserved class declared shared | |
| 527 | +/// there and script-scoped here would silently give each script its own copy of | |
| 528 | +/// a resource the configuration says they share -- which is what happened to KV | |
| 529 | +/// between its manifest landing and this line being written. | |
| 530 | +fn shared_namespace_key(class_name: &str) -> Option<&'static str> { | |
| 531 | + match class_name { | |
| 532 | + crate::deploy::D1_CLASS => Some(D1_NAMESPACE_KEY), | |
| 533 | + crate::deploy::KV_CLASS => Some(KV_NAMESPACE_KEY), | |
| 534 | + crate::deploy::QUEUE_CLASS => Some(QUEUE_NAMESPACE_KEY), | |
| 535 | + _ => { | |
| 536 | + debug_assert!( | |
| 537 | + !crate::deploy::is_shared_reserved_class(class_name), | |
| 538 | + "a shared reserved class needs a fleet-wide namespace key: {class_name}" | |
| 539 | + ); | |
| 540 | + None | |
| 541 | + } | |
| 542 | + } | |
| 543 | +} | |
| 544 | + | |
| 545 | +pub(crate) fn namespace_key(script_name: &str, class_name: &str) -> String { | |
| 546 | + match shared_namespace_key(class_name) { | |
| 547 | + Some(shared) => shared.to_string(), | |
| 548 | + None => format!("cells:v1:{}:{script_name}:{class_name}", script_name.len()), | |
| 549 | + } | |
| 550 | +} | |
| 551 | + | |
| 552 | +/// The cell scope a D1 database lives at, for a caller outside any isolate. | |
| 553 | +/// `celld d1` addresses a database over the operator route, which takes a | |
| 554 | +/// scope, so this derives what `getByName` derives in the harness, from the | |
| 555 | +/// same key and the same HMAC. | |
| 556 | +pub fn d1_cell_scope(database_identity: &str) -> String { | |
| 557 | + let id = durable_object_id_for_name(D1_NAMESPACE_KEY, database_identity); | |
| 558 | + format!("{}:{}", crate::deploy::D1_CLASS, durable_object_id_hex(&id)) | |
| 559 | +} | |
| 560 | + | |
| 561 | +/// The cell scope one shard of a KV namespace lives at, for a caller outside | |
| 562 | +/// any isolate. `celld kv` addresses a namespace over the operator route, and | |
| 563 | +/// this derives what `getByName` derives in the harness -- from the same key, | |
| 564 | +/// the same name, and the same HMAC. | |
| 565 | +/// | |
| 566 | +/// The name comes from `celld_logic::kv::cell_name`, which is also what the | |
| 567 | +/// binding is handed at `build_env`. Neither side formats it, because a | |
| 568 | +/// formatting disagreement here does not fail: it silently addresses a second, | |
| 569 | +/// empty namespace. | |
| 570 | +pub fn kv_cell_scope(namespace_id: &str, shard: u32) -> String { | |
| 571 | + let name = celld_logic::kv::cell_name(namespace_id, shard); | |
| 572 | + let id = durable_object_id_for_name(KV_NAMESPACE_KEY, &name); | |
| 573 | + format!("{}:{}", crate::deploy::KV_CLASS, durable_object_id_hex(&id)) | |
| 574 | +} | |
| 575 | + | |
| 576 | +/// The Queue broker scope for callers outside a Worker isolate. | |
| 577 | +pub fn queue_cell_scope(queue: &str) -> String { | |
| 578 | + let name = celld_logic::queue::cell_name(queue); | |
| 579 | + let id = durable_object_id_for_name(QUEUE_NAMESPACE_KEY, name); | |
| 580 | + format!( | |
| 581 | + "{}:{}", | |
| 582 | + crate::deploy::QUEUE_CLASS, | |
| 583 | + durable_object_id_hex(&id) | |
| 584 | + ) | |
| 585 | +} | |
| 586 | + | |
| 587 | +#[cfg(celld_internal_tests)] | |
| 588 | +#[doc(hidden)] | |
| 589 | +pub fn workflow_cell_scope_for_test( | |
| 590 | + script_name: &str, | |
| 591 | + workflow_name: &str, | |
| 592 | + instance_id: &str, | |
| 593 | +) -> String { | |
| 594 | + let class = crate::deploy::workflow_class(script_name); | |
| 595 | + let namespace = namespace_key(script_name, &class); | |
| 596 | + let name = format!("{workflow_name}/{instance_id}"); | |
| 597 | + let id = durable_object_id_for_name(&namespace, &name); | |
| 598 | + format!("{class}:{}", durable_object_id_hex(&id)) | |
| 599 | +} | |
| 600 | + | |
| 601 | +pub(crate) fn durable_object_id_hex(bytes: &[u8; 32]) -> String { | |
| 602 | + const HEX: &[u8; 16] = b"0123456789abcdef"; | |
| 603 | + let mut output = String::with_capacity(64); | |
| 604 | + for byte in bytes { | |
| 605 | + output.push(HEX[(byte >> 4) as usize] as char); | |
| 606 | + output.push(HEX[(byte & 0x0f) as usize] as char); | |
| 607 | + } | |
| 608 | + output | |
| 609 | +} | |
| 610 | + | |
| 611 | +pub(crate) fn decode_durable_object_id(value: &str) -> Option<[u8; 32]> { | |
| 612 | + if value.len() != 64 { | |
| 613 | + return None; | |
| 614 | + } | |
| 615 | + let mut output = [0_u8; 32]; | |
| 616 | + for (index, pair) in value.as_bytes().chunks_exact(2).enumerate() { | |
| 617 | + let nibble = |byte| match byte { | |
| 618 | + b'0'..=b'9' => Some(byte - b'0'), | |
| 619 | + b'a'..=b'f' => Some(byte - b'a' + 10), | |
| 620 | + b'A'..=b'F' => Some(byte - b'A' + 10), | |
| 621 | + _ => None, | |
| 622 | + }; | |
| 623 | + output[index] = (nibble(pair[0])? << 4) | nibble(pair[1])?; | |
| 624 | + } | |
| 625 | + Some(output) | |
| 626 | +} | |
| 627 | +pub type AlarmObserver = Arc<dyn Fn(String, celld_logic::wake::AlarmSnapshot) + Send + Sync>; | |
| 628 | + | |
| 629 | +#[derive(Clone)] | |
| 630 | +pub(crate) enum StopMode { | |
| 631 | + /// Prove the final position, then optionally retain a local base. | |
| 632 | + /// | |
| 633 | + /// `abandon` travels with `preserve_local` because an eviction that could | |
| 634 | + /// be abandoned and an eviction that keeps a local base are the same | |
| 635 | + /// eviction: the one a live node can change its mind about. A drain and a | |
| 636 | + /// fence carry neither. | |
| 637 | + Evict { | |
| 638 | + preserve_local: bool, | |
| 639 | + abandon: Option<Arc<crate::replication::EvictionAbandon>>, | |
| 640 | + }, | |
| 641 | + /// Prove the final position and retain it for the successor epoch. | |
| 642 | + Rebase, | |
| 643 | + /// Close without a remote write because the caller lacks authority. | |
| 644 | + CloseInPlace, | |
| 645 | + /// Remove an image whose durability proof failed. | |
| 646 | + Discard, | |
| 647 | +} | |
| 648 | +/// One pool's isolates by state, as `/state` reports them. | |
| 649 | +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize)] | |
| 650 | +pub struct PoolCensus { | |
| 651 | + /// Isolates that accept placement and work. | |
| 652 | + pub live: usize, | |
| 653 | + /// Live isolates that house no cell. The next maintenance pass retires | |
| 654 | + /// them, so a count that persists across passes means the pass is not | |
| 655 | + /// running. | |
| 656 | + pub live_empty: usize, | |
| 657 | + /// Retiring isolates whose heap is still installed, because a turn, a | |
| 658 | + /// request, or a cell holds it. | |
| 659 | + pub retiring: usize, | |
| 660 | + /// Slots whose heap has been freed. | |
| 661 | + pub freed: usize, | |
| 662 | + /// Cells housed across the pool. | |
| 663 | + pub cells: usize, | |
| 664 | + /// Request affiliations across the pool, running or suspended. | |
| 665 | + pub requests: usize, | |
| 666 | + /// Turns in flight across the pool. | |
| 667 | + pub turns: usize, | |
| 668 | + /// Physical memory V8 has committed to the heaps of the isolates a turn | |
| 669 | + /// did not hold at the sample. | |
| 670 | + pub heap_bytes: u64, | |
| 671 | + /// External memory those isolates track: array buffer stores and the | |
| 672 | + /// like, which live outside the V8 heap. | |
| 673 | + pub external_bytes: u64, | |
| 674 | +} | |
| 675 | + | |
| 676 | +/// Refused by policy, or the isolate could not be built. Distinct because the | |
| 677 | +/// first is a 503 the caller may retry elsewhere and the second is a fault. | |
| 678 | +#[derive(Debug)] | |
| 679 | +pub enum AdmitError { | |
| 680 | + Refused(Refusal), | |
| 681 | + Build(anyhow::Error), | |
| 682 | +} | |
| 683 | + | |
| 684 | +impl From<Refusal> for AdmitError { | |
| 685 | + fn from(refusal: Refusal) -> Self { | |
| 686 | + AdmitError::Refused(refusal) | |
| 687 | + } | |
| 688 | +} | |
| 689 | + | |
| 690 | +impl std::fmt::Display for AdmitError { | |
| 691 | + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { | |
| 692 | + match self { | |
| 693 | + AdmitError::Refused(Refusal::NodeFull) => { | |
| 694 | + write!(f, "node is at its stateless request limit") | |
| 695 | + } | |
| 696 | + AdmitError::Refused(Refusal::NodePressured) => write!(f, "node is shedding load"), | |
| 697 | + AdmitError::Build(error) => write!(f, "isolate could not be started: {error}"), | |
| 698 | + } | |
| 699 | + } | |
| 700 | +} | |
| 701 | + | |
| 702 | +impl std::error::Error for AdmitError {} | |
| 703 | + | |
| 704 | +/// Node-level inputs to the cell runtime: everything that outlives an | |
| 705 | +/// application generation. What a deployment implies goes through | |
| 706 | +/// `Generation::build` instead. | |
| 707 | +pub struct RuntimeOptions { | |
| 708 | + pub data_dir: std::path::PathBuf, | |
| 709 | + pub replication: Option<crate::ltx_replication::Replication>, | |
| 710 | + pub wake: Option<Arc<crate::wake::WakeFlusher>>, | |
| 711 | + pub alarm_observer: AlarmObserver, | |
| 712 | + pub node: String, | |
| 713 | + pub region: String, | |
| 714 | + /// The fleet bucket, where container images live. `None` for a local | |
| 715 | + /// script, which has no bucket and loads images from the engine alone. | |
| 716 | + pub bucket: Option<crate::bucket::Bucket>, | |
| 717 | +} | |
| 718 | + | |
| 719 | +/// A service-binding fetch crossing from a calling isolate into the router. | |
| 720 | +pub struct ServiceFetch { | |
| 721 | + /// The caller's application generation; the target is resolved in its | |
| 722 | + /// deployment graph. | |
| 723 | + pub generation: crate::generation::GenerationId, | |
| 724 | + pub script: String, | |
| 725 | + pub entrypoint: Option<crate::WorkerFetchEntrypoint>, | |
| 726 | + pub url: String, | |
| 727 | + pub method: String, | |
| 728 | + pub body: RequestBody, | |
| 729 | + pub headers: Vec<(String, String)>, | |
| 730 | + pub cancel: Option<tokio::sync::oneshot::Receiver<()>>, | |
| 731 | +} | |
| 732 | + | |
| 733 | +/// Owned HTTP request crossing from the async shell into a cell executor. | |
| 734 | +pub struct RuntimeFetch { | |
| 735 | + pub url: String, | |
| 736 | + pub method: String, | |
| 737 | + pub body: RequestBody, | |
| 738 | + pub headers: Vec<(String, String)>, | |
| 739 | + pub request_id: Option<RequestId>, | |
| 740 | + /// Where this call sits in its caller's order for this cell. | |
| 741 | + pub order: Option<crate::js::CallOrder>, | |
| 742 | + /// The dispatching Worker's trace context, so the cell's span joins | |
| 743 | + /// the caller's trace instead of rooting a disconnected one. | |
| 744 | + pub parent: Option<crate::telemetry::TraceContext>, | |
| 745 | +} | |
| 746 | + | |
| 747 | +/// What a Durable Object RPC method returned, plus the position its writes | |
| 748 | +/// reached, so the caller can hold the reply behind durability. | |
| 749 | +pub struct RpcOutcome { | |
| 750 | + pub data: RpcData, | |
| 751 | + pub write_position: Option<u64>, | |
| 752 | + /// As on `HttpResponse`: what a read-only reply observed above the cell's | |
| 753 | + /// published baseline. | |
| 754 | + pub observed_position: Option<u64>, | |
| 755 | +} | |
| 756 | + | |
| 757 | +/// An answer the shell gates: a success reports the position its writes | |
| 758 | +/// reached, and the position it observed when it wrote nothing, in its own | |
| 759 | +/// shape. | |
| 760 | +pub trait GatedAnswer { | |
| 761 | + fn write_position(&self) -> Option<u64>; | |
| 762 | + fn observed_position(&self) -> Option<u64>; | |
| 763 | +} | |
| 764 | + | |
| 765 | +impl GatedAnswer for HttpResponse { | |
| 766 | + fn write_position(&self) -> Option<u64> { | |
| 767 | + self.write_position | |
| 768 | + } | |
| 769 | + | |
| 770 | + fn observed_position(&self) -> Option<u64> { | |
| 771 | + self.observed_position | |
| 772 | + } | |
| 773 | +} | |
| 774 | + | |
| 775 | +impl GatedAnswer for RpcOutcome { | |
| 776 | + fn write_position(&self) -> Option<u64> { | |
| 777 | + self.write_position | |
| 778 | + } | |
| 779 | + | |
| 780 | + fn observed_position(&self) -> Option<u64> { | |
| 781 | + self.observed_position | |
| 782 | + } | |
| 783 | +} | |
| 784 | + | |
| 785 | +/// The ticket an answer takes through the output gate, or `None` when it | |
| 786 | +/// takes none. | |
| 787 | +/// | |
| 788 | +/// A success always takes one: a write ticket when the handler advanced the | |
| 789 | +/// position, and otherwise a read-only ticket that carries what the answer | |
| 790 | +/// observed and trails the newest barrier on the cell. A failure raised inside | |
| 791 | +/// the handler's turn takes the same two shapes, which [`FailedInTurn`] | |
| 792 | +/// reports, because an error message can carry the cell's state as a body can. | |
| 793 | +/// A failure raised outside a turn — a budget overrun, a handler waiting on | |
| 794 | +/// nothing — took no sample and reports the host's own words, so it reveals | |
| 795 | +/// nothing and takes no ticket. The shell reads both arms through this one | |
| 796 | +/// function so that no answer site can gate one and forget the other. | |
| 797 | +pub fn answer_ticket<T: GatedAnswer>(result: &Result<T>) -> Option<crate::actor::GateTicket> { | |
| 798 | + match result { | |
| 799 | + Ok(answer) => Some(crate::actor::GateTicket::response( | |
| 800 | + answer.write_position(), | |
| 801 | + answer.observed_position(), | |
| 802 | + )), | |
| 803 | + Err(error) => error.downcast_ref::<FailedInTurn>().map(|failed| { | |
| 804 | + crate::actor::GateTicket::response(failed.write_position, failed.observed_position) | |
| 805 | + }), | |
| 806 | + } | |
| 807 | +} | |
| 808 | + | |
| 809 | +/// Fail the next release of a generation swap, for the black-box matrix. | |
| 810 | +/// | |
| 811 | +/// A count rather than a latch, so a test can prove the retry reaches | |
| 812 | +/// success instead of only proving that it never proceeds. `debug_assertions` | |
| 813 | +/// is the gate `CELLD_TEST_CELL_STARTUP_FAILURE` beside it already uses: the | |
| 814 | +/// runtime matrix drives the debug binary, which no internal test cfg | |
| 815 | +/// reaches, and a release build compiles neither. | |
| 816 | +#[cfg(debug_assertions)] | |
| 817 | +pub(crate) fn injected_swap_release_failure() -> Option<anyhow::Error> { | |
| 818 | + use std::sync::atomic::AtomicI64; | |
| 819 | + use std::sync::atomic::Ordering; | |
| 820 | + | |
| 821 | + static REMAINING: std::sync::OnceLock<AtomicI64> = std::sync::OnceLock::new(); | |
| 822 | + let remaining = REMAINING.get_or_init(|| { | |
| 823 | + AtomicI64::new( | |
| 824 | + std::env::var("CELLD_TEST_SWAP_RELEASE_FAILURES") | |
| 825 | + .ok() | |
| 826 | + .and_then(|value| value.parse().ok()) | |
| 827 | + .unwrap_or(0), | |
| 828 | + ) | |
| 829 | + }); | |
| 830 | + (remaining.fetch_sub(1, Ordering::Relaxed) > 0) | |
| 831 | + .then(|| anyhow::anyhow!("injected generation swap release failure")) | |
| 832 | +} | |
| 833 | + | |
| 834 | +/// The replication stream of a facet: nested under its root's own | |
| 835 | +/// coordinates, `<root>/facets/<h>` locally and `cells/<root>/facets/<h>/` | |
| 836 | +/// in the bucket, one level per name of the facet's path, so no scan of | |
| 837 | +/// cells sees a facet and deleting a facet with everything below it is | |
| 838 | +/// deleting one prefix. `<h>` is the first 16 bytes of the name's SHA-256 | |
| 839 | +/// in hex: a name can be any string of up to 256 bytes, and the charset a | |
| 840 | +/// path segment allows is narrower. Workerd's own server names a facet | |
| 841 | +/// file by a small id from a per-object index; a hash needs no index to | |
| 842 | +/// replicate beside the root. | |
| 843 | +pub(crate) fn facet_cell(root: &str, names: &[String]) -> String { | |
| 844 | + use sha2::Digest; | |
| 845 | + let mut cell = root.to_string(); | |
| 846 | + for name in names { | |
| 847 | + let digest = sha2::Sha256::digest(name.as_bytes()); | |
| 848 | + cell.push_str("/facets/"); | |
| 849 | + for byte in &digest[..16] { | |
| 850 | + cell.push_str(&format!("{byte:02x}")); | |
| 851 | + } | |
| 852 | + } | |
| 853 | + cell | |
| 854 | +} | |
| 855 | + | |
| 856 | +/// How long a stateless request may wait for a free `max_requests` slot | |
| 857 | +/// before it is refused. Zero restores the old refuse-at-once behaviour. | |
| 858 | +/// The default is one second: long enough that a saturated node converts | |
| 859 | +/// its refusal storm into kernel-buffer queueing, short enough that a | |
| 860 | +/// caller learns the truth before it matters. | |
| 861 | +pub fn admission_wait() -> std::time::Duration { | |
| 862 | + // Not `env_usize`, which filters zero out — zero is meaningful here. | |
| 863 | + let ms = crate::env_vars::with_default("CELLD_ADMISSION_WAIT_MS", 1000u64) | |
| 864 | + .expect("validated CELLD_ADMISSION_WAIT_MS"); | |
| 865 | + std::time::Duration::from_millis(ms) | |
| 866 | +} | |
| 867 | + | |
| 868 | +/// The JavaScript handler budget, `CELLD_HANDLER_BUDGET_S`. | |
| 869 | +pub fn handler_budget() -> std::time::Duration { | |
| 870 | + static BUDGET: OnceLock<std::time::Duration> = OnceLock::new(); | |
| 871 | + *BUDGET.get_or_init(|| { | |
| 872 | + std::time::Duration::from_secs( | |
| 873 | + crate::env_vars::positive_or("CELLD_HANDLER_BUDGET_S", 300) | |
| 874 | + .expect("validated CELLD_HANDLER_BUDGET_S"), | |
| 875 | + ) | |
| 876 | + }) | |
| 877 | +} |
addedcrates/celld/facet_streams.rs+313−0View file
| @@ -1,0 +1,313 @@ | ||
| 1 | +// Copyright 2026 Deno Land Inc. Apache-2.0 license. | |
| 2 | + | |
| 3 | +//! The replication streams of Durable Object facets, shared by both engines. | |
| 4 | +//! | |
| 5 | +//! A facet is a database and a replication stream of its own, as a sibling | |
| 6 | +//! file is in workerd's own server. Its stream nests under the root's | |
| 7 | +//! coordinates (`engine_api::facet_cell`), is activated on first use with the | |
| 8 | +//! restore its root's activation used, and stops with the root. A facet has | |
| 9 | +//! no ownership record and no fence of its own; the root's cover it, since a | |
| 10 | +//! facet runs only inside its root. | |
| 11 | + | |
| 12 | +use anyhow::anyhow; | |
| 13 | +use anyhow::Context as _; | |
| 14 | +use std::collections::BTreeSet; | |
| 15 | +use std::collections::HashMap; | |
| 16 | +use std::path::PathBuf; | |
| 17 | +use std::sync::Arc; | |
| 18 | +use std::sync::Mutex; | |
| 19 | + | |
| 20 | +use crate::ltx_replication::Replication; | |
| 21 | + | |
| 22 | +/// The backoff of a facet stop that failed after its root stopped. | |
| 23 | +const FACET_STOP_RETRY_FIRST: std::time::Duration = std::time::Duration::from_millis(50); | |
| 24 | +const FACET_STOP_RETRY_MAX: std::time::Duration = std::time::Duration::from_secs(5); | |
| 25 | + | |
| 26 | +/// A resident root object's facets. | |
| 27 | +struct FacetRoot { | |
| 28 | + epoch: u64, | |
| 29 | + spec: Option<celld_logic::RestoreSpec>, | |
| 30 | + streams: BTreeSet<String>, | |
| 31 | + /// The root began to stop. Its facets neither open nor delete until the | |
| 32 | + /// stop fails before any facet stopped (`resume`): a facet stopped at | |
| 33 | + /// this epoch would otherwise restart its lineage inside an epoch its | |
| 34 | + /// eviction sealed, and an open that finished after the stop's snapshot | |
| 35 | + /// would outlive the root. | |
| 36 | + stopping: bool, | |
| 37 | + /// Serializes the root's first opens: two activations of one stream | |
| 38 | + /// would unlink the file the first one's connection writes. | |
| 39 | + opening: Arc<tokio::sync::Mutex<()>>, | |
| 40 | +} | |
| 41 | + | |
| 42 | +/// The facet streams of every resident root on this node. | |
| 43 | +#[derive(Clone, Default)] | |
| 44 | +pub(crate) struct FacetStreams(Arc<Mutex<HashMap<String, FacetRoot>>>); | |
| 45 | + | |
| 46 | +impl FacetStreams { | |
| 47 | + /// A root's activation: its facets activate later with `spec`. | |
| 48 | + pub(crate) fn register(&self, root: &str, spec: &celld_logic::RestoreSpec) { | |
| 49 | + self.0.lock().expect("facet streams poisoned").insert( | |
| 50 | + root.to_string(), | |
| 51 | + FacetRoot { | |
| 52 | + epoch: spec.epoch, | |
| 53 | + spec: Some(spec.clone()), | |
| 54 | + streams: BTreeSet::new(), | |
| 55 | + stopping: false, | |
| 56 | + opening: Arc::default(), | |
| 57 | + }, | |
| 58 | + ); | |
| 59 | + } | |
| 60 | + | |
| 61 | + /// Activate a facet's stream, once per root activation, and answer its | |
| 62 | + /// database file and whether replication restored it from a replica. | |
| 63 | + /// `db_path` is the engine's own placement of a cell's database. | |
| 64 | + pub(crate) async fn open( | |
| 65 | + &self, | |
| 66 | + replication: Option<&Replication>, | |
| 67 | + db_path: impl Fn(&str, u64) -> PathBuf, | |
| 68 | + root: &str, | |
| 69 | + epoch: u64, | |
| 70 | + names: &[String], | |
| 71 | + ) -> anyhow::Result<(PathBuf, bool)> { | |
| 72 | + let facet = crate::engine_api::facet_cell(root, names); | |
| 73 | + let path = db_path(&facet, epoch); | |
| 74 | + let resident = |roots: &HashMap<String, FacetRoot>| { | |
| 75 | + roots | |
| 76 | + .get(root) | |
| 77 | + .filter(|entry| entry.epoch == epoch && !entry.stopping) | |
| 78 | + .map(|entry| { | |
| 79 | + ( | |
| 80 | + entry.streams.contains(&facet), | |
| 81 | + entry.spec.clone(), | |
| 82 | + entry.opening.clone(), | |
| 83 | + ) | |
| 84 | + }) | |
| 85 | + .ok_or_else(|| anyhow!("{root} epoch {epoch} is not resident")) | |
| 86 | + }; | |
| 87 | + let opening = { | |
| 88 | + let roots = self.0.lock().expect("facet streams poisoned"); | |
| 89 | + let (open, _, opening) = resident(&roots)?; | |
| 90 | + if open { | |
| 91 | + return Ok((path, false)); | |
| 92 | + } | |
| 93 | + opening | |
| 94 | + }; | |
| 95 | + let _opening = opening.lock().await; | |
| 96 | + let spec = { | |
| 97 | + let roots = self.0.lock().expect("facet streams poisoned"); | |
| 98 | + let (open, spec, _) = resident(&roots)?; | |
| 99 | + if open { | |
| 100 | + return Ok((path, false)); | |
| 101 | + } | |
| 102 | + spec | |
| 103 | + }; | |
| 104 | + let restored = match (replication, spec) { | |
| 105 | + (Some(replication), Some(mut spec)) => { | |
| 106 | + // A clean reload resumes the files it closed. A facet that | |
| 107 | + // was not open then has none, so it restores as any facet | |
| 108 | + // of this epoch does. | |
| 109 | + if spec.resume_local && crate::asyncrt::fs().metadata(&path).is_err() { | |
| 110 | + spec.resume_local = false; | |
| 111 | + } | |
| 112 | + let (restored_path, restored, _) = | |
| 113 | + replication.restore(&facet, &spec, false).await?; | |
| 114 | + anyhow::ensure!( | |
| 115 | + restored_path == path, | |
| 116 | + "replication restored {} instead of {}", | |
| 117 | + restored_path.display(), | |
| 118 | + path.display() | |
| 119 | + ); | |
| 120 | + restored | |
| 121 | + } | |
| 122 | + (Some(_), None) => anyhow::bail!("{root} was activated without a restore"), | |
| 123 | + (None, _) => { | |
| 124 | + let parent = path.parent().context("facet database has no parent")?; | |
| 125 | + crate::asyncrt::fs() | |
| 126 | + .create_dir_all(parent) | |
| 127 | + .with_context(|| format!("create facet directory {}", parent.display()))?; | |
| 128 | + false | |
| 129 | + } | |
| 130 | + }; | |
| 131 | + let mut roots = self.0.lock().expect("facet streams poisoned"); | |
| 132 | + match roots | |
| 133 | + .get_mut(root) | |
| 134 | + .filter(|entry| entry.epoch == epoch && !entry.stopping) | |
| 135 | + { | |
| 136 | + Some(entry) => { | |
| 137 | + entry.streams.insert(facet); | |
| 138 | + } | |
| 139 | + // The root stopped while the stream activated. | |
| 140 | + None => { | |
| 141 | + drop(roots); | |
| 142 | + if let Some(replication) = replication { | |
| 143 | + replication.ltx().discard(&facet, epoch); | |
| 144 | + } | |
| 145 | + anyhow::bail!("{root} epoch {epoch} stopped while its facet opened"); | |
| 146 | + } | |
| 147 | + } | |
| 148 | + Ok((path, restored)) | |
| 149 | + } | |
| 150 | + | |
| 151 | + /// Delete a facet's stream and every stream below it, resident or not, | |
| 152 | + /// locally and in the bucket. `local` is the facet's local directory. | |
| 153 | + /// Only the root's resident owner deletes: a delete that runs after the | |
| 154 | + /// root moved would remove what the new owner writes. | |
| 155 | + pub(crate) async fn delete( | |
| 156 | + &self, | |
| 157 | + replication: Option<&Replication>, | |
| 158 | + local: impl Fn(&str) -> PathBuf, | |
| 159 | + root: &str, | |
| 160 | + epoch: u64, | |
| 161 | + names: &[String], | |
| 162 | + ) -> anyhow::Result<()> { | |
| 163 | + let facet = crate::engine_api::facet_cell(root, names); | |
| 164 | + let below = format!("{facet}/"); | |
| 165 | + let doomed: Vec<String> = { | |
| 166 | + let mut roots = self.0.lock().expect("facet streams poisoned"); | |
| 167 | + let entry = roots | |
| 168 | + .get_mut(root) | |
| 169 | + .filter(|entry| entry.epoch == epoch && !entry.stopping) | |
| 170 | + .ok_or_else(|| anyhow!("{root} epoch {epoch} is not resident"))?; | |
| 171 | + let doomed: Vec<String> = entry | |
| 172 | + .streams | |
| 173 | + .iter() | |
| 174 | + .filter(|stream| **stream == facet || stream.starts_with(&below)) | |
| 175 | + .cloned() | |
| 176 | + .collect(); | |
| 177 | + for stream in &doomed { | |
| 178 | + entry.streams.remove(stream); | |
| 179 | + } | |
| 180 | + doomed | |
| 181 | + }; | |
| 182 | + match replication { | |
| 183 | + Some(replication) => { | |
| 184 | + for stream in &doomed { | |
| 185 | + replication.ltx().discard(stream, epoch); | |
| 186 | + } | |
| 187 | + replication.ltx().delete_streams(&facet).await | |
| 188 | + } | |
| 189 | + None => { | |
| 190 | + let local = local(&facet); | |
| 191 | + match crate::asyncrt::fs().remove_dir_all(&local) { | |
| 192 | + Err(error) if error.kind() != std::io::ErrorKind::NotFound => { | |
| 193 | + Err(error).with_context(|| format!("remove facet {}", local.display())) | |
| 194 | + } | |
| 195 | + _ => Ok(()), | |
| 196 | + } | |
| 197 | + } | |
| 198 | + } | |
| 199 | + } | |
| 200 | + | |
| 201 | + /// The root begins to stop: see `FacetRoot::stopping`. Answers the | |
| 202 | + /// streams the stop must stop, after which no open can add one. | |
| 203 | + pub(crate) fn stopping(&self, root: &str, epoch: u64) -> Vec<String> { | |
| 204 | + let mut roots = self.0.lock().expect("facet streams poisoned"); | |
| 205 | + match roots.get_mut(root).filter(|entry| entry.epoch == epoch) { | |
| 206 | + Some(entry) => { | |
| 207 | + entry.stopping = true; | |
| 208 | + entry.streams.iter().cloned().collect() | |
| 209 | + } | |
| 210 | + None => Vec::new(), | |
| 211 | + } | |
| 212 | + } | |
| 213 | + | |
| 214 | + /// Stop a root and its facets. The root's stream stops first, and only | |
| 215 | + /// while it is resident: a retry after the root stopped goes on to the | |
| 216 | + /// facets that remain. A root stop that fails or is abandoned leaves | |
| 217 | + /// every facet resident and resumes them, so a root that restarts in | |
| 218 | + /// place keeps its facets. The facets stop after the root, each | |
| 219 | + /// forgotten once it stopped. Nothing moves the root's ownership before | |
| 220 | + /// this returns, so every facet still stops before a new owner starts. | |
| 221 | + /// | |
| 222 | + /// Once the root stopped, a facet stop that fails is retried here until | |
| 223 | + /// it succeeds instead of returning: the facet's handoff snapshot is what | |
| 224 | + /// carries its acknowledged tail into the bucket, and a stop that failed | |
| 225 | + /// would let the caller restart a root whose stream is gone. The actor's | |
| 226 | + /// release loop has no overall timeout for the same reason. | |
| 227 | + pub(crate) async fn stop_root<R, F, FF>( | |
| 228 | + &self, | |
| 229 | + root: &str, | |
| 230 | + epoch: u64, | |
| 231 | + root_resident: bool, | |
| 232 | + stop_root: impl FnOnce() -> R, | |
| 233 | + mut stop_facet: F, | |
| 234 | + ) -> anyhow::Result<()> | |
| 235 | + where | |
| 236 | + R: std::future::Future<Output = anyhow::Result<()>>, | |
| 237 | + F: FnMut(String) -> FF, | |
| 238 | + FF: std::future::Future<Output = anyhow::Result<()>>, | |
| 239 | + { | |
| 240 | + self.stopping(root, epoch); | |
| 241 | + if root_resident { | |
| 242 | + if let Err(error) = stop_root().await { | |
| 243 | + self.resume(root, epoch); | |
| 244 | + return Err(error); | |
| 245 | + } | |
| 246 | + } | |
| 247 | + for facet in self.stopping(root, epoch) { | |
| 248 | + let mut delay = FACET_STOP_RETRY_FIRST; | |
| 249 | + while let Err(error) = stop_facet(facet.clone()).await { | |
| 250 | + tracing::warn!( | |
| 251 | + root, | |
| 252 | + epoch, | |
| 253 | + facet, | |
| 254 | + %error, | |
| 255 | + "a facet stop failed after its root stopped; retrying" | |
| 256 | + ); | |
| 257 | + crate::asyncrt::sleep(delay).await; | |
| 258 | + delay = (delay * 2).min(FACET_STOP_RETRY_MAX); | |
| 259 | + } | |
| 260 | + self.stopped(root, epoch, &facet); | |
| 261 | + } | |
| 262 | + self.forget(root, epoch); | |
| 263 | + Ok(()) | |
| 264 | + } | |
| 265 | + | |
| 266 | + /// The root's stop failed before any facet stopped, and the root | |
| 267 | + /// restarts in place: its facets open and delete again. | |
| 268 | + pub(crate) fn resume(&self, root: &str, epoch: u64) { | |
| 269 | + if let Some(entry) = self | |
| 270 | + .0 | |
| 271 | + .lock() | |
| 272 | + .expect("facet streams poisoned") | |
| 273 | + .get_mut(root) | |
| 274 | + .filter(|entry| entry.epoch == epoch) | |
| 275 | + { | |
| 276 | + entry.stopping = false; | |
| 277 | + } | |
| 278 | + } | |
| 279 | + | |
| 280 | + /// The facet streams of a resident root. | |
| 281 | + pub(crate) fn resident(&self, root: &str, epoch: u64) -> Vec<String> { | |
| 282 | + self.0 | |
| 283 | + .lock() | |
| 284 | + .expect("facet streams poisoned") | |
| 285 | + .get(root) | |
| 286 | + .filter(|entry| entry.epoch == epoch) | |
| 287 | + .map(|entry| entry.streams.iter().cloned().collect()) | |
| 288 | + .unwrap_or_default() | |
| 289 | + } | |
| 290 | + | |
| 291 | + /// A facet stream that stopped. The root's entry stays until the root | |
| 292 | + /// itself stops, so a stop that fails and restarts the root in place | |
| 293 | + /// can still open its facets. | |
| 294 | + pub(crate) fn stopped(&self, root: &str, epoch: u64, stream: &str) { | |
| 295 | + if let Some(entry) = self | |
| 296 | + .0 | |
| 297 | + .lock() | |
| 298 | + .expect("facet streams poisoned") | |
| 299 | + .get_mut(root) | |
| 300 | + .filter(|entry| entry.epoch == epoch) | |
| 301 | + { | |
| 302 | + entry.streams.remove(stream); | |
| 303 | + } | |
| 304 | + } | |
| 305 | + | |
| 306 | + /// The root stopped: its entry goes. | |
| 307 | + pub(crate) fn forget(&self, root: &str, epoch: u64) { | |
| 308 | + let mut roots = self.0.lock().expect("facet streams poisoned"); | |
| 309 | + if roots.get(root).is_some_and(|entry| entry.epoch == epoch) { | |
| 310 | + roots.remove(root); | |
| 311 | + } | |
| 312 | + } | |
| 313 | +} |
modifiedcrates/celld/generation.rs+204−1View file
| @@ -15,10 +15,11 @@ | ||
| 15 | 15 | //! therefore has one place it can be computed, and a reload cannot miss what |
| 16 | 16 | //! a boot did, because there is no second path for it to miss. |
| 17 | 17 | |
| 18 | +use std::collections::hash_map::Entry; | |
| 18 | 19 | use std::collections::{BTreeMap, BTreeSet, HashMap, VecDeque}; |
| 19 | 20 | use std::sync::Arc; |
| 20 | 21 | |
| 21 | -use anyhow::Context; | |
| 22 | +use anyhow::{anyhow, Context}; | |
| 22 | 23 | |
| 23 | 24 | use crate::assets::AssetResolver; |
| 24 | 25 | use crate::bucket::Bucket; |
| @@ -447,3 +448,205 @@ | ||
| 447 | 448 | /// current when the call lands. |
| 448 | 449 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 449 | 450 | pub struct GenerationTag(pub GenerationId); |
| 451 | +impl Generation { | |
| 452 | + /// Build a deployment into a generation that can serve. | |
| 453 | + /// | |
| 454 | + /// Every script in the graph is compiled and its primary pool warmed, so | |
| 455 | + /// a bundle that does not load, or declares a Durable Object class it | |
| 456 | + /// does not export, fails here — before the generation can take traffic | |
| 457 | + /// — rather than on the first request. The Durable Object classes of | |
| 458 | + /// every script form one flat registry, because `start_cell` resolves a | |
| 459 | + /// cell by the class its scope names and nothing else. | |
| 460 | + /// | |
| 461 | + /// Boot and reload both come through here. There is no other function | |
| 462 | + /// that turns a deployment into runtime state. | |
| 463 | + pub fn build( | |
| 464 | + id: GenerationId, | |
| 465 | + graph: DeploymentGraph, | |
| 466 | + options: GenerationOptions, | |
| 467 | + ) -> anyhow::Result<Self> { | |
| 468 | + let GenerationOptions { node, region } = options; | |
| 469 | + let DeploymentGraph { primary, cohosted } = graph; | |
| 470 | + crate::runtime::init_engine(); | |
| 471 | + | |
| 472 | + // A Queue class is shared by every co-hosted script, but its broker | |
| 473 | + // needs the consumer script rather than whichever script happened to | |
| 474 | + // register `__Queue` first. Resolve one deployment-wide catalog before | |
| 475 | + // constructing any WorkerConfig, then install the same catalog into | |
| 476 | + // every isolate that could host a queue cell. | |
| 477 | + let mut queue_catalog = BTreeMap::new(); | |
| 478 | + for (script, consumers) in | |
| 479 | + std::iter::once((&primary.script_name, &primary.options.queue_consumers)).chain( | |
| 480 | + cohosted | |
| 481 | + .iter() | |
| 482 | + .map(|target| (&target.script_name, &target.options.queue_consumers)), | |
| 483 | + ) | |
| 484 | + { | |
| 485 | + for consumer in consumers { | |
| 486 | + let registration = crate::js::QueueConsumerRegistration { | |
| 487 | + script: script.clone(), | |
| 488 | + config: consumer.clone(), | |
| 489 | + }; | |
| 490 | + if let Some(previous) = queue_catalog.insert(consumer.queue.clone(), registration) { | |
| 491 | + return Err(anyhow!( | |
| 492 | + "queue {:?} is consumed by both {} and {}", | |
| 493 | + consumer.queue, | |
| 494 | + previous.script, | |
| 495 | + script | |
| 496 | + )); | |
| 497 | + } | |
| 498 | + } | |
| 499 | + } | |
| 500 | + let queue_catalog = queue_catalog.into_values().collect::<Vec<_>>(); | |
| 501 | + | |
| 502 | + let node: Arc<str> = Arc::from(node); | |
| 503 | + let region: Arc<str> = Arc::from(region); | |
| 504 | + let primary_script = primary.script_name.clone(); | |
| 505 | + let version = primary.version.clone(); | |
| 506 | + let prefix = primary.prefix.clone(); | |
| 507 | + let mut all_containers = Vec::new(); | |
| 508 | + let mut fence_image = None; | |
| 509 | + // Only classes the user declared can be a bare-id default. Every | |
| 510 | + // runtime-supplied class rides in `do_classes` so that its namespace | |
| 511 | + // key is minted, and counting one here made adding any D1 binding flip | |
| 512 | + // a one-class project past the `len == 1` condition — every | |
| 513 | + // `/do/<bare-id>` request then failed with "requires exactly one | |
| 514 | + // configured Durable Object class" for a config that still declared | |
| 515 | + // exactly one. | |
| 516 | + // | |
| 517 | + // This asks `deploy::is_reserved_class` rather than naming one class, | |
| 518 | + // because the first version of this filter named `__D1Database` alone | |
| 519 | + // and `__Workflow` walked straight back into the same bug when it | |
| 520 | + // shipped. A fourth reserved class must not be able to do it a third | |
| 521 | + // time. | |
| 522 | + let user_classes: Vec<&String> = primary | |
| 523 | + .options | |
| 524 | + .do_classes | |
| 525 | + .iter() | |
| 526 | + .filter(|class| !crate::deploy::is_reserved_class(class)) | |
| 527 | + .collect(); | |
| 528 | + let default_do_class = | |
| 529 | + (user_classes.len() == 1).then(|| Arc::from(user_classes[0].as_str())); | |
| 530 | + // Two scripts exporting one class name is genuinely ambiguous and is | |
| 531 | + // refused — but a *reserved* class is not an export, and the two kinds | |
| 532 | + // behave differently: | |
| 533 | + // | |
| 534 | + // `__D1Database` is deliberately shared. Its namespace is fleet-wide so | |
| 535 | + // that several Workers can bind one database and a rename cannot rename | |
| 536 | + // it, so two scripts declaring `d1_databases` address the same cells on | |
| 537 | + // purpose. A D1 cell runs SQL and reads no user code, binding or var, | |
| 538 | + // so whichever config serves it is immaterial and the first wins. | |
| 539 | + // Refusing the second made the node exit instead of start. | |
| 540 | + // | |
| 541 | + // A workflow class is script-scoped (`deploy::workflow_class`), so two | |
| 542 | + // scripts produce two distinct names and never reach this branch. If | |
| 543 | + // one ever did, it would be a real collision and must still be refused. | |
| 544 | + let mut cell_configs: HashMap<String, Arc<WorkerConfig>> = HashMap::new(); | |
| 545 | + let mut service_pools = HashMap::new(); | |
| 546 | + let mut assets = HashMap::new(); | |
| 547 | + // Primary first: shared reserved classes retain the first script's | |
| 548 | + // config. Only this script owns ingress and the node's cron schedule; | |
| 549 | + // bindings and runtime construction follow the same path for all scripts. | |
| 550 | + for (index, deployment) in std::iter::once(primary).chain(cohosted).enumerate() { | |
| 551 | + let is_primary = index == 0; | |
| 552 | + let crate::fleet::LoadedDeployment { | |
| 553 | + options, | |
| 554 | + script_name: script, | |
| 555 | + asset_binding, | |
| 556 | + loader_bindings, | |
| 557 | + assets: resolver, | |
| 558 | + services, | |
| 559 | + crons, | |
| 560 | + containers, | |
| 561 | + fence_image: fence, | |
| 562 | + .. | |
| 563 | + } = deployment; | |
| 564 | + all_containers.extend(containers.iter().cloned()); | |
| 565 | + fence_image = fence_image.or(fence); | |
| 566 | + if let Some(resolver) = resolver { | |
| 567 | + assets.insert(script.clone(), resolver); | |
| 568 | + } | |
| 569 | + let classes = options.do_classes.clone(); | |
| 570 | + let config = Arc::new( | |
| 571 | + WorkerConfig::new(options) | |
| 572 | + .with_services(services) | |
| 573 | + .with_asset_binding(asset_binding) | |
| 574 | + .with_loaders(loader_bindings) | |
| 575 | + .with_queue_consumers(queue_catalog.clone()) | |
| 576 | + .with_crons(if is_primary { crons } else { Vec::new() }) | |
| 577 | + .with_containers(containers) | |
| 578 | + .with_generation(id), | |
| 579 | + ); | |
| 580 | + let pool = crate::runtime::StatelessRuntime::start( | |
| 581 | + config.clone(), | |
| 582 | + node.clone(), | |
| 583 | + region.clone(), | |
| 584 | + )?; | |
| 585 | + if service_pools.insert(script.clone(), pool).is_some() { | |
| 586 | + return Err(anyhow!("duplicate co-hosted Worker script {script}")); | |
| 587 | + } | |
| 588 | + for class in classes { | |
| 589 | + register_cell_class(&mut cell_configs, class, config.clone(), &|class| { | |
| 590 | + if is_primary { | |
| 591 | + anyhow!("duplicate Durable Object class {class}") | |
| 592 | + } else { | |
| 593 | + anyhow!( | |
| 594 | + "Durable Object class {class} is exported by more than one co-hosted script" | |
| 595 | + ) | |
| 596 | + } | |
| 597 | + })?; | |
| 598 | + } | |
| 599 | + // Cron is runtime-supplied, not a manifest class. Its alarm calls | |
| 600 | + // the primary script's scheduled handler with that script's bindings. | |
| 601 | + if !config.crons.is_empty() { | |
| 602 | + cell_configs.insert(celld_logic::cron::RESERVED_CLASS.to_string(), config); | |
| 603 | + } | |
| 604 | + } | |
| 605 | + let stateless = service_pools[&primary_script].clone(); | |
| 606 | + let cell_isolates: HashMap<String, Arc<crate::pool::Pool>> = cell_configs | |
| 607 | + .values() | |
| 608 | + .map(|config| { | |
| 609 | + ( | |
| 610 | + config.script_name.clone(), | |
| 611 | + crate::runtime::cell_pool(config.clone()), | |
| 612 | + ) | |
| 613 | + }) | |
| 614 | + .collect(); | |
| 615 | + Ok(Generation { | |
| 616 | + id, | |
| 617 | + version, | |
| 618 | + prefix, | |
| 619 | + script_name: primary_script, | |
| 620 | + stateless, | |
| 621 | + services: service_pools, | |
| 622 | + cell_configs, | |
| 623 | + cell_isolates, | |
| 624 | + default_do_class, | |
| 625 | + assets, | |
| 626 | + containers: all_containers, | |
| 627 | + fence_image, | |
| 628 | + }) | |
| 629 | + } | |
| 630 | +} | |
| 631 | +/// Claim one class name in a deployment's cell registry. | |
| 632 | +/// | |
| 633 | +/// A duplicate is an error for a user class, because `start_cell` resolves a | |
| 634 | +/// cell from the class its scope names and two exports of one name are | |
| 635 | +/// genuinely ambiguous. A duplicate of a *shared* reserved class is not: see | |
| 636 | +/// `deploy::is_shared_reserved_class`. The caller supplies the error so the | |
| 637 | +/// message can say whether the collision was inside one script or across two. | |
| 638 | +fn register_cell_class( | |
| 639 | + configs: &mut HashMap<String, Arc<WorkerConfig>>, | |
| 640 | + class: String, | |
| 641 | + config: Arc<WorkerConfig>, | |
| 642 | + duplicate: &dyn Fn(&str) -> anyhow::Error, | |
| 643 | +) -> anyhow::Result<()> { | |
| 644 | + match configs.entry(class) { | |
| 645 | + Entry::Vacant(slot) => { | |
| 646 | + slot.insert(config); | |
| 647 | + Ok(()) | |
| 648 | + } | |
| 649 | + Entry::Occupied(slot) if crate::deploy::is_shared_reserved_class(slot.key()) => Ok(()), | |
| 650 | + Entry::Occupied(slot) => Err(duplicate(slot.key())), | |
| 651 | + } | |
| 652 | +} |
addedcrates/celld/host_channels.rs+282−0View file
| @@ -1,0 +1,282 @@ | ||
| 1 | +// Copyright 2026 Deno Land Inc. Apache-2.0 license. | |
| 2 | + | |
| 3 | +//! The channels a cell runtime uses to hand work to the host: one request | |
| 4 | +//! type and one sender per host service. Engine-neutral; `crate::js` and | |
| 5 | +//! `crate::js::r2_ops` re-export every item at its old path. | |
| 6 | +use crate::bucket::Bucket; | |
| 7 | +use crate::engine_api::HttpResponse; | |
| 8 | +use crate::engine_api::QueueBatch; | |
| 9 | +use crate::engine_api::RequestBody; | |
| 10 | +use crate::engine_api::RpcData; | |
| 11 | +use crate::http_streams::RequestBodyGuard; | |
| 12 | +use crate::ws_registry::OutboundWsReq; | |
| 13 | +use anyhow::Result; | |
| 14 | +#[cfg(celld_internal_tests)] | |
| 15 | +use std::cell::RefCell; | |
| 16 | +use std::sync::OnceLock; | |
| 17 | + | |
| 18 | +/// A ticket asking the actor whether an outbound effect may leave the process. | |
| 19 | +/// | |
| 20 | +/// Every in-handler channel takes one: `fetch`, a service binding, a call to | |
| 21 | +/// another cell, and a frame on a socket the isolate opened. `position` is | |
| 22 | +/// present when the running event wrote through it, absent when the event only | |
| 23 | +/// read and the effect must trail whatever the cell already has outstanding. | |
| 24 | +pub struct GateReq { | |
| 25 | + pub scope: String, | |
| 26 | + /// The route the held effect would leave by, the position it must see | |
| 27 | + /// proven, and the epoch that position was sampled at. The sample happens | |
| 28 | + /// in the handler's turn, before `dispatch_gate` acquires the request that | |
| 29 | + /// pins the cell; a reset in between discards the sampled write and the | |
| 30 | + /// request would activate the next epoch, so the core refuses a ticket | |
| 31 | + /// whose epoch is not the resident one. The core stores the route and | |
| 32 | + /// hands it back, so the shell can route the release to the adapter | |
| 33 | + /// holding the effect. | |
| 34 | + pub ticket: crate::actor::GateTicket, | |
| 35 | + pub reply: tokio::sync::oneshot::Sender<Result<(), celld_logic::RequestError>>, | |
| 36 | +} | |
| 37 | +pub(crate) static GATE_TX: OnceLock<tokio::sync::mpsc::UnboundedSender<GateReq>> = OnceLock::new(); | |
| 38 | + | |
| 39 | +/// A facet's stream, asked for by the isolate that runs the facet: a facet | |
| 40 | +/// is a database and a replication stream of its own | |
| 41 | +/// (`crate::facet_streams`), which only the runtime can activate, delete, or | |
| 42 | +/// prove. | |
| 43 | +pub enum FacetReq { | |
| 44 | + /// Activate the stream of the facet at `names` below `root`, and answer | |
| 45 | + /// its database file and whether replication restored it. | |
| 46 | + Open { | |
| 47 | + root: String, | |
| 48 | + epoch: u64, | |
| 49 | + names: Vec<String>, | |
| 50 | + reply: tokio::sync::oneshot::Sender<Result<(std::path::PathBuf, bool)>>, | |
| 51 | + }, | |
| 52 | + /// Delete the facet's stream and every stream below it. | |
| 53 | + Delete { | |
| 54 | + root: String, | |
| 55 | + epoch: u64, | |
| 56 | + names: Vec<String>, | |
| 57 | + reply: tokio::sync::oneshot::Sender<Result<()>>, | |
| 58 | + }, | |
| 59 | + /// Prove every committed write of the stream durable. | |
| 60 | + Prove { | |
| 61 | + stream: String, | |
| 62 | + epoch: u64, | |
| 63 | + reply: tokio::sync::oneshot::Sender<Result<()>>, | |
| 64 | + }, | |
| 65 | +} | |
| 66 | +pub(crate) static FACET_TX: OnceLock<tokio::sync::mpsc::UnboundedSender<FacetReq>> = | |
| 67 | + OnceLock::new(); | |
| 68 | +pub fn set_facet_tx(tx: tokio::sync::mpsc::UnboundedSender<FacetReq>) { | |
| 69 | + let _ = FACET_TX.set(tx); | |
| 70 | +} | |
| 71 | +pub fn set_gate_tx(tx: tokio::sync::mpsc::UnboundedSender<GateReq>) { | |
| 72 | + let _ = GATE_TX.set(tx); | |
| 73 | +} | |
| 74 | + | |
| 75 | +/// A service-binding call: `env.NAME.fetch()`. Unlike a Durable Object call | |
| 76 | +/// there is no identity to resolve — any isolate running `script` will do — so | |
| 77 | +/// the runtime hands this straight to that script's stateless isolate pool. | |
| 78 | +pub struct SvcCallReq { | |
| 79 | + /// Fires when the caller's request signal aborts, so the router stops | |
| 80 | + /// waiting on the target instead of leaving the call outstanding. | |
| 81 | + pub cancel: Option<tokio::sync::oneshot::Receiver<()>>, | |
| 82 | + /// The application generation of the calling isolate. The target is | |
| 83 | + /// resolved in that generation's service graph, so a caller built for | |
| 84 | + /// one deployment never reaches a target from another. | |
| 85 | + pub generation: crate::generation::GenerationId, | |
| 86 | + pub script: String, | |
| 87 | + /// A named Worker entrypoint and its props, or the target's default export | |
| 88 | + /// when absent. Keeping both values together prevents a route from losing | |
| 89 | + /// the props that select its authority boundary. | |
| 90 | + pub entrypoint: Option<crate::WorkerFetchEntrypoint>, | |
| 91 | + pub url: String, | |
| 92 | + pub method: String, | |
| 93 | + pub body: RequestBody, | |
| 94 | + /// Owns a streamed body until the target installs its request context. | |
| 95 | + pub body_guard: RequestBodyGuard, | |
| 96 | + pub headers: Vec<(String, String)>, | |
| 97 | + pub reply: tokio::sync::oneshot::Sender<Result<HttpResponse>>, | |
| 98 | +} | |
| 99 | +pub(crate) static SVC_CALL_TX: OnceLock<tokio::sync::mpsc::UnboundedSender<SvcCallReq>> = | |
| 100 | + OnceLock::new(); | |
| 101 | + | |
| 102 | +/// A Worker assets-binding call. The script name selects the immutable asset | |
| 103 | +/// index loaded for that Worker; unlike ingress this never falls back into the | |
| 104 | +/// Worker and therefore cannot recurse. | |
| 105 | +pub struct AssetCallReq { | |
| 106 | + /// The calling isolate's application generation; see `SvcCallReq`. | |
| 107 | + pub generation: crate::generation::GenerationId, | |
| 108 | + pub script: String, | |
| 109 | + pub url: String, | |
| 110 | + pub method: String, | |
| 111 | + pub headers: Vec<(String, String)>, | |
| 112 | + pub reply: tokio::sync::oneshot::Sender<Result<HttpResponse>>, | |
| 113 | +} | |
| 114 | +pub(crate) static ASSET_CALL_TX: OnceLock<tokio::sync::mpsc::UnboundedSender<AssetCallReq>> = | |
| 115 | + OnceLock::new(); | |
| 116 | + | |
| 117 | +/// An RPC operation on a named `WorkerEntrypoint` of another script. A call's | |
| 118 | +/// arguments and every result cross as V8 structured-clone bytes. | |
| 119 | +pub struct SvcRpcReq { | |
| 120 | + /// The calling isolate's application generation; see `SvcCallReq`. | |
| 121 | + pub generation: crate::generation::GenerationId, | |
| 122 | + pub script: String, | |
| 123 | + pub entrypoint: String, | |
| 124 | + /// Structured-clone bytes for the target entrypoint's `ctx.props`. | |
| 125 | + pub props: Vec<u8>, | |
| 126 | + pub operation: crate::WorkerRpcOperation, | |
| 127 | + pub reply: tokio::sync::oneshot::Sender<Result<Vec<u8>>>, | |
| 128 | +} | |
| 129 | +pub(crate) static SVC_RPC_TX: OnceLock<tokio::sync::mpsc::UnboundedSender<SvcRpcReq>> = | |
| 130 | + OnceLock::new(); | |
| 131 | + | |
| 132 | +/// The persisted identity a consumer settlement must match for one message. | |
| 133 | +#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] | |
| 134 | +pub struct QueueLeaseRef { | |
| 135 | + pub message_id: String, | |
| 136 | + pub seq: i64, | |
| 137 | + pub generation: u64, | |
| 138 | +} | |
| 139 | + | |
| 140 | +/// A durable broker batch released through its output gate. | |
| 141 | +pub struct QueueDispatchReq { | |
| 142 | + pub scope: String, | |
| 143 | + /// The dispatching queue cell's application generation; see | |
| 144 | + /// `SvcCallReq`. | |
| 145 | + pub generation: crate::generation::GenerationId, | |
| 146 | + pub script: String, | |
| 147 | + pub lease_id: String, | |
| 148 | + pub leases: Vec<QueueLeaseRef>, | |
| 149 | + pub batch: QueueBatch, | |
| 150 | +} | |
| 151 | +pub(crate) static QUEUE_DISPATCH_TX: OnceLock< | |
| 152 | + tokio::sync::mpsc::UnboundedSender<QueueDispatchReq>, | |
| 153 | +> = OnceLock::new(); | |
| 154 | +/// The fleet bucket used by KV values that are too large for a namespace cell. | |
| 155 | +/// | |
| 156 | +/// The landed R2 binding established the safe pattern: a cloneable bucket | |
| 157 | +/// handle can live beside the asynchronous ops, so independent requests do not | |
| 158 | +/// queue behind one task that awaits every object-store operation in order. | |
| 159 | +static KV_BLOB_STORE: OnceLock<crate::bucket::Bucket> = OnceLock::new(); | |
| 160 | + | |
| 161 | +pub fn set_kv_blob_store(store: crate::bucket::Bucket) { | |
| 162 | + let _ = KV_BLOB_STORE.set(store); | |
| 163 | +} | |
| 164 | + | |
| 165 | +pub(crate) fn kv_blob_store() -> std::result::Result<&'static crate::bucket::Bucket, String> { | |
| 166 | + KV_BLOB_STORE | |
| 167 | + .get() | |
| 168 | + .ok_or_else(|| "KV large values need a fleet bucket".to_string()) | |
| 169 | +} | |
| 170 | + | |
| 171 | +pub fn set_svc_rpc_tx(tx: tokio::sync::mpsc::UnboundedSender<SvcRpcReq>) { | |
| 172 | + let _ = SVC_RPC_TX.set(tx); | |
| 173 | +} | |
| 174 | +pub fn set_svc_call_tx(tx: tokio::sync::mpsc::UnboundedSender<SvcCallReq>) { | |
| 175 | + let _ = SVC_CALL_TX.set(tx); | |
| 176 | +} | |
| 177 | +pub fn set_queue_dispatch_tx(tx: tokio::sync::mpsc::UnboundedSender<QueueDispatchReq>) { | |
| 178 | + let _ = QUEUE_DISPATCH_TX.set(tx); | |
| 179 | +} | |
| 180 | +pub fn set_asset_call_tx(tx: tokio::sync::mpsc::UnboundedSender<AssetCallReq>) { | |
| 181 | + let _ = ASSET_CALL_TX.set(tx); | |
| 182 | +} | |
| 183 | + | |
| 184 | +/// A native Durable Object RPC call (`stub.someMethod(...args)`). | |
| 185 | +/// Routing/activation is identical to fetch calls. | |
| 186 | +pub struct RpcCallReq { | |
| 187 | + pub scope: String, | |
| 188 | + pub name: Option<String>, | |
| 189 | + pub method: String, | |
| 190 | + pub args: RpcData, | |
| 191 | + pub reply: tokio::sync::oneshot::Sender<Result<RpcData>>, | |
| 192 | +} | |
| 193 | +pub(crate) static RPC_CALL_TX: OnceLock<tokio::sync::mpsc::UnboundedSender<RpcCallReq>> = | |
| 194 | + OnceLock::new(); | |
| 195 | +pub fn set_rpc_call_tx(tx: tokio::sync::mpsc::UnboundedSender<RpcCallReq>) { | |
| 196 | + let _ = RPC_CALL_TX.set(tx); | |
| 197 | +} | |
| 198 | + | |
| 199 | +static OUTBOUND_WS_TX: OnceLock<tokio::sync::mpsc::UnboundedSender<OutboundWsReq>> = | |
| 200 | + OnceLock::new(); | |
| 201 | +pub fn set_outbound_ws_tx(tx: tokio::sync::mpsc::UnboundedSender<OutboundWsReq>) { | |
| 202 | + let _ = OUTBOUND_WS_TX.set(tx); | |
| 203 | +} | |
| 204 | + | |
| 205 | +#[cfg(celld_internal_tests)] | |
| 206 | +/// An outbound connector scoped to the current internal-test JS thread. | |
| 207 | +/// | |
| 208 | +/// The production connector is process-wide. Installing a test sender there | |
| 209 | +/// captures requests from unrelated suites, and those suites have no receiver | |
| 210 | +/// that can answer them. The thread-local sender follows the current-thread V8 | |
| 211 | +/// harnesses, while this handle owns its receiver and removes the sender when | |
| 212 | +/// the case ends. | |
| 213 | +#[doc(hidden)] | |
| 214 | +pub struct TestOutboundWsConnector { | |
| 215 | + requests: tokio::sync::Mutex<tokio::sync::mpsc::UnboundedReceiver<OutboundWsReq>>, | |
| 216 | + /// A scoped connector must drop on the thread where it installed its sender. | |
| 217 | + _not_send: std::marker::PhantomData<std::rc::Rc<()>>, | |
| 218 | +} | |
| 219 | + | |
| 220 | +#[cfg(celld_internal_tests)] | |
| 221 | +impl TestOutboundWsConnector { | |
| 222 | + #[doc(hidden)] | |
| 223 | + pub fn requests( | |
| 224 | + &self, | |
| 225 | + ) -> &tokio::sync::Mutex<tokio::sync::mpsc::UnboundedReceiver<OutboundWsReq>> { | |
| 226 | + &self.requests | |
| 227 | + } | |
| 228 | +} | |
| 229 | + | |
| 230 | +#[cfg(celld_internal_tests)] | |
| 231 | +thread_local! { | |
| 232 | + static TEST_OUTBOUND_WS_TX: RefCell<Option<tokio::sync::mpsc::UnboundedSender<OutboundWsReq>>> = | |
| 233 | + const { RefCell::new(None) }; | |
| 234 | +} | |
| 235 | + | |
| 236 | +#[cfg(celld_internal_tests)] | |
| 237 | +impl Drop for TestOutboundWsConnector { | |
| 238 | + fn drop(&mut self) { | |
| 239 | + TEST_OUTBOUND_WS_TX.with(|slot| { | |
| 240 | + assert!( | |
| 241 | + slot.borrow_mut().take().is_some(), | |
| 242 | + "test outbound WebSocket connector was not installed", | |
| 243 | + ); | |
| 244 | + }); | |
| 245 | + } | |
| 246 | +} | |
| 247 | + | |
| 248 | +#[cfg(celld_internal_tests)] | |
| 249 | +/// Install the internal-test connector for the current JS thread. | |
| 250 | +#[doc(hidden)] | |
| 251 | +pub fn install_outbound_ws_connector_for_test() -> TestOutboundWsConnector { | |
| 252 | + let (tx, rx) = tokio::sync::mpsc::unbounded_channel(); | |
| 253 | + TEST_OUTBOUND_WS_TX.with(|slot| { | |
| 254 | + let mut slot = slot.borrow_mut(); | |
| 255 | + assert!( | |
| 256 | + slot.is_none(), | |
| 257 | + "test outbound WebSocket connector is already installed" | |
| 258 | + ); | |
| 259 | + *slot = Some(tx); | |
| 260 | + }); | |
| 261 | + TestOutboundWsConnector { | |
| 262 | + requests: tokio::sync::Mutex::new(rx), | |
| 263 | + _not_send: std::marker::PhantomData, | |
| 264 | + } | |
| 265 | +} | |
| 266 | + | |
| 267 | +/// Select the scoped internal-test connector before the production connector. | |
| 268 | +pub(crate) fn outbound_ws_tx() -> Option<tokio::sync::mpsc::UnboundedSender<OutboundWsReq>> { | |
| 269 | + #[cfg(celld_internal_tests)] | |
| 270 | + if let Some(tx) = TEST_OUTBOUND_WS_TX.with(|slot| slot.borrow().clone()) { | |
| 271 | + return Some(tx); | |
| 272 | + } | |
| 273 | + OUTBOUND_WS_TX.get().cloned() | |
| 274 | +} | |
| 275 | +/// The fleet bucket, once a node has opened one. Installed beside the | |
| 276 | +/// wake-entry gate at startup; absent for a bucketless run. | |
| 277 | +pub(crate) static R2_STORE: OnceLock<Bucket> = OnceLock::new(); | |
| 278 | + | |
| 279 | +/// Give the R2 bindings the fleet bucket to live in. | |
| 280 | +pub fn set_r2_store(bucket: Bucket) { | |
| 281 | + let _ = R2_STORE.set(bucket); | |
| 282 | +} |
modifiedcrates/celld/host_services.rs+23−0View file
| @@ -33,6 +33,8 @@ | ||
| 33 | 33 | websockets: crate::js::WebSocketService, |
| 34 | 34 | http_streams: Arc<crate::js::HttpStreamService>, |
| 35 | 35 | metrics: MetricsBackend, |
| 36 | + #[cfg(all(test, celld_internal_tests))] | |
| 37 | + handoff_transport: Mutex<Option<Arc<dyn crate::actor::HandoffTransportForTest>>>, | |
| 36 | 38 | } |
| 37 | 39 | |
| 38 | 40 | impl HostServices { |
| @@ -44,6 +46,8 @@ | ||
| 44 | 46 | websockets: crate::js::WebSocketService::default(), |
| 45 | 47 | http_streams: Arc::new(crate::js::HttpStreamService::default()), |
| 46 | 48 | metrics: MetricsBackend::Production(Mutex::new(ProcessLoadSampler::default())), |
| 49 | + #[cfg(all(test, celld_internal_tests))] | |
| 50 | + handoff_transport: Mutex::new(None), | |
| 47 | 51 | } |
| 48 | 52 | } |
| 49 | 53 | |
| @@ -56,6 +60,8 @@ | ||
| 56 | 60 | websockets: crate::js::WebSocketService::default(), |
| 57 | 61 | http_streams: Arc::new(crate::js::HttpStreamService::default()), |
| 58 | 62 | metrics: MetricsBackend::Scripted(Mutex::new(HostMetricsSample::default())), |
| 63 | + #[cfg(all(test, celld_internal_tests))] | |
| 64 | + handoff_transport: Mutex::new(None), | |
| 59 | 65 | } |
| 60 | 66 | } |
| 61 | 67 | |
| @@ -63,6 +69,23 @@ | ||
| 63 | 69 | let _ = self.node_load.set(load); |
| 64 | 70 | } |
| 65 | 71 | |
| 72 | + #[cfg(all(test, celld_internal_tests))] | |
| 73 | + pub(crate) fn set_handoff_transport_for_test( | |
| 74 | + &self, | |
| 75 | + transport: Arc<dyn crate::actor::HandoffTransportForTest>, | |
| 76 | + ) { | |
| 77 | + let mut slot = self.handoff_transport.lock().unwrap(); | |
| 78 | + assert!(slot.is_none(), "the handoff transport is already installed"); | |
| 79 | + *slot = Some(transport); | |
| 80 | + } | |
| 81 | + | |
| 82 | + #[cfg(all(test, celld_internal_tests))] | |
| 83 | + pub(crate) fn handoff_transport_for_test( | |
| 84 | + &self, | |
| 85 | + ) -> Option<Arc<dyn crate::actor::HandoffTransportForTest>> { | |
| 86 | + self.handoff_transport.lock().unwrap().clone() | |
| 87 | + } | |
| 88 | + | |
| 66 | 89 | pub(crate) fn bind_domain(&self, domain: crate::asyncrt::DomainToken) { |
| 67 | 90 | if let Err(candidate) = self.domain.set(domain) { |
| 68 | 91 | assert!( |
addedcrates/celld/http_streams.rs+2105−0View file
| @@ -1,0 +1,2105 @@ | ||
| 1 | +// Copyright 2026 Deno Land Inc. Apache-2.0 license. | |
| 2 | + | |
| 3 | +//! The HTTP stream registry: request and response bodies that cross the host | |
| 4 | +//! boundary by id rather than by value. Engine-neutral; `crate::js` | |
| 5 | +//! re-exports every item at its old path. | |
| 6 | +use crate::asyncrt; | |
| 7 | +use crate::engine_api::HttpChunkStream; | |
| 8 | +use crate::engine_api::HttpResponse; | |
| 9 | +use crate::engine_api::HttpResponseWebSocket; | |
| 10 | +use crate::engine_api::RequestBody; | |
| 11 | +use anyhow::Result; | |
| 12 | +use futures_util::StreamExt as _; | |
| 13 | +use std::collections::HashMap; | |
| 14 | +use std::pin::Pin; | |
| 15 | +#[cfg(all(test, celld_internal_tests))] | |
| 16 | +use std::sync::atomic::AtomicBool; | |
| 17 | +use std::sync::atomic::AtomicU64; | |
| 18 | +use std::sync::atomic::AtomicU8; | |
| 19 | +use std::sync::atomic::Ordering; | |
| 20 | +use std::sync::Arc; | |
| 21 | +use std::sync::OnceLock; | |
| 22 | +use std::sync::Weak; | |
| 23 | + | |
| 24 | +// Keep IDs process-global. A counter in each Domain could reuse an ID from a | |
| 25 | +// closed Domain, so a stale caller could read an unrelated new stream. | |
| 26 | +pub(crate) static NEXT_HTTP_STREAM_ID: AtomicU64 = AtomicU64::new(1); | |
| 27 | +/// What `__http_stream_read` resolves with at end of stream. | |
| 28 | +/// | |
| 29 | +/// The reader identifies the end by type, not by value. A chunk always | |
| 30 | +/// resolves as a `Uint8Array`, therefore body bytes can never look like | |
| 31 | +/// this marker. The value stays distinctive, so a reader that does compare | |
| 32 | +/// the value cannot match a plausible body. | |
| 33 | +pub(crate) const HTTP_STREAM_DONE: &str = "__celld_http_stream_end__"; | |
| 34 | +pub(crate) const HTTP_STREAM_IDLE_TIMEOUT_MS: u64 = 60_000; | |
| 35 | +pub(crate) const HTTP_STREAM_REGISTRATION_CLOSED: &str = "the HTTP stream service is closed"; | |
| 36 | +pub(crate) const HTTP_TEE_BRANCH_CAPACITY: usize = 16; | |
| 37 | +const RESPONSE_STREAM_CONSUMER_CANCELED: &str = "response stream consumer canceled"; | |
| 38 | +const RESPONSE_STREAM_CLOSE_IN_PROGRESS: &str = "response stream close is already in progress"; | |
| 39 | +pub(crate) enum HttpStreamSource { | |
| 40 | + Response(reqwest::Response), | |
| 41 | + Receiver(tokio::sync::mpsc::Receiver<Result<Vec<u8>, String>>), | |
| 42 | + Stream(HttpChunkStream), | |
| 43 | +} | |
| 44 | + | |
| 45 | +#[derive(Clone, Copy, Debug, Eq, PartialEq)] | |
| 46 | +#[repr(u8)] | |
| 47 | +pub(crate) enum HttpStreamTerminationReason { | |
| 48 | + Live = 0, | |
| 49 | + Finished = 1, | |
| 50 | + Cancelled = 2, | |
| 51 | + Expired = 3, | |
| 52 | +} | |
| 53 | + | |
| 54 | +impl HttpStreamTerminationReason { | |
| 55 | + fn from_u8(value: u8) -> Self { | |
| 56 | + match value { | |
| 57 | + 0 => Self::Live, | |
| 58 | + 1 => Self::Finished, | |
| 59 | + 2 => Self::Cancelled, | |
| 60 | + 3 => Self::Expired, | |
| 61 | + _ => unreachable!("invalid HTTP stream termination reason {value}"), | |
| 62 | + } | |
| 63 | + } | |
| 64 | +} | |
| 65 | + | |
| 66 | +pub(crate) struct HttpStreamTermination { | |
| 67 | + reason: AtomicU8, | |
| 68 | + waiter: futures_util::task::AtomicWaker, | |
| 69 | +} | |
| 70 | + | |
| 71 | +impl HttpStreamTermination { | |
| 72 | + fn new() -> Self { | |
| 73 | + Self { | |
| 74 | + reason: AtomicU8::new(HttpStreamTerminationReason::Live as u8), | |
| 75 | + waiter: futures_util::task::AtomicWaker::new(), | |
| 76 | + } | |
| 77 | + } | |
| 78 | + | |
| 79 | + pub(crate) fn reason(&self) -> HttpStreamTerminationReason { | |
| 80 | + HttpStreamTerminationReason::from_u8(self.reason.load(Ordering::Acquire)) | |
| 81 | + } | |
| 82 | + | |
| 83 | + /// Commit the reason while the registry lock still linearizes removal. | |
| 84 | + /// Waking is a separate operation because a waker can run arbitrary code. | |
| 85 | + fn commit(&self, reason: HttpStreamTerminationReason) { | |
| 86 | + let _ = self.reason.compare_exchange( | |
| 87 | + HttpStreamTerminationReason::Live as u8, | |
| 88 | + reason as u8, | |
| 89 | + Ordering::AcqRel, | |
| 90 | + Ordering::Acquire, | |
| 91 | + ); | |
| 92 | + } | |
| 93 | + | |
| 94 | + pub(crate) fn poll_reason( | |
| 95 | + &self, | |
| 96 | + context: &mut std::task::Context<'_>, | |
| 97 | + ) -> std::task::Poll<HttpStreamTerminationReason> { | |
| 98 | + let reason = self.reason(); | |
| 99 | + if reason != HttpStreamTerminationReason::Live { | |
| 100 | + return std::task::Poll::Ready(reason); | |
| 101 | + } | |
| 102 | + self.waiter.register(context.waker()); | |
| 103 | + let reason = self.reason(); | |
| 104 | + if reason == HttpStreamTerminationReason::Live { | |
| 105 | + std::task::Poll::Pending | |
| 106 | + } else { | |
| 107 | + std::task::Poll::Ready(reason) | |
| 108 | + } | |
| 109 | + } | |
| 110 | + | |
| 111 | + fn take_waiter(&self) -> Option<std::task::Waker> { | |
| 112 | + self.waiter.take() | |
| 113 | + } | |
| 114 | +} | |
| 115 | + | |
| 116 | +#[derive(Clone, Copy, Debug, Eq, PartialEq)] | |
| 117 | +enum HttpSourceLeaseMode { | |
| 118 | + Pull, | |
| 119 | + Transfer, | |
| 120 | +} | |
| 121 | + | |
| 122 | +enum HttpStreamSourceSlot { | |
| 123 | + Available(HttpStreamSource), | |
| 124 | + Leased { | |
| 125 | + token: u64, | |
| 126 | + mode: HttpSourceLeaseMode, | |
| 127 | + }, | |
| 128 | +} | |
| 129 | + | |
| 130 | +pub(crate) struct HttpStreamEntry { | |
| 131 | + generation: u64, | |
| 132 | + deadline_ms: u64, | |
| 133 | + source: HttpStreamSourceSlot, | |
| 134 | + pub(crate) termination: Arc<HttpStreamTermination>, | |
| 135 | + /// Request contexts that can still read this source. A dispatch guard can | |
| 136 | + /// reclaim the entry only while this is zero. | |
| 137 | + owners: usize, | |
| 138 | + active_writes: usize, | |
| 139 | + active_closes: usize, | |
| 140 | + closing: bool, | |
| 141 | +} | |
| 142 | + | |
| 143 | +pub(crate) struct ResponseStreamWriter { | |
| 144 | + writer: tokio::sync::mpsc::Sender<Result<Vec<u8>, String>>, | |
| 145 | + finished: tokio::sync::watch::Sender<bool>, | |
| 146 | +} | |
| 147 | + | |
| 148 | +impl HttpStreamEntry { | |
| 149 | + pub(crate) fn new(generation: u64, deadline_ms: u64, source: HttpStreamSource) -> Self { | |
| 150 | + Self { | |
| 151 | + generation, | |
| 152 | + deadline_ms, | |
| 153 | + source: HttpStreamSourceSlot::Available(source), | |
| 154 | + termination: Arc::new(HttpStreamTermination::new()), | |
| 155 | + owners: 0, | |
| 156 | + active_writes: 0, | |
| 157 | + active_closes: 0, | |
| 158 | + closing: false, | |
| 159 | + } | |
| 160 | + } | |
| 161 | + | |
| 162 | + fn is_expiry_eligible(&self) -> bool { | |
| 163 | + matches!(self.source, HttpStreamSourceSlot::Available(_)) | |
| 164 | + && self.owners == 0 | |
| 165 | + && self.active_writes == 0 | |
| 166 | + && self.active_closes == 0 | |
| 167 | + } | |
| 168 | + | |
| 169 | + fn is_due(&self, now_ms: u64) -> bool { | |
| 170 | + self.is_expiry_eligible() && now_ms >= self.deadline_ms | |
| 171 | + } | |
| 172 | +} | |
| 173 | + | |
| 174 | +impl ResponseStreamWriter { | |
| 175 | + pub(crate) fn new( | |
| 176 | + writer: tokio::sync::mpsc::Sender<Result<Vec<u8>, String>>, | |
| 177 | + finished: tokio::sync::watch::Sender<bool>, | |
| 178 | + ) -> Self { | |
| 179 | + Self { writer, finished } | |
| 180 | + } | |
| 181 | +} | |
| 182 | + | |
| 183 | +type ResponseStreamCloseWatch = ( | |
| 184 | + tokio::sync::mpsc::Sender<Result<Vec<u8>, String>>, | |
| 185 | + tokio::sync::watch::Receiver<bool>, | |
| 186 | +); | |
| 187 | + | |
| 188 | +pub(crate) struct HttpStreamState { | |
| 189 | + closed: bool, | |
| 190 | + next_generation: u64, | |
| 191 | + next_token: u64, | |
| 192 | + sweeper_running: bool, | |
| 193 | + pub(crate) sources: HashMap<u64, HttpStreamEntry>, | |
| 194 | + pub(crate) response_writers: HashMap<u64, ResponseStreamWriter>, | |
| 195 | + #[cfg(all(test, celld_internal_tests))] | |
| 196 | + sweeper_starts: u64, | |
| 197 | + #[cfg(all(test, celld_internal_tests))] | |
| 198 | + sweeper_active: usize, | |
| 199 | + #[cfg(all(test, celld_internal_tests))] | |
| 200 | + sweeper_exit_gate: Option<Arc<HttpSweeperExitGate>>, | |
| 201 | + #[cfg(all(test, celld_internal_tests))] | |
| 202 | + pull_completion_gate: Option<HttpPullCompletionGate>, | |
| 203 | +} | |
| 204 | + | |
| 205 | +pub(crate) struct HttpStreamService { | |
| 206 | + pub(crate) state: std::sync::Mutex<HttpStreamState>, | |
| 207 | + sweeper_notify: Arc<tokio::sync::Notify>, | |
| 208 | + owner: OnceLock<asyncrt::DomainToken>, | |
| 209 | + #[cfg(all(test, celld_internal_tests))] | |
| 210 | + registration_clock_reads: AtomicU64, | |
| 211 | +} | |
| 212 | + | |
| 213 | +#[cfg(all(test, celld_internal_tests))] | |
| 214 | +struct HttpPullCompletionGate { | |
| 215 | + stream_id: u64, | |
| 216 | + reached: std::sync::mpsc::SyncSender<()>, | |
| 217 | + release: std::sync::mpsc::Receiver<()>, | |
| 218 | +} | |
| 219 | + | |
| 220 | +#[cfg(all(test, celld_internal_tests))] | |
| 221 | +impl HttpPullCompletionGate { | |
| 222 | + fn pause(self) { | |
| 223 | + if self.reached.send(()).is_ok() { | |
| 224 | + let _ = self.release.recv(); | |
| 225 | + } | |
| 226 | + } | |
| 227 | +} | |
| 228 | + | |
| 229 | +#[cfg(all(test, celld_internal_tests))] | |
| 230 | +pub(crate) struct HttpSweeperExitGate { | |
| 231 | + pub(crate) reached: AtomicBool, | |
| 232 | + released: AtomicBool, | |
| 233 | + waiter: futures_util::task::AtomicWaker, | |
| 234 | +} | |
| 235 | + | |
| 236 | +#[cfg(all(test, celld_internal_tests))] | |
| 237 | +impl HttpSweeperExitGate { | |
| 238 | + fn new() -> Self { | |
| 239 | + Self { | |
| 240 | + reached: AtomicBool::new(false), | |
| 241 | + released: AtomicBool::new(false), | |
| 242 | + waiter: futures_util::task::AtomicWaker::new(), | |
| 243 | + } | |
| 244 | + } | |
| 245 | + | |
| 246 | + async fn wait(self: Arc<Self>) { | |
| 247 | + self.reached.store(true, Ordering::Release); | |
| 248 | + futures_util::future::poll_fn(|context| { | |
| 249 | + if self.released.load(Ordering::Acquire) { | |
| 250 | + return std::task::Poll::Ready(()); | |
| 251 | + } | |
| 252 | + self.waiter.register(context.waker()); | |
| 253 | + if self.released.load(Ordering::Acquire) { | |
| 254 | + std::task::Poll::Ready(()) | |
| 255 | + } else { | |
| 256 | + std::task::Poll::Pending | |
| 257 | + } | |
| 258 | + }) | |
| 259 | + .await; | |
| 260 | + } | |
| 261 | + | |
| 262 | + pub(crate) fn release(&self) { | |
| 263 | + self.released.store(true, Ordering::Release); | |
| 264 | + self.waiter.wake(); | |
| 265 | + } | |
| 266 | +} | |
| 267 | + | |
| 268 | +#[cfg(all(test, celld_internal_tests))] | |
| 269 | +struct HttpSweeperRunGuard { | |
| 270 | + service: Weak<HttpStreamService>, | |
| 271 | +} | |
| 272 | + | |
| 273 | +struct HttpSweeperOwnerGuard { | |
| 274 | + service: Weak<HttpStreamService>, | |
| 275 | + armed: bool, | |
| 276 | +} | |
| 277 | + | |
| 278 | +impl HttpSweeperOwnerGuard { | |
| 279 | + fn disarm(&mut self) { | |
| 280 | + self.armed = false; | |
| 281 | + } | |
| 282 | +} | |
| 283 | + | |
| 284 | +impl Drop for HttpSweeperOwnerGuard { | |
| 285 | + fn drop(&mut self) { | |
| 286 | + if self.armed { | |
| 287 | + if let Some(service) = self.service.upgrade() { | |
| 288 | + service.owner_lost(); | |
| 289 | + } | |
| 290 | + } | |
| 291 | + } | |
| 292 | +} | |
| 293 | + | |
| 294 | +#[cfg(all(test, celld_internal_tests))] | |
| 295 | +impl Drop for HttpSweeperRunGuard { | |
| 296 | + fn drop(&mut self) { | |
| 297 | + if let Some(service) = self.service.upgrade() { | |
| 298 | + let mut state = service.state.lock().unwrap(); | |
| 299 | + state.sweeper_active = state.sweeper_active.saturating_sub(1); | |
| 300 | + } | |
| 301 | + } | |
| 302 | +} | |
| 303 | + | |
| 304 | +#[derive(Default)] | |
| 305 | +struct HttpStreamDrain { | |
| 306 | + sources: Vec<(u64, HttpStreamEntry)>, | |
| 307 | + detached_sources: Vec<(u64, HttpStreamSource)>, | |
| 308 | + response_writers: Vec<(u64, ResponseStreamWriter)>, | |
| 309 | +} | |
| 310 | + | |
| 311 | +impl HttpStreamDrain { | |
| 312 | + fn dispose(mut self, propagate_panic: bool) { | |
| 313 | + // A source destructor can panic. HashMap drain order can change across | |
| 314 | + // processes, so ID order makes wakes and the retained panic replayable. | |
| 315 | + self.sources.sort_unstable_by_key(|(id, _)| *id); | |
| 316 | + self.detached_sources.sort_unstable_by_key(|(id, _)| *id); | |
| 317 | + self.response_writers.sort_unstable_by_key(|(id, _)| *id); | |
| 318 | + let mut first_panic = None; | |
| 319 | + for (_, source) in self.sources { | |
| 320 | + if let Some(waiter) = source.termination.take_waiter() { | |
| 321 | + let wake = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { | |
| 322 | + waiter.wake_by_ref(); | |
| 323 | + })); | |
| 324 | + if wake.is_err() { | |
| 325 | + // A waker destructor can also panic. Preserve the wake | |
| 326 | + // failure and leak this exceptional handle so cleanup can | |
| 327 | + // continue without a double panic. | |
| 328 | + std::mem::forget(waiter); | |
| 329 | + } else { | |
| 330 | + let drop_waiter = | |
| 331 | + std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| drop(waiter))); | |
| 332 | + retain_first_http_cleanup_panic(&mut first_panic, drop_waiter); | |
| 333 | + } | |
| 334 | + retain_first_http_cleanup_panic(&mut first_panic, wake); | |
| 335 | + } | |
| 336 | + let disposal = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| drop(source))); | |
| 337 | + retain_first_http_cleanup_panic(&mut first_panic, disposal); | |
| 338 | + } | |
| 339 | + for (_, source) in self.detached_sources { | |
| 340 | + let disposal = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| drop(source))); | |
| 341 | + retain_first_http_cleanup_panic(&mut first_panic, disposal); | |
| 342 | + } | |
| 343 | + for (_, writer) in self.response_writers { | |
| 344 | + let disposal = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| drop(writer))); | |
| 345 | + retain_first_http_cleanup_panic(&mut first_panic, disposal); | |
| 346 | + } | |
| 347 | + if let Some(payload) = first_panic { | |
| 348 | + if propagate_panic { | |
| 349 | + std::panic::resume_unwind(payload); | |
| 350 | + } | |
| 351 | + std::mem::forget(payload); | |
| 352 | + } | |
| 353 | + } | |
| 354 | + | |
| 355 | + fn dispose_propagating(self) { | |
| 356 | + self.dispose(true); | |
| 357 | + } | |
| 358 | + | |
| 359 | + fn dispose_suppressing(self) { | |
| 360 | + self.dispose(false); | |
| 361 | + } | |
| 362 | +} | |
| 363 | + | |
| 364 | +pub(crate) fn retain_first_http_cleanup_panic( | |
| 365 | + first: &mut Option<Box<dyn std::any::Any + Send>>, | |
| 366 | + result: std::thread::Result<()>, | |
| 367 | +) { | |
| 368 | + if let Err(payload) = result { | |
| 369 | + if first.is_none() { | |
| 370 | + *first = Some(payload); | |
| 371 | + } else { | |
| 372 | + // The payload is opaque, and its destructor can panic while the | |
| 373 | + // first cleanup failure is already retained. | |
| 374 | + std::mem::forget(payload); | |
| 375 | + } | |
| 376 | + } | |
| 377 | +} | |
| 378 | + | |
| 379 | +fn dispose_http_waiter_suppressing(waiter: Option<std::task::Waker>) { | |
| 380 | + if let Err(payload) = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| drop(waiter))) { | |
| 381 | + std::mem::forget(payload); | |
| 382 | + } | |
| 383 | +} | |
| 384 | + | |
| 385 | +fn run_http_cleanup_from_drop(cleanup: impl FnOnce()) { | |
| 386 | + let already_panicking = std::thread::panicking(); | |
| 387 | + if let Err(payload) = std::panic::catch_unwind(std::panic::AssertUnwindSafe(cleanup)) { | |
| 388 | + if already_panicking { | |
| 389 | + // A cleanup panic cannot replace the panic that already owns this | |
| 390 | + // unwind. The opaque payload is leaked because its destructor can | |
| 391 | + // also panic. | |
| 392 | + std::mem::forget(payload); | |
| 393 | + } else { | |
| 394 | + std::panic::resume_unwind(payload); | |
| 395 | + } | |
| 396 | + } | |
| 397 | +} | |
| 398 | + | |
| 399 | +fn dispose_http_completion(waiter: Option<std::task::Waker>, drain: HttpStreamDrain) { | |
| 400 | + let already_panicking = std::thread::panicking(); | |
| 401 | + let mut first_panic = None; | |
| 402 | + retain_first_http_cleanup_panic( | |
| 403 | + &mut first_panic, | |
| 404 | + std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| drop(waiter))), | |
| 405 | + ); | |
| 406 | + retain_first_http_cleanup_panic( | |
| 407 | + &mut first_panic, | |
| 408 | + std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| drain.dispose_propagating())), | |
| 409 | + ); | |
| 410 | + if let Some(payload) = first_panic { | |
| 411 | + if already_panicking { | |
| 412 | + std::mem::forget(payload); | |
| 413 | + } else { | |
| 414 | + std::panic::resume_unwind(payload); | |
| 415 | + } | |
| 416 | + } | |
| 417 | +} | |
| 418 | + | |
| 419 | +impl Default for HttpStreamState { | |
| 420 | + fn default() -> Self { | |
| 421 | + Self { | |
| 422 | + closed: false, | |
| 423 | + next_generation: 1, | |
| 424 | + next_token: 1, | |
| 425 | + sweeper_running: false, | |
| 426 | + sources: HashMap::new(), | |
| 427 | + response_writers: HashMap::new(), | |
| 428 | + #[cfg(all(test, celld_internal_tests))] | |
| 429 | + sweeper_starts: 0, | |
| 430 | + #[cfg(all(test, celld_internal_tests))] | |
| 431 | + sweeper_active: 0, | |
| 432 | + #[cfg(all(test, celld_internal_tests))] | |
| 433 | + sweeper_exit_gate: None, | |
| 434 | + #[cfg(all(test, celld_internal_tests))] | |
| 435 | + pull_completion_gate: None, | |
| 436 | + } | |
| 437 | + } | |
| 438 | +} | |
| 439 | + | |
| 440 | +impl Default for HttpStreamService { | |
| 441 | + fn default() -> Self { | |
| 442 | + Self { | |
| 443 | + state: std::sync::Mutex::new(HttpStreamState::default()), | |
| 444 | + sweeper_notify: Arc::new(tokio::sync::Notify::new()), | |
| 445 | + owner: OnceLock::new(), | |
| 446 | + #[cfg(all(test, celld_internal_tests))] | |
| 447 | + registration_clock_reads: AtomicU64::new(0), | |
| 448 | + } | |
| 449 | + } | |
| 450 | +} | |
| 451 | + | |
| 452 | +enum HttpSweepWait { | |
| 453 | + Deadline(u64), | |
| 454 | + Notification, | |
| 455 | + Exit, | |
| 456 | +} | |
| 457 | + | |
| 458 | +impl HttpStreamService { | |
| 459 | + pub(crate) fn bind_domain(&self, owner: asyncrt::DomainToken) { | |
| 460 | + if let Err(candidate) = self.owner.set(owner) { | |
| 461 | + assert!( | |
| 462 | + self.owner | |
| 463 | + .get() | |
| 464 | + .is_some_and(|current| current.same_owner(&candidate)), | |
| 465 | + "one HTTP stream service was bound to two execution Domains" | |
| 466 | + ); | |
| 467 | + } | |
| 468 | + } | |
| 469 | + | |
| 470 | + fn next_sequence(sequence: &mut u64) -> u64 { | |
| 471 | + let value = *sequence; | |
| 472 | + *sequence = sequence.wrapping_add(1).max(1); | |
| 473 | + value | |
| 474 | + } | |
| 475 | + | |
| 476 | + fn expired_error(stream_id: u64) -> String { | |
| 477 | + format!( | |
| 478 | + "HTTP stream {stream_id} expired after {} seconds of inactivity", | |
| 479 | + HTTP_STREAM_IDLE_TIMEOUT_MS / 1_000 | |
| 480 | + ) | |
| 481 | + } | |
| 482 | + | |
| 483 | + fn unknown_error(stream_id: u64) -> String { | |
| 484 | + format!("HTTP stream {stream_id} expired or is not registered") | |
| 485 | + } | |
| 486 | + | |
| 487 | + fn termination_result( | |
| 488 | + stream_id: u64, | |
| 489 | + reason: HttpStreamTerminationReason, | |
| 490 | + ) -> Result<Option<Vec<u8>>, String> { | |
| 491 | + match reason { | |
| 492 | + HttpStreamTerminationReason::Finished | HttpStreamTerminationReason::Cancelled => { | |
| 493 | + Ok(None) | |
| 494 | + } | |
| 495 | + HttpStreamTerminationReason::Expired => Err(Self::expired_error(stream_id)), | |
| 496 | + HttpStreamTerminationReason::Live => Err(Self::unknown_error(stream_id)), | |
| 497 | + } | |
| 498 | + } | |
| 499 | + | |
| 500 | + fn remove_locked( | |
| 501 | + state: &mut HttpStreamState, | |
| 502 | + stream_id: u64, | |
| 503 | + reason: HttpStreamTerminationReason, | |
| 504 | + drain: &mut HttpStreamDrain, | |
| 505 | + ) -> bool { | |
| 506 | + let Some(source) = state.sources.remove(&stream_id) else { | |
| 507 | + return false; | |
| 508 | + }; | |
| 509 | + source.termination.commit(reason); | |
| 510 | + if let Some(writer) = state.response_writers.remove(&stream_id) { | |
| 511 | + drain.response_writers.push((stream_id, writer)); | |
| 512 | + } | |
| 513 | + drain.sources.push((stream_id, source)); | |
| 514 | + true | |
| 515 | + } | |
| 516 | + | |
| 517 | + fn close_locked(state: &mut HttpStreamState, drain: &mut HttpStreamDrain) { | |
| 518 | + state.closed = true; | |
| 519 | + state.sweeper_running = false; | |
| 520 | + let mut ids = state.sources.keys().copied().collect::<Vec<_>>(); | |
| 521 | + ids.sort_unstable(); | |
| 522 | + for id in ids { | |
| 523 | + Self::remove_locked(state, id, HttpStreamTerminationReason::Cancelled, drain); | |
| 524 | + } | |
| 525 | + debug_assert!(state.response_writers.is_empty()); | |
| 526 | + } | |
| 527 | + | |
| 528 | + fn registration_clock( | |
| 529 | + &self, | |
| 530 | + state: &mut HttpStreamState, | |
| 531 | + drain: &mut HttpStreamDrain, | |
| 532 | + ) -> Option<(asyncrt::DomainToken, u64)> { | |
| 533 | + #[cfg(all(test, celld_internal_tests))] | |
| 534 | + self.registration_clock_reads.fetch_add(1, Ordering::SeqCst); | |
| 535 | + let owner = self.owner.get()?.clone(); | |
| 536 | + match owner.mono_ms() { | |
| 537 | + Ok(now_ms) => Some((owner, now_ms)), | |
| 538 | + Err(_) => { | |
| 539 | + Self::close_locked(state, drain); | |
| 540 | + None | |
| 541 | + } | |
| 542 | + } | |
| 543 | + } | |
| 544 | + | |
| 545 | + fn spawn_sweeper(self: &Arc<Self>, owner: &asyncrt::DomainToken) -> bool { | |
| 546 | + let service = Arc::downgrade(self); | |
| 547 | + #[cfg(all(test, celld_internal_tests))] | |
| 548 | + let run_guard = { | |
| 549 | + let mut state = self.state.lock().unwrap(); | |
| 550 | + state.sweeper_starts = state.sweeper_starts.saturating_add(1); | |
| 551 | + state.sweeper_active = state.sweeper_active.saturating_add(1); | |
| 552 | + HttpSweeperRunGuard { | |
| 553 | + service: service.clone(), | |
| 554 | + } | |
| 555 | + }; | |
| 556 | + let owner_guard = HttpSweeperOwnerGuard { | |
| 557 | + service: service.clone(), | |
| 558 | + armed: true, | |
| 559 | + }; | |
| 560 | + let notify = self.sweeper_notify.clone(); | |
| 561 | + let sweeper_owner = owner.clone(); | |
| 562 | + owner | |
| 563 | + .spawn_detached("http-stream-idle-sweeper", async move { | |
| 564 | + #[cfg(all(test, celld_internal_tests))] | |
| 565 | + let _run_guard = run_guard; | |
| 566 | + let mut owner_guard = owner_guard; | |
| 567 | + http_stream_sweeper(service, notify, sweeper_owner, &mut owner_guard).await; | |
| 568 | + }) | |
| 569 | + .is_ok() | |
| 570 | + } | |
| 571 | + | |
| 572 | + fn owner_lost(self: &Arc<Self>) { | |
| 573 | + let drain = { | |
| 574 | + let mut state = self.state.lock().unwrap(); | |
| 575 | + let mut drain = HttpStreamDrain::default(); | |
| 576 | + // Simulation quarantine closes registration before it drops tasks. | |
| 577 | + // Its explicit HTTP phase must remain the only place that drains | |
| 578 | + // sources, so task and timer destructors always run first. | |
| 579 | + if !state.closed { | |
| 580 | + Self::close_locked(&mut state, &mut drain); | |
| 581 | + } | |
| 582 | + drain | |
| 583 | + }; | |
| 584 | + self.sweeper_notify.notify_one(); | |
| 585 | + drain.dispose_suppressing(); | |
| 586 | + } | |
| 587 | + | |
| 588 | + #[must_use = "a rejected HTTP stream must not publish an ID"] | |
| 589 | + pub(crate) fn register_source(self: &Arc<Self>, source: HttpStreamSource) -> Option<u64> { | |
| 590 | + let stream_id = NEXT_HTTP_STREAM_ID.fetch_add(1, Ordering::Relaxed); | |
| 591 | + self.register(stream_id, source, None).then_some(stream_id) | |
| 592 | + } | |
| 593 | + | |
| 594 | + #[must_use = "a rejected response stream must not publish an ID"] | |
| 595 | + pub(crate) fn register_response_pair( | |
| 596 | + self: &Arc<Self>, | |
| 597 | + receiver: tokio::sync::mpsc::Receiver<Result<Vec<u8>, String>>, | |
| 598 | + writer: ResponseStreamWriter, | |
| 599 | + ) -> Option<u64> { | |
| 600 | + let stream_id = NEXT_HTTP_STREAM_ID.fetch_add(1, Ordering::Relaxed); | |
| 601 | + self.register( | |
| 602 | + stream_id, | |
| 603 | + HttpStreamSource::Receiver(receiver), | |
| 604 | + Some(writer), | |
| 605 | + ) | |
| 606 | + .then_some(stream_id) | |
| 607 | + } | |
| 608 | + | |
| 609 | + pub(crate) fn register( | |
| 610 | + self: &Arc<Self>, | |
| 611 | + stream_id: u64, | |
| 612 | + source: HttpStreamSource, | |
| 613 | + writer: Option<ResponseStreamWriter>, | |
| 614 | + ) -> bool { | |
| 615 | + let mut candidate_source = Some(source); | |
| 616 | + let mut candidate_writer = writer; | |
| 617 | + let mut drain = HttpStreamDrain::default(); | |
| 618 | + let mut owner = None; | |
| 619 | + let mut start_sweeper = false; | |
| 620 | + let accepted = { | |
| 621 | + let mut state = self.state.lock().unwrap(); | |
| 622 | + if state.closed { | |
| 623 | + false | |
| 624 | + } else if let Some((bound_owner, now_ms)) = | |
| 625 | + self.registration_clock(&mut state, &mut drain) | |
| 626 | + { | |
| 627 | + Self::remove_locked( | |
| 628 | + &mut state, | |
| 629 | + stream_id, | |
| 630 | + HttpStreamTerminationReason::Cancelled, | |
| 631 | + &mut drain, | |
| 632 | + ); | |
| 633 | + let generation = Self::next_sequence(&mut state.next_generation); | |
| 634 | + let deadline_ms = now_ms.saturating_add(HTTP_STREAM_IDLE_TIMEOUT_MS); | |
| 635 | + state.sources.insert( | |
| 636 | + stream_id, | |
| 637 | + HttpStreamEntry::new(generation, deadline_ms, candidate_source.take().unwrap()), | |
| 638 | + ); | |
| 639 | + if let Some(writer) = candidate_writer.take() { | |
| 640 | + state.response_writers.insert(stream_id, writer); | |
| 641 | + } | |
| 642 | + if !state.sweeper_running { | |
| 643 | + state.sweeper_running = true; | |
| 644 | + start_sweeper = true; | |
| 645 | + } | |
| 646 | + owner = Some(bound_owner); | |
| 647 | + true | |
| 648 | + } else { | |
| 649 | + false | |
| 650 | + } | |
| 651 | + }; | |
| 652 | + | |
| 653 | + if !accepted { | |
| 654 | + if let Some(source) = candidate_source.take() { | |
| 655 | + let rejected = HttpStreamEntry::new(0, 0, source); | |
| 656 | + rejected | |
| 657 | + .termination | |
| 658 | + .commit(HttpStreamTerminationReason::Cancelled); | |
| 659 | + drain.sources.push((stream_id, rejected)); | |
| 660 | + } | |
| 661 | + if let Some(writer) = candidate_writer.take() { | |
| 662 | + drain.response_writers.push((stream_id, writer)); | |
| 663 | + } | |
| 664 | + } else if start_sweeper { | |
| 665 | + if !self.spawn_sweeper(owner.as_ref().unwrap()) { | |
| 666 | + self.owner_lost(); | |
| 667 | + drain.dispose_suppressing(); | |
| 668 | + return false; | |
| 669 | + } | |
| 670 | + } else { | |
| 671 | + self.sweeper_notify.notify_one(); | |
| 672 | + } | |
| 673 | + drain.dispose_propagating(); | |
| 674 | + accepted | |
| 675 | + } | |
| 676 | + | |
| 677 | + pub(crate) fn claim(self: &Arc<Self>, stream_id: u64) -> Option<HttpStreamClaim> { | |
| 678 | + let mut drain = HttpStreamDrain::default(); | |
| 679 | + let mut generation = None; | |
| 680 | + { | |
| 681 | + let mut state = self.state.lock().unwrap(); | |
| 682 | + if !state.closed { | |
| 683 | + let now_ms = self | |
| 684 | + .registration_clock(&mut state, &mut drain) | |
| 685 | + .map(|(_, now_ms)| now_ms); | |
| 686 | + if let Some(now_ms) = now_ms { | |
| 687 | + if state | |
| 688 | + .sources | |
| 689 | + .get(&stream_id) | |
| 690 | + .is_some_and(|entry| entry.is_due(now_ms)) | |
| 691 | + { | |
| 692 | + Self::remove_locked( | |
| 693 | + &mut state, | |
| 694 | + stream_id, | |
| 695 | + HttpStreamTerminationReason::Expired, | |
| 696 | + &mut drain, | |
| 697 | + ); | |
| 698 | + } else if let Some(stream) = state.sources.get_mut(&stream_id) { | |
| 699 | + stream.owners = stream.owners.saturating_add(1); | |
| 700 | + generation = Some(stream.generation); | |
| 701 | + } | |
| 702 | + } | |
| 703 | + } | |
| 704 | + } | |
| 705 | + if !drain.sources.is_empty() || !drain.response_writers.is_empty() { | |
| 706 | + self.sweeper_notify.notify_one(); | |
| 707 | + } | |
| 708 | + drain.dispose_propagating(); | |
| 709 | + generation.map(|generation| HttpStreamClaim { | |
| 710 | + service: self.clone(), | |
| 711 | + stream_id, | |
| 712 | + generation, | |
| 713 | + armed: true, | |
| 714 | + }) | |
| 715 | + } | |
| 716 | + | |
| 717 | + fn release_claim(&self, stream_id: u64, generation: u64) { | |
| 718 | + let mut drain = HttpStreamDrain::default(); | |
| 719 | + let mut notify = false; | |
| 720 | + { | |
| 721 | + let mut state = self.state.lock().unwrap(); | |
| 722 | + let mut remove = false; | |
| 723 | + if let Some(stream) = state | |
| 724 | + .sources | |
| 725 | + .get_mut(&stream_id) | |
| 726 | + .filter(|stream| stream.generation == generation) | |
| 727 | + { | |
| 728 | + stream.owners = stream.owners.saturating_sub(1); | |
| 729 | + // Checkout consumes one claim before the asynchronous pull | |
| 730 | + // completes. Keep every leased source registered so the pull | |
| 731 | + // can publish its result. An abandoned lease removes itself, | |
| 732 | + // and an available source with no owners can be reclaimed now. | |
| 733 | + remove = stream.owners == 0 | |
| 734 | + && matches!(stream.source, HttpStreamSourceSlot::Available(_)); | |
| 735 | + notify = true; | |
| 736 | + } | |
| 737 | + if remove { | |
| 738 | + Self::remove_locked( | |
| 739 | + &mut state, | |
| 740 | + stream_id, | |
| 741 | + HttpStreamTerminationReason::Cancelled, | |
| 742 | + &mut drain, | |
| 743 | + ); | |
| 744 | + } | |
| 745 | + } | |
| 746 | + if notify { | |
| 747 | + self.sweeper_notify.notify_one(); | |
| 748 | + } | |
| 749 | + drain.dispose_propagating(); | |
| 750 | + } | |
| 751 | + | |
| 752 | + pub(crate) fn checkout_source( | |
| 753 | + self: &Arc<Self>, | |
| 754 | + stream_id: u64, | |
| 755 | + ) -> Result<(HttpSourceLease, HttpStreamSource), String> { | |
| 756 | + self.checkout(stream_id, HttpSourceLeaseMode::Pull, None) | |
| 757 | + } | |
| 758 | + | |
| 759 | + pub(crate) fn checkout_transfer( | |
| 760 | + self: &Arc<Self>, | |
| 761 | + stream_id: u64, | |
| 762 | + claim_generation: Option<u64>, | |
| 763 | + ) -> Result<HttpTransferredStream, String> { | |
| 764 | + let (lease, source) = | |
| 765 | + self.checkout(stream_id, HttpSourceLeaseMode::Transfer, claim_generation)?; | |
| 766 | + Ok(HttpTransferredStream { | |
| 767 | + inner: http_chunk_stream(source), | |
| 768 | + lease: HttpTransferLease::new(lease), | |
| 769 | + finished: false, | |
| 770 | + }) | |
| 771 | + } | |
| 772 | + | |
| 773 | + fn checkout( | |
| 774 | + self: &Arc<Self>, | |
| 775 | + stream_id: u64, | |
| 776 | + mode: HttpSourceLeaseMode, | |
| 777 | + claim_generation: Option<u64>, | |
| 778 | + ) -> Result<(HttpSourceLease, HttpStreamSource), String> { | |
| 779 | + let mut drain = HttpStreamDrain::default(); | |
| 780 | + let mut checkout = None; | |
| 781 | + let mut error = None; | |
| 782 | + { | |
| 783 | + let mut state = self.state.lock().unwrap(); | |
| 784 | + if state.closed { | |
| 785 | + error = Some(Self::unknown_error(stream_id)); | |
| 786 | + } else { | |
| 787 | + let now_ms = self | |
| 788 | + .registration_clock(&mut state, &mut drain) | |
| 789 | + .map(|(_, now_ms)| now_ms); | |
| 790 | + if let Some(now_ms) = now_ms { | |
| 791 | + if state | |
| 792 | + .sources | |
| 793 | + .get(&stream_id) | |
| 794 | + .is_some_and(|entry| entry.is_due(now_ms)) | |
| 795 | + { | |
| 796 | + Self::remove_locked( | |
| 797 | + &mut state, | |
| 798 | + stream_id, | |
| 799 | + HttpStreamTerminationReason::Expired, | |
| 800 | + &mut drain, | |
| 801 | + ); | |
| 802 | + error = Some(Self::expired_error(stream_id)); | |
| 803 | + } else if !state.sources.contains_key(&stream_id) { | |
| 804 | + error = Some(Self::unknown_error(stream_id)); | |
| 805 | + } else { | |
| 806 | + let token = Self::next_sequence(&mut state.next_token); | |
| 807 | + let entry = state.sources.get_mut(&stream_id).unwrap(); | |
| 808 | + if claim_generation.is_some_and(|generation| { | |
| 809 | + generation != entry.generation || entry.owners == 0 | |
| 810 | + }) { | |
| 811 | + error = Some(Self::unknown_error(stream_id)); | |
| 812 | + } else { | |
| 813 | + let leased = HttpStreamSourceSlot::Leased { token, mode }; | |
| 814 | + match std::mem::replace(&mut entry.source, leased) { | |
| 815 | + HttpStreamSourceSlot::Available(source) => { | |
| 816 | + if claim_generation.is_some() { | |
| 817 | + entry.owners = entry.owners.saturating_sub(1); | |
| 818 | + } | |
| 819 | + checkout = Some(( | |
| 820 | + entry.generation, | |
| 821 | + token, | |
| 822 | + entry.termination.clone(), | |
| 823 | + source, | |
| 824 | + )); | |
| 825 | + } | |
| 826 | + occupied @ HttpStreamSourceSlot::Leased { .. } => { | |
| 827 | + entry.source = occupied; | |
| 828 | + error = Some(format!( | |
| 829 | + "HTTP stream {stream_id} source is checked out" | |
| 830 | + )); | |
| 831 | + } | |
| 832 | + } | |
| 833 | + } | |
| 834 | + } | |
| 835 | + } else { | |
| 836 | + error = Some(Self::unknown_error(stream_id)); | |
| 837 | + } | |
| 838 | + } | |
| 839 | + } | |
| 840 | + self.sweeper_notify.notify_one(); | |
| 841 | + drain.dispose_propagating(); | |
| 842 | + if let Some((generation, token, termination, source)) = checkout { | |
| 843 | + Ok(( | |
| 844 | + HttpSourceLease { | |
| 845 | + service: self.clone(), | |
| 846 | + stream_id, | |
| 847 | + generation, | |
| 848 | + token, | |
| 849 | + mode, | |
| 850 | + termination, | |
| 851 | + settled: false, | |
| 852 | + }, | |
| 853 | + source, | |
| 854 | + )) | |
| 855 | + } else { | |
| 856 | + Err(error.unwrap_or_else(|| Self::unknown_error(stream_id))) | |
| 857 | + } | |
| 858 | + } | |
| 859 | + | |
| 860 | + pub(crate) fn complete_pull( | |
| 861 | + &self, | |
| 862 | + lease: &HttpSourceLease, | |
| 863 | + source: HttpStreamSource, | |
| 864 | + result: Result<Option<Vec<u8>>, String>, | |
| 865 | + ) -> Result<Option<Vec<u8>>, String> { | |
| 866 | + let mut source = Some(source); | |
| 867 | + let mut drain = HttpStreamDrain::default(); | |
| 868 | + #[cfg(all(test, celld_internal_tests))] | |
| 869 | + let mut completion_gate = None; | |
| 870 | + let (answer, waiter) = { | |
| 871 | + let mut state = self.state.lock().unwrap(); | |
| 872 | + let reason = lease.termination.reason(); | |
| 873 | + let matches = state.sources.get(&lease.stream_id).is_some_and(|entry| { | |
| 874 | + entry.generation == lease.generation | |
| 875 | + && matches!( | |
| 876 | + entry.source, | |
| 877 | + HttpStreamSourceSlot::Leased { | |
| 878 | + token, | |
| 879 | + mode: HttpSourceLeaseMode::Pull, | |
| 880 | + } if token == lease.token | |
| 881 | + ) | |
| 882 | + }); | |
| 883 | + let answer = if reason != HttpStreamTerminationReason::Live || !matches { | |
| 884 | + Self::termination_result(lease.stream_id, reason) | |
| 885 | + } else { | |
| 886 | + match result { | |
| 887 | + Ok(Some(bytes)) => { | |
| 888 | + let now_ms = self.owner.get().and_then(|owner| owner.mono_ms().ok()); | |
| 889 | + if let Some(now_ms) = now_ms { | |
| 890 | + let entry = state.sources.get_mut(&lease.stream_id).unwrap(); | |
| 891 | + entry.source = HttpStreamSourceSlot::Available(source.take().unwrap()); | |
| 892 | + entry.deadline_ms = now_ms.saturating_add(HTTP_STREAM_IDLE_TIMEOUT_MS); | |
| 893 | + Ok(Some(bytes)) | |
| 894 | + } else { | |
| 895 | + Self::close_locked(&mut state, &mut drain); | |
| 896 | + Ok(None) | |
| 897 | + } | |
| 898 | + } | |
| 899 | + Ok(None) => { | |
| 900 | + Self::remove_locked( | |
| 901 | + &mut state, | |
| 902 | + lease.stream_id, | |
| 903 | + HttpStreamTerminationReason::Finished, | |
| 904 | + &mut drain, | |
| 905 | + ); | |
| 906 | + Ok(None) | |
| 907 | + } | |
| 908 | + Err(error) => { | |
| 909 | + Self::remove_locked( | |
| 910 | + &mut state, | |
| 911 | + lease.stream_id, | |
| 912 | + HttpStreamTerminationReason::Finished, | |
| 913 | + &mut drain, | |
| 914 | + ); | |
| 915 | + Err(error) | |
| 916 | + } | |
| 917 | + } | |
| 918 | + }; | |
| 919 | + // Restoring the source lets a successor lease register a waiter | |
| 920 | + // as soon as this lock opens. Take only this lease's waiter while | |
| 921 | + // the registry still prevents that successor checkout. | |
| 922 | + let waiter = lease.termination.take_waiter(); | |
| 923 | + #[cfg(all(test, celld_internal_tests))] | |
| 924 | + if state | |
| 925 | + .pull_completion_gate | |
| 926 | + .as_ref() | |
| 927 | + .is_some_and(|candidate| candidate.stream_id == lease.stream_id) | |
| 928 | + { | |
| 929 | + completion_gate = state.pull_completion_gate.take(); | |
| 930 | + } | |
| 931 | + (answer, waiter) | |
| 932 | + }; | |
| 933 | + #[cfg(all(test, celld_internal_tests))] | |
| 934 | + if let Some(gate) = completion_gate { | |
| 935 | + gate.pause(); | |
| 936 | + } | |
| 937 | + if let Some(source) = source { | |
| 938 | + drain.detached_sources.push((lease.stream_id, source)); | |
| 939 | + } | |
| 940 | + self.sweeper_notify.notify_one(); | |
| 941 | + // The waiter must be disposed before an arbitrary source destructor. | |
| 942 | + // Both can panic, so catch both cleanups and retain only the first. | |
| 943 | + dispose_http_completion(waiter, drain); | |
| 944 | + answer | |
| 945 | + } | |
| 946 | + | |
| 947 | + fn transferred_activity( | |
| 948 | + &self, | |
| 949 | + stream_id: u64, | |
| 950 | + generation: u64, | |
| 951 | + token: u64, | |
| 952 | + termination: &HttpStreamTermination, | |
| 953 | + ) -> Result<(), HttpStreamTerminationReason> { | |
| 954 | + let mut state = self.state.lock().unwrap(); | |
| 955 | + let reason = termination.reason(); | |
| 956 | + if reason != HttpStreamTerminationReason::Live { | |
| 957 | + return Err(reason); | |
| 958 | + } | |
| 959 | + let Some(entry) = state.sources.get_mut(&stream_id).filter(|entry| { | |
| 960 | + entry.generation == generation | |
| 961 | + && matches!( | |
| 962 | + entry.source, | |
| 963 | + HttpStreamSourceSlot::Leased { | |
| 964 | + token: current, | |
| 965 | + mode: HttpSourceLeaseMode::Transfer, | |
| 966 | + } if current == token | |
| 967 | + ) | |
| 968 | + }) else { | |
| 969 | + return Err(termination.reason()); | |
| 970 | + }; | |
| 971 | + let Some(now_ms) = self.owner.get().and_then(|owner| owner.mono_ms().ok()) else { | |
| 972 | + return Err(HttpStreamTerminationReason::Cancelled); | |
| 973 | + }; | |
| 974 | + entry.deadline_ms = now_ms.saturating_add(HTTP_STREAM_IDLE_TIMEOUT_MS); | |
| 975 | + Ok(()) | |
| 976 | + } | |
| 977 | + | |
| 978 | + fn finish_lease( | |
| 979 | + &self, | |
| 980 | + stream_id: u64, | |
| 981 | + generation: u64, | |
| 982 | + token: u64, | |
| 983 | + mode: HttpSourceLeaseMode, | |
| 984 | + termination: &HttpStreamTermination, | |
| 985 | + requested_reason: HttpStreamTerminationReason, | |
| 986 | + ) -> HttpStreamTerminationReason { | |
| 987 | + let mut drain = HttpStreamDrain::default(); | |
| 988 | + let winning_reason = { | |
| 989 | + let mut state = self.state.lock().unwrap(); | |
| 990 | + let matches = state.sources.get(&stream_id).is_some_and(|entry| { | |
| 991 | + entry.generation == generation | |
| 992 | + && matches!( | |
| 993 | + entry.source, | |
| 994 | + HttpStreamSourceSlot::Leased { | |
| 995 | + token: current, | |
| 996 | + mode: current_mode, | |
| 997 | + } if current == token && current_mode == mode | |
| 998 | + ) | |
| 999 | + }); | |
| 1000 | + if matches { | |
| 1001 | + let committed_reason = termination.reason(); | |
| 1002 | + let removal_reason = if committed_reason == HttpStreamTerminationReason::Live { | |
| 1003 | + requested_reason | |
| 1004 | + } else { | |
| 1005 | + committed_reason | |
| 1006 | + }; | |
| 1007 | + Self::remove_locked(&mut state, stream_id, removal_reason, &mut drain); | |
| 1008 | + } | |
| 1009 | + let reason = termination.reason(); | |
| 1010 | + if reason == HttpStreamTerminationReason::Live { | |
| 1011 | + HttpStreamTerminationReason::Cancelled | |
| 1012 | + } else { | |
| 1013 | + reason | |
| 1014 | + } | |
| 1015 | + }; | |
| 1016 | + self.sweeper_notify.notify_one(); | |
| 1017 | + drain.dispose_suppressing(); | |
| 1018 | + winning_reason | |
| 1019 | + } | |
| 1020 | + | |
| 1021 | + fn cancel_lease(&self, lease: &HttpSourceLease) { | |
| 1022 | + self.finish_lease( | |
| 1023 | + lease.stream_id, | |
| 1024 | + lease.generation, | |
| 1025 | + lease.token, | |
| 1026 | + lease.mode, | |
| 1027 | + &lease.termination, | |
| 1028 | + HttpStreamTerminationReason::Cancelled, | |
| 1029 | + ); | |
| 1030 | + } | |
| 1031 | + | |
| 1032 | + pub(crate) fn cancel_source(&self, stream_id: u64) { | |
| 1033 | + let mut drain = HttpStreamDrain::default(); | |
| 1034 | + { | |
| 1035 | + let mut state = self.state.lock().unwrap(); | |
| 1036 | + Self::remove_locked( | |
| 1037 | + &mut state, | |
| 1038 | + stream_id, | |
| 1039 | + HttpStreamTerminationReason::Cancelled, | |
| 1040 | + &mut drain, | |
| 1041 | + ); | |
| 1042 | + } | |
| 1043 | + self.sweeper_notify.notify_one(); | |
| 1044 | + drain.dispose_propagating(); | |
| 1045 | + } | |
| 1046 | + | |
| 1047 | + pub(crate) fn begin_activity( | |
| 1048 | + self: &Arc<Self>, | |
| 1049 | + stream_id: u64, | |
| 1050 | + kind: HttpStreamActivityKind, | |
| 1051 | + ) -> Result<HttpStreamActivity, HttpStreamActivityError> { | |
| 1052 | + let mut drain = HttpStreamDrain::default(); | |
| 1053 | + let mut acquired = None; | |
| 1054 | + let mut error = None; | |
| 1055 | + { | |
| 1056 | + let mut state = self.state.lock().unwrap(); | |
| 1057 | + if state.closed { | |
| 1058 | + error = Some(HttpStreamActivityError::Closed); | |
| 1059 | + } else { | |
| 1060 | + let now_ms = self | |
| 1061 | + .registration_clock(&mut state, &mut drain) | |
| 1062 | + .map(|(_, now_ms)| now_ms); | |
| 1063 | + if let Some(now_ms) = now_ms { | |
| 1064 | + if state | |
| 1065 | + .sources | |
| 1066 | + .get(&stream_id) | |
| 1067 | + .is_some_and(|entry| entry.is_due(now_ms)) | |
| 1068 | + { | |
| 1069 | + Self::remove_locked( | |
| 1070 | + &mut state, | |
| 1071 | + stream_id, | |
| 1072 | + HttpStreamTerminationReason::Expired, | |
| 1073 | + &mut drain, | |
| 1074 | + ); | |
| 1075 | + error = Some(HttpStreamActivityError::Gone); | |
| 1076 | + } else { | |
| 1077 | + let endpoints = state | |
| 1078 | + .response_writers | |
| 1079 | + .get(&stream_id) | |
| 1080 | + .map(|writer| (writer.writer.clone(), writer.finished.clone())); | |
| 1081 | + if let (Some(entry), Some((writer, finished))) = | |
| 1082 | + (state.sources.get_mut(&stream_id), endpoints) | |
| 1083 | + { | |
| 1084 | + if entry.closing { | |
| 1085 | + error = Some(HttpStreamActivityError::Closing); | |
| 1086 | + } else { | |
| 1087 | + match kind { | |
| 1088 | + HttpStreamActivityKind::Write => { | |
| 1089 | + entry.active_writes = entry.active_writes.saturating_add(1) | |
| 1090 | + } | |
| 1091 | + HttpStreamActivityKind::Close => { | |
| 1092 | + entry.active_closes = entry.active_closes.saturating_add(1); | |
| 1093 | + entry.closing = true; | |
| 1094 | + } | |
| 1095 | + } | |
| 1096 | + acquired = Some((writer, finished, entry.generation)); | |
| 1097 | + } | |
| 1098 | + } | |
| 1099 | + } | |
| 1100 | + } else if state.closed { | |
| 1101 | + error = Some(HttpStreamActivityError::Closed); | |
| 1102 | + } | |
| 1103 | + } | |
| 1104 | + } | |
| 1105 | + self.sweeper_notify.notify_one(); | |
| 1106 | + drain.dispose_propagating(); | |
| 1107 | + let Some((writer, finished, generation)) = acquired else { | |
| 1108 | + return Err(error.unwrap_or(HttpStreamActivityError::Gone)); | |
| 1109 | + }; | |
| 1110 | + Ok(HttpStreamActivity { | |
| 1111 | + writer, | |
| 1112 | + finished, | |
| 1113 | + lease: HttpStreamActivityLease { | |
| 1114 | + service: self.clone(), | |
| 1115 | + stream_id, | |
| 1116 | + generation, | |
| 1117 | + kind, | |
| 1118 | + active: true, | |
| 1119 | + }, | |
| 1120 | + }) | |
| 1121 | + } | |
| 1122 | + | |
| 1123 | + fn finish_activity( | |
| 1124 | + &self, | |
| 1125 | + stream_id: u64, | |
| 1126 | + generation: u64, | |
| 1127 | + kind: HttpStreamActivityKind, | |
| 1128 | + remove_writer: bool, | |
| 1129 | + ) { | |
| 1130 | + let mut removed_writer = None; | |
| 1131 | + { | |
| 1132 | + let mut state = self.state.lock().unwrap(); | |
| 1133 | + let now_ms = self.owner.get().and_then(|owner| owner.mono_ms().ok()); | |
| 1134 | + if let Some(entry) = state | |
| 1135 | + .sources | |
| 1136 | + .get_mut(&stream_id) | |
| 1137 | + .filter(|entry| entry.generation == generation) | |
| 1138 | + { | |
| 1139 | + match kind { | |
| 1140 | + HttpStreamActivityKind::Write => { | |
| 1141 | + entry.active_writes = entry.active_writes.saturating_sub(1) | |
| 1142 | + } | |
| 1143 | + HttpStreamActivityKind::Close => { | |
| 1144 | + entry.active_closes = entry.active_closes.saturating_sub(1); | |
| 1145 | + entry.closing = false; | |
| 1146 | + } | |
| 1147 | + } | |
| 1148 | + if let Some(now_ms) = now_ms { | |
| 1149 | + entry.deadline_ms = now_ms.saturating_add(HTTP_STREAM_IDLE_TIMEOUT_MS); | |
| 1150 | + } | |
| 1151 | + if remove_writer { | |
| 1152 | + removed_writer = state.response_writers.remove(&stream_id); | |
| 1153 | + } | |
| 1154 | + } | |
| 1155 | + } | |
| 1156 | + self.sweeper_notify.notify_one(); | |
| 1157 | + drop(removed_writer); | |
| 1158 | + } | |
| 1159 | + | |
| 1160 | + fn abandon_activity(&self, stream_id: u64, generation: u64, kind: HttpStreamActivityKind) { | |
| 1161 | + { | |
| 1162 | + let mut state = self.state.lock().unwrap(); | |
| 1163 | + if let Some(entry) = state | |
| 1164 | + .sources | |
| 1165 | + .get_mut(&stream_id) | |
| 1166 | + .filter(|entry| entry.generation == generation) | |
| 1167 | + { | |
| 1168 | + match kind { | |
| 1169 | + HttpStreamActivityKind::Write => { | |
| 1170 | + entry.active_writes = entry.active_writes.saturating_sub(1) | |
| 1171 | + } | |
| 1172 | + HttpStreamActivityKind::Close => { | |
| 1173 | + entry.active_closes = entry.active_closes.saturating_sub(1); | |
| 1174 | + entry.closing = false; | |
| 1175 | + } | |
| 1176 | + } | |
| 1177 | + } | |
| 1178 | + } | |
| 1179 | + // Drop does not read the clock or manufacture activity. It only makes | |
| 1180 | + // the previous successful-activity deadline eligible again. | |
| 1181 | + self.sweeper_notify.notify_one(); | |
| 1182 | + } | |
| 1183 | + | |
| 1184 | + fn cancel_activity_pair(&self, stream_id: u64, generation: u64, kind: HttpStreamActivityKind) { | |
| 1185 | + let mut drain = HttpStreamDrain::default(); | |
| 1186 | + { | |
| 1187 | + let mut state = self.state.lock().unwrap(); | |
| 1188 | + let matches = state | |
| 1189 | + .sources | |
| 1190 | + .get(&stream_id) | |
| 1191 | + .is_some_and(|entry| entry.generation == generation); | |
| 1192 | + if matches { | |
| 1193 | + if let Some(entry) = state.sources.get_mut(&stream_id) { | |
| 1194 | + match kind { | |
| 1195 | + HttpStreamActivityKind::Write => { | |
| 1196 | + entry.active_writes = entry.active_writes.saturating_sub(1) | |
| 1197 | + } | |
| 1198 | + HttpStreamActivityKind::Close => { | |
| 1199 | + entry.active_closes = entry.active_closes.saturating_sub(1) | |
| 1200 | + } | |
| 1201 | + } | |
| 1202 | + } | |
| 1203 | + Self::remove_locked( | |
| 1204 | + &mut state, | |
| 1205 | + stream_id, | |
| 1206 | + HttpStreamTerminationReason::Cancelled, | |
| 1207 | + &mut drain, | |
| 1208 | + ); | |
| 1209 | + } | |
| 1210 | + } | |
| 1211 | + self.sweeper_notify.notify_one(); | |
| 1212 | + drain.dispose_propagating(); | |
| 1213 | + } | |
| 1214 | + | |
| 1215 | + pub(crate) fn writer_close_watch(&self, stream_id: u64) -> Option<ResponseStreamCloseWatch> { | |
| 1216 | + let state = self.state.lock().unwrap(); | |
| 1217 | + if state.closed { | |
| 1218 | + return None; | |
| 1219 | + } | |
| 1220 | + state | |
| 1221 | + .response_writers | |
| 1222 | + .get(&stream_id) | |
| 1223 | + .map(|stream| (stream.writer.clone(), stream.finished.subscribe())) | |
| 1224 | + } | |
| 1225 | + | |
| 1226 | + fn sweep_step(&self, owner: &asyncrt::DomainToken) -> (HttpSweepWait, HttpStreamDrain) { | |
| 1227 | + let mut drain = HttpStreamDrain::default(); | |
| 1228 | + let wait = { | |
| 1229 | + let mut state = self.state.lock().unwrap(); | |
| 1230 | + if state.closed { | |
| 1231 | + state.sweeper_running = false; | |
| 1232 | + HttpSweepWait::Exit | |
| 1233 | + } else if let Ok(now_ms) = owner.mono_ms() { | |
| 1234 | + let mut due = state | |
| 1235 | + .sources | |
| 1236 | + .iter() | |
| 1237 | + .filter_map(|(id, entry)| entry.is_due(now_ms).then_some(*id)) | |
| 1238 | + .collect::<Vec<_>>(); | |
| 1239 | + due.sort_unstable(); | |
| 1240 | + for id in due { | |
| 1241 | + Self::remove_locked( | |
| 1242 | + &mut state, | |
| 1243 | + id, | |
| 1244 | + HttpStreamTerminationReason::Expired, | |
| 1245 | + &mut drain, | |
| 1246 | + ); | |
| 1247 | + } | |
| 1248 | + if state.sources.is_empty() { | |
| 1249 | + state.sweeper_running = false; | |
| 1250 | + HttpSweepWait::Exit | |
| 1251 | + } else if let Some(deadline_ms) = state | |
| 1252 | + .sources | |
| 1253 | + .values() | |
| 1254 | + .filter(|entry| entry.is_expiry_eligible()) | |
| 1255 | + .map(|entry| entry.deadline_ms) | |
| 1256 | + .min() | |
| 1257 | + { | |
| 1258 | + HttpSweepWait::Deadline(deadline_ms) | |
| 1259 | + } else { | |
| 1260 | + HttpSweepWait::Notification | |
| 1261 | + } | |
| 1262 | + } else { | |
| 1263 | + Self::close_locked(&mut state, &mut drain); | |
| 1264 | + HttpSweepWait::Exit | |
| 1265 | + } | |
| 1266 | + }; | |
| 1267 | + (wait, drain) | |
| 1268 | + } | |
| 1269 | + | |
| 1270 | + #[cfg(all(test, celld_internal_tests))] | |
| 1271 | + pub(crate) fn source_exists_for_test(&self, stream_id: u64) -> bool { | |
| 1272 | + self.state.lock().unwrap().sources.contains_key(&stream_id) | |
| 1273 | + } | |
| 1274 | + | |
| 1275 | + #[cfg(all(test, celld_internal_tests))] | |
| 1276 | + pub(crate) fn writer_exists_for_test(&self, stream_id: u64) -> bool { | |
| 1277 | + self.state | |
| 1278 | + .lock() | |
| 1279 | + .unwrap() | |
| 1280 | + .response_writers | |
| 1281 | + .contains_key(&stream_id) | |
| 1282 | + } | |
| 1283 | + | |
| 1284 | + #[cfg(all(test, celld_internal_tests))] | |
| 1285 | + pub(crate) fn termination_for_test( | |
| 1286 | + &self, | |
| 1287 | + stream_id: u64, | |
| 1288 | + ) -> Option<Arc<HttpStreamTermination>> { | |
| 1289 | + self.state | |
| 1290 | + .lock() | |
| 1291 | + .unwrap() | |
| 1292 | + .sources | |
| 1293 | + .get(&stream_id) | |
| 1294 | + .map(|entry| entry.termination.clone()) | |
| 1295 | + } | |
| 1296 | + | |
| 1297 | + #[cfg(all(test, celld_internal_tests))] | |
| 1298 | + pub(crate) fn lock_is_available_for_test(&self) -> bool { | |
| 1299 | + self.state.try_lock().is_ok() | |
| 1300 | + } | |
| 1301 | + | |
| 1302 | + #[cfg(all(test, celld_internal_tests))] | |
| 1303 | + pub(crate) fn arm_sweeper_exit_for_test(&self) -> Arc<HttpSweeperExitGate> { | |
| 1304 | + let gate = Arc::new(HttpSweeperExitGate::new()); | |
| 1305 | + let mut state = self.state.lock().unwrap(); | |
| 1306 | + assert!(state.sweeper_exit_gate.replace(gate.clone()).is_none()); | |
| 1307 | + gate | |
| 1308 | + } | |
| 1309 | + | |
| 1310 | + #[cfg(all(test, celld_internal_tests))] | |
| 1311 | + fn take_sweeper_exit_gate_for_test(&self) -> Option<Arc<HttpSweeperExitGate>> { | |
| 1312 | + self.state.lock().unwrap().sweeper_exit_gate.take() | |
| 1313 | + } | |
| 1314 | + | |
| 1315 | + #[cfg(all(test, celld_internal_tests))] | |
| 1316 | + pub(crate) fn sweeper_state_for_test(&self) -> (u64, usize, bool) { | |
| 1317 | + let state = self.state.lock().unwrap(); | |
| 1318 | + ( | |
| 1319 | + state.sweeper_starts, | |
| 1320 | + state.sweeper_active, | |
| 1321 | + state.sweeper_running, | |
| 1322 | + ) | |
| 1323 | + } | |
| 1324 | + | |
| 1325 | + #[cfg(all(test, celld_internal_tests))] | |
| 1326 | + pub(crate) fn registration_clock_reads_for_test(&self) -> u64 { | |
| 1327 | + self.registration_clock_reads.load(Ordering::SeqCst) | |
| 1328 | + } | |
| 1329 | + | |
| 1330 | + #[cfg(all(test, celld_internal_tests))] | |
| 1331 | + pub(crate) fn arm_pull_completion_after_unlock_for_test( | |
| 1332 | + &self, | |
| 1333 | + stream_id: u64, | |
| 1334 | + ) -> ( | |
| 1335 | + std::sync::mpsc::Receiver<()>, | |
| 1336 | + std::sync::mpsc::SyncSender<()>, | |
| 1337 | + ) { | |
| 1338 | + let (reached_sender, reached_receiver) = std::sync::mpsc::sync_channel(1); | |
| 1339 | + let (release_sender, release_receiver) = std::sync::mpsc::sync_channel(1); | |
| 1340 | + let gate = HttpPullCompletionGate { | |
| 1341 | + stream_id, | |
| 1342 | + reached: reached_sender, | |
| 1343 | + release: release_receiver, | |
| 1344 | + }; | |
| 1345 | + assert!(self | |
| 1346 | + .state | |
| 1347 | + .lock() | |
| 1348 | + .unwrap() | |
| 1349 | + .pull_completion_gate | |
| 1350 | + .replace(gate) | |
| 1351 | + .is_none()); | |
| 1352 | + (reached_receiver, release_sender) | |
| 1353 | + } | |
| 1354 | + | |
| 1355 | + #[cfg(all(test, celld_internal_tests))] | |
| 1356 | + pub(crate) fn closing_for_test(&self, stream_id: u64) -> bool { | |
| 1357 | + self.state | |
| 1358 | + .lock() | |
| 1359 | + .unwrap() | |
| 1360 | + .sources | |
| 1361 | + .get(&stream_id) | |
| 1362 | + .is_some_and(|entry| entry.closing) | |
| 1363 | + } | |
| 1364 | + | |
| 1365 | + #[cfg(all(test, celld_internal_tests))] | |
| 1366 | + pub(crate) fn quarantine(&self) { | |
| 1367 | + self.state.lock().unwrap().closed = true; | |
| 1368 | + self.sweeper_notify.notify_one(); | |
| 1369 | + } | |
| 1370 | + | |
| 1371 | + #[cfg(all(test, celld_internal_tests))] | |
| 1372 | + pub(crate) fn close(&self) { | |
| 1373 | + let drain = { | |
| 1374 | + let mut state = self.state.lock().unwrap(); | |
| 1375 | + let mut drain = HttpStreamDrain::default(); | |
| 1376 | + Self::close_locked(&mut state, &mut drain); | |
| 1377 | + drain | |
| 1378 | + }; | |
| 1379 | + self.sweeper_notify.notify_one(); | |
| 1380 | + drain.dispose_propagating(); | |
| 1381 | + } | |
| 1382 | +} | |
| 1383 | + | |
| 1384 | +impl Drop for HttpStreamService { | |
| 1385 | + fn drop(&mut self) { | |
| 1386 | + // The final runtime anchor can disappear before an explicit Domain | |
| 1387 | + // close. Exclusive access still makes a poisoned registry safe to | |
| 1388 | + // drain, so commit every termination before arbitrary cleanup runs. | |
| 1389 | + let state = match self.state.get_mut() { | |
| 1390 | + Ok(state) => state, | |
| 1391 | + Err(poisoned) => poisoned.into_inner(), | |
| 1392 | + }; | |
| 1393 | + let mut drain = HttpStreamDrain::default(); | |
| 1394 | + Self::close_locked(state, &mut drain); | |
| 1395 | + drain.dispose_suppressing(); | |
| 1396 | + } | |
| 1397 | +} | |
| 1398 | + | |
| 1399 | +async fn http_stream_sweeper( | |
| 1400 | + service: Weak<HttpStreamService>, | |
| 1401 | + notify: Arc<tokio::sync::Notify>, | |
| 1402 | + owner: asyncrt::DomainToken, | |
| 1403 | + owner_guard: &mut HttpSweeperOwnerGuard, | |
| 1404 | +) { | |
| 1405 | + loop { | |
| 1406 | + // Create the notification future before the registry snapshot. A | |
| 1407 | + // registration between the snapshot and the await leaves a permit, so | |
| 1408 | + // the sole sweeper cannot sleep through an earlier deadline. | |
| 1409 | + let notified = notify.notified(); | |
| 1410 | + let Some(service) = service.upgrade() else { | |
| 1411 | + return; | |
| 1412 | + }; | |
| 1413 | + let (wait, drain) = service.sweep_step(&owner); | |
| 1414 | + #[cfg(all(test, celld_internal_tests))] | |
| 1415 | + let exit_gate = matches!(wait, HttpSweepWait::Exit) | |
| 1416 | + .then(|| service.take_sweeper_exit_gate_for_test()) | |
| 1417 | + .flatten(); | |
| 1418 | + drop(service); | |
| 1419 | + // An abandoned source can own a panicking destructor. The leak | |
| 1420 | + // backstop must still service later entries after that failure. | |
| 1421 | + drain.dispose_suppressing(); | |
| 1422 | + match wait { | |
| 1423 | + HttpSweepWait::Exit => { | |
| 1424 | + #[cfg(all(test, celld_internal_tests))] | |
| 1425 | + if let Some(gate) = exit_gate { | |
| 1426 | + gate.wait().await; | |
| 1427 | + } | |
| 1428 | + owner_guard.disarm(); | |
| 1429 | + return; | |
| 1430 | + } | |
| 1431 | + HttpSweepWait::Notification => notified.await, | |
| 1432 | + HttpSweepWait::Deadline(deadline_ms) => { | |
| 1433 | + let Ok(sleep) = owner.sleep_until(deadline_ms) else { | |
| 1434 | + return; | |
| 1435 | + }; | |
| 1436 | + crate::asyncrt::select_biased! { | |
| 1437 | + "a registry notification wins a deadline tie so the next sweep uses the refreshed deadline"; | |
| 1438 | + _ = notified => {} | |
| 1439 | + _ = sleep => {} | |
| 1440 | + } | |
| 1441 | + } | |
| 1442 | + } | |
| 1443 | + } | |
| 1444 | +} | |
| 1445 | + | |
| 1446 | +#[derive(Clone, Copy)] | |
| 1447 | +pub(crate) enum HttpStreamActivityKind { | |
| 1448 | + Write, | |
| 1449 | + Close, | |
| 1450 | +} | |
| 1451 | + | |
| 1452 | +#[derive(Clone, Copy)] | |
| 1453 | +pub(crate) enum HttpStreamActivityError { | |
| 1454 | + Closed, | |
| 1455 | + Gone, | |
| 1456 | + Closing, | |
| 1457 | +} | |
| 1458 | + | |
| 1459 | +impl HttpStreamActivityError { | |
| 1460 | + pub(crate) fn write_message(self) -> &'static str { | |
| 1461 | + match self { | |
| 1462 | + Self::Closed => HTTP_STREAM_REGISTRATION_CLOSED, | |
| 1463 | + Self::Gone | Self::Closing => RESPONSE_STREAM_CONSUMER_CANCELED, | |
| 1464 | + } | |
| 1465 | + } | |
| 1466 | +} | |
| 1467 | + | |
| 1468 | +struct HttpStreamActivityLease { | |
| 1469 | + service: Arc<HttpStreamService>, | |
| 1470 | + stream_id: u64, | |
| 1471 | + generation: u64, | |
| 1472 | + kind: HttpStreamActivityKind, | |
| 1473 | + active: bool, | |
| 1474 | +} | |
| 1475 | + | |
| 1476 | +pub(crate) struct HttpStreamActivity { | |
| 1477 | + writer: tokio::sync::mpsc::Sender<Result<Vec<u8>, String>>, | |
| 1478 | + finished: tokio::sync::watch::Sender<bool>, | |
| 1479 | + lease: HttpStreamActivityLease, | |
| 1480 | +} | |
| 1481 | + | |
| 1482 | +impl HttpStreamActivityLease { | |
| 1483 | + fn succeed(mut self, remove_writer: bool) { | |
| 1484 | + self.active = false; | |
| 1485 | + self.service | |
| 1486 | + .finish_activity(self.stream_id, self.generation, self.kind, remove_writer); | |
| 1487 | + } | |
| 1488 | + | |
| 1489 | + fn cancel_pair(mut self) { | |
| 1490 | + self.active = false; | |
| 1491 | + self.service | |
| 1492 | + .cancel_activity_pair(self.stream_id, self.generation, self.kind); | |
| 1493 | + } | |
| 1494 | +} | |
| 1495 | + | |
| 1496 | +impl Drop for HttpStreamActivityLease { | |
| 1497 | + fn drop(&mut self) { | |
| 1498 | + if self.active { | |
| 1499 | + self.service | |
| 1500 | + .abandon_activity(self.stream_id, self.generation, self.kind); | |
| 1501 | + } | |
| 1502 | + } | |
| 1503 | +} | |
| 1504 | + | |
| 1505 | +pub(crate) struct HttpSourceLease { | |
| 1506 | + service: Arc<HttpStreamService>, | |
| 1507 | + stream_id: u64, | |
| 1508 | + generation: u64, | |
| 1509 | + token: u64, | |
| 1510 | + mode: HttpSourceLeaseMode, | |
| 1511 | + pub(crate) termination: Arc<HttpStreamTermination>, | |
| 1512 | + pub(crate) settled: bool, | |
| 1513 | +} | |
| 1514 | + | |
| 1515 | +struct HttpPull { | |
| 1516 | + // Struct fields drop in declaration order. Registry removal therefore | |
| 1517 | + // commits before an arbitrary checked-out source destructor can re-enter | |
| 1518 | + // the service or panic when a pending read future is abandoned. | |
| 1519 | + lease: HttpSourceLease, | |
| 1520 | + source: HttpStreamSource, | |
| 1521 | +} | |
| 1522 | + | |
| 1523 | +impl Drop for HttpSourceLease { | |
| 1524 | + fn drop(&mut self) { | |
| 1525 | + // A settled path already took its waiter while it still owned the | |
| 1526 | + // registry slot. Taking again here could clear a successor's waiter. | |
| 1527 | + if self.settled { | |
| 1528 | + return; | |
| 1529 | + } | |
| 1530 | + let waiter = self.termination.take_waiter(); | |
| 1531 | + self.service.cancel_lease(self); | |
| 1532 | + dispose_http_waiter_suppressing(waiter); | |
| 1533 | + } | |
| 1534 | +} | |
| 1535 | + | |
| 1536 | +struct HttpTransferLease { | |
| 1537 | + inner: Option<HttpSourceLease>, | |
| 1538 | +} | |
| 1539 | + | |
| 1540 | +impl HttpTransferLease { | |
| 1541 | + fn new(lease: HttpSourceLease) -> Self { | |
| 1542 | + debug_assert_eq!(lease.mode, HttpSourceLeaseMode::Transfer); | |
| 1543 | + Self { inner: Some(lease) } | |
| 1544 | + } | |
| 1545 | + | |
| 1546 | + fn termination(&self) -> &HttpStreamTermination { | |
| 1547 | + &self.inner.as_ref().unwrap().termination | |
| 1548 | + } | |
| 1549 | + | |
| 1550 | + fn stream_id(&self) -> u64 { | |
| 1551 | + self.inner.as_ref().unwrap().stream_id | |
| 1552 | + } | |
| 1553 | + | |
| 1554 | + fn successful_activity(&self) -> Result<(), HttpStreamTerminationReason> { | |
| 1555 | + let lease = self.inner.as_ref().unwrap(); | |
| 1556 | + let result = lease.service.transferred_activity( | |
| 1557 | + lease.stream_id, | |
| 1558 | + lease.generation, | |
| 1559 | + lease.token, | |
| 1560 | + &lease.termination, | |
| 1561 | + ); | |
| 1562 | + dispose_http_waiter_suppressing(lease.termination.take_waiter()); | |
| 1563 | + result | |
| 1564 | + } | |
| 1565 | + | |
| 1566 | + fn finish( | |
| 1567 | + &mut self, | |
| 1568 | + requested_reason: HttpStreamTerminationReason, | |
| 1569 | + ) -> HttpStreamTerminationReason { | |
| 1570 | + let mut lease = self.inner.take().unwrap(); | |
| 1571 | + lease.settled = true; | |
| 1572 | + let waiter = lease.termination.take_waiter(); | |
| 1573 | + let winning_reason = lease.service.finish_lease( | |
| 1574 | + lease.stream_id, | |
| 1575 | + lease.generation, | |
| 1576 | + lease.token, | |
| 1577 | + lease.mode, | |
| 1578 | + &lease.termination, | |
| 1579 | + requested_reason, | |
| 1580 | + ); | |
| 1581 | + dispose_http_waiter_suppressing(waiter); | |
| 1582 | + winning_reason | |
| 1583 | + } | |
| 1584 | +} | |
| 1585 | + | |
| 1586 | +pub(crate) struct HttpTransferredStream { | |
| 1587 | + // The lease drops first, so registry cancellation commits before an | |
| 1588 | + // arbitrary source destructor can re-enter the service or panic. | |
| 1589 | + lease: HttpTransferLease, | |
| 1590 | + inner: HttpChunkStream, | |
| 1591 | + finished: bool, | |
| 1592 | +} | |
| 1593 | + | |
| 1594 | +enum HttpTransferredEvent { | |
| 1595 | + Chunk(Vec<u8>), | |
| 1596 | + Error(String), | |
| 1597 | + End, | |
| 1598 | + Terminated(HttpStreamTerminationReason), | |
| 1599 | +} | |
| 1600 | + | |
| 1601 | +fn transferred_termination_poll( | |
| 1602 | + stream_id: u64, | |
| 1603 | + reason: HttpStreamTerminationReason, | |
| 1604 | +) -> std::task::Poll<Option<Result<Vec<u8>, String>>> { | |
| 1605 | + match HttpStreamService::termination_result(stream_id, reason) { | |
| 1606 | + Ok(None) => std::task::Poll::Ready(None), | |
| 1607 | + Ok(Some(bytes)) => std::task::Poll::Ready(Some(Ok(bytes))), | |
| 1608 | + Err(error) => std::task::Poll::Ready(Some(Err(error))), | |
| 1609 | + } | |
| 1610 | +} | |
| 1611 | + | |
| 1612 | +impl HttpTransferredStream { | |
| 1613 | + fn termination_handle(&self) -> Arc<HttpStreamTermination> { | |
| 1614 | + self.lease.inner.as_ref().unwrap().termination.clone() | |
| 1615 | + } | |
| 1616 | + | |
| 1617 | + /// Poll the transferred source without committing a natural terminal | |
| 1618 | + /// event. A direct consumer commits immediately in `poll_next`. The tee | |
| 1619 | + /// pump keeps the lease live until it publishes an error to each live | |
| 1620 | + /// branch, so cancellation can interrupt a backpressured terminal send. | |
| 1621 | + fn poll_event( | |
| 1622 | + &mut self, | |
| 1623 | + context: &mut std::task::Context<'_>, | |
| 1624 | + ) -> std::task::Poll<HttpTransferredEvent> { | |
| 1625 | + debug_assert!(!self.finished); | |
| 1626 | + if let std::task::Poll::Ready(reason) = self.lease.termination().poll_reason(context) { | |
| 1627 | + return std::task::Poll::Ready(HttpTransferredEvent::Terminated(reason)); | |
| 1628 | + } | |
| 1629 | + match self.inner.as_mut().poll_next(context) { | |
| 1630 | + std::task::Poll::Ready(Some(Ok(bytes))) => match self.lease.successful_activity() { | |
| 1631 | + Ok(()) => std::task::Poll::Ready(HttpTransferredEvent::Chunk(bytes)), | |
| 1632 | + Err(reason) => std::task::Poll::Ready(HttpTransferredEvent::Terminated(reason)), | |
| 1633 | + }, | |
| 1634 | + std::task::Poll::Ready(Some(Err(error))) => { | |
| 1635 | + std::task::Poll::Ready(HttpTransferredEvent::Error(error)) | |
| 1636 | + } | |
| 1637 | + std::task::Poll::Ready(None) => std::task::Poll::Ready(HttpTransferredEvent::End), | |
| 1638 | + std::task::Poll::Pending => match self.lease.termination().poll_reason(context) { | |
| 1639 | + std::task::Poll::Ready(reason) => { | |
| 1640 | + std::task::Poll::Ready(HttpTransferredEvent::Terminated(reason)) | |
| 1641 | + } | |
| 1642 | + std::task::Poll::Pending => std::task::Poll::Pending, | |
| 1643 | + }, | |
| 1644 | + } | |
| 1645 | + } | |
| 1646 | + | |
| 1647 | + fn finish( | |
| 1648 | + &mut self, | |
| 1649 | + requested_reason: HttpStreamTerminationReason, | |
| 1650 | + ) -> HttpStreamTerminationReason { | |
| 1651 | + let winning_reason = self.lease.finish(requested_reason); | |
| 1652 | + self.finished = true; | |
| 1653 | + winning_reason | |
| 1654 | + } | |
| 1655 | + | |
| 1656 | + fn finish_poll( | |
| 1657 | + &mut self, | |
| 1658 | + requested_reason: HttpStreamTerminationReason, | |
| 1659 | + ) -> std::task::Poll<Option<Result<Vec<u8>, String>>> { | |
| 1660 | + let stream_id = self.lease.stream_id(); | |
| 1661 | + let winning_reason = self.finish(requested_reason); | |
| 1662 | + transferred_termination_poll(stream_id, winning_reason) | |
| 1663 | + } | |
| 1664 | +} | |
| 1665 | + | |
| 1666 | +impl futures_util::Stream for HttpTransferredStream { | |
| 1667 | + type Item = Result<Vec<u8>, String>; | |
| 1668 | + | |
| 1669 | + fn poll_next( | |
| 1670 | + mut self: Pin<&mut Self>, | |
| 1671 | + context: &mut std::task::Context<'_>, | |
| 1672 | + ) -> std::task::Poll<Option<Self::Item>> { | |
| 1673 | + if self.finished { | |
| 1674 | + return std::task::Poll::Ready(None); | |
| 1675 | + } | |
| 1676 | + let this = self.as_mut().get_mut(); | |
| 1677 | + match this.poll_event(context) { | |
| 1678 | + std::task::Poll::Ready(HttpTransferredEvent::Chunk(bytes)) => { | |
| 1679 | + std::task::Poll::Ready(Some(Ok(bytes))) | |
| 1680 | + } | |
| 1681 | + std::task::Poll::Ready(HttpTransferredEvent::Error(error)) => { | |
| 1682 | + let stream_id = this.lease.stream_id(); | |
| 1683 | + let winning_reason = this.finish(HttpStreamTerminationReason::Finished); | |
| 1684 | + if winning_reason == HttpStreamTerminationReason::Finished { | |
| 1685 | + std::task::Poll::Ready(Some(Err(error))) | |
| 1686 | + } else { | |
| 1687 | + transferred_termination_poll(stream_id, winning_reason) | |
| 1688 | + } | |
| 1689 | + } | |
| 1690 | + std::task::Poll::Ready(HttpTransferredEvent::End) => { | |
| 1691 | + this.finish_poll(HttpStreamTerminationReason::Finished) | |
| 1692 | + } | |
| 1693 | + std::task::Poll::Ready(HttpTransferredEvent::Terminated(reason)) => { | |
| 1694 | + this.finish_poll(reason) | |
| 1695 | + } | |
| 1696 | + std::task::Poll::Pending => std::task::Poll::Pending, | |
| 1697 | + } | |
| 1698 | + } | |
| 1699 | +} | |
| 1700 | + | |
| 1701 | +pub(crate) struct HttpStreamClaim { | |
| 1702 | + pub(crate) service: Arc<HttpStreamService>, | |
| 1703 | + stream_id: u64, | |
| 1704 | + generation: u64, | |
| 1705 | + armed: bool, | |
| 1706 | +} | |
| 1707 | + | |
| 1708 | +impl HttpStreamClaim { | |
| 1709 | + fn take_source(mut self) -> Result<HttpChunkStream, String> { | |
| 1710 | + let source = self | |
| 1711 | + .service | |
| 1712 | + .checkout_transfer(self.stream_id, Some(self.generation)); | |
| 1713 | + if source.is_ok() { | |
| 1714 | + self.armed = false; | |
| 1715 | + } | |
| 1716 | + source.map(|source| Box::pin(source) as HttpChunkStream) | |
| 1717 | + } | |
| 1718 | +} | |
| 1719 | + | |
| 1720 | +impl Drop for HttpStreamClaim { | |
| 1721 | + fn drop(&mut self) { | |
| 1722 | + if self.armed { | |
| 1723 | + self.armed = false; | |
| 1724 | + let service = self.service.clone(); | |
| 1725 | + let stream_id = self.stream_id; | |
| 1726 | + let generation = self.generation; | |
| 1727 | + run_http_cleanup_from_drop(move || { | |
| 1728 | + service.release_claim(stream_id, generation); | |
| 1729 | + }); | |
| 1730 | + } | |
| 1731 | + } | |
| 1732 | +} | |
| 1733 | + | |
| 1734 | +pub(crate) fn http_stream_service() -> Arc<HttpStreamService> { | |
| 1735 | + asyncrt::runtime_services().http_streams() | |
| 1736 | +} | |
| 1737 | + | |
| 1738 | +fn register_http_stream(source: HttpStreamSource) -> Option<u64> { | |
| 1739 | + http_stream_service().register_source(source) | |
| 1740 | +} | |
| 1741 | + | |
| 1742 | +pub(crate) fn claim_http_stream(stream_id: u64) -> Option<HttpStreamClaim> { | |
| 1743 | + http_stream_service().claim(stream_id) | |
| 1744 | +} | |
| 1745 | + | |
| 1746 | +/// Encode a host response for the JS side. A text body crosses as a | |
| 1747 | +/// JS string (cheap, lossless), binary as a byte array, and a streaming body | |
| 1748 | +/// by id — serializing a Vec<u8> as a JSON number array is the dominant cost | |
| 1749 | +/// for real DO responses. `ws_target` is carried by the paths that can answer | |
| 1750 | +/// with a WebSocket upgrade: a Durable Object call and a service-binding call. | |
| 1751 | +pub(crate) fn encode_http_response( | |
| 1752 | + mut response: HttpResponse, | |
| 1753 | + ws_target: bool, | |
| 1754 | + stream_service: &Arc<HttpStreamService>, | |
| 1755 | +) -> Result<String, String> { | |
| 1756 | + let mut obj = serde_json::json!({ | |
| 1757 | + "status": response.status, | |
| 1758 | + "headers": response.headers, | |
| 1759 | + }); | |
| 1760 | + if ws_target { | |
| 1761 | + let target = match response.websocket.as_ref() { | |
| 1762 | + Some(HttpResponseWebSocket::Cell(target)) => Some(target), | |
| 1763 | + _ => None, | |
| 1764 | + }; | |
| 1765 | + obj["wsTarget"] = serde_json::json!(target); | |
| 1766 | + } | |
| 1767 | + if let Some(stream) = response.stream.take() { | |
| 1768 | + let Some(stream_id) = stream_service.register_source(HttpStreamSource::Stream(stream)) | |
| 1769 | + else { | |
| 1770 | + return Err(HTTP_STREAM_REGISTRATION_CLOSED.into()); | |
| 1771 | + }; | |
| 1772 | + obj["streamId"] = serde_json::json!(stream_id); | |
| 1773 | + } else { | |
| 1774 | + match std::str::from_utf8(&response.body) { | |
| 1775 | + Ok(text) => obj["body"] = serde_json::Value::String(text.into()), | |
| 1776 | + Err(_) => obj["bodyBytes"] = serde_json::json!(response.body), | |
| 1777 | + } | |
| 1778 | + } | |
| 1779 | + Ok(obj.to_string()) | |
| 1780 | +} | |
| 1781 | + | |
| 1782 | +/// Reclaims a streamed request body if a host dispatch fails before the | |
| 1783 | +/// target installs a request context. A successful dispatch disarms this | |
| 1784 | +/// fallback because the target context then owns the unread tail. | |
| 1785 | +pub struct RequestBodyGuard(pub(crate) Option<HttpStreamClaim>); | |
| 1786 | + | |
| 1787 | +impl RequestBodyGuard { | |
| 1788 | + pub fn of(body: &RequestBody) -> Self { | |
| 1789 | + Self(body.stream_id().and_then(claim_http_stream)) | |
| 1790 | + } | |
| 1791 | + | |
| 1792 | + pub(crate) fn transferred(claim: HttpStreamClaim) -> Self { | |
| 1793 | + Self(Some(claim)) | |
| 1794 | + } | |
| 1795 | + | |
| 1796 | + pub fn disarm(&mut self) { | |
| 1797 | + drop(self.0.take()); | |
| 1798 | + } | |
| 1799 | + | |
| 1800 | + pub(crate) fn take_stream(&mut self, stream_id: u64) -> Result<HttpChunkStream, String> { | |
| 1801 | + let Some(claim) = self.0.take() else { | |
| 1802 | + return Err(format!("body stream {stream_id} is not registered")); | |
| 1803 | + }; | |
| 1804 | + if claim.stream_id != stream_id { | |
| 1805 | + let claimed = claim.stream_id; | |
| 1806 | + self.0 = Some(claim); | |
| 1807 | + return Err(format!( | |
| 1808 | + "body stream {stream_id} does not match ownership claim {claimed}" | |
| 1809 | + )); | |
| 1810 | + } | |
| 1811 | + claim.take_source() | |
| 1812 | + } | |
| 1813 | +} | |
| 1814 | + | |
| 1815 | +impl Drop for RequestBodyGuard { | |
| 1816 | + fn drop(&mut self) { | |
| 1817 | + let claim = self.0.take(); | |
| 1818 | + run_http_cleanup_from_drop(|| drop(claim)); | |
| 1819 | + } | |
| 1820 | +} | |
| 1821 | + | |
| 1822 | +/// Take exclusive ownership of a registered request source. | |
| 1823 | +/// | |
| 1824 | +/// The returned stream removes the registry hop, so its eventual consumer | |
| 1825 | +/// supplies the backpressure and dropping that consumer cancels the source. | |
| 1826 | +pub fn take_body_stream(stream_id: u64) -> Result<HttpChunkStream, String> { | |
| 1827 | + http_stream_service() | |
| 1828 | + .checkout_transfer(stream_id, None) | |
| 1829 | + .map(|source| Box::pin(source) as HttpChunkStream) | |
| 1830 | +} | |
| 1831 | + | |
| 1832 | +pub(crate) async fn next_http_stream_chunk( | |
| 1833 | + source: &mut HttpStreamSource, | |
| 1834 | +) -> Result<Option<Vec<u8>>, String> { | |
| 1835 | + match source { | |
| 1836 | + HttpStreamSource::Response(response) => response | |
| 1837 | + .chunk() | |
| 1838 | + .await | |
| 1839 | + .map(|chunk| chunk.map(|bytes| bytes.to_vec())) | |
| 1840 | + .map_err(|error| format!("response stream: {error}")), | |
| 1841 | + HttpStreamSource::Receiver(receiver) => match receiver.recv().await { | |
| 1842 | + Some(Ok(bytes)) => Ok(Some(bytes)), | |
| 1843 | + Some(Err(error)) => Err(error), | |
| 1844 | + None => Ok(None), | |
| 1845 | + }, | |
| 1846 | + HttpStreamSource::Stream(stream) => stream.next().await.transpose(), | |
| 1847 | + } | |
| 1848 | +} | |
| 1849 | + | |
| 1850 | +pub(crate) fn settle_http_stream_read( | |
| 1851 | + mut lease: HttpSourceLease, | |
| 1852 | + source: HttpStreamSource, | |
| 1853 | + next: Option<Result<Option<Vec<u8>>, String>>, | |
| 1854 | +) -> Result<Option<Vec<u8>>, String> { | |
| 1855 | + lease.settled = true; | |
| 1856 | + let service = lease.service.clone(); | |
| 1857 | + let result = next.unwrap_or_else(|| { | |
| 1858 | + HttpStreamService::termination_result(lease.stream_id, lease.termination.reason()) | |
| 1859 | + }); | |
| 1860 | + service.complete_pull(&lease, source, result) | |
| 1861 | +} | |
| 1862 | + | |
| 1863 | +/// Build the future used by the JavaScript read op. | |
| 1864 | +/// | |
| 1865 | +/// Checkout stays synchronous because the op reserves the source before it | |
| 1866 | +/// enqueues asynchronous work. Internal tests call this constructor so they | |
| 1867 | +/// exercise the same checkout and completion transitions as the op. | |
| 1868 | +pub(crate) fn http_stream_read( | |
| 1869 | + service: Arc<HttpStreamService>, | |
| 1870 | + stream_id: u64, | |
| 1871 | +) -> impl std::future::Future<Output = Result<Option<Vec<u8>>, String>> + Send + 'static { | |
| 1872 | + let checkout = service.checkout_source(stream_id); | |
| 1873 | + async move { | |
| 1874 | + let (lease, source) = checkout?; | |
| 1875 | + let mut pull = HttpPull { lease, source }; | |
| 1876 | + let termination = pull.lease.termination.clone(); | |
| 1877 | + let next = crate::asyncrt::select! { | |
| 1878 | + result = next_http_stream_chunk(&mut pull.source) => Some(result), | |
| 1879 | + _ = futures_util::future::poll_fn(|context| termination.poll_reason(context)) => None, | |
| 1880 | + }; | |
| 1881 | + let HttpPull { lease, source } = pull; | |
| 1882 | + settle_http_stream_read(lease, source, next) | |
| 1883 | + } | |
| 1884 | +} | |
| 1885 | + | |
| 1886 | +#[cfg(all(test, celld_internal_tests))] | |
| 1887 | +pub(crate) fn http_stream_read_source_first_for_test( | |
| 1888 | + service: Arc<HttpStreamService>, | |
| 1889 | + stream_id: u64, | |
| 1890 | +) -> impl std::future::Future<Output = Result<Option<Vec<u8>>, String>> + Send + 'static { | |
| 1891 | + let checkout = service.checkout_source(stream_id); | |
| 1892 | + async move { | |
| 1893 | + let (lease, source) = checkout?; | |
| 1894 | + let mut pull = HttpPull { lease, source }; | |
| 1895 | + let termination = pull.lease.termination.clone(); | |
| 1896 | + let next = crate::asyncrt::select_biased! { | |
| 1897 | + "the source-first test probe makes a ready source win a termination tie"; | |
| 1898 | + result = next_http_stream_chunk(&mut pull.source) => Some(result), | |
| 1899 | + _ = futures_util::future::poll_fn(|context| termination.poll_reason(context)) => None, | |
| 1900 | + }; | |
| 1901 | + let HttpPull { lease, source } = pull; | |
| 1902 | + settle_http_stream_read(lease, source, next) | |
| 1903 | + } | |
| 1904 | +} | |
| 1905 | + | |
| 1906 | +pub(crate) async fn response_stream_write( | |
| 1907 | + service: Arc<HttpStreamService>, | |
| 1908 | + stream_id: u64, | |
| 1909 | + bytes: Option<Vec<u8>>, | |
| 1910 | +) -> Result<(), String> { | |
| 1911 | + let Some(bytes) = bytes else { | |
| 1912 | + return Err("response stream chunks must be ArrayBuffer views".into()); | |
| 1913 | + }; | |
| 1914 | + // Acquire on the first poll. Merely constructing and dropping this | |
| 1915 | + // future cannot read the Domain clock or create transient activity. | |
| 1916 | + let activity = service | |
| 1917 | + .begin_activity(stream_id, HttpStreamActivityKind::Write) | |
| 1918 | + .map_err(|error| error.write_message().to_string())?; | |
| 1919 | + if activity.writer.send(Ok(bytes)).await.is_err() { | |
| 1920 | + activity.lease.cancel_pair(); | |
| 1921 | + return Err(RESPONSE_STREAM_CONSUMER_CANCELED.into()); | |
| 1922 | + } | |
| 1923 | + activity.lease.succeed(false); | |
| 1924 | + Ok(()) | |
| 1925 | +} | |
| 1926 | + | |
| 1927 | +pub(crate) async fn response_stream_close( | |
| 1928 | + service: Arc<HttpStreamService>, | |
| 1929 | + stream_id: u64, | |
| 1930 | + error: String, | |
| 1931 | +) -> Result<(), String> { | |
| 1932 | + // Missing and expired writers preserve the producer harness's | |
| 1933 | + // idempotent close contract. A live close reservation is different: a | |
| 1934 | + // second terminal operation must not race the first one. | |
| 1935 | + let activity = match service.begin_activity(stream_id, HttpStreamActivityKind::Close) { | |
| 1936 | + Ok(activity) => activity, | |
| 1937 | + Err(HttpStreamActivityError::Closed) => return Err(HTTP_STREAM_REGISTRATION_CLOSED.into()), | |
| 1938 | + Err(HttpStreamActivityError::Gone) => return Ok(()), | |
| 1939 | + Err(HttpStreamActivityError::Closing) => { | |
| 1940 | + return Err(RESPONSE_STREAM_CLOSE_IN_PROGRESS.into()) | |
| 1941 | + } | |
| 1942 | + }; | |
| 1943 | + if error.is_empty() { | |
| 1944 | + let _ = activity.finished.send(true); | |
| 1945 | + } else { | |
| 1946 | + if activity.writer.send(Err(error)).await.is_err() { | |
| 1947 | + activity.lease.cancel_pair(); | |
| 1948 | + return Ok(()); | |
| 1949 | + } | |
| 1950 | + // A cancelled backpressured close must leave the producer watch | |
| 1951 | + // open. Publish completion only after the terminal item is queued. | |
| 1952 | + let _ = activity.finished.send(true); | |
| 1953 | + } | |
| 1954 | + activity.lease.succeed(true); | |
| 1955 | + Ok(()) | |
| 1956 | +} | |
| 1957 | + | |
| 1958 | +/// Move a host response source into a directly-polled stream. No pump task is | |
| 1959 | +/// needed: the eventual HTTP or JS consumer supplies the backpressure. | |
| 1960 | +fn http_chunk_stream(source: HttpStreamSource) -> HttpChunkStream { | |
| 1961 | + match source { | |
| 1962 | + HttpStreamSource::Response(response) => Box::pin(response.bytes_stream().map(|chunk| { | |
| 1963 | + chunk | |
| 1964 | + .map(|bytes| bytes.to_vec()) | |
| 1965 | + .map_err(|error| format!("response stream: {error}")) | |
| 1966 | + })), | |
| 1967 | + HttpStreamSource::Receiver(receiver) => { | |
| 1968 | + Box::pin(tokio_stream::wrappers::ReceiverStream::new(receiver)) | |
| 1969 | + } | |
| 1970 | + HttpStreamSource::Stream(stream) => stream, | |
| 1971 | + } | |
| 1972 | +} | |
| 1973 | + | |
| 1974 | +/// Host-native tee for an outbound response. Both branches are represented by | |
| 1975 | +/// stream IDs, so one can be returned through Axum while JS independently | |
| 1976 | +/// scans the other for observability or usage accounting. | |
| 1977 | +pub(crate) type HttpTeePump = Pin<Box<dyn std::future::Future<Output = ()> + Send>>; | |
| 1978 | + | |
| 1979 | +#[derive(Clone, Copy, Debug, Eq, PartialEq)] | |
| 1980 | +enum HttpTeeSendOutcome { | |
| 1981 | + Sent, | |
| 1982 | + BranchClosed, | |
| 1983 | + SourceTerminated, | |
| 1984 | +} | |
| 1985 | + | |
| 1986 | +async fn reserve_http_tee_send( | |
| 1987 | + sender: &tokio::sync::mpsc::Sender<Result<Vec<u8>, String>>, | |
| 1988 | + item: Result<Vec<u8>, String>, | |
| 1989 | + termination: &HttpStreamTermination, | |
| 1990 | +) -> HttpTeeSendOutcome { | |
| 1991 | + // Sender::send enqueues before it resolves, so a select cannot retract a | |
| 1992 | + // value after cancellation wins. Reserve capacity first, then recheck the | |
| 1993 | + // committed source reason before the permit makes the value visible. | |
| 1994 | + let reservation = asyncrt::select_biased! { | |
| 1995 | + "a capacity reservation wins a tie because termination is rechecked before the send"; | |
| 1996 | + reservation = sender.reserve() => Some(reservation), | |
| 1997 | + _ = futures_util::future::poll_fn(|context| termination.poll_reason(context)) => None, | |
| 1998 | + }; | |
| 1999 | + if termination.reason() != HttpStreamTerminationReason::Live { | |
| 2000 | + return HttpTeeSendOutcome::SourceTerminated; | |
| 2001 | + } | |
| 2002 | + match reservation { | |
| 2003 | + Some(Ok(permit)) => { | |
| 2004 | + permit.send(item); | |
| 2005 | + HttpTeeSendOutcome::Sent | |
| 2006 | + } | |
| 2007 | + Some(Err(_)) => HttpTeeSendOutcome::BranchClosed, | |
| 2008 | + None => HttpTeeSendOutcome::SourceTerminated, | |
| 2009 | + } | |
| 2010 | +} | |
| 2011 | + | |
| 2012 | +async fn fan_out_http_tee_item( | |
| 2013 | + tx1: &tokio::sync::mpsc::Sender<Result<Vec<u8>, String>>, | |
| 2014 | + tx2: &tokio::sync::mpsc::Sender<Result<Vec<u8>, String>>, | |
| 2015 | + item: Result<Vec<u8>, String>, | |
| 2016 | + termination: &HttpStreamTermination, | |
| 2017 | +) -> Option<(bool, bool)> { | |
| 2018 | + let first = reserve_http_tee_send(tx1, item.clone(), termination).await; | |
| 2019 | + if first == HttpTeeSendOutcome::SourceTerminated { | |
| 2020 | + return None; | |
| 2021 | + } | |
| 2022 | + let second = reserve_http_tee_send(tx2, item, termination).await; | |
| 2023 | + if second == HttpTeeSendOutcome::SourceTerminated { | |
| 2024 | + return None; | |
| 2025 | + } | |
| 2026 | + Some(( | |
| 2027 | + first == HttpTeeSendOutcome::Sent, | |
| 2028 | + second == HttpTeeSendOutcome::Sent, | |
| 2029 | + )) | |
| 2030 | +} | |
| 2031 | + | |
| 2032 | +async fn both_http_tee_receivers_closed( | |
| 2033 | + tx1: &tokio::sync::mpsc::Sender<Result<Vec<u8>, String>>, | |
| 2034 | + tx2: &tokio::sync::mpsc::Sender<Result<Vec<u8>, String>>, | |
| 2035 | +) { | |
| 2036 | + tx1.closed().await; | |
| 2037 | + tx2.closed().await; | |
| 2038 | +} | |
| 2039 | + | |
| 2040 | +pub(crate) fn prepare_http_stream_tee( | |
| 2041 | + service: &Arc<HttpStreamService>, | |
| 2042 | + mut source: HttpTransferredStream, | |
| 2043 | +) -> Result<((u64, u64), HttpTeePump), &'static str> { | |
| 2044 | + let (tx1, rx1) = tokio::sync::mpsc::channel(HTTP_TEE_BRANCH_CAPACITY); | |
| 2045 | + let (tx2, rx2) = tokio::sync::mpsc::channel(HTTP_TEE_BRANCH_CAPACITY); | |
| 2046 | + let Some(id1) = service.register_source(HttpStreamSource::Receiver(rx1)) else { | |
| 2047 | + return Err(HTTP_STREAM_REGISTRATION_CLOSED); | |
| 2048 | + }; | |
| 2049 | + let Some(id2) = service.register_source(HttpStreamSource::Receiver(rx2)) else { | |
| 2050 | + service.cancel_source(id1); | |
| 2051 | + return Err(HTTP_STREAM_REGISTRATION_CLOSED); | |
| 2052 | + }; | |
| 2053 | + let termination = source.termination_handle(); | |
| 2054 | + let pump = Box::pin(async move { | |
| 2055 | + loop { | |
| 2056 | + // A permanently pending source does not wake when its consumers | |
| 2057 | + // disappear. Observe both receivers in the same poll, and prefer | |
| 2058 | + // their committed closure when the source is also ready. | |
| 2059 | + let event = asyncrt::select_biased! { | |
| 2060 | + "closed tee consumers win a tie so the pump cannot read another source item"; | |
| 2061 | + _ = both_http_tee_receivers_closed(&tx1, &tx2) => None, | |
| 2062 | + event = futures_util::future::poll_fn(|context| source.poll_event(context)) => Some(event), | |
| 2063 | + }; | |
| 2064 | + let Some(event) = event else { | |
| 2065 | + break; | |
| 2066 | + }; | |
| 2067 | + match event { | |
| 2068 | + HttpTransferredEvent::Chunk(bytes) => { | |
| 2069 | + let Some((first, second)) = | |
| 2070 | + fan_out_http_tee_item(&tx1, &tx2, Ok(bytes), &termination).await | |
| 2071 | + else { | |
| 2072 | + break; | |
| 2073 | + }; | |
| 2074 | + if !first && !second { | |
| 2075 | + break; | |
| 2076 | + } | |
| 2077 | + } | |
| 2078 | + HttpTransferredEvent::Error(error) => { | |
| 2079 | + if fan_out_http_tee_item(&tx1, &tx2, Err(error), &termination) | |
| 2080 | + .await | |
| 2081 | + .is_some() | |
| 2082 | + { | |
| 2083 | + source.finish(HttpStreamTerminationReason::Finished); | |
| 2084 | + } | |
| 2085 | + break; | |
| 2086 | + } | |
| 2087 | + HttpTransferredEvent::End => { | |
| 2088 | + source.finish(HttpStreamTerminationReason::Finished); | |
| 2089 | + break; | |
| 2090 | + } | |
| 2091 | + HttpTransferredEvent::Terminated(_) => break, | |
| 2092 | + } | |
| 2093 | + } | |
| 2094 | + }); | |
| 2095 | + Ok(((id1, id2), pump)) | |
| 2096 | +} | |
| 2097 | + | |
| 2098 | +/// Hand a request body to the isolate as a stream rather than as bytes. | |
| 2099 | +/// The returned id names the stream for `__http_stream_read`, so the | |
| 2100 | +/// Worker pulls each chunk off the socket as it asks for it and the host | |
| 2101 | +/// never holds the whole body. | |
| 2102 | +pub fn register_body_stream(stream: HttpChunkStream) -> Result<u64, String> { | |
| 2103 | + register_http_stream(HttpStreamSource::Stream(stream)) | |
| 2104 | + .ok_or_else(|| HTTP_STREAM_REGISTRATION_CLOSED.to_string()) | |
| 2105 | +} |
modifiedcrates/celld/js.rs+0−0View file
This diff is too large to display.
modifiedcrates/celld/js/bootstrap.rs+32−263View file
| @@ -118,8 +118,12 @@ | ||
| 118 | 118 | // isolate-local; this shares only the original source buffer. |
| 119 | 119 | #[cfg(any(not(celld_internal_tests), all(test, celld_internal_tests)))] |
| 120 | 120 | static HARNESS_SOURCE: v8::OneByteConst = |
| 121 | - v8::String::create_external_onebyte_const(include_bytes!("harness.js")); | |
| 121 | + v8::String::create_external_onebyte_const(HARNESS.as_bytes()); | |
| 122 | 122 | |
| 123 | +/// The harness and the services it shares with the workerd engine, which | |
| 124 | +/// each end in a function declaration the harness calls. | |
| 125 | +const HARNESS: &str = concat!(include_str!("harness.js"), include_str!("services/kv.js")); | |
| 126 | + | |
| 123 | 127 | fn bootstrap_code_cache() -> &'static std::sync::Mutex<BootstrapCache> { |
| 124 | 128 | static CACHE: std::sync::OnceLock<std::sync::Mutex<BootstrapCache>> = |
| 125 | 129 | std::sync::OnceLock::new(); |
| @@ -260,7 +264,7 @@ | ||
| 260 | 264 | arguments: &InternalArguments<'s>, |
| 261 | 265 | ) -> Result<()> { |
| 262 | 266 | #[cfg(celld_internal_tests)] |
| 263 | - let harness = include_str!("harness.js") | |
| 267 | + let harness = HARNESS | |
| 264 | 268 | .replace( |
| 265 | 269 | "/*__CELLD_TEST_WORKFLOW_EVENT_CONSUMED__*/", |
| 266 | 270 | "__test_workflow_event_consumed();", |
| @@ -534,85 +538,16 @@ | ||
| 534 | 538 | /// Built through the V8 object API rather than by compiling a snippet, because |
| 535 | 539 | /// this runs on every isolate load. |
| 536 | 540 | pub(super) fn inject_kv_limits(scope: &mut v8::PinScope) -> Result<()> { |
| 537 | - use celld_logic::kv; | |
| 538 | 541 | let cell = cell_state(scope)?; |
| 539 | 542 | let limits = v8::Object::new(scope); |
| 540 | - let set = |scope: &mut v8::PinScope, name: &str, value: f64| { | |
| 543 | + let entries = crate::kv_blob::limits(); | |
| 544 | + for (name, value) in entries.as_object().expect("kv limits are an object") { | |
| 541 | 545 | let key = v8::String::new(scope, name).unwrap(); |
| 542 | - let value = v8::Number::new(scope, value); | |
| 543 | - limits.set(scope, key.into(), value.into()); | |
| 544 | - }; | |
| 545 | - set(scope, "maxKeyBytes", kv::MAX_KEY_BYTES as f64); | |
| 546 | - set(scope, "maxValueBytes", kv::MAX_VALUE_BYTES as f64); | |
| 547 | - set( | |
| 548 | - scope, | |
| 549 | - "maxInlineValueBytes", | |
| 550 | - kv::MAX_INLINE_VALUE_BYTES as f64, | |
| 551 | - ); | |
| 552 | - set(scope, "maxMetadataBytes", kv::MAX_METADATA_BYTES as f64); | |
| 553 | - set(scope, "maxBulkKeys", kv::MAX_BULK_KEYS as f64); | |
| 554 | - set(scope, "maxListLimit", kv::MAX_LIST_LIMIT as f64); | |
| 555 | - set( | |
| 556 | - scope, | |
| 557 | - "sweepBatchRows", | |
| 558 | - celld_logic::sweep::BATCH_ROWS as f64, | |
| 559 | - ); | |
| 560 | - // One variable for every KV test knob, not one variable each. | |
| 561 | - // | |
| 562 | - // CELLD_TEST_KV=no-sweep,fail-after-blob,min-ttl-ms=1000 | |
| 563 | - // | |
| 564 | - // These are test-only and they read the production environment rather than | |
| 565 | - // sitting behind `cfg(celld_internal_tests)`, because the code they steer | |
| 566 | - // is JavaScript in the harness and a cfg cannot reach it. | |
| 567 | - // | |
| 568 | - // What each is for, and why a test cannot do without it: | |
| 569 | - // | |
| 570 | - // - `min-ttl-ms` shortens upstream's sixty-second expiry floor, because a | |
| 571 | - // test cannot wait out a minute of wall clock. Nothing else about the | |
| 572 | - // deadline arithmetic changes. | |
| 573 | - // - `no-sweep` stops reclamation, so a test that means to pin the *read | |
| 574 | - // filter* can show the filter hid an expired key rather than the sweep | |
| 575 | - // having deleted the row underneath it. The first expiry test passed | |
| 576 | - // with the filter deleted until this existed. | |
| 577 | - // - `fail-after-blob` fails a put between the blob write and the row | |
| 578 | - // commit. That window is one await wide, and a SIGKILL there would take | |
| 579 | - // the assertion with it. | |
| 580 | - // - `race-sweep-put` holds a blob sweep after its mark snapshot until a | |
| 581 | - // new large put starts. The put and the sweep then overlap, so a test | |
| 582 | - // proves that collection authority is serialized with the put protocol. | |
| 583 | - // - `blob-sweep-ms` shortens the durable collector delay. A crash-orphan | |
| 584 | - // test must observe the wake without waiting one production minute. | |
| 585 | - // - `legacy-schema` creates the inline-only table from the first KV | |
| 586 | - // release, so the migration test proves an existing row survives. | |
| 587 | - let knobs = std::env::var("CELLD_TEST_KV").unwrap_or_default(); | |
| 588 | - let knob = |name: &str| -> Option<String> { | |
| 589 | - knobs.split(',').map(str::trim).find_map(|entry| { | |
| 590 | - let rest = entry.strip_prefix(name)?; | |
| 591 | - match rest { | |
| 592 | - "" => Some(String::new()), | |
| 593 | - rest => rest.strip_prefix('=').map(str::to_string), | |
| 594 | - } | |
| 595 | - }) | |
| 596 | - }; | |
| 597 | - let min_ttl = knob("min-ttl-ms") | |
| 598 | - .and_then(|value| value.parse::<i64>().ok()) | |
| 599 | - .filter(|ms| *ms > 0) | |
| 600 | - .unwrap_or(kv::MIN_EXPIRATION_TTL_MS); | |
| 601 | - set(scope, "minExpirationTtlMs", min_ttl as f64); | |
| 602 | - let blob_sweep_ms = knob("blob-sweep-ms") | |
| 603 | - .and_then(|value| value.parse::<i64>().ok()) | |
| 604 | - .filter(|ms| *ms > 0) | |
| 605 | - .unwrap_or(60_000); | |
| 606 | - set(scope, "blobSweepMs", blob_sweep_ms as f64); | |
| 607 | - for (name, present) in [ | |
| 608 | - ("sweepDisabled", knob("no-sweep").is_some()), | |
| 609 | - ("failAfterBlobWrite", knob("fail-after-blob").is_some()), | |
| 610 | - ("raceSweepPut", knob("race-sweep-put").is_some()), | |
| 611 | - ("legacySchema", knob("legacy-schema").is_some()), | |
| 612 | - ] { | |
| 613 | - let key = v8::String::new(scope, name).unwrap(); | |
| 614 | - let value = v8::Boolean::new(scope, present); | |
| 615 | - limits.set(scope, key.into(), value.into()); | |
| 546 | + let value: v8::Local<v8::Value> = match value { | |
| 547 | + serde_json::Value::Bool(flag) => v8::Boolean::new(scope, *flag).into(), | |
| 548 | + other => v8::Number::new(scope, other.as_f64().expect("kv limit")).into(), | |
| 549 | + }; | |
| 550 | + limits.set(scope, key.into(), value); | |
| 616 | 551 | } |
| 617 | 552 | let key = v8::String::new(scope, "kvLimits").unwrap(); |
| 618 | 553 | cell.set(scope, key.into(), limits.into()); |
| @@ -779,196 +714,21 @@ | ||
| 779 | 714 | Ok(()) |
| 780 | 715 | } |
| 781 | 716 | |
| 782 | -#[cfg(celld_internal_tests)] | |
| 783 | -thread_local! { | |
| 784 | - static QUEUE_LEASE_DURATION_FOR_TEST: std::cell::Cell<Option<i64>> = const { | |
| 785 | - std::cell::Cell::new(None) | |
| 786 | - }; | |
| 787 | - static QUEUE_BATCH_TIMEOUT_FOR_TEST: std::cell::Cell<Option<i64>> = const { | |
| 788 | - std::cell::Cell::new(None) | |
| 789 | - }; | |
| 790 | - static QUEUE_RETENTION_FOR_TEST: std::cell::Cell<Option<i64>> = const { | |
| 791 | - std::cell::Cell::new(None) | |
| 792 | - }; | |
| 793 | - static QUEUE_SWEEP_BATCH_FOR_TEST: std::cell::Cell<Option<usize>> = const { | |
| 794 | - std::cell::Cell::new(None) | |
| 795 | - }; | |
| 796 | -} | |
| 797 | - | |
| 798 | -/// Measure lease expiry without waiting through the production handler budget. | |
| 799 | -/// The override is thread-local because runtime tests build | |
| 800 | -/// unrelated Workers in parallel, and a process environment variable would | |
| 801 | -/// silently shorten their leases too. | |
| 802 | -#[cfg(celld_internal_tests)] | |
| 803 | -#[doc(hidden)] | |
| 804 | -pub fn set_queue_lease_duration_for_test(duration: Option<i64>) { | |
| 805 | - QUEUE_LEASE_DURATION_FOR_TEST.set(duration); | |
| 806 | -} | |
| 807 | - | |
| 808 | -#[cfg(celld_internal_tests)] | |
| 809 | -#[doc(hidden)] | |
| 810 | -pub fn set_queue_batch_timeout_for_test(duration: Option<i64>) { | |
| 811 | - QUEUE_BATCH_TIMEOUT_FOR_TEST.set(duration); | |
| 812 | -} | |
| 813 | - | |
| 814 | -#[cfg(celld_internal_tests)] | |
| 815 | -#[doc(hidden)] | |
| 816 | -pub fn set_queue_retention_for_test(duration: Option<i64>) { | |
| 817 | - QUEUE_RETENTION_FOR_TEST.set(duration); | |
| 818 | -} | |
| 819 | - | |
| 820 | -#[cfg(celld_internal_tests)] | |
| 821 | -pub fn set_queue_sweep_batch_for_test(rows: Option<usize>) { | |
| 822 | - QUEUE_SWEEP_BATCH_FOR_TEST.set(rows); | |
| 823 | -} | |
| 824 | - | |
| 825 | -#[cfg(celld_internal_tests)] | |
| 826 | -fn effective_queue_lease_duration(duration: i64) -> i64 { | |
| 827 | - QUEUE_LEASE_DURATION_FOR_TEST.get().unwrap_or(duration) | |
| 828 | -} | |
| 829 | - | |
| 830 | -#[cfg(not(celld_internal_tests))] | |
| 831 | -fn effective_queue_lease_duration(duration: i64) -> i64 { | |
| 832 | - duration | |
| 833 | -} | |
| 834 | - | |
| 835 | -#[cfg(celld_internal_tests)] | |
| 836 | -fn effective_queue_batch_timeout(duration: i64) -> i64 { | |
| 837 | - if duration == 0 { | |
| 838 | - 0 | |
| 839 | - } else { | |
| 840 | - QUEUE_BATCH_TIMEOUT_FOR_TEST.get().unwrap_or(duration) | |
| 841 | - } | |
| 842 | -} | |
| 843 | - | |
| 844 | -#[cfg(celld_internal_tests)] | |
| 845 | -fn effective_queue_retention(duration: i64) -> i64 { | |
| 846 | - QUEUE_RETENTION_FOR_TEST.get().unwrap_or(duration) | |
| 847 | -} | |
| 848 | - | |
| 849 | -#[cfg(not(celld_internal_tests))] | |
| 850 | -fn effective_queue_retention(duration: i64) -> i64 { | |
| 851 | - duration | |
| 852 | -} | |
| 853 | - | |
| 854 | -#[cfg(celld_internal_tests)] | |
| 855 | -fn effective_queue_sweep_batch(rows: usize) -> usize { | |
| 856 | - QUEUE_SWEEP_BATCH_FOR_TEST.get().unwrap_or(rows) | |
| 857 | -} | |
| 858 | - | |
| 859 | -#[cfg(not(celld_internal_tests))] | |
| 860 | -fn effective_queue_sweep_batch(rows: usize) -> usize { | |
| 861 | - rows | |
| 862 | -} | |
| 863 | - | |
| 864 | -#[cfg(not(celld_internal_tests))] | |
| 865 | -fn effective_queue_batch_timeout(duration: i64) -> i64 { | |
| 866 | - duration | |
| 867 | -} | |
| 868 | - | |
| 869 | 717 | /// Install the deployment-wide Queue consumer catalog and lease budget. |
| 870 | 718 | /// |
| 871 | 719 | /// Every co-hosted config gets the same catalog before an isolate starts, so a |
| 872 | 720 | /// shared `__Queue` class cannot dispatch according to whichever producer |
| 873 | 721 | /// registered the class first. |
| 874 | 722 | pub(super) fn inject_queue_config(scope: &mut v8::PinScope, config: &WorkerConfig) -> Result<()> { |
| 875 | - let cell = cell_state(scope)?; | |
| 876 | - let consumers = v8::Object::new(scope); | |
| 877 | - for registration in &config.queue_consumers { | |
| 878 | - let value = v8::Object::new(scope); | |
| 879 | - let set_string = |scope: &mut v8::PinScope, name: &str, text: &str| { | |
| 880 | - let key = v8::String::new(scope, name).unwrap(); | |
| 881 | - let text = v8::String::new(scope, text).unwrap(); | |
| 882 | - value.set(scope, key.into(), text.into()); | |
| 883 | - }; | |
| 884 | - let set_number = |scope: &mut v8::PinScope, name: &str, number: f64| { | |
| 885 | - let key = v8::String::new(scope, name).unwrap(); | |
| 886 | - let number = v8::Number::new(scope, number); | |
| 887 | - value.set(scope, key.into(), number.into()); | |
| 888 | - }; | |
| 889 | - let config = ®istration.config; | |
| 890 | - set_string(scope, "script", ®istration.script); | |
| 891 | - set_number(scope, "maxBatchSize", f64::from(config.max_batch_size)); | |
| 892 | - set_number( | |
| 893 | - scope, | |
| 894 | - "maxBatchTimeoutMs", | |
| 895 | - effective_queue_batch_timeout(i64::from(config.max_batch_timeout) * 1000) as f64, | |
| 896 | - ); | |
| 897 | - set_number(scope, "maxRetries", f64::from(config.max_retries)); | |
| 898 | - if let Some(dead_letter_queue) = &config.dead_letter_queue { | |
| 899 | - set_string(scope, "deadLetterQueue", dead_letter_queue); | |
| 900 | - } | |
| 901 | - if let Some(max_concurrency) = config.max_concurrency { | |
| 902 | - set_number(scope, "maxConcurrency", f64::from(max_concurrency)); | |
| 903 | - } | |
| 904 | - if let Some(retry_delay) = config.retry_delay { | |
| 905 | - set_number(scope, "retryDelaySeconds", f64::from(retry_delay)); | |
| 906 | - } | |
| 907 | - let key = v8::String::new(scope, &config.queue).unwrap(); | |
| 908 | - consumers.set(scope, key.into(), value.into()); | |
| 909 | - } | |
| 910 | - let key = v8::String::new(scope, "queueConsumers").unwrap(); | |
| 911 | - cell.set(scope, key.into(), consumers.into()); | |
| 912 | - | |
| 913 | - let admission = crate::runtime::admission_wait() | |
| 914 | - .as_millis() | |
| 915 | - .min(i64::MAX as u128) as i64; | |
| 916 | - let handler = super::handler_budget().as_millis().min(i64::MAX as u128) as i64; | |
| 917 | - let settlement = i64::try_from(crate::actor::operation_deadline_ms()?).unwrap_or(i64::MAX); | |
| 918 | - let duration = effective_queue_lease_duration(celld_logic::queue::lease_duration_ms( | |
| 919 | - admission, handler, settlement, | |
| 920 | - )); | |
| 921 | - let key = v8::String::new(scope, "queueLeaseDurationMs").unwrap(); | |
| 922 | - let duration = v8::Number::new(scope, duration as f64); | |
| 923 | - cell.set(scope, key.into(), duration.into()); | |
| 924 | - let limits = v8::Object::new(scope); | |
| 925 | - let set_limit = |scope: &mut v8::PinScope, name: &str, number: f64| { | |
| 926 | - let key = v8::String::new(scope, name).unwrap(); | |
| 927 | - let number = v8::Number::new(scope, number); | |
| 928 | - limits.set(scope, key.into(), number.into()); | |
| 929 | - }; | |
| 930 | - set_limit( | |
| 931 | - scope, | |
| 932 | - "maxMessageBytes", | |
| 933 | - celld_logic::queue::MAX_MESSAGE_BYTES as f64, | |
| 723 | + let queue = crate::queue_policy::consumer_config(config)?; | |
| 724 | + let source = format!( | |
| 725 | + "const q = {queue};\n\ | |
| 726 | + const c = __celld.__cell;\n\ | |
| 727 | + c.queueConsumers = q.consumers;\n\ | |
| 728 | + c.queueLeaseDurationMs = q.leaseDurationMs;\n\ | |
| 729 | + c.queueLimits = q.limits;" | |
| 934 | 730 | ); |
| 935 | - set_limit( | |
| 936 | - scope, | |
| 937 | - "maxBatchBytes", | |
| 938 | - celld_logic::queue::MAX_SEND_BATCH_BYTES as f64, | |
| 939 | - ); | |
| 940 | - set_limit( | |
| 941 | - scope, | |
| 942 | - "maxBatchMessages", | |
| 943 | - celld_logic::queue::MAX_BATCH_MESSAGES as f64, | |
| 944 | - ); | |
| 945 | - set_limit( | |
| 946 | - scope, | |
| 947 | - "producerGroupMs", | |
| 948 | - crate::queue_batching::timing().producer_ms as f64, | |
| 949 | - ); | |
| 950 | - set_limit( | |
| 951 | - scope, | |
| 952 | - "maxConcurrency", | |
| 953 | - celld_logic::queue::MAX_CONCURRENCY as f64, | |
| 954 | - ); | |
| 955 | - set_limit( | |
| 956 | - scope, | |
| 957 | - "maxDelaySeconds", | |
| 958 | - celld_logic::queue::MAX_DELAY_SECONDS as f64, | |
| 959 | - ); | |
| 960 | - set_limit( | |
| 961 | - scope, | |
| 962 | - "retentionMs", | |
| 963 | - effective_queue_retention(celld_logic::queue::RETENTION_MS) as f64, | |
| 964 | - ); | |
| 965 | - set_limit( | |
| 966 | - scope, | |
| 967 | - "sweepBatchRows", | |
| 968 | - effective_queue_sweep_batch(celld_logic::sweep::BATCH_ROWS) as f64, | |
| 969 | - ); | |
| 970 | - let key = v8::String::new(scope, "queueLimits").unwrap(); | |
| 971 | - cell.set(scope, key.into(), limits.into()); | |
| 731 | + run_internal_snippet(scope, &source).ok_or_else(|| anyhow!("queue config install failed"))?; | |
| 972 | 732 | Ok(()) |
| 973 | 733 | } |
| 974 | 734 | |
| @@ -1154,7 +914,8 @@ | ||
| 1154 | 914 | pub(super) struct EmbeddedStartup<'a> { |
| 1155 | 915 | pub id: &'a str, |
| 1156 | 916 | pub props_sc: Vec<u8>, |
| 1157 | - pub restored_image: Option<Vec<u8>>, | |
| 917 | + pub path: std::path::PathBuf, | |
| 918 | + pub restored: bool, | |
| 1158 | 919 | } |
| 1159 | 920 | |
| 1160 | 921 | pub(super) fn adopt_embedded_cell( |
| @@ -1169,7 +930,8 @@ | ||
| 1169 | 930 | cell, |
| 1170 | 931 | parent, |
| 1171 | 932 | name, |
| 1172 | - startup.restored_image, | |
| 933 | + &startup.path, | |
| 934 | + startup.restored, | |
| 1173 | 935 | compat.sqlite_vec, |
| 1174 | 936 | ) |
| 1175 | 937 | .context("facet storage open failed")?; |
| @@ -1231,6 +993,13 @@ | ||
| 1231 | 993 | let source = format!("__celld.__cell.release({cell:?});"); |
| 1232 | 994 | run_internal_snippet(tc, &source).ok_or_else(|| anyhow!("adopt failed"))?; |
| 1233 | 995 | if !owned { |
| 996 | + // A facet of the root's own class lives in this isolate, and nothing | |
| 997 | + // else releases it: its realm and connection would outlive the root. | |
| 998 | + for facet in storage::embedded_facets(cell) { | |
| 999 | + let source = format!("__celld.__cell.release({facet:?});"); | |
| 1000 | + run_internal_snippet(tc, &source).ok_or_else(|| anyhow!("release failed"))?; | |
| 1001 | + storage::close(&facet); | |
| 1002 | + } | |
| 1234 | 1003 | storage::close(cell); |
| 1235 | 1004 | return Ok(None); |
| 1236 | 1005 | } |
modifiedcrates/celld/js/crypto.js+70−8View file
| @@ -43,8 +43,20 @@ | ||
| 43 | 43 | "ECDSA": "ECDSA", |
| 44 | 44 | "ECDH": "ECDH", |
| 45 | 45 | "ED25519": "Ed25519", |
| 46 | + // Cloudflare's pre-standard spelling reports itself back, because a | |
| 47 | + // caller that asked with it matches on what it asked for -- which is | |
| 48 | + // what the upstream `eddsa_test` group pins. | |
| 49 | + "NODE-ED25519": "NODE-ED25519", | |
| 46 | 50 | "X25519": "X25519", |
| 47 | 51 | }; |
| 52 | + // The one signature algorithm over Curve25519, under both spellings. Its | |
| 53 | + // two names share every host op, so sign, verify and generate look the | |
| 54 | + // algorithm up here rather than testing two strings each. | |
| 55 | + const _ED25519_ALGS = new Set(["ED25519", "NODE-ED25519"]); | |
| 56 | + // The Secure Curves, whose `raw` Web Crypto form is the bare 32-byte | |
| 57 | + // public point rather than a DER document. | |
| 58 | + const _OKP_CURVES = { "ED25519": "Ed25519", "NODE-ED25519": "Ed25519", | |
| 59 | + "X25519": "X25519" }; | |
| 48 | 60 | // Algorithms whose keys are asymmetric, whatever celld can then *do* with |
| 49 | 61 | // them: import validates the key, and an unsupported operation throws |
| 50 | 62 | // later at sign/verify/encrypt rather than here. Derived from the table |
| @@ -237,6 +249,30 @@ | ||
| 237 | 249 | "secret", normalized, extractable, usages, { bytes: raw }, |
| 238 | 250 | ); |
| 239 | 251 | } |
| 252 | + // A Secure Curves public key has a `raw` form: the 32-byte point on | |
| 253 | + // its own. It is checked before the asymmetric block below, because | |
| 254 | + // that block reads `raw` bytes as a DER document and can only report a | |
| 255 | + // parse failure for them. | |
| 256 | + if (format === "raw" && _OKP_CURVES[name] !== undefined) { | |
| 257 | + const imported = _extra("asym-key-import", { | |
| 258 | + key: Array.from(_toBuf(keyData)), | |
| 259 | + format: "raw", | |
| 260 | + type: _OKP_CURVES[name], | |
| 261 | + visibility: "public", | |
| 262 | + passphrase: null, | |
| 263 | + }); | |
| 264 | + return _makeKey( | |
| 265 | + "public", | |
| 266 | + _keyAlgorithm(name, algorithm, imported.keyType, imported.details), | |
| 267 | + extractable, | |
| 268 | + usages, | |
| 269 | + { | |
| 270 | + bytes: Uint8Array.from(imported.der), | |
| 271 | + keyType: imported.keyType, | |
| 272 | + details: imported.details, | |
| 273 | + }, | |
| 274 | + ); | |
| 275 | + } | |
| 240 | 276 | // A JWK's `alg` names the algorithm it was made for. Anything that is |
| 241 | 277 | // not a string is not an algorithm name, and importing it would leave |
| 242 | 278 | // a key claiming to be something it cannot be. Web Crypto ignores a |
| @@ -285,6 +321,21 @@ | ||
| 285 | 321 | } |
| 286 | 322 | |
| 287 | 323 | async exportKey(format, key) { |
| 324 | + // The `raw` form of a Secure Curves public key is its 32-byte point. | |
| 325 | + // The branch below answers every `raw` request from the stored bytes, | |
| 326 | + // which for an asymmetric key are its SPKI document -- so without this | |
| 327 | + // arm an X25519 peer key exports as 44 bytes that no counterpart can | |
| 328 | + // read, and nothing reports an error. | |
| 329 | + if (format === "raw" && key?.type === "public" && | |
| 330 | + (key.__celldMaterial?.keyType === "ed25519" || | |
| 331 | + key.__celldMaterial?.keyType === "x25519")) { | |
| 332 | + if (!key.extractable) { | |
| 333 | + throw new DOMException("key is not extractable", "InvalidAccessError"); | |
| 334 | + } | |
| 335 | + return Uint8Array.from(_extra("asym-key-raw-public", { | |
| 336 | + der: Array.from(key.__celldMaterial.bytes), | |
| 337 | + }).bytes).buffer; | |
| 338 | + } | |
| 288 | 339 | if (format === "raw" && key?.__celldMaterial?.bytes) { |
| 289 | 340 | if (!key.extractable) { |
| 290 | 341 | throw new DOMException("key is not extractable", "InvalidAccessError"); |
| @@ -371,17 +422,21 @@ | ||
| 371 | 422 | return out.buffer.slice( |
| 372 | 423 | out.byteOffset, out.byteOffset + out.byteLength); |
| 373 | 424 | } |
| 374 | - if (name !== "ECDH") { | |
| 425 | + if (name !== "ECDH" && name !== "X25519") { | |
| 375 | 426 | throw _notSupported("unsupported derive algorithm: " + name); |
| 376 | 427 | } |
| 377 | 428 | const publicKey = algorithm?.public; |
| 378 | 429 | if (!publicKey || publicKey.type !== "public") { |
| 379 | - throw new TypeError("ECDH requires a public key in algorithm.public"); | |
| 430 | + throw new TypeError(name + " requires a public key in algorithm.public"); | |
| 380 | 431 | } |
| 381 | - const shared = Uint8Array.from(_extra("ecdh-derive", { | |
| 382 | - private: Array.from(_toBuf(baseKey.__celldMaterial.bytes)), | |
| 383 | - public: Array.from(_toBuf(publicKey.__celldMaterial.bytes)), | |
| 384 | - }).bytes); | |
| 432 | + // X25519 carries no `namedCurve`, so it cannot ride the curve match | |
| 433 | + // `ecdh-derive` runs; its op is separate for that reason alone. Both | |
| 434 | + // answer the raw shared secret, so everything below is shared. | |
| 435 | + const shared = Uint8Array.from(_extra( | |
| 436 | + name === "X25519" ? "x25519-derive" : "ecdh-derive", { | |
| 437 | + private: Array.from(_toBuf(baseKey.__celldMaterial.bytes)), | |
| 438 | + public: Array.from(_toBuf(publicKey.__celldMaterial.bytes)), | |
| 439 | + }).bytes); | |
| 385 | 440 | if (length === null || length === undefined) return shared.buffer; |
| 386 | 441 | const bytes = Number(length) / 8; |
| 387 | 442 | if (!Number.isInteger(bytes) || bytes < 0 || bytes > shared.byteLength) { |
| @@ -455,6 +510,7 @@ | ||
| 455 | 510 | "RSA-PSS": "rsa", |
| 456 | 511 | "ED25519": "ed25519", |
| 457 | 512 | "NODE-ED25519": "ed25519", |
| 513 | + "X25519": "x25519", | |
| 458 | 514 | "ECDSA": "ec", |
| 459 | 515 | "ECDH": "ec", |
| 460 | 516 | }; |
| @@ -533,7 +589,7 @@ | ||
| 533 | 589 | if (!sig) throw _operationError("HMAC sign failed"); |
| 534 | 590 | return sig.buffer.slice(sig.byteOffset, sig.byteOffset + sig.byteLength); |
| 535 | 591 | } |
| 536 | - const operation = name === "ED25519" | |
| 592 | + const operation = _ED25519_ALGS.has(name) | |
| 537 | 593 | ? "ed25519-sign" |
| 538 | 594 | : name === "ECDSA" |
| 539 | 595 | ? "p256-sign" |
| @@ -571,7 +627,13 @@ | ||
| 571 | 627 | _toBuf(data), |
| 572 | 628 | ); |
| 573 | 629 | } |
| 574 | - const operation = name === "ECDSA" | |
| 630 | + // Ed25519 signs through `ed25519-sign` above, so a key pair that can | |
| 631 | + // be generated and signed with had no way to check its own signature | |
| 632 | + // until this arm existed (denoland/celld#221). The host op is the one | |
| 633 | + // node:crypto's `verify()` already calls. | |
| 634 | + const operation = _ED25519_ALGS.has(name) | |
| 635 | + ? "ed25519-verify" | |
| 636 | + : name === "ECDSA" | |
| 575 | 637 | ? "p256-verify" |
| 576 | 638 | : name === "RSASSA-PKCS1-V1_5" |
| 577 | 639 | ? "rsa-pkcs1-verify" |
modifiedcrates/celld/js/crypto.rs+140−14View file
| @@ -139,6 +139,57 @@ | ||
| 139 | 139 | der |
| 140 | 140 | } |
| 141 | 141 | |
| 142 | +/// The 32 bytes of X25519 material inside a PKCS#8 or SPKI document, and the | |
| 143 | +/// one place that decides a document really is an X25519 key. | |
| 144 | +/// | |
| 145 | +/// Two failures live here. First, import passes a document through without | |
| 146 | +/// re-encoding it, so a worker can hand this module a well-formed document | |
| 147 | +/// that names X25519 around a body of any length. Every consumer wants exactly | |
| 148 | +/// 32 bytes, and a tail slice on a shorter body panics — which aborts the | |
| 149 | +/// process, because a Rust panic cannot unwind through the v8 | |
| 150 | +/// `FunctionCallback` frame above it. Returning the array makes the length a | |
| 151 | +/// property of the value, so no caller has to remember the rule. | |
| 152 | +/// | |
| 153 | +/// Second, X25519 is the one algorithm in this file with no DER codec of its | |
| 154 | +/// own, so nothing else checks its algorithm OID. RFC 8410 gives Ed25519 the | |
| 155 | +/// identical PKCS#8 and SPKI body shape, and every other algorithm's codec | |
| 156 | +/// (`ed25519_dalek::SigningKey::from_pkcs8_der`, the `p*` curves, `rsa`) | |
| 157 | +/// rejects a foreign OID for free. Without the check below, `x25519-derive` | |
| 158 | +/// would accept an Ed25519 signing key and run its seed as a Montgomery | |
| 159 | +/// scalar, which is the Ed25519/X25519 key-reuse mistake the two algorithms | |
| 160 | +/// exist apart to prevent. | |
| 161 | +fn x25519_material(der: &[u8], private: bool) -> Result<[u8; 32]> { | |
| 162 | + use rsa::pkcs8::der::Decode; | |
| 163 | + | |
| 164 | + let raw = if private { | |
| 165 | + let info = rsa::pkcs8::PrivateKeyInfo::from_der(der) | |
| 166 | + .map_err(|_| anyhow!("invalid X25519 private key"))?; | |
| 167 | + if info.algorithm.oid != X25519_OID { | |
| 168 | + return Err(anyhow!("not an X25519 private key")); | |
| 169 | + } | |
| 170 | + // RFC 8410 wraps the scalar in a second OCTET STRING inside the | |
| 171 | + // PKCS#8 privateKey field, so that header comes off before the | |
| 172 | + // length test. | |
| 173 | + rsa::pkcs8::der::asn1::OctetStringRef::from_der(info.private_key) | |
| 174 | + .map_err(|_| anyhow!("invalid X25519 private key"))? | |
| 175 | + .as_bytes() | |
| 176 | + .to_vec() | |
| 177 | + } else { | |
| 178 | + let info = rsa::pkcs8::SubjectPublicKeyInfoRef::from_der(der) | |
| 179 | + .map_err(|_| anyhow!("invalid X25519 public key"))?; | |
| 180 | + if info.algorithm.oid != X25519_OID { | |
| 181 | + return Err(anyhow!("not an X25519 public key")); | |
| 182 | + } | |
| 183 | + info.subject_public_key | |
| 184 | + .as_bytes() | |
| 185 | + .ok_or_else(|| anyhow!("invalid X25519 public key"))? | |
| 186 | + .to_vec() | |
| 187 | + }; | |
| 188 | + raw.as_slice() | |
| 189 | + .try_into() | |
| 190 | + .map_err(|_| anyhow!("an X25519 key must be 32 bytes")) | |
| 191 | +} | |
| 192 | + | |
| 142 | 193 | /// The JWK `crv` for a parsed EC key, from the `namedCurve` its details |
| 143 | 194 | /// already carry. |
| 144 | 195 | fn ec_jwk_crv(parsed: &ParsedKey) -> Result<&'static str> { |
| @@ -309,11 +360,19 @@ | ||
| 309 | 360 | }), |
| 310 | 361 | }) |
| 311 | 362 | } |
| 312 | - X25519_OID => Ok(ParsedKey { | |
| 313 | - kind: "x25519", | |
| 314 | - der: der.to_vec(), | |
| 315 | - details: serde_json::json!({}), | |
| 316 | - }), | |
| 363 | + X25519_OID => { | |
| 364 | + // Classify by the OID *and* the body. Import passes a document | |
| 365 | + // through without re-encoding it, so without this call a | |
| 366 | + // well-formed PKCS#8 naming X25519 around an empty OCTET STRING | |
| 367 | + // becomes a `ParsedKey` of kind x25519 that holds no key, and | |
| 368 | + // every consumer then has to re-check a length the type claims. | |
| 369 | + x25519_material(der, private)?; | |
| 370 | + Ok(ParsedKey { | |
| 371 | + kind: "x25519", | |
| 372 | + der: der.to_vec(), | |
| 373 | + details: serde_json::json!({}), | |
| 374 | + }) | |
| 375 | + } | |
| 317 | 376 | other => Err(anyhow!( |
| 318 | 377 | "unsupported key algorithm {other}; celld implements RSA, EC P-256 and Ed25519" |
| 319 | 378 | )), |
| @@ -612,6 +671,26 @@ | ||
| 612 | 671 | } |
| 613 | 672 | Ok(serde_json::json!({ "bytes": ec_curve!(crv, derive) })) |
| 614 | 673 | } |
| 674 | + // X25519 key agreement, the Secure Curves half of `deriveBits`. The | |
| 675 | + // secret is the raw 32-byte point with no KDF applied, so it answers | |
| 676 | + // a null `length` the same way `ecdh-derive` does for a NIST curve. | |
| 677 | + // The two ops stay separate because X25519 has no `namedCurve` and no | |
| 678 | + // `elliptic_curve` codec, so nothing in the macro above applies. | |
| 679 | + "x25519-derive" => { | |
| 680 | + let private = crypto_bytes(args, "private")?; | |
| 681 | + let public = crypto_bytes(args, "public")?; | |
| 682 | + let secret = x25519_dalek::StaticSecret::from(x25519_material(&private, true)?); | |
| 683 | + let point = x25519_dalek::PublicKey::from(x25519_material(&public, false)?); | |
| 684 | + let shared = secret.diffie_hellman(&point); | |
| 685 | + // A low-order peer point drives the result to all zeroes, which | |
| 686 | + // carries none of our scalar: both sides would agree on a secret | |
| 687 | + // the attacker also knows. Web Crypto names this failure, so it | |
| 688 | + // must not reach the caller as bytes. | |
| 689 | + if !shared.was_contributory() { | |
| 690 | + return Err(anyhow!("X25519 derived a non-contributory shared secret")); | |
| 691 | + } | |
| 692 | + Ok(serde_json::json!({ "bytes": shared.as_bytes().to_vec() })) | |
| 693 | + } | |
| 615 | 694 | "ed25519-sign" => { |
| 616 | 695 | use ed25519_dalek::pkcs8::DecodePrivateKey; |
| 617 | 696 | use ed25519_dalek::Signer; |
| @@ -902,6 +981,36 @@ | ||
| 902 | 981 | let (der, is_private) = if format == "jwk" { |
| 903 | 982 | let jwk = args.get("key").ok_or_else(|| anyhow!("missing JWK"))?; |
| 904 | 983 | (key_from_jwk(jwk, want_private)?, want_private) |
| 984 | + } else if format == "raw" { | |
| 985 | + // Web Crypto's `raw` format for the Secure Curves: a public | |
| 986 | + // key is its 32-byte point, with no structure around it. The | |
| 987 | + // curve therefore cannot be read off the bytes and arrives in | |
| 988 | + // `type`. Only a public key has a `raw` form, so `visibility` | |
| 989 | + // is not consulted. | |
| 990 | + let key = crypto_bytes(args, "key")?; | |
| 991 | + let curve = args | |
| 992 | + .get("type") | |
| 993 | + .and_then(serde_json::Value::as_str) | |
| 994 | + .unwrap_or_default(); | |
| 995 | + let point: [u8; 32] = key | |
| 996 | + .as_slice() | |
| 997 | + .try_into() | |
| 998 | + .map_err(|_| anyhow!("a {curve} raw public key must be 32 bytes"))?; | |
| 999 | + let der = match curve { | |
| 1000 | + "X25519" => x25519_spki(&point), | |
| 1001 | + "Ed25519" => { | |
| 1002 | + use ed25519_dalek::pkcs8::EncodePublicKey; | |
| 1003 | + // Unlike X25519, an Ed25519 point has to decompress | |
| 1004 | + // to a curve point, so a bad one fails here. | |
| 1005 | + ed25519_dalek::VerifyingKey::from_bytes(&point) | |
| 1006 | + .map_err(|_| anyhow!("invalid Ed25519 public key"))? | |
| 1007 | + .to_public_key_der()? | |
| 1008 | + .as_bytes() | |
| 1009 | + .to_vec() | |
| 1010 | + } | |
| 1011 | + other => return Err(anyhow!("cannot import a raw {other} key")), | |
| 1012 | + }; | |
| 1013 | + (der, false) | |
| 905 | 1014 | } else { |
| 906 | 1015 | let key = crypto_bytes(args, "key")?; |
| 907 | 1016 | let stated = args.get("type").and_then(serde_json::Value::as_str); |
| @@ -996,10 +1105,7 @@ | ||
| 996 | 1105 | key.verifying_key().to_public_key_der()?.as_bytes().to_vec() |
| 997 | 1106 | } |
| 998 | 1107 | "x25519" => { |
| 999 | - let scalar: [u8; 32] = der[der.len() - 32..] | |
| 1000 | - .try_into() | |
| 1001 | - .expect("X25519 PKCS#8 ends with the 32-byte scalar"); | |
| 1002 | - let secret = x25519_dalek::StaticSecret::from(scalar); | |
| 1108 | + let secret = x25519_dalek::StaticSecret::from(x25519_material(&der, true)?); | |
| 1003 | 1109 | x25519_spki(x25519_dalek::PublicKey::from(&secret).as_bytes()) |
| 1004 | 1110 | } |
| 1005 | 1111 | other => return Err(anyhow!("cannot derive a public key for {other}")), |
| @@ -1179,6 +1285,27 @@ | ||
| 1179 | 1285 | Ok(serde_json::json!({ "der": bytes })) |
| 1180 | 1286 | } |
| 1181 | 1287 | } |
| 1288 | + // The inverse of the `raw` import above: the 32-byte point inside an | |
| 1289 | + // Ed25519 or X25519 SPKI document. Web Crypto's `raw` export of a | |
| 1290 | + // Secure Curves public key is those bytes, not the document holding | |
| 1291 | + // them, and a peer that receives 44 bytes of SPKI where it expects a | |
| 1292 | + // point fails far from here. | |
| 1293 | + "asym-key-raw-public" => { | |
| 1294 | + let der = crypto_bytes(args, "der")?; | |
| 1295 | + let parsed = describe_key(&der, false)?; | |
| 1296 | + let point = match parsed.kind { | |
| 1297 | + "x25519" => x25519_material(&der, false)?.to_vec(), | |
| 1298 | + "ed25519" => { | |
| 1299 | + use ed25519_dalek::pkcs8::DecodePublicKey; | |
| 1300 | + ed25519_dalek::VerifyingKey::from_public_key_der(&der) | |
| 1301 | + .map_err(|_| anyhow!("invalid Ed25519 public key"))? | |
| 1302 | + .to_bytes() | |
| 1303 | + .to_vec() | |
| 1304 | + } | |
| 1305 | + other => return Err(anyhow!("cannot export a {other} key as raw")), | |
| 1306 | + }; | |
| 1307 | + Ok(serde_json::json!({ "bytes": point })) | |
| 1308 | + } | |
| 1182 | 1309 | // Export a normalized key back out. `jwk` is the shape `toCryptoKey` |
| 1183 | 1310 | // and Node's `export({format:"jwk"})` both want. |
| 1184 | 1311 | "asym-key-export" => { |
| @@ -1256,17 +1383,16 @@ | ||
| 1256 | 1383 | ec_curve!(crv, export) |
| 1257 | 1384 | } |
| 1258 | 1385 | ("x25519", _) => { |
| 1259 | - let raw = &der[der.len() - 32..]; | |
| 1386 | + let raw = x25519_material(&der, private)?; | |
| 1260 | 1387 | let mut jwk = serde_json::json!({ "kty": "OKP", "crv": "X25519" }); |
| 1261 | 1388 | if private { |
| 1262 | - let scalar: [u8; 32] = raw.try_into().unwrap(); | |
| 1263 | - let secret = x25519_dalek::StaticSecret::from(scalar); | |
| 1389 | + let secret = x25519_dalek::StaticSecret::from(raw); | |
| 1264 | 1390 | jwk["x"] = serde_json::Value::String(base64url( |
| 1265 | 1391 | x25519_dalek::PublicKey::from(&secret).as_bytes(), |
| 1266 | 1392 | )); |
| 1267 | - jwk["d"] = serde_json::Value::String(base64url(raw)); | |
| 1393 | + jwk["d"] = serde_json::Value::String(base64url(&raw)); | |
| 1268 | 1394 | } else { |
| 1269 | - jwk["x"] = serde_json::Value::String(base64url(raw)); | |
| 1395 | + jwk["x"] = serde_json::Value::String(base64url(&raw)); | |
| 1270 | 1396 | } |
| 1271 | 1397 | jwk |
| 1272 | 1398 | } |
modifiedcrates/celld/js/harness.js+7693−8724View file
| @@ -1558,8730 +1558,7699 @@ | ||
| 1558 | 1558 | this._transactionTail = Promise.resolve(); |
| 1559 | 1559 | this._transactionOwner = ""; |
| 1560 | 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 | - const loaderOptions = (method, options, supportsLimits) => { | |
| 3123 | - if (options === null || options === undefined) return undefined; | |
| 3124 | - if (typeof options !== "object") | |
| 3125 | - throw new TypeError(method + "() options must be an object."); | |
| 3126 | - const extra = Object.keys(options).filter( | |
| 3127 | - (key) => key !== "props" && !(supportsLimits && key === "limits")); | |
| 3128 | - if (extra.length !== 0) | |
| 3129 | - throw new TypeError( | |
| 3130 | - method + '() does not support the option "' + extra.join('", "') + | |
| 3131 | - '".'); | |
| 3132 | - return options; | |
| 3133 | - }; | |
| 3134 | - // `props` cross to the loaded isolate by structured clone, on the same | |
| 3135 | - // transport that already carries the call's arguments (`__rpcOut` below). | |
| 3136 | - // JSON is the obvious alternative and it is wrong: JSON.stringify turns a | |
| 3137 | - // Map, a Set, a Date, a typed array, and a RegExp into a plain object or a | |
| 3138 | - // string and reports no error, so the callee reads a mangled value that the | |
| 3139 | - // same call's arguments would have carried intact. Encoding here, once per | |
| 3140 | - // loader API call, also rejects an unclonable value at that call rather than | |
| 3141 | - // at the first operation. | |
| 3142 | - const loaderPropsSc = (method, options) => { | |
| 3143 | - const props = loaderOptions(method, options, false)?.props; | |
| 3144 | - if (props === undefined) return undefined; | |
| 3145 | - // `lift` false: the props cross an isolate boundary, so a stub inside them | |
| 3146 | - // is a DataCloneError, exactly as a stub inside an argument of the same | |
| 3147 | - // call is. | |
| 3148 | - return __rpcOut(props, false); | |
| 3149 | - }; | |
| 3150 | - const loaderEntrypointOptions = (options) => { | |
| 3151 | - options = loaderOptions("getEntrypoint", options, true); | |
| 3152 | - const props = options?.props; | |
| 3153 | - return { | |
| 3154 | - propsSc: props === undefined ? undefined : __rpcOut(props, false), | |
| 3155 | - limitsJson: JSON.stringify(options?.limits ?? null), | |
| 3156 | - }; | |
| 3157 | - }; | |
| 3158 | - const makeEntrypoint = (loadPromise, entrypoint, propsSc, limitsJson) => { | |
| 3159 | - const target = { | |
| 3160 | - async fetch(input, init) { | |
| 3161 | - const { id, tails } = await loadPromise; | |
| 3162 | - const req = new Request(input, init); | |
| 3163 | - // The verbatim header list; see the note on the outbound `fetch`. | |
| 3164 | - // The loaded worker rebuilds a `Headers` from these pairs, so a | |
| 3165 | - // repeat and its casing survive the isolate boundary. | |
| 3166 | - const headers = JSON.stringify(req.headers.__celldHeaderList); | |
| 3167 | - const { body, streamId } = await __subrequestBody(req); | |
| 3168 | - const loaded = __loader_fetch( | |
| 3169 | - id, req.url, req.method, body, headers, streamId, entrypoint, | |
| 3170 | - propsSc === undefined ? new Uint8Array() : propsSc, | |
| 3171 | - limitsJson, tails.length !== 0); | |
| 3172 | - const response = tails.length === 0 ? loaded : loaded[0]; | |
| 3173 | - if (tails.length !== 0) { | |
| 3174 | - const delivery = loaded[1] | |
| 3175 | - .then((report) => JSON.parse(report)) | |
| 3176 | - .then((events) => Promise.allSettled( | |
| 3177 | - tails.map((tail) => tail.tail(events)))) | |
| 3178 | - .then((results) => { | |
| 3179 | - for (const result of results) { | |
| 3180 | - if (result.status === "rejected") | |
| 3181 | - console.error("Tail Worker failed:", result.reason); | |
| 3182 | - } | |
| 3183 | - }) | |
| 3184 | - .catch((error) => console.error("Tail delivery failed:", error)); | |
| 3185 | - // The loaded fetch answers before its report because the child can | |
| 3186 | - // still have waitUntil work. Keep this chain on the loader event so | |
| 3187 | - // its IoContext cannot retire and abort the report operation. | |
| 3188 | - __registerWaitUntil(delivery); | |
| 3189 | - } | |
| 3190 | - const r = JSON.parse(await response); | |
| 3191 | - const responseBody = r.streamId !== undefined | |
| 3192 | - ? new CelldHttpBodyStream(r.streamId) | |
| 3193 | - : r.body !== undefined ? r.body : Uint8Array.from(r.bodyBytes || []); | |
| 3194 | - return __wrapServiceResponse( | |
| 3195 | - new Response(responseBody, { status: r.status, headers: r.headers }), | |
| 3196 | - req.url); | |
| 3197 | - }, | |
| 3198 | - }; | |
| 3199 | - // Both the default and named entrypoints expose RPC: property access is a | |
| 3200 | - // callable pipeline node dispatched via __loader_rpc to that entrypoint in | |
| 3201 | - // the loaded worker (default -> the "default" export, which | |
| 3202 | - // register_entrypoints registers like any other). fetch stays on the | |
| 3203 | - // target. Only single-method calls are supported for now. | |
| 3204 | - const session = { | |
| 3205 | - get: () => Promise.reject(new Error( | |
| 3206 | - "Awaitable properties on loaded workers are not supported yet.")), | |
| 3207 | - call: (path, args) => (async () => { | |
| 3208 | - if (path.length !== 1) | |
| 3209 | - throw new Error( | |
| 3210 | - "Pipelined property paths on loaded workers are not supported " + | |
| 3211 | - "yet."); | |
| 3212 | - const { id } = await loadPromise; | |
| 3213 | - return __rpcDes( | |
| 3214 | - await __loader_rpc(id, entrypoint, path[0], __rpcOut(args, false), | |
| 3215 | - propsSc, limitsJson)); | |
| 3216 | - })(), | |
| 3217 | - }; | |
| 3218 | - return new Proxy(target, { | |
| 3219 | - get: (base, prop) => { | |
| 3220 | - if (prop === "then") return undefined; | |
| 3221 | - if (Reflect.has(base, prop)) return Reflect.get(base, prop); | |
| 3222 | - if (typeof prop !== "string") return undefined; | |
| 3223 | - return __makeNode(session, [prop], null); | |
| 3224 | - }, | |
| 3225 | - }); | |
| 3226 | - }; | |
| 3227 | - // Anonymous load() workers are evicted when their only stub is GC'd: the | |
| 3228 | - // finalizer drops the worker's isolate so it does not leak. Named get() | |
| 3229 | - // workers are retained by `byName` (memoized) and so are not registered. | |
| 3230 | - const finalizer = typeof FinalizationRegistry === "function" | |
| 3231 | - ? new FinalizationRegistry((id) => __loader_drop(id)) | |
| 3232 | - : null; | |
| 3233 | - const makeStub = (loadPromise, evictable) => { | |
| 3234 | - // Explicit disposal evicts the worker deterministically; the finalizer is | |
| 3235 | - // a GC backstop for anonymous stubs that are dropped without disposing. | |
| 3236 | - // __loader_drop is idempotent, so the two paths cannot double-free. | |
| 3237 | - const drop = () => { | |
| 3238 | - loadPromise.then(({ id }) => __loader_drop(id), () => {}); | |
| 3239 | - }; | |
| 3240 | - const stub = { | |
| 3241 | - getEntrypoint(name = null, options = {}) { | |
| 3242 | - const { propsSc, limitsJson } = loaderEntrypointOptions(options); | |
| 3243 | - return makeEntrypoint( | |
| 3244 | - loadPromise, name === null ? "default" : String(name), | |
| 3245 | - propsSc, limitsJson); | |
| 3246 | - }, | |
| 3247 | - getDurableObjectClass(name = null, options = {}) { | |
| 3248 | - return __makeDurableObjectClass( | |
| 3249 | - loadPromise.then(({ id }) => id), name, | |
| 3250 | - loaderPropsSc("getDurableObjectClass", options)); | |
| 3251 | - }, | |
| 3252 | - dispose: drop, | |
| 3253 | - }; | |
| 3254 | - if (typeof Symbol.dispose === "symbol") stub[Symbol.dispose] = drop; | |
| 3255 | - if (evictable && finalizer) | |
| 3256 | - loadPromise.then(({ id }) => finalizer.register(stub, id), () => {}); | |
| 3257 | - return stub; | |
| 3258 | - }; | |
| 3259 | - // JSON.stringify silently drops binary values, so each non-string module -- | |
| 3260 | - // wasm bytes as a BufferSource, or an explicit module shape -- is normalized | |
| 3261 | - // first. JavaScript modules become plain strings, and wasm moves into a | |
| 3262 | - // side-band `[name, Uint8Array]` list so multi-MB blobs never take a | |
| 3263 | - // base64/JSON round-trip. | |
| 3264 | - const toBytes = (v) => v instanceof ArrayBuffer ? new Uint8Array(v) | |
| 3265 | - : ArrayBuffer.isView(v) | |
| 3266 | - ? new Uint8Array(v.buffer, v.byteOffset, v.byteLength) : null; | |
| 3267 | - const moduleKinds = [ | |
| 3268 | - "js", "cjs", "py", "text", "data", "json", "wasm", | |
| 3269 | - ]; | |
| 3270 | - const encodeLoaderEnv = (value) => { | |
| 3271 | - if (value === undefined || value === null) | |
| 3272 | - return { env: undefined, envRoutes: [] }; | |
| 3273 | - const envRoutes = []; | |
| 3274 | - const seen = new Map(); | |
| 3275 | - const project = (v) => { | |
| 3276 | - if (v === null || | |
| 3277 | - (typeof v !== "object" && typeof v !== "function")) return v; | |
| 3278 | - const cached = seen.get(v); | |
| 3279 | - if (cached !== undefined) return cached; | |
| 3280 | - const route = __outboundMeta.get(v); | |
| 3281 | - if (route !== undefined) { | |
| 3282 | - const marker = { [__loaderServiceMarker]: envRoutes.length }; | |
| 3283 | - seen.set(v, marker); | |
| 3284 | - envRoutes.push([ | |
| 3285 | - route.script, | |
| 3286 | - route.entrypoint, | |
| 3287 | - route.propsSc ?? (route.props === undefined | |
| 3288 | - ? new Uint8Array() : __rpcOut(route.props, false)), | |
| 3289 | - ]); | |
| 3290 | - return marker; | |
| 3291 | - } | |
| 3292 | - if (Object.prototype.hasOwnProperty.call(v, __loaderServiceMarker)) | |
| 3293 | - throw new DOMException( | |
| 3294 | - `Worker Loader env contains the reserved key ` + | |
| 3295 | - `${JSON.stringify(__loaderServiceMarker)}.`, | |
| 3296 | - "DataCloneError"); | |
| 3297 | - if (typeof v === "function" || v instanceof __cf.RpcTarget || | |
| 3298 | - __stubMeta.has(v) || __doStubMeta.has(v)) | |
| 3299 | - throw new DOMException( | |
| 3300 | - "Worker Loader env supports only Service Binding capabilities.", | |
| 3301 | - "DataCloneError"); | |
| 3302 | - if (v instanceof Map) { | |
| 3303 | - const out = new Map(); | |
| 3304 | - seen.set(v, out); | |
| 3305 | - for (const [key, item] of v) out.set(project(key), project(item)); | |
| 3306 | - return out; | |
| 3307 | - } | |
| 3308 | - if (v instanceof Set) { | |
| 3309 | - const out = new Set(); | |
| 3310 | - seen.set(v, out); | |
| 3311 | - for (const item of v) out.add(project(item)); | |
| 3312 | - return out; | |
| 3313 | - } | |
| 3314 | - const proto = Object.getPrototypeOf(v); | |
| 3315 | - if (!Array.isArray(v) && proto !== Object.prototype && proto !== null) | |
| 3316 | - return v; | |
| 3317 | - const out = Array.isArray(v) ? [] : {}; | |
| 3318 | - seen.set(v, out); | |
| 3319 | - for (const key of Object.keys(v)) out[key] = project(v[key]); | |
| 3320 | - return out; | |
| 3321 | - }; | |
| 3322 | - return { env: __sc_encode(project(value)), envRoutes }; | |
| 3323 | - }; | |
| 3324 | - const encodeModules = (c) => { | |
| 3325 | - if (c === null || typeof c !== "object" || c.modules === null | |
| 3326 | - || typeof c.modules !== "object") | |
| 3327 | - return { config: c, wasm: [], outbound: undefined, tails: [] }; | |
| 3328 | - const modules = {}; | |
| 3329 | - const wasm = []; | |
| 3330 | - for (const [name, value] of Object.entries(c.modules)) { | |
| 3331 | - const wrapped = value !== null && typeof value === "object" ? value : {}; | |
| 3332 | - const explicitKinds = moduleKinds.filter((kind) => | |
| 3333 | - Object.prototype.hasOwnProperty.call(wrapped, kind) | |
| 3334 | - ); | |
| 3335 | - if (explicitKinds.length > 1) | |
| 3336 | - throw new TypeError( | |
| 3337 | - `Worker Loader module ${JSON.stringify(name)} must contain exactly ` + | |
| 3338 | - "one module type."); | |
| 3339 | - const kind = explicitKinds[0]; | |
| 3340 | - if (kind === "js") { | |
| 3341 | - const source = wrapped[kind]; | |
| 3342 | - if (typeof source !== "string") | |
| 3343 | - throw new TypeError( | |
| 3344 | - `Worker Loader module ${JSON.stringify(name)} field ` + | |
| 3345 | - `${JSON.stringify(kind)} must be a string.`); | |
| 3346 | - modules[name] = source; | |
| 3347 | - continue; | |
| 3348 | - } | |
| 3349 | - const bytes = toBytes(value) ?? | |
| 3350 | - (kind === "wasm" ? toBytes(wrapped.wasm) : null); | |
| 3351 | - if (bytes !== null) wasm.push([name, bytes]); | |
| 3352 | - else modules[name] = value; | |
| 3353 | - } | |
| 3354 | - let outbound; | |
| 3355 | - let outboundProps; | |
| 3356 | - if (Object.prototype.hasOwnProperty.call(c, "globalOutbound")) { | |
| 3357 | - if (c.globalOutbound === undefined) { | |
| 3358 | - outbound = undefined; | |
| 3359 | - } else if (c.globalOutbound === null) { | |
| 3360 | - outbound = null; | |
| 3361 | - } else { | |
| 3362 | - const meta = __outboundMeta.get(c.globalOutbound); | |
| 3363 | - if (meta === undefined) | |
| 3364 | - throw new TypeError("globalOutbound must be a Fetcher or null."); | |
| 3365 | - // JSON carries only the host-minted route. Props use V8 structured | |
| 3366 | - // clone bytes, so their types and the cross-isolate clone boundary | |
| 3367 | - // match the other parameterized ctx.exports transports. | |
| 3368 | - outboundProps = meta.propsSc ?? (meta.props === undefined | |
| 3369 | - ? new Uint8Array() | |
| 3370 | - : __rpcOut(meta.props, false)); | |
| 3371 | - outbound = JSON.stringify({ | |
| 3372 | - script: meta.script, | |
| 3373 | - entrypoint: meta.entrypoint, | |
| 3374 | - }); | |
| 3375 | - } | |
| 3376 | - } | |
| 3377 | - const { env, envRoutes } = encodeLoaderEnv(c.env); | |
| 3378 | - let tails = []; | |
| 3379 | - if (Object.prototype.hasOwnProperty.call(c, "tails")) { | |
| 3380 | - if (!Array.isArray(c.tails)) | |
| 3381 | - throw new TypeError("tails must be an array of Fetchers."); | |
| 3382 | - tails = c.tails.map((tail) => { | |
| 3383 | - if (!__outboundMeta.has(tail)) | |
| 3384 | - throw new TypeError("tails must be an array of Fetchers."); | |
| 3385 | - return tail; | |
| 3386 | - }); | |
| 3387 | - } | |
| 3388 | - const { | |
| 3389 | - globalOutbound: _globalOutbound, | |
| 3390 | - env: _env, | |
| 3391 | - tails: _tails, | |
| 3392 | - ...rest | |
| 3393 | - } = c; | |
| 3394 | - return { | |
| 3395 | - config: { ...rest, modules }, wasm, outbound, outboundProps, | |
| 3396 | - env, envRoutes, tails, | |
| 3397 | - }; | |
| 3398 | - }; | |
| 3399 | - // getCode is deferred into a microtask so a throw (or async getCode) | |
| 3400 | - // surfaces as a rejection when the worker is first used, not at get()/load(). | |
| 3401 | - const loadFrom = (getCode) => | |
| 3402 | - Promise.resolve().then(getCode) | |
| 3403 | - .then((c) => { | |
| 3404 | - const { | |
| 3405 | - config, wasm, outbound, outboundProps, env, envRoutes, tails, | |
| 3406 | - } = encodeModules(c); | |
| 3407 | - const id = __loader_load( | |
| 3408 | - JSON.stringify(config), wasm, outbound, outboundProps, env, | |
| 3409 | - envRoutes, tails.length !== 0); | |
| 3410 | - return { id, tails }; | |
| 3411 | - }); | |
| 3412 | - return { | |
| 3413 | - load(code) { return makeStub(loadFrom(() => code), true); }, | |
| 3414 | - get(name, getCode) { | |
| 3415 | - let idPromise = byName.get(name); | |
| 3416 | - if (idPromise === undefined) { | |
| 3417 | - idPromise = loadFrom(getCode); | |
| 3418 | - byName.set(name, idPromise); | |
| 3419 | - } | |
| 3420 | - return makeStub(idPromise, false); | |
| 3421 | - }, | |
| 3422 | - }; | |
| 3423 | -}; | |
| 3424 | - | |
| 3425 | -const __makeServiceBinding = __celld.__makeServiceBinding = | |
| 3426 | - (script, entrypoint = null, propsSc = undefined) => { | |
| 3427 | - const target = { | |
| 3428 | - async fetch(input, init) { | |
| 3429 | - const req = new Request(input, init); | |
| 3430 | - const signal = req._signalForSubrequests; | |
| 3431 | - if (signal?.aborted) throw signal.reason; | |
| 3432 | - // A stream body advertises its length the way the HTTP layer | |
| 3433 | - // would: known length -> Content-Length, unknown -> chunked. | |
| 3434 | - if (req._bodyBytes === null && | |
| 3435 | - !req.headers.has("content-length") && | |
| 3436 | - !req.headers.has("transfer-encoding")) { | |
| 3437 | - const length = req.body._expectedLength; | |
| 3438 | - if (length === undefined) | |
| 3439 | - req.headers.set("transfer-encoding", "chunked"); | |
| 3440 | - else req.headers.set("content-length", String(length)); | |
| 3441 | - } | |
| 3442 | - const redirectState = __serviceRedirectState(req); | |
| 3443 | - // Fast path: the target is this same script, so its handler lives in | |
| 3444 | - // this isolate. Skip the op + pool-thread hop and call it directly, | |
| 3445 | - // inside its own event so the target's waitUntil does not attach to | |
| 3446 | - // the caller's. Cross-script targets still need their own isolate. | |
| 3447 | - if (script === __cell.script && entrypoint !== null) { | |
| 3448 | - // Mirror __dispatchTo: the target sees a fresh incoming signal, | |
| 3449 | - // aborted with "The client has disconnected" when the caller | |
| 3450 | - // abandons the call or cancels the response body; the caller's | |
| 3451 | - // own signal races the dispatch so an abandoned call rejects | |
| 3452 | - // immediately instead of pinning on a hung target. | |
| 3453 | - const requestController = new AbortController(); | |
| 3454 | - const dispatch = __dispatchEntrypointFetch( | |
| 3455 | - entrypoint, | |
| 3456 | - new Request(req, { | |
| 3457 | - signal: requestController.signal, | |
| 3458 | - __celldIncomingSignal: true, | |
| 3459 | - })); | |
| 3460 | - const response = signal | |
| 3461 | - ? await __raceCallerAbort(dispatch, signal, () => | |
| 3462 | - requestController.abort( | |
| 3463 | - new Error("The client has disconnected"))) | |
| 3464 | - : await dispatch; | |
| 3465 | - __attachResponseRequestCancellation( | |
| 3466 | - response, requestController, true); | |
| 3467 | - return __finishServiceFetch(response, req, redirectState); | |
| 3468 | - } | |
| 3469 | - if (script === __cell.script && typeof __cell.selfFetch === "function") { | |
| 3470 | - if (__cell.svcDepth >= 8) | |
| 3471 | - throw new Error( | |
| 3472 | - "Service binding recursion limit exceeded (8)"); | |
| 3473 | - __cell.svcDepth = (__cell.svcDepth || 0) + 1; | |
| 3474 | - const ctx = __beginEvent(); | |
| 3475 | - try { | |
| 3476 | - return __finishServiceFetch( | |
| 3477 | - await __ctxRun(undefined, | |
| 3478 | - () => __cell.selfFetch(req, __cell.env, ctx)), | |
| 3479 | - req, redirectState); | |
| 3480 | - } finally { | |
| 3481 | - __cell.svcDepth--; | |
| 3482 | - __endEvent(); | |
| 3483 | - } | |
| 3484 | - } | |
| 3485 | - // The verbatim header list; see the note on the outbound `fetch`. The | |
| 3486 | - // target isolate rebuilds a `Headers` from these pairs, so a repeat and | |
| 3487 | - // its casing survive the crossing. | |
| 3488 | - const headers = JSON.stringify(req.headers.__celldHeaderList); | |
| 3489 | - // Cross-isolate calls carry exact bytes. A host-backed stream transfers | |
| 3490 | - // its one source to the target, and another stream uses the byte fallback. | |
| 3491 | - const { body, streamId } = await __subrequestBody(req); | |
| 3492 | - const r = JSON.parse(await (signal | |
| 3493 | - ? __awaitCancellableDoCall( | |
| 3494 | - __svc_call_cancellable( | |
| 3495 | - script, req.url, req.method, body, headers, streamId, entrypoint, | |
| 3496 | - propsSc), | |
| 3497 | - signal) | |
| 3498 | - : __svc_call( | |
| 3499 | - script, req.url, req.method, body, headers, streamId, entrypoint, | |
| 3500 | - propsSc))); | |
| 3501 | - const responseBody = r.streamId !== undefined | |
| 3502 | - ? new CelldHttpBodyStream(r.streamId) | |
| 3503 | - : r.body !== undefined | |
| 3504 | - ? r.body | |
| 3505 | - : Uint8Array.from(r.bodyBytes || []); | |
| 3506 | - return __finishServiceFetch( | |
| 3507 | - new Response(responseBody, { | |
| 3508 | - status: r.status, headers: r.headers, __wsTarget: r.wsTarget, | |
| 3509 | - }), | |
| 3510 | - req, redirectState); | |
| 3511 | - }, | |
| 3512 | - // Workerd's test-visible Fetcher.scheduled(): invoke the target's | |
| 3513 | - // scheduled handler and report the outcome. | |
| 3514 | - async scheduled(options = {}) { | |
| 3515 | - if (script !== __cell.script || entrypoint !== null || | |
| 3516 | - typeof __cell.selfScheduled !== "function") | |
| 3517 | - throw new Error( | |
| 3518 | - "scheduled() is only implemented for same-script service " + | |
| 3519 | - "bindings whose target has a scheduled handler"); | |
| 3520 | - let noRetry = false; | |
| 3521 | - const ctrl = { | |
| 3522 | - scheduledTime: options.scheduledTime === undefined | |
| 3523 | - ? Date.now() : Number(options.scheduledTime), | |
| 3524 | - cron: options.cron === undefined ? "" : String(options.cron), | |
| 3525 | - noRetry() { noRetry = true; }, | |
| 3526 | - }; | |
| 3527 | - const ctx = __beginEvent(); | |
| 3528 | - try { | |
| 3529 | - await __cell.selfScheduled(ctrl, __cell.env, ctx); | |
| 3530 | - return { outcome: "ok", noRetry }; | |
| 3531 | - } finally { | |
| 3532 | - const drain = __endEvent(); | |
| 3533 | - // scheduled() reports the event outcome, so it cannot return while the | |
| 3534 | - // work that defines that event is still pending. Fetch replies differ: | |
| 3535 | - // a streamed response can depend on waitUntil work and must return first. | |
| 3536 | - if (drain !== null) await drain; | |
| 3537 | - } | |
| 3538 | - }, | |
| 3539 | - }; | |
| 3540 | - // An omitted entrypoint selects the module's default export, which may be a | |
| 3541 | - // WorkerEntrypoint or an object handler. `entrypoint = "Name"` selects that | |
| 3542 | - // named class. Any property other than a reserved Fetcher method is an | |
| 3543 | - // awaitable/callable pipeline node: awaiting | |
| 3544 | - // resolves the property remotely (a property-GET wire op), calling | |
| 3545 | - // invokes it, and deeper access extends the path, resolved on the | |
| 3546 | - // receiver side in one op. Same-script dispatch stays in this | |
| 3547 | - // isolate, so stub-able values may cross. A property path rooted | |
| 3548 | - // directly at the binding is context-free (ctx null): awaiting it | |
| 3549 | - // starts a fresh session, as in Workerd. | |
| 3550 | - const rpcEntrypoint = entrypoint === null ? "default" : entrypoint; | |
| 3551 | - const session = __entrypointSession( | |
| 3552 | - rpcEntrypoint, script === __cell.script, script, undefined, propsSc); | |
| 3553 | - const binding = new Proxy(target, { | |
| 3554 | - getPrototypeOf: () => __cf.ServiceStub.prototype, | |
| 3555 | - get: (base, prop) => { | |
| 3556 | - if (prop === "then") return undefined; // a stub is not a thenable | |
| 3557 | - if (Reflect.has(base, prop)) return Reflect.get(base, prop); | |
| 3558 | - if (typeof prop !== "string") return undefined; | |
| 3559 | - // Workerd's test hook: the named method as a callable handle, | |
| 3560 | - // resolved -- and refused -- on the receiver side. | |
| 3561 | - if (prop === "getRpcMethodForTestOnly") | |
| 3562 | - return (name) => __makeNode(session, [String(name)], null); | |
| 3563 | - return __makeNode(session, [prop], null); | |
| 3564 | - }}); | |
| 3565 | - __outboundMeta.set(binding, { script, entrypoint, propsSc }); | |
| 3566 | - return binding; | |
| 3567 | -}; | |
| 3568 | - | |
| 3569 | -__celld.__installLoaderEnv = (bytes, routes) => { | |
| 3570 | - const env = __sc_decode(bytes); | |
| 3571 | - const seen = new Set(); | |
| 3572 | - const revive = (v) => { | |
| 3573 | - if (v === null || typeof v !== "object") return v; | |
| 3574 | - const routeIndex = Object.prototype.hasOwnProperty.call( | |
| 3575 | - v, __loaderServiceMarker) ? v[__loaderServiceMarker] : undefined; | |
| 3576 | - if (Number.isSafeInteger(routeIndex) && routeIndex >= 0) { | |
| 3577 | - // Rust supplies flat [script, entrypoint, props] triples, and the marker | |
| 3578 | - // stores the triple index rather than an offset into that array. | |
| 3579 | - const routeOffset = routeIndex * 3; | |
| 3580 | - if (!Number.isSafeInteger(routeOffset) || routeOffset + 2 >= routes.length) | |
| 3581 | - throw new DOMException( | |
| 3582 | - "Worker Loader env contains an invalid capability.", | |
| 3583 | - "DataCloneError"); | |
| 3584 | - return __makeServiceBinding( | |
| 3585 | - routes[routeOffset], routes[routeOffset + 1], routes[routeOffset + 2]); | |
| 3586 | - } | |
| 3587 | - if (seen.has(v)) return v; | |
| 3588 | - seen.add(v); | |
| 3589 | - if (v instanceof Map) { | |
| 3590 | - const entries = [...v]; | |
| 3591 | - v.clear(); | |
| 3592 | - for (const [key, item] of entries) v.set(revive(key), revive(item)); | |
| 3593 | - return v; | |
| 3594 | - } | |
| 3595 | - if (v instanceof Set) { | |
| 3596 | - const items = [...v]; | |
| 3597 | - v.clear(); | |
| 3598 | - for (const item of items) v.add(revive(item)); | |
| 3599 | - return v; | |
| 3600 | - } | |
| 3601 | - if (Array.isArray(v) || Object.getPrototypeOf(v) === Object.prototype || | |
| 3602 | - Object.getPrototypeOf(v) === null) | |
| 3603 | - for (const key of Object.keys(v)) v[key] = revive(v[key]); | |
| 3604 | - return v; | |
| 3605 | - }; | |
| 3606 | - Object.assign(__cell.env, revive(env)); | |
| 3607 | -}; | |
| 3608 | -// RPC marshalling: V8 structured clone (Workerd js-rpc semantics), so | |
| 3609 | -// undefined, Date, Map, Set, BigInt, typed arrays, and cycles survive. | |
| 3610 | -// A value V8 cannot clone throws DataCloneError, as in Workerd. | |
| 3611 | -// | |
| 3612 | -// The envelope's first byte tags the payload. 0xff (the clone version | |
| 3613 | -// header) = plain clone, decoded as-is. 0x01 = clone of a lifted tree in | |
| 3614 | -// which RpcTarget instances, functions, and Durable Object stubs were | |
| 3615 | -// replaced by stub markers; the lift runs only after a plain clone | |
| 3616 | -// already threw. A projection walk happens first because V8 silently erases | |
| 3617 | -// custom and null prototypes. 0x02 = a lifted tree carrying only by-value | |
| 3618 | -// host types (Blob/File, Headers, | |
| 3619 | -// Request/Response) and no capabilities -- decoded like 0x01, but a | |
| 3620 | -// reply so tagged does not root its callee context. 0x00 = clone of | |
| 3621 | -// [error, ownProps] -- a callee exception crossing as a real Error. | |
| 3622 | -const __dataCloneError = (error) => new DOMException( | |
| 3623 | - String(error && error.message || error), "DataCloneError"); | |
| 3624 | -const __rpcUnsupportedType = (value) => new DOMException( | |
| 3625 | - 'Could not serialize object of type "' + | |
| 3626 | - (__util_constructor_name(value) || "Object") + | |
| 3627 | - '". This type does not support serialization.', | |
| 3628 | - "DataCloneError"); | |
| 3629 | -// V8 clones a user-class instance and a null-prototype object as plain data, | |
| 3630 | -// but Workerd refuses both over RPC. Project the value graph before V8 can | |
| 3631 | -// erase that distinction. The projection also snapshots enumerable getters, | |
| 3632 | -// so validation and serialization cannot invoke one getter twice. Native | |
| 3633 | -// clone types and RPC host types keep their own serializers. | |
| 3634 | -const __rpcProject = (value) => { | |
| 3635 | - const seen = new Map(); | |
| 3636 | - const originals = new WeakMap(); | |
| 3637 | - const set = (target, key, value) => Object.defineProperty(target, key, { | |
| 3638 | - value, enumerable: true, configurable: true, writable: true, | |
| 3639 | - }); | |
| 3640 | - const project = (v) => { | |
| 3641 | - if (v === null || (typeof v !== "object" && typeof v !== "function")) | |
| 3642 | - return v; | |
| 3643 | - const cached = seen.get(v); | |
| 3644 | - if (cached !== undefined) return cached; | |
| 3645 | - if (typeof v === "function" || v instanceof __cf.RpcTarget || | |
| 3646 | - __stubMeta.has(v) || __svcMeta.has(v) || __doStubMeta.has(v) || | |
| 3647 | - v instanceof Headers || v instanceof Blob || v instanceof Request || | |
| 3648 | - v instanceof Response || v instanceof ReadableStream || | |
| 3649 | - v instanceof WritableStream || v instanceof AbortSignal || | |
| 3650 | - v instanceof Date || v instanceof RegExp || v instanceof Error || | |
| 3651 | - v instanceof ArrayBuffer || ArrayBuffer.isView(v) || | |
| 3652 | - (typeof SharedArrayBuffer !== "undefined" && | |
| 3653 | - v instanceof SharedArrayBuffer) || | |
| 3654 | - (typeof CryptoKey !== "undefined" && v instanceof CryptoKey) || | |
| 3655 | - (typeof WebAssembly !== "undefined" && | |
| 3656 | - v instanceof WebAssembly.Module) || | |
| 3657 | - __util_proxy_details(v) !== undefined) return v; | |
| 3658 | - if (v instanceof Map) { | |
| 3659 | - const out = new Map(); | |
| 3660 | - seen.set(v, out); | |
| 3661 | - for (const [key, entry] of v) { | |
| 3662 | - out.set(project(key), project(entry)); | |
| 3663 | - } | |
| 3664 | - return out; | |
| 3665 | - } | |
| 3666 | - if (v instanceof Set) { | |
| 3667 | - const out = new Set(); | |
| 3668 | - seen.set(v, out); | |
| 3669 | - for (const entry of v) out.add(project(entry)); | |
| 3670 | - return out; | |
| 3671 | - } | |
| 3672 | - if (Array.isArray(v)) { | |
| 3673 | - const out = new Array(v.length); | |
| 3674 | - seen.set(v, out); | |
| 3675 | - originals.set(out, v); | |
| 3676 | - for (const key of Object.keys(v)) set(out, key, project(v[key])); | |
| 3677 | - return out; | |
| 3678 | - } | |
| 3679 | - if (Object.getPrototypeOf(v) !== Object.prototype) | |
| 3680 | - throw __rpcUnsupportedType(v); | |
| 3681 | - const out = {}; | |
| 3682 | - seen.set(v, out); | |
| 3683 | - originals.set(out, v); | |
| 3684 | - for (const key of Object.keys(v)) set(out, key, project(v[key])); | |
| 3685 | - return out; | |
| 3686 | - }; | |
| 3687 | - return { tree: project(value), originals }; | |
| 3688 | -}; | |
| 3689 | -const __tagged = (tag, sc) => { | |
| 3690 | - const out = new Uint8Array(sc.length + 1); | |
| 3691 | - out[0] = tag; | |
| 3692 | - out.set(sc, 1); | |
| 3693 | - return out; | |
| 3694 | -}; | |
| 3695 | -// ---- request-context confinement ------------------------------- | |
| 3696 | -// Workerd ties I/O objects to the IoContext of the event that made | |
| 3697 | -// them. Cells' equivalent: each dispatched event enters an | |
| 3698 | -// async-context frame (the same CPED the ALS rides, so it survives | |
| 3699 | -// awaits) carrying a context id. Stubs remember their owning | |
| 3700 | -// context and refuse to serialize elsewhere; pipeline nodes refuse | |
| 3701 | -// foreign awaits and calls -- each with Workerd's exact error. | |
| 3702 | -let __nextCtxId = 1; | |
| 3703 | -const __ctxKey = Symbol("celld.ctx"); | |
| 3704 | -const __ctxNow = () => { | |
| 3705 | - const frame = __als_get(); | |
| 3706 | - return frame === undefined ? undefined : frame.get(__ctxKey); | |
| 3707 | -}; | |
| 3708 | -// Run `fn` under context `id` (undefined = a fresh one). An async | |
| 3709 | -// fn started inside keeps the frame across its awaits. The prior | |
| 3710 | -// frame is cloned so user AsyncLocalStorage stores still flow into | |
| 3711 | -// same-isolate callees, as they did before contexts existed. | |
| 3712 | -const __ctxRun = (id, fn) => { | |
| 3713 | - const prior = __als_get(); | |
| 3714 | - const frame = new Map(prior); | |
| 3715 | - frame.set(__ctxKey, id ?? __nextCtxId++); | |
| 3716 | - __als_set(frame); | |
| 3717 | - try { | |
| 3718 | - return fn(); | |
| 3719 | - } finally { | |
| 3720 | - __als_set(prior); | |
| 3721 | - } | |
| 3722 | -}; | |
| 3723 | -const __ctxError = (kind) => new Error( | |
| 3724 | - "Cannot perform I/O on behalf of a different request. I/O " + | |
| 3725 | - "objects (such as streams, request/response bodies, and others) " + | |
| 3726 | - "created in the context of one request handler cannot be " + | |
| 3727 | - "accessed from a different request's handler. This is a " + | |
| 3728 | - "limitation of Cloudflare Workers which allows us to improve " + | |
| 3729 | - "overall performance. (I/O type: " + kind + ")"); | |
| 3730 | -// ---- abortable request contexts -------------------------------- | |
| 3731 | -// Workerd's ctx.abort(reason) on an entrypoint aborts the request's | |
| 3732 | -// IoContext: the in-flight call rejects with the reason, and stubs | |
| 3733 | -// the context holds are disposed (their disposal callbacks fire). | |
| 3734 | -// State is allocated only when a context first holds a stub handle | |
| 3735 | -// or aborts, so plain-data dispatch pays nothing; call paths gate | |
| 3736 | -// every abort lookup on `__abortedCtxs.size` (one field read). | |
| 3737 | -// Aborted ids stay recorded: a stub rooted in a dead context must | |
| 3738 | -// keep rejecting with the reason. | |
| 3739 | -const __abortedCtxs = new Map(); | |
| 3740 | -// An actor-flavored abort reason: in-flight ops reject with the | |
| 3741 | -// wrapped reason, later ops with Workerd's post-abort message | |
| 3742 | -// (upstream TODO(bug): should propagate the reason, but doesn't). | |
| 3743 | -class __ActorAbort { constructor(reason) { this.reason = reason; } } | |
| 3744 | -const __postAbortError = (aborted) => aborted instanceof __ActorAbort | |
| 3745 | - ? new Error("The execution context which hosts this callback " + | |
| 3746 | - "is no longer running.") | |
| 3747 | - : aborted; | |
| 3748 | -// ctx id -> Set of live stub handles (metas) the context holds. | |
| 3749 | -const __ctxStubs = new Map(); | |
| 3750 | -// ctx id -> Set of reject callbacks for stub ops in flight against | |
| 3751 | -// that context. A hung callee never settles, so a context abort | |
| 3752 | -// must reject its pending callers directly. | |
| 3753 | -const __ctxPendingOps = new Map(); | |
| 3754 | -const __opTrack = (ctx, reject) => { | |
| 3755 | - let set = __ctxPendingOps.get(ctx); | |
| 3756 | - if (set === undefined) __ctxPendingOps.set(ctx, set = new Set()); | |
| 3757 | - set.add(reject); | |
| 3758 | - return () => { | |
| 3759 | - set.delete(reject); | |
| 3760 | - if (set.size === 0) __ctxPendingOps.delete(ctx); | |
| 3761 | - }; | |
| 3762 | -}; | |
| 3763 | -const __ctxRegister = (meta) => { | |
| 3764 | - if (meta.ctx === undefined) return; | |
| 3765 | - let set = __ctxStubs.get(meta.ctx); | |
| 3766 | - if (set === undefined) __ctxStubs.set(meta.ctx, set = new Set()); | |
| 3767 | - set.add(meta); | |
| 3768 | -}; | |
| 3769 | -const __ctxUnregister = (meta) => { | |
| 3770 | - const set = __ctxStubs.get(meta.ctx); | |
| 3771 | - if (set === undefined) return; | |
| 3772 | - set.delete(meta); | |
| 3773 | - if (set.size === 0) __ctxStubs.delete(meta.ctx); | |
| 3774 | -}; | |
| 3775 | -// Tear down a context: dispose every handle it still holds, so a | |
| 3776 | -// dup() leaked into it reaches the sender's disposal callback. | |
| 3777 | -const __ctxEnd = (id) => { | |
| 3778 | - const set = __ctxStubs.get(id); | |
| 3779 | - if (set === undefined) return; | |
| 3780 | - __ctxStubs.delete(id); | |
| 3781 | - for (const meta of set) __disposeStub(meta); | |
| 3782 | -}; | |
| 3783 | -const __ctxAbort = (id, reason) => { | |
| 3784 | - if (id === undefined || __abortedCtxs.has(id)) return; | |
| 3785 | - const stored = reason === undefined | |
| 3786 | - ? new Error("The execution context has been aborted.") | |
| 3787 | - : reason; | |
| 3788 | - __abortedCtxs.set(id, stored); | |
| 3789 | - __ctxEnd(id); | |
| 3790 | - const pending = __ctxPendingOps.get(id); | |
| 3791 | - if (pending === undefined) return; | |
| 3792 | - __ctxPendingOps.delete(id); | |
| 3793 | - const live = | |
| 3794 | - stored instanceof __ActorAbort ? stored.reason : stored; | |
| 3795 | - for (const reject of pending) reject(live); | |
| 3796 | -}; | |
| 3797 | -// The entrypoint ctx.abort. Instances are cached across calls, so | |
| 3798 | -// the construction-time ctx cannot pin a request id (Workerd | |
| 3799 | -// constructs per request); the current frame's id at abort() time | |
| 3800 | -// is the request being served, which matches Workerd observably. | |
| 3801 | -const __ctxAbortCurrent = | |
| 3802 | - (reason) => __ctxAbort(__ctxNow(), reason); | |
| 3803 | -// ---- same-process RPC stubs ------------------------------------ | |
| 3804 | -// A stub entry owns a local target; `refs` counts live handles | |
| 3805 | -// across dup()s. When the last handle is disposed the target's own | |
| 3806 | -// Symbol.dispose runs (async, matching Workerd's disposal callback). | |
| 3807 | -// Stubs cross same-isolate transports only (same-script entrypoint | |
| 3808 | -// RPC and same-process routed dispatch); a marker revived elsewhere fails | |
| 3809 | -// loudly on use instead of aliasing an unrelated local entry. | |
| 3810 | -// `ctx` records the owning request context: the entry's for | |
| 3811 | -// running its target, the handle's for the serialize-elsewhere | |
| 3812 | -// check. | |
| 3813 | -const __stubEntries = new Map(); | |
| 3814 | -const __stubMeta = new WeakMap(); | |
| 3815 | -// Keep the Durable Object brand outside the user-visible object. Reading a | |
| 3816 | -// string property here would invoke an inherited getter before validation can | |
| 3817 | -// reject its unsupported prototype. | |
| 3818 | -const __doStubMeta = new WeakMap(); | |
| 3819 | -let __nextStubId = 1; | |
| 3820 | -const __stubIsolate = Math.random().toString(36).slice(2); | |
| 3821 | -const __newEntry = (target) => { | |
| 3822 | - // `scope` records the actor event that minted the entry (top of | |
| 3823 | - // the event stack at lift time), so an actor breakage can find | |
| 3824 | - // and abort the contexts hosting its exported stubs, and an op on | |
| 3825 | - // the stub can queue on that cell's input gate. `section` is the | |
| 3826 | - // critical section running at lift time, if any -- an op on this | |
| 3827 | - // stub re-enters it rather than queueing behind it. | |
| 3828 | - const scope = __currentActorScope() || undefined; | |
| 3829 | - const entry = { | |
| 3830 | - id: __nextStubId++, target, refs: 1, ctx: __ctxNow(), scope, | |
| 3831 | - section: __cellBlocks.get(scope)?.holder ?? null, | |
| 3832 | - }; | |
| 3833 | - __stubEntries.set(entry.id, entry); | |
| 3834 | - return entry; | |
| 3835 | -}; | |
| 3836 | -// Actors broken in JS: scope -> reason. Workerd's DO ctx.abort | |
| 3837 | -// rejects in-flight and future calls; when the abort fires under a | |
| 3838 | -// same-isolate stub caller, terminate_execution would unwind that | |
| 3839 | -// caller too (the routed dispatch re-enters the isolate), so the | |
| 3840 | -// breakage is recorded here instead: contexts hosting the actor's | |
| 3841 | -// exported stubs abort (in-flight ops reject with the reason, | |
| 3842 | -// later ops with the post-abort message) and RPC dispatch to the | |
| 3843 | -// scope rejects with the reason. Direct host-dispatched DO events | |
| 3844 | -// keep the uncatchable terminate_execution path. | |
| 3845 | -const __brokenActors = new Map(); | |
| 3846 | -const __actorBreak = (scope, reason) => { | |
| 3847 | - if (__brokenActors.has(scope)) return; | |
| 3848 | - __brokenActors.set(scope, reason); | |
| 3849 | - for (const entry of __stubEntries.values()) | |
| 3850 | - if (entry.scope === scope) | |
| 3851 | - __ctxAbort(entry.ctx, new __ActorAbort(reason)); | |
| 3852 | -}; | |
| 3853 | -// Everything this isolate holds for one cell scope that belongs to the | |
| 3854 | -// cell's residency rather than to the isolate, so a fresh instance | |
| 3855 | -// inherits none of it. `adopt_cell` calls this on both edges: the | |
| 3856 | -// give-back frees it, the take-in guarantees that no epoch spans. | |
| 3857 | -// Storage is not here -- `stop_cell` closes it host-side -- and sockets | |
| 3858 | -// live in the host registry, so a hibernated cell keeps them. | |
| 3859 | -const __cellRelease = (scope) => { | |
| 3860 | - __cell.instances[scope]?.ctx?.facets?._release(); | |
| 3861 | - delete __cell.instances[scope]; | |
| 3862 | - delete __cell.idNames[scope]; | |
| 3863 | - delete __cell.facetConfigs[scope]; | |
| 3864 | - __brokenActors.delete(scope); | |
| 3865 | - // An abandoned block can never run `__blockLeave`. A normal eviction | |
| 3866 | - // cannot abandon a block because its event keeps the cell in flight. A | |
| 3867 | - // stop that waits for nobody can, so the release drops every block record | |
| 3868 | - // together with the other state for this residency. | |
| 3869 | - __cellBlocks.delete(scope); | |
| 3870 | - // An entry holds `target`, which can be an object the released | |
| 3871 | - // instance owns. Dropping it ends that reachability; `released` is | |
| 3872 | - // what an already-revived handle reads, since it holds its entry | |
| 3873 | - // directly and never looks in this map again. | |
| 3874 | - for (const entry of __stubEntries.values()) { | |
| 3875 | - if (entry.scope !== scope) continue; | |
| 3876 | - entry.released = true; | |
| 3877 | - __stubEntries.delete(entry.id); | |
| 3878 | - // Break in-flight ops as an abort would, but not through | |
| 3879 | - // `__actorBreak`: that records the scope broken for the life of the | |
| 3880 | - // isolate, which is the state this function drops. | |
| 3881 | - __ctxAbort(entry.ctx, new __ActorAbort(__releasedStubError())); | |
| 3882 | - } | |
| 3883 | -}; | |
| 3884 | -const __releasedStubError = () => new Error( | |
| 3885 | - "The Durable Object that returned this RPC stub no longer runs on " + | |
| 3886 | - "this node."); | |
| 3887 | -const __disposeStub = (meta) => { | |
| 3888 | - if (meta.disposed) return; | |
| 3889 | - meta.disposed = true; | |
| 3890 | - __ctxUnregister(meta); | |
| 3891 | - const entry = meta.entry; | |
| 3892 | - if (--entry.refs > 0) return; | |
| 3893 | - __stubEntries.delete(entry.id); | |
| 3894 | - const disposer = entry.target?.[Symbol.dispose]; | |
| 3895 | - if (typeof disposer === "function") | |
| 3896 | - Promise.resolve().then(() => disposer.call(entry.target)); | |
| 3897 | -}; | |
| 3898 | -const __stubDisposedError = () => | |
| 3899 | - new Error("RPC stub used after being disposed."); | |
| 3900 | -// Shared brand value for RpcTarget instances; see the RpcTarget | |
| 3901 | -// constructor. | |
| 3902 | -const __rpcNoClone = () => {}; | |
| 3903 | -// Workerd method-visibility rules by target kind: an RpcTarget | |
| 3904 | -// exposes inherited methods/accessors (never own instance state, | |
| 3905 | -// never Object.prototype); a plain object or function exposes own | |
| 3906 | -// properties only. Property reads go through normal [[Get]] so | |
| 3907 | -// Proxy handlers participate, as in Workerd. | |
| 3908 | -const __rpcNoSuchMethod = (prop) => new TypeError( | |
| 3909 | - 'The RPC receiver does not implement the method "' + prop + '".'); | |
| 3910 | -// Bind through the intrinsic because a callable proxy can implement `.bind` | |
| 3911 | -// as a remote property. Reading that property can turn a valid named RPC | |
| 3912 | -// method into a non-function. Keep this rule shared by every RPC binding site. | |
| 3913 | -const __rpcBindMethod = (value, receiver) => | |
| 3914 | - Reflect.apply(Function.prototype.bind, value, [receiver]); | |
| 3915 | -const __stubResolve = (target, prop) => { | |
| 3916 | - if (target instanceof __cf.RpcTarget) { | |
| 3917 | - if (Object.hasOwn(target, prop) || !(prop in target) || | |
| 3918 | - prop in Object.prototype) throw __rpcNoSuchMethod(prop); | |
| 3919 | - } else if (!Object.hasOwn(target, prop)) { | |
| 3920 | - throw __rpcNoSuchMethod(prop); | |
| 3921 | - } | |
| 3922 | - const value = target[prop]; | |
| 3923 | - // Keep celld's own stubs and pipeline nodes unwrapped because the wrapper | |
| 3924 | - // would lose their metadata. | |
| 3925 | - return typeof value === "function" && !__stubMeta.has(value) && | |
| 3926 | - !(value instanceof __cf.RpcPromise) && | |
| 3927 | - !(value instanceof __cf.RpcProperty) | |
| 3928 | - ? __rpcBindMethod(value, target) : value; | |
| 3929 | -}; | |
| 3930 | -// ---- streams over RPC ------------------------------------------ | |
| 3931 | -// A live stream crosses as a handle in the caps table: the sender | |
| 3932 | -// locks the origin (reader/writer acquired at lift) behind a | |
| 3933 | -// bridge entry, and the receiver's endpoint is an ordinary | |
| 3934 | -// ReadableStream/WritableStream whose pulls and writes are stub | |
| 3935 | -// ops against the bridge -- one bounded reverse call per chunk, | |
| 3936 | -// the clone being the one wire copy. Backpressure is the op in | |
| 3937 | -// flight: hwm 0 pulls only on demand, and the writable carries | |
| 3938 | -// one chunk per op. EOF, close, and errors cross as op results; | |
| 3939 | -// teardown (param disposal, context end, context abort) runs the | |
| 3940 | -// bridge disposer, which cancels or aborts an unfinished origin | |
| 3941 | -// with Workerd's generic disconnect errors -- reasons do not | |
| 3942 | -// propagate, matching Workerd's own TODOs (and its verbatim | |
| 3943 | -// "endeded" typo). | |
| 3944 | -const __wsDisconnect = () => new Error( | |
| 3945 | - "WritableStream received over RPC was disconnected because " + | |
| 3946 | - "the remote execution context has endeded."); | |
| 3947 | -const __rsDisconnect = () => new Error( | |
| 3948 | - "ReadableStream received over RPC disconnected prematurely."); | |
| 3949 | -// Receiver wrapper stream -> its handle meta, for forwarding. | |
| 3950 | -const __rpcStreamMeta = new WeakMap(); | |
| 3951 | -const __readableBridge = (reader) => { | |
| 3952 | - const bridge = { | |
| 3953 | - done: false, | |
| 3954 | - async read() { | |
| 3955 | - let result; | |
| 3956 | - try { | |
| 3957 | - result = await reader.read(); | |
| 3958 | - } catch (error) { | |
| 3959 | - bridge.done = true; | |
| 3960 | - throw error; | |
| 3961 | - } | |
| 3962 | - if (result.done) bridge.done = true; | |
| 3963 | - return result; | |
| 3964 | - }, | |
| 3965 | - cancel() { | |
| 3966 | - if (bridge.done) return; | |
| 3967 | - bridge.done = true; | |
| 3968 | - reader.cancel(__rsDisconnect()).catch(() => {}); | |
| 3969 | - }, | |
| 3970 | - [Symbol.dispose]() { bridge.cancel(); }, | |
| 3971 | - }; | |
| 3972 | - return bridge; | |
| 3973 | -}; | |
| 3974 | -const __writableBridge = (writer) => { | |
| 3975 | - const bridge = { | |
| 3976 | - done: false, | |
| 3977 | - write: (chunk) => writer.write(chunk), | |
| 3978 | - close() { | |
| 3979 | - bridge.done = true; | |
| 3980 | - return writer.close(); | |
| 3981 | - }, | |
| 3982 | - abort() { | |
| 3983 | - bridge.done = true; | |
| 3984 | - return writer.abort(__wsDisconnect()); | |
| 3985 | - }, | |
| 3986 | - [Symbol.dispose]() { | |
| 3987 | - if (!bridge.done) bridge.abort().catch(() => {}); | |
| 3988 | - }, | |
| 3989 | - }; | |
| 3990 | - return bridge; | |
| 3991 | -}; | |
| 3992 | -const __liftStream = (v) => { | |
| 3993 | - const readable = v instanceof ReadableStream; | |
| 3994 | - const key = readable ? "__celld$rs" : "__celld$ws"; | |
| 3995 | - const meta = __rpcStreamMeta.get(v); | |
| 3996 | - if (meta !== undefined && !meta.disposed && !v.locked) { | |
| 3997 | - // Re-serializing a received, untouched stream forwards the | |
| 3998 | - // original handle: the reference moves (like a stub) and | |
| 3999 | - // the local wrapper is dead -- a round trip stays one hop. | |
| 4000 | - meta.disposed = true; | |
| 4001 | - __ctxUnregister(meta); | |
| 4002 | - return { [key]: meta.entry.id, t: __stubIsolate }; | |
| 4003 | - } | |
| 4004 | - if (v.locked) | |
| 4005 | - throw new TypeError(readable | |
| 4006 | - ? "The ReadableStream has been locked to a reader." | |
| 4007 | - : "The WritableStream has been locked to a writer."); | |
| 4008 | - const bridge = readable | |
| 4009 | - ? __readableBridge(v.getReader()) | |
| 4010 | - : __writableBridge(v.getWriter()); | |
| 4011 | - return { [key]: __newEntry(bridge).id, t: __stubIsolate }; | |
| 4012 | -}; | |
| 4013 | -// A signal is not a snapshot on the RPC wire. The marker carries a | |
| 4014 | -// process-wide identity, and the host forwards the source's single state | |
| 4015 | -// transition to every receiving isolate. A received signal keeps that | |
| 4016 | -// identity when an RPC forwards it again, so a chain does not add relays. | |
| 4017 | -const __rpcSignalMeta = new WeakMap(); | |
| 4018 | -const __rpcSignalReceivers = new Map(); | |
| 4019 | -const __rpcSignalSourceFinalizer = new FinalizationRegistry( | |
| 4020 | - (id) => __rpc_signal_release(id)); | |
| 4021 | -const __rpcSignalReceiverFinalizer = new FinalizationRegistry( | |
| 4022 | - ({ id, subscription }) => | |
| 4023 | - __rpc_signal_unsubscribe(id, subscription)); | |
| 4024 | -const __rpcSignalReasonOut = (reason) => { | |
| 4025 | - if (reason instanceof DOMException) | |
| 4026 | - return __sc_encode({ d: true, n: reason.name, m: reason.message }); | |
| 4027 | - try { | |
| 4028 | - return __sc_encode({ v: reason }); | |
| 4029 | - } catch { | |
| 4030 | - return __sc_encode({ v: new Error(String(reason)) }); | |
| 4031 | - } | |
| 4032 | -}; | |
| 4033 | -const __rpcSignalReasonIn = (bytes) => { | |
| 4034 | - const reason = __sc_decode(bytes); | |
| 4035 | - return reason.d | |
| 4036 | - ? new DOMException(reason.m, reason.n) | |
| 4037 | - : reason.v; | |
| 4038 | -}; | |
| 4039 | -const __rpcSignalSubscribe = (receiver) => { | |
| 4040 | - const signal = receiver.signal.deref(); | |
| 4041 | - if (signal === undefined) return false; | |
| 4042 | - const pending = __rpc_signal_wait(receiver.id); | |
| 4043 | - receiver.subscription = pending.__celldRpcSignalSubscription; | |
| 4044 | - pending.then((reason) => { | |
| 4045 | - const target = receiver.signal.deref(); | |
| 4046 | - if (target !== undefined && reason.byteLength !== 0) | |
| 4047 | - __abortSignal(target, __rpcSignalReasonIn(reason)); | |
| 4048 | - }); | |
| 4049 | - // A wait belongs to the request that installed it. A retained signal needs | |
| 4050 | - // a fresh wait in each later request, and its finalizer must unsubscribe the | |
| 4051 | - // newest one rather than the dead request's subscription. | |
| 4052 | - __rpcSignalReceiverFinalizer.unregister(receiver); | |
| 4053 | - __rpcSignalReceiverFinalizer.register(signal, receiver, receiver); | |
| 4054 | - return true; | |
| 4055 | -}; | |
| 4056 | -const __liftSignal = (signal) => { | |
| 4057 | - let meta = __rpcSignalMeta.get(signal); | |
| 4058 | - if (meta === undefined) { | |
| 4059 | - const id = __rpc_signal_new(); | |
| 4060 | - meta = { id }; | |
| 4061 | - __rpcSignalMeta.set(signal, meta); | |
| 4062 | - __rpcSignalSourceFinalizer.register(signal, id); | |
| 4063 | - if (signal.aborted) { | |
| 4064 | - __rpc_signal_abort(id, __rpcSignalReasonOut(signal.reason)); | |
| 4065 | - } else { | |
| 4066 | - signal.addEventListener("abort", (event) => { | |
| 4067 | - __rpc_signal_abort(id, | |
| 4068 | - __rpcSignalReasonOut(event.target.reason)); | |
| 4069 | - }, { once: true }); | |
| 4070 | - } | |
| 4071 | - } | |
| 4072 | - const marker = { "__celld$sig": meta.id, a: signal.aborted }; | |
| 4073 | - if (signal.aborted) marker.r = __rpcSignalReasonOut(signal.reason); | |
| 4074 | - return marker; | |
| 4075 | -}; | |
| 4076 | -const __rpcSignalRefresh = () => { | |
| 4077 | - for (const [id, receivers] of __rpcSignalReceivers) { | |
| 4078 | - const state = __rpc_signal_poll(id); | |
| 4079 | - const live = new Set(); | |
| 4080 | - for (const receiver of receivers) { | |
| 4081 | - const signal = receiver.signal.deref(); | |
| 4082 | - if (signal === undefined) continue; | |
| 4083 | - if (state instanceof Uint8Array) | |
| 4084 | - __abortSignal(signal, __rpcSignalReasonIn(state)); | |
| 4085 | - else if (state !== null && __rpcSignalSubscribe(receiver)) | |
| 4086 | - live.add(receiver); | |
| 4087 | - } | |
| 4088 | - if (live.size === 0 || state === null || state instanceof Uint8Array) | |
| 4089 | - __rpcSignalReceivers.delete(id); | |
| 4090 | - else | |
| 4091 | - __rpcSignalReceivers.set(id, live); | |
| 4092 | - } | |
| 4093 | -}; | |
| 4094 | -// Replace stub-able values with wire markers. Runs only after a | |
| 4095 | -// plain clone failed, so plain-data serialization never pays for | |
| 4096 | -// it. Passing an existing stub transfers its reference: the | |
| 4097 | -// sender's handle is disposed (dup() first to keep one) and the | |
| 4098 | -// receiver adopts it. Returns null when nothing was liftable. | |
| 4099 | -const __stubLift = (value, allowCapabilities = true, originals) => { | |
| 4100 | - let lifted = false; | |
| 4101 | - // Capabilities (stubs, disposers) root the callee context; | |
| 4102 | - // by-value host types do not -- they pick the 0x02 envelope. | |
| 4103 | - let caps = false; | |
| 4104 | - const seen = new Map(); | |
| 4105 | - const ctx = __ctxNow(); | |
| 4106 | - // A buffered body crosses as its bytes; a live-stream body | |
| 4107 | - // crosses as a stream handle (a capability, so the reply | |
| 4108 | - // roots its callee context and the pulls keep working). | |
| 4109 | - const liftBody = (v) => { | |
| 4110 | - if (v._bodyBytes !== null) return v._bodyBytes; | |
| 4111 | - caps = true; | |
| 4112 | - return __liftStream(v.body); | |
| 4113 | - }; | |
| 4114 | - const lift = (v) => { | |
| 4115 | - if (v === null || | |
| 4116 | - (typeof v !== "object" && typeof v !== "function")) return v; | |
| 4117 | - const cached = seen.get(v); | |
| 4118 | - if (cached !== undefined) return cached; | |
| 4119 | - const meta = __stubMeta.get(v); | |
| 4120 | - if (meta) { | |
| 4121 | - if (!allowCapabilities) return v; | |
| 4122 | - lifted = true; | |
| 4123 | - caps = true; | |
| 4124 | - if (meta.disposed) throw __stubDisposedError(); | |
| 4125 | - // A stub belongs to the request that received it; another | |
| 4126 | - // request cannot serialize it (Workerd's IoContext rule). | |
| 4127 | - if (meta.ctx !== ctx) throw __ctxError("Client"); | |
| 4128 | - meta.disposed = true; // the ref moves to the receiver | |
| 4129 | - __ctxUnregister(meta); | |
| 4130 | - const marker = { "__celld$stub": meta.entry.id, | |
| 4131 | - t: __stubIsolate, c: meta.callable }; | |
| 4132 | - seen.set(v, marker); | |
| 4133 | - return marker; | |
| 4134 | - } | |
| 4135 | - const svc = __svcMeta.get(v); | |
| 4136 | - if (svc !== undefined) { | |
| 4137 | - if (!allowCapabilities) return v; | |
| 4138 | - // A loopback service stub (ctx.exports): name + props cross | |
| 4139 | - // as plain data and revive as a fresh loopback stub. Props | |
| 4140 | - // are lifted too -- they may nest further stubs (Workerd's | |
| 4141 | - // nested channel tokens). | |
| 4142 | - lifted = true; | |
| 4143 | - caps = true; | |
| 4144 | - const marker = { "__celld$svc": svc.name, t: __stubIsolate }; | |
| 4145 | - seen.set(v, marker); | |
| 4146 | - if (svc.props !== undefined) marker.p = lift(svc.props); | |
| 4147 | - return marker; | |
| 4148 | - } | |
| 4149 | - // Workerd refuses to serialize its promise/property handles. | |
| 4150 | - if (v instanceof __cf.RpcPromise || v instanceof __cf.RpcProperty) | |
| 4151 | - throw new DOMException( | |
| 4152 | - 'Could not serialize object of type "' + | |
| 4153 | - (v instanceof __cf.RpcPromise ? "RpcPromise" : "RpcProperty") + | |
| 4154 | - '". This type does not support serialization.', | |
| 4155 | - "DataCloneError"); | |
| 4156 | - if (typeof v === "function" || v instanceof __cf.RpcTarget) { | |
| 4157 | - if (!allowCapabilities) return v; | |
| 4158 | - lifted = true; | |
| 4159 | - caps = true; | |
| 4160 | - const marker = { "__celld$stub": __newEntry(v).id, | |
| 4161 | - t: __stubIsolate, | |
| 4162 | - c: typeof v === "function" }; | |
| 4163 | - seen.set(v, marker); | |
| 4164 | - return marker; | |
| 4165 | - } | |
| 4166 | - const doId = __doStubMeta.get(v); | |
| 4167 | - if (doId !== undefined) { | |
| 4168 | - if (!allowCapabilities) return v; | |
| 4169 | - lifted = true; | |
| 4170 | - caps = true; | |
| 4171 | - const marker = { "__celld$do": doId._className, | |
| 4172 | - v: doId._value, n: v.name ?? null }; | |
| 4173 | - seen.set(v, marker); | |
| 4174 | - return marker; | |
| 4175 | - } | |
| 4176 | - // HTTP host types cross by value, as in Workerd's RPC | |
| 4177 | - // serialization: entry lists for Headers, the buffered bytes | |
| 4178 | - // for bodies (the marker aliases the live buffer; the clone | |
| 4179 | - // is the one wire copy), and no signal -- the receiver mints | |
| 4180 | - // a fresh one. A live stream body cannot cross yet. | |
| 4181 | - let marker; | |
| 4182 | - if (v instanceof Headers) { | |
| 4183 | - if (!allowCapabilities) return v; | |
| 4184 | - marker = { "__celld$hdr": [...v] }; | |
| 4185 | - } else if (v instanceof Blob) { | |
| 4186 | - if (!allowCapabilities) return v; | |
| 4187 | - marker = { "__celld$blob": v._bytes, y: v.type }; | |
| 4188 | - if (v instanceof File) { | |
| 4189 | - marker.n = v.name; | |
| 4190 | - marker.m = v.lastModified; | |
| 4191 | - } | |
| 4192 | - } else if (v instanceof Request) { | |
| 4193 | - if (!allowCapabilities) return v; | |
| 4194 | - marker = { "__celld$req": v.url, m: v.method, | |
| 4195 | - h: [...v.headers], r: v.redirect, c: v.cf, | |
| 4196 | - b: liftBody(v) }; | |
| 4197 | - } else if (v instanceof Response) { | |
| 4198 | - if (!allowCapabilities) return v; | |
| 4199 | - marker = { "__celld$res": v.status, | |
| 4200 | - t: v.statusText || | |
| 4201 | - __STATUS_TEXT[v.status] || "", | |
| 4202 | - h: [...v.headers], c: v.cf, | |
| 4203 | - e: v.type === "error", | |
| 4204 | - b: v.body === null ? null : liftBody(v) }; | |
| 4205 | - } else if (v instanceof ReadableStream || | |
| 4206 | - v instanceof WritableStream) { | |
| 4207 | - if (!allowCapabilities) return v; | |
| 4208 | - caps = true; | |
| 4209 | - marker = __liftStream(v); | |
| 4210 | - } else if (v instanceof AbortSignal) { | |
| 4211 | - marker = __liftSignal(v); | |
| 4212 | - } | |
| 4213 | - if (marker !== undefined) { | |
| 4214 | - lifted = true; | |
| 4215 | - seen.set(v, marker); | |
| 4216 | - return marker; | |
| 4217 | - } | |
| 4218 | - const proto = Object.getPrototypeOf(v); | |
| 4219 | - if (!Array.isArray(v) && | |
| 4220 | - proto !== Object.prototype && proto !== null) { | |
| 4221 | - // A Proxy emulating neither a plain object nor an RpcTarget | |
| 4222 | - // is Workerd's canonical proxy serialization error. | |
| 4223 | - if (__util_proxy_details(v) !== undefined) | |
| 4224 | - throw new DOMException( | |
| 4225 | - "Proxy could not be serialized because it is not a " + | |
| 4226 | - "valid RPC receiver type. The Proxy must emulate either " + | |
| 4227 | - "a plain object or an RpcTarget, as indicated by the " + | |
| 4228 | - "Proxy's prototype chain.", "DataCloneError"); | |
| 4229 | - return v; // host/other: leave to the clone | |
| 4230 | - } | |
| 4231 | - const out = Array.isArray(v) ? [] : {}; | |
| 4232 | - seen.set(v, out); | |
| 4233 | - for (const key of Object.keys(v)) out[key] = lift(v[key]); | |
| 4234 | - const disposerSource = originals?.get(v) ?? v; | |
| 4235 | - const disposer = disposerSource[Symbol.dispose]; | |
| 4236 | - if (allowCapabilities && !Array.isArray(v) && | |
| 4237 | - typeof disposer === "function") { | |
| 4238 | - lifted = true; | |
| 4239 | - caps = true; | |
| 4240 | - out["__celld$disp"] = | |
| 4241 | - __newEntry(__rpcBindMethod(disposer, disposerSource)).id; | |
| 4242 | - } | |
| 4243 | - return out; | |
| 4244 | - }; | |
| 4245 | - const tree = lift(value); | |
| 4246 | - return lifted ? { tree, caps } : null; | |
| 4247 | -}; | |
| 4248 | -// Revive host-type markers into real instances, adopting the wire | |
| 4249 | -// bytes directly -- no copy beyond the clone's own. | |
| 4250 | -const __reviveBlob = (marker, bytes) => { | |
| 4251 | - const blob = marker.n !== undefined | |
| 4252 | - ? new File([], marker.n, | |
| 4253 | - { type: marker.y, lastModified: marker.m }) | |
| 4254 | - : new Blob([], { type: marker.y }); | |
| 4255 | - blob._bytes = bytes; | |
| 4256 | - blob.size = bytes.byteLength; | |
| 4257 | - return blob; | |
| 4258 | -}; | |
| 4259 | -const __adoptBody = (target, bytes) => { | |
| 4260 | - target._bodyBytes = bytes; | |
| 4261 | - target._body = undefined; // decoded lazily on the first text()/json() | |
| 4262 | - const body = target.body; | |
| 4263 | - if (body !== null) { | |
| 4264 | - body._st.bytes = bytes; | |
| 4265 | - body.__celldBodyBytes = bytes; | |
| 4266 | - body._expectedLength = bytes.byteLength; | |
| 4267 | - } | |
| 4268 | -}; | |
| 4269 | -// A non-bytes `b` is a live-stream body marker: revive it and | |
| 4270 | -// let the constructor adopt it as a streaming body. | |
| 4271 | -const __reviveRequest = (marker, url, revive) => { | |
| 4272 | - if (!(marker.b instanceof Uint8Array)) | |
| 4273 | - return new Request(url, { method: marker.m, | |
| 4274 | - headers: marker.h, redirect: marker.r, cf: marker.c, | |
| 4275 | - body: revive(marker.b) }); | |
| 4276 | - const req = new Request(url, { method: marker.m, | |
| 4277 | - headers: marker.h, redirect: marker.r, cf: marker.c }); | |
| 4278 | - __adoptBody(req, marker.b); | |
| 4279 | - return req; | |
| 4280 | -}; | |
| 4281 | -const __reviveResponse = (marker, revive) => { | |
| 4282 | - const bytes = marker.b instanceof Uint8Array; | |
| 4283 | - const res = new Response( | |
| 4284 | - marker.b === null ? null : bytes ? "" : revive(marker.b), { | |
| 4285 | - status: marker["__celld$res"], statusText: marker.t, | |
| 4286 | - headers: marker.h, cf: marker.c }); | |
| 4287 | - if (bytes) __adoptBody(res, marker.b); | |
| 4288 | - if (marker.e) res.type = "error"; | |
| 4289 | - return res; | |
| 4290 | -}; | |
| 4291 | -// Wire a received stream handle to a local endpoint built with | |
| 4292 | -// the ordinary constructors -- nothing new threads through the | |
| 4293 | -// stream hot paths. Read errors surface as Workerd's generic | |
| 4294 | -// premature-disconnect; write errors propagate (Workerd sends | |
| 4295 | -// real errors back through the write loop). | |
| 4296 | -const __foreignStreamOp = () => Promise.reject(new Error( | |
| 4297 | - "RPC streams cannot cross isolate boundaries yet.")); | |
| 4298 | -const __reviveStream = (marker, id, readable, handles) => { | |
| 4299 | - const entry = marker.t === __stubIsolate | |
| 4300 | - ? __stubEntries.get(id) : undefined; | |
| 4301 | - if (entry === undefined) | |
| 4302 | - return readable | |
| 4303 | - ? new ReadableStream({ pull: __foreignStreamOp }) | |
| 4304 | - : new WritableStream({ write: __foreignStreamOp, | |
| 4305 | - close: __foreignStreamOp, abort: __foreignStreamOp }); | |
| 4306 | - const meta = { entry, disposed: false, ctx: __ctxNow() }; | |
| 4307 | - __ctxRegister(meta); | |
| 4308 | - handles.push(meta); | |
| 4309 | - const stream = readable | |
| 4310 | - ? new ReadableStream({ | |
| 4311 | - async pull(controller) { | |
| 4312 | - let result; | |
| 4313 | - try { | |
| 4314 | - result = await __stubOp(meta, ["read"], []); | |
| 4315 | - } catch { | |
| 4316 | - throw __rsDisconnect(); | |
| 4317 | - } | |
| 4318 | - if (result.done) controller.close(); | |
| 4319 | - else controller.enqueue(result.value); | |
| 4320 | - }, | |
| 4321 | - cancel: () => | |
| 4322 | - __stubOp(meta, ["cancel"], []).catch(() => {}), | |
| 4323 | - }, { highWaterMark: 0 }) | |
| 4324 | - : new WritableStream({ | |
| 4325 | - write: (chunk) => __stubOp(meta, ["write"], [chunk]), | |
| 4326 | - close: () => __stubOp(meta, ["close"], []), | |
| 4327 | - abort: () => | |
| 4328 | - __stubOp(meta, ["abort"], []).catch(() => {}), | |
| 4329 | - }); | |
| 4330 | - __rpcStreamMeta.set(stream, meta); | |
| 4331 | - return stream; | |
| 4332 | -}; | |
| 4333 | -const __reviveSignal = (marker, id) => { | |
| 4334 | - const controller = new AbortController(); | |
| 4335 | - const signal = controller.signal; | |
| 4336 | - __rpcSignalMeta.set(signal, { id }); | |
| 4337 | - if (marker.a) { | |
| 4338 | - controller.abort(__rpcSignalReasonIn(marker.r)); | |
| 4339 | - return controller.signal; | |
| 4340 | - } | |
| 4341 | - let receivers = __rpcSignalReceivers.get(id); | |
| 4342 | - if (receivers === undefined) { | |
| 4343 | - receivers = new Set(); | |
| 4344 | - __rpcSignalReceivers.set(id, receivers); | |
| 4345 | - } | |
| 4346 | - const receiver = { id, signal: new WeakRef(signal), subscription: null }; | |
| 4347 | - receivers.add(receiver); | |
| 4348 | - __rpcSignalSubscribe(receiver); | |
| 4349 | - return signal; | |
| 4350 | -}; | |
| 4351 | -// The inverse: markers become live handles. `handles` collects the | |
| 4352 | -// revived stubs (for call-end param disposal or result-tree | |
| 4353 | -// disposal); `disposers` collects remote Symbol.dispose entries. | |
| 4354 | -const __stubRevive = (value) => { | |
| 4355 | - const handles = []; | |
| 4356 | - const disposers = []; | |
| 4357 | - const seen = new Set(); | |
| 4358 | - const revive = (v) => { | |
| 4359 | - if (v === null || typeof v !== "object") return v; | |
| 4360 | - const stubId = v["__celld$stub"]; | |
| 4361 | - if (stubId !== undefined) { | |
| 4362 | - const entry = v.t === __stubIsolate | |
| 4363 | - ? __stubEntries.get(stubId) : undefined; | |
| 4364 | - const stub = entry === undefined | |
| 4365 | - ? __foreignStub() | |
| 4366 | - : __makeStub(entry, v.c); | |
| 4367 | - const meta = __stubMeta.get(stub); | |
| 4368 | - if (meta) handles.push(meta); | |
| 4369 | - return stub; | |
| 4370 | - } | |
| 4371 | - const svcName = v["__celld$svc"]; | |
| 4372 | - if (svcName !== undefined) | |
| 4373 | - return v.t === __stubIsolate | |
| 4374 | - ? __entrypointStub(svcName, revive(v.p)) | |
| 4375 | - : __foreignStub(); | |
| 4376 | - const doClass = v["__celld$do"]; | |
| 4377 | - if (doClass !== undefined) { | |
| 4378 | - const namespace = __cell.makeNamespace(doClass); | |
| 4379 | - return namespace.get( | |
| 4380 | - new DurableObjectId(doClass, v.v, v.n ?? undefined)); | |
| 4381 | - } | |
| 4382 | - const hdr = v["__celld$hdr"]; | |
| 4383 | - if (hdr !== undefined) return new Headers(hdr); | |
| 4384 | - const blobBytes = v["__celld$blob"]; | |
| 4385 | - if (blobBytes !== undefined) return __reviveBlob(v, blobBytes); | |
| 4386 | - const reqUrl = v["__celld$req"]; | |
| 4387 | - if (reqUrl !== undefined) | |
| 4388 | - return __reviveRequest(v, reqUrl, revive); | |
| 4389 | - if (v["__celld$res"] !== undefined) | |
| 4390 | - return __reviveResponse(v, revive); | |
| 4391 | - const rsId = v["__celld$rs"]; | |
| 4392 | - if (rsId !== undefined) | |
| 4393 | - return __reviveStream(v, rsId, true, handles); | |
| 4394 | - const wsId = v["__celld$ws"]; | |
| 4395 | - if (wsId !== undefined) | |
| 4396 | - return __reviveStream(v, wsId, false, handles); | |
| 4397 | - const sigId = v["__celld$sig"]; | |
| 4398 | - if (sigId !== undefined) return __reviveSignal(v, sigId); | |
| 4399 | - if (seen.has(v)) return v; | |
| 4400 | - seen.add(v); | |
| 4401 | - if (Array.isArray(v)) { | |
| 4402 | - for (let i = 0; i < v.length; i++) v[i] = revive(v[i]); | |
| 4403 | - return v; | |
| 4404 | - } | |
| 4405 | - const proto = Object.getPrototypeOf(v); | |
| 4406 | - if (proto !== Object.prototype && proto !== null) return v; | |
| 4407 | - for (const key of Object.keys(v)) { | |
| 4408 | - if (key === "__celld$disp") { | |
| 4409 | - const entry = __stubEntries.get(v[key]); | |
| 4410 | - if (entry) disposers.push(entry); | |
| 4411 | - delete v[key]; | |
| 4412 | - continue; | |
| 4413 | - } | |
| 4414 | - v[key] = revive(v[key]); | |
| 4415 | - } | |
| 4416 | - return v; | |
| 4417 | - }; | |
| 4418 | - return { value: revive(value), handles, disposers }; | |
| 4419 | -}; | |
| 4420 | -// A marker that crossed an isolate boundary: fail on use, loudly. | |
| 4421 | -const __foreignStub = () => new Proxy(function () {}, { | |
| 4422 | - get: (_b, prop) => { | |
| 4423 | - if (prop === "then" || typeof prop !== "string") return undefined; | |
| 4424 | - return () => Promise.reject(new Error( | |
| 4425 | - "RPC stubs cannot cross isolate boundaries yet.")); | |
| 4426 | - }, | |
| 4427 | - apply: () => Promise.reject(new Error( | |
| 4428 | - "RPC stubs cannot cross isolate boundaries yet.")), | |
| 4429 | -}); | |
| 4430 | -// Workerd's entrypoint method-visibility rules (worker-rpc.c++): | |
| 4431 | -// reserved lifecycle names are refused outright; only prototype | |
| 4432 | -// methods and accessors are visible -- never own instance state | |
| 4433 | -// (env/ctx live there) and never Object.prototype. | |
| 4434 | -const __entrypointReserved = new Set([ | |
| 4435 | - "constructor", "fetch", "connect", "alarm", "scheduled", | |
| 4436 | - "webSocketMessage", "webSocketClose", "webSocketError", "dup", | |
| 4437 | -]); | |
| 4438 | -const __entrypointResolve = (inst, prop) => { | |
| 4439 | - if (__entrypointReserved.has(prop)) | |
| 4440 | - throw new TypeError("'" + prop + | |
| 4441 | - "' is a reserved method and cannot be called over RPC."); | |
| 4442 | - if (Object.hasOwn(inst, prop) || !(prop in inst) || | |
| 4443 | - prop in Object.prototype) | |
| 4444 | - throw __rpcNoSuchMethod(prop); | |
| 4445 | - const value = inst[prop]; | |
| 4446 | - return typeof value === "function" && !__stubMeta.has(value) && | |
| 4447 | - !(value instanceof __cf.RpcPromise) && | |
| 4448 | - !(value instanceof __cf.RpcProperty) | |
| 4449 | - ? __rpcBindMethod(value, inst) : value; | |
| 4450 | -}; | |
| 4451 | -// A pipeline hop may continue only through plain data, functions, | |
| 4452 | -// RpcTargets, and stubs -- never through an RPC promise/property | |
| 4453 | -// handle or a class instance (Workerd's receiver rules). | |
| 4454 | -const __walkable = (v) => | |
| 4455 | - v instanceof __cf.RpcPromise || v instanceof __cf.RpcProperty | |
| 4456 | - ? false | |
| 4457 | - : typeof v === "function" || v instanceof __cf.RpcTarget || | |
| 4458 | - (typeof v === "object" && v !== null && | |
| 4459 | - (Object.getPrototypeOf(v) === Object.prototype || | |
| 4460 | - Array.isArray(v))); | |
| 4461 | -// Receiver-side pipeline walk: resolve `path` from `root`, then | |
| 4462 | -// GET the final member (`args` null) or CALL it. Errors name the | |
| 4463 | -// path walked so far, as Workerd's do. A stub mid-walk continues | |
| 4464 | -// against its own target, in the stub's owning context. | |
| 4465 | -const __rpcWalk = async (root, path, args, entrypointRoot) => { | |
| 4466 | - let value = root; | |
| 4467 | - for (let i = 0; i < path.length; i++) { | |
| 4468 | - const meta = __stubMeta.get(value); | |
| 4469 | - if (meta) { | |
| 4470 | - if (meta.disposed) throw __stubDisposedError(); | |
| 4471 | - const rest = path.slice(i); | |
| 4472 | - return await __ctxRun(meta.entry.ctx, | |
| 4473 | - () => __rpcWalk(meta.entry.target, rest, args, false)); | |
| 4474 | - } | |
| 4475 | - if (i > 0 && !__walkable(value)) | |
| 4476 | - throw __rpcNoSuchMethod(path[i - 1]); | |
| 4477 | - const prop = path[i]; | |
| 4478 | - const next = entrypointRoot && i === 0 | |
| 4479 | - ? __entrypointResolve(value, prop) | |
| 4480 | - : __stubResolve(value, prop); | |
| 4481 | - if (i === path.length - 1) { | |
| 4482 | - if (args === null) return next; | |
| 4483 | - if (typeof next !== "function") | |
| 4484 | - throw new TypeError( | |
| 4485 | - '"' + path.join(".") + '" is not a function.'); | |
| 4486 | - return next(...args); | |
| 4487 | - } | |
| 4488 | - if (next instanceof __cf.RpcPromise || | |
| 4489 | - next instanceof __cf.RpcProperty) | |
| 4490 | - throw __rpcNoSuchMethod(prop); | |
| 4491 | - value = next; | |
| 4492 | - } | |
| 4493 | - // An empty path applies the root itself (a callable stub). | |
| 4494 | - if (args === null) return value; | |
| 4495 | - if (typeof value !== "function") | |
| 4496 | - throw new TypeError("The RPC stub is not callable."); | |
| 4497 | - return value(...args); | |
| 4498 | -}; | |
| 4499 | -// One stub-mediated op: clone through the RPC envelope both ways, | |
| 4500 | -// so nested stubs, errors, and uncloneables behave exactly as a | |
| 4501 | -// dispatched call. Args serialize in the caller's context (its | |
| 4502 | -// stubs must be its own to transfer); the decode, the walk, and | |
| 4503 | -// the reply serialization run in the stub's owning context, so | |
| 4504 | -// stubs minted by the target belong to the target's context. | |
| 4505 | -// Params received by the target are disposed when the op ends | |
| 4506 | -// (Workerd's param-disposal rule). | |
| 4507 | -const __stubOp = (meta, path, args) => { | |
| 4508 | - if (meta.disposed) return Promise.reject(__stubDisposedError()); | |
| 4509 | - const entry = meta.entry; | |
| 4510 | - // The cell that minted this stub left residency, so `entry.target` | |
| 4511 | - // belongs to an instance this node released. The stub fails here | |
| 4512 | - // rather than calling into it. | |
| 4513 | - if (entry.released) return Promise.reject(__releasedStubError()); | |
| 4514 | - // A stub rooted in an aborted context is broken: reject with the | |
| 4515 | - // abort reason, before and after the dispatch (the target may | |
| 4516 | - // abort its own context mid-call). Gated on one field read. | |
| 4517 | - if (__abortedCtxs.size !== 0) { | |
| 4518 | - const aborted = __abortedCtxs.get(entry.ctx); | |
| 4519 | - if (aborted !== undefined) | |
| 4520 | - return Promise.reject(__postAbortError(aborted)); | |
| 4521 | - } | |
| 4522 | - const argsSc = args === null ? null : __rpcOut(args, true); | |
| 4523 | - const dispatch = (async () => { | |
| 4524 | - // Workerd delivers RPC asynchronously: the callee must not run | |
| 4525 | - // before the caller's synchronous code. A call made just after | |
| 4526 | - // a not-yet-delivered ctx.abort counts as in flight (rejects | |
| 4527 | - // with the reason, not the post-abort message). Bodies queue | |
| 4528 | - // in call order, so e-order holds. | |
| 4529 | - await null; | |
| 4530 | - // The cell that minted this stub gates it like any other event. | |
| 4531 | - // The op is dispatched inside the isolate and never becomes a | |
| 4532 | - // drive, so it is the one delivery point that has to ask here | |
| 4533 | - // rather than in Rust. A stub carrying the running critical | |
| 4534 | - // section re-enters it; everything else queues, and a section | |
| 4535 | - // that failed refuses what queued. | |
| 4536 | - const cell = entry.scope; | |
| 4537 | - if (cell !== undefined) { | |
| 4538 | - const block = __cellBlocks.get(cell); | |
| 4539 | - if (block !== undefined && (entry.section === null || | |
| 4540 | - entry.section !== block.holder)) | |
| 4541 | - await __gate_wait(cell); | |
| 4542 | - } | |
| 4543 | - const reply = await __ctxRun(entry.ctx, | |
| 4544 | - () => __rpcRun(async () => { | |
| 4545 | - const decoded = | |
| 4546 | - argsSc === null ? null : __rpcDesArgs(argsSc); | |
| 4547 | - try { | |
| 4548 | - return await __rpcWalk(entry.target, path, | |
| 4549 | - decoded === null ? null : decoded.args, false); | |
| 4550 | - } finally { | |
| 4551 | - if (decoded !== null) | |
| 4552 | - for (const handle of decoded.received) | |
| 4553 | - __disposeStub(handle); | |
| 4554 | - } | |
| 4555 | - }, true)); | |
| 4556 | - if (__abortedCtxs.size !== 0) { | |
| 4557 | - const aborted = __abortedCtxs.get(entry.ctx); | |
| 4558 | - if (aborted !== undefined) | |
| 4559 | - throw aborted instanceof __ActorAbort | |
| 4560 | - ? aborted.reason : aborted; | |
| 4561 | - } | |
| 4562 | - return __rpcDes(reply); | |
| 4563 | - })(); | |
| 4564 | - if (entry.ctx === undefined) return dispatch; | |
| 4565 | - // Race the op against its hosting context's abort: a hung callee | |
| 4566 | - // never settles, so the settlement check above cannot reach it. | |
| 4567 | - // A late settlement lands on an already-settled promise (no-op). | |
| 4568 | - return new Promise((resolve, reject) => { | |
| 4569 | - const untrack = __opTrack(entry.ctx, reject); | |
| 4570 | - dispatch.then( | |
| 4571 | - (value) => { untrack(); resolve(value); }, | |
| 4572 | - (error) => { untrack(); reject(error); }); | |
| 4573 | - }); | |
| 4574 | -}; | |
| 4575 | -// Resolve a path against a local, already-revived value. A hop | |
| 4576 | -// landing on a same-isolate stub delegates the rest of the path | |
| 4577 | -// to the stub's target; everything else is a plain [[Get]] so | |
| 4578 | -// Durable Object stubs and Proxies participate. | |
| 4579 | -const __walkLocal = (parent, path, args) => { | |
| 4580 | - for (let i = 0; i < path.length; i++) { | |
| 4581 | - const meta = __stubMeta.get(parent); | |
| 4582 | - if (meta) return __stubOp(meta, path.slice(i), args); | |
| 4583 | - const prop = path[i]; | |
| 4584 | - const member = parent == null ? undefined : parent[prop]; | |
| 4585 | - if (i < path.length - 1) { | |
| 4586 | - parent = member; | |
| 4587 | - continue; | |
| 4588 | - } | |
| 4589 | - if (args === null) return member; | |
| 4590 | - if (typeof member !== "function") { | |
| 4591 | - if (member === undefined) throw __rpcNoSuchMethod(prop); | |
| 4592 | - throw new TypeError('"' + prop + '" is not a function.'); | |
| 4593 | - } | |
| 4594 | - // [[Call]] directly: `.apply` on a stub proxy would be a | |
| 4595 | - // remote property access, not an invocation. | |
| 4596 | - return Reflect.apply(member, parent, args); | |
| 4597 | - } | |
| 4598 | - if (args === null) return parent; | |
| 4599 | - const meta = __stubMeta.get(parent); | |
| 4600 | - if (meta) return __stubOp(meta, [], args); | |
| 4601 | - if (typeof parent !== "function") | |
| 4602 | - throw new TypeError("The RPC value is not callable."); | |
| 4603 | - return parent(...args); | |
| 4604 | -}; | |
| 4605 | -// A session is one place pipeline ops resolve: the local value a | |
| 4606 | -// call returned, a same-isolate stub's target, or a named | |
| 4607 | -// entrypoint (whose paths resolve receiver-side in one op). | |
| 4608 | -const __valueSession = (promise) => ({ | |
| 4609 | - root: () => promise, | |
| 4610 | - get: (path) => promise.then((v) => __walkLocal(v, path, null)), | |
| 4611 | - call: (path, args) => | |
| 4612 | - promise.then((v) => __walkLocal(v, path, args)), | |
| 4613 | -}); | |
| 4614 | -const __stubSession = (meta) => ({ | |
| 4615 | - get: (path) => __stubOp(meta, path, null), | |
| 4616 | - call: (path, args) => __stubOp(meta, path, args), | |
| 4617 | -}); | |
| 4618 | -const __entrypointSession = (name, local, script, makeInst, propsSc) => ({ | |
| 4619 | - get: (path) => local | |
| 4620 | - ? (async () => __rpcDes( | |
| 4621 | - await __entrypointOp(name, path, null, true, makeInst)))() | |
| 4622 | - : (async () => __rpcDes( | |
| 4623 | - await __svc_rpc( | |
| 4624 | - script, name, JSON.stringify(path), null, propsSc)))(), | |
| 4625 | - call: (path, args) => (async () => { | |
| 4626 | - const argsSc = __rpcOut(args, local); | |
| 4627 | - if (local) | |
| 4628 | - return __rpcDes(await __entrypointOp( | |
| 4629 | - name, path, argsSc, true, makeInst)); | |
| 4630 | - return __rpcDes( | |
| 4631 | - await __svc_rpc( | |
| 4632 | - script, name, JSON.stringify(path), argsSc, propsSc)); | |
| 4633 | - })(), | |
| 4634 | -}); | |
| 4635 | -// Workerd's JsRpcPromise/JsRpcProperty: awaitable, callable, and | |
| 4636 | -// property access extends a path resolved at the far end, so | |
| 4637 | -// intermediates obey Workerd's receiver rules. `ctx` is the node's | |
| 4638 | -// owning request context -- null marks a context-free node (a | |
| 4639 | -// property path rooted directly at a service binding, which | |
| 4640 | -// starts a fresh session per await); a foreign context awaiting a | |
| 4641 | -// property or calling through the node gets Workerd's | |
| 4642 | -// cross-context error. Depth is capped like Workerd's | |
| 4643 | -// MAX_PROPERTY_DEPTH. | |
| 4644 | -const __makeNode = (session, path, ctx) => { | |
| 4645 | - let promise; | |
| 4646 | - const value = () => promise ??= (() => { | |
| 4647 | - if (path.length === 0) return session.root(); | |
| 4648 | - if (ctx !== null && ctx !== __ctxNow()) | |
| 4649 | - return Promise.reject(__ctxError("Pipeline")); | |
| 4650 | - return session.get(path); | |
| 4651 | - })(); | |
| 4652 | - const brand = | |
| 4653 | - path.length === 0 ? __cf.RpcPromise : __cf.RpcProperty; | |
| 4654 | - return new Proxy(function () {}, { | |
| 4655 | - getPrototypeOf: () => brand.prototype, | |
| 4656 | - get: (_b, p) => { | |
| 4657 | - if (p === "then") | |
| 4658 | - return (onOk, onErr) => value().then(onOk, onErr); | |
| 4659 | - if (p === "catch") return (onErr) => value().catch(onErr); | |
| 4660 | - if (p === "finally") | |
| 4661 | - return (onDone) => value().finally(onDone); | |
| 4662 | - if (typeof p !== "string") return undefined; | |
| 4663 | - if (path.length >= 5120) | |
| 4664 | - throw new TypeError( | |
| 4665 | - "RPC pipelined property chain is too deep."); | |
| 4666 | - return __makeNode(session, [...path, p], ctx); | |
| 4667 | - }, | |
| 4668 | - apply: (_b, _this, args) => { | |
| 4669 | - let call; | |
| 4670 | - if (ctx !== null && ctx !== __ctxNow()) { | |
| 4671 | - call = Promise.reject(__ctxError("JsRpcPromise")); | |
| 4672 | - call.catch(() => {}); | |
| 4673 | - } else { | |
| 4674 | - // Eager, so concurrent calls keep e-order. | |
| 4675 | - call = session.call(path, args); | |
| 4676 | - } | |
| 4677 | - return __makeNode( | |
| 4678 | - __valueSession(call), [], ctx ?? __ctxNow()); | |
| 4679 | - }, | |
| 4680 | - }); | |
| 4681 | -}; | |
| 4682 | -const __makeStub = (entry, callable) => { | |
| 4683 | - const meta = | |
| 4684 | - { entry, callable, disposed: false, ctx: __ctxNow() }; | |
| 4685 | - __ctxRegister(meta); | |
| 4686 | - const stub = new Proxy(function () {}, { | |
| 4687 | - getPrototypeOf: () => __cf.RpcStub.prototype, | |
| 4688 | - get: (_b, prop) => { | |
| 4689 | - if (prop === "then") return undefined; | |
| 4690 | - if (prop === Symbol.dispose) return () => __disposeStub(meta); | |
| 4691 | - if (prop === "dup") return () => { | |
| 4692 | - if (meta.disposed) throw __stubDisposedError(); | |
| 4693 | - entry.refs++; | |
| 4694 | - return __makeStub(entry, callable); | |
| 4695 | - }; | |
| 4696 | - if (typeof prop !== "string") return undefined; | |
| 4697 | - return __makeNode(__stubSession(meta), [prop], __ctxNow()); | |
| 4698 | - }, | |
| 4699 | - apply: (_b, _this, args) => __makeNode( | |
| 4700 | - __valueSession(__stubOp(meta, [], args)), [], __ctxNow()), | |
| 4701 | - }); | |
| 4702 | - __stubMeta.set(stub, meta); | |
| 4703 | - return stub; | |
| 4704 | -}; | |
| 4705 | -// A loopback service stub for one of this worker's own | |
| 4706 | -// entrypoints -- the ctx.exports surface. Calling the stub itself | |
| 4707 | -// returns a new stub carrying per-instance props, delivered to | |
| 4708 | -// the class constructor as ctx.props (Workerd's | |
| 4709 | -// ctx.exports.Name({ props })). | |
| 4710 | -const __svcMeta = new WeakMap(); | |
| 4711 | -const __entrypointStub = (name, props) => { | |
| 4712 | - let inst; | |
| 4713 | - const makeInst = props === undefined ? undefined : () => { | |
| 4714 | - if (inst !== undefined) return inst; | |
| 4715 | - const cls = __cell.entrypoints[name]; | |
| 4716 | - if (typeof cls !== "function") | |
| 4717 | - throw new TypeError( | |
| 4718 | - "The entrypoint " + name + " cannot carry props."); | |
| 4719 | - // Construction gets its own event, like a top-level invocation, and hands | |
| 4720 | - // that event's drain to the enclosing one. This runs inside the event of | |
| 4721 | - // the first method call on the stub, so a ctx.waitUntil() call in the | |
| 4722 | - // constructor drains before that call replies. | |
| 4723 | - inst = __constructEntrypoint(cls, props); | |
| 4724 | - return inst; | |
| 4725 | - }; | |
| 4726 | - const session = __entrypointSession(name, true, null, makeInst); | |
| 4727 | - const stub = new Proxy(function () {}, { | |
| 4728 | - getPrototypeOf: () => __cf.ServiceStub.prototype, | |
| 4729 | - get: (_b, prop) => { | |
| 4730 | - if (prop === "then") return undefined; | |
| 4731 | - if (typeof prop !== "string") return undefined; | |
| 4732 | - if (prop === "getRpcMethodForTestOnly") | |
| 4733 | - return (n) => __makeNode(session, [String(n)], null); | |
| 4734 | - return __makeNode(session, [prop], null); | |
| 4735 | - }, | |
| 4736 | - apply: (_b, _this, args) => | |
| 4737 | - __entrypointStub(name, args[0]?.props), | |
| 4738 | - }); | |
| 4739 | - __svcMeta.set(stub, { name, props }); | |
| 4740 | - __outboundMeta.set(stub, { | |
| 4741 | - script: __cell.script, | |
| 4742 | - entrypoint: name, | |
| 4743 | - props, | |
| 4744 | - }); | |
| 4745 | - return stub; | |
| 4746 | -}; | |
| 4747 | -// ---- stored stubs ---------------------------------------------- | |
| 4748 | -// Durable Object storage accepts only stubs with durable identity: | |
| 4749 | -// loopback service stubs (entrypoint name + props re-mint a fresh | |
| 4750 | -// stub on read) and Durable Object stubs (HMAC'd id + class revive | |
| 4751 | -// in any isolate). A transient handle -- a received RPC stub, a | |
| 4752 | -// function, an RpcTarget -- dies with its isolate; persisting its | |
| 4753 | -// entry id would revive garbage after a restart, so it is refused. | |
| 4754 | -// A stub-bearing row is written as 0x01 + clone(marker tree), off | |
| 4755 | -// the plain-clone fast path (the lift runs only after the plain | |
| 4756 | -// clone already threw, exactly like the RPC envelope). Reads hand | |
| 4757 | -// tagged rows to JS as [sentinel, tree]; the sentinel never leaves | |
| 4758 | -// this script and no user value can decode to it, so revival | |
| 4759 | -// cannot be spoofed by data shaped like a marker. | |
| 4760 | -const __storedSentinel = {}; | |
| 4761 | -const __storedLift = (value) => { | |
| 4762 | - let lifted = false; | |
| 4763 | - const seen = new Map(); | |
| 4764 | - const lift = (v) => { | |
| 4765 | - if (v === null || | |
| 4766 | - (typeof v !== "object" && typeof v !== "function")) return v; | |
| 4767 | - const cached = seen.get(v); | |
| 4768 | - if (cached !== undefined) return cached; | |
| 4769 | - // Ordering mirrors __stubLift: identify proxies by their | |
| 4770 | - // side tables and brands before touching any property -- a | |
| 4771 | - // stub or pipeline proxy answers every property read with a | |
| 4772 | - // fresh RpcProperty node. | |
| 4773 | - if (__stubMeta.has(v) || v instanceof __cf.RpcTarget) | |
| 4774 | - throw new DOMException( | |
| 4775 | - "Durable Object storage can only store stubs with " + | |
| 4776 | - "durable identity: service stubs from ctx.exports and " + | |
| 4777 | - "Durable Object stubs. This value is a transient RPC " + | |
| 4778 | - "handle that would not survive a restart.", | |
| 4779 | - "DataCloneError"); | |
| 4780 | - const svc = __svcMeta.get(v); | |
| 4781 | - if (svc !== undefined) { | |
| 4782 | - lifted = true; | |
| 4783 | - const marker = { "__celld$svc": svc.name }; | |
| 4784 | - seen.set(v, marker); | |
| 4785 | - if (svc.props !== undefined) marker.p = lift(svc.props); | |
| 4786 | - return marker; | |
| 4787 | - } | |
| 4788 | - if (v instanceof __cf.RpcPromise || | |
| 4789 | - v instanceof __cf.RpcProperty) | |
| 4790 | - throw new DOMException( | |
| 4791 | - 'Could not serialize object of type "' + | |
| 4792 | - (v instanceof __cf.RpcPromise ? "RpcPromise" : "RpcProperty") + | |
| 4793 | - '". This type does not support serialization.', | |
| 4794 | - "DataCloneError"); | |
| 4795 | - if (typeof v === "function") return v; // leave to the clone | |
| 4796 | - const doId = __doStubMeta.get(v); | |
| 4797 | - if (doId !== undefined) { | |
| 4798 | - lifted = true; | |
| 4799 | - const marker = { "__celld$do": doId._className, | |
| 4800 | - v: doId._value, n: v.name ?? null }; | |
| 4801 | - seen.set(v, marker); | |
| 4802 | - return marker; | |
| 4803 | - } | |
| 4804 | - if (Array.isArray(v)) { | |
| 4805 | - const out = []; | |
| 4806 | - seen.set(v, out); | |
| 4807 | - for (let i = 0; i < v.length; i++) out[i] = lift(v[i]); | |
| 4808 | - return out; | |
| 4809 | - } | |
| 4810 | - const proto = Object.getPrototypeOf(v); | |
| 4811 | - if (proto !== Object.prototype && proto !== null) | |
| 4812 | - return v; // host/other: leave to the clone | |
| 4813 | - const out = {}; | |
| 4814 | - seen.set(v, out); | |
| 4815 | - for (const key of Object.keys(v)) out[key] = lift(v[key]); | |
| 4816 | - return out; | |
| 4817 | - }; | |
| 4818 | - const tree = lift(value); | |
| 4819 | - return lifted ? tree : null; | |
| 4820 | -}; | |
| 4821 | -// Encode one stub-bearing value for storage. Rethrows the original | |
| 4822 | -// clone error when nothing was liftable, so plain uncloneables | |
| 4823 | -// fail exactly as they always did. | |
| 4824 | -const __storedBytes = (value, error) => { | |
| 4825 | - const tree = __storedLift(value); | |
| 4826 | - if (tree === null) throw error; | |
| 4827 | - return __tagged(1, __sc_encode(tree)); | |
| 4828 | -}; | |
| 4829 | -const __storedRevive = (value) => { | |
| 4830 | - const seen = new Set(); | |
| 4831 | - const revive = (v) => { | |
| 4832 | - if (v === null || typeof v !== "object") return v; | |
| 4833 | - const svcName = v["__celld$svc"]; | |
| 4834 | - if (svcName !== undefined) | |
| 4835 | - return __entrypointStub(svcName, revive(v.p)); | |
| 4836 | - const doClass = v["__celld$do"]; | |
| 4837 | - if (doClass !== undefined) | |
| 4838 | - return __cell.makeNamespace(doClass).get( | |
| 4839 | - new DurableObjectId(doClass, v.v, v.n ?? undefined)); | |
| 4840 | - if (seen.has(v)) return v; | |
| 4841 | - seen.add(v); | |
| 4842 | - if (Array.isArray(v)) { | |
| 4843 | - for (let i = 0; i < v.length; i++) v[i] = revive(v[i]); | |
| 4844 | - return v; | |
| 4845 | - } | |
| 4846 | - const proto = Object.getPrototypeOf(v); | |
| 4847 | - if (proto !== Object.prototype && proto !== null) return v; | |
| 4848 | - for (const key of Object.keys(v)) v[key] = revive(v[key]); | |
| 4849 | - return v; | |
| 4850 | - }; | |
| 4851 | - return revive(value); | |
| 4852 | -}; | |
| 4853 | -const __unwrapStored = (v) => | |
| 4854 | - Array.isArray(v) && v[0] === __storedSentinel | |
| 4855 | - ? __storedRevive(v[1]) : v; | |
| 4856 | -// A map result is wrapped as a whole only when it holds at least | |
| 4857 | -// one tagged row, so the per-entry walk never runs on plain data. | |
| 4858 | -const __unwrapStoredMap = (v) => { | |
| 4859 | - if (!Array.isArray(v) || v[0] !== __storedSentinel) return v; | |
| 4860 | - const map = v[1]; | |
| 4861 | - for (const [key, value] of map) | |
| 4862 | - map.set(key, __unwrapStored(value)); | |
| 4863 | - return map; | |
| 4864 | -}; | |
| 4865 | -// ctx.exports: loopback stubs for every exported entrypoint plus | |
| 4866 | -// this worker's Durable Object namespaces. Built once, on first | |
| 4867 | -// access -- ctx construction itself only carries the getter. | |
| 4868 | -let __ctxExportsCache; | |
| 4869 | -const __ctxExports = () => __ctxExportsCache ??= (() => { | |
| 4870 | - const out = {}; | |
| 4871 | - for (const name of Object.keys(__cell.entrypoints)) | |
| 4872 | - out[name] = __entrypointStub(name, undefined); | |
| 4873 | - for (const name of Object.keys(__cell.objectEntrypoints)) | |
| 4874 | - if (name !== "default") | |
| 4875 | - out[name] = __entrypointStub(name, undefined); | |
| 4876 | - for (const name of Object.keys(__cell.namespaceKeys)) | |
| 4877 | - out[name] = __cell.makeNamespace(name); | |
| 4878 | - return out; | |
| 4879 | -})(); | |
| 4880 | -// ---- RPC envelope ---------------------------------------------- | |
| 4881 | -// Serialize one payload. `lift` marks a same-isolate transport, | |
| 4882 | -// where stub-able values may cross as markers; elsewhere they stay | |
| 4883 | -// a DataCloneError, exactly as before stubs existed. | |
| 4884 | -const __rpcOut = (value, lift) => { | |
| 4885 | - const projected = __rpcProject(value); | |
| 4886 | - try { | |
| 4887 | - return __sc_encode(projected.tree); | |
| 4888 | - } catch (error) { | |
| 4889 | - // A cross-isolate call lifts only a live signal. A same-isolate call can | |
| 4890 | - // also transfer the existing host values and JS capability handles. | |
| 4891 | - const lifted = __stubLift(projected.tree, lift, projected.originals); | |
| 4892 | - if (lifted === null) throw __dataCloneError(error); | |
| 4893 | - try { | |
| 4894 | - return __tagged( | |
| 4895 | - lifted.caps ? 1 : 2, __sc_encode(lifted.tree)); | |
| 4896 | - } catch (error_) { | |
| 4897 | - throw __dataCloneError(error_); | |
| 4898 | - } | |
| 4899 | - } | |
| 4900 | -}; | |
| 4901 | -// A callee exception as tagged bytes: the Error crosses by value | |
| 4902 | -// (V8 serializes Error natively), custom own properties beside it. | |
| 4903 | -const __rpcErrOut = (error) => { | |
| 4904 | - // `name` rides in the props: V8 only round-trips the standard | |
| 4905 | - // Error subclass names, and e.g. DataCloneError must survive. | |
| 4906 | - const props = error instanceof Error | |
| 4907 | - ? { ...error, name: error.name } : {}; | |
| 4908 | - let sc; | |
| 4909 | - try { | |
| 4910 | - sc = __sc_encode([error, props]); | |
| 4911 | - } catch { | |
| 4912 | - const error_ = new Error(String(error?.message ?? error)); | |
| 4913 | - sc = __sc_encode([error_, { name: String(error?.name ?? "Error") }]); | |
| 4914 | - } | |
| 4915 | - return __tagged(0, sc); | |
| 4916 | -}; | |
| 4917 | -// The callee half of one RPC: run `body`, answer tagged bytes. | |
| 4918 | -const __rpcRun = async (body, lift) => { | |
| 4919 | - try { | |
| 4920 | - return __rpcOut(await body(), lift); | |
| 4921 | - } catch (error) { | |
| 4922 | - return __rpcErrOut(error); | |
| 4923 | - } | |
| 4924 | -}; | |
| 4925 | -const __rpcDesArgs = (bytes) => { | |
| 4926 | - if (bytes[0] === 0xff) | |
| 4927 | - return { args: __sc_decode(bytes), received: [] }; | |
| 4928 | - const revived = __stubRevive(__sc_decode(bytes.subarray(1))); | |
| 4929 | - return { args: revived.value, received: revived.handles }; | |
| 4930 | -}; | |
| 4931 | -// The caller half: decode a reply, rebuilding stubs and rethrowing | |
| 4932 | -// callee exceptions as real Errors with the callee's own | |
| 4933 | -// properties, `.remote`, and a local (caller-side) stack. | |
| 4934 | -const __rpcDes = (bytes) => { | |
| 4935 | - if (bytes[0] === 0xff) return __sc_decode(bytes); | |
| 4936 | - if (bytes[0] === 1 || bytes[0] === 2) { | |
| 4937 | - const { value, handles, disposers } = | |
| 4938 | - __stubRevive(__sc_decode(bytes.subarray(1))); | |
| 4939 | - if (value !== null && typeof value === "object" && | |
| 4940 | - !__stubMeta.has(value) && | |
| 4941 | - (handles.length > 0 || disposers.length > 0)) { | |
| 4942 | - Object.defineProperty(value, Symbol.dispose, { | |
| 4943 | - configurable: true, | |
| 4944 | - value: () => { | |
| 4945 | - for (const handle of handles) __disposeStub(handle); | |
| 4946 | - for (const entry of disposers) { | |
| 4947 | - __stubEntries.delete(entry.id); | |
| 4948 | - Promise.resolve().then(() => entry.target()); | |
| 4949 | - } | |
| 4950 | - }, | |
| 4951 | - }); | |
| 4952 | - } | |
| 4953 | - return value; | |
| 4954 | - } | |
| 4955 | - const [error, props] = __sc_decode(bytes.subarray(1)); | |
| 4956 | - if (error instanceof Error) { | |
| 4957 | - Object.assign(error, props); | |
| 4958 | - error.remote = true; | |
| 4959 | - const local = new Error().stack; | |
| 4960 | - error.stack = error.name + ": " + error.message + | |
| 4961 | - local.slice(local.indexOf("\n")); | |
| 4962 | - } | |
| 4963 | - throw error; | |
| 4964 | -}; | |
| 4965 | -// Deprecated Fetcher `get()`/`put()`/`delete()` HTTP helpers, kept by | |
| 4966 | -// the fetcher_has_get_put_delete compat flag (Workerd http.c++): | |
| 4967 | -// shortcuts for fetch() with the corresponding method. | |
| 4968 | -const __fetcherStatus = (res, method) => { | |
| 4969 | - if (res.status >= 200 && res.status < 300) return; | |
| 4970 | - throw new Error("HTTP " + method + " request failed: " + res.status + | |
| 4971 | - " " + (res.statusText || __STATUS_TEXT[res.status] || "")); | |
| 4972 | -}; | |
| 4973 | -const __fetcherHelper = (fetch, prop) => { | |
| 4974 | - if (prop === "get") return async (url, type) => { | |
| 4975 | - const res = await fetch(url, { method: "GET" }); | |
| 4976 | - if (res.status === 404 || res.status === 410) return null; | |
| 4977 | - __fetcherStatus(res, "GET"); | |
| 4978 | - if (type === "stream") | |
| 4979 | - return res.body ?? new ReadableStream({ start(c) { c.close(); } }); | |
| 4980 | - if (type === "arrayBuffer") return res.arrayBuffer(); | |
| 4981 | - if (type === "json") return res.json(); | |
| 4982 | - return res.text(); | |
| 4983 | - }; | |
| 4984 | - if (prop === "put") return async (url, body, options) => { | |
| 4985 | - const { expiration, expirationTtl } = options ?? {}; | |
| 4986 | - if (expiration !== undefined || expirationTtl !== undefined) { | |
| 4987 | - const url_ = new URL(url); | |
| 4988 | - if (expiration !== undefined) | |
| 4989 | - url_.searchParams.append("expiration", expiration); | |
| 4990 | - if (expirationTtl !== undefined) | |
| 4991 | - url_.searchParams.append("expiration_ttl", expirationTtl); | |
| 4992 | - url = url_.toString(); | |
| 4993 | - } | |
| 4994 | - __fetcherStatus(await fetch(url, { method: "PUT", body }), "PUT"); | |
| 4995 | - }; | |
| 4996 | - return async (url) => { | |
| 4997 | - __fetcherStatus(await fetch(url, { method: "DELETE" }), "DELETE"); | |
| 4998 | - }; | |
| 4999 | -}; | |
| 5000 | -function makeNamespace(className) { | |
| 5001 | - const namespaceKey = __cell.namespaceKeys[className]; | |
| 5002 | - if (typeof namespaceKey !== "string") | |
| 5003 | - throw new Error("no Durable Object namespace key for " + className); | |
| 5004 | - return new DurableObjectNamespace(className, namespaceKey); | |
| 5005 | -} | |
| 5006 | -// A named class: SDKs sniff bindings by constructor name (workers-rs | |
| 5007 | -// EnvBinding requires `constructor.name === "DurableObjectNamespace"`). | |
| 5008 | -class DurableObjectNamespace { | |
| 5009 | - constructor(className, namespaceKey) { | |
| 5010 | - Object.defineProperty(this, "_className", { value: className }); | |
| 5011 | - Object.defineProperty(this, "_namespaceKey", { value: namespaceKey }); | |
| 5012 | - } | |
| 5013 | - idFromName(name) { | |
| 5014 | - name = String(name); | |
| 5015 | - return new DurableObjectId( | |
| 5016 | - this._className, __do_id(this._namespaceKey, "name", name), name, | |
| 5017 | - ); | |
| 5018 | - } | |
| 5019 | - idFromString(value) { | |
| 5020 | - return new DurableObjectId( | |
| 5021 | - this._className, __do_id(this._namespaceKey, "validate", String(value)), | |
| 5022 | - ); | |
| 5023 | - } | |
| 5024 | - newUniqueId(options = {}) { | |
| 5025 | - const jurisdiction = options == null ? undefined : options.jurisdiction; | |
| 5026 | - if (jurisdiction != null) | |
| 5027 | - throw new Error("Jurisdiction restrictions are not implemented"); | |
| 5028 | - return new DurableObjectId( | |
| 5029 | - this._className, __do_id(this._namespaceKey, "unique", ""), | |
| 5030 | - ); | |
| 5031 | - } | |
| 5032 | - jurisdiction(value) { | |
| 5033 | - if (value == null) return this; | |
| 5034 | - throw new Error("Jurisdiction restrictions are not implemented"); | |
| 5035 | - } | |
| 5036 | - getByName(name, options) { | |
| 5037 | - return this.get(this.idFromName(name), options); | |
| 5038 | - } | |
| 5039 | - get(id) { | |
| 5040 | - const className = this._className; | |
| 5041 | - if (!(id instanceof DurableObjectId) || id._className !== className) | |
| 5042 | - throw new TypeError("Durable Object ID is not valid for this namespace"); | |
| 5043 | - const scope = id._scope(); | |
| 5044 | - // Emulate production: the actor recovers its name only when it is | |
| 5045 | - // <= 1024 UTF-8 bytes; longer names are dropped so ctx.id.name is | |
| 5046 | - // undefined. The full name still seeds the routing hash, so | |
| 5047 | - // dispatch is unchanged. Short names skip the byte count (< 256 | |
| 5048 | - // chars is always <= 1020 bytes) to keep the hot path alloc-free. | |
| 5049 | - const nm = id.name; | |
| 5050 | - const dispatchName = nm === undefined ? undefined | |
| 5051 | - : nm.length < 256 || new TextEncoder().encode(nm).length <= 1024 | |
| 5052 | - ? nm : undefined; | |
| 5053 | - if (dispatchName !== undefined) __cell.idNames[scope] = dispatchName; | |
| 5054 | - // Fetch and native RPC use the same host routing/activation seam. | |
| 5055 | - // Never expose `.then`: a DO stub is not itself a promise. | |
| 5056 | - const target = { id, name: dispatchName }; | |
| 5057 | - const abortMarker = "__CELLD_ACTOR_ABORT__:"; | |
| 5058 | - const processExitMarker = "__CELLD_PROCESS_EXIT__:"; | |
| 5059 | - let brokenReason = null; | |
| 5060 | - const invoke = async (operation) => { | |
| 5061 | - if (brokenReason !== null) throw new Error(brokenReason); | |
| 5062 | - try { | |
| 5063 | - return await operation(); | |
| 5064 | - } catch (error) { | |
| 5065 | - const routingError = __durableObjectRoutingError(error); | |
| 5066 | - if (routingError !== null) throw routingError; | |
| 5067 | - const message = String(error && error.message || error); | |
| 5068 | - const marker = [abortMarker, processExitMarker] | |
| 5069 | - .find((candidate) => message.includes(candidate)); | |
| 5070 | - if (!marker) throw error; | |
| 5071 | - brokenReason = message.slice(message.indexOf(marker) + marker.length); | |
| 5072 | - throw new Error(brokenReason); | |
| 5073 | - } | |
| 5074 | - }; | |
| 5075 | - const doFetch = async (input, init) => { | |
| 5076 | - const req = new Request(input, init); | |
| 5077 | - const signal = req._signalForSubrequests; | |
| 5078 | - if (signal?.aborted) throw signal.reason; | |
| 5079 | - // A body already backed by a host stream forwards to the cell as its | |
| 5080 | - // stream id, so a proxied upload to a cell on this node costs a chunk | |
| 5081 | - // rather than the whole body (#156). The host keeps it a stream for a | |
| 5082 | - // local cell and collects it only to sign a cross-node frame. A held | |
| 5083 | - // body -- or a stream with no host id -- crosses as its bytes. | |
| 5084 | - const bodyStreamId = | |
| 5085 | - req._bodyBytes === null && req.body && req.body.__celldStreamId !== undefined | |
| 5086 | - ? req.body.__celldStreamId | |
| 5087 | - : undefined; | |
| 5088 | - const body_ = bodyStreamId !== undefined | |
| 5089 | - ? new Uint8Array() | |
| 5090 | - : req._bodyBytes === null | |
| 5091 | - ? await req._consume() | |
| 5092 | - : req._bodyBytes; | |
| 5093 | - if (bodyStreamId !== undefined) { | |
| 5094 | - // The cell reads this upload through the same host stream id, so the | |
| 5095 | - // Worker's wrapper must not also read it: lock it (a late read throws | |
| 5096 | - // instead of racing the cell over one host stream) and mark it used, | |
| 5097 | - // which is what awaiting the old _consume() did and what workerd | |
| 5098 | - // reports as request.bodyUsed after the forward. | |
| 5099 | - req.bodyUsed = true; | |
| 5100 | - req.body.getReader(); | |
| 5101 | - } | |
| 5102 | - // Forward the request's headers to the cell as JSON. When they were | |
| 5103 | - // never materialized -- a Worker that only routes to a cell reads | |
| 5104 | - // none -- pass the raw header string straight through, so the whole | |
| 5105 | - // dispatch never builds a Headers object on either side. | |
| 5106 | - // | |
| 5107 | - // Both branches now carry the same shape. The raw string is the | |
| 5108 | - // wire list the host handed in, so the materialized branch must send | |
| 5109 | - // the header list too, not the iterator; see the note on the | |
| 5110 | - // outbound `fetch`. Reading `.headers` on a forwarded request used | |
| 5111 | - // to change what the cell received. | |
| 5112 | - const headersJson = req._headersJson !== undefined | |
| 5113 | - ? req._headersJson | |
| 5114 | - : JSON.stringify(req.headers.__celldHeaderList); | |
| 5115 | - const r = JSON.parse(await invoke(() => { | |
| 5116 | - if (!signal) return __do_call( | |
| 5117 | - scope, dispatchName ?? null, req.url, req.method, body_, | |
| 5118 | - headersJson, bodyStreamId, | |
| 5119 | - ); | |
| 5120 | - return __awaitCancellableDoCall( | |
| 5121 | - __do_call_cancellable( | |
| 5122 | - scope, dispatchName ?? null, req.url, req.method, body_, | |
| 5123 | - headersJson, bodyStreamId, | |
| 5124 | - ), | |
| 5125 | - signal, | |
| 5126 | - ); | |
| 5127 | - })); | |
| 5128 | - const body = r.streamId !== undefined | |
| 5129 | - ? new CelldHttpBodyStream(r.streamId) | |
| 5130 | - : r.body !== undefined | |
| 5131 | - ? r.body | |
| 5132 | - : Uint8Array.from(r.bodyBytes || []); | |
| 5133 | - // An upgrade the cell answered with. The pair straddles two isolates, | |
| 5134 | - // so the client end cannot be the peer object itself -- it is a new | |
| 5135 | - // socket the host joins to the cell's on `accept()`. A caller that | |
| 5136 | - // returns this response instead of accepting keeps the direct route | |
| 5137 | - // `__wsTarget` already describes, and binds nothing. | |
| 5138 | - return new Response(body, { | |
| 5139 | - status: r.status, | |
| 5140 | - headers: r.headers, | |
| 5141 | - __wsTarget: r.wsTarget, | |
| 5142 | - webSocket: r.status === 101 && r.wsTarget | |
| 5143 | - ? new WebSocket(undefined, [], r.wsTarget) | |
| 5144 | - : undefined, | |
| 5145 | - }); | |
| 5146 | - }; | |
| 5147 | - const stub = new Proxy(target, { get: (_target, prop) => { | |
| 5148 | - if (prop === "then") return undefined; | |
| 5149 | - if (Reflect.has(_target, prop)) return Reflect.get(_target, prop); | |
| 5150 | - if (prop === "fetch") return doFetch; | |
| 5151 | - if (typeof prop !== "string") return undefined; | |
| 5152 | - if (__cell.compat.fetcherGetPutDelete && | |
| 5153 | - (prop === "get" || prop === "put" || prop === "delete")) | |
| 5154 | - return __fetcherHelper(doFetch, prop); | |
| 5155 | - // Every cell RPC goes out through the host, whichever node owns the | |
| 5156 | - // target. Same-process dispatch re-enters this isolate, where the | |
| 5157 | - // abort and exit markers revive; bytes that land elsewhere revive as | |
| 5158 | - // loud foreign stubs. | |
| 5159 | - return async (...args) => invoke( | |
| 5160 | - async () => __rpcDes(await __rpc_call( | |
| 5161 | - scope, dispatchName ?? null, prop, __rpcOut(args, true), | |
| 5162 | - )), | |
| 5163 | - ); | |
| 5164 | - }}); | |
| 5165 | - __doStubMeta.set(stub, id); | |
| 5166 | - return stub; | |
| 5167 | - } | |
| 5168 | -} | |
| 5169 | -const __attachResponseRequestCancellation = ( | |
| 5170 | - response, | |
| 5171 | - requestController, | |
| 5172 | - wrapBody, | |
| 5173 | -) => { | |
| 5174 | - if (!(response instanceof Response) || | |
| 5175 | - response._bodyBytes !== null || | |
| 5176 | - response.body === null) { | |
| 5177 | - return; | |
| 5178 | - } | |
| 5179 | - const requestControllers = Array.isArray( | |
| 5180 | - response.__celldRequestControllers, | |
| 5181 | - ) | |
| 5182 | - ? response.__celldRequestControllers | |
| 5183 | - : [requestController]; | |
| 5184 | - if (requestControllers !== response.__celldRequestControllers) { | |
| 5185 | - Object.defineProperty(response, "__celldRequestControllers", { | |
| 5186 | - value: requestControllers, | |
| 5187 | - }); | |
| 5188 | - } else { | |
| 5189 | - requestControllers.push(requestController); | |
| 5190 | - } | |
| 5191 | - if (!wrapBody || response.__celldCancellationWrapped) return; | |
| 5192 | - const reader = response.body.getReader(); | |
| 5193 | - response.body = new ReadableStream({ | |
| 5194 | - async pull(controller) { | |
| 5195 | - const result = await reader.read(); | |
| 5196 | - if (result.done) controller.close(); | |
| 5197 | - else controller.enqueue(result.value); | |
| 5198 | - }, | |
| 5199 | - async cancel() { | |
| 5200 | - const reason = new Error("The client has disconnected"); | |
| 5201 | - for (const controller of requestControllers) { | |
| 5202 | - if (!controller.signal.aborted) controller.abort(reason); | |
| 5203 | - } | |
| 5204 | - try { | |
| 5205 | - await reader.cancel(reason); | |
| 5206 | - } catch {} | |
| 5207 | - }, | |
| 5208 | - }, { highWaterMark: 0 }); | |
| 5209 | - Object.defineProperty(response, "__celldCancellationWrapped", { | |
| 5210 | - value: true, | |
| 5211 | - }); | |
| 5212 | -}; | |
| 5213 | -// called on the owner node by the /__do/<scope> endpoint: run one object. | |
| 5214 | -// Returns the Response; Rust's read_response unwraps it (don't double-wrap). | |
| 5215 | -// A top-level (non-actor) request whose signal can be aborted by id, so a | |
| 5216 | -// disconnected HTTP or service-binding caller reaches the target's | |
| 5217 | -// `request.signal`. | |
| 5218 | -// A large body, or a body of unknown length, arrives as a stream id and | |
| 5219 | -// not as bytes. The handler then pulls the body off the socket as it | |
| 5220 | -// reads, so the whole body is never resident. `request.body` is a stream | |
| 5221 | -// in both cases. | |
| 5222 | -__celld.__makeIncomingRequest = ( | |
| 5223 | - url, method, body, headersJson, streamId, | |
| 5224 | -) => __makeRequest( | |
| 5225 | - url, method, | |
| 5226 | - streamId === undefined ? body : new CelldHttpBodyStream(streamId), | |
| 5227 | - headersJson, undefined, true); | |
| 5228 | -const __dispatchTo = __celld.__dispatchTo = async ( | |
| 5229 | - scope, url, method, body, headersJson, requestId = null, bodyStreamId = null, | |
| 5230 | -) => { | |
| 5231 | - // A routed body that must not be collected crosses as a host stream id; the | |
| 5232 | - // handler here reads it in parts. A held body arrives as its bytes. | |
| 5233 | - if (bodyStreamId !== null) body = new CelldHttpBodyStream(bodyStreamId); | |
| 5234 | - // Request already allocates a default controller for an absent signal. | |
| 5235 | - // Retain that same allocation so a streamed response can report reader | |
| 5236 | - // cancellation after the handler has returned. | |
| 5237 | - const requestController = new AbortController(); | |
| 5238 | - if (requestId !== null) | |
| 5239 | - __incomingRequestSignals.set( | |
| 5240 | - String(requestId), requestController.signal); | |
| 5241 | - const actorEvent = __beginActorEvent(scope); | |
| 5242 | - try { | |
| 5243 | - const dispatch = (async () => { | |
| 5244 | - const inst = await _readyInstance(scope); | |
| 5245 | - return await __ctxRun(undefined, () => inst.fetch( | |
| 5246 | - __makeRequest( | |
| 5247 | - url, | |
| 5248 | - method, | |
| 5249 | - body, | |
| 5250 | - headersJson, | |
| 5251 | - requestController.signal, | |
| 5252 | - true, | |
| 5253 | - ))); | |
| 5254 | - })(); | |
| 5255 | - // The caller's abandonment reaches the target through | |
| 5256 | - // __do_call_cancel/__abortIncomingRequest, which aborts the fresh incoming | |
| 5257 | - // signal made above; the host dispatcher passes no caller signal here. | |
| 5258 | - const response = await dispatch; | |
| 5259 | - // Not wrapped: the host holds this response and gates it, and the caller | |
| 5260 | - // that would cancel the body reaches it through the routed channel's own | |
| 5261 | - // controller rather than this one. | |
| 5262 | - __attachResponseRequestCancellation(response, requestController, false); | |
| 5263 | - if (response instanceof Response && response.status === 101 && | |
| 5264 | - response.webSocket && !response.webSocket._target) { | |
| 5265 | - const socket = response.webSocket._peer; | |
| 5266 | - const target = { id: response.webSocket._id, scope }; | |
| 5267 | - response.webSocket._target = target; | |
| 5268 | - if (socket) { | |
| 5269 | - socket._target = target; | |
| 5270 | - if (!socket._hibernatable) | |
| 5271 | - __ws_accept_regular(socket._id, scope); | |
| 5272 | - __sockets.set(socket._id, socket); | |
| 5273 | - socket._flushPending(); | |
| 5274 | - } | |
| 5275 | - } | |
| 5276 | - return response; | |
| 5277 | - } finally { | |
| 5278 | - if (requestId !== null) | |
| 5279 | - __incomingRequestSignals.delete(String(requestId)); | |
| 5280 | - __endActorEvent(actorEvent); | |
| 5281 | - } | |
| 5282 | -}; | |
| 5283 | -const __rpcTargetMethod = async (scope, method) => { | |
| 5284 | - const inst = await _readyInstance(scope); | |
| 5285 | - if (!inst.__celldState._rpcOk) | |
| 5286 | - throw new TypeError( | |
| 5287 | - "The receiving Durable Object does not support RPC, because " + | |
| 5288 | - "its class was not declared with `extends DurableObject`. In " + | |
| 5289 | - "order to enable RPC, make sure your class extends the " + | |
| 5290 | - "special class `DurableObject`, which can be imported from " + | |
| 5291 | - "the module \"cloudflare:workers\"."); | |
| 5292 | - const fn = inst[method]; | |
| 5293 | - if (typeof fn !== "function") | |
| 5294 | - throw new TypeError(method + " is not a function"); | |
| 5295 | - return [inst, fn]; | |
| 5296 | -}; | |
| 5297 | -// The byte path always lifts stub-able values into the reply: the | |
| 5298 | -// markers carry the isolate token, so they revive only back in this | |
| 5299 | -// isolate (same-process routed dispatch re-enters it) and fail loudly | |
| 5300 | -// on use anywhere else. Callee exceptions cross in | |
| 5301 | -// the error envelope on every flavor. | |
| 5302 | -__celld.__dispatchRpc = async (scope, method, args) => { | |
| 5303 | - const actorEvent = __beginActorEvent(scope); | |
| 5304 | - try { | |
| 5305 | - // A string is the legacy JSON flavor; bytes are V8 structured clone. | |
| 5306 | - // Answer in kind. | |
| 5307 | - if (typeof args === "string") { | |
| 5308 | - const [inst, fn] = await __rpcTargetMethod(scope, method); | |
| 5309 | - const result = await fn.apply(inst, JSON.parse(args)); | |
| 5310 | - return JSON.stringify(result) ?? "null"; | |
| 5311 | - } | |
| 5312 | - return await __ctxRun(undefined, () => (async () => { | |
| 5313 | - const decoded = __rpcDesArgs(args); | |
| 5314 | - try { | |
| 5315 | - return await __rpcRun(async () => { | |
| 5316 | - // A broken actor (JS-flavored ctx.abort) rejects every | |
| 5317 | - // later call with the reason. One gated field read. | |
| 5318 | - if (__brokenActors.size !== 0) { | |
| 5319 | - const broken = __brokenActors.get(scope); | |
| 5320 | - if (broken !== undefined) throw broken; | |
| 5321 | - } | |
| 5322 | - const [inst, fn] = await __rpcTargetMethod(scope, method); | |
| 5323 | - return fn.apply(inst, decoded.args); | |
| 5324 | - }, true); | |
| 5325 | - } finally { | |
| 5326 | - for (const handle of decoded.received) __disposeStub(handle); | |
| 5327 | - } | |
| 5328 | - })()); | |
| 5329 | - } finally { | |
| 5330 | - __endActorEvent(actorEvent); | |
| 5331 | - } | |
| 5332 | -}; | |
| 5333 | -const __entrypointClass = (name) => { | |
| 5334 | - const cls = __cell.entrypoints[name]; | |
| 5335 | - if (typeof cls !== "function") { | |
| 5336 | - // Workerd getExportedHandler(): distinguish a Durable Object class | |
| 5337 | - // misused as a stateless entrypoint from a name that resolves to | |
| 5338 | - // nothing. Error path only; both lookups are O(1). | |
| 5339 | - if (__cell.classes[name] !== undefined || __cell.doExports[name]) | |
| 5340 | - throw new TypeError( | |
| 5341 | - `The entrypoint name ${name} refers to a Durable Object ` + | |
| 5342 | - "class, but the incoming request is trying to invoke it as " + | |
| 5343 | - "a stateless worker."); | |
| 5344 | - throw new TypeError( | |
| 5345 | - `The entrypoint name ${name} was not found in this worker. ` + | |
| 5346 | - "Ensure the worker exports an entrypoint with that name."); | |
| 5347 | - } | |
| 5348 | - return cls; | |
| 5349 | -}; | |
| 5350 | -// End the construction event immediately: ctx.waitUntil registers into | |
| 5351 | -// whichever event is current at call time, so leaving this event on the | |
| 5352 | -// stack would swallow every later registration in the isolate. The drain that | |
| 5353 | -// the event yields moves to the enclosing event, because a ctx.waitUntil() | |
| 5354 | -// call inside a constructor is otherwise fire-and-forget: the RPC reply can | |
| 5355 | -// answer and the request context can tear down before that work runs. | |
| 5356 | -// __wait_until drops the drain when no event encloses this one, which is the | |
| 5357 | -// isolate-startup case and matches the older behavior. | |
| 5358 | -const __constructEntrypoint = (cls, props) => { | |
| 5359 | - const ctx = __beginEvent(props); | |
| 5360 | - try { | |
| 5361 | - return new cls(ctx, __cell.env); | |
| 5362 | - } finally { | |
| 5363 | - const drain = __endEvent(); | |
| 5364 | - if (drain !== null) __wait_until(drain); | |
| 5365 | - } | |
| 5366 | -}; | |
| 5367 | -// A stateless Worker invocation owns one class instance and its constructor | |
| 5368 | -// context. Reusing either across invocations leaks class fields and request | |
| 5369 | -// authority, while constructing more than once inside one invocation splits | |
| 5370 | -// work that Cloudflare delivers to one receiver. | |
| 5371 | -const __newEntrypointInstance = (name, props) => | |
| 5372 | - __constructEntrypoint(__entrypointClass(name), props); | |
| 5373 | -// `env.NAME.fetch()` where NAME is bound with `entrypoint = "..."` goes | |
| 5374 | -// to that class's fetch, not the module's default export. A plain | |
| 5375 | -// object export (Workerd's non-class entrypoint) dispatches its | |
| 5376 | -// handler functions as fn(arg, env, ctx). | |
| 5377 | -// A missing fetch reports workerd's own text, the same one the loader | |
| 5378 | -// installs for a Worker with no default export, so the two paths agree. | |
| 5379 | -const __noHandler = (name, method) => | |
| 5380 | - method === "fetch" && name === "default" | |
| 5381 | - ? new Error("Handler does not export a fetch() function.") | |
| 5382 | - : new TypeError( | |
| 5383 | - `Entrypoint ${JSON.stringify(name)} has no ${method} handler`); | |
| 5384 | - | |
| 5385 | -const __dispatchEntrypointMethod = async (name, method, arg, props) => { | |
| 5386 | - const handler = __cell.objectEntrypoints[name]; | |
| 5387 | - if (handler !== undefined) { | |
| 5388 | - if (typeof handler[method] !== "function") | |
| 5389 | - throw __noHandler(name, method); | |
| 5390 | - const ctx = __beginEvent(props); | |
| 5391 | - try { | |
| 5392 | - return await __ctxRun(undefined, | |
| 5393 | - () => handler[method](arg, __cell.env, ctx)); | |
| 5394 | - } finally { | |
| 5395 | - __endEvent(); | |
| 5396 | - } | |
| 5397 | - } | |
| 5398 | - // A class entrypoint's methods get env and ctx from its constructor, | |
| 5399 | - // not as arguments. | |
| 5400 | - const inst = __newEntrypointInstance(name, props); | |
| 5401 | - if (typeof inst[method] !== "function") | |
| 5402 | - throw __noHandler(name, method); | |
| 5403 | - return await __ctxRun(undefined, () => inst[method](arg)); | |
| 5404 | -}; | |
| 5405 | -// Invoke a handler inside the event frame that the host already opened. A | |
| 5406 | -// Queue dispatch uses this form because its host driver must receive and keep | |
| 5407 | -// driving the handler's waitUntil aggregate after the settlement is returned. | |
| 5408 | -const __dispatchEntrypointMethodInCurrentEvent = async (name, method, arg) => { | |
| 5409 | - const handler = __cell.objectEntrypoints[name]; | |
| 5410 | - if (handler !== undefined) { | |
| 5411 | - if (typeof handler[method] !== "function") | |
| 5412 | - throw __noHandler(name, method); | |
| 5413 | - return await __ctxRun(undefined, | |
| 5414 | - () => handler[method](arg, __cell.env, __entrypointContext())); | |
| 5415 | - } | |
| 5416 | - const inst = __newEntrypointInstance(name, undefined); | |
| 5417 | - if (typeof inst[method] !== "function") | |
| 5418 | - throw __noHandler(name, method); | |
| 5419 | - return await __ctxRun(undefined, () => inst[method](arg)); | |
| 5420 | -}; | |
| 5421 | -const __dispatchEntrypointFetch = __celld.__dispatchEntrypointFetch = | |
| 5422 | - (name, request, propsSc = null) => | |
| 5423 | - __dispatchEntrypointMethod( | |
| 5424 | - name, "fetch", request, | |
| 5425 | - propsSc === null || propsSc.length === 0 | |
| 5426 | - ? undefined : __sc_decode(propsSc)); | |
| 5427 | -__celld.__dispatchEntrypointScheduled = (name, ctrl) => | |
| 5428 | - __dispatchEntrypointMethod(name, "scheduled", ctrl); | |
| 5429 | -// A queue batch owns mutable settlement state only while its handler runs. | |
| 5430 | -// Keeping a batch alive after dispatch must not keep authority to settle its | |
| 5431 | -// lease, because that lease can have expired and been handed out again. | |
| 5432 | -__celld.__dispatchEntrypointQueue = async (name, incoming) => { | |
| 5433 | - let active = true; | |
| 5434 | - let ackAll = false; | |
| 5435 | - const explicitAcks = new Set(); | |
| 5436 | - const retries = new Map(); | |
| 5437 | - const retryBatch = { retry: false, delaySeconds: undefined }; | |
| 5438 | - const checkActive = () => { | |
| 5439 | - if (!active) | |
| 5440 | - throw new Error("Queue event methods cannot be called after the handler returns."); | |
| 5441 | - }; | |
| 5442 | - const retryDelay = (options) => { | |
| 5443 | - const value = options?.delaySeconds; | |
| 5444 | - if (value === undefined) return undefined; | |
| 5445 | - if (!Number.isInteger(value) || value < -0x8000_0000 || value > 0x7fff_ffff) | |
| 5446 | - throw new TypeError("delaySeconds must be a 32-bit integer"); | |
| 5447 | - return value; | |
| 5448 | - }; | |
| 5449 | - const decode = (message) => { | |
| 5450 | - switch (message.contentType) { | |
| 5451 | - case "text": return new TextDecoder().decode(message.body); | |
| 5452 | - case "bytes": return message.body; | |
| 5453 | - case "json": return JSON.parse(new TextDecoder().decode(message.body)); | |
| 5454 | - case "v8": return __sc_decode(message.body); | |
| 5455 | - default: throw new TypeError(`Unknown queue content type: ${message.contentType}`); | |
| 5456 | - } | |
| 5457 | - }; | |
| 5458 | - const messages = incoming.messages.map((message) => ({ | |
| 5459 | - id: message.id, | |
| 5460 | - timestamp: new Date(message.timestamp), | |
| 5461 | - body: decode(message), | |
| 5462 | - attempts: message.attempts, | |
| 5463 | - ack() { | |
| 5464 | - checkActive(); | |
| 5465 | - if (ackAll || retryBatch.retry || retries.has(message.id)) return; | |
| 5466 | - explicitAcks.add(message.id); | |
| 5467 | - }, | |
| 5468 | - retry(options) { | |
| 5469 | - checkActive(); | |
| 5470 | - if (ackAll || explicitAcks.has(message.id)) return; | |
| 5471 | - const delaySeconds = retryDelay(options); | |
| 5472 | - if (delaySeconds !== undefined || !retries.has(message.id)) | |
| 5473 | - retries.set(message.id, delaySeconds); | |
| 5474 | - }, | |
| 5475 | - })); | |
| 5476 | - const oldest = incoming.metrics.oldestMessageTimestamp; | |
| 5477 | - const batch = { | |
| 5478 | - queue: incoming.queue, | |
| 5479 | - messages, | |
| 5480 | - metadata: { | |
| 5481 | - metrics: { | |
| 5482 | - backlogCount: incoming.metrics.backlogCount, | |
| 5483 | - backlogBytes: incoming.metrics.backlogBytes, | |
| 5484 | - oldestMessageTimestamp: oldest === undefined ? undefined : new Date(oldest), | |
| 5485 | - }, | |
| 5486 | - }, | |
| 5487 | - ackAll() { | |
| 5488 | - checkActive(); | |
| 5489 | - if (!retryBatch.retry) ackAll = true; | |
| 5490 | - }, | |
| 5491 | - retryAll(options) { | |
| 5492 | - checkActive(); | |
| 5493 | - if (ackAll) return; | |
| 5494 | - retryBatch.retry = true; | |
| 5495 | - const delaySeconds = retryDelay(options); | |
| 5496 | - if (delaySeconds !== undefined) retryBatch.delaySeconds = delaySeconds; | |
| 5497 | - }, | |
| 5498 | - }; | |
| 5499 | - let outcome = "ok"; | |
| 5500 | - let errorText; | |
| 5501 | - try { | |
| 5502 | - await __dispatchEntrypointMethodInCurrentEvent(name, "queue", batch); | |
| 5503 | - } catch (error) { | |
| 5504 | - // A handler exception retries the batch but keeps explicit acks that the | |
| 5505 | - // handler made before it threw. The caller needs both facts together. | |
| 5506 | - outcome = "exception"; | |
| 5507 | - try { | |
| 5508 | - errorText = String(error); | |
| 5509 | - } catch { | |
| 5510 | - errorText = "queue handler rejected"; | |
| 5511 | - } | |
| 5512 | - } finally { | |
| 5513 | - active = false; | |
| 5514 | - } | |
| 5515 | - return { | |
| 5516 | - outcome, | |
| 5517 | - error: errorText, | |
| 5518 | - ackAll, | |
| 5519 | - retryBatch, | |
| 5520 | - explicitAcks: [...explicitAcks], | |
| 5521 | - retryMessages: [...retries].map(([msgId, delaySeconds]) => ({ | |
| 5522 | - msgId, | |
| 5523 | - delaySeconds, | |
| 5524 | - })), | |
| 5525 | - }; | |
| 5526 | -}; | |
| 5527 | -// Workerd's simple-handler RPC rules (worker-rpc.c++): a non-class | |
| 5528 | -// handler method is called as fn(arg, env, ctx), the client must send | |
| 5529 | -// exactly one argument, and the handler must not declare more than | |
| 5530 | -// (arg, env, ctx). The messages are Workerd's, verbatim. | |
| 5531 | -const __callObjectEntrypoint = (handler, method, args, props) => { | |
| 5532 | - const fn = handler[method]; | |
| 5533 | - if (typeof fn !== "function") | |
| 5534 | - throw new TypeError( | |
| 5535 | - 'The RPC receiver does not implement the method "' + method + | |
| 5536 | - '".'); | |
| 5537 | - if (fn.length > 3) | |
| 5538 | - throw new TypeError( | |
| 5539 | - 'Cannot call handler function "' + method + '" over RPC ' + | |
| 5540 | - "because it has the wrong number of arguments. A simple " + | |
| 5541 | - "function handler can only be called over RPC if it has " + | |
| 5542 | - "exactly the arguments (arg, env, ctx), where only the first " + | |
| 5543 | - "argument comes from the client. To support multi-argument " + | |
| 5544 | - "RPC functions, use class-based syntax (extending " + | |
| 5545 | - "WorkerEntrypoint) instead."); | |
| 5546 | - if (args.length !== 1) | |
| 5547 | - throw new TypeError( | |
| 5548 | - 'Attempted to call RPC function "' + method + '" with the ' + | |
| 5549 | - "wrong number of arguments. When calling a top-level handler " + | |
| 5550 | - "function that is not declared as part of a class, you must " + | |
| 5551 | - "always send exactly one argument. In order to support " + | |
| 5552 | - "variable numbers of arguments, the server must use " + | |
| 5553 | - "class-based syntax (extending WorkerEntrypoint) instead."); | |
| 5554 | - return fn.call(handler, args[0], __cell.env, __entrypointContext(props)); | |
| 5555 | -}; | |
| 5556 | -let __nextPendingEventId = 1; | |
| 5557 | -const __pendingEvents = new Map(); | |
| 5558 | -const __pendingEventError = () => new Error( | |
| 5559 | - "The Workers runtime canceled this request because it detected that " + | |
| 5560 | - "your Worker's code had hung and would never generate a response. " + | |
| 5561 | - "Refer to: https://developers.cloudflare.com/workers/observability/errors/"); | |
| 5562 | -// The host calls this only when the request has no native operation that can | |
| 5563 | -// resume JavaScript. Reject the entrypoint call itself, so its caller can | |
| 5564 | -// catch the cancellation and continue the enclosing event. | |
| 5565 | -__celld.__cancelPendingEvents = (ids) => { | |
| 5566 | - for (const id of ids) __pendingEvents.get(id)?.(__pendingEventError()); | |
| 5567 | -}; | |
| 5568 | -// One entrypoint op (a call, or a property GET when argsSc is | |
| 5569 | -// null), inside a fresh request context -- the callee owns stubs | |
| 5570 | -// revived from its params, and stubs it mints belong to it. | |
| 5571 | -// `props` is the caller's per-stub props (Workerd's | |
| 5572 | -// getEntrypoint(name, { props })); undefined leaves the entrypoint's | |
| 5573 | -// default empty props. | |
| 5574 | -const __entrypointOp = (name, path, argsSc, local, makeInst, props) => { | |
| 5575 | - const id = __nextCtxId++; | |
| 5576 | - return __ctxRun(id, () => { | |
| 5577 | - const pendingId = __nextPendingEventId++; | |
| 5578 | - let cancel; | |
| 5579 | - const cancellation = new Promise((_, reject) => { cancel = reject; }); | |
| 5580 | - __pendingEvents.set(pendingId, cancel); | |
| 5581 | - __pending_event_begin(pendingId); | |
| 5582 | - const running = (async () => { | |
| 5583 | - const decoded = argsSc === null ? null : __rpcDesArgs(argsSc); | |
| 5584 | - let drain = null; | |
| 5585 | - try { | |
| 5586 | - const reply = await __rpcRun(async () => { | |
| 5587 | - // The handler's synchronous part runs inside its own event so | |
| 5588 | - // ctx.waitUntil and the imported waitUntil have a target. The | |
| 5589 | - // event pops before the first await -- the event stack is | |
| 5590 | - // strictly LIFO and an event held across an await would be | |
| 5591 | - // popped by whichever event settles next -- and its registered | |
| 5592 | - // work drains before a plain reply (below). | |
| 5593 | - __beginEvent(); | |
| 5594 | - let result; | |
| 5595 | - try { | |
| 5596 | - const handler = __cell.objectEntrypoints[name]; | |
| 5597 | - if (handler !== undefined && makeInst === undefined) { | |
| 5598 | - // Simple-handler entrypoints expose single-method calls | |
| 5599 | - // only; property GETs and deeper paths are refused. | |
| 5600 | - if (argsSc === null || path.length !== 1) | |
| 5601 | - throw __rpcNoSuchMethod(path[0]); | |
| 5602 | - result = __callObjectEntrypoint( | |
| 5603 | - handler, path[0], decoded.args, props); | |
| 5604 | - } else { | |
| 5605 | - // A loopback stub with props retains one instance for that RPC | |
| 5606 | - // session. Each ordinary top-level operation constructs once here, | |
| 5607 | - // so neither its fields nor its constructor context reach the next | |
| 5608 | - // invocation. | |
| 5609 | - const inst = makeInst !== undefined ? makeInst() | |
| 5610 | - : __newEntrypointInstance(name, props); | |
| 5611 | - result = __rpcWalk(inst, path, | |
| 5612 | - decoded === null ? null : decoded.args, true); | |
| 5613 | - } | |
| 5614 | - } finally { | |
| 5615 | - drain = __endEvent(); | |
| 5616 | - } | |
| 5617 | - return await result; | |
| 5618 | - }, local); | |
| 5619 | - // Registered work drains before a plain reply. A | |
| 5620 | - // capability-bearing reply (tag 1) must not wait: a returned | |
| 5621 | - // stream's chunks may be produced by that very work, which | |
| 5622 | - // cannot finish until the caller pulls (returnReadableStream's | |
| 5623 | - // waitUntil writer would deadlock behind its own reply). | |
| 5624 | - if (reply[0] !== 1 && drain !== null) await drain; | |
| 5625 | - // ctx.abort() during the call supersedes its result; the raw | |
| 5626 | - // reason rejects the caller (same isolate -- identity holds). | |
| 5627 | - if (__abortedCtxs.size !== 0) { | |
| 5628 | - const reason = __abortedCtxs.get(id); | |
| 5629 | - if (reason !== undefined) throw reason; | |
| 5630 | - } | |
| 5631 | - // A reply that exports no stubs (tag 0xff plain, tag 0 error) | |
| 5632 | - // leaves nothing rooting this context: tear it down now, so a | |
| 5633 | - // dup() the callee leaked reaches its disposal callback | |
| 5634 | - // promptly (Workerd tears the IoContext down at call end | |
| 5635 | - // unless returned capabilities hold it open). | |
| 5636 | - if (reply[0] !== 1) __ctxEnd(id); | |
| 5637 | - return reply; | |
| 5638 | - } finally { | |
| 5639 | - if (decoded !== null) | |
| 5640 | - for (const handle of decoded.received) __disposeStub(handle); | |
| 5641 | - } | |
| 5642 | - })(); | |
| 5643 | - return Promise.race([running, cancellation]).finally(() => { | |
| 5644 | - __pendingEvents.delete(pendingId); | |
| 5645 | - __pending_event_end(pendingId); | |
| 5646 | - }); | |
| 5647 | - }); | |
| 5648 | -}; | |
| 5649 | -// Cross-isolate service callers pass a complete property path. Older host | |
| 5650 | -// callers can still pass one method name, which becomes a one-part path. | |
| 5651 | -// `propsSc` carries getEntrypoint(name, {props}) as structured-clone bytes, | |
| 5652 | -// the same encoding as `argsSc`. It is empty when the caller sent no props, | |
| 5653 | -// which no encoded value can be, so an empty buffer is an unambiguous absent. | |
| 5654 | -__celld.__dispatchEntrypointRpc = | |
| 5655 | - (name, path, argsSc, local = false, propsSc = null) => __entrypointOp( | |
| 5656 | - name, typeof path === "string" ? [path] : path, argsSc, local, | |
| 5657 | - undefined, | |
| 5658 | - propsSc === null || propsSc.length === 0 | |
| 5659 | - ? undefined : __sc_decode(propsSc)); | |
| 5660 | -// WebSocket: the host holds the socket; these deliver events into the DO. | |
| 5661 | -// `ws` is a lightweight stub whose send/close route back to the host task | |
| 5662 | -// by wsId -- so the isolate can be hibernated between messages. | |
| 5663 | -const __wsStub = __celld.__wsStub = (wsId) => ({ | |
| 5664 | - _hibernatable: true, | |
| 5665 | - send: (data) => { | |
| 5666 | - if (data instanceof ArrayBuffer) | |
| 5667 | - __ws_send_binary(wsId, new Uint8Array(data)); | |
| 5668 | - else if (ArrayBuffer.isView(data)) | |
| 5669 | - __ws_send_binary(wsId, | |
| 5670 | - new Uint8Array(data.buffer, data.byteOffset, data.byteLength)); | |
| 5671 | - else | |
| 5672 | - __ws_send(wsId, String(data)); | |
| 5673 | - }, | |
| 5674 | - close: (code = 1000, reason = "") => __ws_close(wsId, code, reason), | |
| 5675 | -}); | |
| 5676 | -__celld.__wsOpen = async (scope, wsId, protocol) => { | |
| 5677 | - const actorEvent = __beginActorEvent(scope); | |
| 5678 | - try { | |
| 5679 | - const inst = await _readyInstance(scope); | |
| 5680 | - const socket = inst.__celldState._socket(wsId); | |
| 5681 | - if (socket.readyState !== WebSocket.READY_STATE_CONNECTING) return; | |
| 5682 | - socket.protocol = protocol; | |
| 5683 | - socket.readyState = WebSocket.READY_STATE_OPEN; | |
| 5684 | - socket.dispatchEvent(new Event("open")); | |
| 5685 | - } finally { | |
| 5686 | - __endActorEvent(actorEvent); | |
| 5687 | - } | |
| 5688 | -}; | |
| 5689 | -__celld.__wsMessage = async (scope, wsId, msg) => { | |
| 5690 | - const actorEvent = __beginActorEvent(scope); | |
| 5691 | - try { | |
| 5692 | - const inst = await _readyInstance(scope); | |
| 5693 | - const socket = inst.__celldState._socket(wsId); | |
| 5694 | - if (!socket._hibernatable && typeof socket._dispatchMessage === "function") | |
| 5695 | - socket._dispatchMessage(msg); | |
| 5696 | - else if (typeof inst.webSocketMessage === "function") | |
| 5697 | - await inst.webSocketMessage(socket, msg); | |
| 5698 | - } finally { | |
| 5699 | - __endActorEvent(actorEvent); | |
| 5700 | - } | |
| 5701 | -}; | |
| 5702 | -__celld.__wsBinary = async (scope, wsId, data) => { | |
| 5703 | - const actorEvent = __beginActorEvent(scope); | |
| 5704 | - try { | |
| 5705 | - const inst = await _readyInstance(scope); | |
| 5706 | - const socket = inst.__celldState._socket(wsId); | |
| 5707 | - const bytes = data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength); | |
| 5708 | - if (!socket._hibernatable && typeof socket._dispatchMessage === "function") | |
| 5709 | - socket._dispatchMessage(bytes); | |
| 5710 | - else if (typeof inst.webSocketMessage === "function") | |
| 5711 | - await inst.webSocketMessage(socket, bytes); | |
| 5712 | - } finally { | |
| 5713 | - __endActorEvent(actorEvent); | |
| 5714 | - } | |
| 5715 | -}; | |
| 5716 | -__celld.__wsClosed = async (scope, wsId, code, reason, wasClean) => { | |
| 5717 | - const actorEvent = __beginActorEvent(scope); | |
| 5718 | - try { | |
| 5719 | - const inst = await _readyInstance(scope); | |
| 5720 | - const socket = inst.__celldState._socket(wsId); | |
| 5721 | - if (!socket._hibernatable && typeof socket._dispatchClose === "function") | |
| 5722 | - socket._dispatchClose(code, reason, wasClean); | |
| 5723 | - else if (!wasClean && typeof inst.webSocketError === "function") | |
| 5724 | - // A hibernatable socket reports an abnormal closure through | |
| 5725 | - // webSocketError, which celld listed as a handler name and never | |
| 5726 | - // called. | |
| 5727 | - await inst.webSocketError( | |
| 5728 | - socket, | |
| 5729 | - new Error(reason ? `WebSocket closed abnormally: ${reason}` : "WebSocket closed abnormally"), | |
| 5730 | - ); | |
| 5731 | - else if (typeof inst.webSocketClose === "function") | |
| 5732 | - await inst.webSocketClose(socket, code, reason, wasClean); | |
| 5733 | - } finally { | |
| 5734 | - __endActorEvent(actorEvent); | |
| 5735 | - } | |
| 5736 | -}; | |
| 5737 | -// called by celld's scheduler when an alarm is due. Returns a promise. | |
| 5738 | -__celld.__fireAlarm = async (scope, scheduledTime, retryCount) => { | |
| 5739 | - const actorEvent = __beginActorEvent(scope); | |
| 5740 | - try { | |
| 5741 | - const inst = await _readyInstance(scope); | |
| 5742 | - if (typeof inst.alarm !== "function") return; | |
| 5743 | - await inst.alarm({ scheduledTime, retryCount, isRetry: retryCount > 0 }); | |
| 5744 | - } finally { | |
| 5745 | - __endActorEvent(actorEvent); | |
| 5746 | - } | |
| 5747 | -}; | |
| 5748 | -// The reserved cron cell. It is not a user class: celld registers it under | |
| 5749 | -// `.cron` for every deployment that declares `triggers.crons`, and one cell | |
| 5750 | -// per script carries that script's whole schedule. Ownership CAS on that one | |
| 5751 | -// name is what makes a cron trigger fire once per fleet rather than once per | |
| 5752 | -// node -- the same arbiter an alarm already relies on, with nothing added. | |
| 5753 | -// | |
| 5754 | -// The schedule itself is never stored here. `__cell.crons` comes from the | |
| 5755 | -// deployment the cell is running under, so changing a cron expression takes | |
| 5756 | -// effect on the next activation and needs no migration of an armed alarm. | |
| 5757 | -class CelldCronSchedule { | |
| 5758 | - constructor(state) { | |
| 5759 | - this._state = state; | |
| 5760 | - // Failures within one occurrence. Held in memory on purpose: losing the | |
| 5761 | - // count to an eviction only makes the next retry sooner, and every retry | |
| 5762 | - // is capped at the next occurrence anyway, so it need not be durable. | |
| 5763 | - this._retry = 0; | |
| 5764 | - // What a pending retry owes: the occurrence, the expressions of it that | |
| 5765 | - // failed, and the deadline the retry was armed for. A retry deadline is a | |
| 5766 | - // backoff instant and not an occurrence, so nothing about it can be | |
| 5767 | - // recovered from the deadline itself -- without this record the wake | |
| 5768 | - // matches no expression, runs nothing, and drops the failed tick in | |
| 5769 | - // silence. Held in memory beside `_retry` and for the same reason: an | |
| 5770 | - // eviction costs the retry, never the next occurrence. | |
| 5771 | - this._owed = null; | |
| 5772 | - } | |
| 5773 | - // celld calls this once per node after a deployment loads, because a cron | |
| 5774 | - // cell has no client to wake it. Arming is idempotent -- the same schedule | |
| 5775 | - // and the same clock give the same answer -- so it does not matter which | |
| 5776 | - // node wins the cell. | |
| 5777 | - async fetch() { | |
| 5778 | - // A pending retry is a deadline this cell already owes, and re-arming | |
| 5779 | - // would move it to the next occurrence and lose the tick it owes with it. | |
| 5780 | - if (this._owed !== null) return new Response(null, { status: 204 }); | |
| 5781 | - const armed = await this._state.storage.getAlarm(); | |
| 5782 | - // An alarm already due is a tick that is late, not one that is wrong. | |
| 5783 | - // Leaving it alone is what makes a fleet that was down fire the missed | |
| 5784 | - // occurrence once, instead of skipping it by re-arming into the future. | |
| 5785 | - if (armed === null || armed > Date.now()) await this._arm(null, [], false); | |
| 5786 | - return new Response(null, { status: 204 }); | |
| 5787 | - } | |
| 5788 | - async alarm(info) { | |
| 5789 | - const crons = __cell.crons || []; | |
| 5790 | - // A retry wake carries the backoff instant as its deadline, so what to run | |
| 5791 | - // and what time to report both come from the record the failure left. Only | |
| 5792 | - // a deadline that is not a retry is an occurrence to match against. | |
| 5793 | - const owed = this._owed !== null && this._owed.armedFor === info.scheduledTime | |
| 5794 | - ? this._owed | |
| 5795 | - : null; | |
| 5796 | - const occurrence = owed === null ? info.scheduledTime : owed.at; | |
| 5797 | - // One deadline can belong to several expressions, and each is its own | |
| 5798 | - // invocation with its own controller.cron, as on Cloudflare. A retry | |
| 5799 | - // repeats only the expressions that failed, because the ones that | |
| 5800 | - // succeeded already ran for this occurrence. | |
| 5801 | - const due = owed === null | |
| 5802 | - ? __cron_plan(crons, info.scheduledTime, Date.now(), 0, false).matching | |
| 5803 | - : owed.indices; | |
| 5804 | - const failed = []; | |
| 5805 | - for (const index of due) { | |
| 5806 | - let noRetry = false; | |
| 5807 | - const controller = { | |
| 5808 | - // The occurrence, never the instant this attempt started, so a late | |
| 5809 | - // run and a retry both report the minute they were scheduled for. | |
| 5810 | - scheduledTime: occurrence, | |
| 5811 | - cron: crons[index], | |
| 5812 | - noRetry() { noRetry = true; }, | |
| 5813 | - }; | |
| 5814 | - const ctx = __beginEvent(); | |
| 5815 | - try { | |
| 5816 | - if (typeof __cell.selfScheduled !== "function") | |
| 5817 | - throw new Error( | |
| 5818 | - "a cron trigger needs the Worker to export a `scheduled` handler"); | |
| 5819 | - await __cell.selfScheduled(controller, __cell.env, ctx); | |
| 5820 | - } catch (error) { | |
| 5821 | - // Swallowed on purpose: this handler owns the re-arm below, so | |
| 5822 | - // throwing would hand the deadline to the generic alarm retry and | |
| 5823 | - // lose the next occurrence with it. | |
| 5824 | - console.error( | |
| 5825 | - `scheduled handler for cron ${JSON.stringify(crons[index])} failed:`, | |
| 5826 | - error); | |
| 5827 | - if (!noRetry) failed.push(index); | |
| 5828 | - } finally { | |
| 5829 | - const drain = __endEvent(); | |
| 5830 | - // The alarm turn is the only host owner for this scheduled event. | |
| 5831 | - // Dropping its drain lets the actor turn end with waitUntil work still | |
| 5832 | - // pending, so an I/O promise can remain unresolved forever. | |
| 5833 | - if (drain !== null) await drain; | |
| 5834 | - } | |
| 5835 | - } | |
| 5836 | - await this._arm(occurrence, failed, owed !== null); | |
| 5837 | - } | |
| 5838 | - // `occurrence` is the tick just handled, or null when the cell is only | |
| 5839 | - // arming, `failed` holds the expressions of it still owed, and `retried` | |
| 5840 | - // says the deadline just handled was a backoff rather than an occurrence. | |
| 5841 | - async _arm(occurrence, failed, retried) { | |
| 5842 | - const crons = __cell.crons || []; | |
| 5843 | - // The count is failures within one occurrence, so a fresh occurrence | |
| 5844 | - // starts at one however the last one ended. Carrying it across would | |
| 5845 | - // spend `alarm_retry`'s ceiling once and leave every later occurrence | |
| 5846 | - // with no retry at all, which is a budget for the schedule and not for | |
| 5847 | - // the tick. | |
| 5848 | - this._retry = failed.length ? (retried ? this._retry + 1 : 1) : 0; | |
| 5849 | - // A negative first argument means "arming only, nothing fired". | |
| 5850 | - const plan = __cron_plan(crons, -1, Date.now(), this._retry, failed.length > 0); | |
| 5851 | - // The next occurrence beats the backoff whenever it is sooner, and it then | |
| 5852 | - // cancels the retry rather than queueing behind it, so the record the | |
| 5853 | - // retry needed goes when the retry does. | |
| 5854 | - this._owed = plan.armIsRetry | |
| 5855 | - ? { at: occurrence, indices: failed, armedFor: plan.armAt } | |
| 5856 | - : null; | |
| 5857 | - // No expression matches again and nothing is owed: the deployment dropped | |
| 5858 | - // its crons, so the cell retires rather than waking forever. | |
| 5859 | - if (plan.armAt === null) await this._state.storage.deleteAlarm(); | |
| 5860 | - else await this._state.storage.setAlarm(plan.armAt); | |
| 5861 | - } | |
| 5862 | -} | |
| 5863 | -const __cell = __celld.__cell = { | |
| 5864 | - entrypoints: {}, | |
| 5865 | - objectEntrypoints: {}, | |
| 5866 | - doExports: {}, | |
| 5867 | - classes: { ".cron": CelldCronSchedule }, | |
| 5868 | - crons: [], | |
| 5869 | - workflows: {}, | |
| 5870 | - containers: {}, | |
| 5871 | - instances: {}, | |
| 5872 | - facetConfigs: {}, | |
| 5873 | - env: {}, | |
| 5874 | - idNames: {}, | |
| 5875 | - namespaceKeys: {}, | |
| 5876 | - node: "", | |
| 5877 | - deleteAllDeletesAlarm: false, | |
| 5878 | - compat: { jsRpc: false, fetcherGetPutDelete: false, queueJsonMessages: false }, | |
| 5879 | - makeNamespace, | |
| 5880 | - release: __cellRelease, | |
| 5881 | -}; | |
| 5882 | -// ---- KV ------------------------------------------------------------------ | |
| 5883 | -// A KV namespace is a cell of a runtime-supplied Durable Object class, so it | |
| 5884 | -// inherits ownership, fencing, LTX replication and durable acknowledgement | |
| 5885 | -// from the cell it already is. This half is the server; `__makeKvNamespace` | |
| 5886 | -// below is the client the binding hands to a Worker. | |
| 5887 | -// | |
| 5888 | -// Reads here are strongly consistent and the published contract is upstream's: | |
| 5889 | -// a value can be up to 60 seconds old. That gap is deliberate. A node-local | |
| 5890 | -// read cache is the obvious next optimisation and it would make reads | |
| 5891 | -// genuinely stale, and a freshness promise made now could not be withdrawn | |
| 5892 | -// then. Implement strong, promise weak. | |
| 5893 | -// | |
| 5894 | -// Storage is ordinary cell SQL rather than the KV surface, because a namespace | |
| 5895 | -// is read by ordered prefix scan and `list` is the operation that decides the | |
| 5896 | -// schema. `celld_logic::kv` owns every decision about a key, a deadline or a | |
| 5897 | -// limit; nothing here re-derives one. | |
| 5898 | - | |
| 5899 | -// Run one bounded reclamation transaction. A cell supplies only its ordered | |
| 5900 | -// candidate query and its per-row transition, so KV expiry and Queue retention | |
| 5901 | -// share the turn bound and the transaction shape without pretending their SQL | |
| 5902 | -// state machines are the same. | |
| 5903 | -const __cellSweepBatch = (storage, select, reclaim, limit) => { | |
| 5904 | - let processed = 0; | |
| 5905 | - storage.transactionSync(() => { | |
| 5906 | - const rows = select(limit); | |
| 5907 | - if (rows.length > limit) throw new Error("a cell sweep exceeded its row bound"); | |
| 5908 | - for (const row of rows) { | |
| 5909 | - reclaim(row); | |
| 5910 | - processed += 1; | |
| 5911 | - } | |
| 5912 | - }); | |
| 5913 | - return processed; | |
| 5914 | -}; | |
| 5915 | - | |
| 5916 | -const __KV_TABLE = "__kv"; | |
| 5917 | -const __KV_META_TABLE = "__kv_meta"; | |
| 5918 | - | |
| 5919 | -// Upstream's four content types. The wire form is what `get` returns for | |
| 5920 | -// `type: "text"`; the binding converts from there, so the cell stores bytes | |
| 5921 | -// and a tag and never a parsed value. | |
| 5922 | -const __kvError = (message) => new Error("KV_ERROR: " + String(message)); | |
| 5923 | - | |
| 5924 | -// One op for the whole large-value path, following `__d1_run`. Bytes cross as | |
| 5925 | -// a typed view in both directions. Encoding a 25 MiB value as a JSON number | |
| 5926 | -// array creates millions of heap objects and can crash an otherwise valid put. | |
| 5927 | -const __kvBlob = async (request, value) => { | |
| 5928 | - const reply = await __kv_blob(JSON.stringify(request), value); | |
| 5929 | - return reply instanceof Uint8Array | |
| 5930 | - ? { found: true, value: reply } | |
| 5931 | - : JSON.parse(reply); | |
| 5932 | -}; | |
| 5933 | - | |
| 5934 | -// The authenticated operator route still uses JSON for its control envelope. | |
| 5935 | -// A byte array is acceptable for an inline value, but a 25 MiB array creates | |
| 5936 | -// 25 million JavaScript numbers and exhausts the isolate. The raw base64 ops | |
| 5937 | -// accept typed views for this internal wire form; the public atob() and btoa() | |
| 5938 | -// wrappers keep their standard string-only behaviour. | |
| 5939 | -const __kvOperatorValue = (value) => { | |
| 5940 | - const bytes = value instanceof Uint8Array ? value : new Uint8Array(value); | |
| 5941 | - return bytes.byteLength > __kvLimits().maxInlineValueBytes | |
| 5942 | - ? { value: $$btoa(bytes), valueEncoding: "base64" } | |
| 5943 | - : { value: [...bytes] }; | |
| 5944 | -}; | |
| 5945 | - | |
| 5946 | -// Content addressing, so the same value written twice in one ownership epoch | |
| 5947 | -// stores once and a retry after an uncertain failure costs nothing. A later | |
| 5948 | -// epoch deliberately uses a different object. SHA-256 makes an accidental | |
| 5949 | -// collision infeasible. The host adds the active cell scope and epoch to the | |
| 5950 | -// object key, because one activation cannot prove another activation's live | |
| 5951 | -// set and therefore cannot safely collect from a shared digest prefix. | |
| 5952 | -const __kvDigest = async (bytes) => { | |
| 5953 | - const hash = new Uint8Array(await crypto.subtle.digest("SHA-256", bytes)); | |
| 5954 | - let out = ""; | |
| 5955 | - for (const byte of hash) out += byte.toString(16).padStart(2, "0"); | |
| 5956 | - return out; | |
| 5957 | -}; | |
| 5958 | - | |
| 5959 | -// The least name that sorts after every name with this prefix, or null when no | |
| 5960 | -// such name exists. SQLite compares TEXT byte by byte and UTF-8 byte order is | |
| 5961 | -// code point order, so the successor is the prefix with its final code point | |
| 5962 | -// incremented; a final code point that is already the highest carries into the | |
| 5963 | -// code point before it, and an empty prefix has no upper bound at all. | |
| 5964 | -// | |
| 5965 | -// A lone surrogate has no UTF-8 form, so a prefix that holds one gets no bound | |
| 5966 | -// rather than a bound derived from whatever the host substitutes. Such a | |
| 5967 | -// prefix matches no stored name, and answering it with a wrong range would | |
| 5968 | -// answer it with the wrong keys instead of slowly. | |
| 5969 | -const __kvPrefixUpperBound = (prefix) => { | |
| 5970 | - if (/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/.test(prefix)) { | |
| 5971 | - return null; | |
| 5972 | - } | |
| 5973 | - // Array.from splits on code points, so a surrogate pair stays one element | |
| 5974 | - // and cannot be incremented into a different character. | |
| 5975 | - const points = Array.from(prefix); | |
| 5976 | - while (points.length > 0) { | |
| 5977 | - const code = points.pop().codePointAt(0); | |
| 5978 | - if (code >= 0x10FFFF) continue; | |
| 5979 | - // The surrogate block is unencodable, so step over it in one move. | |
| 5980 | - const next = code + 1 === 0xD800 ? 0xE000 : code + 1; | |
| 5981 | - return points.join("") + String.fromCodePoint(next); | |
| 5982 | - } | |
| 5983 | - return null; | |
| 5984 | -}; | |
| 5985 | - | |
| 5986 | -// Which rows a list visits is not visible in its result, so a lost bound reads | |
| 5987 | -// as a correct answer and is measurable only as latency. The plan is the | |
| 5988 | -// evidence, and a gated test seam reads it from the shipped query rather than | |
| 5989 | -// from a copy that can drift. | |
| 5990 | -const __kvReportListPlan = (sql, query, params) => { | |
| 5991 | - if (typeof __test_kv_list_plan !== "function") return; | |
| 5992 | - const plan = sql.exec(`EXPLAIN QUERY PLAN ${query}`, ...params) | |
| 5993 | - .toArray() | |
| 5994 | - .map((row) => row.detail) | |
| 5995 | - .join("; "); | |
| 5996 | - __test_kv_list_plan(plan); | |
| 5997 | -}; | |
| 5998 | - | |
| 5999 | -class __KvNamespaceCell { | |
| 6000 | - constructor(ctx) { | |
| 6001 | - this.ctx = ctx; | |
| 6002 | - this._ready = false; | |
| 6003 | - // Blob references written to the bucket whose row has not committed yet. A sweep | |
| 6004 | - // must spare these, or it collects bytes a put is about to reference. | |
| 6005 | - this._pending = new Set(); | |
| 6006 | - // Blob writes and the mark-and-sweep protocol share one per-cell queue. | |
| 6007 | - // The pending set is live state, not a snapshot that stays valid across an | |
| 6008 | - // await, so collection cannot overlap a put from its announcement through | |
| 6009 | - // its row commit. Other cells and ordinary reads stay independent. | |
| 6010 | - this._blobProtocolTail = Promise.resolve(); | |
| 6011 | - } | |
| 6012 | - | |
| 6013 | - async _withBlobProtocol(operation) { | |
| 6014 | - const previous = this._blobProtocolTail; | |
| 6015 | - let release; | |
| 6016 | - this._blobProtocolTail = new Promise((resolve) => { | |
| 6017 | - release = resolve; | |
| 6018 | - }); | |
| 6019 | - await previous; | |
| 6020 | - try { | |
| 6021 | - return await operation(); | |
| 6022 | - } finally { | |
| 6023 | - release(); | |
| 6024 | - } | |
| 6025 | - } | |
| 6026 | - | |
| 6027 | - // Schedule collection before a blob can leave the process or a row can drop | |
| 6028 | - // its reference. `setAlarm()` writes cell state, and the following bucket | |
| 6029 | - // egress waits on that write's output gate. A crash can therefore leave an | |
| 6030 | - // orphan only together with the durable wake that will collect it. | |
| 6031 | - async _armBlobSweep() { | |
| 6032 | - this._open().exec( | |
| 6033 | - `INSERT INTO ${__KV_META_TABLE} (name, value) VALUES ('blob-sweep-due', 1) | |
| 6034 | - ON CONFLICT(name) DO UPDATE SET value = excluded.value`, | |
| 6035 | - ); | |
| 6036 | - const now = Date.now(); | |
| 6037 | - const deadline = now + __kvLimits().blobSweepMs; | |
| 6038 | - const armed = await this.ctx.storage.getAlarm(); | |
| 6039 | - // During an alarm event, `getAlarm()` can still report the timestamp that | |
| 6040 | - // caused the current delivery. It is not a future wake and cannot cover a | |
| 6041 | - // reference removed by an event that interleaves with this one. | |
| 6042 | - if (armed === null || armed <= now || armed > deadline) { | |
| 6043 | - await this.ctx.storage.setAlarm(deadline); | |
| 6044 | - } | |
| 6045 | - } | |
| 6046 | - | |
| 6047 | - _blobSweepDue() { | |
| 6048 | - return this._open().exec( | |
| 6049 | - `SELECT 1 AS due FROM ${__KV_META_TABLE} | |
| 6050 | - WHERE name = 'blob-sweep-due' AND value = 1`, | |
| 6051 | - ).toArray().length > 0; | |
| 6052 | - } | |
| 6053 | - | |
| 6054 | - _clearBlobSweepDue() { | |
| 6055 | - this._open().exec( | |
| 6056 | - `DELETE FROM ${__KV_META_TABLE} WHERE name = 'blob-sweep-due'`, | |
| 6057 | - ); | |
| 6058 | - } | |
| 6059 | - | |
| 6060 | - // Created on first touch rather than at construction, so a namespace that is | |
| 6061 | - // only ever read costs no write, and an eviction that drops the isolate does | |
| 6062 | - // not need the table rebuilt before the cell can answer. | |
| 6063 | - _open() { | |
| 6064 | - if (this._ready) return this.ctx.storage.sql; | |
| 6065 | - const sql = this.ctx.storage.sql; | |
| 6066 | - // Recreate the first release's table before the normal open path. The | |
| 6067 | - // migration test then reaches the same `CREATE IF NOT EXISTS` boundary as | |
| 6068 | - // an upgraded cell and starts with a row it must preserve. | |
| 6069 | - if (__kvLimits().legacySchema) { | |
| 6070 | - sql.exec( | |
| 6071 | - `CREATE TABLE IF NOT EXISTS ${__KV_TABLE} ( | |
| 6072 | - name TEXT PRIMARY KEY, | |
| 6073 | - value BLOB, | |
| 6074 | - tag TEXT NOT NULL, | |
| 6075 | - metadata TEXT, | |
| 6076 | - expires_at INTEGER | |
| 6077 | - ) WITHOUT ROWID`, | |
| 6078 | - ); | |
| 6079 | - sql.exec( | |
| 6080 | - `INSERT OR IGNORE INTO ${__KV_TABLE} | |
| 6081 | - (name, value, tag, metadata, expires_at) | |
| 6082 | - VALUES ('before-upgrade', CAST('legacy' AS BLOB), 'text', NULL, NULL)`, | |
| 6083 | - ); | |
| 6084 | - } | |
| 6085 | - sql.exec( | |
| 6086 | - `CREATE TABLE IF NOT EXISTS ${__KV_TABLE} ( | |
| 6087 | - name TEXT PRIMARY KEY, | |
| 6088 | - value BLOB, | |
| 6089 | - blob_id TEXT, | |
| 6090 | - size INTEGER NOT NULL, | |
| 6091 | - tag TEXT NOT NULL, | |
| 6092 | - metadata TEXT, | |
| 6093 | - expires_at INTEGER | |
| 6094 | - ) WITHOUT ROWID`, | |
| 6095 | - ); | |
| 6096 | - // Inline KV shipped before `blob_id` and `size`. `CREATE IF NOT EXISTS` | |
| 6097 | - // does not change that table, so migrate each column independently. A | |
| 6098 | - // crash between the ALTER statements is safe because the next open reads | |
| 6099 | - // the surviving shape and resumes at the missing column. | |
| 6100 | - const columns = new Set( | |
| 6101 | - sql.exec(`PRAGMA table_info(${__KV_TABLE})`).toArray().map((row) => row.name), | |
| 6102 | - ); | |
| 6103 | - if (!columns.has("blob_id")) { | |
| 6104 | - sql.exec(`ALTER TABLE ${__KV_TABLE} ADD COLUMN blob_id TEXT`); | |
| 6105 | - } | |
| 6106 | - if (!columns.has("size")) { | |
| 6107 | - sql.exec( | |
| 6108 | - `ALTER TABLE ${__KV_TABLE} | |
| 6109 | - ADD COLUMN size INTEGER NOT NULL DEFAULT 0`, | |
| 6110 | - ); | |
| 6111 | - sql.exec(`UPDATE ${__KV_TABLE} SET size = LENGTH(value)`); | |
| 6112 | - } | |
| 6113 | - // `list` walks the primary key in order, so the only index worth carrying | |
| 6114 | - // is the sweeper's. Without it the sweep is a full scan of a namespace | |
| 6115 | - // whose whole point is being large. | |
| 6116 | - sql.exec( | |
| 6117 | - `CREATE INDEX IF NOT EXISTS ${__KV_TABLE}_expires | |
| 6118 | - ON ${__KV_TABLE} (expires_at) WHERE expires_at IS NOT NULL`, | |
| 6119 | - ); | |
| 6120 | - // The due bit is durable because the isolate that wrote a blob can die | |
| 6121 | - // before its row commit. In-memory state cannot schedule that orphan's | |
| 6122 | - // collector on the next owner. | |
| 6123 | - sql.exec( | |
| 6124 | - `CREATE TABLE IF NOT EXISTS ${__KV_META_TABLE} ( | |
| 6125 | - name TEXT PRIMARY KEY, | |
| 6126 | - value INTEGER NOT NULL | |
| 6127 | - ) WITHOUT ROWID`, | |
| 6128 | - ); | |
| 6129 | - this._ready = true; | |
| 6130 | - return sql; | |
| 6131 | - } | |
| 6132 | - | |
| 6133 | - // A key past its deadline is invisible from the instant it expires, not from | |
| 6134 | - // whenever the sweeper next runs. The read path filters and the sweep only | |
| 6135 | - // reclaims space, so the two can never disagree about which side of the | |
| 6136 | - // boundary a key is on. | |
| 6137 | - async __kvGet({ keys, withMetadata, withExpiration = false, now }) { | |
| 6138 | - const sql = this._open(); | |
| 6139 | - const out = []; | |
| 6140 | - for (const key of keys) { | |
| 6141 | - const row = sql.exec( | |
| 6142 | - `SELECT value, blob_id, tag, metadata, expires_at FROM ${__KV_TABLE} | |
| 6143 | - WHERE name = ? AND (expires_at IS NULL OR expires_at > ?)`, | |
| 6144 | - key, | |
| 6145 | - now, | |
| 6146 | - ).toArray()[0]; | |
| 6147 | - if (row === undefined) { | |
| 6148 | - out.push({ key, found: false }); | |
| 6149 | - continue; | |
| 6150 | - } | |
| 6151 | - let value = row.value; | |
| 6152 | - if (row.blob_id !== null && row.blob_id !== undefined) { | |
| 6153 | - const blob = await __kvBlob({ mode: "get", reference: row.blob_id }); | |
| 6154 | - // A row naming a blob the bucket does not hold is the failure the | |
| 6155 | - // commit order exists to prevent, so it is reported as itself rather | |
| 6156 | - // than as a missing key: an absent key and a broken one need different | |
| 6157 | - // answers from an operator. | |
| 6158 | - if (!blob.found) { | |
| 6159 | - throw __kvError( | |
| 6160 | - `the value for ${JSON.stringify(key)} is missing from the fleet ` + | |
| 6161 | - `bucket (blob ${row.blob_id})`, | |
| 6162 | - ); | |
| 6163 | - } | |
| 6164 | - value = new Uint8Array(blob.value); | |
| 6165 | - } | |
| 6166 | - const entry = { key, found: true, value, tag: row.tag }; | |
| 6167 | - if (withMetadata) entry.metadata = row.metadata ?? null; | |
| 6168 | - // These fields describe one row snapshot. The operator bulk export must | |
| 6169 | - // not combine a value from this read with an expiration from an earlier | |
| 6170 | - // listing when a concurrent put replaces the key between both calls. | |
| 6171 | - if (withExpiration) entry.expiration = row.expires_at ?? null; | |
| 6172 | - out.push(entry); | |
| 6173 | - } | |
| 6174 | - return out; | |
| 6175 | - } | |
| 6176 | - | |
| 6177 | - // One transaction for the whole batch, so a bulk put is all-or-nothing | |
| 6178 | - // rather than a prefix of itself. Upstream gives no such guarantee, and | |
| 6179 | - // giving a stronger one here costs nothing and cannot surprise a caller. | |
| 6180 | - // Blob first, row second. An orphan blob is bytes the collector reclaims; a | |
| 6181 | - // row naming a blob that was never written is a read that fails forever, and | |
| 6182 | - // no sweep repairs it. The opposite commit order can leave that dangling | |
| 6183 | - // row when a process stops between the two writes. | |
| 6184 | - // | |
| 6185 | - // The blob reference travels in `_pending` until the row commits, so a sweep that | |
| 6186 | - // runs mid-put does not collect bytes that are about to be referenced. That | |
| 6187 | - // costs the put and not the read -- the commit requires the blob, so a | |
| 6188 | - // collected blob means the commit cannot fire -- which is why the model's | |
| 6189 | - // tooth for it is an action property and not an invariant. | |
| 6190 | - async _store(value) { | |
| 6191 | - if (value.byteLength <= __kvLimits().maxInlineValueBytes) { | |
| 6192 | - return { value, blobId: null }; | |
| 6193 | - } | |
| 6194 | - const digest = await __kvDigest(value); | |
| 6195 | - await this._armBlobSweep(); | |
| 6196 | - // The host mints the reference from the epoch installed with this cell. | |
| 6197 | - // JavaScript never guesses that authority or recovers it after an await. | |
| 6198 | - const { reference } = await __kvBlob({ mode: "prepare", digest }); | |
| 6199 | - this._pending.add(reference); | |
| 6200 | - try { | |
| 6201 | - await __kvBlob({ mode: "put", reference }, value); | |
| 6202 | - // Force the collector race at its real seam. The alarm took its mark | |
| 6203 | - // snapshot before this put started and waits briefly after the put | |
| 6204 | - // announces itself. Without blob-protocol serialization, this write | |
| 6205 | - // lands during that wait and must stay here until the stale sweep runs. | |
| 6206 | - if ( | |
| 6207 | - __kvLimits().raceSweepPut && this._testSweepMarked && | |
| 6208 | - !this._testSweepFinished | |
| 6209 | - ) { | |
| 6210 | - await new Promise((resolve) => { | |
| 6211 | - this._testResumePut = resolve; | |
| 6212 | - }); | |
| 6213 | - } | |
| 6214 | - // The crash window the commit order exists for: the blob is in the | |
| 6215 | - // bucket and the row is not written yet. The failed operation no longer | |
| 6216 | - // protects the digest in memory, so the durable wake can reclaim it even | |
| 6217 | - // when this isolate remains resident. | |
| 6218 | - if (__kvLimits().failAfterBlobWrite) { | |
| 6219 | - throw __kvError("CELLD_TEST_KV_FAIL_AFTER_BLOB_WRITE"); | |
| 6220 | - } | |
| 6221 | - return { value: null, blobId: reference }; | |
| 6222 | - } catch (error) { | |
| 6223 | - this._pending.delete(reference); | |
| 6224 | - throw error; | |
| 6225 | - } | |
| 6226 | - } | |
| 6227 | - | |
| 6228 | - async __kvPut({ entries }) { | |
| 6229 | - if ( | |
| 6230 | - __kvLimits().raceSweepPut && | |
| 6231 | - entries.some((entry) => | |
| 6232 | - entry.value.byteLength > __kvLimits().maxInlineValueBytes | |
| 6233 | - ) | |
| 6234 | - ) { | |
| 6235 | - if (!this._testSweepMarked || this._testPutAttempted === undefined) { | |
| 6236 | - throw __kvError("the test blob sweep did not reach its mark snapshot"); | |
| 6237 | - } | |
| 6238 | - this._testPutAttempted(); | |
| 6239 | - this._testPutAttempted = undefined; | |
| 6240 | - } | |
| 6241 | - return this._withBlobProtocol(() => this._putLocked(entries)); | |
| 6242 | - } | |
| 6243 | - | |
| 6244 | - async _putLocked(entries) { | |
| 6245 | - const sql = this._open(); | |
| 6246 | - // An inline replacement can remove the final row reference to an old | |
| 6247 | - // blob, so arm before changing the row. A new large value also arms in | |
| 6248 | - // `_store`, before its own bucket write. | |
| 6249 | - const replacesBlob = entries.some((entry) => | |
| 6250 | - sql.exec( | |
| 6251 | - `SELECT 1 AS found FROM ${__KV_TABLE} | |
| 6252 | - WHERE name = ? AND blob_id IS NOT NULL`, | |
| 6253 | - entry.key, | |
| 6254 | - ).toArray().length > 0 | |
| 6255 | - ); | |
| 6256 | - if (replacesBlob) await this._armBlobSweep(); | |
| 6257 | - const stored = []; | |
| 6258 | - try { | |
| 6259 | - for (const entry of entries) { | |
| 6260 | - stored.push({ entry, ...(await this._store(entry.value)) }); | |
| 6261 | - } | |
| 6262 | - this.ctx.storage.transactionSync(() => { | |
| 6263 | - for (const { entry, value, blobId } of stored) { | |
| 6264 | - sql.exec( | |
| 6265 | - `INSERT INTO ${__KV_TABLE} | |
| 6266 | - (name, value, blob_id, size, tag, metadata, expires_at) | |
| 6267 | - VALUES (?, ?, ?, ?, ?, ?, ?) | |
| 6268 | - ON CONFLICT(name) DO UPDATE SET | |
| 6269 | - value = excluded.value, | |
| 6270 | - blob_id = excluded.blob_id, | |
| 6271 | - size = excluded.size, | |
| 6272 | - tag = excluded.tag, | |
| 6273 | - metadata = excluded.metadata, | |
| 6274 | - expires_at = excluded.expires_at`, | |
| 6275 | - entry.key, | |
| 6276 | - value, | |
| 6277 | - blobId, | |
| 6278 | - entry.value.byteLength, | |
| 6279 | - entry.tag, | |
| 6280 | - entry.metadata ?? null, | |
| 6281 | - entry.expiresAt ?? null, | |
| 6282 | - ); | |
| 6283 | - } | |
| 6284 | - }); | |
| 6285 | - } finally { | |
| 6286 | - // A committed row protects the blob durably. A failed put protects | |
| 6287 | - // nothing, so it must not pin an orphan until this isolate is evicted. | |
| 6288 | - for (const { blobId } of stored) { | |
| 6289 | - if (blobId !== null) this._pending.delete(blobId); | |
| 6290 | - } | |
| 6291 | - } | |
| 6292 | - // Only when something in this batch can expire. A namespace of permanent | |
| 6293 | - // keys arms no alarm and wakes for nothing. | |
| 6294 | - if (entries.some((entry) => entry.expiresAt !== null && entry.expiresAt !== undefined)) { | |
| 6295 | - await this._rearm(); | |
| 6296 | - } | |
| 6297 | - } | |
| 6298 | - | |
| 6299 | - async __kvDelete({ keys }) { | |
| 6300 | - return this._withBlobProtocol(() => this._deleteLocked(keys)); | |
| 6301 | - } | |
| 6302 | - | |
| 6303 | - async _deleteLocked(keys) { | |
| 6304 | - const sql = this._open(); | |
| 6305 | - const removesBlob = keys.some((key) => | |
| 6306 | - sql.exec( | |
| 6307 | - `SELECT 1 AS found FROM ${__KV_TABLE} | |
| 6308 | - WHERE name = ? AND blob_id IS NOT NULL`, | |
| 6309 | - key, | |
| 6310 | - ).toArray().length > 0 | |
| 6311 | - ); | |
| 6312 | - if (removesBlob) await this._armBlobSweep(); | |
| 6313 | - this.ctx.storage.transactionSync(() => { | |
| 6314 | - for (const key of keys) { | |
| 6315 | - sql.exec(`DELETE FROM ${__KV_TABLE} WHERE name = ?`, key); | |
| 6316 | - } | |
| 6317 | - }); | |
| 6318 | - } | |
| 6319 | - | |
| 6320 | - // Arm for the earliest deadline the table holds, or disarm when it holds | |
| 6321 | - // none. Asked from the row rather than held in memory, so the answer does | |
| 6322 | - // not depend on what this activation happens to remember -- an evicted cell | |
| 6323 | - // that wakes for an alarm re-derives the same deadline from the same rows. | |
| 6324 | - // | |
| 6325 | - // What carries the deadline across an eviction is the alarm itself, which is | |
| 6326 | - // durable cell state. This is *not* recomputed when a cell is merely opened, | |
| 6327 | - // so the one gap is a `_rearm` that throws after its put committed: the rows | |
| 6328 | - // are written, the caller sees an error, and nothing is armed until the next | |
| 6329 | - // put with a deadline. That costs space and never correctness, because the | |
| 6330 | - // read path filters an expired key whether or not it was reclaimed. | |
| 6331 | - async _rearm() { | |
| 6332 | - // A test that means to pin the read filter must be able to stop the sweep, | |
| 6333 | - // or it cannot tell which mechanism hid the key -- and a test that cannot | |
| 6334 | - // tell will pass when the filter is broken. This seam exists because that | |
| 6335 | - // is exactly what happened: the first version of the expiry test stayed | |
| 6336 | - // green with the filter removed. | |
| 6337 | - if (__kvLimits().sweepDisabled) return; | |
| 6338 | - const sql = this._open(); | |
| 6339 | - const row = sql.exec( | |
| 6340 | - `SELECT MIN(expires_at) AS next FROM ${__KV_TABLE} WHERE expires_at IS NOT NULL`, | |
| 6341 | - ).toArray()[0]; | |
| 6342 | - const next = row === undefined ? null : row.next; | |
| 6343 | - const blobDue = this._blobSweepDue(); | |
| 6344 | - if ((next === null || next === undefined) && !blobDue) { | |
| 6345 | - await this.ctx.storage.deleteAlarm(); | |
| 6346 | - return; | |
| 6347 | - } | |
| 6348 | - const now = Date.now(); | |
| 6349 | - const deadlines = []; | |
| 6350 | - // Never in the past: a deadline already due is swept on this wake, and | |
| 6351 | - // arming behind `now` would spin. | |
| 6352 | - if (next !== null && next !== undefined) { | |
| 6353 | - deadlines.push(Math.max(next, now + 1)); | |
| 6354 | - } | |
| 6355 | - if (blobDue) deadlines.push(now + __kvLimits().blobSweepMs); | |
| 6356 | - const deadline = Math.min(...deadlines); | |
| 6357 | - const armed = await this.ctx.storage.getAlarm(); | |
| 6358 | - if (armed === null || armed <= now || armed > deadline) { | |
| 6359 | - await this.ctx.storage.setAlarm(deadline); | |
| 6360 | - } | |
| 6361 | - } | |
| 6362 | - | |
| 6363 | - // Reclaiming space, never deciding visibility. A key is invisible from the | |
| 6364 | - // instant it expires because the read path filters, so a late sweep costs | |
| 6365 | - // storage and never correctness -- which is what lets this be bounded and | |
| 6366 | - // re-armed rather than obliged to finish. | |
| 6367 | - // Every reference a row names, plus every reference a put has written and | |
| 6368 | - // not yet committed. The two go in one list because the bucket end cannot | |
| 6369 | - // tell them apart and does not need to: it only needs "do not delete these". | |
| 6370 | - _liveBlobs() { | |
| 6371 | - const rows = this._open().exec( | |
| 6372 | - `SELECT blob_id FROM ${__KV_TABLE} WHERE blob_id IS NOT NULL`, | |
| 6373 | - ).toArray(); | |
| 6374 | - return [...new Set([...rows.map((row) => row.blob_id), ...this._pending])]; | |
| 6375 | - } | |
| 6376 | - | |
| 6377 | - async alarm() { | |
| 6378 | - const removed = await this._withBlobProtocol(async () => { | |
| 6379 | - const now = Date.now(); | |
| 6380 | - // If expiry will remove a blob reference, persist the due bit and a | |
| 6381 | - // future wake before deleting the row. A crash later in this alarm then | |
| 6382 | - // leaves the next owner enough durable state to finish collection. | |
| 6383 | - const expiresBlob = this._open().exec( | |
| 6384 | - `SELECT 1 AS found FROM ${__KV_TABLE} | |
| 6385 | - WHERE expires_at IS NOT NULL AND expires_at <= ? | |
| 6386 | - AND blob_id IS NOT NULL | |
| 6387 | - LIMIT ?`, | |
| 6388 | - now, | |
| 6389 | - __kvLimits().sweepBatchRows, | |
| 6390 | - ).toArray().length > 0; | |
| 6391 | - if (expiresBlob) await this._armBlobSweep(); | |
| 6392 | - | |
| 6393 | - const { removed } = this.__kvSweep({ | |
| 6394 | - now, | |
| 6395 | - limit: __kvLimits().sweepBatchRows, | |
| 6396 | - }); | |
| 6397 | - // The blob sweep runs after the row sweep, on the same wake, so a row | |
| 6398 | - // reclaimed above has already dropped its reference by the time the live | |
| 6399 | - // set is read. A durable due bit distinguishes a GC wake from an inline | |
| 6400 | - // expiry wake and survives isolate eviction or a failed bucket request. | |
| 6401 | - if (this._blobSweepDue() || __kvLimits().raceSweepPut) { | |
| 6402 | - const live = this._liveBlobs(); | |
| 6403 | - if (__kvLimits().raceSweepPut && !this._testSweepFinished) { | |
| 6404 | - const putAttempted = new Promise((resolve) => { | |
| 6405 | - this._testPutAttempted = resolve; | |
| 6406 | - }); | |
| 6407 | - this._testSweepMarked = true; | |
| 6408 | - await putAttempted; | |
| 6409 | - // The fixture bucket is local. This bounded pause lets an | |
| 6410 | - // unprotected put finish its blob write; a protected put is waiting | |
| 6411 | - // for this protocol lock and therefore cannot enter the window. | |
| 6412 | - await new Promise((resolve) => setTimeout(resolve, 100)); | |
| 6413 | - } | |
| 6414 | - let swept = false; | |
| 6415 | - try { | |
| 6416 | - await __kvBlob({ mode: "sweep", live }); | |
| 6417 | - swept = true; | |
| 6418 | - } catch (error) { | |
| 6419 | - // Reclaiming space is not deciding visibility, so a bucket that | |
| 6420 | - // refuses a delete costs storage and never correctness. The next | |
| 6421 | - // wake tries again. | |
| 6422 | - console.error("kv blob sweep failed:", error); | |
| 6423 | - } finally { | |
| 6424 | - if (__kvLimits().raceSweepPut) { | |
| 6425 | - this._testSweepFinished = true; | |
| 6426 | - this._testResumePut?.(); | |
| 6427 | - this._testResumePut = undefined; | |
| 6428 | - } | |
| 6429 | - } | |
| 6430 | - if (swept) this._clearBlobSweepDue(); | |
| 6431 | - } | |
| 6432 | - return removed; | |
| 6433 | - }); | |
| 6434 | - // A full batch means there is more to reclaim, so come back promptly | |
| 6435 | - // rather than waiting for the next natural deadline. | |
| 6436 | - if (removed >= __kvLimits().sweepBatchRows) { | |
| 6437 | - await this.ctx.storage.setAlarm(Date.now() + 1); | |
| 6438 | - return; | |
| 6439 | - } | |
| 6440 | - await this._rearm(); | |
| 6441 | - } | |
| 6442 | - | |
| 6443 | - // Pagination resumes at `name > after`, never at an offset. A caller holds | |
| 6444 | - // no transaction across pages, so an offset would skip or repeat keys the | |
| 6445 | - // moment a concurrent writer inserted or deleted inside the prefix. | |
| 6446 | - // | |
| 6447 | - // One row beyond the limit is read to decide `list_complete`, and discarded. | |
| 6448 | - // Asking the database is the only honest answer: a page that happens to fill | |
| 6449 | - // exactly is indistinguishable from a page that ended. | |
| 6450 | - __kvList({ prefix, limit, after, now }) { | |
| 6451 | - const sql = this._open(); | |
| 6452 | - // Every name a prefix can match is one contiguous run of the primary key, | |
| 6453 | - // so bound the key on both sides. The query used to carry the cursor as | |
| 6454 | - // its only range, and SQLite then walked every earlier row in the | |
| 6455 | - // namespace before it could report that a late prefix matches nothing: an | |
| 6456 | - // empty-result list measured 684/s over 4,849 rows and 43/s over 114,881. | |
| 6457 | - // | |
| 6458 | - // The bounds decide which rows a list visits and the prefix comparison | |
| 6459 | - // still decides which rows match. A prefix whose bounds cannot be derived | |
| 6460 | - // -- one holding a lone surrogate, which no stored name can hold -- is | |
| 6461 | - // therefore answered at the old cost rather than short of keys. | |
| 6462 | - const upper = __kvPrefixUpperBound(prefix); | |
| 6463 | - // A cursor names a key this namespace already returned for this prefix, so | |
| 6464 | - // it is inside the range and replaces the prefix as the start. Carrying | |
| 6465 | - // both would leave SQLite to pick one as the seek and demote the other to | |
| 6466 | - // a filter, and picking the prefix rescans every earlier page. A cursor | |
| 6467 | - // arrives from the caller, so a hand-made one can start below the prefix; | |
| 6468 | - // the comparison below, and not the range, keeps that page correct. | |
| 6469 | - const start = after ? "name > ?" : "name >= ?"; | |
| 6470 | - const params = [after ? after : prefix]; | |
| 6471 | - if (upper !== null) params.push(upper); | |
| 6472 | - // `substr` compares under BINARY, so a prefix matches by bytes and not by | |
| 6473 | - // ASCII case. `LIKE` stood here and folded case, which made `list({prefix: | |
| 6474 | - // "A"})` answer a key named `a` -- upstream compares a byte prefix, and no | |
| 6475 | - // range bound can reproduce a case-folded match anyway. The length counts | |
| 6476 | - // code points, which is what SQLite counts, not UTF-16 units. | |
| 6477 | - if (prefix !== "") params.push(Array.from(prefix).length, prefix); | |
| 6478 | - const query = `SELECT name, metadata, expires_at FROM ${__KV_TABLE} | |
| 6479 | - WHERE ${start} | |
| 6480 | - ${upper === null ? "" : "AND name < ?"} | |
| 6481 | - ${prefix === "" ? "" : "AND substr(name, 1, ?) = ?"} | |
| 6482 | - AND (expires_at IS NULL OR expires_at > ?) | |
| 6483 | - ORDER BY name | |
| 6484 | - LIMIT ?`; | |
| 6485 | - params.push(now, limit + 1); | |
| 6486 | - __kvReportListPlan(sql, query, params); | |
| 6487 | - const rows = sql.exec(query, ...params).toArray(); | |
| 6488 | - const complete = rows.length <= limit; | |
| 6489 | - const page = complete ? rows : rows.slice(0, limit); | |
| 6490 | - return { | |
| 6491 | - keys: page.map((row) => ({ | |
| 6492 | - name: row.name, | |
| 6493 | - metadata: row.metadata ?? null, | |
| 6494 | - expiration: row.expires_at ?? null, | |
| 6495 | - })), | |
| 6496 | - complete, | |
| 6497 | - }; | |
| 6498 | - } | |
| 6499 | - | |
| 6500 | - // The operator's live key and byte counts. `size` stays in the row because | |
| 6501 | - // a bucket-backed value has a NULL inline `value`; `LENGTH(value)` would | |
| 6502 | - // report zero bytes for exactly the values whose size matters most. | |
| 6503 | - __kvMetrics({ now }) { | |
| 6504 | - const sql = this._open(); | |
| 6505 | - const row = sql.exec( | |
| 6506 | - `SELECT COUNT(*) AS count, | |
| 6507 | - COALESCE(SUM(size), 0) AS bytes | |
| 6508 | - FROM ${__KV_TABLE} | |
| 6509 | - WHERE expires_at IS NULL OR expires_at > ?`, | |
| 6510 | - now, | |
| 6511 | - ).toArray()[0]; | |
| 6512 | - return { count: row.count, bytes: row.bytes }; | |
| 6513 | - } | |
| 6514 | - | |
| 6515 | - // Reclaim what the read path already treats as gone. Bounded per call so a | |
| 6516 | - // namespace with a large expired population cannot hold the cell for an | |
| 6517 | - // unbounded time; the caller re-arms while there is more. | |
| 6518 | - __kvSweep({ now, limit }) { | |
| 6519 | - const sql = this._open(); | |
| 6520 | - const removed = __cellSweepBatch( | |
| 6521 | - this.ctx.storage, | |
| 6522 | - (bound) => sql.exec( | |
| 6523 | - `SELECT name FROM ${__KV_TABLE} | |
| 6524 | - WHERE expires_at IS NOT NULL AND expires_at <= ? | |
| 6525 | - ORDER BY expires_at | |
| 6526 | - LIMIT ?`, | |
| 6527 | - now, | |
| 6528 | - bound, | |
| 6529 | - ).toArray(), | |
| 6530 | - (row) => { | |
| 6531 | - sql.exec(`DELETE FROM ${__KV_TABLE} WHERE name = ?`, row.name); | |
| 6532 | - }, | |
| 6533 | - limit, | |
| 6534 | - ); | |
| 6535 | - return { removed }; | |
| 6536 | - } | |
| 6537 | - | |
| 6538 | - // The operator surface, reached only over `/runtime/`, which authenticates | |
| 6539 | - // with the fleet secret. `/do/` refuses every reserved class structurally, | |
| 6540 | - // so adding this handler does not put a namespace on an unauthenticated | |
| 6541 | - // route -- the trap d1.md decision 4 records paying for once, and the reason | |
| 6542 | - // that refusal is one question rather than one per class. | |
| 6543 | - // | |
| 6544 | - // Values cross this boundary as arrays of bytes rather than as text, because | |
| 6545 | - // a namespace holds bytes: a value written from a Worker as an ArrayBuffer | |
| 6546 | - // has no faithful string form, and `celld kv` must be able to read back | |
| 6547 | - // exactly what was written. | |
| 6548 | - async fetch(request) { | |
| 6549 | - let body; | |
| 6550 | - try { | |
| 6551 | - body = await request.json(); | |
| 6552 | - } catch { | |
| 6553 | - return Response.json({ error: "KV_ERROR: invalid request body" }, { status: 400 }); | |
| 6554 | - } | |
| 6555 | - const now = Date.now(); | |
| 6556 | - try { | |
| 6557 | - let result; | |
| 6558 | - switch (body.op) { | |
| 6559 | - case "get": { | |
| 6560 | - // Awaited: `__kvGet` resolves a bucket-backed value, so it is | |
| 6561 | - // async. Destructuring the promise instead threw "object is not | |
| 6562 | - // iterable" on every operator read, and only here -- the binding | |
| 6563 | - // reaches the same method over RPC, which awaits for it. | |
| 6564 | - const [row] = await this.__kvGet({ | |
| 6565 | - keys: [String(body.key)], | |
| 6566 | - withMetadata: true, | |
| 6567 | - withExpiration: true, | |
| 6568 | - now, | |
| 6569 | - }); | |
| 6570 | - result = row.found | |
| 6571 | - ? { | |
| 6572 | - found: true, | |
| 6573 | - ...__kvOperatorValue(row.value), | |
| 6574 | - tag: row.tag, | |
| 6575 | - metadata: row.metadata ?? null, | |
| 6576 | - expiration: row.expiration, | |
| 6577 | - } | |
| 6578 | - : { found: false }; | |
| 6579 | - break; | |
| 6580 | - } | |
| 6581 | - case "put": | |
| 6582 | - case "put-base64": { | |
| 6583 | - // Validated here, through the same helpers the binding calls, so a | |
| 6584 | - // key written by `celld kv` is a key the binding could have written. | |
| 6585 | - // The operator route used to arrive pre-validated by the CLI, which | |
| 6586 | - // put the same bound in two processes -- and they disagreed the first | |
| 6587 | - // time a test shortened one of them. | |
| 6588 | - const key = String(body.key); | |
| 6589 | - __kvCheckKey(key); | |
| 6590 | - const value = body.op === "put-base64" | |
| 6591 | - ? $$atob(String(body.value), true) | |
| 6592 | - : new Uint8Array(body.value); | |
| 6593 | - __kvCheckValue(value.byteLength); | |
| 6594 | - const metadata = body.metadata === undefined ? null : body.metadata; | |
| 6595 | - if (metadata !== null) __kvCheckMetadata(metadata); | |
| 6596 | - // Resolved from the cell's clock, not the caller's, because that is | |
| 6597 | - // the clock the read filter and the sweeper compare against. | |
| 6598 | - const expiresAt = __kvExpiryAt(now, body.expiration, body.expirationTtl); | |
| 6599 | - await this.__kvPut({ | |
| 6600 | - entries: [{ | |
| 6601 | - key, | |
| 6602 | - value, | |
| 6603 | - tag: String(body.tag ?? __KV_TAG_BYTES), | |
| 6604 | - metadata, | |
| 6605 | - expiresAt, | |
| 6606 | - }], | |
| 6607 | - }); | |
| 6608 | - result = { ok: true }; | |
| 6609 | - break; | |
| 6610 | - } | |
| 6611 | - case "delete": | |
| 6612 | - for (const key of body.keys) __kvCheckKey(String(key)); | |
| 6613 | - await this.__kvDelete({ keys: body.keys.map(String) }); | |
| 6614 | - result = { ok: true }; | |
| 6615 | - break; | |
| 6616 | - case "list": | |
| 6617 | - result = this.__kvList({ | |
| 6618 | - prefix: String(body.prefix ?? ""), | |
| 6619 | - limit: Number(body.limit), | |
| 6620 | - after: String(body.after ?? ""), | |
| 6621 | - now, | |
| 6622 | - }); | |
| 6623 | - break; | |
| 6624 | - // What `celld kv info` reports. `stored` counts every row and `live` | |
| 6625 | - // counts only what a read would return, so the difference is exactly | |
| 6626 | - // the population the sweeper still owes -- which is the one number | |
| 6627 | - // that makes reclamation observable from outside the cell. | |
| 6628 | - case "info": { | |
| 6629 | - const live = this.__kvMetrics({ now }); | |
| 6630 | - const total = this._open().exec( | |
| 6631 | - `SELECT COUNT(*) AS count FROM ${__KV_TABLE}`, | |
| 6632 | - ).toArray()[0]; | |
| 6633 | - result = { live: live.count, bytes: live.bytes, stored: total.count }; | |
| 6634 | - break; | |
| 6635 | - } | |
| 6636 | - default: | |
| 6637 | - return Response.json( | |
| 6638 | - { error: `KV_ERROR: unknown operation ${JSON.stringify(body.op)}` }, | |
| 6639 | - { status: 400 }, | |
| 6640 | - ); | |
| 6641 | - } | |
| 6642 | - return Response.json({ result }); | |
| 6643 | - } catch (error) { | |
| 6644 | - return Response.json( | |
| 6645 | - { error: String(error && error.message || error) }, | |
| 6646 | - { status: 400 }, | |
| 6647 | - ); | |
| 6648 | - } | |
| 6649 | - } | |
| 6650 | -} | |
| 6651 | - | |
| 6652 | -__cell.classes.__KvNamespace = __KvNamespaceCell; | |
| 6653 | -// RPC on a stub needs `extends DurableObject` or the js_rpc flag. This class is | |
| 6654 | -// the runtime's own, so grant it here rather than making every KV user set a | |
| 6655 | -// compatibility flag to reach a namespace. | |
| 6656 | -__cell.doExports.__KvNamespace = true; | |
| 6657 | - | |
| 6658 | -// The client half. | |
| 6659 | -// | |
| 6660 | -// Every number below is injected from `celld_logic::kv` as `__cell.kvLimits` | |
| 6661 | -// rather than written here, so the binding, `celld kv` and deploy-time | |
| 6662 | -// validation cannot disagree about what a valid key is. No new host op: D1 set | |
| 6663 | -// the bar at one and Workflows came in under it, and a limit is data rather | |
| 6664 | -// than a decision, so shipping the values is enough. What stays in JS is the | |
| 6665 | -// presentation -- the error text is the binding's published contract, in | |
| 6666 | -// upstream's `KV <OP> failed:` shape, and belongs beside the calls that raise | |
| 6667 | -// it. | |
| 6668 | -// | |
| 6669 | -// The cursor codec is the one thing that must byte-match Rust's, and it is | |
| 6670 | -// plain hex: a total function with a single right answer, which two correct | |
| 6671 | -// implementations cannot disagree about. A policy would be a different matter | |
| 6672 | -// and none is duplicated here. | |
| 6673 | -const __kvLimits = () => __cell.kvLimits; | |
| 6674 | - | |
| 6675 | -const __kvCheckKey = (key) => { | |
| 6676 | - if (key.length === 0) throw __kvError("a key must not be empty"); | |
| 6677 | - const bytes = __kvEncoder.encode(key).byteLength; | |
| 6678 | - if (bytes > __kvLimits().maxKeyBytes) { | |
| 6679 | - throw __kvError( | |
| 6680 | - `a key is at most ${__kvLimits().maxKeyBytes} bytes, got ${bytes}`, | |
| 6681 | - ); | |
| 6682 | - } | |
| 6683 | -}; | |
| 6684 | - | |
| 6685 | -// A TTL becomes an absolute deadline here, once, at the call. Resolving it | |
| 6686 | -// again later against a newer clock would extend the life of the key every | |
| 6687 | -// time anything re-read the row -- the reason a workflow persists a sleep | |
| 6688 | -// deadline and not its duration. | |
| 6689 | -const __kvCheckValue = (size) => { | |
| 6690 | - // Upstream's bound, and now the only one. A value above the inline bound is | |
| 6691 | - // no longer refused: it goes to the fleet bucket, which is the split | |
| 6692 | - // Cloudflare's own KV rearchitecture made and for the same reason -- a cell | |
| 6693 | - // replicates every write as LTX, so an inline value is paid for twice. | |
| 6694 | - if (size > __kvLimits().maxValueBytes) { | |
| 6695 | - throw __kvError(`a value is at most ${__kvLimits().maxValueBytes} bytes, got ${size}`); | |
| 6696 | - } | |
| 6697 | -}; | |
| 6698 | - | |
| 6699 | -const __kvCheckMetadata = (metadata) => { | |
| 6700 | - const bytes = __kvEncoder.encode(metadata).byteLength; | |
| 6701 | - if (bytes > __kvLimits().maxMetadataBytes) { | |
| 6702 | - throw __kvError( | |
| 6703 | - `metadata is at most ${__kvLimits().maxMetadataBytes} bytes, got ${bytes}`, | |
| 6704 | - ); | |
| 6705 | - } | |
| 6706 | -}; | |
| 6707 | - | |
| 6708 | -const __kvExpiryAt = (now, expiration, expirationTtl) => { | |
| 6709 | - if (expirationTtl !== undefined && expirationTtl !== null) { | |
| 6710 | - const ms = Math.floor(Number(expirationTtl) * 1000); | |
| 6711 | - if (!Number.isFinite(ms) || ms < __kvLimits().minExpirationTtlMs) { | |
| 6712 | - throw __kvError( | |
| 6713 | - `expirationTtl is at least ${__kvLimits().minExpirationTtlMs / 1000} seconds`, | |
| 6714 | - ); | |
| 6715 | - } | |
| 6716 | - return now + ms; | |
| 6717 | - } | |
| 6718 | - if (expiration !== undefined && expiration !== null) { | |
| 6719 | - const at = Math.floor(Number(expiration) * 1000); | |
| 6720 | - if (!Number.isFinite(at) || at <= now) { | |
| 6721 | - throw __kvError(`expiration ${expiration} is in the past`); | |
| 6722 | - } | |
| 6723 | - return at; | |
| 6724 | - } | |
| 6725 | - return null; | |
| 6726 | -}; | |
| 6727 | - | |
| 6728 | -const __kvCursor = { | |
| 6729 | - encode(key) { | |
| 6730 | - let out = ""; | |
| 6731 | - for (const byte of __kvEncoder.encode(key)) { | |
| 6732 | - out += byte.toString(16).padStart(2, "0"); | |
| 6733 | - } | |
| 6734 | - return out; | |
| 6735 | - }, | |
| 6736 | - decode(cursor) { | |
| 6737 | - // A malformed cursor is refused, never read as "start from the | |
| 6738 | - // beginning": that would hand a paginating caller its first page a second | |
| 6739 | - // time and call it progress. | |
| 6740 | - if (cursor.length % 2 !== 0 || /[^0-9a-f]/.test(cursor)) { | |
| 6741 | - throw __kvError("the list cursor is malformed"); | |
| 6742 | - } | |
| 6743 | - const bytes = new Uint8Array(cursor.length / 2); | |
| 6744 | - for (let at = 0; at < bytes.length; at += 1) { | |
| 6745 | - bytes[at] = Number.parseInt(cursor.slice(at * 2, at * 2 + 2), 16); | |
| 6746 | - } | |
| 6747 | - return __kvDecoder.decode(bytes); | |
| 6748 | - }, | |
| 6749 | -}; | |
| 6750 | - | |
| 6751 | -const __kvListLimit = (requested) => { | |
| 6752 | - const max = __kvLimits().maxListLimit; | |
| 6753 | - if (requested === undefined || requested === null) return max; | |
| 6754 | - const limit = Math.floor(Number(requested)); | |
| 6755 | - // Zero would be a page that never ends. | |
| 6756 | - if (!Number.isFinite(limit) || limit <= 0) return max; | |
| 6757 | - return Math.min(limit, max); | |
| 6758 | -}; | |
| 6759 | - | |
| 6760 | -// Upstream's four content types, and what each one means on the way in and out. | |
| 6761 | -const __KV_TAG_TEXT = "text"; | |
| 6762 | -const __KV_TAG_BYTES = "bytes"; | |
| 6763 | - | |
| 6764 | -const __kvEncoder = new TextEncoder(); | |
| 6765 | -const __kvDecoder = new TextDecoder(); | |
| 6766 | - | |
| 6767 | -// A value becomes bytes plus a tag, once, at the public boundary. Storing the | |
| 6768 | -// tag is what lets `get(key, "text")` and `get(key)` answer differently from | |
| 6769 | -// the same row without the cell parsing anything. | |
| 6770 | -const __kvEncodeValue = (value) => { | |
| 6771 | - if (typeof value === "string") { | |
| 6772 | - return { value: __kvEncoder.encode(value), tag: __KV_TAG_TEXT }; | |
| 6773 | - } | |
| 6774 | - if (value instanceof ArrayBuffer) { | |
| 6775 | - return { value: new Uint8Array(value.slice(0)), tag: __KV_TAG_BYTES }; | |
| 6776 | - } | |
| 6777 | - if (ArrayBuffer.isView(value)) { | |
| 6778 | - // Copied, not referenced. `sendBatch`'s resizable-ArrayBuffer regression | |
| 6779 | - // upstream is the same hazard: a caller may resize or reuse the buffer | |
| 6780 | - // between this call and the write, and a shallow view would then read | |
| 6781 | - // decommitted pages. | |
| 6782 | - return { | |
| 6783 | - value: new Uint8Array( | |
| 6784 | - value.buffer.slice(value.byteOffset, value.byteOffset + value.byteLength), | |
| 6785 | - ), | |
| 6786 | - tag: __KV_TAG_BYTES, | |
| 6787 | - }; | |
| 6788 | - } | |
| 6789 | - throw __kvError( | |
| 6790 | - "a KV value must be a string, an ArrayBuffer, a typed array, or a ReadableStream", | |
| 6791 | - ); | |
| 6792 | -}; | |
| 6793 | - | |
| 6794 | -// Upstream accepts a ReadableStream, and `put(key, request.body)` is how a | |
| 6795 | -// handler stores a request body, so refusing one broke the obvious spelling. | |
| 6796 | -// The stream must become bytes before the cell write: a cell replicates a | |
| 6797 | -// value as LTX, and a pending stream has no bytes to replicate. | |
| 6798 | -// | |
| 6799 | -// The bound is enforced while draining rather than on the finished buffer. | |
| 6800 | -// Checking afterwards would let a body larger than the limit reach memory in | |
| 6801 | -// full before the refusal, which hands an unbounded allocation to whoever | |
| 6802 | -// sends the request. | |
| 6803 | -const __kvDrainStream = async (stream) => { | |
| 6804 | - const limit = __kvLimits().maxValueBytes; | |
| 6805 | - const reader = stream.getReader(); | |
| 6806 | - const chunks = []; | |
| 6807 | - let size = 0; | |
| 6808 | - try { | |
| 6809 | - for (;;) { | |
| 6810 | - const { done, value } = await reader.read(); | |
| 6811 | - if (done) break; | |
| 6812 | - const chunk = ArrayBuffer.isView(value) | |
| 6813 | - ? new Uint8Array(value.buffer, value.byteOffset, value.byteLength) | |
| 6814 | - : new Uint8Array(value); | |
| 6815 | - size += chunk.byteLength; | |
| 6816 | - if (size > limit) { | |
| 6817 | - throw __kvError(`a value is at most ${limit} bytes, and the stream is larger`); | |
| 6818 | - } | |
| 6819 | - chunks.push(chunk); | |
| 6820 | - } | |
| 6821 | - } catch (error) { | |
| 6822 | - await reader.cancel(error).catch(() => {}); | |
| 6823 | - throw error; | |
| 6824 | - } finally { | |
| 6825 | - reader.releaseLock(); | |
| 6826 | - } | |
| 6827 | - // The chunk wrappers can alias the buffers yielded by the stream. `set()` | |
| 6828 | - // copies their current bytes into one owned result, so later mutation of a | |
| 6829 | - // yielded buffer cannot change the stored value. | |
| 6830 | - const value = new Uint8Array(size); | |
| 6831 | - let offset = 0; | |
| 6832 | - for (const chunk of chunks) { | |
| 6833 | - value.set(chunk, offset); | |
| 6834 | - offset += chunk.byteLength; | |
| 6835 | - } | |
| 6836 | - return value; | |
| 6837 | -}; | |
| 6838 | - | |
| 6839 | -const __kvDecodeValue = (bytes, tag, type) => { | |
| 6840 | - const view = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes); | |
| 6841 | - switch (type) { | |
| 6842 | - case "arrayBuffer": | |
| 6843 | - return view.buffer.slice(view.byteOffset, view.byteOffset + view.byteLength); | |
| 6844 | - case "json": | |
| 6845 | - return JSON.parse(__kvDecoder.decode(view)); | |
| 6846 | - case "stream": | |
| 6847 | - return new Response(view).body; | |
| 6848 | - case "text": | |
| 6849 | - default: | |
| 6850 | - // A value written as bytes still decodes as text when asked for text, | |
| 6851 | - // which is upstream's behaviour and the reason the tag is advisory | |
| 6852 | - // rather than a type check. | |
| 6853 | - return __kvDecoder.decode(view); | |
| 6854 | - } | |
| 6855 | -}; | |
| 6856 | - | |
| 6857 | -const __kvReadOptions = (options) => { | |
| 6858 | - if (typeof options === "string") return { type: options }; | |
| 6859 | - if (options === null || options === undefined) return { type: "text" }; | |
| 6860 | - return { type: options.type ?? "text", cacheTtl: options.cacheTtl }; | |
| 6861 | -}; | |
| 6862 | - | |
| 6863 | -class KvNamespace { | |
| 6864 | - constructor(id, cellName) { | |
| 6865 | - Object.defineProperty(this, "_id", { value: id }); | |
| 6866 | - Object.defineProperty(this, "_cellName", { value: cellName }); | |
| 6867 | - } | |
| 6868 | - | |
| 6869 | - // Resolved per call rather than cached: a cell can move between calls, and | |
| 6870 | - // `getByName` costs what the Durable Object path already pays. | |
| 6871 | - get _stub() { | |
| 6872 | - return __cell.makeNamespace("__KvNamespace").getByName(this._cellName); | |
| 6873 | - } | |
| 6874 | - | |
| 6875 | - async _read(keys, options, withMetadata) { | |
| 6876 | - const { type } = __kvReadOptions(options); | |
| 6877 | - for (const key of keys) __kvCheckKey(key); | |
| 6878 | - const rows = await this._stub.__kvGet({ | |
| 6879 | - keys, | |
| 6880 | - withMetadata, | |
| 6881 | - now: Date.now(), | |
| 6882 | - }); | |
| 6883 | - return rows.map((row) => { | |
| 6884 | - if (!row.found) return { key: row.key, value: null, metadata: null }; | |
| 6885 | - return { | |
| 6886 | - key: row.key, | |
| 6887 | - value: __kvDecodeValue(row.value, row.tag, type), | |
| 6888 | - metadata: row.metadata === null || row.metadata === undefined | |
| 6889 | - ? null | |
| 6890 | - : JSON.parse(row.metadata), | |
| 6891 | - }; | |
| 6892 | - }); | |
| 6893 | - } | |
| 6894 | - | |
| 6895 | - // `get(key)` answers a value; `get([keys])` answers a Map with a null hole | |
| 6896 | - // for a key that is not there. Upstream's bulk form is a Map and not an | |
| 6897 | - // object, which matters: an object would collide a key named `__proto__` | |
| 6898 | - // with the prototype chain. | |
| 6899 | - async get(key, options) { | |
| 6900 | - if (Array.isArray(key)) { | |
| 6901 | - const rows = await this._read(__kvBulkKeys(key), options, false); | |
| 6902 | - return new Map(rows.map((row) => [row.key, row.value])); | |
| 6903 | - } | |
| 6904 | - const [row] = await this._read([String(key)], options, false); | |
| 6905 | - return row.value; | |
| 6906 | - } | |
| 6907 | - | |
| 6908 | - async getWithMetadata(key, options) { | |
| 6909 | - if (Array.isArray(key)) { | |
| 6910 | - const rows = await this._read(__kvBulkKeys(key), options, true); | |
| 6911 | - return new Map( | |
| 6912 | - rows.map((row) => [row.key, { value: row.value, metadata: row.metadata }]), | |
| 6913 | - ); | |
| 6914 | - } | |
| 6915 | - const [row] = await this._read([String(key)], options, true); | |
| 6916 | - return { | |
| 6917 | - value: row.value, | |
| 6918 | - metadata: row.metadata, | |
| 6919 | - // Null, and honestly so: celld has no read cache, and reporting a HIT | |
| 6920 | - // from a runtime that never cached anything would be a lie in a field | |
| 6921 | - // applications read. | |
| 6922 | - cacheStatus: null, | |
| 6923 | - }; | |
| 6924 | - } | |
| 6925 | - | |
| 6926 | - async put(key, value, options) { | |
| 6927 | - const name = String(key); | |
| 6928 | - __kvCheckKey(name); | |
| 6929 | - let encoded; | |
| 6930 | - if (typeof ReadableStream !== "undefined" && value instanceof ReadableStream) { | |
| 6931 | - encoded = { value: await __kvDrainStream(value), tag: __KV_TAG_BYTES }; | |
| 6932 | - } else { | |
| 6933 | - encoded = __kvEncodeValue(value); | |
| 6934 | - __kvCheckValue(encoded.value.byteLength); | |
| 6935 | - } | |
| 6936 | - const metadata = options && options.metadata !== undefined | |
| 6937 | - ? JSON.stringify(options.metadata) | |
| 6938 | - : null; | |
| 6939 | - if (metadata !== null) __kvCheckMetadata(metadata); | |
| 6940 | - const expiresAt = __kvExpiryAt( | |
| 6941 | - Date.now(), | |
| 6942 | - options && options.expiration, | |
| 6943 | - options && options.expirationTtl, | |
| 6944 | - ); | |
| 6945 | - await this._stub.__kvPut({ | |
| 6946 | - entries: [{ key: name, value: encoded.value, tag: encoded.tag, metadata, expiresAt }], | |
| 6947 | - }); | |
| 6948 | - } | |
| 6949 | - | |
| 6950 | - async delete(key) { | |
| 6951 | - const name = String(key); | |
| 6952 | - __kvCheckKey(name); | |
| 6953 | - await this._stub.__kvDelete({ keys: [name] }); | |
| 6954 | - } | |
| 6955 | - | |
| 6956 | - // Upstream takes one key or an array, and caps the array at the same 100 a | |
| 6957 | - // bulk get takes. | |
| 6958 | - async deleteBulk(keys) { | |
| 6959 | - const names = Array.isArray(keys) ? __kvBulkKeys(keys) : [String(keys)]; | |
| 6960 | - for (const name of names) __kvCheckKey(name); | |
| 6961 | - await this._stub.__kvDelete({ keys: names }); | |
| 6962 | - } | |
| 6963 | - | |
| 6964 | - async list(options) { | |
| 6965 | - const prefix = options && options.prefix ? String(options.prefix) : ""; | |
| 6966 | - const limit = __kvListLimit(options && options.limit); | |
| 6967 | - const after = options && options.cursor ? __kvCursor.decode(String(options.cursor)) : ""; | |
| 6968 | - const page = await this._stub.__kvList({ prefix, limit, after, now: Date.now() }); | |
| 6969 | - const keys = page.keys.map((entry) => { | |
| 6970 | - const key = { name: entry.name }; | |
| 6971 | - if (entry.metadata !== null) key.metadata = JSON.parse(entry.metadata); | |
| 6972 | - // Upstream reports an expiration in seconds. | |
| 6973 | - if (entry.expiration !== null) key.expiration = Math.floor(entry.expiration / 1000); | |
| 6974 | - return key; | |
| 6975 | - }); | |
| 6976 | - if (page.complete) return { keys, list_complete: true, cacheStatus: null }; | |
| 6977 | - return { | |
| 6978 | - keys, | |
| 6979 | - list_complete: false, | |
| 6980 | - cursor: __kvCursor.encode(keys[keys.length - 1].name), | |
| 6981 | - cacheStatus: null, | |
| 6982 | - }; | |
| 6983 | - } | |
| 6984 | -} | |
| 6985 | - | |
| 6986 | -// The bulk ceiling belongs to the binding, and a CLI chunks beneath it rather | |
| 6987 | -// than inheriting it. An empty array is refused because upstream refuses it: | |
| 6988 | -// answering an empty Map would look like "none of these keys exist". | |
| 6989 | -const __kvBulkKeys = (keys) => { | |
| 6990 | - if (keys.length === 0) throw __kvError("a bulk get needs at least one key"); | |
| 6991 | - if (keys.length > __kvLimits().maxBulkKeys) { | |
| 6992 | - throw __kvError( | |
| 6993 | - `a bulk get takes at most ${__kvLimits().maxBulkKeys} keys, got ${keys.length}`, | |
| 6994 | - ); | |
| 6995 | - } | |
| 6996 | - return keys.map(String); | |
| 6997 | -}; | |
| 6998 | - | |
| 6999 | -const __makeKvNamespace = __celld.__makeKvNamespace = | |
| 7000 | - (id, cellName) => new KvNamespace(id, cellName); | |
| 7001 | - | |
| 7002 | -// ---- Queues -------------------------------------------------------------- | |
| 7003 | -// A Queue is one runtime-supplied Durable Object. The producer binding writes | |
| 7004 | -// bytes and a content tag through RPC, and the cell owns the durable order, | |
| 7005 | -// deadlines, leases, and alarms. `celld_logic::queue` owns every transition | |
| 7006 | -// that can invalidate a lease or choose a deadline; this code supplies SQL and | |
| 7007 | -// the Cloudflare-compatible presentation. | |
| 7008 | - | |
| 7009 | -const __QUEUE_MESSAGES = "__queue_messages"; | |
| 7010 | -const __QUEUE_META = "__queue_meta"; | |
| 7011 | -const __QUEUE_STATS = "__queue_stats"; | |
| 7012 | -const __QUEUE_TRANSFER_RECEIPTS = "__queue_transfer_receipts"; | |
| 7013 | -const __queueEncoder = new TextEncoder(); | |
| 7014 | - | |
| 7015 | -// Independent send() calls share the same economics as sendBatch() without | |
| 7016 | -// changing the public promise boundary. The first call opens a four-millisecond | |
| 7017 | -// owner-local group by default; later cell events append their already-copied | |
| 7018 | -// entries, and park on their own promise. One event commits the bounded group, | |
| 7019 | -// and every response still trails that commit through the ordinary output | |
| 7020 | -// gate. The three caps bound heap retention and keep the persisted transaction | |
| 7021 | -// inside the public sendBatch limits. | |
| 7022 | -const __QUEUE_PRODUCER_GROUP_CALLS = 64; | |
| 7023 | -const __QUEUE_PRODUCER_GROUP_MESSAGES = 100; | |
| 7024 | -const __QUEUE_PRODUCER_GROUP_BYTES = 256_000; | |
| 7025 | - | |
| 7026 | -const __queueError = (message) => new Error("QUEUE_ERROR: " + String(message)); | |
| 7027 | -// A Queue message id is a UUIDv7 (RFC 9562): 48 bits of enqueue time, a | |
| 7028 | -// 12-bit sequence inside that millisecond, and 62 random bits. It keeps the | |
| 7029 | -// UUID shape a consumer can parse, and it sorts in enqueue order, so the | |
| 7030 | -// UNIQUE index on `id` appends. A random v4 id made every grouped send | |
| 7031 | -// transaction dirty one index leaf per message (about 1.6 WAL frames per | |
| 7032 | -// 64-byte message) and turned every passive checkpoint into a random write | |
| 7033 | -// across the whole backlog, which is what made a deep Queue's checkpoint | |
| 7034 | -// cost grow with its backlog. The sequence never moves backwards inside one | |
| 7035 | -// process, so a clock step only widens the gap between consecutive ids. | |
| 7036 | -let __queueIdMs = 0; | |
| 7037 | -let __queueIdSeq = 0; | |
| 7038 | -function __queueMessageId(now) { | |
| 7039 | - if (now > __queueIdMs) { | |
| 7040 | - __queueIdMs = now; | |
| 7041 | - __queueIdSeq = 0; | |
| 7042 | - } else { | |
| 7043 | - __queueIdSeq += 1; | |
| 7044 | - if (__queueIdSeq > 0xfff) { | |
| 7045 | - __queueIdMs += 1; | |
| 7046 | - __queueIdSeq = 0; | |
| 7047 | - } | |
| 7048 | - } | |
| 7049 | - const bytes = new Uint8Array(16); | |
| 7050 | - crypto.getRandomValues(bytes); | |
| 7051 | - const ms = __queueIdMs; | |
| 7052 | - bytes[0] = Math.floor(ms / 0x10000000000) & 0xff; | |
| 7053 | - bytes[1] = Math.floor(ms / 0x100000000) & 0xff; | |
| 7054 | - bytes[2] = (ms >>> 24) & 0xff; | |
| 7055 | - bytes[3] = (ms >>> 16) & 0xff; | |
| 7056 | - bytes[4] = (ms >>> 8) & 0xff; | |
| 7057 | - bytes[5] = ms & 0xff; | |
| 7058 | - bytes[6] = 0x70 | (__queueIdSeq >> 8); | |
| 7059 | - bytes[7] = __queueIdSeq & 0xff; | |
| 7060 | - bytes[8] = (bytes[8] & 0x3f) | 0x80; | |
| 7061 | - let hex = ""; | |
| 7062 | - for (let i = 0; i < 16; i++) hex += bytes[i].toString(16).padStart(2, "0"); | |
| 7063 | - return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${ | |
| 7064 | - hex.slice(16, 20) | |
| 7065 | - }-${hex.slice(20)}`; | |
| 7066 | -} | |
| 7067 | -const __queueLimits = () => __cell.queueLimits; | |
| 7068 | -const __queuePolicy = (request) => | |
| 7069 | - JSON.parse(__queue_policy(JSON.stringify(request))); | |
| 7070 | - | |
| 7071 | -const __queueDelay = (value, fallback = 0) => { | |
| 7072 | - if (value === undefined || value === null) return fallback; | |
| 7073 | - const seconds = Number(value); | |
| 7074 | - if (!Number.isInteger(seconds) || seconds < 0 || | |
| 7075 | - seconds > __queueLimits().maxDelaySeconds) { | |
| 7076 | - throw __queueError( | |
| 7077 | - `delaySeconds must be an integer from 0 to ${__queueLimits().maxDelaySeconds}`, | |
| 7078 | - ); | |
| 7079 | - } | |
| 7080 | - return seconds; | |
| 7081 | -}; | |
| 7082 | - | |
| 7083 | -const __queueBytes = (value) => { | |
| 7084 | - if (value instanceof ArrayBuffer) { | |
| 7085 | - return new Uint8Array(value.slice(0)); | |
| 7086 | - } | |
| 7087 | - if (ArrayBuffer.isView(value)) { | |
| 7088 | - return new Uint8Array( | |
| 7089 | - value.buffer.slice(value.byteOffset, value.byteOffset + value.byteLength), | |
| 7090 | - ); | |
| 7091 | - } | |
| 7092 | - throw __queueError("a bytes message must be an ArrayBuffer or a typed array"); | |
| 7093 | -}; | |
| 7094 | - | |
| 7095 | -// Encode before entering the cell. The copy makes `sendBatch()` immune to a | |
| 7096 | -// caller resizing or reusing a backing buffer while the durable write awaits. | |
| 7097 | -const __queueEncode = (body, requestedType) => { | |
| 7098 | - const contentType = requestedType ?? | |
| 7099 | - (__cell.compat.queueJsonMessages ? "json" : "v8"); | |
| 7100 | - let bytes; | |
| 7101 | - switch (contentType) { | |
| 7102 | - case "text": | |
| 7103 | - bytes = __queueEncoder.encode(String(body)); | |
| 7104 | - break; | |
| 7105 | - case "bytes": | |
| 7106 | - bytes = __queueBytes(body); | |
| 7107 | - break; | |
| 7108 | - case "json": { | |
| 7109 | - let json; | |
| 7110 | - try { | |
| 7111 | - json = JSON.stringify(body); | |
| 7112 | - } catch (error) { | |
| 7113 | - throw __queueError("the JSON message body cannot be serialized", error); | |
| 7114 | - } | |
| 7115 | - if (json === undefined) { | |
| 7116 | - throw __queueError("the JSON message body cannot be undefined"); | |
| 7117 | - } | |
| 7118 | - bytes = __queueEncoder.encode(json); | |
| 7119 | - break; | |
| 7120 | - } | |
| 7121 | - case "v8": | |
| 7122 | - try { | |
| 7123 | - bytes = __sc_encode(body); | |
| 7124 | - } catch (error) { | |
| 7125 | - throw __queueError("the message body cannot be cloned", error); | |
| 7126 | - } | |
| 7127 | - break; | |
| 7128 | - default: | |
| 7129 | - throw __queueError( | |
| 7130 | - `contentType must be "text", "bytes", "json", or "v8", got ${JSON.stringify(contentType)}`, | |
| 7131 | - ); | |
| 7132 | - } | |
| 7133 | - if (bytes.byteLength > __queueLimits().maxMessageBytes) { | |
| 7134 | - throw __queueError( | |
| 7135 | - `a message is at most ${__queueLimits().maxMessageBytes} bytes, got ${bytes.byteLength}`, | |
| 7136 | - ); | |
| 7137 | - } | |
| 7138 | - return { body: bytes, contentType, size: bytes.byteLength }; | |
| 7139 | -}; | |
| 7140 | - | |
| 7141 | -// A lease-scoped read must seek, not walk the backlog. The plan is the only | |
| 7142 | -// evidence that says which, and it is cheap to ask for, so a gated test seam | |
| 7143 | -// reads it from the shipped query rather than from a copy that can drift. | |
| 7144 | -const __queueReportLeaseLookupPlan = (sql, query, leaseId) => { | |
| 7145 | - if (typeof __test_queue_lease_lookup_plan !== "function") return; | |
| 7146 | - const plan = sql.exec(`EXPLAIN QUERY PLAN ${query}`, leaseId) | |
| 7147 | - .toArray() | |
| 7148 | - .map((row) => row.detail) | |
| 7149 | - .join("; "); | |
| 7150 | - __test_queue_lease_lookup_plan(plan); | |
| 7151 | -}; | |
| 7152 | - | |
| 7153 | -const __queueMetricsView = (metrics) => ({ | |
| 7154 | - backlogCount: metrics.backlogCount, | |
| 7155 | - backlogBytes: metrics.backlogBytes, | |
| 7156 | - oldestMessageTimestamp: metrics.oldestMessageTimestamp === null || | |
| 7157 | - metrics.oldestMessageTimestamp === undefined | |
| 7158 | - ? undefined | |
| 7159 | - : new Date(metrics.oldestMessageTimestamp), | |
| 7160 | -}); | |
| 7161 | - | |
| 7162 | -class __QueueCell { | |
| 7163 | - constructor(ctx) { | |
| 7164 | - this.ctx = ctx; | |
| 7165 | - this.queue = ctx.id.name; | |
| 7166 | - this._ready = false; | |
| 7167 | - this._producerGroup = null; | |
| 7168 | - } | |
| 7169 | - | |
| 7170 | - _open() { | |
| 7171 | - if (this._ready) return this.ctx.storage.sql; | |
| 7172 | - const sql = this.ctx.storage.sql; | |
| 7173 | - sql.exec( | |
| 7174 | - `CREATE TABLE IF NOT EXISTS ${__QUEUE_MESSAGES} ( | |
| 7175 | - seq INTEGER PRIMARY KEY AUTOINCREMENT, | |
| 7176 | - id TEXT NOT NULL UNIQUE, | |
| 7177 | - body BLOB NOT NULL, | |
| 7178 | - content_type TEXT NOT NULL, | |
| 7179 | - size INTEGER NOT NULL, | |
| 7180 | - enqueued_at INTEGER NOT NULL, | |
| 7181 | - visible_at INTEGER NOT NULL, | |
| 7182 | - attempts INTEGER NOT NULL DEFAULT 0, | |
| 7183 | - lease_id TEXT, | |
| 7184 | - lease_generation INTEGER NOT NULL DEFAULT 0, | |
| 7185 | - leased_until INTEGER, | |
| 7186 | - purge_on_settle INTEGER NOT NULL DEFAULT 0, | |
| 7187 | - dlq_target TEXT, | |
| 7188 | - dlq_transfer_id TEXT, | |
| 7189 | - transfer_kind TEXT, | |
| 7190 | - dead_letter_source TEXT, | |
| 7191 | - CHECK ((dlq_target IS NULL AND transfer_kind IS NULL) | |
| 7192 | - OR (dlq_target IS NOT NULL | |
| 7193 | - AND transfer_kind IN ('dead-letter', 'redrive'))) | |
| 7194 | - )`, | |
| 7195 | - ); | |
| 7196 | - sql.exec( | |
| 7197 | - `CREATE INDEX IF NOT EXISTS ${__QUEUE_MESSAGES}_visible | |
| 7198 | - ON ${__QUEUE_MESSAGES} (visible_at, seq)`, | |
| 7199 | - ); | |
| 7200 | - // Rearming is on every producer acknowledgement and settlement. Each | |
| 7201 | - // scheduling lookup must therefore stop at one deadline or one batch; | |
| 7202 | - // an aggregate over the backlog makes a large Queue quadratic to fill. | |
| 7203 | - sql.exec( | |
| 7204 | - `CREATE INDEX IF NOT EXISTS ${__QUEUE_MESSAGES}_ready | |
| 7205 | - ON ${__QUEUE_MESSAGES} (visible_at, seq) | |
| 7206 | - WHERE purge_on_settle = 0 AND dlq_target IS NULL | |
| 7207 | - AND lease_id IS NULL`, | |
| 7208 | - ); | |
| 7209 | - sql.exec( | |
| 7210 | - `CREATE INDEX IF NOT EXISTS ${__QUEUE_MESSAGES}_enqueued | |
| 7211 | - ON ${__QUEUE_MESSAGES} (enqueued_at, seq)`, | |
| 7212 | - ); | |
| 7213 | - sql.exec( | |
| 7214 | - `CREATE INDEX IF NOT EXISTS ${__QUEUE_MESSAGES}_retained | |
| 7215 | - ON ${__QUEUE_MESSAGES} (enqueued_at, seq) | |
| 7216 | - WHERE purge_on_settle = 0 AND dlq_target IS NULL`, | |
| 7217 | - ); | |
| 7218 | - sql.exec( | |
| 7219 | - `CREATE INDEX IF NOT EXISTS ${__QUEUE_MESSAGES}_lease | |
| 7220 | - ON ${__QUEUE_MESSAGES} (leased_until, seq) | |
| 7221 | - WHERE lease_id IS NOT NULL`, | |
| 7222 | - ); | |
| 7223 | - sql.exec( | |
| 7224 | - `CREATE INDEX IF NOT EXISTS ${__QUEUE_MESSAGES}_moving | |
| 7225 | - ON ${__QUEUE_MESSAGES} (seq) | |
| 7226 | - WHERE dlq_target IS NOT NULL`, | |
| 7227 | - ); | |
| 7228 | - // Dispatch and settlement both select a whole batch by its lease. Without | |
| 7229 | - // this index SQLite answers them by walking every row: the dispatch | |
| 7230 | - // readback scans `_visible` and the settlement scan walks the table, so | |
| 7231 | - // each delivered batch costs two passes over the backlog. The `_lease` | |
| 7232 | - // index cannot serve them because it is keyed on `leased_until`. | |
| 7233 | - // The partial predicate keeps only leased rows, which `max_concurrency` | |
| 7234 | - // times `max_batch_size` bounds, and an inserted message has a null | |
| 7235 | - // `lease_id`, so `send` pays nothing for it. | |
| 7236 | - sql.exec( | |
| 7237 | - `CREATE INDEX IF NOT EXISTS ${__QUEUE_MESSAGES}_lease_batch | |
| 7238 | - ON ${__QUEUE_MESSAGES} (lease_id, visible_at, seq) | |
| 7239 | - WHERE lease_id IS NOT NULL`, | |
| 7240 | - ); | |
| 7241 | - // The live-row index catches an impossible duplicate while a received | |
| 7242 | - // message remains queued. The receipt below is the durable deduplication | |
| 7243 | - // record after a consumer or purge removes that message. | |
| 7244 | - sql.exec( | |
| 7245 | - `CREATE UNIQUE INDEX IF NOT EXISTS ${__QUEUE_MESSAGES}_dlq_transfer | |
| 7246 | - ON ${__QUEUE_MESSAGES} (dlq_transfer_id) | |
| 7247 | - WHERE dlq_transfer_id IS NOT NULL AND dlq_target IS NULL`, | |
| 7248 | - ); | |
| 7249 | - sql.exec( | |
| 7250 | - `CREATE TABLE IF NOT EXISTS ${__QUEUE_META} ( | |
| 7251 | - name TEXT PRIMARY KEY, | |
| 7252 | - value TEXT NOT NULL | |
| 7253 | - ) WITHOUT ROWID`, | |
| 7254 | - ); | |
| 7255 | - // The producer result and operator metrics are on hot paths. SQLite | |
| 7256 | - // triggers keep the three values in the same transaction as every row | |
| 7257 | - // transition, so a caller cannot observe a new message with old totals. | |
| 7258 | - sql.exec( | |
| 7259 | - `CREATE TABLE IF NOT EXISTS ${__QUEUE_STATS} ( | |
| 7260 | - id INTEGER PRIMARY KEY CHECK (id = 1), | |
| 7261 | - stored_count INTEGER NOT NULL, | |
| 7262 | - backlog_count INTEGER NOT NULL, | |
| 7263 | - backlog_bytes INTEGER NOT NULL, | |
| 7264 | - oldest_message_timestamp INTEGER | |
| 7265 | - )`, | |
| 7266 | - ); | |
| 7267 | - sql.exec( | |
| 7268 | - `INSERT INTO ${__QUEUE_STATS} | |
| 7269 | - (id, stored_count, backlog_count, backlog_bytes, | |
| 7270 | - oldest_message_timestamp) | |
| 7271 | - SELECT 1, | |
| 7272 | - COUNT(*), | |
| 7273 | - COALESCE(SUM(purge_on_settle = 0), 0), | |
| 7274 | - COALESCE(SUM(CASE WHEN purge_on_settle = 0 THEN size ELSE 0 END), 0), | |
| 7275 | - MIN(CASE WHEN purge_on_settle = 0 THEN enqueued_at END) | |
| 7276 | - FROM ${__QUEUE_MESSAGES} | |
| 7277 | - WHERE true | |
| 7278 | - ON CONFLICT(id) DO NOTHING`, | |
| 7279 | - ); | |
| 7280 | - sql.exec( | |
| 7281 | - `CREATE TRIGGER IF NOT EXISTS ${__QUEUE_MESSAGES}_stored_insert | |
| 7282 | - AFTER INSERT ON ${__QUEUE_MESSAGES} | |
| 7283 | - BEGIN | |
| 7284 | - UPDATE ${__QUEUE_STATS} | |
| 7285 | - SET stored_count = stored_count + 1 | |
| 7286 | - WHERE id = 1; | |
| 7287 | - END`, | |
| 7288 | - ); | |
| 7289 | - sql.exec( | |
| 7290 | - `CREATE TRIGGER IF NOT EXISTS ${__QUEUE_MESSAGES}_stored_delete | |
| 7291 | - AFTER DELETE ON ${__QUEUE_MESSAGES} | |
| 7292 | - BEGIN | |
| 7293 | - UPDATE ${__QUEUE_STATS} | |
| 7294 | - SET stored_count = stored_count - 1 | |
| 7295 | - WHERE id = 1; | |
| 7296 | - END`, | |
| 7297 | - ); | |
| 7298 | - sql.exec( | |
| 7299 | - `CREATE TRIGGER IF NOT EXISTS ${__QUEUE_MESSAGES}_stats_insert | |
| 7300 | - AFTER INSERT ON ${__QUEUE_MESSAGES} | |
| 7301 | - WHEN new.purge_on_settle = 0 | |
| 7302 | - BEGIN | |
| 7303 | - UPDATE ${__QUEUE_STATS} | |
| 7304 | - SET backlog_count = backlog_count + 1, | |
| 7305 | - backlog_bytes = backlog_bytes + new.size, | |
| 7306 | - oldest_message_timestamp = CASE | |
| 7307 | - WHEN oldest_message_timestamp IS NULL | |
| 7308 | - OR new.enqueued_at < oldest_message_timestamp | |
| 7309 | - THEN new.enqueued_at ELSE oldest_message_timestamp END | |
| 7310 | - WHERE id = 1; | |
| 7311 | - END`, | |
| 7312 | - ); | |
| 7313 | - sql.exec( | |
| 7314 | - `CREATE TRIGGER IF NOT EXISTS ${__QUEUE_MESSAGES}_stats_delete | |
| 7315 | - AFTER DELETE ON ${__QUEUE_MESSAGES} | |
| 7316 | - WHEN old.purge_on_settle = 0 | |
| 7317 | - BEGIN | |
| 7318 | - UPDATE ${__QUEUE_STATS} | |
| 7319 | - SET backlog_count = backlog_count - 1, | |
| 7320 | - backlog_bytes = backlog_bytes - old.size, | |
| 7321 | - oldest_message_timestamp = CASE | |
| 7322 | - WHEN backlog_count <= 1 THEN NULL | |
| 7323 | - WHEN oldest_message_timestamp = old.enqueued_at | |
| 7324 | - THEN (SELECT MIN(enqueued_at) FROM ${__QUEUE_MESSAGES} | |
| 7325 | - WHERE purge_on_settle = 0) | |
| 7326 | - ELSE oldest_message_timestamp END | |
| 7327 | - WHERE id = 1; | |
| 7328 | - END`, | |
| 7329 | - ); | |
| 7330 | - sql.exec( | |
| 7331 | - `CREATE TRIGGER IF NOT EXISTS ${__QUEUE_MESSAGES}_stats_exclude | |
| 7332 | - AFTER UPDATE OF purge_on_settle ON ${__QUEUE_MESSAGES} | |
| 7333 | - WHEN old.purge_on_settle = 0 AND new.purge_on_settle != 0 | |
| 7334 | - BEGIN | |
| 7335 | - UPDATE ${__QUEUE_STATS} | |
| 7336 | - SET backlog_count = backlog_count - 1, | |
| 7337 | - backlog_bytes = backlog_bytes - old.size, | |
| 7338 | - oldest_message_timestamp = CASE | |
| 7339 | - WHEN backlog_count <= 1 THEN NULL | |
| 7340 | - WHEN oldest_message_timestamp = old.enqueued_at | |
| 7341 | - THEN (SELECT MIN(enqueued_at) FROM ${__QUEUE_MESSAGES} | |
| 7342 | - WHERE purge_on_settle = 0) | |
| 7343 | - ELSE oldest_message_timestamp END | |
| 7344 | - WHERE id = 1; | |
| 7345 | - END`, | |
| 7346 | - ); | |
| 7347 | - sql.exec( | |
| 7348 | - `CREATE TRIGGER IF NOT EXISTS ${__QUEUE_MESSAGES}_stats_include | |
| 7349 | - AFTER UPDATE OF purge_on_settle ON ${__QUEUE_MESSAGES} | |
| 7350 | - WHEN old.purge_on_settle != 0 AND new.purge_on_settle = 0 | |
| 7351 | - BEGIN | |
| 7352 | - UPDATE ${__QUEUE_STATS} | |
| 7353 | - SET backlog_count = backlog_count + 1, | |
| 7354 | - backlog_bytes = backlog_bytes + new.size, | |
| 7355 | - oldest_message_timestamp = CASE | |
| 7356 | - WHEN oldest_message_timestamp IS NULL | |
| 7357 | - OR new.enqueued_at < oldest_message_timestamp | |
| 7358 | - THEN new.enqueued_at ELSE oldest_message_timestamp END | |
| 7359 | - WHERE id = 1; | |
| 7360 | - END`, | |
| 7361 | - ); | |
| 7362 | - sql.exec( | |
| 7363 | - `CREATE TABLE IF NOT EXISTS ${__QUEUE_TRANSFER_RECEIPTS} ( | |
| 7364 | - transfer_id TEXT PRIMARY KEY, | |
| 7365 | - message_id TEXT NOT NULL, | |
| 7366 | - dead_letter_source TEXT, | |
| 7367 | - expires_at INTEGER NOT NULL | |
| 7368 | - ) WITHOUT ROWID`, | |
| 7369 | - ); | |
| 7370 | - sql.exec( | |
| 7371 | - `CREATE INDEX IF NOT EXISTS ${__QUEUE_TRANSFER_RECEIPTS}_expires | |
| 7372 | - ON ${__QUEUE_TRANSFER_RECEIPTS} (expires_at, transfer_id)`, | |
| 7373 | - ); | |
| 7374 | - this._ready = true; | |
| 7375 | - return sql; | |
| 7376 | - } | |
| 7377 | - | |
| 7378 | - _meta(name) { | |
| 7379 | - return this._open().exec( | |
| 7380 | - `SELECT value FROM ${__QUEUE_META} WHERE name = ?`, name, | |
| 7381 | - ).toArray()[0]?.value; | |
| 7382 | - } | |
| 7383 | - | |
| 7384 | - _setMeta(name, value) { | |
| 7385 | - if (value === null || value === undefined) { | |
| 7386 | - this._open().exec(`DELETE FROM ${__QUEUE_META} WHERE name = ?`, name); | |
| 7387 | - return; | |
| 7388 | - } | |
| 7389 | - this._open().exec( | |
| 7390 | - `INSERT INTO ${__QUEUE_META} (name, value) VALUES (?, ?) | |
| 7391 | - ON CONFLICT(name) DO UPDATE SET value = excluded.value`, | |
| 7392 | - name, | |
| 7393 | - String(value), | |
| 7394 | - ); | |
| 7395 | - } | |
| 7396 | - | |
| 7397 | - _paused() { | |
| 7398 | - return this._meta("paused") === "1"; | |
| 7399 | - } | |
| 7400 | - | |
| 7401 | - _metrics(now = Date.now(), waitingOnly = false) { | |
| 7402 | - const expiresBefore = now - __queueLimits().retentionMs; | |
| 7403 | - const sql = this._open(); | |
| 7404 | - const stats = sql.exec( | |
| 7405 | - `SELECT backlog_count, backlog_bytes, oldest_message_timestamp | |
| 7406 | - FROM ${__QUEUE_STATS} WHERE id = 1`, | |
| 7407 | - ).toArray()[0]; | |
| 7408 | - // Retention is a clock transition, not a row transition. Until the | |
| 7409 | - // bounded sweep catches up, use the exact query only at that boundary; | |
| 7410 | - // the normal hot path remains one materialized row at every depth. | |
| 7411 | - if (stats.oldest_message_timestamp !== null && | |
| 7412 | - stats.oldest_message_timestamp <= expiresBefore) { | |
| 7413 | - const row = sql.exec( | |
| 7414 | - `SELECT COUNT(*) AS backlog_count, | |
| 7415 | - COALESCE(SUM(size), 0) AS backlog_bytes, | |
| 7416 | - MIN(enqueued_at) AS oldest_message_timestamp | |
| 7417 | - FROM ${__QUEUE_MESSAGES} | |
| 7418 | - WHERE purge_on_settle = 0 AND enqueued_at > ? | |
| 7419 | - AND (? = 0 OR (lease_id IS NULL AND dlq_target IS NULL | |
| 7420 | - AND visible_at <= ?))`, | |
| 7421 | - expiresBefore, | |
| 7422 | - waitingOnly ? 1 : 0, | |
| 7423 | - now, | |
| 7424 | - ).toArray()[0]; | |
| 7425 | - return { | |
| 7426 | - backlogCount: row.backlog_count, | |
| 7427 | - backlogBytes: row.backlog_bytes, | |
| 7428 | - oldestMessageTimestamp: row.oldest_message_timestamp ?? null, | |
| 7429 | - }; | |
| 7430 | - } | |
| 7431 | - if (!waitingOnly) { | |
| 7432 | - if (typeof __test_queue_metrics_materialized === "function") { | |
| 7433 | - __test_queue_metrics_materialized(); | |
| 7434 | - } | |
| 7435 | - return { | |
| 7436 | - backlogCount: stats.backlog_count, | |
| 7437 | - backlogBytes: stats.backlog_bytes, | |
| 7438 | - oldestMessageTimestamp: stats.oldest_message_timestamp ?? null, | |
| 7439 | - }; | |
| 7440 | - } | |
| 7441 | - const blocked = sql.exec( | |
| 7442 | - `SELECT COALESCE(SUM(blocked_count), 0) AS blocked_count, | |
| 7443 | - COALESCE(SUM(blocked_bytes), 0) AS blocked_bytes | |
| 7444 | - FROM ( | |
| 7445 | - SELECT COUNT(*) AS blocked_count, | |
| 7446 | - COALESCE(SUM(size), 0) AS blocked_bytes | |
| 7447 | - FROM ${__QUEUE_MESSAGES} INDEXED BY ${__QUEUE_MESSAGES}_lease | |
| 7448 | - WHERE purge_on_settle = 0 AND lease_id IS NOT NULL | |
| 7449 | - UNION ALL | |
| 7450 | - SELECT COUNT(*) AS blocked_count, | |
| 7451 | - COALESCE(SUM(size), 0) AS blocked_bytes | |
| 7452 | - FROM ${__QUEUE_MESSAGES} INDEXED BY ${__QUEUE_MESSAGES}_moving | |
| 7453 | - WHERE purge_on_settle = 0 AND dlq_target IS NOT NULL | |
| 7454 | - UNION ALL | |
| 7455 | - SELECT COUNT(*) AS blocked_count, | |
| 7456 | - COALESCE(SUM(size), 0) AS blocked_bytes | |
| 7457 | - FROM ${__QUEUE_MESSAGES} INDEXED BY ${__QUEUE_MESSAGES}_ready | |
| 7458 | - WHERE purge_on_settle = 0 AND dlq_target IS NULL | |
| 7459 | - AND lease_id IS NULL AND visible_at > ? | |
| 7460 | - )`, | |
| 7461 | - now, | |
| 7462 | - ).toArray()[0]; | |
| 7463 | - const unleasedOldest = sql.exec( | |
| 7464 | - `SELECT enqueued_at | |
| 7465 | - FROM ${__QUEUE_MESSAGES} INDEXED BY ${__QUEUE_MESSAGES}_retained | |
| 7466 | - WHERE purge_on_settle = 0 AND dlq_target IS NULL | |
| 7467 | - AND lease_id IS NULL AND visible_at <= ? | |
| 7468 | - ORDER BY enqueued_at, seq | |
| 7469 | - LIMIT 1`, | |
| 7470 | - now, | |
| 7471 | - ).toArray()[0]?.enqueued_at ?? null; | |
| 7472 | - return { | |
| 7473 | - backlogCount: stats.backlog_count - blocked.blocked_count, | |
| 7474 | - backlogBytes: stats.backlog_bytes - blocked.blocked_bytes, | |
| 7475 | - oldestMessageTimestamp: unleasedOldest, | |
| 7476 | - }; | |
| 7477 | - } | |
| 7478 | - | |
| 7479 | - async _rearm(now = Date.now(), waitForWake = false) { | |
| 7480 | - const sql = this._open(); | |
| 7481 | - const consumer = __cell.queueConsumers?.[this.queue]; | |
| 7482 | - const paused = this._paused(); | |
| 7483 | - const active = sql.exec( | |
| 7484 | - `SELECT COUNT(DISTINCT lease_id) AS count | |
| 7485 | - FROM ${__QUEUE_MESSAGES} INDEXED BY ${__QUEUE_MESSAGES}_lease | |
| 7486 | - WHERE lease_id IS NOT NULL AND leased_until > ?`, | |
| 7487 | - now, | |
| 7488 | - ).toArray()[0].count; | |
| 7489 | - const concurrency = consumer | |
| 7490 | - ? consumer.maxConcurrency ?? __queueLimits().maxConcurrency | |
| 7491 | - : 0; | |
| 7492 | - const hasCapacity = !paused && consumer !== undefined && __queuePolicy({ | |
| 7493 | - op: "capacity", | |
| 7494 | - active, | |
| 7495 | - maximum: concurrency, | |
| 7496 | - }); | |
| 7497 | - // We need only enough ready rows to distinguish a partial batch from a | |
| 7498 | - // full one. The two indexed arms cover a new row and an expired lease, | |
| 7499 | - // and the outer LIMIT keeps the work independent of backlog depth. | |
| 7500 | - let ready = []; | |
| 7501 | - if (hasCapacity) { | |
| 7502 | - const visibleReady = sql.exec( | |
| 7503 | - `SELECT visible_at AS ready_at, seq | |
| 7504 | - FROM ${__QUEUE_MESSAGES} INDEXED BY ${__QUEUE_MESSAGES}_ready | |
| 7505 | - WHERE purge_on_settle = 0 AND dlq_target IS NULL | |
| 7506 | - AND lease_id IS NULL AND visible_at <= ? | |
| 7507 | - ORDER BY visible_at, seq | |
| 7508 | - LIMIT ?`, | |
| 7509 | - now, | |
| 7510 | - consumer.maxBatchSize, | |
| 7511 | - ).toArray(); | |
| 7512 | - const expiredReady = sql.exec( | |
| 7513 | - `SELECT leased_until AS ready_at, seq | |
| 7514 | - FROM ${__QUEUE_MESSAGES} INDEXED BY ${__QUEUE_MESSAGES}_lease | |
| 7515 | - WHERE purge_on_settle = 0 AND dlq_target IS NULL | |
| 7516 | - AND lease_id IS NOT NULL AND leased_until <= ? | |
| 7517 | - ORDER BY leased_until, seq | |
| 7518 | - LIMIT ?`, | |
| 7519 | - now, | |
| 7520 | - consumer.maxBatchSize, | |
| 7521 | - ).toArray(); | |
| 7522 | - ready = [...visibleReady, ...expiredReady] | |
| 7523 | - .sort((left, right) => left.ready_at - right.ready_at || left.seq - right.seq) | |
| 7524 | - .slice(0, consumer.maxBatchSize); | |
| 7525 | - } | |
| 7526 | - if (typeof __test_queue_rearm_bounded === "function") { | |
| 7527 | - __test_queue_rearm_bounded( | |
| 7528 | - ready.length <= (consumer?.maxBatchSize ?? 0), | |
| 7529 | - ready.length > 0, | |
| 7530 | - ); | |
| 7531 | - } | |
| 7532 | - const earliestVisible = hasCapacity | |
| 7533 | - ? sql.exec( | |
| 7534 | - `SELECT visible_at | |
| 7535 | - FROM ${__QUEUE_MESSAGES} INDEXED BY ${__QUEUE_MESSAGES}_ready | |
| 7536 | - WHERE purge_on_settle = 0 AND dlq_target IS NULL | |
| 7537 | - AND lease_id IS NULL AND visible_at > ? | |
| 7538 | - ORDER BY visible_at, seq | |
| 7539 | - LIMIT 1`, | |
| 7540 | - now, | |
| 7541 | - ).toArray()[0]?.visible_at ?? null | |
| 7542 | - : null; | |
| 7543 | - const earliestLeaseExpiry = paused | |
| 7544 | - ? null | |
| 7545 | - : sql.exec( | |
| 7546 | - `SELECT leased_until | |
| 7547 | - FROM ${__QUEUE_MESSAGES} INDEXED BY ${__QUEUE_MESSAGES}_lease | |
| 7548 | - WHERE lease_id IS NOT NULL | |
| 7549 | - ORDER BY leased_until | |
| 7550 | - LIMIT 1`, | |
| 7551 | - ).toArray()[0]?.leased_until ?? null; | |
| 7552 | - const nextSweep = sql.exec( | |
| 7553 | - `SELECT enqueued_at + ? AS next_sweep | |
| 7554 | - FROM ${__QUEUE_MESSAGES} INDEXED BY ${__QUEUE_MESSAGES}_retained | |
| 7555 | - WHERE dlq_target IS NULL AND purge_on_settle = 0 | |
| 7556 | - ORDER BY enqueued_at, seq | |
| 7557 | - LIMIT 1`, | |
| 7558 | - __queueLimits().retentionMs, | |
| 7559 | - ).toArray()[0]?.next_sweep ?? null; | |
| 7560 | - const dlqPending = sql.exec( | |
| 7561 | - `SELECT 1 AS pending | |
| 7562 | - FROM ${__QUEUE_MESSAGES} INDEXED BY ${__QUEUE_MESSAGES}_moving | |
| 7563 | - WHERE dlq_target IS NOT NULL | |
| 7564 | - LIMIT 1`, | |
| 7565 | - ).toArray().length !== 0; | |
| 7566 | - const receiptSweep = sql.exec( | |
| 7567 | - `SELECT expires_at AS next_sweep | |
| 7568 | - FROM ${__QUEUE_TRANSFER_RECEIPTS} | |
| 7569 | - ORDER BY expires_at, transfer_id | |
| 7570 | - LIMIT 1`, | |
| 7571 | - ).toArray()[0]?.next_sweep ?? null; | |
| 7572 | - // A queue without an attached consumer only wakes to reclaim retention. | |
| 7573 | - // Consumer attachment will nudge the cell when the fleet catalog gains a | |
| 7574 | - // registration; spinning on an already-visible row cannot make progress. | |
| 7575 | - let batchDeadline = null; | |
| 7576 | - if (ready.length > 0) { | |
| 7577 | - batchDeadline = ready.length >= consumer.maxBatchSize | |
| 7578 | - ? now | |
| 7579 | - : ready[0].ready_at + consumer.maxBatchTimeoutMs; | |
| 7580 | - } | |
| 7581 | - if (dlqPending) { | |
| 7582 | - batchDeadline = batchDeadline === null ? now : Math.min(batchDeadline, now); | |
| 7583 | - } | |
| 7584 | - const sweepDeadlines = [nextSweep, receiptSweep] | |
| 7585 | - .filter((deadline) => deadline !== null && deadline !== undefined); | |
| 7586 | - const armAt = __queuePolicy({ | |
| 7587 | - op: "rearm", | |
| 7588 | - now, | |
| 7589 | - batchDeadline, | |
| 7590 | - earliestVisible, | |
| 7591 | - // A live handler can settle after delivery pauses. Do not reclaim its | |
| 7592 | - // lease while paused; resume re-arms the expired deadline immediately | |
| 7593 | - // and only then can a new generation replace it. | |
| 7594 | - earliestLeaseExpiry, | |
| 7595 | - nextSweep: sweepDeadlines.length === 0 ? null : Math.min(...sweepDeadlines), | |
| 7596 | - }); | |
| 7597 | - if (armAt !== null && !Number.isFinite(armAt)) { | |
| 7598 | - throw __queueError("the Queue sweep deadline is invalid"); | |
| 7599 | - } | |
| 7600 | - if (armAt === null) await this.ctx.storage.deleteAlarm(); | |
| 7601 | - else if (waitForWake) { | |
| 7602 | - await __queue_alarm_set_wait(this.ctx.storage._scope, armAt); | |
| 7603 | - } else await this.ctx.storage.setAlarm(armAt); | |
| 7604 | - } | |
| 7605 | - | |
| 7606 | - _newProducerGroup() { | |
| 7607 | - const group = { | |
| 7608 | - calls: [], | |
| 7609 | - entries: [], | |
| 7610 | - bytes: 0, | |
| 7611 | - flushing: false, | |
| 7612 | - timer: null, | |
| 7613 | - }; | |
| 7614 | - this._producerGroup = group; | |
| 7615 | - group.timer = setTimeout(() => { | |
| 7616 | - void this._flushProducerGroup(group); | |
| 7617 | - }, __queueLimits().producerGroupMs); | |
| 7618 | - return group; | |
| 7619 | - } | |
| 7620 | - | |
| 7621 | - async _flushProducerGroup(group) { | |
| 7622 | - if (group.flushing) return; | |
| 7623 | - group.flushing = true; | |
| 7624 | - if (this._producerGroup === group) this._producerGroup = null; | |
| 7625 | - if (group.timer !== null) { | |
| 7626 | - clearTimeout(group.timer); | |
| 7627 | - group.timer = null; | |
| 7628 | - } | |
| 7629 | - | |
| 7630 | - const now = Date.now(); | |
| 7631 | - try { | |
| 7632 | - const sql = this._open(); | |
| 7633 | - this.ctx.storage.transactionSync(() => { | |
| 7634 | - for (const entry of group.entries) { | |
| 7635 | - sql.exec( | |
| 7636 | - `INSERT INTO ${__QUEUE_MESSAGES} | |
| 7637 | - (id, body, content_type, size, enqueued_at, visible_at) | |
| 7638 | - VALUES (?, ?, ?, ?, ?, ?)`, | |
| 7639 | - __queueMessageId(now), | |
| 7640 | - entry.body, | |
| 7641 | - entry.contentType, | |
| 7642 | - entry.size, | |
| 7643 | - now, | |
| 7644 | - now + entry.delaySeconds * 1000, | |
| 7645 | - ); | |
| 7646 | - } | |
| 7647 | - }); | |
| 7648 | - await this._rearm(now, true); | |
| 7649 | - const metrics = this._metrics(now); | |
| 7650 | - if (typeof __test_queue_producer_group === "function") { | |
| 7651 | - __test_queue_producer_group(group.calls.length, group.entries.length); | |
| 7652 | - } | |
| 7653 | - for (const call of group.calls) call.resolve(metrics); | |
| 7654 | - } catch (error) { | |
| 7655 | - for (const call of group.calls) call.reject(error); | |
| 7656 | - } | |
| 7657 | - } | |
| 7658 | - | |
| 7659 | - __queueSend({ entries }) { | |
| 7660 | - const bytes = entries.reduce((total, entry) => total + entry.size, 0); | |
| 7661 | - return new Promise((resolve, reject) => { | |
| 7662 | - let group = this._producerGroup; | |
| 7663 | - if (group !== null && | |
| 7664 | - (group.calls.length + 1 > __QUEUE_PRODUCER_GROUP_CALLS || | |
| 7665 | - group.entries.length + entries.length > __QUEUE_PRODUCER_GROUP_MESSAGES || | |
| 7666 | - group.bytes + bytes > __QUEUE_PRODUCER_GROUP_BYTES)) { | |
| 7667 | - void this._flushProducerGroup(group); | |
| 7668 | - group = null; | |
| 7669 | - } | |
| 7670 | - if (group === null) group = this._newProducerGroup(); | |
| 7671 | - group.calls.push({ resolve, reject }); | |
| 7672 | - group.entries.push(...entries); | |
| 7673 | - group.bytes += bytes; | |
| 7674 | - if (group.calls.length === __QUEUE_PRODUCER_GROUP_CALLS || | |
| 7675 | - group.entries.length === __QUEUE_PRODUCER_GROUP_MESSAGES || | |
| 7676 | - group.bytes === __QUEUE_PRODUCER_GROUP_BYTES) { | |
| 7677 | - void this._flushProducerGroup(group); | |
| 7678 | - } | |
| 7679 | - }); | |
| 7680 | - } | |
| 7681 | - | |
| 7682 | - __queueMetrics() { | |
| 7683 | - return this._metrics(); | |
| 7684 | - } | |
| 7685 | - | |
| 7686 | - // Retention decides visibility through `_metrics` immediately, while this | |
| 7687 | - // bounded sweep only reclaims space. A live lease is marked instead of | |
| 7688 | - // deleted, so its handler can finish but settlement or expiry removes it | |
| 7689 | - // without a redelivery. | |
| 7690 | - _sweep(now) { | |
| 7691 | - const sql = this._open(); | |
| 7692 | - const cutoff = now - __queueLimits().retentionMs; | |
| 7693 | - const messages = __cellSweepBatch( | |
| 7694 | - this.ctx.storage, | |
| 7695 | - (limit) => sql.exec( | |
| 7696 | - `SELECT seq, lease_id, leased_until FROM ${__QUEUE_MESSAGES} | |
| 7697 | - WHERE enqueued_at <= ? | |
| 7698 | - AND (purge_on_settle = 0 | |
| 7699 | - OR lease_id IS NULL OR leased_until <= ?) | |
| 7700 | - ORDER BY enqueued_at, seq | |
| 7701 | - LIMIT ?`, | |
| 7702 | - cutoff, | |
| 7703 | - now, | |
| 7704 | - limit, | |
| 7705 | - ).toArray(), | |
| 7706 | - (row) => { | |
| 7707 | - if (row.lease_id !== null && row.leased_until > now) { | |
| 7708 | - sql.exec( | |
| 7709 | - `UPDATE ${__QUEUE_MESSAGES} SET purge_on_settle = 1 WHERE seq = ?`, | |
| 7710 | - row.seq, | |
| 7711 | - ); | |
| 7712 | - } else { | |
| 7713 | - sql.exec(`DELETE FROM ${__QUEUE_MESSAGES} WHERE seq = ?`, row.seq); | |
| 7714 | - } | |
| 7715 | - }, | |
| 7716 | - __queueLimits().sweepBatchRows, | |
| 7717 | - ); | |
| 7718 | - const remaining = __queueLimits().sweepBatchRows - messages; | |
| 7719 | - if (remaining === 0) return messages; | |
| 7720 | - const receipts = __cellSweepBatch( | |
| 7721 | - this.ctx.storage, | |
| 7722 | - (limit) => sql.exec( | |
| 7723 | - `SELECT transfer_id FROM ${__QUEUE_TRANSFER_RECEIPTS} | |
| 7724 | - WHERE expires_at <= ? | |
| 7725 | - ORDER BY expires_at, transfer_id | |
| 7726 | - LIMIT ?`, | |
| 7727 | - now, | |
| 7728 | - limit, | |
| 7729 | - ).toArray(), | |
| 7730 | - (row) => { | |
| 7731 | - sql.exec( | |
| 7732 | - `DELETE FROM ${__QUEUE_TRANSFER_RECEIPTS} WHERE transfer_id = ?`, | |
| 7733 | - row.transfer_id, | |
| 7734 | - ); | |
| 7735 | - }, | |
| 7736 | - remaining, | |
| 7737 | - ); | |
| 7738 | - return messages + receipts; | |
| 7739 | - } | |
| 7740 | - | |
| 7741 | - _candidateRows(now, limit) { | |
| 7742 | - return this._open().exec( | |
| 7743 | - `SELECT seq, id, body, content_type, size, enqueued_at, visible_at, | |
| 7744 | - attempts, lease_id, lease_generation, leased_until, | |
| 7745 | - purge_on_settle | |
| 7746 | - FROM ${__QUEUE_MESSAGES} | |
| 7747 | - WHERE dlq_target IS NULL AND ((purge_on_settle = 1 | |
| 7748 | - AND (lease_id IS NULL OR leased_until <= ?)) | |
| 7749 | - OR (purge_on_settle = 0 AND visible_at <= ? | |
| 7750 | - AND (lease_id IS NULL OR leased_until <= ?))) | |
| 7751 | - ORDER BY visible_at, seq | |
| 7752 | - LIMIT ?`, | |
| 7753 | - now, | |
| 7754 | - now, | |
| 7755 | - now, | |
| 7756 | - limit, | |
| 7757 | - ).toArray(); | |
| 7758 | - } | |
| 7759 | - | |
| 7760 | - async _leaseBatch(now, consumer) { | |
| 7761 | - const sql = this._open(); | |
| 7762 | - const active = sql.exec( | |
| 7763 | - `SELECT COUNT(DISTINCT lease_id) AS count | |
| 7764 | - FROM ${__QUEUE_MESSAGES} | |
| 7765 | - WHERE lease_id IS NOT NULL AND leased_until > ?`, | |
| 7766 | - now, | |
| 7767 | - ).toArray()[0].count; | |
| 7768 | - const concurrency = consumer.maxConcurrency ?? __queueLimits().maxConcurrency; | |
| 7769 | - if (!__queuePolicy({ op: "capacity", active, maximum: concurrency })) return null; | |
| 7770 | - | |
| 7771 | - // Read extra rows so expired purge markers cannot hide a deliverable | |
| 7772 | - // batch. Policy chooses at most `maxBatchSize` rows and returns every | |
| 7773 | - // purge deletion that precedes them in this bounded scan. | |
| 7774 | - const rows = this._candidateRows(now, consumer.maxBatchSize + 256); | |
| 7775 | - const deliverable = rows.filter((row) => row.purge_on_settle === 0); | |
| 7776 | - if (deliverable.length === 0) { | |
| 7777 | - if (rows.length > 0) { | |
| 7778 | - this.ctx.storage.transactionSync(() => { | |
| 7779 | - for (const row of rows) { | |
| 7780 | - sql.exec(`DELETE FROM ${__QUEUE_MESSAGES} WHERE seq = ?`, row.seq); | |
| 7781 | - } | |
| 7782 | - }); | |
| 7783 | - } | |
| 7784 | - return null; | |
| 7785 | - } | |
| 7786 | - const readySince = Math.min(...deliverable.map((row) => | |
| 7787 | - row.lease_id === null ? row.visible_at : row.leased_until | |
| 7788 | - )); | |
| 7789 | - if (deliverable.length < consumer.maxBatchSize && | |
| 7790 | - readySince + consumer.maxBatchTimeoutMs > now) { | |
| 7791 | - return null; | |
| 7792 | - } | |
| 7793 | - | |
| 7794 | - const plan = __queuePolicy({ | |
| 7795 | - op: "batch", | |
| 7796 | - now, | |
| 7797 | - maxBatchSize: consumer.maxBatchSize, | |
| 7798 | - rows: rows.map((row) => ({ | |
| 7799 | - seq: row.seq, | |
| 7800 | - visibleAt: row.visible_at, | |
| 7801 | - leaseGeneration: String(row.lease_generation), | |
| 7802 | - leasedUntil: row.leased_until, | |
| 7803 | - purgeOnSettle: row.purge_on_settle !== 0, | |
| 7804 | - })), | |
| 7805 | - }); | |
| 7806 | - if (plan.leases.length === 0 && plan.deletePurged.length === 0) return null; | |
| 7807 | - const rowBySeq = new Map(rows.map((row) => [row.seq, row])); | |
| 7808 | - const reclaimed = plan.leases.filter((lease) => lease.reclaimed); | |
| 7809 | - const expiryPolicy = __queuePolicy({ | |
| 7810 | - op: "expiry", | |
| 7811 | - now, | |
| 7812 | - entries: reclaimed.map((lease) => { | |
| 7813 | - const row = rowBySeq.get(lease.seq); | |
| 7814 | - return { | |
| 7815 | - priorFailures: row.attempts, | |
| 7816 | - maxRetries: consumer.maxRetries, | |
| 7817 | - configuredSeconds: consumer.retryDelaySeconds ?? null, | |
| 7818 | - purgeOnSettle: row.purge_on_settle !== 0, | |
| 7819 | - }; | |
| 7820 | - }), | |
| 7821 | - }); | |
| 7822 | - const expiryBySeq = new Map( | |
| 7823 | - reclaimed.map((lease, index) => [lease.seq, expiryPolicy[index]]), | |
| 7824 | - ); | |
| 7825 | - const installs = plan.leases.filter((lease) => { | |
| 7826 | - const expiry = expiryBySeq.get(lease.seq); | |
| 7827 | - return expiry === undefined || | |
| 7828 | - (expiry.action.kind === "retry" && expiry.action.at <= now); | |
| 7829 | - }); | |
| 7830 | - const exhaustedTransfers = new Map( | |
| 7831 | - reclaimed | |
| 7832 | - .filter((lease) => | |
| 7833 | - expiryBySeq.get(lease.seq).action.kind === "exhausted" && | |
| 7834 | - consumer.deadLetterQueue !== undefined | |
| 7835 | - ) | |
| 7836 | - .map((lease) => [lease.seq, crypto.randomUUID()]), | |
| 7837 | - ); | |
| 7838 | - const leaseId = crypto.randomUUID(); | |
| 7839 | - const leasedUntil = Math.min( | |
| 7840 | - Number.MAX_SAFE_INTEGER, | |
| 7841 | - now + __cell.queueLeaseDurationMs, | |
| 7842 | - ); | |
| 7843 | - this.ctx.storage.transactionSync(() => { | |
| 7844 | - for (const seq of plan.deletePurged) { | |
| 7845 | - sql.exec( | |
| 7846 | - `DELETE FROM ${__QUEUE_MESSAGES} | |
| 7847 | - WHERE seq = ? AND purge_on_settle = 1 | |
| 7848 | - AND (lease_id IS NULL OR leased_until <= ?)`, | |
| 7849 | - seq, | |
| 7850 | - now, | |
| 7851 | - ); | |
| 7852 | - } | |
| 7853 | - for (const lease of reclaimed) { | |
| 7854 | - const expiry = expiryBySeq.get(lease.seq); | |
| 7855 | - if (expiry.action.kind === "delete-purged") { | |
| 7856 | - sql.exec( | |
| 7857 | - `DELETE FROM ${__QUEUE_MESSAGES} | |
| 7858 | - WHERE seq = ? AND leased_until <= ?`, | |
| 7859 | - lease.seq, | |
| 7860 | - now, | |
| 7861 | - ); | |
| 7862 | - } else if (expiry.action.kind === "exhausted") { | |
| 7863 | - if (consumer.deadLetterQueue === undefined) { | |
| 7864 | - sql.exec( | |
| 7865 | - `DELETE FROM ${__QUEUE_MESSAGES} | |
| 7866 | - WHERE seq = ? AND leased_until <= ?`, | |
| 7867 | - lease.seq, | |
| 7868 | - now, | |
| 7869 | - ); | |
| 7870 | - } else { | |
| 7871 | - sql.exec( | |
| 7872 | - `UPDATE ${__QUEUE_MESSAGES} | |
| 7873 | - SET attempts = ?, lease_id = NULL, leased_until = NULL, | |
| 7874 | - dlq_target = ?, dlq_transfer_id = ?, | |
| 7875 | - transfer_kind = 'dead-letter' | |
| 7876 | - WHERE seq = ? AND leased_until <= ?`, | |
| 7877 | - expiry.attempt, | |
| 7878 | - consumer.deadLetterQueue, | |
| 7879 | - exhaustedTransfers.get(lease.seq), | |
| 7880 | - lease.seq, | |
| 7881 | - now, | |
| 7882 | - ); | |
| 7883 | - } | |
| 7884 | - } else if (expiry.action.at > now) { | |
| 7885 | - sql.exec( | |
| 7886 | - `UPDATE ${__QUEUE_MESSAGES} | |
| 7887 | - SET attempts = ?, visible_at = ?, lease_id = NULL, | |
| 7888 | - leased_until = NULL | |
| 7889 | - WHERE seq = ? AND leased_until <= ?`, | |
| 7890 | - expiry.attempt, | |
| 7891 | - expiry.action.at, | |
| 7892 | - lease.seq, | |
| 7893 | - now, | |
| 7894 | - ); | |
| 7895 | - } | |
| 7896 | - } | |
| 7897 | - for (const lease of installs) { | |
| 7898 | - const generation = Number(lease.generation); | |
| 7899 | - if (!Number.isSafeInteger(generation)) { | |
| 7900 | - throw __queueError(`message ${lease.seq} exhausted its safe lease generation`); | |
| 7901 | - } | |
| 7902 | - sql.exec( | |
| 7903 | - `UPDATE ${__QUEUE_MESSAGES} | |
| 7904 | - SET lease_id = ?, lease_generation = ?, leased_until = ?, | |
| 7905 | - attempts = attempts + ? | |
| 7906 | - WHERE seq = ? AND lease_generation = ? | |
| 7907 | - AND (lease_id IS NULL OR leased_until <= ?)`, | |
| 7908 | - leaseId, | |
| 7909 | - generation, | |
| 7910 | - leasedUntil, | |
| 7911 | - lease.reclaimed ? 1 : 0, | |
| 7912 | - lease.seq, | |
| 7913 | - generation - 1, | |
| 7914 | - now, | |
| 7915 | - ); | |
| 7916 | - } | |
| 7917 | - }); | |
| 7918 | - if (installs.length === 0) return null; | |
| 7919 | - const leasedQuery = | |
| 7920 | - `SELECT seq, id, body, content_type, enqueued_at, attempts, | |
| 7921 | - lease_generation | |
| 7922 | - FROM ${__QUEUE_MESSAGES} | |
| 7923 | - WHERE lease_id = ? | |
| 7924 | - ORDER BY visible_at, seq`; | |
| 7925 | - __queueReportLeaseLookupPlan(sql, leasedQuery, leaseId); | |
| 7926 | - const leased = sql.exec(leasedQuery, leaseId).toArray(); | |
| 7927 | - if (leased.length !== installs.length) { | |
| 7928 | - throw __queueError("the Queue lease transaction changed fewer rows than its plan"); | |
| 7929 | - } | |
| 7930 | - return { | |
| 7931 | - leaseId, | |
| 7932 | - leases: leased.map((row) => ({ | |
| 7933 | - message_id: row.id, | |
| 7934 | - seq: row.seq, | |
| 7935 | - generation: row.lease_generation, | |
| 7936 | - })), | |
| 7937 | - messages: leased.map((row) => ({ | |
| 7938 | - id: row.id, | |
| 7939 | - timestampMs: row.enqueued_at, | |
| 7940 | - // SQLite answers a BLOB as an ArrayBuffer. The raw base64 op accepts | |
| 7941 | - // typed views, so normalize here; otherwise it encodes the text | |
| 7942 | - // "[object ArrayBuffer]" and every consumer decoder sees corrupt data. | |
| 7943 | - bodyBase64: $$btoa( | |
| 7944 | - row.body instanceof Uint8Array ? row.body : new Uint8Array(row.body), | |
| 7945 | - ), | |
| 7946 | - contentType: row.content_type, | |
| 7947 | - attempts: row.attempts + 1, | |
| 7948 | - })), | |
| 7949 | - // Miniflare removes every dispatched batch from its backlog before it | |
| 7950 | - // invokes the consumer. Exclude every lease here for the same contract; | |
| 7951 | - // the operator aggregate still includes durable in-flight messages. | |
| 7952 | - metrics: this._metrics(now, true), | |
| 7953 | - }; | |
| 7954 | - } | |
| 7955 | - | |
| 7956 | - // The target deduplicates the stable transfer identity. The source can | |
| 7957 | - // therefore repeat this call after a stop between the target commit and the | |
| 7958 | - // source delete without creating a second message. | |
| 7959 | - async __queueDlqAcceptBatch({ transfers }) { | |
| 7960 | - if (!Array.isArray(transfers) || transfers.length === 0 || | |
| 7961 | - transfers.length > __queueLimits().maxBatchMessages) { | |
| 7962 | - throw __queueError("a Queue transfer batch has an invalid size"); | |
| 7963 | - } | |
| 7964 | - for (const transfer of transfers) { | |
| 7965 | - if (transfer.deadLetterSource !== null && | |
| 7966 | - typeof transfer.deadLetterSource !== "string") { | |
| 7967 | - throw __queueError("a Queue transfer has an invalid dead-letter source"); | |
| 7968 | - } | |
| 7969 | - } | |
| 7970 | - const now = Date.now(); | |
| 7971 | - const sql = this._open(); | |
| 7972 | - this.ctx.storage.transactionSync(() => { | |
| 7973 | - for (const { transferId, entry, deadLetterSource } of transfers) { | |
| 7974 | - const accepted = sql.exec( | |
| 7975 | - `SELECT message_id, dead_letter_source | |
| 7976 | - FROM ${__QUEUE_TRANSFER_RECEIPTS} | |
| 7977 | - WHERE transfer_id = ?`, | |
| 7978 | - transferId, | |
| 7979 | - ).toArray()[0]; | |
| 7980 | - if (accepted !== undefined && (accepted.message_id !== entry.id || | |
| 7981 | - accepted.dead_letter_source !== deadLetterSource)) { | |
| 7982 | - throw __queueError("a DLQ transfer collided with another message identity"); | |
| 7983 | - } | |
| 7984 | - if (accepted !== undefined) continue; | |
| 7985 | - sql.exec( | |
| 7986 | - `INSERT INTO ${__QUEUE_TRANSFER_RECEIPTS} | |
| 7987 | - (transfer_id, message_id, dead_letter_source, expires_at) | |
| 7988 | - VALUES (?, ?, ?, ?)`, | |
| 7989 | - transferId, | |
| 7990 | - entry.id, | |
| 7991 | - deadLetterSource, | |
| 7992 | - now + __queueLimits().retentionMs, | |
| 7993 | - ); | |
| 7994 | - sql.exec( | |
| 7995 | - `INSERT INTO ${__QUEUE_MESSAGES} | |
| 7996 | - (id, body, content_type, size, enqueued_at, visible_at, | |
| 7997 | - attempts, dlq_transfer_id, dead_letter_source) | |
| 7998 | - VALUES (?, ?, ?, ?, ?, ?, 0, ?, ?)`, | |
| 7999 | - entry.id, | |
| 8000 | - entry.body, | |
| 8001 | - entry.contentType, | |
| 8002 | - entry.size, | |
| 8003 | - now, | |
| 8004 | - now, | |
| 8005 | - transferId, | |
| 8006 | - deadLetterSource, | |
| 8007 | - ); | |
| 8008 | - } | |
| 8009 | - }); | |
| 8010 | - await this._rearm(now); | |
| 8011 | - return this._metrics(now); | |
| 8012 | - } | |
| 8013 | - | |
| 8014 | - async _driveDlq(limit = 100) { | |
| 8015 | - const now = Date.now(); | |
| 8016 | - const pending = this._open().exec( | |
| 8017 | - `SELECT seq, id, body, content_type, size, dlq_target, dlq_transfer_id, | |
| 8018 | - transfer_kind | |
| 8019 | - FROM ${__QUEUE_MESSAGES} | |
| 8020 | - WHERE dlq_target IS NOT NULL | |
| 8021 | - AND enqueued_at > ? | |
| 8022 | - ORDER BY seq | |
| 8023 | - LIMIT ?`, | |
| 8024 | - now - __queueLimits().retentionMs, | |
| 8025 | - limit, | |
| 8026 | - ).toArray(); | |
| 8027 | - const groups = new Map(); | |
| 8028 | - for (const row of pending) { | |
| 8029 | - let group = groups.get(row.dlq_target); | |
| 8030 | - if (group === undefined) groups.set(row.dlq_target, group = []); | |
| 8031 | - group.push(row); | |
| 8032 | - } | |
| 8033 | - for (const [targetName, rows] of groups) { | |
| 8034 | - const target = __cell.makeNamespace("__Queue").getByName(targetName); | |
| 8035 | - await target.__queueDlqAcceptBatch({ | |
| 8036 | - transfers: rows.map((row) => ({ | |
| 8037 | - transferId: row.dlq_transfer_id, | |
| 8038 | - // A dead-letter transfer records where redrive returns the message. | |
| 8039 | - // A redrive returns it to ordinary queue state, so the source marker | |
| 8040 | - // must not follow it and make a later redrive bounce it backwards. | |
| 8041 | - deadLetterSource: row.transfer_kind === "dead-letter" ? this.queue : null, | |
| 8042 | - entry: { | |
| 8043 | - id: row.id, | |
| 8044 | - body: row.body, | |
| 8045 | - contentType: row.content_type, | |
| 8046 | - size: row.size, | |
| 8047 | - }, | |
| 8048 | - })), | |
| 8049 | - }); | |
| 8050 | - if (typeof __test_queue_dlq_accepted === "function") { | |
| 8051 | - __test_queue_dlq_accepted(); | |
| 8052 | - } | |
| 8053 | - // The target committed every receipt before this reply. Delete the | |
| 8054 | - // corresponding source marks together; a stop before this transaction | |
| 8055 | - // leaves the whole group replayable through those stable receipts. | |
| 8056 | - this.ctx.storage.transactionSync(() => { | |
| 8057 | - for (const row of rows) { | |
| 8058 | - this._open().exec( | |
| 8059 | - `DELETE FROM ${__QUEUE_MESSAGES} | |
| 8060 | - WHERE seq = ? AND dlq_target = ? AND dlq_transfer_id = ? | |
| 8061 | - AND transfer_kind = ?`, | |
| 8062 | - row.seq, | |
| 8063 | - row.dlq_target, | |
| 8064 | - row.dlq_transfer_id, | |
| 8065 | - row.transfer_kind, | |
| 8066 | - ); | |
| 8067 | - } | |
| 8068 | - }); | |
| 8069 | - } | |
| 8070 | - return pending.length; | |
| 8071 | - } | |
| 8072 | - | |
| 8073 | - async alarm() { | |
| 8074 | - const now = Date.now(); | |
| 8075 | - try { | |
| 8076 | - await this._driveDlq(); | |
| 8077 | - } catch (error) { | |
| 8078 | - // The durable source mark is the retry record. An alarm stays armed at | |
| 8079 | - // `now`, and the target's transfer identity makes a replay idempotent. | |
| 8080 | - console.error("Queue DLQ transfer failed:", error); | |
| 8081 | - } | |
| 8082 | - const swept = this._sweep(now); | |
| 8083 | - const consumer = this._paused() | |
| 8084 | - ? undefined | |
| 8085 | - : __cell.queueConsumers?.[this.queue]; | |
| 8086 | - // Install every lease that the configured concurrency admits before the | |
| 8087 | - // first consumer can settle. One lease per alarm serialized full batches | |
| 8088 | - // because the next alarm depended on a later scheduler turn, so a queue | |
| 8089 | - // with maxConcurrency > 1 still used only one handler under backlog. | |
| 8090 | - // `_leaseBatch` counts the durable lease IDs on every iteration, which | |
| 8091 | - // makes the configured concurrency the structural bound for this loop. | |
| 8092 | - const batches = []; | |
| 8093 | - if (consumer !== undefined) { | |
| 8094 | - while (true) { | |
| 8095 | - const batch = await this._leaseBatch(now, consumer); | |
| 8096 | - if (batch === null) break; | |
| 8097 | - batches.push(batch); | |
| 8098 | - } | |
| 8099 | - } | |
| 8100 | - try { | |
| 8101 | - // `_leaseBatch` can exhaust an expired lease and create a new durable | |
| 8102 | - // DLQ mark. Drive that mark in the same wake; the first call above is | |
| 8103 | - // for a mark recovered from an earlier stopped process. | |
| 8104 | - await this._driveDlq(); | |
| 8105 | - } catch (error) { | |
| 8106 | - console.error("Queue DLQ transfer failed:", error); | |
| 8107 | - } | |
| 8108 | - await this._rearm(now); | |
| 8109 | - if (swept >= __queueLimits().sweepBatchRows && batches.length === 0) { | |
| 8110 | - await this.ctx.storage.setAlarm(now + 1); | |
| 8111 | - return; | |
| 8112 | - } | |
| 8113 | - for (const batch of batches) { | |
| 8114 | - // This await covers only the output-gated handoff to the host. The | |
| 8115 | - // consumer runs after this alarm returns, and settlement comes back as | |
| 8116 | - // an independent cell event. All admitted leases are durable before the | |
| 8117 | - // first handoff, so a fast settlement cannot make this turn exceed the | |
| 8118 | - // configured concurrency. | |
| 8119 | - await __queue_dispatch( | |
| 8120 | - consumer.script, | |
| 8121 | - this.queue, | |
| 8122 | - JSON.stringify(batch), | |
| 8123 | - ); | |
| 8124 | - } | |
| 8125 | - } | |
| 8126 | - | |
| 8127 | - _matchingLease(body) { | |
| 8128 | - if (typeof body.leaseId !== "string" || !Array.isArray(body.leases)) return null; | |
| 8129 | - const matchQuery = | |
| 8130 | - `SELECT seq, id, attempts, lease_generation, purge_on_settle | |
| 8131 | - FROM ${__QUEUE_MESSAGES} | |
| 8132 | - WHERE lease_id = ? | |
| 8133 | - ORDER BY seq`; | |
| 8134 | - __queueReportLeaseLookupPlan(this._open(), matchQuery, body.leaseId); | |
| 8135 | - const rows = this._open().exec(matchQuery, body.leaseId).toArray(); | |
| 8136 | - for (const lease of body.leases) { | |
| 8137 | - if (typeof lease?.message_id !== "string" || | |
| 8138 | - !Number.isSafeInteger(lease.seq) || | |
| 8139 | - !Number.isSafeInteger(lease.generation)) return null; | |
| 8140 | - } | |
| 8141 | - const matches = __queuePolicy({ | |
| 8142 | - op: "settlement", | |
| 8143 | - current: rows.map((row) => ({ | |
| 8144 | - seq: String(row.seq), | |
| 8145 | - messageId: row.id, | |
| 8146 | - generation: String(row.lease_generation), | |
| 8147 | - })), | |
| 8148 | - submitted: body.leases.map((lease) => ({ | |
| 8149 | - seq: String(lease.seq), | |
| 8150 | - messageId: lease.message_id, | |
| 8151 | - generation: String(lease.generation), | |
| 8152 | - })), | |
| 8153 | - }); | |
| 8154 | - return matches ? rows : null; | |
| 8155 | - } | |
| 8156 | - | |
| 8157 | - async _settle(body) { | |
| 8158 | - const rows = this._matchingLease(body); | |
| 8159 | - if (rows === null) return false; | |
| 8160 | - const consumer = __cell.queueConsumers?.[this.queue]; | |
| 8161 | - if (consumer === undefined) return false; | |
| 8162 | - const explicitAcks = new Set(body.explicitAcks ?? []); | |
| 8163 | - const retryMessages = new Map( | |
| 8164 | - (body.retryMessages ?? []).map((retry) => [retry.msgId, retry.delaySeconds]), | |
| 8165 | - ); | |
| 8166 | - const retryBatch = body.retryBatch?.retry === true; | |
| 8167 | - const batchDelay = body.retryBatch?.delaySeconds; | |
| 8168 | - const exception = body.outcome === "exception"; | |
| 8169 | - // An explicit ack-all survives a later handler exception, so it must | |
| 8170 | - // override every batch-level and message-level retry signal. | |
| 8171 | - const ackAll = body.ackAll === true; | |
| 8172 | - const decisions = rows.map((row) => { | |
| 8173 | - const retry = !ackAll && !explicitAcks.has(row.id) && ( | |
| 8174 | - retryMessages.has(row.id) || retryBatch || exception | |
| 8175 | - ); | |
| 8176 | - return { row, retry }; | |
| 8177 | - }); | |
| 8178 | - const retrying = decisions.filter((decision) => | |
| 8179 | - decision.retry && decision.row.purge_on_settle === 0 | |
| 8180 | - ); | |
| 8181 | - const retryPolicy = __queuePolicy({ | |
| 8182 | - op: "retries", | |
| 8183 | - now: Date.now(), | |
| 8184 | - entries: retrying.map(({ row }) => ({ | |
| 8185 | - attempt: row.attempts + 1, | |
| 8186 | - maxRetries: consumer.maxRetries, | |
| 8187 | - explicitSeconds: retryMessages.has(row.id) | |
| 8188 | - ? retryMessages.get(row.id) | |
| 8189 | - : retryBatch ? batchDelay : null, | |
| 8190 | - configuredSeconds: consumer.retryDelaySeconds ?? null, | |
| 8191 | - })), | |
| 8192 | - }); | |
| 8193 | - const retryById = new Map( | |
| 8194 | - retrying.map(({ row }, index) => [row.id, retryPolicy[index]]), | |
| 8195 | - ); | |
| 8196 | - const dlqTransferById = new Map( | |
| 8197 | - retrying | |
| 8198 | - .filter(({ row }) => | |
| 8199 | - retryById.get(row.id).exhausted && consumer.deadLetterQueue !== undefined | |
| 8200 | - ) | |
| 8201 | - .map(({ row }) => [row.id, crypto.randomUUID()]), | |
| 8202 | - ); | |
| 8203 | - const sql = this._open(); | |
| 8204 | - this.ctx.storage.transactionSync(() => { | |
| 8205 | - for (const { row, retry } of decisions) { | |
| 8206 | - const policy = retryById.get(row.id); | |
| 8207 | - if (row.purge_on_settle !== 0 || !retry || | |
| 8208 | - (policy.exhausted && consumer.deadLetterQueue === undefined)) { | |
| 8209 | - sql.exec( | |
| 8210 | - `DELETE FROM ${__QUEUE_MESSAGES} | |
| 8211 | - WHERE seq = ? AND lease_id = ? AND lease_generation = ?`, | |
| 8212 | - row.seq, | |
| 8213 | - body.leaseId, | |
| 8214 | - row.lease_generation, | |
| 8215 | - ); | |
| 8216 | - continue; | |
| 8217 | - } | |
| 8218 | - if (policy.exhausted) { | |
| 8219 | - sql.exec( | |
| 8220 | - `UPDATE ${__QUEUE_MESSAGES} | |
| 8221 | - SET attempts = attempts + 1, lease_id = NULL, | |
| 8222 | - leased_until = NULL, dlq_target = ?, dlq_transfer_id = ?, | |
| 8223 | - transfer_kind = 'dead-letter' | |
| 8224 | - WHERE seq = ? AND lease_id = ? AND lease_generation = ?`, | |
| 8225 | - consumer.deadLetterQueue, | |
| 8226 | - dlqTransferById.get(row.id), | |
| 8227 | - row.seq, | |
| 8228 | - body.leaseId, | |
| 8229 | - row.lease_generation, | |
| 8230 | - ); | |
| 8231 | - continue; | |
| 8232 | - } | |
| 8233 | - sql.exec( | |
| 8234 | - `UPDATE ${__QUEUE_MESSAGES} | |
| 8235 | - SET attempts = attempts + 1, visible_at = ?, | |
| 8236 | - lease_id = NULL, leased_until = NULL | |
| 8237 | - WHERE seq = ? AND lease_id = ? AND lease_generation = ?`, | |
| 8238 | - policy.at, | |
| 8239 | - row.seq, | |
| 8240 | - body.leaseId, | |
| 8241 | - row.lease_generation, | |
| 8242 | - ); | |
| 8243 | - } | |
| 8244 | - }); | |
| 8245 | - try { | |
| 8246 | - await this._driveDlq(); | |
| 8247 | - } catch (error) { | |
| 8248 | - // Settlement is durable once the source mark commits. A failed transfer | |
| 8249 | - // is alarm work now, not a reason to put the message back in delivery. | |
| 8250 | - console.error("Queue DLQ transfer deferred:", error); | |
| 8251 | - } | |
| 8252 | - await this._rearm(); | |
| 8253 | - return true; | |
| 8254 | - } | |
| 8255 | - | |
| 8256 | - async _purge() { | |
| 8257 | - const now = Date.now(); | |
| 8258 | - const sql = this._open(); | |
| 8259 | - let deleted = 0; | |
| 8260 | - let leased = 0; | |
| 8261 | - this.ctx.storage.transactionSync(() => { | |
| 8262 | - let after = 0; | |
| 8263 | - while (true) { | |
| 8264 | - // Purge is necessarily proportional to the stored backlog, but its | |
| 8265 | - // policy envelope stays bounded instead of materializing the Queue in | |
| 8266 | - // V8 or Rust. One SQLite transaction keeps the visibility change | |
| 8267 | - // atomic across all chunks. | |
| 8268 | - const rows = sql.exec( | |
| 8269 | - `SELECT seq, lease_id, leased_until FROM ${__QUEUE_MESSAGES} | |
| 8270 | - WHERE seq > ? | |
| 8271 | - ORDER BY seq | |
| 8272 | - LIMIT 256`, | |
| 8273 | - after, | |
| 8274 | - ).toArray(); | |
| 8275 | - if (rows.length === 0) break; | |
| 8276 | - after = rows[rows.length - 1].seq; | |
| 8277 | - const plan = __queuePolicy({ | |
| 8278 | - op: "purge", | |
| 8279 | - now, | |
| 8280 | - rows: rows.map((row) => ({ | |
| 8281 | - seq: String(row.seq), | |
| 8282 | - leaseIdPresent: row.lease_id !== null, | |
| 8283 | - leasedUntil: row.leased_until, | |
| 8284 | - })), | |
| 8285 | - }); | |
| 8286 | - for (const seq of plan.delete) { | |
| 8287 | - sql.exec( | |
| 8288 | - `DELETE FROM ${__QUEUE_MESSAGES} | |
| 8289 | - WHERE seq = ? | |
| 8290 | - AND (lease_id IS NULL OR leased_until IS NULL OR leased_until <= ?)`, | |
| 8291 | - Number(seq), | |
| 8292 | - now, | |
| 8293 | - ); | |
| 8294 | - deleted += 1; | |
| 8295 | - } | |
| 8296 | - for (const seq of plan.markForSettle) { | |
| 8297 | - sql.exec( | |
| 8298 | - `UPDATE ${__QUEUE_MESSAGES} SET purge_on_settle = 1 | |
| 8299 | - WHERE seq = ? AND lease_id IS NOT NULL AND leased_until > ?`, | |
| 8300 | - Number(seq), | |
| 8301 | - now, | |
| 8302 | - ); | |
| 8303 | - leased += 1; | |
| 8304 | - } | |
| 8305 | - } | |
| 8306 | - }); | |
| 8307 | - await this._rearm(now); | |
| 8308 | - return { deleted, leased, metrics: this._metrics(now) }; | |
| 8309 | - } | |
| 8310 | - | |
| 8311 | - async _setPaused(paused) { | |
| 8312 | - this._setMeta("paused", paused ? "1" : null); | |
| 8313 | - await this._rearm(); | |
| 8314 | - return { paused, ...this._metrics() }; | |
| 8315 | - } | |
| 8316 | - | |
| 8317 | - _operatorLimit(value, fallback) { | |
| 8318 | - const limit = value ?? fallback; | |
| 8319 | - if (!Number.isInteger(limit) || limit < 1 || limit > 100) { | |
| 8320 | - throw __queueError("limit must be an integer from 1 through 100"); | |
| 8321 | - } | |
| 8322 | - return limit; | |
| 8323 | - } | |
| 8324 | - | |
| 8325 | - _peek(limit) { | |
| 8326 | - const now = Date.now(); | |
| 8327 | - const cutoff = now - __queueLimits().retentionMs; | |
| 8328 | - const rows = this._open().exec( | |
| 8329 | - `SELECT id, body, content_type, size, enqueued_at, visible_at, attempts, | |
| 8330 | - lease_id, leased_until, purge_on_settle, dlq_target, | |
| 8331 | - dead_letter_source | |
| 8332 | - FROM ${__QUEUE_MESSAGES} | |
| 8333 | - WHERE enqueued_at > ? | |
| 8334 | - ORDER BY visible_at, seq | |
| 8335 | - LIMIT ?`, | |
| 8336 | - cutoff, | |
| 8337 | - limit, | |
| 8338 | - ).toArray(); | |
| 8339 | - return { | |
| 8340 | - messages: rows.map((row) => ({ | |
| 8341 | - id: row.id, | |
| 8342 | - bodyBase64: $$btoa( | |
| 8343 | - row.body instanceof Uint8Array ? row.body : new Uint8Array(row.body), | |
| 8344 | - ), | |
| 8345 | - contentType: row.content_type, | |
| 8346 | - size: row.size, | |
| 8347 | - enqueuedAt: row.enqueued_at, | |
| 8348 | - visibleAt: row.visible_at, | |
| 8349 | - attempts: row.attempts, | |
| 8350 | - state: row.dlq_target !== null | |
| 8351 | - ? "moving" | |
| 8352 | - : row.purge_on_settle !== 0 | |
| 8353 | - ? "purging" | |
| 8354 | - : row.lease_id !== null && row.leased_until > now | |
| 8355 | - ? "leased" | |
| 8356 | - : row.visible_at <= now | |
| 8357 | - ? "visible" | |
| 8358 | - : "delayed", | |
| 8359 | - leasedUntil: row.lease_id !== null && row.leased_until > now | |
| 8360 | - ? row.leased_until | |
| 8361 | - : null, | |
| 8362 | - transferTarget: row.dlq_target, | |
| 8363 | - deadLetterSource: row.dead_letter_source, | |
| 8364 | - })), | |
| 8365 | - }; | |
| 8366 | - } | |
| 8367 | - | |
| 8368 | - async _redrive(limit) { | |
| 8369 | - // Finish an interrupted move before selecting more work. A transfer mark | |
| 8370 | - // is durable, so selecting it a second time would invent another identity | |
| 8371 | - // where replaying the existing identity is sufficient. | |
| 8372 | - await this._driveDlq(100); | |
| 8373 | - const now = Date.now(); | |
| 8374 | - const cutoff = now - __queueLimits().retentionMs; | |
| 8375 | - const candidates = this._open().exec( | |
| 8376 | - `SELECT seq, dead_letter_source | |
| 8377 | - FROM ${__QUEUE_MESSAGES} | |
| 8378 | - WHERE dead_letter_source IS NOT NULL | |
| 8379 | - AND dlq_target IS NULL | |
| 8380 | - AND purge_on_settle = 0 | |
| 8381 | - AND enqueued_at > ? | |
| 8382 | - AND (lease_id IS NULL OR leased_until <= ?) | |
| 8383 | - ORDER BY visible_at, seq | |
| 8384 | - LIMIT ?`, | |
| 8385 | - cutoff, | |
| 8386 | - now, | |
| 8387 | - limit, | |
| 8388 | - ).toArray(); | |
| 8389 | - const transfers = candidates.map((row) => ({ | |
| 8390 | - ...row, | |
| 8391 | - transferId: crypto.randomUUID(), | |
| 8392 | - })); | |
| 8393 | - this.ctx.storage.transactionSync(() => { | |
| 8394 | - for (const transfer of transfers) { | |
| 8395 | - this._open().exec( | |
| 8396 | - `UPDATE ${__QUEUE_MESSAGES} | |
| 8397 | - SET dlq_target = ?, dlq_transfer_id = ?, transfer_kind = 'redrive', | |
| 8398 | - lease_id = NULL, leased_until = NULL | |
| 8399 | - WHERE seq = ? AND dead_letter_source = ? AND dlq_target IS NULL | |
| 8400 | - AND purge_on_settle = 0 | |
| 8401 | - AND (lease_id IS NULL OR leased_until <= ?)`, | |
| 8402 | - transfer.dead_letter_source, | |
| 8403 | - transfer.transferId, | |
| 8404 | - transfer.seq, | |
| 8405 | - transfer.dead_letter_source, | |
| 8406 | - now, | |
| 8407 | - ); | |
| 8408 | - } | |
| 8409 | - }); | |
| 8410 | - // Arm before the cross-cell call. If the process stops after the durable | |
| 8411 | - // mark, the alarm replays the same transfer identity. | |
| 8412 | - await this._rearm(now); | |
| 8413 | - await this._driveDlq(100); | |
| 8414 | - await this._rearm(); | |
| 8415 | - return { redriven: transfers.length, metrics: this._metrics() }; | |
| 8416 | - } | |
| 8417 | - | |
| 8418 | - async fetch(request) { | |
| 8419 | - const path = new URL(request.url).pathname; | |
| 8420 | - if (request.method !== "POST") { | |
| 8421 | - return new Response("Queue route not found", { status: 404 }); | |
| 8422 | - } | |
| 8423 | - let body; | |
| 8424 | - try { | |
| 8425 | - body = await request.json(); | |
| 8426 | - } catch { | |
| 8427 | - return new Response("invalid Queue request", { status: 400 }); | |
| 8428 | - } | |
| 8429 | - try { | |
| 8430 | - if (path === "/__qSettle") { | |
| 8431 | - return await this._settle(body) | |
| 8432 | - ? new Response(null, { status: 204 }) | |
| 8433 | - : new Response("stale Queue settlement", { status: 409 }); | |
| 8434 | - } | |
| 8435 | - if (body.op === "info") { | |
| 8436 | - const metrics = this._metrics(); | |
| 8437 | - const stored = this._open().exec( | |
| 8438 | - `SELECT stored_count FROM ${__QUEUE_STATS} WHERE id = 1`, | |
| 8439 | - ).toArray()[0].stored_count; | |
| 8440 | - return Response.json({ result: { ...metrics, stored, paused: this._paused() } }); | |
| 8441 | - } | |
| 8442 | - if (body.op === "purge") { | |
| 8443 | - return Response.json({ result: await this._purge() }); | |
| 8444 | - } | |
| 8445 | - if (body.op === "pause") { | |
| 8446 | - return Response.json({ result: await this._setPaused(true) }); | |
| 8447 | - } | |
| 8448 | - if (body.op === "resume") { | |
| 8449 | - return Response.json({ result: await this._setPaused(false) }); | |
| 8450 | - } | |
| 8451 | - if (body.op === "peek") { | |
| 8452 | - return Response.json({ | |
| 8453 | - result: this._peek(this._operatorLimit(body.limit, 10)), | |
| 8454 | - }); | |
| 8455 | - } | |
| 8456 | - if (body.op === "redrive") { | |
| 8457 | - return Response.json({ | |
| 8458 | - result: await this._redrive(this._operatorLimit(body.limit, 100)), | |
| 8459 | - }); | |
| 8460 | - } | |
| 8461 | - return Response.json( | |
| 8462 | - { error: `QUEUE_ERROR: unknown operation ${JSON.stringify(body.op)}` }, | |
| 8463 | - { status: 400 }, | |
| 8464 | - ); | |
| 8465 | - } catch (error) { | |
| 8466 | - return Response.json( | |
| 8467 | - { error: String(error?.message ?? error) }, | |
| 8468 | - { status: 400 }, | |
| 8469 | - ); | |
| 8470 | - } | |
| 8471 | - } | |
| 8472 | -} | |
| 8473 | - | |
| 8474 | -__cell.classes.__Queue = __QueueCell; | |
| 8475 | -__cell.doExports.__Queue = true; | |
| 8476 | - | |
| 8477 | -class Queue { | |
| 8478 | - constructor(queue, cellName, deliveryDelay) { | |
| 8479 | - Object.defineProperties(this, { | |
| 8480 | - _queue: { value: queue }, | |
| 8481 | - _cellName: { value: cellName }, | |
| 8482 | - _deliveryDelay: { value: deliveryDelay }, | |
| 8483 | - }); | |
| 8484 | - } | |
| 8485 | - | |
| 8486 | - get _stub() { | |
| 8487 | - return __cell.makeNamespace("__Queue").getByName(this._cellName); | |
| 8488 | - } | |
| 8489 | - | |
| 8490 | - async _send(entries) { | |
| 8491 | - const metrics = await this._stub.__queueSend({ entries }); | |
| 8492 | - return { metadata: { metrics: __queueMetricsView(metrics) } }; | |
| 8493 | - } | |
| 8494 | - | |
| 8495 | - send(body, options = {}) { | |
| 8496 | - const encoded = __queueEncode(body, options.contentType); | |
| 8497 | - return this._send([{ | |
| 8498 | - ...encoded, | |
| 8499 | - delaySeconds: __queueDelay(options.delaySeconds, this._deliveryDelay), | |
| 8500 | - }]); | |
| 8501 | - } | |
| 8502 | - | |
| 8503 | - sendBatch(messages, options = {}) { | |
| 8504 | - if (messages === null || messages === undefined || | |
| 8505 | - typeof messages[Symbol.iterator] !== "function") { | |
| 8506 | - throw __queueError("sendBatch() needs an iterable of messages"); | |
| 8507 | - } | |
| 8508 | - const entries = []; | |
| 8509 | - let bytes = 0; | |
| 8510 | - const batchDelay = __queueDelay(options.delaySeconds, this._deliveryDelay); | |
| 8511 | - for (const message of messages) { | |
| 8512 | - if (entries.length >= __queueLimits().maxBatchMessages) { | |
| 8513 | - throw __queueError( | |
| 8514 | - `a batch has at most ${__queueLimits().maxBatchMessages} messages`, | |
| 8515 | - ); | |
| 8516 | - } | |
| 8517 | - if (message === null || typeof message !== "object" || !("body" in message)) { | |
| 8518 | - throw __queueError("each batch entry needs a body"); | |
| 8519 | - } | |
| 8520 | - const encoded = __queueEncode(message.body, message.contentType); | |
| 8521 | - bytes += encoded.size; | |
| 8522 | - if (bytes > __queueLimits().maxBatchBytes) { | |
| 8523 | - throw __queueError( | |
| 8524 | - `a batch is at most ${__queueLimits().maxBatchBytes} bytes, got ${bytes}`, | |
| 8525 | - ); | |
| 8526 | - } | |
| 8527 | - entries.push({ | |
| 8528 | - ...encoded, | |
| 8529 | - delaySeconds: __queueDelay(message.delaySeconds, batchDelay), | |
| 8530 | - }); | |
| 8531 | - } | |
| 8532 | - if (entries.length === 0) { | |
| 8533 | - throw __queueError("sendBatch() needs at least one message"); | |
| 8534 | - } | |
| 8535 | - return this._send(entries); | |
| 8536 | - } | |
| 8537 | - | |
| 8538 | - async metrics() { | |
| 8539 | - return __queueMetricsView(await this._stub.__queueMetrics()); | |
| 8540 | - } | |
| 8541 | -} | |
| 8542 | - | |
| 8543 | -__celld.__makeQueue = (queue, cellName, deliveryDelay) => | |
| 8544 | - new Queue(queue, cellName, deliveryDelay); | |
| 8545 | - | |
| 8546 | -// ---- D1 ----------------------------------------------------------------- | |
| 8547 | -// A D1 database is a cell of a runtime-supplied Durable Object class, so it | |
| 8548 | -// inherits ownership, fencing, LTX replication, RPO=0 acknowledgement and | |
| 8549 | -// pressure shedding from the cell it already is. This half is the server; | |
| 8550 | -// `__makeD1Database` below is the client the binding hands to a Worker. | |
| 8551 | -// | |
| 8552 | -// Everything SQL goes through the one `__d1_run` op. The engine owns the | |
| 8553 | -// statement walk, the row and byte caps, and the meta snapshot, all inside | |
| 8554 | -// one execution -- the previous shape assembled these from the general | |
| 8555 | -// SqlStorage ops, and every seam between them was a contract only convention | |
| 8556 | -// enforced. | |
| 8557 | - | |
| 8558 | -// The error families applications match on. A message that already carries | |
| 8559 | -// one must pass through unwrapped: wrapping again would bury the family the | |
| 8560 | -// application is matching under a second D1_ERROR prefix. | |
| 8561 | -const __d1IsFamilyError = (message) => | |
| 8562 | - /^D1_([A-Z]+_)*(ERROR|NOTFOUND): /.test(String(message)); | |
| 8563 | - | |
| 8564 | -const __d1Error = (message, cause) => { | |
| 8565 | - const error = new Error("D1_ERROR: " + String(message)); | |
| 8566 | - error.cause = cause !== undefined ? cause : new Error(String(message)); | |
| 8567 | - return error; | |
| 8568 | -}; | |
| 8569 | - | |
| 8570 | -// A typed refusal from the engine: `{family, message}` becomes the Error the | |
| 8571 | -// application sees, with `.cause` carrying the bare message as upstream does. | |
| 8572 | -const __d1Failure = (failure) => { | |
| 8573 | - const error = new Error(failure.family + ": " + failure.message); | |
| 8574 | - error.cause = new Error(failure.message); | |
| 8575 | - return error; | |
| 8576 | -}; | |
| 8577 | - | |
| 8578 | -const __d1Run = (scope, request) => { | |
| 8579 | - const response = JSON.parse(__d1_run(scope, JSON.stringify(request))); | |
| 8580 | - if (response.error) throw __d1Failure(response.error); | |
| 8581 | - return response.ok; | |
| 8582 | -}; | |
| 8583 | - | |
| 8584 | -class __D1DatabaseCell { | |
| 8585 | - constructor(ctx) { | |
| 8586 | - this.ctx = ctx; | |
| 8587 | - } | |
| 8588 | - // Takes an array so that `batch()` can ride this same method, and the | |
| 8589 | - // same turn, when it lands. | |
| 8590 | - __d1Query(statements) { | |
| 8591 | - const scope = this.ctx.storage.sql._scope; | |
| 8592 | - return statements.map((statement) => | |
| 8593 | - __d1Run(scope, { | |
| 8594 | - mode: "prepared", | |
| 8595 | - sql: String(statement.sql), | |
| 8596 | - params: statement.params || [], | |
| 8597 | - first: !!statement.first, | |
| 8598 | - }) | |
| 8599 | - ); | |
| 8600 | - } | |
| 8601 | - __d1Batch(statements) { | |
| 8602 | - return __d1Run(this.ctx.storage.sql._scope, { | |
| 8603 | - mode: "batch", | |
| 8604 | - statements: statements.map((statement) => ({ | |
| 8605 | - sql: String(statement.sql), | |
| 8606 | - params: statement.params || [], | |
| 8607 | - })), | |
| 8608 | - }); | |
| 8609 | - } | |
| 8610 | - // The CLI's way in. `celld d1` signs each request with the fleet secret | |
| 8611 | - // and sends it to a live node's `/runtime/<scope>` route, which verifies the | |
| 8612 | - // signature and then forwards to the owner over the same dispatch `/do/` | |
| 8613 | - // uses -- so the CLI needs no ownership logic and the database is reached | |
| 8614 | - // the way a Worker reaches it. The unauthenticated `/do/` route refuses a | |
| 8615 | - // D1 scope outright: this cell answers arbitrary SQL, and its scope is an | |
| 8616 | - // HMAC over names that sit in the project's config, so the scope itself | |
| 8617 | - // is no secret. | |
| 8618 | - async fetch(request) { | |
| 8619 | - let body; | |
| 8620 | - try { | |
| 8621 | - body = await request.json(); | |
| 8622 | - } catch { | |
| 8623 | - return Response.json({ error: "D1_ERROR: invalid request body" }, { status: 400 }); | |
| 8624 | - } | |
| 8625 | - try { | |
| 8626 | - let result; | |
| 8627 | - if (body.migrate !== undefined) { | |
| 8628 | - result = this.__d1Migrate( | |
| 8629 | - String(body.migrate.name), | |
| 8630 | - String(body.migrate.sql), | |
| 8631 | - String(body.migrate.table || "d1_migrations"), | |
| 8632 | - ); | |
| 8633 | - } else if (body.exec !== undefined) { | |
| 8634 | - // The CLI asks for rows; the Worker binding's exec() never does. | |
| 8635 | - result = __d1Run(this.ctx.storage.sql._scope, { | |
| 8636 | - mode: "exec", | |
| 8637 | - sql: String(body.exec.sql), | |
| 8638 | - rows: !!body.exec.rows, | |
| 8639 | - }); | |
| 8640 | - } else { | |
| 8641 | - result = this.__d1Query(body.statements || []); | |
| 8642 | - } | |
| 8643 | - return Response.json({ result }); | |
| 8644 | - } catch (error) { | |
| 8645 | - return Response.json({ error: String(error && error.message || error) }, { status: 400 }); | |
| 8646 | - } | |
| 8647 | - } | |
| 8648 | - __d1Exec(source) { | |
| 8649 | - const result = __d1Run(this.ctx.storage.sql._scope, { | |
| 8650 | - mode: "exec", | |
| 8651 | - sql: String(source), | |
| 8652 | - rows: false, | |
| 8653 | - }); | |
| 8654 | - return { count: result.count, duration: result.duration }; | |
| 8655 | - } | |
| 8656 | - // Apply one migration and record it. The engine runs the file, the | |
| 8657 | - // bookkeeping insert (the name is a bound parameter, so a file name never | |
| 8658 | - // reaches SQL text) and the BEGIN IMMEDIATE .. COMMIT bracket in one | |
| 8659 | - // request, so a migration that fails part-way rolls back whole and the | |
| 8660 | - // operator fixes the file and re-runs. Without the transaction the | |
| 8661 | - // statements that DID land are exactly the ones a re-run trips over. | |
| 8662 | - __d1Migrate(name, source, table) { | |
| 8663 | - return __d1Run(this.ctx.storage.sql._scope, { | |
| 8664 | - mode: "migrate", | |
| 8665 | - name, | |
| 8666 | - sql: source, | |
| 8667 | - table, | |
| 8668 | - }); | |
| 8669 | - } | |
| 8670 | -} | |
| 8671 | - | |
| 8672 | -__cell.classes.__D1Database = __D1DatabaseCell; | |
| 8673 | -// RPC on a stub needs `extends DurableObject` or the js_rpc flag. This class | |
| 8674 | -// is the runtime's own, so grant it here instead of making every D1 user set | |
| 8675 | -// a compatibility flag to reach their database. | |
| 8676 | -__cell.doExports.__D1Database = true; | |
| 8677 | - | |
| 8678 | -// Validate and encode bind values once, at the public boundary, exactly as | |
| 8679 | -// upstream does (workerd d1-api.ts). Byte-shaped values become byte arrays -- | |
| 8680 | -// the wire format for a BLOB bind -- and anything unsupported throws | |
| 8681 | -// D1_TYPE_ERROR here, before any SQL runs. The first version deferred this | |
| 8682 | -// to a JSON round-trip whose fallthrough was SQL NULL, so a Uint8Array bind | |
| 8683 | -// stored NULL and nothing said so. | |
| 8684 | -const __d1BindValue = (value) => { | |
| 8685 | - const kind = typeof value; | |
| 8686 | - if (kind === "number") { | |
| 8687 | - // A non-finite number has no JSON form, so it crosses as null and | |
| 8688 | - // stores SQL NULL. Upstream does the same (bind(NaN) selects typeof | |
| 8689 | - // "null"); making it explicit here turns the conversion from an | |
| 8690 | - // accident of JSON.stringify into a pinned decision. | |
| 8691 | - return Number.isFinite(value) ? value : null; | |
| 8692 | - } | |
| 8693 | - if (kind === "string") return value; | |
| 8694 | - if (kind === "boolean") return value ? 1 : 0; | |
| 8695 | - if (kind === "object") { | |
| 8696 | - if (value === null) return value; | |
| 8697 | - if ( | |
| 8698 | - Array.isArray(value) && | |
| 8699 | - value.every((byte) => typeof byte === "number" && byte >= 0 && byte < 256) | |
| 8700 | - ) { | |
| 8701 | - return value; | |
| 8702 | - } | |
| 8703 | - if (value instanceof ArrayBuffer) { | |
| 8704 | - return Array.from(new Uint8Array(value)); | |
| 8705 | - } | |
| 8706 | - // A typed view binds its ELEMENT values, each truncated to a byte -- | |
| 8707 | - // Int8Array([-1]) stores 0xff, Float32Array([1.5]) stores 0x01 -- not | |
| 8708 | - // its underlying byte window, so Uint16Array([65, 66]) stores 2 bytes | |
| 8709 | - // and not 4. Upstream behaves this way (verified against workerd's D1; | |
| 8710 | - // the differential suite pins it), and the bare Array.from that | |
| 8711 | - // preceded this produced elements the engine then refused as bytes. | |
| 8712 | - if (ArrayBuffer.isView(value)) return Array.from(Uint8Array.from(value)); | |
| 8713 | - } | |
| 8714 | - const error = new Error( | |
| 8715 | - `D1_TYPE_ERROR: Type '${kind}' not supported for value '${value}'`, | |
| 8716 | - ); | |
| 8717 | - error.cause = new Error(`Type '${kind}' not supported for value '${value}'`); | |
| 8718 | - throw error; | |
| 8719 | -}; | |
| 8720 | - | |
| 8721 | -class D1PreparedStatement { | |
| 8722 | - constructor(database, sql, params) { | |
| 8723 | - Object.defineProperty(this, "_database", { value: database }); | |
| 8724 | - Object.defineProperty(this, "_sql", { value: sql }); | |
| 8725 | - Object.defineProperty(this, "_params", { value: params }); | |
| 8726 | - } | |
| 8727 | - bind(...values) { | |
| 8728 | - return new D1PreparedStatement( | |
| 8729 | - this._database, | |
| 8730 | - this._sql, | |
| 8731 | - values.map(__d1BindValue), | |
| 8732 | - ); | |
| 8733 | - } | |
| 8734 | - async _run(first) { | |
| 8735 | - const results = await this._database._query([ | |
| 8736 | - { sql: this._sql, params: this._params, first }, | |
| 8737 | - ]); | |
| 8738 | - return results[0]; | |
| 8739 | - } | |
| 8740 | - async all() { | |
| 8741 | - const result = await this._run(); | |
| 8742 | - return { | |
| 8743 | - success: true, | |
| 8744 | - meta: result.meta, | |
| 8745 | - results: result.rows.map((row) => __d1Shape(result.columns, row)), | |
| 8746 | - }; | |
| 8747 | - } | |
| 8748 | - async run() { | |
| 8749 | - return await this.all(); | |
| 8750 | - } | |
| 8751 | - async first(column) { | |
| 8752 | - // `first: true` keeps one row on the cell side, so only that row crosses | |
| 8753 | - // the isolate boundary and the row cap cannot fire for a first(). | |
| 8754 | - const result = await this._run(true); | |
| 8755 | - if (result.rows.length === 0) return null; | |
| 8756 | - const row = __d1Shape(result.columns, result.rows[0]); | |
| 8757 | - if (column === undefined) return row; | |
| 8758 | - // The check runs on the shaped object, as upstream's does, so a column | |
| 8759 | - // named like an Object.prototype member behaves the same here as there. | |
| 8760 | - if (row[column] === undefined) { | |
| 8761 | - const error = new Error( | |
| 8762 | - `D1_COLUMN_NOTFOUND: Column not found (${column})`, | |
| 8763 | - ); | |
| 8764 | - error.cause = new Error("Column not found"); | |
| 8765 | - throw error; | |
| 8766 | - } | |
| 8767 | - return row[column]; | |
| 8768 | - } | |
| 8769 | - async raw(options) { | |
| 8770 | - const result = await this._run(); | |
| 8771 | - return options && options.columnNames | |
| 8772 | - ? [result.columns, ...result.rows] | |
| 8773 | - : result.rows; | |
| 8774 | - } | |
| 8775 | -} | |
| 8776 | - | |
| 8777 | -// Object.fromEntries, not property assignment: assigning to a column named | |
| 8778 | -// `__proto__` would walk the prototype chain and silently drop the value, | |
| 8779 | -// while fromEntries defines an own property whatever the name. | |
| 8780 | -const __d1Shape = (columns, row) => | |
| 8781 | - Object.fromEntries(row.map((value, index) => [columns[index], value])); | |
| 8782 | - | |
| 8783 | -const __d1PublicResult = (result) => ({ | |
| 8784 | - success: true, | |
| 8785 | - meta: result.meta, | |
| 8786 | - results: result.rows.map((row) => __d1Shape(result.columns, row)), | |
| 8787 | -}); | |
| 8788 | - | |
| 8789 | -// celld has one primary and no replicas, so every completed query satisfies | |
| 8790 | -// every earlier session constraint. One stable opaque token states that fact | |
| 8791 | -// without pretending an isolate-local counter is a durable database position. | |
| 8792 | -const __d1PrimaryBookmark = "celld:primary"; | |
| 8793 | - | |
| 8794 | -class D1DatabaseSession { | |
| 8795 | - constructor(database, constraintOrBookmark) { | |
| 8796 | - Object.defineProperty(this, "_database", { value: database }); | |
| 8797 | - const value = constraintOrBookmark == null | |
| 8798 | - ? "first-unconstrained" | |
| 8799 | - : String(constraintOrBookmark).trim(); | |
| 8800 | - if (!value) { | |
| 8801 | - throw new Error("D1_SESSION_ERROR: invalid bookmark or constraint"); | |
| 8802 | - } | |
| 8803 | - Object.defineProperty(this, "_bookmark", { | |
| 8804 | - value: value === "first-primary" || value === "first-unconstrained" ? null : value, | |
| 8805 | - writable: true, | |
| 8806 | - }); | |
| 8807 | - } | |
| 8808 | - _advanceBookmark() { | |
| 8809 | - this._bookmark = __d1PrimaryBookmark; | |
| 8810 | - } | |
| 8811 | - async _query(statements) { | |
| 8812 | - const results = await this._database._query(statements); | |
| 8813 | - this._advanceBookmark(); | |
| 8814 | - return results; | |
| 8815 | - } | |
| 8816 | - prepare(sql) { | |
| 8817 | - return new D1PreparedStatement(this, String(sql), []); | |
| 8818 | - } | |
| 8819 | - async batch(statements) { | |
| 8820 | - const results = await this._database._batch(statements); | |
| 8821 | - this._advanceBookmark(); | |
| 8822 | - return results; | |
| 8823 | - } | |
| 8824 | - getBookmark() { | |
| 8825 | - return this._bookmark; | |
| 8826 | - } | |
| 8827 | -} | |
| 8828 | - | |
| 8829 | -// Named so SDKs that sniff a binding by `constructor.name` recognise it. | |
| 8830 | -class D1Database { | |
| 8831 | - constructor(databaseName) { | |
| 8832 | - Object.defineProperty(this, "_databaseName", { value: databaseName }); | |
| 8833 | - } | |
| 8834 | - // Resolved per call rather than cached: a cell can move between calls, and | |
| 8835 | - // `getByName` is the same cost the Durable Object path already pays. | |
| 8836 | - get _stub() { | |
| 8837 | - return __cell.makeNamespace("__D1Database").getByName(this._databaseName); | |
| 8838 | - } | |
| 8839 | - async _query(statements) { | |
| 8840 | - try { | |
| 8841 | - return await this._stub.__d1Query(statements); | |
| 8842 | - } catch (error) { | |
| 8843 | - if (__d1IsFamilyError(error && error.message)) throw error; | |
| 8844 | - throw __d1Error(String(error && error.message || error), error); | |
| 8845 | - } | |
| 8846 | - } | |
| 8847 | - async _batch(statements) { | |
| 8848 | - try { | |
| 8849 | - const encoded = statements.map((statement) => ({ | |
| 8850 | - sql: statement._sql, | |
| 8851 | - params: statement._params, | |
| 8852 | - })); | |
| 8853 | - const results = await this._stub.__d1Batch(encoded); | |
| 8854 | - return results.map(__d1PublicResult); | |
| 8855 | - } catch (error) { | |
| 8856 | - if (__d1IsFamilyError(error && error.message)) throw error; | |
| 8857 | - throw __d1Error(String(error && error.message || error), error); | |
| 8858 | - } | |
| 8859 | - } | |
| 8860 | - prepare(sql) { | |
| 8861 | - return new D1PreparedStatement(this, String(sql), []); | |
| 8862 | - } | |
| 8863 | - async exec(sql) { | |
| 8864 | - try { | |
| 8865 | - return await this._stub.__d1Exec(String(sql)); | |
| 8866 | - } catch (error) { | |
| 8867 | - if (__d1IsFamilyError(error && error.message)) throw error; | |
| 8868 | - throw __d1Error(String(error && error.message || error), error); | |
| 8869 | - } | |
| 8870 | - } | |
| 8871 | - async batch(statements) { | |
| 8872 | - return await this._batch(statements); | |
| 8873 | - } | |
| 8874 | - withSession(constraintOrBookmark) { | |
| 8875 | - return new D1DatabaseSession(this, constraintOrBookmark); | |
| 8876 | - } | |
| 8877 | - async dump() { | |
| 8878 | - throw __d1Error( | |
| 8879 | - "dump() is not implemented in celld; the database is a SQLite file in " + | |
| 8880 | - "your own bucket", | |
| 8881 | - ); | |
| 8882 | - } | |
| 8883 | -} | |
| 8884 | - | |
| 8885 | -const __makeD1Database = __celld.__makeD1Database = | |
| 8886 | - (databaseName) => new D1Database(databaseName); | |
| 8887 | -// ---- Workflows ---------------------------------------------------------- | |
| 8888 | -// A workflow instance is one cell of the runtime-supplied `__Workflow` class, | |
| 8889 | -// named `<workflow_name>/<instance_id>` through getByName, so it inherits | |
| 8890 | -// ownership, fencing, LTX replication and the output gate from the cell it | |
| 8891 | -// already is. Execution is replay: `run()` re-executes from the top on every | |
| 8892 | -// resume and only steps are memoized, in `ctx.storage` KV under `__wf.*`. | |
| 8893 | -// This half is the server; `__makeWorkflow` below is the client the binding | |
| 8894 | -// hands to a Worker. The public contract is in docs/cloudflare-compat.md. | |
| 8895 | - | |
| 8896 | -// Upstream's limit for a step return, an event payload, and the params. The | |
| 8897 | -// error is distinct and names the step, because "too large" and "the isolate | |
| 8898 | -// died" must not read the same (the D1 row-cap precedent). | |
| 8899 | -const __WF_VALUE_CAP = 1 << 20; | |
| 8900 | -// Workflow names, instance ids, and event types all share this charset. | |
| 8901 | -// `/` is outside it, which is what makes the `<name>/<id>` cell-name join | |
| 8902 | -// unambiguous. | |
| 8903 | -const __WF_NAME_RE = /^[a-zA-Z0-9_][a-zA-Z0-9-_]*$/; | |
| 8904 | -const __wfError = (message) => new Error("WORKFLOW_ERROR: " + message); | |
| 8905 | -// The suspension primitive: a blocked step returns a promise that never | |
| 8906 | -// settles in this invocation, so user code simply stops progressing. A | |
| 8907 | -// sentinel thrown through user code was rejected because `Promise.all` in | |
| 8908 | -// `run()` would observe it as a rejection and user try/catch would eat it. | |
| 8909 | -const __wfNever = new Promise(() => {}); | |
| 8910 | -const __wfTerminal = (status) => | |
| 8911 | - status === "complete" || status === "errored" || status === "terminated"; | |
| 8912 | -// Upstream's hard bounds: 10,000 retries per step, 365 days for any sleep or | |
| 8913 | -// event wait, one second under a waitForEvent timeout. Enforced loudly at the | |
| 8914 | -// call site -- a config outside them would otherwise misbehave only after | |
| 8915 | -// the instance is minutes or days into its run. | |
| 8916 | -const __WF_RETRY_LIMIT_CAP = 10000; | |
| 8917 | -const __WF_STEP_NAME_LIMIT = 256; | |
| 8918 | -const __WF_MAX_WAIT_MS = 365 * 86400000; | |
| 8919 | -const __WF_MIN_EVENT_TIMEOUT_MS = 1000; | |
| 8920 | -// celld has no account plans, so it exposes the larger published retention | |
| 8921 | -// ceiling as one stable application limit. Both an omitted policy and an | |
| 8922 | -// omitted member of a partial policy use this value. | |
| 8923 | -const __WF_RETENTION_MAX_MS = 30 * 86400000; | |
| 8924 | -const __WF_LOCATION_HINTS = new Set([ | |
| 8925 | - "wnam", "enam", "sam", "weur", "eeur", "apac", "apac-ne", "apac-se", | |
| 8926 | - "oc", "afr", "me", | |
| 8927 | -]); | |
| 8928 | -// How long run() can stay pending on non-step work while no step runs and | |
| 8929 | -// none is blocked before the instance fails. Upstream permits un-stepped | |
| 8930 | -// awaits between steps (they are merely non-durable), so erroring at the | |
| 8931 | -// first quiescent macrotask would kill any run() whose external await | |
| 8932 | -// outlives one turn of the loop. Sixty seconds is long enough for any | |
| 8933 | -// sane un-stepped await and short enough that a truly never-settling | |
| 8934 | -// promise fails the instance instead of wedging the alarm handler. | |
| 8935 | -const __WF_STALL_GRACE_MS = 60000; | |
| 8936 | -const __WF_UNITS = { | |
| 8937 | - second: 1000, | |
| 8938 | - minute: 60000, | |
| 8939 | - hour: 3600000, | |
| 8940 | - day: 86400000, | |
| 8941 | - week: 604800000, | |
| 8942 | - // Upstream does not document its month/year arithmetic; fixed 30/365-day | |
| 8943 | - // units are used so one expression cannot mean two durations depending on | |
| 8944 | - // when it runs. | |
| 8945 | - month: 30 * 86400000, | |
| 8946 | - year: 365 * 86400000, | |
| 8947 | -}; | |
| 8948 | -const __wfDuration = (value, what) => { | |
| 8949 | - if (typeof value === "number" && Number.isFinite(value) && value >= 0) return value; | |
| 8950 | - if (typeof value !== "string") { | |
| 8951 | - throw __wfError( | |
| 8952 | - `invalid duration for ${what}: ${JSON.stringify(value)}; use milliseconds ` + | |
| 8953 | - 'or "<n> <second|minute|hour|day|week|month|year>[s]"', | |
| 8954 | - ); | |
| 8955 | - } | |
| 8956 | - const match = /^\s*(\d+(?:\.\d+)?)\s+(second|minute|hour|day|week|month|year)s?\s*$/ | |
| 8957 | - .exec(value); | |
| 8958 | - if (!match) { | |
| 8959 | - throw __wfError( | |
| 8960 | - `invalid duration for ${what}: ${JSON.stringify(value)}; use milliseconds ` + | |
| 8961 | - 'or "<n> <second|minute|hour|day|week|month|year>[s]"', | |
| 8962 | - ); | |
| 8963 | - } | |
| 8964 | - return Number(match[1]) * __WF_UNITS[match[2]]; | |
| 8965 | -}; | |
| 8966 | -const __wfRetentionDuration = (value, what) => { | |
| 8967 | - const durationMs = __wfDuration(value, what); | |
| 8968 | - if (durationMs > __WF_RETENTION_MAX_MS) { | |
| 8969 | - throw __wfError( | |
| 8970 | - `${what} is ${durationMs} ms, above celld's 30-day retention limit`, | |
| 8971 | - ); | |
| 8972 | - } | |
| 8973 | - return durationMs; | |
| 8974 | -}; | |
| 8975 | -const __wfOwnObject = (value) => | |
| 8976 | - value !== null && typeof value === "object" && !Array.isArray(value); | |
| 8977 | -const __wfUnknownKey = (value, allowed) => | |
| 8978 | - Object.keys(value).find((key) => !allowed.includes(key)); | |
| 8979 | -const __wfStepName = (name) => { | |
| 8980 | - // The pinned workers-sdk validator has no minimum length. An empty name is | |
| 8981 | - // therefore valid, although rejecting it looks safer at first glance. A | |
| 8982 | - // non-empty check made celld reject Worker code that the upstream runtime | |
| 8983 | - // accepts, so keep only the upstream length and control-character bounds. | |
| 8984 | - if ( | |
| 8985 | - typeof name !== "string" || name.length > __WF_STEP_NAME_LIMIT || | |
| 8986 | - /[\x00-\x1f]/.test(name) | |
| 8987 | - ) { | |
| 8988 | - throw __wfError( | |
| 8989 | - `invalid step name ${JSON.stringify(name)}: use at most ` + | |
| 8990 | - `${__WF_STEP_NAME_LIMIT} characters and no control characters`, | |
| 8991 | - ); | |
| 8992 | - } | |
| 8993 | -}; | |
| 8994 | -const __wfEventType = (type) => { | |
| 8995 | - if (typeof type !== "string" || type.length > 100 || !__WF_NAME_RE.test(type)) { | |
| 8996 | - throw __wfError( | |
| 8997 | - `invalid event type ${JSON.stringify(type)}: use at most 100 letters, ` + | |
| 8998 | - "digits, hyphens, or underscores", | |
| 8999 | - ); | |
| 9000 | - } | |
| 9001 | -}; | |
| 9002 | -const __wfSleepDuration = (duration, name) => { | |
| 9003 | - const durationMs = __wfDuration( | |
| 9004 | - duration, | |
| 9005 | - `the duration of sleep ${JSON.stringify(name)}`, | |
| 9006 | - ); | |
| 9007 | - if (durationMs > __WF_MAX_WAIT_MS) { | |
| 9008 | - throw __wfError( | |
| 9009 | - `sleep ${JSON.stringify(name)} is ${durationMs} ms, above the upstream ` + | |
| 9010 | - "limit of 365 days", | |
| 9011 | - ); | |
| 9012 | - } | |
| 9013 | - return durationMs; | |
| 9014 | -}; | |
| 9015 | -const __wfSleepUntil = (timestamp, name) => { | |
| 9016 | - const at = timestamp instanceof Date ? timestamp.getTime() : timestamp; | |
| 9017 | - if (typeof at !== "number" || !Number.isFinite(at)) { | |
| 9018 | - throw __wfError( | |
| 9019 | - `invalid sleepUntil timestamp for ${JSON.stringify(name)}: use a Date ` + | |
| 9020 | - "or a UNIX timestamp in milliseconds", | |
| 9021 | - ); | |
| 9022 | - } | |
| 9023 | - const delay = at - Date.now(); | |
| 9024 | - if (delay > __WF_MAX_WAIT_MS) { | |
| 9025 | - throw __wfError( | |
| 9026 | - `sleepUntil ${JSON.stringify(name)} is ${delay} ms away, above the ` + | |
| 9027 | - "upstream limit of 365 days", | |
| 9028 | - ); | |
| 9029 | - } | |
| 9030 | - return at; | |
| 9031 | -}; | |
| 9032 | -const __wfWaitOptions = (options, name) => { | |
| 9033 | - if (!__wfOwnObject(options)) { | |
| 9034 | - throw __wfError(`invalid waitForEvent options for ${JSON.stringify(name)}`); | |
| 9035 | - } | |
| 9036 | - __wfEventType(options.type); | |
| 9037 | - const timeout = options.timeout ?? "24 hours"; | |
| 9038 | - const timeoutMs = __wfDuration( | |
| 9039 | - timeout, | |
| 9040 | - `the timeout of waitForEvent ${JSON.stringify(name)}`, | |
| 9041 | - ); | |
| 9042 | - if (timeoutMs < __WF_MIN_EVENT_TIMEOUT_MS || timeoutMs > __WF_MAX_WAIT_MS) { | |
| 9043 | - throw __wfError( | |
| 9044 | - `the timeout of waitForEvent ${JSON.stringify(name)} is ${timeoutMs} ms; ` + | |
| 9045 | - "upstream allows 1 second to 365 days", | |
| 9046 | - ); | |
| 9047 | - } | |
| 9048 | - return { type: options.type, timeout, timeoutMs }; | |
| 9049 | -}; | |
| 9050 | -const __wfEventOptions = (options) => { | |
| 9051 | - if (!__wfOwnObject(options)) { | |
| 9052 | - throw __wfError("sendEvent() needs an event object"); | |
| 9053 | - } | |
| 9054 | - __wfEventType(options.type); | |
| 9055 | - if (options.payload !== undefined) __wfCheckValue(options.payload, "the event payload"); | |
| 9056 | - return { type: options.type, payload: options.payload }; | |
| 9057 | -}; | |
| 9058 | -const __wfRetentionOptions = (retention, what) => { | |
| 9059 | - if (retention === undefined) { | |
| 9060 | - return { | |
| 9061 | - successMs: __WF_RETENTION_MAX_MS, | |
| 9062 | - errorMs: __WF_RETENTION_MAX_MS, | |
| 9063 | - }; | |
| 9064 | - } | |
| 9065 | - if (!__wfOwnObject(retention)) { | |
| 9066 | - throw __wfError(`${what} option retention must be an object`); | |
| 9067 | - } | |
| 9068 | - const unknown = __wfUnknownKey(retention, ["successRetention", "errorRetention"]); | |
| 9069 | - if (unknown !== undefined) { | |
| 9070 | - throw __wfError( | |
| 9071 | - `${what} option retention has an unknown field ${JSON.stringify(unknown)}`, | |
| 9072 | - ); | |
| 9073 | - } | |
| 9074 | - return { | |
| 9075 | - successMs: retention.successRetention === undefined | |
| 9076 | - ? __WF_RETENTION_MAX_MS | |
| 9077 | - : __wfRetentionDuration( | |
| 9078 | - retention.successRetention, | |
| 9079 | - `${what} successRetention`, | |
| 9080 | - ), | |
| 9081 | - errorMs: retention.errorRetention === undefined | |
| 9082 | - ? __WF_RETENTION_MAX_MS | |
| 9083 | - : __wfRetentionDuration(retention.errorRetention, `${what} errorRetention`), | |
| 9084 | - }; | |
| 9085 | -}; | |
| 9086 | -const __wfLocationHint = (hint, what) => { | |
| 9087 | - if (hint !== undefined && !__WF_LOCATION_HINTS.has(hint)) { | |
| 9088 | - throw __wfError( | |
| 9089 | - `${what} has invalid locationHint ${JSON.stringify(hint)}`, | |
| 9090 | - ); | |
| 9091 | - } | |
| 9092 | - return hint; | |
| 9093 | -}; | |
| 9094 | -const __wfRestartOptions = (options) => { | |
| 9095 | - if (options === undefined) return {}; | |
| 9096 | - if (!__wfOwnObject(options)) { | |
| 9097 | - throw __wfError("restart() options must be an object"); | |
| 9098 | - } | |
| 9099 | - const unknown = __wfUnknownKey(options, ["from"]); | |
| 9100 | - if (unknown !== undefined) { | |
| 9101 | - throw __wfError(`restart() has an unknown option ${JSON.stringify(unknown)}`); | |
| 9102 | - } | |
| 9103 | - if (options.from === undefined) return {}; | |
| 9104 | - const from = options.from; | |
| 9105 | - if (!__wfOwnObject(from)) { | |
| 9106 | - throw __wfError("restart() option from must be an object"); | |
| 9107 | - } | |
| 9108 | - const fromUnknown = __wfUnknownKey(from, ["name", "count", "type"]); | |
| 9109 | - if (fromUnknown !== undefined) { | |
| 9110 | - throw __wfError( | |
| 9111 | - `restart() option from has an unknown field ${JSON.stringify(fromUnknown)}`, | |
| 9112 | - ); | |
| 9113 | - } | |
| 9114 | - __wfStepName(from.name); | |
| 9115 | - const count = from.count ?? 1; | |
| 9116 | - if (!Number.isInteger(count) || count < 1) { | |
| 9117 | - throw __wfError("restart() option from.count must be a positive integer"); | |
| 9118 | - } | |
| 9119 | - const type = from.type ?? "do"; | |
| 9120 | - if (!["do", "sleep", "waitForEvent"].includes(type)) { | |
| 9121 | - throw __wfError( | |
| 9122 | - 'restart() option from.type must be "do", "sleep", or "waitForEvent"', | |
| 9123 | - ); | |
| 9124 | - } | |
| 9125 | - return { from: { name: from.name, count, type } }; | |
| 9126 | -}; | |
| 9127 | -const __wfStepConfig = (config, name) => { | |
| 9128 | - if (!__wfOwnObject(config)) { | |
| 9129 | - throw __wfError(`invalid config for step ${JSON.stringify(name)}: use an object`); | |
| 9130 | - } | |
| 9131 | - let unknown = __wfUnknownKey(config, ["retries", "timeout", "sensitive"]); | |
| 9132 | - if (unknown !== undefined) { | |
| 9133 | - throw __wfError( | |
| 9134 | - `invalid config for step ${JSON.stringify(name)}: unknown option ` + | |
| 9135 | - JSON.stringify(unknown), | |
| 9136 | - ); | |
| 9137 | - } | |
| 9138 | - const retries = config.retries; | |
| 9139 | - if (retries !== undefined) { | |
| 9140 | - if (!__wfOwnObject(retries)) { | |
| 9141 | - throw __wfError(`invalid retries config for step ${JSON.stringify(name)}`); | |
| 9142 | - } | |
| 9143 | - unknown = __wfUnknownKey(retries, ["limit", "delay", "backoff"]); | |
| 9144 | - if (unknown !== undefined) { | |
| 9145 | - throw __wfError( | |
| 9146 | - `invalid retries config for step ${JSON.stringify(name)}: unknown option ` + | |
| 9147 | - JSON.stringify(unknown), | |
| 9148 | - ); | |
| 9149 | - } | |
| 9150 | - if ( | |
| 9151 | - typeof retries.limit !== "number" || !Number.isFinite(retries.limit) || | |
| 9152 | - retries.limit < 0 | |
| 9153 | - ) { | |
| 9154 | - throw __wfError( | |
| 9155 | - `invalid retries config for step ${JSON.stringify(name)}: ` + | |
| 9156 | - "limit must be a non-negative number", | |
| 9157 | - ); | |
| 9158 | - } | |
| 9159 | - if (retries.limit > __WF_RETRY_LIMIT_CAP) { | |
| 9160 | - throw __wfError( | |
| 9161 | - `invalid retries config for step ${JSON.stringify(name)}: limit is above ` + | |
| 9162 | - String(__WF_RETRY_LIMIT_CAP), | |
| 9163 | - ); | |
| 9164 | - } | |
| 9165 | - if (typeof retries.delay !== "function") { | |
| 9166 | - __wfDuration(retries.delay, `the retries config delay of step ${JSON.stringify(name)}`); | |
| 9167 | - } | |
| 9168 | - if ( | |
| 9169 | - retries.backoff !== undefined && | |
| 9170 | - !["constant", "linear", "exponential"].includes(retries.backoff) | |
| 9171 | - ) { | |
| 9172 | - throw __wfError( | |
| 9173 | - `invalid retries config for step ${JSON.stringify(name)}: ` + | |
| 9174 | - "backoff must be constant, linear, or exponential", | |
| 9175 | - ); | |
| 9176 | - } | |
| 9177 | - } | |
| 9178 | - if (config.timeout !== undefined) { | |
| 9179 | - const timeout = __wfDuration( | |
| 9180 | - config.timeout, | |
| 9181 | - `the config timeout of step ${JSON.stringify(name)}`, | |
| 9182 | - ); | |
| 9183 | - if (timeout === 0) { | |
| 9184 | - throw __wfError( | |
| 9185 | - `invalid config timeout for step ${JSON.stringify(name)}: use a value above zero`, | |
| 9186 | - ); | |
| 9187 | - } | |
| 9188 | - } | |
| 9189 | - if (config.sensitive !== undefined && config.sensitive !== "output") { | |
| 9190 | - throw __wfError( | |
| 9191 | - `invalid config sensitive value for step ${JSON.stringify(name)}: use "output"`, | |
| 9192 | - ); | |
| 9193 | - } | |
| 9194 | - return { | |
| 9195 | - ...config, | |
| 9196 | - ...(retries === undefined ? {} : { retries: { ...retries } }), | |
| 9197 | - }; | |
| 9198 | -}; | |
| 9199 | -// Serialization is checked with the same encoder storage and RPC use, so a | |
| 9200 | -// value that passes here cannot fail later at the isolate boundary. The | |
| 9201 | -// thrown errors are permanent: retrying cannot make a value cloneable or | |
| 9202 | -// shrink it. | |
| 9203 | -const __wfEncodeValue = (value, what) => { | |
| 9204 | - try { | |
| 9205 | - return __sc_encode(value); | |
| 9206 | - } catch (error) { | |
| 9207 | - const failure = __wfError( | |
| 9208 | - `${what} is not serializable: ${String(error && error.message || error)}. ` + | |
| 9209 | - "It must survive structured clone; a ReadableStream return is not implemented in celld.", | |
| 9210 | - ); | |
| 9211 | - failure.__wfPermanent = true; | |
| 9212 | - throw failure; | |
| 9213 | - } | |
| 9214 | -}; | |
| 9215 | -const __wfCheckEncodedValue = (bytes, what) => { | |
| 9216 | - if (bytes.byteLength > __WF_VALUE_CAP) { | |
| 9217 | - const failure = __wfError( | |
| 9218 | - `${what} is ${bytes.byteLength} bytes, above the 1 MiB limit; ` + | |
| 9219 | - "store large output externally and return a reference", | |
| 9220 | - ); | |
| 9221 | - failure.__wfPermanent = true; | |
| 9222 | - throw failure; | |
| 9223 | - } | |
| 9224 | -}; | |
| 9225 | -const __wfCheckValue = (value, what) => | |
| 9226 | - __wfCheckEncodedValue(__wfEncodeValue(value, what), what); | |
| 9227 | -const __wfErrorRecord = (error) => ({ | |
| 9228 | - name: String(error && error.name || "Error"), | |
| 9229 | - message: String(error && error.message || error), | |
| 9230 | -}); | |
| 9231 | -// A permanently failed step rejects on every replay, so user try/catch | |
| 9232 | -// around step.do keeps working after a resume, not only on the attempt that | |
| 9233 | -// failed live. | |
| 9234 | -const __wfReviveError = (record) => { | |
| 9235 | - const error = new Error(record.message); | |
| 9236 | - error.name = record.name; | |
| 9237 | - return error; | |
| 9238 | -}; | |
| 9239 | -const __wfLedgerPrefix = (generation) => `__wf.${generation}.`; | |
| 9240 | -const __wfEventPrefix = (generation) => | |
| 9241 | - __wfLedgerPrefix(generation) + "event."; | |
| 9242 | -const __wfEventKey = (generation, sequence) => | |
| 9243 | - __wfEventPrefix(generation) + String(sequence).padStart(9, "0"); | |
| 9244 | -const __wfRetentionMs = (meta, status) => | |
| 9245 | - status === "complete" | |
| 9246 | - ? (meta.retention?.successMs ?? __WF_RETENTION_MAX_MS) | |
| 9247 | - : (meta.retention?.errorMs ?? __WF_RETENTION_MAX_MS); | |
| 9248 | -const __wfFinishRetention = (meta, transaction) => { | |
| 9249 | - meta.endedMs = Date.now(); | |
| 9250 | - meta.expiresMs = meta.endedMs + __wfRetentionMs(meta, meta.status); | |
| 9251 | - transaction.setAlarm(meta.expiresMs); | |
| 9252 | -}; | |
| 9253 | -// A ledger record replays only through the kind of call that wrote it. A | |
| 9254 | -// `do` renamed into a `sleep`, or two calls reordered under one name, would | |
| 9255 | -// otherwise read fields the other kind never wrote and continue on | |
| 9256 | -// undefined -- a deadline of NaN, a value of nothing -- instead of failing. | |
| 9257 | -const __wfKindCheck = (record, kind, name) => { | |
| 9258 | - if (record === undefined || record.kind === kind) return record; | |
| 9259 | - const failure = __wfError( | |
| 9260 | - `step ${JSON.stringify(name)} replays as ${kind} but its ledger record ` + | |
| 9261 | - `was written by ${record.kind}; a step keeps one kind across replays`, | |
| 9262 | - ); | |
| 9263 | - failure.__wfPermanent = true; | |
| 9264 | - throw failure; | |
| 9265 | -}; | |
| 9266 | -// Each step callback runs under an async-context frame naming its step (the | |
| 9267 | -// same CPED-backed frame __ctxRun uses, so it survives the callback's | |
| 9268 | -// awaits). A step started inside another step's callback would wedge | |
| 9269 | -// quiescence: the outer callback cannot settle while it awaits the blocked | |
| 9270 | -// inner step, so `running` never reaches zero and the instance can neither | |
| 9271 | -// suspend nor finish. The frame is what lets the inner call refuse loudly | |
| 9272 | -// at the nesting site instead. | |
| 9273 | -const __wfStepKey = Symbol("celld.wfStep"); | |
| 9274 | -const __wfEnclosingStep = () => { | |
| 9275 | - const frame = __als_get(); | |
| 9276 | - return frame === undefined ? undefined : frame.get(__wfStepKey); | |
| 9277 | -}; | |
| 9278 | -const __wfEnterStep = (name, fn) => { | |
| 9279 | - const prior = __als_get(); | |
| 9280 | - const frame = new Map(prior); | |
| 9281 | - frame.set(__wfStepKey, name); | |
| 9282 | - __als_set(frame); | |
| 9283 | - try { | |
| 9284 | - return fn(); | |
| 9285 | - } finally { | |
| 9286 | - __als_set(prior); | |
| 9287 | - } | |
| 9288 | -}; | |
| 9289 | - | |
| 9290 | -// Race an attempt against its deadline. The abandoned callback keeps | |
| 9291 | -// running -- there is no cancellation to send it -- but its result is | |
| 9292 | -// discarded and the timeout counts as a failed attempt, as upstream. | |
| 9293 | -const __wfTimeout = (promise, ms, name, attempt) => | |
| 9294 | - new Promise((resolve, reject) => { | |
| 9295 | - const timer = setTimeout( | |
| 9296 | - () => | |
| 9297 | - reject(new Error( | |
| 9298 | - `step ${JSON.stringify(name)} timed out after ${ms} ms (attempt ${attempt})`, | |
| 9299 | - )), | |
| 9300 | - ms, | |
| 9301 | - ); | |
| 9302 | - promise.then( | |
| 9303 | - (value) => { clearTimeout(timer); resolve(value); }, | |
| 9304 | - (error) => { clearTimeout(timer); reject(error); }, | |
| 9305 | - ); | |
| 9306 | - }); | |
| 9307 | - | |
| 9308 | -// Storage failures belong to the engine even when workflow code catches the | |
| 9309 | -// rejected step promise. Record them outside the Error object, so user code | |
| 9310 | -// cannot suppress a retry or forge one by returning a marked exception. | |
| 9311 | -const __wfTrackStorageFailures = (storage, driver) => { | |
| 9312 | - const tracked = Object.create(storage); | |
| 9313 | - for (const name of ["get", "put", "transactionSync"]) { | |
| 9314 | - Object.defineProperty(tracked, name, { | |
| 9315 | - value(...args) { | |
| 9316 | - try { | |
| 9317 | - const result = storage[name](...args); | |
| 9318 | - if (result !== null && typeof result === "object" && | |
| 9319 | - typeof result.then === "function") { | |
| 9320 | - return result.catch((error) => { | |
| 9321 | - driver.storageFailure ??= error; | |
| 9322 | - throw error; | |
| 9323 | - }); | |
| 9324 | - } | |
| 9325 | - return result; | |
| 9326 | - } catch (error) { | |
| 9327 | - driver.storageFailure ??= error; | |
| 9328 | - throw error; | |
| 9329 | - } | |
| 9330 | - }, | |
| 9331 | - }); | |
| 9332 | - } | |
| 9333 | - return tracked; | |
| 9334 | -}; | |
| 9335 | - | |
| 9336 | -// The WorkflowStep the driver hands to run(). Each method resolves its step | |
| 9337 | -// record by (name, occurrence count) -- the count is assigned synchronously | |
| 9338 | -// at call time, so `Promise.all` of two same-named steps gets deterministic | |
| 9339 | -// distinct keys in call order, and a repeated name in a loop cannot collide. | |
| 9340 | -const __wfMakeStep = (driver) => { | |
| 9341 | - const storage = driver.storage; | |
| 9342 | - // The shared step frame. `body` resolves to {value} or {block: at, kind}; | |
| 9343 | - // a blocked step leaves its promise unsettled forever in this invocation. | |
| 9344 | - // The running counter covers the whole body, ledger reads included, so | |
| 9345 | - // quiescence cannot fire between a step's read and its decision. | |
| 9346 | - const frame = (name, body) => { | |
| 9347 | - // A stale replay -- one whose invocation already suspended -- can wake | |
| 9348 | - // later if user code raced a step against an un-stepped await. It goes | |
| 9349 | - // quiet instead of executing an attempt beside the fresh replay. | |
| 9350 | - if (driver.finished) return __wfNever; | |
| 9351 | - const enclosing = __wfEnclosingStep(); | |
| 9352 | - if (enclosing !== undefined) { | |
| 9353 | - const failure = __wfError( | |
| 9354 | - `step ${JSON.stringify(name)} cannot start inside the callback of ` + | |
| 9355 | - `step ${JSON.stringify(enclosing)}; a step callback must not use ` + | |
| 9356 | - "the step API", | |
| 9357 | - ); | |
| 9358 | - failure.__wfPermanent = true; | |
| 9359 | - return Promise.reject(failure); | |
| 9360 | - } | |
| 9361 | - const count = (driver.counts.get(name) ?? 0) + 1; | |
| 9362 | - driver.counts.set(name, count); | |
| 9363 | - const ordinal = ++driver.ordinal; | |
| 9364 | - const key = driver.ledgerPrefix + `step.${count}.${name}`; | |
| 9365 | - // Step activity restarts the stall clock: a pending grace timer was | |
| 9366 | - // armed against a run() that looked stuck, and this call is progress. | |
| 9367 | - driver.clearStall(); | |
| 9368 | - driver.running += 1; | |
| 9369 | - return new Promise((resolve, reject) => { | |
| 9370 | - (async () => { | |
| 9371 | - const meta = await storage.get("__wf.meta"); | |
| 9372 | - if ( | |
| 9373 | - meta === undefined || meta.generation !== driver.generation || | |
| 9374 | - __wfTerminal(meta.status) || meta.status === "paused" || | |
| 9375 | - meta.status === "waitingForPause" | |
| 9376 | - ) { | |
| 9377 | - return { pause: true }; | |
| 9378 | - } | |
| 9379 | - return await body(key, count, ordinal); | |
| 9380 | - })().then( | |
| 9381 | - (result) => { | |
| 9382 | - driver.running -= 1; | |
| 9383 | - driver.clearStall(); | |
| 9384 | - if (result.pause === true) { | |
| 9385 | - driver.pauseRequested = true; | |
| 9386 | - driver.check(); | |
| 9387 | - return; | |
| 9388 | - } | |
| 9389 | - if (result.block !== undefined) { | |
| 9390 | - if (!driver.finished) { | |
| 9391 | - driver.blocked.push({ at: result.block, kind: result.kind }); | |
| 9392 | - } | |
| 9393 | - driver.check(); | |
| 9394 | - return; | |
| 9395 | - } | |
| 9396 | - driver.check(); | |
| 9397 | - resolve(result.value); | |
| 9398 | - }, | |
| 9399 | - (error) => { | |
| 9400 | - driver.running -= 1; | |
| 9401 | - driver.clearStall(); | |
| 9402 | - driver.check(); | |
| 9403 | - reject(error); | |
| 9404 | - }, | |
| 9405 | - ); | |
| 9406 | - }); | |
| 9407 | - }; | |
| 9408 | - const doStep = (name, configOrCallback, callbackOrRollback, maybeRollback) => { | |
| 9409 | - const hasConfig = typeof configOrCallback !== "function"; | |
| 9410 | - let config = hasConfig ? (configOrCallback ?? {}) : {}; | |
| 9411 | - const callback = hasConfig ? callbackOrRollback : configOrCallback; | |
| 9412 | - const rollback = hasConfig ? maybeRollback : callbackOrRollback; | |
| 9413 | - try { | |
| 9414 | - __wfStepName(name); | |
| 9415 | - config = __wfStepConfig(config, name); | |
| 9416 | - } catch (error) { | |
| 9417 | - return Promise.reject(error); | |
| 9418 | - } | |
| 9419 | - if (rollback !== undefined) { | |
| 9420 | - return Promise.reject(__wfError( | |
| 9421 | - "step rollbackOptions are not implemented in celld; remove the rollback handler", | |
| 9422 | - )); | |
| 9423 | - } | |
| 9424 | - if (config.sensitive !== undefined) { | |
| 9425 | - return Promise.reject(__wfError( | |
| 9426 | - "sensitive step output is not implemented in celld; remove `sensitive`", | |
| 9427 | - )); | |
| 9428 | - } | |
| 9429 | - if (typeof callback !== "function") { | |
| 9430 | - return Promise.reject(__wfError("step.do needs a callback function")); | |
| 9431 | - } | |
| 9432 | - return frame(name, async (key, count, ordinal) => { | |
| 9433 | - const record = __wfKindCheck(await storage.get(key), "do", name); | |
| 9434 | - if (record !== undefined && record.status === "completed") { | |
| 9435 | - return { value: record.value }; | |
| 9436 | - } | |
| 9437 | - if (record !== undefined && record.status === "failed") { | |
| 9438 | - throw __wfReviveError(record.error); | |
| 9439 | - } | |
| 9440 | - // A pending retry whose backoff has not elapsed blocks without | |
| 9441 | - // executing; the deadline was persisted when the attempt failed, so a | |
| 9442 | - // replay cannot reset the backoff. | |
| 9443 | - if (record !== undefined && record.nextAt > Date.now()) { | |
| 9444 | - return { block: record.nextAt, kind: "retry" }; | |
| 9445 | - } | |
| 9446 | - const attempt = (record === undefined ? 0 : record.attempt) + 1; | |
| 9447 | - const historyOrdinal = record?.ordinal ?? ordinal; | |
| 9448 | - const retries = config.retries ?? | |
| 9449 | - { limit: 5, delay: 10000, backoff: "exponential" }; | |
| 9450 | - const timeout = config.timeout ?? "10 minutes"; | |
| 9451 | - const timeoutMs = __wfDuration( | |
| 9452 | - timeout, | |
| 9453 | - `the timeout of step ${JSON.stringify(name)}`, | |
| 9454 | - ); | |
| 9455 | - // Upstream omits a dynamic delay from the step context. Copying the | |
| 9456 | - // config verbatim would expose the callback to itself as retry policy, | |
| 9457 | - // while callers expect only the serializable limit and backoff fields. | |
| 9458 | - const contextRetries = typeof retries.delay === "function" | |
| 9459 | - ? { limit: retries.limit, ...(retries.backoff === undefined | |
| 9460 | - ? {} | |
| 9461 | - : { backoff: retries.backoff }) } | |
| 9462 | - : retries; | |
| 9463 | - const context = { | |
| 9464 | - step: { name, count }, | |
| 9465 | - attempt, | |
| 9466 | - config: { retries: contextRetries, timeout }, | |
| 9467 | - }; | |
| 9468 | - try { | |
| 9469 | - // Persist the history entry before the callback starts. A concurrent | |
| 9470 | - // selected restart can therefore name an in-flight occurrence, and | |
| 9471 | - // its new generation fences the callback's eventual old-ledger write. | |
| 9472 | - await storage.put(key, { | |
| 9473 | - kind: "do", | |
| 9474 | - status: "running", | |
| 9475 | - attempt: attempt - 1, | |
| 9476 | - ordinal: historyOrdinal, | |
| 9477 | - }); | |
| 9478 | - const value = await __wfTimeout( | |
| 9479 | - __wfEnterStep(name, async () => callback(context)), | |
| 9480 | - timeoutMs, | |
| 9481 | - name, | |
| 9482 | - attempt, | |
| 9483 | - ); | |
| 9484 | - if (value !== undefined) { | |
| 9485 | - __wfCheckValue(value, `the return value of step ${JSON.stringify(name)}`); | |
| 9486 | - } | |
| 9487 | - await storage.put(key, { | |
| 9488 | - kind: "do", | |
| 9489 | - status: "completed", | |
| 9490 | - value, | |
| 9491 | - ordinal: historyOrdinal, | |
| 9492 | - }); | |
| 9493 | - return { value }; | |
| 9494 | - } catch (error) { | |
| 9495 | - // NonRetryableError skips retries by contract; a value-cap or | |
| 9496 | - // serialization failure is marked permanent above because another | |
| 9497 | - // attempt returns the same value. | |
| 9498 | - const permanent = error instanceof NonRetryableError || | |
| 9499 | - (error !== null && typeof error === "object" && | |
| 9500 | - (error.name === "NonRetryableError" || error.__wfPermanent === true)) || | |
| 9501 | - attempt > retries.limit; | |
| 9502 | - if (permanent) { | |
| 9503 | - await storage.put(key, { | |
| 9504 | - kind: "do", | |
| 9505 | - status: "failed", | |
| 9506 | - error: __wfErrorRecord(error), | |
| 9507 | - ordinal: historyOrdinal, | |
| 9508 | - }); | |
| 9509 | - throw error; | |
| 9510 | - } | |
| 9511 | - // Upstream documents the backoff names, not the arithmetic; the | |
| 9512 | - // simplest reading is used and recorded in the design page. When | |
| 9513 | - // `retries` is given without `backoff`, celld uses constant -- the | |
| 9514 | - // documented exponential default is the whole-config-omitted case. | |
| 9515 | - const dynamic = typeof retries.delay === "function"; | |
| 9516 | - const delay = dynamic | |
| 9517 | - ? await __wfEnterStep(name, () => retries.delay({ ctx: context, error })) | |
| 9518 | - : retries.delay; | |
| 9519 | - const base = __wfDuration( | |
| 9520 | - delay, | |
| 9521 | - `the retry delay of step ${JSON.stringify(name)}`, | |
| 9522 | - ); | |
| 9523 | - // A delay callback replaces the fixed base duration, not the backoff | |
| 9524 | - // policy. Skipping this factor makes a dynamic exponential or linear | |
| 9525 | - // policy retry earlier than the same policy with a fixed base. | |
| 9526 | - const factor = retries.backoff === "exponential" | |
| 9527 | - ? 2 ** (attempt - 1) | |
| 9528 | - : retries.backoff === "linear" | |
| 9529 | - ? attempt | |
| 9530 | - : 1; | |
| 9531 | - const nextAt = Date.now() + base * factor; | |
| 9532 | - await storage.put(key, { | |
| 9533 | - kind: "do", | |
| 9534 | - status: "retrying", | |
| 9535 | - attempt, | |
| 9536 | - nextAt, | |
| 9537 | - ordinal: historyOrdinal, | |
| 9538 | - }); | |
| 9539 | - return { block: nextAt, kind: "retry" }; | |
| 9540 | - } | |
| 9541 | - }); | |
| 9542 | - }; | |
| 9543 | - const sleepUntilDeadline = (name, key, ordinal, deadline) => (async () => { | |
| 9544 | - const record = __wfKindCheck(await storage.get(key), "sleep", name); | |
| 9545 | - if (record !== undefined && record.status === "completed") { | |
| 9546 | - return { value: undefined }; | |
| 9547 | - } | |
| 9548 | - const historyOrdinal = record?.ordinal ?? ordinal; | |
| 9549 | - let at = record === undefined ? undefined : record.deadline; | |
| 9550 | - if (at === undefined) { | |
| 9551 | - // The absolute deadline is computed once and persisted. Recomputing | |
| 9552 | - // from "now" on replay would extend the sleep by however long the | |
| 9553 | - // instance was down, so a crash could postpone a deadline forever. | |
| 9554 | - at = deadline(); | |
| 9555 | - if (at - Date.now() > __WF_MAX_WAIT_MS) { | |
| 9556 | - throw __wfError( | |
| 9557 | - `sleep ${JSON.stringify(name)} ends ${at - Date.now()} ms from now, ` + | |
| 9558 | - "above the upstream limit of 365 days", | |
| 9559 | - ); | |
| 9560 | - } | |
| 9561 | - await storage.put(key, { | |
| 9562 | - kind: "sleep", | |
| 9563 | - status: "sleeping", | |
| 9564 | - deadline: at, | |
| 9565 | - ordinal: historyOrdinal, | |
| 9566 | - }); | |
| 9567 | - } | |
| 9568 | - if (at <= Date.now()) { | |
| 9569 | - await storage.put(key, { | |
| 9570 | - kind: "sleep", | |
| 9571 | - status: "completed", | |
| 9572 | - ordinal: historyOrdinal, | |
| 9573 | - }); | |
| 9574 | - return { value: undefined }; | |
| 9575 | - } | |
| 9576 | - return { block: at, kind: "sleep" }; | |
| 9577 | - })(); | |
| 9578 | - return { | |
| 9579 | - do: doStep, | |
| 9580 | - sleep: (name, duration) => { | |
| 9581 | - let durationMs; | |
| 9582 | - try { | |
| 9583 | - __wfStepName(name); | |
| 9584 | - durationMs = __wfSleepDuration(duration, name); | |
| 9585 | - } catch (error) { | |
| 9586 | - return Promise.reject(error); | |
| 9587 | - } | |
| 9588 | - return frame(name, (key, _count, ordinal) => | |
| 9589 | - sleepUntilDeadline( | |
| 9590 | - name, | |
| 9591 | - key, | |
| 9592 | - ordinal, | |
| 9593 | - () => Date.now() + durationMs, | |
| 9594 | - )); | |
| 9595 | - }, | |
| 9596 | - sleepUntil: (name, timestamp) => { | |
| 9597 | - let at; | |
| 9598 | - try { | |
| 9599 | - __wfStepName(name); | |
| 9600 | - at = __wfSleepUntil(timestamp, name); | |
| 9601 | - } catch (error) { | |
| 9602 | - return Promise.reject(error); | |
| 9603 | - } | |
| 9604 | - return frame(name, (key, _count, ordinal) => | |
| 9605 | - sleepUntilDeadline(name, key, ordinal, () => { | |
| 9606 | - // A replay uses the persisted deadline after it has passed. Check | |
| 9607 | - // the moving future bound only while the deadline is first installed, | |
| 9608 | - // or every successful sleep would fail on the resume that completes it. | |
| 9609 | - if (at - Date.now() < 0) { | |
| 9610 | - throw __wfError( | |
| 9611 | - `sleepUntil ${JSON.stringify(name)} needs a future timestamp`, | |
| 9612 | - ); | |
| 9613 | - } | |
| 9614 | - return at; | |
| 9615 | - })); | |
| 9616 | - }, | |
| 9617 | - waitForEvent: (name, options) => { | |
| 9618 | - let checked; | |
| 9619 | - try { | |
| 9620 | - __wfStepName(name); | |
| 9621 | - checked = __wfWaitOptions(options, name); | |
| 9622 | - } catch (error) { | |
| 9623 | - return Promise.reject(error); | |
| 9624 | - } | |
| 9625 | - return frame(name, async (key, _count, ordinal) => { | |
| 9626 | - let record = __wfKindCheck(await storage.get(key), "event", name); | |
| 9627 | - if (record !== undefined && record.status === "completed") { | |
| 9628 | - return { value: record.value }; | |
| 9629 | - } | |
| 9630 | - if (record !== undefined && record.status === "failed") { | |
| 9631 | - throw __wfReviveError(record.error); | |
| 9632 | - } | |
| 9633 | - if (record === undefined) { | |
| 9634 | - record = { | |
| 9635 | - kind: "event", | |
| 9636 | - status: "waiting", | |
| 9637 | - type: checked.type, | |
| 9638 | - deadline: Date.now() + checked.timeoutMs, | |
| 9639 | - ordinal, | |
| 9640 | - }; | |
| 9641 | - await storage.put(key, record); | |
| 9642 | - } | |
| 9643 | - // The deadline is checked before the buffer: an event that arrived | |
| 9644 | - // after the persisted deadline must time the step out, not succeed | |
| 9645 | - // because the replay that noticed it ran late. | |
| 9646 | - if (record.deadline <= Date.now()) { | |
| 9647 | - const error = new Error( | |
| 9648 | - `waitForEvent ${JSON.stringify(name)} timed out waiting for an event ` + | |
| 9649 | - `of type ${JSON.stringify(record.type)}`, | |
| 9650 | - ); | |
| 9651 | - await storage.put(key, { | |
| 9652 | - kind: "event", | |
| 9653 | - status: "failed", | |
| 9654 | - error: __wfErrorRecord(error), | |
| 9655 | - ordinal: record.ordinal, | |
| 9656 | - }); | |
| 9657 | - throw error; | |
| 9658 | - } | |
| 9659 | - // Delivered events persist until a matching step consumes one, in | |
| 9660 | - // arrival order -- the zero-padded sequence key makes list order | |
| 9661 | - // arrival order -- so an event sent before the step is reached is | |
| 9662 | - // buffered, not lost. | |
| 9663 | - const consumed = storage.transactionSync((transaction) => { | |
| 9664 | - const current = __wfKindCheck(transaction.kv.get(key), "event", name); | |
| 9665 | - if (current !== undefined && current.status === "completed") { | |
| 9666 | - return { value: current.value }; | |
| 9667 | - } | |
| 9668 | - if (current !== undefined && current.status === "failed") { | |
| 9669 | - throw __wfReviveError(current.error); | |
| 9670 | - } | |
| 9671 | - for (const [eventKey, event] of transaction.kv.list({ | |
| 9672 | - prefix: __wfEventPrefix(driver.generation), | |
| 9673 | - })) { | |
| 9674 | - if (event.type !== current.type) continue; | |
| 9675 | - const value = { | |
| 9676 | - payload: event.payload, | |
| 9677 | - timestamp: new Date(event.timestampMs), | |
| 9678 | - type: event.type, | |
| 9679 | - }; | |
| 9680 | - // The delete and completed ledger record are one SQLite commit. | |
| 9681 | - // A crash can therefore expose both or neither, so an | |
| 9682 | - // acknowledged event cannot disappear between them. | |
| 9683 | - transaction.kv.delete(eventKey); | |
| 9684 | - /*__CELLD_TEST_WORKFLOW_EVENT_CONSUMED__*/ | |
| 9685 | - transaction.kv.put(key, { | |
| 9686 | - kind: "event", | |
| 9687 | - status: "completed", | |
| 9688 | - value, | |
| 9689 | - ordinal: current.ordinal, | |
| 9690 | - }); | |
| 9691 | - return { value }; | |
| 9692 | - } | |
| 9693 | - }); | |
| 9694 | - if (consumed !== undefined) return consumed; | |
| 9695 | - return { block: record.deadline, kind: "event" }; | |
| 9696 | - }); | |
| 9697 | - }, | |
| 9698 | - }; | |
| 9699 | -}; | |
| 9700 | - | |
| 9701 | -const __WorkflowCell = (() => { | |
| 9702 | - class StorageTransaction { | |
| 9703 | - constructor(storage, transaction) { | |
| 9704 | - this.kv = transaction.kv; | |
| 9705 | - this._scope = storage._scope; | |
| 9706 | - } | |
| 9707 | - setAlarm(t) { | |
| 9708 | - __alarm_set(this._scope, t instanceof Date ? t.getTime() : Number(t)); | |
| 9709 | - } | |
| 9710 | - deleteAlarm() { | |
| 9711 | - __alarm_delete(this._scope); | |
| 9712 | - } | |
| 9713 | - } | |
| 9714 | - const transactionSync = (storage, callback) => | |
| 9715 | - storage.transactionSync((transaction) => | |
| 9716 | - callback(new StorageTransaction(storage, transaction)) | |
| 9717 | - ); | |
| 9718 | - const clearInstance = (transaction) => { | |
| 9719 | - for (const [key] of transaction.kv.list({ prefix: "__wf." })) { | |
| 9720 | - transaction.kv.delete(key); | |
| 9721 | - } | |
| 9722 | - transaction.deleteAlarm(); | |
| 9723 | - }; | |
| 9724 | - const expireTerminal = (transaction, meta, now) => { | |
| 9725 | - if (!__wfTerminal(meta.status)) return false; | |
| 9726 | - if (meta.expiresMs === undefined) { | |
| 9727 | - meta.endedMs = now; | |
| 9728 | - meta.expiresMs = now + __wfRetentionMs(meta, meta.status); | |
| 9729 | - transaction.kv.put("__wf.meta", meta); | |
| 9730 | - } | |
| 9731 | - if (meta.expiresMs > now) return false; | |
| 9732 | - clearInstance(transaction); | |
| 9733 | - return true; | |
| 9734 | - }; | |
| 9735 | - | |
| 9736 | - // The adapter stays in this closure because Workflow needs synchronous | |
| 9737 | - // alarm writes inside transactionSync(). The public async alarm API runs | |
| 9738 | - // after that commit, while a global helper would let application code | |
| 9739 | - // split metadata from its wake or invoke the raw operation after commit. | |
| 9740 | - return class __WorkflowCell { | |
| 9741 | - constructor(state) { | |
| 9742 | - this._state = state; | |
| 9743 | - } | |
| 9744 | - async __wfCreate({ | |
| 9745 | - workflowName, | |
| 9746 | - instanceId, | |
| 9747 | - params, | |
| 9748 | - retention, | |
| 9749 | - locationHint, | |
| 9750 | - skipExisting = false, | |
| 9751 | - }) { | |
| 9752 | - const storage = this._state.storage; | |
| 9753 | - if (params !== undefined) __wfCheckValue(params, "the workflow params"); | |
| 9754 | - const result = transactionSync(storage, (transaction) => { | |
| 9755 | - let meta = transaction.kv.get("__wf.meta"); | |
| 9756 | - if (meta !== undefined && expireTerminal(transaction, meta, Date.now())) { | |
| 9757 | - meta = undefined; | |
| 9758 | - } | |
| 9759 | - if (meta !== undefined && skipExisting) return { id: instanceId, created: false }; | |
| 9760 | - if (meta !== undefined) { | |
| 9761 | - throw __wfError( | |
| 9762 | - `instance ${JSON.stringify(instanceId)} already exists with status ` + | |
| 9763 | - JSON.stringify(meta.status), | |
| 9764 | - ); | |
| 9765 | - } | |
| 9766 | - const generation = crypto.randomUUID(); | |
| 9767 | - transaction.kv.put("__wf.meta", { | |
| 9768 | - workflowName, | |
| 9769 | - instanceId, | |
| 9770 | - params, | |
| 9771 | - retention, | |
| 9772 | - ...(locationHint === undefined ? {} : { locationHint }), | |
| 9773 | - generation, | |
| 9774 | - createdMs: Date.now(), | |
| 9775 | - status: "queued", | |
| 9776 | - }); | |
| 9777 | - // The metadata and alarm are one SQLite commit. A committed creation | |
| 9778 | - // therefore always has the wake that can start or recover its drive. | |
| 9779 | - transaction.setAlarm(Date.now()); | |
| 9780 | - /*__CELLD_TEST_WORKFLOW_META_CREATED__*/ | |
| 9781 | - return { id: instanceId, created: true }; | |
| 9782 | - }); | |
| 9783 | - return result; | |
| 9784 | - } | |
| 9785 | - async __wfStatus() { | |
| 9786 | - const meta = transactionSync(this._state.storage, (transaction) => { | |
| 9787 | - const current = transaction.kv.get("__wf.meta"); | |
| 9788 | - if (current === undefined) return undefined; | |
| 9789 | - return expireTerminal(transaction, current, Date.now()) ? undefined : current; | |
| 9790 | - }); | |
| 9791 | - // A cell exists on first address like any cell, so an absent ledger is | |
| 9792 | - // the only honest "no such instance" signal. Inventing an instance here | |
| 9793 | - // would turn every typo into an empty workflow. | |
| 9794 | - if (meta === undefined) throw __wfError("instance does not exist"); | |
| 9795 | - const status = { status: meta.status, rollback: null }; | |
| 9796 | - if (meta.error !== undefined) status.error = meta.error; | |
| 9797 | - if (meta.output !== undefined) status.output = meta.output; | |
| 9798 | - return status; | |
| 9799 | - } | |
| 9800 | - async __wfDelete() { | |
| 9801 | - const storage = this._state.storage; | |
| 9802 | - const deleted = transactionSync(storage, (transaction) => { | |
| 9803 | - const meta = transaction.kv.get("__wf.meta"); | |
| 9804 | - if (meta === undefined) return false; | |
| 9805 | - if (expireTerminal(transaction, meta, Date.now())) return false; | |
| 9806 | - clearInstance(transaction); | |
| 9807 | - return true; | |
| 9808 | - }); | |
| 9809 | - // Throw after the transaction commits. An expiry discovered here must | |
| 9810 | - // keep its cleanup even though delete() reports that the instance is gone. | |
| 9811 | - if (!deleted) throw __wfError("instance does not exist"); | |
| 9812 | - // A callback can still be awaiting application I/O when deletion lands. | |
| 9813 | - // Reset the object after the deletion commit so that callback cannot | |
| 9814 | - // recreate an old-generation ledger entry after delete() reports success. | |
| 9815 | - this._state.abort(new Error("WORKFLOW_INSTANCE_DELETED")); | |
| 9816 | - } | |
| 9817 | - async __wfPause() { | |
| 9818 | - const storage = this._state.storage; | |
| 9819 | - transactionSync(storage, (transaction) => { | |
| 9820 | - const meta = transaction.kv.get("__wf.meta"); | |
| 9821 | - if (meta === undefined) throw __wfError("instance does not exist"); | |
| 9822 | - if (__wfTerminal(meta.status) || meta.status === "paused" || | |
| 9823 | - meta.status === "waitingForPause") return; | |
| 9824 | - if (meta.status === "running") { | |
| 9825 | - meta.status = "waitingForPause"; | |
| 9826 | - // A drive lost after this commit must re-enter and finish the pause. | |
| 9827 | - transaction.setAlarm(Date.now()); | |
| 9828 | - } else { | |
| 9829 | - meta.status = "paused"; | |
| 9830 | - meta.pausedMs = Date.now(); | |
| 9831 | - transaction.deleteAlarm(); | |
| 9832 | - } | |
| 9833 | - transaction.kv.put("__wf.meta", meta); | |
| 9834 | - }); | |
| 9835 | - } | |
| 9836 | - async __wfResume() { | |
| 9837 | - const storage = this._state.storage; | |
| 9838 | - transactionSync(storage, (transaction) => { | |
| 9839 | - const meta = transaction.kv.get("__wf.meta"); | |
| 9840 | - if (meta === undefined) throw __wfError("instance does not exist"); | |
| 9841 | - if (meta.status === "waitingForPause") { | |
| 9842 | - meta.status = "running"; | |
| 9843 | - transaction.kv.put("__wf.meta", meta); | |
| 9844 | - transaction.setAlarm(Date.now()); | |
| 9845 | - return; | |
| 9846 | - } | |
| 9847 | - if (meta.status !== "paused") { | |
| 9848 | - throw __wfError( | |
| 9849 | - `cannot resume an instance with status ${JSON.stringify(meta.status)}`, | |
| 9850 | - ); | |
| 9851 | - } | |
| 9852 | - const offset = Math.max(0, Date.now() - (meta.pausedMs ?? Date.now())); | |
| 9853 | - for (const [key, record] of transaction.kv.list({ | |
| 9854 | - prefix: __wfLedgerPrefix(meta.generation) + "step.", | |
| 9855 | - })) { | |
| 9856 | - if (record.status === "retrying") record.nextAt += offset; | |
| 9857 | - if (record.status === "sleeping" || record.status === "waiting") { | |
| 9858 | - record.deadline += offset; | |
| 9859 | - } | |
| 9860 | - transaction.kv.put(key, record); | |
| 9861 | - } | |
| 9862 | - delete meta.pausedMs; | |
| 9863 | - meta.status = "queued"; | |
| 9864 | - transaction.kv.put("__wf.meta", meta); | |
| 9865 | - transaction.setAlarm(Date.now()); | |
| 9866 | - }); | |
| 9867 | - } | |
| 9868 | - async __wfRestart(options) { | |
| 9869 | - const checked = __wfRestartOptions(options); | |
| 9870 | - const storage = this._state.storage; | |
| 9871 | - transactionSync(storage, (transaction) => { | |
| 9872 | - const meta = transaction.kv.get("__wf.meta"); | |
| 9873 | - if (meta === undefined) throw __wfError("instance does not exist"); | |
| 9874 | - const oldPrefix = __wfLedgerPrefix(meta.generation); | |
| 9875 | - let targetOrdinal; | |
| 9876 | - if (checked.from !== undefined) { | |
| 9877 | - const expectedKind = checked.from.type === "waitForEvent" | |
| 9878 | - ? "event" | |
| 9879 | - : checked.from.type; | |
| 9880 | - let occurrence = 0; | |
| 9881 | - const history = [...transaction.kv.list({ prefix: oldPrefix + "step." })] | |
| 9882 | - .filter(([, record]) => Number.isInteger(record.ordinal)) | |
| 9883 | - .sort((left, right) => left[1].ordinal - right[1].ordinal); | |
| 9884 | - // The ledger key is `<prefix>step.<per-name-count>.<name>`. Derive | |
| 9885 | - // the name from it because a record stores replay state, not identity. | |
| 9886 | - for (const [key, record] of history) { | |
| 9887 | - const marker = oldPrefix + "step."; | |
| 9888 | - const suffix = key.slice(marker.length); | |
| 9889 | - const dot = suffix.indexOf("."); | |
| 9890 | - const name = dot < 0 ? "" : suffix.slice(dot + 1); | |
| 9891 | - if (record.kind !== expectedKind || name !== checked.from.name) continue; | |
| 9892 | - occurrence += 1; | |
| 9893 | - if (occurrence === checked.from.count) { | |
| 9894 | - targetOrdinal = record.ordinal; | |
| 9895 | - break; | |
| 9896 | - } | |
| 9897 | - } | |
| 9898 | - if (targetOrdinal === undefined) { | |
| 9899 | - throw __wfError( | |
| 9900 | - `restart() could not find ${checked.from.type} step ` + | |
| 9901 | - `${JSON.stringify(checked.from.name)} occurrence ${checked.from.count}`, | |
| 9902 | - ); | |
| 9903 | - } | |
| 9904 | - } | |
| 9905 | - const generation = crypto.randomUUID(); | |
| 9906 | - const newPrefix = __wfLedgerPrefix(generation); | |
| 9907 | - if (targetOrdinal !== undefined) { | |
| 9908 | - for (const [key, record] of transaction.kv.list({ prefix: oldPrefix + "step." })) { | |
| 9909 | - if (Number.isInteger(record.ordinal) && record.ordinal < targetOrdinal) { | |
| 9910 | - transaction.kv.put(newPrefix + key.slice(oldPrefix.length), record); | |
| 9911 | - } | |
| 9912 | - } | |
| 9913 | - } | |
| 9914 | - for (const [key] of transaction.kv.list({ prefix: oldPrefix })) { | |
| 9915 | - transaction.kv.delete(key); | |
| 9916 | - } | |
| 9917 | - meta.generation = generation; | |
| 9918 | - meta.status = "queued"; | |
| 9919 | - delete meta.pausedMs; | |
| 9920 | - delete meta.output; | |
| 9921 | - delete meta.error; | |
| 9922 | - transaction.kv.put("__wf.meta", meta); | |
| 9923 | - transaction.setAlarm(Date.now()); | |
| 9924 | - }); | |
| 9925 | - } | |
| 9926 | - async __wfTerminate() { | |
| 9927 | - const storage = this._state.storage; | |
| 9928 | - transactionSync(storage, (transaction) => { | |
| 9929 | - const meta = transaction.kv.get("__wf.meta"); | |
| 9930 | - if (meta === undefined) throw __wfError("instance does not exist"); | |
| 9931 | - if (__wfTerminal(meta.status)) { | |
| 9932 | - throw __wfError( | |
| 9933 | - `cannot terminate an instance with status ${JSON.stringify(meta.status)}`, | |
| 9934 | - ); | |
| 9935 | - } | |
| 9936 | - meta.status = "terminated"; | |
| 9937 | - __wfFinishRetention(meta, transaction); | |
| 9938 | - transaction.kv.put("__wf.meta", meta); | |
| 9939 | - /*__CELLD_TEST_WORKFLOW_TERMINAL_ALARM_SET__*/ | |
| 9940 | - }); | |
| 9941 | - } | |
| 9942 | - async __wfSendEvent(options) { | |
| 9943 | - const storage = this._state.storage; | |
| 9944 | - // The binding validates first to avoid an unnecessary cell call. Repeat | |
| 9945 | - // the check here because this RPC owns the durable event invariant: no | |
| 9946 | - // current or future internal caller can bypass validation before storage. | |
| 9947 | - const { type, payload } = __wfEventOptions(options); | |
| 9948 | - transactionSync(storage, (transaction) => { | |
| 9949 | - const meta = transaction.kv.get("__wf.meta"); | |
| 9950 | - if (meta === undefined) throw __wfError("instance does not exist"); | |
| 9951 | - if (__wfTerminal(meta.status)) { | |
| 9952 | - throw __wfError( | |
| 9953 | - `cannot send an event to an instance with status ${JSON.stringify(meta.status)}`, | |
| 9954 | - ); | |
| 9955 | - } | |
| 9956 | - const sequenceKey = __wfLedgerPrefix(meta.generation) + "eventSeq"; | |
| 9957 | - const sequence = transaction.kv.get(sequenceKey) ?? 0; | |
| 9958 | - transaction.kv.put(sequenceKey, sequence + 1); | |
| 9959 | - transaction.kv.put(__wfEventKey(meta.generation, sequence), { | |
| 9960 | - type, | |
| 9961 | - payload, | |
| 9962 | - timestampMs: Date.now(), | |
| 9963 | - }); | |
| 9964 | - // Allocation, the event body, and the nudge are one commit. Parallel | |
| 9965 | - // writers cannot reuse a sequence and a crash cannot expose a partial | |
| 9966 | - // acknowledged send. | |
| 9967 | - if (meta.status !== "paused" && meta.status !== "waitingForPause") { | |
| 9968 | - transaction.setAlarm(Date.now()); | |
| 9969 | - } | |
| 9970 | - }); | |
| 9971 | - } | |
| 9972 | - async alarm() { | |
| 9973 | - const storage = this._state.storage; | |
| 9974 | - // One drive at a time. A sendEvent nudge (setAlarm(now)) landing | |
| 9975 | - // mid-fire replaces the firing alarm in the core, and the replacement | |
| 9976 | - // can dispatch a second alarm() into this isolate while the first drive | |
| 9977 | - // still awaits user code. Two concurrent replays would both see the | |
| 9978 | - // same incomplete steps and double-execute their callbacks. The guard | |
| 9979 | - // is isolate-local and that is sufficient: every drive for a cell runs | |
| 9980 | - // in its owner's isolate, and a takeover starts a fresh isolate with no | |
| 9981 | - // drive in flight. The nudge is not lost -- the in-flight drive folds | |
| 9982 | - // `_wfNudge` into the minimum it re-arms, and if it suspended before | |
| 9983 | - // seeing the flag, the re-arm below starts a fresh drive immediately. | |
| 9984 | - // A failed drive is not re-raised here: the engine already retries the | |
| 9985 | - // alarm that fired it. | |
| 9986 | - if (this._wfDriving !== undefined) { | |
| 9987 | - this._wfNudge = Date.now(); | |
| 9988 | - await this._wfDriving.catch(() => {}); | |
| 9989 | - if (this._wfNudge !== undefined) { | |
| 9990 | - this._wfNudge = undefined; | |
| 9991 | - const meta = await storage.get("__wf.meta"); | |
| 9992 | - if ( | |
| 9993 | - meta !== undefined && !__wfTerminal(meta.status) && | |
| 9994 | - meta.status !== "paused" && meta.status !== "waitingForPause" | |
| 9995 | - ) { | |
| 9996 | - await storage.setAlarm(Date.now()); | |
| 9997 | - } | |
| 9998 | - } | |
| 9999 | - return; | |
| 10000 | - } | |
| 10001 | - const meta = await storage.get("__wf.meta"); | |
| 10002 | - // A terminal instance's pending alarm can still fire. It owns retention: | |
| 10003 | - // remove expired state, or restore the expiry wake after a stale nudge. | |
| 10004 | - if (meta === undefined) { | |
| 10005 | - await storage.deleteAlarm(); | |
| 10006 | - return; | |
| 10007 | - } | |
| 10008 | - if (__wfTerminal(meta.status)) { | |
| 10009 | - transactionSync(storage, (transaction) => { | |
| 10010 | - const current = transaction.kv.get("__wf.meta"); | |
| 10011 | - if (current === undefined) { | |
| 10012 | - transaction.deleteAlarm(); | |
| 10013 | - return; | |
| 10014 | - } | |
| 10015 | - if (!expireTerminal(transaction, current, Date.now())) { | |
| 10016 | - transaction.setAlarm(current.expiresMs); | |
| 10017 | - } | |
| 10018 | - }); | |
| 10019 | - return; | |
| 10020 | - } | |
| 10021 | - if (meta.status === "paused") { | |
| 10022 | - await storage.deleteAlarm(); | |
| 10023 | - return; | |
| 10024 | - } | |
| 10025 | - if (meta.status === "waitingForPause") { | |
| 10026 | - transactionSync(storage, (transaction) => { | |
| 10027 | - const current = transaction.kv.get("__wf.meta"); | |
| 10028 | - if (current === undefined || current.generation !== meta.generation || | |
| 10029 | - current.status !== "waitingForPause") return; | |
| 10030 | - current.status = "paused"; | |
| 10031 | - current.pausedMs = Date.now(); | |
| 10032 | - transaction.kv.put("__wf.meta", current); | |
| 10033 | - transaction.deleteAlarm(); | |
| 10034 | - }); | |
| 10035 | - return; | |
| 10036 | - } | |
| 10037 | - // The fired alarm stays armed while the drive runs. The engine consumes | |
| 10038 | - // it only when this handler returns cleanly, and retries it when the | |
| 10039 | - // handler fails -- that retry is the crash safety net. Deleting it here | |
| 10040 | - // would commit the deletion durably mid-drive (durability is per SQLite | |
| 10041 | - // commit, and replication ships frames per commit), so a SIGKILL before | |
| 10042 | - // the suspend-time re-arm would strand a "running" instance with no | |
| 10043 | - // alarm and no wake entry. The suspend path re-arms explicitly, and a | |
| 10044 | - // terminal drive deletes. | |
| 10045 | - const driving = this._drive(meta); | |
| 10046 | - this._wfDriving = driving; | |
| 10047 | - try { | |
| 10048 | - await driving; | |
| 10049 | - } finally { | |
| 10050 | - this._wfDriving = undefined; | |
| 10051 | - } | |
| 10052 | - } | |
| 10053 | - async _drive(meta) { | |
| 10054 | - const storage = this._state.storage; | |
| 10055 | - // The drive owns `status`, `output`, and `error`; every other piece of | |
| 10056 | - // instance state belongs to the RPCs (sendEvent's sequence lives in its | |
| 10057 | - // own key for the same reason). The gate is open at every await, so a | |
| 10058 | - // terminate can land mid-drive: re-reading before each write, and | |
| 10059 | - // writing nothing once the status is terminal, is what makes "terminate | |
| 10060 | - // wins the race" true rather than asserted. Writing back the meta this | |
| 10061 | - // drive entered with would resurrect a terminated instance as "waiting" | |
| 10062 | - // and re-arm the alarm its terminate deleted. | |
| 10063 | - const settle = (mutate) => transactionSync(storage, (transaction) => { | |
| 10064 | - const current = transaction.kv.get("__wf.meta"); | |
| 10065 | - if (current === undefined || __wfTerminal(current.status) || | |
| 10066 | - current.generation !== meta.generation) return false; | |
| 10067 | - mutate(current, transaction); | |
| 10068 | - transaction.kv.put("__wf.meta", current); | |
| 10069 | - return true; | |
| 10070 | - }); | |
| 10071 | - const className = __cell.workflows[meta.workflowName]; | |
| 10072 | - const cls = className === undefined ? undefined : __cf.exports[className]; | |
| 10073 | - if (typeof cls !== "function" || | |
| 10074 | - typeof (cls.prototype && cls.prototype.run) !== "function") { | |
| 10075 | - // Deploy cannot see inside the bundle, so a missing export fails | |
| 10076 | - // here, loudly, with the class and the config key named. | |
| 10077 | - settle((current, transaction) => { | |
| 10078 | - current.status = "errored"; | |
| 10079 | - current.error = { | |
| 10080 | - name: "Error", | |
| 10081 | - message: className === undefined | |
| 10082 | - ? `workflow ${JSON.stringify(meta.workflowName)} is not declared ` + | |
| 10083 | - "in this deployment's `workflows`" | |
| 10084 | - : `workflow class ${JSON.stringify(className)} is not a module ` + | |
| 10085 | - "export with a run() method; export it and extend " + | |
| 10086 | - "WorkflowEntrypoint", | |
| 10087 | - }; | |
| 10088 | - __wfFinishRetention(current, transaction); | |
| 10089 | - /*__CELLD_TEST_WORKFLOW_TERMINAL_ALARM_SET__*/ | |
| 10090 | - }); | |
| 10091 | - return; | |
| 10092 | - } | |
| 10093 | - const driver = { | |
| 10094 | - storage: undefined, | |
| 10095 | - storageFailure: undefined, | |
| 10096 | - generation: meta.generation, | |
| 10097 | - ledgerPrefix: __wfLedgerPrefix(meta.generation), | |
| 10098 | - counts: new Map(), | |
| 10099 | - ordinal: 0, | |
| 10100 | - running: 0, | |
| 10101 | - blocked: [], | |
| 10102 | - pauseRequested: false, | |
| 10103 | - finished: false, | |
| 10104 | - checkQueued: false, | |
| 10105 | - stallTimer: undefined, | |
| 10106 | - clearStall() { | |
| 10107 | - if (this.stallTimer !== undefined) { | |
| 10108 | - clearTimeout(this.stallTimer); | |
| 10109 | - this.stallTimer = undefined; | |
| 10110 | - } | |
| 10111 | - }, | |
| 10112 | - }; | |
| 10113 | - driver.storage = __wfTrackStorageFailures(storage, driver); | |
| 10114 | - const outcome = new Promise((resolve) => { | |
| 10115 | - driver.finish = (result) => { | |
| 10116 | - if (driver.finished) return; | |
| 10117 | - driver.finished = true; | |
| 10118 | - driver.clearStall(); | |
| 10119 | - resolve(result); | |
| 10120 | - }; | |
| 10121 | - }); | |
| 10122 | - // Quiescence: when a step is blocked, no step callback is executing, | |
| 10123 | - // and a macrotask has passed, nothing can progress, so the invocation | |
| 10124 | - // suspends. The macrotask lets every microtask chain a completed step | |
| 10125 | - // unblocked drain first; checking on the spot would suspend an instance | |
| 10126 | - // whose next step is one `await` away from starting. | |
| 10127 | - driver.check = () => { | |
| 10128 | - if (driver.checkQueued || driver.finished) return; | |
| 10129 | - driver.checkQueued = true; | |
| 10130 | - setTimeout(() => { | |
| 10131 | - driver.checkQueued = false; | |
| 10132 | - if (driver.finished || driver.running !== 0) return; | |
| 10133 | - if (driver.pauseRequested) { | |
| 10134 | - driver.finish({ kind: "pause" }); | |
| 10135 | - return; | |
| 10136 | - } | |
| 10137 | - if (driver.blocked.length > 0) { | |
| 10138 | - driver.finish({ kind: "suspend" }); | |
| 10139 | - return; | |
| 10140 | - } | |
| 10141 | - // No step runs, none is blocked, and run() has not settled: it | |
| 10142 | - // awaits something that is not a step. Upstream permits that -- an | |
| 10143 | - // un-stepped `await fetch()` between steps is legal, merely | |
| 10144 | - // non-durable -- so this is not yet an error; but a promise that | |
| 10145 | - // never settles would wedge the alarm handler in silence, with the | |
| 10146 | - // instance "running" forever. A grace timer splits the two: if the | |
| 10147 | - // same nothing-can-progress state still holds when it fires, the | |
| 10148 | - // instance fails loudly. The timer is a plain in-isolate timeout, | |
| 10149 | - // not a durable alarm, on purpose: an eviction or a restart replays | |
| 10150 | - // run() from the top anyway, so losing the timer loses nothing -- | |
| 10151 | - // the replay re-enters the same stall and re-arms its own grace. | |
| 10152 | - if (driver.stallTimer !== undefined) return; | |
| 10153 | - driver.stallTimer = setTimeout(() => { | |
| 10154 | - driver.stallTimer = undefined; | |
| 10155 | - if (driver.finished || driver.running !== 0 || driver.blocked.length > 0) { | |
| 10156 | - return; | |
| 10157 | - } | |
| 10158 | - driver.finish({ | |
| 10159 | - kind: "error", | |
| 10160 | - error: __wfError( | |
| 10161 | - "run() has been awaiting something that is not a step for " + | |
| 10162 | - (__WF_STALL_GRACE_MS / 1000) + " seconds while no step is " + | |
| 10163 | - "running or blocked; a replay cannot resume this wait, so " + | |
| 10164 | - "wrap long async work in step.do", | |
| 10165 | - ), | |
| 10166 | - }); | |
| 10167 | - }, __WF_STALL_GRACE_MS); | |
| 10168 | - }, 0); | |
| 10169 | - }; | |
| 10170 | - if ( | |
| 10171 | - meta.status !== "running" && | |
| 10172 | - !(await settle((current) => { | |
| 10173 | - current.status = "running"; | |
| 10174 | - })) | |
| 10175 | - ) { | |
| 10176 | - return; | |
| 10177 | - } | |
| 10178 | - const step = __wfMakeStep(driver); | |
| 10179 | - const event = { | |
| 10180 | - payload: meta.params, | |
| 10181 | - timestamp: new Date(meta.createdMs), | |
| 10182 | - instanceId: meta.instanceId, | |
| 10183 | - workflowName: meta.workflowName, | |
| 10184 | - }; | |
| 10185 | - // ExecutionContext-shaped, as the WorkflowEntrypoint constructor | |
| 10186 | - // documents upstream. | |
| 10187 | - const ctx = { | |
| 10188 | - waitUntil: __registerWaitUntil, | |
| 10189 | - passThroughOnException() {}, | |
| 10190 | - }; | |
| 10191 | - (async () => new cls(ctx, __cell.env).run(event, step))().then( | |
| 10192 | - (value) => driver.finish({ kind: "complete", value }), | |
| 10193 | - (error) => driver.finish({ kind: "error", error }), | |
| 10194 | - ); | |
| 10195 | - /*__CELLD_TEST_WORKFLOW_AFTER_RUN_STARTED__*/ | |
| 10196 | - let result = await outcome; | |
| 10197 | - // The workflow can catch a rejected step promise, but it cannot turn an | |
| 10198 | - // engine storage failure into a successful run. Preserve the alarm so | |
| 10199 | - // the runtime retries over the last committed ledger prefix. | |
| 10200 | - if (driver.storageFailure !== undefined) { | |
| 10201 | - throw driver.storageFailure; | |
| 10202 | - } | |
| 10203 | - const currentMeta = await storage.get("__wf.meta"); | |
| 10204 | - if ( | |
| 10205 | - result.kind === "pause" || | |
| 10206 | - (currentMeta !== undefined && | |
| 10207 | - currentMeta.generation === meta.generation && | |
| 10208 | - currentMeta.status === "waitingForPause") | |
| 10209 | - ) { | |
| 10210 | - /*__CELLD_TEST_WORKFLOW_BEFORE_PAUSE_SETTLE__*/ | |
| 10211 | - settle((current, transaction) => { | |
| 10212 | - // A resume can cancel waitingForPause after this drive selected its | |
| 10213 | - // pause result. Preserve that newer running state and its alarm, or | |
| 10214 | - // this stale settlement strands an acknowledged resume as paused. | |
| 10215 | - if (current.status !== "waitingForPause") return; | |
| 10216 | - current.status = "paused"; | |
| 10217 | - current.pausedMs = Date.now(); | |
| 10218 | - transaction.deleteAlarm(); | |
| 10219 | - }); | |
| 10220 | - return; | |
| 10221 | - } | |
| 10222 | - if (result.kind === "suspend") { | |
| 10223 | - let at = Math.min(...driver.blocked.map((entry) => entry.at)); | |
| 10224 | - // A nudge that landed mid-drive must not wait out the pending | |
| 10225 | - // deadline. It is visible in one of two places: getAlarm(), when the | |
| 10226 | - // nudge re-armed and no second alarm dispatched yet, or `_wfNudge`, | |
| 10227 | - // when a second alarm() already entered and parked on the drive | |
| 10228 | - // guard -- its dispatch consumed the armed alarm, so getAlarm() | |
| 10229 | - // alone would miss it. | |
| 10230 | - const nudge = await storage.getAlarm(); | |
| 10231 | - if (nudge !== null) at = Math.min(at, nudge); | |
| 10232 | - if (this._wfNudge !== undefined) { | |
| 10233 | - at = Math.min(at, this._wfNudge); | |
| 10234 | - this._wfNudge = undefined; | |
| 10235 | - } | |
| 10236 | - settle((current, transaction) => { | |
| 10237 | - current.status = "waiting"; | |
| 10238 | - transaction.setAlarm(at); | |
| 10239 | - }); | |
| 10240 | - // The explicit re-arm replaces the alarm that fired this drive. | |
| 10241 | - // Durability is per SQLite commit, not per turn: a crash can persist | |
| 10242 | - // any prefix of this invocation's ledger writes, and the unconsumed | |
| 10243 | - // fired alarm is what re-drives the replay over whatever prefix | |
| 10244 | - // survived. A terminated instance re-arms nothing; its leftover | |
| 10245 | - // alarm fires once, sees the terminal status, and retires itself. | |
| 10246 | - return; | |
| 10247 | - } | |
| 10248 | - if (result.kind === "complete") { | |
| 10249 | - try { | |
| 10250 | - if (result.value !== undefined) { | |
| 10251 | - __wfCheckValue(result.value, "the run() return value"); | |
| 10252 | - } | |
| 10253 | - } catch (error) { | |
| 10254 | - result = { kind: "error", error }; | |
| 10255 | - } | |
| 10256 | - if (result.kind === "complete") { | |
| 10257 | - // Keep settlement outside the value-validation catch. A storage | |
| 10258 | - // failure must escape the alarm handler so the engine retries the | |
| 10259 | - // still-armed drive; converting it to a user error would consume the | |
| 10260 | - // alarm and make a transient commit failure terminal. | |
| 10261 | - settle((current, transaction) => { | |
| 10262 | - current.status = "complete"; | |
| 10263 | - if (result.value !== undefined) current.output = result.value; | |
| 10264 | - // The terminal commit installs the expiry wake with the retained | |
| 10265 | - // state, so a crash can expose neither without the other. | |
| 10266 | - __wfFinishRetention(current, transaction); | |
| 10267 | - /*__CELLD_TEST_WORKFLOW_TERMINAL_ALARM_SET__*/ | |
| 10268 | - }); | |
| 10269 | - return; | |
| 10270 | - } | |
| 10271 | - } | |
| 10272 | - settle((current, transaction) => { | |
| 10273 | - current.status = "errored"; | |
| 10274 | - current.error = __wfErrorRecord(result.error); | |
| 10275 | - __wfFinishRetention(current, transaction); | |
| 10276 | - /*__CELLD_TEST_WORKFLOW_TERMINAL_ALARM_SET__*/ | |
| 10277 | - }); | |
| 10278 | - } | |
| 10279 | - }; | |
| 10280 | -})(); | |
| 10281 | -__cell.classes.__Workflow = __WorkflowCell; | |
| 10282 | -// RPC on a stub needs `extends DurableObject` or the js_rpc flag. This class | |
| 10283 | -// is the runtime's own, so grant it here, as __D1Database does. | |
| 10284 | -__cell.doExports.__Workflow = true; | |
| 1561 | + this._activeSyncTransaction = null; | |
| 1562 | + this._syncKvListGeneration = 0; | |
| 1563 | + } | |
| 1564 | + this._kv = new SyncKvStorage(this); | |
| 1565 | + } | |
| 1566 | + get kv() { return this._kv; } | |
| 1567 | + _transactionStatus() { | |
| 1568 | + let status = null; | |
| 1569 | + for (let control = this._transactionControl; control; control = control.parent) { | |
| 1570 | + if (control.rolledBack) return "rolled back"; | |
| 1571 | + if (control.committed) status = "committed"; | |
| 1572 | + } | |
| 1573 | + return status; | |
| 1574 | + } | |
| 1575 | + _assertTransactionActive(operation) { | |
| 1576 | + const status = this._transactionStatus(); | |
| 1577 | + // workerd's wording, which applications match on. | |
| 1578 | + if (status === "committed") | |
| 1579 | + throw new Error( | |
| 1580 | + "Cannot call " + operation + "() on transaction that has already committed: " + | |
| 1581 | + "did you move `txn` outside of the closure?", | |
| 1582 | + ); | |
| 1583 | + if (status) throw new Error("Cannot " + operation + "() on " + status + " transaction"); | |
| 1584 | + } | |
| 1585 | + _flushPendingPuts() { | |
| 1586 | + // An admitted put can resume after its boundary flushed and ended the | |
| 1587 | + // transaction. Its promise completes without flushing a later scope. | |
| 1588 | + if (this._transactionStatus()) return false; | |
| 1589 | + if (this._state && this._state._aborted) return false; | |
| 1590 | + __storage_flush_pending_puts(this._scope); | |
| 1591 | + return true; | |
| 1592 | + } | |
| 1593 | + async get(k) { | |
| 1594 | + this._assertTransactionActive("get"); | |
| 1595 | + // Transaction operations reach SQLite before their caller can roll back. | |
| 1596 | + if (!this._transactionControl) await Promise.resolve(); | |
| 1597 | + if (!this._flushPendingPuts()) return; | |
| 1598 | + const key = Array.isArray(k) ? JSON.stringify(k) : String(k); | |
| 1599 | + return __readStoredValue(this._scope, key, () => { | |
| 1600 | + if (Array.isArray(k)) | |
| 1601 | + return __unwrapStoredMap( | |
| 1602 | + __storage_get_many(this._scope, k, __storedSentinel)); | |
| 1603 | + return __unwrapStored( | |
| 1604 | + __storage_get(this._scope, k, __storedSentinel)); | |
| 1605 | + }); | |
| 1606 | + } | |
| 1607 | + async put(k, val) { | |
| 1608 | + this._assertTransactionActive("put"); | |
| 1609 | + if (typeof k === "string") { | |
| 1610 | + try { | |
| 1611 | + __storage_queue_put(this._scope, k, val); | |
| 1612 | + } catch (error) { | |
| 1613 | + __storage_queue_put_serialized(this._scope, k, | |
| 1614 | + __storedBytes(val, error)); | |
| 1615 | + } | |
| 1616 | + await Promise.resolve(); | |
| 1617 | + this._flushPendingPuts(); | |
| 1618 | + return; | |
| 1619 | + } | |
| 1620 | + const source = k instanceof Map ? Array.from(k) : Object.entries(k); | |
| 1621 | + if (source.length === 0) return; | |
| 1622 | + const entries = | |
| 1623 | + source.map(([key, value]) => [String(key), value]); | |
| 1624 | + try { | |
| 1625 | + __storage_queue_put_many(this._scope, entries); | |
| 1626 | + } catch (error) { | |
| 1627 | + // A batch with a stub entry: encode every entry first (plain | |
| 1628 | + // entries keep their native clone bytes, stub entries take | |
| 1629 | + // the stored-stub envelope), then queue -- so a genuinely | |
| 1630 | + // uncloneable entry still queues nothing, like the batch op, | |
| 1631 | + // which serializes fully before queueing. | |
| 1632 | + const encoded = entries.map(([key, value]) => { | |
| 1633 | + try { | |
| 1634 | + return [key, __sc_encode(value)]; | |
| 1635 | + } catch (error_) { | |
| 1636 | + return [key, __storedBytes(value, error_)]; | |
| 1637 | + } | |
| 1638 | + }); | |
| 1639 | + for (const [key, bytes] of encoded) | |
| 1640 | + __storage_queue_put_serialized(this._scope, key, bytes); | |
| 1641 | + } | |
| 1642 | + await Promise.resolve(); | |
| 1643 | + this._flushPendingPuts(); | |
| 1644 | + } | |
| 1645 | + async delete(k) { | |
| 1646 | + this._assertTransactionActive("delete"); | |
| 1647 | + if (!this._transactionControl) await Promise.resolve(); | |
| 1648 | + if (!this._flushPendingPuts()) return; | |
| 1649 | + if (Array.isArray(k)) { | |
| 1650 | + if (k.length === 0) return 0; | |
| 1651 | + return __storage_delete_many(this._scope, k); | |
| 1652 | + } | |
| 1653 | + return __storage_delete(this._scope, k); | |
| 1654 | + } | |
| 1655 | + async list(options = {}) { | |
| 1656 | + this._assertTransactionActive("list"); | |
| 1657 | + if (!this._transactionControl) await Promise.resolve(); | |
| 1658 | + if (!this._flushPendingPuts()) return new Map(); | |
| 1659 | + return __unwrapStoredMap(__storage_list( | |
| 1660 | + this._scope, JSON.stringify(options), __storedSentinel)); | |
| 1661 | + } | |
| 1662 | + async deleteAll() { | |
| 1663 | + this._assertTransactionActive("deleteAll"); | |
| 1664 | + if (!this._transactionControl) await Promise.resolve(); | |
| 1665 | + if (!this._flushPendingPuts()) return; | |
| 1666 | + __storage_delete_all(this._scope, __cell.deleteAllDeletesAlarm); | |
| 1667 | + } | |
| 1668 | + // Resolves once every write this cell committed before the call is | |
| 1669 | + // proven durable, by the proof the output gate requires before it releases | |
| 1670 | + // an egress. Workerd resolves when the pending writes have completed; on | |
| 1671 | + // celld the local file is a cache, so "completed" is "proven". The host op | |
| 1672 | + // rejects when that proof fails or times out, so an application never | |
| 1673 | + // treats a lost write as safe. | |
| 1674 | + async sync() { | |
| 1675 | + this._assertTransactionActive("sync"); | |
| 1676 | + await Promise.resolve(); | |
| 1677 | + const status = this._transactionStatus(); | |
| 1678 | + // An admitted sync can resume after transactionSync commits or rolls | |
| 1679 | + // back. Its boundary settled the queued puts, so prove the surviving | |
| 1680 | + // state without flushing a later transaction through this handle. A | |
| 1681 | + // new call after that boundary still fails the entry guard above. | |
| 1682 | + if (this._state?._aborted || (status === null && !this._flushPendingPuts())) | |
| 1683 | + throw new Error( | |
| 1684 | + "storage.sync: " + this._scope + " was aborted; the object is no " + | |
| 1685 | + "longer running"); | |
| 1686 | + await __storage_sync(this._scope); | |
| 1687 | + } | |
| 1688 | + async setAlarm(t) { | |
| 1689 | + this._assertTransactionActive("setAlarm"); | |
| 1690 | + if (!this._transactionControl) await Promise.resolve(); | |
| 1691 | + if (!this._flushPendingPuts()) return; | |
| 1692 | + if (this._state?._facetDepth > 0) | |
| 1693 | + throw new Error("Facets currently cannot set alarms."); | |
| 1694 | + __alarm_set(this._scope, t instanceof Date ? t.getTime() : Number(t)); | |
| 1695 | + } | |
| 1696 | + async getAlarm() { | |
| 1697 | + this._assertTransactionActive("getAlarm"); | |
| 1698 | + if (!this._transactionControl) await Promise.resolve(); | |
| 1699 | + if (!this._flushPendingPuts()) return null; | |
| 1700 | + const v = __alarm_get(this._scope); | |
| 1701 | + return v === null ? null : v; | |
| 1702 | + } | |
| 1703 | + async deleteAlarm() { | |
| 1704 | + this._assertTransactionActive("deleteAlarm"); | |
| 1705 | + if (!this._transactionControl) await Promise.resolve(); | |
| 1706 | + if (!this._flushPendingPuts()) return; | |
| 1707 | + __alarm_delete(this._scope); | |
| 1708 | + } | |
| 1709 | + _transactionStart() { | |
| 1710 | + const root = this._transactionRoot; | |
| 1711 | + const savepoint = "cells_tx_" + (++root._transactionSerial); | |
| 1712 | + __storage_transaction_control( | |
| 1713 | + this._scope, "start", this._transactionDepth > 0, savepoint, | |
| 1714 | + ); | |
| 1715 | + return savepoint; | |
| 1716 | + } | |
| 1717 | + _transactionCommit(savepoint) { | |
| 1718 | + __storage_transaction_control( | |
| 1719 | + this._scope, "commit", this._transactionDepth > 0, savepoint, | |
| 1720 | + ); | |
| 1721 | + } | |
| 1722 | + _transactionRollback(savepoint, explicit = false) { | |
| 1723 | + __storage_transaction_control( | |
| 1724 | + this._scope, | |
| 1725 | + explicit ? "rollback_explicit" : "rollback", | |
| 1726 | + this._transactionDepth > 0, | |
| 1727 | + savepoint, | |
| 1728 | + ); | |
| 1729 | + } | |
| 1730 | + _transactionView(transactionControl) { | |
| 1731 | + return new DurableObjectStorage( | |
| 1732 | + this._scope, | |
| 1733 | + this._state, | |
| 1734 | + this._transactionRoot, | |
| 1735 | + this._transactionDepth + 1, | |
| 1736 | + transactionControl, | |
| 1737 | + ); | |
| 1738 | + } | |
| 1739 | + rollback() { | |
| 1740 | + const control = this._transactionControl; | |
| 1741 | + if (!control) | |
| 1742 | + throw new TypeError("rollback() must be called on a transaction"); | |
| 1743 | + if (control.rolledBack) return; | |
| 1744 | + this._assertTransactionActive("rollback"); | |
| 1745 | + // An asynchronous child can still own a nested savepoint. Mark this view | |
| 1746 | + // terminal now, but let its runner release the child before it rolls this | |
| 1747 | + // layer back. | |
| 1748 | + if (control.pending.size === 0) control.rollback(); | |
| 1749 | + control.rolledBack = true; | |
| 1750 | + } | |
| 1751 | + transactionSync(f) { | |
| 1752 | + this._assertTransactionActive("transactionSync"); | |
| 1753 | + const root = this._transactionRoot; | |
| 1754 | + if (this._transactionDepth === 0) { | |
| 1755 | + // A callback can call a helper that reaches the root `ctx.storage` | |
| 1756 | + // handle instead of the transaction view, and the helper starts its own | |
| 1757 | + // synchronous transaction. Workerd nests that one under the open | |
| 1758 | + // transaction; celld attempted a second top-level BEGIN and failed with | |
| 1759 | + // "cannot start a transaction within a transaction" | |
| 1760 | + // (denoland/celld#226). The open view takes the call instead, so it | |
| 1761 | + // becomes a savepoint: an inner rollback then discards only the inner | |
| 1762 | + // writes, and an outer rollback discards both layers. | |
| 1763 | + // | |
| 1764 | + // The synchronous transaction is preferred over an asynchronous one, | |
| 1765 | + // because it is the innermost open layer whenever both are open. | |
| 1766 | + if (root._activeSyncTransaction !== null) | |
| 1767 | + return root._activeSyncTransaction.transactionSync(f); | |
| 1768 | + const owner = String(__io_context_id()); | |
| 1769 | + if (owner !== "" && root._transactionOwner === owner && | |
| 1770 | + root._activeTransaction !== null) | |
| 1771 | + return root._activeTransaction.transactionSync(f); | |
| 1772 | + } | |
| 1773 | + const savepoint = this._transactionStart(); | |
| 1774 | + const control = this._newTransactionControl(savepoint); | |
| 1775 | + const view = this._transactionView(control); | |
| 1776 | + // No owner check guards this slot, unlike `_activeTransaction`, which an | |
| 1777 | + // asynchronous transaction publishes across awaits and must therefore keep | |
| 1778 | + // with the event that opened it. The callback below runs to its end before | |
| 1779 | + // any other event starts, so only that event can read the slot, and the | |
| 1780 | + // restore below runs at exactly the point the savepoint ends. | |
| 1781 | + const previousSync = root._activeSyncTransaction; | |
| 1782 | + root._activeSyncTransaction = view; | |
| 1783 | + try { | |
| 1784 | + // workerd hands the callback nothing: the root's own methods write | |
| 1785 | + // inside the transaction, and a throw rolls it back. | |
| 1786 | + const value = f(); | |
| 1787 | + if (!control.rolledBack) { | |
| 1788 | + this._transactionCommit(savepoint); | |
| 1789 | + control.committed = true; | |
| 1790 | + } | |
| 1791 | + return value; | |
| 1792 | + } catch (error) { | |
| 1793 | + if (!control.rolledBack) { | |
| 1794 | + try { | |
| 1795 | + this._transactionRollback(savepoint); | |
| 1796 | + control.rolledBack = true; | |
| 1797 | + } catch (rollbackError) { | |
| 1798 | + this._abortAfterFailedRollback(rollbackError, error); | |
| 1799 | + } | |
| 1800 | + } | |
| 1801 | + throw error; | |
| 1802 | + } finally { | |
| 1803 | + root._activeSyncTransaction = previousSync; | |
| 1804 | + } | |
| 1805 | + } | |
| 1806 | + _newTransactionControl(savepoint) { | |
| 1807 | + const control = { | |
| 1808 | + rolledBack: false, | |
| 1809 | + rollbackPerformed: false, | |
| 1810 | + committed: false, | |
| 1811 | + parent: this._transactionControl, | |
| 1812 | + pending: new Set(), | |
| 1813 | + rollback: () => { | |
| 1814 | + this._transactionRollback(savepoint, true); | |
| 1815 | + control.rollbackPerformed = true; | |
| 1816 | + }, | |
| 1817 | + }; | |
| 1818 | + return control; | |
| 1819 | + } | |
| 1820 | + async _drainNestedTransactions(control) { | |
| 1821 | + while (control.pending.size !== 0) | |
| 1822 | + await Promise.allSettled(Array.from(control.pending)); | |
| 1823 | + } | |
| 1824 | + async _runTransactionWith(f, savepoint, control) { | |
| 1825 | + const view = this._transactionView(control); | |
| 1826 | + const root = this._transactionRoot; | |
| 1827 | + const owner = String(__io_context_id()); | |
| 1828 | + const installsActive = owner !== "" && root._transactionOwner === owner; | |
| 1829 | + const previousActive = root._activeTransaction; | |
| 1830 | + if (installsActive) root._activeTransaction = view; | |
| 1831 | + try { | |
| 1832 | + const value = await f(view); | |
| 1833 | + // A helper can start a reentrant transaction through the root storage | |
| 1834 | + // handle and omit the returned promise. That child already owns a | |
| 1835 | + // savepoint, so ending this layer first would make SQLite release the | |
| 1836 | + // child's savepoint and let its continuation run against a false owner. | |
| 1837 | + await this._drainNestedTransactions(control); | |
| 1838 | + if (!control.rolledBack) { | |
| 1839 | + this._transactionCommit(savepoint); | |
| 1840 | + control.committed = true; | |
| 1841 | + } else if (!control.rollbackPerformed) { | |
| 1842 | + control.rollback(); | |
| 1843 | + } | |
| 1844 | + return value; | |
| 1845 | + } catch (error) { | |
| 1846 | + await this._drainNestedTransactions(control); | |
| 1847 | + if (!control.rollbackPerformed) { | |
| 1848 | + // The flag records a rollback that happened, not one that was | |
| 1849 | + // attempted: a rollback that fails leaves the savepoint open, and a | |
| 1850 | + // later transaction on the same connection would commit its writes. | |
| 1851 | + // Nothing can be said about the connection then, so the object is | |
| 1852 | + // aborted rather than left to serve from it. | |
| 1853 | + try { | |
| 1854 | + this._transactionRollback(savepoint); | |
| 1855 | + control.rolledBack = true; | |
| 1856 | + control.rollbackPerformed = true; | |
| 1857 | + } catch (rollbackError) { | |
| 1858 | + this._abortAfterFailedRollback(rollbackError, error); | |
| 1859 | + } | |
| 1860 | + } | |
| 1861 | + throw error; | |
| 1862 | + } finally { | |
| 1863 | + if (installsActive && root._activeTransaction === view) | |
| 1864 | + root._activeTransaction = previousActive; | |
| 1865 | + } | |
| 1866 | + } | |
| 1867 | + // `cause` is the failure that led to the rollback; the abort's error keeps | |
| 1868 | + // it, so a debugger can walk back to the callback's own throw. The | |
| 1869 | + // rollback failure is reported even when the object is already aborted, | |
| 1870 | + // as it is after a block's limit: the abort then changes nothing, and the | |
| 1871 | + // log line is the only trace the failure leaves. | |
| 1872 | + _abortAfterFailedRollback(rollbackError, cause) { | |
| 1873 | + // Inside a catch, so the log must not become the throw that leaves it: | |
| 1874 | + // the slot release after the caller's rethrow depends on that. | |
| 1875 | + try { console.error("transaction rollback failed", rollbackError); } catch {} | |
| 1876 | + const state = this._transactionRoot._state; | |
| 1877 | + if (state && !state._aborted) { | |
| 1878 | + state.abort( | |
| 1879 | + new Error( | |
| 1880 | + "a transaction rollback failed: " + __describeFailure(rollbackError), | |
| 1881 | + { cause }, | |
| 1882 | + ), | |
| 1883 | + ); | |
| 1884 | + } | |
| 1885 | + } | |
| 1886 | + async _runTransaction(f) { | |
| 1887 | + const savepoint = this._transactionStart(); | |
| 1888 | + return this._runTransactionWith(f, savepoint, this._newTransactionControl(savepoint)); | |
| 1889 | + } | |
| 1890 | + async transaction(f) { | |
| 1891 | + this._assertTransactionActive("transaction"); | |
| 1892 | + if (this._transactionDepth > 0) { | |
| 1893 | + const nested = this._runTransaction(f); | |
| 1894 | + const pending = this._transactionControl.pending; | |
| 1895 | + pending.add(nested); | |
| 1896 | + nested.then( | |
| 1897 | + () => pending.delete(nested), | |
| 1898 | + () => pending.delete(nested), | |
| 1899 | + ); | |
| 1900 | + return nested; | |
| 1901 | + } | |
| 1902 | + const root = this._transactionRoot; | |
| 1903 | + const owner = String(__io_context_id()); | |
| 1904 | + if (owner !== "" && root._transactionOwner === owner && | |
| 1905 | + root._activeTransaction !== null) | |
| 1906 | + return root._activeTransaction.transaction(f); | |
| 1907 | + // Workerd runs the callback under blockConcurrencyWhile: the input gate | |
| 1908 | + // shuts, so no other event starts in the object while the transaction is | |
| 1909 | + // open. Without it another event's reads saw uncommitted rows, its | |
| 1910 | + // writes joined the open transaction on the same connection, and a | |
| 1911 | + // rollback discarded a write celld had already acknowledged (#714). The | |
| 1912 | + // callback's failure is caught inside the block: a failed transaction | |
| 1913 | + // rolls back and rejects, and must not reset the object the way a failed | |
| 1914 | + // critical section does. | |
| 1915 | + // | |
| 1916 | + // The tail orders transactions one event starts concurrently, which the | |
| 1917 | + // gate does not separate. Its slot is taken here, in call order: taken | |
| 1918 | + // inside the block it would be taken in the order the gate woke the | |
| 1919 | + // callers, which is not theirs to keep. It is released inside the block, | |
| 1920 | + // when the callback has settled, and not when the block has: a second | |
| 1921 | + // transaction the same event starts while the first runs rides the | |
| 1922 | + // outer hold as a nested block, and the outer block waits for nested | |
| 1923 | + // ones before it releases, so a slot held until the block's end would | |
| 1924 | + // wait on itself. | |
| 1925 | + const previous = root._transactionTail; | |
| 1926 | + let release; | |
| 1927 | + root._transactionTail = new Promise((resolve) => { release = resolve; }); | |
| 1928 | + let control = null; | |
| 1929 | + let started = false; | |
| 1930 | + let abandoned = null; | |
| 1931 | + const guarded = async () => { | |
| 1932 | + started = true; | |
| 1933 | + let ownsTransaction = false; | |
| 1934 | + try { | |
| 1935 | + await previous; | |
| 1936 | + // The block ended while this waited for its slot, or the object was | |
| 1937 | + // reset under it by an enclosing block that failed: the caller has | |
| 1938 | + // its rejection and the gate is open again, so starting the | |
| 1939 | + // transaction now would run it beside whatever the object serves. | |
| 1940 | + if (abandoned !== null) return { error: abandoned }; | |
| 1941 | + if (root._state._aborted) { | |
| 1942 | + return { error: new Error("the Durable Object was reset before the transaction started") }; | |
| 1943 | + } | |
| 1944 | + // A callback can compose a helper which reaches the root | |
| 1945 | + // `ctx.storage` handle instead of the transaction view. The input | |
| 1946 | + // gate excludes other events, but an event which entered before the | |
| 1947 | + // gate closed can still be waiting for this slot. Keep the owner with | |
| 1948 | + // the open transaction so only the callback's event takes the | |
| 1949 | + // savepoint path; another event still waits on the tail. | |
| 1950 | + root._transactionOwner = owner; | |
| 1951 | + ownsTransaction = true; | |
| 1952 | + // The start is a host op that can fail like any other statement, and | |
| 1953 | + // a failure there is the transaction's to report, not the block's: | |
| 1954 | + // a throw that escaped here would reset the object. | |
| 1955 | + try { | |
| 1956 | + const savepoint = this._transactionStart(); | |
| 1957 | + control = this._newTransactionControl(savepoint); | |
| 1958 | + return { value: await this._runTransactionWith(f, savepoint, control) }; | |
| 1959 | + } catch (error) { | |
| 1960 | + return { error }; | |
| 1961 | + } | |
| 1962 | + } finally { | |
| 1963 | + if (ownsTransaction && root._transactionOwner === owner) { | |
| 1964 | + root._activeTransaction = null; | |
| 1965 | + root._transactionOwner = ""; | |
| 1966 | + } | |
| 1967 | + release(); | |
| 1968 | + } | |
| 1969 | + }; | |
| 1970 | + let outcome; | |
| 1971 | + try { | |
| 1972 | + outcome = await root._state.blockConcurrencyWhile(guarded); | |
| 1973 | + } catch (error) { | |
| 1974 | + // The block itself failed: its limit ended the callback while it still | |
| 1975 | + // ran, or the block ahead of it failed and this one never started. A | |
| 1976 | + // transaction the callback still holds would otherwise stay open on | |
| 1977 | + // the connection the object's replacement uses, and the callback's | |
| 1978 | + // late commit would carry the replacement's writes with it. Roll it | |
| 1979 | + // back now, unless the callback's continuation committed in the same | |
| 1980 | + // tick the limit won; the callback's own commit is skipped from here | |
| 1981 | + // on. The slot stays with the callback until it settles: the callback | |
| 1982 | + // still runs on the connection, and a transaction started beside it | |
| 1983 | + // would interleave with its remaining statements. A routed child must | |
| 1984 | + // release its savepoint before this layer rolls back, so a live child | |
| 1985 | + // leaves the rollback for `_runTransactionWith`. A block that failed | |
| 1986 | + // before the callback started holds nothing, so its slot is released | |
| 1987 | + // here or nothing ever would. | |
| 1988 | + abandoned = error; | |
| 1989 | + if (control && !control.rolledBack && !control.committed) { | |
| 1990 | + try { | |
| 1991 | + if (control.pending.size === 0) control.rollback(); | |
| 1992 | + control.rolledBack = true; | |
| 1993 | + } catch (rollbackError) { | |
| 1994 | + this._abortAfterFailedRollback(rollbackError, error); | |
| 1995 | + } | |
| 1996 | + } | |
| 1997 | + if (!started) release(); | |
| 1998 | + throw error; | |
| 1999 | + } | |
| 2000 | + if ("error" in outcome) throw outcome.error; | |
| 2001 | + return outcome.value; | |
| 2002 | + } | |
| 2003 | +} | |
| 2004 | +class DurableObjectId { | |
| 2005 | + constructor(className, value, name = undefined) { | |
| 2006 | + Object.defineProperties(this, { | |
| 2007 | + _className: { value: className }, | |
| 2008 | + _value: { value }, | |
| 2009 | + }); | |
| 2010 | + this.name = name; | |
| 2011 | + this.jurisdiction = undefined; | |
| 2012 | + } | |
| 2013 | + toString() { return this._value; } | |
| 2014 | + equals(other) { | |
| 2015 | + return other instanceof DurableObjectId && other._value === this._value; | |
| 2016 | + } | |
| 2017 | + _scope() { return this._className + ":" + this._value; } | |
| 2018 | +} | |
| 2019 | +globalThis.DurableObjectRoutingError = class DurableObjectRoutingError | |
| 2020 | + extends Error { | |
| 2021 | + constructor(detail = {}) { | |
| 2022 | + super("The Durable Object owner is currently unreachable"); | |
| 2023 | + this.name = "DurableObjectRoutingError"; | |
| 2024 | + this.code = "owner_unreachable"; | |
| 2025 | + this.retryable = true; | |
| 2026 | + if (typeof detail.scope === "string") this.scope = detail.scope; | |
| 2027 | + if (typeof detail.owner === "string") this.owner = detail.owner; | |
| 2028 | + } | |
| 2029 | +}; | |
| 2030 | +const __durableObjectRoutingError = (error) => { | |
| 2031 | + const marker = "__CELLD_DO_ROUTING_ERROR__:"; | |
| 2032 | + const message = String(error && error.message || error); | |
| 2033 | + const offset = message.indexOf(marker); | |
| 2034 | + if (offset < 0) return null; | |
| 2035 | + try { | |
| 2036 | + return new DurableObjectRoutingError( | |
| 2037 | + JSON.parse(message.slice(offset + marker.length)), | |
| 2038 | + ); | |
| 2039 | + } catch { | |
| 2040 | + return new DurableObjectRoutingError(); | |
| 2041 | + } | |
| 2042 | +}; | |
| 2043 | +// A cell's input gate as the isolate sees it, for the one delivery | |
| 2044 | +// point that is inside the isolate rather than in front of it: an | |
| 2045 | +// RPC stub op. `events` records every block that has asked for the | |
| 2046 | +// gate, so no window exists in which a block has started and the | |
| 2047 | +// isolate still thinks the cell is open. `holder` names the block | |
| 2048 | +// actually running; another event can still be queued. | |
| 2049 | +// | |
| 2050 | +// A stub minted while a block runs carries that block's token and | |
| 2051 | +// re-enters it instead of queueing behind it. That is Workerd's | |
| 2052 | +// `IoContext::makeReentryCallback`, and without it a callback the | |
| 2053 | +// block itself sent out could never come back. | |
| 2054 | +const __cellBlocks = new Map(); | |
| 2055 | +const __blockEnter = (scope, event, owner) => { | |
| 2056 | + let settleReady; | |
| 2057 | + let rejectReady; | |
| 2058 | + const ready = new Promise((resolve, reject) => { | |
| 2059 | + settleReady = resolve; | |
| 2060 | + rejectReady = reject; | |
| 2061 | + }); | |
| 2062 | + const record = { | |
| 2063 | + owner, | |
| 2064 | + reaction: String(__io_context_id()), | |
| 2065 | + actorEvent: __currentActorEvent(), | |
| 2066 | + retired: false, | |
| 2067 | + ready, | |
| 2068 | + settleReady, | |
| 2069 | + rejectReady, | |
| 2070 | + }; | |
| 2071 | + const block = __cellBlocks.get(scope); | |
| 2072 | + if (block !== undefined) { | |
| 2073 | + block.events.set(event, record); | |
| 2074 | + return { block, record }; | |
| 2075 | + } | |
| 2076 | + const fresh = { | |
| 2077 | + holder: null, | |
| 2078 | + events: new Map([[event, record]]), | |
| 2079 | + }; | |
| 2080 | + __cellBlocks.set(scope, fresh); | |
| 2081 | + return { block: fresh, record }; | |
| 2082 | +}; | |
| 2083 | +const __blockLeave = (scope, block, event) => { | |
| 2084 | + if (!block.events.delete(event)) return; | |
| 2085 | + if (block.holder === event) block.holder = null; | |
| 2086 | + if (block.events.size === 0 && __cellBlocks.get(scope) === block) | |
| 2087 | + __cellBlocks.delete(scope); | |
| 2088 | +}; | |
| 2089 | +const __durableClassMeta = new WeakMap(); | |
| 2090 | +let __nextFacetOwner = 1; | |
| 2091 | +// Takes encoded props, not the caller's options bag: an options bag reaching | |
| 2092 | +// here is a bag nothing validated, and reading one key out of it is how every | |
| 2093 | +// other key came to be dropped in silence. The loader stub validates the bag | |
| 2094 | +// and encodes its value before it creates the class. | |
| 2095 | +const __makeDurableObjectClass = (idPromise, name, propsSc) => { | |
| 2096 | + const value = {}; | |
| 2097 | + __durableClassMeta.set(value, { | |
| 2098 | + idPromise, | |
| 2099 | + name: name === null || name === undefined ? "default" : String(name), | |
| 2100 | + propsSc, | |
| 2101 | + }); | |
| 2102 | + return value; | |
| 2103 | +}; | |
| 2104 | +class DurableObjectFacets { | |
| 2105 | + constructor(state) { | |
| 2106 | + this._state = state; | |
| 2107 | + this._owner = String(__nextFacetOwner++); | |
| 2108 | + this._next = 1; | |
| 2109 | + this._running = new Map(); | |
| 2110 | + this._barriers = new Map(); | |
| 2111 | + } | |
| 2112 | + _validName(name) { | |
| 2113 | + name = String(name); | |
| 2114 | + if (new TextEncoder().encode(name).length > 256) | |
| 2115 | + throw new TypeError("Facet name is too long (max 256 characters)."); | |
| 2116 | + return name; | |
| 2117 | + } | |
| 2118 | + get(name, getStartupOptions) { | |
| 2119 | + name = this._validName(name); | |
| 2120 | + if (this._state._facetDepth >= 3) | |
| 2121 | + throw new Error( | |
| 2122 | + "Facet nesting depth limit exceeded. The maximum depth including the root Durable Object is 4."); | |
| 2123 | + if (typeof getStartupOptions !== "function") | |
| 2124 | + throw new TypeError("The facet startup callback must be a function."); | |
| 2125 | + let record = this._running.get(name); | |
| 2126 | + if (record !== undefined) return record.stub; | |
| 2127 | + // Each run gets a distinct host scope. An aborted request can still have | |
| 2128 | + // a pending continuation, so reusing its scope would let that continuation | |
| 2129 | + // enter the replacement instance after the abort barrier opens. | |
| 2130 | + record = { | |
| 2131 | + aborted: false, | |
| 2132 | + error: undefined, | |
| 2133 | + owner: this._owner + ":" + this._next++, | |
| 2134 | + started: null, | |
| 2135 | + stub: null, | |
| 2136 | + }; | |
| 2137 | + const barrier = this._barriers.get(name); | |
| 2138 | + const start = () => record.started ??= Promise.resolve(barrier) | |
| 2139 | + .then(getStartupOptions) | |
| 2140 | + .then(async (options) => { | |
| 2141 | + const meta = __durableClassMeta.get(options?.class); | |
| 2142 | + if (meta === undefined) | |
| 2143 | + throw new TypeError( | |
| 2144 | + "FacetStartupOptions.class must be a DurableObjectClass."); | |
| 2145 | + const loader = await meta.idPromise; | |
| 2146 | + const id = options.id instanceof DurableObjectId | |
| 2147 | + ? options.id.toString() | |
| 2148 | + : options.id === undefined ? this._state.id.toString() : String(options.id); | |
| 2149 | + return [loader, meta.name, id, meta.propsSc]; | |
| 2150 | + }); | |
| 2151 | + const invoke = async (operation) => { | |
| 2152 | + if (record.aborted) throw record.error; | |
| 2153 | + return operation(await start()); | |
| 2154 | + }; | |
| 2155 | + const target = {}; | |
| 2156 | + // Methods share the loaded-worker RPC transport. A facet stub is not | |
| 2157 | + // awaitable, and a property is a single callable pipeline node. | |
| 2158 | + const session = { | |
| 2159 | + get: () => Promise.reject(new Error( | |
| 2160 | + "Awaitable properties on facets are not supported yet.")), | |
| 2161 | + call: (path, args) => invoke(async ([loader, className, id, propsSc]) => { | |
| 2162 | + if (path.length !== 1) | |
| 2163 | + throw new Error( | |
| 2164 | + "Pipelined property paths on facets are not supported yet."); | |
| 2165 | + return __rpcDes(await __facet_rpc( | |
| 2166 | + loader, className, this._state._scope, record.owner, name, id, | |
| 2167 | + propsSc, path[0], __rpcOut(args, false))); | |
| 2168 | + }), | |
| 2169 | + }; | |
| 2170 | + // Arrow closures retain the manager because `target.fetch`'s method | |
| 2171 | + // receiver is the target object, not the DurableObjectFacets instance. | |
| 2172 | + const manager = this; | |
| 2173 | + target.fetch = async function(input, init) { | |
| 2174 | + return invoke(async ([loader, className, id, propsSc]) => { | |
| 2175 | + const req = new Request(input, init); | |
| 2176 | + const headers = JSON.stringify(req.headers.__celldHeaderList); | |
| 2177 | + const { body, streamId } = await __subrequestBody(req); | |
| 2178 | + const response = JSON.parse(await __facet_fetch( | |
| 2179 | + loader, className, manager._state._scope, record.owner, name, id, | |
| 2180 | + propsSc, req.url, req.method, body, headers, streamId)); | |
| 2181 | + const responseBody = response.streamId !== undefined | |
| 2182 | + ? new CelldHttpBodyStream(response.streamId) | |
| 2183 | + : response.body !== undefined ? response.body | |
| 2184 | + : Uint8Array.from(response.bodyBytes || []); | |
| 2185 | + return __wrapServiceResponse(new Response(responseBody, { | |
| 2186 | + status: response.status, | |
| 2187 | + headers: response.headers, | |
| 2188 | + }), req.url); | |
| 2189 | + }); | |
| 2190 | + }; | |
| 2191 | + record.stub = new Proxy(target, { | |
| 2192 | + get(base, prop) { | |
| 2193 | + if (prop === "then") return undefined; | |
| 2194 | + if (Reflect.has(base, prop)) return Reflect.get(base, prop); | |
| 2195 | + if (typeof prop !== "string") return undefined; | |
| 2196 | + return __makeNode(session, [prop], null); | |
| 2197 | + }, | |
| 2198 | + }); | |
| 2199 | + this._running.set(name, record); | |
| 2200 | + return record.stub; | |
| 2201 | + } | |
| 2202 | + _abort(name, reason) { | |
| 2203 | + name = this._validName(name); | |
| 2204 | + const record = this._running.get(name); | |
| 2205 | + if (record === undefined) return Promise.resolve(); | |
| 2206 | + record.aborted = true; | |
| 2207 | + record.error = reason; | |
| 2208 | + this._running.delete(name); | |
| 2209 | + const barrier = record.started === null ? Promise.resolve() : record.started | |
| 2210 | + .then(([loader, className]) => | |
| 2211 | + __facet_abort( | |
| 2212 | + loader, className, this._state._scope, record.owner, name), () => {}); | |
| 2213 | + this._barriers.set(name, barrier); | |
| 2214 | + const clear = () => { | |
| 2215 | + if (this._barriers.get(name) === barrier) this._barriers.delete(name); | |
| 2216 | + }; | |
| 2217 | + barrier.then(clear, clear); | |
| 2218 | + return barrier; | |
| 2219 | + } | |
| 2220 | + abort(name, reason) { | |
| 2221 | + this._abort(name, reason); | |
| 2222 | + } | |
| 2223 | + delete(name) { | |
| 2224 | + name = this._validName(name); | |
| 2225 | + const barrier = this._abort(name, new Error("Facet was deleted.")).then(() => | |
| 2226 | + __facet_delete(this._state._scope, name)); | |
| 2227 | + this._barriers.set(name, barrier); | |
| 2228 | + const clear = () => { | |
| 2229 | + if (this._barriers.get(name) === barrier) this._barriers.delete(name); | |
| 2230 | + }; | |
| 2231 | + // Keep a failed delete as the name's barrier. Clearing it would let the | |
| 2232 | + // next get reload the image which the failed operation did not delete. | |
| 2233 | + barrier.then(clear, () => {}); | |
| 2234 | + } | |
| 2235 | + _release() { | |
| 2236 | + for (const name of Array.from(this._running.keys())) | |
| 2237 | + this._abort(name, new Error("The parent Durable Object was released.")); | |
| 2238 | + } | |
| 2239 | +} | |
| 2240 | +// The reason a failed critical section gives its waiters. It must not throw: | |
| 2241 | +// it runs where a throw would skip the gate's release, and a value with no | |
| 2242 | +// string form, such as `Object.create(null)`, is a legal thing to throw. | |
| 2243 | +function __describeFailure(error) { | |
| 2244 | + try { | |
| 2245 | + return String((error && error.message) || error); | |
| 2246 | + } catch { | |
| 2247 | + return "critical section failed"; | |
| 2248 | + } | |
| 2249 | +} | |
| 2250 | +// ---- Containers ----------------------------------------------------------- | |
| 2251 | +// `ctx.container` for a class named in the deployment's `containers`. The | |
| 2252 | +// surface and every message follow workerd's api/container.c++; the host | |
| 2253 | +// ops perform the effects against the node's container engine, and the | |
| 2254 | +// scope names the cell the way the storage ops do. | |
| 2255 | +const __containerEnvList = (env, what) => { | |
| 2256 | + const list = []; | |
| 2257 | + if (env === undefined || env === null) return list; | |
| 2258 | + for (const [name, value] of Object.entries(env)) { | |
| 2259 | + const text = String(value); | |
| 2260 | + if (name.includes("=")) | |
| 2261 | + throw new Error(`Environment variable names cannot contain '=': ${name}`); | |
| 2262 | + if (name.includes("\0")) | |
| 2263 | + throw new Error(`Environment variable names cannot contain '\\0': ${name}`); | |
| 2264 | + if (text.includes("\0")) | |
| 2265 | + throw new Error(`Environment variable values cannot contain '\\0': ${name}`); | |
| 2266 | + list.push([name, text]); | |
| 2267 | + } | |
| 2268 | + return list; | |
| 2269 | +}; | |
| 2270 | +const __execOutputMode = (mode, kind) => { | |
| 2271 | + const value = mode === undefined ? "pipe" : String(mode); | |
| 2272 | + if (value === "pipe" || value === "ignore" || | |
| 2273 | + (kind === "stderr" && value === "combined")) return value; | |
| 2274 | + throw new TypeError(`Invalid ${kind} option: ${value}`); | |
| 2275 | +}; | |
| 2276 | +const __validSignal = (signo) => Number.isInteger(signo) && signo > 0 && signo <= 64; | |
| 2277 | +const __execStream = (id, which) => new ReadableStream({ | |
| 2278 | + type: "bytes", | |
| 2279 | + async pull(controller) { | |
| 2280 | + const chunk = await __container_exec_read(id, which); | |
| 2281 | + if (chunk.byteLength === 0) controller.close(); | |
| 2282 | + else controller.enqueue(new Uint8Array(chunk)); | |
| 2283 | + }, | |
| 2284 | +}); | |
| 2285 | +class ContainerExecOutput { | |
| 2286 | + constructor(stdout, stderr, exitCode) { | |
| 2287 | + this.stdout = stdout; | |
| 2288 | + this.stderr = stderr; | |
| 2289 | + this.exitCode = exitCode; | |
| 2290 | + } | |
| 2291 | +} | |
| 2292 | +class ContainerExecProcess { | |
| 2293 | + constructor(id, pid, stdinMode, stdoutMode, stderrMode) { | |
| 2294 | + this._id = id; | |
| 2295 | + this.pid = pid; | |
| 2296 | + this._outputCalled = false; | |
| 2297 | + this._exitCode = null; | |
| 2298 | + this.stdout = stdoutMode === "pipe" ? __execStream(id, 1) : null; | |
| 2299 | + this.stderr = stderrMode === "pipe" ? __execStream(id, 2) : null; | |
| 2300 | + this.stdin = stdinMode === "pipe" | |
| 2301 | + ? new WritableStream({ | |
| 2302 | + write: (chunk) => __container_exec_write(id, __bytesOf(chunk)), | |
| 2303 | + close: () => __container_exec_close(id), | |
| 2304 | + abort: () => __container_exec_close(id), | |
| 2305 | + }) | |
| 2306 | + : null; | |
| 2307 | + } | |
| 2308 | + get exitCode() { | |
| 2309 | + if (this._exitCode === null) { | |
| 2310 | + this._exitCode = __container_exec_wait(this._id).then(Number); | |
| 2311 | + } | |
| 2312 | + return this._exitCode; | |
| 2313 | + } | |
| 2314 | + async output() { | |
| 2315 | + if (this._outputCalled) throw new TypeError("output() can only be called once."); | |
| 2316 | + this._outputCalled = true; | |
| 2317 | + for (const [stream, name] of [[this.stdout, "stdout"], [this.stderr, "stderr"]]) { | |
| 2318 | + if (stream && stream.locked) | |
| 2319 | + throw new TypeError(`Cannot call output() after ${name} has started being consumed.`); | |
| 2320 | + } | |
| 2321 | + const all = (stream) => stream | |
| 2322 | + ? new Response(stream).arrayBuffer() | |
| 2323 | + : Promise.resolve(new ArrayBuffer(0)); | |
| 2324 | + const [stdout, stderr] = await Promise.all([all(this.stdout), all(this.stderr)]); | |
| 2325 | + const exitCode = await this.exitCode; | |
| 2326 | + // Nothing else can read the process now, so the host can forget it. | |
| 2327 | + __container_exec_drop(this._id); | |
| 2328 | + return new ContainerExecOutput(stdout, stderr, exitCode); | |
| 2329 | + } | |
| 2330 | + kill(signal = 15) { | |
| 2331 | + if (!__validSignal(signal)) throw new RangeError("Invalid signal number."); | |
| 2332 | + __container_exec_kill(this._id, signal).catch(() => {}); | |
| 2333 | + } | |
| 2334 | +} | |
| 2335 | +const __bytesOf = (chunk) => { | |
| 2336 | + if (chunk instanceof Uint8Array) return chunk; | |
| 2337 | + if (chunk instanceof ArrayBuffer) return new Uint8Array(chunk); | |
| 2338 | + if (ArrayBuffer.isView(chunk)) | |
| 2339 | + return new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength); | |
| 2340 | + throw new TypeError("stdin accepts bytes"); | |
| 2341 | +}; | |
| 2342 | +// The Fetcher `getTcpPort()` returns: `fetch()` speaks HTTP to the port over | |
| 2343 | +// the node's route to the container, and `connect()` is the raw socket. | |
| 2344 | +class ContainerPort { | |
| 2345 | + constructor(scope, port) { | |
| 2346 | + this._scope = scope; | |
| 2347 | + this._port = port; | |
| 2348 | + } | |
| 2349 | + async fetch(input, init) { | |
| 2350 | + const request = new Request(input, init); | |
| 2351 | + const url = new URL(request.url); | |
| 2352 | + if (url.protocol === "https:") | |
| 2353 | + throw new Error( | |
| 2354 | + "Connecting to a container using HTTPS is not currently supported; use HTTP " + | |
| 2355 | + "instead. TLS is unnecessary anyway, as the connection is already secure by default.", | |
| 2356 | + ); | |
| 2357 | + if (url.protocol !== "http:") throw new TypeError(`Fetch API cannot load: ${url}`); | |
| 2358 | + const authority = url.host; | |
| 2359 | + url.host = __container_address(this._scope, this._port); | |
| 2360 | + const forwarded = new Request(url.toString(), request); | |
| 2361 | + forwarded.headers.set("host", authority); | |
| 2362 | + try { | |
| 2363 | + return await fetch(forwarded); | |
| 2364 | + } catch (error) { | |
| 2365 | + // A refused or reset connection is the port not listening yet, which | |
| 2366 | + // the `@cloudflare/containers` start loop recognizes by this phrase | |
| 2367 | + // and retries; any other failure keeps its own message. | |
| 2368 | + const message = error?.message ?? String(error); | |
| 2369 | + if (/error sending request|connection|connect/i.test(message)) { | |
| 2370 | + throw new Error( | |
| 2371 | + `The container is not listening on port ${this._port}: ${message}`, | |
| 2372 | + ); | |
| 2373 | + } | |
| 2374 | + throw error; | |
| 2375 | + } | |
| 2376 | + } | |
| 2377 | + connect(address, options) { | |
| 2378 | + if (options?.secureTransport === "on") | |
| 2379 | + throw new Error( | |
| 2380 | + "Connencting to a container using TLS is not currently supported. It is " + | |
| 2381 | + "unnecessary anyway, as the connection is already secure by default.", | |
| 2382 | + ); | |
| 2383 | + return __celld.__cfSockets.connect( | |
| 2384 | + __container_address(this._scope, this._port), options); | |
| 2385 | + } | |
| 2386 | +} | |
| 2387 | +class Container { | |
| 2388 | + constructor(scope) { | |
| 2389 | + this._scope = scope; | |
| 2390 | + this._destroyReason = undefined; | |
| 2391 | + } | |
| 2392 | + // The host's answer, not a JavaScript flag: a monitor() promise can be | |
| 2393 | + // dropped with its event, so the flag it would maintain could go stale. | |
| 2394 | + get running() { return __container_running(this._scope); } | |
| 2395 | + start(options) { | |
| 2396 | + if (this.running) | |
| 2397 | + throw new Error("start() cannot be called on a container that is already running."); | |
| 2398 | + const o = options ?? {}; | |
| 2399 | + const params = { enableInternet: !!o.enableInternet, labels: [] }; | |
| 2400 | + if (o.entrypoint !== undefined) params.entrypoint = Array.from(o.entrypoint, String); | |
| 2401 | + params.env = __containerEnvList(o.env); | |
| 2402 | + if (o.labels !== undefined) { | |
| 2403 | + for (const [name, value] of Object.entries(o.labels)) { | |
| 2404 | + if (name.length === 0) throw new Error("Label names cannot be empty"); | |
| 2405 | + for (const text of [name, String(value)]) { | |
| 2406 | + for (let i = 0; i < text.length; i++) { | |
| 2407 | + if (text.charCodeAt(i) < 0x20) | |
| 2408 | + throw new Error(`Label names cannot contain control characters (index ${i})`); | |
| 2409 | + } | |
| 2410 | + } | |
| 2411 | + params.labels.push([name, String(value)]); | |
| 2412 | + } | |
| 2413 | + } | |
| 2414 | + if (o.hardTimeout !== undefined && !(o.hardTimeout > 0)) | |
| 2415 | + throw new RangeError("Hard timeout must be greater than 0"); | |
| 2416 | + // Fire and forget, as on Cloudflare: a start that fails reports | |
| 2417 | + // through monitor(). The host marks the run as running at once. | |
| 2418 | + this._destroyReason = undefined; | |
| 2419 | + __container_start(this._scope, JSON.stringify(params)).catch(() => {}); | |
| 2420 | + } | |
| 2421 | + async monitor() { | |
| 2422 | + if (!this.running) | |
| 2423 | + throw new Error("monitor() cannot be called on a container that is not running."); | |
| 2424 | + let raw; | |
| 2425 | + try { | |
| 2426 | + raw = await __container_monitor(this._scope); | |
| 2427 | + } catch (error) { | |
| 2428 | + this._destroyReason = undefined; | |
| 2429 | + throw error; | |
| 2430 | + } | |
| 2431 | + const exitCode = Number(raw); | |
| 2432 | + if (this._destroyReason !== undefined) { | |
| 2433 | + const reason = this._destroyReason; | |
| 2434 | + this._destroyReason = undefined; | |
| 2435 | + throw reason; | |
| 2436 | + } | |
| 2437 | + if (exitCode !== 0) { | |
| 2438 | + const error = new Error(`Container exited with unexpected exit code: ${exitCode}`); | |
| 2439 | + error.exitCode = exitCode; | |
| 2440 | + throw error; | |
| 2441 | + } | |
| 2442 | + } | |
| 2443 | + async destroy(error) { | |
| 2444 | + if (!this.running) return; | |
| 2445 | + if (this._destroyReason === undefined) this._destroyReason = error; | |
| 2446 | + await __container_destroy(this._scope); | |
| 2447 | + } | |
| 2448 | + signal(signo) { | |
| 2449 | + if (!__validSignal(signo)) throw new RangeError("Invalid signal number."); | |
| 2450 | + if (!this.running) | |
| 2451 | + throw new Error("signal() cannot be called on a container that is not running."); | |
| 2452 | + __container_signal(this._scope, signo).catch(() => {}); | |
| 2453 | + } | |
| 2454 | + getTcpPort(port) { | |
| 2455 | + if (!(Number.isInteger(port) && port > 0 && port < 65536)) | |
| 2456 | + throw new TypeError(`Invalid port number: ${port}`); | |
| 2457 | + return new ContainerPort(this._scope, port); | |
| 2458 | + } | |
| 2459 | + setInactivityTimeout(durationMs) { | |
| 2460 | + if (!(durationMs > 0)) | |
| 2461 | + throw new Error(`setInactivityTimeout() requires durationMs > 0, got ${durationMs}`); | |
| 2462 | + return __container_inactivity(this._scope, durationMs); | |
| 2463 | + } | |
| 2464 | + async exec(cmd, options) { | |
| 2465 | + if (!this.running) | |
| 2466 | + throw new Error("exec() cannot be called on a container that is not running."); | |
| 2467 | + if (!Array.isArray(cmd) || cmd.length === 0) | |
| 2468 | + throw new TypeError("exec() requires a non-empty command array."); | |
| 2469 | + const o = options ?? {}; | |
| 2470 | + const stdoutMode = __execOutputMode(o.stdout, "stdout"); | |
| 2471 | + const stderrMode = __execOutputMode(o.stderr, "stderr"); | |
| 2472 | + const combined = stderrMode === "combined"; | |
| 2473 | + if (combined && stdoutMode !== "pipe") | |
| 2474 | + throw new TypeError('stderr: "combined" requires stdout to be "pipe".'); | |
| 2475 | + if (o.cwd !== undefined && String(o.cwd).includes("\0")) | |
| 2476 | + throw new TypeError("cwd cannot contain '\\0' characters."); | |
| 2477 | + if (o.user !== undefined && String(o.user).includes("\0")) | |
| 2478 | + throw new TypeError("user cannot contain '\\0' characters."); | |
| 2479 | + let stdinMode = "none"; | |
| 2480 | + if (o.stdin !== undefined) { | |
| 2481 | + if (o.stdin === "pipe") stdinMode = "pipe"; | |
| 2482 | + else if (o.stdin instanceof ReadableStream) stdinMode = "stream"; | |
| 2483 | + else throw new TypeError('stdin must be a ReadableStream or the string "pipe".'); | |
| 2484 | + } | |
| 2485 | + const params = { | |
| 2486 | + cmd: Array.from(cmd, String), | |
| 2487 | + env: __containerEnvList(o.env), | |
| 2488 | + combined, | |
| 2489 | + }; | |
| 2490 | + if (o.cwd !== undefined) params.cwd = String(o.cwd); | |
| 2491 | + if (o.user !== undefined) params.user = String(o.user); | |
| 2492 | + const { id, pid } = JSON.parse( | |
| 2493 | + await __container_exec(this._scope, JSON.stringify(params)), | |
| 2494 | + ); | |
| 2495 | + if (stdinMode === "stream") { | |
| 2496 | + // Pump the caller's stream to the process; the pump is pending work | |
| 2497 | + // of the event, like a subrequest body. | |
| 2498 | + (async () => { | |
| 2499 | + const reader = o.stdin.getReader(); | |
| 2500 | + try { | |
| 2501 | + for (;;) { | |
| 2502 | + const { value, done } = await reader.read(); | |
| 2503 | + if (done) break; | |
| 2504 | + await __container_exec_write(id, __bytesOf(value)); | |
| 2505 | + } | |
| 2506 | + } finally { | |
| 2507 | + await __container_exec_close(id); | |
| 2508 | + } | |
| 2509 | + })().catch(() => {}); | |
| 2510 | + } else if (stdinMode === "none") { | |
| 2511 | + __container_exec_close(id).catch(() => {}); | |
| 2512 | + } | |
| 2513 | + return new ContainerExecProcess(id, pid, stdinMode, stdoutMode, stderrMode); | |
| 2514 | + } | |
| 2515 | + inspect() { | |
| 2516 | + return Promise.reject(new Error("inspect() is not implemented in celld")); | |
| 2517 | + } | |
| 2518 | + snapshotDirectory() { | |
| 2519 | + return Promise.reject(new Error("snapshotDirectory() is not implemented in celld")); | |
| 2520 | + } | |
| 2521 | + snapshotContainer() { | |
| 2522 | + return Promise.reject(new Error("snapshotContainer() is not implemented in celld")); | |
| 2523 | + } | |
| 2524 | + interceptOutboundHttp() { | |
| 2525 | + return Promise.reject(new Error("interceptOutboundHttp() is not implemented in celld")); | |
| 2526 | + } | |
| 2527 | + interceptOutboundHttps() { | |
| 2528 | + return Promise.reject(new Error("interceptOutboundHttps() is not implemented in celld")); | |
| 2529 | + } | |
| 2530 | + interceptAllOutboundHttp() { | |
| 2531 | + return Promise.reject(new Error("interceptAllOutboundHttp() is not implemented in celld")); | |
| 2532 | + } | |
| 2533 | + interceptOutboundTcp() { | |
| 2534 | + return Promise.reject(new Error("interceptOutboundTcp() is not implemented in celld")); | |
| 2535 | + } | |
| 2536 | +} | |
| 2537 | +class DurableObjectState { | |
| 2538 | + constructor(scope) { | |
| 2539 | + this._scope = scope; | |
| 2540 | + this._aborted = false; | |
| 2541 | + this.storage = new DurableObjectStorage(scope, this); | |
| 2542 | + this.facets = new DurableObjectFacets(this); | |
| 2543 | + this._gate = Promise.resolve(); | |
| 2544 | + this._blockDepth = 0; | |
| 2545 | + const facet = __cell.facetConfigs[scope]; | |
| 2546 | + this._facetDepth = facet?.depth ?? 0; | |
| 2547 | + const separator = scope.indexOf(":"); | |
| 2548 | + const className = separator < 0 ? scope : scope.slice(0, separator); | |
| 2549 | + const value = facet?.id ?? (separator < 0 ? scope : scope.slice(separator + 1)); | |
| 2550 | + this.id = new DurableObjectId( | |
| 2551 | + className, value, __cell.idNames[scope], | |
| 2552 | + ); | |
| 2553 | + this.props = facet?.props; | |
| 2554 | + // A class outside `containers` has no `ctx.container`, which is what | |
| 2555 | + // the `@cloudflare/containers` constructor checks. | |
| 2556 | + if (__cell.containers[className]) this.container = new Container(scope); | |
| 2557 | + } | |
| 2558 | + // Workerd's DurableObjectState.exports (actor-state.h): the same | |
| 2559 | + // loopback surface as ctx.exports on stateless entrypoints. | |
| 2560 | + get exports() { return __ctxExports(); } | |
| 2561 | + blockConcurrencyWhile(f) { | |
| 2562 | + // The native context binds the gate and its operations to one driver. | |
| 2563 | + // Its async continuations keep that driver even inside a foreign turn. | |
| 2564 | + return __with_input_gate_context(() => this._blockConcurrencyWhile(f)); | |
| 2565 | + } | |
| 2566 | + _blockConcurrencyWhile(f) { | |
| 2567 | + if (typeof f !== "function") | |
| 2568 | + throw new TypeError("blockConcurrencyWhile() requires a function"); | |
| 2569 | + if (this._blockDepth >= 64) | |
| 2570 | + throw new Error( | |
| 2571 | + "blockConcurrencyWhile() calls are nested too deeply.", | |
| 2572 | + ); | |
| 2573 | + if (this._blockDepth > 0) { | |
| 2574 | + // A stale reaction can run while an unrelated live block makes this | |
| 2575 | + // actor's depth nonzero. It cannot ride that hold when either half of | |
| 2576 | + // its retained [origin, driver] pair has already retired. | |
| 2577 | + if (__io_context_id() === "" || __io_context_id(true) === "") { | |
| 2578 | + return Promise.reject(new Error( | |
| 2579 | + "the cell event ended before it could acquire an input gate", | |
| 2580 | + )); | |
| 2581 | + } | |
| 2582 | + // A nested block rides the outer hold. One the outer body starts and | |
| 2583 | + // does not await would outlive that hold, and a `transaction()` | |
| 2584 | + // started that way is the shape that mattered: the outer block | |
| 2585 | + // returned, the gate opened, and another event wrote into the still | |
| 2586 | + // open transaction (#714). The outer block drains these before it | |
| 2587 | + // releases, so the hold lasts as long as any block under it. A nested | |
| 2588 | + // block that fails resets the object as any block does, and the outer | |
| 2589 | + // release must carry that failure, or the waiters would be admitted to | |
| 2590 | + // an object that no longer exists: the drain records it. | |
| 2591 | + const nested = this._runConcurrencyBlock(f); | |
| 2592 | + (this._nestedBlocks ||= []).push(nested.then(() => null, __describeFailure)); | |
| 2593 | + return nested; | |
| 2594 | + } | |
| 2595 | + // The host owns the gate (celld_logic::gate::InputGate). It replaces a | |
| 2596 | + // promise chain that could only order blocks against each other; the | |
| 2597 | + // gate sits at the delivery points, so nothing else is delivered to this | |
| 2598 | + // cell at all while the block runs. | |
| 2599 | + // | |
| 2600 | + // The acquire waits. It used to be synchronous, and had to be: a cell's | |
| 2601 | + // events came off one channel, so yielding even one microtask reopened a | |
| 2602 | + // window in which this cell delivered an event that then waited on a | |
| 2603 | + // gate nothing would release. Events are independent tasks now, so two | |
| 2604 | + // can reach a block together and the second has to queue -- and nothing | |
| 2605 | + // nests, so waiting cannot deadlock on an event suspended beneath it. | |
| 2606 | + // Asked for synchronously, awaited asynchronously, and the split is the | |
| 2607 | + // whole point. The op shuts the gate in this very call, so no event can | |
| 2608 | + // be delivered to this cell from here on -- that immediacy is what makes | |
| 2609 | + // `failCriticalSection()` reject a `ping()` issued right after it. | |
| 2610 | + // Waiting for the *ticket* is separate: events are independent tasks | |
| 2611 | + // now, so two of them can reach a block together and the second has to | |
| 2612 | + // queue behind the first. Calling this inside the async body instead | |
| 2613 | + // costs one microtask, and an event delivered in that window walks | |
| 2614 | + // straight into the critical section. | |
| 2615 | + const [eventText, owner, acquired] = __gate_acquire(this._scope); | |
| 2616 | + // An empty owner is an immediate refusal. Return its already-rejected | |
| 2617 | + // promise before recording the block, because no driver exists to settle | |
| 2618 | + // native work or to repair a readiness gate installed for stale work. | |
| 2619 | + if (owner === "") return acquired; | |
| 2620 | + const event = Number(eventText); | |
| 2621 | + const { block, record } = __blockEnter(this._scope, event, owner); | |
| 2622 | + const next = (async () => { | |
| 2623 | + try { | |
| 2624 | + await acquired; | |
| 2625 | + // A shutdown can retire the promise reaction while another event | |
| 2626 | + // owns this queued acquisition. The owner still has to consume its | |
| 2627 | + // ticket, but the retired callback must not run. | |
| 2628 | + if (record.retired) { | |
| 2629 | + __gate_release(this._scope, event, owner, null); | |
| 2630 | + return; | |
| 2631 | + } | |
| 2632 | + block.holder = event; | |
| 2633 | + // A critical section that fails resets the actor, so whatever queued | |
| 2634 | + // behind its gate must be refused rather than handed to the reset | |
| 2635 | + // one -- it was sent to a cell whose state no longer exists. The | |
| 2636 | + // failure rides with the release for that: waiters are woken with it | |
| 2637 | + // instead of merely woken. | |
| 2638 | + let failure = null; | |
| 2639 | + try { | |
| 2640 | + return await this._runConcurrencyBlock(f); | |
| 2641 | + } catch (error) { | |
| 2642 | + failure = __describeFailure(error); | |
| 2643 | + throw error; | |
| 2644 | + } finally { | |
| 2645 | + // Nested blocks are drained only after a body that returned: a | |
| 2646 | + // body that failed has reset the object, its waiters are refused | |
| 2647 | + // whatever the nested blocks do, and waiting for them would only | |
| 2648 | + // delay the refusal and a transaction's rollback behind it. Each | |
| 2649 | + // nested block has its own limit, so a drain is bounded by the | |
| 2650 | + // last one started, as workerd's nested critical sections are. | |
| 2651 | + while (failure === null && this._nestedBlocks && this._nestedBlocks.length > 0) { | |
| 2652 | + for (const nestedFailure of await Promise.all(this._nestedBlocks.splice(0))) { | |
| 2653 | + if (nestedFailure !== null && failure === null) failure = nestedFailure; | |
| 2654 | + } | |
| 2655 | + } | |
| 2656 | + this._nestedBlocks = undefined; | |
| 2657 | + __gate_release(this._scope, event, owner, failure); | |
| 2658 | + } | |
| 2659 | + } finally { | |
| 2660 | + // Also on a rejected `acquired`: the block ahead failed, this one | |
| 2661 | + // never ran, and the cell must not stay shut on its behalf. | |
| 2662 | + __blockLeave(this._scope, block, event); | |
| 2663 | + } | |
| 2664 | + })(); | |
| 2665 | + // `_ready()` awaits this. The host gate stops *other* events, but a | |
| 2666 | + // block taken in the constructor runs inside the very event that is | |
| 2667 | + // being delivered, so nothing external can hold that event back -- the | |
| 2668 | + // promise does. Concurrent blocks within one event go through | |
| 2669 | + // `_blockDepth` above and never reach here. | |
| 2670 | + this._gate = Promise.all([this._gate, record.ready]).then(() => undefined); | |
| 2671 | + // `_ready()` observes the original promise. This extra handler prevents | |
| 2672 | + // a constructor-time rejection from becoming unhandled before an event | |
| 2673 | + // reaches `_ready()`. | |
| 2674 | + this._gate.catch(() => {}); | |
| 2675 | + next.then(record.settleReady, record.rejectReady); | |
| 2676 | + return next; | |
| 2677 | + } | |
| 2678 | + _runConcurrencyBlock(f) { | |
| 2679 | + this._blockDepth++; | |
| 2680 | + let result; | |
| 2681 | + try { | |
| 2682 | + result = f(); | |
| 2683 | + } catch (error) { | |
| 2684 | + this._blockDepth--; | |
| 2685 | + this._resetAfterConcurrencyFailure(error); | |
| 2686 | + throw error; | |
| 2687 | + } | |
| 2688 | + const timerId = __timer_alloc(); | |
| 2689 | + let settled = false; | |
| 2690 | + const timeout = __op_timer( | |
| 2691 | + timerId, | |
| 2692 | + 30_000, | |
| 2693 | + ).then(() => { | |
| 2694 | + if (!settled) { | |
| 2695 | + throw new Error( | |
| 2696 | + "A call to blockConcurrencyWhile() in a Durable Object waited for " + | |
| 2697 | + "too long. The call was canceled and the Durable Object was reset.", | |
| 2698 | + ); | |
| 2699 | + } | |
| 2700 | + }); | |
| 2701 | + return Promise.race([Promise.resolve(result), timeout]).then( | |
| 2702 | + (value) => { | |
| 2703 | + settled = true; | |
| 2704 | + __timer_cancel(timerId); | |
| 2705 | + this._blockDepth--; | |
| 2706 | + return value; | |
| 2707 | + }, | |
| 2708 | + (error) => { | |
| 2709 | + settled = true; | |
| 2710 | + __timer_cancel(timerId); | |
| 2711 | + this._blockDepth--; | |
| 2712 | + this._resetAfterConcurrencyFailure(error); | |
| 2713 | + throw error; | |
| 2714 | + }, | |
| 2715 | + ); | |
| 2716 | + } | |
| 2717 | + _resetAfterConcurrencyFailure(error) { | |
| 2718 | + if (this._aborted) return; | |
| 2719 | + this._aborted = true; | |
| 2720 | + __storage_cancel_pending_puts(this._scope); | |
| 2721 | + const instance = __cell.instances[this._scope]; | |
| 2722 | + if (instance && instance.__celldState === this) | |
| 2723 | + delete __cell.instances[this._scope]; | |
| 2724 | + // Under a stub-mediated caller (this scope is not the current | |
| 2725 | + // event) the failure breaks the actor, as Workerd joins it | |
| 2726 | + // into the on-abort promise; a direct event keeps reset-only | |
| 2727 | + // semantics -- its caller sees the rejection itself. | |
| 2728 | + if (__currentActorScope() !== this._scope) | |
| 2729 | + __actorBreak(this._scope, error); | |
| 2730 | + } | |
| 2731 | + abort(reason) { | |
| 2732 | + if (this._aborted) return; | |
| 2733 | + this._aborted = true; | |
| 2734 | + __storage_cancel_pending_puts(this._scope); | |
| 2735 | + const instance = __cell.instances[this._scope]; | |
| 2736 | + if (instance && instance.__celldState === this) | |
| 2737 | + delete __cell.instances[this._scope]; | |
| 2738 | + const message = reason instanceof Error | |
| 2739 | + ? reason.message | |
| 2740 | + : String(reason); | |
| 2741 | + // Direct host-dispatched event on this actor: the uncatchable | |
| 2742 | + // terminate_execution path. Under a same-isolate stub caller, | |
| 2743 | + // termination would unwind the caller too, so break in JS. | |
| 2744 | + if (__currentActorScope() === this._scope) { | |
| 2745 | + __actor_abort(this._scope, message); | |
| 2746 | + return; | |
| 2747 | + } | |
| 2748 | + __actorBreak(this._scope, | |
| 2749 | + reason instanceof Error ? reason : new Error(message)); | |
| 2750 | + } | |
| 2751 | + _ready() { return this._gate; } | |
| 2752 | + getWebSockets(tag) { | |
| 2753 | + return JSON.parse(__ws_list(this._scope, tag)).map((row) => __socketFromRow(row)); | |
| 2754 | + } | |
| 2755 | + getTags(ws) { | |
| 2756 | + if (!(ws instanceof WebSocket) || !ws._hibernatable) { | |
| 2757 | + throw new Error( | |
| 2758 | + "you must call 'acceptWebSocket()' before attempting to access " + | |
| 2759 | + "the tags of a WebSocket."); | |
| 2760 | + } | |
| 2761 | + return Array.from(ws._tags); | |
| 2762 | + } | |
| 2763 | + acceptWebSocket(ws, tags = []) { | |
| 2764 | + if (__heap_over_admission_share()) | |
| 2765 | + throw new Error( | |
| 2766 | + "the isolate is near its V8 heap limit, so it refused a " + | |
| 2767 | + "WebSocket (see CELLD_V8_HEAP_LIMIT_MB)"); | |
| 2768 | + ws._target = { id: ws._id, scope: this._scope }; | |
| 2769 | + if (ws._peer) ws._peer._target = ws._target; | |
| 2770 | + ws._hibernatable = true; | |
| 2771 | + if (ws._peer) ws._peer._hibernatable = true; | |
| 2772 | + ws._tags = Array.from(tags, String); | |
| 2773 | + __ws_accept(ws._id, this._scope, JSON.stringify(ws._tags)); | |
| 2774 | + __sockets.set(ws._id, ws); | |
| 2775 | + } | |
| 2776 | + _socket(id) { | |
| 2777 | + return __sockets.get(Number(id)) || | |
| 2778 | + this.getWebSockets().find((ws) => ws._id === id) || | |
| 2779 | + __wsStub(id); | |
| 2780 | + } | |
| 2781 | + // Workerd actor-state.c++ setWebSocketAutoResponse: no pair unsets, and | |
| 2782 | + // each side is capped at 2048 UTF-8 bytes. The pair itself lives in the | |
| 2783 | + // shell -- a matched message is answered without waking this cell. | |
| 2784 | + setWebSocketAutoResponse(pair) { | |
| 2785 | + if (pair === undefined || pair === null) { | |
| 2786 | + __ws_auto_response_set(this._scope, null, null); | |
| 2787 | + return; | |
| 2788 | + } | |
| 2789 | + if (!(pair instanceof WebSocketRequestResponsePair)) | |
| 2790 | + throw new TypeError( | |
| 2791 | + "Failed to execute 'setWebSocketAutoResponse' on " + | |
| 2792 | + "'DurableObjectState': parameter 1 is not of type " + | |
| 2793 | + "'WebSocketRequestResponsePair'.", | |
| 2794 | + ); | |
| 2795 | + const max = 2048; | |
| 2796 | + const bytes = (s) => new TextEncoder().encode(s).length; | |
| 2797 | + const requestSize = bytes(pair.request); | |
| 2798 | + if (requestSize > max) | |
| 2799 | + throw new RangeError( | |
| 2800 | + `Request cannot be larger than ${max} bytes. ` + | |
| 2801 | + `A request of size ${requestSize} was provided.`, | |
| 2802 | + ); | |
| 2803 | + const responseSize = bytes(pair.response); | |
| 2804 | + if (responseSize > max) | |
| 2805 | + throw new RangeError( | |
| 2806 | + `Response cannot be larger than ${max} bytes. ` + | |
| 2807 | + `A response of size ${responseSize} was provided.`, | |
| 2808 | + ); | |
| 2809 | + __ws_auto_response_set(this._scope, pair.request, pair.response); | |
| 2810 | + } | |
| 2811 | + getWebSocketAutoResponse() { | |
| 2812 | + const pair = JSON.parse(__ws_auto_response_get(this._scope)); | |
| 2813 | + if (pair === null) return null; | |
| 2814 | + return new WebSocketRequestResponsePair(pair[0], pair[1]); | |
| 2815 | + } | |
| 2816 | + getWebSocketAutoResponseTimestamp(ws) { | |
| 2817 | + const ms = __ws_auto_response_ts(ws._id); | |
| 2818 | + return ms === null ? null : new Date(ms); | |
| 2819 | + } | |
| 2820 | + waitUntil(promise) { | |
| 2821 | + __registerWaitUntil(promise); | |
| 2822 | + } | |
| 2823 | +} | |
| 2824 | +function _instance(scope) { | |
| 2825 | + let inst = __cell.instances[scope]; | |
| 2826 | + if (!inst) { | |
| 2827 | + const className = scope.split(":")[0]; | |
| 2828 | + const cls = __cell.classes[className]; | |
| 2829 | + if (!cls) throw new Error("no DO class " + className); | |
| 2830 | + const state = new DurableObjectState(scope); | |
| 2831 | + inst = new cls(state, __cell.env); | |
| 2832 | + Object.defineProperty(inst, "__celldState", { value: state }); | |
| 2833 | + // Workerd worker-rpc.c++ getTargetInfo(): RPC needs `extends | |
| 2834 | + // DurableObject` unless the js_rpc compat flag is on. Decided | |
| 2835 | + // once here; dispatch reads a boolean. | |
| 2836 | + state._rpcOk = __cell.compat.jsRpc || | |
| 2837 | + __cell.doExports[className] === true; | |
| 2838 | + __cell.instances[scope] = inst; | |
| 2839 | + } | |
| 2840 | + return inst; | |
| 2841 | +} | |
| 2842 | +async function _readyInstance(scope) { | |
| 2843 | + const inst = _instance(scope); | |
| 2844 | + await inst.__celldState._ready(); | |
| 2845 | + return inst; | |
| 2846 | +} | |
| 2847 | +const __actorEventStack = []; | |
| 2848 | +const __currentActorEvent = () => { | |
| 2849 | + const context = String(__io_context_id()); | |
| 2850 | + if (context === "") return undefined; | |
| 2851 | + for (let index = __actorEventStack.length - 1; index >= 0; index--) { | |
| 2852 | + const event = __actorEventStack[index]; | |
| 2853 | + if (event.context === context) return event; | |
| 2854 | + } | |
| 2855 | + return undefined; | |
| 2856 | +}; | |
| 2857 | +const __currentActorScope = () => __currentActorEvent()?.scope ?? ""; | |
| 2858 | +const __beginActorEvent = (scope) => { | |
| 2859 | + __rpcSignalRefresh(); | |
| 2860 | + const event = { scope, context: String(__io_context_id()) }; | |
| 2861 | + __actorEventStack.push(event); | |
| 2862 | + return event; | |
| 2863 | +}; | |
| 2864 | +const __endActorEvent = (event) => { | |
| 2865 | + const index = __actorEventStack.lastIndexOf(event); | |
| 2866 | + if (index >= 0) __actorEventStack.splice(index, 1); | |
| 2867 | +}; | |
| 2868 | +const __endActorEventsForContext = (context) => { | |
| 2869 | + for (let index = __actorEventStack.length - 1; index >= 0; index--) { | |
| 2870 | + if (__actorEventStack[index].context === context) | |
| 2871 | + __actorEventStack.splice(index, 1); | |
| 2872 | + } | |
| 2873 | +}; | |
| 2874 | +const __incomingRequestSignals = new Map(); | |
| 2875 | +const __abortSignal = (signal, reason) => { | |
| 2876 | + if (signal.aborted) return; | |
| 2877 | + signal.aborted = true; | |
| 2878 | + signal.reason = reason; | |
| 2879 | + signal.dispatchEvent(new Event("abort")); | |
| 2880 | +}; | |
| 2881 | +const __abortIncomingRequest = __celld.__abortIncomingRequest = (requestId) => { | |
| 2882 | + const signal = __incomingRequestSignals.get(String(requestId)); | |
| 2883 | + if (signal && !signal.aborted) { | |
| 2884 | + __abortSignal(signal, new Error("The client has disconnected")); | |
| 2885 | + return true; | |
| 2886 | + } | |
| 2887 | + return false; | |
| 2888 | +}; | |
| 2889 | +__celld.__registerIncomingRequest = (requestId, request) => { | |
| 2890 | + __incomingRequestSignals.set(String(requestId), request.signal); | |
| 2891 | +}; | |
| 2892 | +__celld.__finishIncomingRequest = (requestId) => { | |
| 2893 | + __incomingRequestSignals.delete(String(requestId)); | |
| 2894 | +}; | |
| 2895 | +__celld.__retireInputGateContext = (context) => { | |
| 2896 | + for (const [scope, block] of __cellBlocks) { | |
| 2897 | + const retired = [...block.events].filter(([, record]) => | |
| 2898 | + record.owner === context || record.reaction === context | |
| 2899 | + ); | |
| 2900 | + if (retired.length === 0) continue; | |
| 2901 | + const holder = retired.find(([event]) => block.holder === event); | |
| 2902 | + if (holder === undefined) { | |
| 2903 | + // A queued callback has not changed the actor. Remove only that | |
| 2904 | + // callback, and let an unrelated holder continue with the same state. | |
| 2905 | + for (const [event, record] of retired) { | |
| 2906 | + record.retired = true; | |
| 2907 | + record.settleReady(); | |
| 2908 | + block.events.delete(event); | |
| 2909 | + if (record.actorEvent !== undefined) | |
| 2910 | + __endActorEvent(record.actorEvent); | |
| 2911 | + } | |
| 2912 | + if (block.events.size === 0 && __cellBlocks.get(scope) === block) | |
| 2913 | + __cellBlocks.delete(scope); | |
| 2914 | + continue; | |
| 2915 | + } | |
| 2916 | + // A running callback changed this actor and cannot reach its own | |
| 2917 | + // `finally`. Reset the actor, and release the host gate when the context | |
| 2918 | + // that started the callback differs from the turn that owns its work. | |
| 2919 | + const [holderEvent, holderRecord] = holder; | |
| 2920 | + __gate_release( | |
| 2921 | + scope, | |
| 2922 | + holderEvent, | |
| 2923 | + holderRecord.owner, | |
| 2924 | + "the cell's critical section ended without releasing", | |
| 2925 | + ); | |
| 2926 | + const instance = __cell.instances[scope]; | |
| 2927 | + if (instance !== undefined) instance.__celldState._aborted = true; | |
| 2928 | + __storage_cancel_pending_puts(scope); | |
| 2929 | + if (instance !== undefined && __cell.instances[scope] === instance) | |
| 2930 | + delete __cell.instances[scope]; | |
| 2931 | + for (const record of block.events.values()) { | |
| 2932 | + record.retired = true; | |
| 2933 | + record.settleReady(); | |
| 2934 | + if (record.actorEvent !== undefined) | |
| 2935 | + __endActorEvent(record.actorEvent); | |
| 2936 | + } | |
| 2937 | + // The old actor cannot run any block `finally`. A later event creates an | |
| 2938 | + // instance whose ready promise contains none of this actor's work. | |
| 2939 | + if (__cellBlocks.get(scope) === block) __cellBlocks.delete(scope); | |
| 2940 | + } | |
| 2941 | + __endActorEventsForContext(context); | |
| 2942 | +}; | |
| 2943 | +// Race a pending dispatch against the caller's abort signal: on abort, | |
| 2944 | +// run `abandon` (which reaches the target's side) and reject with the | |
| 2945 | +// caller's reason. The dispatch keeps its settle handlers, so a late | |
| 2946 | +// settlement after abandonment cannot trip the unhandled-rejection | |
| 2947 | +// signal. | |
| 2948 | +const __raceCallerAbort = (dispatch, signal, abandon) => | |
| 2949 | + new Promise((resolve, reject) => { | |
| 2950 | + let settled = false; | |
| 2951 | + const onAbort = () => { | |
| 2952 | + if (settled) return; | |
| 2953 | + settled = true; | |
| 2954 | + abandon(); | |
| 2955 | + reject(signal.reason); | |
| 2956 | + }; | |
| 2957 | + signal.addEventListener("abort", onAbort, { once: true }); | |
| 2958 | + dispatch.then( | |
| 2959 | + (value) => { | |
| 2960 | + if (settled) return; | |
| 2961 | + settled = true; | |
| 2962 | + signal.removeEventListener("abort", onAbort); | |
| 2963 | + resolve(value); | |
| 2964 | + }, | |
| 2965 | + (error) => { | |
| 2966 | + if (settled) return; | |
| 2967 | + settled = true; | |
| 2968 | + signal.removeEventListener("abort", onAbort); | |
| 2969 | + reject(error); | |
| 2970 | + }, | |
| 2971 | + ); | |
| 2972 | + }); | |
| 2973 | +const __awaitCancellableDoCall = (operation, signal) => { | |
| 2974 | + if (signal.aborted) { | |
| 2975 | + __do_call_cancel(operation.__celldCancelId); | |
| 2976 | + return Promise.reject(signal.reason); | |
| 2977 | + } | |
| 2978 | + return __raceCallerAbort(operation, signal, | |
| 2979 | + () => __do_call_cancel(operation.__celldCancelId)); | |
| 2980 | +}; | |
| 2981 | +// Workerd semantics: a Response crossing a service binding is a fresh | |
| 2982 | +// fetch-shaped Response -- immutable headers, default reason phrase, | |
| 2983 | +// the request URL, and a real body stream -- never the callee's own | |
| 2984 | +// mutable object. | |
| 2985 | +const __STATUS_TEXT = { | |
| 2986 | + 100: "Continue", 101: "Switching Protocols", 102: "Processing", | |
| 2987 | + 103: "Early Hints", 200: "OK", 201: "Created", 202: "Accepted", | |
| 2988 | + 203: "Non-Authoritative Information", 204: "No Content", | |
| 2989 | + 205: "Reset Content", 206: "Partial Content", 207: "Multi-Status", | |
| 2990 | + 208: "Already Reported", 226: "IM Used", 300: "Multiple Choices", | |
| 2991 | + 301: "Moved Permanently", 302: "Found", 303: "See Other", | |
| 2992 | + 304: "Not Modified", 305: "Use Proxy", 307: "Temporary Redirect", | |
| 2993 | + 308: "Permanent Redirect", 400: "Bad Request", 401: "Unauthorized", | |
| 2994 | + 402: "Payment Required", 403: "Forbidden", 404: "Not Found", | |
| 2995 | + 405: "Method Not Allowed", 406: "Not Acceptable", | |
| 2996 | + 407: "Proxy Authentication Required", 408: "Request Timeout", | |
| 2997 | + 409: "Conflict", 410: "Gone", 411: "Length Required", | |
| 2998 | + 412: "Precondition Failed", 413: "Payload Too Large", | |
| 2999 | + 414: "URI Too Long", 415: "Unsupported Media Type", | |
| 3000 | + 416: "Range Not Satisfiable", 417: "Expectation Failed", | |
| 3001 | + 418: "I'm a teapot", 421: "Misdirected Request", | |
| 3002 | + 422: "Unprocessable Entity", 423: "Locked", 424: "Failed Dependency", | |
| 3003 | + 425: "Too Early", 426: "Upgrade Required", | |
| 3004 | + 428: "Precondition Required", 429: "Too Many Requests", | |
| 3005 | + 431: "Request Header Fields Too Large", | |
| 3006 | + 451: "Unavailable For Legal Reasons", 500: "Internal Server Error", | |
| 3007 | + 501: "Not Implemented", 502: "Bad Gateway", | |
| 3008 | + 503: "Service Unavailable", 504: "Gateway Timeout", | |
| 3009 | + 505: "HTTP Version Not Supported", 506: "Variant Also Negotiates", | |
| 3010 | + 507: "Insufficient Storage", 508: "Loop Detected", | |
| 3011 | + 510: "Not Extended", 511: "Network Authentication Required", | |
| 3012 | +}; | |
| 3013 | +const __ERROR_RESPONSE_MESSAGE = | |
| 3014 | + "Return value from serve handler must not be an error " + | |
| 3015 | + "response (like Response.error())"; | |
| 3016 | +const __wrapServiceResponse = (res, url) => { | |
| 3017 | + // Response.error() represents a Fetch network error, not an HTTP response. | |
| 3018 | + // Letting status 0 cross this seam turns it into an ordinary response and | |
| 3019 | + // makes callers continue after the target explicitly reported failure. | |
| 3020 | + if (res.type === "error" || res.status === 0) { | |
| 3021 | + throw new TypeError(__ERROR_RESPONSE_MESSAGE); | |
| 3022 | + } | |
| 3023 | + // A 101 that crossed isolates carries a target rather than a socket: the | |
| 3024 | + // pair's other end is in the isolate that answered, and the two cannot be | |
| 3025 | + // linked the way the loopback below links them. Give the caller a client | |
| 3026 | + // end the host can join to that target, on the same terms as a Durable | |
| 3027 | + // Object subrequest -- nothing binds until `accept()`, so a response | |
| 3028 | + // passed straight back out keeps the direct route to the real client. | |
| 3029 | + const bound = !res.webSocket && res._wsTarget && res.status === 101 | |
| 3030 | + ? new WebSocket(undefined, [], res._wsTarget) | |
| 3031 | + : undefined; | |
| 3032 | + const wrapped = new Response( | |
| 3033 | + // Buffered bodies re-stream (an empty buffer still yields a | |
| 3034 | + // stream, as over real HTTP); a streaming body passes through. | |
| 3035 | + res._bodyBytes !== null ? res._bodyBytes : res.body, | |
| 3036 | + { | |
| 3037 | + status: res.status, | |
| 3038 | + statusText: | |
| 3039 | + res.statusText || __STATUS_TEXT[res.status] || "", | |
| 3040 | + headers: res.headers, | |
| 3041 | + webSocket: res.webSocket || bound, | |
| 3042 | + __wsTarget: res._wsTarget, | |
| 3043 | + }, | |
| 3044 | + ); | |
| 3045 | + // The constructor copies headers, so mark the copy. | |
| 3046 | + Object.defineProperty(wrapped.headers, "_immutable", { value: true }); | |
| 3047 | + wrapped.url = url; | |
| 3048 | + // An upgraded pair whose both ends live in this isolate: link them | |
| 3049 | + // directly -- the host connection seam only reaches external | |
| 3050 | + // clients. Frames the handler queued before linking flush first. | |
| 3051 | + const client = wrapped.webSocket; | |
| 3052 | + if (wrapped.status === 101 && client && client._peer) { | |
| 3053 | + const server = client._peer; | |
| 3054 | + client._loopback = server; | |
| 3055 | + server._loopback = client; | |
| 3056 | + for (const frame of server._pending.splice(0)) { | |
| 3057 | + // "send-binary" joined this queue with outbound sockets; without a case | |
| 3058 | + // of its own it fell through to the close branch and tore the pair down | |
| 3059 | + // instead of delivering the frame. | |
| 3060 | + if (frame[0] === "send") | |
| 3061 | + queueMicrotask(() => client._dispatchMessage(frame[1])); | |
| 3062 | + else if (frame[0] === "send-binary") | |
| 3063 | + queueMicrotask(() => { | |
| 3064 | + const data = frame[1]; | |
| 3065 | + client._dispatchMessage( | |
| 3066 | + data instanceof ArrayBuffer ? data : data.buffer.slice( | |
| 3067 | + data.byteOffset, | |
| 3068 | + data.byteOffset + data.byteLength, | |
| 3069 | + ), | |
| 3070 | + ); | |
| 3071 | + }); | |
| 3072 | + else | |
| 3073 | + queueMicrotask( | |
| 3074 | + () => client._dispatchClose(frame[1], frame[2], true)); | |
| 3075 | + } | |
| 3076 | + } | |
| 3077 | + return wrapped; | |
| 3078 | +}; | |
| 3079 | +const __SERVICE_REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]); | |
| 3080 | +const __REQUEST_BODY_HEADERS = [ | |
| 3081 | + "content-encoding", "content-language", "content-length", | |
| 3082 | + "content-location", "content-type", "transfer-encoding", | |
| 3083 | +]; | |
| 3084 | +const __CROSS_ORIGIN_SENSITIVE_HEADERS = [ | |
| 3085 | + "authorization", "cookie", "proxy-authorization", | |
| 3086 | +]; | |
| 3087 | +// A service target only produces the first response. Fetch redirect handling | |
| 3088 | +// belongs to the caller, because the Location leaves through the caller's | |
| 3089 | +// ambient outbound policy rather than gaining the target service's authority. | |
| 3090 | +// Capture the replayable request state before dispatch: a same-isolate target | |
| 3091 | +// receives the Request itself and can consume or mutate it before it redirects. | |
| 3092 | +const __serviceRedirectState = (req) => ({ | |
| 3093 | + method: req.method, | |
| 3094 | + headers: req.headers.__celldHeaderList, | |
| 3095 | + body: req.body === null ? undefined | |
| 3096 | + : req._bodyBytes === null ? null : req._bodyBytes.slice(), | |
| 3097 | + signal: req._signalForSubrequests, | |
| 3098 | +}); | |
| 3099 | +const __finishServiceFetch = async (res, req, replay) => { | |
| 3100 | + const response = __wrapServiceResponse(res, req.url); | |
| 3101 | + if (!__SERVICE_REDIRECT_STATUSES.has(response.status)) return response; | |
| 3102 | + const location = response.headers.get("location"); | |
| 3103 | + if (location === null) return response; | |
| 3104 | + if (req.redirect === "manual") return response; | |
| 3105 | + | |
| 3106 | + // Nobody can consume the redirect response after this branch. Cancelling it | |
| 3107 | + // releases a cross-isolate body stream instead of waiting for its idle TTL. | |
| 3108 | + if (response.body !== null) { | |
| 3109 | + try { await response.body.cancel(); } catch { /* the redirect still wins */ } | |
| 3110 | + } | |
| 3111 | + if (req.redirect === "error") | |
| 3112 | + throw new TypeError("A redirect was returned for a request with redirect mode error."); | |
| 3113 | + | |
| 3114 | + const url = new URL(location, req.url).href; | |
| 3115 | + let method = replay.method; | |
| 3116 | + let body = replay.body; | |
| 3117 | + const headers = new Headers(replay.headers); | |
| 3118 | + if ((response.status === 301 || response.status === 302) && method === "POST" || | |
| 3119 | + response.status === 303 && method !== "GET" && method !== "HEAD") { | |
| 3120 | + method = "GET"; | |
| 3121 | + body = undefined; | |
| 3122 | + for (const name of __REQUEST_BODY_HEADERS) headers.delete(name); | |
| 3123 | + } else if (body === null) { | |
| 3124 | + // A transferred or live JavaScript stream has no replay copy. Fetch treats | |
| 3125 | + // the redirect as a network error instead of sending an empty replacement. | |
| 3126 | + throw new TypeError("Cannot follow a redirect with a non-replayable request body."); | |
| 3127 | + } | |
| 3128 | + // The ambient fetch starts a new native request, so its HTTP client cannot | |
| 3129 | + // know that these credentials came from another origin and remove them. Do | |
| 3130 | + // that at the service-to-network boundary before they can leak to Location. | |
| 3131 | + if (new URL(req.url).origin !== new URL(url).origin) { | |
| 3132 | + for (const name of __CROSS_ORIGIN_SENSITIVE_HEADERS) headers.delete(name); | |
| 3133 | + } | |
| 3134 | + const init = { method, headers, redirect: "follow" }; | |
| 3135 | + if (body !== undefined) init.body = body; | |
| 3136 | + if (replay.signal !== null) init.signal = replay.signal; | |
| 3137 | + const followed = await globalThis.fetch(url, init); | |
| 3138 | + followed.redirected = true; | |
| 3139 | + if (followed.url === "") followed.url = url; | |
| 3140 | + return followed; | |
| 3141 | +}; | |
| 3142 | +// `[[services]]` binding: a Fetcher pointed at another Worker in this | |
| 3143 | +// process. No identity to resolve, so it goes straight to __svc_call. | |
| 3144 | +// Worker Loader (Code Mode): spawn a fresh isolate from supplied code and | |
| 3145 | +// invoke its default or named entrypoint through the cross-isolate request and | |
| 3146 | +// RPC paths. | |
| 3147 | +// A Fetcher can cross into a loaded isolate only as this host-minted route. | |
| 3148 | +// Reading properties from a Proxy is not a trustworthy brand check, so the | |
| 3149 | +// metadata lives in a side table that application objects cannot forge. | |
| 3150 | +const __outboundMeta = new WeakMap(); | |
| 3151 | +const __loaderServiceMarker = "__celld$loaderSvc"; | |
| 3152 | +__celld.__makeLoader = () => { | |
| 3153 | + // `get(name, ...)` is memoized by name to one isolate; `load()` is anonymous. | |
| 3154 | + // A stub holds a Promise<id> so `getCode` may be async and load lazily. | |
| 3155 | + const byName = new Map(); | |
| 3156 | + const loaderOptions = (method, options, supportsLimits) => { | |
| 3157 | + if (options === null || options === undefined) return undefined; | |
| 3158 | + if (typeof options !== "object") | |
| 3159 | + throw new TypeError(method + "() options must be an object."); | |
| 3160 | + const extra = Object.keys(options).filter( | |
| 3161 | + (key) => key !== "props" && !(supportsLimits && key === "limits")); | |
| 3162 | + if (extra.length !== 0) | |
| 3163 | + throw new TypeError( | |
| 3164 | + method + '() does not support the option "' + extra.join('", "') + | |
| 3165 | + '".'); | |
| 3166 | + return options; | |
| 3167 | + }; | |
| 3168 | + // `props` cross to the loaded isolate by structured clone, on the same | |
| 3169 | + // transport that already carries the call's arguments (`__rpcOut` below). | |
| 3170 | + // JSON is the obvious alternative and it is wrong: JSON.stringify turns a | |
| 3171 | + // Map, a Set, a Date, a typed array, and a RegExp into a plain object or a | |
| 3172 | + // string and reports no error, so the callee reads a mangled value that the | |
| 3173 | + // same call's arguments would have carried intact. Encoding here, once per | |
| 3174 | + // loader API call, also rejects an unclonable value at that call rather than | |
| 3175 | + // at the first operation. | |
| 3176 | + const loaderPropsSc = (method, options) => { | |
| 3177 | + const props = loaderOptions(method, options, false)?.props; | |
| 3178 | + if (props === undefined) return undefined; | |
| 3179 | + // `lift` false: the props cross an isolate boundary, so a stub inside them | |
| 3180 | + // is a DataCloneError, exactly as a stub inside an argument of the same | |
| 3181 | + // call is. | |
| 3182 | + return __rpcOut(props, false); | |
| 3183 | + }; | |
| 3184 | + const loaderEntrypointOptions = (options) => { | |
| 3185 | + options = loaderOptions("getEntrypoint", options, true); | |
| 3186 | + const props = options?.props; | |
| 3187 | + return { | |
| 3188 | + propsSc: props === undefined ? undefined : __rpcOut(props, false), | |
| 3189 | + limitsJson: JSON.stringify(options?.limits ?? null), | |
| 3190 | + }; | |
| 3191 | + }; | |
| 3192 | + const makeEntrypoint = (loadPromise, entrypoint, propsSc, limitsJson) => { | |
| 3193 | + const target = { | |
| 3194 | + async fetch(input, init) { | |
| 3195 | + const { id, tails } = await loadPromise; | |
| 3196 | + const req = new Request(input, init); | |
| 3197 | + // The verbatim header list; see the note on the outbound `fetch`. | |
| 3198 | + // The loaded worker rebuilds a `Headers` from these pairs, so a | |
| 3199 | + // repeat and its casing survive the isolate boundary. | |
| 3200 | + const headers = JSON.stringify(req.headers.__celldHeaderList); | |
| 3201 | + const { body, streamId } = await __subrequestBody(req); | |
| 3202 | + const loaded = __loader_fetch( | |
| 3203 | + id, req.url, req.method, body, headers, streamId, entrypoint, | |
| 3204 | + propsSc === undefined ? new Uint8Array() : propsSc, | |
| 3205 | + limitsJson, tails.length !== 0); | |
| 3206 | + const response = tails.length === 0 ? loaded : loaded[0]; | |
| 3207 | + if (tails.length !== 0) { | |
| 3208 | + const delivery = loaded[1] | |
| 3209 | + .then((report) => JSON.parse(report)) | |
| 3210 | + .then((events) => Promise.allSettled( | |
| 3211 | + tails.map((tail) => tail.tail(events)))) | |
| 3212 | + .then((results) => { | |
| 3213 | + for (const result of results) { | |
| 3214 | + if (result.status === "rejected") | |
| 3215 | + console.error("Tail Worker failed:", result.reason); | |
| 3216 | + } | |
| 3217 | + }) | |
| 3218 | + .catch((error) => console.error("Tail delivery failed:", error)); | |
| 3219 | + // The loaded fetch answers before its report because the child can | |
| 3220 | + // still have waitUntil work. Keep this chain on the loader event so | |
| 3221 | + // its IoContext cannot retire and abort the report operation. | |
| 3222 | + __registerWaitUntil(delivery); | |
| 3223 | + } | |
| 3224 | + const r = JSON.parse(await response); | |
| 3225 | + const responseBody = r.streamId !== undefined | |
| 3226 | + ? new CelldHttpBodyStream(r.streamId) | |
| 3227 | + : r.body !== undefined ? r.body : Uint8Array.from(r.bodyBytes || []); | |
| 3228 | + return __wrapServiceResponse( | |
| 3229 | + new Response(responseBody, { status: r.status, headers: r.headers }), | |
| 3230 | + req.url); | |
| 3231 | + }, | |
| 3232 | + }; | |
| 3233 | + // Both the default and named entrypoints expose RPC: property access is a | |
| 3234 | + // callable pipeline node dispatched via __loader_rpc to that entrypoint in | |
| 3235 | + // the loaded worker (default -> the "default" export, which | |
| 3236 | + // register_entrypoints registers like any other). fetch stays on the | |
| 3237 | + // target. Only single-method calls are supported for now. | |
| 3238 | + const session = { | |
| 3239 | + get: () => Promise.reject(new Error( | |
| 3240 | + "Awaitable properties on loaded workers are not supported yet.")), | |
| 3241 | + call: (path, args) => (async () => { | |
| 3242 | + if (path.length !== 1) | |
| 3243 | + throw new Error( | |
| 3244 | + "Pipelined property paths on loaded workers are not supported " + | |
| 3245 | + "yet."); | |
| 3246 | + const { id } = await loadPromise; | |
| 3247 | + return __rpcDes( | |
| 3248 | + await __loader_rpc(id, entrypoint, path[0], __rpcOut(args, false), | |
| 3249 | + propsSc, limitsJson)); | |
| 3250 | + })(), | |
| 3251 | + }; | |
| 3252 | + return new Proxy(target, { | |
| 3253 | + get: (base, prop) => { | |
| 3254 | + if (prop === "then") return undefined; | |
| 3255 | + if (Reflect.has(base, prop)) return Reflect.get(base, prop); | |
| 3256 | + if (typeof prop !== "string") return undefined; | |
| 3257 | + return __makeNode(session, [prop], null); | |
| 3258 | + }, | |
| 3259 | + }); | |
| 3260 | + }; | |
| 3261 | + // Anonymous load() workers are evicted when their only stub is GC'd: the | |
| 3262 | + // finalizer drops the worker's isolate so it does not leak. Named get() | |
| 3263 | + // workers are retained by `byName` (memoized) and so are not registered. | |
| 3264 | + const finalizer = typeof FinalizationRegistry === "function" | |
| 3265 | + ? new FinalizationRegistry((id) => __loader_drop(id)) | |
| 3266 | + : null; | |
| 3267 | + const makeStub = (loadPromise, evictable) => { | |
| 3268 | + // Explicit disposal evicts the worker deterministically; the finalizer is | |
| 3269 | + // a GC backstop for anonymous stubs that are dropped without disposing. | |
| 3270 | + // __loader_drop is idempotent, so the two paths cannot double-free. | |
| 3271 | + const drop = () => { | |
| 3272 | + loadPromise.then(({ id }) => __loader_drop(id), () => {}); | |
| 3273 | + }; | |
| 3274 | + const stub = { | |
| 3275 | + getEntrypoint(name = null, options = {}) { | |
| 3276 | + const { propsSc, limitsJson } = loaderEntrypointOptions(options); | |
| 3277 | + return makeEntrypoint( | |
| 3278 | + loadPromise, name === null ? "default" : String(name), | |
| 3279 | + propsSc, limitsJson); | |
| 3280 | + }, | |
| 3281 | + getDurableObjectClass(name = null, options = {}) { | |
| 3282 | + return __makeDurableObjectClass( | |
| 3283 | + loadPromise.then(({ id }) => id), name, | |
| 3284 | + loaderPropsSc("getDurableObjectClass", options)); | |
| 3285 | + }, | |
| 3286 | + dispose: drop, | |
| 3287 | + }; | |
| 3288 | + if (typeof Symbol.dispose === "symbol") stub[Symbol.dispose] = drop; | |
| 3289 | + if (evictable && finalizer) | |
| 3290 | + loadPromise.then(({ id }) => finalizer.register(stub, id), () => {}); | |
| 3291 | + return stub; | |
| 3292 | + }; | |
| 3293 | + // JSON.stringify silently drops binary values, so each non-string module -- | |
| 3294 | + // an explicit module shape such as `{ wasm: bytes }` -- is normalized | |
| 3295 | + // first. JavaScript modules become plain strings, and wasm moves into a | |
| 3296 | + // side-band `[name, Uint8Array]` list so multi-MB blobs never take a | |
| 3297 | + // base64/JSON round-trip. | |
| 3298 | + const toBytes = (v) => v instanceof ArrayBuffer ? new Uint8Array(v) | |
| 3299 | + : ArrayBuffer.isView(v) | |
| 3300 | + ? new Uint8Array(v.buffer, v.byteOffset, v.byteLength) : null; | |
| 3301 | + const moduleKinds = [ | |
| 3302 | + "js", "cjs", "py", "text", "data", "json", "wasm", | |
| 3303 | + ]; | |
| 3304 | + const encodeLoaderEnv = (value) => { | |
| 3305 | + if (value === undefined || value === null) | |
| 3306 | + return { env: undefined, envRoutes: [] }; | |
| 3307 | + const envRoutes = []; | |
| 3308 | + const seen = new Map(); | |
| 3309 | + const project = (v) => { | |
| 3310 | + if (v === null || | |
| 3311 | + (typeof v !== "object" && typeof v !== "function")) return v; | |
| 3312 | + const cached = seen.get(v); | |
| 3313 | + if (cached !== undefined) return cached; | |
| 3314 | + const route = __outboundMeta.get(v); | |
| 3315 | + if (route !== undefined) { | |
| 3316 | + const marker = { [__loaderServiceMarker]: envRoutes.length }; | |
| 3317 | + seen.set(v, marker); | |
| 3318 | + envRoutes.push([ | |
| 3319 | + route.script, | |
| 3320 | + route.entrypoint, | |
| 3321 | + route.propsSc ?? (route.props === undefined | |
| 3322 | + ? new Uint8Array() : __rpcOut(route.props, false)), | |
| 3323 | + ]); | |
| 3324 | + return marker; | |
| 3325 | + } | |
| 3326 | + if (Object.prototype.hasOwnProperty.call(v, __loaderServiceMarker)) | |
| 3327 | + throw new DOMException( | |
| 3328 | + `Worker Loader env contains the reserved key ` + | |
| 3329 | + `${JSON.stringify(__loaderServiceMarker)}.`, | |
| 3330 | + "DataCloneError"); | |
| 3331 | + if (typeof v === "function" || v instanceof __cf.RpcTarget || | |
| 3332 | + __stubMeta.has(v) || __doStubMeta.has(v)) | |
| 3333 | + throw new DOMException( | |
| 3334 | + "Worker Loader env supports only Service Binding capabilities.", | |
| 3335 | + "DataCloneError"); | |
| 3336 | + if (v instanceof Map) { | |
| 3337 | + const out = new Map(); | |
| 3338 | + seen.set(v, out); | |
| 3339 | + for (const [key, item] of v) out.set(project(key), project(item)); | |
| 3340 | + return out; | |
| 3341 | + } | |
| 3342 | + if (v instanceof Set) { | |
| 3343 | + const out = new Set(); | |
| 3344 | + seen.set(v, out); | |
| 3345 | + for (const item of v) out.add(project(item)); | |
| 3346 | + return out; | |
| 3347 | + } | |
| 3348 | + const proto = Object.getPrototypeOf(v); | |
| 3349 | + if (!Array.isArray(v) && proto !== Object.prototype && proto !== null) | |
| 3350 | + return v; | |
| 3351 | + const out = Array.isArray(v) ? [] : {}; | |
| 3352 | + seen.set(v, out); | |
| 3353 | + for (const key of Object.keys(v)) out[key] = project(v[key]); | |
| 3354 | + return out; | |
| 3355 | + }; | |
| 3356 | + return { env: __sc_encode(project(value)), envRoutes }; | |
| 3357 | + }; | |
| 3358 | + const encodeModules = (c) => { | |
| 3359 | + if (c === null || typeof c !== "object" || c.modules === null | |
| 3360 | + || typeof c.modules !== "object") | |
| 3361 | + return { config: c, wasm: [], outbound: undefined, tails: [] }; | |
| 3362 | + // workerd requires the date, and names the missing value as it does. | |
| 3363 | + if (typeof c.compatibilityDate !== "string") | |
| 3364 | + throw new Error(`Invalid compatibility date: ${c.compatibilityDate}`); | |
| 3365 | + const modules = {}; | |
| 3366 | + const wasm = []; | |
| 3367 | + for (const [name, value] of Object.entries(c.modules)) { | |
| 3368 | + const wrapped = value !== null && typeof value === "object" ? value : {}; | |
| 3369 | + const explicitKinds = moduleKinds.filter((kind) => | |
| 3370 | + Object.prototype.hasOwnProperty.call(wrapped, kind) | |
| 3371 | + ); | |
| 3372 | + // An object is a module shape with one kind, as in workerd; bare bytes | |
| 3373 | + // are not a module. | |
| 3374 | + if (value !== null && typeof value === "object" && | |
| 3375 | + !(value instanceof WebAssembly.Module) && explicitKinds.length !== 1) | |
| 3376 | + throw new TypeError( | |
| 3377 | + "Each module must contain exactly one of 'js', 'cjs', 'text', " + | |
| 3378 | + `'data', 'json', 'py', or 'wasm'. Module '${name}' contained ` + | |
| 3379 | + `${explicitKinds.length} properties.`); | |
| 3380 | + const kind = explicitKinds[0]; | |
| 3381 | + if (kind === "js") { | |
| 3382 | + const source = wrapped[kind]; | |
| 3383 | + if (typeof source !== "string") | |
| 3384 | + throw new TypeError( | |
| 3385 | + `Worker Loader module ${JSON.stringify(name)} field ` + | |
| 3386 | + `${JSON.stringify(kind)} must be a string.`); | |
| 3387 | + modules[name] = source; | |
| 3388 | + continue; | |
| 3389 | + } | |
| 3390 | + const bytes = kind === "wasm" ? toBytes(wrapped.wasm) : null; | |
| 3391 | + if (bytes !== null) wasm.push([name, bytes]); | |
| 3392 | + else modules[name] = value; | |
| 3393 | + } | |
| 3394 | + let outbound; | |
| 3395 | + let outboundProps; | |
| 3396 | + if (Object.prototype.hasOwnProperty.call(c, "globalOutbound")) { | |
| 3397 | + if (c.globalOutbound === undefined) { | |
| 3398 | + outbound = undefined; | |
| 3399 | + } else if (c.globalOutbound === null) { | |
| 3400 | + outbound = null; | |
| 3401 | + } else { | |
| 3402 | + const meta = __outboundMeta.get(c.globalOutbound); | |
| 3403 | + if (meta === undefined) | |
| 3404 | + throw new TypeError("globalOutbound must be a Fetcher or null."); | |
| 3405 | + // JSON carries only the host-minted route. Props use V8 structured | |
| 3406 | + // clone bytes, so their types and the cross-isolate clone boundary | |
| 3407 | + // match the other parameterized ctx.exports transports. | |
| 3408 | + outboundProps = meta.propsSc ?? (meta.props === undefined | |
| 3409 | + ? new Uint8Array() | |
| 3410 | + : __rpcOut(meta.props, false)); | |
| 3411 | + outbound = JSON.stringify({ | |
| 3412 | + script: meta.script, | |
| 3413 | + entrypoint: meta.entrypoint, | |
| 3414 | + }); | |
| 3415 | + } | |
| 3416 | + } | |
| 3417 | + const { env, envRoutes } = encodeLoaderEnv(c.env); | |
| 3418 | + let tails = []; | |
| 3419 | + if (Object.prototype.hasOwnProperty.call(c, "tails")) { | |
| 3420 | + if (!Array.isArray(c.tails)) | |
| 3421 | + throw new TypeError("tails must be an array of Fetchers."); | |
| 3422 | + tails = c.tails.map((tail) => { | |
| 3423 | + if (!__outboundMeta.has(tail)) | |
| 3424 | + throw new TypeError("tails must be an array of Fetchers."); | |
| 3425 | + return tail; | |
| 3426 | + }); | |
| 3427 | + } | |
| 3428 | + const { | |
| 3429 | + globalOutbound: _globalOutbound, | |
| 3430 | + env: _env, | |
| 3431 | + tails: _tails, | |
| 3432 | + ...rest | |
| 3433 | + } = c; | |
| 3434 | + return { | |
| 3435 | + config: { ...rest, modules }, wasm, outbound, outboundProps, | |
| 3436 | + env, envRoutes, tails, | |
| 3437 | + }; | |
| 3438 | + }; | |
| 3439 | + // getCode is deferred into a microtask so a throw (or async getCode) | |
| 3440 | + // surfaces as a rejection when the worker is first used, not at get()/load(). | |
| 3441 | + const loadFrom = (getCode) => | |
| 3442 | + Promise.resolve().then(getCode) | |
| 3443 | + .then((c) => { | |
| 3444 | + const { | |
| 3445 | + config, wasm, outbound, outboundProps, env, envRoutes, tails, | |
| 3446 | + } = encodeModules(c); | |
| 3447 | + const id = __loader_load( | |
| 3448 | + JSON.stringify(config), wasm, outbound, outboundProps, env, | |
| 3449 | + envRoutes, tails.length !== 0); | |
| 3450 | + return { id, tails }; | |
| 3451 | + }); | |
| 3452 | + return { | |
| 3453 | + load(code) { return makeStub(loadFrom(() => code), true); }, | |
| 3454 | + get(name, getCode) { | |
| 3455 | + let idPromise = byName.get(name); | |
| 3456 | + if (idPromise === undefined) { | |
| 3457 | + idPromise = loadFrom(getCode); | |
| 3458 | + byName.set(name, idPromise); | |
| 3459 | + } | |
| 3460 | + return makeStub(idPromise, false); | |
| 3461 | + }, | |
| 3462 | + }; | |
| 3463 | +}; | |
| 3464 | + | |
| 3465 | +const __makeServiceBinding = __celld.__makeServiceBinding = | |
| 3466 | + (script, entrypoint = null, propsSc = undefined) => { | |
| 3467 | + const target = { | |
| 3468 | + async fetch(input, init) { | |
| 3469 | + const req = new Request(input, init); | |
| 3470 | + const signal = req._signalForSubrequests; | |
| 3471 | + if (signal?.aborted) throw signal.reason; | |
| 3472 | + // A stream body advertises its length the way the HTTP layer | |
| 3473 | + // would: known length -> Content-Length, unknown -> chunked. | |
| 3474 | + if (req._bodyBytes === null && | |
| 3475 | + !req.headers.has("content-length") && | |
| 3476 | + !req.headers.has("transfer-encoding")) { | |
| 3477 | + const length = req.body._expectedLength; | |
| 3478 | + if (length === undefined) | |
| 3479 | + req.headers.set("transfer-encoding", "chunked"); | |
| 3480 | + else req.headers.set("content-length", String(length)); | |
| 3481 | + } | |
| 3482 | + const redirectState = __serviceRedirectState(req); | |
| 3483 | + // Fast path: the target is this same script, so its handler lives in | |
| 3484 | + // this isolate. Skip the op + pool-thread hop and call it directly, | |
| 3485 | + // inside its own event so the target's waitUntil does not attach to | |
| 3486 | + // the caller's. Cross-script targets still need their own isolate. | |
| 3487 | + if (script === __cell.script && entrypoint !== null && | |
| 3488 | + propsSc === undefined) { | |
| 3489 | + // Mirror __dispatchTo: the target sees a fresh incoming signal, | |
| 3490 | + // aborted with "The client has disconnected" when the caller | |
| 3491 | + // abandons the call or cancels the response body; the caller's | |
| 3492 | + // own signal races the dispatch so an abandoned call rejects | |
| 3493 | + // immediately instead of pinning on a hung target. | |
| 3494 | + const requestController = new AbortController(); | |
| 3495 | + const dispatch = __dispatchEntrypointFetch( | |
| 3496 | + entrypoint, | |
| 3497 | + new Request(req, { | |
| 3498 | + signal: requestController.signal, | |
| 3499 | + __celldIncomingSignal: true, | |
| 3500 | + })); | |
| 3501 | + const response = signal | |
| 3502 | + ? await __raceCallerAbort(dispatch, signal, () => | |
| 3503 | + requestController.abort( | |
| 3504 | + new Error("The client has disconnected"))) | |
| 3505 | + : await dispatch; | |
| 3506 | + __attachResponseRequestCancellation( | |
| 3507 | + response, requestController, true); | |
| 3508 | + return __finishServiceFetch(response, req, redirectState); | |
| 3509 | + } | |
| 3510 | + if (script === __cell.script && entrypoint === null && | |
| 3511 | + typeof __cell.selfFetch === "function") { | |
| 3512 | + if (__cell.svcDepth >= 8) | |
| 3513 | + throw new Error( | |
| 3514 | + "Service binding recursion limit exceeded (8)"); | |
| 3515 | + __cell.svcDepth = (__cell.svcDepth || 0) + 1; | |
| 3516 | + const ctx = __beginEvent(); | |
| 3517 | + try { | |
| 3518 | + return __finishServiceFetch( | |
| 3519 | + await __ctxRun(undefined, | |
| 3520 | + () => __cell.selfFetch(req, __cell.env, ctx)), | |
| 3521 | + req, redirectState); | |
| 3522 | + } finally { | |
| 3523 | + __cell.svcDepth--; | |
| 3524 | + __endEvent(); | |
| 3525 | + } | |
| 3526 | + } | |
| 3527 | + // The verbatim header list; see the note on the outbound `fetch`. The | |
| 3528 | + // target isolate rebuilds a `Headers` from these pairs, so a repeat and | |
| 3529 | + // its casing survive the crossing. | |
| 3530 | + const headers = JSON.stringify(req.headers.__celldHeaderList); | |
| 3531 | + // Cross-isolate calls carry exact bytes. A host-backed stream transfers | |
| 3532 | + // its one source to the target, and another stream uses the byte fallback. | |
| 3533 | + const { body, streamId } = await __subrequestBody(req); | |
| 3534 | + const r = JSON.parse(await (signal | |
| 3535 | + ? __awaitCancellableDoCall( | |
| 3536 | + __svc_call_cancellable( | |
| 3537 | + script, req.url, req.method, body, headers, streamId, entrypoint, | |
| 3538 | + propsSc), | |
| 3539 | + signal) | |
| 3540 | + : __svc_call( | |
| 3541 | + script, req.url, req.method, body, headers, streamId, entrypoint, | |
| 3542 | + propsSc))); | |
| 3543 | + const responseBody = r.streamId !== undefined | |
| 3544 | + ? new CelldHttpBodyStream(r.streamId) | |
| 3545 | + : r.body !== undefined | |
| 3546 | + ? r.body | |
| 3547 | + : Uint8Array.from(r.bodyBytes || []); | |
| 3548 | + return __finishServiceFetch( | |
| 3549 | + new Response(responseBody, { | |
| 3550 | + status: r.status, headers: r.headers, __wsTarget: r.wsTarget, | |
| 3551 | + }), | |
| 3552 | + req, redirectState); | |
| 3553 | + }, | |
| 3554 | + // Workerd's test-visible Fetcher.scheduled(): invoke the target's | |
| 3555 | + // scheduled handler and report the outcome. | |
| 3556 | + async scheduled(options = {}) { | |
| 3557 | + if (script !== __cell.script || entrypoint !== null || | |
| 3558 | + typeof __cell.selfScheduled !== "function") | |
| 3559 | + throw new Error( | |
| 3560 | + "scheduled() is only implemented for same-script service " + | |
| 3561 | + "bindings whose target has a scheduled handler"); | |
| 3562 | + let noRetry = false; | |
| 3563 | + const ctrl = { | |
| 3564 | + scheduledTime: options.scheduledTime === undefined | |
| 3565 | + ? Date.now() : Number(options.scheduledTime), | |
| 3566 | + cron: options.cron === undefined ? "" : String(options.cron), | |
| 3567 | + noRetry() { noRetry = true; }, | |
| 3568 | + }; | |
| 3569 | + const ctx = __beginEvent(); | |
| 3570 | + try { | |
| 3571 | + await __cell.selfScheduled(ctrl, __cell.env, ctx); | |
| 3572 | + return { outcome: "ok", noRetry }; | |
| 3573 | + } finally { | |
| 3574 | + const drain = __endEvent(); | |
| 3575 | + // scheduled() reports the event outcome, so it cannot return while the | |
| 3576 | + // work that defines that event is still pending. Fetch replies differ: | |
| 3577 | + // a streamed response can depend on waitUntil work and must return first. | |
| 3578 | + if (drain !== null) await drain; | |
| 3579 | + } | |
| 3580 | + }, | |
| 3581 | + }; | |
| 3582 | + // An omitted entrypoint selects the module's default export, which may be a | |
| 3583 | + // WorkerEntrypoint or an object handler. `entrypoint = "Name"` selects that | |
| 3584 | + // named class. Any property other than a reserved Fetcher method is an | |
| 3585 | + // awaitable/callable pipeline node: awaiting | |
| 3586 | + // resolves the property remotely (a property-GET wire op), calling | |
| 3587 | + // invokes it, and deeper access extends the path, resolved on the | |
| 3588 | + // receiver side in one op. Same-script dispatch stays in this | |
| 3589 | + // isolate, so stub-able values may cross. A property path rooted | |
| 3590 | + // directly at the binding is context-free (ctx null): awaiting it | |
| 3591 | + // starts a fresh session, as in Workerd. | |
| 3592 | + const rpcEntrypoint = entrypoint === null ? "default" : entrypoint; | |
| 3593 | + const session = __entrypointSession( | |
| 3594 | + rpcEntrypoint, script === __cell.script, script, undefined, propsSc); | |
| 3595 | + const binding = new Proxy(target, { | |
| 3596 | + getPrototypeOf: () => __cf.ServiceStub.prototype, | |
| 3597 | + get: (base, prop) => { | |
| 3598 | + if (prop === "then") return undefined; // a stub is not a thenable | |
| 3599 | + if (Reflect.has(base, prop)) return Reflect.get(base, prop); | |
| 3600 | + if (typeof prop !== "string") return undefined; | |
| 3601 | + // Workerd's test hook: the named method as a callable handle, | |
| 3602 | + // resolved -- and refused -- on the receiver side. | |
| 3603 | + if (prop === "getRpcMethodForTestOnly") | |
| 3604 | + return (name) => __makeNode(session, [String(name)], null); | |
| 3605 | + return __makeNode(session, [prop], null); | |
| 3606 | + }}); | |
| 3607 | + __outboundMeta.set(binding, { script, entrypoint, propsSc }); | |
| 3608 | + return binding; | |
| 3609 | +}; | |
| 3610 | + | |
| 3611 | +__celld.__installLoaderEnv = (bytes, routes) => { | |
| 3612 | + const env = __sc_decode(bytes); | |
| 3613 | + const seen = new Set(); | |
| 3614 | + const revive = (v) => { | |
| 3615 | + if (v === null || typeof v !== "object") return v; | |
| 3616 | + const routeIndex = Object.prototype.hasOwnProperty.call( | |
| 3617 | + v, __loaderServiceMarker) ? v[__loaderServiceMarker] : undefined; | |
| 3618 | + if (Number.isSafeInteger(routeIndex) && routeIndex >= 0) { | |
| 3619 | + // Rust supplies flat [script, entrypoint, props] triples, and the marker | |
| 3620 | + // stores the triple index rather than an offset into that array. | |
| 3621 | + const routeOffset = routeIndex * 3; | |
| 3622 | + if (!Number.isSafeInteger(routeOffset) || routeOffset + 2 >= routes.length) | |
| 3623 | + throw new DOMException( | |
| 3624 | + "Worker Loader env contains an invalid capability.", | |
| 3625 | + "DataCloneError"); | |
| 3626 | + return __makeServiceBinding( | |
| 3627 | + routes[routeOffset], routes[routeOffset + 1], routes[routeOffset + 2]); | |
| 3628 | + } | |
| 3629 | + if (seen.has(v)) return v; | |
| 3630 | + seen.add(v); | |
| 3631 | + if (v instanceof Map) { | |
| 3632 | + const entries = [...v]; | |
| 3633 | + v.clear(); | |
| 3634 | + for (const [key, item] of entries) v.set(revive(key), revive(item)); | |
| 3635 | + return v; | |
| 3636 | + } | |
| 3637 | + if (v instanceof Set) { | |
| 3638 | + const items = [...v]; | |
| 3639 | + v.clear(); | |
| 3640 | + for (const item of items) v.add(revive(item)); | |
| 3641 | + return v; | |
| 3642 | + } | |
| 3643 | + if (Array.isArray(v) || Object.getPrototypeOf(v) === Object.prototype || | |
| 3644 | + Object.getPrototypeOf(v) === null) | |
| 3645 | + for (const key of Object.keys(v)) v[key] = revive(v[key]); | |
| 3646 | + return v; | |
| 3647 | + }; | |
| 3648 | + Object.assign(__cell.env, revive(env)); | |
| 3649 | +}; | |
| 3650 | +// RPC marshalling: V8 structured clone (Workerd js-rpc semantics), so | |
| 3651 | +// undefined, Date, Map, Set, BigInt, typed arrays, and cycles survive. | |
| 3652 | +// A value V8 cannot clone throws DataCloneError, as in Workerd. | |
| 3653 | +// | |
| 3654 | +// The envelope's first byte tags the payload. 0xff (the clone version | |
| 3655 | +// header) = plain clone, decoded as-is. 0x01 = clone of a lifted tree in | |
| 3656 | +// which RpcTarget instances, functions, and Durable Object stubs were | |
| 3657 | +// replaced by stub markers; the lift runs only after a plain clone | |
| 3658 | +// already threw. A projection walk happens first because V8 silently erases | |
| 3659 | +// custom and null prototypes. 0x02 = a lifted tree carrying only by-value | |
| 3660 | +// host types (Blob/File, Headers, | |
| 3661 | +// Request/Response) and no capabilities -- decoded like 0x01, but a | |
| 3662 | +// reply so tagged does not root its callee context. 0x00 = clone of | |
| 3663 | +// [error, ownProps] -- a callee exception crossing as a real Error. | |
| 3664 | +const __dataCloneError = (error) => new DOMException( | |
| 3665 | + String(error && error.message || error), "DataCloneError"); | |
| 3666 | +const __rpcUnsupportedType = (value) => new DOMException( | |
| 3667 | + 'Could not serialize object of type "' + | |
| 3668 | + (__util_constructor_name(value) || "Object") + | |
| 3669 | + '". This type does not support serialization.', | |
| 3670 | + "DataCloneError"); | |
| 3671 | +// V8 clones a user-class instance and a null-prototype object as plain data, | |
| 3672 | +// but Workerd refuses both over RPC. Project the value graph before V8 can | |
| 3673 | +// erase that distinction. The projection also snapshots enumerable getters, | |
| 3674 | +// so validation and serialization cannot invoke one getter twice. Native | |
| 3675 | +// clone types and RPC host types keep their own serializers. | |
| 3676 | +const __rpcProject = (value) => { | |
| 3677 | + const seen = new Map(); | |
| 3678 | + const originals = new WeakMap(); | |
| 3679 | + const set = (target, key, value) => Object.defineProperty(target, key, { | |
| 3680 | + value, enumerable: true, configurable: true, writable: true, | |
| 3681 | + }); | |
| 3682 | + const project = (v) => { | |
| 3683 | + if (v === null || (typeof v !== "object" && typeof v !== "function")) | |
| 3684 | + return v; | |
| 3685 | + const cached = seen.get(v); | |
| 3686 | + if (cached !== undefined) return cached; | |
| 3687 | + if (typeof v === "function" || v instanceof __cf.RpcTarget || | |
| 3688 | + __stubMeta.has(v) || __svcMeta.has(v) || __doStubMeta.has(v) || | |
| 3689 | + v instanceof Headers || v instanceof Blob || v instanceof Request || | |
| 3690 | + v instanceof Response || v instanceof ReadableStream || | |
| 3691 | + v instanceof WritableStream || v instanceof AbortSignal || | |
| 3692 | + v instanceof Date || v instanceof RegExp || v instanceof Error || | |
| 3693 | + v instanceof ArrayBuffer || ArrayBuffer.isView(v) || | |
| 3694 | + (typeof SharedArrayBuffer !== "undefined" && | |
| 3695 | + v instanceof SharedArrayBuffer) || | |
| 3696 | + (typeof CryptoKey !== "undefined" && v instanceof CryptoKey) || | |
| 3697 | + (typeof WebAssembly !== "undefined" && | |
| 3698 | + v instanceof WebAssembly.Module) || | |
| 3699 | + __util_proxy_details(v) !== undefined) return v; | |
| 3700 | + if (v instanceof Map) { | |
| 3701 | + const out = new Map(); | |
| 3702 | + seen.set(v, out); | |
| 3703 | + for (const [key, entry] of v) { | |
| 3704 | + out.set(project(key), project(entry)); | |
| 3705 | + } | |
| 3706 | + return out; | |
| 3707 | + } | |
| 3708 | + if (v instanceof Set) { | |
| 3709 | + const out = new Set(); | |
| 3710 | + seen.set(v, out); | |
| 3711 | + for (const entry of v) out.add(project(entry)); | |
| 3712 | + return out; | |
| 3713 | + } | |
| 3714 | + if (Array.isArray(v)) { | |
| 3715 | + const out = new Array(v.length); | |
| 3716 | + seen.set(v, out); | |
| 3717 | + originals.set(out, v); | |
| 3718 | + for (const key of Object.keys(v)) set(out, key, project(v[key])); | |
| 3719 | + return out; | |
| 3720 | + } | |
| 3721 | + if (Object.getPrototypeOf(v) !== Object.prototype) | |
| 3722 | + throw __rpcUnsupportedType(v); | |
| 3723 | + const out = {}; | |
| 3724 | + seen.set(v, out); | |
| 3725 | + originals.set(out, v); | |
| 3726 | + for (const key of Object.keys(v)) set(out, key, project(v[key])); | |
| 3727 | + return out; | |
| 3728 | + }; | |
| 3729 | + return { tree: project(value), originals }; | |
| 3730 | +}; | |
| 3731 | +const __tagged = (tag, sc) => { | |
| 3732 | + const out = new Uint8Array(sc.length + 1); | |
| 3733 | + out[0] = tag; | |
| 3734 | + out.set(sc, 1); | |
| 3735 | + return out; | |
| 3736 | +}; | |
| 3737 | +// ---- request-context confinement ------------------------------- | |
| 3738 | +// Workerd ties I/O objects to the IoContext of the event that made | |
| 3739 | +// them. Cells' equivalent: each dispatched event enters an | |
| 3740 | +// async-context frame (the same CPED the ALS rides, so it survives | |
| 3741 | +// awaits) carrying a context id. Stubs remember their owning | |
| 3742 | +// context and refuse to serialize elsewhere; pipeline nodes refuse | |
| 3743 | +// foreign awaits and calls -- each with Workerd's exact error. | |
| 3744 | +let __nextCtxId = 1; | |
| 3745 | +const __ctxKey = Symbol("celld.ctx"); | |
| 3746 | +const __ctxNow = () => { | |
| 3747 | + const frame = __als_get(); | |
| 3748 | + return frame === undefined ? undefined : frame.get(__ctxKey); | |
| 3749 | +}; | |
| 3750 | +// Run `fn` under context `id` (undefined = a fresh one). An async | |
| 3751 | +// fn started inside keeps the frame across its awaits. The prior | |
| 3752 | +// frame is cloned so user AsyncLocalStorage stores still flow into | |
| 3753 | +// same-isolate callees, as they did before contexts existed. | |
| 3754 | +const __ctxRun = (id, fn) => { | |
| 3755 | + const prior = __als_get(); | |
| 3756 | + const frame = new Map(prior); | |
| 3757 | + frame.set(__ctxKey, id ?? __nextCtxId++); | |
| 3758 | + __als_set(frame); | |
| 3759 | + try { | |
| 3760 | + return fn(); | |
| 3761 | + } finally { | |
| 3762 | + __als_set(prior); | |
| 3763 | + } | |
| 3764 | +}; | |
| 3765 | +const __ctxError = (kind) => new Error( | |
| 3766 | + "Cannot perform I/O on behalf of a different request. I/O " + | |
| 3767 | + "objects (such as streams, request/response bodies, and others) " + | |
| 3768 | + "created in the context of one request handler cannot be " + | |
| 3769 | + "accessed from a different request's handler. This is a " + | |
| 3770 | + "limitation of Cloudflare Workers which allows us to improve " + | |
| 3771 | + "overall performance. (I/O type: " + kind + ")"); | |
| 3772 | +// ---- abortable request contexts -------------------------------- | |
| 3773 | +// Workerd's ctx.abort(reason) on an entrypoint aborts the request's | |
| 3774 | +// IoContext: the in-flight call rejects with the reason, and stubs | |
| 3775 | +// the context holds are disposed (their disposal callbacks fire). | |
| 3776 | +// State is allocated only when a context first holds a stub handle | |
| 3777 | +// or aborts, so plain-data dispatch pays nothing; call paths gate | |
| 3778 | +// every abort lookup on `__abortedCtxs.size` (one field read). | |
| 3779 | +// Aborted ids stay recorded: a stub rooted in a dead context must | |
| 3780 | +// keep rejecting with the reason. | |
| 3781 | +const __abortedCtxs = new Map(); | |
| 3782 | +// An actor-flavored abort reason: in-flight ops reject with the | |
| 3783 | +// wrapped reason, later ops with Workerd's post-abort message | |
| 3784 | +// (upstream TODO(bug): should propagate the reason, but doesn't). | |
| 3785 | +class __ActorAbort { constructor(reason) { this.reason = reason; } } | |
| 3786 | +const __postAbortError = (aborted) => aborted instanceof __ActorAbort | |
| 3787 | + ? new Error("The execution context which hosts this callback " + | |
| 3788 | + "is no longer running.") | |
| 3789 | + : aborted; | |
| 3790 | +// ctx id -> Set of live stub handles (metas) the context holds. | |
| 3791 | +const __ctxStubs = new Map(); | |
| 3792 | +// ctx id -> Set of reject callbacks for stub ops in flight against | |
| 3793 | +// that context. A hung callee never settles, so a context abort | |
| 3794 | +// must reject its pending callers directly. | |
| 3795 | +const __ctxPendingOps = new Map(); | |
| 3796 | +const __opTrack = (ctx, reject) => { | |
| 3797 | + let set = __ctxPendingOps.get(ctx); | |
| 3798 | + if (set === undefined) __ctxPendingOps.set(ctx, set = new Set()); | |
| 3799 | + set.add(reject); | |
| 3800 | + return () => { | |
| 3801 | + set.delete(reject); | |
| 3802 | + if (set.size === 0) __ctxPendingOps.delete(ctx); | |
| 3803 | + }; | |
| 3804 | +}; | |
| 3805 | +const __ctxRegister = (meta) => { | |
| 3806 | + if (meta.ctx === undefined) return; | |
| 3807 | + let set = __ctxStubs.get(meta.ctx); | |
| 3808 | + if (set === undefined) __ctxStubs.set(meta.ctx, set = new Set()); | |
| 3809 | + set.add(meta); | |
| 3810 | +}; | |
| 3811 | +const __ctxUnregister = (meta) => { | |
| 3812 | + const set = __ctxStubs.get(meta.ctx); | |
| 3813 | + if (set === undefined) return; | |
| 3814 | + set.delete(meta); | |
| 3815 | + if (set.size === 0) __ctxStubs.delete(meta.ctx); | |
| 3816 | +}; | |
| 3817 | +// Tear down a context: dispose every handle it still holds, so a | |
| 3818 | +// dup() leaked into it reaches the sender's disposal callback. | |
| 3819 | +const __ctxEnd = (id) => { | |
| 3820 | + const set = __ctxStubs.get(id); | |
| 3821 | + if (set === undefined) return; | |
| 3822 | + __ctxStubs.delete(id); | |
| 3823 | + for (const meta of set) __disposeStub(meta); | |
| 3824 | +}; | |
| 3825 | +const __ctxAbort = (id, reason) => { | |
| 3826 | + if (id === undefined || __abortedCtxs.has(id)) return; | |
| 3827 | + const stored = reason === undefined | |
| 3828 | + ? new Error("The execution context has been aborted.") | |
| 3829 | + : reason; | |
| 3830 | + __abortedCtxs.set(id, stored); | |
| 3831 | + __ctxEnd(id); | |
| 3832 | + const pending = __ctxPendingOps.get(id); | |
| 3833 | + if (pending === undefined) return; | |
| 3834 | + __ctxPendingOps.delete(id); | |
| 3835 | + const live = | |
| 3836 | + stored instanceof __ActorAbort ? stored.reason : stored; | |
| 3837 | + for (const reject of pending) reject(live); | |
| 3838 | +}; | |
| 3839 | +// The entrypoint ctx.abort. Instances are cached across calls, so | |
| 3840 | +// the construction-time ctx cannot pin a request id (Workerd | |
| 3841 | +// constructs per request); the current frame's id at abort() time | |
| 3842 | +// is the request being served, which matches Workerd observably. | |
| 3843 | +const __ctxAbortCurrent = | |
| 3844 | + (reason) => __ctxAbort(__ctxNow(), reason); | |
| 3845 | +// ---- same-process RPC stubs ------------------------------------ | |
| 3846 | +// A stub entry owns a local target; `refs` counts live handles | |
| 3847 | +// across dup()s. When the last handle is disposed the target's own | |
| 3848 | +// Symbol.dispose runs (async, matching Workerd's disposal callback). | |
| 3849 | +// Stubs cross same-isolate transports only (same-script entrypoint | |
| 3850 | +// RPC and same-process routed dispatch); a marker revived elsewhere fails | |
| 3851 | +// loudly on use instead of aliasing an unrelated local entry. | |
| 3852 | +// `ctx` records the owning request context: the entry's for | |
| 3853 | +// running its target, the handle's for the serialize-elsewhere | |
| 3854 | +// check. | |
| 3855 | +const __stubEntries = new Map(); | |
| 3856 | +const __stubMeta = new WeakMap(); | |
| 3857 | +// Keep the Durable Object brand outside the user-visible object. Reading a | |
| 3858 | +// string property here would invoke an inherited getter before validation can | |
| 3859 | +// reject its unsupported prototype. | |
| 3860 | +const __doStubMeta = new WeakMap(); | |
| 3861 | +let __nextStubId = 1; | |
| 3862 | +const __stubIsolate = Math.random().toString(36).slice(2); | |
| 3863 | +const __newEntry = (target) => { | |
| 3864 | + // `scope` records the actor event that minted the entry (top of | |
| 3865 | + // the event stack at lift time), so an actor breakage can find | |
| 3866 | + // and abort the contexts hosting its exported stubs, and an op on | |
| 3867 | + // the stub can queue on that cell's input gate. `section` is the | |
| 3868 | + // critical section running at lift time, if any -- an op on this | |
| 3869 | + // stub re-enters it rather than queueing behind it. | |
| 3870 | + const scope = __currentActorScope() || undefined; | |
| 3871 | + const entry = { | |
| 3872 | + id: __nextStubId++, target, refs: 1, ctx: __ctxNow(), scope, | |
| 3873 | + section: __cellBlocks.get(scope)?.holder ?? null, | |
| 3874 | + }; | |
| 3875 | + __stubEntries.set(entry.id, entry); | |
| 3876 | + return entry; | |
| 3877 | +}; | |
| 3878 | +// Actors broken in JS: scope -> reason. Workerd's DO ctx.abort | |
| 3879 | +// rejects in-flight and future calls; when the abort fires under a | |
| 3880 | +// same-isolate stub caller, terminate_execution would unwind that | |
| 3881 | +// caller too (the routed dispatch re-enters the isolate), so the | |
| 3882 | +// breakage is recorded here instead: contexts hosting the actor's | |
| 3883 | +// exported stubs abort (in-flight ops reject with the reason, | |
| 3884 | +// later ops with the post-abort message) and RPC dispatch to the | |
| 3885 | +// scope rejects with the reason. Direct host-dispatched DO events | |
| 3886 | +// keep the uncatchable terminate_execution path. | |
| 3887 | +const __brokenActors = new Map(); | |
| 3888 | +const __actorBreak = (scope, reason) => { | |
| 3889 | + if (__brokenActors.has(scope)) return; | |
| 3890 | + __brokenActors.set(scope, reason); | |
| 3891 | + for (const entry of __stubEntries.values()) | |
| 3892 | + if (entry.scope === scope) | |
| 3893 | + __ctxAbort(entry.ctx, new __ActorAbort(reason)); | |
| 3894 | +}; | |
| 3895 | +// Everything this isolate holds for one cell scope that belongs to the | |
| 3896 | +// cell's residency rather than to the isolate, so a fresh instance | |
| 3897 | +// inherits none of it. `adopt_cell` calls this on both edges: the | |
| 3898 | +// give-back frees it, the take-in guarantees that no epoch spans. | |
| 3899 | +// Storage is not here -- `stop_cell` closes it host-side -- and sockets | |
| 3900 | +// live in the host registry, so a hibernated cell keeps them. | |
| 3901 | +const __cellRelease = (scope) => { | |
| 3902 | + __cell.instances[scope]?.ctx?.facets?._release(); | |
| 3903 | + delete __cell.instances[scope]; | |
| 3904 | + delete __cell.idNames[scope]; | |
| 3905 | + delete __cell.facetConfigs[scope]; | |
| 3906 | + __brokenActors.delete(scope); | |
| 3907 | + // An abandoned block can never run `__blockLeave`. A normal eviction | |
| 3908 | + // cannot abandon a block because its event keeps the cell in flight. A | |
| 3909 | + // stop that waits for nobody can, so the release drops every block record | |
| 3910 | + // together with the other state for this residency. | |
| 3911 | + __cellBlocks.delete(scope); | |
| 3912 | + // An entry holds `target`, which can be an object the released | |
| 3913 | + // instance owns. Dropping it ends that reachability; `released` is | |
| 3914 | + // what an already-revived handle reads, since it holds its entry | |
| 3915 | + // directly and never looks in this map again. | |
| 3916 | + for (const entry of __stubEntries.values()) { | |
| 3917 | + if (entry.scope !== scope) continue; | |
| 3918 | + entry.released = true; | |
| 3919 | + __stubEntries.delete(entry.id); | |
| 3920 | + // Break in-flight ops as an abort would, but not through | |
| 3921 | + // `__actorBreak`: that records the scope broken for the life of the | |
| 3922 | + // isolate, which is the state this function drops. | |
| 3923 | + __ctxAbort(entry.ctx, new __ActorAbort(__releasedStubError())); | |
| 3924 | + } | |
| 3925 | +}; | |
| 3926 | +const __releasedStubError = () => new Error( | |
| 3927 | + "The Durable Object that returned this RPC stub no longer runs on " + | |
| 3928 | + "this node."); | |
| 3929 | +const __disposeStub = (meta) => { | |
| 3930 | + if (meta.disposed) return; | |
| 3931 | + meta.disposed = true; | |
| 3932 | + __ctxUnregister(meta); | |
| 3933 | + const entry = meta.entry; | |
| 3934 | + if (--entry.refs > 0) return; | |
| 3935 | + __stubEntries.delete(entry.id); | |
| 3936 | + const disposer = entry.target?.[Symbol.dispose]; | |
| 3937 | + if (typeof disposer === "function") | |
| 3938 | + Promise.resolve().then(() => disposer.call(entry.target)); | |
| 3939 | +}; | |
| 3940 | +const __stubDisposedError = () => | |
| 3941 | + new Error("RPC stub used after being disposed."); | |
| 3942 | +// Shared brand value for RpcTarget instances; see the RpcTarget | |
| 3943 | +// constructor. | |
| 3944 | +const __rpcNoClone = () => {}; | |
| 3945 | +// Workerd method-visibility rules by target kind: an RpcTarget | |
| 3946 | +// exposes inherited methods/accessors (never own instance state, | |
| 3947 | +// never Object.prototype); a plain object or function exposes own | |
| 3948 | +// properties only. Property reads go through normal [[Get]] so | |
| 3949 | +// Proxy handlers participate, as in Workerd. | |
| 3950 | +const __rpcNoSuchMethod = (prop) => new TypeError( | |
| 3951 | + 'The RPC receiver does not implement the method "' + prop + '".'); | |
| 3952 | +// Bind through the intrinsic because a callable proxy can implement `.bind` | |
| 3953 | +// as a remote property. Reading that property can turn a valid named RPC | |
| 3954 | +// method into a non-function. Keep this rule shared by every RPC binding site. | |
| 3955 | +const __rpcBindMethod = (value, receiver) => | |
| 3956 | + Reflect.apply(Function.prototype.bind, value, [receiver]); | |
| 3957 | +const __stubResolve = (target, prop) => { | |
| 3958 | + if (target instanceof __cf.RpcTarget) { | |
| 3959 | + if (Object.hasOwn(target, prop) || !(prop in target) || | |
| 3960 | + prop in Object.prototype) throw __rpcNoSuchMethod(prop); | |
| 3961 | + } else if (!Object.hasOwn(target, prop)) { | |
| 3962 | + throw __rpcNoSuchMethod(prop); | |
| 3963 | + } | |
| 3964 | + const value = target[prop]; | |
| 3965 | + // Keep celld's own stubs and pipeline nodes unwrapped because the wrapper | |
| 3966 | + // would lose their metadata. | |
| 3967 | + return typeof value === "function" && !__stubMeta.has(value) && | |
| 3968 | + !(value instanceof __cf.RpcPromise) && | |
| 3969 | + !(value instanceof __cf.RpcProperty) | |
| 3970 | + ? __rpcBindMethod(value, target) : value; | |
| 3971 | +}; | |
| 3972 | +// ---- streams over RPC ------------------------------------------ | |
| 3973 | +// A live stream crosses as a handle in the caps table: the sender | |
| 3974 | +// locks the origin (reader/writer acquired at lift) behind a | |
| 3975 | +// bridge entry, and the receiver's endpoint is an ordinary | |
| 3976 | +// ReadableStream/WritableStream whose pulls and writes are stub | |
| 3977 | +// ops against the bridge -- one bounded reverse call per chunk, | |
| 3978 | +// the clone being the one wire copy. Backpressure is the op in | |
| 3979 | +// flight: hwm 0 pulls only on demand, and the writable carries | |
| 3980 | +// one chunk per op. EOF, close, and errors cross as op results; | |
| 3981 | +// teardown (param disposal, context end, context abort) runs the | |
| 3982 | +// bridge disposer, which cancels or aborts an unfinished origin | |
| 3983 | +// with Workerd's generic disconnect errors -- reasons do not | |
| 3984 | +// propagate, matching Workerd's own TODOs (and its verbatim | |
| 3985 | +// "endeded" typo). | |
| 3986 | +const __wsDisconnect = () => new Error( | |
| 3987 | + "WritableStream received over RPC was disconnected because " + | |
| 3988 | + "the remote execution context has endeded."); | |
| 3989 | +const __rsDisconnect = () => new Error( | |
| 3990 | + "ReadableStream received over RPC disconnected prematurely."); | |
| 3991 | +// Receiver wrapper stream -> its handle meta, for forwarding. | |
| 3992 | +const __rpcStreamMeta = new WeakMap(); | |
| 3993 | +const __readableBridge = (reader) => { | |
| 3994 | + const bridge = { | |
| 3995 | + done: false, | |
| 3996 | + async read() { | |
| 3997 | + let result; | |
| 3998 | + try { | |
| 3999 | + result = await reader.read(); | |
| 4000 | + } catch (error) { | |
| 4001 | + bridge.done = true; | |
| 4002 | + throw error; | |
| 4003 | + } | |
| 4004 | + if (result.done) bridge.done = true; | |
| 4005 | + return result; | |
| 4006 | + }, | |
| 4007 | + cancel() { | |
| 4008 | + if (bridge.done) return; | |
| 4009 | + bridge.done = true; | |
| 4010 | + reader.cancel(__rsDisconnect()).catch(() => {}); | |
| 4011 | + }, | |
| 4012 | + [Symbol.dispose]() { bridge.cancel(); }, | |
| 4013 | + }; | |
| 4014 | + return bridge; | |
| 4015 | +}; | |
| 4016 | +const __writableBridge = (writer) => { | |
| 4017 | + const bridge = { | |
| 4018 | + done: false, | |
| 4019 | + write: (chunk) => writer.write(chunk), | |
| 4020 | + close() { | |
| 4021 | + bridge.done = true; | |
| 4022 | + return writer.close(); | |
| 4023 | + }, | |
| 4024 | + abort() { | |
| 4025 | + bridge.done = true; | |
| 4026 | + return writer.abort(__wsDisconnect()); | |
| 4027 | + }, | |
| 4028 | + [Symbol.dispose]() { | |
| 4029 | + if (!bridge.done) bridge.abort().catch(() => {}); | |
| 4030 | + }, | |
| 4031 | + }; | |
| 4032 | + return bridge; | |
| 4033 | +}; | |
| 4034 | +const __liftStream = (v) => { | |
| 4035 | + const readable = v instanceof ReadableStream; | |
| 4036 | + const key = readable ? "__celld$rs" : "__celld$ws"; | |
| 4037 | + const meta = __rpcStreamMeta.get(v); | |
| 4038 | + if (meta !== undefined && !meta.disposed && !v.locked) { | |
| 4039 | + // Re-serializing a received, untouched stream forwards the | |
| 4040 | + // original handle: the reference moves (like a stub) and | |
| 4041 | + // the local wrapper is dead -- a round trip stays one hop. | |
| 4042 | + meta.disposed = true; | |
| 4043 | + __ctxUnregister(meta); | |
| 4044 | + return { [key]: meta.entry.id, t: __stubIsolate }; | |
| 4045 | + } | |
| 4046 | + if (v.locked) | |
| 4047 | + throw new TypeError(readable | |
| 4048 | + ? "The ReadableStream has been locked to a reader." | |
| 4049 | + : "The WritableStream has been locked to a writer."); | |
| 4050 | + const bridge = readable | |
| 4051 | + ? __readableBridge(v.getReader()) | |
| 4052 | + : __writableBridge(v.getWriter()); | |
| 4053 | + return { [key]: __newEntry(bridge).id, t: __stubIsolate }; | |
| 4054 | +}; | |
| 4055 | +// A signal is not a snapshot on the RPC wire. The marker carries a | |
| 4056 | +// process-wide identity, and the host forwards the source's single state | |
| 4057 | +// transition to every receiving isolate. A received signal keeps that | |
| 4058 | +// identity when an RPC forwards it again, so a chain does not add relays. | |
| 4059 | +const __rpcSignalMeta = new WeakMap(); | |
| 4060 | +const __rpcSignalReceivers = new Map(); | |
| 4061 | +const __rpcSignalSourceFinalizer = new FinalizationRegistry( | |
| 4062 | + (id) => __rpc_signal_release(id)); | |
| 4063 | +const __rpcSignalReceiverFinalizer = new FinalizationRegistry( | |
| 4064 | + ({ id, subscription }) => | |
| 4065 | + __rpc_signal_unsubscribe(id, subscription)); | |
| 4066 | +const __rpcSignalReasonOut = (reason) => { | |
| 4067 | + if (reason instanceof DOMException) | |
| 4068 | + return __sc_encode({ d: true, n: reason.name, m: reason.message }); | |
| 4069 | + try { | |
| 4070 | + return __sc_encode({ v: reason }); | |
| 4071 | + } catch { | |
| 4072 | + return __sc_encode({ v: new Error(String(reason)) }); | |
| 4073 | + } | |
| 4074 | +}; | |
| 4075 | +const __rpcSignalReasonIn = (bytes) => { | |
| 4076 | + const reason = __sc_decode(bytes); | |
| 4077 | + return reason.d | |
| 4078 | + ? new DOMException(reason.m, reason.n) | |
| 4079 | + : reason.v; | |
| 4080 | +}; | |
| 4081 | +const __rpcSignalSubscribe = (receiver) => { | |
| 4082 | + const signal = receiver.signal.deref(); | |
| 4083 | + if (signal === undefined) return false; | |
| 4084 | + const pending = __rpc_signal_wait(receiver.id); | |
| 4085 | + receiver.subscription = pending.__celldRpcSignalSubscription; | |
| 4086 | + pending.then((reason) => { | |
| 4087 | + const target = receiver.signal.deref(); | |
| 4088 | + if (target !== undefined && reason.byteLength !== 0) | |
| 4089 | + __abortSignal(target, __rpcSignalReasonIn(reason)); | |
| 4090 | + }); | |
| 4091 | + // A wait belongs to the request that installed it. A retained signal needs | |
| 4092 | + // a fresh wait in each later request, and its finalizer must unsubscribe the | |
| 4093 | + // newest one rather than the dead request's subscription. | |
| 4094 | + __rpcSignalReceiverFinalizer.unregister(receiver); | |
| 4095 | + __rpcSignalReceiverFinalizer.register(signal, receiver, receiver); | |
| 4096 | + return true; | |
| 4097 | +}; | |
| 4098 | +const __liftSignal = (signal) => { | |
| 4099 | + let meta = __rpcSignalMeta.get(signal); | |
| 4100 | + if (meta === undefined) { | |
| 4101 | + const id = __rpc_signal_new(); | |
| 4102 | + meta = { id }; | |
| 4103 | + __rpcSignalMeta.set(signal, meta); | |
| 4104 | + __rpcSignalSourceFinalizer.register(signal, id); | |
| 4105 | + if (signal.aborted) { | |
| 4106 | + __rpc_signal_abort(id, __rpcSignalReasonOut(signal.reason)); | |
| 4107 | + } else { | |
| 4108 | + signal.addEventListener("abort", (event) => { | |
| 4109 | + __rpc_signal_abort(id, | |
| 4110 | + __rpcSignalReasonOut(event.target.reason)); | |
| 4111 | + }, { once: true }); | |
| 4112 | + } | |
| 4113 | + } | |
| 4114 | + const marker = { "__celld$sig": meta.id, a: signal.aborted }; | |
| 4115 | + if (signal.aborted) marker.r = __rpcSignalReasonOut(signal.reason); | |
| 4116 | + return marker; | |
| 4117 | +}; | |
| 4118 | +const __rpcSignalRefresh = () => { | |
| 4119 | + for (const [id, receivers] of __rpcSignalReceivers) { | |
| 4120 | + const state = __rpc_signal_poll(id); | |
| 4121 | + const live = new Set(); | |
| 4122 | + for (const receiver of receivers) { | |
| 4123 | + const signal = receiver.signal.deref(); | |
| 4124 | + if (signal === undefined) continue; | |
| 4125 | + if (state instanceof Uint8Array) | |
| 4126 | + __abortSignal(signal, __rpcSignalReasonIn(state)); | |
| 4127 | + else if (state !== null && __rpcSignalSubscribe(receiver)) | |
| 4128 | + live.add(receiver); | |
| 4129 | + } | |
| 4130 | + if (live.size === 0 || state === null || state instanceof Uint8Array) | |
| 4131 | + __rpcSignalReceivers.delete(id); | |
| 4132 | + else | |
| 4133 | + __rpcSignalReceivers.set(id, live); | |
| 4134 | + } | |
| 4135 | +}; | |
| 4136 | +// Replace stub-able values with wire markers. Runs only after a | |
| 4137 | +// plain clone failed, so plain-data serialization never pays for | |
| 4138 | +// it. Passing an existing stub transfers its reference: the | |
| 4139 | +// sender's handle is disposed (dup() first to keep one) and the | |
| 4140 | +// receiver adopts it. Returns null when nothing was liftable. | |
| 4141 | +const __stubLift = (value, allowCapabilities = true, originals) => { | |
| 4142 | + let lifted = false; | |
| 4143 | + // Capabilities (stubs, disposers) root the callee context; | |
| 4144 | + // by-value host types do not -- they pick the 0x02 envelope. | |
| 4145 | + let caps = false; | |
| 4146 | + const seen = new Map(); | |
| 4147 | + const ctx = __ctxNow(); | |
| 4148 | + // A buffered body crosses as its bytes; a live-stream body | |
| 4149 | + // crosses as a stream handle (a capability, so the reply | |
| 4150 | + // roots its callee context and the pulls keep working). | |
| 4151 | + const liftBody = (v) => { | |
| 4152 | + if (v._bodyBytes !== null) return v._bodyBytes; | |
| 4153 | + caps = true; | |
| 4154 | + return __liftStream(v.body); | |
| 4155 | + }; | |
| 4156 | + const lift = (v) => { | |
| 4157 | + if (v === null || | |
| 4158 | + (typeof v !== "object" && typeof v !== "function")) return v; | |
| 4159 | + const cached = seen.get(v); | |
| 4160 | + if (cached !== undefined) return cached; | |
| 4161 | + const meta = __stubMeta.get(v); | |
| 4162 | + if (meta) { | |
| 4163 | + if (!allowCapabilities) return v; | |
| 4164 | + lifted = true; | |
| 4165 | + caps = true; | |
| 4166 | + if (meta.disposed) throw __stubDisposedError(); | |
| 4167 | + // A stub belongs to the request that received it; another | |
| 4168 | + // request cannot serialize it (Workerd's IoContext rule). | |
| 4169 | + if (meta.ctx !== ctx) throw __ctxError("Client"); | |
| 4170 | + meta.disposed = true; // the ref moves to the receiver | |
| 4171 | + __ctxUnregister(meta); | |
| 4172 | + const marker = { "__celld$stub": meta.entry.id, | |
| 4173 | + t: __stubIsolate, c: meta.callable }; | |
| 4174 | + seen.set(v, marker); | |
| 4175 | + return marker; | |
| 4176 | + } | |
| 4177 | + const svc = __svcMeta.get(v); | |
| 4178 | + if (svc !== undefined) { | |
| 4179 | + if (!allowCapabilities) return v; | |
| 4180 | + // A loopback service stub (ctx.exports): name + props cross | |
| 4181 | + // as plain data and revive as a fresh loopback stub. Props | |
| 4182 | + // are lifted too -- they may nest further stubs (Workerd's | |
| 4183 | + // nested channel tokens). | |
| 4184 | + lifted = true; | |
| 4185 | + caps = true; | |
| 4186 | + const marker = { "__celld$svc": svc.name, t: __stubIsolate }; | |
| 4187 | + seen.set(v, marker); | |
| 4188 | + if (svc.props !== undefined) marker.p = lift(svc.props); | |
| 4189 | + return marker; | |
| 4190 | + } | |
| 4191 | + // Workerd refuses to serialize its promise/property handles. | |
| 4192 | + if (v instanceof __cf.RpcPromise || v instanceof __cf.RpcProperty) | |
| 4193 | + throw new DOMException( | |
| 4194 | + 'Could not serialize object of type "' + | |
| 4195 | + (v instanceof __cf.RpcPromise ? "RpcPromise" : "RpcProperty") + | |
| 4196 | + '". This type does not support serialization.', | |
| 4197 | + "DataCloneError"); | |
| 4198 | + if (typeof v === "function" || v instanceof __cf.RpcTarget) { | |
| 4199 | + if (!allowCapabilities) return v; | |
| 4200 | + lifted = true; | |
| 4201 | + caps = true; | |
| 4202 | + const marker = { "__celld$stub": __newEntry(v).id, | |
| 4203 | + t: __stubIsolate, | |
| 4204 | + c: typeof v === "function" }; | |
| 4205 | + seen.set(v, marker); | |
| 4206 | + return marker; | |
| 4207 | + } | |
| 4208 | + const doId = __doStubMeta.get(v); | |
| 4209 | + if (doId !== undefined) { | |
| 4210 | + if (!allowCapabilities) return v; | |
| 4211 | + lifted = true; | |
| 4212 | + caps = true; | |
| 4213 | + const marker = { "__celld$do": doId._className, | |
| 4214 | + v: doId._value, n: v.name ?? null }; | |
| 4215 | + seen.set(v, marker); | |
| 4216 | + return marker; | |
| 4217 | + } | |
| 4218 | + // HTTP host types cross by value, as in Workerd's RPC | |
| 4219 | + // serialization: entry lists for Headers, the buffered bytes | |
| 4220 | + // for bodies (the marker aliases the live buffer; the clone | |
| 4221 | + // is the one wire copy), and no signal -- the receiver mints | |
| 4222 | + // a fresh one. A live stream body cannot cross yet. | |
| 4223 | + let marker; | |
| 4224 | + if (v instanceof Headers) { | |
| 4225 | + if (!allowCapabilities) return v; | |
| 4226 | + marker = { "__celld$hdr": [...v] }; | |
| 4227 | + } else if (v instanceof Blob) { | |
| 4228 | + if (!allowCapabilities) return v; | |
| 4229 | + marker = { "__celld$blob": v._bytes, y: v.type }; | |
| 4230 | + if (v instanceof File) { | |
| 4231 | + marker.n = v.name; | |
| 4232 | + marker.m = v.lastModified; | |
| 4233 | + } | |
| 4234 | + } else if (v instanceof Request) { | |
| 4235 | + if (!allowCapabilities) return v; | |
| 4236 | + marker = { "__celld$req": v.url, m: v.method, | |
| 4237 | + h: [...v.headers], r: v.redirect, c: v.cf, | |
| 4238 | + b: liftBody(v) }; | |
| 4239 | + } else if (v instanceof Response) { | |
| 4240 | + if (!allowCapabilities) return v; | |
| 4241 | + marker = { "__celld$res": v.status, | |
| 4242 | + t: v.statusText || | |
| 4243 | + __STATUS_TEXT[v.status] || "", | |
| 4244 | + h: [...v.headers], c: v.cf, | |
| 4245 | + e: v.type === "error", | |
| 4246 | + b: v.body === null ? null : liftBody(v) }; | |
| 4247 | + } else if (v instanceof ReadableStream || | |
| 4248 | + v instanceof WritableStream) { | |
| 4249 | + if (!allowCapabilities) return v; | |
| 4250 | + caps = true; | |
| 4251 | + marker = __liftStream(v); | |
| 4252 | + } else if (v instanceof AbortSignal) { | |
| 4253 | + marker = __liftSignal(v); | |
| 4254 | + } | |
| 4255 | + if (marker !== undefined) { | |
| 4256 | + lifted = true; | |
| 4257 | + seen.set(v, marker); | |
| 4258 | + return marker; | |
| 4259 | + } | |
| 4260 | + const proto = Object.getPrototypeOf(v); | |
| 4261 | + if (!Array.isArray(v) && | |
| 4262 | + proto !== Object.prototype && proto !== null) { | |
| 4263 | + // A Proxy emulating neither a plain object nor an RpcTarget | |
| 4264 | + // is Workerd's canonical proxy serialization error. | |
| 4265 | + if (__util_proxy_details(v) !== undefined) | |
| 4266 | + throw new DOMException( | |
| 4267 | + "Proxy could not be serialized because it is not a " + | |
| 4268 | + "valid RPC receiver type. The Proxy must emulate either " + | |
| 4269 | + "a plain object or an RpcTarget, as indicated by the " + | |
| 4270 | + "Proxy's prototype chain.", "DataCloneError"); | |
| 4271 | + return v; // host/other: leave to the clone | |
| 4272 | + } | |
| 4273 | + const out = Array.isArray(v) ? [] : {}; | |
| 4274 | + seen.set(v, out); | |
| 4275 | + for (const key of Object.keys(v)) out[key] = lift(v[key]); | |
| 4276 | + const disposerSource = originals?.get(v) ?? v; | |
| 4277 | + const disposer = disposerSource[Symbol.dispose]; | |
| 4278 | + if (allowCapabilities && !Array.isArray(v) && | |
| 4279 | + typeof disposer === "function") { | |
| 4280 | + lifted = true; | |
| 4281 | + caps = true; | |
| 4282 | + out["__celld$disp"] = | |
| 4283 | + __newEntry(__rpcBindMethod(disposer, disposerSource)).id; | |
| 4284 | + } | |
| 4285 | + return out; | |
| 4286 | + }; | |
| 4287 | + const tree = lift(value); | |
| 4288 | + return lifted ? { tree, caps } : null; | |
| 4289 | +}; | |
| 4290 | +// Revive host-type markers into real instances, adopting the wire | |
| 4291 | +// bytes directly -- no copy beyond the clone's own. | |
| 4292 | +const __reviveBlob = (marker, bytes) => { | |
| 4293 | + const blob = marker.n !== undefined | |
| 4294 | + ? new File([], marker.n, | |
| 4295 | + { type: marker.y, lastModified: marker.m }) | |
| 4296 | + : new Blob([], { type: marker.y }); | |
| 4297 | + blob._bytes = bytes; | |
| 4298 | + blob.size = bytes.byteLength; | |
| 4299 | + return blob; | |
| 4300 | +}; | |
| 4301 | +const __adoptBody = (target, bytes) => { | |
| 4302 | + target._bodyBytes = bytes; | |
| 4303 | + target._body = undefined; // decoded lazily on the first text()/json() | |
| 4304 | + const body = target.body; | |
| 4305 | + if (body !== null) { | |
| 4306 | + body._st.bytes = bytes; | |
| 4307 | + body.__celldBodyBytes = bytes; | |
| 4308 | + body._expectedLength = bytes.byteLength; | |
| 4309 | + } | |
| 4310 | +}; | |
| 4311 | +// A non-bytes `b` is a live-stream body marker: revive it and | |
| 4312 | +// let the constructor adopt it as a streaming body. | |
| 4313 | +const __reviveRequest = (marker, url, revive) => { | |
| 4314 | + if (!(marker.b instanceof Uint8Array)) | |
| 4315 | + return new Request(url, { method: marker.m, | |
| 4316 | + headers: marker.h, redirect: marker.r, cf: marker.c, | |
| 4317 | + body: revive(marker.b) }); | |
| 4318 | + const req = new Request(url, { method: marker.m, | |
| 4319 | + headers: marker.h, redirect: marker.r, cf: marker.c }); | |
| 4320 | + __adoptBody(req, marker.b); | |
| 4321 | + return req; | |
| 4322 | +}; | |
| 4323 | +const __reviveResponse = (marker, revive) => { | |
| 4324 | + const bytes = marker.b instanceof Uint8Array; | |
| 4325 | + const res = new Response( | |
| 4326 | + marker.b === null ? null : bytes ? "" : revive(marker.b), { | |
| 4327 | + status: marker["__celld$res"], statusText: marker.t, | |
| 4328 | + headers: marker.h, cf: marker.c }); | |
| 4329 | + if (bytes) __adoptBody(res, marker.b); | |
| 4330 | + if (marker.e) res.type = "error"; | |
| 4331 | + return res; | |
| 4332 | +}; | |
| 4333 | +// Wire a received stream handle to a local endpoint built with | |
| 4334 | +// the ordinary constructors -- nothing new threads through the | |
| 4335 | +// stream hot paths. Read errors surface as Workerd's generic | |
| 4336 | +// premature-disconnect; write errors propagate (Workerd sends | |
| 4337 | +// real errors back through the write loop). | |
| 4338 | +const __foreignStreamOp = () => Promise.reject(new Error( | |
| 4339 | + "RPC streams cannot cross isolate boundaries yet.")); | |
| 4340 | +const __reviveStream = (marker, id, readable, handles) => { | |
| 4341 | + const entry = marker.t === __stubIsolate | |
| 4342 | + ? __stubEntries.get(id) : undefined; | |
| 4343 | + if (entry === undefined) | |
| 4344 | + return readable | |
| 4345 | + ? new ReadableStream({ pull: __foreignStreamOp }) | |
| 4346 | + : new WritableStream({ write: __foreignStreamOp, | |
| 4347 | + close: __foreignStreamOp, abort: __foreignStreamOp }); | |
| 4348 | + const meta = { entry, disposed: false, ctx: __ctxNow() }; | |
| 4349 | + __ctxRegister(meta); | |
| 4350 | + handles.push(meta); | |
| 4351 | + const stream = readable | |
| 4352 | + ? new ReadableStream({ | |
| 4353 | + async pull(controller) { | |
| 4354 | + let result; | |
| 4355 | + try { | |
| 4356 | + result = await __stubOp(meta, ["read"], []); | |
| 4357 | + } catch { | |
| 4358 | + throw __rsDisconnect(); | |
| 4359 | + } | |
| 4360 | + if (result.done) controller.close(); | |
| 4361 | + else controller.enqueue(result.value); | |
| 4362 | + }, | |
| 4363 | + cancel: () => | |
| 4364 | + __stubOp(meta, ["cancel"], []).catch(() => {}), | |
| 4365 | + }, { highWaterMark: 0 }) | |
| 4366 | + : new WritableStream({ | |
| 4367 | + write: (chunk) => __stubOp(meta, ["write"], [chunk]), | |
| 4368 | + close: () => __stubOp(meta, ["close"], []), | |
| 4369 | + abort: () => | |
| 4370 | + __stubOp(meta, ["abort"], []).catch(() => {}), | |
| 4371 | + }); | |
| 4372 | + __rpcStreamMeta.set(stream, meta); | |
| 4373 | + return stream; | |
| 4374 | +}; | |
| 4375 | +const __reviveSignal = (marker, id) => { | |
| 4376 | + const controller = new AbortController(); | |
| 4377 | + const signal = controller.signal; | |
| 4378 | + __rpcSignalMeta.set(signal, { id }); | |
| 4379 | + if (marker.a) { | |
| 4380 | + controller.abort(__rpcSignalReasonIn(marker.r)); | |
| 4381 | + return controller.signal; | |
| 4382 | + } | |
| 4383 | + let receivers = __rpcSignalReceivers.get(id); | |
| 4384 | + if (receivers === undefined) { | |
| 4385 | + receivers = new Set(); | |
| 4386 | + __rpcSignalReceivers.set(id, receivers); | |
| 4387 | + } | |
| 4388 | + const receiver = { id, signal: new WeakRef(signal), subscription: null }; | |
| 4389 | + receivers.add(receiver); | |
| 4390 | + __rpcSignalSubscribe(receiver); | |
| 4391 | + return signal; | |
| 4392 | +}; | |
| 4393 | +// The inverse: markers become live handles. `handles` collects the | |
| 4394 | +// revived stubs (for call-end param disposal or result-tree | |
| 4395 | +// disposal); `disposers` collects remote Symbol.dispose entries. | |
| 4396 | +const __stubRevive = (value) => { | |
| 4397 | + const handles = []; | |
| 4398 | + const disposers = []; | |
| 4399 | + const seen = new Set(); | |
| 4400 | + const revive = (v) => { | |
| 4401 | + if (v === null || typeof v !== "object") return v; | |
| 4402 | + const stubId = v["__celld$stub"]; | |
| 4403 | + if (stubId !== undefined) { | |
| 4404 | + const entry = v.t === __stubIsolate | |
| 4405 | + ? __stubEntries.get(stubId) : undefined; | |
| 4406 | + const stub = entry === undefined | |
| 4407 | + ? __foreignStub() | |
| 4408 | + : __makeStub(entry, v.c); | |
| 4409 | + const meta = __stubMeta.get(stub); | |
| 4410 | + if (meta) handles.push(meta); | |
| 4411 | + return stub; | |
| 4412 | + } | |
| 4413 | + const svcName = v["__celld$svc"]; | |
| 4414 | + if (svcName !== undefined) | |
| 4415 | + return v.t === __stubIsolate | |
| 4416 | + ? __entrypointStub(svcName, revive(v.p)) | |
| 4417 | + : __foreignStub(); | |
| 4418 | + const doClass = v["__celld$do"]; | |
| 4419 | + if (doClass !== undefined) { | |
| 4420 | + const namespace = __cell.makeNamespace(doClass); | |
| 4421 | + return namespace.get( | |
| 4422 | + new DurableObjectId(doClass, v.v, v.n ?? undefined)); | |
| 4423 | + } | |
| 4424 | + const hdr = v["__celld$hdr"]; | |
| 4425 | + if (hdr !== undefined) return new Headers(hdr); | |
| 4426 | + const blobBytes = v["__celld$blob"]; | |
| 4427 | + if (blobBytes !== undefined) return __reviveBlob(v, blobBytes); | |
| 4428 | + const reqUrl = v["__celld$req"]; | |
| 4429 | + if (reqUrl !== undefined) | |
| 4430 | + return __reviveRequest(v, reqUrl, revive); | |
| 4431 | + if (v["__celld$res"] !== undefined) | |
| 4432 | + return __reviveResponse(v, revive); | |
| 4433 | + const rsId = v["__celld$rs"]; | |
| 4434 | + if (rsId !== undefined) | |
| 4435 | + return __reviveStream(v, rsId, true, handles); | |
| 4436 | + const wsId = v["__celld$ws"]; | |
| 4437 | + if (wsId !== undefined) | |
| 4438 | + return __reviveStream(v, wsId, false, handles); | |
| 4439 | + const sigId = v["__celld$sig"]; | |
| 4440 | + if (sigId !== undefined) return __reviveSignal(v, sigId); | |
| 4441 | + if (seen.has(v)) return v; | |
| 4442 | + seen.add(v); | |
| 4443 | + if (Array.isArray(v)) { | |
| 4444 | + for (let i = 0; i < v.length; i++) v[i] = revive(v[i]); | |
| 4445 | + return v; | |
| 4446 | + } | |
| 4447 | + const proto = Object.getPrototypeOf(v); | |
| 4448 | + if (proto !== Object.prototype && proto !== null) return v; | |
| 4449 | + for (const key of Object.keys(v)) { | |
| 4450 | + if (key === "__celld$disp") { | |
| 4451 | + const entry = __stubEntries.get(v[key]); | |
| 4452 | + if (entry) disposers.push(entry); | |
| 4453 | + delete v[key]; | |
| 4454 | + continue; | |
| 4455 | + } | |
| 4456 | + v[key] = revive(v[key]); | |
| 4457 | + } | |
| 4458 | + return v; | |
| 4459 | + }; | |
| 4460 | + return { value: revive(value), handles, disposers }; | |
| 4461 | +}; | |
| 4462 | +// A marker that crossed an isolate boundary: fail on use, loudly. | |
| 4463 | +const __foreignStub = () => new Proxy(function () {}, { | |
| 4464 | + get: (_b, prop) => { | |
| 4465 | + if (prop === "then" || typeof prop !== "string") return undefined; | |
| 4466 | + return () => Promise.reject(new Error( | |
| 4467 | + "RPC stubs cannot cross isolate boundaries yet.")); | |
| 4468 | + }, | |
| 4469 | + apply: () => Promise.reject(new Error( | |
| 4470 | + "RPC stubs cannot cross isolate boundaries yet.")), | |
| 4471 | +}); | |
| 4472 | +// Workerd's entrypoint method-visibility rules (worker-rpc.c++): | |
| 4473 | +// reserved lifecycle names are refused outright; only prototype | |
| 4474 | +// methods and accessors are visible -- never own instance state | |
| 4475 | +// (env/ctx live there) and never Object.prototype. | |
| 4476 | +const __entrypointReserved = new Set([ | |
| 4477 | + "constructor", "fetch", "connect", "alarm", "scheduled", | |
| 4478 | + "webSocketMessage", "webSocketClose", "webSocketError", "dup", | |
| 4479 | +]); | |
| 4480 | +const __entrypointResolve = (inst, prop) => { | |
| 4481 | + if (__entrypointReserved.has(prop)) | |
| 4482 | + throw new TypeError("'" + prop + | |
| 4483 | + "' is a reserved method and cannot be called over RPC."); | |
| 4484 | + if (Object.hasOwn(inst, prop) || !(prop in inst) || | |
| 4485 | + prop in Object.prototype) | |
| 4486 | + throw __rpcNoSuchMethod(prop); | |
| 4487 | + const value = inst[prop]; | |
| 4488 | + return typeof value === "function" && !__stubMeta.has(value) && | |
| 4489 | + !(value instanceof __cf.RpcPromise) && | |
| 4490 | + !(value instanceof __cf.RpcProperty) | |
| 4491 | + ? __rpcBindMethod(value, inst) : value; | |
| 4492 | +}; | |
| 4493 | +// A pipeline hop may continue only through plain data, functions, | |
| 4494 | +// RpcTargets, and stubs -- never through an RPC promise/property | |
| 4495 | +// handle or a class instance (Workerd's receiver rules). | |
| 4496 | +const __walkable = (v) => | |
| 4497 | + v instanceof __cf.RpcPromise || v instanceof __cf.RpcProperty | |
| 4498 | + ? false | |
| 4499 | + : typeof v === "function" || v instanceof __cf.RpcTarget || | |
| 4500 | + (typeof v === "object" && v !== null && | |
| 4501 | + (Object.getPrototypeOf(v) === Object.prototype || | |
| 4502 | + Array.isArray(v))); | |
| 4503 | +// Receiver-side pipeline walk: resolve `path` from `root`, then | |
| 4504 | +// GET the final member (`args` null) or CALL it. Errors name the | |
| 4505 | +// path walked so far, as Workerd's do. A stub mid-walk continues | |
| 4506 | +// against its own target, in the stub's owning context. | |
| 4507 | +const __rpcWalk = async (root, path, args, entrypointRoot) => { | |
| 4508 | + let value = root; | |
| 4509 | + for (let i = 0; i < path.length; i++) { | |
| 4510 | + const meta = __stubMeta.get(value); | |
| 4511 | + if (meta) { | |
| 4512 | + if (meta.disposed) throw __stubDisposedError(); | |
| 4513 | + const rest = path.slice(i); | |
| 4514 | + return await __ctxRun(meta.entry.ctx, | |
| 4515 | + () => __rpcWalk(meta.entry.target, rest, args, false)); | |
| 4516 | + } | |
| 4517 | + if (i > 0 && !__walkable(value)) | |
| 4518 | + throw __rpcNoSuchMethod(path[i - 1]); | |
| 4519 | + const prop = path[i]; | |
| 4520 | + const next = entrypointRoot && i === 0 | |
| 4521 | + ? __entrypointResolve(value, prop) | |
| 4522 | + : __stubResolve(value, prop); | |
| 4523 | + if (i === path.length - 1) { | |
| 4524 | + if (args === null) return next; | |
| 4525 | + if (typeof next !== "function") | |
| 4526 | + throw new TypeError( | |
| 4527 | + '"' + path.join(".") + '" is not a function.'); | |
| 4528 | + return next(...args); | |
| 4529 | + } | |
| 4530 | + if (next instanceof __cf.RpcPromise || | |
| 4531 | + next instanceof __cf.RpcProperty) | |
| 4532 | + throw __rpcNoSuchMethod(prop); | |
| 4533 | + value = next; | |
| 4534 | + } | |
| 4535 | + // An empty path applies the root itself (a callable stub). | |
| 4536 | + if (args === null) return value; | |
| 4537 | + if (typeof value !== "function") | |
| 4538 | + throw new TypeError("The RPC stub is not callable."); | |
| 4539 | + return value(...args); | |
| 4540 | +}; | |
| 4541 | +// One stub-mediated op: clone through the RPC envelope both ways, | |
| 4542 | +// so nested stubs, errors, and uncloneables behave exactly as a | |
| 4543 | +// dispatched call. Args serialize in the caller's context (its | |
| 4544 | +// stubs must be its own to transfer); the decode, the walk, and | |
| 4545 | +// the reply serialization run in the stub's owning context, so | |
| 4546 | +// stubs minted by the target belong to the target's context. | |
| 4547 | +// Params received by the target are disposed when the op ends | |
| 4548 | +// (Workerd's param-disposal rule). | |
| 4549 | +const __stubOp = (meta, path, args) => { | |
| 4550 | + if (meta.disposed) return Promise.reject(__stubDisposedError()); | |
| 4551 | + const entry = meta.entry; | |
| 4552 | + // The cell that minted this stub left residency, so `entry.target` | |
| 4553 | + // belongs to an instance this node released. The stub fails here | |
| 4554 | + // rather than calling into it. | |
| 4555 | + if (entry.released) return Promise.reject(__releasedStubError()); | |
| 4556 | + // A stub rooted in an aborted context is broken: reject with the | |
| 4557 | + // abort reason, before and after the dispatch (the target may | |
| 4558 | + // abort its own context mid-call). Gated on one field read. | |
| 4559 | + if (__abortedCtxs.size !== 0) { | |
| 4560 | + const aborted = __abortedCtxs.get(entry.ctx); | |
| 4561 | + if (aborted !== undefined) | |
| 4562 | + return Promise.reject(__postAbortError(aborted)); | |
| 4563 | + } | |
| 4564 | + const argsSc = args === null ? null : __rpcOut(args, true); | |
| 4565 | + const dispatch = (async () => { | |
| 4566 | + // Workerd delivers RPC asynchronously: the callee must not run | |
| 4567 | + // before the caller's synchronous code. A call made just after | |
| 4568 | + // a not-yet-delivered ctx.abort counts as in flight (rejects | |
| 4569 | + // with the reason, not the post-abort message). Bodies queue | |
| 4570 | + // in call order, so e-order holds. | |
| 4571 | + await null; | |
| 4572 | + // The cell that minted this stub gates it like any other event. | |
| 4573 | + // The op is dispatched inside the isolate and never becomes a | |
| 4574 | + // drive, so it is the one delivery point that has to ask here | |
| 4575 | + // rather than in Rust. A stub carrying the running critical | |
| 4576 | + // section re-enters it; everything else queues, and a section | |
| 4577 | + // that failed refuses what queued. | |
| 4578 | + const cell = entry.scope; | |
| 4579 | + if (cell !== undefined) { | |
| 4580 | + const block = __cellBlocks.get(cell); | |
| 4581 | + if (block !== undefined && (entry.section === null || | |
| 4582 | + entry.section !== block.holder)) | |
| 4583 | + await __gate_wait(cell); | |
| 4584 | + } | |
| 4585 | + const reply = await __ctxRun(entry.ctx, | |
| 4586 | + () => __rpcRun(async () => { | |
| 4587 | + const decoded = | |
| 4588 | + argsSc === null ? null : __rpcDesArgs(argsSc); | |
| 4589 | + try { | |
| 4590 | + return await __rpcWalk(entry.target, path, | |
| 4591 | + decoded === null ? null : decoded.args, false); | |
| 4592 | + } finally { | |
| 4593 | + if (decoded !== null) | |
| 4594 | + for (const handle of decoded.received) | |
| 4595 | + __disposeStub(handle); | |
| 4596 | + } | |
| 4597 | + }, true)); | |
| 4598 | + if (__abortedCtxs.size !== 0) { | |
| 4599 | + const aborted = __abortedCtxs.get(entry.ctx); | |
| 4600 | + if (aborted !== undefined) | |
| 4601 | + throw aborted instanceof __ActorAbort | |
| 4602 | + ? aborted.reason : aborted; | |
| 4603 | + } | |
| 4604 | + return __rpcDes(reply); | |
| 4605 | + })(); | |
| 4606 | + if (entry.ctx === undefined) return dispatch; | |
| 4607 | + // Race the op against its hosting context's abort: a hung callee | |
| 4608 | + // never settles, so the settlement check above cannot reach it. | |
| 4609 | + // A late settlement lands on an already-settled promise (no-op). | |
| 4610 | + return new Promise((resolve, reject) => { | |
| 4611 | + const untrack = __opTrack(entry.ctx, reject); | |
| 4612 | + dispatch.then( | |
| 4613 | + (value) => { untrack(); resolve(value); }, | |
| 4614 | + (error) => { untrack(); reject(error); }); | |
| 4615 | + }); | |
| 4616 | +}; | |
| 4617 | +// Resolve a path against a local, already-revived value. A hop | |
| 4618 | +// landing on a same-isolate stub delegates the rest of the path | |
| 4619 | +// to the stub's target; everything else is a plain [[Get]] so | |
| 4620 | +// Durable Object stubs and Proxies participate. | |
| 4621 | +const __walkLocal = (parent, path, args) => { | |
| 4622 | + for (let i = 0; i < path.length; i++) { | |
| 4623 | + const meta = __stubMeta.get(parent); | |
| 4624 | + if (meta) return __stubOp(meta, path.slice(i), args); | |
| 4625 | + const prop = path[i]; | |
| 4626 | + const member = parent == null ? undefined : parent[prop]; | |
| 4627 | + if (i < path.length - 1) { | |
| 4628 | + parent = member; | |
| 4629 | + continue; | |
| 4630 | + } | |
| 4631 | + if (args === null) return member; | |
| 4632 | + if (typeof member !== "function") { | |
| 4633 | + if (member === undefined) throw __rpcNoSuchMethod(prop); | |
| 4634 | + throw new TypeError('"' + prop + '" is not a function.'); | |
| 4635 | + } | |
| 4636 | + // [[Call]] directly: `.apply` on a stub proxy would be a | |
| 4637 | + // remote property access, not an invocation. | |
| 4638 | + return Reflect.apply(member, parent, args); | |
| 4639 | + } | |
| 4640 | + if (args === null) return parent; | |
| 4641 | + const meta = __stubMeta.get(parent); | |
| 4642 | + if (meta) return __stubOp(meta, [], args); | |
| 4643 | + if (typeof parent !== "function") | |
| 4644 | + throw new TypeError("The RPC value is not callable."); | |
| 4645 | + return parent(...args); | |
| 4646 | +}; | |
| 4647 | +// A session is one place pipeline ops resolve: the local value a | |
| 4648 | +// call returned, a same-isolate stub's target, or a named | |
| 4649 | +// entrypoint (whose paths resolve receiver-side in one op). | |
| 4650 | +const __valueSession = (promise) => ({ | |
| 4651 | + root: () => promise, | |
| 4652 | + get: (path) => promise.then((v) => __walkLocal(v, path, null)), | |
| 4653 | + call: (path, args) => | |
| 4654 | + promise.then((v) => __walkLocal(v, path, args)), | |
| 4655 | +}); | |
| 4656 | +const __stubSession = (meta) => ({ | |
| 4657 | + get: (path) => __stubOp(meta, path, null), | |
| 4658 | + call: (path, args) => __stubOp(meta, path, args), | |
| 4659 | +}); | |
| 4660 | +const __entrypointSession = (name, local, script, makeInst, propsSc) => ({ | |
| 4661 | + get: (path) => local | |
| 4662 | + ? (async () => __rpcDes( | |
| 4663 | + await __entrypointOp(name, path, null, true, makeInst)))() | |
| 4664 | + : (async () => __rpcDes( | |
| 4665 | + await __svc_rpc( | |
| 4666 | + script, name, JSON.stringify(path), null, propsSc)))(), | |
| 4667 | + call: (path, args) => (async () => { | |
| 4668 | + const argsSc = __rpcOut(args, local); | |
| 4669 | + if (local) | |
| 4670 | + return __rpcDes(await __entrypointOp( | |
| 4671 | + name, path, argsSc, true, makeInst)); | |
| 4672 | + return __rpcDes( | |
| 4673 | + await __svc_rpc( | |
| 4674 | + script, name, JSON.stringify(path), argsSc, propsSc)); | |
| 4675 | + })(), | |
| 4676 | +}); | |
| 4677 | +// Workerd's JsRpcPromise/JsRpcProperty: awaitable, callable, and | |
| 4678 | +// property access extends a path resolved at the far end, so | |
| 4679 | +// intermediates obey Workerd's receiver rules. `ctx` is the node's | |
| 4680 | +// owning request context -- null marks a context-free node (a | |
| 4681 | +// property path rooted directly at a service binding, which | |
| 4682 | +// starts a fresh session per await); a foreign context awaiting a | |
| 4683 | +// property or calling through the node gets Workerd's | |
| 4684 | +// cross-context error. Depth is capped like Workerd's | |
| 4685 | +// MAX_PROPERTY_DEPTH. | |
| 4686 | +const __makeNode = (session, path, ctx) => { | |
| 4687 | + let promise; | |
| 4688 | + const value = () => promise ??= (() => { | |
| 4689 | + if (path.length === 0) return session.root(); | |
| 4690 | + if (ctx !== null && ctx !== __ctxNow()) | |
| 4691 | + return Promise.reject(__ctxError("Pipeline")); | |
| 4692 | + return session.get(path); | |
| 4693 | + })(); | |
| 4694 | + const brand = | |
| 4695 | + path.length === 0 ? __cf.RpcPromise : __cf.RpcProperty; | |
| 4696 | + return new Proxy(function () {}, { | |
| 4697 | + getPrototypeOf: () => brand.prototype, | |
| 4698 | + get: (_b, p) => { | |
| 4699 | + if (p === "then") | |
| 4700 | + return (onOk, onErr) => value().then(onOk, onErr); | |
| 4701 | + if (p === "catch") return (onErr) => value().catch(onErr); | |
| 4702 | + if (p === "finally") | |
| 4703 | + return (onDone) => value().finally(onDone); | |
| 4704 | + if (typeof p !== "string") return undefined; | |
| 4705 | + if (path.length >= 5120) | |
| 4706 | + throw new TypeError( | |
| 4707 | + "RPC pipelined property chain is too deep."); | |
| 4708 | + return __makeNode(session, [...path, p], ctx); | |
| 4709 | + }, | |
| 4710 | + apply: (_b, _this, args) => { | |
| 4711 | + let call; | |
| 4712 | + if (ctx !== null && ctx !== __ctxNow()) { | |
| 4713 | + call = Promise.reject(__ctxError("JsRpcPromise")); | |
| 4714 | + call.catch(() => {}); | |
| 4715 | + } else { | |
| 4716 | + // Eager, so concurrent calls keep e-order. | |
| 4717 | + call = session.call(path, args); | |
| 4718 | + } | |
| 4719 | + return __makeNode( | |
| 4720 | + __valueSession(call), [], ctx ?? __ctxNow()); | |
| 4721 | + }, | |
| 4722 | + }); | |
| 4723 | +}; | |
| 4724 | +const __makeStub = (entry, callable) => { | |
| 4725 | + const meta = | |
| 4726 | + { entry, callable, disposed: false, ctx: __ctxNow() }; | |
| 4727 | + __ctxRegister(meta); | |
| 4728 | + const stub = new Proxy(function () {}, { | |
| 4729 | + getPrototypeOf: () => __cf.RpcStub.prototype, | |
| 4730 | + get: (_b, prop) => { | |
| 4731 | + if (prop === "then") return undefined; | |
| 4732 | + if (prop === Symbol.dispose) return () => __disposeStub(meta); | |
| 4733 | + if (prop === "dup") return () => { | |
| 4734 | + if (meta.disposed) throw __stubDisposedError(); | |
| 4735 | + entry.refs++; | |
| 4736 | + return __makeStub(entry, callable); | |
| 4737 | + }; | |
| 4738 | + if (typeof prop !== "string") return undefined; | |
| 4739 | + return __makeNode(__stubSession(meta), [prop], __ctxNow()); | |
| 4740 | + }, | |
| 4741 | + apply: (_b, _this, args) => __makeNode( | |
| 4742 | + __valueSession(__stubOp(meta, [], args)), [], __ctxNow()), | |
| 4743 | + }); | |
| 4744 | + __stubMeta.set(stub, meta); | |
| 4745 | + return stub; | |
| 4746 | +}; | |
| 4747 | +// A loopback service stub for one of this worker's own | |
| 4748 | +// entrypoints -- the ctx.exports surface. Calling the stub itself | |
| 4749 | +// returns a new stub carrying per-instance props, delivered to | |
| 4750 | +// the class constructor as ctx.props (Workerd's | |
| 4751 | +// ctx.exports.Name({ props })). | |
| 4752 | +const __svcMeta = new WeakMap(); | |
| 4753 | +const __entrypointStub = (name, props) => { | |
| 4754 | + let inst; | |
| 4755 | + const makeInst = props === undefined ? undefined : () => { | |
| 4756 | + if (inst !== undefined) return inst; | |
| 4757 | + const cls = __cell.entrypoints[name]; | |
| 4758 | + if (typeof cls !== "function") | |
| 4759 | + throw new TypeError( | |
| 4760 | + "The entrypoint " + name + " cannot carry props."); | |
| 4761 | + // Construction gets its own event, like a top-level invocation, and hands | |
| 4762 | + // that event's drain to the enclosing one. This runs inside the event of | |
| 4763 | + // the first method call on the stub, so a ctx.waitUntil() call in the | |
| 4764 | + // constructor drains before that call replies. | |
| 4765 | + inst = __constructEntrypoint(cls, props); | |
| 4766 | + return inst; | |
| 4767 | + }; | |
| 4768 | + const session = __entrypointSession(name, true, null, makeInst); | |
| 4769 | + const stub = new Proxy(function () {}, { | |
| 4770 | + getPrototypeOf: () => __cf.ServiceStub.prototype, | |
| 4771 | + get: (_b, prop) => { | |
| 4772 | + if (prop === "then") return undefined; | |
| 4773 | + if (typeof prop !== "string") return undefined; | |
| 4774 | + if (prop === "getRpcMethodForTestOnly") | |
| 4775 | + return (n) => __makeNode(session, [String(n)], null); | |
| 4776 | + // A Fetcher's fetch() is an HTTP request, as a service binding's is. | |
| 4777 | + if (prop === "fetch") | |
| 4778 | + return (input, init) => __makeServiceBinding( | |
| 4779 | + __cell.script, name === "default" ? null : name, | |
| 4780 | + props === undefined ? undefined : __rpcOut(props, false), | |
| 4781 | + ).fetch(input, init); | |
| 4782 | + return __makeNode(session, [prop], null); | |
| 4783 | + }, | |
| 4784 | + apply: (_b, _this, args) => | |
| 4785 | + __entrypointStub(name, args[0]?.props), | |
| 4786 | + }); | |
| 4787 | + __svcMeta.set(stub, { name, props }); | |
| 4788 | + __outboundMeta.set(stub, { | |
| 4789 | + script: __cell.script, | |
| 4790 | + entrypoint: name, | |
| 4791 | + props, | |
| 4792 | + }); | |
| 4793 | + return stub; | |
| 4794 | +}; | |
| 4795 | +// ---- stored stubs ---------------------------------------------- | |
| 4796 | +// Durable Object storage accepts only stubs with durable identity: | |
| 4797 | +// loopback service stubs (entrypoint name + props re-mint a fresh | |
| 4798 | +// stub on read) and Durable Object stubs (HMAC'd id + class revive | |
| 4799 | +// in any isolate). A transient handle -- a received RPC stub, a | |
| 4800 | +// function, an RpcTarget -- dies with its isolate; persisting its | |
| 4801 | +// entry id would revive garbage after a restart, so it is refused. | |
| 4802 | +// A stub-bearing row is written as 0x01 + clone(marker tree), off | |
| 4803 | +// the plain-clone fast path (the lift runs only after the plain | |
| 4804 | +// clone already threw, exactly like the RPC envelope). Reads hand | |
| 4805 | +// tagged rows to JS as [sentinel, tree]; the sentinel never leaves | |
| 4806 | +// this script and no user value can decode to it, so revival | |
| 4807 | +// cannot be spoofed by data shaped like a marker. | |
| 4808 | +const __storedSentinel = {}; | |
| 4809 | +const __storedLift = (value) => { | |
| 4810 | + let lifted = false; | |
| 4811 | + const seen = new Map(); | |
| 4812 | + const lift = (v) => { | |
| 4813 | + if (v === null || | |
| 4814 | + (typeof v !== "object" && typeof v !== "function")) return v; | |
| 4815 | + const cached = seen.get(v); | |
| 4816 | + if (cached !== undefined) return cached; | |
| 4817 | + // Ordering mirrors __stubLift: identify proxies by their | |
| 4818 | + // side tables and brands before touching any property -- a | |
| 4819 | + // stub or pipeline proxy answers every property read with a | |
| 4820 | + // fresh RpcProperty node. | |
| 4821 | + if (__stubMeta.has(v) || v instanceof __cf.RpcTarget) | |
| 4822 | + throw new DOMException( | |
| 4823 | + "Durable Object storage can only store stubs with " + | |
| 4824 | + "durable identity: service stubs from ctx.exports and " + | |
| 4825 | + "Durable Object stubs. This value is a transient RPC " + | |
| 4826 | + "handle that would not survive a restart.", | |
| 4827 | + "DataCloneError"); | |
| 4828 | + const svc = __svcMeta.get(v); | |
| 4829 | + if (svc !== undefined) { | |
| 4830 | + lifted = true; | |
| 4831 | + const marker = { "__celld$svc": svc.name }; | |
| 4832 | + seen.set(v, marker); | |
| 4833 | + if (svc.props !== undefined) marker.p = lift(svc.props); | |
| 4834 | + return marker; | |
| 4835 | + } | |
| 4836 | + if (v instanceof __cf.RpcPromise || | |
| 4837 | + v instanceof __cf.RpcProperty) | |
| 4838 | + throw new DOMException( | |
| 4839 | + 'Could not serialize object of type "' + | |
| 4840 | + (v instanceof __cf.RpcPromise ? "RpcPromise" : "RpcProperty") + | |
| 4841 | + '". This type does not support serialization.', | |
| 4842 | + "DataCloneError"); | |
| 4843 | + if (typeof v === "function") return v; // leave to the clone | |
| 4844 | + const doId = __doStubMeta.get(v); | |
| 4845 | + if (doId !== undefined) { | |
| 4846 | + lifted = true; | |
| 4847 | + const marker = { "__celld$do": doId._className, | |
| 4848 | + v: doId._value, n: v.name ?? null }; | |
| 4849 | + seen.set(v, marker); | |
| 4850 | + return marker; | |
| 4851 | + } | |
| 4852 | + if (Array.isArray(v)) { | |
| 4853 | + const out = []; | |
| 4854 | + seen.set(v, out); | |
| 4855 | + for (let i = 0; i < v.length; i++) out[i] = lift(v[i]); | |
| 4856 | + return out; | |
| 4857 | + } | |
| 4858 | + const proto = Object.getPrototypeOf(v); | |
| 4859 | + if (proto !== Object.prototype && proto !== null) | |
| 4860 | + return v; // host/other: leave to the clone | |
| 4861 | + const out = {}; | |
| 4862 | + seen.set(v, out); | |
| 4863 | + for (const key of Object.keys(v)) out[key] = lift(v[key]); | |
| 4864 | + return out; | |
| 4865 | + }; | |
| 4866 | + const tree = lift(value); | |
| 4867 | + return lifted ? tree : null; | |
| 4868 | +}; | |
| 4869 | +// Encode one stub-bearing value for storage. Rethrows the original | |
| 4870 | +// clone error when nothing was liftable, so plain uncloneables | |
| 4871 | +// fail exactly as they always did. | |
| 4872 | +const __storedBytes = (value, error) => { | |
| 4873 | + const tree = __storedLift(value); | |
| 4874 | + if (tree === null) throw error; | |
| 4875 | + return __tagged(1, __sc_encode(tree)); | |
| 4876 | +}; | |
| 4877 | +const __storedRevive = (value) => { | |
| 4878 | + const seen = new Set(); | |
| 4879 | + const revive = (v) => { | |
| 4880 | + if (v === null || typeof v !== "object") return v; | |
| 4881 | + const svcName = v["__celld$svc"]; | |
| 4882 | + if (svcName !== undefined) | |
| 4883 | + return __entrypointStub(svcName, revive(v.p)); | |
| 4884 | + const doClass = v["__celld$do"]; | |
| 4885 | + if (doClass !== undefined) | |
| 4886 | + return __cell.makeNamespace(doClass).get( | |
| 4887 | + new DurableObjectId(doClass, v.v, v.n ?? undefined)); | |
| 4888 | + if (seen.has(v)) return v; | |
| 4889 | + seen.add(v); | |
| 4890 | + if (Array.isArray(v)) { | |
| 4891 | + for (let i = 0; i < v.length; i++) v[i] = revive(v[i]); | |
| 4892 | + return v; | |
| 4893 | + } | |
| 4894 | + const proto = Object.getPrototypeOf(v); | |
| 4895 | + if (proto !== Object.prototype && proto !== null) return v; | |
| 4896 | + for (const key of Object.keys(v)) v[key] = revive(v[key]); | |
| 4897 | + return v; | |
| 4898 | + }; | |
| 4899 | + return revive(value); | |
| 4900 | +}; | |
| 4901 | +const __unwrapStored = (v) => | |
| 4902 | + Array.isArray(v) && v[0] === __storedSentinel | |
| 4903 | + ? __storedRevive(v[1]) : v; | |
| 4904 | +// A map result is wrapped as a whole only when it holds at least | |
| 4905 | +// one tagged row, so the per-entry walk never runs on plain data. | |
| 4906 | +const __unwrapStoredMap = (v) => { | |
| 4907 | + if (!Array.isArray(v) || v[0] !== __storedSentinel) return v; | |
| 4908 | + const map = v[1]; | |
| 4909 | + for (const [key, value] of map) | |
| 4910 | + map.set(key, __unwrapStored(value)); | |
| 4911 | + return map; | |
| 4912 | +}; | |
| 4913 | +// ctx.exports, as workerd's server builds it: a loopback stub for | |
| 4914 | +// `default` and each other entrypoint, a namespace for each exported | |
| 4915 | +// Durable Object class with storage, and a class, for facets, for | |
| 4916 | +// each other exported one. Built once, on first access -- ctx | |
| 4917 | +// construction itself only carries the getter. | |
| 4918 | +let __ctxExportsCache; | |
| 4919 | +const __ctxExports = () => __ctxExportsCache ??= (() => { | |
| 4920 | + const out = {}; | |
| 4921 | + for (const name of Object.keys(__cell.entrypoints)) | |
| 4922 | + out[name] = __entrypointStub(name, undefined); | |
| 4923 | + for (const name of Object.keys(__cell.objectEntrypoints)) | |
| 4924 | + out[name] = __entrypointStub(name, undefined); | |
| 4925 | + // Loader 0 is the script's own isolate: a facet of such a class runs | |
| 4926 | + // beside the object that holds it. | |
| 4927 | + for (const name of Object.keys(__cell.doExports)) { | |
| 4928 | + if (__runtimeClasses.has(name)) continue; | |
| 4929 | + out[name] = Object.hasOwn(__cell.namespaceKeys, name) | |
| 4930 | + ? __cell.makeNamespace(name) | |
| 4931 | + : __makeDurableObjectClass(Promise.resolve(0), name, undefined); | |
| 4932 | + } | |
| 4933 | + return out; | |
| 4934 | +})(); | |
| 4935 | +// ---- RPC envelope ---------------------------------------------- | |
| 4936 | +// Serialize one payload. `lift` marks a same-isolate transport, | |
| 4937 | +// where stub-able values may cross as markers; elsewhere they stay | |
| 4938 | +// a DataCloneError, exactly as before stubs existed. | |
| 4939 | +const __rpcOut = (value, lift) => { | |
| 4940 | + const projected = __rpcProject(value); | |
| 4941 | + try { | |
| 4942 | + return __sc_encode(projected.tree); | |
| 4943 | + } catch (error) { | |
| 4944 | + // A cross-isolate call lifts only a live signal. A same-isolate call can | |
| 4945 | + // also transfer the existing host values and JS capability handles. | |
| 4946 | + const lifted = __stubLift(projected.tree, lift, projected.originals); | |
| 4947 | + if (lifted === null) throw __dataCloneError(error); | |
| 4948 | + try { | |
| 4949 | + return __tagged( | |
| 4950 | + lifted.caps ? 1 : 2, __sc_encode(lifted.tree)); | |
| 4951 | + } catch (error_) { | |
| 4952 | + throw __dataCloneError(error_); | |
| 4953 | + } | |
| 4954 | + } | |
| 4955 | +}; | |
| 4956 | +// A callee exception as tagged bytes: the Error crosses by value | |
| 4957 | +// (V8 serializes Error natively), custom own properties beside it. | |
| 4958 | +const __rpcErrOut = (error) => { | |
| 4959 | + // `name` rides in the props: V8 only round-trips the standard | |
| 4960 | + // Error subclass names, and e.g. DataCloneError must survive. | |
| 4961 | + const props = error instanceof Error | |
| 4962 | + ? { ...error, name: error.name } : {}; | |
| 4963 | + let sc; | |
| 4964 | + try { | |
| 4965 | + sc = __sc_encode([error, props]); | |
| 4966 | + } catch { | |
| 4967 | + const error_ = new Error(String(error?.message ?? error)); | |
| 4968 | + sc = __sc_encode([error_, { name: String(error?.name ?? "Error") }]); | |
| 4969 | + } | |
| 4970 | + return __tagged(0, sc); | |
| 4971 | +}; | |
| 4972 | +// The callee half of one RPC: run `body`, answer tagged bytes. | |
| 4973 | +const __rpcRun = async (body, lift) => { | |
| 4974 | + try { | |
| 4975 | + return __rpcOut(await body(), lift); | |
| 4976 | + } catch (error) { | |
| 4977 | + return __rpcErrOut(error); | |
| 4978 | + } | |
| 4979 | +}; | |
| 4980 | +const __rpcDesArgs = (bytes) => { | |
| 4981 | + if (bytes[0] === 0xff) | |
| 4982 | + return { args: __sc_decode(bytes), received: [] }; | |
| 4983 | + const revived = __stubRevive(__sc_decode(bytes.subarray(1))); | |
| 4984 | + return { args: revived.value, received: revived.handles }; | |
| 4985 | +}; | |
| 4986 | +// The caller half: decode a reply, rebuilding stubs and rethrowing | |
| 4987 | +// callee exceptions as real Errors with the callee's own | |
| 4988 | +// properties, `.remote`, and a local (caller-side) stack. | |
| 4989 | +const __rpcDes = (bytes) => { | |
| 4990 | + if (bytes[0] === 0xff) return __sc_decode(bytes); | |
| 4991 | + if (bytes[0] === 1 || bytes[0] === 2) { | |
| 4992 | + const { value, handles, disposers } = | |
| 4993 | + __stubRevive(__sc_decode(bytes.subarray(1))); | |
| 4994 | + if (value !== null && typeof value === "object" && | |
| 4995 | + !__stubMeta.has(value) && | |
| 4996 | + (handles.length > 0 || disposers.length > 0)) { | |
| 4997 | + Object.defineProperty(value, Symbol.dispose, { | |
| 4998 | + configurable: true, | |
| 4999 | + value: () => { | |
| 5000 | + for (const handle of handles) __disposeStub(handle); | |
| 5001 | + for (const entry of disposers) { | |
| 5002 | + __stubEntries.delete(entry.id); | |
| 5003 | + Promise.resolve().then(() => entry.target()); | |
| 5004 | + } | |
| 5005 | + }, | |
| 5006 | + }); | |
| 5007 | + } | |
| 5008 | + return value; | |
| 5009 | + } | |
| 5010 | + const [error, props] = __sc_decode(bytes.subarray(1)); | |
| 5011 | + if (error instanceof Error) { | |
| 5012 | + Object.assign(error, props); | |
| 5013 | + error.remote = true; | |
| 5014 | + const local = new Error().stack; | |
| 5015 | + error.stack = error.name + ": " + error.message + | |
| 5016 | + local.slice(local.indexOf("\n")); | |
| 5017 | + } | |
| 5018 | + throw error; | |
| 5019 | +}; | |
| 5020 | +// Deprecated Fetcher `get()`/`put()`/`delete()` HTTP helpers, kept by | |
| 5021 | +// the fetcher_has_get_put_delete compat flag (Workerd http.c++): | |
| 5022 | +// shortcuts for fetch() with the corresponding method. | |
| 5023 | +const __fetcherStatus = (res, method) => { | |
| 5024 | + if (res.status >= 200 && res.status < 300) return; | |
| 5025 | + throw new Error("HTTP " + method + " request failed: " + res.status + | |
| 5026 | + " " + (res.statusText || __STATUS_TEXT[res.status] || "")); | |
| 5027 | +}; | |
| 5028 | +const __fetcherHelper = (fetch, prop) => { | |
| 5029 | + if (prop === "get") return async (url, type) => { | |
| 5030 | + const res = await fetch(url, { method: "GET" }); | |
| 5031 | + if (res.status === 404 || res.status === 410) return null; | |
| 5032 | + __fetcherStatus(res, "GET"); | |
| 5033 | + if (type === "stream") | |
| 5034 | + return res.body ?? new ReadableStream({ start(c) { c.close(); } }); | |
| 5035 | + if (type === "arrayBuffer") return res.arrayBuffer(); | |
| 5036 | + if (type === "json") return res.json(); | |
| 5037 | + return res.text(); | |
| 5038 | + }; | |
| 5039 | + if (prop === "put") return async (url, body, options) => { | |
| 5040 | + const { expiration, expirationTtl } = options ?? {}; | |
| 5041 | + if (expiration !== undefined || expirationTtl !== undefined) { | |
| 5042 | + const url_ = new URL(url); | |
| 5043 | + if (expiration !== undefined) | |
| 5044 | + url_.searchParams.append("expiration", expiration); | |
| 5045 | + if (expirationTtl !== undefined) | |
| 5046 | + url_.searchParams.append("expiration_ttl", expirationTtl); | |
| 5047 | + url = url_.toString(); | |
| 5048 | + } | |
| 5049 | + __fetcherStatus(await fetch(url, { method: "PUT", body }), "PUT"); | |
| 5050 | + }; | |
| 5051 | + return async (url) => { | |
| 5052 | + __fetcherStatus(await fetch(url, { method: "DELETE" }), "DELETE"); | |
| 5053 | + }; | |
| 5054 | +}; | |
| 5055 | +function makeNamespace(className) { | |
| 5056 | + const namespaceKey = __cell.namespaceKeys[className]; | |
| 5057 | + if (typeof namespaceKey !== "string") | |
| 5058 | + throw new Error("no Durable Object namespace key for " + className); | |
| 5059 | + return new DurableObjectNamespace(className, namespaceKey); | |
| 5060 | +} | |
| 5061 | +// A named class: SDKs sniff bindings by constructor name (workers-rs | |
| 5062 | +// EnvBinding requires `constructor.name === "DurableObjectNamespace"`). | |
| 5063 | +class DurableObjectNamespace { | |
| 5064 | + constructor(className, namespaceKey) { | |
| 5065 | + Object.defineProperty(this, "_className", { value: className }); | |
| 5066 | + Object.defineProperty(this, "_namespaceKey", { value: namespaceKey }); | |
| 5067 | + } | |
| 5068 | + idFromName(name) { | |
| 5069 | + name = String(name); | |
| 5070 | + return new DurableObjectId( | |
| 5071 | + this._className, __do_id(this._namespaceKey, "name", name), name, | |
| 5072 | + ); | |
| 5073 | + } | |
| 5074 | + idFromString(value) { | |
| 5075 | + return new DurableObjectId( | |
| 5076 | + this._className, __do_id(this._namespaceKey, "validate", String(value)), | |
| 5077 | + ); | |
| 5078 | + } | |
| 5079 | + newUniqueId(options = {}) { | |
| 5080 | + const jurisdiction = options == null ? undefined : options.jurisdiction; | |
| 5081 | + if (jurisdiction != null) | |
| 5082 | + throw new Error("Jurisdiction restrictions are not implemented"); | |
| 5083 | + return new DurableObjectId( | |
| 5084 | + this._className, __do_id(this._namespaceKey, "unique", ""), | |
| 5085 | + ); | |
| 5086 | + } | |
| 5087 | + jurisdiction(value) { | |
| 5088 | + if (value == null) return this; | |
| 5089 | + throw new Error("Jurisdiction restrictions are not implemented"); | |
| 5090 | + } | |
| 5091 | + getByName(name, options) { | |
| 5092 | + return this.get(this.idFromName(name), options); | |
| 5093 | + } | |
| 5094 | + get(id) { | |
| 5095 | + const className = this._className; | |
| 5096 | + if (!(id instanceof DurableObjectId) || id._className !== className) | |
| 5097 | + throw new TypeError("Durable Object ID is not valid for this namespace"); | |
| 5098 | + const scope = id._scope(); | |
| 5099 | + // Emulate production: the actor recovers its name only when it is | |
| 5100 | + // <= 1024 UTF-8 bytes; longer names are dropped so ctx.id.name is | |
| 5101 | + // undefined. The full name still seeds the routing hash, so | |
| 5102 | + // dispatch is unchanged. Short names skip the byte count (< 256 | |
| 5103 | + // chars is always <= 1020 bytes) to keep the hot path alloc-free. | |
| 5104 | + const nm = id.name; | |
| 5105 | + const dispatchName = nm === undefined ? undefined | |
| 5106 | + : nm.length < 256 || new TextEncoder().encode(nm).length <= 1024 | |
| 5107 | + ? nm : undefined; | |
| 5108 | + if (dispatchName !== undefined) __cell.idNames[scope] = dispatchName; | |
| 5109 | + // Fetch and native RPC use the same host routing/activation seam. | |
| 5110 | + // Never expose `.then`: a DO stub is not itself a promise. | |
| 5111 | + const target = { id, name: dispatchName }; | |
| 5112 | + const abortMarker = "__CELLD_ACTOR_ABORT__:"; | |
| 5113 | + const processExitMarker = "__CELLD_PROCESS_EXIT__:"; | |
| 5114 | + let brokenReason = null; | |
| 5115 | + const invoke = async (operation) => { | |
| 5116 | + if (brokenReason !== null) throw new Error(brokenReason); | |
| 5117 | + try { | |
| 5118 | + return await operation(); | |
| 5119 | + } catch (error) { | |
| 5120 | + const routingError = __durableObjectRoutingError(error); | |
| 5121 | + if (routingError !== null) throw routingError; | |
| 5122 | + const message = String(error && error.message || error); | |
| 5123 | + const marker = [abortMarker, processExitMarker] | |
| 5124 | + .find((candidate) => message.includes(candidate)); | |
| 5125 | + if (!marker) throw error; | |
| 5126 | + brokenReason = message.slice(message.indexOf(marker) + marker.length); | |
| 5127 | + throw new Error(brokenReason); | |
| 5128 | + } | |
| 5129 | + }; | |
| 5130 | + const doFetch = async (input, init) => { | |
| 5131 | + const req = new Request(input, init); | |
| 5132 | + const signal = req._signalForSubrequests; | |
| 5133 | + if (signal?.aborted) throw signal.reason; | |
| 5134 | + // A body already backed by a host stream forwards to the cell as its | |
| 5135 | + // stream id, so a proxied upload to a cell on this node costs a chunk | |
| 5136 | + // rather than the whole body (#156). The host keeps it a stream for a | |
| 5137 | + // local cell and collects it only to sign a cross-node frame. A held | |
| 5138 | + // body -- or a stream with no host id -- crosses as its bytes. | |
| 5139 | + const bodyStreamId = | |
| 5140 | + req._bodyBytes === null && req.body && req.body.__celldStreamId !== undefined | |
| 5141 | + ? req.body.__celldStreamId | |
| 5142 | + : undefined; | |
| 5143 | + const body_ = bodyStreamId !== undefined | |
| 5144 | + ? new Uint8Array() | |
| 5145 | + : req._bodyBytes === null | |
| 5146 | + ? await req._consume() | |
| 5147 | + : req._bodyBytes; | |
| 5148 | + if (bodyStreamId !== undefined) { | |
| 5149 | + // The cell reads this upload through the same host stream id, so the | |
| 5150 | + // Worker's wrapper must not also read it: lock it (a late read throws | |
| 5151 | + // instead of racing the cell over one host stream) and mark it used, | |
| 5152 | + // which is what awaiting the old _consume() did and what workerd | |
| 5153 | + // reports as request.bodyUsed after the forward. | |
| 5154 | + req.bodyUsed = true; | |
| 5155 | + req.body.getReader(); | |
| 5156 | + } | |
| 5157 | + // Forward the request's headers to the cell as JSON. When they were | |
| 5158 | + // never materialized -- a Worker that only routes to a cell reads | |
| 5159 | + // none -- pass the raw header string straight through, so the whole | |
| 5160 | + // dispatch never builds a Headers object on either side. | |
| 5161 | + // | |
| 5162 | + // Both branches now carry the same shape. The raw string is the | |
| 5163 | + // wire list the host handed in, so the materialized branch must send | |
| 5164 | + // the header list too, not the iterator; see the note on the | |
| 5165 | + // outbound `fetch`. Reading `.headers` on a forwarded request used | |
| 5166 | + // to change what the cell received. | |
| 5167 | + const headersJson = req._headersJson !== undefined | |
| 5168 | + ? req._headersJson | |
| 5169 | + : JSON.stringify(req.headers.__celldHeaderList); | |
| 5170 | + const r = JSON.parse(await invoke(() => { | |
| 5171 | + if (!signal) return __do_call( | |
| 5172 | + scope, dispatchName ?? null, req.url, req.method, body_, | |
| 5173 | + headersJson, bodyStreamId, | |
| 5174 | + ); | |
| 5175 | + return __awaitCancellableDoCall( | |
| 5176 | + __do_call_cancellable( | |
| 5177 | + scope, dispatchName ?? null, req.url, req.method, body_, | |
| 5178 | + headersJson, bodyStreamId, | |
| 5179 | + ), | |
| 5180 | + signal, | |
| 5181 | + ); | |
| 5182 | + })); | |
| 5183 | + const body = r.streamId !== undefined | |
| 5184 | + ? new CelldHttpBodyStream(r.streamId) | |
| 5185 | + : r.body !== undefined | |
| 5186 | + ? r.body | |
| 5187 | + : Uint8Array.from(r.bodyBytes || []); | |
| 5188 | + // An upgrade the cell answered with. The pair straddles two isolates, | |
| 5189 | + // so the client end cannot be the peer object itself -- it is a new | |
| 5190 | + // socket the host joins to the cell's on `accept()`. A caller that | |
| 5191 | + // returns this response instead of accepting keeps the direct route | |
| 5192 | + // `__wsTarget` already describes, and binds nothing. | |
| 5193 | + return new Response(body, { | |
| 5194 | + status: r.status, | |
| 5195 | + headers: r.headers, | |
| 5196 | + __wsTarget: r.wsTarget, | |
| 5197 | + webSocket: r.status === 101 && r.wsTarget | |
| 5198 | + ? new WebSocket(undefined, [], r.wsTarget) | |
| 5199 | + : undefined, | |
| 5200 | + }); | |
| 5201 | + }; | |
| 5202 | + const stub = new Proxy(target, { get: (_target, prop) => { | |
| 5203 | + if (prop === "then") return undefined; | |
| 5204 | + if (Reflect.has(_target, prop)) return Reflect.get(_target, prop); | |
| 5205 | + if (prop === "fetch") return doFetch; | |
| 5206 | + if (typeof prop !== "string") return undefined; | |
| 5207 | + if (__cell.compat.fetcherGetPutDelete && | |
| 5208 | + (prop === "get" || prop === "put" || prop === "delete")) | |
| 5209 | + return __fetcherHelper(doFetch, prop); | |
| 5210 | + // Every cell RPC goes out through the host, whichever node owns the | |
| 5211 | + // target. Same-process dispatch re-enters this isolate, where the | |
| 5212 | + // abort and exit markers revive; bytes that land elsewhere revive as | |
| 5213 | + // loud foreign stubs. | |
| 5214 | + return async (...args) => invoke( | |
| 5215 | + async () => __rpcDes(await __rpc_call( | |
| 5216 | + scope, dispatchName ?? null, prop, __rpcOut(args, true), | |
| 5217 | + )), | |
| 5218 | + ); | |
| 5219 | + }}); | |
| 5220 | + __doStubMeta.set(stub, id); | |
| 5221 | + return stub; | |
| 5222 | + } | |
| 5223 | +} | |
| 5224 | +const __attachResponseRequestCancellation = ( | |
| 5225 | + response, | |
| 5226 | + requestController, | |
| 5227 | + wrapBody, | |
| 5228 | +) => { | |
| 5229 | + if (!(response instanceof Response) || | |
| 5230 | + response._bodyBytes !== null || | |
| 5231 | + response.body === null) { | |
| 5232 | + return; | |
| 5233 | + } | |
| 5234 | + const requestControllers = Array.isArray( | |
| 5235 | + response.__celldRequestControllers, | |
| 5236 | + ) | |
| 5237 | + ? response.__celldRequestControllers | |
| 5238 | + : [requestController]; | |
| 5239 | + if (requestControllers !== response.__celldRequestControllers) { | |
| 5240 | + Object.defineProperty(response, "__celldRequestControllers", { | |
| 5241 | + value: requestControllers, | |
| 5242 | + }); | |
| 5243 | + } else { | |
| 5244 | + requestControllers.push(requestController); | |
| 5245 | + } | |
| 5246 | + if (!wrapBody || response.__celldCancellationWrapped) return; | |
| 5247 | + const reader = response.body.getReader(); | |
| 5248 | + response.body = new ReadableStream({ | |
| 5249 | + async pull(controller) { | |
| 5250 | + const result = await reader.read(); | |
| 5251 | + if (result.done) controller.close(); | |
| 5252 | + else controller.enqueue(result.value); | |
| 5253 | + }, | |
| 5254 | + async cancel() { | |
| 5255 | + const reason = new Error("The client has disconnected"); | |
| 5256 | + for (const controller of requestControllers) { | |
| 5257 | + if (!controller.signal.aborted) controller.abort(reason); | |
| 5258 | + } | |
| 5259 | + try { | |
| 5260 | + await reader.cancel(reason); | |
| 5261 | + } catch {} | |
| 5262 | + }, | |
| 5263 | + }, { highWaterMark: 0 }); | |
| 5264 | + Object.defineProperty(response, "__celldCancellationWrapped", { | |
| 5265 | + value: true, | |
| 5266 | + }); | |
| 5267 | +}; | |
| 5268 | +// called on the owner node by the /__do/<scope> endpoint: run one object. | |
| 5269 | +// Returns the Response; Rust's read_response unwraps it (don't double-wrap). | |
| 5270 | +// A top-level (non-actor) request whose signal can be aborted by id, so a | |
| 5271 | +// disconnected HTTP or service-binding caller reaches the target's | |
| 5272 | +// `request.signal`. | |
| 5273 | +// A large body, or a body of unknown length, arrives as a stream id and | |
| 5274 | +// not as bytes. The handler then pulls the body off the socket as it | |
| 5275 | +// reads, so the whole body is never resident. `request.body` is a stream | |
| 5276 | +// in both cases. | |
| 5277 | +__celld.__makeIncomingRequest = ( | |
| 5278 | + url, method, body, headersJson, streamId, | |
| 5279 | +) => __makeRequest( | |
| 5280 | + url, method, | |
| 5281 | + streamId === undefined ? body : new CelldHttpBodyStream(streamId), | |
| 5282 | + headersJson, undefined, true); | |
| 5283 | +const __dispatchTo = __celld.__dispatchTo = async ( | |
| 5284 | + scope, url, method, body, headersJson, requestId = null, bodyStreamId = null, | |
| 5285 | +) => { | |
| 5286 | + // A routed body that must not be collected crosses as a host stream id; the | |
| 5287 | + // handler here reads it in parts. A held body arrives as its bytes. | |
| 5288 | + if (bodyStreamId !== null) body = new CelldHttpBodyStream(bodyStreamId); | |
| 5289 | + // Request already allocates a default controller for an absent signal. | |
| 5290 | + // Retain that same allocation so a streamed response can report reader | |
| 5291 | + // cancellation after the handler has returned. | |
| 5292 | + const requestController = new AbortController(); | |
| 5293 | + if (requestId !== null) | |
| 5294 | + __incomingRequestSignals.set( | |
| 5295 | + String(requestId), requestController.signal); | |
| 5296 | + const actorEvent = __beginActorEvent(scope); | |
| 5297 | + try { | |
| 5298 | + const dispatch = (async () => { | |
| 5299 | + const inst = await _readyInstance(scope); | |
| 5300 | + return await __ctxRun(undefined, () => inst.fetch( | |
| 5301 | + __makeRequest( | |
| 5302 | + url, | |
| 5303 | + method, | |
| 5304 | + body, | |
| 5305 | + headersJson, | |
| 5306 | + requestController.signal, | |
| 5307 | + true, | |
| 5308 | + ))); | |
| 5309 | + })(); | |
| 5310 | + // The caller's abandonment reaches the target through | |
| 5311 | + // __do_call_cancel/__abortIncomingRequest, which aborts the fresh incoming | |
| 5312 | + // signal made above; the host dispatcher passes no caller signal here. | |
| 5313 | + const response = await dispatch; | |
| 5314 | + // Not wrapped: the host holds this response and gates it, and the caller | |
| 5315 | + // that would cancel the body reaches it through the routed channel's own | |
| 5316 | + // controller rather than this one. | |
| 5317 | + __attachResponseRequestCancellation(response, requestController, false); | |
| 5318 | + if (response instanceof Response && response.status === 101 && | |
| 5319 | + response.webSocket && !response.webSocket._target) { | |
| 5320 | + const socket = response.webSocket._peer; | |
| 5321 | + const target = { id: response.webSocket._id, scope }; | |
| 5322 | + response.webSocket._target = target; | |
| 5323 | + if (socket) { | |
| 5324 | + socket._target = target; | |
| 5325 | + if (!socket._hibernatable) | |
| 5326 | + __ws_accept_regular(socket._id, scope); | |
| 5327 | + __sockets.set(socket._id, socket); | |
| 5328 | + socket._flushPending(); | |
| 5329 | + } | |
| 5330 | + } | |
| 5331 | + return response; | |
| 5332 | + } finally { | |
| 5333 | + if (requestId !== null) | |
| 5334 | + __incomingRequestSignals.delete(String(requestId)); | |
| 5335 | + __endActorEvent(actorEvent); | |
| 5336 | + } | |
| 5337 | +}; | |
| 5338 | +const __rpcTargetMethod = async (scope, method) => { | |
| 5339 | + const inst = await _readyInstance(scope); | |
| 5340 | + if (!inst.__celldState._rpcOk) | |
| 5341 | + throw new TypeError( | |
| 5342 | + "The receiving Durable Object does not support RPC, because " + | |
| 5343 | + "its class was not declared with `extends DurableObject`. In " + | |
| 5344 | + "order to enable RPC, make sure your class extends the " + | |
| 5345 | + "special class `DurableObject`, which can be imported from " + | |
| 5346 | + "the module \"cloudflare:workers\"."); | |
| 5347 | + const fn = inst[method]; | |
| 5348 | + if (typeof fn !== "function") | |
| 5349 | + throw new TypeError(method + " is not a function"); | |
| 5350 | + return [inst, fn]; | |
| 5351 | +}; | |
| 5352 | +// The byte path always lifts stub-able values into the reply: the | |
| 5353 | +// markers carry the isolate token, so they revive only back in this | |
| 5354 | +// isolate (same-process routed dispatch re-enters it) and fail loudly | |
| 5355 | +// on use anywhere else. Callee exceptions cross in | |
| 5356 | +// the error envelope on every flavor. | |
| 5357 | +__celld.__dispatchRpc = async (scope, method, args) => { | |
| 5358 | + const actorEvent = __beginActorEvent(scope); | |
| 5359 | + try { | |
| 5360 | + // A string is the legacy JSON flavor; bytes are V8 structured clone. | |
| 5361 | + // Answer in kind. | |
| 5362 | + if (typeof args === "string") { | |
| 5363 | + const [inst, fn] = await __rpcTargetMethod(scope, method); | |
| 5364 | + const result = await fn.apply(inst, JSON.parse(args)); | |
| 5365 | + return JSON.stringify(result) ?? "null"; | |
| 5366 | + } | |
| 5367 | + return await __ctxRun(undefined, () => (async () => { | |
| 5368 | + const decoded = __rpcDesArgs(args); | |
| 5369 | + try { | |
| 5370 | + return await __rpcRun(async () => { | |
| 5371 | + // A broken actor (JS-flavored ctx.abort) rejects every | |
| 5372 | + // later call with the reason. One gated field read. | |
| 5373 | + if (__brokenActors.size !== 0) { | |
| 5374 | + const broken = __brokenActors.get(scope); | |
| 5375 | + if (broken !== undefined) throw broken; | |
| 5376 | + } | |
| 5377 | + const [inst, fn] = await __rpcTargetMethod(scope, method); | |
| 5378 | + return fn.apply(inst, decoded.args); | |
| 5379 | + }, true); | |
| 5380 | + } finally { | |
| 5381 | + for (const handle of decoded.received) __disposeStub(handle); | |
| 5382 | + } | |
| 5383 | + })()); | |
| 5384 | + } finally { | |
| 5385 | + __endActorEvent(actorEvent); | |
| 5386 | + } | |
| 5387 | +}; | |
| 5388 | +const __entrypointClass = (name) => { | |
| 5389 | + const cls = __cell.entrypoints[name]; | |
| 5390 | + if (typeof cls !== "function") { | |
| 5391 | + // Workerd getExportedHandler(): distinguish a Durable Object class | |
| 5392 | + // misused as a stateless entrypoint from a name that resolves to | |
| 5393 | + // nothing. Error path only; both lookups are O(1). | |
| 5394 | + if (__cell.classes[name] !== undefined || __cell.doExports[name]) | |
| 5395 | + throw new TypeError( | |
| 5396 | + `The entrypoint name ${name} refers to a Durable Object ` + | |
| 5397 | + "class, but the incoming request is trying to invoke it as " + | |
| 5398 | + "a stateless worker."); | |
| 5399 | + throw new TypeError( | |
| 5400 | + `The entrypoint name ${name} was not found in this worker. ` + | |
| 5401 | + "Ensure the worker exports an entrypoint with that name."); | |
| 5402 | + } | |
| 5403 | + return cls; | |
| 5404 | +}; | |
| 5405 | +// End the construction event immediately: ctx.waitUntil registers into | |
| 5406 | +// whichever event is current at call time, so leaving this event on the | |
| 5407 | +// stack would swallow every later registration in the isolate. The drain that | |
| 5408 | +// the event yields moves to the enclosing event, because a ctx.waitUntil() | |
| 5409 | +// call inside a constructor is otherwise fire-and-forget: the RPC reply can | |
| 5410 | +// answer and the request context can tear down before that work runs. | |
| 5411 | +// __wait_until drops the drain when no event encloses this one, which is the | |
| 5412 | +// isolate-startup case and matches the older behavior. | |
| 5413 | +const __constructEntrypoint = (cls, props) => { | |
| 5414 | + const ctx = __beginEvent(props); | |
| 5415 | + try { | |
| 5416 | + return new cls(ctx, __cell.env); | |
| 5417 | + } finally { | |
| 5418 | + const drain = __endEvent(); | |
| 5419 | + if (drain !== null) __wait_until(drain); | |
| 5420 | + } | |
| 5421 | +}; | |
| 5422 | +// A stateless Worker invocation owns one class instance and its constructor | |
| 5423 | +// context. Reusing either across invocations leaks class fields and request | |
| 5424 | +// authority, while constructing more than once inside one invocation splits | |
| 5425 | +// work that Cloudflare delivers to one receiver. | |
| 5426 | +const __newEntrypointInstance = (name, props) => | |
| 5427 | + __constructEntrypoint(__entrypointClass(name), props); | |
| 5428 | +// `env.NAME.fetch()` where NAME is bound with `entrypoint = "..."` goes | |
| 5429 | +// to that class's fetch, not the module's default export. A plain | |
| 5430 | +// object export (Workerd's non-class entrypoint) dispatches its | |
| 5431 | +// handler functions as fn(arg, env, ctx). | |
| 5432 | +// A missing fetch reports workerd's own text, the same one the loader | |
| 5433 | +// installs for a Worker with no default export, so the two paths agree. | |
| 5434 | +const __noHandler = (name, method) => | |
| 5435 | + method === "fetch" && name === "default" | |
| 5436 | + ? new Error("Handler does not export a fetch() function.") | |
| 5437 | + : new TypeError( | |
| 5438 | + `Entrypoint ${JSON.stringify(name)} has no ${method} handler`); | |
| 5439 | + | |
| 5440 | +const __dispatchEntrypointMethod = async (name, method, arg, props) => { | |
| 5441 | + const handler = __cell.objectEntrypoints[name]; | |
| 5442 | + if (handler !== undefined) { | |
| 5443 | + if (typeof handler[method] !== "function") | |
| 5444 | + throw __noHandler(name, method); | |
| 5445 | + const ctx = __beginEvent(props); | |
| 5446 | + try { | |
| 5447 | + return await __ctxRun(undefined, | |
| 5448 | + () => handler[method](arg, __cell.env, ctx)); | |
| 5449 | + } finally { | |
| 5450 | + __endEvent(); | |
| 5451 | + } | |
| 5452 | + } | |
| 5453 | + // A class entrypoint's methods get env and ctx from its constructor, | |
| 5454 | + // not as arguments. | |
| 5455 | + const inst = __newEntrypointInstance(name, props); | |
| 5456 | + if (typeof inst[method] !== "function") | |
| 5457 | + throw __noHandler(name, method); | |
| 5458 | + return await __ctxRun(undefined, () => inst[method](arg)); | |
| 5459 | +}; | |
| 5460 | +// Invoke a handler inside the event frame that the host already opened. A | |
| 5461 | +// Queue dispatch uses this form because its host driver must receive and keep | |
| 5462 | +// driving the handler's waitUntil aggregate after the settlement is returned. | |
| 5463 | +const __dispatchEntrypointMethodInCurrentEvent = async (name, method, arg) => { | |
| 5464 | + const handler = __cell.objectEntrypoints[name]; | |
| 5465 | + if (handler !== undefined) { | |
| 5466 | + if (typeof handler[method] !== "function") | |
| 5467 | + throw __noHandler(name, method); | |
| 5468 | + return await __ctxRun(undefined, | |
| 5469 | + () => handler[method](arg, __cell.env, __entrypointContext())); | |
| 5470 | + } | |
| 5471 | + const inst = __newEntrypointInstance(name, undefined); | |
| 5472 | + if (typeof inst[method] !== "function") | |
| 5473 | + throw __noHandler(name, method); | |
| 5474 | + return await __ctxRun(undefined, () => inst[method](arg)); | |
| 5475 | +}; | |
| 5476 | +const __dispatchEntrypointFetch = __celld.__dispatchEntrypointFetch = | |
| 5477 | + (name, request, propsSc = null) => | |
| 5478 | + __dispatchEntrypointMethod( | |
| 5479 | + name, "fetch", request, | |
| 5480 | + propsSc === null || propsSc.length === 0 | |
| 5481 | + ? undefined : __sc_decode(propsSc)); | |
| 5482 | +__celld.__dispatchEntrypointScheduled = (name, ctrl) => | |
| 5483 | + __dispatchEntrypointMethod(name, "scheduled", ctrl); | |
| 5484 | +// A queue batch owns mutable settlement state only while its handler runs. | |
| 5485 | +// Keeping a batch alive after dispatch must not keep authority to settle its | |
| 5486 | +// lease, because that lease can have expired and been handed out again. | |
| 5487 | +__celld.__dispatchEntrypointQueue = async (name, incoming) => { | |
| 5488 | + let active = true; | |
| 5489 | + let ackAll = false; | |
| 5490 | + const explicitAcks = new Set(); | |
| 5491 | + const retries = new Map(); | |
| 5492 | + const retryBatch = { retry: false, delaySeconds: undefined }; | |
| 5493 | + const checkActive = () => { | |
| 5494 | + if (!active) | |
| 5495 | + throw new Error("Queue event methods cannot be called after the handler returns."); | |
| 5496 | + }; | |
| 5497 | + const retryDelay = (options) => { | |
| 5498 | + const value = options?.delaySeconds; | |
| 5499 | + if (value === undefined) return undefined; | |
| 5500 | + if (!Number.isInteger(value) || value < -0x8000_0000 || value > 0x7fff_ffff) | |
| 5501 | + throw new TypeError("delaySeconds must be a 32-bit integer"); | |
| 5502 | + return value; | |
| 5503 | + }; | |
| 5504 | + const decode = (message) => { | |
| 5505 | + switch (message.contentType) { | |
| 5506 | + case "text": return new TextDecoder().decode(message.body); | |
| 5507 | + case "bytes": return message.body; | |
| 5508 | + case "json": return JSON.parse(new TextDecoder().decode(message.body)); | |
| 5509 | + case "v8": return __sc_decode(message.body); | |
| 5510 | + default: throw new TypeError(`Unknown queue content type: ${message.contentType}`); | |
| 5511 | + } | |
| 5512 | + }; | |
| 5513 | + const messages = incoming.messages.map((message) => ({ | |
| 5514 | + id: message.id, | |
| 5515 | + timestamp: new Date(message.timestamp), | |
| 5516 | + body: decode(message), | |
| 5517 | + attempts: message.attempts, | |
| 5518 | + ack() { | |
| 5519 | + checkActive(); | |
| 5520 | + if (ackAll || retryBatch.retry || retries.has(message.id)) return; | |
| 5521 | + explicitAcks.add(message.id); | |
| 5522 | + }, | |
| 5523 | + retry(options) { | |
| 5524 | + checkActive(); | |
| 5525 | + if (ackAll || explicitAcks.has(message.id)) return; | |
| 5526 | + const delaySeconds = retryDelay(options); | |
| 5527 | + if (delaySeconds !== undefined || !retries.has(message.id)) | |
| 5528 | + retries.set(message.id, delaySeconds); | |
| 5529 | + }, | |
| 5530 | + })); | |
| 5531 | + const oldest = incoming.metrics.oldestMessageTimestamp; | |
| 5532 | + const batch = { | |
| 5533 | + queue: incoming.queue, | |
| 5534 | + messages, | |
| 5535 | + metadata: { | |
| 5536 | + metrics: { | |
| 5537 | + backlogCount: incoming.metrics.backlogCount, | |
| 5538 | + backlogBytes: incoming.metrics.backlogBytes, | |
| 5539 | + oldestMessageTimestamp: oldest === undefined ? undefined : new Date(oldest), | |
| 5540 | + }, | |
| 5541 | + }, | |
| 5542 | + ackAll() { | |
| 5543 | + checkActive(); | |
| 5544 | + if (!retryBatch.retry) ackAll = true; | |
| 5545 | + }, | |
| 5546 | + retryAll(options) { | |
| 5547 | + checkActive(); | |
| 5548 | + if (ackAll) return; | |
| 5549 | + retryBatch.retry = true; | |
| 5550 | + const delaySeconds = retryDelay(options); | |
| 5551 | + if (delaySeconds !== undefined) retryBatch.delaySeconds = delaySeconds; | |
| 5552 | + }, | |
| 5553 | + }; | |
| 5554 | + let outcome = "ok"; | |
| 5555 | + let errorText; | |
| 5556 | + try { | |
| 5557 | + await __dispatchEntrypointMethodInCurrentEvent(name, "queue", batch); | |
| 5558 | + } catch (error) { | |
| 5559 | + // A handler exception retries the batch but keeps explicit acks that the | |
| 5560 | + // handler made before it threw. The caller needs both facts together. | |
| 5561 | + outcome = "exception"; | |
| 5562 | + try { | |
| 5563 | + errorText = String(error); | |
| 5564 | + } catch { | |
| 5565 | + errorText = "queue handler rejected"; | |
| 5566 | + } | |
| 5567 | + } finally { | |
| 5568 | + active = false; | |
| 5569 | + } | |
| 5570 | + return { | |
| 5571 | + outcome, | |
| 5572 | + error: errorText, | |
| 5573 | + ackAll, | |
| 5574 | + retryBatch, | |
| 5575 | + explicitAcks: [...explicitAcks], | |
| 5576 | + retryMessages: [...retries].map(([msgId, delaySeconds]) => ({ | |
| 5577 | + msgId, | |
| 5578 | + delaySeconds, | |
| 5579 | + })), | |
| 5580 | + }; | |
| 5581 | +}; | |
| 5582 | +// Workerd's simple-handler RPC rules (worker-rpc.c++): a non-class | |
| 5583 | +// handler method is called as fn(arg, env, ctx), the client must send | |
| 5584 | +// exactly one argument, and the handler must not declare more than | |
| 5585 | +// (arg, env, ctx). The messages are Workerd's, verbatim. | |
| 5586 | +const __callObjectEntrypoint = (handler, method, args, props) => { | |
| 5587 | + const fn = handler[method]; | |
| 5588 | + if (typeof fn !== "function") | |
| 5589 | + throw new TypeError( | |
| 5590 | + 'The RPC receiver does not implement the method "' + method + | |
| 5591 | + '".'); | |
| 5592 | + if (fn.length > 3) | |
| 5593 | + throw new TypeError( | |
| 5594 | + 'Cannot call handler function "' + method + '" over RPC ' + | |
| 5595 | + "because it has the wrong number of arguments. A simple " + | |
| 5596 | + "function handler can only be called over RPC if it has " + | |
| 5597 | + "exactly the arguments (arg, env, ctx), where only the first " + | |
| 5598 | + "argument comes from the client. To support multi-argument " + | |
| 5599 | + "RPC functions, use class-based syntax (extending " + | |
| 5600 | + "WorkerEntrypoint) instead."); | |
| 5601 | + if (args.length !== 1) | |
| 5602 | + throw new TypeError( | |
| 5603 | + 'Attempted to call RPC function "' + method + '" with the ' + | |
| 5604 | + "wrong number of arguments. When calling a top-level handler " + | |
| 5605 | + "function that is not declared as part of a class, you must " + | |
| 5606 | + "always send exactly one argument. In order to support " + | |
| 5607 | + "variable numbers of arguments, the server must use " + | |
| 5608 | + "class-based syntax (extending WorkerEntrypoint) instead."); | |
| 5609 | + return fn.call(handler, args[0], __cell.env, __entrypointContext(props)); | |
| 5610 | +}; | |
| 5611 | +let __nextPendingEventId = 1; | |
| 5612 | +const __pendingEvents = new Map(); | |
| 5613 | +const __pendingEventError = () => new Error( | |
| 5614 | + "The Workers runtime canceled this request because it detected that " + | |
| 5615 | + "your Worker's code had hung and would never generate a response. " + | |
| 5616 | + "Refer to: https://developers.cloudflare.com/workers/observability/errors/"); | |
| 5617 | +// The host calls this only when the request has no native operation that can | |
| 5618 | +// resume JavaScript. Reject the entrypoint call itself, so its caller can | |
| 5619 | +// catch the cancellation and continue the enclosing event. | |
| 5620 | +__celld.__cancelPendingEvents = (ids) => { | |
| 5621 | + for (const id of ids) __pendingEvents.get(id)?.(__pendingEventError()); | |
| 5622 | +}; | |
| 5623 | +// One entrypoint op (a call, or a property GET when argsSc is | |
| 5624 | +// null), inside a fresh request context -- the callee owns stubs | |
| 5625 | +// revived from its params, and stubs it mints belong to it. | |
| 5626 | +// `props` is the caller's per-stub props (Workerd's | |
| 5627 | +// getEntrypoint(name, { props })); undefined leaves the entrypoint's | |
| 5628 | +// default empty props. | |
| 5629 | +const __entrypointOp = (name, path, argsSc, local, makeInst, props) => { | |
| 5630 | + const id = __nextCtxId++; | |
| 5631 | + return __ctxRun(id, () => { | |
| 5632 | + const pendingId = __nextPendingEventId++; | |
| 5633 | + let cancel; | |
| 5634 | + const cancellation = new Promise((_, reject) => { cancel = reject; }); | |
| 5635 | + __pendingEvents.set(pendingId, cancel); | |
| 5636 | + __pending_event_begin(pendingId); | |
| 5637 | + const running = (async () => { | |
| 5638 | + const decoded = argsSc === null ? null : __rpcDesArgs(argsSc); | |
| 5639 | + let drain = null; | |
| 5640 | + try { | |
| 5641 | + const reply = await __rpcRun(async () => { | |
| 5642 | + // The handler's synchronous part runs inside its own event so | |
| 5643 | + // ctx.waitUntil and the imported waitUntil have a target. The | |
| 5644 | + // event pops before the first await -- the event stack is | |
| 5645 | + // strictly LIFO and an event held across an await would be | |
| 5646 | + // popped by whichever event settles next -- and its registered | |
| 5647 | + // work drains before a plain reply (below). | |
| 5648 | + __beginEvent(); | |
| 5649 | + let result; | |
| 5650 | + try { | |
| 5651 | + const handler = __cell.objectEntrypoints[name]; | |
| 5652 | + if (handler !== undefined && makeInst === undefined) { | |
| 5653 | + // Simple-handler entrypoints expose single-method calls | |
| 5654 | + // only; property GETs and deeper paths are refused. | |
| 5655 | + if (argsSc === null || path.length !== 1) | |
| 5656 | + throw __rpcNoSuchMethod(path[0]); | |
| 5657 | + result = __callObjectEntrypoint( | |
| 5658 | + handler, path[0], decoded.args, props); | |
| 5659 | + } else { | |
| 5660 | + // A loopback stub with props retains one instance for that RPC | |
| 5661 | + // session. Each ordinary top-level operation constructs once here, | |
| 5662 | + // so neither its fields nor its constructor context reach the next | |
| 5663 | + // invocation. | |
| 5664 | + const inst = makeInst !== undefined ? makeInst() | |
| 5665 | + : __newEntrypointInstance(name, props); | |
| 5666 | + result = __rpcWalk(inst, path, | |
| 5667 | + decoded === null ? null : decoded.args, true); | |
| 5668 | + } | |
| 5669 | + } finally { | |
| 5670 | + drain = __endEvent(); | |
| 5671 | + } | |
| 5672 | + return await result; | |
| 5673 | + }, local); | |
| 5674 | + // Registered work drains before a plain reply. A | |
| 5675 | + // capability-bearing reply (tag 1) must not wait: a returned | |
| 5676 | + // stream's chunks may be produced by that very work, which | |
| 5677 | + // cannot finish until the caller pulls (returnReadableStream's | |
| 5678 | + // waitUntil writer would deadlock behind its own reply). | |
| 5679 | + if (reply[0] !== 1 && drain !== null) await drain; | |
| 5680 | + // ctx.abort() during the call supersedes its result; the raw | |
| 5681 | + // reason rejects the caller (same isolate -- identity holds). | |
| 5682 | + if (__abortedCtxs.size !== 0) { | |
| 5683 | + const reason = __abortedCtxs.get(id); | |
| 5684 | + if (reason !== undefined) throw reason; | |
| 5685 | + } | |
| 5686 | + // A reply that exports no stubs (tag 0xff plain, tag 0 error) | |
| 5687 | + // leaves nothing rooting this context: tear it down now, so a | |
| 5688 | + // dup() the callee leaked reaches its disposal callback | |
| 5689 | + // promptly (Workerd tears the IoContext down at call end | |
| 5690 | + // unless returned capabilities hold it open). | |
| 5691 | + if (reply[0] !== 1) __ctxEnd(id); | |
| 5692 | + return reply; | |
| 5693 | + } finally { | |
| 5694 | + if (decoded !== null) | |
| 5695 | + for (const handle of decoded.received) __disposeStub(handle); | |
| 5696 | + } | |
| 5697 | + })(); | |
| 5698 | + return Promise.race([running, cancellation]).finally(() => { | |
| 5699 | + __pendingEvents.delete(pendingId); | |
| 5700 | + __pending_event_end(pendingId); | |
| 5701 | + }); | |
| 5702 | + }); | |
| 5703 | +}; | |
| 5704 | +// Cross-isolate service callers pass a complete property path. Older host | |
| 5705 | +// callers can still pass one method name, which becomes a one-part path. | |
| 5706 | +// `propsSc` carries getEntrypoint(name, {props}) as structured-clone bytes, | |
| 5707 | +// the same encoding as `argsSc`. It is empty when the caller sent no props, | |
| 5708 | +// which no encoded value can be, so an empty buffer is an unambiguous absent. | |
| 5709 | +__celld.__dispatchEntrypointRpc = | |
| 5710 | + (name, path, argsSc, local = false, propsSc = null) => __entrypointOp( | |
| 5711 | + name, typeof path === "string" ? [path] : path, argsSc, local, | |
| 5712 | + undefined, | |
| 5713 | + propsSc === null || propsSc.length === 0 | |
| 5714 | + ? undefined : __sc_decode(propsSc)); | |
| 5715 | +// WebSocket: the host holds the socket; these deliver events into the DO. | |
| 5716 | +// `ws` is a lightweight stub whose send/close route back to the host task | |
| 5717 | +// by wsId -- so the isolate can be hibernated between messages. | |
| 5718 | +const __wsStub = __celld.__wsStub = (wsId) => ({ | |
| 5719 | + _hibernatable: true, | |
| 5720 | + send: (data) => { | |
| 5721 | + if (data instanceof ArrayBuffer) | |
| 5722 | + __ws_send_binary(wsId, new Uint8Array(data)); | |
| 5723 | + else if (ArrayBuffer.isView(data)) | |
| 5724 | + __ws_send_binary(wsId, | |
| 5725 | + new Uint8Array(data.buffer, data.byteOffset, data.byteLength)); | |
| 5726 | + else | |
| 5727 | + __ws_send(wsId, String(data)); | |
| 5728 | + }, | |
| 5729 | + close: (code = 1000, reason = "") => __ws_close(wsId, code, reason), | |
| 5730 | +}); | |
| 5731 | +__celld.__wsOpen = async (scope, wsId, protocol) => { | |
| 5732 | + const actorEvent = __beginActorEvent(scope); | |
| 5733 | + try { | |
| 5734 | + const inst = await _readyInstance(scope); | |
| 5735 | + const socket = inst.__celldState._socket(wsId); | |
| 5736 | + if (socket.readyState !== WebSocket.READY_STATE_CONNECTING) return; | |
| 5737 | + socket.protocol = protocol; | |
| 5738 | + socket.readyState = WebSocket.READY_STATE_OPEN; | |
| 5739 | + socket.dispatchEvent(new Event("open")); | |
| 5740 | + } finally { | |
| 5741 | + __endActorEvent(actorEvent); | |
| 5742 | + } | |
| 5743 | +}; | |
| 5744 | +__celld.__wsMessage = async (scope, wsId, msg) => { | |
| 5745 | + const actorEvent = __beginActorEvent(scope); | |
| 5746 | + try { | |
| 5747 | + const inst = await _readyInstance(scope); | |
| 5748 | + const socket = inst.__celldState._socket(wsId); | |
| 5749 | + if (!socket._hibernatable && typeof socket._dispatchMessage === "function") | |
| 5750 | + socket._dispatchMessage(msg); | |
| 5751 | + else if (typeof inst.webSocketMessage === "function") | |
| 5752 | + await inst.webSocketMessage(socket, msg); | |
| 5753 | + } finally { | |
| 5754 | + __endActorEvent(actorEvent); | |
| 5755 | + } | |
| 5756 | +}; | |
| 5757 | +__celld.__wsBinary = async (scope, wsId, data) => { | |
| 5758 | + const actorEvent = __beginActorEvent(scope); | |
| 5759 | + try { | |
| 5760 | + const inst = await _readyInstance(scope); | |
| 5761 | + const socket = inst.__celldState._socket(wsId); | |
| 5762 | + const bytes = data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength); | |
| 5763 | + if (!socket._hibernatable && typeof socket._dispatchMessage === "function") | |
| 5764 | + socket._dispatchMessage(bytes); | |
| 5765 | + else if (typeof inst.webSocketMessage === "function") | |
| 5766 | + await inst.webSocketMessage(socket, bytes); | |
| 5767 | + } finally { | |
| 5768 | + __endActorEvent(actorEvent); | |
| 5769 | + } | |
| 5770 | +}; | |
| 5771 | +__celld.__wsClosed = async (scope, wsId, code, reason, wasClean) => { | |
| 5772 | + const actorEvent = __beginActorEvent(scope); | |
| 5773 | + try { | |
| 5774 | + const inst = await _readyInstance(scope); | |
| 5775 | + const socket = inst.__celldState._socket(wsId); | |
| 5776 | + if (!socket._hibernatable && typeof socket._dispatchClose === "function") | |
| 5777 | + socket._dispatchClose(code, reason, wasClean); | |
| 5778 | + else if (!wasClean && typeof inst.webSocketError === "function") | |
| 5779 | + // A hibernatable socket reports an abnormal closure through | |
| 5780 | + // webSocketError, which celld listed as a handler name and never | |
| 5781 | + // called. | |
| 5782 | + await inst.webSocketError( | |
| 5783 | + socket, | |
| 5784 | + new Error(reason ? `WebSocket closed abnormally: ${reason}` : "WebSocket closed abnormally"), | |
| 5785 | + ); | |
| 5786 | + else if (typeof inst.webSocketClose === "function") | |
| 5787 | + await inst.webSocketClose(socket, code, reason, wasClean); | |
| 5788 | + } finally { | |
| 5789 | + __endActorEvent(actorEvent); | |
| 5790 | + } | |
| 5791 | +}; | |
| 5792 | +// called by celld's scheduler when an alarm is due. Returns a promise. | |
| 5793 | +__celld.__fireAlarm = async (scope, scheduledTime, retryCount) => { | |
| 5794 | + const actorEvent = __beginActorEvent(scope); | |
| 5795 | + try { | |
| 5796 | + const inst = await _readyInstance(scope); | |
| 5797 | + if (typeof inst.alarm !== "function") return; | |
| 5798 | + await inst.alarm({ scheduledTime, retryCount, isRetry: retryCount > 0 }); | |
| 5799 | + } finally { | |
| 5800 | + __endActorEvent(actorEvent); | |
| 5801 | + } | |
| 5802 | +}; | |
| 5803 | +// The reserved cron cell. It is not a user class: celld registers it under | |
| 5804 | +// `.cron` for every deployment that declares `triggers.crons`, and one cell | |
| 5805 | +// per script carries that script's whole schedule. Ownership CAS on that one | |
| 5806 | +// name is what makes a cron trigger fire once per fleet rather than once per | |
| 5807 | +// node -- the same arbiter an alarm already relies on, with nothing added. | |
| 5808 | +// | |
| 5809 | +// The schedule itself is never stored here. `__cell.crons` comes from the | |
| 5810 | +// deployment the cell is running under, so changing a cron expression takes | |
| 5811 | +// effect on the next activation and needs no migration of an armed alarm. | |
| 5812 | +class CelldCronSchedule { | |
| 5813 | + constructor(state) { | |
| 5814 | + this._state = state; | |
| 5815 | + // Failures within one occurrence. Held in memory on purpose: losing the | |
| 5816 | + // count to an eviction only makes the next retry sooner, and every retry | |
| 5817 | + // is capped at the next occurrence anyway, so it need not be durable. | |
| 5818 | + this._retry = 0; | |
| 5819 | + // What a pending retry owes: the occurrence, the expressions of it that | |
| 5820 | + // failed, and the deadline the retry was armed for. A retry deadline is a | |
| 5821 | + // backoff instant and not an occurrence, so nothing about it can be | |
| 5822 | + // recovered from the deadline itself -- without this record the wake | |
| 5823 | + // matches no expression, runs nothing, and drops the failed tick in | |
| 5824 | + // silence. Held in memory beside `_retry` and for the same reason: an | |
| 5825 | + // eviction costs the retry, never the next occurrence. | |
| 5826 | + this._owed = null; | |
| 5827 | + } | |
| 5828 | + // celld calls this once per node after a deployment loads, because a cron | |
| 5829 | + // cell has no client to wake it. Arming is idempotent -- the same schedule | |
| 5830 | + // and the same clock give the same answer -- so it does not matter which | |
| 5831 | + // node wins the cell. | |
| 5832 | + async fetch() { | |
| 5833 | + // A pending retry is a deadline this cell already owes, and re-arming | |
| 5834 | + // would move it to the next occurrence and lose the tick it owes with it. | |
| 5835 | + if (this._owed !== null) return new Response(null, { status: 204 }); | |
| 5836 | + const armed = await this._state.storage.getAlarm(); | |
| 5837 | + // An alarm already due is a tick that is late, not one that is wrong. | |
| 5838 | + // Leaving it alone is what makes a fleet that was down fire the missed | |
| 5839 | + // occurrence once, instead of skipping it by re-arming into the future. | |
| 5840 | + if (armed === null || armed > Date.now()) await this._arm(null, [], false); | |
| 5841 | + return new Response(null, { status: 204 }); | |
| 5842 | + } | |
| 5843 | + async alarm(info) { | |
| 5844 | + const crons = __cell.crons || []; | |
| 5845 | + // A retry wake carries the backoff instant as its deadline, so what to run | |
| 5846 | + // and what time to report both come from the record the failure left. Only | |
| 5847 | + // a deadline that is not a retry is an occurrence to match against. | |
| 5848 | + const owed = this._owed !== null && this._owed.armedFor === info.scheduledTime | |
| 5849 | + ? this._owed | |
| 5850 | + : null; | |
| 5851 | + const occurrence = owed === null ? info.scheduledTime : owed.at; | |
| 5852 | + // One deadline can belong to several expressions, and each is its own | |
| 5853 | + // invocation with its own controller.cron, as on Cloudflare. A retry | |
| 5854 | + // repeats only the expressions that failed, because the ones that | |
| 5855 | + // succeeded already ran for this occurrence. | |
| 5856 | + const due = owed === null | |
| 5857 | + ? __cron_plan(crons, info.scheduledTime, Date.now(), 0, false).matching | |
| 5858 | + : owed.indices; | |
| 5859 | + const failed = []; | |
| 5860 | + for (const index of due) { | |
| 5861 | + let noRetry = false; | |
| 5862 | + const controller = { | |
| 5863 | + // The occurrence, never the instant this attempt started, so a late | |
| 5864 | + // run and a retry both report the minute they were scheduled for. | |
| 5865 | + scheduledTime: occurrence, | |
| 5866 | + cron: crons[index], | |
| 5867 | + noRetry() { noRetry = true; }, | |
| 5868 | + }; | |
| 5869 | + const ctx = __beginEvent(); | |
| 5870 | + try { | |
| 5871 | + if (typeof __cell.selfScheduled !== "function") | |
| 5872 | + throw new Error( | |
| 5873 | + "a cron trigger needs the Worker to export a `scheduled` handler"); | |
| 5874 | + await __cell.selfScheduled(controller, __cell.env, ctx); | |
| 5875 | + } catch (error) { | |
| 5876 | + // Swallowed on purpose: this handler owns the re-arm below, so | |
| 5877 | + // throwing would hand the deadline to the generic alarm retry and | |
| 5878 | + // lose the next occurrence with it. | |
| 5879 | + console.error( | |
| 5880 | + `scheduled handler for cron ${JSON.stringify(crons[index])} failed:`, | |
| 5881 | + error); | |
| 5882 | + if (!noRetry) failed.push(index); | |
| 5883 | + } finally { | |
| 5884 | + const drain = __endEvent(); | |
| 5885 | + // The alarm turn is the only host owner for this scheduled event. | |
| 5886 | + // Dropping its drain lets the actor turn end with waitUntil work still | |
| 5887 | + // pending, so an I/O promise can remain unresolved forever. | |
| 5888 | + if (drain !== null) await drain; | |
| 5889 | + } | |
| 5890 | + } | |
| 5891 | + await this._arm(occurrence, failed, owed !== null); | |
| 5892 | + } | |
| 5893 | + // `occurrence` is the tick just handled, or null when the cell is only | |
| 5894 | + // arming, `failed` holds the expressions of it still owed, and `retried` | |
| 5895 | + // says the deadline just handled was a backoff rather than an occurrence. | |
| 5896 | + async _arm(occurrence, failed, retried) { | |
| 5897 | + const crons = __cell.crons || []; | |
| 5898 | + // The count is failures within one occurrence, so a fresh occurrence | |
| 5899 | + // starts at one however the last one ended. Carrying it across would | |
| 5900 | + // spend `alarm_retry`'s ceiling once and leave every later occurrence | |
| 5901 | + // with no retry at all, which is a budget for the schedule and not for | |
| 5902 | + // the tick. | |
| 5903 | + this._retry = failed.length ? (retried ? this._retry + 1 : 1) : 0; | |
| 5904 | + // A negative first argument means "arming only, nothing fired". | |
| 5905 | + const plan = __cron_plan(crons, -1, Date.now(), this._retry, failed.length > 0); | |
| 5906 | + // The next occurrence beats the backoff whenever it is sooner, and it then | |
| 5907 | + // cancels the retry rather than queueing behind it, so the record the | |
| 5908 | + // retry needed goes when the retry does. | |
| 5909 | + this._owed = plan.armIsRetry | |
| 5910 | + ? { at: occurrence, indices: failed, armedFor: plan.armAt } | |
| 5911 | + : null; | |
| 5912 | + // No expression matches again and nothing is owed: the deployment dropped | |
| 5913 | + // its crons, so the cell retires rather than waking forever. | |
| 5914 | + if (plan.armAt === null) await this._state.storage.deleteAlarm(); | |
| 5915 | + else await this._state.storage.setAlarm(plan.armAt); | |
| 5916 | + } | |
| 5917 | +} | |
| 5918 | +const __cell = __celld.__cell = { | |
| 5919 | + entrypoints: {}, | |
| 5920 | + objectEntrypoints: {}, | |
| 5921 | + doExports: {}, | |
| 5922 | + classes: { ".cron": CelldCronSchedule }, | |
| 5923 | + crons: [], | |
| 5924 | + workflows: {}, | |
| 5925 | + containers: {}, | |
| 5926 | + instances: {}, | |
| 5927 | + facetConfigs: {}, | |
| 5928 | + env: {}, | |
| 5929 | + idNames: {}, | |
| 5930 | + namespaceKeys: {}, | |
| 5931 | + node: "", | |
| 5932 | + deleteAllDeletesAlarm: false, | |
| 5933 | + compat: { jsRpc: false, fetcherGetPutDelete: false, queueJsonMessages: false }, | |
| 5934 | + makeNamespace, | |
| 5935 | + release: __cellRelease, | |
| 5936 | +}; | |
| 5937 | +// A class the runtime supplies. RPC on a stub needs `extends DurableObject` | |
| 5938 | +// or the js_rpc flag; the class is the runtime's own, so grant it here rather | |
| 5939 | +// than make every user set a flag. It is not the application's export, so it | |
| 5940 | +// stays out of ctx.exports. | |
| 5941 | +const __runtimeClasses = new Set(); | |
| 5942 | +const __runtimeClass = (name, cls) => { | |
| 5943 | + __cell.classes[name] = cls; | |
| 5944 | + __cell.doExports[name] = true; | |
| 5945 | + __runtimeClasses.add(name); | |
| 5946 | +}; | |
| 5947 | +// ---- KV ------------------------------------------------------------------ | |
| 5948 | +// The namespace cell and the binding's client are `services/kv.js`, which the | |
| 5949 | +// workerd engine runs too; this is the host they run against here. | |
| 5950 | +const { | |
| 5951 | + KvNamespaceCell: __KvNamespaceCell, | |
| 5952 | + KvNamespace: __KvNamespace, | |
| 5953 | + cellSweepBatch: __cellSweepBatch, | |
| 5954 | +} = kvService({ | |
| 5955 | + // RPC on a runtime class is granted by `__runtimeClass` below. | |
| 5956 | + DurableObject: class { | |
| 5957 | + constructor(ctx) { | |
| 5958 | + this.ctx = ctx; | |
| 5959 | + } | |
| 5960 | + }, | |
| 5961 | + limits: () => __cell.kvLimits, | |
| 5962 | + // One op for the whole large-value path, following `__d1_run`. | |
| 5963 | + blob: async (_cell, request, value) => { | |
| 5964 | + const reply = await __kv_blob(JSON.stringify(request), value); | |
| 5965 | + return reply instanceof Uint8Array | |
| 5966 | + ? { found: true, value: reply } | |
| 5967 | + : JSON.parse(reply); | |
| 5968 | + }, | |
| 5969 | + // The raw base64 ops accept typed views for this internal wire form; the | |
| 5970 | + // public atob() and btoa() wrappers keep their standard string-only | |
| 5971 | + // behaviour. | |
| 5972 | + btoa: (bytes) => $$btoa(bytes), | |
| 5973 | + atob: (text) => $$atob(text, true), | |
| 5974 | +}); | |
| 5975 | + | |
| 5976 | +__runtimeClass("__KvNamespace", __KvNamespaceCell); | |
| 5977 | + | |
| 5978 | +const __makeKvNamespace = __celld.__makeKvNamespace = (id, cellName) => | |
| 5979 | + new __KvNamespace(() => __cell.makeNamespace("__KvNamespace"), cellName); | |
| 5980 | + | |
| 5981 | +// ---- Queues -------------------------------------------------------------- | |
| 5982 | +// A Queue is one runtime-supplied Durable Object. The producer binding writes | |
| 5983 | +// bytes and a content tag through RPC, and the cell owns the durable order, | |
| 5984 | +// deadlines, leases, and alarms. `celld_logic::queue` owns every transition | |
| 5985 | +// that can invalidate a lease or choose a deadline; this code supplies SQL and | |
| 5986 | +// the Cloudflare-compatible presentation. | |
| 5987 | + | |
| 5988 | +const __QUEUE_MESSAGES = "__queue_messages"; | |
| 5989 | +const __QUEUE_META = "__queue_meta"; | |
| 5990 | +const __QUEUE_STATS = "__queue_stats"; | |
| 5991 | +const __QUEUE_TRANSFER_RECEIPTS = "__queue_transfer_receipts"; | |
| 5992 | +const __queueEncoder = new TextEncoder(); | |
| 5993 | + | |
| 5994 | +// Independent send() calls share the same economics as sendBatch() without | |
| 5995 | +// changing the public promise boundary. The first call opens a four-millisecond | |
| 5996 | +// owner-local group by default; later cell events append their already-copied | |
| 5997 | +// entries, and park on their own promise. One event commits the bounded group, | |
| 5998 | +// and every response still trails that commit through the ordinary output | |
| 5999 | +// gate. The three caps bound heap retention and keep the persisted transaction | |
| 6000 | +// inside the public sendBatch limits. | |
| 6001 | +const __QUEUE_PRODUCER_GROUP_CALLS = 64; | |
| 6002 | +const __QUEUE_PRODUCER_GROUP_MESSAGES = 100; | |
| 6003 | +const __QUEUE_PRODUCER_GROUP_BYTES = 256_000; | |
| 6004 | + | |
| 6005 | +const __queueError = (message) => new Error("QUEUE_ERROR: " + String(message)); | |
| 6006 | +// A Queue message id is a UUIDv7 (RFC 9562): 48 bits of enqueue time, a | |
| 6007 | +// 12-bit sequence inside that millisecond, and 62 random bits. It keeps the | |
| 6008 | +// UUID shape a consumer can parse, and it sorts in enqueue order, so the | |
| 6009 | +// UNIQUE index on `id` appends. A random v4 id made every grouped send | |
| 6010 | +// transaction dirty one index leaf per message (about 1.6 WAL frames per | |
| 6011 | +// 64-byte message) and turned every passive checkpoint into a random write | |
| 6012 | +// across the whole backlog, which is what made a deep Queue's checkpoint | |
| 6013 | +// cost grow with its backlog. The sequence never moves backwards inside one | |
| 6014 | +// process, so a clock step only widens the gap between consecutive ids. | |
| 6015 | +let __queueIdMs = 0; | |
| 6016 | +let __queueIdSeq = 0; | |
| 6017 | +function __queueMessageId(now) { | |
| 6018 | + if (now > __queueIdMs) { | |
| 6019 | + __queueIdMs = now; | |
| 6020 | + __queueIdSeq = 0; | |
| 6021 | + } else { | |
| 6022 | + __queueIdSeq += 1; | |
| 6023 | + if (__queueIdSeq > 0xfff) { | |
| 6024 | + __queueIdMs += 1; | |
| 6025 | + __queueIdSeq = 0; | |
| 6026 | + } | |
| 6027 | + } | |
| 6028 | + const bytes = new Uint8Array(16); | |
| 6029 | + crypto.getRandomValues(bytes); | |
| 6030 | + const ms = __queueIdMs; | |
| 6031 | + bytes[0] = Math.floor(ms / 0x10000000000) & 0xff; | |
| 6032 | + bytes[1] = Math.floor(ms / 0x100000000) & 0xff; | |
| 6033 | + bytes[2] = (ms >>> 24) & 0xff; | |
| 6034 | + bytes[3] = (ms >>> 16) & 0xff; | |
| 6035 | + bytes[4] = (ms >>> 8) & 0xff; | |
| 6036 | + bytes[5] = ms & 0xff; | |
| 6037 | + bytes[6] = 0x70 | (__queueIdSeq >> 8); | |
| 6038 | + bytes[7] = __queueIdSeq & 0xff; | |
| 6039 | + bytes[8] = (bytes[8] & 0x3f) | 0x80; | |
| 6040 | + let hex = ""; | |
| 6041 | + for (let i = 0; i < 16; i++) hex += bytes[i].toString(16).padStart(2, "0"); | |
| 6042 | + return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${ | |
| 6043 | + hex.slice(16, 20) | |
| 6044 | + }-${hex.slice(20)}`; | |
| 6045 | +} | |
| 6046 | +const __queueLimits = () => __cell.queueLimits; | |
| 6047 | +const __queuePolicy = (request) => | |
| 6048 | + JSON.parse(__queue_policy(JSON.stringify(request))); | |
| 6049 | + | |
| 6050 | +const __queueDelay = (value, fallback = 0) => { | |
| 6051 | + if (value === undefined || value === null) return fallback; | |
| 6052 | + const seconds = Number(value); | |
| 6053 | + if (!Number.isInteger(seconds) || seconds < 0 || | |
| 6054 | + seconds > __queueLimits().maxDelaySeconds) { | |
| 6055 | + throw __queueError( | |
| 6056 | + `delaySeconds must be an integer from 0 to ${__queueLimits().maxDelaySeconds}`, | |
| 6057 | + ); | |
| 6058 | + } | |
| 6059 | + return seconds; | |
| 6060 | +}; | |
| 6061 | + | |
| 6062 | +const __queueBytes = (value) => { | |
| 6063 | + if (value instanceof ArrayBuffer) { | |
| 6064 | + return new Uint8Array(value.slice(0)); | |
| 6065 | + } | |
| 6066 | + if (ArrayBuffer.isView(value)) { | |
| 6067 | + return new Uint8Array( | |
| 6068 | + value.buffer.slice(value.byteOffset, value.byteOffset + value.byteLength), | |
| 6069 | + ); | |
| 6070 | + } | |
| 6071 | + throw __queueError("a bytes message must be an ArrayBuffer or a typed array"); | |
| 6072 | +}; | |
| 6073 | + | |
| 6074 | +// Encode before entering the cell. The copy makes `sendBatch()` immune to a | |
| 6075 | +// caller resizing or reusing a backing buffer while the durable write awaits. | |
| 6076 | +const __queueEncode = (body, requestedType) => { | |
| 6077 | + const contentType = requestedType ?? | |
| 6078 | + (__cell.compat.queueJsonMessages ? "json" : "v8"); | |
| 6079 | + let bytes; | |
| 6080 | + switch (contentType) { | |
| 6081 | + case "text": | |
| 6082 | + bytes = __queueEncoder.encode(String(body)); | |
| 6083 | + break; | |
| 6084 | + case "bytes": | |
| 6085 | + bytes = __queueBytes(body); | |
| 6086 | + break; | |
| 6087 | + case "json": { | |
| 6088 | + let json; | |
| 6089 | + try { | |
| 6090 | + json = JSON.stringify(body); | |
| 6091 | + } catch (error) { | |
| 6092 | + throw __queueError("the JSON message body cannot be serialized", error); | |
| 6093 | + } | |
| 6094 | + if (json === undefined) { | |
| 6095 | + throw __queueError("the JSON message body cannot be undefined"); | |
| 6096 | + } | |
| 6097 | + bytes = __queueEncoder.encode(json); | |
| 6098 | + break; | |
| 6099 | + } | |
| 6100 | + case "v8": | |
| 6101 | + try { | |
| 6102 | + bytes = __sc_encode(body); | |
| 6103 | + } catch (error) { | |
| 6104 | + throw __queueError("the message body cannot be cloned", error); | |
| 6105 | + } | |
| 6106 | + break; | |
| 6107 | + default: | |
| 6108 | + throw __queueError( | |
| 6109 | + `contentType must be "text", "bytes", "json", or "v8", got ${JSON.stringify(contentType)}`, | |
| 6110 | + ); | |
| 6111 | + } | |
| 6112 | + if (bytes.byteLength > __queueLimits().maxMessageBytes) { | |
| 6113 | + throw __queueError( | |
| 6114 | + `a message is at most ${__queueLimits().maxMessageBytes} bytes, got ${bytes.byteLength}`, | |
| 6115 | + ); | |
| 6116 | + } | |
| 6117 | + return { body: bytes, contentType, size: bytes.byteLength }; | |
| 6118 | +}; | |
| 6119 | + | |
| 6120 | +// A lease-scoped read must seek, not walk the backlog. The plan is the only | |
| 6121 | +// evidence that says which, and it is cheap to ask for, so a gated test seam | |
| 6122 | +// reads it from the shipped query rather than from a copy that can drift. | |
| 6123 | +const __queueReportLeaseLookupPlan = (sql, query, leaseId) => { | |
| 6124 | + if (typeof __test_queue_lease_lookup_plan !== "function") return; | |
| 6125 | + const plan = sql.exec(`EXPLAIN QUERY PLAN ${query}`, leaseId) | |
| 6126 | + .toArray() | |
| 6127 | + .map((row) => row.detail) | |
| 6128 | + .join("; "); | |
| 6129 | + __test_queue_lease_lookup_plan(plan); | |
| 6130 | +}; | |
| 6131 | + | |
| 6132 | +const __queueMetricsView = (metrics) => ({ | |
| 6133 | + backlogCount: metrics.backlogCount, | |
| 6134 | + backlogBytes: metrics.backlogBytes, | |
| 6135 | + oldestMessageTimestamp: metrics.oldestMessageTimestamp === null || | |
| 6136 | + metrics.oldestMessageTimestamp === undefined | |
| 6137 | + ? undefined | |
| 6138 | + : new Date(metrics.oldestMessageTimestamp), | |
| 6139 | +}); | |
| 6140 | + | |
| 6141 | +class __QueueCell { | |
| 6142 | + constructor(ctx) { | |
| 6143 | + this.ctx = ctx; | |
| 6144 | + this.queue = ctx.id.name; | |
| 6145 | + this._ready = false; | |
| 6146 | + this._producerGroup = null; | |
| 6147 | + } | |
| 6148 | + | |
| 6149 | + _open() { | |
| 6150 | + if (this._ready) return this.ctx.storage.sql; | |
| 6151 | + const sql = this.ctx.storage.sql; | |
| 6152 | + sql.exec( | |
| 6153 | + `CREATE TABLE IF NOT EXISTS ${__QUEUE_MESSAGES} ( | |
| 6154 | + seq INTEGER PRIMARY KEY AUTOINCREMENT, | |
| 6155 | + id TEXT NOT NULL UNIQUE, | |
| 6156 | + body BLOB NOT NULL, | |
| 6157 | + content_type TEXT NOT NULL, | |
| 6158 | + size INTEGER NOT NULL, | |
| 6159 | + enqueued_at INTEGER NOT NULL, | |
| 6160 | + visible_at INTEGER NOT NULL, | |
| 6161 | + attempts INTEGER NOT NULL DEFAULT 0, | |
| 6162 | + lease_id TEXT, | |
| 6163 | + lease_generation INTEGER NOT NULL DEFAULT 0, | |
| 6164 | + leased_until INTEGER, | |
| 6165 | + purge_on_settle INTEGER NOT NULL DEFAULT 0, | |
| 6166 | + dlq_target TEXT, | |
| 6167 | + dlq_transfer_id TEXT, | |
| 6168 | + transfer_kind TEXT, | |
| 6169 | + dead_letter_source TEXT, | |
| 6170 | + CHECK ((dlq_target IS NULL AND transfer_kind IS NULL) | |
| 6171 | + OR (dlq_target IS NOT NULL | |
| 6172 | + AND transfer_kind IN ('dead-letter', 'redrive'))) | |
| 6173 | + )`, | |
| 6174 | + ); | |
| 6175 | + sql.exec( | |
| 6176 | + `CREATE INDEX IF NOT EXISTS ${__QUEUE_MESSAGES}_visible | |
| 6177 | + ON ${__QUEUE_MESSAGES} (visible_at, seq)`, | |
| 6178 | + ); | |
| 6179 | + // Rearming is on every producer acknowledgement and settlement. Each | |
| 6180 | + // scheduling lookup must therefore stop at one deadline or one batch; | |
| 6181 | + // an aggregate over the backlog makes a large Queue quadratic to fill. | |
| 6182 | + sql.exec( | |
| 6183 | + `CREATE INDEX IF NOT EXISTS ${__QUEUE_MESSAGES}_ready | |
| 6184 | + ON ${__QUEUE_MESSAGES} (visible_at, seq) | |
| 6185 | + WHERE purge_on_settle = 0 AND dlq_target IS NULL | |
| 6186 | + AND lease_id IS NULL`, | |
| 6187 | + ); | |
| 6188 | + sql.exec( | |
| 6189 | + `CREATE INDEX IF NOT EXISTS ${__QUEUE_MESSAGES}_enqueued | |
| 6190 | + ON ${__QUEUE_MESSAGES} (enqueued_at, seq)`, | |
| 6191 | + ); | |
| 6192 | + sql.exec( | |
| 6193 | + `CREATE INDEX IF NOT EXISTS ${__QUEUE_MESSAGES}_retained | |
| 6194 | + ON ${__QUEUE_MESSAGES} (enqueued_at, seq) | |
| 6195 | + WHERE purge_on_settle = 0 AND dlq_target IS NULL`, | |
| 6196 | + ); | |
| 6197 | + sql.exec( | |
| 6198 | + `CREATE INDEX IF NOT EXISTS ${__QUEUE_MESSAGES}_lease | |
| 6199 | + ON ${__QUEUE_MESSAGES} (leased_until, seq) | |
| 6200 | + WHERE lease_id IS NOT NULL`, | |
| 6201 | + ); | |
| 6202 | + sql.exec( | |
| 6203 | + `CREATE INDEX IF NOT EXISTS ${__QUEUE_MESSAGES}_moving | |
| 6204 | + ON ${__QUEUE_MESSAGES} (seq) | |
| 6205 | + WHERE dlq_target IS NOT NULL`, | |
| 6206 | + ); | |
| 6207 | + // Dispatch and settlement both select a whole batch by its lease. Without | |
| 6208 | + // this index SQLite answers them by walking every row: the dispatch | |
| 6209 | + // readback scans `_visible` and the settlement scan walks the table, so | |
| 6210 | + // each delivered batch costs two passes over the backlog. The `_lease` | |
| 6211 | + // index cannot serve them because it is keyed on `leased_until`. | |
| 6212 | + // The partial predicate keeps only leased rows, which `max_concurrency` | |
| 6213 | + // times `max_batch_size` bounds, and an inserted message has a null | |
| 6214 | + // `lease_id`, so `send` pays nothing for it. | |
| 6215 | + sql.exec( | |
| 6216 | + `CREATE INDEX IF NOT EXISTS ${__QUEUE_MESSAGES}_lease_batch | |
| 6217 | + ON ${__QUEUE_MESSAGES} (lease_id, visible_at, seq) | |
| 6218 | + WHERE lease_id IS NOT NULL`, | |
| 6219 | + ); | |
| 6220 | + // The live-row index catches an impossible duplicate while a received | |
| 6221 | + // message remains queued. The receipt below is the durable deduplication | |
| 6222 | + // record after a consumer or purge removes that message. | |
| 6223 | + sql.exec( | |
| 6224 | + `CREATE UNIQUE INDEX IF NOT EXISTS ${__QUEUE_MESSAGES}_dlq_transfer | |
| 6225 | + ON ${__QUEUE_MESSAGES} (dlq_transfer_id) | |
| 6226 | + WHERE dlq_transfer_id IS NOT NULL AND dlq_target IS NULL`, | |
| 6227 | + ); | |
| 6228 | + sql.exec( | |
| 6229 | + `CREATE TABLE IF NOT EXISTS ${__QUEUE_META} ( | |
| 6230 | + name TEXT PRIMARY KEY, | |
| 6231 | + value TEXT NOT NULL | |
| 6232 | + ) WITHOUT ROWID`, | |
| 6233 | + ); | |
| 6234 | + // The producer result and operator metrics are on hot paths. SQLite | |
| 6235 | + // triggers keep the three values in the same transaction as every row | |
| 6236 | + // transition, so a caller cannot observe a new message with old totals. | |
| 6237 | + sql.exec( | |
| 6238 | + `CREATE TABLE IF NOT EXISTS ${__QUEUE_STATS} ( | |
| 6239 | + id INTEGER PRIMARY KEY CHECK (id = 1), | |
| 6240 | + stored_count INTEGER NOT NULL, | |
| 6241 | + backlog_count INTEGER NOT NULL, | |
| 6242 | + backlog_bytes INTEGER NOT NULL, | |
| 6243 | + oldest_message_timestamp INTEGER | |
| 6244 | + )`, | |
| 6245 | + ); | |
| 6246 | + sql.exec( | |
| 6247 | + `INSERT INTO ${__QUEUE_STATS} | |
| 6248 | + (id, stored_count, backlog_count, backlog_bytes, | |
| 6249 | + oldest_message_timestamp) | |
| 6250 | + SELECT 1, | |
| 6251 | + COUNT(*), | |
| 6252 | + COALESCE(SUM(purge_on_settle = 0), 0), | |
| 6253 | + COALESCE(SUM(CASE WHEN purge_on_settle = 0 THEN size ELSE 0 END), 0), | |
| 6254 | + MIN(CASE WHEN purge_on_settle = 0 THEN enqueued_at END) | |
| 6255 | + FROM ${__QUEUE_MESSAGES} | |
| 6256 | + WHERE true | |
| 6257 | + ON CONFLICT(id) DO NOTHING`, | |
| 6258 | + ); | |
| 6259 | + sql.exec( | |
| 6260 | + `CREATE TRIGGER IF NOT EXISTS ${__QUEUE_MESSAGES}_stored_insert | |
| 6261 | + AFTER INSERT ON ${__QUEUE_MESSAGES} | |
| 6262 | + BEGIN | |
| 6263 | + UPDATE ${__QUEUE_STATS} | |
| 6264 | + SET stored_count = stored_count + 1 | |
| 6265 | + WHERE id = 1; | |
| 6266 | + END`, | |
| 6267 | + ); | |
| 6268 | + sql.exec( | |
| 6269 | + `CREATE TRIGGER IF NOT EXISTS ${__QUEUE_MESSAGES}_stored_delete | |
| 6270 | + AFTER DELETE ON ${__QUEUE_MESSAGES} | |
| 6271 | + BEGIN | |
| 6272 | + UPDATE ${__QUEUE_STATS} | |
| 6273 | + SET stored_count = stored_count - 1 | |
| 6274 | + WHERE id = 1; | |
| 6275 | + END`, | |
| 6276 | + ); | |
| 6277 | + sql.exec( | |
| 6278 | + `CREATE TRIGGER IF NOT EXISTS ${__QUEUE_MESSAGES}_stats_insert | |
| 6279 | + AFTER INSERT ON ${__QUEUE_MESSAGES} | |
| 6280 | + WHEN new.purge_on_settle = 0 | |
| 6281 | + BEGIN | |
| 6282 | + UPDATE ${__QUEUE_STATS} | |
| 6283 | + SET backlog_count = backlog_count + 1, | |
| 6284 | + backlog_bytes = backlog_bytes + new.size, | |
| 6285 | + oldest_message_timestamp = CASE | |
| 6286 | + WHEN oldest_message_timestamp IS NULL | |
| 6287 | + OR new.enqueued_at < oldest_message_timestamp | |
| 6288 | + THEN new.enqueued_at ELSE oldest_message_timestamp END | |
| 6289 | + WHERE id = 1; | |
| 6290 | + END`, | |
| 6291 | + ); | |
| 6292 | + sql.exec( | |
| 6293 | + `CREATE TRIGGER IF NOT EXISTS ${__QUEUE_MESSAGES}_stats_delete | |
| 6294 | + AFTER DELETE ON ${__QUEUE_MESSAGES} | |
| 6295 | + WHEN old.purge_on_settle = 0 | |
| 6296 | + BEGIN | |
| 6297 | + UPDATE ${__QUEUE_STATS} | |
| 6298 | + SET backlog_count = backlog_count - 1, | |
| 6299 | + backlog_bytes = backlog_bytes - old.size, | |
| 6300 | + oldest_message_timestamp = CASE | |
| 6301 | + WHEN backlog_count <= 1 THEN NULL | |
| 6302 | + WHEN oldest_message_timestamp = old.enqueued_at | |
| 6303 | + THEN (SELECT MIN(enqueued_at) FROM ${__QUEUE_MESSAGES} | |
| 6304 | + WHERE purge_on_settle = 0) | |
| 6305 | + ELSE oldest_message_timestamp END | |
| 6306 | + WHERE id = 1; | |
| 6307 | + END`, | |
| 6308 | + ); | |
| 6309 | + sql.exec( | |
| 6310 | + `CREATE TRIGGER IF NOT EXISTS ${__QUEUE_MESSAGES}_stats_exclude | |
| 6311 | + AFTER UPDATE OF purge_on_settle ON ${__QUEUE_MESSAGES} | |
| 6312 | + WHEN old.purge_on_settle = 0 AND new.purge_on_settle != 0 | |
| 6313 | + BEGIN | |
| 6314 | + UPDATE ${__QUEUE_STATS} | |
| 6315 | + SET backlog_count = backlog_count - 1, | |
| 6316 | + backlog_bytes = backlog_bytes - old.size, | |
| 6317 | + oldest_message_timestamp = CASE | |
| 6318 | + WHEN backlog_count <= 1 THEN NULL | |
| 6319 | + WHEN oldest_message_timestamp = old.enqueued_at | |
| 6320 | + THEN (SELECT MIN(enqueued_at) FROM ${__QUEUE_MESSAGES} | |
| 6321 | + WHERE purge_on_settle = 0) | |
| 6322 | + ELSE oldest_message_timestamp END | |
| 6323 | + WHERE id = 1; | |
| 6324 | + END`, | |
| 6325 | + ); | |
| 6326 | + sql.exec( | |
| 6327 | + `CREATE TRIGGER IF NOT EXISTS ${__QUEUE_MESSAGES}_stats_include | |
| 6328 | + AFTER UPDATE OF purge_on_settle ON ${__QUEUE_MESSAGES} | |
| 6329 | + WHEN old.purge_on_settle != 0 AND new.purge_on_settle = 0 | |
| 6330 | + BEGIN | |
| 6331 | + UPDATE ${__QUEUE_STATS} | |
| 6332 | + SET backlog_count = backlog_count + 1, | |
| 6333 | + backlog_bytes = backlog_bytes + new.size, | |
| 6334 | + oldest_message_timestamp = CASE | |
| 6335 | + WHEN oldest_message_timestamp IS NULL | |
| 6336 | + OR new.enqueued_at < oldest_message_timestamp | |
| 6337 | + THEN new.enqueued_at ELSE oldest_message_timestamp END | |
| 6338 | + WHERE id = 1; | |
| 6339 | + END`, | |
| 6340 | + ); | |
| 6341 | + sql.exec( | |
| 6342 | + `CREATE TABLE IF NOT EXISTS ${__QUEUE_TRANSFER_RECEIPTS} ( | |
| 6343 | + transfer_id TEXT PRIMARY KEY, | |
| 6344 | + message_id TEXT NOT NULL, | |
| 6345 | + dead_letter_source TEXT, | |
| 6346 | + expires_at INTEGER NOT NULL | |
| 6347 | + ) WITHOUT ROWID`, | |
| 6348 | + ); | |
| 6349 | + sql.exec( | |
| 6350 | + `CREATE INDEX IF NOT EXISTS ${__QUEUE_TRANSFER_RECEIPTS}_expires | |
| 6351 | + ON ${__QUEUE_TRANSFER_RECEIPTS} (expires_at, transfer_id)`, | |
| 6352 | + ); | |
| 6353 | + this._ready = true; | |
| 6354 | + return sql; | |
| 6355 | + } | |
| 6356 | + | |
| 6357 | + _meta(name) { | |
| 6358 | + return this._open().exec( | |
| 6359 | + `SELECT value FROM ${__QUEUE_META} WHERE name = ?`, name, | |
| 6360 | + ).toArray()[0]?.value; | |
| 6361 | + } | |
| 6362 | + | |
| 6363 | + _setMeta(name, value) { | |
| 6364 | + if (value === null || value === undefined) { | |
| 6365 | + this._open().exec(`DELETE FROM ${__QUEUE_META} WHERE name = ?`, name); | |
| 6366 | + return; | |
| 6367 | + } | |
| 6368 | + this._open().exec( | |
| 6369 | + `INSERT INTO ${__QUEUE_META} (name, value) VALUES (?, ?) | |
| 6370 | + ON CONFLICT(name) DO UPDATE SET value = excluded.value`, | |
| 6371 | + name, | |
| 6372 | + String(value), | |
| 6373 | + ); | |
| 6374 | + } | |
| 6375 | + | |
| 6376 | + _paused() { | |
| 6377 | + return this._meta("paused") === "1"; | |
| 6378 | + } | |
| 6379 | + | |
| 6380 | + _metrics(now = Date.now(), waitingOnly = false) { | |
| 6381 | + const expiresBefore = now - __queueLimits().retentionMs; | |
| 6382 | + const sql = this._open(); | |
| 6383 | + const stats = sql.exec( | |
| 6384 | + `SELECT backlog_count, backlog_bytes, oldest_message_timestamp | |
| 6385 | + FROM ${__QUEUE_STATS} WHERE id = 1`, | |
| 6386 | + ).toArray()[0]; | |
| 6387 | + // Retention is a clock transition, not a row transition. Until the | |
| 6388 | + // bounded sweep catches up, use the exact query only at that boundary; | |
| 6389 | + // the normal hot path remains one materialized row at every depth. | |
| 6390 | + if (stats.oldest_message_timestamp !== null && | |
| 6391 | + stats.oldest_message_timestamp <= expiresBefore) { | |
| 6392 | + const row = sql.exec( | |
| 6393 | + `SELECT COUNT(*) AS backlog_count, | |
| 6394 | + COALESCE(SUM(size), 0) AS backlog_bytes, | |
| 6395 | + MIN(enqueued_at) AS oldest_message_timestamp | |
| 6396 | + FROM ${__QUEUE_MESSAGES} | |
| 6397 | + WHERE purge_on_settle = 0 AND enqueued_at > ? | |
| 6398 | + AND (? = 0 OR (lease_id IS NULL AND dlq_target IS NULL | |
| 6399 | + AND visible_at <= ?))`, | |
| 6400 | + expiresBefore, | |
| 6401 | + waitingOnly ? 1 : 0, | |
| 6402 | + now, | |
| 6403 | + ).toArray()[0]; | |
| 6404 | + return { | |
| 6405 | + backlogCount: row.backlog_count, | |
| 6406 | + backlogBytes: row.backlog_bytes, | |
| 6407 | + oldestMessageTimestamp: row.oldest_message_timestamp ?? null, | |
| 6408 | + }; | |
| 6409 | + } | |
| 6410 | + if (!waitingOnly) { | |
| 6411 | + if (typeof __test_queue_metrics_materialized === "function") { | |
| 6412 | + __test_queue_metrics_materialized(); | |
| 6413 | + } | |
| 6414 | + return { | |
| 6415 | + backlogCount: stats.backlog_count, | |
| 6416 | + backlogBytes: stats.backlog_bytes, | |
| 6417 | + oldestMessageTimestamp: stats.oldest_message_timestamp ?? null, | |
| 6418 | + }; | |
| 6419 | + } | |
| 6420 | + const blocked = sql.exec( | |
| 6421 | + `SELECT COALESCE(SUM(blocked_count), 0) AS blocked_count, | |
| 6422 | + COALESCE(SUM(blocked_bytes), 0) AS blocked_bytes | |
| 6423 | + FROM ( | |
| 6424 | + SELECT COUNT(*) AS blocked_count, | |
| 6425 | + COALESCE(SUM(size), 0) AS blocked_bytes | |
| 6426 | + FROM ${__QUEUE_MESSAGES} INDEXED BY ${__QUEUE_MESSAGES}_lease | |
| 6427 | + WHERE purge_on_settle = 0 AND lease_id IS NOT NULL | |
| 6428 | + UNION ALL | |
| 6429 | + SELECT COUNT(*) AS blocked_count, | |
| 6430 | + COALESCE(SUM(size), 0) AS blocked_bytes | |
| 6431 | + FROM ${__QUEUE_MESSAGES} INDEXED BY ${__QUEUE_MESSAGES}_moving | |
| 6432 | + WHERE purge_on_settle = 0 AND dlq_target IS NOT NULL | |
| 6433 | + UNION ALL | |
| 6434 | + SELECT COUNT(*) AS blocked_count, | |
| 6435 | + COALESCE(SUM(size), 0) AS blocked_bytes | |
| 6436 | + FROM ${__QUEUE_MESSAGES} INDEXED BY ${__QUEUE_MESSAGES}_ready | |
| 6437 | + WHERE purge_on_settle = 0 AND dlq_target IS NULL | |
| 6438 | + AND lease_id IS NULL AND visible_at > ? | |
| 6439 | + )`, | |
| 6440 | + now, | |
| 6441 | + ).toArray()[0]; | |
| 6442 | + const unleasedOldest = sql.exec( | |
| 6443 | + `SELECT enqueued_at | |
| 6444 | + FROM ${__QUEUE_MESSAGES} INDEXED BY ${__QUEUE_MESSAGES}_retained | |
| 6445 | + WHERE purge_on_settle = 0 AND dlq_target IS NULL | |
| 6446 | + AND lease_id IS NULL AND visible_at <= ? | |
| 6447 | + ORDER BY enqueued_at, seq | |
| 6448 | + LIMIT 1`, | |
| 6449 | + now, | |
| 6450 | + ).toArray()[0]?.enqueued_at ?? null; | |
| 6451 | + return { | |
| 6452 | + backlogCount: stats.backlog_count - blocked.blocked_count, | |
| 6453 | + backlogBytes: stats.backlog_bytes - blocked.blocked_bytes, | |
| 6454 | + oldestMessageTimestamp: unleasedOldest, | |
| 6455 | + }; | |
| 6456 | + } | |
| 6457 | + | |
| 6458 | + async _rearm(now = Date.now(), waitForWake = false) { | |
| 6459 | + const sql = this._open(); | |
| 6460 | + const consumer = __cell.queueConsumers?.[this.queue]; | |
| 6461 | + const paused = this._paused(); | |
| 6462 | + const active = sql.exec( | |
| 6463 | + `SELECT COUNT(DISTINCT lease_id) AS count | |
| 6464 | + FROM ${__QUEUE_MESSAGES} INDEXED BY ${__QUEUE_MESSAGES}_lease | |
| 6465 | + WHERE lease_id IS NOT NULL AND leased_until > ?`, | |
| 6466 | + now, | |
| 6467 | + ).toArray()[0].count; | |
| 6468 | + const concurrency = consumer | |
| 6469 | + ? consumer.maxConcurrency ?? __queueLimits().maxConcurrency | |
| 6470 | + : 0; | |
| 6471 | + const hasCapacity = !paused && consumer !== undefined && __queuePolicy({ | |
| 6472 | + op: "capacity", | |
| 6473 | + active, | |
| 6474 | + maximum: concurrency, | |
| 6475 | + }); | |
| 6476 | + // We need only enough ready rows to distinguish a partial batch from a | |
| 6477 | + // full one. The two indexed arms cover a new row and an expired lease, | |
| 6478 | + // and the outer LIMIT keeps the work independent of backlog depth. | |
| 6479 | + let ready = []; | |
| 6480 | + if (hasCapacity) { | |
| 6481 | + const visibleReady = sql.exec( | |
| 6482 | + `SELECT visible_at AS ready_at, seq | |
| 6483 | + FROM ${__QUEUE_MESSAGES} INDEXED BY ${__QUEUE_MESSAGES}_ready | |
| 6484 | + WHERE purge_on_settle = 0 AND dlq_target IS NULL | |
| 6485 | + AND lease_id IS NULL AND visible_at <= ? | |
| 6486 | + ORDER BY visible_at, seq | |
| 6487 | + LIMIT ?`, | |
| 6488 | + now, | |
| 6489 | + consumer.maxBatchSize, | |
| 6490 | + ).toArray(); | |
| 6491 | + const expiredReady = sql.exec( | |
| 6492 | + `SELECT leased_until AS ready_at, seq | |
| 6493 | + FROM ${__QUEUE_MESSAGES} INDEXED BY ${__QUEUE_MESSAGES}_lease | |
| 6494 | + WHERE purge_on_settle = 0 AND dlq_target IS NULL | |
| 6495 | + AND lease_id IS NOT NULL AND leased_until <= ? | |
| 6496 | + ORDER BY leased_until, seq | |
| 6497 | + LIMIT ?`, | |
| 6498 | + now, | |
| 6499 | + consumer.maxBatchSize, | |
| 6500 | + ).toArray(); | |
| 6501 | + ready = [...visibleReady, ...expiredReady] | |
| 6502 | + .sort((left, right) => left.ready_at - right.ready_at || left.seq - right.seq) | |
| 6503 | + .slice(0, consumer.maxBatchSize); | |
| 6504 | + } | |
| 6505 | + if (typeof __test_queue_rearm_bounded === "function") { | |
| 6506 | + __test_queue_rearm_bounded( | |
| 6507 | + ready.length <= (consumer?.maxBatchSize ?? 0), | |
| 6508 | + ready.length > 0, | |
| 6509 | + ); | |
| 6510 | + } | |
| 6511 | + const earliestVisible = hasCapacity | |
| 6512 | + ? sql.exec( | |
| 6513 | + `SELECT visible_at | |
| 6514 | + FROM ${__QUEUE_MESSAGES} INDEXED BY ${__QUEUE_MESSAGES}_ready | |
| 6515 | + WHERE purge_on_settle = 0 AND dlq_target IS NULL | |
| 6516 | + AND lease_id IS NULL AND visible_at > ? | |
| 6517 | + ORDER BY visible_at, seq | |
| 6518 | + LIMIT 1`, | |
| 6519 | + now, | |
| 6520 | + ).toArray()[0]?.visible_at ?? null | |
| 6521 | + : null; | |
| 6522 | + const earliestLeaseExpiry = paused | |
| 6523 | + ? null | |
| 6524 | + : sql.exec( | |
| 6525 | + `SELECT leased_until | |
| 6526 | + FROM ${__QUEUE_MESSAGES} INDEXED BY ${__QUEUE_MESSAGES}_lease | |
| 6527 | + WHERE lease_id IS NOT NULL | |
| 6528 | + ORDER BY leased_until | |
| 6529 | + LIMIT 1`, | |
| 6530 | + ).toArray()[0]?.leased_until ?? null; | |
| 6531 | + const nextSweep = sql.exec( | |
| 6532 | + `SELECT enqueued_at + ? AS next_sweep | |
| 6533 | + FROM ${__QUEUE_MESSAGES} INDEXED BY ${__QUEUE_MESSAGES}_retained | |
| 6534 | + WHERE dlq_target IS NULL AND purge_on_settle = 0 | |
| 6535 | + ORDER BY enqueued_at, seq | |
| 6536 | + LIMIT 1`, | |
| 6537 | + __queueLimits().retentionMs, | |
| 6538 | + ).toArray()[0]?.next_sweep ?? null; | |
| 6539 | + const dlqPending = sql.exec( | |
| 6540 | + `SELECT 1 AS pending | |
| 6541 | + FROM ${__QUEUE_MESSAGES} INDEXED BY ${__QUEUE_MESSAGES}_moving | |
| 6542 | + WHERE dlq_target IS NOT NULL | |
| 6543 | + LIMIT 1`, | |
| 6544 | + ).toArray().length !== 0; | |
| 6545 | + const receiptSweep = sql.exec( | |
| 6546 | + `SELECT expires_at AS next_sweep | |
| 6547 | + FROM ${__QUEUE_TRANSFER_RECEIPTS} | |
| 6548 | + ORDER BY expires_at, transfer_id | |
| 6549 | + LIMIT 1`, | |
| 6550 | + ).toArray()[0]?.next_sweep ?? null; | |
| 6551 | + // A queue without an attached consumer only wakes to reclaim retention. | |
| 6552 | + // Consumer attachment will nudge the cell when the fleet catalog gains a | |
| 6553 | + // registration; spinning on an already-visible row cannot make progress. | |
| 6554 | + let batchDeadline = null; | |
| 6555 | + if (ready.length > 0) { | |
| 6556 | + batchDeadline = ready.length >= consumer.maxBatchSize | |
| 6557 | + ? now | |
| 6558 | + : ready[0].ready_at + consumer.maxBatchTimeoutMs; | |
| 6559 | + } | |
| 6560 | + if (dlqPending) { | |
| 6561 | + batchDeadline = batchDeadline === null ? now : Math.min(batchDeadline, now); | |
| 6562 | + } | |
| 6563 | + const sweepDeadlines = [nextSweep, receiptSweep] | |
| 6564 | + .filter((deadline) => deadline !== null && deadline !== undefined); | |
| 6565 | + const armAt = __queuePolicy({ | |
| 6566 | + op: "rearm", | |
| 6567 | + now, | |
| 6568 | + batchDeadline, | |
| 6569 | + earliestVisible, | |
| 6570 | + // A live handler can settle after delivery pauses. Do not reclaim its | |
| 6571 | + // lease while paused; resume re-arms the expired deadline immediately | |
| 6572 | + // and only then can a new generation replace it. | |
| 6573 | + earliestLeaseExpiry, | |
| 6574 | + nextSweep: sweepDeadlines.length === 0 ? null : Math.min(...sweepDeadlines), | |
| 6575 | + }); | |
| 6576 | + if (armAt !== null && !Number.isFinite(armAt)) { | |
| 6577 | + throw __queueError("the Queue sweep deadline is invalid"); | |
| 6578 | + } | |
| 6579 | + if (armAt === null) await this.ctx.storage.deleteAlarm(); | |
| 6580 | + else if (waitForWake) { | |
| 6581 | + await __queue_alarm_set_wait(this.ctx.storage._scope, armAt); | |
| 6582 | + } else await this.ctx.storage.setAlarm(armAt); | |
| 6583 | + } | |
| 6584 | + | |
| 6585 | + _newProducerGroup() { | |
| 6586 | + const group = { | |
| 6587 | + calls: [], | |
| 6588 | + entries: [], | |
| 6589 | + bytes: 0, | |
| 6590 | + flushing: false, | |
| 6591 | + timer: null, | |
| 6592 | + }; | |
| 6593 | + this._producerGroup = group; | |
| 6594 | + group.timer = setTimeout(() => { | |
| 6595 | + void this._flushProducerGroup(group); | |
| 6596 | + }, __queueLimits().producerGroupMs); | |
| 6597 | + return group; | |
| 6598 | + } | |
| 6599 | + | |
| 6600 | + async _flushProducerGroup(group) { | |
| 6601 | + if (group.flushing) return; | |
| 6602 | + group.flushing = true; | |
| 6603 | + if (this._producerGroup === group) this._producerGroup = null; | |
| 6604 | + if (group.timer !== null) { | |
| 6605 | + clearTimeout(group.timer); | |
| 6606 | + group.timer = null; | |
| 6607 | + } | |
| 6608 | + | |
| 6609 | + const now = Date.now(); | |
| 6610 | + try { | |
| 6611 | + const sql = this._open(); | |
| 6612 | + this.ctx.storage.transactionSync(() => { | |
| 6613 | + for (const entry of group.entries) { | |
| 6614 | + sql.exec( | |
| 6615 | + `INSERT INTO ${__QUEUE_MESSAGES} | |
| 6616 | + (id, body, content_type, size, enqueued_at, visible_at) | |
| 6617 | + VALUES (?, ?, ?, ?, ?, ?)`, | |
| 6618 | + __queueMessageId(now), | |
| 6619 | + entry.body, | |
| 6620 | + entry.contentType, | |
| 6621 | + entry.size, | |
| 6622 | + now, | |
| 6623 | + now + entry.delaySeconds * 1000, | |
| 6624 | + ); | |
| 6625 | + } | |
| 6626 | + }); | |
| 6627 | + await this._rearm(now, true); | |
| 6628 | + const metrics = this._metrics(now); | |
| 6629 | + if (typeof __test_queue_producer_group === "function") { | |
| 6630 | + __test_queue_producer_group(group.calls.length, group.entries.length); | |
| 6631 | + } | |
| 6632 | + for (const call of group.calls) call.resolve(metrics); | |
| 6633 | + } catch (error) { | |
| 6634 | + for (const call of group.calls) call.reject(error); | |
| 6635 | + } | |
| 6636 | + } | |
| 6637 | + | |
| 6638 | + __queueSend({ entries }) { | |
| 6639 | + const bytes = entries.reduce((total, entry) => total + entry.size, 0); | |
| 6640 | + return new Promise((resolve, reject) => { | |
| 6641 | + let group = this._producerGroup; | |
| 6642 | + if (group !== null && | |
| 6643 | + (group.calls.length + 1 > __QUEUE_PRODUCER_GROUP_CALLS || | |
| 6644 | + group.entries.length + entries.length > __QUEUE_PRODUCER_GROUP_MESSAGES || | |
| 6645 | + group.bytes + bytes > __QUEUE_PRODUCER_GROUP_BYTES)) { | |
| 6646 | + void this._flushProducerGroup(group); | |
| 6647 | + group = null; | |
| 6648 | + } | |
| 6649 | + if (group === null) group = this._newProducerGroup(); | |
| 6650 | + group.calls.push({ resolve, reject }); | |
| 6651 | + group.entries.push(...entries); | |
| 6652 | + group.bytes += bytes; | |
| 6653 | + if (group.calls.length === __QUEUE_PRODUCER_GROUP_CALLS || | |
| 6654 | + group.entries.length === __QUEUE_PRODUCER_GROUP_MESSAGES || | |
| 6655 | + group.bytes === __QUEUE_PRODUCER_GROUP_BYTES) { | |
| 6656 | + void this._flushProducerGroup(group); | |
| 6657 | + } | |
| 6658 | + }); | |
| 6659 | + } | |
| 6660 | + | |
| 6661 | + __queueMetrics() { | |
| 6662 | + return this._metrics(); | |
| 6663 | + } | |
| 6664 | + | |
| 6665 | + // Retention decides visibility through `_metrics` immediately, while this | |
| 6666 | + // bounded sweep only reclaims space. A live lease is marked instead of | |
| 6667 | + // deleted, so its handler can finish but settlement or expiry removes it | |
| 6668 | + // without a redelivery. | |
| 6669 | + _sweep(now) { | |
| 6670 | + const sql = this._open(); | |
| 6671 | + const cutoff = now - __queueLimits().retentionMs; | |
| 6672 | + const messages = __cellSweepBatch( | |
| 6673 | + this.ctx.storage, | |
| 6674 | + (limit) => sql.exec( | |
| 6675 | + `SELECT seq, lease_id, leased_until FROM ${__QUEUE_MESSAGES} | |
| 6676 | + WHERE enqueued_at <= ? | |
| 6677 | + AND (purge_on_settle = 0 | |
| 6678 | + OR lease_id IS NULL OR leased_until <= ?) | |
| 6679 | + ORDER BY enqueued_at, seq | |
| 6680 | + LIMIT ?`, | |
| 6681 | + cutoff, | |
| 6682 | + now, | |
| 6683 | + limit, | |
| 6684 | + ).toArray(), | |
| 6685 | + (row) => { | |
| 6686 | + if (row.lease_id !== null && row.leased_until > now) { | |
| 6687 | + sql.exec( | |
| 6688 | + `UPDATE ${__QUEUE_MESSAGES} SET purge_on_settle = 1 WHERE seq = ?`, | |
| 6689 | + row.seq, | |
| 6690 | + ); | |
| 6691 | + } else { | |
| 6692 | + sql.exec(`DELETE FROM ${__QUEUE_MESSAGES} WHERE seq = ?`, row.seq); | |
| 6693 | + } | |
| 6694 | + }, | |
| 6695 | + __queueLimits().sweepBatchRows, | |
| 6696 | + ); | |
| 6697 | + const remaining = __queueLimits().sweepBatchRows - messages; | |
| 6698 | + if (remaining === 0) return messages; | |
| 6699 | + const receipts = __cellSweepBatch( | |
| 6700 | + this.ctx.storage, | |
| 6701 | + (limit) => sql.exec( | |
| 6702 | + `SELECT transfer_id FROM ${__QUEUE_TRANSFER_RECEIPTS} | |
| 6703 | + WHERE expires_at <= ? | |
| 6704 | + ORDER BY expires_at, transfer_id | |
| 6705 | + LIMIT ?`, | |
| 6706 | + now, | |
| 6707 | + limit, | |
| 6708 | + ).toArray(), | |
| 6709 | + (row) => { | |
| 6710 | + sql.exec( | |
| 6711 | + `DELETE FROM ${__QUEUE_TRANSFER_RECEIPTS} WHERE transfer_id = ?`, | |
| 6712 | + row.transfer_id, | |
| 6713 | + ); | |
| 6714 | + }, | |
| 6715 | + remaining, | |
| 6716 | + ); | |
| 6717 | + return messages + receipts; | |
| 6718 | + } | |
| 6719 | + | |
| 6720 | + _candidateRows(now, limit) { | |
| 6721 | + return this._open().exec( | |
| 6722 | + `SELECT seq, id, body, content_type, size, enqueued_at, visible_at, | |
| 6723 | + attempts, lease_id, lease_generation, leased_until, | |
| 6724 | + purge_on_settle | |
| 6725 | + FROM ${__QUEUE_MESSAGES} | |
| 6726 | + WHERE dlq_target IS NULL AND ((purge_on_settle = 1 | |
| 6727 | + AND (lease_id IS NULL OR leased_until <= ?)) | |
| 6728 | + OR (purge_on_settle = 0 AND visible_at <= ? | |
| 6729 | + AND (lease_id IS NULL OR leased_until <= ?))) | |
| 6730 | + ORDER BY visible_at, seq | |
| 6731 | + LIMIT ?`, | |
| 6732 | + now, | |
| 6733 | + now, | |
| 6734 | + now, | |
| 6735 | + limit, | |
| 6736 | + ).toArray(); | |
| 6737 | + } | |
| 6738 | + | |
| 6739 | + async _leaseBatch(now, consumer) { | |
| 6740 | + const sql = this._open(); | |
| 6741 | + const active = sql.exec( | |
| 6742 | + `SELECT COUNT(DISTINCT lease_id) AS count | |
| 6743 | + FROM ${__QUEUE_MESSAGES} | |
| 6744 | + WHERE lease_id IS NOT NULL AND leased_until > ?`, | |
| 6745 | + now, | |
| 6746 | + ).toArray()[0].count; | |
| 6747 | + const concurrency = consumer.maxConcurrency ?? __queueLimits().maxConcurrency; | |
| 6748 | + if (!__queuePolicy({ op: "capacity", active, maximum: concurrency })) return null; | |
| 6749 | + | |
| 6750 | + // Read extra rows so expired purge markers cannot hide a deliverable | |
| 6751 | + // batch. Policy chooses at most `maxBatchSize` rows and returns every | |
| 6752 | + // purge deletion that precedes them in this bounded scan. | |
| 6753 | + const rows = this._candidateRows(now, consumer.maxBatchSize + 256); | |
| 6754 | + const deliverable = rows.filter((row) => row.purge_on_settle === 0); | |
| 6755 | + if (deliverable.length === 0) { | |
| 6756 | + if (rows.length > 0) { | |
| 6757 | + this.ctx.storage.transactionSync(() => { | |
| 6758 | + for (const row of rows) { | |
| 6759 | + sql.exec(`DELETE FROM ${__QUEUE_MESSAGES} WHERE seq = ?`, row.seq); | |
| 6760 | + } | |
| 6761 | + }); | |
| 6762 | + } | |
| 6763 | + return null; | |
| 6764 | + } | |
| 6765 | + const readySince = Math.min(...deliverable.map((row) => | |
| 6766 | + row.lease_id === null ? row.visible_at : row.leased_until | |
| 6767 | + )); | |
| 6768 | + if (deliverable.length < consumer.maxBatchSize && | |
| 6769 | + readySince + consumer.maxBatchTimeoutMs > now) { | |
| 6770 | + return null; | |
| 6771 | + } | |
| 6772 | + | |
| 6773 | + const plan = __queuePolicy({ | |
| 6774 | + op: "batch", | |
| 6775 | + now, | |
| 6776 | + maxBatchSize: consumer.maxBatchSize, | |
| 6777 | + rows: rows.map((row) => ({ | |
| 6778 | + seq: row.seq, | |
| 6779 | + visibleAt: row.visible_at, | |
| 6780 | + leaseGeneration: String(row.lease_generation), | |
| 6781 | + leasedUntil: row.leased_until, | |
| 6782 | + purgeOnSettle: row.purge_on_settle !== 0, | |
| 6783 | + })), | |
| 6784 | + }); | |
| 6785 | + if (plan.leases.length === 0 && plan.deletePurged.length === 0) return null; | |
| 6786 | + const rowBySeq = new Map(rows.map((row) => [row.seq, row])); | |
| 6787 | + const reclaimed = plan.leases.filter((lease) => lease.reclaimed); | |
| 6788 | + const expiryPolicy = __queuePolicy({ | |
| 6789 | + op: "expiry", | |
| 6790 | + now, | |
| 6791 | + entries: reclaimed.map((lease) => { | |
| 6792 | + const row = rowBySeq.get(lease.seq); | |
| 6793 | + return { | |
| 6794 | + priorFailures: row.attempts, | |
| 6795 | + maxRetries: consumer.maxRetries, | |
| 6796 | + configuredSeconds: consumer.retryDelaySeconds ?? null, | |
| 6797 | + purgeOnSettle: row.purge_on_settle !== 0, | |
| 6798 | + }; | |
| 6799 | + }), | |
| 6800 | + }); | |
| 6801 | + const expiryBySeq = new Map( | |
| 6802 | + reclaimed.map((lease, index) => [lease.seq, expiryPolicy[index]]), | |
| 6803 | + ); | |
| 6804 | + const installs = plan.leases.filter((lease) => { | |
| 6805 | + const expiry = expiryBySeq.get(lease.seq); | |
| 6806 | + return expiry === undefined || | |
| 6807 | + (expiry.action.kind === "retry" && expiry.action.at <= now); | |
| 6808 | + }); | |
| 6809 | + const exhaustedTransfers = new Map( | |
| 6810 | + reclaimed | |
| 6811 | + .filter((lease) => | |
| 6812 | + expiryBySeq.get(lease.seq).action.kind === "exhausted" && | |
| 6813 | + consumer.deadLetterQueue !== undefined | |
| 6814 | + ) | |
| 6815 | + .map((lease) => [lease.seq, crypto.randomUUID()]), | |
| 6816 | + ); | |
| 6817 | + const leaseId = crypto.randomUUID(); | |
| 6818 | + const leasedUntil = Math.min( | |
| 6819 | + Number.MAX_SAFE_INTEGER, | |
| 6820 | + now + __cell.queueLeaseDurationMs, | |
| 6821 | + ); | |
| 6822 | + this.ctx.storage.transactionSync(() => { | |
| 6823 | + for (const seq of plan.deletePurged) { | |
| 6824 | + sql.exec( | |
| 6825 | + `DELETE FROM ${__QUEUE_MESSAGES} | |
| 6826 | + WHERE seq = ? AND purge_on_settle = 1 | |
| 6827 | + AND (lease_id IS NULL OR leased_until <= ?)`, | |
| 6828 | + seq, | |
| 6829 | + now, | |
| 6830 | + ); | |
| 6831 | + } | |
| 6832 | + for (const lease of reclaimed) { | |
| 6833 | + const expiry = expiryBySeq.get(lease.seq); | |
| 6834 | + if (expiry.action.kind === "delete-purged") { | |
| 6835 | + sql.exec( | |
| 6836 | + `DELETE FROM ${__QUEUE_MESSAGES} | |
| 6837 | + WHERE seq = ? AND leased_until <= ?`, | |
| 6838 | + lease.seq, | |
| 6839 | + now, | |
| 6840 | + ); | |
| 6841 | + } else if (expiry.action.kind === "exhausted") { | |
| 6842 | + if (consumer.deadLetterQueue === undefined) { | |
| 6843 | + sql.exec( | |
| 6844 | + `DELETE FROM ${__QUEUE_MESSAGES} | |
| 6845 | + WHERE seq = ? AND leased_until <= ?`, | |
| 6846 | + lease.seq, | |
| 6847 | + now, | |
| 6848 | + ); | |
| 6849 | + } else { | |
| 6850 | + sql.exec( | |
| 6851 | + `UPDATE ${__QUEUE_MESSAGES} | |
| 6852 | + SET attempts = ?, lease_id = NULL, leased_until = NULL, | |
| 6853 | + dlq_target = ?, dlq_transfer_id = ?, | |
| 6854 | + transfer_kind = 'dead-letter' | |
| 6855 | + WHERE seq = ? AND leased_until <= ?`, | |
| 6856 | + expiry.attempt, | |
| 6857 | + consumer.deadLetterQueue, | |
| 6858 | + exhaustedTransfers.get(lease.seq), | |
| 6859 | + lease.seq, | |
| 6860 | + now, | |
| 6861 | + ); | |
| 6862 | + } | |
| 6863 | + } else if (expiry.action.at > now) { | |
| 6864 | + sql.exec( | |
| 6865 | + `UPDATE ${__QUEUE_MESSAGES} | |
| 6866 | + SET attempts = ?, visible_at = ?, lease_id = NULL, | |
| 6867 | + leased_until = NULL | |
| 6868 | + WHERE seq = ? AND leased_until <= ?`, | |
| 6869 | + expiry.attempt, | |
| 6870 | + expiry.action.at, | |
| 6871 | + lease.seq, | |
| 6872 | + now, | |
| 6873 | + ); | |
| 6874 | + } | |
| 6875 | + } | |
| 6876 | + for (const lease of installs) { | |
| 6877 | + const generation = Number(lease.generation); | |
| 6878 | + if (!Number.isSafeInteger(generation)) { | |
| 6879 | + throw __queueError(`message ${lease.seq} exhausted its safe lease generation`); | |
| 6880 | + } | |
| 6881 | + sql.exec( | |
| 6882 | + `UPDATE ${__QUEUE_MESSAGES} | |
| 6883 | + SET lease_id = ?, lease_generation = ?, leased_until = ?, | |
| 6884 | + attempts = attempts + ? | |
| 6885 | + WHERE seq = ? AND lease_generation = ? | |
| 6886 | + AND (lease_id IS NULL OR leased_until <= ?)`, | |
| 6887 | + leaseId, | |
| 6888 | + generation, | |
| 6889 | + leasedUntil, | |
| 6890 | + lease.reclaimed ? 1 : 0, | |
| 6891 | + lease.seq, | |
| 6892 | + generation - 1, | |
| 6893 | + now, | |
| 6894 | + ); | |
| 6895 | + } | |
| 6896 | + }); | |
| 6897 | + if (installs.length === 0) return null; | |
| 6898 | + const leasedQuery = | |
| 6899 | + `SELECT seq, id, body, content_type, enqueued_at, attempts, | |
| 6900 | + lease_generation | |
| 6901 | + FROM ${__QUEUE_MESSAGES} | |
| 6902 | + WHERE lease_id = ? | |
| 6903 | + ORDER BY visible_at, seq`; | |
| 6904 | + __queueReportLeaseLookupPlan(sql, leasedQuery, leaseId); | |
| 6905 | + const leased = sql.exec(leasedQuery, leaseId).toArray(); | |
| 6906 | + if (leased.length !== installs.length) { | |
| 6907 | + throw __queueError("the Queue lease transaction changed fewer rows than its plan"); | |
| 6908 | + } | |
| 6909 | + return { | |
| 6910 | + leaseId, | |
| 6911 | + leases: leased.map((row) => ({ | |
| 6912 | + message_id: row.id, | |
| 6913 | + seq: row.seq, | |
| 6914 | + generation: row.lease_generation, | |
| 6915 | + })), | |
| 6916 | + messages: leased.map((row) => ({ | |
| 6917 | + id: row.id, | |
| 6918 | + timestampMs: row.enqueued_at, | |
| 6919 | + // SQLite answers a BLOB as an ArrayBuffer. The raw base64 op accepts | |
| 6920 | + // typed views, so normalize here; otherwise it encodes the text | |
| 6921 | + // "[object ArrayBuffer]" and every consumer decoder sees corrupt data. | |
| 6922 | + bodyBase64: $$btoa( | |
| 6923 | + row.body instanceof Uint8Array ? row.body : new Uint8Array(row.body), | |
| 6924 | + ), | |
| 6925 | + contentType: row.content_type, | |
| 6926 | + attempts: row.attempts + 1, | |
| 6927 | + })), | |
| 6928 | + // Miniflare removes every dispatched batch from its backlog before it | |
| 6929 | + // invokes the consumer. Exclude every lease here for the same contract; | |
| 6930 | + // the operator aggregate still includes durable in-flight messages. | |
| 6931 | + metrics: this._metrics(now, true), | |
| 6932 | + }; | |
| 6933 | + } | |
| 6934 | + | |
| 6935 | + // The target deduplicates the stable transfer identity. The source can | |
| 6936 | + // therefore repeat this call after a stop between the target commit and the | |
| 6937 | + // source delete without creating a second message. | |
| 6938 | + async __queueDlqAcceptBatch({ transfers }) { | |
| 6939 | + if (!Array.isArray(transfers) || transfers.length === 0 || | |
| 6940 | + transfers.length > __queueLimits().maxBatchMessages) { | |
| 6941 | + throw __queueError("a Queue transfer batch has an invalid size"); | |
| 6942 | + } | |
| 6943 | + for (const transfer of transfers) { | |
| 6944 | + if (transfer.deadLetterSource !== null && | |
| 6945 | + typeof transfer.deadLetterSource !== "string") { | |
| 6946 | + throw __queueError("a Queue transfer has an invalid dead-letter source"); | |
| 6947 | + } | |
| 6948 | + } | |
| 6949 | + const now = Date.now(); | |
| 6950 | + const sql = this._open(); | |
| 6951 | + this.ctx.storage.transactionSync(() => { | |
| 6952 | + for (const { transferId, entry, deadLetterSource } of transfers) { | |
| 6953 | + const accepted = sql.exec( | |
| 6954 | + `SELECT message_id, dead_letter_source | |
| 6955 | + FROM ${__QUEUE_TRANSFER_RECEIPTS} | |
| 6956 | + WHERE transfer_id = ?`, | |
| 6957 | + transferId, | |
| 6958 | + ).toArray()[0]; | |
| 6959 | + if (accepted !== undefined && (accepted.message_id !== entry.id || | |
| 6960 | + accepted.dead_letter_source !== deadLetterSource)) { | |
| 6961 | + throw __queueError("a DLQ transfer collided with another message identity"); | |
| 6962 | + } | |
| 6963 | + if (accepted !== undefined) continue; | |
| 6964 | + sql.exec( | |
| 6965 | + `INSERT INTO ${__QUEUE_TRANSFER_RECEIPTS} | |
| 6966 | + (transfer_id, message_id, dead_letter_source, expires_at) | |
| 6967 | + VALUES (?, ?, ?, ?)`, | |
| 6968 | + transferId, | |
| 6969 | + entry.id, | |
| 6970 | + deadLetterSource, | |
| 6971 | + now + __queueLimits().retentionMs, | |
| 6972 | + ); | |
| 6973 | + sql.exec( | |
| 6974 | + `INSERT INTO ${__QUEUE_MESSAGES} | |
| 6975 | + (id, body, content_type, size, enqueued_at, visible_at, | |
| 6976 | + attempts, dlq_transfer_id, dead_letter_source) | |
| 6977 | + VALUES (?, ?, ?, ?, ?, ?, 0, ?, ?)`, | |
| 6978 | + entry.id, | |
| 6979 | + entry.body, | |
| 6980 | + entry.contentType, | |
| 6981 | + entry.size, | |
| 6982 | + now, | |
| 6983 | + now, | |
| 6984 | + transferId, | |
| 6985 | + deadLetterSource, | |
| 6986 | + ); | |
| 6987 | + } | |
| 6988 | + }); | |
| 6989 | + await this._rearm(now); | |
| 6990 | + return this._metrics(now); | |
| 6991 | + } | |
| 6992 | + | |
| 6993 | + async _driveDlq(limit = 100) { | |
| 6994 | + const now = Date.now(); | |
| 6995 | + const pending = this._open().exec( | |
| 6996 | + `SELECT seq, id, body, content_type, size, dlq_target, dlq_transfer_id, | |
| 6997 | + transfer_kind | |
| 6998 | + FROM ${__QUEUE_MESSAGES} | |
| 6999 | + WHERE dlq_target IS NOT NULL | |
| 7000 | + AND enqueued_at > ? | |
| 7001 | + ORDER BY seq | |
| 7002 | + LIMIT ?`, | |
| 7003 | + now - __queueLimits().retentionMs, | |
| 7004 | + limit, | |
| 7005 | + ).toArray(); | |
| 7006 | + const groups = new Map(); | |
| 7007 | + for (const row of pending) { | |
| 7008 | + let group = groups.get(row.dlq_target); | |
| 7009 | + if (group === undefined) groups.set(row.dlq_target, group = []); | |
| 7010 | + group.push(row); | |
| 7011 | + } | |
| 7012 | + for (const [targetName, rows] of groups) { | |
| 7013 | + const target = __cell.makeNamespace("__Queue").getByName(targetName); | |
| 7014 | + await target.__queueDlqAcceptBatch({ | |
| 7015 | + transfers: rows.map((row) => ({ | |
| 7016 | + transferId: row.dlq_transfer_id, | |
| 7017 | + // A dead-letter transfer records where redrive returns the message. | |
| 7018 | + // A redrive returns it to ordinary queue state, so the source marker | |
| 7019 | + // must not follow it and make a later redrive bounce it backwards. | |
| 7020 | + deadLetterSource: row.transfer_kind === "dead-letter" ? this.queue : null, | |
| 7021 | + entry: { | |
| 7022 | + id: row.id, | |
| 7023 | + body: row.body, | |
| 7024 | + contentType: row.content_type, | |
| 7025 | + size: row.size, | |
| 7026 | + }, | |
| 7027 | + })), | |
| 7028 | + }); | |
| 7029 | + if (typeof __test_queue_dlq_accepted === "function") { | |
| 7030 | + __test_queue_dlq_accepted(); | |
| 7031 | + } | |
| 7032 | + // The target committed every receipt before this reply. Delete the | |
| 7033 | + // corresponding source marks together; a stop before this transaction | |
| 7034 | + // leaves the whole group replayable through those stable receipts. | |
| 7035 | + this.ctx.storage.transactionSync(() => { | |
| 7036 | + for (const row of rows) { | |
| 7037 | + this._open().exec( | |
| 7038 | + `DELETE FROM ${__QUEUE_MESSAGES} | |
| 7039 | + WHERE seq = ? AND dlq_target = ? AND dlq_transfer_id = ? | |
| 7040 | + AND transfer_kind = ?`, | |
| 7041 | + row.seq, | |
| 7042 | + row.dlq_target, | |
| 7043 | + row.dlq_transfer_id, | |
| 7044 | + row.transfer_kind, | |
| 7045 | + ); | |
| 7046 | + } | |
| 7047 | + }); | |
| 7048 | + } | |
| 7049 | + return pending.length; | |
| 7050 | + } | |
| 7051 | + | |
| 7052 | + async alarm() { | |
| 7053 | + const now = Date.now(); | |
| 7054 | + try { | |
| 7055 | + await this._driveDlq(); | |
| 7056 | + } catch (error) { | |
| 7057 | + // The durable source mark is the retry record. An alarm stays armed at | |
| 7058 | + // `now`, and the target's transfer identity makes a replay idempotent. | |
| 7059 | + console.error("Queue DLQ transfer failed:", error); | |
| 7060 | + } | |
| 7061 | + const swept = this._sweep(now); | |
| 7062 | + const consumer = this._paused() | |
| 7063 | + ? undefined | |
| 7064 | + : __cell.queueConsumers?.[this.queue]; | |
| 7065 | + // Install every lease that the configured concurrency admits before the | |
| 7066 | + // first consumer can settle. One lease per alarm serialized full batches | |
| 7067 | + // because the next alarm depended on a later scheduler turn, so a queue | |
| 7068 | + // with maxConcurrency > 1 still used only one handler under backlog. | |
| 7069 | + // `_leaseBatch` counts the durable lease IDs on every iteration, which | |
| 7070 | + // makes the configured concurrency the structural bound for this loop. | |
| 7071 | + const batches = []; | |
| 7072 | + if (consumer !== undefined) { | |
| 7073 | + while (true) { | |
| 7074 | + const batch = await this._leaseBatch(now, consumer); | |
| 7075 | + if (batch === null) break; | |
| 7076 | + batches.push(batch); | |
| 7077 | + } | |
| 7078 | + } | |
| 7079 | + try { | |
| 7080 | + // `_leaseBatch` can exhaust an expired lease and create a new durable | |
| 7081 | + // DLQ mark. Drive that mark in the same wake; the first call above is | |
| 7082 | + // for a mark recovered from an earlier stopped process. | |
| 7083 | + await this._driveDlq(); | |
| 7084 | + } catch (error) { | |
| 7085 | + console.error("Queue DLQ transfer failed:", error); | |
| 7086 | + } | |
| 7087 | + await this._rearm(now); | |
| 7088 | + if (swept >= __queueLimits().sweepBatchRows && batches.length === 0) { | |
| 7089 | + await this.ctx.storage.setAlarm(now + 1); | |
| 7090 | + return; | |
| 7091 | + } | |
| 7092 | + for (const batch of batches) { | |
| 7093 | + // This await covers only the output-gated handoff to the host. The | |
| 7094 | + // consumer runs after this alarm returns, and settlement comes back as | |
| 7095 | + // an independent cell event. All admitted leases are durable before the | |
| 7096 | + // first handoff, so a fast settlement cannot make this turn exceed the | |
| 7097 | + // configured concurrency. | |
| 7098 | + await __queue_dispatch( | |
| 7099 | + consumer.script, | |
| 7100 | + this.queue, | |
| 7101 | + JSON.stringify(batch), | |
| 7102 | + ); | |
| 7103 | + } | |
| 7104 | + } | |
| 7105 | + | |
| 7106 | + _matchingLease(body) { | |
| 7107 | + if (typeof body.leaseId !== "string" || !Array.isArray(body.leases)) return null; | |
| 7108 | + const matchQuery = | |
| 7109 | + `SELECT seq, id, attempts, lease_generation, purge_on_settle | |
| 7110 | + FROM ${__QUEUE_MESSAGES} | |
| 7111 | + WHERE lease_id = ? | |
| 7112 | + ORDER BY seq`; | |
| 7113 | + __queueReportLeaseLookupPlan(this._open(), matchQuery, body.leaseId); | |
| 7114 | + const rows = this._open().exec(matchQuery, body.leaseId).toArray(); | |
| 7115 | + for (const lease of body.leases) { | |
| 7116 | + if (typeof lease?.message_id !== "string" || | |
| 7117 | + !Number.isSafeInteger(lease.seq) || | |
| 7118 | + !Number.isSafeInteger(lease.generation)) return null; | |
| 7119 | + } | |
| 7120 | + const matches = __queuePolicy({ | |
| 7121 | + op: "settlement", | |
| 7122 | + current: rows.map((row) => ({ | |
| 7123 | + seq: String(row.seq), | |
| 7124 | + messageId: row.id, | |
| 7125 | + generation: String(row.lease_generation), | |
| 7126 | + })), | |
| 7127 | + submitted: body.leases.map((lease) => ({ | |
| 7128 | + seq: String(lease.seq), | |
| 7129 | + messageId: lease.message_id, | |
| 7130 | + generation: String(lease.generation), | |
| 7131 | + })), | |
| 7132 | + }); | |
| 7133 | + return matches ? rows : null; | |
| 7134 | + } | |
| 7135 | + | |
| 7136 | + async _settle(body) { | |
| 7137 | + const rows = this._matchingLease(body); | |
| 7138 | + if (rows === null) return false; | |
| 7139 | + const consumer = __cell.queueConsumers?.[this.queue]; | |
| 7140 | + if (consumer === undefined) return false; | |
| 7141 | + const explicitAcks = new Set(body.explicitAcks ?? []); | |
| 7142 | + const retryMessages = new Map( | |
| 7143 | + (body.retryMessages ?? []).map((retry) => [retry.msgId, retry.delaySeconds]), | |
| 7144 | + ); | |
| 7145 | + const retryBatch = body.retryBatch?.retry === true; | |
| 7146 | + const batchDelay = body.retryBatch?.delaySeconds; | |
| 7147 | + const exception = body.outcome === "exception"; | |
| 7148 | + // An explicit ack-all survives a later handler exception, so it must | |
| 7149 | + // override every batch-level and message-level retry signal. | |
| 7150 | + const ackAll = body.ackAll === true; | |
| 7151 | + const decisions = rows.map((row) => { | |
| 7152 | + const retry = !ackAll && !explicitAcks.has(row.id) && ( | |
| 7153 | + retryMessages.has(row.id) || retryBatch || exception | |
| 7154 | + ); | |
| 7155 | + return { row, retry }; | |
| 7156 | + }); | |
| 7157 | + const retrying = decisions.filter((decision) => | |
| 7158 | + decision.retry && decision.row.purge_on_settle === 0 | |
| 7159 | + ); | |
| 7160 | + const retryPolicy = __queuePolicy({ | |
| 7161 | + op: "retries", | |
| 7162 | + now: Date.now(), | |
| 7163 | + entries: retrying.map(({ row }) => ({ | |
| 7164 | + attempt: row.attempts + 1, | |
| 7165 | + maxRetries: consumer.maxRetries, | |
| 7166 | + explicitSeconds: retryMessages.has(row.id) | |
| 7167 | + ? retryMessages.get(row.id) | |
| 7168 | + : retryBatch ? batchDelay : null, | |
| 7169 | + configuredSeconds: consumer.retryDelaySeconds ?? null, | |
| 7170 | + })), | |
| 7171 | + }); | |
| 7172 | + const retryById = new Map( | |
| 7173 | + retrying.map(({ row }, index) => [row.id, retryPolicy[index]]), | |
| 7174 | + ); | |
| 7175 | + const dlqTransferById = new Map( | |
| 7176 | + retrying | |
| 7177 | + .filter(({ row }) => | |
| 7178 | + retryById.get(row.id).exhausted && consumer.deadLetterQueue !== undefined | |
| 7179 | + ) | |
| 7180 | + .map(({ row }) => [row.id, crypto.randomUUID()]), | |
| 7181 | + ); | |
| 7182 | + const sql = this._open(); | |
| 7183 | + this.ctx.storage.transactionSync(() => { | |
| 7184 | + for (const { row, retry } of decisions) { | |
| 7185 | + const policy = retryById.get(row.id); | |
| 7186 | + if (row.purge_on_settle !== 0 || !retry || | |
| 7187 | + (policy.exhausted && consumer.deadLetterQueue === undefined)) { | |
| 7188 | + sql.exec( | |
| 7189 | + `DELETE FROM ${__QUEUE_MESSAGES} | |
| 7190 | + WHERE seq = ? AND lease_id = ? AND lease_generation = ?`, | |
| 7191 | + row.seq, | |
| 7192 | + body.leaseId, | |
| 7193 | + row.lease_generation, | |
| 7194 | + ); | |
| 7195 | + continue; | |
| 7196 | + } | |
| 7197 | + if (policy.exhausted) { | |
| 7198 | + sql.exec( | |
| 7199 | + `UPDATE ${__QUEUE_MESSAGES} | |
| 7200 | + SET attempts = attempts + 1, lease_id = NULL, | |
| 7201 | + leased_until = NULL, dlq_target = ?, dlq_transfer_id = ?, | |
| 7202 | + transfer_kind = 'dead-letter' | |
| 7203 | + WHERE seq = ? AND lease_id = ? AND lease_generation = ?`, | |
| 7204 | + consumer.deadLetterQueue, | |
| 7205 | + dlqTransferById.get(row.id), | |
| 7206 | + row.seq, | |
| 7207 | + body.leaseId, | |
| 7208 | + row.lease_generation, | |
| 7209 | + ); | |
| 7210 | + continue; | |
| 7211 | + } | |
| 7212 | + sql.exec( | |
| 7213 | + `UPDATE ${__QUEUE_MESSAGES} | |
| 7214 | + SET attempts = attempts + 1, visible_at = ?, | |
| 7215 | + lease_id = NULL, leased_until = NULL | |
| 7216 | + WHERE seq = ? AND lease_id = ? AND lease_generation = ?`, | |
| 7217 | + policy.at, | |
| 7218 | + row.seq, | |
| 7219 | + body.leaseId, | |
| 7220 | + row.lease_generation, | |
| 7221 | + ); | |
| 7222 | + } | |
| 7223 | + }); | |
| 7224 | + try { | |
| 7225 | + await this._driveDlq(); | |
| 7226 | + } catch (error) { | |
| 7227 | + // Settlement is durable once the source mark commits. A failed transfer | |
| 7228 | + // is alarm work now, not a reason to put the message back in delivery. | |
| 7229 | + console.error("Queue DLQ transfer deferred:", error); | |
| 7230 | + } | |
| 7231 | + await this._rearm(); | |
| 7232 | + return true; | |
| 7233 | + } | |
| 7234 | + | |
| 7235 | + async _purge() { | |
| 7236 | + const now = Date.now(); | |
| 7237 | + const sql = this._open(); | |
| 7238 | + let deleted = 0; | |
| 7239 | + let leased = 0; | |
| 7240 | + this.ctx.storage.transactionSync(() => { | |
| 7241 | + let after = 0; | |
| 7242 | + while (true) { | |
| 7243 | + // Purge is necessarily proportional to the stored backlog, but its | |
| 7244 | + // policy envelope stays bounded instead of materializing the Queue in | |
| 7245 | + // V8 or Rust. One SQLite transaction keeps the visibility change | |
| 7246 | + // atomic across all chunks. | |
| 7247 | + const rows = sql.exec( | |
| 7248 | + `SELECT seq, lease_id, leased_until FROM ${__QUEUE_MESSAGES} | |
| 7249 | + WHERE seq > ? | |
| 7250 | + ORDER BY seq | |
| 7251 | + LIMIT 256`, | |
| 7252 | + after, | |
| 7253 | + ).toArray(); | |
| 7254 | + if (rows.length === 0) break; | |
| 7255 | + after = rows[rows.length - 1].seq; | |
| 7256 | + const plan = __queuePolicy({ | |
| 7257 | + op: "purge", | |
| 7258 | + now, | |
| 7259 | + rows: rows.map((row) => ({ | |
| 7260 | + seq: String(row.seq), | |
| 7261 | + leaseIdPresent: row.lease_id !== null, | |
| 7262 | + leasedUntil: row.leased_until, | |
| 7263 | + })), | |
| 7264 | + }); | |
| 7265 | + for (const seq of plan.delete) { | |
| 7266 | + sql.exec( | |
| 7267 | + `DELETE FROM ${__QUEUE_MESSAGES} | |
| 7268 | + WHERE seq = ? | |
| 7269 | + AND (lease_id IS NULL OR leased_until IS NULL OR leased_until <= ?)`, | |
| 7270 | + Number(seq), | |
| 7271 | + now, | |
| 7272 | + ); | |
| 7273 | + deleted += 1; | |
| 7274 | + } | |
| 7275 | + for (const seq of plan.markForSettle) { | |
| 7276 | + sql.exec( | |
| 7277 | + `UPDATE ${__QUEUE_MESSAGES} SET purge_on_settle = 1 | |
| 7278 | + WHERE seq = ? AND lease_id IS NOT NULL AND leased_until > ?`, | |
| 7279 | + Number(seq), | |
| 7280 | + now, | |
| 7281 | + ); | |
| 7282 | + leased += 1; | |
| 7283 | + } | |
| 7284 | + } | |
| 7285 | + }); | |
| 7286 | + await this._rearm(now); | |
| 7287 | + return { deleted, leased, metrics: this._metrics(now) }; | |
| 7288 | + } | |
| 7289 | + | |
| 7290 | + async _setPaused(paused) { | |
| 7291 | + this._setMeta("paused", paused ? "1" : null); | |
| 7292 | + await this._rearm(); | |
| 7293 | + return { paused, ...this._metrics() }; | |
| 7294 | + } | |
| 7295 | + | |
| 7296 | + _operatorLimit(value, fallback) { | |
| 7297 | + const limit = value ?? fallback; | |
| 7298 | + if (!Number.isInteger(limit) || limit < 1 || limit > 100) { | |
| 7299 | + throw __queueError("limit must be an integer from 1 through 100"); | |
| 7300 | + } | |
| 7301 | + return limit; | |
| 7302 | + } | |
| 7303 | + | |
| 7304 | + _peek(limit) { | |
| 7305 | + const now = Date.now(); | |
| 7306 | + const cutoff = now - __queueLimits().retentionMs; | |
| 7307 | + const rows = this._open().exec( | |
| 7308 | + `SELECT id, body, content_type, size, enqueued_at, visible_at, attempts, | |
| 7309 | + lease_id, leased_until, purge_on_settle, dlq_target, | |
| 7310 | + dead_letter_source | |
| 7311 | + FROM ${__QUEUE_MESSAGES} | |
| 7312 | + WHERE enqueued_at > ? | |
| 7313 | + ORDER BY visible_at, seq | |
| 7314 | + LIMIT ?`, | |
| 7315 | + cutoff, | |
| 7316 | + limit, | |
| 7317 | + ).toArray(); | |
| 7318 | + return { | |
| 7319 | + messages: rows.map((row) => ({ | |
| 7320 | + id: row.id, | |
| 7321 | + bodyBase64: $$btoa( | |
| 7322 | + row.body instanceof Uint8Array ? row.body : new Uint8Array(row.body), | |
| 7323 | + ), | |
| 7324 | + contentType: row.content_type, | |
| 7325 | + size: row.size, | |
| 7326 | + enqueuedAt: row.enqueued_at, | |
| 7327 | + visibleAt: row.visible_at, | |
| 7328 | + attempts: row.attempts, | |
| 7329 | + state: row.dlq_target !== null | |
| 7330 | + ? "moving" | |
| 7331 | + : row.purge_on_settle !== 0 | |
| 7332 | + ? "purging" | |
| 7333 | + : row.lease_id !== null && row.leased_until > now | |
| 7334 | + ? "leased" | |
| 7335 | + : row.visible_at <= now | |
| 7336 | + ? "visible" | |
| 7337 | + : "delayed", | |
| 7338 | + leasedUntil: row.lease_id !== null && row.leased_until > now | |
| 7339 | + ? row.leased_until | |
| 7340 | + : null, | |
| 7341 | + transferTarget: row.dlq_target, | |
| 7342 | + deadLetterSource: row.dead_letter_source, | |
| 7343 | + })), | |
| 7344 | + }; | |
| 7345 | + } | |
| 7346 | + | |
| 7347 | + async _redrive(limit) { | |
| 7348 | + // Finish an interrupted move before selecting more work. A transfer mark | |
| 7349 | + // is durable, so selecting it a second time would invent another identity | |
| 7350 | + // where replaying the existing identity is sufficient. | |
| 7351 | + await this._driveDlq(100); | |
| 7352 | + const now = Date.now(); | |
| 7353 | + const cutoff = now - __queueLimits().retentionMs; | |
| 7354 | + const candidates = this._open().exec( | |
| 7355 | + `SELECT seq, dead_letter_source | |
| 7356 | + FROM ${__QUEUE_MESSAGES} | |
| 7357 | + WHERE dead_letter_source IS NOT NULL | |
| 7358 | + AND dlq_target IS NULL | |
| 7359 | + AND purge_on_settle = 0 | |
| 7360 | + AND enqueued_at > ? | |
| 7361 | + AND (lease_id IS NULL OR leased_until <= ?) | |
| 7362 | + ORDER BY visible_at, seq | |
| 7363 | + LIMIT ?`, | |
| 7364 | + cutoff, | |
| 7365 | + now, | |
| 7366 | + limit, | |
| 7367 | + ).toArray(); | |
| 7368 | + const transfers = candidates.map((row) => ({ | |
| 7369 | + ...row, | |
| 7370 | + transferId: crypto.randomUUID(), | |
| 7371 | + })); | |
| 7372 | + this.ctx.storage.transactionSync(() => { | |
| 7373 | + for (const transfer of transfers) { | |
| 7374 | + this._open().exec( | |
| 7375 | + `UPDATE ${__QUEUE_MESSAGES} | |
| 7376 | + SET dlq_target = ?, dlq_transfer_id = ?, transfer_kind = 'redrive', | |
| 7377 | + lease_id = NULL, leased_until = NULL | |
| 7378 | + WHERE seq = ? AND dead_letter_source = ? AND dlq_target IS NULL | |
| 7379 | + AND purge_on_settle = 0 | |
| 7380 | + AND (lease_id IS NULL OR leased_until <= ?)`, | |
| 7381 | + transfer.dead_letter_source, | |
| 7382 | + transfer.transferId, | |
| 7383 | + transfer.seq, | |
| 7384 | + transfer.dead_letter_source, | |
| 7385 | + now, | |
| 7386 | + ); | |
| 7387 | + } | |
| 7388 | + }); | |
| 7389 | + // Arm before the cross-cell call. If the process stops after the durable | |
| 7390 | + // mark, the alarm replays the same transfer identity. | |
| 7391 | + await this._rearm(now); | |
| 7392 | + await this._driveDlq(100); | |
| 7393 | + await this._rearm(); | |
| 7394 | + return { redriven: transfers.length, metrics: this._metrics() }; | |
| 7395 | + } | |
| 7396 | + | |
| 7397 | + async fetch(request) { | |
| 7398 | + const path = new URL(request.url).pathname; | |
| 7399 | + if (request.method !== "POST") { | |
| 7400 | + return new Response("Queue route not found", { status: 404 }); | |
| 7401 | + } | |
| 7402 | + let body; | |
| 7403 | + try { | |
| 7404 | + body = await request.json(); | |
| 7405 | + } catch { | |
| 7406 | + return new Response("invalid Queue request", { status: 400 }); | |
| 7407 | + } | |
| 7408 | + try { | |
| 7409 | + if (path === "/__qSettle") { | |
| 7410 | + return await this._settle(body) | |
| 7411 | + ? new Response(null, { status: 204 }) | |
| 7412 | + : new Response("stale Queue settlement", { status: 409 }); | |
| 7413 | + } | |
| 7414 | + if (body.op === "info") { | |
| 7415 | + const metrics = this._metrics(); | |
| 7416 | + const stored = this._open().exec( | |
| 7417 | + `SELECT stored_count FROM ${__QUEUE_STATS} WHERE id = 1`, | |
| 7418 | + ).toArray()[0].stored_count; | |
| 7419 | + return Response.json({ result: { ...metrics, stored, paused: this._paused() } }); | |
| 7420 | + } | |
| 7421 | + if (body.op === "purge") { | |
| 7422 | + return Response.json({ result: await this._purge() }); | |
| 7423 | + } | |
| 7424 | + if (body.op === "pause") { | |
| 7425 | + return Response.json({ result: await this._setPaused(true) }); | |
| 7426 | + } | |
| 7427 | + if (body.op === "resume") { | |
| 7428 | + return Response.json({ result: await this._setPaused(false) }); | |
| 7429 | + } | |
| 7430 | + if (body.op === "peek") { | |
| 7431 | + return Response.json({ | |
| 7432 | + result: this._peek(this._operatorLimit(body.limit, 10)), | |
| 7433 | + }); | |
| 7434 | + } | |
| 7435 | + if (body.op === "redrive") { | |
| 7436 | + return Response.json({ | |
| 7437 | + result: await this._redrive(this._operatorLimit(body.limit, 100)), | |
| 7438 | + }); | |
| 7439 | + } | |
| 7440 | + return Response.json( | |
| 7441 | + { error: `QUEUE_ERROR: unknown operation ${JSON.stringify(body.op)}` }, | |
| 7442 | + { status: 400 }, | |
| 7443 | + ); | |
| 7444 | + } catch (error) { | |
| 7445 | + return Response.json( | |
| 7446 | + { error: String(error?.message ?? error) }, | |
| 7447 | + { status: 400 }, | |
| 7448 | + ); | |
| 7449 | + } | |
| 7450 | + } | |
| 7451 | +} | |
| 7452 | + | |
| 7453 | +__runtimeClass("__Queue", __QueueCell); | |
| 7454 | + | |
| 7455 | +class Queue { | |
| 7456 | + constructor(queue, cellName, deliveryDelay) { | |
| 7457 | + Object.defineProperties(this, { | |
| 7458 | + _queue: { value: queue }, | |
| 7459 | + _cellName: { value: cellName }, | |
| 7460 | + _deliveryDelay: { value: deliveryDelay }, | |
| 7461 | + }); | |
| 7462 | + } | |
| 7463 | + | |
| 7464 | + get _stub() { | |
| 7465 | + return __cell.makeNamespace("__Queue").getByName(this._cellName); | |
| 7466 | + } | |
| 7467 | + | |
| 7468 | + async _send(entries) { | |
| 7469 | + const metrics = await this._stub.__queueSend({ entries }); | |
| 7470 | + return { metadata: { metrics: __queueMetricsView(metrics) } }; | |
| 7471 | + } | |
| 7472 | + | |
| 7473 | + send(body, options = {}) { | |
| 7474 | + const encoded = __queueEncode(body, options.contentType); | |
| 7475 | + return this._send([{ | |
| 7476 | + ...encoded, | |
| 7477 | + delaySeconds: __queueDelay(options.delaySeconds, this._deliveryDelay), | |
| 7478 | + }]); | |
| 7479 | + } | |
| 7480 | + | |
| 7481 | + sendBatch(messages, options = {}) { | |
| 7482 | + if (messages === null || messages === undefined || | |
| 7483 | + typeof messages[Symbol.iterator] !== "function") { | |
| 7484 | + throw __queueError("sendBatch() needs an iterable of messages"); | |
| 7485 | + } | |
| 7486 | + const entries = []; | |
| 7487 | + let bytes = 0; | |
| 7488 | + const batchDelay = __queueDelay(options.delaySeconds, this._deliveryDelay); | |
| 7489 | + for (const message of messages) { | |
| 7490 | + if (entries.length >= __queueLimits().maxBatchMessages) { | |
| 7491 | + throw __queueError( | |
| 7492 | + `a batch has at most ${__queueLimits().maxBatchMessages} messages`, | |
| 7493 | + ); | |
| 7494 | + } | |
| 7495 | + if (message === null || typeof message !== "object" || !("body" in message)) { | |
| 7496 | + throw __queueError("each batch entry needs a body"); | |
| 7497 | + } | |
| 7498 | + const encoded = __queueEncode(message.body, message.contentType); | |
| 7499 | + bytes += encoded.size; | |
| 7500 | + if (bytes > __queueLimits().maxBatchBytes) { | |
| 7501 | + throw __queueError( | |
| 7502 | + `a batch is at most ${__queueLimits().maxBatchBytes} bytes, got ${bytes}`, | |
| 7503 | + ); | |
| 7504 | + } | |
| 7505 | + entries.push({ | |
| 7506 | + ...encoded, | |
| 7507 | + delaySeconds: __queueDelay(message.delaySeconds, batchDelay), | |
| 7508 | + }); | |
| 7509 | + } | |
| 7510 | + if (entries.length === 0) { | |
| 7511 | + throw __queueError("sendBatch() needs at least one message"); | |
| 7512 | + } | |
| 7513 | + return this._send(entries); | |
| 7514 | + } | |
| 7515 | + | |
| 7516 | + async metrics() { | |
| 7517 | + return __queueMetricsView(await this._stub.__queueMetrics()); | |
| 7518 | + } | |
| 7519 | +} | |
| 7520 | + | |
| 7521 | +__celld.__makeQueue = (queue, cellName, deliveryDelay) => | |
| 7522 | + new Queue(queue, cellName, deliveryDelay); | |
| 7523 | + | |
| 7524 | +// ---- D1 ----------------------------------------------------------------- | |
| 7525 | +// A D1 database is a cell of a runtime-supplied Durable Object class, so it | |
| 7526 | +// inherits ownership, fencing, LTX replication, RPO=0 acknowledgement and | |
| 7527 | +// pressure shedding from the cell it already is. This half is the server; | |
| 7528 | +// `__makeD1Database` below is the client the binding hands to a Worker. | |
| 7529 | +// | |
| 7530 | +// Everything SQL goes through the one `__d1_run` op. The engine owns the | |
| 7531 | +// statement walk, the row and byte caps, and the meta snapshot, all inside | |
| 7532 | +// one execution -- the previous shape assembled these from the general | |
| 7533 | +// SqlStorage ops, and every seam between them was a contract only convention | |
| 7534 | +// enforced. | |
| 7535 | + | |
| 7536 | +// The error families applications match on. A message that already carries | |
| 7537 | +// one must pass through unwrapped: wrapping again would bury the family the | |
| 7538 | +// application is matching under a second D1_ERROR prefix. | |
| 7539 | +const __d1IsFamilyError = (message) => | |
| 7540 | + /^D1_([A-Z]+_)*(ERROR|NOTFOUND): /.test(String(message)); | |
| 7541 | + | |
| 7542 | +const __d1Error = (message, cause) => { | |
| 7543 | + const error = new Error("D1_ERROR: " + String(message)); | |
| 7544 | + error.cause = cause !== undefined ? cause : new Error(String(message)); | |
| 7545 | + return error; | |
| 7546 | +}; | |
| 7547 | + | |
| 7548 | +// A typed refusal from the engine: `{family, message}` becomes the Error the | |
| 7549 | +// application sees, with `.cause` carrying the bare message as upstream does. | |
| 7550 | +const __d1Failure = (failure) => { | |
| 7551 | + const error = new Error(failure.family + ": " + failure.message); | |
| 7552 | + error.cause = new Error(failure.message); | |
| 7553 | + return error; | |
| 7554 | +}; | |
| 7555 | + | |
| 7556 | +const __d1Run = (scope, request) => { | |
| 7557 | + const response = JSON.parse(__d1_run(scope, JSON.stringify(request))); | |
| 7558 | + if (response.error) throw __d1Failure(response.error); | |
| 7559 | + return response.ok; | |
| 7560 | +}; | |
| 7561 | + | |
| 7562 | +class __D1DatabaseCell { | |
| 7563 | + constructor(ctx) { | |
| 7564 | + this.ctx = ctx; | |
| 7565 | + } | |
| 7566 | + // Takes an array so that `batch()` can ride this same method, and the | |
| 7567 | + // same turn, when it lands. | |
| 7568 | + __d1Query(statements) { | |
| 7569 | + const scope = this.ctx.storage.sql._scope; | |
| 7570 | + return statements.map((statement) => | |
| 7571 | + __d1Run(scope, { | |
| 7572 | + mode: "prepared", | |
| 7573 | + sql: String(statement.sql), | |
| 7574 | + params: statement.params || [], | |
| 7575 | + first: !!statement.first, | |
| 7576 | + }) | |
| 7577 | + ); | |
| 7578 | + } | |
| 7579 | + __d1Batch(statements) { | |
| 7580 | + return __d1Run(this.ctx.storage.sql._scope, { | |
| 7581 | + mode: "batch", | |
| 7582 | + statements: statements.map((statement) => ({ | |
| 7583 | + sql: String(statement.sql), | |
| 7584 | + params: statement.params || [], | |
| 7585 | + })), | |
| 7586 | + }); | |
| 7587 | + } | |
| 7588 | + // The CLI's way in. `celld d1` signs each request with the fleet secret | |
| 7589 | + // and sends it to a live node's `/runtime/<scope>` route, which verifies the | |
| 7590 | + // signature and then forwards to the owner over the same dispatch `/do/` | |
| 7591 | + // uses -- so the CLI needs no ownership logic and the database is reached | |
| 7592 | + // the way a Worker reaches it. The unauthenticated `/do/` route refuses a | |
| 7593 | + // D1 scope outright: this cell answers arbitrary SQL, and its scope is an | |
| 7594 | + // HMAC over names that sit in the project's config, so the scope itself | |
| 7595 | + // is no secret. | |
| 7596 | + async fetch(request) { | |
| 7597 | + let body; | |
| 7598 | + try { | |
| 7599 | + body = await request.json(); | |
| 7600 | + } catch { | |
| 7601 | + return Response.json({ error: "D1_ERROR: invalid request body" }, { status: 400 }); | |
| 7602 | + } | |
| 7603 | + try { | |
| 7604 | + let result; | |
| 7605 | + if (body.migrate !== undefined) { | |
| 7606 | + result = this.__d1Migrate( | |
| 7607 | + String(body.migrate.name), | |
| 7608 | + String(body.migrate.sql), | |
| 7609 | + String(body.migrate.table || "d1_migrations"), | |
| 7610 | + ); | |
| 7611 | + } else if (body.exec !== undefined) { | |
| 7612 | + // The CLI asks for rows; the Worker binding's exec() never does. | |
| 7613 | + result = __d1Run(this.ctx.storage.sql._scope, { | |
| 7614 | + mode: "exec", | |
| 7615 | + sql: String(body.exec.sql), | |
| 7616 | + rows: !!body.exec.rows, | |
| 7617 | + }); | |
| 7618 | + } else { | |
| 7619 | + result = this.__d1Query(body.statements || []); | |
| 7620 | + } | |
| 7621 | + return Response.json({ result }); | |
| 7622 | + } catch (error) { | |
| 7623 | + return Response.json({ error: String(error && error.message || error) }, { status: 400 }); | |
| 7624 | + } | |
| 7625 | + } | |
| 7626 | + __d1Exec(source) { | |
| 7627 | + const result = __d1Run(this.ctx.storage.sql._scope, { | |
| 7628 | + mode: "exec", | |
| 7629 | + sql: String(source), | |
| 7630 | + rows: false, | |
| 7631 | + }); | |
| 7632 | + return { count: result.count, duration: result.duration }; | |
| 7633 | + } | |
| 7634 | + // Apply one migration and record it. The engine runs the file, the | |
| 7635 | + // bookkeeping insert (the name is a bound parameter, so a file name never | |
| 7636 | + // reaches SQL text) and the BEGIN IMMEDIATE .. COMMIT bracket in one | |
| 7637 | + // request, so a migration that fails part-way rolls back whole and the | |
| 7638 | + // operator fixes the file and re-runs. Without the transaction the | |
| 7639 | + // statements that DID land are exactly the ones a re-run trips over. | |
| 7640 | + __d1Migrate(name, source, table) { | |
| 7641 | + return __d1Run(this.ctx.storage.sql._scope, { | |
| 7642 | + mode: "migrate", | |
| 7643 | + name, | |
| 7644 | + sql: source, | |
| 7645 | + table, | |
| 7646 | + }); | |
| 7647 | + } | |
| 7648 | +} | |
| 7649 | + | |
| 7650 | +__runtimeClass("__D1Database", __D1DatabaseCell); | |
| 7651 | + | |
| 7652 | +// Validate and encode bind values once, at the public boundary, exactly as | |
| 7653 | +// upstream does (workerd d1-api.ts). Byte-shaped values become byte arrays -- | |
| 7654 | +// the wire format for a BLOB bind -- and anything unsupported throws | |
| 7655 | +// D1_TYPE_ERROR here, before any SQL runs. The first version deferred this | |
| 7656 | +// to a JSON round-trip whose fallthrough was SQL NULL, so a Uint8Array bind | |
| 7657 | +// stored NULL and nothing said so. | |
| 7658 | +const __d1BindValue = (value) => { | |
| 7659 | + const kind = typeof value; | |
| 7660 | + if (kind === "number") { | |
| 7661 | + // A non-finite number has no JSON form, so it crosses as null and | |
| 7662 | + // stores SQL NULL. Upstream does the same (bind(NaN) selects typeof | |
| 7663 | + // "null"); making it explicit here turns the conversion from an | |
| 7664 | + // accident of JSON.stringify into a pinned decision. | |
| 7665 | + return Number.isFinite(value) ? value : null; | |
| 7666 | + } | |
| 7667 | + if (kind === "string") return value; | |
| 7668 | + if (kind === "boolean") return value ? 1 : 0; | |
| 7669 | + if (kind === "object") { | |
| 7670 | + if (value === null) return value; | |
| 7671 | + if ( | |
| 7672 | + Array.isArray(value) && | |
| 7673 | + value.every((byte) => typeof byte === "number" && byte >= 0 && byte < 256) | |
| 7674 | + ) { | |
| 7675 | + return value; | |
| 7676 | + } | |
| 7677 | + if (value instanceof ArrayBuffer) { | |
| 7678 | + return Array.from(new Uint8Array(value)); | |
| 7679 | + } | |
| 7680 | + // A typed view binds its ELEMENT values, each truncated to a byte -- | |
| 7681 | + // Int8Array([-1]) stores 0xff, Float32Array([1.5]) stores 0x01 -- not | |
| 7682 | + // its underlying byte window, so Uint16Array([65, 66]) stores 2 bytes | |
| 7683 | + // and not 4. Upstream behaves this way (verified against workerd's D1; | |
| 7684 | + // the differential suite pins it), and the bare Array.from that | |
| 7685 | + // preceded this produced elements the engine then refused as bytes. | |
| 7686 | + if (ArrayBuffer.isView(value)) return Array.from(Uint8Array.from(value)); | |
| 7687 | + } | |
| 7688 | + const error = new Error( | |
| 7689 | + `D1_TYPE_ERROR: Type '${kind}' not supported for value '${value}'`, | |
| 7690 | + ); | |
| 7691 | + error.cause = new Error(`Type '${kind}' not supported for value '${value}'`); | |
| 7692 | + throw error; | |
| 7693 | +}; | |
| 7694 | + | |
| 7695 | +class D1PreparedStatement { | |
| 7696 | + constructor(database, sql, params) { | |
| 7697 | + Object.defineProperty(this, "_database", { value: database }); | |
| 7698 | + Object.defineProperty(this, "_sql", { value: sql }); | |
| 7699 | + Object.defineProperty(this, "_params", { value: params }); | |
| 7700 | + } | |
| 7701 | + bind(...values) { | |
| 7702 | + return new D1PreparedStatement( | |
| 7703 | + this._database, | |
| 7704 | + this._sql, | |
| 7705 | + values.map(__d1BindValue), | |
| 7706 | + ); | |
| 7707 | + } | |
| 7708 | + async _run(first) { | |
| 7709 | + const results = await this._database._query([ | |
| 7710 | + { sql: this._sql, params: this._params, first }, | |
| 7711 | + ]); | |
| 7712 | + return results[0]; | |
| 7713 | + } | |
| 7714 | + async all() { | |
| 7715 | + const result = await this._run(); | |
| 7716 | + return { | |
| 7717 | + success: true, | |
| 7718 | + meta: result.meta, | |
| 7719 | + results: result.rows.map((row) => __d1Shape(result.columns, row)), | |
| 7720 | + }; | |
| 7721 | + } | |
| 7722 | + async run() { | |
| 7723 | + return await this.all(); | |
| 7724 | + } | |
| 7725 | + async first(column) { | |
| 7726 | + // `first: true` keeps one row on the cell side, so only that row crosses | |
| 7727 | + // the isolate boundary and the row cap cannot fire for a first(). | |
| 7728 | + const result = await this._run(true); | |
| 7729 | + if (result.rows.length === 0) return null; | |
| 7730 | + const row = __d1Shape(result.columns, result.rows[0]); | |
| 7731 | + if (column === undefined) return row; | |
| 7732 | + // The check runs on the shaped object, as upstream's does, so a column | |
| 7733 | + // named like an Object.prototype member behaves the same here as there. | |
| 7734 | + if (row[column] === undefined) { | |
| 7735 | + const error = new Error( | |
| 7736 | + `D1_COLUMN_NOTFOUND: Column not found (${column})`, | |
| 7737 | + ); | |
| 7738 | + error.cause = new Error("Column not found"); | |
| 7739 | + throw error; | |
| 7740 | + } | |
| 7741 | + return row[column]; | |
| 7742 | + } | |
| 7743 | + async raw(options) { | |
| 7744 | + const result = await this._run(); | |
| 7745 | + return options && options.columnNames | |
| 7746 | + ? [result.columns, ...result.rows] | |
| 7747 | + : result.rows; | |
| 7748 | + } | |
| 7749 | +} | |
| 7750 | + | |
| 7751 | +// Object.fromEntries, not property assignment: assigning to a column named | |
| 7752 | +// `__proto__` would walk the prototype chain and silently drop the value, | |
| 7753 | +// while fromEntries defines an own property whatever the name. | |
| 7754 | +const __d1Shape = (columns, row) => | |
| 7755 | + Object.fromEntries(row.map((value, index) => [columns[index], value])); | |
| 7756 | + | |
| 7757 | +const __d1PublicResult = (result) => ({ | |
| 7758 | + success: true, | |
| 7759 | + meta: result.meta, | |
| 7760 | + results: result.rows.map((row) => __d1Shape(result.columns, row)), | |
| 7761 | +}); | |
| 7762 | + | |
| 7763 | +// celld has one primary and no replicas, so every completed query satisfies | |
| 7764 | +// every earlier session constraint. One stable opaque token states that fact | |
| 7765 | +// without pretending an isolate-local counter is a durable database position. | |
| 7766 | +const __d1PrimaryBookmark = "celld:primary"; | |
| 7767 | + | |
| 7768 | +class D1DatabaseSession { | |
| 7769 | + constructor(database, constraintOrBookmark) { | |
| 7770 | + Object.defineProperty(this, "_database", { value: database }); | |
| 7771 | + const value = constraintOrBookmark == null | |
| 7772 | + ? "first-unconstrained" | |
| 7773 | + : String(constraintOrBookmark).trim(); | |
| 7774 | + if (!value) { | |
| 7775 | + throw new Error("D1_SESSION_ERROR: invalid bookmark or constraint"); | |
| 7776 | + } | |
| 7777 | + Object.defineProperty(this, "_bookmark", { | |
| 7778 | + value: value === "first-primary" || value === "first-unconstrained" ? null : value, | |
| 7779 | + writable: true, | |
| 7780 | + }); | |
| 7781 | + } | |
| 7782 | + _advanceBookmark() { | |
| 7783 | + this._bookmark = __d1PrimaryBookmark; | |
| 7784 | + } | |
| 7785 | + async _query(statements) { | |
| 7786 | + const results = await this._database._query(statements); | |
| 7787 | + this._advanceBookmark(); | |
| 7788 | + return results; | |
| 7789 | + } | |
| 7790 | + prepare(sql) { | |
| 7791 | + return new D1PreparedStatement(this, String(sql), []); | |
| 7792 | + } | |
| 7793 | + async batch(statements) { | |
| 7794 | + const results = await this._database._batch(statements); | |
| 7795 | + this._advanceBookmark(); | |
| 7796 | + return results; | |
| 7797 | + } | |
| 7798 | + getBookmark() { | |
| 7799 | + return this._bookmark; | |
| 7800 | + } | |
| 7801 | +} | |
| 7802 | + | |
| 7803 | +// Named so SDKs that sniff a binding by `constructor.name` recognise it. | |
| 7804 | +class D1Database { | |
| 7805 | + constructor(databaseName) { | |
| 7806 | + Object.defineProperty(this, "_databaseName", { value: databaseName }); | |
| 7807 | + } | |
| 7808 | + // Resolved per call rather than cached: a cell can move between calls, and | |
| 7809 | + // `getByName` is the same cost the Durable Object path already pays. | |
| 7810 | + get _stub() { | |
| 7811 | + return __cell.makeNamespace("__D1Database").getByName(this._databaseName); | |
| 7812 | + } | |
| 7813 | + async _query(statements) { | |
| 7814 | + try { | |
| 7815 | + return await this._stub.__d1Query(statements); | |
| 7816 | + } catch (error) { | |
| 7817 | + if (__d1IsFamilyError(error && error.message)) throw error; | |
| 7818 | + throw __d1Error(String(error && error.message || error), error); | |
| 7819 | + } | |
| 7820 | + } | |
| 7821 | + async _batch(statements) { | |
| 7822 | + try { | |
| 7823 | + const encoded = statements.map((statement) => ({ | |
| 7824 | + sql: statement._sql, | |
| 7825 | + params: statement._params, | |
| 7826 | + })); | |
| 7827 | + const results = await this._stub.__d1Batch(encoded); | |
| 7828 | + return results.map(__d1PublicResult); | |
| 7829 | + } catch (error) { | |
| 7830 | + if (__d1IsFamilyError(error && error.message)) throw error; | |
| 7831 | + throw __d1Error(String(error && error.message || error), error); | |
| 7832 | + } | |
| 7833 | + } | |
| 7834 | + prepare(sql) { | |
| 7835 | + return new D1PreparedStatement(this, String(sql), []); | |
| 7836 | + } | |
| 7837 | + async exec(sql) { | |
| 7838 | + try { | |
| 7839 | + return await this._stub.__d1Exec(String(sql)); | |
| 7840 | + } catch (error) { | |
| 7841 | + if (__d1IsFamilyError(error && error.message)) throw error; | |
| 7842 | + throw __d1Error(String(error && error.message || error), error); | |
| 7843 | + } | |
| 7844 | + } | |
| 7845 | + async batch(statements) { | |
| 7846 | + return await this._batch(statements); | |
| 7847 | + } | |
| 7848 | + withSession(constraintOrBookmark) { | |
| 7849 | + return new D1DatabaseSession(this, constraintOrBookmark); | |
| 7850 | + } | |
| 7851 | + async dump() { | |
| 7852 | + throw __d1Error( | |
| 7853 | + "dump() is not implemented in celld; the database is a SQLite file in " + | |
| 7854 | + "your own bucket", | |
| 7855 | + ); | |
| 7856 | + } | |
| 7857 | +} | |
| 7858 | + | |
| 7859 | +const __makeD1Database = __celld.__makeD1Database = | |
| 7860 | + (databaseName) => new D1Database(databaseName); | |
| 7861 | +// ---- Workflows ---------------------------------------------------------- | |
| 7862 | +// A workflow instance is one cell of the runtime-supplied `__Workflow` class, | |
| 7863 | +// named `<workflow_name>/<instance_id>` through getByName, so it inherits | |
| 7864 | +// ownership, fencing, LTX replication and the output gate from the cell it | |
| 7865 | +// already is. Execution is replay: `run()` re-executes from the top on every | |
| 7866 | +// resume and only steps are memoized, in `ctx.storage` KV under `__wf.*`. | |
| 7867 | +// This half is the server; `__makeWorkflow` below is the client the binding | |
| 7868 | +// hands to a Worker. The public contract is in docs/cloudflare-compat.md. | |
| 7869 | + | |
| 7870 | +// Upstream's limit for a step return, an event payload, and the params. The | |
| 7871 | +// error is distinct and names the step, because "too large" and "the isolate | |
| 7872 | +// died" must not read the same (the D1 row-cap precedent). | |
| 7873 | +const __WF_VALUE_CAP = 1 << 20; | |
| 7874 | +// Workflow names, instance ids, and event types all share this charset. | |
| 7875 | +// `/` is outside it, which is what makes the `<name>/<id>` cell-name join | |
| 7876 | +// unambiguous. | |
| 7877 | +const __WF_NAME_RE = /^[a-zA-Z0-9_][a-zA-Z0-9-_]*$/; | |
| 7878 | +const __wfError = (message) => new Error("WORKFLOW_ERROR: " + message); | |
| 7879 | +// The suspension primitive: a blocked step returns a promise that never | |
| 7880 | +// settles in this invocation, so user code simply stops progressing. A | |
| 7881 | +// sentinel thrown through user code was rejected because `Promise.all` in | |
| 7882 | +// `run()` would observe it as a rejection and user try/catch would eat it. | |
| 7883 | +const __wfNever = new Promise(() => {}); | |
| 7884 | +const __wfTerminal = (status) => | |
| 7885 | + status === "complete" || status === "errored" || status === "terminated"; | |
| 7886 | +// Upstream's hard bounds: 10,000 retries per step, 365 days for any sleep or | |
| 7887 | +// event wait, one second under a waitForEvent timeout. Enforced loudly at the | |
| 7888 | +// call site -- a config outside them would otherwise misbehave only after | |
| 7889 | +// the instance is minutes or days into its run. | |
| 7890 | +const __WF_RETRY_LIMIT_CAP = 10000; | |
| 7891 | +const __WF_STEP_NAME_LIMIT = 256; | |
| 7892 | +const __WF_MAX_WAIT_MS = 365 * 86400000; | |
| 7893 | +const __WF_MIN_EVENT_TIMEOUT_MS = 1000; | |
| 7894 | +// celld has no account plans, so it exposes the larger published retention | |
| 7895 | +// ceiling as one stable application limit. Both an omitted policy and an | |
| 7896 | +// omitted member of a partial policy use this value. | |
| 7897 | +const __WF_RETENTION_MAX_MS = 30 * 86400000; | |
| 7898 | +const __WF_LOCATION_HINTS = new Set([ | |
| 7899 | + "wnam", "enam", "sam", "weur", "eeur", "apac", "apac-ne", "apac-se", | |
| 7900 | + "oc", "afr", "me", | |
| 7901 | +]); | |
| 7902 | +// How long run() can stay pending on non-step work while no step runs and | |
| 7903 | +// none is blocked before the instance fails. Upstream permits un-stepped | |
| 7904 | +// awaits between steps (they are merely non-durable), so erroring at the | |
| 7905 | +// first quiescent macrotask would kill any run() whose external await | |
| 7906 | +// outlives one turn of the loop. Sixty seconds is long enough for any | |
| 7907 | +// sane un-stepped await and short enough that a truly never-settling | |
| 7908 | +// promise fails the instance instead of wedging the alarm handler. | |
| 7909 | +const __WF_STALL_GRACE_MS = 60000; | |
| 7910 | +const __WF_UNITS = { | |
| 7911 | + second: 1000, | |
| 7912 | + minute: 60000, | |
| 7913 | + hour: 3600000, | |
| 7914 | + day: 86400000, | |
| 7915 | + week: 604800000, | |
| 7916 | + // Upstream does not document its month/year arithmetic; fixed 30/365-day | |
| 7917 | + // units are used so one expression cannot mean two durations depending on | |
| 7918 | + // when it runs. | |
| 7919 | + month: 30 * 86400000, | |
| 7920 | + year: 365 * 86400000, | |
| 7921 | +}; | |
| 7922 | +const __wfDuration = (value, what) => { | |
| 7923 | + if (typeof value === "number" && Number.isFinite(value) && value >= 0) return value; | |
| 7924 | + if (typeof value !== "string") { | |
| 7925 | + throw __wfError( | |
| 7926 | + `invalid duration for ${what}: ${JSON.stringify(value)}; use milliseconds ` + | |
| 7927 | + 'or "<n> <second|minute|hour|day|week|month|year>[s]"', | |
| 7928 | + ); | |
| 7929 | + } | |
| 7930 | + const match = /^\s*(\d+(?:\.\d+)?)\s+(second|minute|hour|day|week|month|year)s?\s*$/ | |
| 7931 | + .exec(value); | |
| 7932 | + if (!match) { | |
| 7933 | + throw __wfError( | |
| 7934 | + `invalid duration for ${what}: ${JSON.stringify(value)}; use milliseconds ` + | |
| 7935 | + 'or "<n> <second|minute|hour|day|week|month|year>[s]"', | |
| 7936 | + ); | |
| 7937 | + } | |
| 7938 | + return Number(match[1]) * __WF_UNITS[match[2]]; | |
| 7939 | +}; | |
| 7940 | +const __wfRetentionDuration = (value, what) => { | |
| 7941 | + const durationMs = __wfDuration(value, what); | |
| 7942 | + if (durationMs > __WF_RETENTION_MAX_MS) { | |
| 7943 | + throw __wfError( | |
| 7944 | + `${what} is ${durationMs} ms, above celld's 30-day retention limit`, | |
| 7945 | + ); | |
| 7946 | + } | |
| 7947 | + return durationMs; | |
| 7948 | +}; | |
| 7949 | +const __wfOwnObject = (value) => | |
| 7950 | + value !== null && typeof value === "object" && !Array.isArray(value); | |
| 7951 | +const __wfUnknownKey = (value, allowed) => | |
| 7952 | + Object.keys(value).find((key) => !allowed.includes(key)); | |
| 7953 | +const __wfStepName = (name) => { | |
| 7954 | + // The pinned workers-sdk validator has no minimum length. An empty name is | |
| 7955 | + // therefore valid, although rejecting it looks safer at first glance. A | |
| 7956 | + // non-empty check made celld reject Worker code that the upstream runtime | |
| 7957 | + // accepts, so keep only the upstream length and control-character bounds. | |
| 7958 | + if ( | |
| 7959 | + typeof name !== "string" || name.length > __WF_STEP_NAME_LIMIT || | |
| 7960 | + /[\x00-\x1f]/.test(name) | |
| 7961 | + ) { | |
| 7962 | + throw __wfError( | |
| 7963 | + `invalid step name ${JSON.stringify(name)}: use at most ` + | |
| 7964 | + `${__WF_STEP_NAME_LIMIT} characters and no control characters`, | |
| 7965 | + ); | |
| 7966 | + } | |
| 7967 | +}; | |
| 7968 | +const __wfEventType = (type) => { | |
| 7969 | + if (typeof type !== "string" || type.length > 100 || !__WF_NAME_RE.test(type)) { | |
| 7970 | + throw __wfError( | |
| 7971 | + `invalid event type ${JSON.stringify(type)}: use at most 100 letters, ` + | |
| 7972 | + "digits, hyphens, or underscores", | |
| 7973 | + ); | |
| 7974 | + } | |
| 7975 | +}; | |
| 7976 | +const __wfSleepDuration = (duration, name) => { | |
| 7977 | + const durationMs = __wfDuration( | |
| 7978 | + duration, | |
| 7979 | + `the duration of sleep ${JSON.stringify(name)}`, | |
| 7980 | + ); | |
| 7981 | + if (durationMs > __WF_MAX_WAIT_MS) { | |
| 7982 | + throw __wfError( | |
| 7983 | + `sleep ${JSON.stringify(name)} is ${durationMs} ms, above the upstream ` + | |
| 7984 | + "limit of 365 days", | |
| 7985 | + ); | |
| 7986 | + } | |
| 7987 | + return durationMs; | |
| 7988 | +}; | |
| 7989 | +const __wfSleepUntil = (timestamp, name) => { | |
| 7990 | + const at = timestamp instanceof Date ? timestamp.getTime() : timestamp; | |
| 7991 | + if (typeof at !== "number" || !Number.isFinite(at)) { | |
| 7992 | + throw __wfError( | |
| 7993 | + `invalid sleepUntil timestamp for ${JSON.stringify(name)}: use a Date ` + | |
| 7994 | + "or a UNIX timestamp in milliseconds", | |
| 7995 | + ); | |
| 7996 | + } | |
| 7997 | + const delay = at - Date.now(); | |
| 7998 | + if (delay > __WF_MAX_WAIT_MS) { | |
| 7999 | + throw __wfError( | |
| 8000 | + `sleepUntil ${JSON.stringify(name)} is ${delay} ms away, above the ` + | |
| 8001 | + "upstream limit of 365 days", | |
| 8002 | + ); | |
| 8003 | + } | |
| 8004 | + return at; | |
| 8005 | +}; | |
| 8006 | +const __wfWaitOptions = (options, name) => { | |
| 8007 | + if (!__wfOwnObject(options)) { | |
| 8008 | + throw __wfError(`invalid waitForEvent options for ${JSON.stringify(name)}`); | |
| 8009 | + } | |
| 8010 | + __wfEventType(options.type); | |
| 8011 | + const timeout = options.timeout ?? "24 hours"; | |
| 8012 | + const timeoutMs = __wfDuration( | |
| 8013 | + timeout, | |
| 8014 | + `the timeout of waitForEvent ${JSON.stringify(name)}`, | |
| 8015 | + ); | |
| 8016 | + if (timeoutMs < __WF_MIN_EVENT_TIMEOUT_MS || timeoutMs > __WF_MAX_WAIT_MS) { | |
| 8017 | + throw __wfError( | |
| 8018 | + `the timeout of waitForEvent ${JSON.stringify(name)} is ${timeoutMs} ms; ` + | |
| 8019 | + "upstream allows 1 second to 365 days", | |
| 8020 | + ); | |
| 8021 | + } | |
| 8022 | + return { type: options.type, timeout, timeoutMs }; | |
| 8023 | +}; | |
| 8024 | +const __wfEventOptions = (options) => { | |
| 8025 | + if (!__wfOwnObject(options)) { | |
| 8026 | + throw __wfError("sendEvent() needs an event object"); | |
| 8027 | + } | |
| 8028 | + __wfEventType(options.type); | |
| 8029 | + if (options.payload !== undefined) __wfCheckValue(options.payload, "the event payload"); | |
| 8030 | + return { type: options.type, payload: options.payload }; | |
| 8031 | +}; | |
| 8032 | +const __wfRetentionOptions = (retention, what) => { | |
| 8033 | + if (retention === undefined) { | |
| 8034 | + return { | |
| 8035 | + successMs: __WF_RETENTION_MAX_MS, | |
| 8036 | + errorMs: __WF_RETENTION_MAX_MS, | |
| 8037 | + }; | |
| 8038 | + } | |
| 8039 | + if (!__wfOwnObject(retention)) { | |
| 8040 | + throw __wfError(`${what} option retention must be an object`); | |
| 8041 | + } | |
| 8042 | + const unknown = __wfUnknownKey(retention, ["successRetention", "errorRetention"]); | |
| 8043 | + if (unknown !== undefined) { | |
| 8044 | + throw __wfError( | |
| 8045 | + `${what} option retention has an unknown field ${JSON.stringify(unknown)}`, | |
| 8046 | + ); | |
| 8047 | + } | |
| 8048 | + return { | |
| 8049 | + successMs: retention.successRetention === undefined | |
| 8050 | + ? __WF_RETENTION_MAX_MS | |
| 8051 | + : __wfRetentionDuration( | |
| 8052 | + retention.successRetention, | |
| 8053 | + `${what} successRetention`, | |
| 8054 | + ), | |
| 8055 | + errorMs: retention.errorRetention === undefined | |
| 8056 | + ? __WF_RETENTION_MAX_MS | |
| 8057 | + : __wfRetentionDuration(retention.errorRetention, `${what} errorRetention`), | |
| 8058 | + }; | |
| 8059 | +}; | |
| 8060 | +const __wfLocationHint = (hint, what) => { | |
| 8061 | + if (hint !== undefined && !__WF_LOCATION_HINTS.has(hint)) { | |
| 8062 | + throw __wfError( | |
| 8063 | + `${what} has invalid locationHint ${JSON.stringify(hint)}`, | |
| 8064 | + ); | |
| 8065 | + } | |
| 8066 | + return hint; | |
| 8067 | +}; | |
| 8068 | +const __wfRestartOptions = (options) => { | |
| 8069 | + if (options === undefined) return {}; | |
| 8070 | + if (!__wfOwnObject(options)) { | |
| 8071 | + throw __wfError("restart() options must be an object"); | |
| 8072 | + } | |
| 8073 | + const unknown = __wfUnknownKey(options, ["from"]); | |
| 8074 | + if (unknown !== undefined) { | |
| 8075 | + throw __wfError(`restart() has an unknown option ${JSON.stringify(unknown)}`); | |
| 8076 | + } | |
| 8077 | + if (options.from === undefined) return {}; | |
| 8078 | + const from = options.from; | |
| 8079 | + if (!__wfOwnObject(from)) { | |
| 8080 | + throw __wfError("restart() option from must be an object"); | |
| 8081 | + } | |
| 8082 | + const fromUnknown = __wfUnknownKey(from, ["name", "count", "type"]); | |
| 8083 | + if (fromUnknown !== undefined) { | |
| 8084 | + throw __wfError( | |
| 8085 | + `restart() option from has an unknown field ${JSON.stringify(fromUnknown)}`, | |
| 8086 | + ); | |
| 8087 | + } | |
| 8088 | + __wfStepName(from.name); | |
| 8089 | + const count = from.count ?? 1; | |
| 8090 | + if (!Number.isInteger(count) || count < 1) { | |
| 8091 | + throw __wfError("restart() option from.count must be a positive integer"); | |
| 8092 | + } | |
| 8093 | + const type = from.type ?? "do"; | |
| 8094 | + if (!["do", "sleep", "waitForEvent"].includes(type)) { | |
| 8095 | + throw __wfError( | |
| 8096 | + 'restart() option from.type must be "do", "sleep", or "waitForEvent"', | |
| 8097 | + ); | |
| 8098 | + } | |
| 8099 | + return { from: { name: from.name, count, type } }; | |
| 8100 | +}; | |
| 8101 | +const __wfStepConfig = (config, name) => { | |
| 8102 | + if (!__wfOwnObject(config)) { | |
| 8103 | + throw __wfError(`invalid config for step ${JSON.stringify(name)}: use an object`); | |
| 8104 | + } | |
| 8105 | + let unknown = __wfUnknownKey(config, ["retries", "timeout", "sensitive"]); | |
| 8106 | + if (unknown !== undefined) { | |
| 8107 | + throw __wfError( | |
| 8108 | + `invalid config for step ${JSON.stringify(name)}: unknown option ` + | |
| 8109 | + JSON.stringify(unknown), | |
| 8110 | + ); | |
| 8111 | + } | |
| 8112 | + const retries = config.retries; | |
| 8113 | + if (retries !== undefined) { | |
| 8114 | + if (!__wfOwnObject(retries)) { | |
| 8115 | + throw __wfError(`invalid retries config for step ${JSON.stringify(name)}`); | |
| 8116 | + } | |
| 8117 | + unknown = __wfUnknownKey(retries, ["limit", "delay", "backoff"]); | |
| 8118 | + if (unknown !== undefined) { | |
| 8119 | + throw __wfError( | |
| 8120 | + `invalid retries config for step ${JSON.stringify(name)}: unknown option ` + | |
| 8121 | + JSON.stringify(unknown), | |
| 8122 | + ); | |
| 8123 | + } | |
| 8124 | + if ( | |
| 8125 | + typeof retries.limit !== "number" || !Number.isFinite(retries.limit) || | |
| 8126 | + retries.limit < 0 | |
| 8127 | + ) { | |
| 8128 | + throw __wfError( | |
| 8129 | + `invalid retries config for step ${JSON.stringify(name)}: ` + | |
| 8130 | + "limit must be a non-negative number", | |
| 8131 | + ); | |
| 8132 | + } | |
| 8133 | + if (retries.limit > __WF_RETRY_LIMIT_CAP) { | |
| 8134 | + throw __wfError( | |
| 8135 | + `invalid retries config for step ${JSON.stringify(name)}: limit is above ` + | |
| 8136 | + String(__WF_RETRY_LIMIT_CAP), | |
| 8137 | + ); | |
| 8138 | + } | |
| 8139 | + if (typeof retries.delay !== "function") { | |
| 8140 | + __wfDuration(retries.delay, `the retries config delay of step ${JSON.stringify(name)}`); | |
| 8141 | + } | |
| 8142 | + if ( | |
| 8143 | + retries.backoff !== undefined && | |
| 8144 | + !["constant", "linear", "exponential"].includes(retries.backoff) | |
| 8145 | + ) { | |
| 8146 | + throw __wfError( | |
| 8147 | + `invalid retries config for step ${JSON.stringify(name)}: ` + | |
| 8148 | + "backoff must be constant, linear, or exponential", | |
| 8149 | + ); | |
| 8150 | + } | |
| 8151 | + } | |
| 8152 | + if (config.timeout !== undefined) { | |
| 8153 | + const timeout = __wfDuration( | |
| 8154 | + config.timeout, | |
| 8155 | + `the config timeout of step ${JSON.stringify(name)}`, | |
| 8156 | + ); | |
| 8157 | + if (timeout === 0) { | |
| 8158 | + throw __wfError( | |
| 8159 | + `invalid config timeout for step ${JSON.stringify(name)}: use a value above zero`, | |
| 8160 | + ); | |
| 8161 | + } | |
| 8162 | + } | |
| 8163 | + if (config.sensitive !== undefined && config.sensitive !== "output") { | |
| 8164 | + throw __wfError( | |
| 8165 | + `invalid config sensitive value for step ${JSON.stringify(name)}: use "output"`, | |
| 8166 | + ); | |
| 8167 | + } | |
| 8168 | + return { | |
| 8169 | + ...config, | |
| 8170 | + ...(retries === undefined ? {} : { retries: { ...retries } }), | |
| 8171 | + }; | |
| 8172 | +}; | |
| 8173 | +// Serialization is checked with the same encoder storage and RPC use, so a | |
| 8174 | +// value that passes here cannot fail later at the isolate boundary. The | |
| 8175 | +// thrown errors are permanent: retrying cannot make a value cloneable or | |
| 8176 | +// shrink it. | |
| 8177 | +const __wfEncodeValue = (value, what) => { | |
| 8178 | + try { | |
| 8179 | + return __sc_encode(value); | |
| 8180 | + } catch (error) { | |
| 8181 | + const failure = __wfError( | |
| 8182 | + `${what} is not serializable: ${String(error && error.message || error)}. ` + | |
| 8183 | + "It must survive structured clone; a ReadableStream return is not implemented in celld.", | |
| 8184 | + ); | |
| 8185 | + failure.__wfPermanent = true; | |
| 8186 | + throw failure; | |
| 8187 | + } | |
| 8188 | +}; | |
| 8189 | +const __wfCheckEncodedValue = (bytes, what) => { | |
| 8190 | + if (bytes.byteLength > __WF_VALUE_CAP) { | |
| 8191 | + const failure = __wfError( | |
| 8192 | + `${what} is ${bytes.byteLength} bytes, above the 1 MiB limit; ` + | |
| 8193 | + "store large output externally and return a reference", | |
| 8194 | + ); | |
| 8195 | + failure.__wfPermanent = true; | |
| 8196 | + throw failure; | |
| 8197 | + } | |
| 8198 | +}; | |
| 8199 | +const __wfCheckValue = (value, what) => | |
| 8200 | + __wfCheckEncodedValue(__wfEncodeValue(value, what), what); | |
| 8201 | +const __wfErrorRecord = (error) => ({ | |
| 8202 | + name: String(error && error.name || "Error"), | |
| 8203 | + message: String(error && error.message || error), | |
| 8204 | +}); | |
| 8205 | +// A permanently failed step rejects on every replay, so user try/catch | |
| 8206 | +// around step.do keeps working after a resume, not only on the attempt that | |
| 8207 | +// failed live. | |
| 8208 | +const __wfReviveError = (record) => { | |
| 8209 | + const error = new Error(record.message); | |
| 8210 | + error.name = record.name; | |
| 8211 | + return error; | |
| 8212 | +}; | |
| 8213 | +const __wfLedgerPrefix = (generation) => `__wf.${generation}.`; | |
| 8214 | +const __wfEventPrefix = (generation) => | |
| 8215 | + __wfLedgerPrefix(generation) + "event."; | |
| 8216 | +const __wfEventKey = (generation, sequence) => | |
| 8217 | + __wfEventPrefix(generation) + String(sequence).padStart(9, "0"); | |
| 8218 | +const __wfRetentionMs = (meta, status) => | |
| 8219 | + status === "complete" | |
| 8220 | + ? (meta.retention?.successMs ?? __WF_RETENTION_MAX_MS) | |
| 8221 | + : (meta.retention?.errorMs ?? __WF_RETENTION_MAX_MS); | |
| 8222 | +const __wfFinishRetention = (meta, transaction) => { | |
| 8223 | + meta.endedMs = Date.now(); | |
| 8224 | + meta.expiresMs = meta.endedMs + __wfRetentionMs(meta, meta.status); | |
| 8225 | + transaction.setAlarm(meta.expiresMs); | |
| 8226 | +}; | |
| 8227 | +// A ledger record replays only through the kind of call that wrote it. A | |
| 8228 | +// `do` renamed into a `sleep`, or two calls reordered under one name, would | |
| 8229 | +// otherwise read fields the other kind never wrote and continue on | |
| 8230 | +// undefined -- a deadline of NaN, a value of nothing -- instead of failing. | |
| 8231 | +const __wfKindCheck = (record, kind, name) => { | |
| 8232 | + if (record === undefined || record.kind === kind) return record; | |
| 8233 | + const failure = __wfError( | |
| 8234 | + `step ${JSON.stringify(name)} replays as ${kind} but its ledger record ` + | |
| 8235 | + `was written by ${record.kind}; a step keeps one kind across replays`, | |
| 8236 | + ); | |
| 8237 | + failure.__wfPermanent = true; | |
| 8238 | + throw failure; | |
| 8239 | +}; | |
| 8240 | +// Each step callback runs under an async-context frame naming its step (the | |
| 8241 | +// same CPED-backed frame __ctxRun uses, so it survives the callback's | |
| 8242 | +// awaits). A step started inside another step's callback would wedge | |
| 8243 | +// quiescence: the outer callback cannot settle while it awaits the blocked | |
| 8244 | +// inner step, so `running` never reaches zero and the instance can neither | |
| 8245 | +// suspend nor finish. The frame is what lets the inner call refuse loudly | |
| 8246 | +// at the nesting site instead. | |
| 8247 | +const __wfStepKey = Symbol("celld.wfStep"); | |
| 8248 | +const __wfEnclosingStep = () => { | |
| 8249 | + const frame = __als_get(); | |
| 8250 | + return frame === undefined ? undefined : frame.get(__wfStepKey); | |
| 8251 | +}; | |
| 8252 | +const __wfEnterStep = (name, fn) => { | |
| 8253 | + const prior = __als_get(); | |
| 8254 | + const frame = new Map(prior); | |
| 8255 | + frame.set(__wfStepKey, name); | |
| 8256 | + __als_set(frame); | |
| 8257 | + try { | |
| 8258 | + return fn(); | |
| 8259 | + } finally { | |
| 8260 | + __als_set(prior); | |
| 8261 | + } | |
| 8262 | +}; | |
| 8263 | + | |
| 8264 | +// Race an attempt against its deadline. The abandoned callback keeps | |
| 8265 | +// running -- there is no cancellation to send it -- but its result is | |
| 8266 | +// discarded and the timeout counts as a failed attempt, as upstream. | |
| 8267 | +const __wfTimeout = (promise, ms, name, attempt) => | |
| 8268 | + new Promise((resolve, reject) => { | |
| 8269 | + const timer = setTimeout( | |
| 8270 | + () => | |
| 8271 | + reject(new Error( | |
| 8272 | + `step ${JSON.stringify(name)} timed out after ${ms} ms (attempt ${attempt})`, | |
| 8273 | + )), | |
| 8274 | + ms, | |
| 8275 | + ); | |
| 8276 | + promise.then( | |
| 8277 | + (value) => { clearTimeout(timer); resolve(value); }, | |
| 8278 | + (error) => { clearTimeout(timer); reject(error); }, | |
| 8279 | + ); | |
| 8280 | + }); | |
| 8281 | + | |
| 8282 | +// Storage failures belong to the engine even when workflow code catches the | |
| 8283 | +// rejected step promise. Record them outside the Error object, so user code | |
| 8284 | +// cannot suppress a retry or forge one by returning a marked exception. | |
| 8285 | +const __wfTrackStorageFailures = (storage, driver) => { | |
| 8286 | + const tracked = Object.create(storage); | |
| 8287 | + for (const name of ["get", "put", "transactionSync"]) { | |
| 8288 | + Object.defineProperty(tracked, name, { | |
| 8289 | + value(...args) { | |
| 8290 | + try { | |
| 8291 | + const result = storage[name](...args); | |
| 8292 | + if (result !== null && typeof result === "object" && | |
| 8293 | + typeof result.then === "function") { | |
| 8294 | + return result.catch((error) => { | |
| 8295 | + driver.storageFailure ??= error; | |
| 8296 | + throw error; | |
| 8297 | + }); | |
| 8298 | + } | |
| 8299 | + return result; | |
| 8300 | + } catch (error) { | |
| 8301 | + driver.storageFailure ??= error; | |
| 8302 | + throw error; | |
| 8303 | + } | |
| 8304 | + }, | |
| 8305 | + }); | |
| 8306 | + } | |
| 8307 | + return tracked; | |
| 8308 | +}; | |
| 8309 | + | |
| 8310 | +// The WorkflowStep the driver hands to run(). Each method resolves its step | |
| 8311 | +// record by (name, occurrence count) -- the count is assigned synchronously | |
| 8312 | +// at call time, so `Promise.all` of two same-named steps gets deterministic | |
| 8313 | +// distinct keys in call order, and a repeated name in a loop cannot collide. | |
| 8314 | +const __wfMakeStep = (driver) => { | |
| 8315 | + const storage = driver.storage; | |
| 8316 | + // The shared step frame. `body` resolves to {value} or {block: at, kind}; | |
| 8317 | + // a blocked step leaves its promise unsettled forever in this invocation. | |
| 8318 | + // The running counter covers the whole body, ledger reads included, so | |
| 8319 | + // quiescence cannot fire between a step's read and its decision. | |
| 8320 | + const frame = (name, body) => { | |
| 8321 | + // A stale replay -- one whose invocation already suspended -- can wake | |
| 8322 | + // later if user code raced a step against an un-stepped await. It goes | |
| 8323 | + // quiet instead of executing an attempt beside the fresh replay. | |
| 8324 | + if (driver.finished) return __wfNever; | |
| 8325 | + const enclosing = __wfEnclosingStep(); | |
| 8326 | + if (enclosing !== undefined) { | |
| 8327 | + const failure = __wfError( | |
| 8328 | + `step ${JSON.stringify(name)} cannot start inside the callback of ` + | |
| 8329 | + `step ${JSON.stringify(enclosing)}; a step callback must not use ` + | |
| 8330 | + "the step API", | |
| 8331 | + ); | |
| 8332 | + failure.__wfPermanent = true; | |
| 8333 | + return Promise.reject(failure); | |
| 8334 | + } | |
| 8335 | + const count = (driver.counts.get(name) ?? 0) + 1; | |
| 8336 | + driver.counts.set(name, count); | |
| 8337 | + const ordinal = ++driver.ordinal; | |
| 8338 | + const key = driver.ledgerPrefix + `step.${count}.${name}`; | |
| 8339 | + // Step activity restarts the stall clock: a pending grace timer was | |
| 8340 | + // armed against a run() that looked stuck, and this call is progress. | |
| 8341 | + driver.clearStall(); | |
| 8342 | + driver.running += 1; | |
| 8343 | + return new Promise((resolve, reject) => { | |
| 8344 | + (async () => { | |
| 8345 | + const meta = await storage.get("__wf.meta"); | |
| 8346 | + if ( | |
| 8347 | + meta === undefined || meta.generation !== driver.generation || | |
| 8348 | + __wfTerminal(meta.status) || meta.status === "paused" || | |
| 8349 | + meta.status === "waitingForPause" | |
| 8350 | + ) { | |
| 8351 | + return { pause: true }; | |
| 8352 | + } | |
| 8353 | + return await body(key, count, ordinal); | |
| 8354 | + })().then( | |
| 8355 | + (result) => { | |
| 8356 | + driver.running -= 1; | |
| 8357 | + driver.clearStall(); | |
| 8358 | + if (result.pause === true) { | |
| 8359 | + driver.pauseRequested = true; | |
| 8360 | + driver.check(); | |
| 8361 | + return; | |
| 8362 | + } | |
| 8363 | + if (result.block !== undefined) { | |
| 8364 | + if (!driver.finished) { | |
| 8365 | + driver.blocked.push({ at: result.block, kind: result.kind }); | |
| 8366 | + } | |
| 8367 | + driver.check(); | |
| 8368 | + return; | |
| 8369 | + } | |
| 8370 | + driver.check(); | |
| 8371 | + resolve(result.value); | |
| 8372 | + }, | |
| 8373 | + (error) => { | |
| 8374 | + driver.running -= 1; | |
| 8375 | + driver.clearStall(); | |
| 8376 | + driver.check(); | |
| 8377 | + reject(error); | |
| 8378 | + }, | |
| 8379 | + ); | |
| 8380 | + }); | |
| 8381 | + }; | |
| 8382 | + const doStep = (name, configOrCallback, callbackOrRollback, maybeRollback) => { | |
| 8383 | + const hasConfig = typeof configOrCallback !== "function"; | |
| 8384 | + let config = hasConfig ? (configOrCallback ?? {}) : {}; | |
| 8385 | + const callback = hasConfig ? callbackOrRollback : configOrCallback; | |
| 8386 | + const rollback = hasConfig ? maybeRollback : callbackOrRollback; | |
| 8387 | + try { | |
| 8388 | + __wfStepName(name); | |
| 8389 | + config = __wfStepConfig(config, name); | |
| 8390 | + } catch (error) { | |
| 8391 | + return Promise.reject(error); | |
| 8392 | + } | |
| 8393 | + if (rollback !== undefined) { | |
| 8394 | + return Promise.reject(__wfError( | |
| 8395 | + "step rollbackOptions are not implemented in celld; remove the rollback handler", | |
| 8396 | + )); | |
| 8397 | + } | |
| 8398 | + if (config.sensitive !== undefined) { | |
| 8399 | + return Promise.reject(__wfError( | |
| 8400 | + "sensitive step output is not implemented in celld; remove `sensitive`", | |
| 8401 | + )); | |
| 8402 | + } | |
| 8403 | + if (typeof callback !== "function") { | |
| 8404 | + return Promise.reject(__wfError("step.do needs a callback function")); | |
| 8405 | + } | |
| 8406 | + return frame(name, async (key, count, ordinal) => { | |
| 8407 | + const record = __wfKindCheck(await storage.get(key), "do", name); | |
| 8408 | + if (record !== undefined && record.status === "completed") { | |
| 8409 | + return { value: record.value }; | |
| 8410 | + } | |
| 8411 | + if (record !== undefined && record.status === "failed") { | |
| 8412 | + throw __wfReviveError(record.error); | |
| 8413 | + } | |
| 8414 | + // A pending retry whose backoff has not elapsed blocks without | |
| 8415 | + // executing; the deadline was persisted when the attempt failed, so a | |
| 8416 | + // replay cannot reset the backoff. | |
| 8417 | + if (record !== undefined && record.nextAt > Date.now()) { | |
| 8418 | + return { block: record.nextAt, kind: "retry" }; | |
| 8419 | + } | |
| 8420 | + const attempt = (record === undefined ? 0 : record.attempt) + 1; | |
| 8421 | + const historyOrdinal = record?.ordinal ?? ordinal; | |
| 8422 | + const retries = config.retries ?? | |
| 8423 | + { limit: 5, delay: 10000, backoff: "exponential" }; | |
| 8424 | + const timeout = config.timeout ?? "10 minutes"; | |
| 8425 | + const timeoutMs = __wfDuration( | |
| 8426 | + timeout, | |
| 8427 | + `the timeout of step ${JSON.stringify(name)}`, | |
| 8428 | + ); | |
| 8429 | + // Upstream omits a dynamic delay from the step context. Copying the | |
| 8430 | + // config verbatim would expose the callback to itself as retry policy, | |
| 8431 | + // while callers expect only the serializable limit and backoff fields. | |
| 8432 | + const contextRetries = typeof retries.delay === "function" | |
| 8433 | + ? { limit: retries.limit, ...(retries.backoff === undefined | |
| 8434 | + ? {} | |
| 8435 | + : { backoff: retries.backoff }) } | |
| 8436 | + : retries; | |
| 8437 | + const context = { | |
| 8438 | + step: { name, count }, | |
| 8439 | + attempt, | |
| 8440 | + config: { retries: contextRetries, timeout }, | |
| 8441 | + }; | |
| 8442 | + try { | |
| 8443 | + // Persist the history entry before the callback starts. A concurrent | |
| 8444 | + // selected restart can therefore name an in-flight occurrence, and | |
| 8445 | + // its new generation fences the callback's eventual old-ledger write. | |
| 8446 | + await storage.put(key, { | |
| 8447 | + kind: "do", | |
| 8448 | + status: "running", | |
| 8449 | + attempt: attempt - 1, | |
| 8450 | + ordinal: historyOrdinal, | |
| 8451 | + }); | |
| 8452 | + const value = await __wfTimeout( | |
| 8453 | + __wfEnterStep(name, async () => callback(context)), | |
| 8454 | + timeoutMs, | |
| 8455 | + name, | |
| 8456 | + attempt, | |
| 8457 | + ); | |
| 8458 | + if (value !== undefined) { | |
| 8459 | + __wfCheckValue(value, `the return value of step ${JSON.stringify(name)}`); | |
| 8460 | + } | |
| 8461 | + await storage.put(key, { | |
| 8462 | + kind: "do", | |
| 8463 | + status: "completed", | |
| 8464 | + value, | |
| 8465 | + ordinal: historyOrdinal, | |
| 8466 | + }); | |
| 8467 | + return { value }; | |
| 8468 | + } catch (error) { | |
| 8469 | + // NonRetryableError skips retries by contract; a value-cap or | |
| 8470 | + // serialization failure is marked permanent above because another | |
| 8471 | + // attempt returns the same value. | |
| 8472 | + const permanent = error instanceof NonRetryableError || | |
| 8473 | + (error !== null && typeof error === "object" && | |
| 8474 | + (error.name === "NonRetryableError" || error.__wfPermanent === true)) || | |
| 8475 | + attempt > retries.limit; | |
| 8476 | + if (permanent) { | |
| 8477 | + await storage.put(key, { | |
| 8478 | + kind: "do", | |
| 8479 | + status: "failed", | |
| 8480 | + error: __wfErrorRecord(error), | |
| 8481 | + ordinal: historyOrdinal, | |
| 8482 | + }); | |
| 8483 | + throw error; | |
| 8484 | + } | |
| 8485 | + // Upstream documents the backoff names, not the arithmetic; the | |
| 8486 | + // simplest reading is used and recorded in the design page. When | |
| 8487 | + // `retries` is given without `backoff`, celld uses constant -- the | |
| 8488 | + // documented exponential default is the whole-config-omitted case. | |
| 8489 | + const dynamic = typeof retries.delay === "function"; | |
| 8490 | + const delay = dynamic | |
| 8491 | + ? await __wfEnterStep(name, () => retries.delay({ ctx: context, error })) | |
| 8492 | + : retries.delay; | |
| 8493 | + const base = __wfDuration( | |
| 8494 | + delay, | |
| 8495 | + `the retry delay of step ${JSON.stringify(name)}`, | |
| 8496 | + ); | |
| 8497 | + // A delay callback replaces the fixed base duration, not the backoff | |
| 8498 | + // policy. Skipping this factor makes a dynamic exponential or linear | |
| 8499 | + // policy retry earlier than the same policy with a fixed base. | |
| 8500 | + const factor = retries.backoff === "exponential" | |
| 8501 | + ? 2 ** (attempt - 1) | |
| 8502 | + : retries.backoff === "linear" | |
| 8503 | + ? attempt | |
| 8504 | + : 1; | |
| 8505 | + const nextAt = Date.now() + base * factor; | |
| 8506 | + await storage.put(key, { | |
| 8507 | + kind: "do", | |
| 8508 | + status: "retrying", | |
| 8509 | + attempt, | |
| 8510 | + nextAt, | |
| 8511 | + ordinal: historyOrdinal, | |
| 8512 | + }); | |
| 8513 | + return { block: nextAt, kind: "retry" }; | |
| 8514 | + } | |
| 8515 | + }); | |
| 8516 | + }; | |
| 8517 | + const sleepUntilDeadline = (name, key, ordinal, deadline) => (async () => { | |
| 8518 | + const record = __wfKindCheck(await storage.get(key), "sleep", name); | |
| 8519 | + if (record !== undefined && record.status === "completed") { | |
| 8520 | + return { value: undefined }; | |
| 8521 | + } | |
| 8522 | + const historyOrdinal = record?.ordinal ?? ordinal; | |
| 8523 | + let at = record === undefined ? undefined : record.deadline; | |
| 8524 | + if (at === undefined) { | |
| 8525 | + // The absolute deadline is computed once and persisted. Recomputing | |
| 8526 | + // from "now" on replay would extend the sleep by however long the | |
| 8527 | + // instance was down, so a crash could postpone a deadline forever. | |
| 8528 | + at = deadline(); | |
| 8529 | + if (at - Date.now() > __WF_MAX_WAIT_MS) { | |
| 8530 | + throw __wfError( | |
| 8531 | + `sleep ${JSON.stringify(name)} ends ${at - Date.now()} ms from now, ` + | |
| 8532 | + "above the upstream limit of 365 days", | |
| 8533 | + ); | |
| 8534 | + } | |
| 8535 | + await storage.put(key, { | |
| 8536 | + kind: "sleep", | |
| 8537 | + status: "sleeping", | |
| 8538 | + deadline: at, | |
| 8539 | + ordinal: historyOrdinal, | |
| 8540 | + }); | |
| 8541 | + } | |
| 8542 | + if (at <= Date.now()) { | |
| 8543 | + await storage.put(key, { | |
| 8544 | + kind: "sleep", | |
| 8545 | + status: "completed", | |
| 8546 | + ordinal: historyOrdinal, | |
| 8547 | + }); | |
| 8548 | + return { value: undefined }; | |
| 8549 | + } | |
| 8550 | + return { block: at, kind: "sleep" }; | |
| 8551 | + })(); | |
| 8552 | + return { | |
| 8553 | + do: doStep, | |
| 8554 | + sleep: (name, duration) => { | |
| 8555 | + let durationMs; | |
| 8556 | + try { | |
| 8557 | + __wfStepName(name); | |
| 8558 | + durationMs = __wfSleepDuration(duration, name); | |
| 8559 | + } catch (error) { | |
| 8560 | + return Promise.reject(error); | |
| 8561 | + } | |
| 8562 | + return frame(name, (key, _count, ordinal) => | |
| 8563 | + sleepUntilDeadline( | |
| 8564 | + name, | |
| 8565 | + key, | |
| 8566 | + ordinal, | |
| 8567 | + () => Date.now() + durationMs, | |
| 8568 | + )); | |
| 8569 | + }, | |
| 8570 | + sleepUntil: (name, timestamp) => { | |
| 8571 | + let at; | |
| 8572 | + try { | |
| 8573 | + __wfStepName(name); | |
| 8574 | + at = __wfSleepUntil(timestamp, name); | |
| 8575 | + } catch (error) { | |
| 8576 | + return Promise.reject(error); | |
| 8577 | + } | |
| 8578 | + return frame(name, (key, _count, ordinal) => | |
| 8579 | + sleepUntilDeadline(name, key, ordinal, () => { | |
| 8580 | + // A replay uses the persisted deadline after it has passed. Check | |
| 8581 | + // the moving future bound only while the deadline is first installed, | |
| 8582 | + // or every successful sleep would fail on the resume that completes it. | |
| 8583 | + if (at - Date.now() < 0) { | |
| 8584 | + throw __wfError( | |
| 8585 | + `sleepUntil ${JSON.stringify(name)} needs a future timestamp`, | |
| 8586 | + ); | |
| 8587 | + } | |
| 8588 | + return at; | |
| 8589 | + })); | |
| 8590 | + }, | |
| 8591 | + waitForEvent: (name, options) => { | |
| 8592 | + let checked; | |
| 8593 | + try { | |
| 8594 | + __wfStepName(name); | |
| 8595 | + checked = __wfWaitOptions(options, name); | |
| 8596 | + } catch (error) { | |
| 8597 | + return Promise.reject(error); | |
| 8598 | + } | |
| 8599 | + return frame(name, async (key, _count, ordinal) => { | |
| 8600 | + let record = __wfKindCheck(await storage.get(key), "event", name); | |
| 8601 | + if (record !== undefined && record.status === "completed") { | |
| 8602 | + return { value: record.value }; | |
| 8603 | + } | |
| 8604 | + if (record !== undefined && record.status === "failed") { | |
| 8605 | + throw __wfReviveError(record.error); | |
| 8606 | + } | |
| 8607 | + if (record === undefined) { | |
| 8608 | + record = { | |
| 8609 | + kind: "event", | |
| 8610 | + status: "waiting", | |
| 8611 | + type: checked.type, | |
| 8612 | + deadline: Date.now() + checked.timeoutMs, | |
| 8613 | + ordinal, | |
| 8614 | + }; | |
| 8615 | + await storage.put(key, record); | |
| 8616 | + } | |
| 8617 | + // The deadline is checked before the buffer: an event that arrived | |
| 8618 | + // after the persisted deadline must time the step out, not succeed | |
| 8619 | + // because the replay that noticed it ran late. | |
| 8620 | + if (record.deadline <= Date.now()) { | |
| 8621 | + const error = new Error( | |
| 8622 | + `waitForEvent ${JSON.stringify(name)} timed out waiting for an event ` + | |
| 8623 | + `of type ${JSON.stringify(record.type)}`, | |
| 8624 | + ); | |
| 8625 | + await storage.put(key, { | |
| 8626 | + kind: "event", | |
| 8627 | + status: "failed", | |
| 8628 | + error: __wfErrorRecord(error), | |
| 8629 | + ordinal: record.ordinal, | |
| 8630 | + }); | |
| 8631 | + throw error; | |
| 8632 | + } | |
| 8633 | + // Delivered events persist until a matching step consumes one, in | |
| 8634 | + // arrival order -- the zero-padded sequence key makes list order | |
| 8635 | + // arrival order -- so an event sent before the step is reached is | |
| 8636 | + // buffered, not lost. | |
| 8637 | + const consumed = storage.transactionSync(() => { | |
| 8638 | + const current = __wfKindCheck(storage.kv.get(key), "event", name); | |
| 8639 | + if (current !== undefined && current.status === "completed") { | |
| 8640 | + return { value: current.value }; | |
| 8641 | + } | |
| 8642 | + if (current !== undefined && current.status === "failed") { | |
| 8643 | + throw __wfReviveError(current.error); | |
| 8644 | + } | |
| 8645 | + for (const [eventKey, event] of storage.kv.list({ | |
| 8646 | + prefix: __wfEventPrefix(driver.generation), | |
| 8647 | + })) { | |
| 8648 | + if (event.type !== current.type) continue; | |
| 8649 | + const value = { | |
| 8650 | + payload: event.payload, | |
| 8651 | + timestamp: new Date(event.timestampMs), | |
| 8652 | + type: event.type, | |
| 8653 | + }; | |
| 8654 | + // The delete and completed ledger record are one SQLite commit. | |
| 8655 | + // A crash can therefore expose both or neither, so an | |
| 8656 | + // acknowledged event cannot disappear between them. | |
| 8657 | + storage.kv.delete(eventKey); | |
| 8658 | + /*__CELLD_TEST_WORKFLOW_EVENT_CONSUMED__*/ | |
| 8659 | + storage.kv.put(key, { | |
| 8660 | + kind: "event", | |
| 8661 | + status: "completed", | |
| 8662 | + value, | |
| 8663 | + ordinal: current.ordinal, | |
| 8664 | + }); | |
| 8665 | + return { value }; | |
| 8666 | + } | |
| 8667 | + }); | |
| 8668 | + if (consumed !== undefined) return consumed; | |
| 8669 | + return { block: record.deadline, kind: "event" }; | |
| 8670 | + }); | |
| 8671 | + }, | |
| 8672 | + }; | |
| 8673 | +}; | |
| 8674 | + | |
| 8675 | +const __WorkflowCell = (() => { | |
| 8676 | + class StorageTransaction { | |
| 8677 | + constructor(storage) { | |
| 8678 | + this.kv = storage.kv; | |
| 8679 | + this._scope = storage._scope; | |
| 8680 | + } | |
| 8681 | + setAlarm(t) { | |
| 8682 | + __alarm_set(this._scope, t instanceof Date ? t.getTime() : Number(t)); | |
| 8683 | + } | |
| 8684 | + deleteAlarm() { | |
| 8685 | + __alarm_delete(this._scope); | |
| 8686 | + } | |
| 8687 | + } | |
| 8688 | + const transactionSync = (storage, callback) => | |
| 8689 | + storage.transactionSync(() => callback(new StorageTransaction(storage))); | |
| 8690 | + const clearInstance = (transaction) => { | |
| 8691 | + for (const [key] of transaction.kv.list({ prefix: "__wf." })) { | |
| 8692 | + transaction.kv.delete(key); | |
| 8693 | + } | |
| 8694 | + transaction.deleteAlarm(); | |
| 8695 | + }; | |
| 8696 | + const expireTerminal = (transaction, meta, now) => { | |
| 8697 | + if (!__wfTerminal(meta.status)) return false; | |
| 8698 | + if (meta.expiresMs === undefined) { | |
| 8699 | + meta.endedMs = now; | |
| 8700 | + meta.expiresMs = now + __wfRetentionMs(meta, meta.status); | |
| 8701 | + transaction.kv.put("__wf.meta", meta); | |
| 8702 | + } | |
| 8703 | + if (meta.expiresMs > now) return false; | |
| 8704 | + clearInstance(transaction); | |
| 8705 | + return true; | |
| 8706 | + }; | |
| 8707 | + | |
| 8708 | + // The adapter stays in this closure because Workflow needs synchronous | |
| 8709 | + // alarm writes inside transactionSync(). The public async alarm API runs | |
| 8710 | + // after that commit, while a global helper would let application code | |
| 8711 | + // split metadata from its wake or invoke the raw operation after commit. | |
| 8712 | + return class __WorkflowCell { | |
| 8713 | + constructor(state) { | |
| 8714 | + this._state = state; | |
| 8715 | + } | |
| 8716 | + async __wfCreate({ | |
| 8717 | + workflowName, | |
| 8718 | + instanceId, | |
| 8719 | + params, | |
| 8720 | + retention, | |
| 8721 | + locationHint, | |
| 8722 | + skipExisting = false, | |
| 8723 | + }) { | |
| 8724 | + const storage = this._state.storage; | |
| 8725 | + if (params !== undefined) __wfCheckValue(params, "the workflow params"); | |
| 8726 | + const result = transactionSync(storage, (transaction) => { | |
| 8727 | + let meta = transaction.kv.get("__wf.meta"); | |
| 8728 | + if (meta !== undefined && expireTerminal(transaction, meta, Date.now())) { | |
| 8729 | + meta = undefined; | |
| 8730 | + } | |
| 8731 | + if (meta !== undefined && skipExisting) return { id: instanceId, created: false }; | |
| 8732 | + if (meta !== undefined) { | |
| 8733 | + throw __wfError( | |
| 8734 | + `instance ${JSON.stringify(instanceId)} already exists with status ` + | |
| 8735 | + JSON.stringify(meta.status), | |
| 8736 | + ); | |
| 8737 | + } | |
| 8738 | + const generation = crypto.randomUUID(); | |
| 8739 | + transaction.kv.put("__wf.meta", { | |
| 8740 | + workflowName, | |
| 8741 | + instanceId, | |
| 8742 | + params, | |
| 8743 | + retention, | |
| 8744 | + ...(locationHint === undefined ? {} : { locationHint }), | |
| 8745 | + generation, | |
| 8746 | + createdMs: Date.now(), | |
| 8747 | + status: "queued", | |
| 8748 | + }); | |
| 8749 | + // The metadata and alarm are one SQLite commit. A committed creation | |
| 8750 | + // therefore always has the wake that can start or recover its drive. | |
| 8751 | + transaction.setAlarm(Date.now()); | |
| 8752 | + /*__CELLD_TEST_WORKFLOW_META_CREATED__*/ | |
| 8753 | + return { id: instanceId, created: true }; | |
| 8754 | + }); | |
| 8755 | + return result; | |
| 8756 | + } | |
| 8757 | + async __wfStatus() { | |
| 8758 | + const meta = transactionSync(this._state.storage, (transaction) => { | |
| 8759 | + const current = transaction.kv.get("__wf.meta"); | |
| 8760 | + if (current === undefined) return undefined; | |
| 8761 | + return expireTerminal(transaction, current, Date.now()) ? undefined : current; | |
| 8762 | + }); | |
| 8763 | + // A cell exists on first address like any cell, so an absent ledger is | |
| 8764 | + // the only honest "no such instance" signal. Inventing an instance here | |
| 8765 | + // would turn every typo into an empty workflow. | |
| 8766 | + if (meta === undefined) throw __wfError("instance does not exist"); | |
| 8767 | + const status = { status: meta.status, rollback: null }; | |
| 8768 | + if (meta.error !== undefined) status.error = meta.error; | |
| 8769 | + if (meta.output !== undefined) status.output = meta.output; | |
| 8770 | + return status; | |
| 8771 | + } | |
| 8772 | + async __wfDelete() { | |
| 8773 | + const storage = this._state.storage; | |
| 8774 | + const deleted = transactionSync(storage, (transaction) => { | |
| 8775 | + const meta = transaction.kv.get("__wf.meta"); | |
| 8776 | + if (meta === undefined) return false; | |
| 8777 | + if (expireTerminal(transaction, meta, Date.now())) return false; | |
| 8778 | + clearInstance(transaction); | |
| 8779 | + return true; | |
| 8780 | + }); | |
| 8781 | + // Throw after the transaction commits. An expiry discovered here must | |
| 8782 | + // keep its cleanup even though delete() reports that the instance is gone. | |
| 8783 | + if (!deleted) throw __wfError("instance does not exist"); | |
| 8784 | + // A callback can still be awaiting application I/O when deletion lands. | |
| 8785 | + // Reset the object after the deletion commit so that callback cannot | |
| 8786 | + // recreate an old-generation ledger entry after delete() reports success. | |
| 8787 | + this._state.abort(new Error("WORKFLOW_INSTANCE_DELETED")); | |
| 8788 | + } | |
| 8789 | + async __wfPause() { | |
| 8790 | + const storage = this._state.storage; | |
| 8791 | + transactionSync(storage, (transaction) => { | |
| 8792 | + const meta = transaction.kv.get("__wf.meta"); | |
| 8793 | + if (meta === undefined) throw __wfError("instance does not exist"); | |
| 8794 | + if (__wfTerminal(meta.status) || meta.status === "paused" || | |
| 8795 | + meta.status === "waitingForPause") return; | |
| 8796 | + if (meta.status === "running") { | |
| 8797 | + meta.status = "waitingForPause"; | |
| 8798 | + // A drive lost after this commit must re-enter and finish the pause. | |
| 8799 | + transaction.setAlarm(Date.now()); | |
| 8800 | + } else { | |
| 8801 | + meta.status = "paused"; | |
| 8802 | + meta.pausedMs = Date.now(); | |
| 8803 | + transaction.deleteAlarm(); | |
| 8804 | + } | |
| 8805 | + transaction.kv.put("__wf.meta", meta); | |
| 8806 | + }); | |
| 8807 | + } | |
| 8808 | + async __wfResume() { | |
| 8809 | + const storage = this._state.storage; | |
| 8810 | + transactionSync(storage, (transaction) => { | |
| 8811 | + const meta = transaction.kv.get("__wf.meta"); | |
| 8812 | + if (meta === undefined) throw __wfError("instance does not exist"); | |
| 8813 | + if (meta.status === "waitingForPause") { | |
| 8814 | + meta.status = "running"; | |
| 8815 | + transaction.kv.put("__wf.meta", meta); | |
| 8816 | + transaction.setAlarm(Date.now()); | |
| 8817 | + return; | |
| 8818 | + } | |
| 8819 | + if (meta.status !== "paused") { | |
| 8820 | + throw __wfError( | |
| 8821 | + `cannot resume an instance with status ${JSON.stringify(meta.status)}`, | |
| 8822 | + ); | |
| 8823 | + } | |
| 8824 | + const offset = Math.max(0, Date.now() - (meta.pausedMs ?? Date.now())); | |
| 8825 | + for (const [key, record] of transaction.kv.list({ | |
| 8826 | + prefix: __wfLedgerPrefix(meta.generation) + "step.", | |
| 8827 | + })) { | |
| 8828 | + if (record.status === "retrying") record.nextAt += offset; | |
| 8829 | + if (record.status === "sleeping" || record.status === "waiting") { | |
| 8830 | + record.deadline += offset; | |
| 8831 | + } | |
| 8832 | + transaction.kv.put(key, record); | |
| 8833 | + } | |
| 8834 | + delete meta.pausedMs; | |
| 8835 | + meta.status = "queued"; | |
| 8836 | + transaction.kv.put("__wf.meta", meta); | |
| 8837 | + transaction.setAlarm(Date.now()); | |
| 8838 | + }); | |
| 8839 | + } | |
| 8840 | + async __wfRestart(options) { | |
| 8841 | + const checked = __wfRestartOptions(options); | |
| 8842 | + const storage = this._state.storage; | |
| 8843 | + transactionSync(storage, (transaction) => { | |
| 8844 | + const meta = transaction.kv.get("__wf.meta"); | |
| 8845 | + if (meta === undefined) throw __wfError("instance does not exist"); | |
| 8846 | + const oldPrefix = __wfLedgerPrefix(meta.generation); | |
| 8847 | + let targetOrdinal; | |
| 8848 | + if (checked.from !== undefined) { | |
| 8849 | + const expectedKind = checked.from.type === "waitForEvent" | |
| 8850 | + ? "event" | |
| 8851 | + : checked.from.type; | |
| 8852 | + let occurrence = 0; | |
| 8853 | + const history = [...transaction.kv.list({ prefix: oldPrefix + "step." })] | |
| 8854 | + .filter(([, record]) => Number.isInteger(record.ordinal)) | |
| 8855 | + .sort((left, right) => left[1].ordinal - right[1].ordinal); | |
| 8856 | + // The ledger key is `<prefix>step.<per-name-count>.<name>`. Derive | |
| 8857 | + // the name from it because a record stores replay state, not identity. | |
| 8858 | + for (const [key, record] of history) { | |
| 8859 | + const marker = oldPrefix + "step."; | |
| 8860 | + const suffix = key.slice(marker.length); | |
| 8861 | + const dot = suffix.indexOf("."); | |
| 8862 | + const name = dot < 0 ? "" : suffix.slice(dot + 1); | |
| 8863 | + if (record.kind !== expectedKind || name !== checked.from.name) continue; | |
| 8864 | + occurrence += 1; | |
| 8865 | + if (occurrence === checked.from.count) { | |
| 8866 | + targetOrdinal = record.ordinal; | |
| 8867 | + break; | |
| 8868 | + } | |
| 8869 | + } | |
| 8870 | + if (targetOrdinal === undefined) { | |
| 8871 | + throw __wfError( | |
| 8872 | + `restart() could not find ${checked.from.type} step ` + | |
| 8873 | + `${JSON.stringify(checked.from.name)} occurrence ${checked.from.count}`, | |
| 8874 | + ); | |
| 8875 | + } | |
| 8876 | + } | |
| 8877 | + const generation = crypto.randomUUID(); | |
| 8878 | + const newPrefix = __wfLedgerPrefix(generation); | |
| 8879 | + if (targetOrdinal !== undefined) { | |
| 8880 | + for (const [key, record] of transaction.kv.list({ prefix: oldPrefix + "step." })) { | |
| 8881 | + if (Number.isInteger(record.ordinal) && record.ordinal < targetOrdinal) { | |
| 8882 | + transaction.kv.put(newPrefix + key.slice(oldPrefix.length), record); | |
| 8883 | + } | |
| 8884 | + } | |
| 8885 | + } | |
| 8886 | + for (const [key] of transaction.kv.list({ prefix: oldPrefix })) { | |
| 8887 | + transaction.kv.delete(key); | |
| 8888 | + } | |
| 8889 | + meta.generation = generation; | |
| 8890 | + meta.status = "queued"; | |
| 8891 | + delete meta.pausedMs; | |
| 8892 | + delete meta.output; | |
| 8893 | + delete meta.error; | |
| 8894 | + transaction.kv.put("__wf.meta", meta); | |
| 8895 | + transaction.setAlarm(Date.now()); | |
| 8896 | + }); | |
| 8897 | + } | |
| 8898 | + async __wfTerminate() { | |
| 8899 | + const storage = this._state.storage; | |
| 8900 | + transactionSync(storage, (transaction) => { | |
| 8901 | + const meta = transaction.kv.get("__wf.meta"); | |
| 8902 | + if (meta === undefined) throw __wfError("instance does not exist"); | |
| 8903 | + if (__wfTerminal(meta.status)) { | |
| 8904 | + throw __wfError( | |
| 8905 | + `cannot terminate an instance with status ${JSON.stringify(meta.status)}`, | |
| 8906 | + ); | |
| 8907 | + } | |
| 8908 | + meta.status = "terminated"; | |
| 8909 | + __wfFinishRetention(meta, transaction); | |
| 8910 | + transaction.kv.put("__wf.meta", meta); | |
| 8911 | + /*__CELLD_TEST_WORKFLOW_TERMINAL_ALARM_SET__*/ | |
| 8912 | + }); | |
| 8913 | + } | |
| 8914 | + async __wfSendEvent(options) { | |
| 8915 | + const storage = this._state.storage; | |
| 8916 | + // The binding validates first to avoid an unnecessary cell call. Repeat | |
| 8917 | + // the check here because this RPC owns the durable event invariant: no | |
| 8918 | + // current or future internal caller can bypass validation before storage. | |
| 8919 | + const { type, payload } = __wfEventOptions(options); | |
| 8920 | + transactionSync(storage, (transaction) => { | |
| 8921 | + const meta = transaction.kv.get("__wf.meta"); | |
| 8922 | + if (meta === undefined) throw __wfError("instance does not exist"); | |
| 8923 | + if (__wfTerminal(meta.status)) { | |
| 8924 | + throw __wfError( | |
| 8925 | + `cannot send an event to an instance with status ${JSON.stringify(meta.status)}`, | |
| 8926 | + ); | |
| 8927 | + } | |
| 8928 | + const sequenceKey = __wfLedgerPrefix(meta.generation) + "eventSeq"; | |
| 8929 | + const sequence = transaction.kv.get(sequenceKey) ?? 0; | |
| 8930 | + transaction.kv.put(sequenceKey, sequence + 1); | |
| 8931 | + transaction.kv.put(__wfEventKey(meta.generation, sequence), { | |
| 8932 | + type, | |
| 8933 | + payload, | |
| 8934 | + timestampMs: Date.now(), | |
| 8935 | + }); | |
| 8936 | + // Allocation, the event body, and the nudge are one commit. Parallel | |
| 8937 | + // writers cannot reuse a sequence and a crash cannot expose a partial | |
| 8938 | + // acknowledged send. | |
| 8939 | + if (meta.status !== "paused" && meta.status !== "waitingForPause") { | |
| 8940 | + transaction.setAlarm(Date.now()); | |
| 8941 | + } | |
| 8942 | + }); | |
| 8943 | + } | |
| 8944 | + async alarm() { | |
| 8945 | + const storage = this._state.storage; | |
| 8946 | + // One drive at a time. A sendEvent nudge (setAlarm(now)) landing | |
| 8947 | + // mid-fire replaces the firing alarm in the core, and the replacement | |
| 8948 | + // can dispatch a second alarm() into this isolate while the first drive | |
| 8949 | + // still awaits user code. Two concurrent replays would both see the | |
| 8950 | + // same incomplete steps and double-execute their callbacks. The guard | |
| 8951 | + // is isolate-local and that is sufficient: every drive for a cell runs | |
| 8952 | + // in its owner's isolate, and a takeover starts a fresh isolate with no | |
| 8953 | + // drive in flight. The nudge is not lost -- the in-flight drive folds | |
| 8954 | + // `_wfNudge` into the minimum it re-arms, and if it suspended before | |
| 8955 | + // seeing the flag, the re-arm below starts a fresh drive immediately. | |
| 8956 | + // A failed drive is not re-raised here: the engine already retries the | |
| 8957 | + // alarm that fired it. | |
| 8958 | + if (this._wfDriving !== undefined) { | |
| 8959 | + this._wfNudge = Date.now(); | |
| 8960 | + await this._wfDriving.catch(() => {}); | |
| 8961 | + if (this._wfNudge !== undefined) { | |
| 8962 | + this._wfNudge = undefined; | |
| 8963 | + const meta = await storage.get("__wf.meta"); | |
| 8964 | + if ( | |
| 8965 | + meta !== undefined && !__wfTerminal(meta.status) && | |
| 8966 | + meta.status !== "paused" && meta.status !== "waitingForPause" | |
| 8967 | + ) { | |
| 8968 | + await storage.setAlarm(Date.now()); | |
| 8969 | + } | |
| 8970 | + } | |
| 8971 | + return; | |
| 8972 | + } | |
| 8973 | + const meta = await storage.get("__wf.meta"); | |
| 8974 | + // A terminal instance's pending alarm can still fire. It owns retention: | |
| 8975 | + // remove expired state, or restore the expiry wake after a stale nudge. | |
| 8976 | + if (meta === undefined) { | |
| 8977 | + await storage.deleteAlarm(); | |
| 8978 | + return; | |
| 8979 | + } | |
| 8980 | + if (__wfTerminal(meta.status)) { | |
| 8981 | + transactionSync(storage, (transaction) => { | |
| 8982 | + const current = transaction.kv.get("__wf.meta"); | |
| 8983 | + if (current === undefined) { | |
| 8984 | + transaction.deleteAlarm(); | |
| 8985 | + return; | |
| 8986 | + } | |
| 8987 | + if (!expireTerminal(transaction, current, Date.now())) { | |
| 8988 | + transaction.setAlarm(current.expiresMs); | |
| 8989 | + } | |
| 8990 | + }); | |
| 8991 | + return; | |
| 8992 | + } | |
| 8993 | + if (meta.status === "paused") { | |
| 8994 | + await storage.deleteAlarm(); | |
| 8995 | + return; | |
| 8996 | + } | |
| 8997 | + if (meta.status === "waitingForPause") { | |
| 8998 | + transactionSync(storage, (transaction) => { | |
| 8999 | + const current = transaction.kv.get("__wf.meta"); | |
| 9000 | + if (current === undefined || current.generation !== meta.generation || | |
| 9001 | + current.status !== "waitingForPause") return; | |
| 9002 | + current.status = "paused"; | |
| 9003 | + current.pausedMs = Date.now(); | |
| 9004 | + transaction.kv.put("__wf.meta", current); | |
| 9005 | + transaction.deleteAlarm(); | |
| 9006 | + }); | |
| 9007 | + return; | |
| 9008 | + } | |
| 9009 | + // The fired alarm stays armed while the drive runs. The engine consumes | |
| 9010 | + // it only when this handler returns cleanly, and retries it when the | |
| 9011 | + // handler fails -- that retry is the crash safety net. Deleting it here | |
| 9012 | + // would commit the deletion durably mid-drive (durability is per SQLite | |
| 9013 | + // commit, and replication ships frames per commit), so a SIGKILL before | |
| 9014 | + // the suspend-time re-arm would strand a "running" instance with no | |
| 9015 | + // alarm and no wake entry. The suspend path re-arms explicitly, and a | |
| 9016 | + // terminal drive deletes. | |
| 9017 | + const driving = this._drive(meta); | |
| 9018 | + this._wfDriving = driving; | |
| 9019 | + try { | |
| 9020 | + await driving; | |
| 9021 | + } finally { | |
| 9022 | + this._wfDriving = undefined; | |
| 9023 | + } | |
| 9024 | + } | |
| 9025 | + async _drive(meta) { | |
| 9026 | + const storage = this._state.storage; | |
| 9027 | + // The drive owns `status`, `output`, and `error`; every other piece of | |
| 9028 | + // instance state belongs to the RPCs (sendEvent's sequence lives in its | |
| 9029 | + // own key for the same reason). The gate is open at every await, so a | |
| 9030 | + // terminate can land mid-drive: re-reading before each write, and | |
| 9031 | + // writing nothing once the status is terminal, is what makes "terminate | |
| 9032 | + // wins the race" true rather than asserted. Writing back the meta this | |
| 9033 | + // drive entered with would resurrect a terminated instance as "waiting" | |
| 9034 | + // and re-arm the alarm its terminate deleted. | |
| 9035 | + const settle = (mutate) => transactionSync(storage, (transaction) => { | |
| 9036 | + const current = transaction.kv.get("__wf.meta"); | |
| 9037 | + if (current === undefined || __wfTerminal(current.status) || | |
| 9038 | + current.generation !== meta.generation) return false; | |
| 9039 | + mutate(current, transaction); | |
| 9040 | + transaction.kv.put("__wf.meta", current); | |
| 9041 | + return true; | |
| 9042 | + }); | |
| 9043 | + const className = __cell.workflows[meta.workflowName]; | |
| 9044 | + const cls = className === undefined ? undefined : __cf.exports[className]; | |
| 9045 | + if (typeof cls !== "function" || | |
| 9046 | + typeof (cls.prototype && cls.prototype.run) !== "function") { | |
| 9047 | + // Deploy cannot see inside the bundle, so a missing export fails | |
| 9048 | + // here, loudly, with the class and the config key named. | |
| 9049 | + settle((current, transaction) => { | |
| 9050 | + current.status = "errored"; | |
| 9051 | + current.error = { | |
| 9052 | + name: "Error", | |
| 9053 | + message: className === undefined | |
| 9054 | + ? `workflow ${JSON.stringify(meta.workflowName)} is not declared ` + | |
| 9055 | + "in this deployment's `workflows`" | |
| 9056 | + : `workflow class ${JSON.stringify(className)} is not a module ` + | |
| 9057 | + "export with a run() method; export it and extend " + | |
| 9058 | + "WorkflowEntrypoint", | |
| 9059 | + }; | |
| 9060 | + __wfFinishRetention(current, transaction); | |
| 9061 | + /*__CELLD_TEST_WORKFLOW_TERMINAL_ALARM_SET__*/ | |
| 9062 | + }); | |
| 9063 | + return; | |
| 9064 | + } | |
| 9065 | + const driver = { | |
| 9066 | + storage: undefined, | |
| 9067 | + storageFailure: undefined, | |
| 9068 | + generation: meta.generation, | |
| 9069 | + ledgerPrefix: __wfLedgerPrefix(meta.generation), | |
| 9070 | + counts: new Map(), | |
| 9071 | + ordinal: 0, | |
| 9072 | + running: 0, | |
| 9073 | + blocked: [], | |
| 9074 | + pauseRequested: false, | |
| 9075 | + finished: false, | |
| 9076 | + checkQueued: false, | |
| 9077 | + stallTimer: undefined, | |
| 9078 | + clearStall() { | |
| 9079 | + if (this.stallTimer !== undefined) { | |
| 9080 | + clearTimeout(this.stallTimer); | |
| 9081 | + this.stallTimer = undefined; | |
| 9082 | + } | |
| 9083 | + }, | |
| 9084 | + }; | |
| 9085 | + driver.storage = __wfTrackStorageFailures(storage, driver); | |
| 9086 | + const outcome = new Promise((resolve) => { | |
| 9087 | + driver.finish = (result) => { | |
| 9088 | + if (driver.finished) return; | |
| 9089 | + driver.finished = true; | |
| 9090 | + driver.clearStall(); | |
| 9091 | + resolve(result); | |
| 9092 | + }; | |
| 9093 | + }); | |
| 9094 | + // Quiescence: when a step is blocked, no step callback is executing, | |
| 9095 | + // and a macrotask has passed, nothing can progress, so the invocation | |
| 9096 | + // suspends. The macrotask lets every microtask chain a completed step | |
| 9097 | + // unblocked drain first; checking on the spot would suspend an instance | |
| 9098 | + // whose next step is one `await` away from starting. | |
| 9099 | + driver.check = () => { | |
| 9100 | + if (driver.checkQueued || driver.finished) return; | |
| 9101 | + driver.checkQueued = true; | |
| 9102 | + setTimeout(() => { | |
| 9103 | + driver.checkQueued = false; | |
| 9104 | + if (driver.finished || driver.running !== 0) return; | |
| 9105 | + if (driver.pauseRequested) { | |
| 9106 | + driver.finish({ kind: "pause" }); | |
| 9107 | + return; | |
| 9108 | + } | |
| 9109 | + if (driver.blocked.length > 0) { | |
| 9110 | + driver.finish({ kind: "suspend" }); | |
| 9111 | + return; | |
| 9112 | + } | |
| 9113 | + // No step runs, none is blocked, and run() has not settled: it | |
| 9114 | + // awaits something that is not a step. Upstream permits that -- an | |
| 9115 | + // un-stepped `await fetch()` between steps is legal, merely | |
| 9116 | + // non-durable -- so this is not yet an error; but a promise that | |
| 9117 | + // never settles would wedge the alarm handler in silence, with the | |
| 9118 | + // instance "running" forever. A grace timer splits the two: if the | |
| 9119 | + // same nothing-can-progress state still holds when it fires, the | |
| 9120 | + // instance fails loudly. The timer is a plain in-isolate timeout, | |
| 9121 | + // not a durable alarm, on purpose: an eviction or a restart replays | |
| 9122 | + // run() from the top anyway, so losing the timer loses nothing -- | |
| 9123 | + // the replay re-enters the same stall and re-arms its own grace. | |
| 9124 | + if (driver.stallTimer !== undefined) return; | |
| 9125 | + driver.stallTimer = setTimeout(() => { | |
| 9126 | + driver.stallTimer = undefined; | |
| 9127 | + if (driver.finished || driver.running !== 0 || driver.blocked.length > 0) { | |
| 9128 | + return; | |
| 9129 | + } | |
| 9130 | + driver.finish({ | |
| 9131 | + kind: "error", | |
| 9132 | + error: __wfError( | |
| 9133 | + "run() has been awaiting something that is not a step for " + | |
| 9134 | + (__WF_STALL_GRACE_MS / 1000) + " seconds while no step is " + | |
| 9135 | + "running or blocked; a replay cannot resume this wait, so " + | |
| 9136 | + "wrap long async work in step.do", | |
| 9137 | + ), | |
| 9138 | + }); | |
| 9139 | + }, __WF_STALL_GRACE_MS); | |
| 9140 | + }, 0); | |
| 9141 | + }; | |
| 9142 | + if ( | |
| 9143 | + meta.status !== "running" && | |
| 9144 | + !(await settle((current) => { | |
| 9145 | + current.status = "running"; | |
| 9146 | + })) | |
| 9147 | + ) { | |
| 9148 | + return; | |
| 9149 | + } | |
| 9150 | + const step = __wfMakeStep(driver); | |
| 9151 | + const event = { | |
| 9152 | + payload: meta.params, | |
| 9153 | + timestamp: new Date(meta.createdMs), | |
| 9154 | + instanceId: meta.instanceId, | |
| 9155 | + workflowName: meta.workflowName, | |
| 9156 | + }; | |
| 9157 | + // ExecutionContext-shaped, as the WorkflowEntrypoint constructor | |
| 9158 | + // documents upstream. | |
| 9159 | + const ctx = { | |
| 9160 | + waitUntil: __registerWaitUntil, | |
| 9161 | + passThroughOnException() {}, | |
| 9162 | + }; | |
| 9163 | + (async () => new cls(ctx, __cell.env).run(event, step))().then( | |
| 9164 | + (value) => driver.finish({ kind: "complete", value }), | |
| 9165 | + (error) => driver.finish({ kind: "error", error }), | |
| 9166 | + ); | |
| 9167 | + /*__CELLD_TEST_WORKFLOW_AFTER_RUN_STARTED__*/ | |
| 9168 | + let result = await outcome; | |
| 9169 | + // The workflow can catch a rejected step promise, but it cannot turn an | |
| 9170 | + // engine storage failure into a successful run. Preserve the alarm so | |
| 9171 | + // the runtime retries over the last committed ledger prefix. | |
| 9172 | + if (driver.storageFailure !== undefined) { | |
| 9173 | + throw driver.storageFailure; | |
| 9174 | + } | |
| 9175 | + const currentMeta = await storage.get("__wf.meta"); | |
| 9176 | + if ( | |
| 9177 | + result.kind === "pause" || | |
| 9178 | + (currentMeta !== undefined && | |
| 9179 | + currentMeta.generation === meta.generation && | |
| 9180 | + currentMeta.status === "waitingForPause") | |
| 9181 | + ) { | |
| 9182 | + /*__CELLD_TEST_WORKFLOW_BEFORE_PAUSE_SETTLE__*/ | |
| 9183 | + settle((current, transaction) => { | |
| 9184 | + // A resume can cancel waitingForPause after this drive selected its | |
| 9185 | + // pause result. Preserve that newer running state and its alarm, or | |
| 9186 | + // this stale settlement strands an acknowledged resume as paused. | |
| 9187 | + if (current.status !== "waitingForPause") return; | |
| 9188 | + current.status = "paused"; | |
| 9189 | + current.pausedMs = Date.now(); | |
| 9190 | + transaction.deleteAlarm(); | |
| 9191 | + }); | |
| 9192 | + return; | |
| 9193 | + } | |
| 9194 | + if (result.kind === "suspend") { | |
| 9195 | + let at = Math.min(...driver.blocked.map((entry) => entry.at)); | |
| 9196 | + // A nudge that landed mid-drive must not wait out the pending | |
| 9197 | + // deadline. It is visible in one of two places: getAlarm(), when the | |
| 9198 | + // nudge re-armed and no second alarm dispatched yet, or `_wfNudge`, | |
| 9199 | + // when a second alarm() already entered and parked on the drive | |
| 9200 | + // guard -- its dispatch consumed the armed alarm, so getAlarm() | |
| 9201 | + // alone would miss it. | |
| 9202 | + const nudge = await storage.getAlarm(); | |
| 9203 | + if (nudge !== null) at = Math.min(at, nudge); | |
| 9204 | + if (this._wfNudge !== undefined) { | |
| 9205 | + at = Math.min(at, this._wfNudge); | |
| 9206 | + this._wfNudge = undefined; | |
| 9207 | + } | |
| 9208 | + settle((current, transaction) => { | |
| 9209 | + current.status = "waiting"; | |
| 9210 | + transaction.setAlarm(at); | |
| 9211 | + }); | |
| 9212 | + // The explicit re-arm replaces the alarm that fired this drive. | |
| 9213 | + // Durability is per SQLite commit, not per turn: a crash can persist | |
| 9214 | + // any prefix of this invocation's ledger writes, and the unconsumed | |
| 9215 | + // fired alarm is what re-drives the replay over whatever prefix | |
| 9216 | + // survived. A terminated instance re-arms nothing; its leftover | |
| 9217 | + // alarm fires once, sees the terminal status, and retires itself. | |
| 9218 | + return; | |
| 9219 | + } | |
| 9220 | + if (result.kind === "complete") { | |
| 9221 | + try { | |
| 9222 | + if (result.value !== undefined) { | |
| 9223 | + __wfCheckValue(result.value, "the run() return value"); | |
| 9224 | + } | |
| 9225 | + } catch (error) { | |
| 9226 | + result = { kind: "error", error }; | |
| 9227 | + } | |
| 9228 | + if (result.kind === "complete") { | |
| 9229 | + // Keep settlement outside the value-validation catch. A storage | |
| 9230 | + // failure must escape the alarm handler so the engine retries the | |
| 9231 | + // still-armed drive; converting it to a user error would consume the | |
| 9232 | + // alarm and make a transient commit failure terminal. | |
| 9233 | + settle((current, transaction) => { | |
| 9234 | + current.status = "complete"; | |
| 9235 | + if (result.value !== undefined) current.output = result.value; | |
| 9236 | + // The terminal commit installs the expiry wake with the retained | |
| 9237 | + // state, so a crash can expose neither without the other. | |
| 9238 | + __wfFinishRetention(current, transaction); | |
| 9239 | + /*__CELLD_TEST_WORKFLOW_TERMINAL_ALARM_SET__*/ | |
| 9240 | + }); | |
| 9241 | + return; | |
| 9242 | + } | |
| 9243 | + } | |
| 9244 | + settle((current, transaction) => { | |
| 9245 | + current.status = "errored"; | |
| 9246 | + current.error = __wfErrorRecord(result.error); | |
| 9247 | + __wfFinishRetention(current, transaction); | |
| 9248 | + /*__CELLD_TEST_WORKFLOW_TERMINAL_ALARM_SET__*/ | |
| 9249 | + }); | |
| 9250 | + } | |
| 9251 | + }; | |
| 9252 | +})(); | |
| 9253 | +__runtimeClass("__Workflow", __WorkflowCell); | |
| 10285 | 9254 | |
| 10286 | 9255 | class NonRetryableError extends Error { |
| 10287 | 9256 | constructor(message, name = "NonRetryableError") { |
modifiedcrates/celld/js/headers.js+3−2View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/js/modules.rs+83−9View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/js/r2_ops.rs+21−735View file
Diff not rendered to keep this page fast. View the file
addedcrates/celld/js/services/kv.js+1127−0View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/js/storage_ops.rs+17−21View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/js/websocket.rs+234−1014View file
Diff not rendered to keep this page fast. View the file
addedcrates/celld/kv_blob.rs+180−0View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/lib.rs+59−46View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/local_store.rs+229−217View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/ltx_repl.rs+4670−4441View file
Diff not rendered to keep this page fast. View the file
addedcrates/celld/ltx_replication.rs+162−0View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/main.rs+3756−3707View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/main/websocket.rs+157−153View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/node_log.rs+6276−5755View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/ownership_store.rs+8−2View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/pool.rs+787−820View file
Diff not rendered to keep this page fast. View the file
addedcrates/celld/queue_policy.rs+465−0View file
Diff not rendered to keep this page fast. View the file
addedcrates/celld/r2_store.rs+750−0View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/runtime.rs+2915−3685View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/storage.rs+3244−3534View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/wake.rs+1−1View file
Diff not rendered to keep this page fast. View the file
addedcrates/celld/wake_entry.rs+124−0View file
Diff not rendered to keep this page fast. View the file
addedcrates/celld/ws_registry.rs+1069−0View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/logic/cron.rs+41−0View file
Diff not rendered to keep this page fast. View the file
modifieddocs/README.md+7−0View file
Diff not rendered to keep this page fast. View the file
modifieddocs/cloudflare-compat.md+6−0View file
Diff not rendered to keep this page fast. View the file
modifieddocs/guarantees.md+44−0View file
Diff not rendered to keep this page fast. View the file
modifieddocs/limitations.md+1−1View file
Diff not rendered to keep this page fast. View the file
modifieddocs/security.md+224−223View file
Diff not rendered to keep this page fast. View the file
modifieddocs/services/d1.md+3−2View file
Diff not rendered to keep this page fast. View the file
modifieddocs/services/durable-object-facets-flow.svg+123−124View file
Diff not rendered to keep this page fast. View the file
modifieddocs/services/durable-object-facets.md+87−95View file
Diff not rendered to keep this page fast. View the file
modifieddocs/services/durable-objects.md+71−63View file
Diff not rendered to keep this page fast. View the file
modifieddocs/services/dynamic-workers.md+10−6View file
Diff not rendered to keep this page fast. View the file
modifieddocs/services/r2.md+25−0View file
Diff not rendered to keep this page fast. View the file
modifieddocs/services/static-assets.md+2−2View file
Diff not rendered to keep this page fast. View the file
modifieddocs/services/workers.md+4−1View file
Diff not rendered to keep this page fast. View the file
modifieddocs/wasm.md+10−9View file
Diff not rendered to keep this page fast. View the file
modifiedexamples/dynamic-worker-tails/index.js+1−0View file
Diff not rendered to keep this page fast. View the file
modifiedexamples/facets/index.js+1−0View file
Diff not rendered to keep this page fast. View the file