durability 5.2.1 → 5.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/README.md +42 -18
  2. package/dist/alarms/index.d.ts +1 -1
  3. package/dist/alarms/index.js +6 -3
  4. package/dist/dev.d.ts +7 -3
  5. package/dist/dev.js +17 -11
  6. package/dist/durable-object-target.js +8 -4
  7. package/dist/errors.d.ts +13 -7
  8. package/dist/errors.js +34 -32
  9. package/dist/fanout/index.d.ts +1 -1
  10. package/dist/fanout/index.js +15 -26
  11. package/dist/lifecycle.d.ts +1 -0
  12. package/dist/lifecycle.js +2 -2
  13. package/dist/log/index.js +5 -2
  14. package/dist/memoize/index.js +6 -1
  15. package/dist/migrations.js +37 -37
  16. package/dist/operations/index.js +8 -4
  17. package/dist/outbox/index.d.ts +1 -1
  18. package/dist/outbox/index.js +7 -17
  19. package/dist/policy.d.ts +1 -1
  20. package/dist/policy.js +2 -1
  21. package/dist/predicates.d.ts +9 -0
  22. package/dist/predicates.js +10 -0
  23. package/dist/routing/client.js +3 -4
  24. package/dist/routing/index.d.ts +1 -1
  25. package/dist/routing/index.js +14 -10
  26. package/dist/schedule/index.d.ts +15 -3
  27. package/dist/schedule/index.js +55 -36
  28. package/dist/scheduler/index.d.ts +35 -14
  29. package/dist/scheduler/index.js +78 -74
  30. package/dist/semaphore/client.js +2 -1
  31. package/dist/semaphore/index.d.ts +1 -1
  32. package/dist/semaphore/index.js +10 -5
  33. package/dist/semaphore/leases.d.ts +3 -2
  34. package/dist/semaphore/leases.js +3 -2
  35. package/dist/semaphore/queue-store.js +2 -1
  36. package/dist/semaphore/queue.d.ts +1 -1
  37. package/dist/semaphore/queue.js +36 -37
  38. package/dist/semaphore/server.js +50 -32
  39. package/dist/serialization.d.ts +3 -2
  40. package/dist/serialization.js +16 -13
  41. package/dist/shared-timer.d.ts +27 -0
  42. package/dist/shared-timer.js +191 -0
  43. package/dist/socket/client.d.ts +21 -7
  44. package/dist/socket/client.js +37 -27
  45. package/dist/socket/index.d.ts +20 -13
  46. package/dist/socket/index.js +40 -18
  47. package/dist/socket/protocol.d.ts +37 -17
  48. package/dist/socket/protocol.js +30 -36
  49. package/dist/topology/client.js +36 -19
  50. package/dist/topology/index.d.ts +3 -3
  51. package/dist/topology/index.js +40 -49
  52. package/dist/topology/snapshot.d.ts +6 -5
  53. package/dist/topology/snapshot.js +5 -2
  54. package/dist/tracker/index.js +18 -7
  55. package/dist/tracker/source.d.ts +6 -2
  56. package/package.json +2 -2
@@ -9,9 +9,11 @@ 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 _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;
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_timer, _Connection_cancelRetry, _Connection_cancelPing, _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
13
  import { reportFailure } from '../errors.js';
14
+ import { isString } from '../predicates.js';
14
15
  import { parseServerFrame, socketProtocolErrorCode, socketProtocolVersion, } from './protocol.js';
16
+ import { SharedTimer } from '../shared-timer.js';
15
17
  import { exponential, jitter } from '../utils.js';
16
18
  /** Rejection for calls still waiting when `close()` was called. */
17
19
  export class SocketClosedError extends Error {
@@ -71,8 +73,10 @@ class Connection {
71
73
  _Connection_nextId.set(this, 0);
72
74
  _Connection_lastSeq.set(this, void 0);
73
75
  _Connection_attempt.set(this, 0);
74
- _Connection_retryTimer.set(this, void 0);
75
- _Connection_pingTimer.set(this, void 0);
76
+ // Every pending call holds a timeout, and nothing limits how many are pending.
77
+ _Connection_timer.set(this, new SharedTimer());
78
+ _Connection_cancelRetry.set(this, void 0);
79
+ _Connection_cancelPing.set(this, void 0);
76
80
  _Connection_lastReceivedAt.set(this, 0);
77
81
  __classPrivateFieldSet(this, _Connection_config, config, "f");
78
82
  __classPrivateFieldSet(this, _Connection_url, config.url(id), "f");
@@ -132,7 +136,7 @@ class Connection {
132
136
  __classPrivateFieldGet(this, _Connection_instances, "m", _Connection_stopTimers).call(this);
133
137
  __classPrivateFieldSet(this, _Connection_generation, __classPrivateFieldGet(this, _Connection_generation, "f") + 1, "f");
134
138
  for (const pending of __classPrivateFieldGet(this, _Connection_pending, "f").values()) {
135
- clearTimeout(pending.timer);
139
+ pending.cancelTimeout();
136
140
  pending.reject(new SocketClosedError());
137
141
  }
138
142
  __classPrivateFieldGet(this, _Connection_pending, "f").clear();
@@ -143,7 +147,7 @@ class Connection {
143
147
  __classPrivateFieldSet(this, _Connection_ws, undefined, "f");
144
148
  }
145
149
  }
146
- _Connection_config = new WeakMap(), _Connection_url = new WeakMap(), _Connection_transforms = new WeakMap(), _Connection_pending = new WeakMap(), _Connection_handlers = new WeakMap(), _Connection_statusHandlers = new WeakMap(), _Connection_resyncHandlers = new WeakMap(), _Connection_subscribes = new WeakMap(), _Connection_acknowledged = new WeakMap(), _Connection_status = new WeakMap(), _Connection_ws = new WeakMap(), _Connection_generation = new WeakMap(), _Connection_nextId = new WeakMap(), _Connection_lastSeq = new WeakMap(), _Connection_attempt = new WeakMap(), _Connection_retryTimer = new WeakMap(), _Connection_pingTimer = new WeakMap(), _Connection_lastReceivedAt = new WeakMap(), _Connection_instances = new WeakSet(), _Connection_send = function _Connection_send(method, input) {
150
+ _Connection_config = new WeakMap(), _Connection_url = new WeakMap(), _Connection_transforms = new WeakMap(), _Connection_pending = new WeakMap(), _Connection_handlers = new WeakMap(), _Connection_statusHandlers = new WeakMap(), _Connection_resyncHandlers = new WeakMap(), _Connection_subscribes = new WeakMap(), _Connection_acknowledged = new WeakMap(), _Connection_status = new WeakMap(), _Connection_ws = new WeakMap(), _Connection_generation = new WeakMap(), _Connection_nextId = new WeakMap(), _Connection_lastSeq = new WeakMap(), _Connection_attempt = new WeakMap(), _Connection_timer = new WeakMap(), _Connection_cancelRetry = new WeakMap(), _Connection_cancelPing = new WeakMap(), _Connection_lastReceivedAt = new WeakMap(), _Connection_instances = new WeakSet(), _Connection_send = function _Connection_send(method, input) {
147
151
  var _a;
148
152
  if (__classPrivateFieldGet(this, _Connection_status, "f") === 'closed') {
149
153
  return Promise.reject(new SocketClosedError());
@@ -163,7 +167,7 @@ _Connection_config = new WeakMap(), _Connection_url = new WeakMap(), _Connection
163
167
  sent: false,
164
168
  resolve,
165
169
  reject,
166
- timer: setTimeout(() => {
170
+ cancelTimeout: __classPrivateFieldGet(this, _Connection_timer, "f").schedule(() => {
167
171
  __classPrivateFieldGet(this, _Connection_pending, "f").delete(id);
168
172
  reject(new SocketTimeoutError(method, __classPrivateFieldGet(this, _Connection_config, "f").timeoutMs));
169
173
  }, __classPrivateFieldGet(this, _Connection_config, "f").timeoutMs),
@@ -183,8 +187,10 @@ _Connection_config = new WeakMap(), _Connection_url = new WeakMap(), _Connection
183
187
  type: 'subscribe',
184
188
  id: `subscribe:${__classPrivateFieldSet(this, _Connection_nextId, (_a = __classPrivateFieldGet(this, _Connection_nextId, "f"), ++_a), "f")}`,
185
189
  names,
186
- ...(__classPrivateFieldGet(this, _Connection_lastSeq, "f") === undefined ? {} : { since: __classPrivateFieldGet(this, _Connection_lastSeq, "f") }),
187
190
  };
191
+ if (__classPrivateFieldGet(this, _Connection_lastSeq, "f") !== undefined) {
192
+ frame.since = __classPrivateFieldGet(this, _Connection_lastSeq, "f");
193
+ }
188
194
  __classPrivateFieldGet(this, _Connection_subscribes, "f").set(frame.id, names);
189
195
  __classPrivateFieldGet(this, _Connection_ws, "f")?.send(JSON.stringify(frame));
190
196
  }, _Connection_subscribed = function _Connection_subscribed(frame) {
@@ -215,7 +221,7 @@ _Connection_config = new WeakMap(), _Connection_url = new WeakMap(), _Connection
215
221
  }
216
222
  }, _Connection_connect = function _Connection_connect() {
217
223
  var _a;
218
- if (__classPrivateFieldGet(this, _Connection_status, "f") !== 'disconnected' || __classPrivateFieldGet(this, _Connection_retryTimer, "f") !== undefined) {
224
+ if (__classPrivateFieldGet(this, _Connection_status, "f") !== 'disconnected' || __classPrivateFieldGet(this, _Connection_cancelRetry, "f") !== undefined) {
219
225
  return;
220
226
  }
221
227
  __classPrivateFieldGet(this, _Connection_instances, "m", _Connection_setStatus).call(this, 'connecting');
@@ -240,7 +246,7 @@ _Connection_config = new WeakMap(), _Connection_url = new WeakMap(), _Connection
240
246
  if (!current()) {
241
247
  return;
242
248
  }
243
- __classPrivateFieldGet(this, _Connection_instances, "m", _Connection_receive).call(this, typeof message.data === 'string' ? message.data : '');
249
+ __classPrivateFieldGet(this, _Connection_instances, "m", _Connection_receive).call(this, isString(message.data) ? message.data : '');
244
250
  });
245
251
  ws.addEventListener('close', (closed) => {
246
252
  if (!current()) {
@@ -288,7 +294,7 @@ _Connection_config = new WeakMap(), _Connection_url = new WeakMap(), _Connection
288
294
  return;
289
295
  }
290
296
  __classPrivateFieldGet(this, _Connection_pending, "f").delete(frame.id);
291
- clearTimeout(pending.timer);
297
+ pending.cancelTimeout();
292
298
  settle(pending);
293
299
  }, _Connection_dispatch = function _Connection_dispatch(name, payload) {
294
300
  for (const handler of __classPrivateFieldGet(this, _Connection_handlers, "f").get(name) ?? []) {
@@ -310,7 +316,7 @@ _Connection_config = new WeakMap(), _Connection_url = new WeakMap(), _Connection
310
316
  continue;
311
317
  }
312
318
  __classPrivateFieldGet(this, _Connection_pending, "f").delete(id);
313
- clearTimeout(pending.timer);
319
+ pending.cancelTimeout();
314
320
  pending.reject(new SocketConnectionLostError(pending.method));
315
321
  }
316
322
  if (code === socketProtocolErrorCode) {
@@ -319,36 +325,36 @@ _Connection_config = new WeakMap(), _Connection_url = new WeakMap(), _Connection
319
325
  }
320
326
  __classPrivateFieldGet(this, _Connection_instances, "m", _Connection_setStatus).call(this, 'disconnected');
321
327
  __classPrivateFieldSet(this, _Connection_attempt, __classPrivateFieldGet(this, _Connection_attempt, "f") + 1, "f");
322
- __classPrivateFieldSet(this, _Connection_retryTimer, setTimeout(() => {
323
- __classPrivateFieldSet(this, _Connection_retryTimer, undefined, "f");
328
+ __classPrivateFieldSet(this, _Connection_cancelRetry, __classPrivateFieldGet(this, _Connection_timer, "f").schedule(() => {
329
+ __classPrivateFieldSet(this, _Connection_cancelRetry, undefined, "f");
324
330
  __classPrivateFieldGet(this, _Connection_instances, "m", _Connection_connect).call(this);
325
331
  }, jitter(exponential(__classPrivateFieldGet(this, _Connection_attempt, "f"), 250, 60000))), "f");
326
332
  }, _Connection_abandon = function _Connection_abandon(error) {
327
333
  reportFailure('durability.socket.protocol_error', {}, error);
328
334
  for (const pending of __classPrivateFieldGet(this, _Connection_pending, "f").values()) {
329
- clearTimeout(pending.timer);
335
+ pending.cancelTimeout();
330
336
  pending.reject(error);
331
337
  }
332
338
  __classPrivateFieldGet(this, _Connection_pending, "f").clear();
333
339
  this.close();
334
340
  }, _Connection_startPing = function _Connection_startPing() {
335
341
  const interval = __classPrivateFieldGet(this, _Connection_config, "f").pingIntervalMs;
336
- __classPrivateFieldSet(this, _Connection_pingTimer, setInterval(() => {
342
+ const ping = () => {
343
+ // Scheduled before the socket is used, so a close that stops the timers
344
+ // also stops the next ping.
345
+ __classPrivateFieldSet(this, _Connection_cancelPing, __classPrivateFieldGet(this, _Connection_timer, "f").schedule(ping, interval), "f");
337
346
  if (Date.now() - __classPrivateFieldGet(this, _Connection_lastReceivedAt, "f") > interval * 2) {
338
347
  __classPrivateFieldGet(this, _Connection_ws, "f")?.close(4000, 'Keep-alive timeout');
339
348
  return;
340
349
  }
341
350
  __classPrivateFieldGet(this, _Connection_ws, "f")?.send(pingText);
342
- }, interval), "f");
351
+ };
352
+ __classPrivateFieldSet(this, _Connection_cancelPing, __classPrivateFieldGet(this, _Connection_timer, "f").schedule(ping, interval), "f");
343
353
  }, _Connection_stopTimers = function _Connection_stopTimers() {
344
- if (__classPrivateFieldGet(this, _Connection_pingTimer, "f") !== undefined) {
345
- clearInterval(__classPrivateFieldGet(this, _Connection_pingTimer, "f"));
346
- __classPrivateFieldSet(this, _Connection_pingTimer, undefined, "f");
347
- }
348
- if (__classPrivateFieldGet(this, _Connection_retryTimer, "f") !== undefined) {
349
- clearTimeout(__classPrivateFieldGet(this, _Connection_retryTimer, "f"));
350
- __classPrivateFieldSet(this, _Connection_retryTimer, undefined, "f");
351
- }
354
+ __classPrivateFieldGet(this, _Connection_cancelPing, "f")?.call(this);
355
+ __classPrivateFieldSet(this, _Connection_cancelPing, undefined, "f");
356
+ __classPrivateFieldGet(this, _Connection_cancelRetry, "f")?.call(this);
357
+ __classPrivateFieldSet(this, _Connection_cancelRetry, undefined, "f");
352
358
  }, _Connection_setStatus = function _Connection_setStatus(status) {
353
359
  if (__classPrivateFieldGet(this, _Connection_status, "f") === status) {
354
360
  return;
@@ -400,11 +406,15 @@ export class DurabilitySocketClient {
400
406
  }
401
407
  connect(id) {
402
408
  const connection = new Connection(__classPrivateFieldGet(this, _DurabilitySocketClient_config, "f"), id, __classPrivateFieldGet(this, _DurabilitySocketClient_transforms, "f"));
409
+ // SAFETY: the get trap returns a method for every string key, so the
410
+ // empty target is never read.
403
411
  const rpc = new Proxy({}, {
404
- get: (_target, method) => typeof method === 'string'
412
+ get: (_target, method) => isString(method)
405
413
  ? (input) => connection.call(method, input)
406
414
  : undefined,
407
415
  });
416
+ // SAFETY: the get trap returns a subscriber for every string key, so the
417
+ // empty target is never read.
408
418
  const on = new Proxy({}, {
409
419
  get: (_target, name) => {
410
420
  if (name === 'status') {
@@ -413,7 +423,7 @@ export class DurabilitySocketClient {
413
423
  if (name === 'resync') {
414
424
  return (handler) => connection.onResync(handler);
415
425
  }
416
- return typeof name === 'string'
426
+ return isString(name)
417
427
  ? (handler) => connection.on(name, handler)
418
428
  : undefined;
419
429
  },
@@ -442,4 +452,4 @@ export const logging = (log = console.log) => async ({ method, input, next }) =>
442
452
  throw error;
443
453
  }
444
454
  };
445
- export { socketShape, } from './protocol.js';
455
+ export { socketMessageMaps, } from './protocol.js';
@@ -1,19 +1,17 @@
1
1
  import type { StandardSchemaV1 } from '@standard-schema/spec';
2
2
  import { type DurabilityMigrationResult } from '../migrations.js';
3
- import { type SocketInboundMap, type SocketOutboundMap, type SocketOutboundPayload, type SocketInboundMetadata, type SocketShape, socketShape } from './protocol.js';
3
+ import { type SocketInboundMap, type SocketInboundSchemas, type SocketOutboundMap, type SocketOutboundPayload, type SocketInboundMetadata, type SocketMessageMaps, type SocketValidatedInbound, socketMessageMaps } 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
- export type DurabilitySocketConfig<Inbound extends SocketInboundMap, Outbound extends SocketOutboundMap, Metadata extends SocketInboundMetadata<Inbound>> = {
6
+ export type DurabilitySocketConfig<Inbound extends SocketInboundMap, Outbound extends SocketOutboundMap, Metadata extends SocketInboundMetadata<Inbound>, Schemas extends Record<keyof Inbound, StandardSchemaV1> = SocketInboundSchemas<Inbound>> = {
7
7
  context: DurabilitySocketContext;
8
- /** Methods clients may call, keyed by the names they become on the client. */
9
- inbound: Inbound;
10
- /** Events the object may push, keyed by the methods they become on this instance. */
11
- outbound: Outbound;
12
8
  /**
13
- * Captures trusted per-connection data from the upgrade request. Stored in
14
- * the WebSocket attachment, so it survives hibernation without re-auth.
9
+ * Methods clients may call, keyed by the names they become on the client.
10
+ * Each validates its input with a Standard Schema before `handle` runs.
15
11
  */
16
- metadata?: (request: Request) => Metadata | Promise<Metadata>;
12
+ inbound: Inbound & SocketValidatedInbound<Inbound, Schemas>;
13
+ /** Events the object may push, keyed by the methods they become on this instance. */
14
+ outbound: Outbound;
17
15
  /** Outbound events kept for replay to reconnecting clients. Defaults to 1000. */
18
16
  retention?: number;
19
17
  /**
@@ -23,7 +21,16 @@ export type DurabilitySocketConfig<Inbound extends SocketInboundMap, Outbound ex
23
21
  * whichever instance `webSocketMessage` delegates to.
24
22
  */
25
23
  channel?: string;
24
+ } & SocketMetadataOption<Metadata>;
25
+ type SocketMetadataConfig<Metadata> = {
26
+ /**
27
+ * Captures trusted per-connection data from the upgrade request. Stored in
28
+ * the WebSocket attachment, so it survives hibernation without re-auth.
29
+ * Required when a handler's `SocketCall<…>` metadata excludes `undefined`.
30
+ */
31
+ metadata: (request: Request) => Metadata | Promise<Metadata>;
26
32
  };
33
+ type SocketMetadataOption<Metadata> = undefined extends Metadata ? Partial<SocketMetadataConfig<Metadata>> : SocketMetadataConfig<Metadata>;
27
34
  /** Thrown to the caller when an inbound payload fails its schema. */
28
35
  export declare class SocketInputError extends Error {
29
36
  readonly issues: readonly StandardSchemaV1.Issue[];
@@ -31,7 +38,7 @@ export declare class SocketInputError extends Error {
31
38
  }
32
39
  declare class DurabilitySocketCore<Inbound extends SocketInboundMap, Outbound extends SocketOutboundMap, Metadata extends SocketInboundMetadata<Inbound>> {
33
40
  #private;
34
- readonly [socketShape]: SocketShape<Inbound, Outbound>;
41
+ readonly [socketMessageMaps]: SocketMessageMaps<Inbound, Outbound>;
35
42
  constructor(config: DurabilitySocketConfig<Inbound, Outbound, Metadata>);
36
43
  /** Applies or reverts the `durability_socket_events` schema. */
37
44
  static migrate(context: Pick<DurableObjectState, 'storage'>, target?: string | null): DurabilityMigrationResult;
@@ -67,10 +74,10 @@ type OutboundMethods<Outbound extends SocketOutboundMap> = {
67
74
  * readonly socket = new DurabilitySocket({
68
75
  * context: this.ctx,
69
76
  * inbound: {
70
- * list: () => this.repo.list(),
77
+ * list: { input: v.undefined(), handle: () => this.repo.list() },
71
78
  * create: {
72
79
  * input: TodoSchema,
73
- * handle: async (todo: Todo) => {
80
+ * handle: async (todo) => {
74
81
  * await this.repo.insert(todo);
75
82
  * this.socket.created(todo);
76
83
  * },
@@ -95,7 +102,7 @@ type OutboundMethods<Outbound extends SocketOutboundMap> = {
95
102
  */
96
103
  export type DurabilitySocket<Inbound extends SocketInboundMap, Outbound extends SocketOutboundMap, Metadata extends SocketInboundMetadata<Inbound> = SocketInboundMetadata<Inbound>> = DurabilitySocketCore<Inbound, Outbound, Metadata> & OutboundMethods<Outbound>;
97
104
  export interface DurabilitySocketConstructor {
98
- new <Inbound extends SocketInboundMap, Outbound extends SocketOutboundMap, Metadata extends SocketInboundMetadata<Inbound> = SocketInboundMetadata<Inbound>>(config: DurabilitySocketConfig<Inbound, Outbound, Metadata>): DurabilitySocket<Inbound, Outbound, Metadata>;
105
+ new <Inbound extends SocketInboundMap, Outbound extends SocketOutboundMap, Metadata extends SocketInboundMetadata<Inbound> = SocketInboundMetadata<Inbound>, Schemas extends Record<keyof Inbound, StandardSchemaV1> = SocketInboundSchemas<Inbound>>(config: DurabilitySocketConfig<Inbound, Outbound, Metadata, Schemas>): DurabilitySocket<Inbound, Outbound, Metadata>;
99
106
  migrate: typeof DurabilitySocketCore.migrate;
100
107
  }
101
108
  export declare const DurabilitySocket: DurabilitySocketConstructor;
@@ -15,6 +15,7 @@ import { reportFailure, serializeError } from '../errors.js';
15
15
  import { durabilitySocketMigrations } from './migrations.js';
16
16
  import { migrateCapability, } from '../migrations.js';
17
17
  import { assertChannel, defaultChannel, engineFor, } from '../scheduler/index.js';
18
+ import { isObject, isString } from '../predicates.js';
18
19
  import { deserialize, serialize } from '../serialization.js';
19
20
  import { parseClientFrame, socketMaxFrameLength, socketProtocolErrorCode, socketProtocolVersion, } from './protocol.js';
20
21
  /** Thrown to the caller when an inbound payload fails its schema. */
@@ -29,6 +30,8 @@ export class SocketInputError extends Error {
29
30
  const frameHandlersByObject = new WeakMap();
30
31
  // A configuration problem rather than a protocol violation, so clients reconnect.
31
32
  const channelMissingCloseCode = 1011;
33
+ // Service Restart: the client reconnects, and the new upgrade captures metadata.
34
+ const metadataMissingCloseCode = 1012;
32
35
  const reservedOutboundNames = new Set(['status', 'resync']);
33
36
  const sendFrame = (ws, frame) => {
34
37
  trace('socket.send', { frame });
@@ -57,22 +60,26 @@ const sendFrame = (ws, frame) => {
57
60
  };
58
61
  const readAttachment = (ws) => {
59
62
  const stored = ws.deserializeAttachment();
60
- if (typeof stored !== 'object' || stored === null) {
63
+ if (!isObject(stored)) {
61
64
  return {
62
65
  metadata: undefined,
66
+ hasMetadata: false,
63
67
  names: [],
64
68
  channel: defaultChannel,
65
69
  };
66
70
  }
67
- const names = Reflect.get(stored, 'names');
71
+ const metadata = 'metadata' in stored ? stored.metadata : undefined;
72
+ const names = 'names' in stored ? stored.names : undefined;
68
73
  // Connections accepted before channels existed carry no channel.
69
- const channel = Reflect.get(stored, 'channel');
74
+ const channel = 'channel' in stored ? stored.channel : undefined;
70
75
  return {
71
- metadata: Reflect.get(stored, 'metadata'),
72
- names: Array.isArray(names)
73
- ? names.filter((name) => typeof name === 'string')
74
- : [],
75
- channel: typeof channel === 'string' ? channel : defaultChannel,
76
+ metadata,
77
+ // Attachments written before `hasMetadata` existed captured metadata if they hold any.
78
+ hasMetadata: 'hasMetadata' in stored
79
+ ? stored.hasMetadata === true
80
+ : metadata !== undefined,
81
+ names: Array.isArray(names) ? names.filter(isString) : [],
82
+ channel: isString(channel) ? channel : defaultChannel,
76
83
  };
77
84
  };
78
85
  class DurabilitySocketCore {
@@ -137,6 +144,7 @@ class DurabilitySocketCore {
137
144
  __classPrivateFieldGet(this, _DurabilitySocketCore_context, "f").acceptWebSocket(server);
138
145
  server.serializeAttachment({
139
146
  metadata,
147
+ hasMetadata: __classPrivateFieldGet(this, _DurabilitySocketCore_metadata, "f") !== undefined,
140
148
  names: [],
141
149
  channel: __classPrivateFieldGet(this, _DurabilitySocketCore_channel, "f"),
142
150
  });
@@ -148,7 +156,9 @@ class DurabilitySocketCore {
148
156
  * channel, which need not be this one.
149
157
  */
150
158
  async webSocketMessage(ws, message) {
151
- const text = typeof message === 'string' ? message : new TextDecoder().decode(message);
159
+ const text = isString(message)
160
+ ? message
161
+ : new TextDecoder().decode(message);
152
162
  const frame = parseClientFrame(text);
153
163
  if (!frame) {
154
164
  trace('socket.close', {
@@ -179,6 +189,16 @@ class DurabilitySocketCore {
179
189
  webSocketClose(_ws) { }
180
190
  }
181
191
  _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) {
192
+ // A connection accepted before this socket captured metadata, such as
193
+ // before a deploy added it, must not reach a handler without it.
194
+ if (__classPrivateFieldGet(this, _DurabilitySocketCore_metadata, "f") !== undefined && !readAttachment(ws).hasMetadata) {
195
+ trace('socket.close', {
196
+ code: metadataMissingCloseCode,
197
+ reason: 'Socket metadata was not captured',
198
+ });
199
+ ws.close(metadataMissingCloseCode, 'Socket metadata was not captured');
200
+ return;
201
+ }
182
202
  if (frame.type === 'subscribe') {
183
203
  __classPrivateFieldGet(this, _DurabilitySocketCore_instances, "m", _DurabilitySocketCore_subscribe).call(this, ws, frame);
184
204
  return;
@@ -199,12 +219,15 @@ _DurabilitySocketCore_context = new WeakMap(), _DurabilitySocketCore_storage = n
199
219
  return;
200
220
  }
201
221
  const call = {
222
+ // SAFETY: #inbound erases each handler's metadata type to never. With
223
+ // config.metadata set, #handle closed every connection whose attachment
224
+ // lacks its result; without it, the handlers' metadata admits undefined.
202
225
  metadata: readAttachment(ws).metadata,
203
226
  };
204
227
  try {
205
- const output = typeof handler === 'function'
206
- ? await handler(frame.input, call)
207
- : await handler.handle((await __classPrivateFieldGet(this, _DurabilitySocketCore_instances, "m", _DurabilitySocketCore_validate).call(this, frame.method, handler.input, frame.input)), call);
228
+ // SAFETY: the input passed handler.input, and SocketValidatedInbound
229
+ // requires each handle to accept its own schema's output.
230
+ const output = await handler.handle((await __classPrivateFieldGet(this, _DurabilitySocketCore_instances, "m", _DurabilitySocketCore_validate).call(this, frame, handler.input)), call);
208
231
  sendFrame(ws, {
209
232
  v: socketProtocolVersion,
210
233
  type: 'result',
@@ -220,10 +243,10 @@ _DurabilitySocketCore_context = new WeakMap(), _DurabilitySocketCore_storage = n
220
243
  error: serializeError(error),
221
244
  });
222
245
  }
223
- }, _DurabilitySocketCore_validate = async function _DurabilitySocketCore_validate(method, schema, input) {
224
- const result = await schema['~standard'].validate(input);
246
+ }, _DurabilitySocketCore_validate = async function _DurabilitySocketCore_validate(frame, schema) {
247
+ const result = await schema['~standard'].validate(frame.input);
225
248
  if (result.issues) {
226
- throw new SocketInputError(method, result.issues);
249
+ throw new SocketInputError(frame.method, result.issues);
227
250
  }
228
251
  return result.value;
229
252
  }, _DurabilitySocketCore_subscribe = function _DurabilitySocketCore_subscribe(ws, frame) {
@@ -320,9 +343,8 @@ _DurabilitySocketCore_context = new WeakMap(), _DurabilitySocketCore_storage = n
320
343
  }
321
344
  };
322
345
  traceMethods(DurabilitySocketCore.prototype, 'DurabilitySocket');
323
- // TypeScript cannot declare class members derived from a generic event map,
324
- // so the constructor is typed separately; the constructor installs and
325
- // reserves every outbound method at runtime.
346
+ // SAFETY: the constructor defines a method for every outbound event name on the
347
+ // instance, members TypeScript cannot declare from a generic event map.
326
348
  export const DurabilitySocket = DurabilitySocketCore;
327
349
  export { durabilitySocketMigrations } from './migrations.js';
328
350
  export { event, } from './protocol.js';
@@ -51,22 +51,28 @@ export type SocketCall<Metadata> = {
51
51
  metadata: Metadata;
52
52
  };
53
53
  /**
54
- * An inbound handler: a bare function that takes no input (or `unknown`
55
- * input it validates itself), or a validated `{ input, handle }` pair.
54
+ * An inbound handler: a Standard Schema that validates the call's input, and
55
+ * `handle`, which receives the validated value.
56
56
  */
57
- export type SocketInboundHandler<Metadata> = ((input: unknown, call: SocketCall<Metadata>) => unknown) | {
57
+ export type SocketInboundHandler<Metadata> = {
58
58
  input: StandardSchemaV1;
59
59
  handle: (input: never, call: SocketCall<Metadata>) => unknown;
60
60
  };
61
61
  export type SocketInboundMap<Metadata = never> = Record<string, SocketInboundHandler<Metadata>>;
62
+ /** An unannotated `call` is `SocketCall<never>`, which constrains nothing. */
62
63
  type HandlerMetadata<Handler> = Handler extends {
63
64
  handle: (input: never, call: SocketCall<infer Metadata>) => unknown;
64
- } ? Metadata : Handler extends (input: never, call: SocketCall<infer Metadata>) => unknown ? Metadata : unknown;
65
- type UnionToIntersection<Union> = (Union extends unknown ? (value: Union) => void : never) extends (value: infer Intersection) => void ? Intersection : never;
66
- /** The metadata every inbound handler in the map can accept. */
67
- export type SocketInboundMetadata<Inbound> = UnionToIntersection<{
68
- [Name in keyof Inbound]: HandlerMetadata<Inbound[Name]>;
69
- }[keyof Inbound]>;
65
+ } ? [Metadata] extends [never] ? unknown : Metadata : unknown;
66
+ type MetadataSinks<Inbound> = {
67
+ [Name in keyof Inbound]: (metadata: HandlerMetadata<Inbound[Name]>) => void;
68
+ }[keyof Inbound];
69
+ /**
70
+ * The metadata every inbound handler in the map can accept: the intersection
71
+ * of each handler's metadata, keeping a union such as `User | undefined` whole.
72
+ */
73
+ export type SocketInboundMetadata<Inbound> = [MetadataSinks<Inbound>] extends [
74
+ (metadata: infer Metadata) => void
75
+ ] ? Metadata : unknown;
70
76
  /** Marks an outbound event and carries its payload type. */
71
77
  export type SocketOutboundEvent<Payload> = {
72
78
  readonly payload?: Payload;
@@ -74,22 +80,36 @@ export type SocketOutboundEvent<Payload> = {
74
80
  export type SocketOutboundMap = Record<string, SocketOutboundEvent<unknown>>;
75
81
  /** Declares an outbound event with the given payload type. */
76
82
  export declare const event: <Payload>() => SocketOutboundEvent<Payload>;
83
+ /** The schema of each inbound handler, by method. */
84
+ export type SocketInboundSchemas<Inbound extends SocketInboundMap> = {
85
+ [Name in keyof Inbound]: Inbound[Name]['input'];
86
+ };
87
+ /**
88
+ * Requires each handler to accept its schema's output. `Schemas` is inferred
89
+ * from the schemas alone, so `handle` parameters need no annotation.
90
+ */
91
+ export type SocketValidatedInbound<Inbound extends SocketInboundMap, Schemas extends Record<keyof Inbound, StandardSchemaV1>> = {
92
+ [Name in keyof Schemas]: {
93
+ input: Schemas[Name];
94
+ handle: (input: StandardSchemaV1.InferOutput<Schemas[Name]>, call: SocketCall<never>) => ReturnType<Inbound[Name & keyof Inbound]['handle']>;
95
+ };
96
+ };
77
97
  export type SocketInboundInput<Handler> = Handler extends {
78
98
  input: infer Schema extends StandardSchemaV1;
79
- } ? StandardSchemaV1.InferInput<Schema> : Handler extends (...args: infer Args) => unknown ? Args extends [] ? void : Args[0] : never;
99
+ } ? StandardSchemaV1.InferInput<Schema> : never;
80
100
  export type SocketInboundOutput<Handler> = Handler extends {
81
101
  handle: (...args: never[]) => infer Result;
82
- } ? Awaited<Result> : Handler extends (...args: never[]) => infer Result ? Awaited<Result> : never;
102
+ } ? Awaited<Result> : never;
83
103
  export type SocketOutboundPayload<Event> = Event extends SocketOutboundEvent<infer Payload> ? Payload : never;
84
- export declare const socketShape: unique symbol;
104
+ export declare const socketMessageMaps: unique symbol;
85
105
  /** Phantom type a server socket carries so clients can derive its surface. */
86
- export type SocketShape<Inbound extends SocketInboundMap, Outbound extends SocketOutboundMap> = {
106
+ export type SocketMessageMaps<Inbound extends SocketInboundMap, Outbound extends SocketOutboundMap> = {
87
107
  inbound: Inbound;
88
108
  outbound: Outbound;
89
109
  };
90
- export type AnySocketShape = {
91
- readonly [socketShape]: SocketShape<SocketInboundMap, SocketOutboundMap>;
110
+ export type AnyDurabilitySocket = {
111
+ readonly [socketMessageMaps]: SocketMessageMaps<SocketInboundMap, SocketOutboundMap>;
92
112
  };
93
- export type InboundOf<Socket extends AnySocketShape> = Socket[typeof socketShape]['inbound'];
94
- export type OutboundOf<Socket extends AnySocketShape> = Socket[typeof socketShape]['outbound'];
113
+ export type InboundOf<Socket extends AnyDurabilitySocket> = Socket[typeof socketMessageMaps]['inbound'];
114
+ export type OutboundOf<Socket extends AnyDurabilitySocket> = Socket[typeof socketMessageMaps]['outbound'];
95
115
  export {};
@@ -1,11 +1,11 @@
1
+ import { isJsonObject, isString } from '../predicates.js';
1
2
  export const socketProtocolVersion = 1;
2
3
  /** Largest text frame either side accepts, in UTF-16 code units. */
3
4
  export const socketMaxFrameLength = 1024 * 1024;
4
5
  /** Close code sent when the peer violates the wire protocol; clients must not retry. */
5
6
  export const socketProtocolErrorCode = 4002;
6
- const isRecord = (value) => typeof value === 'object' && value !== null;
7
- const isStringArray = (value) => Array.isArray(value) && value.every((item) => typeof item === 'string');
8
- const isSerializedError = (value) => isRecord(value) &&
7
+ const isStringArray = (value) => Array.isArray(value) && value.every(isString);
8
+ const isSerializedError = (value) => isJsonObject(value) &&
9
9
  typeof value['name'] === 'string' &&
10
10
  typeof value['message'] === 'string';
11
11
  const parseFrame = (text) => {
@@ -19,53 +19,47 @@ const parseFrame = (text) => {
19
19
  catch {
20
20
  return undefined;
21
21
  }
22
- if (!isRecord(parsed) || parsed['v'] !== socketProtocolVersion) {
22
+ if (!isJsonObject(parsed) || parsed['v'] !== socketProtocolVersion) {
23
23
  return undefined;
24
24
  }
25
25
  return parsed;
26
26
  };
27
- export const parseClientFrame = (text) => {
28
- const frame = parseFrame(text);
29
- if (!frame || typeof frame['id'] !== 'string') {
30
- return undefined;
27
+ // `parseFrame` has already checked the protocol version.
28
+ const isClientFrame = (frame) => {
29
+ if (typeof frame['id'] !== 'string') {
30
+ return false;
31
31
  }
32
- if (frame['type'] === 'call' && typeof frame['method'] === 'string') {
33
- return frame;
32
+ if (frame['type'] === 'call') {
33
+ return typeof frame['method'] === 'string';
34
34
  }
35
- if (frame['type'] === 'subscribe' &&
35
+ return (frame['type'] === 'subscribe' &&
36
36
  isStringArray(frame['names']) &&
37
- (frame['since'] === undefined || Number.isSafeInteger(frame['since']))) {
38
- return frame;
39
- }
40
- return undefined;
37
+ (frame['since'] === undefined || Number.isSafeInteger(frame['since'])));
41
38
  };
42
- export const parseServerFrame = (text) => {
43
- const frame = parseFrame(text);
44
- if (!frame) {
45
- return undefined;
46
- }
39
+ const isServerFrame = (frame) => {
47
40
  if (frame['type'] === 'event') {
48
- return Number.isSafeInteger(frame['seq']) &&
49
- typeof frame['name'] === 'string'
50
- ? frame
51
- : undefined;
41
+ return (Number.isSafeInteger(frame['seq']) && typeof frame['name'] === 'string');
52
42
  }
53
43
  if (typeof frame['id'] !== 'string') {
54
- return undefined;
55
- }
56
- if (frame['type'] === 'result') {
57
- return frame;
44
+ return false;
58
45
  }
59
- if (frame['type'] === 'error' && isSerializedError(frame['error'])) {
60
- return frame;
46
+ if (frame['type'] === 'error') {
47
+ return isSerializedError(frame['error']);
61
48
  }
62
- if (frame['type'] === 'subscribed' &&
63
- Number.isSafeInteger(frame['seq']) &&
64
- typeof frame['replayed'] === 'boolean') {
65
- return frame;
49
+ if (frame['type'] === 'subscribed') {
50
+ return (Number.isSafeInteger(frame['seq']) &&
51
+ typeof frame['replayed'] === 'boolean');
66
52
  }
67
- return undefined;
53
+ return frame['type'] === 'result';
54
+ };
55
+ export const parseClientFrame = (text) => {
56
+ const frame = parseFrame(text);
57
+ return frame && isClientFrame(frame) ? frame : undefined;
58
+ };
59
+ export const parseServerFrame = (text) => {
60
+ const frame = parseFrame(text);
61
+ return frame && isServerFrame(frame) ? frame : undefined;
68
62
  };
69
63
  /** Declares an outbound event with the given payload type. */
70
64
  export const event = () => ({});
71
- export const socketShape = Symbol('durability.socket');
65
+ export const socketMessageMaps = Symbol('durability.socket');