durability 5.1.0 → 5.2.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 (86) hide show
  1. package/README.md +145 -12
  2. package/dist/{durability-alarms.d.ts → alarms/index.d.ts} +13 -5
  3. package/dist/{durability-alarms.js → alarms/index.js} +69 -55
  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} +54 -46
  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} +15 -3
  16. package/dist/{log.js → log/index.js} +152 -124
  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} +14 -11
  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 +0 -612
  25. package/dist/{durability.d.ts → operations/index.d.ts} +13 -5
  26. package/dist/{durability.js → operations/index.js} +59 -47
  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} +16 -60
  31. package/dist/outbox/migrations.d.ts +9 -0
  32. package/dist/outbox/migrations.js +43 -0
  33. package/dist/{routing-client.js → routing/client.js} +1 -1
  34. package/dist/{routing.d.ts → routing/index.d.ts} +3 -3
  35. package/dist/{routing.js → routing/index.js} +3 -3
  36. package/dist/{load.d.ts → routing/load.d.ts} +1 -1
  37. package/dist/{schedule.d.ts → schedule/index.d.ts} +16 -8
  38. package/dist/{schedule.js → schedule/index.js} +65 -49
  39. package/dist/schedule/migrations.d.ts +9 -0
  40. package/dist/schedule/migrations.js +118 -0
  41. package/dist/{scheduler.d.ts → scheduler/index.d.ts} +75 -25
  42. package/dist/{scheduler.js → scheduler/index.js} +300 -63
  43. package/dist/{semaphore-client.d.ts → semaphore/client.d.ts} +1 -1
  44. package/dist/{semaphore-client.js → semaphore/client.js} +2 -2
  45. package/dist/{semaphore.d.ts → semaphore/index.d.ts} +10 -10
  46. package/dist/{semaphore.js → semaphore/index.js} +7 -7
  47. package/dist/{semaphore-leases.d.ts → semaphore/leases.d.ts} +17 -6
  48. package/dist/{semaphore-leases.js → semaphore/leases.js} +28 -12
  49. package/dist/semaphore/migrations.d.ts +18 -0
  50. package/dist/semaphore/migrations.js +444 -0
  51. package/dist/{semaphore-protocol.d.ts → semaphore/protocol.d.ts} +16 -8
  52. package/dist/{semaphore-protocol.js → semaphore/protocol.js} +37 -14
  53. package/dist/{semaphore-queue-store.d.ts → semaphore/queue-store.d.ts} +12 -6
  54. package/dist/{semaphore-queue-store.js → semaphore/queue-store.js} +69 -61
  55. package/dist/{semaphore-queue.d.ts → semaphore/queue.d.ts} +15 -5
  56. package/dist/{semaphore-queue.js → semaphore/queue.js} +105 -46
  57. package/dist/{semaphore-server.d.ts → semaphore/server.d.ts} +12 -4
  58. package/dist/{semaphore-server.js → semaphore/server.js} +51 -24
  59. package/dist/{semaphore-store.d.ts → semaphore/store.d.ts} +8 -3
  60. package/dist/{semaphore-store.js → semaphore/store.js} +35 -33
  61. package/dist/{client.d.ts → socket/client.d.ts} +3 -3
  62. package/dist/{client.js → socket/client.js} +4 -4
  63. package/dist/{socket.d.ts → socket/index.d.ts} +15 -4
  64. package/dist/{socket.js → socket/index.js} +66 -20
  65. package/dist/socket/migrations.d.ts +9 -0
  66. package/dist/socket/migrations.js +57 -0
  67. package/dist/{socket-protocol.d.ts → socket/protocol.d.ts} +1 -1
  68. package/dist/storage.d.ts +4 -0
  69. package/dist/storage.js +13 -6
  70. package/dist/{topology-client.d.ts → topology/client.d.ts} +2 -2
  71. package/dist/{topology-client.js → topology/client.js} +3 -3
  72. package/dist/{topology.d.ts → topology/index.d.ts} +17 -7
  73. package/dist/{topology.js → topology/index.js} +92 -58
  74. package/dist/topology/migrations.d.ts +10 -0
  75. package/dist/topology/migrations.js +138 -0
  76. package/dist/{tracker.d.ts → tracker/index.d.ts} +3 -3
  77. package/dist/{tracker.js → tracker/index.js} +2 -2
  78. package/package.json +11 -11
  79. /package/dist/{stored-message.js → fanout/stored-message.js} +0 -0
  80. /package/dist/{routing-client.d.ts → routing/client.d.ts} +0 -0
  81. /package/dist/{load.js → routing/load.js} +0 -0
  82. /package/dist/{socket-protocol.js → socket/protocol.js} +0 -0
  83. /package/dist/{topology-snapshot.d.ts → topology/snapshot.d.ts} +0 -0
  84. /package/dist/{topology-snapshot.js → topology/snapshot.js} +0 -0
  85. /package/dist/{tracked-source.d.ts → tracker/source.d.ts} +0 -0
  86. /package/dist/{tracked-source.js → tracker/source.js} +0 -0
@@ -2,6 +2,8 @@ import { z } from 'zod';
2
2
  export const grantRowSchema = z.object({
3
3
  grant_id: z.string(),
4
4
  client_id: z.string(),
5
+ /** The client's queue channel; `clientId` alone does not identify a client. */
6
+ client_channel: z.string(),
5
7
  grp: z.string(),
6
8
  permits: z.number().int().nonnegative(),
7
9
  claimed: z.number().int().nonnegative(),
@@ -14,6 +16,7 @@ export const grantRowSchema = z.object({
14
16
  export const leaseRowSchema = z.object({
15
17
  lease_id: z.string(),
16
18
  client_id: z.string(),
19
+ client_channel: z.string(),
17
20
  grp: z.string(),
18
21
  permits: z.number().int().nonnegative(),
19
22
  /** Drawn permits the client has returned, as a high-water mark. */
@@ -27,25 +30,26 @@ export const leaseRowSchema = z.object({
27
30
  const grantColumns = grantRowSchema.keyof().options;
28
31
  const leaseColumns = leaseRowSchema.keyof().options;
29
32
  /**
30
- * Permits a semaphore has handed out. Grants and leases are small and bounded
31
- * by live clients, so aggregates are computed from `list()`.
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()`.
32
37
  */
33
38
  export class HolderStore {
34
- constructor(sql) {
39
+ constructor(sql, channel) {
35
40
  this.sql = sql;
41
+ this.channel = channel;
36
42
  }
37
43
  list() {
38
- return grantRowSchema
39
- .array()
40
- .parse(this.sql
41
- .exec('SELECT * FROM durability_semaphore_grants ORDER BY created_at')
44
+ return grantRowSchema.array().parse(this.sql
45
+ .exec(`SELECT * FROM durability_semaphore_grants
46
+ WHERE channel = ? ORDER BY created_at`, this.channel)
42
47
  .toArray());
43
48
  }
44
49
  get(grantId) {
45
- return grantRowSchema
46
- .optional()
47
- .parse(this.sql
48
- .exec('SELECT * FROM durability_semaphore_grants WHERE grant_id = ? LIMIT 1', grantId)
50
+ return grantRowSchema.optional().parse(this.sql
51
+ .exec(`SELECT * FROM durability_semaphore_grants
52
+ WHERE channel = ? AND grant_id = ? LIMIT 1`, this.channel, grantId)
49
53
  .toArray()[0]);
50
54
  }
51
55
  nextPendingAt() {
@@ -54,55 +58,53 @@ export class HolderStore {
54
58
  .optional()
55
59
  .parse(this.sql
56
60
  .exec(`SELECT expires_at FROM durability_semaphore_grants
57
- WHERE claimed < permits
61
+ WHERE channel = ? AND claimed < permits
58
62
  ORDER BY expires_at ASC
59
- LIMIT 1`)
63
+ LIMIT 1`, this.channel)
60
64
  .toArray()[0])?.expires_at;
61
65
  }
62
66
  insert(row) {
63
67
  return (this.sql
64
- .exec(`INSERT INTO durability_semaphore_grants (${grantColumns.join(', ')})
65
- VALUES (${grantColumns.map(() => '?').join(', ')})
66
- ON CONFLICT(grant_id) DO NOTHING
67
- RETURNING grant_id`, ...grantColumns.map((column) => row[column]))
68
+ .exec(`INSERT INTO durability_semaphore_grants (channel, ${grantColumns.join(', ')})
69
+ VALUES (?, ${grantColumns.map(() => '?').join(', ')})
70
+ ON CONFLICT(channel, grant_id) DO NOTHING
71
+ RETURNING grant_id`, this.channel, ...grantColumns.map((column) => row[column]))
68
72
  .toArray().length > 0);
69
73
  }
70
74
  update(row) {
71
75
  this.sql.exec(`UPDATE durability_semaphore_grants
72
76
  SET permits = ?, claimed = ?, released = ?, expires_at = ?
73
- WHERE grant_id = ?`, row.permits, row.claimed, row.released, row.expires_at, row.grant_id);
77
+ WHERE channel = ? AND grant_id = ?`, row.permits, row.claimed, row.released, row.expires_at, this.channel, row.grant_id);
74
78
  }
75
79
  remove(grantId) {
76
- this.sql.exec('DELETE FROM durability_semaphore_grants WHERE grant_id = ?', grantId);
80
+ this.sql.exec('DELETE FROM durability_semaphore_grants WHERE channel = ? AND grant_id = ?', this.channel, grantId);
77
81
  }
78
82
  listLeases() {
79
- return leaseRowSchema
80
- .array()
81
- .parse(this.sql
82
- .exec('SELECT * FROM durability_semaphore_leases ORDER BY created_at')
83
+ return leaseRowSchema.array().parse(this.sql
84
+ .exec(`SELECT * FROM durability_semaphore_leases
85
+ WHERE channel = ? ORDER BY created_at`, this.channel)
83
86
  .toArray());
84
87
  }
85
88
  getLease(leaseId) {
86
- return leaseRowSchema
87
- .optional()
88
- .parse(this.sql
89
- .exec('SELECT * FROM durability_semaphore_leases WHERE lease_id = ? LIMIT 1', leaseId)
89
+ return leaseRowSchema.optional().parse(this.sql
90
+ .exec(`SELECT * FROM durability_semaphore_leases
91
+ WHERE channel = ? AND lease_id = ? LIMIT 1`, this.channel, leaseId)
90
92
  .toArray()[0]);
91
93
  }
92
94
  insertLease(row) {
93
95
  return (this.sql
94
- .exec(`INSERT INTO durability_semaphore_leases (${leaseColumns.join(', ')})
95
- VALUES (${leaseColumns.map(() => '?').join(', ')})
96
- ON CONFLICT(lease_id) DO NOTHING
97
- RETURNING lease_id`, ...leaseColumns.map((column) => row[column]))
96
+ .exec(`INSERT INTO durability_semaphore_leases (channel, ${leaseColumns.join(', ')})
97
+ VALUES (?, ${leaseColumns.map(() => '?').join(', ')})
98
+ ON CONFLICT(channel, lease_id) DO NOTHING
99
+ RETURNING lease_id`, this.channel, ...leaseColumns.map((column) => row[column]))
98
100
  .toArray().length > 0);
99
101
  }
100
102
  updateLease(row) {
101
103
  this.sql.exec(`UPDATE durability_semaphore_leases
102
104
  SET permits = ?, released = ?, expires_at = ?, retired = ?
103
- WHERE lease_id = ?`, row.permits, row.released, row.expires_at, row.retired, row.lease_id);
105
+ WHERE channel = ? AND lease_id = ?`, row.permits, row.released, row.expires_at, row.retired, this.channel, row.lease_id);
104
106
  }
105
107
  removeLease(leaseId) {
106
- this.sql.exec('DELETE FROM durability_semaphore_leases WHERE lease_id = ?', leaseId);
108
+ this.sql.exec('DELETE FROM durability_semaphore_leases WHERE channel = ? AND lease_id = ?', this.channel, leaseId);
107
109
  }
108
110
  }
@@ -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,10 +1,16 @@
1
1
  import { z } from 'zod';
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]);
2
8
  const attemptRowSchema = z.object({
3
9
  attempt: z.number().int().nonnegative(),
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.
@@ -15,7 +21,7 @@ export const claimAttempt = (sql, table, key, generation, maxAttempts, nextAttem
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,20 +32,20 @@ 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
44
  export const exhaustAttempts = (sql, table, key, generation, maxAttempts, error) => attemptRowSchema.optional().parse(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
50
  const createdCursorSchema = z.tuple([
45
51
  z.number().int().nonnegative(),
@@ -59,9 +65,10 @@ export const listCreated = (sql, table, nameColumn, query) => {
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];
@@ -1,5 +1,5 @@
1
- import { type TopologyFallbackReason } from './errors.js';
2
- import { type TopologyMemberInput, type TopologySnapshot } from './topology-snapshot.js';
1
+ import { type TopologyFallbackReason } from '../errors.js';
2
+ import { type TopologyMemberInput, type TopologySnapshot } from './snapshot.js';
3
3
  export type TopologySource = 'published' | 'stale' | 'seed' | 'fallback';
4
4
  export type TopologyView<Meta = undefined> = TopologySnapshot<Meta> & {
5
5
  source: TopologySource;
@@ -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 _TopologyClient_instances, _TopologyClient_config, _TopologyClient_readTimeoutMs, _TopologyClient_ttlMs, _TopologyClient_negativeTtlMs, _TopologyClient_cache, _TopologyClient_inflight, _TopologyClient_load, _TopologyClient_read, _TopologyClient_fallback, _TopologyClient_remember;
13
- import { TopologyUnavailableError, } from './errors.js';
14
- import { assertPositiveInteger } from './policy.js';
15
- import { decodeSnapshot, } from './topology-snapshot.js';
13
+ import { TopologyUnavailableError, } from '../errors.js';
14
+ import { assertPositiveInteger } from '../policy.js';
15
+ import { decodeSnapshot, } from './snapshot.js';
16
16
  // High-cardinality groups (one per tenant) must not grow an isolate without bound; the least recently used go first.
17
17
  const maxCachedGroups = 1024;
18
18
  class ReadTimeoutError extends Error {
@@ -1,7 +1,7 @@
1
- import { type DurabilityOutboxEvent } from './outbox.js';
2
- import { type SchedulerAttachment } from './scheduler.js';
3
- import { TopologyClient, type TopologyClientConfig } from './topology-client.js';
4
- import { type TopologyMember, type TopologyMemberInput, type TopologySnapshot } from './topology-snapshot.js';
1
+ import { type DurabilityOutboxEvent } from '../outbox/index.js';
2
+ import { type SchedulerAttachment } from '../scheduler/index.js';
3
+ import { TopologyClient, type TopologyClientConfig } from './client.js';
4
+ import { type TopologyMember, type TopologyMemberInput, type TopologySnapshot } from './snapshot.js';
5
5
  /** `write` channels reach active members; `read` channels reach draining members too. */
6
6
  export type TopologyRole = 'write' | 'read';
7
7
  /** Publication and sync never give up: a stale topology must still converge. */
@@ -32,11 +32,21 @@ export type TopologyChannel<Value, Meta> = TopologyRetryOptions & {
32
32
  deliver(member: TopologyMember<Meta>, update: TopologyStateUpdate<Value>): unknown;
33
33
  };
34
34
  /**
35
- * Publication and sync run on outbox channels: `durability.topology` keyed by
36
- * group, and `durability.topology.<channel>` keyed by `[group, member]`.
35
+ * Publication and sync run on outbox channels keyed by group and by
36
+ * `[group, member]`. On the default instance channel these are
37
+ * `durability.topology` and `durability.topology.<state>`; on another instance
38
+ * channel they are JSON arrays: `["durability.topology", <channel>,
39
+ * "publication"]` and `["durability.topology", <channel>, "state", <state>]`.
37
40
  */
38
41
  export type DurabilityTopologyEvent = DurabilityOutboxEvent;
39
42
  export type DurabilityTopologyConfig<Meta, States extends Record<string, unknown>> = SchedulerAttachment & TopologyRetryOptions & {
43
+ /**
44
+ * Stable instance ID. Topologies on one scheduler share storage,
45
+ * partitioned by channel; each owns its groups, states, publisher, and
46
+ * deliveries, so the same group name in two channels is two groups.
47
+ * Defaults to `default`.
48
+ */
49
+ channel?: string;
40
50
  /** Without a publisher, membership is only visible inside this object. */
41
51
  publish?: TopologyPublisher<Meta>;
42
52
  states?: {
@@ -66,7 +76,7 @@ export declare class DurabilityTopology<Meta = undefined, States extends Record<
66
76
  /** A read-only client for stateless Workers. It never contacts the coordinator. */
67
77
  static client<Meta = undefined>(config: TopologyClientConfig<Meta>): TopologyClient<Meta>;
68
78
  /** Reverts only the topology tables; outbox channels migrateCapability with `DurabilityOutbox.migrate`. */
69
- static migrate(context: Pick<DurableObjectState, 'storage'>, target?: string | null): import("./migrations.js").DurabilityMigrationResult;
79
+ static migrate(context: Pick<DurableObjectState, 'storage'>, target?: string | null): import("../migrations.js").DurabilityMigrationResult;
70
80
  alarm(info?: AlarmInvocationInfo): Promise<void>;
71
81
  /**
72
82
  * Applies one change in a single transaction. `next` runs inside it and must