@cloudhal/schedules 0.0.0-stage → 0.1.1
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.
- package/LICENSE +202 -0
- package/README.md +103 -2
- package/dist/src/automation.d.ts +82 -0
- package/dist/src/automation.js +199 -0
- package/dist/src/budget-meter.d.ts +58 -0
- package/dist/src/budget-meter.js +130 -0
- package/dist/src/budget.d.ts +41 -0
- package/dist/src/budget.js +76 -0
- package/dist/src/builtins.d.ts +132 -0
- package/dist/src/builtins.js +473 -0
- package/dist/src/engine.d.ts +16 -0
- package/dist/src/engine.js +30 -0
- package/dist/src/errors.d.ts +22 -0
- package/dist/src/errors.js +56 -0
- package/dist/src/feed-check.d.ts +56 -0
- package/dist/src/feed-check.js +365 -0
- package/dist/src/findings.d.ts +185 -0
- package/dist/src/findings.js +287 -0
- package/dist/src/ids.d.ts +24 -0
- package/dist/src/ids.js +96 -0
- package/dist/src/index.d.ts +24 -0
- package/dist/src/index.js +24 -0
- package/dist/src/instant.d.ts +19 -0
- package/dist/src/instant.js +50 -0
- package/dist/src/notify.d.ts +50 -0
- package/dist/src/notify.js +60 -0
- package/dist/src/recurrence.d.ts +155 -0
- package/dist/src/recurrence.js +939 -0
- package/dist/src/release-when.d.ts +23 -0
- package/dist/src/release-when.js +55 -0
- package/dist/src/release.d.ts +198 -0
- package/dist/src/release.js +552 -0
- package/dist/src/scheduler.d.ts +490 -0
- package/dist/src/scheduler.js +1343 -0
- package/dist/src/sql/finish.d.ts +32 -0
- package/dist/src/sql/finish.js +103 -0
- package/dist/src/sql/index.d.ts +6 -0
- package/dist/src/sql/index.js +15 -0
- package/dist/src/sql/rows.d.ts +125 -0
- package/dist/src/sql/rows.js +297 -0
- package/dist/src/sql/store.d.ts +467 -0
- package/dist/src/sql/store.js +2166 -0
- package/dist/src/taint.d.ts +65 -0
- package/dist/src/taint.js +138 -0
- package/dist/src/text.d.ts +6 -0
- package/dist/src/text.js +25 -0
- package/dist/src/time-entry.d.ts +6 -0
- package/dist/src/time-entry.js +6 -0
- package/dist/src/time.d.ts +61 -0
- package/dist/src/time.js +140 -0
- package/package.json +69 -3
|
@@ -0,0 +1,1343 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The scheduler (RFC-0008 §8): one `runDue(now)` that every ticker calls — the every-minute cron,
|
|
3
|
+
* the `SchedulerClock` Durable Object alarm, the Node timer, the request backstop and a person's
|
|
4
|
+
* manual tick. D1 (SQLite on Node) is the only state; tickers only wake `runDue`.
|
|
5
|
+
*
|
|
6
|
+
* A tick does, in order (§8.1): (1) one overview read, which is also the heartbeat check;
|
|
7
|
+
* (2) due releases, one at a time per site in time order (D15), each claimed with a lease
|
|
8
|
+
* (§8.5) and executed by the injected `ReleaseExecutor` (`publishRelease` in core-ts, rollout
|
|
9
|
+
* step 5); expired leases are recovered first; (3) automation occurrences — built-in steps through
|
|
10
|
+
* the injected `BuiltinRunner`, agent-task windows recorded and closed; (4) due system jobs behind
|
|
11
|
+
* their watermarks; (5) the heartbeat write. Every unit first checks that its statements fit the
|
|
12
|
+
* `TickBudget` (S17); a tick that runs out reports `more`.
|
|
13
|
+
*
|
|
14
|
+
* At most one effect per occurrence (S3): run ids are derived from the occurrence, every claim is
|
|
15
|
+
* a compare-and-swap that also stores a fresh lease token, and every later write is guarded on that
|
|
16
|
+
* token, so two ticks racing on two stores over one database produce one effect.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
import {
|
|
30
|
+
AUTOMATION_LEASE_MS,
|
|
31
|
+
accountRunResult,
|
|
32
|
+
dueOccurrences,
|
|
33
|
+
|
|
34
|
+
runWindow,
|
|
35
|
+
} from "./automation.js";
|
|
36
|
+
|
|
37
|
+
import { TickBudgetExhaustedError } from "./errors.js";
|
|
38
|
+
import { newLeaseToken, runId } from "./ids.js";
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
import {
|
|
42
|
+
|
|
43
|
+
baseApprovalVerdict,
|
|
44
|
+
|
|
45
|
+
isPastLateLimit,
|
|
46
|
+
nextRetryAt,
|
|
47
|
+
orderReleases,
|
|
48
|
+
|
|
49
|
+
RELEASE_LEASE_MS,
|
|
50
|
+
releaseHash,
|
|
51
|
+
SCHEDULER_ACTOR,
|
|
52
|
+
} from "./release.js";
|
|
53
|
+
import { cleanCounts, plainLine, plainText } from "./text.js";
|
|
54
|
+
import {
|
|
55
|
+
canonicalInstant,
|
|
56
|
+
instantMs,
|
|
57
|
+
latenessSeconds,
|
|
58
|
+
MINUTE_MS,
|
|
59
|
+
recomputeExecuteAt,
|
|
60
|
+
} from "./time.js";
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
/** §8.1. */
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
// ───────────────────────────── the store seam ─────────────────────────────
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
/** One read that tells an idle tick there is nothing to do (§8.2: an idle tick is cheap). */
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
/** Where a built-in job continues: the run it belongs to and the job's own position. */
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
/** `ScheduleRun.taint` of a built-in run: when and through what it read untrusted text. */
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
/** A built-in run's budget use across its steps, recorded as `counts.steps` / `counts.statements`. */
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
/** What `runDue` needs from storage. `SqlScheduleStore` implements it over `SqlDriver`. */
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
// ───────────────────────────── the work seams ─────────────────────────────
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
|
|
350
|
+
|
|
351
|
+
/** Applies a claimed release — `publishRelease` in core-ts (rollout step 5). */
|
|
352
|
+
|
|
353
|
+
|
|
354
|
+
|
|
355
|
+
|
|
356
|
+
|
|
357
|
+
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
|
|
361
|
+
|
|
362
|
+
|
|
363
|
+
|
|
364
|
+
|
|
365
|
+
|
|
366
|
+
|
|
367
|
+
|
|
368
|
+
|
|
369
|
+
|
|
370
|
+
|
|
371
|
+
|
|
372
|
+
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
|
|
377
|
+
|
|
378
|
+
|
|
379
|
+
|
|
380
|
+
|
|
381
|
+
|
|
382
|
+
/** Runs one bounded step of a built-in job (rollout step 9). */
|
|
383
|
+
|
|
384
|
+
|
|
385
|
+
|
|
386
|
+
|
|
387
|
+
|
|
388
|
+
|
|
389
|
+
|
|
390
|
+
|
|
391
|
+
/** A deployment-wide periodic job behind a watermark (§8.2): `analytics.rollup`, `comments.hourly`, … */
|
|
392
|
+
|
|
393
|
+
|
|
394
|
+
|
|
395
|
+
|
|
396
|
+
|
|
397
|
+
|
|
398
|
+
|
|
399
|
+
|
|
400
|
+
|
|
401
|
+
/** Every hour at `:minute` (UTC). */
|
|
402
|
+
export function hourlyAt(minute ) {
|
|
403
|
+
return (after) => {
|
|
404
|
+
const d = new Date(after.getTime());
|
|
405
|
+
d.setUTCSeconds(0, 0);
|
|
406
|
+
d.setUTCMinutes(minute);
|
|
407
|
+
if (d.getTime() <= after.getTime()) d.setUTCHours(d.getUTCHours() + 1);
|
|
408
|
+
return d;
|
|
409
|
+
};
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
/** Every day at `hour:minute` (UTC). */
|
|
413
|
+
export function dailyAt(hour , minute ) {
|
|
414
|
+
return (after) => {
|
|
415
|
+
const d = new Date(after.getTime());
|
|
416
|
+
d.setUTCHours(hour, minute, 0, 0);
|
|
417
|
+
if (d.getTime() <= after.getTime()) d.setUTCDate(d.getUTCDate() + 1);
|
|
418
|
+
return d;
|
|
419
|
+
};
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
// ───────────────────────────── heartbeat and health ─────────────────────────────
|
|
423
|
+
|
|
424
|
+
/** Idle ticks write the heartbeat every fifth minute (§8.7). */
|
|
425
|
+
export const HEARTBEAT_EVERY_MS = 5 * MINUTE_MS;
|
|
426
|
+
/** Stalled when this far past the expected wake while something is due within 24 h (§8.7). */
|
|
427
|
+
export const STALL_GRACE_DUE_MS = 2 * MINUTE_MS;
|
|
428
|
+
/** Stalled at all when this far past it. */
|
|
429
|
+
export const STALL_GRACE_MS = 10 * MINUTE_MS;
|
|
430
|
+
export const SYSTEM_JOB_LEASE_MS = 10 * MINUTE_MS;
|
|
431
|
+
|
|
432
|
+
export function shouldWriteHeartbeat(
|
|
433
|
+
prev ,
|
|
434
|
+
now ,
|
|
435
|
+
didWork ,
|
|
436
|
+
) {
|
|
437
|
+
return didWork || !prev || instantMs(now) - instantMs(prev.at) >= HEARTBEAT_EVERY_MS;
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
/**
|
|
441
|
+
* The heartbeat's `next_wake_at`: the later of the next wake and the next heartbeat write an idle
|
|
442
|
+
* cron tick owes (`at + 5 min`), so a quiet scheduler is not reported stalled between writes.
|
|
443
|
+
*/
|
|
444
|
+
export function heartbeatNextWake(at , nextWake ) {
|
|
445
|
+
const floor = instantMs(at) + HEARTBEAT_EVERY_MS;
|
|
446
|
+
return canonicalInstant(nextWake ? Math.max(instantMs(nextWake), floor) : floor);
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
|
|
450
|
+
|
|
451
|
+
/**
|
|
452
|
+
* §8.7: stalled = `now > next_wake_at + 2 min` while something is due within 24 h, or
|
|
453
|
+
* `now > next_wake_at + 10 min` at all. `late` is the first, `stopped` the second.
|
|
454
|
+
*/
|
|
455
|
+
export function schedulerHealth(
|
|
456
|
+
heartbeat ,
|
|
457
|
+
now ,
|
|
458
|
+
options ,
|
|
459
|
+
) {
|
|
460
|
+
if (!heartbeat) return { state: "unknown", healthy: false };
|
|
461
|
+
const past = instantMs(now) - instantMs(heartbeat.nextWakeAt);
|
|
462
|
+
const base = { lastTickAt: heartbeat.at, nextWakeAt: heartbeat.nextWakeAt };
|
|
463
|
+
if (past > STALL_GRACE_MS) return { ...base, state: "stopped", healthy: false };
|
|
464
|
+
if (options.dueWithin24h && past > STALL_GRACE_DUE_MS)
|
|
465
|
+
return { ...base, state: "late", healthy: false };
|
|
466
|
+
return { ...base, state: "running", healthy: true };
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
/**
|
|
470
|
+
* The request backstop (§8.6): an admin request runs `runDue(…, "request")` in `waitUntil` when the
|
|
471
|
+
* heartbeat is missing or more than 2 minutes behind its `next_wake_at`.
|
|
472
|
+
*/
|
|
473
|
+
export function backstopDue(
|
|
474
|
+
heartbeat ,
|
|
475
|
+
now ,
|
|
476
|
+
) {
|
|
477
|
+
return !heartbeat || instantMs(now) - instantMs(heartbeat.nextWakeAt) > STALL_GRACE_DUE_MS;
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
/** The next instant anything in the overview is due. */
|
|
481
|
+
export function overviewNextWake(o ) {
|
|
482
|
+
const all = [o.nextReleaseAt, o.nextAutomationAt, o.nextSystemJobAt, o.nextRunDeadline].filter(
|
|
483
|
+
(x) => x !== undefined,
|
|
484
|
+
);
|
|
485
|
+
if (all.length === 0) return undefined;
|
|
486
|
+
return canonicalInstant(Math.min(...all.map(instantMs)));
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
// ───────────────────────────── runDue ─────────────────────────────
|
|
490
|
+
|
|
491
|
+
/** Statement estimates per path, checked before each unit (measured by the conformance suite). */
|
|
492
|
+
export const PATH_COST = {
|
|
493
|
+
overview: 1,
|
|
494
|
+
dueReleases: 1,
|
|
495
|
+
recover: 1,
|
|
496
|
+
releaseClaim: 3,
|
|
497
|
+
releaseFinish: 4,
|
|
498
|
+
releaseSettle: 3,
|
|
499
|
+
releaseMove: 1,
|
|
500
|
+
dueAutomations: 1,
|
|
501
|
+
builtinClaim: 4,
|
|
502
|
+
builtinFinish: 3,
|
|
503
|
+
agentOccurrence: 3,
|
|
504
|
+
closeRuns: 5,
|
|
505
|
+
ensureJobs: 1,
|
|
506
|
+
dueJobs: 1,
|
|
507
|
+
jobClaim: 1,
|
|
508
|
+
jobFinish: 1,
|
|
509
|
+
heartbeat: 1,
|
|
510
|
+
} ;
|
|
511
|
+
|
|
512
|
+
|
|
513
|
+
|
|
514
|
+
|
|
515
|
+
|
|
516
|
+
|
|
517
|
+
|
|
518
|
+
|
|
519
|
+
|
|
520
|
+
|
|
521
|
+
|
|
522
|
+
|
|
523
|
+
|
|
524
|
+
|
|
525
|
+
|
|
526
|
+
|
|
527
|
+
|
|
528
|
+
|
|
529
|
+
|
|
530
|
+
|
|
531
|
+
|
|
532
|
+
|
|
533
|
+
|
|
534
|
+
|
|
535
|
+
const MAX_DUE_AUTOMATIONS = 20;
|
|
536
|
+
const MAX_RECOVER = 5;
|
|
537
|
+
|
|
538
|
+
/** Runs what is due (§8.1). See the module comment for the order and guarantees. */
|
|
539
|
+
export async function runDue(nowDate , deps ) {
|
|
540
|
+
const now = canonicalInstant(nowDate);
|
|
541
|
+
const { store, meter, trigger } = deps;
|
|
542
|
+
const token = deps.newToken ?? newLeaseToken;
|
|
543
|
+
const report = { ran: 0, late: 0, failed: 0, more: false };
|
|
544
|
+
const reserve = PATH_COST.overview + PATH_COST.heartbeat;
|
|
545
|
+
const fits = (n ) => {
|
|
546
|
+
if (meter?.deadlinePassed()) return false;
|
|
547
|
+
return meter ? meter.canAfford(n, reserve) : true;
|
|
548
|
+
};
|
|
549
|
+
let overview ;
|
|
550
|
+
let didWork = false;
|
|
551
|
+
let oldestDue ;
|
|
552
|
+
const noteDue = (at ) => {
|
|
553
|
+
if (!oldestDue || instantMs(at) < instantMs(oldestDue)) oldestDue = at;
|
|
554
|
+
};
|
|
555
|
+
|
|
556
|
+
try {
|
|
557
|
+
overview = await store.overview(now);
|
|
558
|
+
const t = instantMs(now);
|
|
559
|
+
const due = (at ) => at !== undefined && instantMs(at) <= t;
|
|
560
|
+
|
|
561
|
+
// (2) releases — recover expired leases first (§6.3 Recovery), then due releases in order.
|
|
562
|
+
let releasesRun = 0;
|
|
563
|
+
if (due(overview.nextRunDeadline) && deps.releases && fits(PATH_COST.recover)) {
|
|
564
|
+
for (const r of await store.expiredReleaseLeases(now, MAX_RECOVER)) {
|
|
565
|
+
if (releasesRun >= deps.budget.maxReleases) {
|
|
566
|
+
report.more = true;
|
|
567
|
+
break;
|
|
568
|
+
}
|
|
569
|
+
if (!fits(PATH_COST.releaseClaim + deps.releases.cost + PATH_COST.releaseFinish)) {
|
|
570
|
+
report.more = true;
|
|
571
|
+
break;
|
|
572
|
+
}
|
|
573
|
+
noteDue(r.executeAt);
|
|
574
|
+
const lateness = latenessSeconds(r.executeAt, now);
|
|
575
|
+
const tok = token();
|
|
576
|
+
if (isPastLateLimit(r.executeAt, now)) {
|
|
577
|
+
// Nothing is ever published more than an hour late, even by a recovery (S8).
|
|
578
|
+
if (
|
|
579
|
+
await store.reclaimRelease({
|
|
580
|
+
releaseId: r.release.id,
|
|
581
|
+
runId: r.run.id,
|
|
582
|
+
oldToken: r.run.leaseToken,
|
|
583
|
+
token: tok,
|
|
584
|
+
now,
|
|
585
|
+
leaseUntil: now,
|
|
586
|
+
trigger,
|
|
587
|
+
latenessSeconds: lateness,
|
|
588
|
+
})
|
|
589
|
+
) {
|
|
590
|
+
await store.finishRelease({
|
|
591
|
+
releaseId: r.release.id,
|
|
592
|
+
runId: r.run.id,
|
|
593
|
+
token: tok,
|
|
594
|
+
now,
|
|
595
|
+
latenessSeconds: lateness,
|
|
596
|
+
finish: {
|
|
597
|
+
state: "missed",
|
|
598
|
+
outcome: { kind: "missed", at: now, latenessSeconds: lateness },
|
|
599
|
+
},
|
|
600
|
+
});
|
|
601
|
+
report.late++;
|
|
602
|
+
didWork = true;
|
|
603
|
+
}
|
|
604
|
+
continue;
|
|
605
|
+
}
|
|
606
|
+
if (r.sitePaused) continue; // the kill switch: waits, missed after the hour
|
|
607
|
+
const leaseUntil = canonicalInstant(t + RELEASE_LEASE_MS);
|
|
608
|
+
if (
|
|
609
|
+
!(await store.reclaimRelease({
|
|
610
|
+
releaseId: r.release.id,
|
|
611
|
+
runId: r.run.id,
|
|
612
|
+
oldToken: r.run.leaseToken,
|
|
613
|
+
token: tok,
|
|
614
|
+
now,
|
|
615
|
+
leaseUntil,
|
|
616
|
+
trigger,
|
|
617
|
+
latenessSeconds: lateness,
|
|
618
|
+
}))
|
|
619
|
+
)
|
|
620
|
+
continue;
|
|
621
|
+
didWork = true;
|
|
622
|
+
releasesRun++;
|
|
623
|
+
await executeClaimed(deps, report, {
|
|
624
|
+
release: r.release,
|
|
625
|
+
items: r.items,
|
|
626
|
+
executeAt: r.executeAt,
|
|
627
|
+
runId: r.run.id,
|
|
628
|
+
attempt: r.run.attempt + 1,
|
|
629
|
+
token: tok,
|
|
630
|
+
now,
|
|
631
|
+
nowDate,
|
|
632
|
+
lateness,
|
|
633
|
+
recovering: true,
|
|
634
|
+
});
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
if (due(overview.nextReleaseAt) && fits(PATH_COST.dueReleases)) {
|
|
639
|
+
const list = orderReleases(
|
|
640
|
+
(await store.dueReleases(now, Math.max(1, deps.budget.maxReleases) * 4)).map((d) => ({
|
|
641
|
+
...d,
|
|
642
|
+
id: d.release.id,
|
|
643
|
+
})),
|
|
644
|
+
);
|
|
645
|
+
for (const d of list) {
|
|
646
|
+
noteDue(d.executeAt);
|
|
647
|
+
const lateness = latenessSeconds(d.executeAt, now);
|
|
648
|
+
const r = d.release;
|
|
649
|
+
// Gates of the run (§6.3 step 2): lateness first — a paused site waits, but not past the hour.
|
|
650
|
+
if (isPastLateLimit(d.executeAt, now)) {
|
|
651
|
+
if (!fits(PATH_COST.releaseSettle)) {
|
|
652
|
+
report.more = true;
|
|
653
|
+
break;
|
|
654
|
+
}
|
|
655
|
+
if (
|
|
656
|
+
await store.settleRelease({
|
|
657
|
+
siteId: r.siteId,
|
|
658
|
+
releaseId: r.id,
|
|
659
|
+
expectedRev: r.rev,
|
|
660
|
+
executeAt: d.executeAt,
|
|
661
|
+
now,
|
|
662
|
+
trigger,
|
|
663
|
+
outcome: { kind: "missed", at: now, latenessSeconds: lateness },
|
|
664
|
+
})
|
|
665
|
+
) {
|
|
666
|
+
report.late++;
|
|
667
|
+
didWork = true;
|
|
668
|
+
deps.log?.(`schedules: release ${r.id} missed (${lateness} s late)`);
|
|
669
|
+
}
|
|
670
|
+
continue;
|
|
671
|
+
}
|
|
672
|
+
if (d.sitePaused) continue; // the kill switch: waits, missed after the hour (§8.6)
|
|
673
|
+
if (!deps.releases) continue;
|
|
674
|
+
if (releasesRun >= deps.budget.maxReleases) {
|
|
675
|
+
report.more = true;
|
|
676
|
+
break;
|
|
677
|
+
}
|
|
678
|
+
// Approval (§10.6) and the binding (§10.4): items must still hash to the approved `rl1:`.
|
|
679
|
+
let verdict = baseApprovalVerdict(r.approval, nowDate);
|
|
680
|
+
if (
|
|
681
|
+
verdict.ok &&
|
|
682
|
+
(await releaseHash(
|
|
683
|
+
r.siteId,
|
|
684
|
+
d.items.map((i) => i.item),
|
|
685
|
+
)) !== r.hash
|
|
686
|
+
)
|
|
687
|
+
verdict = { ok: false, reason: "approval_lost" };
|
|
688
|
+
if (verdict.ok && deps.checkApproval) verdict = await deps.checkApproval(r, nowDate);
|
|
689
|
+
if (!verdict.ok) {
|
|
690
|
+
if (!fits(PATH_COST.releaseSettle)) {
|
|
691
|
+
report.more = true;
|
|
692
|
+
break;
|
|
693
|
+
}
|
|
694
|
+
if (
|
|
695
|
+
await store.settleRelease({
|
|
696
|
+
siteId: r.siteId,
|
|
697
|
+
releaseId: r.id,
|
|
698
|
+
expectedRev: r.rev,
|
|
699
|
+
executeAt: d.executeAt,
|
|
700
|
+
now,
|
|
701
|
+
trigger,
|
|
702
|
+
outcome: { kind: "expired", at: now, reason: verdict.reason },
|
|
703
|
+
})
|
|
704
|
+
) {
|
|
705
|
+
didWork = true;
|
|
706
|
+
deps.log?.(`schedules: release ${r.id} expired (${verdict.reason})`);
|
|
707
|
+
}
|
|
708
|
+
continue;
|
|
709
|
+
}
|
|
710
|
+
// Never early (S2): recompute a wall-clock time with today's tzdata.
|
|
711
|
+
let executeAt = d.executeAt;
|
|
712
|
+
let adjusted ;
|
|
713
|
+
if (r.when?.kind === "at" && r.when.localTime) {
|
|
714
|
+
const re = recomputeExecuteAt({
|
|
715
|
+
at: d.executeAt,
|
|
716
|
+
timeZone: r.when.timeZone,
|
|
717
|
+
localTime: r.when.localTime,
|
|
718
|
+
});
|
|
719
|
+
if (re.changed) {
|
|
720
|
+
if (!fits(PATH_COST.releaseMove)) {
|
|
721
|
+
report.more = true;
|
|
722
|
+
break;
|
|
723
|
+
}
|
|
724
|
+
if (
|
|
725
|
+
!(await store.moveRelease({
|
|
726
|
+
siteId: r.siteId,
|
|
727
|
+
releaseId: r.id,
|
|
728
|
+
expectedRev: r.rev,
|
|
729
|
+
at: re.at,
|
|
730
|
+
now,
|
|
731
|
+
}))
|
|
732
|
+
)
|
|
733
|
+
continue;
|
|
734
|
+
deps.log?.(`schedules: release ${r.id} moved to ${re.at} (tzdata)`);
|
|
735
|
+
if (instantMs(re.at) > t) continue; // not due yet at its real wall-clock time
|
|
736
|
+
executeAt = re.at;
|
|
737
|
+
adjusted = "tzdata";
|
|
738
|
+
r.rev += 1;
|
|
739
|
+
}
|
|
740
|
+
}
|
|
741
|
+
if (!fits(PATH_COST.releaseClaim + deps.releases.cost + PATH_COST.releaseFinish)) {
|
|
742
|
+
report.more = true;
|
|
743
|
+
break;
|
|
744
|
+
}
|
|
745
|
+
const tok = token();
|
|
746
|
+
const run = await runId(r.id, executeAt);
|
|
747
|
+
const claimed = await store.claimRelease({
|
|
748
|
+
siteId: r.siteId,
|
|
749
|
+
releaseId: r.id,
|
|
750
|
+
expectedRev: r.rev,
|
|
751
|
+
executeAt,
|
|
752
|
+
runId: run,
|
|
753
|
+
token: tok,
|
|
754
|
+
now,
|
|
755
|
+
leaseUntil: canonicalInstant(t + RELEASE_LEASE_MS),
|
|
756
|
+
trigger,
|
|
757
|
+
latenessSeconds: latenessSeconds(executeAt, now),
|
|
758
|
+
...(adjusted ? { adjusted } : {}),
|
|
759
|
+
});
|
|
760
|
+
if (!claimed) continue; // another tick has it, or another release of the site is running
|
|
761
|
+
didWork = true;
|
|
762
|
+
releasesRun++;
|
|
763
|
+
await executeClaimed(deps, report, {
|
|
764
|
+
release: r,
|
|
765
|
+
items: d.items,
|
|
766
|
+
executeAt,
|
|
767
|
+
runId: run,
|
|
768
|
+
attempt: 1,
|
|
769
|
+
token: tok,
|
|
770
|
+
now,
|
|
771
|
+
nowDate,
|
|
772
|
+
lateness: latenessSeconds(executeAt, now),
|
|
773
|
+
recovering: false,
|
|
774
|
+
});
|
|
775
|
+
}
|
|
776
|
+
}
|
|
777
|
+
|
|
778
|
+
// (3) automations.
|
|
779
|
+
const automations = deps.automationsEnabled !== false;
|
|
780
|
+
if (automations && due(overview.nextRunDeadline) && fits(PATH_COST.closeRuns)) {
|
|
781
|
+
const closed = await store.closeExpiredRuns(now);
|
|
782
|
+
if (closed.missed + closed.failed > 0) didWork = true;
|
|
783
|
+
report.failed += closed.failed;
|
|
784
|
+
}
|
|
785
|
+
if (automations && due(overview.nextAutomationAt) && fits(PATH_COST.dueAutomations)) {
|
|
786
|
+
for (const a of await store.dueAutomations(now, MAX_DUE_AUTOMATIONS)) {
|
|
787
|
+
if (a.sitePaused) continue;
|
|
788
|
+
const done = await runAutomation(deps, report, a, now, nowDate, fits, token, noteDue);
|
|
789
|
+
if (done === "budget") {
|
|
790
|
+
report.more = true;
|
|
791
|
+
break;
|
|
792
|
+
}
|
|
793
|
+
if (done === "ran") didWork = true;
|
|
794
|
+
}
|
|
795
|
+
}
|
|
796
|
+
|
|
797
|
+
// (4) system jobs behind watermarks.
|
|
798
|
+
const jobs = deps.systemJobs ?? [];
|
|
799
|
+
if (jobs.length > 0) {
|
|
800
|
+
if (overview.systemJobs < jobs.length && fits(PATH_COST.ensureJobs)) {
|
|
801
|
+
await store.ensureSystemJobs(
|
|
802
|
+
jobs.map((j) => ({ name: j.name, nextRunAt: canonicalInstant(j.next(nowDate)) })),
|
|
803
|
+
);
|
|
804
|
+
}
|
|
805
|
+
if (due(overview.nextSystemJobAt) && fits(PATH_COST.dueJobs)) {
|
|
806
|
+
for (const row of await store.dueSystemJobs(now)) {
|
|
807
|
+
const def = jobs.find((j) => j.name === row.name);
|
|
808
|
+
if (!def) continue;
|
|
809
|
+
if (!fits(PATH_COST.jobClaim + def.cost + PATH_COST.jobFinish)) {
|
|
810
|
+
report.more = true;
|
|
811
|
+
break;
|
|
812
|
+
}
|
|
813
|
+
const tok = token();
|
|
814
|
+
if (
|
|
815
|
+
!(await store.claimSystemJob({
|
|
816
|
+
name: row.name,
|
|
817
|
+
token: tok,
|
|
818
|
+
now,
|
|
819
|
+
leaseUntil: canonicalInstant(t + SYSTEM_JOB_LEASE_MS),
|
|
820
|
+
}))
|
|
821
|
+
)
|
|
822
|
+
continue;
|
|
823
|
+
didWork = true;
|
|
824
|
+
let ok = true;
|
|
825
|
+
let error ;
|
|
826
|
+
try {
|
|
827
|
+
await def.run({ now: nowDate, trigger });
|
|
828
|
+
} catch (e) {
|
|
829
|
+
if (e instanceof TickBudgetExhaustedError) throw e;
|
|
830
|
+
ok = false;
|
|
831
|
+
error = e instanceof Error ? e.message : String(e);
|
|
832
|
+
report.failed++;
|
|
833
|
+
}
|
|
834
|
+
// The watermark moves past `now`: a missed hour is caught up by this run (bounded, idempotent).
|
|
835
|
+
await store.finishSystemJob({
|
|
836
|
+
name: row.name,
|
|
837
|
+
token: tok,
|
|
838
|
+
now,
|
|
839
|
+
ok,
|
|
840
|
+
nextRunAt: canonicalInstant(def.next(nowDate)),
|
|
841
|
+
...(error ? { error: error.slice(0, 500) } : {}),
|
|
842
|
+
});
|
|
843
|
+
if (ok) report.ran++;
|
|
844
|
+
}
|
|
845
|
+
}
|
|
846
|
+
}
|
|
847
|
+
} catch (e) {
|
|
848
|
+
if (!(e instanceof TickBudgetExhaustedError)) throw e;
|
|
849
|
+
report.more = true;
|
|
850
|
+
}
|
|
851
|
+
|
|
852
|
+
// (5) heartbeat; the reserve kept for it above (a fresh overview after work, and the write).
|
|
853
|
+
let nextWake = overview ? overviewNextWake(overview) : undefined;
|
|
854
|
+
if (didWork && (!meter || meter.canAfford(PATH_COST.overview + PATH_COST.heartbeat))) {
|
|
855
|
+
try {
|
|
856
|
+
nextWake = overviewNextWake(await store.overview(now));
|
|
857
|
+
} catch (e) {
|
|
858
|
+
if (!(e instanceof TickBudgetExhaustedError)) throw e;
|
|
859
|
+
}
|
|
860
|
+
}
|
|
861
|
+
// Something due but left (a paused site, no executor) must not make an alarm fire in a loop.
|
|
862
|
+
if (nextWake && instantMs(nextWake) <= instantMs(now))
|
|
863
|
+
nextWake = canonicalInstant(instantMs(now) + MINUTE_MS);
|
|
864
|
+
if (nextWake && instantMs(nextWake) > instantMs(now)) report.nextDueAt = nextWake;
|
|
865
|
+
if (deps.wake === "minute") {
|
|
866
|
+
const nextMinute = canonicalInstant(
|
|
867
|
+
Math.floor(instantMs(now) / MINUTE_MS) * MINUTE_MS + MINUTE_MS,
|
|
868
|
+
);
|
|
869
|
+
nextWake = nextWake && instantMs(nextWake) < instantMs(nextMinute) ? nextWake : nextMinute;
|
|
870
|
+
}
|
|
871
|
+
if (report.more) nextWake = canonicalInstant(instantMs(now) + 1000);
|
|
872
|
+
if (nextWake) report.nextWakeAt = nextWake;
|
|
873
|
+
if (shouldWriteHeartbeat(overview?.heartbeat, now, didWork)) {
|
|
874
|
+
try {
|
|
875
|
+
await store.writeHeartbeat({
|
|
876
|
+
at: now,
|
|
877
|
+
trigger,
|
|
878
|
+
nextWakeAt: heartbeatNextWake(now, nextWake),
|
|
879
|
+
ran: report.ran,
|
|
880
|
+
more: report.more,
|
|
881
|
+
...(oldestDue ? { lagSeconds: latenessSeconds(oldestDue, now) } : {}),
|
|
882
|
+
});
|
|
883
|
+
} catch (e) {
|
|
884
|
+
if (!(e instanceof TickBudgetExhaustedError)) throw e;
|
|
885
|
+
report.more = true;
|
|
886
|
+
}
|
|
887
|
+
}
|
|
888
|
+
if (meter) report.statements = meter.used;
|
|
889
|
+
if (didWork || report.more)
|
|
890
|
+
deps.log?.(
|
|
891
|
+
`schedules tick (${trigger}): ${report.ran} ran, ${report.late} late, ${report.failed} failed${report.more ? ", more" : ""}${nextWake ? `; next ${nextWake}` : ""}`,
|
|
892
|
+
);
|
|
893
|
+
return report;
|
|
894
|
+
}
|
|
895
|
+
|
|
896
|
+
/**
|
|
897
|
+
* Executes a release the caller already claimed — a person's "Publish now"
|
|
898
|
+
* (`SqlScheduleStore.claimManualRun`) — and records its end exactly as a tick does: published,
|
|
899
|
+
* conflict, failed, expired or canceled, or a transient error kept `running` for a retry.
|
|
900
|
+
*/
|
|
901
|
+
export async function runClaimedRelease(
|
|
902
|
+
deps ,
|
|
903
|
+
claimed
|
|
904
|
+
|
|
905
|
+
|
|
906
|
+
|
|
907
|
+
|
|
908
|
+
|
|
909
|
+
|
|
910
|
+
|
|
911
|
+
,
|
|
912
|
+
) {
|
|
913
|
+
const report = { ran: 0, late: 0, failed: 0, more: false };
|
|
914
|
+
const now = canonicalInstant(claimed.now);
|
|
915
|
+
await executeClaimed(
|
|
916
|
+
{
|
|
917
|
+
...deps,
|
|
918
|
+
budget: {
|
|
919
|
+
maxQueries: Number.POSITIVE_INFINITY,
|
|
920
|
+
maxReleases: 1,
|
|
921
|
+
deadlineMs: Number.POSITIVE_INFINITY,
|
|
922
|
+
},
|
|
923
|
+
},
|
|
924
|
+
report,
|
|
925
|
+
{
|
|
926
|
+
release: claimed.release,
|
|
927
|
+
items: claimed.items,
|
|
928
|
+
executeAt: claimed.executeAt,
|
|
929
|
+
runId: claimed.runId,
|
|
930
|
+
attempt: claimed.attempt ?? 1,
|
|
931
|
+
token: claimed.token,
|
|
932
|
+
now,
|
|
933
|
+
nowDate: claimed.now,
|
|
934
|
+
lateness: latenessSeconds(claimed.executeAt, now),
|
|
935
|
+
recovering: false,
|
|
936
|
+
},
|
|
937
|
+
);
|
|
938
|
+
return report;
|
|
939
|
+
}
|
|
940
|
+
|
|
941
|
+
|
|
942
|
+
|
|
943
|
+
|
|
944
|
+
|
|
945
|
+
|
|
946
|
+
|
|
947
|
+
|
|
948
|
+
|
|
949
|
+
|
|
950
|
+
|
|
951
|
+
|
|
952
|
+
|
|
953
|
+
|
|
954
|
+
async function executeClaimed(deps , report , c ) {
|
|
955
|
+
const executor = deps.releases ;
|
|
956
|
+
let result ;
|
|
957
|
+
try {
|
|
958
|
+
result = await executor.execute({
|
|
959
|
+
release: c.release,
|
|
960
|
+
items: c.items,
|
|
961
|
+
executeAt: c.executeAt,
|
|
962
|
+
run: { id: c.runId, attempt: c.attempt, leaseToken: c.token, recovering: c.recovering },
|
|
963
|
+
now: c.nowDate,
|
|
964
|
+
latenessSeconds: c.lateness,
|
|
965
|
+
trigger: deps.trigger,
|
|
966
|
+
});
|
|
967
|
+
} catch (e) {
|
|
968
|
+
if (e instanceof TickBudgetExhaustedError) throw e;
|
|
969
|
+
result = { kind: "retry", error: e instanceof Error ? e.message : String(e) };
|
|
970
|
+
}
|
|
971
|
+
const base = {
|
|
972
|
+
releaseId: c.release.id,
|
|
973
|
+
runId: c.runId,
|
|
974
|
+
token: c.token,
|
|
975
|
+
now: c.now,
|
|
976
|
+
latenessSeconds: c.lateness,
|
|
977
|
+
};
|
|
978
|
+
const at = c.now;
|
|
979
|
+
switch (result.kind) {
|
|
980
|
+
case "published": {
|
|
981
|
+
if (!result.committed)
|
|
982
|
+
await deps.store.finishRelease({
|
|
983
|
+
...base,
|
|
984
|
+
finish: {
|
|
985
|
+
state: "published",
|
|
986
|
+
outcome: {
|
|
987
|
+
kind: "published",
|
|
988
|
+
runId: c.runId,
|
|
989
|
+
at,
|
|
990
|
+
snapshotId: result.snapshotId,
|
|
991
|
+
baseSnapshotId: result.baseSnapshotId,
|
|
992
|
+
latenessSeconds: c.lateness,
|
|
993
|
+
purge: result.purge,
|
|
994
|
+
},
|
|
995
|
+
},
|
|
996
|
+
});
|
|
997
|
+
report.ran++;
|
|
998
|
+
if (c.lateness > 60) report.late++;
|
|
999
|
+
deps.log?.(`schedules: release ${c.release.id} published (${c.lateness} s late)`);
|
|
1000
|
+
return;
|
|
1001
|
+
}
|
|
1002
|
+
case "conflict":
|
|
1003
|
+
await deps.store.finishRelease({
|
|
1004
|
+
...base,
|
|
1005
|
+
finish: {
|
|
1006
|
+
state: "conflict",
|
|
1007
|
+
outcome: {
|
|
1008
|
+
kind: "conflict",
|
|
1009
|
+
runId: c.runId,
|
|
1010
|
+
at,
|
|
1011
|
+
conflicts: result.conflicts ,
|
|
1012
|
+
},
|
|
1013
|
+
},
|
|
1014
|
+
});
|
|
1015
|
+
return;
|
|
1016
|
+
case "failed":
|
|
1017
|
+
report.failed++;
|
|
1018
|
+
await deps.store.finishRelease({
|
|
1019
|
+
...base,
|
|
1020
|
+
finish: {
|
|
1021
|
+
state: "failed",
|
|
1022
|
+
outcome: {
|
|
1023
|
+
kind: "failed",
|
|
1024
|
+
runId: c.runId,
|
|
1025
|
+
at,
|
|
1026
|
+
code: result.code,
|
|
1027
|
+
...(result.message ? { message: plainLine(result.message) } : {}),
|
|
1028
|
+
},
|
|
1029
|
+
},
|
|
1030
|
+
});
|
|
1031
|
+
return;
|
|
1032
|
+
case "expired":
|
|
1033
|
+
await deps.store.finishRelease({
|
|
1034
|
+
...base,
|
|
1035
|
+
finish: { state: "expired", outcome: { kind: "expired", at, reason: result.reason } },
|
|
1036
|
+
});
|
|
1037
|
+
return;
|
|
1038
|
+
case "canceled":
|
|
1039
|
+
await deps.store.finishRelease({
|
|
1040
|
+
...base,
|
|
1041
|
+
finish: {
|
|
1042
|
+
state: "canceled",
|
|
1043
|
+
outcome: { kind: "canceled", at, by: { ...SCHEDULER_ACTOR } },
|
|
1044
|
+
},
|
|
1045
|
+
});
|
|
1046
|
+
return;
|
|
1047
|
+
case "retry": {
|
|
1048
|
+
const retryAt = nextRetryAt(c.executeAt, c.now, c.attempt);
|
|
1049
|
+
if (retryAt) {
|
|
1050
|
+
await deps.store.deferRelease({
|
|
1051
|
+
releaseId: c.release.id,
|
|
1052
|
+
runId: c.runId,
|
|
1053
|
+
token: c.token,
|
|
1054
|
+
now: c.now,
|
|
1055
|
+
retryAt,
|
|
1056
|
+
error: result.error.slice(0, 500),
|
|
1057
|
+
});
|
|
1058
|
+
deps.log?.(`schedules: release ${c.release.id} will retry at ${retryAt}: ${result.error}`);
|
|
1059
|
+
} else {
|
|
1060
|
+
report.late++;
|
|
1061
|
+
await deps.store.finishRelease({
|
|
1062
|
+
...base,
|
|
1063
|
+
finish: { state: "missed", outcome: { kind: "missed", at, latenessSeconds: c.lateness } },
|
|
1064
|
+
});
|
|
1065
|
+
}
|
|
1066
|
+
return;
|
|
1067
|
+
}
|
|
1068
|
+
}
|
|
1069
|
+
}
|
|
1070
|
+
|
|
1071
|
+
async function runAutomation(
|
|
1072
|
+
deps ,
|
|
1073
|
+
report ,
|
|
1074
|
+
a ,
|
|
1075
|
+
now ,
|
|
1076
|
+
nowDate ,
|
|
1077
|
+
fits ,
|
|
1078
|
+
token ,
|
|
1079
|
+
noteDue ,
|
|
1080
|
+
) {
|
|
1081
|
+
const aut = a.automation;
|
|
1082
|
+
if (!aut.nextRunAt) return "skipped";
|
|
1083
|
+
noteDue(aut.nextRunAt);
|
|
1084
|
+
const rec = aut.recurrence;
|
|
1085
|
+
const job = aut.job;
|
|
1086
|
+
|
|
1087
|
+
if (job.kind === "agent-task") {
|
|
1088
|
+
if (!fits(PATH_COST.agentOccurrence)) return "budget";
|
|
1089
|
+
const occ = dueOccurrences(rec, aut.nextRunAt, now);
|
|
1090
|
+
if (!occ) return "skipped";
|
|
1091
|
+
const window = runWindow(occ.latest.at, job.windowMinutes);
|
|
1092
|
+
const closed = instantMs(window.closesAt) <= instantMs(now);
|
|
1093
|
+
const acc = closed
|
|
1094
|
+
? accountRunResult(aut.consecutiveFailures, "missed", "agent-task")
|
|
1095
|
+
: { consecutiveFailures: aut.consecutiveFailures };
|
|
1096
|
+
const ok = await deps.store.recordAgentOccurrence({
|
|
1097
|
+
automation: aut,
|
|
1098
|
+
occurrence: occ.latest,
|
|
1099
|
+
runId: await runId(aut.id, occ.latest.at),
|
|
1100
|
+
window,
|
|
1101
|
+
state: closed ? "missed" : "ready",
|
|
1102
|
+
...(occ.next ? { nextRunAt: occ.next.at } : {}),
|
|
1103
|
+
consecutiveFailures: acc.consecutiveFailures,
|
|
1104
|
+
...(acc.pause ? { pause: acc.pause } : {}),
|
|
1105
|
+
now,
|
|
1106
|
+
trigger: deps.trigger,
|
|
1107
|
+
latenessSeconds: latenessSeconds(occ.latest.at, now),
|
|
1108
|
+
});
|
|
1109
|
+
return ok ? "ran" : "skipped";
|
|
1110
|
+
}
|
|
1111
|
+
|
|
1112
|
+
// Built-in: one bounded step per tick; the cursor carries the run across ticks.
|
|
1113
|
+
const runner = deps.builtins;
|
|
1114
|
+
if (!runner) return "skipped";
|
|
1115
|
+
if (a.leaseUntil && instantMs(a.leaseUntil) > instantMs(now)) return "skipped"; // another tick is stepping it
|
|
1116
|
+
const cost = runner.costOf?.(job) ?? runner.cost;
|
|
1117
|
+
if (!fits(PATH_COST.builtinClaim + cost + PATH_COST.builtinFinish)) return "budget";
|
|
1118
|
+
let occurrence ;
|
|
1119
|
+
let run ;
|
|
1120
|
+
let attempt = 1;
|
|
1121
|
+
let coalesced ;
|
|
1122
|
+
let next ;
|
|
1123
|
+
const continuing = a.cursor !== undefined;
|
|
1124
|
+
const occ = dueOccurrences(rec, aut.nextRunAt, now);
|
|
1125
|
+
if (a.cursor) {
|
|
1126
|
+
occurrence = { at: a.cursor.occurrenceAt, local: a.cursor.occurrenceAt };
|
|
1127
|
+
run = a.cursor.runId;
|
|
1128
|
+
attempt = a.cursor.attempt;
|
|
1129
|
+
// A person's "Run now" moved `nextRunAt` to now; the scheduled occurrence comes back after it.
|
|
1130
|
+
const manual = a.cursor.manual;
|
|
1131
|
+
next = manual
|
|
1132
|
+
? manual.nextRunAt
|
|
1133
|
+
? { at: manual.nextRunAt, local: manual.nextRunAt }
|
|
1134
|
+
: undefined
|
|
1135
|
+
: occ?.next;
|
|
1136
|
+
} else {
|
|
1137
|
+
if (!occ) return "skipped";
|
|
1138
|
+
occurrence = occ.latest;
|
|
1139
|
+
run = await runId(aut.id, occ.latest.at);
|
|
1140
|
+
next = occ.next;
|
|
1141
|
+
if (occ.firstCoalesced && occ.coalesced > 0)
|
|
1142
|
+
coalesced = {
|
|
1143
|
+
runId: await runId(aut.id, occ.firstCoalesced.at),
|
|
1144
|
+
occurrenceAt: occ.firstCoalesced.at,
|
|
1145
|
+
count: occ.coalesced,
|
|
1146
|
+
};
|
|
1147
|
+
}
|
|
1148
|
+
const tok = token();
|
|
1149
|
+
const claimed = await deps.store.claimBuiltinRun({
|
|
1150
|
+
automation: aut,
|
|
1151
|
+
occurrence,
|
|
1152
|
+
runId: run,
|
|
1153
|
+
attempt,
|
|
1154
|
+
continuing,
|
|
1155
|
+
...(coalesced ? { coalesced } : {}),
|
|
1156
|
+
token: tok,
|
|
1157
|
+
now,
|
|
1158
|
+
leaseUntil: canonicalInstant(instantMs(now) + AUTOMATION_LEASE_MS),
|
|
1159
|
+
trigger: deps.trigger,
|
|
1160
|
+
latenessSeconds: latenessSeconds(occurrence.at, now),
|
|
1161
|
+
});
|
|
1162
|
+
if (!claimed) return "skipped";
|
|
1163
|
+
// Run accounting (§11.5, S17): the statements each step executed, summed over the run.
|
|
1164
|
+
const before = deps.meter?.used ?? 0;
|
|
1165
|
+
const prior = a.cursor?.usage ?? { steps: 0, statements: 0 };
|
|
1166
|
+
const usageNow = () => ({
|
|
1167
|
+
steps: prior.steps + 1,
|
|
1168
|
+
statements: prior.statements + Math.max(0, (deps.meter?.used ?? before) - before),
|
|
1169
|
+
});
|
|
1170
|
+
let taint = a.cursor?.taint;
|
|
1171
|
+
let result ;
|
|
1172
|
+
try {
|
|
1173
|
+
result = await runner.step({
|
|
1174
|
+
automation: aut,
|
|
1175
|
+
job,
|
|
1176
|
+
run: { id: run, occurrenceAt: occurrence.at, attempt },
|
|
1177
|
+
...(a.cursor?.position !== undefined ? { position: a.cursor.position } : {}),
|
|
1178
|
+
now: nowDate,
|
|
1179
|
+
trigger: deps.trigger,
|
|
1180
|
+
});
|
|
1181
|
+
} catch (e) {
|
|
1182
|
+
if (e instanceof TickBudgetExhaustedError) throw e;
|
|
1183
|
+
const acc = accountRunResult(aut.consecutiveFailures, "failed", "builtin");
|
|
1184
|
+
report.failed++;
|
|
1185
|
+
const error = {
|
|
1186
|
+
code: "job_error",
|
|
1187
|
+
message: plainLine(e instanceof Error ? e.message : String(e)),
|
|
1188
|
+
};
|
|
1189
|
+
const usage = usageNow();
|
|
1190
|
+
const ended = await deps.store.finishBuiltinRun({
|
|
1191
|
+
automation: aut,
|
|
1192
|
+
runId: run,
|
|
1193
|
+
token: tok,
|
|
1194
|
+
now,
|
|
1195
|
+
step: {
|
|
1196
|
+
done: true,
|
|
1197
|
+
run: {
|
|
1198
|
+
state: "failed",
|
|
1199
|
+
error,
|
|
1200
|
+
counts: usageCounts(usage),
|
|
1201
|
+
...(taint ? { taint } : {}),
|
|
1202
|
+
},
|
|
1203
|
+
...(next ? { nextRunAt: next.at } : {}),
|
|
1204
|
+
consecutiveFailures: acc.consecutiveFailures,
|
|
1205
|
+
...(acc.pause ? { pause: acc.pause } : {}),
|
|
1206
|
+
},
|
|
1207
|
+
});
|
|
1208
|
+
if (ended)
|
|
1209
|
+
await deliver(deps, [
|
|
1210
|
+
runNotice(aut, run, now, "automation-failed", { error }),
|
|
1211
|
+
...pauseNotice(aut, run, now, acc),
|
|
1212
|
+
]);
|
|
1213
|
+
return "ran";
|
|
1214
|
+
}
|
|
1215
|
+
if (result.taint && !taint)
|
|
1216
|
+
taint = { at: canonicalInstant(result.taint.at), tool: result.taint.tool };
|
|
1217
|
+
const usage = usageNow();
|
|
1218
|
+
if (!result.done) {
|
|
1219
|
+
await deps.store.finishBuiltinRun({
|
|
1220
|
+
automation: aut,
|
|
1221
|
+
runId: run,
|
|
1222
|
+
token: tok,
|
|
1223
|
+
now,
|
|
1224
|
+
step: {
|
|
1225
|
+
done: false,
|
|
1226
|
+
cursor: {
|
|
1227
|
+
runId: run,
|
|
1228
|
+
occurrenceAt: occurrence.at,
|
|
1229
|
+
attempt,
|
|
1230
|
+
...(result.position !== undefined ? { position: result.position } : {}),
|
|
1231
|
+
...(taint ? { taint } : {}),
|
|
1232
|
+
usage,
|
|
1233
|
+
...(a.cursor?.manual ? { manual: a.cursor.manual } : {}),
|
|
1234
|
+
},
|
|
1235
|
+
},
|
|
1236
|
+
});
|
|
1237
|
+
return "ran";
|
|
1238
|
+
}
|
|
1239
|
+
report.ran++;
|
|
1240
|
+
const ended = await deps.store.finishBuiltinRun({
|
|
1241
|
+
automation: aut,
|
|
1242
|
+
runId: run,
|
|
1243
|
+
token: tok,
|
|
1244
|
+
now,
|
|
1245
|
+
step: {
|
|
1246
|
+
done: true,
|
|
1247
|
+
run: {
|
|
1248
|
+
state: "succeeded",
|
|
1249
|
+
outcome: result.outcome ?? "nothing-to-do",
|
|
1250
|
+
...(result.summary !== undefined ? { summary: plainText(result.summary) } : {}),
|
|
1251
|
+
counts: cleanCounts({ ...usageCounts(usage), ...(result.counts ?? {}) }),
|
|
1252
|
+
...(result.findings ? { findings: result.findings.slice(0, MAX_FINDINGS) } : {}),
|
|
1253
|
+
...(taint ? { taint } : {}),
|
|
1254
|
+
},
|
|
1255
|
+
...(next ? { nextRunAt: next.at } : {}),
|
|
1256
|
+
consecutiveFailures: 0,
|
|
1257
|
+
},
|
|
1258
|
+
});
|
|
1259
|
+
if (ended && result.notify) await deliver(deps, result.notify);
|
|
1260
|
+
return "ran";
|
|
1261
|
+
}
|
|
1262
|
+
|
|
1263
|
+
/** Findings kept per run (§4.5). */
|
|
1264
|
+
const MAX_FINDINGS = 200;
|
|
1265
|
+
|
|
1266
|
+
function usageCounts(u ) {
|
|
1267
|
+
return { steps: u.steps, statements: u.statements };
|
|
1268
|
+
}
|
|
1269
|
+
|
|
1270
|
+
function runNotice(
|
|
1271
|
+
a ,
|
|
1272
|
+
run ,
|
|
1273
|
+
now ,
|
|
1274
|
+
kind ,
|
|
1275
|
+
extra = {},
|
|
1276
|
+
) {
|
|
1277
|
+
return {
|
|
1278
|
+
id: `${kind}:${run}`,
|
|
1279
|
+
kind,
|
|
1280
|
+
siteId: a.siteId,
|
|
1281
|
+
automationId: a.id,
|
|
1282
|
+
automationName: a.name,
|
|
1283
|
+
runId: run,
|
|
1284
|
+
recipients: [a.owner.id],
|
|
1285
|
+
at: now,
|
|
1286
|
+
...extra,
|
|
1287
|
+
};
|
|
1288
|
+
}
|
|
1289
|
+
|
|
1290
|
+
function pauseNotice(
|
|
1291
|
+
a ,
|
|
1292
|
+
run ,
|
|
1293
|
+
now ,
|
|
1294
|
+
acc ,
|
|
1295
|
+
) {
|
|
1296
|
+
if (!acc.pause) return [];
|
|
1297
|
+
return [
|
|
1298
|
+
{
|
|
1299
|
+
...runNotice(a, run, now, "automation-paused", { pausedReason: acc.pause.pausedReason }),
|
|
1300
|
+
id: `automation-paused:${a.id}:${run}`,
|
|
1301
|
+
},
|
|
1302
|
+
];
|
|
1303
|
+
}
|
|
1304
|
+
|
|
1305
|
+
/** Sends notifications after a committed end; a notifier that fails never fails the tick. */
|
|
1306
|
+
async function deliver(deps , notices ) {
|
|
1307
|
+
if (!deps.notify) return;
|
|
1308
|
+
for (const n of notices) {
|
|
1309
|
+
try {
|
|
1310
|
+
await deps.notify.notify(n);
|
|
1311
|
+
} catch (e) {
|
|
1312
|
+
deps.log?.(
|
|
1313
|
+
`schedules: notification ${n.id} failed: ${e instanceof Error ? e.message : String(e)}`,
|
|
1314
|
+
);
|
|
1315
|
+
}
|
|
1316
|
+
}
|
|
1317
|
+
}
|
|
1318
|
+
|
|
1319
|
+
/** Builds a `Scheduler` over a store factory: each tick gets a fresh meter (and so a fresh budget). */
|
|
1320
|
+
export function createScheduler(
|
|
1321
|
+
options
|
|
1322
|
+
|
|
1323
|
+
|
|
1324
|
+
|
|
1325
|
+
,
|
|
1326
|
+
) {
|
|
1327
|
+
const { openStore, newMeter, ...rest } = options;
|
|
1328
|
+
return {
|
|
1329
|
+
async runDue(now, budget, trigger) {
|
|
1330
|
+
const meter = newMeter(budget);
|
|
1331
|
+
return runDue(now, { ...rest, store: openStore(meter), meter, budget, trigger });
|
|
1332
|
+
},
|
|
1333
|
+
async nextWakeAt(now) {
|
|
1334
|
+
const meter = newMeter({
|
|
1335
|
+
maxQueries: 1,
|
|
1336
|
+
maxReleases: 0,
|
|
1337
|
+
deadlineMs: Number.POSITIVE_INFINITY,
|
|
1338
|
+
});
|
|
1339
|
+
const next = overviewNextWake(await openStore(meter).overview(canonicalInstant(now)));
|
|
1340
|
+
return next ? new Date(next) : undefined;
|
|
1341
|
+
},
|
|
1342
|
+
};
|
|
1343
|
+
}
|