durability 5.1.0 → 5.2.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 (86) hide show
  1. package/README.md +145 -12
  2. package/dist/{durability-alarms.d.ts → alarms/index.d.ts} +13 -5
  3. package/dist/{durability-alarms.js → alarms/index.js} +69 -55
  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} +54 -46
  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} +15 -3
  16. package/dist/{log.js → log/index.js} +152 -124
  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} +14 -11
  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 +0 -612
  25. package/dist/{durability.d.ts → operations/index.d.ts} +13 -5
  26. package/dist/{durability.js → operations/index.js} +59 -47
  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} +16 -60
  31. package/dist/outbox/migrations.d.ts +9 -0
  32. package/dist/outbox/migrations.js +43 -0
  33. package/dist/{routing-client.js → routing/client.js} +1 -1
  34. package/dist/{routing.d.ts → routing/index.d.ts} +3 -3
  35. package/dist/{routing.js → routing/index.js} +3 -3
  36. package/dist/{load.d.ts → routing/load.d.ts} +1 -1
  37. package/dist/{schedule.d.ts → schedule/index.d.ts} +16 -8
  38. package/dist/{schedule.js → schedule/index.js} +65 -49
  39. package/dist/schedule/migrations.d.ts +9 -0
  40. package/dist/schedule/migrations.js +118 -0
  41. package/dist/{scheduler.d.ts → scheduler/index.d.ts} +75 -25
  42. package/dist/{scheduler.js → scheduler/index.js} +300 -63
  43. package/dist/{semaphore-client.d.ts → semaphore/client.d.ts} +1 -1
  44. package/dist/{semaphore-client.js → semaphore/client.js} +2 -2
  45. package/dist/{semaphore.d.ts → semaphore/index.d.ts} +10 -10
  46. package/dist/{semaphore.js → semaphore/index.js} +7 -7
  47. package/dist/{semaphore-leases.d.ts → semaphore/leases.d.ts} +17 -6
  48. package/dist/{semaphore-leases.js → semaphore/leases.js} +28 -12
  49. package/dist/semaphore/migrations.d.ts +18 -0
  50. package/dist/semaphore/migrations.js +444 -0
  51. package/dist/{semaphore-protocol.d.ts → semaphore/protocol.d.ts} +16 -8
  52. package/dist/{semaphore-protocol.js → semaphore/protocol.js} +37 -14
  53. package/dist/{semaphore-queue-store.d.ts → semaphore/queue-store.d.ts} +12 -6
  54. package/dist/{semaphore-queue-store.js → semaphore/queue-store.js} +69 -61
  55. package/dist/{semaphore-queue.d.ts → semaphore/queue.d.ts} +15 -5
  56. package/dist/{semaphore-queue.js → semaphore/queue.js} +105 -46
  57. package/dist/{semaphore-server.d.ts → semaphore/server.d.ts} +12 -4
  58. package/dist/{semaphore-server.js → semaphore/server.js} +51 -24
  59. package/dist/{semaphore-store.d.ts → semaphore/store.d.ts} +8 -3
  60. package/dist/{semaphore-store.js → semaphore/store.js} +35 -33
  61. package/dist/{client.d.ts → socket/client.d.ts} +3 -3
  62. package/dist/{client.js → socket/client.js} +4 -4
  63. package/dist/{socket.d.ts → socket/index.d.ts} +15 -4
  64. package/dist/{socket.js → socket/index.js} +66 -20
  65. package/dist/socket/migrations.d.ts +9 -0
  66. package/dist/socket/migrations.js +57 -0
  67. package/dist/{socket-protocol.d.ts → socket/protocol.d.ts} +1 -1
  68. package/dist/storage.d.ts +4 -0
  69. package/dist/storage.js +13 -6
  70. package/dist/{topology-client.d.ts → topology/client.d.ts} +2 -2
  71. package/dist/{topology-client.js → topology/client.js} +3 -3
  72. package/dist/{topology.d.ts → topology/index.d.ts} +17 -7
  73. package/dist/{topology.js → topology/index.js} +92 -58
  74. package/dist/topology/migrations.d.ts +10 -0
  75. package/dist/topology/migrations.js +138 -0
  76. package/dist/{tracker.d.ts → tracker/index.d.ts} +3 -3
  77. package/dist/{tracker.js → tracker/index.js} +2 -2
  78. package/package.json +11 -11
  79. /package/dist/{stored-message.js → fanout/stored-message.js} +0 -0
  80. /package/dist/{routing-client.d.ts → routing/client.d.ts} +0 -0
  81. /package/dist/{load.js → routing/load.js} +0 -0
  82. /package/dist/{socket-protocol.js → socket/protocol.js} +0 -0
  83. /package/dist/{topology-snapshot.d.ts → topology/snapshot.d.ts} +0 -0
  84. /package/dist/{topology-snapshot.js → topology/snapshot.js} +0 -0
  85. /package/dist/{tracked-source.d.ts → tracker/source.d.ts} +0 -0
  86. /package/dist/{tracked-source.js → tracker/source.js} +0 -0
@@ -1,4 +1,4 @@
1
- import type { SerializedError } from './errors.js';
1
+ import type { SerializedError } from '../errors.js';
2
2
  /** Completion counts and timings cover the same rolling observation window. */
3
3
  export type ProcessingLoad = {
4
4
  inFlight: number;
@@ -1,7 +1,7 @@
1
- import { type SerializedError } from './errors.js';
2
- import { type DurabilityMigrationResult } from './migrations.js';
3
- import { type DurabilityRetryOptions } from './policy.js';
4
- import { type SchedulerAttachment } from './scheduler.js';
1
+ import { type SerializedError } from '../errors.js';
2
+ import { type DurabilityMigrationResult } from '../migrations.js';
3
+ import { type DurabilityRetryOptions } from '../policy.js';
4
+ import { type SchedulerAttachment } from '../scheduler/index.js';
5
5
  /** A schedule as passed to {@link DurabilitySchedule.set}. */
6
6
  export type ScheduleDefinition = {
7
7
  /** Opaque to durability: only `nextOccurrence` interprets it. */
@@ -45,7 +45,8 @@ export type ScheduledRun = {
45
45
  dueAt: number;
46
46
  /**
47
47
  * `<objectId>:<scheduledTime>`, or the bare scheduled time when the context
48
- * has no object ID. A tick fires at most once, so the key is unique per run.
48
+ * has no object ID. A named channel appends `:` and its JSON-encoded name.
49
+ * A tick fires at most once per channel, so the key is unique per run.
49
50
  */
50
51
  idempotencyKey: string;
51
52
  };
@@ -101,6 +102,13 @@ export type DurabilityScheduleEvent = ScheduledRunEntity & ({
101
102
  error: SerializedError;
102
103
  });
103
104
  export type DurabilityScheduleConfig = SchedulerAttachment & {
105
+ /**
106
+ * Stable channel ID. Instances on one scheduler share storage, partitioned
107
+ * by channel; each has its own schedule, runs and hooks. A library should
108
+ * use its own channel so its schedule never meets the application's.
109
+ * Defaults to `default`.
110
+ */
111
+ channel?: string;
104
112
  /**
105
113
  * Returns the first tick strictly after `after`, or `undefined` for none.
106
114
  * Must be synchronous and deterministic; durability ships no cron parser.
@@ -124,9 +132,9 @@ export type DurabilityScheduleConfig = SchedulerAttachment & {
124
132
  onLifecycleEvent?: (event: DurabilityScheduleEvent) => void | Promise<void>;
125
133
  };
126
134
  /**
127
- * Experimental. One recurring schedule per Durable Object whose ticks start
128
- * individually tracked, overlapping runs and report each run's outcome once,
129
- * keeping a run's row only until its outcome is delivered.
135
+ * Experimental. One recurring schedule per channel of a Durable Object whose
136
+ * ticks start individually tracked, overlapping runs and report each run's
137
+ * outcome once, keeping a run's row only until its outcome is delivered.
130
138
  *
131
139
  * A tick inserts its run in the transaction that advances the stored next
132
140
  * tick, so a tick fires at most once without retaining finished runs. Missed
@@ -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;
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
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';
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',
@@ -54,29 +55,30 @@ const serializedErrorSchema = z.object({
54
55
  name: z.string(),
55
56
  message: z.string(),
56
57
  });
57
- const readSchedule = (sql) => scheduleRowSchema.optional().parse(sql
58
+ const readSchedule = (sql, channel) => scheduleRowSchema.optional().parse(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
@@ -137,9 +139,9 @@ const deadline = async (work, timeoutMs, onTimeout) => {
137
139
  }
138
140
  };
139
141
  /**
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.
142
+ * Experimental. One recurring schedule per channel of a Durable Object whose
143
+ * ticks start individually tracked, overlapping runs and report each run's
144
+ * outcome once, keeping a run's row only until its outcome is delivered.
143
145
  *
144
146
  * A tick inserts its run in the transaction that advances the stored next
145
147
  * tick, so a tick fires at most once without retaining finished runs. Missed
@@ -149,6 +151,7 @@ export class DurabilitySchedule {
149
151
  constructor(config) {
150
152
  _DurabilitySchedule_instances.add(this);
151
153
  _DurabilitySchedule_engine.set(this, void 0);
154
+ _DurabilitySchedule_channel.set(this, void 0);
152
155
  _DurabilitySchedule_nextOccurrence.set(this, void 0);
153
156
  _DurabilitySchedule_run.set(this, void 0);
154
157
  _DurabilitySchedule_onOutcome.set(this, void 0);
@@ -158,6 +161,7 @@ export class DurabilitySchedule {
158
161
  _DurabilitySchedule_maxOutcomeAttempts.set(this, void 0);
159
162
  _DurabilitySchedule_delay.set(this, void 0);
160
163
  _DurabilitySchedule_keyPrefix.set(this, void 0);
164
+ _DurabilitySchedule_keySuffix.set(this, void 0);
161
165
  _DurabilitySchedule_emit.set(this, void 0);
162
166
  /** Runs holding a slot: marked running and not yet settled in this instance. */
163
167
  _DurabilitySchedule_active.set(this, new Set());
@@ -166,6 +170,7 @@ export class DurabilitySchedule {
166
170
  _DurabilitySchedule_loop.set(this, void 0);
167
171
  _DurabilitySchedule_woken.set(this, false);
168
172
  _DurabilitySchedule_wakeSleeper.set(this, void 0);
173
+ __classPrivateFieldSet(this, _DurabilitySchedule_channel, assertChannel('DurabilitySchedule', config.channel ?? defaultChannel), "f");
169
174
  for (const name of ['nextOccurrence', 'run', 'onOutcome']) {
170
175
  if (typeof config[name] !== 'function') {
171
176
  throw new TypeError(`Schedule requires a ${name} function`);
@@ -187,10 +192,18 @@ export class DurabilitySchedule {
187
192
  __classPrivateFieldSet(this, _DurabilitySchedule_engine, engineFor(config), "f");
188
193
  const objectId = __classPrivateFieldGet(this, _DurabilitySchedule_engine, "f").objectId();
189
194
  __classPrivateFieldSet(this, _DurabilitySchedule_keyPrefix, objectId === undefined ? '' : `${objectId}:`, "f");
195
+ // Default keys end in a digit and named keys in a quote, so the two never
196
+ // meet, and the default channel keeps the keys it had before channels.
197
+ __classPrivateFieldSet(this, _DurabilitySchedule_keySuffix, __classPrivateFieldGet(this, _DurabilitySchedule_channel, "f") === defaultChannel
198
+ ? ''
199
+ : `:${JSON.stringify(__classPrivateFieldGet(this, _DurabilitySchedule_channel, "f"))}`, "f");
190
200
  __classPrivateFieldSet(this, _DurabilitySchedule_emit, traceLifecycle(__classPrivateFieldGet(this, _DurabilitySchedule_engine, "f").emitter(config.onLifecycleEvent)), "f");
191
201
  __classPrivateFieldGet(this, _DurabilitySchedule_engine, "f").migrateSchema('schedule', durabilityScheduleMigrations);
192
- __classPrivateFieldGet(this, _DurabilitySchedule_engine, "f").register({
202
+ __classPrivateFieldGet(this, _DurabilitySchedule_engine, "f").registerChannel({
193
203
  table: runsTable,
204
+ channelTables: ['durability_schedule'],
205
+ channel: __classPrivateFieldGet(this, _DurabilitySchedule_channel, "f"),
206
+ helper: 'DurabilitySchedule',
194
207
  runDue: () => __classPrivateFieldGet(this, _DurabilitySchedule_instances, "m", _DurabilitySchedule_hold).call(this),
195
208
  nextPendingAt: (sql) => __classPrivateFieldGet(this, _DurabilitySchedule_instances, "m", _DurabilitySchedule_nextPendingAt).call(this, sql),
196
209
  holding: () => __classPrivateFieldGet(this, _DurabilitySchedule_loop, "f") !== undefined,
@@ -204,7 +217,7 @@ export class DurabilitySchedule {
204
217
  }
205
218
  /** The stored schedule, or `undefined` when none is set or it was cancelled. */
206
219
  get() {
207
- const stored = readSchedule(__classPrivateFieldGet(this, _DurabilitySchedule_engine, "f").sql);
220
+ const stored = readSchedule(__classPrivateFieldGet(this, _DurabilitySchedule_engine, "f").sql, __classPrivateFieldGet(this, _DurabilitySchedule_channel, "f"));
208
221
  if (stored === undefined || stored.expression === null) {
209
222
  return undefined;
210
223
  }
@@ -230,12 +243,12 @@ export class DurabilitySchedule {
230
243
  const jitterMs = pickJitter(definition.jitterMs);
231
244
  // Even a no-op transaction reconciles the physical alarm.
232
245
  const applied = await __classPrivateFieldGet(this, _DurabilitySchedule_engine, "f").transaction((sql) => {
233
- const stored = readSchedule(sql);
246
+ const stored = readSchedule(sql, __classPrivateFieldGet(this, _DurabilitySchedule_channel, "f"));
234
247
  if (stored !== undefined && stored.version >= version) {
235
248
  return false;
236
249
  }
237
250
  const nextAt = __classPrivateFieldGet(this, _DurabilitySchedule_instances, "m", _DurabilitySchedule_nextAfter).call(this, expression, Date.now());
238
- writeSchedule(sql, {
251
+ writeSchedule(sql, __classPrivateFieldGet(this, _DurabilitySchedule_channel, "f"), {
239
252
  version,
240
253
  expression,
241
254
  next_at: nextAt ?? null,
@@ -257,7 +270,7 @@ export class DurabilitySchedule {
257
270
  assertNonNegative('Schedule version', version);
258
271
  }
259
272
  return __classPrivateFieldGet(this, _DurabilitySchedule_engine, "f").transaction((sql) => {
260
- const stored = readSchedule(sql);
273
+ const stored = readSchedule(sql, __classPrivateFieldGet(this, _DurabilitySchedule_channel, "f"));
261
274
  const live = stored !== undefined && stored.expression !== null;
262
275
  if (version === undefined && !live) {
263
276
  return false;
@@ -267,7 +280,7 @@ export class DurabilitySchedule {
267
280
  stored.version > version) {
268
281
  return false;
269
282
  }
270
- writeSchedule(sql, {
283
+ writeSchedule(sql, __classPrivateFieldGet(this, _DurabilitySchedule_channel, "f"), {
271
284
  version: version ?? stored?.version ?? 0,
272
285
  expression: null,
273
286
  next_at: null,
@@ -277,11 +290,10 @@ export class DurabilitySchedule {
277
290
  });
278
291
  }
279
292
  }
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')
293
+ _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) {
294
+ const rows = timedRowSchema.array().parse(sql
295
+ .exec(`SELECT scheduled_time, next_at FROM durability_schedule_runs
296
+ WHERE channel = ?`, __classPrivateFieldGet(this, _DurabilitySchedule_channel, "f"))
285
297
  .toArray());
286
298
  const held = [];
287
299
  const pending = [];
@@ -294,7 +306,7 @@ _DurabilitySchedule_engine = new WeakMap(), _DurabilitySchedule_nextOccurrence =
294
306
  pending.push(row.next_at);
295
307
  }
296
308
  }
297
- const tick = firesAt(readSchedule(sql));
309
+ const tick = firesAt(readSchedule(sql, __classPrivateFieldGet(this, _DurabilitySchedule_channel, "f")));
298
310
  if (tick !== undefined) {
299
311
  pending.push(tick);
300
312
  }
@@ -312,7 +324,7 @@ _DurabilitySchedule_engine = new WeakMap(), _DurabilitySchedule_nextOccurrence =
312
324
  }
313
325
  return next;
314
326
  }, _DurabilitySchedule_idempotencyKey = function _DurabilitySchedule_idempotencyKey(scheduledTime) {
315
- return `${__classPrivateFieldGet(this, _DurabilitySchedule_keyPrefix, "f")}${scheduledTime}`;
327
+ return `${__classPrivateFieldGet(this, _DurabilitySchedule_keyPrefix, "f")}${scheduledTime}${__classPrivateFieldGet(this, _DurabilitySchedule_keySuffix, "f")}`;
316
328
  }, _DurabilitySchedule_describe = function _DurabilitySchedule_describe(row) {
317
329
  return {
318
330
  scheduledTime: row.scheduled_time,
@@ -392,11 +404,11 @@ _DurabilitySchedule_engine = new WeakMap(), _DurabilitySchedule_nextOccurrence =
392
404
  .array()
393
405
  .parse(sql
394
406
  .exec(`SELECT * FROM durability_schedule_runs
395
- WHERE state IN ('complete', 'errored')`)
407
+ WHERE channel = ? AND state IN ('complete', 'errored')`, __classPrivateFieldGet(this, _DurabilitySchedule_channel, "f"))
396
408
  .toArray())
397
409
  .filter((row) => !__classPrivateFieldGet(this, _DurabilitySchedule_delivering, "f").has(row.scheduled_time))
398
410
  .map((row) => row.next_at);
399
- const tick = firesAt(readSchedule(sql));
411
+ const tick = firesAt(readSchedule(sql, __classPrivateFieldGet(this, _DurabilitySchedule_channel, "f")));
400
412
  if (tick !== undefined) {
401
413
  times.push(tick);
402
414
  }
@@ -408,7 +420,7 @@ _DurabilitySchedule_engine = new WeakMap(), _DurabilitySchedule_nextOccurrence =
408
420
  */
409
421
  async function _DurabilitySchedule_interruptOrphans() {
410
422
  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));
423
+ WHERE channel = ? AND state = 'running'`, __classPrivateFieldGet(this, _DurabilitySchedule_channel, "f"))).filter((time) => !__classPrivateFieldGet(this, _DurabilitySchedule_active, "f").has(time));
412
424
  if (orphans(__classPrivateFieldGet(this, _DurabilitySchedule_engine, "f").sql).length === 0) {
413
425
  return;
414
426
  }
@@ -419,7 +431,7 @@ async function _DurabilitySchedule_interruptOrphans() {
419
431
  for (const time of times) {
420
432
  sql.exec(`UPDATE durability_schedule_runs
421
433
  SET state = 'errored', error = ?, next_at = ?, attempt = 0
422
- WHERE scheduled_time = ?`, JSON.stringify(error), now, time);
434
+ WHERE channel = ? AND scheduled_time = ?`, JSON.stringify(error), now, __classPrivateFieldGet(this, _DurabilitySchedule_channel, "f"), time);
423
435
  }
424
436
  return times;
425
437
  });
@@ -432,12 +444,12 @@ async function _DurabilitySchedule_interruptOrphans() {
432
444
  });
433
445
  }
434
446
  }, _DurabilitySchedule_tick = async function _DurabilitySchedule_tick() {
435
- const dueAt = firesAt(readSchedule(__classPrivateFieldGet(this, _DurabilitySchedule_engine, "f").sql));
447
+ const dueAt = firesAt(readSchedule(__classPrivateFieldGet(this, _DurabilitySchedule_engine, "f").sql, __classPrivateFieldGet(this, _DurabilitySchedule_channel, "f")));
436
448
  if (dueAt === undefined || dueAt > Date.now()) {
437
449
  return;
438
450
  }
439
451
  const due = await __classPrivateFieldGet(this, _DurabilitySchedule_instances, "m", _DurabilitySchedule_reserveSlots).call(this, (sql, free) => {
440
- const schedule = readSchedule(sql);
452
+ const schedule = readSchedule(sql, __classPrivateFieldGet(this, _DurabilitySchedule_channel, "f"));
441
453
  const now = Date.now();
442
454
  if (schedule === undefined ||
443
455
  schedule.expression === null ||
@@ -449,14 +461,14 @@ async function _DurabilitySchedule_interruptOrphans() {
449
461
  // Searching from nominal times keeps the offset from drifting; ticks
450
462
  // whose firing time already passed collapse into this run.
451
463
  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);
464
+ sql.exec('UPDATE durability_schedule SET next_at = ? WHERE channel = ? AND id = 1', nextAt ?? null, __classPrivateFieldGet(this, _DurabilitySchedule_channel, "f"));
453
465
  const queued = free <= 0;
454
466
  const [row] = dueRowSchema.array().parse(sql
455
467
  .exec(`INSERT INTO durability_schedule_runs
456
- (scheduled_time, due_at, state, next_at)
457
- VALUES (?, ?, ?, ?)
468
+ (channel, scheduled_time, due_at, state, next_at)
469
+ VALUES (?, ?, ?, ?, ?)
458
470
  ON CONFLICT DO NOTHING
459
- RETURNING scheduled_time, due_at`, scheduledTime, scheduledTime + schedule.jitter_ms, queued ? 'queued' : 'running', queued ? scheduledTime : now)
471
+ RETURNING scheduled_time, due_at`, __classPrivateFieldGet(this, _DurabilitySchedule_channel, "f"), scheduledTime, scheduledTime + schedule.jitter_ms, queued ? 'queued' : 'running', queued ? scheduledTime : now)
460
472
  .toArray());
461
473
  if (row === undefined) {
462
474
  return { reserve: [], result: undefined };
@@ -482,7 +494,9 @@ async function _DurabilitySchedule_interruptOrphans() {
482
494
  return;
483
495
  }
484
496
  const queued = __classPrivateFieldGet(this, _DurabilitySchedule_engine, "f").sql
485
- .exec("SELECT 1 FROM durability_schedule_runs WHERE state = 'queued' LIMIT 1")
497
+ .exec(`SELECT 1 FROM durability_schedule_runs
498
+ WHERE channel = ? AND state = 'queued'
499
+ LIMIT 1`, __classPrivateFieldGet(this, _DurabilitySchedule_channel, "f"))
486
500
  .toArray();
487
501
  if (queued.length === 0) {
488
502
  return;
@@ -493,13 +507,13 @@ async function _DurabilitySchedule_interruptOrphans() {
493
507
  : dueRowSchema.array().parse(sql
494
508
  .exec(`UPDATE durability_schedule_runs
495
509
  SET state = 'running', next_at = ?
496
- WHERE scheduled_time IN (
510
+ WHERE channel = ? AND scheduled_time IN (
497
511
  SELECT scheduled_time FROM durability_schedule_runs
498
- WHERE state = 'queued'
512
+ WHERE channel = ? AND state = 'queued'
499
513
  ORDER BY scheduled_time
500
514
  LIMIT ?
501
515
  )
502
- RETURNING scheduled_time, due_at`, Date.now(), free)
516
+ RETURNING scheduled_time, due_at`, Date.now(), __classPrivateFieldGet(this, _DurabilitySchedule_channel, "f"), __classPrivateFieldGet(this, _DurabilitySchedule_channel, "f"), free)
503
517
  .toArray());
504
518
  return {
505
519
  reserve: rows.map((row) => row.scheduled_time),
@@ -564,8 +578,8 @@ async function _DurabilitySchedule_reserveSlots(mark) {
564
578
  const error = outcome.status === 'errored' ? outcome.error : undefined;
565
579
  const recorded = await __classPrivateFieldGet(this, _DurabilitySchedule_engine, "f").transaction((sql) => scheduledTimes(sql.exec(`UPDATE durability_schedule_runs
566
580
  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);
581
+ WHERE channel = ? AND scheduled_time = ? AND state = 'running'
582
+ RETURNING scheduled_time`, outcome.status, error === undefined ? null : JSON.stringify(error), Date.now(), __classPrivateFieldGet(this, _DurabilitySchedule_channel, "f"), run.scheduledTime)).length > 0);
569
583
  if (!recorded) {
570
584
  return;
571
585
  }
@@ -581,7 +595,7 @@ async function _DurabilitySchedule_reserveSlots(mark) {
581
595
  }, _DurabilitySchedule_deliverDue = function _DurabilitySchedule_deliverDue() {
582
596
  const due = runRowSchema.array().parse(__classPrivateFieldGet(this, _DurabilitySchedule_engine, "f").sql
583
597
  .exec(`SELECT * FROM durability_schedule_runs
584
- WHERE state IN ('complete', 'errored') AND next_at <= ?`, Date.now())
598
+ WHERE channel = ? AND state IN ('complete', 'errored') AND next_at <= ?`, __classPrivateFieldGet(this, _DurabilitySchedule_channel, "f"), Date.now())
585
599
  .toArray());
586
600
  for (const row of due) {
587
601
  __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 +621,15 @@ async function _DurabilitySchedule_reserveSlots(mark) {
607
621
  return;
608
622
  }
609
623
  await __classPrivateFieldGet(this, _DurabilitySchedule_engine, "f").transaction((sql) => {
610
- sql.exec('DELETE FROM durability_schedule_runs WHERE scheduled_time = ?', run.scheduledTime);
624
+ sql.exec(`DELETE FROM durability_schedule_runs
625
+ WHERE channel = ? AND scheduled_time = ?`, __classPrivateFieldGet(this, _DurabilitySchedule_channel, "f"), run.scheduledTime);
611
626
  });
612
627
  }, _DurabilitySchedule_failDelivery = async function _DurabilitySchedule_failDelivery(run, attempt, failure) {
613
628
  const error = serializeError(failure);
614
629
  if (attempt >= __classPrivateFieldGet(this, _DurabilitySchedule_maxOutcomeAttempts, "f")) {
615
630
  await __classPrivateFieldGet(this, _DurabilitySchedule_engine, "f").transaction((sql) => {
616
- sql.exec('DELETE FROM durability_schedule_runs WHERE scheduled_time = ?', run.scheduledTime);
631
+ sql.exec(`DELETE FROM durability_schedule_runs
632
+ WHERE channel = ? AND scheduled_time = ?`, __classPrivateFieldGet(this, _DurabilitySchedule_channel, "f"), run.scheduledTime);
617
633
  });
618
634
  reportFailure('durability.schedule.outcome_dead_lettered', { scheduledTime: run.scheduledTime, attempt }, failure);
619
635
  __classPrivateFieldGet(this, _DurabilitySchedule_emit, "f").call(this, {
@@ -627,7 +643,7 @@ async function _DurabilitySchedule_reserveSlots(mark) {
627
643
  const nextAttemptAt = Date.now() + __classPrivateFieldGet(this, _DurabilitySchedule_instances, "m", _DurabilitySchedule_retryDelay).call(this, attempt);
628
644
  await __classPrivateFieldGet(this, _DurabilitySchedule_engine, "f").transaction((sql) => {
629
645
  sql.exec(`UPDATE durability_schedule_runs SET attempt = ?, next_at = ?
630
- WHERE scheduled_time = ?`, attempt, nextAttemptAt, run.scheduledTime);
646
+ WHERE channel = ? AND scheduled_time = ?`, attempt, nextAttemptAt, __classPrivateFieldGet(this, _DurabilitySchedule_channel, "f"), run.scheduledTime);
631
647
  });
632
648
  __classPrivateFieldGet(this, _DurabilitySchedule_emit, "f").call(this, {
633
649
  ...__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
+ ];