@replit/river 0.24.3 → 0.25.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 (63) hide show
  1. package/dist/{chunk-XKHLA5MP.js → chunk-5CNNIOAO.js} +4 -4
  2. package/dist/{chunk-FKBXIWWN.js → chunk-D5O3ERJU.js} +3 -3
  3. package/dist/{chunk-EHXKU4TW.js → chunk-MBMEJIPU.js} +2 -2
  4. package/dist/{chunk-W3CY6PNC.js → chunk-PCBPPTXH.js} +28 -23
  5. package/dist/chunk-PCBPPTXH.js.map +1 -0
  6. package/dist/{chunk-LSHUPI6U.js → chunk-SGSRNAWJ.js} +41 -18
  7. package/dist/{chunk-LSHUPI6U.js.map → chunk-SGSRNAWJ.js.map} +1 -1
  8. package/dist/{chunk-DZNP3EI5.js → chunk-SZ5NBBX7.js} +2 -2
  9. package/dist/{chunk-DZNP3EI5.js.map → chunk-SZ5NBBX7.js.map} +1 -1
  10. package/dist/{chunk-KVLCQ24J.js → chunk-YM5Y4NAT.js} +34 -13
  11. package/dist/chunk-YM5Y4NAT.js.map +1 -0
  12. package/dist/{client-2ba72e89.d.ts → client-1321630c.d.ts} +1 -1
  13. package/dist/{connection-55cba970.d.ts → connection-bd907ca6.d.ts} +1 -1
  14. package/dist/{handshake-0b88e8fc.d.ts → handshake-3772d7ca.d.ts} +4 -2
  15. package/dist/router/index.cjs +40 -17
  16. package/dist/router/index.cjs.map +1 -1
  17. package/dist/router/index.d.cts +7 -7
  18. package/dist/router/index.d.ts +7 -7
  19. package/dist/router/index.js +2 -2
  20. package/dist/{server-732e7014.d.ts → server-f0fd2b98.d.ts} +1 -1
  21. package/dist/{services-adfd0bc3.d.ts → services-8d14ae16.d.ts} +2 -2
  22. package/dist/transport/impls/ws/client.cjs +33 -12
  23. package/dist/transport/impls/ws/client.cjs.map +1 -1
  24. package/dist/transport/impls/ws/client.d.cts +3 -3
  25. package/dist/transport/impls/ws/client.d.ts +3 -3
  26. package/dist/transport/impls/ws/client.js +7 -7
  27. package/dist/transport/impls/ws/server.cjs +57 -31
  28. package/dist/transport/impls/ws/server.cjs.map +1 -1
  29. package/dist/transport/impls/ws/server.d.cts +3 -3
  30. package/dist/transport/impls/ws/server.d.ts +3 -3
  31. package/dist/transport/impls/ws/server.js +5 -5
  32. package/dist/transport/index.cjs +57 -31
  33. package/dist/transport/index.cjs.map +1 -1
  34. package/dist/transport/index.d.cts +3 -3
  35. package/dist/transport/index.d.ts +3 -3
  36. package/dist/transport/index.js +7 -7
  37. package/dist/util/testHelpers.cjs +33 -27
  38. package/dist/util/testHelpers.cjs.map +1 -1
  39. package/dist/util/testHelpers.d.cts +4 -7
  40. package/dist/util/testHelpers.d.ts +4 -7
  41. package/dist/util/testHelpers.js +3 -14
  42. package/dist/util/testHelpers.js.map +1 -1
  43. package/package.json +13 -14
  44. package/dist/chunk-KVLCQ24J.js.map +0 -1
  45. package/dist/chunk-TDFWZIXR.js +0 -106
  46. package/dist/chunk-TDFWZIXR.js.map +0 -1
  47. package/dist/chunk-W3CY6PNC.js.map +0 -1
  48. package/dist/connection-c6db05d9.d.ts +0 -31
  49. package/dist/transport/impls/uds/client.cjs +0 -1684
  50. package/dist/transport/impls/uds/client.cjs.map +0 -1
  51. package/dist/transport/impls/uds/client.d.cts +0 -18
  52. package/dist/transport/impls/uds/client.d.ts +0 -18
  53. package/dist/transport/impls/uds/client.js +0 -38
  54. package/dist/transport/impls/uds/client.js.map +0 -1
  55. package/dist/transport/impls/uds/server.cjs +0 -1650
  56. package/dist/transport/impls/uds/server.cjs.map +0 -1
  57. package/dist/transport/impls/uds/server.d.cts +0 -19
  58. package/dist/transport/impls/uds/server.d.ts +0 -19
  59. package/dist/transport/impls/uds/server.js +0 -33
  60. package/dist/transport/impls/uds/server.js.map +0 -1
  61. /package/dist/{chunk-XKHLA5MP.js.map → chunk-5CNNIOAO.js.map} +0 -0
  62. /package/dist/{chunk-FKBXIWWN.js.map → chunk-D5O3ERJU.js.map} +0 -0
  63. /package/dist/{chunk-EHXKU4TW.js.map → chunk-MBMEJIPU.js.map} +0 -0
@@ -1,1684 +0,0 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
-
20
- // transport/impls/uds/client.ts
21
- var client_exports = {};
22
- __export(client_exports, {
23
- UnixDomainSocketClientTransport: () => UnixDomainSocketClientTransport
24
- });
25
- module.exports = __toCommonJS(client_exports);
26
- var import_node_net = require("net");
27
-
28
- // transport/transforms/messageFraming.ts
29
- var import_node_stream = require("stream");
30
- var Uint32LengthPrefixFraming = class extends import_node_stream.Transform {
31
- receivedBuffer;
32
- maxBufferSizeBytes;
33
- constructor({ maxBufferSizeBytes, ...options }) {
34
- super(options);
35
- this.maxBufferSizeBytes = maxBufferSizeBytes;
36
- this.receivedBuffer = Buffer.alloc(0);
37
- }
38
- _transform(chunk, _encoding, cb) {
39
- if (this.receivedBuffer.byteLength + chunk.byteLength > this.maxBufferSizeBytes) {
40
- const err = new Error(
41
- `buffer overflow: ${this.receivedBuffer.byteLength}B > ${this.maxBufferSizeBytes}B`
42
- );
43
- this.emit("error", err);
44
- cb(err);
45
- return;
46
- }
47
- this.receivedBuffer = Buffer.concat([this.receivedBuffer, chunk]);
48
- while (this.receivedBuffer.length > 4) {
49
- const claimedMessageLength = this.receivedBuffer.readUInt32BE(0) + 4;
50
- if (this.receivedBuffer.length >= claimedMessageLength) {
51
- const message = this.receivedBuffer.subarray(4, claimedMessageLength);
52
- this.push(message);
53
- this.receivedBuffer = this.receivedBuffer.subarray(claimedMessageLength);
54
- } else {
55
- break;
56
- }
57
- }
58
- cb();
59
- }
60
- _flush(cb) {
61
- this.receivedBuffer = Buffer.alloc(0);
62
- cb();
63
- }
64
- _destroy(error, callback) {
65
- this.receivedBuffer = Buffer.alloc(0);
66
- super._destroy(error, callback);
67
- }
68
- };
69
- function createLengthEncodedStream(options) {
70
- return new Uint32LengthPrefixFraming({
71
- maxBufferSizeBytes: options?.maxBufferSizeBytes ?? 16 * 1024 * 1024
72
- // 16MB
73
- });
74
- }
75
- var MessageFramer = {
76
- createFramedStream: createLengthEncodedStream,
77
- write: (buf) => {
78
- const lengthPrefix = Buffer.alloc(4);
79
- lengthPrefix.writeUInt32BE(buf.length, 0);
80
- return Buffer.concat([lengthPrefix, buf]);
81
- }
82
- };
83
-
84
- // transport/id.ts
85
- var import_nanoid = require("nanoid");
86
- var alphabet = (0, import_nanoid.customAlphabet)(
87
- "1234567890abcdefghijklmnopqrstuvxyzABCDEFGHIJKLMNOPQRSTUVXYZ"
88
- );
89
- var generateId = () => alphabet(12);
90
-
91
- // transport/connection.ts
92
- var Connection = class {
93
- id;
94
- telemetry;
95
- constructor() {
96
- this.id = `conn-${generateId()}`;
97
- }
98
- get loggingMetadata() {
99
- const metadata = { connId: this.id };
100
- const spanContext = this.telemetry?.span.spanContext();
101
- if (this.telemetry?.span.isRecording() && spanContext) {
102
- metadata.telemetry = {
103
- traceId: spanContext.traceId,
104
- spanId: spanContext.spanId
105
- };
106
- }
107
- return metadata;
108
- }
109
- // can't use event emitter because we need this to work in both node + browser
110
- _dataListeners = /* @__PURE__ */ new Set();
111
- _closeListeners = /* @__PURE__ */ new Set();
112
- _errorListeners = /* @__PURE__ */ new Set();
113
- get dataListeners() {
114
- return [...this._dataListeners];
115
- }
116
- get closeListeners() {
117
- return [...this._closeListeners];
118
- }
119
- get errorListeners() {
120
- return [...this._errorListeners];
121
- }
122
- /**
123
- * Handle adding a callback for when a message is received.
124
- * @param msg The message that was received.
125
- */
126
- addDataListener(cb) {
127
- this._dataListeners.add(cb);
128
- }
129
- removeDataListener(cb) {
130
- this._dataListeners.delete(cb);
131
- }
132
- /**
133
- * Handle adding a callback for when the connection is closed.
134
- * This should also be called if an error happens and after notifying all the error listeners.
135
- * @param cb The callback to call when the connection is closed.
136
- */
137
- addCloseListener(cb) {
138
- this._closeListeners.add(cb);
139
- }
140
- removeCloseListener(cb) {
141
- this._closeListeners.delete(cb);
142
- }
143
- /**
144
- * Handle adding a callback for when an error is received.
145
- * This should only be used for this.logging errors, all cleanup
146
- * should be delegated to addCloseListener.
147
- *
148
- * The implementer should take care such that the implemented
149
- * connection will call both the close and error callbacks
150
- * on an error.
151
- *
152
- * @param cb The callback to call when an error is received.
153
- */
154
- addErrorListener(cb) {
155
- this._errorListeners.add(cb);
156
- }
157
- removeErrorListener(cb) {
158
- this._errorListeners.delete(cb);
159
- }
160
- };
161
-
162
- // transport/impls/uds/connection.ts
163
- var UdsConnection = class extends Connection {
164
- sock;
165
- input;
166
- framer;
167
- constructor(sock) {
168
- super();
169
- this.framer = MessageFramer.createFramedStream();
170
- this.sock = sock;
171
- this.input = sock.pipe(this.framer);
172
- this.sock.on("close", () => {
173
- for (const cb of this.closeListeners) {
174
- cb();
175
- }
176
- });
177
- this.sock.on("error", (err) => {
178
- if (err instanceof Error && "code" in err && err.code === "EPIPE") {
179
- return;
180
- }
181
- for (const cb of this.errorListeners) {
182
- cb(err);
183
- }
184
- });
185
- this.input.on("data", (msg) => {
186
- for (const cb of this.dataListeners) {
187
- cb(msg);
188
- }
189
- });
190
- }
191
- send(payload) {
192
- if (this.framer.destroyed || !this.sock.writable || this.sock.closed) {
193
- return false;
194
- }
195
- this.sock.write(MessageFramer.write(payload));
196
- return true;
197
- }
198
- close() {
199
- this.sock.destroy();
200
- this.framer.destroy();
201
- }
202
- };
203
-
204
- // transport/client.ts
205
- var import_api3 = require("@opentelemetry/api");
206
-
207
- // transport/message.ts
208
- var import_typebox = require("@sinclair/typebox");
209
- var TransportMessageSchema = (t) => import_typebox.Type.Object({
210
- id: import_typebox.Type.String(),
211
- from: import_typebox.Type.String(),
212
- to: import_typebox.Type.String(),
213
- seq: import_typebox.Type.Integer(),
214
- ack: import_typebox.Type.Integer(),
215
- serviceName: import_typebox.Type.Optional(import_typebox.Type.String()),
216
- procedureName: import_typebox.Type.Optional(import_typebox.Type.String()),
217
- streamId: import_typebox.Type.String(),
218
- controlFlags: import_typebox.Type.Integer(),
219
- tracing: import_typebox.Type.Optional(
220
- import_typebox.Type.Object({
221
- traceparent: import_typebox.Type.String(),
222
- tracestate: import_typebox.Type.String()
223
- })
224
- ),
225
- payload: t
226
- });
227
- var ControlMessageAckSchema = import_typebox.Type.Object({
228
- type: import_typebox.Type.Literal("ACK")
229
- });
230
- var ControlMessageCloseSchema = import_typebox.Type.Object({
231
- type: import_typebox.Type.Literal("CLOSE")
232
- });
233
- var PROTOCOL_VERSION = "v1.1";
234
- var ControlMessageHandshakeRequestSchema = import_typebox.Type.Object({
235
- type: import_typebox.Type.Literal("HANDSHAKE_REQ"),
236
- protocolVersion: import_typebox.Type.String(),
237
- sessionId: import_typebox.Type.String(),
238
- /**
239
- * Specifies what the server's expected session state (from the pov of the client). This can be
240
- * used by the server to know whether this is a new or a reestablished connection, and whether it
241
- * is compatible with what it already has.
242
- */
243
- expectedSessionState: import_typebox.Type.Object({
244
- // what the client expects the server to send next
245
- nextExpectedSeq: import_typebox.Type.Integer(),
246
- // TODO: remove optional once we know all servers
247
- // are nextSentSeq here
248
- // what the server expects the client to send next
249
- nextSentSeq: import_typebox.Type.Optional(import_typebox.Type.Integer())
250
- }),
251
- metadata: import_typebox.Type.Optional(import_typebox.Type.Unknown())
252
- });
253
- var HandshakeErrorRetriableResponseCodes = import_typebox.Type.Union([
254
- import_typebox.Type.Literal("SESSION_STATE_MISMATCH")
255
- ]);
256
- var HandshakeErrorFatalResponseCodes = import_typebox.Type.Union([
257
- import_typebox.Type.Literal("MALFORMED_HANDSHAKE_META"),
258
- import_typebox.Type.Literal("MALFORMED_HANDSHAKE"),
259
- import_typebox.Type.Literal("PROTOCOL_VERSION_MISMATCH"),
260
- import_typebox.Type.Literal("REJECTED_BY_CUSTOM_HANDLER")
261
- ]);
262
- var HandshakeErrorResponseCodes = import_typebox.Type.Union([
263
- HandshakeErrorRetriableResponseCodes,
264
- HandshakeErrorFatalResponseCodes
265
- ]);
266
- var ControlMessageHandshakeResponseSchema = import_typebox.Type.Object({
267
- type: import_typebox.Type.Literal("HANDSHAKE_RESP"),
268
- status: import_typebox.Type.Union([
269
- import_typebox.Type.Object({
270
- ok: import_typebox.Type.Literal(true),
271
- sessionId: import_typebox.Type.String()
272
- }),
273
- import_typebox.Type.Object({
274
- ok: import_typebox.Type.Literal(false),
275
- reason: import_typebox.Type.String(),
276
- // TODO: remove optional once we know all servers
277
- // are sending code here
278
- code: import_typebox.Type.Optional(HandshakeErrorResponseCodes)
279
- })
280
- ])
281
- });
282
- var ControlMessagePayloadSchema = import_typebox.Type.Union([
283
- ControlMessageCloseSchema,
284
- ControlMessageAckSchema,
285
- ControlMessageHandshakeRequestSchema,
286
- ControlMessageHandshakeResponseSchema
287
- ]);
288
- var OpaqueTransportMessageSchema = TransportMessageSchema(
289
- import_typebox.Type.Unknown()
290
- );
291
- function handshakeRequestMessage({
292
- from,
293
- to,
294
- sessionId,
295
- expectedSessionState,
296
- metadata,
297
- tracing
298
- }) {
299
- return {
300
- id: generateId(),
301
- from,
302
- to,
303
- seq: 0,
304
- ack: 0,
305
- streamId: generateId(),
306
- controlFlags: 0,
307
- tracing,
308
- payload: {
309
- type: "HANDSHAKE_REQ",
310
- protocolVersion: PROTOCOL_VERSION,
311
- sessionId,
312
- expectedSessionState,
313
- metadata
314
- }
315
- };
316
- }
317
- function isAck(controlFlag) {
318
- return (controlFlag & 1 /* AckBit */) === 1 /* AckBit */;
319
- }
320
-
321
- // codec/json.ts
322
- var encoder = new TextEncoder();
323
- var decoder = new TextDecoder();
324
- function uint8ArrayToBase64(uint8Array) {
325
- let binary = "";
326
- uint8Array.forEach((byte) => {
327
- binary += String.fromCharCode(byte);
328
- });
329
- return btoa(binary);
330
- }
331
- function base64ToUint8Array(base64) {
332
- const binaryString = atob(base64);
333
- const uint8Array = new Uint8Array(binaryString.length);
334
- for (let i = 0; i < binaryString.length; i++) {
335
- uint8Array[i] = binaryString.charCodeAt(i);
336
- }
337
- return uint8Array;
338
- }
339
- var NaiveJsonCodec = {
340
- toBuffer: (obj) => {
341
- return encoder.encode(
342
- JSON.stringify(obj, function replacer(key) {
343
- const val = this[key];
344
- if (val instanceof Uint8Array) {
345
- return { $t: uint8ArrayToBase64(val) };
346
- } else {
347
- return val;
348
- }
349
- })
350
- );
351
- },
352
- fromBuffer: (buff) => {
353
- try {
354
- const parsed = JSON.parse(
355
- decoder.decode(buff),
356
- function reviver(_key, val) {
357
- if (val?.$t) {
358
- return base64ToUint8Array(val.$t);
359
- } else {
360
- return val;
361
- }
362
- }
363
- );
364
- if (typeof parsed === "object")
365
- return parsed;
366
- return null;
367
- } catch {
368
- return null;
369
- }
370
- }
371
- };
372
-
373
- // transport/options.ts
374
- var defaultTransportOptions = {
375
- heartbeatIntervalMs: 1e3,
376
- heartbeatsUntilDead: 2,
377
- sessionDisconnectGraceMs: 5e3,
378
- connectionTimeoutMs: 2e3,
379
- handshakeTimeoutMs: 1e3,
380
- codec: NaiveJsonCodec
381
- };
382
- var defaultConnectionRetryOptions = {
383
- baseIntervalMs: 250,
384
- maxJitterMs: 200,
385
- maxBackoffMs: 32e3,
386
- attemptBudgetCapacity: 5,
387
- budgetRestoreIntervalMs: 200
388
- };
389
- var defaultClientTransportOptions = {
390
- ...defaultTransportOptions,
391
- ...defaultConnectionRetryOptions
392
- };
393
- var defaultServerTransportOptions = {
394
- ...defaultTransportOptions
395
- };
396
-
397
- // transport/rateLimit.ts
398
- var LeakyBucketRateLimit = class {
399
- budgetConsumed;
400
- intervalHandles;
401
- options;
402
- constructor(options) {
403
- this.options = options;
404
- this.budgetConsumed = /* @__PURE__ */ new Map();
405
- this.intervalHandles = /* @__PURE__ */ new Map();
406
- }
407
- getBackoffMs(user) {
408
- if (!this.budgetConsumed.has(user))
409
- return 0;
410
- const exponent = Math.max(0, this.getBudgetConsumed(user) - 1);
411
- const jitter = Math.floor(Math.random() * this.options.maxJitterMs);
412
- const backoffMs = Math.min(
413
- this.options.baseIntervalMs * 2 ** exponent,
414
- this.options.maxBackoffMs
415
- );
416
- return backoffMs + jitter;
417
- }
418
- get totalBudgetRestoreTime() {
419
- return this.options.budgetRestoreIntervalMs * this.options.attemptBudgetCapacity;
420
- }
421
- consumeBudget(user) {
422
- this.stopLeak(user);
423
- this.budgetConsumed.set(user, this.getBudgetConsumed(user) + 1);
424
- }
425
- getBudgetConsumed(user) {
426
- return this.budgetConsumed.get(user) ?? 0;
427
- }
428
- hasBudget(user) {
429
- return this.getBudgetConsumed(user) < this.options.attemptBudgetCapacity;
430
- }
431
- startRestoringBudget(user) {
432
- if (this.intervalHandles.has(user)) {
433
- return;
434
- }
435
- const restoreBudgetForUser = () => {
436
- const currentBudget = this.budgetConsumed.get(user);
437
- if (!currentBudget) {
438
- this.stopLeak(user);
439
- return;
440
- }
441
- const newBudget = currentBudget - 1;
442
- if (newBudget === 0) {
443
- this.budgetConsumed.delete(user);
444
- return;
445
- }
446
- this.budgetConsumed.set(user, newBudget);
447
- };
448
- const intervalHandle = setInterval(
449
- restoreBudgetForUser,
450
- this.options.budgetRestoreIntervalMs
451
- );
452
- this.intervalHandles.set(user, intervalHandle);
453
- }
454
- stopLeak(user) {
455
- if (!this.intervalHandles.has(user)) {
456
- return;
457
- }
458
- clearInterval(this.intervalHandles.get(user));
459
- this.intervalHandles.delete(user);
460
- }
461
- close() {
462
- for (const user of this.intervalHandles.keys()) {
463
- this.stopLeak(user);
464
- }
465
- }
466
- };
467
-
468
- // logging/log.ts
469
- var LoggingLevels = {
470
- debug: -1,
471
- info: 0,
472
- warn: 1,
473
- error: 2
474
- };
475
- var cleanedLogFn = (log) => {
476
- return (msg, metadata) => {
477
- if (!metadata?.transportMessage) {
478
- log(msg, metadata);
479
- return;
480
- }
481
- const { payload, ...rest } = metadata.transportMessage;
482
- metadata.transportMessage = rest;
483
- log(msg, metadata);
484
- };
485
- };
486
- var BaseLogger = class {
487
- minLevel;
488
- output;
489
- constructor(output, minLevel = "info") {
490
- this.minLevel = minLevel;
491
- this.output = output;
492
- }
493
- debug(msg, metadata) {
494
- if (LoggingLevels[this.minLevel] <= LoggingLevels.debug) {
495
- this.output(msg, metadata ?? {}, "debug");
496
- }
497
- }
498
- info(msg, metadata) {
499
- if (LoggingLevels[this.minLevel] <= LoggingLevels.info) {
500
- this.output(msg, metadata ?? {}, "info");
501
- }
502
- }
503
- warn(msg, metadata) {
504
- if (LoggingLevels[this.minLevel] <= LoggingLevels.warn) {
505
- this.output(msg, metadata ?? {}, "warn");
506
- }
507
- }
508
- error(msg, metadata) {
509
- if (LoggingLevels[this.minLevel] <= LoggingLevels.error) {
510
- this.output(msg, metadata ?? {}, "error");
511
- }
512
- }
513
- };
514
- var createLogProxy = (log) => ({
515
- debug: cleanedLogFn(log.debug.bind(log)),
516
- info: cleanedLogFn(log.info.bind(log)),
517
- warn: cleanedLogFn(log.warn.bind(log)),
518
- error: cleanedLogFn(log.error.bind(log))
519
- });
520
-
521
- // transport/events.ts
522
- var ProtocolError = {
523
- RetriesExceeded: "conn_retry_exceeded",
524
- HandshakeFailed: "handshake_failed",
525
- MessageOrderingViolated: "message_ordering_violated"
526
- };
527
- var EventDispatcher = class {
528
- eventListeners = {};
529
- removeAllListeners() {
530
- this.eventListeners = {};
531
- }
532
- numberOfListeners(eventType) {
533
- return this.eventListeners[eventType]?.size ?? 0;
534
- }
535
- addEventListener(eventType, handler) {
536
- if (!this.eventListeners[eventType]) {
537
- this.eventListeners[eventType] = /* @__PURE__ */ new Set();
538
- }
539
- this.eventListeners[eventType]?.add(handler);
540
- }
541
- removeEventListener(eventType, handler) {
542
- const handlers = this.eventListeners[eventType];
543
- if (handlers) {
544
- this.eventListeners[eventType]?.delete(handler);
545
- }
546
- }
547
- dispatchEvent(eventType, event) {
548
- const handlers = this.eventListeners[eventType];
549
- if (handlers) {
550
- const copy = [...handlers];
551
- for (const handler of copy) {
552
- handler(event);
553
- }
554
- }
555
- }
556
- };
557
-
558
- // transport/sessionStateMachine/common.ts
559
- var import_value = require("@sinclair/typebox/value");
560
- var ERR_CONSUMED = `session state has been consumed and is no longer valid`;
561
- var StateMachineState = class {
562
- /*
563
- * Whether this state has been consumed
564
- * and we've moved on to another state
565
- */
566
- _isConsumed;
567
- close() {
568
- this._handleClose();
569
- }
570
- constructor() {
571
- this._isConsumed = false;
572
- return new Proxy(this, {
573
- get(target, prop) {
574
- if (prop === "_isConsumed" || prop === "id" || prop === "state") {
575
- return Reflect.get(target, prop);
576
- }
577
- if (prop === "_handleStateExit") {
578
- return () => {
579
- target._isConsumed = true;
580
- target._handleStateExit();
581
- };
582
- }
583
- if (prop === "_handleClose") {
584
- return () => {
585
- target._handleStateExit();
586
- target._handleClose();
587
- };
588
- }
589
- if (target._isConsumed) {
590
- throw new Error(
591
- `${ERR_CONSUMED}: getting ${prop.toString()} on consumed state`
592
- );
593
- }
594
- return Reflect.get(target, prop);
595
- },
596
- set(target, prop, value) {
597
- if (target._isConsumed) {
598
- throw new Error(
599
- `${ERR_CONSUMED}: setting ${prop.toString()} on consumed state`
600
- );
601
- }
602
- return Reflect.set(target, prop, value);
603
- }
604
- });
605
- }
606
- };
607
- var CommonSession = class extends StateMachineState {
608
- from;
609
- options;
610
- log;
611
- constructor(from, options, log) {
612
- super();
613
- this.from = from;
614
- this.options = options;
615
- this.log = log;
616
- }
617
- parseMsg(msg) {
618
- const parsedMsg = this.options.codec.fromBuffer(msg);
619
- if (parsedMsg === null) {
620
- const decodedBuffer = new TextDecoder().decode(Buffer.from(msg));
621
- this.log?.error(
622
- `received malformed msg: ${decodedBuffer}`,
623
- this.loggingMetadata
624
- );
625
- return null;
626
- }
627
- if (!import_value.Value.Check(OpaqueTransportMessageSchema, parsedMsg)) {
628
- this.log?.error(`received invalid msg: ${JSON.stringify(parsedMsg)}`, {
629
- ...this.loggingMetadata,
630
- validationErrors: [
631
- ...import_value.Value.Errors(OpaqueTransportMessageSchema, parsedMsg)
632
- ]
633
- });
634
- return null;
635
- }
636
- return parsedMsg;
637
- }
638
- };
639
- var IdentifiedSession = class extends CommonSession {
640
- id;
641
- telemetry;
642
- to;
643
- /**
644
- * Index of the message we will send next (excluding handshake)
645
- */
646
- seq;
647
- /**
648
- * Number of unique messages we've received this session (excluding handshake)
649
- */
650
- ack;
651
- sendBuffer;
652
- constructor(id, from, to, seq, ack, sendBuffer, telemetry, options, log) {
653
- super(from, options, log);
654
- this.id = id;
655
- this.to = to;
656
- this.seq = seq;
657
- this.ack = ack;
658
- this.sendBuffer = sendBuffer;
659
- this.telemetry = telemetry;
660
- this.log = log;
661
- }
662
- get loggingMetadata() {
663
- const spanContext = this.telemetry.span.spanContext();
664
- return {
665
- clientId: this.from,
666
- connectedTo: this.to,
667
- sessionId: this.id,
668
- telemetry: {
669
- traceId: spanContext.traceId,
670
- spanId: spanContext.spanId
671
- }
672
- };
673
- }
674
- constructMsg(partialMsg) {
675
- const msg = {
676
- ...partialMsg,
677
- id: generateId(),
678
- to: this.to,
679
- from: this.from,
680
- seq: this.seq,
681
- ack: this.ack
682
- };
683
- this.seq++;
684
- return msg;
685
- }
686
- nextSeq() {
687
- return this.sendBuffer.length > 0 ? this.sendBuffer[0].seq : this.seq;
688
- }
689
- send(msg) {
690
- const constructedMsg = this.constructMsg(msg);
691
- this.sendBuffer.push(constructedMsg);
692
- return constructedMsg.id;
693
- }
694
- _handleStateExit() {
695
- }
696
- _handleClose() {
697
- this.sendBuffer.length = 0;
698
- this.telemetry.span.end();
699
- }
700
- };
701
-
702
- // transport/sessionStateMachine/SessionConnecting.ts
703
- var SessionConnecting = class extends IdentifiedSession {
704
- state = "Connecting" /* Connecting */;
705
- connPromise;
706
- listeners;
707
- connectionTimeout;
708
- constructor(connPromise, listeners, ...args) {
709
- super(...args);
710
- this.connPromise = connPromise;
711
- this.listeners = listeners;
712
- this.connectionTimeout = setTimeout(() => {
713
- listeners.onConnectionTimeout();
714
- }, this.options.connectionTimeoutMs);
715
- connPromise.then(
716
- (conn) => {
717
- if (this._isConsumed)
718
- return;
719
- listeners.onConnectionEstablished(conn);
720
- },
721
- (err) => {
722
- if (this._isConsumed)
723
- return;
724
- listeners.onConnectionFailed(err);
725
- }
726
- );
727
- }
728
- // close a pending connection if it resolves, ignore errors if the promise
729
- // ends up rejected anyways
730
- bestEffortClose() {
731
- void this.connPromise.then((conn) => conn.close()).catch(() => {
732
- });
733
- }
734
- _handleStateExit() {
735
- super._handleStateExit();
736
- clearTimeout(this.connectionTimeout);
737
- this.connectionTimeout = void 0;
738
- }
739
- _handleClose() {
740
- this.bestEffortClose();
741
- super._handleClose();
742
- }
743
- };
744
-
745
- // transport/sessionStateMachine/SessionNoConnection.ts
746
- var SessionNoConnection = class extends IdentifiedSession {
747
- state = "NoConnection" /* NoConnection */;
748
- listeners;
749
- gracePeriodTimeout;
750
- constructor(listeners, ...args) {
751
- super(...args);
752
- this.listeners = listeners;
753
- this.gracePeriodTimeout = setTimeout(() => {
754
- this.listeners.onSessionGracePeriodElapsed();
755
- }, this.options.sessionDisconnectGraceMs);
756
- }
757
- _handleClose() {
758
- super._handleClose();
759
- }
760
- _handleStateExit() {
761
- super._handleStateExit();
762
- if (this.gracePeriodTimeout) {
763
- clearTimeout(this.gracePeriodTimeout);
764
- this.gracePeriodTimeout = void 0;
765
- }
766
- }
767
- };
768
-
769
- // tracing/index.ts
770
- var import_api = require("@opentelemetry/api");
771
-
772
- // package.json
773
- var version = "0.24.3";
774
-
775
- // tracing/index.ts
776
- function getPropagationContext(ctx) {
777
- const tracing = {
778
- traceparent: "",
779
- tracestate: ""
780
- };
781
- import_api.propagation.inject(ctx, tracing);
782
- return tracing;
783
- }
784
- function createSessionTelemetryInfo(sessionId, to, from, propagationCtx) {
785
- const parentCtx = propagationCtx ? import_api.propagation.extract(import_api.context.active(), propagationCtx) : import_api.context.active();
786
- const span = tracer.startSpan(
787
- `session ${sessionId}`,
788
- {
789
- attributes: {
790
- component: "river",
791
- "river.session.id": sessionId,
792
- "river.session.to": to,
793
- "river.session.from": from
794
- }
795
- },
796
- parentCtx
797
- );
798
- const ctx = import_api.trace.setSpan(parentCtx, span);
799
- return { span, ctx };
800
- }
801
- var tracer = import_api.trace.getTracer("river", version);
802
- var tracing_default = tracer;
803
-
804
- // transport/sessionStateMachine/SessionWaitingForHandshake.ts
805
- var SessionWaitingForHandshake = class extends CommonSession {
806
- state = "WaitingForHandshake" /* WaitingForHandshake */;
807
- conn;
808
- listeners;
809
- handshakeTimeout;
810
- constructor(conn, listeners, ...args) {
811
- super(...args);
812
- this.conn = conn;
813
- this.listeners = listeners;
814
- this.handshakeTimeout = setTimeout(() => {
815
- listeners.onHandshakeTimeout();
816
- }, this.options.handshakeTimeoutMs);
817
- this.conn.addDataListener(this.onHandshakeData);
818
- this.conn.addErrorListener(listeners.onConnectionErrored);
819
- this.conn.addCloseListener(listeners.onConnectionClosed);
820
- }
821
- onHandshakeData = (msg) => {
822
- const parsedMsg = this.parseMsg(msg);
823
- if (parsedMsg === null) {
824
- this.listeners.onInvalidHandshake("could not parse message");
825
- return;
826
- }
827
- this.listeners.onHandshake(parsedMsg);
828
- };
829
- get loggingMetadata() {
830
- return {
831
- clientId: this.from,
832
- connId: this.conn.id
833
- };
834
- }
835
- sendHandshake(msg) {
836
- return this.conn.send(this.options.codec.toBuffer(msg));
837
- }
838
- _handleStateExit() {
839
- this.conn.removeDataListener(this.onHandshakeData);
840
- this.conn.removeErrorListener(this.listeners.onConnectionErrored);
841
- this.conn.removeCloseListener(this.listeners.onConnectionClosed);
842
- clearTimeout(this.handshakeTimeout);
843
- this.handshakeTimeout = void 0;
844
- }
845
- _handleClose() {
846
- this.conn.close();
847
- }
848
- };
849
-
850
- // transport/sessionStateMachine/SessionHandshaking.ts
851
- var SessionHandshaking = class extends IdentifiedSession {
852
- state = "Handshaking" /* Handshaking */;
853
- conn;
854
- listeners;
855
- handshakeTimeout;
856
- constructor(conn, listeners, ...args) {
857
- super(...args);
858
- this.conn = conn;
859
- this.listeners = listeners;
860
- this.handshakeTimeout = setTimeout(() => {
861
- listeners.onHandshakeTimeout();
862
- }, this.options.handshakeTimeoutMs);
863
- this.conn.addDataListener(this.onHandshakeData);
864
- this.conn.addErrorListener(listeners.onConnectionErrored);
865
- this.conn.addCloseListener(listeners.onConnectionClosed);
866
- }
867
- onHandshakeData = (msg) => {
868
- const parsedMsg = this.parseMsg(msg);
869
- if (parsedMsg === null) {
870
- this.listeners.onInvalidHandshake("could not parse message");
871
- return;
872
- }
873
- this.listeners.onHandshake(parsedMsg);
874
- };
875
- sendHandshake(msg) {
876
- return this.conn.send(this.options.codec.toBuffer(msg));
877
- }
878
- _handleStateExit() {
879
- super._handleStateExit();
880
- this.conn.removeDataListener(this.onHandshakeData);
881
- this.conn.removeErrorListener(this.listeners.onConnectionErrored);
882
- this.conn.removeCloseListener(this.listeners.onConnectionClosed);
883
- clearTimeout(this.handshakeTimeout);
884
- }
885
- _handleClose() {
886
- super._handleClose();
887
- this.conn.close();
888
- }
889
- };
890
-
891
- // transport/sessionStateMachine/SessionConnected.ts
892
- var import_api2 = require("@opentelemetry/api");
893
- var SessionConnected = class extends IdentifiedSession {
894
- state = "Connected" /* Connected */;
895
- conn;
896
- listeners;
897
- heartbeatHandle;
898
- heartbeatMisses = 0;
899
- get isActivelyHeartbeating() {
900
- return this.heartbeatHandle !== void 0;
901
- }
902
- updateBookkeeping(ack, seq) {
903
- this.sendBuffer = this.sendBuffer.filter((unacked) => unacked.seq >= ack);
904
- this.ack = seq + 1;
905
- this.heartbeatMisses = 0;
906
- }
907
- send(msg) {
908
- const constructedMsg = this.constructMsg(msg);
909
- this.sendBuffer.push(constructedMsg);
910
- this.conn.send(this.options.codec.toBuffer(constructedMsg));
911
- return constructedMsg.id;
912
- }
913
- constructor(conn, listeners, ...args) {
914
- super(...args);
915
- this.conn = conn;
916
- this.listeners = listeners;
917
- this.conn.addDataListener(this.onMessageData);
918
- this.conn.addCloseListener(listeners.onConnectionClosed);
919
- this.conn.addErrorListener(listeners.onConnectionErrored);
920
- if (this.sendBuffer.length > 0) {
921
- this.log?.debug(
922
- `sending ${this.sendBuffer.length} buffered messages`,
923
- this.loggingMetadata
924
- );
925
- }
926
- for (const msg of this.sendBuffer) {
927
- conn.send(this.options.codec.toBuffer(msg));
928
- }
929
- }
930
- startActiveHeartbeat() {
931
- this.heartbeatHandle = setInterval(() => {
932
- const misses = this.heartbeatMisses;
933
- const missDuration = misses * this.options.heartbeatIntervalMs;
934
- if (misses >= this.options.heartbeatsUntilDead) {
935
- this.log?.info(
936
- `closing connection to ${this.to} due to inactivity (missed ${misses} heartbeats which is ${missDuration}ms)`,
937
- this.loggingMetadata
938
- );
939
- this.telemetry.span.addEvent("closing connection due to inactivity");
940
- this.conn.close();
941
- clearInterval(this.heartbeatHandle);
942
- this.heartbeatHandle = void 0;
943
- return;
944
- }
945
- this.sendHeartbeat();
946
- this.heartbeatMisses++;
947
- }, this.options.heartbeatIntervalMs);
948
- }
949
- sendHeartbeat() {
950
- this.send({
951
- streamId: "heartbeat",
952
- controlFlags: 1 /* AckBit */,
953
- payload: {
954
- type: "ACK"
955
- }
956
- });
957
- }
958
- onMessageData = (msg) => {
959
- const parsedMsg = this.parseMsg(msg);
960
- if (parsedMsg === null)
961
- return;
962
- if (parsedMsg.seq !== this.ack) {
963
- if (parsedMsg.seq < this.ack) {
964
- this.log?.debug(
965
- `received duplicate msg (got seq: ${parsedMsg.seq}, wanted seq: ${this.ack}), discarding`,
966
- {
967
- ...this.loggingMetadata,
968
- transportMessage: parsedMsg
969
- }
970
- );
971
- } else {
972
- const reason = `received out-of-order msg (got seq: ${parsedMsg.seq}, wanted seq: ${this.ack})`;
973
- this.log?.error(reason, {
974
- ...this.loggingMetadata,
975
- transportMessage: parsedMsg,
976
- tags: ["invariant-violation"]
977
- });
978
- this.telemetry.span.setStatus({
979
- code: import_api2.SpanStatusCode.ERROR,
980
- message: reason
981
- });
982
- this.listeners.onInvalidMessage(reason);
983
- }
984
- return;
985
- }
986
- this.log?.debug(`received msg`, {
987
- ...this.loggingMetadata,
988
- transportMessage: parsedMsg
989
- });
990
- this.updateBookkeeping(parsedMsg.ack, parsedMsg.seq);
991
- if (!isAck(parsedMsg.controlFlags)) {
992
- this.listeners.onMessage(parsedMsg);
993
- return;
994
- }
995
- this.log?.debug(`discarding msg (ack bit set)`, {
996
- ...this.loggingMetadata,
997
- transportMessage: parsedMsg
998
- });
999
- if (!this.isActivelyHeartbeating) {
1000
- this.sendHeartbeat();
1001
- }
1002
- };
1003
- _handleStateExit() {
1004
- super._handleStateExit();
1005
- this.conn.removeDataListener(this.onMessageData);
1006
- this.conn.removeCloseListener(this.listeners.onConnectionClosed);
1007
- this.conn.removeErrorListener(this.listeners.onConnectionErrored);
1008
- clearInterval(this.heartbeatHandle);
1009
- this.heartbeatHandle = void 0;
1010
- }
1011
- _handleClose() {
1012
- super._handleClose();
1013
- this.conn.close();
1014
- }
1015
- };
1016
-
1017
- // transport/sessionStateMachine/transitions.ts
1018
- function inheritSharedSession(session) {
1019
- return [
1020
- session.id,
1021
- session.from,
1022
- session.to,
1023
- session.seq,
1024
- session.ack,
1025
- session.sendBuffer,
1026
- session.telemetry,
1027
- session.options,
1028
- session.log
1029
- ];
1030
- }
1031
- var SessionStateGraph = {
1032
- entrypoints: {
1033
- NoConnection(to, from, listeners, options, log) {
1034
- const id = `session-${generateId()}`;
1035
- const telemetry = createSessionTelemetryInfo(id, to, from);
1036
- const sendBuffer = [];
1037
- const session = new SessionNoConnection(
1038
- listeners,
1039
- id,
1040
- from,
1041
- to,
1042
- 0,
1043
- 0,
1044
- sendBuffer,
1045
- telemetry,
1046
- options,
1047
- log
1048
- );
1049
- session.log?.info(`session ${session.id} created in NoConnection state`, {
1050
- ...session.loggingMetadata,
1051
- tags: ["state-transition"]
1052
- });
1053
- return session;
1054
- },
1055
- WaitingForHandshake(from, conn, listeners, options, log) {
1056
- const session = new SessionWaitingForHandshake(
1057
- conn,
1058
- listeners,
1059
- from,
1060
- options,
1061
- log
1062
- );
1063
- session.log?.info(`session created in WaitingForHandshake state`, {
1064
- ...session.loggingMetadata,
1065
- tags: ["state-transition"]
1066
- });
1067
- return session;
1068
- }
1069
- },
1070
- // All of the transitions 'move'/'consume' the old session and return a new one.
1071
- // After a session is transitioned, any usage of the old session will throw.
1072
- transition: {
1073
- // happy path transitions
1074
- NoConnectionToConnecting(oldSession, connPromise, listeners) {
1075
- const carriedState = inheritSharedSession(oldSession);
1076
- oldSession._handleStateExit();
1077
- const session = new SessionConnecting(
1078
- connPromise,
1079
- listeners,
1080
- ...carriedState
1081
- );
1082
- session.log?.info(
1083
- `session ${session.id} transition from NoConnection to Connecting`,
1084
- {
1085
- ...session.loggingMetadata,
1086
- tags: ["state-transition"]
1087
- }
1088
- );
1089
- return session;
1090
- },
1091
- ConnectingToHandshaking(oldSession, conn, listeners) {
1092
- const carriedState = inheritSharedSession(oldSession);
1093
- oldSession._handleStateExit();
1094
- const session = new SessionHandshaking(conn, listeners, ...carriedState);
1095
- session.log?.info(
1096
- `session ${session.id} transition from Connecting to Handshaking`,
1097
- {
1098
- ...session.loggingMetadata,
1099
- tags: ["state-transition"]
1100
- }
1101
- );
1102
- return session;
1103
- },
1104
- HandshakingToConnected(oldSession, listeners) {
1105
- const carriedState = inheritSharedSession(oldSession);
1106
- const conn = oldSession.conn;
1107
- oldSession._handleStateExit();
1108
- const session = new SessionConnected(conn, listeners, ...carriedState);
1109
- session.log?.info(
1110
- `session ${session.id} transition from Handshaking to Connected`,
1111
- {
1112
- ...session.loggingMetadata,
1113
- tags: ["state-transition"]
1114
- }
1115
- );
1116
- return session;
1117
- },
1118
- WaitingForHandshakeToConnected(pendingSession, oldSession, sessionId, to, propagationCtx, listeners) {
1119
- const conn = pendingSession.conn;
1120
- const { from, options } = pendingSession;
1121
- const carriedState = oldSession ? (
1122
- // old session exists, inherit state
1123
- inheritSharedSession(oldSession)
1124
- ) : (
1125
- // old session does not exist, create new state
1126
- [
1127
- sessionId,
1128
- from,
1129
- to,
1130
- 0,
1131
- 0,
1132
- [],
1133
- createSessionTelemetryInfo(sessionId, to, from, propagationCtx),
1134
- options,
1135
- pendingSession.log
1136
- ]
1137
- );
1138
- pendingSession._handleStateExit();
1139
- oldSession?._handleStateExit();
1140
- const session = new SessionConnected(conn, listeners, ...carriedState);
1141
- session.log?.info(
1142
- `session ${session.id} transition from WaitingForHandshake to Connected`,
1143
- {
1144
- ...session.loggingMetadata,
1145
- tags: ["state-transition"]
1146
- }
1147
- );
1148
- return session;
1149
- },
1150
- // disconnect paths
1151
- ConnectingToNoConnection(oldSession, listeners) {
1152
- const carriedState = inheritSharedSession(oldSession);
1153
- oldSession.bestEffortClose();
1154
- oldSession._handleStateExit();
1155
- const session = new SessionNoConnection(listeners, ...carriedState);
1156
- session.log?.info(
1157
- `session ${session.id} transition from Connecting to NoConnection`,
1158
- {
1159
- ...session.loggingMetadata,
1160
- tags: ["state-transition"]
1161
- }
1162
- );
1163
- return session;
1164
- },
1165
- HandshakingToNoConnection(oldSession, listeners) {
1166
- const carriedState = inheritSharedSession(oldSession);
1167
- oldSession.conn.close();
1168
- oldSession._handleStateExit();
1169
- const session = new SessionNoConnection(listeners, ...carriedState);
1170
- session.log?.info(
1171
- `session ${session.id} transition from Handshaking to NoConnection`,
1172
- {
1173
- ...session.loggingMetadata,
1174
- tags: ["state-transition"]
1175
- }
1176
- );
1177
- return session;
1178
- },
1179
- ConnectedToNoConnection(oldSession, listeners) {
1180
- const carriedState = inheritSharedSession(oldSession);
1181
- oldSession.conn.close();
1182
- oldSession._handleStateExit();
1183
- const session = new SessionNoConnection(listeners, ...carriedState);
1184
- session.log?.info(
1185
- `session ${session.id} transition from Connected to NoConnection`,
1186
- {
1187
- ...session.loggingMetadata,
1188
- tags: ["state-transition"]
1189
- }
1190
- );
1191
- return session;
1192
- }
1193
- }
1194
- };
1195
-
1196
- // transport/transport.ts
1197
- var Transport = class {
1198
- /**
1199
- * The status of the transport.
1200
- */
1201
- status;
1202
- /**
1203
- * The client ID of this transport.
1204
- */
1205
- clientId;
1206
- /**
1207
- * The event dispatcher for handling events of type EventTypes.
1208
- */
1209
- eventDispatcher;
1210
- /**
1211
- * The options for this transport.
1212
- */
1213
- options;
1214
- log;
1215
- sessions;
1216
- /**
1217
- * Creates a new Transport instance.
1218
- * @param codec The codec used to encode and decode messages.
1219
- * @param clientId The client ID of this transport.
1220
- */
1221
- constructor(clientId, providedOptions) {
1222
- this.options = { ...defaultTransportOptions, ...providedOptions };
1223
- this.eventDispatcher = new EventDispatcher();
1224
- this.clientId = clientId;
1225
- this.status = "open";
1226
- this.sessions = /* @__PURE__ */ new Map();
1227
- }
1228
- bindLogger(fn, level) {
1229
- if (typeof fn === "function") {
1230
- this.log = createLogProxy(new BaseLogger(fn, level));
1231
- return;
1232
- }
1233
- this.log = createLogProxy(fn);
1234
- }
1235
- /**
1236
- * Called when a message is received by this transport.
1237
- * You generally shouldn't need to override this in downstream transport implementations.
1238
- * @param msg The received message.
1239
- */
1240
- handleMsg(msg) {
1241
- if (this.getStatus() !== "open")
1242
- return;
1243
- this.eventDispatcher.dispatchEvent("message", msg);
1244
- }
1245
- /**
1246
- * Adds a listener to this transport.
1247
- * @param the type of event to listen for
1248
- * @param handler The message handler to add.
1249
- */
1250
- addEventListener(type, handler) {
1251
- this.eventDispatcher.addEventListener(type, handler);
1252
- }
1253
- /**
1254
- * Removes a listener from this transport.
1255
- * @param the type of event to un-listen on
1256
- * @param handler The message handler to remove.
1257
- */
1258
- removeEventListener(type, handler) {
1259
- this.eventDispatcher.removeEventListener(type, handler);
1260
- }
1261
- protocolError(type, message) {
1262
- this.eventDispatcher.dispatchEvent("protocolError", { type, message });
1263
- }
1264
- /**
1265
- * Default close implementation for transports. You should override this in the downstream
1266
- * implementation if you need to do any additional cleanup and call super.close() at the end.
1267
- * Closes the transport. Any messages sent while the transport is closed will be silently discarded.
1268
- */
1269
- close() {
1270
- this.status = "closed";
1271
- for (const session of this.sessions.values()) {
1272
- this.deleteSession(session);
1273
- }
1274
- this.eventDispatcher.dispatchEvent("transportStatus", {
1275
- status: this.status
1276
- });
1277
- this.eventDispatcher.removeAllListeners();
1278
- this.log?.info(`manually closed transport`, { clientId: this.clientId });
1279
- }
1280
- getStatus() {
1281
- return this.status;
1282
- }
1283
- updateSession(session) {
1284
- const activeSession = this.sessions.get(session.to);
1285
- if (activeSession && activeSession.id !== session.id) {
1286
- const msg = `attempt to transition active session for ${session.to} but active session (${activeSession.id}) is different from handle (${session.id})`;
1287
- throw new Error(msg);
1288
- }
1289
- this.sessions.set(session.to, session);
1290
- if (!activeSession) {
1291
- this.eventDispatcher.dispatchEvent("sessionStatus", {
1292
- status: "connect",
1293
- session
1294
- });
1295
- }
1296
- this.eventDispatcher.dispatchEvent("sessionTransition", {
1297
- state: session.state,
1298
- session
1299
- });
1300
- return session;
1301
- }
1302
- // state transitions
1303
- deleteSession(session) {
1304
- session.log?.info(`closing session ${session.id}`, session.loggingMetadata);
1305
- this.eventDispatcher.dispatchEvent("sessionStatus", {
1306
- status: "disconnect",
1307
- session
1308
- });
1309
- session.close();
1310
- this.sessions.delete(session.to);
1311
- }
1312
- // common listeners
1313
- onSessionGracePeriodElapsed(session) {
1314
- this.log?.warn(
1315
- `session to ${session.to} grace period elapsed, closing`,
1316
- session.loggingMetadata
1317
- );
1318
- this.deleteSession(session);
1319
- }
1320
- onConnectingFailed(session) {
1321
- const noConnectionSession = SessionStateGraph.transition.ConnectingToNoConnection(session, {
1322
- onSessionGracePeriodElapsed: () => {
1323
- this.onSessionGracePeriodElapsed(noConnectionSession);
1324
- }
1325
- });
1326
- return this.updateSession(noConnectionSession);
1327
- }
1328
- onConnClosed(session) {
1329
- let noConnectionSession;
1330
- if (session.state === "Handshaking" /* Handshaking */) {
1331
- noConnectionSession = SessionStateGraph.transition.HandshakingToNoConnection(session, {
1332
- onSessionGracePeriodElapsed: () => {
1333
- this.onSessionGracePeriodElapsed(noConnectionSession);
1334
- }
1335
- });
1336
- } else {
1337
- noConnectionSession = SessionStateGraph.transition.ConnectedToNoConnection(session, {
1338
- onSessionGracePeriodElapsed: () => {
1339
- this.onSessionGracePeriodElapsed(noConnectionSession);
1340
- }
1341
- });
1342
- }
1343
- return this.updateSession(noConnectionSession);
1344
- }
1345
- };
1346
-
1347
- // util/stringify.ts
1348
- function coerceErrorString(err) {
1349
- if (err instanceof Error) {
1350
- return err.message || "unknown reason";
1351
- }
1352
- return `[coerced to error] ${String(err)}`;
1353
- }
1354
-
1355
- // transport/client.ts
1356
- var import_value2 = require("@sinclair/typebox/value");
1357
- var ClientTransport = class extends Transport {
1358
- /**
1359
- * The options for this transport.
1360
- */
1361
- options;
1362
- retryBudget;
1363
- /**
1364
- * A flag indicating whether the transport should automatically reconnect
1365
- * when a connection is dropped.
1366
- * Realistically, this should always be true for clients unless you are writing
1367
- * tests or a special case where you don't want to reconnect.
1368
- */
1369
- reconnectOnConnectionDrop = true;
1370
- /**
1371
- * Optional handshake options for this client.
1372
- */
1373
- handshakeExtensions;
1374
- constructor(clientId, providedOptions) {
1375
- super(clientId, providedOptions);
1376
- this.options = {
1377
- ...defaultClientTransportOptions,
1378
- ...providedOptions
1379
- };
1380
- this.retryBudget = new LeakyBucketRateLimit(this.options);
1381
- }
1382
- extendHandshake(options) {
1383
- this.handshakeExtensions = options;
1384
- }
1385
- tryReconnecting(to) {
1386
- if (this.reconnectOnConnectionDrop && this.getStatus() === "open") {
1387
- this.connect(to);
1388
- }
1389
- }
1390
- send(to, msg) {
1391
- if (this.getStatus() === "closed") {
1392
- const err = "transport is closed, cant send";
1393
- this.log?.error(err, {
1394
- clientId: this.clientId,
1395
- transportMessage: msg,
1396
- tags: ["invariant-violation"]
1397
- });
1398
- throw new Error(err);
1399
- }
1400
- let session = this.sessions.get(to);
1401
- if (!session) {
1402
- session = this.createUnconnectedSession(to);
1403
- }
1404
- return session.send(msg);
1405
- }
1406
- createUnconnectedSession(to) {
1407
- const session = SessionStateGraph.entrypoints.NoConnection(
1408
- to,
1409
- this.clientId,
1410
- {
1411
- onSessionGracePeriodElapsed: () => {
1412
- this.onSessionGracePeriodElapsed(session);
1413
- }
1414
- },
1415
- this.options,
1416
- this.log
1417
- );
1418
- this.updateSession(session);
1419
- return session;
1420
- }
1421
- // listeners
1422
- onConnectingFailed(session) {
1423
- const noConnectionSession = super.onConnectingFailed(session);
1424
- this.tryReconnecting(noConnectionSession.to);
1425
- return noConnectionSession;
1426
- }
1427
- onConnClosed(session) {
1428
- const noConnectionSession = super.onConnClosed(session);
1429
- this.tryReconnecting(noConnectionSession.to);
1430
- return noConnectionSession;
1431
- }
1432
- onConnectionEstablished(session, conn) {
1433
- const handshakingSession = SessionStateGraph.transition.ConnectingToHandshaking(session, conn, {
1434
- onConnectionErrored: (err) => {
1435
- const errStr = coerceErrorString(err);
1436
- this.log?.error(
1437
- `connection to ${handshakingSession.to} errored during handshake: ${errStr}`,
1438
- handshakingSession.loggingMetadata
1439
- );
1440
- },
1441
- onConnectionClosed: () => {
1442
- this.log?.warn(
1443
- `connection to ${handshakingSession.to} closed during handshake`,
1444
- handshakingSession.loggingMetadata
1445
- );
1446
- this.onConnClosed(handshakingSession);
1447
- },
1448
- onHandshake: (msg) => {
1449
- this.onHandshakeResponse(handshakingSession, msg);
1450
- },
1451
- onInvalidHandshake: (reason) => {
1452
- this.log?.error(
1453
- `invalid handshake: ${reason}`,
1454
- handshakingSession.loggingMetadata
1455
- );
1456
- this.deleteSession(session);
1457
- this.protocolError(ProtocolError.HandshakeFailed, reason);
1458
- },
1459
- onHandshakeTimeout: () => {
1460
- this.log?.error(
1461
- `connection to ${handshakingSession.to} timed out during handshake`,
1462
- handshakingSession.loggingMetadata
1463
- );
1464
- this.onConnClosed(handshakingSession);
1465
- }
1466
- });
1467
- this.updateSession(handshakingSession);
1468
- void this.sendHandshake(handshakingSession);
1469
- return handshakingSession;
1470
- }
1471
- rejectHandshakeResponse(session, reason, metadata) {
1472
- session.conn.telemetry?.span.setStatus({
1473
- code: import_api3.SpanStatusCode.ERROR,
1474
- message: reason
1475
- });
1476
- this.log?.warn(reason, metadata);
1477
- this.deleteSession(session);
1478
- }
1479
- onHandshakeResponse(session, msg) {
1480
- if (!import_value2.Value.Check(ControlMessageHandshakeResponseSchema, msg.payload)) {
1481
- const reason = `received invalid handshake response`;
1482
- this.rejectHandshakeResponse(session, reason, {
1483
- ...session.loggingMetadata,
1484
- transportMessage: msg,
1485
- validationErrors: [
1486
- ...import_value2.Value.Errors(ControlMessageHandshakeResponseSchema, msg.payload)
1487
- ]
1488
- });
1489
- return;
1490
- }
1491
- if (!msg.payload.status.ok) {
1492
- const retriable = msg.payload.status.code ? import_value2.Value.Check(
1493
- HandshakeErrorRetriableResponseCodes,
1494
- msg.payload.status.code
1495
- ) : false;
1496
- const reason = `handshake failed: ${msg.payload.status.reason}`;
1497
- this.rejectHandshakeResponse(session, reason, {
1498
- ...session.loggingMetadata,
1499
- transportMessage: msg
1500
- });
1501
- if (retriable) {
1502
- this.tryReconnecting(session.to);
1503
- } else {
1504
- this.deleteSession(session);
1505
- this.protocolError(ProtocolError.HandshakeFailed, reason);
1506
- }
1507
- return;
1508
- }
1509
- if (msg.payload.status.sessionId !== session.id) {
1510
- const reason = `session id mismatch: expected ${session.id}, got ${msg.payload.status.sessionId}`;
1511
- this.rejectHandshakeResponse(session, reason, {
1512
- ...session.loggingMetadata,
1513
- transportMessage: msg
1514
- });
1515
- return;
1516
- }
1517
- this.log?.info(`handshake from ${msg.from} ok`, {
1518
- ...session.loggingMetadata,
1519
- transportMessage: msg
1520
- });
1521
- const connectedSession = SessionStateGraph.transition.HandshakingToConnected(session, {
1522
- onConnectionErrored: (err) => {
1523
- const errStr = coerceErrorString(err);
1524
- this.log?.warn(
1525
- `connection to ${connectedSession.to} errored: ${errStr}`,
1526
- connectedSession.loggingMetadata
1527
- );
1528
- },
1529
- onConnectionClosed: () => {
1530
- this.log?.info(
1531
- `connection to ${connectedSession.to} closed`,
1532
- connectedSession.loggingMetadata
1533
- );
1534
- this.onConnClosed(connectedSession);
1535
- },
1536
- onMessage: (msg2) => this.handleMsg(msg2),
1537
- onInvalidMessage: (reason) => {
1538
- this.deleteSession(connectedSession);
1539
- this.protocolError(ProtocolError.MessageOrderingViolated, reason);
1540
- }
1541
- });
1542
- this.updateSession(connectedSession);
1543
- this.retryBudget.startRestoringBudget(connectedSession.to);
1544
- }
1545
- /**
1546
- * Manually attempts to connect to a client.
1547
- * @param to The client ID of the node to connect to.
1548
- */
1549
- connect(to) {
1550
- let session = this.sessions.get(to);
1551
- session ??= this.createUnconnectedSession(to);
1552
- if (session.state !== "NoConnection" /* NoConnection */) {
1553
- this.log?.debug(
1554
- `session to ${to} has state ${session.state}, skipping connect attempt`,
1555
- session.loggingMetadata
1556
- );
1557
- return;
1558
- }
1559
- if (this.getStatus() !== "open") {
1560
- this.log?.info(
1561
- `transport state is no longer open, cancelling attempt to connect to ${to}`,
1562
- session.loggingMetadata
1563
- );
1564
- return;
1565
- }
1566
- if (!this.retryBudget.hasBudget(to)) {
1567
- const budgetConsumed = this.retryBudget.getBudgetConsumed(to);
1568
- const errMsg = `tried to connect to ${to} but retry budget exceeded (more than ${budgetConsumed} attempts in the last ${this.retryBudget.totalBudgetRestoreTime}ms)`;
1569
- this.log?.error(errMsg, session.loggingMetadata);
1570
- this.protocolError(ProtocolError.RetriesExceeded, errMsg);
1571
- return;
1572
- }
1573
- let sleep = Promise.resolve();
1574
- const backoffMs = this.retryBudget.getBackoffMs(to);
1575
- if (backoffMs > 0) {
1576
- sleep = new Promise((resolve) => setTimeout(resolve, backoffMs));
1577
- }
1578
- this.log?.info(
1579
- `attempting connection to ${to} (${backoffMs}ms backoff)`,
1580
- session.loggingMetadata
1581
- );
1582
- this.retryBudget.consumeBudget(to);
1583
- const reconnectPromise = tracing_default.startActiveSpan("connect", async (span) => {
1584
- try {
1585
- span.addEvent("backoff", { backoffMs });
1586
- await sleep;
1587
- if (this.getStatus() !== "open") {
1588
- throw new Error("transport state is no longer open");
1589
- }
1590
- span.addEvent("connecting");
1591
- return await this.createNewOutgoingConnection(to);
1592
- } catch (err) {
1593
- const errStr = coerceErrorString(err);
1594
- span.recordException(errStr);
1595
- span.setStatus({ code: import_api3.SpanStatusCode.ERROR });
1596
- throw err;
1597
- } finally {
1598
- span.end();
1599
- }
1600
- });
1601
- const connectingSession = SessionStateGraph.transition.NoConnectionToConnecting(
1602
- session,
1603
- reconnectPromise,
1604
- {
1605
- onConnectionEstablished: (conn) => {
1606
- this.log?.debug(
1607
- `connection to ${connectingSession.to} established`,
1608
- connectingSession.loggingMetadata
1609
- );
1610
- this.onConnectionEstablished(connectingSession, conn);
1611
- },
1612
- onConnectionFailed: (error) => {
1613
- const errStr = coerceErrorString(error);
1614
- this.log?.error(
1615
- `error connecting to ${connectingSession.to}: ${errStr}`,
1616
- connectingSession.loggingMetadata
1617
- );
1618
- this.onConnectingFailed(connectingSession);
1619
- },
1620
- onConnectionTimeout: () => {
1621
- this.log?.error(
1622
- `connection to ${connectingSession.to} timed out`,
1623
- connectingSession.loggingMetadata
1624
- );
1625
- this.onConnectingFailed(connectingSession);
1626
- }
1627
- }
1628
- );
1629
- this.updateSession(connectingSession);
1630
- }
1631
- async sendHandshake(session) {
1632
- let metadata = void 0;
1633
- if (this.handshakeExtensions) {
1634
- metadata = await this.handshakeExtensions.construct();
1635
- }
1636
- const requestMsg = handshakeRequestMessage({
1637
- from: this.clientId,
1638
- to: session.to,
1639
- sessionId: session.id,
1640
- expectedSessionState: {
1641
- nextExpectedSeq: session.ack,
1642
- nextSentSeq: session.nextSeq()
1643
- },
1644
- metadata,
1645
- tracing: getPropagationContext(session.telemetry.ctx)
1646
- });
1647
- this.log?.debug(`sending handshake request to ${session.to}`, {
1648
- ...session.loggingMetadata,
1649
- transportMessage: requestMsg
1650
- });
1651
- session.sendHandshake(requestMsg);
1652
- }
1653
- close() {
1654
- this.retryBudget.close();
1655
- super.close();
1656
- }
1657
- };
1658
-
1659
- // transport/impls/uds/client.ts
1660
- var UnixDomainSocketClientTransport = class extends ClientTransport {
1661
- path;
1662
- constructor(socketPath, clientId, providedOptions) {
1663
- super(clientId, providedOptions);
1664
- this.path = socketPath;
1665
- }
1666
- async createNewOutgoingConnection(to) {
1667
- this.log?.info(`establishing a new uds to ${to}`, {
1668
- clientId: this.clientId,
1669
- connectedTo: to
1670
- });
1671
- const sock = await new Promise((resolve, reject) => {
1672
- const sock2 = new import_node_net.Socket();
1673
- sock2.on("connect", () => resolve(sock2));
1674
- sock2.on("error", (err) => reject(err));
1675
- sock2.connect(this.path);
1676
- });
1677
- return new UdsConnection(sock);
1678
- }
1679
- };
1680
- // Annotate the CommonJS export names for ESM import in node:
1681
- 0 && (module.exports = {
1682
- UnixDomainSocketClientTransport
1683
- });
1684
- //# sourceMappingURL=client.cjs.map