-
Notifications
You must be signed in to change notification settings - Fork 567
Expand file tree
/
Copy pathcell.ts
More file actions
376 lines (332 loc) · 10 KB
/
cell.ts
File metadata and controls
376 lines (332 loc) · 10 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
/*!
* Copyright (c) Microsoft Corporation and contributors. All rights reserved.
* Licensed under the MIT License.
*/
import { assert, unreachableCase } from "@fluidframework/core-utils/internal";
import type {
IChannelAttributes,
IFluidDataStoreRuntime,
Serializable,
IChannelStorageService,
} from "@fluidframework/datastore-definitions/internal";
import { MessageType } from "@fluidframework/driver-definitions/internal";
import { readAndParse } from "@fluidframework/driver-utils/internal";
import type {
ISummaryTreeWithStats,
AttributionKey,
IRuntimeMessageCollection,
ISequencedMessageEnvelope,
IRuntimeMessagesContent,
} from "@fluidframework/runtime-definitions/internal";
import type { IFluidSerializer } from "@fluidframework/shared-object-base/internal";
import {
SharedObject,
createSingleBlobSummary,
} from "@fluidframework/shared-object-base/internal";
import type {
ICellLocalOpMetadata,
ICellOptions,
ISharedCell,
ISharedCellEvents,
} from "./interfaces.js";
/**
* Description of a cell delta operation
*/
type ICellOperation = ISetCellOperation | IDeleteCellOperation;
interface ISetCellOperation {
type: "setCell";
value: ICellValue;
}
interface IDeleteCellOperation {
type: "deleteCell";
}
interface ICellValue {
/**
* The actual value contained in the `Cell`, which needs to be wrapped to handle `undefined`.
*/
value: unknown;
/**
* The attribution key contained in the `Cell`.
*/
attribution?: AttributionKey;
}
const snapshotFileName = "header";
/**
* {@inheritDoc ISharedCell}
*/
// TODO: use `unknown` instead (breaking change).
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export class SharedCell<T = any>
extends SharedObject<ISharedCellEvents<T>>
implements ISharedCell<T>
{
/**
* The data held by this cell.
*/
private data: Serializable<T> | undefined;
/**
* This is used to assign a unique id to outgoing messages. It is used to track messages until
* they are ack'd.
*/
private messageId: number = -1;
/**
* This keeps track of the messageId of messages that have been ack'd. It is updated every time
* we a message is ack'd with it's messageId.
*/
private messageIdObserved: number = -1;
private readonly pendingMessageIds: number[] = [];
private attribution: AttributionKey | undefined;
private readonly options: ICellOptions | undefined;
/**
* Constructs a new `SharedCell`.
* If the object is non-local an id and service interfaces will be provided.
*
* @param runtime - The data store runtime to which the `SharedCell` belongs.
* @param id - Unique identifier for the `SharedCell`.
*/
// eslint-disable-next-line @typescript-eslint/explicit-member-accessibility
constructor(id: string, runtime: IFluidDataStoreRuntime, attributes: IChannelAttributes) {
super(id, runtime, attributes, "fluid_cell_");
this.options = runtime.options as ICellOptions;
}
/**
* {@inheritDoc ISharedCell.get}
*/
public get(): Serializable<T> | undefined {
return this.data;
}
/**
* {@inheritDoc ISharedCell.set}
*/
public set(value: Serializable<T>): void {
// Set the value locally.
const previousValue = this.setCore(value);
this.setAttribution();
// If we are not attached, don't submit the op.
if (!this.isAttached()) {
return;
}
const operationValue: ICellValue = {
value,
};
const op: ISetCellOperation = {
type: "setCell",
value: operationValue,
};
this.submitCellMessage(op, previousValue);
}
/**
* {@inheritDoc ISharedCell.delete}
*/
public delete(): void {
// Delete the value locally.
const previousValue = this.deleteCore();
this.setAttribution();
// If we are not attached, don't submit the op.
if (!this.isAttached()) {
return;
}
const op: IDeleteCellOperation = {
type: "deleteCell",
};
this.submitCellMessage(op, previousValue);
}
/**
* {@inheritDoc ISharedCell.empty}
*/
public empty(): boolean {
return this.data === undefined;
}
/**
* {@inheritDoc ISharedCell.getAttribution}
*/
public getAttribution(): AttributionKey | undefined {
return this.attribution;
}
/**
* Set the Op-based attribution through the SequencedDocumentMessage,
* or set the local/detached attribution.
*/
private setAttribution(messageEnvelope?: ISequencedMessageEnvelope): void {
if (this.options?.attribution?.track ?? false) {
this.attribution = messageEnvelope
? { type: "op", seq: messageEnvelope.sequenceNumber }
: this.isAttached()
? { type: "local" }
: { type: "detached", id: 0 };
}
}
/**
* Creates a summary for the Cell.
*
* @returns The summary of the current state of the Cell.
*/
protected summarizeCore(serializer: IFluidSerializer): ISummaryTreeWithStats {
const content: ICellValue =
this.attribution?.type === "local"
? { value: this.data, attribution: undefined }
: { value: this.data, attribution: this.attribution };
return createSingleBlobSummary(
snapshotFileName,
serializer.stringify(content, this.handle),
);
}
/**
* {@inheritDoc @fluidframework/shared-object-base#SharedObject.loadCore}
*/
protected async loadCore(storage: IChannelStorageService): Promise<void> {
const content = await readAndParse<ICellValue>(storage, snapshotFileName);
this.data = this.serializer.decode(content.value) as Serializable<T>;
this.attribution = content.attribution;
}
/**
* Initialize a local instance of cell.
*/
protected initializeLocalCore(): void {
this.data = undefined;
}
/**
* Call back on disconnect.
*/
protected onDisconnect(): void {}
/**
* Apply inner op.
*
* @param content - ICellOperation content
*/
private applyInnerOp(content: ICellOperation): Serializable<T> | undefined {
switch (content.type) {
case "setCell": {
return this.setCore(content.value.value as Serializable<T>);
}
case "deleteCell": {
return this.deleteCore();
}
default: {
throw new Error("Unknown operation");
}
}
}
/**
* {@inheritDoc @fluidframework/shared-object-base#SharedObject.processMessagesCore}
*/
protected 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 {
const cellOpMetadata = messageContent.localOpMetadata as ICellLocalOpMetadata;
if (this.messageId !== this.messageIdObserved) {
// We are waiting for an ACK on our change to this cell - we will ignore all messages until we get it.
if (local) {
const messageIdReceived = cellOpMetadata.pendingMessageId;
assert(
messageIdReceived !== undefined && messageIdReceived <= this.messageId,
0x00c /* "messageId is incorrect from from the local client's ACK" */,
);
assert(
this.pendingMessageIds !== undefined &&
this.pendingMessageIds[0] === cellOpMetadata.pendingMessageId,
0x471 /* Unexpected pending message received */,
);
this.pendingMessageIds.shift();
// We got an ACK. Update messageIdObserved.
this.messageIdObserved = cellOpMetadata.pendingMessageId;
// update the attributor
this.setAttribution(messageEnvelope);
}
return;
}
// eslint-disable-next-line @typescript-eslint/no-unsafe-enum-comparison
if (messageEnvelope.type === MessageType.Operation && !local) {
const op = messageContent.contents as ICellOperation;
// update the attributor
this.setAttribution(messageEnvelope);
this.applyInnerOp(op);
}
}
private setCore(value: Serializable<T>): Serializable<T> | undefined {
const previousLocalValue = this.get();
this.data = value;
this.emit("valueChanged", value);
return previousLocalValue;
}
private deleteCore(): Serializable<T> | undefined {
const previousLocalValue = this.get();
this.data = undefined;
this.emit("delete");
return previousLocalValue;
}
private createLocalOpMetadata(
op: ICellOperation,
previousValue?: Serializable<T>,
): ICellLocalOpMetadata {
const pendingMessageId = ++this.messageId;
this.pendingMessageIds.push(pendingMessageId);
const localMetadata: ICellLocalOpMetadata = {
pendingMessageId,
previousValue,
};
return localMetadata;
}
/**
* {@inheritDoc @fluidframework/shared-object-base#SharedObjectCore.applyStashedOp}
*/
protected applyStashedOp(content: unknown): void {
const cellContent = content as ICellOperation;
switch (cellContent.type) {
case "deleteCell": {
this.delete();
break;
}
case "setCell": {
this.set(cellContent.value.value as Serializable<T>);
break;
}
default: {
unreachableCase(cellContent);
}
}
}
/**
* Rollback a local op.
*
* @param content - The operation to rollback.
* @param localOpMetadata - The local metadata associated with the op.
*/
// TODO: use `unknown` instead (breaking change).
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
protected rollback(content: any, localOpMetadata: unknown): void {
const cellOpMetadata = localOpMetadata as ICellLocalOpMetadata;
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
if (content.type === "setCell" || content.type === "deleteCell") {
if (cellOpMetadata.previousValue === undefined) {
this.deleteCore();
} else {
this.setCore(cellOpMetadata.previousValue as Serializable<T>);
}
const lastPendingMessageId = this.pendingMessageIds.pop();
if (lastPendingMessageId !== cellOpMetadata.pendingMessageId) {
throw new Error("Rollback op does not match last pending");
}
} else {
throw new Error("Unsupported op for rollback");
}
}
/**
* Submit a cell message to remote clients.
*
* @param op - The cell message.
* @param previousValue - The value of the cell before this op.
*/
private submitCellMessage(op: ICellOperation, previousValue?: Serializable<T>): void {
const localMetadata = this.createLocalOpMetadata(op, previousValue);
this.submitLocalMessage(op, localMetadata);
}
}