@replit/river 0.200.0-rc.6 → 0.200.0-rc.7

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