@replit/river 0.203.1 → 0.205.0
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.
- package/README.md +7 -3
- package/dist/{chunk-TMOCPK63.js → chunk-AXZPYUY6.js} +50 -11
- package/dist/chunk-AXZPYUY6.js.map +1 -0
- package/dist/{chunk-2FHJVQBE.js → chunk-EU2H4J7U.js} +5 -11
- package/dist/chunk-EU2H4J7U.js.map +1 -0
- package/dist/chunk-GG3GL7CW.js +1955 -0
- package/dist/chunk-GG3GL7CW.js.map +1 -0
- package/dist/{chunk-T4WWG42M.js → chunk-RAO6UI45.js} +21 -17
- package/dist/chunk-RAO6UI45.js.map +1 -0
- package/dist/{chunk-7MKTFUJO.js → chunk-VN7QS6OS.js} +4 -3
- package/dist/chunk-VN7QS6OS.js.map +1 -0
- package/dist/{client-5d2e41a3.d.ts → client-3adfb12a.d.ts} +1 -1
- package/dist/{connection-11a4af0f.d.ts → connection-9ca3e7ed.d.ts} +1 -1
- package/dist/{context-d6dd8a1a.d.ts → context-1a332293.d.ts} +12 -3
- package/dist/router/index.cjs +25 -14
- package/dist/router/index.cjs.map +1 -1
- package/dist/router/index.d.cts +7 -7
- package/dist/router/index.d.ts +7 -7
- package/dist/router/index.js +18 -1611
- package/dist/router/index.js.map +1 -1
- package/dist/{server-e46399f9.d.ts → server-8ac5c6bf.d.ts} +1 -1
- package/dist/{services-56cbea0d.d.ts → services-4213d92e.d.ts} +2 -2
- package/dist/testUtil/index.cjs +82 -36
- package/dist/testUtil/index.cjs.map +1 -1
- package/dist/testUtil/index.d.cts +4 -4
- package/dist/testUtil/index.d.ts +4 -4
- package/dist/testUtil/index.js +8 -6
- package/dist/testUtil/index.js.map +1 -1
- package/dist/transport/impls/ws/client.cjs +82 -44
- package/dist/transport/impls/ws/client.cjs.map +1 -1
- package/dist/transport/impls/ws/client.d.cts +3 -3
- package/dist/transport/impls/ws/client.d.ts +3 -3
- package/dist/transport/impls/ws/client.js +4 -4
- package/dist/transport/impls/ws/server.cjs +66 -31
- package/dist/transport/impls/ws/server.cjs.map +1 -1
- package/dist/transport/impls/ws/server.d.cts +3 -3
- package/dist/transport/impls/ws/server.d.ts +3 -3
- package/dist/transport/impls/ws/server.js +4 -4
- package/dist/transport/index.cjs +80 -35
- package/dist/transport/index.cjs.map +1 -1
- package/dist/transport/index.d.cts +3 -3
- package/dist/transport/index.d.ts +3 -3
- package/dist/transport/index.js +4 -4
- package/package.json +2 -2
- package/dist/chunk-2FHJVQBE.js.map +0 -1
- package/dist/chunk-7MKTFUJO.js.map +0 -1
- package/dist/chunk-AK7NTFAM.js +0 -331
- package/dist/chunk-AK7NTFAM.js.map +0 -1
- package/dist/chunk-T4WWG42M.js.map +0 -1
- package/dist/chunk-TMOCPK63.js.map +0 -1
package/README.md
CHANGED
|
@@ -189,10 +189,14 @@ If your application is stateful on either the server or the client, the service
|
|
|
189
189
|
|
|
190
190
|
```ts
|
|
191
191
|
transport.addEventListener('sessionStatus', (evt) => {
|
|
192
|
-
if (evt.status === '
|
|
192
|
+
if (evt.status === 'created') {
|
|
193
193
|
// do something
|
|
194
|
-
} else if (evt.status === '
|
|
195
|
-
// do
|
|
194
|
+
} else if (evt.status === 'closing') {
|
|
195
|
+
// do other things
|
|
196
|
+
} else if (evt.status === 'closed') {
|
|
197
|
+
// note that evt.session only has id + to
|
|
198
|
+
// this is useful for doing things like creating a new session if
|
|
199
|
+
// a session just got yanked
|
|
196
200
|
}
|
|
197
201
|
});
|
|
198
202
|
|
|
@@ -3,8 +3,9 @@ import {
|
|
|
3
3
|
createConnectionTelemetryInfo,
|
|
4
4
|
createSessionTelemetryInfo,
|
|
5
5
|
generateId,
|
|
6
|
+
getTracer,
|
|
6
7
|
isAck
|
|
7
|
-
} from "./chunk-
|
|
8
|
+
} from "./chunk-GG3GL7CW.js";
|
|
8
9
|
import {
|
|
9
10
|
BaseLogger,
|
|
10
11
|
createLogProxy
|
|
@@ -108,12 +109,14 @@ var StateMachineState = class {
|
|
|
108
109
|
var CommonSession = class extends StateMachineState {
|
|
109
110
|
from;
|
|
110
111
|
options;
|
|
112
|
+
tracer;
|
|
111
113
|
log;
|
|
112
|
-
constructor({ from, options, log }) {
|
|
114
|
+
constructor({ from, options, log, tracer }) {
|
|
113
115
|
super();
|
|
114
116
|
this.from = from;
|
|
115
117
|
this.options = options;
|
|
116
118
|
this.log = log;
|
|
119
|
+
this.tracer = tracer;
|
|
117
120
|
}
|
|
118
121
|
parseMsg(msg) {
|
|
119
122
|
const parsedMsg = this.options.codec.fromBuffer(msg);
|
|
@@ -579,6 +582,7 @@ function inheritSharedSession(session) {
|
|
|
579
582
|
telemetry: session.telemetry,
|
|
580
583
|
options: session.options,
|
|
581
584
|
log: session.log,
|
|
585
|
+
tracer: session.tracer,
|
|
582
586
|
protocolVersion: session.protocolVersion
|
|
583
587
|
};
|
|
584
588
|
}
|
|
@@ -590,9 +594,9 @@ function inheritSharedSessionWithGrace(session) {
|
|
|
590
594
|
}
|
|
591
595
|
var SessionStateGraph = {
|
|
592
596
|
entrypoints: {
|
|
593
|
-
NoConnection: (to, from, listeners, options, protocolVersion, log) => {
|
|
597
|
+
NoConnection: (to, from, listeners, options, protocolVersion, tracer, log) => {
|
|
594
598
|
const id = `session-${generateId()}`;
|
|
595
|
-
const telemetry = createSessionTelemetryInfo(id, to, from);
|
|
599
|
+
const telemetry = createSessionTelemetryInfo(tracer, id, to, from);
|
|
596
600
|
const sendBuffer = [];
|
|
597
601
|
const session = new SessionNoConnection({
|
|
598
602
|
listeners,
|
|
@@ -606,6 +610,7 @@ var SessionStateGraph = {
|
|
|
606
610
|
telemetry,
|
|
607
611
|
options,
|
|
608
612
|
protocolVersion,
|
|
613
|
+
tracer,
|
|
609
614
|
log
|
|
610
615
|
});
|
|
611
616
|
session.log?.info(`session ${session.id} created in NoConnection state`, {
|
|
@@ -614,12 +619,13 @@ var SessionStateGraph = {
|
|
|
614
619
|
});
|
|
615
620
|
return session;
|
|
616
621
|
},
|
|
617
|
-
WaitingForHandshake: (from, conn, listeners, options, log) => {
|
|
622
|
+
WaitingForHandshake: (from, conn, listeners, options, tracer, log) => {
|
|
618
623
|
const session = new SessionWaitingForHandshake({
|
|
619
624
|
conn,
|
|
620
625
|
listeners,
|
|
621
626
|
from,
|
|
622
627
|
options,
|
|
628
|
+
tracer,
|
|
623
629
|
log
|
|
624
630
|
});
|
|
625
631
|
session.log?.info(`session created in WaitingForHandshake state`, {
|
|
@@ -675,7 +681,11 @@ var SessionStateGraph = {
|
|
|
675
681
|
listeners,
|
|
676
682
|
...carriedState
|
|
677
683
|
});
|
|
678
|
-
conn.telemetry = createConnectionTelemetryInfo(
|
|
684
|
+
conn.telemetry = createConnectionTelemetryInfo(
|
|
685
|
+
session.tracer,
|
|
686
|
+
conn,
|
|
687
|
+
session.telemetry
|
|
688
|
+
);
|
|
679
689
|
session.log?.info(
|
|
680
690
|
`session ${session.id} transition from Connecting to Handshaking`,
|
|
681
691
|
{
|
|
@@ -719,12 +729,14 @@ var SessionStateGraph = {
|
|
|
719
729
|
ack: 0,
|
|
720
730
|
sendBuffer: [],
|
|
721
731
|
telemetry: createSessionTelemetryInfo(
|
|
732
|
+
pendingSession.tracer,
|
|
722
733
|
sessionId,
|
|
723
734
|
to,
|
|
724
735
|
from,
|
|
725
736
|
propagationCtx
|
|
726
737
|
),
|
|
727
738
|
options,
|
|
739
|
+
tracer: pendingSession.tracer,
|
|
728
740
|
log: pendingSession.log,
|
|
729
741
|
protocolVersion
|
|
730
742
|
}
|
|
@@ -736,7 +748,11 @@ var SessionStateGraph = {
|
|
|
736
748
|
listeners,
|
|
737
749
|
...carriedState
|
|
738
750
|
});
|
|
739
|
-
conn.telemetry = createConnectionTelemetryInfo(
|
|
751
|
+
conn.telemetry = createConnectionTelemetryInfo(
|
|
752
|
+
session.tracer,
|
|
753
|
+
conn,
|
|
754
|
+
session.telemetry
|
|
755
|
+
);
|
|
740
756
|
session.log?.info(
|
|
741
757
|
`session ${session.id} transition from WaitingForHandshake to Connected`,
|
|
742
758
|
{
|
|
@@ -919,6 +935,7 @@ var Transport = class {
|
|
|
919
935
|
*/
|
|
920
936
|
options;
|
|
921
937
|
log;
|
|
938
|
+
tracer;
|
|
922
939
|
sessions;
|
|
923
940
|
/**
|
|
924
941
|
* Creates a new Transport instance.
|
|
@@ -931,6 +948,7 @@ var Transport = class {
|
|
|
931
948
|
this.clientId = clientId;
|
|
932
949
|
this.status = "open";
|
|
933
950
|
this.sessions = /* @__PURE__ */ new Map();
|
|
951
|
+
this.tracer = getTracer();
|
|
934
952
|
}
|
|
935
953
|
bindLogger(fn, level) {
|
|
936
954
|
if (typeof fn === "function") {
|
|
@@ -975,7 +993,8 @@ var Transport = class {
|
|
|
975
993
|
*/
|
|
976
994
|
close() {
|
|
977
995
|
this.status = "closed";
|
|
978
|
-
|
|
996
|
+
const sessions = Array.from(this.sessions.values());
|
|
997
|
+
for (const session of sessions) {
|
|
979
998
|
this.deleteSession(session);
|
|
980
999
|
}
|
|
981
1000
|
this.eventDispatcher.dispatchEvent("transportStatus", {
|
|
@@ -1000,7 +1019,7 @@ var Transport = class {
|
|
|
1000
1019
|
}
|
|
1001
1020
|
this.sessions.set(session.to, session);
|
|
1002
1021
|
this.eventDispatcher.dispatchEvent("sessionStatus", {
|
|
1003
|
-
status: "
|
|
1022
|
+
status: "created",
|
|
1004
1023
|
session
|
|
1005
1024
|
});
|
|
1006
1025
|
this.eventDispatcher.dispatchEvent("sessionTransition", {
|
|
@@ -1041,12 +1060,16 @@ var Transport = class {
|
|
|
1041
1060
|
}
|
|
1042
1061
|
session.log?.info(`closing session ${session.id}`, loggingMetadata);
|
|
1043
1062
|
this.eventDispatcher.dispatchEvent("sessionStatus", {
|
|
1044
|
-
status: "
|
|
1063
|
+
status: "closing",
|
|
1045
1064
|
session
|
|
1046
1065
|
});
|
|
1047
1066
|
const to = session.to;
|
|
1048
1067
|
session.close();
|
|
1049
1068
|
this.sessions.delete(to);
|
|
1069
|
+
this.eventDispatcher.dispatchEvent("sessionStatus", {
|
|
1070
|
+
status: "closed",
|
|
1071
|
+
session: { id: session.id, to }
|
|
1072
|
+
});
|
|
1050
1073
|
}
|
|
1051
1074
|
// common listeners
|
|
1052
1075
|
onSessionGracePeriodElapsed(session) {
|
|
@@ -1144,6 +1167,22 @@ var Connection = class {
|
|
|
1144
1167
|
get errorListeners() {
|
|
1145
1168
|
return [...this._errorListeners];
|
|
1146
1169
|
}
|
|
1170
|
+
onData(msg) {
|
|
1171
|
+
for (const cb of this.dataListeners) {
|
|
1172
|
+
cb(msg);
|
|
1173
|
+
}
|
|
1174
|
+
}
|
|
1175
|
+
onError(err) {
|
|
1176
|
+
for (const cb of this.errorListeners) {
|
|
1177
|
+
cb(err);
|
|
1178
|
+
}
|
|
1179
|
+
}
|
|
1180
|
+
onClose() {
|
|
1181
|
+
for (const cb of this.closeListeners) {
|
|
1182
|
+
cb();
|
|
1183
|
+
}
|
|
1184
|
+
this.telemetry?.span.end();
|
|
1185
|
+
}
|
|
1147
1186
|
/**
|
|
1148
1187
|
* Handle adding a callback for when a message is received.
|
|
1149
1188
|
* @param msg The message that was received.
|
|
@@ -1196,4 +1235,4 @@ export {
|
|
|
1196
1235
|
Transport,
|
|
1197
1236
|
Connection
|
|
1198
1237
|
};
|
|
1199
|
-
//# sourceMappingURL=chunk-
|
|
1238
|
+
//# sourceMappingURL=chunk-AXZPYUY6.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../transport/options.ts","../transport/sessionStateMachine/common.ts","../transport/sessionStateMachine/SessionConnecting.ts","../transport/sessionStateMachine/SessionNoConnection.ts","../transport/sessionStateMachine/SessionWaitingForHandshake.ts","../transport/sessionStateMachine/SessionHandshaking.ts","../transport/sessionStateMachine/SessionConnected.ts","../transport/sessionStateMachine/SessionBackingOff.ts","../transport/sessionStateMachine/transitions.ts","../transport/events.ts","../transport/transport.ts","../transport/connection.ts"],"sourcesContent":["import { NaiveJsonCodec } from '../codec/json';\nimport { ConnectionRetryOptions } from './rateLimit';\nimport { SessionOptions } from './sessionStateMachine/common';\n\nexport type TransportOptions = SessionOptions;\n\nexport type ProvidedTransportOptions = Partial<TransportOptions>;\n\nexport const defaultTransportOptions: TransportOptions = {\n heartbeatIntervalMs: 1_000,\n heartbeatsUntilDead: 2,\n sessionDisconnectGraceMs: 5_000,\n connectionTimeoutMs: 2_000,\n handshakeTimeoutMs: 1_000,\n enableTransparentSessionReconnects: true,\n codec: NaiveJsonCodec,\n};\n\nexport type ClientTransportOptions = TransportOptions & ConnectionRetryOptions;\n\nexport type ProvidedClientTransportOptions = Partial<ClientTransportOptions>;\n\nconst defaultConnectionRetryOptions: ConnectionRetryOptions = {\n baseIntervalMs: 150,\n maxJitterMs: 200,\n maxBackoffMs: 32_000,\n attemptBudgetCapacity: 5,\n budgetRestoreIntervalMs: 200,\n};\n\nexport const defaultClientTransportOptions: ClientTransportOptions = {\n ...defaultTransportOptions,\n ...defaultConnectionRetryOptions,\n};\n\nexport type ServerTransportOptions = TransportOptions;\n\nexport type ProvidedServerTransportOptions = Partial<ServerTransportOptions>;\n\nexport const defaultServerTransportOptions: ServerTransportOptions = {\n ...defaultTransportOptions,\n};\n","import { Logger, MessageMetadata } from '../../logging';\nimport { TelemetryInfo } from '../../tracing';\nimport {\n OpaqueTransportMessage,\n OpaqueTransportMessageSchema,\n PartialTransportMessage,\n ProtocolVersion,\n TransportClientId,\n TransportMessage,\n} from '../message';\nimport { Value } from '@sinclair/typebox/value';\nimport { Codec } from '../../codec';\nimport { generateId } from '../id';\nimport { Tracer } from '@opentelemetry/api';\n\nexport const enum SessionState {\n NoConnection = 'NoConnection',\n BackingOff = 'BackingOff',\n Connecting = 'Connecting',\n Handshaking = 'Handshaking',\n Connected = 'Connected',\n WaitingForHandshake = 'WaitingForHandshake',\n}\n\nexport const ERR_CONSUMED = `session state has been consumed and is no longer valid`;\n\nabstract class StateMachineState {\n abstract readonly state: SessionState;\n\n /*\n * Whether this state has been consumed\n * and we've moved on to another state\n */\n _isConsumed: boolean;\n\n // called when we're transitioning to another state\n // note that this is internal and should not be called directly\n // by consumers, the proxy will call this when the state is consumed\n // and we're transitioning to another state\n abstract _handleStateExit(): void;\n\n // called when we exit the state machine entirely\n // note that this is internal and should not be called directly\n // by consumers, the proxy will call this when .close is closed\n abstract _handleClose(): void;\n\n /**\n * Cleanup this state machine state and mark it as consumed.\n * After calling close, it is an error to access any properties on the state.\n * You should never need to call this as a consumer.\n *\n * If you're looking to close the session from the client,\n * use `.hardDisconnect` on the client transport.\n */\n close(): void {\n this._handleClose();\n }\n\n constructor() {\n this._isConsumed = false;\n\n // proxy helps us prevent access to properties after the state has been consumed\n // e.g. if we hold a reference to a state and try to access it after it's been consumed\n // we intercept the access and throw an error to help catch bugs\n return new Proxy(this, {\n get(target, prop) {\n // always allow access to _isConsumed, id, and state\n if (prop === '_isConsumed' || prop === 'id' || prop === 'state') {\n return Reflect.get(target, prop);\n }\n\n // modify _handleStateExit\n if (prop === '_handleStateExit') {\n return () => {\n target._isConsumed = true;\n target._handleStateExit();\n };\n }\n\n // modify _handleClose\n if (prop === '_handleClose') {\n return () => {\n // target is the non-proxied object, we need to set _isConsumed again\n target._isConsumed = true;\n target._handleStateExit();\n target._handleClose();\n };\n }\n\n if (target._isConsumed) {\n throw new Error(\n `${ERR_CONSUMED}: getting ${prop.toString()} on consumed state`,\n );\n }\n\n return Reflect.get(target, prop);\n },\n set(target, prop, value) {\n if (target._isConsumed) {\n throw new Error(\n `${ERR_CONSUMED}: setting ${prop.toString()} on consumed state`,\n );\n }\n\n return Reflect.set(target, prop, value);\n },\n });\n }\n}\n\nexport interface SessionOptions {\n /**\n * Frequency at which to send heartbeat acknowledgements\n */\n heartbeatIntervalMs: number;\n /**\n * Number of elapsed heartbeats without a response message before we consider\n * the connection dead.\n */\n heartbeatsUntilDead: number;\n /**\n * Max duration that a session can be without a connection before we consider\n * it dead. This deadline is carried between states and is used to determine\n * when to consider the session a lost cause and delete it entirely.\n * Generally, this should be strictly greater than the sum of\n * {@link connectionTimeoutMs} and {@link handshakeTimeoutMs}.\n */\n sessionDisconnectGraceMs: number;\n /**\n * Connection timeout in milliseconds\n */\n connectionTimeoutMs: number;\n /**\n * Handshake timeout in milliseconds\n */\n handshakeTimeoutMs: number;\n /**\n * Whether to enable transparent session reconnects\n */\n enableTransparentSessionReconnects: boolean;\n /**\n * The codec to use for encoding/decoding messages over the wire\n */\n codec: Codec;\n}\n\n// all session states have a from and options\nexport interface CommonSessionProps {\n from: TransportClientId;\n options: SessionOptions;\n tracer: Tracer;\n log: Logger | undefined;\n}\n\nexport abstract class CommonSession extends StateMachineState {\n readonly from: TransportClientId;\n readonly options: SessionOptions;\n\n tracer: Tracer;\n log?: Logger;\n abstract get loggingMetadata(): MessageMetadata;\n\n constructor({ from, options, log, tracer }: CommonSessionProps) {\n super();\n this.from = from;\n this.options = options;\n this.log = log;\n this.tracer = tracer;\n }\n\n parseMsg(msg: Uint8Array): OpaqueTransportMessage | null {\n const parsedMsg = this.options.codec.fromBuffer(msg);\n\n if (parsedMsg === null) {\n this.log?.error(\n `received malformed msg: ${Buffer.from(msg).toString('base64')}`,\n this.loggingMetadata,\n );\n\n return null;\n }\n\n if (!Value.Check(OpaqueTransportMessageSchema, parsedMsg)) {\n this.log?.error(`received invalid msg: ${JSON.stringify(parsedMsg)}`, {\n ...this.loggingMetadata,\n validationErrors: [\n ...Value.Errors(OpaqueTransportMessageSchema, parsedMsg),\n ],\n });\n\n return null;\n }\n\n return parsedMsg;\n }\n}\n\nexport type InheritedProperties = Pick<\n IdentifiedSession,\n 'id' | 'from' | 'to' | 'seq' | 'ack' | 'sendBuffer' | 'telemetry' | 'options'\n>;\n\nexport type SessionId = string;\n\n// all sessions where we know the other side's client id\nexport interface IdentifiedSessionProps extends CommonSessionProps {\n id: SessionId;\n to: TransportClientId;\n seq: number;\n ack: number;\n sendBuffer: Array<OpaqueTransportMessage>;\n telemetry: TelemetryInfo;\n protocolVersion: ProtocolVersion;\n}\n\nexport abstract class IdentifiedSession extends CommonSession {\n readonly id: SessionId;\n readonly telemetry: TelemetryInfo;\n readonly to: TransportClientId;\n readonly protocolVersion: ProtocolVersion;\n\n /**\n * Index of the message we will send next (excluding handshake)\n */\n seq: number;\n\n /**\n * Number of unique messages we've received this session (excluding handshake)\n */\n ack: number;\n sendBuffer: Array<OpaqueTransportMessage>;\n\n constructor(props: IdentifiedSessionProps) {\n const { id, to, seq, ack, sendBuffer, telemetry, log, protocolVersion } =\n props;\n super(props);\n this.id = id;\n this.to = to;\n this.seq = seq;\n this.ack = ack;\n this.sendBuffer = sendBuffer;\n this.telemetry = telemetry;\n this.log = log;\n this.protocolVersion = protocolVersion;\n }\n\n get loggingMetadata(): MessageMetadata {\n const metadata: MessageMetadata = {\n clientId: this.from,\n connectedTo: this.to,\n sessionId: this.id,\n };\n\n if (this.telemetry.span.isRecording()) {\n const spanContext = this.telemetry.span.spanContext();\n metadata.telemetry = {\n traceId: spanContext.traceId,\n spanId: spanContext.spanId,\n };\n }\n\n return metadata;\n }\n\n constructMsg<Payload>(\n partialMsg: PartialTransportMessage<Payload>,\n ): TransportMessage<Payload> {\n const msg = {\n ...partialMsg,\n id: generateId(),\n to: this.to,\n from: this.from,\n seq: this.seq,\n ack: this.ack,\n };\n\n this.seq++;\n\n return msg;\n }\n\n nextSeq(): number {\n return this.sendBuffer.length > 0 ? this.sendBuffer[0].seq : this.seq;\n }\n\n send(msg: PartialTransportMessage): string {\n const constructedMsg = this.constructMsg(msg);\n this.sendBuffer.push(constructedMsg);\n\n return constructedMsg.id;\n }\n\n _handleStateExit(): void {\n // noop\n }\n\n _handleClose(): void {\n // zero out the buffer\n this.sendBuffer.length = 0;\n this.telemetry.span.end();\n }\n}\n\nexport interface IdentifiedSessionWithGracePeriodListeners {\n onSessionGracePeriodElapsed: () => void;\n}\n\nexport interface IdentifiedSessionWithGracePeriodProps\n extends IdentifiedSessionProps {\n graceExpiryTime: number;\n listeners: IdentifiedSessionWithGracePeriodListeners;\n}\n\nexport abstract class IdentifiedSessionWithGracePeriod extends IdentifiedSession {\n graceExpiryTime: number;\n protected gracePeriodTimeout?: ReturnType<typeof setTimeout>;\n\n listeners: IdentifiedSessionWithGracePeriodListeners;\n\n constructor(props: IdentifiedSessionWithGracePeriodProps) {\n super(props);\n this.listeners = props.listeners;\n\n this.graceExpiryTime = props.graceExpiryTime;\n this.gracePeriodTimeout = setTimeout(() => {\n this.listeners.onSessionGracePeriodElapsed();\n }, this.graceExpiryTime - Date.now());\n }\n\n _handleStateExit(): void {\n super._handleStateExit();\n\n if (this.gracePeriodTimeout) {\n clearTimeout(this.gracePeriodTimeout);\n this.gracePeriodTimeout = undefined;\n }\n }\n\n _handleClose(): void {\n super._handleClose();\n }\n}\n","import { Connection } from '../connection';\nimport {\n IdentifiedSessionWithGracePeriod,\n IdentifiedSessionWithGracePeriodListeners,\n IdentifiedSessionWithGracePeriodProps,\n SessionState,\n} from './common';\n\nexport interface SessionConnectingListeners\n extends IdentifiedSessionWithGracePeriodListeners {\n onConnectionEstablished: (conn: Connection) => void;\n onConnectionFailed: (err: unknown) => void;\n\n // timeout related\n onConnectionTimeout: () => void;\n}\n\nexport interface SessionConnectingProps<ConnType extends Connection>\n extends IdentifiedSessionWithGracePeriodProps {\n connPromise: Promise<ConnType>;\n listeners: SessionConnectingListeners;\n}\n\n/*\n * A session that is connecting but we don't have access to the raw connection yet.\n * See transitions.ts for valid transitions.\n */\nexport class SessionConnecting<\n ConnType extends Connection,\n> extends IdentifiedSessionWithGracePeriod {\n readonly state = SessionState.Connecting as const;\n connPromise: Promise<ConnType>;\n listeners: SessionConnectingListeners;\n\n connectionTimeout?: ReturnType<typeof setTimeout>;\n\n constructor(props: SessionConnectingProps<ConnType>) {\n super(props);\n this.connPromise = props.connPromise;\n this.listeners = props.listeners;\n\n this.connPromise.then(\n (conn) => {\n if (this._isConsumed) return;\n this.listeners.onConnectionEstablished(conn);\n },\n (err) => {\n if (this._isConsumed) return;\n this.listeners.onConnectionFailed(err);\n },\n );\n\n this.connectionTimeout = setTimeout(() => {\n this.listeners.onConnectionTimeout();\n }, this.options.connectionTimeoutMs);\n }\n\n // close a pending connection if it resolves, ignore errors if the promise\n // ends up rejected anyways\n bestEffortClose() {\n // these can technically be stale if the connPromise resolves after the\n // state has transitioned, but that's fine, this is best effort anyways\n // we pull these out so even if the state has transitioned, we can still log\n // without erroring out\n const logger = this.log;\n const metadata = this.loggingMetadata;\n\n this.connPromise\n .then((conn) => {\n conn.close();\n logger?.info(\n 'connection eventually resolved but session has transitioned, closed connection',\n {\n ...metadata,\n ...conn.loggingMetadata,\n },\n );\n })\n .catch(() => {\n // ignore errors\n });\n }\n\n _handleStateExit(): void {\n super._handleStateExit();\n\n if (this.connectionTimeout) {\n clearTimeout(this.connectionTimeout);\n this.connectionTimeout = undefined;\n }\n }\n\n _handleClose(): void {\n // close the pending connection if it resolves\n this.bestEffortClose();\n super._handleClose();\n }\n}\n","import {\n IdentifiedSessionWithGracePeriod,\n IdentifiedSessionWithGracePeriodListeners,\n IdentifiedSessionWithGracePeriodProps,\n SessionState,\n} from './common';\n\nexport type SessionNoConnectionListeners =\n IdentifiedSessionWithGracePeriodListeners;\n\nexport type SessionNoConnectionProps = IdentifiedSessionWithGracePeriodProps;\n\n/*\n * A session that is not connected and cannot send or receive messages.\n * See transitions.ts for valid transitions.\n */\nexport class SessionNoConnection extends IdentifiedSessionWithGracePeriod {\n readonly state = SessionState.NoConnection as const;\n\n _handleClose(): void {\n super._handleClose();\n }\n\n _handleStateExit(): void {\n super._handleStateExit();\n }\n}\n","import { Static } from '@sinclair/typebox';\nimport { Connection } from '../connection';\nimport {\n HandshakeErrorResponseCodes,\n OpaqueTransportMessage,\n TransportMessage,\n} from '../message';\nimport { CommonSession, CommonSessionProps, SessionState } from './common';\n\nexport interface SessionWaitingForHandshakeListeners {\n onConnectionErrored: (err: unknown) => void;\n onConnectionClosed: () => void;\n onHandshake: (msg: OpaqueTransportMessage) => void;\n onInvalidHandshake: (\n reason: string,\n code: Static<typeof HandshakeErrorResponseCodes>,\n ) => void;\n\n // timeout related\n onHandshakeTimeout: () => void;\n}\n\nexport interface SessionWaitingForHandshakeProps<ConnType extends Connection>\n extends CommonSessionProps {\n conn: ConnType;\n listeners: SessionWaitingForHandshakeListeners;\n}\n\n/*\n * Server-side session that has a connection but is waiting for the client to identify itself.\n * See transitions.ts for valid transitions.\n */\nexport class SessionWaitingForHandshake<\n ConnType extends Connection,\n> extends CommonSession {\n readonly state = SessionState.WaitingForHandshake as const;\n conn: ConnType;\n listeners: SessionWaitingForHandshakeListeners;\n\n handshakeTimeout?: ReturnType<typeof setTimeout>;\n\n constructor(props: SessionWaitingForHandshakeProps<ConnType>) {\n super(props);\n this.conn = props.conn;\n this.listeners = props.listeners;\n\n this.handshakeTimeout = setTimeout(() => {\n this.listeners.onHandshakeTimeout();\n }, this.options.handshakeTimeoutMs);\n\n this.conn.addDataListener(this.onHandshakeData);\n this.conn.addErrorListener(this.listeners.onConnectionErrored);\n this.conn.addCloseListener(this.listeners.onConnectionClosed);\n }\n\n get loggingMetadata() {\n return {\n clientId: this.from,\n connId: this.conn.id,\n ...this.conn.loggingMetadata,\n };\n }\n\n onHandshakeData = (msg: Uint8Array) => {\n const parsedMsg = this.parseMsg(msg);\n if (parsedMsg === null) {\n this.listeners.onInvalidHandshake(\n 'could not parse message',\n 'MALFORMED_HANDSHAKE',\n );\n\n return;\n }\n\n // after this fires, the listener is responsible for transitioning the session\n // and thus removing the handshake timeout\n this.listeners.onHandshake(parsedMsg);\n };\n\n sendHandshake(msg: TransportMessage): boolean {\n return this.conn.send(this.options.codec.toBuffer(msg));\n }\n\n _handleStateExit(): void {\n this.conn.removeDataListener(this.onHandshakeData);\n this.conn.removeErrorListener(this.listeners.onConnectionErrored);\n this.conn.removeCloseListener(this.listeners.onConnectionClosed);\n clearTimeout(this.handshakeTimeout);\n this.handshakeTimeout = undefined;\n }\n\n _handleClose(): void {\n this.conn.close();\n }\n}\n","import { Static } from '@sinclair/typebox';\nimport { Connection } from '../connection';\nimport {\n OpaqueTransportMessage,\n TransportMessage,\n HandshakeErrorResponseCodes,\n} from '../message';\nimport {\n IdentifiedSessionWithGracePeriod,\n IdentifiedSessionWithGracePeriodListeners,\n IdentifiedSessionWithGracePeriodProps,\n SessionState,\n} from './common';\n\nexport interface SessionHandshakingListeners\n extends IdentifiedSessionWithGracePeriodListeners {\n onConnectionErrored: (err: unknown) => void;\n onConnectionClosed: () => void;\n onHandshake: (msg: OpaqueTransportMessage) => void;\n onInvalidHandshake: (\n reason: string,\n code: Static<typeof HandshakeErrorResponseCodes>,\n ) => void;\n\n // timeout related\n onHandshakeTimeout: () => void;\n}\n\nexport interface SessionHandshakingProps<ConnType extends Connection>\n extends IdentifiedSessionWithGracePeriodProps {\n conn: ConnType;\n listeners: SessionHandshakingListeners;\n}\n\n/*\n * A session that is handshaking and waiting for the other side to identify itself.\n * See transitions.ts for valid transitions.\n */\nexport class SessionHandshaking<\n ConnType extends Connection,\n> extends IdentifiedSessionWithGracePeriod {\n readonly state = SessionState.Handshaking as const;\n conn: ConnType;\n listeners: SessionHandshakingListeners;\n\n handshakeTimeout?: ReturnType<typeof setTimeout>;\n\n constructor(props: SessionHandshakingProps<ConnType>) {\n super(props);\n this.conn = props.conn;\n this.listeners = props.listeners;\n\n this.handshakeTimeout = setTimeout(() => {\n this.listeners.onHandshakeTimeout();\n }, this.options.handshakeTimeoutMs);\n\n this.conn.addDataListener(this.onHandshakeData);\n this.conn.addErrorListener(this.listeners.onConnectionErrored);\n this.conn.addCloseListener(this.listeners.onConnectionClosed);\n }\n\n get loggingMetadata() {\n return {\n ...super.loggingMetadata,\n ...this.conn.loggingMetadata,\n };\n }\n\n onHandshakeData = (msg: Uint8Array) => {\n const parsedMsg = this.parseMsg(msg);\n if (parsedMsg === null) {\n this.listeners.onInvalidHandshake(\n 'could not parse message',\n 'MALFORMED_HANDSHAKE',\n );\n\n return;\n }\n\n this.listeners.onHandshake(parsedMsg);\n };\n\n sendHandshake(msg: TransportMessage): boolean {\n return this.conn.send(this.options.codec.toBuffer(msg));\n }\n\n _handleStateExit(): void {\n super._handleStateExit();\n this.conn.removeDataListener(this.onHandshakeData);\n this.conn.removeErrorListener(this.listeners.onConnectionErrored);\n this.conn.removeCloseListener(this.listeners.onConnectionClosed);\n\n if (this.handshakeTimeout) {\n clearTimeout(this.handshakeTimeout);\n this.handshakeTimeout = undefined;\n }\n }\n\n _handleClose(): void {\n super._handleClose();\n this.conn.close();\n }\n}\n","import { Static } from '@sinclair/typebox';\nimport {\n ControlFlags,\n ControlMessageAckSchema,\n OpaqueTransportMessage,\n PartialTransportMessage,\n isAck,\n} from '../message';\nimport {\n IdentifiedSession,\n IdentifiedSessionProps,\n SessionState,\n} from './common';\nimport { Connection } from '../connection';\nimport { SpanStatusCode } from '@opentelemetry/api';\n\nexport interface SessionConnectedListeners {\n onConnectionErrored: (err: unknown) => void;\n onConnectionClosed: () => void;\n onMessage: (msg: OpaqueTransportMessage) => void;\n onInvalidMessage: (reason: string) => void;\n}\n\nexport interface SessionConnectedProps<ConnType extends Connection>\n extends IdentifiedSessionProps {\n conn: ConnType;\n listeners: SessionConnectedListeners;\n}\n\n/*\n * A session that is connected and can send and receive messages.\n * See transitions.ts for valid transitions.\n */\nexport class SessionConnected<\n ConnType extends Connection,\n> extends IdentifiedSession {\n readonly state = SessionState.Connected as const;\n conn: ConnType;\n listeners: SessionConnectedListeners;\n\n private heartbeatHandle?: ReturnType<typeof setInterval> | undefined;\n private heartbeatMisses = 0;\n isActivelyHeartbeating: boolean;\n\n updateBookkeeping(ack: number, seq: number) {\n this.sendBuffer = this.sendBuffer.filter((unacked) => unacked.seq >= ack);\n this.ack = seq + 1;\n this.heartbeatMisses = 0;\n }\n\n send(msg: PartialTransportMessage): string {\n const constructedMsg = this.constructMsg(msg);\n this.sendBuffer.push(constructedMsg);\n this.conn.send(this.options.codec.toBuffer(constructedMsg));\n\n return constructedMsg.id;\n }\n\n constructor(props: SessionConnectedProps<ConnType>) {\n super(props);\n this.conn = props.conn;\n this.listeners = props.listeners;\n\n this.conn.addDataListener(this.onMessageData);\n this.conn.addCloseListener(this.listeners.onConnectionClosed);\n this.conn.addErrorListener(this.listeners.onConnectionErrored);\n\n // send any buffered messages\n if (this.sendBuffer.length > 0) {\n this.log?.info(\n `sending ${\n this.sendBuffer.length\n } buffered messages, starting at seq ${this.nextSeq()}`,\n this.loggingMetadata,\n );\n\n for (const msg of this.sendBuffer) {\n this.conn.send(this.options.codec.toBuffer(msg));\n }\n }\n\n // dont explicity clear the buffer, we'll just filter out old messages\n // when we receive an ack\n\n // setup heartbeat\n this.isActivelyHeartbeating = false;\n this.heartbeatHandle = setInterval(() => {\n const misses = this.heartbeatMisses;\n const missDuration = misses * this.options.heartbeatIntervalMs;\n if (misses >= this.options.heartbeatsUntilDead) {\n this.log?.info(\n `closing connection to ${this.to} due to inactivity (missed ${misses} heartbeats which is ${missDuration}ms)`,\n this.loggingMetadata,\n );\n this.telemetry.span.addEvent('closing connection due to inactivity');\n\n // it is OK to close this even on the client when we can't trust the client timer\n // due to browser throttling or hibernation\n // at worst, this interval will fire later than what the server expects and the server\n // will have already closed the connection\n // this just helps us in cases where we have a proxying setup where the server has closed\n // the connection but the proxy hasn't synchronized the server-side close to the client so\n // the client isn't stuck with a pseudo-dead connection forever\n this.conn.close();\n clearInterval(this.heartbeatHandle);\n this.heartbeatHandle = undefined;\n\n return;\n }\n\n if (this.isActivelyHeartbeating) {\n this.sendHeartbeat();\n }\n\n this.heartbeatMisses++;\n }, this.options.heartbeatIntervalMs);\n }\n\n get loggingMetadata() {\n return {\n ...super.loggingMetadata,\n ...this.conn.loggingMetadata,\n };\n }\n\n startActiveHeartbeat() {\n this.isActivelyHeartbeating = true;\n }\n\n private sendHeartbeat() {\n this.log?.debug('sending heartbeat', this.loggingMetadata);\n this.send({\n streamId: 'heartbeat',\n controlFlags: ControlFlags.AckBit,\n payload: {\n type: 'ACK',\n } satisfies Static<typeof ControlMessageAckSchema>,\n });\n }\n\n closeConnection() {\n this.conn.removeDataListener(this.onMessageData);\n this.conn.removeCloseListener(this.listeners.onConnectionClosed);\n this.conn.removeErrorListener(this.listeners.onConnectionErrored);\n this.conn.close();\n }\n\n onMessageData = (msg: Uint8Array) => {\n const parsedMsg = this.parseMsg(msg);\n if (parsedMsg === null) {\n this.listeners.onInvalidMessage('could not parse message');\n\n return;\n }\n\n // check message ordering here\n if (parsedMsg.seq !== this.ack) {\n if (parsedMsg.seq < this.ack) {\n this.log?.debug(\n `received duplicate msg (got seq: ${parsedMsg.seq}, wanted seq: ${this.ack}), discarding`,\n {\n ...this.loggingMetadata,\n transportMessage: parsedMsg,\n },\n );\n } else {\n const reason = `received out-of-order msg, closing connection (got seq: ${parsedMsg.seq}, wanted seq: ${this.ack})`;\n this.log?.warn(reason, {\n ...this.loggingMetadata,\n transportMessage: parsedMsg,\n tags: ['invariant-violation'],\n });\n\n this.telemetry.span.setStatus({\n code: SpanStatusCode.ERROR,\n message: reason,\n });\n\n // try to recover by closing the connection and re-handshaking\n // with the session intact\n this.closeConnection();\n }\n\n return;\n }\n\n // message is ok to update bookkeeping with\n this.log?.debug(`received msg`, {\n ...this.loggingMetadata,\n transportMessage: parsedMsg,\n });\n\n this.updateBookkeeping(parsedMsg.ack, parsedMsg.seq);\n\n // dispatch directly if its not an explicit ack\n if (!isAck(parsedMsg.controlFlags)) {\n this.listeners.onMessage(parsedMsg);\n\n return;\n }\n\n // discard acks (unless we aren't heartbeating in which case just respond)\n this.log?.debug(`discarding msg (ack bit set)`, {\n ...this.loggingMetadata,\n transportMessage: parsedMsg,\n });\n\n // if we are not actively heartbeating, we are in passive\n // heartbeat mode and should send a response to the ack\n if (!this.isActivelyHeartbeating) {\n this.sendHeartbeat();\n }\n };\n\n _handleStateExit(): void {\n super._handleStateExit();\n this.conn.removeDataListener(this.onMessageData);\n this.conn.removeCloseListener(this.listeners.onConnectionClosed);\n this.conn.removeErrorListener(this.listeners.onConnectionErrored);\n\n if (this.heartbeatHandle) {\n clearInterval(this.heartbeatHandle);\n this.heartbeatHandle = undefined;\n }\n }\n\n _handleClose(): void {\n super._handleClose();\n this.conn.close();\n }\n}\n","import {\n IdentifiedSessionWithGracePeriod,\n IdentifiedSessionWithGracePeriodListeners,\n IdentifiedSessionWithGracePeriodProps,\n SessionState,\n} from './common';\n\nexport interface SessionBackingOffListeners\n extends IdentifiedSessionWithGracePeriodListeners {\n onBackoffFinished: () => void;\n}\n\nexport interface SessionBackingOffProps\n extends IdentifiedSessionWithGracePeriodProps {\n backoffMs: number;\n listeners: SessionBackingOffListeners;\n}\n\n/*\n * A session that is backing off before attempting to connect.\n * See transitions.ts for valid transitions.\n */\nexport class SessionBackingOff extends IdentifiedSessionWithGracePeriod {\n readonly state = SessionState.BackingOff as const;\n listeners: SessionBackingOffListeners;\n\n backoffTimeout?: ReturnType<typeof setTimeout>;\n\n constructor(props: SessionBackingOffProps) {\n super(props);\n this.listeners = props.listeners;\n\n this.backoffTimeout = setTimeout(() => {\n this.listeners.onBackoffFinished();\n }, props.backoffMs);\n }\n\n _handleClose(): void {\n super._handleClose();\n }\n\n _handleStateExit(): void {\n super._handleStateExit();\n\n if (this.backoffTimeout) {\n clearTimeout(this.backoffTimeout);\n this.backoffTimeout = undefined;\n }\n }\n}\n","import { OpaqueTransportMessage, TransportClientId } from '..';\nimport {\n SessionConnecting,\n SessionConnectingListeners,\n} from './SessionConnecting';\nimport {\n SessionNoConnection,\n SessionNoConnectionListeners,\n} from './SessionNoConnection';\nimport {\n IdentifiedSession,\n IdentifiedSessionProps,\n IdentifiedSessionWithGracePeriod,\n IdentifiedSessionWithGracePeriodProps,\n SessionOptions,\n} from './common';\nimport {\n PropagationContext,\n createConnectionTelemetryInfo,\n createSessionTelemetryInfo,\n} from '../../tracing';\nimport {\n SessionWaitingForHandshake,\n SessionWaitingForHandshakeListeners,\n} from './SessionWaitingForHandshake';\nimport {\n SessionHandshaking,\n SessionHandshakingListeners,\n} from './SessionHandshaking';\nimport {\n SessionConnected,\n SessionConnectedListeners,\n} from './SessionConnected';\nimport { generateId } from '../id';\nimport { Connection } from '../connection';\nimport { Logger } from '../../logging';\nimport {\n SessionBackingOff,\n SessionBackingOffListeners,\n} from './SessionBackingOff';\nimport { ProtocolVersion } from '../message';\nimport { Tracer } from '@opentelemetry/api';\n\nfunction inheritSharedSession(\n session: IdentifiedSession,\n): IdentifiedSessionProps {\n return {\n id: session.id,\n from: session.from,\n to: session.to,\n seq: session.seq,\n ack: session.ack,\n sendBuffer: session.sendBuffer,\n telemetry: session.telemetry,\n options: session.options,\n log: session.log,\n tracer: session.tracer,\n protocolVersion: session.protocolVersion,\n };\n}\n\nfunction inheritSharedSessionWithGrace(\n session: IdentifiedSessionWithGracePeriod,\n): Omit<IdentifiedSessionWithGracePeriodProps, 'listeners'> {\n return {\n ...inheritSharedSession(session),\n graceExpiryTime: session.graceExpiryTime,\n };\n}\n\nexport const SessionStateGraph = {\n entrypoints: {\n NoConnection: (\n to: TransportClientId,\n from: TransportClientId,\n listeners: SessionNoConnectionListeners,\n options: SessionOptions,\n protocolVersion: ProtocolVersion,\n tracer: Tracer,\n log?: Logger,\n ) => {\n const id = `session-${generateId()}`;\n const telemetry = createSessionTelemetryInfo(tracer, id, to, from);\n const sendBuffer: Array<OpaqueTransportMessage> = [];\n\n const session = new SessionNoConnection({\n listeners,\n id,\n from,\n to,\n seq: 0,\n ack: 0,\n graceExpiryTime: Date.now() + options.sessionDisconnectGraceMs,\n sendBuffer,\n telemetry,\n options,\n protocolVersion,\n tracer,\n log,\n });\n\n session.log?.info(`session ${session.id} created in NoConnection state`, {\n ...session.loggingMetadata,\n tags: ['state-transition'],\n });\n\n return session;\n },\n WaitingForHandshake: <ConnType extends Connection>(\n from: TransportClientId,\n conn: ConnType,\n listeners: SessionWaitingForHandshakeListeners,\n options: SessionOptions,\n tracer: Tracer,\n log?: Logger,\n ): SessionWaitingForHandshake<ConnType> => {\n const session = new SessionWaitingForHandshake({\n conn,\n listeners,\n from,\n options,\n tracer,\n log,\n });\n\n session.log?.info(`session created in WaitingForHandshake state`, {\n ...session.loggingMetadata,\n tags: ['state-transition'],\n });\n\n return session;\n },\n },\n // All of the transitions 'move'/'consume' the old session and return a new one.\n // After a session is transitioned, any usage of the old session will throw.\n transition: {\n // happy path transitions\n NoConnectionToBackingOff: (\n oldSession: SessionNoConnection,\n backoffMs: number,\n listeners: SessionBackingOffListeners,\n ): SessionBackingOff => {\n const carriedState = inheritSharedSessionWithGrace(oldSession);\n oldSession._handleStateExit();\n\n const session = new SessionBackingOff({\n backoffMs,\n listeners,\n ...carriedState,\n });\n\n session.log?.info(\n `session ${session.id} transition from NoConnection to BackingOff`,\n {\n ...session.loggingMetadata,\n tags: ['state-transition'],\n },\n );\n\n return session;\n },\n BackingOffToConnecting: <ConnType extends Connection>(\n oldSession: SessionBackingOff,\n connPromise: Promise<ConnType>,\n listeners: SessionConnectingListeners,\n ): SessionConnecting<ConnType> => {\n const carriedState = inheritSharedSessionWithGrace(oldSession);\n oldSession._handleStateExit();\n\n const session = new SessionConnecting({\n connPromise,\n listeners,\n ...carriedState,\n });\n\n session.log?.info(\n `session ${session.id} transition from BackingOff to Connecting`,\n {\n ...session.loggingMetadata,\n tags: ['state-transition'],\n },\n );\n\n return session;\n },\n ConnectingToHandshaking: <ConnType extends Connection>(\n oldSession: SessionConnecting<ConnType>,\n conn: ConnType,\n listeners: SessionHandshakingListeners,\n ): SessionHandshaking<ConnType> => {\n const carriedState = inheritSharedSessionWithGrace(oldSession);\n oldSession._handleStateExit();\n\n const session = new SessionHandshaking({\n conn,\n listeners,\n ...carriedState,\n });\n\n conn.telemetry = createConnectionTelemetryInfo(\n session.tracer,\n conn,\n session.telemetry,\n );\n session.log?.info(\n `session ${session.id} transition from Connecting to Handshaking`,\n {\n ...session.loggingMetadata,\n tags: ['state-transition'],\n },\n );\n\n return session;\n },\n HandshakingToConnected: <ConnType extends Connection>(\n oldSession: SessionHandshaking<ConnType>,\n listeners: SessionConnectedListeners,\n ): SessionConnected<ConnType> => {\n const carriedState = inheritSharedSession(oldSession);\n const conn = oldSession.conn;\n oldSession._handleStateExit();\n\n const session = new SessionConnected({\n conn,\n listeners,\n ...carriedState,\n });\n\n session.log?.info(\n `session ${session.id} transition from Handshaking to Connected`,\n {\n ...session.loggingMetadata,\n tags: ['state-transition'],\n },\n );\n\n return session;\n },\n WaitingForHandshakeToConnected: <ConnType extends Connection>(\n pendingSession: SessionWaitingForHandshake<ConnType>,\n oldSession: SessionNoConnection | undefined,\n sessionId: string,\n to: TransportClientId,\n propagationCtx: PropagationContext | undefined,\n listeners: SessionConnectedListeners,\n protocolVersion: ProtocolVersion,\n ): SessionConnected<ConnType> => {\n const conn = pendingSession.conn;\n const { from, options } = pendingSession;\n const carriedState: IdentifiedSessionProps = oldSession\n ? // old session exists, inherit state\n inheritSharedSession(oldSession)\n : // old session does not exist, create new state\n {\n id: sessionId,\n from,\n to,\n seq: 0,\n ack: 0,\n sendBuffer: [],\n telemetry: createSessionTelemetryInfo(\n pendingSession.tracer,\n sessionId,\n to,\n from,\n propagationCtx,\n ),\n options,\n tracer: pendingSession.tracer,\n log: pendingSession.log,\n protocolVersion,\n };\n\n pendingSession._handleStateExit();\n oldSession?._handleStateExit();\n\n const session = new SessionConnected({\n conn,\n listeners,\n ...carriedState,\n });\n\n conn.telemetry = createConnectionTelemetryInfo(\n session.tracer,\n conn,\n session.telemetry,\n );\n session.log?.info(\n `session ${session.id} transition from WaitingForHandshake to Connected`,\n {\n ...session.loggingMetadata,\n tags: ['state-transition'],\n },\n );\n\n return session;\n },\n // disconnect paths\n BackingOffToNoConnection: (\n oldSession: SessionBackingOff,\n listeners: SessionNoConnectionListeners,\n ): SessionNoConnection => {\n const carriedState = inheritSharedSessionWithGrace(oldSession);\n oldSession._handleStateExit();\n\n const session = new SessionNoConnection({\n listeners,\n ...carriedState,\n });\n session.log?.info(\n `session ${session.id} transition from BackingOff to NoConnection`,\n {\n ...session.loggingMetadata,\n tags: ['state-transition'],\n },\n );\n\n return session;\n },\n ConnectingToNoConnection: <ConnType extends Connection>(\n oldSession: SessionConnecting<ConnType>,\n listeners: SessionNoConnectionListeners,\n ): SessionNoConnection => {\n const carriedState = inheritSharedSessionWithGrace(oldSession);\n oldSession.bestEffortClose();\n oldSession._handleStateExit();\n\n const session = new SessionNoConnection({\n listeners,\n ...carriedState,\n });\n session.log?.info(\n `session ${session.id} transition from Connecting to NoConnection`,\n {\n ...session.loggingMetadata,\n tags: ['state-transition'],\n },\n );\n\n return session;\n },\n HandshakingToNoConnection: <ConnType extends Connection>(\n oldSession: SessionHandshaking<ConnType>,\n listeners: SessionNoConnectionListeners,\n ): SessionNoConnection => {\n const carriedState = inheritSharedSessionWithGrace(oldSession);\n oldSession.conn.close();\n oldSession._handleStateExit();\n\n const session = new SessionNoConnection({\n listeners,\n ...carriedState,\n });\n session.log?.info(\n `session ${session.id} transition from Handshaking to NoConnection`,\n {\n ...session.loggingMetadata,\n tags: ['state-transition'],\n },\n );\n\n return session;\n },\n ConnectedToNoConnection: <ConnType extends Connection>(\n oldSession: SessionConnected<ConnType>,\n listeners: SessionNoConnectionListeners,\n ): SessionNoConnection => {\n const carriedState = inheritSharedSession(oldSession);\n const graceExpiryTime =\n Date.now() + oldSession.options.sessionDisconnectGraceMs;\n oldSession.conn.close();\n oldSession._handleStateExit();\n\n const session = new SessionNoConnection({\n listeners,\n graceExpiryTime,\n ...carriedState,\n });\n session.log?.info(\n `session ${session.id} transition from Connected to NoConnection`,\n {\n ...session.loggingMetadata,\n tags: ['state-transition'],\n },\n );\n\n return session;\n },\n },\n} as const;\n\nconst transitions = SessionStateGraph.transition;\n\nexport const ClientSessionStateGraph = {\n entrypoint: SessionStateGraph.entrypoints.NoConnection,\n transition: {\n // happy paths\n // NoConnection -> BackingOff: attempt to connect\n NoConnectionToBackingOff: transitions.NoConnectionToBackingOff,\n // BackingOff -> Connecting: backoff period elapsed, start connection\n BackingOffToConnecting: transitions.BackingOffToConnecting,\n // Connecting -> Handshaking: connection established, start handshake\n ConnectingToHandshaking: transitions.ConnectingToHandshaking,\n // Handshaking -> Connected: handshake complete, session ready\n HandshakingToConnected: transitions.HandshakingToConnected,\n\n // disconnect paths\n // BackingOff -> NoConnection: unused\n BackingOffToNoConnection: transitions.BackingOffToNoConnection,\n // Connecting -> NoConnection: connection failed or connection timeout\n ConnectingToNoConnection: transitions.ConnectingToNoConnection,\n // Handshaking -> NoConnection: connection closed or handshake timeout\n HandshakingToNoConnection: transitions.HandshakingToNoConnection,\n // Connected -> NoConnection: connection closed\n ConnectedToNoConnection: transitions.ConnectedToNoConnection,\n\n // destroy/close paths\n // NoConnection -> x: grace period elapsed\n // BackingOff -> x: grace period elapsed\n // Connecting -> x: grace period elapsed\n // Handshaking -> x: grace period elapsed or invalid handshake message or handshake rejection\n // Connected -> x: grace period elapsed or invalid message\n },\n};\n\nexport type ClientSession<ConnType extends Connection> =\n | SessionNoConnection\n | SessionBackingOff\n | SessionConnecting<ConnType>\n | SessionHandshaking<ConnType>\n | SessionConnected<ConnType>;\n\nexport const ServerSessionStateGraph = {\n entrypoint: SessionStateGraph.entrypoints.WaitingForHandshake,\n transition: {\n // happy paths\n // WaitingForHandshake -> Connected: handshake complete, session ready\n WaitingForHandshakeToConnected: transitions.WaitingForHandshakeToConnected,\n\n // disconnect paths\n // Connected -> NoConnection: connection closed\n ConnectedToNoConnection: transitions.ConnectedToNoConnection,\n\n // destroy/close paths\n // WaitingForHandshake -> x: handshake timeout elapsed or invalid handshake message or handshake rejection or connection closed\n },\n};\n\nexport type ServerSession<ConnType extends Connection> =\n // SessionWaitingForHandshake<ConnType> is stored separately in the server transport\n SessionConnected<ConnType> | SessionNoConnection;\n\nexport type Session<ConnType extends Connection> =\n | ClientSession<ConnType>\n | ServerSession<ConnType>;\n","import { type Static } from '@sinclair/typebox';\nimport { Connection } from './connection';\nimport { OpaqueTransportMessage, HandshakeErrorResponseCodes } from './message';\nimport { Session, SessionState } from './sessionStateMachine';\nimport { TransportStatus } from './transport';\n\nexport const ProtocolError = {\n RetriesExceeded: 'conn_retry_exceeded',\n HandshakeFailed: 'handshake_failed',\n MessageOrderingViolated: 'message_ordering_violated',\n InvalidMessage: 'invalid_message',\n} as const;\n\nexport type ProtocolErrorType =\n (typeof ProtocolError)[keyof typeof ProtocolError];\n\nexport interface EventMap {\n message: OpaqueTransportMessage;\n sessionStatus:\n | {\n status: 'created' | 'closing';\n session: Session<Connection>;\n }\n | {\n status: 'closed';\n session: Pick<Session<Connection>, 'id' | 'to'>;\n };\n sessionTransition:\n | { state: SessionState.Connected }\n | { state: SessionState.Handshaking }\n | { state: SessionState.Connecting }\n | { state: SessionState.BackingOff }\n | { state: SessionState.NoConnection };\n protocolError:\n | {\n type: (typeof ProtocolError)['HandshakeFailed'];\n code: Static<typeof HandshakeErrorResponseCodes>;\n message: string;\n }\n | {\n type: Omit<\n ProtocolErrorType,\n (typeof ProtocolError)['HandshakeFailed']\n >;\n message: string;\n };\n transportStatus: {\n status: TransportStatus;\n };\n}\n\nexport type EventTypes = keyof EventMap;\nexport type EventHandler<K extends EventTypes> = (\n event: EventMap[K],\n) => unknown;\n\nexport class EventDispatcher<T extends EventTypes> {\n private eventListeners: { [K in T]?: Set<EventHandler<K>> } = {};\n\n removeAllListeners() {\n this.eventListeners = {};\n }\n\n numberOfListeners<K extends T>(eventType: K) {\n return this.eventListeners[eventType]?.size ?? 0;\n }\n\n addEventListener<K extends T>(eventType: K, handler: EventHandler<K>) {\n if (!this.eventListeners[eventType]) {\n this.eventListeners[eventType] = new Set();\n }\n\n this.eventListeners[eventType]?.add(handler);\n }\n\n removeEventListener<K extends T>(eventType: K, handler: EventHandler<K>) {\n const handlers = this.eventListeners[eventType];\n if (handlers) {\n this.eventListeners[eventType]?.delete(handler);\n }\n }\n\n dispatchEvent<K extends T>(eventType: K, event: EventMap[K]) {\n const handlers = this.eventListeners[eventType];\n if (handlers) {\n // copying ensures that adding more listeners in a handler doesn't\n // affect the current dispatch.\n const copy = [...handlers];\n for (const handler of copy) {\n handler(event);\n }\n }\n }\n}\n","import {\n OpaqueTransportMessage,\n PartialTransportMessage,\n TransportClientId,\n} from './message';\nimport {\n BaseLogger,\n LogFn,\n Logger,\n LoggingLevel,\n createLogProxy,\n} from '../logging/log';\nimport { EventDispatcher, EventHandler, EventMap, EventTypes } from './events';\nimport {\n ProvidedTransportOptions,\n TransportOptions,\n defaultTransportOptions,\n} from './options';\nimport {\n SessionConnected,\n SessionConnecting,\n SessionHandshaking,\n SessionNoConnection,\n SessionState,\n} from './sessionStateMachine';\nimport { Connection } from './connection';\nimport { Session, SessionStateGraph } from './sessionStateMachine/transitions';\nimport { SessionId } from './sessionStateMachine/common';\nimport { Tracer } from '@opentelemetry/api';\nimport { getTracer } from '../tracing';\n\n/**\n * Represents the possible states of a transport.\n * @property {'open'} open - The transport is open and operational (note that this doesn't mean it is actively connected)\n * @property {'closed'} closed - The transport is permanently closed and cannot be reopened.\n */\nexport type TransportStatus = 'open' | 'closed';\n\nexport interface DeleteSessionOptions {\n unhealthy: boolean;\n}\n\nexport type SessionBoundSendFn = (\n msg: PartialTransportMessage,\n) => string | undefined;\n\n/**\n * Transports manage the lifecycle (creation/deletion) of sessions\n *\n * ```plaintext\n * ▲\n * incoming │\n * messages │\n * ▼\n * ┌─────────────┐ 1:N ┌───────────┐ 1:1* ┌────────────┐\n * │ Transport │ ◄─────► │ Session │ ◄─────► │ Connection │\n * └─────────────┘ └───────────┘ └────────────┘\n * ▲ * (may or may not be initialized yet)\n * │\n * ▼\n * ┌───────────┐\n * │ Message │\n * │ Listeners │\n * └───────────┘\n * ```\n * @abstract\n */\nexport abstract class Transport<ConnType extends Connection> {\n /**\n * The status of the transport.\n */\n private status: TransportStatus;\n\n /**\n * The client ID of this transport.\n */\n clientId: TransportClientId;\n\n /**\n * The event dispatcher for handling events of type EventTypes.\n */\n eventDispatcher: EventDispatcher<EventTypes>;\n\n /**\n * The options for this transport.\n */\n protected options: TransportOptions;\n log?: Logger;\n tracer: Tracer;\n\n sessions: Map<TransportClientId, Session<ConnType>>;\n\n /**\n * Creates a new Transport instance.\n * @param codec The codec used to encode and decode messages.\n * @param clientId The client ID of this transport.\n */\n constructor(\n clientId: TransportClientId,\n providedOptions?: ProvidedTransportOptions,\n ) {\n this.options = { ...defaultTransportOptions, ...providedOptions };\n this.eventDispatcher = new EventDispatcher();\n this.clientId = clientId;\n this.status = 'open';\n this.sessions = new Map();\n this.tracer = getTracer();\n }\n\n bindLogger(fn: LogFn | Logger, level?: LoggingLevel) {\n // construct logger from fn\n if (typeof fn === 'function') {\n this.log = createLogProxy(new BaseLogger(fn, level));\n\n return;\n }\n\n // object case, just assign\n this.log = createLogProxy(fn);\n }\n\n /**\n * Called when a message is received by this transport.\n * You generally shouldn't need to override this in downstream transport implementations.\n * @param message The received message.\n */\n protected handleMsg(message: OpaqueTransportMessage) {\n if (this.getStatus() !== 'open') return;\n this.eventDispatcher.dispatchEvent('message', message);\n }\n\n /**\n * Adds a listener to this transport.\n * @param the type of event to listen for\n * @param handler The message handler to add.\n */\n addEventListener<K extends EventTypes, T extends EventHandler<K>>(\n type: K,\n handler: T,\n ): void {\n this.eventDispatcher.addEventListener(type, handler);\n }\n\n /**\n * Removes a listener from this transport.\n * @param the type of event to un-listen on\n * @param handler The message handler to remove.\n */\n removeEventListener<K extends EventTypes, T extends EventHandler<K>>(\n type: K,\n handler: T,\n ): void {\n this.eventDispatcher.removeEventListener(type, handler);\n }\n\n protected protocolError(message: EventMap['protocolError']) {\n this.eventDispatcher.dispatchEvent('protocolError', message);\n }\n\n /**\n * Default close implementation for transports. You should override this in the downstream\n * implementation if you need to do any additional cleanup and call super.close() at the end.\n * Closes the transport. Any messages sent while the transport is closed will be silently discarded.\n */\n close() {\n this.status = 'closed';\n\n const sessions = Array.from(this.sessions.values());\n for (const session of sessions) {\n this.deleteSession(session);\n }\n\n this.eventDispatcher.dispatchEvent('transportStatus', {\n status: this.status,\n });\n\n this.eventDispatcher.removeAllListeners();\n this.log?.info(`manually closed transport`, { clientId: this.clientId });\n }\n\n getStatus(): TransportStatus {\n return this.status;\n }\n\n // state transitions\n protected createSession<S extends Session<ConnType>>(session: S): void {\n const activeSession = this.sessions.get(session.to);\n if (activeSession) {\n const msg = `attempt to create session for ${session.to} but active session (${activeSession.id}) already exists`;\n this.log?.error(msg, {\n ...session.loggingMetadata,\n tags: ['invariant-violation'],\n });\n throw new Error(msg);\n }\n\n this.sessions.set(session.to, session);\n this.eventDispatcher.dispatchEvent('sessionStatus', {\n status: 'created',\n session: session,\n });\n\n this.eventDispatcher.dispatchEvent('sessionTransition', {\n state: session.state,\n session: session,\n } as EventMap['sessionTransition']);\n }\n\n protected updateSession<S extends Session<ConnType>>(session: S): void {\n const activeSession = this.sessions.get(session.to);\n if (!activeSession) {\n const msg = `attempt to transition session for ${session.to} but no active session exists`;\n this.log?.error(msg, {\n ...session.loggingMetadata,\n tags: ['invariant-violation'],\n });\n throw new Error(msg);\n }\n\n if (activeSession.id !== session.id) {\n const msg = `attempt to transition active session for ${session.to} but active session (${activeSession.id}) is different from handle (${session.id})`;\n this.log?.error(msg, {\n ...session.loggingMetadata,\n tags: ['invariant-violation'],\n });\n throw new Error(msg);\n }\n\n this.sessions.set(session.to, session);\n this.eventDispatcher.dispatchEvent('sessionTransition', {\n state: session.state,\n session: session,\n } as EventMap['sessionTransition']);\n }\n\n protected deleteSession(\n session: Session<ConnType>,\n options?: DeleteSessionOptions,\n ) {\n // ensure idempotency esp re: dispatching events\n if (session._isConsumed) return;\n\n const loggingMetadata = session.loggingMetadata;\n if (loggingMetadata.tags && options?.unhealthy) {\n loggingMetadata.tags.push('unhealthy-session');\n }\n\n session.log?.info(`closing session ${session.id}`, loggingMetadata);\n this.eventDispatcher.dispatchEvent('sessionStatus', {\n status: 'closing',\n session: session,\n });\n\n const to = session.to;\n session.close();\n this.sessions.delete(to);\n this.eventDispatcher.dispatchEvent('sessionStatus', {\n status: 'closed',\n session: { id: session.id, to: to },\n });\n }\n\n // common listeners\n protected onSessionGracePeriodElapsed(session: Session<ConnType>) {\n this.log?.warn(\n `session to ${session.to} grace period elapsed, closing`,\n session.loggingMetadata,\n );\n\n this.deleteSession(session);\n }\n\n protected onConnectingFailed(\n session: SessionConnecting<ConnType>,\n ): SessionNoConnection {\n // transition to no connection\n const noConnectionSession =\n SessionStateGraph.transition.ConnectingToNoConnection(session, {\n onSessionGracePeriodElapsed: () => {\n this.onSessionGracePeriodElapsed(noConnectionSession);\n },\n });\n\n this.updateSession(noConnectionSession);\n\n return noConnectionSession;\n }\n\n protected onConnClosed(\n session: SessionHandshaking<ConnType> | SessionConnected<ConnType>,\n ): SessionNoConnection {\n // transition to no connection\n let noConnectionSession: SessionNoConnection;\n if (session.state === SessionState.Handshaking) {\n noConnectionSession =\n SessionStateGraph.transition.HandshakingToNoConnection(session, {\n onSessionGracePeriodElapsed: () => {\n this.onSessionGracePeriodElapsed(noConnectionSession);\n },\n });\n } else {\n noConnectionSession =\n SessionStateGraph.transition.ConnectedToNoConnection(session, {\n onSessionGracePeriodElapsed: () => {\n this.onSessionGracePeriodElapsed(noConnectionSession);\n },\n });\n }\n\n this.updateSession(noConnectionSession);\n\n return noConnectionSession;\n }\n\n /**\n * Gets a send closure scoped to a specific session. Sending using the returned\n * closure after the session has transitioned to a different state will be a noop.\n *\n * Session objects themselves can become stale as they transition between\n * states. As stale sessions cannot be used again (and will throw), holding\n * onto a session object is not recommended.\n */\n getSessionBoundSendFn(\n to: TransportClientId,\n sessionId: SessionId,\n ): SessionBoundSendFn {\n if (this.getStatus() !== 'open') {\n throw new Error('cannot get a bound send function on a closed transport');\n }\n\n return (msg: PartialTransportMessage) => {\n const session = this.sessions.get(to);\n if (!session) {\n throw new Error(\n `session scope for ${sessionId} has ended (close), can't send`,\n );\n }\n\n const sameSession = session.id === sessionId;\n if (!sameSession) {\n throw new Error(\n `session scope for ${sessionId} has ended (transition), can't send`,\n );\n }\n\n return session.send(msg);\n };\n }\n}\n","import { TelemetryInfo } from '../tracing';\nimport { MessageMetadata } from '../logging';\nimport { generateId } from './id';\n\n/**\n * A connection is the actual raw underlying transport connection.\n * It’s responsible for dispatching to/from the actual connection itself\n * This should be instantiated as soon as the client/server has a connection\n * It’s tied to the lifecycle of the underlying transport connection (i.e. if the WS drops, this connection should be deleted)\n */\nexport abstract class Connection {\n id: string;\n telemetry?: TelemetryInfo;\n\n constructor() {\n this.id = `conn-${generateId()}`; // for debugging, no collision safety needed\n }\n\n get loggingMetadata(): MessageMetadata {\n const metadata: MessageMetadata = { connId: this.id };\n\n if (this.telemetry?.span.isRecording()) {\n const spanContext = this.telemetry.span.spanContext();\n metadata.telemetry = {\n traceId: spanContext.traceId,\n spanId: spanContext.spanId,\n };\n }\n\n return metadata;\n }\n\n // can't use event emitter because we need this to work in both node + browser\n private _dataListeners = new Set<(msg: Uint8Array) => void>();\n private _closeListeners = new Set<() => void>();\n private _errorListeners = new Set<(err: Error) => void>();\n\n get dataListeners() {\n return [...this._dataListeners];\n }\n\n get closeListeners() {\n return [...this._closeListeners];\n }\n\n get errorListeners() {\n return [...this._errorListeners];\n }\n\n onData(msg: Uint8Array) {\n for (const cb of this.dataListeners) {\n cb(msg);\n }\n }\n\n onError(err: Error) {\n for (const cb of this.errorListeners) {\n cb(err);\n }\n }\n\n onClose() {\n for (const cb of this.closeListeners) {\n cb();\n }\n\n this.telemetry?.span.end();\n }\n\n /**\n * Handle adding a callback for when a message is received.\n * @param msg The message that was received.\n */\n addDataListener(cb: (msg: Uint8Array) => void) {\n this._dataListeners.add(cb);\n }\n\n removeDataListener(cb: (msg: Uint8Array) => void): void {\n this._dataListeners.delete(cb);\n }\n\n /**\n * Handle adding a callback for when the connection is closed.\n * This should also be called if an error happens and after notifying all the error listeners.\n * @param cb The callback to call when the connection is closed.\n */\n addCloseListener(cb: () => void): void {\n this._closeListeners.add(cb);\n }\n\n removeCloseListener(cb: () => void): void {\n this._closeListeners.delete(cb);\n }\n\n /**\n * Handle adding a callback for when an error is received.\n * This should only be used for this.logging errors, all cleanup\n * should be delegated to addCloseListener.\n *\n * The implementer should take care such that the implemented\n * connection will call both the close and error callbacks\n * on an error.\n *\n * @param cb The callback to call when an error is received.\n */\n addErrorListener(cb: (err: Error) => void): void {\n this._errorListeners.add(cb);\n }\n\n removeErrorListener(cb: (err: Error) => void): void {\n this._errorListeners.delete(cb);\n }\n\n /**\n * Sends a message over the connection.\n * @param msg The message to send.\n * @returns true if the message was sent, false otherwise.\n */\n abstract send(msg: Uint8Array): boolean;\n\n /**\n * Closes the connection.\n */\n abstract close(): void;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAQO,IAAM,0BAA4C;AAAA,EACvD,qBAAqB;AAAA,EACrB,qBAAqB;AAAA,EACrB,0BAA0B;AAAA,EAC1B,qBAAqB;AAAA,EACrB,oBAAoB;AAAA,EACpB,oCAAoC;AAAA,EACpC,OAAO;AACT;AAMA,IAAM,gCAAwD;AAAA,EAC5D,gBAAgB;AAAA,EAChB,aAAa;AAAA,EACb,cAAc;AAAA,EACd,uBAAuB;AAAA,EACvB,yBAAyB;AAC3B;AAEO,IAAM,gCAAwD;AAAA,EACnE,GAAG;AAAA,EACH,GAAG;AACL;AAMO,IAAM,gCAAwD;AAAA,EACnE,GAAG;AACL;;;AC/BA,SAAS,aAAa;AAKf,IAAW,eAAX,kBAAWA,kBAAX;AACL,EAAAA,cAAA,kBAAe;AACf,EAAAA,cAAA,gBAAa;AACb,EAAAA,cAAA,gBAAa;AACb,EAAAA,cAAA,iBAAc;AACd,EAAAA,cAAA,eAAY;AACZ,EAAAA,cAAA,yBAAsB;AANN,SAAAA;AAAA,GAAA;AASX,IAAM,eAAe;AAE5B,IAAe,oBAAf,MAAiC;AAAA;AAAA;AAAA;AAAA;AAAA,EAO/B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAqBA,QAAc;AACZ,SAAK,aAAa;AAAA,EACpB;AAAA,EAEA,cAAc;AACZ,SAAK,cAAc;AA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,IAAgC;AAC/C,SAAK,gBAAgB,IAAI,EAAE;AAAA,EAC7B;AAAA,EAEA,oBAAoB,IAAgC;AAClD,SAAK,gBAAgB,OAAO,EAAE;AAAA,EAChC;AAaF;","names":["SessionState"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
Connection
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-AXZPYUY6.js";
|
|
4
4
|
|
|
5
5
|
// transport/impls/ws/connection.ts
|
|
6
6
|
var WS_HEALTHY_CLOSE_CODE = 1e3;
|
|
@@ -28,18 +28,12 @@ var WebSocketConnection = class extends Connection {
|
|
|
28
28
|
const err = new Error(
|
|
29
29
|
`websocket closed with code and reason: ${code} - ${reason}`
|
|
30
30
|
);
|
|
31
|
-
|
|
32
|
-
cb(err);
|
|
33
|
-
}
|
|
34
|
-
}
|
|
35
|
-
for (const cb of this.closeListeners) {
|
|
36
|
-
cb();
|
|
31
|
+
this.onError(err);
|
|
37
32
|
}
|
|
33
|
+
this.onClose();
|
|
38
34
|
};
|
|
39
35
|
this.ws.onmessage = (msg) => {
|
|
40
|
-
|
|
41
|
-
cb(msg.data);
|
|
42
|
-
}
|
|
36
|
+
this.onData(msg.data);
|
|
43
37
|
};
|
|
44
38
|
}
|
|
45
39
|
send(payload) {
|
|
@@ -57,4 +51,4 @@ var WebSocketConnection = class extends Connection {
|
|
|
57
51
|
export {
|
|
58
52
|
WebSocketConnection
|
|
59
53
|
};
|
|
60
|
-
//# sourceMappingURL=chunk-
|
|
54
|
+
//# sourceMappingURL=chunk-EU2H4J7U.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../transport/impls/ws/connection.ts"],"sourcesContent":["import { Connection } from '../../connection';\nimport { WsLike } from './wslike';\n\ninterface ConnectionInfoExtras extends Record<string, unknown> {\n headers: Record<string, string>;\n}\n\nconst WS_HEALTHY_CLOSE_CODE = 1000;\n\nexport class WebSocketConnection extends Connection {\n ws: WsLike;\n extras?: ConnectionInfoExtras;\n\n get loggingMetadata() {\n const metadata = super.loggingMetadata;\n if (this.extras) {\n metadata.extras = this.extras;\n }\n\n return metadata;\n }\n\n constructor(ws: WsLike, extras?: ConnectionInfoExtras) {\n super();\n this.ws = ws;\n this.extras = extras;\n this.ws.binaryType = 'arraybuffer';\n\n // Websockets are kinda shitty, they emit error events with no\n // information other than it errored, so we have to do some extra\n // work to figure out what happened.\n let didError = false;\n this.ws.onerror = () => {\n didError = true;\n };\n\n this.ws.onclose = ({ code, reason }) => {\n if (didError) {\n const err = new Error(\n `websocket closed with code and reason: ${code} - ${reason}`,\n );\n\n this.onError(err);\n }\n\n this.onClose();\n };\n\n this.ws.onmessage = (msg) => {\n this.onData(msg.data as Uint8Array);\n };\n }\n\n send(payload: Uint8Array) {\n if (this.ws.readyState !== this.ws.OPEN) {\n return false;\n }\n\n this.ws.send(payload);\n\n return true;\n }\n\n close() {\n // we close with 1000 normal even if its not really healthy at the river level\n // if we don't specify this, it defaults to 1005 which\n // some proxies/loggers detect as an error\n this.ws.close(WS_HEALTHY_CLOSE_CODE);\n }\n}\n"],"mappings":";;;;;AAOA,IAAM,wBAAwB;AAEvB,IAAM,sBAAN,cAAkC,WAAW;AAAA,EAClD;AAAA,EACA;AAAA,EAEA,IAAI,kBAAkB;AACpB,UAAM,WAAW,MAAM;AACvB,QAAI,KAAK,QAAQ;AACf,eAAS,SAAS,KAAK;AAAA,IACzB;AAEA,WAAO;AAAA,EACT;AAAA,EAEA,YAAY,IAAY,QAA+B;AACrD,UAAM;AACN,SAAK,KAAK;AACV,SAAK,SAAS;AACd,SAAK,GAAG,aAAa;AAKrB,QAAI,WAAW;AACf,SAAK,GAAG,UAAU,MAAM;AACtB,iBAAW;AAAA,IACb;AAEA,SAAK,GAAG,UAAU,CAAC,EAAE,MAAM,OAAO,MAAM;AACtC,UAAI,UAAU;AACZ,cAAM,MAAM,IAAI;AAAA,UACd,0CAA0C,IAAI,MAAM,MAAM;AAAA,QAC5D;AAEA,aAAK,QAAQ,GAAG;AAAA,MAClB;AAEA,WAAK,QAAQ;AAAA,IACf;AAEA,SAAK,GAAG,YAAY,CAAC,QAAQ;AAC3B,WAAK,OAAO,IAAI,IAAkB;AAAA,IACpC;AAAA,EACF;AAAA,EAEA,KAAK,SAAqB;AACxB,QAAI,KAAK,GAAG,eAAe,KAAK,GAAG,MAAM;AACvC,aAAO;AAAA,IACT;AAEA,SAAK,GAAG,KAAK,OAAO;AAEpB,WAAO;AAAA,EACT;AAAA,EAEA,QAAQ;AAIN,SAAK,GAAG,MAAM,qBAAqB;AAAA,EACrC;AACF;","names":[]}
|