Diffinery

homeflare/celldpublic

celld/docs/cloudflare-compat.md
375 lines · 22.1 KBRaw History
1# Cloudflare compatibility
2
3celld runs the Workers runtime, with Durable Objects as the stateful
4core: module Workers, fetch, JS RPC, service bindings, and static assets.
5This page shows that Worker surface, API by API. celld does not run the
6rest of the Cloudflare platform, and the scope rule is simple: if
7Cloudflare builds a function on Durable Objects, celld can get that
8function, and a function on a different primitive is out of scope.
9Cloudflare builds D1 on Durable Objects, so a D1 binding is a thin layer
10over what celld already has. KV is a global cache with eventual
11consistency, and R2 is blob storage: different systems, not on the
12roadmap.
13
14A configuration or binding that is not available must fail loudly, at
15deploy or at first use. A silent compatibility gap is a bug; the known
16gaps have marks below.
17
18## Services
19
20| service | notes |
21| --- | --- |
22| **Workers** | Module Workers: `fetch`, JS RPC, service bindings, Durable Object bindings, `vars`. Cron triggers run the `scheduled` handler on celld's own alarms, one time for each occurrence in the whole fleet; see [Cron triggers](#cron-triggers). |
23| **Durable Objects** | The stateful core. SQLite storage, alarms, inbound hibernatable WebSockets, outbound `ws:`/`wss:` WebSocket clients (constructor and `fetch()` upgrade), one writer for each cell, names as addresses, RPC methods on stubs. |
24| **Static assets** | Immutable files, served from the fleet bucket: `assets.directory`, `binding`, `html_handling`, `not_found_handling`, `run_worker_first`, plus `_headers` and `_redirects`. An asset-only project deploys without a Worker. |
25| **Worker Loader (Code Mode)** | Experimental. Bind a loader with `CELLD_WORKER_LOADER`. A Worker can then start sandboxed isolates at runtime. See [Dynamic Worker loading](#dynamic-worker-loading-code-mode). |
26| **D1** | Partial. `d1_databases` bindings give `prepare`, `bind`, `all`, `first`, `run`, `raw` and `exec`. The `celld d1` command runs SQL and migrations. See [D1](#d1). |
27
28Planned: **Workflows** (durable execution over cells and alarms),
29**Queues** (a Durable Object shape; if demand appears).
30
31A note on durable execution, because the two terms are close. A
32durable-execution engine (Temporal, Restate, Azure Durable Functions)
33models a process: a sequence of steps that ends. A cell models an
34entity: a named unit with state that persists indefinitely. You can
35build either primitive on the other — Cloudflare builds Workflows on
36Durable Objects — so choose the one that matches the shape of the
37problem. A concert, a user, and a document are entities; an order
38pipeline is a process.
39
40Not planned: **KV** (a different consistency model), **R2** (celld runs
41*on* blob storage; celld does not provide blob storage; declared
42`r2_buckets` bindings load, but each method throws), **Cache API**,
43**Workers AI, Vectorize, Hyperdrive, Browser Rendering, Email** (managed
44platform services; an experimental HTTP adapter for an AI binding exists
45behind `CELLD_AI_URL`), **custom domains, TLS termination** (platform
46surface; put TLS in your ingress proxy), **Python Workers** (workerd
47supplies the Pyodide runtime and the Python module shim; that layer is
48platform surface, not a function on Durable Objects; celld can add
49support if demand appears).
50
51## Runtime APIs
52
53Cloudflare's [Runtime APIs
54index](https://developers.cloudflare.com/workers/runtime-apis/), category
55by category:
56
57| API | status |
58| --- | --- |
59| Fetch, Request, Response, Headers | **Yes.** Gaps: `Response.redirect()`, `Response.error()`, and the `cache` request option are missing. |
60| Bindings (`env`) | **Yes** for Durable Objects, service bindings, `vars`, assets, and D1. Other binding types are out of scope (see Services). |
61| Context (`ctx`) | **Yes**: `waitUntil`, `props`, `exports`. `passThroughOnException()` is accepted but has no effect. There is no CDN behind it. `ctx.facets` is absent (see Facets). |
62| Handlers | `fetch`, `alarm`, `scheduled` (cron), `webSocketMessage`/`Close`/`Error`, RPC methods. **No** `queue`, `tail`, or `email` handlers. See [cron triggers](#cron-triggers). |
63| RPC | **Yes**, for most of the surface. See [RPC](#rpc). |
64| Streams | **Yes.** This includes byte streams, BYOB readers, `tee`/`pipeTo`/`pipeThrough`, `IdentityTransformStream`, `FixedLengthStream`, and `CompressionStream`/`DecompressionStream`. Gap: `ReadableStream.from()`. |
65| Encoding | **Yes**: `TextEncoder`/`TextDecoder` (legacy encodings included), encoder and decoder streams, `atob`/`btoa`. |
66| WebSockets | **Yes**, inbound (hibernatable, with attachments) and outbound. An attachment holds anything that structured clone accepts. A subrequest to a cell can upgrade, and the caller gets the client end as `response.webSocket`. The caller must call `accept()` on that socket, because an unaccepted socket delivers no message. Auto-response works: `setWebSocketAutoResponse` answers a matched message without a wake of the cell. Gap: `getTags()`. Divergence: `acceptWebSocket()` throws when the isolate is near its V8 heap limit (see [Isolate heap limit](#isolate-heap-limit)). |
67| Web Crypto | **Partial**: `digest` (including MD5), HMAC sign and verify, AES-GCM, RSA-OAEP decrypt, Ed25519 and ECDSA-P256 sign, and `verify` for RSASSA-PKCS1-v1_5 and ECDSA-P256 (RS256 and ES256 JWTs). `importKey` and `exportKey` handle `spki`, `pkcs8`, `jwk` and `raw` for RSA, EC (P-256, P-384, P-521), Ed25519 and X25519, validating at import; keys cross to `node:crypto` through `KeyObject.from()`. `generateKey` covers AES, HMAC, RSA (OAEP, PKCS#1 v1.5, PSS), EC P-256 and Ed25519. Cloudflare's extensions `timingSafeEqual` and `DigestStream` (with CRC32, CRC32C and CRC64-NVME) are available. AES-CBC, AES-CTR and AES-GCM (12- or 16-byte IVs). ECDH `deriveBits` and `deriveKey` on P-256, P-384 and P-521. Missing: `wrapKey`/`unwrapKey`, RSA-PSS *signing*, HKDF and PBKDF2 through `deriveBits` (they are available through `node:crypto`). An algorithm that is not available throws. |
68| Web standards | **Yes**: `URL`, `URLSearchParams`, `URLPattern`, `AbortController`/`AbortSignal` (with `timeout()`, `any()`; a signal does **not** abort across an RPC call, and `signal.onabort` is accepted but never invoked — use `addEventListener('abort')`), `Blob`/`File`/`FormData`, `Event`/`EventTarget`, `DOMException`, `queueMicrotask`, `structuredClone` (not conformant on exotic types), `navigator.userAgent`. |
69| WebAssembly | **Yes** (V8's own, without restrictions). A bundle can import a `.wasm` file as a compiled module, as on Cloudflare; see [WebAssembly](wasm.md). |
70| Performance and timers | `setTimeout`/`clearTimeout`, `setInterval`/`clearInterval`, `setImmediate`, `scheduler.wait()`. A Worker must clear each interval before the handler ends because an active interval keeps the request alive. `performance.now()` has millisecond resolution. The other parts of `performance` are stubs. |
71| Console | `log`/`info`/`warn`/`error` are real. `debug`/`trace`/`group`/`table` do nothing. `assert`/`time`/`count` are absent. |
72| Node.js compatibility | **Partial.** See [node: imports](#node-imports). |
73| Facets (`ctx.facets`) | **No.** A Durable Object cannot create a facet, and `ctx.facets` is not defined. celld also has no first-class `DurableObjectClass` value, so `ctx.exports` gives no stub for a Durable Object class that the configuration does not declare. |
74| Cache (`caches`) | **No.** |
75| HTMLRewriter | **No.** |
76| TCP sockets (`cloudflare:sockets`) | **No.** Known silent gap: `connect()` currently gives an inert stub. It does not throw. |
77| EventSource, MessageChannel, BroadcastChannel | **No.** The classes exist so that bundles load, but they do nothing. |
78
79## RPC
80
81celld implements the Workers [JS RPC
82system](https://developers.cloudflare.com/workers/runtime-apis/rpc/):
83`WorkerEntrypoint` and `RpcTarget` from `cloudflare:workers`, named
84entrypoints on service bindings, and method calls on Durable Object stubs
85(this needs `extends DurableObject`, or the `js_rpc` compat flag).
86Arguments and returns use structured clone. Functions, streams, and
87`RpcTarget`s become stubs. Promise pipelining, `ctx.exports` loopback
88stubs, and stubs in DO storage are available. `ctx.exports` covers the
89entrypoints that the configuration declares, so it gives no stub for an
90undeclared Durable Object class.
91
92The current limits: a cross-isolate service binding with a named
93entrypoint can do single method calls, but not `fetch()`, awaitable
94properties, or pipelined paths; a same-isolate binding has the full
95surface.
96
97A stub cannot cross an isolate boundary yet, and a Durable Object is its
98own isolate. A Durable Object method therefore takes and returns
99structured-cloneable values. If you pass a function to one, or return an
100`RpcTarget` from one, the call throws `RPC stubs cannot cross isolate
101boundaries yet`. Callbacks, `RpcTarget` instances and promise pipelining
102all work through `ctx.exports`, which shares the isolate. The
103[`rpc` example](https://github.com/denoland/celld/tree/main/examples/rpc)
104shows each of these.
105
106## D1
107
108A D1 database is a cell. The cell holds one SQLite database, and celld
109replicates that database to the fleet bucket. Therefore a D1 database
110gets the fencing, the replication, and the durable write acknowledgement
111of a Durable Object.
112
113Declare a database with the `d1_databases` key:
114
115```jsonc
116{
117 "d1_databases": [
118 { "binding": "DB", "database_name": "ledger" }
119 ]
120}
121```
122
123The `database_id` value is the stable database identity. The identity does
124not change when a Worker name changes. Several Workers can use the same
125identity, so they can reach the same database. celld uses `database_name`
126when a declaration has no `database_id`.
127
128These methods are available: `prepare()`, `bind()`, `all()`, `first()`,
129`run()`, `raw()`, `exec()`, `batch()`, and `withSession()`. A batch runs
130all of its statements in one transaction. A failed statement rolls back
131the complete batch.
132
133A session always uses the primary database because celld has no read
134replica. The session accepts a Cloudflare constraint or an opaque bookmark.
135It provides `prepare()`, `batch()`, and `getBookmark()`.
136
137A statement result carries the standard `meta` fields. celld reports
138`served_by_region` as `local`, and it reports `served_by_primary` as `true`.
139The `rows_read` value uses the returned-row count and the SQLite full-scan
140counter. It can differ when a query plan reads rows through an operation
141that SQLite does not expose through that counter.
142
143A failure has a `cause` property, and the message prefix identifies the
144error family. A SQL failure gives `D1_ERROR:`. An unsupported bind value
145gives `D1_TYPE_ERROR:`. An `exec()` failure gives `D1_EXEC_ERROR:`. A missing
146column in `first(column)` gives `D1_COLUMN_NOTFOUND:`.
147
148`bind()` accepts a number, a string, a boolean, a null, an `ArrayBuffer`, a
149typed array, or an array of bytes. It converts a boolean to `1` or `0`, as
150Cloudflare does. An `ArrayBuffer` stores its bytes as a BLOB. A typed array
151stores its element values, and each element truncates to one byte. Cloudflare
152uses the same conversion. A `NaN` or an `Infinity` value has no JSON form,
153so `bind()` stores SQL `NULL`.
154
155**One database has one writer.** A celld fleet gets more capacity from
156more databases, and not from a larger database. Cloudflare gives the same
157advice for the same reason.
158
159A query through a binding must hold its full result in memory, because
160the result crosses an isolate boundary. celld refuses a result of more
161than 100,000 rows, and it refuses a result of more than 32 MiB. The
162statement completes before the refusal, so the writes of an
163`INSERT ... RETURNING` statement land even when the result is refused. A
164Durable Object can read a larger result, because the cursor in a cell
165streams the rows.
166
167The `dump()` method and Time Travel are not available. The `wrangler d1`
168commands and the D1 REST API do not operate against celld. Use `celld d1`
169instead.
170
171### The celld d1 command
172
173`celld d1` runs SQL and migrations against a database that is deployed.
174A database is a cell, so the command needs a running fleet. It finds a
175node through the node leases in the bucket. That node then sends the work
176to the node that owns the database. celld signs each request with the
177fleet secret in the bucket, therefore the command needs the same bucket
178credentials that `celld deploy` needs.
179
180```sh
181celld d1 migrations apply ledger --bucket s3://my-cells-bucket
182celld d1 migrations list ledger --bucket s3://my-cells-bucket
183celld d1 execute ledger --command "SELECT count(*) FROM accounts;" \
184 --bucket s3://my-cells-bucket
185```
186
187The command reads the project to resolve the selected `database_name` to its
188stable identity. Give the project directory as an argument, or run the
189command in that directory.
190
191A migration is a `NNNN_description.sql` file in `migrations/`, and celld
192applies the files in the order of their numeric prefixes, as wrangler
193does. A file without a numeric prefix stops the command, because celld
194cannot place the file in that order. Give the `d1_databases` entry a
195`migrations_dir` value to move the directory, and a `migrations_table`
196value to rename the bookkeeping table. celld records an applied migration
197in that table, `d1_migrations` by default, and the table and the columns
198match the table `wrangler d1 migrations` writes.
199
200A project that moves from Cloudflare does not apply a migration twice when
201the migration history arrives with the data. Export the database with
202`wrangler d1 export`. Import the file with `celld d1 execute DATABASE --file
203export.sql`. The import runs as one transaction with a 120-second budget. A
204failed import rolls back the complete transaction. A large export can require
205several smaller files.
206
207The cell applies a migration and records it in one transaction, so a
208migration that fails part-way rolls back whole. The database therefore
209keeps neither a partial schema nor a record of work that did not land,
210and you can correct the file and run the command again. A failure stops
211the run, so the migrations after the failure do not run.
212
213An `exec()` call runs in one transaction, so a call that fails part-way
214rolls back whole. celld refuses SQL that ends in an incomplete statement
215— an open quote, or a statement cut in the middle of a token — because
216the engine does not run such a statement. A complete final statement does
217not need a semicolon, and a comment after the last statement is
218permitted.
219
220## Dynamic Worker loading (Code Mode)
221
222Set `CELLD_WORKER_LOADER=LOADER`. Workers then get `env.LOADER`. This is
223an experimental port of Cloudflare's [Worker
224Loader](https://developers.cloudflare.com/workers/runtime-apis/bindings/worker-loader/).
225`loader.get(name, getCode)` (memoized) and `loader.load(code)` start a
226new isolate for each loaded worker. These inputs are honored:
227`mainModule`, sibling `modules`, `compatibilityDate`/`Flags`, plain-JSON
228`env`, and `globalOutbound: null` (no egress). The limits of workerd
229apply: 64 MiB of code and 1 MiB of env, plus the
230`CELLD_MAX_LOADED_WORKERS` limit. A loaded worker serves `fetch()` and
231single RPC method calls. Not yet available: `globalOutbound` as a
232Fetcher, capability stubs in `env`, awaitable or pipelined properties.
233
234## node: imports
235
236`node:` specifiers are always available; the `nodejs_compat` flag is not
237necessary, and celld does not read it. `celld deploy` externalizes `node:*`
238and bare Node built-ins at bundle time. The runtime supplies its own subset
239(it does not use the Wrangler-style unenv polyfills):
240
241- **Implemented**: `node:assert`, `node:async_hooks` (a real
242 `AsyncLocalStorage`), `node:buffer`, `node:events`, `node:path`,
243 `node:stream` (+ `stream/web`, `stream/promises`, `stream/consumers`),
244 `node:timers/promises`, `node:util`.
245- **Partial**: `node:crypto` (hashes, HMAC, HKDF, PBKDF2, `webcrypto`, secret
246 key objects, asymmetric keys, and one-shot signatures. `createPublicKey` and
247 `createPrivateKey` read PEM, DER and JWK for RSA, EC (P-256, P-384, P-521),
248 Ed25519, X25519 and DSA, including password-protected PKCS#8, and give a key
249 with `asymmetricKeyType`, `asymmetricKeyDetails`, `toCryptoKey()` and
250 `export()` to DER, PEM or JWK. `generateKeyPairSync` covers RSA, EC P-256,
251 Ed25519 and X25519. `sign()` and `verify()` cover Ed25519, RSA PKCS#1 v1.5
252 and ECDSA P-256, with DER signatures as Node's `dsaEncoding` default
253 requires. What still throws: Diffie-Hellman throughout, the streaming
254 `createSign`/`createVerify`, ciphers, RSA-PSS, DSA signing, and key
255 generation for DSA and DH), `node:zlib` (only the sync `gzip`/`deflate`
256 family), `node:fs` (reads fail with `ENOENT`, `existsSync` is `false`).
257- **Not implemented**: the rest — `node:http(s)`, `node:net`,
258 `node:tls`, `node:dns`, `node:os`, `node:process` (the `process`
259 global exists, the module does not), `node:worker_threads`, `node:vm`,
260 `node:child_process`, and the others. Known silent gap: these
261 currently give inert stubs. They do not fail the import.
262
263## Isolate heap limit
264
265Each isolate has a V8 heap limit, and celld defaults it to 128 MB to
266match a Durable Object on Cloudflare. `CELLD_V8_HEAP_LIMIT_MB` changes
267it. celld keeps an isolate that reaches this limit, and Cloudflare
268discards one. Two behaviors follow from that difference, and both
269diverge from workerd on purpose.
270
271`state.acceptWebSocket()` throws when the isolate uses more than 90% of
272the limit. A hibernatable WebSocket is state that the cell holds until
273the peer goes away, so a cell that accepts more sockets than it can
274carry serves none of them. The error names the heap and
275`CELLD_V8_HEAP_LIMIT_MB`. Cloudflare does not refuse the accept.
276
277`SqlStorage.Cursor.toArray()` throws a different message. workerd throws
278`result set is too large to fit in memory`. The guard tests the heap of
279the isolate and not the size of the result, so it fires for a query that
280returns one row, and the workerd message then names the wrong cause.
281celld names the heap instead.
282
283Neither state is permanent. celld measures the heap before each event
284and lifts the refusal when the heap drains. A restart of the process is
285not necessary. The [README](../README.md#operate-a-fleet) gives the
286thresholds.
287
288## Cron triggers
289
290celld runs the `scheduled` handler on a cron schedule. Put the
291expressions in `triggers.crons` in the Wrangler configuration, and export
292`scheduled(controller, env, ctx)` from the default entrypoint. The
293`controller` gives `scheduledTime`, `cron`, and `noRetry()`, as on
294Cloudflare.
295
296An expression has the five standard fields: minute, hour, day of month,
297month, and day of week. A field accepts `*`, a value, an `a-b` range, an
298`a,b` list, and a `/n` step. The month and day-of-week fields also accept
299the three-letter names. The day-of-month field accepts `L`, `L-<n>`, `LW`,
300`L-<n>W`, and `<day>W`. The day-of-week field accepts `<day>L` and
301`<day>#<n>`. If the day-of-month field and the day-of-week field are both
302not `*`, a day matches when one of them matches.
303
304The day-of-week numbers are Cloudflare's: 1 is Sunday and 7 is Saturday.
305Other cron systems number the same days 0 to 6 from Sunday, so `1-5` is
306Sunday to Thursday here and not Monday to Friday. celld refuses 0. Use
307the names to avoid the question.
308
309A step must be smaller than the width of its field, so `*/60` in the
310minute field is an error and not a spelling of "every hour". Cloudflare
311applies the same bound.
312
313celld refuses two expressions that Cloudflare accepts, and both refusals
314stop the deploy with an error:
315
316- A descending range, such as `SAT-SUN` or `NOV-FEB`. Cloudflare wraps a
317 descending range around the end of the field and includes one value too
318 many: `SAT-SUN` matches Friday there. celld does not copy that result
319 and does not silently correct it.
320- A `*` inside a list, such as `1,*`. Cloudflare reads this `*` as the
321 lowest value of the field, so `1,*` is minute 0 and minute 1.
322
323celld also refuses `?`, as Cloudflare does.
324
325A cron runs on one node in the fleet, and celld gives these guarantees:
326
327- The resolution is one minute, and the zone is UTC.
328- The handler runs one time for each occurrence that the fleet is up for,
329 in the whole fleet.
330- Only one handler runs at a time for a script. A slow handler therefore
331 delays the next occurrence.
332- The handler can run late, but it never runs early. If the fleet is
333 down, celld runs the missed occurrence one time and does not run the
334 other missed occurrences. `controller.scheduledTime` is always the
335 occurrence, and not the moment the handler started.
336- celld retries a handler that throws, with an increasing delay, and it
337 retries only the expression that threw. A retry that is still owed when
338 the next occurrence comes is cancelled, so a retry can never delay or
339 cancel a scheduled run. `controller.noRetry()` also cancels the retry.
340
341celld builds this on its alarms, so a cron schedule is durable. celld also
342uses the schedule from the deployment it runs under. A new deployment with
343different expressions therefore takes effect without a migration. A node
344runs the schedule of its own deployment only. If a script that a service
345binding points to declares `triggers.crons`, celld writes a warning and
346does not run them.
347
348## Compatibility flags
349
350`compatibility_date` and `compatibility_flags` are honored for the
351switches that celld models: `delete_all_deletes_alarm`, `js_rpc`,
352`fetcher_no_get_put_delete`, `sqlite_vec`, `websocket_standard_binary_type`,
353and the assets navigation behavior. The `sqlite_vec` flag enables the pre-v1
354sqlite-vec extension, and a compatibility date never enables it.
355`Cloudflare.compatibilityFlags` reports only
356the flags that celld honors. A flag that celld does not model is absent
357rather than reported as enabled, and celld accepts it without effect.
358
359## Wrangler configuration
360
361`celld deploy` builds a standard Wrangler project (esbuild on `PATH`)
362and accepts `wrangler.jsonc` or `wrangler.json`, not `wrangler.toml`.
363The available config keys are `name`, `main`,
364`compatibility_date`, `compatibility_flags`, `durable_objects`,
365`migrations`, `assets`, `services`, `triggers`, `vars`, and
366`d1_databases`. An asset-only project can omit `main`. celld refuses
367symlinks and special files in the asset directory, and `.assetsignore`
368still needs Wrangler. Each other key — `routes`, `kv_namespaces`, and the
369rest — stops the deploy
370with an error that names the key: remove the key, or deploy that project
371with Wrangler.
372
373This page is the reference for the implemented Worker surface. For the
374operational boundaries of the current release — TLS, platforms, pressure
375shedding, updates — see the [limitations](limitations.md).