@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.ts ADDED
@@ -0,0 +1,1196 @@
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
+
46
+ import type {
47
+ Access,
48
+ Bundle,
49
+ Comp,
50
+ Eid,
51
+ Hook,
52
+ HookContext,
53
+ Match,
54
+ Plugin,
55
+ ReadTx,
56
+ } from 'jsr:@yaks/graph@0.2.36'
57
+ import { after, each, isPromise, over } from '@yaks/fp'
58
+ import { during, link, peek, unlink } from '@yaks/trace'
59
+ import { asked, match, reads } from '@yaks/graph/declared'
60
+ import { boundArgs, effectEid, invocationOf } from './invocation.js'
61
+ import { writers } from '@yaks/graph/provenance'
62
+ import { filter } from '@yaks/match'
63
+ import {
64
+ type And,
65
+ and,
66
+ bare,
67
+ type Clause,
68
+ fields,
69
+ limit,
70
+ list,
71
+ ne,
72
+ parse,
73
+ } from '@yaks/query'
74
+ import {
75
+ type EffectDecl,
76
+ effectsIn,
77
+ namespaceOf,
78
+ type Vocab,
79
+ } from '@yaks/vocab'
80
+ import { reworded, rewordedPath } from '@yaks/query'
81
+ import {
82
+ BEFORE,
83
+ type Before,
84
+ before,
85
+ type Event,
86
+ events,
87
+ type Kind,
88
+ strip,
89
+ wanting,
90
+ } from './trace.js'
91
+ import { generation, marked, ORIGIN, unmark, type Write } from './write.js'
92
+ import { settleStale } from './cleanup.js'
93
+ import { owing } from './enqueue.js'
94
+ import {
95
+ describe,
96
+ type Description,
97
+ type Policy,
98
+ type Registration,
99
+ } from './registration.js'
100
+ import {
101
+ type Attempt,
102
+ EFFECT,
103
+ type Owed,
104
+ pool,
105
+ type PoolOpts,
106
+ type Run,
107
+ type WorkOpts,
108
+ } from './pool.js'
109
+ export type { Description, Policy, Registration } from './registration.js'
110
+
111
+ /** A post-commit handler: what happened, a detached transaction to read
112
+ * through, the callback to write through ({@link Write}), and, for a run the
113
+ * pool claimed, which attempt it is ({@link Attempt}). Its return value is
114
+ * awaited when it is a promise. */
115
+ export type Handler = (
116
+ event: Event,
117
+ tx: ReadTx,
118
+ write: Write,
119
+ attempt?: Attempt,
120
+ ) => unknown
121
+
122
+ type DeclaredHandler = Handler & {
123
+ /** A dependency this process knows is still unavailable. Runs deferred
124
+ * with this reason stay pending without being claimed again. */
125
+ waiting?: () => string | undefined
126
+ }
127
+
128
+ /** Where a `fifo` effect's pending runs stand in its queue: a number for each
129
+ * run, read whenever the queue's head is chosen. The lowest goes first; runs
130
+ * ranked alike, or not at all, go oldest first. */
131
+ export type Rank = (
132
+ runs: Bundle[],
133
+ tx: ReadTx,
134
+ ) => Promise<(number | undefined)[]>
135
+
136
+ /** The code for declared effects, by the name each is declared under. */
137
+ export type Handlers = Record<string, DeclaredHandler>
138
+
139
+ /**
140
+ * A `fifo` effect's handler that orders its queue by `rank`.
141
+ *
142
+ * ```ts ignore
143
+ * fx.handle({ start: ranked(starting, (runs) => urgency(runs)) })
144
+ * ```
145
+ */
146
+ export let ranked = (run: Handler, rank: Rank): Handler & { rank: Rank } =>
147
+ Object.assign(run, { rank })
148
+
149
+ let rankOf = (run: Handler): Rank | undefined =>
150
+ 'rank' in run && typeof run.rank == 'function' ? run.rank as Rank : undefined
151
+
152
+ /** One registration: the component it watches, what has to happen to it, and
153
+ * what runs. A declared effect with several triggers is several slots under
154
+ * one name. */
155
+ export type Slot = Policy & {
156
+ /** a declared effect's name, or an observer's `post.created`,
157
+ * `post.changed.published`, `post.removed` (with `#2` for a second one) */
158
+ id: string
159
+ /** Related observers registered in one on() call. */
160
+ group?: string
161
+ /** the component name it watches */
162
+ comp: string
163
+ /** what has to happen to that component */
164
+ kind: Kind
165
+ /** for a `changed` slot, the properties one of which has to have moved;
166
+ * absent means any */
167
+ props?: string[]
168
+ /** a `matched` slot's pattern: the parsed query it was registered with */
169
+ plan?: Match
170
+ /** the components that pattern reads — a batch that moved none of them
171
+ * cannot have changed whether it holds, so it is not asked */
172
+ watch?: string[]
173
+ /** `-comp` — the components the pattern requires this batch to have
174
+ * removed, answered through `tx.bindings` with the batch passed in */
175
+ gone?: string[]
176
+ /** the declaration, for a declared effect */
177
+ effect?: EffectDecl
178
+ /** A call or a match that supplies a callable effect's inputs. */
179
+ invocation?: true | Record<string, unknown>
180
+ declaration?: string
181
+ /** Whether this subject still owes the work at dispatch. */
182
+ eligible?: (eid: Eid, tx: ReadTx) => boolean | Promise<boolean>
183
+ /** the code: always for an observer, once handled for an effect */
184
+ run?: DeclaredHandler
185
+ /** what orders a `fifo` effect's queue, when its code is {@link ranked} */
186
+ rank?: Rank
187
+ }
188
+
189
+ /** A handler or registry failure, for a {@link Report}. */
190
+ export type Job = {
191
+ /** the slot's id */
192
+ handler: string
193
+ /** the committed change it is running for; absent when finding work failed */
194
+ event?: Event
195
+ /** the registration itself, where there is one */
196
+ slot?: Slot
197
+ }
198
+
199
+ /** Where a failing handler goes. A report is telemetry: it is called instead
200
+ * of the error being thrown, and must not throw itself. */
201
+ export type Report = (err: unknown, ctx: Job) => void
202
+
203
+ /** How a registry is built. */
204
+ export type Opts = Partial<PoolOpts> & {
205
+ /** where a failing handler is reported (default: `console.warn`) */
206
+ report?: Report
207
+ /** the plugin's name, for diagnostics (default: `@yaks/effects`) */
208
+ name?: string
209
+ /** how a handler writes back: one new batch through the graph's own
210
+ * `apply()`, trusted (see {@link Write}). Without it a handler that tries to
211
+ * write is reported rather than quietly writing past the pipeline. */
212
+ write?: Write
213
+ /** which declared effects a commit owes runs for: only those this process
214
+ * handles (`handled`, the default: a process that runs every effect itself,
215
+ * as a yaks.app store does), or every declared one (`declared`: a process
216
+ * that writes for another to run, and cannot see the code that one holds) */
217
+ owes?: 'handled' | 'declared'
218
+ /** how many generations of effect-written batches still owe runs (default:
219
+ * `2`). A batch from a client is generation 0 and an effect's own write is
220
+ * 1. The default lets an output effect write an entity, its change effect
221
+ * start a new session, and that session's effect see the request. */
222
+ depth?: number
223
+ }
224
+
225
+ /**
226
+ * A registry: a {@link https://jsr.io/@yaks/graph | @yaks/graph} plugin, plus
227
+ * the methods that register on it. Registration is chainable and may happen
228
+ * at any time — before the graph is built, or after, which is how a handler
229
+ * closes over the graph it writes back through.
230
+ */
231
+ export type Effects = Plugin & {
232
+ /** observe an entity gaining this component */
233
+ created: (comp: string, run: Handler, policy?: Policy) => Effects
234
+ /** observe this component being patched — for one property, or for any */
235
+ changed: (
236
+ comp: string,
237
+ prop: string | Handler,
238
+ run?: Handler,
239
+ policy?: Policy,
240
+ ) => Effects
241
+ /** observe this component going, by its own deletion or with its entity */
242
+ removed: (comp: string, run: Handler, policy?: Policy) => Effects
243
+ /**
244
+ * Observe. Two forms, because there are two questions:
245
+ *
246
+ * fx.on('post', { created, changed: { published }, removed })
247
+ * fx.on('$call .call, !results', (e) => run(e.entity.eid))
248
+ *
249
+ * The first names a component and what has to happen to it; the second is a
250
+ * pattern — any query, any number of entities — and it runs wherever the
251
+ * batch just made it true.
252
+ */
253
+ on: {
254
+ (comp: string, registration: Registration): Effects
255
+ (pattern: string | Match, run: Handler, policy?: Policy): Effects
256
+ }
257
+ /** the code for declared effects, by name. A name the vocabulary does not
258
+ * declare is an error, so a typo never goes quietly unrun. */
259
+ handle: (handlers: Handlers) => Effects
260
+ /** every registration, declared ones first */
261
+ slots: () => Slot[]
262
+ /** Settle unclaimed pending runs no longer owed by this declaration/config. */
263
+ settle: (g: Access, handler: string) => Promise<number>
264
+ /** Documentation derived from the registered slots. */
265
+ docs: () => Description[]
266
+ /** Owe each handled start-up effect, targeting owner, without joining the
267
+ * pool. Where the vocabulary keeps `effect` rows, persist fresh runs;
268
+ * otherwise run the handlers inline. Persistence or inline handler failures
269
+ * reject; inline failures are also reported. The host calls this when its
270
+ * start-up work is owed. */
271
+ startup: (g: Access) => Promise<void>
272
+ /** Work the pool: claim what is owed and run it (./pool.ts). A live signal
273
+ * keeps working until it aborts; an aborted one is one pass, taken only
274
+ * where no process that stays up is working the pool. `startup: true` also
275
+ * owes fresh start-up runs, delivering them inline where the vocabulary
276
+ * keeps no `effect` rows. A finite pool drain answers whether it admitted
277
+ * or settled any work. */
278
+ work: (
279
+ g: Access,
280
+ signal?: AbortSignal,
281
+ options?: number | WorkOpts,
282
+ ) => Promise<boolean>
283
+ /** Look at the pool again now, rather than at the next pass. */
284
+ wake: () => void
285
+ /** Settles once every run this process started has, and a worker whose
286
+ * signal aborted has stopped. */
287
+ idle: () => Promise<void>
288
+ /** Leave the pool: claim nothing more, so what this process commits from now
289
+ * on is left for the others, and settle what it started. What a process
290
+ * does on its way out. */
291
+ stop: () => Promise<void>
292
+ /** On forced exit, leave unfinished claims due for the next worker at
293
+ * `at`. The retiring worker must exit before they become due. */
294
+ handoff: (at: number) => Promise<void>
295
+ /** The runs going in this process, oldest first: what a process winding
296
+ * down is waiting on. */
297
+ running: () => Run[]
298
+ /** When the soonest run this process can take falls due, in ms: `now` when
299
+ * one is due already, null when none is owed or there is no pool
300
+ * (./pool.ts `next`). */
301
+ next: (g: Access, now?: number) => Promise<number | null>
302
+ }
303
+
304
+ let warn: Report = (err, { handler }) =>
305
+ console.warn(`effect ${handler} failed —`, err)
306
+
307
+ // A run a bundle writes that is due now and that nobody holds: pending, with
308
+ // no claim and no backoff. A claim, a renewal, a backoff or a deferral is not.
309
+ let unheld = (b: Bundle): boolean => {
310
+ let run = b[EFFECT] as Comp | null | undefined
311
+ return run?.state == 'pending' && !run.lease_owner && !run.next
312
+ }
313
+
314
+ // Whether a slot is watching for this event. A pattern slot watches no single
315
+ // event: its query is run against the graph instead (see `hits`).
316
+ let watching = (s: Slot, e: Event): boolean =>
317
+ s.kind != 'matched' && s.comp == e.name && s.kind == e.kind &&
318
+ (s.kind != 'changed' || !s.props ||
319
+ (!!e.comp && s.props.some((p) => p in e.comp!)))
320
+
321
+ // What a pattern is about, in one component name: the first component it
322
+ // requires. It names an observer's slot and rides on the event.
323
+ let about = (plan: Match): string => {
324
+ for (let p of plan.patterns) {
325
+ for (let c of p.filter.clauses) {
326
+ if (c.kind == 'pred' && c.op == '!' && c.path.length == 1 && !c.value) {
327
+ return c.path[0]
328
+ }
329
+ }
330
+ }
331
+ return gone(plan)[0] ?? plan.patterns[0]?.entity ?? 'match'
332
+ }
333
+
334
+ // Every `-comp` a plan names: the components it requires this batch to have
335
+ // removed.
336
+ let gone = (plan: Match): string[] => {
337
+ let out: string[] = []
338
+ let walk = (cs: Clause[]) => {
339
+ for (let c of cs) {
340
+ if (c.kind == 'gone') out.push(c.comp)
341
+ else if (c.kind == 'and' || c.kind == 'or') walk(c.clauses)
342
+ }
343
+ }
344
+ for (let p of plan.patterns) walk(p.filter.clauses)
345
+ return out
346
+ }
347
+
348
+ // A pattern whose only clause is `-comp`, and the component it names — which
349
+ // is exactly what a removal event already reports, so it is registered as
350
+ // that event. Anything larger is a question only a batch overlay can answer.
351
+ let solo = (plan: Match): string | undefined => {
352
+ if (plan.patterns.length != 1 || plan.collections.length) return
353
+ let [p] = plan.patterns
354
+ let [c] = p.filter.clauses
355
+ return p.filter.clauses.length == 1 && c.kind == 'gone' && !p.entity &&
356
+ !p.binds.length && !p.gates.length && !p.ensures.length &&
357
+ !p.writes.length
358
+ ? c.comp
359
+ : undefined
360
+ }
361
+
362
+ /**
363
+ * A registry of post-commit effects and observers, as a plugin:
364
+ *
365
+ * ```ts
366
+ * import { graph } from '@yaks/graph'
367
+ * import { loadVocab } from '@yaks/vocab'
368
+ * import { ram } from '@yaks/ram'
369
+ * import { effects } from '@yaks/effects'
370
+ *
371
+ * let title = { type: 'string' }
372
+ * let vocab = loadVocab([{
373
+ * $defs: {
374
+ * post: { component: true, properties: { title } },
375
+ * send_receipt: { effect: true, created: ['post'] },
376
+ * },
377
+ * }])
378
+ * let fx = effects(vocab)
379
+ * let g = graph({ storage: ram(vocab), vocab, plugins: [fx] })
380
+ *
381
+ * fx.handle({ send_receipt: (e) => console.log('mail', e.entity.eid) })
382
+ * fx.created('post', (e) => console.log('a post appeared', e.comp?.title))
383
+ * g.apply([{ entity: { eid: 'p1' }, post: { title: 'Hello' } }])
384
+ * ```
385
+ *
386
+ * It requires the loaded vocabulary: the effects it declares are what a commit
387
+ * owes, and knowing what a cascade will delete — and therefore which
388
+ * components a casualty carried — is a question only a vocabulary can answer.
389
+ */
390
+ export let effects = (vocab: Vocab, opts: Opts = {}): Effects => {
391
+ let slots: Slot[] = []
392
+ let report: Report = (err, job) => {
393
+ try {
394
+ ;(opts.report ?? warn)(err, job)
395
+ } catch (e) {
396
+ console.warn('effect reporting failed —', e)
397
+ }
398
+ }
399
+ let depth = opts.depth ?? 2
400
+ let disabled = new Set(opts.disabled)
401
+ let TARGETS = '$effectTargets'
402
+ type Targets = Record<string, Eid[]>
403
+ // Stored local facts are already gathered by this transaction. Anything
404
+ // needing another entity or a computed read stays with the storage reader.
405
+ let local = (c: Clause): boolean => {
406
+ if (c.kind == 'and' || c.kind == 'or') return c.clauses.every(local)
407
+ if (c.kind != 'pred' || c.where || c.not) return false
408
+ // A reverse association reads the entities that point here.
409
+ if (!vocab.comp(c.path[0]) && vocab.assoc(c.path[0])) return false
410
+ let hops = vocab.aim(c.path.join('.'), bare(c)), h = hops[0]
411
+ if (hops.length != 1 || !h || vocab.comp(h.comp)?.computed) return false
412
+ let prop = h.prop && vocab.prop(h.comp, h.prop)
413
+ let absent = c.value?.kind == 'scalar' && c.value.raw == ''
414
+ return !prop || !prop.computed && prop.scalar != 'time' &&
415
+ (!prop.ref || !c.value || absent)
416
+ }
417
+ // What a target query asks of a batch, worked out once per query: the test
418
+ // its subjects' own rows answer, or the read a storage answers for them.
419
+ type Target =
420
+ | { local: true; comps: string[] | undefined; test: (b: Bundle) => boolean }
421
+ | { local: false; read: And }
422
+ | null
423
+ let targets = new Map<string, Target>()
424
+ let target = (query: string): Target => {
425
+ if (targets.has(query)) return targets.get(query)!
426
+ let plan = asked(match(query), vocab)
427
+ if (plan && (plan.patterns.length != 1 || plan.collections.length)) {
428
+ throw new Error('an effect target must be a single-entity query')
429
+ }
430
+ let where = plan?.patterns[0].filter
431
+ let made: Target = !plan || !where
432
+ ? null
433
+ : local(where)
434
+ ? { local: true, comps: reads(plan, vocab), test: filter(where, vocab) }
435
+ : {
436
+ local: false,
437
+ read: { ...where, clauses: [...where.clauses, fields('entity.eid')] },
438
+ }
439
+ targets.set(query, made)
440
+ return made
441
+ }
442
+ // Restrict scope reads to the batch's subjects, never the whole graph.
443
+ let subjects = (query: string, eids: Eid[], tx: ReadTx) => {
444
+ let t = target(query)
445
+ if (!t || !eids.length) return []
446
+ if (t.local) {
447
+ let { test } = t
448
+ return after(
449
+ tx.get(eids, t.comps),
450
+ (rows) => rows.filter((b) => test(b)).map((b) => b.entity.eid),
451
+ )
452
+ }
453
+ return after(
454
+ tx.read(t.read, { eids }),
455
+ (rows) => rows.map((b) => b.entity.eid),
456
+ )
457
+ }
458
+ let scoped = (bundles: Bundle[], tx: ReadTx) => {
459
+ if (!slots.some((s) => !disabled.has(s.id) && s.effect?.target)) {
460
+ return bundles
461
+ }
462
+ let prior = (bundles[0]?.[BEFORE] ?? {}) as Before
463
+ let batch = new Set(bundles.map((b) => b.entity.eid))
464
+ // What dies with the batch is not in it until the write runs, so it is
465
+ // read as deleted here: a target scopes a casualty by what it was.
466
+ let doomed = Object.keys(prior).filter((eid) => !batch.has(eid))
467
+ let eids = [...batch, ...doomed]
468
+ let seen = events([
469
+ ...bundles,
470
+ ...doomed.map((eid) => ({ entity: { eid }, $delete: true })),
471
+ ])
472
+ let queries = [
473
+ ...new Set(
474
+ slots.filter((s) =>
475
+ !disabled.has(s.id) &&
476
+ // The graph adds created/updated after this precondition, so an
477
+ // input event cannot yet say which stamp trigger will fire.
478
+ (s.comp == 'created' || s.comp == 'updated' ||
479
+ s.kind == 'matched' &&
480
+ s.watch?.some((c) => c == 'created' || c == 'updated') ||
481
+ seen.some((e) =>
482
+ watching(s, e) ||
483
+ (s.kind == 'matched' && s.watch?.includes(e.name))
484
+ ))
485
+ )
486
+ .map((s) => s.effect?.target).filter((q): q is string => !!q),
487
+ ),
488
+ ]
489
+ if (!queries.length) return bundles
490
+ return after(
491
+ each(
492
+ queries,
493
+ {} as Targets,
494
+ (out, query) =>
495
+ after(subjects(query, eids, tx), (found) => {
496
+ out[query] = found
497
+ return out
498
+ }),
499
+ ),
500
+ (targets) => bundles.map((b) => ({ ...b, [TARGETS]: targets })),
501
+ )
502
+ }
503
+
504
+ // The write callback as one run sees it: whatever it writes is marked a
505
+ // generation on from the batch that owed it.
506
+ let writer = (gen: number, context?: HookContext): Write => (bundles) => {
507
+ if (!opts.write) {
508
+ throw new Error(
509
+ 'this effect asked to write and no write door is registered — ' +
510
+ 'effects(vocab, { write: (b) => graph.apply(b, { trusted: true }) })',
511
+ )
512
+ }
513
+ let tagged = marked(bundles, gen + 1)
514
+ if (!context?.parent || !peek(context.graph)) return opts.write(tagged)
515
+ link(context.graph, tagged, context.parent)
516
+ let clean = () => unlink(context.graph, tagged)
517
+ try {
518
+ let out = opts.write(tagged)
519
+ if (isPromise(out)) return out.finally(clean)
520
+ clean()
521
+ return out
522
+ } catch (error) {
523
+ clean()
524
+ throw error
525
+ }
526
+ }
527
+
528
+ let name = (comp: string, kind: Kind, prop?: string) => {
529
+ let base = prop ? `${comp}.${kind}.${prop}` : `${comp}.${kind}`
530
+ let taken = slots.filter((s) => s.id == base || s.id.startsWith(`${base}#`))
531
+ return taken.length ? `${base}#${taken.length + 1}` : base
532
+ }
533
+
534
+ // A pattern, parsed here and narrowed to the components this vocabulary
535
+ // declares (@yaks/graph `asked`), so one pattern is correct in two graphs:
536
+ // one that requires a component this graph cannot store is registered and
537
+ // inert — listed, documented, never run.
538
+ let planned = (what: string | Match) => {
539
+ let written = typeof what == 'string' ? match(what) : what
540
+ let plan = asked(written, vocab)
541
+ if (plan?.collections.length && !plan.patterns.length) {
542
+ throw new Error('a matched effect needs an outer entity')
543
+ }
544
+ let one = plan && solo(plan)
545
+ return one ? { comp: one, kind: 'removed' as Kind } : {
546
+ comp: about(written),
547
+ kind: 'matched' as Kind,
548
+ plan: plan ?? undefined,
549
+ watch: plan ? reads(plan, vocab) : [],
550
+ gone: plan ? gone(plan) : [],
551
+ }
552
+ }
553
+
554
+ // The declared effects, one slot per trigger, all under the effect's name.
555
+ effectsIn(vocab.docs)
556
+ let declared = vocab.docs.flatMap((doc) => {
557
+ let local = vocab.in(namespaceOf(doc))
558
+ return effectsIn(doc).map((effect) => {
559
+ if (local === vocab) return effect
560
+ for (let key of ['created', 'changed', 'removed'] as const) {
561
+ if (effect[key]) {
562
+ effect[key] = effect[key].map((path) =>
563
+ rewordedPath(path, local, vocab)
564
+ )
565
+ }
566
+ }
567
+ for (let key of ['match', 'target', 'eligible', 'active'] as const) {
568
+ if (effect[key]) effect[key] = reworded(effect[key], local, vocab)
569
+ }
570
+ return effect
571
+ })
572
+ })
573
+ let callable = new Map(
574
+ declared.filter((e) => e.call).map((e) => [e.name, e]),
575
+ )
576
+ let addresses = [...callable.keys()].map(effectEid)
577
+ for (let effect of declared) {
578
+ let query = effect.eligible
579
+ let eligible: Slot['eligible'] = query
580
+ ? (eid, tx) =>
581
+ after(subjects(query, [eid], tx), (found) => !!found.length)
582
+ : undefined
583
+ let operation = effect.owe ? callable.get(effect.owe) : undefined
584
+ // Some hosts select only the words they serve.
585
+ if (effect.owe && !operation) continue
586
+ let at = (s: Omit<Slot, 'id' | 'effect'>) =>
587
+ slots.push({
588
+ ...s,
589
+ id: operation?.name ?? effect.name,
590
+ effect: operation
591
+ ? {
592
+ ...operation,
593
+ target: effect.target,
594
+ active: effect.active,
595
+ eligible: effect.eligible,
596
+ }
597
+ : effect,
598
+ ...operation
599
+ ? { declaration: effect.name, invocation: effect.args ?? {} }
600
+ : {},
601
+ eligible,
602
+ doc: effect.description,
603
+ })
604
+ for (let comp of effect.created ?? []) at({ comp, kind: 'created' })
605
+ let changed = new Map<string, string[] | undefined>()
606
+ for (let said of effect.changed ?? []) {
607
+ let [comp, prop] = said.split('.')
608
+ let props = changed.has(comp) ? changed.get(comp) : []
609
+ changed.set(comp, prop && props ? [...props, prop] : undefined)
610
+ }
611
+ for (let [comp, props] of changed) at({ comp, kind: 'changed', props })
612
+ for (let comp of effect.removed ?? []) at({ comp, kind: 'removed' })
613
+ if (effect.match) {
614
+ let slot = planned(effect.match)
615
+ if (
616
+ effect.call === false && addresses.length && 'plan' in slot && slot.plan
617
+ ) {
618
+ let [subject, ...rest] = slot.plan.patterns
619
+ let filter = and(
620
+ ...subject.filter.clauses,
621
+ ne('call.to', list(...addresses)),
622
+ )
623
+ slot = {
624
+ ...slot,
625
+ plan: { ...slot.plan, patterns: [{ ...subject, filter }, ...rest] },
626
+ }
627
+ }
628
+ at(slot)
629
+ }
630
+ if (effect.call && vocab.comp('call') && vocab.comp('result')) {
631
+ let to = `.call.to=${
632
+ effectEid(effect.name)
633
+ }, !execution, !results, !interrupted, !cut`
634
+ at({ ...planned(`*call, ${to}, !wake`), invocation: true })
635
+ if (vocab.comp('wake') && vocab.comp('fired')) {
636
+ at({ ...planned(`*fired, ${to}, .wake`), invocation: true })
637
+ }
638
+ }
639
+ // Start-up work: owed by a worker joining the pool (./pool.ts), and by
640
+ // no commit, so its slot watches nothing.
641
+ if (effect.start) at({ comp: '', kind: 'started' })
642
+ }
643
+
644
+ let observe = (s: Omit<Slot, 'id'>, id: string) => {
645
+ slots.push({ ...s, id })
646
+ return fx
647
+ }
648
+ let add = (
649
+ comp: string,
650
+ kind: Kind,
651
+ run: Handler,
652
+ prop?: string,
653
+ policy: Policy = {},
654
+ group?: string,
655
+ ) =>
656
+ observe(
657
+ { ...policy, group, comp, kind, props: prop ? [prop] : undefined, run },
658
+ name(comp, kind, prop),
659
+ )
660
+ let pattern = (
661
+ what: string | Match,
662
+ run: Handler,
663
+ policy: Policy,
664
+ group?: string,
665
+ ) => {
666
+ let s = planned(what)
667
+ return observe({ ...policy, group, ...s, run }, name(s.comp, s.kind))
668
+ }
669
+
670
+ // Did this batch touch anything a pattern reads?
671
+ let stirred = (s: Slot, seen: Event[]) =>
672
+ seen.some((e) => s.watch?.includes(e.name))
673
+
674
+ // A pattern's bindings, narrowed to this batch: a result row is kept where
675
+ // the batch touched any entity it bound, so a run is owed for what just
676
+ // happened rather than for every row that has matched all along.
677
+ let hits = (
678
+ s: Slot,
679
+ bundles: Bundle[],
680
+ seen: Event[],
681
+ tx: ReadTx,
682
+ ): Event[] | Promise<Event[]> => {
683
+ let plan = s.plan!
684
+ let touched = new Set<Eid>(bundles.map((b) => b.entity.eid))
685
+ let one = plan.patterns.filter((p) => !p.makes)
686
+ // A *component clause anchors the match to a write of that component on
687
+ // the bound entity. The same match without a write clause uses any touch.
688
+ let written: Map<Eid, Set<string>> | undefined
689
+ if (one.some((p) => p.writes.length)) {
690
+ written = new Map()
691
+ for (let e of seen) {
692
+ if (e.kind == 'removed') continue
693
+ let names = written.get(e.entity.eid) ?? new Set<string>()
694
+ names.add(e.name)
695
+ written.set(e.entity.eid, names)
696
+ }
697
+ }
698
+ let anchors = (eid: Eid, writes: string[]) =>
699
+ written
700
+ ? writes.some((name) => written.get(eid)?.has(name))
701
+ : touched.has(eid)
702
+ // The batch is passed to the query only where the query is about it: a
703
+ // `-comp` clause reads the deletions a storage's overlay carries.
704
+ let pending = s.gone?.length ? bundles : []
705
+ if (
706
+ one.length > 1 || plan.collections.length ||
707
+ plan.patterns.some((p) => p.binds.length) ||
708
+ s.gone?.length
709
+ ) {
710
+ if (!tx.bindings) {
711
+ throw new Error(
712
+ `effect ${s.id} asks about more than one entity, or about what ` +
713
+ 'this batch removed, and this storage answers no bindings — a ' +
714
+ 'one-entity pattern over committed rows is all it can be asked',
715
+ )
716
+ }
717
+ return after(
718
+ tx.bindings([plan], pending, s.watch!),
719
+ ([rows]) =>
720
+ rows
721
+ .filter((r) =>
722
+ r.entities.some((e, i) =>
723
+ e && anchors(e, plan.patterns[i].writes)
724
+ )
725
+ )
726
+ .map((r) => ({
727
+ kind: 'matched' as Kind,
728
+ // The subject: the first entity the match bound.
729
+ entity: { eid: r.entities.find((e) => !!e)! },
730
+ name: s.comp,
731
+ vars: r.vars,
732
+ binding: r,
733
+ })),
734
+ )
735
+ }
736
+ // Asked about the entities this batch touched and no others: an index
737
+ // lookup, not a scan with the batch picked out afterwards.
738
+ let { filter, writes } = one[0]
739
+ let eids = [...touched].filter((eid) => anchors(eid, writes))
740
+ if (!eids.length) return []
741
+ return after(
742
+ tx.read(filter, { eids }),
743
+ (rows) =>
744
+ rows.map((b) => ({
745
+ kind: 'matched' as Kind,
746
+ entity: b.entity,
747
+ name: s.comp,
748
+ comp: b[s.comp] as Comp | undefined,
749
+ })),
750
+ )
751
+ }
752
+
753
+ // What this batch did for the slots `which` selects: one pair per slot and
754
+ // event, the created/changed/removed ones first, then the patterns. A
755
+ // pattern this storage cannot answer is reported, never a failed batch.
756
+ let matched = (
757
+ bundles: Bundle[],
758
+ tx: ReadTx,
759
+ which: (s: Slot) => boolean,
760
+ ): [Slot, Event][] | Promise<[Slot, Event][]> => {
761
+ let chosen = slots.filter(which)
762
+ if (!chosen.length) return []
763
+ let byComp = new Map<string, Slot[]>()
764
+ for (let s of chosen) {
765
+ if (s.kind == 'matched') continue
766
+ let group = byComp.get(s.comp) ?? []
767
+ group.push(s)
768
+ byComp.set(s.comp, group)
769
+ }
770
+ let seen = events(bundles)
771
+ let prior = (bundles.find((b) => b[BEFORE])?.[BEFORE] ?? {}) as Before
772
+ // A run is owed for what happened in the graph, never for the pool's own
773
+ // rows: an entity that wears `effect`, before this batch or in it, owes no
774
+ // declared effect a run. Otherwise a mark a settle writes (`completed`)
775
+ // would owe the runs that mark triggers, each of those would settle and
776
+ // owe more, and the depth never stops it, since a settle is generation 0.
777
+ let poolEids: Set<Eid> | undefined
778
+ let inPool = (eid: Eid) => {
779
+ if (!poolEids) {
780
+ poolEids = new Set<Eid>()
781
+ for (let [eid, row] of Object.entries(prior)) {
782
+ if (row[EFFECT] != null) poolEids.add(eid)
783
+ }
784
+ for (let b of bundles) {
785
+ if (b[EFFECT] != null) poolEids.add(b.entity.eid)
786
+ }
787
+ }
788
+ return poolEids.has(eid)
789
+ }
790
+ let allowed = (s: Slot, e: Event) => !s.effect || !inPool(e.entity.eid)
791
+ // Who wrote each event's entity in this batch, carried on the event so a
792
+ // run can write on that commit's behalf (`Event.actor`).
793
+ let wrote = writers(bundles)
794
+ let touched: Set<Eid> | undefined
795
+ let signing = (e: Event, bound = false): Event => {
796
+ if (bound) touched ??= new Set(bundles.map((b) => b.entity.eid))
797
+ let source = bound
798
+ ? e.binding?.entities.find((id) => id && touched!.has(id))
799
+ : undefined
800
+ let { by, via } = wrote(source ?? e.entity.eid)
801
+ return by || via
802
+ ? { ...e, actor: { ...by ? { by } : {}, ...via ? { via } : {} } }
803
+ : e
804
+ }
805
+ let found: [Slot, Event][] = []
806
+ for (let e of seen) {
807
+ let group = byComp.get(e.name)
808
+ if (!group) continue
809
+ for (let s of group) {
810
+ if (watching(s, e) && allowed(s, e)) found.push([s, e])
811
+ }
812
+ }
813
+ let asking = chosen.filter((s) =>
814
+ s.kind == 'matched' && s.plan && stirred(s, seen)
815
+ )
816
+ let targets = new Map<string, Set<Eid> | Promise<Set<Eid>>>()
817
+ let priorTargets = (bundles[0]?.[TARGETS] ?? {}) as Targets
818
+ let matchesNow = (query: string | undefined, eid: Eid) => {
819
+ if (!query) return true
820
+ if (!targets.has(query)) {
821
+ targets.set(
822
+ query,
823
+ after(
824
+ subjects(query, bundles.map((b) => b.entity.eid), tx),
825
+ (found) => new Set(found),
826
+ ),
827
+ )
828
+ }
829
+ return after(targets.get(query)!, (found) => found.has(eid))
830
+ }
831
+ let inScope = (s: Slot, { entity: { eid } }: Event) => {
832
+ let { target, eligible } = s.effect ?? {}
833
+ let scoped = target && priorTargets[target]?.includes(eid) ||
834
+ matchesNow(target, eid)
835
+ return after(scoped, (yes) => yes && matchesNow(eligible, eid))
836
+ }
837
+ let active = new Map<string, boolean | Promise<boolean>>()
838
+ let enabled = (s: Slot): boolean | Promise<boolean> => {
839
+ let query = s.effect?.active
840
+ if (!query) return true
841
+ // Whether any entity matches, so one is all it reads: the matches of
842
+ // `.error .error.bug` are a store's every grouped error.
843
+ if (!active.has(query)) {
844
+ active.set(
845
+ query,
846
+ after(
847
+ tx.read(and(...parse(query).clauses, limit(1))),
848
+ (rows) => rows.length > 0,
849
+ ),
850
+ )
851
+ }
852
+ return active.get(query)!
853
+ }
854
+ return after(
855
+ each(asking, found, (out, s) => {
856
+ try {
857
+ return after(
858
+ hits(s, bundles, seen, tx),
859
+ (evs) => {
860
+ for (let e of evs) if (allowed(s, e)) out.push([s, e])
861
+ return out
862
+ },
863
+ )
864
+ } catch (err) {
865
+ report(err, {
866
+ handler: s.id,
867
+ slot: s,
868
+ })
869
+ return out
870
+ }
871
+ }),
872
+ (hits) => {
873
+ let kept: [Slot, Event][] = []
874
+ return each(
875
+ hits,
876
+ kept,
877
+ (out, pair) =>
878
+ after(
879
+ inScope(...pair),
880
+ (scoped) =>
881
+ scoped
882
+ ? after(enabled(pair[0]), (yes) => {
883
+ if (!yes) return out
884
+ let [s, e] = pair
885
+ let event = signing(
886
+ e,
887
+ !!s.invocation && s.invocation !== true,
888
+ )
889
+ if (s.invocation === true) {
890
+ let eid = e.entity.eid
891
+ return after(tx.get([eid]), ([call]) => {
892
+ if (call?.call) {
893
+ out.push([s, {
894
+ ...event,
895
+ invocation: invocationOf(call),
896
+ }])
897
+ }
898
+ return out
899
+ })
900
+ }
901
+ if (s.invocation) {
902
+ event = {
903
+ ...event,
904
+ invocation: {
905
+ args: boundArgs(s.invocation, e.vars ?? {}),
906
+ match: s.declaration,
907
+ },
908
+ }
909
+ }
910
+ out.push([s, event])
911
+ return out
912
+ })
913
+ : out,
914
+ ),
915
+ )
916
+ },
917
+ )
918
+ }
919
+
920
+ // One observer run, isolated.
921
+ let fire = (
922
+ s: Slot,
923
+ event: Event,
924
+ tx: ReadTx,
925
+ write: Write,
926
+ gen: number,
927
+ context?: HookContext,
928
+ propagate = false,
929
+ ): unknown => {
930
+ let failed = (err: unknown) => {
931
+ report(err, { handler: s.id, event, slot: s })
932
+ if (propagate) throw err
933
+ }
934
+ try {
935
+ let c = context && peek(context.graph)
936
+ let out: unknown
937
+ if (!c) out = s.run!(event, tx, write)
938
+ else {
939
+ let span = c.begin({
940
+ kind: 'effect',
941
+ name: s.id,
942
+ package: '@yaks/effects',
943
+ plugin: opts.name,
944
+ parent: context!.parent,
945
+ })
946
+ out = during(span, () =>
947
+ s.run!(
948
+ event,
949
+ tx,
950
+ writer(gen, {
951
+ graph: context!.graph,
952
+ parent: span?.id,
953
+ }),
954
+ ))
955
+ }
956
+ return isPromise(out) ? out.then(() => null, failed) : null
957
+ } catch (err) {
958
+ return failed(err)
959
+ }
960
+ }
961
+
962
+ // The pool, where this vocabulary keeps effect rows.
963
+ let pooled = vocab.comp(EFFECT)
964
+ ? pool({ slots: () => slots, writer, report }, opts)
965
+ : undefined
966
+
967
+ // What this process runs itself after a commit: every observer, and a
968
+ // handled effect where there is no pool to hand it to.
969
+ let here = (s: Slot) => !!s.run && (!s.effect || !pooled)
970
+
971
+ // The transaction that claimed work carries it through post-commit hooks,
972
+ // even when another hook replaces a bundle while canonicalizing its actor.
973
+ // Standalone hooks without a transaction context retain their bundle key.
974
+ let owed = new WeakMap<object, Owed[]>()
975
+ let left = new WeakSet<object>()
976
+
977
+ // Inside the transaction: the runs this batch owes, written down.
978
+ let owesAll = opts.owes == 'declared'
979
+ // Declarations without a pool or handler cannot observe a commit. Read this
980
+ // afresh, since a caller can register handlers after building the graph.
981
+ let watches = () =>
982
+ slots.some((s) => !!s.run || !!pooled && owesAll && !!s.effect)
983
+ let owe: Hook = (bundles, tx, _err, context) => {
984
+ // A run written down outright (`enqueue`, a retry) is due and nobody
985
+ // holds it. The store hears only other processes' commits (`watch`), so
986
+ // it is left work, as a run a slot owed and this worker could not claim.
987
+ if (bundles.some(unheld)) left.add(context?.transaction ?? bundles[0])
988
+ if (generation(bundles) > depth) return bundles
989
+ // A pool row owes no declared component event. Patterns still inspect
990
+ // the batch: a join can match a different, non-pool subject.
991
+ if (
992
+ bundles.every((b) => b[EFFECT] != null) &&
993
+ !slots.some((s) => s.effect && s.kind == 'matched')
994
+ ) return bundles
995
+ return after(
996
+ matched(
997
+ bundles,
998
+ tx,
999
+ (s) =>
1000
+ !!s.effect && !disabled.has(s.id) &&
1001
+ !disabled.has(s.declaration ?? '') && (owesAll || !!s.run),
1002
+ ),
1003
+ (found) =>
1004
+ !found.length ? bundles : after(
1005
+ pooled!.owe(tx, found, generation(bundles)),
1006
+ (mine) => {
1007
+ let c = context && peek(context.graph)
1008
+ if (c) {
1009
+ for (let [s] of found) {
1010
+ c.instant({
1011
+ kind: 'effect',
1012
+ name: s.id,
1013
+ package: '@yaks/effects',
1014
+ plugin: opts.name,
1015
+ parent: context!.parent,
1016
+ }, { counts: { owed: 1 } })
1017
+ }
1018
+ for (let run of mine) {
1019
+ if (context!.parent) link(context!.graph, run, context!.parent)
1020
+ }
1021
+ }
1022
+ let key = context?.transaction ?? bundles[0]
1023
+ if (mine.length) owed.set(key, mine)
1024
+ if (mine.length < found.length) left.add(key)
1025
+ return bundles
1026
+ },
1027
+ ),
1028
+ )
1029
+ }
1030
+
1031
+ // After the commit: the runs this process claimed as it wrote them are
1032
+ // started, and every observer runs.
1033
+ let effect: Hook = (bundles, tx, _err, context) => {
1034
+ let key = context?.transaction ?? bundles[0]
1035
+ let mine = key && owed.get(key)
1036
+ let clean = () => {
1037
+ for (let b of bundles) delete b[TARGETS]
1038
+ return unmark(strip(bundles))
1039
+ }
1040
+ if (mine) {
1041
+ owed.delete(key!)
1042
+ pooled!.start(mine)
1043
+ }
1044
+ // A run a hook owed in the transaction (./enqueue.ts `owe`) is left work
1045
+ // as a run written in the batch is.
1046
+ if (
1047
+ key && (left.delete(key) || mine?.length || pooled && owing.has(key))
1048
+ ) {
1049
+ // The local worker may be asleep after an empty pass. A host nudge
1050
+ // notifies other workers, but cannot wake this registry's own pool.
1051
+ pooled!.wake()
1052
+ opts.nudge?.()
1053
+ }
1054
+ let gen = generation(bundles)
1055
+ if (gen > depth || !slots.some(here)) return clean()
1056
+ let write = writer(gen)
1057
+ return after(
1058
+ after(
1059
+ matched(bundles, tx, here),
1060
+ (found) =>
1061
+ over(found, ([s, e]) => {
1062
+ let c = context && peek(context.graph)
1063
+ if (c) {
1064
+ c.instant({
1065
+ kind: 'effect',
1066
+ name: s.id,
1067
+ package: '@yaks/effects',
1068
+ plugin: opts.name,
1069
+ parent: context!.parent,
1070
+ }, { counts: { owed: 1 } })
1071
+ }
1072
+ return fire(s, e, tx, write, gen, context)
1073
+ }),
1074
+ ),
1075
+ clean,
1076
+ )
1077
+ }
1078
+
1079
+ // A host without pool rows still owes its declared starts. Their writes
1080
+ // use the same generation boundary as effects after a commit; a failed
1081
+ // start rejects so the host cannot record its deployment as complete.
1082
+ let starter = opts.owner
1083
+ let startup = async (g: Access) => {
1084
+ if (pooled) return pooled.startup(g)
1085
+ let entity = { eid: starter ??= crypto.randomUUID() }
1086
+ for (let s of slots) {
1087
+ if (s.kind != 'started' || !s.run) continue
1088
+ await fire(
1089
+ s,
1090
+ { kind: 'started', entity, name: '' },
1091
+ g.outside,
1092
+ writer(0),
1093
+ 0,
1094
+ undefined,
1095
+ true,
1096
+ )
1097
+ }
1098
+ }
1099
+
1100
+ let fx: Effects = {
1101
+ name: opts.name ?? '@yaks/effects',
1102
+ namespace: null,
1103
+ admission: () => true,
1104
+ // The generation counter an effect's own write carries (write.ts `ORIGIN`)
1105
+ // comes back in through `apply()` like any other request, so this plugin
1106
+ // declares it.
1107
+ requests: [ORIGIN],
1108
+ hooks: {
1109
+ // Read the state the batch is about to change, while it still stands.
1110
+ precondition: (bundles, tx) =>
1111
+ watches()
1112
+ ? after(
1113
+ before(vocab)(bundles, tx),
1114
+ (prepared) => scoped(prepared, tx),
1115
+ )
1116
+ : bundles,
1117
+ ...(pooled ? { commit: owe } : {}),
1118
+ effect,
1119
+ },
1120
+ // Nothing is read while nothing is registered, so nothing is asked for.
1121
+ wants: (bundles) => [
1122
+ ...(watches() ? wanting(vocab)(bundles) : []),
1123
+ ...[...new Set(slots.map((s) => s.wants))]
1124
+ .flatMap((wants) => wants?.(bundles) ?? []),
1125
+ ],
1126
+ created: (comp, run, policy) =>
1127
+ add(comp, 'created', run, undefined, policy),
1128
+ changed: (comp, prop, run, policy) =>
1129
+ typeof prop == 'string'
1130
+ ? add(comp, 'changed', run as Handler, prop, policy)
1131
+ : add(comp, 'changed', prop, undefined, policy),
1132
+ removed: (comp, run, policy = {}) => pattern(`-${comp}`, run, policy),
1133
+ on: ((
1134
+ what: string | Match,
1135
+ second: Registration | Handler,
1136
+ policy: Policy = {},
1137
+ ) => {
1138
+ if (typeof second == 'function') return pattern(what, second, policy)
1139
+ let { created, changed, removed, ...rest } = second
1140
+ let comp = what as string
1141
+ let group = `on:${slots.length}`
1142
+ if (created) add(comp, 'created', created, undefined, rest, group)
1143
+ for (let [prop, run] of Object.entries(changed ?? {})) {
1144
+ add(comp, 'changed', run, prop, rest, group)
1145
+ }
1146
+ if (removed) pattern(`-${comp}`, removed, rest, group)
1147
+ return fx
1148
+ }) as Effects['on'],
1149
+ handle: (handlers) => {
1150
+ for (let [id, run] of Object.entries(handlers)) {
1151
+ let mine = slots.filter((s) => s.effect && s.id == id)
1152
+ if (!mine.length) throw new Error(`no effect is declared as ${id}`)
1153
+ if (disabled.has(id)) continue
1154
+ for (let s of mine) Object.assign(s, { run, rank: rankOf(run) })
1155
+ }
1156
+ return fx
1157
+ },
1158
+ slots: () => [...slots],
1159
+ settle: (g, handler) => {
1160
+ let declared = slots.filter((s) => s.effect && s.id == handler)
1161
+ if (!declared.length) {
1162
+ throw new Error(`no effect is declared as ${handler}`)
1163
+ }
1164
+ return settleStale(g, handler, async (row) => {
1165
+ if (disabled.has(handler)) return false
1166
+ let candidates = declared.filter((s) =>
1167
+ s.kind == row.kind && (s.kind == 'started' || s.comp == row.comp)
1168
+ )
1169
+ if (!candidates.length) return false
1170
+ let eligible = candidates[0].eligible
1171
+ if (eligible && !await eligible(String(row.target), g.outside)) {
1172
+ return false
1173
+ }
1174
+ // A removal's old scope is not recorded; preserve it conservatively.
1175
+ if (row.kind == 'removed') return true
1176
+ let query = candidates[0].effect?.target
1177
+ return !query ||
1178
+ (await subjects(query, [String(row.target)], g.outside)).length > 0
1179
+ })
1180
+ },
1181
+ docs: () => describe(slots),
1182
+ startup,
1183
+ work: (g, signal, options) =>
1184
+ pooled?.work(g, signal, options) ??
1185
+ (typeof options == 'object' && options.startup
1186
+ ? startup(g).then(() => false)
1187
+ : Promise.resolve(false)),
1188
+ wake: () => pooled?.wake(),
1189
+ idle: () => pooled?.idle() ?? Promise.resolve(),
1190
+ stop: () => pooled?.stop() ?? Promise.resolve(),
1191
+ handoff: (at) => pooled?.handoff(at) ?? Promise.resolve(),
1192
+ running: () => pooled?.running() ?? [],
1193
+ next: (g, now) => pooled?.next(g, now) ?? Promise.resolve(null),
1194
+ }
1195
+ return fx
1196
+ }