@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/README.md CHANGED
@@ -1,3 +1,730 @@
1
- # Temporary Holding Version
1
+ # @yaks/sync
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
+ Synchronizes a client graph with a server, applies live query updates, and
4
+ reconciles optimistic writes or reverts them when refused. Use it with
5
+ [@yaks/graph](../graph/README.md#data-model) and a server implementing
6
+ [@yaks/api](../api/README.md).
7
+
8
+ A **Sync** is a graph's connection to a server, returned by `sync()`. It
9
+ registers a [plugin](../graph/README.md#data-model) that posts local
10
+ [bundles](../graph/README.md#data-model) to `/apply` and applies server updates
11
+ received on `/ws`.
12
+
13
+ A Sync holds [subscriptions](../api/README.md#subscriptions) under ids and
14
+ applies their [frames](../api/README.md#subscriptions). A subscription can ask
15
+ for a [query](../query/README.md#query-model) or `true` for the raw stream of
16
+ committed patches.
17
+
18
+ An **optimistic write** is a batch committed locally before the server answers
19
+ it. `report` receives a `Trouble`: the sent bundles,
20
+ [refusal](../api/README.md#refusals-and-request-reports) or transport error, and
21
+ whether the optimistic write was reverted. A subscription the server refuses is
22
+ reported the same way, with no bundles and its id as `subscription`. `Refusal`
23
+ carries the server's `error`, `message`, and optional error-specific fields.
24
+
25
+ ## Install
26
+
27
+ ```sh
28
+ deno add jsr:@yaks/sync jsr:@yaks/graph jsr:@yaks/ram jsr:@yaks/vocab
29
+ # Node projects: npx jsr add @yaks/sync @yaks/graph @yaks/ram @yaks/vocab
30
+ ```
31
+
32
+ ## Connect and write
33
+
34
+ Both HTTP and socket transports can be injected. This example supplies an HTTP
35
+ response in process; no server or network is needed. Applications normally use
36
+ the default global `fetch` and `WebSocket`.
37
+
38
+ ```ts
39
+ import { graph } from '@yaks/graph'
40
+ import { ram } from '@yaks/ram'
41
+ import { loadVocab } from '@yaks/vocab'
42
+ import { sync } from '@yaks/sync'
43
+ import { equal } from '@yaks/testing'
44
+
45
+ const vocab = loadVocab({
46
+ $defs: {
47
+ book: { component: true, properties: { title: { type: 'string' } } },
48
+ },
49
+ })
50
+ const g = graph({ storage: ram(vocab), vocab })
51
+ g.install()
52
+ const link = sync(g, {
53
+ url: 'https://books.example',
54
+ fetch: async (request) => {
55
+ equal(request.method, 'POST')
56
+ equal(new URL(request.url).pathname, '/apply')
57
+ const sent = await request.json()
58
+ equal(sent[0].book, { title: 'Dune' })
59
+ return Response.json([{ entity: { eid: 'b1' }, book: { title: 'DUNE' } }])
60
+ },
61
+ })
62
+ await g.apply([{ entity: { eid: 'b1' }, book: { title: 'Dune' } }])
63
+ equal((await g.get(['b1']))[0].book, { title: 'Dune' })
64
+ await link.idle()
65
+ equal((await g.get(['b1']))[0].book, { title: 'DUNE' })
66
+ link.close()
67
+ ```
68
+
69
+ With synchronous storage and hooks, `apply()` commits locally synchronously.
70
+ Awaiting it does not await the server; `idle()` waits for the queued HTTP
71
+ requests to settle, including failures. Requests are sent serially in local
72
+ commit order. Use [RAM's adoption options](../ram/README.md) when the client
73
+ must accept server-assigned entity numbers.
74
+
75
+ An accepted response contains applied patches, including server-generated
76
+ numbers, stamps, and tombstones, rather than complete snapshots. The Sync
77
+ applies it with `trusted: true` and `replica: true`, excluding components the
78
+ client's vocabulary does not declare. What local rules added to server-stored
79
+ components is undone before that response lands.
80
+
81
+ A refusal reverts the sent properties and everything the write's rules added.
82
+ Caller-written local and peer values stay. A transport failure keeps the local
83
+ batch: the server may have applied it before the connection failed. There is no
84
+ automatic HTTP retry.
85
+
86
+ The refusal and unknown-outcome contracts run in `sync_test.ts`, each with its
87
+ own fixture; this example shows both outcomes together.
88
+
89
+ ```ts ignore
90
+ import { graph } from '@yaks/graph'
91
+ import { ram } from '@yaks/ram'
92
+ import { loadVocab } from '@yaks/vocab'
93
+ import { sync, type Trouble } from '@yaks/sync'
94
+ import { equal } from '@yaks/testing'
95
+
96
+ const vocab = loadVocab({
97
+ $defs: {
98
+ book: { component: true, properties: { title: { type: 'string' } } },
99
+ },
100
+ })
101
+ const g = graph({ storage: ram(vocab), vocab })
102
+ g.install()
103
+ await g.apply([{ entity: { eid: 'b1' }, book: { title: 'Dune' } }])
104
+ const trouble: Trouble[] = []
105
+ let unreachable = false
106
+ const link = sync(g, {
107
+ url: 'https://books.example',
108
+ fetch: () => {
109
+ if (unreachable) throw new Error('connection lost')
110
+ return Response.json({ error: 'Denied', message: 'read only' }, {
111
+ status: 403,
112
+ })
113
+ },
114
+ report: (t) => trouble.push(t),
115
+ })
116
+ await g.apply([{ entity: { eid: 'b1' }, book: { title: 'Changed' } }])
117
+ await link.idle()
118
+ equal((await g.get(['b1']))[0].book, { title: 'Dune' })
119
+ equal(trouble[0].reverted, true)
120
+ unreachable = true
121
+ await g.apply([{ entity: { eid: 'b1' }, book: { title: 'Unconfirmed' } }])
122
+ await link.idle()
123
+ equal((await g.get(['b1']))[0].book, { title: 'Unconfirmed' })
124
+ equal(trouble[1].reverted, false)
125
+ link.close()
126
+ ```
127
+
128
+ A batch containing a deletion waits for the server in its entirety. Its
129
+ page-only and peer components are applied through the local graph only after the
130
+ durable deletion is accepted; peer components then leave over the socket. A
131
+ refusal or unknown outcome applies neither companion. Deletion has no local
132
+ inverse; an accepted response supplies the tombstones. The inverse patches for
133
+ optimistic writes affect touched properties and do not implement general
134
+ conflict resolution for overlapping writes.
135
+
136
+ A batch whose `$was` names an entity this replica doesn't hold waits for the
137
+ server the same way: the page read that entity from the server (a one-time read,
138
+ say), so only the server can judge the precondition. Nothing of the batch is
139
+ applied locally until the server answers, and its answer lands the entity.
140
+
141
+ `apply(bundles)` returns the server-applied bundles while keeping optimistic
142
+ local visibility. It uses the same queue and reconciliation as the plugin's
143
+ background graph writes. A write containing only browser-owned or relayed
144
+ components returns its local result without an HTTP acknowledgement. Deliberate
145
+ refusals reject with `WriteRefused` (`outcome: 'refused'`, `sent`, `refusal`);
146
+ transport or response failures reject with `WriteUnknown` (`outcome: 'unknown'`,
147
+ `sent`, `cause`). An unknown outcome keeps optimistic state because the server
148
+ may have committed. Callers retain their recovery copies while they reconcile or
149
+ retry. See [@yaks/client](../client/README.md#use) for the assembled mutation
150
+ interface.
151
+
152
+ `submit(bundles, key?)` uses the same HTTP queue but waits for the server to
153
+ resolve identity before applying its answer. It rejects on refusal or transport
154
+ failure. Its caller must remove browser-owned components first;
155
+ [@yaks/client](../client/README.md) does this for alias writes. `key` is sent as
156
+ the request's `idempotency-key`: a caller that sends the same batch again after
157
+ a `WriteUnknown` passes the same key, and a server that keeps a write log (a
158
+ yaks.app store) answers the resend as it answered the first instead of taking it
159
+ twice.
160
+
161
+ ## Select outgoing state
162
+
163
+ The vocabulary owns
164
+ [sync, durable, pace, and save](../vocab/README.md#state-lifetimes). `syncOf`
165
+ and `durableOf` are re-exported from that package. This package selects
166
+ components for each transport:
167
+
168
+ | Helper | Result |
169
+ | ------------------------- | -------------------------------------------------------------------------------------------------- |
170
+ | `outbound(vocab, name)` | Whether the component leaves this node (`sync` is not `none`). |
171
+ | `stored(vocab, name)` | Whether stored snapshots include it (`server`, or peers with `save`). |
172
+ | `local(vocab, name)` | `'vault'` for local persistent state, `'memory'` for other local state, `null` for outgoing state. |
173
+ | `outward(bundles, vocab)` | Caller-written server components and writable properties, retaining `$was` and deletion requests. |
174
+ | `inverse(bundles, vocab)` | Patches reverting a refused optimistic write. |
175
+ | `guessed(bundles, vocab)` | Patches undoing local rules' server-stored results before an accepted response. |
176
+
177
+ `local()` describes storage the caller must provide; it neither persists nor
178
+ expires data. Computed and stamped properties are excluded from outgoing writes,
179
+ as are patches added by local rules or later write phases.
180
+
181
+ The helpers recognize caller-written bundles through `$sent`, a
182
+ [request](../graph/README.md#data-model) containing the prior bundle. `asking`
183
+ adds it; `asked` tests it; `before` reads that prior bundle. `$ruled` records
184
+ rule-added bundles through `ruling` and `ruled`. `$echo` identifies server
185
+ updates through `echo` and `echoed`. `clean` removes all three requests. `SENT`,
186
+ `RULED`, and `ECHO` export their names.
187
+
188
+ ```ts
189
+ import { loadVocab } from '@yaks/vocab'
190
+ import {
191
+ asked,
192
+ asking,
193
+ before,
194
+ clean,
195
+ inverse,
196
+ local,
197
+ outbound,
198
+ outward,
199
+ stored,
200
+ } from '@yaks/sync'
201
+ import { equal } from '@yaks/testing'
202
+
203
+ const vocab = loadVocab({
204
+ $defs: {
205
+ book: { component: true, properties: { title: { type: 'string' } } },
206
+ draft: {
207
+ component: true,
208
+ sync: 'none',
209
+ properties: { text: { type: 'string' } },
210
+ },
211
+ },
212
+ })
213
+ const was = { entity: { eid: 'b1' }, book: { title: 'Dune' } }
214
+ const patch = {
215
+ entity: { eid: 'b1' },
216
+ book: { title: 'Changed' },
217
+ draft: { text: 'local' },
218
+ }
219
+ const sent = asking(patch, was)
220
+ equal(asked(sent), true)
221
+ equal(before(sent), was)
222
+ equal(clean(sent), patch)
223
+ equal(outward([sent], vocab), [{
224
+ entity: { eid: 'b1' },
225
+ book: { title: 'Changed' },
226
+ }])
227
+ equal(inverse([sent], vocab), [was])
228
+ equal(local(vocab, 'draft'), 'vault')
229
+ equal(outbound(vocab, 'draft'), false)
230
+ equal(stored(vocab, 'book'), true)
231
+ ```
232
+
233
+ Peer components travel over the socket. Each write commits locally immediately;
234
+ `pace` folds intermediate writes into one patch per entity and component. The
235
+ first write after a quiet interval leaves immediately; the last folded patch
236
+ leaves when the interval ends. Clearing a component sends immediately and
237
+ discards its folded patch. Values sent together share their pace timer.
238
+
239
+ The Sync keeps its own peer values across socket connections and sends them
240
+ again before resubscribing. The server associates each value with its latest
241
+ writing connection, so an older connection's close cannot clear the value
242
+ claimed by the newer connection. A saved peer snapshot cannot replace a newer
243
+ value this node is still writing.
244
+
245
+ ```ts
246
+ import { graph } from '@yaks/graph'
247
+ import { ram } from '@yaks/ram'
248
+ import { loadVocab } from '@yaks/vocab'
249
+ import { hear, sync } from '@yaks/sync'
250
+ import { equal } from '@yaks/testing'
251
+
252
+ const vocab = loadVocab({
253
+ $defs: {
254
+ cursor: {
255
+ component: true,
256
+ sync: 'peers',
257
+ durable: 'connection',
258
+ pace: '100ms',
259
+ properties: { x: { type: 'number' } },
260
+ },
261
+ },
262
+ })
263
+ const g = graph({ storage: ram(vocab), vocab })
264
+ g.install()
265
+ const events = new EventTarget()
266
+ const messages: unknown[] = []
267
+ const timers: { ms: number; fn: () => void }[] = []
268
+ const socket = {
269
+ readyState: 0,
270
+ send: (data: string) => messages.push(JSON.parse(data)),
271
+ close: () => {},
272
+ addEventListener: events.addEventListener.bind(events),
273
+ }
274
+ const link = sync(g, {
275
+ url: 'https://books.example',
276
+ connect: () => socket,
277
+ timer: (fn, ms) => timers.push({ ms, fn }),
278
+ fetch: () => {
279
+ throw new Error('peer writes must use the socket')
280
+ },
281
+ })
282
+ link.open()
283
+ socket.readyState = 1
284
+ events.dispatchEvent(new Event('open'))
285
+ await g.apply([{ entity: { eid: 'b1' }, cursor: { x: 1 } }])
286
+ await g.apply([{ entity: { eid: 'b1' }, cursor: { x: 2 } }])
287
+ // The socket was asked the time as it opened; then the first move goes at once.
288
+ const relays = () => messages.filter((m) => !('clock' in (m as object)))
289
+ equal(relays(), [{ relay: [{ entity: { eid: 'b1' }, cursor: { x: 1 } }] }])
290
+ timers.find((t) => t.ms <= 100)!.fn() // the cursor's pace
291
+ equal(relays()[1], { relay: [{ entity: { eid: 'b1' }, cursor: { x: 2 } }] })
292
+ await hear(g, {
293
+ id: 'books',
294
+ relay: [{ entity: { eid: 'b1' }, cursor: { x: 3 } }],
295
+ })
296
+ equal((await g.get(['b1']))[0].cursor, { x: 3 })
297
+ await link.idle()
298
+ link.close()
299
+ ```
300
+
301
+ ## Subscribe and reconnect
302
+
303
+ `subscribe(query, id?, opts?)` returns the subscription id. `subscribe(true)`
304
+ requests committed patches. Query syntax belongs to
305
+ [@yaks/query](../query/README.md#query-model).
306
+
307
+ The injected socket below shows readiness without network access. `onReady`
308
+ reports changes and refusals, including empty first answers; it does not call
309
+ the listener immediately. `onConnection` hears `true` each time the socket opens
310
+ and `false` each time an open one closes under it, so a page can say it is
311
+ reconnecting while its server is away.
312
+
313
+ ```ts
314
+ import { graph } from '@yaks/graph'
315
+ import { ram } from '@yaks/ram'
316
+ import { loadVocab } from '@yaks/vocab'
317
+ import { sync } from '@yaks/sync'
318
+ import { equal } from '@yaks/testing'
319
+
320
+ const vocab = loadVocab({ $defs: {} })
321
+ const g = graph({ storage: ram(vocab), vocab })
322
+ g.install()
323
+ const events = new EventTarget()
324
+ const messages: unknown[] = []
325
+ const socket = {
326
+ readyState: 0,
327
+ send: (data: string) => messages.push(JSON.parse(data)),
328
+ close: () => {
329
+ socket.readyState = 3
330
+ },
331
+ addEventListener: events.addEventListener.bind(events),
332
+ }
333
+ const link = sync(g, {
334
+ url: 'https://books.example',
335
+ connect: () => socket,
336
+ timer: () => {}, // the reconnect waits, which this example never runs
337
+ })
338
+ const readiness: boolean[] = []
339
+ const remove = link.onReady((_id, ready) => readiness.push(ready))
340
+ const connection: boolean[] = []
341
+ link.onConnection((open) => connection.push(open))
342
+ const id = link.subscribe(true, 'all')
343
+ equal(link.ready(id), false)
344
+ socket.readyState = 1
345
+ events.dispatchEvent(new Event('open'))
346
+ equal(Object.keys(messages[0] as object), ['clock']) // asked the time on open
347
+ equal(messages[1], { subscribe: true, id: 'all', acks: true, frames: true })
348
+ events.dispatchEvent(
349
+ new MessageEvent('message', { data: JSON.stringify({ id, bundles: [] }) }),
350
+ )
351
+ equal(link.ready(id), true)
352
+ equal(readiness, [true])
353
+ link.refresh(id)
354
+ equal(link.ready(id), false)
355
+ socket.readyState = 3
356
+ events.dispatchEvent(new Event('close'))
357
+ equal(connection, [true, false])
358
+ link.unsubscribe(id)
359
+ remove()
360
+ link.close()
361
+ ```
362
+
363
+ Frames land in order. Each packet is acknowledged after its frames finish
364
+ applying. Until the first answer arrives, local queries can return incomplete
365
+ cached data. `refusal(id)` exposes the refusal until a successful answer or an
366
+ unsubscribe clears it.
367
+
368
+ A frame that says its store's `revision` (@yaks/api) does not land when a row it
369
+ carries, or lists as gone, is held at a newer one, or when its `since` is not
370
+ the revision its subscription last landed: that subscription is asked again,
371
+ whole, its set kept until the answer replaces it, and frames still on their way
372
+ from before the asking are let go. A missed frame is also reported. A revision
373
+ is one number, or a number per store from a door over several (@yaks/reach),
374
+ compared on the stores both name. Rows keep their revision after they leave
375
+ memory, up to `REVISIONS` of them, so an older answer cannot bring an evicted or
376
+ deleted row back. `revisions()` is that bookkeeping, and `wire().ask(id)` asks a
377
+ subscription again this way.
378
+
379
+ A row a pending write holds keeps the write's copy whatever a subscription says
380
+ of it meanwhile. When the write is answered, a subscription that said something
381
+ other than the row now shown, the write's answer or its revert, is asked again.
382
+
383
+ A connection that held at least `held` (default 10 seconds) and dropped, as one
384
+ does when its server hands over to a replacement, is reopened within `spread`
385
+ (default 1 second), at a moment drawn at random, so the pages a deploy drops
386
+ together do not all come back in the same instant. A failed attempt, or a
387
+ connection that dropped before it held, is retried after a delay doubling from
388
+ `wait` (default 250 ms) to `most` (default 30 seconds), each drawn between half
389
+ of it and all of it; only a connection that held starts it again from `wait`.
390
+ `random` supplies the draws, and `timer` the reconnect and pace timers. Refused
391
+ subscriptions are not reopened automatically; explicitly subscribe on their id
392
+ to retry. The first successful frame after reconnecting replaces prior
393
+ membership, adding missing entities to `gone`. Cached data alone never makes a
394
+ subscription ready on a new connection.
395
+
396
+ A drop is recovered once the wire has **resumed**: the socket is open again and
397
+ every query it holds has been answered again, with the set as it now stands or
398
+ with a refusal (reported on its own, as `refused`). Nothing was missed, so
399
+ whatever closed it (a restart, a proxy, a laptop waking) says nothing. An outage
400
+ that has not resumed `most` after it began, because the server stays away or
401
+ takes the connection and never answers, is a failure: `report` receives a
402
+ `Dropped` error naming the close code and how long it has been down, once per
403
+ outage, while it lasts. Its `cause` says what the wire was waiting on: a socket
404
+ that has not reopened, and how many attempts it made, or the queries a reopened
405
+ one has not had answered, masked as a trace keeps them, and how long ago the
406
+ server last said anything. It reaches the server whenever only the socket fails;
407
+ a server that is away is seen by its own reporting.
408
+
409
+ A connection can die without closing: a laptop that sleeps or loses its network
410
+ leaves a socket that reads as open and never hears another word. Every open
411
+ socket is asked the time (see the store's clock below), which the server answers
412
+ outside its subscription queues, so a socket that has said nothing `quiet` after
413
+ being asked (default 10 seconds) is given up as if it had closed, and the next
414
+ one asks every query again. A handshake the network holds unanswered, which a
415
+ browser can wait minutes on before it says the socket failed, is given up the
416
+ same `quiet` after the socket was made, as a failed attempt.
417
+
418
+ Both waits, `most` and `quiet`, count only time this thread could hear the
419
+ server in (@yaks/fp `heard`). A thread that stalls (a long synchronous call, a
420
+ starved CPU) runs its overdue timers before the answers that arrived during the
421
+ stall, and a server drops a client that cannot answer its pings; neither is the
422
+ server's failure, so a stall's time counts nothing.
423
+
424
+ A machine with no network has no server to fail it. While `network` says it is
425
+ offline (by default the browser's `navigator.onLine`), an outage is never said,
426
+ and when the network comes back (the `online` event) the wire reopens at once,
427
+ from the first delay, and times what follows afresh.
428
+
429
+ A machine can also have a network that reaches nothing, such as a laptop
430
+ changing networks, which the browser still calls online. Its handshakes hang
431
+ until each is given up. So before an outage whose socket never reopened is said,
432
+ the wire asks the server over HTTP (a `GET` of `/ws`, through `fetch`). If any
433
+ answer comes back, a refusal included, the server is there and the outage is
434
+ said. If nothing answers within `quiet`, the server is out of this machine's
435
+ reach, and the wire times what follows afresh.
436
+
437
+ ### The store's clock
438
+
439
+ `link.now()` returns epoch milliseconds on the store's clock. First use opens
440
+ its socket (even without a subscription); every open socket calibrates, and
441
+ subsequent calls are cheap local reads. With `@yaks/client`, use
442
+ `client.wire.now()` on a client configured with a server URL.
443
+
444
+ Until the first reply it returns the local epoch. During disconnection it keeps
445
+ the last offset, and refines it again after reconnect. Do not use it as a
446
+ readiness signal or a security authority. Corrections can move time in either
447
+ direction: use a local monotonic timer for measuring an animation's elapsed
448
+ time, and this clock for shared epoch deadlines such as a wave's start.
449
+
450
+ Calibration sends `{clock: departure}` and receives
451
+ `{clock: departure, received, sent}` directly on `/ws`, outside subscription
452
+ queues and acknowledgments. All four timestamps are milliseconds. The client
453
+ subtracts server processing time from the round trip, estimates the offset
454
+ NTP-style, and uses the least-delayed of the last eight trips. It samples each
455
+ second initially, then every 30 seconds while connected. Its local epoch is
456
+ anchored to `performance.now()`, so changing the page's wall clock does not
457
+ corrupt measurements. Closing the Sync stops calibration. The same probes tell
458
+ the wire its socket is alive (see the drops above). The box's `@yaks/api` server
459
+ and yaks.app app stores implement the same exchange.
460
+
461
+ Like NTP, this estimates rather than guarantees simultaneity: asymmetric network
462
+ delay contributes error. It is not an HTTP `Date` header's second-granularity
463
+ guess, nor a simulation lockstep protocol.
464
+
465
+ `wire(options)` provides this socket behavior without installing a graph plugin;
466
+ its `land` callback receives frames after membership bookkeeping. It also
467
+ exposes `relay(bundles)` for peer writes. `backoff` calculates the next
468
+ reconnect delay:
469
+
470
+ ```ts
471
+ import { backoff, wire } from '@yaks/sync'
472
+ import { equal } from '@yaks/testing'
473
+
474
+ const w = wire({
475
+ url: 'https://books.example',
476
+ land: () => {},
477
+ report: () => {},
478
+ })
479
+ equal(w.connected(), false)
480
+ equal(backoff(250, 30_000), 500)
481
+ equal(backoff(20_000, 30_000), 30_000)
482
+ w.close()
483
+ ```
484
+
485
+ ## Apply incoming frames and snapshots
486
+
487
+ `land(graph, frame, mine?)` applies incoming bundles as patches, relayed values,
488
+ and transient updates, and strips synchronized components from `gone` entities.
489
+ `strip(graph, eids)` does that removal directly. Identity and local components
490
+ remain, so leaving a result set is not deletion; only an incoming tombstone
491
+ marks deletion. A Sync preserves entities held by overlapping subscriptions.
492
+ Direct `land` callers must provide that protection themselves. A frame with
493
+ `coverage` lands as a `snapshot` within it, so a covered component or property
494
+ the answer no longer carries is cleared.
495
+
496
+ `hear(graph, frame, mine?)` applies only the frame's relayed peer values. A
497
+ reset clears missing peer values for its members, except components this node is
498
+ still writing. `Mine` is the predicate identifying those components.
499
+
500
+ `snapshot(graph, bundles, options?)` replaces server-stored components, clearing
501
+ omitted properties within the supplied
502
+ [coverage](../graph/README.md#projections). It retains local and unsaved peer
503
+ components. `preserve(eid, component, property?)` can retain omitted values
504
+ owned elsewhere; `mine` protects this node's peer writes. A row that already
505
+ reads as the snapshot says is not applied again and is not in what it returns,
506
+ so an answer heard whole again after a reconnect changes only what moved.
507
+
508
+ `replicate(graph, bundles)` marks and applies server patches as trusted replica
509
+ writes, unstamped: a replica keeps the stamps its server wrote. Register `marks`
510
+ on a graph that uses these incoming helpers without a Sync; it declares the
511
+ requests they use.
512
+
513
+ ```ts
514
+ import { graph } from '@yaks/graph'
515
+ import { ram } from '@yaks/ram'
516
+ import { loadVocab } from '@yaks/vocab'
517
+ import { covers, delivered, land, marks, snapshot } from '@yaks/sync'
518
+ import { equal } from '@yaks/testing'
519
+
520
+ const vocab = loadVocab({
521
+ $defs: {
522
+ book: {
523
+ component: true,
524
+ properties: { title: { type: 'string' }, pages: { type: 'number' } },
525
+ },
526
+ draft: {
527
+ component: true,
528
+ sync: 'none',
529
+ properties: { text: { type: 'string' } },
530
+ },
531
+ },
532
+ })
533
+ const g = graph({ storage: ram(vocab), vocab })
534
+ g.use(marks)
535
+ g.install()
536
+ await g.apply([{
537
+ entity: { eid: 'b1' },
538
+ book: { title: 'Dune', pages: 412 },
539
+ draft: { text: 'notes' },
540
+ }])
541
+ await snapshot(g, [{ entity: { eid: 'b1' }, book: { title: 'DUNE' } }])
542
+ equal((await g.get(['b1']))[0].book, { title: 'DUNE' })
543
+ equal(
544
+ await snapshot(g, [{ entity: { eid: 'b1' }, book: { title: 'DUNE' } }]),
545
+ [],
546
+ )
547
+ await land(g, { id: 'books', gone: ['b1'] })
548
+ equal((await g.get(['b1']))[0].book, undefined)
549
+ equal((await g.get(['b1']))[0].draft, { text: 'notes' })
550
+ const scope = delivered({ entity: { eid: 'b1' }, book: { title: 'Dune' } })
551
+ equal(scope, { book: ['title'] })
552
+ equal(covers(scope, 'book', 'title'), true)
553
+ equal(covers(scope, 'book', 'pages'), false)
554
+ ```
555
+
556
+ `covers` tests coverage; `delivered` derives coverage from a bundle's supplied
557
+ components and properties. `Coverage` is re-exported from @yaks/graph.
558
+
559
+ A **Replica** is the optional policy passed to `sync()` to manage retained
560
+ entities, subscription ownership, and pending-write protection. It supplies
561
+ `subscribe`, `unsubscribe`, `land`, and `protect`. Frames with `peerCoverage`,
562
+ `peers`, or `peerGone` require a Replica; standalone `land` rejects them.
563
+ `peers` carries entities reached by projections, independently of query
564
+ membership; `relay` carries peer-written components.
565
+ [@yaks/client](../client/README.md) supplies the Replica policy. `SubscribeOpts`
566
+ controls local priming (`prime`) and the answer's semantic identity
567
+ (`answerKey`) for that policy.
568
+
569
+ ## Workers and MessagePorts
570
+
571
+ A **PortLink** carries request replies and frames over a caller-owned `Worker`
572
+ or `MessagePort`, using structured-clone messages. `portLink()` creates one end;
573
+ `receive(method, value)` handles requests on the other end. The helper provides
574
+ no graph policy, authorization, optimistic writes, reconnection, or frame
575
+ backpressure.
576
+
577
+ The full request/reply and frame example runs beside `portLink` in
578
+ [`port_test.ts`](./port_test.ts); native `MessagePort` delivery is checked there
579
+ too. Both endpoints belong to the caller and are closed separately from the
580
+ link.
581
+
582
+ ```ts
583
+ import { portLink } from '@yaks/sync/port'
584
+
585
+ // const client = portLink(worker, { frame: (frame) => render(frame) })
586
+ // const answer = await client.request('echo', { title: 'Dune' })
587
+ // client.close() // the caller still owns worker
588
+ ```
589
+
590
+ Requests default to a 30-second timeout and at most 256 outstanding requests.
591
+ `timeout` and `maxPending` configure these limits, and `clock` (an @yaks/fp
592
+ `Clock`, by default the runtime's) keeps the deadlines. Per-request
593
+ `{ timeout: null }` disables its deadline; disconnection still rejects it. A
594
+ timeout does not cancel work at the other end. `close()` removes listeners,
595
+ notifies the other end, and rejects pending requests without terminating or
596
+ closing the caller-owned port. `stats` counts sent and received messages and
597
+ frames.
598
+
599
+ Errors arrive as ordinary `Error` objects unless the receiver supplies
600
+ `encodeError` and the requester supplies `decodeError`. The encoded value must
601
+ support structured cloning; a decoder can restore an Error subclass and its
602
+ data.
603
+
604
+ The codec contract is checked in `port_test.ts` with controlled message
605
+ delivery; the example below uses the browser's native ports.
606
+
607
+ ```ts ignore
608
+ import { portLink } from '@yaks/sync/port'
609
+ import { equal, throws } from '@yaks/testing'
610
+
611
+ class Conflict extends Error {
612
+ constructor(public current: unknown) {
613
+ super('changed since read')
614
+ }
615
+ }
616
+ const { port1, port2 } = new MessageChannel()
617
+ const client = portLink(port1, { decodeError: (value) => new Conflict(value) })
618
+ const server = portLink(port2, {
619
+ receive: (_method, value) => {
620
+ throw new Conflict(value)
621
+ },
622
+ encodeError: (error) => (error as Conflict).current,
623
+ })
624
+ try {
625
+ const error = await throws(() =>
626
+ client.request('write', { title: 'Dune' }, { timeout: null })
627
+ )
628
+ equal(error instanceof Conflict, true)
629
+ equal((error as Conflict).current, { title: 'Dune' })
630
+ } finally {
631
+ client.close()
632
+ server.close()
633
+ port1.close()
634
+ port2.close()
635
+ }
636
+ ```
637
+
638
+ ## Exports
639
+
640
+ The root exports replication and transport; the port subpath exports just the
641
+ MessagePort transport, and the socket subpath just the WebSocket wire.
642
+
643
+ | Export | Contents |
644
+ | ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
645
+ | `@yaks/sync` | `sync`, `Sync`, `SyncOpts`, `Replica`, `SubscribeOpts`; `post`, HTTP types (`Fetch`, `PostOpts`, `Refusal`, `Report`, `Trouble`); `land`, `strip`, `snapshot`, `hear`, `changes`, `Mine`; `revisions`, `older`, `REVISIONS`, `Revision`, `Revisions`, `Stamped`, `Verdict`; `wire`, `backoff`, socket types (`Ask`, `Connect`, `Frame`, `Socket`, `Timer`, `Wire`, `WireOpts`); `syncOf`, `durableOf`, `local`, `outbound`, `stored`, `outward`, `inverse`, `guessed`; `asked`, `asking`, `before`, `clean`, `echo`, `echoed`, `marks`, `replicate`, `ruled`, `ruling`, `SENT`, `RULED`, `ECHO`; `covers`, `delivered`, `Coverage`; `portLink`, `Port`, `PortLink`, `RequestOptions` |
646
+ | `@yaks/sync/port` | `portLink`, `Port`, `PortLink`, `RequestOptions`, without the replication client |
647
+ | `@yaks/sync/socket` | `wire`, `backoff`, `Dropped` and the socket types, without the replication client, for a page that holds rows without a graph |
648
+
649
+ `post(bundles, options)` sends and reconciles one write outside the Sync's
650
+ ordered queue, resolving to whether its outcome is known. It uses the same
651
+ selection and reconciliation as `sync()`. Use `asking` to mark caller input, or
652
+ supply `PostOpts.sent` for already selected bundles and `held: true` when the
653
+ write has not committed locally.
654
+
655
+ ```ts
656
+ import { graph } from '@yaks/graph'
657
+ import { ram } from '@yaks/ram'
658
+ import { loadVocab } from '@yaks/vocab'
659
+ import { marks, post } from '@yaks/sync'
660
+ import { equal } from '@yaks/testing'
661
+
662
+ const vocab = loadVocab({
663
+ $defs: {
664
+ book: { component: true, properties: { title: { type: 'string' } } },
665
+ },
666
+ })
667
+ const g = graph({ storage: ram(vocab), vocab })
668
+ g.use(marks)
669
+ g.install()
670
+ const answer = [{ entity: { eid: 'b1' }, book: { title: 'Dune' } }]
671
+ const fetch = () => Response.json(answer)
672
+ equal(
673
+ await post(answer, {
674
+ graph: g,
675
+ url: 'https://books.example',
676
+ fetch,
677
+ sent: answer,
678
+ held: true,
679
+ report: () => {},
680
+ }),
681
+ true,
682
+ )
683
+ equal((await g.get(['b1']))[0].book, { title: 'Dune' })
684
+ ```
685
+
686
+ ## Limits
687
+
688
+ Connection, subscription, and pending-request state live in memory. Entity data
689
+ belongs to the graph's [storage](../graph/README.md#data-model). This package
690
+ provides neither persistent storage nor a durable offline-write queue. It does
691
+ not enforce local expiry timers or persist local components.
692
+
693
+ `close()` does not abort queued HTTP writes or unregister the graph plugin.
694
+ Finish pending work before discarding the graph; browser unload does not
695
+ guarantee time to await it. HTTP `headers` do not authenticate the socket; that
696
+ belongs to the supplied `connect` implementation or server session handling.
697
+
698
+ The package uses web transport APIs and `lib: ["dom", "es2023"]`, without Deno
699
+ runtime types. Inject transports when a runtime lacks compatible defaults.
700
+ [@yaks/ram](../ram/README.md) supplies in-memory storage;
701
+ [@yaks/api](../api/README.md) implements the server protocol.
702
+
703
+ ## License
704
+
705
+ Apache-2.0
706
+
707
+ ## Durable write intent
708
+
709
+ Every HTTP write has a stable `outbox:` identity. In a browser sync commits its
710
+ immutable server batch to IndexedDB **before** posting it. A new page for the
711
+ same store and identity replays pending entries, in order, with the same key.
712
+ Replica eviction and a closed socket do not remove intent. Non-browser runtimes
713
+ use the same delivery queue in memory unless `outbox` supplies a disk store.
714
+ `outboxScope` isolates applications and authenticated accounts sharing an
715
+ origin; cookie-authenticated callers must supply an account-specific scope (or
716
+ an `OutboxStore` whose startup waits for the account).
717
+
718
+ A lost response or HTTP 202 rejects the awaiting caller with `WriteUnknown`,
719
+ which means **unsaved**, not refused or lost. Background delivery retries while
720
+ the page is alive; closing a page pauses delivery, not persistence. A definite
721
+ refusal rejects with `WriteRefused` and remains inspectable, not retried without
722
+ an explicit choice. `pending()` and `onPending()` expose both states;
723
+ `retry(key)` deliberately retries, and `forget(key)` explicitly discards that
724
+ intent. Never label a pending entry saved because an optimistic row rendered.
725
+ IndexedDB failure fails the write before posting, instead of quietly degrading a
726
+ browser write to an in-memory queue. Keep the editable draft until acceptance.
727
+
728
+ The server must retain durable acceptance receipts for these keys. Replaying a
729
+ bare merge or a `$was` guard is not a substitute: after a committed response is
730
+ lost, a guard can be stale and an alias can otherwise mint twice.