@fluidframework/container-loader 0.52.1 → 0.54.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.
Files changed (75) hide show
  1. package/dist/connectionManager.d.ts +153 -0
  2. package/dist/connectionManager.d.ts.map +1 -0
  3. package/dist/connectionManager.js +664 -0
  4. package/dist/connectionManager.js.map +1 -0
  5. package/dist/connectionStateHandler.d.ts +1 -0
  6. package/dist/connectionStateHandler.d.ts.map +1 -1
  7. package/dist/connectionStateHandler.js +6 -0
  8. package/dist/connectionStateHandler.js.map +1 -1
  9. package/dist/container.d.ts +2 -22
  10. package/dist/container.d.ts.map +1 -1
  11. package/dist/container.js +121 -151
  12. package/dist/container.js.map +1 -1
  13. package/dist/containerContext.d.ts +1 -0
  14. package/dist/containerContext.d.ts.map +1 -1
  15. package/dist/containerContext.js +4 -0
  16. package/dist/containerContext.js.map +1 -1
  17. package/dist/contracts.d.ts +112 -0
  18. package/dist/contracts.d.ts.map +1 -0
  19. package/dist/contracts.js +14 -0
  20. package/dist/contracts.js.map +1 -0
  21. package/dist/deltaManager.d.ts +26 -142
  22. package/dist/deltaManager.d.ts.map +1 -1
  23. package/dist/deltaManager.js +143 -770
  24. package/dist/deltaManager.js.map +1 -1
  25. package/dist/loader.d.ts +14 -4
  26. package/dist/loader.d.ts.map +1 -1
  27. package/dist/loader.js +10 -4
  28. package/dist/loader.js.map +1 -1
  29. package/dist/packageVersion.d.ts +1 -1
  30. package/dist/packageVersion.js +1 -1
  31. package/dist/packageVersion.js.map +1 -1
  32. package/dist/protocolTreeDocumentStorageService.d.ts +2 -2
  33. package/dist/protocolTreeDocumentStorageService.d.ts.map +1 -1
  34. package/lib/connectionManager.d.ts +153 -0
  35. package/lib/connectionManager.d.ts.map +1 -0
  36. package/lib/connectionManager.js +660 -0
  37. package/lib/connectionManager.js.map +1 -0
  38. package/lib/connectionStateHandler.d.ts +1 -0
  39. package/lib/connectionStateHandler.d.ts.map +1 -1
  40. package/lib/connectionStateHandler.js +6 -0
  41. package/lib/connectionStateHandler.js.map +1 -1
  42. package/lib/container.d.ts +2 -22
  43. package/lib/container.d.ts.map +1 -1
  44. package/lib/container.js +122 -152
  45. package/lib/container.js.map +1 -1
  46. package/lib/containerContext.d.ts +1 -0
  47. package/lib/containerContext.d.ts.map +1 -1
  48. package/lib/containerContext.js +4 -0
  49. package/lib/containerContext.js.map +1 -1
  50. package/lib/contracts.d.ts +112 -0
  51. package/lib/contracts.d.ts.map +1 -0
  52. package/lib/contracts.js +11 -0
  53. package/lib/contracts.js.map +1 -0
  54. package/lib/deltaManager.d.ts +26 -142
  55. package/lib/deltaManager.d.ts.map +1 -1
  56. package/lib/deltaManager.js +147 -774
  57. package/lib/deltaManager.js.map +1 -1
  58. package/lib/loader.d.ts +14 -4
  59. package/lib/loader.d.ts.map +1 -1
  60. package/lib/loader.js +11 -5
  61. package/lib/loader.js.map +1 -1
  62. package/lib/packageVersion.d.ts +1 -1
  63. package/lib/packageVersion.js +1 -1
  64. package/lib/packageVersion.js.map +1 -1
  65. package/lib/protocolTreeDocumentStorageService.d.ts +2 -2
  66. package/lib/protocolTreeDocumentStorageService.d.ts.map +1 -1
  67. package/package.json +9 -9
  68. package/src/connectionManager.ts +892 -0
  69. package/src/connectionStateHandler.ts +8 -0
  70. package/src/container.ts +165 -187
  71. package/src/containerContext.ts +4 -0
  72. package/src/contracts.ts +156 -0
  73. package/src/deltaManager.ts +181 -978
  74. package/src/loader.ts +59 -27
  75. package/src/packageVersion.ts +1 -1
@@ -0,0 +1,660 @@
1
+ /*!
2
+ * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
3
+ * Licensed under the MIT License.
4
+ */
5
+ import { assert, performance, TypedEventEmitter } from "@fluidframework/common-utils";
6
+ import { TelemetryLogger, normalizeError, wrapError, } from "@fluidframework/telemetry-utils";
7
+ import { MessageType, ScopeType, } from "@fluidframework/protocol-definitions";
8
+ import { canRetryOnError, createWriteError, createGenericNetworkError, getRetryDelayFromError, logNetworkFailure, waitForConnectedState, DeltaStreamConnectionForbiddenError, GenericNetworkError, } from "@fluidframework/driver-utils";
9
+ import { GenericError, } from "@fluidframework/container-utils";
10
+ import { DeltaQueue } from "./deltaQueue";
11
+ import { ReconnectMode, } from "./contracts";
12
+ const MaxReconnectDelayInMs = 8000;
13
+ const InitialReconnectDelayInMs = 1000;
14
+ const DefaultChunkSize = 16 * 1024;
15
+ const fatalConnectErrorProp = { fatalConnectError: true };
16
+ function getNackReconnectInfo(nackContent) {
17
+ const message = `Nack (${nackContent.type}): ${nackContent.message}`;
18
+ const canRetry = nackContent.code !== 403;
19
+ const retryAfterMs = nackContent.retryAfter !== undefined ? nackContent.retryAfter * 1000 : undefined;
20
+ return createGenericNetworkError(`nack [${nackContent.code}]`, message, canRetry, retryAfterMs, { statusCode: nackContent.code });
21
+ }
22
+ const createReconnectError = (fluidErrorCode, err) => wrapError(err, (errorMessage) => new GenericNetworkError(fluidErrorCode, errorMessage, true /* canRetry */));
23
+ /**
24
+ * Implementation of IDocumentDeltaConnection that does not support submitting
25
+ * or receiving ops. Used in storage-only mode.
26
+ */
27
+ class NoDeltaStream extends TypedEventEmitter {
28
+ constructor() {
29
+ super(...arguments);
30
+ this.clientId = "storage-only client";
31
+ this.claims = {
32
+ scopes: [ScopeType.DocRead],
33
+ };
34
+ this.mode = "read";
35
+ this.existing = true;
36
+ this.maxMessageSize = 0;
37
+ this.version = "";
38
+ this.initialMessages = [];
39
+ this.initialSignals = [];
40
+ this.initialClients = [];
41
+ this.serviceConfiguration = {
42
+ maxMessageSize: 0,
43
+ blockSize: 0,
44
+ summary: undefined,
45
+ };
46
+ this.checkpointSequenceNumber = undefined;
47
+ this._disposed = false;
48
+ }
49
+ submit(messages) {
50
+ this.emit("nack", this.clientId, messages.map((operation) => {
51
+ return {
52
+ operation,
53
+ content: { message: "Cannot submit with storage-only connection", code: 403 },
54
+ };
55
+ }));
56
+ }
57
+ submitSignal(message) {
58
+ this.emit("nack", this.clientId, {
59
+ operation: message,
60
+ content: { message: "Cannot submit signal with storage-only connection", code: 403 },
61
+ });
62
+ }
63
+ get disposed() { return this._disposed; }
64
+ dispose() { this._disposed = true; }
65
+ }
66
+ /**
67
+ * Implementation of IConnectionManager, used by Container class
68
+ * Implements constant connectivity to relay service, by reconnecting in case of loast connection or error.
69
+ * Exposes various controls to influecen this process, including manual reconnects, forced read-only mode, etc.
70
+ */
71
+ export class ConnectionManager {
72
+ constructor(serviceProvider, client, reconnectAllowed, logger, props) {
73
+ this.serviceProvider = serviceProvider;
74
+ this.client = client;
75
+ this.logger = logger;
76
+ this.props = props;
77
+ this.pendingConnection = false;
78
+ /** tracks host requiring read-only mode. */
79
+ this._forceReadonly = false;
80
+ /** True if there is pending (async) reconnection from "read" to "write" */
81
+ this.pendingReconnect = false;
82
+ /** downgrade "write" connection to "read" */
83
+ this.downgradedConnection = false;
84
+ this.clientSequenceNumber = 0;
85
+ this.clientSequenceNumberObserved = 0;
86
+ /** Counts the number of noops sent by the client which may not be acked. */
87
+ this.trailingNoopCount = 0;
88
+ this.connectFirstConnection = true;
89
+ this._connectionVerboseProps = {};
90
+ this._connectionProps = {};
91
+ this.closed = false;
92
+ this.opHandler = (documentId, messagesArg) => {
93
+ const messages = Array.isArray(messagesArg) ? messagesArg : [messagesArg];
94
+ this.props.incomingOpHandler(messages, "opHandler");
95
+ };
96
+ // Always connect in write mode after getting nacked.
97
+ this.nackHandler = (documentId, messages) => {
98
+ const message = messages[0];
99
+ // TODO: we should remove this check when service updates?
100
+ // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions
101
+ if (this._readonlyPermissions) {
102
+ this.props.closeHandler(createWriteError("writeOnReadOnlyDocument"));
103
+ }
104
+ // check message.content for Back-compat with old service.
105
+ const reconnectInfo = message.content !== undefined
106
+ ? getNackReconnectInfo(message.content) :
107
+ createGenericNetworkError("nackReasonUnknown", undefined, true);
108
+ this.reconnectOnError("write", reconnectInfo);
109
+ };
110
+ // Connection mode is always read on disconnect/error unless the system mode was write.
111
+ this.disconnectHandlerInternal = (disconnectReason) => {
112
+ // Note: we might get multiple disconnect calls on same socket, as early disconnect notification
113
+ // ("server_disconnect", ODSP-specific) is mapped to "disconnect"
114
+ this.reconnectOnError(this.defaultReconnectionMode, createReconnectError("dmDocumentDeltaConnectionDisconnected", disconnectReason));
115
+ };
116
+ this.errorHandler = (error) => {
117
+ this.reconnectOnError(this.defaultReconnectionMode, createReconnectError("dmDocumentDeltaConnectionError", error));
118
+ };
119
+ this.clientDetails = this.client.details;
120
+ this.defaultReconnectionMode = this.client.mode;
121
+ this._reconnectMode = reconnectAllowed ? ReconnectMode.Enabled : ReconnectMode.Never;
122
+ // Outbound message queue. The outbound queue is represented as a queue of an array of ops. Ops contained
123
+ // within an array *must* fit within the maxMessageSize and are guaranteed to be ordered sequentially.
124
+ this._outbound = new DeltaQueue((messages) => {
125
+ if (this.connection === undefined) {
126
+ throw new Error("Attempted to submit an outbound message without connection");
127
+ }
128
+ this.connection.submit(messages);
129
+ });
130
+ this._outbound.on("error", (error) => {
131
+ this.props.closeHandler(normalizeError(error));
132
+ });
133
+ }
134
+ get connectionVerboseProps() { return this._connectionVerboseProps; }
135
+ /**
136
+ * The current connection mode, initially read.
137
+ */
138
+ get connectionMode() {
139
+ var _a;
140
+ assert(!this.downgradedConnection || ((_a = this.connection) === null || _a === void 0 ? void 0 : _a.mode) === "write", 0x277 /* "Did we forget to reset downgradedConnection on new connection?" */);
141
+ if (this.connection === undefined) {
142
+ return "read";
143
+ }
144
+ return this.connection.mode;
145
+ }
146
+ get connected() { return this.connection !== undefined; }
147
+ get clientId() { var _a; return (_a = this.connection) === null || _a === void 0 ? void 0 : _a.clientId; }
148
+ /**
149
+ * Automatic reconnecting enabled or disabled.
150
+ * If set to Never, then reconnecting will never be allowed.
151
+ */
152
+ get reconnectMode() {
153
+ return this._reconnectMode;
154
+ }
155
+ get maxMessageSize() {
156
+ var _a, _b, _c;
157
+ return (_c = (_b = (_a = this.connection) === null || _a === void 0 ? void 0 : _a.serviceConfiguration) === null || _b === void 0 ? void 0 : _b.maxMessageSize) !== null && _c !== void 0 ? _c : DefaultChunkSize;
158
+ }
159
+ get version() {
160
+ if (this.connection === undefined) {
161
+ throw new Error("Cannot check version without a connection");
162
+ }
163
+ return this.connection.version;
164
+ }
165
+ get serviceConfiguration() {
166
+ var _a;
167
+ return (_a = this.connection) === null || _a === void 0 ? void 0 : _a.serviceConfiguration;
168
+ }
169
+ get scopes() {
170
+ var _a;
171
+ return (_a = this.connection) === null || _a === void 0 ? void 0 : _a.claims.scopes;
172
+ }
173
+ get outbound() {
174
+ return this._outbound;
175
+ }
176
+ /**
177
+ * Returns set of props that can be logged in telemetry that provide some insights / statistics
178
+ * about current or last connection (if there is no connection at the moment)
179
+ */
180
+ get connectionProps() {
181
+ if (this.connection !== undefined) {
182
+ return this._connectionProps;
183
+ }
184
+ else {
185
+ return Object.assign(Object.assign({}, this._connectionProps), {
186
+ // Report how many ops this client sent in last disconnected session
187
+ sentOps: this.clientSequenceNumber });
188
+ }
189
+ }
190
+ shouldJoinWrite() {
191
+ // We don't have to wait for ack for topmost NoOps. So subtract those.
192
+ return this.clientSequenceNumberObserved < (this.clientSequenceNumber - this.trailingNoopCount);
193
+ }
194
+ /**
195
+ * Tells if container is in read-only mode.
196
+ * Data stores should listen for "readonly" notifications and disallow user
197
+ * making changes to data stores.
198
+ * Readonly state can be because of no storage write permission,
199
+ * or due to host forcing readonly mode for container.
200
+ * It is undefined if we have not yet established websocket connection
201
+ * and do not know if user has write access to a file.
202
+ */
203
+ get readonly() {
204
+ if (this._forceReadonly) {
205
+ return true;
206
+ }
207
+ return this._readonlyPermissions;
208
+ }
209
+ get readOnlyInfo() {
210
+ const storageOnly = this.connection !== undefined && this.connection instanceof NoDeltaStream;
211
+ if (storageOnly || this._forceReadonly || this._readonlyPermissions === true) {
212
+ return {
213
+ readonly: true,
214
+ forced: this._forceReadonly,
215
+ permissions: this._readonlyPermissions,
216
+ storageOnly,
217
+ };
218
+ }
219
+ return { readonly: this._readonlyPermissions };
220
+ }
221
+ static detailsFromConnection(connection) {
222
+ return {
223
+ claims: connection.claims,
224
+ clientId: connection.clientId,
225
+ existing: connection.existing,
226
+ checkpointSequenceNumber: connection.checkpointSequenceNumber,
227
+ get initialClients() { return connection.initialClients; },
228
+ mode: connection.mode,
229
+ serviceConfiguration: connection.serviceConfiguration,
230
+ version: connection.version,
231
+ };
232
+ }
233
+ dispose(error) {
234
+ if (this.closed) {
235
+ return;
236
+ }
237
+ this.closed = true;
238
+ this.pendingConnection = false;
239
+ // Ensure that things like triggerConnect() will short circuit
240
+ this._reconnectMode = ReconnectMode.Never;
241
+ this._outbound.clear();
242
+ const disconnectReason = error !== undefined
243
+ ? `Closing DeltaManager (${error.message})`
244
+ : "Closing DeltaManager";
245
+ // This raises "disconnect" event if we have active connection.
246
+ this.disconnectFromDeltaStream(disconnectReason);
247
+ // Notify everyone we are in read-only state.
248
+ // Useful for data stores in case we hit some critical error,
249
+ // to switch to a mode where user edits are not accepted
250
+ this.set_readonlyPermissions(true);
251
+ }
252
+ /**
253
+ * Enables or disables automatic reconnecting.
254
+ * Will throw an error if reconnectMode set to Never.
255
+ */
256
+ setAutoReconnect(mode) {
257
+ assert(mode !== ReconnectMode.Never && this._reconnectMode !== ReconnectMode.Never, 0x278 /* "API is not supported for non-connecting or closed container" */);
258
+ this._reconnectMode = mode;
259
+ if (mode !== ReconnectMode.Enabled) {
260
+ // immediately disconnect - do not rely on service eventually dropping connection.
261
+ this.disconnectFromDeltaStream("setAutoReconnect");
262
+ }
263
+ }
264
+ /**
265
+ * Sends signal to runtime (and data stores) to be read-only.
266
+ * Hosts may have read only views, indicating to data stores that no edits are allowed.
267
+ * This is independent from this._readonlyPermissions (permissions) and this.connectionMode
268
+ * (server can return "write" mode even when asked for "read")
269
+ * Leveraging same "readonly" event as runtime & data stores should behave the same in such case
270
+ * as in read-only permissions.
271
+ * But this.active can be used by some DDSes to figure out if ops can be sent
272
+ * (for example, read-only view still participates in code proposals / upgrades decisions)
273
+ *
274
+ * Forcing Readonly does not prevent DDS from generating ops. It is up to user code to honour
275
+ * the readonly flag. If ops are generated, they will accumulate locally and not be sent. If
276
+ * there are pending in the outbound queue, it will stop sending until force readonly is
277
+ * cleared.
278
+ *
279
+ * @param readonly - set or clear force readonly.
280
+ */
281
+ forceReadonly(readonly) {
282
+ if (readonly !== this._forceReadonly) {
283
+ this.logger.sendTelemetryEvent({
284
+ eventName: "ForceReadOnly",
285
+ value: readonly,
286
+ });
287
+ }
288
+ const oldValue = this.readonly;
289
+ this._forceReadonly = readonly;
290
+ if (oldValue !== this.readonly) {
291
+ assert(this._reconnectMode !== ReconnectMode.Never, 0x279 /* "API is not supported for non-connecting or closed container" */);
292
+ let reconnect = false;
293
+ if (this.readonly === true) {
294
+ // If we switch to readonly while connected, we should disconnect first
295
+ // See comment in the "readonly" event handler to deltaManager set up by
296
+ // the ContainerRuntime constructor
297
+ if (this.shouldJoinWrite()) {
298
+ // If we have pending changes, then we will never send them - it smells like
299
+ // host logic error.
300
+ this.logger.sendErrorEvent({ eventName: "ForceReadonlyPendingChanged" });
301
+ }
302
+ reconnect = this.disconnectFromDeltaStream("Force readonly");
303
+ }
304
+ this.props.readonlyChangeHandler(this.readonly);
305
+ if (reconnect) {
306
+ // reconnect if we disconnected from before.
307
+ this.triggerConnect("read");
308
+ }
309
+ }
310
+ }
311
+ set_readonlyPermissions(readonly) {
312
+ const oldValue = this.readonly;
313
+ this._readonlyPermissions = readonly;
314
+ if (oldValue !== this.readonly) {
315
+ this.props.readonlyChangeHandler(this.readonly);
316
+ }
317
+ }
318
+ connect(connectionMode) {
319
+ this.connectCore(connectionMode).catch((error) => {
320
+ const normalizedError = normalizeError(error, { props: fatalConnectErrorProp });
321
+ this.props.closeHandler(normalizedError);
322
+ });
323
+ }
324
+ async connectCore(connectionMode) {
325
+ var _a;
326
+ assert(!this.closed, 0x26a /* "not closed" */);
327
+ if (this.connection !== undefined || this.pendingConnection) {
328
+ return;
329
+ }
330
+ let requestedMode = connectionMode !== null && connectionMode !== void 0 ? connectionMode : this.defaultReconnectionMode;
331
+ // if we have any non-acked ops from last connection, reconnect as "write".
332
+ // without that we would connect in view-only mode, which will result in immediate
333
+ // firing of "connected" event from Container and switch of current clientId (as tracked
334
+ // by all DDSes). This will make it impossible to figure out if ops actually made it through,
335
+ // so DDSes will immediately resubmit all pending ops, and some of them will be duplicates, corrupting document
336
+ if (this.shouldJoinWrite()) {
337
+ requestedMode = "write";
338
+ }
339
+ const docService = this.serviceProvider();
340
+ assert(docService !== undefined, 0x2a7 /* "Container is not attached" */);
341
+ let connection;
342
+ if (((_a = docService.policies) === null || _a === void 0 ? void 0 : _a.storageOnly) === true) {
343
+ connection = new NoDeltaStream();
344
+ // to keep setupNewSuccessfulConnection happy
345
+ this.pendingConnection = true;
346
+ this.setupNewSuccessfulConnection(connection, "read");
347
+ assert(!this.pendingConnection, 0x2b3 /* "logic error" */);
348
+ return;
349
+ }
350
+ // this.pendingConnection resets to false as soon as we know the outcome of the connection attempt
351
+ this.pendingConnection = true;
352
+ let delayMs = InitialReconnectDelayInMs;
353
+ let connectRepeatCount = 0;
354
+ const connectStartTime = performance.now();
355
+ let lastError;
356
+ // This loop will keep trying to connect until successful, with a delay between each iteration.
357
+ while (connection === undefined) {
358
+ if (this.closed) {
359
+ throw new Error("Attempting to connect a closed DeltaManager");
360
+ }
361
+ connectRepeatCount++;
362
+ try {
363
+ this.client.mode = requestedMode;
364
+ connection = await docService.connectToDeltaStream(this.client);
365
+ if (connection.disposed) {
366
+ // Nobody observed this connection, so drop it on the floor and retry.
367
+ this.logger.sendTelemetryEvent({ eventName: "ReceivedClosedConnection" });
368
+ connection = undefined;
369
+ }
370
+ }
371
+ catch (origError) {
372
+ if (typeof origError === "object" && origError !== null &&
373
+ (origError === null || origError === void 0 ? void 0 : origError.errorType) === DeltaStreamConnectionForbiddenError.errorType) {
374
+ connection = new NoDeltaStream();
375
+ requestedMode = "read";
376
+ break;
377
+ }
378
+ // Socket.io error when we connect to wrong socket, or hit some multiplexing bug
379
+ if (!canRetryOnError(origError)) {
380
+ const error = normalizeError(origError, { props: fatalConnectErrorProp });
381
+ this.props.closeHandler(error);
382
+ throw error;
383
+ }
384
+ // Log error once - we get too many errors in logs when we are offline,
385
+ // and unfortunately there is no reliable way to detect that.
386
+ if (connectRepeatCount === 1) {
387
+ logNetworkFailure(this.logger, {
388
+ delay: delayMs,
389
+ eventName: "DeltaConnectionFailureToConnect",
390
+ duration: TelemetryLogger.formatTick(performance.now() - connectStartTime),
391
+ }, origError);
392
+ }
393
+ lastError = origError;
394
+ const retryDelayFromError = getRetryDelayFromError(origError);
395
+ delayMs = retryDelayFromError !== null && retryDelayFromError !== void 0 ? retryDelayFromError : Math.min(delayMs * 2, MaxReconnectDelayInMs);
396
+ if (retryDelayFromError !== undefined) {
397
+ this.props.reconnectionDelayHandler(retryDelayFromError, origError);
398
+ }
399
+ await waitForConnectedState(delayMs);
400
+ }
401
+ }
402
+ // If we retried more than once, log an event about how long it took
403
+ if (connectRepeatCount > 1) {
404
+ this.logger.sendTelemetryEvent({
405
+ eventName: "MultipleDeltaConnectionFailures",
406
+ attempts: connectRepeatCount,
407
+ duration: TelemetryLogger.formatTick(performance.now() - connectStartTime),
408
+ }, lastError);
409
+ }
410
+ this.setupNewSuccessfulConnection(connection, requestedMode);
411
+ }
412
+ /**
413
+ * Start the connection. Any error should result in container being close.
414
+ * And report the error if it excape for any reason.
415
+ * @param args - The connection arguments
416
+ */
417
+ triggerConnect(connectionMode) {
418
+ assert(this.connection === undefined, 0x239 /* "called only in disconnected state" */);
419
+ if (this.reconnectMode !== ReconnectMode.Enabled) {
420
+ return;
421
+ }
422
+ this.connect(connectionMode);
423
+ }
424
+ /**
425
+ * Disconnect the current connection.
426
+ * @param reason - Text description of disconnect reason to emit with disconnect event
427
+ */
428
+ disconnectFromDeltaStream(reason) {
429
+ this.pendingReconnect = false;
430
+ this.downgradedConnection = false;
431
+ if (this.connection === undefined) {
432
+ return false;
433
+ }
434
+ assert(!this.pendingConnection, 0x27b /* "reentrancy may result in incorrect behavior" */);
435
+ const connection = this.connection;
436
+ // Avoid any re-entrancy - clear object reference
437
+ this.connection = undefined;
438
+ // Remove listeners first so we don't try to retrigger this flow accidentally through reconnectOnError
439
+ connection.off("op", this.opHandler);
440
+ connection.off("signal", this.props.signalHandler);
441
+ connection.off("nack", this.nackHandler);
442
+ connection.off("disconnect", this.disconnectHandlerInternal);
443
+ connection.off("error", this.errorHandler);
444
+ connection.off("pong", this.props.pongHandler);
445
+ // eslint-disable-next-line @typescript-eslint/no-floating-promises
446
+ this._outbound.pause();
447
+ this._outbound.clear();
448
+ this.props.disconnectHandler(reason);
449
+ connection.dispose();
450
+ this._connectionVerboseProps = {};
451
+ return true;
452
+ }
453
+ /**
454
+ * Once we've successfully gotten a connection, we need to set up state, attach event listeners, and process
455
+ * initial messages.
456
+ * @param connection - The newly established connection
457
+ */
458
+ setupNewSuccessfulConnection(connection, requestedMode) {
459
+ // Old connection should have been cleaned up before establishing a new one
460
+ assert(this.connection === undefined, 0x0e6 /* "old connection exists on new connection setup" */);
461
+ assert(!connection.disposed, 0x28a /* "can't be disposed - Callers need to ensure that!" */);
462
+ if (this.pendingConnection) {
463
+ this.pendingConnection = false;
464
+ }
465
+ else {
466
+ assert(this.closed, 0x27f /* "reentrancy may result in incorrect behavior" */);
467
+ }
468
+ this.connection = connection;
469
+ // Does information in scopes & mode matches?
470
+ // If we asked for "write" and got "read", then file is read-only
471
+ // But if we ask read, server can still give us write.
472
+ const readonly = !connection.claims.scopes.includes(ScopeType.DocWrite);
473
+ // This connection mode validation logic is moving to the driver layer in 0.44. These two asserts can be
474
+ // removed after those packages have released and become ubiquitous.
475
+ assert(requestedMode === "read" || readonly === (this.connectionMode === "read"), 0x0e7 /* "claims/connectionMode mismatch" */);
476
+ assert(!readonly || this.connectionMode === "read", 0x0e8 /* "readonly perf with write connection" */);
477
+ this.set_readonlyPermissions(readonly);
478
+ if (this.closed) {
479
+ // Raise proper events, Log telemetry event and close connection.
480
+ this.disconnectFromDeltaStream("ConnectionManager already closed");
481
+ return;
482
+ }
483
+ this._outbound.resume();
484
+ connection.on("op", this.opHandler);
485
+ connection.on("signal", this.props.signalHandler);
486
+ connection.on("nack", this.nackHandler);
487
+ connection.on("disconnect", this.disconnectHandlerInternal);
488
+ connection.on("error", this.errorHandler);
489
+ connection.on("pong", this.props.pongHandler);
490
+ // Initial messages are always sorted. However, due to early op handler installed by drivers and appending those
491
+ // ops to initialMessages, resulting set is no longer sorted, which would result in client hitting storage to
492
+ // fill in gap. We will recover by cancelling this request once we process remaining ops, but it's a waste that
493
+ // we could avoid
494
+ const initialMessages = connection.initialMessages.sort((a, b) => a.sequenceNumber - b.sequenceNumber);
495
+ // Some storages may provide checkpointSequenceNumber to identify how far client is behind.
496
+ let checkpointSequenceNumber = connection.checkpointSequenceNumber;
497
+ this._connectionVerboseProps = {
498
+ clientId: connection.clientId,
499
+ mode: connection.mode,
500
+ };
501
+ // reset connection props
502
+ this._connectionProps = {};
503
+ if (connection.relayServiceAgent !== undefined) {
504
+ this._connectionVerboseProps.relayServiceAgent = connection.relayServiceAgent;
505
+ this._connectionProps.relayServiceAgent = connection.relayServiceAgent;
506
+ }
507
+ this._connectionProps.socketDocumentId = connection.claims.documentId;
508
+ this._connectionProps.connectionMode = connection.mode;
509
+ let last = -1;
510
+ if (initialMessages.length !== 0) {
511
+ this._connectionVerboseProps.connectionInitialOpsFrom = initialMessages[0].sequenceNumber;
512
+ last = initialMessages[initialMessages.length - 1].sequenceNumber;
513
+ this._connectionVerboseProps.connectionInitialOpsTo = last + 1;
514
+ // Update knowledge of how far we are behind, before raising "connect" event
515
+ // This is duplication of what incomingOpHandler() does, but we have to raise event before we get there,
516
+ // so duplicating update logic here as well.
517
+ if (checkpointSequenceNumber === undefined || checkpointSequenceNumber < last) {
518
+ checkpointSequenceNumber = last;
519
+ }
520
+ }
521
+ this.props.incomingOpHandler(initialMessages, this.connectFirstConnection ? "InitialOps" : "ReconnectOps");
522
+ if (connection.initialSignals !== undefined) {
523
+ for (const signal of connection.initialSignals) {
524
+ this.props.signalHandler(signal);
525
+ }
526
+ }
527
+ const details = ConnectionManager.detailsFromConnection(connection);
528
+ details.checkpointSequenceNumber = checkpointSequenceNumber;
529
+ this.props.connectHandler(details);
530
+ this.connectFirstConnection = false;
531
+ }
532
+ /**
533
+ * Disconnect the current connection and reconnect.
534
+ * @param connection - The connection that wants to reconnect - no-op if it's different from this.connection
535
+ * @param requestedMode - Read or write
536
+ * @param error - Error reconnect information including whether or not to reconnect
537
+ * @returns A promise that resolves when the connection is reestablished or we stop trying
538
+ */
539
+ reconnectOnError(requestedMode, error) {
540
+ // eslint-disable-next-line @typescript-eslint/no-floating-promises
541
+ this.reconnectOnErrorCore(requestedMode, error.message, error);
542
+ }
543
+ /**
544
+ * Disconnect the current connection and reconnect.
545
+ * @param connection - The connection that wants to reconnect - no-op if it's different from this.connection
546
+ * @param requestedMode - Read or write
547
+ * @param error - Error reconnect information including whether or not to reconnect
548
+ * @returns A promise that resolves when the connection is reestablished or we stop trying
549
+ */
550
+ async reconnectOnErrorCore(requestedMode, disconnectMessage, error) {
551
+ // We quite often get protocol errors before / after observing nack/disconnect
552
+ // we do not want to run through same sequence twice.
553
+ // If we're already disconnected/disconnecting it's not appropriate to call this again.
554
+ assert(this.connection !== undefined, 0x0eb /* "Missing connection for reconnect" */);
555
+ this.disconnectFromDeltaStream(disconnectMessage);
556
+ const canRetry = error !== undefined ? canRetryOnError(error) : true;
557
+ // If reconnection is not an option, close the DeltaManager
558
+ if (!canRetry) {
559
+ this.props.closeHandler(normalizeError(error, { props: fatalConnectErrorProp }));
560
+ }
561
+ else if (this.reconnectMode === ReconnectMode.Never) {
562
+ // Do not raise container error if we are closing just because we lost connection.
563
+ // Those errors (like IdleDisconnect) would show up in telemetry dashboards and
564
+ // are very misleading, as first initial reaction - some logic is broken.
565
+ this.props.closeHandler();
566
+ }
567
+ // If closed then we can't reconnect
568
+ if (this.closed || this.reconnectMode !== ReconnectMode.Enabled) {
569
+ return;
570
+ }
571
+ const delayMs = error !== undefined ? getRetryDelayFromError(error) : undefined;
572
+ if (delayMs !== undefined) {
573
+ this.props.reconnectionDelayHandler(delayMs, error);
574
+ await waitForConnectedState(delayMs);
575
+ }
576
+ this.triggerConnect(requestedMode);
577
+ }
578
+ prepareMessageToSend(message) {
579
+ var _a, _b;
580
+ if (this.readonly === true) {
581
+ assert(this.readOnlyInfo.readonly === true, 0x1f0 /* "Unexpected mismatch in readonly" */);
582
+ const error = new GenericError("deltaManagerReadonlySubmit", undefined /* error */, {
583
+ readonly: this.readOnlyInfo.readonly,
584
+ forcedReadonly: this.readOnlyInfo.forced,
585
+ readonlyPermissions: this.readOnlyInfo.permissions,
586
+ storageOnly: this.readOnlyInfo.storageOnly,
587
+ });
588
+ this.props.closeHandler(error);
589
+ return undefined;
590
+ }
591
+ // reset clientSequenceNumber if we are using new clientId.
592
+ // we keep info about old connection as long as possible to be able to account for all non-acked ops
593
+ // that we pick up on next connection.
594
+ assert(!!this.connection, 0x0e4 /* "Lost old connection!" */);
595
+ if (this.lastSubmittedClientId !== ((_a = this.connection) === null || _a === void 0 ? void 0 : _a.clientId)) {
596
+ this.lastSubmittedClientId = (_b = this.connection) === null || _b === void 0 ? void 0 : _b.clientId;
597
+ this.clientSequenceNumber = 0;
598
+ this.clientSequenceNumberObserved = 0;
599
+ }
600
+ if (message.type === MessageType.NoOp) {
601
+ this.trailingNoopCount++;
602
+ }
603
+ else {
604
+ this.trailingNoopCount = 0;
605
+ }
606
+ return Object.assign(Object.assign({}, message), { clientSequenceNumber: ++this.clientSequenceNumber });
607
+ }
608
+ submitSignal(content) {
609
+ if (this.connection !== undefined) {
610
+ this.connection.submitSignal(content);
611
+ }
612
+ else {
613
+ this.logger.sendErrorEvent({ eventName: "submitSignalDisconnected" });
614
+ }
615
+ }
616
+ sendMessages(messages) {
617
+ assert(this.connected, 0x2b4 /* "not connected on sending ops!" */);
618
+ // If connection is "read" or implicit "read" (got leave op for "write" connection),
619
+ // then op can't make it through - we will get a nack if op is sent.
620
+ // We can short-circuit this process.
621
+ // Note that we also want nacks to be rare and be treated as catastrophic failures.
622
+ // Be careful with reentrancy though - disconnected event should not be be raised in the
623
+ // middle of the current workflow, but rather on clean stack!
624
+ if (this.connectionMode === "read" || this.downgradedConnection) {
625
+ if (!this.pendingReconnect) {
626
+ this.pendingReconnect = true;
627
+ Promise.resolve().then(async () => {
628
+ if (this.pendingReconnect) { // still valid?
629
+ await this.reconnectOnErrorCore("write", // connectionMode
630
+ "Switch to write");
631
+ }
632
+ })
633
+ .catch(() => { });
634
+ }
635
+ return;
636
+ }
637
+ assert(!this.pendingReconnect, 0x2b5 /* "logic error" */);
638
+ this._outbound.push(messages);
639
+ }
640
+ beforeProcessingIncomingOp(message) {
641
+ // if we have connection, and message is local, then we better treat is as local!
642
+ assert(this.clientId !== message.clientId || this.lastSubmittedClientId === message.clientId, 0x0ee /* "Not accounting local messages correctly" */);
643
+ if (this.lastSubmittedClientId !== undefined && this.lastSubmittedClientId === message.clientId) {
644
+ const clientSequenceNumber = message.clientSequenceNumber;
645
+ assert(this.clientSequenceNumberObserved < clientSequenceNumber, 0x0ef /* "client seq# not growing" */);
646
+ assert(clientSequenceNumber <= this.clientSequenceNumber, 0x0f0 /* "Incoming local client seq# > generated by this client" */);
647
+ this.clientSequenceNumberObserved = clientSequenceNumber;
648
+ }
649
+ if (message.type === MessageType.ClientLeave) {
650
+ const systemLeaveMessage = message;
651
+ const clientId = JSON.parse(systemLeaveMessage.data);
652
+ if (clientId === this.clientId) {
653
+ // We have been kicked out from quorum
654
+ this.logger.sendPerformanceEvent({ eventName: "ReadConnectionTransition" });
655
+ this.downgradedConnection = true;
656
+ }
657
+ }
658
+ }
659
+ }
660
+ //# sourceMappingURL=connectionManager.js.map