@replit/river 0.216.1 → 0.217.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 (76) hide show
  1. package/README.md +2 -2
  2. package/dist/{adapter-BXCk-dmy.d.ts → adapter-Dl5Mewp3.d.ts} +1 -1
  3. package/dist/{chunk-C4EPHIKQ.js → chunk-JFFRB3SS.js} +48 -26
  4. package/dist/chunk-JFFRB3SS.js.map +1 -0
  5. package/dist/{chunk-62BM2WOT.js → chunk-VK3VJZGG.js} +19 -18
  6. package/dist/chunk-VK3VJZGG.js.map +1 -0
  7. package/dist/chunk-WMPWPIA4.js +72 -0
  8. package/dist/chunk-WMPWPIA4.js.map +1 -0
  9. package/dist/{client-BNc5Pj_4.d.ts → client-YP9bECp8.d.ts} +2 -2
  10. package/dist/codec/index.d.ts +3 -3
  11. package/dist/codec/index.js +2 -2
  12. package/dist/{connection-ou9w2dSY.d.ts → connection-D_HE_YQB.d.ts} +3 -3
  13. package/dist/customSchemas/index.d.ts +34 -0
  14. package/dist/customSchemas/index.js +9 -0
  15. package/dist/customSchemas/index.js.map +1 -0
  16. package/dist/{index-ZWkoesQD.d.ts → index-DgUMnNOi.d.ts} +1 -1
  17. package/dist/logging/index.d.ts +3 -3
  18. package/dist/{message-CpXWqmJw.d.ts → message-DxS8db8A.d.ts} +30 -31
  19. package/dist/protobuf/index.d.ts +11 -15
  20. package/dist/protobuf/index.js +7 -5
  21. package/dist/protobuf/index.js.map +1 -1
  22. package/dist/router/index.d.ts +11 -11
  23. package/dist/router/index.js +1 -1
  24. package/dist/{server-BPu7Td80.d.ts → server-BfM3_JLq.d.ts} +5 -5
  25. package/dist/{services-DpT2yNtt.d.ts → services-CL6k3HMH.d.ts} +8 -9
  26. package/dist/testUtil/index.d.ts +8 -8
  27. package/dist/testUtil/index.js +2 -2
  28. package/dist/testUtil/index.js.map +1 -1
  29. package/dist/transport/impls/ws/client.d.ts +7 -7
  30. package/dist/transport/impls/ws/client.js +2 -2
  31. package/dist/transport/impls/ws/server.d.ts +7 -7
  32. package/dist/transport/impls/ws/server.js +2 -2
  33. package/dist/transport/impls/ws/server.js.map +1 -1
  34. package/dist/transport/index.d.ts +8 -8
  35. package/dist/transport/index.js +2 -2
  36. package/dist/{transport-B1MUtXL7.d.ts → transport-CUpXnch7.d.ts} +4 -4
  37. package/package.json +14 -39
  38. package/dist/adapter-D5X11kmP.d.cts +0 -29
  39. package/dist/chunk-62BM2WOT.js.map +0 -1
  40. package/dist/chunk-C4EPHIKQ.js.map +0 -1
  41. package/dist/client-BZUvFL6B.d.cts +0 -54
  42. package/dist/codec/index.cjs +0 -268
  43. package/dist/codec/index.cjs.map +0 -1
  44. package/dist/codec/index.d.cts +0 -19
  45. package/dist/connection-xxgJHs2o.d.cts +0 -40
  46. package/dist/index-BAGGleT3.d.cts +0 -37
  47. package/dist/logging/index.cjs +0 -55
  48. package/dist/logging/index.cjs.map +0 -1
  49. package/dist/logging/index.d.cts +0 -4
  50. package/dist/message-CpXWqmJw.d.cts +0 -119
  51. package/dist/protobuf/codec.cjs +0 -107
  52. package/dist/protobuf/codec.cjs.map +0 -1
  53. package/dist/protobuf/codec.d.cts +0 -13
  54. package/dist/protobuf/index.cjs +0 -1877
  55. package/dist/protobuf/index.cjs.map +0 -1
  56. package/dist/protobuf/index.d.cts +0 -488
  57. package/dist/router/index.cjs +0 -2043
  58. package/dist/router/index.cjs.map +0 -1
  59. package/dist/router/index.d.cts +0 -80
  60. package/dist/server-JdnoVO11.d.cts +0 -72
  61. package/dist/services-CjigASqe.d.cts +0 -1135
  62. package/dist/testUtil/index.cjs +0 -3051
  63. package/dist/testUtil/index.cjs.map +0 -1
  64. package/dist/testUtil/index.d.cts +0 -122
  65. package/dist/transport/impls/ws/client.cjs +0 -2308
  66. package/dist/transport/impls/ws/client.cjs.map +0 -1
  67. package/dist/transport/impls/ws/client.d.cts +0 -33
  68. package/dist/transport/impls/ws/server.cjs +0 -2179
  69. package/dist/transport/impls/ws/server.cjs.map +0 -1
  70. package/dist/transport/impls/ws/server.d.cts +0 -21
  71. package/dist/transport/index.cjs +0 -2727
  72. package/dist/transport/index.cjs.map +0 -1
  73. package/dist/transport/index.d.cts +0 -11
  74. package/dist/transport-BnU3Zb0Q.d.cts +0 -590
  75. package/dist/types-BGGvYIJM.d.cts +0 -20
  76. package/dist/wslike-Dng9H1C7.d.cts +0 -40
@@ -1,2727 +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/index.ts
21
- var transport_exports = {};
22
- __export(transport_exports, {
23
- ClientTransport: () => ClientTransport,
24
- Connection: () => Connection,
25
- OpaqueTransportMessageSchema: () => OpaqueTransportMessageSchema,
26
- ProtocolError: () => ProtocolError,
27
- ServerTransport: () => ServerTransport,
28
- SessionState: () => SessionState,
29
- Transport: () => Transport,
30
- TransportMessageSchema: () => TransportMessageSchema,
31
- WebSocketCloseError: () => WebSocketCloseError,
32
- WebSocketConnection: () => WebSocketConnection
33
- });
34
- module.exports = __toCommonJS(transport_exports);
35
-
36
- // logging/log.ts
37
- var import_api = require("@opentelemetry/api");
38
- var LoggingLevels = {
39
- debug: -1,
40
- info: 0,
41
- warn: 1,
42
- error: 2
43
- };
44
- var cleanedLogFn = (log) => {
45
- return (msg, metadata) => {
46
- if (metadata && !metadata.telemetry) {
47
- const span = import_api.trace.getSpan(import_api.context.active());
48
- if (span) {
49
- metadata.telemetry = {
50
- traceId: span.spanContext().traceId,
51
- spanId: span.spanContext().spanId
52
- };
53
- }
54
- }
55
- if (!metadata?.transportMessage) {
56
- log(msg, metadata);
57
- return;
58
- }
59
- const { payload, ...rest } = metadata.transportMessage;
60
- metadata.transportMessage = rest;
61
- log(msg, metadata);
62
- };
63
- };
64
- var BaseLogger = class {
65
- minLevel;
66
- output;
67
- constructor(output, minLevel = "info") {
68
- this.minLevel = minLevel;
69
- this.output = output;
70
- }
71
- debug(msg, metadata) {
72
- if (LoggingLevels[this.minLevel] <= LoggingLevels.debug) {
73
- this.output(msg, metadata ?? {}, "debug");
74
- }
75
- }
76
- info(msg, metadata) {
77
- if (LoggingLevels[this.minLevel] <= LoggingLevels.info) {
78
- this.output(msg, metadata ?? {}, "info");
79
- }
80
- }
81
- warn(msg, metadata) {
82
- if (LoggingLevels[this.minLevel] <= LoggingLevels.warn) {
83
- this.output(msg, metadata ?? {}, "warn");
84
- }
85
- }
86
- error(msg, metadata) {
87
- if (LoggingLevels[this.minLevel] <= LoggingLevels.error) {
88
- this.output(msg, metadata ?? {}, "error");
89
- }
90
- }
91
- };
92
- var createLogProxy = (log) => ({
93
- debug: cleanedLogFn(log.debug.bind(log)),
94
- info: cleanedLogFn(log.info.bind(log)),
95
- warn: cleanedLogFn(log.warn.bind(log)),
96
- error: cleanedLogFn(log.error.bind(log))
97
- });
98
-
99
- // transport/events.ts
100
- var ProtocolError = {
101
- RetriesExceeded: "conn_retry_exceeded",
102
- HandshakeFailed: "handshake_failed",
103
- MessageOrderingViolated: "message_ordering_violated",
104
- InvalidMessage: "invalid_message",
105
- MessageSendFailure: "message_send_failure"
106
- };
107
- var EventDispatcher = class {
108
- eventListeners = {};
109
- removeAllListeners() {
110
- this.eventListeners = {};
111
- }
112
- numberOfListeners(eventType) {
113
- return this.eventListeners[eventType]?.size ?? 0;
114
- }
115
- addEventListener(eventType, handler) {
116
- if (!this.eventListeners[eventType]) {
117
- this.eventListeners[eventType] = /* @__PURE__ */ new Set();
118
- }
119
- this.eventListeners[eventType]?.add(handler);
120
- }
121
- removeEventListener(eventType, handler) {
122
- const handlers = this.eventListeners[eventType];
123
- if (handlers) {
124
- this.eventListeners[eventType]?.delete(handler);
125
- }
126
- }
127
- dispatchEvent(eventType, event) {
128
- const handlers = this.eventListeners[eventType];
129
- if (handlers) {
130
- const copy = [...handlers];
131
- for (const handler of copy) {
132
- handler(event);
133
- }
134
- }
135
- }
136
- };
137
-
138
- // codec/json.ts
139
- var encoder = new TextEncoder();
140
- var decoder = new TextDecoder();
141
- function uint8ArrayToBase64(uint8Array) {
142
- let binary = "";
143
- uint8Array.forEach((byte) => {
144
- binary += String.fromCharCode(byte);
145
- });
146
- return btoa(binary);
147
- }
148
- function base64ToUint8Array(base64) {
149
- const binaryString = atob(base64);
150
- const uint8Array = new Uint8Array(binaryString.length);
151
- for (let i = 0; i < binaryString.length; i++) {
152
- uint8Array[i] = binaryString.charCodeAt(i);
153
- }
154
- return uint8Array;
155
- }
156
- var NaiveJsonCodec = {
157
- toBuffer: (obj) => {
158
- return encoder.encode(
159
- JSON.stringify(obj, function replacer(key) {
160
- const val = this[key];
161
- if (val instanceof Uint8Array) {
162
- return { $t: uint8ArrayToBase64(val) };
163
- } else if (typeof val === "bigint") {
164
- return { $b: val.toString() };
165
- } else {
166
- return val;
167
- }
168
- })
169
- );
170
- },
171
- fromBuffer: (buff) => {
172
- const parsed = JSON.parse(
173
- decoder.decode(buff),
174
- function reviver(_key, val) {
175
- if (val?.$t !== void 0) {
176
- return base64ToUint8Array(val.$t);
177
- } else if (val?.$b !== void 0) {
178
- return BigInt(val.$b);
179
- } else {
180
- return val;
181
- }
182
- }
183
- );
184
- if (typeof parsed !== "object" || parsed === null) {
185
- throw new Error("unpacked msg is not an object");
186
- }
187
- return parsed;
188
- }
189
- };
190
-
191
- // transport/options.ts
192
- var defaultTransportOptions = {
193
- heartbeatIntervalMs: 1e3,
194
- heartbeatsUntilDead: 2,
195
- sessionDisconnectGraceMs: 5e3,
196
- connectionTimeoutMs: 2e3,
197
- handshakeTimeoutMs: 1e3,
198
- enableTransparentSessionReconnects: true,
199
- codec: NaiveJsonCodec
200
- };
201
- var defaultConnectionRetryOptions = {
202
- baseIntervalMs: 150,
203
- maxJitterMs: 200,
204
- maxBackoffMs: 32e3,
205
- attemptBudgetCapacity: 5,
206
- budgetRestoreIntervalMs: 200,
207
- isFatalConnectionError: () => false
208
- };
209
- var defaultClientTransportOptions = {
210
- ...defaultTransportOptions,
211
- ...defaultConnectionRetryOptions
212
- };
213
- var defaultServerTransportOptions = {
214
- ...defaultTransportOptions
215
- };
216
-
217
- // transport/id.ts
218
- var import_nanoid = require("nanoid");
219
- var alphabet = (0, import_nanoid.customAlphabet)(
220
- "1234567890abcdefghijklmnopqrstuvxyzABCDEFGHIJKLMNOPQRSTUVXYZ"
221
- );
222
- var generateId = () => alphabet(12);
223
-
224
- // transport/sessionStateMachine/common.ts
225
- var SessionState = /* @__PURE__ */ ((SessionState2) => {
226
- SessionState2["NoConnection"] = "NoConnection";
227
- SessionState2["BackingOff"] = "BackingOff";
228
- SessionState2["Connecting"] = "Connecting";
229
- SessionState2["Handshaking"] = "Handshaking";
230
- SessionState2["Connected"] = "Connected";
231
- SessionState2["WaitingForHandshake"] = "WaitingForHandshake";
232
- return SessionState2;
233
- })(SessionState || {});
234
- var ERR_CONSUMED = `session state has been consumed and is no longer valid`;
235
- var StateMachineState = class {
236
- /*
237
- * Whether this state has been consumed
238
- * and we've moved on to another state
239
- */
240
- _isConsumed;
241
- /**
242
- * Cleanup this state machine state and mark it as consumed.
243
- * After calling close, it is an error to access any properties on the state.
244
- * You should never need to call this as a consumer.
245
- *
246
- * If you're looking to close the session from the client,
247
- * use `.hardDisconnect` on the client transport.
248
- */
249
- close() {
250
- this._handleClose();
251
- }
252
- constructor() {
253
- this._isConsumed = false;
254
- return new Proxy(this, {
255
- get(target, prop) {
256
- if (prop === "_isConsumed" || prop === "id" || prop === "state") {
257
- return Reflect.get(target, prop);
258
- }
259
- if (prop === "_handleStateExit") {
260
- return () => {
261
- target._isConsumed = true;
262
- target._handleStateExit();
263
- };
264
- }
265
- if (prop === "_handleClose") {
266
- return () => {
267
- target._isConsumed = true;
268
- target._handleStateExit();
269
- target._handleClose();
270
- };
271
- }
272
- if (target._isConsumed) {
273
- throw new Error(
274
- `${ERR_CONSUMED}: getting ${prop.toString()} on consumed state`
275
- );
276
- }
277
- return Reflect.get(target, prop);
278
- },
279
- set(target, prop, value) {
280
- if (target._isConsumed) {
281
- throw new Error(
282
- `${ERR_CONSUMED}: setting ${prop.toString()} on consumed state`
283
- );
284
- }
285
- return Reflect.set(target, prop, value);
286
- }
287
- });
288
- }
289
- };
290
- var CommonSession = class extends StateMachineState {
291
- from;
292
- options;
293
- codec;
294
- tracer;
295
- log;
296
- constructor({ from, options, log, tracer, codec }) {
297
- super();
298
- this.from = from;
299
- this.options = options;
300
- this.log = log;
301
- this.tracer = tracer;
302
- this.codec = codec;
303
- }
304
- };
305
- var IdentifiedSession = class extends CommonSession {
306
- id;
307
- telemetry;
308
- to;
309
- protocolVersion;
310
- listeners;
311
- /**
312
- * Index of the message we will send next (excluding handshake)
313
- */
314
- seq;
315
- /**
316
- * Last seq we sent over the wire this session (excluding handshake) and retransmissions
317
- */
318
- seqSent;
319
- /**
320
- * Number of unique messages we've received this session (excluding handshake)
321
- */
322
- ack;
323
- sendBuffer;
324
- constructor(props) {
325
- const {
326
- id,
327
- to,
328
- seq,
329
- ack,
330
- sendBuffer,
331
- telemetry,
332
- log,
333
- protocolVersion,
334
- seqSent: messagesSent,
335
- listeners
336
- } = props;
337
- super(props);
338
- this.id = id;
339
- this.to = to;
340
- this.seq = seq;
341
- this.ack = ack;
342
- this.sendBuffer = sendBuffer;
343
- this.telemetry = telemetry;
344
- this.log = log;
345
- this.protocolVersion = protocolVersion;
346
- this.seqSent = messagesSent;
347
- this.listeners = listeners;
348
- }
349
- get loggingMetadata() {
350
- const metadata = {
351
- clientId: this.from,
352
- connectedTo: this.to,
353
- sessionId: this.id
354
- };
355
- if (this.telemetry.span.isRecording()) {
356
- const spanContext = this.telemetry.span.spanContext();
357
- metadata.telemetry = {
358
- traceId: spanContext.traceId,
359
- spanId: spanContext.spanId
360
- };
361
- }
362
- return metadata;
363
- }
364
- encodeMsg(partialMsg) {
365
- const msg = {
366
- ...partialMsg,
367
- id: generateId(),
368
- to: this.to,
369
- from: this.from,
370
- seq: this.seq,
371
- ack: this.ack
372
- };
373
- const encoded = this.codec.toBuffer(msg);
374
- if (!encoded.ok) {
375
- this.listeners.onMessageSendFailure(
376
- { ...partialMsg, seq: this.seq },
377
- encoded.reason
378
- );
379
- return encoded;
380
- }
381
- this.seq++;
382
- return {
383
- ok: true,
384
- value: {
385
- id: msg.id,
386
- seq: msg.seq,
387
- msg: partialMsg,
388
- data: encoded.value
389
- }
390
- };
391
- }
392
- nextSeq() {
393
- return this.sendBuffer.length > 0 ? this.sendBuffer[0].seq : this.seq;
394
- }
395
- send(msg) {
396
- const encodeResult = this.encodeMsg(msg);
397
- if (!encodeResult.ok) {
398
- return encodeResult;
399
- }
400
- this.sendBuffer.push(encodeResult.value);
401
- return {
402
- ok: true,
403
- value: encodeResult.value.id
404
- };
405
- }
406
- _handleStateExit() {
407
- }
408
- _handleClose() {
409
- this.sendBuffer.length = 0;
410
- this.telemetry.span.end();
411
- }
412
- };
413
- var IdentifiedSessionWithGracePeriod = class extends IdentifiedSession {
414
- graceExpiryTime;
415
- gracePeriodTimeout;
416
- listeners;
417
- constructor(props) {
418
- super(props);
419
- this.listeners = props.listeners;
420
- this.graceExpiryTime = props.graceExpiryTime;
421
- this.gracePeriodTimeout = setTimeout(() => {
422
- this.listeners.onSessionGracePeriodElapsed();
423
- }, this.graceExpiryTime - Date.now());
424
- }
425
- _handleStateExit() {
426
- super._handleStateExit();
427
- if (this.gracePeriodTimeout) {
428
- clearTimeout(this.gracePeriodTimeout);
429
- this.gracePeriodTimeout = void 0;
430
- }
431
- }
432
- _handleClose() {
433
- super._handleClose();
434
- }
435
- };
436
-
437
- // transport/sessionStateMachine/SessionConnecting.ts
438
- var SessionConnecting = class extends IdentifiedSessionWithGracePeriod {
439
- state = "Connecting" /* Connecting */;
440
- connPromise;
441
- listeners;
442
- connectionTimeout;
443
- constructor(props) {
444
- super(props);
445
- this.connPromise = props.connPromise;
446
- this.listeners = props.listeners;
447
- this.connPromise.then(
448
- (conn) => {
449
- if (this._isConsumed) return;
450
- this.listeners.onConnectionEstablished(conn);
451
- },
452
- (err) => {
453
- if (this._isConsumed) return;
454
- this.listeners.onConnectionFailed(err);
455
- }
456
- );
457
- this.connectionTimeout = setTimeout(() => {
458
- this.listeners.onConnectionTimeout();
459
- }, this.options.connectionTimeoutMs);
460
- }
461
- // close a pending connection if it resolves, ignore errors if the promise
462
- // ends up rejected anyways
463
- bestEffortClose() {
464
- const logger = this.log;
465
- const metadata = this.loggingMetadata;
466
- this.connPromise.then((conn) => {
467
- conn.close();
468
- logger?.info(
469
- "connection eventually resolved but session has transitioned, closed connection",
470
- {
471
- ...metadata,
472
- ...conn.loggingMetadata
473
- }
474
- );
475
- }).catch(() => {
476
- });
477
- }
478
- _handleStateExit() {
479
- super._handleStateExit();
480
- if (this.connectionTimeout) {
481
- clearTimeout(this.connectionTimeout);
482
- this.connectionTimeout = void 0;
483
- }
484
- }
485
- _handleClose() {
486
- super._handleClose();
487
- this.bestEffortClose();
488
- }
489
- };
490
-
491
- // transport/sessionStateMachine/SessionNoConnection.ts
492
- var SessionNoConnection = class extends IdentifiedSessionWithGracePeriod {
493
- state = "NoConnection" /* NoConnection */;
494
- _handleClose() {
495
- super._handleClose();
496
- }
497
- _handleStateExit() {
498
- super._handleStateExit();
499
- }
500
- };
501
-
502
- // tracing/index.ts
503
- var import_api2 = require("@opentelemetry/api");
504
-
505
- // transport/message.ts
506
- var import_typebox = require("@sinclair/typebox");
507
- var TransportMessageSchema = (t) => import_typebox.Type.Object({
508
- id: import_typebox.Type.String(),
509
- from: import_typebox.Type.String(),
510
- to: import_typebox.Type.String(),
511
- seq: import_typebox.Type.Integer(),
512
- ack: import_typebox.Type.Integer(),
513
- serviceName: import_typebox.Type.Optional(import_typebox.Type.String()),
514
- procedureName: import_typebox.Type.Optional(import_typebox.Type.String()),
515
- streamId: import_typebox.Type.String(),
516
- controlFlags: import_typebox.Type.Integer(),
517
- tracing: import_typebox.Type.Optional(
518
- import_typebox.Type.Object({
519
- traceparent: import_typebox.Type.String(),
520
- tracestate: import_typebox.Type.String()
521
- })
522
- ),
523
- payload: t
524
- });
525
- var ControlMessageAckSchema = import_typebox.Type.Object({
526
- type: import_typebox.Type.Literal("ACK")
527
- });
528
- var ControlMessageCloseSchema = import_typebox.Type.Object({
529
- type: import_typebox.Type.Literal("CLOSE")
530
- });
531
- var currentProtocolVersion = "v2.0";
532
- var acceptedProtocolVersions = ["v1.1", currentProtocolVersion];
533
- function isAcceptedProtocolVersion(version2) {
534
- return acceptedProtocolVersions.includes(version2);
535
- }
536
- var ControlMessageHandshakeRequestSchema = import_typebox.Type.Object({
537
- type: import_typebox.Type.Literal("HANDSHAKE_REQ"),
538
- protocolVersion: import_typebox.Type.String(),
539
- sessionId: import_typebox.Type.String(),
540
- /**
541
- * Specifies what the server's expected session state (from the pov of the client). This can be
542
- * used by the server to know whether this is a new or a reestablished connection, and whether it
543
- * is compatible with what it already has.
544
- */
545
- expectedSessionState: import_typebox.Type.Object({
546
- // what the client expects the server to send next
547
- nextExpectedSeq: import_typebox.Type.Integer(),
548
- nextSentSeq: import_typebox.Type.Integer()
549
- }),
550
- metadata: import_typebox.Type.Optional(import_typebox.Type.Unknown())
551
- });
552
- var HandshakeErrorRetriableResponseCodes = import_typebox.Type.Union([
553
- import_typebox.Type.Literal("SESSION_STATE_MISMATCH")
554
- ]);
555
- var HandshakeErrorCustomHandlerFatalResponseCodes = import_typebox.Type.Union([
556
- // The custom validation handler rejected the handler because the client is unsupported.
557
- import_typebox.Type.Literal("REJECTED_UNSUPPORTED_CLIENT"),
558
- // The custom validation handler rejected the handshake.
559
- import_typebox.Type.Literal("REJECTED_BY_CUSTOM_HANDLER")
560
- ]);
561
- var HandshakeErrorFatalResponseCodes = import_typebox.Type.Union([
562
- HandshakeErrorCustomHandlerFatalResponseCodes,
563
- // The ciient sent a handshake that doesn't comply with the extended handshake metadata.
564
- import_typebox.Type.Literal("MALFORMED_HANDSHAKE_META"),
565
- // The ciient sent a handshake that doesn't comply with ControlMessageHandshakeRequestSchema.
566
- import_typebox.Type.Literal("MALFORMED_HANDSHAKE"),
567
- // The client's protocol version does not match the server's.
568
- import_typebox.Type.Literal("PROTOCOL_VERSION_MISMATCH")
569
- ]);
570
- var HandshakeErrorResponseCodes = import_typebox.Type.Union([
571
- HandshakeErrorRetriableResponseCodes,
572
- HandshakeErrorFatalResponseCodes
573
- ]);
574
- var ControlMessageHandshakeResponseSchema = import_typebox.Type.Object({
575
- type: import_typebox.Type.Literal("HANDSHAKE_RESP"),
576
- status: import_typebox.Type.Union([
577
- import_typebox.Type.Object({
578
- ok: import_typebox.Type.Literal(true),
579
- sessionId: import_typebox.Type.String()
580
- }),
581
- import_typebox.Type.Object({
582
- ok: import_typebox.Type.Literal(false),
583
- reason: import_typebox.Type.String(),
584
- code: HandshakeErrorResponseCodes
585
- })
586
- ])
587
- });
588
- var ControlMessagePayloadSchema = import_typebox.Type.Union([
589
- ControlMessageCloseSchema,
590
- ControlMessageAckSchema,
591
- ControlMessageHandshakeRequestSchema,
592
- ControlMessageHandshakeResponseSchema
593
- ]);
594
- var OpaqueTransportMessageSchema = TransportMessageSchema(
595
- import_typebox.Type.Unknown()
596
- );
597
- function handshakeRequestMessage({
598
- from,
599
- to,
600
- sessionId,
601
- expectedSessionState,
602
- metadata,
603
- tracing
604
- }) {
605
- return {
606
- id: generateId(),
607
- from,
608
- to,
609
- seq: 0,
610
- ack: 0,
611
- streamId: generateId(),
612
- controlFlags: 0,
613
- tracing,
614
- payload: {
615
- type: "HANDSHAKE_REQ",
616
- protocolVersion: currentProtocolVersion,
617
- sessionId,
618
- expectedSessionState,
619
- metadata
620
- }
621
- };
622
- }
623
- function handshakeResponseMessage({
624
- from,
625
- to,
626
- status
627
- }) {
628
- return {
629
- id: generateId(),
630
- from,
631
- to,
632
- seq: 0,
633
- ack: 0,
634
- streamId: generateId(),
635
- controlFlags: 0,
636
- payload: {
637
- type: "HANDSHAKE_RESP",
638
- status
639
- }
640
- };
641
- }
642
- function isAck(controlFlag) {
643
- return (controlFlag & 1 /* AckBit */) === 1 /* AckBit */;
644
- }
645
-
646
- // transport/stringifyError.ts
647
- function coerceErrorString(err) {
648
- if (err instanceof Error) {
649
- return err.message || "unknown reason";
650
- }
651
- return `[coerced to error] ${String(err)}`;
652
- }
653
-
654
- // package.json
655
- var version = "0.216.1";
656
-
657
- // tracing/index.ts
658
- function getPropagationContext(ctx) {
659
- const tracing = {
660
- traceparent: "",
661
- tracestate: ""
662
- };
663
- import_api2.propagation.inject(ctx, tracing);
664
- return tracing;
665
- }
666
- function createSessionTelemetryInfo(tracer, sessionId, to, from, propagationCtx) {
667
- const parentCtx = propagationCtx ? import_api2.propagation.extract(import_api2.context.active(), propagationCtx) : import_api2.context.active();
668
- const span = tracer.startSpan(
669
- `river.session`,
670
- {
671
- attributes: {
672
- component: "river",
673
- "river.session.id": sessionId,
674
- "river.session.to": to,
675
- "river.session.from": from
676
- }
677
- },
678
- parentCtx
679
- );
680
- const ctx = import_api2.trace.setSpan(parentCtx, span);
681
- return { span, ctx };
682
- }
683
- function createConnectionTelemetryInfo(tracer, connection, info) {
684
- const span = tracer.startSpan(
685
- `river.connection`,
686
- {
687
- attributes: {
688
- component: "river",
689
- "river.connection.id": connection.id
690
- },
691
- links: [{ context: info.span.spanContext() }]
692
- },
693
- info.ctx
694
- );
695
- const ctx = import_api2.trace.setSpan(info.ctx, span);
696
- return { span, ctx };
697
- }
698
- function getTracer() {
699
- return import_api2.trace.getTracer("river", version);
700
- }
701
-
702
- // transport/sessionStateMachine/SessionWaitingForHandshake.ts
703
- var SessionWaitingForHandshake = class extends CommonSession {
704
- state = "WaitingForHandshake" /* WaitingForHandshake */;
705
- conn;
706
- listeners;
707
- handshakeTimeout;
708
- constructor(props) {
709
- super(props);
710
- this.conn = props.conn;
711
- this.listeners = props.listeners;
712
- this.handshakeTimeout = setTimeout(() => {
713
- this.listeners.onHandshakeTimeout();
714
- }, this.options.handshakeTimeoutMs);
715
- this.conn.setDataListener(this.onHandshakeData);
716
- this.conn.setErrorListener(this.listeners.onConnectionErrored);
717
- this.conn.setCloseListener(this.listeners.onConnectionClosed);
718
- }
719
- get loggingMetadata() {
720
- return {
721
- clientId: this.from,
722
- connId: this.conn.id,
723
- ...this.conn.loggingMetadata
724
- };
725
- }
726
- onHandshakeData = (msg) => {
727
- const parsedMsgRes = this.codec.fromBuffer(msg);
728
- if (!parsedMsgRes.ok) {
729
- this.listeners.onInvalidHandshake(
730
- `could not parse handshake message: ${parsedMsgRes.reason}`,
731
- "MALFORMED_HANDSHAKE"
732
- );
733
- return;
734
- }
735
- this.listeners.onHandshake(parsedMsgRes.value);
736
- };
737
- sendHandshake(msg) {
738
- const buff = this.codec.toBuffer(msg);
739
- if (!buff.ok) {
740
- return buff;
741
- }
742
- const sent = this.conn.send(buff.value);
743
- if (!sent) {
744
- return {
745
- ok: false,
746
- reason: "failed to send handshake"
747
- };
748
- }
749
- return {
750
- ok: true,
751
- value: msg.id
752
- };
753
- }
754
- _handleStateExit() {
755
- this.conn.removeDataListener();
756
- this.conn.removeErrorListener();
757
- this.conn.removeCloseListener();
758
- clearTimeout(this.handshakeTimeout);
759
- this.handshakeTimeout = void 0;
760
- }
761
- _handleClose() {
762
- this.conn.close();
763
- }
764
- };
765
-
766
- // transport/sessionStateMachine/SessionHandshaking.ts
767
- var SessionHandshaking = class extends IdentifiedSessionWithGracePeriod {
768
- state = "Handshaking" /* Handshaking */;
769
- conn;
770
- listeners;
771
- handshakeTimeout;
772
- constructor(props) {
773
- super(props);
774
- this.conn = props.conn;
775
- this.listeners = props.listeners;
776
- this.handshakeTimeout = setTimeout(() => {
777
- this.listeners.onHandshakeTimeout();
778
- }, this.options.handshakeTimeoutMs);
779
- this.conn.setDataListener(this.onHandshakeData);
780
- this.conn.setErrorListener(this.listeners.onConnectionErrored);
781
- this.conn.setCloseListener(this.listeners.onConnectionClosed);
782
- }
783
- get loggingMetadata() {
784
- return {
785
- ...super.loggingMetadata,
786
- ...this.conn.loggingMetadata
787
- };
788
- }
789
- onHandshakeData = (msg) => {
790
- const parsedMsgRes = this.codec.fromBuffer(msg);
791
- if (!parsedMsgRes.ok) {
792
- this.listeners.onInvalidHandshake(
793
- `could not parse handshake message: ${parsedMsgRes.reason}`,
794
- "MALFORMED_HANDSHAKE"
795
- );
796
- return;
797
- }
798
- this.listeners.onHandshake(parsedMsgRes.value);
799
- };
800
- sendHandshake(msg) {
801
- const buff = this.codec.toBuffer(msg);
802
- if (!buff.ok) {
803
- return buff;
804
- }
805
- const sent = this.conn.send(buff.value);
806
- if (!sent) {
807
- return {
808
- ok: false,
809
- reason: "failed to send handshake"
810
- };
811
- }
812
- return {
813
- ok: true,
814
- value: msg.id
815
- };
816
- }
817
- _handleStateExit() {
818
- super._handleStateExit();
819
- this.conn.removeDataListener();
820
- this.conn.removeErrorListener();
821
- this.conn.removeCloseListener();
822
- if (this.handshakeTimeout) {
823
- clearTimeout(this.handshakeTimeout);
824
- this.handshakeTimeout = void 0;
825
- }
826
- }
827
- _handleClose() {
828
- super._handleClose();
829
- this.conn.close();
830
- }
831
- };
832
-
833
- // transport/sessionStateMachine/SessionConnected.ts
834
- var import_api3 = require("@opentelemetry/api");
835
- var SessionConnected = class extends IdentifiedSession {
836
- state = "Connected" /* Connected */;
837
- conn;
838
- listeners;
839
- heartbeatHandle;
840
- heartbeatMissTimeout;
841
- isActivelyHeartbeating = false;
842
- updateBookkeeping(ack, seq) {
843
- this.sendBuffer = this.sendBuffer.filter((unacked) => unacked.seq >= ack);
844
- this.ack = seq + 1;
845
- if (this.heartbeatMissTimeout) {
846
- clearTimeout(this.heartbeatMissTimeout);
847
- }
848
- this.startMissingHeartbeatTimeout();
849
- }
850
- assertSendOrdering(encodedMsg) {
851
- if (encodedMsg.seq > this.seqSent + 1) {
852
- const msg = `invariant violation: would have sent out of order msg (seq: ${encodedMsg.seq}, expected: ${this.seqSent} + 1)`;
853
- this.log?.error(msg, {
854
- ...this.loggingMetadata,
855
- tags: ["invariant-violation"]
856
- });
857
- throw new Error(msg);
858
- }
859
- }
860
- send(msg) {
861
- const encodeResult = this.encodeMsg(msg);
862
- if (!encodeResult.ok) {
863
- return encodeResult;
864
- }
865
- const encodedMsg = encodeResult.value;
866
- this.assertSendOrdering(encodedMsg);
867
- this.sendBuffer.push(encodedMsg);
868
- const sent = this.conn.send(encodedMsg.data);
869
- if (!sent) {
870
- const reason = "failed to send message";
871
- this.listeners.onMessageSendFailure(
872
- { ...encodedMsg.msg, seq: encodedMsg.seq },
873
- reason
874
- );
875
- return { ok: false, reason };
876
- }
877
- this.seqSent = encodedMsg.seq;
878
- return { ok: true, value: encodedMsg.id };
879
- }
880
- constructor(props) {
881
- super(props);
882
- this.conn = props.conn;
883
- this.listeners = props.listeners;
884
- this.conn.setDataListener(this.onMessageData);
885
- this.conn.setCloseListener(this.listeners.onConnectionClosed);
886
- this.conn.setErrorListener(this.listeners.onConnectionErrored);
887
- }
888
- sendBufferedMessages() {
889
- if (this.sendBuffer.length > 0) {
890
- this.log?.info(
891
- `sending ${this.sendBuffer.length} buffered messages, starting at seq ${this.nextSeq()}`,
892
- this.loggingMetadata
893
- );
894
- for (const msg of this.sendBuffer) {
895
- this.assertSendOrdering(msg);
896
- const sent = this.conn.send(msg.data);
897
- if (!sent) {
898
- const reason = "failed to send buffered message";
899
- this.listeners.onMessageSendFailure(
900
- { ...msg.msg, seq: msg.seq },
901
- reason
902
- );
903
- return { ok: false, reason };
904
- }
905
- this.seqSent = msg.seq;
906
- }
907
- }
908
- return { ok: true, value: void 0 };
909
- }
910
- get loggingMetadata() {
911
- return {
912
- ...super.loggingMetadata,
913
- ...this.conn.loggingMetadata
914
- };
915
- }
916
- startMissingHeartbeatTimeout() {
917
- const maxMisses = this.options.heartbeatsUntilDead;
918
- const missDuration = maxMisses * this.options.heartbeatIntervalMs;
919
- this.heartbeatMissTimeout = setTimeout(() => {
920
- this.log?.info(
921
- `closing connection to ${this.to} due to inactivity (missed ${maxMisses} heartbeats which is ${missDuration}ms)`,
922
- this.loggingMetadata
923
- );
924
- this.telemetry.span.addEvent(
925
- "closing connection due to missing heartbeat"
926
- );
927
- this.conn.close();
928
- }, missDuration);
929
- }
930
- startActiveHeartbeat() {
931
- this.isActivelyHeartbeating = true;
932
- this.heartbeatHandle = setInterval(() => {
933
- this.sendHeartbeat();
934
- }, this.options.heartbeatIntervalMs);
935
- }
936
- sendHeartbeat() {
937
- this.log?.debug("sending heartbeat", this.loggingMetadata);
938
- const heartbeat = {
939
- streamId: "heartbeat",
940
- controlFlags: 1 /* AckBit */,
941
- payload: {
942
- type: "ACK"
943
- }
944
- };
945
- this.send(heartbeat);
946
- }
947
- onMessageData = (msg) => {
948
- const parsedMsgRes = this.codec.fromBuffer(msg);
949
- if (!parsedMsgRes.ok) {
950
- this.listeners.onInvalidMessage(
951
- `could not parse message: ${parsedMsgRes.reason}`
952
- );
953
- return;
954
- }
955
- const parsedMsg = parsedMsgRes.value;
956
- if (parsedMsg.seq !== this.ack) {
957
- if (parsedMsg.seq < this.ack) {
958
- this.log?.debug(
959
- `received duplicate msg (got seq: ${parsedMsg.seq}, wanted seq: ${this.ack}), discarding`,
960
- {
961
- ...this.loggingMetadata,
962
- transportMessage: parsedMsg
963
- }
964
- );
965
- } else {
966
- const reason = `received out-of-order msg, closing connection (got seq: ${parsedMsg.seq}, wanted seq: ${this.ack})`;
967
- this.log?.error(reason, {
968
- ...this.loggingMetadata,
969
- transportMessage: parsedMsg,
970
- tags: ["invariant-violation"]
971
- });
972
- this.telemetry.span.setStatus({
973
- code: import_api3.SpanStatusCode.ERROR,
974
- message: reason
975
- });
976
- this.conn.close();
977
- }
978
- return;
979
- }
980
- this.log?.debug(`received msg`, {
981
- ...this.loggingMetadata,
982
- transportMessage: parsedMsg
983
- });
984
- this.updateBookkeeping(parsedMsg.ack, parsedMsg.seq);
985
- if (!isAck(parsedMsg.controlFlags)) {
986
- this.listeners.onMessage(parsedMsg);
987
- return;
988
- }
989
- this.log?.debug(`discarding msg (ack bit set)`, {
990
- ...this.loggingMetadata,
991
- transportMessage: parsedMsg
992
- });
993
- if (!this.isActivelyHeartbeating) {
994
- this.sendHeartbeat();
995
- }
996
- };
997
- _handleStateExit() {
998
- super._handleStateExit();
999
- this.conn.removeDataListener();
1000
- this.conn.removeCloseListener();
1001
- this.conn.removeErrorListener();
1002
- if (this.heartbeatHandle) {
1003
- clearInterval(this.heartbeatHandle);
1004
- this.heartbeatHandle = void 0;
1005
- }
1006
- if (this.heartbeatMissTimeout) {
1007
- clearTimeout(this.heartbeatMissTimeout);
1008
- this.heartbeatMissTimeout = void 0;
1009
- }
1010
- }
1011
- _handleClose() {
1012
- super._handleClose();
1013
- this.conn.close();
1014
- }
1015
- };
1016
-
1017
- // transport/sessionStateMachine/SessionBackingOff.ts
1018
- var SessionBackingOff = class extends IdentifiedSessionWithGracePeriod {
1019
- state = "BackingOff" /* BackingOff */;
1020
- listeners;
1021
- backoffTimeout;
1022
- constructor(props) {
1023
- super(props);
1024
- this.listeners = props.listeners;
1025
- this.backoffTimeout = setTimeout(() => {
1026
- this.listeners.onBackoffFinished();
1027
- }, props.backoffMs);
1028
- }
1029
- _handleClose() {
1030
- super._handleClose();
1031
- }
1032
- _handleStateExit() {
1033
- super._handleStateExit();
1034
- if (this.backoffTimeout) {
1035
- clearTimeout(this.backoffTimeout);
1036
- this.backoffTimeout = void 0;
1037
- }
1038
- }
1039
- };
1040
-
1041
- // codec/adapter.ts
1042
- var import_value = require("@sinclair/typebox/value");
1043
- var CodecMessageAdapter = class {
1044
- constructor(codec) {
1045
- this.codec = codec;
1046
- }
1047
- toBuffer(msg) {
1048
- try {
1049
- return {
1050
- ok: true,
1051
- value: this.codec.toBuffer(msg)
1052
- };
1053
- } catch (e) {
1054
- return {
1055
- ok: false,
1056
- reason: coerceErrorString(e)
1057
- };
1058
- }
1059
- }
1060
- fromBuffer(buf) {
1061
- try {
1062
- const parsedMsg = this.codec.fromBuffer(buf);
1063
- if (!import_value.Value.Check(OpaqueTransportMessageSchema, parsedMsg)) {
1064
- return {
1065
- ok: false,
1066
- reason: "transport message schema mismatch"
1067
- };
1068
- }
1069
- return {
1070
- ok: true,
1071
- value: parsedMsg
1072
- };
1073
- } catch (e) {
1074
- return {
1075
- ok: false,
1076
- reason: coerceErrorString(e)
1077
- };
1078
- }
1079
- }
1080
- };
1081
-
1082
- // transport/sessionStateMachine/transitions.ts
1083
- function inheritSharedSession(session) {
1084
- return {
1085
- id: session.id,
1086
- from: session.from,
1087
- to: session.to,
1088
- seq: session.seq,
1089
- ack: session.ack,
1090
- seqSent: session.seqSent,
1091
- sendBuffer: session.sendBuffer,
1092
- telemetry: session.telemetry,
1093
- options: session.options,
1094
- log: session.log,
1095
- tracer: session.tracer,
1096
- protocolVersion: session.protocolVersion,
1097
- codec: session.codec
1098
- };
1099
- }
1100
- function inheritSharedSessionWithGrace(session) {
1101
- return {
1102
- ...inheritSharedSession(session),
1103
- graceExpiryTime: session.graceExpiryTime
1104
- };
1105
- }
1106
- var SessionStateGraph = {
1107
- entrypoints: {
1108
- NoConnection: (to, from, listeners, options, protocolVersion, tracer, log) => {
1109
- const id = `session-${generateId()}`;
1110
- const telemetry = createSessionTelemetryInfo(tracer, id, to, from);
1111
- const sendBuffer = [];
1112
- const session = new SessionNoConnection({
1113
- listeners,
1114
- id,
1115
- from,
1116
- to,
1117
- seq: 0,
1118
- ack: 0,
1119
- seqSent: 0,
1120
- graceExpiryTime: Date.now() + options.sessionDisconnectGraceMs,
1121
- sendBuffer,
1122
- telemetry,
1123
- options,
1124
- protocolVersion,
1125
- tracer,
1126
- log,
1127
- codec: new CodecMessageAdapter(options.codec)
1128
- });
1129
- session.log?.info(`session ${session.id} created in NoConnection state`, {
1130
- ...session.loggingMetadata,
1131
- tags: ["state-transition"]
1132
- });
1133
- return session;
1134
- },
1135
- WaitingForHandshake: (from, conn, listeners, options, tracer, log) => {
1136
- const session = new SessionWaitingForHandshake({
1137
- conn,
1138
- listeners,
1139
- from,
1140
- options,
1141
- tracer,
1142
- log,
1143
- codec: new CodecMessageAdapter(options.codec)
1144
- });
1145
- session.log?.info(`session created in WaitingForHandshake state`, {
1146
- ...session.loggingMetadata,
1147
- tags: ["state-transition"]
1148
- });
1149
- return session;
1150
- }
1151
- },
1152
- // All of the transitions 'move'/'consume' the old session and return a new one.
1153
- // After a session is transitioned, any usage of the old session will throw.
1154
- transition: {
1155
- // happy path transitions
1156
- NoConnectionToBackingOff: (oldSession, backoffMs, listeners) => {
1157
- const carriedState = inheritSharedSessionWithGrace(oldSession);
1158
- oldSession._handleStateExit();
1159
- const session = new SessionBackingOff({
1160
- backoffMs,
1161
- listeners,
1162
- ...carriedState
1163
- });
1164
- session.log?.info(
1165
- `session ${session.id} transition from NoConnection to BackingOff`,
1166
- {
1167
- ...session.loggingMetadata,
1168
- tags: ["state-transition"]
1169
- }
1170
- );
1171
- return session;
1172
- },
1173
- BackingOffToConnecting: (oldSession, connPromise, listeners) => {
1174
- const carriedState = inheritSharedSessionWithGrace(oldSession);
1175
- oldSession._handleStateExit();
1176
- const session = new SessionConnecting({
1177
- connPromise,
1178
- listeners,
1179
- ...carriedState
1180
- });
1181
- session.log?.info(
1182
- `session ${session.id} transition from BackingOff to Connecting`,
1183
- {
1184
- ...session.loggingMetadata,
1185
- tags: ["state-transition"]
1186
- }
1187
- );
1188
- return session;
1189
- },
1190
- ConnectingToHandshaking: (oldSession, conn, listeners) => {
1191
- const carriedState = inheritSharedSessionWithGrace(oldSession);
1192
- oldSession._handleStateExit();
1193
- const session = new SessionHandshaking({
1194
- conn,
1195
- listeners,
1196
- ...carriedState
1197
- });
1198
- conn.telemetry = createConnectionTelemetryInfo(
1199
- session.tracer,
1200
- conn,
1201
- session.telemetry
1202
- );
1203
- session.log?.info(
1204
- `session ${session.id} transition from Connecting to Handshaking`,
1205
- {
1206
- ...session.loggingMetadata,
1207
- tags: ["state-transition"]
1208
- }
1209
- );
1210
- return session;
1211
- },
1212
- HandshakingToConnected: (oldSession, listeners) => {
1213
- const carriedState = inheritSharedSession(oldSession);
1214
- const conn = oldSession.conn;
1215
- oldSession._handleStateExit();
1216
- const session = new SessionConnected({
1217
- conn,
1218
- listeners,
1219
- ...carriedState
1220
- });
1221
- session.startMissingHeartbeatTimeout();
1222
- session.log?.info(
1223
- `session ${session.id} transition from Handshaking to Connected`,
1224
- {
1225
- ...session.loggingMetadata,
1226
- tags: ["state-transition"]
1227
- }
1228
- );
1229
- return session;
1230
- },
1231
- WaitingForHandshakeToConnected: (pendingSession, oldSession, sessionId, to, propagationCtx, listeners, protocolVersion) => {
1232
- const conn = pendingSession.conn;
1233
- const { from, options } = pendingSession;
1234
- const carriedState = oldSession ? (
1235
- // old session exists, inherit state
1236
- inheritSharedSession(oldSession)
1237
- ) : (
1238
- // old session does not exist, create new state
1239
- {
1240
- id: sessionId,
1241
- from,
1242
- to,
1243
- seq: 0,
1244
- ack: 0,
1245
- seqSent: 0,
1246
- sendBuffer: [],
1247
- telemetry: createSessionTelemetryInfo(
1248
- pendingSession.tracer,
1249
- sessionId,
1250
- to,
1251
- from,
1252
- propagationCtx
1253
- ),
1254
- options,
1255
- tracer: pendingSession.tracer,
1256
- log: pendingSession.log,
1257
- protocolVersion,
1258
- codec: new CodecMessageAdapter(options.codec)
1259
- }
1260
- );
1261
- pendingSession._handleStateExit();
1262
- oldSession?._handleStateExit();
1263
- const session = new SessionConnected({
1264
- conn,
1265
- listeners,
1266
- ...carriedState
1267
- });
1268
- session.startMissingHeartbeatTimeout();
1269
- conn.telemetry = createConnectionTelemetryInfo(
1270
- session.tracer,
1271
- conn,
1272
- session.telemetry
1273
- );
1274
- session.log?.info(
1275
- `session ${session.id} transition from WaitingForHandshake to Connected`,
1276
- {
1277
- ...session.loggingMetadata,
1278
- tags: ["state-transition"]
1279
- }
1280
- );
1281
- return session;
1282
- },
1283
- // disconnect paths
1284
- BackingOffToNoConnection: (oldSession, listeners) => {
1285
- const carriedState = inheritSharedSessionWithGrace(oldSession);
1286
- oldSession._handleStateExit();
1287
- const session = new SessionNoConnection({
1288
- listeners,
1289
- ...carriedState
1290
- });
1291
- session.log?.info(
1292
- `session ${session.id} transition from BackingOff to NoConnection`,
1293
- {
1294
- ...session.loggingMetadata,
1295
- tags: ["state-transition"]
1296
- }
1297
- );
1298
- return session;
1299
- },
1300
- ConnectingToNoConnection: (oldSession, listeners) => {
1301
- const carriedState = inheritSharedSessionWithGrace(oldSession);
1302
- oldSession.bestEffortClose();
1303
- oldSession._handleStateExit();
1304
- const session = new SessionNoConnection({
1305
- listeners,
1306
- ...carriedState
1307
- });
1308
- session.log?.info(
1309
- `session ${session.id} transition from Connecting to NoConnection`,
1310
- {
1311
- ...session.loggingMetadata,
1312
- tags: ["state-transition"]
1313
- }
1314
- );
1315
- return session;
1316
- },
1317
- HandshakingToNoConnection: (oldSession, listeners) => {
1318
- const carriedState = inheritSharedSessionWithGrace(oldSession);
1319
- oldSession.conn.close();
1320
- oldSession._handleStateExit();
1321
- const session = new SessionNoConnection({
1322
- listeners,
1323
- ...carriedState
1324
- });
1325
- session.log?.info(
1326
- `session ${session.id} transition from Handshaking to NoConnection`,
1327
- {
1328
- ...session.loggingMetadata,
1329
- tags: ["state-transition"]
1330
- }
1331
- );
1332
- return session;
1333
- },
1334
- ConnectedToNoConnection: (oldSession, listeners) => {
1335
- const carriedState = inheritSharedSession(oldSession);
1336
- const graceExpiryTime = Date.now() + oldSession.options.sessionDisconnectGraceMs;
1337
- oldSession.conn.close();
1338
- oldSession._handleStateExit();
1339
- const session = new SessionNoConnection({
1340
- listeners,
1341
- graceExpiryTime,
1342
- ...carriedState
1343
- });
1344
- session.log?.info(
1345
- `session ${session.id} transition from Connected to NoConnection`,
1346
- {
1347
- ...session.loggingMetadata,
1348
- tags: ["state-transition"]
1349
- }
1350
- );
1351
- return session;
1352
- }
1353
- }
1354
- };
1355
- var transitions = SessionStateGraph.transition;
1356
- var ClientSessionStateGraph = {
1357
- entrypoint: SessionStateGraph.entrypoints.NoConnection,
1358
- transition: {
1359
- // happy paths
1360
- // NoConnection -> BackingOff: attempt to connect
1361
- NoConnectionToBackingOff: transitions.NoConnectionToBackingOff,
1362
- // BackingOff -> Connecting: backoff period elapsed, start connection
1363
- BackingOffToConnecting: transitions.BackingOffToConnecting,
1364
- // Connecting -> Handshaking: connection established, start handshake
1365
- ConnectingToHandshaking: transitions.ConnectingToHandshaking,
1366
- // Handshaking -> Connected: handshake complete, session ready
1367
- HandshakingToConnected: transitions.HandshakingToConnected,
1368
- // disconnect paths
1369
- // BackingOff -> NoConnection: unused
1370
- BackingOffToNoConnection: transitions.BackingOffToNoConnection,
1371
- // Connecting -> NoConnection: connection failed or connection timeout
1372
- ConnectingToNoConnection: transitions.ConnectingToNoConnection,
1373
- // Handshaking -> NoConnection: connection closed or handshake timeout
1374
- HandshakingToNoConnection: transitions.HandshakingToNoConnection,
1375
- // Connected -> NoConnection: connection closed
1376
- ConnectedToNoConnection: transitions.ConnectedToNoConnection
1377
- // destroy/close paths
1378
- // NoConnection -> x: grace period elapsed
1379
- // BackingOff -> x: grace period elapsed
1380
- // Connecting -> x: grace period elapsed
1381
- // Handshaking -> x: grace period elapsed or invalid handshake message or handshake rejection
1382
- // Connected -> x: grace period elapsed or invalid message
1383
- }
1384
- };
1385
- var ServerSessionStateGraph = {
1386
- entrypoint: SessionStateGraph.entrypoints.WaitingForHandshake,
1387
- transition: {
1388
- // happy paths
1389
- // WaitingForHandshake -> Connected: handshake complete, session ready
1390
- WaitingForHandshakeToConnected: transitions.WaitingForHandshakeToConnected,
1391
- // disconnect paths
1392
- // Connected -> NoConnection: connection closed
1393
- ConnectedToNoConnection: transitions.ConnectedToNoConnection
1394
- // destroy/close paths
1395
- // WaitingForHandshake -> x: handshake timeout elapsed or invalid handshake message or handshake rejection or connection closed
1396
- }
1397
- };
1398
-
1399
- // transport/transport.ts
1400
- var Transport = class {
1401
- /**
1402
- * The status of the transport.
1403
- */
1404
- status;
1405
- /**
1406
- * The client ID of this transport.
1407
- */
1408
- clientId;
1409
- /**
1410
- * The event dispatcher for handling events of type EventTypes.
1411
- */
1412
- eventDispatcher;
1413
- /**
1414
- * The options for this transport.
1415
- */
1416
- options;
1417
- log;
1418
- tracer;
1419
- sessions;
1420
- /**
1421
- * Creates a new Transport instance.
1422
- * @param codec The codec used to encode and decode messages.
1423
- * @param clientId The client ID of this transport.
1424
- */
1425
- constructor(clientId, providedOptions) {
1426
- this.options = { ...defaultTransportOptions, ...providedOptions };
1427
- this.eventDispatcher = new EventDispatcher();
1428
- this.clientId = clientId;
1429
- this.status = "open";
1430
- this.sessions = /* @__PURE__ */ new Map();
1431
- this.tracer = getTracer();
1432
- }
1433
- bindLogger(fn, level) {
1434
- if (typeof fn === "function") {
1435
- this.log = createLogProxy(new BaseLogger(fn, level));
1436
- return;
1437
- }
1438
- this.log = createLogProxy(fn);
1439
- }
1440
- /**
1441
- * Called when a message is received by this transport.
1442
- * You generally shouldn't need to override this in downstream transport implementations.
1443
- * @param message The received message.
1444
- */
1445
- handleMsg(message) {
1446
- if (this.getStatus() !== "open") return;
1447
- this.eventDispatcher.dispatchEvent("message", message);
1448
- }
1449
- /**
1450
- * Adds a listener to this transport.
1451
- * @param the type of event to listen for
1452
- * @param handler The message handler to add.
1453
- */
1454
- addEventListener(type, handler) {
1455
- this.eventDispatcher.addEventListener(type, handler);
1456
- }
1457
- /**
1458
- * Removes a listener from this transport.
1459
- * @param the type of event to un-listen on
1460
- * @param handler The message handler to remove.
1461
- */
1462
- removeEventListener(type, handler) {
1463
- this.eventDispatcher.removeEventListener(type, handler);
1464
- }
1465
- protocolError(message) {
1466
- this.eventDispatcher.dispatchEvent("protocolError", message);
1467
- }
1468
- /**
1469
- * Default close implementation for transports. You should override this in the downstream
1470
- * implementation if you need to do any additional cleanup and call super.close() at the end.
1471
- * Closes the transport. Any messages sent while the transport is closed will be silently discarded.
1472
- */
1473
- close() {
1474
- this.status = "closed";
1475
- const sessions = Array.from(this.sessions.values());
1476
- for (const session of sessions) {
1477
- this.deleteSession(session);
1478
- }
1479
- this.eventDispatcher.dispatchEvent("transportStatus", {
1480
- status: this.status
1481
- });
1482
- this.eventDispatcher.removeAllListeners();
1483
- this.log?.info(`manually closed transport`, { clientId: this.clientId });
1484
- }
1485
- getStatus() {
1486
- return this.status;
1487
- }
1488
- // state transitions
1489
- createSession(session) {
1490
- const activeSession = this.sessions.get(session.to);
1491
- if (activeSession) {
1492
- const msg = `attempt to create session for ${session.to} but active session (${activeSession.id}) already exists`;
1493
- this.log?.error(msg, {
1494
- ...session.loggingMetadata,
1495
- tags: ["invariant-violation"]
1496
- });
1497
- throw new Error(msg);
1498
- }
1499
- this.sessions.set(session.to, session);
1500
- this.eventDispatcher.dispatchEvent("sessionStatus", {
1501
- status: "created",
1502
- session
1503
- });
1504
- this.eventDispatcher.dispatchEvent("sessionTransition", {
1505
- state: session.state,
1506
- id: session.id
1507
- });
1508
- }
1509
- updateSession(session) {
1510
- const activeSession = this.sessions.get(session.to);
1511
- if (!activeSession) {
1512
- const msg = `attempt to transition session for ${session.to} but no active session exists`;
1513
- this.log?.error(msg, {
1514
- ...session.loggingMetadata,
1515
- tags: ["invariant-violation"]
1516
- });
1517
- throw new Error(msg);
1518
- }
1519
- if (activeSession.id !== session.id) {
1520
- const msg = `attempt to transition active session for ${session.to} but active session (${activeSession.id}) is different from handle (${session.id})`;
1521
- this.log?.error(msg, {
1522
- ...session.loggingMetadata,
1523
- tags: ["invariant-violation"]
1524
- });
1525
- throw new Error(msg);
1526
- }
1527
- this.sessions.set(session.to, session);
1528
- this.eventDispatcher.dispatchEvent("sessionTransition", {
1529
- state: session.state,
1530
- id: session.id
1531
- });
1532
- }
1533
- deleteSession(session, options) {
1534
- if (session._isConsumed) return;
1535
- const loggingMetadata = session.loggingMetadata;
1536
- if (loggingMetadata.tags && options?.unhealthy) {
1537
- loggingMetadata.tags.push("unhealthy-session");
1538
- }
1539
- session.log?.info(`closing session ${session.id}`, loggingMetadata);
1540
- this.eventDispatcher.dispatchEvent("sessionStatus", {
1541
- status: "closing",
1542
- session
1543
- });
1544
- const to = session.to;
1545
- session.close();
1546
- this.sessions.delete(to);
1547
- this.eventDispatcher.dispatchEvent("sessionStatus", {
1548
- status: "closed",
1549
- session: { id: session.id, to }
1550
- });
1551
- }
1552
- // common listeners
1553
- onSessionGracePeriodElapsed(session) {
1554
- this.log?.info(
1555
- `session to ${session.to} grace period elapsed, closing`,
1556
- session.loggingMetadata
1557
- );
1558
- this.deleteSession(session);
1559
- }
1560
- onConnectingFailed(session) {
1561
- const noConnectionSession = SessionStateGraph.transition.ConnectingToNoConnection(session, {
1562
- onSessionGracePeriodElapsed: () => {
1563
- this.onSessionGracePeriodElapsed(noConnectionSession);
1564
- },
1565
- onMessageSendFailure: (msg, reason) => {
1566
- this.log?.error(`failed to send message: ${reason}`, {
1567
- ...noConnectionSession.loggingMetadata,
1568
- transportMessage: msg
1569
- });
1570
- this.protocolError({
1571
- type: ProtocolError.MessageSendFailure,
1572
- message: reason
1573
- });
1574
- this.deleteSession(noConnectionSession, { unhealthy: true });
1575
- }
1576
- });
1577
- this.updateSession(noConnectionSession);
1578
- return noConnectionSession;
1579
- }
1580
- onConnClosed(session) {
1581
- let noConnectionSession;
1582
- const listeners = {
1583
- onSessionGracePeriodElapsed: () => {
1584
- this.onSessionGracePeriodElapsed(noConnectionSession);
1585
- },
1586
- onMessageSendFailure: (msg, reason) => {
1587
- this.log?.error(`failed to send message: ${reason}`, {
1588
- ...noConnectionSession.loggingMetadata,
1589
- transportMessage: msg
1590
- });
1591
- this.protocolError({
1592
- type: ProtocolError.MessageSendFailure,
1593
- message: reason
1594
- });
1595
- this.deleteSession(noConnectionSession, { unhealthy: true });
1596
- }
1597
- };
1598
- if (session.state === "Handshaking" /* Handshaking */) {
1599
- noConnectionSession = SessionStateGraph.transition.HandshakingToNoConnection(
1600
- session,
1601
- listeners
1602
- );
1603
- } else {
1604
- noConnectionSession = SessionStateGraph.transition.ConnectedToNoConnection(
1605
- session,
1606
- listeners
1607
- );
1608
- }
1609
- this.updateSession(noConnectionSession);
1610
- return noConnectionSession;
1611
- }
1612
- /**
1613
- * Gets a send closure scoped to a specific session. Sending using the returned
1614
- * closure after the session has transitioned to a different state will be a noop.
1615
- *
1616
- * Session objects themselves can become stale as they transition between
1617
- * states. As stale sessions cannot be used again (and will throw), holding
1618
- * onto a session object is not recommended.
1619
- */
1620
- getSessionBoundSendFn(to, sessionId) {
1621
- if (this.getStatus() !== "open") {
1622
- throw new Error("cannot get a bound send function on a closed transport");
1623
- }
1624
- return (msg) => {
1625
- const session = this.sessions.get(to);
1626
- if (!session) {
1627
- throw new Error(
1628
- `session scope for ${sessionId} has ended (close), can't send`
1629
- );
1630
- }
1631
- const sameSession = session.id === sessionId;
1632
- if (!sameSession || session._isConsumed) {
1633
- throw new Error(
1634
- `session scope for ${sessionId} has ended (transition), can't send`
1635
- );
1636
- }
1637
- const res = session.send(msg);
1638
- if (!res.ok) {
1639
- throw new Error(res.reason);
1640
- }
1641
- return res.value;
1642
- };
1643
- }
1644
- };
1645
-
1646
- // transport/client.ts
1647
- var import_api4 = require("@opentelemetry/api");
1648
-
1649
- // transport/rateLimit.ts
1650
- var LeakyBucketRateLimit = class {
1651
- budgetConsumed;
1652
- intervalHandle;
1653
- options;
1654
- constructor(options) {
1655
- this.options = options;
1656
- this.budgetConsumed = 0;
1657
- }
1658
- getBackoffMs() {
1659
- if (this.getBudgetConsumed() === 0) {
1660
- return 0;
1661
- }
1662
- const exponent = Math.max(0, this.getBudgetConsumed() - 1);
1663
- const jitter = Math.floor(Math.random() * this.options.maxJitterMs);
1664
- const backoffMs = Math.min(
1665
- this.options.baseIntervalMs * 2 ** exponent,
1666
- this.options.maxBackoffMs
1667
- );
1668
- return backoffMs + jitter;
1669
- }
1670
- get totalBudgetRestoreTime() {
1671
- return this.options.budgetRestoreIntervalMs * this.options.attemptBudgetCapacity;
1672
- }
1673
- consumeBudget() {
1674
- this.stopLeak();
1675
- this.budgetConsumed = this.getBudgetConsumed() + 1;
1676
- }
1677
- getBudgetConsumed() {
1678
- return this.budgetConsumed;
1679
- }
1680
- hasBudget() {
1681
- return this.getBudgetConsumed() < this.options.attemptBudgetCapacity;
1682
- }
1683
- startRestoringBudget() {
1684
- if (this.intervalHandle) {
1685
- return;
1686
- }
1687
- const restoreBudgetForUser = () => {
1688
- const currentBudget = this.budgetConsumed;
1689
- if (!currentBudget) {
1690
- this.stopLeak();
1691
- return;
1692
- }
1693
- const newBudget = currentBudget - 1;
1694
- if (newBudget === 0) {
1695
- return;
1696
- }
1697
- this.budgetConsumed = newBudget;
1698
- };
1699
- this.intervalHandle = setInterval(
1700
- restoreBudgetForUser,
1701
- this.options.budgetRestoreIntervalMs
1702
- );
1703
- }
1704
- stopLeak() {
1705
- if (!this.intervalHandle) {
1706
- return;
1707
- }
1708
- clearInterval(this.intervalHandle);
1709
- this.intervalHandle = void 0;
1710
- }
1711
- resetBudget() {
1712
- this.stopLeak();
1713
- this.budgetConsumed = 0;
1714
- }
1715
- close() {
1716
- this.stopLeak();
1717
- }
1718
- };
1719
-
1720
- // transport/client.ts
1721
- var import_value2 = require("@sinclair/typebox/value");
1722
- var ClientTransport = class extends Transport {
1723
- /**
1724
- * The options for this transport.
1725
- */
1726
- options;
1727
- retryBudget;
1728
- /**
1729
- * A flag indicating whether the transport should automatically reconnect
1730
- * when a connection is dropped.
1731
- * Realistically, this should always be true for clients unless you are writing
1732
- * tests or a special case where you don't want to reconnect.
1733
- */
1734
- reconnectOnConnectionDrop = true;
1735
- /**
1736
- * Optional handshake options for this client.
1737
- */
1738
- handshakeExtensions;
1739
- sessions;
1740
- constructor(clientId, providedOptions) {
1741
- super(clientId, providedOptions);
1742
- this.sessions = /* @__PURE__ */ new Map();
1743
- this.options = {
1744
- ...defaultClientTransportOptions,
1745
- ...providedOptions
1746
- };
1747
- this.retryBudget = new LeakyBucketRateLimit(this.options);
1748
- }
1749
- extendHandshake(options) {
1750
- this.handshakeExtensions = options;
1751
- }
1752
- tryReconnecting(to) {
1753
- const oldSession = this.sessions.get(to);
1754
- if (!this.options.enableTransparentSessionReconnects && oldSession) {
1755
- this.deleteSession(oldSession);
1756
- }
1757
- if (this.reconnectOnConnectionDrop && this.getStatus() === "open") {
1758
- this.connect(to);
1759
- }
1760
- }
1761
- /*
1762
- * Creates a raw unconnected session object.
1763
- * This is mostly a River internal, you shouldn't need to use this directly.
1764
- */
1765
- createUnconnectedSession(to) {
1766
- const session = ClientSessionStateGraph.entrypoint(
1767
- to,
1768
- this.clientId,
1769
- {
1770
- onSessionGracePeriodElapsed: () => {
1771
- this.onSessionGracePeriodElapsed(session);
1772
- },
1773
- onMessageSendFailure: (msg, reason) => {
1774
- this.log?.error(`failed to send message: ${reason}`, {
1775
- ...session.loggingMetadata,
1776
- transportMessage: msg
1777
- });
1778
- this.protocolError({
1779
- type: ProtocolError.MessageSendFailure,
1780
- message: reason
1781
- });
1782
- this.deleteSession(session, { unhealthy: true });
1783
- }
1784
- },
1785
- this.options,
1786
- currentProtocolVersion,
1787
- this.tracer,
1788
- this.log
1789
- );
1790
- this.createSession(session);
1791
- return session;
1792
- }
1793
- // listeners
1794
- onConnectingFailed(session) {
1795
- const noConnectionSession = super.onConnectingFailed(session);
1796
- this.tryReconnecting(noConnectionSession.to);
1797
- return noConnectionSession;
1798
- }
1799
- onConnClosed(session) {
1800
- const noConnectionSession = super.onConnClosed(session);
1801
- this.tryReconnecting(noConnectionSession.to);
1802
- return noConnectionSession;
1803
- }
1804
- onConnectionEstablished(session, conn) {
1805
- const handshakingSession = ClientSessionStateGraph.transition.ConnectingToHandshaking(
1806
- session,
1807
- conn,
1808
- {
1809
- onConnectionErrored: (err) => {
1810
- const errStr = coerceErrorString(err);
1811
- this.log?.error(
1812
- `connection to ${handshakingSession.to} errored during handshake: ${errStr}`,
1813
- handshakingSession.loggingMetadata
1814
- );
1815
- },
1816
- onConnectionClosed: () => {
1817
- this.log?.warn(
1818
- `connection to ${handshakingSession.to} closed during handshake`,
1819
- handshakingSession.loggingMetadata
1820
- );
1821
- this.onConnClosed(handshakingSession);
1822
- },
1823
- onHandshake: (msg) => {
1824
- this.onHandshakeResponse(handshakingSession, msg);
1825
- },
1826
- onInvalidHandshake: (reason, code) => {
1827
- this.log?.error(
1828
- `invalid handshake: ${reason}`,
1829
- handshakingSession.loggingMetadata
1830
- );
1831
- this.deleteSession(session, { unhealthy: true });
1832
- this.protocolError({
1833
- type: ProtocolError.HandshakeFailed,
1834
- code,
1835
- message: reason
1836
- });
1837
- },
1838
- onHandshakeTimeout: () => {
1839
- this.log?.error(
1840
- `connection to ${handshakingSession.to} timed out during handshake`,
1841
- handshakingSession.loggingMetadata
1842
- );
1843
- this.onConnClosed(handshakingSession);
1844
- },
1845
- onSessionGracePeriodElapsed: () => {
1846
- this.onSessionGracePeriodElapsed(handshakingSession);
1847
- },
1848
- onMessageSendFailure: (msg, reason) => {
1849
- this.log?.error(`failed to send message: ${reason}`, {
1850
- ...handshakingSession.loggingMetadata,
1851
- transportMessage: msg
1852
- });
1853
- this.protocolError({
1854
- type: ProtocolError.MessageSendFailure,
1855
- message: reason
1856
- });
1857
- this.deleteSession(handshakingSession, { unhealthy: true });
1858
- }
1859
- }
1860
- );
1861
- this.updateSession(handshakingSession);
1862
- void this.sendHandshake(handshakingSession);
1863
- return handshakingSession;
1864
- }
1865
- rejectHandshakeResponse(session, reason, metadata) {
1866
- session.conn.telemetry?.span.setStatus({
1867
- code: import_api4.SpanStatusCode.ERROR,
1868
- message: reason
1869
- });
1870
- this.log?.warn(reason, metadata);
1871
- this.deleteSession(session, { unhealthy: true });
1872
- }
1873
- onHandshakeResponse(session, msg) {
1874
- if (!import_value2.Value.Check(ControlMessageHandshakeResponseSchema, msg.payload)) {
1875
- const reason = `received invalid handshake response`;
1876
- this.rejectHandshakeResponse(session, reason, {
1877
- ...session.loggingMetadata,
1878
- transportMessage: msg,
1879
- validationErrors: [
1880
- ...import_value2.Value.Errors(ControlMessageHandshakeResponseSchema, msg.payload)
1881
- ]
1882
- });
1883
- return;
1884
- }
1885
- if (!msg.payload.status.ok) {
1886
- const retriable = import_value2.Value.Check(
1887
- HandshakeErrorRetriableResponseCodes,
1888
- msg.payload.status.code
1889
- );
1890
- const reason = `handshake failed: ${msg.payload.status.reason}`;
1891
- const to = session.to;
1892
- this.rejectHandshakeResponse(session, reason, {
1893
- ...session.loggingMetadata,
1894
- transportMessage: msg
1895
- });
1896
- if (retriable) {
1897
- this.tryReconnecting(to);
1898
- } else {
1899
- this.protocolError({
1900
- type: ProtocolError.HandshakeFailed,
1901
- code: msg.payload.status.code,
1902
- message: reason
1903
- });
1904
- }
1905
- return;
1906
- }
1907
- if (msg.payload.status.sessionId !== session.id) {
1908
- const reason = `session id mismatch: expected ${session.id}, got ${msg.payload.status.sessionId}`;
1909
- this.rejectHandshakeResponse(session, reason, {
1910
- ...session.loggingMetadata,
1911
- transportMessage: msg
1912
- });
1913
- return;
1914
- }
1915
- this.log?.info(`handshake from ${msg.from} ok`, {
1916
- ...session.loggingMetadata,
1917
- transportMessage: msg
1918
- });
1919
- const connectedSession = ClientSessionStateGraph.transition.HandshakingToConnected(session, {
1920
- onConnectionErrored: (err) => {
1921
- const errStr = coerceErrorString(err);
1922
- if (err instanceof Error && this.options.isFatalConnectionError(err)) {
1923
- this.log?.warn(
1924
- `connection to ${connectedSession.to} fatally errored: ${errStr}`,
1925
- connectedSession.loggingMetadata
1926
- );
1927
- this.reconnectOnConnectionDrop = false;
1928
- } else {
1929
- this.log?.warn(
1930
- `connection to ${connectedSession.to} errored: ${errStr}`,
1931
- connectedSession.loggingMetadata
1932
- );
1933
- }
1934
- },
1935
- onConnectionClosed: () => {
1936
- this.log?.info(
1937
- `connection to ${connectedSession.to} closed`,
1938
- connectedSession.loggingMetadata
1939
- );
1940
- this.onConnClosed(connectedSession);
1941
- },
1942
- onMessage: (msg2) => {
1943
- this.handleMsg(msg2);
1944
- },
1945
- onInvalidMessage: (reason) => {
1946
- this.log?.error(`invalid message: ${reason}`, {
1947
- ...connectedSession.loggingMetadata,
1948
- transportMessage: msg
1949
- });
1950
- this.protocolError({
1951
- type: ProtocolError.InvalidMessage,
1952
- message: reason
1953
- });
1954
- this.deleteSession(connectedSession, { unhealthy: true });
1955
- },
1956
- onMessageSendFailure: (msg2, reason) => {
1957
- this.log?.error(`failed to send message: ${reason}`, {
1958
- ...connectedSession.loggingMetadata,
1959
- transportMessage: msg2
1960
- });
1961
- this.protocolError({
1962
- type: ProtocolError.MessageSendFailure,
1963
- message: reason
1964
- });
1965
- this.deleteSession(connectedSession, { unhealthy: true });
1966
- }
1967
- });
1968
- const res = connectedSession.sendBufferedMessages();
1969
- if (!res.ok) {
1970
- return;
1971
- }
1972
- this.updateSession(connectedSession);
1973
- this.retryBudget.startRestoringBudget();
1974
- }
1975
- /**
1976
- * Manually attempts to connect to a client.
1977
- * @param to The client ID of the node to connect to.
1978
- */
1979
- connect(to) {
1980
- if (this.getStatus() !== "open") {
1981
- this.log?.info(
1982
- `transport state is no longer open, cancelling attempt to connect to ${to}`
1983
- );
1984
- return;
1985
- }
1986
- const session = this.sessions.get(to) ?? this.createUnconnectedSession(to);
1987
- if (session.state !== "NoConnection" /* NoConnection */) {
1988
- this.log?.debug(
1989
- `session to ${to} has state ${session.state}, skipping connect attempt`,
1990
- session.loggingMetadata
1991
- );
1992
- return;
1993
- }
1994
- if (!this.retryBudget.hasBudget()) {
1995
- const budgetConsumed = this.retryBudget.getBudgetConsumed();
1996
- const errMsg = `tried to connect to ${to} but retry budget exceeded (more than ${budgetConsumed} attempts in the last ${this.retryBudget.totalBudgetRestoreTime}ms)`;
1997
- this.log?.error(errMsg, session.loggingMetadata);
1998
- this.protocolError({
1999
- type: ProtocolError.RetriesExceeded,
2000
- message: errMsg
2001
- });
2002
- return;
2003
- }
2004
- const backoffMs = this.retryBudget.getBackoffMs();
2005
- this.log?.info(
2006
- `attempting connection to ${to} (${backoffMs}ms backoff)`,
2007
- session.loggingMetadata
2008
- );
2009
- this.retryBudget.consumeBudget();
2010
- const backingOffSession = ClientSessionStateGraph.transition.NoConnectionToBackingOff(
2011
- session,
2012
- backoffMs,
2013
- {
2014
- onBackoffFinished: () => {
2015
- this.onBackoffFinished(backingOffSession);
2016
- },
2017
- onSessionGracePeriodElapsed: () => {
2018
- this.onSessionGracePeriodElapsed(backingOffSession);
2019
- },
2020
- onMessageSendFailure: (msg, reason) => {
2021
- this.log?.error(`failed to send message: ${reason}`, {
2022
- ...backingOffSession.loggingMetadata,
2023
- transportMessage: msg
2024
- });
2025
- this.protocolError({
2026
- type: ProtocolError.MessageSendFailure,
2027
- message: reason
2028
- });
2029
- this.deleteSession(backingOffSession, { unhealthy: true });
2030
- }
2031
- }
2032
- );
2033
- this.updateSession(backingOffSession);
2034
- }
2035
- /**
2036
- * Manually kills all sessions to the server (including all pending state).
2037
- * This is useful for when you want to close all connections to a server
2038
- * and don't want to wait for the grace period to elapse.
2039
- */
2040
- hardDisconnect() {
2041
- const sessions = Array.from(this.sessions.values());
2042
- for (const session of sessions) {
2043
- this.deleteSession(session);
2044
- }
2045
- }
2046
- onBackoffFinished(session) {
2047
- const connPromise = session.tracer.startActiveSpan(
2048
- "connect",
2049
- async (span) => {
2050
- try {
2051
- return await this.createNewOutgoingConnection(session.to);
2052
- } catch (err) {
2053
- const errStr = coerceErrorString(err);
2054
- span.recordException(errStr);
2055
- span.setStatus({ code: import_api4.SpanStatusCode.ERROR });
2056
- throw err;
2057
- } finally {
2058
- span.end();
2059
- }
2060
- }
2061
- );
2062
- const connectingSession = ClientSessionStateGraph.transition.BackingOffToConnecting(
2063
- session,
2064
- connPromise,
2065
- {
2066
- onConnectionEstablished: (conn) => {
2067
- this.log?.debug(
2068
- `connection to ${connectingSession.to} established`,
2069
- {
2070
- ...conn.loggingMetadata,
2071
- ...connectingSession.loggingMetadata
2072
- }
2073
- );
2074
- this.onConnectionEstablished(connectingSession, conn);
2075
- },
2076
- onConnectionFailed: (error) => {
2077
- const errStr = coerceErrorString(error);
2078
- this.log?.error(
2079
- `error connecting to ${connectingSession.to}: ${errStr}`,
2080
- connectingSession.loggingMetadata
2081
- );
2082
- this.onConnectingFailed(connectingSession);
2083
- },
2084
- onConnectionTimeout: () => {
2085
- this.log?.error(
2086
- `connection to ${connectingSession.to} timed out`,
2087
- connectingSession.loggingMetadata
2088
- );
2089
- this.onConnectingFailed(connectingSession);
2090
- },
2091
- onSessionGracePeriodElapsed: () => {
2092
- this.onSessionGracePeriodElapsed(connectingSession);
2093
- },
2094
- onMessageSendFailure: (msg, reason) => {
2095
- this.log?.error(`failed to send message: ${reason}`, {
2096
- ...connectingSession.loggingMetadata,
2097
- transportMessage: msg
2098
- });
2099
- this.protocolError({
2100
- type: ProtocolError.MessageSendFailure,
2101
- message: reason
2102
- });
2103
- this.deleteSession(connectingSession, { unhealthy: true });
2104
- }
2105
- }
2106
- );
2107
- this.updateSession(connectingSession);
2108
- }
2109
- async sendHandshake(session) {
2110
- let metadata = void 0;
2111
- if (this.handshakeExtensions) {
2112
- try {
2113
- metadata = await this.handshakeExtensions.construct();
2114
- } catch (err) {
2115
- const errStr = coerceErrorString(err);
2116
- this.log?.error(
2117
- `failed to construct handshake metadata for session to ${session.to}: ${errStr}`,
2118
- session.loggingMetadata
2119
- );
2120
- this.protocolError({
2121
- type: ProtocolError.HandshakeFailed,
2122
- message: `failed to construct handshake metadata: ${errStr}`
2123
- });
2124
- this.deleteSession(session, { unhealthy: true });
2125
- return;
2126
- }
2127
- }
2128
- if (session._isConsumed) {
2129
- return;
2130
- }
2131
- const requestMsg = handshakeRequestMessage({
2132
- from: this.clientId,
2133
- to: session.to,
2134
- sessionId: session.id,
2135
- expectedSessionState: {
2136
- nextExpectedSeq: session.ack,
2137
- nextSentSeq: session.nextSeq()
2138
- },
2139
- metadata,
2140
- tracing: getPropagationContext(session.telemetry.ctx)
2141
- });
2142
- this.log?.debug(`sending handshake request to ${session.to}`, {
2143
- ...session.loggingMetadata,
2144
- transportMessage: requestMsg
2145
- });
2146
- const res = session.sendHandshake(requestMsg);
2147
- if (!res.ok) {
2148
- this.log?.error(`failed to send handshake request: ${res.reason}`, {
2149
- ...session.loggingMetadata,
2150
- transportMessage: requestMsg
2151
- });
2152
- this.protocolError({
2153
- type: ProtocolError.MessageSendFailure,
2154
- message: res.reason
2155
- });
2156
- this.deleteSession(session, { unhealthy: true });
2157
- }
2158
- }
2159
- close() {
2160
- this.retryBudget.close();
2161
- super.close();
2162
- }
2163
- };
2164
-
2165
- // transport/server.ts
2166
- var import_api5 = require("@opentelemetry/api");
2167
- var import_value3 = require("@sinclair/typebox/value");
2168
- var ServerTransport = class extends Transport {
2169
- /**
2170
- * The options for this transport.
2171
- */
2172
- options;
2173
- /**
2174
- * Optional handshake options for the server.
2175
- */
2176
- handshakeExtensions;
2177
- /**
2178
- * A map of session handshake data for each session.
2179
- */
2180
- sessionHandshakeMetadata = /* @__PURE__ */ new Map();
2181
- sessions = /* @__PURE__ */ new Map();
2182
- pendingSessions = /* @__PURE__ */ new Set();
2183
- constructor(clientId, providedOptions) {
2184
- super(clientId, providedOptions);
2185
- this.sessions = /* @__PURE__ */ new Map();
2186
- this.options = {
2187
- ...defaultServerTransportOptions,
2188
- ...providedOptions
2189
- };
2190
- this.log?.info(`initiated server transport`, {
2191
- clientId: this.clientId,
2192
- protocolVersion: currentProtocolVersion
2193
- });
2194
- }
2195
- extendHandshake(options) {
2196
- this.handshakeExtensions = options;
2197
- }
2198
- deletePendingSession(pendingSession) {
2199
- pendingSession.close();
2200
- this.pendingSessions.delete(pendingSession);
2201
- }
2202
- deleteSession(session, options) {
2203
- this.sessionHandshakeMetadata.delete(session.to);
2204
- super.deleteSession(session, options);
2205
- }
2206
- handleConnection(conn) {
2207
- if (this.getStatus() !== "open") return;
2208
- this.log?.info(`new incoming connection`, {
2209
- ...conn.loggingMetadata,
2210
- clientId: this.clientId
2211
- });
2212
- let receivedHandshake = false;
2213
- const pendingSession = ServerSessionStateGraph.entrypoint(
2214
- this.clientId,
2215
- conn,
2216
- {
2217
- onConnectionClosed: () => {
2218
- this.log?.warn(
2219
- `connection from unknown closed before handshake finished`,
2220
- pendingSession.loggingMetadata
2221
- );
2222
- this.deletePendingSession(pendingSession);
2223
- },
2224
- onConnectionErrored: (err) => {
2225
- const errorString = coerceErrorString(err);
2226
- this.log?.warn(
2227
- `connection from unknown errored before handshake finished: ${errorString}`,
2228
- pendingSession.loggingMetadata
2229
- );
2230
- this.deletePendingSession(pendingSession);
2231
- },
2232
- onHandshakeTimeout: () => {
2233
- this.log?.warn(
2234
- `connection from unknown timed out before handshake finished`,
2235
- pendingSession.loggingMetadata
2236
- );
2237
- this.deletePendingSession(pendingSession);
2238
- },
2239
- onHandshake: (msg) => {
2240
- if (receivedHandshake) {
2241
- this.log?.error(
2242
- `received multiple handshake messages from pending session`,
2243
- {
2244
- ...pendingSession.loggingMetadata,
2245
- connectedTo: msg.from,
2246
- transportMessage: msg
2247
- }
2248
- );
2249
- this.deletePendingSession(pendingSession);
2250
- return;
2251
- }
2252
- receivedHandshake = true;
2253
- void this.onHandshakeRequest(pendingSession, msg);
2254
- },
2255
- onInvalidHandshake: (reason, code) => {
2256
- this.log?.error(
2257
- `invalid handshake: ${reason}`,
2258
- pendingSession.loggingMetadata
2259
- );
2260
- this.deletePendingSession(pendingSession);
2261
- this.protocolError({
2262
- type: ProtocolError.HandshakeFailed,
2263
- code,
2264
- message: reason
2265
- });
2266
- }
2267
- },
2268
- this.options,
2269
- this.tracer,
2270
- this.log
2271
- );
2272
- this.pendingSessions.add(pendingSession);
2273
- }
2274
- rejectHandshakeRequest(session, to, reason, code, metadata) {
2275
- session.conn.telemetry?.span.setStatus({
2276
- code: import_api5.SpanStatusCode.ERROR,
2277
- message: reason
2278
- });
2279
- this.log?.warn(reason, metadata);
2280
- const responseMsg = handshakeResponseMessage({
2281
- from: this.clientId,
2282
- to,
2283
- status: {
2284
- ok: false,
2285
- code,
2286
- reason
2287
- }
2288
- });
2289
- const res = session.sendHandshake(responseMsg);
2290
- if (!res.ok) {
2291
- this.log?.error(`failed to send handshake response: ${res.reason}`, {
2292
- ...session.loggingMetadata,
2293
- transportMessage: responseMsg
2294
- });
2295
- this.protocolError({
2296
- type: ProtocolError.MessageSendFailure,
2297
- message: res.reason
2298
- });
2299
- this.deletePendingSession(session);
2300
- return;
2301
- }
2302
- this.protocolError({
2303
- type: ProtocolError.HandshakeFailed,
2304
- code,
2305
- message: reason
2306
- });
2307
- this.deletePendingSession(session);
2308
- }
2309
- async onHandshakeRequest(session, msg) {
2310
- if (!import_value3.Value.Check(ControlMessageHandshakeRequestSchema, msg.payload)) {
2311
- this.rejectHandshakeRequest(
2312
- session,
2313
- msg.from,
2314
- "received invalid handshake request",
2315
- "MALFORMED_HANDSHAKE",
2316
- {
2317
- ...session.loggingMetadata,
2318
- transportMessage: msg,
2319
- connectedTo: msg.from,
2320
- validationErrors: [
2321
- ...import_value3.Value.Errors(ControlMessageHandshakeRequestSchema, msg.payload)
2322
- ]
2323
- }
2324
- );
2325
- return;
2326
- }
2327
- const gotVersion = msg.payload.protocolVersion;
2328
- if (!isAcceptedProtocolVersion(gotVersion)) {
2329
- this.rejectHandshakeRequest(
2330
- session,
2331
- msg.from,
2332
- `expected protocol version oneof [${acceptedProtocolVersions.toString()}], got ${gotVersion}`,
2333
- "PROTOCOL_VERSION_MISMATCH",
2334
- {
2335
- ...session.loggingMetadata,
2336
- connectedTo: msg.from,
2337
- transportMessage: msg
2338
- }
2339
- );
2340
- return;
2341
- }
2342
- let parsedMetadata = {};
2343
- if (this.handshakeExtensions) {
2344
- if (!import_value3.Value.Check(this.handshakeExtensions.schema, msg.payload.metadata)) {
2345
- this.rejectHandshakeRequest(
2346
- session,
2347
- msg.from,
2348
- "received malformed handshake metadata",
2349
- "MALFORMED_HANDSHAKE_META",
2350
- {
2351
- ...session.loggingMetadata,
2352
- connectedTo: msg.from,
2353
- validationErrors: [
2354
- ...import_value3.Value.Errors(
2355
- this.handshakeExtensions.schema,
2356
- msg.payload.metadata
2357
- )
2358
- ]
2359
- }
2360
- );
2361
- return;
2362
- }
2363
- const previousParsedMetadata = this.sessionHandshakeMetadata.get(
2364
- msg.from
2365
- );
2366
- let parsedMetadataOrFailureCode;
2367
- try {
2368
- parsedMetadataOrFailureCode = await this.handshakeExtensions.validate(
2369
- msg.payload.metadata,
2370
- previousParsedMetadata
2371
- );
2372
- } catch (err) {
2373
- this.rejectHandshakeRequest(
2374
- session,
2375
- msg.from,
2376
- `handshake validation threw: ${coerceErrorString(err)}`,
2377
- "REJECTED_BY_CUSTOM_HANDLER",
2378
- {
2379
- ...session.loggingMetadata,
2380
- connectedTo: msg.from,
2381
- clientId: this.clientId
2382
- }
2383
- );
2384
- return;
2385
- }
2386
- if (session._isConsumed) {
2387
- return;
2388
- }
2389
- if (import_value3.Value.Check(
2390
- HandshakeErrorCustomHandlerFatalResponseCodes,
2391
- parsedMetadataOrFailureCode
2392
- )) {
2393
- this.rejectHandshakeRequest(
2394
- session,
2395
- msg.from,
2396
- "rejected by handshake handler",
2397
- parsedMetadataOrFailureCode,
2398
- {
2399
- ...session.loggingMetadata,
2400
- connectedTo: msg.from,
2401
- clientId: this.clientId
2402
- }
2403
- );
2404
- return;
2405
- }
2406
- parsedMetadata = parsedMetadataOrFailureCode;
2407
- }
2408
- let connectCase = "new session";
2409
- const clientNextExpectedSeq = msg.payload.expectedSessionState.nextExpectedSeq;
2410
- const clientNextSentSeq = msg.payload.expectedSessionState.nextSentSeq;
2411
- let oldSession = this.sessions.get(msg.from);
2412
- if (this.options.enableTransparentSessionReconnects && oldSession && oldSession.id === msg.payload.sessionId) {
2413
- connectCase = "transparent reconnection";
2414
- const ourNextSeq = oldSession.nextSeq();
2415
- const ourAck = oldSession.ack;
2416
- if (clientNextSentSeq > ourAck) {
2417
- this.rejectHandshakeRequest(
2418
- session,
2419
- msg.from,
2420
- `client is in the future: server wanted next message to be ${ourAck} but client would have sent ${clientNextSentSeq}`,
2421
- "SESSION_STATE_MISMATCH",
2422
- {
2423
- ...session.loggingMetadata,
2424
- connectedTo: msg.from,
2425
- transportMessage: msg
2426
- }
2427
- );
2428
- return;
2429
- }
2430
- if (ourNextSeq > clientNextExpectedSeq) {
2431
- this.rejectHandshakeRequest(
2432
- session,
2433
- msg.from,
2434
- `server is in the future: client wanted next message to be ${clientNextExpectedSeq} but server would have sent ${ourNextSeq}`,
2435
- "SESSION_STATE_MISMATCH",
2436
- {
2437
- ...session.loggingMetadata,
2438
- connectedTo: msg.from,
2439
- transportMessage: msg
2440
- }
2441
- );
2442
- return;
2443
- }
2444
- if (oldSession.state !== "NoConnection" /* NoConnection */) {
2445
- const noConnectionSession = ServerSessionStateGraph.transition.ConnectedToNoConnection(
2446
- oldSession,
2447
- {
2448
- onSessionGracePeriodElapsed: () => {
2449
- this.onSessionGracePeriodElapsed(noConnectionSession);
2450
- },
2451
- onMessageSendFailure: (msg2, reason) => {
2452
- this.log?.error(`failed to send message: ${reason}`, {
2453
- ...noConnectionSession.loggingMetadata,
2454
- transportMessage: msg2
2455
- });
2456
- this.protocolError({
2457
- type: ProtocolError.MessageSendFailure,
2458
- message: reason
2459
- });
2460
- this.deleteSession(noConnectionSession, { unhealthy: true });
2461
- }
2462
- }
2463
- );
2464
- oldSession = noConnectionSession;
2465
- this.updateSession(oldSession);
2466
- }
2467
- } else if (oldSession) {
2468
- connectCase = "hard reconnection";
2469
- this.log?.info(
2470
- `client is reconnecting to a new session (${msg.payload.sessionId}) with an old session (${oldSession.id}) already existing, closing old session`,
2471
- {
2472
- ...session.loggingMetadata,
2473
- connectedTo: msg.from,
2474
- sessionId: msg.payload.sessionId
2475
- }
2476
- );
2477
- this.deleteSession(oldSession);
2478
- oldSession = void 0;
2479
- }
2480
- if (!oldSession && (clientNextSentSeq > 0 || clientNextExpectedSeq > 0)) {
2481
- connectCase = "unknown session";
2482
- const rejectionMessage = this.options.enableTransparentSessionReconnects ? `client is trying to reconnect to a session the server don't know about: ${msg.payload.sessionId}` : `client is attempting a transparent reconnect to a session but the server does not support it: ${msg.payload.sessionId}`;
2483
- this.rejectHandshakeRequest(
2484
- session,
2485
- msg.from,
2486
- rejectionMessage,
2487
- "SESSION_STATE_MISMATCH",
2488
- {
2489
- ...session.loggingMetadata,
2490
- connectedTo: msg.from,
2491
- transportMessage: msg
2492
- }
2493
- );
2494
- return;
2495
- }
2496
- const sessionId = msg.payload.sessionId;
2497
- this.log?.info(
2498
- `handshake from ${msg.from} ok (${connectCase}), responding with handshake success`,
2499
- {
2500
- ...session.loggingMetadata,
2501
- connectedTo: msg.from
2502
- }
2503
- );
2504
- const responseMsg = handshakeResponseMessage({
2505
- from: this.clientId,
2506
- to: msg.from,
2507
- status: {
2508
- ok: true,
2509
- sessionId
2510
- }
2511
- });
2512
- const res = session.sendHandshake(responseMsg);
2513
- if (!res.ok) {
2514
- this.log?.error(`failed to send handshake response: ${res.reason}`, {
2515
- ...session.loggingMetadata,
2516
- transportMessage: responseMsg
2517
- });
2518
- this.protocolError({
2519
- type: ProtocolError.MessageSendFailure,
2520
- message: res.reason
2521
- });
2522
- this.deletePendingSession(session);
2523
- return;
2524
- }
2525
- this.pendingSessions.delete(session);
2526
- const connectedSession = ServerSessionStateGraph.transition.WaitingForHandshakeToConnected(
2527
- session,
2528
- // by this point oldSession is either no connection or we dont have an old session
2529
- oldSession,
2530
- sessionId,
2531
- msg.from,
2532
- msg.tracing,
2533
- {
2534
- onConnectionErrored: (err) => {
2535
- const errStr = coerceErrorString(err);
2536
- this.log?.warn(
2537
- `connection to ${connectedSession.to} errored: ${errStr}`,
2538
- connectedSession.loggingMetadata
2539
- );
2540
- },
2541
- onConnectionClosed: () => {
2542
- this.log?.info(
2543
- `connection to ${connectedSession.to} closed`,
2544
- connectedSession.loggingMetadata
2545
- );
2546
- this.onConnClosed(connectedSession);
2547
- },
2548
- onMessage: (msg2) => {
2549
- this.handleMsg(msg2);
2550
- },
2551
- onInvalidMessage: (reason) => {
2552
- this.log?.error(`invalid message: ${reason}`, {
2553
- ...connectedSession.loggingMetadata,
2554
- transportMessage: msg
2555
- });
2556
- this.protocolError({
2557
- type: ProtocolError.InvalidMessage,
2558
- message: reason
2559
- });
2560
- this.deleteSession(connectedSession, { unhealthy: true });
2561
- },
2562
- onMessageSendFailure: (msg2, reason) => {
2563
- this.log?.error(`failed to send message: ${reason}`, {
2564
- ...connectedSession.loggingMetadata,
2565
- transportMessage: msg2
2566
- });
2567
- this.protocolError({
2568
- type: ProtocolError.MessageSendFailure,
2569
- message: reason
2570
- });
2571
- this.deleteSession(connectedSession, { unhealthy: true });
2572
- }
2573
- },
2574
- gotVersion
2575
- );
2576
- const bufferSendRes = connectedSession.sendBufferedMessages();
2577
- if (!bufferSendRes.ok) {
2578
- return;
2579
- }
2580
- this.sessionHandshakeMetadata.set(connectedSession.to, parsedMetadata);
2581
- if (oldSession) {
2582
- this.updateSession(connectedSession);
2583
- } else {
2584
- this.createSession(connectedSession);
2585
- }
2586
- connectedSession.startActiveHeartbeat();
2587
- }
2588
- };
2589
-
2590
- // transport/connection.ts
2591
- var Connection = class {
2592
- id;
2593
- telemetry;
2594
- constructor() {
2595
- this.id = `conn-${generateId()}`;
2596
- }
2597
- get loggingMetadata() {
2598
- const metadata = { connId: this.id };
2599
- if (this.telemetry?.span.isRecording()) {
2600
- const spanContext = this.telemetry.span.spanContext();
2601
- metadata.telemetry = {
2602
- traceId: spanContext.traceId,
2603
- spanId: spanContext.spanId
2604
- };
2605
- }
2606
- return metadata;
2607
- }
2608
- dataListener;
2609
- closeListener;
2610
- errorListener;
2611
- onData(msg) {
2612
- this.dataListener?.(msg);
2613
- }
2614
- onError(err) {
2615
- this.errorListener?.(err);
2616
- }
2617
- onClose() {
2618
- this.closeListener?.();
2619
- this.telemetry?.span.end();
2620
- }
2621
- /**
2622
- * Set the callback for when a message is received.
2623
- * @param cb The message handler callback.
2624
- */
2625
- setDataListener(cb) {
2626
- this.dataListener = cb;
2627
- }
2628
- removeDataListener() {
2629
- this.dataListener = void 0;
2630
- }
2631
- /**
2632
- * Set the callback for when the connection is closed.
2633
- * This should also be called if an error happens and after notifying the error listener.
2634
- * @param cb The callback to call when the connection is closed.
2635
- */
2636
- setCloseListener(cb) {
2637
- this.closeListener = cb;
2638
- }
2639
- removeCloseListener() {
2640
- this.closeListener = void 0;
2641
- }
2642
- /**
2643
- * Set the callback for when an error is received.
2644
- * This should only be used for logging errors, all cleanup
2645
- * should be delegated to setCloseListener.
2646
- *
2647
- * The implementer should take care such that the implemented
2648
- * connection will call both the close and error callbacks
2649
- * on an error.
2650
- *
2651
- * @param cb The callback to call when an error is received.
2652
- */
2653
- setErrorListener(cb) {
2654
- this.errorListener = cb;
2655
- }
2656
- removeErrorListener() {
2657
- this.errorListener = void 0;
2658
- }
2659
- };
2660
-
2661
- // transport/impls/ws/connection.ts
2662
- var WS_HEALTHY_CLOSE_CODE = 1e3;
2663
- var WebSocketCloseError = class extends Error {
2664
- code;
2665
- reason;
2666
- constructor(code, reason) {
2667
- super(`websocket closed with code and reason: ${code} - ${reason}`);
2668
- this.code = code;
2669
- this.reason = reason;
2670
- }
2671
- };
2672
- var WebSocketConnection = class extends Connection {
2673
- ws;
2674
- extras;
2675
- get loggingMetadata() {
2676
- const metadata = super.loggingMetadata;
2677
- if (this.extras) {
2678
- metadata.extras = this.extras;
2679
- }
2680
- return metadata;
2681
- }
2682
- constructor(ws, extras) {
2683
- super();
2684
- this.ws = ws;
2685
- this.extras = extras;
2686
- this.ws.binaryType = "arraybuffer";
2687
- let didError = false;
2688
- this.ws.onerror = () => {
2689
- didError = true;
2690
- };
2691
- this.ws.onclose = ({ code, reason }) => {
2692
- if (didError) {
2693
- const err = new WebSocketCloseError(code, reason);
2694
- this.onError(err);
2695
- }
2696
- this.onClose();
2697
- };
2698
- this.ws.onmessage = (msg) => {
2699
- this.onData(msg.data);
2700
- };
2701
- }
2702
- send(payload) {
2703
- try {
2704
- this.ws.send(payload);
2705
- return true;
2706
- } catch {
2707
- return false;
2708
- }
2709
- }
2710
- close() {
2711
- this.ws.close(WS_HEALTHY_CLOSE_CODE);
2712
- }
2713
- };
2714
- // Annotate the CommonJS export names for ESM import in node:
2715
- 0 && (module.exports = {
2716
- ClientTransport,
2717
- Connection,
2718
- OpaqueTransportMessageSchema,
2719
- ProtocolError,
2720
- ServerTransport,
2721
- SessionState,
2722
- Transport,
2723
- TransportMessageSchema,
2724
- WebSocketCloseError,
2725
- WebSocketConnection
2726
- });
2727
- //# sourceMappingURL=index.cjs.map