durability 2.1.0 → 3.0.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.
@@ -0,0 +1,379 @@
1
+ import { z } from 'zod';
2
+ export const migrationTableName = 'durability_migrations';
3
+ /**
4
+ * Ordered SQLite migrations for the `durability_calls` table owned by
5
+ * {@link Durability}. Applied automatically on construction and tracked in the
6
+ * namespaced `durability_migrations` table alongside application migrations.
7
+ */
8
+ export const durabilityOperationMigrations = [
9
+ {
10
+ name: 'durability_0001_create_calls',
11
+ up: `
12
+ CREATE TABLE IF NOT EXISTS durability_calls (
13
+ id TEXT PRIMARY KEY,
14
+ operation TEXT NOT NULL,
15
+ payload TEXT NOT NULL,
16
+ status TEXT NOT NULL CHECK (status IN ('pending', 'completed', 'failed')),
17
+ result TEXT,
18
+ attempt INTEGER NOT NULL DEFAULT 0,
19
+ next_attempt_at INTEGER NOT NULL,
20
+ last_error TEXT,
21
+ last_error_name TEXT,
22
+ completed_at INTEGER
23
+ );
24
+ `,
25
+ down: 'DROP TABLE IF EXISTS durability_calls;',
26
+ },
27
+ {
28
+ name: 'durability_0002_pending_index',
29
+ up: `
30
+ CREATE INDEX IF NOT EXISTS durability_calls_pending_idx
31
+ ON durability_calls (status, next_attempt_at);
32
+ `,
33
+ down: 'DROP INDEX IF EXISTS durability_calls_pending_idx;',
34
+ },
35
+ {
36
+ name: 'durability_0004_calls_generation_and_created_at',
37
+ up: `
38
+ DROP INDEX IF EXISTS durability_calls_pending_idx;
39
+ ALTER TABLE durability_calls RENAME TO durability_calls_v3;
40
+ CREATE TABLE durability_calls (
41
+ id TEXT PRIMARY KEY,
42
+ operation TEXT NOT NULL,
43
+ payload TEXT NOT NULL,
44
+ status TEXT NOT NULL CHECK (status IN ('pending', 'completed', 'failed')),
45
+ result TEXT,
46
+ attempt INTEGER NOT NULL DEFAULT 0,
47
+ next_attempt_at INTEGER NOT NULL,
48
+ last_error TEXT,
49
+ last_error_name TEXT,
50
+ completed_at INTEGER,
51
+ generation_id TEXT NOT NULL DEFAULT 'legacy',
52
+ created_at INTEGER NOT NULL DEFAULT (CAST(unixepoch('subsec') * 1000 AS INTEGER))
53
+ );
54
+ INSERT INTO durability_calls
55
+ SELECT id, operation, payload, status, result, attempt, next_attempt_at,
56
+ last_error, last_error_name, completed_at, 'legacy:' || id,
57
+ CAST(unixepoch('subsec') * 1000 AS INTEGER)
58
+ FROM durability_calls_v3;
59
+ DROP TABLE durability_calls_v3;
60
+ CREATE INDEX durability_calls_pending_idx
61
+ ON durability_calls (status, next_attempt_at);
62
+ CREATE INDEX durability_calls_created_idx
63
+ ON durability_calls (created_at);
64
+ `,
65
+ down: `
66
+ DROP INDEX IF EXISTS durability_calls_pending_idx;
67
+ DROP INDEX IF EXISTS durability_calls_created_idx;
68
+ ALTER TABLE durability_calls RENAME TO durability_calls_v4;
69
+ CREATE TABLE durability_calls (
70
+ id TEXT PRIMARY KEY,
71
+ operation TEXT NOT NULL,
72
+ payload TEXT NOT NULL,
73
+ status TEXT NOT NULL CHECK (status IN ('pending', 'completed', 'failed')),
74
+ result TEXT,
75
+ attempt INTEGER NOT NULL DEFAULT 0,
76
+ next_attempt_at INTEGER NOT NULL,
77
+ last_error TEXT,
78
+ last_error_name TEXT,
79
+ completed_at INTEGER
80
+ );
81
+ INSERT INTO durability_calls
82
+ SELECT id, operation, payload, status, result, attempt, next_attempt_at,
83
+ last_error, last_error_name, completed_at
84
+ FROM durability_calls_v4;
85
+ DROP TABLE durability_calls_v4;
86
+ CREATE INDEX durability_calls_pending_idx
87
+ ON durability_calls (status, next_attempt_at);
88
+ `,
89
+ },
90
+ ];
91
+ /**
92
+ * Ordered SQLite migrations for the `durability_alarms` table owned by
93
+ * {@link DurabilityAlarms}. Applied automatically on construction.
94
+ */
95
+ export const durabilityNamedAlarmMigrations = [
96
+ {
97
+ name: 'durability_0003_create_alarms',
98
+ up: `
99
+ CREATE TABLE IF NOT EXISTS durability_alarms (
100
+ name TEXT PRIMARY KEY,
101
+ generation_id TEXT NOT NULL,
102
+ status TEXT NOT NULL CHECK (status IN ('pending', 'failed')),
103
+ scheduled_at INTEGER NOT NULL,
104
+ next_attempt_at INTEGER NOT NULL,
105
+ attempt INTEGER NOT NULL DEFAULT 0,
106
+ last_error TEXT,
107
+ last_error_name TEXT
108
+ );
109
+ CREATE INDEX IF NOT EXISTS durability_alarms_pending_idx
110
+ ON durability_alarms (status, next_attempt_at);
111
+ `,
112
+ down: `
113
+ DROP INDEX IF EXISTS durability_alarms_pending_idx;
114
+ DROP TABLE IF EXISTS durability_alarms;
115
+ `,
116
+ },
117
+ {
118
+ name: 'durability_0004_alarms_generation_and_created_at',
119
+ up: `
120
+ DROP INDEX IF EXISTS durability_alarms_pending_idx;
121
+ ALTER TABLE durability_alarms RENAME TO durability_alarms_v3;
122
+ CREATE TABLE durability_alarms (
123
+ name TEXT PRIMARY KEY,
124
+ generation_id TEXT NOT NULL,
125
+ status TEXT NOT NULL CHECK (status IN ('pending', 'failed')),
126
+ scheduled_at INTEGER NOT NULL,
127
+ next_attempt_at INTEGER NOT NULL,
128
+ attempt INTEGER NOT NULL DEFAULT 0,
129
+ last_error TEXT,
130
+ last_error_name TEXT,
131
+ created_at INTEGER NOT NULL DEFAULT (CAST(unixepoch('subsec') * 1000 AS INTEGER))
132
+ );
133
+ INSERT INTO durability_alarms
134
+ SELECT name, generation_id, status, scheduled_at, next_attempt_at,
135
+ attempt, last_error, last_error_name,
136
+ CAST(unixepoch('subsec') * 1000 AS INTEGER)
137
+ FROM durability_alarms_v3;
138
+ DROP TABLE durability_alarms_v3;
139
+ CREATE INDEX durability_alarms_pending_idx
140
+ ON durability_alarms (status, next_attempt_at);
141
+ CREATE INDEX durability_alarms_created_idx
142
+ ON durability_alarms (created_at);
143
+ `,
144
+ down: `
145
+ DROP INDEX IF EXISTS durability_alarms_pending_idx;
146
+ DROP INDEX IF EXISTS durability_alarms_created_idx;
147
+ ALTER TABLE durability_alarms RENAME TO durability_alarms_v4;
148
+ CREATE TABLE durability_alarms (
149
+ name TEXT PRIMARY KEY,
150
+ generation_id TEXT NOT NULL,
151
+ status TEXT NOT NULL CHECK (status IN ('pending', 'failed')),
152
+ scheduled_at INTEGER NOT NULL,
153
+ next_attempt_at INTEGER NOT NULL,
154
+ attempt INTEGER NOT NULL DEFAULT 0,
155
+ last_error TEXT,
156
+ last_error_name TEXT
157
+ );
158
+ INSERT INTO durability_alarms
159
+ SELECT name, generation_id, status, scheduled_at, next_attempt_at,
160
+ attempt, last_error, last_error_name
161
+ FROM durability_alarms_v4;
162
+ DROP TABLE durability_alarms_v4;
163
+ CREATE INDEX durability_alarms_pending_idx
164
+ ON durability_alarms (status, next_attempt_at);
165
+ `,
166
+ },
167
+ ];
168
+ /**
169
+ * Ordered SQLite migrations for fanout manifests and deliveries. Applied
170
+ * automatically on construction.
171
+ */
172
+ export const durabilityFanoutMigrations = [
173
+ {
174
+ name: 'durability_0005_create_fanout',
175
+ up: `
176
+ CREATE TABLE IF NOT EXISTS durability_fanout_messages (
177
+ key TEXT PRIMARY KEY,
178
+ id TEXT NOT NULL,
179
+ payload TEXT NOT NULL,
180
+ targets TEXT NOT NULL,
181
+ remaining INTEGER NOT NULL,
182
+ seq INTEGER NOT NULL,
183
+ created_at INTEGER NOT NULL,
184
+ generation_id TEXT NOT NULL
185
+ );
186
+ CREATE TABLE IF NOT EXISTS durability_fanout_deliveries (
187
+ id TEXT PRIMARY KEY,
188
+ message_key TEXT NOT NULL,
189
+ target_id TEXT NOT NULL,
190
+ seq INTEGER NOT NULL,
191
+ status TEXT NOT NULL CHECK (status IN ('pending')),
192
+ phase TEXT NOT NULL CHECK (phase IN ('delivery', 'dead_letter')),
193
+ attempt INTEGER NOT NULL DEFAULT 0,
194
+ next_attempt_at INTEGER NOT NULL,
195
+ last_error TEXT,
196
+ last_error_name TEXT,
197
+ created_at INTEGER NOT NULL,
198
+ generation_id TEXT NOT NULL,
199
+ dead_lettered_at INTEGER,
200
+ dead_letter_reason TEXT CHECK (dead_letter_reason IN ('explicit', 'exhausted'))
201
+ );
202
+ CREATE INDEX IF NOT EXISTS durability_fanout_deliveries_due_idx
203
+ ON durability_fanout_deliveries
204
+ (target_id, phase, status, attempt, seq, next_attempt_at);
205
+ CREATE INDEX IF NOT EXISTS durability_fanout_deliveries_pending_idx
206
+ ON durability_fanout_deliveries (phase, status, next_attempt_at);
207
+ CREATE INDEX IF NOT EXISTS durability_fanout_deliveries_created_idx
208
+ ON durability_fanout_deliveries (created_at);
209
+ CREATE TABLE IF NOT EXISTS durability_fanout_seq (
210
+ id INTEGER PRIMARY KEY CHECK (id = 1),
211
+ next_seq INTEGER NOT NULL
212
+ );
213
+ INSERT OR IGNORE INTO durability_fanout_seq (id, next_seq) VALUES (1, 0);
214
+ `,
215
+ down: `
216
+ DROP INDEX IF EXISTS durability_fanout_deliveries_due_idx;
217
+ DROP INDEX IF EXISTS durability_fanout_deliveries_pending_idx;
218
+ DROP INDEX IF EXISTS durability_fanout_deliveries_created_idx;
219
+ DROP TABLE IF EXISTS durability_fanout_deliveries;
220
+ DROP TABLE IF EXISTS durability_fanout_messages;
221
+ DROP TABLE IF EXISTS durability_fanout_seq;
222
+ `,
223
+ },
224
+ ];
225
+ /**
226
+ * Newer library versions may leave migrations this one does not know about.
227
+ * On downgrade their stored `down` scripts are run, but only this many, so an
228
+ * accidental deploy of an ancient version cannot silently unwind a schema.
229
+ */
230
+ const maxFutureMigrations = 2;
231
+ const historyRowSchema = z.object({
232
+ id: z.number().int(),
233
+ name: z.string(),
234
+ capability: z.string().nullable(),
235
+ down: z.string().nullable(),
236
+ });
237
+ /**
238
+ * Versions before 3.0 tracked the v4 rewrite of both tables under one name.
239
+ * Splitting it lets each capability migrate independently. The combined row is
240
+ * kept and both halves are recorded next to it, so a 2.x deployment reading
241
+ * the same database still sees its history as complete and never re-runs the
242
+ * rewrite.
243
+ */
244
+ const legacyCombinedV4 = 'durability_0004_generation_and_created_at';
245
+ const legacyHalves = [
246
+ 'durability_0004_calls_generation_and_created_at',
247
+ 'durability_0004_alarms_generation_and_created_at',
248
+ ];
249
+ const ensureHistoryTable = (sql) => {
250
+ // The base shape matches the table earlier versions created through workers-qb.
251
+ sql.exec(`
252
+ CREATE TABLE IF NOT EXISTS ${migrationTableName} (
253
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
254
+ name TEXT UNIQUE,
255
+ applied_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL
256
+ )
257
+ `);
258
+ const columns = new Set(sql
259
+ .exec(`SELECT name FROM pragma_table_info('${migrationTableName}')`)
260
+ .toArray()
261
+ .map((row) => row['name']));
262
+ for (const column of ['capability', 'down']) {
263
+ if (!columns.has(column)) {
264
+ sql.exec(`ALTER TABLE ${migrationTableName} ADD COLUMN ${column} TEXT`);
265
+ }
266
+ }
267
+ };
268
+ const translateLegacyHistory = (sql) => {
269
+ const legacy = sql
270
+ .exec(`SELECT name FROM ${migrationTableName} WHERE name = ?`, legacyCombinedV4)
271
+ .toArray();
272
+ if (legacy.length === 0) {
273
+ return;
274
+ }
275
+ for (const name of legacyHalves) {
276
+ sql.exec(`INSERT OR IGNORE INTO ${migrationTableName} (name) VALUES (?)`, name);
277
+ }
278
+ };
279
+ const readHistory = (sql, capability, migrations) => {
280
+ // Rows written before capabilities were tracked are claimed by the list that names them.
281
+ for (const { name } of migrations) {
282
+ sql.exec(`UPDATE ${migrationTableName} SET capability = ?
283
+ WHERE name = ? AND capability IS NULL`, capability, name);
284
+ }
285
+ return historyRowSchema.array().parse(sql
286
+ .exec(`SELECT id, name, capability, down FROM ${migrationTableName}
287
+ WHERE capability = ? ORDER BY id`, capability)
288
+ .toArray());
289
+ };
290
+ const runDown = (sql, name, down) => {
291
+ if (down === null) {
292
+ throw new Error(`Migration "${name}" has no stored down script`);
293
+ }
294
+ sql.exec(down);
295
+ sql.exec(`DELETE FROM ${migrationTableName} WHERE name = ?`, name);
296
+ };
297
+ /**
298
+ * Reverts migrations recorded by a newer library version, newest first, using
299
+ * the down scripts it stored. Refuses when the schema is further ahead than
300
+ * {@link maxFutureMigrations}.
301
+ */
302
+ const revertFutureMigrations = (storage, capability, history, known) => {
303
+ const future = history.filter(({ name }) => !known.has(name)).reverse();
304
+ if (future.length === 0) {
305
+ return [];
306
+ }
307
+ if (future.length > maxFutureMigrations) {
308
+ throw new Error(`Durability ${capability} schema is ${future.length} migrations ahead of this version; refusing to revert more than ${maxFutureMigrations}`);
309
+ }
310
+ storage.transactionSync(() => {
311
+ for (const row of future) {
312
+ runDown(storage.sql, row.name, row.down);
313
+ }
314
+ });
315
+ return future.map(({ name }) => name);
316
+ };
317
+ /**
318
+ * Moves one capability's schema to a target migration, applying or reverting as
319
+ * needed. `null` reverts every migration in the list; the shared migration
320
+ * table is dropped once no durability history remains.
321
+ *
322
+ * Each migration's `down` is stored alongside its history row so a later
323
+ * downgrade of the library can still revert it. Batches of migrations apply or
324
+ * revert atomically.
325
+ */
326
+ export const migrate = (storage, capability, migrations, target) => {
327
+ const resolvedTarget = target === undefined
328
+ ? (migrations[migrations.length - 1]?.name ?? null)
329
+ : target;
330
+ const targetIndex = resolvedTarget === null
331
+ ? -1
332
+ : migrations.findIndex((migration) => migration.name === resolvedTarget);
333
+ if (resolvedTarget !== null && targetIndex === -1) {
334
+ throw new Error(`Unknown durability migration target "${resolvedTarget}"`);
335
+ }
336
+ ensureHistoryTable(storage.sql);
337
+ translateLegacyHistory(storage.sql);
338
+ const known = new Set(migrations.map(({ name }) => name));
339
+ const history = readHistory(storage.sql, capability, migrations);
340
+ const rolledBack = revertFutureMigrations(storage, capability, history, known);
341
+ const applied = new Map(history
342
+ .filter(({ name }) => known.has(name))
343
+ .map((row) => [row.name, row]));
344
+ const toRevert = migrations
345
+ .slice(targetIndex + 1)
346
+ .filter(({ name }) => applied.has(name))
347
+ .reverse();
348
+ const toApply = migrations
349
+ .slice(0, targetIndex + 1)
350
+ .filter(({ name }) => !applied.has(name));
351
+ const toRefresh = migrations
352
+ .slice(0, targetIndex + 1)
353
+ .filter(({ name, down }) => applied.get(name)?.down !== down);
354
+ storage.transactionSync(() => {
355
+ for (const migration of toRevert) {
356
+ runDown(storage.sql, migration.name, migration.down);
357
+ }
358
+ for (const migration of toApply) {
359
+ storage.sql.exec(migration.up);
360
+ storage.sql.exec(`INSERT INTO ${migrationTableName} (name, capability, down) VALUES (?, ?, ?)`, migration.name, capability, migration.down);
361
+ }
362
+ // Keep stored down scripts current so a downgrade runs the latest revert logic.
363
+ for (const migration of toRefresh) {
364
+ storage.sql.exec(`UPDATE ${migrationTableName} SET down = ? WHERE name = ?`, migration.down, migration.name);
365
+ }
366
+ });
367
+ const remaining = z
368
+ .object({ count: z.number().int() })
369
+ .parse(storage.sql
370
+ .exec(`SELECT COUNT(*) AS count FROM ${migrationTableName}`)
371
+ .toArray()[0]).count;
372
+ if (remaining === 0) {
373
+ storage.sql.exec(`DROP TABLE IF EXISTS ${migrationTableName}`);
374
+ }
375
+ return {
376
+ applied: toApply.map(({ name }) => name),
377
+ rolledBack: [...rolledBack, ...toRevert.map(({ name }) => name)],
378
+ };
379
+ };
@@ -0,0 +1,74 @@
1
+ import { z } from 'zod';
2
+ /**
3
+ * Retry policy shared by all methods or overridden for one method.
4
+ *
5
+ * The delay callback owns the complete scheduling policy, so it can compose the
6
+ * helpers exported from `durability/utils` or use an application-specific
7
+ * strategy.
8
+ *
9
+ * @example
10
+ * ```ts
11
+ * import { exponential, jitter } from 'durability/utils';
12
+ *
13
+ * const retries: DurabilityRetryOptions = {
14
+ * maxAttempts: 5,
15
+ * delay: (attempt) => jitter(exponential(attempt)),
16
+ * };
17
+ * ```
18
+ */
19
+ export type DurabilityRetryOptions = {
20
+ /** Returns the delay in milliseconds after a failed attempt. */
21
+ delay?: (attempt: number) => number;
22
+ /** The total number of attempts, including the initial attempt. Defaults to 5. */
23
+ maxAttempts?: number;
24
+ };
25
+ /** Execution policy overrides for one durable operation method. */
26
+ export type DurabilityMethodOptions = {
27
+ /** Maximum duration of one attempt in milliseconds. */
28
+ attemptTimeoutMs?: number;
29
+ /** Retry policy overrides for this method. */
30
+ retries?: DurabilityRetryOptions;
31
+ };
32
+ /** Execution policy overrides for one named alarm. */
33
+ export type DurabilityAlarmMethodOptions = DurabilityMethodOptions & {
34
+ /** Retry timed-out attempts only when their side effects are idempotent or reconciled. */
35
+ retryTimeouts?: boolean;
36
+ };
37
+ /** Policy options shared by durable operations and named alarms. */
38
+ export type ExecutionPolicyOptions = {
39
+ /** Maximum duration of one handler attempt. Defaults to 5 minutes. */
40
+ attemptTimeoutMs?: number;
41
+ /** Retry policy shared by handlers without a method-level override. */
42
+ retries?: DurabilityRetryOptions;
43
+ };
44
+ export type AttemptPolicy = {
45
+ attemptTimeoutMs: number;
46
+ delay: (attempt: number) => number;
47
+ maxAttempts: number;
48
+ };
49
+ export declare const methodOptionsSchema: z.ZodObject<{
50
+ attemptTimeoutMs: z.ZodOptional<z.ZodNumber>;
51
+ retries: z.ZodOptional<z.ZodObject<{
52
+ delay: z.ZodOptional<z.ZodCustom<(attempt: number) => number, (attempt: number) => number>>;
53
+ maxAttempts: z.ZodOptional<z.ZodNumber>;
54
+ }, z.core.$strip>>;
55
+ }, z.core.$strip>;
56
+ export declare const alarmMethodOptionsSchema: z.ZodObject<{
57
+ attemptTimeoutMs: z.ZodOptional<z.ZodNumber>;
58
+ retries: z.ZodOptional<z.ZodObject<{
59
+ delay: z.ZodOptional<z.ZodCustom<(attempt: number) => number, (attempt: number) => number>>;
60
+ maxAttempts: z.ZodOptional<z.ZodNumber>;
61
+ }, z.core.$strip>>;
62
+ retryTimeouts: z.ZodOptional<z.ZodBoolean>;
63
+ }, z.core.$strip>;
64
+ export type MethodPolicy = z.infer<typeof methodOptionsSchema>;
65
+ export type AlarmMethodPolicy = z.infer<typeof alarmMethodOptionsSchema>;
66
+ export declare const assertPositiveInteger: (name: string, value: number) => void;
67
+ /**
68
+ * Validates global and per-method policy options once and resolves the
69
+ * effective policy for a method name.
70
+ */
71
+ export type PolicyResolver<Method> = (name: string) => AttemptPolicy & {
72
+ method: Method | undefined;
73
+ };
74
+ export declare const createPolicyResolver: <Method extends MethodPolicy>(options: ExecutionPolicyOptions, methods: Record<string, unknown>, methodSchema: z.ZodType<Method>) => PolicyResolver<Method>;
package/dist/policy.js ADDED
@@ -0,0 +1,49 @@
1
+ import { z } from 'zod';
2
+ import { exponential, jitter } from './utils.js';
3
+ const functionSchema = () => z.custom((value) => typeof value === 'function');
4
+ const retryOptionsSchema = z.object({
5
+ delay: functionSchema().optional(),
6
+ maxAttempts: z.number().optional(),
7
+ });
8
+ export const methodOptionsSchema = z.object({
9
+ attemptTimeoutMs: z.number().optional(),
10
+ retries: retryOptionsSchema.optional(),
11
+ });
12
+ export const alarmMethodOptionsSchema = methodOptionsSchema.extend({
13
+ retryTimeouts: z.boolean().optional(),
14
+ });
15
+ export const assertPositiveInteger = (name, value) => {
16
+ if (!Number.isInteger(value) || value < 1) {
17
+ throw new RangeError(`${name} must be a positive integer`);
18
+ }
19
+ };
20
+ const assertMethodOptions = (prefix, method) => {
21
+ if (method.attemptTimeoutMs !== undefined) {
22
+ assertPositiveInteger(`${prefix}.attemptTimeoutMs`, method.attemptTimeoutMs);
23
+ }
24
+ if (method.retries?.maxAttempts !== undefined) {
25
+ assertPositiveInteger(`${prefix}.retries.maxAttempts`, method.retries.maxAttempts);
26
+ }
27
+ };
28
+ export const createPolicyResolver = (options, methods, methodSchema) => {
29
+ const attemptTimeoutMs = options.attemptTimeoutMs ?? 5 * 60000;
30
+ const retries = retryOptionsSchema.parse(options.retries ?? {});
31
+ const delay = retries.delay ?? ((attempt) => jitter(exponential(attempt)));
32
+ const maxAttempts = retries.maxAttempts ?? 5;
33
+ assertPositiveInteger('attemptTimeoutMs', attemptTimeoutMs);
34
+ assertPositiveInteger('retries.maxAttempts', maxAttempts);
35
+ const parsed = new Map(Object.entries(methods).map(([name, method]) => {
36
+ const valid = methodSchema.parse(method);
37
+ assertMethodOptions(`methods.${name}`, valid);
38
+ return [name, valid];
39
+ }));
40
+ return (name) => {
41
+ const method = parsed.get(name);
42
+ return {
43
+ method,
44
+ attemptTimeoutMs: method?.attemptTimeoutMs ?? attemptTimeoutMs,
45
+ delay: method?.retries?.delay ?? delay,
46
+ maxAttempts: method?.retries?.maxAttempts ?? maxAttempts,
47
+ };
48
+ };
49
+ };
@@ -0,0 +1,28 @@
1
+ import type { EnqueueResult, LoadSnapshot } from './load.js';
2
+ export type RoutingTarget = string | {
3
+ shard: string;
4
+ locationHint?: DurableObjectLocationHint;
5
+ };
6
+ export type RoutingAddress = {
7
+ shard: string;
8
+ locationHint?: DurableObjectLocationHint;
9
+ };
10
+ /** Routing context is caller-owned and is not persisted or sent to consumers. */
11
+ export type Sharding<Input, Context = unknown> = (input: Input, context: Context | undefined, observations: ReadonlyMap<string, LoadSnapshot>) => RoutingTarget | Promise<RoutingTarget>;
12
+ export type RoutingClientConfig<Input, Value, Context = unknown> = {
13
+ invoke(address: RoutingAddress, input: Input): Promise<EnqueueResult<Value>>;
14
+ sharding?: Sharding<Input, Context>;
15
+ softBacklogLimit?: number;
16
+ };
17
+ /**
18
+ * Transport-independent selection and observation. Every push invokes ONE
19
+ * shard once. A false result is returned unchanged; transport failures throw.
20
+ * Only caller policy decides whether, where, or when to retry.
21
+ */
22
+ export declare class RoutingClient<Input, Value, Context = unknown> {
23
+ #private;
24
+ constructor(config: RoutingClientConfig<Input, Value, Context>);
25
+ /** Returns a copy; stale observations cannot influence custom routing. */
26
+ observations(): ReadonlyMap<string, LoadSnapshot>;
27
+ push(input: Input, context?: Context): Promise<EnqueueResult<Value>>;
28
+ }
@@ -0,0 +1,109 @@
1
+ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
2
+ if (kind === "m") throw new TypeError("Private method is not writable");
3
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
4
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
5
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
6
+ };
7
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
8
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
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
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11
+ };
12
+ var _RoutingClient_instances, _RoutingClient_config, _RoutingClient_observations, _RoutingClient_limit, _RoutingClient_width, _RoutingClient_lastResize, _RoutingClient_select, _RoutingClient_resize;
13
+ import { RoutingError } from './errors.js';
14
+ /**
15
+ * Transport-independent selection and observation. Every push invokes ONE
16
+ * shard once. A false result is returned unchanged; transport failures throw.
17
+ * Only caller policy decides whether, where, or when to retry.
18
+ */
19
+ export class RoutingClient {
20
+ constructor(config) {
21
+ _RoutingClient_instances.add(this);
22
+ _RoutingClient_config.set(this, void 0);
23
+ _RoutingClient_observations.set(this, new Map());
24
+ _RoutingClient_limit.set(this, void 0);
25
+ _RoutingClient_width.set(this, 1);
26
+ _RoutingClient_lastResize.set(this, -Infinity);
27
+ __classPrivateFieldSet(this, _RoutingClient_limit, config.softBacklogLimit ?? 1000, "f");
28
+ if (!Number.isSafeInteger(__classPrivateFieldGet(this, _RoutingClient_limit, "f")) || __classPrivateFieldGet(this, _RoutingClient_limit, "f") < 1) {
29
+ throw new RangeError('softBacklogLimit must be a positive safe integer');
30
+ }
31
+ __classPrivateFieldSet(this, _RoutingClient_config, config, "f");
32
+ }
33
+ /** Returns a copy; stale observations cannot influence custom routing. */
34
+ observations() {
35
+ for (const [key, load] of __classPrivateFieldGet(this, _RoutingClient_observations, "f")) {
36
+ if (Date.now() - load.observedAt >= load.windowMs) {
37
+ __classPrivateFieldGet(this, _RoutingClient_observations, "f").delete(key);
38
+ }
39
+ }
40
+ return new Map([...__classPrivateFieldGet(this, _RoutingClient_observations, "f")].map(([key, load]) => [key, structuredClone(load)]));
41
+ }
42
+ async push(input, context) {
43
+ const observed = this.observations();
44
+ const target = __classPrivateFieldGet(this, _RoutingClient_config, "f").sharding
45
+ ? await __classPrivateFieldGet(this, _RoutingClient_config, "f").sharding(input, context, observed)
46
+ : __classPrivateFieldGet(this, _RoutingClient_instances, "m", _RoutingClient_select).call(this, observed);
47
+ const address = typeof target === 'string' ? { shard: target } : target;
48
+ if (!address ||
49
+ typeof address.shard !== 'string' ||
50
+ address.shard.length === 0) {
51
+ throw new RoutingError('Sharding must return a non-empty shard key or { shard, locationHint }');
52
+ }
53
+ const response = await __classPrivateFieldGet(this, _RoutingClient_config, "f").invoke(address, input);
54
+ const prior = __classPrivateFieldGet(this, _RoutingClient_observations, "f").get(address.shard);
55
+ if (!prior || response.load.observedAt >= prior.observedAt) {
56
+ __classPrivateFieldGet(this, _RoutingClient_observations, "f").delete(address.shard);
57
+ __classPrivateFieldGet(this, _RoutingClient_observations, "f").set(address.shard, structuredClone(response.load));
58
+ }
59
+ // Advisory state must stay bounded for high-cardinality tenant routing.
60
+ if (__classPrivateFieldGet(this, _RoutingClient_observations, "f").size > 1024) {
61
+ const oldest = __classPrivateFieldGet(this, _RoutingClient_observations, "f").keys().next().value;
62
+ if (oldest !== undefined) {
63
+ __classPrivateFieldGet(this, _RoutingClient_observations, "f").delete(oldest);
64
+ }
65
+ }
66
+ if (!__classPrivateFieldGet(this, _RoutingClient_config, "f").sharding) {
67
+ __classPrivateFieldGet(this, _RoutingClient_instances, "m", _RoutingClient_resize).call(this, response.load);
68
+ }
69
+ return response;
70
+ }
71
+ }
72
+ _RoutingClient_config = new WeakMap(), _RoutingClient_observations = new WeakMap(), _RoutingClient_limit = new WeakMap(), _RoutingClient_width = new WeakMap(), _RoutingClient_lastResize = new WeakMap(), _RoutingClient_instances = new WeakSet(), _RoutingClient_select = function _RoutingClient_select(observations) {
73
+ const first = `shard-${Math.floor(Math.random() * __classPrivateFieldGet(this, _RoutingClient_width, "f"))}`;
74
+ const second = `shard-${Math.floor(Math.random() * __classPrivateFieldGet(this, _RoutingClient_width, "f"))}`;
75
+ const a = observations.get(first);
76
+ const b = observations.get(second);
77
+ if (!a || !b) {
78
+ return !a ? first : second;
79
+ }
80
+ // Backlog counts are message-target pairs; timing describes target batches.
81
+ // Compare these separately rather than claiming a bogus drain-time estimate.
82
+ if (a.outbound.pendingDeliveries !== b.outbound.pendingDeliveries) {
83
+ return a.outbound.pendingDeliveries < b.outbound.pendingDeliveries
84
+ ? first
85
+ : second;
86
+ }
87
+ const pressure = (load) => load.inbound.inFlight * (load.inbound.averageProcessingMs ?? 0) +
88
+ load.outbound.inFlight * (load.outbound.averageProcessingMs ?? 0);
89
+ return pressure(a) <= pressure(b) ? first : second;
90
+ }, _RoutingClient_resize = function _RoutingClient_resize(load) {
91
+ const now = Date.now();
92
+ if (now - load.observedAt >= load.windowMs) {
93
+ return;
94
+ }
95
+ if (load.outbound.pendingDeliveries > __classPrivateFieldGet(this, _RoutingClient_limit, "f") &&
96
+ now - __classPrivateFieldGet(this, _RoutingClient_lastResize, "f") >= 1000) {
97
+ __classPrivateFieldSet(this, _RoutingClient_width, __classPrivateFieldGet(this, _RoutingClient_width, "f") + 1, "f");
98
+ __classPrivateFieldSet(this, _RoutingClient_lastResize, now, "f");
99
+ return;
100
+ }
101
+ if (__classPrivateFieldGet(this, _RoutingClient_width, "f") > 1 &&
102
+ now - __classPrivateFieldGet(this, _RoutingClient_lastResize, "f") >= load.windowMs &&
103
+ load.outbound.pendingDeliveries < __classPrivateFieldGet(this, _RoutingClient_limit, "f") / 4 &&
104
+ load.inbound.inFlight === 0 &&
105
+ load.outbound.inFlight === 0) {
106
+ __classPrivateFieldSet(this, _RoutingClient_width, __classPrivateFieldGet(this, _RoutingClient_width, "f") - 1, "f");
107
+ __classPrivateFieldSet(this, _RoutingClient_lastResize, now, "f");
108
+ }
109
+ };
@@ -0,0 +1,33 @@
1
+ import { type TransformContext, type TransformStub } from '@durability/transforms';
2
+ import { RoutingLoad, type EnqueueResult } from './load.js';
3
+ import { type Sharding } from './routing-client.js';
4
+ export type { EnqueueResult, LoadSnapshot, ProcessingLoad } from './load.js';
5
+ export type { RoutingAddress, RoutingTarget, Sharding, } from './routing-client.js';
6
+ export type RoutingSession<Input, Value, Context = unknown> = {
7
+ push(input: Input, context?: Context): Promise<EnqueueResult<Value>>;
8
+ setContext(context: TransformContext): {
9
+ invoke(method: string, args: unknown[]): Promise<unknown>;
10
+ };
11
+ };
12
+ export type DurabilityRoutingConfig<Target extends Rpc.DurableObjectBranded, Input, Value, Context = unknown> = {
13
+ /** Application-owned exported Durable Object class. */
14
+ target: {
15
+ prototype: Target;
16
+ };
17
+ /** Injected by the Vite plugin; explicit for builds without it. */
18
+ exportName?: string;
19
+ /** Explicit namespace escape hatch for cross-worker or non-Vite consumers. */
20
+ namespace?: () => DurableObjectNamespace<Target>;
21
+ /** Chooses the application method/capability to invoke; never hardcoded. */
22
+ invoke(stub: DurableObjectStub<Target>, input: Input): Promise<EnqueueResult<Value>>;
23
+ sharding?: Sharding<Input, Context>;
24
+ softBacklogLimit?: number;
25
+ };
26
+ /**
27
+ * Inside a DO, attach this local load observer to a fanout capability. Outside
28
+ * the DO, client() routes calls to an application-owned class using ordinary
29
+ * @durability/transforms caller transforms. No DO classes are generated.
30
+ */
31
+ export declare class DurabilityRouting extends RoutingLoad {
32
+ static client<Target extends Rpc.DurableObjectBranded, Input, Value, Context = unknown>(config: DurabilityRoutingConfig<Target, Input, Value, Context>): TransformStub<RoutingSession<Input, Value, Context>>;
33
+ }