durability 5.2.1 → 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 (56) hide show
  1. package/README.md +42 -18
  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 -26
  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/migrations.js +37 -37
  16. package/dist/operations/index.js +8 -4
  17. package/dist/outbox/index.d.ts +1 -1
  18. package/dist/outbox/index.js +7 -17
  19. package/dist/policy.d.ts +1 -1
  20. package/dist/policy.js +2 -1
  21. package/dist/predicates.d.ts +9 -0
  22. package/dist/predicates.js +10 -0
  23. package/dist/routing/client.js +3 -4
  24. package/dist/routing/index.d.ts +1 -1
  25. package/dist/routing/index.js +14 -10
  26. package/dist/schedule/index.d.ts +15 -3
  27. package/dist/schedule/index.js +55 -36
  28. package/dist/scheduler/index.d.ts +35 -14
  29. package/dist/scheduler/index.js +78 -74
  30. package/dist/semaphore/client.js +2 -1
  31. package/dist/semaphore/index.d.ts +1 -1
  32. package/dist/semaphore/index.js +10 -5
  33. package/dist/semaphore/leases.d.ts +3 -2
  34. package/dist/semaphore/leases.js +3 -2
  35. package/dist/semaphore/queue-store.js +2 -1
  36. package/dist/semaphore/queue.d.ts +1 -1
  37. package/dist/semaphore/queue.js +36 -37
  38. package/dist/semaphore/server.js +50 -32
  39. package/dist/serialization.d.ts +3 -2
  40. package/dist/serialization.js +16 -13
  41. package/dist/shared-timer.d.ts +27 -0
  42. package/dist/shared-timer.js +191 -0
  43. package/dist/socket/client.d.ts +21 -7
  44. package/dist/socket/client.js +37 -27
  45. package/dist/socket/index.d.ts +20 -13
  46. package/dist/socket/index.js +40 -18
  47. package/dist/socket/protocol.d.ts +37 -17
  48. package/dist/socket/protocol.js +30 -36
  49. package/dist/topology/client.js +36 -19
  50. package/dist/topology/index.d.ts +3 -3
  51. package/dist/topology/index.js +40 -49
  52. package/dist/topology/snapshot.d.ts +6 -5
  53. package/dist/topology/snapshot.js +5 -2
  54. package/dist/tracker/index.js +18 -7
  55. package/dist/tracker/source.d.ts +6 -2
  56. package/package.json +2 -2
package/README.md CHANGED
@@ -164,7 +164,7 @@ export class Subscription extends DurableObject<Env> {
164
164
  }
165
165
  ```
166
166
 
167
- Scheduling a name again replaces its pending occurrence. If that name is already running, the current handler continues and the replacement runs afterward. Different names may run concurrently, but one name never has more than one active handler in the same instance.
167
+ Scheduling a name again replaces its pending occurrence. If that name is already running, the current handler continues and the replacement runs afterward. Different names may run concurrently, but one name never has more than one attempt in progress in the same instance. A handler that ignores the abort of a timed-out attempt may still be running beside the next one.
168
168
 
169
169
  Named alarms inside the scheduler's `alarmMinDelayMs` window start from an in-memory timer at their requested time. The option accepts 1 to 15 seconds and defaults to 15 seconds; the scheduler never sets the physical alarm sooner than that delay; the physical alarm remains as a durable fallback for restarts. If concurrency capacity is full when the timer fires, execution waits in the shared FIFO queue. The scheduling method resolves after persistence and never waits for the handler to finish.
170
170
 
@@ -380,7 +380,7 @@ const durability = new Durability({
380
380
  });
381
381
  ```
382
382
 
383
- Each attempt receives its own `AbortSignal`. A timed-out operation follows the normal retry policy; a timed-out named alarm is terminal unless `retryTimeouts` is set. If a handler ignores abort, its in-memory lock and concurrency permit remain held until it actually settles, so a same-isolate retry cannot overlap it.
383
+ Each attempt receives its own `AbortSignal`. A timed-out operation follows the normal retry policy; a timed-out named alarm is terminal unless `retryTimeouts` is set. A timeout ends the attempt: its concurrency permit is returned and the next attempt starts on schedule, whether or not the handler has stopped. Nothing can stop a running handler, so one that ignores abort keeps running beside the retry; its result is discarded, and once the retry has started its `memoize` calls reject. Stop work when the signal aborts, and make side effects safe to repeat.
384
384
 
385
385
  Throw `NonRetryableError` to move work directly to `failed` without another attempt. Errors named `NonRetryableError` from other packages, such as `cloudflare:workflows`, are recognized too.
386
386
 
@@ -437,6 +437,20 @@ const removedAlarms = await this.alarms.purgeBefore(retentionCutoff);
437
437
 
438
438
  The purge runs in one transaction. It best-effort aborts matching active handlers, but cannot force an abort-ignoring handler to stop. Operation IDs can be reused immediately; a late old generation cannot overwrite the replacement record.
439
439
 
440
+ ## In-memory timeouts
441
+
442
+ The runtime makes the global `setTimeout` throw `QuotaExceededError` once 10,000 timers are pending in one Durable Object. The helpers keep their own timeouts in a min-heap behind one native timer, and `scheduler.setTimeout` puts yours in the same heap, so the number pending does not count against that limit:
443
+
444
+ ```ts
445
+ const cancel = this.scheduler.setTimeout(() => {
446
+ this.sockets.get(id)?.close(4000, 'Idle');
447
+ }, 30_000);
448
+
449
+ cancel();
450
+ ```
451
+
452
+ It returns a cancel function instead of an id. Callbacks due at the same time run one after another in one task, and one that throws is reported as `durability.timer.callback_failed` instead of becoming an uncaught exception. The timeout exists only in memory, so an eviction drops it; use a named alarm for work that must still run after one.
453
+
440
454
  ## Experimental options
441
455
 
442
456
  These options, methods, and capabilities are opt-in: none takes effect unless you set, call, or construct it, so leaving them alone keeps every behavior described above. Their names and behavior may change in a minor release. Scheduler options can also be passed to a helper configured with `context`.
@@ -522,9 +536,10 @@ export class Cron extends DurableObject<Env> {
522
536
  }
523
537
  ```
524
538
 
525
- - **Versions.** `set({ expression, version })` stores the schedule and its next tick only when `version` is higher than the stored one, and resolves `true` when it did. A lower version is ignored. The same version changes nothing but reconciles the physical alarm, so resending it repairs a lost alarm. The expression is opaque; only `nextOccurrence(expression, after)` reads it, and it must return a safe integer after `after`, or `undefined` to stop ticking. `get()` returns `{ expression, version, jitterMs, nextAt }`, where `nextAt` is the next tick's nominal time, or `undefined` when no schedule is live.
539
+ - **Versions.** `set({ expression, version })` stores the schedule and its next tick only when `version` is higher than the stored one, and resolves `true` when it did. A lower version is ignored. The same version changes nothing but reconciles the physical alarm, so resending it repairs a lost alarm. The expression is opaque; only `nextOccurrence(expression, after)` reads it, and it must return a safe integer after `after`, or `undefined` to stop ticking. It must be synchronous; when its answers change, call `reschedule()`. `get()` returns `{ expression, version, jitterMs, nextAt }`, where `nextAt` is the next tick's nominal time, or `undefined` when no schedule is live.
526
540
  - **Jitter.** `set({ expression, version, jitterMs })` delays every tick by one fixed offset, so many objects sharing a popular expression do not all fire at the same instant. `jitterMs` is either a non-negative integer, the offset itself, or `{ maxMs }`, which picks an offset uniformly in `[0, maxMs]` when the version is stored. It defaults to 0, and both forms are at most 2^31 - 1 ms. The offset is stored in the schedule's row, so it costs no write per run, and resending the same version keeps it; only a new version picks a new one. A tick's nominal time `scheduledTime` is what `nextOccurrence` returned, and it fires at `dueAt`, which is `scheduledTime + jitterMs`. `idempotencyKey` derives from `scheduledTime`, and the next tick is always searched from nominal times, so the offset never drifts. Keep `jitterMs` below the expression's interval; durability cannot know the interval of an opaque expression. A larger offset is allowed: every tick still fires once, in nominal order, each `jitterMs` after its nominal time, even when that is after the next tick's nominal time.
527
541
  - **Cancel.** `cancel(version?)` stops future ticks and resolves `true` when a schedule was live. Runs already due or running still finish and report. With a version, the cancel is ignored when the stored version is higher, and is otherwise kept as a one-row tombstone so a delayed `set` of that version or lower cannot revive the schedule.
542
+ - **Reschedule.** `nextOccurrence` may give different answers over time, for example when it reads which ticks the object owns from its own storage. Durability stores the next tick when it fires the previous one, so after such a change the stored tick can be later than one the object now has to fire. `reschedule()` asks `nextOccurrence` again and resolves `true` when the stored next tick changed, moving the alarm earlier or later in the same transaction, as a tick does, so a tick less than `alarmMinDelayMs` away fires from the in-memory timer. It searches from `now - jitterMs`, so the new next tick is the first whose `dueAt` is still ahead: a tick whose nominal time passed but whose `dueAt` has not is kept, and ticks whose `dueAt` already passed are skipped, not collapsed into a catch-up run. A stored tick that is already due is left to the alarm, which fires it and then asks `nextOccurrence` as usual. `reschedule()` resolves `false` in that case, when nothing changed, and when no schedule is live, cancelled or never set; it then changes nothing. Only the next tick is rewritten: the version, the stored jitter (a `{ maxMs }` offset is not picked again), a versioned cancel's tombstone, runs already due, queued or running, and outcome retries stay as they were, so `set` and `cancel` keep ordering by version. Use it when the version cannot change, for example because it also orders cancels. No tick fires twice across a reschedule: every tick that fired had a `dueAt` at or before now, and the new next tick's `dueAt` is after now. When `nextOccurrence` now returns `undefined`, ticking stops as it does after a tick, and a later `reschedule()` can resume it.
528
543
  - **One tick, one run.** A tick inserts its run in the transaction that advances the stored next tick, so a replayed or duplicated alarm finds the cursor already moved and cannot fire the tick again; deduplication needs no finished-run records. When ticks were missed, for example while the object was down, they collapse into one run for the earliest missed time, and the next tick is the first whose `dueAt` is after now. A `nextOccurrence` that throws or returns an invalid time rolls the tick back and fails the alarm run, which is retried at `alarmMinDelayMs` and reported through `onAlarmRetry`.
529
544
  - **Runs.** `run({ scheduledTime, dueAt, idempotencyKey, signal })` starts outside the alarm pass that recorded it, so a long run never delays later ticks. `idempotencyKey` is `<objectId>:<scheduledTime>`; on a named channel it ends with `:` and the JSON-encoded channel name, such as `<objectId>:<scheduledTime>:"library"`, so it never equals a default-channel key or another channel's. At most `maxConcurrentRuns` (default 10) are in flight; later runs wait durably in tick order. This limit is separate from the scheduler's `alarmConcurrency`. A run that throws, or exceeds `runTimeoutMs` (default 15 minutes, which aborts its `signal`), is `errored`. A run is attempted once and never retried. A timed-out run keeps its slot until its handler actually settles.
530
545
  - **Keeping the object alive.** While runs or outcome deliveries are in flight, the alarm pass stays pending, so an alarm invocation stays open and holds the object in memory; it fires the next ticks and outcome retries itself, at their exact times. Before the wall-time limit the scheduler hands off at `alarmHandoffMs`, and the next alarm joins the same loop. A tick started by an in-memory timer is joined by the next physical alarm. Other helpers on the same scheduler still run on each alarm pass, but work of theirs that becomes due during the hold waits for it unless the scheduler uses `liveTimers`.
@@ -651,9 +666,9 @@ export class TodoList extends DurableObject<Env> {
651
666
  readonly socket = new DurabilitySocket({
652
667
  context: this.ctx,
653
668
  inbound: {
654
- // Bare handlers take no input (or `unknown` input they validate themselves).
655
- list: () => [...this.todos.values()],
656
- // Typed input requires a Standard Schema; here the handler is a durable operation.
669
+ // Every handler validates its input; `list` takes none.
670
+ list: { input: v.undefined(), handle: () => [...this.todos.values()] },
671
+ // Here the handler is a durable operation.
657
672
  createTodo: {
658
673
  input: v.object({ id: v.string(), payload: TodoSchema }),
659
674
  handle: this.durability.createTodo,
@@ -729,7 +744,7 @@ export default {
729
744
  };
730
745
  ```
731
746
 
732
- An inbound handler is either a bare function, which receives no input or `unknown` input it validates itself, or `{ input, handle }`, where `input` is any [Standard Schema](https://standardschema.dev) validator (zod, Valibot, ArkType, …) and `handle` declares its parameter type. A bare function that claims a typed parameter does not compile. Handlers receive `call.metadata`, the value `metadata(request)` returned at upgrade time; it is stored in the WebSocket attachment, so it survives hibernation. The fronting Worker is responsible for authentication and for routing the upgrade to the right object; the socket does no authorization of its own. `metadata` must be assignable to every `SocketCall<…>` annotation the handlers declare.
747
+ Every inbound handler is `{ input, handle }`, where `input` is any [Standard Schema](https://standardschema.dev) validator (zod, Valibot, ArkType, …) and `handle` receives the schema's output. A handler without a schema, or whose `handle` does not accept the schema's output, does not compile. A method that takes no input uses a schema for `undefined`, such as Valibot's `v.undefined()`, and the client calls it without arguments. Handlers receive `call.metadata`, the value `metadata(request)` returned at upgrade time; it is stored in the WebSocket attachment, so it survives hibernation. The fronting Worker is responsible for authentication and for routing the upgrade to the right object; the socket does no authorization of its own. `metadata` must be assignable to every `SocketCall<…>` annotation the handlers declare, and is required when any of them excludes `undefined`, so a handler never runs without the metadata it declares. A connection accepted before the socket had `metadata`, such as one from before the deploy that added it, carries none: its next frame closes it with code `1012` before reaching a handler, and the browser client reconnects with backoff so the new upgrade captures it.
733
748
 
734
749
  Every outbound event is persisted to `durability_socket_events` with a sequence number before it is pushed. A reconnecting client subscribes from the last sequence it saw: events still within `retention` (default 1000) are replayed in order, otherwise the client is told to resync and should rebuild its state from an inbound snapshot call. Payloads must be JSON. Keep-alive pings are answered by the runtime through `setWebSocketAutoResponse`, so idle connections never wake the object. Frames over 1 MiB are rejected; malformed frames close the connection with code `4002`.
735
750
 
@@ -741,7 +756,9 @@ Like the other helpers, `DurabilitySocket` takes a `channel` option, `default` u
741
756
  readonly librarySocket = new DurabilitySocket({
742
757
  context: this.ctx,
743
758
  channel: 'durable-alerts',
744
- inbound: { list: () => this.alerts.list() },
759
+ inbound: {
760
+ list: { input: v.undefined(), handle: () => this.alerts.list() },
761
+ },
745
762
  outbound: { updated: event<Alert>() },
746
763
  });
747
764
 
@@ -852,7 +869,7 @@ readonly socket = new DurabilitySocket({
852
869
  inbound: {
853
870
  work: {
854
871
  input: v.object({ cursor: v.optional(v.string()) }),
855
- handle: (query: { cursor?: string }) => this.tracker.records(query),
872
+ handle: (query) => this.tracker.records(query),
856
873
  },
857
874
  },
858
875
  outbound: { settled: event<DurabilityOperationEvent<typeof handlers>>() },
@@ -970,7 +987,7 @@ new DurabilitySemaphore({
970
987
  - **`under`** — a reserve inside the limit is kept for leases; grants may use at most `limit - reserve`. Still never exceeds the limit, and leases have guaranteed headroom. The reserve never takes the last permit: with a reserve at or above the limit (including after lowering the limit), grants keep one, so groups excluded from leases and clients without lease support still make progress.
971
988
  - **`over`** — leases come from a separate budget above the limit (the original gatekeeper behaviour); the effective ceiling is `limit + extra`.
972
989
 
973
- Leases are issued only to clients that report `leases` (both default and named queues do), to groups without their own limit unless `limitedGroups: 'withinGroupLimit'`, and only to a client that holds no undrawn permits for that group. Each round shares the remaining lease budget equally among candidates, oldest demand first, up to `permitsPerLease`; with fewer permits left than candidates, the oldest get one each. When a round leaves demand unserved, the holder marks its replies `contended`, and each client returns the undrawn permits of leases in groups where it has nothing queued, so an idle lease cannot keep other clients waiting. A client that stops talking to the holder keeps its lease until `ttlMs`. Reports (`drawn`, `released` high-water marks) heartbeat a lease, and the queue reports a lease with permits in use at half its lifetime even when nothing else is happening, so long-running work keeps its permits counted; a lease unreported for `ttlMs` is retired rather than forgotten: its client may be cut off from the holder with work still running, so, like a claimed grant permit, its footprint stays counted until the client reports what it drew and released. The queue keeps reporting a stopped lease until the holder settles it. A report for a lease the holder never knew is answered retired and its live footprint charged against that round. On the client, a drawn permit is one-shot: releasing the item returns footprint to the holder but never makes the permit drawable again. Lowering a group's eligibility, or the limit, retires leases on the next round. A retired lease stops drawing at once but stays counted in full until its client confirms how much it drew, since it may have drawn after its last report.
990
+ Leases are issued only to clients that report `leases` (both default and named queues do), to groups without their own limit unless `limitedGroups: 'withinGroupLimit'`, and only to a client that holds no undrawn permits for that group. A group's limit counts its grants and the footprint of its leases together, in every provisioning mode and including retired leases not yet confirmed, so a leased group never admits past its limit. Each round shares the remaining lease budget equally among candidates, oldest demand first, up to `permitsPerLease`; with fewer permits left than candidates, the oldest get one each. When a round leaves demand unserved, the holder marks its replies `contended`, and each client returns the undrawn permits of leases in groups where it has nothing queued, so an idle lease cannot keep other clients waiting. A client that stops talking to the holder keeps its lease until `ttlMs`. Reports (`drawn`, `released` high-water marks) heartbeat a lease, and the queue reports a lease with permits in use at half its lifetime even when nothing else is happening, so long-running work keeps its permits counted; a lease unreported for `ttlMs` is retired rather than forgotten: its client may be cut off from the holder with work still running, so, like a claimed grant permit, its footprint stays counted until the client reports what it drew and released. The queue keeps reporting a stopped lease until the holder settles it. A report for a lease the holder never knew is answered retired and its live footprint charged against that round; the report does not name a group, so no group limit is charged. On the client, a drawn permit is one-shot: releasing the item returns footprint to the holder but never makes the permit drawable again. Lowering a group's eligibility, or the limit, retires leases on the next round. A retired lease stops drawing at once but stays counted in full until its client confirms how much it drew, since it may have drawn after its last report.
974
991
 
975
992
  ### Queueing work in a client Durable Object
976
993
 
@@ -1002,10 +1019,11 @@ export class JobShard extends DurableObject<Env> {
1002
1019
  scheduler: this.scheduler,
1003
1020
  clientId: this.ctx.id.toString(),
1004
1021
  server: limits.with(timeout, 5_000),
1005
- admit: (items) =>
1006
- Promise.all(
1022
+ admit: async (items) => {
1023
+ await Promise.all(
1007
1024
  items.map((item) => this.jobs.run({ id: item.id, payload: item.body }))
1008
- ),
1025
+ );
1026
+ },
1009
1027
  // The hook above is best-effort; this check returns any permit it missed.
1010
1028
  finished: async (ids) => {
1011
1029
  const results = await Promise.all(
@@ -1275,8 +1293,9 @@ export class Coordinator extends DurableObject<Env> {
1275
1293
  private readonly topology = new DurabilityTopology({
1276
1294
  scheduler: this.scheduler,
1277
1295
  publish: {
1278
- write: (snapshot, encoded) =>
1279
- this.env.TOPOLOGY.put(`topology/${snapshot.group}`, encoded),
1296
+ write: async (snapshot, encoded) => {
1297
+ await this.env.TOPOLOGY.put(`topology/${snapshot.group}`, encoded);
1298
+ },
1280
1299
  delete: (group) => this.env.TOPOLOGY.delete(`topology/${group}`),
1281
1300
  },
1282
1301
  states: {
@@ -1382,8 +1401,9 @@ private readonly libraryTopology = new DurabilityTopology({
1382
1401
  scheduler: this.scheduler,
1383
1402
  channel: 'library',
1384
1403
  publish: {
1385
- write: (snapshot, encoded) =>
1386
- this.env.TOPOLOGY.put(`library/${snapshot.group}`, encoded),
1404
+ write: async (snapshot, encoded) => {
1405
+ await this.env.TOPOLOGY.put(`library/${snapshot.group}`, encoded);
1406
+ },
1387
1407
  delete: (group) => this.env.TOPOLOGY.delete(`library/${group}`),
1388
1408
  },
1389
1409
  });
@@ -1476,7 +1496,11 @@ Records leave only through `trim()`, which enforces `maxAgeMs` and `maxRecords`,
1476
1496
  ```ts
1477
1497
  private readonly alarms = new DurabilityAlarms({
1478
1498
  scheduler: this.scheduler,
1479
- handlers: { compact: () => this.log.trim() },
1499
+ handlers: {
1500
+ compact: async () => {
1501
+ await this.log.trim();
1502
+ },
1503
+ },
1480
1504
  });
1481
1505
 
1482
1506
  alarm(info?: AlarmInvocationInfo) {
@@ -35,7 +35,7 @@ export type DurableAlarmInfo = {
35
35
  platform: AlarmInvocationInfo | undefined;
36
36
  };
37
37
  /** A handler for one named logical alarm. */
38
- export type DurableAlarmHandler = (info: DurableAlarmInfo) => unknown | Promise<unknown>;
38
+ export type DurableAlarmHandler = (info: DurableAlarmInfo) => void | Promise<void>;
39
39
  /** Policy configuration for named alarms. */
40
40
  export type DurabilityAlarmsOptions<Names extends string = string> = ExecutionPolicyOptions & {
41
41
  /** Execution policy overrides keyed by alarm name. */
@@ -18,6 +18,7 @@ import { durabilityNamedAlarmMigrations } from './migrations.js';
18
18
  import { durabilityMemoMigrations } from '../memoize/migrations.js';
19
19
  import { migrateCapability, } from '../migrations.js';
20
20
  import { alarmMethodOptionsSchema, createPolicyResolver, } from '../policy.js';
21
+ import { isFunction } from '../predicates.js';
21
22
  import { assertChannel, defaultChannel, engineFor, } from '../scheduler/index.js';
22
23
  import { createMemoize, deleteMemos, deleteMemosOfDroppedTable, memoizedKeys, } from '../memoize/index.js';
23
24
  import { deleteAttempt, listCreated } from '../storage.js';
@@ -35,7 +36,7 @@ const alarmRowSchema = v.object({
35
36
  created_at: v.pipe(v.number(), v.safeInteger(), v.minValue(0)),
36
37
  });
37
38
  const alarmsTable = { name: 'durability_alarms', key: 'name' };
38
- const alarmHandlerSchema = v.custom((value) => typeof value === 'function');
39
+ const alarmHandlerSchema = v.custom(isFunction);
39
40
  const readAlarm = (sql, channel, name) => v.parse(v.optional(alarmRowSchema), sql
40
41
  .exec('SELECT * FROM durability_alarms WHERE channel = ? AND name = ?', channel, name)
41
42
  .toArray()[0]);
@@ -123,6 +124,8 @@ class DurabilityAlarmsCore {
123
124
  * returns a function that detaches it.
124
125
  */
125
126
  lifecycle(hook) {
127
+ // SAFETY: every event this instance emits, from scheduling, alarmEntity
128
+ // attempts, and purges, has entityKind 'named_alarm'.
126
129
  return __classPrivateFieldGet(this, _DurabilityAlarmsCore_lifecycle, "f").add(hook);
127
130
  }
128
131
  /**
@@ -314,6 +317,6 @@ _DurabilityAlarmsCore_engine = new WeakMap(), _DurabilityAlarmsCore_channel = ne
314
317
  });
315
318
  };
316
319
  traceMethods(DurabilityAlarmsCore.prototype, 'DurabilityAlarms');
317
- // See Durability: members derived from the handler names cannot be declared on
318
- // the class, so the constructor is typed separately.
320
+ // SAFETY: the constructor defines a scheduling method for every handler name on
321
+ // the instance, members TypeScript cannot declare from a generic name union.
319
322
  export const DurabilityAlarms = DurabilityAlarmsCore;
package/dist/dev.d.ts CHANGED
@@ -3,14 +3,17 @@
3
3
  * is process-wide and monotonic so interleaved async work can be reordered
4
4
  * and correlated when replaying a simulation.
5
5
  */
6
- export declare const trace: (operation: string, details?: Record<string, unknown>) => number;
6
+ export declare const trace: <Details extends object>(operation: string, details?: Details) => number;
7
7
  /**
8
8
  * Wraps a public function so dev mode logs its arguments and outcome. `details`
9
9
  * identifies the receiver when the arguments alone do not.
10
10
  */
11
- export declare const traceFunction: <Args extends unknown[], Result>(method: string, fn: (...args: Args) => Result, details?: Record<string, unknown>) => ((...args: Args) => Result);
11
+ export declare const traceFunction: <This, Args extends unknown[], Result, Details extends object>(method: string, fn: (this: This, ...args: Args) => Result, details?: Details) => ((this: This, ...args: Args) => Result);
12
+ type ClassPrototype = {
13
+ readonly constructor: Function;
14
+ };
12
15
  /** Wraps every method on a class prototype with {@link traceFunction}. */
13
- export declare const traceMethods: (prototype: object, owner: string) => void;
16
+ export declare const traceMethods: (prototype: ClassPrototype, owner: string) => void;
14
17
  /** Logs each lifecycle event before `emit` hands it to the consumer's hooks. */
15
18
  export declare const traceLifecycle: <Event extends Record<string, unknown>>(emit: (event: Event) => void) => ((event: Event) => void);
16
19
  /**
@@ -20,3 +23,4 @@ export declare const traceLifecycle: <Event extends Record<string, unknown>>(emi
20
23
  * call once.
21
24
  */
22
25
  export declare const traceStorage: <Storage extends object>(storage: Storage) => Storage;
26
+ export {};
package/dist/dev.js CHANGED
@@ -1,17 +1,18 @@
1
1
  import { serializeError } from './errors.js';
2
+ import { isFunction } from './predicates.js';
2
3
  /**
3
4
  * True only when the build defines `__DURABILITY_DEV__` as `true`. Bundlers
4
5
  * fold the check to a constant, so production builds pay one branch per
5
6
  * traced call and log nothing.
6
7
  */
7
- const devMode = typeof __DURABILITY_DEV__ === 'boolean' && __DURABILITY_DEV__;
8
+ const devMode = typeof __DURABILITY_DEV__ !== 'undefined' && __DURABILITY_DEV__ === true;
8
9
  let sequence = 0;
9
10
  /**
10
11
  * Logs one dev-mode trace entry and returns its sequence number. The sequence
11
12
  * is process-wide and monotonic so interleaved async work can be reordered
12
13
  * and correlated when replaying a simulation.
13
14
  */
14
- export const trace = (operation, details = {}) => {
15
+ export const trace = (operation, details) => {
15
16
  if (!devMode) {
16
17
  return 0;
17
18
  }
@@ -45,15 +46,15 @@ const traceCall = (operation, details, run) => {
45
46
  return result;
46
47
  }
47
48
  // Observes the promise without changing what the caller sees.
48
- void result.then((value) => trace(`${operation}.return`, { call, result: value }), (error) => trace(`${operation}.throw`, { call, error: serializeError(error) }));
49
+ void result.then((value) => trace(`${operation}.return`, { call, result: value }), (cause) => trace(`${operation}.throw`, { call, error: serializeError(cause) }));
49
50
  return result;
50
51
  };
51
- const loggableArgs = (args) => args.filter((arg) => typeof arg !== 'function');
52
+ const loggableArgs = (args) => args.filter((arg) => !isFunction(arg));
52
53
  /**
53
54
  * Wraps a public function so dev mode logs its arguments and outcome. `details`
54
55
  * identifies the receiver when the arguments alone do not.
55
56
  */
56
- export const traceFunction = (method, fn, details = {}) => {
57
+ export const traceFunction = (method, fn, details) => {
57
58
  if (!devMode) {
58
59
  return fn;
59
60
  }
@@ -68,7 +69,7 @@ export const traceMethods = (prototype, owner) => {
68
69
  }
69
70
  for (const name of Object.getOwnPropertyNames(prototype)) {
70
71
  const descriptor = Object.getOwnPropertyDescriptor(prototype, name);
71
- if (name === 'constructor' || typeof descriptor?.value !== 'function') {
72
+ if (name === 'constructor' || !isFunction(descriptor?.value)) {
72
73
  continue;
73
74
  }
74
75
  Object.defineProperty(prototype, name, {
@@ -97,7 +98,7 @@ const traceSql = (sql) => new Proxy(sql, {
97
98
  return target.exec(query, ...bindings);
98
99
  };
99
100
  }
100
- return typeof value === 'function' ? value.bind(target) : value;
101
+ return isFunction(value) ? value.bind(target) : value;
101
102
  },
102
103
  });
103
104
  const proxyStorage = (storage, scope) => {
@@ -106,22 +107,25 @@ const proxyStorage = (storage, scope) => {
106
107
  get(target, key) {
107
108
  const value = Reflect.get(target, key);
108
109
  if (key === 'sql' && value !== undefined) {
110
+ // SAFETY: proxyStorage wraps DurableObjectStorage, whose `sql` is a
111
+ // SqlStorage; a transaction has no `sql` and never reaches here.
109
112
  sql ?? (sql = traceSql(value));
110
113
  return sql;
111
114
  }
112
- if (typeof value !== 'function') {
115
+ if (!isFunction(value)) {
113
116
  return value;
114
117
  }
115
118
  const method = `${scope}.${String(key)}`;
116
119
  return (...args) => {
120
+ const [closure] = args;
117
121
  // Alarm writes inside `transaction` go through the transaction object.
118
- const forwarded = key === 'transaction' && typeof args[0] === 'function'
122
+ const forwarded = key === 'transaction' && isFunction(closure)
119
123
  ? [
120
- (transaction) => args[0](proxyStorage(transaction, 'transaction')),
124
+ (transaction) => closure(proxyStorage(transaction, 'transaction')),
121
125
  ...args.slice(1),
122
126
  ]
123
127
  : args;
124
- return traceCall('storage', { method, args: loggableArgs(args) }, () => Reflect.apply(value, target, forwarded));
128
+ return traceCall('storage', { method, args: loggableArgs(args) }, () => value.apply(target, forwarded));
125
129
  };
126
130
  },
127
131
  });
@@ -140,6 +144,8 @@ export const traceStorage = (storage) => {
140
144
  }
141
145
  const existing = tracedStorage.get(storage);
142
146
  if (existing) {
147
+ // SAFETY: tracedStorage maps a storage only to the proxy of that same
148
+ // storage, set below.
143
149
  return existing;
144
150
  }
145
151
  const traced = proxyStorage(storage, 'storage');
@@ -1,4 +1,5 @@
1
1
  import { exports as workerExports } from 'cloudflare:workers';
2
+ import { isFunction, isObjectOrFunction } from './predicates.js';
2
3
  export const resolveNamespace = (config, error) => {
3
4
  const namespace = config.namespace?.();
4
5
  if (namespace) {
@@ -7,11 +8,14 @@ export const resolveNamespace = (config, error) => {
7
8
  if (!config.exportName) {
8
9
  throw error('Use the durability Vite plugin, exportName, or an explicit namespace to resolve the target');
9
10
  }
10
- const exported = Reflect.get(workerExports, config.exportName);
11
- if (exported === null ||
12
- (typeof exported !== 'object' && typeof exported !== 'function') ||
13
- typeof Reflect.get(exported, 'getByName') !== 'function') {
11
+ const exportsByName = workerExports;
12
+ const exported = exportsByName[config.exportName];
13
+ if (!isObjectOrFunction(exported) ||
14
+ !('getByName' in exported) ||
15
+ !isFunction(exported.getByName)) {
14
16
  throw error(`Export "${config.exportName}" is not a Durable Object namespace`);
15
17
  }
18
+ // SAFETY: exportName names the binding of the target class (set by the Vite
19
+ // plugin or the caller), and the check above found its getByName.
16
20
  return exported;
17
21
  };
package/dist/errors.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import type { Json } from './serialization.js';
1
2
  /**
2
3
  * Marks a handler failure as terminal so it is persisted without another retry.
3
4
  *
@@ -30,18 +31,18 @@ export declare class DurableAlarmTimeoutError extends Error {
30
31
  }
31
32
  /** Error persisted when retry-delay evaluation fails or is unsafe. */
32
33
  export declare class DurableRetryPolicyError extends Error {
33
- constructor(entity: string, reason?: unknown);
34
+ constructor(entity: string, cause?: unknown);
34
35
  }
35
36
  /** Error persisted when a successful result cannot be JSON-serialized. */
36
37
  export declare class DurableResultSerializationError extends Error {
37
- constructor(operation: string, reason?: unknown);
38
+ constructor(operation: string, cause?: unknown);
38
39
  }
39
40
  /**
40
41
  * Error persisted when a memoized result cannot be JSON-serialized. It is
41
42
  * terminal because every retry would fail the same way.
42
43
  */
43
44
  export declare class DurableMemoSerializationError extends NonRetryableError {
44
- constructor(key: string, reason?: unknown);
45
+ constructor(key: string, cause?: unknown);
45
46
  }
46
47
  /**
47
48
  * Error persisted when work memoizes more keys, or a larger result, than the
@@ -139,11 +140,15 @@ export type SerializedError = {
139
140
  message: string;
140
141
  };
141
142
  /** Reduces any thrown value to a persistable name and message, never throwing. */
142
- export declare const serializeError: (error: unknown) => SerializedError;
143
- export declare const isErrorInstance: (error: unknown, constructor: new (...args: never[]) => Error) => boolean;
143
+ export declare const serializeError: (cause: unknown) => SerializedError;
144
+ export declare const isErrorInstance: <Instance extends Error>(error: unknown, constructor: new (...args: never[]) => Instance) => error is Instance;
144
145
  /** Recognizes this package's NonRetryableError and same-named errors from other packages. */
145
- export declare const isNonRetryable: (error: unknown) => boolean;
146
- export declare const reportFailure: (event: string, details: Record<string, unknown>, error: unknown) => void;
146
+ export declare const isNonRetryable: (cause: unknown) => boolean;
147
+ /** Fields logged with a failure to identify the work that failed. */
148
+ type FailureDetails = {
149
+ readonly [field: string]: Json;
150
+ };
151
+ export declare const reportFailure: (event: string, details: FailureDetails, cause: unknown) => void;
147
152
  /** A definite rejection of a topology change or configuration. */
148
153
  export declare class TopologyError extends Error {
149
154
  constructor(message: string);
@@ -161,3 +166,4 @@ export declare class TopologyUnavailableError extends Error {
161
166
  cause?: unknown;
162
167
  });
163
168
  }
169
+ export {};
package/dist/errors.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { isNonEmptyString, isObjectOrFunction } from './predicates.js';
1
2
  /**
2
3
  * Marks a handler failure as terminal so it is persisted without another retry.
3
4
  *
@@ -39,21 +40,21 @@ export class DurableAlarmTimeoutError extends Error {
39
40
  }
40
41
  /** Error persisted when retry-delay evaluation fails or is unsafe. */
41
42
  export class DurableRetryPolicyError extends Error {
42
- constructor(entity, reason) {
43
+ constructor(entity, cause) {
43
44
  super(`Retry policy for ${entity} must produce a non-negative safe-integer timestamp`);
44
45
  this.name = 'DurableRetryPolicyError';
45
- if (reason !== undefined) {
46
- Object.defineProperty(this, 'cause', { value: reason });
46
+ if (cause !== undefined) {
47
+ Object.defineProperty(this, 'cause', { value: cause });
47
48
  }
48
49
  }
49
50
  }
50
51
  /** Error persisted when a successful result cannot be JSON-serialized. */
51
52
  export class DurableResultSerializationError extends Error {
52
- constructor(operation, reason) {
53
+ constructor(operation, cause) {
53
54
  super(`Result for durable operation "${operation}" is not JSON-serializable`);
54
55
  this.name = 'DurableResultSerializationError';
55
- if (reason !== undefined) {
56
- Object.defineProperty(this, 'cause', { value: reason });
56
+ if (cause !== undefined) {
57
+ Object.defineProperty(this, 'cause', { value: cause });
57
58
  }
58
59
  }
59
60
  }
@@ -62,11 +63,11 @@ export class DurableResultSerializationError extends Error {
62
63
  * terminal because every retry would fail the same way.
63
64
  */
64
65
  export class DurableMemoSerializationError extends NonRetryableError {
65
- constructor(key, reason) {
66
+ constructor(key, cause) {
66
67
  super(`Memoized result for key ${JSON.stringify(key)} is not JSON-serializable`);
67
68
  this.name = 'DurableMemoSerializationError';
68
- if (reason !== undefined) {
69
- Object.defineProperty(this, 'cause', { value: reason });
69
+ if (cause !== undefined) {
70
+ Object.defineProperty(this, 'cause', { value: cause });
70
71
  }
71
72
  }
72
73
  }
@@ -213,26 +214,24 @@ export class RoutingError extends Error {
213
214
  }
214
215
  const readString = (value, property) => {
215
216
  try {
216
- const candidate = Reflect.get(value, property);
217
- return typeof candidate === 'string' && candidate.length > 0
218
- ? candidate
219
- : undefined;
217
+ const candidate = value[property];
218
+ return isNonEmptyString(candidate) ? candidate : undefined;
220
219
  }
221
220
  catch {
222
221
  return undefined;
223
222
  }
224
223
  };
225
224
  /** Reduces any thrown value to a persistable name and message, never throwing. */
226
- export const serializeError = (error) => {
227
- if (error === null) {
225
+ export const serializeError = (cause) => {
226
+ if (cause === null) {
228
227
  return { name: 'Error', message: 'null' };
229
228
  }
230
- if (typeof error !== 'object' && typeof error !== 'function') {
231
- return { name: 'Error', message: String(error) };
229
+ if (!isObjectOrFunction(cause)) {
230
+ return { name: 'Error', message: String(cause) };
232
231
  }
233
232
  return {
234
- name: readString(error, 'name') ?? 'Error',
235
- message: readString(error, 'message') ?? 'Unknown thrown value',
233
+ name: readString(cause, 'name') ?? 'Error',
234
+ message: readString(cause, 'message') ?? 'Unknown thrown value',
236
235
  };
237
236
  };
238
237
  export const isErrorInstance = (error, constructor) => {
@@ -244,37 +243,40 @@ export const isErrorInstance = (error, constructor) => {
244
243
  }
245
244
  };
246
245
  /** Recognizes this package's NonRetryableError and same-named errors from other packages. */
247
- export const isNonRetryable = (error) => {
248
- if (isErrorInstance(error, NonRetryableError)) {
246
+ export const isNonRetryable = (cause) => {
247
+ if (isErrorInstance(cause, NonRetryableError)) {
249
248
  return true;
250
249
  }
251
- if ((typeof error !== 'object' && typeof error !== 'function') ||
252
- error === null) {
250
+ if (!isObjectOrFunction(cause)) {
253
251
  return false;
254
252
  }
255
- if (readString(error, 'name') === 'NonRetryableError') {
253
+ if (readString(cause, 'name') === 'NonRetryableError') {
256
254
  return true;
257
255
  }
258
256
  try {
259
- const constructor = Reflect.get(error, 'constructor');
260
- return (constructor !== null &&
261
- (typeof constructor === 'object' || typeof constructor === 'function') &&
257
+ const constructor = cause.constructor;
258
+ return (isObjectOrFunction(constructor) &&
262
259
  readString(constructor, 'name') === 'NonRetryableError');
263
260
  }
264
261
  catch {
265
262
  return false;
266
263
  }
267
264
  };
268
- export const reportFailure = (event, details, error) => {
265
+ export const reportFailure = (event, details, cause) => {
269
266
  try {
270
- const stack = error !== null &&
271
- (typeof error === 'object' || typeof error === 'function')
272
- ? readString(error, 'stack')
267
+ const stack = isObjectOrFunction(cause)
268
+ ? readString(cause, 'stack')
273
269
  : undefined;
270
+ const logged = {
271
+ ...serializeError(cause),
272
+ };
273
+ if (stack) {
274
+ logged.stack = stack;
275
+ }
274
276
  console.error({
275
277
  event,
276
278
  ...details,
277
- error: { ...serializeError(error), ...(stack ? { stack } : {}) },
279
+ error: logged,
278
280
  });
279
281
  }
280
282
  catch {
@@ -28,7 +28,7 @@ export type DurabilityFanoutMessage<Body = unknown> = {
28
28
  deadLetter(): Promise<void>;
29
29
  };
30
30
  export type FanoutTarget<Body> = ExecutionPolicyOptions & ({
31
- deliver(messages: DurabilityFanoutMessage<Body>[]): unknown | Promise<unknown>;
31
+ deliver(messages: DurabilityFanoutMessage<Body>[]): void | Promise<void>;
32
32
  /**
33
33
  * Acks every message the consumer leaves unsettled when `deliver`
34
34
  * returns without throwing, in one transaction instead of one call