@fluidframework/container-loader 2.80.0 → 2.81.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/CHANGELOG.md +4 -0
  2. package/dist/connectionManager.d.ts.map +1 -1
  3. package/dist/connectionManager.js +2 -0
  4. package/dist/connectionManager.js.map +1 -1
  5. package/dist/container.js +1 -1
  6. package/dist/container.js.map +1 -1
  7. package/dist/deltaManager.d.ts.map +1 -1
  8. package/dist/deltaManager.js +2 -0
  9. package/dist/deltaManager.js.map +1 -1
  10. package/dist/packageVersion.d.ts +1 -1
  11. package/dist/packageVersion.js +1 -1
  12. package/dist/packageVersion.js.map +1 -1
  13. package/dist/serializedStateManager.d.ts +7 -11
  14. package/dist/serializedStateManager.d.ts.map +1 -1
  15. package/dist/serializedStateManager.js +17 -77
  16. package/dist/serializedStateManager.js.map +1 -1
  17. package/dist/snapshotRefresher.d.ts +68 -0
  18. package/dist/snapshotRefresher.d.ts.map +1 -0
  19. package/dist/snapshotRefresher.js +167 -0
  20. package/dist/snapshotRefresher.js.map +1 -0
  21. package/eslint.config.mts +4 -4
  22. package/lib/connectionManager.d.ts.map +1 -1
  23. package/lib/connectionManager.js +2 -0
  24. package/lib/connectionManager.js.map +1 -1
  25. package/lib/container.js +1 -1
  26. package/lib/container.js.map +1 -1
  27. package/lib/deltaManager.d.ts.map +1 -1
  28. package/lib/deltaManager.js +2 -0
  29. package/lib/deltaManager.js.map +1 -1
  30. package/lib/packageVersion.d.ts +1 -1
  31. package/lib/packageVersion.js +1 -1
  32. package/lib/packageVersion.js.map +1 -1
  33. package/lib/serializedStateManager.d.ts +7 -11
  34. package/lib/serializedStateManager.d.ts.map +1 -1
  35. package/lib/serializedStateManager.js +18 -78
  36. package/lib/serializedStateManager.js.map +1 -1
  37. package/lib/snapshotRefresher.d.ts +68 -0
  38. package/lib/snapshotRefresher.d.ts.map +1 -0
  39. package/lib/snapshotRefresher.js +163 -0
  40. package/lib/snapshotRefresher.js.map +1 -0
  41. package/package.json +15 -15
  42. package/src/connectionManager.ts +2 -0
  43. package/src/container.ts +1 -1
  44. package/src/deltaManager.ts +2 -0
  45. package/src/packageVersion.ts +1 -1
  46. package/src/serializedStateManager.ts +27 -99
  47. package/src/snapshotRefresher.ts +201 -0
  48. package/.eslintrc.cjs +0 -24
@@ -13,36 +13,15 @@ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (
13
13
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
14
14
  return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
15
15
  };
16
- var _RefreshPromiseTracker_promise, _SerializedStateManager_snapshotRefreshEnabled, _SerializedStateManager_disposed;
16
+ var _SerializedStateManager_disposed;
17
17
  import { stringToBuffer } from "@fluid-internal/client-utils";
18
- import { Timer, assert } from "@fluidframework/core-utils/internal";
18
+ import { assert } from "@fluidframework/core-utils/internal";
19
19
  import { FetchSource, } from "@fluidframework/driver-definitions/internal";
20
20
  import { getSnapshotTree, isInstanceOfISnapshot } from "@fluidframework/driver-utils/internal";
21
21
  import { PerformanceEvent, UsageError, createChildMonitoringContext, } from "@fluidframework/telemetry-utils/internal";
22
22
  import { getBlobContentsFromTree, } from "./containerStorageAdapter.js";
23
+ import { SnapshotRefresher } from "./snapshotRefresher.js";
23
24
  import { convertISnapshotToSnapshotWithBlobs, convertSnapshotToSnapshotInfo, getDocumentAttributes, } from "./utils.js";
24
- class RefreshPromiseTracker {
25
- get hasPromise() {
26
- return __classPrivateFieldGet(this, _RefreshPromiseTracker_promise, "f") !== undefined;
27
- }
28
- get Promise() {
29
- return __classPrivateFieldGet(this, _RefreshPromiseTracker_promise, "f");
30
- }
31
- constructor(catchHandler) {
32
- this.catchHandler = catchHandler;
33
- _RefreshPromiseTracker_promise.set(this, void 0);
34
- }
35
- setPromise(p) {
36
- if (this.hasPromise) {
37
- throw new Error("Cannot set promise while promise exists");
38
- }
39
- __classPrivateFieldSet(this, _RefreshPromiseTracker_promise, p.finally(() => {
40
- __classPrivateFieldSet(this, _RefreshPromiseTracker_promise, undefined, "f");
41
- }), "f");
42
- p.catch(this.catchHandler);
43
- }
44
- }
45
- _RefreshPromiseTracker_promise = new WeakMap();
46
25
  /**
47
26
  * Helper class to manage the state of the container needed for proper serialization.
48
27
  *
@@ -64,25 +43,14 @@ export class SerializedStateManager {
64
43
  this.containerDirty = containerDirty;
65
44
  this.supportGetSnapshotApi = supportGetSnapshotApi;
66
45
  this.processedOps = [];
67
- this.refreshTracker = new RefreshPromiseTracker(
68
- // eslint-disable-next-line unicorn/consistent-function-scoping
69
- (error) => this.mc.logger.sendErrorEvent({
70
- eventName: "RefreshLatestSnapshotFailed",
71
- }, error));
72
46
  this.lastSavedOpSequenceNumber = 0;
73
- this.snapshotRefreshTimeoutMs = 60 * 60 * 24 * 1000;
74
- _SerializedStateManager_snapshotRefreshEnabled.set(this, void 0);
75
47
  _SerializedStateManager_disposed.set(this, false);
76
48
  this.mc = createChildMonitoringContext({
77
49
  logger: subLogger,
78
50
  namespace: "serializedStateManager",
79
51
  });
80
- this.snapshotRefreshTimeoutMs = snapshotRefreshTimeoutMs ?? this.snapshotRefreshTimeoutMs;
81
- __classPrivateFieldSet(this, _SerializedStateManager_snapshotRefreshEnabled, this.offlineLoadEnabled &&
82
- (this.mc.config.getBoolean("Fluid.Container.enableOfflineSnapshotRefresh") ??
83
- this.mc.config.getBoolean("Fluid.Container.enableOfflineFull")) === true, "f");
84
- this.refreshTimer = __classPrivateFieldGet(this, _SerializedStateManager_snapshotRefreshEnabled, "f")
85
- ? new Timer(this.snapshotRefreshTimeoutMs, () => this.tryRefreshSnapshot())
52
+ this.snapshotRefresher = this.offlineLoadEnabled
53
+ ? new SnapshotRefresher(subLogger, this.storageAdapter, this.offlineLoadEnabled, this.supportGetSnapshotApi, (snapshot) => this.handleSnapshotRefreshed(snapshot), snapshotRefreshTimeoutMs)
86
54
  : undefined;
87
55
  containerEvent.on("saved", () => this.updateSnapshotAndProcessedOpsMaybe());
88
56
  }
@@ -91,7 +59,7 @@ export class SerializedStateManager {
91
59
  }
92
60
  dispose() {
93
61
  __classPrivateFieldSet(this, _SerializedStateManager_disposed, true, "f");
94
- this.refreshTimer?.clear();
62
+ this.snapshotRefresher?.dispose();
95
63
  }
96
64
  verifyNotDisposed() {
97
65
  if (__classPrivateFieldGet(this, _SerializedStateManager_disposed, "f")) {
@@ -104,7 +72,7 @@ export class SerializedStateManager {
104
72
  * @returns The snapshot sequence number associated with the latest fetched snapshot
105
73
  */
106
74
  get refreshSnapshotP() {
107
- return this.refreshTracker.Promise;
75
+ return this.snapshotRefresher?.refreshSnapshotP;
108
76
  }
109
77
  /**
110
78
  * Called whenever an incoming op is processed by the Container
@@ -132,7 +100,7 @@ export class SerializedStateManager {
132
100
  const baseSnapshotTree = getSnapshotTree(snapshot);
133
101
  const attributes = await getDocumentAttributes(this.storageAdapter, baseSnapshotTree);
134
102
  if (this.offlineLoadEnabled) {
135
- this.refreshTimer?.start();
103
+ this.snapshotRefresher?.startTimer();
136
104
  this.snapshotInfo = {
137
105
  snapshot,
138
106
  snapshotSequenceNumber: attributes.sequenceNumber,
@@ -168,46 +136,18 @@ export class SerializedStateManager {
168
136
  snapshot,
169
137
  snapshotSequenceNumber: attributes.sequenceNumber,
170
138
  };
171
- this.tryRefreshSnapshot();
139
+ this.snapshotRefresher?.tryRefreshSnapshot();
172
140
  }
173
141
  return { snapshot, version: undefined, attributes };
174
142
  }
175
143
  }
176
- tryRefreshSnapshot() {
177
- if (__classPrivateFieldGet(this, _SerializedStateManager_snapshotRefreshEnabled, "f") &&
178
- !__classPrivateFieldGet(this, _SerializedStateManager_disposed, "f") &&
179
- !this.refreshTracker.hasPromise &&
180
- this.latestSnapshot === undefined) {
181
- // Don't block on the refresh snapshot call - it is for the next time we serialize, not booting this incarnation
182
- this.refreshTracker.setPromise(this.refreshLatestSnapshot(this.supportGetSnapshotApi()));
183
- }
184
- }
185
144
  /**
186
- * Fetch the latest snapshot for the container, including delay-loaded groupIds if pendingLocalState was provided and contained any groupIds.
187
- * Note that this will update the StorageAdapter's cached snapshots for the groupIds (if present)
188
- *
189
- * @param supportGetSnapshotApi - a boolean indicating whether to use the fetchISnapshot or fetchISnapshotTree (must be true to fetch by groupIds)
145
+ * Handles the snapshotRefreshed event from SnapshotRefresher.
146
+ * Decides whether to accept the new snapshot based on processed ops.
147
+ * @returns The snapshot sequence number if updated, -1 otherwise
190
148
  */
191
- async refreshLatestSnapshot(supportGetSnapshotApi) {
192
- this.latestSnapshot = await getLatestSnapshotInfo(this.mc, this.storageAdapter, supportGetSnapshotApi);
193
- if (__classPrivateFieldGet(this, _SerializedStateManager_disposed, "f")) {
194
- return -1;
195
- }
196
- // These are loading groupIds that the containerRuntime has requested over its lifetime.
197
- // We will fetch the latest snapshot for the groupIds, which will update storageAdapter.loadedGroupIdSnapshots's cache
198
- const downloadedGroupIds = Object.keys(this.storageAdapter.loadedGroupIdSnapshots);
199
- if (supportGetSnapshotApi && downloadedGroupIds.length > 0) {
200
- assert(this.storageAdapter.getSnapshot !== undefined, 0x972 /* getSnapshot should exist */);
201
- // (This is a separate network call from above because it requires work for storage to add a special base groupId)
202
- const snapshot = await this.storageAdapter.getSnapshot({
203
- versionId: undefined,
204
- scenarioName: "getLatestSnapshotInfo",
205
- cacheSnapshot: false,
206
- loadingGroupIds: downloadedGroupIds,
207
- fetchSource: FetchSource.noCache,
208
- });
209
- assert(snapshot !== undefined, 0x973 /* Snapshot should exist */);
210
- }
149
+ handleSnapshotRefreshed(latestSnapshot) {
150
+ this.latestSnapshot = latestSnapshot;
211
151
  return this.updateSnapshotAndProcessedOpsMaybe();
212
152
  }
213
153
  /**
@@ -238,7 +178,7 @@ export class SerializedStateManager {
238
178
  stashedSnapshotSequenceNumber: this.snapshotInfo?.snapshotSequenceNumber,
239
179
  });
240
180
  this.latestSnapshot = undefined;
241
- this.refreshTimer?.restart();
181
+ this.snapshotRefresher?.clearLatestSnapshot();
242
182
  }
243
183
  else if (snapshotSequenceNumber <= lastProcessedOpSequenceNumber) {
244
184
  // Snapshot seq num is between the first and last processed op.
@@ -246,7 +186,7 @@ export class SerializedStateManager {
246
186
  this.processedOps.splice(0, snapshotSequenceNumber - firstProcessedOpSequenceNumber + 1);
247
187
  this.snapshotInfo = this.latestSnapshot;
248
188
  this.latestSnapshot = undefined;
249
- this.refreshTimer?.restart();
189
+ this.snapshotRefresher?.clearLatestSnapshot();
250
190
  this.mc.logger.sendTelemetryEvent({
251
191
  eventName: "SnapshotRefreshed",
252
192
  snapshotSequenceNumber,
@@ -270,7 +210,7 @@ export class SerializedStateManager {
270
210
  snapshotSequenceNumber: snapshot.sequenceNumber ?? 0,
271
211
  snapshotFetchedTime: Date.now(),
272
212
  };
273
- this.refreshTimer?.start();
213
+ this.snapshotRefresher?.startTimer();
274
214
  }
275
215
  }
276
216
  /**
@@ -324,7 +264,7 @@ export class SerializedStateManager {
324
264
  });
325
265
  }
326
266
  }
327
- _SerializedStateManager_snapshotRefreshEnabled = new WeakMap(), _SerializedStateManager_disposed = new WeakMap();
267
+ _SerializedStateManager_disposed = new WeakMap();
328
268
  async function convertSnapshotTreeToSnapshotWithBlobs(snapshot, storageAdapter) {
329
269
  const snapshotBlobs = await getBlobContentsFromTree(snapshot, storageAdapter);
330
270
  return {
@@ -1 +1 @@
1
- {"version":3,"file":"serializedStateManager.js","sourceRoot":"","sources":["../src/serializedStateManager.ts"],"names":[],"mappings":"AAAA;;;GAGG;;;;;;;;;;;;;AAEH,OAAO,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAQ9D,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,qCAAqC,CAAC;AACpE,OAAO,EACN,WAAW,GAQX,MAAM,6CAA6C,CAAC;AACrD,OAAO,EAAE,eAAe,EAAE,qBAAqB,EAAE,MAAM,uCAAuC,CAAC;AAC/F,OAAO,EAEN,gB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,QAAQ,KAAK,SAAS,IAAI,OAAO,EAAE,EAAE,KAAK,SAAS,EAAE,CAAC;QAChE,EAAE,CAAC,MAAM,CAAC,cAAc,CAAC;YACxB,SAAS,EAAE,wCAAwC;YACnD,UAAU,EAAE,OAAO,KAAK,SAAS,EAAE,mFAAmF;SACtH,CAAC,CAAC;IACJ,CAAC;IACD,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,CAAC;AAC9B,CAAC","sourcesContent":["/*!\n * Copyright (c) Microsoft Corporation and contributors. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { stringToBuffer } from \"@fluid-internal/client-utils\";\nimport type { IRuntime } from \"@fluidframework/container-definitions/internal\";\nimport type {\n\tIEventProvider,\n\tIEvent,\n\tITelemetryBaseLogger,\n} from \"@fluidframework/core-interfaces\";\nimport type { IDisposable } from \"@fluidframework/core-interfaces/internal\";\nimport { Timer, assert } from \"@fluidframework/core-utils/internal\";\nimport {\n\tFetchSource,\n\ttype IDocumentStorageService,\n\ttype IResolvedUrl,\n\ttype ISnapshot,\n\ttype IDocumentAttributes,\n\ttype ISnapshotTree,\n\ttype IVersion,\n\ttype ISequencedDocumentMessage,\n} from \"@fluidframework/driver-definitions/internal\";\nimport { getSnapshotTree, isInstanceOfISnapshot } from \"@fluidframework/driver-utils/internal\";\nimport {\n\ttype MonitoringContext,\n\tPerformanceEvent,\n\tUsageError,\n\tcreateChildMonitoringContext,\n} from \"@fluidframework/telemetry-utils/internal\";\n\nimport {\n\tgetBlobContentsFromTree,\n\ttype ContainerStorageAdapter,\n\ttype ISerializableBlobContents,\n} from \"./containerStorageAdapter.js\";\nimport {\n\tconvertISnapshotToSnapshotWithBlobs,\n\tconvertSnapshotToSnapshotInfo,\n\tgetDocumentAttributes,\n} from \"./utils.js\";\n\n/**\n * This is very similar to {@link @fluidframework/protocol-definitions/internal#ISnapshot}, but the difference is\n * that the blobs of ISnapshot are of type ArrayBufferLike, while the blobs of this interface are serializable because\n * they are already converted to string.\n */\nexport interface SnapshotWithBlobs {\n\t/**\n\t * Snapshot from which container initially loaded.\n\t */\n\tbaseSnapshot: ISnapshotTree;\n\t/**\n\t * Serializable blobs from the base snapshot. Used to load offline since\n\t * storage is not available.\n\t */\n\tsnapshotBlobs: ISerializableBlobContents;\n}\n\n/**\n * State saved by a container at close time, to be used to load a new instance\n * of the container to the same state\n *\n * This is very similar to {@link @fluidframework/protocol-definitions/internal#ISnapshot}, but the difference is\n * that the blobs of ISnapshot are of type ArrayBufferLike, while the blobs of this interface are serializable because\n * they are already converted to string.\n *\n * @internal\n */\nexport interface IPendingContainerState extends SnapshotWithBlobs {\n\t/**\n\t * This container was attached (as opposed to IPendingDetachedContainerState.attached which is false)\n\t */\n\tattached: true;\n\t/**\n\t * Runtime-specific state that will be needed to properly rehydrate\n\t * (it's included in ContainerContext passed to instantiateRuntime)\n\t */\n\tpendingRuntimeState: unknown;\n\t/**\n\t * Any group snapshots (aka delay-loaded) we've downloaded from the service for this container\n\t */\n\tloadedGroupIdSnapshots?: Record<string, SerializedSnapshotInfo>;\n\t/**\n\t * All ops since base snapshot sequence number up to the latest op\n\t * seen when the container was closed. Used to apply stashed (saved pending)\n\t * ops at the same sequence number at which they were made.\n\t */\n\tsavedOps: ISequencedDocumentMessage[];\n\t/**\n\t * The Container's URL in the service, needed to hook up the driver during rehydration\n\t */\n\turl: string;\n\t/**\n\t * If the Container was connected when serialized, its clientId. Used as the initial clientId upon rehydration, until reconnected.\n\t */\n\tclientId?: string;\n}\n\n/**\n * State saved by a container in detached state, to be used to load a new instance\n * of the container to the same state (rehydrate)\n * @internal\n */\nexport interface IPendingDetachedContainerState extends SnapshotWithBlobs {\n\t/**\n\t * This container was not attached (as opposed to IPendingContainerState.attached which is true)\n\t */\n\tattached: false;\n\t/**\n\t * Indicates whether we expect the rehydrated container to have non-empty Detached Blob Storage\n\t */\n\thasAttachmentBlobs: boolean;\n\t/**\n\t * Used by the memory blob storage to persisted attachment blobs\n\t */\n\tattachmentBlobs?: string;\n\t/**\n\t * Runtime-specific state that will be needed to properly rehydrate\n\t * (it's included in ContainerContext passed to instantiateRuntime)\n\t */\n\tpendingRuntimeState?: unknown;\n}\n\nexport interface SerializedSnapshotInfo extends SnapshotWithBlobs {\n\tsnapshotSequenceNumber: number;\n}\n\ninterface ISnapshotInfo {\n\tsnapshotSequenceNumber: number;\n\tsnapshotFetchedTime?: number | undefined;\n\tsnapshot: ISnapshot | ISnapshotTree;\n}\n\nexport type ISerializedStateManagerDocumentStorageService = Pick<\n\tContainerStorageAdapter,\n\t\"getSnapshot\" | \"getSnapshotTree\" | \"getVersions\" | \"readBlob\" | \"cacheSnapshotBlobs\"\n> & {\n\tloadedGroupIdSnapshots: Record<string, ISnapshot>;\n};\n\ninterface ISerializerEvent extends IEvent {\n\t(event: \"saved\", listener: (dirty: boolean) => void): void;\n}\n\nclass RefreshPromiseTracker {\n\tpublic get hasPromise(): boolean {\n\t\treturn this.#promise !== undefined;\n\t}\n\tpublic get Promise(): Promise<number> | undefined {\n\t\treturn this.#promise;\n\t}\n\tconstructor(private readonly catchHandler: (error: Error) => void) {}\n\n\t#promise: Promise<number> | undefined;\n\tsetPromise(p: Promise<number>): void {\n\t\tif (this.hasPromise) {\n\t\t\tthrow new Error(\"Cannot set promise while promise exists\");\n\t\t}\n\t\tthis.#promise = p.finally(() => {\n\t\t\tthis.#promise = undefined;\n\t\t});\n\t\tp.catch(this.catchHandler);\n\t}\n}\n\n/**\n * Helper class to manage the state of the container needed for proper serialization.\n *\n * It holds the pendingLocalState the container was rehydrated from (if any),\n * as well as the snapshot to be used for serialization.\n * It also keeps track of container dirty state and which local ops have been processed\n */\nexport class SerializedStateManager implements IDisposable {\n\tprivate readonly processedOps: ISequencedDocumentMessage[] = [];\n\tprivate readonly mc: MonitoringContext;\n\tprivate snapshotInfo: ISnapshotInfo | undefined;\n\tprivate latestSnapshot: ISnapshotInfo | undefined;\n\tprivate readonly refreshTracker = new RefreshPromiseTracker(\n\t\t// eslint-disable-next-line unicorn/consistent-function-scoping\n\t\t(error) =>\n\t\t\tthis.mc.logger.sendErrorEvent(\n\t\t\t\t{\n\t\t\t\t\teventName: \"RefreshLatestSnapshotFailed\",\n\t\t\t\t},\n\t\t\t\terror,\n\t\t\t),\n\t);\n\tprivate lastSavedOpSequenceNumber: number = 0;\n\tprivate readonly refreshTimer: Timer | undefined;\n\tprivate readonly snapshotRefreshTimeoutMs: number = 60 * 60 * 24 * 1000;\n\treadonly #snapshotRefreshEnabled: boolean;\n\t#disposed: boolean = false;\n\n\t/**\n\t * @param subLogger - Container's logger to use as parent for our logger\n\t * @param storageAdapter - Storage adapter for fetching snapshots\n\t * @param offlineLoadEnabled - Is serializing/rehydrating containers allowed?\n\t * @param containerEvent - Source of the \"saved\" event when the container has all its pending state uploaded\n\t * @param containerDirty - Is the container \"dirty\"? That's the opposite of \"saved\" - there is pending state that may not have been received yet by the service.\n\t */\n\tconstructor(\n\t\tsubLogger: ITelemetryBaseLogger,\n\t\tprivate readonly storageAdapter: ISerializedStateManagerDocumentStorageService,\n\t\tprivate readonly offlineLoadEnabled: boolean,\n\t\tcontainerEvent: IEventProvider<ISerializerEvent>,\n\t\tprivate readonly containerDirty: () => boolean,\n\t\tprivate readonly supportGetSnapshotApi: () => boolean,\n\t\tsnapshotRefreshTimeoutMs?: number,\n\t) {\n\t\tthis.mc = createChildMonitoringContext({\n\t\t\tlogger: subLogger,\n\t\t\tnamespace: \"serializedStateManager\",\n\t\t});\n\n\t\tthis.snapshotRefreshTimeoutMs = snapshotRefreshTimeoutMs ?? this.snapshotRefreshTimeoutMs;\n\n\t\tthis.#snapshotRefreshEnabled =\n\t\t\tthis.offlineLoadEnabled &&\n\t\t\t(this.mc.config.getBoolean(\"Fluid.Container.enableOfflineSnapshotRefresh\") ??\n\t\t\t\tthis.mc.config.getBoolean(\"Fluid.Container.enableOfflineFull\")) === true;\n\n\t\tthis.refreshTimer = this.#snapshotRefreshEnabled\n\t\t\t? new Timer(this.snapshotRefreshTimeoutMs, () => this.tryRefreshSnapshot())\n\t\t\t: undefined;\n\t\tcontainerEvent.on(\"saved\", () => this.updateSnapshotAndProcessedOpsMaybe());\n\t}\n\tpublic get disposed(): boolean {\n\t\treturn this.#disposed;\n\t}\n\tdispose(): void {\n\t\tthis.#disposed = true;\n\t\tthis.refreshTimer?.clear();\n\t}\n\n\tprivate verifyNotDisposed(): void {\n\t\tif (this.#disposed) {\n\t\t\tthrow new Error(\"SerializedStateManager used after dispose.\");\n\t\t}\n\t}\n\n\t/**\n\t * Promise that will resolve (or reject) once we've tried to download the latest snapshot(s) from storage\n\t * only intended to be used for testing purposes.\n\t * @returns The snapshot sequence number associated with the latest fetched snapshot\n\t */\n\tpublic get refreshSnapshotP(): Promise<number | undefined> | undefined {\n\t\treturn this.refreshTracker.Promise;\n\t}\n\n\t/**\n\t * Called whenever an incoming op is processed by the Container\n\t */\n\tpublic addProcessedOp(message: ISequencedDocumentMessage): void {\n\t\tif (this.offlineLoadEnabled) {\n\t\t\tthis.processedOps.push(message);\n\t\t\tthis.updateSnapshotAndProcessedOpsMaybe();\n\t\t}\n\t}\n\n\t/**\n\t * This wraps the basic functionality of fetching the snapshot for this container during Container load.\n\t *\n\t * If we have pendingLocalState, we get the snapshot from there.\n\t * Otherwise, fetch it from storage (according to specifiedVersion if provided).\n\t *\n\t * @param specifiedVersion - If a version is specified and we don't have pendingLocalState, fetch this version from storage.\n\t * @param pendingLocalState - The pendingLocalState being rehydrated, if any (undefined when loading directly from storage)\n\t * @returns The snapshot to boot the container from\n\t */\n\tpublic async fetchSnapshot(\n\t\tspecifiedVersion: string | undefined,\n\t\tpendingLocalState: IPendingContainerState | undefined,\n\t): Promise<{\n\t\tsnapshot: ISnapshot | ISnapshotTree;\n\t\tversion: IVersion | undefined;\n\t\tattributes: IDocumentAttributes;\n\t}> {\n\t\tthis.verifyNotDisposed();\n\t\tif (pendingLocalState === undefined) {\n\t\t\tconst { snapshot, version } = await getSnapshot(\n\t\t\t\tthis.mc,\n\t\t\t\tthis.storageAdapter,\n\t\t\t\tthis.supportGetSnapshotApi(),\n\t\t\t\tspecifiedVersion,\n\t\t\t);\n\t\t\tconst baseSnapshotTree: ISnapshotTree | undefined = getSnapshotTree(snapshot);\n\t\t\tconst attributes = await getDocumentAttributes(this.storageAdapter, baseSnapshotTree);\n\t\t\tif (this.offlineLoadEnabled) {\n\t\t\t\tthis.refreshTimer?.start();\n\t\t\t\tthis.snapshotInfo = {\n\t\t\t\t\tsnapshot,\n\t\t\t\t\tsnapshotSequenceNumber: attributes.sequenceNumber,\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn { snapshot, version, attributes };\n\t\t} else {\n\t\t\tconst { baseSnapshot, snapshotBlobs, savedOps } = pendingLocalState;\n\t\t\tconst blobContents = new Map<string, ArrayBuffer>();\n\t\t\tfor (const [id, value] of Object.entries(snapshotBlobs)) {\n\t\t\t\tblobContents.set(id, stringToBuffer(value, \"utf8\"));\n\t\t\t}\n\t\t\tthis.storageAdapter.cacheSnapshotBlobs(blobContents);\n\t\t\tconst attributes = await getDocumentAttributes(this.storageAdapter, baseSnapshot);\n\n\t\t\tconst snapshot: ISnapshot = {\n\t\t\t\tsequenceNumber: attributes.sequenceNumber,\n\t\t\t\tsnapshotTree: baseSnapshot,\n\t\t\t\tblobContents,\n\t\t\t\tlatestSequenceNumber: undefined,\n\t\t\t\tops: [],\n\t\t\t\tsnapshotFormatV: 1,\n\t\t\t};\n\n\t\t\tif (this.offlineLoadEnabled) {\n\t\t\t\t// special case handle. Obtaining the last saved op seq num to avoid\n\t\t\t\t// refreshing the snapshot before we have processed it. It could cause\n\t\t\t\t// a subsequent stashing to have a newer snapshot than allowed.\n\t\t\t\tif (savedOps.length > 0) {\n\t\t\t\t\tconst savedOpsSize = savedOps.length;\n\t\t\t\t\tthis.lastSavedOpSequenceNumber = savedOps[savedOpsSize - 1].sequenceNumber;\n\t\t\t\t}\n\n\t\t\t\tthis.snapshotInfo = {\n\t\t\t\t\tsnapshot,\n\t\t\t\t\tsnapshotSequenceNumber: attributes.sequenceNumber,\n\t\t\t\t};\n\t\t\t\tthis.tryRefreshSnapshot();\n\t\t\t}\n\t\t\treturn { snapshot, version: undefined, attributes };\n\t\t}\n\t}\n\n\tprivate tryRefreshSnapshot(): void {\n\t\tif (\n\t\t\tthis.#snapshotRefreshEnabled &&\n\t\t\t!this.#disposed &&\n\t\t\t!this.refreshTracker.hasPromise &&\n\t\t\tthis.latestSnapshot === undefined\n\t\t) {\n\t\t\t// Don't block on the refresh snapshot call - it is for the next time we serialize, not booting this incarnation\n\t\t\tthis.refreshTracker.setPromise(this.refreshLatestSnapshot(this.supportGetSnapshotApi()));\n\t\t}\n\t}\n\n\t/**\n\t * Fetch the latest snapshot for the container, including delay-loaded groupIds if pendingLocalState was provided and contained any groupIds.\n\t * Note that this will update the StorageAdapter's cached snapshots for the groupIds (if present)\n\t *\n\t * @param supportGetSnapshotApi - a boolean indicating whether to use the fetchISnapshot or fetchISnapshotTree (must be true to fetch by groupIds)\n\t */\n\tprivate async refreshLatestSnapshot(supportGetSnapshotApi: boolean): Promise<number> {\n\t\tthis.latestSnapshot = await getLatestSnapshotInfo(\n\t\t\tthis.mc,\n\t\t\tthis.storageAdapter,\n\t\t\tsupportGetSnapshotApi,\n\t\t);\n\n\t\tif (this.#disposed) {\n\t\t\treturn -1;\n\t\t}\n\n\t\t// These are loading groupIds that the containerRuntime has requested over its lifetime.\n\t\t// We will fetch the latest snapshot for the groupIds, which will update storageAdapter.loadedGroupIdSnapshots's cache\n\t\tconst downloadedGroupIds = Object.keys(this.storageAdapter.loadedGroupIdSnapshots);\n\t\tif (supportGetSnapshotApi && downloadedGroupIds.length > 0) {\n\t\t\tassert(\n\t\t\t\tthis.storageAdapter.getSnapshot !== undefined,\n\t\t\t\t0x972 /* getSnapshot should exist */,\n\t\t\t);\n\t\t\t// (This is a separate network call from above because it requires work for storage to add a special base groupId)\n\t\t\tconst snapshot = await this.storageAdapter.getSnapshot({\n\t\t\t\tversionId: undefined,\n\t\t\t\tscenarioName: \"getLatestSnapshotInfo\",\n\t\t\t\tcacheSnapshot: false,\n\t\t\t\tloadingGroupIds: downloadedGroupIds,\n\t\t\t\tfetchSource: FetchSource.noCache,\n\t\t\t});\n\t\t\tassert(snapshot !== undefined, 0x973 /* Snapshot should exist */);\n\t\t}\n\n\t\treturn this.updateSnapshotAndProcessedOpsMaybe();\n\t}\n\n\t/**\n\t * Updates class snapshot and processedOps if we have a new snapshot and it's among processedOps range.\n\t */\n\tprivate updateSnapshotAndProcessedOpsMaybe(): number {\n\t\tconst snapshotSequenceNumber = this.latestSnapshot?.snapshotSequenceNumber;\n\t\tif (\n\t\t\tthis.#disposed ||\n\t\t\tsnapshotSequenceNumber === undefined ||\n\t\t\tthis.processedOps.length === 0 ||\n\t\t\tthis.processedOps[this.processedOps.length - 1].sequenceNumber <\n\t\t\t\tthis.lastSavedOpSequenceNumber ||\n\t\t\tthis.containerDirty()\n\t\t) {\n\t\t\t// can't refresh latest snapshot until we have processed the ops up to it.\n\t\t\t// Pending state would be behind the latest snapshot.\n\t\t\treturn -1;\n\t\t}\n\t\tconst firstProcessedOpSequenceNumber = this.processedOps[0].sequenceNumber;\n\t\tconst lastProcessedOpSequenceNumber =\n\t\t\tthis.processedOps[this.processedOps.length - 1].sequenceNumber;\n\n\t\tif (snapshotSequenceNumber < firstProcessedOpSequenceNumber) {\n\t\t\t// Snapshot seq number is older than our first processed op, which could mean we're fetching\n\t\t\t// the same snapshot that we already have or snapshot is too old, implicating an unexpected behavior.\n\t\t\tthis.mc.logger.sendTelemetryEvent({\n\t\t\t\teventName: \"OldSnapshotFetchWhileRefreshing\",\n\t\t\t\tsnapshotSequenceNumber,\n\t\t\t\tfirstProcessedOpSequenceNumber,\n\t\t\t\tlastProcessedOpSequenceNumber,\n\t\t\t\tstashedSnapshotSequenceNumber: this.snapshotInfo?.snapshotSequenceNumber,\n\t\t\t});\n\t\t\tthis.latestSnapshot = undefined;\n\t\t\tthis.refreshTimer?.restart();\n\t\t} else if (snapshotSequenceNumber <= lastProcessedOpSequenceNumber) {\n\t\t\t// Snapshot seq num is between the first and last processed op.\n\t\t\t// Remove the ops that are already part of the snapshot\n\t\t\tthis.processedOps.splice(0, snapshotSequenceNumber - firstProcessedOpSequenceNumber + 1);\n\t\t\tthis.snapshotInfo = this.latestSnapshot;\n\t\t\tthis.latestSnapshot = undefined;\n\t\t\tthis.refreshTimer?.restart();\n\t\t\tthis.mc.logger.sendTelemetryEvent({\n\t\t\t\teventName: \"SnapshotRefreshed\",\n\t\t\t\tsnapshotSequenceNumber,\n\t\t\t\tfirstProcessedOpSequenceNumber,\n\t\t\t\tnewFirstProcessedOpSequenceNumber:\n\t\t\t\t\tthis.processedOps.length === 0 ? undefined : this.processedOps[0].sequenceNumber,\n\t\t\t});\n\t\t}\n\t\treturn snapshotSequenceNumber;\n\t}\n\n\t/**\n\t * When the Container attaches, we need to stash the initial snapshot (a form of the attach summary).\n\t * This method is only meant to be used by Container.attach() to set the initial\n\t * base snapshot when attaching.\n\t * @param snapshot - snapshot and blobs collected while attaching (a form of the attach summary)\n\t */\n\tpublic setInitialSnapshot(snapshot: ISnapshot): void {\n\t\tthis.verifyNotDisposed();\n\t\tif (this.offlineLoadEnabled) {\n\t\t\tthis.snapshotInfo = {\n\t\t\t\tsnapshot,\n\t\t\t\tsnapshotSequenceNumber: snapshot.sequenceNumber ?? 0,\n\t\t\t\tsnapshotFetchedTime: Date.now(),\n\t\t\t};\n\t\t\tthis.refreshTimer?.start();\n\t\t}\n\t}\n\n\t/**\n\t * Assembles and serializes the {@link IPendingContainerState} for the container,\n\t * to be stored and used to rehydrate the container at a later time.\n\t */\n\tpublic async getPendingLocalState(\n\t\tclientId: string | undefined,\n\t\truntime: Pick<IRuntime, \"getPendingLocalState\">,\n\t\tresolvedUrl: IResolvedUrl,\n\t): Promise<string> {\n\t\tthis.verifyNotDisposed();\n\t\tif (!this.offlineLoadEnabled) {\n\t\t\tthrow new UsageError(\"Can't get pending local state unless offline load is enabled\");\n\t\t}\n\n\t\treturn PerformanceEvent.timedExecAsync(\n\t\t\tthis.mc.logger,\n\t\t\t{\n\t\t\t\teventName: \"getPendingLocalState\",\n\t\t\t\tdetails: {\n\t\t\t\t\tnotifyImminentClosure: false,\n\t\t\t\t\tsessionExpiryTimerStarted: undefined,\n\t\t\t\t\tsnapshotSequenceNumber: undefined,\n\t\t\t\t\tprocessedOpsSize: this.processedOps.length,\n\t\t\t\t},\n\t\t\t\tclientId,\n\t\t\t},\n\t\t\tasync () => {\n\t\t\t\tassert(this.snapshotInfo !== undefined, 0x8e5 /* no base data */);\n\t\t\t\tconst pendingRuntimeState = await runtime.getPendingLocalState({\n\t\t\t\t\tnotifyImminentClosure: false,\n\t\t\t\t\tsnapshotSequenceNumber: this.snapshotInfo.snapshotSequenceNumber,\n\t\t\t\t\tsessionExpiryTimerStarted: this.snapshotInfo.snapshotFetchedTime,\n\t\t\t\t});\n\t\t\t\t// This conversion is required because ArrayBufferLike doesn't survive JSON.stringify\n\t\t\t\tconst loadedGroupIdSnapshots: Record<string, SerializedSnapshotInfo> = {};\n\t\t\t\tlet hasGroupIdSnapshots = false;\n\t\t\t\tconst groupIdSnapshots = Object.entries(this.storageAdapter.loadedGroupIdSnapshots);\n\t\t\t\tif (groupIdSnapshots.length > 0) {\n\t\t\t\t\tfor (const [groupId, snapshot] of groupIdSnapshots) {\n\t\t\t\t\t\thasGroupIdSnapshots = true;\n\t\t\t\t\t\tloadedGroupIdSnapshots[groupId] = convertSnapshotToSnapshotInfo(snapshot);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tconst snapshotWithBlobs: SnapshotWithBlobs = isInstanceOfISnapshot(\n\t\t\t\t\tthis.snapshotInfo.snapshot,\n\t\t\t\t)\n\t\t\t\t\t? convertISnapshotToSnapshotWithBlobs(this.snapshotInfo.snapshot)\n\t\t\t\t\t: await convertSnapshotTreeToSnapshotWithBlobs(\n\t\t\t\t\t\t\tthis.snapshotInfo.snapshot,\n\t\t\t\t\t\t\tthis.storageAdapter,\n\t\t\t\t\t\t);\n\n\t\t\t\tconst pendingState: IPendingContainerState = {\n\t\t\t\t\tattached: true,\n\t\t\t\t\tpendingRuntimeState,\n\t\t\t\t\t...snapshotWithBlobs,\n\t\t\t\t\tloadedGroupIdSnapshots: hasGroupIdSnapshots ? loadedGroupIdSnapshots : undefined,\n\t\t\t\t\tsavedOps: this.processedOps,\n\t\t\t\t\turl: resolvedUrl.url,\n\t\t\t\t\tclientId,\n\t\t\t\t};\n\n\t\t\t\treturn JSON.stringify(pendingState);\n\t\t\t},\n\t\t);\n\t}\n}\n\nasync function convertSnapshotTreeToSnapshotWithBlobs(\n\tsnapshot: ISnapshotTree,\n\tstorageAdapter: ISerializedStateManagerDocumentStorageService,\n): Promise<SnapshotWithBlobs> {\n\tconst snapshotBlobs = await getBlobContentsFromTree(snapshot, storageAdapter);\n\treturn {\n\t\tbaseSnapshot: snapshot,\n\t\tsnapshotBlobs,\n\t};\n}\n\n/**\n * Retrieves the most recent snapshot and returns its info.\n *\n * @param mc - The monitoring context.\n * @param storageAdapter - The storage adapter providing methods to retrieve the snapshot.\n * @param supportGetSnapshotApi - a boolean indicating whether to use the fetchISnapshot or fetchISnapshotTree.\n * @returns a SnapshotInfo object containing the snapshot tree, snapshot blobs and its sequence number.\n */\nexport async function getLatestSnapshotInfo(\n\tmc: MonitoringContext,\n\tstorageAdapter: ISerializedStateManagerDocumentStorageService,\n\tsupportGetSnapshotApi: boolean,\n): Promise<ISnapshotInfo | undefined> {\n\treturn PerformanceEvent.timedExecAsync<ISnapshotInfo | undefined>(\n\t\tmc.logger,\n\t\t{ eventName: \"GetLatestSnapshotInfo\" },\n\t\tasync (event) => {\n\t\t\ttry {\n\t\t\t\t// get the latest non cached snapshot version\n\t\t\t\tconst specifiedVersion: IVersion[] = await storageAdapter.getVersions(\n\t\t\t\t\t// eslint-disable-next-line unicorn/no-null\n\t\t\t\t\tnull,\n\t\t\t\t\t1,\n\t\t\t\t\t\"getLatestSnapshotInfo\",\n\t\t\t\t\tFetchSource.noCache,\n\t\t\t\t);\n\t\t\t\tconst { snapshot: baseSnapshot } = await getSnapshot(\n\t\t\t\t\tmc,\n\t\t\t\t\tstorageAdapter,\n\t\t\t\t\tsupportGetSnapshotApi,\n\t\t\t\t\tspecifiedVersion[0]?.id,\n\t\t\t\t);\n\n\t\t\t\tconst { sequenceNumber, snapshotTree } = isInstanceOfISnapshot(baseSnapshot)\n\t\t\t\t\t? baseSnapshot\n\t\t\t\t\t: { snapshotTree: baseSnapshot, sequenceNumber: undefined };\n\n\t\t\t\tconst snapshotSequenceNumber: number =\n\t\t\t\t\tsequenceNumber ??\n\t\t\t\t\t(await getDocumentAttributes(storageAdapter, snapshotTree).then(\n\t\t\t\t\t\t(a) => a.sequenceNumber,\n\t\t\t\t\t));\n\t\t\t\treturn {\n\t\t\t\t\tsnapshot: baseSnapshot,\n\t\t\t\t\tsnapshotSequenceNumber,\n\t\t\t\t\tsnapshotFetchedTime: Date.now(),\n\t\t\t\t};\n\t\t\t} catch (error) {\n\t\t\t\tevent.cancel(undefined, error);\n\t\t\t}\n\t\t\treturn undefined;\n\t\t},\n\t);\n}\n\n/**\n * Retrieves a snapshot from the storage adapter and transforms it into an ISnapshotTree object.\n *\n * @param mc - The monitoring context.\n * @param storageAdapter - The storage adapter providing methods to retrieve the snapshot.\n * @param supportGetSnapshotApi - a boolean indicating whether to use the fetchISnapshot or fetchISnapshotTree.\n * @param specifiedVersion - An optional version string specifying the version of the snapshot tree to fetch.\n * @returns An ISnapshotTree and its version.\n */\nasync function getSnapshot(\n\tmc: MonitoringContext,\n\tstorageAdapter: Pick<\n\t\tIDocumentStorageService,\n\t\t\"getSnapshot\" | \"getSnapshotTree\" | \"getVersions\"\n\t>,\n\tsupportGetSnapshotApi: boolean,\n\tspecifiedVersion: string | undefined,\n): Promise<{ snapshot: ISnapshot | ISnapshotTree; version?: IVersion }> {\n\tconst { snapshot, version } = supportGetSnapshotApi\n\t\t? await fetchISnapshot(mc, storageAdapter, specifiedVersion)\n\t\t: await fetchISnapshotTree(mc, storageAdapter, specifiedVersion);\n\tassert(snapshot !== undefined, 0x8e4 /* Snapshot should exist */);\n\treturn { snapshot, version };\n}\n\n/**\n * Fetches an ISnapshot from a storage adapter based on the specified version.\n *\n * @param mc - The monitoring context.\n * @param storageAdapter - The storage adapter providing a getSnapshot method to retrieve the ISnapshot and version.\n * @param specifiedVersion - An optional version string specifying the version of the snapshot tree to fetch.\n * @returns The fetched snapshot tree and its version.\n */\nexport async function fetchISnapshot(\n\tmc: MonitoringContext,\n\tstorageAdapter: Pick<IDocumentStorageService, \"getSnapshot\">,\n\tspecifiedVersion: string | undefined,\n): Promise<{ snapshot?: ISnapshot; version?: IVersion }> {\n\tconst snapshot = await storageAdapter.getSnapshot?.({ versionId: specifiedVersion });\n\tconst version: IVersion | undefined =\n\t\tsnapshot?.snapshotTree.id === undefined\n\t\t\t? undefined\n\t\t\t: {\n\t\t\t\t\tid: snapshot.snapshotTree.id,\n\t\t\t\t\ttreeId: snapshot.snapshotTree.id,\n\t\t\t\t};\n\n\tif (snapshot === undefined && specifiedVersion !== undefined) {\n\t\tmc.logger.sendErrorEvent({\n\t\t\teventName: \"getSnapshotTreeFailed\",\n\t\t\tid: specifiedVersion,\n\t\t});\n\t} else if (snapshot !== undefined && version?.id === undefined) {\n\t\tmc.logger.sendErrorEvent({\n\t\t\teventName: \"getSnapshotFetchedTreeWithoutVersionId\",\n\t\t\thasVersion: version !== undefined, // if hasVersion is true, this means that the contract with the service was broken.\n\t\t});\n\t}\n\treturn { snapshot, version };\n}\n\n/**\n * Fetches an ISnapshotTree from a storage adapter based on the specified version.\n *\n * @param mc - The monitoring context.\n * @param storageAdapter - The storage adapter providing methods to retrieve the ISnapshotTree and version.\n * @param specifiedVersion - An optional version string specifying the version of the snapshot tree to fetch.\n * @returns The fetched snapshot tree and its version.\n */\nexport async function fetchISnapshotTree(\n\tmc: MonitoringContext,\n\tstorageAdapter: Pick<IDocumentStorageService, \"getSnapshotTree\" | \"getVersions\">,\n\tspecifiedVersion: string | undefined,\n): Promise<{ snapshot?: ISnapshotTree; version?: IVersion | undefined }> {\n\t// API uses null\n\t// eslint-disable-next-line unicorn/no-null\n\tconst versions = await storageAdapter.getVersions(specifiedVersion ?? null, 1);\n\tconst version = versions[0];\n\n\tif (version === undefined && specifiedVersion !== undefined) {\n\t\t// We should have a defined version to load from if specified version requested\n\t\tmc.logger.sendErrorEvent({\n\t\t\teventName: \"NoVersionFoundWhenSpecified\",\n\t\t\tid: specifiedVersion,\n\t\t});\n\t}\n\tconst snapshot = (await storageAdapter.getSnapshotTree(version)) ?? undefined;\n\n\tif (snapshot === undefined && version !== undefined) {\n\t\tmc.logger.sendErrorEvent({ eventName: \"getSnapshotTreeFailed\", id: version.id });\n\t} else if (snapshot !== undefined && version?.id === undefined) {\n\t\tmc.logger.sendErrorEvent({\n\t\t\teventName: \"getSnapshotFetchedTreeWithoutVersionId\",\n\t\t\thasVersion: version !== undefined, // if hasVersion is true, this means that the contract with the service was broken.\n\t\t});\n\t}\n\treturn { snapshot, version };\n}\n"]}
1
+ {"version":3,"file":"serializedStateManager.js","sourceRoot":"","sources":["../src/serializedStateManager.ts"],"names":[],"mappings":"AAAA;;;GAGG;;;;;;;;;;;;;AAEH,OAAO,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAQ9D,OAAO,EAAE,MAAM,EAAE,MAAM,qCAAqC,CAAC;AAC7D,OAAO,EACN,WAAW,GAQX,MAAM,6CAA6C,CAAC;AACrD,OAAO,EAAE,eAAe,EAAE,qBAAqB,EAAE,MAAM,uCAAuC,CAAC;AAC/F,OAAO,EAEN,gBAAgB,EAChB,UAAU,EACV,4BAA4B,GAC5B,MAAM,0CAA0C,CAAC;AAElD,OAAO,EACN,uBAAuB,GAGvB,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAC3D,OAAO,EACN,mCAAmC,EACnC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AK,SAAS,EAAE,CAAC;QACrD,EAAE,CAAC,MAAM,CAAC,cAAc,CAAC,EAAE,SAAS,EAAE,uBAAuB,EAAE,EAAE,EAAE,OAAO,CAAC,EAAE,EAAE,CAAC,CAAC;IAClF,CAAC;SAAM,IAAI,QAAQ,KAAK,SAAS,IAAI,OAAO,EAAE,EAAE,KAAK,SAAS,EAAE,CAAC;QAChE,EAAE,CAAC,MAAM,CAAC,cAAc,CAAC;YACxB,SAAS,EAAE,wCAAwC;YACnD,UAAU,EAAE,OAAO,KAAK,SAAS,EAAE,mFAAmF;SACtH,CAAC,CAAC;IACJ,CAAC;IACD,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,CAAC;AAC9B,CAAC","sourcesContent":["/*!\n * Copyright (c) Microsoft Corporation and contributors. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { stringToBuffer } from \"@fluid-internal/client-utils\";\nimport type { IRuntime } from \"@fluidframework/container-definitions/internal\";\nimport type {\n\tIEventProvider,\n\tIEvent,\n\tITelemetryBaseLogger,\n} from \"@fluidframework/core-interfaces\";\nimport type { IDisposable } from \"@fluidframework/core-interfaces/internal\";\nimport { assert } from \"@fluidframework/core-utils/internal\";\nimport {\n\tFetchSource,\n\ttype IDocumentStorageService,\n\ttype IResolvedUrl,\n\ttype ISnapshot,\n\ttype IDocumentAttributes,\n\ttype ISnapshotTree,\n\ttype IVersion,\n\ttype ISequencedDocumentMessage,\n} from \"@fluidframework/driver-definitions/internal\";\nimport { getSnapshotTree, isInstanceOfISnapshot } from \"@fluidframework/driver-utils/internal\";\nimport {\n\ttype MonitoringContext,\n\tPerformanceEvent,\n\tUsageError,\n\tcreateChildMonitoringContext,\n} from \"@fluidframework/telemetry-utils/internal\";\n\nimport {\n\tgetBlobContentsFromTree,\n\ttype ContainerStorageAdapter,\n\ttype ISerializableBlobContents,\n} from \"./containerStorageAdapter.js\";\nimport { SnapshotRefresher } from \"./snapshotRefresher.js\";\nimport {\n\tconvertISnapshotToSnapshotWithBlobs,\n\tconvertSnapshotToSnapshotInfo,\n\tgetDocumentAttributes,\n} from \"./utils.js\";\n\n/**\n * This is very similar to {@link @fluidframework/protocol-definitions/internal#ISnapshot}, but the difference is\n * that the blobs of ISnapshot are of type ArrayBufferLike, while the blobs of this interface are serializable because\n * they are already converted to string.\n */\nexport interface SnapshotWithBlobs {\n\t/**\n\t * Snapshot from which container initially loaded.\n\t */\n\tbaseSnapshot: ISnapshotTree;\n\t/**\n\t * Serializable blobs from the base snapshot. Used to load offline since\n\t * storage is not available.\n\t */\n\tsnapshotBlobs: ISerializableBlobContents;\n}\n\n/**\n * State saved by a container at close time, to be used to load a new instance\n * of the container to the same state\n *\n * This is very similar to {@link @fluidframework/protocol-definitions/internal#ISnapshot}, but the difference is\n * that the blobs of ISnapshot are of type ArrayBufferLike, while the blobs of this interface are serializable because\n * they are already converted to string.\n *\n * @internal\n */\nexport interface IPendingContainerState extends SnapshotWithBlobs {\n\t/**\n\t * This container was attached (as opposed to IPendingDetachedContainerState.attached which is false)\n\t */\n\tattached: true;\n\t/**\n\t * Runtime-specific state that will be needed to properly rehydrate\n\t * (it's included in ContainerContext passed to instantiateRuntime)\n\t */\n\tpendingRuntimeState: unknown;\n\t/**\n\t * Any group snapshots (aka delay-loaded) we've downloaded from the service for this container\n\t */\n\tloadedGroupIdSnapshots?: Record<string, SerializedSnapshotInfo>;\n\t/**\n\t * All ops since base snapshot sequence number up to the latest op\n\t * seen when the container was closed. Used to apply stashed (saved pending)\n\t * ops at the same sequence number at which they were made.\n\t */\n\tsavedOps: ISequencedDocumentMessage[];\n\t/**\n\t * The Container's URL in the service, needed to hook up the driver during rehydration\n\t */\n\turl: string;\n\t/**\n\t * If the Container was connected when serialized, its clientId. Used as the initial clientId upon rehydration, until reconnected.\n\t */\n\tclientId?: string;\n}\n\n/**\n * State saved by a container in detached state, to be used to load a new instance\n * of the container to the same state (rehydrate)\n * @internal\n */\nexport interface IPendingDetachedContainerState extends SnapshotWithBlobs {\n\t/**\n\t * This container was not attached (as opposed to IPendingContainerState.attached which is true)\n\t */\n\tattached: false;\n\t/**\n\t * Indicates whether we expect the rehydrated container to have non-empty Detached Blob Storage\n\t */\n\thasAttachmentBlobs: boolean;\n\t/**\n\t * Used by the memory blob storage to persisted attachment blobs\n\t */\n\tattachmentBlobs?: string;\n\t/**\n\t * Runtime-specific state that will be needed to properly rehydrate\n\t * (it's included in ContainerContext passed to instantiateRuntime)\n\t */\n\tpendingRuntimeState?: unknown;\n}\n\nexport interface SerializedSnapshotInfo extends SnapshotWithBlobs {\n\tsnapshotSequenceNumber: number;\n}\n\nexport interface ISnapshotInfo {\n\tsnapshotSequenceNumber: number;\n\tsnapshotFetchedTime?: number | undefined;\n\tsnapshot: ISnapshot | ISnapshotTree;\n}\n\nexport type ISerializedStateManagerDocumentStorageService = Pick<\n\tContainerStorageAdapter,\n\t\"getSnapshot\" | \"getSnapshotTree\" | \"getVersions\" | \"readBlob\" | \"cacheSnapshotBlobs\"\n> & {\n\tloadedGroupIdSnapshots: Record<string, ISnapshot>;\n};\n\ninterface ISerializerEvent extends IEvent {\n\t(event: \"saved\", listener: (dirty: boolean) => void): void;\n}\n\n/**\n * Helper class to manage the state of the container needed for proper serialization.\n *\n * It holds the pendingLocalState the container was rehydrated from (if any),\n * as well as the snapshot to be used for serialization.\n * It also keeps track of container dirty state and which local ops have been processed\n */\nexport class SerializedStateManager implements IDisposable {\n\tprivate readonly processedOps: ISequencedDocumentMessage[] = [];\n\tprivate readonly mc: MonitoringContext;\n\tprivate snapshotInfo: ISnapshotInfo | undefined;\n\tprivate latestSnapshot: ISnapshotInfo | undefined;\n\tprivate lastSavedOpSequenceNumber: number = 0;\n\tprivate readonly snapshotRefresher: SnapshotRefresher | undefined;\n\t#disposed: boolean = false;\n\n\t/**\n\t * @param subLogger - Container's logger to use as parent for our logger\n\t * @param storageAdapter - Storage adapter for fetching snapshots\n\t * @param offlineLoadEnabled - Is serializing/rehydrating containers allowed?\n\t * @param containerEvent - Source of the \"saved\" event when the container has all its pending state uploaded\n\t * @param containerDirty - Is the container \"dirty\"? That's the opposite of \"saved\" - there is pending state that may not have been received yet by the service.\n\t */\n\tconstructor(\n\t\tsubLogger: ITelemetryBaseLogger,\n\t\tprivate readonly storageAdapter: ISerializedStateManagerDocumentStorageService,\n\t\tprivate readonly offlineLoadEnabled: boolean,\n\t\tcontainerEvent: IEventProvider<ISerializerEvent>,\n\t\tprivate readonly containerDirty: () => boolean,\n\t\tprivate readonly supportGetSnapshotApi: () => boolean,\n\t\tsnapshotRefreshTimeoutMs?: number,\n\t) {\n\t\tthis.mc = createChildMonitoringContext({\n\t\t\tlogger: subLogger,\n\t\t\tnamespace: \"serializedStateManager\",\n\t\t});\n\n\t\tthis.snapshotRefresher = this.offlineLoadEnabled\n\t\t\t? new SnapshotRefresher(\n\t\t\t\t\tsubLogger,\n\t\t\t\t\tthis.storageAdapter,\n\t\t\t\t\tthis.offlineLoadEnabled,\n\t\t\t\t\tthis.supportGetSnapshotApi,\n\t\t\t\t\t(snapshot: ISnapshotInfo) => this.handleSnapshotRefreshed(snapshot),\n\t\t\t\t\tsnapshotRefreshTimeoutMs,\n\t\t\t\t)\n\t\t\t: undefined;\n\n\t\tcontainerEvent.on(\"saved\", () => this.updateSnapshotAndProcessedOpsMaybe());\n\t}\n\tpublic get disposed(): boolean {\n\t\treturn this.#disposed;\n\t}\n\tdispose(): void {\n\t\tthis.#disposed = true;\n\t\tthis.snapshotRefresher?.dispose();\n\t}\n\n\tprivate verifyNotDisposed(): void {\n\t\tif (this.#disposed) {\n\t\t\tthrow new Error(\"SerializedStateManager used after dispose.\");\n\t\t}\n\t}\n\n\t/**\n\t * Promise that will resolve (or reject) once we've tried to download the latest snapshot(s) from storage\n\t * only intended to be used for testing purposes.\n\t * @returns The snapshot sequence number associated with the latest fetched snapshot\n\t */\n\tpublic get refreshSnapshotP(): Promise<number> | undefined {\n\t\treturn this.snapshotRefresher?.refreshSnapshotP;\n\t}\n\n\t/**\n\t * Called whenever an incoming op is processed by the Container\n\t */\n\tpublic addProcessedOp(message: ISequencedDocumentMessage): void {\n\t\tif (this.offlineLoadEnabled) {\n\t\t\tthis.processedOps.push(message);\n\t\t\tthis.updateSnapshotAndProcessedOpsMaybe();\n\t\t}\n\t}\n\n\t/**\n\t * This wraps the basic functionality of fetching the snapshot for this container during Container load.\n\t *\n\t * If we have pendingLocalState, we get the snapshot from there.\n\t * Otherwise, fetch it from storage (according to specifiedVersion if provided).\n\t *\n\t * @param specifiedVersion - If a version is specified and we don't have pendingLocalState, fetch this version from storage.\n\t * @param pendingLocalState - The pendingLocalState being rehydrated, if any (undefined when loading directly from storage)\n\t * @returns The snapshot to boot the container from\n\t */\n\tpublic async fetchSnapshot(\n\t\tspecifiedVersion: string | undefined,\n\t\tpendingLocalState: IPendingContainerState | undefined,\n\t): Promise<{\n\t\tsnapshot: ISnapshot | ISnapshotTree;\n\t\tversion: IVersion | undefined;\n\t\tattributes: IDocumentAttributes;\n\t}> {\n\t\tthis.verifyNotDisposed();\n\t\tif (pendingLocalState === undefined) {\n\t\t\tconst { snapshot, version } = await getSnapshot(\n\t\t\t\tthis.mc,\n\t\t\t\tthis.storageAdapter,\n\t\t\t\tthis.supportGetSnapshotApi(),\n\t\t\t\tspecifiedVersion,\n\t\t\t);\n\t\t\tconst baseSnapshotTree: ISnapshotTree | undefined = getSnapshotTree(snapshot);\n\t\t\tconst attributes = await getDocumentAttributes(this.storageAdapter, baseSnapshotTree);\n\t\t\tif (this.offlineLoadEnabled) {\n\t\t\t\tthis.snapshotRefresher?.startTimer();\n\t\t\t\tthis.snapshotInfo = {\n\t\t\t\t\tsnapshot,\n\t\t\t\t\tsnapshotSequenceNumber: attributes.sequenceNumber,\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn { snapshot, version, attributes };\n\t\t} else {\n\t\t\tconst { baseSnapshot, snapshotBlobs, savedOps } = pendingLocalState;\n\t\t\tconst blobContents = new Map<string, ArrayBuffer>();\n\t\t\tfor (const [id, value] of Object.entries(snapshotBlobs)) {\n\t\t\t\tblobContents.set(id, stringToBuffer(value, \"utf8\"));\n\t\t\t}\n\t\t\tthis.storageAdapter.cacheSnapshotBlobs(blobContents);\n\t\t\tconst attributes = await getDocumentAttributes(this.storageAdapter, baseSnapshot);\n\n\t\t\tconst snapshot: ISnapshot = {\n\t\t\t\tsequenceNumber: attributes.sequenceNumber,\n\t\t\t\tsnapshotTree: baseSnapshot,\n\t\t\t\tblobContents,\n\t\t\t\tlatestSequenceNumber: undefined,\n\t\t\t\tops: [],\n\t\t\t\tsnapshotFormatV: 1,\n\t\t\t};\n\n\t\t\tif (this.offlineLoadEnabled) {\n\t\t\t\t// special case handle. Obtaining the last saved op seq num to avoid\n\t\t\t\t// refreshing the snapshot before we have processed it. It could cause\n\t\t\t\t// a subsequent stashing to have a newer snapshot than allowed.\n\t\t\t\tif (savedOps.length > 0) {\n\t\t\t\t\tconst savedOpsSize = savedOps.length;\n\t\t\t\t\tthis.lastSavedOpSequenceNumber = savedOps[savedOpsSize - 1].sequenceNumber;\n\t\t\t\t}\n\n\t\t\t\tthis.snapshotInfo = {\n\t\t\t\t\tsnapshot,\n\t\t\t\t\tsnapshotSequenceNumber: attributes.sequenceNumber,\n\t\t\t\t};\n\t\t\t\tthis.snapshotRefresher?.tryRefreshSnapshot();\n\t\t\t}\n\t\t\treturn { snapshot, version: undefined, attributes };\n\t\t}\n\t}\n\n\t/**\n\t * Handles the snapshotRefreshed event from SnapshotRefresher.\n\t * Decides whether to accept the new snapshot based on processed ops.\n\t * @returns The snapshot sequence number if updated, -1 otherwise\n\t */\n\tprivate handleSnapshotRefreshed(latestSnapshot: ISnapshotInfo): number {\n\t\tthis.latestSnapshot = latestSnapshot;\n\t\treturn this.updateSnapshotAndProcessedOpsMaybe();\n\t}\n\n\t/**\n\t * Updates class snapshot and processedOps if we have a new snapshot and it's among processedOps range.\n\t */\n\tprivate updateSnapshotAndProcessedOpsMaybe(): number {\n\t\tconst snapshotSequenceNumber = this.latestSnapshot?.snapshotSequenceNumber;\n\t\tif (\n\t\t\tthis.#disposed ||\n\t\t\tsnapshotSequenceNumber === undefined ||\n\t\t\tthis.processedOps.length === 0 ||\n\t\t\tthis.processedOps[this.processedOps.length - 1].sequenceNumber <\n\t\t\t\tthis.lastSavedOpSequenceNumber ||\n\t\t\tthis.containerDirty()\n\t\t) {\n\t\t\t// can't refresh latest snapshot until we have processed the ops up to it.\n\t\t\t// Pending state would be behind the latest snapshot.\n\t\t\treturn -1;\n\t\t}\n\t\tconst firstProcessedOpSequenceNumber = this.processedOps[0].sequenceNumber;\n\t\tconst lastProcessedOpSequenceNumber =\n\t\t\tthis.processedOps[this.processedOps.length - 1].sequenceNumber;\n\n\t\tif (snapshotSequenceNumber < firstProcessedOpSequenceNumber) {\n\t\t\t// Snapshot seq number is older than our first processed op, which could mean we're fetching\n\t\t\t// the same snapshot that we already have or snapshot is too old, implicating an unexpected behavior.\n\t\t\tthis.mc.logger.sendTelemetryEvent({\n\t\t\t\teventName: \"OldSnapshotFetchWhileRefreshing\",\n\t\t\t\tsnapshotSequenceNumber,\n\t\t\t\tfirstProcessedOpSequenceNumber,\n\t\t\t\tlastProcessedOpSequenceNumber,\n\t\t\t\tstashedSnapshotSequenceNumber: this.snapshotInfo?.snapshotSequenceNumber,\n\t\t\t});\n\t\t\tthis.latestSnapshot = undefined;\n\t\t\tthis.snapshotRefresher?.clearLatestSnapshot();\n\t\t} else if (snapshotSequenceNumber <= lastProcessedOpSequenceNumber) {\n\t\t\t// Snapshot seq num is between the first and last processed op.\n\t\t\t// Remove the ops that are already part of the snapshot\n\t\t\tthis.processedOps.splice(0, snapshotSequenceNumber - firstProcessedOpSequenceNumber + 1);\n\t\t\tthis.snapshotInfo = this.latestSnapshot;\n\t\t\tthis.latestSnapshot = undefined;\n\t\t\tthis.snapshotRefresher?.clearLatestSnapshot();\n\t\t\tthis.mc.logger.sendTelemetryEvent({\n\t\t\t\teventName: \"SnapshotRefreshed\",\n\t\t\t\tsnapshotSequenceNumber,\n\t\t\t\tfirstProcessedOpSequenceNumber,\n\t\t\t\tnewFirstProcessedOpSequenceNumber:\n\t\t\t\t\tthis.processedOps.length === 0 ? undefined : this.processedOps[0].sequenceNumber,\n\t\t\t});\n\t\t}\n\t\treturn snapshotSequenceNumber;\n\t}\n\n\t/**\n\t * When the Container attaches, we need to stash the initial snapshot (a form of the attach summary).\n\t * This method is only meant to be used by Container.attach() to set the initial\n\t * base snapshot when attaching.\n\t * @param snapshot - snapshot and blobs collected while attaching (a form of the attach summary)\n\t */\n\tpublic setInitialSnapshot(snapshot: ISnapshot): void {\n\t\tthis.verifyNotDisposed();\n\t\tif (this.offlineLoadEnabled) {\n\t\t\tthis.snapshotInfo = {\n\t\t\t\tsnapshot,\n\t\t\t\tsnapshotSequenceNumber: snapshot.sequenceNumber ?? 0,\n\t\t\t\tsnapshotFetchedTime: Date.now(),\n\t\t\t};\n\t\t\tthis.snapshotRefresher?.startTimer();\n\t\t}\n\t}\n\n\t/**\n\t * Assembles and serializes the {@link IPendingContainerState} for the container,\n\t * to be stored and used to rehydrate the container at a later time.\n\t */\n\tpublic async getPendingLocalState(\n\t\tclientId: string | undefined,\n\t\truntime: Pick<IRuntime, \"getPendingLocalState\">,\n\t\tresolvedUrl: IResolvedUrl,\n\t): Promise<string> {\n\t\tthis.verifyNotDisposed();\n\t\tif (!this.offlineLoadEnabled) {\n\t\t\tthrow new UsageError(\"Can't get pending local state unless offline load is enabled\");\n\t\t}\n\n\t\treturn PerformanceEvent.timedExecAsync(\n\t\t\tthis.mc.logger,\n\t\t\t{\n\t\t\t\teventName: \"getPendingLocalState\",\n\t\t\t\tdetails: {\n\t\t\t\t\tnotifyImminentClosure: false,\n\t\t\t\t\tsessionExpiryTimerStarted: undefined,\n\t\t\t\t\tsnapshotSequenceNumber: undefined,\n\t\t\t\t\tprocessedOpsSize: this.processedOps.length,\n\t\t\t\t},\n\t\t\t\tclientId,\n\t\t\t},\n\t\t\tasync () => {\n\t\t\t\tassert(this.snapshotInfo !== undefined, 0x8e5 /* no base data */);\n\t\t\t\tconst pendingRuntimeState = await runtime.getPendingLocalState({\n\t\t\t\t\tnotifyImminentClosure: false,\n\t\t\t\t\tsnapshotSequenceNumber: this.snapshotInfo.snapshotSequenceNumber,\n\t\t\t\t\tsessionExpiryTimerStarted: this.snapshotInfo.snapshotFetchedTime,\n\t\t\t\t});\n\t\t\t\t// This conversion is required because ArrayBufferLike doesn't survive JSON.stringify\n\t\t\t\tconst loadedGroupIdSnapshots: Record<string, SerializedSnapshotInfo> = {};\n\t\t\t\tlet hasGroupIdSnapshots = false;\n\t\t\t\tconst groupIdSnapshots = Object.entries(this.storageAdapter.loadedGroupIdSnapshots);\n\t\t\t\tif (groupIdSnapshots.length > 0) {\n\t\t\t\t\tfor (const [groupId, snapshot] of groupIdSnapshots) {\n\t\t\t\t\t\thasGroupIdSnapshots = true;\n\t\t\t\t\t\tloadedGroupIdSnapshots[groupId] = convertSnapshotToSnapshotInfo(snapshot);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tconst snapshotWithBlobs: SnapshotWithBlobs = isInstanceOfISnapshot(\n\t\t\t\t\tthis.snapshotInfo.snapshot,\n\t\t\t\t)\n\t\t\t\t\t? convertISnapshotToSnapshotWithBlobs(this.snapshotInfo.snapshot)\n\t\t\t\t\t: await convertSnapshotTreeToSnapshotWithBlobs(\n\t\t\t\t\t\t\tthis.snapshotInfo.snapshot,\n\t\t\t\t\t\t\tthis.storageAdapter,\n\t\t\t\t\t\t);\n\n\t\t\t\tconst pendingState: IPendingContainerState = {\n\t\t\t\t\tattached: true,\n\t\t\t\t\tpendingRuntimeState,\n\t\t\t\t\t...snapshotWithBlobs,\n\t\t\t\t\tloadedGroupIdSnapshots: hasGroupIdSnapshots ? loadedGroupIdSnapshots : undefined,\n\t\t\t\t\tsavedOps: this.processedOps,\n\t\t\t\t\turl: resolvedUrl.url,\n\t\t\t\t\tclientId,\n\t\t\t\t};\n\n\t\t\t\treturn JSON.stringify(pendingState);\n\t\t\t},\n\t\t);\n\t}\n}\n\nasync function convertSnapshotTreeToSnapshotWithBlobs(\n\tsnapshot: ISnapshotTree,\n\tstorageAdapter: ISerializedStateManagerDocumentStorageService,\n): Promise<SnapshotWithBlobs> {\n\tconst snapshotBlobs = await getBlobContentsFromTree(snapshot, storageAdapter);\n\treturn {\n\t\tbaseSnapshot: snapshot,\n\t\tsnapshotBlobs,\n\t};\n}\n\n/**\n * Retrieves the most recent snapshot and returns its info.\n *\n * @param mc - The monitoring context.\n * @param storageAdapter - The storage adapter providing methods to retrieve the snapshot.\n * @param supportGetSnapshotApi - a boolean indicating whether to use the fetchISnapshot or fetchISnapshotTree.\n * @returns a SnapshotInfo object containing the snapshot tree, snapshot blobs and its sequence number.\n */\nexport async function getLatestSnapshotInfo(\n\tmc: MonitoringContext,\n\tstorageAdapter: ISerializedStateManagerDocumentStorageService,\n\tsupportGetSnapshotApi: boolean,\n): Promise<ISnapshotInfo | undefined> {\n\treturn PerformanceEvent.timedExecAsync<ISnapshotInfo | undefined>(\n\t\tmc.logger,\n\t\t{ eventName: \"GetLatestSnapshotInfo\" },\n\t\tasync (event) => {\n\t\t\ttry {\n\t\t\t\t// get the latest non cached snapshot version\n\t\t\t\tconst specifiedVersion: IVersion[] = await storageAdapter.getVersions(\n\t\t\t\t\t// eslint-disable-next-line unicorn/no-null\n\t\t\t\t\tnull,\n\t\t\t\t\t1,\n\t\t\t\t\t\"getLatestSnapshotInfo\",\n\t\t\t\t\tFetchSource.noCache,\n\t\t\t\t);\n\t\t\t\tconst { snapshot: baseSnapshot } = await getSnapshot(\n\t\t\t\t\tmc,\n\t\t\t\t\tstorageAdapter,\n\t\t\t\t\tsupportGetSnapshotApi,\n\t\t\t\t\tspecifiedVersion[0]?.id,\n\t\t\t\t);\n\n\t\t\t\tconst { sequenceNumber, snapshotTree } = isInstanceOfISnapshot(baseSnapshot)\n\t\t\t\t\t? baseSnapshot\n\t\t\t\t\t: { snapshotTree: baseSnapshot, sequenceNumber: undefined };\n\n\t\t\t\tconst snapshotSequenceNumber: number =\n\t\t\t\t\tsequenceNumber ??\n\t\t\t\t\t(await getDocumentAttributes(storageAdapter, snapshotTree).then(\n\t\t\t\t\t\t(a) => a.sequenceNumber,\n\t\t\t\t\t));\n\t\t\t\treturn {\n\t\t\t\t\tsnapshot: baseSnapshot,\n\t\t\t\t\tsnapshotSequenceNumber,\n\t\t\t\t\tsnapshotFetchedTime: Date.now(),\n\t\t\t\t};\n\t\t\t} catch (error) {\n\t\t\t\tevent.cancel(undefined, error);\n\t\t\t}\n\t\t\treturn undefined;\n\t\t},\n\t);\n}\n\n/**\n * Retrieves a snapshot from the storage adapter and transforms it into an ISnapshotTree object.\n *\n * @param mc - The monitoring context.\n * @param storageAdapter - The storage adapter providing methods to retrieve the snapshot.\n * @param supportGetSnapshotApi - a boolean indicating whether to use the fetchISnapshot or fetchISnapshotTree.\n * @param specifiedVersion - An optional version string specifying the version of the snapshot tree to fetch.\n * @returns An ISnapshotTree and its version.\n */\nasync function getSnapshot(\n\tmc: MonitoringContext,\n\tstorageAdapter: Pick<\n\t\tIDocumentStorageService,\n\t\t\"getSnapshot\" | \"getSnapshotTree\" | \"getVersions\"\n\t>,\n\tsupportGetSnapshotApi: boolean,\n\tspecifiedVersion: string | undefined,\n): Promise<{ snapshot: ISnapshot | ISnapshotTree; version?: IVersion }> {\n\tconst { snapshot, version } = supportGetSnapshotApi\n\t\t? await fetchISnapshot(mc, storageAdapter, specifiedVersion)\n\t\t: await fetchISnapshotTree(mc, storageAdapter, specifiedVersion);\n\tassert(snapshot !== undefined, 0x8e4 /* Snapshot should exist */);\n\treturn { snapshot, version };\n}\n\n/**\n * Fetches an ISnapshot from a storage adapter based on the specified version.\n *\n * @param mc - The monitoring context.\n * @param storageAdapter - The storage adapter providing a getSnapshot method to retrieve the ISnapshot and version.\n * @param specifiedVersion - An optional version string specifying the version of the snapshot tree to fetch.\n * @returns The fetched snapshot tree and its version.\n */\nexport async function fetchISnapshot(\n\tmc: MonitoringContext,\n\tstorageAdapter: Pick<IDocumentStorageService, \"getSnapshot\">,\n\tspecifiedVersion: string | undefined,\n): Promise<{ snapshot?: ISnapshot; version?: IVersion }> {\n\tconst snapshot = await storageAdapter.getSnapshot?.({ versionId: specifiedVersion });\n\tconst version: IVersion | undefined =\n\t\tsnapshot?.snapshotTree.id === undefined\n\t\t\t? undefined\n\t\t\t: {\n\t\t\t\t\tid: snapshot.snapshotTree.id,\n\t\t\t\t\ttreeId: snapshot.snapshotTree.id,\n\t\t\t\t};\n\n\tif (snapshot === undefined && specifiedVersion !== undefined) {\n\t\tmc.logger.sendErrorEvent({\n\t\t\teventName: \"getSnapshotTreeFailed\",\n\t\t\tid: specifiedVersion,\n\t\t});\n\t} else if (snapshot !== undefined && version?.id === undefined) {\n\t\tmc.logger.sendErrorEvent({\n\t\t\teventName: \"getSnapshotFetchedTreeWithoutVersionId\",\n\t\t\thasVersion: version !== undefined, // if hasVersion is true, this means that the contract with the service was broken.\n\t\t});\n\t}\n\treturn { snapshot, version };\n}\n\n/**\n * Fetches an ISnapshotTree from a storage adapter based on the specified version.\n *\n * @param mc - The monitoring context.\n * @param storageAdapter - The storage adapter providing methods to retrieve the ISnapshotTree and version.\n * @param specifiedVersion - An optional version string specifying the version of the snapshot tree to fetch.\n * @returns The fetched snapshot tree and its version.\n */\nexport async function fetchISnapshotTree(\n\tmc: MonitoringContext,\n\tstorageAdapter: Pick<IDocumentStorageService, \"getSnapshotTree\" | \"getVersions\">,\n\tspecifiedVersion: string | undefined,\n): Promise<{ snapshot?: ISnapshotTree; version?: IVersion | undefined }> {\n\t// API uses null\n\t// eslint-disable-next-line unicorn/no-null\n\tconst versions = await storageAdapter.getVersions(specifiedVersion ?? null, 1);\n\tconst version = versions[0];\n\n\tif (version === undefined && specifiedVersion !== undefined) {\n\t\t// We should have a defined version to load from if specified version requested\n\t\tmc.logger.sendErrorEvent({\n\t\t\teventName: \"NoVersionFoundWhenSpecified\",\n\t\t\tid: specifiedVersion,\n\t\t});\n\t}\n\tconst snapshot = (await storageAdapter.getSnapshotTree(version)) ?? undefined;\n\n\tif (snapshot === undefined && version !== undefined) {\n\t\tmc.logger.sendErrorEvent({ eventName: \"getSnapshotTreeFailed\", id: version.id });\n\t} else if (snapshot !== undefined && version?.id === undefined) {\n\t\tmc.logger.sendErrorEvent({\n\t\t\teventName: \"getSnapshotFetchedTreeWithoutVersionId\",\n\t\t\thasVersion: version !== undefined, // if hasVersion is true, this means that the contract with the service was broken.\n\t\t});\n\t}\n\treturn { snapshot, version };\n}\n"]}
@@ -0,0 +1,68 @@
1
+ /*!
2
+ * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
3
+ * Licensed under the MIT License.
4
+ */
5
+ import type { ITelemetryBaseLogger } from "@fluidframework/core-interfaces";
6
+ import type { IDisposable } from "@fluidframework/core-interfaces/internal";
7
+ import { type ISerializedStateManagerDocumentStorageService, type ISnapshotInfo } from "./serializedStateManager.js";
8
+ /**
9
+ * Manages periodic refresh of the latest snapshot for a document.
10
+ *
11
+ * `SnapshotRefresher` polls the storage service for the most recent snapshot and, when a newer
12
+ * snapshot is discovered, invokes the provided `onSnapshotRefreshed` callback with the updated
13
+ * snapshot metadata. It is responsible for:
14
+ *
15
+ * - Tracking the most recent snapshot that has been observed.
16
+ * - Scheduling and managing refresh attempts via an internal timer.
17
+ * - Emitting telemetry for successful and failed refresh attempts.
18
+ *
19
+ * The refresh behavior can be configured via constructor arguments, including whether offline
20
+ * loading and the `getSnapshot` API are supported, as well as the refresh timeout. Callers
21
+ * should dispose this instance when snapshot refresh is no longer needed to stop any pending
22
+ * timers and prevent further refresh attempts.
23
+ */
24
+ export declare class SnapshotRefresher implements IDisposable {
25
+ #private;
26
+ private readonly storageAdapter;
27
+ private readonly offlineLoadEnabled;
28
+ private readonly supportGetSnapshotApi;
29
+ private readonly onSnapshotRefreshed;
30
+ private readonly mc;
31
+ private latestSnapshot;
32
+ get disposed(): boolean;
33
+ private readonly refreshTracker;
34
+ private readonly refreshTimer;
35
+ private readonly snapshotRefreshTimeoutMs;
36
+ constructor(subLogger: ITelemetryBaseLogger, storageAdapter: ISerializedStateManagerDocumentStorageService, offlineLoadEnabled: boolean, supportGetSnapshotApi: () => boolean, onSnapshotRefreshed: (snapshot: ISnapshotInfo) => number, snapshotRefreshTimeoutMs?: number);
37
+ tryRefreshSnapshot(): void;
38
+ /**
39
+ * Fetch the latest snapshot for the container, including delay-loaded groupIds if pendingLocalState was provided and contained any groupIds.
40
+ * Note that this will update the StorageAdapter's cached snapshots for the groupIds (if present)
41
+ *
42
+ * @param supportGetSnapshotApi - a boolean indicating whether to use the fetchISnapshot or fetchISnapshotTree (must be true to fetch by groupIds)
43
+ */
44
+ private refreshLatestSnapshot;
45
+ /**
46
+ * Clears the latest snapshot after it's been consumed by the manager.
47
+ * This allows the next refresh cycle to proceed.
48
+ */
49
+ clearLatestSnapshot(): void;
50
+ /**
51
+ * Starts the refresh timer.
52
+ */
53
+ startTimer(): void;
54
+ /**
55
+ * Restarts the refresh timer.
56
+ */
57
+ restartTimer(): void;
58
+ /**
59
+ * Gets the current refresh promise for testing purposes.
60
+ * @returns The snapshot sequence number promise, or undefined if no refresh is in progress
61
+ */
62
+ get refreshSnapshotP(): Promise<number> | undefined;
63
+ /**
64
+ * Disposes the refresher and clears the timer.
65
+ */
66
+ dispose(): void;
67
+ }
68
+ //# sourceMappingURL=snapshotRefresher.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"snapshotRefresher.d.ts","sourceRoot":"","sources":["../src/snapshotRefresher.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,iCAAiC,CAAC;AAC5E,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,0CAA0C,CAAC;AAQ5E,OAAO,EAEN,KAAK,6CAA6C,EAClD,KAAK,aAAa,EAClB,MAAM,6BAA6B,CAAC;AAyBrC;;;;;;;;;;;;;;;GAeG;AACH,qBAAa,iBAAkB,YAAW,WAAW;;IAyBnD,OAAO,CAAC,QAAQ,CAAC,cAAc;IAC/B,OAAO,CAAC,QAAQ,CAAC,kBAAkB;IACnC,OAAO,CAAC,QAAQ,CAAC,qBAAqB;IACtC,OAAO,CAAC,QAAQ,CAAC,mBAAmB;IA3BrC,OAAO,CAAC,QAAQ,CAAC,EAAE,CAAoB;IACvC,OAAO,CAAC,cAAc,CAA4B;IAGlD,IAAW,QAAQ,IAAI,OAAO,CAE7B;IAED,OAAO,CAAC,QAAQ,CAAC,cAAc,CAS7B;IACF,OAAO,CAAC,QAAQ,CAAC,YAAY,CAAoB;IACjD,OAAO,CAAC,QAAQ,CAAC,wBAAwB,CAA+B;gBAIvE,SAAS,EAAE,oBAAoB,EACd,cAAc,EAAE,6CAA6C,EAC7D,kBAAkB,EAAE,OAAO,EAC3B,qBAAqB,EAAE,MAAM,OAAO,EACpC,mBAAmB,EAAE,CAAC,QAAQ,EAAE,aAAa,KAAK,MAAM,EACzE,wBAAwB,CAAC,EAAE,MAAM;IAmB3B,kBAAkB,IAAI,IAAI;IAYjC;;;;;OAKG;YACW,qBAAqB;IAsCnC;;;OAGG;IACI,mBAAmB,IAAI,IAAI;IAIlC;;OAEG;IACI,UAAU,IAAI,IAAI;IAIzB;;OAEG;IACI,YAAY,IAAI,IAAI;IAI3B;;;OAGG;IACH,IAAW,gBAAgB,IAAI,OAAO,CAAC,MAAM,CAAC,GAAG,SAAS,CAEzD;IAED;;OAEG;IACI,OAAO,IAAI,IAAI;CAItB"}
@@ -0,0 +1,163 @@
1
+ /*!
2
+ * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
3
+ * Licensed under the MIT License.
4
+ */
5
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
6
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
7
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
8
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
9
+ };
10
+ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
11
+ if (kind === "m") throw new TypeError("Private method is not writable");
12
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
13
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
14
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
15
+ };
16
+ var _RefreshPromiseTracker_promise, _SnapshotRefresher_disposed, _SnapshotRefresher_snapshotRefreshEnabled;
17
+ import { assert, Timer } from "@fluidframework/core-utils/internal";
18
+ import { FetchSource } from "@fluidframework/driver-definitions/internal";
19
+ import { createChildMonitoringContext, } from "@fluidframework/telemetry-utils/internal";
20
+ import { getLatestSnapshotInfo, } from "./serializedStateManager.js";
21
+ class RefreshPromiseTracker {
22
+ get hasPromise() {
23
+ return __classPrivateFieldGet(this, _RefreshPromiseTracker_promise, "f") !== undefined;
24
+ }
25
+ get promise() {
26
+ return __classPrivateFieldGet(this, _RefreshPromiseTracker_promise, "f");
27
+ }
28
+ constructor(catchHandler) {
29
+ this.catchHandler = catchHandler;
30
+ _RefreshPromiseTracker_promise.set(this, void 0);
31
+ }
32
+ setPromise(p) {
33
+ if (this.hasPromise) {
34
+ throw new Error("Cannot start new snapshot refresh while a refresh is already in progress");
35
+ }
36
+ __classPrivateFieldSet(this, _RefreshPromiseTracker_promise, p.finally(() => {
37
+ __classPrivateFieldSet(this, _RefreshPromiseTracker_promise, undefined, "f");
38
+ }), "f");
39
+ p.catch(this.catchHandler);
40
+ }
41
+ }
42
+ _RefreshPromiseTracker_promise = new WeakMap();
43
+ /**
44
+ * Manages periodic refresh of the latest snapshot for a document.
45
+ *
46
+ * `SnapshotRefresher` polls the storage service for the most recent snapshot and, when a newer
47
+ * snapshot is discovered, invokes the provided `onSnapshotRefreshed` callback with the updated
48
+ * snapshot metadata. It is responsible for:
49
+ *
50
+ * - Tracking the most recent snapshot that has been observed.
51
+ * - Scheduling and managing refresh attempts via an internal timer.
52
+ * - Emitting telemetry for successful and failed refresh attempts.
53
+ *
54
+ * The refresh behavior can be configured via constructor arguments, including whether offline
55
+ * loading and the `getSnapshot` API are supported, as well as the refresh timeout. Callers
56
+ * should dispose this instance when snapshot refresh is no longer needed to stop any pending
57
+ * timers and prevent further refresh attempts.
58
+ */
59
+ export class SnapshotRefresher {
60
+ get disposed() {
61
+ return __classPrivateFieldGet(this, _SnapshotRefresher_disposed, "f");
62
+ }
63
+ constructor(subLogger, storageAdapter, offlineLoadEnabled, supportGetSnapshotApi, onSnapshotRefreshed, snapshotRefreshTimeoutMs) {
64
+ this.storageAdapter = storageAdapter;
65
+ this.offlineLoadEnabled = offlineLoadEnabled;
66
+ this.supportGetSnapshotApi = supportGetSnapshotApi;
67
+ this.onSnapshotRefreshed = onSnapshotRefreshed;
68
+ _SnapshotRefresher_disposed.set(this, false);
69
+ this.refreshTracker = new RefreshPromiseTracker(
70
+ // eslint-disable-next-line unicorn/consistent-function-scoping
71
+ (error) => this.mc.logger.sendErrorEvent({
72
+ eventName: "RefreshLatestSnapshotFailed",
73
+ }, error));
74
+ this.snapshotRefreshTimeoutMs = 60 * 60 * 24 * 1000;
75
+ _SnapshotRefresher_snapshotRefreshEnabled.set(this, void 0);
76
+ this.mc = createChildMonitoringContext({
77
+ logger: subLogger,
78
+ namespace: "serializedStateManager",
79
+ });
80
+ this.snapshotRefreshTimeoutMs = snapshotRefreshTimeoutMs ?? this.snapshotRefreshTimeoutMs;
81
+ __classPrivateFieldSet(this, _SnapshotRefresher_snapshotRefreshEnabled, this.offlineLoadEnabled &&
82
+ (this.mc.config.getBoolean("Fluid.Container.enableOfflineSnapshotRefresh") ??
83
+ this.mc.config.getBoolean("Fluid.Container.enableOfflineFull")) === true, "f");
84
+ this.refreshTimer = __classPrivateFieldGet(this, _SnapshotRefresher_snapshotRefreshEnabled, "f")
85
+ ? new Timer(this.snapshotRefreshTimeoutMs, () => this.tryRefreshSnapshot())
86
+ : undefined;
87
+ }
88
+ tryRefreshSnapshot() {
89
+ if (__classPrivateFieldGet(this, _SnapshotRefresher_snapshotRefreshEnabled, "f") &&
90
+ !__classPrivateFieldGet(this, _SnapshotRefresher_disposed, "f") &&
91
+ !this.refreshTracker.hasPromise &&
92
+ this.latestSnapshot === undefined) {
93
+ // Don't block on the refresh snapshot call - it is for the next time we serialize, not booting this incarnation
94
+ this.refreshTracker.setPromise(this.refreshLatestSnapshot(this.supportGetSnapshotApi()));
95
+ }
96
+ }
97
+ /**
98
+ * Fetch the latest snapshot for the container, including delay-loaded groupIds if pendingLocalState was provided and contained any groupIds.
99
+ * Note that this will update the StorageAdapter's cached snapshots for the groupIds (if present)
100
+ *
101
+ * @param supportGetSnapshotApi - a boolean indicating whether to use the fetchISnapshot or fetchISnapshotTree (must be true to fetch by groupIds)
102
+ */
103
+ async refreshLatestSnapshot(supportGetSnapshotApi) {
104
+ this.latestSnapshot = await getLatestSnapshotInfo(this.mc, this.storageAdapter, supportGetSnapshotApi);
105
+ if (__classPrivateFieldGet(this, _SnapshotRefresher_disposed, "f")) {
106
+ return -1;
107
+ }
108
+ // These are loading groupIds that the containerRuntime has requested over its lifetime.
109
+ // We will fetch the latest snapshot for the groupIds, which will update storageAdapter.loadedGroupIdSnapshots's cache
110
+ const downloadedGroupIds = Object.keys(this.storageAdapter.loadedGroupIdSnapshots);
111
+ if (supportGetSnapshotApi && downloadedGroupIds.length > 0) {
112
+ assert(this.storageAdapter.getSnapshot !== undefined, 0x972 /* getSnapshot should exist */);
113
+ // (This is a separate network call from above because it requires work for storage to add a special base groupId)
114
+ const snapshot = await this.storageAdapter.getSnapshot({
115
+ versionId: undefined,
116
+ scenarioName: "getLatestSnapshotInfo",
117
+ cacheSnapshot: false,
118
+ loadingGroupIds: downloadedGroupIds,
119
+ fetchSource: FetchSource.noCache,
120
+ });
121
+ assert(snapshot !== undefined, 0x973 /* Snapshot should exist */);
122
+ }
123
+ // Notify the manager about the fetched snapshot - let it decide what to do with it
124
+ const result = this.latestSnapshot === undefined ? -1 : this.onSnapshotRefreshed(this.latestSnapshot);
125
+ this.refreshTimer?.restart();
126
+ return result;
127
+ }
128
+ /**
129
+ * Clears the latest snapshot after it's been consumed by the manager.
130
+ * This allows the next refresh cycle to proceed.
131
+ */
132
+ clearLatestSnapshot() {
133
+ this.latestSnapshot = undefined;
134
+ }
135
+ /**
136
+ * Starts the refresh timer.
137
+ */
138
+ startTimer() {
139
+ this.refreshTimer?.start();
140
+ }
141
+ /**
142
+ * Restarts the refresh timer.
143
+ */
144
+ restartTimer() {
145
+ this.refreshTimer?.restart();
146
+ }
147
+ /**
148
+ * Gets the current refresh promise for testing purposes.
149
+ * @returns The snapshot sequence number promise, or undefined if no refresh is in progress
150
+ */
151
+ get refreshSnapshotP() {
152
+ return this.refreshTracker.promise;
153
+ }
154
+ /**
155
+ * Disposes the refresher and clears the timer.
156
+ */
157
+ dispose() {
158
+ __classPrivateFieldSet(this, _SnapshotRefresher_disposed, true, "f");
159
+ this.refreshTimer?.clear();
160
+ }
161
+ }
162
+ _SnapshotRefresher_disposed = new WeakMap(), _SnapshotRefresher_snapshotRefreshEnabled = new WeakMap();
163
+ //# sourceMappingURL=snapshotRefresher.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"snapshotRefresher.js","sourceRoot":"","sources":["../src/snapshotRefresher.ts"],"names":[],"mappings":"AAAA;;;GAGG;;;;;;;;;;;;;AAIH,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,qCAAqC,CAAC;AACpE,OAAO,EAAE,WAAW,EAAE,MAAM,6CAA6C,CAAC;AAC1E,OAAO,EACN,4BAA4B,GAE5B,MAAM,0CAA0C,CAAC;AAElD,OAAO,EACN,qBAAqB,GAGrB,MAAM,6BAA6B,CAAC;AAErC,MAAM,qBAAqB;IAC1B,IAAW,UAAU;QACpB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A,CAAC;QACtB,IAAI,CAAC,YAAY,EAAE,KAAK,EAAE,CAAC;IAC5B,CAAC;CACD","sourcesContent":["/*!\n * Copyright (c) Microsoft Corporation and contributors. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport type { ITelemetryBaseLogger } from \"@fluidframework/core-interfaces\";\nimport type { IDisposable } from \"@fluidframework/core-interfaces/internal\";\nimport { assert, Timer } from \"@fluidframework/core-utils/internal\";\nimport { FetchSource } from \"@fluidframework/driver-definitions/internal\";\nimport {\n\tcreateChildMonitoringContext,\n\ttype MonitoringContext,\n} from \"@fluidframework/telemetry-utils/internal\";\n\nimport {\n\tgetLatestSnapshotInfo,\n\ttype ISerializedStateManagerDocumentStorageService,\n\ttype ISnapshotInfo,\n} from \"./serializedStateManager.js\";\n\nclass RefreshPromiseTracker {\n\tpublic get hasPromise(): boolean {\n\t\treturn this.#promise !== undefined;\n\t}\n\tpublic get promise(): Promise<number> | undefined {\n\t\treturn this.#promise;\n\t}\n\tconstructor(private readonly catchHandler: (error: Error) => void) {}\n\n\t#promise: Promise<number> | undefined;\n\tsetPromise(p: Promise<number>): void {\n\t\tif (this.hasPromise) {\n\t\t\tthrow new Error(\n\t\t\t\t\"Cannot start new snapshot refresh while a refresh is already in progress\",\n\t\t\t);\n\t\t}\n\t\tthis.#promise = p.finally(() => {\n\t\t\tthis.#promise = undefined;\n\t\t});\n\t\tp.catch(this.catchHandler);\n\t}\n}\n\n/**\n * Manages periodic refresh of the latest snapshot for a document.\n *\n * `SnapshotRefresher` polls the storage service for the most recent snapshot and, when a newer\n * snapshot is discovered, invokes the provided `onSnapshotRefreshed` callback with the updated\n * snapshot metadata. It is responsible for:\n *\n * - Tracking the most recent snapshot that has been observed.\n * - Scheduling and managing refresh attempts via an internal timer.\n * - Emitting telemetry for successful and failed refresh attempts.\n *\n * The refresh behavior can be configured via constructor arguments, including whether offline\n * loading and the `getSnapshot` API are supported, as well as the refresh timeout. Callers\n * should dispose this instance when snapshot refresh is no longer needed to stop any pending\n * timers and prevent further refresh attempts.\n */\nexport class SnapshotRefresher implements IDisposable {\n\tprivate readonly mc: MonitoringContext;\n\tprivate latestSnapshot: ISnapshotInfo | undefined;\n\t#disposed: boolean = false;\n\n\tpublic get disposed(): boolean {\n\t\treturn this.#disposed;\n\t}\n\n\tprivate readonly refreshTracker = new RefreshPromiseTracker(\n\t\t// eslint-disable-next-line unicorn/consistent-function-scoping\n\t\t(error) =>\n\t\t\tthis.mc.logger.sendErrorEvent(\n\t\t\t\t{\n\t\t\t\t\teventName: \"RefreshLatestSnapshotFailed\",\n\t\t\t\t},\n\t\t\t\terror,\n\t\t\t),\n\t);\n\tprivate readonly refreshTimer: Timer | undefined;\n\tprivate readonly snapshotRefreshTimeoutMs: number = 60 * 60 * 24 * 1000;\n\treadonly #snapshotRefreshEnabled: boolean;\n\n\tconstructor(\n\t\tsubLogger: ITelemetryBaseLogger,\n\t\tprivate readonly storageAdapter: ISerializedStateManagerDocumentStorageService,\n\t\tprivate readonly offlineLoadEnabled: boolean,\n\t\tprivate readonly supportGetSnapshotApi: () => boolean,\n\t\tprivate readonly onSnapshotRefreshed: (snapshot: ISnapshotInfo) => number,\n\t\tsnapshotRefreshTimeoutMs?: number,\n\t) {\n\t\tthis.mc = createChildMonitoringContext({\n\t\t\tlogger: subLogger,\n\t\t\tnamespace: \"serializedStateManager\",\n\t\t});\n\n\t\tthis.snapshotRefreshTimeoutMs = snapshotRefreshTimeoutMs ?? this.snapshotRefreshTimeoutMs;\n\n\t\tthis.#snapshotRefreshEnabled =\n\t\t\tthis.offlineLoadEnabled &&\n\t\t\t(this.mc.config.getBoolean(\"Fluid.Container.enableOfflineSnapshotRefresh\") ??\n\t\t\t\tthis.mc.config.getBoolean(\"Fluid.Container.enableOfflineFull\")) === true;\n\n\t\tthis.refreshTimer = this.#snapshotRefreshEnabled\n\t\t\t? new Timer(this.snapshotRefreshTimeoutMs, () => this.tryRefreshSnapshot())\n\t\t\t: undefined;\n\t}\n\n\tpublic tryRefreshSnapshot(): void {\n\t\tif (\n\t\t\tthis.#snapshotRefreshEnabled &&\n\t\t\t!this.#disposed &&\n\t\t\t!this.refreshTracker.hasPromise &&\n\t\t\tthis.latestSnapshot === undefined\n\t\t) {\n\t\t\t// Don't block on the refresh snapshot call - it is for the next time we serialize, not booting this incarnation\n\t\t\tthis.refreshTracker.setPromise(this.refreshLatestSnapshot(this.supportGetSnapshotApi()));\n\t\t}\n\t}\n\n\t/**\n\t * Fetch the latest snapshot for the container, including delay-loaded groupIds if pendingLocalState was provided and contained any groupIds.\n\t * Note that this will update the StorageAdapter's cached snapshots for the groupIds (if present)\n\t *\n\t * @param supportGetSnapshotApi - a boolean indicating whether to use the fetchISnapshot or fetchISnapshotTree (must be true to fetch by groupIds)\n\t */\n\tprivate async refreshLatestSnapshot(supportGetSnapshotApi: boolean): Promise<number> {\n\t\tthis.latestSnapshot = await getLatestSnapshotInfo(\n\t\t\tthis.mc,\n\t\t\tthis.storageAdapter,\n\t\t\tsupportGetSnapshotApi,\n\t\t);\n\n\t\tif (this.#disposed) {\n\t\t\treturn -1;\n\t\t}\n\n\t\t// These are loading groupIds that the containerRuntime has requested over its lifetime.\n\t\t// We will fetch the latest snapshot for the groupIds, which will update storageAdapter.loadedGroupIdSnapshots's cache\n\t\tconst downloadedGroupIds = Object.keys(this.storageAdapter.loadedGroupIdSnapshots);\n\t\tif (supportGetSnapshotApi && downloadedGroupIds.length > 0) {\n\t\t\tassert(\n\t\t\t\tthis.storageAdapter.getSnapshot !== undefined,\n\t\t\t\t0x972 /* getSnapshot should exist */,\n\t\t\t);\n\t\t\t// (This is a separate network call from above because it requires work for storage to add a special base groupId)\n\t\t\tconst snapshot = await this.storageAdapter.getSnapshot({\n\t\t\t\tversionId: undefined,\n\t\t\t\tscenarioName: \"getLatestSnapshotInfo\",\n\t\t\t\tcacheSnapshot: false,\n\t\t\t\tloadingGroupIds: downloadedGroupIds,\n\t\t\t\tfetchSource: FetchSource.noCache,\n\t\t\t});\n\t\t\tassert(snapshot !== undefined, 0x973 /* Snapshot should exist */);\n\t\t}\n\n\t\t// Notify the manager about the fetched snapshot - let it decide what to do with it\n\t\tconst result =\n\t\t\tthis.latestSnapshot === undefined ? -1 : this.onSnapshotRefreshed(this.latestSnapshot);\n\n\t\tthis.refreshTimer?.restart();\n\t\treturn result;\n\t}\n\n\t/**\n\t * Clears the latest snapshot after it's been consumed by the manager.\n\t * This allows the next refresh cycle to proceed.\n\t */\n\tpublic clearLatestSnapshot(): void {\n\t\tthis.latestSnapshot = undefined;\n\t}\n\n\t/**\n\t * Starts the refresh timer.\n\t */\n\tpublic startTimer(): void {\n\t\tthis.refreshTimer?.start();\n\t}\n\n\t/**\n\t * Restarts the refresh timer.\n\t */\n\tpublic restartTimer(): void {\n\t\tthis.refreshTimer?.restart();\n\t}\n\n\t/**\n\t * Gets the current refresh promise for testing purposes.\n\t * @returns The snapshot sequence number promise, or undefined if no refresh is in progress\n\t */\n\tpublic get refreshSnapshotP(): Promise<number> | undefined {\n\t\treturn this.refreshTracker.promise;\n\t}\n\n\t/**\n\t * Disposes the refresher and clears the timer.\n\t */\n\tpublic dispose(): void {\n\t\tthis.#disposed = true;\n\t\tthis.refreshTimer?.clear();\n\t}\n}\n"]}