@replit/river 0.23.18 → 0.24.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 (84) hide show
  1. package/README.md +17 -16
  2. package/dist/chunk-227EQHH5.js +653 -0
  3. package/dist/chunk-227EQHH5.js.map +1 -0
  4. package/dist/chunk-6YFPHVNO.js +277 -0
  5. package/dist/chunk-6YFPHVNO.js.map +1 -0
  6. package/dist/{chunk-7MJYOL32.js → chunk-BGJDNLTJ.js} +15 -23
  7. package/dist/chunk-BGJDNLTJ.js.map +1 -0
  8. package/dist/chunk-HXOQQXL4.js +382 -0
  9. package/dist/chunk-HXOQQXL4.js.map +1 -0
  10. package/dist/{chunk-R2HAS3GM.js → chunk-IYYQ7BII.js} +55 -41
  11. package/dist/chunk-IYYQ7BII.js.map +1 -0
  12. package/dist/{chunk-AVL32IMG.js → chunk-L664A3WA.js} +20 -16
  13. package/dist/chunk-L664A3WA.js.map +1 -0
  14. package/dist/{chunk-EV5HW4IC.js → chunk-M7E6LQO2.js} +66 -53
  15. package/dist/chunk-M7E6LQO2.js.map +1 -0
  16. package/dist/{chunk-6LCL2ZZF.js → chunk-TAH2GVTJ.js} +1 -1
  17. package/dist/chunk-TAH2GVTJ.js.map +1 -0
  18. package/dist/chunk-XOFF3UPL.js +399 -0
  19. package/dist/chunk-XOFF3UPL.js.map +1 -0
  20. package/dist/{client-5776a6bb.d.ts → client-2ba72e89.d.ts} +12 -15
  21. package/dist/connection-55cba970.d.ts +11 -0
  22. package/dist/{connection-bd35d442.d.ts → connection-c6db05d9.d.ts} +1 -5
  23. package/dist/{handshake-a947c234.d.ts → handshake-0b88e8fc.d.ts} +150 -184
  24. package/dist/logging/index.cjs.map +1 -1
  25. package/dist/logging/index.d.cts +1 -1
  26. package/dist/logging/index.d.ts +1 -1
  27. package/dist/logging/index.js +1 -1
  28. package/dist/{index-ea74cdbb.d.ts → message-e6c560fd.d.ts} +2 -2
  29. package/dist/router/index.cjs +105 -63
  30. package/dist/router/index.cjs.map +1 -1
  31. package/dist/router/index.d.cts +11 -10
  32. package/dist/router/index.d.ts +11 -10
  33. package/dist/router/index.js +2 -2
  34. package/dist/server-732e7014.d.ts +42 -0
  35. package/dist/{services-38b3f758.d.ts → services-adfd0bc3.d.ts} +3 -3
  36. package/dist/transport/impls/uds/client.cjs +1246 -1230
  37. package/dist/transport/impls/uds/client.cjs.map +1 -1
  38. package/dist/transport/impls/uds/client.d.cts +4 -4
  39. package/dist/transport/impls/uds/client.d.ts +4 -4
  40. package/dist/transport/impls/uds/client.js +7 -13
  41. package/dist/transport/impls/uds/client.js.map +1 -1
  42. package/dist/transport/impls/uds/server.cjs +1298 -1151
  43. package/dist/transport/impls/uds/server.cjs.map +1 -1
  44. package/dist/transport/impls/uds/server.d.cts +4 -4
  45. package/dist/transport/impls/uds/server.d.ts +4 -4
  46. package/dist/transport/impls/uds/server.js +6 -6
  47. package/dist/transport/impls/ws/client.cjs +976 -965
  48. package/dist/transport/impls/ws/client.cjs.map +1 -1
  49. package/dist/transport/impls/ws/client.d.cts +4 -4
  50. package/dist/transport/impls/ws/client.d.ts +4 -4
  51. package/dist/transport/impls/ws/client.js +6 -7
  52. package/dist/transport/impls/ws/client.js.map +1 -1
  53. package/dist/transport/impls/ws/server.cjs +1182 -1047
  54. package/dist/transport/impls/ws/server.cjs.map +1 -1
  55. package/dist/transport/impls/ws/server.d.cts +4 -4
  56. package/dist/transport/impls/ws/server.d.ts +4 -4
  57. package/dist/transport/impls/ws/server.js +6 -6
  58. package/dist/transport/index.cjs +1433 -1360
  59. package/dist/transport/index.cjs.map +1 -1
  60. package/dist/transport/index.d.cts +5 -5
  61. package/dist/transport/index.d.ts +5 -5
  62. package/dist/transport/index.js +9 -9
  63. package/dist/util/testHelpers.cjs +744 -310
  64. package/dist/util/testHelpers.cjs.map +1 -1
  65. package/dist/util/testHelpers.d.cts +9 -6
  66. package/dist/util/testHelpers.d.ts +9 -6
  67. package/dist/util/testHelpers.js +34 -10
  68. package/dist/util/testHelpers.js.map +1 -1
  69. package/package.json +1 -1
  70. package/dist/chunk-6LCL2ZZF.js.map +0 -1
  71. package/dist/chunk-7MJYOL32.js.map +0 -1
  72. package/dist/chunk-AVL32IMG.js.map +0 -1
  73. package/dist/chunk-DPKOJQWF.js +0 -476
  74. package/dist/chunk-DPKOJQWF.js.map +0 -1
  75. package/dist/chunk-EV5HW4IC.js.map +0 -1
  76. package/dist/chunk-J6N6H2WU.js +0 -476
  77. package/dist/chunk-J6N6H2WU.js.map +0 -1
  78. package/dist/chunk-MW5JXLHY.js +0 -348
  79. package/dist/chunk-MW5JXLHY.js.map +0 -1
  80. package/dist/chunk-R2HAS3GM.js.map +0 -1
  81. package/dist/chunk-RJOWZIWB.js +0 -335
  82. package/dist/chunk-RJOWZIWB.js.map +0 -1
  83. package/dist/connection-df85db7e.d.ts +0 -17
  84. package/dist/server-53cd5b7e.d.ts +0 -24
@@ -1,6 +1,6 @@
1
- import { C as Codec } from './types-3e5768ec.js';
2
- import { e as TelemetryInfo, M as MessageMetadata, c as TransportClientId, f as PropagationContext, L as Logger, P as PartialTransportMessage, a as TransportMessage, b as OpaqueTransportMessage, g as LogFn, h as LoggingLevel } from './index-ea74cdbb.js';
1
+ import { e as TelemetryInfo, M as MessageMetadata, a as TransportMessage, b as OpaqueTransportMessage, P as PartialTransportMessage, c as TransportClientId, L as Logger, f as LogFn, g as LoggingLevel } from './message-e6c560fd.js';
3
2
  import { TSchema, Static } from '@sinclair/typebox';
3
+ import { C as Codec } from './types-3e5768ec.js';
4
4
 
5
5
  /**
6
6
  * A connection is the actual raw underlying transport connection.
@@ -13,18 +13,25 @@ declare abstract class Connection {
13
13
  telemetry?: TelemetryInfo;
14
14
  constructor();
15
15
  get loggingMetadata(): MessageMetadata;
16
+ private _dataListeners;
17
+ private _closeListeners;
18
+ private _errorListeners;
19
+ get dataListeners(): ((msg: Uint8Array) => void)[];
20
+ get closeListeners(): (() => void)[];
21
+ get errorListeners(): ((err: Error) => void)[];
16
22
  /**
17
23
  * Handle adding a callback for when a message is received.
18
24
  * @param msg The message that was received.
19
25
  */
20
- abstract addDataListener(cb: (msg: Uint8Array) => void): void;
21
- abstract removeDataListener(cb: (msg: Uint8Array) => void): void;
26
+ addDataListener(cb: (msg: Uint8Array) => void): void;
27
+ removeDataListener(cb: (msg: Uint8Array) => void): void;
22
28
  /**
23
29
  * Handle adding a callback for when the connection is closed.
24
- * This should also be called if an error happens.
30
+ * This should also be called if an error happens and after notifying all the error listeners.
25
31
  * @param cb The callback to call when the connection is closed.
26
32
  */
27
- abstract addCloseListener(cb: () => void): void;
33
+ addCloseListener(cb: () => void): void;
34
+ removeCloseListener(cb: () => void): void;
28
35
  /**
29
36
  * Handle adding a callback for when an error is received.
30
37
  * This should only be used for this.logging errors, all cleanup
@@ -36,7 +43,8 @@ declare abstract class Connection {
36
43
  *
37
44
  * @param cb The callback to call when an error is received.
38
45
  */
39
- abstract addErrorListener(cb: (err: Error) => void): void;
46
+ addErrorListener(cb: (err: Error) => void): void;
47
+ removeErrorListener(cb: (err: Error) => void): void;
40
48
  /**
41
49
  * Sends a message over the connection.
42
50
  * @param msg The message to send.
@@ -48,6 +56,93 @@ declare abstract class Connection {
48
56
  */
49
57
  abstract close(): void;
50
58
  }
59
+
60
+ interface SessionNoConnectionListeners {
61
+ onSessionGracePeriodElapsed: () => void;
62
+ }
63
+ declare class SessionNoConnection extends IdentifiedSession {
64
+ readonly state: SessionState.NoConnection;
65
+ listeners: SessionNoConnectionListeners;
66
+ gracePeriodTimeout?: ReturnType<typeof setTimeout>;
67
+ constructor(listeners: SessionNoConnectionListeners, ...args: ConstructorParameters<typeof IdentifiedSession>);
68
+ _handleClose(): void;
69
+ _handleStateExit(): void;
70
+ }
71
+
72
+ interface SessionConnectingListeners {
73
+ onConnectionEstablished: (conn: Connection) => void;
74
+ onConnectionFailed: (err: unknown) => void;
75
+ onConnectionTimeout: () => void;
76
+ }
77
+ declare class SessionConnecting<ConnType extends Connection> extends IdentifiedSession {
78
+ readonly state: SessionState.Connecting;
79
+ connPromise: Promise<ConnType>;
80
+ listeners: SessionConnectingListeners;
81
+ connectionTimeout?: ReturnType<typeof setTimeout>;
82
+ constructor(connPromise: Promise<ConnType>, listeners: SessionConnectingListeners, ...args: ConstructorParameters<typeof IdentifiedSession>);
83
+ bestEffortClose(): void;
84
+ _handleStateExit(): void;
85
+ _handleClose(): void;
86
+ }
87
+
88
+ interface SessionHandshakingListeners {
89
+ onConnectionErrored: (err: unknown) => void;
90
+ onConnectionClosed: () => void;
91
+ onHandshake: (msg: OpaqueTransportMessage) => void;
92
+ onInvalidHandshake: (reason: string) => void;
93
+ onHandshakeTimeout: () => void;
94
+ }
95
+ declare class SessionHandshaking<ConnType extends Connection> extends IdentifiedSession {
96
+ readonly state: SessionState.Handshaking;
97
+ conn: ConnType;
98
+ listeners: SessionHandshakingListeners;
99
+ handshakeTimeout: ReturnType<typeof setTimeout>;
100
+ constructor(conn: ConnType, listeners: SessionHandshakingListeners, ...args: ConstructorParameters<typeof IdentifiedSession>);
101
+ onHandshakeData: (msg: Uint8Array) => void;
102
+ sendHandshake(msg: TransportMessage): boolean;
103
+ _handleStateExit(): void;
104
+ _handleClose(): void;
105
+ }
106
+
107
+ interface SessionConnectedListeners {
108
+ onConnectionErrored: (err: unknown) => void;
109
+ onConnectionClosed: () => void;
110
+ onMessage: (msg: OpaqueTransportMessage) => void;
111
+ onInvalidMessage: (reason: string) => void;
112
+ }
113
+ declare class SessionConnected<ConnType extends Connection> extends IdentifiedSession {
114
+ readonly state: SessionState.Connected;
115
+ conn: ConnType;
116
+ listeners: SessionConnectedListeners;
117
+ heartbeatHandle?: ReturnType<typeof setInterval> | undefined;
118
+ heartbeatMisses: number;
119
+ get isActivelyHeartbeating(): boolean;
120
+ updateBookkeeping(ack: number, seq: number): void;
121
+ send(msg: PartialTransportMessage): string;
122
+ constructor(conn: ConnType, listeners: SessionConnectedListeners, ...args: ConstructorParameters<typeof IdentifiedSession>);
123
+ startActiveHeartbeat(): void;
124
+ private sendHeartbeat;
125
+ onMessageData: (msg: Uint8Array) => void;
126
+ _handleStateExit(): void;
127
+ _handleClose(): void;
128
+ }
129
+
130
+ declare const enum SessionState {
131
+ NoConnection = "NoConnection",
132
+ Connecting = "Connecting",
133
+ Handshaking = "Handshaking",
134
+ Connected = "Connected",
135
+ WaitingForHandshake = "WaitingForHandshake"
136
+ }
137
+ type Session<ConnType extends Connection> = SessionNoConnection | SessionConnecting<ConnType> | SessionHandshaking<ConnType> | SessionConnected<ConnType>;
138
+ declare abstract class StateMachineState {
139
+ abstract readonly state: SessionState;
140
+ _isConsumed: boolean;
141
+ abstract _handleStateExit(): void;
142
+ abstract _handleClose(): void;
143
+ close(): void;
144
+ constructor();
145
+ }
51
146
  interface SessionOptions {
52
147
  /**
53
148
  * Frequency at which to send heartbeat acknowledgements
@@ -63,111 +158,49 @@ interface SessionOptions {
63
158
  */
64
159
  sessionDisconnectGraceMs: number;
65
160
  /**
66
- * Duration to wait for a handshake to complete before considering the connection dead.
161
+ * Connection timeout in milliseconds
67
162
  */
68
- handshakeTimeoutMs?: number;
163
+ connectionTimeoutMs: number;
164
+ /**
165
+ * Handshake timeout in milliseconds
166
+ */
167
+ handshakeTimeoutMs: number;
69
168
  /**
70
169
  * The codec to use for encoding/decoding messages over the wire
71
170
  */
72
171
  codec: Codec;
73
172
  }
74
- /**
75
- * A session is a higher-level abstraction that operates over the span of potentially multiple transport-level connections
76
- * - It’s responsible for tracking any metadata for a particular client that might need to be persisted across connections (i.e. the sendBuffer, ack, seq)
77
- * - This will only be considered disconnected if
78
- * - the server tells the client that we’ve reconnected but it doesn’t recognize us anymore (server definitely died) or
79
- * - we hit a grace period after a connection disconnect
80
- */
81
- declare class Session<ConnType extends Connection> {
82
- private codec;
83
- private options;
84
- readonly telemetry: TelemetryInfo;
85
- /**
86
- * The buffer of messages that have been sent but not yet acknowledged.
87
- */
88
- private sendBuffer;
89
- /**
90
- * The active connection associated with this session
91
- */
92
- connection?: ConnType;
93
- /**
94
- * A connection that is currently undergoing handshaking. Used to distinguish between the active
95
- * connection, but still be able to close it if needed.
96
- */
97
- private handshakingConnection?;
173
+ declare abstract class CommonSession extends StateMachineState {
98
174
  readonly from: TransportClientId;
175
+ readonly options: SessionOptions;
176
+ log?: Logger;
177
+ abstract get loggingMetadata(): MessageMetadata;
178
+ constructor(from: TransportClientId, options: SessionOptions, log: Logger | undefined);
179
+ parseMsg(msg: Uint8Array): OpaqueTransportMessage | null;
180
+ }
181
+ type SessionId = string;
182
+ declare abstract class IdentifiedSession extends CommonSession {
183
+ readonly id: SessionId;
184
+ readonly telemetry: TelemetryInfo;
99
185
  readonly to: TransportClientId;
100
186
  /**
101
- * The unique ID of this session.
102
- */
103
- readonly id: string;
104
- /**
105
- * What the other side advertised as their session ID
106
- * for this session.
107
- */
108
- advertisedSessionId?: string;
109
- /**
110
- * Number of messages we've sent along this session (excluding handshake and acks)
111
- */
112
- private seq;
113
- /**
114
- * Number of unique messages we've received this session (excluding handshake and acks)
115
- */
116
- private ack;
117
- /**
118
- * The grace period between when the inner connection is disconnected
119
- * and when we should consider the entire session disconnected.
187
+ * Index of the message we will send next (excluding handshake)
120
188
  */
121
- private disconnectionGrace?;
189
+ seq: number;
122
190
  /**
123
- * Number of heartbeats we've sent without a response.
191
+ * Number of unique messages we've received this session (excluding handshake)
124
192
  */
125
- private heartbeatMisses;
126
- /**
127
- * The interval for sending heartbeats.
128
- */
129
- private heartbeat;
130
- private log?;
131
- constructor(conn: ConnType | undefined, from: TransportClientId, to: TransportClientId, options: SessionOptions, propagationCtx?: PropagationContext);
132
- bindLogger(log: Logger): void;
193
+ ack: number;
194
+ sendBuffer: Array<OpaqueTransportMessage>;
195
+ constructor(id: SessionId, from: TransportClientId, to: TransportClientId, seq: number, ack: number, sendBuffer: Array<OpaqueTransportMessage>, telemetry: TelemetryInfo, options: SessionOptions, log: Logger | undefined);
133
196
  get loggingMetadata(): MessageMetadata;
134
- /**
135
- * Sends a message over the session's connection.
136
- * If the connection is not ready or the message fails to send, the message can be buffered for retry unless skipped.
137
- *
138
- * @param msg The partial message to be sent, which will be constructed into a full message.
139
- * @param addToSendBuff Whether to add the message to the send buffer for retry.
140
- * @returns The full transport ID of the message that was attempted to be sent.
141
- */
142
- send(msg: PartialTransportMessage): string;
143
- sendHeartbeat(): void;
144
- resetBufferedMessages(): void;
145
- sendBufferedMessages(conn: ConnType): void;
146
- updateBookkeeping(ack: number, seq: number): void;
147
- private closeStaleConnection;
148
- replaceWithNewConnection(newConn: ConnType, isTransparentReconnect: boolean): void;
149
- replaceWithNewHandshakingConnection(newConn: ConnType): void;
150
- beginGrace(cb: () => void): void;
151
- cancelGrace(): void;
152
- /**
153
- * Used to close the handshaking connection, if set.
154
- */
155
- closeHandshakingConnection(expectedHandshakingConn?: ConnType): void;
156
- close(): void;
157
- get connected(): boolean;
158
- get nextExpectedAck(): number;
159
- get nextExpectedSeq(): number;
160
- /**
161
- * Check that the peer's next expected seq number matches something that is in our send buffer
162
- * _or_ matches our actual next seq.
163
- */
164
- nextExpectedSeqInRange(nextExpectedSeq: number): boolean;
165
- advanceAckForTesting(by: number): void;
166
197
  constructMsg<Payload>(partialMsg: PartialTransportMessage<Payload>): TransportMessage<Payload>;
167
- inspectSendBuffer(): ReadonlyArray<OpaqueTransportMessage>;
198
+ nextSeq(): number;
199
+ send(msg: PartialTransportMessage): string;
200
+ _handleStateExit(): void;
201
+ _handleClose(): void;
168
202
  }
169
203
 
170
- type ConnectionStatus = 'connect' | 'disconnect';
171
204
  declare const ProtocolError: {
172
205
  readonly RetriesExceeded: "conn_retry_exceeded";
173
206
  readonly HandshakeFailed: "handshake_failed";
@@ -176,14 +209,19 @@ declare const ProtocolError: {
176
209
  type ProtocolErrorType = (typeof ProtocolError)[keyof typeof ProtocolError];
177
210
  interface EventMap {
178
211
  message: OpaqueTransportMessage;
179
- connectionStatus: {
180
- status: ConnectionStatus;
181
- conn: Connection;
182
- };
183
212
  sessionStatus: {
184
- status: ConnectionStatus;
213
+ status: 'connect' | 'disconnect';
185
214
  session: Session<Connection>;
186
215
  };
216
+ sessionTransition: {
217
+ state: SessionState.Connected;
218
+ } | {
219
+ state: SessionState.Handshaking;
220
+ } | {
221
+ state: SessionState.Connecting;
222
+ } | {
223
+ state: SessionState.NoConnection;
224
+ };
187
225
  protocolError: {
188
226
  type: ProtocolErrorType;
189
227
  message: string;
@@ -269,16 +307,7 @@ type ProvidedServerTransportOptions = Partial<ServerTransportOptions>;
269
307
  */
270
308
  type TransportStatus = 'open' | 'closed';
271
309
  /**
272
- * Transports manage the lifecycle (creation/deletion) of sessions and connections. Its responsibilities include:
273
- *
274
- * 1) Constructing a new {@link Session} and {@link Connection} on {@link TransportMessage}s from new clients.
275
- * After constructing the {@link Connection}, {@link onConnect} is called which adds it to the connection map.
276
- * 2) Delegating message listening of the connection to the newly created {@link Connection}.
277
- * From this point on, the {@link Connection} is responsible for *reading* and *writing*
278
- * messages from the connection.
279
- * 3) When a connection is closed, the {@link Transport} calls {@link onDisconnect} which closes the
280
- * connection via {@link Connection.close} and removes it from the {@link connections} map.
281
-
310
+ * Transports manage the lifecycle (creation/deletion) of sessions
282
311
  *
283
312
  * ```plaintext
284
313
  * ▲
@@ -303,22 +332,10 @@ declare abstract class Transport<ConnType extends Connection> {
303
332
  * The status of the transport.
304
333
  */
305
334
  private status;
306
- /**
307
- * The {@link Codec} used to encode and decode messages.
308
- */
309
- codec: Codec;
310
335
  /**
311
336
  * The client ID of this transport.
312
337
  */
313
338
  clientId: TransportClientId;
314
- /**
315
- * The map of {@link Session}s managed by this transport.
316
- */
317
- sessions: Map<TransportClientId, Session<ConnType>>;
318
- /**
319
- * The map of {@link Connection}s managed by this transport.
320
- */
321
- get connections(): Map<string, ConnType>;
322
339
  /**
323
340
  * The event dispatcher for handling events of type EventTypes.
324
341
  */
@@ -328,75 +345,20 @@ declare abstract class Transport<ConnType extends Connection> {
328
345
  */
329
346
  protected options: TransportOptions;
330
347
  log?: Logger;
348
+ sessions: Map<TransportClientId, Session<ConnType>>;
331
349
  /**
332
350
  * Creates a new Transport instance.
333
- * This should also set up {@link onConnect}, and {@link onDisconnect} listeners.
334
351
  * @param codec The codec used to encode and decode messages.
335
352
  * @param clientId The client ID of this transport.
336
353
  */
337
354
  constructor(clientId: TransportClientId, providedOptions?: ProvidedTransportOptions);
338
355
  bindLogger(fn: LogFn | Logger, level?: LoggingLevel): void;
339
- /**
340
- * This is called immediately after a new connection is established and we
341
- * may or may not know the identity of the connected client.
342
- * It should attach all the necessary listeners to the connection for lifecycle
343
- * events (i.e. data, close, error)
344
- *
345
- * This method is implemented by {@link ClientTransport} and {@link ServerTransport}.
346
- */
347
- protected abstract handleConnection(conn: ConnType, to: TransportClientId): void;
348
- /**
349
- * Called when a new connection is established
350
- * and we know the identity of the connected client.
351
- * @param conn The connection object.
352
- */
353
- protected onConnect(conn: ConnType, session: Session<ConnType>, isTransparentReconnect: boolean): void;
354
- protected createSession(to: TransportClientId, conn?: ConnType, propagationCtx?: PropagationContext): Session<ConnType>;
355
- protected createNewSession({ to, conn, sessionId, propagationCtx, }: {
356
- to: TransportClientId;
357
- conn: ConnType;
358
- sessionId: string;
359
- propagationCtx?: PropagationContext;
360
- }): Session<ConnType>;
361
- protected getExistingSession({ to, sessionId, nextExpectedSeq, }: {
362
- to: TransportClientId;
363
- sessionId: string;
364
- nextExpectedSeq: number;
365
- }): false | Session<ConnType>;
366
- protected getOrCreateSession({ to, conn, handshakingConn, sessionId, propagationCtx, }: {
367
- to: TransportClientId;
368
- conn?: ConnType;
369
- handshakingConn?: ConnType;
370
- sessionId?: string;
371
- propagationCtx?: PropagationContext;
372
- }): {
373
- session: Session<ConnType>;
374
- isReconnect: boolean;
375
- isTransparentReconnect: boolean;
376
- };
377
- protected deleteSession({ session, closeHandshakingConnection, handshakingConn, }: {
378
- session: Session<ConnType>;
379
- closeHandshakingConnection: boolean;
380
- handshakingConn?: ConnType;
381
- }): void;
382
- /**
383
- * The downstream implementation needs to call this when a connection is closed.
384
- * @param conn The connection object.
385
- * @param connectedTo The peer we are connected to.
386
- */
387
- protected onDisconnect(conn: ConnType, session: Session<ConnType>): void;
388
- /**
389
- * Parses a message from a Uint8Array into a {@link OpaqueTransportMessage}.
390
- * @param msg The message to parse.
391
- * @returns The parsed message, or null if the message is malformed or invalid.
392
- */
393
- protected parseMsg(msg: Uint8Array, conn: ConnType): OpaqueTransportMessage | null;
394
356
  /**
395
357
  * Called when a message is received by this transport.
396
358
  * You generally shouldn't need to override this in downstream transport implementations.
397
359
  * @param msg The received message.
398
360
  */
399
- protected handleMsg(msg: OpaqueTransportMessage, conn: ConnType): void;
361
+ protected handleMsg(msg: OpaqueTransportMessage): void;
400
362
  /**
401
363
  * Adds a listener to this transport.
402
364
  * @param the type of event to listen for
@@ -415,8 +377,7 @@ declare abstract class Transport<ConnType extends Connection> {
415
377
  * @param msg The message to send.
416
378
  * @returns The ID of the sent message or undefined if it wasn't sent
417
379
  */
418
- send(to: TransportClientId, msg: PartialTransportMessage): string;
419
- sendCloseStream(to: TransportClientId, streamId: string): string;
380
+ abstract send(to: TransportClientId, msg: PartialTransportMessage): string;
420
381
  protected protocolError(type: ProtocolErrorType, message: string): void;
421
382
  /**
422
383
  * Default close implementation for transports. You should override this in the downstream
@@ -425,6 +386,11 @@ declare abstract class Transport<ConnType extends Connection> {
425
386
  */
426
387
  close(): void;
427
388
  getStatus(): TransportStatus;
389
+ protected updateSession<S extends Session<ConnType>>(session: S): S;
390
+ protected deleteSession(session: Session<ConnType>): void;
391
+ protected onSessionGracePeriodElapsed(session: SessionNoConnection): void;
392
+ protected onConnectingFailed(session: SessionConnecting<ConnType>): SessionNoConnection;
393
+ protected onConnClosed(session: SessionHandshaking<ConnType> | SessionConnected<ConnType>): SessionNoConnection;
428
394
  }
429
395
 
430
396
  /**
@@ -475,10 +441,10 @@ type ServiceContextWithState<State> = ServiceContext & {
475
441
  };
476
442
  type ServiceContextWithTransportInfo<State> = ServiceContext & {
477
443
  state: State;
444
+ sessionId: SessionId;
478
445
  to: TransportClientId;
479
446
  from: TransportClientId;
480
447
  streamId: string;
481
- session: Session<Connection>;
482
448
  metadata: ParsedMetadata;
483
449
  };
484
450
 
@@ -517,4 +483,4 @@ interface ServerHandshakeOptions<MetadataSchema extends TSchema = TSchema> {
517
483
  declare function createClientHandshakeOptions<MetadataSchema extends TSchema = TSchema>(schema: MetadataSchema, construct: ConstructHandshake<MetadataSchema>): ClientHandshakeOptions;
518
484
  declare function createServerHandshakeOptions<MetadataSchema extends TSchema = TSchema>(schema: MetadataSchema, validate: ValidateHandshake<MetadataSchema>): ServerHandshakeOptions;
519
485
 
520
- export { Connection as C, EventMap as E, LeakyBucketRateLimit as L, ProvidedTransportOptions as P, Session as S, Transport as T, TransportStatus as a, ProvidedClientTransportOptions as b, ProvidedServerTransportOptions as c, EventTypes as d, EventHandler as e, ProtocolError as f, ProtocolErrorType as g, SessionOptions as h, ServiceContext as i, ClientTransportOptions as j, ClientHandshakeOptions as k, ServerTransportOptions as l, ServerHandshakeOptions as m, ParsedMetadata as n, ServiceContextWithState as o, ServiceContextWithTransportInfo as p, createClientHandshakeOptions as q, createServerHandshakeOptions as r };
486
+ export { Connection as C, EventMap as E, LeakyBucketRateLimit as L, ProvidedTransportOptions as P, Session as S, Transport as T, TransportStatus as a, ProvidedClientTransportOptions as b, ProvidedServerTransportOptions as c, SessionState as d, SessionNoConnection as e, SessionConnecting as f, SessionHandshaking as g, SessionConnected as h, EventTypes as i, EventHandler as j, ProtocolError as k, ProtocolErrorType as l, SessionOptions as m, ServiceContext as n, ClientTransportOptions as o, ClientHandshakeOptions as p, ServerHandshakeOptions as q, ParsedMetadata as r, ServiceContextWithState as s, ServiceContextWithTransportInfo as t, createClientHandshakeOptions as u, createServerHandshakeOptions as v, CommonSession as w, SessionHandshakingListeners as x, ServerTransportOptions as y };
@@ -1 +1 @@
1
- {"version":3,"sources":["../../logging/index.ts","../../logging/log.ts"],"sourcesContent":["export { stringLogger, coloredStringLogger, jsonLogger } from './log';\nexport type { Logger, LogFn, MessageMetadata } from './log';\n","import { ValueError } from '@sinclair/typebox/value';\nimport { OpaqueTransportMessage } from '../transport/message';\n\nconst LoggingLevels = {\n debug: -1,\n info: 0,\n warn: 1,\n error: 2,\n} as const;\nexport type LoggingLevel = keyof typeof LoggingLevels;\n\nexport type LogFn = (\n msg: string,\n ctx?: MessageMetadata,\n level?: LoggingLevel,\n) => void;\nexport type Logger = {\n [key in LoggingLevel]: (msg: string, metadata?: MessageMetadata) => void;\n};\n\nexport type Tags = 'invariant-violation';\n\nconst cleanedLogFn = (log: LogFn) => {\n return (msg: string, metadata?: MessageMetadata) => {\n // skip cloning object if metadata has no transportMessage\n if (!metadata?.transportMessage) {\n log(msg, metadata);\n return;\n }\n\n // clone metadata and clean transportMessage\n const { payload, ...rest } = metadata.transportMessage;\n metadata.transportMessage = rest;\n log(msg, metadata);\n };\n};\n\nexport type MessageMetadata = Partial<{\n protocolVersion: string;\n clientId: string;\n connectedTo: string;\n sessionId: string;\n connId: string;\n transportMessage: Partial<OpaqueTransportMessage>;\n validationErrors: Array<ValueError>;\n tags: Array<Tags>;\n telemetry: {\n traceId: string;\n spanId: string;\n };\n}>;\n\nexport class BaseLogger implements Logger {\n minLevel: LoggingLevel;\n private output: LogFn;\n\n constructor(output: LogFn, minLevel: LoggingLevel = 'info') {\n this.minLevel = minLevel;\n this.output = output;\n }\n\n debug(msg: string, metadata?: MessageMetadata) {\n if (LoggingLevels[this.minLevel] <= LoggingLevels.debug) {\n this.output(msg, metadata ?? {}, 'debug');\n }\n }\n\n info(msg: string, metadata?: MessageMetadata) {\n if (LoggingLevels[this.minLevel] <= LoggingLevels.info) {\n this.output(msg, metadata ?? {}, 'info');\n }\n }\n\n warn(msg: string, metadata?: MessageMetadata) {\n if (LoggingLevels[this.minLevel] <= LoggingLevels.warn) {\n this.output(msg, metadata ?? {}, 'warn');\n }\n }\n\n error(msg: string, metadata?: MessageMetadata) {\n if (LoggingLevels[this.minLevel] <= LoggingLevels.error) {\n this.output(msg, metadata ?? {}, 'error');\n }\n }\n}\n\nexport const stringLogger: LogFn = (msg, ctx, level = 'info') => {\n const from = ctx?.clientId ? `${ctx.clientId} -- ` : '';\n console.log(`[river:${level}] ${from}${msg}`);\n};\n\nconst colorMap = {\n debug: '\\u001b[34m',\n info: '\\u001b[32m',\n warn: '\\u001b[33m',\n error: '\\u001b[31m',\n};\n\nexport const coloredStringLogger: LogFn = (msg, ctx, level = 'info') => {\n const color = colorMap[level];\n const from = ctx?.clientId ? `${ctx.clientId} -- ` : '';\n console.log(`[river:${color}${level}\\u001b[0m] ${from}${msg}`);\n};\n\nexport const jsonLogger: LogFn = (msg, ctx, level) => {\n console.log(JSON.stringify({ msg, ctx, level }));\n};\n\nexport const createLogProxy = (log: Logger) => ({\n debug: cleanedLogFn(log.debug.bind(log)),\n info: cleanedLogFn(log.info.bind(log)),\n warn: cleanedLogFn(log.warn.bind(log)),\n error: cleanedLogFn(log.error.bind(log)),\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACsFO,IAAM,eAAsB,CAAC,KAAK,KAAK,QAAQ,WAAW;AAC/D,QAAM,OAAO,KAAK,WAAW,GAAG,IAAI,QAAQ,SAAS;AACrD,UAAQ,IAAI,UAAU,KAAK,KAAK,IAAI,GAAG,GAAG,EAAE;AAC9C;AAEA,IAAM,WAAW;AAAA,EACf,OAAO;AAAA,EACP,MAAM;AAAA,EACN,MAAM;AAAA,EACN,OAAO;AACT;AAEO,IAAM,sBAA6B,CAAC,KAAK,KAAK,QAAQ,WAAW;AACtE,QAAM,QAAQ,SAAS,KAAK;AAC5B,QAAM,OAAO,KAAK,WAAW,GAAG,IAAI,QAAQ,SAAS;AACrD,UAAQ,IAAI,UAAU,KAAK,GAAG,KAAK,YAAc,IAAI,GAAG,GAAG,EAAE;AAC/D;AAEO,IAAM,aAAoB,CAAC,KAAK,KAAK,UAAU;AACpD,UAAQ,IAAI,KAAK,UAAU,EAAE,KAAK,KAAK,MAAM,CAAC,CAAC;AACjD;","names":[]}
1
+ {"version":3,"sources":["../../logging/index.ts","../../logging/log.ts"],"sourcesContent":["export { stringLogger, coloredStringLogger, jsonLogger } from './log';\nexport type { Logger, LogFn, MessageMetadata } from './log';\n","import { ValueError } from '@sinclair/typebox/value';\nimport { OpaqueTransportMessage } from '../transport/message';\n\nconst LoggingLevels = {\n debug: -1,\n info: 0,\n warn: 1,\n error: 2,\n} as const;\nexport type LoggingLevel = keyof typeof LoggingLevels;\n\nexport type LogFn = (\n msg: string,\n ctx?: MessageMetadata,\n level?: LoggingLevel,\n) => void;\nexport type Logger = {\n [key in LoggingLevel]: (msg: string, metadata?: MessageMetadata) => void;\n};\n\nexport type Tags = 'invariant-violation' | 'state-transition';\n\nconst cleanedLogFn = (log: LogFn) => {\n return (msg: string, metadata?: MessageMetadata) => {\n // skip cloning object if metadata has no transportMessage\n if (!metadata?.transportMessage) {\n log(msg, metadata);\n return;\n }\n\n // clone metadata and clean transportMessage\n const { payload, ...rest } = metadata.transportMessage;\n metadata.transportMessage = rest;\n log(msg, metadata);\n };\n};\n\nexport type MessageMetadata = Partial<{\n protocolVersion: string;\n clientId: string;\n connectedTo: string;\n sessionId: string;\n connId: string;\n transportMessage: Partial<OpaqueTransportMessage>;\n validationErrors: Array<ValueError>;\n tags: Array<Tags>;\n telemetry: {\n traceId: string;\n spanId: string;\n };\n}>;\n\nexport class BaseLogger implements Logger {\n minLevel: LoggingLevel;\n private output: LogFn;\n\n constructor(output: LogFn, minLevel: LoggingLevel = 'info') {\n this.minLevel = minLevel;\n this.output = output;\n }\n\n debug(msg: string, metadata?: MessageMetadata) {\n if (LoggingLevels[this.minLevel] <= LoggingLevels.debug) {\n this.output(msg, metadata ?? {}, 'debug');\n }\n }\n\n info(msg: string, metadata?: MessageMetadata) {\n if (LoggingLevels[this.minLevel] <= LoggingLevels.info) {\n this.output(msg, metadata ?? {}, 'info');\n }\n }\n\n warn(msg: string, metadata?: MessageMetadata) {\n if (LoggingLevels[this.minLevel] <= LoggingLevels.warn) {\n this.output(msg, metadata ?? {}, 'warn');\n }\n }\n\n error(msg: string, metadata?: MessageMetadata) {\n if (LoggingLevels[this.minLevel] <= LoggingLevels.error) {\n this.output(msg, metadata ?? {}, 'error');\n }\n }\n}\n\nexport const stringLogger: LogFn = (msg, ctx, level = 'info') => {\n const from = ctx?.clientId ? `${ctx.clientId} -- ` : '';\n console.log(`[river:${level}] ${from}${msg}`);\n};\n\nconst colorMap = {\n debug: '\\u001b[34m',\n info: '\\u001b[32m',\n warn: '\\u001b[33m',\n error: '\\u001b[31m',\n};\n\nexport const coloredStringLogger: LogFn = (msg, ctx, level = 'info') => {\n const color = colorMap[level];\n const from = ctx?.clientId ? `${ctx.clientId} -- ` : '';\n console.log(`[river:${color}${level}\\u001b[0m] ${from}${msg}`);\n};\n\nexport const jsonLogger: LogFn = (msg, ctx, level) => {\n console.log(JSON.stringify({ msg, ctx, level }));\n};\n\nexport const createLogProxy = (log: Logger) => ({\n debug: cleanedLogFn(log.debug.bind(log)),\n info: cleanedLogFn(log.info.bind(log)),\n warn: cleanedLogFn(log.warn.bind(log)),\n error: cleanedLogFn(log.error.bind(log)),\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACsFO,IAAM,eAAsB,CAAC,KAAK,KAAK,QAAQ,WAAW;AAC/D,QAAM,OAAO,KAAK,WAAW,GAAG,IAAI,QAAQ,SAAS;AACrD,UAAQ,IAAI,UAAU,KAAK,KAAK,IAAI,GAAG,GAAG,EAAE;AAC9C;AAEA,IAAM,WAAW;AAAA,EACf,OAAO;AAAA,EACP,MAAM;AAAA,EACN,MAAM;AAAA,EACN,OAAO;AACT;AAEO,IAAM,sBAA6B,CAAC,KAAK,KAAK,QAAQ,WAAW;AACtE,QAAM,QAAQ,SAAS,KAAK;AAC5B,QAAM,OAAO,KAAK,WAAW,GAAG,IAAI,QAAQ,SAAS;AACrD,UAAQ,IAAI,UAAU,KAAK,GAAG,KAAK,YAAc,IAAI,GAAG,GAAG,EAAE;AAC/D;AAEO,IAAM,aAAoB,CAAC,KAAK,KAAK,UAAU;AACpD,UAAQ,IAAI,KAAK,UAAU,EAAE,KAAK,KAAK,MAAM,CAAC,CAAC;AACjD;","names":[]}
@@ -1,4 +1,4 @@
1
- export { g as LogFn, L as Logger, M as MessageMetadata, j as coloredStringLogger, k as jsonLogger, s as stringLogger } from '../index-ea74cdbb.js';
1
+ export { f as LogFn, L as Logger, M as MessageMetadata, h as coloredStringLogger, j as jsonLogger, s as stringLogger } from '../message-e6c560fd.js';
2
2
  import '@sinclair/typebox/value';
3
3
  import '@sinclair/typebox';
4
4
  import '@opentelemetry/api';
@@ -1,4 +1,4 @@
1
- export { g as LogFn, L as Logger, M as MessageMetadata, j as coloredStringLogger, k as jsonLogger, s as stringLogger } from '../index-ea74cdbb.js';
1
+ export { f as LogFn, L as Logger, M as MessageMetadata, h as coloredStringLogger, j as jsonLogger, s as stringLogger } from '../message-e6c560fd.js';
2
2
  import '@sinclair/typebox/value';
3
3
  import '@sinclair/typebox';
4
4
  import '@opentelemetry/api';
@@ -2,7 +2,7 @@ import {
2
2
  coloredStringLogger,
3
3
  jsonLogger,
4
4
  stringLogger
5
- } from "../chunk-6LCL2ZZF.js";
5
+ } from "../chunk-TAH2GVTJ.js";
6
6
  export {
7
7
  coloredStringLogger,
8
8
  jsonLogger,
@@ -14,7 +14,7 @@ type LogFn = (msg: string, ctx?: MessageMetadata, level?: LoggingLevel) => void;
14
14
  type Logger = {
15
15
  [key in LoggingLevel]: (msg: string, metadata?: MessageMetadata) => void;
16
16
  };
17
- type Tags = 'invariant-violation';
17
+ type Tags = 'invariant-violation' | 'state-transition';
18
18
  type MessageMetadata = Partial<{
19
19
  protocolVersion: string;
20
20
  clientId: string;
@@ -133,4 +133,4 @@ declare function isStreamOpen(controlFlag: number): boolean;
133
133
  */
134
134
  declare function isStreamClose(controlFlag: number): boolean;
135
135
 
136
- export { Logger as L, MessageMetadata as M, OpaqueTransportMessageSchema as O, PartialTransportMessage as P, TransportMessageSchema as T, TransportMessage as a, OpaqueTransportMessage as b, TransportClientId as c, isStreamClose as d, TelemetryInfo as e, PropagationContext as f, LogFn as g, LoggingLevel as h, isStreamOpen as i, coloredStringLogger as j, jsonLogger as k, stringLogger as s };
136
+ export { Logger as L, MessageMetadata as M, OpaqueTransportMessageSchema as O, PartialTransportMessage as P, TransportMessageSchema as T, TransportMessage as a, OpaqueTransportMessage as b, TransportClientId as c, isStreamClose as d, TelemetryInfo as e, LogFn as f, LoggingLevel as g, coloredStringLogger as h, isStreamOpen as i, jsonLogger as j, stringLogger as s };