@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/pool.ts ADDED
@@ -0,0 +1,1635 @@
1
+ // The pool: effects written down by whoever committed, and run by whoever is
2
+ // working. It is optional — a vocabulary that does not declare the `effect`
3
+ // component keeps no rows, and a handled effect runs in the process that
4
+ // committed (./registry.ts) — and it is what separates effects from writers:
5
+ //
6
+ // effect{handler, target, comp, kind, touched, before, state, attempts, at,
7
+ // generation, error, next, version, lease_owner, lease_token,
8
+ // lease_expiry}
9
+ //
10
+ // A commit writes one row for each run it owes, inside its own transaction,
11
+ // whichever process wrote it: a crash after the commit cannot lose a run,
12
+ // because the run was committed with the write. A run reads the target as it
13
+ // stands when it runs, except for what the commit removed, which is gone by
14
+ // then: a removal's row keeps that, as `before` (./trace.ts). Any number of
15
+ // processes work the pool, and a row is run by the one that claims it.
16
+ //
17
+ // A claim is the row's own lease — owner, token, expiry — written through the
18
+ // graph's own `apply()` with its precondition (@yaks/graph `$was`): the claim
19
+ // lands only if the token and the attempt count are still the ones the
20
+ // claimant read, so two workers reaching for one row settle it there and the
21
+ // loser moves on. A worker renews the claims it is running, while it works the
22
+ // pool and while it waits for them to finish; one that dies leaves claims that expire,
23
+ // and the next pass takes them — at once, where the dead worker is known to
24
+ // have ended ({@link PoolOpts.gone}).
25
+ //
26
+ // A process working the pool claims the rows its own commits owe as it writes
27
+ // them, and starts them once the commit is done: nothing another process could
28
+ // do with them would be sooner. What another process wrote is heard as it
29
+ // lands, where the storage can hear it ({@link PoolOpts.watch}), and is
30
+ // otherwise found by the next pass, at most {@link CAP} away.
31
+ //
32
+ // A worker shares its thread with whatever hosts it, and a synchronous
33
+ // storage (SQLite, on the box or in a Durable Object) never hands the thread
34
+ // back on its own: a backlog worked in one go is one turn, and nothing else in
35
+ // the process happens until it ends — no request is answered (a Durable
36
+ // Object's runtime refuses them as overloaded), no timer fires, no child
37
+ // process is reaped and no signal is heard. So a worker gives way between
38
+ // passes, and a turn starts at most a page of runs. How many go at once is
39
+ // not a number: each time a worker gives way it times the turn, and it takes
40
+ // more runs only while its thread comes back to it promptly (no more than
41
+ // {@link LATE} ms behind). Runs waiting on the network cost the thread
42
+ // nothing, so thousands can go at once; a thread busy starting or finishing
43
+ // them, or starved by a loaded box, comes back late, and the worker takes no
44
+ // more until it catches up. A host that wants a fixed bound still says `max`.
45
+ //
46
+ // Every write to a run under its claim goes straight through storage
47
+ // (@yaks/graph `book`), past `apply()`'s phases: nothing stamps it or moves it
48
+ // to another archetype. Success erases its run under the same claim guard; it
49
+ // leaves no done row and no tombstone.
50
+ // There are two ways a run does not complete, and they are not the same:
51
+ //
52
+ // It reported. The handler threw, so the row is marked with the error and
53
+ // `next`, the instant its backoff is up, and a pass runs it again then.
54
+ //
55
+ // It was interrupted. The worker died mid-run, or its claim expired: nothing
56
+ // records how far it got. A claimed row with no `next` is one of these, and
57
+ // it is run again — unless its declaration says `idempotent: false`, where a
58
+ // second run could duplicate something that already reached an external
59
+ // system, and it is left failed instead. A run records the code version its
60
+ // attempt started on ({@link PoolOpts.version}). Resumed under another, a
61
+ // deploy cut it off, and it runs again as the same attempt, since nothing
62
+ // failed. Resumed under the same one, or where the host names none, its
63
+ // process crashed under it, perhaps because of the run itself, and that
64
+ // spends an attempt like a reported failure, so a crash loop stops at the
65
+ // attempt limit.
66
+ //
67
+ // How many attempts a run gets is the declaration's (`tries`), never a
68
+ // handler's, so no effect carries retry code of its own. A run that spent them
69
+ // is left `failed` with the error it last threw, for a person (the
70
+ // `effect_check` tool). An error that asks to be tried again (it carries
71
+ // `retry`, as @yaks/model's `ModelError` does for a provider's transient
72
+ // failure) is expected: it is kept on the row and reported only once nothing
73
+ // will try it again, and where it says when to come back (`retry.after`, a
74
+ // provider's Retry-After in milliseconds) it is due no sooner than that. One
75
+ // whose `retry` also says `defer` is no failure at all, as a handler's own
76
+ // `defer` is not: its object refused it for a while (@yaks/durable-object
77
+ // `Stopped`), and the run is due again after the wait as the same attempt.
78
+ // The pool's own write of how a run ended goes through the host's `free`,
79
+ // where its storage takes it even while it refuses everything else, so a run
80
+ // that finished is never run again for want of the word, whatever becomes of
81
+ // the process.
82
+ //
83
+ // A handler is told which attempt it is ({@link Attempt}): whether this is its
84
+ // last, so the failure it records there is the one that stands; and a way to
85
+ // say it got somewhere, so a long run that fails again after succeeding counts
86
+ // that failure as its first, not as one more in a row.
87
+ //
88
+ // A worker winds down by leaving: the moment its signal aborts it claims
89
+ // nothing more, and what it started runs to its end, however long that is,
90
+ // still under its claim. What its runs commit meanwhile is written down for
91
+ // whichever worker comes next. A run failing after its worker left is handed
92
+ // back with the tries it has left rather than retried in place: the leaving
93
+ // process may run older code than the store it reads, and the next worker
94
+ // does not.
95
+ //
96
+ // A worker that stays up holds a presence lease while it works, one per
97
+ // process, so a process that only passes through — a command line — can tell
98
+ // whether anyone is working the pool, and leaves the work to them when they
99
+ // are. Only a worker with code for every enabled declared effect holds one: a process
100
+ // lending one effect its code (a terminal running its own transcripts) works
101
+ // that one, and says nothing about the rest.
102
+ //
103
+ // A worker that stays up also says what it is doing, every fifteen seconds, on
104
+ // its own process entity: the runs it has going, how many it has finished and
105
+ // how busy it is (./worker.ts). Where it leaves the pool, the row goes too, and
106
+ // a worker starting clears the rows of those `gone` says were killed first.
107
+
108
+ import type {
109
+ Access,
110
+ Actor,
111
+ Bundle,
112
+ Comp,
113
+ Eid,
114
+ HookContext,
115
+ Tx,
116
+ } from 'jsr:@yaks/graph@0.2.36'
117
+ import { after, type Clock, system } from '@yaks/fp'
118
+ import {
119
+ during,
120
+ outcome,
121
+ parent,
122
+ peek,
123
+ scope,
124
+ type Span,
125
+ unlink,
126
+ } from '@yaks/trace'
127
+ import { comps } from '@yaks/graph/bundle'
128
+ import { Stale } from '@yaks/graph/errors'
129
+ import { token } from '@yaks/graph/sha256'
130
+ import {
131
+ type And,
132
+ and,
133
+ eq,
134
+ fields,
135
+ gt,
136
+ limit as window,
137
+ line,
138
+ list,
139
+ ne,
140
+ or,
141
+ order,
142
+ present,
143
+ time as relative,
144
+ } from '@yaks/query'
145
+ import type { Report, Slot } from './registry.ts'
146
+ import type { Event, Kind } from './trace.ts'
147
+ import type { Write } from './write.ts'
148
+ import { HOLD, LEASE, leaseEid, sleep, take } from './lease.js'
149
+ import { callRun } from './invocation.js'
150
+ import { finishedRun } from './cleanup.js'
151
+ import { available, except, firstPending, ready } from './ready.js'
152
+ import { lagging, SAY, seconds, SHOWN, WORKER } from './worker.js'
153
+
154
+ export { effectDoc } from './docs.js'
155
+
156
+ /** The pool's component, by the name ./vocab.json declares it. */
157
+ export let EFFECT = 'effect'
158
+
159
+ // Keep relative time in the cached query and supply the pass's clock when
160
+ // reading it. The first pass and every later pass ask the same indexed question.
161
+ let HEADS = new Map<string, And>()
162
+ let head = (
163
+ handler: string,
164
+ singleOwner: boolean,
165
+ disabled: boolean,
166
+ n: number,
167
+ owner: string,
168
+ waiting?: string,
169
+ ) => {
170
+ let key = waiting
171
+ ? undefined
172
+ : JSON.stringify([handler, singleOwner, disabled, n, owner])
173
+ let q = key && HEADS.get(key)
174
+ if (!q) {
175
+ q = and(
176
+ ...ready([handler], {
177
+ singleOwner,
178
+ disabled: disabled ? [handler] : [],
179
+ owner,
180
+ waiting: waiting ? new Map([[handler, waiting]]) : undefined,
181
+ }).clauses,
182
+ window(n),
183
+ )
184
+ if (key) HEADS.set(key, q)
185
+ }
186
+ return q
187
+ }
188
+
189
+ /** How many of a ranked fifo queue's oldest runs its rank orders. */
190
+ export let QUEUE = 200
191
+
192
+ /** The most attempts a run gets where its declaration does not say: the
193
+ * first, and two more. */
194
+ export let TRIES = 3
195
+
196
+ /** How long after the nth attempt the next one falls due: a second, doubling,
197
+ * and never more than five minutes apart.
198
+ *
199
+ * ```ts
200
+ * import { backoff } from '@yaks/effects'
201
+ *
202
+ * [1, 2, 3, 10].map(backoff) // [1000, 2000, 4000, 300000]
203
+ * ```
204
+ */
205
+ export { backoff } from '@yaks/fp'
206
+ import { backoff } from '@yaks/fp'
207
+
208
+ // A thrown error that asks to be tried again: it carries `retry`, with the
209
+ // wait it asks for as `retry.after` in milliseconds, the shape a provider's
210
+ // Retry-After takes (@yaks/model `ModelError`).
211
+ let retryOf = (err: unknown) =>
212
+ (err as { retry?: { after?: unknown } } | null)?.retry
213
+ let retried = (err: unknown): boolean => {
214
+ let retry = retryOf(err)
215
+ return retry != null && typeof retry == 'object'
216
+ }
217
+ let asked = (err: unknown): number => {
218
+ let after = retryOf(err)?.after
219
+ return typeof after == 'number' && after > 0 ? after : 0
220
+ }
221
+ // An error that asks for a wait and is no failure: it spends no attempt.
222
+ let deferral = (err: unknown): boolean =>
223
+ (retryOf(err) as { defer?: unknown } | undefined)?.defer === true
224
+
225
+ /** A run the pool started, as its handler sees it. */
226
+ export type Attempt = {
227
+ /** Whether this attempt is the run's last: if it fails now, it is left
228
+ * failed, so what the handler records about the failure is what stands. */
229
+ last: () => boolean
230
+ /** Wait for a dependency without spending an attempt. The same run remains
231
+ * pending for at least this delay, with the reason alongside it. */
232
+ defer?: (delay: number, reason?: string) => Promise<void>
233
+ /** The run got somewhere: a failure after this counts as its first attempt,
234
+ * not one more in a row. For a run that does many steps, where one success
235
+ * should give the next failure its full tries back. */
236
+ progressed: () => Promise<void>
237
+ /** Retry a local completion without replaying the handler's external work.
238
+ * Uses this run's remaining tries and backoff without releasing the run,
239
+ * until the worker leaves: a failure after that is thrown, and the run goes
240
+ * back to the pool with the tries it has left. */
241
+ retry?: <T>(body: () => Promise<T>) => Promise<T>
242
+ }
243
+
244
+ /** The longest a worker waits between passes (ms): how soon a run another
245
+ * process wrote is picked up when nothing hears it land. */
246
+ export let CAP = 1_000
247
+
248
+ // An alarm-driven store with deferred work rechecks its dependencies even
249
+ // when no other work is due. Shared workers already do so on every pass.
250
+ let RECHECK = 60_000
251
+
252
+ /** How late a worker's turn may come back (ms) and it still take more runs:
253
+ * past this, its event loop is full. */
254
+ export let LATE = 50
255
+
256
+ /** What every worker's presence lease is named under: `@yaks/effects/<eid>`. */
257
+ export let POOL = '@yaks/effects'
258
+
259
+ /** How a pool is worked. */
260
+ export type PoolOpts = {
261
+ /** One process exclusively owns this store (for example a Durable Object).
262
+ * Drain recorded runs without claims, presence leases, or expiration
263
+ * duties. Persist attempts and outcomes for crash recovery and retries,
264
+ * but for a start-up run started at once, whose recovery is the host's
265
+ * pass and which writes only a failure. Never enable this for a shared box
266
+ * store. */
267
+ singleOwner?: boolean
268
+ /** When start-up runs are owed: on joining the pool (`join`, the default
269
+ * for shared workers), or only when the host calls startup (`manual`, the
270
+ * default for single-owner stores). */
271
+ startup?: 'join' | 'manual'
272
+ /** Effects explicitly disabled by this configuration, whose unclaimed runs owe no work. */
273
+ disabled?: string[]
274
+ /** who this process is: what its claims and its presence lease name. A
275
+ * worker that names nobody claims under a fresh id and holds no presence
276
+ * lease, since a lease's holder is an entity */
277
+ owner: Eid
278
+ /** Maximum handlers this worker runs together (default: no bound but its
279
+ * event loop, {@link LATE}). */
280
+ max?: number
281
+ /** Ask the host to wake after a commit owes work or a full pool frees a slot. */
282
+ nudge?: () => void
283
+ /** Positive integer maximum candidates examined per pass, including fresh
284
+ * start-up admission (default: 32). */
285
+ page?: number
286
+ /** The code version this process runs (a Worker version's id): what a run
287
+ * records as its attempt starts, so one cut off by a deploy runs again as
288
+ * the same attempt while one whose process crashed under the same code
289
+ * spends one. Without it, every interruption spends an attempt. */
290
+ version?: string
291
+ /** Leave committed runs for work() instead of starting them on the writer. */
292
+ defer?: boolean
293
+ /** how long a claim holds, in milliseconds (default: 60_000) */
294
+ lease?: number
295
+ /** the most attempts a run gets where its declaration says none (default:
296
+ * {@link TRIES}) */
297
+ tries?: number
298
+ /** how long after the nth attempt the next is due, in milliseconds
299
+ * (default: {@link backoff}) */
300
+ backoff?: (attempts: number) => number
301
+ /** the time the pool keeps, in milliseconds, and the timers it waits on:
302
+ * a retry's backoff, the turn and the nap between passes, a claim's renewal
303
+ * (default: the runtime's, @yaks/fp `system`) */
304
+ clock?: Clock
305
+ /** ids for the rows it writes (default: `crypto.randomUUID()`) */
306
+ mint?: () => Eid
307
+ /** whether a process is known to be over (@yaks/process `gone`), so its
308
+ * presence need not be waited out. Ending processes release their claims;
309
+ * otherwise claims recover when their leases expire. */
310
+ gone?: (holder: Eid) => boolean | Promise<boolean>
311
+ /** The CPU time this process has spent so far, in ms (`process.cpuUsage`,
312
+ * user and system together): a worker that stays says from it how busy its
313
+ * process is. Without it, a worker says nothing of its CPU. */
314
+ cpu?: () => number
315
+ /** Hear the runs another process commits soon after they land (@yaks/sqlite
316
+ * `Store.watch` of the `effect` component): `heard` is called, and a
317
+ * worker that stays passes at once instead of at the next pass, up to
318
+ * {@link CAP} away. Answers a stop. */
319
+ watch?: (heard: () => void) => () => void
320
+ /** Make the pool's write of how a run ended, where the storage would
321
+ * refuse it for a while (@yaks/durable-object `Ceiling.free`): a run that
322
+ * finished and could not say so would run again. Without it the write is
323
+ * made as any other. */
324
+ free?: <T>(write: () => Promise<T>) => Promise<T>
325
+ /** Run the pool's work apart from whatever started it: a request's ambient
326
+ * context (a Worker's count of its round trips) does not reach the runs a
327
+ * write nudged. Every start of the pool goes through it. Without it the
328
+ * work runs where it was called. */
329
+ apart?: <T>(work: () => T) => T
330
+ }
331
+
332
+ /** A run this process claimed as it wrote it, to start after the commit. */
333
+ export type Owed = { eid: Eid; row: Comp }
334
+
335
+ /** What the pool is given by the registry it serves. */
336
+ export type Ctx = {
337
+ /** every registration, declared and observed */
338
+ slots: () => Slot[]
339
+ /** the write callback a run writes through, a generation on */
340
+ writer: (gen: number, context?: HookContext) => Write
341
+ report: Report
342
+ }
343
+
344
+ /** Work requested by one host invocation. */
345
+ export type WorkOpts = {
346
+ /** Maximum discovery passes; omitted, drain until nothing is left to start. */
347
+ passes?: number
348
+ /** A drain starts another bounded pass only while the host has capacity. */
349
+ while?: () => boolean
350
+ /** The instant (ms, the pool's clock) a drain stops starting runs: what it
351
+ * started goes on, and what is owed waits for the host's next call. */
352
+ until?: number
353
+ /** Owe fresh start-up runs and start those fitting the worker's free slots. */
354
+ startup?: boolean
355
+ }
356
+
357
+ /** The pool over one registry: what a commit owes, and the worker. */
358
+ export type Pool = {
359
+ /** Write down the runs a batch owes, inside its transaction — claimed by
360
+ * this process where it works the pool and can run them. Returns those. */
361
+ owe: (
362
+ tx: Tx,
363
+ found: [Slot, Event][],
364
+ gen: number,
365
+ ) => Owed[] | Promise<Owed[]>
366
+ /** Start what this process claimed as it wrote it, once the commit is
367
+ * done. */
368
+ start: (owed: Owed[]) => void
369
+ /** Persist handled start-up runs without joining or draining the pool.
370
+ * Each call owes a fresh run, targeting owner; the host chooses when.
371
+ * A failed write rejects so the host can retry its start-up pass. */
372
+ startup: (g: Access) => Promise<void>
373
+ /** Work the pool: with a live signal, until it aborts; with an aborted
374
+ * one, pass after pass until nothing is left to start, giving way to the
375
+ * host between them — and none at all where a process that stays up is
376
+ * already working it. Repeated live calls share the current worker; its
377
+ * first signal owns its lifetime. A finite drain answers whether it
378
+ * admitted or settled any work. */
379
+ work: (
380
+ g: Access,
381
+ signal?: AbortSignal,
382
+ options?: number | WorkOpts,
383
+ ) => Promise<boolean>
384
+ /** Look again now, rather than at the next pass: what a thread beside this
385
+ * one says after it wrote runs down (./registry.ts `nudge`). */
386
+ wake: () => void
387
+ /** Settles once every run started here has, and a worker whose signal
388
+ * aborted has stopped, keeping their claims while it waits. */
389
+ idle: () => Promise<void>
390
+ /** Leave the pool: claim nothing more — what this process commits from
391
+ * now on is left for the others — and settle what was started. */
392
+ stop: () => Promise<void>
393
+ /** Set the earliest takeover of unfinished claims before a forced process
394
+ * exit. The caller must have stopped admission and exit before `at`. */
395
+ handoff: (at: number) => Promise<void>
396
+ /** The runs going in this process, oldest first. */
397
+ running: () => Run[]
398
+ /** When the soonest run this process can take falls due (ms, the pool's
399
+ * clock): `now` when one is due already, null when none is owed. What a
400
+ * host that sleeps between passes sets its wake by. */
401
+ next: (g: Access, now?: number) => Promise<number | null>
402
+ }
403
+
404
+ /** A run going in this process: its row, what it is, and when it started
405
+ * (ms, the pool's clock). */
406
+ export type Run = { eid: Eid; handler: string; target: Eid; since: number }
407
+
408
+ /** Whether a process that stays up is working the pool over `g`: a presence
409
+ * lease other than `except`'s, still standing, held by a process not known
410
+ * to be gone. */
411
+ export let working = async (
412
+ g: Access,
413
+ o: {
414
+ /** the asking process, whose own presence does not count */
415
+ except?: Eid
416
+ /** the clock, in milliseconds (default: `Date.now()`) */
417
+ now?: number
418
+ gone?: PoolOpts['gone']
419
+ } = {},
420
+ ): Promise<boolean> => {
421
+ if (!g.vocab.comp(LEASE)) return false
422
+ let now = o.now ?? Date.now()
423
+ let rows = (await g.read(line`.${LEASE}`)) as Bundle[]
424
+ for (let b of rows) {
425
+ let l = (b[LEASE] ?? {}) as Comp
426
+ let holder = l.holder as Eid | undefined
427
+ if (!holder || holder == o.except || l.name != `${POOL}/${holder}`) {
428
+ continue
429
+ }
430
+ if (Date.parse(String(l.until)) <= now) continue
431
+ if (!await o.gone?.(holder)) return true
432
+ }
433
+ return false
434
+ }
435
+
436
+ // What a handler threw, as the row can keep it.
437
+ let said = (err: unknown): string =>
438
+ err instanceof Error ? err.message : String(err)
439
+
440
+ // Whether `p` is still going after `ms`: true when the wait ran out first.
441
+ let still = (
442
+ p: Promise<unknown>,
443
+ ms: number,
444
+ time: Clock,
445
+ ): Promise<boolean> =>
446
+ new Promise((answer) => {
447
+ let cancel = time.after(ms, () => answer(true))
448
+ let over = () => {
449
+ cancel()
450
+ answer(false)
451
+ }
452
+ p.then(over, over)
453
+ })
454
+
455
+ // A run going in this process: what it is, the claim it holds, and the run
456
+ // itself.
457
+ type Held = Run & {
458
+ token: string
459
+ attempts: number
460
+ expiry: number
461
+ run: Promise<void>
462
+ }
463
+
464
+ /** The pool over one registry: what a commit owes, and the worker. */
465
+ export let pool = (ctx: Ctx, opts: Partial<PoolOpts> = {}): Pool => {
466
+ // A pass admits at most this many candidates, even when concurrency is
467
+ // unlimited; any other window than a whole number of them cannot make
468
+ // bounded progress, so it is refused before anything is built.
469
+ let page = opts.page ?? 32
470
+ if (!Number.isSafeInteger(page) || page < 1) {
471
+ throw new RangeError('effect page must be a positive integer')
472
+ }
473
+ let me = opts.owner ?? crypto.randomUUID()
474
+ let time = opts.clock ?? system
475
+ let clock = () => time.now()
476
+ let apart = opts.apart ?? (<T>(work: () => T) => work())
477
+ let hold = opts.lease ?? 60_000
478
+ let mint = opts.mint ?? (() => crypto.randomUUID() as Eid)
479
+ let wait = opts.backoff ?? backoff
480
+ let max = opts.max ?? Infinity
481
+ let disabled = new Set(opts.disabled)
482
+ let stamp = (ms: number) => new Date(ms).toISOString()
483
+ let limit = (s?: Slot) => s?.effect?.tries ?? opts.tries ?? TRIES
484
+ let safe = (s?: Slot) => s?.effect?.idempotent != false
485
+ // The declared effects this process can run, by name.
486
+ let handled = (id: string) =>
487
+ ctx.slots().find((s) => s.id == id && s.effect && s.run)
488
+ let waitingFor = (slots: Slot[]) => {
489
+ let waiting = new Map<string, string>()
490
+ let seen = new Set<string>()
491
+ for (let { id, run } of slots) {
492
+ if (!run?.waiting || disabled.has(id) || seen.has(id)) continue
493
+ seen.add(id)
494
+ try {
495
+ let reason = run.waiting()
496
+ if (reason) waiting.set(id, reason)
497
+ } catch { /* let the attempt handle a dependency check that threw */ }
498
+ }
499
+ return waiting
500
+ }
501
+
502
+ // A fifo queue's head: the run a worker holds, else the one its handler's
503
+ // rank puts first, else the oldest. A rank is read at each choice, so a
504
+ // run ranked above a deferred head goes before it.
505
+ let foremost = async (g: Access, name: string) => {
506
+ let rank = handled(name)?.rank
507
+ if (!rank) return firstPending(g, name)
508
+ let runs = await g.read(
509
+ and(
510
+ eq(`${EFFECT}.handler`, name),
511
+ eq(`${EFFECT}.state`, 'pending'),
512
+ order(`${EFFECT}.at`),
513
+ window(QUEUE),
514
+ ),
515
+ { unordered: true },
516
+ )
517
+ let now = clock()
518
+ let held = runs.find((b) =>
519
+ running.has(b.entity.eid) ||
520
+ Date.parse(String((b[EFFECT] as Comp).lease_expiry)) > now
521
+ )
522
+ if (held || runs.length < 2) return held ?? runs[0]
523
+ let ranks = await rank(runs, g.outside)
524
+ let at = (i: number) => ranks[i] ?? Infinity
525
+ return runs[runs.reduce((best, _, i) => at(i) < at(best) ? i : best, 0)]
526
+ }
527
+
528
+ // Whether this process works the pool, and the graph it works it on: until
529
+ // then, what it commits is written down for somebody else.
530
+ let member = false
531
+ let graph: Access | undefined
532
+ let running = new Map<Eid, Held>()
533
+ let admitting = 0
534
+ // Runs that ended here, however they ended: in all, by the second, and how
535
+ // many threw. What a worker says of itself (./worker.ts).
536
+ let ran = 0, errors = 0
537
+ let ends = seconds()
538
+ let loop: { done: Promise<void>; signal: AbortSignal } | undefined
539
+ // How late the last turn this worker gave way came back, by its clock: a
540
+ // full event loop runs it late.
541
+ let behind = 0
542
+ let turn = async () => {
543
+ let at = clock()
544
+ await sleep(0, undefined, time)
545
+ behind = clock() - at
546
+ }
547
+ // Whether this process takes another run: it works the pool, has a slot,
548
+ // and its thread is keeping up.
549
+ let room = (taken = 0) =>
550
+ member && running.size + admitting + taken < max && behind <= LATE
551
+
552
+ // What an attempt records as it starts: the code it runs, and, on a shared
553
+ // store, the claim.
554
+ let claim = () => ({
555
+ ...opts.version ? { version: opts.version } : {},
556
+ ...opts.singleOwner ? {} : {
557
+ lease_owner: me,
558
+ lease_token: mint(),
559
+ lease_expiry: stamp(clock() + hold),
560
+ },
561
+ })
562
+ // How the pool writes down how a run ended (`PoolOpts.free`).
563
+ let freely = opts.free ?? (<T>(write: () => Promise<T>) => write())
564
+ // Shared workers release their claims on every ending. A single-owner
565
+ // store never writes claim fields, even when draining a legacy row.
566
+ let free = opts.singleOwner
567
+ ? {}
568
+ : { lease_owner: null, lease_token: null, lease_expiry: null }
569
+
570
+ // Compare and set: the patch lands only if the row's claim and attempt count
571
+ // are still the ones read — the graph's own precondition, riding on the
572
+ // write like any other (@yaks/graph `$was`).
573
+ let guarded = (eid: Eid, was: Comp): Bundle => ({
574
+ entity: { eid },
575
+ $was: {
576
+ [EFFECT]: {
577
+ ...(opts.singleOwner ? {} : {
578
+ lease_token: token(was.lease_token ?? null),
579
+ }),
580
+ attempts: token(was.attempts ?? null),
581
+ },
582
+ },
583
+ })
584
+ let changing = (eid: Eid, was: Comp, patch: Comp): Bundle => ({
585
+ ...guarded(eid, was),
586
+ [EFFECT]: patch,
587
+ })
588
+ // Whether `write` landed, or found the row's claim moved on.
589
+ let landed = async (write: () => Promise<boolean>): Promise<boolean> => {
590
+ try {
591
+ return await write()
592
+ } catch (error) {
593
+ if (error instanceof Stale) return false
594
+ throw error
595
+ }
596
+ }
597
+ // A run is the pool's own bookkeeping: nothing refers to it and nothing
598
+ // derives from it, so it is written through storage alone (@yaks/graph
599
+ // `book`). Through `apply()` a claim was stamped `created` and moved to
600
+ // another archetype, eleven rows on the platform tracker where one does.
601
+ let swap = (g: Access, eid: Eid, was: Comp, patch: Comp) =>
602
+ landed(async () =>
603
+ (await g.book([changing(eid, was, patch)])).includes(eid)
604
+ )
605
+ // A finished run's row leaves under the same guard, erased.
606
+ let drop = (g: Access, eid: Eid, was: Comp) =>
607
+ landed(async () =>
608
+ (await g.book([{ ...guarded(eid, was), $delete: true }])).includes(eid)
609
+ )
610
+
611
+ // One claimed run: the event rebuilt from what the target holds now, the
612
+ // handler, and the outcome written back under the same claim. A run with
613
+ // no row (`kept` false, a single-owner start-up run, `starting`) writes
614
+ // only a failure, as the row a retry reads.
615
+ let start = (
616
+ g: Access,
617
+ eid: Eid,
618
+ row: Comp,
619
+ cause?: string,
620
+ kept = true,
621
+ ) => {
622
+ let s = handled(String(row.handler))
623
+ let c = peek(g)
624
+ let span: Span | undefined
625
+ if (c) {
626
+ span = c.begin({
627
+ kind: 'effect',
628
+ name: s?.id ?? 'unhandled',
629
+ package: '@yaks/effects',
630
+ parent: cause,
631
+ })
632
+ }
633
+ let held: Held = {
634
+ eid,
635
+ handler: String(row.handler),
636
+ target: String(row.target),
637
+ since: clock(),
638
+ token: row.lease_token as string,
639
+ attempts: Number(row.attempts),
640
+ expiry: Date.parse(String(row.lease_expiry)),
641
+ run: Promise.resolve(),
642
+ }
643
+ let tries = held.attempts
644
+ let deferred: number | undefined
645
+ let waiting: string | undefined
646
+ let settle = (patch: Comp) =>
647
+ kept
648
+ ? swap(g, eid, { lease_token: held.token, attempts: held.attempts }, {
649
+ ...patch,
650
+ attempts: tries,
651
+ })
652
+ : g.apply([{
653
+ entity: { eid },
654
+ [EFFECT]: { ...row, ...patch, attempts: tries },
655
+ }], { trusted: true })
656
+ // A success puts the count back at this attempt, the first: only a run
657
+ // that has failed before has anything to write.
658
+ let attempt: Attempt = {
659
+ last: () => tries >= limit(s),
660
+ defer: (delay, reason) => {
661
+ if (!Number.isFinite(delay) || delay <= 0) {
662
+ throw new RangeError('an effect deferral needs a positive delay')
663
+ }
664
+ deferred = Math.max(deferred ?? 0, clock() + delay)
665
+ waiting = reason
666
+ return Promise.resolve()
667
+ },
668
+ progressed: async () => {
669
+ tries = 1
670
+ if (held.attempts <= 1) return
671
+ let was = { lease_token: held.token, attempts: held.attempts }
672
+ if (await swap(g, eid, was, { attempts: 1 })) held.attempts = 1
673
+ },
674
+ }
675
+ attempt.retry = async <T>(body: () => Promise<T>): Promise<T> => {
676
+ while (true) {
677
+ try {
678
+ return await body()
679
+ } catch (err) {
680
+ if (attempt.last() || !member) throw err
681
+ ctx.report(err, {
682
+ handler: String(row.handler),
683
+ slot: s,
684
+ event: {
685
+ kind: String(row.kind) as Kind,
686
+ entity: { eid: String(row.target) },
687
+ name: String(row.comp ?? ''),
688
+ },
689
+ })
690
+ let due = Math.max(wait(tries), asked(err))
691
+ await sleep(due, undefined, time)
692
+ tries++
693
+ }
694
+ }
695
+ }
696
+ let go = async () => {
697
+ let tx = g.outside
698
+ let kind = String(row.kind) as Kind
699
+ let name = String(row.comp ?? '')
700
+ let [found] = await tx.get(
701
+ [String(row.target)],
702
+ kind == 'started' ? [] : name ? [name] : undefined,
703
+ )
704
+ let entity = found?.entity ?? { eid: String(row.target) }
705
+ let before = row.before as Comp | undefined
706
+ let event: Event = {
707
+ at: String(row.at),
708
+ run: eid,
709
+ invocation: row.invocation as Event['invocation'],
710
+ kind,
711
+ entity,
712
+ name,
713
+ touched: row.touched as string[] | undefined,
714
+ ...row.actor ? { actor: row.actor as Actor } : {},
715
+ ...(kind != 'removed'
716
+ ? { comp: found?.[name] as Comp }
717
+ : before
718
+ ? { before: { ...before, entity } }
719
+ : {}),
720
+ }
721
+ // An attempt that failed with `err`, written down: tried again after
722
+ // its wait, or failed once nothing will.
723
+ let failed = (err: unknown) => {
724
+ errors++
725
+ // A deferral gives its attempt back and is due after its wait.
726
+ let waits = deferral(err)
727
+ if (waits) tries = Math.max(0, tries - 1)
728
+ // An error that asks to be tried again is the handler waiting on
729
+ // something outside, expected and kept on the row; it is reported
730
+ // only once nothing will try it again.
731
+ let last = !waits && attempt.last()
732
+ if (last || !retried(err)) {
733
+ ctx.report(err, { handler: String(row.handler), event, slot: s })
734
+ }
735
+ let due = waits ? asked(err) : Math.max(wait(tries), asked(err))
736
+ let patch = last
737
+ ? {
738
+ state: 'failed',
739
+ error: said(err),
740
+ next: null,
741
+ waiting: null,
742
+ ...free,
743
+ }
744
+ : {
745
+ state: 'pending',
746
+ error: said(err),
747
+ next: stamp(clock() + due),
748
+ waiting: null,
749
+ ...free,
750
+ }
751
+ return () => settle(patch)
752
+ }
753
+ // How the run ended, for its row.
754
+ let ended: (() => unknown) | undefined
755
+ try {
756
+ if (!s?.run) throw new Error(`no effect is handled as ${row.handler}`)
757
+ let match = event.invocation?.match
758
+ let chosen = match
759
+ ? ctx.slots().find((slot) =>
760
+ slot.id == row.handler && slot.declaration == match && slot.run
761
+ )
762
+ : s
763
+ let eligible = chosen &&
764
+ (!chosen.eligible || await chosen.eligible(entity.eid, tx))
765
+ if (eligible && chosen) {
766
+ await chosen.run!(
767
+ event,
768
+ tx,
769
+ ctx.writer(
770
+ Number(row.generation ?? 0),
771
+ span && peek(g) ? { graph: g, parent: span.id } : undefined,
772
+ ),
773
+ attempt,
774
+ )
775
+ }
776
+ if (peek(g) && span?.active) {
777
+ span.end({ counts: { runs: Number(eligible) } })
778
+ }
779
+ if (deferred != null) {
780
+ let next = stamp(deferred)
781
+ tries = Math.max(0, tries - 1)
782
+ ended = () =>
783
+ settle({
784
+ state: 'pending',
785
+ next,
786
+ waiting: waiting ?? null,
787
+ ...free,
788
+ })
789
+ } else if (kept) {
790
+ let was = { lease_token: held.token, attempts: held.attempts }
791
+ ended = () => drop(g, eid, was)
792
+ }
793
+ } catch (err) {
794
+ if (peek(g) && span?.active) {
795
+ span.end({ outcome: outcome(err), counts: { runs: 1 } })
796
+ }
797
+ ended = failed(err)
798
+ }
799
+ // Pool bookkeeping follows the completed handler, not its trace, and is
800
+ // made though its object refuses for a while (`freely`). An ending the
801
+ // store refused would leave the run claimed, which the next pass reads
802
+ // as a run whose process ended under it, and starts again at once: it is
803
+ // this attempt's failure instead, and waits as a thrown one does.
804
+ let end = (write: () => unknown) =>
805
+ freely(async () => await scope(undefined, write))
806
+ if (ended) await end(ended).catch((err) => end(failed(err)))
807
+ }
808
+ // A host's task-local carrier retains this effect's ancestry across
809
+ // asynchronous reads and handler work. Explicit write parents still work
810
+ // for hosts without one, and the existing success/error boundaries end it.
811
+ held.run = during(span, go)
812
+ .catch((err) => {
813
+ if (peek(g) && span?.active) span.end({ outcome: outcome(err) })
814
+ return ctx.report(err, {
815
+ handler: String(row.handler),
816
+ event: { kind: 'created', entity: { eid }, name: EFFECT },
817
+ })
818
+ })
819
+ .finally(() => {
820
+ let saturated = running.size + admitting >= max
821
+ running.delete(eid)
822
+ ran++
823
+ ends.count(clock())
824
+ if (saturated && member && opts.defer) opts.nudge?.()
825
+ if (full || s?.effect?.fifo) nap?.abort()
826
+ })
827
+ running.set(eid, held)
828
+ return held.run
829
+ }
830
+
831
+ // One pass over what is owed: every row this process can run that nobody
832
+ // holds and whose backoff is up, claimed and started. Returns the runs.
833
+ // Separate handler windows keep one backlog from owning the pass.
834
+ let next = 0
835
+ // The last pass found every slot taken: the next run to end wakes the
836
+ // worker, rather than leaving its slot empty for a nap.
837
+ let full = false
838
+ let pending: And, signature = ''
839
+ // The worker's wait between passes, which a wake cuts short.
840
+ let nap: AbortController | undefined
841
+ type Pass = { started: Promise<void>[]; more: boolean; progressed: boolean }
842
+ // In a single-owner store most alarm and deployment passes find an empty
843
+ // queue. The state index can answer that before planning eligibility for
844
+ // every handler or reading any of their fields.
845
+ let pendingHead = and(
846
+ eq(`${EFFECT}.state`, 'pending'),
847
+ window(1),
848
+ fields('entity.eid'),
849
+ )
850
+ let emptyQueue = async (g: Access): Promise<boolean> =>
851
+ !(await g.rows(pendingHead, { unordered: true })).length
852
+
853
+ let due = async (g: Access, budget = page): Promise<Pass> => {
854
+ let now = clock()
855
+ let started: Promise<void>[] = []
856
+ let claims: { eid: Eid; row: Comp; mine: Comp }[] = []
857
+ let reserved = 0, progressed = false
858
+ full = false
859
+ let slots = ctx.slots().filter((s) => s.effect && s.run)
860
+ let names = [...new Set([...slots.map((s) => s.id), ...disabled])]
861
+ if (!room() || !names.length) {
862
+ full = member && running.size + admitting >= max
863
+ // A thread behind takes its next turn before it looks again.
864
+ return {
865
+ started,
866
+ more: member && !!names.length && behind > LATE,
867
+ progressed,
868
+ }
869
+ }
870
+ if (!budget) return { started, more: true, progressed }
871
+ if (opts.singleOwner && await emptyQueue(g)) {
872
+ return { started, more: false, progressed }
873
+ }
874
+ // Every handler's ready runs but our own live ones, a page of them: what
875
+ // a pass can examine. A page that comes back short holds all there are.
876
+ let live = [...running.keys()]
877
+ let ordered = new Set(
878
+ slots.filter((s) => s.effect?.fifo && !disabled.has(s.id))
879
+ .map((s) => s.id),
880
+ )
881
+ let other = names.filter((name) => !ordered.has(name))
882
+ let waiting = waitingFor(slots)
883
+ let key = JSON.stringify([other, live, [...waiting]])
884
+ if (other.length && key != signature) {
885
+ pending = and(
886
+ ...ready(other, {
887
+ singleOwner: opts.singleOwner,
888
+ disabled: [...disabled],
889
+ owner: me,
890
+ waiting,
891
+ }).clauses,
892
+ window(page),
893
+ ...live.length ? [ne('entity.eid', list(...live))] : [],
894
+ )
895
+ signature = key
896
+ }
897
+ let found = other.length
898
+ ? await g.read(pending, { unordered: true, now })
899
+ : []
900
+ let first = new Map(
901
+ await Promise.all(
902
+ [...ordered].map(async (name) =>
903
+ [name, await foremost(g, name)] as const
904
+ ),
905
+ ),
906
+ )
907
+ if (!found.length && ![...first.values()].some(Boolean)) {
908
+ return { started, more: false, progressed }
909
+ }
910
+ let eligible = (row: Comp) =>
911
+ (!row.waiting || row.waiting != waiting.get(String(row.handler))) &&
912
+ !(Date.parse(String(row.next)) > now) &&
913
+ (opts.singleOwner || !row.lease_owner ||
914
+ !(Date.parse(String(row.lease_expiry)) > now))
915
+ let examine = async (b: Bundle) => {
916
+ let eid = b.entity.eid
917
+ let row = (b[EFFECT] ?? {}) as Comp
918
+ // An older writer can still owe an opt-in this config disables. Settle
919
+ // that obsolete errand without inventing a handler or spending an attempt.
920
+ if (disabled.has(String(row.handler)) && !row.lease_owner) {
921
+ try {
922
+ let [whole] = await g.get([eid])
923
+ let current = whole?.[EFFECT] as Comp | undefined
924
+ if (current?.state == 'pending' && !current.lease_owner) {
925
+ await g.apply(finishedRun(whole), { trusted: true })
926
+ progressed = true
927
+ }
928
+ } catch (e) {
929
+ if (!(e instanceof Stale)) throw e
930
+ }
931
+ return
932
+ }
933
+ let s = handled(String(row.handler))
934
+ if (!s || running.has(eid)) return
935
+ if (!eligible(row)) return
936
+ // A due time on a held claim is a deliberate handoff. Check that the
937
+ // retiring process has actually exited, even if its timer ran late.
938
+ if (
939
+ row.next && row.lease_owner && opts.gone &&
940
+ !await opts.gone(String(row.lease_owner))
941
+ ) return
942
+ let attempts = Number(row.attempts ?? 0)
943
+ // Claimed and no `next`: interrupted, not reported, so how far it got
944
+ // is unknown — and a second run is not the same as a first. Started
945
+ // under other code, a deploy cut it off; under this code, it crashed.
946
+ let interrupted = attempts > 0 && !row.next
947
+ let cut = interrupted && !!opts.version && row.version != opts.version
948
+ // An interruption left failed is a failure no handler threw, so the
949
+ // pool reports it itself.
950
+ let abandon = async (error: string) => {
951
+ let patch = { state: 'failed', error, next: null, ...free }
952
+ if (!await swap(g, eid, row, patch)) return
953
+ progressed = true
954
+ ctx.report(new Error(`${row.handler}: ${error}`), {
955
+ handler: String(row.handler),
956
+ event: { kind: 'created', entity: { eid }, name: EFFECT },
957
+ slot: s,
958
+ })
959
+ }
960
+ if (interrupted && !safe(s)) {
961
+ return abandon(`interrupted, and ${row.handler} is not idempotent`)
962
+ }
963
+ // Every attempt spent: left failed, with the last error beside it. A
964
+ // deploy's cut spent none: it runs again as the same attempt rather
965
+ // than leaving the run failed by however many deploys it met.
966
+ if (!cut && attempts >= limit(s)) {
967
+ if (interrupted) {
968
+ return abandon(`its process ended under it in attempt ${attempts}`)
969
+ }
970
+ if (await swap(g, eid, row, { state: 'failed', next: null, ...free })) {
971
+ progressed = true
972
+ }
973
+ return
974
+ }
975
+ // Reads and owner checks can yield to a writer that fills a slot.
976
+ // Reserve against the current admission count, not the scan's earlier one.
977
+ if (!room()) return
978
+ // `next` keys three of the run's indexes, so a claim clears it only
979
+ // where a backoff set it.
980
+ let mine = {
981
+ attempts: cut ? attempts : attempts + 1,
982
+ ...row.next ? { next: null } : {},
983
+ ...claim(),
984
+ }
985
+ claims.push({ eid, row, mine })
986
+ admitting++
987
+ reserved++
988
+ }
989
+ // What the page holds of a handler's runs heads its backlog. A short page
990
+ // held them all, so a handler it holds none of is drained without a read;
991
+ // after a full one, a handler whose rows run out reads its own window.
992
+ let drained = new Set<string>(), visited = new Set(live)
993
+ let heads = new Map(
994
+ names.map((name) => [name, {
995
+ rows: [] as Bundle[],
996
+ full: found.length == page,
997
+ }]),
998
+ )
999
+ for (let b of found) {
1000
+ heads.get(String((b[EFFECT] as Comp).handler))?.rows.push(b)
1001
+ }
1002
+ try {
1003
+ while (room() && budget > 0 && drained.size < names.length) {
1004
+ let name = names[next % names.length]
1005
+ next = (next + 1) % names.length
1006
+ if (drained.has(name)) continue
1007
+ // One candidate, then the next handler's, not the rest of this backlog.
1008
+ if (first.has(name)) {
1009
+ drained.add(name)
1010
+ let b = first.get(name)
1011
+ // A held, deferred or local run heads this queue until a run
1012
+ // ranked above it is owed.
1013
+ if (b && !running.has(b.entity.eid) && eligible(b[EFFECT] as Comp)) {
1014
+ budget--
1015
+ await examine(b)
1016
+ }
1017
+ continue
1018
+ }
1019
+ let cached = heads.get(name)
1020
+ if (!cached || !cached.rows.length && cached.full) {
1021
+ let n = Math.min(budget, max - running.size - admitting)
1022
+ let rows = await g.read(
1023
+ except(
1024
+ head(
1025
+ name,
1026
+ !!opts.singleOwner,
1027
+ disabled.has(name),
1028
+ n,
1029
+ me,
1030
+ waiting.get(name),
1031
+ ),
1032
+ [...visited],
1033
+ ),
1034
+ { unordered: true, now },
1035
+ )
1036
+ heads.set(name, cached = { rows, full: rows.length == n })
1037
+ }
1038
+ let b = cached.rows.shift()
1039
+ // Revisit a drained handler's head next pass: a writer can owe it a
1040
+ // new run while another handler still has thousands left to examine.
1041
+ // Finding it empty spends no budget, so idle handlers cannot crowd a
1042
+ // backlog out of the pass.
1043
+ if (!b) {
1044
+ drained.add(name)
1045
+ continue
1046
+ }
1047
+ budget--
1048
+ visited.add(b.entity.eid)
1049
+ await examine(b)
1050
+ }
1051
+ if (!member) {
1052
+ return { started, more: false, progressed }
1053
+ }
1054
+ let begin = ({ eid, row, mine }: typeof claims[number]) => {
1055
+ admitting--
1056
+ reserved--
1057
+ started.push(start(g, eid, { ...row, ...mine }))
1058
+ }
1059
+ if (claims.length == 1) {
1060
+ let c = claims[0]
1061
+ if (await swap(g, c.eid, c.row, c.mine)) begin(c)
1062
+ } else if (claims.length) {
1063
+ let committed: Set<Eid> | undefined
1064
+ try {
1065
+ committed = new Set(
1066
+ await g.book(
1067
+ claims.map(({ eid, row, mine }) => changing(eid, row, mine)),
1068
+ ),
1069
+ )
1070
+ } catch (error) {
1071
+ if (!(error instanceof Stale)) throw error
1072
+ }
1073
+ if (committed) {
1074
+ for (let c of claims) if (committed.has(c.eid)) begin(c)
1075
+ } else {
1076
+ // Another worker may have taken just one row. Its stale guard
1077
+ // rolls back the batch; the remaining claims can still proceed.
1078
+ for (let c of claims) {
1079
+ if (await swap(g, c.eid, c.row, c.mine)) begin(c)
1080
+ }
1081
+ }
1082
+ }
1083
+ } finally {
1084
+ admitting -= reserved
1085
+ }
1086
+ full = member && running.size >= max
1087
+ let more = started.length > 0 || budget <= 0
1088
+
1089
+ return { started, more, progressed: progressed || !!started.length }
1090
+ }
1091
+
1092
+ // Drains may overlap on the same registry. Serialize selection
1093
+ // through attempt persistence and local admission: another pass must see the
1094
+ // running set before reading an attempt just written by this pass.
1095
+ let passing: Promise<unknown> = Promise.resolve()
1096
+ let pass = (g: Access, budget = page): Promise<Pass> => {
1097
+ let next = passing.then(() => due(g, budget))
1098
+ passing = next.catch(() => {})
1099
+ return next
1100
+ }
1101
+
1102
+ // The claims this process is running, pushed out before they lapse.
1103
+ let renew = async (g: Access) => {
1104
+ if (opts.singleOwner) return
1105
+ let now = clock()
1106
+ for (let [eid, held] of running) {
1107
+ if (held.expiry - now > hold / 2) continue
1108
+ let expiry = now + hold
1109
+ let was = { lease_token: held.token, attempts: held.attempts }
1110
+ if (await swap(g, eid, was, { lease_expiry: stamp(expiry) })) {
1111
+ held.expiry = expiry
1112
+ }
1113
+ }
1114
+ }
1115
+
1116
+ // Its presence lease goes with it, so nobody waits out its expiry.
1117
+ let stay = async (g: Access, signal: AbortSignal, budget = page) => {
1118
+ let seat = `${POOL}/${me}`
1119
+ let present = !opts.singleOwner && !!opts.owner && !!g.vocab.comp(LEASE) &&
1120
+ ctx.slots().every((s) => !s.effect || disabled.has(s.id) || !!s.run)
1121
+ let until = 0
1122
+ let told = (err: unknown) =>
1123
+ ctx.report(err, {
1124
+ handler: POOL,
1125
+ event: { kind: 'created', entity: { eid: me }, name: EFFECT },
1126
+ })
1127
+ // What it says of itself, every SAY (./worker.ts): busy as the
1128
+ // CPU its process used and how late its thread ran a timer, both over
1129
+ // the time since it last said, by the wall's clock rather than the pool's.
1130
+ let speaks = !opts.singleOwner && !!opts.owner && !!g.vocab.comp(WORKER)
1131
+ let lag = speaks ? lagging() : undefined
1132
+ let spoke = -Infinity
1133
+ let spent = {
1134
+ cpu: speaks ? opts.cpu?.() : undefined,
1135
+ at: performance.now(),
1136
+ }
1137
+ let say = async () => {
1138
+ let now = clock()
1139
+ let was = spent
1140
+ spent = { cpu: opts.cpu?.(), at: performance.now() }
1141
+ let cpu = spent.cpu != null && was.cpu != null
1142
+ ? (spent.cpu - was.cpu) / Math.max(1, spent.at - was.at)
1143
+ : undefined
1144
+ let runs = [...running.values()].sort((a, b) => a.since - b.since)
1145
+ await g.apply([{
1146
+ entity: { eid: me },
1147
+ [WORKER]: {
1148
+ at: stamp(now),
1149
+ running: running.size,
1150
+ runs: runs.slice(0, SHOWN).map((r) => ({
1151
+ run: r.eid,
1152
+ handler: r.handler,
1153
+ target: r.target,
1154
+ since: stamp(r.since),
1155
+ })),
1156
+ ran,
1157
+ errors,
1158
+ history: ends.last(now),
1159
+ ...cpu != null ? { cpu: Math.round(cpu * 100) / 100 } : {},
1160
+ lag: lag!.read(),
1161
+ },
1162
+ }], { trusted: true })
1163
+ }
1164
+ // The rows of workers killed before they could take them.
1165
+ let clear = async () => {
1166
+ let rows = (await g.read(line`.${WORKER}`)) as Bundle[]
1167
+ let over = []
1168
+ for (let b of rows) {
1169
+ if (b.entity.eid != me && await opts.gone?.(b.entity.eid)) over.push(b)
1170
+ }
1171
+ if (over.length) {
1172
+ let gone = over.map((b) => ({
1173
+ entity: { eid: b.entity.eid },
1174
+ [WORKER]: null,
1175
+ }))
1176
+ await g.apply(gone, { trusted: true })
1177
+ }
1178
+ }
1179
+ if (speaks && opts.gone) await clear().catch(told)
1180
+ // A wake before the first pass is answered by it.
1181
+ if (!nap || nap.signal.aborted) nap = new AbortController()
1182
+ // A worker that cannot hear other processes still finds their runs, a
1183
+ // pass later.
1184
+ let unwatch = () => {}
1185
+ try {
1186
+ unwatch = opts.watch?.(() => nap?.abort()) ?? unwatch
1187
+ } catch (err) {
1188
+ told(err)
1189
+ }
1190
+ try {
1191
+ while (!signal.aborted) {
1192
+ // A traversal the last pass left unfinished goes on at once; the
1193
+ // worker waits for the next pass only once one finds nothing more.
1194
+ let more = false
1195
+ try {
1196
+ if (present && until - clock() < HOLD / 2) {
1197
+ if (await take(g, seat, { holder: me, now: clock })) {
1198
+ until = clock() + HOLD
1199
+ }
1200
+ }
1201
+ more = (await pass(g, budget)).more
1202
+ budget = page
1203
+ await renew(g)
1204
+ if (speaks && clock() - spoke >= SAY) {
1205
+ spoke = clock()
1206
+ await say()
1207
+ }
1208
+ } catch (err) {
1209
+ if (signal.aborted) break
1210
+ told(err)
1211
+ }
1212
+ // A turn for what the pass started, and a signal to stop, before
1213
+ // the next; a wake ends the nap at once, never the turn.
1214
+ await turn()
1215
+ if (!more) {
1216
+ await sleep(CAP, AbortSignal.any([signal, nap!.signal]), time)
1217
+ }
1218
+ if (nap!.signal.aborted) {
1219
+ nap = new AbortController()
1220
+ await turn()
1221
+ }
1222
+ }
1223
+ } finally {
1224
+ unwatch()
1225
+ nap = undefined
1226
+ lag?.stop()
1227
+ if (present) {
1228
+ try {
1229
+ await g.apply([{ entity: { eid: leaseEid(seat) }, $delete: true }])
1230
+ } catch { /* already gone, or the graph is closing */ }
1231
+ }
1232
+ if (speaks) {
1233
+ try {
1234
+ await g.apply([{ entity: { eid: me }, [WORKER]: null }], {
1235
+ trusted: true,
1236
+ })
1237
+ } catch { /* the graph is closing */ }
1238
+ }
1239
+ }
1240
+ }
1241
+
1242
+ // Start-up work: a run of each `start` effect this process has the code
1243
+ // for, its target this process. The host may owe these explicitly rather
1244
+ // than on joining, so a store waking need not be a store starting.
1245
+ //
1246
+ // A single-owner host owes its start-up pass until the runs it started
1247
+ // there have ended, so a run it starts at once keeps no row: the pass is
1248
+ // its crash recovery, and only a failure is written down, for the retry.
1249
+ // What waits for a slot is a row, like any run owed for later.
1250
+ let starting = async (
1251
+ g: Access,
1252
+ immediate = false,
1253
+ ): Promise<Promise<void>[]> => {
1254
+ let at = stamp(clock())
1255
+ let mine: Owed[] = []
1256
+ let rows: Bundle[] = []
1257
+ for (let s of ctx.slots()) {
1258
+ if (s.kind != 'started' || !s.run) continue
1259
+ let ours = immediate && !disabled.has(s.id) && limit(s) > 0 &&
1260
+ mine.length < page && room(mine.length)
1261
+ let eid = mint()
1262
+ let row: Comp = {
1263
+ handler: s.id,
1264
+ target: me,
1265
+ kind: 'started',
1266
+ state: 'pending',
1267
+ attempts: ours ? 1 : 0,
1268
+ at,
1269
+ generation: 0,
1270
+ ...(ours ? claim() : {}),
1271
+ }
1272
+ if (ours) mine.push({ eid, row })
1273
+ if (!ours || !opts.singleOwner) {
1274
+ rows.push({ entity: { eid }, [EFFECT]: row })
1275
+ }
1276
+ }
1277
+ let reserved = mine.length
1278
+ admitting += reserved
1279
+ try {
1280
+ let applied = rows.length ? await g.apply(rows, { trusted: true }) : []
1281
+ let committed = new Set(applied.map((b) => b.entity.eid))
1282
+ return mine.flatMap(({ eid, row }) => {
1283
+ let kept = !opts.singleOwner
1284
+ if (kept && !committed.has(eid)) return []
1285
+ admitting--
1286
+ reserved--
1287
+ return [start(g, eid, row, undefined, kept)]
1288
+ })
1289
+ } finally {
1290
+ admitting -= reserved
1291
+ }
1292
+ }
1293
+ let startup = async (g: Access): Promise<void> => {
1294
+ await starting(g)
1295
+ }
1296
+
1297
+ // Joining the pool, once: this process claims what it writes from now on,
1298
+ // it owes start-up work where the host chose joining. Source commits have
1299
+ // already recorded every other run; discovery is the same on every pass.
1300
+ let joined = false
1301
+ let join = async (
1302
+ g: Access,
1303
+ requested = false,
1304
+ immediate = true,
1305
+ ): Promise<Promise<void>[]> => {
1306
+ member = true
1307
+ if (joined) return requested ? starting(g, immediate) : []
1308
+ joined = true
1309
+ if (
1310
+ !requested &&
1311
+ (opts.startup ?? (opts.singleOwner ? 'manual' : 'join')) == 'join'
1312
+ ) {
1313
+ try {
1314
+ await startup(g)
1315
+ } catch (err) {
1316
+ ctx.report(err, {
1317
+ handler: POOL,
1318
+ event: { kind: 'started', entity: { eid: me }, name: EFFECT },
1319
+ })
1320
+ }
1321
+ }
1322
+ return requested ? starting(g, immediate) : []
1323
+ }
1324
+
1325
+ // Waiting on what it started, a worker keeps its claims: renewed as they
1326
+ // near expiry whether or not its loop still runs, so a run that outlasts
1327
+ // its lease is never taken by another worker while it is going.
1328
+ let beat = Math.max(1, Math.min(CAP, Math.floor(hold / 4)))
1329
+ let idle = async () => {
1330
+ for (;;) {
1331
+ // Discovery and claim persistence precede running.set. Wait for the
1332
+ // current admission pass before deciding whether anything is running.
1333
+ let pending = passing
1334
+ await pending
1335
+ if (pending !== passing) continue
1336
+ if (!running.size && !(loop?.signal.aborted && loop.done)) return
1337
+ let stopping = loop?.signal.aborted ? loop.done : undefined
1338
+ let settled = Promise.allSettled([
1339
+ stopping,
1340
+ ...[...running.values()].map((h) => h.run),
1341
+ ])
1342
+ if (opts.singleOwner) {
1343
+ await settled
1344
+ continue
1345
+ }
1346
+ while (await still(settled, beat, time)) {
1347
+ if (!graph) continue
1348
+ await renew(graph).catch((err) =>
1349
+ ctx.report(err, {
1350
+ handler: POOL,
1351
+ event: { kind: 'created', entity: { eid: me }, name: EFFECT },
1352
+ })
1353
+ )
1354
+ }
1355
+ }
1356
+ }
1357
+
1358
+ // A freshly owed run has no `next`, so a backlog is one long tie, and a
1359
+ // read of the soonest in `next` order reads every run tied with it: 53,697
1360
+ // rows each time the platform tracker asked behind its backlog (2026-11-12).
1361
+ // So the question is asked first as a pass asks it, `ready`, which stops at
1362
+ // the first run it finds. If later runs exist, walk each handler's `next`
1363
+ // index to find the earliest one without sorting all deferred runs.
1364
+ let soonest = async (g: Access, now = clock()): Promise<number | null> => {
1365
+ if (running.size + admitting >= max) return null
1366
+ if (opts.singleOwner && await emptyQueue(g)) return null
1367
+ let slots = ctx.slots().filter((s) =>
1368
+ s.effect && s.run && !disabled.has(s.id)
1369
+ )
1370
+ let names = [...new Set(slots.map((s) => s.id))]
1371
+ let waiting = waitingFor(slots)
1372
+ let at = Infinity
1373
+ let other: string[] = []
1374
+ let live = [...running.keys()]
1375
+ for (let name of names) {
1376
+ if (!handled(name)?.effect?.fifo) {
1377
+ other.push(name)
1378
+ continue
1379
+ }
1380
+ let head = await foremost(g, name)
1381
+ if (!head || running.has(head.entity.eid)) continue
1382
+ let run = head[EFFECT] as Comp
1383
+ if (run.waiting && run.waiting == waiting.get(name)) {
1384
+ at = Math.min(at, now + RECHECK)
1385
+ continue
1386
+ }
1387
+ let due = Date.parse(String(run.next)) || now
1388
+ let expiry = !opts.singleOwner && run.lease_owner
1389
+ ? Date.parse(String(run.lease_expiry)) || now
1390
+ : now
1391
+ at = Math.min(at, Math.max(due, expiry))
1392
+ }
1393
+ if (at <= now) return now
1394
+ let scheduledAt = opts.singleOwner
1395
+ ? gt(`${EFFECT}.next`, relative('now'))
1396
+ : present(`${EFFECT}.next`)
1397
+ if (other.length) {
1398
+ let [due] = await g.rows(
1399
+ except(
1400
+ and(
1401
+ ...ready(other, {
1402
+ singleOwner: opts.singleOwner,
1403
+ owner: me,
1404
+ waiting,
1405
+ })
1406
+ .clauses,
1407
+ window(1),
1408
+ fields('entity.eid'),
1409
+ ),
1410
+ live,
1411
+ ),
1412
+ { unordered: true, now },
1413
+ )
1414
+ if (due) return now
1415
+ let parked = other.flatMap((name) => {
1416
+ let reason = waiting.get(name)
1417
+ return reason
1418
+ ? [and(
1419
+ eq(`${EFFECT}.handler`, name),
1420
+ eq(`${EFFECT}.waiting`, reason),
1421
+ )]
1422
+ : []
1423
+ })
1424
+ if (parked.length && at > now + RECHECK) {
1425
+ let [blocked] = await g.rows(
1426
+ and(
1427
+ eq(`${EFFECT}.state`, 'pending'),
1428
+ or(...parked),
1429
+ window(1),
1430
+ fields('entity.eid'),
1431
+ ),
1432
+ { unordered: true, now },
1433
+ )
1434
+ if (blocked) at = now + RECHECK
1435
+ }
1436
+ if (other.length > 1) {
1437
+ let [scheduled] = await g.rows(
1438
+ and(
1439
+ eq(`${EFFECT}.state`, 'pending'),
1440
+ available(other, waiting),
1441
+ scheduledAt,
1442
+ window(1),
1443
+ fields('entity.eid'),
1444
+ ),
1445
+ { unordered: true, now },
1446
+ )
1447
+ if (!scheduled) return Number.isFinite(at) ? Math.max(now, at) : null
1448
+ }
1449
+ }
1450
+ for (let name of other) {
1451
+ let [run] = await g.rows(
1452
+ and(
1453
+ eq(`${EFFECT}.state`, 'pending'),
1454
+ available([name], waiting),
1455
+ scheduledAt,
1456
+ order(`${EFFECT}.next`),
1457
+ window(1),
1458
+ fields(`${EFFECT}.next`),
1459
+ ),
1460
+ { unordered: true, now },
1461
+ )
1462
+ let next = Date.parse(String(run?.[`${EFFECT}.next`]))
1463
+ if (next < at) at = next
1464
+ }
1465
+ return Number.isFinite(at) ? Math.max(now, at) : null
1466
+ }
1467
+
1468
+ return {
1469
+ next: soonest,
1470
+ owe: (tx, found, gen) => {
1471
+ let at = stamp(clock())
1472
+ let seen = new Set<string>()
1473
+ let rows: Bundle[] = []
1474
+ let mine: Owed[] = []
1475
+ for (let [s, e] of found) {
1476
+ let key = e.invocation?.call ??
1477
+ (e.invocation
1478
+ ? undefined
1479
+ : [s.id, e.entity.eid, e.name, e.kind].join('|'))
1480
+ if (key && seen.has(key)) continue
1481
+ if (key) seen.add(key)
1482
+ let ours = !opts.defer && !s.effect?.fifo && !!s.run &&
1483
+ mine.length < page &&
1484
+ room(mine.length)
1485
+ let row: Comp = {
1486
+ handler: s.id,
1487
+ target: e.entity.eid,
1488
+ comp: e.name,
1489
+ kind: e.kind,
1490
+ touched: e.touched,
1491
+ ...e.invocation ? { invocation: e.invocation } : {},
1492
+ ...e.before ? { before: Object.fromEntries(comps(e.before)) } : {},
1493
+ state: 'pending',
1494
+ attempts: ours ? 1 : 0,
1495
+ at,
1496
+ generation: gen,
1497
+ ...e.actor ? { actor: e.actor } : {},
1498
+ ...(ours ? claim() : {}),
1499
+ }
1500
+ let eid = e.invocation?.call ? callRun(e.invocation.call) : mint()
1501
+ rows.push({ entity: { eid }, [EFFECT]: row })
1502
+ if (ours) mine.push({ eid, row })
1503
+ }
1504
+ let calls = found.flatMap(([, e]) =>
1505
+ e.invocation?.call ? [callRun(e.invocation.call)] : []
1506
+ )
1507
+ let persist = (held: Bundle[]) => {
1508
+ let existing = new Set(held.map((b) => b.entity.eid))
1509
+ return after(
1510
+ tx.patch(rows.filter((b) => !existing.has(b.entity.eid))),
1511
+ () => mine.filter((run) => !existing.has(run.eid)),
1512
+ )
1513
+ }
1514
+ return calls.length
1515
+ ? after(tx.get(calls, [EFFECT]), persist)
1516
+ : persist([])
1517
+ },
1518
+ start: (owed) =>
1519
+ apart(() => {
1520
+ for (let run of owed) {
1521
+ let cause = peek(graph!) ? parent(graph!, run) : undefined
1522
+ start(graph!, run.eid, run.row, cause)
1523
+ unlink(graph!, run)
1524
+ }
1525
+ }),
1526
+ startup,
1527
+ // Without a signal, drain and return. Only a continuing worker needs a
1528
+ // signal; constructing an aborted one also constructs its unused error.
1529
+ work: (g, signal, options = Infinity) =>
1530
+ apart(async () => {
1531
+ let requested = typeof options == 'number'
1532
+ ? { passes: options }
1533
+ : options
1534
+ let passes = requested.passes ?? Infinity
1535
+ let until = requested.until ?? Infinity
1536
+ graph = g
1537
+ if (!signal || signal.aborted) {
1538
+ if (
1539
+ !opts.singleOwner &&
1540
+ await working(g, { except: me, now: clock(), gone: opts.gone })
1541
+ ) {
1542
+ if (requested.startup) await startup(g)
1543
+ return false
1544
+ }
1545
+ if (requested.while?.() === false) return false
1546
+ let opening = await join(g, requested.startup, passes > 0)
1547
+ let progressed = !!opening.length
1548
+ for (
1549
+ let n = 0;
1550
+ n < passes && clock() < until && requested.while?.() !== false;
1551
+ n++
1552
+ ) {
1553
+ let { started, more, progressed: advanced } = await pass(
1554
+ g,
1555
+ n ? page : page - opening.length,
1556
+ )
1557
+ progressed ||= advanced
1558
+ if (!n && opening.length) started = [...opening, ...started]
1559
+ if (!started.length && !more && !running.size) break
1560
+ // A drain refills a slot as soon as its run ends, even while a
1561
+ // slower run still holds another. A finite pass settles its batch
1562
+ // and leaves newly owed work for the next wake.
1563
+ let pending = passes == Infinity
1564
+ ? [...started, ...[...running.values()].map((h) => h.run)]
1565
+ : started
1566
+ if (pending.length) {
1567
+ let settled = passes == Infinity
1568
+ ? Promise.race(pending)
1569
+ : Promise.all(pending)
1570
+ if (opts.singleOwner) await settled
1571
+ else while (await still(settled, beat, time)) await renew(g)
1572
+ }
1573
+ // A turn for timers and I/O between passes, never after the last.
1574
+ if (n + 1 < passes && clock() < until) await turn()
1575
+ }
1576
+ return progressed
1577
+ }
1578
+ // Leaving is the moment the signal aborts, not the end of the pass in
1579
+ // flight: what this process commits from then on is the others'.
1580
+ if (loop) {
1581
+ await loop.done
1582
+ return false
1583
+ }
1584
+ let done = (async () => {
1585
+ let joining = join(g, requested.startup)
1586
+ signal.addEventListener('abort', () => member = false, { once: true })
1587
+ let opening = await joining
1588
+ await stay(g, signal, page - opening.length)
1589
+ })()
1590
+ let worker = { done, signal }
1591
+ loop = worker
1592
+ try {
1593
+ await done
1594
+ } finally {
1595
+ if (loop === worker) loop = undefined
1596
+ }
1597
+ return false
1598
+ }),
1599
+ wake: () => nap?.abort(),
1600
+ idle,
1601
+ stop: () => {
1602
+ member = false
1603
+ return idle()
1604
+ },
1605
+ handoff: async (at) => {
1606
+ if (!graph || opts.singleOwner) return
1607
+ let g = graph
1608
+ let due = stamp(at)
1609
+ await Promise.all([...running.values()].map((held) =>
1610
+ swap(g, held.eid, {
1611
+ lease_token: held.token,
1612
+ attempts: held.attempts,
1613
+ }, {
1614
+ // Fence the old attempt's completion and lease renewal.
1615
+ lease_token: mint(),
1616
+ lease_expiry: due,
1617
+ // A deliberate handover doesn't spend a try. Unsafe work stays
1618
+ // interrupted for the replacement's normal recovery.
1619
+ ...safe(handled(held.handler))
1620
+ ? { attempts: Math.max(0, held.attempts - 1), next: due }
1621
+ : {},
1622
+ })
1623
+ ))
1624
+ },
1625
+ running: () =>
1626
+ [...running.values()]
1627
+ .map(({ eid, handler, target, since }) => ({
1628
+ eid,
1629
+ handler,
1630
+ target,
1631
+ since,
1632
+ }))
1633
+ .sort((a, b) => a.since - b.since),
1634
+ }
1635
+ }