@fluidframework/driver-base 2.0.0-dev.2.3.0.115467 → 2.0.0-dev.4.1.0.148229

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.
@@ -5,31 +5,32 @@
5
5
 
6
6
  import { assert } from "@fluidframework/common-utils";
7
7
  import {
8
- IAnyDriverError,
9
- IDocumentDeltaConnection,
10
- IDocumentDeltaConnectionEvents,
8
+ IAnyDriverError,
9
+ IDocumentDeltaConnection,
10
+ IDocumentDeltaConnectionEvents,
11
11
  } from "@fluidframework/driver-definitions";
12
12
  import { createGenericNetworkError } from "@fluidframework/driver-utils";
13
13
  import {
14
- ConnectionMode,
15
- IClientConfiguration,
16
- IConnect,
17
- IConnected,
18
- IDocumentMessage,
19
- ISequencedDocumentMessage,
20
- ISignalClient,
21
- ISignalMessage,
22
- ITokenClaims,
23
- ScopeType,
14
+ ConnectionMode,
15
+ IClientConfiguration,
16
+ IConnect,
17
+ IConnected,
18
+ IDocumentMessage,
19
+ ISequencedDocumentMessage,
20
+ ISignalClient,
21
+ ISignalMessage,
22
+ ITokenClaims,
23
+ ScopeType,
24
24
  } from "@fluidframework/protocol-definitions";
25
25
  import { IDisposable, ITelemetryLogger } from "@fluidframework/common-definitions";
26
26
  import {
27
- ChildLogger,
28
- extractLogSafeErrorProperties,
29
- getCircularReplacer,
30
- loggerToMonitoringContext,
31
- MonitoringContext,
32
- EventEmitterWithErrorHandling,
27
+ ChildLogger,
28
+ extractLogSafeErrorProperties,
29
+ getCircularReplacer,
30
+ loggerToMonitoringContext,
31
+ MonitoringContext,
32
+ EventEmitterWithErrorHandling,
33
+ normalizeError,
33
34
  } from "@fluidframework/telemetry-utils";
34
35
  import type { Socket } from "socket.io-client";
35
36
  // For now, this package is versioned and released in unison with the specific drivers
@@ -39,576 +40,706 @@ import { pkgVersion as driverVersion } from "./packageVersion";
39
40
  * Represents a connection to a stream of delta updates
40
41
  */
41
42
  export class DocumentDeltaConnection
42
- extends EventEmitterWithErrorHandling<IDocumentDeltaConnectionEvents>
43
- implements IDocumentDeltaConnection, IDisposable {
44
- static readonly eventsToForward = ["nack", "op", "signal", "pong"];
45
-
46
- // WARNING: These are critical events that we can't miss, so registration for them has to be in place at all times!
47
- // Including before handshake is over, and after that (but before DeltaManager had a chance to put its own handlers)
48
- static readonly eventsAlwaysForwarded = ["disconnect", "error"];
49
-
50
- /**
51
- * Last known sequence number to ordering service at the time of connection
52
- * It may lap actual last sequence number (quite a bit, if container is very active).
53
- * But it's best information for client to figure out how far it is behind, at least
54
- * for "read" connections. "write" connections may use own "join" op to similar information,
55
- * that is likely to be more up-to-date.
56
- */
57
- public checkpointSequenceNumber: number | undefined;
58
-
59
- // Listen for ops sent before we receive a response to connect_document
60
- protected readonly queuedMessages: ISequencedDocumentMessage[] = [];
61
- protected readonly queuedSignals: ISignalMessage[] = [];
62
-
63
- /**
64
- * A flag to indicate whether we have our handler attached. If it's attached, we're queueing incoming ops
65
- * to later be retrieved via initialMessages.
66
- */
67
- private earlyOpHandlerAttached: boolean = false;
68
-
69
- private socketConnectionTimeout: ReturnType<typeof setTimeout> | undefined;
70
-
71
- private _details: IConnected | undefined;
72
-
73
- // Listeners only needed while the connection is in progress
74
- private readonly connectionListeners: Map<string, (...args: any[]) => void> = new Map();
75
- // Listeners used throughout the lifetime of the DocumentDeltaConnection
76
- private readonly trackedListeners: Map<string, (...args: any[]) => void> = new Map();
77
-
78
- protected get hasDetails(): boolean {
79
- return !!this._details;
80
- }
81
-
82
- public get disposed() {
83
- assert(this._disposed || this.socket.connected, 0x244 /* "Socket is closed, but connection is not!" */);
84
- return this._disposed;
85
- }
86
-
87
- /**
88
- * Flag to indicate whether the DocumentDeltaConnection is expected to still be capable of sending messages.
89
- * After disconnection, we flip this to prevent any stale messages from being emitted.
90
- */
91
- protected _disposed: boolean = false;
92
- private readonly mc: MonitoringContext;
93
-
94
- /**
95
- * @deprecated Implementors should manage their own logger or monitoring context
96
- */
97
- protected get logger(): ITelemetryLogger {
98
- return this.mc.logger;
99
- }
100
-
101
- public get details(): IConnected {
102
- if (!this._details) {
103
- throw new Error("Internal error: calling method before _details is initialized!");
104
- }
105
- return this._details;
106
- }
107
-
108
- /**
109
- * @param socket - websocket to be used
110
- * @param documentId - ID of the document
111
- * @param logger - for reporting telemetry events
112
- * @param enableLongPollingDowngrades - allow connection to be downgraded to long-polling on websocket failure
113
- */
114
- protected constructor(
115
- protected readonly socket: Socket,
116
- public documentId: string,
117
- logger: ITelemetryLogger,
118
- private readonly enableLongPollingDowngrades: boolean = false,
119
- ) {
120
- super((name, error) => {
121
- logger.sendErrorEvent(
122
- {
123
- eventName: "DeltaConnection:EventException",
124
- name,
125
- },
126
- error);
127
- });
128
-
129
- this.mc = loggerToMonitoringContext(
130
- ChildLogger.create(logger, "DeltaConnection"));
131
-
132
- this.on("newListener", (event, listener) => {
133
- assert(!this.disposed, 0x20a /* "register for event on disposed object" */);
134
-
135
- // Some events are already forwarded - see this.addTrackedListener() calls in initialize().
136
- if (DocumentDeltaConnection.eventsAlwaysForwarded.includes(event)) {
137
- assert(this.trackedListeners.has(event), 0x245 /* "tracked listener" */);
138
- return;
139
- }
140
-
141
- if (!DocumentDeltaConnection.eventsToForward.includes(event)) {
142
- throw new Error(`DocumentDeltaConnection: Registering for unknown event: ${event}`);
143
- }
144
-
145
- // Whenever listener is added, we should subscribe on same event on socket, so these two things
146
- // should be in sync. This currently assumes that nobody unregisters and registers back listeners,
147
- // and that there are no "internal" listeners installed (like "error" case we skip above)
148
- // Better flow might be to always unconditionally register all handlers on successful connection,
149
- // though some logic (naming assert in initialMessages getter) might need to be adjusted (it becomes noop)
150
- assert((this.listeners(event).length !== 0) === this.trackedListeners.has(event), 0x20b /* "mismatch" */);
151
- if (!this.trackedListeners.has(event)) {
152
- this.addTrackedListener(
153
- event,
154
- (...args: any[]) => {
155
- this.emit(event, ...args);
156
- });
157
- }
158
- });
159
- }
160
-
161
- /**
162
- * Get the ID of the client who is sending the message
163
- *
164
- * @returns the client ID
165
- */
166
- public get clientId(): string {
167
- return this.details.clientId;
168
- }
169
-
170
- /**
171
- * Get the mode of the client
172
- *
173
- * @returns the client mode
174
- */
175
- public get mode(): ConnectionMode {
176
- return this.details.mode;
177
- }
178
-
179
- /**
180
- * Get the claims of the client who is sending the message
181
- *
182
- * @returns client claims
183
- */
184
- public get claims(): ITokenClaims {
185
- return this.details.claims;
186
- }
187
-
188
- /**
189
- * Get whether or not this is an existing document
190
- *
191
- * @returns true if the document exists
192
- */
193
- public get existing(): boolean {
194
- return this.details.existing;
195
- }
196
-
197
- /**
198
- * Get the maximum size of a message before chunking is required
199
- *
200
- * @returns the maximum size of a message before chunking is required
201
- */
202
- public get maxMessageSize(): number {
203
- return this.details.serviceConfiguration.maxMessageSize;
204
- }
205
-
206
- /**
207
- * Semver of protocol being used with the service
208
- */
209
- public get version(): string {
210
- return this.details.version;
211
- }
212
-
213
- /**
214
- * Configuration details provided by the service
215
- */
216
- public get serviceConfiguration(): IClientConfiguration {
217
- return this.details.serviceConfiguration;
218
- }
219
-
220
- private checkNotClosed() {
221
- assert(!this.disposed, 0x20c /* "connection disposed" */);
222
- }
223
-
224
- /**
225
- * Get messages sent during the connection
226
- *
227
- * @returns messages sent during the connection
228
- */
229
- public get initialMessages(): ISequencedDocumentMessage[] {
230
- this.checkNotClosed();
231
-
232
- // If we call this when the earlyOpHandler is not attached, then the queuedMessages may not include the
233
- // latest ops. This could possibly indicate that initialMessages was called twice.
234
- assert(this.earlyOpHandlerAttached, 0x08e /* "Potentially missed initial messages" */);
235
- // We will lose ops and perf will tank as we need to go to storage to become current!
236
- assert(this.listeners("op").length !== 0, 0x08f /* "No op handler is setup!" */);
237
-
238
- this.removeEarlyOpHandler();
239
-
240
- if (this.queuedMessages.length > 0) {
241
- // Some messages were queued.
242
- // add them to the list of initialMessages to be processed
243
- this.details.initialMessages.push(...this.queuedMessages);
244
- this.details.initialMessages.sort((a, b) => a.sequenceNumber - b.sequenceNumber);
245
- this.queuedMessages.length = 0;
246
- }
247
- return this.details.initialMessages;
248
- }
249
-
250
- /**
251
- * Get signals sent during the connection
252
- *
253
- * @returns signals sent during the connection
254
- */
255
- public get initialSignals(): ISignalMessage[] {
256
- this.checkNotClosed();
257
- assert(this.listeners("signal").length !== 0, 0x090 /* "No signal handler is setup!" */);
258
-
259
- this.removeEarlySignalHandler();
260
-
261
- if (this.queuedSignals.length > 0) {
262
- // Some signals were queued.
263
- // add them to the list of initialSignals to be processed
264
- this.details.initialSignals.push(...this.queuedSignals);
265
- this.queuedSignals.length = 0;
266
- }
267
- return this.details.initialSignals;
268
- }
269
-
270
- /**
271
- * Get initial client list
272
- *
273
- * @returns initial client list sent during the connection
274
- */
275
- public get initialClients(): ISignalClient[] {
276
- this.checkNotClosed();
277
- return this.details.initialClients;
278
- }
279
-
280
- protected emitMessages(type: string, messages: IDocumentMessage[][]) {
281
- // Although the implementation here disconnects the socket and does not reuse it, other subclasses
282
- // (e.g. OdspDocumentDeltaConnection) may reuse the socket. In these cases, we need to avoid emitting
283
- // on the still-live socket.
284
- if (!this.disposed) {
285
- this.socket.emit(type, this.clientId, messages);
286
- }
287
- }
288
-
289
- protected submitCore(type: string, messages: IDocumentMessage[]) {
290
- this.emitMessages(type, [messages]);
291
- }
292
-
293
- /**
294
- * Submits a new delta operation to the server
295
- *
296
- * @param message - delta operation to submit
297
- */
298
- public submit(messages: IDocumentMessage[]): void {
299
- this.checkNotClosed();
300
- this.submitCore("submitOp", messages);
301
- }
302
-
303
- /**
304
- * Submits a new signal to the server
305
- *
306
- * @param message - signal to submit
307
- */
308
- public submitSignal(message: IDocumentMessage): void {
309
- this.checkNotClosed();
310
- this.submitCore("submitSignal", [message]);
311
- }
312
-
313
- /**
314
- * Disconnect from the websocket and close the websocket too.
315
- */
316
- protected closeSocket(error: IAnyDriverError) {
317
- this.disconnect(error);
318
- }
319
-
320
- /**
321
- * Disconnect from the websocket, and permanently disable this DocumentDeltaConnection and close the socket.
322
- * However the OdspDocumentDeltaConnection differ in dispose as in there we don't close the socket. There is no
323
- * multiplexing here, so we need to close the socket here.
324
- */
325
- public dispose() {
326
- this.logger.sendTelemetryEvent({
327
- eventName: "ClientClosingDeltaConnection",
328
- driverVersion,
329
- details: JSON.stringify({ disposed: this._disposed, socketConnected: this.socket.connected }),
330
- });
331
- this.disconnect(createGenericNetworkError(
332
- // pre-0.58 error message: clientClosingConnection
333
- "Client closing delta connection", { canRetry: true }, { driverVersion }),
334
- );
335
- }
336
-
337
- protected disconnect(err: IAnyDriverError) {
338
- // Can't check this.disposed here, as we get here on socket closure,
339
- // so _disposed & socket.connected might be not in sync while processing
340
- // "dispose" event.
341
- if (this._disposed) {
342
- return;
343
- }
344
-
345
- // We set the disposed flag as a part of the contract for overriding the disconnect method. This is used by
346
- // DocumentDeltaConnection to determine if emitting messages (ops) on the socket is allowed, which is
347
- // important since OdspDocumentDeltaConnection reuses the socket rather than truly disconnecting it. Note that
348
- // OdspDocumentDeltaConnection may still send disconnect_document which is allowed; this is only intended
349
- // to prevent normal messages from being emitted.
350
- this._disposed = true;
351
-
352
- // Let user of connection object know about disconnect. This has to happen in between setting _disposed and
353
- // removing all listeners!
354
- this.emit("disconnect", err);
355
- this.logger.sendTelemetryEvent({
356
- eventName: "AfterDisconnectEvent",
357
- driverVersion,
358
- details: JSON.stringify({
359
- socketConnected: this.socket.connected,
360
- disconnectListenerCount: this.listenerCount("disconnect"),
361
- }),
362
- });
363
- // user of DeltaConnection should have processed "disconnect" event and removed all listeners. Not clear
364
- // if we want to enforce that, as some users (like LocalDocumentService) do not unregister any handlers
365
- // assert(this.listenerCount("disconnect") === 0, "'disconnect` events should be processed synchronously");
366
-
367
- this.removeTrackedListeners();
368
- this.disconnectCore();
369
- }
370
-
371
- /**
372
- * Disconnect from the websocket.
373
- * @param reason - reason for disconnect
374
- */
375
- protected disconnectCore() {
376
- this.socket.disconnect();
377
- }
378
-
379
- protected async initialize(connectMessage: IConnect, timeout: number) {
380
- this.socket.on("op", this.earlyOpHandler);
381
- this.socket.on("signal", this.earlySignalHandler);
382
- this.earlyOpHandlerAttached = true;
383
-
384
- // Socket.io's reconnect_attempt event is unreliable, so we track connect_error count instead.
385
- let internalSocketConnectionFailureCount: number = 0;
386
- const isInternalSocketReconnectionEnabled = (): boolean => this.socket.io.reconnection();
387
- const getMaxInternalSocketReconnectionAttempts = (): number => isInternalSocketReconnectionEnabled()
388
- ? this.socket.io.reconnectionAttempts()
389
- : 0;
390
- const getMaxAllowedInternalSocketConnectionFailures = (): number =>
391
- getMaxInternalSocketReconnectionAttempts() + 1;
392
-
393
- this._details = await new Promise<IConnected>((resolve, reject) => {
394
- const failAndCloseSocket = (err: IAnyDriverError) => {
395
- this.closeSocket(err);
396
- reject(err);
397
- };
398
-
399
- const failConnection = (err: IAnyDriverError) => {
400
- this.disconnect(err);
401
- reject(err);
402
- };
403
- // Listen for connection issues
404
- this.addConnectionListener("connect_error", (error) => {
405
- internalSocketConnectionFailureCount++;
406
- let isWebSocketTransportError = false;
407
- try {
408
- const description = error?.description;
409
- if (description && typeof description === "object") {
410
- if (error.type === "TransportError") {
411
- isWebSocketTransportError = true;
412
- }
413
- // That's a WebSocket. Clear it as we can't log it.
414
- description.target = undefined;
415
- }
416
- } catch (_e) { }
417
-
418
- // Handle socket transport downgrading when not offline.
419
- if (
420
- isWebSocketTransportError &&
421
- this.enableLongPollingDowngrades &&
422
- this.socket.io.opts.transports?.[0] !== "polling") {
423
- // Downgrade transports to polling upgrade mechanism.
424
- this.socket.io.opts.transports = ["polling", "websocket"];
425
- // Don't alter reconnection behavior if already enabled.
426
- if (!isInternalSocketReconnectionEnabled()) {
427
- // Allow single reconnection attempt using polling upgrade mechanism.
428
- this.socket.io.reconnection(true);
429
- this.socket.io.reconnectionAttempts(1);
430
- }
431
- }
432
-
433
- // Allow built-in socket.io reconnection handling.
434
- if (isInternalSocketReconnectionEnabled() &&
435
- internalSocketConnectionFailureCount < getMaxAllowedInternalSocketConnectionFailures()) {
436
- // Reconnection is enabled and maximum reconnect attempts have not been reached.
437
- return;
438
- }
439
-
440
- failAndCloseSocket(this.createErrorObject("connect_error", error));
441
- });
442
-
443
- // Listen for timeouts
444
- this.addConnectionListener("connect_timeout", () => {
445
- failAndCloseSocket(this.createErrorObject("connect_timeout"));
446
- });
447
-
448
- this.addConnectionListener("connect_document_success", (response: IConnected) => {
449
- // If we sent a nonce and the server supports nonces, check that the nonces match
450
- if (connectMessage.nonce !== undefined &&
451
- response.nonce !== undefined &&
452
- response.nonce !== connectMessage.nonce) {
453
- return;
454
- }
455
-
456
- const requestedMode = connectMessage.mode;
457
- const actualMode = response.mode;
458
- const writingPermitted = response.claims.scopes.includes(ScopeType.DocWrite);
459
-
460
- if (writingPermitted) {
461
- // The only time we expect a mismatch in requested/actual is if we lack write permissions
462
- // In this case we will get "read", even if we requested "write"
463
- if (actualMode !== requestedMode) {
464
- failConnection(this.createErrorObject(
465
- "connect_document_success",
466
- "Connected in a different mode than was requested",
467
- false,
468
- ));
469
- return;
470
- }
471
- } else {
472
- if (actualMode === "write") {
473
- failConnection(this.createErrorObject(
474
- "connect_document_success",
475
- "Connected in write mode without write permissions",
476
- false,
477
- ));
478
- return;
479
- }
480
- }
481
-
482
- this.checkpointSequenceNumber = response.checkpointSequenceNumber;
483
-
484
- this.removeConnectionListeners();
485
- resolve(response);
486
- });
487
-
488
- // Socket can be disconnected while waiting for Fluid protocol messages
489
- // (connect_document_error / connect_document_success), as well as before DeltaManager
490
- // had a chance to register its handlers.
491
- this.addTrackedListener("disconnect", (reason) => {
492
- const err = this.createErrorObject("disconnect", reason);
493
- failAndCloseSocket(err);
494
- });
495
-
496
- this.addTrackedListener("error", ((error) => {
497
- // This includes "Invalid namespace" error, which we consider critical (reconnecting will not help)
498
- const err = this.createErrorObject("error", error, error !== "Invalid namespace");
499
- // Disconnect socket - required if happened before initial handshake
500
- failAndCloseSocket(err);
501
- }));
502
-
503
- this.addConnectionListener("connect_document_error", ((error) => {
504
- // If we sent a nonce and the server supports nonces, check that the nonces match
505
- if (connectMessage.nonce !== undefined &&
506
- error.nonce !== undefined &&
507
- error.nonce !== connectMessage.nonce) {
508
- return;
509
- }
510
-
511
- // This is not an socket.io error - it's Fluid protocol error.
512
- // In this case fail connection and indicate that we were unable to create connection
513
- failConnection(this.createErrorObject("connect_document_error", error));
514
- }));
515
-
516
- this.socket.emit("connect_document", connectMessage);
517
-
518
- // Give extra 2 seconds for handshake on top of socket connection timeout
519
- this.socketConnectionTimeout = setTimeout(() => {
520
- failConnection(this.createErrorObject("orderingServiceHandshakeTimeout"));
521
- }, timeout + 2000);
522
- });
523
-
524
- assert(!this.disposed, 0x246 /* "checking consistency of socket & _disposed flags" */);
525
- }
526
-
527
- protected earlyOpHandler = (documentId: string, msgs: ISequencedDocumentMessage[]) => {
528
- this.queuedMessages.push(...msgs);
529
- };
530
-
531
- protected earlySignalHandler = (msg: ISignalMessage) => {
532
- this.queuedSignals.push(msg);
533
- };
534
-
535
- private removeEarlyOpHandler() {
536
- this.socket.removeListener("op", this.earlyOpHandler);
537
- this.earlyOpHandlerAttached = false;
538
- }
539
-
540
- private removeEarlySignalHandler() {
541
- this.socket.removeListener("signal", this.earlySignalHandler);
542
- }
543
-
544
- private addConnectionListener(event: string, listener: (...args: any[]) => void) {
545
- assert(!DocumentDeltaConnection.eventsAlwaysForwarded.includes(event),
546
- 0x247 /* "Use addTrackedListener instead" */);
547
- assert(!DocumentDeltaConnection.eventsToForward.includes(event),
548
- 0x248 /* "should not subscribe to forwarded events" */);
549
- this.socket.on(event, listener);
550
- assert(!this.connectionListeners.has(event), 0x20d /* "double connection listener" */);
551
- this.connectionListeners.set(event, listener);
552
- }
553
-
554
- protected addTrackedListener(event: string, listener: (...args: any[]) => void) {
555
- this.socket.on(event, listener);
556
- assert(!this.trackedListeners.has(event), 0x20e /* "double tracked listener" */);
557
- this.trackedListeners.set(event, listener);
558
- }
559
-
560
- private removeTrackedListeners() {
561
- for (const [event, listener] of this.trackedListeners.entries()) {
562
- this.socket.off(event, listener);
563
- }
564
- // removeTrackedListeners removes all listeners, including connection listeners
565
- this.removeConnectionListeners();
566
-
567
- this.removeEarlyOpHandler();
568
- this.removeEarlySignalHandler();
569
-
570
- this.trackedListeners.clear();
571
- }
572
-
573
- private removeConnectionListeners() {
574
- if (this.socketConnectionTimeout !== undefined) {
575
- clearTimeout(this.socketConnectionTimeout);
576
- }
577
-
578
- for (const [event, listener] of this.connectionListeners.entries()) {
579
- this.socket.off(event, listener);
580
- }
581
- this.connectionListeners.clear();
582
- }
583
-
584
- /**
585
- * Error raising for socket.io issues
586
- */
587
- protected createErrorObject(handler: string, error?: any, canRetry = true): IAnyDriverError {
588
- // Note: we suspect the incoming error object is either:
589
- // - a string: log it in the message (if not a string, it may contain PII but will print as [object Object])
590
- // - an Error object thrown by socket.io engine. Be careful with not recording PII!
591
- let message: string;
592
- if (error?.type === "TransportError") {
593
- // JSON.stringify drops Error.message
594
- const messagePrefix = (error?.message !== undefined)
595
- ? `${error.message}: `
596
- : "";
597
-
598
- // Websocket errors reported by engine.io-client.
599
- // They are Error objects with description containing WS error and description = "TransportError"
600
- // Please see https://github.com/socketio/engine.io-client/blob/7245b80/lib/transport.ts#L44,
601
- message = `${messagePrefix}${JSON.stringify(error, getCircularReplacer())}`;
602
- } else {
603
- message = extractLogSafeErrorProperties(error, true).message;
604
- }
605
-
606
- const errorObj = createGenericNetworkError(
607
- `socket.io (${handler}): ${message}`,
608
- { canRetry },
609
- { driverVersion },
610
- );
611
-
612
- return errorObj;
613
- }
43
+ extends EventEmitterWithErrorHandling<IDocumentDeltaConnectionEvents>
44
+ implements IDocumentDeltaConnection, IDisposable
45
+ {
46
+ static readonly eventsToForward = ["nack", "op", "signal", "pong"];
47
+
48
+ // WARNING: These are critical events that we can't miss, so registration for them has to be in place at all times!
49
+ // Including before handshake is over, and after that (but before DeltaManager had a chance to put its own handlers)
50
+ static readonly eventsAlwaysForwarded = ["disconnect", "error"];
51
+
52
+ /**
53
+ * Last known sequence number to ordering service at the time of connection
54
+ * It may lap actual last sequence number (quite a bit, if container is very active).
55
+ * But it's best information for client to figure out how far it is behind, at least
56
+ * for "read" connections. "write" connections may use own "join" op to similar information,
57
+ * that is likely to be more up-to-date.
58
+ */
59
+ public checkpointSequenceNumber: number | undefined;
60
+
61
+ // Listen for ops sent before we receive a response to connect_document
62
+ protected readonly queuedMessages: ISequencedDocumentMessage[] = [];
63
+ protected readonly queuedSignals: ISignalMessage[] = [];
64
+
65
+ /**
66
+ * A flag to indicate whether we have our handler attached. If it's attached, we're queueing incoming ops
67
+ * to later be retrieved via initialMessages.
68
+ */
69
+ private earlyOpHandlerAttached: boolean = false;
70
+
71
+ private socketConnectionTimeout: ReturnType<typeof setTimeout> | undefined;
72
+
73
+ private _details: IConnected | undefined;
74
+
75
+ // Listeners only needed while the connection is in progress
76
+ private readonly connectionListeners: Map<string, (...args: any[]) => void> = new Map();
77
+ // Listeners used throughout the lifetime of the DocumentDeltaConnection
78
+ private readonly trackedListeners: Map<string, (...args: any[]) => void> = new Map();
79
+
80
+ protected get hasDetails(): boolean {
81
+ return !!this._details;
82
+ }
83
+
84
+ public get disposed() {
85
+ // Increase the stack trace limit temporarily, so as to debug better in case it occurs.
86
+ // We are seeing this in telemetry and we are unable to figure out why it is happening, so this should help.
87
+ const originalStackTraceLimit = (Error as any).stackTraceLimit;
88
+ try {
89
+ (Error as any).stackTraceLimit = 50;
90
+ assert(
91
+ this._disposed || this.socket.connected,
92
+ 0x244 /* "Socket is closed, but connection is not!" */,
93
+ );
94
+ } catch (error) {
95
+ const normalizedError = this.addPropsToError(error);
96
+ throw normalizedError;
97
+ } finally {
98
+ (Error as any).stackTraceLimit = originalStackTraceLimit;
99
+ }
100
+ return this._disposed;
101
+ }
102
+
103
+ /**
104
+ * Flag to indicate whether the DocumentDeltaConnection is expected to still be capable of sending messages.
105
+ * After disconnection, we flip this to prevent any stale messages from being emitted.
106
+ */
107
+ protected _disposed: boolean = false;
108
+ private readonly mc: MonitoringContext;
109
+
110
+ /**
111
+ * @deprecated Implementors should manage their own logger or monitoring context
112
+ */
113
+ protected get logger(): ITelemetryLogger {
114
+ return this.mc.logger;
115
+ }
116
+
117
+ public get details(): IConnected {
118
+ if (!this._details) {
119
+ throw new Error("Internal error: calling method before _details is initialized!");
120
+ }
121
+ return this._details;
122
+ }
123
+
124
+ /**
125
+ * @param socket - websocket to be used
126
+ * @param documentId - ID of the document
127
+ * @param logger - for reporting telemetry events
128
+ * @param enableLongPollingDowngrades - allow connection to be downgraded to long-polling on websocket failure
129
+ */
130
+ protected constructor(
131
+ protected readonly socket: Socket,
132
+ public documentId: string,
133
+ logger: ITelemetryLogger,
134
+ private readonly enableLongPollingDowngrades: boolean = false,
135
+ protected readonly connectionId?: string,
136
+ ) {
137
+ super((name, error) => {
138
+ logger.sendErrorEvent(
139
+ {
140
+ eventName: "DeltaConnection:EventException",
141
+ name,
142
+ },
143
+ error,
144
+ );
145
+ });
146
+
147
+ this.mc = loggerToMonitoringContext(ChildLogger.create(logger, "DeltaConnection"));
148
+
149
+ this.on("newListener", (event, listener) => {
150
+ assert(!this.disposed, 0x20a /* "register for event on disposed object" */);
151
+
152
+ // Some events are already forwarded - see this.addTrackedListener() calls in initialize().
153
+ if (DocumentDeltaConnection.eventsAlwaysForwarded.includes(event)) {
154
+ assert(this.trackedListeners.has(event), 0x245 /* "tracked listener" */);
155
+ return;
156
+ }
157
+
158
+ if (!DocumentDeltaConnection.eventsToForward.includes(event)) {
159
+ throw new Error(`DocumentDeltaConnection: Registering for unknown event: ${event}`);
160
+ }
161
+
162
+ // Whenever listener is added, we should subscribe on same event on socket, so these two things
163
+ // should be in sync. This currently assumes that nobody unregisters and registers back listeners,
164
+ // and that there are no "internal" listeners installed (like "error" case we skip above)
165
+ // Better flow might be to always unconditionally register all handlers on successful connection,
166
+ // though some logic (naming assert in initialMessages getter) might need to be adjusted (it becomes noop)
167
+ assert(
168
+ (this.listeners(event).length !== 0) === this.trackedListeners.has(event),
169
+ 0x20b /* "mismatch" */,
170
+ );
171
+ if (!this.trackedListeners.has(event)) {
172
+ this.addTrackedListener(event, (...args: any[]) => {
173
+ this.emit(event, ...args);
174
+ });
175
+ }
176
+ });
177
+ }
178
+
179
+ /**
180
+ * Get the ID of the client who is sending the message
181
+ *
182
+ * @returns the client ID
183
+ */
184
+ public get clientId(): string {
185
+ return this.details.clientId;
186
+ }
187
+
188
+ /**
189
+ * Get the mode of the client
190
+ *
191
+ * @returns the client mode
192
+ */
193
+ public get mode(): ConnectionMode {
194
+ return this.details.mode;
195
+ }
196
+
197
+ /**
198
+ * Get the claims of the client who is sending the message
199
+ *
200
+ * @returns client claims
201
+ */
202
+ public get claims(): ITokenClaims {
203
+ return this.details.claims;
204
+ }
205
+
206
+ /**
207
+ * Get whether or not this is an existing document
208
+ *
209
+ * @returns true if the document exists
210
+ */
211
+ public get existing(): boolean {
212
+ return this.details.existing;
213
+ }
214
+
215
+ /**
216
+ * Get the maximum size of a message before chunking is required
217
+ *
218
+ * @returns the maximum size of a message before chunking is required
219
+ */
220
+ public get maxMessageSize(): number {
221
+ return this.details.serviceConfiguration.maxMessageSize;
222
+ }
223
+
224
+ /**
225
+ * Semver of protocol being used with the service
226
+ */
227
+ public get version(): string {
228
+ return this.details.version;
229
+ }
230
+
231
+ /**
232
+ * Configuration details provided by the service
233
+ */
234
+ public get serviceConfiguration(): IClientConfiguration {
235
+ return this.details.serviceConfiguration;
236
+ }
237
+
238
+ private checkNotClosed() {
239
+ // Increase the stack trace limit temporarily, so as to debug better in case it occurs.
240
+ // We are seeing this in telemetry and we are unable to figure out why it is happening, so this should help.
241
+ const originalStackTraceLimit = (Error as any).stackTraceLimit;
242
+ try {
243
+ (Error as any).stackTraceLimit = 50;
244
+ assert(!this.disposed, 0x20c /* "connection disposed" */);
245
+ } catch (error) {
246
+ const normalizedError = this.addPropsToError(error);
247
+ throw normalizedError;
248
+ } finally {
249
+ (Error as any).stackTraceLimit = originalStackTraceLimit;
250
+ }
251
+ }
252
+
253
+ /**
254
+ * Get messages sent during the connection
255
+ *
256
+ * @returns messages sent during the connection
257
+ */
258
+ public get initialMessages(): ISequencedDocumentMessage[] {
259
+ this.checkNotClosed();
260
+
261
+ // If we call this when the earlyOpHandler is not attached, then the queuedMessages may not include the
262
+ // latest ops. This could possibly indicate that initialMessages was called twice.
263
+ assert(this.earlyOpHandlerAttached, 0x08e /* "Potentially missed initial messages" */);
264
+ // We will lose ops and perf will tank as we need to go to storage to become current!
265
+ assert(this.listeners("op").length !== 0, 0x08f /* "No op handler is setup!" */);
266
+
267
+ this.removeEarlyOpHandler();
268
+
269
+ if (this.queuedMessages.length > 0) {
270
+ // Some messages were queued.
271
+ // add them to the list of initialMessages to be processed
272
+ this.details.initialMessages.push(...this.queuedMessages);
273
+ this.details.initialMessages.sort((a, b) => a.sequenceNumber - b.sequenceNumber);
274
+ this.queuedMessages.length = 0;
275
+ }
276
+ return this.details.initialMessages;
277
+ }
278
+
279
+ /**
280
+ * Get signals sent during the connection
281
+ *
282
+ * @returns signals sent during the connection
283
+ */
284
+ public get initialSignals(): ISignalMessage[] {
285
+ this.checkNotClosed();
286
+ assert(this.listeners("signal").length !== 0, 0x090 /* "No signal handler is setup!" */);
287
+
288
+ this.removeEarlySignalHandler();
289
+
290
+ if (this.queuedSignals.length > 0) {
291
+ // Some signals were queued.
292
+ // add them to the list of initialSignals to be processed
293
+ this.details.initialSignals.push(...this.queuedSignals);
294
+ this.queuedSignals.length = 0;
295
+ }
296
+ return this.details.initialSignals;
297
+ }
298
+
299
+ /**
300
+ * Get initial client list
301
+ *
302
+ * @returns initial client list sent during the connection
303
+ */
304
+ public get initialClients(): ISignalClient[] {
305
+ this.checkNotClosed();
306
+ return this.details.initialClients;
307
+ }
308
+
309
+ protected emitMessages(type: string, messages: IDocumentMessage[][]) {
310
+ // Although the implementation here disconnects the socket and does not reuse it, other subclasses
311
+ // (e.g. OdspDocumentDeltaConnection) may reuse the socket. In these cases, we need to avoid emitting
312
+ // on the still-live socket.
313
+ if (!this.disposed) {
314
+ this.socket.emit(type, this.clientId, messages);
315
+ }
316
+ }
317
+
318
+ protected submitCore(type: string, messages: IDocumentMessage[]) {
319
+ this.emitMessages(type, [messages]);
320
+ }
321
+
322
+ /**
323
+ * Submits a new delta operation to the server
324
+ *
325
+ * @param message - delta operation to submit
326
+ */
327
+ public submit(messages: IDocumentMessage[]): void {
328
+ this.checkNotClosed();
329
+ this.submitCore("submitOp", messages);
330
+ }
331
+
332
+ /**
333
+ * Submits a new signal to the server
334
+ *
335
+ * @param message - signal to submit
336
+ */
337
+ public submitSignal(message: IDocumentMessage): void {
338
+ this.checkNotClosed();
339
+ this.submitCore("submitSignal", [message]);
340
+ }
341
+
342
+ /**
343
+ * Disconnect from the websocket and close the websocket too.
344
+ */
345
+ private closeSocket(error: IAnyDriverError) {
346
+ if (this._disposed) {
347
+ // This would be rare situation due to complexity around socket emitting events.
348
+ this.logger.sendTelemetryEvent(
349
+ {
350
+ eventName: "SocketCloseOnDisposedConnection",
351
+ driverVersion,
352
+ details: JSON.stringify({
353
+ ...this.getConnectionDetailsProps(),
354
+ trackedListenerCount: this.trackedListeners.size,
355
+ }),
356
+ },
357
+ error,
358
+ );
359
+ return;
360
+ }
361
+ this.closeSocketCore(error);
362
+ }
363
+
364
+ protected closeSocketCore(error: IAnyDriverError) {
365
+ this.disconnect(error);
366
+ }
367
+
368
+ /**
369
+ * Disconnect from the websocket, and permanently disable this DocumentDeltaConnection and close the socket.
370
+ * However the OdspDocumentDeltaConnection differ in dispose as in there we don't close the socket. There is no
371
+ * multiplexing here, so we need to close the socket here.
372
+ */
373
+ public dispose() {
374
+ this.logger.sendTelemetryEvent({
375
+ eventName: "ClientClosingDeltaConnection",
376
+ driverVersion,
377
+ details: JSON.stringify({
378
+ ...this.getConnectionDetailsProps(),
379
+ }),
380
+ });
381
+ this.disconnect(
382
+ createGenericNetworkError(
383
+ // pre-0.58 error message: clientClosingConnection
384
+ "Client closing delta connection",
385
+ { canRetry: true },
386
+ { driverVersion },
387
+ ),
388
+ );
389
+ }
390
+
391
+ protected disconnect(err: IAnyDriverError) {
392
+ // Can't check this.disposed here, as we get here on socket closure,
393
+ // so _disposed & socket.connected might be not in sync while processing
394
+ // "dispose" event.
395
+ if (this._disposed) {
396
+ return;
397
+ }
398
+
399
+ // We set the disposed flag as a part of the contract for overriding the disconnect method. This is used by
400
+ // DocumentDeltaConnection to determine if emitting messages (ops) on the socket is allowed, which is
401
+ // important since OdspDocumentDeltaConnection reuses the socket rather than truly disconnecting it. Note that
402
+ // OdspDocumentDeltaConnection may still send disconnect_document which is allowed; this is only intended
403
+ // to prevent normal messages from being emitted.
404
+ this._disposed = true;
405
+
406
+ // Remove all listeners listening on the socket. These are listeners on socket and not on this connection
407
+ // object. Anyway since we have disposed this connection object, nobody should listen to event on socket
408
+ // anymore.
409
+ this.removeTrackedListeners();
410
+
411
+ // Clear the connection/socket before letting the deltaManager/connection manager know about the disconnect.
412
+ this.disconnectCore();
413
+
414
+ // Let user of connection object know about disconnect.
415
+ this.emit("disconnect", err);
416
+ this.logger.sendTelemetryEvent({
417
+ eventName: "AfterDisconnectEvent",
418
+ driverVersion,
419
+ details: JSON.stringify({
420
+ ...this.getConnectionDetailsProps(),
421
+ disconnectListenerCount: this.listenerCount("disconnect"),
422
+ }),
423
+ });
424
+ }
425
+
426
+ /**
427
+ * Disconnect from the websocket.
428
+ * @param reason - reason for disconnect
429
+ */
430
+ protected disconnectCore() {
431
+ this.socket.disconnect();
432
+ }
433
+
434
+ protected async initialize(connectMessage: IConnect, timeout: number) {
435
+ this.socket.on("op", this.earlyOpHandler);
436
+ this.socket.on("signal", this.earlySignalHandler);
437
+ this.earlyOpHandlerAttached = true;
438
+
439
+ // Socket.io's reconnect_attempt event is unreliable, so we track connect_error count instead.
440
+ let internalSocketConnectionFailureCount: number = 0;
441
+ const isInternalSocketReconnectionEnabled = (): boolean => this.socket.io.reconnection();
442
+ const getMaxInternalSocketReconnectionAttempts = (): number =>
443
+ isInternalSocketReconnectionEnabled() ? this.socket.io.reconnectionAttempts() : 0;
444
+ const getMaxAllowedInternalSocketConnectionFailures = (): number =>
445
+ getMaxInternalSocketReconnectionAttempts() + 1;
446
+
447
+ this._details = await new Promise<IConnected>((resolve, reject) => {
448
+ const failAndCloseSocket = (err: IAnyDriverError) => {
449
+ try {
450
+ this.closeSocket(err);
451
+ } catch (failError) {
452
+ const normalizedError = this.addPropsToError(failError);
453
+ this.logger.sendErrorEvent({ eventName: "CloseSocketError" }, normalizedError);
454
+ }
455
+ reject(err);
456
+ };
457
+
458
+ const failConnection = (err: IAnyDriverError) => {
459
+ try {
460
+ this.disconnect(err);
461
+ } catch (failError) {
462
+ const normalizedError = this.addPropsToError(failError);
463
+ this.logger.sendErrorEvent(
464
+ { eventName: "FailConnectionError" },
465
+ normalizedError,
466
+ );
467
+ }
468
+ reject(err);
469
+ };
470
+
471
+ // Immediately set the connection timeout.
472
+ // Give extra 2 seconds for handshake on top of socket connection timeout.
473
+ this.socketConnectionTimeout = setTimeout(() => {
474
+ failConnection(this.createErrorObject("orderingServiceHandshakeTimeout"));
475
+ }, timeout + 2000);
476
+
477
+ // Listen for connection issues
478
+ this.addConnectionListener("connect_error", (error) => {
479
+ internalSocketConnectionFailureCount++;
480
+ let isWebSocketTransportError = false;
481
+ try {
482
+ const description = error?.description;
483
+ const context = error?.context;
484
+
485
+ if (context && typeof context === "object") {
486
+ const statusText = context.statusText?.code;
487
+
488
+ // Self-Signed Certificate ErrorCode Found in error.context
489
+ if (statusText === "DEPTH_ZERO_SELF_SIGNED_CERT") {
490
+ failAndCloseSocket(
491
+ this.createErrorObject("connect_error", error, false),
492
+ );
493
+ return;
494
+ }
495
+ } else if (description && typeof description === "object") {
496
+ const errorCode = description.error?.code;
497
+
498
+ // Self-Signed Certificate ErrorCode Found in error.description
499
+ if (errorCode === "DEPTH_ZERO_SELF_SIGNED_CERT") {
500
+ failAndCloseSocket(
501
+ this.createErrorObject("connect_error", error, false),
502
+ );
503
+ return;
504
+ }
505
+
506
+ if (error.type === "TransportError") {
507
+ isWebSocketTransportError = true;
508
+ }
509
+
510
+ // That's a WebSocket. Clear it as we can't log it.
511
+ description.target = undefined;
512
+ }
513
+ } catch (_e) {}
514
+
515
+ // Handle socket transport downgrading when not offline.
516
+ if (
517
+ isWebSocketTransportError &&
518
+ this.enableLongPollingDowngrades &&
519
+ this.socket.io.opts.transports?.[0] !== "polling"
520
+ ) {
521
+ // Downgrade transports to polling upgrade mechanism.
522
+ this.socket.io.opts.transports = ["polling", "websocket"];
523
+ // Don't alter reconnection behavior if already enabled.
524
+ if (!isInternalSocketReconnectionEnabled()) {
525
+ // Allow single reconnection attempt using polling upgrade mechanism.
526
+ this.socket.io.reconnection(true);
527
+ this.socket.io.reconnectionAttempts(1);
528
+ }
529
+ }
530
+
531
+ // Allow built-in socket.io reconnection handling.
532
+ if (
533
+ isInternalSocketReconnectionEnabled() &&
534
+ internalSocketConnectionFailureCount <
535
+ getMaxAllowedInternalSocketConnectionFailures()
536
+ ) {
537
+ // Reconnection is enabled and maximum reconnect attempts have not been reached.
538
+ return;
539
+ }
540
+
541
+ failAndCloseSocket(this.createErrorObject("connect_error", error));
542
+ });
543
+
544
+ // Listen for timeouts
545
+ this.addConnectionListener("connect_timeout", () => {
546
+ failAndCloseSocket(this.createErrorObject("connect_timeout"));
547
+ });
548
+
549
+ this.addConnectionListener("connect_document_success", (response: IConnected) => {
550
+ // If we sent a nonce and the server supports nonces, check that the nonces match
551
+ if (
552
+ connectMessage.nonce !== undefined &&
553
+ response.nonce !== undefined &&
554
+ response.nonce !== connectMessage.nonce
555
+ ) {
556
+ return;
557
+ }
558
+
559
+ const requestedMode = connectMessage.mode;
560
+ const actualMode = response.mode;
561
+ const writingPermitted = response.claims.scopes.includes(ScopeType.DocWrite);
562
+
563
+ if (writingPermitted) {
564
+ // The only time we expect a mismatch in requested/actual is if we lack write permissions
565
+ // In this case we will get "read", even if we requested "write"
566
+ if (actualMode !== requestedMode) {
567
+ failConnection(
568
+ this.createErrorObject(
569
+ "connect_document_success",
570
+ "Connected in a different mode than was requested",
571
+ false,
572
+ ),
573
+ );
574
+ return;
575
+ }
576
+ } else {
577
+ if (actualMode === "write") {
578
+ failConnection(
579
+ this.createErrorObject(
580
+ "connect_document_success",
581
+ "Connected in write mode without write permissions",
582
+ false,
583
+ ),
584
+ );
585
+ return;
586
+ }
587
+ }
588
+
589
+ this.checkpointSequenceNumber = response.checkpointSequenceNumber;
590
+
591
+ this.removeConnectionListeners();
592
+ resolve(response);
593
+ });
594
+
595
+ // Socket can be disconnected while waiting for Fluid protocol messages
596
+ // (connect_document_error / connect_document_success), as well as before DeltaManager
597
+ // had a chance to register its handlers.
598
+ this.addTrackedListener("disconnect", (reason) => {
599
+ const err = this.createErrorObject("disconnect", reason);
600
+ failAndCloseSocket(err);
601
+ });
602
+
603
+ this.addTrackedListener("error", (error) => {
604
+ // This includes "Invalid namespace" error, which we consider critical (reconnecting will not help)
605
+ const err = this.createErrorObject("error", error, error !== "Invalid namespace");
606
+ // Disconnect socket - required if happened before initial handshake
607
+ failAndCloseSocket(err);
608
+ });
609
+
610
+ this.addConnectionListener("connect_document_error", (error) => {
611
+ // If we sent a nonce and the server supports nonces, check that the nonces match
612
+ if (
613
+ connectMessage.nonce !== undefined &&
614
+ error.nonce !== undefined &&
615
+ error.nonce !== connectMessage.nonce
616
+ ) {
617
+ return;
618
+ }
619
+
620
+ // This is not an socket.io error - it's Fluid protocol error.
621
+ // In this case fail connection and indicate that we were unable to create connection
622
+ failConnection(this.createErrorObject("connect_document_error", error));
623
+ });
624
+
625
+ this.socket.emit("connect_document", connectMessage);
626
+ });
627
+
628
+ assert(!this.disposed, 0x246 /* "checking consistency of socket & _disposed flags" */);
629
+ }
630
+
631
+ private addPropsToError(errorToBeNormalized: unknown) {
632
+ const normalizedError = normalizeError(errorToBeNormalized, {
633
+ props: {
634
+ details: JSON.stringify({
635
+ ...this.getConnectionDetailsProps(),
636
+ }),
637
+ },
638
+ });
639
+ return normalizedError;
640
+ }
641
+
642
+ private getConnectionDetailsProps() {
643
+ return {
644
+ disposed: this._disposed,
645
+ socketConnected: this.socket?.connected,
646
+ clientId: this._details?.clientId,
647
+ connectionId: this.connectionId,
648
+ };
649
+ }
650
+
651
+ protected earlyOpHandler = (documentId: string, msgs: ISequencedDocumentMessage[]) => {
652
+ this.queuedMessages.push(...msgs);
653
+ };
654
+
655
+ protected earlySignalHandler = (msg: ISignalMessage) => {
656
+ this.queuedSignals.push(msg);
657
+ };
658
+
659
+ private removeEarlyOpHandler() {
660
+ this.socket.removeListener("op", this.earlyOpHandler);
661
+ this.earlyOpHandlerAttached = false;
662
+ }
663
+
664
+ private removeEarlySignalHandler() {
665
+ this.socket.removeListener("signal", this.earlySignalHandler);
666
+ }
667
+
668
+ private addConnectionListener(event: string, listener: (...args: any[]) => void) {
669
+ assert(
670
+ !DocumentDeltaConnection.eventsAlwaysForwarded.includes(event),
671
+ 0x247 /* "Use addTrackedListener instead" */,
672
+ );
673
+ assert(
674
+ !DocumentDeltaConnection.eventsToForward.includes(event),
675
+ 0x248 /* "should not subscribe to forwarded events" */,
676
+ );
677
+ this.socket.on(event, listener);
678
+ assert(!this.connectionListeners.has(event), 0x20d /* "double connection listener" */);
679
+ this.connectionListeners.set(event, listener);
680
+ }
681
+
682
+ protected addTrackedListener(event: string, listener: (...args: any[]) => void) {
683
+ this.socket.on(event, listener);
684
+ assert(!this.trackedListeners.has(event), 0x20e /* "double tracked listener" */);
685
+ this.trackedListeners.set(event, listener);
686
+ }
687
+
688
+ private removeTrackedListeners() {
689
+ for (const [event, listener] of this.trackedListeners.entries()) {
690
+ this.socket.off(event, listener);
691
+ }
692
+ // removeTrackedListeners removes all listeners, including connection listeners
693
+ this.removeConnectionListeners();
694
+
695
+ this.removeEarlyOpHandler();
696
+ this.removeEarlySignalHandler();
697
+
698
+ this.trackedListeners.clear();
699
+ }
700
+
701
+ private removeConnectionListeners() {
702
+ if (this.socketConnectionTimeout !== undefined) {
703
+ clearTimeout(this.socketConnectionTimeout);
704
+ }
705
+
706
+ for (const [event, listener] of this.connectionListeners.entries()) {
707
+ this.socket.off(event, listener);
708
+ }
709
+ this.connectionListeners.clear();
710
+ }
711
+
712
+ /**
713
+ * Error raising for socket.io issues
714
+ */
715
+ protected createErrorObject(handler: string, error?: any, canRetry = true): IAnyDriverError {
716
+ // Note: we suspect the incoming error object is either:
717
+ // - a string: log it in the message (if not a string, it may contain PII but will print as [object Object])
718
+ // - an Error object thrown by socket.io engine. Be careful with not recording PII!
719
+ let message: string;
720
+ if (error?.type === "TransportError") {
721
+ // JSON.stringify drops Error.message
722
+ const messagePrefix = error?.message !== undefined ? `${error.message}: ` : "";
723
+
724
+ // Websocket errors reported by engine.io-client.
725
+ // They are Error objects with description containing WS error and description = "TransportError"
726
+ // Please see https://github.com/socketio/engine.io-client/blob/7245b80/lib/transport.ts#L44,
727
+ message = `${messagePrefix}${JSON.stringify(error, getCircularReplacer())}`;
728
+ } else {
729
+ message = extractLogSafeErrorProperties(error, true).message;
730
+ }
731
+
732
+ const errorObj = createGenericNetworkError(
733
+ `socket.io (${handler}): ${message}`,
734
+ { canRetry },
735
+ {
736
+ driverVersion,
737
+ details: JSON.stringify({
738
+ ...this.getConnectionDetailsProps(),
739
+ }),
740
+ },
741
+ );
742
+
743
+ return errorObj;
744
+ }
614
745
  }