@replit/river 0.11.0 → 0.12.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 (82) hide show
  1. package/README.md +28 -8
  2. package/dist/{builder-1f26296b.d.ts → builder-c593de11.d.ts} +14 -13
  3. package/dist/{chunk-3JGVFWKQ.js → chunk-55XUAPC6.js} +205 -180
  4. package/dist/{chunk-R6H2BIMC.js → chunk-GZ7HCLLM.js} +31 -7
  5. package/dist/{chunk-T7M7OKPE.js → chunk-H4BYJELI.js} +5 -1
  6. package/dist/{chunk-GKPT5YQE.js → chunk-IIBVKYDB.js} +6 -34
  7. package/dist/chunk-M6LY25P2.js +47 -0
  8. package/dist/chunk-QEYN2Z6O.js +726 -0
  9. package/dist/chunk-RDTTKCGV.js +40 -0
  10. package/dist/chunk-TKINU53F.js +44 -0
  11. package/dist/chunk-XFFS4UOD.js +127 -0
  12. package/dist/codec/index.cjs +13 -7
  13. package/dist/codec/index.js +2 -4
  14. package/dist/connection-bf7811aa.d.ts +17 -0
  15. package/dist/connection-d880aa4a.d.ts +18 -0
  16. package/dist/connection-eb10d250.d.ts +15 -0
  17. package/dist/index-0c0a69f6.d.ts +440 -0
  18. package/dist/logging/index.cjs +8 -3
  19. package/dist/logging/index.d.cts +6 -1
  20. package/dist/logging/index.d.ts +6 -1
  21. package/dist/logging/index.js +5 -3
  22. package/dist/messageFraming-b200ef25.d.ts +20 -0
  23. package/dist/router/index.cjs +250 -211
  24. package/dist/router/index.d.cts +6 -7
  25. package/dist/router/index.d.ts +6 -7
  26. package/dist/router/index.js +3 -3
  27. package/dist/transport/impls/stdio/client.cjs +909 -0
  28. package/dist/transport/impls/stdio/client.d.cts +27 -0
  29. package/dist/transport/impls/stdio/client.d.ts +27 -0
  30. package/dist/transport/impls/stdio/client.js +42 -0
  31. package/dist/transport/impls/stdio/server.cjs +883 -0
  32. package/dist/transport/impls/stdio/server.d.cts +25 -0
  33. package/dist/transport/impls/stdio/server.d.ts +25 -0
  34. package/dist/transport/impls/stdio/server.js +33 -0
  35. package/dist/transport/impls/uds/client.cjs +911 -0
  36. package/dist/transport/impls/uds/client.d.cts +16 -0
  37. package/dist/transport/impls/uds/client.d.ts +16 -0
  38. package/dist/transport/impls/uds/client.js +44 -0
  39. package/dist/transport/impls/uds/server.cjs +885 -0
  40. package/dist/transport/impls/uds/server.d.cts +16 -0
  41. package/dist/transport/impls/uds/server.d.ts +16 -0
  42. package/dist/transport/impls/uds/server.js +39 -0
  43. package/dist/transport/impls/ws/client.cjs +612 -249
  44. package/dist/transport/impls/ws/client.d.cts +6 -21
  45. package/dist/transport/impls/ws/client.d.ts +6 -21
  46. package/dist/transport/impls/ws/client.js +83 -7
  47. package/dist/transport/impls/ws/server.cjs +565 -196
  48. package/dist/transport/impls/ws/server.d.cts +6 -10
  49. package/dist/transport/impls/ws/server.d.ts +6 -10
  50. package/dist/transport/impls/ws/server.js +31 -8
  51. package/dist/transport/index.cjs +673 -130
  52. package/dist/transport/index.d.cts +3 -276
  53. package/dist/transport/index.d.ts +3 -276
  54. package/dist/transport/index.js +13 -10
  55. package/dist/util/testHelpers.cjs +40 -602
  56. package/dist/util/testHelpers.d.cts +18 -37
  57. package/dist/util/testHelpers.d.ts +18 -37
  58. package/dist/util/testHelpers.js +27 -47
  59. package/package.json +29 -14
  60. package/dist/chunk-5IC5XMWK.js +0 -140
  61. package/dist/chunk-L7D75G4K.js +0 -29
  62. package/dist/chunk-LQXPKF3A.js +0 -282
  63. package/dist/chunk-PJ2EUO7O.js +0 -63
  64. package/dist/chunk-WVT5QXMZ.js +0 -20
  65. package/dist/chunk-ZE4MX7DF.js +0 -75
  66. package/dist/connection-2529fc14.d.ts +0 -10
  67. package/dist/connection-316d6e3a.d.ts +0 -10
  68. package/dist/connection-8e19874c.d.ts +0 -11
  69. package/dist/connection-f7688cc1.d.ts +0 -11
  70. package/dist/transport/impls/stdio/stdio.cjs +0 -518
  71. package/dist/transport/impls/stdio/stdio.d.cts +0 -26
  72. package/dist/transport/impls/stdio/stdio.d.ts +0 -26
  73. package/dist/transport/impls/stdio/stdio.js +0 -70
  74. package/dist/transport/impls/unixsocket/client.cjs +0 -516
  75. package/dist/transport/impls/unixsocket/client.d.cts +0 -16
  76. package/dist/transport/impls/unixsocket/client.d.ts +0 -16
  77. package/dist/transport/impls/unixsocket/client.js +0 -67
  78. package/dist/transport/impls/unixsocket/server.cjs +0 -520
  79. package/dist/transport/impls/unixsocket/server.d.cts +0 -18
  80. package/dist/transport/impls/unixsocket/server.d.ts +0 -18
  81. package/dist/transport/impls/unixsocket/server.js +0 -73
  82. /package/dist/{chunk-ORAG7IAU.js → chunk-5IZ2UHWV.js} +0 -0
@@ -0,0 +1,726 @@
1
+ import {
2
+ NaiveJsonCodec
3
+ } from "./chunk-GZ7HCLLM.js";
4
+ import {
5
+ ControlMessageHandshakeRequestSchema,
6
+ ControlMessageHandshakeResponseSchema,
7
+ OpaqueTransportMessageSchema,
8
+ PROTOCOL_VERSION,
9
+ bootRequestMessage,
10
+ bootResponseMessage,
11
+ coerceErrorString,
12
+ isAck
13
+ } from "./chunk-XFFS4UOD.js";
14
+ import {
15
+ log
16
+ } from "./chunk-H4BYJELI.js";
17
+
18
+ // transport/events.ts
19
+ var EventDispatcher = class {
20
+ eventListeners = {};
21
+ numberOfListeners(eventType) {
22
+ return this.eventListeners[eventType]?.size ?? 0;
23
+ }
24
+ addEventListener(eventType, handler) {
25
+ if (!this.eventListeners[eventType]) {
26
+ this.eventListeners[eventType] = /* @__PURE__ */ new Set();
27
+ }
28
+ this.eventListeners[eventType]?.add(handler);
29
+ }
30
+ removeEventListener(eventType, handler) {
31
+ const handlers = this.eventListeners[eventType];
32
+ if (handlers) {
33
+ this.eventListeners[eventType]?.delete(handler);
34
+ }
35
+ }
36
+ dispatchEvent(eventType, event) {
37
+ const handlers = this.eventListeners[eventType];
38
+ if (handlers) {
39
+ for (const handler of handlers) {
40
+ handler(event);
41
+ }
42
+ }
43
+ }
44
+ };
45
+
46
+ // transport/session.ts
47
+ import { customAlphabet } from "nanoid";
48
+ var nanoid = customAlphabet("1234567890abcdefghijklmnopqrstuvxyz", 6);
49
+ var unsafeId = () => nanoid();
50
+ var Connection = class {
51
+ debugId;
52
+ constructor() {
53
+ this.debugId = `conn-${unsafeId()}`;
54
+ }
55
+ };
56
+ var HEARTBEAT_INTERVAL_MS = 1e3;
57
+ var HEARTBEATS_TILL_DEAD = 2;
58
+ var SESSION_DISCONNECT_GRACE_MS = 5e3;
59
+ var Session = class {
60
+ codec;
61
+ /**
62
+ * The buffer of messages that have been sent but not yet acknowledged.
63
+ */
64
+ sendBuffer = [];
65
+ /**
66
+ * The active connection associated with this session
67
+ */
68
+ connection;
69
+ from;
70
+ to;
71
+ /**
72
+ * The unique ID of this session.
73
+ */
74
+ debugId;
75
+ /**
76
+ * Number of messages we've sent along this session (excluding handshake)
77
+ */
78
+ seq = 0;
79
+ /**
80
+ * Number of unique messages we've received this session (excluding handshake)
81
+ */
82
+ ack = 0;
83
+ /**
84
+ * The grace period between when the inner connection is disconnected
85
+ * and when we should consider the entire session disconnected.
86
+ */
87
+ disconnectionGrace;
88
+ /**
89
+ * Number of heartbeats we've sent without a response.
90
+ */
91
+ heartbeatMisses;
92
+ /**
93
+ * The interval for sending heartbeats.
94
+ */
95
+ heartbeat;
96
+ constructor(codec, from, connectedTo, conn) {
97
+ this.debugId = `sess-${unsafeId()}`;
98
+ this.from = from;
99
+ this.to = connectedTo;
100
+ this.connection = conn;
101
+ this.codec = codec;
102
+ this.heartbeatMisses = 0;
103
+ this.heartbeat = setInterval(
104
+ () => this.sendHeartbeat(),
105
+ HEARTBEAT_INTERVAL_MS
106
+ );
107
+ }
108
+ /**
109
+ * Sends a message over the session's connection.
110
+ * If the connection is not ready or the message fails to send, the message can be buffered for retry unless skipped.
111
+ *
112
+ * @param msg The partial message to be sent, which will be constructed into a full message.
113
+ * @param skipRetry Optional. If true, the message will not be buffered for retry on failure. This should only be used for
114
+ * ack hearbeats, which contain information that can already be found in the other buffered messages.
115
+ * @returns The full transport ID of the message that was attempted to be sent.
116
+ */
117
+ send(msg, skipRetry) {
118
+ const fullMsg = this.constructMsg(msg);
119
+ log?.debug(`${this.from} -- sending ${JSON.stringify(fullMsg)}`);
120
+ if (this.connection) {
121
+ const ok = this.connection.send(this.codec.toBuffer(fullMsg));
122
+ if (ok)
123
+ return fullMsg.id;
124
+ log?.info(
125
+ `${this.from} -- failed to send ${fullMsg.id} to ${fullMsg.to}, connection (id: ${this.connection.debugId}) is probably dead`
126
+ );
127
+ } else {
128
+ log?.info(
129
+ `${this.from} -- failed to send ${fullMsg.id} to ${fullMsg.to}, connection not ready yet`
130
+ );
131
+ }
132
+ if (skipRetry)
133
+ return fullMsg.id;
134
+ this.addToSendBuff(fullMsg);
135
+ log?.info(
136
+ `${this.from} -- buffering msg ${fullMsg.id} until connection is healthy again`
137
+ );
138
+ return fullMsg.id;
139
+ }
140
+ sendHeartbeat() {
141
+ if (this.heartbeatMisses >= HEARTBEATS_TILL_DEAD) {
142
+ if (this.connection) {
143
+ log?.info(
144
+ `${this.from} -- closing connection (id: ${this.connection.debugId}) to ${this.to} due to inactivity`
145
+ );
146
+ this.halfCloseConnection();
147
+ }
148
+ return;
149
+ }
150
+ this.send(
151
+ {
152
+ streamId: "heartbeat",
153
+ controlFlags: 1 /* AckBit */,
154
+ payload: {
155
+ type: "ACK"
156
+ }
157
+ },
158
+ true
159
+ );
160
+ this.heartbeatMisses++;
161
+ }
162
+ resetBufferedMessages() {
163
+ this.sendBuffer = [];
164
+ this.seq = 0;
165
+ this.ack = 0;
166
+ }
167
+ sendBufferedMessages() {
168
+ if (!this.connection) {
169
+ const msg = `${this.from} -- tried sending buffered messages without a connection (if you hit this code path something is seriously wrong)`;
170
+ log?.error(msg);
171
+ throw new Error(msg);
172
+ }
173
+ for (const msg of this.sendBuffer) {
174
+ log?.debug(`${this.from} -- resending ${JSON.stringify(msg)}`);
175
+ const ok = this.connection.send(this.codec.toBuffer(msg));
176
+ if (!ok) {
177
+ const msg2 = `${this.from} -- failed to send buffered message to ${this.to} in session (id: ${this.debugId}) (if you hit this code path something is seriously wrong)`;
178
+ log?.error(msg2);
179
+ throw new Error(msg2);
180
+ }
181
+ }
182
+ }
183
+ updateBookkeeping(ack, seq) {
184
+ this.sendBuffer = this.sendBuffer.filter((unacked) => unacked.seq > ack);
185
+ this.ack = seq + 1;
186
+ }
187
+ addToSendBuff(msg) {
188
+ this.sendBuffer.push(msg);
189
+ log?.debug(
190
+ `${this.from} -- send buff to ${this.to} now tracking ${this.sendBuffer.length} messages`
191
+ );
192
+ }
193
+ closeStaleConnection(conn) {
194
+ if (!this.connection || this.connection !== conn)
195
+ return;
196
+ log?.info(
197
+ `${this.from} -- closing old inner connection (id: ${this.connection.debugId}) from session (id: ${this.debugId}) to ${this.to}`
198
+ );
199
+ this.connection.close();
200
+ this.connection = void 0;
201
+ }
202
+ replaceWithNewConnection(newConn) {
203
+ this.closeStaleConnection(this.connection);
204
+ this.cancelGrace();
205
+ this.connection = newConn;
206
+ }
207
+ beginGrace(cb) {
208
+ this.disconnectionGrace = setTimeout(() => {
209
+ this.resetBufferedMessages();
210
+ clearInterval(this.heartbeat);
211
+ cb();
212
+ }, SESSION_DISCONNECT_GRACE_MS);
213
+ }
214
+ cancelGrace() {
215
+ this.heartbeatMisses = 0;
216
+ clearTimeout(this.disconnectionGrace);
217
+ }
218
+ get connected() {
219
+ return this.connection !== void 0;
220
+ }
221
+ get nextExpectedSeq() {
222
+ return this.ack;
223
+ }
224
+ constructMsg(partialMsg) {
225
+ const msg = {
226
+ ...partialMsg,
227
+ id: unsafeId(),
228
+ to: this.to,
229
+ from: this.from,
230
+ seq: this.seq,
231
+ ack: this.ack
232
+ };
233
+ this.seq++;
234
+ return msg;
235
+ }
236
+ /**
237
+ * Closes the out-going connection but doesn't remove the listeners
238
+ * for incoming messages. The connection will eventually call onClose
239
+ * when it is ready to be cleaned up and only then will {@link connection} be set back
240
+ * to undefined
241
+ */
242
+ halfCloseConnection() {
243
+ this.connection?.close();
244
+ }
245
+ inspectSendBuffer() {
246
+ return this.sendBuffer;
247
+ }
248
+ };
249
+
250
+ // transport/transport.ts
251
+ import { Value } from "@sinclair/typebox/value";
252
+ import { nanoid as nanoid2 } from "nanoid";
253
+ var DEFAULT_RECONNECT_JITTER_MAX_MS = 500;
254
+ var DEFAULT_RECONNECT_INTERVAL_MS = 250;
255
+ var defaultTransportOptions = {
256
+ retryIntervalMs: DEFAULT_RECONNECT_INTERVAL_MS,
257
+ retryJitterMs: DEFAULT_RECONNECT_JITTER_MAX_MS,
258
+ retryAttemptsMax: 5,
259
+ codec: NaiveJsonCodec
260
+ };
261
+ var Transport = class {
262
+ /**
263
+ * Unique per instance of the transport.
264
+ * This allows us to distinguish reconnects to different
265
+ * transports.
266
+ */
267
+ instanceId = nanoid2();
268
+ connectedInstanceIds = /* @__PURE__ */ new Map();
269
+ /**
270
+ * A flag indicating whether the transport has been destroyed.
271
+ * A destroyed transport will not attempt to reconnect and cannot be used again.
272
+ */
273
+ state;
274
+ /**
275
+ * The {@link Codec} used to encode and decode messages.
276
+ */
277
+ codec;
278
+ /**
279
+ * The client ID of this transport.
280
+ */
281
+ clientId;
282
+ /**
283
+ * The map of {@link Session}s managed by this transport.
284
+ */
285
+ sessions;
286
+ /**
287
+ * The map of {@link Connection}s managed by this transport.
288
+ */
289
+ get connections() {
290
+ return new Map(
291
+ [...this.sessions].map(([client, session]) => [client, session.connection]).filter((entry) => entry[1] !== void 0)
292
+ );
293
+ }
294
+ /**
295
+ * The event dispatcher for handling events of type EventTypes.
296
+ */
297
+ eventDispatcher;
298
+ /**
299
+ * The options for this transport.
300
+ */
301
+ options;
302
+ /**
303
+ * Creates a new Transport instance.
304
+ * This should also set up {@link onConnect}, and {@link onDisconnect} listeners.
305
+ * @param codec The codec used to encode and decode messages.
306
+ * @param clientId The client ID of this transport.
307
+ */
308
+ constructor(clientId, providedOptions) {
309
+ this.options = { ...defaultTransportOptions, ...providedOptions };
310
+ this.eventDispatcher = new EventDispatcher();
311
+ this.sessions = /* @__PURE__ */ new Map();
312
+ this.codec = this.options.codec;
313
+ this.clientId = clientId;
314
+ this.state = "open";
315
+ }
316
+ sessionByClientId(clientId) {
317
+ const session = this.sessions.get(clientId);
318
+ if (!session) {
319
+ const err = `${this.clientId} -- (invariant violation) no existing session for ${clientId}`;
320
+ log?.error(err);
321
+ throw new Error(err);
322
+ }
323
+ return session;
324
+ }
325
+ /**
326
+ * Called when a new connection is established
327
+ * and we know the identity of the connected client.
328
+ * @param conn The connection object.
329
+ */
330
+ onConnect(conn, connectedTo, instanceId) {
331
+ this.eventDispatcher.dispatchEvent("connectionStatus", {
332
+ status: "connect",
333
+ conn
334
+ });
335
+ let session = this.sessions.get(connectedTo);
336
+ const lastInstanceId = this.connectedInstanceIds.get(connectedTo);
337
+ if (session && lastInstanceId !== instanceId && lastInstanceId !== void 0) {
338
+ log?.debug(
339
+ `${this.clientId} -- handshake from ${connectedTo} has different server instance (got: ${instanceId}, last connected to: ${lastInstanceId}), starting a new session`
340
+ );
341
+ session.resetBufferedMessages();
342
+ session.closeStaleConnection();
343
+ this.deleteSession(session);
344
+ session = void 0;
345
+ }
346
+ this.connectedInstanceIds.set(connectedTo, instanceId);
347
+ if (session === void 0) {
348
+ const newSession = this.createSession(connectedTo, conn);
349
+ log?.info(
350
+ `${this.clientId} -- new connection (id: ${conn.debugId}) for new session (id: ${newSession.debugId}) to ${connectedTo}`
351
+ );
352
+ return newSession;
353
+ }
354
+ log?.info(
355
+ `${this.clientId} -- new connection (id: ${conn.debugId}) for existing session (id: ${session.debugId}) to ${connectedTo}`
356
+ );
357
+ session.replaceWithNewConnection(conn);
358
+ session.sendBufferedMessages();
359
+ return session;
360
+ }
361
+ createSession(connectedTo, conn) {
362
+ const session = new Session(
363
+ this.codec,
364
+ this.clientId,
365
+ connectedTo,
366
+ conn
367
+ );
368
+ this.sessions.set(session.to, session);
369
+ this.eventDispatcher.dispatchEvent("sessionStatus", {
370
+ status: "connect",
371
+ session
372
+ });
373
+ return session;
374
+ }
375
+ deleteSession(session) {
376
+ this.sessions.delete(session.to);
377
+ this.eventDispatcher.dispatchEvent("sessionStatus", {
378
+ status: "disconnect",
379
+ session
380
+ });
381
+ log?.info(
382
+ `${this.clientId} -- session ${session.debugId} disconnect from ${session.to}`
383
+ );
384
+ }
385
+ /**
386
+ * The downstream implementation needs to call this when a connection is closed.
387
+ * @param conn The connection object.
388
+ */
389
+ onDisconnect(conn, connectedTo) {
390
+ this.eventDispatcher.dispatchEvent("connectionStatus", {
391
+ status: "disconnect",
392
+ conn
393
+ });
394
+ if (!connectedTo)
395
+ return;
396
+ const session = this.sessionByClientId(connectedTo);
397
+ log?.info(
398
+ `${this.clientId} -- connection (id: ${conn.debugId}) disconnect from ${connectedTo}, ${SESSION_DISCONNECT_GRACE_MS}ms until session (id: ${session.debugId}) disconnect`
399
+ );
400
+ session.closeStaleConnection(conn);
401
+ session.beginGrace(() => this.deleteSession(session));
402
+ }
403
+ /**
404
+ * Parses a message from a Uint8Array into a {@link OpaqueTransportMessage}.
405
+ * @param msg The message to parse.
406
+ * @returns The parsed message, or null if the message is malformed or invalid.
407
+ */
408
+ parseMsg(msg) {
409
+ const parsedMsg = this.codec.fromBuffer(msg);
410
+ if (parsedMsg === null) {
411
+ const decodedBuffer = new TextDecoder().decode(msg);
412
+ log?.error(
413
+ `${this.clientId} -- received malformed msg, killing conn: ${decodedBuffer}`
414
+ );
415
+ return null;
416
+ }
417
+ if (!Value.Check(OpaqueTransportMessageSchema, parsedMsg)) {
418
+ log?.error(
419
+ `${this.clientId} -- received invalid msg: ${JSON.stringify(
420
+ parsedMsg
421
+ )}`
422
+ );
423
+ return null;
424
+ }
425
+ return {
426
+ ...parsedMsg,
427
+ serviceName: parsedMsg.serviceName === null ? void 0 : parsedMsg.serviceName,
428
+ procedureName: parsedMsg.procedureName === null ? void 0 : parsedMsg.procedureName
429
+ };
430
+ }
431
+ /**
432
+ * Called when a message is received by this transport.
433
+ * You generally shouldn't need to override this in downstream transport implementations.
434
+ * @param msg The received message.
435
+ */
436
+ handleMsg(msg) {
437
+ const session = this.sessionByClientId(msg.from);
438
+ session.cancelGrace();
439
+ log?.debug(`${this.clientId} -- received msg: ${JSON.stringify(msg)}`);
440
+ if (msg.seq !== session.nextExpectedSeq) {
441
+ log?.warn(
442
+ `${this.clientId} -- received out-of-order msg (got: ${msg.seq}, wanted: ${session.nextExpectedSeq}), discarding: ${JSON.stringify(
443
+ msg
444
+ )}`
445
+ );
446
+ return;
447
+ }
448
+ if (!isAck(msg.controlFlags)) {
449
+ this.eventDispatcher.dispatchEvent("message", msg);
450
+ }
451
+ session.updateBookkeeping(msg.ack, msg.seq);
452
+ }
453
+ /**
454
+ * Adds a listener to this transport.
455
+ * @param the type of event to listen for
456
+ * @param handler The message handler to add.
457
+ */
458
+ addEventListener(type, handler) {
459
+ this.eventDispatcher.addEventListener(type, handler);
460
+ }
461
+ /**
462
+ * Removes a listener from this transport.
463
+ * @param the type of event to unlisten on
464
+ * @param handler The message handler to remove.
465
+ */
466
+ removeEventListener(type, handler) {
467
+ this.eventDispatcher.removeEventListener(type, handler);
468
+ }
469
+ /**
470
+ * Sends a message over this transport, delegating to the appropriate connection to actually
471
+ * send the message.
472
+ * @param msg The message to send.
473
+ * @returns The ID of the sent message or undefined if it wasn't sent
474
+ */
475
+ send(to, msg) {
476
+ if (this.state === "destroyed") {
477
+ const err = "transport is destroyed, cant send";
478
+ log?.error(`${this.clientId} -- ` + err + `: ${JSON.stringify(msg)}`);
479
+ throw new Error(err);
480
+ } else if (this.state === "closed") {
481
+ log?.info(
482
+ `${this.clientId} -- transport closed when sending, discarding : ${JSON.stringify(
483
+ msg
484
+ )}`
485
+ );
486
+ return void 0;
487
+ }
488
+ let session = this.sessions.get(to);
489
+ if (!session) {
490
+ session = this.createSession(to, void 0);
491
+ log?.info(
492
+ `${this.clientId} -- no session for ${to}, created a new one (id: ${session.debugId})`
493
+ );
494
+ }
495
+ return session.send(msg);
496
+ }
497
+ // control helpers
498
+ sendCloseStream(to, streamId) {
499
+ return this.send(to, {
500
+ streamId,
501
+ controlFlags: 4 /* StreamClosedBit */,
502
+ payload: {
503
+ type: "CLOSE"
504
+ }
505
+ });
506
+ }
507
+ /**
508
+ * Default close implementation for transports. You should override this in the downstream
509
+ * implementation if you need to do any additional cleanup and call super.close() at the end.
510
+ * Closes the transport. Any messages sent while the transport is closed will be silently discarded.
511
+ */
512
+ close() {
513
+ for (const session of this.sessions.values()) {
514
+ session.halfCloseConnection();
515
+ }
516
+ this.state = "closed";
517
+ log?.info(`${this.clientId} -- manually closed transport`);
518
+ }
519
+ /**
520
+ * Default destroy implementation for transports. You should override this in the downstream
521
+ * implementation if you need to do any additional cleanup and call super.destroy() at the end.
522
+ * Destroys the transport. Any messages sent while the transport is destroyed will throw an error.
523
+ */
524
+ destroy() {
525
+ for (const session of this.sessions.values()) {
526
+ session.closeStaleConnection(session.connection);
527
+ }
528
+ this.state = "destroyed";
529
+ log?.info(`${this.clientId} -- manually destroyed transport`);
530
+ }
531
+ };
532
+ var ClientTransport = class extends Transport {
533
+ /**
534
+ * The map of reconnect promises for each client ID.
535
+ */
536
+ inflightConnectionPromises;
537
+ tryReconnecting = true;
538
+ constructor(clientId, providedOptions) {
539
+ super(clientId, providedOptions);
540
+ this.inflightConnectionPromises = /* @__PURE__ */ new Map();
541
+ }
542
+ handleConnection(conn, to) {
543
+ const bootHandler = this.receiveWithBootSequence(conn, () => {
544
+ conn.removeDataListener(bootHandler);
545
+ conn.addDataListener((data) => {
546
+ const parsed = this.parseMsg(data);
547
+ if (!parsed) {
548
+ conn.close();
549
+ return;
550
+ }
551
+ this.handleMsg(parsed);
552
+ });
553
+ });
554
+ conn.addDataListener(bootHandler);
555
+ conn.addCloseListener(() => {
556
+ this.onDisconnect(conn, to);
557
+ void this.connect(to);
558
+ });
559
+ conn.addErrorListener((err) => {
560
+ log?.warn(
561
+ `${this.clientId} -- error in connection (id: ${conn.debugId}) to ${to}: ${coerceErrorString(err)}`
562
+ );
563
+ });
564
+ }
565
+ /**
566
+ * Manually attempts to connect to a client.
567
+ * @param to The client ID of the node to connect to.
568
+ */
569
+ async connect(to, attempt = 0) {
570
+ if (this.state !== "open" || !this.tryReconnecting) {
571
+ log?.info(
572
+ `${this.clientId} -- transport state is no longer open, not attempting connection`
573
+ );
574
+ return;
575
+ }
576
+ let reconnectPromise = this.inflightConnectionPromises.get(to);
577
+ if (!reconnectPromise) {
578
+ reconnectPromise = this.createNewOutgoingConnection(to);
579
+ this.inflightConnectionPromises.set(to, reconnectPromise);
580
+ }
581
+ try {
582
+ const conn = await reconnectPromise;
583
+ this.state = "open";
584
+ const requestMsg = bootRequestMessage(this.clientId, to, this.instanceId);
585
+ log?.debug(`${this.clientId} -- sending boot handshake to ${to}`);
586
+ conn.send(this.codec.toBuffer(requestMsg));
587
+ } catch (error) {
588
+ const errStr = coerceErrorString(error);
589
+ this.inflightConnectionPromises.delete(to);
590
+ if (attempt >= this.options.retryAttemptsMax) {
591
+ const errMsg = `connection to ${to} failed after ${attempt} attempts (${errStr}), giving up`;
592
+ log?.error(`${this.clientId} -- ${errMsg}`);
593
+ throw new Error(errMsg);
594
+ } else {
595
+ const jitter = Math.floor(Math.random() * this.options.retryJitterMs);
596
+ const backoffMs = this.options.retryIntervalMs * 2 ** attempt + jitter;
597
+ log?.warn(
598
+ `${this.clientId} -- connection to ${to} failed (${errStr}), trying again in ${backoffMs}ms`
599
+ );
600
+ setTimeout(() => void this.connect(to, attempt + 1), backoffMs);
601
+ }
602
+ }
603
+ }
604
+ receiveWithBootSequence(conn, sessionCb) {
605
+ const bootHandler = (data) => {
606
+ const parsed = this.parseMsg(data);
607
+ if (!parsed) {
608
+ conn.close();
609
+ return;
610
+ }
611
+ if (!Value.Check(ControlMessageHandshakeResponseSchema, parsed.payload)) {
612
+ log?.warn(
613
+ `${this.clientId} -- received invalid handshake resp: ${JSON.stringify(parsed)}`
614
+ );
615
+ return;
616
+ }
617
+ if (!parsed.payload.status.ok) {
618
+ log?.warn(
619
+ `${this.clientId} -- received failed handshake resp: ${JSON.stringify(
620
+ parsed
621
+ )}`
622
+ );
623
+ return;
624
+ }
625
+ const serverInstanceId = parsed.payload.status.instanceId;
626
+ log?.debug(
627
+ `${this.clientId} -- handshake from ${parsed.from} ok (server instance: ${serverInstanceId})`
628
+ );
629
+ sessionCb(this.onConnect(conn, parsed.from, serverInstanceId));
630
+ };
631
+ return bootHandler;
632
+ }
633
+ onDisconnect(conn, connectedTo) {
634
+ if (connectedTo)
635
+ this.inflightConnectionPromises.delete(connectedTo);
636
+ super.onDisconnect(conn, connectedTo);
637
+ }
638
+ };
639
+ var ServerTransport = class extends Transport {
640
+ constructor(clientId, providedOptions) {
641
+ super(clientId, providedOptions);
642
+ log?.info(
643
+ `${this.clientId} -- initiated server transport (instance id: ${this.instanceId}, protocol: ${PROTOCOL_VERSION})`
644
+ );
645
+ }
646
+ handleConnection(conn) {
647
+ let session = void 0;
648
+ const client = () => session?.to ?? "unknown";
649
+ const bootHandler = this.receiveWithBootSequence(
650
+ conn,
651
+ (establishedSession) => {
652
+ session = establishedSession;
653
+ conn.removeDataListener(bootHandler);
654
+ conn.addDataListener((data) => {
655
+ const parsed = this.parseMsg(data);
656
+ if (!parsed) {
657
+ conn.close();
658
+ return;
659
+ }
660
+ this.handleMsg(parsed);
661
+ });
662
+ }
663
+ );
664
+ conn.addDataListener(bootHandler);
665
+ conn.addCloseListener(() => {
666
+ if (!session)
667
+ return;
668
+ log?.info(
669
+ `${this.clientId} -- connection (id: ${conn.debugId}) to ${client()} disconnected`
670
+ );
671
+ this.onDisconnect(conn, session.to);
672
+ });
673
+ conn.addErrorListener((err) => {
674
+ if (!session)
675
+ return;
676
+ log?.warn(
677
+ `${this.clientId} -- connection (id: ${conn.debugId}) to ${client()} got an error: ${coerceErrorString(err)}`
678
+ );
679
+ });
680
+ }
681
+ receiveWithBootSequence(conn, sessionCb) {
682
+ const bootHandler = (data) => {
683
+ const parsed = this.parseMsg(data);
684
+ if (!parsed) {
685
+ conn.close();
686
+ return;
687
+ }
688
+ if (!Value.Check(ControlMessageHandshakeRequestSchema, parsed.payload)) {
689
+ const responseMsg2 = bootResponseMessage(
690
+ this.clientId,
691
+ this.instanceId,
692
+ parsed.from,
693
+ false
694
+ );
695
+ conn.send(this.codec.toBuffer(responseMsg2));
696
+ log?.warn(
697
+ `${this.clientId} -- received invalid handshake msg: ${JSON.stringify(
698
+ parsed
699
+ )}`
700
+ );
701
+ return;
702
+ }
703
+ const instanceId = parsed.payload.instanceId;
704
+ log?.debug(
705
+ `${this.clientId} -- handshake from ${parsed.from} ok (instance id: ${instanceId}), responding with handshake success`
706
+ );
707
+ const responseMsg = bootResponseMessage(
708
+ this.clientId,
709
+ this.instanceId,
710
+ parsed.from,
711
+ true
712
+ );
713
+ conn.send(this.codec.toBuffer(responseMsg));
714
+ sessionCb(this.onConnect(conn, parsed.from, instanceId));
715
+ };
716
+ return bootHandler;
717
+ }
718
+ };
719
+
720
+ export {
721
+ Connection,
722
+ Session,
723
+ Transport,
724
+ ClientTransport,
725
+ ServerTransport
726
+ };