durability 5.2.0 → 5.3.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.
package/dist/log/index.js CHANGED
@@ -10,7 +10,7 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
10
10
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11
11
  };
12
12
  var _DurabilityLog_instances, _DurabilityLog_engine, _DurabilityLog_channel, _DurabilityLog_routing, _DurabilityLog_retention, _DurabilityLog_cold, _DurabilityLog_leases, _DurabilityLog_maxParallelism, _DurabilityLog_leaseMs, _DurabilityLog_maxBatchSize, _DurabilityLog_encoder, _DurabilityLog_rehydrate, _DurabilityLog_record, _DurabilityLog_settle, _DurabilityLog_dropTrimmed, _DurabilityLog_advance, _DurabilityLog_between, _DurabilityLog_readFrom, _DurabilityLog_requireLeases;
13
- import { z } from 'zod';
13
+ import * as v from 'valibot';
14
14
  import { traceMethods } from '../dev.js';
15
15
  import { LogAppendError, LogLeaseError, LogTruncatedError, reportFailure, serializeError, } from '../errors.js';
16
16
  import { RoutingLoad, } from '../routing/load.js';
@@ -19,54 +19,60 @@ import { migrateCapability } from '../migrations.js';
19
19
  import { assertPositiveInteger } from '../policy.js';
20
20
  import { assertChannel, defaultChannel, engineFor, } from '../scheduler/index.js';
21
21
  import { deserialize, serialize } from '../serialization.js';
22
- const logRecordRowSchema = z.object({
23
- offset: z.number().int().nonnegative(),
24
- dedup_key: z.string(),
25
- payload: z.string(),
26
- bytes: z.number().int().nonnegative(),
27
- appended_at: z.number().int().nonnegative(),
22
+ const logRecordRowSchema = v.object({
23
+ offset: v.pipe(v.number(), v.safeInteger(), v.minValue(0)),
24
+ dedup_key: v.string(),
25
+ payload: v.string(),
26
+ bytes: v.pipe(v.number(), v.safeInteger(), v.minValue(0)),
27
+ appended_at: v.pipe(v.number(), v.safeInteger(), v.minValue(0)),
28
28
  });
29
- const logCursorRowSchema = z.object({
30
- consumer: z.string(),
31
- offset: z.number().int().nonnegative(),
32
- committed_at: z.number().int().nonnegative(),
29
+ const logCursorRowSchema = v.object({
30
+ consumer: v.string(),
31
+ offset: v.pipe(v.number(), v.safeInteger(), v.minValue(0)),
32
+ committed_at: v.pipe(v.number(), v.safeInteger(), v.minValue(0)),
33
33
  });
34
34
  /** One contiguous run of records moved out of the object into cold storage. */
35
- const logSegmentRowSchema = z.object({
36
- first_offset: z.number().int().nonnegative(),
37
- last_offset: z.number().int().nonnegative(),
38
- locator: z.string(),
39
- bytes: z.number().int().nonnegative(),
40
- flushed_at: z.number().int().nonnegative(),
35
+ const logSegmentRowSchema = v.object({
36
+ first_offset: v.pipe(v.number(), v.safeInteger(), v.minValue(0)),
37
+ last_offset: v.pipe(v.number(), v.safeInteger(), v.minValue(0)),
38
+ locator: v.string(),
39
+ bytes: v.pipe(v.number(), v.safeInteger(), v.minValue(0)),
40
+ flushed_at: v.pipe(v.number(), v.safeInteger(), v.minValue(0)),
41
41
  });
42
42
  /**
43
43
  * One in-flight or settled range of offsets held by a consumer. A range is
44
44
  * redelivered under a fresh `batch_id`, so an ack from a previous holder is
45
45
  * rejected rather than advancing a range someone else now owns.
46
46
  */
47
- const logLeaseRowSchema = z.object({
48
- batch_id: z.string(),
49
- consumer: z.string(),
50
- first_offset: z.number().int().nonnegative(),
51
- last_offset: z.number().int().nonnegative(),
52
- state: z.enum(['active', 'pending', 'acked', 'skipped']),
53
- attempt: z.number().int().positive(),
54
- expires_at: z.number().int().nonnegative(),
55
- created_at: z.number().int().nonnegative(),
47
+ const logLeaseRowSchema = v.object({
48
+ batch_id: v.string(),
49
+ consumer: v.string(),
50
+ first_offset: v.pipe(v.number(), v.safeInteger(), v.minValue(0)),
51
+ last_offset: v.pipe(v.number(), v.safeInteger(), v.minValue(0)),
52
+ state: v.picklist(['active', 'pending', 'acked', 'skipped']),
53
+ attempt: v.pipe(v.number(), v.safeInteger(), v.gtValue(0)),
54
+ expires_at: v.pipe(v.number(), v.safeInteger(), v.minValue(0)),
55
+ created_at: v.pipe(v.number(), v.safeInteger(), v.minValue(0)),
56
56
  });
57
- const allocationRowSchema = z.object({
58
- allocated_offset: z.number().int().nonnegative(),
57
+ const allocationRowSchema = v.object({
58
+ allocated_offset: v.pipe(v.number(), v.safeInteger(), v.minValue(0)),
59
59
  });
60
- const offsetRowSchema = z.object({ offset: z.number().int().nonnegative() });
61
- const seqRowSchema = z.object({ seq: z.number().int().nonnegative() });
62
- const countRowSchema = z.object({ count: z.number().int().nonnegative() });
63
- const totalBytesRowSchema = z.object({
64
- total_bytes: z.number().int().nonnegative(),
60
+ const offsetRowSchema = v.object({
61
+ offset: v.pipe(v.number(), v.safeInteger(), v.minValue(0)),
65
62
  });
66
- const boundsRowSchema = z.object({
67
- hot: z.number().int().nonnegative().nullable(),
68
- cold: z.number().int().nonnegative().nullable(),
69
- next_offset: z.number().int().nonnegative(),
63
+ const seqRowSchema = v.object({
64
+ seq: v.pipe(v.number(), v.safeInteger(), v.minValue(0)),
65
+ });
66
+ const countRowSchema = v.object({
67
+ count: v.pipe(v.number(), v.safeInteger(), v.minValue(0)),
68
+ });
69
+ const totalBytesRowSchema = v.object({
70
+ total_bytes: v.pipe(v.number(), v.safeInteger(), v.minValue(0)),
71
+ });
72
+ const boundsRowSchema = v.object({
73
+ hot: v.nullable(v.pipe(v.number(), v.safeInteger(), v.minValue(0))),
74
+ cold: v.nullable(v.pipe(v.number(), v.safeInteger(), v.minValue(0))),
75
+ next_offset: v.pipe(v.number(), v.safeInteger(), v.minValue(0)),
70
76
  });
71
77
  /**
72
78
  * Inserts the batch and returns each record's offset in input order. A record
@@ -77,7 +83,7 @@ const boundsRowSchema = z.object({
77
83
  const appendRecords = (sql, channel, records, appendedAt) => {
78
84
  const assigned = new Map();
79
85
  for (const record of records) {
80
- const existing = offsetRowSchema.optional().parse(sql
86
+ const existing = v.parse(v.optional(offsetRowSchema), sql
81
87
  .exec(`SELECT "offset" FROM durability_log_records
82
88
  WHERE channel = ? AND dedup_key = ? LIMIT 1`, channel, record.dedup_key)
83
89
  .toArray()[0]);
@@ -91,7 +97,7 @@ const appendRecords = (sql, channel, records, appendedAt) => {
91
97
  return records.map((record) => assigned.get(record.dedup_key));
92
98
  }
93
99
  // A channel's counter row is created by its first append.
94
- const first = seqRowSchema.parse(sql
100
+ const first = v.parse(seqRowSchema, sql
95
101
  .exec(`INSERT INTO durability_log_seq (channel, next_offset, total_bytes)
96
102
  VALUES (?, ?, 0)
97
103
  ON CONFLICT(channel) DO UPDATE
@@ -112,14 +118,14 @@ const appendRecords = (sql, channel, records, appendedAt) => {
112
118
  WHERE channel = ?`, added, channel);
113
119
  return records.map((record) => assigned.get(record.dedup_key));
114
120
  };
115
- const readRecords = (sql, channel, from, limit) => logRecordRowSchema.array().parse(sql
121
+ const readRecords = (sql, channel, from, limit) => v.parse(v.array(logRecordRowSchema), sql
116
122
  .exec(`SELECT * FROM durability_log_records
117
123
  WHERE channel = ? AND "offset" >= ?
118
124
  ORDER BY "offset" ASC
119
125
  LIMIT ?`, channel, from, limit)
120
126
  .toArray());
121
127
  const readBounds = (sql, channel) => {
122
- const row = boundsRowSchema.parse(sql
128
+ const row = v.parse(boundsRowSchema, sql
123
129
  .exec(`SELECT
124
130
  (SELECT MIN("offset") FROM durability_log_records
125
131
  WHERE channel = ?1) AS hot,
@@ -137,18 +143,18 @@ const readBounds = (sql, channel) => {
137
143
  nextOffset: row.next_offset,
138
144
  };
139
145
  };
140
- const countRecords = (sql, channel) => countRowSchema.parse(sql
146
+ const countRecords = (sql, channel) => v.parse(countRowSchema, sql
141
147
  .exec('SELECT COUNT(*) AS count FROM durability_log_records WHERE channel = ?', channel)
142
148
  .toArray()[0]).count;
143
149
  /** Bytes of record payloads held in the object, excluding flushed segments. */
144
- const totalBytes = (sql, channel) => totalBytesRowSchema.parse(sql
150
+ const totalBytes = (sql, channel) => v.parse(totalBytesRowSchema, sql
145
151
  .exec(`SELECT COALESCE(
146
152
  (SELECT total_bytes FROM durability_log_seq WHERE channel = ?),
147
153
  0
148
154
  ) AS total_bytes`, channel)
149
155
  .toArray()[0]).total_bytes;
150
156
  /** Oldest retained records in offset order, for flush-or-delete decisions. */
151
- const listOldest = (sql, channel, limit) => logRecordRowSchema.array().parse(sql
157
+ const listOldest = (sql, channel, limit) => v.parse(v.array(logRecordRowSchema), sql
152
158
  .exec(`SELECT * FROM durability_log_records
153
159
  WHERE channel = ?
154
160
  ORDER BY "offset" ASC
@@ -159,7 +165,7 @@ const listOldest = (sql, channel, limit) => logRecordRowSchema.array().parse(sql
159
165
  * how many were removed. Runs inside the caller's transaction.
160
166
  */
161
167
  const trimThrough = (sql, channel, through, limit) => {
162
- const removed = logRecordRowSchema.array().parse(sql
168
+ const removed = v.parse(v.array(logRecordRowSchema), sql
163
169
  .exec(`DELETE FROM durability_log_records
164
170
  WHERE channel = ?1 AND "offset" IN (
165
171
  SELECT "offset" FROM durability_log_records
@@ -188,17 +194,17 @@ const insertSegment = (sql, channel, row) => {
188
194
  flushed_at = excluded.flushed_at`, channel, row.first_offset, row.last_offset, row.locator, row.bytes, row.flushed_at);
189
195
  };
190
196
  /** The segment holding an offset, if that offset was flushed. */
191
- const findSegment = (sql, channel, offset) => logSegmentRowSchema.optional().parse(sql
197
+ const findSegment = (sql, channel, offset) => v.parse(v.optional(logSegmentRowSchema), sql
192
198
  .exec(`SELECT * FROM durability_log_segments
193
199
  WHERE channel = ?1 AND first_offset <= ?2 AND last_offset >= ?2
194
200
  LIMIT 1`, channel, offset)
195
201
  .toArray()[0]);
196
- const readCursors = (sql, channel) => logCursorRowSchema.array().parse(sql
202
+ const readCursors = (sql, channel) => v.parse(v.array(logCursorRowSchema), sql
197
203
  .exec(`SELECT * FROM durability_log_cursors
198
204
  WHERE channel = ?
199
205
  ORDER BY consumer`, channel)
200
206
  .toArray());
201
- const readCursor = (sql, channel, consumer) => offsetRowSchema.optional().parse(sql
207
+ const readCursor = (sql, channel, consumer) => v.parse(v.optional(offsetRowSchema), sql
202
208
  .exec(`SELECT "offset" FROM durability_log_cursors
203
209
  WHERE channel = ? AND consumer = ? LIMIT 1`, channel, consumer)
204
210
  .toArray()[0])?.offset;
@@ -212,7 +218,7 @@ const commitCursor = (sql, channel, consumer, offset, committedAt) => {
212
218
  WHERE excluded."offset" > durability_log_cursors."offset"`, channel, consumer, offset, committedAt);
213
219
  };
214
220
  /** Highest offset handed to a lease, which runs ahead of the commit. */
215
- const readAllocation = (sql, channel, consumer) => allocationRowSchema.optional().parse(sql
221
+ const readAllocation = (sql, channel, consumer) => v.parse(v.optional(allocationRowSchema), sql
216
222
  .exec(`SELECT allocated_offset FROM durability_log_allocations
217
223
  WHERE channel = ? AND consumer = ? LIMIT 1`, channel, consumer)
218
224
  .toArray()[0])?.allocated_offset;
@@ -233,7 +239,7 @@ const insertLease = (sql, channel, row) => {
233
239
  * Oldest range owed redelivery: explicitly nacked, or held past its expiry.
234
240
  * Claiming rewrites its `batch_id`, fencing the previous holder.
235
241
  */
236
- const claimExpired = (sql, channel, consumer, now, batchId, expiresAt) => logLeaseRowSchema.optional().parse(sql
242
+ const claimExpired = (sql, channel, consumer, now, batchId, expiresAt) => v.parse(v.optional(logLeaseRowSchema), sql
237
243
  .exec(`UPDATE durability_log_leases
238
244
  SET batch_id = ?1, state = 'active', attempt = attempt + 1,
239
245
  expires_at = ?2
@@ -249,7 +255,7 @@ const claimExpired = (sql, channel, consumer, now, batchId, expiresAt) => logLea
249
255
  RETURNING *`, batchId, expiresAt, channel, consumer, now)
250
256
  .toArray()[0]);
251
257
  /** Ranges still held, so parallelism can be bounded per consumer. */
252
- const countHeld = (sql, channel, consumer, now) => countRowSchema.parse(sql
258
+ const countHeld = (sql, channel, consumer, now) => v.parse(countRowSchema, sql
253
259
  .exec(`SELECT COUNT(*) AS count FROM durability_log_leases
254
260
  WHERE channel = ?
255
261
  AND consumer = ?
@@ -266,7 +272,7 @@ const settleLease = (sql, channel, batchId, state, expiresAt) => sql
266
272
  * Ranges from `from` in offset order, so a commit can advance over the
267
273
  * unbroken run of settled ones and no further.
268
274
  */
269
- const leasesFrom = (sql, channel, consumer, from, limit) => logLeaseRowSchema.array().parse(sql
275
+ const leasesFrom = (sql, channel, consumer, from, limit) => v.parse(v.array(logLeaseRowSchema), sql
270
276
  .exec(`SELECT * FROM durability_log_leases
271
277
  WHERE channel = ? AND consumer = ? AND last_offset >= ?
272
278
  ORDER BY first_offset ASC
@@ -639,7 +645,7 @@ export class DurabilityLog {
639
645
  /** In-flight and settled-but-uncommitted ranges, for operators and tests. */
640
646
  async leases(consumer) {
641
647
  __classPrivateFieldGet(this, _DurabilityLog_instances, "m", _DurabilityLog_requireLeases).call(this);
642
- return logLeaseRowSchema.array().parse(__classPrivateFieldGet(this, _DurabilityLog_engine, "f").sql
648
+ return v.parse(v.array(logLeaseRowSchema), __classPrivateFieldGet(this, _DurabilityLog_engine, "f").sql
643
649
  .exec(`SELECT * FROM durability_log_leases
644
650
  WHERE channel = ? AND consumer = ?
645
651
  ORDER BY first_offset ASC`, __classPrivateFieldGet(this, _DurabilityLog_channel, "f"), consumer)
@@ -1,4 +1,4 @@
1
- import { z } from 'zod';
1
+ import * as v from 'valibot';
2
2
  import { traceFunction } from '../dev.js';
3
3
  import { DurableMemoLimitError, DurableMemoSerializationError, } from '../errors.js';
4
4
  import { deserialize, serialize } from '../serialization.js';
@@ -7,10 +7,10 @@ import { channelBindings, pendingGeneration, tableOwner, } from '../storage.js';
7
7
  export const maxMemosPerRecord = 1000;
8
8
  /** The largest serialized memoized result, in UTF-8 bytes. */
9
9
  export const maxMemoBytes = 1048576;
10
- const memoLookupSchema = z.object({
11
- result: z.string().nullable(),
12
- owned: z.number().int(),
13
- saved: z.number().int(),
10
+ const memoLookupSchema = v.object({
11
+ result: v.nullable(v.string()),
12
+ owned: v.pipe(v.number(), v.safeInteger()),
13
+ saved: v.pipe(v.number(), v.safeInteger()),
14
14
  });
15
15
  const supersededError = (key) => new Error(`Memoized key ${JSON.stringify(key)} belongs to a superseded attempt`);
16
16
  /** Memoization for one attempt; only that attempt may persist new results. */
@@ -53,7 +53,7 @@ export const createMemoize = (sql, table, ref) => {
53
53
  if (typeof key !== 'string' || key === '') {
54
54
  throw new TypeError('Memoize keys must be non-empty strings');
55
55
  }
56
- const lookup = memoLookupSchema.parse(sql
56
+ const lookup = v.parse(memoLookupSchema, sql
57
57
  .exec(`SELECT
58
58
  (SELECT result FROM durability_memos
59
59
  WHERE owner = ? AND key = ? AND generation_id = ? AND memo_key = ?)
@@ -97,11 +97,10 @@ export const createMemoize = (sql, table, ref) => {
97
97
  memoKey: key,
98
98
  })();
99
99
  };
100
- const memoKeySchema = z.object({ memo_key: z.string() });
100
+ const memoKeySchema = v.object({ memo_key: v.string() });
101
101
  /** Keys a record's current generation has results for, in the order they were saved. */
102
- export const memoizedKeys = (sql, table, key, generation) => memoKeySchema
103
- .array()
104
- .parse(sql
102
+ export const memoizedKeys = (sql, table, key, generation) => v
103
+ .parse(v.array(memoKeySchema), sql
105
104
  .exec(`SELECT memo_key FROM durability_memos
106
105
  WHERE owner = ? AND key = ? AND generation_id = ?
107
106
  ORDER BY rowid`, tableOwner(table), key, generation)
@@ -1,4 +1,4 @@
1
- import { z } from 'zod';
1
+ import * as v from 'valibot';
2
2
  import { traceStorage } from './dev.js';
3
3
  export const migrationTableName = 'durability_migrations';
4
4
  /**
@@ -7,11 +7,11 @@ export const migrationTableName = 'durability_migrations';
7
7
  * accidental deploy of an ancient version cannot silently unwind a schema.
8
8
  */
9
9
  const maxFutureMigrations = 2;
10
- const historyRowSchema = z.object({
11
- id: z.number().int(),
12
- name: z.string(),
13
- capability: z.string().nullable(),
14
- down: z.string().nullable(),
10
+ const historyRowSchema = v.object({
11
+ id: v.pipe(v.number(), v.safeInteger()),
12
+ name: v.string(),
13
+ capability: v.nullable(v.string()),
14
+ down: v.nullable(v.string()),
15
15
  });
16
16
  /**
17
17
  * Versions before 3.0 tracked the v4 rewrite of both tables under one name.
@@ -61,7 +61,7 @@ const readHistory = (sql, scope, migrations) => {
61
61
  sql.exec(`UPDATE ${scope.table} SET capability = ?
62
62
  WHERE name = ? AND capability IS NULL`, scope.capability, name);
63
63
  }
64
- return historyRowSchema.array().parse(sql
64
+ return v.parse(v.array(historyRowSchema), sql
65
65
  .exec(`SELECT id, name, capability, down FROM ${scope.table}
66
66
  WHERE capability = ? ORDER BY id`, scope.capability)
67
67
  .toArray());
@@ -78,7 +78,7 @@ const runDown = (sql, table, name, down) => {
78
78
  * scripts it stored. Refuses when the schema is further ahead than
79
79
  * {@link maxFutureMigrations}.
80
80
  */
81
- const revertFutureMigrations = (storage, scope, history, known) => {
81
+ const revertFutureMigrations = (sql, scope, history, known) => {
82
82
  const future = history.filter(({ name }) => !known.has(name)).reverse();
83
83
  if (future.length === 0) {
84
84
  return [];
@@ -86,16 +86,14 @@ const revertFutureMigrations = (storage, scope, history, known) => {
86
86
  if (future.length > maxFutureMigrations) {
87
87
  throw new Error(`${scope.label} schema is ${future.length} migrations ahead of this version; refusing to revert more than ${maxFutureMigrations}`);
88
88
  }
89
- storage.transactionSync(() => {
90
- for (const row of future) {
91
- runDown(storage.sql, scope.table, row.name, row.down);
92
- }
93
- });
89
+ for (const row of future) {
90
+ runDown(sql, scope.table, row.name, row.down);
91
+ }
94
92
  return future.map(({ name }) => name);
95
93
  };
96
- const currentRowSchema = z.object({
97
- name: z.string(),
98
- down: z.string().nullable(),
94
+ const currentRowSchema = v.object({
95
+ name: v.string(),
96
+ down: v.nullable(v.string()),
99
97
  });
100
98
  /**
101
99
  * Whether a capability's history already lists exactly these migrations with
@@ -106,9 +104,7 @@ const currentRowSchema = z.object({
106
104
  export const isSchemaCurrent = (sql, capability, migrations) => {
107
105
  let rows;
108
106
  try {
109
- rows = currentRowSchema
110
- .array()
111
- .parse(sql
107
+ rows = v.parse(v.array(currentRowSchema), sql
112
108
  .exec(`SELECT name, down FROM ${migrationTableName} WHERE capability = ?`, capability)
113
109
  .toArray());
114
110
  }
@@ -132,27 +128,29 @@ const migrateScope = (storage, scope, migrations, target) => {
132
128
  if (resolvedTarget !== null && targetIndex === -1) {
133
129
  throw new Error(`Unknown ${scope.label} migration target "${resolvedTarget}"`);
134
130
  }
135
- ensureHistoryTable(storage.sql, scope.table);
136
- if (scope.table === migrationTableName) {
137
- translateLegacyHistory(storage.sql);
138
- }
139
- const known = new Set(migrations.map(({ name }) => name));
140
- const history = readHistory(storage.sql, scope, migrations);
141
- const rolledBack = revertFutureMigrations(storage, scope, history, known);
142
- const applied = new Map(history
143
- .filter(({ name }) => known.has(name))
144
- .map((row) => [row.name, row]));
145
- const toRevert = migrations
146
- .slice(targetIndex + 1)
147
- .filter(({ name }) => applied.has(name))
148
- .reverse();
149
- const toApply = migrations
150
- .slice(0, targetIndex + 1)
151
- .filter(({ name }) => !applied.has(name));
152
- const toRefresh = migrations
153
- .slice(0, targetIndex + 1)
154
- .filter(({ name, down }) => applied.has(name) && applied.get(name)?.down !== down);
155
- storage.transactionSync(() => {
131
+ // Every step shares one transaction so a failure anywhere, including after
132
+ // future migrations were reverted, leaves the schema and history as they were.
133
+ return storage.transactionSync(() => {
134
+ ensureHistoryTable(storage.sql, scope.table);
135
+ if (scope.table === migrationTableName) {
136
+ translateLegacyHistory(storage.sql);
137
+ }
138
+ const known = new Set(migrations.map(({ name }) => name));
139
+ const history = readHistory(storage.sql, scope, migrations);
140
+ const rolledBack = revertFutureMigrations(storage.sql, scope, history, known);
141
+ const applied = new Map(history
142
+ .filter(({ name }) => known.has(name))
143
+ .map((row) => [row.name, row]));
144
+ const toRevert = migrations
145
+ .slice(targetIndex + 1)
146
+ .filter(({ name }) => applied.has(name))
147
+ .reverse();
148
+ const toApply = migrations
149
+ .slice(0, targetIndex + 1)
150
+ .filter(({ name }) => !applied.has(name));
151
+ const toRefresh = migrations
152
+ .slice(0, targetIndex + 1)
153
+ .filter(({ name, down }) => applied.has(name) && applied.get(name)?.down !== down);
156
154
  for (const migration of toRevert) {
157
155
  runDown(storage.sql, scope.table, migration.name, migration.down);
158
156
  }
@@ -164,19 +162,17 @@ const migrateScope = (storage, scope, migrations, target) => {
164
162
  for (const migration of toRefresh) {
165
163
  storage.sql.exec(`UPDATE ${scope.table} SET down = ? WHERE name = ?`, migration.down, migration.name);
166
164
  }
165
+ const remaining = v.parse(v.object({ count: v.pipe(v.number(), v.safeInteger()) }), storage.sql
166
+ .exec(`SELECT COUNT(*) AS count FROM ${scope.table}`)
167
+ .toArray()[0]).count;
168
+ if (remaining === 0) {
169
+ storage.sql.exec(`DROP TABLE IF EXISTS ${scope.table}`);
170
+ }
171
+ return {
172
+ applied: toApply.map(({ name }) => name),
173
+ rolledBack: [...rolledBack, ...toRevert.map(({ name }) => name)],
174
+ };
167
175
  });
168
- const remaining = z
169
- .object({ count: z.number().int() })
170
- .parse(storage.sql
171
- .exec(`SELECT COUNT(*) AS count FROM ${scope.table}`)
172
- .toArray()[0]).count;
173
- if (remaining === 0) {
174
- storage.sql.exec(`DROP TABLE IF EXISTS ${scope.table}`);
175
- }
176
- return {
177
- applied: toApply.map(({ name }) => name),
178
- rolledBack: [...rolledBack, ...toRevert.map(({ name }) => name)],
179
- };
180
176
  };
181
177
  /**
182
178
  * Moves one capability's schema to a target migration, applying or reverting as
@@ -10,7 +10,7 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
10
10
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11
11
  };
12
12
  var _DurabilityCore_instances, _DurabilityCore_engine, _DurabilityCore_channel, _DurabilityCore_table, _DurabilityCore_handlers, _DurabilityCore_policy, _DurabilityCore_lifecycle, _DurabilityCore_emit, _DurabilityCore_includeResults, _DurabilityCore_active, _DurabilityCore_executionStarts, _DurabilityCore_trackedSource, _DurabilityCore_runDue, _DurabilityCore_getResult, _DurabilityCore_run, _DurabilityCore_execute, _DurabilityCore_start;
13
- import { z } from 'zod';
13
+ import * as v from 'valibot';
14
14
  import { traceFunction, traceMethods } from '../dev.js';
15
15
  import { DuplicateDurableCallError, DuplicateDurablePayloadError, DurableAttemptsExhaustedError, DurableAttemptTimeoutError, DurableResultSerializationError, isErrorInstance, NonRetryableError, reportFailure, } from '../errors.js';
16
16
  import { createLifecycleHooks, } from '../lifecycle.js';
@@ -23,25 +23,23 @@ import { canonical, deserialize, serialize } from '../serialization.js';
23
23
  import { createMemoize, deleteMemosOfDroppedTable, memoizedKeys, } from '../memoize/index.js';
24
24
  import { listCreated, updateAttempt } from '../storage.js';
25
25
  import { registerTrackedSource, } from '../tracker/source.js';
26
- const callRowSchema = z.object({
27
- id: z.string(),
28
- channel: z.string(),
29
- operation: z.string(),
30
- payload: z.string(),
31
- status: z.enum(['pending', 'completed', 'failed']),
32
- result: z.string().nullable(),
33
- attempt: z.number().int().nonnegative(),
34
- next_attempt_at: z.number().int().nonnegative(),
35
- last_error: z.string().nullable(),
36
- last_error_name: z.string().nullable(),
37
- completed_at: z.number().int().nonnegative().nullable(),
38
- created_at: z.number().int().nonnegative(),
39
- generation_id: z.string(),
26
+ const callRowSchema = v.object({
27
+ id: v.string(),
28
+ channel: v.string(),
29
+ operation: v.string(),
30
+ payload: v.string(),
31
+ status: v.picklist(['pending', 'completed', 'failed']),
32
+ result: v.nullable(v.string()),
33
+ attempt: v.pipe(v.number(), v.safeInteger(), v.minValue(0)),
34
+ next_attempt_at: v.pipe(v.number(), v.safeInteger(), v.minValue(0)),
35
+ last_error: v.nullable(v.string()),
36
+ last_error_name: v.nullable(v.string()),
37
+ completed_at: v.nullable(v.pipe(v.number(), v.safeInteger(), v.minValue(0))),
38
+ created_at: v.pipe(v.number(), v.safeInteger(), v.minValue(0)),
39
+ generation_id: v.string(),
40
40
  });
41
41
  const callsTable = { name: 'durability_calls', key: 'id' };
42
- const readCall = (sql, channel, id) => callRowSchema
43
- .optional()
44
- .parse(sql
42
+ const readCall = (sql, channel, id) => v.parse(v.optional(callRowSchema), sql
45
43
  .exec('SELECT * FROM durability_calls WHERE channel = ? AND id = ?', channel, id)
46
44
  .toArray()[0]);
47
45
  const assertOperation = (id, existingOperation, requestedOperation) => {
@@ -186,9 +184,8 @@ _DurabilityCore_engine = new WeakMap(), _DurabilityCore_channel = new WeakMap(),
186
184
  status,
187
185
  name,
188
186
  });
189
- const records = callRowSchema
190
- .array()
191
- .parse(page.rows)
187
+ const records = v
188
+ .parse(v.array(callRowSchema), page.rows)
192
189
  .map((call) => callRecord(sql, call));
193
190
  return page.next === undefined
194
191
  ? { records }
@@ -197,14 +194,11 @@ _DurabilityCore_engine = new WeakMap(), _DurabilityCore_channel = new WeakMap(),
197
194
  watch: (id, listener) => __classPrivateFieldGet(this, _DurabilityCore_engine, "f").watch(__classPrivateFieldGet(this, _DurabilityCore_table, "f"), id, () => listener()),
198
195
  };
199
196
  }, _DurabilityCore_runDue = async function _DurabilityCore_runDue(now) {
200
- const due = z
201
- .object({ id: z.string() })
202
- .array()
203
- .parse(__classPrivateFieldGet(this, _DurabilityCore_engine, "f").sql
197
+ const due = v.parse(v.array(v.object({ id: v.string() })), __classPrivateFieldGet(this, _DurabilityCore_engine, "f").sql
204
198
  .exec(`SELECT id FROM durability_calls
205
- WHERE channel = ? AND status = 'pending' AND next_attempt_at <= ?
206
- ORDER BY next_attempt_at ASC
207
- LIMIT 100`, __classPrivateFieldGet(this, _DurabilityCore_channel, "f"), now)
199
+ WHERE channel = ? AND status = 'pending' AND next_attempt_at <= ?
200
+ ORDER BY next_attempt_at ASC
201
+ LIMIT 100`, __classPrivateFieldGet(this, _DurabilityCore_channel, "f"), now)
208
202
  .toArray());
209
203
  // With liveTimers an active operation reschedules itself when it settles, so
210
204
  // skipping it keeps a long handler from blocking a concurrent alarm pass.
@@ -19,24 +19,26 @@ import { assertChannel, defaultChannel, engineFor, } from '../scheduler/index.js
19
19
  import { deserialize, serialize } from '../serialization.js';
20
20
  import { claimAttempt, deleteAttempt, updateAttempt, } from '../storage.js';
21
21
  import { exponential, jitter } from '../utils.js';
22
- import { z } from 'zod';
22
+ import * as v from 'valibot';
23
23
  const outboxTable = { name: 'durability_outbox', key: 'id' };
24
- const outboxRowSchema = z.object({
25
- id: z.string(),
26
- channel: z.string(),
27
- entry_key: z.string(),
28
- version: z.number().int().positive(),
29
- payload: z.string(),
30
- status: z.literal('pending'),
31
- attempt: z.number().int().nonnegative(),
32
- next_attempt_at: z.number().int().nonnegative(),
33
- last_error: z.string().nullable(),
34
- last_error_name: z.string().nullable(),
35
- created_at: z.number().int().nonnegative(),
36
- generation_id: z.string(),
24
+ const outboxRowSchema = v.object({
25
+ id: v.string(),
26
+ channel: v.string(),
27
+ entry_key: v.string(),
28
+ version: v.pipe(v.number(), v.safeInteger(), v.gtValue(0)),
29
+ payload: v.string(),
30
+ status: v.literal('pending'),
31
+ attempt: v.pipe(v.number(), v.safeInteger(), v.minValue(0)),
32
+ next_attempt_at: v.pipe(v.number(), v.safeInteger(), v.minValue(0)),
33
+ last_error: v.nullable(v.string()),
34
+ last_error_name: v.nullable(v.string()),
35
+ created_at: v.pipe(v.number(), v.safeInteger(), v.minValue(0)),
36
+ generation_id: v.string(),
37
37
  });
38
- const versionRowSchema = z.object({ version: z.number().int().positive() });
39
- const listDueForChannel = (sql, channel, now, limit, key) => outboxRowSchema.array().parse(sql
38
+ const versionRowSchema = v.object({
39
+ version: v.pipe(v.number(), v.safeInteger(), v.gtValue(0)),
40
+ });
41
+ const listDueForChannel = (sql, channel, now, limit, key) => v.parse(v.array(outboxRowSchema), sql
40
42
  .exec(`SELECT * FROM durability_outbox
41
43
  WHERE channel = ? AND status = 'pending' AND next_attempt_at <= ?
42
44
  AND (? IS NULL OR entry_key = ?)
@@ -45,7 +47,7 @@ const listDueForChannel = (sql, channel, now, limit, key) => outboxRowSchema.arr
45
47
  .toArray());
46
48
  /** Allocates a version from a durable counter that survives row deletion. */
47
49
  const nextVersion = (sql) => {
48
- const { version } = versionRowSchema.parse(sql
50
+ const { version } = v.parse(versionRowSchema, sql
49
51
  .exec(`UPDATE durability_outbox_seq
50
52
  SET next_version = next_version + 1
51
53
  WHERE id = 1
@@ -359,20 +361,7 @@ _DurabilityOutbox_engine = new WeakMap(), _DurabilityOutbox_channel = new WeakMa
359
361
  }
360
362
  return infrastructureRetryMs;
361
363
  }, _DurabilityOutbox_deadline = async function _DurabilityOutbox_deadline(run) {
362
- let timer;
363
- try {
364
- await Promise.race([
365
- Promise.resolve().then(run),
366
- new Promise((_resolve, reject) => {
367
- timer = setTimeout(() => reject(new OutboxTimeoutError(__classPrivateFieldGet(this, _DurabilityOutbox_attemptTimeoutMs, "f"))), __classPrivateFieldGet(this, _DurabilityOutbox_attemptTimeoutMs, "f"));
368
- }),
369
- ]);
370
- }
371
- finally {
372
- if (timer !== undefined) {
373
- clearTimeout(timer);
374
- }
375
- }
364
+ await __classPrivateFieldGet(this, _DurabilityOutbox_engine, "f").timer.withTimeout(Promise.resolve().then(run), __classPrivateFieldGet(this, _DurabilityOutbox_attemptTimeoutMs, "f"), () => new OutboxTimeoutError(__classPrivateFieldGet(this, _DurabilityOutbox_attemptTimeoutMs, "f")));
376
365
  };
377
366
  (() => {
378
367
  stageWithin = (outbox, sql, key, value) => {