@yaks/sync 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 (75) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +729 -2
  3. package/_dist/coverage.d.ts +7 -0
  4. package/_dist/coverage.d.ts.map +1 -0
  5. package/_dist/inbound.d.ts +43 -0
  6. package/_dist/inbound.d.ts.map +1 -0
  7. package/_dist/mark.d.ts +29 -0
  8. package/_dist/mark.d.ts.map +1 -0
  9. package/_dist/mod.d.ts +78 -0
  10. package/_dist/mod.d.ts.map +1 -0
  11. package/_dist/outbound.d.ts +55 -0
  12. package/_dist/outbound.d.ts.map +1 -0
  13. package/_dist/outbox.d.ts +48 -0
  14. package/_dist/outbox.d.ts.map +1 -0
  15. package/_dist/pace.d.ts +9 -0
  16. package/_dist/pace.d.ts.map +1 -0
  17. package/_dist/port.d.ts +31 -0
  18. package/_dist/port.d.ts.map +1 -0
  19. package/_dist/revision.d.ts +60 -0
  20. package/_dist/revision.d.ts.map +1 -0
  21. package/_dist/saying.d.ts +12 -0
  22. package/_dist/saying.d.ts.map +1 -0
  23. package/_dist/socket.d.ts +151 -0
  24. package/_dist/socket.d.ts.map +1 -0
  25. package/_dist/sync.d.ts +97 -0
  26. package/_dist/sync.d.ts.map +1 -0
  27. package/_dist/tier.d.ts +62 -0
  28. package/_dist/tier.d.ts.map +1 -0
  29. package/clock.js +43 -0
  30. package/clock.js.map +1 -0
  31. package/clock.ts +56 -0
  32. package/coverage.js +13 -0
  33. package/coverage.js.map +1 -0
  34. package/coverage.ts +26 -0
  35. package/deno.json +1 -0
  36. package/inbound.js +217 -0
  37. package/inbound.js.map +1 -0
  38. package/inbound.ts +251 -0
  39. package/mark.js +87 -0
  40. package/mark.js.map +1 -0
  41. package/mark.ts +108 -0
  42. package/mod.js +78 -0
  43. package/mod.js.map +1 -0
  44. package/mod.ts +153 -0
  45. package/outbound.js +170 -0
  46. package/outbound.js.map +1 -0
  47. package/outbound.ts +221 -0
  48. package/outbox.js +281 -0
  49. package/outbox.js.map +1 -0
  50. package/outbox.ts +343 -0
  51. package/pace.js +96 -0
  52. package/pace.js.map +1 -0
  53. package/pace.ts +91 -0
  54. package/package.json +32 -4
  55. package/port.js +128 -0
  56. package/port.js.map +1 -0
  57. package/port.ts +176 -0
  58. package/rebase.js +93 -0
  59. package/rebase.js.map +1 -0
  60. package/rebase.ts +77 -0
  61. package/revision.js +104 -0
  62. package/revision.js.map +1 -0
  63. package/revision.ts +146 -0
  64. package/saying.js +62 -0
  65. package/saying.js.map +1 -0
  66. package/saying.ts +69 -0
  67. package/socket.js +694 -0
  68. package/socket.js.map +1 -0
  69. package/socket.ts +927 -0
  70. package/sync.js +542 -0
  71. package/sync.js.map +1 -0
  72. package/sync.ts +705 -0
  73. package/tier.js +176 -0
  74. package/tier.js.map +1 -0
  75. package/tier.ts +211 -0
package/socket.ts ADDED
@@ -0,0 +1,927 @@
1
+ // The receiving side: one WebSocket, the subscriptions held open across it,
2
+ // and the reconnect that opens them again.
3
+ //
4
+ // A socket dies for reasons that have nothing to do with the client — a laptop
5
+ // lid, a deploy, a proxy timeout — so "connected" is a state this module keeps
6
+ // track of rather than something the caller checks. There is one reconnect
7
+ // timer per instance: a second one turns a server that is merely slow into a
8
+ // client that hammers it, which is how a wedged server stays wedged.
9
+ //
10
+ // Reopening is not the same as never having disconnected. The server tracks
11
+ // each subscription's membership per connection, so a subscription opened again
12
+ // answers with the set as it stands and reports nothing about what left while
13
+ // the client was away. This module therefore tracks each subscription's members
14
+ // itself and treats the first frame after a reopen as a reset: whatever it was
15
+ // holding and did not hear about again is reported as gone. The relayed values
16
+ // this side is saying are said again first, since the server held them under
17
+ // the connection that closed.
18
+ //
19
+ // A connection can also die without closing: a laptop that sleeps or loses
20
+ // its network leaves a socket that reads as open and never hears another
21
+ // word. So every open socket is asked the time (its clock probe, which the
22
+ // server answers outside its frame queue), and one that has said nothing for
23
+ // `quiet` after being asked is given up and replaced, as if it had closed.
24
+ //
25
+ // So a drop the wire comes back from is recovered, not lost: once the socket
26
+ // is open again and every subscription has been answered again (the set as it
27
+ // now stands, or a refusal, which is said on its own), nothing was missed.
28
+ // Only a drop that has not recovered `most` after it began is a failure, and
29
+ // only while this machine reaches the server: one with no network has no
30
+ // server to fail it, and when its network comes back the wire reopens at once.
31
+ // A machine can also have a network that reaches nothing (a laptop changing
32
+ // networks, a route that went away), which the browser still calls online. So
33
+ // before a socket that never reopened is said, the server is asked over HTTP
34
+ // whether it answers at all: a server that answers anything, even a refusal,
35
+ // is there and the socket is failing; one that does not answer is out of this
36
+ // machine's reach, and what follows is timed afresh.
37
+
38
+ import type { Bundle, Eid } from 'jsr:@yaks/graph@0.2.36'
39
+ import { after, heard } from '@yaks/fp'
40
+ import { mask } from '@yaks/query'
41
+ import { decode, stringify, unpack } from '@yaks/vocab/wire'
42
+ import type { Vocab } from 'jsr:@yaks/vocab@0.2.36'
43
+ import { coalesced } from '@yaks/graph/bundle'
44
+ import { rayOf, SOCKET_ATTEMPT } from '@yaks/trace/browser'
45
+ import type { Coverage } from './coverage.ts'
46
+ import { clock } from './clock.js'
47
+ import { type Revision, revisions, type Verdict } from './revision.js'
48
+ import type { Fetch } from './outbound.ts'
49
+
50
+ /** The part of a WebSocket this package uses. The standard `WebSocket`
51
+ * satisfies it, and so does any stand-in a test or a caller provides. */
52
+ export type Socket = {
53
+ /** `0` connecting, `1` open, `2` closing, `3` closed */
54
+ readyState: number
55
+ /** bytes already handed to the transport but not yet sent */
56
+ bufferedAmount?: number
57
+ /** send one frame, already serialized */
58
+ send(data: string): void
59
+ /** close the connection, saying why with a close code */
60
+ close(code?: number): void
61
+ /** listen for `open`, `message`, `close` and `error` */
62
+ addEventListener(
63
+ type: string,
64
+ listener: (event: Event & { data?: unknown }) => void,
65
+ ): void
66
+ }
67
+
68
+ /** How a socket is made: the `WebSocket` constructor, or a stand-in with the
69
+ * same call shape. */
70
+ export type Connect = (url: string) => Socket
71
+
72
+ /** How a retry is scheduled. Defaults to `setTimeout`; a test passes its own
73
+ * and fires the reconnect when it wants one. */
74
+ export type Timer = (fn: () => void, ms: number) => void
75
+
76
+ /** Whether this machine has a network, and how to hear that it has one again.
77
+ * A browser says both, with `navigator.onLine` and the `online` event, and is
78
+ * the default; a runtime that says neither is always online. */
79
+ export type Network = {
80
+ /** false while this machine has no network at all */
81
+ online: () => boolean
82
+ /** call `fn` each time the network comes back; returns its removal */
83
+ back: (fn: () => void) => () => void
84
+ }
85
+
86
+ /** What a subscriber asks for: a query, or `true` for the raw feed of every
87
+ * committed write. */
88
+ export type Ask = string | true
89
+
90
+ /** One push from the server: the entities now in the set, the ones that left
91
+ * it, or the refusal that closed the subscription. */
92
+ export type Frame = {
93
+ /** A host can attach display names for referenced people. */
94
+ refs?: string[]
95
+ names?: Record<string, string>
96
+ /** an opted-in subscriber echoes this after applying the frame */
97
+ ack?: string
98
+ transient?: import('jsr:@yaks/graph@0.2.36').TransientFrame[]
99
+ transientReset?: string[]
100
+ /** the subscription this frame answers */
101
+ id: string
102
+ /** the store's revision its rows were read at (./revision.ts) */
103
+ revision?: Revision
104
+ /** the revision its subscription's frame before it said */
105
+ since?: Revision
106
+ /** the entities now in the set (whole rows, unless `coverage` says what
107
+ * each answers for), or, for a raw feed, the bundles as applied */
108
+ bundles?: Bundle[]
109
+ /** Per-row coverage for result bundles. Omitted entries are full rows. Each delivery
110
+ * replaces that role's coverage. Adapters must repeat projected coverage on
111
+ * deltas, including exclusions for deliberately omitted bodies. */
112
+ coverage?: Record<Eid, Coverage>
113
+ /** Rider coverage, independent even when an eid has both roles in a frame.
114
+ * Omitted entries cover only delivered properties. */
115
+ peerCoverage?: Record<Eid, Coverage>
116
+ /** Payload riders, pinned by this subscription but never query members:
117
+ * the entities a `.fields` projection's paths reach (@yaks/api). */
118
+ peers?: Bundle[]
119
+ /** Rider departures, independent of result membership. reset replaces both. */
120
+ peerGone?: Eid[]
121
+ /** entities that left the set — deleted, or no longer matching */
122
+ gone?: Eid[]
123
+ /**
124
+ * `sync: peers` components the server is relaying: somebody's cursor, a
125
+ * caret, a presence dot. The server keeps none of it, and a client holds it
126
+ * in its graph's memory until it is cleared: a value cleared by its writer —
127
+ * or by that writer's connection closing — arrives as the component set to
128
+ * `null`.
129
+ *
130
+ * Not to be confused with `peers` above, the payload riders. The two are
131
+ * unrelated; this one carries the `sync: peers` components.
132
+ */
133
+ relay?: Bundle[]
134
+ /** why the subscription was refused, when it was */
135
+ refused?: { error: string; message: string; [k: string]: unknown }
136
+ /** an aggregate query's answer, in place of bundles: `.count`,
137
+ * `.distinct=prop` and `.tally=prop` (@yaks/api) */
138
+ count?: number
139
+ distinct?: string[]
140
+ tally?: Record<string, number>
141
+ /** the first frame after a reopen: the set as it now stands, whole */
142
+ reset?: boolean
143
+ }
144
+
145
+ /** The socket's half of a sync: what it has to be told, and what it reports. */
146
+ export type WireOpts = {
147
+ /** Interpret binary properties only when their vocabulary declares them. */
148
+ vocab?: Vocab
149
+ /** Decode a packet when the vocabulary must be loaded on demand. */
150
+ decode?: (
151
+ value: unknown,
152
+ payload?: Uint8Array,
153
+ text?: string,
154
+ ) => unknown | Promise<unknown>
155
+ /** Resend connection-owned values after the server restores a connection. */
156
+ resay?: () => void
157
+ /** the server's base URL — `https://…` or `http://…` */
158
+ url: string
159
+ /** the socket constructor (default: the global `WebSocket`) */
160
+ connect?: Connect
161
+ /** Local epoch milliseconds for clock measurements (default: a monotonic epoch). */
162
+ time?: () => number
163
+ /** how a reconnect is scheduled (default: `setTimeout`) */
164
+ timer?: Timer
165
+ /** the reconnect delay in ms after a failed attempt, doubling to `most`
166
+ * (default: 250), each drawn between half of it and all of it */
167
+ wait?: number
168
+ /** how long in ms a connection holds before its loss starts the backoff
169
+ * again rather than going on with it (default: 10_000) */
170
+ held?: number
171
+ /** the window in ms a connection that held is opened again within, at a
172
+ * moment drawn at random in it (default: 1_000) */
173
+ spread?: number
174
+ /** each draw in [0, 1) a reconnect's moment is taken from (default:
175
+ * `Math.random`) */
176
+ random?: () => number
177
+ /** the longest reconnect delay in ms, and how long an outage may go
178
+ * unresumed before it is reported (default: 30_000) */
179
+ most?: number
180
+ /** how long in ms an open socket may say nothing after its clock probe,
181
+ * and a new one wait on its handshake, before it is given up as dead and
182
+ * replaced (default: 10_000) */
183
+ quiet?: number
184
+ /** whether this machine has a network (default: the browser's say, where
185
+ * there is one) */
186
+ network?: Network
187
+ /** how the server is asked whether it answers at all, before a socket that
188
+ * never reopened is said dropped (default: the global `fetch`) */
189
+ fetch?: Fetch
190
+ /** each frame, once the reset bookkeeping has been done for it */
191
+ land: (frame: Frame) => unknown | Promise<unknown>
192
+ /** a subscription needs a fresh answer: opened, re-pointed or disconnected */
193
+ pending?: (id: string) => void
194
+ /** the `sync: peers` values this side is saying, said again on every
195
+ * connection before its subscriptions (./saying.ts) */
196
+ again?: () => Bundle[]
197
+ /** anything that went wrong on the socket */
198
+ report: (err: unknown) => void
199
+ }
200
+
201
+ /** One page's tab: whether it is visible, focused, and idle. */
202
+ export type Tab = { visible: boolean; focused: boolean; idle?: boolean }
203
+
204
+ /** A live WebSocket with subscriptions held open on it. */
205
+ export type Wire = {
206
+ /** open the socket if it is not already opening or open */
207
+ open: () => void
208
+ /** subscribe (or re-point an existing id); returns the id */
209
+ subscribe: (query: Ask, id?: string) => string
210
+ /** drop one subscription */
211
+ unsubscribe: (id: string) => void
212
+ /** ask a subscription again, whole: what it holds stays until the answer
213
+ * replaces it, and its frames still on their way from before are let go */
214
+ ask: (id: string) => void
215
+ /**
216
+ * Send `sync: peers` components to the server to relay. It is the only write
217
+ * sent over the socket rather than posted, and it goes here because its
218
+ * lifetime is this socket's: the server holds it under this connection and
219
+ * clears it when the connection closes. A relay message sent while the socket
220
+ * is down is dropped, never queued: there is no backlog worth replaying, and
221
+ * the next connection is told what is being said as it stands (`again`).
222
+ */
223
+ relay: (bundles: Bundle[]) => void
224
+ /** Say whether this page's tab is visible and focused, which is where its
225
+ * person is (@yaks/notify/whereabouts). Said now when the socket is open,
226
+ * and again on every connection; it never opens one. */
227
+ tab: (tab: Tab) => void
228
+ /** Store epoch milliseconds; first use opens the socket. Every open socket
229
+ * calibrates; until the first reply this is the local epoch, and across
230
+ * outages it holds the offset. */
231
+ now: () => number
232
+ /** whether the socket is open right now */
233
+ connected: () => boolean
234
+ /** be called with true each time the socket opens, and with false each
235
+ * time an open one closes under it; not called immediately. The returned
236
+ * function removes the listener. */
237
+ onConnection: (fn: (open: boolean) => void) => () => void
238
+ /** open a new socket in place of the one open now, at once and with no
239
+ * outage: the server said its address now reaches another store
240
+ * (outbound.ts `MOVED`), which the new socket subscribes to afresh */
241
+ reopen: () => void
242
+ /** close the socket and stop reconnecting */
243
+ close: () => void
244
+ }
245
+
246
+ /** A connection that closed under this wire and has not resumed `most` after
247
+ * it began: what closed it (its close code, when it gave one) and how long it
248
+ * has been down. Resumed is open again with every subscription answered again,
249
+ * so a drop that resumes in time, whatever its close code (a restart, a proxy
250
+ * reloading, a laptop waking), is the system working and is never said. Said
251
+ * once per outage, while it lasts, and never while this machine has no
252
+ * network. Its `cause` says what it was waiting on: a socket that never
253
+ * reopened, or the queries a reopened one has not had answered. */
254
+ export class Dropped extends Error {
255
+ constructor(
256
+ url: string,
257
+ code: number | undefined,
258
+ ms: number,
259
+ waiting?: string,
260
+ ) {
261
+ super(
262
+ `${url} closed${code ? ` (${code})` : ''} and has not resumed after ${
263
+ secs(ms)
264
+ }`,
265
+ waiting ? { cause: waiting } : undefined,
266
+ )
267
+ this.name = 'Dropped'
268
+ }
269
+ }
270
+
271
+ let secs = (ms: number) => `${(ms / 1000).toFixed(1)} s`
272
+
273
+ /** The next reconnect delay: double it, but never past the ceiling. */
274
+ export let backoff = (wait: number, most: number): number =>
275
+ Math.min(wait * 2, most)
276
+
277
+ // `https://shelf.example/api` → `wss://shelf.example/api/ws`. The socket is
278
+ // served from the same origin as the HTTP routes, so only the scheme changes.
279
+ let httpUrl = (url: string): string => `${url.replace(/\/$/, '')}/ws`
280
+ let wsUrl = (url: string): string => httpUrl(url).replace(/^http/, 'ws')
281
+
282
+ let unpacked = (
283
+ data: unknown,
284
+ ): { value: unknown; text?: string; payload?: Uint8Array } => {
285
+ if (data instanceof ArrayBuffer || data instanceof Uint8Array) {
286
+ return unpack(data)
287
+ }
288
+ let text = String(data)
289
+ return { text, value: JSON.parse(text) }
290
+ }
291
+
292
+ // What a subscription says beside its query: acks, grouped frames, and in a
293
+ // browser the page asking, which a failure its reads meet names.
294
+ let asking = () => {
295
+ let page = (globalThis as { document?: Document }).document?.location
296
+ ?.pathname
297
+ return { acks: true, frames: true, ...(page && { page }) }
298
+ }
299
+
300
+ let OPEN = 1
301
+ let BUFFER = 8 * 1024
302
+
303
+ let global = (): Connect | undefined => {
304
+ let W = (globalThis as { WebSocket?: new (url: string) => Socket }).WebSocket
305
+ return W && ((url) => new W(url))
306
+ }
307
+
308
+ // The browser's say on whether this machine has a network: `navigator.onLine`
309
+ // is false only when it has none, and `online` fires when one comes back.
310
+ let browser = (): Network => {
311
+ let g = globalThis as {
312
+ navigator?: { onLine?: boolean }
313
+ addEventListener?: (type: string, fn: () => void) => void
314
+ removeEventListener?: (type: string, fn: () => void) => void
315
+ }
316
+ return {
317
+ online: () => g.navigator?.onLine !== false,
318
+ back: (fn) => {
319
+ g.addEventListener?.('online', fn)
320
+ return () => g.removeEventListener?.('online', fn)
321
+ },
322
+ }
323
+ }
324
+
325
+ /** An outage: when it began, what closed it, the attempts made since, and
326
+ * when a socket last opened during it, while that one is still open. */
327
+ type Outage = {
328
+ at: number
329
+ code?: number
330
+ tries: number
331
+ opened?: number
332
+ unreadable?: boolean
333
+ recent?: Attempt[]
334
+ }
335
+
336
+ type Attempt = {
337
+ id: string
338
+ at: number
339
+ opened?: number
340
+ ended?: string
341
+ }
342
+
343
+ /**
344
+ * The socket half of a sync: subscriptions that survive a disconnection, one
345
+ * reconnect timer, and a reset frame after each reopen so a client can work out
346
+ * what left the set while it was away.
347
+ */
348
+ export let wire = (opts: WireOpts): Wire => {
349
+ let connect = opts.connect ?? global()
350
+ let identify = typeof document != 'undefined'
351
+ ? () => globalThis.crypto?.randomUUID?.()
352
+ : undefined
353
+ let timer = opts.timer ?? ((fn, ms) => setTimeout(fn, ms))
354
+ let first = opts.wait ?? 250
355
+ let steady = opts.held ?? 10_000
356
+ let spread = opts.spread ?? 1_000
357
+ let random = opts.random ?? Math.random
358
+ let most = opts.most ?? 30_000
359
+ let quiet = opts.quiet ?? 10_000
360
+ let network = opts.network ?? browser()
361
+ let fetch = opts.fetch ?? (globalThis.fetch && ((r) => globalThis.fetch(r)))
362
+
363
+ let asks = new Map<string, Ask>() // what each subscription asked for
364
+ let tab: Tab | undefined // what this page last said of its tab
365
+ let refused = new Set<string>() // terminal until explicitly re-pointed
366
+ let members = new Map<string, Set<Eid>>() // who is in each set
367
+ let resetting = new Set<string>() // ids whose next frame is a reset
368
+ let revised = revisions() // of each row and subscription heard
369
+ let socket: Socket | null = null
370
+ let spoke = 0 // when the open socket last said anything
371
+ let words = 0 // how many messages it has said
372
+ let hangUp = () => {} // give the open socket up as dead
373
+ let wait = first
374
+ let retrying = false // the one timer — never a second
375
+ let turn = 0 // the timer that is live; a network coming back retires it
376
+ let closed = false
377
+ // The outage under way, from the first close until the wire resumes: an
378
+ // open socket closing, or an attempt failing, starts one, and one still
379
+ // here `most` later is said (`Dropped`).
380
+ let down: Outage | undefined
381
+ let hearing = new Set<(open: boolean) => void>()
382
+ let say = (open: boolean) => {
383
+ for (let fn of hearing) fn(open)
384
+ }
385
+ let n = 0
386
+ let waiting: Bundle[] = []
387
+ let draining = false
388
+ let agreed = clock(opts.time)
389
+ let timing = false
390
+ let trip: number | undefined
391
+ let rounds = 0
392
+ let clockGeneration = 0
393
+ let clockTimers = new Set<ReturnType<typeof setTimeout>>()
394
+ let stopClock = () => {
395
+ clockGeneration++
396
+ for (let t of clockTimers) clearTimeout(t)
397
+ clockTimers.clear()
398
+ trip = undefined
399
+ }
400
+ let later = (fn: () => void, ms: number) => {
401
+ if (opts.timer) return opts.timer(fn, ms)
402
+ let t = setTimeout(() => {
403
+ clockTimers.delete(t)
404
+ fn()
405
+ }, ms)
406
+ clockTimers.add(t)
407
+ }
408
+ // A deadline on the server in time this thread could hear it (@yaks/fp
409
+ // `heard`), on `set`'s timers, beating only while it is still `owed`.
410
+ let within = (
411
+ ms: number,
412
+ owed: () => boolean,
413
+ lapse: () => void,
414
+ set: Timer = timer,
415
+ ) =>
416
+ heard(ms, lapse, {
417
+ now: agreed.read,
418
+ after: (ms, fn) => (set(() => owed() && fn(), ms), () => {}),
419
+ })
420
+ // The time, asked of every open socket: its answer calibrates the clock,
421
+ // and a socket that has said nothing `quiet` after it was asked is dead.
422
+ let probe = () => {
423
+ if (closed || socket?.readyState != OPEN) return
424
+ let before = words
425
+ trip = agreed.read()
426
+ send({ clock: trip })
427
+ let generation = clockGeneration
428
+ later(() => {
429
+ if (generation == clockGeneration) probe()
430
+ }, rounds++ < 7 ? 1000 : 30_000)
431
+ within(
432
+ quiet,
433
+ () => generation == clockGeneration && words == before,
434
+ hangUp,
435
+ later,
436
+ )
437
+ }
438
+
439
+ let send = (msg: unknown) => {
440
+ if (socket && socket.readyState == OPEN) socket.send(stringify(msg))
441
+ }
442
+ let flush = () => {
443
+ if (!waiting.length) return
444
+ if (!socket || socket.readyState != OPEN) {
445
+ waiting = []
446
+ return
447
+ }
448
+ if ((socket.bufferedAmount ?? 0) >= BUFFER) {
449
+ schedule()
450
+ return
451
+ }
452
+ let bundles = waiting
453
+ waiting = []
454
+ send({ relay: bundles })
455
+ }
456
+ let schedule = () => {
457
+ if (draining) return
458
+ draining = true
459
+ timer(() => {
460
+ draining = false
461
+ flush()
462
+ }, 16)
463
+ }
464
+
465
+ // An outage still under way `most` after it began is a failure, said once,
466
+ // unless this machine has no network: then it is the machine's, and the
467
+ // network coming back times what follows afresh. `most` is time this thread
468
+ // could hear the server in: one that stalls is dropped by the server and
469
+ // then reopens and reads its answers late, its own doing, not the server's.
470
+ let overdue = (outage: Outage) =>
471
+ within(most, () => down === outage && !closed, async () => {
472
+ if (!network.online()) return
473
+ let http = outage.opened === undefined ? await reaches() : undefined
474
+ if (http === false) {
475
+ if (down !== outage || closed) return
476
+ down = { ...outage, at: agreed.read(), tries: 0 }
477
+ return overdue(down)
478
+ }
479
+ if (down !== outage || closed) return
480
+ let ms = agreed.read() - outage.at
481
+ let waiting = waited(outage)
482
+ if (outage.unreadable) {
483
+ waiting = `received an unreadable WebSocket message; ${waiting}`
484
+ }
485
+ let attempts = outage.recent?.map(({ id, at, opened, ended }) =>
486
+ `${id} at ${secs(at - outage.at)}: ${
487
+ opened == null ? 'handshake' : `open after ${secs(opened - at)}`
488
+ }, ${ended ?? 'waiting'}`
489
+ )
490
+ opts.report(
491
+ new Dropped(
492
+ wsUrl(opts.url),
493
+ outage.code,
494
+ ms,
495
+ [waiting, http, ...(attempts ?? [])].filter(Boolean).join('; '),
496
+ ),
497
+ )
498
+ })
499
+
500
+ // Whether the server answers this machine over HTTP within `quiet`: any
501
+ // answer, a refusal included, says it is there. A runtime with no `fetch`
502
+ // cannot ask, and takes the server to be there.
503
+ let reaches = async (): Promise<false | string | undefined> => {
504
+ if (!fetch) return
505
+ try {
506
+ let res = await fetch(
507
+ new Request(httpUrl(opts.url), { signal: AbortSignal.timeout(quiet) }),
508
+ )
509
+ let ray = rayOf(res.headers.get('cf-ray'))
510
+ await res.body?.cancel()
511
+ return `HTTP probe returned ${res.status}${ray ? ` (ray ${ray})` : ''}`
512
+ } catch {
513
+ return false
514
+ }
515
+ }
516
+
517
+ // What an overdue outage waits on: a socket that never reopened, or the
518
+ // queries a reopened one has not had answered, the first few masked as a
519
+ // trace keeps them.
520
+ let waited = (outage: Outage): string => {
521
+ if (outage.opened === undefined) {
522
+ let n = outage.tries
523
+ return `it has not reopened: ${n} attempt${n == 1 ? '' : 's'}${
524
+ socket?.readyState == 0 ? ', the last still connecting' : ''
525
+ }`
526
+ }
527
+ let held = [...asks].filter(([id, q]) => q !== true && !refused.has(id))
528
+ let unanswered = held.filter(([id]) => resetting.has(id))
529
+ let some = unanswered.slice(0, 3).map(([, q]) =>
530
+ mask(String(q)).slice(0, 200)
531
+ )
532
+ return `it reopened after ${
533
+ secs(outage.opened - outage.at)
534
+ }, and ${unanswered.length} of ${held.length} queries are not answered again: ${
535
+ some.join(', ')
536
+ }${unanswered.length > some.length ? ', …' : ''}; the server last spoke ${
537
+ secs(agreed.read() - spoke)
538
+ } ago`
539
+ }
540
+
541
+ // Open, and every query answered since, with the set as it now stands or a
542
+ // refusal: the outage is over, and no change in it was missed. A raw feed
543
+ // has no set to answer with, and holds nothing up.
544
+ let resume = () => {
545
+ if (!down || socket?.readyState != OPEN) return
546
+ for (let id of resetting) {
547
+ if (asks.get(id) !== true && !refused.has(id)) return
548
+ }
549
+ down = undefined
550
+ }
551
+
552
+ // A frame that must not land (./revision.ts): its subscription is asked
553
+ // again, whole, its set kept so the answer can say what left it. One sent
554
+ // before the asking is let go; a frame missed is the server's failure.
555
+ let again = (id: string, why: Verdict) => {
556
+ if (why == 'asked') return
557
+ if (why == 'skipped') {
558
+ opts.report(new Error(`a frame of subscription ${id} never arrived`))
559
+ }
560
+ ask(id)
561
+ }
562
+ let ask = (id: string) => {
563
+ let query = asks.get(id)
564
+ if (query === undefined || refused.has(id)) return
565
+ revised.asked(id)
566
+ resetting.add(id)
567
+ send({ subscribe: query, id, ...asking() })
568
+ }
569
+
570
+ // A frame, with the reopen bookkeeping done: a reset frame reports whatever
571
+ // the client was holding and did not hear about again as gone, and every
572
+ // frame keeps the membership set current so the next reset can do the same.
573
+ let landed = (frame: Frame): unknown | Promise<unknown> => {
574
+ // An unsubscribe can race a frame already in transit. It must not refill
575
+ // the cache or recreate membership bookkeeping after its last owner left.
576
+ if (frame.refused) {
577
+ if (asks.has(frame.id)) {
578
+ let ms = (frame.refused.retry as { after?: number } | undefined)?.after
579
+ if (ms && ms > 0) {
580
+ let query = asks.get(frame.id)
581
+ timer(() => {
582
+ if (asks.get(frame.id) === query) ask(frame.id)
583
+ }, ms)
584
+ return
585
+ }
586
+ refused.add(frame.id)
587
+ resume()
588
+ return opts.land(frame)
589
+ }
590
+ // A malformed or relay request may have no subscription id at all.
591
+ let error = new Error(frame.refused.message)
592
+ error.name = frame.refused.error
593
+ opts.report(error)
594
+ return
595
+ }
596
+ if (!asks.has(frame.id)) return
597
+ let wrong = revised.check(frame)
598
+ if (wrong) return again(frame.id, wrong)
599
+ revised.landed(frame)
600
+ refused.delete(frame.id)
601
+ let set = members.get(frame.id) ?? new Set<Eid>()
602
+ members.set(frame.id, set)
603
+ let gone = [...(frame.gone ?? [])]
604
+ let arrived = (frame.bundles ?? []).map((b) => b.entity.eid)
605
+ if (!frame.refused && (resetting.delete(frame.id) || frame.reset)) {
606
+ let seen = new Set(arrived)
607
+ for (let eid of set) if (!seen.has(eid)) gone.push(eid)
608
+ set.clear()
609
+ frame = { ...frame, reset: true }
610
+ }
611
+ for (let eid of arrived) set.add(eid)
612
+ for (let eid of gone) set.delete(eid)
613
+ resume()
614
+ return opts.land({ ...frame, gone })
615
+ }
616
+
617
+ // `held`: the connection that dropped had held for a while, which is what a
618
+ // server handing over to its replacement looks like, so the next one opens
619
+ // within `spread`, at a moment drawn at random: a deploy drops every page's
620
+ // socket at once, and they come back spread out rather than together. A
621
+ // connection that fails, or drops before it held, waits out the backoff,
622
+ // each wait drawn too, so a server that accepts and hangs up is never
623
+ // hammered, and pages that failed together do not try again together.
624
+ let retry = (held = false) => {
625
+ if (closed || retrying) return
626
+ let ms = held ? random() * spread : wait * (1 + random()) / 2
627
+ if (!held) wait = backoff(wait, most)
628
+ if (ms <= 0) return open()
629
+ retrying = true
630
+ let mine = ++turn
631
+ timer(() => {
632
+ if (mine != turn) return
633
+ retrying = false
634
+ open()
635
+ }, ms)
636
+ }
637
+
638
+ // The network is back, so the outage so far was this machine's: the wire
639
+ // tries again at once from the first delay, and times what follows afresh.
640
+ let stopBack = network.back(() => {
641
+ if (closed || !down) return
642
+ let now = agreed.read()
643
+ down = {
644
+ ...down,
645
+ at: now,
646
+ tries: 0,
647
+ opened: socket?.readyState == OPEN ? now : undefined,
648
+ }
649
+ overdue(down)
650
+ turn++
651
+ retrying = false
652
+ wait = first
653
+ open()
654
+ })
655
+
656
+ let open = () => {
657
+ if (closed || !connect) return
658
+ if (socket && socket.readyState <= OPEN) return
659
+ if (down) down.tries++
660
+ let id = down && identify?.()
661
+ let attempt = id ? { id, at: agreed.read() } as Attempt : undefined
662
+ let address = wsUrl(opts.url)
663
+ if (attempt && down) {
664
+ let url = new URL(address)
665
+ url.searchParams.set(SOCKET_ATTEMPT, attempt.id)
666
+ address = url.href
667
+ down.recent = [...(down.recent ?? []).slice(-3), attempt]
668
+ }
669
+ let s = connect(address)
670
+ socket = s
671
+ let opened: number | undefined
672
+ s.addEventListener('open', () => {
673
+ if (socket != s || closed) return
674
+ opened = agreed.read()
675
+ if (attempt) attempt.opened = opened
676
+ if (down) down.opened = opened
677
+ waiting = []
678
+ spoke = opened
679
+ hangUp = () => {
680
+ if (socket != s) return
681
+ lost(undefined, 'clock response timed out')
682
+ s.close()
683
+ }
684
+ agreed.reset()
685
+ rounds = 0
686
+ probe()
687
+ // Said before anything is asked, so no answer hands back an older copy.
688
+ let said = opts.again?.() ?? []
689
+ if (said.length) s.send(stringify({ relay: said }))
690
+ if (tab) s.send(stringify({ tab }))
691
+ for (let [id, query] of asks) {
692
+ if (refused.has(id)) continue
693
+ resetting.add(id) // its answer will be the whole set, as it now stands
694
+ revised.asked(id)
695
+ s.send(stringify({ subscribe: query, id, ...asking() }))
696
+ }
697
+ resume() // at once, when nothing is asked
698
+ say(true)
699
+ })
700
+ let inbox: Frame[] = []
701
+ let landing = false
702
+ let ack = (frame: Frame) => {
703
+ if (frame.ack && socket == s && s.readyState == OPEN) {
704
+ s.send(stringify({ ack: frame.ack }))
705
+ }
706
+ }
707
+ let drain = () => {
708
+ if (landing || socket != s || closed) return
709
+ while (inbox.length) {
710
+ let frame = inbox.shift()!
711
+ try {
712
+ let out = landed(frame)
713
+ if (out instanceof Promise) {
714
+ landing = true
715
+ out.then(() => {
716
+ ack(frame)
717
+ landing = false
718
+ drain()
719
+ }, (err) => {
720
+ opts.report(err)
721
+ ack(frame)
722
+ landing = false
723
+ drain()
724
+ })
725
+ return
726
+ }
727
+ ack(frame)
728
+ } catch (err) {
729
+ opts.report(err)
730
+ ack(frame)
731
+ }
732
+ }
733
+ }
734
+ let packetOf = (value: unknown) => {
735
+ if (socket != s || closed) return
736
+ if (value && typeof value == 'object' && 'clock' in value) {
737
+ if (
738
+ trip !== undefined && value.clock === trip &&
739
+ 'received' in value && typeof value.received == 'number' &&
740
+ 'sent' in value && typeof value.sent == 'number'
741
+ ) {
742
+ agreed.sample(trip, value.received, value.sent)
743
+ trip = undefined
744
+ }
745
+ return
746
+ }
747
+ if (value && typeof value == 'object' && 'resay' in value) {
748
+ if (value.resay) opts.resay?.()
749
+ return
750
+ }
751
+ let packet = value as
752
+ | Frame
753
+ | { frames: Frame[]; ack?: string }
754
+ if ('frames' in packet) {
755
+ if (!Array.isArray(packet.frames) || !packet.frames.length) {
756
+ throw new SyntaxError('expected nonempty frames')
757
+ }
758
+ inbox.push(...packet.frames.map((frame, i) => ({
759
+ ...frame,
760
+ ack: i == packet.frames.length - 1 ? packet.ack : undefined,
761
+ })))
762
+ } else inbox.push(packet)
763
+ drain()
764
+ }
765
+ let unreadable = () => {
766
+ if (socket != s || closed) return
767
+ // A missing packet can carry the ACK and any of the subscriptions.
768
+ // Reconnect to ask for whole answers while keeping the painted rows.
769
+ lost(undefined, 'unreadable message')
770
+ s.close()
771
+ }
772
+ let message = (data: unknown) => {
773
+ if (socket != s || closed) return
774
+ let packet
775
+ try {
776
+ packet = unpacked(data)
777
+ } catch {
778
+ return unreadable()
779
+ }
780
+ let { text, value, payload } = packet
781
+ try {
782
+ if (opts.decode) {
783
+ return after(opts.decode(value, payload, text), packetOf)
784
+ }
785
+ packetOf(
786
+ opts.vocab ? decode(opts.vocab, value, payload) : value,
787
+ )
788
+ } catch (err) {
789
+ opts.report(err)
790
+ }
791
+ }
792
+ let pending: Promise<void> | undefined
793
+ s.addEventListener('message', (e) => {
794
+ if (socket == s) spoke = agreed.read(), words++
795
+ if (e.data instanceof Blob || pending) {
796
+ let data = e.data
797
+ pending = (pending ?? Promise.resolve()).then(() =>
798
+ data instanceof Blob
799
+ ? data.arrayBuffer().then(message, unreadable)
800
+ : message(data)
801
+ ).catch(opts.report).finally(() => {
802
+ if (pending === next) pending = undefined
803
+ })
804
+ let next = pending
805
+ } else {
806
+ let result = message(e.data)
807
+ if (result instanceof Promise) {
808
+ let next = pending = result.catch(opts.report).finally(() => {
809
+ if (pending === next) pending = undefined
810
+ })
811
+ }
812
+ }
813
+ })
814
+ // The socket is gone: it closed, or it stopped answering and was given up.
815
+ let lost = (code?: number, ended?: string) => {
816
+ if (socket != s) return
817
+ if (attempt) attempt.ended = ended ?? `closed (${code ?? 'no code'})`
818
+ socket = null
819
+ // An open socket closing begins an outage, and so does a failed
820
+ // attempt, which is its first.
821
+ let outage: Outage = down ?? {
822
+ at: agreed.read(),
823
+ code,
824
+ tries: opened === undefined ? 1 : 0,
825
+ }
826
+ let begun = outage !== down
827
+ outage.opened = undefined
828
+ if (ended == 'unreadable message') outage.unreadable = true
829
+ down = outage
830
+ stopClock()
831
+ waiting = []
832
+ inbox = []
833
+ // A connection that held for a while restarts the backoff, and the
834
+ // next one is on its way before the page hears of the loss; one that
835
+ // failed, or dropped as soon as it opened, keeps backing off.
836
+ let held = opened !== undefined && agreed.read() - opened >= steady
837
+ if (held) wait = first
838
+ retry(held)
839
+ if (begun) overdue(outage)
840
+ for (let id of asks.keys()) {
841
+ if (!refused.has(id)) opts.pending?.(id)
842
+ }
843
+ if (opened !== undefined) say(false)
844
+ }
845
+ s.addEventListener('close', (e) => lost((e as CloseEvent).code))
846
+ // A handshake the network holds unanswered can wait minutes before the
847
+ // socket says it failed: one still connecting `quiet` after it was made
848
+ // is given up as a failed attempt, and the next is made after its wait.
849
+ within(quiet, () => socket == s && s.readyState == 0, () => {
850
+ lost(undefined, 'handshake timed out')
851
+ s.close()
852
+ }, later)
853
+ }
854
+
855
+ return {
856
+ open,
857
+ subscribe: (query, id) => {
858
+ if (closed) throw new Error('wire is closed')
859
+ let key = id ?? `s${++n}`
860
+ refused.delete(key)
861
+ asks.set(key, query)
862
+ members.set(key, new Set())
863
+ resetting.add(key)
864
+ revised.asked(key)
865
+ opts.pending?.(key)
866
+ open()
867
+ send({ subscribe: query, id: key, ...asking() })
868
+ return key
869
+ },
870
+ ask,
871
+ unsubscribe: (id) => {
872
+ asks.delete(id)
873
+ refused.delete(id)
874
+ members.delete(id)
875
+ resetting.delete(id)
876
+ revised.closed(id)
877
+ send({ unsubscribe: id })
878
+ resume()
879
+ },
880
+ tab: (now) => {
881
+ tab = now
882
+ send({ tab })
883
+ },
884
+ relay: (bundles) => {
885
+ if (!bundles.length || !socket || socket.readyState != OPEN) return
886
+ waiting = coalesced([...waiting, ...bundles])
887
+ flush()
888
+ },
889
+ now: () => {
890
+ if (!closed && !timing) {
891
+ timing = true
892
+ open()
893
+ }
894
+ return agreed.now()
895
+ },
896
+ reopen: () => {
897
+ let s = socket
898
+ if (closed || !s) return
899
+ // Every listener on the old socket asks whether it is still the one.
900
+ socket = null
901
+ stopClock()
902
+ waiting = []
903
+ s.close()
904
+ open()
905
+ },
906
+ connected: () => socket?.readyState == OPEN,
907
+ onConnection: (fn) => {
908
+ hearing.add(fn)
909
+ return () => hearing.delete(fn)
910
+ },
911
+ close: () => {
912
+ closed = true
913
+ hearing.clear()
914
+ stopBack()
915
+ stopClock()
916
+ waiting = []
917
+ let s = socket
918
+ socket = null
919
+ for (let id of asks.keys()) opts.pending?.(id)
920
+ asks.clear()
921
+ refused.clear()
922
+ members.clear()
923
+ resetting.clear()
924
+ s?.close()
925
+ },
926
+ }
927
+ }