-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathcommon.ts
More file actions
344 lines (291 loc) Β· 9.05 KB
/
common.ts
File metadata and controls
344 lines (291 loc) Β· 9.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
import { Logger, MessageMetadata } from '../../logging';
import { TelemetryInfo } from '../../tracing';
import {
EncodedTransportMessage,
OpaqueTransportMessage,
OpaqueTransportMessageSchema,
PartialTransportMessage,
ProtocolVersion,
TransportClientId,
} from '../message';
import { Value } from '@sinclair/typebox/value';
import { Codec } from '../../codec';
import { generateId } from '../id';
export const enum SessionState {
NoConnection = 'NoConnection',
BackingOff = 'BackingOff',
Connecting = 'Connecting',
Handshaking = 'Handshaking',
Connected = 'Connected',
WaitingForHandshake = 'WaitingForHandshake',
}
export const ERR_CONSUMED = `session state has been consumed and is no longer valid`;
abstract class StateMachineState {
abstract readonly state: SessionState;
/*
* Whether this state has been consumed
* and we've moved on to another state
*/
_isConsumed: boolean;
// called when we're transitioning to another state
// note that this is internal and should not be called directly
// by consumers, the proxy will call this when the state is consumed
// and we're transitioning to another state
abstract _handleStateExit(): void;
// called when we exit the state machine entirely
// note that this is internal and should not be called directly
// by consumers, the proxy will call this when .close is closed
abstract _handleClose(): void;
/**
* Cleanup this state machine state and mark it as consumed.
* After calling close, it is an error to access any properties on the state.
* You should never need to call this as a consumer.
*
* If you're looking to close the session from the client,
* use `.hardDisconnect` on the client transport.
*/
close(): void {
this._handleClose();
}
constructor() {
this._isConsumed = false;
// proxy helps us prevent access to properties after the state has been consumed
// e.g. if we hold a reference to a state and try to access it after it's been consumed
// we intercept the access and throw an error to help catch bugs
return new Proxy(this, {
get(target, prop) {
// always allow access to _isConsumed, id, and state
if (prop === '_isConsumed' || prop === 'id' || prop === 'state') {
return Reflect.get(target, prop);
}
// modify _handleStateExit
if (prop === '_handleStateExit') {
return () => {
target._isConsumed = true;
target._handleStateExit();
};
}
// modify _handleClose
if (prop === '_handleClose') {
return () => {
// target is the non-proxied object, we need to set _isConsumed again
target._isConsumed = true;
target._handleStateExit();
target._handleClose();
};
}
if (target._isConsumed) {
throw new Error(
`${ERR_CONSUMED}: getting ${prop.toString()} on consumed state`,
);
}
return Reflect.get(target, prop);
},
set(target, prop, value) {
if (target._isConsumed) {
throw new Error(
`${ERR_CONSUMED}: setting ${prop.toString()} on consumed state`,
);
}
return Reflect.set(target, prop, value);
},
});
}
}
export interface SessionOptions {
/**
* Frequency at which to send heartbeat acknowledgements
*/
heartbeatIntervalMs: number;
/**
* Number of elapsed heartbeats without a response message before we consider
* the connection dead.
*/
heartbeatsUntilDead: number;
/**
* Max duration that a session can be without a connection before we consider
* it dead. This deadline is carried between states and is used to determine
* when to consider the session a lost cause and delete it entirely.
* Generally, this should be strictly greater than the sum of
* {@link connectionTimeoutMs} and {@link handshakeTimeoutMs}.
*/
sessionDisconnectGraceMs: number;
/**
* Connection timeout in milliseconds
*/
connectionTimeoutMs: number;
/**
* Handshake timeout in milliseconds
*/
handshakeTimeoutMs: number;
/**
* Whether to enable transparent session reconnects
*/
enableTransparentSessionReconnects: boolean;
/**
* The codec to use for encoding/decoding messages over the wire
*/
codec: Codec;
}
// all session states have a from and options
export interface CommonSessionProps {
from: TransportClientId;
options: SessionOptions;
log: Logger | undefined;
}
export abstract class CommonSession extends StateMachineState {
readonly from: TransportClientId;
readonly options: SessionOptions;
log?: Logger;
abstract get loggingMetadata(): MessageMetadata;
constructor({ from, options, log }: CommonSessionProps) {
super();
this.from = from;
this.options = options;
this.log = log;
}
parseMsg(msg: Uint8Array): OpaqueTransportMessage | null {
const parsedMsg = this.options.codec.fromBuffer(msg);
if (parsedMsg === null) {
this.log?.error(
`received malformed msg: ${Buffer.from(msg).toString('base64')}`,
this.loggingMetadata,
);
return null;
}
if (!Value.Check(OpaqueTransportMessageSchema, parsedMsg)) {
this.log?.error(`received invalid msg: ${JSON.stringify(parsedMsg)}`, {
...this.loggingMetadata,
validationErrors: [
...Value.Errors(OpaqueTransportMessageSchema, parsedMsg),
],
});
return null;
}
return parsedMsg;
}
}
export type InheritedProperties = Pick<
IdentifiedSession,
'id' | 'from' | 'to' | 'seq' | 'ack' | 'sendBuffer' | 'telemetry' | 'options'
>;
export type SessionId = string;
// all sessions where we know the other side's client id
export interface IdentifiedSessionProps extends CommonSessionProps {
id: SessionId;
to: TransportClientId;
seq: number;
ack: number;
sendBuffer: Array<EncodedTransportMessage>;
telemetry: TelemetryInfo;
protocolVersion: ProtocolVersion;
}
export abstract class IdentifiedSession extends CommonSession {
readonly id: SessionId;
readonly telemetry: TelemetryInfo;
readonly to: TransportClientId;
readonly protocolVersion: ProtocolVersion;
/**
* Index of the message we will send next (excluding handshake)
*/
seq: number;
/**
* Number of unique messages we've received this session (excluding handshake)
*/
ack: number;
sendBuffer: Array<EncodedTransportMessage>;
constructor(props: IdentifiedSessionProps) {
const { id, to, seq, ack, sendBuffer, telemetry, log, protocolVersion } =
props;
super(props);
this.id = id;
this.to = to;
this.seq = seq;
this.ack = ack;
this.sendBuffer = sendBuffer;
this.telemetry = telemetry;
this.log = log;
this.protocolVersion = protocolVersion;
}
get loggingMetadata(): MessageMetadata {
const metadata: MessageMetadata = {
clientId: this.from,
connectedTo: this.to,
sessionId: this.id,
};
if (this.telemetry.span.isRecording()) {
const spanContext = this.telemetry.span.spanContext();
metadata.telemetry = {
traceId: spanContext.traceId,
spanId: spanContext.spanId,
};
}
return metadata;
}
encodeMsg<Payload>(
partialMsg: PartialTransportMessage<Payload>,
): EncodedTransportMessage {
const msg = {
...partialMsg,
id: generateId(),
to: this.to,
from: this.from,
seq: this.seq,
ack: this.ack,
};
const encodedMsg = {
id: msg.id,
seq: msg.seq,
data: this.options.codec.toBuffer(msg),
};
this.seq++;
return encodedMsg;
}
nextSeq(): number {
return this.sendBuffer.length > 0 ? this.sendBuffer[0].seq : this.seq;
}
send(msg: PartialTransportMessage): string {
const constructedMsg = this.encodeMsg(msg);
this.sendBuffer.push(constructedMsg);
return constructedMsg.id;
}
_handleStateExit(): void {
// noop
}
_handleClose(): void {
// zero out the buffer
this.sendBuffer.length = 0;
this.telemetry.span.end();
}
}
export interface IdentifiedSessionWithGracePeriodListeners {
onSessionGracePeriodElapsed: () => void;
}
export interface IdentifiedSessionWithGracePeriodProps
extends IdentifiedSessionProps {
graceExpiryTime: number;
listeners: IdentifiedSessionWithGracePeriodListeners;
}
export abstract class IdentifiedSessionWithGracePeriod extends IdentifiedSession {
graceExpiryTime: number;
protected gracePeriodTimeout?: ReturnType<typeof setTimeout>;
listeners: IdentifiedSessionWithGracePeriodListeners;
constructor(props: IdentifiedSessionWithGracePeriodProps) {
super(props);
this.listeners = props.listeners;
this.graceExpiryTime = props.graceExpiryTime;
this.gracePeriodTimeout = setTimeout(() => {
this.listeners.onSessionGracePeriodElapsed();
}, this.graceExpiryTime - Date.now());
}
_handleStateExit(): void {
super._handleStateExit();
if (this.gracePeriodTimeout) {
clearTimeout(this.gracePeriodTimeout);
this.gracePeriodTimeout = undefined;
}
}
_handleClose(): void {
super._handleClose();
}
}