@replit/river 0.207.3 → 0.208.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 (52) hide show
  1. package/dist/{adapter-f2b6e211.d.ts → adapter-ChksXKVN.d.ts} +2 -2
  2. package/dist/adapter-Cuc4JtfV.d.cts +46 -0
  3. package/dist/{chunk-BO7MFCO6.js → chunk-2JNVDUMN.js} +55 -97
  4. package/dist/chunk-2JNVDUMN.js.map +1 -0
  5. package/dist/{chunk-B7REV3ZV.js → chunk-DKW3GC3M.js} +2 -2
  6. package/dist/{chunk-QGPYCXV4.js → chunk-ETZAHFGQ.js} +80 -61
  7. package/dist/chunk-ETZAHFGQ.js.map +1 -0
  8. package/dist/codec/index.d.cts +3 -3
  9. package/dist/codec/index.d.ts +3 -3
  10. package/dist/codec/index.js +2 -2
  11. package/dist/connection-BF4zg6Qv.d.cts +35 -0
  12. package/dist/{connection-06d72f2e.d.ts → connection-Donr3JRB.d.ts} +4 -4
  13. package/dist/index-C9tpZjBN.d.cts +37 -0
  14. package/dist/{index-02554794.d.ts → index-D8IOd3LG.d.ts} +2 -2
  15. package/dist/logging/index.d.cts +2 -2
  16. package/dist/logging/index.d.ts +2 -2
  17. package/dist/{message-01c3e85a.d.ts → message-Di94OL80.d.cts} +1 -1
  18. package/dist/message-Di94OL80.d.ts +108 -0
  19. package/dist/router/index.cjs +62 -43
  20. package/dist/router/index.cjs.map +1 -1
  21. package/dist/router/index.d.cts +27 -8
  22. package/dist/router/index.d.ts +27 -8
  23. package/dist/router/index.js +1 -1
  24. package/dist/testUtil/index.cjs +56 -105
  25. package/dist/testUtil/index.cjs.map +1 -1
  26. package/dist/testUtil/index.d.cts +5 -5
  27. package/dist/testUtil/index.d.ts +5 -5
  28. package/dist/testUtil/index.js +7 -14
  29. package/dist/testUtil/index.js.map +1 -1
  30. package/dist/transport/impls/ws/client.cjs +51 -80
  31. package/dist/transport/impls/ws/client.cjs.map +1 -1
  32. package/dist/transport/impls/ws/client.d.cts +6 -6
  33. package/dist/transport/impls/ws/client.d.ts +6 -6
  34. package/dist/transport/impls/ws/client.js +3 -3
  35. package/dist/transport/impls/ws/server.cjs +52 -85
  36. package/dist/transport/impls/ws/server.cjs.map +1 -1
  37. package/dist/transport/impls/ws/server.d.cts +6 -6
  38. package/dist/transport/impls/ws/server.d.ts +6 -6
  39. package/dist/transport/impls/ws/server.js +3 -3
  40. package/dist/transport/index.cjs +52 -94
  41. package/dist/transport/index.cjs.map +1 -1
  42. package/dist/transport/index.d.cts +6 -6
  43. package/dist/transport/index.d.ts +6 -6
  44. package/dist/transport/index.js +3 -3
  45. package/dist/transport-CCaWx1Rb.d.cts +1566 -0
  46. package/dist/{services-87887bc5.d.ts → transport-CZb3vdB4.d.ts} +344 -347
  47. package/dist/{wslike-e0b32dd5.d.ts → wslike-Dng9H1C7.d.cts} +1 -1
  48. package/dist/wslike-Dng9H1C7.d.ts +40 -0
  49. package/package.json +3 -3
  50. package/dist/chunk-BO7MFCO6.js.map +0 -1
  51. package/dist/chunk-QGPYCXV4.js.map +0 -1
  52. /package/dist/{chunk-B7REV3ZV.js.map → chunk-DKW3GC3M.js.map} +0 -0
@@ -1,47 +1,44 @@
1
1
  import * as _sinclair_typebox from '@sinclair/typebox';
2
- import { Static, TSchema, TObject, TString, TUnion, TLiteral, TNever } from '@sinclair/typebox';
2
+ import { TSchema, Static, TNever, TObject, TLiteral, TString, TUnion } from '@sinclair/typebox';
3
3
  import { Tracer, Span } from '@opentelemetry/api';
4
- import { b as TelemetryInfo, T as TransportClientId, P as ProtocolVersion, O as OpaqueTransportMessage, a as PartialTransportMessage, c as TransportMessage, H as HandshakeErrorResponseCodes, d as HandshakeErrorCustomHandlerFatalResponseCodes } from './message-01c3e85a.js';
5
- import { M as MessageMetadata, L as Logger, T as Tags, a as LogFn, b as LoggingLevel } from './index-02554794.js';
6
- import { C as Codec, a as CodecMessageAdapter, S as SendResult, b as SendBufferResult } from './adapter-f2b6e211.js';
4
+ import { b as TelemetryInfo, T as TransportClientId, P as ProtocolVersion, O as OpaqueTransportMessage, a as PartialTransportMessage, c as TransportMessage, H as HandshakeErrorCustomHandlerFatalResponseCodes, d as HandshakeErrorResponseCodes } from './message-Di94OL80.js';
5
+ import { M as MessageMetadata, L as Logger, T as Tags, a as LogFn, b as LoggingLevel } from './index-D8IOd3LG.js';
6
+ import { C as Codec, a as CodecMessageAdapter, S as SendResult, b as SendBufferResult } from './adapter-ChksXKVN.js';
7
7
 
8
8
  /**
9
9
  * A connection is the actual raw underlying transport connection.
10
- * Its responsible for dispatching to/from the actual connection itself
10
+ * It's responsible for dispatching to/from the actual connection itself
11
11
  * This should be instantiated as soon as the client/server has a connection
12
- * Its tied to the lifecycle of the underlying transport connection (i.e. if the WS drops, this connection should be deleted)
12
+ * It's tied to the lifecycle of the underlying transport connection (i.e. if the WS drops, this connection should be deleted)
13
13
  */
14
14
  declare abstract class Connection {
15
15
  id: string;
16
16
  telemetry?: TelemetryInfo;
17
17
  constructor();
18
18
  get loggingMetadata(): MessageMetadata;
19
- private _dataListeners;
20
- private _closeListeners;
21
- private _errorListeners;
22
- get dataListeners(): ((msg: Uint8Array) => void)[];
23
- get closeListeners(): (() => void)[];
24
- get errorListeners(): ((err: Error) => void)[];
19
+ dataListener?: (msg: Uint8Array) => void;
20
+ closeListener?: () => void;
21
+ errorListener?: (err: Error) => void;
25
22
  onData(msg: Uint8Array): void;
26
23
  onError(err: Error): void;
27
24
  onClose(): void;
28
25
  /**
29
- * Handle adding a callback for when a message is received.
30
- * @param msg The message that was received.
26
+ * Set the callback for when a message is received.
27
+ * @param cb The message handler callback.
31
28
  */
32
- addDataListener(cb: (msg: Uint8Array) => void): void;
33
- removeDataListener(cb: (msg: Uint8Array) => void): void;
29
+ setDataListener(cb: (msg: Uint8Array) => void): void;
30
+ removeDataListener(): void;
34
31
  /**
35
- * Handle adding a callback for when the connection is closed.
36
- * This should also be called if an error happens and after notifying all the error listeners.
32
+ * Set the callback for when the connection is closed.
33
+ * This should also be called if an error happens and after notifying the error listener.
37
34
  * @param cb The callback to call when the connection is closed.
38
35
  */
39
- addCloseListener(cb: () => void): void;
40
- removeCloseListener(cb: () => void): void;
36
+ setCloseListener(cb: () => void): void;
37
+ removeCloseListener(): void;
41
38
  /**
42
- * Handle adding a callback for when an error is received.
43
- * This should only be used for this.logging errors, all cleanup
44
- * should be delegated to addCloseListener.
39
+ * Set the callback for when an error is received.
40
+ * This should only be used for logging errors, all cleanup
41
+ * should be delegated to setCloseListener.
45
42
  *
46
43
  * The implementer should take care such that the implemented
47
44
  * connection will call both the close and error callbacks
@@ -49,8 +46,8 @@ declare abstract class Connection {
49
46
  *
50
47
  * @param cb The callback to call when an error is received.
51
48
  */
52
- addErrorListener(cb: (err: Error) => void): void;
53
- removeErrorListener(cb: (err: Error) => void): void;
49
+ setErrorListener(cb: (err: Error) => void): void;
50
+ removeErrorListener(): void;
54
51
  /**
55
52
  * Sends a message over the connection.
56
53
  * @param msg The message to send.
@@ -191,6 +188,100 @@ declare abstract class IdentifiedSessionWithGracePeriod extends IdentifiedSessio
191
188
  _handleClose(): void;
192
189
  }
193
190
 
191
+ type ConstructHandshake<T extends TSchema> = () => Static<T> | Promise<Static<T>>;
192
+ type ValidateHandshake<T extends TSchema> = (metadata: Static<T>, previousParsedMetadata?: ParsedMetadata) => Static<typeof HandshakeErrorCustomHandlerFatalResponseCodes> | ParsedMetadata | Promise<Static<typeof HandshakeErrorCustomHandlerFatalResponseCodes> | ParsedMetadata>;
193
+ interface ClientHandshakeOptions<MetadataSchema extends TSchema = TSchema> {
194
+ /**
195
+ * Schema for the metadata that the client sends to the server
196
+ * during the handshake.
197
+ */
198
+ schema: MetadataSchema;
199
+ /**
200
+ * Gets the {@link HandshakeRequestMetadata} to send to the server.
201
+ */
202
+ construct: ConstructHandshake<MetadataSchema>;
203
+ }
204
+ interface ServerHandshakeOptions<MetadataSchema extends TSchema = TSchema> {
205
+ /**
206
+ * Schema for the metadata that the server receives from the client
207
+ * during the handshake.
208
+ */
209
+ schema: MetadataSchema;
210
+ /**
211
+ * Parses the {@link HandshakeRequestMetadata} sent by the client, transforming
212
+ * it into {@link ParsedHandshakeMetadata}.
213
+ *
214
+ * May return `false` if the client should be rejected.
215
+ *
216
+ * @param metadata - The metadata sent by the client.
217
+ * @param session - The session that the client would be associated with.
218
+ * @param isReconnect - Whether the client is reconnecting to the session,
219
+ * or if this is a new session.
220
+ */
221
+ validate: ValidateHandshake<MetadataSchema>;
222
+ }
223
+ declare function createClientHandshakeOptions<MetadataSchema extends TSchema = TSchema>(schema: MetadataSchema, construct: ConstructHandshake<MetadataSchema>): ClientHandshakeOptions;
224
+ declare function createServerHandshakeOptions<MetadataSchema extends TSchema = TSchema>(schema: MetadataSchema, validate: ValidateHandshake<MetadataSchema>): ServerHandshakeOptions;
225
+
226
+ /**
227
+ * Options to control the backoff and retry behavior of the client transport's connection behaviour.
228
+ *
229
+ * River implements exponential backoff with jitter to prevent flooding the server
230
+ * when there's an issue with connection establishment.
231
+ *
232
+ * The backoff is calculated via the following:
233
+ * backOff = min(jitter + {@link baseIntervalMs} * 2 ^ budget_consumed, {@link maxBackoffMs})
234
+ *
235
+ * We use a leaky bucket rate limit with a budget of {@link attemptBudgetCapacity} reconnection attempts.
236
+ * Budget only starts to restore after a successful handshake at a rate of one budget per {@link budgetRestoreIntervalMs}.
237
+ */
238
+ interface ConnectionRetryOptions {
239
+ /**
240
+ * The base interval to wait before retrying a connection.
241
+ */
242
+ baseIntervalMs: number;
243
+ /**
244
+ * The maximum random jitter to add to the total backoff time.
245
+ */
246
+ maxJitterMs: number;
247
+ /**
248
+ * The maximum amount of time to wait before retrying a connection.
249
+ * This does not include the jitter.
250
+ */
251
+ maxBackoffMs: number;
252
+ /**
253
+ * The max number of times to attempt a connection before a successful handshake.
254
+ * This persists across connections but starts restoring budget after a successful handshake.
255
+ * The restoration interval depends on {@link budgetRestoreIntervalMs}
256
+ */
257
+ attemptBudgetCapacity: number;
258
+ /**
259
+ * After a successful connection attempt, how long to wait before we restore a single budget.
260
+ */
261
+ budgetRestoreIntervalMs: number;
262
+ }
263
+ declare class LeakyBucketRateLimit {
264
+ private budgetConsumed;
265
+ private intervalHandle?;
266
+ private readonly options;
267
+ constructor(options: ConnectionRetryOptions);
268
+ getBackoffMs(): number;
269
+ get totalBudgetRestoreTime(): number;
270
+ consumeBudget(): void;
271
+ getBudgetConsumed(): number;
272
+ hasBudget(): boolean;
273
+ startRestoringBudget(): void;
274
+ private stopLeak;
275
+ close(): void;
276
+ }
277
+
278
+ type TransportOptions = SessionOptions;
279
+ type ProvidedTransportOptions = Partial<TransportOptions>;
280
+ type ClientTransportOptions = TransportOptions & ConnectionRetryOptions;
281
+ type ProvidedClientTransportOptions = Partial<ClientTransportOptions>;
282
+ type ServerTransportOptions = TransportOptions;
283
+ type ProvidedServerTransportOptions = Partial<ServerTransportOptions>;
284
+
194
285
  interface SessionConnectingListeners extends IdentifiedSessionWithGracePeriodListeners {
195
286
  onConnectionEstablished: (conn: Connection) => void;
196
287
  onConnectionFailed: (err: unknown) => void;
@@ -211,12 +302,6 @@ declare class SessionConnecting<ConnType extends Connection> extends IdentifiedS
211
302
  _handleClose(): void;
212
303
  }
213
304
 
214
- declare class SessionNoConnection extends IdentifiedSessionWithGracePeriod {
215
- readonly state: SessionState.NoConnection;
216
- _handleClose(): void;
217
- _handleStateExit(): void;
218
- }
219
-
220
305
  interface SessionHandshakingListeners extends IdentifiedSessionWithGracePeriodListeners {
221
306
  onConnectionErrored: (err: unknown) => void;
222
307
  onConnectionClosed: () => void;
@@ -261,322 +346,77 @@ declare class SessionHandshaking<ConnType extends Connection> extends Identified
261
346
  interface SessionConnectedListeners {
262
347
  onConnectionErrored: (err: unknown) => void;
263
348
  onConnectionClosed: () => void;
264
- onMessage: (msg: OpaqueTransportMessage) => void;
265
- onMessageSendFailure: (msg: PartialTransportMessage, reason: string) => void;
266
- onInvalidMessage: (reason: string) => void;
267
- }
268
- interface SessionConnectedProps<ConnType extends Connection> extends IdentifiedSessionProps {
269
- conn: ConnType;
270
- listeners: SessionConnectedListeners;
271
- }
272
- declare class SessionConnected<ConnType extends Connection> extends IdentifiedSession {
273
- readonly state: SessionState.Connected;
274
- conn: ConnType;
275
- listeners: SessionConnectedListeners;
276
- private heartbeatHandle?;
277
- private heartbeatMissTimeout?;
278
- private isActivelyHeartbeating;
279
- updateBookkeeping(ack: number, seq: number): void;
280
- private assertSendOrdering;
281
- send(msg: PartialTransportMessage): SendResult;
282
- constructor(props: SessionConnectedProps<ConnType>);
283
- sendBufferedMessages(): SendBufferResult;
284
- get loggingMetadata(): {
285
- protocolVersion?: ProtocolVersion | undefined;
286
- clientId?: string | undefined;
287
- connectedTo?: string | undefined;
288
- sessionId?: string | undefined;
289
- connId?: string | undefined;
290
- transportMessage?: Partial<OpaqueTransportMessage> | undefined;
291
- validationErrors?: {
292
- path: string;
293
- message: string;
294
- }[] | undefined;
295
- tags?: Tags[] | undefined;
296
- telemetry?: {
297
- traceId: string;
298
- spanId: string;
299
- } | undefined;
300
- extras?: Record<string, unknown> | undefined;
301
- };
302
- startMissingHeartbeatTimeout(): void;
303
- startActiveHeartbeat(): void;
304
- private sendHeartbeat;
305
- onMessageData: (msg: Uint8Array) => void;
306
- _handleStateExit(): void;
307
- _handleClose(): void;
308
- }
309
-
310
- interface SessionBackingOffListeners extends IdentifiedSessionWithGracePeriodListeners {
311
- onBackoffFinished: () => void;
312
- }
313
- interface SessionBackingOffProps extends IdentifiedSessionWithGracePeriodProps {
314
- backoffMs: number;
315
- listeners: SessionBackingOffListeners;
316
- }
317
- declare class SessionBackingOff extends IdentifiedSessionWithGracePeriod {
318
- readonly state: SessionState.BackingOff;
319
- listeners: SessionBackingOffListeners;
320
- backoffTimeout?: ReturnType<typeof setTimeout>;
321
- constructor(props: SessionBackingOffProps);
322
- _handleClose(): void;
323
- _handleStateExit(): void;
324
- }
325
-
326
- type ClientSession<ConnType extends Connection> = SessionNoConnection | SessionBackingOff | SessionConnecting<ConnType> | SessionHandshaking<ConnType> | SessionConnected<ConnType>;
327
- type ServerSession<ConnType extends Connection> = SessionConnected<ConnType> | SessionNoConnection;
328
- type Session<ConnType extends Connection> = ClientSession<ConnType> | ServerSession<ConnType>;
329
-
330
- declare const ProtocolError: {
331
- readonly RetriesExceeded: "conn_retry_exceeded";
332
- readonly HandshakeFailed: "handshake_failed";
333
- readonly MessageOrderingViolated: "message_ordering_violated";
334
- readonly InvalidMessage: "invalid_message";
335
- readonly MessageSendFailure: "message_send_failure";
336
- };
337
- type ProtocolErrorType = (typeof ProtocolError)[keyof typeof ProtocolError];
338
- interface EventMap {
339
- message: OpaqueTransportMessage;
340
- sessionStatus: {
341
- status: 'created' | 'closing';
342
- session: Session<Connection>;
343
- } | {
344
- status: 'closed';
345
- session: Pick<Session<Connection>, 'id' | 'to'>;
346
- };
347
- sessionTransition: {
348
- state: SessionState.Connected;
349
- id: SessionId;
350
- } | {
351
- state: SessionState.Handshaking;
352
- id: SessionId;
353
- } | {
354
- state: SessionState.Connecting;
355
- id: SessionId;
356
- } | {
357
- state: SessionState.BackingOff;
358
- id: SessionId;
359
- } | {
360
- state: SessionState.NoConnection;
361
- id: SessionId;
362
- };
363
- protocolError: {
364
- type: (typeof ProtocolError)['HandshakeFailed'];
365
- code: Static<typeof HandshakeErrorResponseCodes>;
366
- message: string;
367
- } | {
368
- type: Omit<ProtocolErrorType, (typeof ProtocolError)['HandshakeFailed']>;
369
- message: string;
370
- };
371
- transportStatus: {
372
- status: TransportStatus;
373
- };
374
- }
375
- type EventTypes = keyof EventMap;
376
- type EventHandler<K extends EventTypes> = (event: EventMap[K]) => unknown;
377
- declare class EventDispatcher<T extends EventTypes> {
378
- private eventListeners;
379
- removeAllListeners(): void;
380
- numberOfListeners<K extends T>(eventType: K): number;
381
- addEventListener<K extends T>(eventType: K, handler: EventHandler<K>): void;
382
- removeEventListener<K extends T>(eventType: K, handler: EventHandler<K>): void;
383
- dispatchEvent<K extends T>(eventType: K, event: EventMap[K]): void;
384
- }
385
-
386
- /**
387
- * Options to control the backoff and retry behavior of the client transport's connection behaviour.
388
- *
389
- * River implements exponential backoff with jitter to prevent flooding the server
390
- * when there's an issue with connection establishment.
391
- *
392
- * The backoff is calculated via the following:
393
- * backOff = min(jitter + {@link baseIntervalMs} * 2 ^ budget_consumed, {@link maxBackoffMs})
394
- *
395
- * We use a leaky bucket rate limit with a budget of {@link attemptBudgetCapacity} reconnection attempts.
396
- * Budget only starts to restore after a successful handshake at a rate of one budget per {@link budgetRestoreIntervalMs}.
397
- */
398
- interface ConnectionRetryOptions {
399
- /**
400
- * The base interval to wait before retrying a connection.
401
- */
402
- baseIntervalMs: number;
403
- /**
404
- * The maximum random jitter to add to the total backoff time.
405
- */
406
- maxJitterMs: number;
407
- /**
408
- * The maximum amount of time to wait before retrying a connection.
409
- * This does not include the jitter.
410
- */
411
- maxBackoffMs: number;
412
- /**
413
- * The max number of times to attempt a connection before a successful handshake.
414
- * This persists across connections but starts restoring budget after a successful handshake.
415
- * The restoration interval depends on {@link budgetRestoreIntervalMs}
416
- */
417
- attemptBudgetCapacity: number;
418
- /**
419
- * After a successful connection attempt, how long to wait before we restore a single budget.
420
- */
421
- budgetRestoreIntervalMs: number;
422
- }
423
- declare class LeakyBucketRateLimit {
424
- private budgetConsumed;
425
- private intervalHandle?;
426
- private readonly options;
427
- constructor(options: ConnectionRetryOptions);
428
- getBackoffMs(): number;
429
- get totalBudgetRestoreTime(): number;
430
- consumeBudget(): void;
431
- getBudgetConsumed(): number;
432
- hasBudget(): boolean;
433
- startRestoringBudget(): void;
434
- private stopLeak;
435
- close(): void;
436
- }
437
-
438
- type TransportOptions = SessionOptions;
439
- type ProvidedTransportOptions = Partial<TransportOptions>;
440
- type ClientTransportOptions = TransportOptions & ConnectionRetryOptions;
441
- type ProvidedClientTransportOptions = Partial<ClientTransportOptions>;
442
- type ServerTransportOptions = TransportOptions;
443
- type ProvidedServerTransportOptions = Partial<ServerTransportOptions>;
444
-
445
- /**
446
- * Represents the possible states of a transport.
447
- * @property {'open'} open - The transport is open and operational (note that this doesn't mean it is actively connected)
448
- * @property {'closed'} closed - The transport is permanently closed and cannot be reopened.
449
- */
450
- type TransportStatus = 'open' | 'closed';
451
- interface DeleteSessionOptions {
452
- unhealthy: boolean;
453
- }
454
- type SessionBoundSendFn = (msg: PartialTransportMessage) => string;
455
- /**
456
- * Transports manage the lifecycle (creation/deletion) of sessions
457
- *
458
- * ```plaintext
459
- * ▲
460
- * incoming │
461
- * messages │
462
- * ▼
463
- * ┌─────────────┐ 1:N ┌───────────┐ 1:1* ┌────────────┐
464
- * │ Transport │ ◄─────► │ Session │ ◄─────► │ Connection │
465
- * └─────────────┘ └───────────┘ └────────────┘
466
- * ▲ * (may or may not be initialized yet)
467
- * │
468
- * ▼
469
- * ┌───────────┐
470
- * │ Message │
471
- * │ Listeners │
472
- * └───────────┘
473
- * ```
474
- * @abstract
475
- */
476
- declare abstract class Transport<ConnType extends Connection> {
477
- /**
478
- * The status of the transport.
479
- */
480
- private status;
481
- /**
482
- * The client ID of this transport.
483
- */
484
- clientId: TransportClientId;
485
- /**
486
- * The event dispatcher for handling events of type EventTypes.
487
- */
488
- eventDispatcher: EventDispatcher<EventTypes>;
489
- /**
490
- * The options for this transport.
491
- */
492
- protected options: TransportOptions;
493
- log?: Logger;
494
- tracer: Tracer;
495
- sessions: Map<TransportClientId, Session<ConnType>>;
496
- /**
497
- * Creates a new Transport instance.
498
- * @param codec The codec used to encode and decode messages.
499
- * @param clientId The client ID of this transport.
500
- */
501
- constructor(clientId: TransportClientId, providedOptions?: ProvidedTransportOptions);
502
- bindLogger(fn: LogFn | Logger, level?: LoggingLevel): void;
503
- /**
504
- * Called when a message is received by this transport.
505
- * You generally shouldn't need to override this in downstream transport implementations.
506
- * @param message The received message.
507
- */
508
- protected handleMsg(message: OpaqueTransportMessage): void;
509
- /**
510
- * Adds a listener to this transport.
511
- * @param the type of event to listen for
512
- * @param handler The message handler to add.
513
- */
514
- addEventListener<K extends EventTypes, T extends EventHandler<K>>(type: K, handler: T): void;
515
- /**
516
- * Removes a listener from this transport.
517
- * @param the type of event to un-listen on
518
- * @param handler The message handler to remove.
519
- */
520
- removeEventListener<K extends EventTypes, T extends EventHandler<K>>(type: K, handler: T): void;
521
- protected protocolError(message: EventMap['protocolError']): void;
522
- /**
523
- * Default close implementation for transports. You should override this in the downstream
524
- * implementation if you need to do any additional cleanup and call super.close() at the end.
525
- * Closes the transport. Any messages sent while the transport is closed will be silently discarded.
526
- */
527
- close(): void;
528
- getStatus(): TransportStatus;
529
- protected createSession<S extends Session<ConnType>>(session: S): void;
530
- protected updateSession<S extends Session<ConnType>>(session: S): void;
531
- protected deleteSession(session: Session<ConnType>, options?: DeleteSessionOptions): void;
532
- protected onSessionGracePeriodElapsed(session: Session<ConnType>): void;
533
- protected onConnectingFailed(session: SessionConnecting<ConnType>): SessionNoConnection;
534
- protected onConnClosed(session: SessionHandshaking<ConnType> | SessionConnected<ConnType>): SessionNoConnection;
535
- /**
536
- * Gets a send closure scoped to a specific session. Sending using the returned
537
- * closure after the session has transitioned to a different state will be a noop.
538
- *
539
- * Session objects themselves can become stale as they transition between
540
- * states. As stale sessions cannot be used again (and will throw), holding
541
- * onto a session object is not recommended.
542
- */
543
- getSessionBoundSendFn(to: TransportClientId, sessionId: SessionId): SessionBoundSendFn;
349
+ onMessage: (msg: OpaqueTransportMessage) => void;
350
+ onMessageSendFailure: (msg: PartialTransportMessage, reason: string) => void;
351
+ onInvalidMessage: (reason: string) => void;
352
+ }
353
+ interface SessionConnectedProps<ConnType extends Connection> extends IdentifiedSessionProps {
354
+ conn: ConnType;
355
+ listeners: SessionConnectedListeners;
356
+ }
357
+ declare class SessionConnected<ConnType extends Connection> extends IdentifiedSession {
358
+ readonly state: SessionState.Connected;
359
+ conn: ConnType;
360
+ listeners: SessionConnectedListeners;
361
+ private heartbeatHandle?;
362
+ private heartbeatMissTimeout?;
363
+ private isActivelyHeartbeating;
364
+ updateBookkeeping(ack: number, seq: number): void;
365
+ private assertSendOrdering;
366
+ send(msg: PartialTransportMessage): SendResult;
367
+ constructor(props: SessionConnectedProps<ConnType>);
368
+ sendBufferedMessages(): SendBufferResult;
369
+ get loggingMetadata(): {
370
+ protocolVersion?: ProtocolVersion | undefined;
371
+ clientId?: string | undefined;
372
+ connectedTo?: string | undefined;
373
+ sessionId?: string | undefined;
374
+ connId?: string | undefined;
375
+ transportMessage?: Partial<OpaqueTransportMessage> | undefined;
376
+ validationErrors?: {
377
+ path: string;
378
+ message: string;
379
+ }[] | undefined;
380
+ tags?: Tags[] | undefined;
381
+ telemetry?: {
382
+ traceId: string;
383
+ spanId: string;
384
+ } | undefined;
385
+ extras?: Record<string, unknown> | undefined;
386
+ };
387
+ startMissingHeartbeatTimeout(): void;
388
+ startActiveHeartbeat(): void;
389
+ private sendHeartbeat;
390
+ onMessageData: (msg: Uint8Array) => void;
391
+ _handleStateExit(): void;
392
+ _handleClose(): void;
544
393
  }
545
394
 
546
- type ConstructHandshake<T extends TSchema> = () => Static<T> | Promise<Static<T>>;
547
- type ValidateHandshake<T extends TSchema> = (metadata: Static<T>, previousParsedMetadata?: ParsedMetadata) => Static<typeof HandshakeErrorCustomHandlerFatalResponseCodes> | ParsedMetadata | Promise<Static<typeof HandshakeErrorCustomHandlerFatalResponseCodes> | ParsedMetadata>;
548
- interface ClientHandshakeOptions<MetadataSchema extends TSchema = TSchema> {
549
- /**
550
- * Schema for the metadata that the client sends to the server
551
- * during the handshake.
552
- */
553
- schema: MetadataSchema;
554
- /**
555
- * Gets the {@link HandshakeRequestMetadata} to send to the server.
556
- */
557
- construct: ConstructHandshake<MetadataSchema>;
395
+ declare class SessionNoConnection extends IdentifiedSessionWithGracePeriod {
396
+ readonly state: SessionState.NoConnection;
397
+ _handleClose(): void;
398
+ _handleStateExit(): void;
558
399
  }
559
- interface ServerHandshakeOptions<MetadataSchema extends TSchema = TSchema> {
560
- /**
561
- * Schema for the metadata that the server receives from the client
562
- * during the handshake.
563
- */
564
- schema: MetadataSchema;
565
- /**
566
- * Parses the {@link HandshakeRequestMetadata} sent by the client, transforming
567
- * it into {@link ParsedHandshakeMetadata}.
568
- *
569
- * May return `false` if the client should be rejected.
570
- *
571
- * @param metadata - The metadata sent by the client.
572
- * @param session - The session that the client would be associated with.
573
- * @param isReconnect - Whether the client is reconnecting to the session,
574
- * or if this is a new session.
575
- */
576
- validate: ValidateHandshake<MetadataSchema>;
400
+
401
+ interface SessionBackingOffListeners extends IdentifiedSessionWithGracePeriodListeners {
402
+ onBackoffFinished: () => void;
577
403
  }
578
- declare function createClientHandshakeOptions<MetadataSchema extends TSchema = TSchema>(schema: MetadataSchema, construct: ConstructHandshake<MetadataSchema>): ClientHandshakeOptions;
579
- declare function createServerHandshakeOptions<MetadataSchema extends TSchema = TSchema>(schema: MetadataSchema, validate: ValidateHandshake<MetadataSchema>): ServerHandshakeOptions;
404
+ interface SessionBackingOffProps extends IdentifiedSessionWithGracePeriodProps {
405
+ backoffMs: number;
406
+ listeners: SessionBackingOffListeners;
407
+ }
408
+ declare class SessionBackingOff extends IdentifiedSessionWithGracePeriod {
409
+ readonly state: SessionState.BackingOff;
410
+ listeners: SessionBackingOffListeners;
411
+ backoffTimeout?: ReturnType<typeof setTimeout>;
412
+ constructor(props: SessionBackingOffProps);
413
+ _handleClose(): void;
414
+ _handleStateExit(): void;
415
+ }
416
+
417
+ type ClientSession<ConnType extends Connection> = SessionNoConnection | SessionBackingOff | SessionConnecting<ConnType> | SessionHandshaking<ConnType> | SessionConnected<ConnType>;
418
+ type ServerSession<ConnType extends Connection> = SessionConnected<ConnType> | SessionNoConnection;
419
+ type Session<ConnType extends Connection> = ClientSession<ConnType> | ServerSession<ConnType>;
580
420
 
581
421
  declare abstract class ClientTransport<ConnType extends Connection> extends Transport<ConnType> {
582
422
  /**
@@ -658,7 +498,7 @@ type BaseErrorSchemaType = TObject<{
658
498
  /**
659
499
  * A schema for cancel payloads sent from the client
660
500
  */
661
- declare const CancelResultSchema: TObject<{
501
+ declare const CancelErrorSchema: TObject<{
662
502
  code: TLiteral<"CANCEL">;
663
503
  message: TString;
664
504
  }>;
@@ -978,7 +818,7 @@ type ProcedureHandlerContext<State> = ServiceContext & {
978
818
  * Cancelling is not the same as closing procedure calls gracefully, please refer to
979
819
  * the river documentation to understand the difference between the two concepts.
980
820
  */
981
- cancel: (message?: string) => ErrResult<Static<typeof CancelResultSchema>>;
821
+ cancel: (message?: string) => ErrResult<Static<typeof CancelErrorSchema>>;
982
822
  /**
983
823
  * This signal is a standard [AbortSignal](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal)
984
824
  * triggered when the procedure invocation is done. This signal tracks the invocation/request finishing
@@ -1022,7 +862,7 @@ type ValidProcType = 'rpc' | 'upload' | 'subscription' | 'stream';
1022
862
  * Represents the payload type for {@link Procedure}s.
1023
863
  */
1024
864
  type PayloadType = TSchema;
1025
- type Cancellable<T> = T | Static<typeof CancelResultSchema>;
865
+ type Cancellable<T> = T | Static<typeof CancelErrorSchema>;
1026
866
  /**
1027
867
  * Procedure for a single message in both directions (1:1).
1028
868
  *
@@ -1566,4 +1406,161 @@ declare class ServiceScaffold<State extends object> {
1566
1406
  }>;
1567
1407
  }
1568
1408
 
1569
- export { ResultUnwrapOk as $, AnyServiceSchemaMap as A, Readable as B, ClientTransport as C, Procedure as D, ProcedureErrorSchemaType as E, flattenErrorType as F, UNCAUGHT_ERROR_CODE as G, UNEXPECTED_DISCONNECT_CODE as H, InstantiatedServiceSchemaMap as I, INVALID_REQUEST_CODE as J, CANCEL_CODE as K, ReaderErrorSchema as L, BaseErrorSchemaType as M, createClient as N, Client as O, ProvidedClientTransportOptions as P, ProcedureHandlerContext as Q, RpcProcedure as R, ServerHandshakeOptions as S, Ok as T, UploadProcedure as U, ValidProcType as V, Writable as W, Err as X, Result as Y, ErrResult as Z, OkResult as _, ProvidedServerTransportOptions as a, ResultUnwrapErr as a0, ResponseData as a1, createClientHandshakeOptions as a2, createServerHandshakeOptions as a3, ClientHandshakeOptions as a4, ReadableIterator as a5, ReadableResult as a6, Transport as a7, SessionOptions as a8, ClientTransportOptions as a9, SessionNoConnection as aa, SessionBoundSendFn as ab, CommonSession as ac, SessionState as ad, CommonSessionProps as ae, ServerTransportOptions as af, ServerSession as ag, DeleteSessionOptions as ah, TransportStatus as ai, ProvidedTransportOptions as aj, Session as ak, SessionConnecting as al, SessionHandshaking as am, SessionConnected as an, EventMap as ao, EventTypes as ap, EventHandler as aq, ProtocolError as ar, ProtocolErrorType as as, Connection as b, ParsedMetadata as c, AnyProcedure as d, ServiceContext as e, Service as f, ServiceConfiguration as g, ProcHandler as h, ProcInit as i, ProcRequest as j, ProcResponse as k, ProcErrors as l, ProcType as m, ServiceSchema as n, SerializedServerSchema as o, SerializedServiceSchema as p, SerializedProcedureSchema as q, serializeSchemaV1Compat as r, serializeSchema as s, SerializedServerSchemaProtocolv1 as t, SerializedServiceSchemaProtocolv1 as u, SerializedProcedureSchemaProtocolv1 as v, PayloadType as w, ProcedureMap as x, SubscriptionProcedure as y, StreamProcedure as z };
1409
+ declare const ProtocolError: {
1410
+ readonly RetriesExceeded: "conn_retry_exceeded";
1411
+ readonly HandshakeFailed: "handshake_failed";
1412
+ readonly MessageOrderingViolated: "message_ordering_violated";
1413
+ readonly InvalidMessage: "invalid_message";
1414
+ readonly MessageSendFailure: "message_send_failure";
1415
+ };
1416
+ type ProtocolErrorType = (typeof ProtocolError)[keyof typeof ProtocolError];
1417
+ interface EventMap {
1418
+ message: OpaqueTransportMessage;
1419
+ sessionStatus: {
1420
+ status: 'created' | 'closing';
1421
+ session: Session<Connection>;
1422
+ } | {
1423
+ status: 'closed';
1424
+ session: Pick<Session<Connection>, 'id' | 'to'>;
1425
+ };
1426
+ sessionTransition: {
1427
+ state: SessionState.Connected;
1428
+ id: SessionId;
1429
+ } | {
1430
+ state: SessionState.Handshaking;
1431
+ id: SessionId;
1432
+ } | {
1433
+ state: SessionState.Connecting;
1434
+ id: SessionId;
1435
+ } | {
1436
+ state: SessionState.BackingOff;
1437
+ id: SessionId;
1438
+ } | {
1439
+ state: SessionState.NoConnection;
1440
+ id: SessionId;
1441
+ };
1442
+ protocolError: {
1443
+ type: (typeof ProtocolError)['HandshakeFailed'];
1444
+ code: Static<typeof HandshakeErrorResponseCodes>;
1445
+ message: string;
1446
+ } | {
1447
+ type: Omit<ProtocolErrorType, (typeof ProtocolError)['HandshakeFailed']>;
1448
+ message: string;
1449
+ };
1450
+ transportStatus: {
1451
+ status: TransportStatus;
1452
+ };
1453
+ }
1454
+ type EventTypes = keyof EventMap;
1455
+ type EventHandler<K extends EventTypes> = (event: EventMap[K]) => unknown;
1456
+ declare class EventDispatcher<T extends EventTypes> {
1457
+ private eventListeners;
1458
+ removeAllListeners(): void;
1459
+ numberOfListeners<K extends T>(eventType: K): number;
1460
+ addEventListener<K extends T>(eventType: K, handler: EventHandler<K>): void;
1461
+ removeEventListener<K extends T>(eventType: K, handler: EventHandler<K>): void;
1462
+ dispatchEvent<K extends T>(eventType: K, event: EventMap[K]): void;
1463
+ }
1464
+
1465
+ /**
1466
+ * Represents the possible states of a transport.
1467
+ * @property {'open'} open - The transport is open and operational (note that this doesn't mean it is actively connected)
1468
+ * @property {'closed'} closed - The transport is permanently closed and cannot be reopened.
1469
+ */
1470
+ type TransportStatus = 'open' | 'closed';
1471
+ interface DeleteSessionOptions {
1472
+ unhealthy: boolean;
1473
+ }
1474
+ type SessionBoundSendFn = (msg: PartialTransportMessage) => string;
1475
+ /**
1476
+ * Transports manage the lifecycle (creation/deletion) of sessions
1477
+ *
1478
+ * ```plaintext
1479
+ * ▲
1480
+ * incoming │
1481
+ * messages │
1482
+ * ▼
1483
+ * ┌─────────────┐ 1:N ┌───────────┐ 1:1* ┌────────────┐
1484
+ * │ Transport │ ◄─────► │ Session │ ◄─────► │ Connection │
1485
+ * └─────────────┘ └───────────┘ └────────────┘
1486
+ * ▲ * (may or may not be initialized yet)
1487
+ * │
1488
+ * ▼
1489
+ * ┌───────────┐
1490
+ * │ Message │
1491
+ * │ Listeners │
1492
+ * └───────────┘
1493
+ * ```
1494
+ * @abstract
1495
+ */
1496
+ declare abstract class Transport<ConnType extends Connection> {
1497
+ /**
1498
+ * The status of the transport.
1499
+ */
1500
+ private status;
1501
+ /**
1502
+ * The client ID of this transport.
1503
+ */
1504
+ clientId: TransportClientId;
1505
+ /**
1506
+ * The event dispatcher for handling events of type EventTypes.
1507
+ */
1508
+ eventDispatcher: EventDispatcher<EventTypes>;
1509
+ /**
1510
+ * The options for this transport.
1511
+ */
1512
+ protected options: TransportOptions;
1513
+ log?: Logger;
1514
+ tracer: Tracer;
1515
+ sessions: Map<TransportClientId, Session<ConnType>>;
1516
+ /**
1517
+ * Creates a new Transport instance.
1518
+ * @param codec The codec used to encode and decode messages.
1519
+ * @param clientId The client ID of this transport.
1520
+ */
1521
+ constructor(clientId: TransportClientId, providedOptions?: ProvidedTransportOptions);
1522
+ bindLogger(fn: LogFn | Logger, level?: LoggingLevel): void;
1523
+ /**
1524
+ * Called when a message is received by this transport.
1525
+ * You generally shouldn't need to override this in downstream transport implementations.
1526
+ * @param message The received message.
1527
+ */
1528
+ protected handleMsg(message: OpaqueTransportMessage): void;
1529
+ /**
1530
+ * Adds a listener to this transport.
1531
+ * @param the type of event to listen for
1532
+ * @param handler The message handler to add.
1533
+ */
1534
+ addEventListener<K extends EventTypes, T extends EventHandler<K>>(type: K, handler: T): void;
1535
+ /**
1536
+ * Removes a listener from this transport.
1537
+ * @param the type of event to un-listen on
1538
+ * @param handler The message handler to remove.
1539
+ */
1540
+ removeEventListener<K extends EventTypes, T extends EventHandler<K>>(type: K, handler: T): void;
1541
+ protected protocolError(message: EventMap['protocolError']): void;
1542
+ /**
1543
+ * Default close implementation for transports. You should override this in the downstream
1544
+ * implementation if you need to do any additional cleanup and call super.close() at the end.
1545
+ * Closes the transport. Any messages sent while the transport is closed will be silently discarded.
1546
+ */
1547
+ close(): void;
1548
+ getStatus(): TransportStatus;
1549
+ protected createSession<S extends Session<ConnType>>(session: S): void;
1550
+ protected updateSession<S extends Session<ConnType>>(session: S): void;
1551
+ protected deleteSession(session: Session<ConnType>, options?: DeleteSessionOptions): void;
1552
+ protected onSessionGracePeriodElapsed(session: Session<ConnType>): void;
1553
+ protected onConnectingFailed(session: SessionConnecting<ConnType>): SessionNoConnection;
1554
+ protected onConnClosed(session: SessionHandshaking<ConnType> | SessionConnected<ConnType>): SessionNoConnection;
1555
+ /**
1556
+ * Gets a send closure scoped to a specific session. Sending using the returned
1557
+ * closure after the session has transitioned to a different state will be a noop.
1558
+ *
1559
+ * Session objects themselves can become stale as they transition between
1560
+ * states. As stale sessions cannot be used again (and will throw), holding
1561
+ * onto a session object is not recommended.
1562
+ */
1563
+ getSessionBoundSendFn(to: TransportClientId, sessionId: SessionId): SessionBoundSendFn;
1564
+ }
1565
+
1566
+ export { type ResultUnwrapOk as $, type AnyServiceSchemaMap as A, type StreamProcedure as B, ClientTransport as C, type Readable as D, Procedure as E, type ProcedureErrorSchemaType as F, flattenErrorType as G, UNCAUGHT_ERROR_CODE as H, type InstantiatedServiceSchemaMap as I, UNEXPECTED_DISCONNECT_CODE as J, INVALID_REQUEST_CODE as K, CANCEL_CODE as L, ReaderErrorSchema as M, type BaseErrorSchemaType as N, createClient as O, type ProvidedClientTransportOptions as P, type Client as Q, type RpcProcedure as R, type ServerHandshakeOptions as S, Ok as T, type UploadProcedure as U, type ValidProcType as V, type Writable as W, Err as X, type Result as Y, type ErrResult as Z, type OkResult as _, type ProvidedServerTransportOptions as a, type ResultUnwrapErr as a0, type ResponseData as a1, createClientHandshakeOptions as a2, createServerHandshakeOptions as a3, type ClientHandshakeOptions as a4, type ReadableIterator as a5, type ReadableResult as a6, Transport as a7, type SessionOptions as a8, type ClientTransportOptions as a9, SessionNoConnection as aa, type SessionBoundSendFn as ab, CommonSession as ac, SessionState as ad, type CommonSessionProps as ae, type ServerTransportOptions as af, type ServerSession as ag, type DeleteSessionOptions as ah, type TransportStatus as ai, type ProvidedTransportOptions as aj, type Session as ak, SessionConnecting as al, SessionHandshaking as am, SessionConnected as an, type EventMap as ao, type EventTypes as ap, type EventHandler as aq, ProtocolError as ar, type ProtocolErrorType as as, Connection as b, type ServiceContext as c, type ProcedureHandlerContext as d, type PayloadType as e, type ParsedMetadata as f, type AnyProcedure as g, type Service as h, type ServiceConfiguration as i, type ProcHandler as j, type ProcInit as k, type ProcRequest as l, type ProcResponse as m, type ProcErrors as n, type ProcType as o, ServiceSchema as p, type SerializedServerSchema as q, type SerializedServiceSchema as r, serializeSchema as s, type SerializedProcedureSchema as t, serializeSchemaV1Compat as u, type SerializedServerSchemaProtocolv1 as v, type SerializedServiceSchemaProtocolv1 as w, type SerializedProcedureSchemaProtocolv1 as x, type ProcedureMap as y, type SubscriptionProcedure as z };