durability 5.1.0 → 5.2.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.
Files changed (98) hide show
  1. package/README.md +154 -21
  2. package/dist/{durability-alarms.d.ts → alarms/index.d.ts} +13 -5
  3. package/dist/{durability-alarms.js → alarms/index.js} +85 -74
  4. package/dist/alarms/migrations.d.ts +9 -0
  5. package/dist/alarms/migrations.js +133 -0
  6. package/dist/experimental.d.ts +10 -10
  7. package/dist/experimental.js +7 -7
  8. package/dist/{fanout.d.ts → fanout/index.d.ts} +13 -6
  9. package/dist/{fanout.js → fanout/index.js} +91 -83
  10. package/dist/fanout/migrations.d.ts +9 -0
  11. package/dist/fanout/migrations.js +181 -0
  12. package/dist/{stored-message.d.ts → fanout/stored-message.d.ts} +1 -1
  13. package/dist/index.d.ts +14 -9
  14. package/dist/index.js +13 -8
  15. package/dist/{log.d.ts → log/index.d.ts} +27 -20
  16. package/dist/{log.js → log/index.js} +200 -166
  17. package/dist/log/migrations.d.ts +18 -0
  18. package/dist/log/migrations.js +297 -0
  19. package/dist/{memoize.d.ts → memoize/index.d.ts} +1 -1
  20. package/dist/{memoize.js → memoize/index.js} +23 -21
  21. package/dist/memoize/migrations.d.ts +10 -0
  22. package/dist/memoize/migrations.js +21 -0
  23. package/dist/migrations.d.ts +0 -111
  24. package/dist/migrations.js +12 -628
  25. package/dist/{durability.d.ts → operations/index.d.ts} +13 -5
  26. package/dist/{durability.js → operations/index.js} +76 -70
  27. package/dist/operations/migrations.d.ts +10 -0
  28. package/dist/operations/migrations.js +150 -0
  29. package/dist/{outbox.d.ts → outbox/index.d.ts} +4 -4
  30. package/dist/{outbox.js → outbox/index.js} +35 -77
  31. package/dist/outbox/migrations.d.ts +9 -0
  32. package/dist/outbox/migrations.js +43 -0
  33. package/dist/policy.d.ts +19 -19
  34. package/dist/policy.js +13 -12
  35. package/dist/{routing-client.js → routing/client.js} +1 -1
  36. package/dist/{routing.d.ts → routing/index.d.ts} +3 -3
  37. package/dist/{routing.js → routing/index.js} +3 -3
  38. package/dist/{load.d.ts → routing/load.d.ts} +1 -1
  39. package/dist/{schedule.d.ts → schedule/index.d.ts} +16 -8
  40. package/dist/{schedule.js → schedule/index.js} +97 -83
  41. package/dist/schedule/migrations.d.ts +9 -0
  42. package/dist/schedule/migrations.js +118 -0
  43. package/dist/{scheduler.d.ts → scheduler/index.d.ts} +75 -25
  44. package/dist/{scheduler.js → scheduler/index.js} +308 -70
  45. package/dist/{semaphore-client.d.ts → semaphore/client.d.ts} +1 -1
  46. package/dist/{semaphore-client.js → semaphore/client.js} +8 -7
  47. package/dist/{semaphore.d.ts → semaphore/index.d.ts} +10 -10
  48. package/dist/{semaphore.js → semaphore/index.js} +7 -7
  49. package/dist/{semaphore-leases.d.ts → semaphore/leases.d.ts} +17 -6
  50. package/dist/{semaphore-leases.js → semaphore/leases.js} +28 -12
  51. package/dist/semaphore/migrations.d.ts +18 -0
  52. package/dist/semaphore/migrations.js +444 -0
  53. package/dist/semaphore/protocol.d.ts +451 -0
  54. package/dist/semaphore/protocol.js +114 -0
  55. package/dist/semaphore/queue-store.d.ts +107 -0
  56. package/dist/semaphore/queue-store.js +258 -0
  57. package/dist/{semaphore-queue.d.ts → semaphore/queue.d.ts} +15 -5
  58. package/dist/{semaphore-queue.js → semaphore/queue.js} +105 -46
  59. package/dist/{semaphore-server.d.ts → semaphore/server.d.ts} +12 -4
  60. package/dist/{semaphore-server.js → semaphore/server.js} +56 -28
  61. package/dist/semaphore/store.d.ts +53 -0
  62. package/dist/semaphore/store.js +107 -0
  63. package/dist/serialization.d.ts +5 -0
  64. package/dist/serialization.js +41 -16
  65. package/dist/{client.d.ts → socket/client.d.ts} +3 -3
  66. package/dist/{client.js → socket/client.js} +4 -4
  67. package/dist/{socket.d.ts → socket/index.d.ts} +15 -4
  68. package/dist/{socket.js → socket/index.js} +66 -20
  69. package/dist/socket/migrations.d.ts +9 -0
  70. package/dist/socket/migrations.js +57 -0
  71. package/dist/{socket-protocol.d.ts → socket/protocol.d.ts} +1 -1
  72. package/dist/storage.d.ts +4 -0
  73. package/dist/storage.js +22 -15
  74. package/dist/{topology-client.d.ts → topology/client.d.ts} +2 -2
  75. package/dist/{topology-client.js → topology/client.js} +3 -3
  76. package/dist/{topology.d.ts → topology/index.d.ts} +17 -7
  77. package/dist/{topology.js → topology/index.js} +106 -72
  78. package/dist/topology/migrations.d.ts +10 -0
  79. package/dist/topology/migrations.js +138 -0
  80. package/dist/topology/snapshot.d.ts +50 -0
  81. package/dist/topology/snapshot.js +38 -0
  82. package/dist/{tracker.d.ts → tracker/index.d.ts} +3 -3
  83. package/dist/{tracker.js → tracker/index.js} +9 -9
  84. package/package.json +11 -11
  85. package/dist/semaphore-protocol.d.ts +0 -231
  86. package/dist/semaphore-protocol.js +0 -106
  87. package/dist/semaphore-queue-store.d.ts +0 -95
  88. package/dist/semaphore-queue-store.js +0 -252
  89. package/dist/semaphore-store.d.ts +0 -43
  90. package/dist/semaphore-store.js +0 -108
  91. package/dist/topology-snapshot.d.ts +0 -70
  92. package/dist/topology-snapshot.js +0 -48
  93. /package/dist/{stored-message.js → fanout/stored-message.js} +0 -0
  94. /package/dist/{routing-client.d.ts → routing/client.d.ts} +0 -0
  95. /package/dist/{load.js → routing/load.js} +0 -0
  96. /package/dist/{socket-protocol.js → socket/protocol.js} +0 -0
  97. /package/dist/{tracked-source.d.ts → tracker/source.d.ts} +0 -0
  98. /package/dist/{tracked-source.js → tracker/source.js} +0 -0
@@ -0,0 +1,107 @@
1
+ import * as v from 'valibot';
2
+ export const grantRowSchema = v.object({
3
+ grant_id: v.string(),
4
+ client_id: v.string(),
5
+ /** The client's queue channel; `clientId` alone does not identify a client. */
6
+ client_channel: v.string(),
7
+ grp: v.string(),
8
+ permits: v.pipe(v.number(), v.safeInteger(), v.minValue(0)),
9
+ claimed: v.pipe(v.number(), v.safeInteger(), v.minValue(0)),
10
+ released: v.pipe(v.number(), v.safeInteger(), v.minValue(0)),
11
+ created_at: v.pipe(v.number(), v.safeInteger(), v.minValue(0)),
12
+ /** Unclaimed permits are reclaimed once this passes. */
13
+ expires_at: v.pipe(v.number(), v.safeInteger(), v.minValue(0)),
14
+ });
15
+ /** Permits a client may draw locally without a round trip; held by the holder. */
16
+ export const leaseRowSchema = v.object({
17
+ lease_id: v.string(),
18
+ client_id: v.string(),
19
+ client_channel: v.string(),
20
+ grp: v.string(),
21
+ permits: v.pipe(v.number(), v.safeInteger(), v.minValue(0)),
22
+ /** Drawn permits the client has returned, as a high-water mark. */
23
+ released: v.pipe(v.number(), v.safeInteger(), v.minValue(0)),
24
+ created_at: v.pipe(v.number(), v.safeInteger(), v.minValue(0)),
25
+ /** Refreshed by every report; the lease is swept once this passes. */
26
+ expires_at: v.pipe(v.number(), v.safeInteger(), v.minValue(0)),
27
+ /** 1 once no more permits may be drawn; footprint stays until released. */
28
+ retired: v.pipe(v.number(), v.safeInteger(), v.minValue(0), v.maxValue(1)),
29
+ });
30
+ const grantColumns = v.keyof(grantRowSchema).options;
31
+ const leaseColumns = v.keyof(leaseRowSchema).options;
32
+ /**
33
+ * Permits one semaphore channel has handed out. Every query is scoped to the
34
+ * channel, so semaphores sharing an object never see each other's grants or
35
+ * leases. Grants and leases are small and bounded by live clients, so
36
+ * aggregates are computed from `list()`.
37
+ */
38
+ export class HolderStore {
39
+ constructor(sql, channel) {
40
+ this.sql = sql;
41
+ this.channel = channel;
42
+ }
43
+ list() {
44
+ return v.parse(v.array(grantRowSchema), this.sql
45
+ .exec(`SELECT * FROM durability_semaphore_grants
46
+ WHERE channel = ? ORDER BY created_at`, this.channel)
47
+ .toArray());
48
+ }
49
+ get(grantId) {
50
+ return v.parse(v.optional(grantRowSchema), this.sql
51
+ .exec(`SELECT * FROM durability_semaphore_grants
52
+ WHERE channel = ? AND grant_id = ? LIMIT 1`, this.channel, grantId)
53
+ .toArray()[0]);
54
+ }
55
+ nextPendingAt() {
56
+ return v.parse(v.optional(v.pick(grantRowSchema, ['expires_at'])), this.sql
57
+ .exec(`SELECT expires_at FROM durability_semaphore_grants
58
+ WHERE channel = ? AND claimed < permits
59
+ ORDER BY expires_at ASC
60
+ LIMIT 1`, this.channel)
61
+ .toArray()[0])?.expires_at;
62
+ }
63
+ insert(row) {
64
+ return (this.sql
65
+ .exec(`INSERT INTO durability_semaphore_grants (channel, ${grantColumns.join(', ')})
66
+ VALUES (?, ${grantColumns.map(() => '?').join(', ')})
67
+ ON CONFLICT(channel, grant_id) DO NOTHING
68
+ RETURNING grant_id`, this.channel, ...grantColumns.map((column) => row[column]))
69
+ .toArray().length > 0);
70
+ }
71
+ update(row) {
72
+ this.sql.exec(`UPDATE durability_semaphore_grants
73
+ SET permits = ?, claimed = ?, released = ?, expires_at = ?
74
+ WHERE channel = ? AND grant_id = ?`, row.permits, row.claimed, row.released, row.expires_at, this.channel, row.grant_id);
75
+ }
76
+ remove(grantId) {
77
+ this.sql.exec('DELETE FROM durability_semaphore_grants WHERE channel = ? AND grant_id = ?', this.channel, grantId);
78
+ }
79
+ listLeases() {
80
+ return v.parse(v.array(leaseRowSchema), this.sql
81
+ .exec(`SELECT * FROM durability_semaphore_leases
82
+ WHERE channel = ? ORDER BY created_at`, this.channel)
83
+ .toArray());
84
+ }
85
+ getLease(leaseId) {
86
+ return v.parse(v.optional(leaseRowSchema), this.sql
87
+ .exec(`SELECT * FROM durability_semaphore_leases
88
+ WHERE channel = ? AND lease_id = ? LIMIT 1`, this.channel, leaseId)
89
+ .toArray()[0]);
90
+ }
91
+ insertLease(row) {
92
+ return (this.sql
93
+ .exec(`INSERT INTO durability_semaphore_leases (channel, ${leaseColumns.join(', ')})
94
+ VALUES (?, ${leaseColumns.map(() => '?').join(', ')})
95
+ ON CONFLICT(channel, lease_id) DO NOTHING
96
+ RETURNING lease_id`, this.channel, ...leaseColumns.map((column) => row[column]))
97
+ .toArray().length > 0);
98
+ }
99
+ updateLease(row) {
100
+ this.sql.exec(`UPDATE durability_semaphore_leases
101
+ SET permits = ?, released = ?, expires_at = ?, retired = ?
102
+ WHERE channel = ? AND lease_id = ?`, row.permits, row.released, row.expires_at, row.retired, this.channel, row.lease_id);
103
+ }
104
+ removeLease(leaseId) {
105
+ this.sql.exec('DELETE FROM durability_semaphore_leases WHERE channel = ? AND lease_id = ?', this.channel, leaseId);
106
+ }
107
+ }
@@ -1,3 +1,8 @@
1
+ import * as v from 'valibot';
2
+ export type Json = string | number | boolean | null | Json[] | {
3
+ [key: string]: Json;
4
+ };
5
+ export declare const jsonSchema: v.CustomSchema<Json, v.ErrorMessage<v.CustomIssue> | undefined>;
1
6
  export declare const serialize: (value: unknown) => string;
2
7
  export declare const deserialize: (value: string) => unknown;
3
8
  /**
@@ -1,11 +1,40 @@
1
- import { z } from 'zod';
2
- const storedValueSchema = z.discriminatedUnion('kind', [
3
- z.object({ kind: z.literal('value'), value: z.json() }),
4
- z.object({ kind: z.literal('undefined') }),
1
+ import * as v from 'valibot';
2
+ const isPlainObject = (value) => {
3
+ if (value === null || typeof value !== 'object') {
4
+ return false;
5
+ }
6
+ const prototype = Object.getPrototypeOf(value);
7
+ return prototype === Object.prototype || prototype === null;
8
+ };
9
+ const isJson = (value) => {
10
+ if (value === null ||
11
+ typeof value === 'string' ||
12
+ typeof value === 'boolean') {
13
+ return true;
14
+ }
15
+ if (typeof value === 'number') {
16
+ return Number.isFinite(value);
17
+ }
18
+ if (Array.isArray(value)) {
19
+ // `every` would skip the holes of a sparse array, which are not JSON.
20
+ for (const item of value) {
21
+ if (!isJson(item)) {
22
+ return false;
23
+ }
24
+ }
25
+ return true;
26
+ }
27
+ return isPlainObject(value) && Object.values(value).every(isJson);
28
+ };
29
+ // Not built from `v.record`, which silently drops `constructor` and `prototype` keys.
30
+ export const jsonSchema = v.custom(isJson, 'Invalid JSON value');
31
+ const storedValueSchema = v.variant('kind', [
32
+ v.object({ kind: v.literal('value'), value: jsonSchema }),
33
+ v.object({ kind: v.literal('undefined') }),
5
34
  ]);
6
35
  /**
7
36
  * What `JSON.stringify` would produce: `undefined` properties are dropped and
8
- * `undefined` array elements become `null`. `z.json()` rejects both as given,
37
+ * `undefined` array elements become `null`. `jsonSchema` rejects both as given,
9
38
  * although they are routine in values such as lifecycle events whose handler
10
39
  * returned nothing.
11
40
  */
@@ -13,24 +42,20 @@ const asJson = (value) => {
13
42
  if (Array.isArray(value)) {
14
43
  return value.map((item) => (item === undefined ? null : asJson(item)));
15
44
  }
16
- if (value === null || typeof value !== 'object') {
17
- return value;
18
- }
19
45
  // Only plain objects are rewritten; anything else must fail validation as is.
20
- const prototype = Object.getPrototypeOf(value);
21
- if (prototype === Object.prototype || prototype === null) {
22
- return Object.fromEntries(Object.entries(value)
23
- .filter(([, item]) => item !== undefined)
24
- .map(([key, item]) => [key, asJson(item)]));
46
+ if (!isPlainObject(value)) {
47
+ return value;
25
48
  }
26
- return value;
49
+ return Object.fromEntries(Object.entries(value)
50
+ .filter(([, item]) => item !== undefined)
51
+ .map(([key, item]) => [key, asJson(item)]));
27
52
  };
28
53
  // Wrapping preserves a successful `undefined` result, which bare JSON cannot represent.
29
54
  export const serialize = (value) => JSON.stringify(value === undefined
30
55
  ? { kind: 'undefined' }
31
- : { kind: 'value', value: z.json().parse(asJson(value)) });
56
+ : { kind: 'value', value: v.parse(jsonSchema, asJson(value)) });
32
57
  export const deserialize = (value) => {
33
- const stored = storedValueSchema.parse(JSON.parse(value));
58
+ const stored = v.parse(storedValueSchema, JSON.parse(value));
34
59
  return stored.kind === 'undefined' ? undefined : stored.value;
35
60
  };
36
61
  const canonicalize = (value) => {
@@ -1,5 +1,5 @@
1
- import { type SerializedError } from './errors.js';
2
- import { type AnySocketShape, type InboundOf, type OutboundOf, type SocketInboundInput, type SocketInboundOutput, type SocketOutboundPayload } from './socket-protocol.js';
1
+ import { type SerializedError } from '../errors.js';
2
+ import { type AnySocketShape, type InboundOf, type OutboundOf, type SocketInboundInput, type SocketInboundOutput, type SocketOutboundPayload } from './protocol.js';
3
3
  /** Rejection for calls still waiting when `close()` was called. */
4
4
  export declare class SocketClosedError extends Error {
5
5
  constructor();
@@ -91,4 +91,4 @@ export declare class DurabilitySocketClient<Socket extends AnySocketShape> {
91
91
  }
92
92
  /** Logs every call's input, output or error, and duration. */
93
93
  export declare const logging: (log?: (entry: Record<string, unknown>) => void) => SocketTransform;
94
- export { socketShape, type AnySocketShape, type InboundOf, type OutboundOf, type SocketInboundInput, type SocketInboundOutput, type SocketOutboundPayload, type SocketShape, } from './socket-protocol.js';
94
+ export { socketShape, type AnySocketShape, type InboundOf, type OutboundOf, type SocketInboundInput, type SocketInboundOutput, type SocketOutboundPayload, type SocketShape, } from './protocol.js';
@@ -10,9 +10,9 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
10
10
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11
11
  };
12
12
  var _Connection_instances, _Connection_config, _Connection_url, _Connection_transforms, _Connection_pending, _Connection_handlers, _Connection_statusHandlers, _Connection_resyncHandlers, _Connection_subscribes, _Connection_acknowledged, _Connection_status, _Connection_ws, _Connection_generation, _Connection_nextId, _Connection_lastSeq, _Connection_attempt, _Connection_retryTimer, _Connection_pingTimer, _Connection_lastReceivedAt, _Connection_send, _Connection_subscribe, _Connection_subscribed, _Connection_flush, _Connection_connect, _Connection_receive, _Connection_settle, _Connection_dispatch, _Connection_invoke, _Connection_disconnected, _Connection_abandon, _Connection_startPing, _Connection_stopTimers, _Connection_setStatus, _DurabilitySocketClient_config, _DurabilitySocketClient_transforms;
13
- import { reportFailure } from './errors.js';
14
- import { parseServerFrame, socketProtocolErrorCode, socketProtocolVersion, } from './socket-protocol.js';
15
- import { exponential, jitter } from './utils.js';
13
+ import { reportFailure } from '../errors.js';
14
+ import { parseServerFrame, socketProtocolErrorCode, socketProtocolVersion, } from './protocol.js';
15
+ import { exponential, jitter } from '../utils.js';
16
16
  /** Rejection for calls still waiting when `close()` was called. */
17
17
  export class SocketClosedError extends Error {
18
18
  constructor() {
@@ -442,4 +442,4 @@ export const logging = (log = console.log) => async ({ method, input, next }) =>
442
442
  throw error;
443
443
  }
444
444
  };
445
- export { socketShape, } from './socket-protocol.js';
445
+ export { socketShape, } from './protocol.js';
@@ -1,6 +1,6 @@
1
1
  import type { StandardSchemaV1 } from '@standard-schema/spec';
2
- import { type DurabilityMigrationResult } from './migrations.js';
3
- import { type SocketInboundMap, type SocketOutboundMap, type SocketOutboundPayload, type SocketInboundMetadata, type SocketShape, socketShape } from './socket-protocol.js';
2
+ import { type DurabilityMigrationResult } from '../migrations.js';
3
+ import { type SocketInboundMap, type SocketOutboundMap, type SocketOutboundPayload, type SocketInboundMetadata, type SocketShape, socketShape } from './protocol.js';
4
4
  /** The Durable Object state a socket needs: SQLite storage and hibernatable WebSockets. */
5
5
  export type DurabilitySocketContext = Pick<DurableObjectState, 'storage' | 'acceptWebSocket' | 'getWebSockets' | 'setWebSocketAutoResponse'>;
6
6
  export type DurabilitySocketConfig<Inbound extends SocketInboundMap, Outbound extends SocketOutboundMap, Metadata extends SocketInboundMetadata<Inbound>> = {
@@ -16,6 +16,13 @@ export type DurabilitySocketConfig<Inbound extends SocketInboundMap, Outbound ex
16
16
  metadata?: (request: Request) => Metadata | Promise<Metadata>;
17
17
  /** Outbound events kept for replay to reconnecting clients. Defaults to 1000. */
18
18
  retention?: number;
19
+ /**
20
+ * Partitions the object's sockets, so a library and the application can each
21
+ * have one. Defaults to `default`. Each connection belongs to the channel
22
+ * whose `fetch` accepted it, and its frames reach that instance's handlers
23
+ * whichever instance `webSocketMessage` delegates to.
24
+ */
25
+ channel?: string;
19
26
  };
20
27
  /** Thrown to the caller when an inbound payload fails its schema. */
21
28
  export declare class SocketInputError extends Error {
@@ -30,7 +37,11 @@ declare class DurabilitySocketCore<Inbound extends SocketInboundMap, Outbound ex
30
37
  static migrate(context: Pick<DurableObjectState, 'storage'>, target?: string | null): DurabilityMigrationResult;
31
38
  /** Accepts a WebSocket upgrade; call from the Durable Object's `fetch`. */
32
39
  fetch(request: Request): Promise<Response>;
33
- /** Handles one inbound frame; call from the Durable Object's `webSocketMessage`. */
40
+ /**
41
+ * Handles one inbound frame; call from the Durable Object's
42
+ * `webSocketMessage`. The frame goes to the socket of the connection's
43
+ * channel, which need not be this one.
44
+ */
34
45
  webSocketMessage(ws: WebSocket, message: string | ArrayBuffer): Promise<void>;
35
46
  /**
36
47
  * Call from the Durable Object's `webSocketClose`. Subscriptions live in the
@@ -89,4 +100,4 @@ export interface DurabilitySocketConstructor {
89
100
  }
90
101
  export declare const DurabilitySocket: DurabilitySocketConstructor;
91
102
  export { durabilitySocketMigrations } from './migrations.js';
92
- export { event, type SocketCall, type SocketInboundHandler, type SocketInboundMap, type SocketOutboundEvent, type SocketOutboundMap, } from './socket-protocol.js';
103
+ export { event, type SocketCall, type SocketInboundHandler, type SocketInboundMap, type SocketOutboundEvent, type SocketOutboundMap, } from './protocol.js';
@@ -9,12 +9,14 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
9
9
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
10
10
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11
11
  };
12
- var _DurabilitySocketCore_instances, _DurabilitySocketCore_context, _DurabilitySocketCore_storage, _DurabilitySocketCore_inbound, _DurabilitySocketCore_outboundNames, _DurabilitySocketCore_metadata, _DurabilitySocketCore_retention, _DurabilitySocketCore_call, _DurabilitySocketCore_validate, _DurabilitySocketCore_subscribe, _DurabilitySocketCore_replay, _DurabilitySocketCore_headSeq, _DurabilitySocketCore_publish;
13
- import { trace, traceFunction, traceMethods, traceStorage } from './dev.js';
14
- import { reportFailure, serializeError } from './errors.js';
15
- import { durabilitySocketMigrations, migrateCapability, } from './migrations.js';
16
- import { deserialize, serialize } from './serialization.js';
17
- import { parseClientFrame, socketMaxFrameLength, socketProtocolErrorCode, socketProtocolVersion, } from './socket-protocol.js';
12
+ var _DurabilitySocketCore_instances, _DurabilitySocketCore_context, _DurabilitySocketCore_storage, _DurabilitySocketCore_inbound, _DurabilitySocketCore_outboundNames, _DurabilitySocketCore_metadata, _DurabilitySocketCore_retention, _DurabilitySocketCore_channel, _DurabilitySocketCore_frameHandlers, _DurabilitySocketCore_handle, _DurabilitySocketCore_call, _DurabilitySocketCore_validate, _DurabilitySocketCore_subscribe, _DurabilitySocketCore_replay, _DurabilitySocketCore_headSeq, _DurabilitySocketCore_publish;
13
+ import { trace, traceFunction, traceMethods, traceStorage } from '../dev.js';
14
+ import { reportFailure, serializeError } from '../errors.js';
15
+ import { durabilitySocketMigrations } from './migrations.js';
16
+ import { migrateCapability, } from '../migrations.js';
17
+ import { assertChannel, defaultChannel, engineFor, } from '../scheduler/index.js';
18
+ import { deserialize, serialize } from '../serialization.js';
19
+ import { parseClientFrame, socketMaxFrameLength, socketProtocolErrorCode, socketProtocolVersion, } from './protocol.js';
18
20
  /** Thrown to the caller when an inbound payload fails its schema. */
19
21
  export class SocketInputError extends Error {
20
22
  constructor(method, issues) {
@@ -23,6 +25,10 @@ export class SocketInputError extends Error {
23
25
  this.issues = issues;
24
26
  }
25
27
  }
28
+ /** The socket instances of each Durable Object, by channel, so any of them can route a frame. */
29
+ const frameHandlersByObject = new WeakMap();
30
+ // A configuration problem rather than a protocol violation, so clients reconnect.
31
+ const channelMissingCloseCode = 1011;
26
32
  const reservedOutboundNames = new Set(['status', 'resync']);
27
33
  const sendFrame = (ws, frame) => {
28
34
  trace('socket.send', { frame });
@@ -52,14 +58,21 @@ const sendFrame = (ws, frame) => {
52
58
  const readAttachment = (ws) => {
53
59
  const stored = ws.deserializeAttachment();
54
60
  if (typeof stored !== 'object' || stored === null) {
55
- return { metadata: undefined, names: [] };
61
+ return {
62
+ metadata: undefined,
63
+ names: [],
64
+ channel: defaultChannel,
65
+ };
56
66
  }
57
67
  const names = Reflect.get(stored, 'names');
68
+ // Connections accepted before channels existed carry no channel.
69
+ const channel = Reflect.get(stored, 'channel');
58
70
  return {
59
71
  metadata: Reflect.get(stored, 'metadata'),
60
72
  names: Array.isArray(names)
61
73
  ? names.filter((name) => typeof name === 'string')
62
74
  : [],
75
+ channel: typeof channel === 'string' ? channel : defaultChannel,
63
76
  };
64
77
  };
65
78
  class DurabilitySocketCore {
@@ -71,10 +84,13 @@ class DurabilitySocketCore {
71
84
  _DurabilitySocketCore_outboundNames.set(this, void 0);
72
85
  _DurabilitySocketCore_metadata.set(this, void 0);
73
86
  _DurabilitySocketCore_retention.set(this, void 0);
87
+ _DurabilitySocketCore_channel.set(this, void 0);
88
+ _DurabilitySocketCore_frameHandlers.set(this, void 0);
74
89
  const retention = config.retention ?? 1000;
75
90
  if (!Number.isSafeInteger(retention) || retention <= 0) {
76
91
  throw new RangeError('retention must be a positive safe integer');
77
92
  }
93
+ __classPrivateFieldSet(this, _DurabilitySocketCore_channel, assertChannel('DurabilitySocket', config.channel ?? defaultChannel), "f");
78
94
  __classPrivateFieldSet(this, _DurabilitySocketCore_context, config.context, "f");
79
95
  __classPrivateFieldSet(this, _DurabilitySocketCore_storage, traceStorage(config.context.storage), "f");
80
96
  // Only own keys are callable; nothing on the prototype chain is reachable.
@@ -95,7 +111,13 @@ class DurabilitySocketCore {
95
111
  enumerable: true,
96
112
  });
97
113
  }
98
- migrateCapability(__classPrivateFieldGet(this, _DurabilitySocketCore_storage, "f"), 'socket', durabilitySocketMigrations, undefined);
114
+ const engine = engineFor({ context: config.context });
115
+ engine.migrateSchema('socket', durabilitySocketMigrations);
116
+ engine.claimChannel('durability_socket_events', __classPrivateFieldGet(this, _DurabilitySocketCore_channel, "f"), 'DurabilitySocket');
117
+ const frameHandlers = frameHandlersByObject.get(engine) ?? new Map();
118
+ frameHandlers.set(__classPrivateFieldGet(this, _DurabilitySocketCore_channel, "f"), (ws, frame) => __classPrivateFieldGet(this, _DurabilitySocketCore_instances, "m", _DurabilitySocketCore_handle).call(this, ws, frame));
119
+ frameHandlersByObject.set(engine, frameHandlers);
120
+ __classPrivateFieldSet(this, _DurabilitySocketCore_frameHandlers, frameHandlers, "f");
99
121
  // Keep-alive pings are answered by the runtime without waking a hibernated object.
100
122
  __classPrivateFieldGet(this, _DurabilitySocketCore_context, "f").setWebSocketAutoResponse(new WebSocketRequestResponsePair(JSON.stringify({ v: socketProtocolVersion, type: 'ping' }), JSON.stringify({ v: socketProtocolVersion, type: 'pong' })));
101
123
  }
@@ -116,10 +138,15 @@ class DurabilitySocketCore {
116
138
  server.serializeAttachment({
117
139
  metadata,
118
140
  names: [],
141
+ channel: __classPrivateFieldGet(this, _DurabilitySocketCore_channel, "f"),
119
142
  });
120
143
  return new Response(null, { status: 101, webSocket: client });
121
144
  }
122
- /** Handles one inbound frame; call from the Durable Object's `webSocketMessage`. */
145
+ /**
146
+ * Handles one inbound frame; call from the Durable Object's
147
+ * `webSocketMessage`. The frame goes to the socket of the connection's
148
+ * channel, which need not be this one.
149
+ */
123
150
  async webSocketMessage(ws, message) {
124
151
  const text = typeof message === 'string' ? message : new TextDecoder().decode(message);
125
152
  const frame = parseClientFrame(text);
@@ -131,11 +158,18 @@ class DurabilitySocketCore {
131
158
  ws.close(socketProtocolErrorCode, 'Invalid frame');
132
159
  return;
133
160
  }
134
- if (frame.type === 'subscribe') {
135
- __classPrivateFieldGet(this, _DurabilitySocketCore_instances, "m", _DurabilitySocketCore_subscribe).call(this, ws, frame);
161
+ const { channel } = readAttachment(ws);
162
+ const handle = __classPrivateFieldGet(this, _DurabilitySocketCore_frameHandlers, "f").get(channel);
163
+ if (!handle) {
164
+ reportFailure('durability.socket.channel_missing', { channel }, new Error(`No DurabilitySocket is attached for channel "${channel}"`));
165
+ trace('socket.close', {
166
+ code: channelMissingCloseCode,
167
+ reason: 'Socket channel is not attached',
168
+ });
169
+ ws.close(channelMissingCloseCode, 'Socket channel is not attached');
136
170
  return;
137
171
  }
138
- await __classPrivateFieldGet(this, _DurabilitySocketCore_instances, "m", _DurabilitySocketCore_call).call(this, ws, frame);
172
+ await handle(ws, frame);
139
173
  }
140
174
  /**
141
175
  * Call from the Durable Object's `webSocketClose`. Subscriptions live in the
@@ -144,7 +178,13 @@ class DurabilitySocketCore {
144
178
  */
145
179
  webSocketClose(_ws) { }
146
180
  }
147
- _DurabilitySocketCore_context = new WeakMap(), _DurabilitySocketCore_storage = new WeakMap(), _DurabilitySocketCore_inbound = new WeakMap(), _DurabilitySocketCore_outboundNames = new WeakMap(), _DurabilitySocketCore_metadata = new WeakMap(), _DurabilitySocketCore_retention = new WeakMap(), _DurabilitySocketCore_instances = new WeakSet(), _DurabilitySocketCore_call = async function _DurabilitySocketCore_call(ws, frame) {
181
+ _DurabilitySocketCore_context = new WeakMap(), _DurabilitySocketCore_storage = new WeakMap(), _DurabilitySocketCore_inbound = new WeakMap(), _DurabilitySocketCore_outboundNames = new WeakMap(), _DurabilitySocketCore_metadata = new WeakMap(), _DurabilitySocketCore_retention = new WeakMap(), _DurabilitySocketCore_channel = new WeakMap(), _DurabilitySocketCore_frameHandlers = new WeakMap(), _DurabilitySocketCore_instances = new WeakSet(), _DurabilitySocketCore_handle = async function _DurabilitySocketCore_handle(ws, frame) {
182
+ if (frame.type === 'subscribe') {
183
+ __classPrivateFieldGet(this, _DurabilitySocketCore_instances, "m", _DurabilitySocketCore_subscribe).call(this, ws, frame);
184
+ return;
185
+ }
186
+ await __classPrivateFieldGet(this, _DurabilitySocketCore_instances, "m", _DurabilitySocketCore_call).call(this, ws, frame);
187
+ }, _DurabilitySocketCore_call = async function _DurabilitySocketCore_call(ws, frame) {
148
188
  const handler = __classPrivateFieldGet(this, _DurabilitySocketCore_inbound, "f").get(frame.method);
149
189
  if (!handler) {
150
190
  sendFrame(ws, {
@@ -222,13 +262,13 @@ _DurabilitySocketCore_context = new WeakMap(), _DurabilitySocketCore_storage = n
222
262
  return true;
223
263
  }
224
264
  const oldest = __classPrivateFieldGet(this, _DurabilitySocketCore_storage, "f").sql
225
- .exec('SELECT MIN(seq) AS seq FROM durability_socket_events')
265
+ .exec('SELECT MIN(seq) AS seq FROM durability_socket_events WHERE channel = ?', __classPrivateFieldGet(this, _DurabilitySocketCore_channel, "f"))
226
266
  .one().seq;
227
267
  if (since + 1 < oldest) {
228
268
  return false;
229
269
  }
230
270
  const rows = __classPrivateFieldGet(this, _DurabilitySocketCore_storage, "f").sql
231
- .exec('SELECT seq, name, payload FROM durability_socket_events WHERE seq > ? ORDER BY seq', since)
271
+ .exec('SELECT seq, name, payload FROM durability_socket_events WHERE channel = ? AND seq > ? ORDER BY seq', __classPrivateFieldGet(this, _DurabilitySocketCore_channel, "f"), since)
232
272
  .toArray();
233
273
  const wanted = new Set(names);
234
274
  for (const row of rows) {
@@ -246,16 +286,20 @@ _DurabilitySocketCore_context = new WeakMap(), _DurabilitySocketCore_storage = n
246
286
  return true;
247
287
  }, _DurabilitySocketCore_headSeq = function _DurabilitySocketCore_headSeq() {
248
288
  const row = __classPrivateFieldGet(this, _DurabilitySocketCore_storage, "f").sql
249
- .exec('SELECT MAX(seq) AS seq FROM durability_socket_events')
289
+ .exec('SELECT MAX(seq) AS seq FROM durability_socket_events WHERE channel = ?', __classPrivateFieldGet(this, _DurabilitySocketCore_channel, "f"))
250
290
  .one();
251
291
  return row.seq ?? 0;
252
292
  }, _DurabilitySocketCore_publish = function _DurabilitySocketCore_publish(name, payload) {
253
293
  const serialized = serialize(payload);
254
294
  const sql = __classPrivateFieldGet(this, _DurabilitySocketCore_storage, "f").sql;
295
+ // Trimming keeps the newest event of a channel, so its maximum never goes back.
255
296
  const { seq } = sql
256
- .exec('INSERT INTO durability_socket_events (name, payload, created_at) VALUES (?, ?, ?) RETURNING seq', name, serialized, Date.now())
297
+ .exec(`INSERT INTO durability_socket_events (channel, seq, name, payload, created_at)
298
+ SELECT ?, COALESCE(MAX(seq), 0) + 1, ?, ?, ?
299
+ FROM durability_socket_events WHERE channel = ?
300
+ RETURNING seq`, __classPrivateFieldGet(this, _DurabilitySocketCore_channel, "f"), name, serialized, Date.now(), __classPrivateFieldGet(this, _DurabilitySocketCore_channel, "f"))
257
301
  .one();
258
- sql.exec('DELETE FROM durability_socket_events WHERE seq <= ?', seq - __classPrivateFieldGet(this, _DurabilitySocketCore_retention, "f"));
302
+ sql.exec('DELETE FROM durability_socket_events WHERE channel = ? AND seq <= ?', __classPrivateFieldGet(this, _DurabilitySocketCore_channel, "f"), seq - __classPrivateFieldGet(this, _DurabilitySocketCore_retention, "f"));
259
303
  const frame = {
260
304
  v: socketProtocolVersion,
261
305
  type: 'event',
@@ -267,7 +311,9 @@ _DurabilitySocketCore_context = new WeakMap(), _DurabilitySocketCore_storage = n
267
311
  if (ws.readyState !== WebSocket.OPEN) {
268
312
  continue;
269
313
  }
270
- if (!readAttachment(ws).names.includes(name)) {
314
+ const attachment = readAttachment(ws);
315
+ if (attachment.channel !== __classPrivateFieldGet(this, _DurabilitySocketCore_channel, "f") ||
316
+ !attachment.names.includes(name)) {
271
317
  continue;
272
318
  }
273
319
  sendFrame(ws, frame);
@@ -279,4 +325,4 @@ traceMethods(DurabilitySocketCore.prototype, 'DurabilitySocket');
279
325
  // reserves every outbound method at runtime.
280
326
  export const DurabilitySocket = DurabilitySocketCore;
281
327
  export { durabilitySocketMigrations } from './migrations.js';
282
- export { event, } from './socket-protocol.js';
328
+ export { event, } from './protocol.js';
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Ordered SQLite migrations for the outbound event log owned by
3
+ * {@link DurabilitySocket}. Applied automatically on construction.
4
+ */
5
+ export declare const durabilitySocketMigrations: {
6
+ name: string;
7
+ up: string;
8
+ down: string;
9
+ }[];
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Ordered SQLite migrations for the outbound event log owned by
3
+ * {@link DurabilitySocket}. Applied automatically on construction.
4
+ */
5
+ export const durabilitySocketMigrations = [
6
+ {
7
+ name: 'durability_0006_create_socket_events',
8
+ up: `
9
+ CREATE TABLE IF NOT EXISTS durability_socket_events (
10
+ seq INTEGER PRIMARY KEY AUTOINCREMENT,
11
+ name TEXT NOT NULL,
12
+ payload TEXT NOT NULL,
13
+ created_at INTEGER NOT NULL
14
+ );
15
+ `,
16
+ down: 'DROP TABLE IF EXISTS durability_socket_events;',
17
+ },
18
+ {
19
+ // Each channel numbers its own events, so existing events keep their
20
+ // sequence numbers on the default channel.
21
+ name: 'durability_0023_socket_channels',
22
+ up: `
23
+ ALTER TABLE durability_socket_events RENAME TO durability_socket_events_before_channels;
24
+ CREATE TABLE durability_socket_events (
25
+ seq INTEGER NOT NULL,
26
+ name TEXT NOT NULL,
27
+ payload TEXT NOT NULL,
28
+ created_at INTEGER NOT NULL,
29
+ channel TEXT NOT NULL DEFAULT 'default',
30
+ PRIMARY KEY (channel, seq)
31
+ );
32
+ INSERT INTO durability_socket_events (seq, name, payload, created_at, channel)
33
+ SELECT seq, name, payload, created_at, 'default'
34
+ FROM durability_socket_events_before_channels;
35
+ DROP TABLE durability_socket_events_before_channels;
36
+ `,
37
+ down: `
38
+ CREATE TABLE durability_socket_events_channel_guard (
39
+ channel TEXT CONSTRAINT cannot_downgrade_nondefault_channels CHECK (channel = 'default')
40
+ );
41
+ INSERT INTO durability_socket_events_channel_guard
42
+ SELECT DISTINCT channel FROM durability_socket_events;
43
+ DROP TABLE durability_socket_events_channel_guard;
44
+ ALTER TABLE durability_socket_events RENAME TO durability_socket_events_with_channels;
45
+ CREATE TABLE durability_socket_events (
46
+ seq INTEGER PRIMARY KEY AUTOINCREMENT,
47
+ name TEXT NOT NULL,
48
+ payload TEXT NOT NULL,
49
+ created_at INTEGER NOT NULL
50
+ );
51
+ INSERT INTO durability_socket_events (seq, name, payload, created_at)
52
+ SELECT seq, name, payload, created_at
53
+ FROM durability_socket_events_with_channels;
54
+ DROP TABLE durability_socket_events_with_channels;
55
+ `,
56
+ },
57
+ ];
@@ -1,5 +1,5 @@
1
1
  import type { StandardSchemaV1 } from '@standard-schema/spec';
2
- import type { SerializedError } from './errors.js';
2
+ import type { SerializedError } from '../errors.js';
3
3
  export declare const socketProtocolVersion = 1;
4
4
  /** Largest text frame either side accepts, in UTF-16 code units. */
5
5
  export declare const socketMaxFrameLength: number;
package/dist/storage.d.ts CHANGED
@@ -5,7 +5,11 @@
5
5
  export type DurableTable = {
6
6
  name: string;
7
7
  key: string;
8
+ channel?: string;
8
9
  };
10
+ export declare const channelClause: (table: DurableTable) => string;
11
+ export declare const channelBindings: (table: DurableTable) => string[];
12
+ export declare const tableOwner: (table: DurableTable) => string;
9
13
  /** One attempt of one record generation. */
10
14
  export type AttemptRef = {
11
15
  key: string;
package/dist/storage.js CHANGED
@@ -1,21 +1,27 @@
1
- import { z } from 'zod';
2
- const attemptRowSchema = z.object({
3
- attempt: z.number().int().nonnegative(),
1
+ import * as v from 'valibot';
2
+ export const channelClause = (table) => table.channel === undefined ? '' : ' AND channel = ?';
3
+ export const channelBindings = (table) => table.channel === undefined ? [] : [table.channel];
4
+ // Keep existing memo owners on the default channel, without restricting record IDs.
5
+ export const tableOwner = (table) => table.channel === undefined || table.channel === 'default'
6
+ ? table.name
7
+ : JSON.stringify([table.name, table.channel]);
8
+ const attemptRowSchema = v.object({
9
+ attempt: v.pipe(v.number(), v.safeInteger(), v.minValue(0)),
4
10
  });
5
11
  // Every write is conditional on the record's generation and pending status, so a
6
12
  // stale execution can never overwrite a replacement or a later attempt.
7
- export const pendingGeneration = (table) => `${table.key} = ? AND generation_id = ? AND status = 'pending'`;
13
+ export const pendingGeneration = (table) => `${table.key} = ? AND generation_id = ? AND status = 'pending'${channelClause(table)}`;
8
14
  /**
9
15
  * Starts the next attempt, optionally persisting its deadline in the same write.
10
16
  * Returns undefined when the generation is gone or out of attempts.
11
17
  */
12
18
  export const claimAttempt = (sql, table, key, generation, maxAttempts, nextAttemptAt) => {
13
19
  const deadlineAssignment = nextAttemptAt === undefined ? '' : ', next_attempt_at = ?';
14
- return attemptRowSchema.optional().parse(sql
20
+ return v.parse(v.optional(attemptRowSchema), sql
15
21
  .exec(`UPDATE ${table.name}
16
22
  SET attempt = attempt + 1${deadlineAssignment}
17
23
  WHERE ${pendingGeneration(table)} AND attempt < ?
18
- RETURNING attempt`, ...(nextAttemptAt === undefined ? [] : [nextAttemptAt]), key, generation, maxAttempts)
24
+ RETURNING attempt`, ...(nextAttemptAt === undefined ? [] : [nextAttemptAt]), key, generation, ...channelBindings(table), maxAttempts)
19
25
  .toArray()[0])?.attempt;
20
26
  };
21
27
  /**
@@ -26,24 +32,24 @@ export const updateAttempt = (sql, table, ref, assignments, ...values) => sql
26
32
  .exec(`UPDATE ${table.name}
27
33
  SET ${assignments}
28
34
  WHERE ${pendingGeneration(table)} AND attempt = ?
29
- RETURNING ${table.key}`, ...values, ref.key, ref.generation, ref.attempt)
35
+ RETURNING ${table.key}`, ...values, ref.key, ref.generation, ...channelBindings(table), ref.attempt)
30
36
  .toArray().length > 0;
31
37
  /** Deletes the record if the attempt still owns it, and reports whether it did. */
32
38
  export const deleteAttempt = (sql, table, ref) => sql
33
39
  .exec(`DELETE FROM ${table.name}
34
40
  WHERE ${pendingGeneration(table)} AND attempt = ?
35
- RETURNING ${table.key}`, ref.key, ref.generation, ref.attempt)
41
+ RETURNING ${table.key}`, ref.key, ref.generation, ...channelBindings(table), ref.attempt)
36
42
  .toArray().length > 0;
37
43
  /** Fails a generation that has used every attempt and returns its attempt count. */
38
- export const exhaustAttempts = (sql, table, key, generation, maxAttempts, error) => attemptRowSchema.optional().parse(sql
44
+ export const exhaustAttempts = (sql, table, key, generation, maxAttempts, error) => v.parse(v.optional(attemptRowSchema), sql
39
45
  .exec(`UPDATE ${table.name}
40
46
  SET status = 'failed', last_error = ?, last_error_name = ?
41
47
  WHERE ${pendingGeneration(table)} AND attempt >= ?
42
- RETURNING attempt`, error.message, error.name, key, generation, maxAttempts)
48
+ RETURNING attempt`, error.message, error.name, key, generation, ...channelBindings(table), maxAttempts)
43
49
  .toArray()[0])?.attempt;
44
- const createdCursorSchema = z.tuple([
45
- z.number().int().nonnegative(),
46
- z.string(),
50
+ const createdCursorSchema = v.strictTuple([
51
+ v.pipe(v.number(), v.safeInteger(), v.minValue(0)),
52
+ v.string(),
47
53
  ]);
48
54
  /**
49
55
  * Lists records in creation order, then by key, filtered by status and by the
@@ -52,16 +58,17 @@ const createdCursorSchema = z.tuple([
52
58
  export const listCreated = (sql, table, nameColumn, query) => {
53
59
  const [createdAt, key] = query.after === undefined
54
60
  ? [-1, '']
55
- : createdCursorSchema.parse(JSON.parse(query.after));
61
+ : v.parse(createdCursorSchema, JSON.parse(query.after));
56
62
  const status = query.status ?? null;
57
63
  const name = query.name ?? null;
58
64
  const found = sql
59
65
  .exec(`SELECT * FROM ${table.name}
60
66
  WHERE (? IS NULL OR status = ?)
61
67
  AND (? IS NULL OR ${nameColumn} = ?)
68
+ ${channelClause(table)}
62
69
  AND (created_at > ? OR (created_at = ? AND ${table.key} > ?))
63
70
  ORDER BY created_at ASC, ${table.key} ASC
64
- LIMIT ?`, status, status, name, name, createdAt, createdAt, key, query.limit + 1)
71
+ LIMIT ?`, status, status, name, name, ...channelBindings(table), createdAt, createdAt, key, query.limit + 1)
65
72
  .toArray();
66
73
  const rows = found.slice(0, query.limit);
67
74
  const last = rows[rows.length - 1];