Diffinery

homeflare/celldpublic

celld/docs/services/durable-objects.md
159 lines · 9.0 KBRaw History
1# Durable Objects / Cells
2
3A Durable Object is a single-threaded actor with durable storage, and celld
4calls each running Durable Object a cell. An application uses one when a piece
5of state needs a single consistent owner, such as a chat room, a game match, a
6shopping cart, an agent session, or a rate limiter. The state lives in a SQLite
7database that belongs to that object alone, on the node that serves it, and
8celld replicates the database to the fleet. Read the
9[Cloudflare Durable Objects documentation](https://developers.cloudflare.com/durable-objects/)
10for the standard API behavior.
11
12## Example
13
14The [counter example](../../examples/counter) keeps a counter in the key-value
15storage of a Durable Object, and it uses `idFromName()` to give each name a
16separate counter.
17
18<!-- celld-example: counter -->
19
20## Identity and addressing
21
22A `durable_objects` binding exposes one class as a namespace, and an
23application reaches an object in two steps. `env.COUNTER.idFromName("room-7")`
24returns a `DurableObjectId`, and `env.COUNTER.get(id)` returns a
25`DurableObjectStub`. `getByName("room-7")` performs both steps together. The
26stub 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/)
29for the complete method list.
30
31`idFromName()` is deterministic. celld derives the id with HMAC-SHA-256 over
32the name, under a key that belongs to the namespace, so one name always gives
33the same 64-digit hexadecimal id. That id always reaches the same object, and
34two Workers on two different nodes that use one name therefore reach one
35object. The name also survives in `ctx.id.name` when it is 1024 UTF-8 bytes or
36less, which is the Cloudflare rule, and a longer name still routes to the
37correct object.
38
39`newUniqueId()` instead draws random bytes, so its object carries no name and
40no later caller can address it again. Keep the `toString()` form of such an id
41if the application must reach the object a second time. `idFromString()` parses
42that hexadecimal form and verifies the HMAC, therefore celld refuses an id that
43belongs to a different namespace instead of creating an unrelated object.
44
45celld builds the key of a namespace from the script name and the class name, so
46a rename of the Worker script changes every id that the namespace derives. The
47objects of the old name keep their storage under the old ids, and the renamed
48script reaches new and empty objects. Keep the script name stable, or migrate
49the data before the rename.
50
51celld implements no jurisdiction, because a celld fleet has only the machines
52that you run. `newUniqueId({ jurisdiction })` and `namespace.jurisdiction()`
53throw an error, so an application learns about the gap at the call site.
54
55## Ownership and the single-threaded model
56
57Cloudflare creates an object near the first request that uses it, and
58Cloudflare can migrate the object afterwards. celld makes no placement,
59migration, or jurisdiction promise, and it makes one narrower promise instead:
60exactly one node serves a cell at a time.
61
62A node claims a cell by writing an ownership record into the fleet bucket with
63a conditional write. The object store accepts only one of two competing
64writers, so two nodes cannot own one cell. Every activation advances a fencing
65epoch, and the epoch appears in the storage prefix, therefore a node that lost
66the cell writes only into a superseded prefix. The
67[guarantees](../guarantees.md) page gives the full mechanism.
68
69A Worker holds its stub on whichever node served the request. celld resolves
70the owner of the cell and forwards the call to that node, so the object code
71runs on the owner and nowhere else. Inside the cell, one event runs at a time:
72a `fetch`, an RPC method, an `alarm()`, or a WebSocket message. celld also
73holds a response until a durability proof covers every write that the response
74can reveal, which is the behavior Cloudflare calls the
75[output gate](https://developers.cloudflare.com/durable-objects/best-practices/rules-of-durable-objects/).
76An application therefore does not have to `await` a `put()`, because a client
77cannot receive the response before the write survives a failure.
78
79![Two Workers on different nodes address the name room-7, the owner record in the fleet bucket names one owner node, celld forwards both calls to that node, and the cell replicates through a follower node into an epoch-fenced bucket prefix](durable-objects-flow.svg)
80
81A cell keeps no in-memory state across an eviction. celld removes an idle cell
82from memory, and the cell then hibernates on its node or becomes inactive in
83the bucket, so the constructor runs again at the next event. Ownership can move
84as well, because a node can stop, a node can drain, and idle rebalancing can
85move a hibernated cell to another node. A reader must therefore treat only
86durable storage as persistent. A hibernatable WebSocket survives a hibernation
87on the same node, and it closes when the cell moves to a new owner, so a client
88must 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
96through `ctx.storage.sql.exec()`. `transaction()` and `transactionSync()` group
97several writes, and `storage.sync()` waits for the durability of the earlier
98committed writes. Read the
99[storage documentation](https://developers.cloudflare.com/durable-objects/best-practices/access-durable-objects-storage/)
100for the method signatures.
101
102The durability of that database comes from the fleet, not from a managed
103service. celld captures each write as an LTX segment and replicates the segment
104to `cells/<cell>/ltx/e<epoch>/` in the fleet bucket. A fleet of two or more
105nodes is faster, because the owner also sends each write to one or two follower
106nodes and answers as soon as a follower holds the write on its own disk. The
107bucket upload follows afterwards. A single node has no follower, so every write
108on 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
112scheduled time and passes `retryCount` and `isRetry`, as the
113[Alarms API](https://developers.cloudflare.com/durable-objects/api/alarms/)
114describes. celld does not answer a successful response until a durable wake
115entry in the bucket covers the alarm, so a crash cannot lose a schedule that a
116client already saw. A hibernated cell fires its alarm on the node that owns it.
117One node in the fleet holds the waker role, and it wakes only a cell whose
118owner node stopped, so the alarm work of the fleet does not queue on one
119machine.
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
158The [Cloudflare compatibility](../cloudflare-compat.md#services) page
159lists the runtime APIs and the unsupported services.