durability 5.1.0 → 5.2.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.
Files changed (98) hide show
  1. package/README.md +154 -21
  2. package/dist/{durability-alarms.d.ts → alarms/index.d.ts} +13 -5
  3. package/dist/{durability-alarms.js → alarms/index.js} +85 -74
  4. package/dist/alarms/migrations.d.ts +9 -0
  5. package/dist/alarms/migrations.js +133 -0
  6. package/dist/experimental.d.ts +10 -10
  7. package/dist/experimental.js +7 -7
  8. package/dist/{fanout.d.ts → fanout/index.d.ts} +13 -6
  9. package/dist/{fanout.js → fanout/index.js} +91 -83
  10. package/dist/fanout/migrations.d.ts +9 -0
  11. package/dist/fanout/migrations.js +181 -0
  12. package/dist/{stored-message.d.ts → fanout/stored-message.d.ts} +1 -1
  13. package/dist/index.d.ts +14 -9
  14. package/dist/index.js +13 -8
  15. package/dist/{log.d.ts → log/index.d.ts} +27 -20
  16. package/dist/{log.js → log/index.js} +200 -166
  17. package/dist/log/migrations.d.ts +18 -0
  18. package/dist/log/migrations.js +297 -0
  19. package/dist/{memoize.d.ts → memoize/index.d.ts} +1 -1
  20. package/dist/{memoize.js → memoize/index.js} +23 -21
  21. package/dist/memoize/migrations.d.ts +10 -0
  22. package/dist/memoize/migrations.js +21 -0
  23. package/dist/migrations.d.ts +0 -111
  24. package/dist/migrations.js +12 -628
  25. package/dist/{durability.d.ts → operations/index.d.ts} +13 -5
  26. package/dist/{durability.js → operations/index.js} +76 -70
  27. package/dist/operations/migrations.d.ts +10 -0
  28. package/dist/operations/migrations.js +150 -0
  29. package/dist/{outbox.d.ts → outbox/index.d.ts} +4 -4
  30. package/dist/{outbox.js → outbox/index.js} +35 -77
  31. package/dist/outbox/migrations.d.ts +9 -0
  32. package/dist/outbox/migrations.js +43 -0
  33. package/dist/policy.d.ts +19 -19
  34. package/dist/policy.js +13 -12
  35. package/dist/{routing-client.js → routing/client.js} +1 -1
  36. package/dist/{routing.d.ts → routing/index.d.ts} +3 -3
  37. package/dist/{routing.js → routing/index.js} +3 -3
  38. package/dist/{load.d.ts → routing/load.d.ts} +1 -1
  39. package/dist/{schedule.d.ts → schedule/index.d.ts} +16 -8
  40. package/dist/{schedule.js → schedule/index.js} +97 -83
  41. package/dist/schedule/migrations.d.ts +9 -0
  42. package/dist/schedule/migrations.js +118 -0
  43. package/dist/{scheduler.d.ts → scheduler/index.d.ts} +75 -25
  44. package/dist/{scheduler.js → scheduler/index.js} +308 -70
  45. package/dist/{semaphore-client.d.ts → semaphore/client.d.ts} +1 -1
  46. package/dist/{semaphore-client.js → semaphore/client.js} +8 -7
  47. package/dist/{semaphore.d.ts → semaphore/index.d.ts} +10 -10
  48. package/dist/{semaphore.js → semaphore/index.js} +7 -7
  49. package/dist/{semaphore-leases.d.ts → semaphore/leases.d.ts} +17 -6
  50. package/dist/{semaphore-leases.js → semaphore/leases.js} +28 -12
  51. package/dist/semaphore/migrations.d.ts +18 -0
  52. package/dist/semaphore/migrations.js +444 -0
  53. package/dist/semaphore/protocol.d.ts +451 -0
  54. package/dist/semaphore/protocol.js +114 -0
  55. package/dist/semaphore/queue-store.d.ts +107 -0
  56. package/dist/semaphore/queue-store.js +258 -0
  57. package/dist/{semaphore-queue.d.ts → semaphore/queue.d.ts} +15 -5
  58. package/dist/{semaphore-queue.js → semaphore/queue.js} +105 -46
  59. package/dist/{semaphore-server.d.ts → semaphore/server.d.ts} +12 -4
  60. package/dist/{semaphore-server.js → semaphore/server.js} +56 -28
  61. package/dist/semaphore/store.d.ts +53 -0
  62. package/dist/semaphore/store.js +107 -0
  63. package/dist/serialization.d.ts +5 -0
  64. package/dist/serialization.js +41 -16
  65. package/dist/{client.d.ts → socket/client.d.ts} +3 -3
  66. package/dist/{client.js → socket/client.js} +4 -4
  67. package/dist/{socket.d.ts → socket/index.d.ts} +15 -4
  68. package/dist/{socket.js → socket/index.js} +66 -20
  69. package/dist/socket/migrations.d.ts +9 -0
  70. package/dist/socket/migrations.js +57 -0
  71. package/dist/{socket-protocol.d.ts → socket/protocol.d.ts} +1 -1
  72. package/dist/storage.d.ts +4 -0
  73. package/dist/storage.js +22 -15
  74. package/dist/{topology-client.d.ts → topology/client.d.ts} +2 -2
  75. package/dist/{topology-client.js → topology/client.js} +3 -3
  76. package/dist/{topology.d.ts → topology/index.d.ts} +17 -7
  77. package/dist/{topology.js → topology/index.js} +106 -72
  78. package/dist/topology/migrations.d.ts +10 -0
  79. package/dist/topology/migrations.js +138 -0
  80. package/dist/topology/snapshot.d.ts +50 -0
  81. package/dist/topology/snapshot.js +38 -0
  82. package/dist/{tracker.d.ts → tracker/index.d.ts} +3 -3
  83. package/dist/{tracker.js → tracker/index.js} +9 -9
  84. package/package.json +11 -11
  85. package/dist/semaphore-protocol.d.ts +0 -231
  86. package/dist/semaphore-protocol.js +0 -106
  87. package/dist/semaphore-queue-store.d.ts +0 -95
  88. package/dist/semaphore-queue-store.js +0 -252
  89. package/dist/semaphore-store.d.ts +0 -43
  90. package/dist/semaphore-store.js +0 -108
  91. package/dist/topology-snapshot.d.ts +0 -70
  92. package/dist/topology-snapshot.js +0 -48
  93. /package/dist/{stored-message.js → fanout/stored-message.js} +0 -0
  94. /package/dist/{routing-client.d.ts → routing/client.d.ts} +0 -0
  95. /package/dist/{load.js → routing/load.js} +0 -0
  96. /package/dist/{socket-protocol.js → socket/protocol.js} +0 -0
  97. /package/dist/{tracked-source.d.ts → tracker/source.d.ts} +0 -0
  98. /package/dist/{tracked-source.js → tracker/source.js} +0 -0
@@ -9,14 +9,15 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
9
9
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
10
10
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11
11
  };
12
- var _DurabilitySchedule_instances, _DurabilitySchedule_engine, _DurabilitySchedule_nextOccurrence, _DurabilitySchedule_run, _DurabilitySchedule_onOutcome, _DurabilitySchedule_maxConcurrentRuns, _DurabilitySchedule_runTimeoutMs, _DurabilitySchedule_outcomeTimeoutMs, _DurabilitySchedule_maxOutcomeAttempts, _DurabilitySchedule_delay, _DurabilitySchedule_keyPrefix, _DurabilitySchedule_emit, _DurabilitySchedule_active, _DurabilitySchedule_delivering, _DurabilitySchedule_loop, _DurabilitySchedule_woken, _DurabilitySchedule_wakeSleeper, _DurabilitySchedule_nextPendingAt, _DurabilitySchedule_nextAfter, _DurabilitySchedule_idempotencyKey, _DurabilitySchedule_describe, _DurabilitySchedule_entity, _DurabilitySchedule_hold, _DurabilitySchedule_drive, _DurabilitySchedule_pass, _DurabilitySchedule_wake, _DurabilitySchedule_sleep, _DurabilitySchedule_nextWakeAt, _DurabilitySchedule_interruptOrphans, _DurabilitySchedule_tick, _DurabilitySchedule_startQueued, _DurabilitySchedule_reserveSlots, _DurabilitySchedule_start, _DurabilitySchedule_record, _DurabilitySchedule_deliverDue, _DurabilitySchedule_deliver, _DurabilitySchedule_deliverOnce, _DurabilitySchedule_failDelivery, _DurabilitySchedule_retryDelay;
13
- import { z } from 'zod';
14
- import { traceLifecycle, traceMethods } from './dev.js';
15
- import { reportFailure, ScheduledOutcomeTimeoutError, ScheduledRunInterruptedError, ScheduledRunTimeoutError, serializeError, } from './errors.js';
16
- import { durabilityScheduleMigrations, migrateCapability, } from './migrations.js';
17
- import { assertPositiveInteger, } from './policy.js';
18
- import { engineFor, } from './scheduler.js';
19
- import { exponential, jitter } from './utils.js';
12
+ var _DurabilitySchedule_instances, _DurabilitySchedule_engine, _DurabilitySchedule_channel, _DurabilitySchedule_nextOccurrence, _DurabilitySchedule_run, _DurabilitySchedule_onOutcome, _DurabilitySchedule_maxConcurrentRuns, _DurabilitySchedule_runTimeoutMs, _DurabilitySchedule_outcomeTimeoutMs, _DurabilitySchedule_maxOutcomeAttempts, _DurabilitySchedule_delay, _DurabilitySchedule_keyPrefix, _DurabilitySchedule_keySuffix, _DurabilitySchedule_emit, _DurabilitySchedule_active, _DurabilitySchedule_delivering, _DurabilitySchedule_loop, _DurabilitySchedule_woken, _DurabilitySchedule_wakeSleeper, _DurabilitySchedule_nextPendingAt, _DurabilitySchedule_nextAfter, _DurabilitySchedule_idempotencyKey, _DurabilitySchedule_describe, _DurabilitySchedule_entity, _DurabilitySchedule_hold, _DurabilitySchedule_drive, _DurabilitySchedule_pass, _DurabilitySchedule_wake, _DurabilitySchedule_sleep, _DurabilitySchedule_nextWakeAt, _DurabilitySchedule_interruptOrphans, _DurabilitySchedule_tick, _DurabilitySchedule_startQueued, _DurabilitySchedule_reserveSlots, _DurabilitySchedule_start, _DurabilitySchedule_record, _DurabilitySchedule_deliverDue, _DurabilitySchedule_deliver, _DurabilitySchedule_deliverOnce, _DurabilitySchedule_failDelivery, _DurabilitySchedule_retryDelay;
13
+ import * as v from 'valibot';
14
+ import { traceLifecycle, traceMethods } from '../dev.js';
15
+ import { reportFailure, ScheduledOutcomeTimeoutError, ScheduledRunInterruptedError, ScheduledRunTimeoutError, serializeError, } from '../errors.js';
16
+ import { durabilityScheduleMigrations } from './migrations.js';
17
+ import { migrateCapability, } from '../migrations.js';
18
+ import { assertPositiveInteger, } from '../policy.js';
19
+ import { assertChannel, defaultChannel, engineFor, } from '../scheduler/index.js';
20
+ import { exponential, jitter } from '../utils.js';
20
21
  const runsTable = {
21
22
  name: 'durability_schedule_runs',
22
23
  key: 'scheduled_time',
@@ -24,71 +25,71 @@ const runsTable = {
24
25
  // setTimeout overflows past 2^31 - 1 ms.
25
26
  const maxDelayMs = 2 ** 31 - 1;
26
27
  const fallbackRetryMs = 60000;
27
- const scheduleRowSchema = z.object({
28
- version: z.number().int().nonnegative(),
29
- expression: z.string().nullable(),
30
- next_at: z.number().int().nonnegative().nullable(),
31
- jitter_ms: z.number().int().nonnegative(),
28
+ const scheduleRowSchema = v.object({
29
+ version: v.pipe(v.number(), v.safeInteger(), v.minValue(0)),
30
+ expression: v.nullable(v.string()),
31
+ next_at: v.nullable(v.pipe(v.number(), v.safeInteger(), v.minValue(0))),
32
+ jitter_ms: v.pipe(v.number(), v.safeInteger(), v.minValue(0)),
32
33
  });
33
- const runStateSchema = z.enum(['queued', 'running', 'complete', 'errored']);
34
- const runRowSchema = z.object({
35
- scheduled_time: z.number().int().nonnegative(),
36
- due_at: z.number().int().nonnegative(),
34
+ const runStateSchema = v.picklist(['queued', 'running', 'complete', 'errored']);
35
+ const runRowSchema = v.object({
36
+ scheduled_time: v.pipe(v.number(), v.safeInteger(), v.minValue(0)),
37
+ due_at: v.pipe(v.number(), v.safeInteger(), v.minValue(0)),
37
38
  state: runStateSchema,
38
- next_at: z.number().int().nonnegative(),
39
- attempt: z.number().int().nonnegative(),
40
- error: z.string().nullable(),
39
+ next_at: v.pipe(v.number(), v.safeInteger(), v.minValue(0)),
40
+ attempt: v.pipe(v.number(), v.safeInteger(), v.minValue(0)),
41
+ error: v.nullable(v.string()),
41
42
  });
42
- const timeRowSchema = z.object({
43
- scheduled_time: z.number().int().nonnegative(),
43
+ const timeRowSchema = v.object({
44
+ scheduled_time: v.pipe(v.number(), v.safeInteger(), v.minValue(0)),
44
45
  });
45
- const dueRowSchema = z.object({
46
- scheduled_time: z.number().int().nonnegative(),
47
- due_at: z.number().int().nonnegative(),
46
+ const dueRowSchema = v.object({
47
+ scheduled_time: v.pipe(v.number(), v.safeInteger(), v.minValue(0)),
48
+ due_at: v.pipe(v.number(), v.safeInteger(), v.minValue(0)),
48
49
  });
49
- const timedRowSchema = z.object({
50
- scheduled_time: z.number().int().nonnegative(),
51
- next_at: z.number().int().nonnegative(),
50
+ const timedRowSchema = v.object({
51
+ scheduled_time: v.pipe(v.number(), v.safeInteger(), v.minValue(0)),
52
+ next_at: v.pipe(v.number(), v.safeInteger(), v.minValue(0)),
52
53
  });
53
- const serializedErrorSchema = z.object({
54
- name: z.string(),
55
- message: z.string(),
54
+ const serializedErrorSchema = v.object({
55
+ name: v.string(),
56
+ message: v.string(),
56
57
  });
57
- const readSchedule = (sql) => scheduleRowSchema.optional().parse(sql
58
+ const readSchedule = (sql, channel) => v.parse(v.optional(scheduleRowSchema), sql
58
59
  .exec(`SELECT
59
60
  version,
60
61
  expression,
61
62
  next_at,
62
63
  jitter_ms
63
64
  FROM durability_schedule
64
- WHERE id = 1`)
65
+ WHERE channel = ? AND id = 1`, channel)
65
66
  .toArray()[0]);
66
- const writeSchedule = (sql, schedule) => {
67
+ const writeSchedule = (sql, channel, schedule) => {
67
68
  sql.exec(`INSERT INTO durability_schedule (
69
+ channel,
68
70
  id,
69
71
  version,
70
72
  expression,
71
73
  next_at,
72
74
  jitter_ms
73
75
  )
74
- VALUES (1, ?, ?, ?, ?)
75
- ON CONFLICT (id) DO UPDATE SET
76
+ VALUES (?, 1, ?, ?, ?, ?)
77
+ ON CONFLICT (channel, id) DO UPDATE SET
76
78
  version = excluded.version,
77
79
  expression = excluded.expression,
78
80
  next_at = excluded.next_at,
79
- jitter_ms = excluded.jitter_ms`, schedule.version, schedule.expression, schedule.next_at, schedule.jitter_ms);
81
+ jitter_ms = excluded.jitter_ms`, channel, schedule.version, schedule.expression, schedule.next_at, schedule.jitter_ms);
80
82
  };
81
83
  const firesAt = (schedule) => schedule === undefined || schedule.next_at === null
82
84
  ? undefined
83
85
  : schedule.next_at + schedule.jitter_ms;
84
- const scheduledTimes = (cursor) => timeRowSchema
85
- .array()
86
- .parse(cursor.toArray())
86
+ const scheduledTimes = (cursor) => v
87
+ .parse(v.array(timeRowSchema), cursor.toArray())
87
88
  .map((row) => row.scheduled_time);
88
89
  const outcomeOf = (row) => row.state === 'errored'
89
90
  ? {
90
91
  status: 'errored',
91
- error: serializedErrorSchema.parse(JSON.parse(row.error ?? '{}')),
92
+ error: v.parse(serializedErrorSchema, JSON.parse(row.error ?? '{}')),
92
93
  }
93
94
  : { status: 'complete' };
94
95
  const assertNonNegative = (name, value) => {
@@ -137,9 +138,9 @@ const deadline = async (work, timeoutMs, onTimeout) => {
137
138
  }
138
139
  };
139
140
  /**
140
- * Experimental. One recurring schedule per Durable Object whose ticks start
141
- * individually tracked, overlapping runs and report each run's outcome once,
142
- * keeping a run's row only until its outcome is delivered.
141
+ * Experimental. One recurring schedule per channel of a Durable Object whose
142
+ * ticks start individually tracked, overlapping runs and report each run's
143
+ * outcome once, keeping a run's row only until its outcome is delivered.
143
144
  *
144
145
  * A tick inserts its run in the transaction that advances the stored next
145
146
  * tick, so a tick fires at most once without retaining finished runs. Missed
@@ -149,6 +150,7 @@ export class DurabilitySchedule {
149
150
  constructor(config) {
150
151
  _DurabilitySchedule_instances.add(this);
151
152
  _DurabilitySchedule_engine.set(this, void 0);
153
+ _DurabilitySchedule_channel.set(this, void 0);
152
154
  _DurabilitySchedule_nextOccurrence.set(this, void 0);
153
155
  _DurabilitySchedule_run.set(this, void 0);
154
156
  _DurabilitySchedule_onOutcome.set(this, void 0);
@@ -158,6 +160,7 @@ export class DurabilitySchedule {
158
160
  _DurabilitySchedule_maxOutcomeAttempts.set(this, void 0);
159
161
  _DurabilitySchedule_delay.set(this, void 0);
160
162
  _DurabilitySchedule_keyPrefix.set(this, void 0);
163
+ _DurabilitySchedule_keySuffix.set(this, void 0);
161
164
  _DurabilitySchedule_emit.set(this, void 0);
162
165
  /** Runs holding a slot: marked running and not yet settled in this instance. */
163
166
  _DurabilitySchedule_active.set(this, new Set());
@@ -166,6 +169,7 @@ export class DurabilitySchedule {
166
169
  _DurabilitySchedule_loop.set(this, void 0);
167
170
  _DurabilitySchedule_woken.set(this, false);
168
171
  _DurabilitySchedule_wakeSleeper.set(this, void 0);
172
+ __classPrivateFieldSet(this, _DurabilitySchedule_channel, assertChannel('DurabilitySchedule', config.channel ?? defaultChannel), "f");
169
173
  for (const name of ['nextOccurrence', 'run', 'onOutcome']) {
170
174
  if (typeof config[name] !== 'function') {
171
175
  throw new TypeError(`Schedule requires a ${name} function`);
@@ -187,10 +191,18 @@ export class DurabilitySchedule {
187
191
  __classPrivateFieldSet(this, _DurabilitySchedule_engine, engineFor(config), "f");
188
192
  const objectId = __classPrivateFieldGet(this, _DurabilitySchedule_engine, "f").objectId();
189
193
  __classPrivateFieldSet(this, _DurabilitySchedule_keyPrefix, objectId === undefined ? '' : `${objectId}:`, "f");
194
+ // Default keys end in a digit and named keys in a quote, so the two never
195
+ // meet, and the default channel keeps the keys it had before channels.
196
+ __classPrivateFieldSet(this, _DurabilitySchedule_keySuffix, __classPrivateFieldGet(this, _DurabilitySchedule_channel, "f") === defaultChannel
197
+ ? ''
198
+ : `:${JSON.stringify(__classPrivateFieldGet(this, _DurabilitySchedule_channel, "f"))}`, "f");
190
199
  __classPrivateFieldSet(this, _DurabilitySchedule_emit, traceLifecycle(__classPrivateFieldGet(this, _DurabilitySchedule_engine, "f").emitter(config.onLifecycleEvent)), "f");
191
200
  __classPrivateFieldGet(this, _DurabilitySchedule_engine, "f").migrateSchema('schedule', durabilityScheduleMigrations);
192
- __classPrivateFieldGet(this, _DurabilitySchedule_engine, "f").register({
201
+ __classPrivateFieldGet(this, _DurabilitySchedule_engine, "f").registerChannel({
193
202
  table: runsTable,
203
+ channelTables: ['durability_schedule'],
204
+ channel: __classPrivateFieldGet(this, _DurabilitySchedule_channel, "f"),
205
+ helper: 'DurabilitySchedule',
194
206
  runDue: () => __classPrivateFieldGet(this, _DurabilitySchedule_instances, "m", _DurabilitySchedule_hold).call(this),
195
207
  nextPendingAt: (sql) => __classPrivateFieldGet(this, _DurabilitySchedule_instances, "m", _DurabilitySchedule_nextPendingAt).call(this, sql),
196
208
  holding: () => __classPrivateFieldGet(this, _DurabilitySchedule_loop, "f") !== undefined,
@@ -204,7 +216,7 @@ export class DurabilitySchedule {
204
216
  }
205
217
  /** The stored schedule, or `undefined` when none is set or it was cancelled. */
206
218
  get() {
207
- const stored = readSchedule(__classPrivateFieldGet(this, _DurabilitySchedule_engine, "f").sql);
219
+ const stored = readSchedule(__classPrivateFieldGet(this, _DurabilitySchedule_engine, "f").sql, __classPrivateFieldGet(this, _DurabilitySchedule_channel, "f"));
208
220
  if (stored === undefined || stored.expression === null) {
209
221
  return undefined;
210
222
  }
@@ -230,12 +242,12 @@ export class DurabilitySchedule {
230
242
  const jitterMs = pickJitter(definition.jitterMs);
231
243
  // Even a no-op transaction reconciles the physical alarm.
232
244
  const applied = await __classPrivateFieldGet(this, _DurabilitySchedule_engine, "f").transaction((sql) => {
233
- const stored = readSchedule(sql);
245
+ const stored = readSchedule(sql, __classPrivateFieldGet(this, _DurabilitySchedule_channel, "f"));
234
246
  if (stored !== undefined && stored.version >= version) {
235
247
  return false;
236
248
  }
237
249
  const nextAt = __classPrivateFieldGet(this, _DurabilitySchedule_instances, "m", _DurabilitySchedule_nextAfter).call(this, expression, Date.now());
238
- writeSchedule(sql, {
250
+ writeSchedule(sql, __classPrivateFieldGet(this, _DurabilitySchedule_channel, "f"), {
239
251
  version,
240
252
  expression,
241
253
  next_at: nextAt ?? null,
@@ -257,7 +269,7 @@ export class DurabilitySchedule {
257
269
  assertNonNegative('Schedule version', version);
258
270
  }
259
271
  return __classPrivateFieldGet(this, _DurabilitySchedule_engine, "f").transaction((sql) => {
260
- const stored = readSchedule(sql);
272
+ const stored = readSchedule(sql, __classPrivateFieldGet(this, _DurabilitySchedule_channel, "f"));
261
273
  const live = stored !== undefined && stored.expression !== null;
262
274
  if (version === undefined && !live) {
263
275
  return false;
@@ -267,7 +279,7 @@ export class DurabilitySchedule {
267
279
  stored.version > version) {
268
280
  return false;
269
281
  }
270
- writeSchedule(sql, {
282
+ writeSchedule(sql, __classPrivateFieldGet(this, _DurabilitySchedule_channel, "f"), {
271
283
  version: version ?? stored?.version ?? 0,
272
284
  expression: null,
273
285
  next_at: null,
@@ -277,11 +289,10 @@ export class DurabilitySchedule {
277
289
  });
278
290
  }
279
291
  }
280
- _DurabilitySchedule_engine = new WeakMap(), _DurabilitySchedule_nextOccurrence = new WeakMap(), _DurabilitySchedule_run = new WeakMap(), _DurabilitySchedule_onOutcome = new WeakMap(), _DurabilitySchedule_maxConcurrentRuns = new WeakMap(), _DurabilitySchedule_runTimeoutMs = new WeakMap(), _DurabilitySchedule_outcomeTimeoutMs = new WeakMap(), _DurabilitySchedule_maxOutcomeAttempts = new WeakMap(), _DurabilitySchedule_delay = new WeakMap(), _DurabilitySchedule_keyPrefix = new WeakMap(), _DurabilitySchedule_emit = new WeakMap(), _DurabilitySchedule_active = new WeakMap(), _DurabilitySchedule_delivering = new WeakMap(), _DurabilitySchedule_loop = new WeakMap(), _DurabilitySchedule_woken = new WeakMap(), _DurabilitySchedule_wakeSleeper = new WeakMap(), _DurabilitySchedule_instances = new WeakSet(), _DurabilitySchedule_nextPendingAt = function _DurabilitySchedule_nextPendingAt(sql) {
281
- const rows = timedRowSchema
282
- .array()
283
- .parse(sql
284
- .exec('SELECT scheduled_time, next_at FROM durability_schedule_runs')
292
+ _DurabilitySchedule_engine = new WeakMap(), _DurabilitySchedule_channel = new WeakMap(), _DurabilitySchedule_nextOccurrence = new WeakMap(), _DurabilitySchedule_run = new WeakMap(), _DurabilitySchedule_onOutcome = new WeakMap(), _DurabilitySchedule_maxConcurrentRuns = new WeakMap(), _DurabilitySchedule_runTimeoutMs = new WeakMap(), _DurabilitySchedule_outcomeTimeoutMs = new WeakMap(), _DurabilitySchedule_maxOutcomeAttempts = new WeakMap(), _DurabilitySchedule_delay = new WeakMap(), _DurabilitySchedule_keyPrefix = new WeakMap(), _DurabilitySchedule_keySuffix = new WeakMap(), _DurabilitySchedule_emit = new WeakMap(), _DurabilitySchedule_active = new WeakMap(), _DurabilitySchedule_delivering = new WeakMap(), _DurabilitySchedule_loop = new WeakMap(), _DurabilitySchedule_woken = new WeakMap(), _DurabilitySchedule_wakeSleeper = new WeakMap(), _DurabilitySchedule_instances = new WeakSet(), _DurabilitySchedule_nextPendingAt = function _DurabilitySchedule_nextPendingAt(sql) {
293
+ const rows = v.parse(v.array(timedRowSchema), sql
294
+ .exec(`SELECT scheduled_time, next_at FROM durability_schedule_runs
295
+ WHERE channel = ?`, __classPrivateFieldGet(this, _DurabilitySchedule_channel, "f"))
285
296
  .toArray());
286
297
  const held = [];
287
298
  const pending = [];
@@ -294,7 +305,7 @@ _DurabilitySchedule_engine = new WeakMap(), _DurabilitySchedule_nextOccurrence =
294
305
  pending.push(row.next_at);
295
306
  }
296
307
  }
297
- const tick = firesAt(readSchedule(sql));
308
+ const tick = firesAt(readSchedule(sql, __classPrivateFieldGet(this, _DurabilitySchedule_channel, "f")));
298
309
  if (tick !== undefined) {
299
310
  pending.push(tick);
300
311
  }
@@ -312,7 +323,7 @@ _DurabilitySchedule_engine = new WeakMap(), _DurabilitySchedule_nextOccurrence =
312
323
  }
313
324
  return next;
314
325
  }, _DurabilitySchedule_idempotencyKey = function _DurabilitySchedule_idempotencyKey(scheduledTime) {
315
- return `${__classPrivateFieldGet(this, _DurabilitySchedule_keyPrefix, "f")}${scheduledTime}`;
326
+ return `${__classPrivateFieldGet(this, _DurabilitySchedule_keyPrefix, "f")}${scheduledTime}${__classPrivateFieldGet(this, _DurabilitySchedule_keySuffix, "f")}`;
316
327
  }, _DurabilitySchedule_describe = function _DurabilitySchedule_describe(row) {
317
328
  return {
318
329
  scheduledTime: row.scheduled_time,
@@ -388,15 +399,14 @@ _DurabilitySchedule_engine = new WeakMap(), _DurabilitySchedule_nextOccurrence =
388
399
  }
389
400
  }, _DurabilitySchedule_nextWakeAt = function _DurabilitySchedule_nextWakeAt() {
390
401
  const sql = __classPrivateFieldGet(this, _DurabilitySchedule_engine, "f").sql;
391
- const times = runRowSchema
392
- .array()
393
- .parse(sql
402
+ const times = v
403
+ .parse(v.array(runRowSchema), sql
394
404
  .exec(`SELECT * FROM durability_schedule_runs
395
- WHERE state IN ('complete', 'errored')`)
405
+ WHERE channel = ? AND state IN ('complete', 'errored')`, __classPrivateFieldGet(this, _DurabilitySchedule_channel, "f"))
396
406
  .toArray())
397
407
  .filter((row) => !__classPrivateFieldGet(this, _DurabilitySchedule_delivering, "f").has(row.scheduled_time))
398
408
  .map((row) => row.next_at);
399
- const tick = firesAt(readSchedule(sql));
409
+ const tick = firesAt(readSchedule(sql, __classPrivateFieldGet(this, _DurabilitySchedule_channel, "f")));
400
410
  if (tick !== undefined) {
401
411
  times.push(tick);
402
412
  }
@@ -408,7 +418,7 @@ _DurabilitySchedule_engine = new WeakMap(), _DurabilitySchedule_nextOccurrence =
408
418
  */
409
419
  async function _DurabilitySchedule_interruptOrphans() {
410
420
  const orphans = (sql) => scheduledTimes(sql.exec(`SELECT scheduled_time FROM durability_schedule_runs
411
- WHERE state = 'running'`)).filter((time) => !__classPrivateFieldGet(this, _DurabilitySchedule_active, "f").has(time));
421
+ WHERE channel = ? AND state = 'running'`, __classPrivateFieldGet(this, _DurabilitySchedule_channel, "f"))).filter((time) => !__classPrivateFieldGet(this, _DurabilitySchedule_active, "f").has(time));
412
422
  if (orphans(__classPrivateFieldGet(this, _DurabilitySchedule_engine, "f").sql).length === 0) {
413
423
  return;
414
424
  }
@@ -419,7 +429,7 @@ async function _DurabilitySchedule_interruptOrphans() {
419
429
  for (const time of times) {
420
430
  sql.exec(`UPDATE durability_schedule_runs
421
431
  SET state = 'errored', error = ?, next_at = ?, attempt = 0
422
- WHERE scheduled_time = ?`, JSON.stringify(error), now, time);
432
+ WHERE channel = ? AND scheduled_time = ?`, JSON.stringify(error), now, __classPrivateFieldGet(this, _DurabilitySchedule_channel, "f"), time);
423
433
  }
424
434
  return times;
425
435
  });
@@ -432,12 +442,12 @@ async function _DurabilitySchedule_interruptOrphans() {
432
442
  });
433
443
  }
434
444
  }, _DurabilitySchedule_tick = async function _DurabilitySchedule_tick() {
435
- const dueAt = firesAt(readSchedule(__classPrivateFieldGet(this, _DurabilitySchedule_engine, "f").sql));
445
+ const dueAt = firesAt(readSchedule(__classPrivateFieldGet(this, _DurabilitySchedule_engine, "f").sql, __classPrivateFieldGet(this, _DurabilitySchedule_channel, "f")));
436
446
  if (dueAt === undefined || dueAt > Date.now()) {
437
447
  return;
438
448
  }
439
449
  const due = await __classPrivateFieldGet(this, _DurabilitySchedule_instances, "m", _DurabilitySchedule_reserveSlots).call(this, (sql, free) => {
440
- const schedule = readSchedule(sql);
450
+ const schedule = readSchedule(sql, __classPrivateFieldGet(this, _DurabilitySchedule_channel, "f"));
441
451
  const now = Date.now();
442
452
  if (schedule === undefined ||
443
453
  schedule.expression === null ||
@@ -449,14 +459,14 @@ async function _DurabilitySchedule_interruptOrphans() {
449
459
  // Searching from nominal times keeps the offset from drifting; ticks
450
460
  // whose firing time already passed collapse into this run.
451
461
  const nextAt = __classPrivateFieldGet(this, _DurabilitySchedule_instances, "m", _DurabilitySchedule_nextAfter).call(this, schedule.expression, Math.max(scheduledTime, now - schedule.jitter_ms));
452
- sql.exec('UPDATE durability_schedule SET next_at = ? WHERE id = 1', nextAt ?? null);
462
+ sql.exec('UPDATE durability_schedule SET next_at = ? WHERE channel = ? AND id = 1', nextAt ?? null, __classPrivateFieldGet(this, _DurabilitySchedule_channel, "f"));
453
463
  const queued = free <= 0;
454
- const [row] = dueRowSchema.array().parse(sql
464
+ const [row] = v.parse(v.array(dueRowSchema), sql
455
465
  .exec(`INSERT INTO durability_schedule_runs
456
- (scheduled_time, due_at, state, next_at)
457
- VALUES (?, ?, ?, ?)
466
+ (channel, scheduled_time, due_at, state, next_at)
467
+ VALUES (?, ?, ?, ?, ?)
458
468
  ON CONFLICT DO NOTHING
459
- RETURNING scheduled_time, due_at`, scheduledTime, scheduledTime + schedule.jitter_ms, queued ? 'queued' : 'running', queued ? scheduledTime : now)
469
+ RETURNING scheduled_time, due_at`, __classPrivateFieldGet(this, _DurabilitySchedule_channel, "f"), scheduledTime, scheduledTime + schedule.jitter_ms, queued ? 'queued' : 'running', queued ? scheduledTime : now)
460
470
  .toArray());
461
471
  if (row === undefined) {
462
472
  return { reserve: [], result: undefined };
@@ -482,7 +492,9 @@ async function _DurabilitySchedule_interruptOrphans() {
482
492
  return;
483
493
  }
484
494
  const queued = __classPrivateFieldGet(this, _DurabilitySchedule_engine, "f").sql
485
- .exec("SELECT 1 FROM durability_schedule_runs WHERE state = 'queued' LIMIT 1")
495
+ .exec(`SELECT 1 FROM durability_schedule_runs
496
+ WHERE channel = ? AND state = 'queued'
497
+ LIMIT 1`, __classPrivateFieldGet(this, _DurabilitySchedule_channel, "f"))
486
498
  .toArray();
487
499
  if (queued.length === 0) {
488
500
  return;
@@ -490,16 +502,16 @@ async function _DurabilitySchedule_interruptOrphans() {
490
502
  const started = await __classPrivateFieldGet(this, _DurabilitySchedule_instances, "m", _DurabilitySchedule_reserveSlots).call(this, (sql, free) => {
491
503
  const rows = free <= 0
492
504
  ? []
493
- : dueRowSchema.array().parse(sql
505
+ : v.parse(v.array(dueRowSchema), sql
494
506
  .exec(`UPDATE durability_schedule_runs
495
507
  SET state = 'running', next_at = ?
496
- WHERE scheduled_time IN (
508
+ WHERE channel = ? AND scheduled_time IN (
497
509
  SELECT scheduled_time FROM durability_schedule_runs
498
- WHERE state = 'queued'
510
+ WHERE channel = ? AND state = 'queued'
499
511
  ORDER BY scheduled_time
500
512
  LIMIT ?
501
513
  )
502
- RETURNING scheduled_time, due_at`, Date.now(), free)
514
+ RETURNING scheduled_time, due_at`, Date.now(), __classPrivateFieldGet(this, _DurabilitySchedule_channel, "f"), __classPrivateFieldGet(this, _DurabilitySchedule_channel, "f"), free)
503
515
  .toArray());
504
516
  return {
505
517
  reserve: rows.map((row) => row.scheduled_time),
@@ -564,8 +576,8 @@ async function _DurabilitySchedule_reserveSlots(mark) {
564
576
  const error = outcome.status === 'errored' ? outcome.error : undefined;
565
577
  const recorded = await __classPrivateFieldGet(this, _DurabilitySchedule_engine, "f").transaction((sql) => scheduledTimes(sql.exec(`UPDATE durability_schedule_runs
566
578
  SET state = ?, error = ?, next_at = ?, attempt = 0
567
- WHERE scheduled_time = ? AND state = 'running'
568
- RETURNING scheduled_time`, outcome.status, error === undefined ? null : JSON.stringify(error), Date.now(), run.scheduledTime)).length > 0);
579
+ WHERE channel = ? AND scheduled_time = ? AND state = 'running'
580
+ RETURNING scheduled_time`, outcome.status, error === undefined ? null : JSON.stringify(error), Date.now(), __classPrivateFieldGet(this, _DurabilitySchedule_channel, "f"), run.scheduledTime)).length > 0);
569
581
  if (!recorded) {
570
582
  return;
571
583
  }
@@ -579,9 +591,9 @@ async function _DurabilitySchedule_reserveSlots(mark) {
579
591
  });
580
592
  __classPrivateFieldGet(this, _DurabilitySchedule_instances, "m", _DurabilitySchedule_deliver).call(this, run, outcome, 1);
581
593
  }, _DurabilitySchedule_deliverDue = function _DurabilitySchedule_deliverDue() {
582
- const due = runRowSchema.array().parse(__classPrivateFieldGet(this, _DurabilitySchedule_engine, "f").sql
594
+ const due = v.parse(v.array(runRowSchema), __classPrivateFieldGet(this, _DurabilitySchedule_engine, "f").sql
583
595
  .exec(`SELECT * FROM durability_schedule_runs
584
- WHERE state IN ('complete', 'errored') AND next_at <= ?`, Date.now())
596
+ WHERE channel = ? AND state IN ('complete', 'errored') AND next_at <= ?`, __classPrivateFieldGet(this, _DurabilitySchedule_channel, "f"), Date.now())
585
597
  .toArray());
586
598
  for (const row of due) {
587
599
  __classPrivateFieldGet(this, _DurabilitySchedule_instances, "m", _DurabilitySchedule_deliver).call(this, __classPrivateFieldGet(this, _DurabilitySchedule_instances, "m", _DurabilitySchedule_describe).call(this, row), outcomeOf(row), row.attempt + 1);
@@ -607,13 +619,15 @@ async function _DurabilitySchedule_reserveSlots(mark) {
607
619
  return;
608
620
  }
609
621
  await __classPrivateFieldGet(this, _DurabilitySchedule_engine, "f").transaction((sql) => {
610
- sql.exec('DELETE FROM durability_schedule_runs WHERE scheduled_time = ?', run.scheduledTime);
622
+ sql.exec(`DELETE FROM durability_schedule_runs
623
+ WHERE channel = ? AND scheduled_time = ?`, __classPrivateFieldGet(this, _DurabilitySchedule_channel, "f"), run.scheduledTime);
611
624
  });
612
625
  }, _DurabilitySchedule_failDelivery = async function _DurabilitySchedule_failDelivery(run, attempt, failure) {
613
626
  const error = serializeError(failure);
614
627
  if (attempt >= __classPrivateFieldGet(this, _DurabilitySchedule_maxOutcomeAttempts, "f")) {
615
628
  await __classPrivateFieldGet(this, _DurabilitySchedule_engine, "f").transaction((sql) => {
616
- sql.exec('DELETE FROM durability_schedule_runs WHERE scheduled_time = ?', run.scheduledTime);
629
+ sql.exec(`DELETE FROM durability_schedule_runs
630
+ WHERE channel = ? AND scheduled_time = ?`, __classPrivateFieldGet(this, _DurabilitySchedule_channel, "f"), run.scheduledTime);
617
631
  });
618
632
  reportFailure('durability.schedule.outcome_dead_lettered', { scheduledTime: run.scheduledTime, attempt }, failure);
619
633
  __classPrivateFieldGet(this, _DurabilitySchedule_emit, "f").call(this, {
@@ -627,7 +641,7 @@ async function _DurabilitySchedule_reserveSlots(mark) {
627
641
  const nextAttemptAt = Date.now() + __classPrivateFieldGet(this, _DurabilitySchedule_instances, "m", _DurabilitySchedule_retryDelay).call(this, attempt);
628
642
  await __classPrivateFieldGet(this, _DurabilitySchedule_engine, "f").transaction((sql) => {
629
643
  sql.exec(`UPDATE durability_schedule_runs SET attempt = ?, next_at = ?
630
- WHERE scheduled_time = ?`, attempt, nextAttemptAt, run.scheduledTime);
644
+ WHERE channel = ? AND scheduled_time = ?`, attempt, nextAttemptAt, __classPrivateFieldGet(this, _DurabilitySchedule_channel, "f"), run.scheduledTime);
631
645
  });
632
646
  __classPrivateFieldGet(this, _DurabilitySchedule_emit, "f").call(this, {
633
647
  ...__classPrivateFieldGet(this, _DurabilitySchedule_instances, "m", _DurabilitySchedule_entity).call(this, run.scheduledTime),
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Ordered SQLite migrations for the experimental schedule. Applied
3
+ * automatically on construction.
4
+ */
5
+ export declare const durabilityScheduleMigrations: {
6
+ name: string;
7
+ up: string;
8
+ down: string;
9
+ }[];
@@ -0,0 +1,118 @@
1
+ /**
2
+ * Ordered SQLite migrations for the experimental schedule. Applied
3
+ * automatically on construction.
4
+ */
5
+ export const durabilityScheduleMigrations = [
6
+ {
7
+ name: 'durability_0013_create_schedule',
8
+ // INTEGER PRIMARY KEY aliases the rowid, so each table is a single b-tree
9
+ // with no secondary index for per-run writes to maintain.
10
+ up: `
11
+ CREATE TABLE IF NOT EXISTS durability_schedule (
12
+ id INTEGER PRIMARY KEY CHECK (id = 1),
13
+ version INTEGER NOT NULL,
14
+ expression TEXT,
15
+ next_at INTEGER
16
+ );
17
+ CREATE TABLE IF NOT EXISTS durability_schedule_runs (
18
+ scheduled_time INTEGER PRIMARY KEY,
19
+ state TEXT NOT NULL
20
+ CHECK (state IN ('queued', 'running', 'complete', 'errored')),
21
+ next_at INTEGER NOT NULL,
22
+ attempt INTEGER NOT NULL DEFAULT 0,
23
+ error TEXT
24
+ );
25
+ `,
26
+ down: `
27
+ DROP TABLE IF EXISTS durability_schedule_runs;
28
+ DROP TABLE IF EXISTS durability_schedule;
29
+ `,
30
+ },
31
+ {
32
+ name: 'durability_0014_add_schedule_jitter',
33
+ up: `
34
+ ALTER TABLE durability_schedule ADD COLUMN jitter_ms INTEGER NOT NULL DEFAULT 0;
35
+ ALTER TABLE durability_schedule_runs ADD COLUMN due_at INTEGER;
36
+ UPDATE durability_schedule_runs SET due_at = scheduled_time;
37
+ `,
38
+ down: `
39
+ ALTER TABLE durability_schedule_runs DROP COLUMN due_at;
40
+ ALTER TABLE durability_schedule DROP COLUMN jitter_ms;
41
+ `,
42
+ },
43
+ {
44
+ name: 'durability_0018_schedule_channels',
45
+ // WITHOUT ROWID keeps each table a single b-tree under its composite key,
46
+ // so per-run writes still maintain no secondary index.
47
+ up: `
48
+ ALTER TABLE durability_schedule RENAME TO durability_schedule_before_channels;
49
+ CREATE TABLE durability_schedule (
50
+ channel TEXT NOT NULL DEFAULT 'default',
51
+ id INTEGER NOT NULL CHECK (id = 1),
52
+ version INTEGER NOT NULL,
53
+ expression TEXT,
54
+ next_at INTEGER,
55
+ jitter_ms INTEGER NOT NULL DEFAULT 0,
56
+ PRIMARY KEY (channel, id)
57
+ ) WITHOUT ROWID;
58
+ INSERT INTO durability_schedule
59
+ (channel, id, version, expression, next_at, jitter_ms)
60
+ SELECT 'default', id, version, expression, next_at, jitter_ms
61
+ FROM durability_schedule_before_channels;
62
+ DROP TABLE durability_schedule_before_channels;
63
+ ALTER TABLE durability_schedule_runs RENAME TO durability_schedule_runs_before_channels;
64
+ CREATE TABLE durability_schedule_runs (
65
+ channel TEXT NOT NULL DEFAULT 'default',
66
+ scheduled_time INTEGER NOT NULL,
67
+ state TEXT NOT NULL
68
+ CHECK (state IN ('queued', 'running', 'complete', 'errored')),
69
+ next_at INTEGER NOT NULL,
70
+ attempt INTEGER NOT NULL DEFAULT 0,
71
+ error TEXT,
72
+ due_at INTEGER,
73
+ PRIMARY KEY (channel, scheduled_time)
74
+ ) WITHOUT ROWID;
75
+ INSERT INTO durability_schedule_runs
76
+ (channel, scheduled_time, state, next_at, attempt, error, due_at)
77
+ SELECT 'default', scheduled_time, state, next_at, attempt, error, due_at
78
+ FROM durability_schedule_runs_before_channels;
79
+ DROP TABLE durability_schedule_runs_before_channels;
80
+ `,
81
+ down: `
82
+ CREATE TABLE durability_schedule_channel_guard (
83
+ channel TEXT CONSTRAINT cannot_downgrade_nondefault_channels CHECK (channel = 'default')
84
+ );
85
+ INSERT INTO durability_schedule_channel_guard
86
+ SELECT channel FROM durability_schedule
87
+ UNION SELECT channel FROM durability_schedule_runs;
88
+ DROP TABLE durability_schedule_channel_guard;
89
+ ALTER TABLE durability_schedule RENAME TO durability_schedule_with_channels;
90
+ CREATE TABLE durability_schedule (
91
+ id INTEGER PRIMARY KEY CHECK (id = 1),
92
+ version INTEGER NOT NULL,
93
+ expression TEXT,
94
+ next_at INTEGER,
95
+ jitter_ms INTEGER NOT NULL DEFAULT 0
96
+ );
97
+ INSERT INTO durability_schedule (id, version, expression, next_at, jitter_ms)
98
+ SELECT id, version, expression, next_at, jitter_ms
99
+ FROM durability_schedule_with_channels;
100
+ DROP TABLE durability_schedule_with_channels;
101
+ ALTER TABLE durability_schedule_runs RENAME TO durability_schedule_runs_with_channels;
102
+ CREATE TABLE durability_schedule_runs (
103
+ scheduled_time INTEGER PRIMARY KEY,
104
+ state TEXT NOT NULL
105
+ CHECK (state IN ('queued', 'running', 'complete', 'errored')),
106
+ next_at INTEGER NOT NULL,
107
+ attempt INTEGER NOT NULL DEFAULT 0,
108
+ error TEXT,
109
+ due_at INTEGER
110
+ );
111
+ INSERT INTO durability_schedule_runs
112
+ (scheduled_time, state, next_at, attempt, error, due_at)
113
+ SELECT scheduled_time, state, next_at, attempt, error, due_at
114
+ FROM durability_schedule_runs_with_channels;
115
+ DROP TABLE durability_schedule_runs_with_channels;
116
+ `,
117
+ },
118
+ ];