@replit/river 0.208.0 → 0.208.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/dist/{adapter-ChksXKVN.d.ts → adapter-f2b6e211.d.ts} +2 -2
  2. package/dist/{chunk-2JNVDUMN.js → chunk-2WFRHXDZ.js} +17 -12
  3. package/dist/chunk-2WFRHXDZ.js.map +1 -0
  4. package/dist/{chunk-DKW3GC3M.js → chunk-BXKBENJE.js} +2 -2
  5. package/dist/{chunk-ETZAHFGQ.js → chunk-EVAQ2QMB.js} +25 -21
  6. package/dist/{chunk-ETZAHFGQ.js.map → chunk-EVAQ2QMB.js.map} +1 -1
  7. package/dist/codec/index.cjs +1 -1
  8. package/dist/codec/index.cjs.map +1 -1
  9. package/dist/codec/index.d.cts +3 -3
  10. package/dist/codec/index.d.ts +3 -3
  11. package/dist/codec/index.js +2 -2
  12. package/dist/{connection-Donr3JRB.d.ts → connection-098d4aad.d.ts} +4 -4
  13. package/dist/{index-D8IOd3LG.d.ts → index-02554794.d.ts} +2 -2
  14. package/dist/logging/index.d.cts +2 -2
  15. package/dist/logging/index.d.ts +2 -2
  16. package/dist/{message-Di94OL80.d.cts → message-01c3e85a.d.ts} +1 -1
  17. package/dist/router/index.cjs +9 -5
  18. package/dist/router/index.cjs.map +1 -1
  19. package/dist/router/index.d.cts +7 -7
  20. package/dist/router/index.d.ts +7 -7
  21. package/dist/router/index.js +1 -1
  22. package/dist/{transport-CZb3vdB4.d.ts → services-44be1b6b.d.ts} +275 -275
  23. package/dist/testUtil/index.cjs +14 -8
  24. package/dist/testUtil/index.cjs.map +1 -1
  25. package/dist/testUtil/index.d.cts +5 -5
  26. package/dist/testUtil/index.d.ts +5 -5
  27. package/dist/testUtil/index.js +5 -4
  28. package/dist/testUtil/index.js.map +1 -1
  29. package/dist/transport/impls/ws/client.cjs +10 -6
  30. package/dist/transport/impls/ws/client.cjs.map +1 -1
  31. package/dist/transport/impls/ws/client.d.cts +6 -6
  32. package/dist/transport/impls/ws/client.d.ts +6 -6
  33. package/dist/transport/impls/ws/client.js +3 -3
  34. package/dist/transport/impls/ws/server.cjs +12 -7
  35. package/dist/transport/impls/ws/server.cjs.map +1 -1
  36. package/dist/transport/impls/ws/server.d.cts +6 -6
  37. package/dist/transport/impls/ws/server.d.ts +6 -6
  38. package/dist/transport/impls/ws/server.js +3 -3
  39. package/dist/transport/index.cjs +12 -7
  40. package/dist/transport/index.cjs.map +1 -1
  41. package/dist/transport/index.d.cts +6 -6
  42. package/dist/transport/index.d.ts +6 -6
  43. package/dist/transport/index.js +3 -3
  44. package/dist/{wslike-Dng9H1C7.d.ts → wslike-e0b32dd5.d.ts} +1 -1
  45. package/package.json +1 -1
  46. package/dist/adapter-Cuc4JtfV.d.cts +0 -46
  47. package/dist/chunk-2JNVDUMN.js.map +0 -1
  48. package/dist/connection-BF4zg6Qv.d.cts +0 -35
  49. package/dist/index-C9tpZjBN.d.cts +0 -37
  50. package/dist/message-Di94OL80.d.ts +0 -108
  51. package/dist/transport-CCaWx1Rb.d.cts +0 -1566
  52. package/dist/wslike-Dng9H1C7.d.cts +0 -40
  53. /package/dist/{chunk-DKW3GC3M.js.map → chunk-BXKBENJE.js.map} +0 -0
@@ -1,11 +1,11 @@
1
- import { A as AnyServiceSchemaMap, b as Connection, S as ServerHandshakeOptions, c as ServiceContext, d as ProcedureHandlerContext, e as PayloadType, I as InstantiatedServiceSchemaMap, f as ParsedMetadata, g as AnyProcedure } from '../transport-CCaWx1Rb.cjs';
2
- export { N as BaseErrorSchemaType, L as CANCEL_CODE, Q as Client, X as Err, Z as ErrResult, K as INVALID_REQUEST_CODE, T as Ok, _ as OkResult, n as ProcErrors, j as ProcHandler, k as ProcInit, l as ProcRequest, m as ProcResponse, o as ProcType, E as Procedure, F as ProcedureErrorSchemaType, y as ProcedureMap, R as RPCProcedure, D as Readable, M as ReaderErrorSchema, a1 as ResponseData, Y as Result, a0 as ResultUnwrapErr, $ as ResultUnwrapOk, t as SerializedProcedureSchema, x as SerializedProcedureSchemaProtocolv1, q as SerializedServerSchema, v as SerializedServerSchemaProtocolv1, r as SerializedServiceSchema, w as SerializedServiceSchemaProtocolv1, h as Service, i as ServiceConfiguration, p as ServiceSchema, B as StreamProcedure, z as SubscriptionProcedure, H as UNCAUGHT_ERROR_CODE, J as UNEXPECTED_DISCONNECT_CODE, U as UploadProcedure, V as ValidProcType, W as Writable, O as createClient, a2 as createClientHandshakeOptions, a3 as createServerHandshakeOptions, G as flattenErrorType, s as serializeSchema, u as serializeSchemaV1Compat } from '../transport-CCaWx1Rb.cjs';
1
+ import { A as AnyServiceSchemaMap, I as InstantiatedServiceSchemaMap, c as ParsedMetadata, d as AnyProcedure, e as ProcedureHandlerContext, f as PayloadType, b as Connection, S as ServerHandshakeOptions, g as ServiceContext } from '../services-44be1b6b.js';
2
+ export { N as BaseErrorSchemaType, L as CANCEL_CODE, Q as Client, X as Err, Z as ErrResult, K as INVALID_REQUEST_CODE, T as Ok, _ as OkResult, n as ProcErrors, j as ProcHandler, k as ProcInit, l as ProcRequest, m as ProcResponse, o as ProcType, E as Procedure, F as ProcedureErrorSchemaType, y as ProcedureMap, R as RPCProcedure, D as Readable, M as ReaderErrorSchema, a1 as ResponseData, Y as Result, a0 as ResultUnwrapErr, $ as ResultUnwrapOk, t as SerializedProcedureSchema, x as SerializedProcedureSchemaProtocolv1, q as SerializedServerSchema, v as SerializedServerSchemaProtocolv1, r as SerializedServiceSchema, w as SerializedServiceSchemaProtocolv1, h as Service, i as ServiceConfiguration, p as ServiceSchema, B as StreamProcedure, z as SubscriptionProcedure, H as UNCAUGHT_ERROR_CODE, J as UNEXPECTED_DISCONNECT_CODE, U as UploadProcedure, V as ValidProcType, W as Writable, O as createClient, a2 as createClientHandshakeOptions, a3 as createServerHandshakeOptions, G as flattenErrorType, s as serializeSchema, u as serializeSchemaV1Compat } from '../services-44be1b6b.js';
3
3
  import { Static } from '@sinclair/typebox';
4
- import { T as TransportClientId, O as OpaqueTransportMessage } from '../message-Di94OL80.cjs';
4
+ import { T as TransportClientId, O as OpaqueTransportMessage } from '../message-01c3e85a.js';
5
5
  import { ServerTransport } from '../transport/index.cjs';
6
6
  import '@opentelemetry/api';
7
- import '../index-C9tpZjBN.cjs';
8
- import '../adapter-Cuc4JtfV.cjs';
7
+ import '../index-02554794.js';
8
+ import '../adapter-f2b6e211.js';
9
9
 
10
10
  type StreamId = string;
11
11
  /**
@@ -71,6 +71,6 @@ declare function createServer<Services extends AnyServiceSchemaMap>(transport: S
71
71
  middlewares?: Array<Middleware>;
72
72
  }>): Server<Services>;
73
73
 
74
- var version = "0.208.0";
74
+ var version = "0.208.1";
75
75
 
76
- export { type Middleware, type MiddlewareContext, type MiddlewareParam, ParsedMetadata, PayloadType, ProcedureHandlerContext, version as RIVER_VERSION, type Server, ServiceContext, createServer };
76
+ export { Middleware, MiddlewareContext, MiddlewareParam, ParsedMetadata, PayloadType, ProcedureHandlerContext, version as RIVER_VERSION, Server, ServiceContext, createServer };
@@ -1,11 +1,11 @@
1
- import { A as AnyServiceSchemaMap, b as Connection, S as ServerHandshakeOptions, c as ServiceContext, d as ProcedureHandlerContext, e as PayloadType, I as InstantiatedServiceSchemaMap, f as ParsedMetadata, g as AnyProcedure } from '../transport-CZb3vdB4.js';
2
- export { N as BaseErrorSchemaType, L as CANCEL_CODE, Q as Client, X as Err, Z as ErrResult, K as INVALID_REQUEST_CODE, T as Ok, _ as OkResult, n as ProcErrors, j as ProcHandler, k as ProcInit, l as ProcRequest, m as ProcResponse, o as ProcType, E as Procedure, F as ProcedureErrorSchemaType, y as ProcedureMap, R as RPCProcedure, D as Readable, M as ReaderErrorSchema, a1 as ResponseData, Y as Result, a0 as ResultUnwrapErr, $ as ResultUnwrapOk, t as SerializedProcedureSchema, x as SerializedProcedureSchemaProtocolv1, q as SerializedServerSchema, v as SerializedServerSchemaProtocolv1, r as SerializedServiceSchema, w as SerializedServiceSchemaProtocolv1, h as Service, i as ServiceConfiguration, p as ServiceSchema, B as StreamProcedure, z as SubscriptionProcedure, H as UNCAUGHT_ERROR_CODE, J as UNEXPECTED_DISCONNECT_CODE, U as UploadProcedure, V as ValidProcType, W as Writable, O as createClient, a2 as createClientHandshakeOptions, a3 as createServerHandshakeOptions, G as flattenErrorType, s as serializeSchema, u as serializeSchemaV1Compat } from '../transport-CZb3vdB4.js';
1
+ import { A as AnyServiceSchemaMap, I as InstantiatedServiceSchemaMap, c as ParsedMetadata, d as AnyProcedure, e as ProcedureHandlerContext, f as PayloadType, b as Connection, S as ServerHandshakeOptions, g as ServiceContext } from '../services-44be1b6b.js';
2
+ export { N as BaseErrorSchemaType, L as CANCEL_CODE, Q as Client, X as Err, Z as ErrResult, K as INVALID_REQUEST_CODE, T as Ok, _ as OkResult, n as ProcErrors, j as ProcHandler, k as ProcInit, l as ProcRequest, m as ProcResponse, o as ProcType, E as Procedure, F as ProcedureErrorSchemaType, y as ProcedureMap, R as RPCProcedure, D as Readable, M as ReaderErrorSchema, a1 as ResponseData, Y as Result, a0 as ResultUnwrapErr, $ as ResultUnwrapOk, t as SerializedProcedureSchema, x as SerializedProcedureSchemaProtocolv1, q as SerializedServerSchema, v as SerializedServerSchemaProtocolv1, r as SerializedServiceSchema, w as SerializedServiceSchemaProtocolv1, h as Service, i as ServiceConfiguration, p as ServiceSchema, B as StreamProcedure, z as SubscriptionProcedure, H as UNCAUGHT_ERROR_CODE, J as UNEXPECTED_DISCONNECT_CODE, U as UploadProcedure, V as ValidProcType, W as Writable, O as createClient, a2 as createClientHandshakeOptions, a3 as createServerHandshakeOptions, G as flattenErrorType, s as serializeSchema, u as serializeSchemaV1Compat } from '../services-44be1b6b.js';
3
3
  import { Static } from '@sinclair/typebox';
4
- import { T as TransportClientId, O as OpaqueTransportMessage } from '../message-Di94OL80.js';
4
+ import { T as TransportClientId, O as OpaqueTransportMessage } from '../message-01c3e85a.js';
5
5
  import { ServerTransport } from '../transport/index.js';
6
6
  import '@opentelemetry/api';
7
- import '../index-D8IOd3LG.js';
8
- import '../adapter-ChksXKVN.js';
7
+ import '../index-02554794.js';
8
+ import '../adapter-f2b6e211.js';
9
9
 
10
10
  type StreamId = string;
11
11
  /**
@@ -71,6 +71,6 @@ declare function createServer<Services extends AnyServiceSchemaMap>(transport: S
71
71
  middlewares?: Array<Middleware>;
72
72
  }>): Server<Services>;
73
73
 
74
- var version = "0.208.0";
74
+ var version = "0.208.1";
75
75
 
76
- export { type Middleware, type MiddlewareContext, type MiddlewareParam, ParsedMetadata, PayloadType, ProcedureHandlerContext, version as RIVER_VERSION, type Server, ServiceContext, createServer };
76
+ export { Middleware, MiddlewareContext, MiddlewareParam, ParsedMetadata, PayloadType, ProcedureHandlerContext, version as RIVER_VERSION, Server, ServiceContext, createServer };
@@ -16,7 +16,7 @@ import {
16
16
  serializeSchema,
17
17
  serializeSchemaV1Compat,
18
18
  version
19
- } from "../chunk-ETZAHFGQ.js";
19
+ } from "../chunk-EVAQ2QMB.js";
20
20
  export {
21
21
  CANCEL_CODE,
22
22
  Err,
@@ -1,9 +1,9 @@
1
1
  import * as _sinclair_typebox from '@sinclair/typebox';
2
- import { TSchema, Static, TNever, TObject, TLiteral, TString, TUnion } from '@sinclair/typebox';
2
+ import { Static, TSchema, TObject, TString, TUnion, TLiteral, TNever } 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 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';
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';
7
7
 
8
8
  /**
9
9
  * A connection is the actual raw underlying transport connection.
@@ -188,100 +188,6 @@ declare abstract class IdentifiedSessionWithGracePeriod extends IdentifiedSessio
188
188
  _handleClose(): void;
189
189
  }
190
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
-
285
191
  interface SessionConnectingListeners extends IdentifiedSessionWithGracePeriodListeners {
286
192
  onConnectionEstablished: (conn: Connection) => void;
287
193
  onConnectionFailed: (err: unknown) => void;
@@ -302,6 +208,12 @@ declare class SessionConnecting<ConnType extends Connection> extends IdentifiedS
302
208
  _handleClose(): void;
303
209
  }
304
210
 
211
+ declare class SessionNoConnection extends IdentifiedSessionWithGracePeriod {
212
+ readonly state: SessionState.NoConnection;
213
+ _handleClose(): void;
214
+ _handleStateExit(): void;
215
+ }
216
+
305
217
  interface SessionHandshakingListeners extends IdentifiedSessionWithGracePeriodListeners {
306
218
  onConnectionErrored: (err: unknown) => void;
307
219
  onConnectionClosed: () => void;
@@ -392,31 +304,276 @@ declare class SessionConnected<ConnType extends Connection> extends IdentifiedSe
392
304
  _handleClose(): void;
393
305
  }
394
306
 
395
- declare class SessionNoConnection extends IdentifiedSessionWithGracePeriod {
396
- readonly state: SessionState.NoConnection;
307
+ interface SessionBackingOffListeners extends IdentifiedSessionWithGracePeriodListeners {
308
+ onBackoffFinished: () => void;
309
+ }
310
+ interface SessionBackingOffProps extends IdentifiedSessionWithGracePeriodProps {
311
+ backoffMs: number;
312
+ listeners: SessionBackingOffListeners;
313
+ }
314
+ declare class SessionBackingOff extends IdentifiedSessionWithGracePeriod {
315
+ readonly state: SessionState.BackingOff;
316
+ listeners: SessionBackingOffListeners;
317
+ backoffTimeout?: ReturnType<typeof setTimeout>;
318
+ constructor(props: SessionBackingOffProps);
397
319
  _handleClose(): void;
398
320
  _handleStateExit(): void;
399
321
  }
400
322
 
401
- interface SessionBackingOffListeners extends IdentifiedSessionWithGracePeriodListeners {
402
- onBackoffFinished: () => void;
403
- }
404
- interface SessionBackingOffProps extends IdentifiedSessionWithGracePeriodProps {
405
- backoffMs: number;
406
- listeners: SessionBackingOffListeners;
323
+ type ClientSession<ConnType extends Connection> = SessionNoConnection | SessionBackingOff | SessionConnecting<ConnType> | SessionHandshaking<ConnType> | SessionConnected<ConnType>;
324
+ type ServerSession<ConnType extends Connection> = SessionConnected<ConnType> | SessionNoConnection;
325
+ type Session<ConnType extends Connection> = ClientSession<ConnType> | ServerSession<ConnType>;
326
+
327
+ declare const ProtocolError: {
328
+ readonly RetriesExceeded: "conn_retry_exceeded";
329
+ readonly HandshakeFailed: "handshake_failed";
330
+ readonly MessageOrderingViolated: "message_ordering_violated";
331
+ readonly InvalidMessage: "invalid_message";
332
+ readonly MessageSendFailure: "message_send_failure";
333
+ };
334
+ type ProtocolErrorType = (typeof ProtocolError)[keyof typeof ProtocolError];
335
+ interface EventMap {
336
+ message: OpaqueTransportMessage;
337
+ sessionStatus: {
338
+ status: 'created' | 'closing';
339
+ session: Session<Connection>;
340
+ } | {
341
+ status: 'closed';
342
+ session: Pick<Session<Connection>, 'id' | 'to'>;
343
+ };
344
+ sessionTransition: {
345
+ state: SessionState.Connected;
346
+ id: SessionId;
347
+ } | {
348
+ state: SessionState.Handshaking;
349
+ id: SessionId;
350
+ } | {
351
+ state: SessionState.Connecting;
352
+ id: SessionId;
353
+ } | {
354
+ state: SessionState.BackingOff;
355
+ id: SessionId;
356
+ } | {
357
+ state: SessionState.NoConnection;
358
+ id: SessionId;
359
+ };
360
+ protocolError: {
361
+ type: (typeof ProtocolError)['HandshakeFailed'];
362
+ code: Static<typeof HandshakeErrorResponseCodes>;
363
+ message: string;
364
+ } | {
365
+ type: Omit<ProtocolErrorType, (typeof ProtocolError)['HandshakeFailed']>;
366
+ message: string;
367
+ };
368
+ transportStatus: {
369
+ status: TransportStatus;
370
+ };
371
+ }
372
+ type EventTypes = keyof EventMap;
373
+ type EventHandler<K extends EventTypes> = (event: EventMap[K]) => unknown;
374
+ declare class EventDispatcher<T extends EventTypes> {
375
+ private eventListeners;
376
+ removeAllListeners(): void;
377
+ numberOfListeners<K extends T>(eventType: K): number;
378
+ addEventListener<K extends T>(eventType: K, handler: EventHandler<K>): void;
379
+ removeEventListener<K extends T>(eventType: K, handler: EventHandler<K>): void;
380
+ dispatchEvent<K extends T>(eventType: K, event: EventMap[K]): void;
381
+ }
382
+
383
+ /**
384
+ * Options to control the backoff and retry behavior of the client transport's connection behaviour.
385
+ *
386
+ * River implements exponential backoff with jitter to prevent flooding the server
387
+ * when there's an issue with connection establishment.
388
+ *
389
+ * The backoff is calculated via the following:
390
+ * backOff = min(jitter + {@link baseIntervalMs} * 2 ^ budget_consumed, {@link maxBackoffMs})
391
+ *
392
+ * We use a leaky bucket rate limit with a budget of {@link attemptBudgetCapacity} reconnection attempts.
393
+ * Budget only starts to restore after a successful handshake at a rate of one budget per {@link budgetRestoreIntervalMs}.
394
+ */
395
+ interface ConnectionRetryOptions {
396
+ /**
397
+ * The base interval to wait before retrying a connection.
398
+ */
399
+ baseIntervalMs: number;
400
+ /**
401
+ * The maximum random jitter to add to the total backoff time.
402
+ */
403
+ maxJitterMs: number;
404
+ /**
405
+ * The maximum amount of time to wait before retrying a connection.
406
+ * This does not include the jitter.
407
+ */
408
+ maxBackoffMs: number;
409
+ /**
410
+ * The max number of times to attempt a connection before a successful handshake.
411
+ * This persists across connections but starts restoring budget after a successful handshake.
412
+ * The restoration interval depends on {@link budgetRestoreIntervalMs}
413
+ */
414
+ attemptBudgetCapacity: number;
415
+ /**
416
+ * After a successful connection attempt, how long to wait before we restore a single budget.
417
+ */
418
+ budgetRestoreIntervalMs: number;
419
+ }
420
+ declare class LeakyBucketRateLimit {
421
+ private budgetConsumed;
422
+ private intervalHandle?;
423
+ private readonly options;
424
+ constructor(options: ConnectionRetryOptions);
425
+ getBackoffMs(): number;
426
+ get totalBudgetRestoreTime(): number;
427
+ consumeBudget(): void;
428
+ getBudgetConsumed(): number;
429
+ hasBudget(): boolean;
430
+ startRestoringBudget(): void;
431
+ private stopLeak;
432
+ close(): void;
433
+ }
434
+
435
+ type TransportOptions = SessionOptions;
436
+ type ProvidedTransportOptions = Partial<TransportOptions>;
437
+ type ClientTransportOptions = TransportOptions & ConnectionRetryOptions;
438
+ type ProvidedClientTransportOptions = Partial<ClientTransportOptions>;
439
+ type ServerTransportOptions = TransportOptions;
440
+ type ProvidedServerTransportOptions = Partial<ServerTransportOptions>;
441
+
442
+ /**
443
+ * Represents the possible states of a transport.
444
+ * @property {'open'} open - The transport is open and operational (note that this doesn't mean it is actively connected)
445
+ * @property {'closed'} closed - The transport is permanently closed and cannot be reopened.
446
+ */
447
+ type TransportStatus = 'open' | 'closed';
448
+ interface DeleteSessionOptions {
449
+ unhealthy: boolean;
450
+ }
451
+ type SessionBoundSendFn = (msg: PartialTransportMessage) => string;
452
+ /**
453
+ * Transports manage the lifecycle (creation/deletion) of sessions
454
+ *
455
+ * ```plaintext
456
+ * ▲
457
+ * incoming │
458
+ * messages │
459
+ * ▼
460
+ * ┌─────────────┐ 1:N ┌───────────┐ 1:1* ┌────────────┐
461
+ * │ Transport │ ◄─────► │ Session │ ◄─────► │ Connection │
462
+ * └─────────────┘ └───────────┘ └────────────┘
463
+ * ▲ * (may or may not be initialized yet)
464
+ * │
465
+ * ▼
466
+ * ┌───────────┐
467
+ * │ Message │
468
+ * │ Listeners │
469
+ * └───────────┘
470
+ * ```
471
+ * @abstract
472
+ */
473
+ declare abstract class Transport<ConnType extends Connection> {
474
+ /**
475
+ * The status of the transport.
476
+ */
477
+ private status;
478
+ /**
479
+ * The client ID of this transport.
480
+ */
481
+ clientId: TransportClientId;
482
+ /**
483
+ * The event dispatcher for handling events of type EventTypes.
484
+ */
485
+ eventDispatcher: EventDispatcher<EventTypes>;
486
+ /**
487
+ * The options for this transport.
488
+ */
489
+ protected options: TransportOptions;
490
+ log?: Logger;
491
+ tracer: Tracer;
492
+ sessions: Map<TransportClientId, Session<ConnType>>;
493
+ /**
494
+ * Creates a new Transport instance.
495
+ * @param codec The codec used to encode and decode messages.
496
+ * @param clientId The client ID of this transport.
497
+ */
498
+ constructor(clientId: TransportClientId, providedOptions?: ProvidedTransportOptions);
499
+ bindLogger(fn: LogFn | Logger, level?: LoggingLevel): void;
500
+ /**
501
+ * Called when a message is received by this transport.
502
+ * You generally shouldn't need to override this in downstream transport implementations.
503
+ * @param message The received message.
504
+ */
505
+ protected handleMsg(message: OpaqueTransportMessage): void;
506
+ /**
507
+ * Adds a listener to this transport.
508
+ * @param the type of event to listen for
509
+ * @param handler The message handler to add.
510
+ */
511
+ addEventListener<K extends EventTypes, T extends EventHandler<K>>(type: K, handler: T): void;
512
+ /**
513
+ * Removes a listener from this transport.
514
+ * @param the type of event to un-listen on
515
+ * @param handler The message handler to remove.
516
+ */
517
+ removeEventListener<K extends EventTypes, T extends EventHandler<K>>(type: K, handler: T): void;
518
+ protected protocolError(message: EventMap['protocolError']): void;
519
+ /**
520
+ * Default close implementation for transports. You should override this in the downstream
521
+ * implementation if you need to do any additional cleanup and call super.close() at the end.
522
+ * Closes the transport. Any messages sent while the transport is closed will be silently discarded.
523
+ */
524
+ close(): void;
525
+ getStatus(): TransportStatus;
526
+ protected createSession<S extends Session<ConnType>>(session: S): void;
527
+ protected updateSession<S extends Session<ConnType>>(session: S): void;
528
+ protected deleteSession(session: Session<ConnType>, options?: DeleteSessionOptions): void;
529
+ protected onSessionGracePeriodElapsed(session: Session<ConnType>): void;
530
+ protected onConnectingFailed(session: SessionConnecting<ConnType>): SessionNoConnection;
531
+ protected onConnClosed(session: SessionHandshaking<ConnType> | SessionConnected<ConnType>): SessionNoConnection;
532
+ /**
533
+ * Gets a send closure scoped to a specific session. Sending using the returned
534
+ * closure after the session has transitioned to a different state will be a noop.
535
+ *
536
+ * Session objects themselves can become stale as they transition between
537
+ * states. As stale sessions cannot be used again (and will throw), holding
538
+ * onto a session object is not recommended.
539
+ */
540
+ getSessionBoundSendFn(to: TransportClientId, sessionId: SessionId): SessionBoundSendFn;
541
+ }
542
+
543
+ type ConstructHandshake<T extends TSchema> = () => Static<T> | Promise<Static<T>>;
544
+ type ValidateHandshake<T extends TSchema> = (metadata: Static<T>, previousParsedMetadata?: ParsedMetadata) => Static<typeof HandshakeErrorCustomHandlerFatalResponseCodes> | ParsedMetadata | Promise<Static<typeof HandshakeErrorCustomHandlerFatalResponseCodes> | ParsedMetadata>;
545
+ interface ClientHandshakeOptions<MetadataSchema extends TSchema = TSchema> {
546
+ /**
547
+ * Schema for the metadata that the client sends to the server
548
+ * during the handshake.
549
+ */
550
+ schema: MetadataSchema;
551
+ /**
552
+ * Gets the {@link HandshakeRequestMetadata} to send to the server.
553
+ */
554
+ construct: ConstructHandshake<MetadataSchema>;
407
555
  }
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;
556
+ interface ServerHandshakeOptions<MetadataSchema extends TSchema = TSchema> {
557
+ /**
558
+ * Schema for the metadata that the server receives from the client
559
+ * during the handshake.
560
+ */
561
+ schema: MetadataSchema;
562
+ /**
563
+ * Parses the {@link HandshakeRequestMetadata} sent by the client, transforming
564
+ * it into {@link ParsedHandshakeMetadata}.
565
+ *
566
+ * May return `false` if the client should be rejected.
567
+ *
568
+ * @param metadata - The metadata sent by the client.
569
+ * @param session - The session that the client would be associated with.
570
+ * @param isReconnect - Whether the client is reconnecting to the session,
571
+ * or if this is a new session.
572
+ */
573
+ validate: ValidateHandshake<MetadataSchema>;
415
574
  }
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>;
575
+ declare function createClientHandshakeOptions<MetadataSchema extends TSchema = TSchema>(schema: MetadataSchema, construct: ConstructHandshake<MetadataSchema>): ClientHandshakeOptions;
576
+ declare function createServerHandshakeOptions<MetadataSchema extends TSchema = TSchema>(schema: MetadataSchema, validate: ValidateHandshake<MetadataSchema>): ServerHandshakeOptions;
420
577
 
421
578
  declare abstract class ClientTransport<ConnType extends Connection> extends Transport<ConnType> {
422
579
  /**
@@ -1406,161 +1563,4 @@ declare class ServiceScaffold<State extends object> {
1406
1563
  }>;
1407
1564
  }
1408
1565
 
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 };
1566
+ export { ResultUnwrapOk as $, AnyServiceSchemaMap as A, StreamProcedure as B, ClientTransport as C, Readable as D, Procedure as E, ProcedureErrorSchemaType as F, flattenErrorType as G, UNCAUGHT_ERROR_CODE as H, InstantiatedServiceSchemaMap as I, UNEXPECTED_DISCONNECT_CODE as J, INVALID_REQUEST_CODE as K, CANCEL_CODE as L, ReaderErrorSchema as M, BaseErrorSchemaType as N, createClient as O, ProvidedClientTransportOptions as P, Client 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, ProcedureHandlerContext as e, PayloadType as f, ServiceContext as g, Service as h, ServiceConfiguration as i, ProcHandler as j, ProcInit as k, ProcRequest as l, ProcResponse as m, ProcErrors as n, ProcType as o, ServiceSchema as p, SerializedServerSchema as q, SerializedServiceSchema as r, serializeSchema as s, SerializedProcedureSchema as t, serializeSchemaV1Compat as u, SerializedServerSchemaProtocolv1 as v, SerializedServiceSchemaProtocolv1 as w, SerializedProcedureSchemaProtocolv1 as x, ProcedureMap as y, SubscriptionProcedure as z };