@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/lease.ts ADDED
@@ -0,0 +1,444 @@
1
+ // A duty, and the one process running it.
2
+ //
3
+ // Some work is not about a batch at all: picking back up the agents a restart
4
+ // left running, freeing the locks a dead session held, firing the wakes that
5
+ // came due while nobody was looking. Every process that opens the graph could
6
+ // do it, and if they all did, an agent would be tailed twice and a wake fired
7
+ // twice. So each such duty is a row, and taking it is a contest:
8
+ //
9
+ // lease{name, holder, until}
10
+ //
11
+ // The eid is derived from the name, the way an edge's eid is derived from its
12
+ // endpoints and relation, so one duty is one row in every graph and two
13
+ // processes reaching for it address the same row. Taking it is a write with a
14
+ // `$was` precondition — the holder and the expiry as the taker read them — so
15
+ // the loser is refused inside the transaction rather than overwriting the
16
+ // winner a moment later. Nothing here polls a lock table; the graph's own
17
+ // precondition is the lock.
18
+ //
19
+ // `until` is what makes a lease a lease. A holder that is still doing the work
20
+ // takes it again on a timer and pushes the expiry out; one that was killed
21
+ // leaves a row that expires, and the next process to ask gets it. Nothing has
22
+ // to clean up after it, which is the whole reason the duty is held under a
23
+ // lease rather than a claim. An asker that can tell the holder is gone (`gone`:
24
+ // its pid no longer running, or its row saying it is over) does not wait for
25
+ // the expiry at all.
26
+ //
27
+ // A graph whose vocabulary does not declare `lease` has no other process to
28
+ // contend with — one process, one graph — so every take succeeds and nothing
29
+ // is written.
30
+
31
+ import { after } from '@yaks/fp'
32
+ import type { Access, Bundle, Comp, Eid } from 'jsr:@yaks/graph@0.2.36'
33
+ import { derivedEid } from '@yaks/graph/identity'
34
+ import { Stale } from '@yaks/graph/errors'
35
+ import { token } from '@yaks/graph/sha256'
36
+ import { and, eq, every, line, or } from '@yaks/query'
37
+ import { finishedRun } from './cleanup.js'
38
+
39
+ /** The name of the component a lease is stored as. */
40
+ export let LEASE = 'lease'
41
+
42
+ /** How long a take stands before another process may have it (ms). */
43
+ export let HOLD = 30_000
44
+
45
+ /** A lease row, as it is held. */
46
+ export type Lease = {
47
+ /** the duty being held — the eid is derived from it */
48
+ name?: string | null
49
+ /** the process holding it */
50
+ holder?: Eid | null
51
+ /** when it expires, ISO-8601 */
52
+ until?: string | null
53
+ }
54
+
55
+ /**
56
+ * The eid a lease is stored at: `sha256("lease|<name>")` formatted as a uuid,
57
+ * the same derivation an edge's eid gets.
58
+ *
59
+ * ```ts
60
+ * leaseEid('@yaks/wake') == leaseEid('@yaks/wake') // true
61
+ * ```
62
+ */
63
+ export let leaseEid = (name: string): Eid => derivedEid(`${LEASE}|${name}`)
64
+
65
+ /** The arguments to a take: who is asking, and for how long. */
66
+ export type HoldOpts = {
67
+ /** the process asking — what `holder` names */
68
+ holder: Eid
69
+ /** how long the take stands (default {@link HOLD}) */
70
+ hold?: number
71
+ /** the clock, in milliseconds (default `Date.now`) */
72
+ now?: () => number
73
+ /** whether a holder is known to be over (@yaks/process `gone`): its take no
74
+ * longer stands, so the lease is had now rather than at its expiry (default:
75
+ * nobody is known to be) */
76
+ gone?: (holder: Eid) => boolean | Promise<boolean>
77
+ }
78
+
79
+ let leaseOf = (g: Access, eid: Eid): Promise<Lease | undefined> =>
80
+ Promise.resolve(g.get([eid]))
81
+ .then(([row]) => row?.[LEASE] as Lease | undefined)
82
+
83
+ /** Whether this graph contends at all: a component its vocabulary does not
84
+ * declare cannot be stored on anything in it, so there is one process and the
85
+ * duty is its own. */
86
+ let contested = (g: Access): boolean => !!g.vocab.comp(LEASE)
87
+
88
+ /**
89
+ * Take a lease, or find out somebody else holds it. Returns whether it is now
90
+ * ours — a holder taking its own again is a renewal, and pushes `until` out.
91
+ *
92
+ * ```ts
93
+ * import { take } from '@yaks/effects'
94
+ *
95
+ * // if (await take(graph, '@yaks/wake', { holder: me })) …
96
+ * ```
97
+ */
98
+ export let take = async (
99
+ g: Access,
100
+ name: string,
101
+ o: HoldOpts,
102
+ ): Promise<boolean> => {
103
+ if (!contested(g)) return true
104
+ let [taken] = await taking(g, [name], o)
105
+ if (!taken) return false
106
+ try {
107
+ await g.apply([taken])
108
+ return true
109
+ } catch (error) {
110
+ // Another process got there first, inside the transaction. That is the
111
+ // answer, not a failure.
112
+ if (error instanceof Stale) return false
113
+ throw error
114
+ }
115
+ }
116
+
117
+ // The write that takes each of `names`, or `undefined` for one somebody else
118
+ // holds, read in one look.
119
+ let taking = async (
120
+ g: Access,
121
+ names: string[],
122
+ o: HoldOpts,
123
+ ): Promise<(Bundle | undefined)[]> => {
124
+ let eids = names.map(leaseEid)
125
+ let rows = new Map(
126
+ (await g.get(eids)).map((row) => [row.entity.eid, row[LEASE] as Lease]),
127
+ )
128
+ let now = (o.now ?? Date.now)()
129
+ return Promise.all(names.map(async (name, i) => {
130
+ let eid = eids[i]
131
+ let held = rows.get(eid)
132
+ let until = held?.until ? Date.parse(String(held.until)) : 0
133
+ // Somebody else's, and their take still stands: they are not known gone.
134
+ if (
135
+ held?.holder && held.holder != o.holder && until > now &&
136
+ !await o.gone?.(held.holder)
137
+ ) return undefined
138
+ return {
139
+ entity: { eid },
140
+ [LEASE]: {
141
+ name,
142
+ holder: o.holder,
143
+ until: new Date(now + (o.hold ?? HOLD)).toISOString(),
144
+ },
145
+ // Both properties, because both move: a rival taking an expired lease
146
+ // moves `holder`, and the holder renewing it moves only `until`. Guarding
147
+ // one would let the other slip past.
148
+ $was: {
149
+ [LEASE]: {
150
+ holder: token(held?.holder ?? null),
151
+ until: token(held?.until ?? null),
152
+ },
153
+ },
154
+ } as Bundle
155
+ }))
156
+ }
157
+
158
+ /**
159
+ * Release a lease, if we are the one holding it. The row stays — the duty
160
+ * outlives whoever was doing it — and the next process to ask gets it without
161
+ * waiting for the expiry.
162
+ */
163
+ export let drop = async (
164
+ g: Access,
165
+ name: string,
166
+ o: { holder: Eid },
167
+ ): Promise<void> => {
168
+ if (!contested(g)) return
169
+ let eid = leaseEid(name)
170
+ let held = await leaseOf(g, eid)
171
+ if (!held?.holder || held.holder != o.holder) return
172
+ try {
173
+ await g.apply([{
174
+ entity: { eid },
175
+ [LEASE]: { holder: null, until: null },
176
+ $was: { [LEASE]: { holder: token(held.holder) } },
177
+ } as Bundle])
178
+ } catch (error) {
179
+ // Somebody took it over while we were finishing. Releasing a lease we no
180
+ // longer hold is a no-op, not an error.
181
+ if (!(error instanceof Stale)) throw error
182
+ }
183
+ }
184
+
185
+ let relinquish = (b: Bundle, comp: string, props: string[]): Bundle => ({
186
+ entity: { eid: b.entity.eid },
187
+ [comp]: Object.fromEntries(props.map((p) => [p, null])),
188
+ $was: {
189
+ [comp]: Object.fromEntries(
190
+ props.map((p) => [p, token((b[comp] as Comp)?.[p] ?? null)]),
191
+ ),
192
+ },
193
+ })
194
+
195
+ let started = (b: Bundle, holder: Eid) => {
196
+ let e = b.effect as Comp
197
+ return e.kind == 'started' && e.target == holder && e.state == 'pending'
198
+ }
199
+
200
+ /**
201
+ * Every duty and effect lease a holder has, as bundles that release them,
202
+ * guarded against a concurrent handover — to be applied
203
+ * in the same batch that records the holder's ending, because they are one
204
+ * fact: a process that is over is not doing anything, and the next one to ask
205
+ * should not have to wait out an expiry nobody is using. Its pending startup
206
+ * runs end with it: another process owes its own startup, not this closure.
207
+ */
208
+ export let released = (
209
+ g: Access,
210
+ holder: Eid,
211
+ ): Bundle[] | Promise<Bundle[]> =>
212
+ after(
213
+ contested(g) ? g.read(line`.${LEASE}.holder=${holder}`) : [],
214
+ (leases) =>
215
+ after(
216
+ g.vocab.comp('effect')
217
+ ? g.read(and(
218
+ or(
219
+ eq('effect.lease_owner', holder),
220
+ and(
221
+ eq('effect.kind', 'started'),
222
+ eq('effect.target', holder),
223
+ eq('effect.state', 'pending'),
224
+ ),
225
+ ),
226
+ every(),
227
+ ))
228
+ : [],
229
+ (runs) => [
230
+ ...leases.map((b) => relinquish(b, LEASE, ['holder', 'until'])),
231
+ ...runs.flatMap((b) =>
232
+ started(b, holder) ? finishedRun(b) : [relinquish(b, 'effect', [
233
+ 'lease_owner',
234
+ 'lease_token',
235
+ 'lease_expiry',
236
+ ])]
237
+ ),
238
+ ],
239
+ ),
240
+ )
241
+
242
+ /** Who holds a lease right now, if anybody — the read a check makes. */
243
+ export let held = (g: Access, name: string): Promise<Lease | undefined> =>
244
+ contested(g) ? leaseOf(g, leaseEid(name)) : Promise.resolve(undefined)
245
+
246
+ /** Wait, unless we are done waiting: a sleep the signal cuts short, so a pass
247
+ * between renewals releases the lease the moment it is asked to. */
248
+ export { sleep } from '@yaks/fp'
249
+ import { sleep } from '@yaks/fp'
250
+
251
+ /** How a lease is held for a while: {@link HoldOpts}, plus what signals that
252
+ * we are done, how often to retry while somebody else holds it, and where a
253
+ * store that failed to answer is told. */
254
+ export type HoldingOpts = HoldOpts & {
255
+ /** abort to release the lease. Already aborted means one pass and out — a
256
+ * CLI command does what nobody else is doing and never queues for what
257
+ * somebody else is. */
258
+ signal?: AbortSignal
259
+ /** whether to wait out a holder ahead of this one (default: while the
260
+ * signal is live). Not waiting answers at once, leaving the work to them —
261
+ * one run of something whose holder already runs it, like a transcript's
262
+ * turn — and a take the store fails is then thrown, for the caller to try
263
+ * again, rather than waited out. */
264
+ wait?: boolean
265
+ /** how often to ask again while somebody else holds it (default a tenth of
266
+ * the hold) */
267
+ poll?: number
268
+ /** a take or a renewal the store failed (default `console.error`); it is
269
+ * asked again, since a busy store is not an answer */
270
+ report?: (err: unknown) => void
271
+ }
272
+
273
+ // A lease held while its work runs: what renews it, what aborts when another
274
+ // process has it, and where a store that failed to answer is told.
275
+ type Renewal = {
276
+ name: string
277
+ ask: HoldOpts & { hold: number }
278
+ lost: AbortController
279
+ report: (err: unknown) => void
280
+ }
281
+ type Beat = {
282
+ renewals: Set<Renewal>
283
+ beating: boolean
284
+ timer?: ReturnType<typeof setInterval>
285
+ }
286
+
287
+ // The leases one holder holds in one graph for one length of hold, renewed on
288
+ // one timer in one commit: a process holding fifteen duties writes once a beat,
289
+ // not fifteen times.
290
+ let beats = new WeakMap<Access, Map<string, Beat>>()
291
+
292
+ // Renew `r` beside the others its holder holds, until the answer is called.
293
+ // Renewed on a timer while the work runs: a holder still at it never expires,
294
+ // and one that stops existing does. One renewal at a time, so two of this
295
+ // process's own cannot refuse each other.
296
+ let beside = (g: Access, r: Renewal): () => void => {
297
+ let held = beats.get(g) ?? new Map<string, Beat>()
298
+ beats.set(g, held)
299
+ let key = `${r.ask.holder}|${r.ask.hold}`
300
+ let beat = held.get(key)
301
+ if (!beat) {
302
+ let b: Beat = beat = { renewals: new Set(), beating: false }
303
+ held.set(key, b)
304
+ // A third of the hold, however short: a renewal later than the hold would
305
+ // let the lease lapse under work still running.
306
+ b.timer = setInterval(async () => {
307
+ if (b.beating) return
308
+ b.beating = true
309
+ try {
310
+ await renew(g, [...b.renewals], (r) => b.renewals.has(r))
311
+ } finally {
312
+ b.beating = false
313
+ }
314
+ }, Math.max(1, Math.floor(r.ask.hold / 3)))
315
+ }
316
+ let b = beat
317
+ b.renewals.add(r)
318
+ return () => {
319
+ b.renewals.delete(r)
320
+ if (b.renewals.size) return
321
+ clearInterval(b.timer)
322
+ held.delete(key)
323
+ }
324
+ }
325
+
326
+ // One commit renewing every lease a beat holds. One somebody else holds now is
327
+ // lost; a commit refused is asked again a lease at a time, and a refusal is
328
+ // read back before it counts, since only another holder means it is gone.
329
+ //
330
+ // A beat runs beside the work, so the work can end while one is under way.
331
+ // `kept` says whether a renewal is still wanted: a lease its holder has let go
332
+ // is not taken back, and nothing the store fails about it is anybody's to hear,
333
+ // since a holder on its way out may have closed the store behind it.
334
+ let renew = async (
335
+ g: Access,
336
+ all: Renewal[],
337
+ kept: (r: Renewal) => boolean,
338
+ ): Promise<void> => {
339
+ if (!all.length) return
340
+ let { ask } = all[0]
341
+ try {
342
+ let bundles = await taking(g, all.map((r) => r.name), ask)
343
+ all.forEach((r, i) => bundles[i] || r.lost.abort())
344
+ let taken = bundles.filter((b, i): b is Bundle => !!b && kept(all[i]))
345
+ if (!taken.length) return
346
+ try {
347
+ await g.apply(taken)
348
+ return
349
+ } catch (error) {
350
+ if (!(error instanceof Stale)) throw error
351
+ }
352
+ } catch (e) {
353
+ return all.find(kept)?.report(e)
354
+ }
355
+ for (let r of all) {
356
+ if (r.lost.signal.aborted || !kept(r)) continue
357
+ try {
358
+ if (await take(g, r.name, r.ask)) continue
359
+ if ((await held(g, r.name))?.holder != r.ask.holder) r.lost.abort()
360
+ } catch (e) {
361
+ if (kept(r)) r.report(e)
362
+ }
363
+ }
364
+ }
365
+
366
+ /**
367
+ * Run a duty for as long as this process is up: take the lease, renew it
368
+ * while the work runs, and release it at the end. Answers what the work last
369
+ * answered, or `undefined` where it never ran.
370
+ *
371
+ * The same call serves a process of either shape, which is the point — nothing
372
+ * here assumes a separate one. A server or a TUI passes a live signal and
373
+ * holds the lease until that aborts, waiting for the holder ahead of it to
374
+ * expire; a one-shot CLI command passes a signal that has already aborted,
375
+ * does the pass if nobody else is, and releases on the way out. Either way the
376
+ * lease is renewed for as long as the work runs.
377
+ *
378
+ * The work is handed a signal that also aborts when the lease is lost: a
379
+ * renewal that finds another process holding it means that process is doing
380
+ * the duty now, so this one stops, and goes back to waiting in case that one
381
+ * stops too. Renewals run on a timer beside the work, so the work has to
382
+ * yield to timers (a sleep, a wait on I/O) more often than a third of the
383
+ * hold; a step that blocks longer can lapse, and the next renewal to run
384
+ * finds out and stops it.
385
+ *
386
+ * ```ts
387
+ * import { holding } from '@yaks/effects'
388
+ *
389
+ * // await holding(graph, '@yaks/wake', { holder: me, signal }, (s) => loop(g, { signal: s }))
390
+ * ```
391
+ */
392
+ export let holding = async <T = void>(
393
+ g: Access,
394
+ name: string,
395
+ o: HoldingOpts,
396
+ work: (signal: AbortSignal) => T | Promise<T>,
397
+ ): Promise<T | undefined> => {
398
+ let signal = o.signal ?? AbortSignal.abort()
399
+ let wait = o.wait ?? !signal.aborted
400
+ let hold = o.hold ?? HOLD
401
+ let ask = { ...o, hold }
402
+ let report = o.report ?? ((e: unknown) => console.error(`${name} —`, e))
403
+ // A take the store failed is not a no. Waiting, it is told and asked again
404
+ // next time; not waiting, there is no next time here, so the caller hears.
405
+ let ours = () =>
406
+ wait
407
+ ? take(g, name, ask).catch((e) => {
408
+ report(e)
409
+ return false
410
+ })
411
+ : take(g, name, ask)
412
+ let out: T | undefined
413
+ while (true) {
414
+ while (!await ours()) {
415
+ // Somebody is doing it. A process that is staying up waits them out — a
416
+ // holder that was killed expires and this is what takes over — and one
417
+ // that is only passing through leaves it to them.
418
+ if (!wait || signal.aborted) return out
419
+ await sleep(o.poll ?? Math.max(250, Math.floor(hold / 10)), signal)
420
+ if (signal.aborted) return out
421
+ }
422
+ let lost = new AbortController()
423
+ let leave = beside(g, { name, ask, lost, report })
424
+ try {
425
+ out = await work(AbortSignal.any([signal, lost.signal]))
426
+ } finally {
427
+ leave()
428
+ await drop(g, name, { holder: o.holder }).catch(report)
429
+ }
430
+ if (signal.aborted || !lost.signal.aborted) return out
431
+ }
432
+ }
433
+
434
+ /** A promise that keeps a lease held and does nothing else, until the signal
435
+ * reports that we are done — what a pass that has already finished its work
436
+ * waits on, so the lease stays this process's while it is up. */
437
+ export let until = (signal: AbortSignal): Promise<void> =>
438
+ signal.aborted
439
+ ? Promise.resolve()
440
+ : new Promise((done) =>
441
+ signal.addEventListener('abort', () => done(), {
442
+ once: true,
443
+ })
444
+ )
package/mod.js ADDED
@@ -0,0 +1,89 @@
1
+ /**
2
+ * @yaks/effects — what a graph does about the data it commits, kept out of the
3
+ * write path and out of the writer.
4
+ *
5
+ * A write is settled by {@link https://jsr.io/@yaks/graph | @yaks/graph}'s
6
+ * `apply()`. An effect is the other half: work a commit owes, run after the
7
+ * transaction commits. When a letter is written, send it. When an order is
8
+ * paid, print a receipt.
9
+ *
10
+ * A batch, here and throughout, is bundles applied in one
11
+ * transaction: the array passed to `apply()`, written in full or not at all.
12
+ *
13
+ * ## Declared, then handled
14
+ * An effect is declared in a vocabulary, beside the components it is about,
15
+ * so every process that loads the vocabulary knows what a write owes:
16
+ *
17
+ * ```json
18
+ * { "$defs": { "send_receipt": { "effect": true, "changed": ["order.paid"] } } }
19
+ * ```
20
+ *
21
+ * and the code that runs it is registered by name, by a process that runs
22
+ * effects:
23
+ *
24
+ * ```ts
25
+ * import { graph } from '@yaks/graph'
26
+ * import { loadVocab } from '@yaks/vocab'
27
+ * import { ram } from '@yaks/ram'
28
+ * import { effects } from '@yaks/effects'
29
+ *
30
+ * let paid = { type: 'boolean' }
31
+ * let vocab = loadVocab([{
32
+ * $defs: {
33
+ * order: { component: true, properties: { paid } },
34
+ * send_receipt: { effect: true, changed: ['order.paid'] },
35
+ * },
36
+ * }])
37
+ * let fx = effects(vocab)
38
+ * let g = graph({ storage: ram(vocab), vocab, plugins: [fx] })
39
+ * fx.handle({ send_receipt: (e) => console.log(e.entity.eid) })
40
+ * ```
41
+ *
42
+ * Where the vocabulary also loads {@link effectDoc}, a commit writes every run
43
+ * it owes into the graph, in its own transaction, and any number of processes
44
+ * work the pool ({@link Effects.work}): each claims a run, runs it, and retries
45
+ * it on the terms its declaration set. Where it does not, a handled effect
46
+ * runs in the process that committed, at most once.
47
+ *
48
+ * ## Observers
49
+ * A process can also watch its own commits, for as long as it runs:
50
+ * `fx.created('post', redraw)` calls `redraw` for each post a commit makes,
51
+ * and `fx.on('$call .call, !results', show)` calls `show` wherever a commit
52
+ * leaves a call without results.
53
+ *
54
+ * An observer is known only to the process that registered it, so it runs
55
+ * there, after that process's commits, and is never written down.
56
+ *
57
+ * ## The promises
58
+ * - **Post-commit only.** A handler cannot reject a write; by the time it runs,
59
+ * the write is durable. A batch that was refused owes nothing.
60
+ * - **Isolated.** A handler that throws is passed to `report` and the next
61
+ * handler still runs.
62
+ * - **Written with the write.** Where the pool is kept, a run is committed with
63
+ * the batch that owes it, so no crash between the two can lose it.
64
+ *
65
+ * ## Writing back
66
+ * An effect that writes has one route, and it is the graph's own `apply()`:
67
+ * `effects(vocab, { write: (b) => g.apply(b, { trusted: true }) })`.
68
+ *
69
+ * So the write is admitted, stamped, journaled and broadcast like any other. A
70
+ * write from an effect could trigger an effect; that loop is stopped in one
71
+ * place: every batch carries its {@link generation} — 0 when it came from a
72
+ * client, 1 for an effect's write — and a batch past `depth` (default 1) owes
73
+ * nothing.
74
+ *
75
+ * It imports no platform API, so the same registry runs on a server, in a
76
+ * worker, and in a browser tab.
77
+ *
78
+ * @module
79
+ */ export * from "./trace.js";
80
+ export * from "./write.js";
81
+ export * from "./registry.js";
82
+ export * from "./pool.js";
83
+ export * from "./lease.js";
84
+ export * from "./provisional.js";
85
+ export { WORKER } from "./worker.js";
86
+ export * from "./expire.js";
87
+ export { effectInvocation, effectRetry, enqueue, owe } from "./enqueue.js";
88
+ export { firstPending } from "./ready.js";
89
+ //# sourceMappingURL=mod.js.map
package/mod.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mod.js","sources":["./mod.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA8EC,GAED,2BAA0B;AAC1B,2BAA0B;AAC1B,8BAA6B;AAC7B,0BAAyB;AACzB,2BAA0B;AAC1B,iCAAgC;AAChC,SAAsB,MAAM,sBAAkC;AAE9D,4BAA2B;AAE3B,SAAS,gBAAgB,EAAE,WAAW,EAAE,OAAO,EAAE,GAAG,uBAAsB;AAC1E,SAAS,YAAY,qBAAoB"}
package/mod.ts ADDED
@@ -0,0 +1,92 @@
1
+ /**
2
+ * @yaks/effects — what a graph does about the data it commits, kept out of the
3
+ * write path and out of the writer.
4
+ *
5
+ * A write is settled by {@link https://jsr.io/@yaks/graph | @yaks/graph}'s
6
+ * `apply()`. An effect is the other half: work a commit owes, run after the
7
+ * transaction commits. When a letter is written, send it. When an order is
8
+ * paid, print a receipt.
9
+ *
10
+ * A batch, here and throughout, is bundles applied in one
11
+ * transaction: the array passed to `apply()`, written in full or not at all.
12
+ *
13
+ * ## Declared, then handled
14
+ * An effect is declared in a vocabulary, beside the components it is about,
15
+ * so every process that loads the vocabulary knows what a write owes:
16
+ *
17
+ * ```json
18
+ * { "$defs": { "send_receipt": { "effect": true, "changed": ["order.paid"] } } }
19
+ * ```
20
+ *
21
+ * and the code that runs it is registered by name, by a process that runs
22
+ * effects:
23
+ *
24
+ * ```ts
25
+ * import { graph } from '@yaks/graph'
26
+ * import { loadVocab } from '@yaks/vocab'
27
+ * import { ram } from '@yaks/ram'
28
+ * import { effects } from '@yaks/effects'
29
+ *
30
+ * let paid = { type: 'boolean' }
31
+ * let vocab = loadVocab([{
32
+ * $defs: {
33
+ * order: { component: true, properties: { paid } },
34
+ * send_receipt: { effect: true, changed: ['order.paid'] },
35
+ * },
36
+ * }])
37
+ * let fx = effects(vocab)
38
+ * let g = graph({ storage: ram(vocab), vocab, plugins: [fx] })
39
+ * fx.handle({ send_receipt: (e) => console.log(e.entity.eid) })
40
+ * ```
41
+ *
42
+ * Where the vocabulary also loads {@link effectDoc}, a commit writes every run
43
+ * it owes into the graph, in its own transaction, and any number of processes
44
+ * work the pool ({@link Effects.work}): each claims a run, runs it, and retries
45
+ * it on the terms its declaration set. Where it does not, a handled effect
46
+ * runs in the process that committed, at most once.
47
+ *
48
+ * ## Observers
49
+ * A process can also watch its own commits, for as long as it runs:
50
+ * `fx.created('post', redraw)` calls `redraw` for each post a commit makes,
51
+ * and `fx.on('$call .call, !results', show)` calls `show` wherever a commit
52
+ * leaves a call without results.
53
+ *
54
+ * An observer is known only to the process that registered it, so it runs
55
+ * there, after that process's commits, and is never written down.
56
+ *
57
+ * ## The promises
58
+ * - **Post-commit only.** A handler cannot reject a write; by the time it runs,
59
+ * the write is durable. A batch that was refused owes nothing.
60
+ * - **Isolated.** A handler that throws is passed to `report` and the next
61
+ * handler still runs.
62
+ * - **Written with the write.** Where the pool is kept, a run is committed with
63
+ * the batch that owes it, so no crash between the two can lose it.
64
+ *
65
+ * ## Writing back
66
+ * An effect that writes has one route, and it is the graph's own `apply()`:
67
+ * `effects(vocab, { write: (b) => g.apply(b, { trusted: true }) })`.
68
+ *
69
+ * So the write is admitted, stamped, journaled and broadcast like any other. A
70
+ * write from an effect could trigger an effect; that loop is stopped in one
71
+ * place: every batch carries its {@link generation} — 0 when it came from a
72
+ * client, 1 for an effect's write — and a batch past `depth` (default 1) owes
73
+ * nothing.
74
+ *
75
+ * It imports no platform API, so the same registry runs on a server, in a
76
+ * worker, and in a browser tab.
77
+ *
78
+ * @module
79
+ */
80
+
81
+ export * from './trace.js'
82
+ export * from './write.js'
83
+ export * from './registry.js'
84
+ export * from './pool.js'
85
+ export * from './lease.js'
86
+ export * from './provisional.js'
87
+ export { type Listed, WORKER, type Worker } from './worker.js'
88
+
89
+ export * from './expire.js'
90
+
91
+ export { effectInvocation, effectRetry, enqueue, owe } from './enqueue.js'
92
+ export { firstPending } from './ready.js'