forked from microsoft/FluidFramework
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontainerRuntime.spec.ts
More file actions
4360 lines (3965 loc) · 149 KB
/
containerRuntime.spec.ts
File metadata and controls
4360 lines (3965 loc) · 149 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 { strict as assert } from "node:assert";
import { stringToBuffer } from "@fluid-internal/client-utils";
import {
AttachState,
type ICriticalContainerError,
} from "@fluidframework/container-definitions";
import {
ContainerErrorTypes,
type IContainerContext,
type IBatchMessage,
type IContainerStorageService,
} from "@fluidframework/container-definitions/internal";
import type { IContainerRuntime } from "@fluidframework/container-runtime-definitions/internal";
import type {
ConfigTypes,
FluidObject,
IConfigProviderBase,
IResponse,
} from "@fluidframework/core-interfaces";
import type {
IErrorBase,
ISignalEnvelope,
ITelemetryBaseLogger,
OpaqueJsonDeserialized,
} from "@fluidframework/core-interfaces/internal";
import type { ISummaryTree, SummaryObject } from "@fluidframework/driver-definitions";
import {
type ISnapshot,
type ISummaryContext,
type ISnapshotTree,
MessageType,
type ISequencedDocumentMessage,
type IVersion,
type FetchSource,
type IDocumentAttributes,
SummaryType,
} from "@fluidframework/driver-definitions/internal";
import type {
FluidDataStoreMessage,
ISummaryTreeWithStats,
FluidDataStoreRegistryEntry,
IFluidDataStoreContext,
IFluidDataStoreFactory,
IFluidDataStoreRegistry,
NamedFluidDataStoreRegistryEntries,
IRuntimeMessageCollection,
ISequencedMessageEnvelope,
ITelemetryContext,
ISummarizeInternalResult,
} from "@fluidframework/runtime-definitions/internal";
import { FlushMode } from "@fluidframework/runtime-definitions/internal";
import { defaultMinVersionForCollab } from "@fluidframework/runtime-utils/internal";
import {
type IFluidErrorBase,
MockLogger,
UsageError,
createChildLogger,
isFluidError,
isILoggingError,
mixinMonitoringContext,
} from "@fluidframework/telemetry-utils/internal";
import {
MockAudience,
MockDeltaManager,
MockFluidDataStoreRuntime,
MockQuorumClients,
} from "@fluidframework/test-runtime-utils/internal";
import Sinon, { type SinonFakeTimers } from "sinon";
import { ChannelCollection } from "../channelCollection.js";
import { CompressionAlgorithms, enabledCompressionConfig } from "../compressionDefinitions.js";
import {
ContainerRuntime,
type IContainerRuntimeOptions,
type IPendingRuntimeState,
defaultPendingOpsWaitTimeoutMs,
getSingleUseLegacyLogCallback,
type ContainerRuntimeOptionsInternal,
type IContainerRuntimeOptionsInternal,
type UnknownIncomingTypedMessage,
} from "../containerRuntime.js";
import { FluidDataStoreRegistry } from "../dataStoreRegistry.js";
import {
ContainerMessageType,
type InboundSequencedContainerRuntimeMessage,
type LocalContainerRuntimeMessage,
type UnknownContainerRuntimeMessage,
} from "../messageTypes.js";
import type {
BatchResubmitInfo,
InboundMessageResult,
LocalBatchMessage,
} from "../opLifecycle/index.js";
import { pkgVersion } from "../packageVersion.js";
import type {
IPendingLocalState,
IPendingMessage,
PendingStateManager,
} from "../pendingStateManager.js";
import {
type ISummaryCancellationToken,
neverCancelledSummaryToken,
recentBatchInfoBlobName,
type IRefreshSummaryAckOptions,
} from "../summary/index.js";
type Patch<T, U> = Omit<T, keyof U> & U;
type ContainerRuntime_WithPrivates = Patch<
ContainerRuntime,
{ flush: (resubmitInfo?: BatchResubmitInfo) => void; channelCollection: ChannelCollection }
>;
const testDataStoreMessage = {
type: "op",
content: { address: "test-address", contents: "test-contents" },
} as const satisfies FluidDataStoreMessage;
function genTestDataStoreMessage(contents: unknown): FluidDataStoreMessage {
return {
type: "op",
content: { address: "test-address", contents },
};
}
function submitDataStoreOp(
runtime: Pick<ContainerRuntime, "submitMessage">,
id: string,
contents: FluidDataStoreMessage,
localOpMetadata?: unknown,
): void {
runtime.submitMessage(
{
type: ContainerMessageType.FluidDataStoreOp,
contents: {
address: id,
contents,
},
},
localOpMetadata,
);
}
const changeConnectionState = (
runtime: Omit<ContainerRuntime, "submit">,
connected: boolean,
clientId: string,
): void => {
const audience = runtime.getAudience() as MockAudience;
audience.setCurrentClientId(clientId);
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access -- Modifying private property
(runtime as any)._getClientId = () => clientId;
runtime.setConnectionState(connected, clientId);
};
interface ISignalEnvelopeWithClientIds {
envelope: ISignalEnvelope<UnknownIncomingTypedMessage>;
clientId: string;
targetClientId?: string;
}
function isSignalEnvelope(obj: unknown): obj is ISignalEnvelope<UnknownIncomingTypedMessage> {
return (
typeof obj === "object" &&
obj !== null &&
"contents" in obj &&
typeof obj.contents === "object" &&
obj.contents !== null &&
"content" in obj.contents &&
"type" in obj.contents &&
typeof obj.contents.type === "string" &&
(!("address" in obj) || typeof obj.address === "string" || obj.address === undefined) &&
(!("clientBroadcastSignalSequenceNumber" in obj) ||
typeof obj.clientBroadcastSignalSequenceNumber === "number")
);
}
let sandbox: Sinon.SinonSandbox;
function stubChannelCollection(
containerRuntime: ContainerRuntime_WithPrivates,
): Sinon.SinonStubbedInstance<ChannelCollection> {
// Pass data store op right back to ContainerRuntime
const reSubmitFake = sandbox
.stub<Parameters<ChannelCollection["reSubmitContainerMessage"]>, void>()
.callsFake(containerRuntime.submitMessage.bind(containerRuntime));
const stub = Sinon.createStubInstance(
// createSubInstance does not work with property methods (which are
// used for stricter typing); so, override via a subclass here.
class TestChannelCollection extends ChannelCollection {
// @ts-expect-error -- redefine as instance method for stubbing
public reSubmitContainerMessage(
..._args: Parameters<ChannelCollection["reSubmitContainerMessage"]>
): void {}
// @ts-expect-error -- redefine as instance method for stubbing
public rollbackDataStoreOp(
..._args: Parameters<ChannelCollection["rollbackDataStoreOp"]>
) {}
},
{
setConnectionState: sandbox.stub(),
reSubmitContainerMessage: reSubmitFake,
rollbackDataStoreOp: sandbox.stub(),
notifyStagingMode: sandbox.stub(),
dispose: sandbox.stub(),
},
);
containerRuntime.channelCollection = stub;
return stub;
}
function assertSignalContentIsAString(
content: OpaqueJsonDeserialized<unknown> | string,
): asserts content is string {
assert(typeof content === "string", "Signal content expected to be a string");
}
describe("Runtime", () => {
const configProvider = (settings: Record<string, ConfigTypes>): IConfigProviderBase => ({
getRawConfig: (name: string): ConfigTypes => settings[name],
});
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let submittedOps: any[] = [];
let submittedSignals: ISignalEnvelopeWithClientIds[] = [];
let opFakeSequenceNumber = 1;
let clock: SinonFakeTimers;
before(() => {
clock = Sinon.useFakeTimers();
});
beforeEach(() => {
submittedOps = [];
opFakeSequenceNumber = 1;
submittedSignals = [];
sandbox = Sinon.createSandbox();
});
afterEach(() => {
clock.reset();
});
after(() => {
clock.restore();
});
const mockClientId = "mockClientId";
// Mock the storage layer so "submitSummary" works.
const defaultMockStorage: Partial<IContainerStorageService> = {
uploadSummaryWithContext: async (summary: ISummaryTree, context: ISummaryContext) => {
return "fakeHandle";
},
};
const getMockContext = (
params: {
settings?: Record<string, ConfigTypes>;
logger?: ITelemetryBaseLogger;
mockStorage?: Partial<IContainerStorageService>;
loadedFromVersion?: IVersion;
baseSnapshot?: ISnapshotTree;
connected?: boolean;
attachState?: AttachState;
} = {},
clientId: string = mockClientId,
): Partial<IContainerContext> => {
const {
settings = {},
logger = new MockLogger(),
mockStorage = defaultMockStorage,
loadedFromVersion,
baseSnapshot,
connected = true,
attachState = AttachState.Attached,
} = params;
const mockContext = {
attachState,
deltaManager: new MockDeltaManager(),
audience: new MockAudience(),
quorum: new MockQuorumClients(),
taggedLogger: mixinMonitoringContext(logger, configProvider(settings)).logger,
clientDetails: { capabilities: { interactive: true } },
closeFn: (_error?: ICriticalContainerError): void => {},
updateDirtyContainerState: (_dirty: boolean) => {},
getLoadedFromVersion: () => loadedFromVersion,
submitFn: (
_type: MessageType,
contents: object,
_batch: boolean,
metadata?: unknown,
) => {
submittedOps.push({ ...contents, metadata }); // Note: this object shape is for testing only. Not representative of real ops.
return opFakeSequenceNumber++;
},
submitSignalFn: (content: unknown, targetClientId?: string) => {
assert(isSignalEnvelope(content), "Invalid signal envelope");
submittedSignals.push({
envelope: content,
clientId,
targetClientId,
}); // Note: this object shape is for testing only. Not representative of real signals.
},
clientId,
connected,
storage: mockStorage as IContainerStorageService,
baseSnapshot,
} satisfies Partial<IContainerContext>;
// Update the delta manager's last message which is used for validation during summarization.
mockContext.deltaManager.lastMessage = {
clientId: mockClientId,
type: MessageType.Operation,
sequenceNumber: 0,
timestamp: Date.now(),
minimumSequenceNumber: 0,
referenceSequenceNumber: 0,
clientSequenceNumber: 0,
contents: undefined,
};
return mockContext;
};
const mockProvideEntryPoint = async () => ({
myProp: "myValue",
});
describe("Container Runtime", () => {
describe("IdCompressor", () => {
it("finalizes idRange on attach", async () => {
const logger = new MockLogger();
const containerRuntime = await ContainerRuntime.loadRuntime2({
context: getMockContext({ logger }) as IContainerContext,
registry: new FluidDataStoreRegistry([]),
existing: false,
runtimeOptions: {
enableRuntimeIdCompressor: "on",
},
provideEntryPoint: mockProvideEntryPoint,
});
logger.clear();
const compressor = containerRuntime.idCompressor;
assert(compressor !== undefined);
compressor.generateCompressedId();
containerRuntime.createSummary();
const range = compressor.takeNextCreationRange();
assert.equal(
range.ids,
undefined,
"All Ids should have been finalized after calling createSummary()",
);
});
});
describe("Batching", () => {
it("Default flush mode", async () => {
const containerRuntime = await ContainerRuntime.loadRuntime2({
context: getMockContext() as IContainerContext,
registry: new FluidDataStoreRegistry([]),
existing: false,
runtimeOptions: {},
provideEntryPoint: mockProvideEntryPoint,
});
assert.strictEqual(containerRuntime.flushMode, FlushMode.TurnBased);
});
it("Override default flush mode using options", async () => {
const runtimeOptions: IContainerRuntimeOptionsInternal = {
flushMode: FlushMode.Immediate,
};
const containerRuntime = await ContainerRuntime.loadRuntime2({
context: getMockContext() as IContainerContext,
registry: new FluidDataStoreRegistry([]),
existing: false,
runtimeOptions,
provideEntryPoint: mockProvideEntryPoint,
});
assert.strictEqual(containerRuntime.flushMode, FlushMode.Immediate);
});
it("Throws UsageError and calls closeFn for invalid flushMode", async () => {
const containerErrors: ICriticalContainerError[] = [];
const context = {
...getMockContext(),
closeFn: (error?: ICriticalContainerError): void => {
if (error !== undefined) {
containerErrors.push(error);
}
},
};
// Cast through unknown to simulate a stale/invalid numeric flushMode value (e.g., the former FlushModeExperimental.Async = 2)
const invalidFlushMode = 2 as unknown as FlushMode;
await assert.rejects(
ContainerRuntime.loadRuntime2({
context: context as IContainerContext,
registry: new FluidDataStoreRegistry([]),
existing: false,
runtimeOptions: { flushMode: invalidFlushMode },
provideEntryPoint: mockProvideEntryPoint,
}),
(error: Error) => {
assert.ok(
error instanceof UsageError,
"Should throw a UsageError for invalid flushMode",
);
return true;
},
);
assert.strictEqual(
containerErrors.length,
1,
"closeFn should have been called with the error",
);
assert.ok(
containerErrors[0] instanceof UsageError,
"closeFn should have been called with a UsageError",
);
});
it("Process empty batch", async () => {
let batchBegin = 0;
let batchEnd = 0;
let callsToEnsure = 0;
const containerRuntime = await ContainerRuntime.loadRuntime2({
context: getMockContext({
settings: {
"Fluid.ContainerRuntime.enableBatchIdTracking": true,
},
}) as IContainerContext,
registry: new FluidDataStoreRegistry([]),
existing: false,
runtimeOptions: {},
provideEntryPoint: mockProvideEntryPoint,
});
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access
(containerRuntime as any).ensureNoDataModelChanges = (callback: () => void) => {
callback();
callsToEnsure++;
};
changeConnectionState(containerRuntime, false, mockClientId);
// Not connected, so nothing is submitted on flush - just queued in PendingStateManager
submitDataStoreOp(containerRuntime, "1", testDataStoreMessage, { emptyBatch: true });
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call
(containerRuntime as any).flush();
changeConnectionState(containerRuntime, true, mockClientId);
containerRuntime.on("batchBegin", () => batchBegin++);
containerRuntime.on("batchEnd", () => batchEnd++);
containerRuntime.process(
{
clientId: mockClientId,
sequenceNumber: 10,
clientSequenceNumber: 1,
type: MessageType.Operation,
contents: JSON.stringify({
type: "groupedBatch",
contents: [],
}),
} satisfies Partial<ISequencedDocumentMessage> as ISequencedDocumentMessage,
true,
);
assert.strictEqual(callsToEnsure, 1);
assert.strictEqual(batchBegin, 1);
assert.strictEqual(batchEnd, 1);
assert.strictEqual(containerRuntime.isDirty, false);
});
for (const enableBatchIdTracking of [true, undefined])
it("Replaying ops should resend in correct order, with batch ID if applicable", async () => {
const containerRuntime = (await ContainerRuntime.loadRuntime2({
context: getMockContext({
settings: {
"Fluid.ContainerRuntime.enableBatchIdTracking": enableBatchIdTracking, // batchId only stamped if true
},
}) as IContainerContext,
registry: new FluidDataStoreRegistry([]),
existing: false,
runtimeOptions: {},
provideEntryPoint: mockProvideEntryPoint,
})) as unknown as ContainerRuntime_WithPrivates;
stubChannelCollection(containerRuntime);
changeConnectionState(containerRuntime, false, mockClientId);
// Not connected, so nothing is submitted on flush - just queued in PendingStateManager
submitDataStoreOp(containerRuntime, "1", testDataStoreMessage);
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call
(containerRuntime as any).flush();
submitDataStoreOp(containerRuntime, "2", testDataStoreMessage);
changeConnectionState(containerRuntime, true, mockClientId);
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call
(containerRuntime as any).flush();
assert.strictEqual(submittedOps.length, 2);
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
assert.strictEqual(submittedOps[0].contents.address, "1");
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
assert.strictEqual(submittedOps[1].contents.address, "2");
function batchIdMatchesUnsentFormat(batchId?: string): boolean {
return (
// eslint-disable-next-line @typescript-eslint/prefer-optional-chain -- TODO: ADO#58523 Code owners should verify if this code change is safe and make it if so or update this comment otherwise
batchId !== undefined &&
batchId.length === "00000000-0000-0000-0000-000000000000_[-1]".length &&
batchId.endsWith("_[-1]")
);
}
if (enableBatchIdTracking === true) {
assert(
batchIdMatchesUnsentFormat(
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
submittedOps[0].metadata?.batchId as string | undefined,
),
"expected unsent batchId format (0)",
);
assert(
batchIdMatchesUnsentFormat(
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
submittedOps[1].metadata?.batchId as string | undefined,
),
"expected unsent batchId format (0)",
);
} else {
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
assert(submittedOps[0].metadata?.batchId === undefined, "Expected no batchId (0)");
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
assert(submittedOps[1].metadata?.batchId === undefined, "Expected no batchId (1)");
}
});
// NOTE: This test is examining a case that only occurs with an old Loader that doesn't tell ContainerRuntime when processing system ops.
// In other words, when the MockDeltaManager bumps its lastSequenceNumber, ContainerRuntime.process would be called in the current code, but not with legacy loader.
it("Inbound (non-runtime) op triggers flush due to refSeq changing", async () => {
const submittedBatches: {
messages: IBatchMessage[];
referenceSequenceNumber: number;
}[] = [];
const mockContext = getMockContext();
(mockContext as { submitBatchFn: IContainerContext["submitBatchFn"] }).submitBatchFn =
(messages: IBatchMessage[], referenceSequenceNumber: number = -1) => {
submittedOps.push(...messages); // Reusing submittedOps since submitFn won't be invoked due to submitBatchFn's presence
submittedBatches.push({ messages, referenceSequenceNumber });
return 999; // CSN not used in test asserts below
};
const containerRuntime = await ContainerRuntime.loadRuntime2({
context: mockContext as IContainerContext,
registry: new FluidDataStoreRegistry([]),
existing: false,
runtimeOptions: {},
provideEntryPoint: mockProvideEntryPoint,
});
// Submit the first message
submitDataStoreOp(containerRuntime, "1", testDataStoreMessage);
assert.strictEqual(submittedOps.length, 0, "No ops submitted yet");
// Bump lastSequenceNumber and trigger the "op" event artificially to simulate processing a non-runtime op
// This will trigger a flush, which allows us to safely submit more ops next
const mockDeltaManager = mockContext.deltaManager as MockDeltaManager;
++mockDeltaManager.lastSequenceNumber;
mockDeltaManager.emit("op", {
clientId: mockClientId,
sequenceNumber: mockDeltaManager.lastSequenceNumber,
clientSequenceNumber: 1,
type: MessageType.ClientJoin,
contents: "test content",
});
assert.equal(submittedOps.length, 1, "Submitted op count wrong after first op");
// Submit the second message
submitDataStoreOp(containerRuntime, "2", {
type: "op",
content: { address: "test-address", contents: "test-contents2" },
});
assert.equal(
submittedOps.length,
1,
"Second op not yet submitted (scheduled for next microtask)",
);
// Wait for the next tick for the second message to be flushed
await Promise.resolve();
// Validate that the messages were submitted
assert.equal(submittedOps.length, 2, "Two messages should be submitted");
assert.deepEqual(
submittedBatches,
[
{ messages: [submittedOps[0]], referenceSequenceNumber: 0 }, // The first op
{ messages: [submittedOps[1]], referenceSequenceNumber: 1 }, // The second op
],
"Two batches should be submitted with different refSeq",
);
});
it("IDs generated before a lost range are finalized after reconnect", async () => {
// Start out disconnected since step 1 is to generate IDs before reconnect
const connected = false;
const mockContext = getMockContext({ connected }) as IContainerContext;
const mockDeltaManager = mockContext.deltaManager as MockDeltaManager;
const containerRuntime = await ContainerRuntime.loadRuntime2({
context: mockContext,
registry: new FluidDataStoreRegistry([]),
existing: false,
runtimeOptions: { enableRuntimeIdCompressor: "on" },
provideEntryPoint: mockProvideEntryPoint,
});
const compressor = containerRuntime.idCompressor;
assert(compressor !== undefined, "Expected idCompressor to be defined");
// Generate an ID while disconnected.
const id1 = compressor.generateCompressedId();
// Simulate the range being taken but lost (e.g. nack'd / disconnect before submit).
compressor.takeNextCreationRange();
// Re-connect – replayPendingStates releases unfinalized ranges
// (no IdAllocation op is submitted at this point).
changeConnectionState(containerRuntime, true, mockClientId);
// Simulate a remote op arriving before we submit anything else.
// Bump refSeq and continue execution at the end of the microtask queue.
// This is how Inbound Queue works, and this is makes sure we get coverage of ref seq coherency in this test.
++mockDeltaManager.lastSequenceNumber;
await Promise.resolve();
// Generate another ID and submit a data store op referencing it.
// This triggers submitIdAllocationOpIfNeeded → takeNextCreationRange.
// Because the unfinalized range was released during replay, both IDs
// are included in the resulting allocation range.
const id2 = compressor.generateCompressedId();
submitDataStoreOp(containerRuntime, "someDS", genTestDataStoreMessage({ id: id2 }));
// Let the Outbox flush so we can check submittedOps length
await Promise.resolve();
assert.strictEqual(submittedOps.length, 2, "Expected 1 ID Allocation + 1 data op");
// Simulate processing the ID Allocation ack — finalize the range.
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-unsafe-member-access
compressor.finalizeCreationRange(submittedOps[0].contents);
// Both IDs should now be finalized (positive final IDs in op space).
// Without releaseUnfinalizedCreationRange, id1 would remain a local-only
// ID (negative) that could never be shared with other clients.
const id1OpSpace = compressor.normalizeToOpSpace(id1);
const id2OpSpace = compressor.normalizeToOpSpace(id2);
assert(id1OpSpace >= 0, "id1 should be finalized after allocation range is sequenced");
assert(id2OpSpace >= 0, "id2 should be finalized after allocation range is sequenced");
});
});
const expectedOrderSequentiallyErrorMessage = "orderSequentially callback exception";
describe("orderSequentially (rollback not enabled)", () => {
for (const flushMode of [FlushMode.TurnBased, FlushMode.Immediate]) {
const fakeClientId = "fakeClientId";
describe(`orderSequentially with flush mode: ${FlushMode[flushMode]}`, () => {
let containerRuntime: ContainerRuntime_WithPrivates;
let mockContext: Partial<IContainerContext>;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const submittedOpsMetadata: any[] = [];
const containerErrors: ICriticalContainerError[] = [];
const getMockContextForOrderSequentially = (): Partial<IContainerContext> => {
return {
attachState: AttachState.Attached,
deltaManager: new MockDeltaManager(),
audience: new MockAudience(),
quorum: new MockQuorumClients(),
taggedLogger: new MockLogger(),
supportedFeatures: new Map([["referenceSequenceNumbers", true]]),
clientDetails: { capabilities: { interactive: true } },
closeFn: (error?: ICriticalContainerError): void => {
if (error !== undefined) {
containerErrors.push(error);
}
},
updateDirtyContainerState: (_dirty: boolean) => {},
submitFn: (
_type: MessageType,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
contents: any,
_batch: boolean,
appData?: unknown,
) => {
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
if (contents.type === "groupedBatch") {
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
for (const subMessage of contents.contents) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
submittedOpsMetadata.push(subMessage.metadata);
}
} else {
submittedOpsMetadata.push(appData);
}
return opFakeSequenceNumber++;
},
connected: true,
clientId: fakeClientId,
getLoadedFromVersion: () => undefined,
};
};
const getFirstContainerError = (): ICriticalContainerError => {
assert.ok(containerErrors.length > 0, "Container should have errors");
return containerErrors[0];
};
beforeEach(async () => {
mockContext = getMockContextForOrderSequentially();
const runtimeOptions: IContainerRuntimeOptionsInternal = {
summaryOptions: {
summaryConfigOverrides: {
state: "disabled",
},
},
flushMode,
};
containerRuntime = (await ContainerRuntime.loadRuntime2({
context: mockContext as IContainerContext,
registry: new FluidDataStoreRegistry([]),
existing: false,
runtimeOptions,
provideEntryPoint: mockProvideEntryPoint,
})) as unknown as ContainerRuntime_WithPrivates;
containerErrors.length = 0;
submittedOpsMetadata.length = 0;
});
it("Can't call flush() inside orderSequentially's callback", () => {
assert.throws(() =>
containerRuntime.orderSequentially(() => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call
(containerRuntime as any).flush();
}),
);
const error = getFirstContainerError();
assert(isFluidError(error));
assert.strictEqual(error.errorType, ContainerErrorTypes.genericError);
assert.strictEqual(error.message, "0x24c");
assert.strictEqual(error.getTelemetryProperties().orderSequentiallyCalls, 1);
});
it("Can't call flush() inside orderSequentially's callback when nested", () => {
assert.throws(() =>
containerRuntime.orderSequentially(() =>
containerRuntime.orderSequentially(() => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call
(containerRuntime as any).flush();
}),
),
);
const error = getFirstContainerError();
assert(isFluidError(error));
assert.strictEqual(error.errorType, ContainerErrorTypes.genericError);
assert.strictEqual(error.message, "0x24c");
assert.strictEqual(error.getTelemetryProperties().orderSequentiallyCalls, 2);
});
it("Can't call flush() inside orderSequentially's callback when nested ignoring exceptions", () => {
containerRuntime.orderSequentially(() => {
try {
containerRuntime.orderSequentially(() => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call
(containerRuntime as any).flush();
});
} catch {
// ignore
}
});
const error = getFirstContainerError();
assert(isFluidError(error));
assert.strictEqual(error.errorType, ContainerErrorTypes.genericError);
assert.strictEqual(error.message, "0x24c");
assert.strictEqual(error.getTelemetryProperties().orderSequentiallyCalls, 2);
});
it("Errors propagate to the container", () => {
assert.throws(() =>
containerRuntime.orderSequentially(() => {
throw new Error("Any");
}),
);
const error = getFirstContainerError();
assert(isFluidError(error));
assert.strictEqual(error.errorType, ContainerErrorTypes.genericError);
assert.strictEqual(error.message, `${expectedOrderSequentiallyErrorMessage}: Any`);
assert.strictEqual(error.getTelemetryProperties().orderSequentiallyCalls, 1);
});
it("Errors propagate to the container when nested", () => {
assert.throws(() =>
containerRuntime.orderSequentially(() =>
containerRuntime.orderSequentially(() => {
throw new Error("Any");
}),
),
);
const error = getFirstContainerError();
assert(isFluidError(error));
assert.strictEqual(error.errorType, ContainerErrorTypes.genericError);
assert.strictEqual(error.message, `${expectedOrderSequentiallyErrorMessage}: Any`);
assert.strictEqual(error.getTelemetryProperties().orderSequentiallyCalls, 2);
});
it("Batching property set properly", () => {
containerRuntime.orderSequentially(() => {
submitDataStoreOp(containerRuntime, "1", testDataStoreMessage);
submitDataStoreOp(containerRuntime, "2", testDataStoreMessage);
submitDataStoreOp(containerRuntime, "3", testDataStoreMessage);
});
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call
(containerRuntime as any).flush();
assert.strictEqual(submittedOpsMetadata.length, 3, "3 messages should be sent");
assert.strictEqual(
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
submittedOpsMetadata[0].batch,
true,
"first message should be the batch start",
);
assert.strictEqual(
submittedOpsMetadata[1],
undefined,
"second message should not hold batch info",
);
assert.strictEqual(
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
submittedOpsMetadata[2].batch,
false,
"third message should be the batch end",
);
});
it("Resubmitting batch preserves original batches", async () => {
stubChannelCollection(containerRuntime);
changeConnectionState(containerRuntime, false, fakeClientId);
containerRuntime.orderSequentially(() => {
submitDataStoreOp(containerRuntime, "1", testDataStoreMessage);
submitDataStoreOp(containerRuntime, "2", testDataStoreMessage);
submitDataStoreOp(containerRuntime, "3", testDataStoreMessage);
});
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call
(containerRuntime as any).flush();
containerRuntime.orderSequentially(() => {
submitDataStoreOp(containerRuntime, "4", testDataStoreMessage);
submitDataStoreOp(containerRuntime, "5", testDataStoreMessage);
submitDataStoreOp(containerRuntime, "6", testDataStoreMessage);
});
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call
(containerRuntime as any).flush();
assert.strictEqual(submittedOpsMetadata.length, 0, "no messages should be sent");
changeConnectionState(containerRuntime, true, fakeClientId);
assert.strictEqual(submittedOpsMetadata.length, 6, "6 messages should be sent");
const expectedBatchMetadata = [
{ batch: true },
undefined,
{ batch: false },
{ batch: true },
undefined,
{ batch: false },
];
assert.deepStrictEqual(
submittedOpsMetadata,
expectedBatchMetadata,
"batch metadata does not match",
);
});
});
}
});
describe("orderSequentially with rollback", () => {
for (const flushMode of [FlushMode.TurnBased, FlushMode.Immediate]) {
describe(`orderSequentially with flush mode: ${FlushMode[flushMode]}`, () => {
let containerRuntime: ContainerRuntime_WithPrivates;
const containerErrors: ICriticalContainerError[] = [];
let submittedOpsCount: number = 0;
const getMockContextForOrderSequentially = (): Partial<IContainerContext> => ({
attachState: AttachState.Attached,
connected: true,
clientId: "client-id",
supportedFeatures: new Map([["referenceSequenceNumbers", true]]),
deltaManager: new MockDeltaManager(),
audience: new MockAudience(),
quorum: new MockQuorumClients(),
taggedLogger: mixinMonitoringContext(
new MockLogger(),
configProvider({
"Fluid.ContainerRuntime.EnableRollback": true,
}),
) as unknown as MockLogger,
clientDetails: { capabilities: { interactive: true } },
closeFn: (error?: ICriticalContainerError): void => {
if (error !== undefined) {
containerErrors.push(error);
}
},
submitFn: (...args) => {
return ++submittedOpsCount; // clientSequenceNumber
},
updateDirtyContainerState: (dirty: boolean) => {},
getLoadedFromVersion: () => undefined,
});
beforeEach(async () => {
const runtimeOptions: IContainerRuntimeOptionsInternal = {
summaryOptions: {
summaryConfigOverrides: { state: "disabled" },
},
flushMode,
};
containerRuntime = (await ContainerRuntime.loadRuntime2({
context: getMockContextForOrderSequentially() as IContainerContext,
registry: new FluidDataStoreRegistry([]),
existing: false,
runtimeOptions,
provideEntryPoint: mockProvideEntryPoint,
})) as unknown as ContainerRuntime_WithPrivates;
containerErrors.length = 0;
submittedOpsCount = 0;
});
it("No errors propagate to the container on rollback", () => {
assert.throws(() =>
containerRuntime.orderSequentially(() => {
throw new Error("Any");
}),
);
assert.equal(containerRuntime.inStagingMode, false, "Still in Staging Mode");
assert.equal(containerRuntime.isDirty, false, "Dirty after rollback");
assert.strictEqual(containerErrors.length, 0);
});
it("No errors on successful callback with rollback set", () => {
containerRuntime.orderSequentially(() => {});
assert.equal(containerRuntime.inStagingMode, false, "Still in Staging Mode");
assert.strictEqual(containerErrors.length, 0);
});
it("orderSequentially while in StagingMode works", async () => {
stubChannelCollection(containerRuntime);
const stageControls = containerRuntime.enterStagingMode();
containerRuntime.orderSequentially(() => {
submitDataStoreOp(containerRuntime, "1", testDataStoreMessage);
});
assert.strictEqual(
submittedOpsCount,
0,
"No ops should be submitted in Staging Mode",
);
stageControls.commitChanges();
assert.strictEqual(
submittedOpsCount,
1,