forked from microsoft/FluidFramework
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserializedStateManager.ts
More file actions
634 lines (601 loc) · 23.6 KB
/
serializedStateManager.ts
File metadata and controls
634 lines (601 loc) · 23.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
/*!
* Copyright (c) Microsoft Corporation and contributors. All rights reserved.
* Licensed under the MIT License.
*/
import { stringToBuffer } from "@fluid-internal/client-utils";
import {
IGetPendingLocalStateProps,
IRuntime,
} from "@fluidframework/container-definitions/internal";
import type {
IEventProvider,
IEvent,
ITelemetryBaseLogger,
Tagged,
} from "@fluidframework/core-interfaces";
import { Timer, assert } from "@fluidframework/core-utils/internal";
import {
FetchSource,
IDocumentStorageService,
IResolvedUrl,
ISnapshot,
type IDocumentAttributes,
ISnapshotTree,
IVersion,
ISequencedDocumentMessage,
} from "@fluidframework/driver-definitions/internal";
import { getSnapshotTree } from "@fluidframework/driver-utils/internal";
import {
MonitoringContext,
PerformanceEvent,
UsageError,
createChildMonitoringContext,
type TelemetryEventPropertyTypeExt,
} from "@fluidframework/telemetry-utils/internal";
import {
ISerializableBlobContents,
getBlobContentsFromTree,
} from "./containerStorageAdapter.js";
import { convertSnapshotToSnapshotInfo, getDocumentAttributes } from "./utils.js";
/**
* This is very similar to {@link @fluidframework/protocol-definitions/internal#ISnapshot}, but the difference is
* that the blobs of ISnapshot are of type ArrayBufferLike, while the blobs of this interface are serializable because
* they are already converted to string.
*/
export interface SnapshotWithBlobs {
/**
* Snapshot from which container initially loaded.
*/
baseSnapshot: ISnapshotTree;
/**
* Serializable blobs from the base snapshot. Used to load offline since
* storage is not available.
*/
snapshotBlobs: ISerializableBlobContents;
}
/**
* State saved by a container at close time, to be used to load a new instance
* of the container to the same state
*
* This is very similar to {@link @fluidframework/protocol-definitions/internal#ISnapshot}, but the difference is
* that the blobs of ISnapshot are of type ArrayBufferLike, while the blobs of this interface are serializable because
* they are already converted to string.
*
* @internal
*/
export interface IPendingContainerState extends SnapshotWithBlobs {
/**
* This container was attached (as opposed to IPendingDetachedContainerState.attached which is false)
*/
attached: true;
/**
* Runtime-specific state that will be needed to properly rehydrate
* (it's included in ContainerContext passed to instantiateRuntime)
*/
pendingRuntimeState: unknown;
/**
* Any group snapshots (aka delay-loaded) we've downloaded from the service for this container
*/
loadedGroupIdSnapshots?: Record<string, ISnapshotInfo>;
/**
* All ops since base snapshot sequence number up to the latest op
* seen when the container was closed. Used to apply stashed (saved pending)
* ops at the same sequence number at which they were made.
*/
savedOps: ISequencedDocumentMessage[];
/**
* The Container's URL in the service, needed to hook up the driver during rehydration
*/
url: string;
/**
* If the Container was connected when serialized, its clientId. Used as the initial clientId upon rehydration, until reconnected.
*/
clientId?: string;
}
/**
* State saved by a container in detached state, to be used to load a new instance
* of the container to the same state (rehydrate)
* @internal
*/
export interface IPendingDetachedContainerState extends SnapshotWithBlobs {
/**
* This container was not attached (as opposed to IPendingContainerState.attached which is true)
*/
attached: false;
/**
* Indicates whether we expect the rehydrated container to have non-empty Detached Blob Storage
*/
hasAttachmentBlobs: boolean;
/**
* Used by the memory blob storage to persisted attachment blobs
*/
attachmentBlobs?: string;
/**
* Runtime-specific state that will be needed to properly rehydrate
* (it's included in ContainerContext passed to instantiateRuntime)
*/
pendingRuntimeState?: unknown;
}
export interface ISnapshotInfo extends SnapshotWithBlobs {
snapshotSequenceNumber: number;
snapshotFetchedTime?: number | undefined;
}
export type ISerializedStateManagerDocumentStorageService = Pick<
IDocumentStorageService,
"getSnapshot" | "getSnapshotTree" | "getVersions" | "readBlob"
> & {
loadedGroupIdSnapshots: Record<string, ISnapshot>;
};
interface ISerializerEvent extends IEvent {
(event: "saved", listener: (dirty: boolean) => void): void;
}
/**
* Helper class to manage the state of the container needed for proper serialization.
*
* It holds the pendingLocalState the container was rehydrated from (if any),
* as well as the snapshot to be used for serialization.
* It also keeps track of container dirty state and which local ops have been processed
*/
export class SerializedStateManager {
private readonly processedOps: ISequencedDocumentMessage[] = [];
private readonly mc: MonitoringContext;
private snapshot: ISnapshotInfo | undefined;
private latestSnapshot: ISnapshotInfo | undefined;
private _refreshSnapshotP: Promise<number> | undefined;
private readonly lastSavedOpSequenceNumber: number = 0;
private readonly refreshTimer: Timer;
private readonly snapshotRefreshTimeoutMs: number = 60 * 60 * 24 * 1000;
/**
* @param pendingLocalState - The pendingLocalState being rehydrated, if any (undefined when loading directly from storage)
* @param subLogger - Container's logger to use as parent for our logger
* @param storageAdapter - Storage adapter for fetching snapshots
* @param _offlineLoadEnabled - Is serializing/rehydrating containers allowed?
* @param containerEvent - Source of the "saved" event when the container has all its pending state uploaded
* @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.
*/
constructor(
private readonly pendingLocalState: IPendingContainerState | undefined,
subLogger: ITelemetryBaseLogger,
private readonly storageAdapter: ISerializedStateManagerDocumentStorageService,
private readonly _offlineLoadEnabled: boolean,
containerEvent: IEventProvider<ISerializerEvent>,
private readonly containerDirty: () => boolean,
private readonly supportGetSnapshotApi: () => boolean,
snapshotRefreshTimeoutMs?: number,
) {
this.mc = createChildMonitoringContext({
logger: subLogger,
namespace: "serializedStateManager",
});
this.snapshotRefreshTimeoutMs = snapshotRefreshTimeoutMs ?? this.snapshotRefreshTimeoutMs;
this.refreshTimer = new Timer(this.snapshotRefreshTimeoutMs, () =>
this.tryRefreshSnapshot(),
);
// special case handle. Obtaining the last saved op seq num to avoid
// refreshing the snapshot before we have processed it. It could cause
// a subsequent stashing to have a newer snapshot than allowed.
if (pendingLocalState && pendingLocalState.savedOps.length > 0) {
const savedOpsSize = pendingLocalState.savedOps.length;
this.lastSavedOpSequenceNumber =
pendingLocalState.savedOps[savedOpsSize - 1].sequenceNumber;
}
containerEvent.on("saved", () => this.updateSnapshotAndProcessedOpsMaybe());
}
public get offlineLoadEnabled(): boolean {
return this._offlineLoadEnabled;
}
/**
* Promise that will resolve (or reject) once we've tried to download the latest snapshot(s) from storage
* only intended to be used for testing purposes.
* @returns The snapshot sequence number associated with the latest fetched snapshot
*/
public get refreshSnapshotP(): Promise<number> | undefined {
return this._refreshSnapshotP;
}
/**
* Called whenever an incoming op is processed by the Container
*/
public addProcessedOp(message: ISequencedDocumentMessage): void {
if (this.offlineLoadEnabled) {
this.processedOps.push(message);
this.updateSnapshotAndProcessedOpsMaybe();
}
}
/**
* This wraps the basic functionality of fetching the snapshot for this container during Container load.
*
* If we have pendingLocalState, we get the snapshot from there.
* Otherwise, fetch it from storage (according to specifiedVersion if provided).
*
* @param specifiedVersion - If a version is specified and we don't have pendingLocalState, fetch this version from storage.
* @param supportGetSnapshotApi - a boolean indicating whether to use the fetchISnapshot or fetchISnapshotTree.
* @returns The snapshot to boot the container from
*/
public async fetchSnapshot(specifiedVersion: string | undefined): Promise<{
baseSnapshot: ISnapshot | ISnapshotTree;
version: IVersion | undefined;
}> {
if (this.pendingLocalState === undefined) {
const { baseSnapshot, version } = await getSnapshot(
this.mc,
this.storageAdapter,
this.supportGetSnapshotApi(),
specifiedVersion,
);
const baseSnapshotTree: ISnapshotTree | undefined = getSnapshotTree(baseSnapshot);
// non-interactive clients will not have any pending state we want to save
if (this.offlineLoadEnabled) {
const snapshotBlobs = await getBlobContentsFromTree(baseSnapshot, this.storageAdapter);
const attributes = await getDocumentAttributes(this.storageAdapter, baseSnapshotTree);
this.snapshot = {
baseSnapshot: baseSnapshotTree,
snapshotBlobs,
snapshotSequenceNumber: attributes.sequenceNumber,
};
this.refreshTimer.start();
}
return { baseSnapshot, version };
} else {
const { baseSnapshot, snapshotBlobs } = this.pendingLocalState;
const attributes = await getDocumentAttributes(this.storageAdapter, baseSnapshot);
this.snapshot = {
baseSnapshot,
snapshotBlobs,
snapshotSequenceNumber: attributes.sequenceNumber,
};
this.tryRefreshSnapshot();
const blobContents = new Map<string, ArrayBuffer>();
for (const [id, value] of Object.entries(snapshotBlobs)) {
blobContents.set(id, stringToBuffer(value, "utf8"));
}
const iSnapshot: ISnapshot = {
sequenceNumber: this.snapshot.snapshotSequenceNumber,
snapshotTree: baseSnapshot,
blobContents,
latestSequenceNumber: undefined,
ops: [],
snapshotFormatV: 1,
};
return { baseSnapshot: iSnapshot, version: undefined };
}
}
private tryRefreshSnapshot(): void {
if (
this.mc.config.getBoolean("Fluid.Container.enableOfflineSnapshotRefresh") === true &&
this._refreshSnapshotP === undefined &&
this.latestSnapshot === undefined
) {
// Don't block on the refresh snapshot call - it is for the next time we serialize, not booting this incarnation
this._refreshSnapshotP = this.refreshLatestSnapshot(this.supportGetSnapshotApi());
this._refreshSnapshotP
.catch(
(error: TelemetryEventPropertyTypeExt | Tagged<TelemetryEventPropertyTypeExt>) => {
this.mc.logger.sendTelemetryEvent({
eventName: "RefreshLatestSnapshotFailed",
error,
});
},
)
.finally(() => {
this._refreshSnapshotP = undefined;
});
}
}
/**
* Fetch the latest snapshot for the container, including delay-loaded groupIds if pendingLocalState was provided and contained any groupIds.
* Note that this will update the StorageAdapter's cached snapshots for the groupIds (if present)
*
* @param supportGetSnapshotApi - a boolean indicating whether to use the fetchISnapshot or fetchISnapshotTree (must be true to fetch by groupIds)
*/
private async refreshLatestSnapshot(supportGetSnapshotApi: boolean): Promise<number> {
this.latestSnapshot = await getLatestSnapshotInfo(
this.mc,
this.storageAdapter,
supportGetSnapshotApi,
);
// These are loading groupIds that the containerRuntime has requested over its lifetime.
// We will fetch the latest snapshot for the groupIds, which will update storageAdapter.loadedGroupIdSnapshots's cache
const downloadedGroupIds = Object.keys(this.storageAdapter.loadedGroupIdSnapshots);
if (supportGetSnapshotApi && downloadedGroupIds.length > 0) {
assert(
this.storageAdapter.getSnapshot !== undefined,
0x972 /* getSnapshot should exist */,
);
// (This is a separate network call from above because it requires work for storage to add a special base groupId)
const snapshot = await this.storageAdapter.getSnapshot({
versionId: undefined,
scenarioName: "getLatestSnapshotInfo",
cacheSnapshot: false,
loadingGroupIds: downloadedGroupIds,
fetchSource: FetchSource.noCache,
});
assert(snapshot !== undefined, 0x973 /* Snapshot should exist */);
}
return this.updateSnapshotAndProcessedOpsMaybe();
}
/**
* Updates class snapshot and processedOps if we have a new snapshot and it's among processedOps range.
*/
private updateSnapshotAndProcessedOpsMaybe(): number {
const snapshotSequenceNumber = this.latestSnapshot?.snapshotSequenceNumber;
if (
snapshotSequenceNumber === undefined ||
this.processedOps.length === 0 ||
this.processedOps[this.processedOps.length - 1].sequenceNumber <
this.lastSavedOpSequenceNumber ||
this.containerDirty()
) {
// can't refresh latest snapshot until we have processed the ops up to it.
// Pending state would be behind the latest snapshot.
return -1;
}
const firstProcessedOpSequenceNumber = this.processedOps[0].sequenceNumber;
const lastProcessedOpSequenceNumber =
this.processedOps[this.processedOps.length - 1].sequenceNumber;
if (snapshotSequenceNumber < firstProcessedOpSequenceNumber) {
// Snapshot seq number is older than our first processed op, which could mean we're fetching
// the same snapshot that we already have or snapshot is too old, implicating an unexpected behavior.
this.mc.logger.sendTelemetryEvent({
eventName: "OldSnapshotFetchWhileRefreshing",
snapshotSequenceNumber,
firstProcessedOpSequenceNumber,
lastProcessedOpSequenceNumber,
stashedSnapshotSequenceNumber: this.snapshot?.snapshotSequenceNumber,
});
this.latestSnapshot = undefined;
this.refreshTimer.restart();
} else if (snapshotSequenceNumber <= lastProcessedOpSequenceNumber) {
// Snapshot seq num is between the first and last processed op.
// Remove the ops that are already part of the snapshot
this.processedOps.splice(0, snapshotSequenceNumber - firstProcessedOpSequenceNumber + 1);
this.snapshot = this.latestSnapshot;
this.latestSnapshot = undefined;
this.refreshTimer.restart();
this.mc.logger.sendTelemetryEvent({
eventName: "SnapshotRefreshed",
snapshotSequenceNumber,
firstProcessedOpSequenceNumber,
newFirstProcessedOpSequenceNumber:
this.processedOps.length === 0 ? undefined : this.processedOps[0].sequenceNumber,
});
}
return snapshotSequenceNumber;
}
/**
* When the Container attaches, we need to stash the initial snapshot (a form of the attach summary).
* This method is only meant to be used by Container.attach() to set the initial
* base snapshot when attaching.
* @param snapshot - snapshot and blobs collected while attaching (a form of the attach summary)
*/
public setInitialSnapshot(snapshot: SnapshotWithBlobs | undefined): void {
if (this.offlineLoadEnabled) {
assert(
this.snapshot === undefined,
0x937 /* inital snapshot should only be defined once */,
);
assert(snapshot !== undefined, 0x938 /* attachment snapshot should be defined */);
const { baseSnapshot, snapshotBlobs } = snapshot;
const attributesHash =
".protocol" in baseSnapshot.trees
? baseSnapshot.trees[".protocol"].blobs.attributes
: baseSnapshot.blobs[".attributes"];
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const attributes = JSON.parse(snapshotBlobs[attributesHash]);
assert(
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
attributes.sequenceNumber === 0,
0x939 /* trying to set a non attachment snapshot */,
);
this.snapshot = {
...snapshot,
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
snapshotSequenceNumber: attributes.sequenceNumber as number,
};
this.refreshTimer.start();
}
}
/**
* Assembles and serializes the {@link IPendingContainerState} for the container,
* to be stored and used to rehydrate the container at a later time.
*/
public async getPendingLocalState(
props: IGetPendingLocalStateProps,
clientId: string | undefined,
runtime: Pick<IRuntime, "getPendingLocalState">,
resolvedUrl: IResolvedUrl,
): Promise<string> {
return PerformanceEvent.timedExecAsync(
this.mc.logger,
{
eventName: "getPendingLocalState",
details: {
notifyImminentClosure: props.notifyImminentClosure,
sessionExpiryTimerStarted: props.sessionExpiryTimerStarted,
snapshotSequenceNumber: props.snapshotSequenceNumber,
processedOpsSize: this.processedOps.length,
},
clientId,
},
async () => {
if (!this.offlineLoadEnabled) {
throw new UsageError("Can't get pending local state unless offline load is enabled");
}
assert(this.snapshot !== undefined, 0x8e5 /* no base data */);
const pendingRuntimeState = await runtime.getPendingLocalState({
...props,
snapshotSequenceNumber: this.snapshot.snapshotSequenceNumber,
sessionExpiryTimerStarted: this.snapshot.snapshotFetchedTime,
});
// This conversion is required because ArrayBufferLike doesn't survive JSON.stringify
const loadedGroupIdSnapshots = {};
let hasGroupIdSnapshots = false;
const groupIdSnapshots = Object.entries(this.storageAdapter.loadedGroupIdSnapshots);
if (groupIdSnapshots.length > 0) {
for (const [groupId, snapshot] of groupIdSnapshots) {
hasGroupIdSnapshots = true;
loadedGroupIdSnapshots[groupId] = convertSnapshotToSnapshotInfo(snapshot);
}
}
const pendingState: IPendingContainerState = {
attached: true,
pendingRuntimeState,
baseSnapshot: this.snapshot.baseSnapshot,
snapshotBlobs: this.snapshot.snapshotBlobs,
loadedGroupIdSnapshots: hasGroupIdSnapshots ? loadedGroupIdSnapshots : undefined,
savedOps: this.processedOps,
url: resolvedUrl.url,
clientId,
};
return JSON.stringify(pendingState);
},
);
}
/**
* Dispose of the SerializedStateManager, cleaning up any active timers.
* This prevents Node.js processes from hanging due to the refresh timer.
*/
public dispose(): void {
this.refreshTimer.clear();
}
}
/**
* Retrieves the most recent snapshot and returns its info.
*
* @param mc - The monitoring context.
* @param storageAdapter - The storage adapter providing methods to retrieve the snapshot.
* @param supportGetSnapshotApi - a boolean indicating whether to use the fetchISnapshot or fetchISnapshotTree.
* @returns a SnapshotInfo object containing the snapshot tree, snapshot blobs and its sequence number.
*/
export async function getLatestSnapshotInfo(
mc: MonitoringContext,
storageAdapter: ISerializedStateManagerDocumentStorageService,
supportGetSnapshotApi: boolean,
): Promise<ISnapshotInfo | undefined> {
return PerformanceEvent.timedExecAsync(
mc.logger,
{ eventName: "GetLatestSnapshotInfo" },
async () => {
// get the latest non cached snapshot version
const specifiedVersion: IVersion[] = await storageAdapter.getVersions(
// eslint-disable-next-line unicorn/no-null
null,
1,
"getLatestSnapshotInfo",
FetchSource.noCache,
);
const { baseSnapshot } = await getSnapshot(
mc,
storageAdapter,
supportGetSnapshotApi,
specifiedVersion[0]?.id,
);
const baseSnapshotTree: ISnapshotTree | undefined = getSnapshotTree(baseSnapshot);
const snapshotFetchedTime = Date.now();
const snapshotBlobs = await getBlobContentsFromTree(baseSnapshot, storageAdapter);
const attributes: IDocumentAttributes = await getDocumentAttributes(
storageAdapter,
baseSnapshotTree,
);
const snapshotSequenceNumber = attributes.sequenceNumber;
return {
baseSnapshot: baseSnapshotTree,
snapshotBlobs,
snapshotSequenceNumber,
snapshotFetchedTime,
};
},
).catch(() => undefined);
}
/**
* Retrieves a snapshot from the storage adapter and transforms it into an ISnapshotTree object.
*
* @param mc - The monitoring context.
* @param storageAdapter - The storage adapter providing methods to retrieve the snapshot.
* @param supportGetSnapshotApi - a boolean indicating whether to use the fetchISnapshot or fetchISnapshotTree.
* @param specifiedVersion - An optional version string specifying the version of the snapshot tree to fetch.
* @returns - An ISnapshotTree and its version.
*/
async function getSnapshot(
mc: MonitoringContext,
storageAdapter: Pick<
IDocumentStorageService,
"getSnapshot" | "getSnapshotTree" | "getVersions"
>,
supportGetSnapshotApi: boolean,
specifiedVersion: string | undefined,
): Promise<{ baseSnapshot: ISnapshot | ISnapshotTree; version?: IVersion }> {
const { snapshot, version } = supportGetSnapshotApi
? await fetchISnapshot(mc, storageAdapter, specifiedVersion)
: await fetchISnapshotTree(mc, storageAdapter, specifiedVersion);
assert(snapshot !== undefined, 0x8e4 /* Snapshot should exist */);
return { baseSnapshot: snapshot, version };
}
/**
* Fetches an ISnapshot from a storage adapter based on the specified version.
*
* @param mc - The monitoring context.
* @param storageAdapter - The storage adapter providing a getSnapshot method to retrieve the ISnapshot and version.
* @param specifiedVersion - An optional version string specifying the version of the snapshot tree to fetch.
* @returns - The fetched snapshot tree and its version.
*/
export async function fetchISnapshot(
mc: MonitoringContext,
storageAdapter: Pick<IDocumentStorageService, "getSnapshot">,
specifiedVersion: string | undefined,
): Promise<{ snapshot?: ISnapshot; version?: IVersion }> {
const snapshot = await storageAdapter.getSnapshot?.({ versionId: specifiedVersion });
const version: IVersion | undefined =
snapshot?.snapshotTree.id === undefined
? undefined
: {
id: snapshot.snapshotTree.id,
treeId: snapshot.snapshotTree.id,
};
if (snapshot === undefined && specifiedVersion !== undefined) {
mc.logger.sendErrorEvent({
eventName: "getSnapshotTreeFailed",
id: specifiedVersion,
});
} else if (snapshot !== undefined && version?.id === undefined) {
mc.logger.sendErrorEvent({
eventName: "getSnapshotFetchedTreeWithoutVersionId",
hasVersion: version !== undefined, // if hasVersion is true, this means that the contract with the service was broken.
});
}
return { snapshot, version };
}
/**
* Fetches an ISnapshotTree from a storage adapter based on the specified version.
*
* @param mc - The monitoring context.
* @param storageAdapter - The storage adapter providing methods to retrieve the ISnapshotTree and version.
* @param specifiedVersion - An optional version string specifying the version of the snapshot tree to fetch.
* @returns - The fetched snapshot tree and its version.
*/
export async function fetchISnapshotTree(
mc: MonitoringContext,
storageAdapter: Pick<IDocumentStorageService, "getSnapshotTree" | "getVersions">,
specifiedVersion: string | undefined,
): Promise<{ snapshot?: ISnapshotTree; version?: IVersion | undefined }> {
// API uses null
// eslint-disable-next-line unicorn/no-null
const versions = await storageAdapter.getVersions(specifiedVersion ?? null, 1);
const version = versions[0];
if (version === undefined && specifiedVersion !== undefined) {
// We should have a defined version to load from if specified version requested
mc.logger.sendErrorEvent({
eventName: "NoVersionFoundWhenSpecified",
id: specifiedVersion,
});
}
const snapshot = (await storageAdapter.getSnapshotTree(version)) ?? undefined;
if (snapshot === undefined && version !== undefined) {
mc.logger.sendErrorEvent({ eventName: "getSnapshotTreeFailed", id: version.id });
} else if (snapshot !== undefined && version?.id === undefined) {
mc.logger.sendErrorEvent({
eventName: "getSnapshotFetchedTreeWithoutVersionId",
hasVersion: version !== undefined, // if hasVersion is true, this means that the contract with the service was broken.
});
}
return { snapshot, version };
}