@fluidframework/container-loader 2.0.0-internal.3.0.5 → 2.0.0-internal.3.1.1

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 (148) hide show
  1. package/.eslintrc.js +18 -21
  2. package/.mocharc.js +2 -2
  3. package/README.md +45 -43
  4. package/api-extractor.json +2 -2
  5. package/closeAndGetPendingLocalState.md +51 -0
  6. package/dist/audience.d.ts.map +1 -1
  7. package/dist/audience.js.map +1 -1
  8. package/dist/catchUpMonitor.d.ts.map +1 -1
  9. package/dist/catchUpMonitor.js.map +1 -1
  10. package/dist/collabWindowTracker.d.ts.map +1 -1
  11. package/dist/collabWindowTracker.js.map +1 -1
  12. package/dist/connectionManager.d.ts +2 -2
  13. package/dist/connectionManager.d.ts.map +1 -1
  14. package/dist/connectionManager.js +51 -24
  15. package/dist/connectionManager.js.map +1 -1
  16. package/dist/connectionState.d.ts.map +1 -1
  17. package/dist/connectionState.js.map +1 -1
  18. package/dist/connectionStateHandler.d.ts.map +1 -1
  19. package/dist/connectionStateHandler.js +35 -16
  20. package/dist/connectionStateHandler.js.map +1 -1
  21. package/dist/container.d.ts +1 -10
  22. package/dist/container.d.ts.map +1 -1
  23. package/dist/container.js +89 -44
  24. package/dist/container.js.map +1 -1
  25. package/dist/containerContext.d.ts.map +1 -1
  26. package/dist/containerContext.js +6 -2
  27. package/dist/containerContext.js.map +1 -1
  28. package/dist/containerStorageAdapter.d.ts.map +1 -1
  29. package/dist/containerStorageAdapter.js +2 -4
  30. package/dist/containerStorageAdapter.js.map +1 -1
  31. package/dist/contracts.d.ts.map +1 -1
  32. package/dist/contracts.js.map +1 -1
  33. package/dist/deltaManager.d.ts +3 -3
  34. package/dist/deltaManager.d.ts.map +1 -1
  35. package/dist/deltaManager.js +56 -27
  36. package/dist/deltaManager.js.map +1 -1
  37. package/dist/deltaManagerProxy.d.ts.map +1 -1
  38. package/dist/deltaManagerProxy.js.map +1 -1
  39. package/dist/deltaQueue.d.ts.map +1 -1
  40. package/dist/deltaQueue.js +4 -2
  41. package/dist/deltaQueue.js.map +1 -1
  42. package/dist/index.d.ts +1 -1
  43. package/dist/index.d.ts.map +1 -1
  44. package/dist/index.js.map +1 -1
  45. package/dist/loader.d.ts +3 -3
  46. package/dist/loader.d.ts.map +1 -1
  47. package/dist/loader.js +18 -15
  48. package/dist/loader.js.map +1 -1
  49. package/dist/packageVersion.d.ts +1 -1
  50. package/dist/packageVersion.js +1 -1
  51. package/dist/packageVersion.js.map +1 -1
  52. package/dist/protocol.d.ts.map +1 -1
  53. package/dist/protocol.js +2 -1
  54. package/dist/protocol.js.map +1 -1
  55. package/dist/protocolTreeDocumentStorageService.d.ts.map +1 -1
  56. package/dist/protocolTreeDocumentStorageService.js.map +1 -1
  57. package/dist/quorum.d.ts.map +1 -1
  58. package/dist/quorum.js.map +1 -1
  59. package/dist/retriableDocumentStorageService.d.ts.map +1 -1
  60. package/dist/retriableDocumentStorageService.js +6 -2
  61. package/dist/retriableDocumentStorageService.js.map +1 -1
  62. package/dist/utils.d.ts.map +1 -1
  63. package/dist/utils.js +6 -4
  64. package/dist/utils.js.map +1 -1
  65. package/lib/audience.d.ts.map +1 -1
  66. package/lib/audience.js.map +1 -1
  67. package/lib/catchUpMonitor.d.ts.map +1 -1
  68. package/lib/catchUpMonitor.js.map +1 -1
  69. package/lib/collabWindowTracker.d.ts.map +1 -1
  70. package/lib/collabWindowTracker.js.map +1 -1
  71. package/lib/connectionManager.d.ts +2 -2
  72. package/lib/connectionManager.d.ts.map +1 -1
  73. package/lib/connectionManager.js +53 -26
  74. package/lib/connectionManager.js.map +1 -1
  75. package/lib/connectionState.d.ts.map +1 -1
  76. package/lib/connectionState.js.map +1 -1
  77. package/lib/connectionStateHandler.d.ts.map +1 -1
  78. package/lib/connectionStateHandler.js +35 -16
  79. package/lib/connectionStateHandler.js.map +1 -1
  80. package/lib/container.d.ts +1 -10
  81. package/lib/container.d.ts.map +1 -1
  82. package/lib/container.js +93 -48
  83. package/lib/container.js.map +1 -1
  84. package/lib/containerContext.d.ts.map +1 -1
  85. package/lib/containerContext.js +6 -2
  86. package/lib/containerContext.js.map +1 -1
  87. package/lib/containerStorageAdapter.d.ts.map +1 -1
  88. package/lib/containerStorageAdapter.js +2 -4
  89. package/lib/containerStorageAdapter.js.map +1 -1
  90. package/lib/contracts.d.ts.map +1 -1
  91. package/lib/contracts.js.map +1 -1
  92. package/lib/deltaManager.d.ts +3 -3
  93. package/lib/deltaManager.d.ts.map +1 -1
  94. package/lib/deltaManager.js +58 -29
  95. package/lib/deltaManager.js.map +1 -1
  96. package/lib/deltaManagerProxy.d.ts.map +1 -1
  97. package/lib/deltaManagerProxy.js.map +1 -1
  98. package/lib/deltaQueue.d.ts.map +1 -1
  99. package/lib/deltaQueue.js +4 -2
  100. package/lib/deltaQueue.js.map +1 -1
  101. package/lib/index.d.ts +1 -1
  102. package/lib/index.d.ts.map +1 -1
  103. package/lib/index.js.map +1 -1
  104. package/lib/loader.d.ts +3 -3
  105. package/lib/loader.d.ts.map +1 -1
  106. package/lib/loader.js +18 -15
  107. package/lib/loader.js.map +1 -1
  108. package/lib/packageVersion.d.ts +1 -1
  109. package/lib/packageVersion.js +1 -1
  110. package/lib/packageVersion.js.map +1 -1
  111. package/lib/protocol.d.ts.map +1 -1
  112. package/lib/protocol.js +2 -1
  113. package/lib/protocol.js.map +1 -1
  114. package/lib/protocolTreeDocumentStorageService.d.ts.map +1 -1
  115. package/lib/protocolTreeDocumentStorageService.js.map +1 -1
  116. package/lib/quorum.d.ts.map +1 -1
  117. package/lib/quorum.js.map +1 -1
  118. package/lib/retriableDocumentStorageService.d.ts.map +1 -1
  119. package/lib/retriableDocumentStorageService.js +6 -2
  120. package/lib/retriableDocumentStorageService.js.map +1 -1
  121. package/lib/utils.d.ts.map +1 -1
  122. package/lib/utils.js +6 -4
  123. package/lib/utils.js.map +1 -1
  124. package/package.json +115 -114
  125. package/prettier.config.cjs +1 -1
  126. package/src/audience.ts +51 -46
  127. package/src/catchUpMonitor.ts +39 -37
  128. package/src/collabWindowTracker.ts +75 -70
  129. package/src/connectionManager.ts +1006 -944
  130. package/src/connectionState.ts +19 -19
  131. package/src/connectionStateHandler.ts +544 -465
  132. package/src/container.ts +2056 -1909
  133. package/src/containerContext.ts +350 -340
  134. package/src/containerStorageAdapter.ts +163 -153
  135. package/src/contracts.ts +155 -153
  136. package/src/deltaManager.ts +1069 -992
  137. package/src/deltaManagerProxy.ts +143 -137
  138. package/src/deltaQueue.ts +155 -151
  139. package/src/index.ts +14 -17
  140. package/src/loader.ts +428 -430
  141. package/src/packageVersion.ts +1 -1
  142. package/src/protocol.ts +93 -87
  143. package/src/protocolTreeDocumentStorageService.ts +30 -33
  144. package/src/quorum.ts +34 -34
  145. package/src/retriableDocumentStorageService.ts +118 -102
  146. package/src/utils.ts +89 -82
  147. package/tsconfig.esnext.json +6 -6
  148. package/tsconfig.json +8 -12
@@ -5,59 +5,52 @@
5
5
 
6
6
  import { default as AbortController } from "abort-controller";
7
7
  import {
8
- IDisposable,
9
- ITelemetryLogger,
10
- ITelemetryProperties,
8
+ IDisposable,
9
+ ITelemetryLogger,
10
+ ITelemetryProperties,
11
11
  } from "@fluidframework/common-definitions";
12
12
  import { assert, performance, TypedEventEmitter } from "@fluidframework/common-utils";
13
13
  import {
14
- IDeltaQueue,
15
- ReadOnlyInfo,
16
- IConnectionDetails,
17
- ICriticalContainerError,
14
+ IDeltaQueue,
15
+ ReadOnlyInfo,
16
+ IConnectionDetails,
17
+ ICriticalContainerError,
18
18
  } from "@fluidframework/container-definitions";
19
19
  import { GenericError, UsageError } from "@fluidframework/container-utils";
20
20
  import {
21
- IAnyDriverError,
22
- IDocumentService,
23
- IDocumentDeltaConnection,
24
- IDocumentDeltaConnectionEvents,
21
+ IAnyDriverError,
22
+ IDocumentService,
23
+ IDocumentDeltaConnection,
24
+ IDocumentDeltaConnectionEvents,
25
25
  } from "@fluidframework/driver-definitions";
26
26
  import {
27
- canRetryOnError,
28
- createWriteError,
29
- createGenericNetworkError,
30
- getRetryDelayFromError,
31
- waitForConnectedState,
32
- DeltaStreamConnectionForbiddenError,
33
- logNetworkFailure,
34
- isRuntimeMessage,
27
+ canRetryOnError,
28
+ createWriteError,
29
+ createGenericNetworkError,
30
+ getRetryDelayFromError,
31
+ waitForConnectedState,
32
+ DeltaStreamConnectionForbiddenError,
33
+ logNetworkFailure,
34
+ isRuntimeMessage,
35
35
  } from "@fluidframework/driver-utils";
36
36
  import {
37
- ConnectionMode,
38
- IClient,
39
- IClientConfiguration,
40
- IClientDetails,
41
- IDocumentMessage,
42
- INack,
43
- INackContent,
44
- ISequencedDocumentMessage,
45
- ISignalClient,
46
- ISignalMessage,
47
- ITokenClaims,
48
- MessageType,
49
- ScopeType,
50
- ISequencedDocumentSystemMessage,
37
+ ConnectionMode,
38
+ IClient,
39
+ IClientConfiguration,
40
+ IClientDetails,
41
+ IDocumentMessage,
42
+ INack,
43
+ INackContent,
44
+ ISequencedDocumentMessage,
45
+ ISignalClient,
46
+ ISignalMessage,
47
+ ITokenClaims,
48
+ MessageType,
49
+ ScopeType,
50
+ ISequencedDocumentSystemMessage,
51
51
  } from "@fluidframework/protocol-definitions";
52
- import {
53
- TelemetryLogger,
54
- normalizeError,
55
- } from "@fluidframework/telemetry-utils";
56
- import {
57
- ReconnectMode,
58
- IConnectionManager,
59
- IConnectionManagerFactoryArgs,
60
- } from "./contracts";
52
+ import { TelemetryLogger, normalizeError } from "@fluidframework/telemetry-utils";
53
+ import { ReconnectMode, IConnectionManager, IConnectionManagerFactoryArgs } from "./contracts";
61
54
  import { DeltaQueue } from "./deltaQueue";
62
55
  import { SignalType } from "./protocol";
63
56
 
@@ -68,13 +61,15 @@ const DefaultChunkSize = 16 * 1024;
68
61
  const fatalConnectErrorProp = { fatalConnectError: true };
69
62
 
70
63
  function getNackReconnectInfo(nackContent: INackContent) {
71
- const message = `Nack (${nackContent.type}): ${nackContent.message}`;
72
- const canRetry = nackContent.code !== 403;
73
- const retryAfterMs = nackContent.retryAfter !== undefined ? nackContent.retryAfter * 1000 : undefined;
74
- return createGenericNetworkError(
75
- message,
76
- { canRetry, retryAfterMs },
77
- { statusCode: nackContent.code, driverVersion: undefined });
64
+ const message = `Nack (${nackContent.type}): ${nackContent.message}`;
65
+ const canRetry = nackContent.code !== 403;
66
+ const retryAfterMs =
67
+ nackContent.retryAfter !== undefined ? nackContent.retryAfter * 1000 : undefined;
68
+ return createGenericNetworkError(
69
+ message,
70
+ { canRetry, retryAfterMs },
71
+ { statusCode: nackContent.code, driverVersion: undefined },
72
+ );
78
73
  }
79
74
 
80
75
  /**
@@ -82,66 +77,77 @@ function getNackReconnectInfo(nackContent: INackContent) {
82
77
  * or receiving ops. Used in storage-only mode.
83
78
  */
84
79
  const clientNoDeltaStream: IClient = {
85
- mode: "read",
86
- details: { capabilities: { interactive: true } },
87
- permission: [],
88
- user: { id: "storage-only client" }, // we need some "fake" ID here.
89
- scopes: [],
80
+ mode: "read",
81
+ details: { capabilities: { interactive: true } },
82
+ permission: [],
83
+ user: { id: "storage-only client" }, // we need some "fake" ID here.
84
+ scopes: [],
90
85
  };
91
86
  const clientIdNoDeltaStream: string = "storage-only client";
92
87
 
93
88
  class NoDeltaStream
94
- extends TypedEventEmitter<IDocumentDeltaConnectionEvents>
95
- implements IDocumentDeltaConnection, IDisposable {
96
- clientId = clientIdNoDeltaStream;
97
- claims: ITokenClaims = {
98
- scopes: [ScopeType.DocRead],
99
- } as any;
100
- mode: ConnectionMode = "read";
101
- existing: boolean = true;
102
- maxMessageSize: number = 0;
103
- version: string = "";
104
- initialMessages: ISequencedDocumentMessage[] = [];
105
- initialSignals: ISignalMessage[] = [];
106
- initialClients: ISignalClient[] = [{ client: clientNoDeltaStream, clientId: clientIdNoDeltaStream }];
107
- serviceConfiguration: IClientConfiguration = {
108
- maxMessageSize: 0,
109
- blockSize: 0,
110
- };
111
- checkpointSequenceNumber?: number | undefined = undefined;
112
- submit(messages: IDocumentMessage[]): void {
113
- this.emit("nack", this.clientId, messages.map((operation) => {
114
- return {
115
- operation,
116
- content: { message: "Cannot submit with storage-only connection", code: 403 },
117
- };
118
- }));
119
- }
120
- submitSignal(message: any): void {
121
- this.emit("nack", this.clientId, {
122
- operation: message,
123
- content: { message: "Cannot submit signal with storage-only connection", code: 403 },
124
- });
125
- }
126
-
127
- private _disposed = false;
128
- public get disposed() { return this._disposed; }
129
- public dispose() { this._disposed = true; }
89
+ extends TypedEventEmitter<IDocumentDeltaConnectionEvents>
90
+ implements IDocumentDeltaConnection, IDisposable
91
+ {
92
+ clientId = clientIdNoDeltaStream;
93
+ claims: ITokenClaims = {
94
+ scopes: [ScopeType.DocRead],
95
+ } as any;
96
+ mode: ConnectionMode = "read";
97
+ existing: boolean = true;
98
+ maxMessageSize: number = 0;
99
+ version: string = "";
100
+ initialMessages: ISequencedDocumentMessage[] = [];
101
+ initialSignals: ISignalMessage[] = [];
102
+ initialClients: ISignalClient[] = [
103
+ { client: clientNoDeltaStream, clientId: clientIdNoDeltaStream },
104
+ ];
105
+ serviceConfiguration: IClientConfiguration = {
106
+ maxMessageSize: 0,
107
+ blockSize: 0,
108
+ };
109
+ checkpointSequenceNumber?: number | undefined = undefined;
110
+ submit(messages: IDocumentMessage[]): void {
111
+ this.emit(
112
+ "nack",
113
+ this.clientId,
114
+ messages.map((operation) => {
115
+ return {
116
+ operation,
117
+ content: { message: "Cannot submit with storage-only connection", code: 403 },
118
+ };
119
+ }),
120
+ );
121
+ }
122
+ submitSignal(message: any): void {
123
+ this.emit("nack", this.clientId, {
124
+ operation: message,
125
+ content: { message: "Cannot submit signal with storage-only connection", code: 403 },
126
+ });
127
+ }
128
+
129
+ private _disposed = false;
130
+ public get disposed() {
131
+ return this._disposed;
132
+ }
133
+ public dispose() {
134
+ this._disposed = true;
135
+ }
130
136
  }
131
137
 
132
138
  /**
133
139
  * Interface to track the current in-progress connection attempt.
134
140
  */
135
141
  interface IPendingConnection {
136
- /**
137
- * Used to cancel an in-progress connection attempt.
138
- */
139
- abort(): void;
140
-
141
- /**
142
- * Desired ConnectionMode of this in-progress connection attempt.
143
- */
144
- connectionMode: ConnectionMode;
142
+ /**
143
+ * Used to cancel an in-progress connection attempt.
144
+ */
145
+ abort(): void;
146
+
147
+ /**
148
+ * Desired ConnectionMode of this in-progress connection attempt.
149
+ */
150
+ connectionMode: ConnectionMode;
145
151
  }
146
152
 
147
153
  /**
@@ -150,849 +156,905 @@ interface IPendingConnection {
150
156
  * Exposes various controls to influence this process, including manual reconnects, forced read-only mode, etc.
151
157
  */
152
158
  export class ConnectionManager implements IConnectionManager {
153
- /** Connection mode used when reconnecting on error or disconnect. */
154
- private readonly defaultReconnectionMode: ConnectionMode;
155
-
156
- /**
157
- * Tracks the current in-progress connection attempt. Undefined if there is none.
158
- * Note: Once the connection attempt fires and the code becomes asynchronous, its possible that a new connection
159
- * attempt was fired and this.pendingConnection was overwritten to reflect the new attempt.
160
- */
161
- private pendingConnection: IPendingConnection | undefined;
162
- private connection: IDocumentDeltaConnection | undefined;
163
-
164
- /** file ACL - whether user has only read-only access to a file */
165
- private _readonlyPermissions: boolean | undefined;
166
-
167
- /** tracks host requiring read-only mode. */
168
- private _forceReadonly = false;
169
-
170
- /**
171
- * Controls whether the DeltaManager will automatically reconnect to the delta stream after receiving a disconnect.
172
- */
173
- private _reconnectMode: ReconnectMode;
174
-
175
- /** True if there is pending (async) reconnection from "read" to "write" */
176
- private pendingReconnect = false;
177
-
178
- private clientSequenceNumber = 0;
179
- private clientSequenceNumberObserved = 0;
180
- /** Counts the number of non-runtime ops sent by the client which may not be acked. */
181
- private localOpsToIgnore = 0;
182
-
183
- /** track clientId used last time when we sent any ops */
184
- private lastSubmittedClientId: string | undefined;
185
-
186
- private connectFirstConnection = true;
187
-
188
- private _connectionVerboseProps: Record<string, string | number> = {};
189
-
190
- private _connectionProps: ITelemetryProperties = {};
191
-
192
- private _disposed = false;
193
-
194
- private readonly _outbound: DeltaQueue<IDocumentMessage[]>;
195
-
196
- public get connectionVerboseProps() { return this._connectionVerboseProps; }
197
-
198
- public readonly clientDetails: IClientDetails;
199
-
200
- /**
201
- * The current connection mode, initially read.
202
- */
203
- public get connectionMode(): ConnectionMode {
204
- return this.connection?.mode ?? "read";
205
- }
206
-
207
- public get connected() { return this.connection !== undefined; }
208
-
209
- public get clientId() { return this.connection?.clientId; }
210
- /**
211
- * Automatic reconnecting enabled or disabled.
212
- * If set to Never, then reconnecting will never be allowed.
213
- */
214
- public get reconnectMode(): ReconnectMode {
215
- return this._reconnectMode;
216
- }
217
-
218
- public get maxMessageSize(): number {
219
- return this.connection?.serviceConfiguration?.maxMessageSize
220
- ?? DefaultChunkSize;
221
- }
222
-
223
- public get version(): string {
224
- if (this.connection === undefined) {
225
- throw new Error("Cannot check version without a connection");
226
- }
227
- return this.connection.version;
228
- }
229
-
230
- public get serviceConfiguration(): IClientConfiguration | undefined {
231
- return this.connection?.serviceConfiguration;
232
- }
233
-
234
- public get scopes(): string[] | undefined {
235
- return this.connection?.claims.scopes;
236
- }
237
-
238
- public get outbound(): IDeltaQueue<IDocumentMessage[]> {
239
- return this._outbound;
240
- }
241
-
242
- /**
243
- * Returns set of props that can be logged in telemetry that provide some insights / statistics
244
- * about current or last connection (if there is no connection at the moment)
245
- */
246
- public get connectionProps(): ITelemetryProperties {
247
- return this.connection !== undefined
248
- ? this._connectionProps
249
- : {
250
- ...this._connectionProps,
251
- // Report how many ops this client sent in last disconnected session
252
- sentOps: this.clientSequenceNumber,
253
- };
254
- }
255
-
256
- public shouldJoinWrite(): boolean {
257
- // We don't have to wait for ack for topmost NoOps. So subtract those.
258
- return this.clientSequenceNumberObserved < (this.clientSequenceNumber - this.localOpsToIgnore);
259
- }
260
-
261
- /**
262
- * Tells if container is in read-only mode.
263
- * Data stores should listen for "readonly" notifications and disallow user
264
- * making changes to data stores.
265
- * Readonly state can be because of no storage write permission,
266
- * or due to host forcing readonly mode for container.
267
- * It is undefined if we have not yet established websocket connection
268
- * and do not know if user has write access to a file.
269
- */
270
- private get readonly(): boolean | undefined {
271
- if (this._forceReadonly) {
272
- return true;
273
- }
274
- return this._readonlyPermissions;
275
- }
276
-
277
- public get readOnlyInfo(): ReadOnlyInfo {
278
- const storageOnly = this.connection !== undefined && this.connection instanceof NoDeltaStream;
279
- if (storageOnly || this._forceReadonly || this._readonlyPermissions === true) {
280
- return {
281
- readonly: true,
282
- forced: this._forceReadonly,
283
- permissions: this._readonlyPermissions,
284
- storageOnly,
285
- };
286
- }
287
-
288
- return { readonly: this._readonlyPermissions };
289
- }
290
-
291
- private static detailsFromConnection(connection: IDocumentDeltaConnection): IConnectionDetails {
292
- return {
293
- claims: connection.claims,
294
- clientId: connection.clientId,
295
- existing: connection.existing,
296
- checkpointSequenceNumber: connection.checkpointSequenceNumber,
297
- get initialClients() { return connection.initialClients; },
298
- mode: connection.mode,
299
- serviceConfiguration: connection.serviceConfiguration,
300
- version: connection.version,
301
- };
302
- }
303
-
304
- constructor(
305
- private readonly serviceProvider: () => IDocumentService | undefined,
306
- private client: IClient,
307
- reconnectAllowed: boolean,
308
- private readonly logger: ITelemetryLogger,
309
- private readonly props: IConnectionManagerFactoryArgs,
310
- ) {
311
- this.clientDetails = this.client.details;
312
- this.defaultReconnectionMode = this.client.mode;
313
- this._reconnectMode = reconnectAllowed ? ReconnectMode.Enabled : ReconnectMode.Never;
314
-
315
- // Outbound message queue. The outbound queue is represented as a queue of an array of ops. Ops contained
316
- // within an array *must* fit within the maxMessageSize and are guaranteed to be ordered sequentially.
317
- this._outbound = new DeltaQueue<IDocumentMessage[]>(
318
- (messages) => {
319
- if (this.connection === undefined) {
320
- throw new Error("Attempted to submit an outbound message without connection");
321
- }
322
- this.connection.submit(messages);
323
- });
324
-
325
- this._outbound.on("error", (error) => {
326
- this.props.closeHandler(normalizeError(error));
327
- });
328
- }
329
-
330
- public dispose(error?: ICriticalContainerError, switchToReadonly: boolean = true) {
331
- if (this._disposed) {
332
- return;
333
- }
334
- this._disposed = true;
335
-
336
- this.pendingConnection = undefined;
337
-
338
- // Ensure that things like triggerConnect() will short circuit
339
- this._reconnectMode = ReconnectMode.Never;
340
-
341
- this._outbound.clear();
342
-
343
- const disconnectReason = error !== undefined
344
- ? `Closing DeltaManager (${error.message})`
345
- : "Closing DeltaManager";
346
-
347
- // This raises "disconnect" event if we have active connection.
348
- this.disconnectFromDeltaStream(disconnectReason);
349
-
350
- if (switchToReadonly) {
351
- // Notify everyone we are in read-only state.
352
- // Useful for data stores in case we hit some critical error,
353
- // to switch to a mode where user edits are not accepted
354
- this.set_readonlyPermissions(true);
355
- }
356
- }
357
-
358
- /**
359
- * Enables or disables automatic reconnecting.
360
- * Will throw an error if reconnectMode set to Never.
361
- */
362
- public setAutoReconnect(mode: ReconnectMode): void {
363
- assert(mode !== ReconnectMode.Never && this._reconnectMode !== ReconnectMode.Never,
364
- 0x278 /* "API is not supported for non-connecting or closed container" */);
365
-
366
- this._reconnectMode = mode;
367
-
368
- if (mode !== ReconnectMode.Enabled) {
369
- // immediately disconnect - do not rely on service eventually dropping connection.
370
- this.disconnectFromDeltaStream("setAutoReconnect");
371
- }
372
- }
373
-
374
- /**
375
- * Sends signal to runtime (and data stores) to be read-only.
376
- * Hosts may have read only views, indicating to data stores that no edits are allowed.
377
- * This is independent from this._readonlyPermissions (permissions) and this.connectionMode
378
- * (server can return "write" mode even when asked for "read")
379
- * Leveraging same "readonly" event as runtime & data stores should behave the same in such case
380
- * as in read-only permissions.
381
- * But this.active can be used by some DDSes to figure out if ops can be sent
382
- * (for example, read-only view still participates in code proposals / upgrades decisions)
383
- *
384
- * Forcing Readonly does not prevent DDS from generating ops. It is up to user code to honour
385
- * the readonly flag. If ops are generated, they will accumulate locally and not be sent. If
386
- * there are pending in the outbound queue, it will stop sending until force readonly is
387
- * cleared.
388
- *
389
- * @param readonly - set or clear force readonly.
390
- */
391
- public forceReadonly(readonly: boolean) {
392
- if (readonly !== this._forceReadonly) {
393
- this.logger.sendTelemetryEvent({
394
- eventName: "ForceReadOnly",
395
- value: readonly,
396
- });
397
- }
398
- const oldValue = this.readonly;
399
- this._forceReadonly = readonly;
400
-
401
- if (oldValue !== this.readonly) {
402
- if (this._reconnectMode === ReconnectMode.Never) {
403
- throw new UsageError("API is not supported for non-connecting or closed container");
404
- }
405
- let reconnect = false;
406
- if (this.readonly === true) {
407
- // If we switch to readonly while connected, we should disconnect first
408
- // See comment in the "readonly" event handler to deltaManager set up by
409
- // the ContainerRuntime constructor
410
-
411
- if (this.shouldJoinWrite()) {
412
- // If we have pending changes, then we will never send them - it smells like
413
- // host logic error.
414
- this.logger.sendErrorEvent({ eventName: "ForceReadonlyPendingChanged" });
415
- }
416
-
417
- reconnect = this.disconnectFromDeltaStream("Force readonly");
418
- }
419
- this.props.readonlyChangeHandler(this.readonly);
420
- if (reconnect) {
421
- // reconnect if we disconnected from before.
422
- this.triggerConnect("read");
423
- }
424
- }
425
- }
426
-
427
- private set_readonlyPermissions(readonly: boolean) {
428
- const oldValue = this.readonly;
429
- this._readonlyPermissions = readonly;
430
- if (oldValue !== this.readonly) {
431
- this.props.readonlyChangeHandler(this.readonly);
432
- }
433
- }
434
-
435
- public connect(connectionMode?: ConnectionMode) {
436
- this.connectCore(connectionMode).catch((error) => {
437
- const normalizedError = normalizeError(error, { props: fatalConnectErrorProp });
438
- this.props.closeHandler(normalizedError);
439
- });
440
- }
441
-
442
- private async connectCore(connectionMode?: ConnectionMode): Promise<void> {
443
- assert(!this._disposed, 0x26a /* "not closed" */);
444
-
445
- if (this.connection !== undefined) {
446
- return; // Connection attempt already completed successfully
447
- }
448
-
449
- let pendingConnectionMode;
450
- if (this.pendingConnection !== undefined) {
451
- pendingConnectionMode = this.pendingConnection.connectionMode;
452
- this.cancelConnection(); // Throw out in-progress connection attempt in favor of new attempt
453
- assert(this.pendingConnection === undefined, 0x344 /* this.pendingConnection should be undefined */);
454
- }
455
- // If there is no specified ConnectionMode, try the previous mode, if there is no previous mode use default
456
- let requestedMode = connectionMode ?? pendingConnectionMode ?? this.defaultReconnectionMode;
457
-
458
- // if we have any non-acked ops from last connection, reconnect as "write".
459
- // without that we would connect in view-only mode, which will result in immediate
460
- // firing of "connected" event from Container and switch of current clientId (as tracked
461
- // by all DDSes). This will make it impossible to figure out if ops actually made it through,
462
- // so DDSes will immediately resubmit all pending ops, and some of them will be duplicates, corrupting document
463
- if (this.shouldJoinWrite()) {
464
- requestedMode = "write";
465
- }
466
-
467
- const docService = this.serviceProvider();
468
- assert(docService !== undefined, 0x2a7 /* "Container is not attached" */);
469
-
470
- let connection: IDocumentDeltaConnection | undefined;
471
-
472
- if (docService.policies?.storageOnly === true) {
473
- connection = new NoDeltaStream();
474
- this.setupNewSuccessfulConnection(connection, "read");
475
- assert(this.pendingConnection === undefined, 0x2b3 /* "logic error" */);
476
- return;
477
- }
478
-
479
- let delayMs = InitialReconnectDelayInMs;
480
- let connectRepeatCount = 0;
481
- const connectStartTime = performance.now();
482
- let lastError: any;
483
-
484
- const abortController = new AbortController();
485
- const abortSignal = abortController.signal;
486
- this.pendingConnection = { abort: () => { abortController.abort(); }, connectionMode: requestedMode };
487
-
488
- // This loop will keep trying to connect until successful, with a delay between each iteration.
489
- while (connection === undefined) {
490
- if (this._disposed) {
491
- throw new Error("Attempting to connect a closed DeltaManager");
492
- }
493
- if (abortSignal.aborted === true) {
494
- this.logger.sendTelemetryEvent({
495
- eventName: "ConnectionAttemptCancelled",
496
- attempts: connectRepeatCount,
497
- duration: TelemetryLogger.formatTick(performance.now() - connectStartTime),
498
- connectionEstablished: false,
499
- });
500
- return;
501
- }
502
- connectRepeatCount++;
503
-
504
- try {
505
- this.client.mode = requestedMode;
506
- connection = await docService.connectToDeltaStream({ ...this.client, mode: requestedMode });
507
-
508
- if (connection.disposed) {
509
- // Nobody observed this connection, so drop it on the floor and retry.
510
- this.logger.sendTelemetryEvent({ eventName: "ReceivedClosedConnection" });
511
- connection = undefined;
512
- }
513
- } catch (origError: any) {
514
- if (typeof origError === "object" && origError !== null &&
515
- origError?.errorType === DeltaStreamConnectionForbiddenError.errorType) {
516
- connection = new NoDeltaStream();
517
- requestedMode = "read";
518
- break;
519
- }
520
-
521
- // Socket.io error when we connect to wrong socket, or hit some multiplexing bug
522
- if (!canRetryOnError(origError)) {
523
- const error = normalizeError(origError, { props: fatalConnectErrorProp });
524
- this.props.closeHandler(error);
525
- throw error;
526
- }
527
-
528
- // Since the error is retryable this will not log to the error table
529
- logNetworkFailure(
530
- this.logger,
531
- {
532
- attempts: connectRepeatCount,
533
- delay: delayMs, // milliseconds
534
- eventName: "DeltaConnectionFailureToConnect",
535
- duration: TelemetryLogger.formatTick(performance.now() - connectStartTime),
536
- },
537
- origError);
538
-
539
- lastError = origError;
540
-
541
- const retryDelayFromError = getRetryDelayFromError(origError);
542
- delayMs = retryDelayFromError ?? Math.min(delayMs * 2, MaxReconnectDelayInMs);
543
-
544
- if (retryDelayFromError !== undefined) {
545
- this.props.reconnectionDelayHandler(retryDelayFromError, origError);
546
- }
547
- await waitForConnectedState(delayMs);
548
- }
549
- }
550
-
551
- // If we retried more than once, log an event about how long it took (this will not log to error table)
552
- if (connectRepeatCount > 1) {
553
- logNetworkFailure(
554
- this.logger,
555
- {
556
- eventName: "MultipleDeltaConnectionFailures",
557
- attempts: connectRepeatCount,
558
- duration: TelemetryLogger.formatTick(performance.now() - connectStartTime),
559
- },
560
- lastError,
561
- );
562
- }
563
-
564
- // Check for abort signal after while loop as well
565
- if (abortSignal.aborted === true) {
566
- connection.dispose();
567
- this.logger.sendTelemetryEvent({
568
- eventName: "ConnectionAttemptCancelled",
569
- attempts: connectRepeatCount,
570
- duration: TelemetryLogger.formatTick(performance.now() - connectStartTime),
571
- connectionEstablished: true,
572
- });
573
- return;
574
- }
575
-
576
- this.setupNewSuccessfulConnection(connection, requestedMode);
577
- }
578
-
579
- /**
580
- * Start the connection. Any error should result in container being closed.
581
- * And report the error if it escapes for any reason.
582
- * @param args - The connection arguments
583
- */
584
- private triggerConnect(connectionMode: ConnectionMode) {
585
- // reconnect() has async await of waitForConnectedState(), and that causes potential race conditions
586
- // where we might already have a connection. If it were to happen, it's possible that we will connect
587
- // with different mode to `connectionMode`. Glancing through the caller chains, it looks like code should be
588
- // fine (if needed, reconnect flow will get triggered again). Places where new mode matters should encode it
589
- // directly in connectCore - see this.shouldJoinWrite() test as an example.
590
- // assert(this.connection === undefined, 0x239 /* "called only in disconnected state" */);
591
-
592
- if (this.reconnectMode !== ReconnectMode.Enabled) {
593
- return;
594
- }
595
- this.connect(connectionMode);
596
- }
597
-
598
- /**
599
- * Disconnect the current connection.
600
- * @param reason - Text description of disconnect reason to emit with disconnect event
601
- * @returns A boolean that indicates if there was an existing connection (or pending connection) to disconnect
602
- */
603
- private disconnectFromDeltaStream(reason: string): boolean {
604
- this.pendingReconnect = false;
605
-
606
- if (this.connection === undefined) {
607
- if (this.pendingConnection !== undefined) {
608
- this.cancelConnection();
609
- return true;
610
- }
611
- return false;
612
- }
613
-
614
- assert(this.pendingConnection === undefined, 0x27b /* "reentrancy may result in incorrect behavior" */);
615
-
616
- const connection = this.connection;
617
- // Avoid any re-entrancy - clear object reference
618
- this.connection = undefined;
619
-
620
- // Remove listeners first so we don't try to retrigger this flow accidentally through reconnectOnError
621
- connection.off("op", this.opHandler);
622
- connection.off("signal", this.props.signalHandler);
623
- connection.off("nack", this.nackHandler);
624
- connection.off("disconnect", this.disconnectHandlerInternal);
625
- connection.off("error", this.errorHandler);
626
- connection.off("pong", this.props.pongHandler);
627
-
628
- // eslint-disable-next-line @typescript-eslint/no-floating-promises
629
- this._outbound.pause();
630
- this._outbound.clear();
631
-
632
- connection.dispose();
633
-
634
- this.props.disconnectHandler(reason);
635
-
636
- this._connectionVerboseProps = {};
637
-
638
- return true;
639
- }
640
-
641
- /**
642
- * Cancel in-progress connection attempt.
643
- */
644
- private cancelConnection() {
645
- assert(this.pendingConnection !== undefined,
646
- 0x345 /* this.pendingConnection is undefined when trying to cancel */);
647
- this.pendingConnection.abort();
648
- this.pendingConnection = undefined;
649
- this.logger.sendTelemetryEvent({ eventName: "ConnectionCancelReceived" });
650
- }
651
-
652
- /**
653
- * Once we've successfully gotten a connection, we need to set up state, attach event listeners, and process
654
- * initial messages.
655
- * @param connection - The newly established connection
656
- */
657
- private setupNewSuccessfulConnection(connection: IDocumentDeltaConnection, requestedMode: ConnectionMode) {
658
- // Old connection should have been cleaned up before establishing a new one
659
- assert(this.connection === undefined, 0x0e6 /* "old connection exists on new connection setup" */);
660
- assert(!connection.disposed, 0x28a /* "can't be disposed - Callers need to ensure that!" */);
661
-
662
- this.pendingConnection = undefined;
663
-
664
- this.connection = connection;
665
-
666
- // Does information in scopes & mode matches?
667
- // If we asked for "write" and got "read", then file is read-only
668
- // But if we ask read, server can still give us write.
669
- const readonly = !connection.claims.scopes.includes(ScopeType.DocWrite);
670
-
671
- if (connection.mode !== requestedMode) {
672
- this.logger.sendTelemetryEvent({ eventName: "ConnectionModeMismatch", requestedMode, mode: connection.mode });
673
- }
674
- // This connection mode validation logic is moving to the driver layer in 0.44. These two asserts can be
675
- // removed after those packages have released and become ubiquitous.
676
- assert(requestedMode === "read" || readonly === (this.connectionMode === "read"),
677
- 0x0e7 /* "claims/connectionMode mismatch" */);
678
- assert(!readonly || this.connectionMode === "read", 0x0e8 /* "readonly perf with write connection" */);
679
-
680
- this.set_readonlyPermissions(readonly);
681
-
682
- if (this._disposed) {
683
- // Raise proper events, Log telemetry event and close connection.
684
- this.disconnectFromDeltaStream("ConnectionManager already closed");
685
- return;
686
- }
687
-
688
- this._outbound.resume();
689
-
690
- connection.on("op", this.opHandler);
691
- connection.on("signal", this.props.signalHandler);
692
- connection.on("nack", this.nackHandler);
693
- connection.on("disconnect", this.disconnectHandlerInternal);
694
- connection.on("error", this.errorHandler);
695
- connection.on("pong", this.props.pongHandler);
696
-
697
- // Initial messages are always sorted. However, due to early op handler installed by drivers and appending those
698
- // ops to initialMessages, resulting set is no longer sorted, which would result in client hitting storage to
699
- // fill in gap. We will recover by cancelling this request once we process remaining ops, but it's a waste that
700
- // we could avoid
701
- const initialMessages = connection.initialMessages.sort((a, b) => a.sequenceNumber - b.sequenceNumber);
702
-
703
- // Some storages may provide checkpointSequenceNumber to identify how far client is behind.
704
- let checkpointSequenceNumber = connection.checkpointSequenceNumber;
705
-
706
- this._connectionVerboseProps = {
707
- clientId: connection.clientId,
708
- mode: connection.mode,
709
- };
710
-
711
- // reset connection props
712
- this._connectionProps = {};
713
-
714
- if (connection.relayServiceAgent !== undefined) {
715
- this._connectionVerboseProps.relayServiceAgent = connection.relayServiceAgent;
716
- this._connectionProps.relayServiceAgent = connection.relayServiceAgent;
717
- }
718
- this._connectionProps.socketDocumentId = connection.claims.documentId;
719
- this._connectionProps.connectionMode = connection.mode;
720
-
721
- let last = -1;
722
- if (initialMessages.length !== 0) {
723
- this._connectionVerboseProps.connectionInitialOpsFrom = initialMessages[0].sequenceNumber;
724
- last = initialMessages[initialMessages.length - 1].sequenceNumber;
725
- this._connectionVerboseProps.connectionInitialOpsTo = last + 1;
726
- // Update knowledge of how far we are behind, before raising "connect" event
727
- // This is duplication of what incomingOpHandler() does, but we have to raise event before we get there,
728
- // so duplicating update logic here as well.
729
- if (checkpointSequenceNumber === undefined || checkpointSequenceNumber < last) {
730
- checkpointSequenceNumber = last;
731
- }
732
- }
733
-
734
- this.props.incomingOpHandler(
735
- initialMessages,
736
- this.connectFirstConnection ? "InitialOps" : "ReconnectOps");
737
-
738
- const details = ConnectionManager.detailsFromConnection(connection);
739
- details.checkpointSequenceNumber = checkpointSequenceNumber;
740
- this.props.connectHandler(details);
741
-
742
- this.connectFirstConnection = false;
743
-
744
- // Synthesize clear & join signals out of initialClients state.
745
- // This allows us to have single way to process signals, and makes it simpler to initialize
746
- // protocol in Container.
747
- const clearSignal: ISignalMessage = {
748
- clientId: null, // system message
749
- content: JSON.stringify({
750
- type: SignalType.Clear,
751
- }),
752
- };
753
- this.props.signalHandler(clearSignal);
754
-
755
- for (const priorClient of connection.initialClients ?? []) {
756
- const joinSignal: ISignalMessage = {
757
- clientId: null, // system signal
758
- content: JSON.stringify({
759
- type: SignalType.ClientJoin,
760
- content: priorClient, // ISignalClient
761
- }),
762
- };
763
- this.props.signalHandler(joinSignal);
764
- }
765
-
766
- // Unfortunately, there is no defined order between initialSignals (including join & leave signals)
767
- // and connection.initialClients. In practice, connection.initialSignals quite often contains join signal
768
- // for "self" and connection.initialClients does not contain "self", so we have to process them after
769
- // "clear" signal above.
770
- if (connection.initialSignals !== undefined) {
771
- for (const signal of connection.initialSignals) {
772
- this.props.signalHandler(signal);
773
- }
774
- }
775
- }
776
-
777
- /**
778
- * Disconnect the current connection and reconnect. Closes the container if it fails.
779
- * @param connection - The connection that wants to reconnect - no-op if it's different from this.connection
780
- * @param requestedMode - Read or write
781
- * @param error - Error reconnect information including whether or not to reconnect
782
- * @returns A promise that resolves when the connection is reestablished or we stop trying
783
- */
784
- private reconnectOnError(
785
- requestedMode: ConnectionMode,
786
- error: IAnyDriverError,
787
- ) {
788
- this.reconnect(
789
- requestedMode,
790
- error.message,
791
- error)
792
- .catch(this.props.closeHandler);
793
- }
794
-
795
- /**
796
- * Disconnect the current connection and reconnect.
797
- * @param connection - The connection that wants to reconnect - no-op if it's different from this.connection
798
- * @param requestedMode - Read or write
799
- * @param error - Error reconnect information including whether or not to reconnect
800
- * @returns A promise that resolves when the connection is reestablished or we stop trying
801
- */
802
- private async reconnect(
803
- requestedMode: ConnectionMode,
804
- disconnectMessage: string,
805
- error?: IAnyDriverError,
806
- ) {
807
- // We quite often get protocol errors before / after observing nack/disconnect
808
- // we do not want to run through same sequence twice.
809
- // If we're already disconnected/disconnecting it's not appropriate to call this again.
810
- assert(this.connection !== undefined, 0x0eb /* "Missing connection for reconnect" */);
811
-
812
- this.disconnectFromDeltaStream(disconnectMessage);
813
-
814
- // We will always trigger reconnect, even if canRetry is false.
815
- // Any truly fatal error state will result in container close upon attempted reconnect,
816
- // which is a preferable to closing abruptly when a live connection fails.
817
- if (error !== undefined && !error.canRetry) {
818
- this.logger.sendTelemetryEvent({
819
- eventName: "reconnectingDespiteFatalError",
820
- reconnectMode: this.reconnectMode,
821
- }, error);
822
- }
823
-
824
- if (this.reconnectMode === ReconnectMode.Never) {
825
- // Do not raise container error if we are closing just because we lost connection.
826
- // Those errors (like IdleDisconnect) would show up in telemetry dashboards and
827
- // are very misleading, as first initial reaction - some logic is broken.
828
- this.props.closeHandler();
829
- }
830
-
831
- // If closed then we can't reconnect
832
- if (this._disposed || this.reconnectMode !== ReconnectMode.Enabled) {
833
- return;
834
- }
835
-
836
- const delayMs = getRetryDelayFromError(error);
837
- if (error !== undefined && delayMs !== undefined) {
838
- this.props.reconnectionDelayHandler(delayMs, error);
839
- await waitForConnectedState(delayMs);
840
- }
841
-
842
- this.triggerConnect(requestedMode);
843
- }
844
-
845
- public prepareMessageToSend(message: Omit<IDocumentMessage, "clientSequenceNumber">): IDocumentMessage | undefined {
846
- if (this.readonly === true) {
847
- assert(this.readOnlyInfo.readonly === true, 0x1f0 /* "Unexpected mismatch in readonly" */);
848
- const error = new GenericError("deltaManagerReadonlySubmit", undefined /* error */, {
849
- readonly: this.readOnlyInfo.readonly,
850
- forcedReadonly: this.readOnlyInfo.forced,
851
- readonlyPermissions: this.readOnlyInfo.permissions,
852
- storageOnly: this.readOnlyInfo.storageOnly,
853
- });
854
- this.props.closeHandler(error);
855
- return undefined;
856
- }
857
-
858
- // reset clientSequenceNumber if we are using new clientId.
859
- // we keep info about old connection as long as possible to be able to account for all non-acked ops
860
- // that we pick up on next connection.
861
- assert(!!this.connection, 0x0e4 /* "Lost old connection!" */);
862
- if (this.lastSubmittedClientId !== this.connection?.clientId) {
863
- this.lastSubmittedClientId = this.connection?.clientId;
864
- this.clientSequenceNumber = 0;
865
- this.clientSequenceNumberObserved = 0;
866
- }
867
-
868
- if (!isRuntimeMessage(message)) {
869
- this.localOpsToIgnore++;
870
- } else {
871
- this.localOpsToIgnore = 0;
872
- }
873
-
874
- return {
875
- ...message,
876
- clientSequenceNumber: ++this.clientSequenceNumber,
877
- };
878
- }
879
-
880
- public submitSignal(content: any) {
881
- if (this.connection !== undefined) {
882
- this.connection.submitSignal(content);
883
- } else {
884
- this.logger.sendErrorEvent({ eventName: "submitSignalDisconnected" });
885
- }
886
- }
887
-
888
- public sendMessages(messages: IDocumentMessage[]) {
889
- assert(this.connected, 0x2b4 /* "not connected on sending ops!" */);
890
- // If connection is "read" or implicit "read" (got leave op for "write" connection),
891
- // then op can't make it through - we will get a nack if op is sent.
892
- // We can short-circuit this process.
893
- // Note that we also want nacks to be rare and be treated as catastrophic failures.
894
- // Be careful with reentrancy though - disconnected event should not be be raised in the
895
- // middle of the current workflow, but rather on clean stack!
896
- if (this.connectionMode === "read") {
897
- if (!this.pendingReconnect) {
898
- this.pendingReconnect = true;
899
- Promise.resolve().then(async () => {
900
- if (this.pendingReconnect) { // still valid?
901
- await this.reconnect(
902
- "write", // connectionMode
903
- "Switch to write", // message
904
- );
905
- }
906
- }).catch(() => { });
907
- }
908
- return;
909
- }
910
-
911
- assert(!this.pendingReconnect, 0x2b5 /* "logic error" */);
912
-
913
- this._outbound.push(messages);
914
- }
915
-
916
- public beforeProcessingIncomingOp(message: ISequencedDocumentMessage) {
917
- // if we have connection, and message is local, then we better treat is as local!
918
- assert(this.clientId !== message.clientId || this.lastSubmittedClientId === message.clientId,
919
- 0x0ee /* "Not accounting local messages correctly" */,
920
- );
921
-
922
- if (this.lastSubmittedClientId !== undefined && this.lastSubmittedClientId === message.clientId) {
923
- const clientSequenceNumber = message.clientSequenceNumber;
924
-
925
- assert(this.clientSequenceNumberObserved < clientSequenceNumber, 0x0ef /* "client seq# not growing" */);
926
- assert(clientSequenceNumber <= this.clientSequenceNumber,
927
- 0x0f0 /* "Incoming local client seq# > generated by this client" */);
928
-
929
- this.clientSequenceNumberObserved = clientSequenceNumber;
930
- }
931
-
932
- if (message.type === MessageType.ClientLeave) {
933
- const systemLeaveMessage = message as ISequencedDocumentSystemMessage;
934
- const clientId = JSON.parse(systemLeaveMessage.data) as string;
935
- if (clientId === this.clientId) {
936
- // We have been kicked out from quorum
937
- this.logger.sendPerformanceEvent({ eventName: "ReadConnectionTransition" });
938
-
939
- // Please see #8483 for more details on why maintaining connection further as is would not work.
940
- // Short story - connection properties are immutable, and many processes (consensus DDSes, summarizer)
941
- // assume that connection stays "write" connection until disconnect, and act accordingly, which may
942
- // not work well with de-facto "read" connection we are in after receiving own leave op on timeout.
943
- // Clients need to be able to transition to "read" state after some time of inactivity!
944
- // Note - this may close container!
945
- this.reconnect(
946
- "read", // connectionMode
947
- "Switch to read", // message
948
- ).catch((error) => {
949
- this.logger.sendErrorEvent({ eventName: "SwitchToReadConnection" }, error);
950
- });
951
- }
952
- }
953
- }
954
-
955
- private readonly opHandler = (documentId: string, messagesArg: ISequencedDocumentMessage[]) => {
956
- const messages = Array.isArray(messagesArg) ? messagesArg : [messagesArg];
957
- this.props.incomingOpHandler(messages, "opHandler");
958
- };
959
-
960
- // Always connect in write mode after getting nacked.
961
- private readonly nackHandler = (documentId: string, messages: INack[]) => {
962
- const message = messages[0];
963
- if (this._readonlyPermissions === true) {
964
- this.props.closeHandler(createWriteError("writeOnReadOnlyDocument", { driverVersion: undefined }));
965
- return;
966
- }
967
-
968
- const reconnectInfo = getNackReconnectInfo(message.content);
969
-
970
- // If the nack indicates we cannot retry, then close the container outright
971
- if (!reconnectInfo.canRetry) {
972
- this.props.closeHandler(reconnectInfo);
973
- return;
974
- }
975
-
976
- this.reconnectOnError(
977
- "write",
978
- reconnectInfo,
979
- );
980
- };
981
-
982
- // Connection mode is always read on disconnect/error unless the system mode was write.
983
- private readonly disconnectHandlerInternal = (disconnectReason: IAnyDriverError) => {
984
- // Note: we might get multiple disconnect calls on same socket, as early disconnect notification
985
- // ("server_disconnect", ODSP-specific) is mapped to "disconnect"
986
- this.reconnectOnError(
987
- this.defaultReconnectionMode,
988
- disconnectReason,
989
- );
990
- };
991
-
992
- private readonly errorHandler = (error: IAnyDriverError) => {
993
- this.reconnectOnError(
994
- this.defaultReconnectionMode,
995
- error,
996
- );
997
- };
159
+ /** Connection mode used when reconnecting on error or disconnect. */
160
+ private readonly defaultReconnectionMode: ConnectionMode;
161
+
162
+ /**
163
+ * Tracks the current in-progress connection attempt. Undefined if there is none.
164
+ * Note: Once the connection attempt fires and the code becomes asynchronous, its possible that a new connection
165
+ * attempt was fired and this.pendingConnection was overwritten to reflect the new attempt.
166
+ */
167
+ private pendingConnection: IPendingConnection | undefined;
168
+ private connection: IDocumentDeltaConnection | undefined;
169
+
170
+ /** file ACL - whether user has only read-only access to a file */
171
+ private _readonlyPermissions: boolean | undefined;
172
+
173
+ /** tracks host requiring read-only mode. */
174
+ private _forceReadonly = false;
175
+
176
+ /**
177
+ * Controls whether the DeltaManager will automatically reconnect to the delta stream after receiving a disconnect.
178
+ */
179
+ private _reconnectMode: ReconnectMode;
180
+
181
+ /** True if there is pending (async) reconnection from "read" to "write" */
182
+ private pendingReconnect = false;
183
+
184
+ private clientSequenceNumber = 0;
185
+ private clientSequenceNumberObserved = 0;
186
+ /** Counts the number of non-runtime ops sent by the client which may not be acked. */
187
+ private localOpsToIgnore = 0;
188
+
189
+ /** track clientId used last time when we sent any ops */
190
+ private lastSubmittedClientId: string | undefined;
191
+
192
+ private connectFirstConnection = true;
193
+
194
+ private _connectionVerboseProps: Record<string, string | number> = {};
195
+
196
+ private _connectionProps: ITelemetryProperties = {};
197
+
198
+ private _disposed = false;
199
+
200
+ private readonly _outbound: DeltaQueue<IDocumentMessage[]>;
201
+
202
+ public get connectionVerboseProps() {
203
+ return this._connectionVerboseProps;
204
+ }
205
+
206
+ public readonly clientDetails: IClientDetails;
207
+
208
+ /**
209
+ * The current connection mode, initially read.
210
+ */
211
+ public get connectionMode(): ConnectionMode {
212
+ return this.connection?.mode ?? "read";
213
+ }
214
+
215
+ public get connected() {
216
+ return this.connection !== undefined;
217
+ }
218
+
219
+ public get clientId() {
220
+ return this.connection?.clientId;
221
+ }
222
+ /**
223
+ * Automatic reconnecting enabled or disabled.
224
+ * If set to Never, then reconnecting will never be allowed.
225
+ */
226
+ public get reconnectMode(): ReconnectMode {
227
+ return this._reconnectMode;
228
+ }
229
+
230
+ public get maxMessageSize(): number {
231
+ return this.connection?.serviceConfiguration?.maxMessageSize ?? DefaultChunkSize;
232
+ }
233
+
234
+ public get version(): string {
235
+ if (this.connection === undefined) {
236
+ throw new Error("Cannot check version without a connection");
237
+ }
238
+ return this.connection.version;
239
+ }
240
+
241
+ public get serviceConfiguration(): IClientConfiguration | undefined {
242
+ return this.connection?.serviceConfiguration;
243
+ }
244
+
245
+ public get scopes(): string[] | undefined {
246
+ return this.connection?.claims.scopes;
247
+ }
248
+
249
+ public get outbound(): IDeltaQueue<IDocumentMessage[]> {
250
+ return this._outbound;
251
+ }
252
+
253
+ /**
254
+ * Returns set of props that can be logged in telemetry that provide some insights / statistics
255
+ * about current or last connection (if there is no connection at the moment)
256
+ */
257
+ public get connectionProps(): ITelemetryProperties {
258
+ return this.connection !== undefined
259
+ ? this._connectionProps
260
+ : {
261
+ ...this._connectionProps,
262
+ // Report how many ops this client sent in last disconnected session
263
+ sentOps: this.clientSequenceNumber,
264
+ };
265
+ }
266
+
267
+ public shouldJoinWrite(): boolean {
268
+ // We don't have to wait for ack for topmost NoOps. So subtract those.
269
+ return (
270
+ this.clientSequenceNumberObserved < this.clientSequenceNumber - this.localOpsToIgnore
271
+ );
272
+ }
273
+
274
+ /**
275
+ * Tells if container is in read-only mode.
276
+ * Data stores should listen for "readonly" notifications and disallow user
277
+ * making changes to data stores.
278
+ * Readonly state can be because of no storage write permission,
279
+ * or due to host forcing readonly mode for container.
280
+ * It is undefined if we have not yet established websocket connection
281
+ * and do not know if user has write access to a file.
282
+ */
283
+ private get readonly(): boolean | undefined {
284
+ if (this._forceReadonly) {
285
+ return true;
286
+ }
287
+ return this._readonlyPermissions;
288
+ }
289
+
290
+ public get readOnlyInfo(): ReadOnlyInfo {
291
+ const storageOnly =
292
+ this.connection !== undefined && this.connection instanceof NoDeltaStream;
293
+ if (storageOnly || this._forceReadonly || this._readonlyPermissions === true) {
294
+ return {
295
+ readonly: true,
296
+ forced: this._forceReadonly,
297
+ permissions: this._readonlyPermissions,
298
+ storageOnly,
299
+ };
300
+ }
301
+
302
+ return { readonly: this._readonlyPermissions };
303
+ }
304
+
305
+ private static detailsFromConnection(connection: IDocumentDeltaConnection): IConnectionDetails {
306
+ return {
307
+ claims: connection.claims,
308
+ clientId: connection.clientId,
309
+ existing: connection.existing,
310
+ checkpointSequenceNumber: connection.checkpointSequenceNumber,
311
+ get initialClients() {
312
+ return connection.initialClients;
313
+ },
314
+ mode: connection.mode,
315
+ serviceConfiguration: connection.serviceConfiguration,
316
+ version: connection.version,
317
+ };
318
+ }
319
+
320
+ constructor(
321
+ private readonly serviceProvider: () => IDocumentService | undefined,
322
+ private client: IClient,
323
+ reconnectAllowed: boolean,
324
+ private readonly logger: ITelemetryLogger,
325
+ private readonly props: IConnectionManagerFactoryArgs,
326
+ ) {
327
+ this.clientDetails = this.client.details;
328
+ this.defaultReconnectionMode = this.client.mode;
329
+ this._reconnectMode = reconnectAllowed ? ReconnectMode.Enabled : ReconnectMode.Never;
330
+
331
+ // Outbound message queue. The outbound queue is represented as a queue of an array of ops. Ops contained
332
+ // within an array *must* fit within the maxMessageSize and are guaranteed to be ordered sequentially.
333
+ this._outbound = new DeltaQueue<IDocumentMessage[]>((messages) => {
334
+ if (this.connection === undefined) {
335
+ throw new Error("Attempted to submit an outbound message without connection");
336
+ }
337
+ this.connection.submit(messages);
338
+ });
339
+
340
+ this._outbound.on("error", (error) => {
341
+ this.props.closeHandler(normalizeError(error));
342
+ });
343
+ }
344
+
345
+ public dispose(error?: ICriticalContainerError, switchToReadonly: boolean = true) {
346
+ if (this._disposed) {
347
+ return;
348
+ }
349
+ this._disposed = true;
350
+
351
+ this.pendingConnection = undefined;
352
+
353
+ // Ensure that things like triggerConnect() will short circuit
354
+ this._reconnectMode = ReconnectMode.Never;
355
+
356
+ this._outbound.clear();
357
+
358
+ const disconnectReason = "Closing DeltaManager";
359
+
360
+ // This raises "disconnect" event if we have active connection.
361
+ this.disconnectFromDeltaStream(disconnectReason);
362
+
363
+ if (switchToReadonly) {
364
+ // Notify everyone we are in read-only state.
365
+ // Useful for data stores in case we hit some critical error,
366
+ // to switch to a mode where user edits are not accepted
367
+ this.set_readonlyPermissions(true);
368
+ }
369
+ }
370
+
371
+ /**
372
+ * Enables or disables automatic reconnecting.
373
+ * Will throw an error if reconnectMode set to Never.
374
+ */
375
+ public setAutoReconnect(mode: ReconnectMode): void {
376
+ assert(
377
+ mode !== ReconnectMode.Never && this._reconnectMode !== ReconnectMode.Never,
378
+ 0x278 /* "API is not supported for non-connecting or closed container" */,
379
+ );
380
+
381
+ this._reconnectMode = mode;
382
+
383
+ if (mode !== ReconnectMode.Enabled) {
384
+ // immediately disconnect - do not rely on service eventually dropping connection.
385
+ this.disconnectFromDeltaStream("setAutoReconnect");
386
+ }
387
+ }
388
+
389
+ /**
390
+ * Sends signal to runtime (and data stores) to be read-only.
391
+ * Hosts may have read only views, indicating to data stores that no edits are allowed.
392
+ * This is independent from this._readonlyPermissions (permissions) and this.connectionMode
393
+ * (server can return "write" mode even when asked for "read")
394
+ * Leveraging same "readonly" event as runtime & data stores should behave the same in such case
395
+ * as in read-only permissions.
396
+ * But this.active can be used by some DDSes to figure out if ops can be sent
397
+ * (for example, read-only view still participates in code proposals / upgrades decisions)
398
+ *
399
+ * Forcing Readonly does not prevent DDS from generating ops. It is up to user code to honour
400
+ * the readonly flag. If ops are generated, they will accumulate locally and not be sent. If
401
+ * there are pending in the outbound queue, it will stop sending until force readonly is
402
+ * cleared.
403
+ *
404
+ * @param readonly - set or clear force readonly.
405
+ */
406
+ public forceReadonly(readonly: boolean) {
407
+ if (readonly !== this._forceReadonly) {
408
+ this.logger.sendTelemetryEvent({
409
+ eventName: "ForceReadOnly",
410
+ value: readonly,
411
+ });
412
+ }
413
+ const oldValue = this.readonly;
414
+ this._forceReadonly = readonly;
415
+
416
+ if (oldValue !== this.readonly) {
417
+ if (this._reconnectMode === ReconnectMode.Never) {
418
+ throw new UsageError("API is not supported for non-connecting or closed container");
419
+ }
420
+ let reconnect = false;
421
+ if (this.readonly === true) {
422
+ // If we switch to readonly while connected, we should disconnect first
423
+ // See comment in the "readonly" event handler to deltaManager set up by
424
+ // the ContainerRuntime constructor
425
+
426
+ if (this.shouldJoinWrite()) {
427
+ // If we have pending changes, then we will never send them - it smells like
428
+ // host logic error.
429
+ this.logger.sendErrorEvent({ eventName: "ForceReadonlyPendingChanged" });
430
+ }
431
+
432
+ reconnect = this.disconnectFromDeltaStream("Force readonly");
433
+ }
434
+ this.props.readonlyChangeHandler(this.readonly);
435
+ if (reconnect) {
436
+ // reconnect if we disconnected from before.
437
+ this.triggerConnect("read");
438
+ }
439
+ }
440
+ }
441
+
442
+ private set_readonlyPermissions(readonly: boolean) {
443
+ const oldValue = this.readonly;
444
+ this._readonlyPermissions = readonly;
445
+ if (oldValue !== this.readonly) {
446
+ this.props.readonlyChangeHandler(this.readonly);
447
+ }
448
+ }
449
+
450
+ public connect(connectionMode?: ConnectionMode) {
451
+ this.connectCore(connectionMode).catch((error) => {
452
+ const normalizedError = normalizeError(error, { props: fatalConnectErrorProp });
453
+ this.props.closeHandler(normalizedError);
454
+ });
455
+ }
456
+
457
+ private async connectCore(connectionMode?: ConnectionMode): Promise<void> {
458
+ assert(!this._disposed, 0x26a /* "not closed" */);
459
+
460
+ if (this.connection !== undefined) {
461
+ return; // Connection attempt already completed successfully
462
+ }
463
+
464
+ let pendingConnectionMode;
465
+ if (this.pendingConnection !== undefined) {
466
+ pendingConnectionMode = this.pendingConnection.connectionMode;
467
+ this.cancelConnection(); // Throw out in-progress connection attempt in favor of new attempt
468
+ assert(
469
+ this.pendingConnection === undefined,
470
+ 0x344 /* this.pendingConnection should be undefined */,
471
+ );
472
+ }
473
+ // If there is no specified ConnectionMode, try the previous mode, if there is no previous mode use default
474
+ let requestedMode = connectionMode ?? pendingConnectionMode ?? this.defaultReconnectionMode;
475
+
476
+ // if we have any non-acked ops from last connection, reconnect as "write".
477
+ // without that we would connect in view-only mode, which will result in immediate
478
+ // firing of "connected" event from Container and switch of current clientId (as tracked
479
+ // by all DDSes). This will make it impossible to figure out if ops actually made it through,
480
+ // so DDSes will immediately resubmit all pending ops, and some of them will be duplicates, corrupting document
481
+ if (this.shouldJoinWrite()) {
482
+ requestedMode = "write";
483
+ }
484
+
485
+ const docService = this.serviceProvider();
486
+ assert(docService !== undefined, 0x2a7 /* "Container is not attached" */);
487
+
488
+ let connection: IDocumentDeltaConnection | undefined;
489
+
490
+ if (docService.policies?.storageOnly === true) {
491
+ connection = new NoDeltaStream();
492
+ this.setupNewSuccessfulConnection(connection, "read");
493
+ assert(this.pendingConnection === undefined, 0x2b3 /* "logic error" */);
494
+ return;
495
+ }
496
+
497
+ let delayMs = InitialReconnectDelayInMs;
498
+ let connectRepeatCount = 0;
499
+ const connectStartTime = performance.now();
500
+ let lastError: any;
501
+
502
+ const abortController = new AbortController();
503
+ const abortSignal = abortController.signal;
504
+ this.pendingConnection = {
505
+ abort: () => {
506
+ abortController.abort();
507
+ },
508
+ connectionMode: requestedMode,
509
+ };
510
+
511
+ // This loop will keep trying to connect until successful, with a delay between each iteration.
512
+ while (connection === undefined) {
513
+ if (this._disposed) {
514
+ throw new Error("Attempting to connect a closed DeltaManager");
515
+ }
516
+ if (abortSignal.aborted === true) {
517
+ this.logger.sendTelemetryEvent({
518
+ eventName: "ConnectionAttemptCancelled",
519
+ attempts: connectRepeatCount,
520
+ duration: TelemetryLogger.formatTick(performance.now() - connectStartTime),
521
+ connectionEstablished: false,
522
+ });
523
+ return;
524
+ }
525
+ connectRepeatCount++;
526
+
527
+ try {
528
+ this.client.mode = requestedMode;
529
+ connection = await docService.connectToDeltaStream({
530
+ ...this.client,
531
+ mode: requestedMode,
532
+ });
533
+
534
+ if (connection.disposed) {
535
+ // Nobody observed this connection, so drop it on the floor and retry.
536
+ this.logger.sendTelemetryEvent({ eventName: "ReceivedClosedConnection" });
537
+ connection = undefined;
538
+ }
539
+ } catch (origError: any) {
540
+ if (
541
+ typeof origError === "object" &&
542
+ origError !== null &&
543
+ origError?.errorType === DeltaStreamConnectionForbiddenError.errorType
544
+ ) {
545
+ connection = new NoDeltaStream();
546
+ requestedMode = "read";
547
+ break;
548
+ }
549
+
550
+ // Socket.io error when we connect to wrong socket, or hit some multiplexing bug
551
+ if (!canRetryOnError(origError)) {
552
+ const error = normalizeError(origError, { props: fatalConnectErrorProp });
553
+ this.props.closeHandler(error);
554
+ throw error;
555
+ }
556
+
557
+ // Since the error is retryable this will not log to the error table
558
+ logNetworkFailure(
559
+ this.logger,
560
+ {
561
+ attempts: connectRepeatCount,
562
+ delay: delayMs, // milliseconds
563
+ eventName: "DeltaConnectionFailureToConnect",
564
+ duration: TelemetryLogger.formatTick(performance.now() - connectStartTime),
565
+ },
566
+ origError,
567
+ );
568
+
569
+ lastError = origError;
570
+
571
+ const retryDelayFromError = getRetryDelayFromError(origError);
572
+ delayMs = retryDelayFromError ?? Math.min(delayMs * 2, MaxReconnectDelayInMs);
573
+
574
+ if (retryDelayFromError !== undefined) {
575
+ this.props.reconnectionDelayHandler(retryDelayFromError, origError);
576
+ }
577
+ await waitForConnectedState(delayMs);
578
+ }
579
+ }
580
+
581
+ // If we retried more than once, log an event about how long it took (this will not log to error table)
582
+ if (connectRepeatCount > 1) {
583
+ logNetworkFailure(
584
+ this.logger,
585
+ {
586
+ eventName: "MultipleDeltaConnectionFailures",
587
+ attempts: connectRepeatCount,
588
+ duration: TelemetryLogger.formatTick(performance.now() - connectStartTime),
589
+ },
590
+ lastError,
591
+ );
592
+ }
593
+
594
+ // Check for abort signal after while loop as well
595
+ if (abortSignal.aborted === true) {
596
+ connection.dispose();
597
+ this.logger.sendTelemetryEvent({
598
+ eventName: "ConnectionAttemptCancelled",
599
+ attempts: connectRepeatCount,
600
+ duration: TelemetryLogger.formatTick(performance.now() - connectStartTime),
601
+ connectionEstablished: true,
602
+ });
603
+ return;
604
+ }
605
+
606
+ this.setupNewSuccessfulConnection(connection, requestedMode);
607
+ }
608
+
609
+ /**
610
+ * Start the connection. Any error should result in container being closed.
611
+ * And report the error if it escapes for any reason.
612
+ * @param args - The connection arguments
613
+ */
614
+ private triggerConnect(connectionMode: ConnectionMode) {
615
+ // reconnect() has async await of waitForConnectedState(), and that causes potential race conditions
616
+ // where we might already have a connection. If it were to happen, it's possible that we will connect
617
+ // with different mode to `connectionMode`. Glancing through the caller chains, it looks like code should be
618
+ // fine (if needed, reconnect flow will get triggered again). Places where new mode matters should encode it
619
+ // directly in connectCore - see this.shouldJoinWrite() test as an example.
620
+ // assert(this.connection === undefined, 0x239 /* "called only in disconnected state" */);
621
+
622
+ if (this.reconnectMode !== ReconnectMode.Enabled) {
623
+ return;
624
+ }
625
+ this.connect(connectionMode);
626
+ }
627
+
628
+ /**
629
+ * Disconnect the current connection.
630
+ * @param reason - Text description of disconnect reason to emit with disconnect event
631
+ * @returns A boolean that indicates if there was an existing connection (or pending connection) to disconnect
632
+ */
633
+ private disconnectFromDeltaStream(reason: string): boolean {
634
+ this.pendingReconnect = false;
635
+
636
+ if (this.connection === undefined) {
637
+ if (this.pendingConnection !== undefined) {
638
+ this.cancelConnection();
639
+ return true;
640
+ }
641
+ return false;
642
+ }
643
+
644
+ assert(
645
+ this.pendingConnection === undefined,
646
+ 0x27b /* "reentrancy may result in incorrect behavior" */,
647
+ );
648
+
649
+ const connection = this.connection;
650
+ // Avoid any re-entrancy - clear object reference
651
+ this.connection = undefined;
652
+
653
+ // Remove listeners first so we don't try to retrigger this flow accidentally through reconnectOnError
654
+ connection.off("op", this.opHandler);
655
+ connection.off("signal", this.props.signalHandler);
656
+ connection.off("nack", this.nackHandler);
657
+ connection.off("disconnect", this.disconnectHandlerInternal);
658
+ connection.off("error", this.errorHandler);
659
+ connection.off("pong", this.props.pongHandler);
660
+
661
+ // eslint-disable-next-line @typescript-eslint/no-floating-promises
662
+ this._outbound.pause();
663
+ this._outbound.clear();
664
+ this.props.disconnectHandler(reason);
665
+
666
+ connection.dispose();
667
+
668
+ this._connectionVerboseProps = {};
669
+
670
+ return true;
671
+ }
672
+
673
+ /**
674
+ * Cancel in-progress connection attempt.
675
+ */
676
+ private cancelConnection() {
677
+ assert(
678
+ this.pendingConnection !== undefined,
679
+ 0x345 /* this.pendingConnection is undefined when trying to cancel */,
680
+ );
681
+ this.pendingConnection.abort();
682
+ this.pendingConnection = undefined;
683
+ this.logger.sendTelemetryEvent({ eventName: "ConnectionCancelReceived" });
684
+ }
685
+
686
+ /**
687
+ * Once we've successfully gotten a connection, we need to set up state, attach event listeners, and process
688
+ * initial messages.
689
+ * @param connection - The newly established connection
690
+ */
691
+ private setupNewSuccessfulConnection(
692
+ connection: IDocumentDeltaConnection,
693
+ requestedMode: ConnectionMode,
694
+ ) {
695
+ // Old connection should have been cleaned up before establishing a new one
696
+ assert(
697
+ this.connection === undefined,
698
+ 0x0e6 /* "old connection exists on new connection setup" */,
699
+ );
700
+ assert(
701
+ !connection.disposed,
702
+ 0x28a /* "can't be disposed - Callers need to ensure that!" */,
703
+ );
704
+
705
+ this.pendingConnection = undefined;
706
+
707
+ this.connection = connection;
708
+
709
+ // Does information in scopes & mode matches?
710
+ // If we asked for "write" and got "read", then file is read-only
711
+ // But if we ask read, server can still give us write.
712
+ const readonly = !connection.claims.scopes.includes(ScopeType.DocWrite);
713
+
714
+ if (connection.mode !== requestedMode) {
715
+ this.logger.sendTelemetryEvent({
716
+ eventName: "ConnectionModeMismatch",
717
+ requestedMode,
718
+ mode: connection.mode,
719
+ });
720
+ }
721
+ // This connection mode validation logic is moving to the driver layer in 0.44. These two asserts can be
722
+ // removed after those packages have released and become ubiquitous.
723
+ assert(
724
+ requestedMode === "read" || readonly === (this.connectionMode === "read"),
725
+ 0x0e7 /* "claims/connectionMode mismatch" */,
726
+ );
727
+ assert(
728
+ !readonly || this.connectionMode === "read",
729
+ 0x0e8 /* "readonly perf with write connection" */,
730
+ );
731
+
732
+ this.set_readonlyPermissions(readonly);
733
+
734
+ if (this._disposed) {
735
+ // Raise proper events, Log telemetry event and close connection.
736
+ this.disconnectFromDeltaStream("ConnectionManager already closed");
737
+ return;
738
+ }
739
+
740
+ this._outbound.resume();
741
+
742
+ connection.on("op", this.opHandler);
743
+ connection.on("signal", this.props.signalHandler);
744
+ connection.on("nack", this.nackHandler);
745
+ connection.on("disconnect", this.disconnectHandlerInternal);
746
+ connection.on("error", this.errorHandler);
747
+ connection.on("pong", this.props.pongHandler);
748
+
749
+ // Initial messages are always sorted. However, due to early op handler installed by drivers and appending those
750
+ // ops to initialMessages, resulting set is no longer sorted, which would result in client hitting storage to
751
+ // fill in gap. We will recover by cancelling this request once we process remaining ops, but it's a waste that
752
+ // we could avoid
753
+ const initialMessages = connection.initialMessages.sort(
754
+ (a, b) => a.sequenceNumber - b.sequenceNumber,
755
+ );
756
+
757
+ // Some storages may provide checkpointSequenceNumber to identify how far client is behind.
758
+ let checkpointSequenceNumber = connection.checkpointSequenceNumber;
759
+
760
+ this._connectionVerboseProps = {
761
+ clientId: connection.clientId,
762
+ mode: connection.mode,
763
+ };
764
+
765
+ // reset connection props
766
+ this._connectionProps = {};
767
+
768
+ if (connection.relayServiceAgent !== undefined) {
769
+ this._connectionVerboseProps.relayServiceAgent = connection.relayServiceAgent;
770
+ this._connectionProps.relayServiceAgent = connection.relayServiceAgent;
771
+ }
772
+ this._connectionProps.socketDocumentId = connection.claims.documentId;
773
+ this._connectionProps.connectionMode = connection.mode;
774
+
775
+ let last = -1;
776
+ if (initialMessages.length !== 0) {
777
+ this._connectionVerboseProps.connectionInitialOpsFrom =
778
+ initialMessages[0].sequenceNumber;
779
+ last = initialMessages[initialMessages.length - 1].sequenceNumber;
780
+ this._connectionVerboseProps.connectionInitialOpsTo = last + 1;
781
+ // Update knowledge of how far we are behind, before raising "connect" event
782
+ // This is duplication of what incomingOpHandler() does, but we have to raise event before we get there,
783
+ // so duplicating update logic here as well.
784
+ if (checkpointSequenceNumber === undefined || checkpointSequenceNumber < last) {
785
+ checkpointSequenceNumber = last;
786
+ }
787
+ }
788
+
789
+ this.props.incomingOpHandler(
790
+ initialMessages,
791
+ this.connectFirstConnection ? "InitialOps" : "ReconnectOps",
792
+ );
793
+
794
+ const details = ConnectionManager.detailsFromConnection(connection);
795
+ details.checkpointSequenceNumber = checkpointSequenceNumber;
796
+ this.props.connectHandler(details);
797
+
798
+ this.connectFirstConnection = false;
799
+
800
+ // Synthesize clear & join signals out of initialClients state.
801
+ // This allows us to have single way to process signals, and makes it simpler to initialize
802
+ // protocol in Container.
803
+ const clearSignal: ISignalMessage = {
804
+ clientId: null, // system message
805
+ content: JSON.stringify({
806
+ type: SignalType.Clear,
807
+ }),
808
+ };
809
+ this.props.signalHandler(clearSignal);
810
+
811
+ for (const priorClient of connection.initialClients ?? []) {
812
+ const joinSignal: ISignalMessage = {
813
+ clientId: null, // system signal
814
+ content: JSON.stringify({
815
+ type: SignalType.ClientJoin,
816
+ content: priorClient, // ISignalClient
817
+ }),
818
+ };
819
+ this.props.signalHandler(joinSignal);
820
+ }
821
+
822
+ // Unfortunately, there is no defined order between initialSignals (including join & leave signals)
823
+ // and connection.initialClients. In practice, connection.initialSignals quite often contains join signal
824
+ // for "self" and connection.initialClients does not contain "self", so we have to process them after
825
+ // "clear" signal above.
826
+ if (connection.initialSignals !== undefined) {
827
+ for (const signal of connection.initialSignals) {
828
+ this.props.signalHandler(signal);
829
+ }
830
+ }
831
+ }
832
+
833
+ /**
834
+ * Disconnect the current connection and reconnect. Closes the container if it fails.
835
+ * @param connection - The connection that wants to reconnect - no-op if it's different from this.connection
836
+ * @param requestedMode - Read or write
837
+ * @param error - Error reconnect information including whether or not to reconnect
838
+ * @returns A promise that resolves when the connection is reestablished or we stop trying
839
+ */
840
+ private reconnectOnError(requestedMode: ConnectionMode, error: IAnyDriverError) {
841
+ this.reconnect(requestedMode, error.message, error).catch(this.props.closeHandler);
842
+ }
843
+
844
+ /**
845
+ * Disconnect the current connection and reconnect.
846
+ * @param connection - The connection that wants to reconnect - no-op if it's different from this.connection
847
+ * @param requestedMode - Read or write
848
+ * @param error - Error reconnect information including whether or not to reconnect
849
+ * @returns A promise that resolves when the connection is reestablished or we stop trying
850
+ */
851
+ private async reconnect(
852
+ requestedMode: ConnectionMode,
853
+ disconnectMessage: string,
854
+ error?: IAnyDriverError,
855
+ ) {
856
+ // We quite often get protocol errors before / after observing nack/disconnect
857
+ // we do not want to run through same sequence twice.
858
+ // If we're already disconnected/disconnecting it's not appropriate to call this again.
859
+ assert(this.connection !== undefined, 0x0eb /* "Missing connection for reconnect" */);
860
+
861
+ this.disconnectFromDeltaStream(disconnectMessage);
862
+
863
+ // We will always trigger reconnect, even if canRetry is false.
864
+ // Any truly fatal error state will result in container close upon attempted reconnect,
865
+ // which is a preferable to closing abruptly when a live connection fails.
866
+ if (error !== undefined && !error.canRetry) {
867
+ this.logger.sendTelemetryEvent(
868
+ {
869
+ eventName: "reconnectingDespiteFatalError",
870
+ reconnectMode: this.reconnectMode,
871
+ },
872
+ error,
873
+ );
874
+ }
875
+
876
+ if (this.reconnectMode === ReconnectMode.Never) {
877
+ // Do not raise container error if we are closing just because we lost connection.
878
+ // Those errors (like IdleDisconnect) would show up in telemetry dashboards and
879
+ // are very misleading, as first initial reaction - some logic is broken.
880
+ this.props.closeHandler();
881
+ }
882
+
883
+ // If closed then we can't reconnect
884
+ if (this._disposed || this.reconnectMode !== ReconnectMode.Enabled) {
885
+ return;
886
+ }
887
+
888
+ const delayMs = getRetryDelayFromError(error);
889
+ if (error !== undefined && delayMs !== undefined) {
890
+ this.props.reconnectionDelayHandler(delayMs, error);
891
+ await waitForConnectedState(delayMs);
892
+ }
893
+
894
+ this.triggerConnect(requestedMode);
895
+ }
896
+
897
+ public prepareMessageToSend(
898
+ message: Omit<IDocumentMessage, "clientSequenceNumber">,
899
+ ): IDocumentMessage | undefined {
900
+ if (this.readonly === true) {
901
+ assert(
902
+ this.readOnlyInfo.readonly === true,
903
+ 0x1f0 /* "Unexpected mismatch in readonly" */,
904
+ );
905
+ const error = new GenericError("deltaManagerReadonlySubmit", undefined /* error */, {
906
+ readonly: this.readOnlyInfo.readonly,
907
+ forcedReadonly: this.readOnlyInfo.forced,
908
+ readonlyPermissions: this.readOnlyInfo.permissions,
909
+ storageOnly: this.readOnlyInfo.storageOnly,
910
+ });
911
+ this.props.closeHandler(error);
912
+ return undefined;
913
+ }
914
+
915
+ // reset clientSequenceNumber if we are using new clientId.
916
+ // we keep info about old connection as long as possible to be able to account for all non-acked ops
917
+ // that we pick up on next connection.
918
+ assert(!!this.connection, 0x0e4 /* "Lost old connection!" */);
919
+ if (this.lastSubmittedClientId !== this.connection?.clientId) {
920
+ this.lastSubmittedClientId = this.connection?.clientId;
921
+ this.clientSequenceNumber = 0;
922
+ this.clientSequenceNumberObserved = 0;
923
+ }
924
+
925
+ if (!isRuntimeMessage(message)) {
926
+ this.localOpsToIgnore++;
927
+ } else {
928
+ this.localOpsToIgnore = 0;
929
+ }
930
+
931
+ return {
932
+ ...message,
933
+ clientSequenceNumber: ++this.clientSequenceNumber,
934
+ };
935
+ }
936
+
937
+ public submitSignal(content: any) {
938
+ if (this.connection !== undefined) {
939
+ this.connection.submitSignal(content);
940
+ } else {
941
+ this.logger.sendErrorEvent({ eventName: "submitSignalDisconnected" });
942
+ }
943
+ }
944
+
945
+ public sendMessages(messages: IDocumentMessage[]) {
946
+ assert(this.connected, 0x2b4 /* "not connected on sending ops!" */);
947
+ // If connection is "read" or implicit "read" (got leave op for "write" connection),
948
+ // then op can't make it through - we will get a nack if op is sent.
949
+ // We can short-circuit this process.
950
+ // Note that we also want nacks to be rare and be treated as catastrophic failures.
951
+ // Be careful with reentrancy though - disconnected event should not be be raised in the
952
+ // middle of the current workflow, but rather on clean stack!
953
+ if (this.connectionMode === "read") {
954
+ if (!this.pendingReconnect) {
955
+ this.pendingReconnect = true;
956
+ Promise.resolve()
957
+ .then(async () => {
958
+ if (this.pendingReconnect) {
959
+ // still valid?
960
+ await this.reconnect(
961
+ "write", // connectionMode
962
+ "Switch to write", // message
963
+ );
964
+ }
965
+ })
966
+ .catch(() => {});
967
+ }
968
+ return;
969
+ }
970
+
971
+ assert(!this.pendingReconnect, 0x2b5 /* "logic error" */);
972
+
973
+ this._outbound.push(messages);
974
+ }
975
+
976
+ public beforeProcessingIncomingOp(message: ISequencedDocumentMessage) {
977
+ // if we have connection, and message is local, then we better treat is as local!
978
+ assert(
979
+ this.clientId !== message.clientId || this.lastSubmittedClientId === message.clientId,
980
+ 0x0ee /* "Not accounting local messages correctly" */,
981
+ );
982
+
983
+ if (
984
+ this.lastSubmittedClientId !== undefined &&
985
+ this.lastSubmittedClientId === message.clientId
986
+ ) {
987
+ const clientSequenceNumber = message.clientSequenceNumber;
988
+
989
+ assert(
990
+ this.clientSequenceNumberObserved < clientSequenceNumber,
991
+ 0x0ef /* "client seq# not growing" */,
992
+ );
993
+ assert(
994
+ clientSequenceNumber <= this.clientSequenceNumber,
995
+ 0x0f0 /* "Incoming local client seq# > generated by this client" */,
996
+ );
997
+
998
+ this.clientSequenceNumberObserved = clientSequenceNumber;
999
+ }
1000
+
1001
+ if (message.type === MessageType.ClientLeave) {
1002
+ const systemLeaveMessage = message as ISequencedDocumentSystemMessage;
1003
+ const clientId = JSON.parse(systemLeaveMessage.data) as string;
1004
+ if (clientId === this.clientId) {
1005
+ // We have been kicked out from quorum
1006
+ this.logger.sendPerformanceEvent({ eventName: "ReadConnectionTransition" });
1007
+
1008
+ // Please see #8483 for more details on why maintaining connection further as is would not work.
1009
+ // Short story - connection properties are immutable, and many processes (consensus DDSes, summarizer)
1010
+ // assume that connection stays "write" connection until disconnect, and act accordingly, which may
1011
+ // not work well with de-facto "read" connection we are in after receiving own leave op on timeout.
1012
+ // Clients need to be able to transition to "read" state after some time of inactivity!
1013
+ // Note - this may close container!
1014
+ this.reconnect(
1015
+ "read", // connectionMode
1016
+ "Switch to read", // message
1017
+ ).catch((error) => {
1018
+ this.logger.sendErrorEvent({ eventName: "SwitchToReadConnection" }, error);
1019
+ });
1020
+ }
1021
+ }
1022
+ }
1023
+
1024
+ private readonly opHandler = (documentId: string, messagesArg: ISequencedDocumentMessage[]) => {
1025
+ const messages = Array.isArray(messagesArg) ? messagesArg : [messagesArg];
1026
+ this.props.incomingOpHandler(messages, "opHandler");
1027
+ };
1028
+
1029
+ // Always connect in write mode after getting nacked.
1030
+ private readonly nackHandler = (documentId: string, messages: INack[]) => {
1031
+ const message = messages[0];
1032
+ if (this._readonlyPermissions === true) {
1033
+ this.props.closeHandler(
1034
+ createWriteError("writeOnReadOnlyDocument", { driverVersion: undefined }),
1035
+ );
1036
+ return;
1037
+ }
1038
+
1039
+ const reconnectInfo = getNackReconnectInfo(message.content);
1040
+
1041
+ // If the nack indicates we cannot retry, then close the container outright
1042
+ if (!reconnectInfo.canRetry) {
1043
+ this.props.closeHandler(reconnectInfo);
1044
+ return;
1045
+ }
1046
+
1047
+ this.reconnectOnError("write", reconnectInfo);
1048
+ };
1049
+
1050
+ // Connection mode is always read on disconnect/error unless the system mode was write.
1051
+ private readonly disconnectHandlerInternal = (disconnectReason: IAnyDriverError) => {
1052
+ // Note: we might get multiple disconnect calls on same socket, as early disconnect notification
1053
+ // ("server_disconnect", ODSP-specific) is mapped to "disconnect"
1054
+ this.reconnectOnError(this.defaultReconnectionMode, disconnectReason);
1055
+ };
1056
+
1057
+ private readonly errorHandler = (error: IAnyDriverError) => {
1058
+ this.reconnectOnError(this.defaultReconnectionMode, error);
1059
+ };
998
1060
  }