@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/pace.js ADDED
@@ -0,0 +1,96 @@
1
+ // How often a relayed value leaves: the `pace` a `sync: peers` component
2
+ // declares (@yaks/vocab lifetime.ts).
3
+ //
4
+ // A page that moves something every frame writes every frame, and its own
5
+ // graph takes every write at once. What crosses the socket is paced: for each
6
+ // entity, a paced component is sent at most once a pace. The first write after
7
+ // a quiet spell goes at once; the writes inside the pace fold into one patch,
8
+ // sent when the pace runs out, so the last value always arrives and a mover
9
+ // that stops is heard where it stopped. A clear goes at once, and takes the
10
+ // patch it would have followed with it: a peer should not see a value come
11
+ // back after it was cleared.
12
+ //
13
+ // A pace starts per send, not per value: the values one relay message carried
14
+ // cool together, and what they gathered goes out together, so a page moving
15
+ // forty things sends one message a pace, not forty.
16
+ import { comps } from "@yaks/graph/bundle";
17
+ import { paceOf } from "@yaks/vocab";
18
+ /** The key one relayed component on one entity is known by. */ export let key = (eid, comp)=>eid + ' ' + comp;
19
+ /** Said values, one bundle per entity, in the order they were said. */ export let bundled = (said)=>{
20
+ let out = new Map();
21
+ for (let [eid, comp, patch] of said){
22
+ let b = out.get(eid) ?? {
23
+ entity: {
24
+ eid
25
+ }
26
+ };
27
+ b[comp] = patch;
28
+ out.set(eid, b);
29
+ }
30
+ return [
31
+ ...out.values()
32
+ ];
33
+ };
34
+ /**
35
+ * The relay, paced. Returns what the sync hands each committed write's relayed
36
+ * bundles to; `send` is the socket's relay, and `timer` is how a pace is timed.
37
+ * A component with no pace is sent as it is written.
38
+ */ export let pacer = (vocab, send, timer)=>{
39
+ let cooling = new Set() // sent less than a pace ago
40
+ ;
41
+ let gathered = new Map() // written since, folded into one
42
+ ;
43
+ let say = (said)=>{
44
+ if (said.length) send(bundled(said));
45
+ };
46
+ // A pace ran out for the values one message carried: what they gathered
47
+ // meanwhile goes out, and starts the next pace; the rest are quiet again.
48
+ let cool = (keys, pace)=>timer(()=>{
49
+ let due = keys.filter((k)=>gathered.has(k));
50
+ for (let k of keys)if (!gathered.has(k)) cooling.delete(k);
51
+ say(due.map((k)=>gathered.get(k)));
52
+ for (let k of due)gathered.delete(k);
53
+ if (due.length) cool(due, pace);
54
+ }, pace);
55
+ return (bundles)=>{
56
+ let now = [];
57
+ let starting = new Map() // pace → the keys it times
58
+ ;
59
+ for (let b of bundles){
60
+ let eid = b.entity.eid;
61
+ for (let [comp, patch] of comps(b)){
62
+ let k = key(eid, comp);
63
+ let pace = paceOf(typeof vocab == 'function' ? vocab() : vocab, comp);
64
+ if (patch == null) gathered.delete(k);
65
+ if (patch == null || pace == null) now.push([
66
+ eid,
67
+ comp,
68
+ patch
69
+ ]);
70
+ else if (cooling.has(k)) {
71
+ let was = gathered.get(k)?.[2];
72
+ gathered.set(k, [
73
+ eid,
74
+ comp,
75
+ {
76
+ ...was,
77
+ ...patch
78
+ }
79
+ ]);
80
+ } else {
81
+ cooling.add(k);
82
+ now.push([
83
+ eid,
84
+ comp,
85
+ patch
86
+ ]);
87
+ if (!starting.has(pace)) starting.set(pace, []);
88
+ starting.get(pace).push(k);
89
+ }
90
+ }
91
+ }
92
+ say(now);
93
+ for (let [pace, keys] of starting)cool(keys, pace);
94
+ };
95
+ };
96
+ //# sourceMappingURL=pace.js.map
package/pace.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pace.js","sources":["./pace.ts"],"names":[],"mappings":"AAAA,yEAAyE;AACzE,sCAAsC;AACtC,EAAE;AACF,0EAA0E;AAC1E,8EAA8E;AAC9E,+EAA+E;AAC/E,8EAA8E;AAC9E,4EAA4E;AAC5E,4EAA4E;AAC5E,2EAA2E;AAC3E,6BAA6B;AAC7B,EAAE;AACF,8EAA8E;AAC9E,4EAA4E;AAC5E,oDAAoD;AAGpD,SAAS,KAAK,kCAAuC;AACrD,SAAS,MAAM,2BAA4C;AAM3D,6DAA6D,GAC7D,OAAO,IAAI,MAAM,CAAC,KAAU,OAAyB,MAAM,MAAM,KAAI;AAErE,qEAAqE,GACrE,OAAO,IAAI,UAAU,CAAC;EACpB,IAAI,MAAM,IAAI;EACd,KAAK,IAAI,CAAC,KAAK,MAAM,MAAM,IAAI,KAAM;IACnC,IAAI,IAAI,IAAI,GAAG,CAAC,QAAQ;MAAE,QAAQ;QAAE;MAAI;IAAE;IAC1C,CAAC,CAAC,KAAK,GAAG;IACV,IAAI,GAAG,CAAC,KAAK;EACf;EACA,OAAO;OAAI,IAAI,MAAM;GAAG;AAC1B,EAAC;AAED;;;;CAIC,GACD,OAAO,IAAI,QAAQ,CACjB,OACA,MACA;EAEA,IAAI,UAAU,IAAI,MAAc,4BAA4B;;EAC5D,IAAI,WAAW,IAAI,MAAoB,iCAAiC;;EAExE,IAAI,MAAM,CAAC;IACT,IAAI,KAAK,MAAM,EAAE,KAAK,QAAQ;EAChC;EAEA,wEAAwE;EACxE,0EAA0E;EAC1E,IAAI,OAAO,CAAC,MAAgB,OAC1B,MAAM;MACJ,IAAI,MAAM,KAAK,MAAM,CAAC,CAAC,IAAM,SAAS,GAAG,CAAC;MAC1C,KAAK,IAAI,KAAK,KAAM,IAAI,CAAC,SAAS,GAAG,CAAC,IAAI,QAAQ,MAAM,CAAC;MACzD,IAAI,IAAI,GAAG,CAAC,CAAC,IAAM,SAAS,GAAG,CAAC;MAChC,KAAK,IAAI,KAAK,IAAK,SAAS,MAAM,CAAC;MACnC,IAAI,IAAI,MAAM,EAAE,KAAK,KAAK;IAC5B,GAAG;EAEL,OAAO,CAAC;IACN,IAAI,MAAc,EAAE;IACpB,IAAI,WAAW,IAAI,MAAwB,2BAA2B;;IACtE,KAAK,IAAI,KAAK,QAAS;MACrB,IAAI,MAAM,EAAE,MAAM,CAAC,GAAG;MACtB,KAAK,IAAI,CAAC,MAAM,MAAM,IAAI,MAAM,GAAI;QAClC,IAAI,IAAI,IAAI,KAAK;QACjB,IAAI,OAAO,OAAO,OAAO,SAAS,aAAa,UAAU,OAAO;QAChE,IAAI,SAAS,MAAM,SAAS,MAAM,CAAC;QACnC,IAAI,SAAS,QAAQ,QAAQ,MAAM,IAAI,IAAI,CAAC;UAAC;UAAK;UAAM;SAAM;aACzD,IAAI,QAAQ,GAAG,CAAC,IAAI;UACvB,IAAI,MAAM,SAAS,GAAG,CAAC,IAAI,CAAC,EAAE;UAC9B,SAAS,GAAG,CAAC,GAAG;YAAC;YAAK;YAAM;cAAE,GAAG,GAAG;cAAE,GAAG,KAAK;YAAC;WAAE;QACnD,OAAO;UACL,QAAQ,GAAG,CAAC;UACZ,IAAI,IAAI,CAAC;YAAC;YAAK;YAAM;WAAM;UAC3B,IAAI,CAAC,SAAS,GAAG,CAAC,OAAO,SAAS,GAAG,CAAC,MAAM,EAAE;UAC9C,SAAS,GAAG,CAAC,MAAO,IAAI,CAAC;QAC3B;MACF;IACF;IACA,IAAI;IACJ,KAAK,IAAI,CAAC,MAAM,KAAK,IAAI,SAAU,KAAK,MAAM;EAChD;AACF,EAAC"}
package/pace.ts ADDED
@@ -0,0 +1,91 @@
1
+ // How often a relayed value leaves: the `pace` a `sync: peers` component
2
+ // declares (@yaks/vocab lifetime.ts).
3
+ //
4
+ // A page that moves something every frame writes every frame, and its own
5
+ // graph takes every write at once. What crosses the socket is paced: for each
6
+ // entity, a paced component is sent at most once a pace. The first write after
7
+ // a quiet spell goes at once; the writes inside the pace fold into one patch,
8
+ // sent when the pace runs out, so the last value always arrives and a mover
9
+ // that stops is heard where it stopped. A clear goes at once, and takes the
10
+ // patch it would have followed with it: a peer should not see a value come
11
+ // back after it was cleared.
12
+ //
13
+ // A pace starts per send, not per value: the values one relay message carried
14
+ // cool together, and what they gathered goes out together, so a page moving
15
+ // forty things sends one message a pace, not forty.
16
+
17
+ import type { Bundle, Comp, Eid } from 'jsr:@yaks/graph@0.2.36'
18
+ import { comps } from '@yaks/graph/bundle'
19
+ import { paceOf, type Vocab } from '@yaks/vocab'
20
+ import type { Timer } from './socket.ts'
21
+
22
+ /** One relayed component on one entity, and what is said about it. */
23
+ export type Said = [eid: Eid, comp: string, patch: Comp | null]
24
+
25
+ /** The key one relayed component on one entity is known by. */
26
+ export let key = (eid: Eid, comp: string): string => eid + ' ' + comp
27
+
28
+ /** Said values, one bundle per entity, in the order they were said. */
29
+ export let bundled = (said: Said[]): Bundle[] => {
30
+ let out = new Map<Eid, Bundle>()
31
+ for (let [eid, comp, patch] of said) {
32
+ let b = out.get(eid) ?? { entity: { eid } }
33
+ b[comp] = patch
34
+ out.set(eid, b)
35
+ }
36
+ return [...out.values()]
37
+ }
38
+
39
+ /**
40
+ * The relay, paced. Returns what the sync hands each committed write's relayed
41
+ * bundles to; `send` is the socket's relay, and `timer` is how a pace is timed.
42
+ * A component with no pace is sent as it is written.
43
+ */
44
+ export let pacer = (
45
+ vocab: Pick<Vocab, 'comp'> | (() => Pick<Vocab, 'comp'>),
46
+ send: (bundles: Bundle[]) => void,
47
+ timer: Timer,
48
+ ): (bundles: Bundle[]) => void => {
49
+ let cooling = new Set<string>() // sent less than a pace ago
50
+ let gathered = new Map<string, Said>() // written since, folded into one
51
+
52
+ let say = (said: Said[]) => {
53
+ if (said.length) send(bundled(said))
54
+ }
55
+
56
+ // A pace ran out for the values one message carried: what they gathered
57
+ // meanwhile goes out, and starts the next pace; the rest are quiet again.
58
+ let cool = (keys: string[], pace: number) =>
59
+ timer(() => {
60
+ let due = keys.filter((k) => gathered.has(k))
61
+ for (let k of keys) if (!gathered.has(k)) cooling.delete(k)
62
+ say(due.map((k) => gathered.get(k)!))
63
+ for (let k of due) gathered.delete(k)
64
+ if (due.length) cool(due, pace)
65
+ }, pace)
66
+
67
+ return (bundles) => {
68
+ let now: Said[] = []
69
+ let starting = new Map<number, string[]>() // pace → the keys it times
70
+ for (let b of bundles) {
71
+ let eid = b.entity.eid
72
+ for (let [comp, patch] of comps(b)) {
73
+ let k = key(eid, comp)
74
+ let pace = paceOf(typeof vocab == 'function' ? vocab() : vocab, comp)
75
+ if (patch == null) gathered.delete(k)
76
+ if (patch == null || pace == null) now.push([eid, comp, patch])
77
+ else if (cooling.has(k)) {
78
+ let was = gathered.get(k)?.[2]
79
+ gathered.set(k, [eid, comp, { ...was, ...patch }])
80
+ } else {
81
+ cooling.add(k)
82
+ now.push([eid, comp, patch])
83
+ if (!starting.has(pace)) starting.set(pace, [])
84
+ starting.get(pace)!.push(k)
85
+ }
86
+ }
87
+ }
88
+ say(now)
89
+ for (let [pace, keys] of starting) cool(keys, pace)
90
+ }
91
+ }
package/package.json CHANGED
@@ -1,6 +1,34 @@
1
1
  {
2
2
  "name": "@yaks/sync",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.36",
4
+ "homepage": "https://jsr.io/@yaks/sync",
5
+ "type": "module",
6
+ "exports": {
7
+ ".": {
8
+ "types": "./_dist/mod.d.ts",
9
+ "default": "./mod.js"
10
+ },
11
+ "./port": {
12
+ "types": "./_dist/port.d.ts",
13
+ "default": "./port.js"
14
+ },
15
+ "./socket": {
16
+ "types": "./_dist/socket.d.ts",
17
+ "default": "./socket.js"
18
+ },
19
+ "./outbox": {
20
+ "types": "./_dist/outbox.d.ts",
21
+ "default": "./outbox.js"
22
+ }
23
+ },
24
+ "license": "Apache-2.0",
25
+ "dependencies": {
26
+ "@yaks/fp": "0.2.36",
27
+ "@yaks/graph": "0.2.36",
28
+ "@yaks/query": "0.2.36",
29
+ "@yaks/trace": "0.2.36",
30
+ "@yaks/vocab": "0.2.36"
31
+ },
32
+ "description": "Synchronizes a client graph with a server, applies live query updates, and reconciles optimistic writes or reverts them when refused.",
33
+ "repository": "https://github.com/yak-sh/yak.git"
34
+ }
package/port.js ADDED
@@ -0,0 +1,128 @@
1
+ /** Ordered request/reply calls and subscription frames over a Worker or a
2
+ * MessagePort. The port belongs to the caller; closing the link removes the
3
+ * listeners it added but does not close the port.
4
+ */ import { system } from "@yaks/fp";
5
+ export let portLink = (port, opts = {})=>{
6
+ let next = 0, closed = false;
7
+ let clock = opts.clock ?? system;
8
+ let stats = {
9
+ sent: 0,
10
+ received: 0,
11
+ frames: 0
12
+ };
13
+ let held = new Map();
14
+ let send = (packet)=>{
15
+ if (closed) return;
16
+ stats.sent++;
17
+ port.postMessage({
18
+ channel: 'yaks',
19
+ ...packet
20
+ });
21
+ };
22
+ let onMessage = (event)=>{
23
+ let packet = event.data;
24
+ if (packet?.channel != 'yaks' || closed) return;
25
+ if (packet.closed) {
26
+ close(new Error('Peer disconnected'), false);
27
+ return;
28
+ }
29
+ stats.received++;
30
+ if (packet.frame) {
31
+ stats.frames++;
32
+ opts.frame?.(packet.frame);
33
+ return;
34
+ }
35
+ if (packet.method) {
36
+ Promise.resolve().then(()=>{
37
+ if (!opts.receive) throw new Error('No request handler');
38
+ return opts.receive(packet.method, packet.value);
39
+ }).then((value)=>send({
40
+ id: packet.id,
41
+ value
42
+ }), (error)=>{
43
+ opts.report?.(error);
44
+ return send({
45
+ id: packet.id,
46
+ error: opts.encodeError ? opts.encodeError(error) : error instanceof Error ? error.stack ?? error.message : String(error)
47
+ });
48
+ }).catch((error)=>opts.report?.(error));
49
+ return;
50
+ }
51
+ let pending = held.get(packet.id);
52
+ if (!pending) return;
53
+ held.delete(packet.id);
54
+ pending.cancel();
55
+ if ('error' in packet) {
56
+ try {
57
+ pending.reject(opts.decodeError ? opts.decodeError(packet.error) : new Error(String(packet.error)));
58
+ } catch (error) {
59
+ pending.reject(error instanceof Error ? error : new Error(String(error)));
60
+ }
61
+ } else pending.resolve(packet.value);
62
+ };
63
+ let close = (reason, notify = true)=>{
64
+ if (closed) return;
65
+ if (notify) {
66
+ try {
67
+ send({
68
+ closed: true
69
+ });
70
+ } catch {}
71
+ }
72
+ closed = true;
73
+ port.removeEventListener('message', onMessage);
74
+ port.removeEventListener('messageerror', disconnected);
75
+ port.removeEventListener('error', disconnected);
76
+ port.removeEventListener('close', disconnected);
77
+ if (held.size) reason ??= new Error('Message link closed');
78
+ for (let pending of held.values()){
79
+ pending.cancel();
80
+ pending.reject(reason);
81
+ }
82
+ held.clear();
83
+ };
84
+ let disconnected = ()=>close(new Error('Message transport disconnected'), false);
85
+ port.addEventListener('messageerror', disconnected);
86
+ port.addEventListener('error', disconnected);
87
+ port.addEventListener('close', disconnected);
88
+ port.addEventListener('message', onMessage);
89
+ if ('start' in port) port.start();
90
+ return {
91
+ stats,
92
+ request: (method, value, options = {})=>{
93
+ if (closed) return Promise.reject(new Error('Message link closed'));
94
+ if (held.size >= (opts.maxPending ?? 256)) {
95
+ return Promise.reject(new Error('Too many pending message requests'));
96
+ }
97
+ let id = ++next;
98
+ return new Promise((resolve, reject)=>{
99
+ let timeout = options.timeout === undefined ? opts.timeout ?? 30000 : options.timeout;
100
+ let cancel = timeout === null ? ()=>{} : clock.after(timeout, ()=>{
101
+ held.delete(id);
102
+ reject(new Error('Message request timed out: ' + method));
103
+ });
104
+ held.set(id, {
105
+ resolve,
106
+ reject,
107
+ cancel
108
+ });
109
+ try {
110
+ send({
111
+ id,
112
+ method,
113
+ value
114
+ });
115
+ } catch (error) {
116
+ cancel();
117
+ held.delete(id);
118
+ reject(error);
119
+ }
120
+ });
121
+ },
122
+ frame: (frame)=>send({
123
+ frame
124
+ }),
125
+ close
126
+ };
127
+ };
128
+ //# sourceMappingURL=port.js.map
package/port.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"port.js","sources":["./port.ts"],"names":[],"mappings":"AAAA;;;CAGC,GACD,SAAqB,MAAM,wBAA6B;AA+BxD,OAAO,IAAI,WAAW,CAAC,MAAY,OAa/B,CAAC,CAAC;EACJ,IAAI,OAAO,GAAG,SAAS;EACvB,IAAI,QAAQ,KAAK,KAAK,IAAI;EAC1B,IAAI,QAAQ;IAAE,MAAM;IAAG,UAAU;IAAG,QAAQ;EAAE;EAC9C,IAAI,OAAO,IAAI;EAQf,IAAI,OAAO,CAAC;IACV,IAAI,QAAQ;IACZ,MAAM,IAAI;IACV,KAAK,WAAW,CAAC;MAAE,SAAS;MAAQ,GAAG,MAAM;IAAC;EAChD;EACA,IAAI,YAAY,CAAC;IACf,IAAI,SAAS,AAAC,MAA+B,IAAI;IACjD,IAAI,QAAQ,WAAW,UAAU,QAAQ;IACzC,IAAI,OAAO,MAAM,EAAE;MACjB,MAAM,IAAI,MAAM,sBAAsB;MACtC;IACF;IACA,MAAM,QAAQ;IACd,IAAI,OAAO,KAAK,EAAE;MAChB,MAAM,MAAM;MACZ,KAAK,KAAK,GAAG,OAAO,KAAK;MACzB;IACF;IACA,IAAI,OAAO,MAAM,EAAE;MACjB,QAAQ,OAAO,GAAG,IAAI,CAAC;QACrB,IAAI,CAAC,KAAK,OAAO,EAAE,MAAM,IAAI,MAAM;QACnC,OAAO,KAAK,OAAO,CAAC,OAAO,MAAM,EAAG,OAAO,KAAK;MAClD,GAAG,IAAI,CACL,CAAC,QAAU,KAAK;UAAE,IAAI,OAAO,EAAE;UAAE;QAAM,IACvC,CAAC;QACC,KAAK,MAAM,GAAG;QACd,OAAO,KAAK;UACV,IAAI,OAAO,EAAE;UACb,OAAO,KAAK,WAAW,GACnB,KAAK,WAAW,CAAC,SACjB,iBAAiB,QACjB,MAAM,KAAK,IAAI,MAAM,OAAO,GAC5B,OAAO;Q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E5B,IAAI,QAAQ,OAAO,QAAQ,MAAM,CAAC,IAAI,MAAM;MAC5C,IAAI,KAAK,IAAI,IAAI,CAAC,KAAK,UAAU,IAAI,GAAG,GAAG;QACzC,OAAO,QAAQ,MAAM,CAAC,IAAI,MAAM;MAClC;MACA,IAAI,KAAK,EAAE;MACX,OAAO,IAAI,QAAQ,CAAC,SAAS;QAC3B,IAAI,UAAU,QAAQ,OAAO,KAAK,YAC9B,KAAK,OAAO,IAAI,QAChB,QAAQ,OAAO;QACnB,IAAI,SAAS,YAAY,OAAO,KAAO,IAAI,MAAM,KAAK,CAAC,SAAS;UAC9D,KAAK,MAAM,CAAC;UACZ,OAAO,IAAI,MAAM,gCAAgC;QACnD;QACA,KAAK,GAAG,CAAC,IAAI;UAAE;UAAS;UAAQ;QAAO;QACvC,IAAI;UACF,KAAK;YAAE;YAAI;YAAQ;UAAM;QAC3B,EAAE,OAAO,OAAO;UACd;UACA,KAAK,MAAM,CAAC;UACZ,OAAO;QACT;MACF;IACF;IACA,OAAO,CAAC,QAAiB,KAAK;QAAE;MAAM;IACtC;EACF;AACF,EAAC"}
package/port.ts ADDED
@@ -0,0 +1,176 @@
1
+ /** Ordered request/reply calls and subscription frames over a Worker or a
2
+ * MessagePort. The port belongs to the caller; closing the link removes the
3
+ * listeners it added but does not close the port.
4
+ */
5
+ import { type Clock, system } from '@yaks/fp'
6
+ import type { Frame } from './socket.ts'
7
+ export type Port = Pick<
8
+ MessagePort,
9
+ 'postMessage' | 'addEventListener' | 'removeEventListener'
10
+ >
11
+ type Packet = {
12
+ channel: 'yaks'
13
+ id?: number
14
+ method?: string
15
+ value?: unknown
16
+ error?: unknown
17
+ frame?: Frame
18
+ closed?: boolean
19
+ }
20
+ export type RequestOptions = {
21
+ /** Override the link's timeout for this request; `null` waits until a reply
22
+ * or a disconnection. */
23
+ timeout?: number | null
24
+ }
25
+ /** One end of a link: what it has carried, and the three things it can do. */
26
+ export type PortLink = {
27
+ stats: { sent: number; received: number; frames: number }
28
+ request: (
29
+ method: string,
30
+ value?: unknown,
31
+ options?: RequestOptions,
32
+ ) => Promise<unknown>
33
+ frame: (frame: Frame) => void
34
+ close: (reason?: Error) => void
35
+ }
36
+ export let portLink = (port: Port, opts: {
37
+ receive?: (method: string, value: unknown) => unknown | Promise<unknown>
38
+ frame?: (frame: Frame) => void
39
+ report?: (error: unknown) => void
40
+ /** Encode a request failure as a structured-cloneable value. */
41
+ encodeError?: (error: unknown) => unknown
42
+ /** Restore a received failure, such as a domain-specific Error subclass. */
43
+ decodeError?: (value: unknown) => Error
44
+ timeout?: number
45
+ /** Maximum outstanding requests before a further one is rejected. */
46
+ maxPending?: number
47
+ /** The clock request deadlines are kept by (default the runtime's). */
48
+ clock?: Clock
49
+ } = {}): PortLink => {
50
+ let next = 0, closed = false
51
+ let clock = opts.clock ?? system
52
+ let stats = { sent: 0, received: 0, frames: 0 }
53
+ let held = new Map<
54
+ number,
55
+ {
56
+ resolve: (v: unknown) => void
57
+ reject: (e: Error) => void
58
+ cancel: () => void
59
+ }
60
+ >()
61
+ let send = (packet: Omit<Packet, 'channel'>) => {
62
+ if (closed) return
63
+ stats.sent++
64
+ port.postMessage({ channel: 'yaks', ...packet })
65
+ }
66
+ let onMessage = (event: Event) => {
67
+ let packet = (event as MessageEvent<Packet>).data
68
+ if (packet?.channel != 'yaks' || closed) return
69
+ if (packet.closed) {
70
+ close(new Error('Peer disconnected'), false)
71
+ return
72
+ }
73
+ stats.received++
74
+ if (packet.frame) {
75
+ stats.frames++
76
+ opts.frame?.(packet.frame)
77
+ return
78
+ }
79
+ if (packet.method) {
80
+ Promise.resolve().then(() => {
81
+ if (!opts.receive) throw new Error('No request handler')
82
+ return opts.receive(packet.method!, packet.value)
83
+ }).then(
84
+ (value) => send({ id: packet.id, value }),
85
+ (error) => {
86
+ opts.report?.(error)
87
+ return send({
88
+ id: packet.id,
89
+ error: opts.encodeError
90
+ ? opts.encodeError(error)
91
+ : error instanceof Error
92
+ ? error.stack ?? error.message
93
+ : String(error),
94
+ })
95
+ },
96
+ ).catch((error) => opts.report?.(error))
97
+ return
98
+ }
99
+ let pending = held.get(packet.id!)
100
+ if (!pending) return
101
+ held.delete(packet.id!)
102
+ pending.cancel()
103
+ if ('error' in packet) {
104
+ try {
105
+ pending.reject(
106
+ opts.decodeError
107
+ ? opts.decodeError(packet.error)
108
+ : new Error(String(packet.error)),
109
+ )
110
+ } catch (error) {
111
+ pending.reject(
112
+ error instanceof Error ? error : new Error(String(error)),
113
+ )
114
+ }
115
+ } else pending.resolve(packet.value)
116
+ }
117
+ let close = (reason?: Error, notify = true) => {
118
+ if (closed) return
119
+ if (notify) {
120
+ try {
121
+ send({ closed: true })
122
+ } catch { /* disconnected */ }
123
+ }
124
+ closed = true
125
+ port.removeEventListener('message', onMessage)
126
+ port.removeEventListener('messageerror', disconnected)
127
+ port.removeEventListener('error', disconnected)
128
+ port.removeEventListener('close', disconnected)
129
+ if (held.size) reason ??= new Error('Message link closed')
130
+ for (let pending of held.values()) {
131
+ pending.cancel()
132
+ pending.reject(reason!)
133
+ }
134
+ held.clear()
135
+ }
136
+ let disconnected = () =>
137
+ close(new Error('Message transport disconnected'), false)
138
+ port.addEventListener('messageerror', disconnected)
139
+ port.addEventListener('error', disconnected)
140
+ port.addEventListener('close', disconnected)
141
+ port.addEventListener('message', onMessage)
142
+ if ('start' in port) (port as MessagePort).start()
143
+ return {
144
+ stats,
145
+ request: (
146
+ method: string,
147
+ value?: unknown,
148
+ options: RequestOptions = {},
149
+ ): Promise<unknown> => {
150
+ if (closed) return Promise.reject(new Error('Message link closed'))
151
+ if (held.size >= (opts.maxPending ?? 256)) {
152
+ return Promise.reject(new Error('Too many pending message requests'))
153
+ }
154
+ let id = ++next
155
+ return new Promise((resolve, reject) => {
156
+ let timeout = options.timeout === undefined
157
+ ? opts.timeout ?? 30000
158
+ : options.timeout
159
+ let cancel = timeout === null ? () => {} : clock.after(timeout, () => {
160
+ held.delete(id)
161
+ reject(new Error('Message request timed out: ' + method))
162
+ })
163
+ held.set(id, { resolve, reject, cancel })
164
+ try {
165
+ send({ id, method, value })
166
+ } catch (error) {
167
+ cancel()
168
+ held.delete(id)
169
+ reject(error)
170
+ }
171
+ })
172
+ },
173
+ frame: (frame: Frame) => send({ frame }),
174
+ close,
175
+ }
176
+ }
package/rebase.js ADDED
@@ -0,0 +1,93 @@
1
+ // Reconcile an older receipt without replacing newer optimistic transactions.
2
+ import { after, same } from "@yaks/fp";
3
+ import { comps, dead } from "@yaks/graph/bundle";
4
+ import { asked, asking, before, replicate, ruling } from "./mark.js";
5
+ let patched = (row, patch)=>{
6
+ let entity = {
7
+ ...row.entity,
8
+ ...patch.entity
9
+ };
10
+ if (dead(patch)) return {
11
+ entity,
12
+ tombstone: {}
13
+ };
14
+ let next = {
15
+ ...row,
16
+ entity
17
+ };
18
+ for (let [name, values] of comps(patch)){
19
+ if (values == null) {
20
+ delete next[name];
21
+ continue;
22
+ }
23
+ let comp = {
24
+ ...next[name],
25
+ ...values
26
+ };
27
+ for (let prop of Object.keys(values)){
28
+ if (values[prop] == null) delete comp[prop];
29
+ }
30
+ next[name] = comp;
31
+ }
32
+ return next;
33
+ };
34
+ let difference = (held, next)=>{
35
+ if (!held || dead(next)) return next;
36
+ let patch = {
37
+ entity: next.entity
38
+ };
39
+ for (let [name] of comps(held))if (!(name in next)) patch[name] = null;
40
+ for (let [name, values] of comps(next)){
41
+ let was = held[name];
42
+ if (same(was, values)) continue;
43
+ patch[name] = {
44
+ ...Object.fromEntries(Object.keys(was ?? {}).filter((prop)=>!(prop in (values ?? {}))).map((prop)=>[
45
+ prop,
46
+ null
47
+ ])),
48
+ ...values
49
+ };
50
+ }
51
+ return patch;
52
+ };
53
+ export let rebase = (graph, landing, later)=>{
54
+ let affected = new Set(landing.map((b)=>b.entity.eid));
55
+ let rows = new Map();
56
+ for (let write of later){
57
+ if (write.held) continue;
58
+ let snapshots = new Map();
59
+ write.bundles = write.bundles.map((b)=>{
60
+ let eid = b.entity.eid;
61
+ if (!affected.has(eid) || before(b) === undefined) return b;
62
+ let row = rows.get(eid);
63
+ if (!row) {
64
+ row = before(b) ?? {
65
+ entity: b.entity
66
+ };
67
+ for (let patch of landing){
68
+ if (patch.entity.eid === eid) row = patched(row, patch);
69
+ }
70
+ }
71
+ if (!snapshots.has(eid)) snapshots.set(eid, row);
72
+ rows.set(eid, dead(row) ? row : patched(row, b));
73
+ let base = snapshots.get(eid);
74
+ return asked(b) ? asking(b, base) : ruling(b, base);
75
+ });
76
+ }
77
+ if (!rows.size) return replicate(graph, landing);
78
+ return after(graph.get([
79
+ ...rows.keys()
80
+ ]), (held)=>{
81
+ let prior = new Map(held.map((b)=>[
82
+ b.entity.eid,
83
+ b
84
+ ]));
85
+ return replicate(graph, [
86
+ ...landing.filter((b)=>!rows.has(b.entity.eid)),
87
+ ...[
88
+ ...rows
89
+ ].map(([eid, row])=>difference(prior.get(eid), row))
90
+ ]);
91
+ });
92
+ };
93
+ //# sourceMappingURL=rebase.js.map
package/rebase.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rebase.js","sources":["./rebase.ts"],"names":[],"mappings":"AAAA,8EAA8E;AAC9E,SAAS,KAAK,EAAE,IAAI,wBAA6B;AAEjD,SAAS,KAAK,EAAE,IAAI,kCAAuC;AAC3D,SAAS,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,oBAAmB;AAEpE,IAAI,UAAU,CAAC,KAAa;EAC1B,IAAI,SAAS;IAAE,GAAG,IAAI,MAAM;IAAE,GAAG,MAAM,MAAM;EAAC;EAC9C,IAAI,KAAK,QAAQ,OAAO;IAAE;IAAQ,WAAW,CAAC;EAAE;EAChD,IAAI,OAAe;IAAE,GAAG,GAAG;IAAE;EAAO;EACpC,KAAK,IAAI,CAAC,MAAM,OAAO,IAAI,MAAM,OAAQ;IACvC,IAAI,UAAU,MAAM;MAClB,OAAO,IAAI,CAAC,KAAK;MACjB;IACF;IACA,IAAI,OAAO;MAAE,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