durability 5.3.0 → 5.4.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 (53) hide show
  1. package/README.md +23 -14
  2. package/dist/alarms/index.d.ts +1 -1
  3. package/dist/alarms/index.js +6 -3
  4. package/dist/dev.d.ts +7 -3
  5. package/dist/dev.js +17 -11
  6. package/dist/durable-object-target.js +8 -4
  7. package/dist/errors.d.ts +13 -7
  8. package/dist/errors.js +34 -32
  9. package/dist/fanout/index.d.ts +1 -1
  10. package/dist/fanout/index.js +15 -13
  11. package/dist/lifecycle.d.ts +1 -0
  12. package/dist/lifecycle.js +2 -2
  13. package/dist/log/index.js +5 -2
  14. package/dist/memoize/index.js +6 -1
  15. package/dist/operations/index.js +8 -4
  16. package/dist/outbox/index.d.ts +1 -1
  17. package/dist/outbox/index.js +7 -4
  18. package/dist/policy.d.ts +1 -1
  19. package/dist/policy.js +2 -1
  20. package/dist/predicates.d.ts +9 -0
  21. package/dist/predicates.js +10 -0
  22. package/dist/routing/client.js +3 -4
  23. package/dist/routing/index.d.ts +1 -1
  24. package/dist/routing/index.js +14 -10
  25. package/dist/schedule/index.d.ts +2 -2
  26. package/dist/schedule/index.js +16 -12
  27. package/dist/scheduler/index.d.ts +16 -13
  28. package/dist/scheduler/index.js +39 -33
  29. package/dist/semaphore/client.js +2 -1
  30. package/dist/semaphore/index.d.ts +1 -1
  31. package/dist/semaphore/index.js +10 -5
  32. package/dist/semaphore/leases.d.ts +3 -2
  33. package/dist/semaphore/leases.js +3 -2
  34. package/dist/semaphore/queue-store.js +2 -1
  35. package/dist/semaphore/queue.d.ts +1 -1
  36. package/dist/semaphore/queue.js +34 -22
  37. package/dist/semaphore/server.js +31 -22
  38. package/dist/serialization.d.ts +3 -2
  39. package/dist/serialization.js +16 -13
  40. package/dist/socket/client.d.ts +21 -7
  41. package/dist/socket/client.js +12 -5
  42. package/dist/socket/index.d.ts +20 -13
  43. package/dist/socket/index.js +40 -18
  44. package/dist/socket/protocol.d.ts +37 -17
  45. package/dist/socket/protocol.js +30 -36
  46. package/dist/topology/client.js +9 -6
  47. package/dist/topology/index.d.ts +3 -3
  48. package/dist/topology/index.js +38 -33
  49. package/dist/topology/snapshot.d.ts +6 -5
  50. package/dist/topology/snapshot.js +5 -2
  51. package/dist/tracker/index.js +10 -2
  52. package/dist/tracker/source.d.ts +6 -2
  53. package/package.json +2 -2
@@ -1,6 +1,7 @@
1
1
  import * as v from 'valibot';
2
2
  import { traceFunction } from '../dev.js';
3
3
  import { DurableMemoLimitError, DurableMemoSerializationError, } from '../errors.js';
4
+ import { isNonEmptyString } from '../predicates.js';
4
5
  import { deserialize, serialize } from '../serialization.js';
5
6
  import { channelBindings, pendingGeneration, tableOwner, } from '../storage.js';
6
7
  /** The most keys one operation, alarm occurrence, or fanout delivery may memoize. */
@@ -45,12 +46,14 @@ export const createMemoize = (sql, table, ref) => {
45
46
  throw supersededError(key);
46
47
  }
47
48
  // Return what a replay would return, so later code sees one shape either way.
49
+ // SAFETY: `serialized` encodes `value`, and serialize rejects values JSON
50
+ // cannot round-trip, so this reads back as a T.
48
51
  return deserialize(serialized);
49
52
  };
50
53
  // Everything up to the callback runs synchronously, so a concurrent call
51
54
  // with the same key sees either the saved result or this key as running.
52
55
  const run = async (key, callback) => {
53
- if (typeof key !== 'string' || key === '') {
56
+ if (!isNonEmptyString(key)) {
54
57
  throw new TypeError('Memoize keys must be non-empty strings');
55
58
  }
56
59
  const lookup = v.parse(memoLookupSchema, sql
@@ -66,6 +69,8 @@ export const createMemoize = (sql, table, ref) => {
66
69
  WHERE owner = ? AND key = ? AND generation_id = ?) AS saved`, owner, ref.key, ref.generation, key, ref.key, ref.generation, ...channelBindings(table), ref.attempt, owner, ref.key, ref.generation)
67
70
  .toArray()[0]);
68
71
  if (lookup.result !== null) {
72
+ // SAFETY: only save() writes memos, with the result of the callback
73
+ // memoized under this key, which has type T on every attempt.
69
74
  return deserialize(lookup.result);
70
75
  }
71
76
  // A rescheduled or purged attempt must not start side effects it can never record.
@@ -152,6 +152,9 @@ class DurabilityCore {
152
152
  * returns a function that detaches it.
153
153
  */
154
154
  lifecycle(hook) {
155
+ // SAFETY: this instance emits only its purge event and events for its own
156
+ // calls, whose `operation` is a key of Handlers and whose result is that
157
+ // handler's return value.
155
158
  return __classPrivateFieldGet(this, _DurabilityCore_lifecycle, "f").add(hook);
156
159
  }
157
160
  /**
@@ -260,7 +263,7 @@ _DurabilityCore_engine = new WeakMap(), _DurabilityCore_channel = new WeakMap(),
260
263
  if (!eagerPermit) {
261
264
  return;
262
265
  }
263
- const onError = (error) => reportFailure('durability.background_execution.failed', { operation: input.operation, id: input.id }, error);
266
+ const onError = (cause) => reportFailure('durability.background_execution.failed', { operation: input.operation, id: input.id }, cause);
264
267
  const background = __classPrivateFieldGet(this, _DurabilityCore_instances, "m", _DurabilityCore_execute).call(this, key, eagerPermit)
265
268
  .then(() => __classPrivateFieldGet(this, _DurabilityCore_engine, "f").scheduleNextAlarm())
266
269
  .catch(onError);
@@ -307,6 +310,8 @@ async function _DurabilityCore_execute(key, eagerPermit) {
307
310
  }
308
311
  }, _DurabilityCore_start = function _DurabilityCore_start(call, eagerPermit) {
309
312
  const policy = __classPrivateFieldGet(this, _DurabilityCore_policy, "f").call(this, call.operation);
313
+ // SAFETY: the row was stored by the method for `call.operation`, which
314
+ // takes that handler's payload; rows of removed handlers find undefined.
310
315
  const handler = __classPrivateFieldGet(this, _DurabilityCore_handlers, "f")[call.operation];
311
316
  return __classPrivateFieldGet(this, _DurabilityCore_engine, "f").startExecution({
312
317
  table: __classPrivateFieldGet(this, _DurabilityCore_table, "f"),
@@ -354,7 +359,6 @@ async function _DurabilityCore_execute(key, eagerPermit) {
354
359
  }, eagerPermit);
355
360
  };
356
361
  traceMethods(DurabilityCore.prototype, 'Durability');
357
- // TypeScript cannot declare class members derived from a generic handler map,
358
- // so the constructor is typed separately; the constructor installs and reserves
359
- // every operation method at runtime.
362
+ // SAFETY: the constructor defines a method for every handler name on the
363
+ // instance, members TypeScript cannot declare from a generic handler map.
360
364
  export const Durability = DurabilityCore;
@@ -28,7 +28,7 @@ export type DurabilityOutboxConfig<Value> = SchedulerAttachment & {
28
28
  * every entry not marked with `retry()`; throwing retries the whole batch.
29
29
  * Sinks must be idempotent on `(key, version)` and keep the highest version.
30
30
  */
31
- publish(entries: OutboxEntry<Value>[]): unknown | Promise<unknown>;
31
+ publish(entries: OutboxEntry<Value>[]): void | Promise<void>;
32
32
  /** Defaults to 50. */
33
33
  maxBatchSize?: number;
34
34
  /**
@@ -15,6 +15,7 @@ import { OutboxTimeoutError, reportFailure, serializeError, } from '../errors.js
15
15
  import { durabilityOutboxMigrations } from './migrations.js';
16
16
  import { migrateCapability, } from '../migrations.js';
17
17
  import { assertPositiveInteger, } from '../policy.js';
18
+ import { isFunction, isNonEmptyString } from '../predicates.js';
18
19
  import { assertChannel, defaultChannel, engineFor, } from '../scheduler/index.js';
19
20
  import { deserialize, serialize } from '../serialization.js';
20
21
  import { claimAttempt, deleteAttempt, updateAttempt, } from '../storage.js';
@@ -108,7 +109,7 @@ export class DurabilityOutbox {
108
109
  /** The channel's one publish run, never one still waiting for a permit. */
109
110
  _DurabilityOutbox_running.set(this, void 0);
110
111
  __classPrivateFieldSet(this, _DurabilityOutbox_channel, assertChannel('Outbox', config.channel ?? defaultChannel), "f");
111
- if (typeof config.publish !== 'function') {
112
+ if (!isFunction(config.publish)) {
112
113
  throw new TypeError('Outbox requires a publish function');
113
114
  }
114
115
  __classPrivateFieldSet(this, _DurabilityOutbox_maxBatchSize, config.maxBatchSize ?? 50, "f");
@@ -150,7 +151,7 @@ export class DurabilityOutbox {
150
151
  }
151
152
  }
152
153
  _DurabilityOutbox_engine = new WeakMap(), _DurabilityOutbox_channel = new WeakMap(), _DurabilityOutbox_publish = new WeakMap(), _DurabilityOutbox_maxBatchSize = new WeakMap(), _DurabilityOutbox_batchDelayMs = new WeakMap(), _DurabilityOutbox_attemptTimeoutMs = new WeakMap(), _DurabilityOutbox_delay = new WeakMap(), _DurabilityOutbox_emit = new WeakMap(), _DurabilityOutbox_running = new WeakMap(), _DurabilityOutbox_instances = new WeakSet(), _DurabilityOutbox_stageIn = function _DurabilityOutbox_stageIn(sql, key, value) {
153
- if (typeof key !== 'string' || key.length === 0) {
154
+ if (!isNonEmptyString(key)) {
154
155
  throw new TypeError('Outbox keys must be non-empty strings');
155
156
  }
156
157
  const payload = serialize(value);
@@ -265,6 +266,8 @@ _DurabilityOutbox_engine = new WeakMap(), _DurabilityOutbox_channel = new WeakMa
265
266
  const entries = claims.map((row) => ({
266
267
  key: row.entry_key,
267
268
  version: row.version,
269
+ // SAFETY: #stageIn is the only writer of payloads, each serialized
270
+ // from a Value.
268
271
  value: deserialize(row.payload),
269
272
  attempt: row.attempt,
270
273
  stagedAt: row.created_at,
@@ -360,8 +363,8 @@ _DurabilityOutbox_engine = new WeakMap(), _DurabilityOutbox_channel = new WeakMa
360
363
  reportFailure('durability.outbox.retry_policy_failed', { channel: __classPrivateFieldGet(this, _DurabilityOutbox_channel, "f") }, error);
361
364
  }
362
365
  return infrastructureRetryMs;
363
- }, _DurabilityOutbox_deadline = async function _DurabilityOutbox_deadline(run) {
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")));
366
+ }, _DurabilityOutbox_deadline = function _DurabilityOutbox_deadline(run) {
367
+ return __classPrivateFieldGet(this, _DurabilityOutbox_engine, "f").timer.withTimeout(Promise.resolve().then(run), __classPrivateFieldGet(this, _DurabilityOutbox_attemptTimeoutMs, "f"), () => new OutboxTimeoutError(__classPrivateFieldGet(this, _DurabilityOutbox_attemptTimeoutMs, "f")));
365
368
  };
366
369
  (() => {
367
370
  stageWithin = (outbox, sql, key, value) => {
package/dist/policy.d.ts CHANGED
@@ -71,4 +71,4 @@ export declare const assertPositiveInteger: (name: string, value: number) => voi
71
71
  export type PolicyResolver<Method> = (name: string) => AttemptPolicy & {
72
72
  method: Method | undefined;
73
73
  };
74
- export declare const createPolicyResolver: <Method extends MethodPolicy>(options: ExecutionPolicyOptions, methods: Record<string, unknown>, methodSchema: v.GenericSchema<unknown, Method>) => PolicyResolver<Method>;
74
+ export declare const createPolicyResolver: <Input, Method extends MethodPolicy>(options: ExecutionPolicyOptions, methods: Partial<Record<string, NoInfer<Input>>>, methodSchema: v.GenericSchema<Input, Method>) => PolicyResolver<Method>;
package/dist/policy.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import * as v from 'valibot';
2
+ import { isFunction } from './predicates.js';
2
3
  import { exponential, jitter } from './utils.js';
3
- const functionSchema = () => v.custom((value) => typeof value === 'function');
4
+ const functionSchema = () => v.custom(isFunction);
4
5
  const retryOptionsSchema = v.object({
5
6
  delay: v.optional(functionSchema()),
6
7
  maxAttempts: v.optional(v.number()),
@@ -0,0 +1,9 @@
1
+ import type { Json, JsonObject } from './serialization.js';
2
+ export declare const isString: (value: unknown) => value is string;
3
+ export declare const isNonEmptyString: (value: unknown) => value is string;
4
+ export declare const isNumber: (value: unknown) => value is number;
5
+ export declare const isFunction: (value: unknown) => value is Function;
6
+ /** Excludes functions, unlike {@link isObjectOrFunction}. */
7
+ export declare const isObject: (value: unknown) => value is object;
8
+ export declare const isObjectOrFunction: (value: unknown) => value is object;
9
+ export declare const isJsonObject: (value: Json | undefined) => value is JsonObject;
@@ -0,0 +1,10 @@
1
+ // Runtime checks for values JavaScript callers, storage, and peers hand in
2
+ // without a TypeScript contract.
3
+ export const isString = (value) => typeof value === 'string';
4
+ export const isNonEmptyString = (value) => typeof value === 'string' && value.length > 0;
5
+ export const isNumber = (value) => typeof value === 'number';
6
+ export const isFunction = (value) => typeof value === 'function';
7
+ /** Excludes functions, unlike {@link isObjectOrFunction}. */
8
+ export const isObject = (value) => typeof value === 'object' && value !== null;
9
+ export const isObjectOrFunction = (value) => isObject(value) || isFunction(value);
10
+ export const isJsonObject = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
@@ -11,6 +11,7 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
11
11
  };
12
12
  var _RoutingClient_instances, _RoutingClient_config, _RoutingClient_observations, _RoutingClient_limit, _RoutingClient_width, _RoutingClient_lastResize, _RoutingClient_select, _RoutingClient_resize;
13
13
  import { RoutingError } from '../errors.js';
14
+ import { isNonEmptyString, isString } from '../predicates.js';
14
15
  /**
15
16
  * Transport-independent selection and observation. Every push invokes ONE
16
17
  * shard once. A false result is returned unchanged; transport failures throw.
@@ -44,10 +45,8 @@ export class RoutingClient {
44
45
  const target = __classPrivateFieldGet(this, _RoutingClient_config, "f").sharding
45
46
  ? await __classPrivateFieldGet(this, _RoutingClient_config, "f").sharding(input, context, observed)
46
47
  : __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) {
48
+ const address = isString(target) ? { shard: target } : target;
49
+ if (!address || !isNonEmptyString(address.shard)) {
51
50
  throw new RoutingError('Sharding must return a non-empty shard key or { shard, locationHint }');
52
51
  }
53
52
  const response = await __classPrivateFieldGet(this, _RoutingClient_config, "f").invoke(address, input);
@@ -7,7 +7,7 @@ export type { RoutingAddress, RoutingTarget, Sharding } from './client.js';
7
7
  export type RoutingSession<Input, Value, Context = unknown> = {
8
8
  push(input: Input, context?: Context): Promise<EnqueueResult<Value>>;
9
9
  setContext(context: TransformContext): {
10
- invoke(method: string, args: unknown[]): Promise<unknown>;
10
+ invoke(method: string, args: unknown[]): Promise<EnqueueResult<Value>>;
11
11
  };
12
12
  };
13
13
  export type DurabilityRoutingConfig<Target extends Rpc.DurableObjectBranded, Input, Value, Context = unknown> = DurableObjectTarget<Target> & {
@@ -1,8 +1,9 @@
1
1
  import { createTransformStub, } from '@durability/transforms';
2
2
  import { resolveNamespace, } from '../durable-object-target.js';
3
3
  import { RoutingError } from '../errors.js';
4
+ import { isObject } from '../predicates.js';
4
5
  import { RoutingLoad } from './load.js';
5
- import { RoutingClient } from './client.js';
6
+ import { RoutingClient, } from './client.js';
6
7
  /**
7
8
  * Inside a DO, attach this local load observer to a fanout capability. Outside
8
9
  * the DO, client() routes calls to an application-owned class using ordinary
@@ -10,7 +11,7 @@ import { RoutingClient } from './client.js';
10
11
  */
11
12
  export class DurabilityRouting extends RoutingLoad {
12
13
  static client(config) {
13
- const client = new RoutingClient({
14
+ const clientConfig = {
14
15
  invoke: (address, input) => {
15
16
  const namespace = resolveNamespace(config, (message) => new RoutingError(message));
16
17
  const stub = namespace.getByName(address.shard, address.locationHint === undefined
@@ -18,11 +19,14 @@ export class DurabilityRouting extends RoutingLoad {
18
19
  : { locationHint: address.locationHint });
19
20
  return config.invoke(stub, input);
20
21
  },
21
- ...(config.sharding === undefined ? {} : { sharding: config.sharding }),
22
- ...(config.softBacklogLimit === undefined
23
- ? {}
24
- : { softBacklogLimit: config.softBacklogLimit }),
25
- });
22
+ };
23
+ if (config.sharding !== undefined) {
24
+ clientConfig.sharding = config.sharding;
25
+ }
26
+ if (config.softBacklogLimit !== undefined) {
27
+ clientConfig.softBacklogLimit = config.softBacklogLimit;
28
+ }
29
+ const client = new RoutingClient(clientConfig);
26
30
  const session = {
27
31
  push: (input, context) => client.push(input, context),
28
32
  setContext: (context) => ({
@@ -32,11 +36,11 @@ export class DurabilityRouting extends RoutingLoad {
32
36
  }
33
37
  const positional = args[1];
34
38
  if (positional !== undefined &&
35
- (positional === null ||
36
- typeof positional !== 'object' ||
37
- Array.isArray(positional))) {
39
+ (!isObject(positional) || Array.isArray(positional))) {
38
40
  throw new TypeError('Routing context must be an object when combined with transform context');
39
41
  }
42
+ // SAFETY: the transform stub forwards the arguments of a typed `push`,
43
+ // so args are [Input, Context?]; transform context only adds keys.
40
44
  return client.push(args[0], { ...positional, ...context });
41
45
  },
42
46
  }),
@@ -116,12 +116,12 @@ export type DurabilityScheduleConfig = SchedulerAttachment & {
116
116
  */
117
117
  nextOccurrence(expression: string, after: number): number | undefined;
118
118
  /** The work of one tick. Throwing or timing out makes the run `errored`. */
119
- run(run: ScheduledRunContext): unknown;
119
+ run(run: ScheduledRunContext): void | Promise<void>;
120
120
  /**
121
121
  * Receives each run's outcome at least once. Returning acknowledges it and
122
122
  * deletes the run's row; throwing retries it with `outcomeRetries`.
123
123
  */
124
- onOutcome(run: ScheduledOutcomeDelivery, outcome: ScheduledRunOutcome): unknown;
124
+ onOutcome(run: ScheduledOutcomeDelivery, outcome: ScheduledRunOutcome): void | Promise<void>;
125
125
  /** Runs in flight at once; later runs wait durably in order. Defaults to 10. */
126
126
  maxConcurrentRuns?: number;
127
127
  /** Maximum duration of one run. Defaults to 15 minutes. */
@@ -16,6 +16,7 @@ import { reportFailure, ScheduledOutcomeTimeoutError, ScheduledRunInterruptedErr
16
16
  import { durabilityScheduleMigrations } from './migrations.js';
17
17
  import { migrateCapability, } from '../migrations.js';
18
18
  import { assertPositiveInteger, } from '../policy.js';
19
+ import { isFunction, isNonEmptyString, isNumber, isObject, } from '../predicates.js';
19
20
  import { assertChannel, defaultChannel, engineFor, } from '../scheduler/index.js';
20
21
  import { exponential, jitter } from '../utils.js';
21
22
  const runsTable = {
@@ -105,11 +106,11 @@ const assertJitter = (name, value) => {
105
106
  }
106
107
  };
107
108
  const pickJitter = (jitterMs = 0) => {
108
- if (typeof jitterMs === 'number') {
109
+ if (isNumber(jitterMs)) {
109
110
  assertJitter('Schedule jitterMs', jitterMs);
110
111
  return jitterMs;
111
112
  }
112
- if (typeof jitterMs !== 'object' || jitterMs === null) {
113
+ if (!isObject(jitterMs)) {
113
114
  throw new TypeError('Schedule jitterMs must be a number or { maxMs }');
114
115
  }
115
116
  assertJitter('Schedule jitterMs.maxMs', jitterMs.maxMs);
@@ -155,7 +156,7 @@ export class DurabilitySchedule {
155
156
  _DurabilitySchedule_wakeSleeper.set(this, void 0);
156
157
  __classPrivateFieldSet(this, _DurabilitySchedule_channel, assertChannel('DurabilitySchedule', config.channel ?? defaultChannel), "f");
157
158
  for (const name of ['nextOccurrence', 'run', 'onOutcome']) {
158
- if (typeof config[name] !== 'function') {
159
+ if (!isFunction(config[name])) {
159
160
  throw new TypeError(`Schedule requires a ${name} function`);
160
161
  }
161
162
  }
@@ -219,7 +220,7 @@ export class DurabilitySchedule {
219
220
  */
220
221
  async set(definition) {
221
222
  const { expression, version } = definition;
222
- if (typeof expression !== 'string' || expression.length === 0) {
223
+ if (!isNonEmptyString(expression)) {
223
224
  throw new TypeError('Schedule expression must be a non-empty string');
224
225
  }
225
226
  assertNonNegative('Schedule version', version);
@@ -572,9 +573,9 @@ async function _DurabilitySchedule_reserveSlots(mark) {
572
573
  controller.abort(error);
573
574
  return error;
574
575
  })
575
- .then(() => ({ status: 'complete' }), (error) => ({
576
+ .then(() => ({ status: 'complete' }), (cause) => ({
576
577
  status: 'errored',
577
- error: serializeError(error),
578
+ error: serializeError(cause),
578
579
  }))
579
580
  .then((outcome) => __classPrivateFieldGet(this, _DurabilitySchedule_instances, "m", _DurabilitySchedule_record).call(this, run, outcome, startedAt))
580
581
  .catch((error) => reportFailure('durability.schedule.record_failed', { scheduledTime }, error));
@@ -597,13 +598,16 @@ async function _DurabilitySchedule_reserveSlots(mark) {
597
598
  return;
598
599
  }
599
600
  const entity = __classPrivateFieldGet(this, _DurabilitySchedule_instances, "m", _DurabilitySchedule_entity).call(this, run.scheduledTime);
600
- __classPrivateFieldGet(this, _DurabilitySchedule_emit, "f").call(this, {
601
+ const settled = {
601
602
  ...entity,
602
603
  type: 'settled',
603
604
  outcome: outcome.status,
604
605
  durationMs: Math.max(0, entity.timestamp - startedAt),
605
- ...(error === undefined ? {} : { error }),
606
- });
606
+ };
607
+ if (error !== undefined) {
608
+ settled.error = error;
609
+ }
610
+ __classPrivateFieldGet(this, _DurabilitySchedule_emit, "f").call(this, settled);
607
611
  __classPrivateFieldGet(this, _DurabilitySchedule_instances, "m", _DurabilitySchedule_deliver).call(this, run, outcome, 1);
608
612
  }, _DurabilitySchedule_deliverDue = function _DurabilitySchedule_deliverDue() {
609
613
  const due = v.parse(v.array(runRowSchema), __classPrivateFieldGet(this, _DurabilitySchedule_engine, "f").sql
@@ -637,14 +641,14 @@ async function _DurabilitySchedule_reserveSlots(mark) {
637
641
  sql.exec(`DELETE FROM durability_schedule_runs
638
642
  WHERE channel = ? AND scheduled_time = ?`, __classPrivateFieldGet(this, _DurabilitySchedule_channel, "f"), run.scheduledTime);
639
643
  });
640
- }, _DurabilitySchedule_failDelivery = async function _DurabilitySchedule_failDelivery(run, attempt, failure) {
641
- const error = serializeError(failure);
644
+ }, _DurabilitySchedule_failDelivery = async function _DurabilitySchedule_failDelivery(run, attempt, cause) {
645
+ const error = serializeError(cause);
642
646
  if (attempt >= __classPrivateFieldGet(this, _DurabilitySchedule_maxOutcomeAttempts, "f")) {
643
647
  await __classPrivateFieldGet(this, _DurabilitySchedule_engine, "f").transaction((sql) => {
644
648
  sql.exec(`DELETE FROM durability_schedule_runs
645
649
  WHERE channel = ? AND scheduled_time = ?`, __classPrivateFieldGet(this, _DurabilitySchedule_channel, "f"), run.scheduledTime);
646
650
  });
647
- reportFailure('durability.schedule.outcome_dead_lettered', { scheduledTime: run.scheduledTime, attempt }, failure);
651
+ reportFailure('durability.schedule.outcome_dead_lettered', { scheduledTime: run.scheduledTime, attempt }, cause);
648
652
  __classPrivateFieldGet(this, _DurabilitySchedule_emit, "f").call(this, {
649
653
  ...__classPrivateFieldGet(this, _DurabilitySchedule_instances, "m", _DurabilitySchedule_entity).call(this, run.scheduledTime),
650
654
  type: 'dead_lettered',
@@ -87,27 +87,28 @@ export type ChannelParticipant = Participant & {
87
87
  channelTables?: readonly string[];
88
88
  };
89
89
  /** Rejects a channel name a helper would otherwise store rows under. */
90
- export declare const assertChannel: (helper: string, channel: unknown) => string;
90
+ export declare const assertChannel: (helper: string, channel: string) => string;
91
91
  /**
92
92
  * Called after a record may have settled. Successful completions pass the
93
93
  * executed row because some tables delete it on success; other changes pass
94
94
  * nothing and listeners re-read storage.
95
95
  */
96
- export type SettlementListener = (completed?: ExecutionSpec['row']) => void;
96
+ export type SettlementListener = (completed?: ExecutionRow) => void;
97
97
  export type ActiveExecution = {
98
98
  generation: string;
99
99
  createdAt: number;
100
100
  settled: Promise<void>;
101
101
  controller?: AbortController;
102
102
  };
103
+ type ExecutionRow = {
104
+ generation_id: string;
105
+ created_at: number;
106
+ };
103
107
  /** Everything that differs between running a durable operation and a named alarm attempt. */
104
- export type ExecutionSpec = {
108
+ export type ExecutionSpec<Result> = {
105
109
  table: DurableTable;
106
110
  key: string;
107
- row: {
108
- generation_id: string;
109
- created_at: number;
110
- };
111
+ row: ExecutionRow;
111
112
  label: string;
112
113
  entity: LifecycleEntity;
113
114
  active: Map<string, ActiveExecution>;
@@ -117,15 +118,15 @@ export type ExecutionSpec = {
117
118
  includeResult?: boolean;
118
119
  exhaustedError: () => Error;
119
120
  timeoutError: () => Error;
120
- invoke: (attempt: number, signal: AbortSignal) => unknown;
121
+ invoke: (attempt: number, signal: AbortSignal) => Result | Promise<Result>;
121
122
  /**
122
123
  * Persists a successful attempt and returns its settlement timestamp, or
123
124
  * undefined when a newer generation won. May throw to turn the success into
124
125
  * a failure.
125
126
  */
126
- complete: (result: unknown, attempt: number) => number | undefined;
127
+ complete: (result: Result, attempt: number) => number | undefined;
127
128
  /** Kind-specific terminal rule beyond non-retryable errors and exhausted attempts. */
128
- isTerminal: (error: unknown) => boolean;
129
+ isTerminal: (cause: unknown) => boolean;
129
130
  };
130
131
  /**
131
132
  * Shared machinery behind {@link DurabilityScheduler}: transactions, the physical
@@ -179,7 +180,7 @@ export declare class Engine {
179
180
  * are kept and looked at again later, since their owner may return.
180
181
  */
181
182
  private postponeUnattachedChannels;
182
- waitUntil(promise: Promise<unknown>, onError: (error: unknown) => void): void;
183
+ waitUntil(promise: Promise<unknown>, onError: (cause: unknown) => void): void;
183
184
  /**
184
185
  * The owning Durable Object's ID. The public context type omits it, but the
185
186
  * `DurableObjectState` applications pass at runtime carries it.
@@ -188,6 +189,7 @@ export declare class Engine {
188
189
  emitter<Event extends {
189
190
  entityKind: string;
190
191
  type: string;
192
+ id?: string;
191
193
  } = DurabilityLifecycleEvent>(hook: ((event: Event) => void | Promise<void>) | undefined): (event: Event) => void;
192
194
  /** Applies a helper's SQLite migrations. */
193
195
  migrateSchema(capability: MigrationCapability, migrations: DurableMigrations): void;
@@ -223,7 +225,7 @@ export declare class Engine {
223
225
  /** In-memory only: listeners never survive eviction. */
224
226
  watch(table: DurableTable, key: string, listener: SettlementListener): () => void;
225
227
  /** Call only after the change has committed. */
226
- notify(table: DurableTable, key: string, completed?: ExecutionSpec['row']): void;
228
+ notify(table: DurableTable, key: string, completed?: ExecutionRow): void;
227
229
  tryAcquirePermit(): (() => void) | undefined;
228
230
  acquirePermit(): Promise<() => void>;
229
231
  private createRelease;
@@ -258,7 +260,7 @@ export declare class Engine {
258
260
  * settled: nothing can stop a handler, and one that never settles would
259
261
  * otherwise keep its retry from ever starting.
260
262
  */
261
- startExecution(spec: ExecutionSpec, eagerPermit?: () => void): Promise<void>;
263
+ startExecution<Result>(spec: ExecutionSpec<Result>, eagerPermit?: () => void): Promise<void>;
262
264
  private failExhausted;
263
265
  private settleFailure;
264
266
  }
@@ -310,3 +312,4 @@ export declare class DurabilityScheduler {
310
312
  }
311
313
  /** Resolves the engine a helper attaches to: the object's one scheduler. */
312
314
  export declare const engineFor: (attachment: SchedulerAttachment) => Engine;
315
+ export {};