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