v0.5.1
Upgrading from v0.5.0 can use a rolling update. Stop one node, wait for its replacement to report healthy, then continue to the next node. Highlights: - Dynamic Workers can enforce CPU time and subrequest limits from `WorkerCode.limits` or a `getEntrypoint()` call. - Dynamic Workers can send Tail Workers an invocation report with the request, response, console logs, exception, and outcome. - The new `celld r2` CLI tool can put, get, list, inspect, and delete objects behind an `r2_buckets` binding without a running node. It preserves the binding's object metadata. - `celld deploy` accepts Wrangler `define` values and `rules` for Text, Data, and CompiledWasm modules when it bundles a Worker. - KV accepts a `ReadableStream` value in `put()`. It checks the value-size limit while reading the stream. - The node caps its LTX writer and read-lock SQLite page caches, and returns freed C allocator pages before it measures memory pressure. - Compaction can read retained LTX bundles after their segments leave the in-memory index, so a slow cell can continue draining its history. - The `/evict/<cell>` operator route reports a refusal, cancellation, or failure instead of returning success before the eviction completes. - `/state` reports isolate counts and V8 and allocator memory counters. - Node.js compatibility improves for mutable built-in modules and the `process` fields that dependencies read during module loading. Issues fixed: - #204: `KeyObject.toCryptoKey()` honors the requested algorithm, key usages, and extractability, so valid RSA keys can sign with `jose`. - #209: R2 writes work with Azure Blob Storage metadata-name rules. Co-authored-by: Josh Collinsworth <[email protected]> Co-authored-by: Kyle Kelley <[email protected]> Co-authored-by: Nathan Whitaker <[email protected]> Co-authored-by: Ryan Dahl <[email protected]> Co-authored-by: Yusuke Tanaka <[email protected]>
Bartek Iwańczuk authored signed1 parent 12d5b63commit 42269c121c989c65c0638ab01f368baf18a5f0dfBrowse files
80 files changed+6096−1086
Files (80)
- Cargo.lock+1−1
- README.md+32−18
- crates/celld/Cargo.toml+1−1
- crates/celld/actor.rs+82−148
- crates/celld/assets.rs+8−2
- crates/celld/bucket.rs+73−25
- crates/celld/cli_output.rs+21−0
- crates/celld/deploy.rs+267−47
- crates/celld/generation.rs+29−0
- crates/celld/js.rs+0−0
- crates/celld/js/bootstrap.rs+1−1
- crates/celld/js/crypto.js+6−4
- crates/celld/js/harness.js+169−42
- crates/celld/js/node_crypto.js+74−14
- crates/celld/js/node_stream.js+10−0
- crates/celld/js/r2_ops.rs+191−132
- crates/celld/js/tcp.rs+4−4
- crates/celld/js/websocket.rs+2−2
- crates/celld/lib.rs+16−1
- crates/celld/local_store.rs+4−4
- crates/celld/ltx_repl.rs+143−57
- crates/celld/machine.rs+2−2
- crates/celld/main.rs+55−20
- crates/celld/main/cli.rs+3−0
- crates/celld/memory.rs+140−0
- crates/celld/node_log.rs+129−46
- crates/celld/ownership_store.rs+4−10
- crates/celld/pool.rs+77−0
- crates/celld/r2_cli.rs+592−0
- crates/celld/runtime.rs+12−6
- crates/celld/storage.rs+15−9
- crates/celld/telemetry.rs+1−1
- crates/celld/wake.rs+36−22
- crates/logic/lib.rs+250−65
- crates/logic/log_evict.rs+3−3
- crates/logic/pressure.rs+1−1
- crates/logic/types.rs+125−13
- crates/ltx/src/db.rs+32−1
- docs/README.md+107−26
- docs/cloudflare-compat.md+43−278
- docs/guarantees.md+17−12
- docs/security.md+65−1
- docs/services/containers-flow.svg+97−0
- docs/services/containers.md+215−0
- docs/services/cron-triggers-flow.svg+148−0
- docs/services/cron-triggers.md+140−0
- docs/services/d1-flow.svg+111−0
- docs/services/d1.md+148−0
- docs/services/durable-object-facets-flow.svg+127−0
- docs/services/durable-object-facets.md+108−0
- docs/services/durable-objects-flow.svg+127−0
- docs/services/durable-objects.md+159−0
- docs/services/dynamic-workers-flow.svg+106−0
- docs/services/dynamic-workers.md+151−0
- docs/services/kv-flow.svg+102−0
- docs/services/kv.md+107−0
- docs/services/queues-flow.svg+127−0
- docs/services/queues.md+123−0
- docs/services/r2-flow.svg+64−0
- docs/services/r2.md+121−0
- docs/services/static-assets-flow.svg+183−0
- docs/services/static-assets.md+147−0
- docs/services/workers-flow.svg+111−0
- docs/services/workers.md+83−0
- docs/services/workflows-flow.svg+125−0
- docs/services/workflows.md+123−0
- docs/telemetry.md+3−1
- docs/testing.md+51−65
- docs/wasm.md+7−0
- examples/README.md+3−0
- examples/dynamic-worker-tails/README.md+23−0
- examples/dynamic-worker-tails/index.js+40−0
- examples/dynamic-worker-tails/wrangler.jsonc+6−0
- examples/queues/index.js+29−0
- examples/queues/wrangler.jsonc+18−0
- examples/sandbox/README.md+1−1
- examples/static-assets/public/_headers+2−0
- examples/static-assets/public/_redirects+1−0
- examples/static-assets/public/index.html+11−0
- examples/static-assets/wrangler.jsonc+5−0
modifiedCargo.lock+1−1View file
| @@ -285,7 +285,7 @@ | ||
| 285 | 285 | |
| 286 | 286 | [[package]] |
| 287 | 287 | name = "celld" |
| 288 | -version = "0.5.0" | |
| 288 | +version = "0.5.1" | |
| 289 | 289 | dependencies = [ |
| 290 | 290 | "aes", |
| 291 | 291 | "aes-gcm", |
modifiedREADME.md+32−18View file
| @@ -6,10 +6,10 @@ | ||
| 6 | 6 | on your own machines: Workers, Durable Objects, KV, Queues, D1, R2, |
| 7 | 7 | Workflows, Cron Triggers, and static assets, deployed from the |
| 8 | 8 | `wrangler.json` that you already have. Each object is a cell: a named |
| 9 | -server with its own SQLite database. celld stores the long-term state in a bucket | |
| 10 | -that you own — S3-compatible, Google Cloud Storage, or Azure Blob | |
| 11 | -Storage — and needs no serving control plane and no consensus service. | |
| 12 | -A cell that nothing is serving costs almost nothing. Learn more at | |
| 9 | +server with its own SQLite database. celld stores the long-term state in | |
| 10 | +your S3-compatible, Google Cloud Storage, or Azure Blob Storage bucket. | |
| 11 | +It needs no serving control plane or consensus service. | |
| 12 | +An inactive cell costs almost nothing. Learn more at | |
| 13 | 13 | [celld.dev](https://celld.dev) or read the |
| 14 | 14 | [documentation](https://celld.dev/docs). |
| 15 | 15 | |
| @@ -19,13 +19,12 @@ | ||
| 19 | 19 | node embeds V8 and executes Wrangler bundles. The nodes that share one |
| 20 | 20 | bucket are a fleet, and that bucket holds the deployments, the cell |
| 21 | 21 | state, and small ownership records. A conditional bucket write gives a node the |
| 22 | -ownership of a cell, so exactly one node owns a cell at a time — no | |
| 23 | -membership protocol, no failure detector, no consensus service. Signed | |
| 22 | +ownership of a cell, so exactly one node owns a cell at a time. The fleet | |
| 23 | +needs no membership protocol, failure detector, or consensus service. Signed | |
| 24 | 24 | peer HTTP provides routing and replicated-log transport. |
| 25 | 25 | |
| 26 | -celld captures each committed SQLite write as LTX data, the transaction | |
| 27 | -format the replication uses. A single node proves the write durable by | |
| 28 | -uploading that data to the bucket. A fleet of two or more nodes proves it | |
| 26 | +celld captures each committed SQLite write in the LTX replication format. | |
| 27 | +A single node proves the write durable by uploading that data to the bucket. A fleet of two or more nodes proves it | |
| 29 | 28 | sooner: the owner sends the data to one or two other nodes, and the write |
| 30 | 29 | is durable as soon as they hold it on their disks. celld uploads the data |
| 31 | 30 | to the bucket afterwards. A single node has no other node to send to, so |
| @@ -39,21 +38,23 @@ | ||
| 39 | 38 | |
| 40 | 39 | celld runs the programmatic Workers platform: the runtime, and each binding |
| 41 | 40 | that Cloudflare builds on Workers and Durable Objects. A KV namespace, a |
| 42 | -queue, a D1 database, a Workflow, and the R2 index are each a cell, so | |
| 41 | +queue, a D1 database, and a Workflow are each a cell, so | |
| 43 | 42 | they get the same lease, the same replication, and the same failover as a |
| 44 | -Durable Object. Each row links to a project that deploys as-is: | |
| 43 | +Durable Object. R2 bindings read, write, and list objects directly in the | |
| 44 | +fleet bucket. Each row links to a project that deploys as-is: | |
| 45 | 45 | |
| 46 | 46 | | service | example | |
| 47 | 47 | | --- | --- | |
| 48 | 48 | | Workers: fetch handlers, service bindings, JS RPC, Node.js compat | [`hello`](examples/hello) | |
| 49 | 49 | | Durable Objects: SQLite storage, alarms, hibernating WebSockets | [`counter`](examples/counter) | |
| 50 | 50 | | KV: list, metadata, expiration, bulk import | [`kv`](examples/kv) | |
| 51 | -| Queues: producers, batching consumers, retries, dead letters | [docs](docs/cloudflare-compat.md#queues) | | |
| 51 | +| Queues: producers, batching consumers, retries, dead letters | [`queues`](examples/queues) | | |
| 52 | 52 | | D1: SQL databases, batches, migrations | [`d1`](examples/d1) | |
| 53 | 53 | | R2: reads, writes, lists, multipart uploads | [`r2`](examples/r2) | |
| 54 | 54 | | Workflows: durable steps, sleeps, events, pause and restart | [`workflow`](examples/workflow) | |
| 55 | 55 | | Cron Triggers: one run for each occurrence across the fleet | [`cron`](examples/cron) | |
| 56 | -| Static assets: asset-only or with a Worker, `_headers`, `_redirects` | [docs](docs/cloudflare-compat.md#static-assets) | | |
| 56 | +| Static assets: asset-only or with a Worker, `_headers`, `_redirects` | [`static-assets`](examples/static-assets) | | |
| 57 | +| Dynamic Workers: runtime-loaded code and Tail Worker observability | [`dynamic-worker-tails`](examples/dynamic-worker-tails) | | |
| 57 | 58 | | Containers (experimental): a Durable Object that supervises a container, `@cloudflare/containers` | [`container`](examples/container) | |
| 58 | 59 | | Sandboxes: the Cloudflare Sandbox SDK, `@cloudflare/sandbox`, on a container per sandbox | [`sandbox`](examples/sandbox) | |
| 59 | 60 | |
| @@ -123,8 +124,8 @@ | ||
| 123 | 124 | celld dev |
| 124 | 125 | ``` |
| 125 | 126 | |
| 126 | -The command starts one celld node and uses a local object store. It does not | |
| 127 | -require Docker or a cloud bucket. The Worker listener uses | |
| 127 | +The command starts one celld node with a local object store, so it needs | |
| 128 | +no Docker or cloud bucket. The Worker listener uses | |
| 128 | 129 | `http://127.0.0.1:9876`. Use `celld dev --port PORT` to select a different |
| 129 | 130 | Worker port. Use `celld dev --host IP` to select a different interface. A |
| 130 | 131 | non-loopback IP exposes the Worker listener to the network, and the internal |
| @@ -213,7 +214,7 @@ | ||
| 213 | 214 | A fleet runs one application, and every node loads its latest successfully |
| 214 | 215 | committed deployment from `deploy/current.json`. `celld deploy` invokes |
| 215 | 216 | `esbuild` from `PATH` for Worker code, accepts the supported Wrangler config |
| 216 | -subset — including co-deployed or asset-only static assets — and writes the | |
| 217 | +subset (including co-deployed or asset-only static assets), and writes the | |
| 217 | 218 | deployment objects directly, using the documented types in |
| 218 | 219 | `crates/celld/protocol.rs`. Every node discovers owners and peers from |
| 219 | 220 | bucket leases; there is no account or join service. Run `celld --help` for |
| @@ -232,7 +233,7 @@ | ||
| 232 | 233 | rejects a literal public IP unless you supply `--unsafe-public-advertise`. |
| 233 | 234 | An explicit advertised address requires an explicit internal-listener |
| 234 | 235 | address, and you must route the advertised address to the internal |
| 235 | -listener — celld cannot verify a hostname or a translated port. The first | |
| 236 | +listener, because celld cannot verify a hostname or a translated port. The first | |
| 236 | 237 | current node creates `fleet/peer-auth.json` in the bucket. Cell fetch and RPC |
| 237 | 238 | requests carry a protocol version and depend on the trusted private network. |
| 238 | 239 | Peer-control and reserved-cell operator requests use the fleet HMAC. This HMAC |
| @@ -290,6 +291,17 @@ | ||
| 290 | 291 | --bucket s3://my-cells-bucket |
| 291 | 292 | ``` |
| 292 | 293 | |
| 294 | +`celld r2` reads and writes the objects behind an `r2_buckets` binding. The | |
| 295 | +command reads the fleet bucket directly, so it needs no running node and a | |
| 296 | +release pipeline can publish an artifact before it deploys the Worker: | |
| 297 | + | |
| 298 | +```sh | |
| 299 | +celld r2 put assets app.zip --path dist/app.zip \ | |
| 300 | + --content-type application/zip \ | |
| 301 | + --metadata '{"release":"1.2.3"}' \ | |
| 302 | + --bucket s3://my-cells-bucket | |
| 303 | +``` | |
| 304 | + | |
| 293 | 305 | `celld queue` inspects and controls a deployed Queue. A queue can continue to |
| 294 | 306 | accept messages while delivery is paused: |
| 295 | 307 | |
| @@ -326,7 +338,9 @@ | ||
| 326 | 338 | calculates the working set as `memory.current` less `inactive_file` from |
| 327 | 339 | `memory.stat`, then it removes the measured allocator slack. This calculation |
| 328 | 340 | includes active kernel charges that process RSS does not report, and it excludes |
| 329 | -file pages and allocator pages that celld cannot return by shedding a cell. The | |
| 341 | +file pages and allocator pages that celld cannot return by shedding a cell. | |
| 342 | +Before each sample, celld returns the memory that the C allocator keeps after | |
| 343 | +a cell stops, so a hibernated cell does not hold its storage cache in RSS. The | |
| 330 | 344 | `/state` route reports all four input measurements. |
| 331 | 345 | |
| 332 | 346 | A separate absolute cap applies to the complete cgroup charge at 95% of the |
modifiedcrates/celld/Cargo.toml+1−1View file
| @@ -1,6 +1,6 @@ | ||
| 1 | 1 | [package] |
| 2 | 2 | name = "celld" |
| 3 | -version = "0.5.0" | |
| 3 | +version = "0.5.1" | |
| 4 | 4 | edition = "2021" |
| 5 | 5 | rust-version = "1.94.1" |
| 6 | 6 | license = "Apache-2.0" |
modifiedcrates/celld/actor.rs+82−148View file
| @@ -13,9 +13,10 @@ | ||
| 13 | 13 | use crate::runtime::{CellHost, RuntimeManager}; |
| 14 | 14 | use anyhow::Context as _; |
| 15 | 15 | use celld_logic::{ |
| 16 | - on_event, AdoptedCell, CapacityPeer, CasGuard, CasOutcome, Channel, Config, Effect, Event, | |
| 17 | - Failure, LeaseCasOutcome, NodeLeaseRecord, NodeLeaseSpec, OpId, OwnerRecord, OwnershipOnEvict, | |
| 18 | - Phase, RequestError, Route, State, StopCause, Timer, WebSocketKind, WorkerRoute, | |
| 16 | + on_event, AdoptedCell, CapacityPeer, CasGuard, CasOutcome, CellId, Channel, Config, Effect, | |
| 17 | + Event, EvictionAdmission, Failure, LeaseCasOutcome, NodeLeaseRecord, NodeLeaseSpec, OpId, | |
| 18 | + OwnerRecord, OwnershipOnEvict, Phase, RequestError, Route, State, StopCause, Timer, | |
| 19 | + WebSocketKind, WorkerRoute, | |
| 19 | 20 | }; |
| 20 | 21 | use futures_util::stream::FuturesUnordered; |
| 21 | 22 | use std::collections::{BTreeMap, BTreeSet, HashMap, VecDeque}; |
| @@ -28,8 +29,11 @@ | ||
| 28 | 29 | |
| 29 | 30 | mod local_request; |
| 30 | 31 | mod production; |
| 32 | +pub use celld_logic::{EvictCancellation, EvictError, EvictFailure, EvictRefusal, EvictSuccess}; | |
| 31 | 33 | pub use local_request::{LocalRequest, LocalRequestCompletion, LocalRequestFailure}; |
| 32 | 34 | |
| 35 | +type EvictionReply = oneshot::Sender<Result<EvictSuccess, EvictError>>; | |
| 36 | + | |
| 33 | 37 | const DEFAULT_OPERATION_DEADLINE_MS: u64 = 15_000; |
| 34 | 38 | /// How long a graceful handoff keeps refreshing an uncovered alarm's wake |
| 35 | 39 | /// entry before it gives up and lets the drain deadline decide. |
| @@ -477,7 +481,7 @@ | ||
| 477 | 481 | }, |
| 478 | 482 | Evict { |
| 479 | 483 | cell: String, |
| 480 | - reply: oneshot::Sender<()>, | |
| 484 | + reply: EvictionReply, | |
| 481 | 485 | }, |
| 482 | 486 | InvalidateRemote { |
| 483 | 487 | cell: String, |
| @@ -1100,9 +1104,10 @@ | ||
| 1100 | 1104 | /// realm may still have. Both stop paths therefore retry rather than report, |
| 1101 | 1105 | /// and they share this loop so neither can drift into reporting first. |
| 1102 | 1106 | /// |
| 1103 | -/// The retry is unbounded on purpose. The core arms an operation deadline on | |
| 1104 | -/// the `Cleaning` phase this answers, so a host that never lets go is bounded | |
| 1105 | -/// there rather than by a count guessed here. | |
| 1107 | +/// A bounded eviction checks its retry deadline after a release returns an | |
| 1108 | +/// error. Neither this await nor the core's `Cleaning` phase has an overall | |
| 1109 | +/// timeout. A pending release must not trigger a restart against a database | |
| 1110 | +/// that the old runtime can still own; it can keep the eviction reply pending. | |
| 1106 | 1111 | async fn report_stopped_when_released<F, Fut>( |
| 1107 | 1112 | op: OpId, |
| 1108 | 1113 | cell: String, |
| @@ -1119,8 +1124,8 @@ | ||
| 1119 | 1124 | // An abandoned eviction is the one failure that must not be retried. |
| 1120 | 1125 | // The cell is resident at its own epoch with a request waiting on it, |
| 1121 | 1126 | // and a retry would take the cell the abandonment just gave back. |
| 1122 | - // `RuntimeStopFailed` is the same ending a stop that ran out of time | |
| 1123 | - // reports, and the core answers both by starting the cell in place. | |
| 1127 | + // The core restarts both outcomes in place, but callers must be able | |
| 1128 | + // to distinguish this cancellation from an execution failure. | |
| 1124 | 1129 | if let Some(abandoned) = error.downcast_ref::<crate::replication::EvictionAbandoned>() { |
| 1125 | 1130 | tracing::info!( |
| 1126 | 1131 | event, |
| @@ -1129,7 +1134,7 @@ | ||
| 1129 | 1134 | reason = %abandoned, |
| 1130 | 1135 | "a request reached the cell before the eviction took it; restarting it in place" |
| 1131 | 1136 | ); |
| 1132 | - return CompletedEffect::plain(Event::RuntimeStopFailed { op }); | |
| 1137 | + return CompletedEffect::plain(Event::RuntimeStopCancelled { op }); | |
| 1133 | 1138 | } |
| 1134 | 1139 | if deadline_mono_ms.is_some_and(|deadline| crate::asyncrt::mono_ms() >= deadline) { |
| 1135 | 1140 | tracing::warn!( |
| @@ -1641,11 +1646,17 @@ | ||
| 1641 | 1646 | let _ = self.tx.send(Message::WebSocketClosed { cell, websocket }); |
| 1642 | 1647 | } |
| 1643 | 1648 | |
| 1644 | - pub async fn evict(&self, cell: String) { | |
| 1649 | + /// Try eviction now, or join the eviction already running on this node. | |
| 1650 | + /// Success confirms that operation or settled local absence; later demand | |
| 1651 | + /// can activate the cell again before the caller receives the reply. | |
| 1652 | + pub async fn evict(&self, cell: CellId) -> Result<EvictSuccess, EvictError> { | |
| 1645 | 1653 | let (reply, receive) = oneshot::channel(); |
| 1646 | - if self.tx.send(Message::Evict { cell, reply }).is_ok() { | |
| 1647 | - let _ = receive.await; | |
| 1648 | - } | |
| 1654 | + self.tx | |
| 1655 | + .send(Message::Evict { cell, reply }) | |
| 1656 | + .map_err(|_| EvictError::Failed(EvictFailure::ActorUnavailable))?; | |
| 1657 | + receive | |
| 1658 | + .await | |
| 1659 | + .map_err(|_| EvictError::Failed(EvictFailure::ReplyLost))? | |
| 1649 | 1660 | } |
| 1650 | 1661 | |
| 1651 | 1662 | pub async fn invalidate_remote(&self, cell: String, node: String, epoch: u64) { |
| @@ -1692,8 +1703,21 @@ | ||
| 1692 | 1703 | "draining": runtime |
| 1693 | 1704 | .draining_generations() |
| 1694 | 1705 | .into_iter() |
| 1695 | - .map(|(id, version)| serde_json::json!({"generation": id, "version": version})) | |
| 1706 | + .map(|generation| { | |
| 1707 | + serde_json::json!({ | |
| 1708 | + "generation": generation.id(), | |
| 1709 | + "version": generation.version(), | |
| 1710 | + "isolates": generation.isolate_census(), | |
| 1711 | + }) | |
| 1712 | + }) | |
| 1696 | 1713 | .collect::<Vec<_>>(), |
| 1714 | + // The V8 heaps behind the counters above. A dormant cell | |
| 1715 | + // keeps no isolate of its own, so a cell pool whose | |
| 1716 | + // `live_empty` persists across maintenance passes, or whose | |
| 1717 | + // `retiring` never frees, is memory the node holds for | |
| 1718 | + // nothing -- the residual GCE measured at about 160 KB per | |
| 1719 | + // hibernated cell (measured 2026-09-03). | |
| 1720 | + "isolates": generation.isolate_census(), | |
| 1697 | 1721 | // Resident cells moving to the current generation right now, |
| 1698 | 1722 | // and the generation each resident cell runs: the two numbers |
| 1699 | 1723 | // an operator watches while a deployment converges. |
| @@ -1892,9 +1916,7 @@ | ||
| 1892 | 1916 | handoff_accepts: BTreeMap<u64, (String, HandoffAcceptWaiter)>, |
| 1893 | 1917 | route_timings: BTreeMap<String, CellRouteTiming>, |
| 1894 | 1918 | pending_workers: BTreeMap<u64, oneshot::Sender<WorkerRouted>>, |
| 1895 | - eviction_waiters: BTreeMap<String, Vec<oneshot::Sender<()>>>, | |
| 1896 | - durability_waiters: BTreeMap<u64, (String, Vec<oneshot::Sender<()>>)>, | |
| 1897 | - eviction_stops: BTreeMap<u64, Vec<oneshot::Sender<()>>>, | |
| 1919 | + pending_evictions: BTreeMap<u64, EvictionReply>, | |
| 1898 | 1920 | /// Outputs held by the gate, keyed by request and channel. Every output but |
| 1899 | 1921 | /// a captured `WsHibernatable` frame waits here for the core's `Release`. |
| 1900 | 1922 | gated_responses: BTreeMap<HeldOutputKey, oneshot::Sender<Result<(), RequestError>>>, |
| @@ -2423,12 +2445,10 @@ | ||
| 2423 | 2445 | handoff_accepts: BTreeMap::new(), |
| 2424 | 2446 | route_timings: BTreeMap::new(), |
| 2425 | 2447 | pending_workers: BTreeMap::new(), |
| 2426 | - eviction_waiters: BTreeMap::new(), | |
| 2427 | - durability_waiters: BTreeMap::new(), | |
| 2448 | + pending_evictions: BTreeMap::new(), | |
| 2428 | 2449 | gated_responses: BTreeMap::new(), |
| 2429 | 2450 | ws_gates: BTreeMap::new(), |
| 2430 | 2451 | ws_gated: BTreeMap::new(), |
| 2431 | - eviction_stops: BTreeMap::new(), | |
| 2432 | 2452 | published: BTreeSet::new(), |
| 2433 | 2453 | fail_publish_once, |
| 2434 | 2454 | publishes: 0, |
| @@ -2507,10 +2527,6 @@ | ||
| 2507 | 2527 | websocket, |
| 2508 | 2528 | reply, |
| 2509 | 2529 | } => { |
| 2510 | - let retired_durability = match self.state.phase(&cell) { | |
| 2511 | - Some(Phase::EnsuringDurability { op, .. }) => Some(*op), | |
| 2512 | - _ => None, | |
| 2513 | - }; | |
| 2514 | 2530 | self.pending.insert(request, reply); |
| 2515 | 2531 | let ownership_handoff = handoff_accept.is_some(); |
| 2516 | 2532 | if let Some(waiter) = handoff_accept { |
| @@ -2550,13 +2566,6 @@ | ||
| 2550 | 2566 | out, |
| 2551 | 2567 | ); |
| 2552 | 2568 | self.observe_capacity_wait(&cell); |
| 2553 | - if let Some(op) = retired_durability { | |
| 2554 | - if let Some((_, waiters)) = self.durability_waiters.remove(&op) { | |
| 2555 | - for waiter in waiters { | |
| 2556 | - let _ = waiter.send(()); | |
| 2557 | - } | |
| 2558 | - } | |
| 2559 | - } | |
| 2560 | 2569 | } |
| 2561 | 2570 | Message::CancelRoute { request } => { |
| 2562 | 2571 | self.pending.remove(&request); |
| @@ -2771,14 +2780,8 @@ | ||
| 2771 | 2780 | alarm, |
| 2772 | 2781 | alarm_covered, |
| 2773 | 2782 | } => { |
| 2774 | - // Folded from the old AlarmObserved-then-ActivityFinished pair the | |
| 2775 | - // activity drop sent: observe the alarm and release any retired | |
| 2776 | - // durability waiters, then finish the activity — same events, same | |
| 2777 | - // order, one message instead of two. | |
| 2778 | - let retired_durability = match self.state.phase(&cell) { | |
| 2779 | - Some(Phase::EnsuringDurability { op, .. }) => Some(*op), | |
| 2780 | - _ => None, | |
| 2781 | - }; | |
| 2783 | + // Observe the alarm before releasing the activity. The core | |
| 2784 | + // reports whether that observation cancels an eviction proof. | |
| 2782 | 2785 | self.drive( |
| 2783 | 2786 | Event::AlarmObserved { |
| 2784 | 2787 | cell, |
| @@ -2789,13 +2792,6 @@ | ||
| 2789 | 2792 | }, |
| 2790 | 2793 | out, |
| 2791 | 2794 | ); |
| 2792 | - if let Some(op) = retired_durability { | |
| 2793 | - if let Some((_, waiters)) = self.durability_waiters.remove(&op) { | |
| 2794 | - for waiter in waiters { | |
| 2795 | - let _ = waiter.send(()); | |
| 2796 | - } | |
| 2797 | - } | |
| 2798 | - } | |
| 2799 | 2795 | self.drive(Event::ActivityFinished { request }, out); |
| 2800 | 2796 | } |
| 2801 | 2797 | Message::WebSocketOpened { |
| @@ -2831,10 +2827,6 @@ | ||
| 2831 | 2827 | alarm, |
| 2832 | 2828 | covered, |
| 2833 | 2829 | } => { |
| 2834 | - let retired_durability = match self.state.phase(&cell) { | |
| 2835 | - Some(Phase::EnsuringDurability { op, .. }) => Some(*op), | |
| 2836 | - _ => None, | |
| 2837 | - }; | |
| 2838 | 2830 | self.drive( |
| 2839 | 2831 | Event::AlarmObserved { |
| 2840 | 2832 | cell, |
| @@ -2845,13 +2837,6 @@ | ||
| 2845 | 2837 | }, |
| 2846 | 2838 | out, |
| 2847 | 2839 | ); |
| 2848 | - if let Some(op) = retired_durability { | |
| 2849 | - if let Some((_, waiters)) = self.durability_waiters.remove(&op) { | |
| 2850 | - for waiter in waiters { | |
| 2851 | - let _ = waiter.send(()); | |
| 2852 | - } | |
| 2853 | - } | |
| 2854 | - } | |
| 2855 | 2840 | } |
| 2856 | 2841 | Message::NudgeNodeLease => { |
| 2857 | 2842 | self.drive( |
| @@ -2885,37 +2870,20 @@ | ||
| 2885 | 2870 | ); |
| 2886 | 2871 | } |
| 2887 | 2872 | Message::Evict { reply, .. } if self.preserving => { |
| 2888 | - let _ = reply.send(()); | |
| 2873 | + let _ = reply.send(Err(EvictError::Refused(EvictRefusal::NodeUnavailable))); | |
| 2889 | 2874 | } |
| 2890 | - Message::Evict { cell, reply } if self.state.is_active(&cell) => { | |
| 2891 | - let _ = reply.send(()); | |
| 2875 | + Message::Evict { cell, reply } => { | |
| 2876 | + let request = crate::asyncrt::next_core_request(); | |
| 2877 | + self.pending_evictions.insert(request, reply); | |
| 2878 | + self.drive( | |
| 2879 | + Event::EvictRequested { | |
| 2880 | + request, | |
| 2881 | + cell, | |
| 2882 | + now_mono_ms: crate::asyncrt::mono_ms(), | |
| 2883 | + }, | |
| 2884 | + out, | |
| 2885 | + ); | |
| 2892 | 2886 | } |
| 2893 | - Message::Evict { cell, reply } => match self.state.phase(&cell) { | |
| 2894 | - Some(Phase::Resident { .. }) => { | |
| 2895 | - self.eviction_waiters | |
| 2896 | - .entry(cell.clone()) | |
| 2897 | - .or_default() | |
| 2898 | - .push(reply); | |
| 2899 | - self.drive(Event::Evict { cell }, out); | |
| 2900 | - } | |
| 2901 | - Some(Phase::EnsuringDurability { op, .. }) => { | |
| 2902 | - self.durability_waiters | |
| 2903 | - .entry(*op) | |
| 2904 | - .or_insert_with(|| (cell, Vec::new())) | |
| 2905 | - .1 | |
| 2906 | - .push(reply); | |
| 2907 | - } | |
| 2908 | - Some(Phase::Cleaning { | |
| 2909 | - op, | |
| 2910 | - cause: StopCause::Evict { .. }, | |
| 2911 | - .. | |
| 2912 | - }) => { | |
| 2913 | - self.eviction_stops.entry(*op).or_default().push(reply); | |
| 2914 | - } | |
| 2915 | - _ => { | |
| 2916 | - let _ = reply.send(()); | |
| 2917 | - } | |
| 2918 | - }, | |
| 2919 | 2887 | Message::InvalidateRemote { |
| 2920 | 2888 | cell, |
| 2921 | 2889 | node, |
| @@ -3055,62 +3023,17 @@ | ||
| 3055 | 3023 | let mut events = VecDeque::from([first]); |
| 3056 | 3024 | while let Some(event) = events.pop_front() { |
| 3057 | 3025 | self.close_handoff_phase(&event); |
| 3058 | - let durability = match &event { | |
| 3059 | - Event::DurabilityChecked { op, .. } => Some(*op), | |
| 3060 | - // A deadline resolves the same operation the proof would | |
| 3061 | - // have, so it has to release the same waiters. Without this | |
| 3062 | - // the core abandons the eviction and the caller that asked | |
| 3063 | - // for it stays blocked on a proof that is no longer coming. | |
| 3064 | - Event::TimerFired { | |
| 3065 | - timer: Timer::OperationDeadline { op }, | |
| 3066 | - .. | |
| 3067 | - } => Some(*op), | |
| 3068 | - _ => None, | |
| 3069 | - }; | |
| 3070 | - // A bounded stop that gave up also ends the eviction the | |
| 3071 | - // waiters asked about; without this branch `/evict/` waited | |
| 3072 | - // forever on a cell that had already restarted in place. | |
| 3073 | - let stopped = match &event { | |
| 3074 | - Event::RuntimeStopped { op } | Event::RuntimeStopFailed { op } => Some(*op), | |
| 3075 | - _ => None, | |
| 3076 | - }; | |
| 3077 | - // The stop has an ending, so its signal can no longer change | |
| 3078 | - // anything. Dropping it here keeps the map the size of the stops | |
| 3079 | - // actually in flight. | |
| 3080 | - if let Some(op) = stopped { | |
| 3081 | - self.eviction_abandons.remove(&op); | |
| 3026 | + if let Event::RuntimeStopped { op } | |
| 3027 | + | Event::RuntimeStopFailed { op } | |
| 3028 | + | Event::RuntimeStopCancelled { op } = &event | |
| 3029 | + { | |
| 3030 | + self.eviction_abandons.remove(op); | |
| 3082 | 3031 | } |
| 3083 | 3032 | let effects = apply_core_event(&mut self.state, event); |
| 3084 | - if let Some(op) = durability { | |
| 3085 | - if let Some((_, waiters)) = self.durability_waiters.remove(&op) { | |
| 3086 | - let stop = effects.iter().find_map(|effect| match effect { | |
| 3087 | - Effect::StopRuntime { | |
| 3088 | - op, | |
| 3089 | - cause: StopCause::Evict { .. }, | |
| 3090 | - .. | |
| 3091 | - } => Some(*op), | |
| 3092 | - _ => None, | |
| 3093 | - }); | |
| 3094 | - if let Some(stop) = stop { | |
| 3095 | - self.eviction_stops.entry(stop).or_default().extend(waiters); | |
| 3096 | - } else { | |
| 3097 | - for waiter in waiters { | |
| 3098 | - let _ = waiter.send(()); | |
| 3099 | - } | |
| 3100 | - } | |
| 3101 | - } | |
| 3102 | - } | |
| 3103 | 3033 | for effect in effects { |
| 3104 | 3034 | self.execute(effect, &mut events, out); |
| 3105 | 3035 | } |
| 3106 | 3036 | self.settle_handoff_accepts(); |
| 3107 | - if let Some(op) = stopped { | |
| 3108 | - if let Some(waiters) = self.eviction_stops.remove(&op) { | |
| 3109 | - for waiter in waiters { | |
| 3110 | - let _ = waiter.send(()); | |
| 3111 | - } | |
| 3112 | - } | |
| 3113 | - } | |
| 3114 | 3037 | if self.validate_invariants { |
| 3115 | 3038 | self.state.validate().expect("celld core invariant"); |
| 3116 | 3039 | } |
| @@ -3776,6 +3699,21 @@ | ||
| 3776 | 3699 | } |
| 3777 | 3700 | immediate.push_back(Event::Published { op, result }); |
| 3778 | 3701 | } |
| 3702 | + Effect::EvictionAdmission { request, result } => { | |
| 3703 | + let result = match result { | |
| 3704 | + Ok(EvictionAdmission::Pending) => return, | |
| 3705 | + Ok(EvictionAdmission::Absent) => Ok(EvictSuccess::AlreadyAbsent), | |
| 3706 | + Err(error) => Err(error), | |
| 3707 | + }; | |
| 3708 | + if let Some(reply) = self.pending_evictions.remove(&request) { | |
| 3709 | + let _ = reply.send(result); | |
| 3710 | + } | |
| 3711 | + } | |
| 3712 | + Effect::EvictionFinished { request, result } => { | |
| 3713 | + if let Some(reply) = self.pending_evictions.remove(&request) { | |
| 3714 | + let _ = reply.send(result); | |
| 3715 | + } | |
| 3716 | + } | |
| 3779 | 3717 | Effect::EnsureDurable { |
| 3780 | 3718 | op, |
| 3781 | 3719 | cell, |
| @@ -3795,8 +3733,6 @@ | ||
| 3795 | 3733 | ), |
| 3796 | 3734 | ); |
| 3797 | 3735 | } |
| 3798 | - let waiters = self.eviction_waiters.remove(&cell).unwrap_or_default(); | |
| 3799 | - self.durability_waiters.insert(op, (cell.clone(), waiters)); | |
| 3800 | 3736 | if let Some(runtime) = self.host.clone() { |
| 3801 | 3737 | // A hot cell can merge thousands of staged LTX rows while |
| 3802 | 3738 | // this future is between awaits. Keep that synchronous |
| @@ -4144,13 +4080,6 @@ | ||
| 4144 | 4080 | } |
| 4145 | 4081 | } |
| 4146 | 4082 | Effect::CompleteWorker { request, route } => { |
| 4147 | - if let Some(op) = route.as_ref().and_then(|route| route.retired_durability) { | |
| 4148 | - if let Some((_, waiters)) = self.durability_waiters.remove(&op) { | |
| 4149 | - for waiter in waiters { | |
| 4150 | - let _ = waiter.send(()); | |
| 4151 | - } | |
| 4152 | - } | |
| 4153 | - } | |
| 4154 | 4083 | if let Some(reply) = self.pending_workers.remove(&request) { |
| 4155 | 4084 | let reserved = route.is_some(); |
| 4156 | 4085 | if reply.send(WorkerRouted { request, route }).is_err() && reserved { |
| @@ -4234,7 +4163,6 @@ | ||
| 4234 | 4163 | // `capacity_waiting` is queued behind residency. The census says where |
| 4235 | 4164 | // every cell is, which `occupied` cannot: it counts residency, so a |
| 4236 | 4165 | // node part-way through thousands of cold starts reports almost none. |
| 4237 | - // Issue #50 is open because none of this was recorded at the time. | |
| 4238 | 4166 | let phases = self |
| 4239 | 4167 | .state |
| 4240 | 4168 | .phase_census() |
| @@ -4243,7 +4171,7 @@ | ||
| 4243 | 4171 | .collect::<Vec<_>>() |
| 4244 | 4172 | .join(","); |
| 4245 | 4173 | format!( |
| 4246 | - "{{\"ownership\":{:?},\"owned_cells\":{},\"occupied\":{},\"quiescing\":{},\"evicting\":{},\"releasing\":{},\"adopting\":{},\"restoring\":{},\"activating\":{},\"activation_waiting\":{},\"capacity_waiting\":{},\"phases\":{{{}}},\"handed_off\":{},\"handoff_failed\":{},\"rebalanced\":{},\"rebalance_failed\":{},\"remote_route_refreshes\":{},\"shedding\":{},\"rss_bytes\":{},\"in_use_bytes\":{},\"cgroup_working_set_bytes\":{},\"cgroup_current_bytes\":{},\"node_load\":{},\"residents\":[{}],\"published\":[{}],\"publishes\":{},\"stops\":{}}}", | |
| 4174 | + "{{\"ownership\":{:?},\"owned_cells\":{},\"occupied\":{},\"quiescing\":{},\"evicting\":{},\"releasing\":{},\"adopting\":{},\"restoring\":{},\"activating\":{},\"activation_waiting\":{},\"capacity_waiting\":{},\"phases\":{{{}}},\"handed_off\":{},\"handoff_failed\":{},\"rebalanced\":{},\"rebalance_failed\":{},\"remote_route_refreshes\":{},\"shedding\":{},\"rss_bytes\":{},\"in_use_bytes\":{},\"allocator\":{},\"libc_malloc\":{},\"cgroup_working_set_bytes\":{},\"cgroup_current_bytes\":{},\"node_load\":{},\"residents\":[{}],\"published\":[{}],\"publishes\":{},\"stops\":{}}}", | |
| 4247 | 4175 | self.ownership.name(), |
| 4248 | 4176 | self.state.owned_cells(), |
| 4249 | 4177 | self.state.occupied(), |
| @@ -4266,6 +4194,12 @@ | ||
| 4266 | 4194 | .map_or_else(|| "null".to_string(), |reason| format!("{reason:?}")), |
| 4267 | 4195 | memory.rss_bytes, |
| 4268 | 4196 | memory.in_use_bytes, |
| 4197 | + // The allocator's split of the two numbers above. `None` | |
| 4198 | + // serializes as null, so a failed read leaves the rest intact. | |
| 4199 | + serde_json::to_string(&crate::memory::allocator_stats()) | |
| 4200 | + .unwrap_or_else(|_| "null".to_string()), | |
| 4201 | + serde_json::to_string(&crate::memory::libc_malloc_stats()) | |
| 4202 | + .unwrap_or_else(|_| "null".to_string()), | |
| 4269 | 4203 | memory |
| 4270 | 4204 | .cgroup_working_set_bytes |
| 4271 | 4205 | .map_or_else(|| "null".to_string(), |bytes| bytes.to_string()), |
modifiedcrates/celld/assets.rs+8−2View file
| @@ -1007,14 +1007,20 @@ | ||
| 1007 | 1007 | } |
| 1008 | 1008 | |
| 1009 | 1009 | fn strip_port(host: &str) -> &str { |
| 1010 | - if host.starts_with('[') { | |
| 1011 | - return host.find(']').map_or(host, |end| &host[1..end]); | |
| 1010 | + let original = host; | |
| 1011 | + if let Some(host) = host.strip_prefix('[') { | |
| 1012 | + return host.split_once(']').map_or(original, |(host, _)| host); | |
| 1012 | 1013 | } |
| 1013 | 1014 | host.rsplit_once(':') |
| 1014 | 1015 | .filter(|(_, port)| port.bytes().all(|byte| byte.is_ascii_digit())) |
| 1015 | 1016 | .map_or(host, |(host, _)| host) |
| 1016 | 1017 | } |
| 1017 | 1018 | |
| 1019 | +#[cfg(all(test, celld_internal_tests))] | |
| 1020 | +mod internal_tests { | |
| 1021 | + include!(env!("CELLD_INTERNAL_ASSETS_TESTS")); | |
| 1022 | +} | |
| 1023 | + | |
| 1018 | 1024 | fn route(index: &AssetIndex, path: &str, include_not_found: bool) -> Route { |
| 1019 | 1025 | let entries = &index.entries; |
| 1020 | 1026 | let html = index |
modifiedcrates/celld/bucket.rs+73−25View file
| @@ -58,6 +58,11 @@ | ||
| 58 | 58 | use std::sync::Arc; |
| 59 | 59 | use std::time::Duration; |
| 60 | 60 | |
| 61 | +#[cfg(all(test, celld_internal_tests))] | |
| 62 | +mod internal_tests { | |
| 63 | + include!(env!("CELLD_INTERNAL_BUCKET_TESTS")); | |
| 64 | +} | |
| 65 | + | |
| 61 | 66 | /// Explicit credentials for a managed installation; everything else comes |
| 62 | 67 | /// from the standard `AWS_*` environment. |
| 63 | 68 | pub struct StaticCredentials { |
| @@ -137,6 +142,28 @@ | ||
| 137 | 142 | StorageBackend::Gcs => "x-goog-if-generation-match", |
| 138 | 143 | } |
| 139 | 144 | } |
| 145 | + | |
| 146 | + /// How a user-metadata name that celld writes is spelled on this | |
| 147 | + /// backend. | |
| 148 | + /// | |
| 149 | + /// Azure Blob Storage requires a metadata name to be a C# identifier, | |
| 150 | + /// and it refuses the whole write with `400 InvalidMetadata` when a name | |
| 151 | + /// holds a hyphen. celld names such as `celld-r2` failed every R2 write | |
| 152 | + /// and lost every telemetry batch on an `az://` bucket | |
| 153 | + /// (denoland/celld#209). Azure therefore gets an underscore for each | |
| 154 | + /// hyphen, and [`BlobAttributes::metadata_value`] reads either spelling. | |
| 155 | + /// | |
| 156 | + /// The other backends keep the hyphen. An object that a fleet already | |
| 157 | + /// wrote carries the hyphenated name, and a proxy in front of an | |
| 158 | + /// S3-compatible store can drop a header name that holds an underscore | |
| 159 | + /// (nginx does by default). The LTX timestamp key makes the same | |
| 160 | + /// per-backend choice in `celld_ltx::TimestampMetadataKey`. | |
| 161 | + fn metadata_name(self, name: &str) -> Cow<'_, str> { | |
| 162 | + match self { | |
| 163 | + StorageBackend::Azure => Cow::Owned(name.replace('-', "_")), | |
| 164 | + StorageBackend::S3 | StorageBackend::Gcs | StorageBackend::Local => Cow::Borrowed(name), | |
| 165 | + } | |
| 166 | + } | |
| 140 | 167 | } |
| 141 | 168 | |
| 142 | 169 | /// One object-store bucket, optionally scoped to a key prefix. Cheap to |
| @@ -363,6 +390,8 @@ | ||
| 363 | 390 | /// `metadata` is the backend's user metadata, kept under its own |
| 364 | 391 | /// `x-amz-meta-` / `x-goog-meta-` / `x-ms-meta-` prefix; what an R2 |
| 365 | 392 | /// binding puts in there is the binding's business, not this module's. |
| 393 | +/// The one thing this module decides is how a written name is spelled, | |
| 394 | +/// because only this module knows which backend refuses which name. | |
| 366 | 395 | #[derive(Default, Clone)] |
| 367 | 396 | pub struct BlobAttributes { |
| 368 | 397 | pub content_type: Option<String>, |
| @@ -392,8 +421,9 @@ | ||
| 392 | 421 | } |
| 393 | 422 | } |
| 394 | 423 | |
| 395 | - /// The same, as the store's write-side attribute set. | |
| 396 | - fn write(&self) -> Attributes { | |
| 424 | + /// The same, as the store's write-side attribute set, with each | |
| 425 | + /// metadata name spelled for `backend`. | |
| 426 | + fn write(&self, backend: StorageBackend) -> Attributes { | |
| 397 | 427 | let mut attributes = Attributes::new(); |
| 398 | 428 | let mut set = |attribute: Attribute, value: &Option<String>| { |
| 399 | 429 | if let Some(value) = value { |
| @@ -407,12 +437,29 @@ | ||
| 407 | 437 | set(Attribute::CacheControl, &self.cache_control); |
| 408 | 438 | for (name, value) in &self.metadata { |
| 409 | 439 | attributes.insert( |
| 410 | - Attribute::Metadata(Cow::Owned(name.clone())), | |
| 440 | + Attribute::Metadata(Cow::Owned(backend.metadata_name(name).into_owned())), | |
| 411 | 441 | value.clone().into(), |
| 412 | 442 | ); |
| 413 | 443 | } |
| 414 | 444 | attributes |
| 415 | 445 | } |
| 446 | + | |
| 447 | + /// The value under a metadata name that celld writes, in whichever | |
| 448 | + /// spelling the backend stored. A store can fold the case of a name, so | |
| 449 | + /// case does not matter. Both spellings match on every backend, so an | |
| 450 | + /// object copied out of an Azure container into another store still | |
| 451 | + /// reads. | |
| 452 | + pub fn metadata_value(&self, name: &str) -> Option<&str> { | |
| 453 | + self.metadata | |
| 454 | + .iter() | |
| 455 | + .find(|(stored, _)| { | |
| 456 | + stored.len() == name.len() | |
| 457 | + && stored.bytes().zip(name.bytes()).all(|(stored, wanted)| { | |
| 458 | + stored.eq_ignore_ascii_case(&wanted) || (stored == b'_' && wanted == b'-') | |
| 459 | + }) | |
| 460 | + }) | |
| 461 | + .map(|(_, value)| value.as_str()) | |
| 462 | + } | |
| 416 | 463 | } |
| 417 | 464 | |
| 418 | 465 | /// What every answer about an object knows, whatever asked for it. |
| @@ -857,9 +904,10 @@ | ||
| 857 | 904 | Ok(()) |
| 858 | 905 | } |
| 859 | 906 | |
| 860 | - /// Size plus one user-metadata value (`x-amz-meta-*` / `x-goog-meta-*`), | |
| 861 | - /// or `None` when the key does not exist. A plain `head` cannot see | |
| 862 | - /// user metadata; this one can. | |
| 907 | + /// Size plus one user-metadata value (`x-amz-meta-*` / `x-goog-meta-*` | |
| 908 | + /// / `x-ms-meta-*`), or `None` when the key does not exist. A plain | |
| 909 | + /// `head` cannot see user metadata; this one can, under either spelling | |
| 910 | + /// of the name. | |
| 863 | 911 | pub async fn head_with_meta( |
| 864 | 912 | &self, |
| 865 | 913 | key: &str, |
| @@ -876,10 +924,9 @@ | ||
| 876 | 924 | .await |
| 877 | 925 | { |
| 878 | 926 | Ok(result) => { |
| 879 | - let value = result | |
| 880 | - .attributes | |
| 881 | - .get(&Attribute::Metadata(name.to_string().into())) | |
| 882 | - .map(|value| value.as_ref().to_string()); | |
| 927 | + let value = BlobAttributes::read(&result.attributes) | |
| 928 | + .metadata_value(name) | |
| 929 | + .map(str::to_string); | |
| 883 | 930 | Ok(Some((result.meta.size, value))) |
| 884 | 931 | } |
| 885 | 932 | Err(Error::NotFound { .. }) => Ok(None), |
| @@ -889,7 +936,8 @@ | ||
| 889 | 936 | } |
| 890 | 937 | } |
| 891 | 938 | |
| 892 | - /// Plain write carrying user metadata (`x-amz-meta-*` / `x-goog-meta-*`). | |
| 939 | + /// Plain write carrying user metadata (`x-amz-meta-*` / `x-goog-meta-*` | |
| 940 | + /// / `x-ms-meta-*`), each name spelled for the backend. | |
| 893 | 941 | pub async fn put_with_meta( |
| 894 | 942 | &self, |
| 895 | 943 | key: &str, |
| @@ -897,15 +945,15 @@ | ||
| 897 | 945 | meta: &[(&'static str, &str)], |
| 898 | 946 | ) -> anyhow::Result<()> { |
| 899 | 947 | let key = self.key(key); |
| 900 | - let mut attributes = Attributes::new(); | |
| 901 | - for (name, value) in meta { | |
| 902 | - attributes.insert( | |
| 903 | - Attribute::Metadata(Cow::Borrowed(name)), | |
| 904 | - value.to_string().into(), | |
| 905 | - ); | |
| 906 | - } | |
| 948 | + let attributes = BlobAttributes { | |
| 949 | + metadata: meta | |
| 950 | + .iter() | |
| 951 | + .map(|(name, value)| (name.to_string(), value.to_string())) | |
| 952 | + .collect(), | |
| 953 | + ..BlobAttributes::default() | |
| 954 | + }; | |
| 907 | 955 | let options = PutOptions { |
| 908 | - attributes, | |
| 956 | + attributes: attributes.write(self.backend), | |
| 909 | 957 | ..PutOptions::default() |
| 910 | 958 | }; |
| 911 | 959 | self.store |
| @@ -1318,7 +1366,7 @@ | ||
| 1318 | 1366 | let scoped = self.key(key); |
| 1319 | 1367 | let options = PutOptions { |
| 1320 | 1368 | mode, |
| 1321 | - attributes: attributes.write(), | |
| 1369 | + attributes: attributes.write(self.backend), | |
| 1322 | 1370 | ..PutOptions::default() |
| 1323 | 1371 | }; |
| 1324 | 1372 | match store |
| @@ -1393,13 +1441,13 @@ | ||
| 1393 | 1441 | let meta = |
| 1394 | 1442 | meta.with_context(|| format!("list {}://{}/{path}", self.scheme(), self.name))?; |
| 1395 | 1443 | let key = self.unkey(meta.location.as_ref()); |
| 1396 | - if !key.starts_with(prefix) { | |
| 1444 | + let Some(remainder) = key.strip_prefix(prefix) else { | |
| 1397 | 1445 | continue; |
| 1398 | - } | |
| 1446 | + }; | |
| 1399 | 1447 | let group = delimiter.and_then(|delimiter| { |
| 1400 | - key[prefix.len()..] | |
| 1448 | + remainder | |
| 1401 | 1449 | .find(delimiter) |
| 1402 | - .map(|at| key[..prefix.len() + at + delimiter.len()].to_string()) | |
| 1450 | + .map(|at| format!("{prefix}{}", &remainder[..at + delimiter.len()])) | |
| 1403 | 1451 | }); |
| 1404 | 1452 | // A prefix already rolled up costs nothing and does not end the |
| 1405 | 1453 | // page: it is the same entry the caller has already been given. |
| @@ -1444,7 +1492,7 @@ | ||
| 1444 | 1492 | ) -> anyhow::Result<Box<dyn MultipartUpload>> { |
| 1445 | 1493 | let key = self.key(key); |
| 1446 | 1494 | let options = PutMultipartOptions { |
| 1447 | - attributes: attributes.write(), | |
| 1495 | + attributes: attributes.write(self.backend), | |
| 1448 | 1496 | ..PutMultipartOptions::default() |
| 1449 | 1497 | }; |
| 1450 | 1498 | self.store |
modifiedcrates/celld/cli_output.rs+21−0View file
| @@ -158,6 +158,27 @@ | ||
| 158 | 158 | self.finish() |
| 159 | 159 | } |
| 160 | 160 | |
| 161 | + /// One opaque payload that arrives in pieces, byte for byte. | |
| 162 | + /// | |
| 163 | + /// The same contract as [`Self::bytes`], and separate from it because an | |
| 164 | + /// R2 object can be far larger than the memory the command runs in. A | |
| 165 | + /// closed reader ends the drain rather than reading the rest of a | |
| 166 | + /// multi-gigabyte body nobody wants. | |
| 167 | + pub async fn stream( | |
| 168 | + mut self, | |
| 169 | + mut body: impl futures_util::Stream<Item = Result<Vec<u8>, String>> + Unpin, | |
| 170 | + ) -> anyhow::Result<()> { | |
| 171 | + use futures_util::StreamExt as _; | |
| 172 | + while let Some(chunk) = body.next().await { | |
| 173 | + let chunk = chunk.map_err(anyhow::Error::msg)?; | |
| 174 | + self.sink.write(|data| data.write_all(&chunk))?; | |
| 175 | + if self.sink.closed { | |
| 176 | + break; | |
| 177 | + } | |
| 178 | + } | |
| 179 | + self.finish() | |
| 180 | + } | |
| 181 | + | |
| 161 | 182 | /// Write one formatted line and flush it before returning. |
| 162 | 183 | /// |
| 163 | 184 | /// The method takes `fmt::Arguments`, so a protocol caller can format the |
modifiedcrates/celld/deploy.rs+267−47View file
| @@ -56,6 +56,8 @@ | ||
| 56 | 56 | "worker_loaders", |
| 57 | 57 | "containers", |
| 58 | 58 | "no_bundle", |
| 59 | + "define", | |
| 60 | + "rules", | |
| 59 | 61 | ]; |
| 60 | 62 | |
| 61 | 63 | /// The Durable Object class every D1 database runs as. It is supplied by the |
| @@ -284,6 +286,8 @@ | ||
| 284 | 286 | /// bundle, so it must not depend on the working directory celld was |
| 285 | 287 | /// invoked from — identical source would otherwise hash two ways. |
| 286 | 288 | entry: Option<String>, |
| 289 | + /// What the config's `define` and `rules` add to the esbuild run. | |
| 290 | + bundle: BundleConfig, | |
| 287 | 291 | assets: Option<ProjectAssets>, |
| 288 | 292 | metadata: Value, |
| 289 | 293 | do_classes: Vec<String>, |
| @@ -297,6 +301,69 @@ | ||
| 297 | 301 | containers: Vec<ContainerDecl>, |
| 298 | 302 | } |
| 299 | 303 | |
| 304 | +/// The two Wrangler bundling knobs that celld forwards to esbuild. | |
| 305 | +/// | |
| 306 | +/// Both are pass-throughs, so celld validates their shape and leaves their | |
| 307 | +/// meaning to esbuild. They travel together because both are build inputs and | |
| 308 | +/// neither reaches the deployment metadata: a change to either changes the | |
| 309 | +/// bundle bytes, and the deployment version hashes those. | |
| 310 | +struct BundleConfig { | |
| 311 | + /// `define` as `--define:KEY=VALUE`. Each value is a JavaScript | |
| 312 | + /// expression, which is what Wrangler and esbuild both take. | |
| 313 | + define: BTreeMap<String, String>, | |
| 314 | + /// `rules` as `--loader:.EXT=LOADER`, plus celld's own default rule. | |
| 315 | + loaders: BTreeMap<String, Loader>, | |
| 316 | +} | |
| 317 | + | |
| 318 | +/// The esbuild loaders a Wrangler module rule can ask for. | |
| 319 | +#[derive(Clone, Copy, PartialEq, Eq, Debug)] | |
| 320 | +enum Loader { | |
| 321 | + /// Wrangler's `Text`. The file becomes a string in the bundle. | |
| 322 | + Text, | |
| 323 | + /// Wrangler's `Data`. The file becomes a byte array in the bundle. | |
| 324 | + Binary, | |
| 325 | + /// Wrangler's `CompiledWasm`. The file becomes a sibling module that the | |
| 326 | + /// runtime serves as a compiled `WebAssembly.Module`. | |
| 327 | + Copy, | |
| 328 | +} | |
| 329 | + | |
| 330 | +impl Loader { | |
| 331 | + fn esbuild_name(self) -> &'static str { | |
| 332 | + match self { | |
| 333 | + Loader::Text => "text", | |
| 334 | + Loader::Binary => "binary", | |
| 335 | + Loader::Copy => "copy", | |
| 336 | + } | |
| 337 | + } | |
| 338 | + | |
| 339 | + /// The `rules[].type` a config writes for this loader. An error names the | |
| 340 | + /// config's own word, not celld's internal one. | |
| 341 | + fn rule_type(self) -> &'static str { | |
| 342 | + match self { | |
| 343 | + Loader::Text => "Text", | |
| 344 | + Loader::Binary => "Data", | |
| 345 | + Loader::Copy => "CompiledWasm", | |
| 346 | + } | |
| 347 | + } | |
| 348 | +} | |
| 349 | + | |
| 350 | +impl Default for BundleConfig { | |
| 351 | + fn default() -> Self { | |
| 352 | + // Wasm is a sibling module (Wrangler's built-in `CompiledWasm` rule). | |
| 353 | + // The `copy` loader makes esbuild resolve each wasm import like any | |
| 354 | + // other import (importer-relative, node_modules, deduplicated) and | |
| 355 | + // rewrite the specifier to the copied file, so the bundle and the | |
| 356 | + // emitted files agree on names. It lives in the same map as the | |
| 357 | + // configured rules, so a config that gives `.wasm` a conflicting rule | |
| 358 | + // is refused by the same check that catches two conflicting rules, | |
| 359 | + // rather than emitting two `--loader` arguments for one extension. | |
| 360 | + Self { | |
| 361 | + define: BTreeMap::new(), | |
| 362 | + loaders: BTreeMap::from([(".wasm".to_string(), Loader::Copy)]), | |
| 363 | + } | |
| 364 | + } | |
| 365 | +} | |
| 366 | + | |
| 300 | 367 | /// One `containers[]` entry as written, before its image is resolved. |
| 301 | 368 | #[derive(Clone, Debug, serde::Serialize)] |
| 302 | 369 | struct ContainerDecl { |
| @@ -550,7 +617,7 @@ | ||
| 550 | 617 | wasm.sort_by(|a, b| a.0.cmp(&b.0)); |
| 551 | 618 | Ok(BundleOutput { bundle, wasm }) |
| 552 | 619 | } else { |
| 553 | - run_esbuild(&root, entry) | |
| 620 | + run_esbuild(&root, entry, &project.bundle) | |
| 554 | 621 | } |
| 555 | 622 | }) |
| 556 | 623 | .transpose()?; |
| @@ -1248,6 +1315,24 @@ | ||
| 1248 | 1315 | if no_bundle && main.is_none() { |
| 1249 | 1316 | bail!("config sets `no_bundle` without `main`"); |
| 1250 | 1317 | } |
| 1318 | + let bundle = read_bundle_config(object)?; | |
| 1319 | + // `define` and `rules` describe the esbuild run, and `no_bundle` is the | |
| 1320 | + // absence of one. Accepting both would produce a deployment that silently | |
| 1321 | + // omits every substitution the config asks for, which is the failure the | |
| 1322 | + // caller wrote those keys to prevent. | |
| 1323 | + if no_bundle { | |
| 1324 | + let ignored: Vec<&str> = ["define", "rules"] | |
| 1325 | + .into_iter() | |
| 1326 | + .filter(|key| object.contains_key(*key)) | |
| 1327 | + .collect(); | |
| 1328 | + if !ignored.is_empty() { | |
| 1329 | + bail!( | |
| 1330 | + "config sets `no_bundle` with `{}`; those keys only change the \ | |
| 1331 | + esbuild run, and `no_bundle` does not run esbuild", | |
| 1332 | + ignored.join("` and `") | |
| 1333 | + ); | |
| 1334 | + } | |
| 1335 | + } | |
| 1251 | 1336 | let assets = object |
| 1252 | 1337 | .get("assets") |
| 1253 | 1338 | .map(|value| read_asset_project(value, root, object)) |
| @@ -1736,14 +1821,18 @@ | ||
| 1736 | 1821 | if !valid_binding(binding) { |
| 1737 | 1822 | bail!("invalid worker loader binding name: {binding:?}"); |
| 1738 | 1823 | } |
| 1739 | - // Cloudflare carries the per-loader Dynamic Workers options inside the | |
| 1740 | - // entry: `limits`, `tails`, and `allowExperimental`. celld honours none | |
| 1741 | - // of them, so accepting the key would deploy the project clean and drop | |
| 1742 | - // the option the author asked for. This follows the r2 `jurisdiction` | |
| 1743 | - // refusal above, and it is the config half of the gaps #836 tracks. | |
| 1824 | + // Wrangler's worker_loaders entries contain only a binding name. | |
| 1825 | + // Resource limits and tail Fetchers belong to WorkerCode, because the | |
| 1826 | + // loader can create Workers with different limits and tail targets. | |
| 1827 | + // Refuse misplaced options instead of deploying without their effect. | |
| 1744 | 1828 | for key in loader.keys() { |
| 1745 | 1829 | if key != "binding" { |
| 1746 | - bail!("worker loader {binding} sets `{key}`, which celld does not have"); | |
| 1830 | + match key.as_str() { | |
| 1831 | + "limits" => bail!("worker loader {binding} sets `limits`; set limits in WorkerCode or getEntrypoint()"), | |
| 1832 | + "tails" => bail!("worker loader {binding} sets `tails`; set tails in WorkerCode"), | |
| 1833 | + "allowExperimental" => bail!("worker loader {binding} sets `allowExperimental`, which celld does not support"), | |
| 1834 | + _ => bail!("worker loader {binding} sets `{key}`, which is not a supported worker_loaders option"), | |
| 1835 | + } | |
| 1747 | 1836 | } |
| 1748 | 1837 | } |
| 1749 | 1838 | bindings.push(json!({ |
| @@ -1850,6 +1939,7 @@ | ||
| 1850 | 1939 | script_name, |
| 1851 | 1940 | no_bundle, |
| 1852 | 1941 | entry: main, |
| 1942 | + bundle, | |
| 1853 | 1943 | assets, |
| 1854 | 1944 | metadata: Value::Object(metadata), |
| 1855 | 1945 | do_classes, |
| @@ -1864,6 +1954,114 @@ | ||
| 1864 | 1954 | }) |
| 1865 | 1955 | } |
| 1866 | 1956 | |
| 1957 | +/// The config's `define` and `rules`, as esbuild arguments. | |
| 1958 | +/// | |
| 1959 | +/// Wrangler owns the spelling of both keys, so celld reads them as written | |
| 1960 | +/// rather than inventing a celld-only escape hatch: a project keeps one | |
| 1961 | +/// config, and a later move back to Wrangler bundles the same way. | |
| 1962 | +fn read_bundle_config(object: &Map<String, Value>) -> anyhow::Result<BundleConfig> { | |
| 1963 | + let mut bundle = BundleConfig::default(); | |
| 1964 | + match object.get("define") { | |
| 1965 | + None => {} | |
| 1966 | + Some(Value::Object(entries)) => { | |
| 1967 | + for (key, value) in entries { | |
| 1968 | + let Some(value) = value.as_str() else { | |
| 1969 | + bail!("config `define` value for {key:?} must be a string"); | |
| 1970 | + }; | |
| 1971 | + // esbuild takes one `--define:KEY=VALUE` argument and splits | |
| 1972 | + // it at the first `=`. A key carrying `=` would move that | |
| 1973 | + // split and define a different name than the config names, | |
| 1974 | + // and a key carrying whitespace or a control character cannot | |
| 1975 | + // be a JavaScript reference at all. | |
| 1976 | + if key.is_empty() | |
| 1977 | + || key.contains('=') | |
| 1978 | + || key.chars().any(|c| c.is_whitespace() || c.is_control()) | |
| 1979 | + { | |
| 1980 | + bail!("invalid `define` key: {key:?}"); | |
| 1981 | + } | |
| 1982 | + bundle.define.insert(key.clone(), value.to_string()); | |
| 1983 | + } | |
| 1984 | + } | |
| 1985 | + Some(_) => bail!("config `define` must be an object"), | |
| 1986 | + } | |
| 1987 | + let rules = match object.get("rules") { | |
| 1988 | + None => &[][..], | |
| 1989 | + Some(Value::Array(rules)) => rules.as_slice(), | |
| 1990 | + Some(_) => bail!("config `rules` must be an array"), | |
| 1991 | + }; | |
| 1992 | + for rule in rules { | |
| 1993 | + let Value::Object(rule) = rule else { | |
| 1994 | + bail!("module rule must be an object with a `type` and `globs`"); | |
| 1995 | + }; | |
| 1996 | + for key in rule.keys() { | |
| 1997 | + if !matches!(key.as_str(), "type" | "globs") { | |
| 1998 | + bail!("module rule sets `{key}`, which celld does not have"); | |
| 1999 | + } | |
| 2000 | + } | |
| 2001 | + let Some(rule_type) = rule.get("type").and_then(Value::as_str) else { | |
| 2002 | + bail!("module rule has no `type` string"); | |
| 2003 | + }; | |
| 2004 | + let loader = match rule_type { | |
| 2005 | + "Text" => Loader::Text, | |
| 2006 | + "Data" => Loader::Binary, | |
| 2007 | + "CompiledWasm" => Loader::Copy, | |
| 2008 | + other => bail!( | |
| 2009 | + "module rule type {other:?} is not supported; celld supports \ | |
| 2010 | + Text, Data, and CompiledWasm" | |
| 2011 | + ), | |
| 2012 | + }; | |
| 2013 | + let Some(Value::Array(globs)) = rule.get("globs") else { | |
| 2014 | + bail!("module rule {rule_type} must have a `globs` array"); | |
| 2015 | + }; | |
| 2016 | + if globs.is_empty() { | |
| 2017 | + bail!("module rule {rule_type} has no globs"); | |
| 2018 | + } | |
| 2019 | + for glob in globs { | |
| 2020 | + let Some(glob) = glob.as_str() else { | |
| 2021 | + bail!("module rule glob must be a string"); | |
| 2022 | + }; | |
| 2023 | + let extension = rule_extension(glob)?; | |
| 2024 | + // Two rules that claim one extension have no single answer, and | |
| 2025 | + // picking either silently loads half the files the config lists | |
| 2026 | + // the wrong way. | |
| 2027 | + if let Some(previous) = bundle.loaders.insert(extension.clone(), loader) { | |
| 2028 | + if previous != loader { | |
| 2029 | + bail!( | |
| 2030 | + "two module rules claim {extension:?}: {} and {}", | |
| 2031 | + previous.rule_type(), | |
| 2032 | + loader.rule_type() | |
| 2033 | + ); | |
| 2034 | + } | |
| 2035 | + } | |
| 2036 | + } | |
| 2037 | + } | |
| 2038 | + Ok(bundle) | |
| 2039 | +} | |
| 2040 | + | |
| 2041 | +/// The file extension a Wrangler module glob selects. | |
| 2042 | +/// | |
| 2043 | +/// esbuild chooses a loader by extension, and Wrangler chooses one by glob, so | |
| 2044 | +/// only a glob that is exactly an extension match crosses that gap. celld | |
| 2045 | +/// refuses every other glob rather than load a different set of files than the | |
| 2046 | +/// config asks for. | |
| 2047 | +fn rule_extension(glob: &str) -> anyhow::Result<String> { | |
| 2048 | + let extension = glob | |
| 2049 | + .strip_prefix("**/*") | |
| 2050 | + .or_else(|| glob.strip_prefix('*')) | |
| 2051 | + .filter(|extension| { | |
| 2052 | + extension.strip_prefix('.').is_some_and(|name| { | |
| 2053 | + !name.is_empty() && !name.contains(['*', '?', '.', '/', '\\', '[', '{']) | |
| 2054 | + }) | |
| 2055 | + }) | |
| 2056 | + .ok_or_else(|| { | |
| 2057 | + anyhow!( | |
| 2058 | + "module rule glob {glob:?} is not an extension match; celld \ | |
| 2059 | + supports a glob of the form `**/*.ext`" | |
| 2060 | + ) | |
| 2061 | + })?; | |
| 2062 | + Ok(extension.to_string()) | |
| 2063 | +} | |
| 2064 | + | |
| 1867 | 2065 | /// The config's `containers[]`. Each entry attaches a container to one |
| 1868 | 2066 | /// SQLite-backed Durable Object class of this Worker, which is what |
| 1869 | 2067 | /// Cloudflare requires too. |
| @@ -2037,7 +2235,7 @@ | ||
| 2037 | 2235 | /// the same rule for a second reason: the name becomes a key prefix inside the |
| 2038 | 2236 | /// fleet bucket, and this rule is what keeps it a single path segment, so a |
| 2039 | 2237 | /// binding cannot address the fleet's own deployment, cell, or lease keys. |
| 2040 | -fn valid_resource_name(name: &str) -> bool { | |
| 2238 | +pub(crate) fn valid_resource_name(name: &str) -> bool { | |
| 2041 | 2239 | name.len() <= 64 |
| 2042 | 2240 | && name |
| 2043 | 2241 | .chars() |
| @@ -2611,7 +2809,7 @@ | ||
| 2611 | 2809 | Ok(()) |
| 2612 | 2810 | } |
| 2613 | 2811 | |
| 2614 | -fn run_esbuild(root: &Path, entry: &str) -> anyhow::Result<BundleOutput> { | |
| 2812 | +fn run_esbuild(root: &Path, entry: &str, config: &BundleConfig) -> anyhow::Result<BundleOutput> { | |
| 2615 | 2813 | // node: builtins stay external. Wrangler polyfills them with unenv; celld |
| 2616 | 2814 | // implements the workerd `nodejs_compat` subset itself, so the runtime |
| 2617 | 2815 | // provides them. |
| @@ -2633,43 +2831,46 @@ | ||
| 2633 | 2831 | } |
| 2634 | 2832 | return builtin; |
| 2635 | 2833 | };"#; |
| 2636 | - let output = Command::new(&binary) | |
| 2637 | - .current_dir(root) | |
| 2638 | - .arg(entry) | |
| 2639 | - .arg("--bundle") | |
| 2640 | - .arg("--format=esm") | |
| 2641 | - .arg("--platform=browser") | |
| 2642 | - .arg("--target=es2024") | |
| 2643 | - .arg("--conditions=workerd,worker,browser") | |
| 2644 | - .arg(format!("--banner:js={commonjs_builtin_bridge}")) | |
| 2645 | - .arg("--external:node:*") | |
| 2646 | - .arg("--external:cloudflare:*") | |
| 2647 | - .args( | |
| 2648 | - crate::js::BARE_NODE_BUILTINS | |
| 2649 | - .iter() | |
| 2650 | - .map(|specifier| format!("--external:{specifier}")), | |
| 2651 | - ) | |
| 2652 | - // Wasm becomes a sibling module (Wrangler's CompiledWasm rule). The | |
| 2653 | - // `copy` loader makes esbuild resolve each wasm import like any other | |
| 2654 | - // import (importer-relative, node_modules, deduplicated) and rewrite | |
| 2655 | - // the specifier to the copied file, so the bundle and the emitted | |
| 2656 | - // files agree on names; the runtime serves each file as a compiled | |
| 2657 | - // WebAssembly.Module default export. | |
| 2658 | - .arg("--loader:.wasm=copy") | |
| 2659 | - .arg(format!("--outdir={}", outdir.path().display())) | |
| 2660 | - .arg("--entry-names=index") | |
| 2661 | - .output() | |
| 2662 | - .map_err(|error| { | |
| 2663 | - if error.kind() == std::io::ErrorKind::NotFound { | |
| 2664 | - anyhow!( | |
| 2665 | - "esbuild not found ({binary}).\n\ | |
| 2834 | + let output = | |
| 2835 | + Command::new(&binary) | |
| 2836 | + .current_dir(root) | |
| 2837 | + .arg(entry) | |
| 2838 | + .arg("--bundle") | |
| 2839 | + .arg("--format=esm") | |
| 2840 | + .arg("--platform=browser") | |
| 2841 | + .arg("--target=es2024") | |
| 2842 | + .arg("--conditions=workerd,worker,browser") | |
| 2843 | + .arg(format!("--banner:js={commonjs_builtin_bridge}")) | |
| 2844 | + .arg("--external:node:*") | |
| 2845 | + .arg("--external:cloudflare:*") | |
| 2846 | + .args( | |
| 2847 | + crate::js::BARE_NODE_BUILTINS | |
| 2848 | + .iter() | |
| 2849 | + .map(|specifier| format!("--external:{specifier}")), | |
| 2850 | + ) | |
| 2851 | + .args(config.loaders.iter().map(|(extension, loader)| { | |
| 2852 | + format!("--loader:{extension}={}", loader.esbuild_name()) | |
| 2853 | + })) | |
| 2854 | + .args( | |
| 2855 | + config | |
| 2856 | + .define | |
| 2857 | + .iter() | |
| 2858 | + .map(|(key, value)| format!("--define:{key}={value}")), | |
| 2859 | + ) | |
| 2860 | + .arg(format!("--outdir={}", outdir.path().display())) | |
| 2861 | + .arg("--entry-names=index") | |
| 2862 | + .output() | |
| 2863 | + .map_err(|error| { | |
| 2864 | + if error.kind() == std::io::ErrorKind::NotFound { | |
| 2865 | + anyhow!( | |
| 2866 | + "esbuild not found ({binary}).\n\ | |
| 2666 | 2867 | `celld deploy` bundles with esbuild; install it and retry,\n\ |
| 2667 | 2868 | or set CELLD_ESBUILD to its path." |
| 2668 | - ) | |
| 2669 | - } else { | |
| 2670 | - anyhow!("run esbuild: {error}") | |
| 2671 | - } | |
| 2672 | - })?; | |
| 2869 | + ) | |
| 2870 | + } else { | |
| 2871 | + anyhow!("run esbuild: {error}") | |
| 2872 | + } | |
| 2873 | + })?; | |
| 2673 | 2874 | if !output.status.success() { |
| 2674 | 2875 | bail!( |
| 2675 | 2876 | "esbuild failed:\n{}", |
| @@ -2678,12 +2879,31 @@ | ||
| 2678 | 2879 | } |
| 2679 | 2880 | let bundle = |
| 2680 | 2881 | std::fs::read(outdir.path().join("index.js")).context("read esbuild output bundle")?; |
| 2681 | - // The copied wasm files land beside the bundle; each becomes its own | |
| 2682 | - // deployed module under the name the rewritten imports use. | |
| 2882 | + // The copied files land beside the bundle; each becomes its own deployed | |
| 2883 | + // module under the name the rewritten imports use. Only the `copy` loader | |
| 2884 | + // emits a sibling — `text` and `binary` put the file inside the bundle — | |
| 2885 | + // so the emitted set follows the same extension map the run used. It must | |
| 2886 | + // follow that map and not a fixed `.wasm` test: a config that gives | |
| 2887 | + // `.wasm` a different rule emits no wasm, and a `CompiledWasm` rule on | |
| 2888 | + // another extension emits one under that extension. | |
| 2889 | + let copied: BTreeSet<&str> = config | |
| 2890 | + .loaders | |
| 2891 | + .iter() | |
| 2892 | + .filter(|(_, loader)| **loader == Loader::Copy) | |
| 2893 | + .map(|(extension, _)| extension.as_str()) | |
| 2894 | + .collect(); | |
| 2683 | 2895 | let mut wasm = Vec::new(); |
| 2684 | 2896 | for dirent in std::fs::read_dir(outdir.path()).context("read esbuild output directory")? { |
| 2685 | 2897 | let path = dirent?.path(); |
| 2686 | - if path.extension().and_then(|extension| extension.to_str()) == Some("wasm") { | |
| 2898 | + let is_copied = path | |
| 2899 | + .file_name() | |
| 2900 | + .and_then(|name| name.to_str()) | |
| 2901 | + .is_some_and(|name| { | |
| 2902 | + // The bundle already holds the main-module slot. A rule that | |
| 2903 | + // claims `.js` would otherwise deploy it a second time. | |
| 2904 | + name != "index.js" && copied.iter().any(|extension| name.ends_with(extension)) | |
| 2905 | + }); | |
| 2906 | + if is_copied { | |
| 2687 | 2907 | let name = path |
| 2688 | 2908 | .file_name() |
| 2689 | 2909 | .expect("read_dir entries have a file name") |
modifiedcrates/celld/generation.rs+29−0View file
| @@ -409,8 +409,37 @@ | ||
| 409 | 409 | pool.reap_empty(); |
| 410 | 410 | } |
| 411 | 411 | } |
| 412 | + | |
| 413 | + /// The isolates this generation holds right now, for `/state`. | |
| 414 | + pub(crate) fn isolate_census(&self) -> IsolateCensus { | |
| 415 | + IsolateCensus { | |
| 416 | + stateless: self.stateless.isolates.census(), | |
| 417 | + services: self | |
| 418 | + .services | |
| 419 | + .iter() | |
| 420 | + .map(|(name, service)| (name.clone(), service.isolates.census())) | |
| 421 | + .collect(), | |
| 422 | + cells: self | |
| 423 | + .cell_isolates | |
| 424 | + .iter() | |
| 425 | + .map(|(script, pool)| (script.clone(), pool.census())) | |
| 426 | + .collect(), | |
| 427 | + } | |
| 428 | + } | |
| 412 | 429 | } |
| 413 | 430 | |
| 431 | +/// The isolates one generation holds, by the pool they belong to, as | |
| 432 | +/// `/state` reports them. | |
| 433 | +#[derive(Debug, serde::Serialize)] | |
| 434 | +pub struct IsolateCensus { | |
| 435 | + /// The pool that serves the primary script's stateless handlers. | |
| 436 | + pub stateless: crate::pool::PoolCensus, | |
| 437 | + /// The pools of the named services, by service name. | |
| 438 | + pub services: BTreeMap<String, crate::pool::PoolCensus>, | |
| 439 | + /// The pools the cells live in, by Worker script. | |
| 440 | + pub cells: BTreeMap<String, crate::pool::PoolCensus>, | |
| 441 | +} | |
| 442 | + | |
| 414 | 443 | /// The generation an isolate was built for, installed as an isolate slot by |
| 415 | 444 | /// `Worker::load_config` so a call the isolate makes into the host — a |
| 416 | 445 | /// service binding, an assets binding, a queue dispatch — resolves against |
modifiedcrates/celld/js.rs+0−0View file
This diff is too large to display.
modifiedcrates/celld/js/bootstrap.rs+1−1View file
| @@ -796,7 +796,7 @@ | ||
| 796 | 796 | } |
| 797 | 797 | |
| 798 | 798 | /// Measure lease expiry without waiting through the production handler budget. |
| 799 | -/// The override is thread-local because the private runtime corpus builds | |
| 799 | +/// The override is thread-local because runtime tests build | |
| 800 | 800 | /// unrelated Workers in parallel, and a process environment variable would |
| 801 | 801 | /// silently shorten their leases too. |
| 802 | 802 | #[cfg(celld_internal_tests)] |
modifiedcrates/celld/js/crypto.js+6−4View file
| @@ -30,6 +30,7 @@ | ||
| 30 | 30 | "P-384": "P-384", "secp384r1": "P-384", |
| 31 | 31 | "P-521": "P-521", "secp521r1": "P-521", |
| 32 | 32 | }; |
| 33 | + const _canonicalEcCurve = (curve) => _EC_CURVES[_curveName(curve)]; | |
| 33 | 34 | // The asymmetric algorithms, as the uppercased name `_algorithmName` |
| 34 | 35 | // produces mapped to the spelling `key.algorithm.name` reports. The |
| 35 | 36 | // uppercased form is for lookup only: echoing it back names an algorithm |
| @@ -137,7 +138,7 @@ | ||
| 137 | 138 | // The host names the curve as node:crypto does; Web Crypto spells it |
| 138 | 139 | // as the caller did, so map it back. |
| 139 | 140 | reported.namedCurve = |
| 140 | - _EC_CURVES[details.namedCurve] ?? details.namedCurve; | |
| 141 | + _canonicalEcCurve(details.namedCurve) ?? details.namedCurve; | |
| 141 | 142 | } else if (algorithm?.namedCurve !== undefined) { |
| 142 | 143 | // Ed25519 and X25519 have one curve each, so the parsed key carries |
| 143 | 144 | // no curve to report. Cloudflare still puts `namedCurve` on such a |
| @@ -495,7 +496,7 @@ | ||
| 495 | 496 | } |
| 496 | 497 | } |
| 497 | 498 | if (kind === "ec") { |
| 498 | - const curve = _EC_CURVES[_curveName(algorithm?.namedCurve)]; | |
| 499 | + const curve = _canonicalEcCurve(algorithm?.namedCurve); | |
| 499 | 500 | if (curve === undefined) |
| 500 | 501 | throw _notSupported("unsupported curve: " + algorithm?.namedCurve); |
| 501 | 502 | options.namedCurve = curve; |
| @@ -543,7 +544,7 @@ | ||
| 543 | 544 | : null; |
| 544 | 545 | if (!operation) throw _notSupported("unsupported sign algorithm: " + name); |
| 545 | 546 | if (name === "ECDSA") { |
| 546 | - if (_EC_CURVES[_curveName(key?.algorithm?.namedCurve)] !== "P-256") { | |
| 547 | + if (_canonicalEcCurve(key?.algorithm?.namedCurve) !== "P-256") { | |
| 547 | 548 | throw _notSupported("ECDSA signatures support only P-256"); |
| 548 | 549 | } |
| 549 | 550 | if (_hashName(algorithm?.hash) !== "SHA-256") { |
| @@ -583,7 +584,7 @@ | ||
| 583 | 584 | const material = key?.__celldMaterial?.bytes; |
| 584 | 585 | if (!material) throw _notSupported("verify needs an spki public key"); |
| 585 | 586 | if (name === "ECDSA") { |
| 586 | - if (_EC_CURVES[_curveName(key?.algorithm?.namedCurve)] !== "P-256") { | |
| 587 | + if (_canonicalEcCurve(key?.algorithm?.namedCurve) !== "P-256") { | |
| 587 | 588 | throw _notSupported("ECDSA signatures support only P-256"); |
| 588 | 589 | } |
| 589 | 590 | if (_hashName(algorithm?.hash) !== "SHA-256") { |
| @@ -798,4 +799,5 @@ | ||
| 798 | 799 | // left the exponent off an RSA key. The loop below hides this name, and |
| 799 | 800 | // the module is lazy, so it always resolves after this script runs. |
| 800 | 801 | __celld.$$keyAlgorithm = _keyAlgorithm; |
| 802 | + __celld.$$canonicalEcCurve = _canonicalEcCurve; | |
| 801 | 803 | })(); |
modifiedcrates/celld/js/harness.js+169−42View file
| @@ -547,11 +547,11 @@ | ||
| 547 | 547 | }).join(" "); |
| 548 | 548 | const __consoleNoop = () => {}; |
| 549 | 549 | globalThis.console = { |
| 550 | - debug: (...a) => __log(__fmt(a)), | |
| 551 | - error: (...a) => __log("ERROR " + __fmt(a)), | |
| 552 | - info: (...a) => __log(__fmt(a)), | |
| 553 | - log: (...a) => __log(__fmt(a)), | |
| 554 | - warn: (...a) => __log("WARN " + __fmt(a)), | |
| 550 | + debug: (...a) => __log("debug", __fmt(a)), | |
| 551 | + error: (...a) => __log("error", __fmt(a)), | |
| 552 | + info: (...a) => __log("info", __fmt(a)), | |
| 553 | + log: (...a) => __log("log", __fmt(a)), | |
| 554 | + warn: (...a) => __log("warn", __fmt(a)), | |
| 555 | 555 | clear: __consoleNoop, |
| 556 | 556 | count: __consoleNoop, |
| 557 | 557 | group: __consoleNoop, |
| @@ -3119,22 +3119,17 @@ | ||
| 3119 | 3119 | // `get(name, ...)` is memoized by name to one isolate; `load()` is anonymous. |
| 3120 | 3120 | // A stub holds a Promise<id> so `getCode` may be async and load lazily. |
| 3121 | 3121 | const byName = new Map(); |
| 3122 | - // getEntrypoint() and getDurableObjectClass() take the same options bag, so | |
| 3123 | - // one function reads it and returns the only option celld implements. | |
| 3124 | - // Workerd ignores an option it does not know; celld refuses it, because a | |
| 3125 | - // silently dropped option is exactly the defect getEntrypoint() had. Keeping | |
| 3126 | - // the rule here rather than in each method is what stops the two from | |
| 3127 | - // drifting apart again. | |
| 3128 | - const loaderProps = (method, options) => { | |
| 3122 | + const loaderOptions = (method, options, supportsLimits) => { | |
| 3129 | 3123 | if (options === null || options === undefined) return undefined; |
| 3130 | 3124 | if (typeof options !== "object") |
| 3131 | 3125 | throw new TypeError(method + "() options must be an object."); |
| 3132 | - const extra = Object.keys(options).filter((key) => key !== "props"); | |
| 3126 | + const extra = Object.keys(options).filter( | |
| 3127 | + (key) => key !== "props" && !(supportsLimits && key === "limits")); | |
| 3133 | 3128 | if (extra.length !== 0) |
| 3134 | 3129 | throw new TypeError( |
| 3135 | 3130 | method + '() does not support the option "' + extra.join('", "') + |
| 3136 | - '". celld supports only "props".'); | |
| 3137 | - return options.props; | |
| 3131 | + '".'); | |
| 3132 | + return options; | |
| 3138 | 3133 | }; |
| 3139 | 3134 | // `props` cross to the loaded isolate by structured clone, on the same |
| 3140 | 3135 | // transport that already carries the call's arguments (`__rpcOut` below). |
| @@ -3145,27 +3140,54 @@ | ||
| 3145 | 3140 | // loader API call, also rejects an unclonable value at that call rather than |
| 3146 | 3141 | // at the first operation. |
| 3147 | 3142 | const loaderPropsSc = (method, options) => { |
| 3148 | - const props = loaderProps(method, options); | |
| 3143 | + const props = loaderOptions(method, options, false)?.props; | |
| 3149 | 3144 | if (props === undefined) return undefined; |
| 3150 | 3145 | // `lift` false: the props cross an isolate boundary, so a stub inside them |
| 3151 | 3146 | // is a DataCloneError, exactly as a stub inside an argument of the same |
| 3152 | 3147 | // call is. |
| 3153 | 3148 | return __rpcOut(props, false); |
| 3154 | 3149 | }; |
| 3155 | - const makeEntrypoint = (idPromise, entrypoint, propsSc) => { | |
| 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) => { | |
| 3156 | 3159 | const target = { |
| 3157 | 3160 | async fetch(input, init) { |
| 3158 | - const id = await idPromise; | |
| 3161 | + const { id, tails } = await loadPromise; | |
| 3159 | 3162 | const req = new Request(input, init); |
| 3160 | 3163 | // The verbatim header list; see the note on the outbound `fetch`. |
| 3161 | 3164 | // The loaded worker rebuilds a `Headers` from these pairs, so a |
| 3162 | 3165 | // repeat and its casing survive the isolate boundary. |
| 3163 | 3166 | const headers = JSON.stringify(req.headers.__celldHeaderList); |
| 3164 | 3167 | const { body, streamId } = await __subrequestBody(req); |
| 3165 | - const r = JSON.parse( | |
| 3166 | - await __loader_fetch( | |
| 3167 | - id, req.url, req.method, body, headers, streamId, entrypoint, | |
| 3168 | - propsSc === undefined ? new Uint8Array() : propsSc)); | |
| 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); | |
| 3169 | 3191 | const responseBody = r.streamId !== undefined |
| 3170 | 3192 | ? new CelldHttpBodyStream(r.streamId) |
| 3171 | 3193 | : r.body !== undefined ? r.body : Uint8Array.from(r.bodyBytes || []); |
| @@ -3187,10 +3209,10 @@ | ||
| 3187 | 3209 | throw new Error( |
| 3188 | 3210 | "Pipelined property paths on loaded workers are not supported " + |
| 3189 | 3211 | "yet."); |
| 3190 | - const id = await idPromise; | |
| 3212 | + const { id } = await loadPromise; | |
| 3191 | 3213 | return __rpcDes( |
| 3192 | 3214 | await __loader_rpc(id, entrypoint, path[0], __rpcOut(args, false), |
| 3193 | - propsSc)); | |
| 3215 | + propsSc, limitsJson)); | |
| 3194 | 3216 | })(), |
| 3195 | 3217 | }; |
| 3196 | 3218 | return new Proxy(target, { |
| @@ -3208,26 +3230,30 @@ | ||
| 3208 | 3230 | const finalizer = typeof FinalizationRegistry === "function" |
| 3209 | 3231 | ? new FinalizationRegistry((id) => __loader_drop(id)) |
| 3210 | 3232 | : null; |
| 3211 | - const makeStub = (idPromise, evictable) => { | |
| 3233 | + const makeStub = (loadPromise, evictable) => { | |
| 3212 | 3234 | // Explicit disposal evicts the worker deterministically; the finalizer is |
| 3213 | 3235 | // a GC backstop for anonymous stubs that are dropped without disposing. |
| 3214 | 3236 | // __loader_drop is idempotent, so the two paths cannot double-free. |
| 3215 | - const drop = () => { idPromise.then((id) => __loader_drop(id), () => {}); }; | |
| 3237 | + const drop = () => { | |
| 3238 | + loadPromise.then(({ id }) => __loader_drop(id), () => {}); | |
| 3239 | + }; | |
| 3216 | 3240 | const stub = { |
| 3217 | 3241 | getEntrypoint(name = null, options = {}) { |
| 3242 | + const { propsSc, limitsJson } = loaderEntrypointOptions(options); | |
| 3218 | 3243 | return makeEntrypoint( |
| 3219 | - idPromise, name === null ? "default" : String(name), | |
| 3220 | - loaderPropsSc("getEntrypoint", options)); | |
| 3244 | + loadPromise, name === null ? "default" : String(name), | |
| 3245 | + propsSc, limitsJson); | |
| 3221 | 3246 | }, |
| 3222 | 3247 | getDurableObjectClass(name = null, options = {}) { |
| 3223 | 3248 | return __makeDurableObjectClass( |
| 3224 | - idPromise, name, loaderPropsSc("getDurableObjectClass", options)); | |
| 3249 | + loadPromise.then(({ id }) => id), name, | |
| 3250 | + loaderPropsSc("getDurableObjectClass", options)); | |
| 3225 | 3251 | }, |
| 3226 | 3252 | dispose: drop, |
| 3227 | 3253 | }; |
| 3228 | 3254 | if (typeof Symbol.dispose === "symbol") stub[Symbol.dispose] = drop; |
| 3229 | 3255 | if (evictable && finalizer) |
| 3230 | - idPromise.then((id) => finalizer.register(stub, id), () => {}); | |
| 3256 | + loadPromise.then(({ id }) => finalizer.register(stub, id), () => {}); | |
| 3231 | 3257 | return stub; |
| 3232 | 3258 | }; |
| 3233 | 3259 | // JSON.stringify silently drops binary values, so each non-string module -- |
| @@ -3298,7 +3324,7 @@ | ||
| 3298 | 3324 | const encodeModules = (c) => { |
| 3299 | 3325 | if (c === null || typeof c !== "object" || c.modules === null |
| 3300 | 3326 | || typeof c.modules !== "object") |
| 3301 | - return { config: c, wasm: [], outbound: undefined }; | |
| 3327 | + return { config: c, wasm: [], outbound: undefined, tails: [] }; | |
| 3302 | 3328 | const modules = {}; |
| 3303 | 3329 | const wasm = []; |
| 3304 | 3330 | for (const [name, value] of Object.entries(c.modules)) { |
| @@ -3349,14 +3375,25 @@ | ||
| 3349 | 3375 | } |
| 3350 | 3376 | } |
| 3351 | 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 | + } | |
| 3352 | 3388 | const { |
| 3353 | 3389 | globalOutbound: _globalOutbound, |
| 3354 | 3390 | env: _env, |
| 3391 | + tails: _tails, | |
| 3355 | 3392 | ...rest |
| 3356 | 3393 | } = c; |
| 3357 | 3394 | return { |
| 3358 | 3395 | config: { ...rest, modules }, wasm, outbound, outboundProps, |
| 3359 | - env, envRoutes, | |
| 3396 | + env, envRoutes, tails, | |
| 3360 | 3397 | }; |
| 3361 | 3398 | }; |
| 3362 | 3399 | // getCode is deferred into a microtask so a throw (or async getCode) |
| @@ -3365,11 +3402,12 @@ | ||
| 3365 | 3402 | Promise.resolve().then(getCode) |
| 3366 | 3403 | .then((c) => { |
| 3367 | 3404 | const { |
| 3368 | - config, wasm, outbound, outboundProps, env, envRoutes, | |
| 3405 | + config, wasm, outbound, outboundProps, env, envRoutes, tails, | |
| 3369 | 3406 | } = encodeModules(c); |
| 3370 | - return __loader_load( | |
| 3407 | + const id = __loader_load( | |
| 3371 | 3408 | JSON.stringify(config), wasm, outbound, outboundProps, env, |
| 3372 | - envRoutes); | |
| 3409 | + envRoutes, tails.length !== 0); | |
| 3410 | + return { id, tails }; | |
| 3373 | 3411 | }); |
| 3374 | 3412 | return { |
| 3375 | 3413 | load(code) { return makeStub(loadFrom(() => code), true); }, |
| @@ -6749,10 +6787,55 @@ | ||
| 6749 | 6787 | }; |
| 6750 | 6788 | } |
| 6751 | 6789 | throw __kvError( |
| 6752 | - "a KV value must be a string, an ArrayBuffer, or a typed array", | |
| 6790 | + "a KV value must be a string, an ArrayBuffer, a typed array, or a ReadableStream", | |
| 6753 | 6791 | ); |
| 6754 | 6792 | }; |
| 6755 | 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 | + | |
| 6756 | 6839 | const __kvDecodeValue = (bytes, tag, type) => { |
| 6757 | 6840 | const view = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes); |
| 6758 | 6841 | switch (type) { |
| @@ -6843,8 +6926,13 @@ | ||
| 6843 | 6926 | async put(key, value, options) { |
| 6844 | 6927 | const name = String(key); |
| 6845 | 6928 | __kvCheckKey(name); |
| 6846 | - const encoded = __kvEncodeValue(value); | |
| 6847 | - __kvCheckValue(encoded.value.byteLength); | |
| 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 | + } | |
| 6848 | 6936 | const metadata = options && options.metadata !== undefined |
| 6849 | 6937 | ? JSON.stringify(options.metadata) |
| 6850 | 6938 | : null; |
| @@ -10439,10 +10527,10 @@ | ||
| 10439 | 10527 | RpcProperty: class RpcProperty {}, |
| 10440 | 10528 | ServiceStub: class ServiceStub {}, |
| 10441 | 10529 | // `import { waitUntil } from "cloudflare:workers"`: register into |
| 10442 | - // the current event; outside any event this is Workerd's | |
| 10443 | - // global-scope error. | |
| 10530 | + // the current event or extend its active background work. Outside either | |
| 10531 | + // lifetime this is Workerd's global-scope error. | |
| 10444 | 10532 | waitUntil(promise) { |
| 10445 | - if (__event_depth() === 0) | |
| 10533 | + if (!__wait_until_active()) | |
| 10446 | 10534 | throw new Error( |
| 10447 | 10535 | "Disallowed operation called within global scope."); |
| 10448 | 10536 | __registerWaitUntil(promise); |
| @@ -11804,14 +11892,42 @@ | ||
| 11804 | 11892 | deflateRawSync: (data, _options) => __zlibSync("deflateRaw", data), |
| 11805 | 11893 | inflateRawSync: (data, _options) => __zlibSync("inflateRaw", data), |
| 11806 | 11894 | }; |
| 11895 | +// A Node dependency reads a `process` field at module scope and passes it | |
| 11896 | +// straight to something that rejects `undefined` -- `dirname(process.execPath)` | |
| 11897 | +// is one such case. Workerd defines every field | |
| 11898 | +// below with a neutral value, so the same bundle evaluates there. A missing | |
| 11899 | +// field therefore fails the whole Worker at load, which is why each one is | |
| 11900 | +// defined even though nothing in a cell has an executable path, a parent | |
| 11901 | +// process, or a real exit code. The values match workerd's | |
| 11902 | +// `src/node/internal/public_process.ts` at workerd revision 04a08513a419 | |
| 11903 | +// (2026-09-04); celld does not invent its own, because a dependency that reads | |
| 11904 | +// them is comparing them to what workerd reports. A field whose workerd | |
| 11905 | +// implementation throws at that revision -- `kill`, `binding`, `dlopen`, | |
| 11906 | +// `cpuUsage` -- stays absent, because it fails on both runtimes and a stub | |
| 11907 | +// here would only change the message. | |
| 11807 | 11908 | if (!globalThis.process) globalThis.process = { |
| 11808 | 11909 | env: {}, platform: "linux", arch: "x64", version: "v20.0.0", |
| 11809 | - versions: { node: "20.0.0" }, argv: [], cwd: () => "/", | |
| 11910 | + versions: { node: "20.0.0" }, cwd: () => "/", | |
| 11911 | + title: "workerd", argv: ["workerd"], argv0: "workerd", execArgv: [], | |
| 11912 | + execPath: "", pid: 1, ppid: 0, exitCode: undefined, | |
| 11913 | + allowedNodeEnvironmentFlags: new Set(), | |
| 11914 | + release: { name: "node", lts: true, sourceUrl: "", headersUrl: "" }, | |
| 11915 | + channel: null, connected: false, debugPort: 0, domain: null, | |
| 11916 | + noDeprecation: false, traceDeprecation: false, throwDeprecation: false, | |
| 11917 | + sourceMapsEnabled: false, moduleLoadList: [], | |
| 11810 | 11918 | stdin: { fd: 0, isTTY: false }, |
| 11811 | 11919 | stdout: { fd: 1, isTTY: false, write: (s) => { __log(String(s)); return true; } }, |
| 11812 | 11920 | stderr: { fd: 2, isTTY: false, write: (s) => { __log(String(s)); return true; } }, |
| 11813 | 11921 | nextTick: (f, ...a) => queueMicrotask(() => f(...a)), |
| 11814 | 11922 | on() {}, once() {}, off() {}, emit() {}, hrtime: () => [0, 0], |
| 11923 | + // Workerd routes a warning to the process 'warning' event, and this | |
| 11924 | + // process emits nothing, so a no-op keeps the two runtimes equivalent. | |
| 11925 | + emitWarning() {}, | |
| 11926 | + ref() {}, unref() {}, uptime: () => 0, | |
| 11927 | + constrainedMemory: () => 0, availableMemory: () => 0, | |
| 11928 | + memoryUsage: () => ({ | |
| 11929 | + rss: 0, heapTotal: 0, heapUsed: 0, external: 0, arrayBuffers: 0, | |
| 11930 | + }), | |
| 11815 | 11931 | }; |
| 11816 | 11932 | globalThis.process.exit = (code = 0) => { |
| 11817 | 11933 | const actorScope = __currentActorScope(); |
| @@ -12156,6 +12272,17 @@ | ||
| 12156 | 12272 | return __nodeStubFor(path + "." + p); |
| 12157 | 12273 | }, |
| 12158 | 12274 | ownKeys: () => [...namespaceNames], |
| 12275 | + // A lazy name has no descriptor on the target, so the synthetic one below | |
| 12276 | + // completes to `writable: false`. Without this trap an assignment would | |
| 12277 | + // reach OrdinarySet, read that descriptor off the proxy as the receiver, | |
| 12278 | + // and throw "Cannot redefine property". CommonJS dependencies patch a | |
| 12279 | + // builtin at module scope, so the throw takes the whole Worker down at | |
| 12280 | + // load. Write through to the surface instead, which also promotes the name | |
| 12281 | + // to a real own property and keeps the descriptor honest from then on. | |
| 12282 | + // Materializing a complete descriptor in the trap below would fix the | |
| 12283 | + // assignment too, but it would charge every Worker for all the stubs the | |
| 12284 | + // moment anything enumerates the namespace. | |
| 12285 | + set: (target, p, value) => Reflect.set(target, p, value), | |
| 12159 | 12286 | getOwnPropertyDescriptor: (target, p) => |
| 12160 | 12287 | Reflect.getOwnPropertyDescriptor(target, p) ?? |
| 12161 | 12288 | (namespaceNames.has(p) |
modifiedcrates/celld/js/node_crypto.js+74−14View file
| @@ -629,20 +629,44 @@ | ||
| 629 | 629 | } |
| 630 | 630 | }; |
| 631 | 631 | const asymmetricMaterial = (key) => key.__celldMaterial ?? {}; |
| 632 | - // Node names the Web Crypto algorithm, not the key type, on the CryptoKey. | |
| 633 | - // Node accepts several spellings of the same curve; celld generates P-256 | |
| 634 | - // only, so the table doubles as the supported-curve check. | |
| 635 | - const EC_CURVE_ALIASES = { | |
| 636 | - "prime256v1": "P-256", | |
| 637 | - "secp256r1": "P-256", | |
| 638 | - "P-256": "P-256", | |
| 639 | - }; | |
| 632 | + // The generation op does not carry a curve yet, so it always generates | |
| 633 | + // P-256. Keep that limitation separate from imported-key conversion, which | |
| 634 | + // accepts every curve that the shared Web Crypto implementation parses. | |
| 635 | + const GENERATED_EC_CURVES = new Set([ | |
| 636 | + "prime256v1", "secp256r1", "P-256", | |
| 637 | + ]); | |
| 640 | 638 | const WEB_CRYPTO_ALGORITHM = { |
| 641 | 639 | rsa: "RSASSA-PKCS1-v1_5", |
| 642 | 640 | ec: "ECDSA", |
| 643 | 641 | ed25519: "Ed25519", |
| 644 | 642 | x25519: "X25519", |
| 645 | 643 | }; |
| 644 | + // Keep each algorithm's key type and legal usages together. A converted | |
| 645 | + // key that carries only one of these values can pass a library's surface | |
| 646 | + // checks and then authorize the wrong Web Crypto operation. | |
| 647 | + const WEB_CRYPTO_KEY_CONTRACT = { | |
| 648 | + "RSASSA-PKCS1-V1_5": { | |
| 649 | + keyType: "rsa", private: ["sign"], public: ["verify"], | |
| 650 | + }, | |
| 651 | + "RSA-PSS": { keyType: "rsa", private: ["sign"], public: ["verify"] }, | |
| 652 | + "RSA-OAEP": { | |
| 653 | + keyType: "rsa", | |
| 654 | + private: ["decrypt", "unwrapKey"], | |
| 655 | + public: ["encrypt", "wrapKey"], | |
| 656 | + }, | |
| 657 | + "ECDSA": { keyType: "ec", private: ["sign"], public: ["verify"] }, | |
| 658 | + "ECDH": { | |
| 659 | + keyType: "ec", private: ["deriveKey", "deriveBits"], public: [], | |
| 660 | + }, | |
| 661 | + "ED25519": { | |
| 662 | + keyType: "ed25519", private: ["sign"], public: ["verify"], | |
| 663 | + }, | |
| 664 | + "X25519": { | |
| 665 | + keyType: "x25519", | |
| 666 | + private: ["deriveKey", "deriveBits"], | |
| 667 | + public: [], | |
| 668 | + }, | |
| 669 | + }; | |
| 646 | 670 | |
| 647 | 671 | function asymmetricKeyObject(result, visibility) { |
| 648 | 672 | const material = { |
| @@ -673,11 +697,47 @@ | ||
| 673 | 697 | get asymmetricKeyType() { |
| 674 | 698 | return asymmetricMaterial(this[kHandle]).keyType; |
| 675 | 699 | } |
| 676 | - // The handle already *is* a CryptoKey; Node's contract is only that the | |
| 677 | - // result is usable with Web Crypto, and this key was built with the | |
| 678 | - // algorithm Web Crypto expects. | |
| 679 | - toCryptoKey() { | |
| 680 | - return this[kHandle]; | |
| 700 | + toCryptoKey(algorithm, extractable, usages) { | |
| 701 | + const material = asymmetricMaterial(this[kHandle]); | |
| 702 | + const requestedName = typeof algorithm === "string" | |
| 703 | + ? algorithm | |
| 704 | + : algorithm?.name; | |
| 705 | + const contract = WEB_CRYPTO_KEY_CONTRACT[ | |
| 706 | + String(requestedName ?? "").toUpperCase() | |
| 707 | + ]; | |
| 708 | + if (contract?.keyType !== material.keyType) { | |
| 709 | + throw new DOMException("Invalid key type", "DataError"); | |
| 710 | + } | |
| 711 | + if (material.keyType === "ec" && typeof algorithm === "object" && | |
| 712 | + algorithm?.namedCurve !== undefined) { | |
| 713 | + const requestedCurve = __celld.$$canonicalEcCurve( | |
| 714 | + algorithm.namedCurve); | |
| 715 | + const keyCurve = __celld.$$canonicalEcCurve( | |
| 716 | + material.details?.namedCurve); | |
| 717 | + if (requestedCurve === undefined || requestedCurve !== keyCurve) { | |
| 718 | + throw new DOMException("Named curve mismatch", "DataError"); | |
| 719 | + } | |
| 720 | + } | |
| 721 | + | |
| 722 | + // `toCryptoKey()` is synchronous, so it cannot call subtle.importKey(). | |
| 723 | + // Build a new view over the normalized material instead. Returning the | |
| 724 | + // KeyObject's storage handle loses all three requested values and makes | |
| 725 | + // libraries such as jose reject a valid private key before signing. | |
| 726 | + const requestedUsages = Array.from(usages); | |
| 727 | + const allowedUsages = contract[this.type]; | |
| 728 | + if (requestedUsages.some((usage) => !allowedUsages.includes(usage)) || | |
| 729 | + (this.type === "private" && requestedUsages.length === 0)) { | |
| 730 | + throw new DOMException( | |
| 731 | + `Invalid ${this.type} key usages`, "SyntaxError"); | |
| 732 | + } | |
| 733 | + return new CryptoKey( | |
| 734 | + this.type, | |
| 735 | + __celld.$$keyAlgorithm( | |
| 736 | + requestedName, algorithm, material.keyType, material.details), | |
| 737 | + extractable, | |
| 738 | + requestedUsages, | |
| 739 | + material, | |
| 740 | + ); | |
| 681 | 741 | } |
| 682 | 742 | } |
| 683 | 743 | class PublicKeyObject extends AsymmetricKeyObject { |
| @@ -919,7 +979,7 @@ | ||
| 919 | 979 | `generateKeyPairSync rsa with publicExponent ${publicExponent}`); |
| 920 | 980 | } |
| 921 | 981 | } |
| 922 | - if (type === "ec" && EC_CURVE_ALIASES[namedCurve] === undefined) { | |
| 982 | + if (type === "ec" && !GENERATED_EC_CURVES.has(namedCurve)) { | |
| 923 | 983 | throw ERR_METHOD_NOT_IMPLEMENTED( |
| 924 | 984 | `generateKeyPairSync ec ${namedCurve}`); |
| 925 | 985 | } |
modifiedcrates/celld/js/node_stream.js+10−0View file
| @@ -5476,9 +5476,19 @@ | ||
| 5476 | 5476 | "CountQueuingStrategy", "TextEncoderStream", "TextDecoderStream", |
| 5477 | 5477 | "CompressionStream", "DecompressionStream", |
| 5478 | 5478 | ]) { |
| 5479 | + // The getter keeps the class lazy, but a getter alone makes the export | |
| 5480 | + // read-only, and a CommonJS dependency that swaps a stream class at module | |
| 5481 | + // scope would take the Worker down at load. The setter replaces the | |
| 5482 | + // accessor with a plain value, so the patch stays on this module object | |
| 5483 | + // and does not reach the global. | |
| 5479 | 5484 | Object.defineProperty(web, name, { |
| 5480 | 5485 | enumerable: true, configurable: true, |
| 5481 | 5486 | get: () => globalThis[name], |
| 5487 | + set: (value) => { | |
| 5488 | + Object.defineProperty(web, name, { | |
| 5489 | + value, writable: true, enumerable: true, configurable: true, | |
| 5490 | + }); | |
| 5491 | + }, | |
| 5482 | 5492 | }); |
| 5483 | 5493 | } |
| 5484 | 5494 |
modifiedcrates/celld/js/r2_ops.rs+191−132View file
| @@ -63,13 +63,14 @@ | ||
| 63 | 63 | const PART_BACKLOG: usize = 256 << 20; |
| 64 | 64 | |
| 65 | 65 | /// The user-metadata name the R2 object record lives under. See |
| 66 | -/// [`Envelope`]. | |
| 66 | +/// [`Envelope`]. The bucket stores it as `celld_r2` on Azure, which | |
| 67 | +/// refuses a hyphen in a metadata name. | |
| 67 | 68 | const ENVELOPE: &str = "celld-r2"; |
| 68 | 69 | |
| 69 | 70 | /// The key space one binding owns inside the fleet bucket. `bucket_name` |
| 70 | 71 | /// comes from the deployment manifest, which validates it, so the prefix |
| 71 | 72 | /// cannot escape into the fleet's own keys. |
| 72 | -fn blob_key(bucket_name: &str, key: &str) -> String { | |
| 73 | +pub(crate) fn blob_key(bucket_name: &str, key: &str) -> String { | |
| 73 | 74 | format!("r2/{bucket_name}/{key}") |
| 74 | 75 | } |
| 75 | 76 | |
| @@ -139,10 +140,8 @@ | ||
| 139 | 140 | /// headers and stay right even for an object written by another tool. |
| 140 | 141 | fn read(attributes: &BlobAttributes) -> Self { |
| 141 | 142 | let mut envelope = attributes |
| 142 | - .metadata | |
| 143 | - .iter() | |
| 144 | - .find(|(name, _)| name.eq_ignore_ascii_case(ENVELOPE)) | |
| 145 | - .and_then(|(_, value)| serde_json::from_str::<Self>(value).ok()) | |
| 143 | + .metadata_value(ENVELOPE) | |
| 144 | + .and_then(|value| serde_json::from_str::<Self>(value).ok()) | |
| 146 | 145 | .unwrap_or_else(|| Self { |
| 147 | 146 | custom: attributes |
| 148 | 147 | .metadata |
| @@ -199,7 +198,11 @@ | ||
| 199 | 198 | |
| 200 | 199 | /// One R2 object, in the shape `__makeR2Bucket` turns into an `R2Object`. |
| 201 | 200 | /// `range` is present only on the answer to a `get`. |
| 202 | -fn object_json(key: &str, meta: &BlobMeta, range: Option<(u64, u64)>) -> serde_json::Value { | |
| 201 | +pub(crate) fn object_json( | |
| 202 | + key: &str, | |
| 203 | + meta: &BlobMeta, | |
| 204 | + range: Option<(u64, u64)>, | |
| 205 | +) -> serde_json::Value { | |
| 203 | 206 | let envelope = Envelope::read(&meta.attributes); |
| 204 | 207 | let mut json = serde_json::json!({ |
| 205 | 208 | "key": key, |
| @@ -408,6 +411,18 @@ | ||
| 408 | 411 | |
| 409 | 412 | // ---- reads --------------------------------------------------------------- |
| 410 | 413 | |
| 414 | +/// One object's record, or `None` when the key does not exist. | |
| 415 | +/// | |
| 416 | +/// Shared with `celld r2 head`: an operator and a Worker must not be able | |
| 417 | +/// to disagree about which key an object lives under, and the answer is | |
| 418 | +/// only right because both sides scope the key the same way. | |
| 419 | +pub(crate) async fn head(bucket_name: &str, key: &str) -> Result<Option<BlobMeta>, String> { | |
| 420 | + store()? | |
| 421 | + .head_blob(&blob_key(bucket_name, key)) | |
| 422 | + .await | |
| 423 | + .map_err(|error| error.to_string()) | |
| 424 | +} | |
| 425 | + | |
| 411 | 426 | /// `__r2_head(bucketName, key)`. Resolves to the object's record, or to |
| 412 | 427 | /// `{"state":"miss"}` when there is no such key. |
| 413 | 428 | pub(super) fn op_r2_head( |
| @@ -418,10 +433,7 @@ | ||
| 418 | 433 | let bucket_name = args.get(0).to_rust_string_lossy(scope); |
| 419 | 434 | let key = args.get(1).to_rust_string_lossy(scope); |
| 420 | 435 | let id = asyncrt::enqueue(async move { |
| 421 | - let meta = store()? | |
| 422 | - .head_blob(&blob_key(&bucket_name, &key)) | |
| 423 | - .await | |
| 424 | - .map_err(|error| error.to_string())?; | |
| 436 | + let meta = head(&bucket_name, &key).await?; | |
| 425 | 437 | Ok(match meta { |
| 426 | 438 | None => serde_json::json!({ "state": "miss" }).to_string(), |
| 427 | 439 | Some(meta) => serde_json::json!({ |
| @@ -434,6 +446,22 @@ | ||
| 434 | 446 | rv.set(promise_for(scope, id)); |
| 435 | 447 | } |
| 436 | 448 | |
| 449 | +/// One conditional read, with the body still on the wire. | |
| 450 | +/// | |
| 451 | +/// Shared with `celld r2 get`, which drains the body to stdout instead of | |
| 452 | +/// handing it to an isolate. | |
| 453 | +pub(crate) async fn read( | |
| 454 | + bucket_name: &str, | |
| 455 | + key: &str, | |
| 456 | + range: BlobRange, | |
| 457 | + conditions: &BlobConditions, | |
| 458 | +) -> Result<BlobRead, String> { | |
| 459 | + store()? | |
| 460 | + .get_blob(&blob_key(bucket_name, key), range, conditions) | |
| 461 | + .await | |
| 462 | + .map_err(|error| error.to_string()) | |
| 463 | +} | |
| 464 | + | |
| 437 | 465 | /// `__r2_get(bucketName, key, requestJson)`. Resolves to a JSON envelope; |
| 438 | 466 | /// a hit's body is a host stream the caller drains as a `ReadableStream`, |
| 439 | 467 | /// so a blob never has to fit in the isolate's heap. A read whose |
| @@ -456,10 +484,7 @@ | ||
| 456 | 484 | .map(BlobRange::from) |
| 457 | 485 | .unwrap_or(BlobRange::Whole); |
| 458 | 486 | let conditions = BlobConditions::from(request.only_if.unwrap_or_default()); |
| 459 | - let read = store()? | |
| 460 | - .get_blob(&blob_key(&bucket_name, &key), range, &conditions) | |
| 461 | - .await | |
| 462 | - .map_err(|error| error.to_string())?; | |
| 487 | + let read = read(&bucket_name, &key, range, &conditions).await?; | |
| 463 | 488 | Ok(match read { |
| 464 | 489 | BlobRead::Missing => serde_json::json!({ "state": "miss" }).to_string(), |
| 465 | 490 | BlobRead::Unmet(meta) => serde_json::json!({ |
| @@ -497,25 +522,31 @@ | ||
| 497 | 522 | let id = asyncrt::enqueue(async move { |
| 498 | 523 | let keys = keys?; |
| 499 | 524 | await_egress_gate(gate).await?; |
| 500 | - let store = store()?; | |
| 501 | - let keys = keys | |
| 502 | - .iter() | |
| 503 | - .map(|key| blob_key(&bucket_name, key)) | |
| 504 | - .collect::<Vec<_>>(); | |
| 505 | - // `delete_many` reports what went; anything left is a failure the | |
| 506 | - // caller must see, because R2's delete either applies or throws. | |
| 507 | - let gone = store.delete_many(&keys).await.len(); | |
| 508 | - if gone != keys.len() { | |
| 509 | - return Err(format!( | |
| 510 | - "R2 delete removed {gone} of {} keys; the rest failed", | |
| 511 | - keys.len() | |
| 512 | - )); | |
| 513 | - } | |
| 525 | + delete(&bucket_name, &keys).await?; | |
| 514 | 526 | Ok(String::new()) |
| 515 | 527 | }); |
| 516 | 528 | rv.set(promise_for(scope, id)); |
| 517 | 529 | } |
| 518 | 530 | |
| 531 | +/// Remove every named key. Shared with `celld r2 delete`. | |
| 532 | +pub(crate) async fn delete(bucket_name: &str, keys: &[String]) -> Result<(), String> { | |
| 533 | + let store = store()?; | |
| 534 | + let keys = keys | |
| 535 | + .iter() | |
| 536 | + .map(|key| blob_key(bucket_name, key)) | |
| 537 | + .collect::<Vec<_>>(); | |
| 538 | + // `delete_many` reports what went; anything left is a failure the | |
| 539 | + // caller must see, because R2's delete either applies or throws. | |
| 540 | + let gone = store.delete_many(&keys).await.len(); | |
| 541 | + if gone != keys.len() { | |
| 542 | + return Err(format!( | |
| 543 | + "R2 delete removed {gone} of {} keys; the rest failed", | |
| 544 | + keys.len() | |
| 545 | + )); | |
| 546 | + } | |
| 547 | + Ok(()) | |
| 548 | +} | |
| 549 | + | |
| 519 | 550 | /// `__r2_list(bucketName, requestJson)`. An absent cursor starts at the |
| 520 | 551 | /// first key. The cursor a truncated page answers with is the last key it |
| 521 | 552 | /// consumed, so the next page resumes strictly after it. |
| @@ -525,92 +556,104 @@ | ||
| 525 | 556 | mut rv: v8::ReturnValue<v8::Value>, |
| 526 | 557 | ) { |
| 527 | 558 | let bucket_name = args.get(0).to_rust_string_lossy(scope); |
| 528 | - let request = serde_json::from_str::<ListRequest>(&args.get(1).to_rust_string_lossy(scope)) | |
| 529 | - .map_err(|error| format!("invalid R2 list options: {error}")); | |
| 530 | - let id = asyncrt::enqueue(async move { | |
| 531 | - let request = request?; | |
| 532 | - let store = store()?; | |
| 533 | - let limit = match request.limit.unwrap_or(0) { | |
| 534 | - limit if limit > 0 => (limit as usize).min(LIST_LIMIT), | |
| 535 | - _ => LIST_LIMIT, | |
| 536 | - }; | |
| 537 | - let scoped = blob_key(&bucket_name, &request.prefix); | |
| 538 | - // R2 resumes from the cursor when it has one and ignores | |
| 539 | - // `startAfter`, which is the same knob for a first page. | |
| 540 | - let after = request | |
| 541 | - .cursor | |
| 542 | - .filter(|cursor| !cursor.is_empty()) | |
| 543 | - .or(request.start_after) | |
| 544 | - .filter(|after| !after.is_empty()) | |
| 545 | - .map(|after| blob_key(&bucket_name, &after)); | |
| 546 | - let page = store | |
| 547 | - .list_page( | |
| 548 | - &scoped, | |
| 549 | - after.as_deref(), | |
| 550 | - limit, | |
| 551 | - request.delimiter.as_deref(), | |
| 552 | - ) | |
| 553 | - .await | |
| 554 | - .map_err(|error| error.to_string())?; | |
| 555 | - // The binding's key space is the caller's: strip the reserved | |
| 556 | - // prefix back off, so a listed key is one the caller can `get`. | |
| 557 | - let strip = blob_key(&bucket_name, ""); | |
| 558 | - let unscope = |key: &str| key.strip_prefix(&strip).unwrap_or(key).to_string(); | |
| 559 | - // A listing carries no metadata on any object store; `include` is | |
| 560 | - // R2 saying it is worth one head per object to have it, and those | |
| 561 | - // heads go out together rather than one after another. | |
| 562 | - let objects = match request.include { | |
| 563 | - false => page | |
| 559 | + let request_json = args.get(1).to_rust_string_lossy(scope); | |
| 560 | + let id = | |
| 561 | + asyncrt::enqueue(async move { Ok(list(&bucket_name, &request_json).await?.to_string()) }); | |
| 562 | + rv.set(promise_for(scope, id)); | |
| 563 | +} | |
| 564 | + | |
| 565 | +/// One listing page, in the shape `__makeR2Bucket` turns into an | |
| 566 | +/// `R2Objects`. `request_json` is R2's `R2ListOptions`, normalized by the | |
| 567 | +/// harness. | |
| 568 | +/// | |
| 569 | +/// Shared with `celld r2 list`, so an operator's listing applies the same | |
| 570 | +/// prefix scoping, the same cursor rule, and the same page bound as a | |
| 571 | +/// Worker's. | |
| 572 | +pub(crate) async fn list( | |
| 573 | + bucket_name: &str, | |
| 574 | + request_json: &str, | |
| 575 | +) -> Result<serde_json::Value, String> { | |
| 576 | + let request = serde_json::from_str::<ListRequest>(request_json) | |
| 577 | + .map_err(|error| format!("invalid R2 list options: {error}"))?; | |
| 578 | + let store = store()?; | |
| 579 | + let limit = match request.limit.unwrap_or(0) { | |
| 580 | + limit if limit > 0 => (limit as usize).min(LIST_LIMIT), | |
| 581 | + _ => LIST_LIMIT, | |
| 582 | + }; | |
| 583 | + let scoped = blob_key(bucket_name, &request.prefix); | |
| 584 | + // R2 resumes from the cursor when it has one and ignores | |
| 585 | + // `startAfter`, which is the same knob for a first page. | |
| 586 | + let after = request | |
| 587 | + .cursor | |
| 588 | + .filter(|cursor| !cursor.is_empty()) | |
| 589 | + .or(request.start_after) | |
| 590 | + .filter(|after| !after.is_empty()) | |
| 591 | + .map(|after| blob_key(bucket_name, &after)); | |
| 592 | + let page = store | |
| 593 | + .list_page( | |
| 594 | + &scoped, | |
| 595 | + after.as_deref(), | |
| 596 | + limit, | |
| 597 | + request.delimiter.as_deref(), | |
| 598 | + ) | |
| 599 | + .await | |
| 600 | + .map_err(|error| error.to_string())?; | |
| 601 | + // The binding's key space is the caller's: strip the reserved | |
| 602 | + // prefix back off, so a listed key is one the caller can `get`. | |
| 603 | + let strip = blob_key(bucket_name, ""); | |
| 604 | + let unscope = |key: &str| key.strip_prefix(&strip).unwrap_or(key).to_string(); | |
| 605 | + // A listing carries no metadata on any object store; `include` is | |
| 606 | + // R2 saying it is worth one head per object to have it, and those | |
| 607 | + // heads go out together rather than one after another. | |
| 608 | + let objects = match request.include { | |
| 609 | + false => page | |
| 610 | + .objects | |
| 611 | + .iter() | |
| 612 | + .map(|entry| { | |
| 613 | + let meta = BlobMeta { | |
| 614 | + size: entry.size, | |
| 615 | + etag: entry.etag.clone(), | |
| 616 | + version: entry.version.clone(), | |
| 617 | + cas: None, | |
| 618 | + uploaded_ms: entry.uploaded_ms, | |
| 619 | + attributes: BlobAttributes::default(), | |
| 620 | + }; | |
| 621 | + object_json(&unscope(&entry.key), &meta, None) | |
| 622 | + }) | |
| 623 | + .collect::<Vec<_>>(), | |
| 624 | + true => { | |
| 625 | + let keys = page | |
| 564 | 626 | .objects |
| 565 | 627 | .iter() |
| 566 | - .map(|entry| { | |
| 567 | - let meta = BlobMeta { | |
| 568 | - size: entry.size, | |
| 569 | - etag: entry.etag.clone(), | |
| 570 | - version: entry.version.clone(), | |
| 571 | - cas: None, | |
| 572 | - uploaded_ms: entry.uploaded_ms, | |
| 573 | - attributes: BlobAttributes::default(), | |
| 574 | - }; | |
| 575 | - object_json(&unscope(&entry.key), &meta, None) | |
| 628 | + .map(|entry| entry.key.clone()) | |
| 629 | + .collect::<Vec<_>>(); | |
| 630 | + let heads = futures_util::stream::iter(keys) | |
| 631 | + .map(|key| async move { | |
| 632 | + store | |
| 633 | + .head_blob(&key) | |
| 634 | + .await | |
| 635 | + .map_err(|error| error.to_string()) | |
| 576 | 636 | }) |
| 577 | - .collect::<Vec<_>>(), | |
| 578 | - true => { | |
| 579 | - let keys = page | |
| 580 | - .objects | |
| 581 | - .iter() | |
| 582 | - .map(|entry| entry.key.clone()) | |
| 583 | - .collect::<Vec<_>>(); | |
| 584 | - let heads = futures_util::stream::iter(keys) | |
| 585 | - .map(|key| async move { | |
| 586 | - store | |
| 587 | - .head_blob(&key) | |
| 588 | - .await | |
| 589 | - .map_err(|error| error.to_string()) | |
| 590 | - }) | |
| 591 | - .buffered(LIST_HEADS) | |
| 592 | - .collect::<Vec<_>>() | |
| 593 | - .await; | |
| 594 | - let mut objects = Vec::with_capacity(heads.len()); | |
| 595 | - for (entry, head) in page.objects.iter().zip(heads) { | |
| 596 | - // A key deleted between the listing and the head is one | |
| 597 | - // R2 would not have listed either. | |
| 598 | - if let Some(meta) = head? { | |
| 599 | - objects.push(object_json(&unscope(&entry.key), &meta, None)); | |
| 600 | - } | |
| 637 | + .buffered(LIST_HEADS) | |
| 638 | + .collect::<Vec<_>>() | |
| 639 | + .await; | |
| 640 | + let mut objects = Vec::with_capacity(heads.len()); | |
| 641 | + for (entry, head) in page.objects.iter().zip(heads) { | |
| 642 | + // A key deleted between the listing and the head is one | |
| 643 | + // R2 would not have listed either. | |
| 644 | + if let Some(meta) = head? { | |
| 645 | + objects.push(object_json(&unscope(&entry.key), &meta, None)); | |
| 601 | 646 | } |
| 602 | - objects | |
| 603 | 647 | } |
| 604 | - }; | |
| 605 | - Ok(serde_json::json!({ | |
| 606 | - "objects": objects, | |
| 607 | - "prefixes": page.prefixes.iter().map(|prefix| unscope(prefix)).collect::<Vec<_>>(), | |
| 608 | - "truncated": page.truncated, | |
| 609 | - "cursor": page.cursor.as_deref().map(unscope), | |
| 610 | - }) | |
| 611 | - .to_string()) | |
| 612 | - }); | |
| 613 | - rv.set(promise_for(scope, id)); | |
| 648 | + objects | |
| 649 | + } | |
| 650 | + }; | |
| 651 | + Ok(serde_json::json!({ | |
| 652 | + "objects": objects, | |
| 653 | + "prefixes": page.prefixes.iter().map(|prefix| unscope(prefix)).collect::<Vec<_>>(), | |
| 654 | + "truncated": page.truncated, | |
| 655 | + "cursor": page.cursor.as_deref().map(unscope), | |
| 656 | + })) | |
| 614 | 657 | } |
| 615 | 658 | |
| 616 | 659 | // ---- writes -------------------------------------------------------------- |
| @@ -691,7 +734,7 @@ | ||
| 691 | 734 | /// A `put` whose body is a `ReadableStream`: the isolate hands over one |
| 692 | 735 | /// chunk at a time and the host decides, at the first part boundary, |
| 693 | 736 | /// whether this is one request or a multipart upload. |
| 694 | -struct PutStream { | |
| 737 | +pub(crate) struct PutStream { | |
| 695 | 738 | bucket_name: String, |
| 696 | 739 | key: String, |
| 697 | 740 | request: PutRequest, |
| @@ -704,9 +747,38 @@ | ||
| 704 | 747 | touched: Instant, |
| 705 | 748 | } |
| 706 | 749 | |
| 750 | +/// Open a streaming write. `request_json` is R2's `R2PutOptions`, | |
| 751 | +/// normalized by the harness. | |
| 752 | +/// | |
| 753 | +/// This is the one constructor, so `celld r2 put` and a Worker's | |
| 754 | +/// `env.BUCKET.put()` cannot store a different record for the same input: | |
| 755 | +/// the checksum set, the envelope, and the single-request/multipart choice | |
| 756 | +/// are all decided here and in [`PutStream::finish`]. | |
| 757 | +pub(crate) fn open_put( | |
| 758 | + bucket_name: String, | |
| 759 | + key: String, | |
| 760 | + request_json: &str, | |
| 761 | +) -> Result<PutStream, String> { | |
| 762 | + let request = serde_json::from_str::<PutRequest>(request_json) | |
| 763 | + .map_err(|error| format!("invalid R2 put options: {error}"))?; | |
| 764 | + // Fail before a byte moves if there is no bucket at all. | |
| 765 | + store()?; | |
| 766 | + let digests = Digests::wanted(&request.verify, true); | |
| 767 | + Ok(PutStream { | |
| 768 | + bucket_name, | |
| 769 | + key, | |
| 770 | + request, | |
| 771 | + digests, | |
| 772 | + buffered: Vec::new(), | |
| 773 | + size: 0, | |
| 774 | + upload: None, | |
| 775 | + touched: Instant::now(), | |
| 776 | + }) | |
| 777 | +} | |
| 778 | + | |
| 707 | 779 | impl PutStream { |
| 708 | 780 | /// Take in one chunk, handing the store every whole part it makes. |
| 709 | - async fn push(&mut self, chunk: Vec<u8>) -> Result<(), String> { | |
| 781 | + pub(crate) async fn push(&mut self, chunk: Vec<u8>) -> Result<(), String> { | |
| 710 | 782 | self.digests.update(&chunk); |
| 711 | 783 | self.size += chunk.len() as u64; |
| 712 | 784 | self.buffered.extend_from_slice(&chunk); |
| @@ -760,7 +832,7 @@ | ||
| 760 | 832 | |
| 761 | 833 | /// Close the stream out: one request if nothing was ever parted off, |
| 762 | 834 | /// the multipart completion otherwise. |
| 763 | - async fn finish(&mut self) -> Result<String, String> { | |
| 835 | + pub(crate) async fn finish(&mut self) -> Result<String, String> { | |
| 764 | 836 | let Some(mut upload) = self.upload.take() else { |
| 765 | 837 | return put_once( |
| 766 | 838 | std::mem::take(&mut self.bucket_name), |
| @@ -874,28 +946,15 @@ | ||
| 874 | 946 | ) { |
| 875 | 947 | let bucket_name = args.get(0).to_rust_string_lossy(scope); |
| 876 | 948 | let key = args.get(1).to_rust_string_lossy(scope); |
| 877 | - let request = serde_json::from_str::<PutRequest>(&args.get(2).to_rust_string_lossy(scope)) | |
| 878 | - .map_err(|error| format!("invalid R2 put options: {error}")); | |
| 949 | + let request_json = args.get(2).to_rust_string_lossy(scope); | |
| 879 | 950 | let id = asyncrt::enqueue(async move { |
| 880 | - let request = request?; | |
| 951 | + let put = open_put(bucket_name, key, &request_json)?; | |
| 881 | 952 | reap_puts(); |
| 882 | - // Fail before a byte moves if there is no bucket at all. | |
| 883 | - store()?; | |
| 884 | - let digests = Digests::wanted(&request.verify, true); | |
| 885 | 953 | let put_id = NEXT_ID.fetch_add(1, Ordering::Relaxed); |
| 886 | - puts().lock().unwrap().insert( | |
| 887 | - put_id, | |
| 888 | - Arc::new(tokio::sync::Mutex::new(PutStream { | |
| 889 | - bucket_name, | |
| 890 | - key, | |
| 891 | - request, | |
| 892 | - digests, | |
| 893 | - buffered: Vec::new(), | |
| 894 | - size: 0, | |
| 895 | - upload: None, | |
| 896 | - touched: Instant::now(), | |
| 897 | - })), | |
| 898 | - ); | |
| 954 | + puts() | |
| 955 | + .lock() | |
| 956 | + .unwrap() | |
| 957 | + .insert(put_id, Arc::new(tokio::sync::Mutex::new(put))); | |
| 899 | 958 | Ok(put_id.to_string()) |
| 900 | 959 | }); |
| 901 | 960 | rv.set(promise_for(scope, id)); |
modifiedcrates/celld/js/tcp.rs+4−4View file
| @@ -67,16 +67,16 @@ | ||
| 67 | 67 | |
| 68 | 68 | /// Mozilla's roots, the same choice `ws_client` makes and for the same |
| 69 | 69 | /// reason: a downloaded celld must reach TLS hosts on a machine with no |
| 70 | -/// `/etc/ssl/certs`. The private suite's TLS servers present certs from | |
| 71 | -/// a test root, injected through the gated seam below. | |
| 70 | +/// `/etc/ssl/certs`. Test TLS servers use a root injected through the | |
| 71 | +/// gated seam below. | |
| 72 | 72 | #[cfg(celld_internal_tests)] |
| 73 | 73 | fn test_root() -> &'static Mutex<Option<Vec<u8>>> { |
| 74 | 74 | static ROOT: OnceLock<Mutex<Option<Vec<u8>>>> = OnceLock::new(); |
| 75 | 75 | ROOT.get_or_init(Default::default) |
| 76 | 76 | } |
| 77 | 77 | |
| 78 | -/// Trust one extra DER root for outbound TLS, so the private suite's | |
| 79 | -/// self-signed servers verify. No compatibility guarantee. | |
| 78 | +/// Trust one extra DER root for outbound TLS, so test servers with | |
| 79 | +/// self-signed certificates verify. No compatibility guarantee. | |
| 80 | 80 | #[cfg(celld_internal_tests)] |
| 81 | 81 | #[doc(hidden)] |
| 82 | 82 | pub fn test_extra_tls_root(der: Vec<u8>) { |
modifiedcrates/celld/js/websocket.rs+2−2View file
| @@ -458,8 +458,8 @@ | ||
| 458 | 458 | /// only within one instance. Each map a socket reaches must therefore belong |
| 459 | 459 | /// to the same instance: a map that stayed process-wide would be shared by |
| 460 | 460 | /// the sockets that two instances both numbered, and a second instance is not |
| 461 | -/// hypothetical — the private build runs one per test runtime, and a | |
| 462 | -/// per-isolate or per-generation instance in production would inherit the | |
| 461 | +/// hypothetical: a test can run multiple instances, and a per-isolate or | |
| 462 | +/// per-generation instance in production would inherit the | |
| 463 | 463 | /// collision. |
| 464 | 464 | pub(crate) struct WebSocketService { |
| 465 | 465 | registry: Arc<std::sync::Mutex<WsRegistry>>, |
modifiedcrates/celld/lib.rs+16−1View file
| @@ -308,7 +308,7 @@ | ||
| 308 | 308 | pub mod assets; |
| 309 | 309 | #[cfg(not(celld_internal_tests))] |
| 310 | 310 | pub mod asyncrt; |
| 311 | -// The corpus flag alone selects the simulated asyncrt, so an external | |
| 311 | +// The internal test flag alone selects the simulated asyncrt, so an external | |
| 312 | 312 | // test harness built with the flag sees the same simulated world the |
| 313 | 313 | // in-crate suites see. `test` must not be part of the gate: |
| 314 | 314 | // a dependency never has it, and the harness binary builds unflagged, |
| @@ -361,6 +361,7 @@ | ||
| 361 | 361 | pub mod protocol; |
| 362 | 362 | pub(crate) mod queue_batching; |
| 363 | 363 | pub mod queue_cli; |
| 364 | +pub mod r2_cli; | |
| 364 | 365 | pub mod replication; |
| 365 | 366 | pub mod runtime; |
| 366 | 367 | pub mod startup; |
| @@ -484,6 +485,15 @@ | ||
| 484 | 485 | pub props: Vec<u8>, |
| 485 | 486 | } |
| 486 | 487 | |
| 488 | +/// Resource limits selected by a Worker Loader stub for one invocation. | |
| 489 | +#[doc(hidden)] | |
| 490 | +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Deserialize)] | |
| 491 | +#[serde(rename_all = "camelCase", deny_unknown_fields)] | |
| 492 | +pub struct WorkerInvocationLimits { | |
| 493 | + pub cpu_ms: Option<u32>, | |
| 494 | + pub sub_requests: Option<u32>, | |
| 495 | +} | |
| 496 | + | |
| 487 | 497 | /// One operation on a Worker entrypoint. A property read has no arguments, |
| 488 | 498 | /// while a call owns its complete receiver path and structured-clone payload. |
| 489 | 499 | pub enum WorkerRpcOperation { |
| @@ -497,11 +507,15 @@ | ||
| 497 | 507 | /// An entrypoint dispatcher target, or the direct default export when |
| 498 | 508 | /// absent. |
| 499 | 509 | entrypoint: Option<WorkerFetchEntrypoint>, |
| 510 | + invocation_limits: Option<WorkerInvocationLimits>, | |
| 500 | 511 | url: String, |
| 501 | 512 | method: String, |
| 502 | 513 | body: js::RequestBody, |
| 503 | 514 | headers: Vec<(String, String)>, |
| 504 | 515 | request_id: Option<js::RequestId>, |
| 516 | + /// Receives one completed invocation report for Dynamic Worker tails. | |
| 517 | + /// Ordinary fetches leave this empty. | |
| 518 | + tail_report: Option<tokio::sync::oneshot::Sender<String>>, | |
| 505 | 519 | reply: tokio::sync::oneshot::Sender<anyhow::Result<js::HttpResponse>>, |
| 506 | 520 | }, |
| 507 | 521 | Rpc { |
| @@ -512,6 +526,7 @@ | ||
| 512 | 526 | /// encoded value can be. A Worker Loader entrypoint or a transferred |
| 513 | 527 | /// Service Binding can set it. |
| 514 | 528 | props: Vec<u8>, |
| 529 | + invocation_limits: Option<WorkerInvocationLimits>, | |
| 515 | 530 | reply: tokio::sync::oneshot::Sender<anyhow::Result<Vec<u8>>>, |
| 516 | 531 | }, |
| 517 | 532 | Queue { |
modifiedcrates/celld/local_store.rs+4−4View file
| @@ -371,12 +371,12 @@ | ||
| 371 | 371 | let limit = options.max_keys.unwrap_or(usize::MAX); |
| 372 | 372 | let mut entries: Vec<(String, Option<Path>, Option<ObjectMeta>)> = Vec::new(); |
| 373 | 373 | for object in self.metadata()? { |
| 374 | - if !object.key.starts_with(prefix) | |
| 375 | - || after.is_some_and(|after| object.key.as_str() <= after) | |
| 376 | - { | |
| 374 | + let Some(remainder) = object.key.strip_prefix(prefix) else { | |
| 377 | 375 | continue; |
| 376 | + }; | |
| 377 | + if after.is_some_and(|after| object.key.as_str() <= after) { | |
| 378 | + continue; | |
| 378 | 379 | } |
| 379 | - let remainder = &object.key[prefix.len()..]; | |
| 380 | 380 | let common = delimiter.and_then(|delimiter| { |
| 381 | 381 | remainder.find(delimiter).map(|index| { |
| 382 | 382 | Path::from(format!("{prefix}{}{}", &remainder[..index], delimiter)) |
modifiedcrates/celld/ltx_repl.rs+143−57View file
| @@ -187,6 +187,9 @@ | ||
| 187 | 187 | registration: Arc<Mutex<RegistrationState>>, |
| 188 | 188 | cell: String, |
| 189 | 189 | epoch: u64, |
| 190 | + // One snapshot per compaction round. Opening every L0 row must not | |
| 191 | + // repeat a persisted-index fallback for the same slow cell. | |
| 192 | + rows: tokio::sync::Mutex<Option<Vec<celld_ltx::LocatedRow>>>, | |
| 190 | 193 | } |
| 191 | 194 | |
| 192 | 195 | impl celld_ltx::BundleFetcher for SinkFetcher { |
| @@ -200,9 +203,21 @@ | ||
| 200 | 203 | >, |
| 201 | 204 | > { |
| 202 | 205 | Box::pin(async move { |
| 206 | + let mut rows = self.rows.lock().await; | |
| 207 | + if let Some(rows) = rows.as_ref() { | |
| 208 | + return Ok(rows.clone()); | |
| 209 | + } | |
| 203 | 210 | let sink = |
| 204 | 211 | registered_durability(&self.registration).map(|targets| targets.manager.clone()); |
| 205 | - Ok(sink.map_or_else(Vec::new, |sink| sink.rows_for(&self.cell, self.epoch))) | |
| 212 | + let fetched = match sink { | |
| 213 | + Some(sink) => sink | |
| 214 | + .rows_for(&self.cell, self.epoch) | |
| 215 | + .await | |
| 216 | + .map_err(|error| celld_ltx::Error::Other(error.to_string().into()))?, | |
| 217 | + None => Vec::new(), | |
| 218 | + }; | |
| 219 | + *rows = Some(fetched.clone()); | |
| 220 | + Ok(fetched) | |
| 206 | 221 | }) |
| 207 | 222 | } |
| 208 | 223 | |
| @@ -530,6 +545,7 @@ | ||
| 530 | 545 | cell: String, |
| 531 | 546 | epoch: u64, |
| 532 | 547 | client: celld_ltx::BundleOverlayClient<ObjectStoreClient>, |
| 548 | + fetcher: Arc<SinkFetcher>, | |
| 533 | 549 | local_path: PathBuf, |
| 534 | 550 | host: LtxHost, |
| 535 | 551 | queue: mpsc::UnboundedSender<CompactionWork>, |
| @@ -540,6 +556,10 @@ | ||
| 540 | 556 | /// L0 bytes uploaded since the last fold, the size trigger's measure. |
| 541 | 557 | pending_bytes: AtomicU64, |
| 542 | 558 | compacted_txid: AtomicU64, |
| 559 | + /// Ship rounds also queue work, so the failure delay must gate admission | |
| 560 | + /// rather than only delaying the worker's own requeue task. | |
| 561 | + retry_after_ms: AtomicU64, | |
| 562 | + failures: AtomicU64, | |
| 543 | 563 | queued: AtomicBool, |
| 544 | 564 | cancelled: AtomicBool, |
| 545 | 565 | cancel: Notify, |
| @@ -692,6 +712,8 @@ | ||
| 692 | 712 | upload_round_receipts: Mutex<Vec<LtxUploadRoundReceiptForWorldV1>>, |
| 693 | 713 | #[cfg(all(test, celld_internal_tests))] |
| 694 | 714 | fleet_credit_receipts: Mutex<Vec<LtxFleetCreditReceiptForWorldV1>>, |
| 715 | + #[cfg(all(test, celld_internal_tests))] | |
| 716 | + fleet_capture_receipts: Mutex<Vec<LtxFleetCaptureReceiptForWorld>>, | |
| 695 | 717 | } |
| 696 | 718 | type CellHandle = Arc<Cell>; |
| 697 | 719 | |
| @@ -1322,7 +1344,7 @@ | ||
| 1322 | 1344 | .get(&key) |
| 1323 | 1345 | .map(|handle| percell_coverage(handle)); |
| 1324 | 1346 | let known = self.covered_by_cell.lock().unwrap().get(&key).copied(); |
| 1325 | - if let Some(covered) = resident.max(known).filter(|covered| *covered > 0) { | |
| 1347 | + if let Some(covered) = resident.filter(|covered| *covered > 0).max(known) { | |
| 1326 | 1348 | return covered; |
| 1327 | 1349 | } |
| 1328 | 1350 | // Nothing this process put there: a cell it never served, or one it |
| @@ -1331,14 +1353,16 @@ | ||
| 1331 | 1353 | // answer; the watermark only rises, so a remembered value never |
| 1332 | 1354 | // over-reports. A restarting node recovers thousands of cells it |
| 1333 | 1355 | // never served, so this listing is its whole recovery cost. |
| 1334 | - let covered = self | |
| 1335 | - .client_for(cell, epoch) | |
| 1336 | - .max_txid_all_levels() | |
| 1337 | - .await | |
| 1338 | - .map(|txid| txid.0) | |
| 1339 | - .unwrap_or(0); | |
| 1340 | - self.note_covered(cell, epoch, covered); | |
| 1341 | - covered | |
| 1356 | + match self.client_for(cell, epoch).max_txid_all_levels().await { | |
| 1357 | + Ok(txid) => { | |
| 1358 | + // Zero is a useful answer too: undrained cells otherwise | |
| 1359 | + // force the same empty-prefix LIST on every GC tick. A read | |
| 1360 | + // error is not zero coverage and must remain retryable. | |
| 1361 | + self.note_covered(cell, epoch, txid.0); | |
| 1362 | + txid.0 | |
| 1363 | + } | |
| 1364 | + Err(_) => 0, | |
| 1365 | + } | |
| 1342 | 1366 | } |
| 1343 | 1367 | |
| 1344 | 1368 | /// Remember that the bucket holds this cell epoch through `txid`. |
| @@ -1925,34 +1949,43 @@ | ||
| 1925 | 1949 | upload_round_receipts: Mutex::new(Vec::new()), |
| 1926 | 1950 | #[cfg(all(test, celld_internal_tests))] |
| 1927 | 1951 | fleet_credit_receipts: Mutex::new(Vec::new()), |
| 1928 | - compaction: self.compaction_queue.as_ref().map(|queue| CellCompaction { | |
| 1929 | - cell: cell.to_string(), | |
| 1930 | - epoch, | |
| 1931 | - // The overlay lets compaction read bundle-resident frames | |
| 1932 | - // beside the per-cell objects; its output stays pure | |
| 1933 | - // per-cell L1s, which is the continuous drain. | |
| 1934 | - client: celld_ltx::BundleOverlayClient::new( | |
| 1935 | - self.client_for(cell, epoch), | |
| 1936 | - Some(Arc::new(SinkFetcher { | |
| 1937 | - registration: self.registration.clone(), | |
| 1938 | - cell: cell.to_string(), | |
| 1939 | - epoch, | |
| 1940 | - })), | |
| 1941 | - ), | |
| 1942 | - local_path: Db::meta_path_for_path(&dst), | |
| 1943 | - host: self.ltx_host.clone(), | |
| 1944 | - queue: queue.clone(), | |
| 1945 | - base_txid: continuation.map_or(1, |(txid, _)| txid.0), | |
| 1946 | - min_txids: self.compaction_min_txids, | |
| 1947 | - min_bytes: self.compaction_min_bytes, | |
| 1948 | - pending_bytes: AtomicU64::new(0), | |
| 1949 | - compacted_txid: AtomicU64::new(0), | |
| 1950 | - queued: AtomicBool::new(false), | |
| 1951 | - cancelled: AtomicBool::new(false), | |
| 1952 | - cancel: Notify::new(), | |
| 1953 | - #[cfg(all(test, celld_internal_tests))] | |
| 1954 | - finish_pause: Mutex::new(None), | |
| 1955 | - run: tokio::sync::Mutex::new(()), | |
| 1952 | + #[cfg(all(test, celld_internal_tests))] | |
| 1953 | + fleet_capture_receipts: Mutex::new(Vec::new()), | |
| 1954 | + compaction: self.compaction_queue.as_ref().map(|queue| { | |
| 1955 | + let fetcher = Arc::new(SinkFetcher { | |
| 1956 | + registration: self.registration.clone(), | |
| 1957 | + cell: cell.to_string(), | |
| 1958 | + epoch, | |
| 1959 | + rows: tokio::sync::Mutex::new(None), | |
| 1960 | + }); | |
| 1961 | + CellCompaction { | |
| 1962 | + cell: cell.to_string(), | |
| 1963 | + epoch, | |
| 1964 | + // The overlay lets compaction read bundle-resident frames | |
| 1965 | + // beside the per-cell objects; its output stays pure | |
| 1966 | + // per-cell L1s, which is the continuous drain. | |
| 1967 | + client: celld_ltx::BundleOverlayClient::new( | |
| 1968 | + self.client_for(cell, epoch), | |
| 1969 | + Some(fetcher.clone()), | |
| 1970 | + ), | |
| 1971 | + fetcher, | |
| 1972 | + local_path: Db::meta_path_for_path(&dst), | |
| 1973 | + host: self.ltx_host.clone(), | |
| 1974 | + queue: queue.clone(), | |
| 1975 | + base_txid: continuation.map_or(1, |(txid, _)| txid.0), | |
| 1976 | + min_txids: self.compaction_min_txids, | |
| 1977 | + min_bytes: self.compaction_min_bytes, | |
| 1978 | + pending_bytes: AtomicU64::new(0), | |
| 1979 | + compacted_txid: AtomicU64::new(0), | |
| 1980 | + retry_after_ms: AtomicU64::new(0), | |
| 1981 | + failures: AtomicU64::new(0), | |
| 1982 | + queued: AtomicBool::new(false), | |
| 1983 | + cancelled: AtomicBool::new(false), | |
| 1984 | + cancel: Notify::new(), | |
| 1985 | + #[cfg(all(test, celld_internal_tests))] | |
| 1986 | + finish_pause: Mutex::new(None), | |
| 1987 | + run: tokio::sync::Mutex::new(()), | |
| 1988 | + } | |
| 1956 | 1989 | }), |
| 1957 | 1990 | }); |
| 1958 | 1991 | #[cfg(celld_internal_tests)] |
| @@ -2094,14 +2127,14 @@ | ||
| 2094 | 2127 | celld_ltx::paged_vfs::hydration(&self.paged_vfs_name(cell, epoch)?) |
| 2095 | 2128 | } |
| 2096 | 2129 | |
| 2097 | - /// The private suite's chain-size threshold for paging, so a world can | |
| 2130 | + /// The test chain-size threshold for paging, so a world can | |
| 2098 | 2131 | /// page a small cut or clone one. |
| 2099 | 2132 | #[cfg(all(test, celld_internal_tests))] |
| 2100 | 2133 | pub fn set_paged_min_bytes_for_test(&self, bytes: u64) { |
| 2101 | 2134 | self.paged_min_bytes.store(bytes, Ordering::Relaxed); |
| 2102 | 2135 | } |
| 2103 | 2136 | |
| 2104 | - /// The private suite's switch for paged restore, so a world runs its | |
| 2137 | + /// The test switch for paged restore, so a world runs its | |
| 2105 | 2138 | /// schedules over the fault path without the process environment. It |
| 2106 | 2139 | /// pages every cut; `set_paged_min_bytes_for_test` restores a threshold. |
| 2107 | 2140 | #[cfg(all(test, celld_internal_tests))] |
| @@ -2341,14 +2374,14 @@ | ||
| 2341 | 2374 | } |
| 2342 | 2375 | } |
| 2343 | 2376 | |
| 2344 | - /// Return the configured durability deadline to a private deterministic | |
| 2377 | + /// Return the configured durability deadline to a deterministic | |
| 2345 | 2378 | /// world, so a bounded-liveness assertion uses the production value. |
| 2346 | 2379 | #[cfg(all(test, celld_internal_tests))] |
| 2347 | 2380 | pub(crate) fn durability_timeout_ms_for_world(&self) -> u64 { |
| 2348 | 2381 | self.durability_timeout_ms |
| 2349 | 2382 | } |
| 2350 | 2383 | |
| 2351 | - /// Lower the handoff snapshot budget, so a private world can hand off a | |
| 2384 | + /// Lower the handoff snapshot budget, so a test world can hand off a | |
| 2352 | 2385 | /// small database the way production hands off a whale. |
| 2353 | 2386 | #[cfg(all(test, celld_internal_tests))] |
| 2354 | 2387 | pub(crate) fn set_handoff_snapshot_budget_for_world(&self, bytes: u64) { |
| @@ -3204,6 +3237,7 @@ | ||
| 3204 | 3237 | >= compaction.min_txids; |
| 3205 | 3238 | let due_by_bytes = compaction.pending_bytes.load(Ordering::SeqCst) >= compaction.min_bytes; |
| 3206 | 3239 | if compaction.cancelled.load(Ordering::SeqCst) |
| 3240 | + || asyncrt::mono_ms() < compaction.retry_after_ms.load(Ordering::SeqCst) | |
| 3207 | 3241 | || !(due_by_txids || due_by_bytes) |
| 3208 | 3242 | || compaction |
| 3209 | 3243 | .queued |
| @@ -3316,24 +3350,30 @@ | ||
| 3316 | 3350 | let source_at_start = source_position(); |
| 3317 | 3351 | let queue_ms = asyncrt::mono_ms().saturating_sub(queued_at_mono_ms); |
| 3318 | 3352 | let started = asyncrt::mono_ms(); |
| 3353 | + // The run lock keeps the snapshot stable through listing and every row | |
| 3354 | + // open. The next round must see bundles published since this one began. | |
| 3355 | + *compaction.fetcher.rows.lock().await = None; | |
| 3319 | 3356 | let compactor = ReplicaCompactor::new(&compaction.client) |
| 3320 | 3357 | .with_host(compaction.host.clone()) |
| 3321 | 3358 | .with_verification(true) |
| 3322 | 3359 | .with_local_path(&compaction.local_path) |
| 3323 | 3360 | .with_limits(COMPACTION_MAX_FILES, COMPACTION_MAX_INPUT_BYTES) |
| 3324 | 3361 | .with_base(TXID(compaction.base_txid)); |
| 3325 | - let worker = compactor.compact_with_progress(1); | |
| 3326 | - tokio::pin!(worker); | |
| 3327 | - let result = if cancellable { | |
| 3328 | - asyncrt::select_biased! { | |
| 3329 | - "a cancellation that ties compaction completion discards the cancelled round"; | |
| 3330 | - _ = &mut cancelled => None, | |
| 3331 | - result = &mut worker => Some(result), | |
| 3362 | + let result = { | |
| 3363 | + let worker = compactor.compact_with_progress(1); | |
| 3364 | + tokio::pin!(worker); | |
| 3365 | + if cancellable { | |
| 3366 | + asyncrt::select_biased! { | |
| 3367 | + "a cancellation that ties compaction completion discards the cancelled round"; | |
| 3368 | + _ = &mut cancelled => None, | |
| 3369 | + result = &mut worker => Some(result), | |
| 3370 | + } | |
| 3371 | + } else { | |
| 3372 | + Some(worker.as_mut().await) | |
| 3332 | 3373 | } |
| 3333 | - } else { | |
| 3334 | - Some(worker.as_mut().await) | |
| 3335 | 3374 | }; |
| 3336 | 3375 | |
| 3376 | + *compaction.fetcher.rows.lock().await = None; | |
| 3337 | 3377 | #[cfg(all(test, celld_internal_tests))] |
| 3338 | 3378 | { |
| 3339 | 3379 | let pause = compaction.finish_pause.lock().unwrap().take(); |
| @@ -3430,23 +3470,44 @@ | ||
| 3430 | 3470 | CompactionOutcome::Cancelled |
| 3431 | 3471 | } |
| 3432 | 3472 | }; |
| 3473 | + let failure_pause = if outcome == CompactionOutcome::Failed { | |
| 3474 | + let failures = compaction.failures.fetch_add(1, Ordering::SeqCst); | |
| 3475 | + let pause = Duration::from_secs((30u64 << failures.min(4)).min(300)); | |
| 3476 | + compaction.retry_after_ms.store( | |
| 3477 | + asyncrt::mono_ms().saturating_add(pause.as_millis() as u64), | |
| 3478 | + Ordering::SeqCst, | |
| 3479 | + ); | |
| 3480 | + Some(pause) | |
| 3481 | + } else { | |
| 3482 | + compaction.failures.store(0, Ordering::SeqCst); | |
| 3483 | + compaction.retry_after_ms.store(0, Ordering::SeqCst); | |
| 3484 | + None | |
| 3485 | + }; | |
| 3486 | + // Publish the delay before admitting another ship-triggered attempt. | |
| 3433 | 3487 | compaction.queued.store(false, Ordering::SeqCst); |
| 3434 | 3488 | |
| 3435 | - // A no-work result can mean that only old bundle metadata is missing. | |
| 3436 | - // Its truthful coverage stays behind durable_txid, so self-requeueing | |
| 3489 | + // A no-work result proves coverage only through the sources that the | |
| 3490 | + // overlay can see, which can end below durable_txid. Self-requeueing | |
| 3437 | 3491 | // would spin on the same empty listing. Preserve a publication that raced |
| 3438 | 3492 | // this attempt: its queue request can lose the queued CAS. Read its two |
| 3439 | 3493 | // watermarks after clearing queued, so a later publisher queues itself. |
| 3440 | - let requeue = outcome == CompactionOutcome::Advanced | |
| 3441 | - || (outcome == CompactionOutcome::Current && source_position() != source_at_start); | |
| 3494 | + // A failed round schedules its own retry after the backoff, so a cell | |
| 3495 | + // with no later ship round still retries. | |
| 3496 | + let requeue = match outcome { | |
| 3497 | + CompactionOutcome::Advanced | CompactionOutcome::Failed => true, | |
| 3498 | + CompactionOutcome::Current => source_position() != source_at_start, | |
| 3499 | + CompactionOutcome::Cancelled => false, | |
| 3500 | + }; | |
| 3442 | 3501 | if requeue && !compaction.cancelled.load(Ordering::SeqCst) { |
| 3443 | 3502 | // Pace consecutive rounds for one cell: a restart with a large tail |
| 3444 | 3503 | // otherwise drains back-to-back for minutes. The pause matches the |
| 3445 | 3504 | // round it follows (capped), so a cell compacts at half duty cycle |
| 3446 | 3505 | // while the worker slot frees for other cells immediately. The owner |
| 3447 | 3506 | // retains this delayed task, but the task does not retain the permit. |
| 3448 | - let pause = Duration::from_millis(asyncrt::mono_ms().saturating_sub(started)) | |
| 3449 | - .min(Duration::from_secs(2)); | |
| 3507 | + let pause = failure_pause.unwrap_or_else(|| { | |
| 3508 | + Duration::from_millis(asyncrt::mono_ms().saturating_sub(started)) | |
| 3509 | + .min(Duration::from_secs(2)) | |
| 3510 | + }); | |
| 3450 | 3511 | let handle_ = Arc::downgrade(&handle); |
| 3451 | 3512 | let Some(requeues) = requeues else { |
| 3452 | 3513 | return outcome; |
| @@ -4152,6 +4213,19 @@ | ||
| 4152 | 4213 | // frame, not only that the bucket already covers them. Queue the |
| 4153 | 4214 | // empty credit through the same ordered pipeline, so an earlier |
| 4154 | 4215 | // failure discards it instead of releasing an unproved fleet ticket. |
| 4216 | + #[cfg(all(test, celld_internal_tests))] | |
| 4217 | + let observer_rounds = credits | |
| 4218 | + .iter() | |
| 4219 | + .map(|(handle, tickets, position)| { | |
| 4220 | + let count = entries | |
| 4221 | + .iter() | |
| 4222 | + .filter(|entry| { | |
| 4223 | + entry.cell == handle.observer_cell && entry.epoch == handle.observer_epoch | |
| 4224 | + }) | |
| 4225 | + .count(); | |
| 4226 | + handle.begin_fleet_capture_for_world(*tickets, *position, count, capture_epoch) | |
| 4227 | + }) | |
| 4228 | + .collect::<Vec<_>>(); | |
| 4155 | 4229 | let append = if entries.is_empty() { |
| 4156 | 4230 | None |
| 4157 | 4231 | } else { |
| @@ -4168,6 +4242,8 @@ | ||
| 4168 | 4242 | let submitted = asyncrt::mono_ms(); |
| 4169 | 4243 | inflight.push_back(Box::pin(async move { |
| 4170 | 4244 | ShipRound { |
| 4245 | + #[cfg(all(test, celld_internal_tests))] | |
| 4246 | + observer_rounds, | |
| 4171 | 4247 | completion: match append { |
| 4172 | 4248 | Some(append) => ShipRoundCompletion::Append(append.await), |
| 4173 | 4249 | None => ShipRoundCompletion::OrderedEmpty, |
| @@ -4205,6 +4281,8 @@ | ||
| 4205 | 4281 | |
| 4206 | 4282 | /// One pipelined round's completion, applied strictly in submission order. |
| 4207 | 4283 | struct ShipRound { |
| 4284 | + #[cfg(all(test, celld_internal_tests))] | |
| 4285 | + observer_rounds: Vec<LtxFleetCaptureForWorld>, | |
| 4208 | 4286 | completion: ShipRoundCompletion, |
| 4209 | 4287 | credits: Vec<(CellHandle, u64, u64)>, |
| 4210 | 4288 | covered_seq: u64, |
| @@ -4242,6 +4320,10 @@ | ||
| 4242 | 4320 | let proof_last_seq = match &round.completion { |
| 4243 | 4321 | ShipRoundCompletion::Append(completion) => { |
| 4244 | 4322 | let Some(last_seq) = completion.last_seq() else { |
| 4323 | + #[cfg(all(test, celld_internal_tests))] | |
| 4324 | + for observer in &round.observer_rounds { | |
| 4325 | + observer.finish(LtxFleetCaptureStatusForWorld::Failed); | |
| 4326 | + } | |
| 4245 | 4327 | return false; |
| 4246 | 4328 | }; |
| 4247 | 4329 | if last_seq > round.covered_seq { |
| @@ -4309,6 +4391,10 @@ | ||
| 4309 | 4391 | proof_last_seq = ?proof_last_seq, |
| 4310 | 4392 | "shipped a log batch" |
| 4311 | 4393 | ); |
| 4394 | + #[cfg(all(test, celld_internal_tests))] | |
| 4395 | + for observer in &round.observer_rounds { | |
| 4396 | + observer.finish(LtxFleetCaptureStatusForWorld::Applied); | |
| 4397 | + } | |
| 4312 | 4398 | for (handle, tickets, position) in round.credits { |
| 4313 | 4399 | #[cfg(all(test, celld_internal_tests))] |
| 4314 | 4400 | handle.record_fleet_credit_for_world(tickets, position, proof_last_seq); |
modifiedcrates/celld/machine.rs+2−2View file
| @@ -29,8 +29,8 @@ | ||
| 29 | 29 | /// (owner read 25 ms, ownership CAS 60 ms, restore 10 ms) and ~10 ms of CPU, |
| 30 | 30 | /// so a bound equal to the thread count admitted 35-40 activations a second |
| 31 | 31 | /// per node whatever the client offered, and 1,000 hibernated alarms due in |
| 32 | -/// one minute were 29 s late at the tail (issue #42 found the same ceiling | |
| 33 | -/// on two-core nodes). Eight per thread keeps the CPU share of the route | |
| 32 | +/// one minute were 29 s late at the tail. The same ceiling appeared on | |
| 33 | +/// two-core nodes. Eight per thread keeps the CPU share of the route | |
| 34 | 34 | /// below one core per thread at full duty (measured 30 % of four vCPUs at |
| 35 | 35 | /// 16 slots, 43 % at 64); the floor keeps a one- or two-thread node from |
| 36 | 36 | /// serializing an I/O-bound path; the cap is the point past which more |
modifiedcrates/celld/main.rs+55−20View file
| @@ -2892,6 +2892,9 @@ | ||
| 2892 | 2892 | ) -> Result<HttpReply, Infallible> { |
| 2893 | 2893 | let path = request.uri().path().to_string(); |
| 2894 | 2894 | let draining = app.is_draining(); |
| 2895 | + let do_scope = path.strip_prefix("/do/"); | |
| 2896 | + let cell_scope = path.strip_prefix("/cell/"); | |
| 2897 | + let evict_scope = path.strip_prefix("/evict/"); | |
| 2895 | 2898 | let result = match path.as_str() { |
| 2896 | 2899 | "/peer/probe" => internal_probe(request, app).await, |
| 2897 | 2900 | "/peer/handoff" => internal_handoff(request, app).await, |
| @@ -3017,9 +3020,10 @@ | ||
| 3017 | 3020 | ) |
| 3018 | 3021 | .await |
| 3019 | 3022 | } |
| 3020 | - _ if path.starts_with("/do/") && app.runtime.is_some() => { | |
| 3023 | + _ if do_scope.is_some() && app.runtime.is_some() => { | |
| 3021 | 3024 | let runtime = app.runtime.as_ref().expect("checked runtime"); |
| 3022 | - let cell = match runtime.cell_scope(&path[4..]) { | |
| 3025 | + let scope = do_scope.expect("checked prefix"); | |
| 3026 | + let cell = match runtime.cell_scope(scope) { | |
| 3023 | 3027 | Ok(cell) => cell, |
| 3024 | 3028 | Err(error) => { |
| 3025 | 3029 | return Ok(response(StatusCode::BAD_REQUEST, format!("{error:#}"))); |
| @@ -3058,12 +3062,13 @@ | ||
| 3058 | 3062 | }; |
| 3059 | 3063 | dispatch_cell_fetch(cell, None, url, method, body, headers).await |
| 3060 | 3064 | } |
| 3061 | - _ if path.starts_with("/cell/") && !celld_logic::cell::valid_cell_scope(&path[6..]) => { | |
| 3062 | - malformed_scope() | |
| 3063 | - } | |
| 3064 | - _ if path.starts_with("/cell/") => { | |
| 3065 | - let cell = path[6..].to_string(); | |
| 3066 | - match app.request(cell.clone()).await { | |
| 3065 | + _ if cell_scope.is_some() => { | |
| 3066 | + let cell = cell_scope.expect("checked prefix"); | |
| 3067 | + if !celld_logic::cell::valid_cell_scope(cell) { | |
| 3068 | + malformed_scope() | |
| 3069 | + } else { | |
| 3070 | + let cell = cell.to_string(); | |
| 3071 | + match app.request(cell.clone()).await { | |
| 3067 | 3072 | Ok(Routed { |
| 3068 | 3073 | request, |
| 3069 | 3074 | route: Route::Local, |
| @@ -3089,19 +3094,21 @@ | ||
| 3089 | 3094 | "{{\"route\":\"remote\",\"node\":{node:?},\"addr\":{addr:?},\"epoch\":{epoch},\"peer_protocol\":{peer_protocol}}}" |
| 3090 | 3095 | ), |
| 3091 | 3096 | ), |
| 3092 | - Err(error) => response( | |
| 3093 | - StatusCode::SERVICE_UNAVAILABLE, | |
| 3094 | - format!("{{\"error\":\"{error:?}\"}}"), | |
| 3095 | - ), | |
| 3097 | + Err(error) => response( | |
| 3098 | + StatusCode::SERVICE_UNAVAILABLE, | |
| 3099 | + format!("{{\"error\":\"{error:?}\"}}"), | |
| 3100 | + ), | |
| 3101 | + } | |
| 3096 | 3102 | } |
| 3097 | 3103 | } |
| 3098 | - _ if path.starts_with("/evict/") && !celld_logic::cell::valid_cell_scope(&path[7..]) => { | |
| 3099 | - malformed_scope() | |
| 3104 | + _ if evict_scope.is_some() => { | |
| 3105 | + let cell = evict_scope.expect("checked prefix"); | |
| 3106 | + if !celld_logic::cell::valid_cell_scope(cell) { | |
| 3107 | + malformed_scope() | |
| 3108 | + } else { | |
| 3109 | + eviction_response(app.evict(cell.to_string()).await) | |
| 3110 | + } | |
| 3100 | 3111 | } |
| 3101 | - _ if path.starts_with("/evict/") => { | |
| 3102 | - app.evict(path[7..].to_string()).await; | |
| 3103 | - response(StatusCode::OK, "{\"ok\":true}") | |
| 3104 | - } | |
| 3105 | 3112 | _ => response(StatusCode::NOT_FOUND, "{\"error\":\"not_found\"}"), |
| 3106 | 3113 | }; |
| 3107 | 3114 | // Close the connection behind any response sent while draining, so |
| @@ -3122,6 +3129,26 @@ | ||
| 3122 | 3129 | Ok(result) |
| 3123 | 3130 | } |
| 3124 | 3131 | |
| 3132 | +fn eviction_response(result: Result<EvictSuccess, EvictError>) -> HttpReply { | |
| 3133 | + let Err(error) = result else { | |
| 3134 | + return response(StatusCode::OK, r#"{"ok":true}"#); | |
| 3135 | + }; | |
| 3136 | + let status = match error { | |
| 3137 | + EvictError::Refused(EvictRefusal::NodeUnavailable | EvictRefusal::ConcurrencyLimit) | |
| 3138 | + | EvictError::Failed(EvictFailure::ActorUnavailable) => StatusCode::SERVICE_UNAVAILABLE, | |
| 3139 | + EvictError::Refused(_) | EvictError::Cancelled(_) => StatusCode::CONFLICT, | |
| 3140 | + EvictError::Failed(_) => StatusCode::INTERNAL_SERVER_ERROR, | |
| 3141 | + }; | |
| 3142 | + response( | |
| 3143 | + status, | |
| 3144 | + serde_json::json!({ | |
| 3145 | + "ok": false, | |
| 3146 | + "error": { "kind": error.kind(), "reason": error.reason() } | |
| 3147 | + }) | |
| 3148 | + .to_string(), | |
| 3149 | + ) | |
| 3150 | +} | |
| 3151 | + | |
| 3125 | 3152 | #[derive(Clone, Copy)] |
| 3126 | 3153 | enum HttpSurface { |
| 3127 | 3154 | Public, |
| @@ -3505,8 +3532,8 @@ | ||
| 3505 | 3532 | .init(); |
| 3506 | 3533 | // After the subscriber, because this reports whether the allocator agreed |
| 3507 | 3534 | // to return freed pages on a timer. A node without that thread holds |
| 3508 | - // retention until a thread allocates again, which is the condition behind | |
| 3509 | - // issue #36, so the operator has to be able to read the answer. | |
| 3535 | + // retention until a thread allocates again, so the operator has to be | |
| 3536 | + // able to read whether that cleanup thread started. | |
| 3510 | 3537 | celld::memory::tune_allocator(); |
| 3511 | 3538 | let mut settings = match action { |
| 3512 | 3539 | Action::Deploy(arguments) => return fleet::run_deploy(arguments).await, |
| @@ -3515,6 +3542,7 @@ | ||
| 3515 | 3542 | Action::D1(arguments) => return celld::d1_cli::run(arguments).await, |
| 3516 | 3543 | Action::Kv(arguments) => return celld::kv_cli::run(arguments).await, |
| 3517 | 3544 | Action::Queue(arguments) => return celld::queue_cli::run(arguments).await, |
| 3545 | + Action::R2(arguments) => return celld::r2_cli::run(arguments).await, | |
| 3518 | 3546 | Action::Connect(arguments) => { |
| 3519 | 3547 | return celld::control_plane::handle_connect_command(arguments).await |
| 3520 | 3548 | } |
| @@ -4356,6 +4384,13 @@ | ||
| 4356 | 4384 | tick.set_missed_tick_behavior(celld::asyncrt::MissedTickBehavior::Delay); |
| 4357 | 4385 | loop { |
| 4358 | 4386 | tick.tick().await; |
| 4387 | + // What SQLite freed when a cell stopped stays on the C | |
| 4388 | + // allocator's free lists, and the sample would count it as | |
| 4389 | + // the node's: 5,000 hibernated cells kept RSS at 1.6 GB with | |
| 4390 | + // 1.5 GB of it free (GCE, 2026-09-04). Trimmed here, | |
| 4391 | + // ahead of the sample, on a blocking thread because a trim | |
| 4392 | + // walks every free chunk. | |
| 4393 | + let _ = tokio::task::spawn_blocking(celld::memory::trim_c_heap_if_retained).await; | |
| 4359 | 4394 | if sample_tx.send(Message::SampleLoad).is_err() { |
| 4360 | 4395 | return; |
| 4361 | 4396 | } |
modifiedcrates/celld/main/cli.rs+3−0View file
| @@ -41,6 +41,7 @@ | ||
| 41 | 41 | D1(Vec<String>), |
| 42 | 42 | Kv(Vec<String>), |
| 43 | 43 | Queue(Vec<String>), |
| 44 | + R2(Vec<String>), | |
| 44 | 45 | Connect(Vec<String>), |
| 45 | 46 | Credentials(Vec<String>), |
| 46 | 47 | Token(Vec<String>), |
| @@ -77,6 +78,7 @@ | ||
| 77 | 78 | "d1" => return Ok(Action::D1(arguments)), |
| 78 | 79 | "kv" => return Ok(Action::Kv(arguments)), |
| 79 | 80 | "queue" => return Ok(Action::Queue(arguments)), |
| 81 | + "r2" => return Ok(Action::R2(arguments)), | |
| 80 | 82 | "connect" => return Ok(Action::Connect(arguments)), |
| 81 | 83 | "credentials" => return Ok(Action::Credentials(arguments)), |
| 82 | 84 | "token" => return Ok(Action::Token(arguments)), |
| @@ -272,6 +274,7 @@ | ||
| 272 | 274 | celld d1 execute DATABASE --command SQL [PROJECT] --bucket [s3://|gs://|az://]NAME[/PREFIX] |
| 273 | 275 | celld kv get|put|delete|list|info NAMESPACE --bucket [s3://|gs://|az://]NAME[/PREFIX] |
| 274 | 276 | celld queue info|peek|purge|pause|resume|redrive QUEUE --bucket [s3://|gs://|az://]NAME[/PREFIX] |
| 277 | + celld r2 get|head|put|delete|list BUCKET [KEY] --bucket [s3://|gs://|az://]NAME[/PREFIX] | |
| 275 | 278 | celld diagnose --bucket [s3://|gs://|az://]NAME[/PREFIX] [OPTIONS] [--peer NODE_ID]... |
| 276 | 279 | |
| 277 | 280 | Production install: celld --bucket s3://NAME [OPTIONS] |
modifiedcrates/celld/memory.rs+140−0View file
| @@ -177,6 +177,146 @@ | ||
| 177 | 177 | (resident as u64).saturating_sub(allocated as u64) |
| 178 | 178 | } |
| 179 | 179 | |
| 180 | +/// The allocator's own view of the heap, for `/state`. | |
| 181 | +/// | |
| 182 | +/// RSS and `in_use_bytes` cannot say whether memory belongs to Rust or to | |
| 183 | +/// V8: V8 maps its heaps itself, so both counts include it. `allocated` is | |
| 184 | +/// what Rust code holds right now, `active` adds the pages jemalloc has | |
| 185 | +/// given to size classes, `resident` adds the dirty pages it keeps for | |
| 186 | +/// reuse, and `mapped` and `retained` are its address space. The residual | |
| 187 | +/// a hibernated cell leaves (about 160 KB on GCE, measured 2026-09-03) | |
| 188 | +/// is in `allocated` if it is a Rust structure and outside it if it is not. | |
| 189 | +#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize)] | |
| 190 | +pub struct AllocatorStats { | |
| 191 | + pub allocated_bytes: u64, | |
| 192 | + pub active_bytes: u64, | |
| 193 | + pub resident_bytes: u64, | |
| 194 | + pub mapped_bytes: u64, | |
| 195 | + pub retained_bytes: u64, | |
| 196 | +} | |
| 197 | + | |
| 198 | +/// The allocator statistics after one epoch advance, or `None` when jemalloc | |
| 199 | +/// cannot answer, so a broken allocator does not break `/state`. | |
| 200 | +pub fn allocator_stats() -> Option<AllocatorStats> { | |
| 201 | + tikv_jemalloc_ctl::epoch::advance().ok()?; | |
| 202 | + Some(AllocatorStats { | |
| 203 | + allocated_bytes: tikv_jemalloc_ctl::stats::allocated::read().ok()? as u64, | |
| 204 | + active_bytes: tikv_jemalloc_ctl::stats::active::read().ok()? as u64, | |
| 205 | + resident_bytes: tikv_jemalloc_ctl::stats::resident::read().ok()? as u64, | |
| 206 | + mapped_bytes: tikv_jemalloc_ctl::stats::mapped::read().ok()? as u64, | |
| 207 | + retained_bytes: tikv_jemalloc_ctl::stats::retained::read().ok()? as u64, | |
| 208 | + }) | |
| 209 | +} | |
| 210 | + | |
| 211 | +/// The C allocator's own view of its heap, for `/state`, on Linux only. | |
| 212 | +/// | |
| 213 | +/// Rust allocates through jemalloc, but SQLite and V8's C++ side allocate | |
| 214 | +/// through the system allocator, and glibc keeps a freed chunk in its | |
| 215 | +/// arena until the top of that arena is free. `in_use` is what those | |
| 216 | +/// callers hold and `free` is what glibc keeps for them; RSS counts both. | |
| 217 | +/// The residual a hibernated cell left on GCE (2026-09-03) survived | |
| 218 | +/// every isolate being freed, so this is the counter that decides whether | |
| 219 | +/// it is glibc retention. | |
| 220 | +#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize)] | |
| 221 | +pub struct LibcMallocStats { | |
| 222 | + pub in_use_bytes: u64, | |
| 223 | + pub free_bytes: u64, | |
| 224 | + pub mmap_bytes: u64, | |
| 225 | + pub arena_bytes: u64, | |
| 226 | +} | |
| 227 | + | |
| 228 | +#[cfg(target_os = "linux")] | |
| 229 | +pub fn libc_malloc_stats() -> Option<LibcMallocStats> { | |
| 230 | + // `mallinfo2` exists from glibc 2.33, and the release binaries link | |
| 231 | + // against 2.31, so the symbol is resolved at run time: a node on an | |
| 232 | + // older libc reports null instead of the binary failing to link. The | |
| 233 | + // older `mallinfo` is not a fallback, because its fields are `int` and | |
| 234 | + // wrap above 2 GiB, which a 16 GB node reaches. | |
| 235 | + // SAFETY: `dlsym` on the default namespace takes a C string; the symbol | |
| 236 | + // has the documented signature, reads allocator statistics, and takes | |
| 237 | + // no pointer. | |
| 238 | + let info = unsafe { | |
| 239 | + let symbol = libc::dlsym(libc::RTLD_DEFAULT, c"mallinfo2".as_ptr()); | |
| 240 | + if symbol.is_null() { | |
| 241 | + return None; | |
| 242 | + } | |
| 243 | + let mallinfo2: unsafe extern "C" fn() -> libc::mallinfo2 = std::mem::transmute(symbol); | |
| 244 | + mallinfo2() | |
| 245 | + }; | |
| 246 | + Some(LibcMallocStats { | |
| 247 | + in_use_bytes: info.uordblks as u64, | |
| 248 | + free_bytes: info.fordblks as u64, | |
| 249 | + mmap_bytes: info.hblkhd as u64, | |
| 250 | + arena_bytes: info.arena as u64, | |
| 251 | + }) | |
| 252 | +} | |
| 253 | + | |
| 254 | +#[cfg(not(target_os = "linux"))] | |
| 255 | +pub fn libc_malloc_stats() -> Option<LibcMallocStats> { | |
| 256 | + None | |
| 257 | +} | |
| 258 | + | |
| 259 | +/// Growth of the C allocator's free lists since the last trim that earns | |
| 260 | +/// another one. A trim walks every free chunk of every arena, so it is not | |
| 261 | +/// worth running for the churn of ordinary requests; 32 MiB is about a | |
| 262 | +/// hundred evicted cells' storage caches, so a node hibernating cells | |
| 263 | +/// trims within seconds of the first batch and a busy node with nothing | |
| 264 | +/// freed never does. | |
| 265 | +const C_HEAP_TRIM_THRESHOLD_BYTES: u64 = 32 << 20; | |
| 266 | + | |
| 267 | +/// The free-list size at the last trim, lowered whenever the lists shrink | |
| 268 | +/// below it, so a trim answers memory freed since then and not the chunks a | |
| 269 | +/// previous trim already gave back: `mallinfo2` keeps counting a trimmed | |
| 270 | +/// chunk as free, because trimming decommits its pages and does not take it | |
| 271 | +/// off the list. | |
| 272 | +static C_HEAP_FREE_AT_TRIM: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); | |
| 273 | + | |
| 274 | +/// Give the kernel the pages the C allocator keeps for memory that SQLite | |
| 275 | +/// and V8's C++ side freed, once enough has been freed since the last time. | |
| 276 | +/// | |
| 277 | +/// glibc keeps a freed chunk in its arena until the top of that arena is | |
| 278 | +/// free, and a cell's storage is freed in the middle of an arena when the | |
| 279 | +/// cell stops. Every eviction therefore left about 300 KB on glibc's free | |
| 280 | +/// lists: with 5,000 cells hibernated a node held 1.5 GB there and reported | |
| 281 | +/// 1.6 GB of RSS, and one trim took it to 126 MB (GCE, 2026-09-04). | |
| 282 | +/// jemalloc's background thread already does this for the Rust heap. | |
| 283 | +/// | |
| 284 | +/// Returns the free-list size that earned the trim, for the log. The sample | |
| 285 | +/// that follows sees the node without the retained pages, so the pressure | |
| 286 | +/// classifier measures cells and not the allocator. | |
| 287 | +pub fn trim_c_heap_if_retained() -> Option<u64> { | |
| 288 | + use std::sync::atomic::Ordering; | |
| 289 | + let free_bytes = libc_malloc_stats()?.free_bytes; | |
| 290 | + let floor = C_HEAP_FREE_AT_TRIM | |
| 291 | + .fetch_min(free_bytes, Ordering::Relaxed) | |
| 292 | + .min(free_bytes); | |
| 293 | + if free_bytes.saturating_sub(floor) < C_HEAP_TRIM_THRESHOLD_BYTES { | |
| 294 | + return None; | |
| 295 | + } | |
| 296 | + let started_ms = crate::asyncrt::mono_ms(); | |
| 297 | + trim_c_heap(); | |
| 298 | + C_HEAP_FREE_AT_TRIM.store(free_bytes, Ordering::Relaxed); | |
| 299 | + tracing::debug!( | |
| 300 | + event = "c_heap_trimmed", | |
| 301 | + free_bytes, | |
| 302 | + elapsed_ms = crate::asyncrt::mono_ms().saturating_sub(started_ms), | |
| 303 | + "returned the C allocator's retained free pages to the kernel" | |
| 304 | + ); | |
| 305 | + Some(free_bytes) | |
| 306 | +} | |
| 307 | + | |
| 308 | +#[cfg(target_os = "linux")] | |
| 309 | +fn trim_c_heap() { | |
| 310 | + // SAFETY: `malloc_trim` takes a pad size and touches only the | |
| 311 | + // allocator's own bookkeeping. | |
| 312 | + unsafe { | |
| 313 | + libc::malloc_trim(0); | |
| 314 | + } | |
| 315 | +} | |
| 316 | + | |
| 317 | +#[cfg(not(target_os = "linux"))] | |
| 318 | +fn trim_c_heap() {} | |
| 319 | + | |
| 180 | 320 | /// Ask jemalloc to give freed pages back on a timer. Its 10-second decay runs |
| 181 | 321 | /// only when a thread next calls the allocator, which a node that just shed its |
| 182 | 322 | /// working set does not do. This repairs what RSS reports, not the decision. |
modifiedcrates/celld/node_log.rs+129−46View file
| @@ -300,6 +300,7 @@ | ||
| 300 | 300 | /// listing per cell at once. |
| 301 | 301 | const COVERAGE_READ_CONCURRENCY: usize = 16; |
| 302 | 302 | const BUNDLE_ROW_INDEX_CAPACITY: usize = 512; |
| 303 | +const BUNDLE_GC_EXAMINED_PER_TICK: usize = 512; | |
| 303 | 304 | |
| 304 | 305 | struct IndexedBundle { |
| 305 | 306 | cells: BTreeSet<String>, |
| @@ -311,8 +312,21 @@ | ||
| 311 | 312 | bundles: BTreeMap<String, IndexedBundle>, |
| 312 | 313 | by_cell: BTreeMap<String, BTreeSet<String>>, |
| 313 | 314 | recent: std::collections::VecDeque<String>, |
| 315 | + /// The highest txid whose row metadata left `recent`, per cell epoch. A | |
| 316 | + /// cell needs its evicted bundles only until its per-cell coverage passes | |
| 317 | + /// this cut, so a covered cell costs no bundle read. | |
| 318 | + evicted: BTreeMap<(String, u64), u64>, | |
| 314 | 319 | } |
| 315 | 320 | |
| 321 | +/// One cell epoch's view of the index. The rows, the evicted bundles, and | |
| 322 | +/// their cut come from one lock: an eviction between two reads could drop a | |
| 323 | +/// bundle from both the rows and the evicted set. | |
| 324 | +struct CellBundleRows { | |
| 325 | + located: Vec<celld_ltx::LocatedRow>, | |
| 326 | + evicted: Vec<String>, | |
| 327 | + evicted_through: Option<u64>, | |
| 328 | +} | |
| 329 | + | |
| 316 | 330 | impl BundleIndex { |
| 317 | 331 | fn insert(&mut self, key: String, rows: Vec<celld_ltx::bundle::BundleRow>) { |
| 318 | 332 | let cells: BTreeSet<String> = rows.iter().map(|row| row.cell.clone()).collect(); |
| @@ -339,8 +353,13 @@ | ||
| 339 | 353 | .recent |
| 340 | 354 | .pop_front() |
| 341 | 355 | .expect("an over-capacity bundle row index is not empty"); |
| 342 | - if let Some(bundle) = self.bundles.get_mut(&oldest) { | |
| 343 | - bundle.rows = None; | |
| 356 | + let rows = self | |
| 357 | + .bundles | |
| 358 | + .get_mut(&oldest) | |
| 359 | + .and_then(|bundle| bundle.rows.take()); | |
| 360 | + for row in rows.into_iter().flatten() { | |
| 361 | + let through = self.evicted.entry((row.cell, row.cell_epoch)).or_default(); | |
| 362 | + *through = (*through).max(row.txid); | |
| 344 | 363 | } |
| 345 | 364 | } |
| 346 | 365 | } |
| @@ -361,22 +380,30 @@ | ||
| 361 | 380 | }) |
| 362 | 381 | } |
| 363 | 382 | |
| 364 | - fn recent_rows_for(&self, cell: &str, epoch: u64) -> Vec<celld_ltx::LocatedRow> { | |
| 365 | - self.recent | |
| 366 | - .iter() | |
| 367 | - .filter_map(|key| self.bundles.get_key_value(key)) | |
| 368 | - .flat_map(|(key, bundle)| { | |
| 369 | - bundle | |
| 370 | - .rows | |
| 371 | - .iter() | |
| 372 | - .flatten() | |
| 373 | - .filter(|row| row.cell == cell && row.cell_epoch == epoch) | |
| 374 | - .map(|row| celld_ltx::LocatedRow { | |
| 375 | - source: key.clone(), | |
| 376 | - row: row.clone(), | |
| 377 | - }) | |
| 378 | - }) | |
| 379 | - .collect() | |
| 383 | + fn cell_rows(&self, cell: &str, epoch: u64) -> CellBundleRows { | |
| 384 | + let mut located = Vec::new(); | |
| 385 | + let mut evicted = Vec::new(); | |
| 386 | + for key in self.by_cell.get(cell).into_iter().flatten() { | |
| 387 | + let Some(bundle) = self.bundles.get(key) else { | |
| 388 | + continue; | |
| 389 | + }; | |
| 390 | + match &bundle.rows { | |
| 391 | + Some(rows) => located.extend( | |
| 392 | + rows.iter() | |
| 393 | + .filter(|row| row.cell == cell && row.cell_epoch == epoch) | |
| 394 | + .map(|row| celld_ltx::LocatedRow { | |
| 395 | + source: key.clone(), | |
| 396 | + row: row.clone(), | |
| 397 | + }), | |
| 398 | + ), | |
| 399 | + None => evicted.push(key.clone()), | |
| 400 | + } | |
| 401 | + } | |
| 402 | + CellBundleRows { | |
| 403 | + located, | |
| 404 | + evicted, | |
| 405 | + evicted_through: self.evicted.get(&(cell.to_string(), epoch)).copied(), | |
| 406 | + } | |
| 380 | 407 | } |
| 381 | 408 | |
| 382 | 409 | fn remove(&mut self, keys: &[String]) { |
| @@ -3502,6 +3529,9 @@ | ||
| 3502 | 3529 | /// metadata stays bounded. A restart loses the index safely because it |
| 3503 | 3530 | /// creates a new session and recovers the previous session as one unit. |
| 3504 | 3531 | bundle_index: Mutex<BundleIndex>, |
| 3532 | + /// Resume after examined bundles, including those not yet covered. | |
| 3533 | + /// Serialize passes so overlapping callers cannot move the cursor back. | |
| 3534 | + bundle_gc_cursor: tokio::sync::Mutex<Option<String>>, | |
| 3505 | 3535 | /// Sessions whose bundle subtree one sweep pass confirmed empty: |
| 3506 | 3536 | /// a permanent tombstone (dead-lease GC never deletes a folded |
| 3507 | 3537 | /// record) must not cost a bundle LIST on every sweep tick forever |
| @@ -3547,7 +3577,7 @@ | ||
| 3547 | 3577 | maintenance_publish_pause: Mutex<Option<Arc<NodeLogTransitionPause>>>, |
| 3548 | 3578 | #[cfg(all(test, celld_internal_tests))] |
| 3549 | 3579 | shipper_injection_calls: std::sync::atomic::AtomicU64, |
| 3550 | - /// The gather window budget. The internal test cfg lowers it to fold a | |
| 3580 | + /// The gather window budget. A test override lowers it to fold a | |
| 3551 | 3581 | /// small session in several windows. |
| 3552 | 3582 | #[cfg(all(test, celld_internal_tests))] |
| 3553 | 3583 | recovery_gather_window_bytes: std::sync::atomic::AtomicU64, |
| @@ -4010,6 +4040,7 @@ | ||
| 4010 | 4040 | inner: Mutex::new(None), |
| 4011 | 4041 | bundle_seq: std::sync::atomic::AtomicU64::new(0), |
| 4012 | 4042 | bundle_index: Mutex::new(BundleIndex::default()), |
| 4043 | + bundle_gc_cursor: tokio::sync::Mutex::new(None), | |
| 4013 | 4044 | bundle_cache: tokio::sync::Mutex::new(None), |
| 4014 | 4045 | health: Arc::new(Mutex::new(celld_logic::log_evict::FollowerHealth::default())), |
| 4015 | 4046 | policy: Arc::new(policy), |
| @@ -5643,35 +5674,35 @@ | ||
| 5643 | 5674 | } |
| 5644 | 5675 | |
| 5645 | 5676 | pub async fn gc_bundles(&self) -> anyhow::Result<()> { |
| 5646 | - // 512, not 32: the lab's profiling round found 1,300+ retained | |
| 5647 | - // bundles — at ~1 bundle/s produced and 32 examined per 30 s tick | |
| 5648 | - // the backlog only ever grew, and recovery's whole-prefix gather | |
| 5649 | - // paid for it (89-112 s of a 97-116 s outage). The examined set | |
| 5650 | - // costs one LIST plus mostly index-hits; the covered_txid cache | |
| 5651 | - // bounds the per-tick LIST fan-out to the cell count. The TIME | |
| 5652 | - // budget is the other half: un-indexed bundles cost a GET each, | |
| 5653 | - // and an unbounded drain pass competed with serving hard enough | |
| 5654 | - // to gray followers and trigger eviction churn (the ~300 ms | |
| 5655 | - // bucket-riding window the faceted latency lanes exposed). The | |
| 5656 | - // pass stops at the budget; the next tick continues where the | |
| 5657 | - // listing puts it. | |
| 5658 | - const EXAMINED_PER_TICK: usize = 512; | |
| 5677 | + // Bound both the listing and the work. Restarting at the prefix | |
| 5678 | + // every tick starved newer, covered bundles behind an undrained | |
| 5679 | + // prefix forever. Advance after every examination, even a failed GET, | |
| 5680 | + // and wrap only when the page reaches the end of the session. | |
| 5659 | 5681 | const TICK_BUDGET: std::time::Duration = std::time::Duration::from_secs(2); |
| 5682 | + let mut cursor = self.bundle_gc_cursor.lock().await; | |
| 5660 | 5683 | let started = mono_ms(); |
| 5661 | 5684 | let prefix = format!("log/{}/bundle/", self.session); |
| 5685 | + let page = self | |
| 5686 | + .bucket | |
| 5687 | + .list_page( | |
| 5688 | + &prefix, | |
| 5689 | + cursor.as_deref(), | |
| 5690 | + BUNDLE_GC_EXAMINED_PER_TICK, | |
| 5691 | + None, | |
| 5692 | + ) | |
| 5693 | + .await?; | |
| 5662 | 5694 | let mut covered: HashMap<(String, u64), u64> = HashMap::new(); |
| 5663 | 5695 | let mut deletable: Vec<(String, usize)> = Vec::new(); |
| 5664 | - for meta in self | |
| 5665 | - .bucket | |
| 5666 | - .list(&prefix) | |
| 5667 | - .await? | |
| 5668 | - .into_iter() | |
| 5669 | - .take(EXAMINED_PER_TICK) | |
| 5670 | - { | |
| 5671 | - if mono_ms().saturating_sub(started) > TICK_BUDGET.as_millis() as u64 { | |
| 5696 | + let mut exhausted = true; | |
| 5697 | + for (examined, meta) in page.objects.into_iter().enumerate() { | |
| 5698 | + // Always examine one object so a slow listing cannot prevent | |
| 5699 | + // progress. The budget can stop the remainder of the page. | |
| 5700 | + if examined > 0 && mono_ms().saturating_sub(started) > TICK_BUDGET.as_millis() as u64 { | |
| 5701 | + exhausted = false; | |
| 5672 | 5702 | break; |
| 5673 | 5703 | } |
| 5674 | - let key = meta.location.as_ref().to_string(); | |
| 5704 | + let key = meta.key; | |
| 5705 | + *cursor = Some(key.clone()); | |
| 5675 | 5706 | let indexed = { |
| 5676 | 5707 | let index = self.bundle_index.lock().unwrap(); |
| 5677 | 5708 | index.rows(&key) |
| @@ -5700,12 +5731,20 @@ | ||
| 5700 | 5731 | } |
| 5701 | 5732 | }; |
| 5702 | 5733 | paired.push((row.txid, watermark)); |
| 5734 | + // One uncovered row retains the whole bundle. Do not pay | |
| 5735 | + // for every other cell before reaching the same answer. | |
| 5736 | + if !log_tier::bundle_deletable([(row.txid, watermark)]) { | |
| 5737 | + break; | |
| 5738 | + } | |
| 5703 | 5739 | } |
| 5704 | 5740 | if !log_tier::bundle_deletable(paired) { |
| 5705 | 5741 | continue; |
| 5706 | 5742 | } |
| 5707 | 5743 | deletable.push((key, rows.len())); |
| 5708 | 5744 | } |
| 5745 | + if exhausted && !page.truncated { | |
| 5746 | + *cursor = None; | |
| 5747 | + } | |
| 5709 | 5748 | if deletable.is_empty() { |
| 5710 | 5749 | return Ok(()); |
| 5711 | 5750 | } |
| @@ -6089,11 +6128,55 @@ | ||
| 6089 | 6128 | !self.closing.load(Ordering::SeqCst) && self.inner.lock().unwrap().is_some() |
| 6090 | 6129 | } |
| 6091 | 6130 | |
| 6092 | - pub(crate) fn rows_for(&self, cell: &str, epoch: u64) -> Vec<celld_ltx::LocatedRow> { | |
| 6093 | - self.bundle_index | |
| 6094 | - .lock() | |
| 6095 | - .unwrap() | |
| 6096 | - .recent_rows_for(cell, epoch) | |
| 6131 | + /// One cell epoch's retained bundle rows, for the compaction overlay. | |
| 6132 | + /// A slow cell can outlive the bounded row index, so a row that left the | |
| 6133 | + /// index is read from the persisted bundles that the membership names. | |
| 6134 | + pub(crate) async fn rows_for( | |
| 6135 | + &self, | |
| 6136 | + cell: &str, | |
| 6137 | + epoch: u64, | |
| 6138 | + ) -> anyhow::Result<Vec<celld_ltx::LocatedRow>> { | |
| 6139 | + let CellBundleRows { | |
| 6140 | + mut located, | |
| 6141 | + evicted, | |
| 6142 | + evicted_through, | |
| 6143 | + } = self.bundle_index.lock().unwrap().cell_rows(cell, epoch); | |
| 6144 | + let covered = self.ltx.covered_txid(cell, epoch).await; | |
| 6145 | + if evicted_through.is_some_and(|through| covered < through) { | |
| 6146 | + // A cache is not the source of truth. A slow cell can lose its | |
| 6147 | + // first row long before it reaches the compaction threshold. | |
| 6148 | + // Fetch only the evicted bundles that contain the cell, with | |
| 6149 | + // bounded concurrency. A failed read must fail the compaction; | |
| 6150 | + // treating it as no rows would hide a gap or report false | |
| 6151 | + // completion. | |
| 6152 | + let fetches = evicted.into_iter().map(|key| async move { | |
| 6153 | + let rows = match self.bucket.get(&key).await? { | |
| 6154 | + Some((bytes, _)) => celld_ltx::bundle::decode_rows(&bytes)?, | |
| 6155 | + // GC removes only rows covered by the per-cell layout. | |
| 6156 | + // A concurrent deletion is safe to omit. | |
| 6157 | + None => Vec::new(), | |
| 6158 | + }; | |
| 6159 | + anyhow::Ok((key, rows)) | |
| 6160 | + }); | |
| 6161 | + let mut fetches = | |
| 6162 | + futures_util::stream::iter(fetches).buffer_unordered(COVERAGE_READ_CONCURRENCY); | |
| 6163 | + while let Some(fetched) = fetches.next().await { | |
| 6164 | + let (key, rows) = fetched?; | |
| 6165 | + located.extend( | |
| 6166 | + rows.into_iter() | |
| 6167 | + .filter(|row| row.cell == cell && row.cell_epoch == epoch) | |
| 6168 | + .map(|row| celld_ltx::LocatedRow { | |
| 6169 | + source: key.clone(), | |
| 6170 | + row, | |
| 6171 | + }), | |
| 6172 | + ); | |
| 6173 | + } | |
| 6174 | + } | |
| 6175 | + // A folded L0 can cover several rows still in the index. The | |
| 6176 | + // overlay deduplicates file starts, not interior transactions; | |
| 6177 | + // returning those rows merges the same transaction twice. | |
| 6178 | + located.retain(|located| located.row.txid > covered); | |
| 6179 | + Ok(located) | |
| 6097 | 6180 | } |
| 6098 | 6181 | |
| 6099 | 6182 | pub(crate) async fn fetch_bundle(&self, source: &str) -> anyhow::Result<Vec<u8>> { |
modifiedcrates/celld/ownership_store.rs+4−10View file
| @@ -45,16 +45,10 @@ | ||
| 45 | 45 | /// records readable during a mixed-version rollout. |
| 46 | 46 | #[serde(default)] |
| 47 | 47 | pub(crate) paced_handoff: bool, |
| 48 | - /// The process generation. In production this IS `probe_public_key`, | |
| 49 | - /// published twice under two names. Part 1 (this release) reads the | |
| 50 | - /// probe key when the old field is absent, see `NodeLeaseWireRaw`. | |
| 51 | - /// Part 2, after 2026-10-01: stop writing this field, publish only | |
| 52 | - /// `probe_public_key`, and derive the generation from it everywhere, | |
| 53 | - /// which needs the probe signer to draw from the simulation-aware RNG | |
| 54 | - /// so the deterministic worlds keep their replay, and the private | |
| 55 | - /// fixtures that plant `ownership_index_generation` to plant | |
| 56 | - /// `probe_public_key` instead. The reader fallback stays; it becomes | |
| 57 | - /// the only path. | |
| 48 | + /// The process generation has the same value as `probe_public_key` in | |
| 49 | + /// production. Keep writing both names while older nodes read this one. | |
| 50 | + /// `NodeLeaseWireRaw` reads the probe key when this field is absent, so | |
| 51 | + /// a later format can omit the duplicate after mixed-version support ends. | |
| 58 | 52 | #[serde(default, rename = "ownership_index_generation")] |
| 59 | 53 | pub(crate) generation: String, |
| 60 | 54 | /// The folded node log: absent until the |
modifiedcrates/celld/pool.rs+77−0View file
| @@ -456,6 +456,34 @@ | ||
| 456 | 456 | |
| 457 | 457 | type Build = Box<dyn Fn() -> Result<js::Worker> + Send + Sync>; |
| 458 | 458 | |
| 459 | +/// One pool's isolates by state, as `/state` reports them. | |
| 460 | +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize)] | |
| 461 | +pub struct PoolCensus { | |
| 462 | + /// Isolates that accept placement and work. | |
| 463 | + pub live: usize, | |
| 464 | + /// Live isolates that house no cell. The next maintenance pass retires | |
| 465 | + /// them, so a count that persists across passes means the pass is not | |
| 466 | + /// running. | |
| 467 | + pub live_empty: usize, | |
| 468 | + /// Retiring isolates whose heap is still installed, because a turn, a | |
| 469 | + /// request, or a cell holds it. | |
| 470 | + pub retiring: usize, | |
| 471 | + /// Slots whose heap has been freed. | |
| 472 | + pub freed: usize, | |
| 473 | + /// Cells housed across the pool. | |
| 474 | + pub cells: usize, | |
| 475 | + /// Request affiliations across the pool, running or suspended. | |
| 476 | + pub requests: usize, | |
| 477 | + /// Turns in flight across the pool. | |
| 478 | + pub turns: usize, | |
| 479 | + /// Physical memory V8 has committed to the heaps of the isolates a turn | |
| 480 | + /// did not hold at the sample. | |
| 481 | + pub heap_bytes: u64, | |
| 482 | + /// External memory those isolates track: array buffer stores and the | |
| 483 | + /// like, which live outside the V8 heap. | |
| 484 | + pub external_bytes: u64, | |
| 485 | +} | |
| 486 | + | |
| 459 | 487 | pub struct Pool { |
| 460 | 488 | slots: RwLock<Vec<Arc<Slot>>>, |
| 461 | 489 | limits: PoolLimits, |
| @@ -681,6 +709,10 @@ | ||
| 681 | 709 | /// an empty cell heap carries no warm request capacity worth preserving. |
| 682 | 710 | pub fn reap_empty(&self) { |
| 683 | 711 | let Ok(_maintenance) = self.maintenance.try_write() else { |
| 712 | + tracing::debug!( | |
| 713 | + event = "isolate_reap_skipped", | |
| 714 | + "a cell start holds the pool; empty isolates wait for the next pass" | |
| 715 | + ); | |
| 684 | 716 | return; |
| 685 | 717 | }; |
| 686 | 718 | while self.retire_one() {} |
| @@ -752,6 +784,51 @@ | ||
| 752 | 784 | .filter(|slot| !slot.is_retiring()) |
| 753 | 785 | .count() |
| 754 | 786 | } |
| 787 | + | |
| 788 | + /// What the pool holds right now, for `/state`. | |
| 789 | + /// | |
| 790 | + /// The count an operator of a hibernation-heavy node needs and could | |
| 791 | + /// not get: a dormant cell keeps about 160 KB more than its own records | |
| 792 | + /// explain (GCE, 2026-09-03), and the one O(cells) structure | |
| 793 | + /// that fits is the isolate. `live_empty` is what `reap_empty` retires | |
| 794 | + /// on its next pass and `retiring` is what `may_free` still refuses, so | |
| 795 | + /// either staying positive across passes names the leak. | |
| 796 | + pub fn census(&self) -> PoolCensus { | |
| 797 | + let mut census = PoolCensus::default(); | |
| 798 | + for slot in self.slots.read().expect("pool poisoned").iter() { | |
| 799 | + let load = slot.observe(); | |
| 800 | + census.cells += load.cells; | |
| 801 | + census.requests += load.requests; | |
| 802 | + census.turns += load.turns; | |
| 803 | + // A heap is gone once its worker was taken. A worker a turn | |
| 804 | + // holds right now is installed, so a failed `try_lock` counts | |
| 805 | + // as a heap and never as freed; its size is unknown this pass. | |
| 806 | + // Holding the guard is the permit a turn holds, which is what | |
| 807 | + // makes the V8 lock inside `heap_bytes` uncontended. | |
| 808 | + match slot.worker.try_lock() { | |
| 809 | + Ok(worker) if worker.is_none() => { | |
| 810 | + census.freed += 1; | |
| 811 | + continue; | |
| 812 | + } | |
| 813 | + Ok(worker) => { | |
| 814 | + if let Some(heap) = worker.as_ref().and_then(js::Worker::heap_bytes) { | |
| 815 | + census.heap_bytes += heap.physical; | |
| 816 | + census.external_bytes += heap.external; | |
| 817 | + } | |
| 818 | + } | |
| 819 | + Err(_) => {} | |
| 820 | + } | |
| 821 | + if load.retiring { | |
| 822 | + census.retiring += 1; | |
| 823 | + } else { | |
| 824 | + census.live += 1; | |
| 825 | + if load.cells == 0 { | |
| 826 | + census.live_empty += 1; | |
| 827 | + } | |
| 828 | + } | |
| 829 | + } | |
| 830 | + census | |
| 831 | + } | |
| 755 | 832 | } |
| 756 | 833 | |
| 757 | 834 | /// Refused by policy, or the isolate could not be built. Distinct because the |
addedcrates/celld/r2_cli.rs+592−0View file
| @@ -1,0 +1,592 @@ | ||
| 1 | +// Copyright 2026 Deno Land Inc. Apache-2.0 license. | |
| 2 | + | |
| 3 | +// The R2 CLI reads operator input and object bodies outside node storage. | |
| 4 | +#![allow(clippy::disallowed_methods)] | |
| 5 | + | |
| 6 | +//! `celld r2` — read and write the objects behind an `r2_buckets` binding. | |
| 7 | +//! | |
| 8 | +//! A release pipeline publishes a build artifact with | |
| 9 | +//! `wrangler r2 object put` and the Worker serves it from its `r2_buckets` | |
| 10 | +//! binding. celld served the binding but had no command, so the only way to | |
| 11 | +//! seed a bucket was `aws s3 cp` straight into the fleet bucket. That works | |
| 12 | +//! for the bytes and loses the record: an R2 object carries | |
| 13 | +//! `customMetadata`, a `cacheExpiry`, and its checksums in a celld-private | |
| 14 | +//! envelope that a plain copy does not write. The result reads back with no | |
| 15 | +//! custom metadata, which is a silent difference rather than a failure. | |
| 16 | +//! | |
| 17 | +//! So this command does not implement R2. It installs the fleet bucket the | |
| 18 | +//! same way a node does and calls [`crate::js::r2_ops`] — the functions the | |
| 19 | +//! binding's ops call. The key scoping, the envelope, the checksum set and | |
| 20 | +//! the single-request/multipart choice therefore have one implementation, | |
| 21 | +//! and an object written here is an object the binding could have written. | |
| 22 | +//! | |
| 23 | +//! Unlike `celld d1`, `celld kv` and `celld queue`, this command needs no | |
| 24 | +//! node. A binding reads the fleet bucket directly, so an operator with the | |
| 25 | +//! bucket credentials can publish into an empty fleet — which is what a | |
| 26 | +//! release pipeline that runs before a deployment needs. | |
| 27 | + | |
| 28 | +use crate::cli_options::FLEET_HELP; | |
| 29 | +use crate::cli_options::LISTING_HELP; | |
| 30 | +use crate::cli_output::list; | |
| 31 | +use crate::cli_output::Bounds; | |
| 32 | +use crate::cli_output::Format; | |
| 33 | +use crate::cli_output::Output; | |
| 34 | +use crate::cli_output::Page; | |
| 35 | +use crate::cli_output::Record; | |
| 36 | +use crate::cli_output::Resumable; | |
| 37 | +use crate::cli_output::Resume; | |
| 38 | +use crate::note; | |
| 39 | +use anyhow::anyhow; | |
| 40 | +use anyhow::bail; | |
| 41 | +use anyhow::Context; | |
| 42 | +use serde_json::json; | |
| 43 | +use serde_json::Value; | |
| 44 | +use std::borrow::Cow; | |
| 45 | +use std::collections::BTreeMap; | |
| 46 | +use std::io::Read; | |
| 47 | +use std::path::PathBuf; | |
| 48 | + | |
| 49 | +/// How much of a body the command reads at once. The write buffers what it | |
| 50 | +/// is given and cuts its own parts, so this only bounds the resident copy | |
| 51 | +/// of a body that can be many gigabytes. | |
| 52 | +const READ_CHUNK: usize = 1 << 20; | |
| 53 | + | |
| 54 | +/// One object in a listing. | |
| 55 | +struct Object { | |
| 56 | + key: String, | |
| 57 | + size: u64, | |
| 58 | + etag: Option<String>, | |
| 59 | + uploaded_ms: i64, | |
| 60 | +} | |
| 61 | + | |
| 62 | +impl Record for Object { | |
| 63 | + fn json(&self) -> Value { | |
| 64 | + json!({ | |
| 65 | + "key": self.key, | |
| 66 | + "size": self.size, | |
| 67 | + "etag": self.etag, | |
| 68 | + "uploaded": self.uploaded_ms, | |
| 69 | + }) | |
| 70 | + } | |
| 71 | + | |
| 72 | + fn text(&self) -> Cow<'_, str> { | |
| 73 | + Cow::Borrowed(&self.key) | |
| 74 | + } | |
| 75 | +} | |
| 76 | + | |
| 77 | +impl Resumable for Object { | |
| 78 | + fn cursor(&self) -> &str { | |
| 79 | + &self.key | |
| 80 | + } | |
| 81 | +} | |
| 82 | + | |
| 83 | +/// One object's complete record, as `celld r2 head` reports it. | |
| 84 | +/// | |
| 85 | +/// The JSON carries the binding's object record before the JS conversion. | |
| 86 | +/// Its `http` and `custom` fields become `httpMetadata` and | |
| 87 | +/// `customMetadata` in an `R2Object`. | |
| 88 | +struct Head(Value); | |
| 89 | + | |
| 90 | +impl Record for Head { | |
| 91 | + fn json(&self) -> Value { | |
| 92 | + self.0.clone() | |
| 93 | + } | |
| 94 | + | |
| 95 | + fn text(&self) -> Cow<'_, str> { | |
| 96 | + let field = |name: &str| self.0.get(name).cloned().unwrap_or(Value::Null); | |
| 97 | + let scalar = |value: &Value| match value { | |
| 98 | + Value::Null => "-".to_string(), | |
| 99 | + Value::String(text) => text.clone(), | |
| 100 | + other => other.to_string(), | |
| 101 | + }; | |
| 102 | + let mut lines = vec![ | |
| 103 | + format!("key: {}", scalar(&field("key"))), | |
| 104 | + format!("size: {}", scalar(&field("size"))), | |
| 105 | + format!("etag: {}", scalar(&field("etag"))), | |
| 106 | + format!("uploaded: {}", scalar(&field("uploaded"))), | |
| 107 | + ]; | |
| 108 | + // The two maps print only when they hold something. An object | |
| 109 | + // written by a plain `aws s3 cp` has neither, and an empty block | |
| 110 | + // for each would hide that difference in a wall of dashes. | |
| 111 | + for (label, name) in [("http", "http"), ("custom", "custom")] { | |
| 112 | + if let Some(map) = field(name).as_object().filter(|map| !map.is_empty()) { | |
| 113 | + for (key, value) in map { | |
| 114 | + lines.push(format!("{label}.{key}: {}", scalar(value))); | |
| 115 | + } | |
| 116 | + } | |
| 117 | + } | |
| 118 | + Cow::Owned(lines.join("\n")) | |
| 119 | + } | |
| 120 | +} | |
| 121 | + | |
| 122 | +pub async fn run(arguments: Vec<String>) -> anyhow::Result<()> { | |
| 123 | + let Some(command) = Command::parse(arguments)? else { | |
| 124 | + print_help(); | |
| 125 | + return Ok(()); | |
| 126 | + }; | |
| 127 | + let storage = command.fleet.clone().resolve("celld r2")?; | |
| 128 | + // The binding's store, installed exactly as a node installs it, so | |
| 129 | + // every call below reaches the same keys the Worker reads. | |
| 130 | + crate::js::set_r2_store(storage.open().await?); | |
| 131 | + let bucket = command.bucket.as_str(); | |
| 132 | + | |
| 133 | + match command.action { | |
| 134 | + Action::Get { key } => { | |
| 135 | + let read = crate::js::r2_ops::read( | |
| 136 | + bucket, | |
| 137 | + &key, | |
| 138 | + crate::bucket::BlobRange::Whole, | |
| 139 | + &crate::bucket::BlobConditions::default(), | |
| 140 | + ) | |
| 141 | + .await | |
| 142 | + .map_err(anyhow::Error::msg)?; | |
| 143 | + match read { | |
| 144 | + crate::bucket::BlobRead::Hit(blob) => { | |
| 145 | + // Streamed rather than collected: a release artifact is | |
| 146 | + // routinely larger than the memory a CI runner gives | |
| 147 | + // this process. | |
| 148 | + Output::new(Format::Text).stream(blob.body).await?; | |
| 149 | + } | |
| 150 | + // An unconditional read cannot be refused, so the only | |
| 151 | + // other answer is an absent key. | |
| 152 | + crate::bucket::BlobRead::Missing | crate::bucket::BlobRead::Unmet(_) => { | |
| 153 | + bail!("no object {key:?} in r2 bucket {bucket:?}") | |
| 154 | + } | |
| 155 | + } | |
| 156 | + } | |
| 157 | + Action::Head { key } => { | |
| 158 | + let meta = crate::js::r2_ops::head(bucket, &key) | |
| 159 | + .await | |
| 160 | + .map_err(anyhow::Error::msg)? | |
| 161 | + .ok_or_else(|| anyhow!("no object {key:?} in r2 bucket {bucket:?}"))?; | |
| 162 | + let mut out = Output::new(if command.json { | |
| 163 | + Format::Json | |
| 164 | + } else { | |
| 165 | + Format::Text | |
| 166 | + }); | |
| 167 | + out.row(&Head(crate::js::r2_ops::object_json(&key, &meta, None)))?; | |
| 168 | + out.finish()?; | |
| 169 | + } | |
| 170 | + Action::Put { | |
| 171 | + key, | |
| 172 | + file, | |
| 173 | + http, | |
| 174 | + custom, | |
| 175 | + } => { | |
| 176 | + let request = json!({ "http": http, "custom": custom }).to_string(); | |
| 177 | + let mut put = crate::js::r2_ops::open_put(bucket.to_string(), key.clone(), &request) | |
| 178 | + .map_err(anyhow::Error::msg)?; | |
| 179 | + let mut source = Source::open(file.as_deref())?; | |
| 180 | + let mut buffer = vec![0u8; READ_CHUNK]; | |
| 181 | + loop { | |
| 182 | + let read = source.read(&mut buffer).context("read the object body")?; | |
| 183 | + if read == 0 { | |
| 184 | + break; | |
| 185 | + } | |
| 186 | + put.push(buffer[..read].to_vec()) | |
| 187 | + .await | |
| 188 | + .map_err(anyhow::Error::msg)?; | |
| 189 | + } | |
| 190 | + let answer = put.finish().await.map_err(anyhow::Error::msg)?; | |
| 191 | + let answer: Value = serde_json::from_str(&answer).context("read the write's answer")?; | |
| 192 | + let size = answer | |
| 193 | + .pointer("/object/size") | |
| 194 | + .and_then(Value::as_u64) | |
| 195 | + .unwrap_or_default(); | |
| 196 | + note!("wrote {key:?} ({size} bytes)"); | |
| 197 | + } | |
| 198 | + Action::Delete { keys } => { | |
| 199 | + crate::js::r2_ops::delete(bucket, &keys) | |
| 200 | + .await | |
| 201 | + .map_err(anyhow::Error::msg)?; | |
| 202 | + note!("deleted {} object(s)", keys.len()); | |
| 203 | + } | |
| 204 | + Action::List { prefix, bounds } => { | |
| 205 | + let mut out = Output::new(if command.json { | |
| 206 | + Format::Json | |
| 207 | + } else { | |
| 208 | + Format::Text | |
| 209 | + }); | |
| 210 | + let listed = list(&mut out, &bounds, |resume, want| { | |
| 211 | + let prefix = prefix.clone(); | |
| 212 | + // An operator's `--after` is a key and the driver's own | |
| 213 | + // continuation is the cursor a truncated page answered | |
| 214 | + // with. R2 reads the cursor first and both name the same | |
| 215 | + // place, so either one resumes strictly after that key. | |
| 216 | + let (cursor, after) = match resume { | |
| 217 | + Resume::From(after) => (String::new(), after.unwrap_or_default()), | |
| 218 | + Resume::Token(token) => (token, String::new()), | |
| 219 | + }; | |
| 220 | + async move { | |
| 221 | + let page = crate::js::r2_ops::list( | |
| 222 | + bucket, | |
| 223 | + &json!({ | |
| 224 | + "prefix": prefix, | |
| 225 | + "cursor": cursor, | |
| 226 | + "startAfter": after, | |
| 227 | + "limit": want, | |
| 228 | + }) | |
| 229 | + .to_string(), | |
| 230 | + ) | |
| 231 | + .await | |
| 232 | + .map_err(anyhow::Error::msg)?; | |
| 233 | + let objects = page | |
| 234 | + .get("objects") | |
| 235 | + .and_then(Value::as_array) | |
| 236 | + .ok_or_else(|| anyhow!("the listing carried no objects: {page}"))?; | |
| 237 | + let rows = objects | |
| 238 | + .iter() | |
| 239 | + .map(|object| Object { | |
| 240 | + key: object | |
| 241 | + .get("key") | |
| 242 | + .and_then(Value::as_str) | |
| 243 | + .unwrap_or_default() | |
| 244 | + .to_string(), | |
| 245 | + size: object | |
| 246 | + .get("size") | |
| 247 | + .and_then(Value::as_u64) | |
| 248 | + .unwrap_or_default(), | |
| 249 | + etag: object | |
| 250 | + .get("etag") | |
| 251 | + .and_then(Value::as_str) | |
| 252 | + .map(str::to_string), | |
| 253 | + uploaded_ms: object | |
| 254 | + .get("uploaded") | |
| 255 | + .and_then(Value::as_i64) | |
| 256 | + .unwrap_or_default(), | |
| 257 | + }) | |
| 258 | + .collect(); | |
| 259 | + // The store's own truncation signal, never a row | |
| 260 | + // count: a page filled exactly to its bound is not | |
| 261 | + // evidence that another object exists. | |
| 262 | + let next = page | |
| 263 | + .get("cursor") | |
| 264 | + .and_then(Value::as_str) | |
| 265 | + .map(str::to_string); | |
| 266 | + Ok(Page { rows, next }) | |
| 267 | + } | |
| 268 | + }) | |
| 269 | + .await?; | |
| 270 | + out.finish()?; | |
| 271 | + listed.report("object", "--after"); | |
| 272 | + } | |
| 273 | + } | |
| 274 | + Ok(()) | |
| 275 | +} | |
| 276 | + | |
| 277 | +/// Where a `put` reads its body. A named file and standard input are both | |
| 278 | +/// read in bounded pieces, so neither has to fit in memory. | |
| 279 | +enum Source { | |
| 280 | + File(std::io::BufReader<std::fs::File>), | |
| 281 | + Stdin(std::io::Stdin), | |
| 282 | +} | |
| 283 | + | |
| 284 | +impl Source { | |
| 285 | + fn open(path: Option<&std::path::Path>) -> anyhow::Result<Self> { | |
| 286 | + match path { | |
| 287 | + None => Ok(Self::Stdin(std::io::stdin())), | |
| 288 | + Some(path) => { | |
| 289 | + let file = std::fs::File::open(path) | |
| 290 | + .with_context(|| format!("open {}", path.display()))?; | |
| 291 | + Ok(Self::File(std::io::BufReader::new(file))) | |
| 292 | + } | |
| 293 | + } | |
| 294 | + } | |
| 295 | + | |
| 296 | + fn read(&mut self, buffer: &mut [u8]) -> std::io::Result<usize> { | |
| 297 | + match self { | |
| 298 | + Self::File(file) => file.read(buffer), | |
| 299 | + Self::Stdin(stdin) => stdin.lock().read(buffer), | |
| 300 | + } | |
| 301 | + } | |
| 302 | +} | |
| 303 | + | |
| 304 | +enum Action { | |
| 305 | + Get { | |
| 306 | + key: String, | |
| 307 | + }, | |
| 308 | + Head { | |
| 309 | + key: String, | |
| 310 | + }, | |
| 311 | + Put { | |
| 312 | + key: String, | |
| 313 | + /// `None` reads the body from standard input. | |
| 314 | + file: Option<PathBuf>, | |
| 315 | + /// R2's `httpMetadata`, already in the binding's spelling. | |
| 316 | + http: BTreeMap<String, Value>, | |
| 317 | + /// R2's `customMetadata`. | |
| 318 | + custom: BTreeMap<String, String>, | |
| 319 | + }, | |
| 320 | + Delete { | |
| 321 | + keys: Vec<String>, | |
| 322 | + }, | |
| 323 | + List { | |
| 324 | + prefix: String, | |
| 325 | + bounds: Bounds, | |
| 326 | + }, | |
| 327 | +} | |
| 328 | + | |
| 329 | +struct Command { | |
| 330 | + action: Action, | |
| 331 | + bucket: String, | |
| 332 | + fleet: crate::cli_options::FleetFlags, | |
| 333 | + json: bool, | |
| 334 | +} | |
| 335 | + | |
| 336 | +/// The `httpMetadata` field each flag sets, in R2's spelling. | |
| 337 | +const HTTP_FLAGS: [(&str, &str); 5] = [ | |
| 338 | + ("--content-type", "contentType"), | |
| 339 | + ("--content-language", "contentLanguage"), | |
| 340 | + ("--content-disposition", "contentDisposition"), | |
| 341 | + ("--content-encoding", "contentEncoding"), | |
| 342 | + ("--cache-control", "cacheControl"), | |
| 343 | +]; | |
| 344 | + | |
| 345 | +impl Command { | |
| 346 | + fn parse(arguments: Vec<String>) -> anyhow::Result<Option<Self>> { | |
| 347 | + let mut arguments = arguments.into_iter().peekable(); | |
| 348 | + let Some(first) = arguments.next() else { | |
| 349 | + return Ok(None); | |
| 350 | + }; | |
| 351 | + let verb = match first.as_str() { | |
| 352 | + "--help" | "-h" | "help" => return Ok(None), | |
| 353 | + verb @ ("get" | "head" | "put" | "delete" | "list") => verb.to_string(), | |
| 354 | + other => bail!("unknown `celld r2` subcommand: {other}"), | |
| 355 | + }; | |
| 356 | + // The bucket is the `bucket_name` from `r2_buckets`, not the | |
| 357 | + // binding name: the name is what places the keys in the fleet | |
| 358 | + // bucket, and it is the one an `env.BUCKET` call resolves to. | |
| 359 | + let bucket = arguments | |
| 360 | + .next() | |
| 361 | + .filter(|value| !value.starts_with('-')) | |
| 362 | + .ok_or_else(|| anyhow!("celld r2 needs an r2 bucket name"))?; | |
| 363 | + // The same rule the deployment applies to `bucket_name`. Without | |
| 364 | + // it a name with a `/` in it would write under another binding's | |
| 365 | + // prefix, or outside the reserved `r2/` space entirely. | |
| 366 | + if !crate::deploy::valid_resource_name(&bucket) { | |
| 367 | + bail!( | |
| 368 | + "invalid r2 bucket name {bucket:?}: use letters, digits, `-` and `_` \ | |
| 369 | + (not starting with `-`), at most 64 characters" | |
| 370 | + ); | |
| 371 | + } | |
| 372 | + | |
| 373 | + let mut positional = Vec::new(); | |
| 374 | + let mut file = None; | |
| 375 | + let mut pipe = false; | |
| 376 | + let mut metadata = None; | |
| 377 | + let mut prefix = String::new(); | |
| 378 | + let mut http = BTreeMap::new(); | |
| 379 | + let mut cache_expiry = None; | |
| 380 | + let mut fleet = crate::cli_options::FleetFlags::default(); | |
| 381 | + let mut bounds = Bounds::default(); | |
| 382 | + let mut json = false; | |
| 383 | + while let Some(argument) = arguments.next() { | |
| 384 | + let mut value = |flag: &str| { | |
| 385 | + arguments | |
| 386 | + .next() | |
| 387 | + .ok_or_else(|| anyhow!("{flag} requires a value")) | |
| 388 | + }; | |
| 389 | + match argument.as_str() { | |
| 390 | + "--path" | "--file" => file = Some(PathBuf::from(value("--path")?)), | |
| 391 | + "--pipe" => pipe = true, | |
| 392 | + "--metadata" => metadata = Some(value("--metadata")?), | |
| 393 | + "--cache-expiry" => { | |
| 394 | + let raw = value("--cache-expiry")?; | |
| 395 | + cache_expiry = Some(raw.parse::<i64>().with_context(|| { | |
| 396 | + format!("--cache-expiry takes unix milliseconds, got {raw:?}") | |
| 397 | + })?); | |
| 398 | + } | |
| 399 | + "--prefix" => prefix = value("--prefix")?, | |
| 400 | + "--json" => json = true, | |
| 401 | + // celld has neither concept, and a flag that silently means | |
| 402 | + // nothing is the gap the compatibility page forbids. | |
| 403 | + flag @ ("--local" | "--remote" | "--jurisdiction") => bail!( | |
| 404 | + "celld r2 does not take {flag}: celld runs neither a local \ | |
| 405 | + miniflare store nor a Cloudflare account, and it has no \ | |
| 406 | + jurisdiction. An r2 bucket name addresses one key space in \ | |
| 407 | + one fleet." | |
| 408 | + ), | |
| 409 | + "--help" | "-h" => return Ok(None), | |
| 410 | + other => { | |
| 411 | + if let Some((_, field)) = HTTP_FLAGS.iter().find(|(flag, _)| *flag == other) { | |
| 412 | + let text = value(other)?; | |
| 413 | + http.insert((*field).to_string(), Value::String(text)); | |
| 414 | + continue; | |
| 415 | + } | |
| 416 | + // The shared flags first, so `--bucket`, `--limit` and | |
| 417 | + // their siblings mean here exactly what they mean in | |
| 418 | + // every other command. | |
| 419 | + if fleet.consume(other, &mut value)? || bounds.consume(other, &mut value)? { | |
| 420 | + continue; | |
| 421 | + } | |
| 422 | + if other.starts_with('-') { | |
| 423 | + bail!("unknown option: {other}; run `celld r2 --help` for usage") | |
| 424 | + } | |
| 425 | + positional.push(other.to_string()); | |
| 426 | + } | |
| 427 | + } | |
| 428 | + } | |
| 429 | + if let Some(expiry) = cache_expiry { | |
| 430 | + http.insert("cacheExpiry".to_string(), Value::from(expiry)); | |
| 431 | + } | |
| 432 | + // A flag the verb does not read must be a refusal. Accepting | |
| 433 | + // `--content-type` on a `get` would tell an operator they set a | |
| 434 | + // header that nothing wrote. | |
| 435 | + let refuse = |flag: &str, set: bool| -> anyhow::Result<()> { | |
| 436 | + if set { | |
| 437 | + bail!("`celld r2 {verb}` takes no {flag}"); | |
| 438 | + } | |
| 439 | + Ok(()) | |
| 440 | + }; | |
| 441 | + let write_flags = !http.is_empty() || metadata.is_some(); | |
| 442 | + let one_key = |what: &str| -> anyhow::Result<String> { | |
| 443 | + let [key] = positional.as_slice() else { | |
| 444 | + bail!("celld r2 {what} needs exactly one key"); | |
| 445 | + }; | |
| 446 | + Ok(key.clone()) | |
| 447 | + }; | |
| 448 | + let action = match verb.as_str() { | |
| 449 | + "get" | "head" => { | |
| 450 | + refuse("--path", file.is_some())?; | |
| 451 | + refuse("--pipe", pipe)?; | |
| 452 | + refuse("--metadata or a content flag", write_flags)?; | |
| 453 | + let key = one_key(&verb)?; | |
| 454 | + match verb.as_str() { | |
| 455 | + "get" => Action::Get { key }, | |
| 456 | + _ => Action::Head { key }, | |
| 457 | + } | |
| 458 | + } | |
| 459 | + "put" => { | |
| 460 | + let key = one_key("put")?; | |
| 461 | + // Reading a body from a terminal by default would hang | |
| 462 | + // with no output, so standard input is opt-in. | |
| 463 | + if file.is_some() == pipe { | |
| 464 | + bail!("celld r2 put requires exactly one of --path FILE or --pipe"); | |
| 465 | + } | |
| 466 | + let custom = match &metadata { | |
| 467 | + None => BTreeMap::new(), | |
| 468 | + Some(text) => parse_metadata(text)?, | |
| 469 | + }; | |
| 470 | + Action::Put { | |
| 471 | + key, | |
| 472 | + file, | |
| 473 | + http, | |
| 474 | + custom, | |
| 475 | + } | |
| 476 | + } | |
| 477 | + "delete" => { | |
| 478 | + refuse("--path", file.is_some())?; | |
| 479 | + refuse("--pipe", pipe)?; | |
| 480 | + refuse("--metadata or a content flag", write_flags)?; | |
| 481 | + if positional.is_empty() { | |
| 482 | + bail!("celld r2 delete needs at least one key"); | |
| 483 | + } | |
| 484 | + Action::Delete { keys: positional } | |
| 485 | + } | |
| 486 | + "list" => { | |
| 487 | + refuse("--path", file.is_some())?; | |
| 488 | + refuse("--pipe", pipe)?; | |
| 489 | + refuse("--metadata or a content flag", write_flags)?; | |
| 490 | + if !positional.is_empty() { | |
| 491 | + bail!("celld r2 list takes no positional arguments; use --prefix"); | |
| 492 | + } | |
| 493 | + Action::List { | |
| 494 | + prefix, | |
| 495 | + bounds: bounds.clone(), | |
| 496 | + } | |
| 497 | + } | |
| 498 | + _ => unreachable!("the verb was matched above"), | |
| 499 | + }; | |
| 500 | + bounds.validate()?; | |
| 501 | + Ok(Some(Self { | |
| 502 | + action, | |
| 503 | + bucket, | |
| 504 | + fleet: fleet.with_environment(), | |
| 505 | + json, | |
| 506 | + })) | |
| 507 | + } | |
| 508 | +} | |
| 509 | + | |
| 510 | +/// `--metadata` as R2's `customMetadata`: a flat object of strings. | |
| 511 | +/// | |
| 512 | +/// A nested value is refused rather than stringified. R2 stores strings, so | |
| 513 | +/// accepting an object would write `[object Object]` on one side of the | |
| 514 | +/// binding and a JSON document on the other. | |
| 515 | +fn parse_metadata(text: &str) -> anyhow::Result<BTreeMap<String, String>> { | |
| 516 | + let parsed: Value = serde_json::from_str(text).context("parse --metadata as JSON")?; | |
| 517 | + let object = parsed | |
| 518 | + .as_object() | |
| 519 | + .ok_or_else(|| anyhow!("--metadata takes a JSON object of strings"))?; | |
| 520 | + object | |
| 521 | + .iter() | |
| 522 | + .map(|(name, value)| match value { | |
| 523 | + Value::String(text) => Ok((name.clone(), text.clone())), | |
| 524 | + _ => Err(anyhow!( | |
| 525 | + "--metadata value for {name:?} must be a string, because R2 \ | |
| 526 | + stores customMetadata as strings" | |
| 527 | + )), | |
| 528 | + }) | |
| 529 | + .collect() | |
| 530 | +} | |
| 531 | + | |
| 532 | +pub fn print_help() { | |
| 533 | + // The whole block is laid out here, and the content flags are generated | |
| 534 | + // from the table the parser reads, so a flag cannot be accepted and | |
| 535 | + // undocumented, or documented and rejected. The column is wide enough | |
| 536 | + // for `--content-disposition VALUE`, which is the longest of them. | |
| 537 | + let row = |flag: String, text: &str| format!(" {flag:<27} {text}"); | |
| 538 | + let flags = [ | |
| 539 | + row("--path FILE".to_string(), "read the body from a file"), | |
| 540 | + row("--pipe".to_string(), "read the body from standard input"), | |
| 541 | + row( | |
| 542 | + "--metadata JSON".to_string(), | |
| 543 | + "customMetadata, as a JSON object of strings", | |
| 544 | + ), | |
| 545 | + ] | |
| 546 | + .into_iter() | |
| 547 | + .chain(HTTP_FLAGS.iter().map(|(flag, field)| { | |
| 548 | + row( | |
| 549 | + format!("{flag} VALUE"), | |
| 550 | + &format!("set httpMetadata.{field}"), | |
| 551 | + ) | |
| 552 | + })) | |
| 553 | + .chain(std::iter::once(row( | |
| 554 | + "--cache-expiry MS".to_string(), | |
| 555 | + "set httpMetadata.cacheExpiry, in unix milliseconds", | |
| 556 | + ))) | |
| 557 | + .collect::<Vec<_>>() | |
| 558 | + .join("\n"); | |
| 559 | + let text = format!( | |
| 560 | + "celld r2 — read and write the objects behind an `r2_buckets` binding | |
| 561 | + | |
| 562 | +USAGE | |
| 563 | + celld r2 get <bucket-name> <key> [fleet options] | |
| 564 | + celld r2 head <bucket-name> <key> [--json] [fleet options] | |
| 565 | + celld r2 put <bucket-name> <key> --path FILE | --pipe [put options] | |
| 566 | + celld r2 delete <bucket-name> <key>... [fleet options] | |
| 567 | + celld r2 list <bucket-name> [--prefix P] [listing options] | |
| 568 | + | |
| 569 | +The bucket name is the `bucket_name` from the project's `r2_buckets` entry, | |
| 570 | +not the binding name. `get` writes the object to stdout as bytes, so an | |
| 571 | +artifact comes back byte for byte. | |
| 572 | + | |
| 573 | +This command reads the fleet bucket directly and needs no running node, so | |
| 574 | +a release pipeline can publish an object before it deploys the Worker. | |
| 575 | + | |
| 576 | +PUT OPTIONS | |
| 577 | +{flags} | |
| 578 | + | |
| 579 | +LISTING OPTIONS (list) | |
| 580 | + --prefix P list only the keys under this prefix | |
| 581 | +{LISTING_HELP} | |
| 582 | + | |
| 583 | +FLEET OPTIONS | |
| 584 | +{FLEET_HELP} | |
| 585 | + | |
| 586 | +An object written here carries the same record as one a Worker writes: | |
| 587 | +customMetadata, cacheExpiry and the checksums travel in a celld envelope | |
| 588 | +beside the five content headers. A copy made with another tool still reads | |
| 589 | +through the binding, and its user metadata becomes its customMetadata." | |
| 590 | + ); | |
| 591 | + let _ = crate::cli_output::Output::new(crate::cli_output::Format::Text).help(&text); | |
| 592 | +} |
modifiedcrates/celld/runtime.rs+12−6View file
| @@ -152,11 +152,13 @@ | ||
| 152 | 152 | job: crate::WorkerJob::Fetch { |
| 153 | 153 | queued_at: Instant::now(), |
| 154 | 154 | entrypoint, |
| 155 | + invocation_limits: None, | |
| 155 | 156 | url, |
| 156 | 157 | method, |
| 157 | 158 | body, |
| 158 | 159 | headers, |
| 159 | 160 | request_id, |
| 161 | + tail_report: None, | |
| 160 | 162 | reply, |
| 161 | 163 | }, |
| 162 | 164 | cancellation, |
| @@ -1567,15 +1569,15 @@ | ||
| 1567 | 1569 | next |
| 1568 | 1570 | } |
| 1569 | 1571 | |
| 1570 | - /// The generations still draining: id and version, for `/state`. | |
| 1571 | - pub fn draining_generations(&self) -> Vec<(GenerationId, String)> { | |
| 1572 | + /// The generations still draining, for `/state`. Each one holds its | |
| 1573 | + /// isolates until the last cell in them moves, so the caller reads the | |
| 1574 | + /// census from the generation and not only its version. | |
| 1575 | + pub fn draining_generations(&self) -> Vec<Arc<Generation>> { | |
| 1572 | 1576 | self.generations |
| 1573 | 1577 | .read() |
| 1574 | 1578 | .expect("generation lock poisoned") |
| 1575 | 1579 | .draining |
| 1576 | - .iter() | |
| 1577 | - .map(|generation| (generation.id, generation.version.clone())) | |
| 1578 | - .collect() | |
| 1580 | + .clone() | |
| 1579 | 1581 | } |
| 1580 | 1582 | |
| 1581 | 1583 | /// Spawn the maintenance loop for one generation's cell pools. |
| @@ -1735,11 +1737,13 @@ | ||
| 1735 | 1737 | let job = crate::WorkerJob::Fetch { |
| 1736 | 1738 | queued_at: Instant::now(), |
| 1737 | 1739 | entrypoint: None, |
| 1740 | + invocation_limits: None, | |
| 1738 | 1741 | url, |
| 1739 | 1742 | method, |
| 1740 | 1743 | body, |
| 1741 | 1744 | headers, |
| 1742 | 1745 | request_id: Some(request_id), |
| 1746 | + tail_report: None, | |
| 1743 | 1747 | reply, |
| 1744 | 1748 | }; |
| 1745 | 1749 | tokio::spawn(async move { |
| @@ -2930,6 +2934,7 @@ | ||
| 2930 | 2934 | on_finish(&entry); |
| 2931 | 2935 | // Dropping `ops` aborts whatever is still pending, which is what a region |
| 2932 | 2936 | // does on every exit path; their resolvers have to go with them. |
| 2937 | + entry.finish_tail_report(); | |
| 2933 | 2938 | entry.abandon(); |
| 2934 | 2939 | } |
| 2935 | 2940 | |
| @@ -3490,6 +3495,7 @@ | ||
| 3490 | 3495 | entrypoint, |
| 3491 | 3496 | operation, |
| 3492 | 3497 | props, |
| 3498 | + invocation_limits: None, | |
| 3493 | 3499 | reply, |
| 3494 | 3500 | }) |
| 3495 | 3501 | .await |
| @@ -3562,7 +3568,7 @@ | ||
| 3562 | 3568 | /// A count rather than a latch, so a test can prove the retry reaches |
| 3563 | 3569 | /// success instead of only proving that it never proceeds. `debug_assertions` |
| 3564 | 3570 | /// is the gate `CELLD_TEST_CELL_STARTUP_FAILURE` beside it already uses: the |
| 3565 | -/// runtime matrix drives the shipped debug binary, which no private cfg | |
| 3571 | +/// runtime matrix drives the debug binary, which no internal test cfg | |
| 3566 | 3572 | /// reaches, and a release build compiles neither. |
| 3567 | 3573 | #[cfg(debug_assertions)] |
| 3568 | 3574 | fn injected_swap_release_failure() -> Option<anyhow::Error> { |
modifiedcrates/celld/storage.rs+15−9View file
| @@ -243,7 +243,7 @@ | ||
| 243 | 243 | ON CONFLICT(scope,k) DO UPDATE SET v=excluded.v"; |
| 244 | 244 | const KV_DELETE_SQL: &str = "DELETE FROM _cf_KV WHERE scope=?1 AND k=?2"; |
| 245 | 245 | |
| 246 | -/// The number of SQL compilations so far, for the internal test hooks: a | |
| 246 | +/// The number of SQL compilations so far, for a test assertion: a | |
| 247 | 247 | /// warm cell's gets and puts must not move it. |
| 248 | 248 | #[cfg(celld_internal_tests)] |
| 249 | 249 | pub fn sql_prepares_for_test() -> u64 { |
| @@ -540,20 +540,26 @@ | ||
| 540 | 540 | |
| 541 | 541 | fn valid_sql_boolean(value: &str) -> bool { |
| 542 | 542 | let value = value.trim(); |
| 543 | - let value = if value.len() >= 2 | |
| 544 | - && ((value.starts_with('\'') && value.ends_with('\'')) | |
| 545 | - || (value.starts_with('"') && value.ends_with('"'))) | |
| 546 | - { | |
| 547 | - &value[1..value.len() - 1] | |
| 548 | - } else { | |
| 549 | - value | |
| 550 | - }; | |
| 543 | + let value = value | |
| 544 | + .strip_prefix('\'') | |
| 545 | + .and_then(|value| value.strip_suffix('\'')) | |
| 546 | + .or_else(|| { | |
| 547 | + value | |
| 548 | + .strip_prefix('"') | |
| 549 | + .and_then(|value| value.strip_suffix('"')) | |
| 550 | + }) | |
| 551 | + .unwrap_or(value); | |
| 551 | 552 | matches!( |
| 552 | 553 | value.to_ascii_lowercase().as_str(), |
| 553 | 554 | "true" | "false" | "yes" | "no" | "on" | "off" | "1" | "0" |
| 554 | 555 | ) |
| 555 | 556 | } |
| 556 | 557 | |
| 558 | +#[cfg(all(test, celld_internal_tests))] | |
| 559 | +mod internal_tests { | |
| 560 | + include!(env!("CELLD_INTERNAL_STORAGE_TESTS")); | |
| 561 | +} | |
| 562 | + | |
| 557 | 563 | fn valid_sql_i32(value: &str) -> bool { |
| 558 | 564 | value.parse::<i32>().is_ok() |
| 559 | 565 | || value |
modifiedcrates/celld/telemetry.rs+1−1View file
| @@ -491,7 +491,7 @@ | ||
| 491 | 491 | (trace_id, sampled) |
| 492 | 492 | } |
| 493 | 493 | |
| 494 | -/// The sampler is private, so the private suite reaches the decision | |
| 494 | +/// The sampler is private, so tests reach the decision | |
| 495 | 495 | /// through the ratio the configuration carries. |
| 496 | 496 | #[cfg(celld_internal_tests)] |
| 497 | 497 | #[doc(hidden)] |
modifiedcrates/celld/wake.rs+36−22View file
| @@ -282,38 +282,52 @@ | ||
| 282 | 282 | } |
| 283 | 283 | } |
| 284 | 284 | |
| 285 | +#[derive(serde::Deserialize)] | |
| 286 | +struct WakerRoleLease { | |
| 287 | + node: String, | |
| 288 | + expires_ms: i64, | |
| 289 | +} | |
| 290 | + | |
| 291 | +async fn same_node_still_holds_waker(bucket: &Bucket, node: &str) -> bool { | |
| 292 | + let Ok(Some((bytes, _))) = bucket.get("wake/waker.json").await else { | |
| 293 | + return false; | |
| 294 | + }; | |
| 295 | + let Ok(lease) = serde_json::from_slice::<WakerRoleLease>(&bytes) else { | |
| 296 | + return false; | |
| 297 | + }; | |
| 298 | + lease.node == node && lease.expires_ms > crate::asyncrt::wall_ms() | |
| 299 | +} | |
| 300 | + | |
| 285 | 301 | /// Advisory waker-role lease: one holder per fleet to avoid N nodes polling. |
| 286 | 302 | /// Correctness never depends on it — concurrent wakers race activation CAS |
| 287 | -/// harmlessly — so every failure path just returns false and skips a tick. | |
| 303 | +/// harmlessly — so a caller skips the tick when another node holds the role. | |
| 288 | 304 | pub async fn try_hold_waker(bucket: &Bucket, node: &str, now_ms: i64, ttl_ms: i64) -> bool { |
| 289 | 305 | const KEY: &str = "wake/waker.json"; |
| 290 | 306 | let body = |
| 291 | 307 | |expires: i64| format!("{{\"node\":{node:?},\"expires_ms\":{expires}}}").into_bytes(); |
| 292 | - match bucket.get(KEY).await { | |
| 308 | + let token = match bucket.get(KEY).await { | |
| 293 | 309 | // absent (or unreadable): claim if absent |
| 294 | - Ok(None) | Err(_) => matches!( | |
| 295 | - bucket.put_cas(KEY, body(now_ms + ttl_ms), None).await, | |
| 296 | - Ok(Some(_)) | |
| 297 | - ), | |
| 310 | + Ok(None) | Err(_) => None, | |
| 298 | 311 | Ok(Some((bytes, etag))) => { |
| 299 | - let text = String::from_utf8_lossy(&bytes); | |
| 300 | - let held_by_us = text.contains(&format!("\"node\":{node:?}")); | |
| 301 | - let expires = text | |
| 302 | - .rsplit("\"expires_ms\":") | |
| 303 | - .next() | |
| 304 | - .and_then(|t| t.trim_end_matches('}').trim().parse::<i64>().ok()) | |
| 305 | - .unwrap_or(0); | |
| 306 | - if celld_logic::wake::waker_may_claim(held_by_us, expires, now_ms) { | |
| 307 | - matches!( | |
| 308 | - bucket | |
| 309 | - .put_cas(KEY, body(now_ms + ttl_ms), Some(&etag)) | |
| 310 | - .await, | |
| 311 | - Ok(Some(_)) | |
| 312 | - ) | |
| 313 | - } else { | |
| 314 | - false | |
| 312 | + let lease = serde_json::from_slice::<WakerRoleLease>(&bytes).ok(); | |
| 313 | + let held_by_us = lease.as_ref().is_some_and(|lease| lease.node == node); | |
| 314 | + let expires = lease.map_or(0, |lease| lease.expires_ms); | |
| 315 | + if !celld_logic::wake::waker_may_claim(held_by_us, expires, now_ms) { | |
| 316 | + return false; | |
| 315 | 317 | } |
| 318 | + Some(etag) | |
| 316 | 319 | } |
| 320 | + }; | |
| 321 | + match bucket | |
| 322 | + .put_cas(KEY, body(now_ms + ttl_ms), token.as_deref()) | |
| 323 | + .await | |
| 324 | + { | |
| 325 | + Ok(Some(_)) => true, | |
| 326 | + // The cleanup loop and the due-scan loop renew the same node's role. | |
| 327 | + // A clean CAS conflict can be their overlap, so check the winner | |
| 328 | + // before cancelling a GC pass and repeating its fleet-wide LIST. | |
| 329 | + Ok(None) => same_node_still_holds_waker(bucket, node).await, | |
| 330 | + Err(_) => false, | |
| 317 | 331 | } |
| 318 | 332 | } |
| 319 | 333 |
modifiedcrates/logic/lib.rs+250−65View file
| @@ -708,6 +708,10 @@ | ||
| 708 | 708 | /// permits: the bound belongs in the replayable state machine rather than |
| 709 | 709 | /// being implied by how many executor tasks happen to exist. |
| 710 | 710 | eviction_permits: BTreeSet<CellId>, |
| 711 | + /// Bind explicit callers to their operation in the same place that moves | |
| 712 | + /// a proof to its stop. The executor must not reconstruct that binding | |
| 713 | + /// from unrelated effects in the same batch. Policy evictions have none. | |
| 714 | + eviction_notifications: BTreeMap<OpId, BTreeSet<RequestId>>, | |
| 711 | 715 | /// Cells waiting for a residency slot, in arrival order. FIFO is the |
| 712 | 716 | /// whole admission policy: waking every waiter on a release and letting |
| 713 | 717 | /// them race is unfair by construction — under sustained eviction a |
| @@ -858,6 +862,7 @@ | ||
| 858 | 862 | activation_waiters: VecDeque::new(), |
| 859 | 863 | activation_permits: BTreeSet::new(), |
| 860 | 864 | eviction_permits: BTreeSet::new(), |
| 865 | + eviction_notifications: BTreeMap::new(), | |
| 861 | 866 | capacity_waiters: VecDeque::new(), |
| 862 | 867 | capacity_requests: BTreeSet::new(), |
| 863 | 868 | handoff_requests: BTreeSet::new(), |
| @@ -1060,7 +1065,7 @@ | ||
| 1060 | 1065 | self.quiescing_cells.len() |
| 1061 | 1066 | } |
| 1062 | 1067 | |
| 1063 | - /// Return the release pump's exact cell-table work for a private bounded | |
| 1068 | + /// Return the release pump's exact cell-table work for a bounded | |
| 1064 | 1069 | /// work assertion. This is not elapsed time, so the result is stable on |
| 1065 | 1070 | /// every host and under every scheduler. |
| 1066 | 1071 | #[cfg(celld_internal_tests)] |
| @@ -1187,7 +1192,7 @@ | ||
| 1187 | 1192 | /// `occupied` cannot say: it counts residency, so a node holding thousands |
| 1188 | 1193 | /// of cells part-way through a cold start reports almost none. A fleet held |
| 1189 | 1194 | /// that state for fifteen minutes and the record could not say what the |
| 1190 | - /// cells were doing (issue #50). | |
| 1195 | + /// cells were doing. | |
| 1191 | 1196 | /// |
| 1192 | 1197 | /// The names are part of the operator interface. A chart and a human read |
| 1193 | 1198 | /// them, so they do not change with an internal rename. |
| @@ -1289,6 +1294,18 @@ | ||
| 1289 | 1294 | )); |
| 1290 | 1295 | } |
| 1291 | 1296 | let eviction_ceiling = self.eviction_ceiling(); |
| 1297 | + for op in self.eviction_notifications.keys() { | |
| 1298 | + let waiting = self.cell_ops.get(op).and_then(|id| self.cells.get(id)); | |
| 1299 | + if !waiting.is_some_and(|cell| { | |
| 1300 | + matches!(cell.phase, | |
| 1301 | + Phase::EnsuringDurability { op: current, .. } | |
| 1302 | + | Phase::Cleaning { op: current, cause: StopCause::Evict { .. }, .. } | |
| 1303 | + if current == *op | |
| 1304 | + ) | |
| 1305 | + }) { | |
| 1306 | + return Err(format!("eviction notification {op} has no live operation")); | |
| 1307 | + } | |
| 1308 | + } | |
| 1292 | 1309 | if self.eviction_permits.len() > eviction_ceiling { |
| 1293 | 1310 | return Err(format!( |
| 1294 | 1311 | "evicting {} exceeds ceiling {}", |
| @@ -1553,8 +1570,11 @@ | ||
| 1553 | 1570 | let Some(cell) = self.cells.get(id) else { |
| 1554 | 1571 | return Err(format!("cell op {op} points to missing cell {id:?}")); |
| 1555 | 1572 | }; |
| 1556 | - if cell.phase == Phase::Fenced && cell.releasing != Some(*op) { | |
| 1557 | - return Err(format!("fenced cell {id:?} retains stale operation {op}")); | |
| 1573 | + if phase_op(&cell.phase) != Some(*op) | |
| 1574 | + && cell.releasing != Some(*op) | |
| 1575 | + && !matches!(cell.alarm, Some(AlarmState::Firing { op: current, .. }) if current == *op) | |
| 1576 | + { | |
| 1577 | + return Err(format!("indexed cell op {op} has no owning slot in {id:?}")); | |
| 1558 | 1578 | } |
| 1559 | 1579 | } |
| 1560 | 1580 | for op in &self.timed_out_runtime_starts { |
| @@ -1834,9 +1854,17 @@ | ||
| 1834 | 1854 | /// Return a voluntary eviction to service as one transition. Every |
| 1835 | 1855 | /// rescue returns the permit with the phase, or the cell looks resident |
| 1836 | 1856 | /// while a permit stays spent. |
| 1837 | - fn cancel_eviction(&mut self, id: &str, cell: &mut Cell, epoch: Epoch) { | |
| 1857 | + fn cancel_eviction( | |
| 1858 | + &mut self, | |
| 1859 | + id: &str, | |
| 1860 | + cell: &mut Cell, | |
| 1861 | + epoch: Epoch, | |
| 1862 | + reason: EvictCancellation, | |
| 1863 | + effects: &mut Vec<Effect>, | |
| 1864 | + ) { | |
| 1838 | 1865 | if let Some(op) = phase_op(&cell.phase) { |
| 1839 | 1866 | self.cell_ops.remove(&op); |
| 1867 | + self.finish_eviction(op, Err(EvictError::Cancelled(reason)), effects); | |
| 1840 | 1868 | } |
| 1841 | 1869 | set_phase(&mut self.occupied, cell, Phase::Resident { epoch }); |
| 1842 | 1870 | self.eviction_permits.remove(id); |
| @@ -1847,9 +1875,8 @@ | ||
| 1847 | 1875 | .cells |
| 1848 | 1876 | .iter() |
| 1849 | 1877 | .filter_map(|(id, cell)| { |
| 1850 | - let (epoch, retired_durability) = match cell.phase { | |
| 1851 | - Phase::Resident { epoch } => (epoch, None), | |
| 1852 | - Phase::EnsuringDurability { op, epoch } => (epoch, Some(op)), | |
| 1878 | + let epoch = match cell.phase { | |
| 1879 | + Phase::Resident { epoch } | Phase::EnsuringDurability { epoch, .. } => epoch, | |
| 1853 | 1880 | _ => return None, |
| 1854 | 1881 | }; |
| 1855 | 1882 | if cell.quiescing |
| @@ -1858,34 +1885,37 @@ | ||
| 1858 | 1885 | { |
| 1859 | 1886 | return None; |
| 1860 | 1887 | } |
| 1861 | - Some((id.clone(), epoch, retired_durability)) | |
| 1888 | + Some((id.clone(), epoch)) | |
| 1862 | 1889 | }) |
| 1863 | - .find(|(id, _, _)| self.worker_cursor.as_ref().is_none_or(|cursor| id > cursor)) | |
| 1890 | + .find(|(id, _)| self.worker_cursor.as_ref().is_none_or(|cursor| id > cursor)) | |
| 1864 | 1891 | .or_else(|| { |
| 1865 | 1892 | self.cells.iter().find_map(|(id, cell)| { |
| 1866 | - let (epoch, retired_durability) = match cell.phase { | |
| 1867 | - Phase::Resident { epoch } => (epoch, None), | |
| 1868 | - Phase::EnsuringDurability { op, epoch } => (epoch, Some(op)), | |
| 1893 | + let epoch = match cell.phase { | |
| 1894 | + Phase::Resident { epoch } | Phase::EnsuringDurability { epoch, .. } => { | |
| 1895 | + epoch | |
| 1896 | + } | |
| 1869 | 1897 | _ => return None, |
| 1870 | 1898 | }; |
| 1871 | 1899 | (!cell.quiescing |
| 1872 | 1900 | && !self.is_active(id) |
| 1873 | 1901 | && !matches!(cell.alarm, Some(AlarmState::Firing { .. }))) |
| 1874 | - .then(|| (id.clone(), epoch, retired_durability)) | |
| 1902 | + .then(|| (id.clone(), epoch)) | |
| 1875 | 1903 | }) |
| 1876 | 1904 | }) |
| 1877 | - .map(|(cell, epoch, retired_durability)| WorkerRoute { | |
| 1878 | - cell, | |
| 1879 | - epoch, | |
| 1880 | - retired_durability, | |
| 1881 | - }); | |
| 1905 | + .map(|(cell, epoch)| WorkerRoute { cell, epoch }); | |
| 1882 | 1906 | |
| 1883 | 1907 | if let Some(route) = &route { |
| 1884 | 1908 | self.worker_cursor = Some(route.cell.clone()); |
| 1885 | 1909 | self.activate_request(request, route.cell.clone()); |
| 1886 | 1910 | if let Some(mut cell) = self.cells.remove(&route.cell) { |
| 1887 | 1911 | if matches!(cell.phase, Phase::EnsuringDurability { .. }) { |
| 1888 | - self.cancel_eviction(&route.cell, &mut cell, route.epoch); | |
| 1912 | + self.cancel_eviction( | |
| 1913 | + &route.cell, | |
| 1914 | + &mut cell, | |
| 1915 | + route.epoch, | |
| 1916 | + EvictCancellation::Activity, | |
| 1917 | + effects, | |
| 1918 | + ); | |
| 1889 | 1919 | } |
| 1890 | 1920 | Self::record_local_request(&mut cell, request, self.now_mono_ms); |
| 1891 | 1921 | self.cells.insert(route.cell.clone(), cell); |
| @@ -2737,11 +2767,10 @@ | ||
| 2737 | 2767 | // a firing alarm holds the cell out of dormancy. All three |
| 2738 | 2768 | // keep the ownership record claimed while they wait. |
| 2739 | 2769 | // |
| 2740 | - // `StopRuntime` is the deliberate exception. It has no failure | |
| 2741 | - // handling to reuse -- a stop cannot fail, it can only not | |
| 2742 | - // finish -- so abandoning one would mean declaring a runtime | |
| 2743 | - // gone while it may still be running. That needs a decision, | |
| 2744 | - // not a timer. | |
| 2770 | + // `StopRuntime` is the deliberate exception. A returned host | |
| 2771 | + // error can take the failed-stop path, but a pending release | |
| 2772 | + // can still own the runtime and its database. Expiring that | |
| 2773 | + // operation would permit an unsafe concurrent restart. | |
| 2745 | 2774 | // A restore is a sequence of individually bounded object-store |
| 2746 | 2775 | // requests. Its total duration scales with the replica. The |
| 2747 | 2776 | // shell cannot cancel the task, so retiring the core op would |
| @@ -2890,7 +2919,7 @@ | ||
| 2890 | 2919 | // An unprovable snapshot leaves the cell resident. Evicting on a |
| 2891 | 2920 | // proof that never arrived is the one outcome that loses data. |
| 2892 | 2921 | Some(Phase::EnsuringDurability { .. }) => { |
| 2893 | - self.durability_checked(op, Err(Failure::Ambiguous), effects) | |
| 2922 | + self.durability_checked(op, Err(EvictFailure::DurabilityTimeout), effects) | |
| 2894 | 2923 | } |
| 2895 | 2924 | _ => {} |
| 2896 | 2925 | } |
| @@ -3103,7 +3132,7 @@ | ||
| 3103 | 3132 | // here re-emits EnsureDurable forever while the cell has no pin. |
| 3104 | 3133 | let safe_drain_refresh = self.draining && (at_ms.is_none() || covered); |
| 3105 | 3134 | if !safe_drain_refresh { |
| 3106 | - self.cancel_eviction(id, &mut cell, epoch); | |
| 3135 | + self.cancel_eviction(id, &mut cell, epoch, EvictCancellation::Alarm, effects); | |
| 3107 | 3136 | } |
| 3108 | 3137 | } |
| 3109 | 3138 | // Runtime observations can arrive before `AlarmFinished`. The alarm |
| @@ -3249,7 +3278,7 @@ | ||
| 3249 | 3278 | } |
| 3250 | 3279 | Phase::Resident { epoch } => epoch, |
| 3251 | 3280 | Phase::EnsuringDurability { epoch, .. } => { |
| 3252 | - self.cancel_eviction(id, &mut cell, epoch); | |
| 3281 | + self.cancel_eviction(id, &mut cell, epoch, EvictCancellation::Alarm, effects); | |
| 3253 | 3282 | epoch |
| 3254 | 3283 | } |
| 3255 | 3284 | Phase::Fenced => { |
| @@ -3526,7 +3555,7 @@ | ||
| 3526 | 3555 | // counts against `max_evictions` forever and eventually |
| 3527 | 3556 | // stands every future eviction down. |
| 3528 | 3557 | let epoch = *epoch; |
| 3529 | - self.cancel_eviction(&id, &mut cell, epoch); | |
| 3558 | + self.cancel_eviction(&id, &mut cell, epoch, EvictCancellation::Activity, effects); | |
| 3530 | 3559 | Self::record_local_request(&mut cell, request, self.now_mono_ms); |
| 3531 | 3560 | self.complete_request(&id, request, Ok(Route::Local), effects); |
| 3532 | 3561 | } |
| @@ -3764,6 +3793,10 @@ | ||
| 3764 | 3793 | Phase::ReadingOwner { .. } |
| 3765 | 3794 | | Phase::ReadingNodeLease { .. } |
| 3766 | 3795 | | Phase::RecoveringOwnerLog { .. } |
| 3796 | + // Backoff retains its callers after returning the activation | |
| 3797 | + // permit. Retire its phase too, or the retry timer restarts | |
| 3798 | + // cold work while the shell prepares the local reload. | |
| 3799 | + | Phase::WaitingOwnerLogRecovery { .. } | |
| 3767 | 3800 | | Phase::ReadingCapacity { .. } |
| 3768 | 3801 | | Phase::Acquiring { .. } |
| 3769 | 3802 | | Phase::ReconcilingAcquire { .. } => Some(Phase::Inactive), |
| @@ -3780,6 +3813,9 @@ | ||
| 3780 | 3813 | } |
| 3781 | 3814 | self.finish_requests(&id, &mut cell, Err(RequestError::NodeFenced), effects); |
| 3782 | 3815 | set_phase(&mut self.occupied, &mut cell, fallback); |
| 3816 | + // A later cold route must not inherit failures from the | |
| 3817 | + // recovery episode that preserve just retired. | |
| 3818 | + cell.owner_log_recovery_attempts = 0; | |
| 3783 | 3819 | cell.waiting_for = None; |
| 3784 | 3820 | cell.waiting_activation = None; |
| 3785 | 3821 | cell.alarm_wake = false; |
| @@ -4968,6 +5004,12 @@ | ||
| 4968 | 5004 | let Phase::Cleaning { epoch, cause, .. } = cell.phase else { |
| 4969 | 5005 | unreachable!() |
| 4970 | 5006 | }; |
| 5007 | + if matches!(cause, StopCause::Evict { .. }) { | |
| 5008 | + // The stop completed even when waiting demand immediately starts | |
| 5009 | + // a new runtime. Its callers await this operation, not absence | |
| 5010 | + // after the next activation. | |
| 5011 | + self.finish_eviction(op, Ok(EvictSuccess::Evicted), effects); | |
| 5012 | + } | |
| 4971 | 5013 | match cause { |
| 4972 | 5014 | StopCause::Cleanup => { |
| 4973 | 5015 | set_phase(&mut self.occupied, &mut cell, Phase::Dormant { epoch }); |
| @@ -5048,6 +5090,15 @@ | ||
| 5048 | 5090 | self.cells.insert(id, cell); |
| 5049 | 5091 | self.pump_capacity(effects); |
| 5050 | 5092 | self.shed_toward_floor(effects); |
| 5093 | + // The permit this stop returned is spent here, not on the next load | |
| 5094 | + // sample. Without this re-entry the idle path drains at | |
| 5095 | + // `max_evictions` cells per sampling period, whatever the proof and | |
| 5096 | + // stop take: 10,000 idle rooms hibernated at exactly four per second | |
| 5097 | + // for 42 minutes (GCE, 2026-09-03), and raising the bound only | |
| 5098 | + // raised the rate. The clock is the last one an event carried, which | |
| 5099 | + // is at or before the real time, so a cell idle at the sample is | |
| 5100 | + // still idle here. | |
| 5101 | + self.evict_idle(self.now_mono_ms, effects); | |
| 5051 | 5102 | } |
| 5052 | 5103 | |
| 5053 | 5104 | /// A bounded stop gave up. The host dropped the runtime and kept the |
| @@ -5058,7 +5109,7 @@ | ||
| 5058 | 5109 | /// the cell again instead of stopping it on every sample. Without this a |
| 5059 | 5110 | /// cell whose final proof stalled retried every 10 s without end and |
| 5060 | 5111 | /// answered nobody (the 2026-09-03 whale runs). |
| 5061 | - fn runtime_stop_failed(&mut self, op: OpId, effects: &mut Vec<Effect>) { | |
| 5112 | + fn runtime_stop_failed(&mut self, op: OpId, error: EvictError, effects: &mut Vec<Effect>) { | |
| 5062 | 5113 | let Some(id) = self.take_cell_op( |
| 5063 | 5114 | op, |
| 5064 | 5115 | |cell| matches!(cell.phase, Phase::Cleaning { op: current, .. } if current == op), |
| @@ -5073,6 +5124,8 @@ | ||
| 5073 | 5124 | matches!(cause, StopCause::Evict { .. }), |
| 5074 | 5125 | "only an eviction stop is bounded" |
| 5075 | 5126 | ); |
| 5127 | + self.finish_eviction(op, Err(error), effects); | |
| 5128 | + | |
| 5076 | 5129 | cell.isolate = None; |
| 5077 | 5130 | cell.evict_rebalance = false; |
| 5078 | 5131 | cell.handoff = false; |
| @@ -5281,7 +5334,7 @@ | ||
| 5281 | 5334 | fn durability_checked( |
| 5282 | 5335 | &mut self, |
| 5283 | 5336 | op: OpId, |
| 5284 | - result: Result<(), Failure>, | |
| 5337 | + result: Result<(), EvictFailure>, | |
| 5285 | 5338 | effects: &mut Vec<Effect>, |
| 5286 | 5339 | ) { |
| 5287 | 5340 | let now = self.now_mono_ms; |
| @@ -5300,6 +5353,9 @@ | ||
| 5300 | 5353 | // accesses split where a method call cannot. |
| 5301 | 5354 | let stop = self.next_op; |
| 5302 | 5355 | self.next_op = self.next_op.checked_add(1).expect("operation id exhausted"); |
| 5356 | + if let Some(requests) = self.eviction_notifications.remove(&op) { | |
| 5357 | + self.eviction_notifications.insert(stop, requests); | |
| 5358 | + } | |
| 5303 | 5359 | self.cell_ops.insert(stop, id.clone()); |
| 5304 | 5360 | let rebalance = cell.evict_rebalance; |
| 5305 | 5361 | set_phase( |
| @@ -5319,10 +5375,11 @@ | ||
| 5319 | 5375 | bounded: !self.draining, |
| 5320 | 5376 | }); |
| 5321 | 5377 | } |
| 5322 | - Err(_) => { | |
| 5378 | + Err(reason) => { | |
| 5323 | 5379 | set_phase(&mut self.occupied, cell, Phase::Resident { epoch }); |
| 5324 | 5380 | cell.eviction_refused_mono_ms = Some(now); |
| 5325 | 5381 | self.eviction_permits.remove(&id); |
| 5382 | + self.finish_eviction(op, Err(EvictError::Failed(reason)), effects); | |
| 5326 | 5383 | } |
| 5327 | 5384 | } |
| 5328 | 5385 | } |
| @@ -5330,9 +5387,96 @@ | ||
| 5330 | 5387 | /// Evict on demand. Local, like an idle eviction: the caller asked |
| 5331 | 5388 | /// this node to drop the cell, not to give it away. |
| 5332 | 5389 | fn evict(&mut self, id: &str, effects: &mut Vec<Effect>) { |
| 5333 | - self.begin_eviction(id, false, effects); | |
| 5390 | + let _ = self.begin_eviction(id, false, effects); | |
| 5334 | 5391 | } |
| 5335 | 5392 | |
| 5393 | + fn evict_requested(&mut self, request: RequestId, id: CellId, effects: &mut Vec<Effect>) { | |
| 5394 | + let mut admitted_effects = Vec::new(); | |
| 5395 | + let result = self | |
| 5396 | + .admit_eviction(&id, &mut admitted_effects) | |
| 5397 | + .map(|op| match op { | |
| 5398 | + Some(op) => { | |
| 5399 | + self.eviction_notifications | |
| 5400 | + .entry(op) | |
| 5401 | + .or_default() | |
| 5402 | + .insert(request); | |
| 5403 | + EvictionAdmission::Pending | |
| 5404 | + } | |
| 5405 | + None => EvictionAdmission::Absent, | |
| 5406 | + }); | |
| 5407 | + effects.push(Effect::EvictionAdmission { request, result }); | |
| 5408 | + effects.extend(admitted_effects); | |
| 5409 | + } | |
| 5410 | + | |
| 5411 | + fn finish_eviction( | |
| 5412 | + &mut self, | |
| 5413 | + op: OpId, | |
| 5414 | + result: Result<EvictSuccess, EvictError>, | |
| 5415 | + effects: &mut Vec<Effect>, | |
| 5416 | + ) { | |
| 5417 | + if let Some(requests) = self.eviction_notifications.remove(&op) { | |
| 5418 | + effects.extend( | |
| 5419 | + requests | |
| 5420 | + .into_iter() | |
| 5421 | + .map(|request| Effect::EvictionFinished { request, result }), | |
| 5422 | + ); | |
| 5423 | + } | |
| 5424 | + } | |
| 5425 | + | |
| 5426 | + fn admit_eviction( | |
| 5427 | + &mut self, | |
| 5428 | + id: &str, | |
| 5429 | + effects: &mut Vec<Effect>, | |
| 5430 | + ) -> Result<Option<OpId>, EvictError> { | |
| 5431 | + let refuse = |reason| Err(EvictError::Refused(reason)); | |
| 5432 | + if !self.ready_to_serve() || self.confirming { | |
| 5433 | + return refuse(EvictRefusal::NodeUnavailable); | |
| 5434 | + } | |
| 5435 | + if self.is_active(id) { | |
| 5436 | + return refuse(EvictRefusal::CellActive); | |
| 5437 | + } | |
| 5438 | + let cell = self.cells.get(id); | |
| 5439 | + let phase = cell.map(|cell| &cell.phase); | |
| 5440 | + match phase { | |
| 5441 | + Some(Phase::EnsuringDurability { op, .. }) => return Ok(Some(*op)), | |
| 5442 | + Some(Phase::Cleaning { | |
| 5443 | + op, | |
| 5444 | + cause: StopCause::Evict { .. }, | |
| 5445 | + .. | |
| 5446 | + }) => return Ok(Some(*op)), | |
| 5447 | + _ => {} | |
| 5448 | + } | |
| 5449 | + // A dormant phase can still owe an ownership release. The operation | |
| 5450 | + // index is validated against these slots, so no global scan is needed. | |
| 5451 | + let transitioning = cell.is_some_and(|cell| { | |
| 5452 | + cell.releasing.is_some() | |
| 5453 | + || cell.waiting_for.is_some() | |
| 5454 | + || cell.waiting_activation.is_some() | |
| 5455 | + || !cell.requests.is_empty() | |
| 5456 | + || cell.quiescing | |
| 5457 | + || cell.swapping | |
| 5458 | + || cell.handoff | |
| 5459 | + || cell.confirming | |
| 5460 | + || cell.resume_demand | |
| 5461 | + }); | |
| 5462 | + if transitioning { | |
| 5463 | + return refuse(EvictRefusal::CellTransitioning); | |
| 5464 | + } | |
| 5465 | + match phase { | |
| 5466 | + None | Some(Phase::Inactive | Phase::Dormant { .. } | Phase::Remote { .. }) => { | |
| 5467 | + // A wake hint can outlive a remote lookup or an eviction with | |
| 5468 | + // a future alarm. Refusing on the hint alone would reject | |
| 5469 | + // settled absence; only pending lifecycle work prevents it. | |
| 5470 | + Ok(None) | |
| 5471 | + } | |
| 5472 | + Some(Phase::Resident { .. }) => self | |
| 5473 | + .begin_eviction(id, false, effects) | |
| 5474 | + .map(Some) | |
| 5475 | + .map_err(EvictError::Refused), | |
| 5476 | + _ => refuse(EvictRefusal::CellTransitioning), | |
| 5477 | + } | |
| 5478 | + } | |
| 5479 | + | |
| 5336 | 5480 | /// Shutdown handoff: give every resident cell away by releasing its |
| 5337 | 5481 | /// owner record, so peers take over at once instead of waiting out the |
| 5338 | 5482 | /// node lease. `rebalance` is forced true, so this releases even when |
| @@ -5395,7 +5539,7 @@ | ||
| 5395 | 5539 | // ordinary eviction state without spending another handoff permit. |
| 5396 | 5540 | let quiescing: Vec<CellId> = self.quiescing_cells.iter().cloned().collect(); |
| 5397 | 5541 | for id in quiescing { |
| 5398 | - self.begin_eviction(&id, true, effects); | |
| 5542 | + let _ = self.begin_eviction(&id, true, effects); | |
| 5399 | 5543 | } |
| 5400 | 5544 | |
| 5401 | 5545 | // A full batch cannot nominate another cell. Stop before rebuilding |
| @@ -5503,7 +5647,7 @@ | ||
| 5503 | 5647 | keep_hibernatable: false, |
| 5504 | 5648 | }); |
| 5505 | 5649 | in_flight += 1; |
| 5506 | - self.begin_eviction(&id, true, effects); | |
| 5650 | + let _ = self.begin_eviction(&id, true, effects); | |
| 5507 | 5651 | } |
| 5508 | 5652 | // A cell evicted before the drain kept its record on this node -- |
| 5509 | 5653 | // a sticky eviction, hibernation, or a release whose write failed |
| @@ -5631,42 +5775,45 @@ | ||
| 5631 | 5775 | } |
| 5632 | 5776 | } |
| 5633 | 5777 | |
| 5634 | - fn begin_eviction(&mut self, id: &str, rebalance: bool, effects: &mut Vec<Effect>) -> bool { | |
| 5635 | - let alarm_is_imminent = self | |
| 5636 | - .cells | |
| 5637 | - .get(id) | |
| 5638 | - .is_some_and(|cell| self.alarm_is_imminent(cell)); | |
| 5778 | + fn begin_eviction( | |
| 5779 | + &mut self, | |
| 5780 | + id: &str, | |
| 5781 | + rebalance: bool, | |
| 5782 | + effects: &mut Vec<Effect>, | |
| 5783 | + ) -> Result<OpId, EvictRefusal> { | |
| 5784 | + let Some(cell) = self.cells.get(id) else { | |
| 5785 | + return Err(EvictRefusal::CellTransitioning); | |
| 5786 | + }; | |
| 5639 | 5787 | // Only while there is room to spare. Holding a cell to save a wake is |
| 5640 | 5788 | // worth it on an idle node and indefensible on a full one: the window |
| 5641 | 5789 | // defaults to an hour, so on an alarm-driven workload this would hold |
| 5642 | 5790 | // most of the node and pin it at its ceiling -- trading a real |
| 5643 | 5791 | // admission failure for a saved activation. Under pressure the node |
| 5644 | 5792 | // takes the wake. |
| 5645 | - if alarm_is_imminent && !self.shedding && !self.draining { | |
| 5646 | - return false; | |
| 5793 | + if self.alarm_is_imminent(cell) && !self.shedding && !self.draining { | |
| 5794 | + return Err(EvictRefusal::AlarmImminent); | |
| 5647 | 5795 | } |
| 5648 | - let alarm_is_safe = self.cells.get(id).is_some_and(|cell| { | |
| 5649 | - cell.alarm | |
| 5650 | - .as_ref() | |
| 5651 | - .is_none_or(|alarm| matches!(alarm, AlarmState::Armed { covered: true, .. })) | |
| 5652 | - }); | |
| 5653 | - if !self.is_hibernatable(id) || !alarm_is_safe { | |
| 5654 | - return false; | |
| 5796 | + if self.is_active(id) { | |
| 5797 | + return Err(EvictRefusal::CellActive); | |
| 5655 | 5798 | } |
| 5799 | + let Phase::Resident { epoch } = cell.phase else { | |
| 5800 | + return Err(EvictRefusal::CellTransitioning); | |
| 5801 | + }; | |
| 5802 | + if !cell | |
| 5803 | + .alarm | |
| 5804 | + .as_ref() | |
| 5805 | + .is_none_or(|alarm| matches!(alarm, AlarmState::Armed { covered: true, .. })) | |
| 5806 | + { | |
| 5807 | + return Err(EvictRefusal::AlarmUncovered); | |
| 5808 | + } | |
| 5656 | 5809 | // The permit is taken here, so the ceiling holds here. A balancing |
| 5657 | 5810 | // batch reserves more cells than permits, and the pump promotes |
| 5658 | 5811 | // them as permits return. |
| 5659 | 5812 | if self.eviction_permits.len() >= self.eviction_ceiling() { |
| 5660 | - return false; | |
| 5813 | + return Err(EvictRefusal::ConcurrencyLimit); | |
| 5661 | 5814 | } |
| 5662 | - let Some(Phase::Resident { epoch }) = self.cells.get(id).map(|cell| &cell.phase) else { | |
| 5663 | - return false; | |
| 5664 | - }; | |
| 5665 | - let epoch = *epoch; | |
| 5666 | 5815 | let op = self.cell_op(id); |
| 5667 | - let Some(cell) = self.cells.get_mut(id) else { | |
| 5668 | - return false; | |
| 5669 | - }; | |
| 5816 | + let cell = self.cells.get_mut(id).expect("resident cell checked above"); | |
| 5670 | 5817 | cell.evict_rebalance = rebalance; |
| 5671 | 5818 | set_phase( |
| 5672 | 5819 | &mut self.occupied, |
| @@ -5688,7 +5835,7 @@ | ||
| 5688 | 5835 | // `Effect::EnsureDurable::revocable` records the argument. |
| 5689 | 5836 | revocable: !self.draining, |
| 5690 | 5837 | }); |
| 5691 | - true | |
| 5838 | + Ok(op) | |
| 5692 | 5839 | } |
| 5693 | 5840 | |
| 5694 | 5841 | fn shed_one(&mut self, effects: &mut Vec<Effect>) { |
| @@ -5711,7 +5858,7 @@ | ||
| 5711 | 5858 | return; |
| 5712 | 5859 | } |
| 5713 | 5860 | if let Some(victim) = self.shed_candidate() { |
| 5714 | - self.begin_eviction(&victim, self.rebalances(), effects); | |
| 5861 | + let _ = self.begin_eviction(&victim, self.rebalances(), effects); | |
| 5715 | 5862 | } |
| 5716 | 5863 | } |
| 5717 | 5864 | |
| @@ -5879,6 +6026,13 @@ | ||
| 5879 | 6026 | let Some(idle_ms) = self.config.idle_evict_ms else { |
| 5880 | 6027 | return; |
| 5881 | 6028 | }; |
| 6029 | + // A latched node is already walking down on its own schedule, and | |
| 6030 | + // `shed_toward_floor` prefers the same cold cells. This is reached | |
| 6031 | + // from every eviction stop as well as from the sample, so the guard | |
| 6032 | + // lives here rather than at each caller. | |
| 6033 | + if self.shedding { | |
| 6034 | + return; | |
| 6035 | + } | |
| 5882 | 6036 | // Fill the permits, exactly as `shed_toward_floor` does. One |
| 5883 | 6037 | // candidate per sample drains an idle backlog at the sampling |
| 5884 | 6038 | // period: a few thousand parked hibernatable cells — the shape |
| @@ -5898,7 +6052,7 @@ | ||
| 5898 | 6052 | return; |
| 5899 | 6053 | }; |
| 5900 | 6054 | // Idle eviction is a local residency decision, not a handoff. |
| 5901 | - if !self.begin_eviction(&candidate, false, effects) { | |
| 6055 | + if self.begin_eviction(&candidate, false, effects).is_err() { | |
| 5902 | 6056 | return; |
| 5903 | 6057 | } |
| 5904 | 6058 | } |
| @@ -6080,7 +6234,10 @@ | ||
| 6080 | 6234 | let Some(victim) = self.shed_candidate() else { |
| 6081 | 6235 | return; |
| 6082 | 6236 | }; |
| 6083 | - if !self.begin_eviction(&victim, self.rebalances(), effects) { | |
| 6237 | + if self | |
| 6238 | + .begin_eviction(&victim, self.rebalances(), effects) | |
| 6239 | + .is_err() | |
| 6240 | + { | |
| 6084 | 6241 | return; |
| 6085 | 6242 | } |
| 6086 | 6243 | } |
| @@ -6388,6 +6545,19 @@ | ||
| 6388 | 6545 | // never match a lookup again. The release op survives on purpose: |
| 6389 | 6546 | // `owner_released` still consumes it after a fence, as it did |
| 6390 | 6547 | // when resolution was a scan. |
| 6548 | + if let Phase::EnsuringDurability { op, .. } | |
| 6549 | + | Phase::Cleaning { | |
| 6550 | + op, | |
| 6551 | + cause: StopCause::Evict { .. }, | |
| 6552 | + .. | |
| 6553 | + } = cell.phase | |
| 6554 | + { | |
| 6555 | + self.finish_eviction( | |
| 6556 | + op, | |
| 6557 | + Err(EvictError::Cancelled(EvictCancellation::NodeFenced)), | |
| 6558 | + effects, | |
| 6559 | + ); | |
| 6560 | + } | |
| 6391 | 6561 | if let Some(stale) = phase_op(&cell.phase) { |
| 6392 | 6562 | self.cell_ops.remove(&stale); |
| 6393 | 6563 | } |
| @@ -6456,6 +6626,7 @@ | ||
| 6456 | 6626 | | Event::SelfNodeLeaseRead { now_mono_ms, .. } |
| 6457 | 6627 | | Event::NodeLeaseCasCompleted { now_mono_ms, .. } |
| 6458 | 6628 | | Event::RequestAt { now_mono_ms, .. } |
| 6629 | + | Event::EvictRequested { now_mono_ms, .. } | |
| 6459 | 6630 | | Event::CapacityRequestAt { now_mono_ms, .. } |
| 6460 | 6631 | | Event::HandoffRequestAt { now_mono_ms, .. } |
| 6461 | 6632 | | Event::WebSocketRequestAt { now_mono_ms, .. } |
| @@ -6641,12 +6812,26 @@ | ||
| 6641 | 6812 | .. |
| 6642 | 6813 | } => state.generation_changed(generation, max_age_ms, &eager_classes), |
| 6643 | 6814 | Event::Published { op, result } => state.published(op, result, &mut effects), |
| 6644 | - Event::DurabilityChecked { op, result } => { | |
| 6645 | - state.durability_checked(op, result, &mut effects) | |
| 6646 | - } | |
| 6815 | + Event::DurabilityChecked { op, result } => state.durability_checked( | |
| 6816 | + op, | |
| 6817 | + result.map_err(|_| EvictFailure::Durability), | |
| 6818 | + &mut effects, | |
| 6819 | + ), | |
| 6647 | 6820 | Event::RuntimeStopped { op } => state.runtime_stopped(op, &mut effects), |
| 6648 | - Event::RuntimeStopFailed { op } => state.runtime_stop_failed(op, &mut effects), | |
| 6821 | + Event::RuntimeStopFailed { op } => state.runtime_stop_failed( | |
| 6822 | + op, | |
| 6823 | + EvictError::Failed(EvictFailure::RuntimeStop), | |
| 6824 | + &mut effects, | |
| 6825 | + ), | |
| 6826 | + Event::RuntimeStopCancelled { op } => state.runtime_stop_failed( | |
| 6827 | + op, | |
| 6828 | + EvictError::Cancelled(EvictCancellation::Activity), | |
| 6829 | + &mut effects, | |
| 6830 | + ), | |
| 6649 | 6831 | Event::Evict { cell } => state.evict(&cell, &mut effects), |
| 6832 | + Event::EvictRequested { request, cell, .. } => { | |
| 6833 | + state.evict_requested(request, cell, &mut effects) | |
| 6834 | + } | |
| 6650 | 6835 | Event::LoadSampled { load, now_mono_ms } => { |
| 6651 | 6836 | state.load_sampled(load, now_mono_ms, &mut effects) |
| 6652 | 6837 | } |
modifiedcrates/logic/log_evict.rs+3−3View file
| @@ -38,9 +38,9 @@ | ||
| 38 | 38 | pub sustain_ms: u64, |
| 39 | 39 | /// The hard backstop: any single append outstanding this long evicts |
| 40 | 40 | /// immediately, sustain or none. The default covers the measured |
| 41 | - /// append tail, not a guess: the S5c kill-validation corpus's worst | |
| 42 | - /// uncensored append is 923 ms with the tail right-censored above the | |
| 43 | - /// old 400 ms deadline (issue #295), and the 2026-08-24 stream-fleet | |
| 41 | + /// append tail, not a guess: the worst uncensored measured append is | |
| 42 | + /// 923 ms with the tail right-censored above the | |
| 43 | + /// old 400 ms deadline, and the 2026-08-24 stream-fleet | |
| 44 | 44 | /// verification took the same fleet from two gray evictions of |
| 45 | 45 | /// healthy members and 14.5% bucket-proof acks at 400 ms to zero and |
| 46 | 46 | /// 0.94% at this value. A truly dead member still evicts well inside |
modifiedcrates/logic/pressure.rs+1−1View file
| @@ -212,7 +212,7 @@ | ||
| 212 | 212 | /// The latches are carried separately and not derived from the reported |
| 213 | 213 | /// reason. Sharing them lets one crossing hold the node against the other's |
| 214 | 214 | /// watermark, in either direction: a crossing of the ordinary ceiling then |
| 215 | - /// holds the node on a resident-set watermark, which is issue #36 again, | |
| 215 | + /// holds the node on a resident-set watermark it did not cross, | |
| 216 | 216 | /// and a hard-cap crossing then holds it on a ceiling it never crossed. |
| 217 | 217 | pub fn classify(self, s: Load, was: Latches) -> (Latches, Option<&'static str>) { |
| 218 | 218 | let over = |ceiling: Option<u64>, sample: u64, latched: bool| { |
modifiedcrates/logic/types.rs+125−13View file
| @@ -826,17 +826,30 @@ | ||
| 826 | 826 | RuntimeStopped { |
| 827 | 827 | op: OpId, |
| 828 | 828 | }, |
| 829 | - /// A bounded stop did not complete before its deadline. The runtime is | |
| 829 | + /// A stop returned an error after its retry deadline. The runtime is | |
| 830 | 830 | /// gone, the database stays open, and the cell restarts on it at the |
| 831 | - /// same epoch, as a generation swap does. | |
| 831 | + /// same epoch, as a generation swap does. A pending stop emits no result. | |
| 832 | 832 | RuntimeStopFailed { |
| 833 | 833 | op: OpId, |
| 834 | 834 | }, |
| 835 | - /// Policy input for this first slice. Later eviction selection emits this | |
| 836 | - /// from the same core rather than an external caller choosing a victim. | |
| 835 | + /// The host rescued the database for new activity instead of completing | |
| 836 | + /// the eviction. The runtime restarts through the failed-stop path. | |
| 837 | + RuntimeStopCancelled { | |
| 838 | + op: OpId, | |
| 839 | + }, | |
| 840 | + /// Attempt a policy eviction without a caller result. Deterministic | |
| 841 | + /// policy drivers use this input; the Actor uses `EvictRequested` so a | |
| 842 | + /// refusal or an interrupted operation cannot look like success. | |
| 837 | 843 | Evict { |
| 838 | 844 | cell: CellId, |
| 839 | 845 | }, |
| 846 | + /// Try an explicit eviction now and report admission before its effects | |
| 847 | + /// run, so the executor can bind the caller to the accepted operation. | |
| 848 | + EvictRequested { | |
| 849 | + request: RequestId, | |
| 850 | + cell: CellId, | |
| 851 | + now_mono_ms: u64, | |
| 852 | + }, | |
| 840 | 853 | /// A periodic resource sample from the edge. |
| 841 | 854 | /// |
| 842 | 855 | /// The core never reads a clock or a proc file; the shell measures and |
| @@ -886,10 +899,6 @@ | ||
| 886 | 899 | pub struct WorkerRoute { |
| 887 | 900 | pub cell: CellId, |
| 888 | 901 | pub epoch: Epoch, |
| 889 | - /// A pending durability proof made stale by selecting this still-routable | |
| 890 | - /// resident. The executor uses the ID only to release its effect waiter; | |
| 891 | - /// a late completion is ignored by the core's phase check. | |
| 892 | - pub retired_durability: Option<OpId>, | |
| 893 | 902 | } |
| 894 | 903 | |
| 895 | 904 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| @@ -908,10 +917,113 @@ | ||
| 908 | 917 | DurabilityUnproven, |
| 909 | 918 | } |
| 910 | 919 | |
| 920 | +/// A successful local eviction request. A later request can reactivate the cell. | |
| 921 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | |
| 922 | +pub enum EvictSuccess { | |
| 923 | + /// The awaited eviction completes its runtime stop, including for joined callers. | |
| 924 | + Evicted, | |
| 925 | + /// The Actor finds settled local absence without a pending lifecycle transition. | |
| 926 | + AlreadyAbsent, | |
| 927 | +} | |
| 928 | + | |
| 929 | +/// An eviction refused before an operation starts. | |
| 930 | +#[derive(Clone, Copy, Debug, PartialEq, Eq)] | |
| 931 | +pub enum EvictRefusal { | |
| 932 | + NodeUnavailable, | |
| 933 | + CellActive, | |
| 934 | + CellTransitioning, | |
| 935 | + AlarmImminent, | |
| 936 | + AlarmUncovered, | |
| 937 | + ConcurrencyLimit, | |
| 938 | +} | |
| 939 | + | |
| 940 | +/// An accepted eviction interrupted by a later lifecycle decision. | |
| 941 | +#[derive(Clone, Copy, Debug, PartialEq, Eq)] | |
| 942 | +pub enum EvictCancellation { | |
| 943 | + Activity, | |
| 944 | + Alarm, | |
| 945 | + NodeFenced, | |
| 946 | +} | |
| 947 | + | |
| 948 | +/// An eviction whose completion could not be established. | |
| 949 | +#[derive(Clone, Copy, Debug, PartialEq, Eq)] | |
| 950 | +pub enum EvictFailure { | |
| 951 | + Durability, | |
| 952 | + DurabilityTimeout, | |
| 953 | + RuntimeStop, | |
| 954 | + ActorUnavailable, | |
| 955 | + ReplyLost, | |
| 956 | +} | |
| 957 | + | |
| 958 | +/// Refusal and cancellation are expected outcomes, not node malfunctions. | |
| 959 | +#[derive(Clone, Copy, Debug, PartialEq, Eq)] | |
| 960 | +pub enum EvictError { | |
| 961 | + Refused(EvictRefusal), | |
| 962 | + Cancelled(EvictCancellation), | |
| 963 | + Failed(EvictFailure), | |
| 964 | +} | |
| 965 | + | |
| 966 | +impl EvictError { | |
| 967 | + /// Stable category shared by Rust diagnostics and HTTP responses. | |
| 968 | + pub const fn kind(&self) -> &'static str { | |
| 969 | + match self { | |
| 970 | + Self::Refused(_) => "refused", | |
| 971 | + Self::Cancelled(_) => "cancelled", | |
| 972 | + Self::Failed(_) => "failed", | |
| 973 | + } | |
| 974 | + } | |
| 975 | + | |
| 976 | + /// Stable reason code. Debug output cannot define the wire contract, | |
| 977 | + /// because a Rust variant rename must not change operator clients. | |
| 978 | + pub const fn reason(&self) -> &'static str { | |
| 979 | + match self { | |
| 980 | + Self::Refused(EvictRefusal::NodeUnavailable) => "node_unavailable", | |
| 981 | + Self::Refused(EvictRefusal::CellActive) => "cell_active", | |
| 982 | + Self::Refused(EvictRefusal::CellTransitioning) => "cell_transitioning", | |
| 983 | + Self::Refused(EvictRefusal::AlarmImminent) => "alarm_imminent", | |
| 984 | + Self::Refused(EvictRefusal::AlarmUncovered) => "alarm_uncovered", | |
| 985 | + Self::Refused(EvictRefusal::ConcurrencyLimit) => "eviction_limit", | |
| 986 | + Self::Cancelled(EvictCancellation::Activity) => "new_activity", | |
| 987 | + Self::Cancelled(EvictCancellation::Alarm) => "alarm_activity", | |
| 988 | + Self::Cancelled(EvictCancellation::NodeFenced) => "node_fenced", | |
| 989 | + Self::Failed(EvictFailure::Durability) => "durability_failed", | |
| 990 | + Self::Failed(EvictFailure::DurabilityTimeout) => "durability_timeout", | |
| 991 | + Self::Failed(EvictFailure::RuntimeStop) => "runtime_stop_failed", | |
| 992 | + Self::Failed(EvictFailure::ActorUnavailable) => "actor_unavailable", | |
| 993 | + Self::Failed(EvictFailure::ReplyLost) => "reply_lost", | |
| 994 | + } | |
| 995 | + } | |
| 996 | +} | |
| 997 | + | |
| 998 | +impl std::fmt::Display for EvictError { | |
| 999 | + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { | |
| 1000 | + write!(f, "{}: {}", self.kind(), self.reason()) | |
| 1001 | + } | |
| 1002 | +} | |
| 1003 | + | |
| 1004 | +impl std::error::Error for EvictError {} | |
| 1005 | + | |
| 1006 | +/// Admission of an explicit caller. The core keeps its operation binding. | |
| 1007 | +#[derive(Clone, Copy, Debug, PartialEq, Eq)] | |
| 1008 | +pub enum EvictionAdmission { | |
| 1009 | + Absent, | |
| 1010 | + Pending, | |
| 1011 | +} | |
| 1012 | + | |
| 911 | 1013 | /// Work performed outside the core. Every asynchronous effect is versioned; |
| 912 | 1014 | /// completion events with an obsolete `op` are ignored. |
| 913 | 1015 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 914 | 1016 | pub enum Effect { |
| 1017 | + EvictionAdmission { | |
| 1018 | + request: RequestId, | |
| 1019 | + result: Result<EvictionAdmission, EvictError>, | |
| 1020 | + }, | |
| 1021 | + /// Settle a caller bound to the completed operation. A later activation | |
| 1022 | + /// or eviction of the same cell cannot change this result. | |
| 1023 | + EvictionFinished { | |
| 1024 | + request: RequestId, | |
| 1025 | + result: Result<EvictSuccess, EvictError>, | |
| 1026 | + }, | |
| 915 | 1027 | ScheduleTimer { |
| 916 | 1028 | timer: Timer, |
| 917 | 1029 | at_mono_ms: u64, |
| @@ -1076,10 +1188,10 @@ | ||
| 1076 | 1188 | cell: CellId, |
| 1077 | 1189 | epoch: Epoch, |
| 1078 | 1190 | cause: StopCause, |
| 1079 | - /// The shell gives up after its operation deadline and reports | |
| 1080 | - /// `RuntimeStopFailed`. A drain and a fence retry until the process | |
| 1081 | - /// ends, because their node is leaving; an eviction on a serving | |
| 1082 | - /// node is not worth a cell that never answers again. | |
| 1191 | + /// After a returned error, the shell stops retrying at its deadline | |
| 1192 | + /// and reports `RuntimeStopFailed`. An in-flight release has no | |
| 1193 | + /// timeout. A drain and a fence keep retrying returned errors until | |
| 1194 | + /// the process ends, because their node is leaving. | |
| 1083 | 1195 | bounded: bool, |
| 1084 | 1196 | }, |
| 1085 | 1197 | /// Give the cell back instead of finishing this eviction stop. |
| @@ -1087,7 +1199,7 @@ | ||
| 1087 | 1199 | /// A request is waiting on a cell in `Phase::Cleaning`, and the stop that |
| 1088 | 1200 | /// holds it is a bounded eviction, so the node has somewhere to put the |
| 1089 | 1201 | /// cell back. The shell abandons the stop if it can still do so, and it |
| 1090 | - /// reports `RuntimeStopFailed`, which restarts the cell on its open | |
| 1202 | + /// reports `RuntimeStopCancelled`, which restarts the cell on its open | |
| 1091 | 1203 | /// database at the epoch it already had. |
| 1092 | 1204 | /// |
| 1093 | 1205 | /// The shell decides whether it is still able to. An eviction that has |
modifiedcrates/ltx/src/db.rs+32−1View file
| @@ -395,7 +395,7 @@ | ||
| 395 | 395 | } |
| 396 | 396 | |
| 397 | 397 | /// Opens both managed connections through a named SQLite VFS. Used by the |
| 398 | - /// fault-injection VFS of the test suite and by paged restore's fault-in VFS. | |
| 398 | + /// fault-injection VFS in tests and by paged restore's fault-in VFS. | |
| 399 | 399 | pub fn open_with_host_and_vfs( |
| 400 | 400 | path: impl AsRef<Path>, |
| 401 | 401 | host: crate::LtxHost, |
| @@ -418,6 +418,16 @@ | ||
| 418 | 418 | }; |
| 419 | 419 | let conn = open(&path).map_err(sql_err)?; |
| 420 | 420 | disable_lookaside(&conn)?; |
| 421 | + // Cap the page cache at 64 KiB; SQLite's default (-2000) lets each | |
| 422 | + // connection grow to 2 MiB, and every resident cell owns this | |
| 423 | + // connection, so the default repeats a dead-weight cost at fleet | |
| 424 | + // density. The connection only runs PRAGMAs, the sealing write to | |
| 425 | + // the control tables, and checkpoints, and a checkpoint streams WAL | |
| 426 | + // frames into the database without revisiting pages, so a larger | |
| 427 | + // cache buys no reuse. 16 default-size pages still cover the | |
| 428 | + // control tables and their schema pages. | |
| 429 | + conn.pragma_update(None, "cache_size", -64) | |
| 430 | + .map_err(sql_err)?; | |
| 421 | 431 | |
| 422 | 432 | // DSN pragmas: busy_timeout + wal_autocheckpoint(0) (db.go:818). |
| 423 | 433 | // autocheckpoint MUST be 0 because litestream owns checkpointing. |
| @@ -446,7 +456,15 @@ | ||
| 446 | 456 | // Dedicated read-lock connection (mirrors a second pooled connection). |
| 447 | 457 | let rtx_conn = open(&path).map_err(sql_err)?; |
| 448 | 458 | disable_lookaside(&rtx_conn)?; |
| 459 | + // This connection runs one tiny read to take the read lock and then | |
| 460 | + // idles for the whole residency, so SQLite's default page-cache limit | |
| 461 | + // (-2000 = up to 2 MiB) is dead weight repeated per resident cell. | |
| 462 | + // Cap it at a few pages; no user query or checkpoint runs here, so a | |
| 463 | + // smaller cache cannot slow either path. | |
| 449 | 464 | rtx_conn |
| 465 | + .pragma_update(None, "cache_size", -16) | |
| 466 | + .map_err(sql_err)?; | |
| 467 | + rtx_conn | |
| 450 | 468 | .busy_timeout(Self::DEFAULT_BUSY_TIMEOUT) |
| 451 | 469 | .map_err(sql_err)?; |
| 452 | 470 | |
| @@ -2395,6 +2413,19 @@ | ||
| 2395 | 2413 | .map_err(sql_err) |
| 2396 | 2414 | } |
| 2397 | 2415 | |
| 2416 | + /// The effective `PRAGMA cache_size` of the writer connection. | |
| 2417 | + pub fn writer_cache_size(db: &Db) -> Result<i64> { | |
| 2418 | + db.conn | |
| 2419 | + .query_row("PRAGMA cache_size", [], |row| row.get(0)) | |
| 2420 | + .map_err(sql_err) | |
| 2421 | + } | |
| 2422 | + | |
| 2423 | + pub fn read_lock_connection_cache_size(db: &Db) -> Result<i64> { | |
| 2424 | + db.rtx_conn | |
| 2425 | + .query_row("PRAGMA cache_size", [], |row| row.get(0)) | |
| 2426 | + .map_err(sql_err) | |
| 2427 | + } | |
| 2428 | + | |
| 2398 | 2429 | pub fn rollback_read_lock_connection(db: &Db) -> Result<()> { |
| 2399 | 2430 | db.rtx_conn.execute_batch("ROLLBACK").map_err(sql_err) |
| 2400 | 2431 | } |
modifieddocs/README.md+107−26View file
| @@ -1,4 +1,4 @@ | ||
| 1 | -# celld documentation | |
| 1 | +# celld | |
| 2 | 2 | |
| 3 | 3 | celld is a stateful distributed system. It runs server-side JavaScript on |
| 4 | 4 | your machines, and it stores the long-term state in a bucket that you own: |
| @@ -6,9 +6,11 @@ | ||
| 6 | 6 | API and the configuration follow Cloudflare Workers: Workers, Durable |
| 7 | 7 | Objects, KV, Queues, D1, R2, Workflows, Cron Triggers, and static assets. |
| 8 | 8 | |
| 9 | +## Cells and nodes | |
| 10 | + | |
| 9 | 11 | In Cloudflare terms, a cell is a Durable Object: a small server with a |
| 10 | -name and a private SQLite database. You make one cell for each user, each | |
| 11 | -document, each chat room, or each AI agent. A cell serves HTTP, holds | |
| 12 | +name and a private SQLite database. You make one cell for each user, | |
| 13 | +document, chat room, or AI agent. A cell serves HTTP, holds | |
| 12 | 14 | WebSocket connections, sets alarms, and makes outbound connections. Cells |
| 13 | 15 | share no database, so the application divides into cells from the start. |
| 14 | 16 | Each cell runs on one thread: a second request interleaves only while the |
| @@ -20,6 +22,8 @@ | ||
| 20 | 22 | any cell, so you add capacity by starting another node against the same |
| 21 | 23 | bucket. |
| 22 | 24 | |
| 25 | +## Cell lifecycle | |
| 26 | + | |
| 23 | 27 | A cell has the same states as a Durable Object. A **resident** cell is in |
| 24 | 28 | memory: it is **active** while it does work, and **idle** when it waits. |
| 25 | 29 | celld removes an idle cell from memory after `CELLD_IDLE_EVICT_S` seconds |
| @@ -39,21 +43,22 @@ | ||
| 39 | 43 | One 8 GB node holds 1,000 resident cells, so one resident cell costs |
| 40 | 44 | approximately $0.05 each month. |
| 41 | 45 | |
| 46 | +## Ownership and durability | |
| 47 | + | |
| 42 | 48 | Exactly one node serves a cell at a time. The nodes do not elect a leader |
| 43 | 49 | or keep a membership list: a node claims a cell by writing a small record |
| 44 | -to the bucket, and it writes that record with a condition the storage | |
| 45 | -enforces — the write succeeds only if nobody else changed the record | |
| 46 | -first. Object storage therefore decides who wins, and two nodes cannot | |
| 47 | -both claim the same cell. The claim expires unless the node keeps | |
| 48 | -renewing it, so a machine that dies releases its cells without anyone | |
| 49 | -having to declare it dead. | |
| 50 | +to the bucket. The store accepts the write only if no other node changed | |
| 51 | +the record first. Object storage therefore decides who wins, and two nodes | |
| 52 | +cannot both claim the same cell. The claim expires unless the node renews | |
| 53 | +it, so a failed machine releases its cells without a separate failure | |
| 54 | +detector. | |
| 50 | 55 | |
| 51 | 56 | celld does not answer a write until the data survives a failure, so no |
| 52 | 57 | write you were told succeeded is ever lost. That guarantee is called |
| 53 | 58 | RPO=0, for a recovery point of zero. |
| 54 | 59 | |
| 55 | -How celld earns it depends on how many nodes you run. One node writes the | |
| 56 | -data to the bucket first, which costs one storage round trip. Two or more | |
| 60 | +The durability mechanism depends on how many nodes you run. One node | |
| 61 | +writes the data to the bucket first, which costs one storage round trip. Two or more | |
| 57 | 62 | nodes are faster: the node serving the cell sends each write to another |
| 58 | 63 | node as well, and answers as soon as that node has the data on its own |
| 59 | 64 | disk. celld uploads the data to the bucket afterwards, so the bucket |
| @@ -68,6 +73,8 @@ | ||
| 68 | 73 | gives the full mechanism and the exact properties that the bucket must |
| 69 | 74 | provide. |
| 70 | 75 | |
| 76 | +## Alarms | |
| 77 | + | |
| 71 | 78 | When an event sets an alarm before its response boundary, celld does not send a |
| 72 | 79 | successful response until a durable wake entry covers the alarm. celld does |
| 73 | 80 | not let a later `waitUntil` alarm delay another event's response. |
| @@ -101,17 +108,22 @@ | ||
| 101 | 108 | |
| 102 | 109 | ## Contents |
| 103 | 110 | |
| 111 | +- [Cells and nodes](#cells-and-nodes) | |
| 112 | +- [Cell lifecycle](#cell-lifecycle) | |
| 113 | +- [Ownership and durability](#ownership-and-durability) | |
| 114 | +- [Alarms](#alarms) | |
| 104 | 115 | - [What do you build with cells](#what-do-you-build-with-cells) |
| 105 | 116 | - [Install](#install) |
| 106 | 117 | - [Configure object storage](#configure-object-storage) |
| 107 | 118 | - [Deploy an application](#deploy-an-application) |
| 108 | -- [Operate D1 and KV](#operate-d1-and-kv) | |
| 119 | +- [Operate D1, KV, and R2](#operate-d1-kv-and-r2) | |
| 109 | 120 | - [Start a node](#start-a-node) |
| 110 | 121 | - [Add nodes](#add-nodes) |
| 111 | 122 | - [Shut down and roll out a node](#shut-down-and-roll-out-a-node) |
| 112 | 123 | - [Diagnose a fleet](#diagnose-a-fleet) |
| 113 | 124 | - [List Durable Objects](#list-durable-objects) |
| 114 | 125 | - [Environment variables](#environment-variables) |
| 126 | +- [Services](#services) | |
| 115 | 127 | - [Cloudflare compatibility](cloudflare-compat.md) |
| 116 | 128 | - [What celld guarantees](guarantees.md) |
| 117 | 129 | - [Limitations](limitations.md) |
| @@ -120,6 +132,24 @@ | ||
| 120 | 132 | - [Testing](testing.md) |
| 121 | 133 | - [WebAssembly](wasm.md) |
| 122 | 134 | |
| 135 | +## Services | |
| 136 | + | |
| 137 | +Each service page contains a runnable example and the known differences from | |
| 138 | +the Cloudflare service. | |
| 139 | + | |
| 140 | +- [Workers](services/workers.md) | |
| 141 | +- [Durable Objects / Cells](services/durable-objects.md) | |
| 142 | +- [Durable Object Facets](services/durable-object-facets.md) | |
| 143 | +- [KV](services/kv.md) | |
| 144 | +- [Queues](services/queues.md) | |
| 145 | +- [D1](services/d1.md) | |
| 146 | +- [R2](services/r2.md) | |
| 147 | +- [Workflows](services/workflows.md) | |
| 148 | +- [Cron Triggers](services/cron-triggers.md) | |
| 149 | +- [Static assets](services/static-assets.md) | |
| 150 | +- [Dynamic Workers](services/dynamic-workers.md) | |
| 151 | +- [Containers](services/containers.md) | |
| 152 | + | |
| 123 | 153 | ## Install |
| 124 | 154 | |
| 125 | 155 | The installer downloads the `celld` binary. Replication runs inside the |
| @@ -183,10 +213,9 @@ | ||
| 183 | 213 | export CELLD_BUCKET=az://YOUR-CONTAINER |
| 184 | 214 | ``` |
| 185 | 215 | |
| 186 | -celld accepts three Azure credential families — a storage account key, a | |
| 187 | -managed identity, and a workload identity — and you must configure | |
| 188 | -exactly one. A system-assigned managed identity needs only the account | |
| 189 | -name. A user-assigned managed identity needs exactly one selector among | |
| 216 | +You must configure exactly one Azure credential family: a storage account | |
| 217 | +key, a managed identity, or a workload identity. A system-assigned managed | |
| 218 | +identity needs only the account name. A user-assigned managed identity needs exactly one selector among | |
| 190 | 219 | `AZURE_CLIENT_ID`, `AZURE_OBJECT_ID`, and `AZURE_MSI_RESOURCE_ID`, |
| 191 | 220 | because two selectors can name two different identities. An identity |
| 192 | 221 | must hold the Azure Blob data-plane permission to read, write, list, and |
| @@ -203,8 +232,8 @@ | ||
| 203 | 232 | works with the public authority host, `https://login.microsoftonline.com`, |
| 204 | 233 | with or without a trailing slash; celld rejects a sovereign or custom |
| 205 | 234 | host. celld also rejects each recognized Azure configuration variable |
| 206 | -outside these families — another credential source, an endpoint override, | |
| 207 | -the OneLake endpoint — and it ignores an `AZURE_*` name that | |
| 235 | +outside these families, including another credential source, an endpoint | |
| 236 | +override, or the OneLake endpoint. It ignores an `AZURE_*` name that | |
| 208 | 237 | `object_store` 0.12 does not recognize, because that name cannot change |
| 209 | 238 | the client. |
| 210 | 239 | |
| @@ -398,7 +427,7 @@ | ||
| 398 | 427 | The watcher does not watch a source file outside the project directory. Worker |
| 399 | 428 | projects need `esbuild` on `PATH`, and asset-only projects do not need it. |
| 400 | 429 | |
| 401 | -## Operate D1 and KV | |
| 430 | +## Operate D1, KV, and R2 | |
| 402 | 431 | |
| 403 | 432 | `celld d1` runs SQL and migrations against a deployed D1 database. The |
| 404 | 433 | command uses the fleet bucket to find a node, and the node routes the |
| @@ -430,6 +459,35 @@ | ||
| 430 | 459 | the listing. Pass `--all` to read every key, or `--json` for one JSON |
| 431 | 460 | object per key. |
| 432 | 461 | |
| 462 | +`celld r2` reads and writes the objects behind an `r2_buckets` binding. The | |
| 463 | +binding serves the fleet bucket under the reserved `r2/<bucket_name>/` | |
| 464 | +prefix, and this command reads the same prefix directly. It therefore needs | |
| 465 | +no running node, so a release pipeline can publish an artifact before it | |
| 466 | +deploys the Worker. | |
| 467 | + | |
| 468 | +```sh | |
| 469 | +celld r2 put assets app.zip --path dist/app.zip \ | |
| 470 | + --content-type application/zip \ | |
| 471 | + --metadata '{"release":"1.2.3"}' \ | |
| 472 | + --bucket "$CELLD_BUCKET" | |
| 473 | +``` | |
| 474 | + | |
| 475 | +The first argument is the `bucket_name` from the project's `r2_buckets` | |
| 476 | +entry, not the binding name. An object this command writes carries the same | |
| 477 | +record as an object `env.BUCKET.put()` writes, so `--metadata` becomes | |
| 478 | +`customMetadata` and the content flags become `httpMetadata`. Another tool | |
| 479 | +can write an object into the prefix, and the binding still reads it: the | |
| 480 | +object's user metadata becomes its `customMetadata`, and its headers become | |
| 481 | +its `httpMetadata`. Such an object carries no `cacheExpiry` and no | |
| 482 | +checksums, because a store has no place for either. | |
| 483 | + | |
| 484 | +`celld r2 get` writes the object to stdout as bytes, and it reads the body | |
| 485 | +as a stream, so an artifact larger than the available memory still | |
| 486 | +transfers. `celld r2 list` prints at most 1000 keys and reports on stderr | |
| 487 | +how to continue, the same as `celld kv list`. The `celld r2 head` command | |
| 488 | +prints the object's stored record. With `--json`, the `http` and `custom` | |
| 489 | +fields contain the binding's `httpMetadata` and `customMetadata` values. | |
| 490 | + | |
| 433 | 491 | Every celld command writes its data to stdout and its messages to stderr, |
| 434 | 492 | so a redirect or a pipe carries only data: |
| 435 | 493 | |
| @@ -587,7 +645,14 @@ | ||
| 587 | 645 | |
| 588 | 646 | The internal listener answers `GET /state` with the live counters: |
| 589 | 647 | `owned_cells`, `occupied`, `capacity_waiting`, `activation_waiting`, `restoring`, |
| 590 | -`shedding`, and the memory values. The `handed_off` counter is the number of | |
| 648 | +`shedding`, and the memory values. The `allocator` object reports the | |
| 649 | +Rust allocator's own counters in bytes: `allocated_bytes` is the memory | |
| 650 | +that Rust code holds, `resident_bytes` adds the freed pages that the | |
| 651 | +allocator keeps for reuse, and `mapped_bytes` and `retained_bytes` are its | |
| 652 | +address space. V8 maps its heaps itself, so `rss_bytes` includes them and | |
| 653 | +`allocated_bytes` does not. On Linux the `libc_malloc` object reports the | |
| 654 | +C allocator that SQLite and V8 use: `in_use_bytes` is what they hold, and | |
| 655 | +`free_bytes` is what glibc keeps for them after a free. The `handed_off` counter is the number of | |
| 591 | 656 | cells this node gave to a peer, `rebalanced` is the part of that number |
| 592 | 657 | that balancing moved, and `rebalance_failed` is the number of balancing |
| 593 | 658 | moves that no peer acquired. A positive `capacity_waiting` means |
| @@ -603,6 +668,21 @@ | ||
| 603 | 668 | route, so it also increases during normal lease renewal. An adoption |
| 604 | 669 | without a lease and an explicit invalidation do not increase it. |
| 605 | 670 | |
| 671 | +The `deployment.isolates` object reports the V8 isolates of the current | |
| 672 | +deployment, and each entry of `deployment.draining` reports the isolates | |
| 673 | +of one superseded deployment. The `cells` map has one entry for each | |
| 674 | +Worker script, and the `stateless` and `services` entries cover the | |
| 675 | +request handlers. Each entry counts the isolates that accept work | |
| 676 | +(`live`), the live isolates that house no cell (`live_empty`), the | |
| 677 | +retiring isolates that still hold a heap (`retiring`), and the freed | |
| 678 | +slots (`freed`), with the cells, requests, and turns that they hold. | |
| 679 | +`heap_bytes` is the physical memory that V8 has committed to those heaps, | |
| 680 | +and `external_bytes` is the memory that the isolates track outside them. A | |
| 681 | +dormant cell holds no isolate, and celld retires an empty cell isolate on | |
| 682 | +its next maintenance pass, so a `live_empty` count that persists for more | |
| 683 | +than 30 seconds means that the pass does not run. A `retiring` count that | |
| 684 | +persists means that a turn or a request still holds the heap. | |
| 685 | + | |
| 606 | 686 | The public `/.well-known/celld/health` path stays a boolean. It reports |
| 607 | 687 | 503 during a drain and before a joining node settles, so an |
| 608 | 688 | orchestrator can gate a rolling update on it, but it carries no |
| @@ -772,13 +852,12 @@ | ||
| 772 | 852 | contains `node-log close: sealed epoch`. A graceful stop attempts this |
| 773 | 853 | seal, but a stop under load can leave the record open, and a v0.2.x |
| 774 | 854 | binary cannot read writes that wait in the replicated log or bundle |
| 775 | - objects — this downgrade can lose acknowledged writes. | |
| 855 | + objects. Therefore, this downgrade can lose acknowledged writes. | |
| 776 | 856 | - The upgrade from v0.3.0 to v0.4.0 must not use a rolling update. Stop |
| 777 | 857 | every v0.3.0 node, and then start the v0.4.0 nodes. v0.4.0 moves every |
| 778 | - proxied cell call — the fetch, the RPC, and the WebSocket — onto one | |
| 779 | - tunneled connection that carries plain HTTP, and the peer protocol | |
| 780 | - refuses a different version, so the two versions cannot proxy calls to | |
| 781 | - each other. v0.4.0 also stores each new large KV value under its ownership | |
| 858 | + proxied fetch, RPC, and WebSocket call onto one tunneled connection that | |
| 859 | + carries plain HTTP. The peer protocol refuses a different version, so the | |
| 860 | + two versions cannot proxy calls to each other. v0.4.0 also stores each new large KV value under its ownership | |
| 782 | 861 | epoch and writes an epoch-qualified row reference. A v0.3.0 node cannot |
| 783 | 862 | read that reference, so a mixed fleet can make a committed KV value |
| 784 | 863 | unavailable. The tunnel establishment carries the version, so a later |
| @@ -803,7 +882,9 @@ | ||
| 803 | 882 | pause in its lease, and one paused lease stops every move in the fleet, so |
| 804 | 883 | a pause on one node pauses the fleet. `POST /rebalance/resume` on the same |
| 805 | 884 | node resumes it. The `POST /shutdown?handoff=preserve` request prepares a clean |
| 806 | -same-node reload and keeps the ownership records. celld writes the reload marker | |
| 885 | +same-node reload and keeps the ownership records. The preserve operation cancels | |
| 886 | +a cold activation, including a wait for a recovery retry, because the activation | |
| 887 | +has no runtime to retain. celld writes the reload marker | |
| 807 | 888 | only after it uploads each stopped database position to the bucket. If an upload |
| 808 | 889 | fails, the next process uses the normal recovery path. A release can change this |
| 809 | 890 | API, so keep the operator tooling and the celld release together. |
modifieddocs/cloudflare-compat.md+43−278View file
| @@ -17,20 +17,23 @@ | ||
| 17 | 17 | |
| 18 | 18 | ## Services |
| 19 | 19 | |
| 20 | +Each supported service has a page with an example and the known differences | |
| 21 | +from Cloudflare. | |
| 22 | + | |
| 20 | 23 | | service | status | |
| 21 | 24 | | --- | --- | |
| 22 | -| [Workers](#workers) | **Yes** | | |
| 23 | -| [Durable Objects](#durable-objects) | **Yes** | | |
| 24 | -| [Durable Object Facets](#durable-object-facets) | **Yes** | | |
| 25 | -| [Containers](#containers) | **Experimental** | | |
| 26 | -| [Static assets](#static-assets) | **Yes** | | |
| 27 | -| [Cron Triggers](#cron-triggers) | **Yes** | | |
| 28 | -| [Dynamic Workers](#dynamic-workers) | **Yes** | | |
| 29 | -| [KV](#kv) | **Yes** | | |
| 30 | -| [Queues](#queues) | **Yes** | | |
| 31 | -| [D1](#d1) | **Yes** | | |
| 32 | -| [Workflows](#workflows) | **Yes** | | |
| 33 | -| [R2](#r2) | **Yes** | | |
| 25 | +| [Workers](services/workers.md) | **Yes** | | |
| 26 | +| [Durable Objects](services/durable-objects.md) | **Yes** | | |
| 27 | +| [Durable Object Facets](services/durable-object-facets.md) | **Yes** | | |
| 28 | +| [Containers](services/containers.md) | **Experimental** | | |
| 29 | +| [Static assets](services/static-assets.md) | **Yes** | | |
| 30 | +| [Cron Triggers](services/cron-triggers.md) | **Yes** | | |
| 31 | +| [Dynamic Workers](services/dynamic-workers.md) | **Yes** | | |
| 32 | +| [KV](services/kv.md) | **Yes** | | |
| 33 | +| [Queues](services/queues.md) | **Yes** | | |
| 34 | +| [D1](services/d1.md) | **Yes** | | |
| 35 | +| [Workflows](services/workflows.md) | **Yes** | | |
| 36 | +| [R2](services/r2.md) | **Yes** | | |
| 34 | 37 | | Workers AI | **No** | |
| 35 | 38 | | Vectorize | **No** | |
| 36 | 39 | | Hyperdrive | **No** | |
| @@ -38,272 +41,6 @@ | ||
| 38 | 41 | | Email Workers | **No** | |
| 39 | 42 | | Python Workers | **No** | |
| 40 | 43 | |
| 41 | -### [Workers](https://developers.cloudflare.com/workers/runtime-apis/) | |
| 42 | - | |
| 43 | -- celld does not manage a custom domain or terminate TLS. Terminate TLS in the | |
| 44 | - ingress proxy. | |
| 45 | -- celld does not supply a Workers AI binding. Call an AI provider from the | |
| 46 | - application. The process rejects `CELLD_AI_BINDING` and `CELLD_AI_URL`, and a | |
| 47 | - deployment rejects an `ai` declaration. | |
| 48 | - | |
| 49 | -### [Durable Objects](https://developers.cloudflare.com/durable-objects/) | |
| 50 | - | |
| 51 | -- A Durable Object event keeps pending I/O active after the handler returns, so | |
| 52 | - a timer or a subrequest does not require `ctx.waitUntil()`. | |
| 53 | -- An RPC stub cannot cross an isolate boundary. See [RPC](#rpc). | |
| 54 | -- An outbound WebSocket does not continue after the object moves to another | |
| 55 | - node. | |
| 56 | -- celld refuses invalid UTF-8 from a SQLite `TEXT` value. Store arbitrary bytes | |
| 57 | - in a `BLOB`. | |
| 58 | -- `SqlStorage.Cursor.toArray()` gives a celld-specific error near the V8 heap | |
| 59 | - limit. | |
| 60 | -- `storage.sync()` waits for the object store or the fleet ensemble to hold all | |
| 61 | - earlier committed writes. The operation uses the shorter of the 10-second | |
| 62 | - `CELLD_LTX_DURABILITY_TIMEOUT_SECS` default and the 15-second | |
| 63 | - `CELLD_OPERATION_DEADLINE_MS` default. | |
| 64 | -- `storage.sync()` rejects during an open transaction and after an object abort. | |
| 65 | - Without an object store, it resolves after the local commit. | |
| 66 | -- A transaction and `blockConcurrencyWhile()` have a 30-second limit. A timeout | |
| 67 | - resets the object and rolls back an open transaction. | |
| 68 | -- A failed handler still waits for the durability of any value or write that it | |
| 69 | - can expose. A celld-generated failure that exposes no object value returns | |
| 70 | - immediately. | |
| 71 | -- Outside an explicit transaction, a SQL write cursor must finish before a | |
| 72 | - response, an outbound effect, or `storage.sync()`. An unfinished `RETURNING` | |
| 73 | - cursor holds uncommitted writes, so celld rejects that output with an error. | |
| 74 | - A read cursor can remain open. | |
| 75 | - | |
| 76 | -### [Containers](https://developers.cloudflare.com/containers/) | |
| 77 | - | |
| 78 | -Containers are experimental. The configuration keys, the `ctx.container` | |
| 79 | -surface, the node-side defaults, and the security boundary can change | |
| 80 | -without notice, and a change appears on this page. | |
| 81 | - | |
| 82 | -Configuration and images: | |
| 83 | - | |
| 84 | -- A `containers` entry accepts `class_name`, `image`, `name`, | |
| 85 | - `instance_type`, and `max_instances`. Each other key stops the deployment. | |
| 86 | - The class must be a SQLite-backed Durable Object class of the same script. | |
| 87 | -- `image` is a Dockerfile path in the project or an image reference. `celld | |
| 88 | - deploy` and `celld dev` build or pull the image with the `docker` CLI on | |
| 89 | - `PATH`, or the CLI that `CELLD_DOCKER` names. A Podman CLI works. | |
| 90 | -- `celld deploy` builds and pulls for `linux/amd64`, as Wrangler does, so a | |
| 91 | - deploy from an ARM machine runs on x86-64 nodes. Set | |
| 92 | - `CELLD_CONTAINER_PLATFORM` to build for another platform. `celld dev` | |
| 93 | - builds for the local machine. | |
| 94 | -- `celld deploy` saves each image to the bucket at `deploy/images/<key>.tar`, | |
| 95 | - where the key hashes the image layers and config, so a node never contacts | |
| 96 | - a registry. A node loads an image into its own engine the first time a | |
| 97 | - cell of the class starts, and a redeploy of an unchanged image uploads | |
| 98 | - nothing. The `celld-fence` image that the node needs rides with every | |
| 99 | - deployment that has a container. | |
| 100 | -- `instance_type` sets the CPU and memory limits of the Cloudflare instance | |
| 101 | - type with that name. An entry without one gets the `dev` type, a sixteenth | |
| 102 | - of a CPU and 256 MiB, as on Cloudflare. The disk size of the type is not | |
| 103 | - enforced. | |
| 104 | -- `max_instances` caps the containers a class runs across the fleet. | |
| 105 | - Cloudflare enforces the cap centrally; celld has no coordinator, so each | |
| 106 | - node publishes its running container count per class in its node record, | |
| 107 | - and a node about to start a container sums that count across the fleet | |
| 108 | - from the shared node sample and adds its own live count. A start over the | |
| 109 | - cap fails, and the object's `monitor()` reports the limit. The sample can | |
| 110 | - lag one refresh, so two nodes that start the same class at once can | |
| 111 | - briefly exceed the cap and converge on the next refresh. | |
| 112 | - | |
| 113 | -The node and its engine: | |
| 114 | - | |
| 115 | -- Each node that serves a container class needs a Docker or Podman daemon. | |
| 116 | - celld uses the unix socket that `DOCKER_HOST` names, or the default socket | |
| 117 | - of Docker, Docker Desktop, OrbStack, or Podman. A node without an engine | |
| 118 | - rejects each `start()` with an error, and it serves every other class. | |
| 119 | -- `CELLD_CONTAINER_RUNTIME` names the OCI runtime for every container on the | |
| 120 | - node, for example `runsc` for gVisor or `kata` for a virtual machine. A | |
| 121 | - `containers` entry can name a `runtime` of its own, which overrides the | |
| 122 | - node setting for that class; celld adds this key, which Cloudflare's | |
| 123 | - config does not have. The daemon must have the runtime, or every `start()` | |
| 124 | - of a container that names it fails and `monitor()` rejects with the | |
| 125 | - daemon's error, so a class runs only where its isolation exists. Under the | |
| 126 | - default runtime a container is a kernel namespace boundary, not a virtual | |
| 127 | - machine. For code you did not write, set a runtime that gives each | |
| 128 | - container its own kernel, and keep secrets in the Worker, as the Sandbox | |
| 129 | - SDK recommends. | |
| 130 | -- A container that runs under a named runtime gets a public resolver in its | |
| 131 | - `/etc/resolv.conf`, `1.1.1.1` by default and the `CELLD_CONTAINER_DNS` | |
| 132 | - resolvers when the operator sets them. gVisor cannot reach the container | |
| 133 | - engine's built-in resolver, so a container under it would resolve no | |
| 134 | - hostname otherwise; the fence permits the public resolver. A container on | |
| 135 | - the node's default runtime keeps the engine's resolver. | |
| 136 | -- A container runs on the node that owns the cell. An idle eviction keeps the | |
| 137 | - container running for the `setInactivityTimeout()` window, or for 10 | |
| 138 | - minutes without one, and the next activation on the same node reconnects to | |
| 139 | - it. A move to another node, a node restart, and a reset destroy it, so the | |
| 140 | - container disk is ephemeral, as on Cloudflare. A node stop destroys every | |
| 141 | - container of the node, and Ctrl-C on `celld dev` does the same while it | |
| 142 | - keeps the local state. | |
| 143 | - | |
| 144 | -Every container gets the same limits and the same boundary: | |
| 145 | - | |
| 146 | -- All Linux capabilities are dropped, `no-new-privileges` is set, the | |
| 147 | - daemon's default seccomp profile applies, and the container can hold 1024 | |
| 148 | - processes. Two containers on one node cannot open connections to each | |
| 149 | - other. | |
| 150 | -- The node fences its container bridges before the first container starts, | |
| 151 | - with nftables rules on the node, outside every container and every | |
| 152 | - runtime. A container with `enableInternet: true` reaches the Internet and | |
| 153 | - nothing of the node's own: it cannot open a connection to the node, to | |
| 154 | - another node, to the private ranges `10/8`, `172.16/12`, `192.168/16`, and | |
| 155 | - `100.64/10`, or to the link-local range, so the node's internal listener | |
| 156 | - and a cloud metadata service are out of reach. celld installs the rules | |
| 157 | - through the daemon with a one-shot privileged container of the | |
| 158 | - `celld-fence` image. A node that cannot install the rules starts no | |
| 159 | - container, and a deployment from a celld without the fence image starts | |
| 160 | - no container on a node with it. IPv6 bridges are not created, so only IPv4 | |
| 161 | - is fenced. | |
| 162 | -- `enableInternet: false` attaches the container to an internal bridge with | |
| 163 | - no route out. On macOS the node reaches a container only through | |
| 164 | - published ports, and an internal network publishes none, so `celld dev` on | |
| 165 | - macOS keeps egress on and logs a warning; the fence still applies. | |
| 166 | - | |
| 167 | -The `ctx.container` surface: | |
| 168 | - | |
| 169 | -- `running`, `start()`, `monitor()`, `destroy()`, `signal()`, | |
| 170 | - `getTcpPort()`, `exec()`, and `setInactivityTimeout()` work. `start()` | |
| 171 | - accepts `entrypoint`, `env`, `enableInternet`, and `labels`; it ignores | |
| 172 | - `hardTimeout`. `inspect()`, the snapshot methods, and the outbound | |
| 173 | - interception methods reject with an error. | |
| 174 | -- A `monitor()` promise and an `exec()` process settle only inside the event | |
| 175 | - that created them. After the handler answers, they do not keep the object | |
| 176 | - active, so a drain can move the object. `running` always reports the | |
| 177 | - engine's state, so an object that lost its `monitor()` sees the exit at | |
| 178 | - its next event. A `start()` that fails is logged by the node as | |
| 179 | - `container_start_failed`. | |
| 180 | -- `getTcpPort(port).fetch()` reaches the container over the node's route to | |
| 181 | - it. On Linux the route is the container's bridge address, so every port | |
| 182 | - works. On macOS the route is a published loopback port, so the image must | |
| 183 | - declare the port with `EXPOSE`, as `wrangler dev` requires. A fetch with | |
| 184 | - an `Upgrade: websocket` header gives a 101 response with a `webSocket`, | |
| 185 | - as on Cloudflare. | |
| 186 | -- `getTcpPort(port).connect()` gives a socket with the lifetime of the | |
| 187 | - event that opened it. See [TCP sockets](#tcp-sockets). | |
| 188 | - | |
| 189 | -The published packages: | |
| 190 | - | |
| 191 | -- `@cloudflare/containers` runs as published. Its `sleepAfter` alarm stops | |
| 192 | - the container, and `getContainer()`, `getRandom()`, and `switchPort()` | |
| 193 | - work. | |
| 194 | -- `@cloudflare/sandbox` runs as published on the `cloudflare/sandbox` image: | |
| 195 | - `exec()`, files, processes, sessions, and the code interpreter run inside | |
| 196 | - the container, over the HTTP and the RPC transport. A move of the object | |
| 197 | - to another node stops its container, so the first call after the move can | |
| 198 | - fail with the SDK's `OperationInterruptedError`, as after a container | |
| 199 | - restart on Cloudflare. The next call starts a fresh container. Preview | |
| 200 | - URLs need a wildcard hostname at the operator's load balancer, tunnels | |
| 201 | - run cloudflared inside the container, and bucket mounts use the | |
| 202 | - credentials the application passes. See | |
| 203 | - [`examples/sandbox`](../examples/sandbox). | |
| 204 | - | |
| 205 | -### [Static assets](https://developers.cloudflare.com/workers/static-assets/) | |
| 206 | - | |
| 207 | -- celld does not compress an asset response. Use a compressing ingress proxy | |
| 208 | - when a client needs gzip or brotli. | |
| 209 | -- celld has no edge cache. Each node keeps a 512 MiB disk cache, configured by | |
| 210 | - `CELLD_ASSET_CACHE_BYTES`, and requires browser revalidation. | |
| 211 | -- A node checks the deployment pointer after an asset miss at most once in five | |
| 212 | - seconds. | |
| 213 | -- A `_headers` file cannot change `connection`, `content-length`, or | |
| 214 | - `transfer-encoding`. | |
| 215 | -- A deployment can contain 20,000 assets, 25 MiB for each asset, and 1 GiB in | |
| 216 | - total. Each `_headers` or `_redirects` file has a 100 KiB limit. | |
| 217 | -- `celld deploy` does not read `.assetsignore`. It also refuses a symbolic link, | |
| 218 | - a special file, a non-UTF-8 name, an unsafe decoded path, and a `_worker.js` | |
| 219 | - entry. | |
| 220 | - | |
| 221 | -### [Cron Triggers](https://developers.cloudflare.com/workers/configuration/cron-triggers/) | |
| 222 | - | |
| 223 | -- celld rejects a descending range such as `SAT-SUN` and a list that contains | |
| 224 | - `*`. | |
| 225 | -- celld runs one handler for each occurrence across the fleet. After downtime, | |
| 226 | - it runs only the most recent missed occurrence. | |
| 227 | -- celld serializes the handlers for one script. It retries a failure until the | |
| 228 | - next occurrence unless the handler calls `noRetry()`. | |
| 229 | -- A service-binding target cannot run its own Cron Triggers. | |
| 230 | - | |
| 231 | -### [Dynamic Workers](https://developers.cloudflare.com/dynamic-workers/) | |
| 232 | - | |
| 233 | -- The process limit is 256 live Dynamic Workers, and each script generation can | |
| 234 | - use 255 slots. Every loader and script shares the process limit. | |
| 235 | -- The process rejects the removed `CELLD_MAX_LOADED_WORKERS` environment | |
| 236 | - variable. | |
| 237 | -- `getEntrypoint()` and `getDurableObjectClass()` support only the `props` | |
| 238 | - option. A structured-clone encoded `props` value can be at most 1 MiB. | |
| 239 | -- A `globalOutbound` Fetcher cannot use `connect()` or a WebSocket. | |
| 240 | -- celld rejects `limits`, `tails`, and `allowExperimental`. It does not enforce | |
| 241 | - the `cpuMs` or `subRequests` values inside `limits`. | |
| 242 | -- `WorkerCode.env` accepts structured-clone values and Service Binding | |
| 243 | - capabilities. The encoded values and the capability props can total 1 MiB. | |
| 244 | -- A loaded Worker entrypoint cannot transfer to another Worker. Awaitable and | |
| 245 | - pipelined properties are also unavailable. | |
| 246 | - | |
| 247 | -### [Durable Object Facets](https://developers.cloudflare.com/dynamic-workers/usage/durable-object-facets/) | |
| 248 | - | |
| 249 | -- Facets require Dynamic Workers and a class from a Worker Loader binding. A | |
| 250 | - class from `ctx.exports` or a Durable Object binding is unavailable. | |
| 251 | -- Each facet has a separate SQLite database, which celld replicates with the | |
| 252 | - root Durable Object. | |
| 253 | -- celld rejects an outbound effect from a facet while a root storage transaction | |
| 254 | - holds an uncommitted facet image. | |
| 255 | -- An explicit transaction keeps its uncommitted writes in the facet. A rollback | |
| 256 | - discards those writes, and a commit makes them available for root replication. | |
| 257 | -- The `clone()` method is unavailable. | |
| 258 | - | |
| 259 | -### [KV](https://developers.cloudflare.com/kv/api/) | |
| 260 | - | |
| 261 | -- celld has no edge cache. `cacheTtl` has no effect, and `cacheStatus` is | |
| 262 | - `null`. | |
| 263 | -- A value above 1 MiB requires a fleet bucket. | |
| 264 | -- A namespace has one writer. Use more namespaces to increase write capacity. | |
| 265 | - | |
| 266 | -### [Queues](https://developers.cloudflare.com/queues/configuration/javascript-apis/) | |
| 267 | - | |
| 268 | -- A queue has one writer. Use more queues to increase write capacity. | |
| 269 | -- A Queue owner accepts at most 256 concurrent producer calls. It refuses an | |
| 270 | - additional call, which the producer can retry. | |
| 271 | -- celld retains a message for four days. This period is not configurable. | |
| 272 | -- Pull consumers, the Queues HTTP API, dashboard controls, manual consumer | |
| 273 | - attachment, R2 event notifications, and Queue event subscriptions are | |
| 274 | - unavailable. | |
| 275 | - | |
| 276 | -### [D1](https://developers.cloudflare.com/d1/worker-api/d1-database/) | |
| 277 | - | |
| 278 | -- A binding result can contain at most 100,000 rows or 32 MiB. | |
| 279 | -- celld refuses invalid UTF-8 from a SQLite `TEXT` value. Store arbitrary bytes | |
| 280 | - in a `BLOB`. | |
| 281 | - | |
| 282 | -### [Workflows](https://developers.cloudflare.com/workflows/build/workers-api/) | |
| 283 | - | |
| 284 | -- celld retains a successful or failed instance for 30 days by default. Each | |
| 285 | - duration in the `retention` option can be at most 30 days. | |
| 286 | -- `locationHint` accepts the Cloudflare values, but fleet ownership selects the | |
| 287 | - cell location. | |
| 288 | -- Non-step work cannot remain pending for more than 60 seconds. | |
| 289 | -- A step result, an event payload, and the workflow parameters each have a | |
| 290 | - 1 MiB limit. | |
| 291 | -- Rollback, a sensitive step result, and a `ReadableStream` step result are | |
| 292 | - unavailable. | |
| 293 | - | |
| 294 | -### [R2](https://developers.cloudflare.com/r2/api/workers/workers-api-reference/) | |
| 295 | - | |
| 296 | -- An R2 binding uses the fleet bucket under `r2/<bucket_name>/`. | |
| 297 | -- An object `version` equals its content ETag, so identical content produces | |
| 298 | - the same version. | |
| 299 | -- `ssecKey` and `jurisdiction` are unavailable. | |
| 300 | -- A conditional write cannot use a streamed body larger than 8 MiB. | |
| 301 | -- `createMultipartUpload()` does not accept a checksum. | |
| 302 | -- A multipart upload cannot resume on another node or after a restart. celld | |
| 303 | - also cannot replace a part that the object store already holds. | |
| 304 | -- Out-of-order parts can use at most 256 MiB of memory, and completion cannot | |
| 305 | - change the stored part order. | |
| 306 | - | |
| 307 | 44 | ## Runtime APIs |
| 308 | 45 | |
| 309 | 46 | | API | status | |
| @@ -408,12 +145,23 @@ | ||
| 408 | 145 | - `node:diagnostics_channel` does not export messages to a tail Worker. |
| 409 | 146 | - `node:crypto` does not implement Diffie-Hellman, streaming signatures, |
| 410 | 147 | ciphers, RSA-PSS, or DSA signatures and key generation. |
| 148 | +- `KeyObject.toCryptoKey()` applies the requested algorithm, extractability, | |
| 149 | + and usages to an asymmetric key. | |
| 411 | 150 | - `node:zlib` implements only the synchronous gzip and deflate functions. |
| 412 | 151 | - `node:fs` provides `access`, `mkdir`, `realpath`, `stat`, `lstat`, and |
| 413 | 152 | `readFile`. It exposes an empty, request-local `/tmp` and a read-only |
| 414 | 153 | `/bundle` that contains the Worker modules. |
| 154 | +- The global `process` gives each field that it defines the same value that | |
| 155 | + workerd gives it, so a dependency that reads `process.execPath`, | |
| 156 | + `process.argv`, or `process.title` at module scope can load. celld does not | |
| 157 | + define the full workerd surface, so a field such as `process.kill` or | |
| 158 | + `process.features` is undefined. | |
| 415 | 159 | - The celld bundler supports a synchronous CommonJS `require()` of a Node.js |
| 416 | 160 | built-in module. A raw ESM Worker has no global `require()`. |
| 161 | +- A Node.js built-in module object is writable, so a CommonJS dependency that | |
| 162 | + replaces a function on the module at load can start. The `graceful-fs` | |
| 163 | + package replaces `fs.close` this way. A patch stays in the isolate that | |
| 164 | + applies it, therefore another Worker never observes the patch. | |
| 417 | 165 | - An import of another Node.js module succeeds, but its first call throws an |
| 418 | 166 | error. |
| 419 | 167 | |
| @@ -467,9 +215,26 @@ | ||
| 467 | 215 | - `d1_databases`, `kv_namespaces`, `queues`, `workflows`, and |
| 468 | 216 | `r2_buckets` |
| 469 | 217 | - `worker_loaders` and `containers` |
| 218 | +- `define` and `rules` | |
| 470 | 219 | |
| 471 | 220 | Each other top-level key, including `routes`, stops the deployment. |
| 472 | 221 | |
| 222 | +`celld deploy` bundles with esbuild, and it gives `define` and `rules` to that | |
| 223 | +run. Each `define` value is a JavaScript expression, as it is for Wrangler. | |
| 224 | +A rule must have a `type` of `Text`, `Data`, or `CompiledWasm`, and each of its | |
| 225 | +globs must have the form `**/*.ext` or `*.ext`: esbuild selects a loader by | |
| 226 | +file extension, so celld refuses a glob that selects a different set of files. | |
| 227 | + | |
| 228 | +Two rules can name one extension only if they give it the same type. Two rules | |
| 229 | +that give one extension different types stop the deployment, because no single | |
| 230 | +loader satisfies both. celld applies a `CompiledWasm` rule to `**/*.wasm` | |
| 231 | +already, so a `CompiledWasm` rule for that extension agrees with the built-in | |
| 232 | +rule and the deployment continues. Another type for `**/*.wasm` stops the | |
| 233 | +deployment. | |
| 234 | + | |
| 235 | +`no_bundle` does not run esbuild. A config that sets `no_bundle` with `define` | |
| 236 | +or `rules` therefore stops the deployment. | |
| 237 | + | |
| 473 | 238 | An asset-only project can omit `main`. The native deploy command refuses an |
| 474 | 239 | unsafe asset path, and `.assetsignore` requires Wrangler. |
| 475 | 240 |
modifieddocs/guarantees.md+17−12View file
| @@ -5,14 +5,13 @@ | ||
| 5 | 5 | not answer a write until that write survives a failure, so nothing you |
| 6 | 6 | were told succeeded is lost. |
| 7 | 7 | |
| 8 | -This page is how both promises are kept. Fencing is the part that keeps | |
| 9 | -the first one true when a node is slow, paused, or cut off from the | |
| 10 | -network: celld refuses that node's writes rather than trusting it to | |
| 11 | -notice it lost the cell. Both claims rest on the object | |
| 12 | -store, so this page starts with what you must provide: a bucket with | |
| 13 | -working conditional writes and ranged reads, and a supervisor that | |
| 14 | -restarts the process. The mechanism follows, so you can check the | |
| 15 | -argument against the code. | |
| 8 | +This page explains how celld keeps both promises. Fencing prevents a | |
| 9 | +slow, paused, or disconnected node's writes from damaging the current | |
| 10 | +owner's data after it loses a cell. | |
| 11 | +Each ownership epoch has a separate storage prefix, so a stale node's | |
| 12 | +writes cannot overwrite the current owner's data. | |
| 13 | +Both guarantees require a bucket with working conditional writes and | |
| 14 | +ranged reads, and a supervisor that restarts the process. | |
| 16 | 15 | |
| 17 | 16 | ## What the bucket must provide |
| 18 | 17 | |
| @@ -34,7 +33,7 @@ | ||
| 34 | 33 | implement the required conditional writes. celld is not correct on such |
| 35 | 34 | a store: two nodes can then own one cell. A store can also accept the |
| 36 | 35 | conditional headers and ignore the condition, and that store fails late |
| 37 | -and silently — so run the storage test below. | |
| 36 | +and silently, so run the storage test below. | |
| 38 | 37 | |
| 39 | 38 | MinIO (the community edition) implements the conditional writes and |
| 40 | 39 | passes the storage test, but celld has not qualified it for production. |
| @@ -124,9 +123,9 @@ | ||
| 124 | 123 | |
| 125 | 124 | Each cell has one ownership record in the bucket. The record names the |
| 126 | 125 | owner node's session and carries a fencing epoch. A node acquires a |
| 127 | -cell with a conditional write — a create when no record exists, a | |
| 128 | -compare-and-swap on the previous record when one does — and the bucket | |
| 129 | -accepts one such write, so two nodes cannot acquire the same cell. | |
| 126 | +cell with a conditional create when no record exists, or a compare-and-swap | |
| 127 | +on an existing record. The bucket accepts only one competing write, so two | |
| 128 | +nodes cannot acquire the same cell. | |
| 130 | 129 | |
| 131 | 130 | Every activation advances the epoch, a takeover and a local wake alike. |
| 132 | 131 | Each owner therefore replicates under a fresh epoch, and an epoch never |
| @@ -142,6 +141,12 @@ | ||
| 142 | 141 | cells into a node bundle, and it drains each segment into its per-cell |
| 143 | 142 | prefix later.) |
| 144 | 143 | |
| 144 | +The compactor reads retained bundles when a cell's segments leave the | |
| 145 | +in-memory index. A failed compaction retries after 30 seconds, and repeated | |
| 146 | +failures increase the delay to a maximum of 300 seconds. The bundle collector | |
| 147 | +advances through retained objects and deletes a bundle only when the per-cell | |
| 148 | +prefixes cover every segment in that bundle. | |
| 149 | + | |
| 145 | 150 | The prefix protects the new owner's data from stale writes. The next |
| 146 | 151 | two sections protect the durability promise. |
| 147 | 152 |
modifieddocs/security.md+65−1View file
| @@ -94,7 +94,7 @@ | ||
| 94 | 94 | |
| 95 | 95 | - `/state` reports node state. |
| 96 | 96 | - `/cell/<SCOPE>` resolves or activates a cell. |
| 97 | -- `/evict/<SCOPE>` evicts a resident cell. | |
| 97 | +- `/evict/<SCOPE>` tries to evict a resident cell and reports the result. | |
| 98 | 98 | - `/do/<ID>` sends a direct request to an ordinary Durable Object. |
| 99 | 99 | - `POST /shutdown` starts a graceful ownership handoff. The |
| 100 | 100 | `handoff=preserve` query prepares a same-node reload. |
| @@ -108,6 +108,70 @@ | ||
| 108 | 108 | uses other reserved internal paths. An operator must not call these paths |
| 109 | 109 | directly. |
| 110 | 110 | |
| 111 | +### Read an eviction result | |
| 112 | + | |
| 113 | +The eviction request waits for the accepted operation to finish. A refused | |
| 114 | +request does not wait for an idle period or another lifecycle transition. | |
| 115 | +An accepted request can join an eviction that is already running, and each | |
| 116 | +waiting caller receives that operation's result. | |
| 117 | + | |
| 118 | +The Rust method `AppHandle::evict` returns `Result<EvictSuccess, EvictError>`. | |
| 119 | +The success value `Evicted` confirms that the awaited eviction completes its | |
| 120 | +runtime stop. The success value `AlreadyAbsent` confirms settled local absence | |
| 121 | +when the Actor handles the request. A caller that requires a completed eviction | |
| 122 | +must check for `Evicted`. | |
| 123 | + | |
| 124 | +Multiple callers can join one eviction and receive `Evicted`, so the successful | |
| 125 | +call count does not measure the runtime stop count. | |
| 126 | +The error distinguishes a refusal, a cancellation, and an execution failure. | |
| 127 | +The Rust error methods `kind()` and `reason()` return the `kind` and `reason` | |
| 128 | +strings of the HTTP error body. | |
| 129 | + | |
| 130 | +The response uses `application/json`. Both success values use status 200 with | |
| 131 | +`{"ok":true}`, so the HTTP response does not distinguish them. | |
| 132 | +It confirms a completed eviction or a settled local absence at the decision | |
| 133 | +point. A later request can reactivate the cell before the response arrives. | |
| 134 | + | |
| 135 | +A missing cell or a settled `Inactive`, `Dormant`, or `Remote` cell counts | |
| 136 | +as locally absent. A pending activation, stop, or ownership transfer prevents | |
| 137 | +that result. The request does not evict a remote runtime. A dormant cell | |
| 138 | +keeps its ownership and its hibernated host sockets. | |
| 139 | + | |
| 140 | +The node checks its availability before it reports local absence. The node | |
| 141 | +refuses an eviction during preservation, reload, or local inventory | |
| 142 | +confirmation, or when it lacks authority. | |
| 143 | + | |
| 144 | +Every eviction error has this structure: | |
| 145 | + | |
| 146 | +```json | |
| 147 | +{"ok":false,"error":{"kind":"refused","reason":"cell_active"}} | |
| 148 | +``` | |
| 149 | + | |
| 150 | +The `kind` and `reason` values have these meanings: | |
| 151 | + | |
| 152 | +| Status | Kind | Reason | Cause | | |
| 153 | +| --- | --- | --- | --- | | |
| 154 | +| 409 | `refused` | `cell_active` | The cell has active work or a socket that requires a runtime. | | |
| 155 | +| 409 | `refused` | `cell_transitioning` | The cell has another lifecycle transition. | | |
| 156 | +| 409 | `refused` | `alarm_imminent` | The alarm residency policy retains the cell. | | |
| 157 | +| 409 | `refused` | `alarm_uncovered` | The alarm coverage is unconfirmed, or a firing alarm blocks eviction during pressure shedding. | | |
| 158 | +| 503 | `refused` | `node_unavailable` | The node cannot accept the eviction. | | |
| 159 | +| 503 | `refused` | `eviction_limit` | The node has reached its eviction concurrency limit. | | |
| 160 | +| 409 | `cancelled` | `new_activity` | A new request cancels an accepted eviction. | | |
| 161 | +| 409 | `cancelled` | `alarm_activity` | An alarm observation or firing cancels an accepted eviction. | | |
| 162 | +| 409 | `cancelled` | `node_fenced` | The node loses its authority during the eviction. | | |
| 163 | +| 503 | `failed` | `actor_unavailable` | The request cannot reach the Actor. | | |
| 164 | +| 500 | `failed` | `reply_lost` | A delivered request loses its reply, so its outcome is unknown. | | |
| 165 | +| 500 | `failed` | `durability_failed` | The durability verification fails. | | |
| 166 | +| 500 | `failed` | `durability_timeout` | The durability verification exceeds its operation deadline. | | |
| 167 | +| 500 | `failed` | `runtime_stop_failed` | The runtime stop reports a failure. | | |
| 168 | + | |
| 169 | +The runtime stop has no overall timeout. A stop that does not return keeps | |
| 170 | +the eviction request pending. | |
| 171 | + | |
| 172 | +An error does not prove that the runtime remains resident. A malformed scope | |
| 173 | +still returns status 400 through the existing scope validation. | |
| 174 | + | |
| 111 | 175 | ## Set the forwarded-header policy |
| 112 | 176 | |
| 113 | 177 | celld ignores `X-Forwarded-Host` and `X-Forwarded-Proto` by default. Set |
addeddocs/services/containers-flow.svg+97−0View file
| @@ -1,0 +1,97 @@ | ||
| 1 | +<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 440 478" role="img" aria-labelledby="containerFlowTitle containerFlowDesc"> | |
| 2 | + <title id="containerFlowTitle">One node runs the cell and its container, behind a fence on the bridge</title> | |
| 3 | + <desc id="containerFlowDesc">A Worker on any node calls MY_CONTAINER.get(id), and celld routes the call to the node that owns the cell. The fleet bucket holds the image as deploy slash images slash key dot tar, and the node loads it into its container engine once. On that one owner node, two runtimes run side by side: a V8 isolate that holds the cell, the Durable Object, with ctx.container and getTcpPort(8080), and a container process with the image from the bucket, port 8080, and an ephemeral disk. The call crosses the node's container engine socket, which is a local socket and not the network. Below both runtimes, an nftables fence on the node's bridge allows a connection out to the Internet and blocks a connection to any node and to every private range. A move, a restart, or a reset destroys the container, and the new owner starts a fresh one, so the disk never survives.</desc> | |
| 4 | + <style> | |
| 5 | + svg { font-family: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Helvetica, Arial, sans-serif; } | |
| 6 | + text { font-size: 13px; fill: currentColor; } | |
| 7 | + tspan { fill: currentColor; } | |
| 8 | + .mono { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; font-size: 12px; } | |
| 9 | + .lead { font-weight: 600; } | |
| 10 | + .d-ink { color: #121212; } | |
| 11 | + .d-soft { color: #3d3b37; } | |
| 12 | + .d-faint { color: #6e6a62; } | |
| 13 | + .d-acc { color: #10803f; } | |
| 14 | + .d-panel { color: #ffffff; } | |
| 15 | + .d-sunk { color: #f0eee8; } | |
| 16 | + .d-tint { color: #d6efdf; } | |
| 17 | + @media (prefers-color-scheme: dark) { | |
| 18 | + .d-ink { color: #efede7; } | |
| 19 | + .d-soft { color: #c9c6be; } | |
| 20 | + .d-faint { color: #928e85; } | |
| 21 | + .d-acc { color: #3fc472; } | |
| 22 | + .d-panel { color: #1a1a19; } | |
| 23 | + .d-sunk { color: #232321; } | |
| 24 | + .d-tint { color: #10301d; } | |
| 25 | + } | |
| 26 | + </style> | |
| 27 | + <defs> | |
| 28 | + <marker id="ct-arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="6" | |
| 29 | + markerHeight="6" orient="auto-start-reverse"> | |
| 30 | + <path class="d-soft" fill="currentColor" d="M0 0 L10 5 L0 10 z" /> | |
| 31 | + </marker> | |
| 32 | + </defs> | |
| 33 | + | |
| 34 | + <!-- The caller, and the image the node needs before it can answer the caller. --> | |
| 35 | + <rect class="d-panel" fill="currentColor" x="8" y="8" width="196" height="54" rx="8" /> | |
| 36 | + <rect class="d-faint" fill="none" stroke="currentColor" x="8" y="8" width="196" height="54" rx="8" /> | |
| 37 | + <text class="d-faint" fill="currentColor" x="20" y="30">Worker, on any node</text> | |
| 38 | + <text class="d-ink mono" fill="currentColor" x="20" y="50">MY_CONTAINER.get(id)</text> | |
| 39 | + | |
| 40 | + <rect class="d-panel" fill="currentColor" x="236" y="8" width="196" height="54" rx="8" /> | |
| 41 | + <rect class="d-faint" fill="none" stroke="currentColor" x="236" y="8" width="196" height="54" rx="8" /> | |
| 42 | + <text class="d-faint" fill="currentColor" x="248" y="30">Fleet bucket, no registry</text> | |
| 43 | + <text class="d-ink mono" fill="currentColor" x="248" y="50">deploy/images/<key>.tar</text> | |
| 44 | + | |
| 45 | + <g class="d-soft" fill="none" stroke="currentColor" stroke-width="1.5"> | |
| 46 | + <path d="M106 62 V108" marker-end="url(#ct-arrow)" /> | |
| 47 | + <path d="M334 62 V108" marker-end="url(#ct-arrow)" /> | |
| 48 | + </g> | |
| 49 | + <text class="d-faint" fill="currentColor" x="116" y="80">routed to the owner</text> | |
| 50 | + <text class="d-faint" fill="currentColor" x="324" y="100" text-anchor="end">loaded once per node</text> | |
| 51 | + | |
| 52 | + <!-- One node holds the cell and the container together. --> | |
| 53 | + <rect class="d-sunk" fill="currentColor" x="8" y="112" width="424" height="284" rx="12" /> | |
| 54 | + <rect class="d-faint" fill="none" stroke="currentColor" x="8" y="112" width="424" height="284" rx="12" /> | |
| 55 | + <text class="d-ink lead" fill="currentColor" x="24" y="138">Owner node</text> | |
| 56 | + <text class="d-faint" fill="currentColor" x="24" y="158">the cell and its container never separate</text> | |
| 57 | + | |
| 58 | + <text class="d-acc" fill="currentColor" x="220" y="176" text-anchor="middle">container engine socket</text> | |
| 59 | + | |
| 60 | + <rect class="d-panel" fill="currentColor" x="22" y="184" width="176" height="112" rx="8" /> | |
| 61 | + <rect class="d-faint" fill="none" stroke="currentColor" x="22" y="184" width="176" height="112" rx="8" /> | |
| 62 | + <text class="d-faint" fill="currentColor" x="34" y="206">V8 isolate</text> | |
| 63 | + <text class="d-ink" fill="currentColor" x="34" y="228">cell, a Durable Object</text> | |
| 64 | + <text class="d-acc mono" fill="currentColor" x="34" y="252">ctx.container</text> | |
| 65 | + <text class="d-soft mono" fill="currentColor" x="34" y="276">getTcpPort(8080)</text> | |
| 66 | + | |
| 67 | + <rect class="d-tint" fill="currentColor" x="242" y="184" width="176" height="112" rx="8" /> | |
| 68 | + <rect class="d-acc" fill="none" stroke="currentColor" stroke-width="2" x="242" y="184" width="176" height="112" rx="8" /> | |
| 69 | + <text class="d-faint" fill="currentColor" x="254" y="206">container process</text> | |
| 70 | + <text class="d-ink" fill="currentColor" x="254" y="228">the bucket's image</text> | |
| 71 | + <text class="d-soft mono" fill="currentColor" x="254" y="252">EXPOSE 8080</text> | |
| 72 | + <text class="d-soft" fill="currentColor" x="254" y="276">ephemeral disk</text> | |
| 73 | + | |
| 74 | + <path class="d-faint" fill="none" stroke="currentColor" stroke-dasharray="5 4" | |
| 75 | + d="M220 184 V296" /> | |
| 76 | + <g class="d-soft" fill="none" stroke="currentColor" stroke-width="1.5"> | |
| 77 | + <path d="M198 222 H238" marker-end="url(#ct-arrow)" /> | |
| 78 | + <path d="M242 270 H202" marker-end="url(#ct-arrow)" /> | |
| 79 | + </g> | |
| 80 | + | |
| 81 | + <!-- The fence is on the node, outside every container and every runtime. --> | |
| 82 | + <rect class="d-acc" fill="none" stroke="currentColor" stroke-dasharray="5 4" | |
| 83 | + x="22" y="310" width="396" height="70" rx="8" /> | |
| 84 | + <text class="d-acc" fill="currentColor" x="34" y="332">nftables fence on the node's bridge</text> | |
| 85 | + <text class="d-soft" fill="currentColor" x="34" y="352">out to the Internet: allowed</text> | |
| 86 | + <text class="d-soft" fill="currentColor" x="34" y="372">to any node, to a private range: blocked</text> | |
| 87 | + | |
| 88 | + <g class="d-soft" fill="none" stroke="currentColor" stroke-width="1.5"> | |
| 89 | + <path d="M220 396 V412" marker-end="url(#ct-arrow)" /> | |
| 90 | + </g> | |
| 91 | + | |
| 92 | + <!-- The container belongs to one ownership epoch on one node. --> | |
| 93 | + <rect class="d-panel" fill="currentColor" x="8" y="418" width="424" height="56" rx="8" /> | |
| 94 | + <rect class="d-faint" fill="none" stroke="currentColor" x="8" y="418" width="424" height="56" rx="8" /> | |
| 95 | + <text class="d-ink" fill="currentColor" x="24" y="442">A move, a restart, or a reset destroys the container.</text> | |
| 96 | + <text class="d-faint" fill="currentColor" x="24" y="463">The new owner starts a fresh one; the disk never survives.</text> | |
| 97 | +</svg> |
addeddocs/services/containers.md+215−0View file
| @@ -1,0 +1,215 @@ | ||
| 1 | +# Containers | |
| 2 | + | |
| 3 | +A container runs a program that is not JavaScript beside the Worker that needs | |
| 4 | +it. A Durable Object supervises that program, so the object starts the | |
| 5 | +container, reaches it over a TCP port, and stops it. An application uses a | |
| 6 | +container for a language or a dependency that the Workers runtime does not | |
| 7 | +have, for a heavy computation, or for code that a customer supplies. The | |
| 8 | +container disk is ephemeral, therefore durable state belongs in the object's | |
| 9 | +storage or in another binding. Containers are experimental in celld, so the | |
| 10 | +configuration keys, the `ctx.container` surface, the node-side defaults, and the | |
| 11 | +security boundary can change without notice. Read the | |
| 12 | +[Cloudflare Containers documentation](https://developers.cloudflare.com/containers/) | |
| 13 | +for the standard API behavior. | |
| 14 | + | |
| 15 | +## Example | |
| 16 | + | |
| 17 | +The [Containers example](../../examples/container) starts a Python HTTP server | |
| 18 | +and reaches it through a container port. | |
| 19 | + | |
| 20 | +<!-- celld-example: container --> | |
| 21 | + | |
| 22 | +## The object and its container | |
| 23 | + | |
| 24 | +A `containers` entry names a Durable Object class, and each object of that class | |
| 25 | +controls at most one container. The class must be SQLite-backed, and it must | |
| 26 | +belong to the same script. celld gives such an object a `ctx.container` handle, | |
| 27 | +and an object of any other class has none. A Worker therefore addresses a | |
| 28 | +container the way it addresses an object, with a name or an id. | |
| 29 | + | |
| 30 | +celld implements `running`, `start()`, `monitor()`, `destroy()`, `signal()`, | |
| 31 | +`getTcpPort()`, `exec()`, and `setInactivityTimeout()`. `start()` accepts | |
| 32 | +`entrypoint`, `env`, `enableInternet`, and `labels`. It checks `hardTimeout` | |
| 33 | +and then ignores it, so a value of 0 or less throws and a valid value changes | |
| 34 | +nothing. `inspect()`, the snapshot methods, and the outbound interception | |
| 35 | +methods reject with an error. Read the | |
| 36 | +[`ctx.container` reference](https://developers.cloudflare.com/durable-objects/api/container/) | |
| 37 | +for the standard method list. | |
| 38 | + | |
| 39 | +A request reaches the container through a port, and not through a public | |
| 40 | +address. `getTcpPort(port).fetch()` opens a connection from the node to the | |
| 41 | +container and speaks HTTP on it. On Linux, the node uses the container's bridge | |
| 42 | +address, so every port works. On macOS, the node uses a published loopback port, | |
| 43 | +so the image must declare the port with `EXPOSE`, as `wrangler dev` requires. A | |
| 44 | +fetch with an `Upgrade: websocket` header gives a 101 response with a | |
| 45 | +`webSocket`, as on Cloudflare. `getTcpPort(port).connect()` gives a raw socket | |
| 46 | +with the lifetime of the event that opened it. See | |
| 47 | +[TCP sockets](../cloudflare-compat.md#tcp-sockets). | |
| 48 | + | |
| 49 | +A `monitor()` promise and an `exec()` process have that same event lifetime. | |
| 50 | +They settle only inside the event that created them, and after the handler | |
| 51 | +answers they do not keep the object active, so a drain can move the object. | |
| 52 | +`running` always reports the engine's state, therefore an object that lost its | |
| 53 | +`monitor()` sees the exit at its next event. A `start()` that fails is logged by | |
| 54 | +the node as `container_start_failed`. | |
| 55 | + | |
| 56 | +`@cloudflare/containers` runs as published, and the example above uses it. Its | |
| 57 | +`sleepAfter` alarm stops the container, and `getContainer()`, `getRandom()`, and | |
| 58 | +`switchPort()` work. Read the | |
| 59 | +[Container class reference](https://developers.cloudflare.com/containers/reference/container-class/) | |
| 60 | +for the hooks and the defaults. `@cloudflare/sandbox` also runs as published, on | |
| 61 | +the `cloudflare/sandbox` image. Its `exec()` API, files, processes, sessions, | |
| 62 | +and code interpreter run inside the container, over the HTTP transport and over | |
| 63 | +the RPC transport. Preview URLs need a wildcard hostname at the operator's load | |
| 64 | +balancer, tunnels run cloudflared inside the container, and bucket mounts use | |
| 65 | +the credentials that the application passes. See the | |
| 66 | +[sandbox example](../../examples/sandbox). | |
| 67 | + | |
| 68 | +## The image and the node | |
| 69 | + | |
| 70 | +Cloudflare pushes an image to its own registry, distributes it across its | |
| 71 | +network, and starts the container in a virtual machine at | |
| 72 | +[the nearest location that already holds the image](https://developers.cloudflare.com/containers/concepts/architecture/). | |
| 73 | +An object and its container can therefore run in different places. celld has no | |
| 74 | +registry and no global network, so it builds the same two steps out of the fleet | |
| 75 | +bucket and the node's own container engine. | |
| 76 | + | |
| 77 | +`celld deploy` builds a Dockerfile in the project, or it pulls an image | |
| 78 | +reference, with the `docker` CLI on `PATH` or with the CLI that `CELLD_DOCKER` | |
| 79 | +names. A Podman CLI works. `celld deploy` then saves the image to the fleet | |
| 80 | +bucket at `deploy/images/<key>.tar`, where the key hashes the image layers and | |
| 81 | +the image config. A node loads the image into its own engine the first time a | |
| 82 | +cell of the class starts, so a node never contacts a registry, and a redeploy of | |
| 83 | +an unchanged image uploads nothing. The `celld-fence` image that a node needs | |
| 84 | +rides with every deployment that has a container. | |
| 85 | + | |
| 86 | +`celld deploy` builds and pulls for `linux/amd64`, as Wrangler does, so a deploy | |
| 87 | +from an ARM machine runs on x86-64 nodes. `CELLD_CONTAINER_PLATFORM` selects | |
| 88 | +another platform. `celld dev` builds for the local machine and keeps the image | |
| 89 | +in the local engine. | |
| 90 | + | |
| 91 | +The container runs on the node that owns the cell, and the two never separate. | |
| 92 | +Each node that serves a container class therefore needs a Docker daemon or a | |
| 93 | +Podman daemon. celld uses the Unix socket that `DOCKER_HOST` names, or the | |
| 94 | +default socket of Docker, Docker Desktop, OrbStack, or Podman. A `DOCKER_HOST` | |
| 95 | +value that is not a `unix://` URL gives celld no socket at all. A node without | |
| 96 | +an engine cannot activate a cell of a container class, and it serves every other | |
| 97 | +class. | |
| 98 | + | |
| 99 | + | |
| 100 | + | |
| 101 | +## The isolation boundary | |
| 102 | + | |
| 103 | +Cloudflare runs each container in its own virtual machine, so Cloudflare | |
| 104 | +publishes no capability policy. Under the default runtime a celld container | |
| 105 | +shares the node's kernel, so celld sets a policy of its own. celld drops all | |
| 106 | +Linux capabilities, sets `no-new-privileges`, keeps the daemon's default seccomp | |
| 107 | +profile, limits the container to 1024 processes, and runs an init as PID 1 that | |
| 108 | +reaps an orphaned process. Two containers on one node cannot open connections to | |
| 109 | +each other. | |
| 110 | + | |
| 111 | +The node fences its container bridges before the first container starts. The | |
| 112 | +rules are nftables rules on the node, outside every container and every runtime, | |
| 113 | +and celld installs them through the daemon with a one-shot privileged container | |
| 114 | +of the `celld-fence` image. A container with `enableInternet: true` reaches the | |
| 115 | +Internet and nothing of the node's own. It cannot open a connection to the node, | |
| 116 | +to another node, to the private ranges `10/8`, `172.16/12`, `192.168/16`, and | |
| 117 | +`100.64/10`, or to the link-local range, so the node's internal listener and a | |
| 118 | +cloud metadata service are both out of reach. A node that cannot install the | |
| 119 | +rules starts no container, and a deployment from a celld without the fence image | |
| 120 | +starts no container on a node that has the fence. | |
| 121 | + | |
| 122 | +`enableInternet: false` attaches the container to an internal bridge with no | |
| 123 | +route out. On macOS, the node reaches a container only through a published port, | |
| 124 | +and an internal network publishes none, so `celld dev` on macOS keeps egress on | |
| 125 | +and logs a warning. The fence still applies. | |
| 126 | + | |
| 127 | +`CELLD_CONTAINER_RUNTIME` names the OCI runtime for every container on the node, | |
| 128 | +for example `runsc` for gVisor or `kata` for a virtual machine. A `containers` | |
| 129 | +entry can also name a `runtime` of its own, which overrides the node setting for | |
| 130 | +that class. celld adds this key, and the Cloudflare configuration has no | |
| 131 | +equivalent. The daemon must have the named runtime, or every `start()` of such a | |
| 132 | +container fails with the daemon's error, so a class runs only where its | |
| 133 | +isolation exists. Under the default runtime, a container is a kernel namespace | |
| 134 | +boundary and not a virtual machine. For code that you did not write, name a | |
| 135 | +runtime that gives each container its own kernel, and keep the secrets in the | |
| 136 | +Worker. | |
| 137 | + | |
| 138 | +A container that runs under a named runtime gets a written `/etc/resolv.conf` | |
| 139 | +with public resolvers, `1.1.1.1` and `1.0.0.1` by default, or the | |
| 140 | +`CELLD_CONTAINER_DNS` resolvers when the operator sets them. gVisor cannot reach | |
| 141 | +the container engine's built-in resolver, so a container under gVisor resolves | |
| 142 | +no hostname otherwise, and the fence permits the public resolver. A container on | |
| 143 | +the node's default runtime keeps the engine's resolver, unless the operator sets | |
| 144 | +`CELLD_CONTAINER_DNS`. | |
| 145 | + | |
| 146 | +## Sleep, wake, and the node's resources | |
| 147 | + | |
| 148 | +Cloudflare stops an idle container after 10 minutes, and `sleepAfter` changes | |
| 149 | +that window. celld keeps the same default and the same mechanism. | |
| 150 | +`setInactivityTimeout()` sets the window for the engine, and celld uses 10 | |
| 151 | +minutes without one. An idle eviction of the cell keeps the container running | |
| 152 | +for that window, and the next activation of the cell on the same node reconnects | |
| 153 | +to it. A move to another node, a node restart, and a reset destroy the container | |
| 154 | +instead, so the container disk is ephemeral, as on Cloudflare. A node stop | |
| 155 | +destroys every container of the node, and Ctrl-C on `celld dev` does the same | |
| 156 | +while it keeps the local state. | |
| 157 | + | |
| 158 | +`instance_type` sets the CPU limit and the memory limit of the Cloudflare | |
| 159 | +instance type with that name. celld accepts `lite` and its older name `dev`, | |
| 160 | +`basic`, `standard-1` and its alias `standard`, `standard-2`, `standard-3`, and | |
| 161 | +`standard-4`, with the values that | |
| 162 | +[the Cloudflare limits page](https://developers.cloudflare.com/containers/platform/limits/) | |
| 163 | +gives. An entry without an `instance_type` gets `dev`, a sixteenth of a CPU and | |
| 164 | +256 MiB, as on Cloudflare. A sixteenth of a CPU is a slow start for an | |
| 165 | +interpreter, so name a larger type when the image boots a runtime. celld does | |
| 166 | +not enforce the disk size of the type. | |
| 167 | + | |
| 168 | +A container runs in its own cgroup, so the node process does not carry the | |
| 169 | +container's memory in its own charge. The node therefore counts the instance | |
| 170 | +type's memory cap of every running container as committed memory. A | |
| 171 | +container-heavy node reports no headroom and sheds cells, which keeps the node | |
| 172 | +away from the kernel out-of-memory killer. An operator must set the node memory | |
| 173 | +ceiling at or above the largest instance type in use, plus headroom. | |
| 174 | + | |
| 175 | +`max_instances` caps the containers that one class runs across the fleet. | |
| 176 | +Cloudflare holds that cap centrally. celld has no coordinator, so each node | |
| 177 | +publishes its running container count per class in the shared capacity sample. A | |
| 178 | +node that is about to start a container sums that count across the fleet and | |
| 179 | +adds its own live count. A start over the cap fails, and the node logs | |
| 180 | +`container_start_failed` with the limit. The sample can lag one refresh, | |
| 181 | +therefore two nodes that start the same class at once can exceed the cap for a | |
| 182 | +moment and converge at the next refresh. `celld dev` reads no sample, so it | |
| 183 | +enforces no fleet cap. | |
| 184 | + | |
| 185 | +## Differences from Cloudflare | |
| 186 | + | |
| 187 | +- A `containers` entry accepts `class_name`, `image`, `name`, `instance_type`, | |
| 188 | + `max_instances`, and `runtime`. Each other key stops the deployment. celld | |
| 189 | + adds `runtime`, and it accepts `name` without using it. | |
| 190 | +- celld places a container on the node that owns the cell. Cloudflare can place | |
| 191 | + a container away from its object. | |
| 192 | +- A node that serves a container class needs a Docker daemon or a Podman daemon. | |
| 193 | +- celld does not enforce the disk size of an instance type. | |
| 194 | +- `max_instances` converges across the fleet instead of holding centrally, so | |
| 195 | + the fleet can exceed the cap for one refresh. `celld dev` enforces no cap. | |
| 196 | +- `inspect()`, `snapshotDirectory()`, `snapshotContainer()`, and the outbound | |
| 197 | + interception methods reject with an error. `start()` checks `hardTimeout` and | |
| 198 | + then ignores it, so a value of 0 or less throws and a valid value has no | |
| 199 | + effect. | |
| 200 | +- `getTcpPort(port).connect()` gives a socket with the lifetime of the event | |
| 201 | + that opened it. See [TCP sockets](../cloudflare-compat.md#tcp-sockets). | |
| 202 | +- A `monitor()` promise and an `exec()` process do not keep the object active | |
| 203 | + after the handler answers. | |
| 204 | +- On macOS, the node reaches a container through a published port, so the image | |
| 205 | + must declare the port with `EXPOSE`. `enableInternet: false` has no effect on | |
| 206 | + macOS. | |
| 207 | +- The container bridges carry no IPv6 address, and the fence rejects the IPv6 | |
| 208 | + link-local and unique-local ranges as well. | |
| 209 | +- A move of an object to another node stops its container, so the first | |
| 210 | + `@cloudflare/sandbox` call after the move can fail with the SDK's | |
| 211 | + `OperationInterruptedError`, as after a container restart on Cloudflare. The | |
| 212 | + next call starts a fresh container. | |
| 213 | + | |
| 214 | +The [Cloudflare compatibility](../cloudflare-compat.md#services) page lists | |
| 215 | +the runtime APIs and the unsupported services. |
addeddocs/services/cron-triggers-flow.svg+148−0View file
| @@ -1,0 +1,148 @@ | ||
| 1 | +<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 440 676" role="img" aria-labelledby="cronFlowTitle cronFlowDesc"> | |
| 2 | + <title id="cronFlowTitle">Every node arms one reserved cron cell, its single alarm row carries the earliest occurrence, a shared deadline runs one invocation for each matching expression, and the re-arm takes the earlier of the next occurrence and the failure backoff</title> | |
| 3 | + <desc id="cronFlowDesc">The first panel shows three nodes of one fleet. Each node calls the same | |
| 4 | +reserved cell, named .cron:cron from the class and the script name, once after | |
| 5 | +its deployment loads. The ownership record in the fleet bucket accepts one | |
| 6 | +caller, and the other nodes route to that owner, so celld needs no election and | |
| 7 | +no reserved cron node. The second panel shows three cron expressions of one | |
| 8 | +script at 12:35 UTC. Two of them come due at 13:00 and one comes due on the | |
| 9 | +next Monday at 09:00, and the one alarm row of the cell arms for 13:00, the | |
| 10 | +earliest occurrence across the whole list. The third panel shows the 13:00 | |
| 11 | +deadline firing. Both expressions that match that minute get their own call of | |
| 12 | +scheduled(controller, env, ctx), each with its own controller.cron, and the two | |
| 13 | +calls run one after another inside the cell because a cell runs one event at a | |
| 14 | +time. controller.scheduledTime is 13:00 for both calls and never the instant | |
| 15 | +the attempt started. The fourth panel shows the re-arm after a failed 13:00 | |
| 16 | +run. For the expression */30 * * * * the retry backoff of 4 seconds is earlier | |
| 17 | +than the next occurrence at 13:30, so the retry is armed. For the expression | |
| 18 | +* * * * * the next occurrence at 13:01 is earlier than a grown backoff of 128 | |
| 19 | +seconds, so the occurrence is armed and the retry is dropped. A backoff | |
| 20 | +therefore never delays or skips a scheduled occurrence.</desc> | |
| 21 | + <style> | |
| 22 | + svg { font-family: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Helvetica, Arial, sans-serif; } | |
| 23 | + text { font-size: 13px; fill: currentColor; } | |
| 24 | + tspan { fill: currentColor; } | |
| 25 | + .mono { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; font-size: 12px; } | |
| 26 | + .lead { font-weight: 600; } | |
| 27 | + .sm { font-size: 12px; } | |
| 28 | + .d-ink { color: #121212; } | |
| 29 | + .d-soft { color: #3d3b37; } | |
| 30 | + .d-faint { color: #6e6a62; } | |
| 31 | + .d-acc { color: #10803f; } | |
| 32 | + .d-panel { color: #ffffff; } | |
| 33 | + .d-sunk { color: #f0eee8; } | |
| 34 | + .d-tint { color: #d6efdf; } | |
| 35 | + @media (prefers-color-scheme: dark) { | |
| 36 | + .d-ink { color: #efede7; } | |
| 37 | + .d-soft { color: #c9c6be; } | |
| 38 | + .d-faint { color: #928e85; } | |
| 39 | + .d-acc { color: #3fc472; } | |
| 40 | + .d-panel { color: #1a1a19; } | |
| 41 | + .d-sunk { color: #232321; } | |
| 42 | + .d-tint { color: #10301d; } | |
| 43 | + } | |
| 44 | + </style> | |
| 45 | + <defs> | |
| 46 | + <marker id="cron-arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="6" | |
| 47 | + markerHeight="6" orient="auto-start-reverse"> | |
| 48 | + <path class="d-soft" fill="currentColor" d="M0 0 L10 5 L0 10 z" /> | |
| 49 | + </marker> | |
| 50 | + </defs> | |
| 51 | + | |
| 52 | + <!-- Panel one: the fan-in. Every node arms, and one ownership CAS decides. --> | |
| 53 | + <rect class="d-sunk" fill="currentColor" x="8" y="8" width="424" height="186" rx="10" /> | |
| 54 | + <rect class="d-faint" fill="none" stroke="currentColor" x="8" y="8" width="424" height="186" rx="10" /> | |
| 55 | + <text class="d-ink lead" fill="currentColor" x="22" y="32">Every node arms the same reserved cell</text> | |
| 56 | + <text class="d-faint sm" fill="currentColor" x="22" y="50">no election, and no reserved cron node</text> | |
| 57 | + | |
| 58 | + <g> | |
| 59 | + <rect class="d-panel" fill="currentColor" x="22" y="64" width="122" height="38" rx="8" /> | |
| 60 | + <rect class="d-soft" fill="none" stroke="currentColor" x="22" y="64" width="122" height="38" rx="8" /> | |
| 61 | + <text class="d-ink" fill="currentColor" x="83" y="88" text-anchor="middle">node A</text> | |
| 62 | + <rect class="d-panel" fill="currentColor" x="159" y="64" width="122" height="38" rx="8" /> | |
| 63 | + <rect class="d-soft" fill="none" stroke="currentColor" x="159" y="64" width="122" height="38" rx="8" /> | |
| 64 | + <text class="d-ink" fill="currentColor" x="220" y="88" text-anchor="middle">node B</text> | |
| 65 | + <rect class="d-panel" fill="currentColor" x="296" y="64" width="122" height="38" rx="8" /> | |
| 66 | + <rect class="d-soft" fill="none" stroke="currentColor" x="296" y="64" width="122" height="38" rx="8" /> | |
| 67 | + <text class="d-ink" fill="currentColor" x="357" y="88" text-anchor="middle">node C</text> | |
| 68 | + </g> | |
| 69 | + | |
| 70 | + <g class="d-soft" fill="none" stroke="currentColor" stroke-width="1.5"> | |
| 71 | + <path d="M83 102 V122 H220" /> | |
| 72 | + <path d="M357 102 V122 H220" /> | |
| 73 | + <path d="M220 102 V136" marker-end="url(#cron-arrow)" /> | |
| 74 | + </g> | |
| 75 | + <text class="d-faint sm" fill="currentColor" x="228" y="118">arm</text> | |
| 76 | + | |
| 77 | + <rect class="d-tint" fill="currentColor" x="110" y="140" width="220" height="46" rx="8" /> | |
| 78 | + <rect class="d-acc" fill="none" stroke="currentColor" stroke-width="2" x="110" y="140" width="220" height="46" rx="8" /> | |
| 79 | + <text class="d-ink mono" fill="currentColor" x="220" y="162" text-anchor="middle">.cron:cron</text> | |
| 80 | + <text class="d-soft sm" fill="currentColor" x="220" y="179" text-anchor="middle">one owner, by ownership CAS</text> | |
| 81 | + | |
| 82 | + <!-- Panel two: many expressions, one alarm row, the earliest deadline. --> | |
| 83 | + <text class="d-ink lead" fill="currentColor" x="22" y="226">One alarm row holds one deadline</text> | |
| 84 | + <text class="d-faint sm mono" fill="currentColor" x="22" y="244">now 12:35 UTC</text> | |
| 85 | + | |
| 86 | + <text class="d-soft mono" fill="currentColor" x="26" y="272">*/30 * * * *</text> | |
| 87 | + <text class="d-ink mono" fill="currentColor" x="150" y="272">13:00</text> | |
| 88 | + <text class="d-soft mono" fill="currentColor" x="26" y="292">0 * * * *</text> | |
| 89 | + <text class="d-ink mono" fill="currentColor" x="150" y="292">13:00</text> | |
| 90 | + <text class="d-soft mono" fill="currentColor" x="26" y="312">0 9 * * MON</text> | |
| 91 | + <text class="d-faint mono" fill="currentColor" x="150" y="312">Mon 09:00</text> | |
| 92 | + | |
| 93 | + <path class="d-acc" fill="none" stroke="currentColor" stroke-width="2" | |
| 94 | + d="M214 260 H222 V298 H214" /> | |
| 95 | + <path class="d-soft" fill="none" stroke="currentColor" stroke-width="1.5" | |
| 96 | + d="M224 279 H244" marker-end="url(#cron-arrow)" /> | |
| 97 | + | |
| 98 | + <rect class="d-panel" fill="currentColor" x="252" y="253" width="178" height="52" rx="8" /> | |
| 99 | + <rect class="d-acc" fill="none" stroke="currentColor" stroke-width="2" x="252" y="253" width="178" height="52" rx="8" /> | |
| 100 | + <text class="d-ink" fill="currentColor" x="341" y="276" text-anchor="middle">armed for 13:00</text> | |
| 101 | + <text class="d-soft sm" fill="currentColor" x="341" y="294" text-anchor="middle">the earliest of the three</text> | |
| 102 | + | |
| 103 | + <!-- Panel three: the fan-out. One deadline, one call per matching expression. --> | |
| 104 | + <text class="d-ink lead" fill="currentColor" x="22" y="350">A deadline that two expressions share runs twice</text> | |
| 105 | + | |
| 106 | + <rect class="d-tint" fill="currentColor" x="22" y="364" width="142" height="52" rx="8" /> | |
| 107 | + <rect class="d-acc" fill="none" stroke="currentColor" stroke-width="2" x="22" y="364" width="142" height="52" rx="8" /> | |
| 108 | + <text class="d-ink" fill="currentColor" x="93" y="388" text-anchor="middle">the alarm fires</text> | |
| 109 | + <text class="d-soft sm mono" fill="currentColor" x="93" y="406" text-anchor="middle">13:00 UTC</text> | |
| 110 | + | |
| 111 | + <g class="d-soft" fill="none" stroke="currentColor" stroke-width="1.5"> | |
| 112 | + <path d="M164 390 H182 V380 H194" marker-end="url(#cron-arrow)" /> | |
| 113 | + <path d="M164 390 H182 V436 H194" marker-end="url(#cron-arrow)" /> | |
| 114 | + </g> | |
| 115 | + | |
| 116 | + <rect class="d-panel" fill="currentColor" x="200" y="356" width="232" height="48" rx="8" /> | |
| 117 | + <rect class="d-soft" fill="none" stroke="currentColor" x="200" y="356" width="232" height="48" rx="8" /> | |
| 118 | + <text class="d-ink mono" fill="currentColor" x="316" y="378" text-anchor="middle">scheduled(controller, env, ctx)</text> | |
| 119 | + <text class="d-acc sm mono" fill="currentColor" x="316" y="396" text-anchor="middle">cron: "*/30 * * * *"</text> | |
| 120 | + | |
| 121 | + <rect class="d-panel" fill="currentColor" x="200" y="412" width="232" height="48" rx="8" /> | |
| 122 | + <rect class="d-soft" fill="none" stroke="currentColor" x="200" y="412" width="232" height="48" rx="8" /> | |
| 123 | + <text class="d-ink mono" fill="currentColor" x="316" y="434" text-anchor="middle">scheduled(controller, env, ctx)</text> | |
| 124 | + <text class="d-acc sm mono" fill="currentColor" x="316" y="452" text-anchor="middle">cron: "0 * * * *"</text> | |
| 125 | + | |
| 126 | + <text class="d-soft sm" fill="currentColor" x="22" y="436">one after the other,</text> | |
| 127 | + <text class="d-soft sm" fill="currentColor" x="22" y="452">inside the one cell</text> | |
| 128 | + <text class="d-faint sm" fill="currentColor" x="22" y="486">scheduledTime is the occurrence 13:00 for both calls, never the</text> | |
| 129 | + <text class="d-faint sm" fill="currentColor" x="22" y="502">instant an attempt started</text> | |
| 130 | + | |
| 131 | + <!-- Panel four: the re-arm race, where the answer flips with the interval. --> | |
| 132 | + <text class="d-ink lead" fill="currentColor" x="22" y="536">The re-arm takes whichever deadline is earlier</text> | |
| 133 | + <text class="d-faint sm" fill="currentColor" x="22" y="554">both lines start at a failed 13:00 run</text> | |
| 134 | + | |
| 135 | + <text class="d-soft mono" fill="currentColor" x="22" y="586">*/30 * * * *</text> | |
| 136 | + <path class="d-faint" fill="none" stroke="currentColor" stroke-width="1.5" d="M120 582 H424" /> | |
| 137 | + <path class="d-faint" fill="none" stroke="currentColor" d="M170 574 V590 M390 574 V590" /> | |
| 138 | + <circle class="d-acc" fill="currentColor" cx="170" cy="582" r="5" /> | |
| 139 | + <text class="d-acc sm" fill="currentColor" x="170" y="606" text-anchor="middle">retry +4 s</text> | |
| 140 | + <text class="d-faint sm" fill="currentColor" x="424" y="606" text-anchor="end">next 13:30</text> | |
| 141 | + | |
| 142 | + <text class="d-soft mono" fill="currentColor" x="22" y="638">* * * * *</text> | |
| 143 | + <path class="d-faint" fill="none" stroke="currentColor" stroke-width="1.5" d="M120 634 H424" /> | |
| 144 | + <path class="d-faint" fill="none" stroke="currentColor" d="M210 626 V642 M330 626 V642" /> | |
| 145 | + <circle class="d-acc" fill="currentColor" cx="210" cy="634" r="5" /> | |
| 146 | + <text class="d-acc sm" fill="currentColor" x="210" y="658" text-anchor="middle">next 13:01</text> | |
| 147 | + <text class="d-faint sm" fill="currentColor" x="424" y="658" text-anchor="end">retry +128 s</text> | |
| 148 | +</svg> |
addeddocs/services/cron-triggers.md+140−0View file
| @@ -1,0 +1,140 @@ | ||
| 1 | +# Cron Triggers | |
| 2 | + | |
| 3 | +A Cron Trigger runs a Worker on a schedule instead of on a request. An | |
| 4 | +application uses one for periodic work, such as a cleanup, a report, or a poll | |
| 5 | +of an upstream service. celld keeps the schedule of a script in one reserved | |
| 6 | +cell, so a fleet of many nodes runs each occurrence once. Read the | |
| 7 | +[Cloudflare Cron Triggers documentation](https://developers.cloudflare.com/workers/configuration/cron-triggers/) | |
| 8 | +for the standard API behavior. | |
| 9 | + | |
| 10 | +## Example | |
| 11 | + | |
| 12 | +The [Cron Trigger example](../../examples/cron) logs the scheduled time once a | |
| 13 | +minute. | |
| 14 | + | |
| 15 | +<!-- celld-example: cron --> | |
| 16 | + | |
| 17 | +## Configuring a schedule | |
| 18 | + | |
| 19 | +A project declares its schedules in a `triggers.crons` array, and each entry is | |
| 20 | +one cron expression. `celld deploy` parses every entry, therefore a malformed | |
| 21 | +expression stops the deployment instead of failing at the first occurrence. A | |
| 22 | +configuration that sets `triggers.crons` without `main` also fails, because a | |
| 23 | +Cron Trigger needs a `scheduled` handler to call. | |
| 24 | + | |
| 25 | +celld reads the Cloudflare cron dialect and not the POSIX one. An expression has | |
| 26 | +five fields: minute, hour, day of month, month, and day of week. The resolution | |
| 27 | +is one minute and the zone is UTC. Cloudflare | |
| 28 | +[numbers the weekdays 1 to 7 from Sunday](https://developers.cloudflare.com/workers/configuration/cron-triggers/), | |
| 29 | +so `1-5` means Sunday to Thursday here and not Monday to Friday. | |
| 30 | + | |
| 31 | +Each field takes `*`, a single value, an `a-b` range, an `a,b` list, and a `/n` | |
| 32 | +step on any of those. The month field and the day-of-week field also take the | |
| 33 | +three-letter names in any case, such as `JAN` and `MON`. celld supports the | |
| 34 | +non-standard day forms as well: the day-of-month field takes `L`, `L-<n>`, `LW`, | |
| 35 | +`L-<n>W`, and `<d>W`, and the day-of-week field takes `<dow>L` and `<dow>#<n>`. | |
| 36 | + | |
| 37 | +The two day fields form a union and not an intersection when both of them carry | |
| 38 | +a restriction, which is the ordinary cron rule. `0 0 1 * MON` therefore fires on | |
| 39 | +the first day of each month and on every Monday. Only a literal `*` leaves a day | |
| 40 | +field unrestricted, so `*/2` in the day-of-month field joins that union. | |
| 41 | + | |
| 42 | +celld refuses a small set of expressions that Cloudflare accepts, because the | |
| 43 | +upstream parser answers them in a way that nobody writes on purpose. A | |
| 44 | +descending range such as `SAT-SUN` wraps around the end of the field there and | |
| 45 | +takes one value too many at the low end, so celld stops the deployment instead | |
| 46 | +of shipping a schedule that fires on an unasked day. A `*` inside a list such as | |
| 47 | +`1,*` means the minimum of the field there and not every value, so celld refuses | |
| 48 | +that form and asks for the values. celld also bounds a step by the width of its | |
| 49 | +field, therefore `*/60` fails for the minute field. | |
| 50 | + | |
| 51 | +A script can declare as many expressions as it needs, because celld sets no | |
| 52 | +count limit. A node fires only the schedule of the deployment that it serves, so | |
| 53 | +a `triggers.crons` entry in a service-binding target never runs, and celld logs | |
| 54 | +a warning when it loads such a target. | |
| 55 | + | |
| 56 | +## The node that runs a scheduled event | |
| 57 | + | |
| 58 | +celld gives each deployment that declares `triggers.crons` one reserved cell, | |
| 59 | +named from the class `.cron` and the script name. That cell carries the whole | |
| 60 | +schedule of the script. Exactly one node owns a cell at a time, which is the | |
| 61 | +rule that every [Durable Object](durable-objects.md) already follows, so the | |
| 62 | +reserved cell is what makes an occurrence run once for the fleet and not once | |
| 63 | +for each node. | |
| 64 | + | |
| 65 | +A cron cell has no client that can wake it, so every node calls the cell once | |
| 66 | +after its deployment loads. The ownership record in the fleet bucket accepts one | |
| 67 | +of those callers, and the other nodes route their call to that owner. celld adds | |
| 68 | +no election and reserves no cron node. The call is idempotent, because the same | |
| 69 | +schedule and the same clock give the same deadline, so which node wins does not | |
| 70 | +matter. | |
| 71 | + | |
| 72 | +The cell does nothing between two occurrences, so it hibernates like any other | |
| 73 | +cell and costs no isolate while it waits. A deployment that declares no | |
| 74 | +expression leaves nothing to arm, and the cell then deletes its alarm and | |
| 75 | +retires instead of waking forever. | |
| 76 | + | |
| 77 | +The cell holds one alarm row, therefore one deadline covers every expression of | |
| 78 | +the script. celld arms that row at the earliest next occurrence across the whole | |
| 79 | +list. When the alarm fires, celld finds every expression that matches that | |
| 80 | +minute and calls `scheduled(controller, env, ctx)` once for each one. The | |
| 81 | +invocations run one after another inside the cell, because a cell runs one event | |
| 82 | +at a time. | |
| 83 | + | |
| 84 | +`controller.cron` holds the expression text as the developer wrote it, and | |
| 85 | +`controller.scheduledTime` holds the occurrence in milliseconds. celld reports | |
| 86 | +the occurrence and never the instant the attempt started, so a late run and a | |
| 87 | +retry both name the minute that they were scheduled for. `controller.noRetry()` | |
| 88 | +and `ctx.waitUntil()` behave as the | |
| 89 | +[scheduled handler documentation](https://developers.cloudflare.com/workers/runtime-apis/handlers/scheduled/) | |
| 90 | +describes, and celld drains the `waitUntil()` work of one invocation before it | |
| 91 | +starts the next one. | |
| 92 | + | |
| 93 | + | |
| 94 | + | |
| 95 | +Cloudflare runs a scheduled event on its own global network and selects the | |
| 96 | +location for you. celld makes no such placement promise. The occurrence runs on | |
| 97 | +the node that owns the reserved cell at the deadline, and that owner can change | |
| 98 | +when a node stops, when a node drains, or when idle rebalancing moves the cell. | |
| 99 | + | |
| 100 | +## Failure, retry, and a missed occurrence | |
| 101 | + | |
| 102 | +A `scheduled` handler that throws leaves its expression owed. celld logs the | |
| 103 | +error and arms a backoff of 4 seconds, and each further failure of the same | |
| 104 | +occurrence doubles that delay. celld gives up on the occurrence after six | |
| 105 | +failures. A retry repeats only the expressions that failed, because the | |
| 106 | +expressions that succeeded already ran for that occurrence. | |
| 107 | +`controller.noRetry()` removes an expression from that set, so a handler that | |
| 108 | +knows the work is pointless ends the loop itself. | |
| 109 | + | |
| 110 | +The next occurrence and the backoff compete for the one alarm row, and the | |
| 111 | +earlier deadline wins. A retry therefore never delays a scheduled run and never | |
| 112 | +replaces one. A schedule that fires faster than the backoff never retries at | |
| 113 | +all, which costs little, because the next attempt is already seconds away. celld | |
| 114 | +holds the retry state in memory, so an eviction or an ownership move loses a | |
| 115 | +pending retry and never the next occurrence. | |
| 116 | + | |
| 117 | +celld runs one missed occurrence after downtime. A deadline that is already due | |
| 118 | +when the fleet returns is a late tick and not a wrong one, so celld leaves the | |
| 119 | +armed alarm in place and runs it. The re-arm then walks forward from the current | |
| 120 | +time, therefore the occurrences between the late one and now do not run. An | |
| 121 | +application that must process every interval reads the interval from | |
| 122 | +`controller.scheduledTime` and catches up in its own code. | |
| 123 | + | |
| 124 | +Two occurrences of one script never overlap. The reserved cell runs one event at | |
| 125 | +a time, so a handler that takes longer than the interval holds the cell and | |
| 126 | +delays the next occurrence. Move long work into a [queue](queues.md) or a | |
| 127 | +[Workflow](workflows.md) when the schedule must stay on time. | |
| 128 | + | |
| 129 | +## Differences from Cloudflare | |
| 130 | + | |
| 131 | +- celld rejects a descending range such as `SAT-SUN` and a list that contains | |
| 132 | + `*`. | |
| 133 | +- celld runs one handler for each occurrence across the fleet. After downtime, | |
| 134 | + it runs one missed occurrence and skips the rest. | |
| 135 | +- celld serializes the handlers for one script. It retries a failure until the | |
| 136 | + next occurrence unless the handler calls `noRetry()`. | |
| 137 | +- A service-binding target cannot run its own Cron Triggers. | |
| 138 | + | |
| 139 | +The [Cloudflare compatibility](../cloudflare-compat.md#services) page | |
| 140 | +lists the runtime APIs and the unsupported services. |
addeddocs/services/d1-flow.svg+111−0View file
| @@ -1,0 +1,111 @@ | ||
| 1 | +<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 440 464" role="img" aria-labelledby="d1FlowTitle d1FlowDesc"> | |
| 2 | + <title id="d1FlowTitle">A D1 database is one cell, so every statement crosses a node boundary</title> | |
| 3 | + <desc id="d1FlowDesc">Worker A runs three prepared statements against the binding DB and pays three | |
| 4 | +round trips. Worker B sends the same three statements as one batch and pays one | |
| 5 | +round trip. Both cross a node boundary, because celld routes every statement to | |
| 6 | +the node that owns the cell. The guestbook database is one cell owned by node C. | |
| 7 | +It holds one SQLite file and has one writer, so the three separate statements | |
| 8 | +take three cell turns while the batch runs inside one BEGIN IMMEDIATE and COMMIT | |
| 9 | +in a single turn, all or nothing. Below the cell, a read answers from the cell's | |
| 10 | +own SQLite file and touches no bucket, while a write commits and then replicates | |
| 11 | +to the fleet bucket as LTX, and the acknowledgement waits for that write. A | |
| 12 | +second database is a second cell with its own owner node and its own writer, so | |
| 13 | +more write capacity comes from more databases and not from a bigger one.</desc> | |
| 14 | + <style> | |
| 15 | + svg { font-family: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Helvetica, Arial, sans-serif; } | |
| 16 | + text { font-size: 13px; fill: currentColor; } | |
| 17 | + tspan { fill: currentColor; } | |
| 18 | + .mono { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; } | |
| 19 | + .lead { font-weight: 600; } | |
| 20 | + .d-ink { color: #121212; } | |
| 21 | + .d-soft { color: #3d3b37; } | |
| 22 | + .d-faint { color: #6e6a62; } | |
| 23 | + .d-acc { color: #10803f; } | |
| 24 | + .d-panel { color: #ffffff; } | |
| 25 | + .d-sunk { color: #f0eee8; } | |
| 26 | + .d-tint { color: #d6efdf; } | |
| 27 | + @media (prefers-color-scheme: dark) { | |
| 28 | + .d-ink { color: #efede7; } | |
| 29 | + .d-soft { color: #c9c6be; } | |
| 30 | + .d-faint { color: #928e85; } | |
| 31 | + .d-acc { color: #3fc472; } | |
| 32 | + .d-panel { color: #1a1a19; } | |
| 33 | + .d-sunk { color: #232321; } | |
| 34 | + .d-tint { color: #10301d; } | |
| 35 | + } | |
| 36 | + </style> | |
| 37 | + <defs> | |
| 38 | + <marker id="d1-arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="6" | |
| 39 | + markerHeight="6" orient="auto-start-reverse"> | |
| 40 | + <path class="d-soft" fill="currentColor" d="M0 0 L10 5 L0 10 z" /> | |
| 41 | + </marker> | |
| 42 | + </defs> | |
| 43 | + | |
| 44 | + <!-- The same three statements, sent two ways. --> | |
| 45 | + <rect class="d-panel" fill="currentColor" x="6" y="8" width="196" height="68" rx="8" /> | |
| 46 | + <rect class="d-faint" fill="none" stroke="currentColor" x="6" y="8" width="196" height="68" rx="8" /> | |
| 47 | + <text class="d-faint" fill="currentColor" x="18" y="30">Worker · node A</text> | |
| 48 | + <text class="d-ink mono" fill="currentColor" x="18" y="52">prepare(…).run() ×3</text> | |
| 49 | + <text class="d-acc" fill="currentColor" x="18" y="70">three round trips</text> | |
| 50 | + | |
| 51 | + <rect class="d-panel" fill="currentColor" x="238" y="8" width="196" height="68" rx="8" /> | |
| 52 | + <rect class="d-faint" fill="none" stroke="currentColor" x="238" y="8" width="196" height="68" rx="8" /> | |
| 53 | + <text class="d-faint" fill="currentColor" x="250" y="30">Worker · node B</text> | |
| 54 | + <text class="d-ink mono" fill="currentColor" x="250" y="52">batch([a, b, c])</text> | |
| 55 | + <text class="d-acc" fill="currentColor" x="250" y="70">one round trip</text> | |
| 56 | + | |
| 57 | + <!-- The boundary every statement crosses. --> | |
| 58 | + <rect class="d-faint" fill="none" stroke="currentColor" stroke-dasharray="5 4" | |
| 59 | + x="6" y="90" width="428" height="40" rx="8" /> | |
| 60 | + <text class="d-soft" fill="currentColor" x="220" y="110" text-anchor="middle">node boundary</text> | |
| 61 | + <text class="d-faint" fill="currentColor" x="220" y="126" text-anchor="middle">celld routes each call to the owner</text> | |
| 62 | + | |
| 63 | + <g class="d-soft" fill="none" stroke="currentColor" stroke-width="1.5"> | |
| 64 | + <path d="M30 76 V144" marker-end="url(#d1-arrow)" /> | |
| 65 | + <path d="M60 76 V144" marker-end="url(#d1-arrow)" /> | |
| 66 | + <path d="M90 76 V144" marker-end="url(#d1-arrow)" /> | |
| 67 | + <path d="M396 76 V144" marker-end="url(#d1-arrow)" /> | |
| 68 | + </g> | |
| 69 | + | |
| 70 | + <!-- One database, one cell, one SQLite file, one writer. --> | |
| 71 | + <rect class="d-tint" fill="currentColor" x="16" y="144" width="408" height="134" rx="10" /> | |
| 72 | + <rect class="d-acc" fill="none" stroke="currentColor" stroke-width="2" x="16" y="144" width="408" height="134" rx="10" /> | |
| 73 | + <text class="d-ink lead" fill="currentColor" x="32" y="170">guestbook database = one cell · owner: node C</text> | |
| 74 | + <text class="d-soft" fill="currentColor" x="32" y="190">one SQLite file, one writer — statements never overlap</text> | |
| 75 | + | |
| 76 | + <rect class="d-sunk" fill="currentColor" x="30" y="204" width="184" height="60" rx="8" /> | |
| 77 | + <rect class="d-faint" fill="none" stroke="currentColor" x="30" y="204" width="184" height="60" rx="8" /> | |
| 78 | + <text class="d-ink mono" fill="currentColor" x="122" y="228" text-anchor="middle">run · run · run</text> | |
| 79 | + <text class="d-soft" fill="currentColor" x="122" y="248" text-anchor="middle">three cell turns</text> | |
| 80 | + | |
| 81 | + <rect class="d-sunk" fill="currentColor" x="226" y="204" width="184" height="60" rx="8" /> | |
| 82 | + <rect class="d-faint" fill="none" stroke="currentColor" x="226" y="204" width="184" height="60" rx="8" /> | |
| 83 | + <text class="d-ink mono" fill="currentColor" x="318" y="228" text-anchor="middle">BEGIN … COMMIT</text> | |
| 84 | + <text class="d-soft" fill="currentColor" x="318" y="248" text-anchor="middle">one turn, all or nothing</text> | |
| 85 | + | |
| 86 | + <!-- A read stops at the cell; a write goes on to the bucket. --> | |
| 87 | + <g class="d-soft" fill="none" stroke="currentColor" stroke-width="1.5"> | |
| 88 | + <path d="M100 278 V308" marker-end="url(#d1-arrow)" /> | |
| 89 | + <path d="M330 278 V308" marker-end="url(#d1-arrow)" /> | |
| 90 | + </g> | |
| 91 | + <text class="d-faint" fill="currentColor" x="108" y="300">read</text> | |
| 92 | + <text class="d-faint" fill="currentColor" x="338" y="300">write</text> | |
| 93 | + | |
| 94 | + <rect class="d-sunk" fill="currentColor" x="16" y="312" width="196" height="76" rx="8" /> | |
| 95 | + <rect class="d-faint" fill="none" stroke="currentColor" x="16" y="312" width="196" height="76" rx="8" /> | |
| 96 | + <text class="d-ink" fill="currentColor" x="30" y="336">answered here</text> | |
| 97 | + <text class="d-soft" fill="currentColor" x="30" y="356">from the cell's SQLite</text> | |
| 98 | + <text class="d-faint" fill="currentColor" x="30" y="376">no bucket round trip</text> | |
| 99 | + | |
| 100 | + <rect class="d-sunk" fill="currentColor" x="228" y="312" width="196" height="76" rx="8" /> | |
| 101 | + <rect class="d-faint" fill="none" stroke="currentColor" x="228" y="312" width="196" height="76" rx="8" /> | |
| 102 | + <text class="d-ink" fill="currentColor" x="242" y="336">commits, then LTX</text> | |
| 103 | + <text class="d-soft" fill="currentColor" x="242" y="356">to the fleet bucket</text> | |
| 104 | + <text class="d-faint" fill="currentColor" x="242" y="376">the ack waits for it</text> | |
| 105 | + | |
| 106 | + <!-- Scale comes from more cells, not a bigger one. --> | |
| 107 | + <rect class="d-faint" fill="none" stroke="currentColor" stroke-dasharray="5 4" | |
| 108 | + x="16" y="404" width="408" height="50" rx="8" /> | |
| 109 | + <text class="d-soft" fill="currentColor" x="32" y="426">orders database = a second cell, a second owner node</text> | |
| 110 | + <text class="d-faint" fill="currentColor" x="32" y="446">a second writer, so capacity comes from more databases</text> | |
| 111 | +</svg> |
addeddocs/services/d1.md+148−0View file
| @@ -1,0 +1,148 @@ | ||
| 1 | +# D1 | |
| 2 | + | |
| 3 | +D1 is a SQL database that a Worker reaches through a binding. An application | |
| 4 | +uses D1 for relational data that needs queries, joins, and constraints, such as | |
| 5 | +a user table, an order history, or a guestbook. celld gives each database its | |
| 6 | +own SQLite file inside one cell, so the rows live on the node that owns that | |
| 7 | +cell and never in the Worker isolate. Read the | |
| 8 | +[Cloudflare D1 documentation](https://developers.cloudflare.com/d1/worker-api/d1-database/) | |
| 9 | +for the standard API behavior. | |
| 10 | + | |
| 11 | +## Example | |
| 12 | + | |
| 13 | +The [D1 example](../../examples/d1) implements a guestbook with a D1 database. | |
| 14 | + | |
| 15 | +<!-- celld-example: d1 --> | |
| 16 | + | |
| 17 | +## Statements and results | |
| 18 | + | |
| 19 | +A project declares a database with a `d1_databases` entry that gives a | |
| 20 | +`binding`, a `database_name`, and a `database_id`. celld uses the | |
| 21 | +`database_id` as the stable identity when the entry carries one, and it falls | |
| 22 | +back to the `database_name`. That identity belongs to the fleet and not to one | |
| 23 | +script, so two Workers that name one identity reach one database. celld also | |
| 24 | +creates a database on first use, therefore a typo in the name opens an empty | |
| 25 | +database instead of an error. | |
| 26 | + | |
| 27 | +`env.DB.prepare(sql)` returns a statement, and `bind()` returns a new statement | |
| 28 | +that carries the values. celld checks each value at that call: a number and a | |
| 29 | +string pass, a boolean becomes `1` or `0`, and an `ArrayBuffer`, a typed array, | |
| 30 | +or an array of byte numbers becomes a `BLOB`. Any other value throws | |
| 31 | +`D1_TYPE_ERROR` before SQL runs. celld binds the positional parameters `?` and | |
| 32 | +`?NNN` that | |
| 33 | +[Cloudflare binds](https://developers.cloudflare.com/d1/worker-api/prepared-statements/). | |
| 34 | + | |
| 35 | +Four methods run a statement, and each one shapes the answer differently. | |
| 36 | +`all()` returns `success`, a `results` array of row objects, and a `meta` | |
| 37 | +block, and `run()` is the same method under a second name. `first()` returns | |
| 38 | +the first row as an object, or `null` for an empty result, and `first(column)` | |
| 39 | +returns one column of that row. `raw()` returns the rows as arrays and drops | |
| 40 | +`meta`, and `raw({ columnNames: true })` puts the column names in the first | |
| 41 | +array. `meta` carries `duration`, `rows_read`, `rows_written`, `last_row_id`, | |
| 42 | +`changes`, `changed_db`, and `size_after`. A read-only statement reports | |
| 43 | +`last_row_id` and `changes` as `0`, because both values belong to the | |
| 44 | +connection and a read changes neither. | |
| 45 | + | |
| 46 | +`exec(sql)` runs one or more statements without a parameter and returns a count | |
| 47 | +and a duration. Use it for a schema or an import, as the example does. A | |
| 48 | +prepared statement must hold exactly one statement, so celld refuses a second | |
| 49 | +one with `A prepared SQL statement must contain only one statement.` Cloudflare | |
| 50 | +runs the extra statement and answers with the last result, therefore an | |
| 51 | +application that relies on that behavior must call `exec()` or `batch()` | |
| 52 | +instead. The count that `exec()` returns also differs: celld counts each | |
| 53 | +statement, and Cloudflare counts each input line. | |
| 54 | + | |
| 55 | +celld applies the SQLite budgets that workerd applies, so these published | |
| 56 | +[D1 limits](https://developers.cloudflare.com/d1/platform/limits/) hold: a | |
| 57 | +statement of at most 100,000 bytes, at most 100 bound parameters, at most 100 | |
| 58 | +columns in a table, and a string, a `BLOB`, or a row of at most 2,200,000 | |
| 59 | +bytes. | |
| 60 | + | |
| 61 | +## One database is one cell | |
| 62 | + | |
| 63 | +A celld D1 database is a cell, which is the same single-threaded actor that | |
| 64 | +runs a Durable Object. One node of the fleet owns a cell at a time, so a query | |
| 65 | +leaves the Worker's isolate and celld routes it to the owner node. A statement | |
| 66 | +therefore costs one cell dispatch, and a larger fleet does not make that | |
| 67 | +dispatch cheaper. celld materializes the result inside the cell and then copies | |
| 68 | +it into the calling isolate, so a result carries at most 100,000 rows or | |
| 69 | +32 MiB. | |
| 70 | +`first()` keeps one row on the cell side, so a `first()` cannot reach the row | |
| 71 | +cap. | |
| 72 | + | |
| 73 | +A cell holds one SQLite file and has one writer. Two statements against one | |
| 74 | +database therefore run one after the other, even when they touch different | |
| 75 | +tables. More nodes do not divide that work, because the database has one owner. | |
| 76 | +An application that needs more write capacity uses more databases, and | |
| 77 | +[Cloudflare recommends the same many-database shape](https://developers.cloudflare.com/d1/) | |
| 78 | +for the same reason. | |
| 79 | + | |
| 80 | +Cloudflare gives a database one primary instance and asynchronous | |
| 81 | +[read replicas](https://developers.cloudflare.com/d1/best-practices/read-replication/) | |
| 82 | +across its network, and its Sessions API uses a bookmark to keep a session | |
| 83 | +sequentially consistent. celld has one cell and no replica. `withSession()` | |
| 84 | +therefore works and always selects the primary, `getBookmark()` returns the | |
| 85 | +stable token `celld:primary` after a query, and every read already observes | |
| 86 | +every committed write. `meta.served_by_primary` is therefore always `true` and | |
| 87 | +`meta.served_by_region` is always `local`. A celld read cannot become faster | |
| 88 | +near a user, because celld has no replica that can serve it. | |
| 89 | + | |
| 90 | + | |
| 91 | + | |
| 92 | +## Batches, transactions, and durability | |
| 93 | + | |
| 94 | +`batch()` takes an array of prepared statements, sends them to the cell in one | |
| 95 | +dispatch, and runs them inside one `BEGIN IMMEDIATE ... COMMIT`. A failure | |
| 96 | +rolls the whole batch back, so a batch is all or nothing, and the call returns | |
| 97 | +one result for each statement in the order of the array. `exec()` uses the same | |
| 98 | +bracket, therefore a failing line in a multi-statement import rolls the import | |
| 99 | +back whole. Both behaviors match | |
| 100 | +[Cloudflare's batch semantics](https://developers.cloudflare.com/d1/worker-api/d1-database/). | |
| 101 | + | |
| 102 | +A batch is also one round trip and one cell turn. Three separate `run()` calls | |
| 103 | +cost three dispatches to the owner node, and one `batch()` of those three | |
| 104 | +statements costs one. Group the statements that belong together, because the | |
| 105 | +grouping removes two boundary crossings and makes the three writes atomic. | |
| 106 | + | |
| 107 | +An application cannot open its own transaction. celld denies `BEGIN`, `COMMIT`, | |
| 108 | +`ROLLBACK`, and `SAVEPOINT` in application SQL, because a D1 call owns the | |
| 109 | +transaction bracket and must never hand an open transaction back to the Worker. | |
| 110 | +`batch()` and `exec()` are therefore the transaction primitives. celld also | |
| 111 | +denies `ATTACH`, `DETACH`, `VACUUM`, `load_extension()`, and a temporary table, | |
| 112 | +index, trigger, or view. celld allows the `fts5` and `fts5vocab` virtual tables | |
| 113 | +that D1 allows, and it accepts a `PRAGMA` allowlist that covers the list in the | |
| 114 | +[D1 SQL statement reference](https://developers.cloudflare.com/d1/sql-api/sql-statements/). | |
| 115 | + | |
| 116 | +celld acknowledges a write only after the cell's output gate releases it. The | |
| 117 | +cell writes its SQLite changes to the fleet bucket as LTX transaction files, so | |
| 118 | +an acknowledged D1 write survives the loss of the owner node and restores on | |
| 119 | +another node. That durability is the durability of the object store that the | |
| 120 | +operator runs, and it is not the durability of Cloudflare D1. A read needs no | |
| 121 | +such step, because the cell answers it from the SQLite file that it already | |
| 122 | +holds. | |
| 123 | + | |
| 124 | +`celld d1 execute` and `celld d1 migrations apply` reach a database from the | |
| 125 | +command line. They find a live node through the fleet bucket and send the SQL | |
| 126 | +over the same dispatch path that `env.DB` uses, so the CLI never writes the | |
| 127 | +SQLite file behind the owner's back. | |
| 128 | + | |
| 129 | +## Differences from Cloudflare | |
| 130 | + | |
| 131 | +- A binding result can contain at most 100,000 rows or 32 MiB. | |
| 132 | +- celld refuses invalid UTF-8 from a SQLite `TEXT` value. Store arbitrary bytes | |
| 133 | + in a `BLOB`. | |
| 134 | +- A database has one writer. Use more databases to increase write capacity. | |
| 135 | +- celld has no read replica. `withSession()` always selects the primary, and | |
| 136 | + `getBookmark()` returns `celld:primary`. | |
| 137 | +- A read-only statement reports `last_row_id` and `changes` as `0`. Cloudflare | |
| 138 | + reports the values that the previous write left on the connection. | |
| 139 | +- `prepare()` accepts exactly one statement. | |
| 140 | +- `exec()` counts each statement. Cloudflare counts each input line. | |
| 141 | +- `dump()` throws. The database is a SQLite file in the operator's own bucket. | |
| 142 | +- Application SQL cannot use `BEGIN`, `SAVEPOINT`, `ATTACH`, `VACUUM`, | |
| 143 | + `load_extension()`, or a temporary table. | |
| 144 | +- celld has no D1 REST API and no Time Travel. Use `celld d1` for SQL and for | |
| 145 | + migrations. | |
| 146 | + | |
| 147 | +The [Cloudflare compatibility](../cloudflare-compat.md#services) page lists the | |
| 148 | +runtime APIs and the unsupported services. |
addeddocs/services/durable-object-facets-flow.svg+127−0View file
| @@ -1,0 +1,127 @@ | ||
| 1 | +<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 440 372" role="img"> | |
| 2 | + <title>Several facets share one cell, one owner node, and one replication stream, while separate Durable Objects each take their own owner record and node</title> | |
| 3 | + <desc>Two arrangements of the same three application databases. On the left, a | |
| 4 | +Worker calls one supervisor cell on node B at epoch e4. That single cell holds | |
| 5 | +the supervisor's SQLite database and, in separate databases beside it, the | |
| 6 | +facets app-a and app-b. One owner record and one stream under | |
| 7 | +cells/acct-9/ltx/e4/ cover all of them, so the call takes one hop and one output | |
| 8 | +gate. On the right, the same three databases are three separate Durable Object | |
| 9 | +cells on nodes B, C, and A. Each cell holds its own owner record and its own | |
| 10 | +epoch, and the three replicate under three prefixes, so a call takes a hop and | |
| 11 | +an output gate for each object.</desc> | |
| 12 | + <style> | |
| 13 | + .d-ink { color: #121212 } | |
| 14 | + .d-soft { color: #3d3b37 } | |
| 15 | + .d-faint { color: #6e6a62 } | |
| 16 | + .d-acc { color: #10803f } | |
| 17 | + .d-panel { color: #ffffff } | |
| 18 | + .d-sunk { color: #f0eee8 } | |
| 19 | + .d-tint { color: #d6efdf } | |
| 20 | + text { | |
| 21 | + font-family: ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif; | |
| 22 | + font-size: 13px; | |
| 23 | + fill: currentColor; | |
| 24 | + } | |
| 25 | + tspan { fill: currentColor; } | |
| 26 | + @media (prefers-color-scheme: dark) { | |
| 27 | + .d-ink { color: #efede7 } | |
| 28 | + .d-soft { color: #c9c6be } | |
| 29 | + .d-faint { color: #928e85 } | |
| 30 | + .d-acc { color: #3fc472 } | |
| 31 | + .d-panel { color: #1a1a19 } | |
| 32 | + .d-sunk { color: #232321 } | |
| 33 | + .d-tint { color: #10301d } | |
| 34 | + } | |
| 35 | + </style> | |
| 36 | + <defs> | |
| 37 | + <marker id="facet-arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="6" | |
| 38 | + markerHeight="6" orient="auto-start-reverse"> | |
| 39 | + <path class="d-soft" fill="currentColor" d="M0 0 L10 5 L0 10 z" /> | |
| 40 | + </marker> | |
| 41 | + </defs> | |
| 42 | + | |
| 43 | + <!-- Column captions: one object with facets, against separate objects. --> | |
| 44 | + <text class="d-ink" fill="currentColor" x="110" y="14" text-anchor="middle">one object, two facets</text> | |
| 45 | + <text class="d-ink" fill="currentColor" x="330" y="14" text-anchor="middle">three separate objects</text> | |
| 46 | + | |
| 47 | + <!-- The same caller in both arrangements. --> | |
| 48 | + <rect class="d-panel" fill="currentColor" x="6" y="24" width="208" height="32" rx="6" /> | |
| 49 | + <rect class="d-soft" fill="none" stroke="currentColor" x="6" y="24" width="208" height="32" rx="6" /> | |
| 50 | + <text class="d-soft" fill="currentColor" x="110" y="45" text-anchor="middle">Worker</text> | |
| 51 | + | |
| 52 | + <rect class="d-panel" fill="currentColor" x="226" y="24" width="208" height="32" rx="6" /> | |
| 53 | + <rect class="d-soft" fill="none" stroke="currentColor" x="226" y="24" width="208" height="32" rx="6" /> | |
| 54 | + <text class="d-soft" fill="currentColor" x="330" y="45" text-anchor="middle">Worker</text> | |
| 55 | + | |
| 56 | + <!-- One dispatch on the left; one dispatch for each object on the right. --> | |
| 57 | + <g class="d-soft" fill="none" stroke="currentColor" stroke-width="1.5"> | |
| 58 | + <path d="M110 56 V74" marker-end="url(#facet-arrow)" /> | |
| 59 | + <path d="M330 56 V66 H234 V219" /> | |
| 60 | + <path d="M234 99 H246" marker-end="url(#facet-arrow)" /> | |
| 61 | + <path d="M234 159 H246" marker-end="url(#facet-arrow)" /> | |
| 62 | + <path d="M234 219 H246" marker-end="url(#facet-arrow)" /> | |
| 63 | + </g> | |
| 64 | + | |
| 65 | + <!-- One cell, one owner, one epoch, and two private databases inside it. --> | |
| 66 | + <rect class="d-tint" fill="currentColor" x="6" y="74" width="208" height="172" rx="6" /> | |
| 67 | + <rect class="d-acc" fill="none" stroke="currentColor" stroke-width="2" x="6" y="74" width="208" height="172" rx="6" /> | |
| 68 | + <text class="d-ink" fill="currentColor" x="110" y="95" text-anchor="middle">supervisor cell</text> | |
| 69 | + <text class="d-soft" fill="currentColor" x="110" y="112" text-anchor="middle">node B · epoch e4</text> | |
| 70 | + | |
| 71 | + <rect class="d-sunk" fill="currentColor" x="16" y="122" width="188" height="34" rx="6" /> | |
| 72 | + <rect class="d-soft" fill="none" stroke="currentColor" x="16" y="122" width="188" height="34" rx="6" /> | |
| 73 | + <text class="d-ink" fill="currentColor" x="110" y="144" text-anchor="middle">supervisor SQLite</text> | |
| 74 | + | |
| 75 | + <g class="d-faint" fill="none" stroke="currentColor" stroke-dasharray="5 4"> | |
| 76 | + <path d="M16 168 H46" /> | |
| 77 | + <path d="M174 168 H204" /> | |
| 78 | + </g> | |
| 79 | + <text class="d-faint" fill="currentColor" x="110" y="172" text-anchor="middle">separate databases</text> | |
| 80 | + | |
| 81 | + <rect class="d-sunk" fill="currentColor" x="16" y="180" width="90" height="56" rx="6" /> | |
| 82 | + <rect class="d-soft" fill="none" stroke="currentColor" x="16" y="180" width="90" height="56" rx="6" /> | |
| 83 | + <text class="d-ink" fill="currentColor" x="61" y="202" text-anchor="middle">facet app-a</text> | |
| 84 | + <text class="d-soft" fill="currentColor" x="61" y="221" text-anchor="middle">own SQLite</text> | |
| 85 | + | |
| 86 | + <rect class="d-sunk" fill="currentColor" x="114" y="180" width="90" height="56" rx="6" /> | |
| 87 | + <rect class="d-soft" fill="none" stroke="currentColor" x="114" y="180" width="90" height="56" rx="6" /> | |
| 88 | + <text class="d-ink" fill="currentColor" x="159" y="202" text-anchor="middle">facet app-b</text> | |
| 89 | + <text class="d-soft" fill="currentColor" x="159" y="221" text-anchor="middle">own SQLite</text> | |
| 90 | + | |
| 91 | + <!-- The same three databases as three cells, each with its own owner. --> | |
| 92 | + <rect class="d-panel" fill="currentColor" x="246" y="74" width="176" height="50" rx="6" /> | |
| 93 | + <rect class="d-soft" fill="none" stroke="currentColor" x="246" y="74" width="176" height="50" rx="6" /> | |
| 94 | + <text class="d-ink" fill="currentColor" x="334" y="95" text-anchor="middle">APP-A cell · node B</text> | |
| 95 | + <text class="d-soft" fill="currentColor" x="334" y="112" text-anchor="middle">own owner record · e4</text> | |
| 96 | + | |
| 97 | + <rect class="d-panel" fill="currentColor" x="246" y="134" width="176" height="50" rx="6" /> | |
| 98 | + <rect class="d-soft" fill="none" stroke="currentColor" x="246" y="134" width="176" height="50" rx="6" /> | |
| 99 | + <text class="d-ink" fill="currentColor" x="334" y="155" text-anchor="middle">APP-B cell · node C</text> | |
| 100 | + <text class="d-soft" fill="currentColor" x="334" y="172" text-anchor="middle">own owner record · e9</text> | |
| 101 | + | |
| 102 | + <rect class="d-panel" fill="currentColor" x="246" y="194" width="176" height="50" rx="6" /> | |
| 103 | + <rect class="d-soft" fill="none" stroke="currentColor" x="246" y="194" width="176" height="50" rx="6" /> | |
| 104 | + <text class="d-ink" fill="currentColor" x="334" y="215" text-anchor="middle">APP-C cell · node A</text> | |
| 105 | + <text class="d-soft" fill="currentColor" x="334" y="232" text-anchor="middle">own owner record · e2</text> | |
| 106 | + | |
| 107 | + <!-- One stream against three streams. --> | |
| 108 | + <g class="d-soft" fill="none" stroke="currentColor" stroke-width="1.5"> | |
| 109 | + <path d="M110 246 V272" marker-end="url(#facet-arrow)" /> | |
| 110 | + <path d="M422 99 H428 V264 H330 V272" marker-end="url(#facet-arrow)" /> | |
| 111 | + <path d="M422 159 H428" /> | |
| 112 | + <path d="M422 219 H428" /> | |
| 113 | + </g> | |
| 114 | + | |
| 115 | + <rect class="d-sunk" fill="currentColor" x="6" y="272" width="208" height="52" rx="6" /> | |
| 116 | + <rect class="d-soft" fill="none" stroke="currentColor" x="6" y="272" width="208" height="52" rx="6" /> | |
| 117 | + <text class="d-ink" fill="currentColor" x="110" y="293" text-anchor="middle">cells/acct-9/ltx/e4/</text> | |
| 118 | + <text class="d-soft" fill="currentColor" x="110" y="311" text-anchor="middle">one stream covers all</text> | |
| 119 | + | |
| 120 | + <rect class="d-sunk" fill="currentColor" x="226" y="272" width="208" height="52" rx="6" /> | |
| 121 | + <rect class="d-soft" fill="none" stroke="currentColor" x="226" y="272" width="208" height="52" rx="6" /> | |
| 122 | + <text class="d-ink" fill="currentColor" x="330" y="293" text-anchor="middle">three bucket prefixes</text> | |
| 123 | + <text class="d-soft" fill="currentColor" x="330" y="311" text-anchor="middle">three epochs</text> | |
| 124 | + | |
| 125 | + <text class="d-faint" fill="currentColor" x="110" y="348" text-anchor="middle">one hop, one gate, one proof</text> | |
| 126 | + <text class="d-faint" fill="currentColor" x="330" y="348" text-anchor="middle">a hop and a gate for each</text> | |
| 127 | +</svg> |
addeddocs/services/durable-object-facets.md+108−0View file
| @@ -1,0 +1,108 @@ | ||
| 1 | +# Durable Object Facets | |
| 2 | + | |
| 3 | +A facet is a child object inside a Durable Object. A supervisor class starts a | |
| 4 | +facet from a class that a [Worker Loader](dynamic-workers.md) provides, and the | |
| 5 | +supervisor and the facet then keep separate SQLite databases. An application | |
| 6 | +uses a facet to give generated or untrusted code durable storage without giving | |
| 7 | +that code a Durable Object namespace. The state of a facet lives inside the | |
| 8 | +storage of its root object, so celld replicates the two together. Read the | |
| 9 | +[Cloudflare Durable Object Facets documentation](https://developers.cloudflare.com/dynamic-workers/usage/durable-object-facets/) | |
| 10 | +for the standard API behavior. | |
| 11 | + | |
| 12 | +## Example | |
| 13 | + | |
| 14 | +The [facets example](../../examples/facets) creates a facet from a class that a | |
| 15 | +Worker Loader provides. | |
| 16 | + | |
| 17 | +<!-- celld-example: facets --> | |
| 18 | + | |
| 19 | +## A facet is a part of its root object | |
| 20 | + | |
| 21 | +A facet is not a cell. celld holds the SQLite database of a facet as an image in | |
| 22 | +a row of the root cell's own database, and it copies that image into the row | |
| 23 | +before an effect of the facet leaves the node. A facet therefore owns no | |
| 24 | +ownership record, no fencing epoch, and no replication stream. It inherits all | |
| 25 | +three from the root cell, so one upload covers the writes of the supervisor and | |
| 26 | +the writes of every facet together. The | |
| 27 | +[Durable Objects page](durable-objects.md#ownership-and-the-single-threaded-model) | |
| 28 | +describes that record, that epoch, and that stream. | |
| 29 | + | |
| 30 | +Containment also sets the lifecycle. A facet starts inside an event of the root | |
| 31 | +object, therefore the code of the facet runs on the node that owns the root | |
| 32 | +cell. celld releases every running facet when it releases the root cell, and the | |
| 33 | +startup callback runs again at the next call. An eviction, a reset, and a move | |
| 34 | +of ownership take the root object and its facets as one group. | |
| 35 | + | |
| 36 | +celld holds an outbound effect of a facet against the output gate of the root | |
| 37 | +cell, because that effect can reveal a write that only the root cell can prove. | |
| 38 | +A root storage transaction keeps an uncommitted facet image out of the root | |
| 39 | +database, so celld rejects an outbound effect while that transaction is open. | |
| 40 | +The error states that the root transaction has not committed the facet image. | |
| 41 | +celld applies the check to a read-only call as well, because an earlier call in | |
| 42 | +the same turn can leave an image behind and the read can reveal it. | |
| 43 | + | |
| 44 | + | |
| 45 | + | |
| 46 | +## Starting and addressing a facet | |
| 47 | + | |
| 48 | +`ctx.facets.get(name, callback)` returns a stub for the facet with that name, | |
| 49 | +and celld runs the callback only when the facet is not already running. The | |
| 50 | +callback takes no argument and returns a `class` and an optional `id`. `class` | |
| 51 | +must come from `worker.getDurableObjectClass("App")` on a Worker Loader binding, | |
| 52 | +because that method is the only source of a `DurableObjectClass`. `id` sets what | |
| 53 | +the facet reads at `ctx.id`, and the facet inherits the id of its root object | |
| 54 | +when the callback gives no `id`. | |
| 55 | + | |
| 56 | +The name alone selects the database, so a later call that keeps the name and | |
| 57 | +changes the `id` still reaches the stored data. A name has a limit of 256 bytes. | |
| 58 | +A facet can start a facet of its own, to a total depth of 4 that counts the root | |
| 59 | +object. `ctx.facets.abort(name, reason)` stops a running facet and keeps its | |
| 60 | +database, and a call on the stopped stub then throws the given reason. | |
| 61 | +`ctx.facets.delete(name)` stops the facet and removes its database and the | |
| 62 | +database of every facet below it. The stub answers `fetch()` and the RPC methods | |
| 63 | +of the class. The stub itself is not a promise, and a pipelined property path is | |
| 64 | +unavailable, so a call must name one method. | |
| 65 | + | |
| 66 | +## Choose a facet or a second Durable Object | |
| 67 | + | |
| 68 | +Use a facet when the child state belongs to the parent. The supervisor sits on | |
| 69 | +the path of every call, so it can count a call, apply a quota, and refuse a | |
| 70 | +request before the child code runs. The facet stays on the owner node of the | |
| 71 | +root cell, therefore a call from the supervisor crosses no node boundary and | |
| 72 | +waits for no second output gate. A write of the facet also becomes durable with | |
| 73 | +the next upload of the root cell, and a facet write that a root storage | |
| 74 | +transaction encloses commits with that transaction or rolls back with it. Two | |
| 75 | +separate Durable Objects give no such atomicity, because each one proves its own | |
| 76 | +writes. | |
| 77 | + | |
| 78 | +A facet has a cost as well. celld copies the complete SQLite image of a facet | |
| 79 | +into the root database after a turn that changed it, so a large facet database | |
| 80 | +makes each changed turn more expensive. | |
| 81 | + | |
| 82 | +Use a separate Durable Object when the children must scale apart. Each object | |
| 83 | +then takes its own id, its own ownership record, and its own owner node, so the | |
| 84 | +fleet can place two of them on two machines and the stop of one node affects one | |
| 85 | +of them. A caller can also address such an object directly with | |
| 86 | +[`idFromName()`](durable-objects.md#identity-and-addressing). No name reaches a | |
| 87 | +facet from outside its root object, and a facet that must serve external traffic | |
| 88 | +therefore needs a supervisor that forwards the request. | |
| 89 | + | |
| 90 | +## Differences from Cloudflare | |
| 91 | + | |
| 92 | +- Facets require Dynamic Workers and a class from a Worker Loader binding. A | |
| 93 | + class from `ctx.exports` or a Durable Object binding is unavailable. | |
| 94 | +- Each facet has a separate SQLite database, which celld replicates with the | |
| 95 | + root Durable Object. celld copies the complete image of that database into the | |
| 96 | + root database after a turn that changed it, so the cost of a changed turn | |
| 97 | + grows with the size of the facet database. | |
| 98 | +- celld rejects an outbound effect from a facet while a root storage transaction | |
| 99 | + holds an uncommitted facet image. | |
| 100 | +- An explicit transaction keeps its uncommitted writes in the facet. A rollback | |
| 101 | + discards those writes, and a commit makes them available for root replication. | |
| 102 | +- A facet cannot set an alarm. `storage.setAlarm()` throws inside a facet, so | |
| 103 | + the root object must hold the schedule. | |
| 104 | +- A facet stub is not awaitable, and a pipelined property path is unavailable. | |
| 105 | +- The `clone()` method is unavailable. | |
| 106 | + | |
| 107 | +The [Cloudflare compatibility](../cloudflare-compat.md#services) | |
| 108 | +page lists the runtime APIs and the unsupported services. |
addeddocs/services/durable-objects-flow.svg+127−0View file
| @@ -1,0 +1,127 @@ | ||
| 1 | +<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 440 520" role="img" aria-labelledby="doFlowTitle doFlowDesc"> | |
| 2 | + <title id="doFlowTitle">One name reaches one cell, and one node owns that cell</title> | |
| 3 | + <desc id="doFlowDesc">Workers on node A and node B both address the name room-7, | |
| 4 | +and a Worker on node C addresses the name room-8. getByName turns each name into | |
| 5 | +one 64-digit hexadecimal id, the owner record in the fleet bucket names one | |
| 6 | +owner node for each cell, and celld forwards the call to that node. The room-7 | |
| 7 | +cell has owner node B and epoch e7, and the room-8 cell has owner node C and | |
| 8 | +epoch e3, so ownership belongs to a cell and not to a class. Each cell runs one | |
| 9 | +event at a time. The room-7 cell keeps its own SQLite database on node B. Node B | |
| 10 | +sends each write to a follower node, whose fsync releases the answer, and the | |
| 11 | +write then uploads to the fleet bucket under cells/room-7/ltx/e7/. The previous | |
| 12 | +prefix, cells/room-7/ltx/e6/, is superseded, so a node that lost the cell cannot | |
| 13 | +damage the current data. Node C keeps the room-8 cell the same way, under its | |
| 14 | +own epoch.</desc> | |
| 15 | + <style> | |
| 16 | + .d-ink { color: #121212 } | |
| 17 | + .d-soft { color: #3d3b37 } | |
| 18 | + .d-faint { color: #6e6a62 } | |
| 19 | + .d-acc { color: #10803f } | |
| 20 | + .d-panel { color: #ffffff } | |
| 21 | + .d-sunk { color: #f0eee8 } | |
| 22 | + .d-tint { color: #d6efdf } | |
| 23 | + text { | |
| 24 | + font-family: ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif; | |
| 25 | + font-size: 13px; | |
| 26 | + fill: currentColor; | |
| 27 | + } | |
| 28 | + @media (prefers-color-scheme: dark) { | |
| 29 | + .d-ink { color: #efede7 } | |
| 30 | + .d-soft { color: #c9c6be } | |
| 31 | + .d-faint { color: #928e85 } | |
| 32 | + .d-acc { color: #3fc472 } | |
| 33 | + .d-panel { color: #1a1a19 } | |
| 34 | + .d-sunk { color: #232321 } | |
| 35 | + .d-tint { color: #10301d } | |
| 36 | + } | |
| 37 | + </style> | |
| 38 | + <defs> | |
| 39 | + <marker id="do-arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="6" | |
| 40 | + markerHeight="6" orient="auto-start-reverse"> | |
| 41 | + <path class="d-soft" fill="currentColor" d="M0 0 L10 5 L0 10 z" /> | |
| 42 | + </marker> | |
| 43 | + </defs> | |
| 44 | + | |
| 45 | + <!-- Callers: three nodes, two of them addressing one name. --> | |
| 46 | + <rect class="d-panel" fill="currentColor" x="6" y="8" width="136" height="48" rx="6" /> | |
| 47 | + <rect class="d-soft" fill="none" stroke="currentColor" x="6" y="8" width="136" height="48" rx="6" /> | |
| 48 | + <text class="d-ink" fill="currentColor" x="74" y="29" text-anchor="middle">Worker · node A</text> | |
| 49 | + <text class="d-soft" fill="currentColor" x="74" y="46" text-anchor="middle">name: "room-7"</text> | |
| 50 | + | |
| 51 | + <rect class="d-panel" fill="currentColor" x="152" y="8" width="136" height="48" rx="6" /> | |
| 52 | + <rect class="d-soft" fill="none" stroke="currentColor" x="152" y="8" width="136" height="48" rx="6" /> | |
| 53 | + <text class="d-ink" fill="currentColor" x="220" y="29" text-anchor="middle">Worker · node B</text> | |
| 54 | + <text class="d-soft" fill="currentColor" x="220" y="46" text-anchor="middle">name: "room-7"</text> | |
| 55 | + | |
| 56 | + <rect class="d-panel" fill="currentColor" x="298" y="8" width="136" height="48" rx="6" /> | |
| 57 | + <rect class="d-soft" fill="none" stroke="currentColor" x="298" y="8" width="136" height="48" rx="6" /> | |
| 58 | + <text class="d-ink" fill="currentColor" x="366" y="29" text-anchor="middle">Worker · node C</text> | |
| 59 | + <text class="d-soft" fill="currentColor" x="366" y="46" text-anchor="middle">name: "room-8"</text> | |
| 60 | + | |
| 61 | + <!-- The boundary each call crosses: name to id, owner record, forward. --> | |
| 62 | + <rect class="d-faint" fill="none" stroke="currentColor" stroke-dasharray="5 4" | |
| 63 | + x="6" y="72" width="428" height="62" rx="6" /> | |
| 64 | + <text class="d-faint" fill="currentColor" x="220" y="92" text-anchor="middle">getByName() gives one 64-hex id</text> | |
| 65 | + <text class="d-faint" fill="currentColor" x="220" y="111" text-anchor="middle">the owner record in the bucket names one node</text> | |
| 66 | + <text class="d-faint" fill="currentColor" x="220" y="130" text-anchor="middle">celld forwards the call to that node</text> | |
| 67 | + | |
| 68 | + <!-- Two callers of one name join. A second name is a second cell. --> | |
| 69 | + <g class="d-soft" fill="none" stroke="currentColor" stroke-width="1.5"> | |
| 70 | + <path d="M74 56 V66" /> | |
| 71 | + <path d="M220 56 V66" /> | |
| 72 | + <path d="M60 66 H220" /> | |
| 73 | + <path d="M60 66 V152" marker-end="url(#do-arrow)" /> | |
| 74 | + <path d="M366 56 V66 H380 V152" marker-end="url(#do-arrow)" /> | |
| 75 | + </g> | |
| 76 | + | |
| 77 | + <!-- One cell, one owner, one event. Ownership belongs to a cell, not a class. --> | |
| 78 | + <rect class="d-tint" fill="currentColor" x="16" y="156" width="200" height="90" rx="6" /> | |
| 79 | + <rect class="d-acc" fill="none" stroke="currentColor" stroke-width="2" x="16" y="156" width="200" height="90" rx="6" /> | |
| 80 | + <text class="d-ink" fill="currentColor" x="116" y="177" text-anchor="middle">room-7 cell</text> | |
| 81 | + <text class="d-soft" fill="currentColor" x="116" y="196" text-anchor="middle">owner: node B</text> | |
| 82 | + <text class="d-soft" fill="currentColor" x="116" y="215" text-anchor="middle">one event at a time</text> | |
| 83 | + <text class="d-faint" fill="currentColor" x="116" y="234" text-anchor="middle">epoch e7</text> | |
| 84 | + | |
| 85 | + <rect class="d-tint" fill="currentColor" x="224" y="156" width="200" height="90" rx="6" /> | |
| 86 | + <rect class="d-acc" fill="none" stroke="currentColor" stroke-width="2" x="224" y="156" width="200" height="90" rx="6" /> | |
| 87 | + <text class="d-ink" fill="currentColor" x="324" y="177" text-anchor="middle">room-8 cell</text> | |
| 88 | + <text class="d-soft" fill="currentColor" x="324" y="196" text-anchor="middle">owner: node C</text> | |
| 89 | + <text class="d-soft" fill="currentColor" x="324" y="215" text-anchor="middle">one event at a time</text> | |
| 90 | + <text class="d-faint" fill="currentColor" x="324" y="234" text-anchor="middle">epoch e3</text> | |
| 91 | + | |
| 92 | + <!-- The owner holds the database, and the write then buys its durability. --> | |
| 93 | + <g class="d-soft" fill="none" stroke="currentColor" stroke-width="1.5"> | |
| 94 | + <path d="M116 246 V272" marker-end="url(#do-arrow)" /> | |
| 95 | + <path d="M116 322 V346" marker-end="url(#do-arrow)" /> | |
| 96 | + <path d="M116 396 V420" marker-end="url(#do-arrow)" /> | |
| 97 | + </g> | |
| 98 | + | |
| 99 | + <rect class="d-sunk" fill="currentColor" x="16" y="276" width="200" height="46" rx="6" /> | |
| 100 | + <rect class="d-soft" fill="none" stroke="currentColor" x="16" y="276" width="200" height="46" rx="6" /> | |
| 101 | + <text class="d-ink" fill="currentColor" x="116" y="297" text-anchor="middle">SQLite on node B</text> | |
| 102 | + <text class="d-soft" fill="currentColor" x="116" y="314" text-anchor="middle">one database per cell</text> | |
| 103 | + | |
| 104 | + <rect class="d-sunk" fill="currentColor" x="16" y="350" width="200" height="46" rx="6" /> | |
| 105 | + <rect class="d-soft" fill="none" stroke="currentColor" x="16" y="350" width="200" height="46" rx="6" /> | |
| 106 | + <text class="d-ink" fill="currentColor" x="116" y="371" text-anchor="middle">a follower node</text> | |
| 107 | + <text class="d-soft" fill="currentColor" x="116" y="388" text-anchor="middle">fsync frees the answer</text> | |
| 108 | + | |
| 109 | + <text class="d-faint" fill="currentColor" x="326" y="297" text-anchor="middle">node C keeps room-8</text> | |
| 110 | + <text class="d-faint" fill="currentColor" x="326" y="316" text-anchor="middle">the same way, under</text> | |
| 111 | + <text class="d-faint" fill="currentColor" x="326" y="335" text-anchor="middle">its own epoch</text> | |
| 112 | + | |
| 113 | + <!-- The epoch in the prefix is the fence. --> | |
| 114 | + <rect class="d-sunk" fill="currentColor" x="6" y="424" width="428" height="90" rx="6" /> | |
| 115 | + <rect class="d-soft" fill="none" stroke="currentColor" x="6" y="424" width="428" height="90" rx="6" /> | |
| 116 | + <text class="d-ink" fill="currentColor" x="220" y="444" text-anchor="middle">fleet bucket · the long-term copy</text> | |
| 117 | + | |
| 118 | + <rect class="d-tint" fill="currentColor" x="18" y="454" width="200" height="48" rx="6" /> | |
| 119 | + <rect class="d-acc" fill="none" stroke="currentColor" stroke-width="2" x="18" y="454" width="200" height="48" rx="6" /> | |
| 120 | + <text class="d-ink" fill="currentColor" x="118" y="474" text-anchor="middle">cells/room-7/ltx/e7/</text> | |
| 121 | + <text class="d-soft" fill="currentColor" x="118" y="492" text-anchor="middle">this owner writes here</text> | |
| 122 | + | |
| 123 | + <rect class="d-faint" fill="none" stroke="currentColor" stroke-dasharray="5 4" | |
| 124 | + x="222" y="454" width="200" height="48" rx="6" /> | |
| 125 | + <text class="d-faint" fill="currentColor" x="322" y="474" text-anchor="middle">cells/room-7/ltx/e6/</text> | |
| 126 | + <text class="d-faint" fill="currentColor" x="322" y="492" text-anchor="middle">an old owner is fenced</text> | |
| 127 | +</svg> |
addeddocs/services/durable-objects.md+159−0View file
| @@ -1,0 +1,159 @@ | ||
| 1 | +# Durable Objects / Cells | |
| 2 | + | |
| 3 | +A Durable Object is a single-threaded actor with durable storage, and celld | |
| 4 | +calls each running Durable Object a cell. An application uses one when a piece | |
| 5 | +of state needs a single consistent owner, such as a chat room, a game match, a | |
| 6 | +shopping cart, an agent session, or a rate limiter. The state lives in a SQLite | |
| 7 | +database that belongs to that object alone, on the node that serves it, and | |
| 8 | +celld replicates the database to the fleet. Read the | |
| 9 | +[Cloudflare Durable Objects documentation](https://developers.cloudflare.com/durable-objects/) | |
| 10 | +for the standard API behavior. | |
| 11 | + | |
| 12 | +## Example | |
| 13 | + | |
| 14 | +The [counter example](../../examples/counter) keeps a counter in the key-value | |
| 15 | +storage of a Durable Object, and it uses `idFromName()` to give each name a | |
| 16 | +separate counter. | |
| 17 | + | |
| 18 | +<!-- celld-example: counter --> | |
| 19 | + | |
| 20 | +## Identity and addressing | |
| 21 | + | |
| 22 | +A `durable_objects` binding exposes one class as a namespace, and an | |
| 23 | +application reaches an object in two steps. `env.COUNTER.idFromName("room-7")` | |
| 24 | +returns a `DurableObjectId`, and `env.COUNTER.get(id)` returns a | |
| 25 | +`DurableObjectStub`. `getByName("room-7")` performs both steps together. The | |
| 26 | +stub is only a handle, so celld creates the object at the first call and not at | |
| 27 | +`get()`. Read the | |
| 28 | +[Durable Object ID documentation](https://developers.cloudflare.com/durable-objects/api/id/) | |
| 29 | +for the complete method list. | |
| 30 | + | |
| 31 | +`idFromName()` is deterministic. celld derives the id with HMAC-SHA-256 over | |
| 32 | +the name, under a key that belongs to the namespace, so one name always gives | |
| 33 | +the same 64-digit hexadecimal id. That id always reaches the same object, and | |
| 34 | +two Workers on two different nodes that use one name therefore reach one | |
| 35 | +object. The name also survives in `ctx.id.name` when it is 1024 UTF-8 bytes or | |
| 36 | +less, which is the Cloudflare rule, and a longer name still routes to the | |
| 37 | +correct object. | |
| 38 | + | |
| 39 | +`newUniqueId()` instead draws random bytes, so its object carries no name and | |
| 40 | +no later caller can address it again. Keep the `toString()` form of such an id | |
| 41 | +if the application must reach the object a second time. `idFromString()` parses | |
| 42 | +that hexadecimal form and verifies the HMAC, therefore celld refuses an id that | |
| 43 | +belongs to a different namespace instead of creating an unrelated object. | |
| 44 | + | |
| 45 | +celld builds the key of a namespace from the script name and the class name, so | |
| 46 | +a rename of the Worker script changes every id that the namespace derives. The | |
| 47 | +objects of the old name keep their storage under the old ids, and the renamed | |
| 48 | +script reaches new and empty objects. Keep the script name stable, or migrate | |
| 49 | +the data before the rename. | |
| 50 | + | |
| 51 | +celld implements no jurisdiction, because a celld fleet has only the machines | |
| 52 | +that you run. `newUniqueId({ jurisdiction })` and `namespace.jurisdiction()` | |
| 53 | +throw an error, so an application learns about the gap at the call site. | |
| 54 | + | |
| 55 | +## Ownership and the single-threaded model | |
| 56 | + | |
| 57 | +Cloudflare creates an object near the first request that uses it, and | |
| 58 | +Cloudflare can migrate the object afterwards. celld makes no placement, | |
| 59 | +migration, or jurisdiction promise, and it makes one narrower promise instead: | |
| 60 | +exactly one node serves a cell at a time. | |
| 61 | + | |
| 62 | +A node claims a cell by writing an ownership record into the fleet bucket with | |
| 63 | +a conditional write. The object store accepts only one of two competing | |
| 64 | +writers, so two nodes cannot own one cell. Every activation advances a fencing | |
| 65 | +epoch, and the epoch appears in the storage prefix, therefore a node that lost | |
| 66 | +the cell writes only into a superseded prefix. The | |
| 67 | +[guarantees](../guarantees.md) page gives the full mechanism. | |
| 68 | + | |
| 69 | +A Worker holds its stub on whichever node served the request. celld resolves | |
| 70 | +the owner of the cell and forwards the call to that node, so the object code | |
| 71 | +runs on the owner and nowhere else. Inside the cell, one event runs at a time: | |
| 72 | +a `fetch`, an RPC method, an `alarm()`, or a WebSocket message. celld also | |
| 73 | +holds a response until a durability proof covers every write that the response | |
| 74 | +can reveal, which is the behavior Cloudflare calls the | |
| 75 | +[output gate](https://developers.cloudflare.com/durable-objects/best-practices/rules-of-durable-objects/). | |
| 76 | +An application therefore does not have to `await` a `put()`, because a client | |
| 77 | +cannot receive the response before the write survives a failure. | |
| 78 | + | |
| 79 | + | |
| 80 | + | |
| 81 | +A cell keeps no in-memory state across an eviction. celld removes an idle cell | |
| 82 | +from memory, and the cell then hibernates on its node or becomes inactive in | |
| 83 | +the bucket, so the constructor runs again at the next event. Ownership can move | |
| 84 | +as well, because a node can stop, a node can drain, and idle rebalancing can | |
| 85 | +move a hibernated cell to another node. A reader must therefore treat only | |
| 86 | +durable storage as persistent. A hibernatable WebSocket survives a hibernation | |
| 87 | +on the same node, and it closes when the cell moves to a new owner, so a client | |
| 88 | +must reconnect. Cloudflare gives the same rule for | |
| 89 | +[in-memory state](https://developers.cloudflare.com/durable-objects/reference/in-memory-state/). | |
| 90 | + | |
| 91 | +## Durable storage and alarms | |
| 92 | + | |
| 93 | +`ctx.storage` gives each object its own SQLite database. A class that a | |
| 94 | +`new_sqlite_classes` migration declares can use the key-value methods `get()`, | |
| 95 | +`put()`, `delete()`, `list()`, and `deleteAll()`, and it can also run SQL | |
| 96 | +through `ctx.storage.sql.exec()`. `transaction()` and `transactionSync()` group | |
| 97 | +several writes, and `storage.sync()` waits for the durability of the earlier | |
| 98 | +committed writes. Read the | |
| 99 | +[storage documentation](https://developers.cloudflare.com/durable-objects/best-practices/access-durable-objects-storage/) | |
| 100 | +for the method signatures. | |
| 101 | + | |
| 102 | +The durability of that database comes from the fleet, not from a managed | |
| 103 | +service. celld captures each write as an LTX segment and replicates the segment | |
| 104 | +to `cells/<cell>/ltx/e<epoch>/` in the fleet bucket. A fleet of two or more | |
| 105 | +nodes is faster, because the owner also sends each write to one or two follower | |
| 106 | +nodes and answers as soon as a follower holds the write on its own disk. The | |
| 107 | +bucket upload follows afterwards. A single node has no follower, so every write | |
| 108 | +on it waits for the object store instead. | |
| 109 | + | |
| 110 | +`storage.setAlarm()` schedules one alarm per object, `getAlarm()` reads it, and | |
| 111 | +`deleteAlarm()` removes it. celld calls the `alarm(alarmInfo)` handler at the | |
| 112 | +scheduled time and passes `retryCount` and `isRetry`, as the | |
| 113 | +[Alarms API](https://developers.cloudflare.com/durable-objects/api/alarms/) | |
| 114 | +describes. celld does not answer a successful response until a durable wake | |
| 115 | +entry in the bucket covers the alarm, so a crash cannot lose a schedule that a | |
| 116 | +client already saw. A hibernated cell fires its alarm on the node that owns it. | |
| 117 | +One node in the fleet holds the waker role, and it wakes only a cell whose | |
| 118 | +owner node stopped, so the alarm work of the fleet does not queue on one | |
| 119 | +machine. | |
| 120 | + | |
| 121 | +## Differences from Cloudflare | |
| 122 | + | |
| 123 | +- celld makes no placement, migration, or jurisdiction promise. A cell runs on | |
| 124 | + a node of your fleet, and `newUniqueId({ jurisdiction })` and | |
| 125 | + `namespace.jurisdiction()` throw. | |
| 126 | +- The key of a namespace contains the script name, so a rename of the script | |
| 127 | + changes every id that `idFromName()` derives. | |
| 128 | +- A `migrations` entry accepts `tag` and `new_sqlite_classes` only. A class | |
| 129 | + rename, a class delete, and a class transfer stop the deployment. | |
| 130 | +- A Durable Object event keeps pending I/O active after the handler returns, so | |
| 131 | + a timer or a subrequest does not require `ctx.waitUntil()`. | |
| 132 | +- The imported `waitUntil()` and `ctx.waitUntil()` can add work while previously | |
| 133 | + registered background work remains active. | |
| 134 | +- An RPC stub cannot cross an isolate boundary. See | |
| 135 | + [RPC](../cloudflare-compat.md#rpc). | |
| 136 | +- An outbound WebSocket does not continue after the object moves to another | |
| 137 | + node. | |
| 138 | +- celld refuses invalid UTF-8 from a SQLite `TEXT` value. Store arbitrary bytes | |
| 139 | + in a `BLOB`. | |
| 140 | +- `SqlStorage.Cursor.toArray()` gives a celld-specific error near the V8 heap | |
| 141 | + limit. | |
| 142 | +- `storage.sync()` waits for the object store or the fleet ensemble to hold all | |
| 143 | + earlier committed writes. The operation uses the shorter of the 10-second | |
| 144 | + `CELLD_LTX_DURABILITY_TIMEOUT_SECS` default and the 15-second | |
| 145 | + `CELLD_OPERATION_DEADLINE_MS` default. | |
| 146 | +- `storage.sync()` rejects during an open transaction and after an object abort. | |
| 147 | + Without an object store, it resolves after the local commit. | |
| 148 | +- A transaction and `blockConcurrencyWhile()` have a 30-second limit. A timeout | |
| 149 | + resets the object and rolls back an open transaction. | |
| 150 | +- A failed handler still waits for the durability of any value or write that it | |
| 151 | + can expose. A celld-generated failure that exposes no object value returns | |
| 152 | + immediately. | |
| 153 | +- Outside an explicit transaction, a SQL write cursor must finish before a | |
| 154 | + response, an outbound effect, or `storage.sync()`. An unfinished `RETURNING` | |
| 155 | + cursor holds uncommitted writes, so celld rejects that output with an error. | |
| 156 | + A read cursor can remain open. | |
| 157 | + | |
| 158 | +The [Cloudflare compatibility](../cloudflare-compat.md#services) page | |
| 159 | +lists the runtime APIs and the unsupported services. |
addeddocs/services/dynamic-workers-flow.svg+106−0View file
| @@ -1,0 +1,106 @@ | ||
| 1 | +<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 440 600" role="img" aria-labelledby="dwFlowTitle dwFlowDesc"> | |
| 2 | + <title id="dwFlowTitle">What a loader grants a Dynamic Worker, and what it withholds</title> | |
| 3 | + <desc id="dwFlowDesc">One celld node runs one process that holds two V8 isolates, and not two machines and not a virtual machine. The host Worker isolate holds the deployment's bindings, vars, and secrets, and it calls env.LOADER.get(id, getCode), whose getCode runs once per id in that isolate. Only two things cross the boundary into the loaded isolate: the modules map with its mainModule, at most 64 MiB and compiled once, and the env and props values, which carry structured-clone values and capabilities up to 1 MiB. Everything else stops at the boundary: the deployment's KV, D1, R2, Queues, and Durable Object bindings, its vars and secrets, a Worker Loader binding of its own, and the host's globals and host ops. The loaded Worker isolate therefore has no ambient binding, and env is the whole of its reach. A capability call returns to the host isolate as an RPC, which is the only path back. Below, globalOutbound decides what the loaded code can dial: unspecified inherits the host's egress policy, null makes fetch() and connect() throw, and a Fetcher brokers fetch() while connect() and a WebSocket are refused.</desc> | |
| 4 | + <style> | |
| 5 | + svg { font-family: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Helvetica, Arial, sans-serif; } | |
| 6 | + text { font-size: 13px; fill: currentColor; } | |
| 7 | + tspan { fill: currentColor; } | |
| 8 | + .mono { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; font-size: 12px; } | |
| 9 | + .lead { font-weight: 600; } | |
| 10 | + .d-ink { color: #121212; } | |
| 11 | + .d-soft { color: #3d3b37; } | |
| 12 | + .d-faint { color: #6e6a62; } | |
| 13 | + .d-acc { color: #10803f; } | |
| 14 | + .d-panel { color: #ffffff; } | |
| 15 | + .d-sunk { color: #f0eee8; } | |
| 16 | + .d-tint { color: #d6efdf; } | |
| 17 | + @media (prefers-color-scheme: dark) { | |
| 18 | + .d-ink { color: #efede7; } | |
| 19 | + .d-soft { color: #c9c6be; } | |
| 20 | + .d-faint { color: #928e85; } | |
| 21 | + .d-acc { color: #3fc472; } | |
| 22 | + .d-panel { color: #1a1a19; } | |
| 23 | + .d-sunk { color: #232321; } | |
| 24 | + .d-tint { color: #10301d; } | |
| 25 | + } | |
| 26 | + </style> | |
| 27 | + <defs> | |
| 28 | + <marker id="dw-arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="6" | |
| 29 | + markerHeight="6" orient="auto-start-reverse"> | |
| 30 | + <path class="d-soft" fill="currentColor" d="M0 0 L10 5 L0 10 z" /> | |
| 31 | + </marker> | |
| 32 | + </defs> | |
| 33 | + | |
| 34 | + <!-- Both isolates live in one process on one node. The picture says how | |
| 35 | + strong the boundary is, because the prose cannot show its scale. --> | |
| 36 | + <rect class="d-sunk" fill="currentColor" x="8" y="8" width="424" height="444" rx="12" /> | |
| 37 | + <rect class="d-faint" fill="none" stroke="currentColor" x="8" y="8" width="424" height="444" rx="12" /> | |
| 38 | + <text class="d-ink lead" fill="currentColor" x="24" y="34">One celld node, one process</text> | |
| 39 | + <text class="d-faint" fill="currentColor" x="24" y="54">two V8 isolates, not two machines and not a virtual machine</text> | |
| 40 | + | |
| 41 | + <rect class="d-panel" fill="currentColor" x="22" y="68" width="372" height="104" rx="8" /> | |
| 42 | + <rect class="d-faint" fill="none" stroke="currentColor" x="22" y="68" width="372" height="104" rx="8" /> | |
| 43 | + <text class="d-faint" fill="currentColor" x="34" y="92">Host Worker isolate</text> | |
| 44 | + <text class="d-ink mono" fill="currentColor" x="34" y="114">MY_KV MY_DB MY_BUCKET vars secrets</text> | |
| 45 | + <text class="d-acc mono" fill="currentColor" x="34" y="140">env.LOADER.get(id, getCode)</text> | |
| 46 | + <text class="d-faint" fill="currentColor" x="34" y="160">getCode runs once per id in this isolate</text> | |
| 47 | + | |
| 48 | + <!-- One arrow crosses; the other stops at a bar. The contrast is the fact. --> | |
| 49 | + <g class="d-soft" fill="none" stroke="currentColor" stroke-width="1.5"> | |
| 50 | + <path d="M114 172 V196" marker-end="url(#dw-arrow)" /> | |
| 51 | + </g> | |
| 52 | + <g class="d-faint" fill="none" stroke="currentColor" stroke-width="1.5"> | |
| 53 | + <path d="M302 172 V188" /> | |
| 54 | + <path d="M288 192 H316" stroke-width="2.5" /> | |
| 55 | + </g> | |
| 56 | + | |
| 57 | + <rect class="d-tint" fill="currentColor" x="22" y="200" width="184" height="142" rx="8" /> | |
| 58 | + <rect class="d-acc" fill="none" stroke="currentColor" stroke-width="2" x="22" y="200" width="184" height="142" rx="8" /> | |
| 59 | + <text class="d-acc lead" fill="currentColor" x="34" y="224">crosses the boundary</text> | |
| 60 | + <text class="d-ink mono" fill="currentColor" x="34" y="248">modules, mainModule</text> | |
| 61 | + <text class="d-faint" fill="currentColor" x="34" y="266">64 MiB, compiled once</text> | |
| 62 | + <text class="d-ink mono" fill="currentColor" x="34" y="292">env, props</text> | |
| 63 | + <text class="d-faint" fill="currentColor" x="34" y="310">structured-clone values</text> | |
| 64 | + <text class="d-faint" fill="currentColor" x="34" y="328">and capabilities, 1 MiB</text> | |
| 65 | + | |
| 66 | + <rect class="d-panel" fill="currentColor" x="210" y="200" width="184" height="142" rx="8" /> | |
| 67 | + <rect class="d-faint" fill="none" stroke="currentColor" stroke-dasharray="5 4" | |
| 68 | + x="210" y="200" width="184" height="142" rx="8" /> | |
| 69 | + <text class="d-faint lead" fill="currentColor" x="222" y="224">stays in the host</text> | |
| 70 | + <text class="d-soft" fill="currentColor" x="222" y="248">KV, D1, R2, Queues,</text> | |
| 71 | + <text class="d-soft" fill="currentColor" x="222" y="266">and Durable Objects</text> | |
| 72 | + <text class="d-soft" fill="currentColor" x="222" y="292">vars and secrets</text> | |
| 73 | + <text class="d-soft" fill="currentColor" x="222" y="310">a Worker Loader binding</text> | |
| 74 | + <text class="d-soft" fill="currentColor" x="222" y="328">the host's globals, ops</text> | |
| 75 | + | |
| 76 | + <g class="d-soft" fill="none" stroke="currentColor" stroke-width="1.5"> | |
| 77 | + <path d="M114 342 V356" marker-end="url(#dw-arrow)" /> | |
| 78 | + </g> | |
| 79 | + | |
| 80 | + <rect class="d-panel" fill="currentColor" x="22" y="360" width="372" height="76" rx="8" /> | |
| 81 | + <rect class="d-acc" fill="none" stroke="currentColor" stroke-width="2" x="22" y="360" width="372" height="76" rx="8" /> | |
| 82 | + <text class="d-faint" fill="currentColor" x="34" y="384">Loaded Worker isolate</text> | |
| 83 | + <text class="d-ink" fill="currentColor" x="34" y="406">no ambient binding: env is the whole of its reach</text> | |
| 84 | + <text class="d-soft" fill="currentColor" x="34" y="426">a capability call is an RPC back to the host</text> | |
| 85 | + | |
| 86 | + <!-- The only path back into the host isolate. --> | |
| 87 | + <g class="d-acc" fill="none" stroke="currentColor" stroke-width="1.5"> | |
| 88 | + <path d="M394 400 C 424 400 424 130 398 130" marker-end="url(#dw-arrow)" /> | |
| 89 | + </g> | |
| 90 | + | |
| 91 | + <g class="d-soft" fill="none" stroke="currentColor" stroke-width="1.5"> | |
| 92 | + <path d="M220 452 V464" marker-end="url(#dw-arrow)" /> | |
| 93 | + </g> | |
| 94 | + | |
| 95 | + <!-- Egress is a third state, and celld's answer differs per protocol. --> | |
| 96 | + <rect class="d-panel" fill="currentColor" x="8" y="468" width="424" height="124" rx="8" /> | |
| 97 | + <rect class="d-faint" fill="none" stroke="currentColor" x="8" y="468" width="424" height="124" rx="8" /> | |
| 98 | + <text class="d-ink lead" fill="currentColor" x="24" y="492">globalOutbound decides what the loaded code can dial</text> | |
| 99 | + <text class="d-soft mono" fill="currentColor" x="24" y="516">unspecified</text> | |
| 100 | + <text class="d-soft" fill="currentColor" x="150" y="516">inherits the host's egress policy</text> | |
| 101 | + <text class="d-soft mono" fill="currentColor" x="24" y="538">null</text> | |
| 102 | + <text class="d-soft" fill="currentColor" x="150" y="538">fetch() and connect() throw</text> | |
| 103 | + <text class="d-acc mono" fill="currentColor" x="24" y="560">a Fetcher</text> | |
| 104 | + <text class="d-soft" fill="currentColor" x="150" y="560">brokers fetch()</text> | |
| 105 | + <text class="d-faint" fill="currentColor" x="150" y="578">connect() and a WebSocket are refused</text> | |
| 106 | +</svg> |
addeddocs/services/dynamic-workers.md+151−0View file
| @@ -1,0 +1,151 @@ | ||
| 1 | +# Dynamic Workers | |
| 2 | + | |
| 3 | +A Dynamic Worker is Worker code that a running Worker supplies at runtime and | |
| 4 | +loads through a Worker Loader binding. An application uses one for code that it | |
| 5 | +does not write itself: code that a customer uploads, or code that a model | |
| 6 | +writes. celld compiles that code into a separate V8 isolate on the node that | |
| 7 | +runs the loader, and it gives the loaded Worker no binding of its own, so the | |
| 8 | +loader hands over every capability that the loaded code can use, and the | |
| 9 | +durable state stays behind in the loader's own bindings. Cloudflare runs this | |
| 10 | +feature in an | |
| 11 | +[open beta](https://developers.cloudflare.com/changelog/post/2026-03-24-dynamic-workers-open-beta/), | |
| 12 | +therefore the API can still change. Read the | |
| 13 | +[Cloudflare Dynamic Workers documentation](https://developers.cloudflare.com/dynamic-workers/) | |
| 14 | +for the standard API behavior. | |
| 15 | + | |
| 16 | +## Example | |
| 17 | + | |
| 18 | +The [Dynamic Workers example](../../examples/dynamic-worker-tails) loads a | |
| 19 | +Worker and sends its invocation records to a Tail Worker. | |
| 20 | + | |
| 21 | +<!-- celld-example: dynamic-worker-tails --> | |
| 22 | + | |
| 23 | +## Loading a Worker | |
| 24 | + | |
| 25 | +A `worker_loaders` entry in the Wrangler configuration adds the binding, and | |
| 26 | +the example names it `LOADER`. Wrangler accepts only the `binding` name in | |
| 27 | +this entry, so set `tails` in a `WorkerCode` object and set `limits` there or | |
| 28 | +in a `getEntrypoint()` call. celld stops the deployment when the entry | |
| 29 | +contains either option. `env.LOADER.get(id, getCode)` gives a loaded | |
| 30 | +Worker a string id, and `env.LOADER.load(code)` loads an anonymous one. celld | |
| 31 | +calls `getCode` only when it must compile, so the callback can read the code | |
| 32 | +from a store, and it can be asynchronous. A throw inside `getCode` therefore | |
| 33 | +surfaces when the application first uses the Worker, and not at the `get()` | |
| 34 | +call. | |
| 35 | + | |
| 36 | +`getCode` returns a `WorkerCode` object. `mainModule` names the entry module, | |
| 37 | +and `modules` maps each module name to its source. A value in that map can also | |
| 38 | +be wasm bytes, and the [WebAssembly page](../wasm.md#dynamic-workers) shows | |
| 39 | +that form. `compatibilityDate` and `compatibilityFlags` select the runtime | |
| 40 | +behavior of the loaded Worker, and celld reads both. The module sources can | |
| 41 | +total 64 MiB, which is the workerd limit. A `WorkerCode.limits` object can | |
| 42 | +set `cpuMs` and `subRequests` for each invocation. celld refuses a | |
| 43 | +`WorkerCode` that sets `allowExperimental`. Read the | |
| 44 | +[API reference](https://developers.cloudflare.com/dynamic-workers/api-reference/) | |
| 45 | +for the complete shape. | |
| 46 | + | |
| 47 | +The stub that `get()` and `load()` return invokes the loaded code. | |
| 48 | +`getEntrypoint(name, options)` gives a Fetcher for the default export or for a | |
| 49 | +named `WorkerEntrypoint`, and `getDurableObjectClass(name, options)` gives a | |
| 50 | +Durable Object class. Both accept a `props` option. `getEntrypoint()` also | |
| 51 | +accepts `limits` for its fetch and RPC calls. celld uses the lower value for | |
| 52 | +each limit when both the `WorkerCode` object and the call set it. The | |
| 53 | +`getDurableObjectClass()` options accept only `props`. | |
| 54 | + | |
| 55 | +## The isolation boundary | |
| 56 | + | |
| 57 | +celld compiles the loaded code into its own V8 isolate, with its own context | |
| 58 | +and its own heap. That isolate runs in the same process as the loader, on the | |
| 59 | +same node. It is not a second process and it is not a virtual machine, so the | |
| 60 | +boundary scopes what the loaded code can address, and it is not a claim about | |
| 61 | +V8 escape safety. Run the code in a container under a named runtime when the | |
| 62 | +workload needs a kernel boundary, and read | |
| 63 | +[the isolation boundary](containers.md#the-isolation-boundary) on the | |
| 64 | +Containers page. | |
| 65 | + | |
| 66 | +celld builds the loaded Worker with an empty binding set. It carries no KV | |
| 67 | +namespace, no D1 database, no R2 bucket, no queue, no Workflow, no Durable | |
| 68 | +Object class, and no `vars` entry of the deployment. It also carries no Worker | |
| 69 | +Loader binding, so a loaded Worker cannot load another one. The loaded code | |
| 70 | +therefore reaches only the `env` that the `WorkerCode` supplies. That `env` | |
| 71 | +takes structured-clone values and Service Binding capabilities, and Cloudflare | |
| 72 | +gives the same | |
| 73 | +[capability rule](https://developers.cloudflare.com/dynamic-workers/usage/bindings/). | |
| 74 | +A capability call leaves the loaded isolate as an RPC into the loader's | |
| 75 | +isolate, so the loader keeps control of what the call does. | |
| 76 | + | |
| 77 | + | |
| 78 | + | |
| 79 | +The runtime internals stay out of reach as well. celld passes each host | |
| 80 | +operation to its internal scripts as a function parameter and never as a | |
| 81 | +global, so loaded code cannot find one by reading `globalThis`. A loaded Worker | |
| 82 | +once reached the host through such a global, and the parameter form closed that | |
| 83 | +path. | |
| 84 | + | |
| 85 | +`globalOutbound` decides what the loaded code can dial. celld gives the loaded | |
| 86 | +Worker the loader's own egress policy when the `WorkerCode` omits the field, so | |
| 87 | +a deployed Worker with Internet access passes that access on. A `null` value | |
| 88 | +removes every ambient connection instead, and `fetch()` and `connect()` both | |
| 89 | +throw, which leaves an `env` capability as the only way out. A Fetcher | |
| 90 | +brokers each `fetch()` through the loader, which can read the request, change | |
| 91 | +it, or refuse it. celld does not broker a `connect()` or a WebSocket through a | |
| 92 | +Fetcher, and each of those throws, because celld's service protocol carries no | |
| 93 | +bidirectional tunnel and a direct socket would pass the broker in silence. Read | |
| 94 | +the | |
| 95 | +[egress control documentation](https://developers.cloudflare.com/dynamic-workers/usage/egress-control/) | |
| 96 | +for the Cloudflare behavior. | |
| 97 | + | |
| 98 | +## Lifetime and caching | |
| 99 | + | |
| 100 | +`get(id, getCode)` memoizes the load by id inside one loader binding of one | |
| 101 | +host isolate. The first use of an id runs `getCode` and compiles the modules, | |
| 102 | +and a later use of that id in the same isolate reuses the compiled isolate and | |
| 103 | +runs no callback, so module scope survives between the two calls. Another | |
| 104 | +isolate holds its own map. A request that a different node serves, or a fresh | |
| 105 | +isolate on the same node, therefore pays the compile again. Two `worker_loaders` | |
| 106 | +entries are two maps as well, so the same id in each one loads twice. | |
| 107 | +Cloudflare describes the same reuse as a possibility and not as a guarantee. | |
| 108 | + | |
| 109 | +`load(code)` caches nothing and compiles on each call. Its isolate goes away | |
| 110 | +when the application disposes the stub, and a garbage collection of an | |
| 111 | +undisposed stub drops it as a backstop. A `get()` stub instead stays in the | |
| 112 | +memo map, so its loaded isolate lives as long as the loader's isolate does. | |
| 113 | + | |
| 114 | +Every loaded Worker belongs to the isolate that created it. celld drops all of | |
| 115 | +them when that isolate retires, which happens when the request load falls or | |
| 116 | +when a new deployment supersedes the script. An in-flight call finishes first. | |
| 117 | +A loaded Worker therefore never outlives its loader, and a redeploy compiles | |
| 118 | +the code again. | |
| 119 | + | |
| 120 | +A process holds at most 256 live Dynamic Workers, and one generation of one | |
| 121 | +script holds at most 255 of them. The last slot stays reserved, so a single | |
| 122 | +runaway loader cannot take the whole process. A load over either limit throws. | |
| 123 | + | |
| 124 | +## Differences from Cloudflare | |
| 125 | + | |
| 126 | +- The process limit is 256 live Dynamic Workers, and each script generation can | |
| 127 | + use 255 slots. Every loader and script shares the process limit. | |
| 128 | +- The process rejects the removed `CELLD_MAX_LOADED_WORKERS` environment | |
| 129 | + variable. | |
| 130 | +- `getEntrypoint()` supports `props` and `limits` options, while | |
| 131 | + `getDurableObjectClass()` supports only `props`. A structured-clone encoded | |
| 132 | + `props` value can be at most 1 MiB. | |
| 133 | +- A `globalOutbound` Fetcher cannot use `connect()` or a WebSocket. | |
| 134 | +- A `WorkerCode.tails` array accepts Service Binding Fetchers. Each Fetcher | |
| 135 | + receives one event after a Dynamic Worker fetch invocation finishes. | |
| 136 | +- The event contains the request metadata, the response status, the console | |
| 137 | + logs, the uncaught exception, and the invocation outcome. | |
| 138 | +- celld records at most 256 KiB of serialized console log records for each | |
| 139 | + invocation. It stops recording when the next complete record exceeds this | |
| 140 | + limit. | |
| 141 | +- Tail delivery starts after the response is available. A Tail Worker failure | |
| 142 | + does not change the response, and celld writes the failure to the console. | |
| 143 | +- celld enforces `cpuMs` and `subRequests` in `WorkerCode.limits` and in a | |
| 144 | + `getEntrypoint()` call. It rejects `allowExperimental`. | |
| 145 | +- `WorkerCode.env` accepts structured-clone values and Service Binding | |
| 146 | + capabilities. The encoded values and the capability props can total 1 MiB. | |
| 147 | +- A loaded Worker entrypoint cannot transfer to another Worker. Awaitable and | |
| 148 | + pipelined properties are also unavailable. | |
| 149 | + | |
| 150 | +The [Cloudflare compatibility](../cloudflare-compat.md#services) page | |
| 151 | +lists the runtime APIs and the unsupported services. |
addeddocs/services/kv-flow.svg+102−0View file
| @@ -1,0 +1,102 @@ | ||
| 1 | +<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 440 322" role="img" aria-labelledby="kvFlowTitle kvFlowDesc"> | |
| 2 | + <title id="kvFlowTitle">Each namespace resolves to one cell with one owner node and one writer</title> | |
| 3 | + <desc id="kvFlowDesc">Workers on nodes A, B, and C call two namespaces. The calls cross an empty | |
| 4 | +dashed layer, marked as the place where celld holds no cache, and reach two | |
| 5 | +namespace cells. The VALUES cell has owner node B and one writer, and the | |
| 6 | +SESSIONS cell has owner node C and one writer, so a second namespace adds a | |
| 7 | +second writer. Under the VALUES cell, a value of 1 MiB or less goes to an inline | |
| 8 | +row and a larger value goes to the fleet bucket. Every namespace splits the same | |
| 9 | +way.</desc> | |
| 10 | + <style> | |
| 11 | + .d-ink { color: #121212 } | |
| 12 | + .d-soft { color: #3d3b37 } | |
| 13 | + .d-faint { color: #6e6a62 } | |
| 14 | + .d-acc { color: #10803f } | |
| 15 | + .d-panel { color: #ffffff } | |
| 16 | + .d-sunk { color: #f0eee8 } | |
| 17 | + .d-tint { color: #d6efdf } | |
| 18 | + text { | |
| 19 | + font-family: ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif; | |
| 20 | + font-size: 13px; | |
| 21 | + fill: currentColor; | |
| 22 | + } | |
| 23 | + @media (prefers-color-scheme: dark) { | |
| 24 | + .d-ink { color: #efede7 } | |
| 25 | + .d-soft { color: #c9c6be } | |
| 26 | + .d-faint { color: #928e85 } | |
| 27 | + .d-acc { color: #3fc472 } | |
| 28 | + .d-panel { color: #1a1a19 } | |
| 29 | + .d-sunk { color: #232321 } | |
| 30 | + .d-tint { color: #10301d } | |
| 31 | + } | |
| 32 | + </style> | |
| 33 | + <defs> | |
| 34 | + <marker id="kv-arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="6" | |
| 35 | + markerHeight="6" orient="auto-start-reverse"> | |
| 36 | + <path class="d-soft" fill="currentColor" d="M0 0 L10 5 L0 10 z" /> | |
| 37 | + </marker> | |
| 38 | + </defs> | |
| 39 | + | |
| 40 | + <!-- Callers: three nodes, two namespaces, reads and writes together. --> | |
| 41 | + <rect class="d-panel" fill="currentColor" x="6" y="8" width="136" height="48" rx="6" /> | |
| 42 | + <rect class="d-soft" fill="none" stroke="currentColor" x="6" y="8" width="136" height="48" rx="6" /> | |
| 43 | + <text class="d-ink" fill="currentColor" x="74" y="29" text-anchor="middle">Worker · node A</text> | |
| 44 | + <text class="d-soft" fill="currentColor" x="74" y="46" text-anchor="middle">VALUES.get()</text> | |
| 45 | + | |
| 46 | + <rect class="d-panel" fill="currentColor" x="152" y="8" width="136" height="48" rx="6" /> | |
| 47 | + <rect class="d-soft" fill="none" stroke="currentColor" x="152" y="8" width="136" height="48" rx="6" /> | |
| 48 | + <text class="d-ink" fill="currentColor" x="220" y="29" text-anchor="middle">Worker · node B</text> | |
| 49 | + <text class="d-soft" fill="currentColor" x="220" y="46" text-anchor="middle">VALUES.put()</text> | |
| 50 | + | |
| 51 | + <rect class="d-panel" fill="currentColor" x="298" y="8" width="136" height="48" rx="6" /> | |
| 52 | + <rect class="d-soft" fill="none" stroke="currentColor" x="298" y="8" width="136" height="48" rx="6" /> | |
| 53 | + <text class="d-ink" fill="currentColor" x="366" y="29" text-anchor="middle">Worker · node C</text> | |
| 54 | + <text class="d-soft" fill="currentColor" x="366" y="46" text-anchor="middle">SESSIONS.put()</text> | |
| 55 | + | |
| 56 | + <!-- The layer Cloudflare fills with a cache, and celld leaves empty. --> | |
| 57 | + <rect class="d-faint" fill="none" stroke="currentColor" stroke-dasharray="5 4" | |
| 58 | + x="6" y="76" width="428" height="48" rx="6" /> | |
| 59 | + <text class="d-faint" fill="currentColor" x="220" y="96" text-anchor="middle">no cache layer</text> | |
| 60 | + <text class="d-faint" fill="currentColor" x="220" y="114" text-anchor="middle">every call reaches the owner cell</text> | |
| 61 | + | |
| 62 | + <!-- The two callers of one namespace join; the third goes elsewhere. --> | |
| 63 | + <g class="d-soft" fill="none" stroke="currentColor" stroke-width="1.5"> | |
| 64 | + <path d="M74 56 V70" /> | |
| 65 | + <path d="M220 56 V70" /> | |
| 66 | + <path d="M60 70 H220" /> | |
| 67 | + <path d="M60 70 V142" marker-end="url(#kv-arrow)" /> | |
| 68 | + <path d="M366 56 V70 H380 V142" marker-end="url(#kv-arrow)" /> | |
| 69 | + </g> | |
| 70 | + | |
| 71 | + <!-- One namespace, one cell, one writer. A second namespace, a second writer. --> | |
| 72 | + <rect class="d-tint" fill="currentColor" x="16" y="146" width="200" height="72" rx="6" /> | |
| 73 | + <rect class="d-acc" fill="none" stroke="currentColor" stroke-width="2" x="16" y="146" width="200" height="72" rx="6" /> | |
| 74 | + <text class="d-ink" fill="currentColor" x="116" y="169" text-anchor="middle">VALUES cell</text> | |
| 75 | + <text class="d-soft" fill="currentColor" x="116" y="188" text-anchor="middle">owner: node B</text> | |
| 76 | + <text class="d-soft" fill="currentColor" x="116" y="207" text-anchor="middle">one writer</text> | |
| 77 | + | |
| 78 | + <rect class="d-tint" fill="currentColor" x="224" y="146" width="200" height="72" rx="6" /> | |
| 79 | + <rect class="d-acc" fill="none" stroke="currentColor" stroke-width="2" x="224" y="146" width="200" height="72" rx="6" /> | |
| 80 | + <text class="d-ink" fill="currentColor" x="324" y="169" text-anchor="middle">SESSIONS cell</text> | |
| 81 | + <text class="d-soft" fill="currentColor" x="324" y="188" text-anchor="middle">owner: node C</text> | |
| 82 | + <text class="d-soft" fill="currentColor" x="324" y="207" text-anchor="middle">one writer</text> | |
| 83 | + | |
| 84 | + <!-- Inside a cell, the value size selects the store. --> | |
| 85 | + <g class="d-soft" fill="none" stroke="currentColor" stroke-width="1.5"> | |
| 86 | + <path d="M70 218 V240 H65 V262" marker-end="url(#kv-arrow)" /> | |
| 87 | + <path d="M162 218 V240 H167 V262" marker-end="url(#kv-arrow)" /> | |
| 88 | + </g> | |
| 89 | + | |
| 90 | + <rect class="d-sunk" fill="currentColor" x="16" y="266" width="98" height="46" rx="6" /> | |
| 91 | + <rect class="d-soft" fill="none" stroke="currentColor" x="16" y="266" width="98" height="46" rx="6" /> | |
| 92 | + <text class="d-ink" fill="currentColor" x="65" y="287" text-anchor="middle">inline row</text> | |
| 93 | + <text class="d-soft" fill="currentColor" x="65" y="304" text-anchor="middle">1 MiB or less</text> | |
| 94 | + | |
| 95 | + <rect class="d-sunk" fill="currentColor" x="118" y="266" width="98" height="46" rx="6" /> | |
| 96 | + <rect class="d-soft" fill="none" stroke="currentColor" x="118" y="266" width="98" height="46" rx="6" /> | |
| 97 | + <text class="d-ink" fill="currentColor" x="167" y="287" text-anchor="middle">fleet bucket</text> | |
| 98 | + <text class="d-soft" fill="currentColor" x="167" y="304" text-anchor="middle">above 1 MiB</text> | |
| 99 | + | |
| 100 | + <text class="d-faint" fill="currentColor" x="324" y="287" text-anchor="middle">every namespace splits</text> | |
| 101 | + <text class="d-faint" fill="currentColor" x="324" y="304" text-anchor="middle">the same way</text> | |
| 102 | +</svg> |
addeddocs/services/kv.md+107−0View file
| @@ -1,0 +1,107 @@ | ||
| 1 | +# KV | |
| 2 | + | |
| 3 | +KV is a key-value store that an application accesses through a binding. A | |
| 4 | +Worker reads a value with `env.NAMESPACE.get()`, and it writes one with | |
| 5 | +`env.NAMESPACE.put()`. An application uses KV for data that many requests read | |
| 6 | +and few requests change, such as a feature flag, a redirect table, or a | |
| 7 | +configuration document. Each namespace lives in one celld cell, and a value | |
| 8 | +above 1 MiB lives in the fleet bucket. Read the | |
| 9 | +[Cloudflare KV documentation](https://developers.cloudflare.com/kv/api/) for the | |
| 10 | +standard API behavior. | |
| 11 | + | |
| 12 | +## Example | |
| 13 | + | |
| 14 | +The [KV example](../../examples/kv) reads, writes, and deletes values in a KV | |
| 15 | +namespace. | |
| 16 | + | |
| 17 | +<!-- celld-example: kv --> | |
| 18 | + | |
| 19 | +## Namespaces, keys, and values | |
| 20 | + | |
| 21 | +A project declares a namespace with a `kv_namespaces` entry that gives a | |
| 22 | +`binding` name and an `id`. celld uses the `id` as the namespace identity, | |
| 23 | +whatever string it holds, so a hexadecimal id from Cloudflare and a plain name | |
| 24 | +such as `sessions` both work. A namespace belongs to the fleet and not to one | |
| 25 | +script, so two Workers that name one `id` reach one namespace. celld accepts | |
| 26 | +`preview_id` and ignores it, because celld does not run `wrangler dev`. | |
| 27 | + | |
| 28 | +`put()` accepts a string, an `ArrayBuffer`, a typed array, or a | |
| 29 | +`ReadableStream`, and celld copies the bytes at the call so a later change to | |
| 30 | +the buffer cannot alter the stored value. celld reads a stream to its end | |
| 31 | +before the write, therefore `put(key, request.body)` stores a request body. | |
| 32 | +`get()` returns the value as `"text"`, `"json"`, `"arrayBuffer"`, or | |
| 33 | +`"stream"`. `getWithMetadata()` also returns the metadata that the write | |
| 34 | +attached, and a missing key gives `null` in both methods. `list()` returns at | |
| 35 | +most 1000 key names in byte order, and its cursor resumes after the last | |
| 36 | +returned name, so a concurrent write cannot make the pagination skip a key. | |
| 37 | + | |
| 38 | +celld enforces the | |
| 39 | +[Cloudflare KV limits](https://developers.cloudflare.com/kv/platform/limits/): a | |
| 40 | +key of at most 512 bytes, a value of at most 25 MiB, and serialized metadata of | |
| 41 | +at most 1024 bytes. One bulk `get()` takes at most 100 keys. celld refuses a | |
| 42 | +call that crosses a limit instead of truncating the data, so the application | |
| 43 | +learns about the problem at the call site. | |
| 44 | + | |
| 45 | +A write can set `expiration` as an absolute time in seconds, or `expirationTtl` | |
| 46 | +as a count of seconds from now. The minimum lifetime is 60 seconds. celld | |
| 47 | +filters an expired key on the read path, so the key becomes invisible at the | |
| 48 | +moment it expires, and a sweeper reclaims the storage afterwards. | |
| 49 | + | |
| 50 | +## The read and write path | |
| 51 | + | |
| 52 | +A Cloudflare namespace is | |
| 53 | +[a database that replicates to the global network](https://developers.cloudflare.com/kv/concepts/kv-namespaces/), | |
| 54 | +and each location caches the values that it reads. celld has no such cache. A | |
| 55 | +celld namespace is one cell, which is the same single-threaded actor that runs a | |
| 56 | +Durable Object, so the namespace state lives in that cell's SQLite database. | |
| 57 | +Every call reaches the node that owns the cell, therefore a celld read returns | |
| 58 | +the committed value and is never stale. | |
| 59 | + | |
| 60 | + | |
| 61 | + | |
| 62 | +One cell owns a namespace, and a cell has one writer. Two writes to one | |
| 63 | +namespace therefore run one after the other, even when they touch different | |
| 64 | +keys. More nodes do not divide that work, because the namespace has one owner. | |
| 65 | +An application that needs more write capacity splits its keys across more | |
| 66 | +namespaces, because KV has no operation that spans two keys. | |
| 67 | + | |
| 68 | +Reads and writes cost different amounts. A write commits to the cell's SQLite | |
| 69 | +database and replicates to the fleet, so it pays for durability every time. A | |
| 70 | +read only answers from the committed state. This asymmetry makes KV a good | |
| 71 | +choice for configuration data that a Worker reads on every request, and a poor | |
| 72 | +choice for a counter that many requests increment. Use a Durable Object for a | |
| 73 | +write-hot value, which is the same advice that | |
| 74 | +[Cloudflare gives](https://developers.cloudflare.com/kv/concepts/how-kv-works/). | |
| 75 | + | |
| 76 | +A read also has a cost in celld that it does not have on Cloudflare. Cloudflare | |
| 77 | +answers a hot key from a cache in the location that serves the request. celld | |
| 78 | +sends every `get()` to the owner node, so a read costs one cell dispatch. An | |
| 79 | +application that reads one key many times inside one request must hold the value | |
| 80 | +in a local variable. | |
| 81 | + | |
| 82 | +## A value above the inline limit | |
| 83 | + | |
| 84 | +celld keeps a value of 1 MiB or less inside the cell, because such a value | |
| 85 | +replicates with the cell's other writes. A larger value goes to the fleet bucket | |
| 86 | +under a content address, and the cell row holds only the reference. This split | |
| 87 | +keeps one large `put()` from becoming the most expensive operation in the | |
| 88 | +runtime. Cloudflare made the same split for the same reason, and sends a large | |
| 89 | +value to object storage. | |
| 90 | + | |
| 91 | +A node therefore needs a fleet bucket to write a value above 1 MiB. Without one, | |
| 92 | +the write fails with the message `KV large values need a fleet bucket`. celld | |
| 93 | +writes the object before it commits the row, so a crash between the two steps | |
| 94 | +leaves an unreferenced object that a collector removes later. A committed row | |
| 95 | +never names an object that does not exist. | |
| 96 | + | |
| 97 | +## Differences from Cloudflare | |
| 98 | + | |
| 99 | +- A celld read never returns a stale value, because it reaches the cell that | |
| 100 | + owns the namespace. Cloudflare KV is eventually consistent. | |
| 101 | +- celld has no edge cache. `cacheTtl` has no effect, and `cacheStatus` is | |
| 102 | + `null`. | |
| 103 | +- A value above 1 MiB requires a fleet bucket. | |
| 104 | +- A namespace has one writer. Use more namespaces to increase write capacity. | |
| 105 | + | |
| 106 | +The [Cloudflare compatibility](../cloudflare-compat.md#services) page lists the | |
| 107 | +runtime APIs and the unsupported services. |
addeddocs/services/queues-flow.svg+127−0View file
| @@ -1,0 +1,127 @@ | ||
| 1 | +<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 440 512" role="img" aria-labelledby="queuesFlowTitle queuesFlowDesc"> | |
| 2 | + <title id="queuesFlowTitle">A batch closes on size or on timeout, and an unacknowledged message returns to the queue until the retry bound moves it to the dead-letter queue</title> | |
| 3 | + <desc id="queuesFlowDesc">The upper panel shows two batches under a consumer with max_batch_size 10 and | |
| 4 | +max_batch_timeout 5 seconds. A busy queue reaches ten messages before the | |
| 5 | +timeout, so the batch closes on size. A sparse queue reaches only three | |
| 6 | +messages, so the batch closes on the timeout and the consumer receives a | |
| 7 | +partial batch. The timeout runs from the oldest ready message, not from the | |
| 8 | +last one. The lower panel shows the settlement cycle. One queue cell with one | |
| 9 | +writer leases a batch to one call of queue(batch, env, ctx). A message that the | |
| 10 | +handler acknowledges, or that a clean return leaves unsettled, is deleted. A | |
| 11 | +message that calls retry, that a thrown handler abandons, or that no | |
| 12 | +settlement reaches, returns to the queue as the same message with its attempts | |
| 13 | +count raised by one, so a consumer can see a duplicate. When attempts pass | |
| 14 | +max_retries, the message leaves the loop and moves to the dead-letter queue | |
| 15 | +cell, which is itself a queue with its own consumer. celld deletes the message | |
| 16 | +instead when no dead_letter_queue is configured.</desc> | |
| 17 | + <style> | |
| 18 | + svg { font-family: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Helvetica, Arial, sans-serif; } | |
| 19 | + text { font-size: 13px; fill: currentColor; } | |
| 20 | + tspan { fill: currentColor; } | |
| 21 | + .mono { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; font-size: 12px; } | |
| 22 | + .lead { font-weight: 600; } | |
| 23 | + .sm { font-size: 12px; } | |
| 24 | + .d-ink { color: #121212; } | |
| 25 | + .d-soft { color: #3d3b37; } | |
| 26 | + .d-faint { color: #6e6a62; } | |
| 27 | + .d-acc { color: #10803f; } | |
| 28 | + .d-panel { color: #ffffff; } | |
| 29 | + .d-sunk { color: #f0eee8; } | |
| 30 | + .d-tint { color: #d6efdf; } | |
| 31 | + @media (prefers-color-scheme: dark) { | |
| 32 | + .d-ink { color: #efede7; } | |
| 33 | + .d-soft { color: #c9c6be; } | |
| 34 | + .d-faint { color: #928e85; } | |
| 35 | + .d-acc { color: #3fc472; } | |
| 36 | + .d-panel { color: #1a1a19; } | |
| 37 | + .d-sunk { color: #232321; } | |
| 38 | + .d-tint { color: #10301d; } | |
| 39 | + } | |
| 40 | + </style> | |
| 41 | + <defs> | |
| 42 | + <marker id="queues-arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="6" | |
| 43 | + markerHeight="6" orient="auto-start-reverse"> | |
| 44 | + <path class="d-soft" fill="currentColor" d="M0 0 L10 5 L0 10 z" /> | |
| 45 | + </marker> | |
| 46 | + </defs> | |
| 47 | + | |
| 48 | + <!-- Panel one: the batch window, where two limits race. --> | |
| 49 | + <rect class="d-sunk" fill="currentColor" x="8" y="8" width="424" height="170" rx="10" /> | |
| 50 | + <rect class="d-faint" fill="none" stroke="currentColor" x="8" y="8" width="424" height="170" rx="10" /> | |
| 51 | + <text class="d-ink lead" fill="currentColor" x="22" y="32">A batch closes on whichever limit arrives first</text> | |
| 52 | + <text class="d-faint mono" fill="currentColor" x="22" y="52">max_batch_size 10 · max_batch_timeout 5 s</text> | |
| 53 | + | |
| 54 | + <path class="d-faint" fill="none" stroke="currentColor" stroke-dasharray="4 4" d="M300 62 V152" /> | |
| 55 | + | |
| 56 | + <!-- A busy queue fills the batch before the clock runs out. --> | |
| 57 | + <g class="d-acc" fill="currentColor"> | |
| 58 | + <circle cx="24" cy="82" r="4" /> | |
| 59 | + <circle cx="48" cy="82" r="4" /> | |
| 60 | + <circle cx="72" cy="82" r="4" /> | |
| 61 | + <circle cx="96" cy="82" r="4" /> | |
| 62 | + <circle cx="120" cy="82" r="4" /> | |
| 63 | + <circle cx="144" cy="82" r="4" /> | |
| 64 | + <circle cx="168" cy="82" r="4" /> | |
| 65 | + <circle cx="192" cy="82" r="4" /> | |
| 66 | + <circle cx="216" cy="82" r="4" /> | |
| 67 | + <circle cx="240" cy="82" r="4" /> | |
| 68 | + </g> | |
| 69 | + <path class="d-acc" fill="none" stroke="currentColor" stroke-width="2.5" d="M252 68 V96" /> | |
| 70 | + <text class="d-soft sm" fill="currentColor" x="24" y="105">closes on size, before the timeout</text> | |
| 71 | + | |
| 72 | + <!-- A sparse queue reaches the clock with a partial batch. --> | |
| 73 | + <g class="d-acc" fill="currentColor"> | |
| 74 | + <circle cx="24" cy="130" r="4" /> | |
| 75 | + <circle cx="100" cy="130" r="4" /> | |
| 76 | + <circle cx="184" cy="130" r="4" /> | |
| 77 | + </g> | |
| 78 | + <path class="d-acc" fill="none" stroke="currentColor" stroke-width="2.5" d="M300 116 V144" /> | |
| 79 | + <text class="d-soft sm" fill="currentColor" x="24" y="153">closes on the timeout, 3 messages</text> | |
| 80 | + <text class="d-faint sm" fill="currentColor" x="308" y="134">partial batch</text> | |
| 81 | + <text class="d-faint sm" fill="currentColor" x="290" y="170" text-anchor="middle">the timeout runs from the oldest message</text> | |
| 82 | + | |
| 83 | + <!-- Panel two: the settlement cycle and the bound that ends it. --> | |
| 84 | + <text class="d-ink lead" fill="currentColor" x="22" y="204">An unacknowledged message returns to the queue</text> | |
| 85 | + | |
| 86 | + <rect class="d-tint" fill="currentColor" x="24" y="216" width="146" height="62" rx="8" /> | |
| 87 | + <rect class="d-acc" fill="none" stroke="currentColor" stroke-width="2" x="24" y="216" width="146" height="62" rx="8" /> | |
| 88 | + <text class="d-ink" fill="currentColor" x="97" y="242" text-anchor="middle">JOBS queue cell</text> | |
| 89 | + <text class="d-soft sm" fill="currentColor" x="97" y="262" text-anchor="middle">one writer</text> | |
| 90 | + | |
| 91 | + <rect class="d-panel" fill="currentColor" x="240" y="216" width="192" height="62" rx="8" /> | |
| 92 | + <rect class="d-soft" fill="none" stroke="currentColor" x="240" y="216" width="192" height="62" rx="8" /> | |
| 93 | + <text class="d-ink mono" fill="currentColor" x="336" y="242" text-anchor="middle">queue(batch, env, ctx)</text> | |
| 94 | + <text class="d-soft sm" fill="currentColor" x="336" y="262" text-anchor="middle">one batch, one lease</text> | |
| 95 | + | |
| 96 | + <g class="d-soft" fill="none" stroke="currentColor" stroke-width="1.5"> | |
| 97 | + <path d="M170 247 H232" marker-end="url(#queues-arrow)" /> | |
| 98 | + <path d="M336 278 V336" marker-end="url(#queues-arrow)" /> | |
| 99 | + <path d="M336 294 H97 V336" marker-end="url(#queues-arrow)" /> | |
| 100 | + <path d="M24 366 H12 V247 H18" marker-end="url(#queues-arrow)" /> | |
| 101 | + <path d="M97 406 V440" marker-end="url(#queues-arrow)" /> | |
| 102 | + </g> | |
| 103 | + <text class="d-faint sm" fill="currentColor" x="201" y="237" text-anchor="middle">lease</text> | |
| 104 | + <text class="d-soft sm" fill="currentColor" x="108" y="311">retry(), a throw,</text> | |
| 105 | + <text class="d-soft sm" fill="currentColor" x="108" y="327">or no settlement</text> | |
| 106 | + | |
| 107 | + <rect class="d-panel" fill="currentColor" x="24" y="336" width="146" height="70" rx="8" /> | |
| 108 | + <rect class="d-soft" fill="none" stroke="currentColor" x="24" y="336" width="146" height="70" rx="8" /> | |
| 109 | + <text class="d-ink" fill="currentColor" x="97" y="360" text-anchor="middle">back to the queue</text> | |
| 110 | + <text class="d-soft sm" fill="currentColor" x="97" y="379" text-anchor="middle">attempts + 1</text> | |
| 111 | + <text class="d-soft sm" fill="currentColor" x="97" y="396" text-anchor="middle">the same message</text> | |
| 112 | + | |
| 113 | + <rect class="d-panel" fill="currentColor" x="240" y="336" width="192" height="70" rx="8" /> | |
| 114 | + <rect class="d-soft" fill="none" stroke="currentColor" x="240" y="336" width="192" height="70" rx="8" /> | |
| 115 | + <text class="d-ink" fill="currentColor" x="336" y="366" text-anchor="middle">deleted</text> | |
| 116 | + <text class="d-soft sm" fill="currentColor" x="336" y="387" text-anchor="middle">ack(), or a clean return</text> | |
| 117 | + | |
| 118 | + <text class="d-acc mono" fill="currentColor" x="108" y="428">attempts > max_retries</text> | |
| 119 | + | |
| 120 | + <rect class="d-tint" fill="currentColor" x="24" y="444" width="250" height="58" rx="8" /> | |
| 121 | + <rect class="d-acc" fill="none" stroke="currentColor" stroke-width="2" x="24" y="444" width="250" height="58" rx="8" /> | |
| 122 | + <text class="d-ink" fill="currentColor" x="149" y="470" text-anchor="middle">dead-letter queue cell</text> | |
| 123 | + <text class="d-soft sm" fill="currentColor" x="149" y="490" text-anchor="middle">a queue with its own consumer</text> | |
| 124 | + | |
| 125 | + <text class="d-faint sm mono" fill="currentColor" x="286" y="466">no dead_letter_queue</text> | |
| 126 | + <text class="d-faint sm" fill="currentColor" x="286" y="486">celld deletes it</text> | |
| 127 | +</svg> |
addeddocs/services/queues.md+123−0View file
| @@ -1,0 +1,123 @@ | ||
| 1 | +# Queues | |
| 2 | + | |
| 3 | +[Queues](https://developers.cloudflare.com/queues/) is a message broker. A | |
| 4 | +producer Worker sends a message, and a consumer Worker receives the message | |
| 5 | +later in a batch. An application uses a queue to move work out of a request, | |
| 6 | +such as an email, a webhook call, a thumbnail, or a search index update. Each | |
| 7 | +queue is one celld cell, so a message lives in that cell's SQLite database | |
| 8 | +until a consumer acknowledges it. Read the | |
| 9 | +[Cloudflare Queues documentation](https://developers.cloudflare.com/queues/configuration/javascript-apis/) | |
| 10 | +for the standard API behavior. | |
| 11 | + | |
| 12 | +## Example | |
| 13 | + | |
| 14 | +The [Queues example](../../examples/queues) sends one job from a request and | |
| 15 | +processes the job in a queue handler. A job for a path that ends in `/fail` | |
| 16 | +retries twice, and the example then reads it from a dead-letter queue. | |
| 17 | + | |
| 18 | +<!-- celld-example: queues --> | |
| 19 | + | |
| 20 | +## Sending a message | |
| 21 | + | |
| 22 | +A project declares a producer with a `queues.producers` entry that gives a | |
| 23 | +`binding` name and a `queue` name. `env.JOBS.send(body)` sends one message, and | |
| 24 | +`env.JOBS.sendBatch(messages)` sends up to 100 messages in one call. celld | |
| 25 | +resolves the queue name to one cell, therefore every producer in the fleet that | |
| 26 | +names `example-jobs` writes to the same queue. | |
| 27 | + | |
| 28 | +A message carries a body and a content type. The `contentType` option selects | |
| 29 | +`"v8"`, `"json"`, `"text"`, or `"bytes"`, and the `queues_json_messages` | |
| 30 | +compatibility flag chooses the default, as on Cloudflare. celld enforces the | |
| 31 | +[Cloudflare limits](https://developers.cloudflare.com/queues/platform/limits/): | |
| 32 | +a message of at most 128,000 bytes, a batch of at most 100 messages, and at most | |
| 33 | +256,000 bytes in one `sendBatch()` call. A `delaySeconds` option holds a message | |
| 34 | +invisible for up to 86,400 seconds, and a producer entry can set | |
| 35 | +`delivery_delay` as the default for every message of that binding. | |
| 36 | + | |
| 37 | +`send()` resolves after the queue cell commits the message, so a producer learns | |
| 38 | +that the message is durable. celld joins the concurrent sends of one queue into | |
| 39 | +one transaction, because a separate commit for each call makes durability the | |
| 40 | +cost of the queue. The cell accepts at most 256 producer calls at a time, and it | |
| 41 | +refuses a further call with a cell overload error that the producer can retry. | |
| 42 | +One queue has one writer, so an application that needs more write capacity | |
| 43 | +spreads its messages across more queues. | |
| 44 | + | |
| 45 | +## The consumer and the batch | |
| 46 | + | |
| 47 | +A project declares a consumer with a `queues.consumers` entry that names the | |
| 48 | +`queue`. One script consumes a queue, and a deployment in which two scripts | |
| 49 | +consume one queue fails. The consumer entry sets `max_batch_size` (10 by | |
| 50 | +default, 100 at most), `max_batch_timeout` in seconds (5 by default, 60 at | |
| 51 | +most), `max_retries` (3 by default), `max_concurrency` (250 at most), | |
| 52 | +`retry_delay`, and `dead_letter_queue`. celld validates each bound at deploy | |
| 53 | +time, so a bad value fails the deployment instead of the first delivery. Read | |
| 54 | +[Batching, retries, and delays](https://developers.cloudflare.com/queues/configuration/batching-retries/) | |
| 55 | +for the upstream meaning of each key. | |
| 56 | + | |
| 57 | +The queue cell forms the batch. It closes a batch when `max_batch_size` messages | |
| 58 | +are ready, or when `max_batch_timeout` passes after the oldest ready message, | |
| 59 | +whichever arrives first. A batch can therefore hold fewer messages than | |
| 60 | +`max_batch_size`. The cell leases the batch and calls the | |
| 61 | +`queue(batch, env, ctx)` handler that the consumer script exports. That handler | |
| 62 | +runs in a stateless isolate and not inside the queue cell, so a slow handler | |
| 63 | +does not block a producer. `max_concurrency` bounds how many batches of one | |
| 64 | +queue can run at the same time. | |
| 65 | + | |
| 66 | +`batch.queue` names the queue, and `batch.messages` holds the messages. Each | |
| 67 | +message has an `id`, a `timestamp`, the decoded `body`, and an `attempts` count | |
| 68 | +that is 1 on the first delivery. celld does not guarantee a delivery order, and | |
| 69 | +[Cloudflare gives the same rule](https://developers.cloudflare.com/queues/reference/how-queues-works/). | |
| 70 | +A retry, a per-message delay, and a concurrent batch each move a message away | |
| 71 | +from its send order, so an application that needs an order must carry that order | |
| 72 | +in the message body. | |
| 73 | + | |
| 74 | +## Acknowledgement and retry | |
| 75 | + | |
| 76 | +celld leases a batch instead of deleting it, so a message survives a consumer | |
| 77 | +that fails. Each message settles once. `message.ack()` marks one message as | |
| 78 | +done, and `message.retry()` returns one message to the queue. `batch.ackAll()` | |
| 79 | +and `batch.retryAll()` apply the same two outcomes to the whole batch. The first | |
| 80 | +call for a message wins, therefore a later call on that message does nothing. | |
| 81 | + | |
| 82 | +A handler that returns without a call acknowledges every message of its batch. A | |
| 83 | +handler that throws returns every message to the queue, except a message that | |
| 84 | +the handler acknowledged before the throw. A handler that never settles its | |
| 85 | +batch holds the lease until the lease expires, and celld then counts the batch | |
| 86 | +as one failed delivery. | |
| 87 | + | |
| 88 | +Every failed delivery raises `attempts` by one and makes the message visible | |
| 89 | +again. A `delaySeconds` option on `retry()` or `retryAll()` sets the delay, and | |
| 90 | +the consumer's `retry_delay` is the default. celld adds no exponential backoff, | |
| 91 | +so an application that wants one computes the delay from `message.attempts`. | |
| 92 | + | |
| 93 | +A message leaves the retry loop when `attempts` passes `max_retries`. celld | |
| 94 | +moves the message to the queue that `dead_letter_queue` names, which is an | |
| 95 | +ordinary queue and can have its own consumer. celld deletes a message that | |
| 96 | +reaches the bound when the consumer configures no dead-letter queue. Read | |
| 97 | +[Dead letter queues](https://developers.cloudflare.com/queues/configuration/dead-letter-queues/) | |
| 98 | +for the upstream behavior. | |
| 99 | + | |
| 100 | + | |
| 101 | + | |
| 102 | +celld delivers a message at least once, as Cloudflare does. A consumer can crash | |
| 103 | +after its side effect and before its acknowledgement, and the message then | |
| 104 | +returns to the queue and runs again. A consumer must therefore tolerate a | |
| 105 | +duplicate. `message.id` stays the same across a redelivery, so an application | |
| 106 | +can use it as an idempotency key. | |
| 107 | + | |
| 108 | +celld keeps a message for four days after the send. A sweeper removes an older | |
| 109 | +message, even when no consumer read it, so a queue with no working consumer | |
| 110 | +loses its backlog instead of growing without a bound. | |
| 111 | + | |
| 112 | +## Differences from Cloudflare | |
| 113 | + | |
| 114 | +- A queue has one writer. Use more queues to increase write capacity. | |
| 115 | +- A queue owner accepts at most 256 concurrent producer calls. It refuses an | |
| 116 | + additional call, which the producer can retry. | |
| 117 | +- celld retains a message for four days. This period is not configurable. | |
| 118 | +- Pull consumers, the Queues HTTP API, dashboard controls, manual consumer | |
| 119 | + attachment, R2 event notifications, and Queue event subscriptions are | |
| 120 | + unavailable. | |
| 121 | + | |
| 122 | +The [Cloudflare compatibility](../cloudflare-compat.md#services) page lists the | |
| 123 | +runtime APIs and the unsupported services. |
addeddocs/services/r2-flow.svg+64−0View file
| @@ -1,0 +1,64 @@ | ||
| 1 | +<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 440 416" role="img" aria-labelledby="r2FlowTitle r2FlowDesc"> | |
| 2 | + <title id="r2FlowTitle">Two R2 bindings share one fleet object store under reserved prefixes</title> | |
| 3 | + <desc id="r2FlowDesc">Two Workers each hold an R2 binding. The binding FILES has the bucket name example-files, and the binding CACHE has the bucket name renders. Both Workers write the same key, photo.png. Both bindings use one fleet object-store bucket, which is an s3, gs, or az bucket, so that store gives the binding its durability. celld turns each key into r2 slash bucket name slash key, so the two writes become the separate objects r2/example-files/photo.png and r2/renders/photo.png. The fleet's own keys, under deploy, cells, nodes, and wake, live in the same bucket outside every r2 prefix, and no binding can reach them.</desc> | |
| 4 | + <style> | |
| 5 | + svg { font-family: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Helvetica, Arial, sans-serif; } | |
| 6 | + text { font-size: 13px; fill: currentColor; } | |
| 7 | + .mono { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; } | |
| 8 | + .lead { font-weight: 600; } | |
| 9 | + .d-ink { color: #121212; } | |
| 10 | + .d-soft { color: #3d3b37; } | |
| 11 | + .d-faint { color: #6e6a62; } | |
| 12 | + .d-acc { color: #10803f; } | |
| 13 | + .d-panel { color: #ffffff; } | |
| 14 | + .d-sunk { color: #f0eee8; } | |
| 15 | + .d-tint { color: #d6efdf; } | |
| 16 | + @media (prefers-color-scheme: dark) { | |
| 17 | + .d-ink { color: #efede7; } | |
| 18 | + .d-soft { color: #c9c6be; } | |
| 19 | + .d-faint { color: #928e85; } | |
| 20 | + .d-acc { color: #3fc472; } | |
| 21 | + .d-panel { color: #1a1a19; } | |
| 22 | + .d-sunk { color: #232321; } | |
| 23 | + .d-tint { color: #10301d; } | |
| 24 | + } | |
| 25 | + </style> | |
| 26 | + | |
| 27 | + <!-- Two Workers, two bindings, the same key --> | |
| 28 | + <rect class="d-panel" x="8" y="10" width="200" height="86" rx="10" fill="currentColor" /> | |
| 29 | + <rect class="d-faint" x="8" y="10" width="200" height="86" rx="10" fill="none" stroke="currentColor" /> | |
| 30 | + <text class="d-faint" x="20" y="34">Worker A, binding FILES</text> | |
| 31 | + <text class="d-ink mono" x="20" y="58">put("photo.png")</text> | |
| 32 | + <text class="d-acc" x="20" y="80">bucket_name: example-files</text> | |
| 33 | + | |
| 34 | + <rect class="d-panel" x="232" y="10" width="200" height="86" rx="10" fill="currentColor" /> | |
| 35 | + <rect class="d-faint" x="232" y="10" width="200" height="86" rx="10" fill="none" stroke="currentColor" /> | |
| 36 | + <text class="d-faint" x="244" y="34">Worker B, binding CACHE</text> | |
| 37 | + <text class="d-ink mono" x="244" y="58">put("photo.png")</text> | |
| 38 | + <text class="d-acc" x="244" y="80">bucket_name: renders</text> | |
| 39 | + | |
| 40 | + <!-- Both bindings fan in to one store --> | |
| 41 | + <path class="d-faint" d="M108 96 C108 134 220 130 220 156" fill="none" stroke="currentColor" stroke-width="1.5" /> | |
| 42 | + <path class="d-faint" d="M332 96 C332 134 220 130 220 156" fill="none" stroke="currentColor" stroke-width="1.5" /> | |
| 43 | + <path class="d-faint" d="M220 168 L214 154 L226 154 Z" fill="currentColor" /> | |
| 44 | + <text class="d-faint" x="220" y="130" text-anchor="middle">one store</text> | |
| 45 | + | |
| 46 | + <!-- The fleet object store --> | |
| 47 | + <rect class="d-sunk" x="8" y="172" width="424" height="234" rx="12" fill="currentColor" /> | |
| 48 | + <rect class="d-faint" x="8" y="172" width="424" height="234" rx="12" fill="none" stroke="currentColor" /> | |
| 49 | + <text class="d-ink lead" x="24" y="198">Fleet object-store bucket</text> | |
| 50 | + <text class="d-faint" x="24" y="218">s3:// gs:// az:// — durability comes from here</text> | |
| 51 | + | |
| 52 | + <rect class="d-tint" x="22" y="228" width="396" height="108" rx="8" fill="currentColor" /> | |
| 53 | + <rect class="d-acc" x="22" y="228" width="396" height="108" rx="8" fill="none" stroke="currentColor" stroke-dasharray="5 4" /> | |
| 54 | + <text class="d-acc" x="36" y="252">reserved r2/ prefixes, one per bucket_name</text> | |
| 55 | + <text class="d-ink mono" x="36" y="280"><tspan class="d-acc" fill="currentColor">r2/example-files/</tspan>photo.png</text> | |
| 56 | + <text class="d-faint" x="404" y="280" text-anchor="end">FILES</text> | |
| 57 | + <text class="d-ink mono" x="36" y="304"><tspan class="d-acc" fill="currentColor">r2/renders/</tspan>photo.png</text> | |
| 58 | + <text class="d-faint" x="404" y="304" text-anchor="end">CACHE</text> | |
| 59 | + <text class="d-ink mono" x="36" y="328"><tspan class="d-acc" fill="currentColor">r2/renders/</tspan>tile-04.png</text> | |
| 60 | + <text class="d-faint" x="404" y="328" text-anchor="end">CACHE</text> | |
| 61 | + | |
| 62 | + <text class="d-soft mono" x="24" y="366">deploy/ cells/ nodes/ wake/</text> | |
| 63 | + <text class="d-faint" x="24" y="388">fleet keys, outside every binding's reach</text> | |
| 64 | +</svg> |
addeddocs/services/r2.md+121−0View file
| @@ -1,0 +1,121 @@ | ||
| 1 | +# R2 | |
| 2 | + | |
| 3 | +[R2](https://developers.cloudflare.com/r2/) is object storage. A bucket holds | |
| 4 | +unstructured blobs of any size, and an application reads or writes a blob by | |
| 5 | +name. An application uses R2 for a file that a request handler must keep: an | |
| 6 | +upload, an image, a backup, a build artifact, or a large data export. A Worker | |
| 7 | +reaches a bucket through an `r2_buckets` binding, so `env.BUCKET` gives the | |
| 8 | +bucket API without a credential in the Worker code. The objects live outside the | |
| 9 | +Worker isolate, in the fleet object store that the node already uses. Read the | |
| 10 | +[Workers API reference](https://developers.cloudflare.com/r2/api/workers/workers-api-reference/) | |
| 11 | +for the full method list. | |
| 12 | + | |
| 13 | +## Example | |
| 14 | + | |
| 15 | +The [R2 example](../../examples/r2) reads, writes, and deletes objects in an R2 | |
| 16 | +bucket. | |
| 17 | + | |
| 18 | +<!-- celld-example: r2 --> | |
| 19 | + | |
| 20 | +## The object model | |
| 21 | + | |
| 22 | +A bucket contains objects, and each object has a key. A key is a string of 1 to | |
| 23 | +1024 bytes. The namespace is flat, so a slash in a key is only a character, and | |
| 24 | +`list()` folds a prefix into a group when a caller passes a `delimiter`. See | |
| 25 | +[Objects](https://developers.cloudflare.com/r2/objects/) for the upstream model. | |
| 26 | + | |
| 27 | +An object carries a body and a record. The record holds `httpMetadata` (the | |
| 28 | +content headers and a cache expiry), `customMetadata` (the application's own | |
| 29 | +string map), `checksums`, a `storageClass`, a `size`, an `uploaded` time, an | |
| 30 | +`etag`, and a `version`. celld stores the body as a plain object in the fleet | |
| 31 | +bucket and writes the five content headers as real headers, so another tool can | |
| 32 | +read the object. The parts that an object store has no place for travel as one | |
| 33 | +JSON value in a reserved metadata entry, and an object without that entry still | |
| 34 | +reads correctly. | |
| 35 | + | |
| 36 | +celld takes the `version` from the object store. Most object stores report no | |
| 37 | +version identifier, so the ETag becomes the version. Two writes of identical | |
| 38 | +bytes therefore produce the same version, and an application must not use a | |
| 39 | +version to count writes. | |
| 40 | + | |
| 41 | +## Where celld stores an object | |
| 42 | + | |
| 43 | +celld does not run its own blob service, because celld already runs on one. An | |
| 44 | +R2 binding therefore uses the fleet bucket that the node opened with `--bucket`, | |
| 45 | +and it does not use a second store or a second credential. The durability of an | |
| 46 | +R2 binding is the durability of that object store, and it is not the durability | |
| 47 | +of Cloudflare R2. A node that starts without a fleet bucket has nowhere to put a | |
| 48 | +blob, so every R2 method on such a node fails with an explicit error. | |
| 49 | + | |
| 50 | +Each binding is a logical bucket with its own `bucket_name`, and celld gives | |
| 51 | +each one a reserved key space in the single fleet bucket. A call to `get()`, | |
| 52 | +`put()`, `head()`, or `delete()` turns the key into `r2/<bucket_name>/<key>` | |
| 53 | +before the call reaches the store. The `bucket_name` comes from the deployment | |
| 54 | +manifest, which validates it, so two bindings cannot collide and no binding can | |
| 55 | +read or overwrite the fleet's own keys. | |
| 56 | + | |
| 57 | + | |
| 58 | + | |
| 59 | +`get(key)` returns an `R2ObjectBody`, or `null` when the key is absent. The body | |
| 60 | +arrives as a `ReadableStream` from the host, so a large object never has to fit | |
| 61 | +in the isolate heap. `get()` also accepts a range, and celld accepts every range | |
| 62 | +spelling that R2 accepts: an `offset`, a `length`, a `suffix`, or a `Range` | |
| 63 | +header. `put(key, value, options)` accepts a string, an `ArrayBuffer`, a typed | |
| 64 | +array, a `Blob`, or a `ReadableStream`. celld writes a small body in one | |
| 65 | +request, and a streamed body that grows past 8 MiB becomes a multipart upload to | |
| 66 | +the object store. `delete(keys)` removes up to 1000 keys in one call, and | |
| 67 | +`head(key)` returns the record without the body. | |
| 68 | + | |
| 69 | +celld serves a bucket through the binding only. There is no public bucket URL, | |
| 70 | +no presigned URL, and no S3 endpoint into an R2 binding, so an application must | |
| 71 | +put a Worker in front of the bytes it wants to publish. | |
| 72 | + | |
| 73 | +## Conditional requests and multipart uploads | |
| 74 | + | |
| 75 | +A conditional operation takes an `onlyIf`, either as an `R2Conditional` or as a | |
| 76 | +`Headers` object with `If-Match`, `If-None-Match`, `If-Modified-Since`, or | |
| 77 | +`If-Unmodified-Since`. A refused `get()` answers the record with no body, and a | |
| 78 | +refused `put()` answers `null`. celld passes the precondition to the object | |
| 79 | +store, which applies it. A streamed body larger than 8 MiB becomes a multipart | |
| 80 | +upload, and a multipart completion takes no precondition, so celld refuses a | |
| 81 | +conditional write of such a body instead of dropping the condition. | |
| 82 | + | |
| 83 | +`createMultipartUpload(key)` returns a handle, `uploadPart(number, value)` sends | |
| 84 | +one part, and `complete(parts)` assembles the object. Read | |
| 85 | +[Multipart upload](https://developers.cloudflare.com/r2/objects/multipart-objects/) | |
| 86 | +for the part-size and part-number rules. celld holds the upload in the node that | |
| 87 | +opened it, because the handle that the object store returns cannot be derived | |
| 88 | +again from an upload id. An upload therefore cannot resume on another node or | |
| 89 | +after a restart. | |
| 90 | + | |
| 91 | +celld hands the parts to the object store in ascending order, because the store | |
| 92 | +appends them. A part that arrives before its predecessor waits in memory, and | |
| 93 | +that backlog can reach 256 MiB before celld refuses a further part. A part that | |
| 94 | +is still waiting can be replaced by a second upload of the same number. A part | |
| 95 | +that already went to the store cannot be replaced, so celld refuses that write | |
| 96 | +rather than losing the bytes without a report. | |
| 97 | + | |
| 98 | +## Differences from Cloudflare | |
| 99 | + | |
| 100 | +- An R2 binding uses the fleet bucket under `r2/<bucket_name>/`. | |
| 101 | +- The five content headers are stored as headers. `customMetadata`, | |
| 102 | + `cacheExpiry`, the checksums, and the storage class are stored together as | |
| 103 | + one JSON value, under the `celld-r2` user-metadata name (`celld_r2` on | |
| 104 | + Azure Blob Storage, which refuses a hyphen in a metadata name). | |
| 105 | +- An object another tool wrote still reads through the binding. Its user | |
| 106 | + metadata becomes its `customMetadata`, and its headers become its | |
| 107 | + `httpMetadata`. Use `celld r2 put` to write the complete record. | |
| 108 | +- `celld r2 get|head|put|delete|list` replaces `wrangler r2 object`. The | |
| 109 | + command reads the fleet bucket directly, so it needs no running node. | |
| 110 | +- An object `version` equals its content ETag, so identical content produces | |
| 111 | + the same version. | |
| 112 | +- `ssecKey` and `jurisdiction` are unavailable. | |
| 113 | +- A conditional write cannot use a streamed body larger than 8 MiB. | |
| 114 | +- `createMultipartUpload()` does not accept a checksum. | |
| 115 | +- A multipart upload cannot resume on another node or after a restart. celld | |
| 116 | + also cannot replace a part that the object store already holds. | |
| 117 | +- Out-of-order parts can use at most 256 MiB of memory, and completion cannot | |
| 118 | + change the stored part order. | |
| 119 | + | |
| 120 | +The [Cloudflare compatibility](../cloudflare-compat.md#services) page lists the | |
| 121 | +runtime APIs and the unsupported services. |
addeddocs/services/static-assets-flow.svg+183−0View file
| @@ -1,0 +1,183 @@ | ||
| 1 | +<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 440 674" role="img" aria-labelledby="assetsFlowTitle assetsFlowDesc"> | |
| 2 | + <title id="assetsFlowTitle">How celld decides between an asset and the Worker</title> | |
| 3 | + <desc id="assetsFlowDesc">A request reaches a node and passes down a column of tests. A method other | |
| 4 | +than GET or HEAD leaves at once and the Worker answers. A path that | |
| 5 | +run_worker_first matches also leaves, and no asset lookup happens. The | |
| 6 | +_redirects rules run next, in file order, and the first match wins: status 301, | |
| 7 | +302, 303, 307, or 308 gives a Location header with no body, and status 200 | |
| 8 | +restarts routing at the destination path. html_handling then looks for a file: | |
| 9 | +the exact path gives 200 with the body, and another spelling gives 307 to the | |
| 10 | +canonical path. After a miss the node re-reads the deployment pointer, at most | |
| 11 | +once in five seconds, so a newer deployment can still answer. not_found_handling | |
| 12 | +fabricates the last answer, but only for a navigation request or for a | |
| 13 | +deployment with no Worker: single-page-application returns /index.html with 200, | |
| 14 | +and 404-page returns the nearest 404.html with 404. When nothing matches the | |
| 15 | +Worker answers, and a deployment with no Worker answers 404. A green outcome | |
| 16 | +comes from the asset layer and a grey outcome comes from the Worker. Separately, | |
| 17 | +a missing or corrupt asset body gives 502 and never falls through to the | |
| 18 | +Worker.</desc> | |
| 19 | + <style> | |
| 20 | + /* GitHub renders this file as an image, so the diagram carries literal | |
| 21 | + colours here. The site rules in landing/src/style.css are more specific, | |
| 22 | + so the documentation theme tokens win there. SVG paints text black by | |
| 23 | + default, and a class that sets only `color` never reaches the fill, so | |
| 24 | + every label sets fill="currentColor" as well. */ | |
| 25 | + svg { font-family: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Helvetica, Arial, sans-serif; } | |
| 26 | + text { font-size: 12px; fill: currentColor; } | |
| 27 | + tspan { fill: currentColor; } | |
| 28 | + .sm { font-size: 11px; } | |
| 29 | + .mono { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; } | |
| 30 | + .d-ink { color: #121212; } | |
| 31 | + .d-soft { color: #3d3b37; } | |
| 32 | + .d-faint { color: #6e6a62; } | |
| 33 | + .d-acc { color: #10803f; } | |
| 34 | + .d-panel { color: #ffffff; } | |
| 35 | + .d-sunk { color: #f0eee8; } | |
| 36 | + .d-tint { color: #d6efdf; } | |
| 37 | + @media (prefers-color-scheme: dark) { | |
| 38 | + .d-ink { color: #efede7; } | |
| 39 | + .d-soft { color: #c9c6be; } | |
| 40 | + .d-faint { color: #928e85; } | |
| 41 | + .d-acc { color: #3fc472; } | |
| 42 | + .d-panel { color: #1a1a19; } | |
| 43 | + .d-sunk { color: #232321; } | |
| 44 | + .d-tint { color: #10301d; } | |
| 45 | + } | |
| 46 | + </style> | |
| 47 | + <defs> | |
| 48 | + <marker id="sa-arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="6" markerHeight="6" orient="auto-start-reverse"> | |
| 49 | + <path class="d-soft" d="M0,1 L9,5 L0,9 z" fill="currentColor" /> | |
| 50 | + </marker> | |
| 51 | + <marker id="sa-arrow-acc" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="6" markerHeight="6" orient="auto-start-reverse"> | |
| 52 | + <path class="d-acc" d="M0,1 L9,5 L0,9 z" fill="currentColor" /> | |
| 53 | + </marker> | |
| 54 | + </defs> | |
| 55 | + | |
| 56 | + <!-- One request enters the column of tests. --> | |
| 57 | + <rect class="d-panel" x="8" y="8" width="228" height="32" rx="6" fill="currentColor" /> | |
| 58 | + <rect class="d-ink" x="8" y="8" width="228" height="32" rx="6" fill="none" stroke="currentColor" stroke-width="1.5" /> | |
| 59 | + <text class="d-ink" x="122" y="29" fill="currentColor" text-anchor="middle">One request reaches a node</text> | |
| 60 | + <text class="d-faint sm" x="342" y="29" fill="currentColor" text-anchor="middle">who answers, and with what</text> | |
| 61 | + | |
| 62 | + <path class="d-soft" d="M122,40 V62" fill="none" stroke="currentColor" stroke-width="1.5" marker-end="url(#sa-arrow)" /> | |
| 63 | + | |
| 64 | + <!-- The method test: only GET and HEAD can reach an asset. --> | |
| 65 | + <rect class="d-panel" x="8" y="62" width="228" height="40" rx="6" fill="currentColor" /> | |
| 66 | + <rect class="d-faint" x="8" y="62" width="228" height="40" rx="6" fill="none" stroke="currentColor" /> | |
| 67 | + <text class="d-ink" x="20" y="87" fill="currentColor">Method other than GET or HEAD</text> | |
| 68 | + <path class="d-soft" d="M236,82 H252" fill="none" stroke="currentColor" stroke-width="1.5" marker-end="url(#sa-arrow)" /> | |
| 69 | + <rect class="d-sunk" x="252" y="62" width="180" height="40" rx="6" fill="currentColor" /> | |
| 70 | + <rect class="d-soft" x="252" y="62" width="180" height="40" rx="6" fill="none" stroke="currentColor" /> | |
| 71 | + <text class="d-ink sm" x="262" y="87" fill="currentColor">the Worker answers</text> | |
| 72 | + | |
| 73 | + <path class="d-soft" d="M122,102 V124" fill="none" stroke="currentColor" stroke-width="1.5" marker-end="url(#sa-arrow)" /> | |
| 74 | + | |
| 75 | + <!-- run_worker_first inverts the order for the paths it names. --> | |
| 76 | + <rect class="d-panel" x="8" y="124" width="228" height="40" rx="6" fill="currentColor" /> | |
| 77 | + <rect class="d-faint" x="8" y="124" width="228" height="40" rx="6" fill="none" stroke="currentColor" /> | |
| 78 | + <text class="d-ink mono" x="20" y="143" fill="currentColor">run_worker_first</text> | |
| 79 | + <text class="d-faint sm" x="20" y="158" fill="currentColor">true, or up to 100 patterns</text> | |
| 80 | + <path class="d-soft" d="M236,144 H252" fill="none" stroke="currentColor" stroke-width="1.5" marker-end="url(#sa-arrow)" /> | |
| 81 | + <rect class="d-sunk" x="252" y="124" width="180" height="40" rx="6" fill="currentColor" /> | |
| 82 | + <rect class="d-soft" x="252" y="124" width="180" height="40" rx="6" fill="none" stroke="currentColor" /> | |
| 83 | + <text class="d-ink sm" x="262" y="143" fill="currentColor">the Worker answers</text> | |
| 84 | + <text class="d-faint sm" x="262" y="158" fill="currentColor">no asset lookup at all</text> | |
| 85 | + | |
| 86 | + <path class="d-soft" d="M122,164 V186" fill="none" stroke="currentColor" stroke-width="1.5" marker-end="url(#sa-arrow)" /> | |
| 87 | + | |
| 88 | + <!-- _redirects runs before any file lookup. --> | |
| 89 | + <rect class="d-panel" x="8" y="186" width="228" height="80" rx="6" fill="currentColor" /> | |
| 90 | + <rect class="d-faint" x="8" y="186" width="228" height="80" rx="6" fill="none" stroke="currentColor" /> | |
| 91 | + <text class="d-ink mono" x="20" y="218" fill="currentColor">_redirects</text> | |
| 92 | + <text class="d-faint sm" x="20" y="236" fill="currentColor">file order, first match wins</text> | |
| 93 | + <g class="d-acc" fill="none" stroke="currentColor" stroke-width="1.5"> | |
| 94 | + <path d="M236,226 H244" /> | |
| 95 | + <path d="M244,204 V248" /> | |
| 96 | + <path d="M244,204 H252" marker-end="url(#sa-arrow-acc)" /> | |
| 97 | + <path d="M244,248 H252" marker-end="url(#sa-arrow-acc)" /> | |
| 98 | + </g> | |
| 99 | + <rect class="d-tint" x="252" y="186" width="180" height="36" rx="6" fill="currentColor" /> | |
| 100 | + <rect class="d-acc" x="252" y="186" width="180" height="36" rx="6" fill="none" stroke="currentColor" /> | |
| 101 | + <text class="d-ink sm" x="262" y="204" fill="currentColor">301 302 303 307 308</text> | |
| 102 | + <text class="d-faint sm" x="262" y="218" fill="currentColor">a Location, no body</text> | |
| 103 | + <rect class="d-tint" x="252" y="230" width="180" height="36" rx="6" fill="currentColor" /> | |
| 104 | + <rect class="d-acc" x="252" y="230" width="180" height="36" rx="6" fill="none" stroke="currentColor" /> | |
| 105 | + <text class="d-ink sm" x="262" y="248" fill="currentColor">200</text> | |
| 106 | + <text class="d-faint sm" x="262" y="262" fill="currentColor">restart at the destination</text> | |
| 107 | + | |
| 108 | + <path class="d-soft" d="M122,266 V288" fill="none" stroke="currentColor" stroke-width="1.5" marker-end="url(#sa-arrow)" /> | |
| 109 | + <path class="d-acc" d="M268,266 V282 H126" fill="none" stroke="currentColor" stroke-width="1.5" stroke-dasharray="4 3" marker-end="url(#sa-arrow-acc)" /> | |
| 110 | + | |
| 111 | + <!-- html_handling chooses which file a path can reach. --> | |
| 112 | + <rect class="d-panel" x="8" y="288" width="228" height="80" rx="6" fill="currentColor" /> | |
| 113 | + <rect class="d-faint" x="8" y="288" width="228" height="80" rx="6" fill="none" stroke="currentColor" /> | |
| 114 | + <text class="d-ink mono" x="20" y="320" fill="currentColor">html_handling</text> | |
| 115 | + <text class="d-faint sm" x="20" y="338" fill="currentColor">auto, force, drop, or none</text> | |
| 116 | + <g class="d-acc" fill="none" stroke="currentColor" stroke-width="1.5"> | |
| 117 | + <path d="M236,328 H244" /> | |
| 118 | + <path d="M244,306 V350" /> | |
| 119 | + <path d="M244,306 H252" marker-end="url(#sa-arrow-acc)" /> | |
| 120 | + <path d="M244,350 H252" marker-end="url(#sa-arrow-acc)" /> | |
| 121 | + </g> | |
| 122 | + <rect class="d-tint" x="252" y="288" width="180" height="36" rx="6" fill="currentColor" /> | |
| 123 | + <rect class="d-acc" x="252" y="288" width="180" height="36" rx="6" fill="none" stroke="currentColor" /> | |
| 124 | + <text class="d-ink sm" x="262" y="306" fill="currentColor">the canonical path</text> | |
| 125 | + <text class="d-faint sm" x="262" y="320" fill="currentColor">200 with the body</text> | |
| 126 | + <rect class="d-tint" x="252" y="332" width="180" height="36" rx="6" fill="currentColor" /> | |
| 127 | + <rect class="d-acc" x="252" y="332" width="180" height="36" rx="6" fill="none" stroke="currentColor" /> | |
| 128 | + <text class="d-ink sm" x="262" y="350" fill="currentColor">another spelling</text> | |
| 129 | + <text class="d-faint sm" x="262" y="364" fill="currentColor">307 to the canonical path</text> | |
| 130 | + | |
| 131 | + <path class="d-soft" d="M122,368 V390" fill="none" stroke="currentColor" stroke-width="1.5" marker-end="url(#sa-arrow)" /> | |
| 132 | + | |
| 133 | + <!-- The step Cloudflare does not need: a rolling restart leaves nodes on | |
| 134 | + different indexes, so a miss re-reads the pointer. --> | |
| 135 | + <rect class="d-panel" x="8" y="390" width="228" height="44" rx="6" fill="currentColor" /> | |
| 136 | + <rect class="d-faint" x="8" y="390" width="228" height="44" rx="6" fill="none" stroke="currentColor" /> | |
| 137 | + <text class="d-ink" x="20" y="411" fill="currentColor">Miss: re-read the pointer</text> | |
| 138 | + <text class="d-faint sm" x="20" y="427" fill="currentColor">at most once in five seconds</text> | |
| 139 | + <path class="d-acc" d="M236,412 H252" fill="none" stroke="currentColor" stroke-width="1.5" marker-end="url(#sa-arrow-acc)" /> | |
| 140 | + <rect class="d-tint" x="252" y="390" width="180" height="44" rx="6" fill="currentColor" /> | |
| 141 | + <rect class="d-acc" x="252" y="390" width="180" height="44" rx="6" fill="none" stroke="currentColor" /> | |
| 142 | + <text class="d-ink sm" x="262" y="411" fill="currentColor">a newer deployment has it</text> | |
| 143 | + <text class="d-faint sm" x="262" y="427" fill="currentColor">200 with the body</text> | |
| 144 | + | |
| 145 | + <path class="d-soft" d="M122,434 V456" fill="none" stroke="currentColor" stroke-width="1.5" marker-end="url(#sa-arrow)" /> | |
| 146 | + | |
| 147 | + <!-- not_found_handling fabricates a response, but not for every request. --> | |
| 148 | + <rect class="d-panel" x="8" y="456" width="228" height="80" rx="6" fill="currentColor" /> | |
| 149 | + <rect class="d-faint" x="8" y="456" width="228" height="80" rx="6" fill="none" stroke="currentColor" /> | |
| 150 | + <text class="d-ink mono" x="20" y="488" fill="currentColor">not_found_handling</text> | |
| 151 | + <text class="d-faint sm" x="20" y="506" fill="currentColor">navigation, or no Worker</text> | |
| 152 | + <g class="d-acc" fill="none" stroke="currentColor" stroke-width="1.5"> | |
| 153 | + <path d="M236,496 H244" /> | |
| 154 | + <path d="M244,474 V518" /> | |
| 155 | + <path d="M244,474 H252" marker-end="url(#sa-arrow-acc)" /> | |
| 156 | + <path d="M244,518 H252" marker-end="url(#sa-arrow-acc)" /> | |
| 157 | + </g> | |
| 158 | + <rect class="d-tint" x="252" y="456" width="180" height="36" rx="6" fill="currentColor" /> | |
| 159 | + <rect class="d-acc" x="252" y="456" width="180" height="36" rx="6" fill="none" stroke="currentColor" /> | |
| 160 | + <text class="d-ink sm" x="262" y="474" fill="currentColor">single-page-application</text> | |
| 161 | + <text class="d-faint sm" x="262" y="488" fill="currentColor">/index.html, 200</text> | |
| 162 | + <rect class="d-tint" x="252" y="500" width="180" height="36" rx="6" fill="currentColor" /> | |
| 163 | + <rect class="d-acc" x="252" y="500" width="180" height="36" rx="6" fill="none" stroke="currentColor" /> | |
| 164 | + <text class="d-ink sm" x="262" y="518" fill="currentColor">404-page</text> | |
| 165 | + <text class="d-faint sm" x="262" y="532" fill="currentColor">the nearest 404.html, 404</text> | |
| 166 | + | |
| 167 | + <path class="d-soft" d="M122,536 V558" fill="none" stroke="currentColor" stroke-width="1.5" marker-end="url(#sa-arrow)" /> | |
| 168 | + | |
| 169 | + <!-- The asset layer has no answer left. --> | |
| 170 | + <rect class="d-panel" x="8" y="558" width="228" height="44" rx="6" fill="currentColor" /> | |
| 171 | + <rect class="d-ink" x="8" y="558" width="228" height="44" rx="6" fill="none" stroke="currentColor" stroke-width="1.5" /> | |
| 172 | + <text class="d-ink" x="20" y="585" fill="currentColor">Nothing matched</text> | |
| 173 | + <path class="d-soft" d="M236,580 H252" fill="none" stroke="currentColor" stroke-width="1.5" marker-end="url(#sa-arrow)" /> | |
| 174 | + <rect class="d-sunk" x="252" y="558" width="180" height="44" rx="6" fill="currentColor" /> | |
| 175 | + <rect class="d-soft" x="252" y="558" width="180" height="44" rx="6" fill="none" stroke="currentColor" /> | |
| 176 | + <text class="d-ink sm" x="262" y="579" fill="currentColor">the Worker answers</text> | |
| 177 | + <text class="d-faint sm" x="262" y="595" fill="currentColor">no Worker: 404</text> | |
| 178 | + | |
| 179 | + <!-- The one outcome that never reaches the Worker. --> | |
| 180 | + <rect class="d-faint" x="8" y="624" width="424" height="42" rx="6" fill="none" stroke="currentColor" stroke-dasharray="5 4" /> | |
| 181 | + <text class="d-ink sm" x="20" y="644" fill="currentColor">A missing or corrupt asset body gives 502.</text> | |
| 182 | + <text class="d-faint sm" x="20" y="659" fill="currentColor">The request never falls through to the Worker.</text> | |
| 183 | +</svg> |
addeddocs/services/static-assets.md+147−0View file
| @@ -1,0 +1,147 @@ | ||
| 1 | +# Static assets | |
| 2 | + | |
| 3 | +Static assets serve the files of a directory, with a Worker or without one. An | |
| 4 | +application uses them for the front end that a browser downloads: an HTML page, | |
| 5 | +a stylesheet, a script bundle, a font, or an image. `celld deploy` uploads the | |
| 6 | +directory with the deployment, so the files become part of the deployed version | |
| 7 | +and not a separate store. The bytes live in the fleet bucket, and a node copies | |
| 8 | +a file to its own disk cache when it first serves that file. Read the | |
| 9 | +[Cloudflare Static Assets documentation](https://developers.cloudflare.com/workers/static-assets/) | |
| 10 | +for the standard behavior. | |
| 11 | + | |
| 12 | +## Example | |
| 13 | + | |
| 14 | +The [Static assets example](../../examples/static-assets) serves an HTML file | |
| 15 | +from the `public` directory without a Worker. A `_headers` file adds a response | |
| 16 | +header, and a `_redirects` file moves `/home` to `/`. | |
| 17 | + | |
| 18 | +<!-- celld-example: static-assets --> | |
| 19 | + | |
| 20 | +## What a deployment uploads | |
| 21 | + | |
| 22 | +An `assets` block in the Wrangler configuration names the directory. celld | |
| 23 | +accepts five keys in that block: `directory`, `binding`, `html_handling`, | |
| 24 | +`not_found_handling`, and `run_worker_first`. It refuses any other key by name, | |
| 25 | +so an unsupported Cloudflare option stops the deployment instead of changing the | |
| 26 | +behavior in silence. A project that declares `assets` and no `main` is an | |
| 27 | +asset-only project, and such a project cannot set `run_worker_first` or declare | |
| 28 | +a binding, because it runs no code. The | |
| 29 | +[binding documentation](https://developers.cloudflare.com/workers/static-assets/binding/) | |
| 30 | +describes the same keys for Cloudflare. | |
| 31 | + | |
| 32 | +`celld deploy` reads each file, takes the SHA-256 digest of the exact bytes, and | |
| 33 | +stores the body once under that digest. Two identical files in one directory | |
| 34 | +therefore upload one body. A redeploy compares the digest with the stored object | |
| 35 | +and skips a body that the fleet already holds, so a build that changes one file | |
| 36 | +uploads one file. The command also assigns a content type from a fixed table of | |
| 37 | +file extensions. An unknown extension gets no `Content-Type` header at all, | |
| 38 | +which is the behavior that Wrangler produces. | |
| 39 | + | |
| 40 | +The upload produces an index beside the deployment manifest. The index maps each | |
| 41 | +path to its digest, its size, and its content type, and it carries the `assets` | |
| 42 | +configuration and the complete text of the `_headers` and `_redirects` files. | |
| 43 | +The manifest names the index and the checksum of the index. celld writes the | |
| 44 | +bodies first, then the index, then the manifest, and the deployment pointer | |
| 45 | +last. A node therefore cannot read a pointer whose bodies are still incomplete. | |
| 46 | +A node loads only the index at startup and fetches a body when a request asks | |
| 47 | +for it, so a large asset directory does not become a large startup cost. | |
| 48 | + | |
| 49 | +## The routing decision | |
| 50 | + | |
| 51 | +A request meets the asset layer before it meets the Worker. celld considers only | |
| 52 | +a `GET` or a `HEAD` request for an asset, and it sends every other method to the | |
| 53 | +Worker. `run_worker_first` reverses the order. It takes `true`, or a list of up | |
| 54 | +to 100 route patterns in which a `!` prefix excludes a path, and a match sends | |
| 55 | +the request to the Worker with no asset lookup. Cloudflare describes the same | |
| 56 | +control in its | |
| 57 | +[Worker script routing documentation](https://developers.cloudflare.com/workers/static-assets/routing/worker-script/). | |
| 58 | + | |
| 59 | + | |
| 60 | + | |
| 61 | +The `_redirects` rules run before any file lookup, in file order, and the first | |
| 62 | +match wins. A rule with status 301, 302, 303, 307, or 308 answers with a | |
| 63 | +`Location` header. A rule with status 200 names a local path, and routing | |
| 64 | +restarts at that path, so the client sees the destination content under the | |
| 65 | +original URL. | |
| 66 | + | |
| 67 | +`html_handling` then decides which file a path can reach. | |
| 68 | +`auto-trailing-slash` is the default, and it maps `/about` to `/about.html` and | |
| 69 | +`/about/` to `/about/index.html`. `force-trailing-slash` and | |
| 70 | +`drop-trailing-slash` pick one spelling, and `none` matches the exact path only. | |
| 71 | +When the request uses a spelling that is not the canonical one, celld answers | |
| 72 | +`307` to the canonical path and keeps the query string. The | |
| 73 | +[html_handling documentation](https://developers.cloudflare.com/workers/static-assets/routing/advanced/html-handling/) | |
| 74 | +lists the same four modes. | |
| 75 | + | |
| 76 | +A miss has one more step that Cloudflare does not need. celld re-reads the | |
| 77 | +deployment pointer, at most once in five seconds, because a rolling restart can | |
| 78 | +leave one node on an older index while an upgraded node serves HTML that names a | |
| 79 | +newer content-hashed file. A newer index therefore answers the request instead | |
| 80 | +of a broken page. | |
| 81 | + | |
| 82 | +`not_found_handling` fabricates the last answer. `single-page-application` | |
| 83 | +returns `/index.html` with status 200, and `404-page` returns the nearest | |
| 84 | +`404.html` with status 404, which | |
| 85 | +[Cloudflare also does](https://developers.cloudflare.com/workers/static-assets/routing/single-page-application/). | |
| 86 | +celld applies this step only when the deployment has no Worker, or when the | |
| 87 | +request is a navigation request. A deployment with a Worker therefore keeps a | |
| 88 | +non-navigation miss for the Worker, and the Worker answers it. When nothing | |
| 89 | +matches and there is no Worker, the node answers `404`. | |
| 90 | + | |
| 91 | +One failure never reaches the Worker. A body that the fleet bucket cannot supply | |
| 92 | +gives `502`, because a silent fall through would run the Worker for a request | |
| 93 | +that an asset owns. | |
| 94 | + | |
| 95 | +## How a node serves a file | |
| 96 | + | |
| 97 | +A node fetches a body once and writes it to a local disk cache. It verifies the | |
| 98 | +digest after the write, and it keeps the cache under a bound of 512 MiB that | |
| 99 | +`CELLD_ASSET_CACHE_BYTES` changes. The cache evicts the least recently used file | |
| 100 | +when it crosses the bound, so the cache is a copy and never the durable record. | |
| 101 | +The fleet bucket holds the durable bytes. | |
| 102 | + | |
| 103 | +The `ETag` is the strong SHA-256 digest of the body. A conditional `GET` with | |
| 104 | +`If-None-Match` therefore gives `304` with no body, and a changed file gives a | |
| 105 | +new tag. celld sends no `Last-Modified` header and reads no `If-Modified-Since` | |
| 106 | +header, so revalidation uses the tag. A `Range` header selects one byte range | |
| 107 | +and gives `206`, an unsatisfiable range gives `416`, and a `HEAD` request keeps | |
| 108 | +the real `Content-Length` with an empty body. celld also sends | |
| 109 | +`Cache-Control: public, max-age=0, must-revalidate` on a plain request, which | |
| 110 | +makes a browser revalidate each time. | |
| 111 | + | |
| 112 | +celld runs no edge cache and no content delivery network, so this response path | |
| 113 | +is the whole of it. Cloudflare caches an asset in the location that serves the | |
| 114 | +request and pulls a miss from a nearby cache. A celld fleet has only the | |
| 115 | +machines that you run. Latency comes from your own placement, and a `_headers` | |
| 116 | +rule that sets a long `Cache-Control` on a content-hashed file is the way to | |
| 117 | +keep a browser from asking again. | |
| 118 | + | |
| 119 | +A `binding` name puts the same serving code behind `env.ASSETS.fetch()`. The | |
| 120 | +binding takes a `Request`, a `URL`, or a string, and `fetch()` is its only | |
| 121 | +method. It answers `405` for a method other than `GET` or `HEAD`, and it always | |
| 122 | +applies `not_found_handling`, so a Worker can render a fallback page itself. | |
| 123 | + | |
| 124 | +## Differences from Cloudflare | |
| 125 | + | |
| 126 | +- celld does not compress an asset response. Use a compressing ingress proxy | |
| 127 | + when a client needs gzip or brotli. | |
| 128 | +- celld has no edge cache. Each node keeps a 512 MiB disk cache, configured by | |
| 129 | + `CELLD_ASSET_CACHE_BYTES`, and requires browser revalidation. | |
| 130 | +- A node checks the deployment pointer after an asset miss at most once in five | |
| 131 | + seconds. | |
| 132 | +- celld reads `If-None-Match` and `If-Range`. It sends no `Last-Modified` header | |
| 133 | + and reads no `If-Modified-Since` header. | |
| 134 | +- A `_headers` file cannot change `connection`, `content-length`, or | |
| 135 | + `transfer-encoding`. | |
| 136 | +- A deployment can contain 20,000 assets, 25 MiB for each asset, and 1 GiB in | |
| 137 | + total. Each `_headers` or `_redirects` file has a 100 KiB limit. | |
| 138 | +- `celld deploy` accepts only `directory`, `binding`, `html_handling`, | |
| 139 | + `not_found_handling`, and `run_worker_first` in the `assets` block. | |
| 140 | +- `celld deploy` refuses a `.assetsignore` file, and it stops the deployment | |
| 141 | + instead of ignoring the file. It also refuses a symbolic link, a special | |
| 142 | + file, a non-UTF-8 name, an unsafe decoded path, and a `_worker.js` entry. | |
| 143 | +- The assets binding has one method, `fetch()`. celld supplies no `unstable_` | |
| 144 | + helper. | |
| 145 | + | |
| 146 | +The [Cloudflare compatibility](../cloudflare-compat.md#services) page | |
| 147 | +lists the runtime APIs and the unsupported services. |
addeddocs/services/workers-flow.svg+111−0View file
| @@ -1,0 +1,111 @@ | ||
| 1 | +<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 400 454" role="img" aria-labelledby="workersFlowTitle workersFlowDesc"> | |
| 2 | + <title id="workersFlowTitle">Where a Worker request runs on a celld fleet</title> | |
| 3 | + <desc id="workersFlowDesc">An ingress terminates TLS and can send a request to any node of the fleet. The node that accepts the request runs the Worker deployment in a V8 isolate and calls fetch with the request, env, and ctx. The handler returns a Response. The env object holds the bindings, and a binding call leaves the isolate: a KV namespace, a D1 database, a queue, and a Durable Object are each a cell with one owner node, and an R2 binding reads the shared fleet bucket instead.</desc> | |
| 4 | + <style> | |
| 5 | + /* GitHub renders this file as an image, so the diagram carries literal | |
| 6 | + colours here. The site rules in landing/src/style.css are more specific, | |
| 7 | + so the documentation theme tokens win there. SVG paints text black by | |
| 8 | + default, and a class that sets only `color` never reaches the fill, so | |
| 9 | + every label sets fill="currentColor" as well. */ | |
| 10 | + svg { font-family: ui-sans-serif, system-ui, -apple-system, sans-serif; } | |
| 11 | + text { font-size: 13px; fill: currentColor; } | |
| 12 | + .mono { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; } | |
| 13 | + .d-ink { color: #121212; } | |
| 14 | + .d-soft { color: #3d3b37; } | |
| 15 | + .d-faint { color: #6e6a62; } | |
| 16 | + .d-acc { color: #10803f; } | |
| 17 | + .d-panel { color: #ffffff; } | |
| 18 | + .d-sunk { color: #f0eee8; } | |
| 19 | + .d-tint { color: #d6efdf; } | |
| 20 | + @media (prefers-color-scheme: dark) { | |
| 21 | + .d-ink { color: #efede7; } | |
| 22 | + .d-soft { color: #c9c6be; } | |
| 23 | + .d-faint { color: #928e85; } | |
| 24 | + .d-acc { color: #3fc472; } | |
| 25 | + .d-panel { color: #1a1a19; } | |
| 26 | + .d-sunk { color: #232321; } | |
| 27 | + .d-tint { color: #10301d; } | |
| 28 | + } | |
| 29 | + </style> | |
| 30 | + <defs> | |
| 31 | + <marker id="wf-arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="6" markerHeight="6" orient="auto-start-reverse"> | |
| 32 | + <path class="d-soft" d="M0,1 L9,5 L0,9 z" fill="currentColor"/> | |
| 33 | + </marker> | |
| 34 | + <marker id="wf-arrow-acc" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="6" markerHeight="6" orient="auto-start-reverse"> | |
| 35 | + <path class="d-acc" d="M0,1 L9,5 L0,9 z" fill="currentColor"/> | |
| 36 | + </marker> | |
| 37 | + </defs> | |
| 38 | + | |
| 39 | + <!-- client and ingress: TLS ends outside celld --> | |
| 40 | + <rect class="d-panel" x="110" y="8" width="180" height="34" rx="6" fill="currentColor"/> | |
| 41 | + <rect class="d-ink" x="110" y="8" width="180" height="34" rx="6" fill="none" stroke="currentColor" stroke-width="1.5"/> | |
| 42 | + <text class="d-ink" x="200" y="30" fill="currentColor" text-anchor="middle">HTTP client</text> | |
| 43 | + <path class="d-soft" d="M200,42 V58" fill="none" stroke="currentColor" stroke-width="1.5" marker-end="url(#wf-arrow)"/> | |
| 44 | + | |
| 45 | + <rect class="d-panel" x="70" y="62" width="260" height="46" rx="6" fill="currentColor"/> | |
| 46 | + <rect class="d-ink" x="70" y="62" width="260" height="46" rx="6" fill="none" stroke="currentColor" stroke-width="1.5"/> | |
| 47 | + <text class="d-ink" x="200" y="84" fill="currentColor" text-anchor="middle">Ingress or load balancer</text> | |
| 48 | + <text class="d-soft" x="200" y="101" fill="currentColor" text-anchor="middle">terminates TLS</text> | |
| 49 | + | |
| 50 | + <!-- any node of the fleet can accept the request --> | |
| 51 | + <path class="d-soft" d="M200,108 C200,124 66,114 66,126" fill="none" stroke="currentColor" stroke-width="1.5" marker-end="url(#wf-arrow)"/> | |
| 52 | + <path class="d-soft" d="M200,108 V126" fill="none" stroke="currentColor" stroke-width="1.5" marker-end="url(#wf-arrow)"/> | |
| 53 | + <path class="d-soft" d="M200,108 C200,124 334,114 334,126" fill="none" stroke="currentColor" stroke-width="1.5" marker-end="url(#wf-arrow)"/> | |
| 54 | + | |
| 55 | + <rect class="d-ink" x="8" y="132" width="116" height="32" rx="6" fill="none" stroke="currentColor" stroke-width="1.5"/> | |
| 56 | + <text class="d-ink" x="66" y="153" fill="currentColor" text-anchor="middle">celld node</text> | |
| 57 | + <rect class="d-acc" x="142" y="132" width="116" height="32" rx="6" fill="none" stroke="currentColor" stroke-width="1.5"/> | |
| 58 | + <text class="d-ink" x="200" y="153" fill="currentColor" text-anchor="middle">celld node</text> | |
| 59 | + <rect class="d-ink" x="276" y="132" width="116" height="32" rx="6" fill="none" stroke="currentColor" stroke-width="1.5"/> | |
| 60 | + <text class="d-ink" x="334" y="153" fill="currentColor" text-anchor="middle">celld node</text> | |
| 61 | + | |
| 62 | + <path class="d-soft" d="M200,164 V184" fill="none" stroke="currentColor" stroke-width="1.5" marker-end="url(#wf-arrow)"/> | |
| 63 | + <text class="d-faint" x="208" y="180" fill="currentColor">any node</text> | |
| 64 | + | |
| 65 | + <!-- the isolate of the accepting node --> | |
| 66 | + <rect class="d-sunk" x="20" y="188" width="360" height="124" rx="8" fill="currentColor"/> | |
| 67 | + <rect class="d-ink" x="20" y="188" width="360" height="124" rx="8" fill="none" stroke="currentColor" stroke-width="1.5"/> | |
| 68 | + <text class="d-soft" x="200" y="211" fill="currentColor" text-anchor="middle">Worker deployment in a V8 isolate</text> | |
| 69 | + | |
| 70 | + <rect class="d-tint" x="60" y="220" width="280" height="32" rx="6" fill="currentColor"/> | |
| 71 | + <rect class="d-acc" x="60" y="220" width="280" height="32" rx="6" fill="none" stroke="currentColor" stroke-width="1.5"/> | |
| 72 | + <text class="d-ink mono" x="200" y="241" fill="currentColor" text-anchor="middle">fetch(request, env, ctx)</text> | |
| 73 | + | |
| 74 | + <path class="d-soft" d="M150,252 C150,268 110,258 110,268" fill="none" stroke="currentColor" stroke-width="1.5" marker-end="url(#wf-arrow)"/> | |
| 75 | + <path class="d-acc" d="M250,252 C250,268 290,258 290,268" fill="none" stroke="currentColor" stroke-width="1.5" marker-end="url(#wf-arrow-acc)"/> | |
| 76 | + | |
| 77 | + <rect class="d-panel" x="40" y="272" width="140" height="30" rx="6" fill="currentColor"/> | |
| 78 | + <rect class="d-ink" x="40" y="272" width="140" height="30" rx="6" fill="none" stroke="currentColor" stroke-width="1.5"/> | |
| 79 | + <text class="d-ink" x="110" y="292" fill="currentColor" text-anchor="middle">Response</text> | |
| 80 | + | |
| 81 | + <rect class="d-panel" x="228" y="272" width="124" height="30" rx="6" fill="currentColor"/> | |
| 82 | + <rect class="d-acc" x="228" y="272" width="124" height="30" rx="6" fill="none" stroke="currentColor" stroke-width="1.5"/> | |
| 83 | + <text class="d-ink mono" x="290" y="292" fill="currentColor" text-anchor="middle">env</text> | |
| 84 | + | |
| 85 | + <!-- a binding call leaves the isolate, and its target decides where it goes --> | |
| 86 | + <path class="d-acc" d="M290,302 V330" fill="none" stroke="currentColor" stroke-width="1.5"/> | |
| 87 | + <path class="d-acc" d="M142,330 H338" fill="none" stroke="currentColor" stroke-width="1.5"/> | |
| 88 | + <path class="d-acc" d="M142,330 V348" fill="none" stroke="currentColor" stroke-width="1.5" marker-end="url(#wf-arrow-acc)"/> | |
| 89 | + <path class="d-acc" d="M338,330 V348" fill="none" stroke="currentColor" stroke-width="1.5" marker-end="url(#wf-arrow-acc)"/> | |
| 90 | + <text class="d-faint" x="96" y="326" fill="currentColor" text-anchor="middle">to the owner</text> | |
| 91 | + <text class="d-faint" x="366" y="326" fill="currentColor" text-anchor="middle">direct</text> | |
| 92 | + | |
| 93 | + <rect class="d-soft" x="8" y="352" width="268" height="92" rx="8" fill="none" stroke="currentColor" stroke-width="1.5"/> | |
| 94 | + <text class="d-ink" x="142" y="370" fill="currentColor" text-anchor="middle">cells</text> | |
| 95 | + <text class="d-faint" x="142" y="386" fill="currentColor" text-anchor="middle">one owner node each</text> | |
| 96 | + <rect class="d-soft" x="14" y="394" width="58" height="40" rx="6" fill="none" stroke="currentColor" stroke-width="1.5"/> | |
| 97 | + <text class="d-ink" x="43" y="419" fill="currentColor" text-anchor="middle">KV</text> | |
| 98 | + <rect class="d-soft" x="78" y="394" width="58" height="40" rx="6" fill="none" stroke="currentColor" stroke-width="1.5"/> | |
| 99 | + <text class="d-ink" x="107" y="419" fill="currentColor" text-anchor="middle">D1</text> | |
| 100 | + <rect class="d-soft" x="142" y="394" width="58" height="40" rx="6" fill="none" stroke="currentColor" stroke-width="1.5"/> | |
| 101 | + <text class="d-ink" x="171" y="419" fill="currentColor" text-anchor="middle">Queues</text> | |
| 102 | + <rect class="d-soft" x="206" y="394" width="58" height="40" rx="6" fill="none" stroke="currentColor" stroke-width="1.5"/> | |
| 103 | + <text class="d-ink" x="235" y="412" fill="currentColor" text-anchor="middle">Durable</text> | |
| 104 | + <text class="d-ink" x="235" y="427" fill="currentColor" text-anchor="middle">Objects</text> | |
| 105 | + | |
| 106 | + <rect class="d-soft" x="284" y="352" width="108" height="92" rx="8" fill="none" stroke="currentColor" stroke-width="1.5"/> | |
| 107 | + <text class="d-ink" x="338" y="370" fill="currentColor" text-anchor="middle">fleet bucket</text> | |
| 108 | + <text class="d-faint" x="338" y="386" fill="currentColor" text-anchor="middle">no owner</text> | |
| 109 | + <rect class="d-soft" x="292" y="394" width="92" height="40" rx="6" fill="none" stroke="currentColor" stroke-width="1.5"/> | |
| 110 | + <text class="d-ink" x="338" y="419" fill="currentColor" text-anchor="middle">R2</text> | |
| 111 | +</svg> |
addeddocs/services/workers.md+83−0View file
| @@ -1,0 +1,83 @@ | ||
| 1 | +# Workers | |
| 2 | + | |
| 3 | +A Worker is a stateless request handler that uses the Cloudflare Workers API. | |
| 4 | +An application uses a Worker for the code that answers an HTTP request, such as | |
| 5 | +an API endpoint, a router, a webhook receiver, or a front end for a binding. | |
| 6 | +celld runs the deployment in a V8 isolate on a node of the fleet, so a Worker | |
| 7 | +keeps the persistent state of an application in a binding instead. Read the | |
| 8 | +[Cloudflare Workers documentation](https://developers.cloudflare.com/workers/runtime-apis/) | |
| 9 | +for the standard API behavior. | |
| 10 | + | |
| 11 | +## Example | |
| 12 | + | |
| 13 | +The [hello example](../../examples/hello) returns a text response from a | |
| 14 | +`fetch` handler. | |
| 15 | + | |
| 16 | +<!-- celld-example: hello --> | |
| 17 | + | |
| 18 | +## The request path | |
| 19 | + | |
| 20 | +An operator puts an ingress proxy or a load balancer in front of the fleet. | |
| 21 | +The ingress terminates TLS, because celld serves plain HTTP on the public | |
| 22 | +listener of a node. The load balancer can send a request to any node in its | |
| 23 | +rotation, and every node embeds V8 and holds the current deployment. The node | |
| 24 | +that accepts the request therefore runs the handler itself, and it forwards | |
| 25 | +only a binding call that a different node owns. | |
| 26 | + | |
| 27 | +Cloudflare instead routes a request through its own global network and starts | |
| 28 | +the Worker in a nearby data center. A celld fleet has only the machines that | |
| 29 | +you run, so you control the placement and the routing. Read | |
| 30 | +[How Workers works](https://developers.cloudflare.com/workers/reference/how-workers-works/) | |
| 31 | +for the Cloudflare model. | |
| 32 | + | |
| 33 | + | |
| 34 | + | |
| 35 | +## The handler | |
| 36 | + | |
| 37 | +An HTTP request invokes the `fetch(request, env, ctx)` handler that the module | |
| 38 | +exports as its default export. The handler receives the inbound `Request`, and | |
| 39 | +it must return a `Response`. A module can export more handlers, such as | |
| 40 | +`scheduled` for a Cron Trigger or `queue` for a Queues consumer. Read the | |
| 41 | +[handlers documentation](https://developers.cloudflare.com/workers/runtime-apis/handlers/) | |
| 42 | +for the complete list, and the | |
| 43 | +[fetch handler documentation](https://developers.cloudflare.com/workers/runtime-apis/handlers/fetch/) | |
| 44 | +for the parameters. | |
| 45 | + | |
| 46 | +The `ctx` argument controls the lifetime of the invocation. `ctx.waitUntil()` | |
| 47 | +keeps the isolate alive for a promise after the response goes to the client. | |
| 48 | +`ctx.passThroughOnException()` has no effect on celld, because celld has no CDN | |
| 49 | +that can answer in place of a failed Worker. | |
| 50 | + | |
| 51 | +## State and bindings | |
| 52 | + | |
| 53 | +The `env` argument contains the bindings that the Wrangler configuration | |
| 54 | +declares. A binding gives the Worker a permission and an API together, so the | |
| 55 | +code needs no credential for the target service. Read the | |
| 56 | +[bindings documentation](https://developers.cloudflare.com/workers/runtime-apis/bindings/) | |
| 57 | +for the configuration syntax. | |
| 58 | + | |
| 59 | +A binding call leaves the isolate, and the target decides where the call goes. | |
| 60 | +A KV namespace, a D1 database, a queue, and a Durable Object are each a cell, | |
| 61 | +and one node owns a cell at a time, so celld routes the call to that owner. An | |
| 62 | +R2 binding has no cell, and it reads and writes the fleet bucket directly. | |
| 63 | + | |
| 64 | +celld runs many requests in one isolate, so a value in the module scope can | |
| 65 | +still be present for a later request. That value is not a safe place for | |
| 66 | +application state. The load balancer can send the next request to a different | |
| 67 | +node, and celld retires an isolate when the request load falls or when a new | |
| 68 | +deployment supersedes it, so the value can also disappear. A Worker must | |
| 69 | +therefore not depend on mutable in-memory state, and it must write the state | |
| 70 | +that it must keep into a binding. The Cloudflare | |
| 71 | +[best practices](https://developers.cloudflare.com/workers/best-practices/workers-best-practices/) | |
| 72 | +give the same rule. | |
| 73 | + | |
| 74 | +## Differences from Cloudflare | |
| 75 | + | |
| 76 | +- celld does not manage a custom domain or terminate TLS. Terminate TLS in the | |
| 77 | + ingress proxy. | |
| 78 | +- celld does not supply a Workers AI binding. Call an AI provider from the | |
| 79 | + application. The process rejects `CELLD_AI_BINDING` and `CELLD_AI_URL`, and a | |
| 80 | + deployment rejects an `ai` declaration. | |
| 81 | + | |
| 82 | +The [Cloudflare compatibility](../cloudflare-compat.md#services) page lists the | |
| 83 | +runtime APIs and the unsupported services. |
addeddocs/services/workflows-flow.svg+125−0View file
| @@ -1,0 +1,125 @@ | ||
| 1 | +<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 420" role="img" aria-labelledby="wfFlowTitle wfFlowDesc"> | |
| 2 | + <title id="wfFlowTitle">A replay re-enters run() from the top, and the ledger answers for every finished step</title> | |
| 3 | + <desc id="wfFlowDesc">A workflow instance starts when create() makes the first run, and it starts again every time the cell alarm fires on the node that owns the cell at that moment. Each run re-executes run(event, step) from the first line. The instance cell holds a ledger under the __wf prefix, with one record per step occurrence. The first two steps, step.do("fetch") and step.do("charge"), read their stored results out of the ledger records step.1.fetch and step.1.charge, so their callbacks do not run again. A key counts the occurrences of one step name, so each of these names is at its first occurrence. The third step, step.sleep("wait"), reads the record step.1.wait, finds the stored wake time, and blocks because the deadline is not due. The run then arms the cell alarm at the earliest blocked deadline and returns, so the cell hibernates and a fleet wake entry holds the time instead of an isolate. No isolate waits for the deadline, and the node that owns the cell when the alarm fires runs the next replay. The loop closes from the hibernated cell back to the alarm on every resume.</desc> | |
| 4 | + <style> | |
| 5 | + svg { font-family: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Helvetica, Arial, sans-serif; } | |
| 6 | + text { font-size: 12.5px; fill: currentColor; } | |
| 7 | + tspan { fill: currentColor; } | |
| 8 | + .sm { font-size: 11.5px; } | |
| 9 | + .mono { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; font-size: 11.5px; } | |
| 10 | + .d-ink { color: #121212; } | |
| 11 | + .d-soft { color: #3d3b37; } | |
| 12 | + .d-faint { color: #6e6a62; } | |
| 13 | + .d-acc { color: #10803f; } | |
| 14 | + .d-panel { color: #ffffff; } | |
| 15 | + .d-sunk { color: #f0eee8; } | |
| 16 | + .d-tint { color: #d6efdf; } | |
| 17 | + @media (prefers-color-scheme: dark) { | |
| 18 | + .d-ink { color: #efede7; } | |
| 19 | + .d-soft { color: #c9c6be; } | |
| 20 | + .d-faint { color: #928e85; } | |
| 21 | + .d-acc { color: #3fc472; } | |
| 22 | + .d-panel { color: #1a1a19; } | |
| 23 | + .d-sunk { color: #232321; } | |
| 24 | + .d-tint { color: #10301d; } | |
| 25 | + } | |
| 26 | + </style> | |
| 27 | + <defs> | |
| 28 | + <marker id="wf-arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="6" | |
| 29 | + markerHeight="6" orient="auto-start-reverse"> | |
| 30 | + <path class="d-soft" fill="currentColor" d="M0 0 L10 5 L0 10 z" /> | |
| 31 | + </marker> | |
| 32 | + </defs> | |
| 33 | + | |
| 34 | + <!-- The two entries into a run: the first create, and every later alarm. --> | |
| 35 | + <rect class="d-tint" fill="currentColor" x="36" y="6" width="216" height="44" rx="6" /> | |
| 36 | + <rect class="d-acc" fill="none" stroke="currentColor" stroke-width="2" x="36" y="6" width="216" height="44" rx="6" /> | |
| 37 | + <text class="d-ink" fill="currentColor" x="144" y="26" text-anchor="middle">the alarm fires</text> | |
| 38 | + <text class="d-soft sm" fill="currentColor" x="144" y="42" text-anchor="middle">on the node that owns the cell</text> | |
| 39 | + | |
| 40 | + <rect class="d-panel" fill="currentColor" x="288" y="6" width="152" height="44" rx="6" /> | |
| 41 | + <rect class="d-soft" fill="none" stroke="currentColor" x="288" y="6" width="152" height="44" rx="6" /> | |
| 42 | + <text class="d-ink mono" fill="currentColor" x="364" y="26" text-anchor="middle">create()</text> | |
| 43 | + <text class="d-soft sm" fill="currentColor" x="364" y="42" text-anchor="middle">starts the first run</text> | |
| 44 | + | |
| 45 | + <g class="d-soft" fill="none" stroke="currentColor" stroke-width="1.5"> | |
| 46 | + <path d="M364 50 V56 H144" /> | |
| 47 | + <path d="M144 50 V62" marker-end="url(#wf-arrow)" /> | |
| 48 | + </g> | |
| 49 | + | |
| 50 | + <!-- The replay: one invocation that always begins at the first line. --> | |
| 51 | + <rect class="d-sunk" fill="currentColor" x="36" y="62" width="216" height="206" rx="8" /> | |
| 52 | + <rect class="d-soft" fill="none" stroke="currentColor" x="36" y="62" width="216" height="206" rx="8" /> | |
| 53 | + <text class="d-ink mono" fill="currentColor" x="144" y="84" text-anchor="middle">run(event, step)</text> | |
| 54 | + <text class="d-faint sm" fill="currentColor" x="144" y="101" text-anchor="middle">re-executed from the top</text> | |
| 55 | + | |
| 56 | + <rect class="d-panel" fill="currentColor" x="46" y="112" width="196" height="44" rx="6" /> | |
| 57 | + <rect class="d-soft" fill="none" stroke="currentColor" x="46" y="112" width="196" height="44" rx="6" /> | |
| 58 | + <text class="d-ink mono" fill="currentColor" x="58" y="131">step.do("fetch")</text> | |
| 59 | + <text class="d-acc sm" fill="currentColor" x="58" y="148">ledger hit, callback skipped</text> | |
| 60 | + | |
| 61 | + <rect class="d-panel" fill="currentColor" x="46" y="164" width="196" height="44" rx="6" /> | |
| 62 | + <rect class="d-soft" fill="none" stroke="currentColor" x="46" y="164" width="196" height="44" rx="6" /> | |
| 63 | + <text class="d-ink mono" fill="currentColor" x="58" y="183">step.do("charge")</text> | |
| 64 | + <text class="d-acc sm" fill="currentColor" x="58" y="200">ledger hit, callback skipped</text> | |
| 65 | + | |
| 66 | + <rect class="d-tint" fill="currentColor" x="46" y="216" width="196" height="44" rx="6" /> | |
| 67 | + <rect class="d-acc" fill="none" stroke="currentColor" stroke-width="2" x="46" y="216" width="196" height="44" rx="6" /> | |
| 68 | + <text class="d-ink mono" fill="currentColor" x="58" y="235">step.sleep("wait")</text> | |
| 69 | + <text class="d-soft sm" fill="currentColor" x="58" y="252">not due, so it blocks</text> | |
| 70 | + | |
| 71 | + <!-- The ledger in the instance cell: one record per step occurrence. --> | |
| 72 | + <rect class="d-sunk" fill="currentColor" x="288" y="62" width="152" height="206" rx="8" /> | |
| 73 | + <rect class="d-soft" fill="none" stroke="currentColor" x="288" y="62" width="152" height="206" rx="8" /> | |
| 74 | + <text class="d-ink" fill="currentColor" x="364" y="84" text-anchor="middle">instance cell</text> | |
| 75 | + <text class="d-faint mono" fill="currentColor" x="364" y="101" text-anchor="middle">__wf ledger</text> | |
| 76 | + | |
| 77 | + <rect class="d-panel" fill="currentColor" x="296" y="112" width="136" height="44" rx="6" /> | |
| 78 | + <rect class="d-soft" fill="none" stroke="currentColor" x="296" y="112" width="136" height="44" rx="6" /> | |
| 79 | + <text class="d-soft mono" fill="currentColor" x="306" y="131">step.1.fetch</text> | |
| 80 | + <text class="d-ink mono" fill="currentColor" x="306" y="148">{bytes: 812}</text> | |
| 81 | + | |
| 82 | + <rect class="d-panel" fill="currentColor" x="296" y="164" width="136" height="44" rx="6" /> | |
| 83 | + <rect class="d-soft" fill="none" stroke="currentColor" x="296" y="164" width="136" height="44" rx="6" /> | |
| 84 | + <text class="d-soft mono" fill="currentColor" x="306" y="183">step.1.charge</text> | |
| 85 | + <text class="d-ink mono" fill="currentColor" x="306" y="200">{ok: true}</text> | |
| 86 | + | |
| 87 | + <rect class="d-tint" fill="currentColor" x="296" y="216" width="136" height="44" rx="6" /> | |
| 88 | + <rect class="d-acc" fill="none" stroke="currentColor" stroke-width="2" x="296" y="216" width="136" height="44" rx="6" /> | |
| 89 | + <text class="d-soft mono" fill="currentColor" x="306" y="235">step.1.wait</text> | |
| 90 | + <text class="d-ink mono" fill="currentColor" x="306" y="252">wake at 09:00</text> | |
| 91 | + | |
| 92 | + <!-- The ledger answers; the callback never starts. --> | |
| 93 | + <g class="d-soft" fill="none" stroke="currentColor" stroke-width="1.5"> | |
| 94 | + <path d="M288 134 H254" marker-end="url(#wf-arrow)" /> | |
| 95 | + <path d="M288 186 H254" marker-end="url(#wf-arrow)" /> | |
| 96 | + <path d="M288 238 H254" marker-end="url(#wf-arrow)" /> | |
| 97 | + <path d="M144 268 V292" marker-end="url(#wf-arrow)" /> | |
| 98 | + <path d="M144 344 V356" marker-end="url(#wf-arrow)" /> | |
| 99 | + </g> | |
| 100 | + | |
| 101 | + <!-- The blocked step ends the invocation instead of waiting inside it. --> | |
| 102 | + <rect class="d-panel" fill="currentColor" x="36" y="292" width="216" height="52" rx="6" /> | |
| 103 | + <rect class="d-soft" fill="none" stroke="currentColor" x="36" y="292" width="216" height="52" rx="6" /> | |
| 104 | + <text class="d-ink" fill="currentColor" x="144" y="313" text-anchor="middle">arm the cell alarm at the</text> | |
| 105 | + <text class="d-ink" fill="currentColor" x="144" y="331" text-anchor="middle">earliest blocked deadline</text> | |
| 106 | + | |
| 107 | + <rect class="d-sunk" fill="currentColor" x="36" y="356" width="216" height="52" rx="6" /> | |
| 108 | + <rect class="d-soft" fill="none" stroke="currentColor" x="36" y="356" width="216" height="52" rx="6" /> | |
| 109 | + <text class="d-ink" fill="currentColor" x="144" y="377" text-anchor="middle">the cell hibernates</text> | |
| 110 | + <text class="d-soft sm" fill="currentColor" x="144" y="395" text-anchor="middle">a fleet wake entry holds the time</text> | |
| 111 | + | |
| 112 | + <rect class="d-faint" fill="none" stroke="currentColor" stroke-dasharray="5 4" | |
| 113 | + x="288" y="292" width="152" height="116" rx="8" /> | |
| 114 | + <text class="d-faint sm" fill="currentColor" x="364" y="318" text-anchor="middle">no isolate waits</text> | |
| 115 | + <text class="d-faint sm" fill="currentColor" x="364" y="336" text-anchor="middle">for the deadline.</text> | |
| 116 | + <text class="d-faint sm" fill="currentColor" x="364" y="360" text-anchor="middle">the owner at that</text> | |
| 117 | + <text class="d-faint sm" fill="currentColor" x="364" y="378" text-anchor="middle">moment runs the</text> | |
| 118 | + <text class="d-faint sm" fill="currentColor" x="364" y="396" text-anchor="middle">next replay.</text> | |
| 119 | + | |
| 120 | + <!-- The back edge: the loop that makes this a replay and not a sequence. --> | |
| 121 | + <path class="d-soft" fill="none" stroke="currentColor" stroke-width="1.5" | |
| 122 | + stroke-dasharray="6 4" d="M36 382 H10 V28 H36" marker-end="url(#wf-arrow)" /> | |
| 123 | + <text class="d-faint sm" fill="currentColor" x="26" y="200" text-anchor="middle" | |
| 124 | + transform="rotate(-90 26 200)">every resume</text> | |
| 125 | +</svg> |
addeddocs/services/workflows.md+123−0View file
| @@ -1,0 +1,123 @@ | ||
| 1 | +# Workflows | |
| 2 | + | |
| 3 | +A Workflow is a durable function that runs as a named sequence of steps, | |
| 4 | +sleeps, and events. An application uses a Workflow for work that must survive a | |
| 5 | +failure or a long delay, such as an order pipeline, a staged import, or an | |
| 6 | +export that retries. celld runs each instance as a cell, so the state of an | |
| 7 | +instance lives in that cell's storage and moves with the cell. Read the | |
| 8 | +[Cloudflare Workflows documentation](https://developers.cloudflare.com/workflows/build/workers-api/) | |
| 9 | +for the standard API behavior. | |
| 10 | + | |
| 11 | +## Example | |
| 12 | + | |
| 13 | +The [Workflow example](../../examples/workflow) fetches a document and stores | |
| 14 | +the result of a durable step. | |
| 15 | + | |
| 16 | +<!-- celld-example: workflow --> | |
| 17 | + | |
| 18 | +## Steps and replay | |
| 19 | + | |
| 20 | +A Workflow class extends `WorkflowEntrypoint` and implements | |
| 21 | +`run(event, step)`. `event.payload` holds the parameters that `create()` | |
| 22 | +supplied, and the `step` object supplies the durable operations. A value that | |
| 23 | +`run()` returns becomes the `output` field of `status()`. Read the | |
| 24 | +[Workers API documentation](https://developers.cloudflare.com/workflows/build/workers-api/) | |
| 25 | +for the complete signature. | |
| 26 | + | |
| 27 | +celld does not stop `run()` in place and continue it later. Each time an | |
| 28 | +instance makes progress, celld calls `run()` again from the first line. A step | |
| 29 | +that already finished returns its stored result, and its callback does not run | |
| 30 | +a second time. celld writes each result into the storage of the instance cell, | |
| 31 | +under a key that joins the step name and the occurrence count of that name, so | |
| 32 | +a step inside a loop keeps one record for each iteration. | |
| 33 | + | |
| 34 | + | |
| 35 | + | |
| 36 | +This design puts one rule on the application code: everything outside a step | |
| 37 | +callback runs again on every replay. Put each subrequest, each side effect, and | |
| 38 | +each value that must stay stable inside a `step.do()` callback. Cloudflare | |
| 39 | +gives the same rule in the | |
| 40 | +[rules of Workflows](https://developers.cloudflare.com/workflows/build/rules-of-workflows/). | |
| 41 | + | |
| 42 | +celld ends an invocation when no step callback runs and no step can make | |
| 43 | +progress. `run()` can also await work that is not a step. Upstream permits that | |
| 44 | +await and does not make it durable, and celld accepts it for a short time. A | |
| 45 | +replay cannot resume such an await, therefore celld fails the instance when it | |
| 46 | +keeps `run()` pending for 60 seconds while no step runs and none waits. | |
| 47 | + | |
| 48 | +## Sleeping and waiting for an event | |
| 49 | + | |
| 50 | +`step.sleep(name, duration)` and `step.sleepUntil(name, timestamp)` stop the | |
| 51 | +instance until a deadline. `step.waitForEvent(name, options)` stops it until | |
| 52 | +`sendEvent()` delivers an event of the matching type, or until a timeout that | |
| 53 | +is 24 hours by default. Read | |
| 54 | +[sleeping and retrying](https://developers.cloudflare.com/workflows/build/sleeping-and-retrying/) | |
| 55 | +and | |
| 56 | +[events and parameters](https://developers.cloudflare.com/workflows/build/events-and-parameters/) | |
| 57 | +for the durations and the event rules. | |
| 58 | + | |
| 59 | +celld computes the deadline once and commits it with the step record. A later | |
| 60 | +replay reads the stored deadline instead of adding the duration to the current | |
| 61 | +time, therefore a crash or a slow resume cannot move the wake further away. | |
| 62 | + | |
| 63 | +A waiting instance holds no isolate. celld arms the alarm of the instance cell | |
| 64 | +at the earliest blocked deadline and returns, so the cell hibernates like any | |
| 65 | +other [cell](durable-objects.md) when the alarm is further away than the | |
| 66 | +near-alarm residency window. That window is one hour, and | |
| 67 | +`CELLD_ALARM_RESIDENT_MS` changes it. The armed alarm has a durable wake entry | |
| 68 | +in the fleet, and the node that owns the cell at the deadline runs the next | |
| 69 | +replay. | |
| 70 | + | |
| 71 | +An event that arrives before the instance reaches its wait step is buffered, | |
| 72 | +and a matching step then consumes the buffered events in arrival order. celld | |
| 73 | +deletes the event and writes the step record in one SQLite commit, so an | |
| 74 | +acknowledged event cannot disappear. celld compares the stored deadline before | |
| 75 | +the buffer, therefore a late replay cannot accept an event that arrived after | |
| 76 | +the step timed out. | |
| 77 | + | |
| 78 | +## Retries, failure, and a node that stops | |
| 79 | + | |
| 80 | +`step.do()` retries a failed callback. celld uses the upstream defaults when | |
| 81 | +the call supplies no `retries` object: a limit of 5 retries, a delay of 10 | |
| 82 | +seconds, exponential backoff, and a timeout of 10 minutes for one attempt. A | |
| 83 | +`NonRetryableError` stops the retries at once. When the retries run out, the | |
| 84 | +step promise rejects and `run()` can catch it. An error that escapes `run()` | |
| 85 | +moves the instance to the `errored` status. | |
| 86 | + | |
| 87 | +celld commits the time of the next attempt when an attempt fails, so a replay | |
| 88 | +waits out the rest of the backoff instead of starting it again. A pending retry | |
| 89 | +suspends the instance in the same way a sleep does, and `status()` reports | |
| 90 | +`waiting` for both. | |
| 91 | + | |
| 92 | +A node that stops does not lose an instance. The instance is a cell, so it has | |
| 93 | +the ownership, the fencing, and the replication that every cell has. celld | |
| 94 | +leaves the alarm that started an invocation armed for the whole invocation, and | |
| 95 | +it consumes that alarm only after the invocation returns cleanly. A node that | |
| 96 | +dies in the middle therefore leaves an armed alarm, and the next owner replays | |
| 97 | +`run()` over the step results that reached a replicated commit. A step whose | |
| 98 | +result did not commit runs again, which is why a step callback must tolerate a | |
| 99 | +second attempt. | |
| 100 | + | |
| 101 | +celld enforces no limit on the number of instances that run at once. The memory | |
| 102 | +of the fleet and the resident-cell cap bound that number instead. A waiting | |
| 103 | +instance costs no memory, so a fleet holds far more waiting instances than | |
| 104 | +running ones. | |
| 105 | + | |
| 106 | +## Differences from Cloudflare | |
| 107 | + | |
| 108 | +- celld retains a successful or failed instance for 30 days by default. Each | |
| 109 | + duration in the `retention` option can be at most 30 days. | |
| 110 | +- `locationHint` accepts the Cloudflare values, but fleet ownership selects the | |
| 111 | + cell location. | |
| 112 | +- Non-step work cannot remain pending for more than 60 seconds. | |
| 113 | +- A step result, an event payload, and the workflow parameters each have a | |
| 114 | + 1 MiB limit. | |
| 115 | +- Rollback, a sensitive step result, and a `ReadableStream` step result are | |
| 116 | + unavailable. | |
| 117 | +- A `workflows` entry cannot carry `schedules`, `limits`, or a `script_name` | |
| 118 | + that names another script. | |
| 119 | +- The Workflows REST API and the `wrangler workflows` commands are | |
| 120 | + unavailable. Drive an instance through the binding. | |
| 121 | + | |
| 122 | +The [Cloudflare compatibility](../cloudflare-compat.md#services) page lists | |
| 123 | +the runtime APIs and the unsupported services. |
modifieddocs/telemetry.md+3−1View file
| @@ -12,7 +12,9 @@ | ||
| 12 | 12 | |
| 13 | 13 | The schema is version `v0-unstable`. The column names can change |
| 14 | 14 | before a stable release, and each file carries the schema version in |
| 15 | -its object metadata. | |
| 15 | +its object metadata under the name `celld-schema`. Azure Blob Storage | |
| 16 | +does not accept a hyphen in a metadata name, so on an `az://` bucket | |
| 17 | +the name is `celld_schema`. | |
| 16 | 18 | |
| 17 | 19 | ## Configuration |
| 18 | 20 |
modifieddocs/testing.md+51−65View file
| @@ -1,9 +1,9 @@ | ||
| 1 | 1 | # Testing |
| 2 | 2 | |
| 3 | -celld makes three important promises: | |
| 3 | +celld makes three promises: | |
| 4 | 4 | |
| 5 | 5 | - An acknowledged write is durable. |
| 6 | -- A cell has one writer at a time. It never has two. | |
| 6 | +- A cell has one writer at a time. | |
| 7 | 7 | - Code written for Cloudflare Workers and Durable Objects operates the |
| 8 | 8 | same on celld. |
| 9 | 9 | |
| @@ -16,21 +16,18 @@ | ||
| 16 | 16 | |
| 17 | 17 | ## Conformance: two runtimes, one output |
| 18 | 18 | |
| 19 | -We test the compatibility promise differentially. We run each Workers and | |
| 20 | -Durable Objects program twice: once on workerd, the runtime binary that | |
| 21 | -Cloudflare operates in production, and once on celld, on identical bytes. | |
| 22 | -The two outputs must be equal. This shows two facts at once: the program | |
| 23 | -is real Cloudflare code, because workerd accepts it, and celld obeys the | |
| 24 | -contract, because the outputs are equal. A test cannot agree with our own | |
| 25 | -runtime by accident. | |
| 19 | +We run the same Workers and Durable Objects program on both workerd, | |
| 20 | +Cloudflare's production runtime, and celld. The two outputs must match, | |
| 21 | +so each test checks celld against the Cloudflare runtime. | |
| 22 | +The reference output comes from workerd, so the expected behavior does | |
| 23 | +not depend on the celld implementation. | |
| 26 | 24 | |
| 27 | -The corpus only grows. When celld gets a new API surface, we add fixtures | |
| 28 | -for that surface, and the fixtures must give equal output on the two | |
| 29 | -engines. We also port test suites from workerd itself: the Durable | |
| 30 | -Objects contract, the web-platform globals, and the upstream Web Platform | |
| 31 | -Tests. Before a release, we also replay scenarios through the full | |
| 32 | -`celld` binary in each deployment mode: storage, SQL, alarms, streams, | |
| 33 | -WebSockets, and lifecycle. | |
| 25 | +We expand the corpus with fixtures for each new API, and each fixture must | |
| 26 | +give the same output on both engines. We also port test suites from workerd: | |
| 27 | +the Durable Objects contract, the web-platform globals, and the upstream | |
| 28 | +Web Platform Tests. Before a release, we replay storage, SQL, alarm, | |
| 29 | +stream, WebSocket, and lifecycle scenarios through the full `celld` binary | |
| 30 | +in each deployment mode. | |
| 34 | 31 | |
| 35 | 32 | ## Specification: exhaustive at small size |
| 36 | 33 | |
| @@ -45,16 +42,14 @@ | ||
| 45 | 42 | clocks, so a violation it finds needs no clock skew and no storage |
| 46 | 43 | anomaly to occur. The invariants are the first two promises at the top |
| 47 | 44 | of this page: one writer for each epoch, and no acknowledged write |
| 48 | -lost. The fencing argument itself — that a stale owner's late writes | |
| 49 | -cannot cost an acknowledged write, because the epoch in the key keeps | |
| 50 | -its lineage apart — is checked, not asserted. | |
| 45 | +lost. The checker also verifies that the epoch in the key prevents a stale | |
| 46 | +owner's late writes from causing the loss of an acknowledged write. | |
| 51 | 47 | |
| 52 | 48 | Every configuration carries a pinned expected verdict, and most of the |
| 53 | 49 | verdicts are failures: each failing configuration models a bug the |
| 54 | 50 | protocol once had, or a deliberately broken checker, and the model |
| 55 | -must produce the counterexample. A configuration that stops failing | |
| 56 | -has lost its tooth. One tooth had already fallen out when the | |
| 57 | -specifications arrived; we repaired it. | |
| 51 | +must produce the counterexample. If a configuration stops producing its | |
| 52 | +expected failure, we investigate and repair the check. | |
| 58 | 53 | |
| 59 | 54 | Some specifications model a proposed protocol before it is built. When |
| 60 | 55 | the fence on write acknowledgments was redesigned, the design-stage |
| @@ -66,17 +61,16 @@ | ||
| 66 | 61 | |
| 67 | 62 | The checker has also removed code: celld once sealed a cell's durable |
| 68 | 63 | history at restore, and the verdicts showed the seal defended only the |
| 69 | -return of a write that was never acknowledged — an outcome celld does | |
| 70 | -not promise to prevent — while its permanent cut could turn a | |
| 71 | -recoverable ordering slip into a permanent loss. The seal is gone. | |
| 64 | +return of an unacknowledged write, which celld does not promise to prevent. | |
| 65 | +The seal could also turn a recoverable ordering error into permanent data | |
| 66 | +loss, so celld no longer uses it. | |
| 72 | 67 | |
| 73 | -The specifications are a hand-synced snapshot, deliberately not in | |
| 74 | -continuous integration: a silently stale gate is worse than none. In | |
| 75 | -practice their updates have landed in the same changes that moved the | |
| 76 | -protocol, and a delta ledger records what the model does not yet | |
| 77 | -describe, including places where the model is weaker than the code | |
| 78 | -rather than wrong. Simulation remains the per-commit ratchet; the | |
| 79 | -model is its exhaustive small-configuration complement. | |
| 68 | +We update the specifications manually alongside the protocol changes. | |
| 69 | +They do not run in continuous integration, because an outdated model can | |
| 70 | +give false confidence. A separate record tracks what the model does not | |
| 71 | +yet describe, including guarantees weaker than those in the code. | |
| 72 | +Simulation checks each commit, and model checking adds exhaustive coverage | |
| 73 | +of small configurations. | |
| 80 | 74 | |
| 81 | 75 | ## Simulation: the protocol under adversarial schedules |
| 82 | 76 | |
| @@ -94,18 +88,17 @@ | ||
| 94 | 88 | play the cells: a handler that never returns, a write stream that stops |
| 95 | 89 | halfway. V8 stays out of the simulation, because V8 is not deterministic. |
| 96 | 90 | |
| 97 | -A seeded scheduler drives each run, so a failure is not a fluke: the seed | |
| 98 | -replays it exactly, every time, and we keep the seed until the bug is | |
| 99 | -dead. We examine each property for safety (two writers in one epoch, a | |
| 100 | -lost acknowledged write, an expired lease that comes back) and for | |
| 101 | -liveness (each armed alarm fires, and ownership settles on one node after | |
| 102 | -a crash). A property must survive tens of thousands of seeds, and the | |
| 103 | -core protocols have run through millions of different schedules. | |
| 91 | +A seeded scheduler drives each run, so we can reproduce a failure exactly | |
| 92 | +and keep its seed until we fix the bug. We check safety properties for | |
| 93 | +two writers in one epoch, a lost acknowledged write, and an expired lease | |
| 94 | +that returns. We also check liveness: each armed alarm fires, and ownership | |
| 95 | +settles on one node after a crash. A property must survive tens of thousands | |
| 96 | +of seeds, and the core protocols have run through millions of different | |
| 97 | +schedules. | |
| 104 | 98 | |
| 105 | -Simulation has a known failure mode: the checker that cannot fail. So | |
| 106 | -we also test the checkers: we run deliberately broken variants of the | |
| 107 | -protocol against the properties, and the properties must find the damage. | |
| 108 | -A suite that stays green against a broken protocol is a broken suite. | |
| 99 | +We also run deliberately broken variants of the protocol to verify that | |
| 100 | +the checkers detect the faults. A checker that accepts a broken protocol | |
| 101 | +cannot protect the corresponding property. | |
| 109 | 102 | |
| 110 | 103 | ## Live fleets: what simulation cannot see |
| 111 | 104 | |
| @@ -116,18 +109,16 @@ | ||
| 116 | 109 | connections, working sets that shift across tens of thousands of cells |
| 117 | 110 | (each cell has a unique checksum), deployment cutovers under load, and |
| 118 | 111 | runs that fill the nodes to the memory limit. The lab qualifies each |
| 119 | -release, and between releases it pushes the density and the fault | |
| 120 | -coverage further. Each run makes an archived evidence bundle: the | |
| 121 | -configuration, the verification sweeps, the node journals, the kernel | |
| 122 | -logs, and the phase timings. We keep a red run with the same care as a | |
| 123 | -green run, because a failure that the harness caught is a result, not a | |
| 124 | -retry. | |
| 112 | +release and tests greater density and more faults between releases. We | |
| 113 | +archive each run's configuration, verification sweeps, node journals, | |
| 114 | +kernel logs, and phase timings. We preserve failed runs as well as | |
| 115 | +successful ones, because both provide evidence of the system's behavior. | |
| 125 | 116 | |
| 126 | 117 | We inject the faults between verification passes. A pass fetches each |
| 127 | 118 | cell through different nodes and compares the durable state exactly: the |
| 128 | -status, the body, and the full message ledger. Each run therefore has a | |
| 129 | -clean picture before the fault and after it. A cell can be unavailable | |
| 130 | -for a short time while its ownership moves, but its committed state must | |
| 119 | +status, the body, and the full message ledger. Each run therefore records | |
| 120 | +the state before and after the fault. A cell can be unavailable for a short | |
| 121 | +time while its ownership moves, but its committed state must | |
| 131 | 122 | stay complete, and a live node must serve that state again. |
| 132 | 123 | |
| 133 | 124 | The scenarios attack every seam that we know: |
| @@ -156,8 +147,8 @@ | ||
| 156 | 147 | |
| 157 | 148 | ## A few numbers we trust |
| 158 | 149 | |
| 159 | -Each number includes the condition of its measurement. A number without | |
| 160 | -its conditions has no value. | |
| 150 | +Each number includes its measurement conditions, so you can assess whether | |
| 151 | +it applies to your workload. | |
| 161 | 152 | |
| 162 | 153 | - **The epoch fence holds under contention.** Five hundred claimants |
| 163 | 154 | tried at the same time to own the same cells: 5,500 attempts, one |
| @@ -187,15 +178,10 @@ | ||
| 187 | 178 | |
| 188 | 179 | ## The failure edges we intend to find |
| 189 | 180 | |
| 190 | -We must also know where a policy stops, so we record the edges instead of | |
| 191 | -tuning them away. The clearest edge is the reserve headroom: a fleet that | |
| 192 | -is full to its resident limit has no space for the cells of a lost node, | |
| 193 | -so a failure of more than one node at the limit degrades the service, | |
| 194 | -and a fleet with headroom does not. We measure both sides of that line, | |
| 195 | -the good restoration with reserve and the red case without, because this | |
| 196 | -measurement is part of the work. | |
| 181 | +A fleet at its resident limit has no space for the cells of a lost node, | |
| 182 | +so the loss of multiple nodes degrades the service. We test recovery with | |
| 183 | +and without reserve capacity to measure this limit. | |
| 197 | 184 | |
| 198 | -If you find an edge that we did not find, tell us: a schedule that breaks | |
| 199 | -a promise, a fault that we did not inject, a number that you cannot | |
| 200 | -reproduce. That is exactly the bug report that we want: | |
| 201 | -[github.com/denoland/celld/issues](https://github.com/denoland/celld/issues). | |
| 185 | +Report a schedule that breaks a guarantee, a fault that we do not test, | |
| 186 | +or a measurement that you cannot reproduce in the | |
| 187 | +[issue tracker](https://github.com/denoland/celld/issues). |
modifieddocs/wasm.md+7−0View file
| @@ -27,6 +27,13 @@ | ||
| 27 | 27 | isolate after the first one reuses the compiled module, so a cell |
| 28 | 28 | activation does not pay the compilation again. |
| 29 | 29 | |
| 30 | +## Example | |
| 31 | + | |
| 32 | +The [WebAssembly example](../examples/wasm) compiles a Rust Durable Object and | |
| 33 | +imports its WebAssembly module. | |
| 34 | + | |
| 35 | +<!-- celld-example: wasm --> | |
| 36 | + | |
| 30 | 37 | ## Prebuilt Workers |
| 31 | 38 | |
| 32 | 39 | With `no_bundle: true`, celld preserves the entry JavaScript byte for byte. |
modifiedexamples/README.md+3−0View file
| @@ -5,11 +5,13 @@ | ||
| 5 | 5 | |
| 6 | 6 | - `hello/` — a stateless Worker `fetch` handler |
| 7 | 7 | - `webapi/` — common Web Platform APIs |
| 8 | +- `static-assets/` — an asset-only website with headers and redirects | |
| 8 | 9 | - `counter/` — a SQLite-backed Durable Object |
| 9 | 10 | - `vectordb/` — nearest-color search with a per-object `vec0` index |
| 10 | 11 | - `d1/` — a guestbook on a D1 database |
| 11 | 12 | - `r2/` — object reads, writes, and deletes on an R2 bucket |
| 12 | 13 | - `kv/` — key reads, writes, and deletes in a KV namespace |
| 14 | +- `queues/` — a producer and a consumer, with retries and a dead-letter queue | |
| 13 | 15 | - `async/` — a timer and asynchronous Durable Object storage |
| 14 | 16 | - `body/` — request and response bodies |
| 15 | 17 | - `router/` — Worker-to-Durable-Object routing |
| @@ -19,6 +21,7 @@ | ||
| 19 | 21 | - `cron/` — a cron trigger that logs each tick |
| 20 | 22 | - `workflow/` — a Workflow that builds a report in one durable step |
| 21 | 23 | - `rpc/` — Durable Object method calls through JS RPC |
| 24 | +- `dynamic-worker-tails/` — a runtime-loaded Worker with a Tail Worker | |
| 22 | 25 | - `facets/` — a Durable Object facet over a class the Worker Loader starts |
| 23 | 26 | - `container/` — a Durable Object that supervises a container with |
| 24 | 27 | `@cloudflare/containers`; needs `npm install` and a Docker or Podman CLI |
addedexamples/dynamic-worker-tails/README.md+23−0View file
| @@ -1,0 +1,23 @@ | ||
| 1 | +# Dynamic Worker tails | |
| 2 | + | |
| 3 | +This example loads a Worker from a source string. The loaded Worker returns a | |
| 4 | +response and writes one console record. | |
| 5 | + | |
| 6 | +`DynamicWorkerTail` receives the invocation event after the response is | |
| 7 | +available. It copies the captured record into the loader Worker's logs and adds | |
| 8 | +the `workerId` prop. | |
| 9 | + | |
| 10 | +Run the example and enable log output: | |
| 11 | + | |
| 12 | +```sh | |
| 13 | +celld dev . --logs | |
| 14 | +``` | |
| 15 | + | |
| 16 | +Send a request from another terminal: | |
| 17 | + | |
| 18 | +```sh | |
| 19 | +curl http://127.0.0.1:8787 | |
| 20 | +``` | |
| 21 | + | |
| 22 | +The request returns `Hello from a Dynamic Worker!`. The celld output contains | |
| 23 | +`dynamic-worker-tail: hello from loaded code`. |
addedexamples/dynamic-worker-tails/index.js+40−0View file
| @@ -1,0 +1,40 @@ | ||
| 1 | +import { WorkerEntrypoint } from "cloudflare:workers"; | |
| 2 | + | |
| 3 | +const WORKER_ID = "hello-v1"; | |
| 4 | +const WORKER_MAIN = "worker.js"; | |
| 5 | +const WORKER_SOURCE = ` | |
| 6 | + export default { | |
| 7 | + fetch() { | |
| 8 | + console.log("hello from loaded code"); | |
| 9 | + return new Response("Hello from a Dynamic Worker!\\n"); | |
| 10 | + } | |
| 11 | + }; | |
| 12 | +`; | |
| 13 | + | |
| 14 | +export class DynamicWorkerTail extends WorkerEntrypoint { | |
| 15 | + tail(events) { | |
| 16 | + for (const event of events) { | |
| 17 | + for (const log of event.logs) { | |
| 18 | + console.log(`dynamic-worker-tail: ${log.message.join(" ")}`, { | |
| 19 | + workerId: this.ctx.props.workerId, | |
| 20 | + level: log.level, | |
| 21 | + }); | |
| 22 | + } | |
| 23 | + } | |
| 24 | + } | |
| 25 | +} | |
| 26 | + | |
| 27 | +export default { | |
| 28 | + fetch(request, env, ctx) { | |
| 29 | + const worker = env.LOADER.get(WORKER_ID, () => ({ | |
| 30 | + mainModule: WORKER_MAIN, | |
| 31 | + modules: { [WORKER_MAIN]: WORKER_SOURCE }, | |
| 32 | + tails: [ | |
| 33 | + ctx.exports.DynamicWorkerTail({ | |
| 34 | + props: { workerId: WORKER_ID }, | |
| 35 | + }), | |
| 36 | + ], | |
| 37 | + })); | |
| 38 | + return worker.getEntrypoint().fetch(request); | |
| 39 | + }, | |
| 40 | +}; |
addedexamples/dynamic-worker-tails/wrangler.jsonc+6−0View file
| @@ -1,0 +1,6 @@ | ||
| 1 | +{ | |
| 2 | + "name": "dynamic-worker-tails", | |
| 3 | + "main": "index.js", | |
| 4 | + "compatibility_date": "2026-01-01", | |
| 5 | + "worker_loaders": [{ "binding": "LOADER" }] | |
| 6 | +} |
addedexamples/queues/index.js+29−0View file
| @@ -1,0 +1,29 @@ | ||
| 1 | +export default { | |
| 2 | + async fetch(request, env) { | |
| 3 | + const job = { | |
| 4 | + path: new URL(request.url).pathname, | |
| 5 | + createdAt: new Date().toISOString(), | |
| 6 | + }; | |
| 7 | + await env.JOBS.send(job); | |
| 8 | + return Response.json({ queued: job }); | |
| 9 | + }, | |
| 10 | + | |
| 11 | + async queue(batch) { | |
| 12 | + for (const message of batch.messages) { | |
| 13 | + if (batch.queue === "example-jobs-dead-letter") { | |
| 14 | + console.log("dead job", message.body); | |
| 15 | + message.ack(); | |
| 16 | + continue; | |
| 17 | + } | |
| 18 | + | |
| 19 | + if (message.body.path.endsWith("/fail")) { | |
| 20 | + console.log("retrying job", message.body, message.attempts); | |
| 21 | + message.retry({ delaySeconds: 1 }); | |
| 22 | + continue; | |
| 23 | + } | |
| 24 | + | |
| 25 | + console.log("processing job", message.body); | |
| 26 | + message.ack(); | |
| 27 | + } | |
| 28 | + }, | |
| 29 | +}; |
addedexamples/queues/wrangler.jsonc+18−0View file
| @@ -1,0 +1,18 @@ | ||
| 1 | +{ | |
| 2 | + "name": "queues", | |
| 3 | + "main": "index.js", | |
| 4 | + "compatibility_date": "2026-01-01", | |
| 5 | + "queues": { | |
| 6 | + "producers": [{ "binding": "JOBS", "queue": "example-jobs" }], | |
| 7 | + "consumers": [ | |
| 8 | + { | |
| 9 | + "queue": "example-jobs", | |
| 10 | + "max_batch_size": 10, | |
| 11 | + "max_batch_timeout": 5, | |
| 12 | + "max_retries": 2, | |
| 13 | + "dead_letter_queue": "example-jobs-dead-letter" | |
| 14 | + }, | |
| 15 | + { "queue": "example-jobs-dead-letter" } | |
| 16 | + ] | |
| 17 | + } | |
| 18 | +} |
modifiedexamples/sandbox/README.md+1−1View file
| @@ -28,5 +28,5 @@ | ||
| 28 | 28 | `celld deploy` saves the image to the bucket once, and each node loads it |
| 29 | 29 | the first time one of its sandboxes starts. Preview URLs, tunnels, and |
| 30 | 30 | bucket mounts are features of the package and of the container; see the |
| 31 | -[Cloudflare compatibility](../../docs/cloudflare-compat.md#containers) | |
| 31 | +[Containers documentation](../../docs/services/containers.md) | |
| 32 | 32 | notes for what celld does not provide. |
addedexamples/static-assets/public/_headers+2−0View file
| @@ -1,0 +1,2 @@ | ||
| 1 | +/* | |
| 2 | + X-Served-By: celld |
addedexamples/static-assets/public/_redirects+1−0View file
| @@ -1,0 +1,1 @@ | ||
| 1 | +/home / 301 |
addedexamples/static-assets/public/index.html+11−0View file
| @@ -1,0 +1,11 @@ | ||
| 1 | +<!doctype html> | |
| 2 | +<html lang="en"> | |
| 3 | + <head> | |
| 4 | + <meta charset="utf-8"> | |
| 5 | + <meta name="viewport" content="width=device-width, initial-scale=1"> | |
| 6 | + <title>celld static assets</title> | |
| 7 | + </head> | |
| 8 | + <body> | |
| 9 | + <h1>This file is served by celld.</h1> | |
| 10 | + </body> | |
| 11 | +</html> |
addedexamples/static-assets/wrangler.jsonc+5−0View file
| @@ -1,0 +1,5 @@ | ||
| 1 | +{ | |
| 2 | + "name": "static-assets", | |
| 3 | + "compatibility_date": "2026-01-01", | |
| 4 | + "assets": { "directory": "./public" } | |
| 5 | +} |