@proofoftech/flowsafe 0.34.0 → 0.35.0

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 (33) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/README.md +1 -1
  3. package/dist/do-runner/schedule-source.d.ts +4 -3
  4. package/dist/do-runner/schedule-source.d.ts.map +1 -1
  5. package/dist/do-runner/schedule-source.js.map +1 -1
  6. package/dist/schedules/fire-plan.d.ts +30 -0
  7. package/dist/schedules/fire-plan.d.ts.map +1 -0
  8. package/dist/schedules/fire-plan.js +111 -0
  9. package/dist/schedules/fire-plan.js.map +1 -0
  10. package/dist/schedules/index.d.ts +4 -2
  11. package/dist/schedules/index.d.ts.map +1 -1
  12. package/dist/schedules/index.js +2 -0
  13. package/dist/schedules/index.js.map +1 -1
  14. package/dist/schedules/mutation-contract.d.ts +8 -6
  15. package/dist/schedules/mutation-contract.d.ts.map +1 -1
  16. package/dist/schedules/mutation-contract.js.map +1 -1
  17. package/dist/schedules/router.d.ts +9 -6
  18. package/dist/schedules/router.d.ts.map +1 -1
  19. package/dist/schedules/router.js +362 -94
  20. package/dist/schedules/router.js.map +1 -1
  21. package/dist/schedules/schedule-extensions.d.ts +46 -0
  22. package/dist/schedules/schedule-extensions.d.ts.map +1 -0
  23. package/dist/schedules/schedule-extensions.js +7 -0
  24. package/dist/schedules/schedule-extensions.js.map +1 -0
  25. package/dist/schedules/schedules-d1.d.ts +44 -10
  26. package/dist/schedules/schedules-d1.d.ts.map +1 -1
  27. package/dist/schedules/schedules-d1.js +437 -68
  28. package/dist/schedules/schedules-d1.js.map +1 -1
  29. package/dist/schedules/tick.d.ts +81 -18
  30. package/dist/schedules/tick.d.ts.map +1 -1
  31. package/dist/schedules/tick.js +701 -168
  32. package/dist/schedules/tick.js.map +1 -1
  33. package/package.json +1 -1
@@ -31,6 +31,7 @@ import { isPathSafeId } from '../do-runner/path-safe-id.js';
31
31
  import { validateTablePrefix } from '../do-runner/table-prefix.js';
32
32
  import { d1Changes, jsonOrNull, parseJsonOrUndefined, } from '../signals/d1-shared.js';
33
33
  import { FENCED_SCHEDULE_STORAGE, ScheduleMutationConflictError, ScheduleMutationOutcomeUnknownError, } from './mutation-contract.js';
34
+ import { SCHEDULE_CATCH_UP_MAX_MISSED, SCHEDULE_CATCH_UP_MAX_WINDOW_MS, SCHEDULE_JITTER_MAX_MS, } from './schedule-extensions.js';
34
35
  const AGENT_DISPATCH_OUTCOME_BY_ACTION = {
35
36
  wake: 'succeeded',
36
37
  deliver: 'delivered',
@@ -82,7 +83,26 @@ const SCHEDULE_COLUMNS = [
82
83
  'ownerType',
83
84
  'ownerId',
84
85
  'creatorRole',
86
+ 'at',
87
+ 'completedAt',
88
+ 'admissionRefusals',
89
+ 'heldFireAt',
90
+ 'nominalFireAt',
91
+ 'fireStateNextFireAt',
92
+ 'firePolicy',
85
93
  ];
94
+ const SCHEDULE_ADDED_COLUMNS = {
95
+ creatorRole: "TEXT CHECK (creatorRole IN ('admin', 'builder', 'operator', 'reviewer', 'viewer'))",
96
+ deletionRequestedAt: 'INTEGER',
97
+ at: 'INTEGER',
98
+ completedAt: 'INTEGER',
99
+ admissionRefusals: 'INTEGER NOT NULL DEFAULT 0',
100
+ heldFireAt: 'INTEGER',
101
+ nominalFireAt: 'INTEGER',
102
+ fireStateNextFireAt: 'INTEGER',
103
+ firePolicy: 'TEXT',
104
+ lastPublishedDispatch: 'TEXT',
105
+ };
86
106
  function mutationUnknown(cause) {
87
107
  return new ScheduleMutationOutcomeUnknownError({ cause });
88
108
  }
@@ -162,9 +182,18 @@ function mutationScheduleRow(row) {
162
182
  'ownerType',
163
183
  'ownerId',
164
184
  'creatorRole',
185
+ 'firePolicy',
186
+ ];
187
+ const numeric = ['nextFireAt', 'createdAt', 'updatedAt', 'admissionRefusals'];
188
+ const nullableNumeric = [
189
+ 'lastFireAt',
190
+ 'deletionRequestedAt',
191
+ 'at',
192
+ 'completedAt',
193
+ 'heldFireAt',
194
+ 'nominalFireAt',
195
+ 'fireStateNextFireAt',
165
196
  ];
166
- const numeric = ['nextFireAt', 'createdAt', 'updatedAt'];
167
- const nullableNumeric = ['lastFireAt', 'deletionRequestedAt'];
168
197
  if (text.some((key) => typeof row[key] !== 'string') ||
169
198
  nullableText.some((key) => row[key] !== null && typeof row[key] !== 'string') ||
170
199
  numeric.some((key) => typeof row[key] !== 'number' || !Number.isFinite(row[key])) ||
@@ -175,7 +204,7 @@ function mutationScheduleRow(row) {
175
204
  return row;
176
205
  }
177
206
  function captureSchedule(schedule) {
178
- const { id, target, cron, timezone, status, nextFireAt, lastFireAt, lastRunId, createdAt, updatedAt, metadata, ownerType, ownerId, creatorRole, } = schedule;
207
+ const { id, target, cron, timezone, status, nextFireAt, lastFireAt, lastRunId, createdAt, updatedAt, metadata, ownerType, ownerId, creatorRole, at, completedAt, admissionRefusals, heldFireAt, nominalFireAt, overlapPolicy, catchUp, jitterMs, } = schedule;
179
208
  return {
180
209
  id,
181
210
  target: JSON.stringify(target),
@@ -192,22 +221,107 @@ function captureSchedule(schedule) {
192
221
  ownerId: ownerId ?? null,
193
222
  creatorRole: creatorRole ?? null,
194
223
  deletionRequestedAt: null,
224
+ at: at ?? null,
225
+ completedAt: completedAt ?? null,
226
+ admissionRefusals: admissionRefusals ?? 0,
227
+ heldFireAt: heldFireAt ?? null,
228
+ nominalFireAt: nominalFireAt ?? null,
229
+ fireStateNextFireAt: nextFireAt,
230
+ firePolicy: overlapPolicy === undefined &&
231
+ catchUp === undefined &&
232
+ jitterMs === undefined
233
+ ? null
234
+ : JSON.stringify({ overlapPolicy, catchUp, jitterMs }),
195
235
  };
196
236
  }
197
237
  function captureSchedulePatch(patch) {
198
- const { cron, timezone, status, nextFireAt, metadata, target, ownerType, ownerId, } = patch;
238
+ const { cron, timezone, status, nextFireAt, metadata, target, ownerType, ownerId, at, completedAt, heldFireAt, overlapPolicy, catchUp, jitterMs, } = patch;
239
+ const timingChanged = at !== undefined ||
240
+ cron !== undefined ||
241
+ timezone !== undefined ||
242
+ nextFireAt !== undefined;
243
+ const policyChanged = overlapPolicy !== undefined ||
244
+ catchUp !== undefined ||
245
+ jitterMs !== undefined;
199
246
  return {
200
247
  updatedAt: Date.now(),
201
248
  ...(cron !== undefined ? { cron } : {}),
202
- ...(timezone !== undefined ? { timezone: timezone ?? null } : {}),
249
+ ...(typeof at === 'number'
250
+ ? { timezone: null }
251
+ : timezone !== undefined
252
+ ? { timezone: timezone ?? null }
253
+ : {}),
203
254
  ...(status !== undefined ? { status } : {}),
204
255
  ...(nextFireAt !== undefined ? { nextFireAt } : {}),
205
256
  ...(metadata !== undefined ? { metadata: jsonOrNull(metadata) } : {}),
206
257
  ...(target !== undefined ? { target: JSON.stringify(target) } : {}),
207
258
  ...(ownerType !== undefined ? { ownerType: ownerType ?? null } : {}),
208
259
  ...(ownerId !== undefined ? { ownerId: ownerId ?? null } : {}),
260
+ ...(at !== undefined ? { at } : {}),
261
+ ...(completedAt !== undefined ? { completedAt } : {}),
262
+ ...(timingChanged || status === 'paused' || heldFireAt === null
263
+ ? { heldFireAt: null }
264
+ : {}),
265
+ ...(timingChanged
266
+ ? { nominalFireAt: null, admissionRefusals: 0, fireStateNextFireAt: null }
267
+ : {}),
268
+ ...(policyChanged
269
+ ? { firePolicy: JSON.stringify({ overlapPolicy, catchUp, jitterMs }) }
270
+ : {}),
209
271
  };
210
272
  }
273
+ function patchFirePolicySql(parameter) {
274
+ return `NULLIF(json_patch(
275
+ CASE WHEN json_valid(firePolicy)
276
+ THEN CASE WHEN json_type(firePolicy) = 'object' THEN firePolicy ELSE '{}' END
277
+ ELSE '{}'
278
+ END,
279
+ ${parameter}
280
+ ), '{}')`;
281
+ }
282
+ function isIntegerInRange(value, min, max) {
283
+ return (typeof value === 'number' &&
284
+ Number.isSafeInteger(value) &&
285
+ value >= min &&
286
+ value <= max);
287
+ }
288
+ function isScheduleCatchUp(value) {
289
+ if (!value || typeof value !== 'object' || Array.isArray(value))
290
+ return false;
291
+ const { maxMissed, windowMs } = value;
292
+ return (isIntegerInRange(maxMissed, 0, SCHEDULE_CATCH_UP_MAX_MISSED) &&
293
+ isIntegerInRange(windowMs, 60_000, SCHEDULE_CATCH_UP_MAX_WINDOW_MS));
294
+ }
295
+ function decodeFirePolicy(row) {
296
+ if (row.firePolicy === null)
297
+ return undefined;
298
+ const policy = parseJsonOrUndefined(row.firePolicy);
299
+ if (policy && typeof policy === 'object' && !Array.isArray(policy)) {
300
+ const { overlapPolicy, catchUp, jitterMs } = policy;
301
+ if ((overlapPolicy === undefined ||
302
+ overlapPolicy === 'allow' ||
303
+ overlapPolicy === 'skip' ||
304
+ overlapPolicy === 'queue_one') &&
305
+ (catchUp === undefined || isScheduleCatchUp(catchUp)) &&
306
+ (jitterMs === undefined ||
307
+ isIntegerInRange(jitterMs, 0, SCHEDULE_JITTER_MAX_MS))) {
308
+ return {
309
+ ...(overlapPolicy !== undefined ? { overlapPolicy } : {}),
310
+ ...(catchUp !== undefined
311
+ ? {
312
+ catchUp: {
313
+ maxMissed: catchUp.maxMissed,
314
+ windowMs: catchUp.windowMs,
315
+ },
316
+ }
317
+ : {}),
318
+ ...(jitterMs !== undefined ? { jitterMs } : {}),
319
+ };
320
+ }
321
+ }
322
+ console.warn('schedule-fire-policy-malformed', { scheduleId: row.id });
323
+ return undefined;
324
+ }
211
325
  function requiresOpenFence(operation) {
212
326
  return (operation === 'create' ||
213
327
  operation === 'fire' ||
@@ -245,6 +359,8 @@ function deletionFacts(result) {
245
359
  }
246
360
  function rowToSchedule(row) {
247
361
  const target = parseJsonOrUndefined(row.target);
362
+ // Older writers can advance nextFireAt without updating its associated state.
363
+ const fireStateMatches = row.fireStateNextFireAt === row.nextFireAt;
248
364
  const schedule = {
249
365
  id: row.id,
250
366
  // Legacy read-shim: base.d.ts mandates every SchedulesStorage run row
@@ -270,6 +386,16 @@ function rowToSchedule(row) {
270
386
  ? { ownerType: row.ownerType }
271
387
  : {}),
272
388
  ...(row.ownerId !== null ? { ownerId: row.ownerId } : {}),
389
+ ...(row.at !== null ? { at: row.at } : {}),
390
+ ...(row.completedAt !== null ? { completedAt: row.completedAt } : {}),
391
+ ...(fireStateMatches && row.admissionRefusals !== 0
392
+ ? { admissionRefusals: row.admissionRefusals }
393
+ : {}),
394
+ ...(row.heldFireAt !== null ? { heldFireAt: row.heldFireAt } : {}),
395
+ ...(fireStateMatches && row.nominalFireAt !== null
396
+ ? { nominalFireAt: row.nominalFireAt }
397
+ : {}),
398
+ ...decodeFirePolicy(row),
273
399
  };
274
400
  return row.creatorRole !== null &&
275
401
  APPROVAL_ROLES.includes(row.creatorRole)
@@ -455,8 +581,9 @@ export class D1SchedulesStorage extends SchedulesStorage {
455
581
  metadata TEXT,
456
582
  ownerType TEXT,
457
583
  ownerId TEXT,
458
- creatorRole TEXT CHECK (creatorRole IN ('admin', 'builder', 'operator', 'reviewer', 'viewer')),
459
- deletionRequestedAt INTEGER
584
+ ${Object.entries(SCHEDULE_ADDED_COLUMNS)
585
+ .map(([name, type]) => `${name} ${type}`)
586
+ .join(',\n ')}
460
587
  )`)
461
588
  .run()
462
589
  .then(() => this.#ensureScheduleColumns())
@@ -468,6 +595,10 @@ export class D1SchedulesStorage extends SchedulesStorage {
468
595
  ON ${this.#schedules} (status, nextFireAt)`)
469
596
  .run())
470
597
  .then(() => this.#db
598
+ .prepare(`CREATE INDEX IF NOT EXISTS idx_${this.#schedules}_held
599
+ ON ${this.#schedules} (status, heldFireAt)`)
600
+ .run())
601
+ .then(() => this.#db
471
602
  .prepare(`CREATE TABLE IF NOT EXISTS ${this.#triggers} (
472
603
  id TEXT PRIMARY KEY,
473
604
  scheduleId TEXT NOT NULL,
@@ -496,22 +627,22 @@ export class D1SchedulesStorage extends SchedulesStorage {
496
627
  return this.#ready;
497
628
  }
498
629
  async #ensureScheduleColumns() {
499
- const { results } = await this.#db
500
- .prepare(`PRAGMA table_info(${this.#schedules})`)
501
- .all();
502
- const names = new Set(results.map((column) => column.name));
503
- if (!names.has('creatorRole')) {
504
- await this.#db
505
- .prepare(`ALTER TABLE ${this.#schedules}
506
- ADD COLUMN creatorRole TEXT
507
- CHECK (creatorRole IN ('admin', 'builder', 'operator', 'reviewer', 'viewer'))`)
508
- .run();
509
- }
510
- if (!names.has('deletionRequestedAt')) {
511
- await this.#db
512
- .prepare(`ALTER TABLE ${this.#schedules}
513
- ADD COLUMN deletionRequestedAt INTEGER`)
514
- .run();
630
+ const statement = this.#db.prepare(`PRAGMA table_info(${this.#schedules})`);
631
+ let { results } = await statement.all();
632
+ for (const [name, type] of Object.entries(SCHEDULE_ADDED_COLUMNS)) {
633
+ if (results.some((column) => column.name === name))
634
+ continue;
635
+ try {
636
+ await this.#db
637
+ .prepare(`ALTER TABLE ${this.#schedules} ADD COLUMN ${name} ${type}`)
638
+ .run();
639
+ }
640
+ catch (error) {
641
+ // Another initializer can add the same column after the schema read.
642
+ ({ results } = await statement.all());
643
+ if (!results.some((column) => column.name === name))
644
+ throw error;
645
+ }
515
646
  }
516
647
  }
517
648
  async init() {
@@ -567,7 +698,7 @@ export class D1SchedulesStorage extends SchedulesStorage {
567
698
  this.#db
568
699
  .prepare(`SELECT COUNT(*) AS total,
569
700
  EXISTS(SELECT 1 FROM ${this.#schedules} WHERE id COLLATE BINARY = ?1) AS id_exists
570
- FROM ${this.#schedules}`)
701
+ FROM ${this.#schedules} WHERE completedAt IS NULL`)
571
702
  .bind(row.id),
572
703
  this.#insertScheduleStatement(row, prepared, maxSchedules),
573
704
  this.#db
@@ -678,57 +809,97 @@ export class D1SchedulesStorage extends SchedulesStorage {
678
809
  const { results } = await bound.all();
679
810
  return results.map(rowToSchedule);
680
811
  }
681
- async updateSchedule(id, patch, context) {
812
+ async listHeldSchedules(now, limit) {
813
+ await this.#ensureSchema();
814
+ const limitClause = limit !== undefined ? ' LIMIT ?' : '';
815
+ const stmt = this.#db.prepare(`SELECT * FROM ${this.#schedules}
816
+ WHERE status = 'active' AND deletionRequestedAt IS NULL
817
+ AND heldFireAt IS NOT NULL AND nextFireAt > ?
818
+ ORDER BY heldFireAt ASC${limitClause}`);
819
+ const bound = limit !== undefined ? stmt.bind(now, limit) : stmt.bind(now);
820
+ const { results } = await bound.all();
821
+ return results.map(rowToSchedule);
822
+ }
823
+ async updateSchedule(id, patch, context, expected) {
682
824
  const epoch = normalizeMutationEpoch(context?.mutationEpoch);
683
- return this.#updateSchedule(id, captureSchedulePatch(patch), epoch, 'update');
825
+ return this.#updateSchedule(id, captureSchedulePatch(patch), epoch, 'update', expected
826
+ ? { at: expected.at ?? null, completedAt: expected.completedAt ?? null }
827
+ : undefined);
684
828
  }
685
829
  async pauseSchedule(id, context) {
686
830
  const epoch = normalizeMutationEpoch(context?.mutationEpoch);
687
- return this.#updateSchedule(id, { status: 'paused', updatedAt: Date.now() }, epoch, 'pause');
831
+ return this.#updateSchedule(id, { status: 'paused', heldFireAt: null, updatedAt: Date.now() }, epoch, 'pause');
688
832
  }
689
833
  async resumeSchedule(id, mutation, context) {
690
834
  const epoch = normalizeMutationEpoch(context?.mutationEpoch);
691
- const { expectedCron, expectedTimezone, nextFireAt } = mutation;
692
- return this.#updateSchedule(id, { status: 'active', nextFireAt, updatedAt: Date.now() }, epoch, 'resume', {
835
+ const { expectedCron, expectedTimezone, expectedAt, nextFireAt } = mutation;
836
+ return this.#updateSchedule(id, {
837
+ status: 'active',
838
+ nextFireAt,
839
+ nominalFireAt: null,
840
+ admissionRefusals: 0,
841
+ fireStateNextFireAt: null,
842
+ updatedAt: Date.now(),
843
+ }, epoch, 'resume', {
693
844
  cron: expectedCron,
694
845
  timezone: expectedTimezone ?? null,
846
+ at: expectedAt ?? null,
847
+ completedAt: null,
695
848
  });
696
849
  }
697
850
  async #updateSchedule(id, patch, epoch, operation, expected) {
698
851
  const fields = Object.entries(patch);
699
852
  const prepared = await this.#prepareMutation(epoch, operation);
700
853
  const idParameter = fields.length + 13;
854
+ const expectedFields = Object.entries(expected ?? {});
855
+ const expectedGuard = expectedFields
856
+ .map(([key], index) => `AND ${key} COLLATE BINARY IS ?${idParameter + index + 1}`)
857
+ .join(' ');
858
+ const firePolicyPatch = patch.firePolicy;
859
+ // The prior-row projection verifies the merge against the same fenced batch.
860
+ const priorPolicy = firePolicyPatch === undefined
861
+ ? ''
862
+ : `, ${patchFirePolicySql('?2')} AS patchedFirePolicy`;
701
863
  // Targeted writes preserve columns advanced by a concurrent fire claim.
702
- const sets = fields.map(([key], index) => `${key} = ?${index + 13}`);
864
+ const sets = fields.map(([key], index) => {
865
+ const parameter = `?${index + 13}`;
866
+ return `${key} = ${key === 'firePolicy' ? patchFirePolicySql(parameter) : parameter}`;
867
+ });
703
868
  const results = await this.#executeMutation(prepared, [
704
869
  ...this.#mutationDiagnostics(),
705
870
  this.#db
706
- .prepare(`SELECT * FROM ${this.#schedules} WHERE id COLLATE BINARY = ?1 LIMIT 2`)
707
- .bind(id),
871
+ .prepare(`SELECT *${priorPolicy} FROM ${this.#schedules} WHERE id COLLATE BINARY = ?1 LIMIT 2`)
872
+ .bind(id, ...(firePolicyPatch === undefined ? [] : [firePolicyPatch])),
708
873
  this.#db
709
874
  .prepare(`UPDATE ${this.#schedules} SET ${sets.join(', ')}
710
875
  WHERE id COLLATE BINARY = ?${idParameter} AND deletionRequestedAt IS NULL
711
- ${expected ? `AND cron COLLATE BINARY = ?${idParameter + 1} AND timezone COLLATE BINARY IS ?${idParameter + 2}` : ''}
876
+ ${expectedGuard}
712
877
  AND ${scheduleMutationGuard(prepared)} RETURNING *`)
713
- .bind(...prepared.bindings, ...fields.map(([, value]) => value), id, ...(expected ? [expected.cron, expected.timezone] : [])),
878
+ .bind(...prepared.bindings, ...fields.map(([, value]) => value), id, ...expectedFields.map(([, value]) => value)),
714
879
  ], [3]);
715
880
  let missing;
716
881
  let changed = false;
717
882
  try {
718
- const previous = singleScheduleRow(results[2]);
883
+ const selected = singleScheduleRow(results[2]);
884
+ const { patchedFirePolicy, ...previous } = selected ?? {};
719
885
  const updated = singleScheduleRow(results[3]);
720
- if (previous) {
886
+ if (selected) {
721
887
  requireScheduleFields(previous, { id });
722
888
  mutationScheduleRow(previous);
723
889
  }
724
- missing = !previous || previous.deletionRequestedAt !== null;
890
+ missing = !selected || previous.deletionRequestedAt !== null;
725
891
  if (updated) {
726
- if (missing ||
727
- (expected &&
728
- !sameScheduleFields(previous, expected))) {
892
+ if (missing || (expected && !sameScheduleFields(previous, expected))) {
729
893
  throw new Error('schedule update contradicts its prior row');
730
894
  }
731
- requireScheduleFields(updated, { ...previous, ...patch, id });
895
+ requireScheduleFields(updated, {
896
+ ...previous,
897
+ ...patch,
898
+ ...(firePolicyPatch === undefined
899
+ ? {}
900
+ : { firePolicy: patchedFirePolicy }),
901
+ id,
902
+ });
732
903
  return rowToSchedule(mutationScheduleRow(updated));
733
904
  }
734
905
  changed =
@@ -787,8 +958,10 @@ export class D1SchedulesStorage extends SchedulesStorage {
787
958
  ...this.#mutationDiagnostics(),
788
959
  this.#db
789
960
  .prepare(`UPDATE ${this.#schedules}
790
- SET nextFireAt = ?13, lastFireAt = ?14, lastRunId = ?15, updatedAt = ?16
961
+ SET nextFireAt = ?13, lastFireAt = ?14, lastRunId = ?15, updatedAt = ?16,
962
+ nominalFireAt = NULL, admissionRefusals = 0, fireStateNextFireAt = NULL
791
963
  WHERE id = ?17 AND nextFireAt = ?18 AND status = 'active'
964
+ AND nextFireAt <= ?14 AND at IS NULL
792
965
  AND deletionRequestedAt IS NULL AND ${scheduleMutationGuard(prepared)}
793
966
  RETURNING id`)
794
967
  .bind(...prepared.bindings, newNextFireAt, lastFireAt, lastRunId, Date.now(), id, expectedNextFireAt),
@@ -798,30 +971,162 @@ export class D1SchedulesStorage extends SchedulesStorage {
798
971
  /** Atomically claim one due fire and persist its recoverable dispatch row. */
799
972
  async claimScheduleFire(claim) {
800
973
  const epoch = normalizeMutationEpoch(claim.mutationEpoch);
801
- const captured = { ...claim, trigger: { ...claim.trigger } };
802
- const triggerMetadata = jsonOrNull(epoch === undefined
803
- ? captured.trigger.metadata
804
- : { ...captured.trigger.metadata, mutationEpoch: epoch });
974
+ const { scheduleId, expectedNextFireAt, expectedLastRunId, newNextFireAt, actualFireAt, runId, held, complete, nominalFireAt, trigger, } = claim;
975
+ return this.#mutateScheduleFire(epoch, scheduleId, expectedNextFireAt, held ? 'held' : complete ? 'complete' : 'due', {
976
+ lastFireAt: actualFireAt,
977
+ lastRunId: runId,
978
+ admissionRefusals: 0,
979
+ ...(held
980
+ ? { heldFireAt: null }
981
+ : complete
982
+ ? {
983
+ status: 'paused',
984
+ completedAt: actualFireAt,
985
+ nominalFireAt: null,
986
+ fireStateNextFireAt: null,
987
+ }
988
+ : {
989
+ nextFireAt: newNextFireAt,
990
+ nominalFireAt: nominalFireAt ?? null,
991
+ fireStateNextFireAt: newNextFireAt,
992
+ }),
993
+ }, trigger, actualFireAt, expectedLastRunId);
994
+ }
995
+ async skipScheduleFire(skip) {
996
+ const epoch = normalizeMutationEpoch(skip.mutationEpoch);
997
+ const { scheduleId, expectedNextFireAt, expectedHeldFireAt, newNextFireAt, nominalFireAt, status, completedAt, admissionRefusals, trigger, } = skip;
998
+ return this.#mutateScheduleFire(epoch, scheduleId, expectedHeldFireAt ?? expectedNextFireAt, expectedHeldFireAt !== undefined ? 'held' : 'skip', {
999
+ admissionRefusals,
1000
+ ...(expectedHeldFireAt === undefined
1001
+ ? {
1002
+ nextFireAt: newNextFireAt,
1003
+ nominalFireAt: nominalFireAt ?? null,
1004
+ fireStateNextFireAt: newNextFireAt,
1005
+ }
1006
+ : {}),
1007
+ ...(expectedHeldFireAt !== undefined || status === 'paused'
1008
+ ? { heldFireAt: null }
1009
+ : {}),
1010
+ ...(status !== undefined ? { status } : {}),
1011
+ ...(completedAt !== undefined ? { completedAt } : {}),
1012
+ }, trigger);
1013
+ }
1014
+ async holdScheduleFire(hold) {
1015
+ const epoch = normalizeMutationEpoch(hold.mutationEpoch);
1016
+ const { scheduleId, expectedNextFireAt, newNextFireAt, heldFireAt, nominalFireAt, } = hold;
1017
+ return this.#mutateScheduleFire(epoch, scheduleId, expectedNextFireAt, 'hold', {
1018
+ nextFireAt: newNextFireAt,
1019
+ heldFireAt,
1020
+ nominalFireAt: nominalFireAt ?? null,
1021
+ admissionRefusals: 0,
1022
+ fireStateNextFireAt: newNextFireAt,
1023
+ });
1024
+ }
1025
+ async #mutateScheduleFire(epoch, scheduleId, expectedFireAt, operation, patch, trigger, actualFireAt = null, expectedLastRunId) {
1026
+ const triggerId = trigger?.id;
1027
+ const triggerActualFireAt = trigger?.actualFireAt;
1028
+ const triggerOutcome = trigger?.outcome;
1029
+ // The NOT NULL fire time aborts the CAS batch if the trigger ID belongs to another fire.
1030
+ const unavailable = triggerOutcome === 'skipped' &&
1031
+ trigger?.metadata?.reason === 'admission-unavailable';
1032
+ const triggerValues = trigger
1033
+ ? [
1034
+ triggerId,
1035
+ trigger.scheduleId,
1036
+ trigger.runId,
1037
+ trigger.scheduledFireAt,
1038
+ triggerActualFireAt,
1039
+ triggerOutcome,
1040
+ trigger.error ?? null,
1041
+ trigger.triggerKind ?? 'schedule-fire',
1042
+ trigger.parentTriggerId ?? null,
1043
+ jsonOrNull(epoch === undefined
1044
+ ? trigger.metadata
1045
+ : { ...trigger.metadata, mutationEpoch: epoch }),
1046
+ ]
1047
+ : undefined;
1048
+ const fields = Object.entries({ ...patch, updatedAt: Date.now() });
1049
+ const sets = fields.map(([key], index) => `${key} = ?${index + 15}`);
1050
+ if (operation === 'complete')
1051
+ sets.push('nextFireAt = at');
1052
+ if (operation === 'held' && triggerOutcome === 'skipped') {
1053
+ sets.push('nominalFireAt = CASE WHEN fireStateNextFireAt = nextFireAt THEN nominalFireAt END', 'fireStateNextFireAt = nextFireAt');
1054
+ }
1055
+ const fireColumn = operation === 'held' ? 'heldFireAt' : 'nextFireAt';
1056
+ const phaseGuard = {
1057
+ due: ' AND at IS NULL AND heldFireAt IS NULL',
1058
+ hold: ' AND at IS NULL AND heldFireAt IS NULL',
1059
+ held: ' AND at IS NULL',
1060
+ complete: ' AND at IS NOT NULL',
1061
+ skip: '',
1062
+ }[operation];
1063
+ const requiresDue = operation !== 'held' && operation !== 'hold';
1064
+ const guards = [];
1065
+ const guardBindings = [];
1066
+ if (requiresDue) {
1067
+ guards.push(` AND nextFireAt <= ?${fields.length + 15}`);
1068
+ guardBindings.push(operation === 'skip' ? triggerActualFireAt : actualFireAt);
1069
+ }
1070
+ if (expectedLastRunId !== undefined) {
1071
+ guards.push(` AND lastRunId IS ?${fields.length + guardBindings.length + 15}`);
1072
+ guardBindings.push(expectedLastRunId);
1073
+ }
805
1074
  const prepared = await this.#prepareMutation(epoch, 'fire');
806
- const { trigger } = captured;
807
1075
  const results = await this.#executeMutation(prepared, [
808
1076
  ...this.#mutationDiagnostics(),
809
1077
  this.#db
810
- .prepare(`UPDATE ${this.#schedules}
811
- SET nextFireAt = ?13, lastFireAt = ?14, lastRunId = ?15, updatedAt = ?16
812
- WHERE id = ?17 AND nextFireAt = ?18 AND status = 'active'
813
- AND deletionRequestedAt IS NULL AND ${scheduleMutationGuard(prepared)}
814
- RETURNING id`)
815
- .bind(...prepared.bindings, captured.newNextFireAt, captured.actualFireAt, captured.runId, Date.now(), captured.scheduleId, captured.expectedNextFireAt),
816
- this.#db
817
- .prepare(`INSERT INTO ${this.#triggers} (
818
- id, scheduleId, runId, scheduledFireAt, actualFireAt, outcome,
819
- error, triggerKind, parentTriggerId, metadata
820
- ) SELECT ?, ?, ?, ?, ?, ?, ?, ?, ?, ? WHERE changes() = 1
1078
+ .prepare(`UPDATE ${this.#schedules} SET ${sets.join(', ')}
1079
+ WHERE id = ?13 AND ${fireColumn} = ?14 AND status = 'active'
1080
+ AND deletionRequestedAt IS NULL${phaseGuard}${guards.join('')}
1081
+ AND ${scheduleMutationGuard(prepared)}
821
1082
  RETURNING id`)
822
- .bind(trigger.id, trigger.scheduleId, trigger.runId, trigger.scheduledFireAt, trigger.actualFireAt, trigger.outcome, trigger.error ?? null, trigger.triggerKind ?? 'schedule-fire', trigger.parentTriggerId ?? null, triggerMetadata),
823
- ], [2, 3]);
824
- return results[2].rows.length === 1;
1083
+ .bind(...prepared.bindings, scheduleId, expectedFireAt, ...fields.map(([, value]) => value), ...guardBindings),
1084
+ ...(triggerValues
1085
+ ? [
1086
+ this.#db
1087
+ .prepare(`INSERT INTO ${this.#triggers} (
1088
+ id, scheduleId, runId, scheduledFireAt, actualFireAt, outcome,
1089
+ error, triggerKind, parentTriggerId, metadata
1090
+ ) SELECT ?, ?, ?, ?, ?, ?, ?, ?, ?, ? WHERE changes() = 1
1091
+ ${unavailable
1092
+ ? `ON CONFLICT (id) DO UPDATE SET
1093
+ actualFireAt = CASE
1094
+ WHEN scheduleId = excluded.scheduleId
1095
+ AND scheduledFireAt = excluded.scheduledFireAt
1096
+ AND outcome = 'skipped'
1097
+ AND json_extract(metadata, '$.reason') = 'admission-unavailable'
1098
+ THEN excluded.actualFireAt
1099
+ END,
1100
+ metadata = json_patch(metadata, json_object(
1101
+ 'unavailableAttempts', COALESCE(json_extract(metadata, '$.unavailableAttempts'), 0) + 1,
1102
+ 'refusedAt', json_extract(excluded.metadata, '$.refusedAt'),
1103
+ 'retryAt', json_extract(excluded.metadata, '$.retryAt'),
1104
+ 'mutationEpoch', json_extract(excluded.metadata, '$.mutationEpoch')
1105
+ ))`
1106
+ : ''}
1107
+ RETURNING id`)
1108
+ .bind(...triggerValues),
1109
+ ]
1110
+ : []),
1111
+ ], triggerValues ? [2, 3] : [2]);
1112
+ try {
1113
+ const row = singleScheduleRow(results[2]);
1114
+ const recorded = triggerValues
1115
+ ? singleScheduleRow(results[3])
1116
+ : undefined;
1117
+ if (row)
1118
+ requireScheduleFields(row, { id: scheduleId });
1119
+ if (row && triggerValues) {
1120
+ requireScheduleFields(recorded, { id: triggerId });
1121
+ }
1122
+ else if (recorded) {
1123
+ throw new Error('a lost schedule fire recorded a trigger');
1124
+ }
1125
+ return row !== undefined;
1126
+ }
1127
+ catch (cause) {
1128
+ throw mutationUnknown(cause);
1129
+ }
825
1130
  }
826
1131
  /**
827
1132
  * Lease one target-side signal attempt. A retry waits while the lease is
@@ -970,7 +1275,7 @@ export class D1SchedulesStorage extends SchedulesStorage {
970
1275
  this.#deletionFactsStatement(id),
971
1276
  this.#db
972
1277
  .prepare(`UPDATE ${this.#schedules}
973
- SET status = 'paused', updatedAt = ?13,
1278
+ SET status = 'paused', heldFireAt = NULL, updatedAt = ?13,
974
1279
  deletionRequestedAt = CASE
975
1280
  WHEN EXISTS (
976
1281
  SELECT 1 FROM ${this.#triggers}
@@ -1066,16 +1371,48 @@ export class D1SchedulesStorage extends SchedulesStorage {
1066
1371
  }
1067
1372
  async recordTrigger(trigger) {
1068
1373
  const id = trigger.id ?? crypto.randomUUID();
1069
- await this.#settleTrigger(trigger.scheduleId, () => this.#db
1374
+ const dispatchRef = trigger.metadata?.dispatchRef;
1375
+ const publishedDispatch = trigger.outcome === 'published' && dispatchRef !== undefined
1376
+ ? JSON.stringify({
1377
+ id,
1378
+ scheduleId: trigger.scheduleId,
1379
+ runId: trigger.runId,
1380
+ scheduledFireAt: trigger.scheduledFireAt,
1381
+ actualFireAt: trigger.actualFireAt,
1382
+ outcome: trigger.outcome,
1383
+ triggerKind: trigger.triggerKind ?? 'schedule-fire',
1384
+ metadata: { dispatchRef },
1385
+ })
1386
+ : undefined;
1387
+ const writeTrigger = () => this.#db
1070
1388
  .prepare(`INSERT OR REPLACE INTO ${this.#triggers} (
1071
1389
  id, scheduleId, runId, scheduledFireAt, actualFireAt, outcome,
1072
1390
  error, triggerKind, parentTriggerId, metadata
1073
1391
  )
1074
- SELECT ?, ?, ?, ?, ?, ?, ?, ?, ?, ?
1075
- WHERE EXISTS (SELECT 1 FROM ${this.#schedules} WHERE id = ?)`)
1076
- .bind(id, trigger.scheduleId, trigger.runId, trigger.scheduledFireAt, trigger.actualFireAt, trigger.outcome, trigger.error ?? null, trigger.triggerKind ?? 'schedule-fire', trigger.parentTriggerId ?? null, jsonOrNull(trigger.metadata), trigger.scheduleId));
1392
+ SELECT ?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9,
1393
+ CASE WHEN prior.origin IS NOT NULL
1394
+ THEN json_set(COALESCE(?10, '{}'), '$.scheduleOrigin', json(prior.origin))
1395
+ ELSE ?10
1396
+ END
1397
+ FROM (
1398
+ SELECT (
1399
+ SELECT CASE WHEN json_valid(metadata)
1400
+ THEN NULLIF(metadata -> '$.scheduleOrigin', 'null')
1401
+ END
1402
+ FROM ${this.#triggers} WHERE id = ?1 AND scheduleId = ?2
1403
+ ) AS origin
1404
+ ) AS prior
1405
+ WHERE EXISTS (SELECT 1 FROM ${this.#schedules} WHERE id = ?2)`)
1406
+ .bind(id, trigger.scheduleId, trigger.runId, trigger.scheduledFireAt, trigger.actualFireAt, trigger.outcome, trigger.error ?? null, trigger.triggerKind ?? 'schedule-fire', trigger.parentTriggerId ?? null, jsonOrNull(trigger.metadata));
1407
+ await this.#settleTrigger(trigger.scheduleId, writeTrigger, publishedDispatch === undefined
1408
+ ? undefined
1409
+ : () => this.#db
1410
+ .prepare(`UPDATE ${this.#schedules} SET lastPublishedDispatch = ?1
1411
+ WHERE id = ?2 AND (lastPublishedDispatch IS NULL
1412
+ OR json_extract(lastPublishedDispatch, '$.actualFireAt') <= ?3)`)
1413
+ .bind(publishedDispatch, trigger.scheduleId, trigger.actualFireAt));
1077
1414
  }
1078
- async #settleTrigger(scheduleId, build) {
1415
+ async #settleTrigger(scheduleId, build, rememberDispatch) {
1079
1416
  await this.#ensureSchema();
1080
1417
  const batch = this.#db.batch?.bind(this.#db);
1081
1418
  if (!batch) {
@@ -1083,6 +1420,7 @@ export class D1SchedulesStorage extends SchedulesStorage {
1083
1420
  }
1084
1421
  return batch([
1085
1422
  build(),
1423
+ ...(rememberDispatch ? [rememberDispatch()] : []),
1086
1424
  ...this.#completePendingDeletionStatements(scheduleId),
1087
1425
  ]);
1088
1426
  }
@@ -1162,6 +1500,37 @@ export class D1SchedulesStorage extends SchedulesStorage {
1162
1500
  .all();
1163
1501
  return results.map(rowToTrigger);
1164
1502
  }
1503
+ /** Read one trigger by its schedule and trigger ids, including after settlement. */
1504
+ async getTrigger(scheduleId, triggerId) {
1505
+ await this.#ensureSchema();
1506
+ const row = await this.#db
1507
+ .prepare(`SELECT * FROM ${this.#triggers} WHERE scheduleId = ? AND id = ?`)
1508
+ .bind(scheduleId, triggerId)
1509
+ .first();
1510
+ return row ? rowToTrigger(row) : null;
1511
+ }
1512
+ async latestDispatchedTrigger(scheduleId) {
1513
+ await this.#ensureSchema();
1514
+ const row = await this.#db
1515
+ .prepare(`SELECT schedules.lastPublishedDispatch, triggers.*
1516
+ FROM ${this.#schedules} AS schedules
1517
+ LEFT JOIN ${this.#triggers} AS triggers ON triggers.rowid = (
1518
+ SELECT rowid FROM ${this.#triggers}
1519
+ WHERE scheduleId = schedules.id AND outcome IN ('published', 'deferred')
1520
+ ORDER BY actualFireAt DESC, rowid DESC LIMIT 1
1521
+ )
1522
+ WHERE schedules.id = ?`)
1523
+ .bind(scheduleId)
1524
+ .first();
1525
+ if (!row)
1526
+ return null;
1527
+ const retained = parseJsonOrUndefined(row.lastPublishedDispatch);
1528
+ if (row.id !== null &&
1529
+ (!retained || row.actualFireAt >= retained.actualFireAt)) {
1530
+ return rowToTrigger(row);
1531
+ }
1532
+ return retained ?? null;
1533
+ }
1165
1534
  async listDeferredTriggers(limit = 100) {
1166
1535
  await this.#ensureSchema();
1167
1536
  if (!Number.isSafeInteger(limit) || limit < 0) {
@@ -1233,7 +1602,7 @@ export class D1SchedulesStorage extends SchedulesStorage {
1233
1602
  .prepare(`INSERT INTO ${this.#schedules} (${SCHEDULE_COLUMNS.join(', ')})
1234
1603
  SELECT ${SCHEDULE_COLUMNS.map((_, index) => `?${index + 13}`).join(', ')}
1235
1604
  WHERE ${scheduleMutationGuard(prepared)}
1236
- ${maxSchedules === undefined ? '' : `AND (SELECT COUNT(*) FROM ${this.#schedules}) < ?27`}
1605
+ ${maxSchedules === undefined ? '' : `AND (SELECT COUNT(*) FROM ${this.#schedules} WHERE completedAt IS NULL) < ?${SCHEDULE_COLUMNS.length + 13}`}
1237
1606
  ON CONFLICT (id) DO NOTHING RETURNING *`)
1238
1607
  .bind(...prepared.bindings, ...SCHEDULE_COLUMNS.map((key) => row[key]), ...(maxSchedules === undefined ? [] : [maxSchedules]));
1239
1608
  }