@yaks/wake 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 (85) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +325 -2
  3. package/_dist/cloudflare.d.ts +68 -0
  4. package/_dist/cloudflare.d.ts.map +1 -0
  5. package/_dist/comp.d.ts +59 -0
  6. package/_dist/comp.d.ts.map +1 -0
  7. package/_dist/deno.d.ts +40 -0
  8. package/_dist/deno.d.ts.map +1 -0
  9. package/_dist/due.d.ts +96 -0
  10. package/_dist/due.d.ts.map +1 -0
  11. package/_dist/every.d.ts +65 -0
  12. package/_dist/every.d.ts.map +1 -0
  13. package/_dist/graph.d.ts +4 -0
  14. package/_dist/graph.d.ts.map +1 -0
  15. package/_dist/held.d.ts +9 -0
  16. package/_dist/held.d.ts.map +1 -0
  17. package/_dist/mod.d.ts +59 -0
  18. package/_dist/mod.d.ts.map +1 -0
  19. package/_dist/plugin.d.ts +20 -0
  20. package/_dist/plugin.d.ts.map +1 -0
  21. package/_dist/run.d.ts +24 -0
  22. package/_dist/run.d.ts.map +1 -0
  23. package/_dist/service.d.ts +9 -0
  24. package/_dist/service.d.ts.map +1 -0
  25. package/_dist/tick.d.ts +36 -0
  26. package/_dist/tick.d.ts.map +1 -0
  27. package/_dist/tools.d.ts +6 -0
  28. package/_dist/tools.d.ts.map +1 -0
  29. package/_dist/vocab.d.ts +7 -0
  30. package/_dist/vocab.d.ts.map +1 -0
  31. package/_dist/watch.d.ts +58 -0
  32. package/_dist/watch.d.ts.map +1 -0
  33. package/_dist/while.d.ts +43 -0
  34. package/_dist/while.d.ts.map +1 -0
  35. package/cloudflare.js +80 -0
  36. package/cloudflare.js.map +1 -0
  37. package/cloudflare.ts +113 -0
  38. package/comp.js +59 -0
  39. package/comp.js.map +1 -0
  40. package/comp.ts +139 -0
  41. package/deno.js +57 -0
  42. package/deno.js.map +1 -0
  43. package/deno.json +1 -0
  44. package/deno.ts +78 -0
  45. package/due.js +147 -0
  46. package/due.js.map +1 -0
  47. package/due.ts +180 -0
  48. package/every.js +203 -0
  49. package/every.js.map +1 -0
  50. package/every.ts +223 -0
  51. package/graph.js +10 -0
  52. package/graph.js.map +1 -0
  53. package/graph.ts +11 -0
  54. package/held.js +29 -0
  55. package/held.js.map +1 -0
  56. package/held.ts +42 -0
  57. package/mod.js +59 -0
  58. package/mod.js.map +1 -0
  59. package/mod.ts +60 -0
  60. package/package.json +49 -4
  61. package/plugin.js +87 -0
  62. package/plugin.js.map +1 -0
  63. package/plugin.ts +94 -0
  64. package/run.js +124 -0
  65. package/run.js.map +1 -0
  66. package/run.ts +117 -0
  67. package/service.js +28 -0
  68. package/service.js.map +1 -0
  69. package/service.ts +42 -0
  70. package/tick.js +168 -0
  71. package/tick.js.map +1 -0
  72. package/tick.ts +181 -0
  73. package/tools.js +83 -0
  74. package/tools.js.map +1 -0
  75. package/tools.ts +76 -0
  76. package/vocab.js +14 -0
  77. package/vocab.js.map +1 -0
  78. package/vocab.json +270 -0
  79. package/vocab.ts +16 -0
  80. package/watch.js +175 -0
  81. package/watch.js.map +1 -0
  82. package/watch.ts +193 -0
  83. package/while.js +159 -0
  84. package/while.js.map +1 -0
  85. package/while.ts +176 -0
package/vocab.json ADDED
@@ -0,0 +1,270 @@
1
+ {
2
+ "$id": "urn:uuid:b47e3c8f-3def-4a79-aeec-955a37480fd2",
3
+ "title": "wake",
4
+ "$defs": {
5
+ "wake": {
6
+ "$id": "urn:uuid:8552ecd4-e1d0-48e6-902f-ee9ffc096367",
7
+ "component": true,
8
+ "fence": "own",
9
+ "type": "object",
10
+ "description": "a scheduled time to come back to something",
11
+ "$comment": "A wake carries no patch to apply when it fires: a rule's produce already writes the entity it matched. Patching a wake's target declaratively would need a rule that names that target.",
12
+ "properties": {
13
+ "at": {
14
+ "$id": "urn:uuid:0903ab23-fc94-444c-a2d3-310d50eec5ea",
15
+ "type": "string",
16
+ "format": "date-time",
17
+ "index": true,
18
+ "description": "when it is next due; absent once a one-shot has fired, or once a recurrence has ended"
19
+ },
20
+ "target": {
21
+ "$id": "urn:uuid:11ba5980-bc10-4192-af74-77cfffbbe664",
22
+ "type": "string",
23
+ "ref": "entity",
24
+ "death": "cascade",
25
+ "description": "what the wake is about; when absent, the entity carrying it"
26
+ },
27
+ "note": {
28
+ "$id": "urn:uuid:3eda4b5f-d6d0-43ad-ab47-bce35eec5846",
29
+ "type": "string",
30
+ "description": "a line for whoever is woken: why the wake was set"
31
+ },
32
+ "every": {
33
+ "$id": "urn:uuid:d092cd9f-54cf-46b2-af79-e8593396d300",
34
+ "type": "string",
35
+ "description": "how it recurs: a duration (30m, 2h, 1d), five cron fields (0 9 * * 1-5), or @hourly/@daily/@weekly/@monthly; a cron line may end with an IANA time zone (0 9 * * 1-5 America/New_York), otherwise UTC"
36
+ },
37
+ "while": {
38
+ "$id": "urn:uuid:74a31464-1c60-4f3d-95e9-a17523a3d913",
39
+ "type": "array",
40
+ "description": "how it recurs while something holds: {match, every} in order, a query over the whole store and the cadence it asks for; at each firing the first whose query finds anything sets the next instant, else every does, and with neither the wake sleeps until a write makes one hold",
41
+ "items": {
42
+ "type": "object",
43
+ "properties": {
44
+ "match": {
45
+ "type": "string",
46
+ "format": "query",
47
+ "description": "holds while this query finds anything"
48
+ },
49
+ "every": {
50
+ "type": "string",
51
+ "description": "the cadence while it holds, written as wake.every is"
52
+ }
53
+ },
54
+ "required": [
55
+ "match",
56
+ "every"
57
+ ]
58
+ }
59
+ },
60
+ "for": {
61
+ "$id": "urn:uuid:2a62b406-a7cf-4053-b9f4-e73d3f6af69d",
62
+ "type": "string",
63
+ "ref": "person",
64
+ "death": "keep",
65
+ "description": "the person it was set for: it runs as them, with their permissions as they stand when it fires, and it is theirs to list and cancel"
66
+ },
67
+ "brief": {
68
+ "$id": "urn:uuid:359065e9-b215-49d7-ad03-dfa259cfe063",
69
+ "type": "string",
70
+ "description": "words for a fresh session started at each firing, given the outcome of the call it carries: a helper that checks the work and tells whom it is for only when they should hear"
71
+ }
72
+ }
73
+ },
74
+ "wake_new": {
75
+ "tool": true,
76
+ "destructive": false,
77
+ "noun": "wake",
78
+ "verb": "new",
79
+ "title": "Schedule a wake",
80
+ "description": "Come back to something later: once at an instant, or on a cadence. Each firing knocks whoever attends the target with the note: the session it names (your own, to come back to something yourself), a persona's operator, or the session opened on a topic (a goal or project that is its own topic). Returns the wake.",
81
+ "input": {
82
+ "target": {
83
+ "type": "string",
84
+ "ref": "entity",
85
+ "description": "What the wake is about: a session, a persona, a topic, a goal or project id."
86
+ },
87
+ "every": {
88
+ "type": "string",
89
+ "description": "How it recurs: a duration (30m, 1d), five cron fields with an optional time zone (0 7 * * * America/Detroit), or @hourly/@daily/@weekly/@monthly."
90
+ },
91
+ "at": {
92
+ "type": "string",
93
+ "description": "When it is next due: an instant (2026-01-02T09:00Z), or a delay from now (10m, 2h, 1d). With every, the first firing. Without every, it fires once."
94
+ },
95
+ "note": {
96
+ "type": "string",
97
+ "description": "A line for whoever is woken: what to do."
98
+ }
99
+ },
100
+ "required": [
101
+ "target",
102
+ "note"
103
+ ],
104
+ "positional": [
105
+ "target"
106
+ ]
107
+ },
108
+ "wake_list": {
109
+ "tool": true,
110
+ "readOnly": true,
111
+ "noun": "wake",
112
+ "verb": "list",
113
+ "title": "List your wakes",
114
+ "description": "The wakes set for you that will fire again, soonest first: each one's id, when it next fires, how it recurs, its note, the query it watches, the call it makes and when it last fired.",
115
+ "input": {}
116
+ },
117
+ "wake_cancel": {
118
+ "tool": true,
119
+ "destructive": true,
120
+ "noun": "wake",
121
+ "verb": "cancel",
122
+ "title": "Cancel a wake",
123
+ "description": "Cancel a wake set for you, by its id, so it never fires again. Returns the wake cancelled.",
124
+ "input": {
125
+ "wake": {
126
+ "type": "string",
127
+ "ref": "wake",
128
+ "description": "The wake's id, as wake_new or wake_list gave it."
129
+ }
130
+ },
131
+ "required": [
132
+ "wake"
133
+ ],
134
+ "positional": [
135
+ "wake"
136
+ ]
137
+ },
138
+ "fired": {
139
+ "$id": "urn:uuid:6a83fc72-8b4d-49e5-9a29-8203b1cc691b",
140
+ "component": true,
141
+ "journal": false,
142
+ "type": "object",
143
+ "description": "when a wake last fired",
144
+ "properties": {
145
+ "at": {
146
+ "$id": "urn:uuid:f04ffaf2-a553-4ae8-bc10-3be5c8802dc6",
147
+ "type": "string",
148
+ "format": "date-time",
149
+ "description": "the instant it fired"
150
+ }
151
+ }
152
+ },
153
+ "watch": {
154
+ "$id": "urn:uuid:5630c807-dc45-47ae-8075-a74c8653991e",
155
+ "component": true,
156
+ "type": "object",
157
+ "description": "a query a wake watches: each time the wake comes due its rows are read again, and it fires only when they changed since it last looked; a look that finds nothing new moves it on without firing",
158
+ "properties": {
159
+ "query": {
160
+ "$id": "urn:uuid:0311eea7-4cd3-48b9-b642-448c2b50c08e",
161
+ "type": "string",
162
+ "format": "query",
163
+ "description": "the query whose rows it watches, written as for graph_query"
164
+ },
165
+ "tool": {
166
+ "$id": "urn:uuid:57653ddb-56be-46bb-9ef1-8a48e3f414bf",
167
+ "type": "string",
168
+ "description": "the reading tool it was subscribed to, whose declared query (@yaks/tools watched) is its query"
169
+ },
170
+ "args": {
171
+ "$id": "urn:uuid:80a30e91-9ac5-4c85-848b-9c7de0e1d70d",
172
+ "type": "object",
173
+ "description": "the arguments that tool was given, which filled its query"
174
+ },
175
+ "local": {
176
+ "$id": "urn:uuid:7d7439ef-a8f9-4c39-9ed2-ad5e648a2290",
177
+ "type": "boolean",
178
+ "description": "read over the store the wake is kept in, rather than everything its person reaches (on yaks.app, the space's apps)"
179
+ },
180
+ "over": {
181
+ "$id": "urn:uuid:5b314310-da55-4c69-9ea9-d31cf571b4be",
182
+ "type": "string",
183
+ "description": "the graph its host reads the query over, by the host's name for it, where it is neither the store the wake is kept in nor everything its person reaches (on yaks.app, `members`: the space's seats in the directory)"
184
+ },
185
+ "seen": {
186
+ "$id": "urn:uuid:c46f629b-c00f-4844-a1be-c44dca332db3",
187
+ "type": "object",
188
+ "description": "each row the query answered at the last look, by eid, and a digest of what it held"
189
+ },
190
+ "changes": {
191
+ "$id": "urn:uuid:c1ca711b-422f-4765-8acf-8fcf4ad67a2e",
192
+ "type": "string",
193
+ "description": "what changed at the look the wake last fired for, in words: rows new, changed and gone"
194
+ },
195
+ "record_only": {
196
+ "$id": "urn:uuid:a18c8d90-2f0c-4aa0-bf80-ce5be0a69a6a",
197
+ "type": "boolean",
198
+ "description": "keep successful changes as activity without waking a conversation"
199
+ },
200
+ "refused": {
201
+ "$id": "urn:uuid:bbf0a37e-2c75-4e92-bf1e-e1e1b5f46903",
202
+ "type": "string",
203
+ "description": "why its reader refused the query at the last look (an app that is gone, a reader with no right to it); a look refused for the same reason fires nothing, and one that reads again clears it"
204
+ }
205
+ }
206
+ },
207
+ "occurrence": {
208
+ "$id": "urn:uuid:9a9736bd-8e09-4ae7-8b90-17c41f2078b5",
209
+ "component": true,
210
+ "type": "object",
211
+ "description": "one firing of a wake that did work; completed or failed says how it ended",
212
+ "properties": {
213
+ "wake": {
214
+ "$id": "urn:uuid:592ea322-24c2-4948-8f36-5343584fc08f",
215
+ "type": "string",
216
+ "ref": "wake",
217
+ "death": "keep",
218
+ "description": "the wake that fired, kept when it is cancelled"
219
+ },
220
+ "at": {
221
+ "$id": "urn:uuid:eacbfd8d-2ef8-4b00-bd1d-a649dd68bbd0",
222
+ "type": "string",
223
+ "format": "date-time",
224
+ "description": "the instant it fired"
225
+ },
226
+ "call": {
227
+ "$id": "urn:uuid:a11eb437-749b-45a5-94fa-a4739c865516",
228
+ "type": "string",
229
+ "ref": "call",
230
+ "death": "keep",
231
+ "description": "the call it made, whose answer is that call's own record (@yaks/tools)"
232
+ },
233
+ "error": {
234
+ "$id": "urn:uuid:16d22572-23bc-416c-b486-28dbdcedac2b",
235
+ "type": "string",
236
+ "description": "the call's failure, kept while a session given the wake's brief checks its outcome"
237
+ }
238
+ }
239
+ },
240
+ "wake_run": {
241
+ "effect": true,
242
+ "created": [
243
+ "fired"
244
+ ],
245
+ "changed": [
246
+ "fired.at"
247
+ ],
248
+ "target": ".wake.for",
249
+ "option": "run",
250
+ "tries": 3,
251
+ "description": "Do what a wake set for a person asks each time it fires: its call with no model turn (an occurrence records it), its note in their conversation, and its brief to a fresh session. The host that runs sessions handles it; owed only where @yaks/wake is given run: true"
252
+ }
253
+ },
254
+ "kinds": {
255
+ "wake": {
256
+ "$id": "urn:uuid:8552ecd4-e1d0-48e6-902f-ee9ffc096367",
257
+ "description": "a scheduled time to come back to something",
258
+ "prefix": "W",
259
+ "examples": [
260
+ {
261
+ "wake": {
262
+ "at": "2026-12-01T09:00:00.000Z",
263
+ "target": "7c1e1f0a-3b5d-4c2e-9a41-2f6d8b0e5a13",
264
+ "note": "Check the deploy"
265
+ }
266
+ }
267
+ ]
268
+ }
269
+ }
270
+ }
package/vocab.ts ADDED
@@ -0,0 +1,16 @@
1
+ // The component declarations, and nothing else: the module a server or a
2
+ // browser page imports at `@yaks/wake/vocab`. It reaches no storage, no SQL and
3
+ // no runtime, so a browser tab loading this vocabulary loads nothing else.
4
+
5
+ import type { VocabDoc } from 'jsr:@yaks/vocab@0.2.36'
6
+ import { wakeDoc } from './comp.js'
7
+ import manifest from './package.json' with { type: 'json' }
8
+
9
+ export { wakeDoc }
10
+
11
+ /** What this package is: its manifest's description, the one place it is
12
+ * written, which a host stamps on each document here. */
13
+ export let description: string = manifest.description
14
+
15
+ /** Every document this plugin declares. */
16
+ export let docs: VocabDoc[] = [wakeDoc]
package/watch.js ADDED
@@ -0,0 +1,175 @@
1
+ // A wake that watches a query fires only when the query's rows changed. Each
2
+ // time it comes due its query is read again (`tick`) and compared with what
3
+ // it saw last (`watch.seen`): a row arrived, a row changed, a row left the
4
+ // answer. A change fires it, with what changed said in `watch.changes`; a look
5
+ // that finds nothing new moves `at` on and fires nothing, so rules matching
6
+ // `*fired` (a knock, a turn of a model) run only for a change.
7
+ //
8
+ // A watch needs no cadence: its host hears each commit to what it reads, and
9
+ // `stir` brings the wake due a beat later (`SOON`), so a burst of commits is
10
+ // one look. Between commits it rests with no `at`.
11
+ //
12
+ // What a row "is" for the comparison is its content in a fixed order, its
13
+ // read-time marks ($was, $actor) left out, so the same row digests the same
14
+ // however it was read. A watch keeps at most ROWS rows, so a broad query
15
+ // watches its first ROWS.
16
+ import { Stale } from "@yaks/graph/errors";
17
+ import { token } from "@yaks/graph/sha256";
18
+ import { line } from "@yaks/query";
19
+ import { WAKE, WATCH } from "./comp.js";
20
+ /** The most rows a watch keeps track of. */ export let ROWS = 200;
21
+ /** The query a wake watches, or `undefined`. */ export let watchOf = (b)=>b[WATCH] ?? undefined;
22
+ let canon = (v)=>Array.isArray(v) ? v.map(canon) : v && typeof v == 'object' ? Object.fromEntries(Object.keys(v).filter((k)=>!k.startsWith('$')).sort().map((k)=>[
23
+ k,
24
+ canon(v[k])
25
+ ])) : v;
26
+ let digest = async (row)=>{
27
+ let bytes = new TextEncoder().encode(JSON.stringify(canon(row)));
28
+ let hash = new Uint8Array(await crypto.subtle.digest('SHA-256', bytes));
29
+ return [
30
+ ...hash.slice(0, 8)
31
+ ].map((b)=>b.toString(16).padStart(2, '0')).join('');
32
+ };
33
+ let SHOWN = 10;
34
+ let WIDE = 600;
35
+ let clipped = (row)=>{
36
+ let json = JSON.stringify(canon(row));
37
+ return json.length > WIDE ? json.slice(0, WIDE) + '…' : json;
38
+ };
39
+ /**
40
+ * What `rows` say against what a watch saw before (`was`): what it sees now,
41
+ * and what changed in words, `''` when nothing did.
42
+ *
43
+ * ```ts
44
+ * import { assertEquals } from '@std/assert'
45
+ * import { look } from './watch.ts'
46
+ *
47
+ * let row = { entity: { eid: 'm1' }, meeting: { title: 'Road millage' } }
48
+ * let { seen, changes } = await look({}, [row])
49
+ * assertEquals(changes.split('\n')[0], 'What changed (1 new):')
50
+ * assertEquals((await look(seen, [row])).changes, '')
51
+ * ```
52
+ */ export let look = async (was, rows)=>{
53
+ let now = new Map();
54
+ for (let row of rows.slice(0, ROWS)){
55
+ now.set(row.entity.eid, {
56
+ hash: await digest(row),
57
+ row
58
+ });
59
+ }
60
+ let seen = Object.fromEntries([
61
+ ...now
62
+ ].map(([eid, n])=>[
63
+ eid,
64
+ n.hash
65
+ ]));
66
+ let added = [
67
+ ...now
68
+ ].filter(([eid])=>!(eid in was));
69
+ let edited = [
70
+ ...now
71
+ ].filter(([eid, n])=>eid in was && was[eid] != n.hash);
72
+ let left = Object.keys(was).filter((eid)=>!now.has(eid));
73
+ if (!added.length && !edited.length && !left.length) {
74
+ return {
75
+ seen,
76
+ changes: ''
77
+ };
78
+ }
79
+ let lines = [
80
+ ...added.map(([, n])=>`new: ${clipped(n.row)}`),
81
+ ...edited.map(([, n])=>`changed: ${clipped(n.row)}`),
82
+ ...left.map((eid)=>`gone: ${eid}`)
83
+ ];
84
+ let counts = [
85
+ added.length && `${added.length} new`,
86
+ edited.length && `${edited.length} changed`,
87
+ left.length && `${left.length} gone`
88
+ ].filter(Boolean).join(', ');
89
+ let more = lines.length - SHOWN;
90
+ return {
91
+ seen,
92
+ changes: [
93
+ `What changed (${counts}):`,
94
+ ...lines.slice(0, SHOWN),
95
+ ...more > 0 ? [
96
+ `and ${more} more`
97
+ ] : []
98
+ ].join('\n')
99
+ };
100
+ };
101
+ /**
102
+ * What `changes`, as `look` says them, counted: `1 new, 2 changed`, or
103
+ * nothing for other words.
104
+ *
105
+ * ```ts
106
+ * import { assertEquals } from '@std/assert'
107
+ * import { counted } from './watch.ts'
108
+ * assertEquals(counted('What changed (1 new, 2 gone):\nnew: {}'), '1 new, 2 gone')
109
+ * assertEquals(counted('Fixed it.'), undefined)
110
+ * ```
111
+ */ export let counted = (changes)=>changes.match(/^What changed \((.+)\):/)?.[1];
112
+ /** How long after a commit a stirred wake looks: commits inside it are one
113
+ * look, and one firing. */ export let SOON = 2_000;
114
+ // How many times a wake another writer keeps moving is read before it is
115
+ // left as that writer put it.
116
+ let TRIES = 3;
117
+ let iso = (t)=>new Date(t).toISOString();
118
+ /**
119
+ * Something the watching wakes of `graph` read committed: each one `which`
120
+ * picks comes due `soon` after `now` (unless it is due sooner already), so
121
+ * the host's next `tick` reads its query again and fires it if its rows
122
+ * changed. Answers the soonest instant a stirred wake is due, in epoch ms,
123
+ * or null when `which` picks none.
124
+ *
125
+ * ```ts
126
+ * import { assertEquals } from '@std/assert'
127
+ * import { stir } from './watch.ts'
128
+ * import { store, T0, woken } from './testing.ts'
129
+ *
130
+ * let g = woken(store())
131
+ * await g.apply([{ entity: { eid: 'w' }, wake: {}, watch: { query: '.plant' } }])
132
+ * assertEquals(await stir(g, T0), T0 + 2_000)
133
+ * ```
134
+ */ export let stir = async (graph, now, opts = {})=>{
135
+ let by = now + (opts.soon ?? SOON);
136
+ let soonest = null;
137
+ let watching = await graph.read('.watch&.wake&.fields=entity.eid,wake.at,watch.local');
138
+ for (let wake of watching){
139
+ if (opts.which && !opts.which(wake)) continue;
140
+ for(let tries = 1;; tries++){
141
+ let at = wake[WAKE]?.at;
142
+ let due = at ? Date.parse(at) : NaN;
143
+ if (due <= by) {
144
+ soonest = Math.min(soonest ?? due, due);
145
+ break;
146
+ }
147
+ try {
148
+ await graph.apply([
149
+ {
150
+ entity: wake.entity,
151
+ [WAKE]: {
152
+ at: iso(by)
153
+ },
154
+ $was: {
155
+ [WAKE]: {
156
+ at: token(at)
157
+ }
158
+ }
159
+ }
160
+ ], {
161
+ now: iso(now)
162
+ });
163
+ soonest = Math.min(soonest ?? by, by);
164
+ break;
165
+ } catch (error) {
166
+ if (!(error instanceof Stale) || tries == TRIES) throw error;
167
+ }
168
+ let [fresh] = await graph.read(line`.entity.eid=${wake.entity.eid}&.fields=entity.eid,wake.at`);
169
+ if (!fresh) break;
170
+ wake = fresh;
171
+ }
172
+ }
173
+ return soonest;
174
+ };
175
+ //# sourceMappingURL=watch.js.map
package/watch.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"watch.js","sources":["./watch.ts"],"names":[],"mappings":"AAAA,6EAA6E;AAC7E,4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AC,KAAK,EAAE;gBAAE,IAAI,MAAM;cAAI;YAAE;UACpC;SAAE,EAAE;UAAE,KAAK,IAAI;QAAK;QACpB,UAAU,KAAK,GAAG,CAAC,WAAW,IAAI;QAClC;MACF,EAAE,OAAO,OAAO;QACd,IAAI,CAAC,CAAC,iBAAiB,KAAK,KAAK,SAAS,OAAO,MAAM;MACzD;MACA,IAAI,CAAC,MAAM,GAAG,MAAM,MAAM,IAAI,CAC5B,IAAI,CAAC,YAAY,EAAE,KAAK,MAAM,CAAC,GAAG,CAAC,2BAA2B,CAAC;MAEjE,IAAI,CAAC,OAAO;MACZ,OAAO;IACT;EACF;EACA,OAAO;AACT,EAAC"}
package/watch.ts ADDED
@@ -0,0 +1,193 @@
1
+ // A wake that watches a query fires only when the query's rows changed. Each
2
+ // time it comes due its query is read again (`tick`) and compared with what
3
+ // it saw last (`watch.seen`): a row arrived, a row changed, a row left the
4
+ // answer. A change fires it, with what changed said in `watch.changes`; a look
5
+ // that finds nothing new moves `at` on and fires nothing, so rules matching
6
+ // `*fired` (a knock, a turn of a model) run only for a change.
7
+ //
8
+ // A watch needs no cadence: its host hears each commit to what it reads, and
9
+ // `stir` brings the wake due a beat later (`SOON`), so a burst of commits is
10
+ // one look. Between commits it rests with no `at`.
11
+ //
12
+ // What a row "is" for the comparison is its content in a fixed order, its
13
+ // read-time marks ($was, $actor) left out, so the same row digests the same
14
+ // however it was read. A watch keeps at most ROWS rows, so a broad query
15
+ // watches its first ROWS.
16
+
17
+ import type { Bundle, Graph } from 'jsr:@yaks/graph@0.2.36'
18
+ import { Stale } from '@yaks/graph/errors'
19
+ import { token } from '@yaks/graph/sha256'
20
+ import { line } from '@yaks/query'
21
+ import { WAKE, WATCH, type Watch } from './comp.js'
22
+
23
+ /** The most rows a watch keeps track of. */
24
+ export let ROWS = 200
25
+
26
+ /** Each row a look saw, by eid, and a digest of what it held. */
27
+ export type Seen = Record<string, string>
28
+
29
+ /** How a watched query is read for a wake: over the graph the wake is kept
30
+ * in, unless its host reads one that is not `local` more widely. */
31
+ export type Watching = (
32
+ wake: Bundle,
33
+ watch: Watch,
34
+ ) => Bundle[] | Promise<Bundle[]>
35
+
36
+ /** The query a wake watches, or `undefined`. */
37
+ export let watchOf = (b: Bundle): Watch | undefined =>
38
+ (b[WATCH] ?? undefined) as Watch | undefined
39
+
40
+ let canon = (v: unknown): unknown =>
41
+ Array.isArray(v)
42
+ ? v.map(canon)
43
+ : v && typeof v == 'object'
44
+ ? Object.fromEntries(
45
+ Object.keys(v).filter((k) => !k.startsWith('$')).sort()
46
+ .map((k) => [k, canon((v as Record<string, unknown>)[k])]),
47
+ )
48
+ : v
49
+
50
+ let digest = async (row: Bundle) => {
51
+ let bytes = new TextEncoder().encode(JSON.stringify(canon(row)))
52
+ let hash = new Uint8Array(await crypto.subtle.digest('SHA-256', bytes))
53
+ return [...hash.slice(0, 8)].map((b) => b.toString(16).padStart(2, '0'))
54
+ .join('')
55
+ }
56
+
57
+ let SHOWN = 10
58
+ let WIDE = 600
59
+ let clipped = (row: Bundle) => {
60
+ let json = JSON.stringify(canon(row))
61
+ return json.length > WIDE ? json.slice(0, WIDE) + '…' : json
62
+ }
63
+
64
+ /**
65
+ * What `rows` say against what a watch saw before (`was`): what it sees now,
66
+ * and what changed in words, `''` when nothing did.
67
+ *
68
+ * ```ts
69
+ * import { assertEquals } from '@std/assert'
70
+ * import { look } from './watch.ts'
71
+ *
72
+ * let row = { entity: { eid: 'm1' }, meeting: { title: 'Road millage' } }
73
+ * let { seen, changes } = await look({}, [row])
74
+ * assertEquals(changes.split('\n')[0], 'What changed (1 new):')
75
+ * assertEquals((await look(seen, [row])).changes, '')
76
+ * ```
77
+ */
78
+ export let look = async (
79
+ was: Seen,
80
+ rows: Bundle[],
81
+ ): Promise<{ seen: Seen; changes: string }> => {
82
+ let now = new Map<string, { hash: string; row: Bundle }>()
83
+ for (let row of rows.slice(0, ROWS)) {
84
+ now.set(row.entity.eid, { hash: await digest(row), row })
85
+ }
86
+ let seen = Object.fromEntries([...now].map(([eid, n]) => [eid, n.hash]))
87
+ let added = [...now].filter(([eid]) => !(eid in was))
88
+ let edited = [...now].filter(([eid, n]) => eid in was && was[eid] != n.hash)
89
+ let left = Object.keys(was).filter((eid) => !now.has(eid))
90
+ if (!added.length && !edited.length && !left.length) {
91
+ return { seen, changes: '' }
92
+ }
93
+ let lines = [
94
+ ...added.map(([, n]) => `new: ${clipped(n.row)}`),
95
+ ...edited.map(([, n]) => `changed: ${clipped(n.row)}`),
96
+ ...left.map((eid) => `gone: ${eid}`),
97
+ ]
98
+ let counts = [
99
+ added.length && `${added.length} new`,
100
+ edited.length && `${edited.length} changed`,
101
+ left.length && `${left.length} gone`,
102
+ ].filter(Boolean).join(', ')
103
+ let more = lines.length - SHOWN
104
+ return {
105
+ seen,
106
+ changes: [
107
+ `What changed (${counts}):`,
108
+ ...lines.slice(0, SHOWN),
109
+ ...more > 0 ? [`and ${more} more`] : [],
110
+ ].join('\n'),
111
+ }
112
+ }
113
+
114
+ /**
115
+ * What `changes`, as `look` says them, counted: `1 new, 2 changed`, or
116
+ * nothing for other words.
117
+ *
118
+ * ```ts
119
+ * import { assertEquals } from '@std/assert'
120
+ * import { counted } from './watch.ts'
121
+ * assertEquals(counted('What changed (1 new, 2 gone):\nnew: {}'), '1 new, 2 gone')
122
+ * assertEquals(counted('Fixed it.'), undefined)
123
+ * ```
124
+ */
125
+ export let counted = (changes: string): string | undefined =>
126
+ changes.match(/^What changed \((.+)\):/)?.[1]
127
+
128
+ /** How long after a commit a stirred wake looks: commits inside it are one
129
+ * look, and one firing. */
130
+ export let SOON = 2_000
131
+
132
+ // How many times a wake another writer keeps moving is read before it is
133
+ // left as that writer put it.
134
+ let TRIES = 3
135
+
136
+ let iso = (t: number) => new Date(t).toISOString()
137
+
138
+ /**
139
+ * Something the watching wakes of `graph` read committed: each one `which`
140
+ * picks comes due `soon` after `now` (unless it is due sooner already), so
141
+ * the host's next `tick` reads its query again and fires it if its rows
142
+ * changed. Answers the soonest instant a stirred wake is due, in epoch ms,
143
+ * or null when `which` picks none.
144
+ *
145
+ * ```ts
146
+ * import { assertEquals } from '@std/assert'
147
+ * import { stir } from './watch.ts'
148
+ * import { store, T0, woken } from './testing.ts'
149
+ *
150
+ * let g = woken(store())
151
+ * await g.apply([{ entity: { eid: 'w' }, wake: {}, watch: { query: '.plant' } }])
152
+ * assertEquals(await stir(g, T0), T0 + 2_000)
153
+ * ```
154
+ */
155
+ export let stir = async (
156
+ graph: Pick<Graph, 'read' | 'apply'>,
157
+ now: number,
158
+ opts: { which?: (wake: Bundle) => boolean; soon?: number } = {},
159
+ ): Promise<number | null> => {
160
+ let by = now + (opts.soon ?? SOON)
161
+ let soonest: number | null = null
162
+ let watching = await graph.read(
163
+ '.watch&.wake&.fields=entity.eid,wake.at,watch.local',
164
+ )
165
+ for (let wake of watching) {
166
+ if (opts.which && !opts.which(wake)) continue
167
+ for (let tries = 1;; tries++) {
168
+ let at = (wake[WAKE] as { at?: string | null } | undefined)?.at
169
+ let due = at ? Date.parse(at) : NaN
170
+ if (due <= by) {
171
+ soonest = Math.min(soonest ?? due, due)
172
+ break
173
+ }
174
+ try {
175
+ await graph.apply([{
176
+ entity: wake.entity,
177
+ [WAKE]: { at: iso(by) },
178
+ $was: { [WAKE]: { at: token(at) } },
179
+ }], { now: iso(now) })
180
+ soonest = Math.min(soonest ?? by, by)
181
+ break
182
+ } catch (error) {
183
+ if (!(error instanceof Stale) || tries == TRIES) throw error
184
+ }
185
+ let [fresh] = await graph.read(
186
+ line`.entity.eid=${wake.entity.eid}&.fields=entity.eid,wake.at`,
187
+ )
188
+ if (!fresh) break
189
+ wake = fresh
190
+ }
191
+ }
192
+ return soonest
193
+ }