@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/inbound.ts ADDED
@@ -0,0 +1,251 @@
1
+ // What the server pushes, applied to the local graph. An incoming frame goes
2
+ // through the same `apply()` a local write goes through — trusted, because the
3
+ // server is where the stamped properties and the numbers were written — and
4
+ // marked as an echo so the outbound hook does not send it straight back.
5
+ //
6
+ // `gone` is the part no client could work out for itself: an entity that left a
7
+ // subscription's set, whether it was deleted or merely stopped matching. The
8
+ // frame does not distinguish the two, so this module removes the entity's
9
+ // components rather than tombstoning it: an entity with no components matches
10
+ // no query — which is what leaving the set means — and it can come back whole
11
+ // when it matches again, where a tombstone could never be lifted. A deletion
12
+ // still tombstones, because a deletion arrives as a `tombstone` component in
13
+ // the frame's bundles.
14
+ //
15
+ // `relay` is the other half no client could work out: a peer's `sync: peers`
16
+ // values, somebody's cursor, which the server forwards without keeping. They
17
+ // land in the local graph like anything else the server sends, so a query
18
+ // finds them beside the entity they belong to.
19
+
20
+ import type { Bundle, Comp, Eid, Graph } from 'jsr:@yaks/graph@0.2.36'
21
+ import { after, same } from '@yaks/fp'
22
+ import { comps, dead } from '@yaks/graph/bundle'
23
+ import { transient } from '@yaks/graph/read'
24
+ import { replicate } from './mark.js'
25
+ import type { Mine } from './saying.ts'
26
+ import type { Frame } from './socket.ts'
27
+ import { type Coverage, covers } from './coverage.js'
28
+ import { outbound, stored, syncOf } from './tier.js'
29
+
30
+ // A patch that removes an entity's server-owned components, leaving its local
31
+ // state alone. The entity is then invisible to every query, which is what "no
32
+ // longer in the set" looks like locally.
33
+ let bare = (graph: Graph, b: Bundle): Bundle[] => {
34
+ if (dead(b)) return [] // already tombstoned; nothing left to remove
35
+ let out: Bundle = { entity: { eid: b.entity.eid } }
36
+ for (let [name] of comps(b)) {
37
+ if (outbound(graph.vocab, name)) out[name] = null
38
+ }
39
+ return comps(out).length ? [out] : []
40
+ }
41
+
42
+ // A saved peer snapshot can lag this node's own paced relay. It initializes
43
+ // a reader, but cannot move a writer back behind what it is already saying.
44
+ let incoming = (graph: Graph, bundles: Bundle[], mine: Mine) =>
45
+ bundles.map((b) => {
46
+ let out = { ...b }
47
+ for (let [name] of comps(b)) {
48
+ if (syncOf(graph.vocab, name) == 'peers' && mine(b.entity.eid, name)) {
49
+ delete out[name]
50
+ }
51
+ }
52
+ return out
53
+ })
54
+
55
+ /**
56
+ * Take these entities out of the local graph: their server-owned components are
57
+ * dropped, their identity stays. This is what a subscription's `gone` list
58
+ * means.
59
+ */
60
+ export let strip = (
61
+ graph: Graph,
62
+ eids: Eid[],
63
+ ): Bundle[] | Promise<Bundle[]> =>
64
+ after(graph.get(eids), (held) => {
65
+ let out = held.flatMap((b) => bare(graph, b))
66
+ return out.length ? replicate(graph, out) : []
67
+ })
68
+
69
+ /**
70
+ * One frame from the server, applied: the bundles it carries go in whole and
71
+ * trusted, and the entities it lists as gone have their components removed. A
72
+ * frame with `coverage` is a {@link snapshot} within it, so what the answer
73
+ * covers and no longer carries is cleared. Riders need a Replica to own them.
74
+ * A refused subscription changes nothing in the graph — it is reported, not
75
+ * applied. `mine` is what this node is saying itself, as {@link hear} takes it.
76
+ */
77
+ export let land = (
78
+ graph: Graph,
79
+ frame: Frame,
80
+ mine: Mine = none,
81
+ ): Bundle[] | Promise<Bundle[]> => {
82
+ if (frame.refused) return []
83
+ if (frame.peerCoverage || frame.peers || frame.peerGone) {
84
+ throw new Error('rider delivery requires a working-set replica')
85
+ }
86
+ const live = transient(graph)
87
+ let bundles = frame.bundles ?? [], coverage = frame.coverage
88
+ let gone = frame.gone ?? []
89
+ live.forget([...gone, ...frame.transientReset ?? []])
90
+ return after(
91
+ !bundles.length
92
+ ? []
93
+ : coverage
94
+ ? snapshot(graph, bundles, { coverage, mine })
95
+ : replicate(graph, incoming(graph, bundles, mine)),
96
+ (applied) => {
97
+ for (const update of frame.transient ?? []) live.receive(update)
98
+ return after(
99
+ gone.length ? strip(graph, gone) : [],
100
+ (out) =>
101
+ after(
102
+ hear(graph, frame, mine),
103
+ (heard) => [...applied, ...out, ...heard],
104
+ ),
105
+ )
106
+ },
107
+ )
108
+ }
109
+
110
+ // Saying nothing: a graph whose sync is not relaying anything of its own.
111
+ let none: Mine = () => false
112
+
113
+ /**
114
+ * The relayed values a frame carries, applied: each peer's `sync: peers`
115
+ * components, and nothing else, as the patches they were sent as. A reset
116
+ * frame is the whole set as it now stands, relay included, so a peer value
117
+ * this copy still holds for one of its members and the frame does not repeat
118
+ * went away while this connection was not listening, and is cleared. What
119
+ * this node is saying itself (`mine`) is the exception: a connection is never
120
+ * told its own values, so the frame leaving them out says nothing about them.
121
+ */
122
+ export let hear = (
123
+ graph: Graph,
124
+ frame: Frame,
125
+ mine: Mine = none,
126
+ ): Bundle[] | Promise<Bundle[]> => {
127
+ let peer = (name: string) => syncOf(graph.vocab, name) == 'peers'
128
+ let said: Bundle[] = []
129
+ let seen = new Map<Eid, Set<string>>()
130
+ for (let b of frame.bundles ?? []) {
131
+ for (let [name, patch] of comps(b)) {
132
+ if (peer(name) && stored(graph.vocab, name) && patch != null) {
133
+ let names = seen.get(b.entity.eid) ?? new Set<string>()
134
+ names.add(name)
135
+ seen.set(b.entity.eid, names)
136
+ }
137
+ }
138
+ }
139
+ for (let b of frame.relay ?? []) {
140
+ let out: Bundle = { entity: { eid: b.entity.eid } }
141
+ for (let [name, patch] of comps(b)) {
142
+ if (!peer(name)) continue
143
+ out[name] = patch
144
+ let names = seen.get(b.entity.eid) ?? new Set<string>()
145
+ names.add(name)
146
+ seen.set(b.entity.eid, names)
147
+ }
148
+ if (comps(out).length) said.push(out)
149
+ }
150
+ let landed = () => said.length ? replicate(graph, said) : []
151
+ if (!frame.reset || !frame.bundles?.length) return landed()
152
+ return after(graph.get(frame.bundles.map((b) => b.entity.eid)), (held) => {
153
+ for (let b of held) {
154
+ let eid = b.entity.eid
155
+ let out: Bundle = { entity: { eid } }
156
+ for (let [name] of comps(b)) {
157
+ if (!peer(name) || mine(eid, name)) continue
158
+ if (seen.get(eid)?.has(name)) continue
159
+ out[name] = null
160
+ }
161
+ if (comps(out).length) said.push(out)
162
+ }
163
+ return landed()
164
+ })
165
+ }
166
+
167
+ /** Whether a patch would change the row held: an entity field, component or
168
+ * property it sets that does not already read so, or one it clears that is
169
+ * there. A whole answer heard again after a reconnect is mostly rows that did
170
+ * not move, and applying those would redo every reader's work for nothing. */
171
+ export let changes = (held: Bundle | undefined, patch: Bundle): boolean => {
172
+ if (!held || dead(held) || dead(patch)) return true
173
+ for (let [key, value] of Object.entries(patch.entity)) {
174
+ if (!same((held.entity as Record<string, unknown>)[key], value)) return true
175
+ }
176
+ for (let [name, comp] of comps(patch)) {
177
+ let was = held[name] as Comp | null | undefined
178
+ if (comp == null ? was != null : was == null) return true
179
+ for (let [prop, value] of Object.entries(comp ?? {})) {
180
+ if (value == null ? was![prop] != null : !same(was![prop], value)) {
181
+ return true
182
+ }
183
+ }
184
+ }
185
+ return false
186
+ }
187
+
188
+ /** Replace the components the server stores with a query's whole rows,
189
+ * including the properties it reports as absent. A raw feed carries patches
190
+ * instead, and must use land(). Local components and unsaved peer components
191
+ * never ride a stored row, so a snapshot never removes them. Saved peer values
192
+ * initialize readers while this node's own live writes remain ahead of them.
193
+ * A row that already reads as its snapshot says is left alone, and is not in
194
+ * what this returns: landing a whole answer again costs a comparison per row,
195
+ * and only what moved is applied. */
196
+ export let snapshot = (
197
+ graph: Graph,
198
+ bundles: Bundle[],
199
+ opts: {
200
+ coverage?: Record<Eid, Coverage>
201
+ /** Peer values this node is writing itself, ahead of its saved snapshot. */
202
+ mine?: Mine
203
+ /** Lets another owner of a property keep it when this snapshot omits it. */
204
+ preserve?: (eid: Eid, name: string, prop?: string) => boolean
205
+ } = {},
206
+ ): Bundle[] | Promise<Bundle[]> =>
207
+ after(
208
+ graph.get(bundles.map((b) => b.entity.eid)),
209
+ (held) => {
210
+ let previous = new Map(held.map((b) => [b.entity.eid, b]))
211
+ let mine = opts.mine ?? none
212
+ let patches = incoming(graph, bundles, mine).map((b) => {
213
+ if (dead(b)) return b
214
+ let out: Bundle = { entity: b.entity }
215
+ let scope = opts.coverage?.[b.entity.eid] ?? true
216
+ let keep = (name: string, prop?: string) =>
217
+ opts.preserve?.(b.entity.eid, name, prop) ?? false
218
+ for (let [name, comp] of comps(previous.get(b.entity.eid) ?? out)) {
219
+ if (!stored(graph.vocab, name)) continue
220
+ if (
221
+ syncOf(graph.vocab, name) == 'peers' && mine(b.entity.eid, name)
222
+ ) continue
223
+ if (!covers(scope, name)) continue
224
+ if (
225
+ b[name] == null && (scope === true || scope[name] === true) &&
226
+ !keep(name)
227
+ ) {
228
+ out[name] = null
229
+ } else {
230
+ let cut = Object.fromEntries(
231
+ Object.keys(comp ?? {}).filter((key) =>
232
+ covers(scope, name, key) && !keep(name, key)
233
+ ).map((key) => [key, null]),
234
+ )
235
+ if (Object.keys(cut).length) out[name] = cut
236
+ }
237
+ }
238
+ for (let [name, comp] of comps(b)) {
239
+ if (!stored(graph.vocab, name) || !covers(scope, name)) continue
240
+ out[name] = comp == null ? null : {
241
+ ...(out[name] as Comp ?? {}),
242
+ ...Object.fromEntries(
243
+ Object.entries(comp).filter(([key]) => covers(scope, name, key)),
244
+ ),
245
+ }
246
+ }
247
+ return out
248
+ }).filter((patch) => changes(previous.get(patch.entity.eid), patch))
249
+ return patches.length ? replicate(graph, patches) : []
250
+ },
251
+ )
package/mark.js ADDED
@@ -0,0 +1,87 @@
1
+ // Three marks this package puts on bundles while they pass through `apply()`.
2
+ // Neither is ever stored: they exist only to carry a decision from one phase of
3
+ // the write to a later one. Both names begin with `$`, which is what keeps them
4
+ // out of admission's property checks and out of every storage adapter's write
5
+ // path.
6
+ //
7
+ // $sent added to each bundle the caller passed in, before the patches went
8
+ // in, carrying a copy of that entity as it then stood. Its presence
9
+ // means a caller wrote this bundle — the stamps and the cascade
10
+ // deletions that later phases add have no such mark — and its
11
+ // contents are what to patch back if the server refuses the write.
12
+ //
13
+ // $ruled added to each bundle a rule of the write added (@yaks/graph's
14
+ // rules phase), carrying a copy of that entity as it stood before
15
+ // the write. A page runs some rules itself to show their result at
16
+ // once (@yaks/client); the server runs them too, and its answer is
17
+ // the truth, so what the page's rules added is put back before the
18
+ // answer lands, and when the server refuses.
19
+ //
20
+ // $echo added to every list of bundles that came from the server: the
21
+ // response to a POST, and a push over the socket. The outbound hook
22
+ // skips any bundle carrying it, which is how a client can apply what
23
+ // it just received without sending it straight back.
24
+ /** The mark on a bundle a caller sent, carrying the entity as it then stood. */ export let SENT = '$sent';
25
+ /** The mark on a bundle a rule of the write added, carrying the entity as it
26
+ * stood before the write. */ export let RULED = '$ruled';
27
+ /** The mark on a batch that arrived from the server and must not go back. */ export let ECHO = '$echo';
28
+ // A write waiting for its HTTP answer. Local bookkeeping only; outward()
29
+ // never sends it and clean() never returns it.
30
+ export let ACK = '$ack';
31
+ /** Mark a bundle as the caller's, with a copy of the entity it patches
32
+ * (`null` when there was no such entity yet). */ export let asking = (b, was)=>({
33
+ ...b,
34
+ [SENT]: {
35
+ before: was
36
+ }
37
+ });
38
+ /** Mark a bundle as a rule's, with a copy of the entity before the write
39
+ * (`null` when there was no such entity yet). */ export let ruling = (b, was)=>({
40
+ ...b,
41
+ [RULED]: {
42
+ before: was
43
+ }
44
+ });
45
+ /** Whether a caller passed this bundle in — as opposed to a later phase
46
+ * adding it. */ export let asked = (b)=>b[SENT] !== undefined;
47
+ /** Whether a rule of the write added this bundle. */ export let ruled = (b)=>b[RULED] !== undefined;
48
+ /** The entity as it stood before this write: the bundle for it, `null` if it
49
+ * did not exist, `undefined` if neither a caller nor a rule wrote this
50
+ * bundle. */ export let before = (b)=>(b[SENT] ?? b[RULED])?.before;
51
+ /** The plugin a graph registers to accept these two marks when it carries no
52
+ * sync plugin of its own — a replica that only lands what a server sent
53
+ * (`land`, `snapshot`) and never posts anything back. `apply()` refuses a `$`
54
+ * key no plugin declared, and these are ours; it declares them and does nothing
55
+ * else. */ export let marks = {
56
+ name: '@yaks/sync/marks',
57
+ requests: [
58
+ SENT,
59
+ ECHO
60
+ ]
61
+ };
62
+ /** Mark bundles as the server's, so the outbound hook lets them pass. */ export let echo = (bundles)=>bundles.map((b)=>({
63
+ ...b,
64
+ [ECHO]: true
65
+ }));
66
+ /** Whether a bundle came from the server. */ export let echoed = (b)=>b[ECHO] === true;
67
+ /** What the server sent, applied to this replica: marked as an echo so it never
68
+ * goes back, trusted since the server admitted it already, unstamped since its
69
+ * stamps are the server's, and as a replica so a component this copy was not
70
+ * loaded with is left out rather than refused. */ export let replicate = (graph, bundles)=>graph.apply(echo(bundles), {
71
+ trusted: true,
72
+ replica: true,
73
+ stamp: false
74
+ });
75
+ /** A bundle with the marks removed: what a caller gets back from `apply()`,
76
+ * which is their data and not this package's bookkeeping. */ export let clean = (b)=>{
77
+ if (b[SENT] === undefined && b[ECHO] === undefined && b[ACK] === undefined && !ruled(b)) return b;
78
+ let out = {
79
+ ...b
80
+ };
81
+ delete out[SENT];
82
+ delete out[ECHO];
83
+ delete out[RULED];
84
+ delete out[ACK];
85
+ return out;
86
+ };
87
+ //# sourceMappingURL=mark.js.map
package/mark.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mark.js","sources":["./mark.ts"],"names":[],"mappings":"AAAA,8EAA8E;AAC9E,gFAAgF;AAChF,gFAAgF;AAChF,8EAA8E;AAC9E,QAAQ;AACR,EAAE;AACF,+EAA+E;AAC/E,8EAA8E;AAC9E,0EAA0E;AAC1E,wEAAwE;AACxE,6EAA6E;AAC7E,EAAE;AACF,0EAA0E;AAC1E,4EAA4E;AAC5E,6EAA6E;AAC7E,6EAA6E;AAC7E,6EAA6E;AAC7E,uDAAuD;AACvD,EAAE;AACF,0EAA0E;AAC1E,8EAA8E;AAC9E,+EAA+E;AAC/E,+DAA+D;AAI/D,8EAA8E,GAC9E,OAAO,IAAI,OAAO,QAAO;AAEzB;2BAC2B,GAC3B,OAAO,IAAI,QAAQ,SAAQ;AAE3B,2EAA2E,GAC3E,OAAO,IAAI,OAAO,QAAO;AAEzB,yEAAyE;AACzE,+CAA+C;AAC/C,OAAO,IAAI,MAAM,OAAM;AAEvB;+CAC+C,GAC/C,OAAO,IAAI,SAAS,CAAC,GAAW,MAA+B,CAAC;IAC9D,GAAG,CAAC;IACJ,CAAC,KAAK,EAAE;MAAE,QAAQ;IAAI;EACxB,CAAC,EAAC;AAEF;+CAC+C,GAC/C,OAAO,IAAI,SAAS,CAAC,GAAW,MAA+B,CAAC;IAC9D,GAAG,CAAC;IACJ,CAAC,MAAM,EAAE;MAAE,QAAQ;IAAI;EACzB,CAAC,EAAC;AAEF;cACc,GACd,OAAO,IAAI,QAAQ,CAAC,IAAuB,CAAC,CAAC,KAAK,KAAK,UAAS;AAEhE,mDAAmD,GACnD,OAAO,IAAI,QAAQ,CAAC,IAAuB,CAAC,CAAC,MAAM,KAAK,UAAS;AAEjE;;WAEW,GACX,OAAO,IAAI,SAAS,CAAC,IAClB,CAAC,CAAC,CAAC,KAAK,IAAI,CAAC,CAAC,MAAM,GAA6C,OAAM;AAE1E;;;;SAIS,GACT,OAAO,IAAI,QAAgB;EACzB,MAAM;EACN,UAAU;IAAC;IAAM;GAAK;AACxB,EAAC;AAED,uEAAuE,GACvE,OAAO,IAAI,OAAO,CAAC,UACjB,QAAQ,GAAG,CAAC,CAAC,IAAM,CAAC;MAAE,GAAG,CAAC;MAAE,CAAC,KAAK,EAAE;IAAK,CAAC,GAAE;AAE9C,2CAA2C,GAC3C,OAAO,IAAI,SAAS,CAAC,IAAuB,CAAC,CAAC,KAAK,KAAK,KAAI;AAE5D;;;gDAGgD,GAChD,OAAO,IAAI,YAAY,CACrB,OACA,UAEA,MAAM,KAAK,CAAC,KAAK,UAAU;IAAE,SAAS;IAAM,SAAS;IAAM,OAAO;EAAM,GAAE;AAE5E;2DAC2D,GAC3D,OAAO,IAAI,QAAQ,CAAC;EAClB,IACE,CAAC,CAAC,KAAK,KAAK,aAAa,CAAC,CAAC,KAAK,KAAK,aAAa,CAAC,CAAC,IAAI,KAAK,aAC7D,CAAC,MAAM,IACP,OAAO;EACT,IAAI,MAAM;IAAE,GAAG,CAAC;EAAC;EACjB,OAAO,GAAG,CAAC,KAAK;EAChB,OAAO,GAAG,CAAC,KAAK;EAChB,OAAO,GAAG,CAAC,MAAM;EACjB,OAAO,GAAG,CAAC,IAAI;EACf,OAAO;AACT,EAAC"}
package/mark.ts ADDED
@@ -0,0 +1,108 @@
1
+ // Three marks this package puts on bundles while they pass through `apply()`.
2
+ // Neither is ever stored: they exist only to carry a decision from one phase of
3
+ // the write to a later one. Both names begin with `$`, which is what keeps them
4
+ // out of admission's property checks and out of every storage adapter's write
5
+ // path.
6
+ //
7
+ // $sent added to each bundle the caller passed in, before the patches went
8
+ // in, carrying a copy of that entity as it then stood. Its presence
9
+ // means a caller wrote this bundle — the stamps and the cascade
10
+ // deletions that later phases add have no such mark — and its
11
+ // contents are what to patch back if the server refuses the write.
12
+ //
13
+ // $ruled added to each bundle a rule of the write added (@yaks/graph's
14
+ // rules phase), carrying a copy of that entity as it stood before
15
+ // the write. A page runs some rules itself to show their result at
16
+ // once (@yaks/client); the server runs them too, and its answer is
17
+ // the truth, so what the page's rules added is put back before the
18
+ // answer lands, and when the server refuses.
19
+ //
20
+ // $echo added to every list of bundles that came from the server: the
21
+ // response to a POST, and a push over the socket. The outbound hook
22
+ // skips any bundle carrying it, which is how a client can apply what
23
+ // it just received without sending it straight back.
24
+
25
+ import type { Bundle, Graph, Plugin } from 'jsr:@yaks/graph@0.2.36'
26
+
27
+ /** The mark on a bundle a caller sent, carrying the entity as it then stood. */
28
+ export let SENT = '$sent'
29
+
30
+ /** The mark on a bundle a rule of the write added, carrying the entity as it
31
+ * stood before the write. */
32
+ export let RULED = '$ruled'
33
+
34
+ /** The mark on a batch that arrived from the server and must not go back. */
35
+ export let ECHO = '$echo'
36
+
37
+ // A write waiting for its HTTP answer. Local bookkeeping only; outward()
38
+ // never sends it and clean() never returns it.
39
+ export let ACK = '$ack'
40
+
41
+ /** Mark a bundle as the caller's, with a copy of the entity it patches
42
+ * (`null` when there was no such entity yet). */
43
+ export let asking = (b: Bundle, was: Bundle | null): Bundle => ({
44
+ ...b,
45
+ [SENT]: { before: was },
46
+ })
47
+
48
+ /** Mark a bundle as a rule's, with a copy of the entity before the write
49
+ * (`null` when there was no such entity yet). */
50
+ export let ruling = (b: Bundle, was: Bundle | null): Bundle => ({
51
+ ...b,
52
+ [RULED]: { before: was },
53
+ })
54
+
55
+ /** Whether a caller passed this bundle in — as opposed to a later phase
56
+ * adding it. */
57
+ export let asked = (b: Bundle): boolean => b[SENT] !== undefined
58
+
59
+ /** Whether a rule of the write added this bundle. */
60
+ export let ruled = (b: Bundle): boolean => b[RULED] !== undefined
61
+
62
+ /** The entity as it stood before this write: the bundle for it, `null` if it
63
+ * did not exist, `undefined` if neither a caller nor a rule wrote this
64
+ * bundle. */
65
+ export let before = (b: Bundle): Bundle | null | undefined =>
66
+ ((b[SENT] ?? b[RULED]) as { before: Bundle | null } | undefined)?.before
67
+
68
+ /** The plugin a graph registers to accept these two marks when it carries no
69
+ * sync plugin of its own — a replica that only lands what a server sent
70
+ * (`land`, `snapshot`) and never posts anything back. `apply()` refuses a `$`
71
+ * key no plugin declared, and these are ours; it declares them and does nothing
72
+ * else. */
73
+ export let marks: Plugin = {
74
+ name: '@yaks/sync/marks',
75
+ requests: [SENT, ECHO],
76
+ }
77
+
78
+ /** Mark bundles as the server's, so the outbound hook lets them pass. */
79
+ export let echo = (bundles: Bundle[]): Bundle[] =>
80
+ bundles.map((b) => ({ ...b, [ECHO]: true }))
81
+
82
+ /** Whether a bundle came from the server. */
83
+ export let echoed = (b: Bundle): boolean => b[ECHO] === true
84
+
85
+ /** What the server sent, applied to this replica: marked as an echo so it never
86
+ * goes back, trusted since the server admitted it already, unstamped since its
87
+ * stamps are the server's, and as a replica so a component this copy was not
88
+ * loaded with is left out rather than refused. */
89
+ export let replicate = (
90
+ graph: Graph,
91
+ bundles: Bundle[],
92
+ ): Bundle[] | Promise<Bundle[]> =>
93
+ graph.apply(echo(bundles), { trusted: true, replica: true, stamp: false })
94
+
95
+ /** A bundle with the marks removed: what a caller gets back from `apply()`,
96
+ * which is their data and not this package's bookkeeping. */
97
+ export let clean = (b: Bundle): Bundle => {
98
+ if (
99
+ b[SENT] === undefined && b[ECHO] === undefined && b[ACK] === undefined &&
100
+ !ruled(b)
101
+ ) return b
102
+ let out = { ...b }
103
+ delete out[SENT]
104
+ delete out[ECHO]
105
+ delete out[RULED]
106
+ delete out[ACK]
107
+ return out
108
+ }
package/mod.js ADDED
@@ -0,0 +1,78 @@
1
+ /**
2
+ * @yaks/sync — connects a client {@link https://jsr.io/@yaks/graph |
3
+ * @yaks/graph} to a server: a plugin that sends a local graph's writes to the
4
+ * server over HTTP and applies the server's writes back over a WebSocket.
5
+ *
6
+ * A graph in a page over {@link https://jsr.io/@yaks/ram | @yaks/ram} is
7
+ * a complete graph — same `apply()`, same queries, same bundles — but it is
8
+ * the only participant. This package adds the other one.
9
+ *
10
+ * ```ts
11
+ * import { graph } from '@yaks/graph'
12
+ * import { ram } from '@yaks/ram'
13
+ * import { sync } from '@yaks/sync'
14
+ *
15
+ * // let g = graph({ storage: ram(vocab, { adopt: true }), vocab })
16
+ * // let link = sync(g, { url: 'https://recipes.example' })
17
+ * // link.subscribe('.recipe.course=dinner&.recipe.serves>4')
18
+ * ```
19
+ *
20
+ * ## Writes are optimistic A write commits locally first — the page renders it
21
+ * before anything crosses the network — and is then sent as `POST /apply`. The
22
+ * list of bundles the server responds with is applied back through the same
23
+ * local graph, which is how the numbers it assigned, the properties it stamped
24
+ * and the entities it deleted reach the client. If the server refuses the
25
+ * write, the optimistic batch is undone from the copy {@link sync} took of
26
+ * those entities beforehand, along with whatever the write's rules added, and
27
+ * the refusal is reported. A rule the page ran itself is a guess the server's
28
+ * answer replaces: what it added is undone as the answer lands. If the server
29
+ * is merely unreachable, nothing is undone: the write may have been applied
30
+ * there and only the response lost.
31
+ *
32
+ * ## Two keywords, one apply()
33
+ * A client holds state the server owns, state this browser owns, and state
34
+ * that dies with the tab. Each component declares which it is, using the two
35
+ * core vocabulary keywords:
36
+ *
37
+ * ```json
38
+ * { "$defs": { "draft": { "type": "object", "sync": "none",
39
+ * "properties": { "text": { "type": "string" } } } } }
40
+ * ```
41
+ *
42
+ * `sync` declares who is told about a write — `server` (the default) and
43
+ * `peers` are sent, `none` stays here — and `durable` declares how long the
44
+ * value lives: `forever` (the default) is the vault, `connection` or a
45
+ * duration is memory. All of them go through the same `apply()`. A `peers`
46
+ * component may also declare a `pace` (`"100ms"`): each write lands here at
47
+ * once, and the latest leaves at most once a pace, the last one always.
48
+ *
49
+ * ## Reading is a subscription
50
+ * {@link Sync.subscribe} opens a stored query on the server's `/ws`. Its
51
+ * answer — and every later change to it, including what left the set — is
52
+ * applied to the local graph, so a render reads the local store and never
53
+ * awaits. A dropped socket reconnects with a widening backoff, sends every
54
+ * subscription again, and treats the first frame after a reopen as the whole
55
+ * set. A drop the wire resumes from (open again, every query answered again)
56
+ * missed nothing and says nothing; an outage still unresumed `most` after it
57
+ * began is reported once as a {@link Dropped}.
58
+ *
59
+ * ## Both transports are injected
60
+ * {@link SyncOpts.fetch} and {@link SyncOpts.connect} default to the
61
+ * platform's `fetch` and `WebSocket`, and either can be passed in — which is
62
+ * how this package is tested against an in-process handler with no network at
63
+ * all.
64
+ *
65
+ * @module
66
+ */ export { sync } from "./sync.js";
67
+ export { MOVED, post, WriteRefused, WriteUnknown } from "./outbound.js";
68
+ export { changes, hear, land, snapshot, strip } from "./inbound.js";
69
+ export { pacer } from "./pace.js";
70
+ export { saying } from "./saying.js";
71
+ export { backoff, Dropped, wire } from "./socket.js";
72
+ export { durableOf, guessed, inverse, local, outbound, outward, stays, stored, syncOf } from "./tier.js";
73
+ export { asked, asking, before, clean, ECHO, echo, echoed, marks, replicate, RULED, ruled, ruling, SENT } from "./mark.js";
74
+ export { portLink } from "./port.js";
75
+ export { covers, delivered } from "./coverage.js";
76
+ export { older, REVISIONS, revisions } from "./revision.js";
77
+ export { durableOutbox, outboxIdb } from "./outbox.js";
78
+ //# sourceMappingURL=mod.js.map
package/mod.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mod.js","sources":["./mod.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAiEC,GAED,SAIE,IAAI,oBAEY;AAClB,SAEE,KAAK,EACL,IAAI,EAKJ,YAAY,EACZ,YAAY,wBACQ;AACtB,SAAS,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,QAAQ,EAAE,KAAK,uBAAsB;AACnE,SAAS,KAAK,oBAAmB;AACjC,SAAoB,MAAM,sBAAqB;AAC/C,SAEE,OAAO,EAEP,OAAO,EAOP,IAAI,sBAEc;AACpB,SACE,SAAS,EACT,OAAO,EACP,OAAO,EACP,KAAK,EACL,QAAQ,EACR,OAAO,EACP,KAAK,EACL,MAAM,EACN,MAAM,oBACU;AAClB,SACE,KAAK,EACL,MAAM,EACN,MAAM,EACN,KAAK,EACL,IAAI,EACJ,IAAI,EACJ,MAAM,EACN,KAAK,EACL,SAAS,EACT,KAAK,EACL,KAAK,EACL,MAAM,EACN,IAAI,oBACY;AAClB,SAGE,QAAQ,oBAEQ;AAElB,SAAwB,MAAM,EAAE,SAAS,wBAAuB;AAChE,SACE,KAAK,EAEL,SAAS,EAET,SAAS,wBAGW;AAEtB,SACE,aAAa,EAEb,SAAS,sBAGS"}