@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/sockets.ts ADDED
@@ -0,0 +1,991 @@
1
+ // The socket plumbing, and only the plumbing. What a subscription means — a
2
+ // saved query whose results are sent again when a committed write changes them
3
+ // — belongs to @yaks/api; this file carries frames between that registry and a
4
+ // Durable Object's WebSockets, which no standard covers.
5
+ //
6
+ // The whole difficulty is hibernation. A socket accepted with
7
+ // `ctx.acceptWebSocket` outlives the object: the runtime evicts the object
8
+ // between two frames and rebuilds it on the next one, so every subscription
9
+ // held in memory is gone while the client still believes it is watching. The
10
+ // socket's attachment preserves its subscriptions or their storage key. A
11
+ // woken object rebuilds the registry from it (`wake`) before doing anything
12
+ // else. It can resume from a snapshot already on the wire or send current
13
+ // results to resync the client.
14
+ //
15
+ // A hibernated socket fires no events either, so @yaks/api's `attach()`, which
16
+ // registers event listeners, cannot be used here: the object's own
17
+ // `webSocketMessage` and `webSocketClose` handlers take its place, calling
18
+ // {@link Sockets.message} and {@link Sockets.close}.
19
+
20
+ import {
21
+ type Ask,
22
+ clockReply,
23
+ decode,
24
+ fault,
25
+ type Frame,
26
+ json,
27
+ type Opening,
28
+ type PeerWriter,
29
+ queue,
30
+ receive,
31
+ type RecoverableListening,
32
+ refusal,
33
+ type Revision,
34
+ type Sink,
35
+ } from '@yaks/api'
36
+ import type { ReadOpts } from 'jsr:@yaks/graph@0.2.36'
37
+ import { sha256 } from '@yaks/graph/sha256'
38
+ import { after, isPromise, over } from '@yaks/fp'
39
+ import { stringify } from '@yaks/vocab/wire'
40
+ import type { DurableStorage } from './sql.ts'
41
+ import { checkpoints, holds, MissingSubscriptions } from './holds.js'
42
+ import { type Delta, pack, unpack } from './watches.js'
43
+
44
+ /**
45
+ * The part of a hibernatable WebSocket this package uses: a frame out, and the
46
+ * attachment that is the socket's only durable memory. A Cloudflare Worker's
47
+ * server-side `WebSocket` satisfies it.
48
+ */
49
+ export type Wire = {
50
+ /** only an open socket can receive a frame; closing sockets may still be
51
+ * returned by `getWebSockets()` */
52
+ readyState: number
53
+ /** send one frame, already serialized */
54
+ send(data: string): void
55
+ /** close a connection whose messages keep exceeding its relay allowance */
56
+ close?(code?: number, reason?: string): void
57
+ /** bytes waiting inside the socket transport */
58
+ bufferedAmount?: number
59
+ /** hold a value on the socket itself — it survives hibernation (2KB cap) */
60
+ serializeAttachment(value: unknown): void
61
+ /** read that value back, `null` when nothing was held */
62
+ deserializeAttachment(): unknown
63
+ }
64
+
65
+ /**
66
+ * The part of a `DurableObjectState` this package uses: accepting a socket for
67
+ * hibernation, and finding the ones a woken object inherited.
68
+ */
69
+ export type Hibernation = {
70
+ /** hand a socket to the runtime, so it outlives this object's memory */
71
+ acceptWebSocket(ws: Wire, tags?: string[]): void
72
+ /** every socket this object is serving, hibernated or not */
73
+ getWebSockets(): Wire[]
74
+ /** the object's storage, used when watches or delivery state exceed 2 KB */
75
+ storage: DurableStorage
76
+ /** Keep an asynchronous transport delivery alive after its entry answers. */
77
+ waitUntil?(work: Promise<unknown>): void
78
+ }
79
+
80
+ /** The plumbing an object wires its handlers to. */
81
+ export type Sockets = {
82
+ /** answer a `/ws` request: accept the socket for hibernation, return the 101 */
83
+ accept(
84
+ request: Request,
85
+ opts?: ReadOpts,
86
+ writer?: PeerWriter,
87
+ socket?: { tags: string[]; opened: (ws: Wire) => void },
88
+ ): Response
89
+ /** a frame arrived — the object's `webSocketMessage` */
90
+ message(
91
+ ws: Wire,
92
+ data: unknown,
93
+ scope?: (
94
+ kind: SocketKind,
95
+ work: () => void | Promise<void>,
96
+ ) => void | Promise<void>,
97
+ ): void | Promise<void>
98
+ /** a socket went away — the object's `webSocketClose` */
99
+ close(ws: Wire): void | Promise<void>
100
+ /** re-open the subscriptions of every socket this object inherited; call it
101
+ * at the top of `fetch`, so a batch applied on a woken object still pushes.
102
+ * Cold peer-only recovery may omit proven static snapshots, not interests. */
103
+ wake(deferStatic?: boolean): void | Promise<void>
104
+ }
105
+
106
+ type Renewals = {
107
+ at: (at: number, read: () => Promise<void>) => () => void
108
+ run: () => Promise<number | null>
109
+ }
110
+
111
+ type LiveSockets = Sockets & {
112
+ /** Refresh timed watches from the object's alarm and return the next due time. */
113
+ renew(): Promise<number | null>
114
+ /** Each open socket's read as `update` makes it, kept on the socket, then
115
+ * checked again (`authorize`): a host told that a caller's standing moved
116
+ * (a seat taken away) says so here, rather than reading it on each frame.
117
+ * A socket refused closes. */
118
+ restand(
119
+ update: (read: ReadOpts | undefined) => ReadOpts | undefined,
120
+ ): Promise<void>
121
+ }
122
+
123
+ /** Schedule subscription reads on the object's existing alarm. On a cold
124
+ * alarm, the adapter restores the socket's watches and reads their current
125
+ * answers, which supply fresh deadlines. The runtime holds no timer between
126
+ * reads. */
127
+ export let socketRenewals = (
128
+ arm: (at: number) => Promise<void>,
129
+ {
130
+ now = Date.now,
131
+ keep,
132
+ }: { now?: () => number; keep?: (work: Promise<void>) => void } = {},
133
+ ): Renewals => {
134
+ let held = new Map<() => Promise<void>, number>()
135
+ let running = false
136
+ return {
137
+ at: (at: number, read: () => Promise<void>) => {
138
+ held.set(read, at)
139
+ if (!running) {
140
+ let armed = arm(at).catch((e) => fault(e, 'socket renewal alarm'))
141
+ keep?.(armed)
142
+ }
143
+ return () => void held.delete(read)
144
+ },
145
+ run: async (): Promise<number | null> => {
146
+ let at = now()
147
+ let due = [...held].filter(([, time]) => time <= at)
148
+ running = true
149
+ try {
150
+ await Promise.all(due.map(([read]) => {
151
+ if (held.delete(read)) return read()
152
+ }))
153
+ let next = Infinity
154
+ for (let time of held.values()) next = Math.min(next, time)
155
+ return next == Infinity ? null : next
156
+ } finally {
157
+ running = false
158
+ }
159
+ },
160
+ }
161
+ }
162
+
163
+ // The runtime's socket factory: two ends of one connection, the client half
164
+ // handed back in the 101 response, the server half handed to the runtime.
165
+ // Declared structurally (the global is looked up at call time) so this package
166
+ // needs no Cloudflare dependency to compile.
167
+ //
168
+ // A plain Worker's upgrade — a pair accepted in this isolate, for @yaks/api's
169
+ // own `/ws` route — is @yaks/workerd' `workerUpgrade`. Here the socket is
170
+ // handed to the runtime instead, which is what hibernation means.
171
+ declare let WebSocketPair: { new (): { 0: unknown; 1: Wire } }
172
+
173
+ // A socket's subscriptions, stored on the socket. The runtime caps an
174
+ // attachment at 2KB, and the application may be storing fields of its own
175
+ // there, so the subscriptions live under one key and the rest is left alone.
176
+ type Held = {
177
+ read?: ReadOpts
178
+ writer?: PeerWriter
179
+ subs?: Record<string, Ask>
180
+ subref?: string
181
+ subdelta?: Delta | string
182
+ relay?: string[]
183
+ acks?: boolean
184
+ frames?: boolean
185
+ owed?: string
186
+ kept?: true
187
+ seen?: string[]
188
+ snapshots?: (Snapshot | null)[]
189
+ }
190
+ type Snapshot = { print: string; revision?: Revision }
191
+ type Seen = [string, Snapshot | null][]
192
+ let CAP = 2048
193
+ let TOKEN = '0'.repeat(36)
194
+ /** How long a burst of watch changes may take before its map is stored, ms. */
195
+ export let SETTLE = 1000
196
+ // A `sync: peers` value is held in memory, and this object's memory does not
197
+ // survive hibernation. The attachment keeps keys; saved components are
198
+ // hydrated from storage under those surviving holders. Unsaved components
199
+ // retain keys alone so their holder's close can still clear them. The 2KB
200
+ // attachment bounds how many keys survive alongside subscriptions.
201
+ let KEYS = 16
202
+ let open = (ws: Wire) => ws.readyState == 1
203
+
204
+ let copy = <T>(values: Record<string, T> = {}): Record<string, T> =>
205
+ Object.assign(Object.create(null), values)
206
+
207
+ let bytes = new TextEncoder()
208
+ let size = (value: unknown) => bytes.encode(JSON.stringify(value)).length
209
+ let within = (value: unknown) => size(value) <= CAP
210
+
211
+ // A delivery can grow independently of its watches. Reserve just the space
212
+ // for its storage key, including on sockets that have yet to enable ACKs.
213
+ let fits = (held: Held) =>
214
+ within(held) && within({
215
+ ...held,
216
+ owed: TOKEN,
217
+ kept: true,
218
+ seen: undefined,
219
+ snapshots: undefined,
220
+ })
221
+
222
+ // Snapshot proofs only avoid redundant transfers. Keep the watches even
223
+ // when there is room for their queries and ACKs alone.
224
+ let fitted = (held: Held): Held | undefined => {
225
+ if (fits(held)) return held
226
+ if (!held.snapshots) return
227
+ let short = { ...held, snapshots: undefined }
228
+ if (fits(short)) return short
229
+ }
230
+
231
+ let snapshot = (frame: Frame) =>
232
+ !frame.refused && (frame.transientReset !== undefined || frame.reset)
233
+
234
+ // Compare the answer itself. A new registry's revision can differ without a
235
+ // change, and rows behind an outstanding ACK can change before it wakes.
236
+ let checkpoint = (frame: Frame): Snapshot => {
237
+ let { revision, since: _, reset: _reset, ...answer } = frame
238
+ return { print: sha256(stringify(answer)).slice(0, 32), revision }
239
+ }
240
+
241
+ let relayOf = (ws: Wire): string[] => {
242
+ let held = ws.deserializeAttachment() as Held | null
243
+ let keys = held && typeof held == 'object' ? held.relay : undefined
244
+ return Array.isArray(keys) ? keys : []
245
+ }
246
+
247
+ // The relay keys, written back beside everything else. Over the cap they are
248
+ // simply not written: a relay must never cost somebody their subscriptions.
249
+ let remember = (ws: Wire, keys: string[]) => {
250
+ let held = ws.deserializeAttachment()
251
+ let was = held && typeof held == 'object' ? held as Held : {}
252
+ let relay = keys.slice(0, KEYS)
253
+ let next = relay.length ? { ...was, relay } : { ...was, relay: undefined }
254
+ if (fits(next)) ws.serializeAttachment(next)
255
+ }
256
+
257
+ // What a frame subscribed to, read alongside @yaks/api's own dispatch so that
258
+ // the attachment stays current. Anything malformed is not a subscription —
259
+ // `receive` rejects it.
260
+ let asked = (
261
+ msg: unknown,
262
+ ):
263
+ | { id: string; ask?: Ask; acks?: boolean; frames?: boolean; ack?: string }
264
+ | null => {
265
+ if (!msg || typeof msg != 'object') return null
266
+ if ('ack' in msg && typeof msg.ack == 'string') {
267
+ return { id: '', ack: msg.ack }
268
+ }
269
+ let sub = 'subscribe' in msg ? msg.subscribe : undefined
270
+ if (typeof sub == 'string' || sub === true) {
271
+ return {
272
+ id: 'id' in msg && msg.id != null ? String(msg.id) : '',
273
+ ask: sub,
274
+ acks: 'acks' in msg && msg.acks === true,
275
+ frames: 'acks' in msg && msg.acks === true &&
276
+ 'frames' in msg && msg.frames === true,
277
+ }
278
+ }
279
+ if ('unsubscribe' in msg && msg.unsubscribe != null) {
280
+ return { id: String(msg.unsubscribe) }
281
+ }
282
+ return null
283
+ }
284
+
285
+ /** The finite protocol label a host may use for aggregate socket costs.
286
+ * Frame ids, queries, relay values and malformed input never become labels. */
287
+ export type SocketKind = 'ack' | 'subscribe' | 'unsubscribe' | 'relay' | 'other'
288
+ let messageKind = (msg: unknown): SocketKind => {
289
+ if (msg && typeof msg == 'object') {
290
+ if ('ack' in msg && typeof msg.ack == 'string') return 'ack'
291
+ if (
292
+ 'subscribe' in msg &&
293
+ (typeof msg.subscribe == 'string' || msg.subscribe === true)
294
+ ) {
295
+ return 'subscribe'
296
+ }
297
+ if ('unsubscribe' in msg && msg.unsubscribe != null) return 'unsubscribe'
298
+ if ('relay' in msg && Array.isArray(msg.relay)) return 'relay'
299
+ }
300
+ return 'other'
301
+ }
302
+
303
+ /** Answer a client's clock probe, `received` at the object's door: true
304
+ * when the frame was one, on a socket still open. Nothing else is read or
305
+ * written, so an object answers one before it opens anything. */
306
+ export let probed = (
307
+ ws: Wire,
308
+ data: unknown,
309
+ received: number = Date.now(),
310
+ ): boolean => open(ws) && answered(ws, decode(data), received)
311
+
312
+ let answered = (
313
+ ws: Wire,
314
+ input: ReturnType<typeof decode>,
315
+ received: number,
316
+ ) => clockReply(ws, 'value' in input ? input.value : null, received)
317
+
318
+ /**
319
+ * Wire a Durable Object's sockets to a subscription registry. The object keeps
320
+ * one of these and calls it from its three handlers:
321
+ *
322
+ * ```ts
323
+ * // fetch(request) → live.wake(); live.accept(request)
324
+ * // webSocketMessage(ws, data) → live.message(ws, data)
325
+ * // webSocketClose(ws) → live.close(ws)
326
+ * ```
327
+ *
328
+ * Frames go straight to the socket; no durable write crosses it (a batch is
329
+ * applied with `POST /apply`, and the socket is how everyone hears about it).
330
+ * The one exception is a `sync: peers` relay, which crosses here because its
331
+ * lifetime is this socket's — see @yaks/api's `receive`.
332
+ */
333
+ export let sockets = (
334
+ subs: RecoverableListening,
335
+ ctx: Hibernation,
336
+ report?: (error: Error) => void,
337
+ opts: {
338
+ /** On peer-only recovery, register static durable watch interests without
339
+ * repeating the snapshot already held by the page. Unknown queries open. */
340
+ deferStatic?: boolean
341
+ /** Restore caller read context from the authenticated socket writer. */
342
+ read?: (
343
+ read: ReadOpts | undefined,
344
+ writer: PeerWriter | undefined,
345
+ ) => ReadOpts
346
+ /** A host whose authenticated standing expires on wake can require a
347
+ * new handshake before this writer relays again. */
348
+ writer?: (writer: PeerWriter) => boolean | Promise<boolean>
349
+ /** Current read/delivery authority. Denial or failure retires the socket.
350
+ * Checked on recovery, input, and at transport delivery (including ACKs).
351
+ * `held` is the read the socket holds, as accepted or last `restand`. */
352
+ authorize?: (
353
+ read: ReadOpts | undefined,
354
+ writer: PeerWriter | undefined,
355
+ held: ReadOpts | undefined,
356
+ ) => boolean | Promise<boolean>
357
+ /** Told each refusal a socket is sent, as the client reads it: an
358
+ * object on older code than its caller restarts on one, as it does on a
359
+ * refused request, since a socket's refusals come after its handshake was
360
+ * answered. */
361
+ refused?: (refusal: { error: string; message: string }) => void
362
+ /** The subprotocol the host selected for this upgrade, if it uses one. */
363
+ protocol?: (request: Request) => string | undefined
364
+ /** The alarm-backed scheduler used by this registry's timed watches. */
365
+ renewals?: Renewals
366
+ /** How a burst of watch changes is put off until its stored map is
367
+ * written once (default: a timer of {@link SETTLE} ms, which also keeps
368
+ * the object from hibernating before the write is made). */
369
+ defer?: (write: () => void) => void
370
+ } = {},
371
+ ): LiveSockets => {
372
+ let sinks = new Map<
373
+ Wire,
374
+ ReturnType<typeof queue> & { forget: (id: string) => void }
375
+ >()
376
+ let closed = new WeakSet<Wire>()
377
+ // Sockets this incarnation accepted, and those any check has let through:
378
+ // the handshake already asked who the caller is, so a check refusing one
379
+ // it admitted before letting anything through is two answers to one
380
+ // question, which is ours to hear about.
381
+ let accepted = new WeakSet<Wire>()
382
+ let admitted = new WeakSet<Wire>()
383
+ let recovered = new Map<Wire, Promise<void>>()
384
+ let waking: Promise<void> | undefined
385
+ let queries = new Map<Wire, Record<string, Ask>>()
386
+ let baselines = new Map<Wire, Record<string, Ask>>()
387
+ let repo: ReturnType<typeof holds> | undefined
388
+ let backing = () => repo ??= holds(ctx.storage)
389
+ let saved: ReturnType<typeof checkpoints<Seen>> | undefined
390
+ let proofs = () => saved ??= checkpoints<Seen>(ctx.storage)
391
+ // A page changes its watches in bursts: one that walks into another tile
392
+ // opens the tiles it reaches and closes the ones it left, a message each.
393
+ // Its stored map is written once the burst settles, not once a message.
394
+ let owed = new Map<string, Record<string, Ask>>()
395
+ let reading = (held: Held | null): ReadOpts | undefined =>
396
+ opts.read ? opts.read(held?.read, held?.writer) : held?.read
397
+ // The registry's timers (@yaks/api `Subs`), unset the runtime's: read as a
398
+ // timer is set, so a clock probe never touches the registry.
399
+ let timer = (fn: () => void, ms: number) => {
400
+ if (subs.timer) return subs.timer(fn, ms)
401
+ let t = setTimeout(fn, ms)
402
+ return () => clearTimeout(t)
403
+ }
404
+ let defer = opts.defer ?? ((write) => void timer(write, SETTLE))
405
+ let pay = () => {
406
+ let due = [...owed]
407
+ owed.clear()
408
+ for (let [ref, map] of due) backing().write(ref, map)
409
+ }
410
+ let owe = (ref: string, map: Record<string, Ask>) => {
411
+ let first = !owed.size
412
+ owed.set(ref, map)
413
+ if (first) defer(pay)
414
+ }
415
+ let release = (ref: string) => {
416
+ owed.delete(ref)
417
+ backing().delete(ref)
418
+ }
419
+ let asks = (ws: Wire): Record<string, Ask> => {
420
+ let cached = queries.get(ws)
421
+ if (cached) return cached
422
+ let held = ws.deserializeAttachment() as Held | null
423
+ let found = copy(held?.subref ? backing().read(held.subref) : held?.subs)
424
+ if (held?.subref) baselines.set(ws, copy(found))
425
+ for (let [id, ask] of Object.entries(unpack(held?.subdelta ?? {}))) {
426
+ if (ask === null) delete found[id]
427
+ else found[id] = ask
428
+ }
429
+ queries.set(ws, found)
430
+ return found
431
+ }
432
+ // Keep the small map on the socket. Once it exceeds the attachment's
433
+ // allowance, keep only its key there and store the queries on this object.
434
+ let hold = (
435
+ ws: Wire,
436
+ nextSubs: Record<string, Ask>,
437
+ held: Held,
438
+ ) => {
439
+ let next: Held = {
440
+ ...held,
441
+ subs: nextSubs,
442
+ subref: undefined,
443
+ subdelta: undefined,
444
+ }
445
+ let inline = fitted(next)
446
+ if (inline) {
447
+ ws.serializeAttachment(inline)
448
+ if (held.subref) release(held.subref)
449
+ baselines.delete(ws)
450
+ } else {
451
+ let ref = held.subref ?? crypto.randomUUID()
452
+ let short = { ...next, subs: undefined, subref: ref }
453
+ // A watch burst changes only part of a large stored map. Keep that
454
+ // difference on the socket; compact only when it no longer fits.
455
+ let baseline = baselines.get(ws)
456
+ let delta = copy<Ask | null>()
457
+ if (baseline) {
458
+ for (let [id, ask] of Object.entries(nextSubs)) {
459
+ if (!Object.hasOwn(baseline, id) || baseline[id] !== ask) {
460
+ delta[id] = ask
461
+ }
462
+ }
463
+ for (let id of Object.keys(baseline)) {
464
+ if (!Object.hasOwn(nextSubs, id)) delta[id] = null
465
+ }
466
+ }
467
+ let overlay = baseline &&
468
+ (fitted({ ...short, subdelta: delta }) ??
469
+ fitted({ ...short, subdelta: pack(delta) }))
470
+ if (overlay) {
471
+ ws.serializeAttachment(overlay)
472
+ } else {
473
+ // Repeated query paths often compress the complete watch map below
474
+ // the attachment limit. Its existing delta format carries the map
475
+ // over an empty base, preserving ACK room before anything spills.
476
+ let packed = fitted({
477
+ ...next,
478
+ subs: undefined,
479
+ subdelta: pack(nextSubs),
480
+ })
481
+ if (packed) {
482
+ ws.serializeAttachment(packed)
483
+ if (held.subref) release(held.subref)
484
+ baselines.delete(ws)
485
+ } else {
486
+ let attached = fitted(short)
487
+ if (!attached) return false
488
+ baselines.set(ws, nextSubs)
489
+ owe(ref, nextSubs)
490
+ ws.serializeAttachment(attached)
491
+ }
492
+ }
493
+ }
494
+ queries.set(ws, nextSubs)
495
+ return true
496
+ }
497
+
498
+ let delivery = (
499
+ ws: Wire,
500
+ owed?: string,
501
+ seen = new Map<string, Snapshot | undefined>(),
502
+ ) => {
503
+ let was = ws.deserializeAttachment() as Held | null
504
+ let next: Held = {
505
+ ...was,
506
+ owed,
507
+ kept: undefined,
508
+ seen: seen.size ? [...seen.keys()] : undefined,
509
+ snapshots: seen.size
510
+ ? [...seen.values()].map((s) => s ?? null)
511
+ : undefined,
512
+ }
513
+ let previous = was?.kept ? was.owed : undefined
514
+ let inline = within(next)
515
+ let spill = owed && seen.size && !inline ? owed : undefined
516
+ if (spill) {
517
+ proofs().write(
518
+ spill,
519
+ [...seen].map(([id, proof]) => [id, proof ?? null]),
520
+ )
521
+ next = { ...next, kept: true, seen: undefined, snapshots: undefined }
522
+ }
523
+ try {
524
+ if (inline || within(next)) ws.serializeAttachment(next)
525
+ // A socket inherited from before the reservation can still have its
526
+ // watches in the space now owed to the delivery key.
527
+ else if (!hold(ws, asks(ws), next)) {
528
+ throw new RangeError('socket attachment has no room for an ACK key')
529
+ }
530
+ } catch (error) {
531
+ if (spill && spill !== previous) proofs().delete(spill)
532
+ throw error
533
+ }
534
+ if (previous && previous !== spill) proofs().delete(previous)
535
+ }
536
+
537
+ let drop = (ws: Wire) => {
538
+ if (closed.has(ws)) return
539
+ closed.add(ws)
540
+ let to = sinks.get(ws)
541
+ let dropped: void | Promise<void> = undefined
542
+ if (to) {
543
+ to.close()
544
+ dropped = subs.drop(to.send)
545
+ }
546
+ sinks.delete(ws)
547
+ queries.delete(ws)
548
+ baselines.delete(ws)
549
+ let held = ws.deserializeAttachment() as Held | null
550
+ if (held?.subref || held?.kept) {
551
+ // The socket can outlive this incarnation. Clear its pointer before
552
+ // deleting the row, so a later wake cannot read a row we removed.
553
+ ws.serializeAttachment({
554
+ ...held,
555
+ subref: undefined,
556
+ subdelta: undefined,
557
+ subs: undefined,
558
+ kept: undefined,
559
+ owed: undefined,
560
+ })
561
+ if (held.subref) release(held.subref)
562
+ if (held.kept && held.owed) proofs().delete(held.owed)
563
+ }
564
+ return dropped
565
+ }
566
+
567
+ let retire = (ws: Wire, error: unknown) => {
568
+ if (!(error instanceof MissingSubscriptions)) throw error
569
+ finish(ws)
570
+ try {
571
+ ws.close?.(1012, 'subscriptions lost')
572
+ } catch { /* the socket may already be closed */ }
573
+ report?.(error)
574
+ }
575
+
576
+ // A protocol retirement has no caller to await its final saved writes.
577
+ let finish = (ws: Wire) => {
578
+ let out = drop(ws)
579
+ if (out) out.catch((error) => fault(error, 'socket close'))
580
+ }
581
+
582
+ // The sink for a socket, created once. A socket this object has not seen
583
+ // before may still be one it inherited, so its stored subscriptions are
584
+ // re-opened here — the client is sent its current results, which is the
585
+ // resync.
586
+ let authorize = (ws: Wire): boolean | Promise<boolean> => {
587
+ if (!opts.authorize) return true
588
+ // A socket is closed once: two checks in flight together (a wake's and a
589
+ // message's) both refuse it, and only the first closes it.
590
+ let refused = (why?: unknown) => {
591
+ if (closed.has(ws)) return false
592
+ if (why !== undefined) {
593
+ report?.(why instanceof Error ? why : new Error(String(why)))
594
+ }
595
+ finish(ws)
596
+ try {
597
+ ws.close?.(1012, 'authorization handshake required')
598
+ } catch { /* closed */ }
599
+ return false
600
+ }
601
+ try {
602
+ let held = ws.deserializeAttachment() as Held | null
603
+ let out = opts.authorize(reading(held), held?.writer, held?.read)
604
+ let admit = (ok: boolean) => {
605
+ if (closed.has(ws)) return refused()
606
+ if (!ok) {
607
+ return refused(
608
+ accepted.has(ws) && !admitted.has(ws)
609
+ ? new Error('a socket its handshake admitted was refused')
610
+ : undefined,
611
+ )
612
+ }
613
+ admitted.add(ws)
614
+ return true
615
+ }
616
+ return isPromise(out) ? out.then(admit, refused) : admit(out)
617
+ } catch (error) {
618
+ return refused(error)
619
+ }
620
+ }
621
+
622
+ let sink = (
623
+ ws: Wire,
624
+ openings?: Opening[],
625
+ deferStatic = false,
626
+ ): Sink | Promise<Sink> => {
627
+ let to = sinks.get(ws)?.send
628
+ if (to) return after(recovered.get(ws), () => to!)
629
+ let held = ws.deserializeAttachment() as Held | null
630
+ let saved: Seen | undefined
631
+ if (held?.owed && held.kept) {
632
+ saved = proofs().read(held.owed)
633
+ if (!saved) {
634
+ let error = new Error('socket delivery checkpoint missing')
635
+ if (report) report(error)
636
+ else fault(error, 'socket wake')
637
+ }
638
+ }
639
+ let seen = new Map<string, Snapshot | undefined>(
640
+ saved
641
+ ? saved.map(([id, proof]) => [id, proof ?? undefined])
642
+ : (held?.owed ? held.seen ?? [] : []).map((id, i) => [
643
+ id,
644
+ held?.snapshots?.[i] ?? undefined,
645
+ ]),
646
+ )
647
+ if (!held?.owed && held?.seen?.length) {
648
+ delivery(ws)
649
+ }
650
+ // Gate the transport, not just the registry sink: ACKs and timer flushes
651
+ // can release frames long after the subscription's last read.
652
+ let waiting: string[] = []
653
+ let sending = 0
654
+ let delivering = false
655
+ let deliver = async () => {
656
+ try {
657
+ while (waiting.length && !closed.has(ws) && open(ws)) {
658
+ // Frames already queued can leave together. Anything queued while
659
+ // this check is away belongs to the next authorization.
660
+ let batch = waiting.splice(0)
661
+ sending = batch.length
662
+ if (!await authorize(ws) || closed.has(ws) || !open(ws)) return
663
+ for (let data of batch) ws.send(data)
664
+ sending = 0
665
+ }
666
+ } catch {
667
+ finish(ws)
668
+ try {
669
+ ws.close?.(1012, 'authorization handshake required')
670
+ } catch { /* closed */ }
671
+ } finally {
672
+ waiting.length = sending = 0
673
+ delivering = false
674
+ }
675
+ }
676
+ let transport = !opts.authorize ? ws : {
677
+ get bufferedAmount() {
678
+ return ws.bufferedAmount
679
+ },
680
+ send: (data: string) => {
681
+ if (waiting.length + sending >= 64) {
682
+ finish(ws)
683
+ ws.close?.(1012, 'authorization delivery backlog')
684
+ return
685
+ }
686
+ waiting.push(data)
687
+ if (delivering) return
688
+ delivering = true
689
+ let pending = Promise.resolve().then(deliver)
690
+ ctx.waitUntil?.(pending)
691
+ },
692
+ }
693
+ let fresh = queue(transport, timer, () => open(ws), {
694
+ owed: held?.owed,
695
+ sent: (frames, token) => {
696
+ if ((ws.deserializeAttachment() as Held | null)?.frames) seen.clear()
697
+ for (let f of frames) {
698
+ if (snapshot(f)) seen.set(f.id, checkpoint(f))
699
+ else if (f.revision !== undefined || f.refused) seen.delete(f.id)
700
+ }
701
+ delivery(ws, token, seen)
702
+ },
703
+ // An ACK that let the next frame out was recorded by `sent` already.
704
+ acked: (owed) => {
705
+ if (owed) return
706
+ seen.clear()
707
+ delivery(ws)
708
+ },
709
+ })
710
+ let skip = new Map(seen)
711
+ let previous = new Map<string, Revision | undefined>()
712
+ let reopening = new Map(Object.entries(asks(ws)))
713
+ let send: Sink = (frame) => {
714
+ if (frame.refused) opts.refused?.(frame.refused)
715
+ let id = frame.id
716
+ if (reopening.has(id) && reopening.get(id) !== true) {
717
+ reopening.delete(id)
718
+ let sent = skip.get(id)
719
+ skip.delete(id)
720
+ // A proof from the old attachment lets an identical snapshot keep
721
+ // its predecessor on the wire. A changed answer needs a full reset.
722
+ if (
723
+ sent && snapshot(frame) && !frame.reset &&
724
+ sent.print === checkpoint(frame).print
725
+ ) {
726
+ previous.set(id, sent.revision)
727
+ return
728
+ }
729
+ frame = { ...frame, reset: true }
730
+ }
731
+ if (frame.revision !== undefined && previous.has(id)) {
732
+ if (frame.since !== undefined) {
733
+ frame = { ...frame, since: previous.get(id) }
734
+ }
735
+ previous.delete(id)
736
+ }
737
+ fresh.send(frame)
738
+ }
739
+ sinks.set(ws, {
740
+ ...fresh,
741
+ send,
742
+ forget: (id) => {
743
+ skip.delete(id)
744
+ previous.delete(id)
745
+ if (!seen.delete(id)) return
746
+ let held = ws.deserializeAttachment() as Held | null
747
+ delivery(ws, held?.owed, seen)
748
+ },
749
+ })
750
+ if (held?.acks) fresh.enable(held.frames)
751
+ // The relay keys first: whatever else this socket did, the registry has to
752
+ // know what it is saying before a close can stop saying it.
753
+ let relay = relayOf(ws)
754
+ let out = after(subs.relayed(send, relay), () => {
755
+ if (closed.has(ws)) return
756
+ if (
757
+ relay.some((key) => {
758
+ let comp = key.slice(key.indexOf(' ') + 1)
759
+ return subs.vocab?.comp(comp)?.durable == 'connection'
760
+ })
761
+ ) transport.send(JSON.stringify({ id: '', resay: true }))
762
+ return after(
763
+ over(Object.entries(asks(ws)), ([id, ask]) => {
764
+ if (openings) {
765
+ openings.push({
766
+ sink: send,
767
+ id,
768
+ query: ask,
769
+ opts: reading(held),
770
+ writer: held?.writer,
771
+ })
772
+ } else {
773
+ return subs.restore([{
774
+ sink: send,
775
+ id,
776
+ query: ask,
777
+ opts: reading(held),
778
+ writer: held?.writer,
779
+ }], deferStatic)
780
+ }
781
+ }),
782
+ () => {},
783
+ )
784
+ })
785
+ if (isPromise(out)) {
786
+ recovered.set(ws, out)
787
+ out.then(() => recovered.delete(ws), () => recovered.delete(ws))
788
+ }
789
+ return after(out, () => send)
790
+ }
791
+
792
+ let adapter: LiveSockets = {
793
+ accept: (request, read, writer, socket) => {
794
+ if ((request.headers.get('upgrade') ?? '').toLowerCase() != 'websocket') {
795
+ return json(
796
+ { error: 'NotAllowed', message: 'this is a WebSocket endpoint' },
797
+ 405,
798
+ )
799
+ }
800
+ let pair = new WebSocketPair()
801
+ // Accepted for hibernation: the runtime holds this socket while the
802
+ // object is evicted and wakes the object with the next frame, so an idle
803
+ // client costs nothing.
804
+ if (read || writer) {
805
+ pair[1].serializeAttachment({ read, writer })
806
+ }
807
+ ctx.acceptWebSocket(pair[1], socket?.tags)
808
+ accepted.add(pair[1])
809
+ socket?.opened(pair[1])
810
+ // The 101 carries the other end; `webSocket` is the runtime's own
811
+ // ResponseInit field, which no standard declares.
812
+ let protocol = opts.protocol?.(request)
813
+ return new Response(
814
+ null,
815
+ {
816
+ status: 101,
817
+ webSocket: pair[0],
818
+ ...protocol
819
+ ? { headers: { 'sec-websocket-protocol': protocol } }
820
+ : {},
821
+ } as
822
+ & ResponseInit
823
+ & { webSocket: unknown },
824
+ )
825
+ },
826
+
827
+ message: (ws, data, scope) => {
828
+ if (closed.has(ws)) return
829
+ if (!open(ws)) return
830
+ let received = Date.now()
831
+ let input = decode(data)
832
+ if (answered(ws, input, received)) return
833
+ let run = () => {
834
+ let held = ws.deserializeAttachment() as Held | null
835
+ let msg = 'value' in input ? input.value : undefined
836
+ // A held identity is vouched at the handshake. A host may refresh its
837
+ // current standing on wake without making the page reopen its socket.
838
+ let relay = msg && typeof msg == 'object' &&
839
+ 'relay' in msg && Array.isArray(msg.relay)
840
+ let valid = relay
841
+ ? held?.writer === undefined
842
+ ? false
843
+ : opts.writer?.(held.writer) ?? true
844
+ : true
845
+ return after(valid, (valid) => {
846
+ if (!valid) {
847
+ finish(ws)
848
+ ws.close?.(1012, 'writer handshake required')
849
+ return
850
+ }
851
+ return after(
852
+ after(
853
+ authorize(ws),
854
+ (ok) =>
855
+ ok
856
+ ? sink(ws, undefined, !!opts.deferStatic && !!relay)
857
+ : undefined,
858
+ ),
859
+ (to) => {
860
+ if (!to) return
861
+ let ask = asked('value' in input ? input.value : null)
862
+ let sender = sinks.get(ws)!
863
+ if (ask?.ack) return sender.ack(ask.ack)
864
+ if (ask) sender.forget(ask.id)
865
+ if (ask?.acks) sender.enable(ask.frames)
866
+ let was = subs.relaying(to).join('\n')
867
+ return after(
868
+ receive(
869
+ subs,
870
+ to,
871
+ data,
872
+ undefined,
873
+ input,
874
+ reading(ws.deserializeAttachment() as Held | null),
875
+ (ws.deserializeAttachment() as Held | null)?.writer,
876
+ ),
877
+ (verdict) => {
878
+ if (verdict == 'close') {
879
+ finish(ws)
880
+ ws.close?.(1008, 'relay flood')
881
+ return
882
+ }
883
+ // Only when it moved: a frame that relays nothing should not rewrite
884
+ // an attachment, and most frames relay nothing.
885
+ let now = subs.relaying(to)
886
+ if (now.join('\n') != was) remember(ws, now)
887
+ if (!ask) return
888
+ let subscriptions = copy(asks(ws))
889
+ if (ask.ask === undefined) delete subscriptions[ask.id]
890
+ else subscriptions[ask.id] = ask.ask
891
+ let held = ws.deserializeAttachment() as Held | null
892
+ if (
893
+ hold(ws, subscriptions, {
894
+ ...held,
895
+ ...(ask.acks ? { acks: true } : {}),
896
+ ...(ask.frames ? { frames: true } : {}),
897
+ })
898
+ ) return
899
+ subs.close(to, ask.id)
900
+ to({
901
+ id: ask.id,
902
+ refused: refusal(
903
+ new RangeError(
904
+ 'too many subscriptions to survive hibernation',
905
+ ),
906
+ ),
907
+ })
908
+ },
909
+ )
910
+ },
911
+ )
912
+ })
913
+ }
914
+ let kind = messageKind('value' in input ? input.value : null)
915
+ let recover = () => {
916
+ try {
917
+ let out = run()
918
+ if (isPromise(out)) return out.catch((error) => retire(ws, error))
919
+ } catch (error) {
920
+ retire(ws, error)
921
+ }
922
+ }
923
+ return scope ? scope(kind, recover) : recover()
924
+ },
925
+
926
+ close: drop,
927
+
928
+ renew: async () => {
929
+ if (!opts.renewals) return null
930
+ await adapter.wake()
931
+ return await opts.renewals.run()
932
+ },
933
+
934
+ restand: async (update) => {
935
+ await Promise.all(
936
+ ctx.getWebSockets().map((ws) => {
937
+ if (closed.has(ws) || !open(ws)) return
938
+ let held = ws.deserializeAttachment() as Held | null
939
+ let read = update(held?.read)
940
+ if (read !== held?.read) ws.serializeAttachment({ ...held, read })
941
+ return authorize(ws)
942
+ }),
943
+ )
944
+ },
945
+
946
+ wake: (deferStatic = false) => {
947
+ if (waking) {
948
+ return deferStatic ? waking : waking.then(() => subs.resume?.())
949
+ }
950
+ let openings: Opening[] = []
951
+ // Start the inherited readers' checks together so the host can batch
952
+ // them. Register their sinks in order as their own checks answer.
953
+ let inherited = ctx.getWebSockets()
954
+ .filter((ws) => !closed.has(ws) && open(ws))
955
+ .map((ws) => ({ ws, check: sinks.has(ws) || authorize(ws) }))
956
+ let out = after(
957
+ over(inherited, ({ ws, check }) => {
958
+ if (closed.has(ws) || !open(ws)) return
959
+ // An open sink already has its watches. Messages and delivery
960
+ // check its standing when it next uses them.
961
+ if (sinks.has(ws)) return recovered.get(ws)
962
+ try {
963
+ let restored = after(
964
+ check,
965
+ (ok) =>
966
+ ok && !closed.has(ws) && open(ws)
967
+ ? sink(ws, openings)
968
+ : undefined,
969
+ )
970
+ if (isPromise(restored)) {
971
+ return restored.then(() => {}, (error) => retire(ws, error))
972
+ }
973
+ } catch (error) {
974
+ retire(ws, error)
975
+ }
976
+ }),
977
+ () =>
978
+ after(
979
+ openings.length ? subs.restore(openings, deferStatic) : undefined,
980
+ () => !deferStatic ? subs.resume?.() : undefined,
981
+ ),
982
+ )
983
+ if (isPromise(out)) {
984
+ waking = out
985
+ out.then(() => waking = undefined, () => waking = undefined)
986
+ }
987
+ return out
988
+ },
989
+ }
990
+ return adapter
991
+ }