@fluidframework/container-loader 0.53.0-46105 → 0.54.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 (59) 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/container.d.ts +2 -1
  6. package/dist/container.d.ts.map +1 -1
  7. package/dist/container.js +25 -28
  8. package/dist/container.js.map +1 -1
  9. package/dist/contracts.d.ts +112 -0
  10. package/dist/contracts.d.ts.map +1 -0
  11. package/dist/contracts.js +14 -0
  12. package/dist/contracts.js.map +1 -0
  13. package/dist/deltaManager.d.ts +26 -135
  14. package/dist/deltaManager.d.ts.map +1 -1
  15. package/dist/deltaManager.js +142 -768
  16. package/dist/deltaManager.js.map +1 -1
  17. package/dist/loader.d.ts +9 -4
  18. package/dist/loader.d.ts.map +1 -1
  19. package/dist/loader.js +5 -4
  20. package/dist/loader.js.map +1 -1
  21. package/dist/packageVersion.d.ts +1 -1
  22. package/dist/packageVersion.d.ts.map +1 -1
  23. package/dist/packageVersion.js +1 -1
  24. package/dist/packageVersion.js.map +1 -1
  25. package/dist/protocolTreeDocumentStorageService.d.ts +2 -2
  26. package/dist/protocolTreeDocumentStorageService.d.ts.map +1 -1
  27. package/lib/connectionManager.d.ts +153 -0
  28. package/lib/connectionManager.d.ts.map +1 -0
  29. package/lib/connectionManager.js +660 -0
  30. package/lib/connectionManager.js.map +1 -0
  31. package/lib/container.d.ts +2 -1
  32. package/lib/container.d.ts.map +1 -1
  33. package/lib/container.js +25 -28
  34. package/lib/container.js.map +1 -1
  35. package/lib/contracts.d.ts +112 -0
  36. package/lib/contracts.d.ts.map +1 -0
  37. package/lib/contracts.js +11 -0
  38. package/lib/contracts.js.map +1 -0
  39. package/lib/deltaManager.d.ts +26 -135
  40. package/lib/deltaManager.d.ts.map +1 -1
  41. package/lib/deltaManager.js +146 -772
  42. package/lib/deltaManager.js.map +1 -1
  43. package/lib/loader.d.ts +9 -4
  44. package/lib/loader.d.ts.map +1 -1
  45. package/lib/loader.js +6 -5
  46. package/lib/loader.js.map +1 -1
  47. package/lib/packageVersion.d.ts +1 -1
  48. package/lib/packageVersion.d.ts.map +1 -1
  49. package/lib/packageVersion.js +1 -1
  50. package/lib/packageVersion.js.map +1 -1
  51. package/lib/protocolTreeDocumentStorageService.d.ts +2 -2
  52. package/lib/protocolTreeDocumentStorageService.d.ts.map +1 -1
  53. package/package.json +9 -9
  54. package/src/connectionManager.ts +892 -0
  55. package/src/container.ts +39 -39
  56. package/src/contracts.ts +156 -0
  57. package/src/deltaManager.ts +181 -979
  58. package/src/loader.ts +31 -9
  59. package/src/packageVersion.ts +1 -1
@@ -4,87 +4,24 @@
4
4
  */
5
5
  import { default as AbortController } from "abort-controller";
6
6
  import { v4 as uuid } from "uuid";
7
- import { assert, Deferred, performance, TypedEventEmitter } from "@fluidframework/common-utils";
8
- import { TelemetryLogger, safeRaiseEvent, logIfFalse, normalizeError, wrapError, } from "@fluidframework/telemetry-utils";
7
+ import { assert, TypedEventEmitter } from "@fluidframework/common-utils";
8
+ import { normalizeError, logIfFalse, safeRaiseEvent, } from "@fluidframework/telemetry-utils";
9
9
  import { DriverErrorType, } from "@fluidframework/driver-definitions";
10
10
  import { isSystemMessage } from "@fluidframework/protocol-base";
11
- import { MessageType, ScopeType, } from "@fluidframework/protocol-definitions";
12
- import { canRetryOnError, createWriteError, createGenericNetworkError, getRetryDelayFromError, logNetworkFailure, waitForConnectedState, NonRetryableError, DeltaStreamConnectionForbiddenError, GenericNetworkError, } from "@fluidframework/driver-utils";
13
- import { ThrottlingWarning, CreateProcessingError, DataCorruptionError, GenericError, } from "@fluidframework/container-utils";
11
+ import { MessageType, } from "@fluidframework/protocol-definitions";
12
+ import { NonRetryableError, } from "@fluidframework/driver-utils";
13
+ import { ThrottlingWarning, CreateProcessingError, DataCorruptionError, } from "@fluidframework/container-utils";
14
14
  import { DeltaQueue } from "./deltaQueue";
15
- const MaxReconnectDelayInMs = 8000;
16
- const InitialReconnectDelayInMs = 1000;
17
- const DefaultChunkSize = 16 * 1024;
18
- function getNackReconnectInfo(nackContent) {
19
- const message = `Nack (${nackContent.type}): ${nackContent.message}`;
20
- const canRetry = nackContent.code !== 403;
21
- const retryAfterMs = nackContent.retryAfter !== undefined ? nackContent.retryAfter * 1000 : undefined;
22
- return createGenericNetworkError(`nack [${nackContent.code}]`, message, canRetry, retryAfterMs, { statusCode: nackContent.code });
23
- }
24
- const createReconnectError = (fluidErrorCode, err) => wrapError(err, (errorMessage) => new GenericNetworkError(fluidErrorCode, errorMessage, true /* canRetry */));
25
- const fatalConnectErrorProp = { fatalConnectError: true };
26
- export var ReconnectMode;
27
- (function (ReconnectMode) {
28
- ReconnectMode["Never"] = "Never";
29
- ReconnectMode["Disabled"] = "Disabled";
30
- ReconnectMode["Enabled"] = "Enabled";
31
- })(ReconnectMode || (ReconnectMode = {}));
32
- /**
33
- * Implementation of IDocumentDeltaConnection that does not support submitting
34
- * or receiving ops. Used in storage-only mode.
35
- */
36
- class NoDeltaStream extends TypedEventEmitter {
37
- constructor() {
38
- super(...arguments);
39
- this.clientId = "storage-only client";
40
- this.claims = {
41
- scopes: [ScopeType.DocRead],
42
- };
43
- this.mode = "read";
44
- this.existing = true;
45
- this.maxMessageSize = 0;
46
- this.version = "";
47
- this.initialMessages = [];
48
- this.initialSignals = [];
49
- this.initialClients = [];
50
- this.serviceConfiguration = {
51
- maxMessageSize: 0,
52
- blockSize: 0,
53
- summary: undefined,
54
- };
55
- this.checkpointSequenceNumber = undefined;
56
- this._disposed = false;
57
- }
58
- submit(messages) {
59
- this.emit("nack", this.clientId, messages.map((operation) => {
60
- return {
61
- operation,
62
- content: { message: "Cannot submit with storage-only connection", code: 403 },
63
- };
64
- }));
65
- }
66
- submitSignal(message) {
67
- this.emit("nack", this.clientId, {
68
- operation: message,
69
- content: { message: "Cannot submit signal with storage-only connection", code: 403 },
70
- });
71
- }
72
- get disposed() { return this._disposed; }
73
- dispose() { this._disposed = true; }
74
- }
75
15
  /**
76
16
  * Manages the flow of both inbound and outbound messages. This class ensures that shared objects receive delta
77
17
  * messages in order regardless of possible network conditions or timings causing out of order delivery.
78
18
  */
79
19
  export class DeltaManager extends TypedEventEmitter {
80
- constructor(serviceProvider, client, logger, reconnectAllowed, _active) {
20
+ constructor(serviceProvider, logger, _active, createConnectionManager) {
81
21
  super();
82
22
  this.serviceProvider = serviceProvider;
83
- this.client = client;
84
23
  this.logger = logger;
85
24
  this._active = _active;
86
- // tracks host requiring read-only mode.
87
- this._forceReadonly = false;
88
25
  this.pending = [];
89
26
  // The minimum sequence number and last sequence number received from the server
90
27
  this.minSequenceNumber = 0;
@@ -101,82 +38,30 @@ export class DeltaManager extends TypedEventEmitter {
101
38
  this.baseTerm = 0;
102
39
  // The sequence number we initially loaded from
103
40
  this.initSequenceNumber = 0;
104
- this.clientSequenceNumber = 0;
105
- this.clientSequenceNumberObserved = 0;
106
- // Counts the number of noops sent by the client which may not be acked.
107
- this.trailingNoopCount = 0;
108
41
  this.closed = false;
109
- this.deltaStreamDelayId = uuid();
110
- this.deltaStorageDelayId = uuid();
111
- this.messageBuffer = [];
112
- this.connectFirstConnection = true;
113
42
  this.throttlingIdSet = new Set();
114
43
  this.timeTillThrottling = 0;
115
- this.connectionStateProps = {};
116
- // True if current connection has checkpoint information
117
- // I.e. we know how far behind the client was at the time of establishing connection
118
- this._hasCheckpointSequenceNumber = false;
119
44
  this.closeAbortController = new AbortController();
120
- // True if there is pending (async) reconnection from "read" to "write"
121
- this.pendingReconnect = false;
122
- // downgrade "write" connection to "read"
123
- this.downgradedConnection = false;
124
- this.opHandler = (documentId, messagesArg) => {
125
- const messages = Array.isArray(messagesArg) ? messagesArg : [messagesArg];
126
- this.enqueueMessages(messages, "opHandler");
127
- };
128
- this.signalHandler = (message) => {
129
- this._inboundSignal.push(message);
130
- };
131
- // Always connect in write mode after getting nacked.
132
- this.nackHandler = (documentId, messages) => {
133
- const message = messages[0];
134
- // TODO: we should remove this check when service updates?
135
- // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions
136
- if (this._readonlyPermissions) {
137
- this.close(createWriteError("writeOnReadOnlyDocument"));
138
- }
139
- // check message.content for Back-compat with old service.
140
- const reconnectInfo = message.content !== undefined
141
- ? getNackReconnectInfo(message.content) :
142
- createGenericNetworkError("nackReasonUnknown", undefined, true);
143
- // eslint-disable-next-line @typescript-eslint/no-floating-promises
144
- this.reconnectOnError("write", reconnectInfo);
145
- };
146
- // Connection mode is always read on disconnect/error unless the system mode was write.
147
- this.disconnectHandler = (disconnectReason) => {
148
- // Note: we might get multiple disconnect calls on same socket, as early disconnect notification
149
- // ("server_disconnect", ODSP-specific) is mapped to "disconnect"
150
- // eslint-disable-next-line @typescript-eslint/no-floating-promises
151
- this.reconnectOnError(this.defaultReconnectionMode, createReconnectError("dmDocumentDeltaConnectionDisconnected", disconnectReason));
152
- };
153
- this.errorHandler = (error) => {
154
- // eslint-disable-next-line @typescript-eslint/no-floating-promises
155
- this.reconnectOnError(this.defaultReconnectionMode, createReconnectError("dmDocumentDeltaConnectionError", error));
156
- };
157
- this.pongHandler = (latency) => {
158
- this.emit("pong", latency);
45
+ this.deltaStorageDelayId = uuid();
46
+ this.deltaStreamDelayId = uuid();
47
+ this.messageBuffer = [];
48
+ const props = {
49
+ incomingOpHandler: (messages, reason) => this.enqueueMessages(messages, reason),
50
+ signalHandler: (message) => this._inboundSignal.push(message),
51
+ reconnectionDelayHandler: (delayMs, error) => this.emitDelayInfo(this.deltaStreamDelayId, delayMs, error),
52
+ closeHandler: (error) => this.close(error),
53
+ disconnectHandler: (reason) => this.disconnectHandler(reason),
54
+ connectHandler: (connection) => this.connectHandler(connection),
55
+ pongHandler: (latency) => this.emit("pong", latency),
56
+ readonlyChangeHandler: (readonly) => safeRaiseEvent(this, this.logger, "readonly", readonly),
159
57
  };
160
- this.clientDetails = this.client.details;
161
- this.defaultReconnectionMode = this.client.mode;
162
- this._reconnectMode = reconnectAllowed ? ReconnectMode.Enabled : ReconnectMode.Never;
58
+ this.connectionManager = createConnectionManager(props);
163
59
  this._inbound = new DeltaQueue((op) => {
164
60
  this.processInboundMessage(op);
165
61
  });
166
62
  this._inbound.on("error", (error) => {
167
63
  this.close(CreateProcessingError(error, "deltaManagerInboundErrorHandler", this.lastMessage));
168
64
  });
169
- // Outbound message queue. The outbound queue is represented as a queue of an array of ops. Ops contained
170
- // within an array *must* fit within the maxMessageSize and are guaranteed to be ordered sequentially.
171
- this._outbound = new DeltaQueue((messages) => {
172
- if (this.connection === undefined) {
173
- throw new Error("Attempted to submit an outbound message without connection");
174
- }
175
- this.connection.submit(messages);
176
- });
177
- this._outbound.on("error", (error) => {
178
- this.close(normalizeError(error));
179
- });
180
65
  // Inbound signal queue
181
66
  this._inboundSignal = new DeltaQueue((message) => {
182
67
  if (this.handler === undefined) {
@@ -197,21 +82,9 @@ export class DeltaManager extends TypedEventEmitter {
197
82
  get active() { return this._active(); }
198
83
  get disposed() { return this.closed; }
199
84
  get IDeltaSender() { return this; }
200
- /**
201
- * Tells if current connection has checkpoint information.
202
- * I.e. we know how far behind the client was at the time of establishing connection
203
- */
204
- get hasCheckpointSequenceNumber() {
205
- // Valid to be called only if we have active connection.
206
- assert(this.connection !== undefined, 0x0df /* "Missing active connection" */);
207
- return this._hasCheckpointSequenceNumber;
208
- }
209
85
  get inbound() {
210
86
  return this._inbound;
211
87
  }
212
- get outbound() {
213
- return this._outbound;
214
- }
215
88
  get inboundSignal() {
216
89
  return this._inboundSignal;
217
90
  }
@@ -233,39 +106,22 @@ export class DeltaManager extends TypedEventEmitter {
233
106
  get minimumSequenceNumber() {
234
107
  return this.minSequenceNumber;
235
108
  }
236
- get maxMessageSize() {
237
- var _a, _b, _c;
238
- 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;
239
- }
240
- get version() {
241
- if (this.connection === undefined) {
242
- throw new Error("Cannot check version without a connection");
243
- }
244
- return this.connection.version;
245
- }
246
- get serviceConfiguration() {
247
- var _a;
248
- return (_a = this.connection) === null || _a === void 0 ? void 0 : _a.serviceConfiguration;
249
- }
250
- get scopes() {
251
- var _a;
252
- return (_a = this.connection) === null || _a === void 0 ? void 0 : _a.claims.scopes;
253
- }
254
- get socketDocumentId() {
255
- var _a;
256
- return (_a = this.connection) === null || _a === void 0 ? void 0 : _a.claims.documentId;
257
- }
258
109
  /**
259
- * The current connection mode, initially read.
110
+ * Tells if current connection has checkpoint information.
111
+ * I.e. we know how far behind the client was at the time of establishing connection
260
112
  */
261
- get connectionMode() {
262
- var _a;
263
- 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?" */);
264
- if (this.connection === undefined) {
265
- return "read";
266
- }
267
- return this.connection.mode;
268
- }
113
+ get hasCheckpointSequenceNumber() {
114
+ // Valid to be called only if we have active connection.
115
+ assert(this.connectionManager.connected, 0x0df /* "Missing active connection" */);
116
+ return this._checkpointSequenceNumber !== undefined;
117
+ }
118
+ // Forwarding connection manager properties / IDeltaManager implementation
119
+ get maxMessageSize() { return this.connectionManager.maxMessageSize; }
120
+ get version() { return this.connectionManager.version; }
121
+ get serviceConfiguration() { return this.connectionManager.serviceConfiguration; }
122
+ get outbound() { return this.connectionManager.outbound; }
123
+ get readOnlyInfo() { return this.connectionManager.readOnlyInfo; }
124
+ get clientDetails() { return this.connectionManager.clientDetails; }
269
125
  /**
270
126
  * Tells if container is in read-only mode.
271
127
  * Data stores should listen for "readonly" notifications and disallow user
@@ -277,109 +133,50 @@ export class DeltaManager extends TypedEventEmitter {
277
133
  * @deprecated - use readOnlyInfo
278
134
  */
279
135
  get readonly() {
280
- if (this._forceReadonly) {
281
- return true;
282
- }
283
- return this._readonlyPermissions;
284
- }
285
- get readOnlyInfo() {
286
- const storageOnly = this.connection !== undefined && this.connection instanceof NoDeltaStream;
287
- if (storageOnly || this._forceReadonly || this._readonlyPermissions === true) {
288
- return {
289
- readonly: true,
290
- forced: this._forceReadonly,
291
- permissions: this._readonlyPermissions,
292
- storageOnly,
293
- };
294
- }
295
- return { readonly: this._readonlyPermissions };
296
- }
297
- /**
298
- * Automatic reconnecting enabled or disabled.
299
- * If set to Never, then reconnecting will never be allowed.
300
- */
301
- get reconnectMode() {
302
- return this._reconnectMode;
136
+ return this.readOnlyInfo.readonly;
303
137
  }
304
- shouldJoinWrite() {
305
- // We don't have to wait for ack for topmost NoOps. So subtract those.
306
- return this.clientSequenceNumberObserved < (this.clientSequenceNumber - this.trailingNoopCount);
307
- }
308
- /**
309
- * Returns set of props that can be logged in telemetry that provide some insights / statistics
310
- * about current or last connection (if there is no connection at the moment)
311
- */
312
- connectionProps() {
313
- const common = {
314
- sequenceNumber: this.lastSequenceNumber,
138
+ submit(type, contents, batch = false, metadata) {
139
+ // Start adding trace for the op.
140
+ const traces = [
141
+ {
142
+ action: "start",
143
+ service: "client",
144
+ timestamp: Date.now(),
145
+ }
146
+ ];
147
+ const messagePartial = {
148
+ contents: JSON.stringify(contents),
149
+ metadata,
150
+ referenceSequenceNumber: this.lastProcessedSequenceNumber,
151
+ traces,
152
+ type,
315
153
  };
316
- if (this.connection !== undefined) {
317
- return Object.assign(Object.assign({}, common), { connectionMode: this.connectionMode, relayServiceAgent: this.connection.relayServiceAgent });
154
+ if (!batch) {
155
+ this.flush();
318
156
  }
319
- else {
320
- return Object.assign(Object.assign({}, common), {
321
- // Report how many ops this client sent in last disconnected session
322
- sentOps: this.clientSequenceNumber });
157
+ const message = this.connectionManager.prepareMessageToSend(messagePartial);
158
+ if (message === undefined) {
159
+ return -1;
323
160
  }
324
- }
325
- /**
326
- * Enables or disables automatic reconnecting.
327
- * Will throw an error if reconnectMode set to Never.
328
- */
329
- setAutoReconnect(mode) {
330
- assert(mode !== ReconnectMode.Never && this._reconnectMode !== ReconnectMode.Never, 0x278 /* "API is not supported for non-connecting or closed container" */);
331
- this._reconnectMode = mode;
332
- if (mode !== ReconnectMode.Enabled) {
333
- // immediately disconnect - do not rely on service eventually dropping connection.
334
- this.disconnectFromDeltaStream("setAutoReconnect");
161
+ this.messageBuffer.push(message);
162
+ if (!batch) {
163
+ this.flush();
335
164
  }
165
+ this.emit("submitOp", message);
166
+ return message.clientSequenceNumber;
336
167
  }
337
- /**
338
- * Sends signal to runtime (and data stores) to be read-only.
339
- * Hosts may have read only views, indicating to data stores that no edits are allowed.
340
- * This is independent from this._readonlyPermissions (permissions) and this.connectionMode
341
- * (server can return "write" mode even when asked for "read")
342
- * Leveraging same "readonly" event as runtime & data stores should behave the same in such case
343
- * as in read-only permissions.
344
- * But this.active can be used by some DDSes to figure out if ops can be sent
345
- * (for example, read-only view still participates in code proposals / upgrades decisions)
346
- *
347
- * Forcing Readonly does not prevent DDS from generating ops. It is up to user code to honour
348
- * the readonly flag. If ops are generated, they will accumulate locally and not be sent. If
349
- * there are pending in the outbound queue, it will stop sending until force readonly is
350
- * cleared.
351
- *
352
- * @param readonly - set or clear force readonly.
353
- */
354
- forceReadonly(readonly) {
355
- if (readonly !== this._forceReadonly) {
356
- this.logger.sendTelemetryEvent({
357
- eventName: "ForceReadOnly",
358
- value: readonly,
359
- });
360
- }
361
- const oldValue = this.readOnlyInfo.readonly;
362
- this._forceReadonly = readonly;
363
- if (oldValue !== this.readOnlyInfo.readonly) {
364
- assert(this._reconnectMode !== ReconnectMode.Never, 0x279 /* "API is not supported for non-connecting or closed container" */);
365
- let reconnect = false;
366
- if (this.readOnlyInfo.readonly === true) {
367
- // If we switch to readonly while connected, we should disconnect first
368
- // See comment in the "readonly" event handler to deltaManager set up by
369
- // the ContainerRuntime constructor
370
- if (this.shouldJoinWrite()) {
371
- // If we have pending changes, then we will never send them - it smells like
372
- // host logic error.
373
- this.logger.sendErrorEvent({ eventName: "ForceReadonlyPendingChanged" });
374
- }
375
- reconnect = this.disconnectFromDeltaStream("Force readonly");
376
- }
377
- safeRaiseEvent(this, this.logger, "readonly", this.readOnlyInfo.readonly);
378
- if (reconnect) {
379
- // reconnect if we disconnected from before.
380
- this.triggerConnect({ reason: "forceReadonly", mode: "read", fetchOpsFromStorage: false });
381
- }
168
+ submitSignal(content) { return this.connectionManager.submitSignal(content); }
169
+ flush() {
170
+ if (this.messageBuffer.length === 0) {
171
+ return;
382
172
  }
173
+ // The prepareFlush event allows listeners to append metadata to the batch prior to submission.
174
+ this.emit("prepareSend", this.messageBuffer);
175
+ this.connectionManager.sendMessages(this.messageBuffer);
176
+ this.messageBuffer = [];
177
+ }
178
+ get connectionProps() {
179
+ return Object.assign({ sequenceNumber: this.lastSequenceNumber }, this.connectionManager.connectionProps);
383
180
  }
384
181
  /**
385
182
  * Log error event with a bunch of internal to DeltaManager information about state of op processing
@@ -389,20 +186,46 @@ export class DeltaManager extends TypedEventEmitter {
389
186
  */
390
187
  logConnectionIssue(event) {
391
188
  var _a;
392
- assert(this.connection !== undefined, 0x238 /* "called only in connected state" */);
189
+ assert(this.connectionManager.connected, 0x238 /* "called only in connected state" */);
393
190
  const pendingSorted = this.pending.sort((a, b) => a.sequenceNumber - b.sequenceNumber);
394
191
  this.logger.sendErrorEvent(Object.assign(Object.assign(Object.assign(Object.assign({}, event), {
395
192
  // This directly tells us if fetching ops is in flight, and thus likely the reason of
396
193
  // stalled op processing
397
194
  fetchReason: this.fetchReason,
398
195
  // A bunch of useful sequence numbers to understand if we are holding some ops from processing
399
- lastQueuedSequenceNumber: this.lastQueuedSequenceNumber, lastProcessedSequenceNumber: this.lastProcessedSequenceNumber, lastObserved: this.lastObservedSeqNumber }), this.connectionStateProps), { pendingOps: this.pending.length, pendingFirst: (_a = pendingSorted[0]) === null || _a === void 0 ? void 0 : _a.sequenceNumber, haveHandler: this.handler !== undefined, inboundLength: this.inbound.length, inboundPaused: this.inbound.paused }));
196
+ lastQueuedSequenceNumber: this.lastQueuedSequenceNumber, lastProcessedSequenceNumber: this.lastProcessedSequenceNumber, lastObserved: this.lastObservedSeqNumber }), this.connectionManager.connectionVerboseProps), { pendingOps: this.pending.length, pendingFirst: (_a = pendingSorted[0]) === null || _a === void 0 ? void 0 : _a.sequenceNumber, haveHandler: this.handler !== undefined, inboundLength: this.inbound.length, inboundPaused: this.inbound.paused }));
400
197
  }
401
- set_readonlyPermissions(readonly) {
402
- const oldValue = this.readOnlyInfo.readonly;
403
- this._readonlyPermissions = readonly;
404
- if (oldValue !== this.readOnlyInfo.readonly) {
405
- safeRaiseEvent(this, this.logger, "readonly", this.readOnlyInfo.readonly);
198
+ connectHandler(connection) {
199
+ this.refreshDelayInfo(this.deltaStreamDelayId);
200
+ const props = this.connectionManager.connectionVerboseProps;
201
+ props.connectionLastQueuedSequenceNumber = this.lastQueuedSequenceNumber;
202
+ props.connectionLastObservedSeqNumber = this.lastObservedSeqNumber;
203
+ const checkpointSequenceNumber = connection.checkpointSequenceNumber;
204
+ this._checkpointSequenceNumber = checkpointSequenceNumber;
205
+ if (checkpointSequenceNumber !== undefined) {
206
+ this.updateLatestKnownOpSeqNumber(checkpointSequenceNumber);
207
+ }
208
+ // We cancel all ops on lost of connectivity, and rely on DDSes to resubmit them.
209
+ // Semantics are not well defined for batches (and they are broken right now on disconnects anyway),
210
+ // but it's safe to assume (until better design is put into place) that batches should not exist
211
+ // across multiple connections. Right now we assume runtime will not submit any ops in disconnected
212
+ // state. As requirements change, so should these checks.
213
+ assert(this.messageBuffer.length === 0, 0x0e9 /* "messageBuffer is not empty on new connection" */);
214
+ this.emit("connect", connection, checkpointSequenceNumber !== undefined ?
215
+ this.lastObservedSeqNumber - this.lastSequenceNumber : undefined);
216
+ // If we got some initial ops, then we know the gap and call above fetched ops to fill it.
217
+ // Same is true for "write" mode even if we have no ops - we will get "join" own op very very soon.
218
+ // However if we are connecting as view-only, then there is no good signal to realize if client is behind.
219
+ // Thus we have to hit storage to see if any ops are there.
220
+ if (checkpointSequenceNumber !== undefined) {
221
+ // We know how far we are behind (roughly). If it's non-zero gap, fetch ops right away.
222
+ if (checkpointSequenceNumber > this.lastQueuedSequenceNumber) {
223
+ this.fetchMissingDeltas("AfterConnection");
224
+ }
225
+ // we do not know the gap, and we will not learn about it if socket is quite - have to ask.
226
+ }
227
+ else if (connection.mode === "read") {
228
+ this.fetchMissingDeltas("AfterReadConnection");
406
229
  }
407
230
  }
408
231
  dispose() {
@@ -443,66 +266,16 @@ export class DeltaManager extends TypedEventEmitter {
443
266
  // (which in most cases will happen when we are done processing cached ops)
444
267
  if (cacheOnly) {
445
268
  // fire and forget
446
- this.fetchMissingDeltas("DocumentOpen", this.lastQueuedSequenceNumber);
269
+ this.fetchMissingDeltas("DocumentOpen");
447
270
  }
448
271
  }
449
272
  // Ensure there is no need to call this.processPendingOps() at the end of boot sequence
450
273
  assert(this.fetchReason !== undefined || this.pending.length === 0, 0x269 /* "pending ops are not dropped" */);
451
274
  }
452
- static detailsFromConnection(connection) {
453
- return {
454
- claims: connection.claims,
455
- clientId: connection.clientId,
456
- existing: connection.existing,
457
- checkpointSequenceNumber: connection.checkpointSequenceNumber,
458
- get initialClients() { return connection.initialClients; },
459
- maxMessageSize: connection.serviceConfiguration.maxMessageSize,
460
- mode: connection.mode,
461
- serviceConfiguration: connection.serviceConfiguration,
462
- version: connection.version,
463
- };
464
- }
465
- async connect(args) {
466
- const connection = await this.connectCore(args);
467
- return DeltaManager.detailsFromConnection(connection);
468
- }
469
- /**
470
- * Start the connection. Any error should result in container being close.
471
- * And report the error if it excape for any reason.
472
- * @param args - The connection arguments
473
- */
474
- triggerConnect(args) {
475
- assert(this.connection === undefined, 0x239 /* "called only in disconnected state" */);
476
- if (this.reconnectMode !== ReconnectMode.Enabled) {
477
- return;
478
- }
479
- this.connectCore(args).catch((err) => {
480
- // Errors are raised as "error" event and close container.
481
- // Have a catch-all case in case we missed something
482
- if (!this.closed) {
483
- this.logger.sendErrorEvent({ eventName: "ConnectException" }, err);
484
- }
485
- });
486
- }
487
- async connectCore(args) {
488
- var _a, _b, _c;
489
- assert(!this.closed, 0x26a /* "not closed" */);
490
- if (this.connection !== undefined) {
491
- return this.connection;
492
- }
493
- if (this.connectionP !== undefined) {
494
- return this.connectionP;
495
- }
275
+ connect(args) {
276
+ var _a;
496
277
  const fetchOpsFromStorage = (_a = args.fetchOpsFromStorage) !== null && _a !== void 0 ? _a : true;
497
- let requestedMode = (_b = args.mode) !== null && _b !== void 0 ? _b : this.defaultReconnectionMode;
498
- // if we have any non-acked ops from last connection, reconnect as "write".
499
- // without that we would connect in view-only mode, which will result in immediate
500
- // firing of "connected" event from Container and switch of current clientId (as tracked
501
- // by all DDSes). This will make it impossible to figure out if ops actually made it through,
502
- // so DDSes will immediately resubmit all pending ops, and some of them will be duplicates, corrupting document
503
- if (this.shouldJoinWrite()) {
504
- requestedMode = "write";
505
- }
278
+ logIfFalse(this.handler !== undefined || !fetchOpsFromStorage, this.logger, "CantFetchWithoutBaseline"); // can't fetch if no baseline
506
279
  // Note: There is race condition here.
507
280
  // We want to issue request to storage as soon as possible, to
508
281
  // reduce latency of becoming current, thus this code here.
@@ -512,213 +285,11 @@ export class DeltaManager extends TypedEventEmitter {
512
285
  // own "join" message and realize any gap client has in ops.
513
286
  // But for view-only connection, we have no such signal, and with no traffic
514
287
  // on the wire, we might be always behind.
515
- // See comment at the end of setupNewSuccessfulConnection()
516
- logIfFalse(this.handler !== undefined || !fetchOpsFromStorage, this.logger, "CantFetchWithoutBaseline"); // can't fetch if no baseline
288
+ // See comment at the end of "connect" handler
517
289
  if (fetchOpsFromStorage) {
518
- this.fetchMissingDeltas(args.reason, this.lastQueuedSequenceNumber);
519
- }
520
- const docService = this.serviceProvider();
521
- assert(docService !== undefined, 0x2a7 /* "Container is not attached" */);
522
- if (((_c = docService.policies) === null || _c === void 0 ? void 0 : _c.storageOnly) === true) {
523
- const connection = new NoDeltaStream();
524
- this.connectionP = Promise.resolve(connection); // to keep setupNewSuccessfulConnection happy
525
- this.setupNewSuccessfulConnection(connection, "read");
526
- return connection;
527
- }
528
- // The promise returned from connectCore will settle with a resolved connection or reject with error
529
- const connectCore = async () => {
530
- let connection;
531
- let delayMs = InitialReconnectDelayInMs;
532
- let connectRepeatCount = 0;
533
- const connectStartTime = performance.now();
534
- let lastError;
535
- // This loop will keep trying to connect until successful, with a delay between each iteration.
536
- while (connection === undefined) {
537
- if (this.closed) {
538
- throw new Error("Attempting to connect a closed DeltaManager");
539
- }
540
- connectRepeatCount++;
541
- try {
542
- this.client.mode = requestedMode;
543
- connection = await docService.connectToDeltaStream(this.client);
544
- if (connection.disposed) {
545
- // Nobody observed this connection, so drop it on the floor and retry.
546
- this.logger.sendTelemetryEvent({ eventName: "ReceivedClosedConnection" });
547
- connection = undefined;
548
- }
549
- }
550
- catch (origError) {
551
- if (typeof origError === "object" && origError !== null &&
552
- (origError === null || origError === void 0 ? void 0 : origError.errorType) === DeltaStreamConnectionForbiddenError.errorType) {
553
- connection = new NoDeltaStream();
554
- requestedMode = "read";
555
- break;
556
- }
557
- // Socket.io error when we connect to wrong socket, or hit some multiplexing bug
558
- if (!canRetryOnError(origError)) {
559
- const error = normalizeError(origError, { props: fatalConnectErrorProp });
560
- this.close(error);
561
- throw error;
562
- }
563
- // Log error once - we get too many errors in logs when we are offline,
564
- // and unfortunately there is no reliable way to detect that.
565
- if (connectRepeatCount === 1) {
566
- logNetworkFailure(this.logger, {
567
- delay: delayMs,
568
- eventName: "DeltaConnectionFailureToConnect",
569
- duration: TelemetryLogger.formatTick(performance.now() - connectStartTime),
570
- }, origError);
571
- }
572
- lastError = origError;
573
- const retryDelayFromError = getRetryDelayFromError(origError);
574
- delayMs = retryDelayFromError !== null && retryDelayFromError !== void 0 ? retryDelayFromError : Math.min(delayMs * 2, MaxReconnectDelayInMs);
575
- if (retryDelayFromError !== undefined) {
576
- this.emitDelayInfo(this.deltaStreamDelayId, retryDelayFromError, origError);
577
- }
578
- await waitForConnectedState(delayMs);
579
- }
580
- }
581
- // If we retried more than once, log an event about how long it took
582
- if (connectRepeatCount > 1) {
583
- this.logger.sendTelemetryEvent({
584
- eventName: "MultipleDeltaConnectionFailures",
585
- attempts: connectRepeatCount,
586
- duration: TelemetryLogger.formatTick(performance.now() - connectStartTime),
587
- }, lastError);
588
- }
589
- this.setupNewSuccessfulConnection(connection, requestedMode);
590
- return connection;
591
- };
592
- // This promise settles as soon as we know the outcome of the connection attempt
593
- // Set it upfront, such that if connection is established (NoDeltaConnection) or rejected (bug in
594
- // connectToDeltaStream() implementation - throwing exception vs. returning rejected promise) in
595
- // synchronous way, we have this.connectionP setup for all the code to assert correctness of the flow.
596
- const deferred = new Deferred();
597
- this.connectionP = deferred.promise;
598
- // Regardless of how the connection attempt concludes, we'll clear the promise and remove the listener
599
- // Reject the connection promise if the DeltaManager gets closed during connection
600
- const cleanupAndReject = (error) => {
601
- this.connectionP = undefined;
602
- this.removeListener("closed", cleanupAndReject);
603
- // This error came from some logic error in this file. Fail-fast to learn and fix the issue faster
604
- const normalizedError = normalizeError(error, { props: fatalConnectErrorProp });
605
- this.close(normalizedError);
606
- deferred.reject(normalizedError);
607
- };
608
- this.on("closed", cleanupAndReject);
609
- // Attempt the connection
610
- connectCore().then((connection) => {
611
- this.removeListener("closed", cleanupAndReject);
612
- deferred.resolve(connection);
613
- }).catch(cleanupAndReject);
614
- return this.connectionP;
615
- }
616
- flush() {
617
- if (this.messageBuffer.length === 0) {
618
- return;
619
- }
620
- // The prepareFlush event allows listeners to append metadata to the batch prior to submission.
621
- this.emit("prepareSend", this.messageBuffer);
622
- this._outbound.push(this.messageBuffer);
623
- this.messageBuffer = [];
624
- }
625
- /**
626
- * Submits the given delta returning the client sequence number for the message. Contents is the actual
627
- * contents of the message. appData is optional metadata that can be attached to the op by the app.
628
- *
629
- * If batch is set to true then the submit will be batched - and as a result guaranteed to be ordered sequentially
630
- * in the global sequencing space. The batch will be flushed either when flush is called or when a non-batched
631
- * op is submitted.
632
- */
633
- submit(type, contents, batch = false, metadata) {
634
- // TODO need to fail if gets too large
635
- // const serializedContent = JSON.stringify(this.messageBuffer);
636
- // const maxOpSize = this.context.deltaManager.maxMessageSize;
637
- var _a, _b;
638
- if (this.readOnlyInfo.readonly === true) {
639
- assert(this.readOnlyInfo.readonly === true, 0x1f0 /* "Unexpected mismatch in readonly" */);
640
- const error = new GenericError("deltaManagerReadonlySubmit", undefined /* error */, {
641
- readonly: this.readOnlyInfo.readonly,
642
- forcedReadonly: this.readOnlyInfo.forced,
643
- readonlyPermissions: this.readOnlyInfo.permissions,
644
- storageOnly: this.readOnlyInfo.storageOnly,
645
- });
646
- this.close(error);
647
- return -1;
648
- }
649
- // reset clientSequenceNumber if we are using new clientId.
650
- // we keep info about old connection as long as possible to be able to account for all non-acked ops
651
- // that we pick up on next connection.
652
- assert(!!this.connection, 0x0e4 /* "Lost old connection!" */);
653
- if (this.lastSubmittedClientId !== ((_a = this.connection) === null || _a === void 0 ? void 0 : _a.clientId)) {
654
- this.lastSubmittedClientId = (_b = this.connection) === null || _b === void 0 ? void 0 : _b.clientId;
655
- this.clientSequenceNumber = 0;
656
- this.clientSequenceNumberObserved = 0;
657
- }
658
- // If connection is "read" or implicit "read" (got leave op for "write" connection),
659
- // then op can't make it through - we will get a nack if op is sent.
660
- // We can short-circuit this process.
661
- // Note that we also want nacks to be rare and be treated as catastrophic failures.
662
- // Be careful with reentrancy though - disconnected event should not be be raised in the
663
- // middle of the current workflow, but rather on clean stack!
664
- if (this.connectionMode === "read" || this.downgradedConnection) {
665
- if (!this.pendingReconnect) {
666
- this.pendingReconnect = true;
667
- Promise.resolve().then(async () => {
668
- if (this.pendingReconnect) { // still valid?
669
- return this.reconnectOnErrorCore("write", // connectionMode
670
- "Switch to write");
671
- }
672
- })
673
- .catch(() => { });
674
- }
675
- // Can return -1 here, but no other path does it (other than error path in Container),
676
- // so it's better not to introduce new states.
677
- return ++this.clientSequenceNumber;
678
- }
679
- const service = this.clientDetails.type === undefined || this.clientDetails.type === ""
680
- ? "unknown"
681
- : this.clientDetails.type;
682
- // Start adding trace for the op.
683
- const traces = [
684
- {
685
- action: "start",
686
- service,
687
- timestamp: Date.now(),
688
- }
689
- ];
690
- const message = {
691
- clientSequenceNumber: ++this.clientSequenceNumber,
692
- contents: JSON.stringify(contents),
693
- metadata,
694
- referenceSequenceNumber: this.lastProcessedSequenceNumber,
695
- traces,
696
- type,
697
- };
698
- if (type === MessageType.NoOp) {
699
- this.trailingNoopCount++;
700
- }
701
- else {
702
- this.trailingNoopCount = 0;
703
- }
704
- this.emit("submitOp", message);
705
- if (!batch) {
706
- this.flush();
707
- this.messageBuffer.push(message);
708
- this.flush();
709
- }
710
- else {
711
- this.messageBuffer.push(message);
712
- }
713
- return message.clientSequenceNumber;
714
- }
715
- submitSignal(content) {
716
- if (this.connection !== undefined) {
717
- this.connection.submitSignal(content);
718
- }
719
- else {
720
- this.logger.sendErrorEvent({ eventName: "submitSignalDisconnected" });
290
+ this.fetchMissingDeltas(args.reason);
721
291
  }
292
+ this.connectionManager.connect(args.mode);
722
293
  }
723
294
  async getDeltas(from, // inclusive
724
295
  to, // exclusive
@@ -730,9 +301,6 @@ export class DeltaManager extends TypedEventEmitter {
730
301
  if (this.deltaStorage === undefined) {
731
302
  this.deltaStorage = await docService.connectToDeltaStorage();
732
303
  }
733
- assert(this.closeAbortController.signal.onabort === null, 0x1e8 /* "reentrancy" */);
734
- const controller = new AbortController();
735
- this.closeAbortController.signal.onabort = () => controller.abort();
736
304
  let cancelFetch;
737
305
  if (to !== undefined) {
738
306
  const lastExpectedOp = to - 1; // make it inclusive!
@@ -740,7 +308,7 @@ export class DeltaManager extends TypedEventEmitter {
740
308
  // received through delta stream. Validate that before moving forward.
741
309
  if (this.lastQueuedSequenceNumber >= lastExpectedOp) {
742
310
  this.logger.sendPerformanceEvent(Object.assign({ reason: this.fetchReason, eventName: "ExtraStorageCall", early: true, from,
743
- to }, this.connectionStateProps));
311
+ to }, this.connectionManager.connectionVerboseProps));
744
312
  return;
745
313
  }
746
314
  // Be prepared for the case where webSocket would receive the ops that we are trying to fill through
@@ -757,6 +325,7 @@ export class DeltaManager extends TypedEventEmitter {
757
325
  // That said, if we have socket connection, make sure we got ops up to checkpointSequenceNumber!
758
326
  cancelFetch = (op) => op.sequenceNumber >= this.lastObservedSeqNumber;
759
327
  }
328
+ const controller = new AbortController();
760
329
  let opsFromFetch = false;
761
330
  const opListener = (op) => {
762
331
  assert(op.sequenceNumber === this.lastQueuedSequenceNumber, 0x23a /* "seq#'s" */);
@@ -768,8 +337,10 @@ export class DeltaManager extends TypedEventEmitter {
768
337
  this._inbound.off("push", opListener);
769
338
  }
770
339
  };
771
- this._inbound.on("push", opListener);
772
340
  try {
341
+ this._inbound.on("push", opListener);
342
+ assert(this.closeAbortController.signal.onabort === null, 0x1e8 /* "reentrancy" */);
343
+ this.closeAbortController.signal.onabort = () => controller.abort();
773
344
  const stream = this.deltaStorage.fetchMessages(from, // inclusive
774
345
  to, // exclusive
775
346
  controller.signal, cacheOnly, this.fetchReason);
@@ -789,9 +360,9 @@ export class DeltaManager extends TypedEventEmitter {
789
360
  }
790
361
  }
791
362
  finally {
792
- assert(!opsFromFetch, 0x289 /* "logic error" */);
793
363
  this.closeAbortController.signal.onabort = null;
794
364
  this._inbound.off("push", opListener);
365
+ assert(!opsFromFetch, 0x289 /* "logic error" */);
795
366
  }
796
367
  }
797
368
  /**
@@ -802,16 +373,9 @@ export class DeltaManager extends TypedEventEmitter {
802
373
  return;
803
374
  }
804
375
  this.closed = true;
805
- // Ensure that things like triggerConnect() will short circuit
806
- this._reconnectMode = ReconnectMode.Never;
376
+ this.connectionManager.dispose(error);
807
377
  this.closeAbortController.abort();
808
- const disconnectReason = error !== undefined
809
- ? `Closing DeltaManager (${error.message})`
810
- : "Closing DeltaManager";
811
- // This raises "disconnect" event if we have active connection.
812
- this.disconnectFromDeltaStream(disconnectReason);
813
378
  this._inbound.clear();
814
- this._outbound.clear();
815
379
  this._inboundSignal.clear();
816
380
  // eslint-disable-next-line @typescript-eslint/no-floating-promises
817
381
  this._inbound.pause();
@@ -819,10 +383,6 @@ export class DeltaManager extends TypedEventEmitter {
819
383
  this._inboundSignal.pause();
820
384
  // Drop pending messages - this will ensure catchUp() does not go into infinite loop
821
385
  this.pending = [];
822
- // Notify everyone we are in read-only state.
823
- // Useful for data stores in case we hit some critical error,
824
- // to switch to a mode where user edits are not accepted
825
- this.set_readonlyPermissions(true);
826
386
  // This needs to be the last thing we do (before removing listeners), as it causes
827
387
  // Container to dispose context and break ability of data stores / runtime to "hear"
828
388
  // from delta manager, including notification (above) about readonly state.
@@ -835,6 +395,20 @@ export class DeltaManager extends TypedEventEmitter {
835
395
  this.timeTillThrottling = 0;
836
396
  }
837
397
  }
398
+ disconnectHandler(reason) {
399
+ if (this.messageBuffer.length > 0) {
400
+ // Behavior is not well defined here RE batches across connections / disconnect.
401
+ // DeltaManager overall policy - drop all ops on disconnection and rely on
402
+ // container runtime to deal with resubmitting any ops that did not make it through.
403
+ // So drop them, but also raise error event to look into details.
404
+ this.logger.sendErrorEvent({
405
+ eventName: "OpenBatchOnDisconnect",
406
+ length: this.messageBuffer.length,
407
+ });
408
+ this.messageBuffer.length = 0;
409
+ }
410
+ this.emit("disconnect", reason);
411
+ }
838
412
  /**
839
413
  * Emit info about a delay in service communication on account of throttling.
840
414
  * @param id - Id of the connection that is delayed
@@ -850,183 +424,6 @@ export class DeltaManager extends TypedEventEmitter {
850
424
  this.emit("throttled", throttlingWarning);
851
425
  }
852
426
  }
853
- /**
854
- * Once we've successfully gotten a connection, we need to set up state, attach event listeners, and process
855
- * initial messages.
856
- * @param connection - The newly established connection
857
- */
858
- setupNewSuccessfulConnection(connection, requestedMode) {
859
- // Old connection should have been cleaned up before establishing a new one
860
- assert(this.connection === undefined, 0x0e6 /* "old connection exists on new connection setup" */);
861
- assert(this.connectionP !== undefined || this.closed, 0x27f /* "reentrancy may result in incorrect behavior" */);
862
- assert(!connection.disposed, 0x28a /* "can't be disposed - Callers need to ensure that!" */);
863
- this.connectionP = undefined;
864
- this.connection = connection;
865
- // Does information in scopes & mode matches?
866
- // If we asked for "write" and got "read", then file is read-only
867
- // But if we ask read, server can still give us write.
868
- const readonly = !connection.claims.scopes.includes(ScopeType.DocWrite);
869
- // This connection mode validation logic is moving to the driver layer in 0.44. These two asserts can be
870
- // removed after those packages have released and become ubiquitous.
871
- assert(requestedMode === "read" || readonly === (this.connectionMode === "read"), 0x0e7 /* "claims/connectionMode mismatch" */);
872
- assert(!readonly || this.connectionMode === "read", 0x0e8 /* "readonly perf with write connection" */);
873
- this.set_readonlyPermissions(readonly);
874
- this.refreshDelayInfo(this.deltaStreamDelayId);
875
- if (this.closed) {
876
- // Raise proper events, Log telemetry event and close connection.
877
- this.disconnectFromDeltaStream("DeltaManager already closed");
878
- return;
879
- }
880
- // We cancel all ops on lost of connectivity, and rely on DDSes to resubmit them.
881
- // Semantics are not well defined for batches (and they are broken right now on disconnects anyway),
882
- // but it's safe to assume (until better design is put into place) that batches should not exist
883
- // across multiple connections. Right now we assume runtime will not submit any ops in disconnected
884
- // state. As requirements change, so should these checks.
885
- assert(this.messageBuffer.length === 0, 0x0e9 /* "messageBuffer is not empty on new connection" */);
886
- this._outbound.resume();
887
- connection.on("op", this.opHandler);
888
- connection.on("signal", this.signalHandler);
889
- connection.on("nack", this.nackHandler);
890
- connection.on("disconnect", this.disconnectHandler);
891
- connection.on("error", this.errorHandler);
892
- connection.on("pong", this.pongHandler);
893
- // Initial messages are always sorted. However, due to early op handler installed by drivers and appending those
894
- // ops to initialMessages, resulting set is no longer sorted, which would result in client hitting storage to
895
- // fill in gap. We will recover by cancelling this request once we process remaining ops, but it's a waste that
896
- // we could avoid
897
- const initialMessages = connection.initialMessages.sort((a, b) => a.sequenceNumber - b.sequenceNumber);
898
- this.connectionStateProps = {
899
- connectionLastQueuedSequenceNumber: this.lastQueuedSequenceNumber,
900
- connectionLastObservedSeqNumber: this.lastObservedSeqNumber,
901
- clientId: connection.clientId,
902
- mode: connection.mode,
903
- };
904
- if (connection.relayServiceAgent !== undefined) {
905
- this.connectionStateProps.relayServiceAgent = connection.relayServiceAgent;
906
- }
907
- this._hasCheckpointSequenceNumber = false;
908
- // Some storages may provide checkpointSequenceNumber to identify how far client is behind.
909
- const checkpointSequenceNumber = connection.checkpointSequenceNumber;
910
- if (checkpointSequenceNumber !== undefined) {
911
- this._hasCheckpointSequenceNumber = true;
912
- this.updateLatestKnownOpSeqNumber(checkpointSequenceNumber);
913
- }
914
- // Update knowledge of how far we are behind, before raising "connect" event
915
- // This is duplication of what enqueueMessages() does, but we have to raise event before we get there,
916
- // so duplicating update logic here as well.
917
- const last = initialMessages.length > 0 ? initialMessages[initialMessages.length - 1].sequenceNumber : -1;
918
- if (initialMessages.length > 0) {
919
- this._hasCheckpointSequenceNumber = true;
920
- this.updateLatestKnownOpSeqNumber(last);
921
- }
922
- // Notify of the connection
923
- // WARNING: This has to happen before processInitialMessages() call below.
924
- // If not, we may not update Container.pendingClientId in time before seeing our own join session op.
925
- this.emit("connect", DeltaManager.detailsFromConnection(connection), this._hasCheckpointSequenceNumber ? this.lastObservedSeqNumber - this.lastSequenceNumber : undefined);
926
- this.enqueueMessages(initialMessages, this.connectFirstConnection ? "InitialOps" : "ReconnectOps");
927
- if (connection.initialSignals !== undefined) {
928
- for (const signal of connection.initialSignals) {
929
- this._inboundSignal.push(signal);
930
- }
931
- }
932
- // If we got some initial ops, then we know the gap and call above fetched ops to fill it.
933
- // Same is true for "write" mode even if we have no ops - we will get self "join" ops very very soon.
934
- // However if we are connecting as view-only, then there is no good signal to realize if client is behind.
935
- // Thus we have to hit storage to see if any ops are there.
936
- if (initialMessages.length === 0) {
937
- if (checkpointSequenceNumber !== undefined) {
938
- // We know how far we are behind (roughly). If it's non-zero gap, fetch ops right away.
939
- if (checkpointSequenceNumber > this.lastQueuedSequenceNumber) {
940
- this.fetchMissingDeltas("AfterConnection", this.lastQueuedSequenceNumber);
941
- }
942
- // we do not know the gap, and we will not learn about it if socket is quite - have to ask.
943
- }
944
- else if (connection.mode === "read") {
945
- this.fetchMissingDeltas("AfterReadConnection", this.lastQueuedSequenceNumber);
946
- }
947
- }
948
- else {
949
- this.connectionStateProps.connectionInitialOpsFrom = initialMessages[0].sequenceNumber;
950
- this.connectionStateProps.connectionInitialOpsTo = last + 1;
951
- }
952
- this.connectFirstConnection = false;
953
- }
954
- /**
955
- * Disconnect the current connection.
956
- * @param reason - Text description of disconnect reason to emit with disconnect event
957
- */
958
- disconnectFromDeltaStream(reason) {
959
- this.pendingReconnect = false;
960
- this.downgradedConnection = false;
961
- if (this.connection === undefined) {
962
- return false;
963
- }
964
- assert(this.connectionP === undefined, 0x27b /* "reentrancy may result in incorrect behavior" */);
965
- const connection = this.connection;
966
- // Avoid any re-entrancy - clear object reference
967
- this.connection = undefined;
968
- // Remove listeners first so we don't try to retrigger this flow accidentally through reconnectOnError
969
- connection.off("op", this.opHandler);
970
- connection.off("signal", this.signalHandler);
971
- connection.off("nack", this.nackHandler);
972
- connection.off("disconnect", this.disconnectHandler);
973
- connection.off("error", this.errorHandler);
974
- connection.off("pong", this.pongHandler);
975
- // eslint-disable-next-line @typescript-eslint/no-floating-promises
976
- this._outbound.pause();
977
- this._outbound.clear();
978
- this.emit("disconnect", reason);
979
- connection.dispose();
980
- this.connectionStateProps = {};
981
- return true;
982
- }
983
- /**
984
- * Disconnect the current connection and reconnect.
985
- * @param connection - The connection that wants to reconnect - no-op if it's different from this.connection
986
- * @param requestedMode - Read or write
987
- * @param error - Error reconnect information including whether or not to reconnect
988
- * @returns A promise that resolves when the connection is reestablished or we stop trying
989
- */
990
- async reconnectOnError(requestedMode, error) {
991
- return this.reconnectOnErrorCore(requestedMode, error.message, error);
992
- }
993
- /**
994
- * Disconnect the current connection and reconnect.
995
- * @param connection - The connection that wants to reconnect - no-op if it's different from this.connection
996
- * @param requestedMode - Read or write
997
- * @param error - Error reconnect information including whether or not to reconnect
998
- * @returns A promise that resolves when the connection is reestablished or we stop trying
999
- */
1000
- async reconnectOnErrorCore(requestedMode, disconnectMessage, error) {
1001
- // We quite often get protocol errors before / after observing nack/disconnect
1002
- // we do not want to run through same sequence twice.
1003
- // If we're already disconnected/disconnecting it's not appropriate to call this again.
1004
- assert(this.connection !== undefined, 0x0eb /* "Missing connection for reconnect" */);
1005
- this.disconnectFromDeltaStream(disconnectMessage);
1006
- const canRetry = error !== undefined ? canRetryOnError(error) : true;
1007
- // If reconnection is not an option, close the DeltaManager
1008
- if (!canRetry) {
1009
- this.close(normalizeError(error, { props: fatalConnectErrorProp }));
1010
- }
1011
- else if (this.reconnectMode === ReconnectMode.Never) {
1012
- // Do not raise container error if we are closing just because we lost connection.
1013
- // Those errors (like IdleDisconnect) would show up in telemetry dashboards and
1014
- // are very misleading, as first initial reaction - some logic is broken.
1015
- this.close();
1016
- }
1017
- // If closed then we can't reconnect
1018
- if (this.closed) {
1019
- return;
1020
- }
1021
- if (this.reconnectMode === ReconnectMode.Enabled) {
1022
- const delayMs = error !== undefined ? getRetryDelayFromError(error) : undefined;
1023
- if (delayMs !== undefined) {
1024
- this.emitDelayInfo(this.deltaStreamDelayId, delayMs, error);
1025
- await waitForConnectedState(delayMs);
1026
- }
1027
- this.triggerConnect({ reason: "reconnect", mode: requestedMode, fetchOpsFromStorage: false });
1028
- }
1029
- }
1030
427
  // returns parts of message (in string format) that should never change for a given message.
1031
428
  // Used for message comparison. It attempts to avoid comparing fields that potentially may differ.
1032
429
  // for example, it's not clear if serverMetadata or timestamp property is a property of message or server state.
@@ -1038,7 +435,7 @@ export class DeltaManager extends TypedEventEmitter {
1038
435
  return `${m.clientId}-${m.type}-${m.minimumSequenceNumber}-${m.referenceSequenceNumber}-${m.timestamp}`;
1039
436
  }
1040
437
  enqueueMessages(messages, reason, allowGaps = false) {
1041
- var _a, _b, _c;
438
+ var _a, _b;
1042
439
  if (this.handler === undefined) {
1043
440
  // We did not setup handler yet.
1044
441
  // This happens when we connect to web socket faster than we get attributes for container
@@ -1098,7 +495,7 @@ export class DeltaManager extends TypedEventEmitter {
1098
495
  // correctly take into account pending ops.
1099
496
  if (eventName !== undefined) {
1100
497
  this.logger.sendPerformanceEvent(Object.assign({ eventName,
1101
- reason, previousReason: this.prevEnqueueMessagesReason, from, to: last + 1, length: messages.length, fetchReason: this.fetchReason, duplicate: duplicate > 0 ? duplicate : undefined, initialGap: initialGap !== 0 ? initialGap : undefined, gap: gap > 0 ? gap : undefined, firstMissing, dmInitialSeqNumber: this.initialSequenceNumber }, this.connectionStateProps));
498
+ reason, previousReason: this.prevEnqueueMessagesReason, from, to: last + 1, length: messages.length, fetchReason: this.fetchReason, duplicate: duplicate > 0 ? duplicate : undefined, initialGap: initialGap !== 0 ? initialGap : undefined, gap: gap > 0 ? gap : undefined, firstMissing, dmInitialSeqNumber: this.initialSequenceNumber }, this.connectionManager.connectionVerboseProps));
1102
499
  }
1103
500
  }
1104
501
  this.updateLatestKnownOpSeqNumber(messages[messages.length - 1].sequenceNumber);
@@ -1114,7 +511,7 @@ export class DeltaManager extends TypedEventEmitter {
1114
511
  const message2 = this.comparableMessagePayload(message);
1115
512
  if (message1 !== message2) {
1116
513
  const error = new NonRetryableError("twoMessagesWithSameSeqNumAndDifferentPayload", undefined, DriverErrorType.fileOverwrittenInStorage, {
1117
- clientId: (_c = this.connection) === null || _c === void 0 ? void 0 : _c.clientId,
514
+ clientId: this.connectionManager.clientId,
1118
515
  sequenceNumber: message.sequenceNumber,
1119
516
  message1,
1120
517
  message2,
@@ -1125,7 +522,7 @@ export class DeltaManager extends TypedEventEmitter {
1125
522
  }
1126
523
  else if (message.sequenceNumber !== this.lastQueuedSequenceNumber + 1) {
1127
524
  this.pending.push(message);
1128
- this.fetchMissingDeltas(reason, this.lastQueuedSequenceNumber, message.sequenceNumber);
525
+ this.fetchMissingDeltas(reason, message.sequenceNumber);
1129
526
  }
1130
527
  else {
1131
528
  this.lastQueuedSequenceNumber = message.sequenceNumber;
@@ -1139,56 +536,34 @@ export class DeltaManager extends TypedEventEmitter {
1139
536
  this.prevEnqueueMessagesReason = this.pending.length > 0 ? "unknown" : reason;
1140
537
  }
1141
538
  processInboundMessage(message) {
1142
- var _a, _b, _c;
1143
539
  const startTime = Date.now();
1144
540
  this.lastProcessedMessage = message;
1145
541
  // All non-system messages are coming from some client, and should have clientId
1146
542
  // System messages may have no clientId (but some do, like propose, noop, summarize)
1147
543
  assert(message.clientId !== undefined
1148
544
  || isSystemMessage(message), 0x0ed /* "non-system message have to have clientId" */);
1149
- // if we have connection, and message is local, then we better treat is as local!
1150
- assert(this.connection === undefined
1151
- || this.connection.clientId !== message.clientId
1152
- || this.lastSubmittedClientId === message.clientId, 0x0ee /* "Not accounting local messages correctly" */);
1153
- if (this.lastSubmittedClientId !== undefined && this.lastSubmittedClientId === message.clientId) {
1154
- const clientSequenceNumber = message.clientSequenceNumber;
1155
- assert(this.clientSequenceNumberObserved < clientSequenceNumber, 0x0ef /* "client seq# not growing" */);
1156
- assert(clientSequenceNumber <= this.clientSequenceNumber, 0x0f0 /* "Incoming local client seq# > generated by this client" */);
1157
- this.clientSequenceNumberObserved = clientSequenceNumber;
1158
- }
1159
545
  // TODO Remove after SPO picks up the latest build.
1160
546
  if (typeof message.contents === "string"
1161
547
  && message.contents !== ""
1162
548
  && message.type !== MessageType.ClientLeave) {
1163
549
  message.contents = JSON.parse(message.contents);
1164
550
  }
1165
- if (message.type === MessageType.ClientLeave) {
1166
- const systemLeaveMessage = message;
1167
- const clientId = JSON.parse(systemLeaveMessage.data);
1168
- if (clientId === ((_a = this.connection) === null || _a === void 0 ? void 0 : _a.clientId)) {
1169
- // We have been kicked out from quorum
1170
- this.logger.sendPerformanceEvent({ eventName: "ReadConnectionTransition" });
1171
- this.downgradedConnection = true;
1172
- }
1173
- }
551
+ this.connectionManager.beforeProcessingIncomingOp(message);
1174
552
  // Add final ack trace.
1175
553
  if (message.traces !== undefined && message.traces.length > 0) {
1176
- const service = this.clientDetails.type === undefined || this.clientDetails.type === ""
1177
- ? "unknown"
1178
- : this.clientDetails.type;
1179
554
  message.traces.push({
1180
555
  action: "end",
1181
- service,
556
+ service: "client",
1182
557
  timestamp: Date.now(),
1183
558
  });
1184
559
  }
1185
560
  // Watch the minimum sequence number and be ready to update as needed
1186
561
  if (this.minSequenceNumber > message.minimumSequenceNumber) {
1187
- throw new DataCorruptionError("msnMovesBackwards", Object.assign(Object.assign({}, extractLogSafeMessageProperties(message)), { clientId: (_b = this.connection) === null || _b === void 0 ? void 0 : _b.clientId }));
562
+ throw new DataCorruptionError("msnMovesBackwards", Object.assign(Object.assign({}, extractLogSafeMessageProperties(message)), { clientId: this.connectionManager.clientId }));
1188
563
  }
1189
564
  this.minSequenceNumber = message.minimumSequenceNumber;
1190
565
  if (message.sequenceNumber !== this.lastProcessedSequenceNumber + 1) {
1191
- throw new DataCorruptionError("nonSequentialSequenceNumber", Object.assign(Object.assign({}, extractLogSafeMessageProperties(message)), { clientId: (_c = this.connection) === null || _c === void 0 ? void 0 : _c.clientId }));
566
+ throw new DataCorruptionError("nonSequentialSequenceNumber", Object.assign(Object.assign({}, extractLogSafeMessageProperties(message)), { clientId: this.connectionManager.clientId }));
1192
567
  }
1193
568
  this.lastProcessedSequenceNumber = message.sequenceNumber;
1194
569
  // a bunch of code assumes that this is true
@@ -1210,15 +585,15 @@ export class DeltaManager extends TypedEventEmitter {
1210
585
  /**
1211
586
  * Retrieves the missing deltas between the given sequence numbers
1212
587
  */
1213
- fetchMissingDeltas(reasonArg, lastKnowOp, to) {
1214
- this.fetchMissingDeltasCore(reasonArg, false /* cacheOnly */, lastKnowOp, to).catch((error) => {
588
+ fetchMissingDeltas(reasonArg, to) {
589
+ this.fetchMissingDeltasCore(reasonArg, false /* cacheOnly */, to).catch((error) => {
1215
590
  this.logger.sendErrorEvent({ eventName: "fetchMissingDeltasException" }, error);
1216
591
  });
1217
592
  }
1218
593
  /**
1219
594
  * Retrieves the missing deltas between the given sequence numbers
1220
595
  */
1221
- async fetchMissingDeltasCore(reason, cacheOnly, lastKnowOp, to) {
596
+ async fetchMissingDeltasCore(reason, cacheOnly, to) {
1222
597
  var _a;
1223
598
  // Exit out early if we're already fetching deltas
1224
599
  if (this.fetchReason !== undefined) {
@@ -1230,12 +605,11 @@ export class DeltaManager extends TypedEventEmitter {
1230
605
  }
1231
606
  if (this.handler === undefined) {
1232
607
  // We do not poses yet any information
1233
- assert(lastKnowOp === 0, 0x26b /* "initial state" */);
608
+ assert(this.lastQueuedSequenceNumber === 0, 0x26b /* "initial state" */);
1234
609
  return;
1235
610
  }
1236
611
  try {
1237
- assert(lastKnowOp === this.lastQueuedSequenceNumber, 0x0f1 /* "from arg" */);
1238
- let from = lastKnowOp + 1;
612
+ let from = this.lastQueuedSequenceNumber + 1;
1239
613
  const n = (_a = this.previouslyProcessedMessage) === null || _a === void 0 ? void 0 : _a.sequenceNumber;
1240
614
  if (n !== undefined) {
1241
615
  // If we already processed at least one op, then we have this.previouslyProcessedMessage populated
@@ -1243,7 +617,7 @@ export class DeltaManager extends TypedEventEmitter {
1243
617
  // Knowing about this mechanism, we could ask for op we already observed to increase validation.
1244
618
  // This is especially useful when coming out of offline mode or loading from
1245
619
  // very old cached (by client / driver) snapshot.
1246
- assert(n === lastKnowOp, 0x0f2 /* "previouslyProcessedMessage" */);
620
+ assert(n === this.lastQueuedSequenceNumber, 0x0f2 /* "previouslyProcessedMessage" */);
1247
621
  assert(from > 1, 0x0f3 /* "not positive" */);
1248
622
  from--;
1249
623
  }
@@ -1291,7 +665,7 @@ export class DeltaManager extends TypedEventEmitter {
1291
665
  // (the other 50%), and thus these errors below should be looked at even if code below results in
1292
666
  // recovery.
1293
667
  if (this.lastQueuedSequenceNumber < this.lastObservedSeqNumber) {
1294
- this.fetchMissingDeltas("OpsBehind", this.lastQueuedSequenceNumber);
668
+ this.fetchMissingDeltas("OpsBehind");
1295
669
  }
1296
670
  }
1297
671
  }