-
Notifications
You must be signed in to change notification settings - Fork 567
Expand file tree
/
Copy pathdirectory.ts
More file actions
2692 lines (2470 loc) · 87.7 KB
/
directory.ts
File metadata and controls
2692 lines (2470 loc) · 87.7 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 } from "@fluid-internal/client-utils";
import { assert, unreachableCase } from "@fluidframework/core-utils/internal";
import type {
IChannelAttributes,
IFluidDataStoreRuntime,
IChannelStorageService,
} from "@fluidframework/datastore-definitions/internal";
import { MessageType } from "@fluidframework/driver-definitions/internal";
import { readAndParse } from "@fluidframework/driver-utils/internal";
import type {
ISummaryTreeWithStats,
ITelemetryContext,
IRuntimeMessageCollection,
IRuntimeMessagesContent,
ISequencedMessageEnvelope,
} from "@fluidframework/runtime-definitions/internal";
import { SummaryTreeBuilder } from "@fluidframework/runtime-utils/internal";
import type { IFluidSerializer } from "@fluidframework/shared-object-base/internal";
import {
SharedObject,
ValueType,
bindHandles,
parseHandles,
} from "@fluidframework/shared-object-base/internal";
import {
createChildMonitoringContext,
type ITelemetryLoggerExt,
type MonitoringContext,
UsageError,
} from "@fluidframework/telemetry-utils/internal";
import path from "path-browserify";
import type {
IDirectory,
IDirectoryEvents,
IDirectoryValueChanged,
ISharedDirectory,
ISharedDirectoryEvents,
IValueChanged,
} from "./interfaces.js";
import type {
// eslint-disable-next-line import/no-deprecated
ISerializableValue,
ISerializedValue,
} from "./internalInterfaces.js";
import { serializeValue, migrateIfSharedSerializable } from "./localValues.js";
import { findLast, findLastIndex } from "./utils.js";
// We use path-browserify since this code can run safely on the server or the browser.
// We standardize on using posix slashes everywhere.
const posix = path.posix;
const snapshotFileName = "header";
/**
* Defines the means to process and submit a given op on a directory.
*/
interface IDirectoryMessageHandler {
/**
* Apply the given operation.
* @param msgEnvelope - The envelope of the message from the server to apply.
* @param op - The directory operation to apply
* @param local - Whether the message originated from the local client
* @param localOpMetadata - For local client messages, this is the metadata that was submitted with the message.
* For messages from a remote client, this will be undefined.
* @param clientSequenceNumber - The client sequence number of the message.
*/
process(
msgEnvelope: ISequencedMessageEnvelope,
op: IDirectoryOperation,
local: boolean,
localOpMetadata: DirectoryLocalOpMetadata | undefined,
clientSequenceNumber: number,
): void;
/**
* Resubmit a previously submitted operation that was not delivered.
* @param op - The directory operation to resubmit
* @param localOpMetadata - The metadata that was originally submitted with the message.
*/
resubmit(op: IDirectoryOperation, localOpMetadata: DirectoryLocalOpMetadata): void;
}
/**
* Operation indicating a value should be set for a key.
*/
export interface IDirectorySetOperation {
/**
* String identifier of the operation type.
*/
type: "set";
/**
* Directory key being modified.
*/
key: string;
/**
* Absolute path of the directory where the modified key is located.
*/
path: string;
/**
* Value to be set on the key.
*/
// eslint-disable-next-line import/no-deprecated
value: ISerializableValue;
}
/**
* Operation indicating a key should be deleted from the directory.
*/
export interface IDirectoryDeleteOperation {
/**
* String identifier of the operation type.
*/
type: "delete";
/**
* Directory key being modified.
*/
key: string;
/**
* Absolute path of the directory where the modified key is located.
*/
path: string;
}
/**
* An operation on a specific key within a directory.
*/
export type IDirectoryKeyOperation = IDirectorySetOperation | IDirectoryDeleteOperation;
/**
* Operation indicating the directory should be cleared.
*/
export interface IDirectoryClearOperation {
/**
* String identifier of the operation type.
*/
type: "clear";
/**
* Absolute path of the directory being cleared.
*/
path: string;
}
/**
* An operation on one or more of the keys within a directory.
*/
export type IDirectoryStorageOperation = IDirectoryKeyOperation | IDirectoryClearOperation;
/**
* Operation indicating a subdirectory should be created.
*/
export interface IDirectoryCreateSubDirectoryOperation {
/**
* String identifier of the operation type.
*/
type: "createSubDirectory";
/**
* Absolute path of the directory that will contain the new subdirectory.
*/
path: string;
/**
* Name of the new subdirectory.
*/
subdirName: string;
}
/**
* Operation indicating a subdirectory should be deleted.
*/
export interface IDirectoryDeleteSubDirectoryOperation {
/**
* String identifier of the operation type.
*/
type: "deleteSubDirectory";
/**
* Absolute path of the directory that contains the directory to be deleted.
*/
path: string;
/**
* Name of the subdirectory to be deleted.
*/
subdirName: string;
}
/**
* An operation on the subdirectories within a directory.
*/
export type IDirectorySubDirectoryOperation =
| IDirectoryCreateSubDirectoryOperation
| IDirectoryDeleteSubDirectoryOperation;
/**
* Any operation on a directory.
*/
export type IDirectoryOperation = IDirectoryStorageOperation | IDirectorySubDirectoryOperation;
interface PendingKeySet {
type: "set";
path: string;
value: unknown;
subdir: SubDirectory;
}
interface PendingKeyDelete {
type: "delete";
path: string;
key: string;
subdir: SubDirectory;
}
interface PendingClear {
type: "clear";
path: string;
subdir: SubDirectory;
}
/**
* Represents the "lifetime" of a series of pending set operations before the pending
* set operations are ack'd.
*/
interface PendingKeyLifetime {
type: "lifetime";
key: string;
path: string;
/**
* A non-empty array of pending key sets that occurred during this lifetime. If the list
* becomes empty (e.g. during processing or rollback), the lifetime no longer exists and
* must be removed from the pending data.
*/
keySets: PendingKeySet[];
subdir: SubDirectory;
}
/**
* A member of the pendingStorageData array, which tracks outstanding changes and can be used to
* compute optimistic values. Local sets are aggregated into lifetimes.
*/
type PendingStorageEntry = PendingKeyLifetime | PendingKeyDelete | PendingClear;
interface PendingSubDirectoryCreate {
type: "createSubDirectory";
subdirName: string;
subdir: SubDirectory;
}
interface PendingSubDirectoryDelete {
type: "deleteSubDirectory";
subdirName: string;
subdir: SubDirectory;
}
type PendingSubDirectoryEntry = PendingSubDirectoryCreate | PendingSubDirectoryDelete;
/**
* Create info for the subdirectory.
*
* @deprecated This interface will no longer be exported in the future(AB#8004).
*
* @legacy @beta
*/
export interface ICreateInfo {
/**
* Sequence number at which this subdirectory was created.
*/
csn: number;
/**
* clientids of the clients which created this sub directory.
*/
ccIds: string[];
}
/**
* Defines the in-memory object structure to be used for the conversion to/from serialized.
*
* @remarks Directly used in
* {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
* | JSON.stringify}, direct result from
* {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse | JSON.parse}.
*
* @deprecated This interface will no longer be exported in the future(AB#8004).
*
* @legacy @beta
*/
export interface IDirectoryDataObject {
/**
* Key/value date set by the user.
*/
// eslint-disable-next-line import/no-deprecated
storage?: Record<string, ISerializableValue>;
/**
* Recursive sub-directories {@link IDirectoryDataObject | objects}.
*/
subdirectories?: Record<string, IDirectoryDataObject>;
/**
* Create info for the sub directory. Since directories with same name can get deleted/created by multiple clients
* asynchronously, this info helps us to determine whether the ops where for the current instance of sub directory
* or not and whether to process them or not based on that. Summaries which were not produced which this change
* will not have this info and in that case we can still run in eventual consistency issues but that is no worse
* than the state before this change.
*/
ci?: ICreateInfo;
}
/**
* {@link IDirectory} storage format.
*
* @deprecated This interface will no longer be exported in the future(AB#8004).
*
* @legacy @beta
*/
export interface IDirectoryNewStorageFormat {
/**
* Blob IDs representing larger directory data that was serialized.
*/
blobs: string[];
/**
* Storage content representing directory data that was not serialized.
*/
content: IDirectoryDataObject;
}
/**
* The comparator essentially performs the following procedure to determine the order of subdirectory creation:
* 1. If subdirectory A has a non-negative 'seq' and subdirectory B has a negative 'seq', subdirectory A is always placed first due to
* the policy that acknowledged subdirectories precede locally created ones that have not been committed yet.
*
* 2. When both subdirectories A and B have a non-negative 'seq', they are compared as follows:
* - If A and B have different 'seq', they are ordered based on 'seq', and the one with the lower 'seq' will be positioned ahead. Notably this rule
* should not be applied in the directory ordering, since the lowest 'seq' is -1, when the directory is created locally but not acknowledged yet.
* - In the case where A and B have equal 'seq', the one with the lower 'clientSeq' will be positioned ahead. This scenario occurs when grouped
* batching is enabled, and a lower 'clientSeq' indicates that it was processed earlier after the batch was ungrouped.
*
* 3. When both subdirectories A and B have a negative 'seq', they are compared as follows:
* - If A and B have different 'seq', the one with lower 'seq' will be positioned ahead, which indicates the corresponding creation message was
* acknowledged by the server earlier.
* - If A and B have equal 'seq', the one with lower 'clientSeq' will be placed at the front. This scenario suggests that both subdirectories A
* and B were created locally and not acknowledged yet, with the one possessing the lower 'clientSeq' being created earlier.
*
* 4. A 'seq' value of zero indicates that the subdirectory was created in detached state, and it is considered acknowledged for the
* purpose of ordering.
*/
const seqDataComparator = (a: SequenceData, b: SequenceData): number => {
if (isAcknowledgedOrDetached(a)) {
if (isAcknowledgedOrDetached(b)) {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
return a.seq === b.seq ? a.clientSeq! - b.clientSeq! : a.seq - b.seq;
} else {
return -1;
}
} else {
if (isAcknowledgedOrDetached(b)) {
return 1;
} else {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
return a.seq === b.seq ? a.clientSeq! - b.clientSeq! : a.seq - b.seq;
}
}
};
function isAcknowledgedOrDetached(seqData: SequenceData): boolean {
return seqData.seq >= 0;
}
/**
* The combination of sequence numebr and client sequence number of a subdirectory
*/
interface SequenceData {
seq: number;
clientSeq?: number;
}
/**
* {@inheritDoc ISharedDirectory}
*
* @example
*
* ```typescript
* mySharedDirectory.createSubDirectory("a").createSubDirectory("b").createSubDirectory("c").set("foo", val1);
* const mySubDir = mySharedDirectory.getWorkingDirectory("/a/b/c");
* mySubDir.get("foo"); // returns val1
* ```
*
* @sealed
*/
export class SharedDirectory
extends SharedObject<ISharedDirectoryEvents>
implements ISharedDirectory
{
/**
* String representation for the class.
*/
public [Symbol.toStringTag]: string = "SharedDirectory";
/**
* {@inheritDoc IDirectory.absolutePath}
*/
public get absolutePath(): string {
return this.root.absolutePath;
}
/**
* Root of the SharedDirectory, most operations on the SharedDirectory itself act on the root.
*/
private readonly root: SubDirectory = new SubDirectory(
{ seq: 0, clientSeq: 0 },
new Set(),
this,
this.runtime,
this.serializer,
posix.sep,
this.logger,
);
/**
* Mapping of op types to message handlers.
*/
private readonly messageHandlers = new Map<string, IDirectoryMessageHandler>();
/**
* Constructs a new shared directory. If the object is non-local an id and service interfaces will
* be provided.
* @param id - String identifier for the SharedDirectory
* @param runtime - Data store runtime
* @param type - Type identifier
*/
public constructor(
id: string,
runtime: IFluidDataStoreRuntime,
attributes: IChannelAttributes,
) {
super(id, runtime, attributes, "fluid_directory_");
this.setMessageHandlers();
// Mirror the containedValueChanged op on the SharedDirectory
this.root.on("containedValueChanged", (changed: IValueChanged, local: boolean) => {
this.emit("containedValueChanged", changed, local, this);
});
this.root.on("subDirectoryCreated", (relativePath: string, local: boolean) => {
this.emit("subDirectoryCreated", relativePath, local, this);
});
this.root.on("subDirectoryDeleted", (relativePath: string, local: boolean) => {
this.emit("subDirectoryDeleted", relativePath, local, this);
});
}
/**
* {@inheritDoc IDirectory.get}
*/
// TODO: Use `unknown` instead (breaking change).
// eslint-disable-next-line @typescript-eslint/no-explicit-any
public get<T = any>(key: string): T | undefined {
return this.root.get<T>(key);
}
/**
* {@inheritDoc IDirectory.set}
*/
public set<T = unknown>(key: string, value: T): this {
this.root.set(key, value);
return this;
}
public dispose(error?: Error): void {
this.root.dispose(error);
}
public get disposed(): boolean {
return this.root.disposed;
}
/**
* Deletes the given key from within this IDirectory.
* @param key - The key to delete
* @returns True if the key existed and was deleted, false if it did not exist
*/
public delete(key: string): boolean {
return this.root.delete(key);
}
/**
* Deletes all keys from within this IDirectory.
*/
public clear(): void {
this.root.clear();
}
/**
* Checks whether the given key exists in this IDirectory.
* @param key - The key to check
* @returns True if the key exists, false otherwise
*/
public has(key: string): boolean {
return this.root.has(key);
}
/**
* The number of entries under this IDirectory.
*/
public get size(): number {
return this.root.size;
}
/**
* Issue a callback on each entry under this IDirectory.
* @param callback - Callback to issue
*/
// TODO: Use `unknown` instead (breaking change).
// eslint-disable-next-line @typescript-eslint/no-explicit-any
public forEach(callback: (value: any, key: string, map: Map<string, any>) => void): void {
// eslint-disable-next-line unicorn/no-array-for-each, unicorn/no-array-callback-reference
this.root.forEach(callback);
}
/**
* Get an iterator over the entries under this IDirectory.
* @returns The iterator
*/
// TODO: Use `unknown` instead (breaking change).
// eslint-disable-next-line @typescript-eslint/no-explicit-any
public [Symbol.iterator](): IterableIterator<[string, any]> {
return this.root[Symbol.iterator]();
}
/**
* Get an iterator over the entries under this IDirectory.
* @returns The iterator
*/
// TODO: Use `unknown` instead (breaking change).
// eslint-disable-next-line @typescript-eslint/no-explicit-any
public entries(): IterableIterator<[string, any]> {
return this.root.entries();
}
/**
* {@inheritDoc IDirectory.countSubDirectory}
*/
public countSubDirectory(): number {
return this.root.countSubDirectory();
}
/**
* Get an iterator over the keys under this IDirectory.
* @returns The iterator
*/
public keys(): IterableIterator<string> {
return this.root.keys();
}
/**
* Get an iterator over the values under this IDirectory.
* @returns The iterator
*/
// TODO: Use `unknown` instead (breaking change).
// eslint-disable-next-line @typescript-eslint/no-explicit-any
public values(): IterableIterator<any> {
return this.root.values();
}
/**
* {@inheritDoc IDirectory.createSubDirectory}
*/
public createSubDirectory(subdirName: string): IDirectory {
return this.root.createSubDirectory(subdirName);
}
/**
* {@inheritDoc IDirectory.getSubDirectory}
*/
public getSubDirectory(subdirName: string): IDirectory | undefined {
return this.root.getSubDirectory(subdirName);
}
/**
* {@inheritDoc IDirectory.hasSubDirectory}
*/
public hasSubDirectory(subdirName: string): boolean {
return this.root.hasSubDirectory(subdirName);
}
/**
* {@inheritDoc IDirectory.deleteSubDirectory}
*/
public deleteSubDirectory(subdirName: string): boolean {
return this.root.deleteSubDirectory(subdirName);
}
/**
* {@inheritDoc IDirectory.subdirectories}
*/
public subdirectories(): IterableIterator<[string, IDirectory]> {
return this.root.subdirectories();
}
/**
* {@inheritDoc IDirectory.getWorkingDirectory}
*/
public getWorkingDirectory(relativePath: string): IDirectory | undefined {
const absolutePath = this.makeAbsolute(relativePath);
if (absolutePath === posix.sep) {
return this.root;
}
let currentSubDir = this.root;
const subdirs = absolutePath.slice(1).split(posix.sep);
for (const subdir of subdirs) {
currentSubDir = currentSubDir.getSubDirectory(subdir) as SubDirectory;
if (!currentSubDir) {
return undefined;
}
}
return currentSubDir;
}
/**
* Similar to `getWorkingDirectory`, but only returns directories that are sequenced.
* This can be useful for op processing since we only process ops on sequenced directories.
*/
private getSequencedWorkingDirectory(relativePath: string): IDirectory | undefined {
const absolutePath = this.makeAbsolute(relativePath);
if (absolutePath === posix.sep) {
return this.root;
}
let currentSubDir: SubDirectory | undefined = this.root;
const subdirs = absolutePath.slice(1).split(posix.sep);
for (const subdir of subdirs) {
currentSubDir = currentSubDir.sequencedSubdirectories.get(subdir);
if (!currentSubDir) {
return undefined;
}
}
return currentSubDir;
}
/**
* {@inheritDoc @fluidframework/shared-object-base#SharedObject.summarizeCore}
*/
protected summarizeCore(
serializer: IFluidSerializer,
telemetryContext?: ITelemetryContext,
): ISummaryTreeWithStats {
return this.serializeDirectory(this.root, serializer);
}
/**
* Submits an operation
* @param op - Op to submit
* @param localOpMetadata - The local metadata associated with the op. We send a unique id that is used to track
* this op while it has not been ack'd. This will be sent when we receive this op back from the server.
*/
public submitDirectoryMessage(
op: IDirectoryOperation,
localOpMetadata: DirectoryLocalOpMetadata,
): void {
this.submitLocalMessage(op, localOpMetadata);
}
/**
* {@inheritDoc @fluidframework/shared-object-base#SharedObject.onDisconnect}
*/
protected onDisconnect(): void {}
/**
* {@inheritDoc @fluidframework/shared-object-base#SharedObject.reSubmitCore}
*/
protected override reSubmitCore(
content: unknown,
localOpMetadata: DirectoryLocalOpMetadata,
): void {
const message = content as IDirectoryOperation;
const handler = this.messageHandlers.get(message.type);
assert(handler !== undefined, 0x00d /* Missing message handler for message type */);
handler.resubmit(message, localOpMetadata);
}
/**
* {@inheritDoc @fluidframework/shared-object-base#SharedObject.loadCore}
*/
protected async loadCore(storage: IChannelStorageService): Promise<void> {
const data = await readAndParse(storage, snapshotFileName);
const newFormat = data as IDirectoryNewStorageFormat;
if (Array.isArray(newFormat.blobs)) {
// New storage format
this.populate(newFormat.content);
const blobContents = await Promise.all(
newFormat.blobs.map(async (blobName) => readAndParse(storage, blobName)),
);
for (const blobContent of blobContents) {
this.populate(blobContent as IDirectoryDataObject);
}
} else {
// Old storage format
this.populate(data as IDirectoryDataObject);
}
}
/**
* Populate the directory with the given directory data.
* @param data - A JSON string containing serialized directory data
*/
protected populate(data: IDirectoryDataObject): void {
const stack: [SubDirectory, IDirectoryDataObject][] = [];
stack.push([this.root, data]);
while (stack.length > 0) {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const [currentSubDir, currentSubDirObject] = stack.pop()!;
if (currentSubDirObject.subdirectories) {
// Utilize a map to store the seq -> clientSeq for the newly created subdirectory
const tempSeqNums = new Map<number, number>();
for (const [subdirName, subdirObject] of Object.entries(
currentSubDirObject.subdirectories,
)) {
let newSubDir = currentSubDir.getSubDirectory(subdirName) as SubDirectory;
let seqData: SequenceData;
if (!newSubDir) {
const createInfo = subdirObject.ci;
// We do not store the client sequence number in the storage because the order has already been
// guaranteed during the serialization process. As a result, it is only essential to utilize the
// "fake" client sequence number to signify the loading order, and there is no need to retain
// the actual client sequence number at this point.
if (createInfo !== undefined && createInfo.csn > 0) {
if (!tempSeqNums.has(createInfo.csn)) {
tempSeqNums.set(createInfo.csn, 0);
}
let fakeClientSeq = tempSeqNums.get(createInfo.csn) as number;
seqData = { seq: createInfo.csn, clientSeq: fakeClientSeq };
tempSeqNums.set(createInfo.csn, ++fakeClientSeq);
} else {
/**
* 1. If csn is -1, then initialize it with 0, otherwise we will never process ops for this
* sub directory. This could be done at serialization time too, but we need to maintain
* back compat too and also we will actually know the state when it was serialized.
* 2. We need to make the csn = -1 and csn = 0 share the same counter, there are cases
* where both -1 and 0 coexist within a single document.
*/
seqData = {
seq: 0,
clientSeq: ++currentSubDir.localCreationSeq,
};
}
newSubDir = new SubDirectory(
seqData,
createInfo === undefined ? new Set() : new Set<string>(createInfo.ccIds),
this,
this.runtime,
this.serializer,
posix.join(currentSubDir.absolutePath, subdirName),
this.logger,
);
currentSubDir.populateSubDirectory(subdirName, newSubDir);
}
stack.push([newSubDir, subdirObject]);
}
}
if (currentSubDirObject.storage) {
for (const [key, serializable] of Object.entries(currentSubDirObject.storage)) {
const parsedSerializable = parseHandles(
serializable,
this.serializer,
// eslint-disable-next-line import/no-deprecated
) as ISerializableValue;
migrateIfSharedSerializable(parsedSerializable, this.serializer, this.handle);
currentSubDir.populateStorage(key, parsedSerializable.value);
}
}
}
}
/**
* {@inheritDoc @fluidframework/shared-object-base#SharedObject.processMessagesCore}
*/
protected override processMessagesCore(messagesCollection: IRuntimeMessageCollection): void {
const { envelope, local, messagesContent } = messagesCollection;
for (const messageContent of messagesContent) {
this.processMessage(envelope, messageContent, local);
}
}
private processMessage(
messageEnvelope: ISequencedMessageEnvelope,
messageContent: IRuntimeMessagesContent,
local: boolean,
): void {
// eslint-disable-next-line @typescript-eslint/no-unsafe-enum-comparison
if (messageEnvelope.type === MessageType.Operation) {
const op: IDirectoryOperation = messageContent.contents as IDirectoryOperation;
const handler = this.messageHandlers.get(op.type);
assert(
handler !== undefined,
0x00e /* "Missing message handler for message type: op may be from a newer version */,
);
handler.process(
messageEnvelope,
op,
local,
messageContent.localOpMetadata as DirectoryLocalOpMetadata | undefined,
messageContent.clientSequenceNumber,
);
}
}
/**
* {@inheritDoc @fluidframework/shared-object-base#SharedObject.rollback}
*/
protected override rollback(
content: unknown,
localOpMetadata: DirectoryLocalOpMetadata,
): void {
const op: IDirectoryOperation = content as IDirectoryOperation;
const subdir = this.getWorkingDirectory(op.path) as SubDirectory | undefined;
if (subdir) {
subdir.rollback(op, localOpMetadata);
}
}
/**
* Converts the given relative path to absolute against the root.
* @param relativePath - The path to convert
*/
private makeAbsolute(relativePath: string): string {
return posix.resolve(posix.sep, relativePath);
}
/**
* Set the message handlers for the directory.
*/
private setMessageHandlers(): void {
// Notes on how we target the correct subdirectory:
// `process`: When processing ops, we only ever want to process ops on sequenced directories. This prevents
// scenarios where ops could be processed on a pending directory instead of a sequenced directory,
// leading to ops effectively being processed out of order.
// `resubmit`: When resubmitting ops, we use `localOpMetadata` to get a reference to the subdirectory that
// the op was originally targeting.
this.messageHandlers.set("clear", {
process: (
msgEnvelope: ISequencedMessageEnvelope,
op: IDirectoryClearOperation,
local: boolean,
localOpMetadata: ClearLocalOpMetadata | undefined,
clientSequenceNumber: number,
) => {
const subdir = this.getSequencedWorkingDirectory(op.path) as SubDirectory | undefined;
if (subdir !== undefined && !subdir?.disposed) {
subdir.processClearMessage(msgEnvelope, op, local, localOpMetadata);
}
},
resubmit: (op: IDirectoryClearOperation, localOpMetadata: ClearLocalOpMetadata) => {
const targetSubdir = localOpMetadata.subdir;
if (!targetSubdir.disposed) {
targetSubdir.resubmitClearMessage(op, localOpMetadata);
}
},
});
this.messageHandlers.set("delete", {
process: (
msgEnvelope: ISequencedMessageEnvelope,
op: IDirectoryDeleteOperation,
local: boolean,
localOpMetadata: EditLocalOpMetadata | undefined,
clientSequenceNumber: number,
) => {
const subdir = this.getSequencedWorkingDirectory(op.path) as SubDirectory | undefined;
if (subdir !== undefined && !subdir?.disposed) {
subdir.processDeleteMessage(msgEnvelope, op, local, localOpMetadata);
}
},
resubmit: (op: IDirectoryDeleteOperation, localOpMetadata: EditLocalOpMetadata) => {
const targetSubdir = localOpMetadata.subdir;
if (!targetSubdir.disposed) {
targetSubdir.resubmitKeyMessage(op, localOpMetadata);
}
},
});
this.messageHandlers.set("set", {
process: (
msgEnvelope: ISequencedMessageEnvelope,
op: IDirectorySetOperation,
local: boolean,
localOpMetadata: EditLocalOpMetadata | undefined,
clientSequenceNumber: number,
) => {
const subdir = this.getSequencedWorkingDirectory(op.path) as SubDirectory | undefined;
if (subdir !== undefined && !subdir?.disposed) {
migrateIfSharedSerializable(op.value, this.serializer, this.handle);
const localValue: unknown = local ? undefined : op.value.value;
subdir.processSetMessage(msgEnvelope, op, localValue, local, localOpMetadata);
}
},
resubmit: (op: IDirectorySetOperation, localOpMetadata: EditLocalOpMetadata) => {
const targetSubdir = localOpMetadata.subdir;
if (!targetSubdir.disposed) {
targetSubdir.resubmitKeyMessage(op, localOpMetadata);
}
},
});
this.messageHandlers.set("createSubDirectory", {
process: (
msgEnvelope: ISequencedMessageEnvelope,
op: IDirectoryCreateSubDirectoryOperation,
local: boolean,
localOpMetadata: SubDirLocalOpMetadata | undefined,
clientSequenceNumber: number,
) => {
const parentSubdir = this.getSequencedWorkingDirectory(op.path) as
| SubDirectory
| undefined;
if (parentSubdir !== undefined && !parentSubdir?.disposed) {
parentSubdir.processCreateSubDirectoryMessage(
msgEnvelope,
op,
local,
localOpMetadata,
clientSequenceNumber,
);
}
},
resubmit: (
op: IDirectoryCreateSubDirectoryOperation,
localOpMetadata: SubDirLocalOpMetadata,
) => {
const targetSubdir = localOpMetadata.parentSubdir;
if (!targetSubdir.disposed) {
// We don't reuse the metadata but send a new one on each submit.
targetSubdir.resubmitSubDirectoryMessage(op, localOpMetadata);
}
},
});
this.messageHandlers.set("deleteSubDirectory", {
process: (
msgEnvelope: ISequencedMessageEnvelope,
op: IDirectoryDeleteSubDirectoryOperation,
local: boolean,
localOpMetadata: SubDirLocalOpMetadata | undefined,
) => {
const parentSubdir = this.getSequencedWorkingDirectory(op.path) as
| SubDirectory
| undefined;
if (parentSubdir !== undefined && !parentSubdir?.disposed) {
parentSubdir.processDeleteSubDirectoryMessage(
msgEnvelope,
op,
local,
localOpMetadata,
);
}
},
resubmit: (
op: IDirectoryDeleteSubDirectoryOperation,
localOpMetadata: SubDirLocalOpMetadata,
) => {
const targetSubdir = localOpMetadata.parentSubdir;
if (!targetSubdir.disposed) {
// We don't reuse the metadata but send a new one on each submit.
targetSubdir.resubmitSubDirectoryMessage(op, localOpMetadata);
}
},
});
}
/**
* {@inheritDoc @fluidframework/shared-object-base#SharedObjectCore.applyStashedOp}
*/
protected applyStashedOp(op: unknown): void {
const directoryOp = op as IDirectoryOperation;
const dir = this.getWorkingDirectory(directoryOp.path);
switch (directoryOp.type) {
case "clear": {
dir?.clear();
break;
}
case "createSubDirectory": {
dir?.createSubDirectory(directoryOp.subdirName);
break;
}
case "delete": {
dir?.delete(directoryOp.key);
break;
}