durability 5.0.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 (89) hide show
  1. package/README.md +238 -7
  2. package/dist/{durability-alarms.d.ts → alarms/index.d.ts} +23 -6
  3. package/dist/{durability-alarms.js → alarms/index.js} +96 -52
  4. package/dist/alarms/migrations.d.ts +9 -0
  5. package/dist/alarms/migrations.js +133 -0
  6. package/dist/errors.d.ts +15 -0
  7. package/dist/errors.js +24 -0
  8. package/dist/experimental.d.ts +11 -8
  9. package/dist/experimental.js +8 -5
  10. package/dist/{fanout.d.ts → fanout/index.d.ts} +13 -6
  11. package/dist/{fanout.js → fanout/index.js} +55 -49
  12. package/dist/fanout/migrations.d.ts +9 -0
  13. package/dist/fanout/migrations.js +181 -0
  14. package/dist/{stored-message.d.ts → fanout/stored-message.d.ts} +1 -1
  15. package/dist/index.d.ts +14 -9
  16. package/dist/index.js +13 -8
  17. package/dist/{log.d.ts → log/index.d.ts} +15 -3
  18. package/dist/{log.js → log/index.js} +152 -124
  19. package/dist/log/migrations.d.ts +18 -0
  20. package/dist/log/migrations.js +297 -0
  21. package/dist/{memoize.d.ts → memoize/index.d.ts} +1 -1
  22. package/dist/{memoize.js → memoize/index.js} +14 -11
  23. package/dist/memoize/migrations.d.ts +10 -0
  24. package/dist/memoize/migrations.js +21 -0
  25. package/dist/migrations.d.ts +1 -103
  26. package/dist/migrations.js +1 -570
  27. package/dist/{durability.d.ts → operations/index.d.ts} +13 -5
  28. package/dist/{durability.js → operations/index.js} +63 -46
  29. package/dist/operations/migrations.d.ts +10 -0
  30. package/dist/operations/migrations.js +150 -0
  31. package/dist/{outbox.d.ts → outbox/index.d.ts} +4 -4
  32. package/dist/{outbox.js → outbox/index.js} +18 -63
  33. package/dist/outbox/migrations.d.ts +9 -0
  34. package/dist/outbox/migrations.js +43 -0
  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/index.d.ts +165 -0
  40. package/dist/schedule/index.js +667 -0
  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} +122 -22
  44. package/dist/scheduler/index.js +925 -0
  45. package/dist/{semaphore-client.d.ts → semaphore/client.d.ts} +1 -1
  46. package/dist/{semaphore-client.js → semaphore/client.js} +2 -2
  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 → semaphore/protocol.d.ts} +16 -8
  54. package/dist/{semaphore-protocol.js → semaphore/protocol.js} +37 -14
  55. package/dist/{semaphore-queue-store.d.ts → semaphore/queue-store.d.ts} +12 -6
  56. package/dist/{semaphore-queue-store.js → semaphore/queue-store.js} +87 -75
  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} +51 -24
  61. package/dist/{semaphore-store.d.ts → semaphore/store.d.ts} +8 -3
  62. package/dist/{semaphore-store.js → semaphore/store.js} +35 -33
  63. package/dist/{client.d.ts → socket/client.d.ts} +3 -3
  64. package/dist/{client.js → socket/client.js} +4 -4
  65. package/dist/{socket.d.ts → socket/index.d.ts} +15 -4
  66. package/dist/{socket.js → socket/index.js} +66 -20
  67. package/dist/socket/migrations.d.ts +9 -0
  68. package/dist/socket/migrations.js +57 -0
  69. package/dist/{socket-protocol.d.ts → socket/protocol.d.ts} +1 -1
  70. package/dist/storage.d.ts +9 -2
  71. package/dist/storage.js +24 -11
  72. package/dist/{topology-client.d.ts → topology/client.d.ts} +2 -2
  73. package/dist/{topology-client.js → topology/client.js} +3 -3
  74. package/dist/{topology.d.ts → topology/index.d.ts} +17 -7
  75. package/dist/{topology.js → topology/index.js} +92 -58
  76. package/dist/topology/migrations.d.ts +10 -0
  77. package/dist/topology/migrations.js +138 -0
  78. package/dist/{tracker.d.ts → tracker/index.d.ts} +3 -3
  79. package/dist/{tracker.js → tracker/index.js} +2 -2
  80. package/package.json +11 -11
  81. package/dist/scheduler.js +0 -577
  82. /package/dist/{stored-message.js → fanout/stored-message.js} +0 -0
  83. /package/dist/{routing-client.d.ts → routing/client.d.ts} +0 -0
  84. /package/dist/{load.js → routing/load.js} +0 -0
  85. /package/dist/{socket-protocol.js → socket/protocol.js} +0 -0
  86. /package/dist/{topology-snapshot.d.ts → topology/snapshot.d.ts} +0 -0
  87. /package/dist/{topology-snapshot.js → topology/snapshot.js} +0 -0
  88. /package/dist/{tracked-source.d.ts → tracker/source.d.ts} +0 -0
  89. /package/dist/{tracked-source.js → tracker/source.js} +0 -0
@@ -10,14 +10,15 @@ 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 _DurabilitySemaphoreServer_instances, _DurabilitySemaphoreServer_engine, _DurabilitySemaphoreServer_store, _DurabilitySemaphoreServer_limit, _DurabilitySemaphoreServer_groupLimit, _DurabilitySemaphoreServer_canGrant, _DurabilitySemaphoreServer_roundWaitMs, _DurabilitySemaphoreServer_roundPeriodMs, _DurabilitySemaphoreServer_grantTimeoutMs, _DurabilitySemaphoreServer_leases, _DurabilitySemaphoreServer_emit, _DurabilitySemaphoreServer_pending, _DurabilitySemaphoreServer_roundTimer, _DurabilitySemaphoreServer_round, _DurabilitySemaphoreServer_lastRoundAt, _DurabilitySemaphoreServer_contended, _DurabilitySemaphoreServer_grantRoom, _DurabilitySemaphoreServer_scheduleRound, _DurabilitySemaphoreServer_runRound, _DurabilitySemaphoreServer_allocate, _DurabilitySemaphoreServer_sync, _DurabilitySemaphoreServer_applyReports, _DurabilitySemaphoreServer_reclaim, _DurabilitySemaphoreServer_reclaimExpired, _DurabilitySemaphoreServer_resolveLimit, _DurabilitySemaphoreServer_groupPolicy;
13
- import { traceLifecycle, traceMethods } from './dev.js';
14
- import { SemaphoreProtocolError, reportFailure } from './errors.js';
15
- import { durabilitySemaphoreMigrations, migrateCapability, } from './migrations.js';
16
- import { assertPositiveInteger } from './policy.js';
17
- import { allocateLeases, applyLeaseReports, budgets, leaseFootprint, resolveLeasePolicy, } from './semaphore-leases.js';
18
- import { engineFor, } from './scheduler.js';
19
- import { semaphoreRequestSchema, } from './semaphore-protocol.js';
20
- import { HolderStore } from './semaphore-store.js';
13
+ import { traceLifecycle, traceMethods } from '../dev.js';
14
+ import { SemaphoreProtocolError, reportFailure } from '../errors.js';
15
+ import { durabilitySemaphoreMigrations } from './migrations.js';
16
+ import { migrateCapability, } from '../migrations.js';
17
+ import { assertPositiveInteger } from '../policy.js';
18
+ import { allocateLeases, applyLeaseReports, budgets, clientKey, leaseFootprint, ownedBy, resolveLeasePolicy, } from './leases.js';
19
+ import { assertChannel, defaultChannel, engineFor, } from '../scheduler/index.js';
20
+ import { semaphoreRequestSchema, } from './protocol.js';
21
+ import { HolderStore } from './store.js';
21
22
  const grantsTable = {
22
23
  name: 'durability_semaphore_grants',
23
24
  key: 'grant_id',
@@ -27,6 +28,20 @@ const maxDelayMs = 2 ** 31 - 1;
27
28
  /** Unclaimed permits are reclaimed once the claim window passes. */
28
29
  const effectivePermits = (grant, now) => now >= grant.expires_at ? grant.claimed : grant.permits;
29
30
  const outstanding = (grant, now) => Math.max(0, effectivePermits(grant, now) - grant.released);
31
+ const clientOf = (message) => ({
32
+ clientId: message.clientId,
33
+ clientChannel: message.clientChannel ?? defaultChannel,
34
+ });
35
+ /**
36
+ * Echoes the protocol identity so the client can verify which queue was counted.
37
+ * Version 1 retains the response shape older clients expect.
38
+ */
39
+ const acknowledgement = (message) => ({
40
+ v: message.v,
41
+ ...(message.clientChannel === undefined
42
+ ? {}
43
+ : { clientChannel: message.clientChannel }),
44
+ });
30
45
  /** Permits left queued per (group, reason) across one round's allocations. */
31
46
  const blockedCounts = (allocations) => {
32
47
  const counts = new Map();
@@ -75,6 +90,7 @@ export class DurabilitySemaphoreServer {
75
90
  _DurabilitySemaphoreServer_lastRoundAt.set(this, -Infinity);
76
91
  // From the last round; tells clients in later syncs to return idle lease headroom.
77
92
  _DurabilitySemaphoreServer_contended.set(this, false);
93
+ const channel = assertChannel('Semaphore', config.channel ?? defaultChannel);
78
94
  const limit = config.limit;
79
95
  __classPrivateFieldSet(this, _DurabilitySemaphoreServer_limit, typeof limit === 'function' ? limit : () => limit, "f");
80
96
  if (typeof limit === 'number' &&
@@ -100,9 +116,12 @@ export class DurabilitySemaphoreServer {
100
116
  __classPrivateFieldSet(this, _DurabilitySemaphoreServer_engine, engineFor(config), "f");
101
117
  __classPrivateFieldSet(this, _DurabilitySemaphoreServer_emit, traceLifecycle(__classPrivateFieldGet(this, _DurabilitySemaphoreServer_engine, "f").emitter(config.onLifecycleEvent)), "f");
102
118
  __classPrivateFieldGet(this, _DurabilitySemaphoreServer_engine, "f").migrateSchema('semaphore', durabilitySemaphoreMigrations);
103
- __classPrivateFieldSet(this, _DurabilitySemaphoreServer_store, new HolderStore(__classPrivateFieldGet(this, _DurabilitySemaphoreServer_engine, "f").sql), "f");
104
- __classPrivateFieldGet(this, _DurabilitySemaphoreServer_engine, "f").register({
119
+ __classPrivateFieldSet(this, _DurabilitySemaphoreServer_store, new HolderStore(__classPrivateFieldGet(this, _DurabilitySemaphoreServer_engine, "f").sql, channel), "f");
120
+ __classPrivateFieldGet(this, _DurabilitySemaphoreServer_engine, "f").registerChannel({
105
121
  table: grantsTable,
122
+ channelTables: ['durability_semaphore_leases'],
123
+ channel,
124
+ helper: 'A semaphore',
106
125
  runDue: () => __classPrivateFieldGet(this, _DurabilitySemaphoreServer_instances, "m", _DurabilitySemaphoreServer_reclaimExpired).call(this),
107
126
  nextPendingAt: () => __classPrivateFieldGet(this, _DurabilitySemaphoreServer_store, "f").nextPendingAt(),
108
127
  });
@@ -129,7 +148,12 @@ export class DurabilitySemaphoreServer {
129
148
  }
130
149
  const request = parsed.data;
131
150
  return new Promise((resolve, reject) => {
132
- __classPrivateFieldGet(this, _DurabilitySemaphoreServer_pending, "f").push({ request, resolve, reject });
151
+ __classPrivateFieldGet(this, _DurabilitySemaphoreServer_pending, "f").push({
152
+ request,
153
+ client: clientOf(request),
154
+ resolve,
155
+ reject,
156
+ });
133
157
  __classPrivateFieldGet(this, _DurabilitySemaphoreServer_instances, "m", _DurabilitySemaphoreServer_scheduleRound).call(this);
134
158
  });
135
159
  }
@@ -223,7 +247,7 @@ _DurabilitySemaphoreServer_engine = new WeakMap(), _DurabilitySemaphoreServer_st
223
247
  const { leases, ...rest } = allocation;
224
248
  entry.resolve({
225
249
  type: 'grant',
226
- v: 1,
250
+ ...acknowledgement(entry.request),
227
251
  ...rest,
228
252
  nextRequestAt,
229
253
  ...(entry.request.leases === undefined
@@ -258,11 +282,10 @@ _DurabilitySemaphoreServer_engine = new WeakMap(), _DurabilitySemaphoreServer_st
258
282
  let unknownDebt = 0;
259
283
  const drawn = new Map();
260
284
  for (const entry of pending) {
261
- const { clientId } = entry.request;
262
- const grantResults = __classPrivateFieldGet(this, _DurabilitySemaphoreServer_instances, "m", _DurabilitySemaphoreServer_applyReports).call(this, store, clientId, entry.request.grants, now);
285
+ const grantResults = __classPrivateFieldGet(this, _DurabilitySemaphoreServer_instances, "m", _DurabilitySemaphoreServer_applyReports).call(this, store, entry.client, entry.request.grants, now);
263
286
  const leases = [];
264
287
  if (__classPrivateFieldGet(this, _DurabilitySemaphoreServer_leases, "f") && entry.request.leases) {
265
- const outcome = applyLeaseReports(store, __classPrivateFieldGet(this, _DurabilitySemaphoreServer_leases, "f"), clientId, entry.request.leases, now);
288
+ const outcome = applyLeaseReports(store, __classPrivateFieldGet(this, _DurabilitySemaphoreServer_leases, "f"), entry.client, entry.request.leases, now);
266
289
  leases.push(...outcome.echoes);
267
290
  unknownDebt += outcome.unknownDebt;
268
291
  for (const [leaseId, count] of outcome.drawn) {
@@ -293,7 +316,8 @@ _DurabilitySemaphoreServer_engine = new WeakMap(), _DurabilitySemaphoreServer_st
293
316
  const demands = pending
294
317
  .flatMap((entry) => entry.request.demand.map((demand) => ({ entry, ...demand })))
295
318
  .sort((left, right) => left.oldestAt - right.oldestAt ||
296
- left.entry.request.clientId.localeCompare(right.entry.request.clientId));
319
+ left.entry.client.clientId.localeCompare(right.entry.client.clientId) ||
320
+ left.entry.client.clientChannel.localeCompare(right.entry.client.clientChannel));
297
321
  let requested = 0;
298
322
  let granted = 0;
299
323
  for (const demand of demands) {
@@ -313,7 +337,8 @@ _DurabilitySemaphoreServer_engine = new WeakMap(), _DurabilitySemaphoreServer_st
313
337
  if (give > 0) {
314
338
  const grant = {
315
339
  grant_id: crypto.randomUUID(),
316
- client_id: demand.entry.request.clientId,
340
+ client_id: demand.entry.client.clientId,
341
+ client_channel: demand.entry.client.clientChannel,
317
342
  grp: demand.group,
318
343
  permits: give,
319
344
  claimed: 0,
@@ -345,7 +370,7 @@ _DurabilitySemaphoreServer_engine = new WeakMap(), _DurabilitySemaphoreServer_st
345
370
  const candidates = pending.flatMap((entry) => entry.request.leases === undefined
346
371
  ? []
347
372
  : entry.request.demand.map((demand) => ({
348
- clientId: entry.request.clientId,
373
+ ...entry.client,
349
374
  group: demand.group,
350
375
  oldestAt: demand.oldestAt,
351
376
  })));
@@ -373,7 +398,7 @@ _DurabilitySemaphoreServer_engine = new WeakMap(), _DurabilitySemaphoreServer_st
373
398
  // One echo per lease; the allocator's view (e.g. retired) supersedes the report's.
374
399
  const byLease = new Map([
375
400
  ...allocation.leases,
376
- ...(outcome.grants.get(entry.request.clientId) ?? []),
401
+ ...(outcome.grants.get(clientKey(entry.client.clientId, entry.client.clientChannel)) ?? []),
377
402
  ].map((lease) => [lease.leaseId, lease]));
378
403
  allocation.leases = [...byLease.values()];
379
404
  }
@@ -407,17 +432,18 @@ _DurabilitySemaphoreServer_engine = new WeakMap(), _DurabilitySemaphoreServer_st
407
432
  };
408
433
  }, _DurabilitySemaphoreServer_sync = async function _DurabilitySemaphoreServer_sync(message) {
409
434
  const now = Date.now();
435
+ const client = clientOf(message);
410
436
  const result = await __classPrivateFieldGet(this, _DurabilitySemaphoreServer_engine, "f").transaction(() => {
411
437
  const store = __classPrivateFieldGet(this, _DurabilitySemaphoreServer_store, "f");
412
- const grantResults = __classPrivateFieldGet(this, _DurabilitySemaphoreServer_instances, "m", _DurabilitySemaphoreServer_applyReports).call(this, store, message.clientId, message.grants, now);
438
+ const grantResults = __classPrivateFieldGet(this, _DurabilitySemaphoreServer_instances, "m", _DurabilitySemaphoreServer_applyReports).call(this, store, client, message.grants, now);
413
439
  const leaseOutcome = __classPrivateFieldGet(this, _DurabilitySemaphoreServer_leases, "f") && message.leases
414
- ? applyLeaseReports(store, __classPrivateFieldGet(this, _DurabilitySemaphoreServer_leases, "f"), message.clientId, message.leases, now)
440
+ ? applyLeaseReports(store, __classPrivateFieldGet(this, _DurabilitySemaphoreServer_leases, "f"), client, message.leases, now)
415
441
  : undefined;
416
442
  return { grantResults, leaseEchoes: leaseOutcome?.echoes };
417
443
  });
418
444
  return {
419
445
  type: 'synced',
420
- v: 1,
446
+ ...acknowledgement(message),
421
447
  grantResults: result.grantResults,
422
448
  ...(result.leaseEchoes === undefined
423
449
  ? {}
@@ -426,11 +452,11 @@ _DurabilitySemaphoreServer_engine = new WeakMap(), _DurabilitySemaphoreServer_st
426
452
  ...(__classPrivateFieldGet(this, _DurabilitySemaphoreServer_contended, "f") ? { contended: true } : {}),
427
453
  }),
428
454
  };
429
- }, _DurabilitySemaphoreServer_applyReports = function _DurabilitySemaphoreServer_applyReports(store, clientId, reports, now) {
455
+ }, _DurabilitySemaphoreServer_applyReports = function _DurabilitySemaphoreServer_applyReports(store, client, reports, now) {
430
456
  const results = [];
431
457
  for (const report of reports) {
432
458
  const grant = store.get(report.grantId);
433
- if (!grant || grant.client_id !== clientId) {
459
+ if (!grant || !ownedBy(grant, client)) {
434
460
  results.push({
435
461
  grantId: report.grantId,
436
462
  claimed: 0,
@@ -478,6 +504,7 @@ _DurabilitySemaphoreServer_engine = new WeakMap(), _DurabilitySemaphoreServer_st
478
504
  timestamp: now,
479
505
  grantId: grant.grant_id,
480
506
  clientId: grant.client_id,
507
+ clientChannel: grant.client_channel,
481
508
  group: grant.grp,
482
509
  permits: grant.permits - grant.claimed,
483
510
  });
@@ -2,6 +2,7 @@ import { z } from 'zod';
2
2
  export declare const grantRowSchema: z.ZodObject<{
3
3
  grant_id: z.ZodString;
4
4
  client_id: z.ZodString;
5
+ client_channel: z.ZodString;
5
6
  grp: z.ZodString;
6
7
  permits: z.ZodNumber;
7
8
  claimed: z.ZodNumber;
@@ -14,6 +15,7 @@ export type GrantRow = z.infer<typeof grantRowSchema>;
14
15
  export declare const leaseRowSchema: z.ZodObject<{
15
16
  lease_id: z.ZodString;
16
17
  client_id: z.ZodString;
18
+ client_channel: z.ZodString;
17
19
  grp: z.ZodString;
18
20
  permits: z.ZodNumber;
19
21
  released: z.ZodNumber;
@@ -23,12 +25,15 @@ export declare const leaseRowSchema: z.ZodObject<{
23
25
  }, z.core.$strip>;
24
26
  export type LeaseRow = z.infer<typeof leaseRowSchema>;
25
27
  /**
26
- * Permits a semaphore has handed out. Grants and leases are small and bounded
27
- * by live clients, so aggregates are computed from `list()`.
28
+ * Permits one semaphore channel has handed out. Every query is scoped to the
29
+ * channel, so semaphores sharing an object never see each other's grants or
30
+ * leases. Grants and leases are small and bounded by live clients, so
31
+ * aggregates are computed from `list()`.
28
32
  */
29
33
  export declare class HolderStore {
30
34
  private readonly sql;
31
- constructor(sql: SqlStorage);
35
+ private readonly channel;
36
+ constructor(sql: SqlStorage, channel: string);
32
37
  list(): GrantRow[];
33
38
  get(grantId: string): GrantRow | undefined;
34
39
  nextPendingAt(): number | undefined;
@@ -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
+ }[];