@yaks/effects 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 (101) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +979 -2
  3. package/_dist/docs.d.ts +10 -0
  4. package/_dist/docs.d.ts.map +1 -0
  5. package/_dist/enqueue.d.ts +12 -0
  6. package/_dist/enqueue.d.ts.map +1 -0
  7. package/_dist/expire.d.ts +31 -0
  8. package/_dist/expire.d.ts.map +1 -0
  9. package/_dist/invocation.d.ts +36 -0
  10. package/_dist/invocation.d.ts.map +1 -0
  11. package/_dist/lease.d.ts +98 -0
  12. package/_dist/lease.d.ts.map +1 -0
  13. package/_dist/mod.d.ts +89 -0
  14. package/_dist/mod.d.ts.map +1 -0
  15. package/_dist/outage.d.ts +48 -0
  16. package/_dist/outage.d.ts.map +1 -0
  17. package/_dist/pool.d.ts +148 -0
  18. package/_dist/pool.d.ts.map +1 -0
  19. package/_dist/provisional.d.ts +8 -0
  20. package/_dist/provisional.d.ts.map +1 -0
  21. package/_dist/ready.d.ts +3 -0
  22. package/_dist/ready.d.ts.map +1 -0
  23. package/_dist/registration.d.ts +17 -0
  24. package/_dist/registration.d.ts.map +1 -0
  25. package/_dist/registry.d.ts +153 -0
  26. package/_dist/registry.d.ts.map +1 -0
  27. package/_dist/tools.d.ts +21 -0
  28. package/_dist/tools.d.ts.map +1 -0
  29. package/_dist/trace.d.ts +63 -0
  30. package/_dist/trace.d.ts.map +1 -0
  31. package/_dist/views.d.ts +15 -0
  32. package/_dist/views.d.ts.map +1 -0
  33. package/_dist/vocab.d.ts +11 -0
  34. package/_dist/vocab.d.ts.map +1 -0
  35. package/_dist/worker.d.ts +19 -0
  36. package/_dist/worker.d.ts.map +1 -0
  37. package/_dist/write.d.ts +25 -0
  38. package/_dist/write.d.ts.map +1 -0
  39. package/cleanup.js +75 -0
  40. package/cleanup.js.map +1 -0
  41. package/cleanup.ts +83 -0
  42. package/deno.json +1 -0
  43. package/docs.js +13 -0
  44. package/docs.js.map +1 -0
  45. package/docs.ts +13 -0
  46. package/enqueue.js +71 -0
  47. package/enqueue.js.map +1 -0
  48. package/enqueue.ts +86 -0
  49. package/expire.js +225 -0
  50. package/expire.js.map +1 -0
  51. package/expire.ts +244 -0
  52. package/invocation.js +245 -0
  53. package/invocation.js.map +1 -0
  54. package/invocation.ts +250 -0
  55. package/lease.js +343 -0
  56. package/lease.js.map +1 -0
  57. package/lease.ts +444 -0
  58. package/mod.js +89 -0
  59. package/mod.js.map +1 -0
  60. package/mod.ts +92 -0
  61. package/outage.js +77 -0
  62. package/outage.js.map +1 -0
  63. package/outage.ts +84 -0
  64. package/package.json +52 -4
  65. package/page.js +315 -0
  66. package/page.js.map +1 -0
  67. package/page.ts +524 -0
  68. package/pool.js +1474 -0
  69. package/pool.js.map +1 -0
  70. package/pool.ts +1635 -0
  71. package/provisional.js +20 -0
  72. package/provisional.js.map +1 -0
  73. package/provisional.ts +26 -0
  74. package/ready.js +48 -0
  75. package/ready.js.map +1 -0
  76. package/ready.ts +93 -0
  77. package/registration.js +21 -0
  78. package/registration.js.map +1 -0
  79. package/registration.ts +43 -0
  80. package/registry.js +872 -0
  81. package/registry.js.map +1 -0
  82. package/registry.ts +1196 -0
  83. package/tools.js +182 -0
  84. package/tools.js.map +1 -0
  85. package/tools.ts +229 -0
  86. package/trace.js +167 -0
  87. package/trace.js.map +1 -0
  88. package/trace.ts +217 -0
  89. package/views.js +18 -0
  90. package/views.js.map +1 -0
  91. package/views.ts +18 -0
  92. package/vocab.js +18 -0
  93. package/vocab.js.map +1 -0
  94. package/vocab.json +364 -0
  95. package/vocab.ts +20 -0
  96. package/worker.js +114 -0
  97. package/worker.js.map +1 -0
  98. package/worker.ts +146 -0
  99. package/write.js +38 -0
  100. package/write.js.map +1 -0
  101. package/write.ts +60 -0
package/registry.js ADDED
@@ -0,0 +1,872 @@
1
+ // The registry: what a commit owes, what this process watches, and what
2
+ // running either means.
3
+ //
4
+ // Two kinds of registration meet here, and the difference is who knows about
5
+ // them.
6
+ //
7
+ // An effect is declared in a vocabulary (`effect: true`, @yaks/vocab
8
+ // `effectsIn`), so every process that loads the vocabulary knows what a
9
+ // write can owe. The code that runs one is registered under its name, by a
10
+ // process that runs effects (`handle`). Where the vocabulary declares the
11
+ // `effect` component, a commit writes runs only for registered handlers (or,
12
+ // in a process that writes for another to run, `owes: 'declared'`, for every
13
+ // declared effect) into the graph in its own transaction, and any process
14
+ // working the pool claims it and runs it (./pool.ts). Where it does not,
15
+ // there is no pool to hand one to, and a handled effect runs here after the
16
+ // commit.
17
+ //
18
+ // An observer is registered at runtime (`created`, `changed`, `removed`,
19
+ // `on`), so only the process that registered it knows it: it runs in that
20
+ // process, after that process's own commits, at most once. A view refreshing
21
+ // what it shows is an observer.
22
+ //
23
+ // Both are slots — a component name, one of the things that can happen to it,
24
+ // and (for a change) the properties that have to have moved — or a pattern, a
25
+ // query run wherever the batch just made it true. `-comp` (@yaks/query) means
26
+ // a batch removed a component, so `removed('post')` is `on('-post')`, and a
27
+ // pattern with no other clause folds back into the removal event it describes
28
+ // (`solo` below): an event already reports exactly that, cascaded casualties
29
+ // included.
30
+ //
31
+ // Two rules hold, and they are the reason effects are a separate phase:
32
+ //
33
+ // Post-commit only. A run is written in the transaction that owes it and
34
+ // started once that transaction commits, and an observer runs after it; what
35
+ // they read is settled and nothing they do can reject the write. A batch
36
+ // that was refused owes nothing.
37
+ //
38
+ // Isolated. Every handler runs inside its own try — a throw, or a rejected
39
+ // promise, is passed to `report` and the next handler still runs.
40
+ //
41
+ // A handler that writes is handed the write callback (./write.ts), which puts
42
+ // its bundles through the graph's own `apply()` as a new batch. The loop that
43
+ // invites is stopped by the generation number that callback sets and this file
44
+ // reads, never by a rule each handler has to remember.
45
+ import { after, each, isPromise, over } from "@yaks/fp";
46
+ import { during, link, peek, unlink } from "@yaks/trace";
47
+ import { asked, match, reads } from "@yaks/graph/declared";
48
+ import { boundArgs, effectEid, invocationOf } from "./invocation.js";
49
+ import { writers } from "@yaks/graph/provenance";
50
+ import { filter } from "@yaks/match";
51
+ import { and, bare, fields, limit, list, ne, parse } from "@yaks/query";
52
+ import { effectsIn, namespaceOf } from "@yaks/vocab";
53
+ import { reworded, rewordedPath } from "@yaks/query";
54
+ import { BEFORE, before, events, strip, wanting } from "./trace.js";
55
+ import { generation, marked, ORIGIN, unmark } from "./write.js";
56
+ import { settleStale } from "./cleanup.js";
57
+ import { owing } from "./enqueue.js";
58
+ import { describe } from "./registration.js";
59
+ import { EFFECT, pool } from "./pool.js";
60
+ /**
61
+ * A `fifo` effect's handler that orders its queue by `rank`.
62
+ *
63
+ * ```ts ignore
64
+ * fx.handle({ start: ranked(starting, (runs) => urgency(runs)) })
65
+ * ```
66
+ */ export let ranked = (run, rank)=>Object.assign(run, {
67
+ rank
68
+ });
69
+ let rankOf = (run)=>'rank' in run && typeof run.rank == 'function' ? run.rank : undefined;
70
+ let warn = (err, { handler })=>console.warn(`effect ${handler} failed —`, err);
71
+ // A run a bundle writes that is due now and that nobody holds: pending, with
72
+ // no claim and no backoff. A claim, a renewal, a backoff or a deferral is not.
73
+ let unheld = (b)=>{
74
+ let run = b[EFFECT];
75
+ return run?.state == 'pending' && !run.lease_owner && !run.next;
76
+ };
77
+ // Whether a slot is watching for this event. A pattern slot watches no single
78
+ // event: its query is run against the graph instead (see `hits`).
79
+ let watching = (s, e)=>s.kind != 'matched' && s.comp == e.name && s.kind == e.kind && (s.kind != 'changed' || !s.props || !!e.comp && s.props.some((p)=>p in e.comp));
80
+ // What a pattern is about, in one component name: the first component it
81
+ // requires. It names an observer's slot and rides on the event.
82
+ let about = (plan)=>{
83
+ for (let p of plan.patterns){
84
+ for (let c of p.filter.clauses){
85
+ if (c.kind == 'pred' && c.op == '!' && c.path.length == 1 && !c.value) {
86
+ return c.path[0];
87
+ }
88
+ }
89
+ }
90
+ return gone(plan)[0] ?? plan.patterns[0]?.entity ?? 'match';
91
+ };
92
+ // Every `-comp` a plan names: the components it requires this batch to have
93
+ // removed.
94
+ let gone = (plan)=>{
95
+ let out = [];
96
+ let walk = (cs)=>{
97
+ for (let c of cs){
98
+ if (c.kind == 'gone') out.push(c.comp);
99
+ else if (c.kind == 'and' || c.kind == 'or') walk(c.clauses);
100
+ }
101
+ };
102
+ for (let p of plan.patterns)walk(p.filter.clauses);
103
+ return out;
104
+ };
105
+ // A pattern whose only clause is `-comp`, and the component it names — which
106
+ // is exactly what a removal event already reports, so it is registered as
107
+ // that event. Anything larger is a question only a batch overlay can answer.
108
+ let solo = (plan)=>{
109
+ if (plan.patterns.length != 1 || plan.collections.length) return;
110
+ let [p] = plan.patterns;
111
+ let [c] = p.filter.clauses;
112
+ return p.filter.clauses.length == 1 && c.kind == 'gone' && !p.entity && !p.binds.length && !p.gates.length && !p.ensures.length && !p.writes.length ? c.comp : undefined;
113
+ };
114
+ /**
115
+ * A registry of post-commit effects and observers, as a plugin:
116
+ *
117
+ * ```ts
118
+ * import { graph } from '@yaks/graph'
119
+ * import { loadVocab } from '@yaks/vocab'
120
+ * import { ram } from '@yaks/ram'
121
+ * import { effects } from '@yaks/effects'
122
+ *
123
+ * let title = { type: 'string' }
124
+ * let vocab = loadVocab([{
125
+ * $defs: {
126
+ * post: { component: true, properties: { title } },
127
+ * send_receipt: { effect: true, created: ['post'] },
128
+ * },
129
+ * }])
130
+ * let fx = effects(vocab)
131
+ * let g = graph({ storage: ram(vocab), vocab, plugins: [fx] })
132
+ *
133
+ * fx.handle({ send_receipt: (e) => console.log('mail', e.entity.eid) })
134
+ * fx.created('post', (e) => console.log('a post appeared', e.comp?.title))
135
+ * g.apply([{ entity: { eid: 'p1' }, post: { title: 'Hello' } }])
136
+ * ```
137
+ *
138
+ * It requires the loaded vocabulary: the effects it declares are what a commit
139
+ * owes, and knowing what a cascade will delete — and therefore which
140
+ * components a casualty carried — is a question only a vocabulary can answer.
141
+ */ export let effects = (vocab, opts = {})=>{
142
+ let slots = [];
143
+ let report = (err, job)=>{
144
+ try {
145
+ ;
146
+ (opts.report ?? warn)(err, job);
147
+ } catch (e) {
148
+ console.warn('effect reporting failed —', e);
149
+ }
150
+ };
151
+ let depth = opts.depth ?? 2;
152
+ let disabled = new Set(opts.disabled);
153
+ let TARGETS = '$effectTargets';
154
+ // Stored local facts are already gathered by this transaction. Anything
155
+ // needing another entity or a computed read stays with the storage reader.
156
+ let local = (c)=>{
157
+ if (c.kind == 'and' || c.kind == 'or') return c.clauses.every(local);
158
+ if (c.kind != 'pred' || c.where || c.not) return false;
159
+ // A reverse association reads the entities that point here.
160
+ if (!vocab.comp(c.path[0]) && vocab.assoc(c.path[0])) return false;
161
+ let hops = vocab.aim(c.path.join('.'), bare(c)), h = hops[0];
162
+ if (hops.length != 1 || !h || vocab.comp(h.comp)?.computed) return false;
163
+ let prop = h.prop && vocab.prop(h.comp, h.prop);
164
+ let absent = c.value?.kind == 'scalar' && c.value.raw == '';
165
+ return !prop || !prop.computed && prop.scalar != 'time' && (!prop.ref || !c.value || absent);
166
+ };
167
+ let targets = new Map();
168
+ let target = (query)=>{
169
+ if (targets.has(query)) return targets.get(query);
170
+ let plan = asked(match(query), vocab);
171
+ if (plan && (plan.patterns.length != 1 || plan.collections.length)) {
172
+ throw new Error('an effect target must be a single-entity query');
173
+ }
174
+ let where = plan?.patterns[0].filter;
175
+ let made = !plan || !where ? null : local(where) ? {
176
+ local: true,
177
+ comps: reads(plan, vocab),
178
+ test: filter(where, vocab)
179
+ } : {
180
+ local: false,
181
+ read: {
182
+ ...where,
183
+ clauses: [
184
+ ...where.clauses,
185
+ fields('entity.eid')
186
+ ]
187
+ }
188
+ };
189
+ targets.set(query, made);
190
+ return made;
191
+ };
192
+ // Restrict scope reads to the batch's subjects, never the whole graph.
193
+ let subjects = (query, eids, tx)=>{
194
+ let t = target(query);
195
+ if (!t || !eids.length) return [];
196
+ if (t.local) {
197
+ let { test } = t;
198
+ return after(tx.get(eids, t.comps), (rows)=>rows.filter((b)=>test(b)).map((b)=>b.entity.eid));
199
+ }
200
+ return after(tx.read(t.read, {
201
+ eids
202
+ }), (rows)=>rows.map((b)=>b.entity.eid));
203
+ };
204
+ let scoped = (bundles, tx)=>{
205
+ if (!slots.some((s)=>!disabled.has(s.id) && s.effect?.target)) {
206
+ return bundles;
207
+ }
208
+ let prior = bundles[0]?.[BEFORE] ?? {};
209
+ let batch = new Set(bundles.map((b)=>b.entity.eid));
210
+ // What dies with the batch is not in it until the write runs, so it is
211
+ // read as deleted here: a target scopes a casualty by what it was.
212
+ let doomed = Object.keys(prior).filter((eid)=>!batch.has(eid));
213
+ let eids = [
214
+ ...batch,
215
+ ...doomed
216
+ ];
217
+ let seen = events([
218
+ ...bundles,
219
+ ...doomed.map((eid)=>({
220
+ entity: {
221
+ eid
222
+ },
223
+ $delete: true
224
+ }))
225
+ ]);
226
+ let queries = [
227
+ ...new Set(slots.filter((s)=>!disabled.has(s.id) && // The graph adds created/updated after this precondition, so an
228
+ // input event cannot yet say which stamp trigger will fire.
229
+ (s.comp == 'created' || s.comp == 'updated' || s.kind == 'matched' && s.watch?.some((c)=>c == 'created' || c == 'updated') || seen.some((e)=>watching(s, e) || s.kind == 'matched' && s.watch?.includes(e.name)))).map((s)=>s.effect?.target).filter((q)=>!!q))
230
+ ];
231
+ if (!queries.length) return bundles;
232
+ return after(each(queries, {}, (out, query)=>after(subjects(query, eids, tx), (found)=>{
233
+ out[query] = found;
234
+ return out;
235
+ })), (targets)=>bundles.map((b)=>({
236
+ ...b,
237
+ [TARGETS]: targets
238
+ })));
239
+ };
240
+ // The write callback as one run sees it: whatever it writes is marked a
241
+ // generation on from the batch that owed it.
242
+ let writer = (gen, context)=>(bundles)=>{
243
+ if (!opts.write) {
244
+ throw new Error('this effect asked to write and no write door is registered — ' + 'effects(vocab, { write: (b) => graph.apply(b, { trusted: true }) })');
245
+ }
246
+ let tagged = marked(bundles, gen + 1);
247
+ if (!context?.parent || !peek(context.graph)) return opts.write(tagged);
248
+ link(context.graph, tagged, context.parent);
249
+ let clean = ()=>unlink(context.graph, tagged);
250
+ try {
251
+ let out = opts.write(tagged);
252
+ if (isPromise(out)) return out.finally(clean);
253
+ clean();
254
+ return out;
255
+ } catch (error) {
256
+ clean();
257
+ throw error;
258
+ }
259
+ };
260
+ let name = (comp, kind, prop)=>{
261
+ let base = prop ? `${comp}.${kind}.${prop}` : `${comp}.${kind}`;
262
+ let taken = slots.filter((s)=>s.id == base || s.id.startsWith(`${base}#`));
263
+ return taken.length ? `${base}#${taken.length + 1}` : base;
264
+ };
265
+ // A pattern, parsed here and narrowed to the components this vocabulary
266
+ // declares (@yaks/graph `asked`), so one pattern is correct in two graphs:
267
+ // one that requires a component this graph cannot store is registered and
268
+ // inert — listed, documented, never run.
269
+ let planned = (what)=>{
270
+ let written = typeof what == 'string' ? match(what) : what;
271
+ let plan = asked(written, vocab);
272
+ if (plan?.collections.length && !plan.patterns.length) {
273
+ throw new Error('a matched effect needs an outer entity');
274
+ }
275
+ let one = plan && solo(plan);
276
+ return one ? {
277
+ comp: one,
278
+ kind: 'removed'
279
+ } : {
280
+ comp: about(written),
281
+ kind: 'matched',
282
+ plan: plan ?? undefined,
283
+ watch: plan ? reads(plan, vocab) : [],
284
+ gone: plan ? gone(plan) : []
285
+ };
286
+ };
287
+ // The declared effects, one slot per trigger, all under the effect's name.
288
+ effectsIn(vocab.docs);
289
+ let declared = vocab.docs.flatMap((doc)=>{
290
+ let local = vocab.in(namespaceOf(doc));
291
+ return effectsIn(doc).map((effect)=>{
292
+ if (local === vocab) return effect;
293
+ for (let key of [
294
+ 'created',
295
+ 'changed',
296
+ 'removed'
297
+ ]){
298
+ if (effect[key]) {
299
+ effect[key] = effect[key].map((path)=>rewordedPath(path, local, vocab));
300
+ }
301
+ }
302
+ for (let key of [
303
+ 'match',
304
+ 'target',
305
+ 'eligible',
306
+ 'active'
307
+ ]){
308
+ if (effect[key]) effect[key] = reworded(effect[key], local, vocab);
309
+ }
310
+ return effect;
311
+ });
312
+ });
313
+ let callable = new Map(declared.filter((e)=>e.call).map((e)=>[
314
+ e.name,
315
+ e
316
+ ]));
317
+ let addresses = [
318
+ ...callable.keys()
319
+ ].map(effectEid);
320
+ for (let effect of declared){
321
+ let query = effect.eligible;
322
+ let eligible = query ? (eid, tx)=>after(subjects(query, [
323
+ eid
324
+ ], tx), (found)=>!!found.length) : undefined;
325
+ let operation = effect.owe ? callable.get(effect.owe) : undefined;
326
+ // Some hosts select only the words they serve.
327
+ if (effect.owe && !operation) continue;
328
+ let at = (s)=>slots.push({
329
+ ...s,
330
+ id: operation?.name ?? effect.name,
331
+ effect: operation ? {
332
+ ...operation,
333
+ target: effect.target,
334
+ active: effect.active,
335
+ eligible: effect.eligible
336
+ } : effect,
337
+ ...operation ? {
338
+ declaration: effect.name,
339
+ invocation: effect.args ?? {}
340
+ } : {},
341
+ eligible,
342
+ doc: effect.description
343
+ });
344
+ for (let comp of effect.created ?? [])at({
345
+ comp,
346
+ kind: 'created'
347
+ });
348
+ let changed = new Map();
349
+ for (let said of effect.changed ?? []){
350
+ let [comp, prop] = said.split('.');
351
+ let props = changed.has(comp) ? changed.get(comp) : [];
352
+ changed.set(comp, prop && props ? [
353
+ ...props,
354
+ prop
355
+ ] : undefined);
356
+ }
357
+ for (let [comp, props] of changed)at({
358
+ comp,
359
+ kind: 'changed',
360
+ props
361
+ });
362
+ for (let comp of effect.removed ?? [])at({
363
+ comp,
364
+ kind: 'removed'
365
+ });
366
+ if (effect.match) {
367
+ let slot = planned(effect.match);
368
+ if (effect.call === false && addresses.length && 'plan' in slot && slot.plan) {
369
+ let [subject, ...rest] = slot.plan.patterns;
370
+ let filter = and(...subject.filter.clauses, ne('call.to', list(...addresses)));
371
+ slot = {
372
+ ...slot,
373
+ plan: {
374
+ ...slot.plan,
375
+ patterns: [
376
+ {
377
+ ...subject,
378
+ filter
379
+ },
380
+ ...rest
381
+ ]
382
+ }
383
+ };
384
+ }
385
+ at(slot);
386
+ }
387
+ if (effect.call && vocab.comp('call') && vocab.comp('result')) {
388
+ let to = `.call.to=${effectEid(effect.name)}, !execution, !results, !interrupted, !cut`;
389
+ at({
390
+ ...planned(`*call, ${to}, !wake`),
391
+ invocation: true
392
+ });
393
+ if (vocab.comp('wake') && vocab.comp('fired')) {
394
+ at({
395
+ ...planned(`*fired, ${to}, .wake`),
396
+ invocation: true
397
+ });
398
+ }
399
+ }
400
+ // Start-up work: owed by a worker joining the pool (./pool.ts), and by
401
+ // no commit, so its slot watches nothing.
402
+ if (effect.start) at({
403
+ comp: '',
404
+ kind: 'started'
405
+ });
406
+ }
407
+ let observe = (s, id)=>{
408
+ slots.push({
409
+ ...s,
410
+ id
411
+ });
412
+ return fx;
413
+ };
414
+ let add = (comp, kind, run, prop, policy = {}, group)=>observe({
415
+ ...policy,
416
+ group,
417
+ comp,
418
+ kind,
419
+ props: prop ? [
420
+ prop
421
+ ] : undefined,
422
+ run
423
+ }, name(comp, kind, prop));
424
+ let pattern = (what, run, policy, group)=>{
425
+ let s = planned(what);
426
+ return observe({
427
+ ...policy,
428
+ group,
429
+ ...s,
430
+ run
431
+ }, name(s.comp, s.kind));
432
+ };
433
+ // Did this batch touch anything a pattern reads?
434
+ let stirred = (s, seen)=>seen.some((e)=>s.watch?.includes(e.name));
435
+ // A pattern's bindings, narrowed to this batch: a result row is kept where
436
+ // the batch touched any entity it bound, so a run is owed for what just
437
+ // happened rather than for every row that has matched all along.
438
+ let hits = (s, bundles, seen, tx)=>{
439
+ let plan = s.plan;
440
+ let touched = new Set(bundles.map((b)=>b.entity.eid));
441
+ let one = plan.patterns.filter((p)=>!p.makes);
442
+ // A *component clause anchors the match to a write of that component on
443
+ // the bound entity. The same match without a write clause uses any touch.
444
+ let written;
445
+ if (one.some((p)=>p.writes.length)) {
446
+ written = new Map();
447
+ for (let e of seen){
448
+ if (e.kind == 'removed') continue;
449
+ let names = written.get(e.entity.eid) ?? new Set();
450
+ names.add(e.name);
451
+ written.set(e.entity.eid, names);
452
+ }
453
+ }
454
+ let anchors = (eid, writes)=>written ? writes.some((name)=>written.get(eid)?.has(name)) : touched.has(eid);
455
+ // The batch is passed to the query only where the query is about it: a
456
+ // `-comp` clause reads the deletions a storage's overlay carries.
457
+ let pending = s.gone?.length ? bundles : [];
458
+ if (one.length > 1 || plan.collections.length || plan.patterns.some((p)=>p.binds.length) || s.gone?.length) {
459
+ if (!tx.bindings) {
460
+ throw new Error(`effect ${s.id} asks about more than one entity, or about what ` + 'this batch removed, and this storage answers no bindings — a ' + 'one-entity pattern over committed rows is all it can be asked');
461
+ }
462
+ return after(tx.bindings([
463
+ plan
464
+ ], pending, s.watch), ([rows])=>rows.filter((r)=>r.entities.some((e, i)=>e && anchors(e, plan.patterns[i].writes))).map((r)=>({
465
+ kind: 'matched',
466
+ // The subject: the first entity the match bound.
467
+ entity: {
468
+ eid: r.entities.find((e)=>!!e)
469
+ },
470
+ name: s.comp,
471
+ vars: r.vars,
472
+ binding: r
473
+ })));
474
+ }
475
+ // Asked about the entities this batch touched and no others: an index
476
+ // lookup, not a scan with the batch picked out afterwards.
477
+ let { filter, writes } = one[0];
478
+ let eids = [
479
+ ...touched
480
+ ].filter((eid)=>anchors(eid, writes));
481
+ if (!eids.length) return [];
482
+ return after(tx.read(filter, {
483
+ eids
484
+ }), (rows)=>rows.map((b)=>({
485
+ kind: 'matched',
486
+ entity: b.entity,
487
+ name: s.comp,
488
+ comp: b[s.comp]
489
+ })));
490
+ };
491
+ // What this batch did for the slots `which` selects: one pair per slot and
492
+ // event, the created/changed/removed ones first, then the patterns. A
493
+ // pattern this storage cannot answer is reported, never a failed batch.
494
+ let matched = (bundles, tx, which)=>{
495
+ let chosen = slots.filter(which);
496
+ if (!chosen.length) return [];
497
+ let byComp = new Map();
498
+ for (let s of chosen){
499
+ if (s.kind == 'matched') continue;
500
+ let group = byComp.get(s.comp) ?? [];
501
+ group.push(s);
502
+ byComp.set(s.comp, group);
503
+ }
504
+ let seen = events(bundles);
505
+ let prior = bundles.find((b)=>b[BEFORE])?.[BEFORE] ?? {};
506
+ // A run is owed for what happened in the graph, never for the pool's own
507
+ // rows: an entity that wears `effect`, before this batch or in it, owes no
508
+ // declared effect a run. Otherwise a mark a settle writes (`completed`)
509
+ // would owe the runs that mark triggers, each of those would settle and
510
+ // owe more, and the depth never stops it, since a settle is generation 0.
511
+ let poolEids;
512
+ let inPool = (eid)=>{
513
+ if (!poolEids) {
514
+ poolEids = new Set();
515
+ for (let [eid, row] of Object.entries(prior)){
516
+ if (row[EFFECT] != null) poolEids.add(eid);
517
+ }
518
+ for (let b of bundles){
519
+ if (b[EFFECT] != null) poolEids.add(b.entity.eid);
520
+ }
521
+ }
522
+ return poolEids.has(eid);
523
+ };
524
+ let allowed = (s, e)=>!s.effect || !inPool(e.entity.eid);
525
+ // Who wrote each event's entity in this batch, carried on the event so a
526
+ // run can write on that commit's behalf (`Event.actor`).
527
+ let wrote = writers(bundles);
528
+ let touched;
529
+ let signing = (e, bound = false)=>{
530
+ if (bound) touched ??= new Set(bundles.map((b)=>b.entity.eid));
531
+ let source = bound ? e.binding?.entities.find((id)=>id && touched.has(id)) : undefined;
532
+ let { by, via } = wrote(source ?? e.entity.eid);
533
+ return by || via ? {
534
+ ...e,
535
+ actor: {
536
+ ...by ? {
537
+ by
538
+ } : {},
539
+ ...via ? {
540
+ via
541
+ } : {}
542
+ }
543
+ } : e;
544
+ };
545
+ let found = [];
546
+ for (let e of seen){
547
+ let group = byComp.get(e.name);
548
+ if (!group) continue;
549
+ for (let s of group){
550
+ if (watching(s, e) && allowed(s, e)) found.push([
551
+ s,
552
+ e
553
+ ]);
554
+ }
555
+ }
556
+ let asking = chosen.filter((s)=>s.kind == 'matched' && s.plan && stirred(s, seen));
557
+ let targets = new Map();
558
+ let priorTargets = bundles[0]?.[TARGETS] ?? {};
559
+ let matchesNow = (query, eid)=>{
560
+ if (!query) return true;
561
+ if (!targets.has(query)) {
562
+ targets.set(query, after(subjects(query, bundles.map((b)=>b.entity.eid), tx), (found)=>new Set(found)));
563
+ }
564
+ return after(targets.get(query), (found)=>found.has(eid));
565
+ };
566
+ let inScope = (s, { entity: { eid } })=>{
567
+ let { target, eligible } = s.effect ?? {};
568
+ let scoped = target && priorTargets[target]?.includes(eid) || matchesNow(target, eid);
569
+ return after(scoped, (yes)=>yes && matchesNow(eligible, eid));
570
+ };
571
+ let active = new Map();
572
+ let enabled = (s)=>{
573
+ let query = s.effect?.active;
574
+ if (!query) return true;
575
+ // Whether any entity matches, so one is all it reads: the matches of
576
+ // `.error .error.bug` are a store's every grouped error.
577
+ if (!active.has(query)) {
578
+ active.set(query, after(tx.read(and(...parse(query).clauses, limit(1))), (rows)=>rows.length > 0));
579
+ }
580
+ return active.get(query);
581
+ };
582
+ return after(each(asking, found, (out, s)=>{
583
+ try {
584
+ return after(hits(s, bundles, seen, tx), (evs)=>{
585
+ for (let e of evs)if (allowed(s, e)) out.push([
586
+ s,
587
+ e
588
+ ]);
589
+ return out;
590
+ });
591
+ } catch (err) {
592
+ report(err, {
593
+ handler: s.id,
594
+ slot: s
595
+ });
596
+ return out;
597
+ }
598
+ }), (hits)=>{
599
+ let kept = [];
600
+ return each(hits, kept, (out, pair)=>after(inScope(...pair), (scoped)=>scoped ? after(enabled(pair[0]), (yes)=>{
601
+ if (!yes) return out;
602
+ let [s, e] = pair;
603
+ let event = signing(e, !!s.invocation && s.invocation !== true);
604
+ if (s.invocation === true) {
605
+ let eid = e.entity.eid;
606
+ return after(tx.get([
607
+ eid
608
+ ]), ([call])=>{
609
+ if (call?.call) {
610
+ out.push([
611
+ s,
612
+ {
613
+ ...event,
614
+ invocation: invocationOf(call)
615
+ }
616
+ ]);
617
+ }
618
+ return out;
619
+ });
620
+ }
621
+ if (s.invocation) {
622
+ event = {
623
+ ...event,
624
+ invocation: {
625
+ args: boundArgs(s.invocation, e.vars ?? {}),
626
+ match: s.declaration
627
+ }
628
+ };
629
+ }
630
+ out.push([
631
+ s,
632
+ event
633
+ ]);
634
+ return out;
635
+ }) : out));
636
+ });
637
+ };
638
+ // One observer run, isolated.
639
+ let fire = (s, event, tx, write, gen, context, propagate = false)=>{
640
+ let failed = (err)=>{
641
+ report(err, {
642
+ handler: s.id,
643
+ event,
644
+ slot: s
645
+ });
646
+ if (propagate) throw err;
647
+ };
648
+ try {
649
+ let c = context && peek(context.graph);
650
+ let out;
651
+ if (!c) out = s.run(event, tx, write);
652
+ else {
653
+ let span = c.begin({
654
+ kind: 'effect',
655
+ name: s.id,
656
+ package: '@yaks/effects',
657
+ plugin: opts.name,
658
+ parent: context.parent
659
+ });
660
+ out = during(span, ()=>s.run(event, tx, writer(gen, {
661
+ graph: context.graph,
662
+ parent: span?.id
663
+ })));
664
+ }
665
+ return isPromise(out) ? out.then(()=>null, failed) : null;
666
+ } catch (err) {
667
+ return failed(err);
668
+ }
669
+ };
670
+ // The pool, where this vocabulary keeps effect rows.
671
+ let pooled = vocab.comp(EFFECT) ? pool({
672
+ slots: ()=>slots,
673
+ writer,
674
+ report
675
+ }, opts) : undefined;
676
+ // What this process runs itself after a commit: every observer, and a
677
+ // handled effect where there is no pool to hand it to.
678
+ let here = (s)=>!!s.run && (!s.effect || !pooled);
679
+ // The transaction that claimed work carries it through post-commit hooks,
680
+ // even when another hook replaces a bundle while canonicalizing its actor.
681
+ // Standalone hooks without a transaction context retain their bundle key.
682
+ let owed = new WeakMap();
683
+ let left = new WeakSet();
684
+ // Inside the transaction: the runs this batch owes, written down.
685
+ let owesAll = opts.owes == 'declared';
686
+ // Declarations without a pool or handler cannot observe a commit. Read this
687
+ // afresh, since a caller can register handlers after building the graph.
688
+ let watches = ()=>slots.some((s)=>!!s.run || !!pooled && owesAll && !!s.effect);
689
+ let owe = (bundles, tx, _err, context)=>{
690
+ // A run written down outright (`enqueue`, a retry) is due and nobody
691
+ // holds it. The store hears only other processes' commits (`watch`), so
692
+ // it is left work, as a run a slot owed and this worker could not claim.
693
+ if (bundles.some(unheld)) left.add(context?.transaction ?? bundles[0]);
694
+ if (generation(bundles) > depth) return bundles;
695
+ // A pool row owes no declared component event. Patterns still inspect
696
+ // the batch: a join can match a different, non-pool subject.
697
+ if (bundles.every((b)=>b[EFFECT] != null) && !slots.some((s)=>s.effect && s.kind == 'matched')) return bundles;
698
+ return after(matched(bundles, tx, (s)=>!!s.effect && !disabled.has(s.id) && !disabled.has(s.declaration ?? '') && (owesAll || !!s.run)), (found)=>!found.length ? bundles : after(pooled.owe(tx, found, generation(bundles)), (mine)=>{
699
+ let c = context && peek(context.graph);
700
+ if (c) {
701
+ for (let [s] of found){
702
+ c.instant({
703
+ kind: 'effect',
704
+ name: s.id,
705
+ package: '@yaks/effects',
706
+ plugin: opts.name,
707
+ parent: context.parent
708
+ }, {
709
+ counts: {
710
+ owed: 1
711
+ }
712
+ });
713
+ }
714
+ for (let run of mine){
715
+ if (context.parent) link(context.graph, run, context.parent);
716
+ }
717
+ }
718
+ let key = context?.transaction ?? bundles[0];
719
+ if (mine.length) owed.set(key, mine);
720
+ if (mine.length < found.length) left.add(key);
721
+ return bundles;
722
+ }));
723
+ };
724
+ // After the commit: the runs this process claimed as it wrote them are
725
+ // started, and every observer runs.
726
+ let effect = (bundles, tx, _err, context)=>{
727
+ let key = context?.transaction ?? bundles[0];
728
+ let mine = key && owed.get(key);
729
+ let clean = ()=>{
730
+ for (let b of bundles)delete b[TARGETS];
731
+ return unmark(strip(bundles));
732
+ };
733
+ if (mine) {
734
+ owed.delete(key);
735
+ pooled.start(mine);
736
+ }
737
+ // A run a hook owed in the transaction (./enqueue.ts `owe`) is left work
738
+ // as a run written in the batch is.
739
+ if (key && (left.delete(key) || mine?.length || pooled && owing.has(key))) {
740
+ // The local worker may be asleep after an empty pass. A host nudge
741
+ // notifies other workers, but cannot wake this registry's own pool.
742
+ pooled.wake();
743
+ opts.nudge?.();
744
+ }
745
+ let gen = generation(bundles);
746
+ if (gen > depth || !slots.some(here)) return clean();
747
+ let write = writer(gen);
748
+ return after(after(matched(bundles, tx, here), (found)=>over(found, ([s, e])=>{
749
+ let c = context && peek(context.graph);
750
+ if (c) {
751
+ c.instant({
752
+ kind: 'effect',
753
+ name: s.id,
754
+ package: '@yaks/effects',
755
+ plugin: opts.name,
756
+ parent: context.parent
757
+ }, {
758
+ counts: {
759
+ owed: 1
760
+ }
761
+ });
762
+ }
763
+ return fire(s, e, tx, write, gen, context);
764
+ })), clean);
765
+ };
766
+ // A host without pool rows still owes its declared starts. Their writes
767
+ // use the same generation boundary as effects after a commit; a failed
768
+ // start rejects so the host cannot record its deployment as complete.
769
+ let starter = opts.owner;
770
+ let startup = async (g)=>{
771
+ if (pooled) return pooled.startup(g);
772
+ let entity = {
773
+ eid: starter ??= crypto.randomUUID()
774
+ };
775
+ for (let s of slots){
776
+ if (s.kind != 'started' || !s.run) continue;
777
+ await fire(s, {
778
+ kind: 'started',
779
+ entity,
780
+ name: ''
781
+ }, g.outside, writer(0), 0, undefined, true);
782
+ }
783
+ };
784
+ let fx = {
785
+ name: opts.name ?? '@yaks/effects',
786
+ namespace: null,
787
+ admission: ()=>true,
788
+ // The generation counter an effect's own write carries (write.ts `ORIGIN`)
789
+ // comes back in through `apply()` like any other request, so this plugin
790
+ // declares it.
791
+ requests: [
792
+ ORIGIN
793
+ ],
794
+ hooks: {
795
+ // Read the state the batch is about to change, while it still stands.
796
+ precondition: (bundles, tx)=>watches() ? after(before(vocab)(bundles, tx), (prepared)=>scoped(prepared, tx)) : bundles,
797
+ ...pooled ? {
798
+ commit: owe
799
+ } : {},
800
+ effect
801
+ },
802
+ // Nothing is read while nothing is registered, so nothing is asked for.
803
+ wants: (bundles)=>[
804
+ ...watches() ? wanting(vocab)(bundles) : [],
805
+ ...[
806
+ ...new Set(slots.map((s)=>s.wants))
807
+ ].flatMap((wants)=>wants?.(bundles) ?? [])
808
+ ],
809
+ created: (comp, run, policy)=>add(comp, 'created', run, undefined, policy),
810
+ changed: (comp, prop, run, policy)=>typeof prop == 'string' ? add(comp, 'changed', run, prop, policy) : add(comp, 'changed', prop, undefined, policy),
811
+ removed: (comp, run, policy = {})=>pattern(`-${comp}`, run, policy),
812
+ on: (what, second, policy = {})=>{
813
+ if (typeof second == 'function') return pattern(what, second, policy);
814
+ let { created, changed, removed, ...rest } = second;
815
+ let comp = what;
816
+ let group = `on:${slots.length}`;
817
+ if (created) add(comp, 'created', created, undefined, rest, group);
818
+ for (let [prop, run] of Object.entries(changed ?? {})){
819
+ add(comp, 'changed', run, prop, rest, group);
820
+ }
821
+ if (removed) pattern(`-${comp}`, removed, rest, group);
822
+ return fx;
823
+ },
824
+ handle: (handlers)=>{
825
+ for (let [id, run] of Object.entries(handlers)){
826
+ let mine = slots.filter((s)=>s.effect && s.id == id);
827
+ if (!mine.length) throw new Error(`no effect is declared as ${id}`);
828
+ if (disabled.has(id)) continue;
829
+ for (let s of mine)Object.assign(s, {
830
+ run,
831
+ rank: rankOf(run)
832
+ });
833
+ }
834
+ return fx;
835
+ },
836
+ slots: ()=>[
837
+ ...slots
838
+ ],
839
+ settle: (g, handler)=>{
840
+ let declared = slots.filter((s)=>s.effect && s.id == handler);
841
+ if (!declared.length) {
842
+ throw new Error(`no effect is declared as ${handler}`);
843
+ }
844
+ return settleStale(g, handler, async (row)=>{
845
+ if (disabled.has(handler)) return false;
846
+ let candidates = declared.filter((s)=>s.kind == row.kind && (s.kind == 'started' || s.comp == row.comp));
847
+ if (!candidates.length) return false;
848
+ let eligible = candidates[0].eligible;
849
+ if (eligible && !await eligible(String(row.target), g.outside)) {
850
+ return false;
851
+ }
852
+ // A removal's old scope is not recorded; preserve it conservatively.
853
+ if (row.kind == 'removed') return true;
854
+ let query = candidates[0].effect?.target;
855
+ return !query || (await subjects(query, [
856
+ String(row.target)
857
+ ], g.outside)).length > 0;
858
+ });
859
+ },
860
+ docs: ()=>describe(slots),
861
+ startup,
862
+ work: (g, signal, options)=>pooled?.work(g, signal, options) ?? (typeof options == 'object' && options.startup ? startup(g).then(()=>false) : Promise.resolve(false)),
863
+ wake: ()=>pooled?.wake(),
864
+ idle: ()=>pooled?.idle() ?? Promise.resolve(),
865
+ stop: ()=>pooled?.stop() ?? Promise.resolve(),
866
+ handoff: (at)=>pooled?.handoff(at) ?? Promise.resolve(),
867
+ running: ()=>pooled?.running() ?? [],
868
+ next: (g, now)=>pooled?.next(g, now) ?? Promise.resolve(null)
869
+ };
870
+ return fx;
871
+ };
872
+ //# sourceMappingURL=registry.js.map