durability 2.1.0 → 3.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2 @@
1
+ import { type DurabilityStorage } from './storage.js';
2
+ export declare const createKvDurabilityStorage: (storage: DurableObjectStorage) => DurabilityStorage;
@@ -0,0 +1,421 @@
1
+ import { z } from 'zod';
2
+ import { alarmRowSchema, callRowSchema, deliveryRowSchema, fanoutMessageRowSchema, } from './storage.js';
3
+ const callTable = {
4
+ name: 'call',
5
+ keyOf: (row) => row.id,
6
+ schema: callRowSchema,
7
+ };
8
+ const alarmTable = {
9
+ name: 'alarm',
10
+ keyOf: (row) => row.name,
11
+ schema: alarmRowSchema,
12
+ };
13
+ const deliveryTable = {
14
+ name: 'fanout-delivery',
15
+ keyOf: (row) => row.id,
16
+ schema: deliveryRowSchema,
17
+ };
18
+ const keyPrefix = '__durability:kv:v1:';
19
+ const timestampWidth = 16;
20
+ const timestampKey = (timestamp) => timestamp.toString().padStart(timestampWidth, '0');
21
+ const indexTimestampSchema = z
22
+ .string()
23
+ .regex(/^\d{16}$/)
24
+ .transform(Number)
25
+ .pipe(z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER));
26
+ const keySchema = z.string().array();
27
+ const counterSchema = z.number().int().nonnegative().optional();
28
+ /** Deleting more keys than this in one KV call exceeds the Durable Object limit. */
29
+ const purgeBatchSize = 20;
30
+ const encodeIndexPart = (value) => encodeURIComponent(value);
31
+ const deliveryAttemptClass = (row) => row.attempt === 0 ? 0 : 1;
32
+ /**
33
+ * One record kind stored as a primary row plus two ordered index keys:
34
+ * `pending-<name>:<next_attempt_at>:<key>` for due work and
35
+ * `created-<name>:<created_at>:<key>` for retention purges.
36
+ */
37
+ class KvTable {
38
+ constructor(kv, spec, atomically) {
39
+ this.kv = kv;
40
+ this.spec = spec;
41
+ this.atomically = atomically;
42
+ this.rowPrefix = `${keyPrefix}${spec.name}:`;
43
+ this.pendingPrefix = `${keyPrefix}pending-${spec.name}:`;
44
+ this.createdPrefix = `${keyPrefix}created-${spec.name}:`;
45
+ }
46
+ async get(key) {
47
+ return this.spec.schema
48
+ .optional()
49
+ .parse(await this.kv.get(this.rowKey(key)));
50
+ }
51
+ async listDue(now, limit) {
52
+ const index = await this.kv.list({
53
+ prefix: this.pendingPrefix,
54
+ end: `${this.pendingPrefix}${timestampKey(now)};`,
55
+ limit,
56
+ });
57
+ return this.rows(keySchema.parse([...index.values()]));
58
+ }
59
+ async nextPendingAt() {
60
+ const index = await this.kv.list({ prefix: this.pendingPrefix, limit: 1 });
61
+ const first = index.keys().next().value;
62
+ if (typeof first !== 'string') {
63
+ return undefined;
64
+ }
65
+ return indexTimestampSchema.parse(first.slice(this.pendingPrefix.length, this.pendingPrefix.length + timestampWidth));
66
+ }
67
+ insert(row) {
68
+ return this.atomically(async (table) => {
69
+ if ((await table.get(this.spec.keyOf(row))) !== undefined) {
70
+ return false;
71
+ }
72
+ await table.write(undefined, row);
73
+ return true;
74
+ });
75
+ }
76
+ upsert(row) {
77
+ return this.atomically(async (table) => {
78
+ await table.write(await table.get(this.spec.keyOf(row)), row);
79
+ });
80
+ }
81
+ claimAttempt(key, generation, maxAttempts) {
82
+ return this.atomically(async (table) => {
83
+ const row = await table.pending(key, generation);
84
+ if (!row || row.attempt >= maxAttempts) {
85
+ return undefined;
86
+ }
87
+ const attempt = row.attempt + 1;
88
+ await table.write(row, { ...row, attempt });
89
+ return attempt;
90
+ });
91
+ }
92
+ settle(key, generation, attempt, patch) {
93
+ return this.atomically(async (table) => {
94
+ const row = await table.pending(key, generation);
95
+ if (!row || row.attempt !== attempt) {
96
+ return false;
97
+ }
98
+ await table.write(row, { ...row, ...patch });
99
+ return true;
100
+ });
101
+ }
102
+ exhaust(key, generation, maxAttempts, patch) {
103
+ return this.atomically(async (table) => {
104
+ const row = await table.pending(key, generation);
105
+ if (!row || row.attempt < maxAttempts) {
106
+ return false;
107
+ }
108
+ await table.write(row, { ...row, ...patch });
109
+ return true;
110
+ });
111
+ }
112
+ remove(key, generation, attempt) {
113
+ return this.atomically(async (table) => {
114
+ const row = await table.pending(key, generation);
115
+ if (!row || row.attempt !== attempt) {
116
+ return false;
117
+ }
118
+ await table.kv.delete([table.rowKey(key), ...table.indexKeys(row)]);
119
+ return true;
120
+ });
121
+ }
122
+ /** Deletes one bounded batch so a purge never exceeds the KV delete limit. */
123
+ async deleteCreatedBefore(before) {
124
+ const index = await this.kv.list({
125
+ prefix: this.createdPrefix,
126
+ end: `${this.createdPrefix}${timestampKey(before)}:`,
127
+ limit: purgeBatchSize,
128
+ });
129
+ const rows = await this.rows(keySchema.parse([...index.values()]));
130
+ if (rows.length === 0) {
131
+ return 0;
132
+ }
133
+ await this.kv.delete(rows.flatMap((row) => [
134
+ this.rowKey(this.spec.keyOf(row)),
135
+ ...this.indexKeys(row),
136
+ ]));
137
+ return rows.length;
138
+ }
139
+ async pending(key, generation) {
140
+ const row = await this.get(key);
141
+ if (row?.generation_id !== generation || row.status !== 'pending') {
142
+ return undefined;
143
+ }
144
+ return row;
145
+ }
146
+ async rows(keys) {
147
+ if (keys.length === 0) {
148
+ return [];
149
+ }
150
+ const found = await this.kv.get(keys.map((key) => this.rowKey(key)));
151
+ // The batch result is keyed, not ordered; keep the index order.
152
+ return this.spec.schema
153
+ .array()
154
+ .parse(keys.map((key) => found.get(this.rowKey(key))));
155
+ }
156
+ async write(previous, next) {
157
+ const key = this.spec.keyOf(next);
158
+ const previousIndexes = previous ? this.indexKeys(previous) : [];
159
+ const nextIndexes = this.indexKeys(next);
160
+ const stale = previousIndexes.filter((index) => !nextIndexes.includes(index));
161
+ if (stale.length > 0) {
162
+ await this.kv.delete(stale);
163
+ }
164
+ const entries = { [this.rowKey(key)]: next };
165
+ for (const index of nextIndexes) {
166
+ if (!previousIndexes.includes(index)) {
167
+ entries[index] = key;
168
+ }
169
+ }
170
+ await this.kv.put(entries);
171
+ }
172
+ rowKey(key) {
173
+ return `${this.rowPrefix}${key}`;
174
+ }
175
+ indexKeys(row) {
176
+ const key = this.spec.keyOf(row);
177
+ const created = `${this.createdPrefix}${timestampKey(row.created_at)}:${key}`;
178
+ if (row.status !== 'pending') {
179
+ return [created];
180
+ }
181
+ return [
182
+ created,
183
+ `${this.pendingPrefix}${timestampKey(row.next_attempt_at)}:${key}`,
184
+ ];
185
+ }
186
+ }
187
+ const fanoutMessagePrefix = `${keyPrefix}fanout-message:`;
188
+ const fanoutSeqCounterKey = `${keyPrefix}fanout-seq`;
189
+ const fanoutPendingCounterKey = `${keyPrefix}fanout-pending-count`;
190
+ const fanoutTargetPrefix = `${keyPrefix}fanout-target:`;
191
+ const fanoutTargetIndexPrefix = `${keyPrefix}fanout-target-index:`;
192
+ const fanoutTargetPendingPrefix = `${keyPrefix}pending-fanout-target:`;
193
+ class KvDeliveryTable extends KvTable {
194
+ constructor(kv, atomically) {
195
+ super(kv, deliveryTable, atomically);
196
+ this.globalPendingPrefix = this.pendingPrefix;
197
+ }
198
+ nextSeq() {
199
+ return this.atomically(async (raw) => {
200
+ const table = raw;
201
+ const seq = counterSchema.parse(await table.kv.get(fanoutSeqCounterKey)) ?? 0;
202
+ if (!Number.isSafeInteger(seq + 1)) {
203
+ throw new RangeError('Fanout sequence exhausted');
204
+ }
205
+ await table.kv.put(fanoutSeqCounterKey, seq + 1);
206
+ return seq;
207
+ });
208
+ }
209
+ indexKeys(row) {
210
+ const created = `${this.createdPrefix}${timestampKey(row.created_at)}:${row.id}`;
211
+ const attemptClass = deliveryAttemptClass(row);
212
+ const sequence = timestampKey(row.seq);
213
+ const target = encodeIndexPart(row.target_id);
214
+ const id = encodeIndexPart(row.id);
215
+ return [
216
+ created,
217
+ `${this.globalPendingPrefix}${attemptClass}:${timestampKey(row.next_attempt_at)}:${sequence}:${target}:${id}`,
218
+ `${fanoutTargetPendingPrefix}${target}:${attemptClass}:${timestampKey(row.next_attempt_at)}:${sequence}:${id}`,
219
+ ];
220
+ }
221
+ async getMessage(key) {
222
+ return fanoutMessageRowSchema
223
+ .optional()
224
+ .parse(await this.kv.get(this.messageKey(key)));
225
+ }
226
+ insertMessage(row) {
227
+ return this.atomically(async (raw) => {
228
+ const table = raw;
229
+ if ((await table.getMessage(row.key)) !== undefined) {
230
+ return false;
231
+ }
232
+ await table.kv.put(table.messageKey(row.key), row);
233
+ return true;
234
+ });
235
+ }
236
+ async listTargets() {
237
+ const targets = [];
238
+ let startAfter;
239
+ for (;;) {
240
+ // eslint-disable-next-line no-await-in-loop
241
+ const page = await this.kv.list({
242
+ prefix: fanoutTargetIndexPrefix,
243
+ limit: 128,
244
+ ...(startAfter === undefined ? {} : { startAfter }),
245
+ });
246
+ targets.push(...page.values());
247
+ if (page.size < 128) {
248
+ return targets;
249
+ }
250
+ startAfter = [...page.keys()][page.size - 1];
251
+ }
252
+ }
253
+ async listDueForTarget(target, now, limit) {
254
+ const firstPrefix = `${fanoutTargetPendingPrefix}${encodeIndexPart(target)}:0:`;
255
+ const first = await this.dueIndex(firstPrefix, now, limit);
256
+ if (first.length >= limit) {
257
+ return first;
258
+ }
259
+ const retryPrefix = `${fanoutTargetPendingPrefix}${encodeIndexPart(target)}:1:`;
260
+ const retries = await this.dueIndex(retryPrefix, now, limit - first.length);
261
+ return [...first, ...retries];
262
+ }
263
+ async pendingCount() {
264
+ return counterSchema.parse(await this.kv.get(fanoutPendingCounterKey)) ?? 0;
265
+ }
266
+ async listDue(now, limit) {
267
+ const firstPrefix = `${this.globalPendingPrefix}0:`;
268
+ const first = await this.dueIndex(firstPrefix, now, limit);
269
+ if (first.length >= limit) {
270
+ return first;
271
+ }
272
+ const retryPrefix = `${this.globalPendingPrefix}1:`;
273
+ const retries = await this.dueIndex(retryPrefix, now, limit - first.length);
274
+ return [...first, ...retries];
275
+ }
276
+ async nextPendingAt() {
277
+ const values = await Promise.all([0, 1].map(async (attemptClass) => {
278
+ const prefix = `${this.globalPendingPrefix}${attemptClass}:`;
279
+ const index = await this.kv.list({ prefix, limit: 1 });
280
+ const first = index.keys().next().value;
281
+ if (typeof first !== 'string') {
282
+ return undefined;
283
+ }
284
+ const offset = prefix.length;
285
+ return indexTimestampSchema.parse(first.slice(offset, offset + timestampWidth));
286
+ }));
287
+ const pending = values.filter((value) => value !== undefined);
288
+ return pending.length === 0 ? undefined : Math.min(...pending);
289
+ }
290
+ remove(key, generation, attempt) {
291
+ return this.atomically(async (raw) => {
292
+ const table = raw;
293
+ const row = await table.get(key);
294
+ if (row?.generation_id !== generation ||
295
+ row.status !== 'pending' ||
296
+ row.attempt !== attempt) {
297
+ return false;
298
+ }
299
+ await table.kv.delete([table.rowKey(key), ...table.indexKeys(row)]);
300
+ await table.adjustTargetCount(row.target_id, -1);
301
+ await table.adjustPendingCount(-1);
302
+ await table.decrementManifest(row.message_key);
303
+ return true;
304
+ });
305
+ }
306
+ deleteCreatedBefore(before) {
307
+ return this.atomically(async (raw) => {
308
+ const table = raw;
309
+ const index = await table.kv.list({
310
+ prefix: table.createdPrefix,
311
+ end: `${table.createdPrefix}${timestampKey(before)}:`,
312
+ limit: purgeBatchSize,
313
+ });
314
+ const rows = await table.rows(keySchema.parse([...index.values()]));
315
+ for (const row of rows) {
316
+ // Already the transaction's table; remove cannot nest a transaction.
317
+ // eslint-disable-next-line no-await-in-loop
318
+ await table.remove(row.id, row.generation_id, row.attempt);
319
+ }
320
+ return rows.length;
321
+ });
322
+ }
323
+ async write(previous, next) {
324
+ await super.write(previous, next);
325
+ if (previous === undefined) {
326
+ await this.adjustTargetCount(next.target_id, 1);
327
+ await this.adjustPendingCount(1);
328
+ return;
329
+ }
330
+ if (previous.target_id !== next.target_id) {
331
+ await this.adjustTargetCount(previous.target_id, -1);
332
+ await this.adjustTargetCount(next.target_id, 1);
333
+ }
334
+ }
335
+ async dueIndex(prefix, now, limit) {
336
+ if (limit <= 0) {
337
+ return [];
338
+ }
339
+ const rows = [];
340
+ let startAfter;
341
+ for (;;) {
342
+ const pageSize = Math.min(128, limit - rows.length);
343
+ // eslint-disable-next-line no-await-in-loop
344
+ const index = await this.kv.list({
345
+ prefix,
346
+ end: `${prefix}${timestampKey(now)};`,
347
+ limit: pageSize,
348
+ ...(startAfter === undefined ? {} : { startAfter }),
349
+ });
350
+ // eslint-disable-next-line no-await-in-loop
351
+ rows.push(...(await this.rows(keySchema.parse([...index.values()]))));
352
+ if (index.size < pageSize || rows.length >= limit) {
353
+ return rows.sort((left, right) => left.seq - right.seq);
354
+ }
355
+ startAfter = [...index.keys()][index.size - 1];
356
+ }
357
+ }
358
+ messageKey(key) {
359
+ return `${fanoutMessagePrefix}${key}`;
360
+ }
361
+ targetCountKey(target) {
362
+ return `${fanoutTargetPrefix}${encodeIndexPart(target)}`;
363
+ }
364
+ targetIndexKey(target) {
365
+ return `${fanoutTargetIndexPrefix}${encodeIndexPart(target)}`;
366
+ }
367
+ async adjustTargetCount(target, delta) {
368
+ const count = counterSchema.parse(await this.kv.get(this.targetCountKey(target))) ?? 0;
369
+ const next = count + delta;
370
+ if (next <= 0) {
371
+ await this.kv.delete([
372
+ this.targetCountKey(target),
373
+ this.targetIndexKey(target),
374
+ ]);
375
+ return;
376
+ }
377
+ await this.kv.put({
378
+ [this.targetCountKey(target)]: next,
379
+ [this.targetIndexKey(target)]: target,
380
+ });
381
+ }
382
+ async adjustPendingCount(delta) {
383
+ const count = counterSchema.parse(await this.kv.get(fanoutPendingCounterKey)) ?? 0;
384
+ await this.kv.put(fanoutPendingCounterKey, count + delta);
385
+ }
386
+ async decrementManifest(messageKey, amount = 1) {
387
+ const manifest = fanoutMessageRowSchema
388
+ .optional()
389
+ .parse(await this.kv.get(this.messageKey(messageKey)));
390
+ if (manifest === undefined || manifest.remaining <= amount) {
391
+ await this.kv.delete(this.messageKey(messageKey));
392
+ return;
393
+ }
394
+ await this.kv.put(this.messageKey(messageKey), {
395
+ ...manifest,
396
+ remaining: manifest.remaining - amount,
397
+ });
398
+ }
399
+ }
400
+ class KvSession {
401
+ constructor(physicalAlarm, atomically) {
402
+ this.physicalAlarm = physicalAlarm;
403
+ this.calls = new KvTable(physicalAlarm, callTable, (callback) => atomically((session) => callback(session.calls)));
404
+ this.alarms = new KvTable(physicalAlarm, alarmTable, (callback) => atomically((session) => callback(session.alarms)));
405
+ this.deliveries = new KvDeliveryTable(physicalAlarm, (callback) => atomically((session) => callback(session.deliveries)));
406
+ }
407
+ }
408
+ const transactionalSession = (kv) => {
409
+ const session = new KvSession(kv, (callback) => callback(session));
410
+ return session;
411
+ };
412
+ export const createKvDurabilityStorage = (storage) => {
413
+ const transaction = (callback) => storage.transaction((durableTransaction) => callback(transactionalSession(durableTransaction)));
414
+ const session = new KvSession(storage, transaction);
415
+ return {
416
+ calls: session.calls,
417
+ alarms: session.alarms,
418
+ deliveries: session.deliveries,
419
+ transaction,
420
+ };
421
+ };
@@ -0,0 +1,70 @@
1
+ import { type SerializedError } from './errors.js';
2
+ export type OperationLifecycleEntity = {
3
+ entityKind: 'operation';
4
+ operation: string;
5
+ id: string;
6
+ generation: string;
7
+ };
8
+ export type AlarmLifecycleEntity = {
9
+ entityKind: 'named_alarm';
10
+ alarm: string;
11
+ id: string;
12
+ generation: string;
13
+ };
14
+ export type FanoutLifecycleEntity = {
15
+ entityKind: 'fanout_delivery';
16
+ id: string;
17
+ target: string;
18
+ generation: string;
19
+ };
20
+ export type LifecycleEntity = OperationLifecycleEntity | AlarmLifecycleEntity | FanoutLifecycleEntity;
21
+ type AttemptSettled = {
22
+ type: 'attempt_settled';
23
+ timestamp: number;
24
+ attempt: number;
25
+ durationMs: number;
26
+ };
27
+ /** Best-effort metrics signal for queue lifecycle changes. */
28
+ export type DurabilityLifecycleEvent = ((OperationLifecycleEntity | FanoutLifecycleEntity) & {
29
+ type: 'registered';
30
+ timestamp: number;
31
+ attempt: 0;
32
+ }) | (AlarmLifecycleEntity & {
33
+ type: 'scheduled';
34
+ timestamp: number;
35
+ attempt: 0;
36
+ scheduledTime: number;
37
+ }) | (LifecycleEntity & {
38
+ type: 'attempt_started';
39
+ timestamp: number;
40
+ attempt: number;
41
+ }) | (LifecycleEntity & AttemptSettled & {
42
+ outcome: 'completed';
43
+ }) | (LifecycleEntity & AttemptSettled & {
44
+ outcome: 'retry_scheduled';
45
+ error: SerializedError;
46
+ nextAttemptAt: number;
47
+ }) | (LifecycleEntity & AttemptSettled & {
48
+ outcome: 'failed';
49
+ error: SerializedError;
50
+ }) | (LifecycleEntity & {
51
+ type: 'terminal';
52
+ timestamp: number;
53
+ attempt: number;
54
+ reason: 'attempts_exhausted' | 'dead_lettered';
55
+ error: SerializedError;
56
+ }) | {
57
+ type: 'purged';
58
+ entityKind: LifecycleEntity['entityKind'];
59
+ timestamp: number;
60
+ before: number;
61
+ count: number;
62
+ };
63
+ export type LifecycleHook = (event: DurabilityLifecycleEvent) => void | Promise<void>;
64
+ export type Emit = (event: DurabilityLifecycleEvent) => void;
65
+ /**
66
+ * Wraps a consumer hook so it can never affect queue state: synchronous throws
67
+ * and rejections are logged, and promises ride on `waitUntil` when available.
68
+ */
69
+ export declare const createEmitter: (hook: LifecycleHook | undefined, waitUntil: ((promise: Promise<unknown>) => void) | undefined) => Emit;
70
+ export {};
@@ -0,0 +1,36 @@
1
+ import { reportFailure } from './errors.js';
2
+ /**
3
+ * Wraps a consumer hook so it can never affect queue state: synchronous throws
4
+ * and rejections are logged, and promises ride on `waitUntil` when available.
5
+ */
6
+ export const createEmitter = (hook, waitUntil) => {
7
+ if (!hook) {
8
+ return () => undefined;
9
+ }
10
+ return (event) => {
11
+ const report = (error) => reportFailure('durability.lifecycle_hook.failed', {
12
+ entityKind: event.entityKind,
13
+ lifecycleType: event.type,
14
+ entityId: 'id' in event ? event.id : 'durability',
15
+ }, error);
16
+ try {
17
+ const result = hook(event);
18
+ if (result === undefined) {
19
+ return;
20
+ }
21
+ const caught = Promise.resolve(result).catch(report);
22
+ if (!waitUntil) {
23
+ return;
24
+ }
25
+ try {
26
+ waitUntil(caught);
27
+ }
28
+ catch (error) {
29
+ report(error);
30
+ }
31
+ }
32
+ catch (error) {
33
+ report(error);
34
+ }
35
+ };
36
+ };
package/dist/load.d.ts ADDED
@@ -0,0 +1,40 @@
1
+ import type { SerializedError } from './errors.js';
2
+ /** Completion counts and timings cover the same rolling observation window. */
3
+ export type ProcessingLoad = {
4
+ inFlight: number;
5
+ completed: number;
6
+ averageProcessingMs: number | null;
7
+ };
8
+ export type LoadSnapshot = {
9
+ observedAt: number;
10
+ windowMs: number;
11
+ inbound: ProcessingLoad;
12
+ outbound: ProcessingLoad & {
13
+ pendingDeliveries: number;
14
+ };
15
+ };
16
+ /** Success means accepted durably, not delivered to any target. */
17
+ export type EnqueueResult<T, E = SerializedError> = {
18
+ success: true;
19
+ value: T;
20
+ load: LoadSnapshot;
21
+ } | {
22
+ success: false;
23
+ error: E;
24
+ load: LoadSnapshot;
25
+ };
26
+ type Direction = 'inbound' | 'outbound';
27
+ /**
28
+ * Local advisory telemetry, reset on eviction. Sixty one-second buckets bound
29
+ * memory independently of traffic; in-flight counts are instantaneous.
30
+ */
31
+ export declare class RoutingLoad {
32
+ private readonly buckets;
33
+ private readonly active;
34
+ /** Begins an observed request and returns an idempotent completion callback. */
35
+ begin(direction: Direction): () => void;
36
+ /** Backlog comes from durable state, never reconstructed from telemetry. */
37
+ snapshot(pendingDeliveries: number): LoadSnapshot;
38
+ private processing;
39
+ }
40
+ export {};
package/dist/load.js ADDED
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Local advisory telemetry, reset on eviction. Sixty one-second buckets bound
3
+ * memory independently of traffic; in-flight counts are instantaneous.
4
+ */
5
+ export class RoutingLoad {
6
+ constructor() {
7
+ this.buckets = {
8
+ inbound: new Map(),
9
+ outbound: new Map(),
10
+ };
11
+ this.active = {
12
+ inbound: 0,
13
+ outbound: 0,
14
+ };
15
+ }
16
+ /** Begins an observed request and returns an idempotent completion callback. */
17
+ begin(direction) {
18
+ const startedAt = Date.now();
19
+ this.active[direction] += 1;
20
+ let finished = false;
21
+ return () => {
22
+ if (finished) {
23
+ return;
24
+ }
25
+ finished = true;
26
+ this.active[direction] -= 1;
27
+ const now = Date.now();
28
+ const second = Math.floor(now / 1000);
29
+ const slot = second % 60;
30
+ const previous = this.buckets[direction].get(slot);
31
+ const bucket = previous?.second === second
32
+ ? previous
33
+ : { second, count: 0, durationMs: 0 };
34
+ bucket.count += 1;
35
+ bucket.durationMs += Math.max(0, now - startedAt);
36
+ this.buckets[direction].set(slot, bucket);
37
+ };
38
+ }
39
+ /** Backlog comes from durable state, never reconstructed from telemetry. */
40
+ snapshot(pendingDeliveries) {
41
+ const now = Date.now();
42
+ return {
43
+ observedAt: now,
44
+ windowMs: 60000,
45
+ inbound: this.processing('inbound', now),
46
+ outbound: {
47
+ ...this.processing('outbound', now),
48
+ pendingDeliveries,
49
+ },
50
+ };
51
+ }
52
+ processing(direction, now) {
53
+ const second = Math.floor(now / 1000);
54
+ let completed = 0;
55
+ let durationMs = 0;
56
+ for (const bucket of this.buckets[direction].values()) {
57
+ if (bucket.second <= second && bucket.second > second - 60) {
58
+ completed += bucket.count;
59
+ durationMs += bucket.durationMs;
60
+ }
61
+ }
62
+ return {
63
+ inFlight: this.active[direction],
64
+ completed,
65
+ averageProcessingMs: completed === 0 ? null : durationMs / completed,
66
+ };
67
+ }
68
+ }
@@ -0,0 +1,50 @@
1
+ import type { DurableMigrations } from '@durability/storage';
2
+ export declare 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 declare const durabilityOperationMigrations: {
9
+ name: string;
10
+ up: string;
11
+ down: string;
12
+ }[];
13
+ /**
14
+ * Ordered SQLite migrations for the `durability_alarms` table owned by
15
+ * {@link DurabilityAlarms}. Applied automatically on construction.
16
+ */
17
+ export declare const durabilityNamedAlarmMigrations: {
18
+ name: string;
19
+ up: string;
20
+ down: string;
21
+ }[];
22
+ /**
23
+ * Ordered SQLite migrations for fanout manifests and deliveries. Applied
24
+ * automatically on construction.
25
+ */
26
+ export declare const durabilityFanoutMigrations: {
27
+ name: string;
28
+ up: string;
29
+ down: string;
30
+ }[];
31
+ /** Migration names changed by one migrate call. */
32
+ export type DurabilityMigrationResult = {
33
+ /** Migrations applied in ascending order. */
34
+ applied: string[];
35
+ /** Migrations reverted in descending order. */
36
+ rolledBack: string[];
37
+ };
38
+ export type MigrationCapability = 'operations' | 'namedAlarms' | 'fanout';
39
+ type MigrationStorage = Pick<DurableObjectStorage, 'sql' | 'transactionSync'>;
40
+ /**
41
+ * Moves one capability's schema to a target migration, applying or reverting as
42
+ * needed. `null` reverts every migration in the list; the shared migration
43
+ * table is dropped once no durability history remains.
44
+ *
45
+ * Each migration's `down` is stored alongside its history row so a later
46
+ * downgrade of the library can still revert it. Batches of migrations apply or
47
+ * revert atomically.
48
+ */
49
+ export declare const migrate: (storage: MigrationStorage, capability: MigrationCapability, migrations: DurableMigrations, target: string | null | undefined) => DurabilityMigrationResult;
50
+ export {};