@yaks/durable-object 0.0.0-stage → 0.2.36

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (91) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +554 -2
  3. package/_dist/alarm.d.ts +35 -0
  4. package/_dist/alarm.d.ts.map +1 -0
  5. package/_dist/ceiling.d.ts +167 -0
  6. package/_dist/ceiling.d.ts.map +1 -0
  7. package/_dist/compose.d.ts +79 -0
  8. package/_dist/compose.d.ts.map +1 -0
  9. package/_dist/copy.d.ts +67 -0
  10. package/_dist/copy.d.ts.map +1 -0
  11. package/_dist/door.d.ts +172 -0
  12. package/_dist/door.d.ts.map +1 -0
  13. package/_dist/job.d.ts +26 -0
  14. package/_dist/job.d.ts.map +1 -0
  15. package/_dist/keys.d.ts +14 -0
  16. package/_dist/keys.d.ts.map +1 -0
  17. package/_dist/mod.d.ts +65 -0
  18. package/_dist/mod.d.ts.map +1 -0
  19. package/_dist/object.d.ts +75 -0
  20. package/_dist/object.d.ts.map +1 -0
  21. package/_dist/profile.d.ts +32 -0
  22. package/_dist/profile.d.ts.map +1 -0
  23. package/_dist/query-memory.d.ts +27 -0
  24. package/_dist/query-memory.d.ts.map +1 -0
  25. package/_dist/resets.d.ts +208 -0
  26. package/_dist/resets.d.ts.map +1 -0
  27. package/_dist/rewind.d.ts +21 -0
  28. package/_dist/rewind.d.ts.map +1 -0
  29. package/_dist/sockets.d.ts +90 -0
  30. package/_dist/sockets.d.ts.map +1 -0
  31. package/_dist/sql.d.ts +72 -0
  32. package/_dist/sql.d.ts.map +1 -0
  33. package/_dist/store.d.ts +8 -0
  34. package/_dist/store.d.ts.map +1 -0
  35. package/alarm.js +126 -0
  36. package/alarm.js.map +1 -0
  37. package/alarm.ts +188 -0
  38. package/ceiling.js +536 -0
  39. package/ceiling.js.map +1 -0
  40. package/ceiling.ts +681 -0
  41. package/compose.js +201 -0
  42. package/compose.js.map +1 -0
  43. package/compose.ts +249 -0
  44. package/copy.js +394 -0
  45. package/copy.js.map +1 -0
  46. package/copy.ts +413 -0
  47. package/deno.json +1 -0
  48. package/door.js +364 -0
  49. package/door.js.map +1 -0
  50. package/door.ts +542 -0
  51. package/example.ts +108 -0
  52. package/holds.js +85 -0
  53. package/holds.js.map +1 -0
  54. package/holds.ts +72 -0
  55. package/job.js +151 -0
  56. package/job.js.map +1 -0
  57. package/job.ts +166 -0
  58. package/keys.js +59 -0
  59. package/keys.js.map +1 -0
  60. package/keys.ts +85 -0
  61. package/mod.js +65 -0
  62. package/mod.js.map +1 -0
  63. package/mod.ts +167 -0
  64. package/object.js +247 -0
  65. package/object.js.map +1 -0
  66. package/object.ts +385 -0
  67. package/package.json +68 -4
  68. package/profile.js +131 -0
  69. package/profile.js.map +1 -0
  70. package/profile.ts +150 -0
  71. package/query-memory.js +157 -0
  72. package/query-memory.js.map +1 -0
  73. package/query-memory.ts +240 -0
  74. package/resets.js +302 -0
  75. package/resets.js.map +1 -0
  76. package/resets.ts +353 -0
  77. package/rewind.js +68 -0
  78. package/rewind.js.map +1 -0
  79. package/rewind.ts +91 -0
  80. package/sockets.js +749 -0
  81. package/sockets.js.map +1 -0
  82. package/sockets.ts +991 -0
  83. package/sql.js +221 -0
  84. package/sql.js.map +1 -0
  85. package/sql.ts +330 -0
  86. package/store.js +58 -0
  87. package/store.js.map +1 -0
  88. package/store.ts +80 -0
  89. package/watches.js +8 -0
  90. package/watches.js.map +1 -0
  91. package/watches.ts +23 -0
package/README.md CHANGED
@@ -1,3 +1,555 @@
1
- # Temporary Holding Version
1
+ # @yaks/durable-object
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ SQLite storage and hibernatable WebSocket support for
4
+ [@yaks/graph](../graph/README.md) in a Cloudflare Durable Object. The
5
+ application supplies the vocabulary, plugins, and request authorization.
6
+
7
+ Graph data persists in the object's embedded SQLite database. A **bundle** is
8
+ one entity's components represented as a JSON object; a **batch** is a list of
9
+ bundles applied in one transaction. Socket subscriptions are saved in WebSocket
10
+ attachments so they can be restored after the object hibernates.
11
+
12
+ For graph write phases and adapter responsibilities, see the
13
+ [graph architecture](../graph/ARCHITECTURE.md).
14
+
15
+ ## Install
16
+
17
+ ```sh
18
+ deno add jsr:@yaks/durable-object jsr:@yaks/graph jsr:@yaks/vocab jsr:@yaks/api
19
+ ```
20
+
21
+ ## Storage and sockets
22
+
23
+ `storage(ctx.storage, vocab, base?)` adapts the object's SQLite API to an
24
+ [@yaks/sql](../sql/README.md) `Driver`, and [@yaks/sqlite](../sqlite/README.md)
25
+ over that driver creates the schema, reads components, and applies row changes.
26
+ `ctx.storage.transactionSync` provides the transaction. Storage operations are
27
+ synchronous; graph plugins can make an operation asynchronous, but code
28
+ executing inside `transactionSync` must remain synchronous: it commits when its
29
+ body returns, so a write that awaits inside it commits half way. Such a write is
30
+ reported to the store's `report` (an error named `Halfway`, its stack the
31
+ write's) and goes on as it was; the code that went async is the fix.
32
+
33
+ Pass an optional observer to `driver(ctx.storage, observe)` or as the fourth
34
+ argument to `storage(ctx.storage, vocab, base, observe)` to receive each drained
35
+ cursor's `rowsRead` and `rowsWritten` with a value-free SQL shape.
36
+ `profile(emit)` collects these samples in memory. `flush()` emits its first
37
+ nonempty summary immediately and subsequent summaries at most once per minute.
38
+
39
+ Cloudflare bills every row a statement reads or writes and offers no cap on it,
40
+ so every driver counts its statements against its object's **ceiling**
41
+ (`./ceiling.ts`): the rows the object may read and write in a minute and in an
42
+ hour (`WINDOWS`). Two failures are reported as they happen:
43
+
44
+ - `Scan`: one statement read `SCAN` (100,000) rows or more and `FAR` (100) times
45
+ what its answer represents or it wrote. A direct `COUNT(*)` answer represents
46
+ its counted inputs, including each group's count in a tally, and an `ANALYZE`
47
+ represents every row it reads to count. It is reported once an hour for each
48
+ statement shape, with the shape; the ratio alone does not establish which
49
+ indexes the engine used.
50
+ - `Runaway`: the object's statements together passed a window's rows. It is
51
+ reported once for that window, with the costliest shapes.
52
+
53
+ A host names where the reports go once, before its first driver:
54
+ `bounded(ctx.storage, { report, refuse })`. Every driver over that storage
55
+ counts against the same ceiling, and so does `keys(ctx.storage)`, the object's
56
+ async key-value calls (`get`, `put`, `delete`, `list`): Cloudflare bills a key
57
+ read as a row read and a key put or deleted as a row written, and a `Durable`
58
+ object's `keys` are these. With `refuse`, a statement past a window is refused
59
+ as `Stopped` (status 429, `retry.after` in milliseconds, `retry.defer`) until
60
+ the window ends: past its written rows the object still reads, and past its read
61
+ rows it takes nothing. A host asks `stopped(writing)` (the wait in milliseconds,
62
+ 0 when a statement is admitted) or `refusal(writing)` at its doors, so a stopped
63
+ object answers there rather than failing deep inside. Statements a stopped
64
+ object must still take, such as keeping a person's write for later or an effect
65
+ pool's word on how a run ended, run inside the ceiling's `free(body)`, which
66
+ holds across the awaits of an asynchronous body until it settles and not for the
67
+ timers it leaves; work that must not stop half way runs on
68
+ `freely(ctx.storage)`, a driver that counts and never refuses. What runs free
69
+ counts against windows of its own: it is told past them and stops nothing, so a
70
+ relocation's new object takes writes once it serves. Work whose cost is the
71
+ object's own size, once, runs inside `take(body)`: a deploy's schema install, or
72
+ an index over a table past what any window writes, which SQLite builds in one
73
+ statement. It stops nothing, counts against no window and is told only as a
74
+ scan, never as a runaway. Work that can wait asks
75
+ `under(share, written?, lane?)` how long until the object has spent under that
76
+ share of every window. Run as a lane's work (`lane(name, body)`, across awaits
77
+ like `free`), the share is of that lane's own rows, so two kinds of background
78
+ work each keep an allowance the other's backlog cannot spend. A lane includes
79
+ its free statements, such as an effect's completion write, and saves its tally
80
+ after it spends rows so the next instance resumes with the same share remaining.
81
+ An object whose stopping costs more than its rows is `spare()`d: told, never
82
+ refused.
83
+
84
+ The tallies outlive the instance, so an object evicted or restarted mid-window
85
+ goes on where it stood. `bounded` keeps them in one row of the object's
86
+ `ctx.storage.kv` as a window's rows pass half of what it may and as they pass
87
+ it, once the turn that passed it is over (a transaction its `Stopped` unwound
88
+ still read and wrote its rows), and a new instance reads that row at its first
89
+ statement. That costs no row a statement: at most two rows written a window for
90
+ reads and two for writes, none for an object spending under half. `ceiling`
91
+ takes the same as `kept()` and `keep(spent)`.
92
+
93
+ A `Stopped` that crosses a stub reaches its caller as a new error with the name,
94
+ message and own properties it was thrown with, never its class
95
+ ([RPC error handling](https://developers.cloudflare.com/workers/runtime-apis/rpc/error-handling/),
96
+ enhanced error serialization, on from compatibility date 2026-04-21), so a
97
+ caller asks `stopped(error)`, which knows it by its name and its `retry.after`.
98
+ `crossed(error)` in `./testing.ts` hands an error over the same way.
99
+
100
+ `sockets(subs, ctx)` connects hibernatable WebSockets to
101
+ [@yaks/api](../api/README.md) subscriptions. The API registry re-evaluates saved
102
+ queries after committed changes; this adapter accepts sockets, dispatches
103
+ frames, and restores subscriptions after hibernation.
104
+
105
+ ## The whole object
106
+
107
+ This example stores books with title, body, price, status, and an author
108
+ reference. `State` describes the subset of `DurableObjectState` used here, so
109
+ the example does not need Cloudflare's global types. The package also contains a
110
+ similar [example.ts](./example.ts).
111
+
112
+ ```ts
113
+ import { api, type Handler, subscriptions } from '@yaks/api'
114
+ import { graph } from '@yaks/graph'
115
+ import { loadVocab } from '@yaks/vocab'
116
+ import {
117
+ type DurableStorage,
118
+ type Hibernation,
119
+ type Sockets,
120
+ sockets,
121
+ storage,
122
+ type Wire,
123
+ } from '@yaks/durable-object'
124
+
125
+ type State = Hibernation & { storage: DurableStorage }
126
+
127
+ let vocab = loadVocab({
128
+ $defs: {
129
+ entity: {
130
+ component: true,
131
+ type: 'object',
132
+ wire: false,
133
+ properties: { num: { type: 'number', stamped: true } },
134
+ },
135
+ doc: {
136
+ component: true,
137
+ type: 'object',
138
+ kind: true,
139
+ properties: {
140
+ title: { type: 'string' },
141
+ body: { type: 'string' },
142
+ },
143
+ },
144
+ book: {
145
+ component: true,
146
+ type: 'object',
147
+ kind: true,
148
+ before: ['doc'],
149
+ properties: {
150
+ price: { type: 'number' },
151
+ status: { type: 'string', enum: ['shelved', 'sold'] },
152
+ author: { type: 'string', ref: 'entity', death: 'detach' },
153
+ },
154
+ },
155
+ },
156
+ })
157
+
158
+ export class Bookshop {
159
+ #live: Sockets
160
+ #route: Handler
161
+
162
+ constructor(ctx: State) {
163
+ let store = storage(ctx.storage, vocab, { number: true })
164
+ store.install() // initialize tables and indexes
165
+ let shop = graph({ storage: store, vocab })
166
+ let subs = subscriptions(shop) // shared by HTTP and WebSocket handlers
167
+ this.#live = sockets(subs, ctx)
168
+ this.#route = api({ graph: shop, subs })
169
+ }
170
+
171
+ fetch(request: Request): Response | Promise<Response> {
172
+ this.#live.wake()
173
+ return new URL(request.url).pathname == '/ws'
174
+ ? this.#live.accept(request)
175
+ : this.#route(request)
176
+ }
177
+
178
+ webSocketMessage(ws: Wire, data: string | ArrayBuffer): void {
179
+ this.#live.message(ws, data)
180
+ }
181
+
182
+ webSocketClose(ws: Wire): void {
183
+ this.#live.close(ws)
184
+ }
185
+ }
186
+ ```
187
+
188
+ Declare the class in your Worker's `wrangler.toml`:
189
+
190
+ ```toml
191
+ [[durable_objects.bindings]]
192
+ name = "SHOP"
193
+ class_name = "Bookshop"
194
+
195
+ [[migrations]]
196
+ tag = "v1"
197
+ new_sqlite_classes = ["Bookshop"]
198
+ ```
199
+
200
+ A Worker must forward requests to an object instance, for example using its
201
+ `SHOP.getByName('main').fetch(request)` binding. The class implements HTTP apply
202
+ and query routes and handles `/ws` itself:
203
+
204
+ ```sh
205
+ curl -X POST https://shop.example/apply -H 'content-type: application/json' -d '[
206
+ { "entity": { "eid": "b1" },
207
+ "doc": { "title": "The Left Hand of Spring" },
208
+ "book": { "price": 12, "status": "shelved" } }
209
+ ]'
210
+
211
+ curl --get https://shop.example/query --data-urlencode 'q=.book.status=shelved&.book.price<20'
212
+ ```
213
+
214
+ ```ts ignore
215
+ // After opening a WebSocket to /ws:
216
+ socket.send(JSON.stringify({ subscribe: '.book.status=shelved', id: 'shelf' }))
217
+ // Response: { id: 'shelf', bundles: [{ entity: { eid: 'b1', num: 1 }, ... }] }
218
+ ```
219
+
220
+ The example stores body text directly. A property declared `store: 'blob'`
221
+ requires the corresponding blob storage and graph plugin setup; this adapter
222
+ does not provide that automatically. Schema installation is repeatable, but
223
+ application schema migrations still require coordination.
224
+
225
+ ## One class, one alarm
226
+
227
+ `Durable` is the object as a class, for every kind of object a Worker serves.
228
+ What differs between kinds is its spec, which a subclass hands to `super`, or
229
+ answers from `specify()` where the spec names the subclass's own members:
230
+
231
+ - `open(object)` composes what the object holds, once an instance, given the
232
+ object (its `ctx`, `clock` and `ceiling`): its door (`serve`), the
233
+ subscriptions its sockets serve (`subs`), and the works its alarm runs
234
+ (`works`). An open that fails is tried again by the next entry. An object that
235
+ holds nothing to open names none, and one with no door answers every
236
+ request 404.
237
+ - `report(error, entry)` takes every failure the object catches.
238
+ - `ceiling` is the row ceiling's options, refusing by default; `version` is the
239
+ deploy the object runs.
240
+
241
+ Every entry opens first and wakes the sockets the object inherited: `fetch`,
242
+ `alarm`, a socket's frame, and the subclass's own, `enter(name, work)`, which
243
+ its RPC methods call. A failure is reported by its entry, and the alarm rings a
244
+ second on. A door's statement past the ceiling is answered `Stopped`, with how
245
+ long to wait; an RPC method throws it on, its wait with it, unreported. A socket
246
+ is the door's to accept, through `accept(request)`, after whatever the door
247
+ checks. The first entry on a new `version` arms the alarm, which takes up what
248
+ the object owes: a deploy restarts it idle.
249
+
250
+ A socket's frame or close is the object's to `admit` first: one it does not is
251
+ let go unanswered. A clock probe is answered next, before the sockets are asked.
252
+ An object that makes its own sockets, over subscriptions it remakes, answers
253
+ them from `live()`; none closes a frame's socket, for the page to open another.
254
+ `frame(ws, data, take)` reads a frame itself, or around `take`, the sockets' own
255
+ reading. A socket's error is its close.
256
+
257
+ `clock(ctx.storage, works, options?)` is the alarm loop the class runs. Each
258
+ ring gives every work one slice (`SLICE`, ten seconds), and each answers when it
259
+ is next owed; the alarm is set for the soonest. While a slice runs the alarm
260
+ stands at `BACKSTOP`, so an instance cut off mid-slice is rung again. A work
261
+ that fails is reported and tried again `RETRY` (a minute) on; one the ceiling
262
+ stopped waits for its window. A write that owes work calls `clock.arm(at)`,
263
+ which keeps an alarm already set sooner.
264
+
265
+ ```ts
266
+ import { Durable, type State } from '@yaks/durable-object'
267
+
268
+ class Counter extends Durable {
269
+ constructor(ctx: State) {
270
+ super(ctx, {
271
+ open: async () => ({
272
+ serve: () => new Response('ok'),
273
+ works: { sweep: async (until) => null },
274
+ }),
275
+ report: (error, entry) => console.error(entry, error),
276
+ })
277
+ }
278
+ }
279
+ ```
280
+
281
+ ## An object from a config
282
+
283
+ An object whose graph is composed through [@yaks/host](../host/README.md)
284
+ differs from another only by its plugins, so its spec is data:
285
+ `composed(config, load, options?)` (`@yaks/durable-object/compose`).
286
+
287
+ - Its graph is the config's plugins, their facets taken from `load`, over the
288
+ object's SQLite (`storage(ctx.storage, vocab, …)`), with schema and blobs
289
+ installed as it opens. `options.roles` are the roles it serves (`ROLES`: its
290
+ graph and effects); `options.words` the words it speaks, where it knows them
291
+ before its facets do.
292
+ - Its door is `api({graph, subs})`, which hands `/ws` to its sockets.
293
+ - Its works are the wakes due (@yaks/wake `tick`) and the effects pool, and a
294
+ write that moves a wake or owes a run arms the alarm.
295
+
296
+ `planned(config, load, roles?)` is the plan behind it: the facets imported once
297
+ an isolate (@yaks/host `prepare`), then assembled once a vocabulary
298
+ (`assemble`). An object that binds its plan to capabilities of its own asks it
299
+ and binds what it answers; `lent(me, blobs)` is what an object lends what it
300
+ composes, hosting no process.
301
+
302
+ ```ts ignore
303
+ import { Durable, type State } from '@yaks/durable-object'
304
+ import { composed } from '@yaks/durable-object/compose'
305
+
306
+ export class Shelf extends Durable {
307
+ constructor(ctx: State) {
308
+ super(ctx, composed({ plugins: ['@yaks/wake', 'shelf'] }, load))
309
+ }
310
+ }
311
+ ```
312
+
313
+ ## Hibernation, and why `wake()`
314
+
315
+ A socket accepted with `ctx.acceptWebSocket` can remain connected while the
316
+ runtime discards the object instance. Reconstructing the instance loses its
317
+ in-memory subscription registry. The adapter saves each socket's subscriptions
318
+ in its attachment and restores them when needed.
319
+
320
+ Call `wake()` before handling HTTP requests so a write that wakes the object
321
+ also reaches existing subscribers. Restoring a subscription sends its current
322
+ results. Forward `webSocketMessage` and `webSocketClose` to `message` and
323
+ `close`, returning the latter's promise so final saves finish before the handler
324
+ ends; the adapter restores inherited sockets when processing frames as well.
325
+ Ordinary event-listener attachment through `@yaks/api` does not handle this
326
+ hibernation lifecycle.
327
+
328
+ Attachments have a 2 KB runtime limit. Small subscription maps use the `subs`
329
+ field, preserving other application fields. When queries exceed that limit, the
330
+ adapter keeps them in the object's SQLite and holds their key in `subref`. The
331
+ socket holds its outstanding ACK and up to 16 temporary relay keys. Snapshot
332
+ proofs that outgrow the attachment go to SQLite under the outstanding ACK token.
333
+ They are released as the ACK advances or the socket closes. The subscription row
334
+ is removed when the socket closes. The relay values themselves remain in memory.
335
+ Components declaring `save` also keep a durable snapshot through the graph's
336
+ `apply()`. Pass the handshake's authenticated writer and vocabulary versions as
337
+ `accept`'s third argument; the attachment retains them across hibernation.
338
+ Unsaved values keep a timer until their save is due; a quiet saved value leaves
339
+ no timer. Legacy sockets reconnect before their first saved relay to obtain the
340
+ writer's vouch.
341
+
342
+ ## What the runtime is strict about
343
+
344
+ The driver converts booleans to 0/1, bigints to numbers, and `Uint8Array` values
345
+ to `ArrayBuffer` slices. BLOB results become `Uint8Array` again. Bigint
346
+ conversion can lose precision outside JavaScript's safe-integer range.
347
+
348
+ The runtime rejects transaction SQL such as `BEGIN` and `SAVEPOINT`; the adapter
349
+ uses nested `transactionSync` calls through `Driver.tx`. It enables foreign-key
350
+ enforcement when creating the driver.
351
+
352
+ Cloudflare-owned tables may appear in the SQLite catalog but reject application
353
+ reads. `prohibited(name)` recognizes `_cf_` names regardless of case or leading
354
+ underscore count. `reserved(name)` also recognizes SQLite's `sqlite_` tables,
355
+ for code enumerating application-owned tables.
356
+
357
+ ## Resets
358
+
359
+ The runtime moves an object to a new instance when it likes (a deploy, a runtime
360
+ update, another machine, a failure inside its own storage, a lost connection to
361
+ it), and the instance it moved fails its work in flight; whoever owns that work
362
+ runs it again. `moved(error)` recognizes those words, "Network connection lost."
363
+ among them: a caller meets it when its call is cut off, and an instance whose
364
+ own storage lost its connection refuses every statement in it.
365
+ `replaced(ctx.storage)` says whether this instance is the one that was moved: a
366
+ reset instance still answers a read but refuses every write, so it asks through
367
+ a transaction; one killed for its CPU or memory limit is replaced as well.
368
+ `vacating(run, ctx.storage)` is `run`'s answer, or those words as soon as
369
+ `replaced` turns true while `run` still waits, asked every `LOOK` ms: a request
370
+ its instance was reset under can wait on what never settles, and its caller
371
+ sends it again to the live instance. `evicted(error)` is a reset a caller should
372
+ send again for, and `killed(error)` a kill for the CPU or memory limit, which no
373
+ code of the object sees. `opaque(error)` is the runtime's own internal error,
374
+ which names only a reference: the work is tried again, and reported if it keeps
375
+ failing. `retried(send, replayable, retry, wait)` sends a call again while it
376
+ fails in words `retry` knows (`evicted` by default), pausing before each resend
377
+ as `backoff` says; `wait` waits a pause out, `jittered(clock)` by default (half
378
+ of it or more, on the runtime's clock unless given one), and a test hands its
379
+ own.
380
+
381
+ ```ts
382
+ import { assertEquals } from '@std/assert'
383
+ import { moved, replaced } from '@yaks/durable-object'
384
+
385
+ let error = new Error('Durable Object reset because its code was updated.')
386
+ let reset = {
387
+ sql: { exec: () => [] },
388
+ transactionSync: () => {
389
+ throw error
390
+ },
391
+ }
392
+ // This instance was reset: the next one runs the work again, so no report.
393
+ assertEquals(moved(error) && replaced(reset), true)
394
+ ```
395
+
396
+ ## The door to an object
397
+
398
+ A caller reaches an object only by fetch, through a stub its namespace hands out
399
+ by name. `stubOf(ns, name, hint?)` is that stub, created where the location hint
400
+ says (`'enam'`, say): the runtime reads a hint only at an object's first get and
401
+ never moves an object. A stub is bound to the request that took it, so take one
402
+ per call; getting one costs nothing.
403
+
404
+ `doorOf(send, scrub?)` is a `Door`: a path, an init and the call's headers in,
405
+ the object's answer out (`consume(path, read, …)` reads it). It builds every
406
+ request from scratch, drops the init's headers named in `scrub` before setting
407
+ the call's own, and hands the request to `send`, which has the last word on its
408
+ headers. An init that is a `Request` carries its method, body and headers
409
+ across, which is how a socket upgrade reaches the object.
410
+
411
+ `coalesced(door, reads, {hold?, turn?, patience?, headStart?, clock?, beat?, wait?})`
412
+ shares GETs that `reads(request)` accepts and that arrive before `turn` sends
413
+ them, keyed by address and headers. Each caller gets its own response bytes. A
414
+ read already sent answers no later caller, since its snapshot may predate that
415
+ caller, so one read of a request travels at a time: callers who ask it meanwhile
416
+ share the next, sent once it lands, and the object answers a burst of one read
417
+ once a round trip. A write or an excluded request separates batches. Select only
418
+ finite read responses. `turn` defaults to a microtask; `hold` keeps the opener's
419
+ trip alive past its own request, as a Worker's `waitUntil` does.
420
+
421
+ A Worker settles a promise only in the request that made it, so no caller awaits
422
+ or settles another's (@yaks/fp `Scope`). The caller that opens a batch sends it
423
+ from its own request, and the answer lands on the batch as a value: the bytes,
424
+ or the failure. Every caller looks for it every `beat` ms (5 by default) on its
425
+ own clock (@yaks/fp `waitFor`). A caller unanswered for `patience` ms (15 s by
426
+ default, on `clock`) presumes its batch lost, as when its opener's request
427
+ ended, and boards once more. A second lost trip fails the read. With a shorter
428
+ `headStart`, a batch can send after that much time behind a pending trip, and a
429
+ caller sharing its first batch can join a fresh batch after the same wait. The
430
+ original sender keeps its own trip until it answers or reaches `patience`.
431
+ `wait` wraps the full wait so a host can name it. Wrap a resending door so
432
+ reading the shared body participates in its retries.
433
+
434
+ `resending(door, { report?, wait? })` sends a call again, as `retried` paces it,
435
+ when the runtime reset the object or lost the call: thrown, or answered as a
436
+ 500's refusal body (`reset(response)`, `thrown(response)`). A call is sent again
437
+ only while that is safe: its request can be built again (no streamed body, and
438
+ not `replayable: false`), and every send carries one `IDEMPOTENCY` key, which a
439
+ caller may name, so an object that applied it before its answer was lost answers
440
+ the next send as it answered the first (@yaks/api receipts). An answer is read
441
+ whole inside the retry, so a restart that cuts off its body is sent again too; a
442
+ stream is handed on as it comes. A read that fails in the runtime's opaque words
443
+ is sent again, a write is not, and a kill for the object's limits or a refusal
444
+ for memory goes to `report` before anything else sees it.
445
+
446
+ ```ts
447
+ import { assertEquals } from '@std/assert'
448
+ import { doorOf, resending, stubOf } from '@yaks/durable-object/door'
449
+
450
+ let sends = 0
451
+ let ns = {
452
+ idFromName: (name: string) => name,
453
+ get: () => ({
454
+ fetch: () =>
455
+ Promise.resolve(
456
+ ++sends == 1
457
+ ? Response.json({ message: 'Network connection lost.' }, {
458
+ status: 500,
459
+ })
460
+ : new Response('ok'),
461
+ ),
462
+ }),
463
+ }
464
+ let door = resending(
465
+ doorOf((req) => stubOf(ns, 'ada', 'enam').fetch(req), ['x-who']),
466
+ { wait: () => Promise.resolve() },
467
+ )
468
+ assertEquals(await (await door('/query')).text(), 'ok')
469
+ assertEquals(sends, 2)
470
+ ```
471
+
472
+ What a call says beyond that is the caller's: yaks.app's kernel names the
473
+ headers only it may set as `scrub`, and its `send` stamps its deploy and the app
474
+ on every request (workers/yak/door.ts).
475
+
476
+ ## API
477
+
478
+ `@yaks/durable-object` exports everything below. A reader of the object's
479
+ storage that holds no socket imports `@yaks/durable-object/sql` (`driver`),
480
+ `/store` (`storage`), `/resets` (the reset helpers), `/door` (the door to an
481
+ object), `/ceiling`, `/keys` or `/alarm` alone, without `sockets` and the
482
+ `@yaks/api` dispatch it brings:
483
+
484
+ | Export | Purpose |
485
+ | ------------------------------------------------------- | --------------------------------------------------- |
486
+ | `storage(ctx.storage, vocab, base?)` | Creates an `@yaks/sqlite` `Store` |
487
+ | `driver(ctx.storage, observe?)` | Creates the underlying synchronous SQLite `Driver` |
488
+ | `freely(ctx.storage, observe?)` | A `driver` the ceiling counts and never refuses |
489
+ | `keys(ctx.storage)` | The async key-value calls, counted by the ceiling |
490
+ | `profile(emit)` | Aggregates cursor costs into bounded summaries |
491
+ | `bounded(ctx.storage, options?)`, `ceiling(options?)` | Report a scan or a runaway, and stop the object |
492
+ | `stopped(error)` | Whether a failure is a stop, here or across a stub |
493
+ | `Durable`, `Spec`, `Opened`, `State` | The object class and what makes one kind of object |
494
+ | `clock(ctx.storage, works, options?)`, `Work` | The one alarm loop, in slices |
495
+ | `composed(config, load, options?)`, `planned`, `lent` | An object's spec, and its plan, from a config |
496
+ | `sockets(subs, ctx)` | Returns `accept`, `message`, `close`, and `wake` |
497
+ | `stubOf(ns, name, hint?)`, `Namespace`, `Stub` | An object's stub by name, placed by a hint |
498
+ | `doorOf(send, scrub?)`, `Door`, `Send`, `Call` | A request built from scratch for every call |
499
+ | `resending(door, { report?, wait? })`, `IDEMPOTENCY` | A door that sends a call again across a reset |
500
+ | `reset(response)`, `thrown(response)` | A reset an object answered, read or thrown |
501
+ | `prohibited`, `reserved` | Identify internal runtime tables |
502
+ | `moved`, `replaced`, `evicted`, `killed`, `opaque` | Tell a reset of this instance from a failure |
503
+ | `vacating(run, ctx.storage, clock?, every?)`, `LOOK` | Fail a request whose instance was replaced |
504
+ | `retried`, `backoff`, `jittered` | Send a call again when the object was reset or lost |
505
+ | `DurableStorage`, `DurableSql`, `SqlCursor`, `SqlValue` | Structural storage types |
506
+ | `Hibernation`, `Wire`, `Sockets`, `Store` | Structural socket and store types |
507
+
508
+ The store exposes `ddl`, `grown`, `install`, `read`, `rows`, `get`, and `tx`.
509
+ Base options include derived expressions, SQL extensions, a fixed `now`, schema
510
+ text expressions, numbering, and identity adoption. See the
511
+ [SQLite API](../sqlite/README.md#api) for details.
512
+
513
+ For a regular Worker without Durable Object hibernation, use `@yaks/workerd`'s
514
+ `workerUpgrade` with the `@yaks/api` WebSocket route. Subscriptions in that
515
+ arrangement last only as long as the Worker isolate.
516
+
517
+ ## Composition
518
+
519
+ This adapter shares the graph `Storage` interface with in-process `@yaks/sqlite`
520
+ and asynchronous `@yaks/d1`. The SQLite schema and write planners are shared;
521
+ the transaction implementation differs. Conformance tests compare this package
522
+ with the embedded SQLite adapter using the same sequence of graph operations.
523
+
524
+ ## Compatibility
525
+
526
+ The adapter targets Cloudflare Durable Objects with SQLite storage and
527
+ hibernatable sockets. Its published code imports no Deno or Node globals and
528
+ uses structural types instead of importing Cloudflare runtime code. `conform.ts`
529
+ checks compatibility with `@cloudflare/workers-types` in the Workers program of
530
+ `deno task check:types`, apart from Deno's, to keep Workers globals out of
531
+ unrelated type-checks:
532
+
533
+ ```sh
534
+ deno task check:types packages/durable-object/conform.ts
535
+ ```
536
+
537
+ ## Related packages
538
+
539
+ - [@yaks/query](../query/README.md): query parsing.
540
+ - [@yaks/vocab](../vocab/README.md): component and reference schema.
541
+ - [@yaks/graph](../graph/README.md): bundles, validation, plugins, and
542
+ `apply()`.
543
+ - [@yaks/sqlite](../sqlite/README.md): schema, SQL reads, and writes.
544
+ - [@yaks/api](../api/README.md): HTTP routes and subscriptions.
545
+
546
+ ## License
547
+
548
+ Apache-2.0
549
+
550
+ When a trace context is subscribed, the SQL driver emits one `sql` span per
551
+ statement. Its code name comes from the SQL AST, never rendered values. The
552
+ span's `rowsRead` and `rowsWritten` counts are the runtime cursor's billed
553
+ counts, not the number of returned rows; `statements` includes failed calls.
554
+ These measurements are charged inclusively to enclosing spans through
555
+ [@yaks/trace](../trace/README.md). Recording adds no SQL reads or writes.
@@ -0,0 +1,35 @@
1
+ /** The alarm methods a Durable Object's storage provides. */ export type Alarms = {
2
+ getAlarm(): Promise<number | null>;
3
+ setAlarm(at: number): Promise<void>;
4
+ deleteAlarm?(): Promise<void>;
5
+ };
6
+ /**
7
+ * One kind of work the alarm does. Given the instant its slice ends, it does
8
+ * what is due and answers when it is next owed, in ms since the epoch: now or
9
+ * earlier when the slice ended with some left, null when nothing is owed.
10
+ */ export type Work = (until: number) => Promise<number | null | undefined> | number | null | undefined;
11
+ /** How the loop is run. */ export type Options = {
12
+ /** The clock; `Date.now` by default. */ now?: () => number;
13
+ /** A work's failure, by the work's name. */ report?: (error: unknown, work: string) => void;
14
+ /** Observe a named work for as long as its slice runs. */ around?: (name: string, run: () => ReturnType<Work>) => ReturnType<Work>;
15
+ /** How long until the object may work again: its ceiling's
16
+ * `stopped(true)`, 0 while it is admitted. */ wait?: () => number;
17
+ /** Given the slice once it is under way, so the alarm answers then: the
18
+ * object's `waitUntil`. Without it the ring answers once the slice ends. */ keep?: (slice: Promise<void>) => void;
19
+ /** How long one ring works: an alarm is one invocation, and the runtime
20
+ * caps its CPU. */ slice?: number;
21
+ /** How far out the alarm stands while a slice it answered before runs. */ backstop?: number;
22
+ /** How long a failed work waits before it is tried again. */ retry?: number;
23
+ };
24
+ /** An object's alarm loop. */ export type Clock = {
25
+ /** Ring at `at` (ms since the epoch), unless the alarm is set sooner. */ arm(at: number): Promise<void>;
26
+ /** The runtime's `alarm()`: one slice of every work, then the alarm set
27
+ * for the soonest owed. */ ring(): Promise<void>;
28
+ };
29
+ /** How long one ring works. */ export declare let SLICE: number;
30
+ /** How far out the alarm stands while a slice runs. */ export declare let BACKSTOP: number;
31
+ /** How long a failed work waits before it is tried again. */ export declare let RETRY: number;
32
+ /** The loop over `works`, run in the order given. Given as a function, the
33
+ * works are asked for at each ring, so an object can name them once it has
34
+ * opened what they work on. */ export declare let clock: (storage: Alarms, works: Record<string, Work> | (() => Record<string, Work>), opts?: Options) => Clock;
35
+ //# sourceMappingURL=alarm.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"alarm.d.ts","sources":["../alarm.ts"],"names":[],"mappings":"AA6CA,2DAA2D,GAC3D,YAAY;EACV,YAAY,QAAQ,MAAM,GAAG,IAAI;EACjC,SAAS,IAAI,MAAM,GAAG,QAAQ,IAAI;EAClC,gBAAgB,QAAQ,IAAI;;AAG9B;;;;CAIC,GACD,YAAY,QACV,OAAO,MAAM,KACV,QAAQ,MAAM,GAAG,IAAI,GAAG,SAAS,IAAI,MAAM,GAAG,IAAI,GAAG,SAAS;AAEnE,yBAAyB,GACzB,YAAY;EACV,sCAAsC,GACtC,YAAY,MAAM;EAClB,0CAA0C,GAC1C,UAAU,OAAO,OAAO,EAAE,MAAM,MAAM,KAAK,IAAI;EAC/C,wDAAwD,GACxD,UAAU,MAAM,MAAM,EAAE,WAAW,WAAW,UAAU,WAAW;EACnE;8CAC4C,GAC5C,aAAa,MAAM;EACnB;4EAC0E,GAC1E,QAAQ,OAAO,QAAQ,IAAI,MAAM,IAAI;EACrC;mBACiB,GACjB,QAAQ,MAAM;EACd,wEAAwE,GACxE,WAAW,MAAM;EACjB,2DAA2D,GAC3D,QAAQ,MAAM;;AAGhB,4BAA4B,GAC5B,YAAY;EACV,uEAAuE,GACvE,IAAI,IAAI,MAAM,GAAG,QAAQ,IAAI;EAC7B;2BACyB,GACzB,QAAQ,QAAQ,IAAI;;AAGtB,6BAA6B,GAC7B,OAAO,YAAI,cAAc;AACzB,qDAAqD,GACrD,OAAO,YAAI,iBAAiB;AAC5B,2DAA2D,GAC3D,OAAO,YAAI,cAAc;AAEzB;;6BAE6B,GAC7B,OAAO,YAAI,QACT,SAAS,QACT,OAAO,OAAO,MAAM,EAAE,eAAe,OAAO,MAAM,EAAE,QACpD,OAAM,YACL,MAgFF"}