forked from microsoft/FluidFramework
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdataStoreContext.ts
More file actions
1638 lines (1450 loc) · 54.5 KB
/
dataStoreContext.ts
File metadata and controls
1638 lines (1450 loc) · 54.5 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
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*!
* Copyright (c) Microsoft Corporation and contributors. All rights reserved.
* Licensed under the MIT License.
*/
import {
TypedEventEmitter,
type ILayerCompatDetails,
type IProvideLayerCompatDetails,
} from "@fluid-internal/client-utils";
import { AttachState, type IAudience } from "@fluidframework/container-definitions";
import {
type IDeltaManager,
isIDeltaManagerFull,
type IDeltaManagerFull,
type ReadOnlyInfo,
} from "@fluidframework/container-definitions/internal";
import type {
FluidObject,
IDisposable,
ITelemetryBaseProperties,
IEvent,
} from "@fluidframework/core-interfaces";
import type {
IFluidHandleContext,
IFluidHandleInternal,
ITelemetryBaseLogger,
} from "@fluidframework/core-interfaces/internal";
import { assert, LazyPromise, unreachableCase } from "@fluidframework/core-utils/internal";
import type { IClientDetails, IQuorumClients } from "@fluidframework/driver-definitions";
import type {
ISnapshot,
IDocumentMessage,
ISnapshotTree,
ITreeEntry,
ISequencedDocumentMessage,
} from "@fluidframework/driver-definitions/internal";
import {
BlobTreeEntry,
isInstanceOfISnapshot,
readAndParse,
} from "@fluidframework/driver-utils/internal";
import type { IIdCompressor } from "@fluidframework/id-compressor";
import {
type ISummaryTreeWithStats,
type ITelemetryContext,
type IGarbageCollectionData,
type CreateChildSummarizerNodeFn,
type CreateChildSummarizerNodeParam,
type FluidDataStoreRegistryEntry,
type IContainerRuntimeBase,
type IDataStore,
type IFluidDataStoreChannel,
type IFluidDataStoreContext,
type IFluidDataStoreContextDetached,
type IFluidDataStoreRegistry,
type IGarbageCollectionDetailsBase,
type IProvideFluidDataStoreFactory,
type ISummarizeInternalResult,
type ISummarizeResult,
type ISummarizerNodeWithGC,
type SummarizeInternalFn,
channelsTreeName,
type IInboundSignalMessage,
type IPendingMessagesState,
type IRuntimeMessageCollection,
type IFluidDataStoreFactory,
type PackagePath,
type IRuntimeStorageService,
type MinimumVersionForCollab,
} from "@fluidframework/runtime-definitions/internal";
import {
addBlobToSummary,
isSnapshotFetchRequiredForLoadingGroupId,
} from "@fluidframework/runtime-utils/internal";
import {
DataProcessingError,
LoggingError,
type MonitoringContext,
ThresholdCounter,
UsageError,
createChildMonitoringContext,
extractSafePropertiesFromMessage,
generateStack,
tagCodeArtifacts,
} from "@fluidframework/telemetry-utils/internal";
import type { IFluidParentContextPrivate } from "./channelCollection.js";
import { BaseDeltaManagerProxy } from "./deltaManagerProxies.js";
import {
runtimeCompatDetailsForDataStore,
validateDatastoreCompatibility,
} from "./runtimeLayerCompatState.js";
import {
// eslint-disable-next-line import/no-deprecated
type ReadFluidDataStoreAttributes,
type WriteFluidDataStoreAttributes,
dataStoreAttributesBlobName,
getAttributesFormatVersion,
getFluidDataStoreAttributes,
hasIsolatedChannels,
wrapSummaryInChannelsTree,
} from "./summary/index.js";
function createAttributes(
pkg: readonly string[],
isRootDataStore: boolean,
): WriteFluidDataStoreAttributes {
const stringifiedPkg = JSON.stringify(pkg);
return {
pkg: stringifiedPkg,
summaryFormatVersion: 2,
isRootDataStore,
};
}
export function createAttributesBlob(
pkg: readonly string[],
isRootDataStore: boolean,
): ITreeEntry {
const attributes = createAttributes(pkg, isRootDataStore);
return new BlobTreeEntry(dataStoreAttributesBlobName, JSON.stringify(attributes));
}
export interface ISnapshotDetails {
pkg: readonly string[];
isRootDataStore: boolean;
snapshot?: ISnapshotTree;
sequenceNumber?: number;
}
/**
* This is interface that every context should implement.
* This interface is used for context's parent - ChannelCollection.
* It should not be exposed to any other users of context.
*/
export interface IFluidDataStoreContextInternal extends IFluidDataStoreContext {
getAttachSummary(telemetryContext?: ITelemetryContext): ISummaryTreeWithStats;
getAttachGCData(telemetryContext?: ITelemetryContext): IGarbageCollectionData;
getInitialSnapshotDetails(): Promise<ISnapshotDetails>;
realize(): Promise<IFluidDataStoreChannel>;
isRoot(): Promise<boolean>;
}
/**
* Properties necessary for creating a FluidDataStoreContext
*/
export interface IFluidDataStoreContextProps {
readonly id: string;
readonly parentContext: IFluidParentContextPrivate;
readonly storage: IRuntimeStorageService;
readonly scope: FluidObject;
readonly createSummarizerNodeFn: CreateChildSummarizerNodeFn;
/**
* See {@link FluidDataStoreContext.pkg}.
*/
readonly pkg?: PackagePath;
/**
* See {@link FluidDataStoreContext.loadingGroupId}.
*/
readonly loadingGroupId?: string;
}
/**
* Properties necessary for creating a local FluidDataStoreContext
*/
export interface ILocalFluidDataStoreContextProps extends IFluidDataStoreContextProps {
readonly pkg: readonly string[] | undefined;
readonly snapshotTree: ISnapshotTree | undefined;
readonly makeLocallyVisibleFn: () => void;
}
/**
* Properties necessary for creating a local FluidDataStoreContext
*/
export interface ILocalDetachedFluidDataStoreContextProps
extends ILocalFluidDataStoreContextProps {
readonly channelToDataStoreFn: (channel: IFluidDataStoreChannel) => IDataStore;
}
/**
* Properties necessary for creating a remote FluidDataStoreContext
*/
export interface IRemoteFluidDataStoreContextProps extends IFluidDataStoreContextProps {
readonly snapshot: ISnapshotTree | ISnapshot | undefined;
}
// back-compat: To be removed in the future.
// Added in "2.0.0-rc.2.0.0" timeframe (to support older builds).
export interface IFluidDataStoreContextEvents extends IEvent {
(event: "attaching" | "attached", listener: () => void);
}
/**
* Eventually we should remove the delta manger from being exposed to Datastore runtimes via the context. However to remove that exposure we need to add new
* features, and those features themselves need forward and back compat. This proxy is here to enable that back compat. Each feature this proxy is used to
* support should be listed below, and as layer compat support goes away for those feature, we should also remove them from this proxy, with the eventual goal
* of completely removing this proxy.
*
* - Everything regarding readonly is to support older datastore runtimes which do not have the setReadonly function, so they must get their readonly state via the delta manager.
*
*/
class ContextDeltaManagerProxy extends BaseDeltaManagerProxy {
constructor(
base: IDeltaManagerFull,
private readonly isReadOnly: () => boolean,
) {
super(base, {
onReadonly: (): void => {
/* readonly is controlled from the context which calls setReadonly */
},
});
}
public get readOnlyInfo(): ReadOnlyInfo {
const readonly = this.isReadOnly();
if (readonly === this.deltaManager.readOnlyInfo.readonly) {
return this.deltaManager.readOnlyInfo;
} else {
return readonly === true
? {
readonly,
forced: false,
permissions: undefined,
storageOnly: false,
}
: { readonly };
}
}
/**
* Called by the owning datastore context to emit the readonly
* event on the delta manger that is projected down to the datastore
* runtime. This state may not align with that of the true delta
* manager if the context wishes to control the read only state
* differently than the delta manager itself.
*/
public emitReadonly(): void {
this.emit("readonly", this.isReadOnly());
}
}
/**
* {@link IFluidDataStoreContext} for the implementations of {@link IFluidDataStoreChannel} which powers the {@link IDataStore}s.
*/
export abstract class FluidDataStoreContext
extends TypedEventEmitter<IFluidDataStoreContextEvents>
implements
IFluidDataStoreContextInternal,
IFluidDataStoreContext,
IDisposable,
IProvideLayerCompatDetails
{
public get packagePath(): PackagePath {
assert(this.pkg !== undefined, 0x139 /* "Undefined package path" */);
return this.pkg;
}
public get options(): Record<string | number, unknown> {
return this.parentContext.options;
}
public get clientId(): string | undefined {
return this.parentContext.clientId;
}
public get clientDetails(): IClientDetails {
return this.parentContext.clientDetails;
}
public get baseLogger(): ITelemetryBaseLogger {
return this.parentContext.baseLogger;
}
private readonly _contextDeltaManagerProxy: ContextDeltaManagerProxy;
public get deltaManager(): IDeltaManager<ISequencedDocumentMessage, IDocumentMessage> {
return this._contextDeltaManagerProxy;
}
private isStagingMode: boolean = false;
public isReadOnly = (): boolean =>
(this.isStagingMode && this.channel?.policies?.readonlyInStagingMode === true) ||
this.parentContext.isReadOnly();
public get connected(): boolean {
return this.parentContext.connected;
}
public get IFluidHandleContext(): IFluidHandleContext {
return this.parentContext.IFluidHandleContext;
}
public get containerRuntime(): IContainerRuntimeBase {
return this._containerRuntime;
}
public get isLoaded(): boolean {
return this.loaded;
}
public get baseSnapshot(): ISnapshotTree | undefined {
return this._baseSnapshot;
}
public get idCompressor(): IIdCompressor | undefined {
return this.parentContext.idCompressor;
}
private _disposed = false;
public get disposed(): boolean {
return this._disposed;
}
/**
* A Tombstoned object has been unreferenced long enough that GC knows it won't be referenced again.
* Tombstoned objects are eventually deleted by GC.
*/
private _tombstoned = false;
public get tombstoned(): boolean {
return this._tombstoned;
}
/**
* If true, throw an error when a tombstone data store is used.
* @deprecated NOT SUPPORTED - hardcoded to return false since it's deprecated.
*/
public readonly gcThrowOnTombstoneUsage: boolean = false;
/**
* @deprecated NOT SUPPORTED - hardcoded to return false since it's deprecated.
*/
public readonly gcTombstoneEnforcementAllowed: boolean = false;
/**
* If true, this means that this data store context and its children have been removed from the runtime
*/
protected deleted: boolean = false;
public get attachState(): AttachState {
return this._attachState;
}
public get IFluidDataStoreRegistry(): IFluidDataStoreRegistry | undefined {
return this.registry;
}
/**
* The compatibility details of the Runtime layer that is exposed to the DataStore layer
* for validating DataStore-Runtime compatibility.
*/
public get ILayerCompatDetails(): ILayerCompatDetails {
return runtimeCompatDetailsForDataStore;
}
/**
* {@inheritdoc IFluidDataStoreContext.minVersionForCollab}
*/
public readonly minVersionForCollab: MinimumVersionForCollab;
private baseSnapshotSequenceNumber: number | undefined;
/**
* A datastore is considered as root if it
* 1. is root in memory - see isInMemoryRoot
* 2. is root as part of the base snapshot that the datastore loaded from
* @returns whether a datastore is root
*/
public async isRoot(aliasedDataStores?: Set<string>): Promise<boolean> {
if (this.isInMemoryRoot()) {
return true;
}
// This if is a performance optimization.
// We know that if the base snapshot is omitted, then the isRootDataStore flag is not set.
// That means we can skip the expensive call to getInitialSnapshotDetails for virtualized datastores,
// and get the information from the alias map directly.
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access
if (aliasedDataStores !== undefined && (this.baseSnapshot as any)?.omitted === true) {
return aliasedDataStores.has(this.id);
}
const snapshotDetails = await this.getInitialSnapshotDetails();
return snapshotDetails.isRootDataStore;
}
/**
* There are 3 states where isInMemoryRoot needs to be true
* 1. when a datastore becomes aliased. This can happen for both remote and local datastores
* 2. when a datastore is created locally as root
* 3. when a datastore is created locally as root and is rehydrated
* @returns whether a datastore is root in memory
*/
protected isInMemoryRoot(): boolean {
return this._isInMemoryRoot;
}
/**
* Returns the count of pending messages that are stored until the data store is realized.
*/
public get pendingCount(): number {
return this.pendingMessagesState?.pendingCount ?? 0;
}
protected registry: IFluidDataStoreRegistry | undefined;
protected detachedRuntimeCreation = false;
protected channel: IFluidDataStoreChannel | undefined;
private loaded = false;
/**
* Tracks the messages for this data store that are sent while it's not loaded
*/
private pendingMessagesState: IPendingMessagesState | undefined = {
messageCollections: [],
pendingCount: 0,
};
protected channelP: Promise<IFluidDataStoreChannel> | undefined;
protected _baseSnapshot: ISnapshotTree | undefined;
protected _attachState: AttachState;
private _isInMemoryRoot: boolean = false;
protected readonly summarizerNode: ISummarizerNodeWithGC;
protected readonly mc: MonitoringContext;
private readonly thresholdOpsCounter: ThresholdCounter;
private static readonly pendingOpsCountThreshold = 1000;
/**
* If the summarizer makes local changes, a telemetry event is logged. This has the potential to be very noisy.
* So, adding a count of how many telemetry events are logged per data store context. This can be
* controlled via feature flags.
*/
private localChangesTelemetryCount: number;
public readonly id: string;
private readonly _containerRuntime: IContainerRuntimeBase;
/**
* Information for this data store from its parent.
*
* @remarks
* The parent which provided this information currently can be the container runtime or a datastore (if the datastore this context is for is nested under another one).
*/
private readonly parentContext: IFluidParentContextPrivate;
public readonly storage: IRuntimeStorageService;
public readonly scope: FluidObject;
/**
* The loading group to which the data store belongs to.
*/
public readonly loadingGroupId: string | undefined;
/**
* {@link PackagePath} of this data store.
*
* This can be undefined when a data store is delay loaded, i.e., the attributes of this data store in the snapshot are not fetched until this data store is actually used.
* At that time, the attributes blob is fetched and the pkg is updated from it.
*
* @see {@link PackagePath}.
* @see {@link IFluidDataStoreContext.packagePath}.
* @see {@link factoryFromPackagePath}.
*/
protected pkg?: PackagePath;
public constructor(
props: IFluidDataStoreContextProps,
private readonly existing: boolean,
public readonly isLocalDataStore: boolean,
private readonly makeLocallyVisibleFn: () => void,
) {
super();
this._containerRuntime = props.parentContext.containerRuntime;
this.parentContext = props.parentContext;
this.minVersionForCollab = props.parentContext.minVersionForCollab;
this.id = props.id;
this.storage = props.storage;
this.scope = props.scope;
this.pkg = props.pkg;
this.loadingGroupId = props.loadingGroupId;
// URIs use slashes as delimiters. Handles use URIs.
// Thus having slashes in types almost guarantees trouble down the road!
assert(!this.id.includes("/"), 0x13a /* Data store ID contains slash */);
this._attachState =
this.parentContext.attachState !== AttachState.Detached && this.existing
? this.parentContext.attachState
: AttachState.Detached;
this.summarizerNode = props.createSummarizerNodeFn(
async (fullTree, trackState, telemetryContext) =>
this.summarizeInternal(fullTree, trackState, telemetryContext),
async (fullGC?: boolean) => this.getGCDataInternal(fullGC),
);
this.mc = createChildMonitoringContext({
logger: this.baseLogger,
namespace: "FluidDataStoreContext",
properties: {
all: tagCodeArtifacts({
fluidDataStoreId: this.id,
// The package name is a getter because `this.pkg` may not be initialized during construction.
// For data stores loaded from summary, it is initialized during data store realization.
fullPackageName: () => this.pkg?.join("/"),
}),
},
});
this.thresholdOpsCounter = new ThresholdCounter(
FluidDataStoreContext.pendingOpsCountThreshold,
this.mc.logger,
);
// By default, a data store can log maximum 10 local changes telemetry in summarizer.
this.localChangesTelemetryCount =
this.mc.config.getNumber("Fluid.Telemetry.LocalChangesTelemetryCount") ?? 10;
assert(
isIDeltaManagerFull(this.parentContext.deltaManager),
0xb83 /* Invalid delta manager */,
);
this._contextDeltaManagerProxy = new ContextDeltaManagerProxy(
this.parentContext.deltaManager,
() => this.isReadOnly(),
);
}
public dispose(): void {
if (this._disposed) {
return;
}
this._disposed = true;
// Dispose any pending runtime after it gets fulfilled
// Errors are logged where this.channelP is consumed/generated (realizeCore(), bindRuntime())
if (this.channelP) {
this.channelP
.then((runtime) => {
runtime.dispose();
})
.catch((error) => {});
}
this._contextDeltaManagerProxy.dispose();
}
/**
* When delete is called, that means that the data store is permanently removed from the runtime, and will not show up in future summaries
* This function is called to prevent ops from being generated from this data store once it has been deleted. Furthermore, this data store
* should not receive any ops/signals.
*/
public delete(): void {
this.deleted = true;
}
public setTombstone(tombstone: boolean): void {
if (this.tombstoned === tombstone) {
return;
}
this._tombstoned = tombstone;
}
public abstract setAttachState(
attachState: AttachState.Attaching | AttachState.Attached,
): void;
/**
* Throw a {@link LoggingError} indicating that {@link factoryFromPackagePath} failed.
*/
private factoryFromPackagePathError(
reason: string,
failedPkgPath?: string,
fullPackageName?: PackagePath,
): never {
throw new LoggingError(
reason,
tagCodeArtifacts({
failedPkgPath,
packagePath: fullPackageName?.join("/"),
}),
);
}
public async realize(): Promise<IFluidDataStoreChannel> {
assert(
!this.detachedRuntimeCreation,
0x13d /* "Detached runtime creation on realize()" */,
);
if (!this.channelP) {
this.channelP = this.realizeCore(this.existing).catch((error) => {
const errorWrapped = DataProcessingError.wrapIfUnrecognized(
error,
"realizeFluidDataStoreContext",
);
errorWrapped.addTelemetryProperties(
tagCodeArtifacts({
fullPackageName: this.pkg?.join("/"),
fluidDataStoreId: this.id,
}),
);
this.mc.logger.sendErrorEvent({ eventName: "RealizeError" }, errorWrapped);
throw errorWrapped;
});
}
return this.channelP;
}
/**
* Gets the factory that would be used to instantiate this data store by calling `instantiateDataStore` based on {@link pkg}.
* @remarks
* Also populates {@link registry}.
*
* Must be called after {@link pkg} is set, and only called once.
*
* @see {@link @fluidframework/container-runtime-definitions#IContainerRuntimeBase.createDataStore}.
* @see {@link FluidDataStoreContext.pkg}.
*/
protected async factoryFromPackagePath(): Promise<IFluidDataStoreFactory> {
const path = this.pkg;
if (path === undefined) {
this.factoryFromPackagePathError("packages is undefined");
}
let entry: FluidDataStoreRegistryEntry | undefined;
let registry: IFluidDataStoreRegistry | undefined =
this.parentContext.IFluidDataStoreRegistry;
let lastIdentifier: string | undefined;
// Follow the path, looking up each identifier in the registry along the way:
for (const identifier of path) {
if (!registry) {
this.factoryFromPackagePathError("No registry for package", lastIdentifier, path);
}
lastIdentifier = identifier;
entry = registry.getSync?.(identifier) ?? (await registry.get(identifier));
if (!entry) {
this.factoryFromPackagePathError(
"Registry does not contain entry for the package",
identifier,
path,
);
}
registry = entry.IFluidDataStoreRegistry;
}
const factory = entry?.IFluidDataStoreFactory;
if (factory === undefined) {
this.factoryFromPackagePathError("Can't find factory for package", lastIdentifier, path);
}
assert(this.registry === undefined, 0x157 /* "datastore registry already attached" */);
this.registry = registry;
return factory;
}
public createChildDataStore<T extends IFluidDataStoreFactory>(
childFactory: T,
): ReturnType<Exclude<T["createDataStore"], undefined>> {
const maybe = this.registry?.getSync?.(childFactory.type);
const isUndefined = maybe === undefined;
const diffInstance = maybe?.IFluidDataStoreFactory !== childFactory;
if (isUndefined || diffInstance) {
throw new UsageError(
"The provided factory instance must be synchronously available as a child of this datastore",
{ isUndefined, diffInstance },
);
}
if (childFactory?.createDataStore === undefined) {
throw new UsageError("createDataStore must exist on the provided factory", {
noCreateDataStore: true,
});
}
const context = this._containerRuntime.createDetachedDataStore([
...this.packagePath,
childFactory.type,
]);
assert(
context instanceof LocalDetachedFluidDataStoreContext,
0xa89 /* must be a LocalDetachedFluidDataStoreContext */,
);
const created = childFactory.createDataStore(context) as ReturnType<
Exclude<T["createDataStore"], undefined>
>;
context.unsafe_AttachRuntimeSync(created.runtime);
return created;
}
private async realizeCore(existing: boolean): Promise<IFluidDataStoreChannel> {
const details = await this.getInitialSnapshotDetails();
// Base snapshot is the baseline where pending ops are applied to.
// It is important that this be in sync with the pending ops, and also
// that it is set here, before bindRuntime is called.
this._baseSnapshot = details.snapshot;
this.baseSnapshotSequenceNumber = details.sequenceNumber;
assert(this.pkg === details.pkg, 0x13e /* "Unexpected package path" */);
const factory = await this.factoryFromPackagePath();
const channel = await factory.instantiateDataStore(this, existing);
assert(channel !== undefined, 0x140 /* "undefined channel on datastore context" */);
await this.bindRuntime(channel, existing);
// This data store may have been disposed before the channel is created during realization. If so,
// dispose the channel now.
if (this.disposed) {
channel.dispose();
}
return channel;
}
/**
* Notifies this object about changes in the connection state.
* @param value - New connection state.
* @param clientId - ID of the client. Its old ID when in disconnected state and
* its new client ID when we are connecting or connected.
*/
public setConnectionState(connected: boolean, clientId?: string): void {
// ConnectionState should not fail in tombstone mode as this is internally run
this.verifyNotClosed("setConnectionState", false /* checkTombstone */);
// Connection events are ignored if the store is not yet loaded
if (!this.loaded) {
return;
}
assert(this.connected === connected, 0x141 /* "Unexpected connected state" */);
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
this.channel!.setConnectionState(connected, clientId);
}
public notifyReadOnlyState(): void {
this.verifyNotClosed("notifyReadOnlyState", false /* checkTombstone */);
// These two calls achieve the same purpose, and are both needed for a time for back compat
this.channel?.notifyReadOnlyState?.(this.isReadOnly());
this._contextDeltaManagerProxy.emitReadonly();
}
/**
* Updates the readonly state of the data store based on the staging mode.
*
* @param staging - A boolean indicating whether the container is in staging mode.
* If true, the data store is set to readonly unless explicitly allowed by its policies.
*/
public notifyStagingMode(staging: boolean): void {
// If the `readonlyInStagingMode` policy is not explicitly set to `false`,
// the data store is treated as readonly in staging mode.
const oldReadOnlyState = this.isReadOnly();
this.isStagingMode = staging;
if (this.isReadOnly() !== oldReadOnlyState) {
this.notifyReadOnlyState();
}
}
/**
* Process messages for this data store. The messages here are contiguous messages for this data store in a batch.
* @param messageCollection - The collection of messages to process.
*/
public processMessages(messageCollection: IRuntimeMessageCollection): void {
const { envelope, messagesContent, local } = messageCollection;
const safeTelemetryProps = extractSafePropertiesFromMessage(envelope);
// Tombstone error is logged in garbage collector. So, set "checkTombstone" to false when calling
// "verifyNotClosed" which logs tombstone errors.
this.verifyNotClosed("process", false /* checkTombstone */, safeTelemetryProps);
this.summarizerNode.recordChange(envelope as ISequencedDocumentMessage);
if (this.loaded) {
assert(this.channel !== undefined, 0xa68 /* Channel is not loaded */);
this.channel.processMessages(messageCollection);
} else {
assert(!local, 0x142 /* "local store channel is not loaded" */);
assert(
this.pendingMessagesState !== undefined,
0xa69 /* pending messages queue is undefined */,
);
this.pendingMessagesState.messageCollections.push({
...messageCollection,
messagesContent: [...messagesContent],
});
this.pendingMessagesState.pendingCount += messagesContent.length;
this.thresholdOpsCounter.sendIfMultiple(
"StorePendingOps",
this.pendingMessagesState.pendingCount,
);
}
}
public processSignal(message: IInboundSignalMessage, local: boolean): void {
this.verifyNotClosed("processSignal");
// Signals are ignored if the store is not yet loaded
if (!this.loaded) {
return;
}
this.channel?.processSignal(message, local);
}
public getQuorum(): IQuorumClients {
return this.parentContext.getQuorum();
}
public getAudience(): IAudience {
return this.parentContext.getAudience();
}
/**
* Returns a summary at the current sequence number.
* @param fullTree - true to bypass optimizations and force a full summary tree
* @param trackState - This tells whether we should track state from this summary.
* @param telemetryContext - summary data passed through the layers for telemetry purposes
*/
public async summarize(
fullTree: boolean = false,
trackState: boolean = true,
telemetryContext?: ITelemetryContext,
): Promise<ISummarizeResult> {
return this.summarizerNode.summarize(fullTree, trackState, telemetryContext);
}
private async summarizeInternal(
fullTree: boolean,
trackState: boolean,
telemetryContext?: ITelemetryContext,
): Promise<ISummarizeInternalResult> {
await this.realize();
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const summarizeResult = await this.channel!.summarize(
fullTree,
trackState,
telemetryContext,
);
// Wrap dds summaries in .channels subtree.
wrapSummaryInChannelsTree(summarizeResult);
const pathPartsForChildren = [channelsTreeName];
// Add data store's attributes to the summary.
const { pkg } = await this.getInitialSnapshotDetails();
const isRoot = await this.isRoot();
const attributes = createAttributes(pkg, isRoot);
addBlobToSummary(summarizeResult, dataStoreAttributesBlobName, JSON.stringify(attributes));
// If we are not referenced, mark the summary tree as unreferenced. Also, update unreferenced blob
// size in the summary stats with the blobs size of this data store.
if (!this.summarizerNode.isReferenced()) {
summarizeResult.summary.unreferenced = true;
summarizeResult.stats.unreferencedBlobSize = summarizeResult.stats.totalBlobSize;
}
// Add loadingGroupId to the summary
if (this.loadingGroupId !== undefined) {
summarizeResult.summary.groupId = this.loadingGroupId;
}
return {
...summarizeResult,
id: this.id,
pathPartsForChildren,
};
}
/**
* Returns the data used for garbage collection. This includes a list of GC nodes that represent this data store
* including any of its child channel contexts. Each node has a set of outbound routes to other GC nodes in the
* document.
* If there is no new data in this data store since the last summary, previous GC data is used.
* If there is new data, the GC data is generated again (by calling getGCDataInternal).
* @param fullGC - true to bypass optimizations and force full generation of GC data.
*/
public async getGCData(fullGC: boolean = false): Promise<IGarbageCollectionData> {
return this.summarizerNode.getGCData(fullGC);
}
/**
* Generates data used for garbage collection. This is called when there is new data since last summary. It
* realizes the data store and calls into each channel context to get its GC data.
* @param fullGC - true to bypass optimizations and force full generation of GC data.
*/
private async getGCDataInternal(fullGC: boolean = false): Promise<IGarbageCollectionData> {
await this.realize();
assert(
this.channel !== undefined,
0x143 /* "Channel should not be undefined when running GC" */,
);
return this.channel.getGCData(fullGC);
}
/**
* After GC has run, called to notify the data store of routes used in it. These are used for the following:
* 1. To identify if this data store is being referenced in the document or not.
* 2. To determine if it needs to re-summarize in case used routes changed since last summary.
* 3. To notify child contexts of their used routes. This is done immediately if the data store is loaded.
* Else, it is done by the data stores's summarizer node when child summarizer nodes are created.
*
* @param usedRoutes - The routes that are used in this data store.
*/
public updateUsedRoutes(usedRoutes: string[]): void {
// Update the used routes in this data store's summarizer node.
this.summarizerNode.updateUsedRoutes(usedRoutes);
// If the channel doesn't exist yet (data store is not realized), the summarizer node will update it
// when it creates child nodes.
if (!this.channel) {
return;
}
// Remove the route to this data store, if it exists.
const usedChannelRoutes = usedRoutes.filter((id: string) => {
return id !== "/" && id !== "";
});
this.channel.updateUsedRoutes(usedChannelRoutes);
}
/**
* Called when a new outbound reference is added to another node. This is used by garbage collection to identify
* all references added in the system.
*
* @param fromPath - The absolute path of the node that added the reference.
* @param toPath - The absolute path of the outbound node that is referenced.
* @param messageTimestampMs - The timestamp of the message that added the reference.
*/
public addedGCOutboundRoute(
fromPath: string,
toPath: string,
messageTimestampMs?: number,
): void {
this.parentContext.addedGCOutboundRoute(fromPath, toPath, messageTimestampMs);
}
public submitMessage(type: string, content: unknown, localOpMetadata: unknown): void {
this.verifyNotClosed("submitMessage");
assert(!!this.channel, 0x146 /* "Channel must exist when submitting message" */);
// Readonly clients should not submit messages.
this.identifyLocalChangeIfReadonly("DataStoreMessageWhileReadonly", type);
this.parentContext.submitMessage(type, content, localOpMetadata);
}
/**
* This is called from a SharedSummaryBlock that does not generate ops but only wants to be part of the summary.
* It indicates that there is data in the object that needs to be summarized.
* We will update the latestSequenceNumber of the summary tracker of this
* store and of the object's channel.
*
* @param address - The address of the channel that is dirty.
*
*/
public setChannelDirty(address: string): void {
this.verifyNotClosed("setChannelDirty");
// Get the latest sequence number.
const latestSequenceNumber = this.deltaManager.lastSequenceNumber;
this.summarizerNode.invalidate(latestSequenceNumber);
const channelSummarizerNode = this.summarizerNode.getChild(address);
if (channelSummarizerNode) {
channelSummarizerNode.invalidate(latestSequenceNumber); // TODO: lazy load problem?
}
}
public submitSignal(type: string, content: unknown, targetClientId?: string): void {
this.verifyNotClosed("submitSignal");
assert(!!this.channel, 0x147 /* "Channel must exist on submitting signal" */);
return this.parentContext.submitSignal(type, content, targetClientId);
}
/**
* This is called by the data store channel when it becomes locally visible indicating that it is ready to become
* globally visible now.
*/
public makeLocallyVisible(): void {
assert(this.channel !== undefined, 0x2cf /* "undefined channel on datastore context" */);
this.makeLocallyVisibleFn();
}
protected processPendingOps(channel: IFluidDataStoreChannel): void {
const baseSequenceNumber = this.baseSnapshotSequenceNumber ?? -1;
assert(
this.pendingMessagesState !== undefined,
0xa6a /* pending messages queue is undefined */,
);
for (const messageCollection of this.pendingMessagesState.messageCollections) {
// Only process ops whose seq number is greater than snapshot sequence number from which it loaded.
if (messageCollection.envelope.sequenceNumber > baseSequenceNumber) {
channel.processMessages(messageCollection);
}
}
this.thresholdOpsCounter.send("ProcessPendingOps", this.pendingMessagesState.pendingCount);
this.pendingMessagesState = undefined;
}