@fluidframework/container-loader 0.53.0 → 0.54.2

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 (57) 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 -767
  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.js +1 -1
  23. package/dist/packageVersion.js.map +1 -1
  24. package/dist/protocolTreeDocumentStorageService.d.ts +2 -2
  25. package/dist/protocolTreeDocumentStorageService.d.ts.map +1 -1
  26. package/lib/connectionManager.d.ts +153 -0
  27. package/lib/connectionManager.d.ts.map +1 -0
  28. package/lib/connectionManager.js +660 -0
  29. package/lib/connectionManager.js.map +1 -0
  30. package/lib/container.d.ts +2 -1
  31. package/lib/container.d.ts.map +1 -1
  32. package/lib/container.js +25 -28
  33. package/lib/container.js.map +1 -1
  34. package/lib/contracts.d.ts +112 -0
  35. package/lib/contracts.d.ts.map +1 -0
  36. package/lib/contracts.js +11 -0
  37. package/lib/contracts.js.map +1 -0
  38. package/lib/deltaManager.d.ts +26 -135
  39. package/lib/deltaManager.d.ts.map +1 -1
  40. package/lib/deltaManager.js +146 -771
  41. package/lib/deltaManager.js.map +1 -1
  42. package/lib/loader.d.ts +9 -4
  43. package/lib/loader.d.ts.map +1 -1
  44. package/lib/loader.js +6 -5
  45. package/lib/loader.js.map +1 -1
  46. package/lib/packageVersion.d.ts +1 -1
  47. package/lib/packageVersion.js +1 -1
  48. package/lib/packageVersion.js.map +1 -1
  49. package/lib/protocolTreeDocumentStorageService.d.ts +2 -2
  50. package/lib/protocolTreeDocumentStorageService.d.ts.map +1 -1
  51. package/package.json +8 -8
  52. package/src/connectionManager.ts +892 -0
  53. package/src/container.ts +39 -39
  54. package/src/contracts.ts +156 -0
  55. package/src/deltaManager.ts +181 -978
  56. package/src/loader.ts +31 -9
  57. 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,65 +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
- mode: connection.mode,
460
- serviceConfiguration: connection.serviceConfiguration,
461
- version: connection.version,
462
- };
463
- }
464
- async connect(args) {
465
- const connection = await this.connectCore(args);
466
- return DeltaManager.detailsFromConnection(connection);
467
- }
468
- /**
469
- * Start the connection. Any error should result in container being close.
470
- * And report the error if it excape for any reason.
471
- * @param args - The connection arguments
472
- */
473
- triggerConnect(args) {
474
- assert(this.connection === undefined, 0x239 /* "called only in disconnected state" */);
475
- if (this.reconnectMode !== ReconnectMode.Enabled) {
476
- return;
477
- }
478
- this.connectCore(args).catch((err) => {
479
- // Errors are raised as "error" event and close container.
480
- // Have a catch-all case in case we missed something
481
- if (!this.closed) {
482
- this.logger.sendErrorEvent({ eventName: "ConnectException" }, err);
483
- }
484
- });
485
- }
486
- async connectCore(args) {
487
- var _a, _b, _c;
488
- assert(!this.closed, 0x26a /* "not closed" */);
489
- if (this.connection !== undefined) {
490
- return this.connection;
491
- }
492
- if (this.connectionP !== undefined) {
493
- return this.connectionP;
494
- }
275
+ connect(args) {
276
+ var _a;
495
277
  const fetchOpsFromStorage = (_a = args.fetchOpsFromStorage) !== null && _a !== void 0 ? _a : true;
496
- let requestedMode = (_b = args.mode) !== null && _b !== void 0 ? _b : this.defaultReconnectionMode;
497
- // if we have any non-acked ops from last connection, reconnect as "write".
498
- // without that we would connect in view-only mode, which will result in immediate
499
- // firing of "connected" event from Container and switch of current clientId (as tracked
500
- // by all DDSes). This will make it impossible to figure out if ops actually made it through,
501
- // so DDSes will immediately resubmit all pending ops, and some of them will be duplicates, corrupting document
502
- if (this.shouldJoinWrite()) {
503
- requestedMode = "write";
504
- }
278
+ logIfFalse(this.handler !== undefined || !fetchOpsFromStorage, this.logger, "CantFetchWithoutBaseline"); // can't fetch if no baseline
505
279
  // Note: There is race condition here.
506
280
  // We want to issue request to storage as soon as possible, to
507
281
  // reduce latency of becoming current, thus this code here.
@@ -511,213 +285,11 @@ export class DeltaManager extends TypedEventEmitter {
511
285
  // own "join" message and realize any gap client has in ops.
512
286
  // But for view-only connection, we have no such signal, and with no traffic
513
287
  // on the wire, we might be always behind.
514
- // See comment at the end of setupNewSuccessfulConnection()
515
- logIfFalse(this.handler !== undefined || !fetchOpsFromStorage, this.logger, "CantFetchWithoutBaseline"); // can't fetch if no baseline
288
+ // See comment at the end of "connect" handler
516
289
  if (fetchOpsFromStorage) {
517
- this.fetchMissingDeltas(args.reason, this.lastQueuedSequenceNumber);
518
- }
519
- const docService = this.serviceProvider();
520
- assert(docService !== undefined, 0x2a7 /* "Container is not attached" */);
521
- if (((_c = docService.policies) === null || _c === void 0 ? void 0 : _c.storageOnly) === true) {
522
- const connection = new NoDeltaStream();
523
- this.connectionP = Promise.resolve(connection); // to keep setupNewSuccessfulConnection happy
524
- this.setupNewSuccessfulConnection(connection, "read");
525
- return connection;
526
- }
527
- // The promise returned from connectCore will settle with a resolved connection or reject with error
528
- const connectCore = async () => {
529
- let connection;
530
- let delayMs = InitialReconnectDelayInMs;
531
- let connectRepeatCount = 0;
532
- const connectStartTime = performance.now();
533
- let lastError;
534
- // This loop will keep trying to connect until successful, with a delay between each iteration.
535
- while (connection === undefined) {
536
- if (this.closed) {
537
- throw new Error("Attempting to connect a closed DeltaManager");
538
- }
539
- connectRepeatCount++;
540
- try {
541
- this.client.mode = requestedMode;
542
- connection = await docService.connectToDeltaStream(this.client);
543
- if (connection.disposed) {
544
- // Nobody observed this connection, so drop it on the floor and retry.
545
- this.logger.sendTelemetryEvent({ eventName: "ReceivedClosedConnection" });
546
- connection = undefined;
547
- }
548
- }
549
- catch (origError) {
550
- if (typeof origError === "object" && origError !== null &&
551
- (origError === null || origError === void 0 ? void 0 : origError.errorType) === DeltaStreamConnectionForbiddenError.errorType) {
552
- connection = new NoDeltaStream();
553
- requestedMode = "read";
554
- break;
555
- }
556
- // Socket.io error when we connect to wrong socket, or hit some multiplexing bug
557
- if (!canRetryOnError(origError)) {
558
- const error = normalizeError(origError, { props: fatalConnectErrorProp });
559
- this.close(error);
560
- throw error;
561
- }
562
- // Log error once - we get too many errors in logs when we are offline,
563
- // and unfortunately there is no reliable way to detect that.
564
- if (connectRepeatCount === 1) {
565
- logNetworkFailure(this.logger, {
566
- delay: delayMs,
567
- eventName: "DeltaConnectionFailureToConnect",
568
- duration: TelemetryLogger.formatTick(performance.now() - connectStartTime),
569
- }, origError);
570
- }
571
- lastError = origError;
572
- const retryDelayFromError = getRetryDelayFromError(origError);
573
- delayMs = retryDelayFromError !== null && retryDelayFromError !== void 0 ? retryDelayFromError : Math.min(delayMs * 2, MaxReconnectDelayInMs);
574
- if (retryDelayFromError !== undefined) {
575
- this.emitDelayInfo(this.deltaStreamDelayId, retryDelayFromError, origError);
576
- }
577
- await waitForConnectedState(delayMs);
578
- }
579
- }
580
- // If we retried more than once, log an event about how long it took
581
- if (connectRepeatCount > 1) {
582
- this.logger.sendTelemetryEvent({
583
- eventName: "MultipleDeltaConnectionFailures",
584
- attempts: connectRepeatCount,
585
- duration: TelemetryLogger.formatTick(performance.now() - connectStartTime),
586
- }, lastError);
587
- }
588
- this.setupNewSuccessfulConnection(connection, requestedMode);
589
- return connection;
590
- };
591
- // This promise settles as soon as we know the outcome of the connection attempt
592
- // Set it upfront, such that if connection is established (NoDeltaConnection) or rejected (bug in
593
- // connectToDeltaStream() implementation - throwing exception vs. returning rejected promise) in
594
- // synchronous way, we have this.connectionP setup for all the code to assert correctness of the flow.
595
- const deferred = new Deferred();
596
- this.connectionP = deferred.promise;
597
- // Regardless of how the connection attempt concludes, we'll clear the promise and remove the listener
598
- // Reject the connection promise if the DeltaManager gets closed during connection
599
- const cleanupAndReject = (error) => {
600
- this.connectionP = undefined;
601
- this.removeListener("closed", cleanupAndReject);
602
- // This error came from some logic error in this file. Fail-fast to learn and fix the issue faster
603
- const normalizedError = normalizeError(error, { props: fatalConnectErrorProp });
604
- this.close(normalizedError);
605
- deferred.reject(normalizedError);
606
- };
607
- this.on("closed", cleanupAndReject);
608
- // Attempt the connection
609
- connectCore().then((connection) => {
610
- this.removeListener("closed", cleanupAndReject);
611
- deferred.resolve(connection);
612
- }).catch(cleanupAndReject);
613
- return this.connectionP;
614
- }
615
- flush() {
616
- if (this.messageBuffer.length === 0) {
617
- return;
618
- }
619
- // The prepareFlush event allows listeners to append metadata to the batch prior to submission.
620
- this.emit("prepareSend", this.messageBuffer);
621
- this._outbound.push(this.messageBuffer);
622
- this.messageBuffer = [];
623
- }
624
- /**
625
- * Submits the given delta returning the client sequence number for the message. Contents is the actual
626
- * contents of the message. appData is optional metadata that can be attached to the op by the app.
627
- *
628
- * If batch is set to true then the submit will be batched - and as a result guaranteed to be ordered sequentially
629
- * in the global sequencing space. The batch will be flushed either when flush is called or when a non-batched
630
- * op is submitted.
631
- */
632
- submit(type, contents, batch = false, metadata) {
633
- // TODO need to fail if gets too large
634
- // const serializedContent = JSON.stringify(this.messageBuffer);
635
- // const maxOpSize = this.context.deltaManager.maxMessageSize;
636
- var _a, _b;
637
- if (this.readOnlyInfo.readonly === true) {
638
- assert(this.readOnlyInfo.readonly === true, 0x1f0 /* "Unexpected mismatch in readonly" */);
639
- const error = new GenericError("deltaManagerReadonlySubmit", undefined /* error */, {
640
- readonly: this.readOnlyInfo.readonly,
641
- forcedReadonly: this.readOnlyInfo.forced,
642
- readonlyPermissions: this.readOnlyInfo.permissions,
643
- storageOnly: this.readOnlyInfo.storageOnly,
644
- });
645
- this.close(error);
646
- return -1;
647
- }
648
- // reset clientSequenceNumber if we are using new clientId.
649
- // we keep info about old connection as long as possible to be able to account for all non-acked ops
650
- // that we pick up on next connection.
651
- assert(!!this.connection, 0x0e4 /* "Lost old connection!" */);
652
- if (this.lastSubmittedClientId !== ((_a = this.connection) === null || _a === void 0 ? void 0 : _a.clientId)) {
653
- this.lastSubmittedClientId = (_b = this.connection) === null || _b === void 0 ? void 0 : _b.clientId;
654
- this.clientSequenceNumber = 0;
655
- this.clientSequenceNumberObserved = 0;
656
- }
657
- // If connection is "read" or implicit "read" (got leave op for "write" connection),
658
- // then op can't make it through - we will get a nack if op is sent.
659
- // We can short-circuit this process.
660
- // Note that we also want nacks to be rare and be treated as catastrophic failures.
661
- // Be careful with reentrancy though - disconnected event should not be be raised in the
662
- // middle of the current workflow, but rather on clean stack!
663
- if (this.connectionMode === "read" || this.downgradedConnection) {
664
- if (!this.pendingReconnect) {
665
- this.pendingReconnect = true;
666
- Promise.resolve().then(async () => {
667
- if (this.pendingReconnect) { // still valid?
668
- return this.reconnectOnErrorCore("write", // connectionMode
669
- "Switch to write");
670
- }
671
- })
672
- .catch(() => { });
673
- }
674
- // Can return -1 here, but no other path does it (other than error path in Container),
675
- // so it's better not to introduce new states.
676
- return ++this.clientSequenceNumber;
677
- }
678
- const service = this.clientDetails.type === undefined || this.clientDetails.type === ""
679
- ? "unknown"
680
- : this.clientDetails.type;
681
- // Start adding trace for the op.
682
- const traces = [
683
- {
684
- action: "start",
685
- service,
686
- timestamp: Date.now(),
687
- }
688
- ];
689
- const message = {
690
- clientSequenceNumber: ++this.clientSequenceNumber,
691
- contents: JSON.stringify(contents),
692
- metadata,
693
- referenceSequenceNumber: this.lastProcessedSequenceNumber,
694
- traces,
695
- type,
696
- };
697
- if (type === MessageType.NoOp) {
698
- this.trailingNoopCount++;
699
- }
700
- else {
701
- this.trailingNoopCount = 0;
702
- }
703
- this.emit("submitOp", message);
704
- if (!batch) {
705
- this.flush();
706
- this.messageBuffer.push(message);
707
- this.flush();
708
- }
709
- else {
710
- this.messageBuffer.push(message);
711
- }
712
- return message.clientSequenceNumber;
713
- }
714
- submitSignal(content) {
715
- if (this.connection !== undefined) {
716
- this.connection.submitSignal(content);
717
- }
718
- else {
719
- this.logger.sendErrorEvent({ eventName: "submitSignalDisconnected" });
290
+ this.fetchMissingDeltas(args.reason);
720
291
  }
292
+ this.connectionManager.connect(args.mode);
721
293
  }
722
294
  async getDeltas(from, // inclusive
723
295
  to, // exclusive
@@ -729,9 +301,6 @@ export class DeltaManager extends TypedEventEmitter {
729
301
  if (this.deltaStorage === undefined) {
730
302
  this.deltaStorage = await docService.connectToDeltaStorage();
731
303
  }
732
- assert(this.closeAbortController.signal.onabort === null, 0x1e8 /* "reentrancy" */);
733
- const controller = new AbortController();
734
- this.closeAbortController.signal.onabort = () => controller.abort();
735
304
  let cancelFetch;
736
305
  if (to !== undefined) {
737
306
  const lastExpectedOp = to - 1; // make it inclusive!
@@ -739,7 +308,7 @@ export class DeltaManager extends TypedEventEmitter {
739
308
  // received through delta stream. Validate that before moving forward.
740
309
  if (this.lastQueuedSequenceNumber >= lastExpectedOp) {
741
310
  this.logger.sendPerformanceEvent(Object.assign({ reason: this.fetchReason, eventName: "ExtraStorageCall", early: true, from,
742
- to }, this.connectionStateProps));
311
+ to }, this.connectionManager.connectionVerboseProps));
743
312
  return;
744
313
  }
745
314
  // Be prepared for the case where webSocket would receive the ops that we are trying to fill through
@@ -756,6 +325,7 @@ export class DeltaManager extends TypedEventEmitter {
756
325
  // That said, if we have socket connection, make sure we got ops up to checkpointSequenceNumber!
757
326
  cancelFetch = (op) => op.sequenceNumber >= this.lastObservedSeqNumber;
758
327
  }
328
+ const controller = new AbortController();
759
329
  let opsFromFetch = false;
760
330
  const opListener = (op) => {
761
331
  assert(op.sequenceNumber === this.lastQueuedSequenceNumber, 0x23a /* "seq#'s" */);
@@ -767,8 +337,10 @@ export class DeltaManager extends TypedEventEmitter {
767
337
  this._inbound.off("push", opListener);
768
338
  }
769
339
  };
770
- this._inbound.on("push", opListener);
771
340
  try {
341
+ this._inbound.on("push", opListener);
342
+ assert(this.closeAbortController.signal.onabort === null, 0x1e8 /* "reentrancy" */);
343
+ this.closeAbortController.signal.onabort = () => controller.abort();
772
344
  const stream = this.deltaStorage.fetchMessages(from, // inclusive
773
345
  to, // exclusive
774
346
  controller.signal, cacheOnly, this.fetchReason);
@@ -788,9 +360,9 @@ export class DeltaManager extends TypedEventEmitter {
788
360
  }
789
361
  }
790
362
  finally {
791
- assert(!opsFromFetch, 0x289 /* "logic error" */);
792
363
  this.closeAbortController.signal.onabort = null;
793
364
  this._inbound.off("push", opListener);
365
+ assert(!opsFromFetch, 0x289 /* "logic error" */);
794
366
  }
795
367
  }
796
368
  /**
@@ -801,16 +373,9 @@ export class DeltaManager extends TypedEventEmitter {
801
373
  return;
802
374
  }
803
375
  this.closed = true;
804
- // Ensure that things like triggerConnect() will short circuit
805
- this._reconnectMode = ReconnectMode.Never;
376
+ this.connectionManager.dispose(error);
806
377
  this.closeAbortController.abort();
807
- const disconnectReason = error !== undefined
808
- ? `Closing DeltaManager (${error.message})`
809
- : "Closing DeltaManager";
810
- // This raises "disconnect" event if we have active connection.
811
- this.disconnectFromDeltaStream(disconnectReason);
812
378
  this._inbound.clear();
813
- this._outbound.clear();
814
379
  this._inboundSignal.clear();
815
380
  // eslint-disable-next-line @typescript-eslint/no-floating-promises
816
381
  this._inbound.pause();
@@ -818,10 +383,6 @@ export class DeltaManager extends TypedEventEmitter {
818
383
  this._inboundSignal.pause();
819
384
  // Drop pending messages - this will ensure catchUp() does not go into infinite loop
820
385
  this.pending = [];
821
- // Notify everyone we are in read-only state.
822
- // Useful for data stores in case we hit some critical error,
823
- // to switch to a mode where user edits are not accepted
824
- this.set_readonlyPermissions(true);
825
386
  // This needs to be the last thing we do (before removing listeners), as it causes
826
387
  // Container to dispose context and break ability of data stores / runtime to "hear"
827
388
  // from delta manager, including notification (above) about readonly state.
@@ -834,6 +395,20 @@ export class DeltaManager extends TypedEventEmitter {
834
395
  this.timeTillThrottling = 0;
835
396
  }
836
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
+ }
837
412
  /**
838
413
  * Emit info about a delay in service communication on account of throttling.
839
414
  * @param id - Id of the connection that is delayed
@@ -849,183 +424,6 @@ export class DeltaManager extends TypedEventEmitter {
849
424
  this.emit("throttled", throttlingWarning);
850
425
  }
851
426
  }
852
- /**
853
- * Once we've successfully gotten a connection, we need to set up state, attach event listeners, and process
854
- * initial messages.
855
- * @param connection - The newly established connection
856
- */
857
- setupNewSuccessfulConnection(connection, requestedMode) {
858
- // Old connection should have been cleaned up before establishing a new one
859
- assert(this.connection === undefined, 0x0e6 /* "old connection exists on new connection setup" */);
860
- assert(this.connectionP !== undefined || this.closed, 0x27f /* "reentrancy may result in incorrect behavior" */);
861
- assert(!connection.disposed, 0x28a /* "can't be disposed - Callers need to ensure that!" */);
862
- this.connectionP = undefined;
863
- this.connection = connection;
864
- // Does information in scopes & mode matches?
865
- // If we asked for "write" and got "read", then file is read-only
866
- // But if we ask read, server can still give us write.
867
- const readonly = !connection.claims.scopes.includes(ScopeType.DocWrite);
868
- // This connection mode validation logic is moving to the driver layer in 0.44. These two asserts can be
869
- // removed after those packages have released and become ubiquitous.
870
- assert(requestedMode === "read" || readonly === (this.connectionMode === "read"), 0x0e7 /* "claims/connectionMode mismatch" */);
871
- assert(!readonly || this.connectionMode === "read", 0x0e8 /* "readonly perf with write connection" */);
872
- this.set_readonlyPermissions(readonly);
873
- this.refreshDelayInfo(this.deltaStreamDelayId);
874
- if (this.closed) {
875
- // Raise proper events, Log telemetry event and close connection.
876
- this.disconnectFromDeltaStream("DeltaManager already closed");
877
- return;
878
- }
879
- // We cancel all ops on lost of connectivity, and rely on DDSes to resubmit them.
880
- // Semantics are not well defined for batches (and they are broken right now on disconnects anyway),
881
- // but it's safe to assume (until better design is put into place) that batches should not exist
882
- // across multiple connections. Right now we assume runtime will not submit any ops in disconnected
883
- // state. As requirements change, so should these checks.
884
- assert(this.messageBuffer.length === 0, 0x0e9 /* "messageBuffer is not empty on new connection" */);
885
- this._outbound.resume();
886
- connection.on("op", this.opHandler);
887
- connection.on("signal", this.signalHandler);
888
- connection.on("nack", this.nackHandler);
889
- connection.on("disconnect", this.disconnectHandler);
890
- connection.on("error", this.errorHandler);
891
- connection.on("pong", this.pongHandler);
892
- // Initial messages are always sorted. However, due to early op handler installed by drivers and appending those
893
- // ops to initialMessages, resulting set is no longer sorted, which would result in client hitting storage to
894
- // fill in gap. We will recover by cancelling this request once we process remaining ops, but it's a waste that
895
- // we could avoid
896
- const initialMessages = connection.initialMessages.sort((a, b) => a.sequenceNumber - b.sequenceNumber);
897
- this.connectionStateProps = {
898
- connectionLastQueuedSequenceNumber: this.lastQueuedSequenceNumber,
899
- connectionLastObservedSeqNumber: this.lastObservedSeqNumber,
900
- clientId: connection.clientId,
901
- mode: connection.mode,
902
- };
903
- if (connection.relayServiceAgent !== undefined) {
904
- this.connectionStateProps.relayServiceAgent = connection.relayServiceAgent;
905
- }
906
- this._hasCheckpointSequenceNumber = false;
907
- // Some storages may provide checkpointSequenceNumber to identify how far client is behind.
908
- const checkpointSequenceNumber = connection.checkpointSequenceNumber;
909
- if (checkpointSequenceNumber !== undefined) {
910
- this._hasCheckpointSequenceNumber = true;
911
- this.updateLatestKnownOpSeqNumber(checkpointSequenceNumber);
912
- }
913
- // Update knowledge of how far we are behind, before raising "connect" event
914
- // This is duplication of what enqueueMessages() does, but we have to raise event before we get there,
915
- // so duplicating update logic here as well.
916
- const last = initialMessages.length > 0 ? initialMessages[initialMessages.length - 1].sequenceNumber : -1;
917
- if (initialMessages.length > 0) {
918
- this._hasCheckpointSequenceNumber = true;
919
- this.updateLatestKnownOpSeqNumber(last);
920
- }
921
- // Notify of the connection
922
- // WARNING: This has to happen before processInitialMessages() call below.
923
- // If not, we may not update Container.pendingClientId in time before seeing our own join session op.
924
- this.emit("connect", DeltaManager.detailsFromConnection(connection), this._hasCheckpointSequenceNumber ? this.lastObservedSeqNumber - this.lastSequenceNumber : undefined);
925
- this.enqueueMessages(initialMessages, this.connectFirstConnection ? "InitialOps" : "ReconnectOps");
926
- if (connection.initialSignals !== undefined) {
927
- for (const signal of connection.initialSignals) {
928
- this._inboundSignal.push(signal);
929
- }
930
- }
931
- // If we got some initial ops, then we know the gap and call above fetched ops to fill it.
932
- // Same is true for "write" mode even if we have no ops - we will get self "join" ops very very soon.
933
- // However if we are connecting as view-only, then there is no good signal to realize if client is behind.
934
- // Thus we have to hit storage to see if any ops are there.
935
- if (initialMessages.length === 0) {
936
- if (checkpointSequenceNumber !== undefined) {
937
- // We know how far we are behind (roughly). If it's non-zero gap, fetch ops right away.
938
- if (checkpointSequenceNumber > this.lastQueuedSequenceNumber) {
939
- this.fetchMissingDeltas("AfterConnection", this.lastQueuedSequenceNumber);
940
- }
941
- // we do not know the gap, and we will not learn about it if socket is quite - have to ask.
942
- }
943
- else if (connection.mode === "read") {
944
- this.fetchMissingDeltas("AfterReadConnection", this.lastQueuedSequenceNumber);
945
- }
946
- }
947
- else {
948
- this.connectionStateProps.connectionInitialOpsFrom = initialMessages[0].sequenceNumber;
949
- this.connectionStateProps.connectionInitialOpsTo = last + 1;
950
- }
951
- this.connectFirstConnection = false;
952
- }
953
- /**
954
- * Disconnect the current connection.
955
- * @param reason - Text description of disconnect reason to emit with disconnect event
956
- */
957
- disconnectFromDeltaStream(reason) {
958
- this.pendingReconnect = false;
959
- this.downgradedConnection = false;
960
- if (this.connection === undefined) {
961
- return false;
962
- }
963
- assert(this.connectionP === undefined, 0x27b /* "reentrancy may result in incorrect behavior" */);
964
- const connection = this.connection;
965
- // Avoid any re-entrancy - clear object reference
966
- this.connection = undefined;
967
- // Remove listeners first so we don't try to retrigger this flow accidentally through reconnectOnError
968
- connection.off("op", this.opHandler);
969
- connection.off("signal", this.signalHandler);
970
- connection.off("nack", this.nackHandler);
971
- connection.off("disconnect", this.disconnectHandler);
972
- connection.off("error", this.errorHandler);
973
- connection.off("pong", this.pongHandler);
974
- // eslint-disable-next-line @typescript-eslint/no-floating-promises
975
- this._outbound.pause();
976
- this._outbound.clear();
977
- this.emit("disconnect", reason);
978
- connection.dispose();
979
- this.connectionStateProps = {};
980
- return true;
981
- }
982
- /**
983
- * Disconnect the current connection and reconnect.
984
- * @param connection - The connection that wants to reconnect - no-op if it's different from this.connection
985
- * @param requestedMode - Read or write
986
- * @param error - Error reconnect information including whether or not to reconnect
987
- * @returns A promise that resolves when the connection is reestablished or we stop trying
988
- */
989
- async reconnectOnError(requestedMode, error) {
990
- return this.reconnectOnErrorCore(requestedMode, error.message, error);
991
- }
992
- /**
993
- * Disconnect the current connection and reconnect.
994
- * @param connection - The connection that wants to reconnect - no-op if it's different from this.connection
995
- * @param requestedMode - Read or write
996
- * @param error - Error reconnect information including whether or not to reconnect
997
- * @returns A promise that resolves when the connection is reestablished or we stop trying
998
- */
999
- async reconnectOnErrorCore(requestedMode, disconnectMessage, error) {
1000
- // We quite often get protocol errors before / after observing nack/disconnect
1001
- // we do not want to run through same sequence twice.
1002
- // If we're already disconnected/disconnecting it's not appropriate to call this again.
1003
- assert(this.connection !== undefined, 0x0eb /* "Missing connection for reconnect" */);
1004
- this.disconnectFromDeltaStream(disconnectMessage);
1005
- const canRetry = error !== undefined ? canRetryOnError(error) : true;
1006
- // If reconnection is not an option, close the DeltaManager
1007
- if (!canRetry) {
1008
- this.close(normalizeError(error, { props: fatalConnectErrorProp }));
1009
- }
1010
- else if (this.reconnectMode === ReconnectMode.Never) {
1011
- // Do not raise container error if we are closing just because we lost connection.
1012
- // Those errors (like IdleDisconnect) would show up in telemetry dashboards and
1013
- // are very misleading, as first initial reaction - some logic is broken.
1014
- this.close();
1015
- }
1016
- // If closed then we can't reconnect
1017
- if (this.closed) {
1018
- return;
1019
- }
1020
- if (this.reconnectMode === ReconnectMode.Enabled) {
1021
- const delayMs = error !== undefined ? getRetryDelayFromError(error) : undefined;
1022
- if (delayMs !== undefined) {
1023
- this.emitDelayInfo(this.deltaStreamDelayId, delayMs, error);
1024
- await waitForConnectedState(delayMs);
1025
- }
1026
- this.triggerConnect({ reason: "reconnect", mode: requestedMode, fetchOpsFromStorage: false });
1027
- }
1028
- }
1029
427
  // returns parts of message (in string format) that should never change for a given message.
1030
428
  // Used for message comparison. It attempts to avoid comparing fields that potentially may differ.
1031
429
  // for example, it's not clear if serverMetadata or timestamp property is a property of message or server state.
@@ -1037,7 +435,7 @@ export class DeltaManager extends TypedEventEmitter {
1037
435
  return `${m.clientId}-${m.type}-${m.minimumSequenceNumber}-${m.referenceSequenceNumber}-${m.timestamp}`;
1038
436
  }
1039
437
  enqueueMessages(messages, reason, allowGaps = false) {
1040
- var _a, _b, _c;
438
+ var _a, _b;
1041
439
  if (this.handler === undefined) {
1042
440
  // We did not setup handler yet.
1043
441
  // This happens when we connect to web socket faster than we get attributes for container
@@ -1097,7 +495,7 @@ export class DeltaManager extends TypedEventEmitter {
1097
495
  // correctly take into account pending ops.
1098
496
  if (eventName !== undefined) {
1099
497
  this.logger.sendPerformanceEvent(Object.assign({ eventName,
1100
- 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));
1101
499
  }
1102
500
  }
1103
501
  this.updateLatestKnownOpSeqNumber(messages[messages.length - 1].sequenceNumber);
@@ -1113,7 +511,7 @@ export class DeltaManager extends TypedEventEmitter {
1113
511
  const message2 = this.comparableMessagePayload(message);
1114
512
  if (message1 !== message2) {
1115
513
  const error = new NonRetryableError("twoMessagesWithSameSeqNumAndDifferentPayload", undefined, DriverErrorType.fileOverwrittenInStorage, {
1116
- clientId: (_c = this.connection) === null || _c === void 0 ? void 0 : _c.clientId,
514
+ clientId: this.connectionManager.clientId,
1117
515
  sequenceNumber: message.sequenceNumber,
1118
516
  message1,
1119
517
  message2,
@@ -1124,7 +522,7 @@ export class DeltaManager extends TypedEventEmitter {
1124
522
  }
1125
523
  else if (message.sequenceNumber !== this.lastQueuedSequenceNumber + 1) {
1126
524
  this.pending.push(message);
1127
- this.fetchMissingDeltas(reason, this.lastQueuedSequenceNumber, message.sequenceNumber);
525
+ this.fetchMissingDeltas(reason, message.sequenceNumber);
1128
526
  }
1129
527
  else {
1130
528
  this.lastQueuedSequenceNumber = message.sequenceNumber;
@@ -1138,56 +536,34 @@ export class DeltaManager extends TypedEventEmitter {
1138
536
  this.prevEnqueueMessagesReason = this.pending.length > 0 ? "unknown" : reason;
1139
537
  }
1140
538
  processInboundMessage(message) {
1141
- var _a, _b, _c;
1142
539
  const startTime = Date.now();
1143
540
  this.lastProcessedMessage = message;
1144
541
  // All non-system messages are coming from some client, and should have clientId
1145
542
  // System messages may have no clientId (but some do, like propose, noop, summarize)
1146
543
  assert(message.clientId !== undefined
1147
544
  || isSystemMessage(message), 0x0ed /* "non-system message have to have clientId" */);
1148
- // if we have connection, and message is local, then we better treat is as local!
1149
- assert(this.connection === undefined
1150
- || this.connection.clientId !== message.clientId
1151
- || this.lastSubmittedClientId === message.clientId, 0x0ee /* "Not accounting local messages correctly" */);
1152
- if (this.lastSubmittedClientId !== undefined && this.lastSubmittedClientId === message.clientId) {
1153
- const clientSequenceNumber = message.clientSequenceNumber;
1154
- assert(this.clientSequenceNumberObserved < clientSequenceNumber, 0x0ef /* "client seq# not growing" */);
1155
- assert(clientSequenceNumber <= this.clientSequenceNumber, 0x0f0 /* "Incoming local client seq# > generated by this client" */);
1156
- this.clientSequenceNumberObserved = clientSequenceNumber;
1157
- }
1158
545
  // TODO Remove after SPO picks up the latest build.
1159
546
  if (typeof message.contents === "string"
1160
547
  && message.contents !== ""
1161
548
  && message.type !== MessageType.ClientLeave) {
1162
549
  message.contents = JSON.parse(message.contents);
1163
550
  }
1164
- if (message.type === MessageType.ClientLeave) {
1165
- const systemLeaveMessage = message;
1166
- const clientId = JSON.parse(systemLeaveMessage.data);
1167
- if (clientId === ((_a = this.connection) === null || _a === void 0 ? void 0 : _a.clientId)) {
1168
- // We have been kicked out from quorum
1169
- this.logger.sendPerformanceEvent({ eventName: "ReadConnectionTransition" });
1170
- this.downgradedConnection = true;
1171
- }
1172
- }
551
+ this.connectionManager.beforeProcessingIncomingOp(message);
1173
552
  // Add final ack trace.
1174
553
  if (message.traces !== undefined && message.traces.length > 0) {
1175
- const service = this.clientDetails.type === undefined || this.clientDetails.type === ""
1176
- ? "unknown"
1177
- : this.clientDetails.type;
1178
554
  message.traces.push({
1179
555
  action: "end",
1180
- service,
556
+ service: "client",
1181
557
  timestamp: Date.now(),
1182
558
  });
1183
559
  }
1184
560
  // Watch the minimum sequence number and be ready to update as needed
1185
561
  if (this.minSequenceNumber > message.minimumSequenceNumber) {
1186
- 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 }));
1187
563
  }
1188
564
  this.minSequenceNumber = message.minimumSequenceNumber;
1189
565
  if (message.sequenceNumber !== this.lastProcessedSequenceNumber + 1) {
1190
- 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 }));
1191
567
  }
1192
568
  this.lastProcessedSequenceNumber = message.sequenceNumber;
1193
569
  // a bunch of code assumes that this is true
@@ -1209,15 +585,15 @@ export class DeltaManager extends TypedEventEmitter {
1209
585
  /**
1210
586
  * Retrieves the missing deltas between the given sequence numbers
1211
587
  */
1212
- fetchMissingDeltas(reasonArg, lastKnowOp, to) {
1213
- this.fetchMissingDeltasCore(reasonArg, false /* cacheOnly */, lastKnowOp, to).catch((error) => {
588
+ fetchMissingDeltas(reasonArg, to) {
589
+ this.fetchMissingDeltasCore(reasonArg, false /* cacheOnly */, to).catch((error) => {
1214
590
  this.logger.sendErrorEvent({ eventName: "fetchMissingDeltasException" }, error);
1215
591
  });
1216
592
  }
1217
593
  /**
1218
594
  * Retrieves the missing deltas between the given sequence numbers
1219
595
  */
1220
- async fetchMissingDeltasCore(reason, cacheOnly, lastKnowOp, to) {
596
+ async fetchMissingDeltasCore(reason, cacheOnly, to) {
1221
597
  var _a;
1222
598
  // Exit out early if we're already fetching deltas
1223
599
  if (this.fetchReason !== undefined) {
@@ -1229,12 +605,11 @@ export class DeltaManager extends TypedEventEmitter {
1229
605
  }
1230
606
  if (this.handler === undefined) {
1231
607
  // We do not poses yet any information
1232
- assert(lastKnowOp === 0, 0x26b /* "initial state" */);
608
+ assert(this.lastQueuedSequenceNumber === 0, 0x26b /* "initial state" */);
1233
609
  return;
1234
610
  }
1235
611
  try {
1236
- assert(lastKnowOp === this.lastQueuedSequenceNumber, 0x0f1 /* "from arg" */);
1237
- let from = lastKnowOp + 1;
612
+ let from = this.lastQueuedSequenceNumber + 1;
1238
613
  const n = (_a = this.previouslyProcessedMessage) === null || _a === void 0 ? void 0 : _a.sequenceNumber;
1239
614
  if (n !== undefined) {
1240
615
  // If we already processed at least one op, then we have this.previouslyProcessedMessage populated
@@ -1242,7 +617,7 @@ export class DeltaManager extends TypedEventEmitter {
1242
617
  // Knowing about this mechanism, we could ask for op we already observed to increase validation.
1243
618
  // This is especially useful when coming out of offline mode or loading from
1244
619
  // very old cached (by client / driver) snapshot.
1245
- assert(n === lastKnowOp, 0x0f2 /* "previouslyProcessedMessage" */);
620
+ assert(n === this.lastQueuedSequenceNumber, 0x0f2 /* "previouslyProcessedMessage" */);
1246
621
  assert(from > 1, 0x0f3 /* "not positive" */);
1247
622
  from--;
1248
623
  }
@@ -1290,7 +665,7 @@ export class DeltaManager extends TypedEventEmitter {
1290
665
  // (the other 50%), and thus these errors below should be looked at even if code below results in
1291
666
  // recovery.
1292
667
  if (this.lastQueuedSequenceNumber < this.lastObservedSeqNumber) {
1293
- this.fetchMissingDeltas("OpsBehind", this.lastQueuedSequenceNumber);
668
+ this.fetchMissingDeltas("OpsBehind");
1294
669
  }
1295
670
  }
1296
671
  }