@fluidframework/matrix 2.0.0-internal.2.4.0 → 2.0.0-internal.3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/matrix.d.ts CHANGED
@@ -82,6 +82,7 @@ export declare class SharedMatrix<T = any> extends SharedObject implements IMatr
82
82
  protected submitLocalMessage(message: any, localOpMetadata?: any): void;
83
83
  protected didAttach(): void;
84
84
  protected onConnect(): void;
85
+ private rebasePosition;
85
86
  protected reSubmitCore(content: any, localOpMetadata: unknown): void;
86
87
  protected onDisconnect(): void;
87
88
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"matrix.d.ts","sourceRoot":"","sources":["../src/matrix.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAGH,OAAO,EAAE,yBAAyB,EAAE,MAAM,sCAAsC,CAAC;AACjF,OAAO,EACH,sBAAsB,EACtB,sBAAsB,EACtB,YAAY,EACZ,kBAAkB,EACrB,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EACH,gBAAgB,EAGhB,YAAY,EACZ,iBAAiB,EACpB,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EAAE,qBAAqB,EAAE,MAAM,qCAAqC,CAAC;AAE5E,OAAO,EACH,eAAe,EACf,eAAe,EACf,aAAa,EACb,aAAa,EAChB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAkD,QAAQ,EAAE,MAAM,4BAA4B,CAAC;AAItG,OAAO,EAAE,mBAAmB,EAAE,MAAM,WAAW,CAAC;AAIhD,OAAO,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAwBxC;;;GAGG;AACH,oBAAY,UAAU,CAAC,CAAC,IAAI,YAAY,CAAC,OAAO,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC,GAAG,SAAS,CAAC;AAEvE;;;;;;;;;;;GAWG;AACH,qBAAa,YAAY,CAAC,CAAC,GAAG,GAAG,CAC7B,SAAQ,YACR,YAAW,eAAe,CAAC,UAAU,CA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Q,CAAC,oBAAoB,CAKnC;IAEF,OAAO,CAAC,QAAQ,CAAC,oBAAoB,CAKnC;IAEF;;;;;;;OAOG;IACH,OAAO,CAAC,oBAAoB;IAerB,QAAQ;IAkBf;;OAEG;IACH,SAAS,CAAC,cAAc,CAAC,OAAO,EAAE,GAAG,GAAG,OAAO;CAoDlD"}
package/dist/matrix.js CHANGED
@@ -332,6 +332,14 @@ class SharedMatrix extends shared_object_base_1.SharedObject {
332
332
  this.rows.startOrUpdateCollaboration(this.runtime.clientId);
333
333
  this.cols.startOrUpdateCollaboration(this.runtime.clientId);
334
334
  }
335
+ rebasePosition(client, pos, referenceSequenceNumber, localSeq) {
336
+ const { clientId } = client.getCollabWindow();
337
+ const { segment, offset } = client.getContainingSegment(pos, { referenceSequenceNumber, clientId: client.getLongClientId(clientId) }, localSeq);
338
+ if (segment === undefined || offset === undefined) {
339
+ return;
340
+ }
341
+ return client.findReconnectionPosition(segment, localSeq) + offset;
342
+ }
335
343
  reSubmitCore(content, localOpMetadata) {
336
344
  switch (content.target) {
337
345
  case "cols" /* cols */:
@@ -348,8 +356,8 @@ class SharedMatrix extends shared_object_base_1.SharedObject {
348
356
  // to skip resubmitting this op since it is possible the row/col handle has been recycled
349
357
  // and now refers to a different position than when this op was originally submitted.
350
358
  if (this.isLatestPendingWrite(rowHandle, colHandle, localSeq)) {
351
- const row = this.rows.rebasePositionWithoutSegmentSlide(setOp.row, rowsRefSeq, localSeq);
352
- const col = this.cols.rebasePositionWithoutSegmentSlide(setOp.col, colsRefSeq, localSeq);
359
+ const row = this.rebasePosition(this.rows, setOp.row, rowsRefSeq, localSeq);
360
+ const col = this.rebasePosition(this.cols, setOp.col, colsRefSeq, localSeq);
353
361
  if (row !== undefined && col !== undefined && row >= 0 && col >= 0) {
354
362
  this.sendSetCellOp(row, col, setOp.value, rowHandle, colHandle, localSeq, rowsRefSeq, colsRefSeq);
355
363
  }
@@ -433,9 +441,7 @@ class SharedMatrix extends shared_object_base_1.SharedObject {
433
441
  // Note while we're awaiting the ACK for a local set, it's possible for the row/col to be
434
442
  // locally removed and the row/col handles recycled. If this happens, the pendingLocalSeq will
435
443
  // be 'undefined' or > 'localSeq'.
436
- (0, common_utils_1.assert)(!(pendingLocalSeq < localSeq),
437
- // eslint-disable-next-line max-len
438
- 0x023 /* "The 'localSeq' of pending write (if any) must be <= the localSeq of the currently processed op." */);
444
+ (0, common_utils_1.assert)(!(pendingLocalSeq < localSeq), 0x023 /* "The 'localSeq' of pending write (if any) must be <= the localSeq of the currently processed op." */);
439
445
  // If this is the most recent write to the cell by the local client, the stored localSeq
440
446
  // will be an exact match for the given 'localSeq'.
441
447
  return pendingLocalSeq === localSeq;
@@ -1 +1 @@
1
- {"version":3,"file":"matrix.js","sourceRoot":"","sources":["../src/matrix.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;AAEH,+DAAsD;AAQtD,2EAM4C;AAE5C,iEAA2F;AAO3F,2DAAsG;AACtG,+BAAiC;AACjC,2DAA4E;AAC5E,mDAAgD;AAChD,uCAAgD;AAChD,+CAAsD;AACtD,mDAAkD;AAClD,mCAAsC;AAEtC,iDAAoD;AA6BpD;;;;;;;;;;;GAWG;AACH,MAAa,YACT,SAAQ,iCAAY;IAcpB,YAAY,OAA+B,EAAS,EAAU,EAAE,UAA8B;QAC1F,KAAK,CAAC,EAAE,EAAE,OAAO,EAAE,UAAU,EAAE,eAAe,CAAC,CAAC;QADA,OAAE,GAAF,EAAE,CAAQ;QAV7C,cAAS,GAAG,IAAI,GAAG,EAAkC,CAAC;QAO/D,UAAK,GAAG,IAAI,6BAAa,EAAiB,CAAC,CAAK,sBAAsB;QACtE,YAAO,GAAG,IAAI,6BAAa,EAAU,CAAC,CAAU,yBAAyB;QAohBjF,sFAAsF;QACrE,eAAU,GAAG,CAAC,QAAgB,EAAE,YAAoB,EAAE,aAAqB,EAAE,EAAE;YAC5F,KAAK,MAAM,QAAQ,IAAI,IAAI,CAAC,SAAS,EAAE;gBACnC,QAAQ,CAAC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,CAAC,UAAU,CAAC;YAC1D,IAAI,IAAI,CAAC,IAAI,KAAK,SAAS,EAAE;gBACzB,IAAI,QAAQ,GAAG,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,SAAS,EAAE,SAAS,CAAC,CAAC;gBACxD,IAAI,QAAQ,KAAK,IAAI,EAAE;oBACnB,QAAQ,GAAG,SAAS,CAAC;iBACxB;gBAED,IAAI,CAAC,IAAI,CAAC,OAAO,CACb,SAAS,EACT,SAAS,EACT,QAAQ,CAAC,CAAC;aACjB;YAED,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,SAAS,EAAE,SAAS,EAAE,KAAK,CAAC,KAAK,CAAC,CAAC;YACtD,MAAM,QAAQ,GAAG,IAAI,CAAC,YAAY,EAAE,CAAC;YACrC,MAAM,QAAQ,GAAmB;gBAC7B,SAAS;gBACT,SAAS;gBACT,QAAQ;gBACR,UAAU;gBACV,UAAU;aACb,CAAC;YAEF,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,SAAS,EAAE,SAAS,EAAE,QAAQ,CAAC,CAAC;YACrD,OAAO,QAAQ,CAAC;SACnB;IACL,CAAC;CACJ;AA9pBD,oCA8pBC","sourcesContent":["/*!\n * Copyright (c) Microsoft Corporation and contributors. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { assert } from \"@fluidframework/common-utils\";\nimport { ISequencedDocumentMessage } from \"@fluidframework/protocol-definitions\";\nimport {\n IFluidDataStoreRuntime,\n IChannelStorageService,\n Serializable,\n IChannelAttributes,\n} from \"@fluidframework/datastore-definitions\";\nimport {\n IFluidSerializer,\n makeHandlesSerializable,\n parseHandles,\n SharedObject,\n SummarySerializer,\n} from \"@fluidframework/shared-object-base\";\nimport { ISummaryTreeWithStats } from \"@fluidframework/runtime-definitions\";\nimport { ObjectStoragePartition, SummaryTreeBuilder } from \"@fluidframework/runtime-utils\";\nimport {\n IMatrixProducer,\n IMatrixConsumer,\n IMatrixReader,\n IMatrixWriter,\n} from \"@tiny-calc/nano\";\nimport { MergeTreeDeltaType, IMergeTreeOp, SegmentGroup, ISegment } from \"@fluidframework/merge-tree\";\nimport { MatrixOp } from \"./ops\";\nimport { PermutationVector, PermutationSegment } from \"./permutationvector\";\nimport { SparseArray2D } from \"./sparsearray2d\";\nimport { SharedMatrixFactory } from \"./runtime\";\nimport { Handle, isHandleValid } from \"./handletable\";\nimport { deserializeBlob } from \"./serialization\";\nimport { ensureRange } from \"./range\";\nimport { IUndoConsumer } from \"./types\";\nimport { MatrixUndoProvider } from \"./undoprovider\";\n\nconst enum SnapshotPath {\n rows = \"rows\",\n cols = \"cols\",\n cells = \"cells\",\n}\n\ninterface ISetOp<T> {\n type: MatrixOp.set;\n row: number;\n col: number;\n value: MatrixItem<T>;\n}\n\ninterface ISetOpMetadata {\n rowHandle: Handle;\n colHandle: Handle;\n localSeq: number;\n rowsRefSeq: number;\n colsRefSeq: number;\n}\n\n/**\n * A matrix cell value may be undefined (indicating an empty cell) or any serializable type,\n * excluding null. (However, nulls may be embedded inside objects and arrays.)\n */\nexport type MatrixItem<T> = Serializable<Exclude<T, null>> | undefined;\n\n/**\n * A SharedMatrix holds a rectangular 2D array of values. Supported operations\n * include setting values and inserting/removing rows and columns.\n *\n * Matrix values may be any Fluid serializable type, which is the set of JSON\n * serializable types extended to include IFluidHandles.\n *\n * Fluid's SharedMatrix implementation works equally well for dense and sparse\n * matrix data and physically stores data in Z-order to leverage CPU caches and\n * prefetching when reading in either row or column major order. (See README.md\n * for more details.)\n */\nexport class SharedMatrix<T = any>\n extends SharedObject\n implements IMatrixProducer<MatrixItem<T>>,\n IMatrixReader<MatrixItem<T>>,\n IMatrixWriter<MatrixItem<T>> {\n private readonly consumers = new Set<IMatrixConsumer<MatrixItem<T>>>();\n\n public static getFactory() { return new SharedMatrixFactory(); }\n\n private readonly rows: PermutationVector; // Map logical row to storage handle (if any)\n private readonly cols: PermutationVector; // Map logical col to storage handle (if any)\n\n private cells = new SparseArray2D<MatrixItem<T>>(); // Stores cell values.\n private pending = new SparseArray2D<number>(); // Tracks pending writes.\n\n constructor(runtime: IFluidDataStoreRuntime, public id: string, attributes: IChannelAttributes) {\n super(id, runtime, attributes, \"fluid_matrix_\");\n\n this.rows = new PermutationVector(\n SnapshotPath.rows,\n this.logger,\n runtime,\n this.onRowDelta,\n this.onRowHandlesRecycled);\n\n this.cols = new PermutationVector(\n SnapshotPath.cols,\n this.logger,\n runtime,\n this.onColDelta,\n this.onColHandlesRecycled);\n }\n\n private undo?: MatrixUndoProvider<T>;\n\n /**\n * Subscribes the given IUndoConsumer to the matrix.\n */\n public openUndo(consumer: IUndoConsumer) {\n assert(this.undo === undefined,\n 0x019 /* \"SharedMatrix.openUndo() supports at most a single IUndoConsumer.\" */);\n\n this.undo = new MatrixUndoProvider(consumer, this, this.rows, this.cols);\n }\n\n // TODO: closeUndo()?\n\n private get rowHandles() { return this.rows.handleCache; }\n private get colHandles() { return this.cols.handleCache; }\n\n /**\n * {@inheritDoc @fluidframework/datastore-definitions#IChannelFactory.create}\n */\n public static create<T>(runtime: IFluidDataStoreRuntime, id?: string) {\n return runtime.createChannel(id, SharedMatrixFactory.Type) as SharedMatrix<T>;\n }\n\n // #region IMatrixProducer\n\n openMatrix(\n consumer: IMatrixConsumer<MatrixItem<T>>,\n ): IMatrixReader<MatrixItem<T>> {\n this.consumers.add(consumer);\n return this;\n }\n\n closeMatrix(consumer: IMatrixConsumer<MatrixItem<T>>): void {\n this.consumers.delete(consumer);\n }\n\n // #endregion IMatrixProducer\n\n // #region IMatrixReader\n\n public get rowCount() { return this.rows.getLength(); }\n public get colCount() { return this.cols.getLength(); }\n\n public getCell(row: number, col: number): MatrixItem<T> {\n // Perf: When possible, bounds checking is performed inside the implementation for\n // 'getHandle()' so that it can be elided in the case of a cache hit. This\n // yields an ~40% improvement in the case of a cache hit (node v12 x64)\n\n // Map the logical (row, col) to associated storage handles.\n const rowHandle = this.rowHandles.getHandle(row);\n if (isHandleValid(rowHandle)) {\n const colHandle = this.colHandles.getHandle(col);\n if (isHandleValid(colHandle)) {\n return this.cells.getCell(rowHandle, colHandle);\n }\n } else {\n // If we early exit because the given rowHandle is unallocated, we still need to\n // bounds-check the 'col' parameter.\n ensureRange(col, this.cols.getLength());\n }\n\n return undefined;\n }\n\n public get matrixProducer(): IMatrixProducer<MatrixItem<T>> { return this; }\n\n // #endregion IMatrixReader\n\n public setCell(row: number, col: number, value: MatrixItem<T>) {\n assert(0 <= row && row < this.rowCount\n && 0 <= col && col < this.colCount,\n 0x01a /* \"Trying to set out-of-bounds cell!\" */);\n\n this.setCellCore(row, col, value);\n\n // Avoid reentrancy by raising change notifications after the op is queued.\n for (const consumer of this.consumers.values()) {\n consumer.cellsChanged(row, col, 1, 1, this);\n }\n }\n\n public setCells(\n rowStart: number,\n colStart: number,\n colCount: number,\n values: readonly (MatrixItem<T>)[],\n ) {\n const rowCount = Math.ceil(values.length / colCount);\n\n assert((0 <= rowStart && rowStart < this.rowCount)\n && (0 <= colStart && colStart < this.colCount)\n && (1 <= colCount && colCount <= (this.colCount - colStart))\n && (rowCount <= (this.rowCount - rowStart)),\n 0x01b /* \"Trying to set multiple out-of-bounds cells!\" */);\n\n const endCol = colStart + colCount;\n let r = rowStart;\n let c = colStart;\n\n for (const value of values) {\n this.setCellCore(r, c, value);\n\n if (++c === endCol) {\n c = colStart;\n r++;\n }\n }\n\n // Avoid reentrancy by raising change notifications after the op is queued.\n for (const consumer of this.consumers.values()) {\n consumer.cellsChanged(rowStart, colStart, rowCount, colCount, this);\n }\n }\n\n private setCellCore(\n row: number,\n col: number,\n value: MatrixItem<T>,\n rowHandle = this.rows.getAllocatedHandle(row),\n colHandle = this.cols.getAllocatedHandle(col),\n ) {\n if (this.undo !== undefined) {\n let oldValue = this.cells.getCell(rowHandle, colHandle);\n if (oldValue === null) {\n oldValue = undefined;\n }\n\n this.undo.cellSet(\n rowHandle,\n colHandle,\n oldValue);\n }\n\n this.cells.setCell(rowHandle, colHandle, value);\n\n if (this.isAttached()) {\n this.sendSetCellOp(row, col, value, rowHandle, colHandle);\n }\n }\n\n private sendSetCellOp(\n row: number,\n col: number,\n value: MatrixItem<T>,\n rowHandle: Handle,\n colHandle: Handle,\n localSeq = this.nextLocalSeq(),\n rowsRefSeq = this.rows.getCollabWindow().currentSeq,\n colsRefSeq = this.cols.getCollabWindow().currentSeq,\n ) {\n assert(this.isAttached(), 0x1e2 /* \"Caller must ensure 'isAttached()' before calling 'sendSetCellOp'.\" */);\n\n const op: ISetOp<T> = {\n type: MatrixOp.set,\n row,\n col,\n value,\n };\n\n const metadata: ISetOpMetadata = {\n rowHandle,\n colHandle,\n localSeq,\n rowsRefSeq,\n colsRefSeq,\n };\n\n this.submitLocalMessage(op, metadata);\n this.pending.setCell(rowHandle, colHandle, localSeq);\n }\n\n private submitVectorMessage(\n currentVector: PermutationVector,\n oppositeVector: PermutationVector,\n dimension: SnapshotPath.rows | SnapshotPath.cols,\n message: any,\n ) {\n // Ideally, we would have a single 'localSeq' counter that is shared between both PermutationVectors\n // and the SharedMatrix's cell data. Instead, we externally advance each MergeTree's 'localSeq' counter\n // for each submitted op it not aware of to keep them synchronized.\n const localSeq = currentVector.getCollabWindow().localSeq;\n const oppositeWindow = oppositeVector.getCollabWindow();\n\n // Note that the comparison is '>=' because, in the case the MergeTree is regenerating ops for reconnection,\n // the MergeTree submits the op with the original 'localSeq'.\n assert(localSeq >= oppositeWindow.localSeq,\n 0x01c /* \"The 'localSeq' of the vector submitting an op must >= the 'localSeq' of the other vector.\" */);\n\n oppositeWindow.localSeq = localSeq;\n\n // If the SharedMatrix is local, it's state will be submitted via a Snapshot when initially connected.\n // Do not queue a message or track the pending op, as there will never be an ACK, etc.\n if (this.isAttached()) {\n // Record whether this `op` targets rows or cols. (See dispatch in `processCore()`)\n message.target = dimension;\n\n this.submitLocalMessage(\n message,\n currentVector.peekPendingSegmentGroups(\n message.type === MergeTreeDeltaType.GROUP\n ? message.ops.length\n : 1));\n }\n }\n\n private submitColMessage(message: any) {\n this.submitVectorMessage(this.cols, this.rows, SnapshotPath.cols, message);\n }\n\n public insertCols(colStart: number, count: number) {\n this.submitColMessage(this.cols.insert(colStart, count));\n }\n\n public removeCols(colStart: number, count: number) {\n this.submitColMessage(this.cols.remove(colStart, count));\n }\n\n private submitRowMessage(message: any) {\n this.submitVectorMessage(this.rows, this.cols, SnapshotPath.rows, message);\n }\n\n public insertRows(rowStart: number, count: number) {\n this.submitRowMessage(this.rows.insert(rowStart, count));\n }\n\n public removeRows(rowStart: number, count: number) {\n this.submitRowMessage(this.rows.remove(rowStart, count));\n }\n\n /** @internal */ public _undoRemoveRows(segment: ISegment) {\n const original = segment as PermutationSegment;\n\n // (Re)insert the removed number of rows at the original position.\n const { op, inserted } = this.rows.insertRelative(original, original.cachedLength);\n this.submitRowMessage(op);\n\n // Transfer handles and undo/redo tracking groups from the original segment to the\n // newly inserted segment.\n original.transferToReplacement(inserted);\n\n // Invalidate the handleCache in case it was populated during the 'rowsChanged'\n // callback, which occurs before the handle span is populated.\n const rowStart = this.rows.getPosition(inserted);\n this.rows.handleCache.itemsChanged(\n rowStart,\n /* removedCount: */ 0,\n /* insertedCount: */ inserted.cachedLength);\n\n // Generate setCell ops for each populated cell in the reinserted rows.\n let rowHandle = inserted.start;\n const rowCount = inserted.cachedLength;\n for (let row = rowStart; row < rowStart + rowCount; row++, rowHandle++) {\n for (let col = 0; col < this.colCount; col++) {\n const colHandle = this.colHandles.getHandle(col);\n const value = this.cells.getCell(rowHandle, colHandle);\n if (this.isAttached() && value !== undefined && value !== null) {\n this.sendSetCellOp(\n row,\n col,\n value,\n rowHandle,\n colHandle);\n }\n }\n }\n\n // Avoid reentrancy by raising change notifications after the op is queued.\n for (const consumer of this.consumers.values()) {\n consumer.cellsChanged(rowStart, /* colStart: */ 0, rowCount, this.colCount, this);\n }\n }\n\n /** @internal */ public _undoRemoveCols(segment: ISegment) {\n const original = segment as PermutationSegment;\n\n // (Re)insert the removed number of columns at the original position.\n const { op, inserted } = this.cols.insertRelative(original, original.cachedLength);\n this.submitColMessage(op);\n\n // Transfer handles and undo/redo tracking groups from the original segment to the\n // newly inserted segment.\n original.transferToReplacement(inserted);\n\n // Invalidate the handleCache in case it was populated during the 'colsChanged'\n // callback, which occurs before the handle span is populated.\n const colStart = this.cols.getPosition(inserted);\n this.cols.handleCache.itemsChanged(\n colStart,\n /* removedCount: */ 0,\n /* insertedCount: */ inserted.cachedLength);\n\n // Generate setCell ops for each populated cell in the reinserted cols.\n let colHandle = inserted.start;\n const colCount = inserted.cachedLength;\n for (let col = colStart; col < colStart + colCount; col++, colHandle++) {\n for (let row = 0; row < this.rowCount; row++) {\n const rowHandle = this.rowHandles.getHandle(row);\n const value = this.cells.getCell(rowHandle, colHandle);\n if (this.isAttached() && value !== undefined && value !== null) {\n this.sendSetCellOp(\n row,\n col,\n value,\n rowHandle,\n colHandle);\n }\n }\n }\n\n // Avoid reentrancy by raising change notifications after the op is queued.\n for (const consumer of this.consumers.values()) {\n consumer.cellsChanged(/* rowStart: */ 0, colStart, this.rowCount, colCount, this);\n }\n }\n\n protected summarizeCore(serializer: IFluidSerializer): ISummaryTreeWithStats {\n const builder = new SummaryTreeBuilder();\n builder.addWithStats(SnapshotPath.rows, this.rows.summarize(this.runtime, this.handle, serializer));\n builder.addWithStats(SnapshotPath.cols, this.cols.summarize(this.runtime, this.handle, serializer));\n builder.addBlob(SnapshotPath.cells,\n serializer.stringify([\n this.cells.snapshot(),\n this.pending.snapshot(),\n ], this.handle));\n return builder.getSummaryTree();\n }\n\n /**\n * Runs serializer on the GC data for this SharedMatrix.\n * All the IFluidHandle's stored in the cells represent routes to other objects.\n */\n protected processGCDataCore(serializer: SummarySerializer) {\n for (let row = 0; row < this.rowCount; row++) {\n for (let col = 0; col < this.colCount; col++) {\n serializer.stringify(this.getCell(row, col), this.handle);\n }\n }\n }\n\n /**\n * Advances the 'localSeq' counter for the cell data operation currently being queued.\n *\n * Do not use with 'submitColMessage()/submitRowMessage()' as these helpers + the MergeTree will\n * automatically advance 'localSeq'.\n */\n private nextLocalSeq() {\n // Ideally, we would have a single 'localSeq' counter that is shared between both PermutationVectors\n // and the SharedMatrix's cell data. Instead, we externally bump each MergeTree's 'localSeq' counter\n // for SharedMatrix ops it's not aware of to keep them synchronized. (For cell data operations, we\n // need to bump both counters.)\n\n this.cols.getCollabWindow().localSeq++;\n return ++this.rows.getCollabWindow().localSeq;\n }\n\n protected submitLocalMessage(message: any, localOpMetadata?: any) {\n // TODO: Recommend moving this assertion into SharedObject\n // (See https://github.com/microsoft/FluidFramework/issues/2559)\n assert(this.isAttached() === true, 0x01d /* \"Trying to submit message to runtime while detached!\" */);\n\n super.submitLocalMessage(makeHandlesSerializable(message, this.serializer, this.handle), localOpMetadata);\n\n // Ensure that row/col 'localSeq' are synchronized (see 'nextLocalSeq()').\n assert(\n this.rows.getCollabWindow().localSeq === this.cols.getCollabWindow().localSeq,\n 0x01e /* \"Row and col collab window 'localSeq' desynchronized!\" */,\n );\n }\n\n protected didAttach() {\n // We've attached we need to start generating and sending ops.\n // so start collaboration and provide a default client id incase we are not connected\n if (this.isAttached()) {\n this.rows.startOrUpdateCollaboration(this.runtime.clientId ?? \"attached\");\n this.cols.startOrUpdateCollaboration(this.runtime.clientId ?? \"attached\");\n }\n }\n\n protected onConnect() {\n assert(this.rows.getCollabWindow().collaborating === this.cols.getCollabWindow().collaborating,\n 0x01f /* \"Row and col collab window 'collaborating' status desynchronized!\" */);\n\n // Update merge tree collaboration information with new client ID and then resend pending ops\n this.rows.startOrUpdateCollaboration(this.runtime.clientId as string);\n this.cols.startOrUpdateCollaboration(this.runtime.clientId as string);\n }\n\n protected reSubmitCore(content: any, localOpMetadata: unknown) {\n switch (content.target) {\n case SnapshotPath.cols:\n this.submitColMessage(this.cols.regeneratePendingOp(\n content as IMergeTreeOp,\n localOpMetadata as SegmentGroup | SegmentGroup[]));\n break;\n case SnapshotPath.rows:\n this.submitRowMessage(this.rows.regeneratePendingOp(\n content as IMergeTreeOp,\n localOpMetadata as SegmentGroup | SegmentGroup[]));\n break;\n default: {\n assert(content.type === MatrixOp.set, 0x020 /* \"Unknown SharedMatrix 'op' type.\" */);\n\n const setOp = content as ISetOp<T>;\n const { rowHandle, colHandle, localSeq, rowsRefSeq, colsRefSeq } = localOpMetadata as ISetOpMetadata;\n\n // If there are more pending local writes to the same row/col handle, it is important\n // to skip resubmitting this op since it is possible the row/col handle has been recycled\n // and now refers to a different position than when this op was originally submitted.\n if (this.isLatestPendingWrite(rowHandle, colHandle, localSeq)) {\n const row = this.rows.rebasePositionWithoutSegmentSlide(setOp.row, rowsRefSeq, localSeq);\n const col = this.cols.rebasePositionWithoutSegmentSlide(setOp.col, colsRefSeq, localSeq);\n\n if (row !== undefined && col !== undefined && row >= 0 && col >= 0) {\n this.sendSetCellOp(\n row,\n col,\n setOp.value,\n rowHandle,\n colHandle,\n localSeq,\n rowsRefSeq,\n colsRefSeq,\n );\n }\n }\n break;\n }\n }\n }\n\n protected onDisconnect() {}\n\n /**\n * {@inheritDoc @fluidframework/shared-object-base#SharedObject.loadCore}\n */\n protected async loadCore(storage: IChannelStorageService) {\n try {\n await this.rows.load(\n this.runtime,\n new ObjectStoragePartition(storage, SnapshotPath.rows),\n this.serializer);\n await this.cols.load(\n this.runtime,\n new ObjectStoragePartition(storage, SnapshotPath.cols),\n this.serializer);\n const [cellData, pendingCliSeqData] = await deserializeBlob(storage, SnapshotPath.cells, this.serializer);\n\n this.cells = SparseArray2D.load(cellData);\n this.pending = SparseArray2D.load(pendingCliSeqData);\n } catch (error) {\n this.logger.sendErrorEvent({ eventName: \"MatrixLoadFailed\" }, error);\n }\n }\n\n protected processCore(rawMessage: ISequencedDocumentMessage, local: boolean, localOpMetadata: unknown) {\n const msg = parseHandles(rawMessage, this.serializer);\n\n const contents = msg.contents;\n\n switch (contents.target) {\n case SnapshotPath.cols:\n this.cols.applyMsg(msg, local);\n break;\n case SnapshotPath.rows:\n this.rows.applyMsg(msg, local);\n break;\n default: {\n assert(contents.type === MatrixOp.set,\n 0x021 /* \"SharedMatrix message contents have unexpected type!\" */);\n\n const { row, col } = contents;\n\n if (local) {\n // We are receiving the ACK for a local pending set operation.\n const { rowHandle, colHandle, localSeq } = localOpMetadata as ISetOpMetadata;\n\n // If this is the most recent write to the cell by the local client, remove our\n // entry from 'pendingCliSeqs' to resume allowing remote writes.\n if (this.isLatestPendingWrite(rowHandle, colHandle, localSeq)) {\n this.pending.setCell(rowHandle, colHandle, undefined);\n }\n } else {\n const adjustedRow = this.rows.adjustPosition(row, rawMessage);\n\n if (adjustedRow !== undefined) {\n const adjustedCol = this.cols.adjustPosition(col, rawMessage);\n\n if (adjustedCol !== undefined) {\n const rowHandle = this.rows.getAllocatedHandle(adjustedRow);\n const colHandle = this.cols.getAllocatedHandle(adjustedCol);\n\n assert(isHandleValid(rowHandle) && isHandleValid(colHandle),\n 0x022 /* \"SharedMatrix row and/or col handles are invalid!\" */);\n\n // If there is a pending (unACKed) local write to the same cell, skip the current op\n // since it \"happened before\" the pending write.\n if (this.pending.getCell(rowHandle, colHandle) === undefined) {\n const { value } = contents;\n this.cells.setCell(rowHandle, colHandle, value);\n\n for (const consumer of this.consumers.values()) {\n consumer.cellsChanged(adjustedRow, adjustedCol, 1, 1, this);\n }\n }\n }\n }\n }\n }\n }\n }\n\n // Invoked by PermutationVector to notify IMatrixConsumers of row insertion/deletions.\n private readonly onRowDelta = (position: number, removedCount: number, insertedCount: number) => {\n for (const consumer of this.consumers) {\n consumer.rowsChanged(position, removedCount, insertedCount, this);\n }\n };\n\n // Invoked by PermutationVector to notify IMatrixConsumers of col insertion/deletions.\n private readonly onColDelta = (position: number, removedCount: number, insertedCount: number) => {\n for (const consumer of this.consumers) {\n consumer.colsChanged(position, removedCount, insertedCount, this);\n }\n };\n\n private readonly onRowHandlesRecycled = (rowHandles: Handle[]) => {\n for (const rowHandle of rowHandles) {\n this.cells.clearRows(/* rowStart: */ rowHandle, /* rowCount: */ 1);\n this.pending.clearRows(/* rowStart: */ rowHandle, /* rowCount: */ 1);\n }\n };\n\n private readonly onColHandlesRecycled = (colHandles: Handle[]) => {\n for (const colHandle of colHandles) {\n this.cells.clearCols(/* colStart: */ colHandle, /* colCount: */ 1);\n this.pending.clearCols(/* colStart: */ colHandle, /* colCount: */ 1);\n }\n };\n\n /**\n * Returns true if the latest pending write to the cell indicated by the given row/col handles\n * matches the given 'localSeq'.\n *\n * A return value of `true` indicates that there are no later local operations queued that will\n * clobber the write op at the given 'localSeq'. This includes later ops that overwrite the cell\n * with a different value as well as row/col removals that might recycled the given row/col handles.\n */\n private isLatestPendingWrite(rowHandle: Handle, colHandle: Handle, localSeq: number) {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const pendingLocalSeq = this.pending.getCell(rowHandle, colHandle)!;\n\n // Note while we're awaiting the ACK for a local set, it's possible for the row/col to be\n // locally removed and the row/col handles recycled. If this happens, the pendingLocalSeq will\n // be 'undefined' or > 'localSeq'.\n assert(!(pendingLocalSeq < localSeq),\n // eslint-disable-next-line max-len\n 0x023 /* \"The 'localSeq' of pending write (if any) must be <= the localSeq of the currently processed op.\" */);\n\n // If this is the most recent write to the cell by the local client, the stored localSeq\n // will be an exact match for the given 'localSeq'.\n return pendingLocalSeq === localSeq;\n }\n\n public toString() {\n let s = `client:${this.runtime.clientId}\\nrows: ${this.rows.toString()}\\ncols: ${this.cols.toString()}\\n\\n`;\n\n for (let r = 0; r < this.rowCount; r++) {\n s += ` [`;\n for (let c = 0; c < this.colCount; c++) {\n if (c > 0) {\n s += \", \";\n }\n\n s += `${this.serializer.stringify(this.getCell(r, c), this.handle)}`;\n }\n s += \"]\\n\";\n }\n\n return `${s}\\n`;\n }\n\n /**\n * {@inheritDoc @fluidframework/shared-object-base#SharedObjectCore.applyStashedOp}\n */\n protected applyStashedOp(content: any): unknown {\n if (content.target === SnapshotPath.cols || content.target === SnapshotPath.rows) {\n const op = content as IMergeTreeOp;\n const currentVector = content.target === SnapshotPath.cols ? this.cols : this.rows;\n const oppositeVector = content.target === SnapshotPath.cols ? this.rows : this.cols;\n const metadata = currentVector.applyStashedOp(op);\n const localSeq = currentVector.getCollabWindow().localSeq;\n const oppositeWindow = oppositeVector.getCollabWindow();\n\n assert(\n localSeq > oppositeWindow.localSeq,\n 0x2d9,\n /* \"The 'localSeq' of the vector applying stashed op must > the 'localSeq' of the other vector.\" */\n );\n\n oppositeWindow.localSeq = localSeq;\n\n return metadata;\n } else {\n assert(content.type === MatrixOp.set, 0x2da /* \"Unknown SharedMatrix 'op' type.\" */);\n\n const setOp = content as ISetOp<T>;\n const rowHandle = this.rows.getAllocatedHandle(setOp.row);\n const colHandle = this.cols.getAllocatedHandle(setOp.col);\n const rowsRefSeq = this.rows.getCollabWindow().currentSeq;\n const colsRefSeq = this.cols.getCollabWindow().currentSeq;\n if (this.undo !== undefined) {\n let oldValue = this.cells.getCell(rowHandle, colHandle);\n if (oldValue === null) {\n oldValue = undefined;\n }\n\n this.undo.cellSet(\n rowHandle,\n colHandle,\n oldValue);\n }\n\n this.cells.setCell(rowHandle, colHandle, setOp.value);\n const localSeq = this.nextLocalSeq();\n const metadata: ISetOpMetadata = {\n rowHandle,\n colHandle,\n localSeq,\n rowsRefSeq,\n colsRefSeq,\n };\n\n this.pending.setCell(rowHandle, colHandle, localSeq);\n return metadata;\n }\n }\n}\n"]}
1
+ {"version":3,"file":"matrix.js","sourceRoot":"","sources":["../src/matrix.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;AAEH,+DAAsD;AAQtD,2EAM4C;AAE5C,iEAA2F;AAO3F,2DAA8G;AAC9G,+BAAiC;AACjC,2DAA4E;AAC5E,mDAAgD;AAChD,uCAAgD;AAChD,+CAAsD;AACtD,mDAAkD;AAClD,mCAAsC;AAEtC,iDAAoD;AA6BpD;;;;;;;;;;;GAWG;AACH,MAAa,YACT,SAAQ,iCAAY;IAcpB,YAAY,OAA+B,EAAS,EAAU,EAAE,UAA8B;QAC1F,KAAK,CAAC,EAAE,EAAE,OAAO,EAAE,UAAU,EAAE,e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AO,CAAC,SAAS,EAAE,SAAS,EAAE,KAAK,CAAC,KAAK,CAAC,CAAC;YACtD,MAAM,QAAQ,GAAG,IAAI,CAAC,YAAY,EAAE,CAAC;YACrC,MAAM,QAAQ,GAAmB;gBAC7B,SAAS;gBACT,SAAS;gBACT,QAAQ;gBACR,UAAU;gBACV,UAAU;aACb,CAAC;YAEF,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,SAAS,EAAE,SAAS,EAAE,QAAQ,CAAC,CAAC;YACrD,OAAO,QAAQ,CAAC;SACnB;IACL,CAAC;CACJ;AA5qBD,oCA4qBC","sourcesContent":["/*!\n * Copyright (c) Microsoft Corporation and contributors. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { assert } from \"@fluidframework/common-utils\";\nimport { ISequencedDocumentMessage } from \"@fluidframework/protocol-definitions\";\nimport {\n IFluidDataStoreRuntime,\n IChannelStorageService,\n Serializable,\n IChannelAttributes,\n} from \"@fluidframework/datastore-definitions\";\nimport {\n IFluidSerializer,\n makeHandlesSerializable,\n parseHandles,\n SharedObject,\n SummarySerializer,\n} from \"@fluidframework/shared-object-base\";\nimport { ISummaryTreeWithStats } from \"@fluidframework/runtime-definitions\";\nimport { ObjectStoragePartition, SummaryTreeBuilder } from \"@fluidframework/runtime-utils\";\nimport {\n IMatrixProducer,\n IMatrixConsumer,\n IMatrixReader,\n IMatrixWriter,\n} from \"@tiny-calc/nano\";\nimport { MergeTreeDeltaType, IMergeTreeOp, SegmentGroup, ISegment, Client } from \"@fluidframework/merge-tree\";\nimport { MatrixOp } from \"./ops\";\nimport { PermutationVector, PermutationSegment } from \"./permutationvector\";\nimport { SparseArray2D } from \"./sparsearray2d\";\nimport { SharedMatrixFactory } from \"./runtime\";\nimport { Handle, isHandleValid } from \"./handletable\";\nimport { deserializeBlob } from \"./serialization\";\nimport { ensureRange } from \"./range\";\nimport { IUndoConsumer } from \"./types\";\nimport { MatrixUndoProvider } from \"./undoprovider\";\n\nconst enum SnapshotPath {\n rows = \"rows\",\n cols = \"cols\",\n cells = \"cells\",\n}\n\ninterface ISetOp<T> {\n type: MatrixOp.set;\n row: number;\n col: number;\n value: MatrixItem<T>;\n}\n\ninterface ISetOpMetadata {\n rowHandle: Handle;\n colHandle: Handle;\n localSeq: number;\n rowsRefSeq: number;\n colsRefSeq: number;\n}\n\n/**\n * A matrix cell value may be undefined (indicating an empty cell) or any serializable type,\n * excluding null. (However, nulls may be embedded inside objects and arrays.)\n */\nexport type MatrixItem<T> = Serializable<Exclude<T, null>> | undefined;\n\n/**\n * A SharedMatrix holds a rectangular 2D array of values. Supported operations\n * include setting values and inserting/removing rows and columns.\n *\n * Matrix values may be any Fluid serializable type, which is the set of JSON\n * serializable types extended to include IFluidHandles.\n *\n * Fluid's SharedMatrix implementation works equally well for dense and sparse\n * matrix data and physically stores data in Z-order to leverage CPU caches and\n * prefetching when reading in either row or column major order. (See README.md\n * for more details.)\n */\nexport class SharedMatrix<T = any>\n extends SharedObject\n implements IMatrixProducer<MatrixItem<T>>,\n IMatrixReader<MatrixItem<T>>,\n IMatrixWriter<MatrixItem<T>> {\n private readonly consumers = new Set<IMatrixConsumer<MatrixItem<T>>>();\n\n public static getFactory() { return new SharedMatrixFactory(); }\n\n private readonly rows: PermutationVector; // Map logical row to storage handle (if any)\n private readonly cols: PermutationVector; // Map logical col to storage handle (if any)\n\n private cells = new SparseArray2D<MatrixItem<T>>(); // Stores cell values.\n private pending = new SparseArray2D<number>(); // Tracks pending writes.\n\n constructor(runtime: IFluidDataStoreRuntime, public id: string, attributes: IChannelAttributes) {\n super(id, runtime, attributes, \"fluid_matrix_\");\n\n this.rows = new PermutationVector(\n SnapshotPath.rows,\n this.logger,\n runtime,\n this.onRowDelta,\n this.onRowHandlesRecycled);\n\n this.cols = new PermutationVector(\n SnapshotPath.cols,\n this.logger,\n runtime,\n this.onColDelta,\n this.onColHandlesRecycled);\n }\n\n private undo?: MatrixUndoProvider<T>;\n\n /**\n * Subscribes the given IUndoConsumer to the matrix.\n */\n public openUndo(consumer: IUndoConsumer) {\n assert(this.undo === undefined,\n 0x019 /* \"SharedMatrix.openUndo() supports at most a single IUndoConsumer.\" */);\n\n this.undo = new MatrixUndoProvider(consumer, this, this.rows, this.cols);\n }\n\n // TODO: closeUndo()?\n\n private get rowHandles() { return this.rows.handleCache; }\n private get colHandles() { return this.cols.handleCache; }\n\n /**\n * {@inheritDoc @fluidframework/datastore-definitions#IChannelFactory.create}\n */\n public static create<T>(runtime: IFluidDataStoreRuntime, id?: string) {\n return runtime.createChannel(id, SharedMatrixFactory.Type) as SharedMatrix<T>;\n }\n\n // #region IMatrixProducer\n\n openMatrix(\n consumer: IMatrixConsumer<MatrixItem<T>>,\n ): IMatrixReader<MatrixItem<T>> {\n this.consumers.add(consumer);\n return this;\n }\n\n closeMatrix(consumer: IMatrixConsumer<MatrixItem<T>>): void {\n this.consumers.delete(consumer);\n }\n\n // #endregion IMatrixProducer\n\n // #region IMatrixReader\n\n public get rowCount() { return this.rows.getLength(); }\n public get colCount() { return this.cols.getLength(); }\n\n public getCell(row: number, col: number): MatrixItem<T> {\n // Perf: When possible, bounds checking is performed inside the implementation for\n // 'getHandle()' so that it can be elided in the case of a cache hit. This\n // yields an ~40% improvement in the case of a cache hit (node v12 x64)\n\n // Map the logical (row, col) to associated storage handles.\n const rowHandle = this.rowHandles.getHandle(row);\n if (isHandleValid(rowHandle)) {\n const colHandle = this.colHandles.getHandle(col);\n if (isHandleValid(colHandle)) {\n return this.cells.getCell(rowHandle, colHandle);\n }\n } else {\n // If we early exit because the given rowHandle is unallocated, we still need to\n // bounds-check the 'col' parameter.\n ensureRange(col, this.cols.getLength());\n }\n\n return undefined;\n }\n\n public get matrixProducer(): IMatrixProducer<MatrixItem<T>> { return this; }\n\n // #endregion IMatrixReader\n\n public setCell(row: number, col: number, value: MatrixItem<T>) {\n assert(0 <= row && row < this.rowCount\n && 0 <= col && col < this.colCount,\n 0x01a /* \"Trying to set out-of-bounds cell!\" */);\n\n this.setCellCore(row, col, value);\n\n // Avoid reentrancy by raising change notifications after the op is queued.\n for (const consumer of this.consumers.values()) {\n consumer.cellsChanged(row, col, 1, 1, this);\n }\n }\n\n public setCells(\n rowStart: number,\n colStart: number,\n colCount: number,\n values: readonly (MatrixItem<T>)[],\n ) {\n const rowCount = Math.ceil(values.length / colCount);\n\n assert((0 <= rowStart && rowStart < this.rowCount)\n && (0 <= colStart && colStart < this.colCount)\n && (1 <= colCount && colCount <= (this.colCount - colStart))\n && (rowCount <= (this.rowCount - rowStart)),\n 0x01b /* \"Trying to set multiple out-of-bounds cells!\" */);\n\n const endCol = colStart + colCount;\n let r = rowStart;\n let c = colStart;\n\n for (const value of values) {\n this.setCellCore(r, c, value);\n\n if (++c === endCol) {\n c = colStart;\n r++;\n }\n }\n\n // Avoid reentrancy by raising change notifications after the op is queued.\n for (const consumer of this.consumers.values()) {\n consumer.cellsChanged(rowStart, colStart, rowCount, colCount, this);\n }\n }\n\n private setCellCore(\n row: number,\n col: number,\n value: MatrixItem<T>,\n rowHandle = this.rows.getAllocatedHandle(row),\n colHandle = this.cols.getAllocatedHandle(col),\n ) {\n if (this.undo !== undefined) {\n let oldValue = this.cells.getCell(rowHandle, colHandle);\n if (oldValue === null) {\n oldValue = undefined;\n }\n\n this.undo.cellSet(\n rowHandle,\n colHandle,\n oldValue);\n }\n\n this.cells.setCell(rowHandle, colHandle, value);\n\n if (this.isAttached()) {\n this.sendSetCellOp(row, col, value, rowHandle, colHandle);\n }\n }\n\n private sendSetCellOp(\n row: number,\n col: number,\n value: MatrixItem<T>,\n rowHandle: Handle,\n colHandle: Handle,\n localSeq = this.nextLocalSeq(),\n rowsRefSeq = this.rows.getCollabWindow().currentSeq,\n colsRefSeq = this.cols.getCollabWindow().currentSeq,\n ) {\n assert(this.isAttached(), 0x1e2 /* \"Caller must ensure 'isAttached()' before calling 'sendSetCellOp'.\" */);\n\n const op: ISetOp<T> = {\n type: MatrixOp.set,\n row,\n col,\n value,\n };\n\n const metadata: ISetOpMetadata = {\n rowHandle,\n colHandle,\n localSeq,\n rowsRefSeq,\n colsRefSeq,\n };\n\n this.submitLocalMessage(op, metadata);\n this.pending.setCell(rowHandle, colHandle, localSeq);\n }\n\n private submitVectorMessage(\n currentVector: PermutationVector,\n oppositeVector: PermutationVector,\n dimension: SnapshotPath.rows | SnapshotPath.cols,\n message: any,\n ) {\n // Ideally, we would have a single 'localSeq' counter that is shared between both PermutationVectors\n // and the SharedMatrix's cell data. Instead, we externally advance each MergeTree's 'localSeq' counter\n // for each submitted op it not aware of to keep them synchronized.\n const localSeq = currentVector.getCollabWindow().localSeq;\n const oppositeWindow = oppositeVector.getCollabWindow();\n\n // Note that the comparison is '>=' because, in the case the MergeTree is regenerating ops for reconnection,\n // the MergeTree submits the op with the original 'localSeq'.\n assert(localSeq >= oppositeWindow.localSeq,\n 0x01c /* \"The 'localSeq' of the vector submitting an op must >= the 'localSeq' of the other vector.\" */);\n\n oppositeWindow.localSeq = localSeq;\n\n // If the SharedMatrix is local, it's state will be submitted via a Snapshot when initially connected.\n // Do not queue a message or track the pending op, as there will never be an ACK, etc.\n if (this.isAttached()) {\n // Record whether this `op` targets rows or cols. (See dispatch in `processCore()`)\n message.target = dimension;\n\n this.submitLocalMessage(\n message,\n currentVector.peekPendingSegmentGroups(\n message.type === MergeTreeDeltaType.GROUP\n ? message.ops.length\n : 1));\n }\n }\n\n private submitColMessage(message: any) {\n this.submitVectorMessage(this.cols, this.rows, SnapshotPath.cols, message);\n }\n\n public insertCols(colStart: number, count: number) {\n this.submitColMessage(this.cols.insert(colStart, count));\n }\n\n public removeCols(colStart: number, count: number) {\n this.submitColMessage(this.cols.remove(colStart, count));\n }\n\n private submitRowMessage(message: any) {\n this.submitVectorMessage(this.rows, this.cols, SnapshotPath.rows, message);\n }\n\n public insertRows(rowStart: number, count: number) {\n this.submitRowMessage(this.rows.insert(rowStart, count));\n }\n\n public removeRows(rowStart: number, count: number) {\n this.submitRowMessage(this.rows.remove(rowStart, count));\n }\n\n /** @internal */ public _undoRemoveRows(segment: ISegment) {\n const original = segment as PermutationSegment;\n\n // (Re)insert the removed number of rows at the original position.\n const { op, inserted } = this.rows.insertRelative(original, original.cachedLength);\n this.submitRowMessage(op);\n\n // Transfer handles and undo/redo tracking groups from the original segment to the\n // newly inserted segment.\n original.transferToReplacement(inserted);\n\n // Invalidate the handleCache in case it was populated during the 'rowsChanged'\n // callback, which occurs before the handle span is populated.\n const rowStart = this.rows.getPosition(inserted);\n this.rows.handleCache.itemsChanged(\n rowStart,\n /* removedCount: */ 0,\n /* insertedCount: */ inserted.cachedLength);\n\n // Generate setCell ops for each populated cell in the reinserted rows.\n let rowHandle = inserted.start;\n const rowCount = inserted.cachedLength;\n for (let row = rowStart; row < rowStart + rowCount; row++, rowHandle++) {\n for (let col = 0; col < this.colCount; col++) {\n const colHandle = this.colHandles.getHandle(col);\n const value = this.cells.getCell(rowHandle, colHandle);\n if (this.isAttached() && value !== undefined && value !== null) {\n this.sendSetCellOp(\n row,\n col,\n value,\n rowHandle,\n colHandle);\n }\n }\n }\n\n // Avoid reentrancy by raising change notifications after the op is queued.\n for (const consumer of this.consumers.values()) {\n consumer.cellsChanged(rowStart, /* colStart: */ 0, rowCount, this.colCount, this);\n }\n }\n\n /** @internal */ public _undoRemoveCols(segment: ISegment) {\n const original = segment as PermutationSegment;\n\n // (Re)insert the removed number of columns at the original position.\n const { op, inserted } = this.cols.insertRelative(original, original.cachedLength);\n this.submitColMessage(op);\n\n // Transfer handles and undo/redo tracking groups from the original segment to the\n // newly inserted segment.\n original.transferToReplacement(inserted);\n\n // Invalidate the handleCache in case it was populated during the 'colsChanged'\n // callback, which occurs before the handle span is populated.\n const colStart = this.cols.getPosition(inserted);\n this.cols.handleCache.itemsChanged(\n colStart,\n /* removedCount: */ 0,\n /* insertedCount: */ inserted.cachedLength);\n\n // Generate setCell ops for each populated cell in the reinserted cols.\n let colHandle = inserted.start;\n const colCount = inserted.cachedLength;\n for (let col = colStart; col < colStart + colCount; col++, colHandle++) {\n for (let row = 0; row < this.rowCount; row++) {\n const rowHandle = this.rowHandles.getHandle(row);\n const value = this.cells.getCell(rowHandle, colHandle);\n if (this.isAttached() && value !== undefined && value !== null) {\n this.sendSetCellOp(\n row,\n col,\n value,\n rowHandle,\n colHandle);\n }\n }\n }\n\n // Avoid reentrancy by raising change notifications after the op is queued.\n for (const consumer of this.consumers.values()) {\n consumer.cellsChanged(/* rowStart: */ 0, colStart, this.rowCount, colCount, this);\n }\n }\n\n protected summarizeCore(serializer: IFluidSerializer): ISummaryTreeWithStats {\n const builder = new SummaryTreeBuilder();\n builder.addWithStats(SnapshotPath.rows, this.rows.summarize(this.runtime, this.handle, serializer));\n builder.addWithStats(SnapshotPath.cols, this.cols.summarize(this.runtime, this.handle, serializer));\n builder.addBlob(SnapshotPath.cells,\n serializer.stringify([\n this.cells.snapshot(),\n this.pending.snapshot(),\n ], this.handle));\n return builder.getSummaryTree();\n }\n\n /**\n * Runs serializer on the GC data for this SharedMatrix.\n * All the IFluidHandle's stored in the cells represent routes to other objects.\n */\n protected processGCDataCore(serializer: SummarySerializer) {\n for (let row = 0; row < this.rowCount; row++) {\n for (let col = 0; col < this.colCount; col++) {\n serializer.stringify(this.getCell(row, col), this.handle);\n }\n }\n }\n\n /**\n * Advances the 'localSeq' counter for the cell data operation currently being queued.\n *\n * Do not use with 'submitColMessage()/submitRowMessage()' as these helpers + the MergeTree will\n * automatically advance 'localSeq'.\n */\n private nextLocalSeq() {\n // Ideally, we would have a single 'localSeq' counter that is shared between both PermutationVectors\n // and the SharedMatrix's cell data. Instead, we externally bump each MergeTree's 'localSeq' counter\n // for SharedMatrix ops it's not aware of to keep them synchronized. (For cell data operations, we\n // need to bump both counters.)\n\n this.cols.getCollabWindow().localSeq++;\n return ++this.rows.getCollabWindow().localSeq;\n }\n\n protected submitLocalMessage(message: any, localOpMetadata?: any) {\n // TODO: Recommend moving this assertion into SharedObject\n // (See https://github.com/microsoft/FluidFramework/issues/2559)\n assert(this.isAttached() === true, 0x01d /* \"Trying to submit message to runtime while detached!\" */);\n\n super.submitLocalMessage(makeHandlesSerializable(message, this.serializer, this.handle), localOpMetadata);\n\n // Ensure that row/col 'localSeq' are synchronized (see 'nextLocalSeq()').\n assert(\n this.rows.getCollabWindow().localSeq === this.cols.getCollabWindow().localSeq,\n 0x01e /* \"Row and col collab window 'localSeq' desynchronized!\" */,\n );\n }\n\n protected didAttach() {\n // We've attached we need to start generating and sending ops.\n // so start collaboration and provide a default client id incase we are not connected\n if (this.isAttached()) {\n this.rows.startOrUpdateCollaboration(this.runtime.clientId ?? \"attached\");\n this.cols.startOrUpdateCollaboration(this.runtime.clientId ?? \"attached\");\n }\n }\n\n protected onConnect() {\n assert(this.rows.getCollabWindow().collaborating === this.cols.getCollabWindow().collaborating,\n 0x01f /* \"Row and col collab window 'collaborating' status desynchronized!\" */);\n\n // Update merge tree collaboration information with new client ID and then resend pending ops\n this.rows.startOrUpdateCollaboration(this.runtime.clientId as string);\n this.cols.startOrUpdateCollaboration(this.runtime.clientId as string);\n }\n\n private rebasePosition(\n client: Client,\n pos: number,\n referenceSequenceNumber: number,\n localSeq: number\n ): number | undefined {\n const { clientId } = client.getCollabWindow();\n const { segment, offset } = client.getContainingSegment(pos, { referenceSequenceNumber, clientId: client.getLongClientId(clientId) }, localSeq);\n if (segment === undefined || offset === undefined) {\n return;\n }\n\n return client.findReconnectionPosition(segment, localSeq) + offset;\n }\n\n protected reSubmitCore(content: any, localOpMetadata: unknown) {\n switch (content.target) {\n case SnapshotPath.cols:\n this.submitColMessage(this.cols.regeneratePendingOp(\n content as IMergeTreeOp,\n localOpMetadata as SegmentGroup | SegmentGroup[]));\n break;\n case SnapshotPath.rows:\n this.submitRowMessage(this.rows.regeneratePendingOp(\n content as IMergeTreeOp,\n localOpMetadata as SegmentGroup | SegmentGroup[]));\n break;\n default: {\n assert(content.type === MatrixOp.set, 0x020 /* \"Unknown SharedMatrix 'op' type.\" */);\n\n const setOp = content as ISetOp<T>;\n const { rowHandle, colHandle, localSeq, rowsRefSeq, colsRefSeq } = localOpMetadata as ISetOpMetadata;\n\n // If there are more pending local writes to the same row/col handle, it is important\n // to skip resubmitting this op since it is possible the row/col handle has been recycled\n // and now refers to a different position than when this op was originally submitted.\n if (this.isLatestPendingWrite(rowHandle, colHandle, localSeq)) {\n const row = this.rebasePosition(this.rows, setOp.row, rowsRefSeq, localSeq);\n const col = this.rebasePosition(this.cols, setOp.col, colsRefSeq, localSeq);\n\n if (row !== undefined && col !== undefined && row >= 0 && col >= 0) {\n this.sendSetCellOp(\n row,\n col,\n setOp.value,\n rowHandle,\n colHandle,\n localSeq,\n rowsRefSeq,\n colsRefSeq,\n );\n }\n }\n break;\n }\n }\n }\n\n protected onDisconnect() {}\n\n /**\n * {@inheritDoc @fluidframework/shared-object-base#SharedObject.loadCore}\n */\n protected async loadCore(storage: IChannelStorageService) {\n try {\n await this.rows.load(\n this.runtime,\n new ObjectStoragePartition(storage, SnapshotPath.rows),\n this.serializer);\n await this.cols.load(\n this.runtime,\n new ObjectStoragePartition(storage, SnapshotPath.cols),\n this.serializer);\n const [cellData, pendingCliSeqData] = await deserializeBlob(storage, SnapshotPath.cells, this.serializer);\n\n this.cells = SparseArray2D.load(cellData);\n this.pending = SparseArray2D.load(pendingCliSeqData);\n } catch (error) {\n this.logger.sendErrorEvent({ eventName: \"MatrixLoadFailed\" }, error);\n }\n }\n\n protected processCore(rawMessage: ISequencedDocumentMessage, local: boolean, localOpMetadata: unknown) {\n const msg = parseHandles(rawMessage, this.serializer);\n\n const contents = msg.contents;\n\n switch (contents.target) {\n case SnapshotPath.cols:\n this.cols.applyMsg(msg, local);\n break;\n case SnapshotPath.rows:\n this.rows.applyMsg(msg, local);\n break;\n default: {\n assert(contents.type === MatrixOp.set,\n 0x021 /* \"SharedMatrix message contents have unexpected type!\" */);\n\n const { row, col } = contents;\n\n if (local) {\n // We are receiving the ACK for a local pending set operation.\n const { rowHandle, colHandle, localSeq } = localOpMetadata as ISetOpMetadata;\n\n // If this is the most recent write to the cell by the local client, remove our\n // entry from 'pendingCliSeqs' to resume allowing remote writes.\n if (this.isLatestPendingWrite(rowHandle, colHandle, localSeq)) {\n this.pending.setCell(rowHandle, colHandle, undefined);\n }\n } else {\n const adjustedRow = this.rows.adjustPosition(row, rawMessage);\n\n if (adjustedRow !== undefined) {\n const adjustedCol = this.cols.adjustPosition(col, rawMessage);\n\n if (adjustedCol !== undefined) {\n const rowHandle = this.rows.getAllocatedHandle(adjustedRow);\n const colHandle = this.cols.getAllocatedHandle(adjustedCol);\n\n assert(isHandleValid(rowHandle) && isHandleValid(colHandle),\n 0x022 /* \"SharedMatrix row and/or col handles are invalid!\" */);\n\n // If there is a pending (unACKed) local write to the same cell, skip the current op\n // since it \"happened before\" the pending write.\n if (this.pending.getCell(rowHandle, colHandle) === undefined) {\n const { value } = contents;\n this.cells.setCell(rowHandle, colHandle, value);\n\n for (const consumer of this.consumers.values()) {\n consumer.cellsChanged(adjustedRow, adjustedCol, 1, 1, this);\n }\n }\n }\n }\n }\n }\n }\n }\n\n // Invoked by PermutationVector to notify IMatrixConsumers of row insertion/deletions.\n private readonly onRowDelta = (position: number, removedCount: number, insertedCount: number) => {\n for (const consumer of this.consumers) {\n consumer.rowsChanged(position, removedCount, insertedCount, this);\n }\n };\n\n // Invoked by PermutationVector to notify IMatrixConsumers of col insertion/deletions.\n private readonly onColDelta = (position: number, removedCount: number, insertedCount: number) => {\n for (const consumer of this.consumers) {\n consumer.colsChanged(position, removedCount, insertedCount, this);\n }\n };\n\n private readonly onRowHandlesRecycled = (rowHandles: Handle[]) => {\n for (const rowHandle of rowHandles) {\n this.cells.clearRows(/* rowStart: */ rowHandle, /* rowCount: */ 1);\n this.pending.clearRows(/* rowStart: */ rowHandle, /* rowCount: */ 1);\n }\n };\n\n private readonly onColHandlesRecycled = (colHandles: Handle[]) => {\n for (const colHandle of colHandles) {\n this.cells.clearCols(/* colStart: */ colHandle, /* colCount: */ 1);\n this.pending.clearCols(/* colStart: */ colHandle, /* colCount: */ 1);\n }\n };\n\n /**\n * Returns true if the latest pending write to the cell indicated by the given row/col handles\n * matches the given 'localSeq'.\n *\n * A return value of `true` indicates that there are no later local operations queued that will\n * clobber the write op at the given 'localSeq'. This includes later ops that overwrite the cell\n * with a different value as well as row/col removals that might recycled the given row/col handles.\n */\n private isLatestPendingWrite(rowHandle: Handle, colHandle: Handle, localSeq: number) {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const pendingLocalSeq = this.pending.getCell(rowHandle, colHandle)!;\n\n // Note while we're awaiting the ACK for a local set, it's possible for the row/col to be\n // locally removed and the row/col handles recycled. If this happens, the pendingLocalSeq will\n // be 'undefined' or > 'localSeq'.\n assert(!(pendingLocalSeq < localSeq),\n 0x023 /* \"The 'localSeq' of pending write (if any) must be <= the localSeq of the currently processed op.\" */);\n\n // If this is the most recent write to the cell by the local client, the stored localSeq\n // will be an exact match for the given 'localSeq'.\n return pendingLocalSeq === localSeq;\n }\n\n public toString() {\n let s = `client:${this.runtime.clientId}\\nrows: ${this.rows.toString()}\\ncols: ${this.cols.toString()}\\n\\n`;\n\n for (let r = 0; r < this.rowCount; r++) {\n s += ` [`;\n for (let c = 0; c < this.colCount; c++) {\n if (c > 0) {\n s += \", \";\n }\n\n s += `${this.serializer.stringify(this.getCell(r, c), this.handle)}`;\n }\n s += \"]\\n\";\n }\n\n return `${s}\\n`;\n }\n\n /**\n * {@inheritDoc @fluidframework/shared-object-base#SharedObjectCore.applyStashedOp}\n */\n protected applyStashedOp(content: any): unknown {\n if (content.target === SnapshotPath.cols || content.target === SnapshotPath.rows) {\n const op = content as IMergeTreeOp;\n const currentVector = content.target === SnapshotPath.cols ? this.cols : this.rows;\n const oppositeVector = content.target === SnapshotPath.cols ? this.rows : this.cols;\n const metadata = currentVector.applyStashedOp(op);\n const localSeq = currentVector.getCollabWindow().localSeq;\n const oppositeWindow = oppositeVector.getCollabWindow();\n\n assert(\n localSeq > oppositeWindow.localSeq,\n 0x2d9,\n /* \"The 'localSeq' of the vector applying stashed op must > the 'localSeq' of the other vector.\" */\n );\n\n oppositeWindow.localSeq = localSeq;\n\n return metadata;\n } else {\n assert(content.type === MatrixOp.set, 0x2da /* \"Unknown SharedMatrix 'op' type.\" */);\n\n const setOp = content as ISetOp<T>;\n const rowHandle = this.rows.getAllocatedHandle(setOp.row);\n const colHandle = this.cols.getAllocatedHandle(setOp.col);\n const rowsRefSeq = this.rows.getCollabWindow().currentSeq;\n const colsRefSeq = this.cols.getCollabWindow().currentSeq;\n if (this.undo !== undefined) {\n let oldValue = this.cells.getCell(rowHandle, colHandle);\n if (oldValue === null) {\n oldValue = undefined;\n }\n\n this.undo.cellSet(\n rowHandle,\n colHandle,\n oldValue);\n }\n\n this.cells.setCell(rowHandle, colHandle, setOp.value);\n const localSeq = this.nextLocalSeq();\n const metadata: ISetOpMetadata = {\n rowHandle,\n colHandle,\n localSeq,\n rowsRefSeq,\n colsRefSeq,\n };\n\n this.pending.setCell(rowHandle, colHandle, localSeq);\n return metadata;\n }\n }\n}\n"]}
@@ -5,5 +5,5 @@
5
5
  * THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY
6
6
  */
7
7
  export declare const pkgName = "@fluidframework/matrix";
8
- export declare const pkgVersion = "2.0.0-internal.2.4.0";
8
+ export declare const pkgVersion = "2.0.0-internal.3.0.0";
9
9
  //# sourceMappingURL=packageVersion.d.ts.map
@@ -8,5 +8,5 @@
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
9
  exports.pkgVersion = exports.pkgName = void 0;
10
10
  exports.pkgName = "@fluidframework/matrix";
11
- exports.pkgVersion = "2.0.0-internal.2.4.0";
11
+ exports.pkgVersion = "2.0.0-internal.3.0.0";
12
12
  //# sourceMappingURL=packageVersion.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"packageVersion.js","sourceRoot":"","sources":["../src/packageVersion.ts"],"names":[],"mappings":";AAAA;;;;;GAKG;;;AAEU,QAAA,OAAO,GAAG,wBAAwB,CAAC;AACnC,QAAA,UAAU,GAAG,sBAAsB,CAAC","sourcesContent":["/*!\n * Copyright (c) Microsoft Corporation and contributors. All rights reserved.\n * Licensed under the MIT License.\n *\n * THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY\n */\n\nexport const pkgName = \"@fluidframework/matrix\";\nexport const pkgVersion = \"2.0.0-internal.2.4.0\";\n"]}
1
+ {"version":3,"file":"packageVersion.js","sourceRoot":"","sources":["../src/packageVersion.ts"],"names":[],"mappings":";AAAA;;;;;GAKG;;;AAEU,QAAA,OAAO,GAAG,wBAAwB,CAAC;AACnC,QAAA,UAAU,GAAG,sBAAsB,CAAC","sourcesContent":["/*!\n * Copyright (c) Microsoft Corporation and contributors. All rights reserved.\n * Licensed under the MIT License.\n *\n * THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY\n */\n\nexport const pkgName = \"@fluidframework/matrix\";\nexport const pkgVersion = \"2.0.0-internal.3.0.0\";\n"]}
@@ -168,8 +168,8 @@ class PermutationVector extends merge_tree_1.Client {
168
168
  }
169
169
  }
170
170
  };
171
- this.mergeTreeDeltaCallback = this.onDelta;
172
- this.mergeTreeMaintenanceCallback = this.onMaintenance;
171
+ this.on("delta", this.onDelta);
172
+ this.on("maintenance", this.onMaintenance);
173
173
  }
174
174
  insert(start, length) {
175
175
  return this.insertSegmentLocal(start, new PermutationSegment(length));
@@ -204,7 +204,7 @@ class PermutationVector extends merge_tree_1.Client {
204
204
  return handle;
205
205
  }
206
206
  adjustPosition(pos, op) {
207
- const { segment, offset } = this.getContainingSegment(pos, op);
207
+ const { segment, offset } = this.getContainingSegment(pos, { referenceSequenceNumber: op.referenceSequenceNumber, clientId: op.clientId });
208
208
  // Note that until the MergeTree GCs, the segment is still reachable via `getContainingSegment()` with
209
209
  // a `refSeq` in the past. Prevent remote ops from accidentally allocating or using recycled handles
210
210
  // by checking for the presence of 'removedSeq'.
@@ -1 +1 @@
1
- {"version":3,"file":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AAC,IAAI,CAAC,OAAO,EAAE,IAAI,sCAAsB,CAAC,OAAO,4BAAwB,EAAE,UAAU,CAAC,CAAC;IACvG,CAAC;IA0FM,QAAQ;QACX,MAAM,CAAC,GAAa,EAAE,CAAC;QAEvB,IAAI,CAAC,YAAY,CAAC,CAAC,OAAO,EAAE,EAAE;YAC1B,CAAC,CAAC,IAAI,CAAC,GAAG,OAAO,EAAE,CAAC,CAAC;YACrB,OAAO,IAAI,CAAC;QAChB,CAAC,CAAC,CAAC;QAEH,OAAO,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;IACtB,CAAC;CACJ;AArQD,8CAqQC","sourcesContent":["/*!\n * Copyright (c) Microsoft Corporation and contributors. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { assert } from \"@fluidframework/common-utils\";\nimport { ChildLogger } from \"@fluidframework/telemetry-utils\";\nimport { IFluidDataStoreRuntime, IChannelStorageService } from \"@fluidframework/datastore-definitions\";\nimport { ITelemetryBaseLogger } from \"@fluidframework/common-definitions\";\nimport {\n BaseSegment,\n ISegment,\n Client,\n IMergeTreeDeltaOpArgs,\n IMergeTreeDeltaCallbackArgs,\n MergeTreeDeltaType,\n IMergeTreeMaintenanceCallbackArgs,\n MergeTreeMaintenanceType,\n ReferenceType,\n} from \"@fluidframework/merge-tree\";\nimport { IFluidHandle } from \"@fluidframework/core-interfaces\";\nimport { IFluidSerializer } from \"@fluidframework/shared-object-base\";\nimport { ISummaryTreeWithStats } from \"@fluidframework/runtime-definitions\";\nimport { ObjectStoragePartition, SummaryTreeBuilder } from \"@fluidframework/runtime-utils\";\nimport { ISequencedDocumentMessage } from \"@fluidframework/protocol-definitions\";\nimport { HandleTable, Handle, isHandleValid } from \"./handletable\";\nimport { deserializeBlob } from \"./serialization\";\nimport { HandleCache } from \"./handlecache\";\nimport { VectorUndoProvider } from \"./undoprovider\";\n\nconst enum SnapshotPath {\n segments = \"segments\",\n handleTable = \"handleTable\",\n}\n\ntype PermutationSegmentSpec = [number, number];\n\nexport class PermutationSegment extends BaseSegment {\n public static readonly typeString: string = \"PermutationSegment\";\n private _start = Handle.unallocated;\n\n public static fromJSONObject(spec: any) {\n const [length, start] = spec as PermutationSegmentSpec;\n return new PermutationSegment(length, start);\n }\n\n public readonly type = PermutationSegment.typeString;\n\n constructor(length: number, start = Handle.unallocated) {\n super();\n this._start = start;\n this.cachedLength = length;\n }\n\n public get start() { return this._start; }\n public set start(value: Handle) {\n assert(this._start === Handle.unallocated, 0x024 /* \"Start of PermutationSegment already allocated!\" */);\n assert(isHandleValid(value), 0x025 /* \"Trying to set start of PermutationSegment to invalid handle!\" */);\n\n this._start = value;\n }\n\n /**\n * Invoked by '_undoRow/ColRemove' to prepare the newly inserted destination\n * segment to serve as the replacement for this removed segment. This moves handle\n * allocations from this segment to the replacement as well as maintains tracking\n * groups for the undo/redo stack.\n */\n public transferToReplacement(destination: PermutationSegment) {\n // When this segment was removed, it may have been split from a larger original\n // segment. In this case, it will have been added to an undo/redo tracking group\n // that associates all of the fragments from the original insertion.\n //\n // Move this association from the this removed segment to its replacement so that\n // it is included if the undo stack continues to unwind to the original insertion.\n //\n // Out of paranoia we link and unlink in separate loops to avoid mutating the underlying\n // set during enumeration. In practice, this is unlikely to matter since there should be\n // exactly 0 or 1 items in the enumeration.\n for (const group of this.trackingCollection.trackingGroups) {\n group.link(destination);\n }\n for (const group of this.trackingCollection.trackingGroups) {\n group.unlink(this);\n }\n\n // Move handle allocations from this segment to its replacement.\n destination._start = this._start;\n this.reset();\n }\n\n public reset() {\n this._start = Handle.unallocated;\n }\n\n public toJSONObject() {\n return [this.cachedLength, this.start];\n }\n\n public clone(start = 0, end = this.cachedLength) {\n const b = new PermutationSegment(\n /* length: */ end - start,\n /* start: */ this.start + start);\n this.cloneInto(b);\n return b;\n }\n\n public canAppend(segment: ISegment) {\n const asPerm = segment as PermutationSegment;\n\n return this.start === Handle.unallocated\n ? asPerm.start === Handle.unallocated\n : asPerm.start === this.start + this.cachedLength;\n }\n\n protected createSplitSegmentAt(pos: number) {\n assert(0 < pos && pos < this.cachedLength, 0x026 /* \"Trying to split segment at out-of-bounds position!\" */);\n\n const leafSegment = new PermutationSegment(\n /* length: */ this.cachedLength - pos,\n /* start: */ this.start === Handle.unallocated\n ? Handle.unallocated\n : this.start + pos);\n\n this.cachedLength = pos;\n\n return leafSegment;\n }\n\n public toString() {\n return this.start === Handle.unallocated\n ? `<${this.cachedLength} empty>`\n : `<${this.cachedLength}: ${this.start}..${this.start + this.cachedLength - 1}>`;\n }\n}\n\nexport class PermutationVector extends Client {\n private handleTable = new HandleTable<never>(); // Tracks available storage handles for rows.\n public readonly handleCache = new HandleCache(this);\n public undo: VectorUndoProvider | undefined;\n\n constructor(\n path: string,\n logger: ITelemetryBaseLogger,\n runtime: IFluidDataStoreRuntime,\n private readonly deltaCallback: (position: number, numRemoved: number, numInserted: number) => void,\n private readonly handlesRecycledCallback: (handles: Handle[]) => void,\n ) {\n super(\n PermutationSegment.fromJSONObject,\n ChildLogger.create(logger, `Matrix.${path}.MergeTreeClient`), {\n ...runtime.options,\n newMergeTreeSnapshotFormat: true, // Temporarily force new snapshot format until it is the default.\n }); // (See https://github.com/microsoft/FluidFramework/issues/84)\n\n this.mergeTreeDeltaCallback = this.onDelta;\n this.mergeTreeMaintenanceCallback = this.onMaintenance;\n }\n\n public insert(start: number, length: number) {\n return this.insertSegmentLocal(\n start,\n new PermutationSegment(length));\n }\n\n public insertRelative(segment: ISegment, length: number) {\n const inserted = new PermutationSegment(length);\n\n return {\n op: this.insertAtReferencePositionLocal(\n this.createLocalReferencePosition(segment, 0, ReferenceType.Transient, undefined),\n inserted),\n inserted,\n };\n }\n\n public remove(start: number, length: number) {\n return this.removeRangeLocal(start, start + length);\n }\n\n public getMaybeHandle(pos: number): Handle {\n assert(0 <= pos && pos < this.getLength(), 0x027 /* \"Trying to get handle of out-of-bounds position!\" */);\n\n return this.handleCache.getHandle(pos);\n }\n\n public getAllocatedHandle(pos: number): Handle {\n let handle = this.getMaybeHandle(pos);\n if (isHandleValid(handle)) {\n return handle;\n }\n\n this.walkSegments(\n (segment) => {\n const asPerm = segment as PermutationSegment;\n asPerm.start = handle = this.handleTable.allocate();\n return true;\n },\n pos,\n pos + 1,\n /* accum: */ undefined,\n /* splitRange: */ true);\n\n this.handleCache.addHandle(pos, handle);\n\n return handle;\n }\n\n public adjustPosition(pos: number, op: ISequencedDocumentMessage) {\n const { segment, offset } = this.getContainingSegment(pos, op);\n\n // Note that until the MergeTree GCs, the segment is still reachable via `getContainingSegment()` with\n // a `refSeq` in the past. Prevent remote ops from accidentally allocating or using recycled handles\n // by checking for the presence of 'removedSeq'.\n if (segment === undefined || segment.removedSeq !== undefined) {\n return undefined;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n return this.getPosition(segment) + offset!;\n }\n\n public handleToPosition(handle: Handle, localSeq = this.getCollabWindow().localSeq) {\n assert(localSeq <= this.getCollabWindow().localSeq,\n 0x028 /* \"'localSeq' for op being resubmitted must be <= the 'localSeq' of the last submitted op.\" */);\n\n // TODO: In theory, the MergeTree should be able to map the (position, refSeq, localSeq) from\n // the original operation to the current position for undo/redo scenarios. This is probably the\n // ideal solution, as we would no longer need to store row/col handles in the op metadata.\n //\n // Failing that, we could avoid the O(n) search below by building a temporary map in the\n // opposite direction from the handle to either it's current position or segment + offset\n // and reuse it for the duration of undo/redo. (Ideally, we would know when the undo/redo\n // ended so we could discard this map.)\n //\n // If we find that we frequently need a reverse handle -> position lookup, we could maintain\n // one using the Tiny-Calc adjust tree.\n let containingSegment!: PermutationSegment;\n let containingOffset: number;\n\n this.walkAllSegments(\n (segment) => {\n const { start, cachedLength } = segment as PermutationSegment;\n\n // If the segment is unallocated, skip it.\n if (!isHandleValid(start)) {\n return true;\n }\n\n const end = start + cachedLength;\n\n if (start <= handle && handle < end) {\n containingSegment = segment as PermutationSegment;\n containingOffset = handle - start;\n return false;\n }\n\n return true;\n });\n\n // We are guaranteed to find the handle in the PermutationVector, even if the corresponding\n // row/col has been removed, because handles are not recycled until the containing segment\n // is unlinked from the MergeTree.\n //\n // Therefore, either a row/col removal has been ACKed, in which case there will be no pending\n // ops that reference the stale handle, or the removal is unACKed, in which case the handle\n // has not yet been recycled.\n\n assert(isHandleValid(containingSegment.start), 0x029 /* \"Invalid handle at start of containing segment!\" */);\n\n // Once we know the current position of the handle, we can use the MergeTree to get the segment\n // containing this position and use 'findReconnectionPosition' to adjust for the local ops that\n // have not yet been submitted.\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n return this.findReconnectionPosition(containingSegment, localSeq) + containingOffset!;\n }\n\n // Constructs an ISummaryTreeWithStats for the cell data.\n public summarize(runtime: IFluidDataStoreRuntime, handle: IFluidHandle, serializer: IFluidSerializer):\n ISummaryTreeWithStats {\n const builder = new SummaryTreeBuilder();\n builder.addWithStats(SnapshotPath.segments, super.summarize(runtime, handle, serializer, /* catchUpMsgs: */[]));\n builder.addBlob(SnapshotPath.handleTable, serializer.stringify(this.handleTable.getSummaryContent(), handle));\n return builder.getSummaryTree();\n }\n\n public async load(\n runtime: IFluidDataStoreRuntime,\n storage: IChannelStorageService,\n serializer: IFluidSerializer,\n ) {\n const handleTableData = await deserializeBlob(storage, SnapshotPath.handleTable, serializer);\n\n this.handleTable = HandleTable.load<never>(handleTableData);\n\n return super.load(runtime, new ObjectStoragePartition(storage, SnapshotPath.segments), serializer);\n }\n\n private readonly onDelta = (\n opArgs: IMergeTreeDeltaOpArgs,\n { operation, deltaSegments }: IMergeTreeDeltaCallbackArgs,\n ) => {\n // Apply deltas in descending order to prevent positions from shifting.\n const ranges = deltaSegments\n .map(({ segment }) => ({\n segment: segment as PermutationSegment,\n position: this.getPosition(segment),\n }))\n .sort((left, right) => left.position - right.position);\n\n const isLocal = opArgs.sequencedMessage === undefined;\n\n // Notify the undo provider, if any is attached.\n if (this.undo !== undefined && isLocal) {\n this.undo.record(operation, ranges);\n }\n\n switch (operation) {\n case MergeTreeDeltaType.INSERT:\n // Pass 1: Perform any internal maintenance first to avoid reentrancy.\n for (const { segment, position } of ranges) {\n // HACK: We need to include the allocated handle in the segment's JSON representation\n // for snapshots, but need to ignore the remote client's handle allocations when\n // processing remote ops.\n segment.reset();\n\n this.handleCache.itemsChanged(\n position,\n /* deleteCount: */ 0,\n /* insertCount: */ segment.cachedLength);\n }\n\n // Pass 2: Notify the 'deltaCallback', which may involve callbacks into user code.\n for (const { segment, position } of ranges) {\n this.deltaCallback(position, /* numRemoved: */ 0, /* numInserted: */ segment.cachedLength);\n }\n break;\n\n case MergeTreeDeltaType.REMOVE: {\n // Pass 1: Perform any internal maintenance first to avoid reentrancy.\n for (const { segment, position } of ranges) {\n this.handleCache.itemsChanged(\n position, /* deleteCount: */\n segment.cachedLength,\n /* insertCount: */ 0);\n }\n\n // Pass 2: Notify the 'deltaCallback', which may involve callbacks into user code.\n for (const { segment, position } of ranges) {\n this.deltaCallback(position, /* numRemoved: */ segment.cachedLength, /* numInsert: */ 0);\n }\n break;\n }\n\n default:\n throw new Error(\"Unhandled MergeTreeDeltaType\");\n }\n };\n\n private readonly onMaintenance = (args: IMergeTreeMaintenanceCallbackArgs) => {\n if (args.operation === MergeTreeMaintenanceType.UNLINK) {\n let freed: number[] = [];\n\n for (const { segment } of args.deltaSegments) {\n const asPerm = segment as PermutationSegment;\n if (isHandleValid(asPerm.start)) {\n // Note: Using the spread operator with `.splice()` can exhaust the stack.\n freed = freed.concat(\n new Array(asPerm.cachedLength)\n .fill(0)\n .map((value, index) => index + asPerm.start),\n );\n }\n }\n\n // Notify matrix that handles are about to be freed. The matrix is responsible for clearing\n // the rows/cols prior to free to ensure recycled row/cols are initially empty.\n this.handlesRecycledCallback(freed);\n\n // Now that the physical storage has been cleared, add the recycled handles back to the free pool.\n for (const handle of freed) {\n this.handleTable.free(handle);\n }\n }\n };\n\n public toString() {\n const s: string[] = [];\n\n this.walkSegments((segment) => {\n s.push(`${segment}`);\n return true;\n });\n\n return s.join(\"\");\n }\n}\n"]}
1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O,mCAA4B,UAAU,CAAC,CAAC;QAE7F,IAAI,CAAC,WAAW,GAAG,yBAAW,CAAC,IAAI,CAAQ,eAAe,CAAC,CAAC;QAE5D,OAAO,KAAK,CAAC,IAAI,CAAC,OAAO,EAAE,IAAI,sCAAsB,CAAC,OAAO,4BAAwB,EAAE,UAAU,CAAC,CAAC;IACvG,CAAC;IA0FM,QAAQ;QACX,MAAM,CAAC,GAAa,EAAE,CAAC;QAEvB,IAAI,CAAC,YAAY,CAAC,CAAC,OAAO,EAAE,EAAE;YAC1B,CAAC,CAAC,IAAI,CAAC,GAAG,OAAO,EAAE,CAAC,CAAC;YACrB,OAAO,IAAI,CAAC;QAChB,CAAC,CAAC,CAAC;QAEH,OAAO,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;IACtB,CAAC;CACJ;AArQD,8CAqQC","sourcesContent":["/*!\n * Copyright (c) Microsoft Corporation and contributors. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { assert } from \"@fluidframework/common-utils\";\nimport { ChildLogger } from \"@fluidframework/telemetry-utils\";\nimport { IFluidDataStoreRuntime, IChannelStorageService } from \"@fluidframework/datastore-definitions\";\nimport { ITelemetryBaseLogger } from \"@fluidframework/common-definitions\";\nimport {\n BaseSegment,\n ISegment,\n Client,\n IMergeTreeDeltaOpArgs,\n IMergeTreeDeltaCallbackArgs,\n MergeTreeDeltaType,\n IMergeTreeMaintenanceCallbackArgs,\n MergeTreeMaintenanceType,\n ReferenceType,\n} from \"@fluidframework/merge-tree\";\nimport { IFluidHandle } from \"@fluidframework/core-interfaces\";\nimport { IFluidSerializer } from \"@fluidframework/shared-object-base\";\nimport { ISummaryTreeWithStats } from \"@fluidframework/runtime-definitions\";\nimport { ObjectStoragePartition, SummaryTreeBuilder } from \"@fluidframework/runtime-utils\";\nimport { ISequencedDocumentMessage } from \"@fluidframework/protocol-definitions\";\nimport { HandleTable, Handle, isHandleValid } from \"./handletable\";\nimport { deserializeBlob } from \"./serialization\";\nimport { HandleCache } from \"./handlecache\";\nimport { VectorUndoProvider } from \"./undoprovider\";\n\nconst enum SnapshotPath {\n segments = \"segments\",\n handleTable = \"handleTable\",\n}\n\ntype PermutationSegmentSpec = [number, number];\n\nexport class PermutationSegment extends BaseSegment {\n public static readonly typeString: string = \"PermutationSegment\";\n private _start = Handle.unallocated;\n\n public static fromJSONObject(spec: any) {\n const [length, start] = spec as PermutationSegmentSpec;\n return new PermutationSegment(length, start);\n }\n\n public readonly type = PermutationSegment.typeString;\n\n constructor(length: number, start = Handle.unallocated) {\n super();\n this._start = start;\n this.cachedLength = length;\n }\n\n public get start() { return this._start; }\n public set start(value: Handle) {\n assert(this._start === Handle.unallocated, 0x024 /* \"Start of PermutationSegment already allocated!\" */);\n assert(isHandleValid(value), 0x025 /* \"Trying to set start of PermutationSegment to invalid handle!\" */);\n\n this._start = value;\n }\n\n /**\n * Invoked by '_undoRow/ColRemove' to prepare the newly inserted destination\n * segment to serve as the replacement for this removed segment. This moves handle\n * allocations from this segment to the replacement as well as maintains tracking\n * groups for the undo/redo stack.\n */\n public transferToReplacement(destination: PermutationSegment) {\n // When this segment was removed, it may have been split from a larger original\n // segment. In this case, it will have been added to an undo/redo tracking group\n // that associates all of the fragments from the original insertion.\n //\n // Move this association from the this removed segment to its replacement so that\n // it is included if the undo stack continues to unwind to the original insertion.\n //\n // Out of paranoia we link and unlink in separate loops to avoid mutating the underlying\n // set during enumeration. In practice, this is unlikely to matter since there should be\n // exactly 0 or 1 items in the enumeration.\n for (const group of this.trackingCollection.trackingGroups) {\n group.link(destination);\n }\n for (const group of this.trackingCollection.trackingGroups) {\n group.unlink(this);\n }\n\n // Move handle allocations from this segment to its replacement.\n destination._start = this._start;\n this.reset();\n }\n\n public reset() {\n this._start = Handle.unallocated;\n }\n\n public toJSONObject() {\n return [this.cachedLength, this.start];\n }\n\n public clone(start = 0, end = this.cachedLength) {\n const b = new PermutationSegment(\n /* length: */ end - start,\n /* start: */ this.start + start);\n this.cloneInto(b);\n return b;\n }\n\n public canAppend(segment: ISegment) {\n const asPerm = segment as PermutationSegment;\n\n return this.start === Handle.unallocated\n ? asPerm.start === Handle.unallocated\n : asPerm.start === this.start + this.cachedLength;\n }\n\n protected createSplitSegmentAt(pos: number) {\n assert(0 < pos && pos < this.cachedLength, 0x026 /* \"Trying to split segment at out-of-bounds position!\" */);\n\n const leafSegment = new PermutationSegment(\n /* length: */ this.cachedLength - pos,\n /* start: */ this.start === Handle.unallocated\n ? Handle.unallocated\n : this.start + pos);\n\n this.cachedLength = pos;\n\n return leafSegment;\n }\n\n public toString() {\n return this.start === Handle.unallocated\n ? `<${this.cachedLength} empty>`\n : `<${this.cachedLength}: ${this.start}..${this.start + this.cachedLength - 1}>`;\n }\n}\n\nexport class PermutationVector extends Client {\n private handleTable = new HandleTable<never>(); // Tracks available storage handles for rows.\n public readonly handleCache = new HandleCache(this);\n public undo: VectorUndoProvider | undefined;\n\n constructor(\n path: string,\n logger: ITelemetryBaseLogger,\n runtime: IFluidDataStoreRuntime,\n private readonly deltaCallback: (position: number, numRemoved: number, numInserted: number) => void,\n private readonly handlesRecycledCallback: (handles: Handle[]) => void,\n ) {\n super(\n PermutationSegment.fromJSONObject,\n ChildLogger.create(logger, `Matrix.${path}.MergeTreeClient`), {\n ...runtime.options,\n newMergeTreeSnapshotFormat: true, // Temporarily force new snapshot format until it is the default.\n }); // (See https://github.com/microsoft/FluidFramework/issues/84)\n\n this.on(\"delta\", this.onDelta);\n this.on(\"maintenance\", this.onMaintenance);\n }\n\n public insert(start: number, length: number) {\n return this.insertSegmentLocal(\n start,\n new PermutationSegment(length));\n }\n\n public insertRelative(segment: ISegment, length: number) {\n const inserted = new PermutationSegment(length);\n\n return {\n op: this.insertAtReferencePositionLocal(\n this.createLocalReferencePosition(segment, 0, ReferenceType.Transient, undefined),\n inserted),\n inserted,\n };\n }\n\n public remove(start: number, length: number) {\n return this.removeRangeLocal(start, start + length);\n }\n\n public getMaybeHandle(pos: number): Handle {\n assert(0 <= pos && pos < this.getLength(), 0x027 /* \"Trying to get handle of out-of-bounds position!\" */);\n\n return this.handleCache.getHandle(pos);\n }\n\n public getAllocatedHandle(pos: number): Handle {\n let handle = this.getMaybeHandle(pos);\n if (isHandleValid(handle)) {\n return handle;\n }\n\n this.walkSegments(\n (segment) => {\n const asPerm = segment as PermutationSegment;\n asPerm.start = handle = this.handleTable.allocate();\n return true;\n },\n pos,\n pos + 1,\n /* accum: */ undefined,\n /* splitRange: */ true);\n\n this.handleCache.addHandle(pos, handle);\n\n return handle;\n }\n\n public adjustPosition(pos: number, op: ISequencedDocumentMessage) {\n const { segment, offset } = this.getContainingSegment(pos, { referenceSequenceNumber: op.referenceSequenceNumber, clientId: op.clientId });\n\n // Note that until the MergeTree GCs, the segment is still reachable via `getContainingSegment()` with\n // a `refSeq` in the past. Prevent remote ops from accidentally allocating or using recycled handles\n // by checking for the presence of 'removedSeq'.\n if (segment === undefined || segment.removedSeq !== undefined) {\n return undefined;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n return this.getPosition(segment) + offset!;\n }\n\n public handleToPosition(handle: Handle, localSeq = this.getCollabWindow().localSeq) {\n assert(localSeq <= this.getCollabWindow().localSeq,\n 0x028 /* \"'localSeq' for op being resubmitted must be <= the 'localSeq' of the last submitted op.\" */);\n\n // TODO: In theory, the MergeTree should be able to map the (position, refSeq, localSeq) from\n // the original operation to the current position for undo/redo scenarios. This is probably the\n // ideal solution, as we would no longer need to store row/col handles in the op metadata.\n //\n // Failing that, we could avoid the O(n) search below by building a temporary map in the\n // opposite direction from the handle to either it's current position or segment + offset\n // and reuse it for the duration of undo/redo. (Ideally, we would know when the undo/redo\n // ended so we could discard this map.)\n //\n // If we find that we frequently need a reverse handle -> position lookup, we could maintain\n // one using the Tiny-Calc adjust tree.\n let containingSegment!: PermutationSegment;\n let containingOffset: number;\n\n this.walkAllSegments(\n (segment) => {\n const { start, cachedLength } = segment as PermutationSegment;\n\n // If the segment is unallocated, skip it.\n if (!isHandleValid(start)) {\n return true;\n }\n\n const end = start + cachedLength;\n\n if (start <= handle && handle < end) {\n containingSegment = segment as PermutationSegment;\n containingOffset = handle - start;\n return false;\n }\n\n return true;\n });\n\n // We are guaranteed to find the handle in the PermutationVector, even if the corresponding\n // row/col has been removed, because handles are not recycled until the containing segment\n // is unlinked from the MergeTree.\n //\n // Therefore, either a row/col removal has been ACKed, in which case there will be no pending\n // ops that reference the stale handle, or the removal is unACKed, in which case the handle\n // has not yet been recycled.\n\n assert(isHandleValid(containingSegment.start), 0x029 /* \"Invalid handle at start of containing segment!\" */);\n\n // Once we know the current position of the handle, we can use the MergeTree to get the segment\n // containing this position and use 'findReconnectionPosition' to adjust for the local ops that\n // have not yet been submitted.\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n return this.findReconnectionPosition(containingSegment, localSeq) + containingOffset!;\n }\n\n // Constructs an ISummaryTreeWithStats for the cell data.\n public summarize(runtime: IFluidDataStoreRuntime, handle: IFluidHandle, serializer: IFluidSerializer):\n ISummaryTreeWithStats {\n const builder = new SummaryTreeBuilder();\n builder.addWithStats(SnapshotPath.segments, super.summarize(runtime, handle, serializer, /* catchUpMsgs: */[]));\n builder.addBlob(SnapshotPath.handleTable, serializer.stringify(this.handleTable.getSummaryContent(), handle));\n return builder.getSummaryTree();\n }\n\n public async load(\n runtime: IFluidDataStoreRuntime,\n storage: IChannelStorageService,\n serializer: IFluidSerializer,\n ) {\n const handleTableData = await deserializeBlob(storage, SnapshotPath.handleTable, serializer);\n\n this.handleTable = HandleTable.load<never>(handleTableData);\n\n return super.load(runtime, new ObjectStoragePartition(storage, SnapshotPath.segments), serializer);\n }\n\n private readonly onDelta = (\n opArgs: IMergeTreeDeltaOpArgs,\n { operation, deltaSegments }: IMergeTreeDeltaCallbackArgs,\n ) => {\n // Apply deltas in descending order to prevent positions from shifting.\n const ranges = deltaSegments\n .map(({ segment }) => ({\n segment: segment as PermutationSegment,\n position: this.getPosition(segment),\n }))\n .sort((left, right) => left.position - right.position);\n\n const isLocal = opArgs.sequencedMessage === undefined;\n\n // Notify the undo provider, if any is attached.\n if (this.undo !== undefined && isLocal) {\n this.undo.record(operation, ranges);\n }\n\n switch (operation) {\n case MergeTreeDeltaType.INSERT:\n // Pass 1: Perform any internal maintenance first to avoid reentrancy.\n for (const { segment, position } of ranges) {\n // HACK: We need to include the allocated handle in the segment's JSON representation\n // for snapshots, but need to ignore the remote client's handle allocations when\n // processing remote ops.\n segment.reset();\n\n this.handleCache.itemsChanged(\n position,\n /* deleteCount: */ 0,\n /* insertCount: */ segment.cachedLength);\n }\n\n // Pass 2: Notify the 'deltaCallback', which may involve callbacks into user code.\n for (const { segment, position } of ranges) {\n this.deltaCallback(position, /* numRemoved: */ 0, /* numInserted: */ segment.cachedLength);\n }\n break;\n\n case MergeTreeDeltaType.REMOVE: {\n // Pass 1: Perform any internal maintenance first to avoid reentrancy.\n for (const { segment, position } of ranges) {\n this.handleCache.itemsChanged(\n position, /* deleteCount: */\n segment.cachedLength,\n /* insertCount: */ 0);\n }\n\n // Pass 2: Notify the 'deltaCallback', which may involve callbacks into user code.\n for (const { segment, position } of ranges) {\n this.deltaCallback(position, /* numRemoved: */ segment.cachedLength, /* numInsert: */ 0);\n }\n break;\n }\n\n default:\n throw new Error(\"Unhandled MergeTreeDeltaType\");\n }\n };\n\n private readonly onMaintenance = (args: IMergeTreeMaintenanceCallbackArgs) => {\n if (args.operation === MergeTreeMaintenanceType.UNLINK) {\n let freed: number[] = [];\n\n for (const { segment } of args.deltaSegments) {\n const asPerm = segment as PermutationSegment;\n if (isHandleValid(asPerm.start)) {\n // Note: Using the spread operator with `.splice()` can exhaust the stack.\n freed = freed.concat(\n new Array(asPerm.cachedLength)\n .fill(0)\n .map((value, index) => index + asPerm.start),\n );\n }\n }\n\n // Notify matrix that handles are about to be freed. The matrix is responsible for clearing\n // the rows/cols prior to free to ensure recycled row/cols are initially empty.\n this.handlesRecycledCallback(freed);\n\n // Now that the physical storage has been cleared, add the recycled handles back to the free pool.\n for (const handle of freed) {\n this.handleTable.free(handle);\n }\n }\n };\n\n public toString() {\n const s: string[] = [];\n\n this.walkSegments((segment) => {\n s.push(`${segment}`);\n return true;\n });\n\n return s.join(\"\");\n }\n}\n"]}
package/lib/matrix.d.ts CHANGED
@@ -82,6 +82,7 @@ export declare class SharedMatrix<T = any> extends SharedObject implements IMatr
82
82
  protected submitLocalMessage(message: any, localOpMetadata?: any): void;
83
83
  protected didAttach(): void;
84
84
  protected onConnect(): void;
85
+ private rebasePosition;
85
86
  protected reSubmitCore(content: any, localOpMetadata: unknown): void;
86
87
  protected onDisconnect(): void;
87
88
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"matrix.d.ts","sourceRoot":"","sources":["../src/matrix.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAGH,OAAO,EAAE,yBAAyB,EAAE,MAAM,sCAAsC,CAAC;AACjF,OAAO,EACH,sBAAsB,EACtB,sBAAsB,EACtB,YAAY,EACZ,kBAAkB,EACrB,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EACH,gBAAgB,EAGhB,YAAY,EACZ,iBAAiB,EACpB,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EAAE,qBAAqB,EAAE,MAAM,qCAAqC,CAAC;AAE5E,OAAO,EACH,eAAe,EACf,eAAe,EACf,aAAa,EACb,aAAa,EAChB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAkD,QAAQ,EAAE,MAAM,4BAA4B,CAAC;AAItG,OAAO,EAAE,mBAAmB,EAAE,MAAM,WAAW,CAAC;AAIhD,OAAO,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAwBxC;;;GAGG;AACH,oBAAY,UAAU,CAAC,CAAC,IAAI,YAAY,CAAC,OAAO,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC,GAAG,SAAS,CAAC;AAEvE;;;;;;;;;;;GAWG;AACH,qBAAa,YAAY,CAAC,CAAC,GAAG,GAAG,CAC7B,SAAQ,YACR,YAAW,eAAe,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AAO,CAAC,QAAQ,CAAC,oBAAoB,CAKnC;IAEF,OAAO,CAAC,QAAQ,CAAC,oBAAoB,CAKnC;IAEF;;;;;;;OAOG;IACH,OAAO,CAAC,oBAAoB;IAerB,QAAQ;IAkBf;;OAEG;IACH,SAAS,CAAC,cAAc,CAAC,OAAO,EAAE,GAAG,GAAG,OAAO;CAoDlD"}
package/lib/matrix.js CHANGED
@@ -329,6 +329,14 @@ export class SharedMatrix extends SharedObject {
329
329
  this.rows.startOrUpdateCollaboration(this.runtime.clientId);
330
330
  this.cols.startOrUpdateCollaboration(this.runtime.clientId);
331
331
  }
332
+ rebasePosition(client, pos, referenceSequenceNumber, localSeq) {
333
+ const { clientId } = client.getCollabWindow();
334
+ const { segment, offset } = client.getContainingSegment(pos, { referenceSequenceNumber, clientId: client.getLongClientId(clientId) }, localSeq);
335
+ if (segment === undefined || offset === undefined) {
336
+ return;
337
+ }
338
+ return client.findReconnectionPosition(segment, localSeq) + offset;
339
+ }
332
340
  reSubmitCore(content, localOpMetadata) {
333
341
  switch (content.target) {
334
342
  case "cols" /* cols */:
@@ -345,8 +353,8 @@ export class SharedMatrix extends SharedObject {
345
353
  // to skip resubmitting this op since it is possible the row/col handle has been recycled
346
354
  // and now refers to a different position than when this op was originally submitted.
347
355
  if (this.isLatestPendingWrite(rowHandle, colHandle, localSeq)) {
348
- const row = this.rows.rebasePositionWithoutSegmentSlide(setOp.row, rowsRefSeq, localSeq);
349
- const col = this.cols.rebasePositionWithoutSegmentSlide(setOp.col, colsRefSeq, localSeq);
356
+ const row = this.rebasePosition(this.rows, setOp.row, rowsRefSeq, localSeq);
357
+ const col = this.rebasePosition(this.cols, setOp.col, colsRefSeq, localSeq);
350
358
  if (row !== undefined && col !== undefined && row >= 0 && col >= 0) {
351
359
  this.sendSetCellOp(row, col, setOp.value, rowHandle, colHandle, localSeq, rowsRefSeq, colsRefSeq);
352
360
  }
@@ -430,9 +438,7 @@ export class SharedMatrix extends SharedObject {
430
438
  // Note while we're awaiting the ACK for a local set, it's possible for the row/col to be
431
439
  // locally removed and the row/col handles recycled. If this happens, the pendingLocalSeq will
432
440
  // be 'undefined' or > 'localSeq'.
433
- assert(!(pendingLocalSeq < localSeq),
434
- // eslint-disable-next-line max-len
435
- 0x023 /* "The 'localSeq' of pending write (if any) must be <= the localSeq of the currently processed op." */);
441
+ assert(!(pendingLocalSeq < localSeq), 0x023 /* "The 'localSeq' of pending write (if any) must be <= the localSeq of the currently processed op." */);
436
442
  // If this is the most recent write to the cell by the local client, the stored localSeq
437
443
  // will be an exact match for the given 'localSeq'.
438
444
  return pendingLocalSeq === localSeq;
package/lib/matrix.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"matrix.js","sourceRoot":"","sources":["../src/matrix.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,MAAM,EAAE,MAAM,8BAA8B,CAAC;AAQtD,OAAO,EAEH,uBAAuB,EACvB,YAAY,EACZ,YAAY,GAEf,MAAM,oCAAoC,CAAC;AAE5C,OAAO,EAAE,sBAAsB,EAAE,kBAAkB,EAAE,MAAM,+BAA+B,CAAC;AAO3F,OAAO,EAAE,kBAAkB,EAAwC,MAAM,4BAA4B,CAAC;AACtG,OAAO,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AACjC,OAAO,EAAE,iBAAiB,EAAsB,MAAM,qBAAqB,CAAC;AAC5E,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAChD,OAAO,EAAE,mBAAmB,EAAE,MAAM,WAAW,CAAC;AAChD,OAAO,EAAU,aAAa,EAAE,MAAM,eAAe,CAAC;AACtD,OAAO,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAClD,OAAO,EAAE,WAAW,EAAE,MAAM,SAAS,CAAC;AAEtC,OAAO,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AA6BpD;;;;;;;;;;;GAWG;AACH,MAAM,OAAO,YACT,SAAQ,YAAY;IAcpB,YAA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AAI,CAAC,IAAI,CAAC,kBAAkB,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;YAC1D,MAAM,SAAS,GAAG,IAAI,CAAC,IAAI,CAAC,kBAAkB,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;YAC1D,MAAM,UAAU,GAAG,IAAI,CAAC,IAAI,CAAC,eAAe,EAAE,CAAC,UAAU,CAAC;YAC1D,MAAM,UAAU,GAAG,IAAI,CAAC,IAAI,CAAC,eAAe,EAAE,CAAC,UAAU,CAAC;YAC1D,IAAI,IAAI,CAAC,IAAI,KAAK,SAAS,EAAE;gBACzB,IAAI,QAAQ,GAAG,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,SAAS,EAAE,SAAS,CAAC,CAAC;gBACxD,IAAI,QAAQ,KAAK,IAAI,EAAE;oBACnB,QAAQ,GAAG,SAAS,CAAC;iBACxB;gBAED,IAAI,CAAC,IAAI,CAAC,OAAO,CACb,SAAS,EACT,SAAS,EACT,QAAQ,CAAC,CAAC;aACjB;YAED,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,SAAS,EAAE,SAAS,EAAE,KAAK,CAAC,KAAK,CAAC,CAAC;YACtD,MAAM,QAAQ,GAAG,IAAI,CAAC,YAAY,EAAE,CAAC;YACrC,MAAM,QAAQ,GAAmB;gBAC7B,SAAS;gBACT,SAAS;gBACT,QAAQ;gBACR,UAAU;gBACV,UAAU;aACb,CAAC;YAEF,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,SAAS,EAAE,SAAS,EAAE,QAAQ,CAAC,CAAC;YACrD,OAAO,QAAQ,CAAC;SACnB;IACL,CAAC;CACJ","sourcesContent":["/*!\n * Copyright (c) Microsoft Corporation and contributors. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { assert } from \"@fluidframework/common-utils\";\nimport { ISequencedDocumentMessage } from \"@fluidframework/protocol-definitions\";\nimport {\n IFluidDataStoreRuntime,\n IChannelStorageService,\n Serializable,\n IChannelAttributes,\n} from \"@fluidframework/datastore-definitions\";\nimport {\n IFluidSerializer,\n makeHandlesSerializable,\n parseHandles,\n SharedObject,\n SummarySerializer,\n} from \"@fluidframework/shared-object-base\";\nimport { ISummaryTreeWithStats } from \"@fluidframework/runtime-definitions\";\nimport { ObjectStoragePartition, SummaryTreeBuilder } from \"@fluidframework/runtime-utils\";\nimport {\n IMatrixProducer,\n IMatrixConsumer,\n IMatrixReader,\n IMatrixWriter,\n} from \"@tiny-calc/nano\";\nimport { MergeTreeDeltaType, IMergeTreeOp, SegmentGroup, ISegment } from \"@fluidframework/merge-tree\";\nimport { MatrixOp } from \"./ops\";\nimport { PermutationVector, PermutationSegment } from \"./permutationvector\";\nimport { SparseArray2D } from \"./sparsearray2d\";\nimport { SharedMatrixFactory } from \"./runtime\";\nimport { Handle, isHandleValid } from \"./handletable\";\nimport { deserializeBlob } from \"./serialization\";\nimport { ensureRange } from \"./range\";\nimport { IUndoConsumer } from \"./types\";\nimport { MatrixUndoProvider } from \"./undoprovider\";\n\nconst enum SnapshotPath {\n rows = \"rows\",\n cols = \"cols\",\n cells = \"cells\",\n}\n\ninterface ISetOp<T> {\n type: MatrixOp.set;\n row: number;\n col: number;\n value: MatrixItem<T>;\n}\n\ninterface ISetOpMetadata {\n rowHandle: Handle;\n colHandle: Handle;\n localSeq: number;\n rowsRefSeq: number;\n colsRefSeq: number;\n}\n\n/**\n * A matrix cell value may be undefined (indicating an empty cell) or any serializable type,\n * excluding null. (However, nulls may be embedded inside objects and arrays.)\n */\nexport type MatrixItem<T> = Serializable<Exclude<T, null>> | undefined;\n\n/**\n * A SharedMatrix holds a rectangular 2D array of values. Supported operations\n * include setting values and inserting/removing rows and columns.\n *\n * Matrix values may be any Fluid serializable type, which is the set of JSON\n * serializable types extended to include IFluidHandles.\n *\n * Fluid's SharedMatrix implementation works equally well for dense and sparse\n * matrix data and physically stores data in Z-order to leverage CPU caches and\n * prefetching when reading in either row or column major order. (See README.md\n * for more details.)\n */\nexport class SharedMatrix<T = any>\n extends SharedObject\n implements IMatrixProducer<MatrixItem<T>>,\n IMatrixReader<MatrixItem<T>>,\n IMatrixWriter<MatrixItem<T>> {\n private readonly consumers = new Set<IMatrixConsumer<MatrixItem<T>>>();\n\n public static getFactory() { return new SharedMatrixFactory(); }\n\n private readonly rows: PermutationVector; // Map logical row to storage handle (if any)\n private readonly cols: PermutationVector; // Map logical col to storage handle (if any)\n\n private cells = new SparseArray2D<MatrixItem<T>>(); // Stores cell values.\n private pending = new SparseArray2D<number>(); // Tracks pending writes.\n\n constructor(runtime: IFluidDataStoreRuntime, public id: string, attributes: IChannelAttributes) {\n super(id, runtime, attributes, \"fluid_matrix_\");\n\n this.rows = new PermutationVector(\n SnapshotPath.rows,\n this.logger,\n runtime,\n this.onRowDelta,\n this.onRowHandlesRecycled);\n\n this.cols = new PermutationVector(\n SnapshotPath.cols,\n this.logger,\n runtime,\n this.onColDelta,\n this.onColHandlesRecycled);\n }\n\n private undo?: MatrixUndoProvider<T>;\n\n /**\n * Subscribes the given IUndoConsumer to the matrix.\n */\n public openUndo(consumer: IUndoConsumer) {\n assert(this.undo === undefined,\n 0x019 /* \"SharedMatrix.openUndo() supports at most a single IUndoConsumer.\" */);\n\n this.undo = new MatrixUndoProvider(consumer, this, this.rows, this.cols);\n }\n\n // TODO: closeUndo()?\n\n private get rowHandles() { return this.rows.handleCache; }\n private get colHandles() { return this.cols.handleCache; }\n\n /**\n * {@inheritDoc @fluidframework/datastore-definitions#IChannelFactory.create}\n */\n public static create<T>(runtime: IFluidDataStoreRuntime, id?: string) {\n return runtime.createChannel(id, SharedMatrixFactory.Type) as SharedMatrix<T>;\n }\n\n // #region IMatrixProducer\n\n openMatrix(\n consumer: IMatrixConsumer<MatrixItem<T>>,\n ): IMatrixReader<MatrixItem<T>> {\n this.consumers.add(consumer);\n return this;\n }\n\n closeMatrix(consumer: IMatrixConsumer<MatrixItem<T>>): void {\n this.consumers.delete(consumer);\n }\n\n // #endregion IMatrixProducer\n\n // #region IMatrixReader\n\n public get rowCount() { return this.rows.getLength(); }\n public get colCount() { return this.cols.getLength(); }\n\n public getCell(row: number, col: number): MatrixItem<T> {\n // Perf: When possible, bounds checking is performed inside the implementation for\n // 'getHandle()' so that it can be elided in the case of a cache hit. This\n // yields an ~40% improvement in the case of a cache hit (node v12 x64)\n\n // Map the logical (row, col) to associated storage handles.\n const rowHandle = this.rowHandles.getHandle(row);\n if (isHandleValid(rowHandle)) {\n const colHandle = this.colHandles.getHandle(col);\n if (isHandleValid(colHandle)) {\n return this.cells.getCell(rowHandle, colHandle);\n }\n } else {\n // If we early exit because the given rowHandle is unallocated, we still need to\n // bounds-check the 'col' parameter.\n ensureRange(col, this.cols.getLength());\n }\n\n return undefined;\n }\n\n public get matrixProducer(): IMatrixProducer<MatrixItem<T>> { return this; }\n\n // #endregion IMatrixReader\n\n public setCell(row: number, col: number, value: MatrixItem<T>) {\n assert(0 <= row && row < this.rowCount\n && 0 <= col && col < this.colCount,\n 0x01a /* \"Trying to set out-of-bounds cell!\" */);\n\n this.setCellCore(row, col, value);\n\n // Avoid reentrancy by raising change notifications after the op is queued.\n for (const consumer of this.consumers.values()) {\n consumer.cellsChanged(row, col, 1, 1, this);\n }\n }\n\n public setCells(\n rowStart: number,\n colStart: number,\n colCount: number,\n values: readonly (MatrixItem<T>)[],\n ) {\n const rowCount = Math.ceil(values.length / colCount);\n\n assert((0 <= rowStart && rowStart < this.rowCount)\n && (0 <= colStart && colStart < this.colCount)\n && (1 <= colCount && colCount <= (this.colCount - colStart))\n && (rowCount <= (this.rowCount - rowStart)),\n 0x01b /* \"Trying to set multiple out-of-bounds cells!\" */);\n\n const endCol = colStart + colCount;\n let r = rowStart;\n let c = colStart;\n\n for (const value of values) {\n this.setCellCore(r, c, value);\n\n if (++c === endCol) {\n c = colStart;\n r++;\n }\n }\n\n // Avoid reentrancy by raising change notifications after the op is queued.\n for (const consumer of this.consumers.values()) {\n consumer.cellsChanged(rowStart, colStart, rowCount, colCount, this);\n }\n }\n\n private setCellCore(\n row: number,\n col: number,\n value: MatrixItem<T>,\n rowHandle = this.rows.getAllocatedHandle(row),\n colHandle = this.cols.getAllocatedHandle(col),\n ) {\n if (this.undo !== undefined) {\n let oldValue = this.cells.getCell(rowHandle, colHandle);\n if (oldValue === null) {\n oldValue = undefined;\n }\n\n this.undo.cellSet(\n rowHandle,\n colHandle,\n oldValue);\n }\n\n this.cells.setCell(rowHandle, colHandle, value);\n\n if (this.isAttached()) {\n this.sendSetCellOp(row, col, value, rowHandle, colHandle);\n }\n }\n\n private sendSetCellOp(\n row: number,\n col: number,\n value: MatrixItem<T>,\n rowHandle: Handle,\n colHandle: Handle,\n localSeq = this.nextLocalSeq(),\n rowsRefSeq = this.rows.getCollabWindow().currentSeq,\n colsRefSeq = this.cols.getCollabWindow().currentSeq,\n ) {\n assert(this.isAttached(), 0x1e2 /* \"Caller must ensure 'isAttached()' before calling 'sendSetCellOp'.\" */);\n\n const op: ISetOp<T> = {\n type: MatrixOp.set,\n row,\n col,\n value,\n };\n\n const metadata: ISetOpMetadata = {\n rowHandle,\n colHandle,\n localSeq,\n rowsRefSeq,\n colsRefSeq,\n };\n\n this.submitLocalMessage(op, metadata);\n this.pending.setCell(rowHandle, colHandle, localSeq);\n }\n\n private submitVectorMessage(\n currentVector: PermutationVector,\n oppositeVector: PermutationVector,\n dimension: SnapshotPath.rows | SnapshotPath.cols,\n message: any,\n ) {\n // Ideally, we would have a single 'localSeq' counter that is shared between both PermutationVectors\n // and the SharedMatrix's cell data. Instead, we externally advance each MergeTree's 'localSeq' counter\n // for each submitted op it not aware of to keep them synchronized.\n const localSeq = currentVector.getCollabWindow().localSeq;\n const oppositeWindow = oppositeVector.getCollabWindow();\n\n // Note that the comparison is '>=' because, in the case the MergeTree is regenerating ops for reconnection,\n // the MergeTree submits the op with the original 'localSeq'.\n assert(localSeq >= oppositeWindow.localSeq,\n 0x01c /* \"The 'localSeq' of the vector submitting an op must >= the 'localSeq' of the other vector.\" */);\n\n oppositeWindow.localSeq = localSeq;\n\n // If the SharedMatrix is local, it's state will be submitted via a Snapshot when initially connected.\n // Do not queue a message or track the pending op, as there will never be an ACK, etc.\n if (this.isAttached()) {\n // Record whether this `op` targets rows or cols. (See dispatch in `processCore()`)\n message.target = dimension;\n\n this.submitLocalMessage(\n message,\n currentVector.peekPendingSegmentGroups(\n message.type === MergeTreeDeltaType.GROUP\n ? message.ops.length\n : 1));\n }\n }\n\n private submitColMessage(message: any) {\n this.submitVectorMessage(this.cols, this.rows, SnapshotPath.cols, message);\n }\n\n public insertCols(colStart: number, count: number) {\n this.submitColMessage(this.cols.insert(colStart, count));\n }\n\n public removeCols(colStart: number, count: number) {\n this.submitColMessage(this.cols.remove(colStart, count));\n }\n\n private submitRowMessage(message: any) {\n this.submitVectorMessage(this.rows, this.cols, SnapshotPath.rows, message);\n }\n\n public insertRows(rowStart: number, count: number) {\n this.submitRowMessage(this.rows.insert(rowStart, count));\n }\n\n public removeRows(rowStart: number, count: number) {\n this.submitRowMessage(this.rows.remove(rowStart, count));\n }\n\n /** @internal */ public _undoRemoveRows(segment: ISegment) {\n const original = segment as PermutationSegment;\n\n // (Re)insert the removed number of rows at the original position.\n const { op, inserted } = this.rows.insertRelative(original, original.cachedLength);\n this.submitRowMessage(op);\n\n // Transfer handles and undo/redo tracking groups from the original segment to the\n // newly inserted segment.\n original.transferToReplacement(inserted);\n\n // Invalidate the handleCache in case it was populated during the 'rowsChanged'\n // callback, which occurs before the handle span is populated.\n const rowStart = this.rows.getPosition(inserted);\n this.rows.handleCache.itemsChanged(\n rowStart,\n /* removedCount: */ 0,\n /* insertedCount: */ inserted.cachedLength);\n\n // Generate setCell ops for each populated cell in the reinserted rows.\n let rowHandle = inserted.start;\n const rowCount = inserted.cachedLength;\n for (let row = rowStart; row < rowStart + rowCount; row++, rowHandle++) {\n for (let col = 0; col < this.colCount; col++) {\n const colHandle = this.colHandles.getHandle(col);\n const value = this.cells.getCell(rowHandle, colHandle);\n if (this.isAttached() && value !== undefined && value !== null) {\n this.sendSetCellOp(\n row,\n col,\n value,\n rowHandle,\n colHandle);\n }\n }\n }\n\n // Avoid reentrancy by raising change notifications after the op is queued.\n for (const consumer of this.consumers.values()) {\n consumer.cellsChanged(rowStart, /* colStart: */ 0, rowCount, this.colCount, this);\n }\n }\n\n /** @internal */ public _undoRemoveCols(segment: ISegment) {\n const original = segment as PermutationSegment;\n\n // (Re)insert the removed number of columns at the original position.\n const { op, inserted } = this.cols.insertRelative(original, original.cachedLength);\n this.submitColMessage(op);\n\n // Transfer handles and undo/redo tracking groups from the original segment to the\n // newly inserted segment.\n original.transferToReplacement(inserted);\n\n // Invalidate the handleCache in case it was populated during the 'colsChanged'\n // callback, which occurs before the handle span is populated.\n const colStart = this.cols.getPosition(inserted);\n this.cols.handleCache.itemsChanged(\n colStart,\n /* removedCount: */ 0,\n /* insertedCount: */ inserted.cachedLength);\n\n // Generate setCell ops for each populated cell in the reinserted cols.\n let colHandle = inserted.start;\n const colCount = inserted.cachedLength;\n for (let col = colStart; col < colStart + colCount; col++, colHandle++) {\n for (let row = 0; row < this.rowCount; row++) {\n const rowHandle = this.rowHandles.getHandle(row);\n const value = this.cells.getCell(rowHandle, colHandle);\n if (this.isAttached() && value !== undefined && value !== null) {\n this.sendSetCellOp(\n row,\n col,\n value,\n rowHandle,\n colHandle);\n }\n }\n }\n\n // Avoid reentrancy by raising change notifications after the op is queued.\n for (const consumer of this.consumers.values()) {\n consumer.cellsChanged(/* rowStart: */ 0, colStart, this.rowCount, colCount, this);\n }\n }\n\n protected summarizeCore(serializer: IFluidSerializer): ISummaryTreeWithStats {\n const builder = new SummaryTreeBuilder();\n builder.addWithStats(SnapshotPath.rows, this.rows.summarize(this.runtime, this.handle, serializer));\n builder.addWithStats(SnapshotPath.cols, this.cols.summarize(this.runtime, this.handle, serializer));\n builder.addBlob(SnapshotPath.cells,\n serializer.stringify([\n this.cells.snapshot(),\n this.pending.snapshot(),\n ], this.handle));\n return builder.getSummaryTree();\n }\n\n /**\n * Runs serializer on the GC data for this SharedMatrix.\n * All the IFluidHandle's stored in the cells represent routes to other objects.\n */\n protected processGCDataCore(serializer: SummarySerializer) {\n for (let row = 0; row < this.rowCount; row++) {\n for (let col = 0; col < this.colCount; col++) {\n serializer.stringify(this.getCell(row, col), this.handle);\n }\n }\n }\n\n /**\n * Advances the 'localSeq' counter for the cell data operation currently being queued.\n *\n * Do not use with 'submitColMessage()/submitRowMessage()' as these helpers + the MergeTree will\n * automatically advance 'localSeq'.\n */\n private nextLocalSeq() {\n // Ideally, we would have a single 'localSeq' counter that is shared between both PermutationVectors\n // and the SharedMatrix's cell data. Instead, we externally bump each MergeTree's 'localSeq' counter\n // for SharedMatrix ops it's not aware of to keep them synchronized. (For cell data operations, we\n // need to bump both counters.)\n\n this.cols.getCollabWindow().localSeq++;\n return ++this.rows.getCollabWindow().localSeq;\n }\n\n protected submitLocalMessage(message: any, localOpMetadata?: any) {\n // TODO: Recommend moving this assertion into SharedObject\n // (See https://github.com/microsoft/FluidFramework/issues/2559)\n assert(this.isAttached() === true, 0x01d /* \"Trying to submit message to runtime while detached!\" */);\n\n super.submitLocalMessage(makeHandlesSerializable(message, this.serializer, this.handle), localOpMetadata);\n\n // Ensure that row/col 'localSeq' are synchronized (see 'nextLocalSeq()').\n assert(\n this.rows.getCollabWindow().localSeq === this.cols.getCollabWindow().localSeq,\n 0x01e /* \"Row and col collab window 'localSeq' desynchronized!\" */,\n );\n }\n\n protected didAttach() {\n // We've attached we need to start generating and sending ops.\n // so start collaboration and provide a default client id incase we are not connected\n if (this.isAttached()) {\n this.rows.startOrUpdateCollaboration(this.runtime.clientId ?? \"attached\");\n this.cols.startOrUpdateCollaboration(this.runtime.clientId ?? \"attached\");\n }\n }\n\n protected onConnect() {\n assert(this.rows.getCollabWindow().collaborating === this.cols.getCollabWindow().collaborating,\n 0x01f /* \"Row and col collab window 'collaborating' status desynchronized!\" */);\n\n // Update merge tree collaboration information with new client ID and then resend pending ops\n this.rows.startOrUpdateCollaboration(this.runtime.clientId as string);\n this.cols.startOrUpdateCollaboration(this.runtime.clientId as string);\n }\n\n protected reSubmitCore(content: any, localOpMetadata: unknown) {\n switch (content.target) {\n case SnapshotPath.cols:\n this.submitColMessage(this.cols.regeneratePendingOp(\n content as IMergeTreeOp,\n localOpMetadata as SegmentGroup | SegmentGroup[]));\n break;\n case SnapshotPath.rows:\n this.submitRowMessage(this.rows.regeneratePendingOp(\n content as IMergeTreeOp,\n localOpMetadata as SegmentGroup | SegmentGroup[]));\n break;\n default: {\n assert(content.type === MatrixOp.set, 0x020 /* \"Unknown SharedMatrix 'op' type.\" */);\n\n const setOp = content as ISetOp<T>;\n const { rowHandle, colHandle, localSeq, rowsRefSeq, colsRefSeq } = localOpMetadata as ISetOpMetadata;\n\n // If there are more pending local writes to the same row/col handle, it is important\n // to skip resubmitting this op since it is possible the row/col handle has been recycled\n // and now refers to a different position than when this op was originally submitted.\n if (this.isLatestPendingWrite(rowHandle, colHandle, localSeq)) {\n const row = this.rows.rebasePositionWithoutSegmentSlide(setOp.row, rowsRefSeq, localSeq);\n const col = this.cols.rebasePositionWithoutSegmentSlide(setOp.col, colsRefSeq, localSeq);\n\n if (row !== undefined && col !== undefined && row >= 0 && col >= 0) {\n this.sendSetCellOp(\n row,\n col,\n setOp.value,\n rowHandle,\n colHandle,\n localSeq,\n rowsRefSeq,\n colsRefSeq,\n );\n }\n }\n break;\n }\n }\n }\n\n protected onDisconnect() {}\n\n /**\n * {@inheritDoc @fluidframework/shared-object-base#SharedObject.loadCore}\n */\n protected async loadCore(storage: IChannelStorageService) {\n try {\n await this.rows.load(\n this.runtime,\n new ObjectStoragePartition(storage, SnapshotPath.rows),\n this.serializer);\n await this.cols.load(\n this.runtime,\n new ObjectStoragePartition(storage, SnapshotPath.cols),\n this.serializer);\n const [cellData, pendingCliSeqData] = await deserializeBlob(storage, SnapshotPath.cells, this.serializer);\n\n this.cells = SparseArray2D.load(cellData);\n this.pending = SparseArray2D.load(pendingCliSeqData);\n } catch (error) {\n this.logger.sendErrorEvent({ eventName: \"MatrixLoadFailed\" }, error);\n }\n }\n\n protected processCore(rawMessage: ISequencedDocumentMessage, local: boolean, localOpMetadata: unknown) {\n const msg = parseHandles(rawMessage, this.serializer);\n\n const contents = msg.contents;\n\n switch (contents.target) {\n case SnapshotPath.cols:\n this.cols.applyMsg(msg, local);\n break;\n case SnapshotPath.rows:\n this.rows.applyMsg(msg, local);\n break;\n default: {\n assert(contents.type === MatrixOp.set,\n 0x021 /* \"SharedMatrix message contents have unexpected type!\" */);\n\n const { row, col } = contents;\n\n if (local) {\n // We are receiving the ACK for a local pending set operation.\n const { rowHandle, colHandle, localSeq } = localOpMetadata as ISetOpMetadata;\n\n // If this is the most recent write to the cell by the local client, remove our\n // entry from 'pendingCliSeqs' to resume allowing remote writes.\n if (this.isLatestPendingWrite(rowHandle, colHandle, localSeq)) {\n this.pending.setCell(rowHandle, colHandle, undefined);\n }\n } else {\n const adjustedRow = this.rows.adjustPosition(row, rawMessage);\n\n if (adjustedRow !== undefined) {\n const adjustedCol = this.cols.adjustPosition(col, rawMessage);\n\n if (adjustedCol !== undefined) {\n const rowHandle = this.rows.getAllocatedHandle(adjustedRow);\n const colHandle = this.cols.getAllocatedHandle(adjustedCol);\n\n assert(isHandleValid(rowHandle) && isHandleValid(colHandle),\n 0x022 /* \"SharedMatrix row and/or col handles are invalid!\" */);\n\n // If there is a pending (unACKed) local write to the same cell, skip the current op\n // since it \"happened before\" the pending write.\n if (this.pending.getCell(rowHandle, colHandle) === undefined) {\n const { value } = contents;\n this.cells.setCell(rowHandle, colHandle, value);\n\n for (const consumer of this.consumers.values()) {\n consumer.cellsChanged(adjustedRow, adjustedCol, 1, 1, this);\n }\n }\n }\n }\n }\n }\n }\n }\n\n // Invoked by PermutationVector to notify IMatrixConsumers of row insertion/deletions.\n private readonly onRowDelta = (position: number, removedCount: number, insertedCount: number) => {\n for (const consumer of this.consumers) {\n consumer.rowsChanged(position, removedCount, insertedCount, this);\n }\n };\n\n // Invoked by PermutationVector to notify IMatrixConsumers of col insertion/deletions.\n private readonly onColDelta = (position: number, removedCount: number, insertedCount: number) => {\n for (const consumer of this.consumers) {\n consumer.colsChanged(position, removedCount, insertedCount, this);\n }\n };\n\n private readonly onRowHandlesRecycled = (rowHandles: Handle[]) => {\n for (const rowHandle of rowHandles) {\n this.cells.clearRows(/* rowStart: */ rowHandle, /* rowCount: */ 1);\n this.pending.clearRows(/* rowStart: */ rowHandle, /* rowCount: */ 1);\n }\n };\n\n private readonly onColHandlesRecycled = (colHandles: Handle[]) => {\n for (const colHandle of colHandles) {\n this.cells.clearCols(/* colStart: */ colHandle, /* colCount: */ 1);\n this.pending.clearCols(/* colStart: */ colHandle, /* colCount: */ 1);\n }\n };\n\n /**\n * Returns true if the latest pending write to the cell indicated by the given row/col handles\n * matches the given 'localSeq'.\n *\n * A return value of `true` indicates that there are no later local operations queued that will\n * clobber the write op at the given 'localSeq'. This includes later ops that overwrite the cell\n * with a different value as well as row/col removals that might recycled the given row/col handles.\n */\n private isLatestPendingWrite(rowHandle: Handle, colHandle: Handle, localSeq: number) {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const pendingLocalSeq = this.pending.getCell(rowHandle, colHandle)!;\n\n // Note while we're awaiting the ACK for a local set, it's possible for the row/col to be\n // locally removed and the row/col handles recycled. If this happens, the pendingLocalSeq will\n // be 'undefined' or > 'localSeq'.\n assert(!(pendingLocalSeq < localSeq),\n // eslint-disable-next-line max-len\n 0x023 /* \"The 'localSeq' of pending write (if any) must be <= the localSeq of the currently processed op.\" */);\n\n // If this is the most recent write to the cell by the local client, the stored localSeq\n // will be an exact match for the given 'localSeq'.\n return pendingLocalSeq === localSeq;\n }\n\n public toString() {\n let s = `client:${this.runtime.clientId}\\nrows: ${this.rows.toString()}\\ncols: ${this.cols.toString()}\\n\\n`;\n\n for (let r = 0; r < this.rowCount; r++) {\n s += ` [`;\n for (let c = 0; c < this.colCount; c++) {\n if (c > 0) {\n s += \", \";\n }\n\n s += `${this.serializer.stringify(this.getCell(r, c), this.handle)}`;\n }\n s += \"]\\n\";\n }\n\n return `${s}\\n`;\n }\n\n /**\n * {@inheritDoc @fluidframework/shared-object-base#SharedObjectCore.applyStashedOp}\n */\n protected applyStashedOp(content: any): unknown {\n if (content.target === SnapshotPath.cols || content.target === SnapshotPath.rows) {\n const op = content as IMergeTreeOp;\n const currentVector = content.target === SnapshotPath.cols ? this.cols : this.rows;\n const oppositeVector = content.target === SnapshotPath.cols ? this.rows : this.cols;\n const metadata = currentVector.applyStashedOp(op);\n const localSeq = currentVector.getCollabWindow().localSeq;\n const oppositeWindow = oppositeVector.getCollabWindow();\n\n assert(\n localSeq > oppositeWindow.localSeq,\n 0x2d9,\n /* \"The 'localSeq' of the vector applying stashed op must > the 'localSeq' of the other vector.\" */\n );\n\n oppositeWindow.localSeq = localSeq;\n\n return metadata;\n } else {\n assert(content.type === MatrixOp.set, 0x2da /* \"Unknown SharedMatrix 'op' type.\" */);\n\n const setOp = content as ISetOp<T>;\n const rowHandle = this.rows.getAllocatedHandle(setOp.row);\n const colHandle = this.cols.getAllocatedHandle(setOp.col);\n const rowsRefSeq = this.rows.getCollabWindow().currentSeq;\n const colsRefSeq = this.cols.getCollabWindow().currentSeq;\n if (this.undo !== undefined) {\n let oldValue = this.cells.getCell(rowHandle, colHandle);\n if (oldValue === null) {\n oldValue = undefined;\n }\n\n this.undo.cellSet(\n rowHandle,\n colHandle,\n oldValue);\n }\n\n this.cells.setCell(rowHandle, colHandle, setOp.value);\n const localSeq = this.nextLocalSeq();\n const metadata: ISetOpMetadata = {\n rowHandle,\n colHandle,\n localSeq,\n rowsRefSeq,\n colsRefSeq,\n };\n\n this.pending.setCell(rowHandle, colHandle, localSeq);\n return metadata;\n }\n }\n}\n"]}
1
+ {"version":3,"file":"matrix.js","sourceRoot":"","sources":["../src/matrix.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,MAAM,EAAE,MAAM,8BAA8B,CAAC;AAQtD,O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AAC,CAAC;YAC1D,MAAM,SAAS,GAAG,IAAI,CAAC,IAAI,CAAC,kBAAkB,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;YAC1D,MAAM,UAAU,GAAG,IAAI,CAAC,IAAI,CAAC,eAAe,EAAE,CAAC,UAAU,CAAC;YAC1D,MAAM,UAAU,GAAG,IAAI,CAAC,IAAI,CAAC,eAAe,EAAE,CAAC,UAAU,CAAC;YAC1D,IAAI,IAAI,CAAC,IAAI,KAAK,SAAS,EAAE;gBACzB,IAAI,QAAQ,GAAG,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,SAAS,EAAE,SAAS,CAAC,CAAC;gBACxD,IAAI,QAAQ,KAAK,IAAI,EAAE;oBACnB,QAAQ,GAAG,SAAS,CAAC;iBACxB;gBAED,IAAI,CAAC,IAAI,CAAC,OAAO,CACb,SAAS,EACT,SAAS,EACT,QAAQ,CAAC,CAAC;aACjB;YAED,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,SAAS,EAAE,SAAS,EAAE,KAAK,CAAC,KAAK,CAAC,CAAC;YACtD,MAAM,QAAQ,GAAG,IAAI,CAAC,YAAY,EAAE,CAAC;YACrC,MAAM,QAAQ,GAAmB;gBAC7B,SAAS;gBACT,SAAS;gBACT,QAAQ;gBACR,UAAU;gBACV,UAAU;aACb,CAAC;YAEF,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,SAAS,EAAE,SAAS,EAAE,QAAQ,CAAC,CAAC;YACrD,OAAO,QAAQ,CAAC;SACnB;IACL,CAAC;CACJ","sourcesContent":["/*!\n * Copyright (c) Microsoft Corporation and contributors. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { assert } from \"@fluidframework/common-utils\";\nimport { ISequencedDocumentMessage } from \"@fluidframework/protocol-definitions\";\nimport {\n IFluidDataStoreRuntime,\n IChannelStorageService,\n Serializable,\n IChannelAttributes,\n} from \"@fluidframework/datastore-definitions\";\nimport {\n IFluidSerializer,\n makeHandlesSerializable,\n parseHandles,\n SharedObject,\n SummarySerializer,\n} from \"@fluidframework/shared-object-base\";\nimport { ISummaryTreeWithStats } from \"@fluidframework/runtime-definitions\";\nimport { ObjectStoragePartition, SummaryTreeBuilder } from \"@fluidframework/runtime-utils\";\nimport {\n IMatrixProducer,\n IMatrixConsumer,\n IMatrixReader,\n IMatrixWriter,\n} from \"@tiny-calc/nano\";\nimport { MergeTreeDeltaType, IMergeTreeOp, SegmentGroup, ISegment, Client } from \"@fluidframework/merge-tree\";\nimport { MatrixOp } from \"./ops\";\nimport { PermutationVector, PermutationSegment } from \"./permutationvector\";\nimport { SparseArray2D } from \"./sparsearray2d\";\nimport { SharedMatrixFactory } from \"./runtime\";\nimport { Handle, isHandleValid } from \"./handletable\";\nimport { deserializeBlob } from \"./serialization\";\nimport { ensureRange } from \"./range\";\nimport { IUndoConsumer } from \"./types\";\nimport { MatrixUndoProvider } from \"./undoprovider\";\n\nconst enum SnapshotPath {\n rows = \"rows\",\n cols = \"cols\",\n cells = \"cells\",\n}\n\ninterface ISetOp<T> {\n type: MatrixOp.set;\n row: number;\n col: number;\n value: MatrixItem<T>;\n}\n\ninterface ISetOpMetadata {\n rowHandle: Handle;\n colHandle: Handle;\n localSeq: number;\n rowsRefSeq: number;\n colsRefSeq: number;\n}\n\n/**\n * A matrix cell value may be undefined (indicating an empty cell) or any serializable type,\n * excluding null. (However, nulls may be embedded inside objects and arrays.)\n */\nexport type MatrixItem<T> = Serializable<Exclude<T, null>> | undefined;\n\n/**\n * A SharedMatrix holds a rectangular 2D array of values. Supported operations\n * include setting values and inserting/removing rows and columns.\n *\n * Matrix values may be any Fluid serializable type, which is the set of JSON\n * serializable types extended to include IFluidHandles.\n *\n * Fluid's SharedMatrix implementation works equally well for dense and sparse\n * matrix data and physically stores data in Z-order to leverage CPU caches and\n * prefetching when reading in either row or column major order. (See README.md\n * for more details.)\n */\nexport class SharedMatrix<T = any>\n extends SharedObject\n implements IMatrixProducer<MatrixItem<T>>,\n IMatrixReader<MatrixItem<T>>,\n IMatrixWriter<MatrixItem<T>> {\n private readonly consumers = new Set<IMatrixConsumer<MatrixItem<T>>>();\n\n public static getFactory() { return new SharedMatrixFactory(); }\n\n private readonly rows: PermutationVector; // Map logical row to storage handle (if any)\n private readonly cols: PermutationVector; // Map logical col to storage handle (if any)\n\n private cells = new SparseArray2D<MatrixItem<T>>(); // Stores cell values.\n private pending = new SparseArray2D<number>(); // Tracks pending writes.\n\n constructor(runtime: IFluidDataStoreRuntime, public id: string, attributes: IChannelAttributes) {\n super(id, runtime, attributes, \"fluid_matrix_\");\n\n this.rows = new PermutationVector(\n SnapshotPath.rows,\n this.logger,\n runtime,\n this.onRowDelta,\n this.onRowHandlesRecycled);\n\n this.cols = new PermutationVector(\n SnapshotPath.cols,\n this.logger,\n runtime,\n this.onColDelta,\n this.onColHandlesRecycled);\n }\n\n private undo?: MatrixUndoProvider<T>;\n\n /**\n * Subscribes the given IUndoConsumer to the matrix.\n */\n public openUndo(consumer: IUndoConsumer) {\n assert(this.undo === undefined,\n 0x019 /* \"SharedMatrix.openUndo() supports at most a single IUndoConsumer.\" */);\n\n this.undo = new MatrixUndoProvider(consumer, this, this.rows, this.cols);\n }\n\n // TODO: closeUndo()?\n\n private get rowHandles() { return this.rows.handleCache; }\n private get colHandles() { return this.cols.handleCache; }\n\n /**\n * {@inheritDoc @fluidframework/datastore-definitions#IChannelFactory.create}\n */\n public static create<T>(runtime: IFluidDataStoreRuntime, id?: string) {\n return runtime.createChannel(id, SharedMatrixFactory.Type) as SharedMatrix<T>;\n }\n\n // #region IMatrixProducer\n\n openMatrix(\n consumer: IMatrixConsumer<MatrixItem<T>>,\n ): IMatrixReader<MatrixItem<T>> {\n this.consumers.add(consumer);\n return this;\n }\n\n closeMatrix(consumer: IMatrixConsumer<MatrixItem<T>>): void {\n this.consumers.delete(consumer);\n }\n\n // #endregion IMatrixProducer\n\n // #region IMatrixReader\n\n public get rowCount() { return this.rows.getLength(); }\n public get colCount() { return this.cols.getLength(); }\n\n public getCell(row: number, col: number): MatrixItem<T> {\n // Perf: When possible, bounds checking is performed inside the implementation for\n // 'getHandle()' so that it can be elided in the case of a cache hit. This\n // yields an ~40% improvement in the case of a cache hit (node v12 x64)\n\n // Map the logical (row, col) to associated storage handles.\n const rowHandle = this.rowHandles.getHandle(row);\n if (isHandleValid(rowHandle)) {\n const colHandle = this.colHandles.getHandle(col);\n if (isHandleValid(colHandle)) {\n return this.cells.getCell(rowHandle, colHandle);\n }\n } else {\n // If we early exit because the given rowHandle is unallocated, we still need to\n // bounds-check the 'col' parameter.\n ensureRange(col, this.cols.getLength());\n }\n\n return undefined;\n }\n\n public get matrixProducer(): IMatrixProducer<MatrixItem<T>> { return this; }\n\n // #endregion IMatrixReader\n\n public setCell(row: number, col: number, value: MatrixItem<T>) {\n assert(0 <= row && row < this.rowCount\n && 0 <= col && col < this.colCount,\n 0x01a /* \"Trying to set out-of-bounds cell!\" */);\n\n this.setCellCore(row, col, value);\n\n // Avoid reentrancy by raising change notifications after the op is queued.\n for (const consumer of this.consumers.values()) {\n consumer.cellsChanged(row, col, 1, 1, this);\n }\n }\n\n public setCells(\n rowStart: number,\n colStart: number,\n colCount: number,\n values: readonly (MatrixItem<T>)[],\n ) {\n const rowCount = Math.ceil(values.length / colCount);\n\n assert((0 <= rowStart && rowStart < this.rowCount)\n && (0 <= colStart && colStart < this.colCount)\n && (1 <= colCount && colCount <= (this.colCount - colStart))\n && (rowCount <= (this.rowCount - rowStart)),\n 0x01b /* \"Trying to set multiple out-of-bounds cells!\" */);\n\n const endCol = colStart + colCount;\n let r = rowStart;\n let c = colStart;\n\n for (const value of values) {\n this.setCellCore(r, c, value);\n\n if (++c === endCol) {\n c = colStart;\n r++;\n }\n }\n\n // Avoid reentrancy by raising change notifications after the op is queued.\n for (const consumer of this.consumers.values()) {\n consumer.cellsChanged(rowStart, colStart, rowCount, colCount, this);\n }\n }\n\n private setCellCore(\n row: number,\n col: number,\n value: MatrixItem<T>,\n rowHandle = this.rows.getAllocatedHandle(row),\n colHandle = this.cols.getAllocatedHandle(col),\n ) {\n if (this.undo !== undefined) {\n let oldValue = this.cells.getCell(rowHandle, colHandle);\n if (oldValue === null) {\n oldValue = undefined;\n }\n\n this.undo.cellSet(\n rowHandle,\n colHandle,\n oldValue);\n }\n\n this.cells.setCell(rowHandle, colHandle, value);\n\n if (this.isAttached()) {\n this.sendSetCellOp(row, col, value, rowHandle, colHandle);\n }\n }\n\n private sendSetCellOp(\n row: number,\n col: number,\n value: MatrixItem<T>,\n rowHandle: Handle,\n colHandle: Handle,\n localSeq = this.nextLocalSeq(),\n rowsRefSeq = this.rows.getCollabWindow().currentSeq,\n colsRefSeq = this.cols.getCollabWindow().currentSeq,\n ) {\n assert(this.isAttached(), 0x1e2 /* \"Caller must ensure 'isAttached()' before calling 'sendSetCellOp'.\" */);\n\n const op: ISetOp<T> = {\n type: MatrixOp.set,\n row,\n col,\n value,\n };\n\n const metadata: ISetOpMetadata = {\n rowHandle,\n colHandle,\n localSeq,\n rowsRefSeq,\n colsRefSeq,\n };\n\n this.submitLocalMessage(op, metadata);\n this.pending.setCell(rowHandle, colHandle, localSeq);\n }\n\n private submitVectorMessage(\n currentVector: PermutationVector,\n oppositeVector: PermutationVector,\n dimension: SnapshotPath.rows | SnapshotPath.cols,\n message: any,\n ) {\n // Ideally, we would have a single 'localSeq' counter that is shared between both PermutationVectors\n // and the SharedMatrix's cell data. Instead, we externally advance each MergeTree's 'localSeq' counter\n // for each submitted op it not aware of to keep them synchronized.\n const localSeq = currentVector.getCollabWindow().localSeq;\n const oppositeWindow = oppositeVector.getCollabWindow();\n\n // Note that the comparison is '>=' because, in the case the MergeTree is regenerating ops for reconnection,\n // the MergeTree submits the op with the original 'localSeq'.\n assert(localSeq >= oppositeWindow.localSeq,\n 0x01c /* \"The 'localSeq' of the vector submitting an op must >= the 'localSeq' of the other vector.\" */);\n\n oppositeWindow.localSeq = localSeq;\n\n // If the SharedMatrix is local, it's state will be submitted via a Snapshot when initially connected.\n // Do not queue a message or track the pending op, as there will never be an ACK, etc.\n if (this.isAttached()) {\n // Record whether this `op` targets rows or cols. (See dispatch in `processCore()`)\n message.target = dimension;\n\n this.submitLocalMessage(\n message,\n currentVector.peekPendingSegmentGroups(\n message.type === MergeTreeDeltaType.GROUP\n ? message.ops.length\n : 1));\n }\n }\n\n private submitColMessage(message: any) {\n this.submitVectorMessage(this.cols, this.rows, SnapshotPath.cols, message);\n }\n\n public insertCols(colStart: number, count: number) {\n this.submitColMessage(this.cols.insert(colStart, count));\n }\n\n public removeCols(colStart: number, count: number) {\n this.submitColMessage(this.cols.remove(colStart, count));\n }\n\n private submitRowMessage(message: any) {\n this.submitVectorMessage(this.rows, this.cols, SnapshotPath.rows, message);\n }\n\n public insertRows(rowStart: number, count: number) {\n this.submitRowMessage(this.rows.insert(rowStart, count));\n }\n\n public removeRows(rowStart: number, count: number) {\n this.submitRowMessage(this.rows.remove(rowStart, count));\n }\n\n /** @internal */ public _undoRemoveRows(segment: ISegment) {\n const original = segment as PermutationSegment;\n\n // (Re)insert the removed number of rows at the original position.\n const { op, inserted } = this.rows.insertRelative(original, original.cachedLength);\n this.submitRowMessage(op);\n\n // Transfer handles and undo/redo tracking groups from the original segment to the\n // newly inserted segment.\n original.transferToReplacement(inserted);\n\n // Invalidate the handleCache in case it was populated during the 'rowsChanged'\n // callback, which occurs before the handle span is populated.\n const rowStart = this.rows.getPosition(inserted);\n this.rows.handleCache.itemsChanged(\n rowStart,\n /* removedCount: */ 0,\n /* insertedCount: */ inserted.cachedLength);\n\n // Generate setCell ops for each populated cell in the reinserted rows.\n let rowHandle = inserted.start;\n const rowCount = inserted.cachedLength;\n for (let row = rowStart; row < rowStart + rowCount; row++, rowHandle++) {\n for (let col = 0; col < this.colCount; col++) {\n const colHandle = this.colHandles.getHandle(col);\n const value = this.cells.getCell(rowHandle, colHandle);\n if (this.isAttached() && value !== undefined && value !== null) {\n this.sendSetCellOp(\n row,\n col,\n value,\n rowHandle,\n colHandle);\n }\n }\n }\n\n // Avoid reentrancy by raising change notifications after the op is queued.\n for (const consumer of this.consumers.values()) {\n consumer.cellsChanged(rowStart, /* colStart: */ 0, rowCount, this.colCount, this);\n }\n }\n\n /** @internal */ public _undoRemoveCols(segment: ISegment) {\n const original = segment as PermutationSegment;\n\n // (Re)insert the removed number of columns at the original position.\n const { op, inserted } = this.cols.insertRelative(original, original.cachedLength);\n this.submitColMessage(op);\n\n // Transfer handles and undo/redo tracking groups from the original segment to the\n // newly inserted segment.\n original.transferToReplacement(inserted);\n\n // Invalidate the handleCache in case it was populated during the 'colsChanged'\n // callback, which occurs before the handle span is populated.\n const colStart = this.cols.getPosition(inserted);\n this.cols.handleCache.itemsChanged(\n colStart,\n /* removedCount: */ 0,\n /* insertedCount: */ inserted.cachedLength);\n\n // Generate setCell ops for each populated cell in the reinserted cols.\n let colHandle = inserted.start;\n const colCount = inserted.cachedLength;\n for (let col = colStart; col < colStart + colCount; col++, colHandle++) {\n for (let row = 0; row < this.rowCount; row++) {\n const rowHandle = this.rowHandles.getHandle(row);\n const value = this.cells.getCell(rowHandle, colHandle);\n if (this.isAttached() && value !== undefined && value !== null) {\n this.sendSetCellOp(\n row,\n col,\n value,\n rowHandle,\n colHandle);\n }\n }\n }\n\n // Avoid reentrancy by raising change notifications after the op is queued.\n for (const consumer of this.consumers.values()) {\n consumer.cellsChanged(/* rowStart: */ 0, colStart, this.rowCount, colCount, this);\n }\n }\n\n protected summarizeCore(serializer: IFluidSerializer): ISummaryTreeWithStats {\n const builder = new SummaryTreeBuilder();\n builder.addWithStats(SnapshotPath.rows, this.rows.summarize(this.runtime, this.handle, serializer));\n builder.addWithStats(SnapshotPath.cols, this.cols.summarize(this.runtime, this.handle, serializer));\n builder.addBlob(SnapshotPath.cells,\n serializer.stringify([\n this.cells.snapshot(),\n this.pending.snapshot(),\n ], this.handle));\n return builder.getSummaryTree();\n }\n\n /**\n * Runs serializer on the GC data for this SharedMatrix.\n * All the IFluidHandle's stored in the cells represent routes to other objects.\n */\n protected processGCDataCore(serializer: SummarySerializer) {\n for (let row = 0; row < this.rowCount; row++) {\n for (let col = 0; col < this.colCount; col++) {\n serializer.stringify(this.getCell(row, col), this.handle);\n }\n }\n }\n\n /**\n * Advances the 'localSeq' counter for the cell data operation currently being queued.\n *\n * Do not use with 'submitColMessage()/submitRowMessage()' as these helpers + the MergeTree will\n * automatically advance 'localSeq'.\n */\n private nextLocalSeq() {\n // Ideally, we would have a single 'localSeq' counter that is shared between both PermutationVectors\n // and the SharedMatrix's cell data. Instead, we externally bump each MergeTree's 'localSeq' counter\n // for SharedMatrix ops it's not aware of to keep them synchronized. (For cell data operations, we\n // need to bump both counters.)\n\n this.cols.getCollabWindow().localSeq++;\n return ++this.rows.getCollabWindow().localSeq;\n }\n\n protected submitLocalMessage(message: any, localOpMetadata?: any) {\n // TODO: Recommend moving this assertion into SharedObject\n // (See https://github.com/microsoft/FluidFramework/issues/2559)\n assert(this.isAttached() === true, 0x01d /* \"Trying to submit message to runtime while detached!\" */);\n\n super.submitLocalMessage(makeHandlesSerializable(message, this.serializer, this.handle), localOpMetadata);\n\n // Ensure that row/col 'localSeq' are synchronized (see 'nextLocalSeq()').\n assert(\n this.rows.getCollabWindow().localSeq === this.cols.getCollabWindow().localSeq,\n 0x01e /* \"Row and col collab window 'localSeq' desynchronized!\" */,\n );\n }\n\n protected didAttach() {\n // We've attached we need to start generating and sending ops.\n // so start collaboration and provide a default client id incase we are not connected\n if (this.isAttached()) {\n this.rows.startOrUpdateCollaboration(this.runtime.clientId ?? \"attached\");\n this.cols.startOrUpdateCollaboration(this.runtime.clientId ?? \"attached\");\n }\n }\n\n protected onConnect() {\n assert(this.rows.getCollabWindow().collaborating === this.cols.getCollabWindow().collaborating,\n 0x01f /* \"Row and col collab window 'collaborating' status desynchronized!\" */);\n\n // Update merge tree collaboration information with new client ID and then resend pending ops\n this.rows.startOrUpdateCollaboration(this.runtime.clientId as string);\n this.cols.startOrUpdateCollaboration(this.runtime.clientId as string);\n }\n\n private rebasePosition(\n client: Client,\n pos: number,\n referenceSequenceNumber: number,\n localSeq: number\n ): number | undefined {\n const { clientId } = client.getCollabWindow();\n const { segment, offset } = client.getContainingSegment(pos, { referenceSequenceNumber, clientId: client.getLongClientId(clientId) }, localSeq);\n if (segment === undefined || offset === undefined) {\n return;\n }\n\n return client.findReconnectionPosition(segment, localSeq) + offset;\n }\n\n protected reSubmitCore(content: any, localOpMetadata: unknown) {\n switch (content.target) {\n case SnapshotPath.cols:\n this.submitColMessage(this.cols.regeneratePendingOp(\n content as IMergeTreeOp,\n localOpMetadata as SegmentGroup | SegmentGroup[]));\n break;\n case SnapshotPath.rows:\n this.submitRowMessage(this.rows.regeneratePendingOp(\n content as IMergeTreeOp,\n localOpMetadata as SegmentGroup | SegmentGroup[]));\n break;\n default: {\n assert(content.type === MatrixOp.set, 0x020 /* \"Unknown SharedMatrix 'op' type.\" */);\n\n const setOp = content as ISetOp<T>;\n const { rowHandle, colHandle, localSeq, rowsRefSeq, colsRefSeq } = localOpMetadata as ISetOpMetadata;\n\n // If there are more pending local writes to the same row/col handle, it is important\n // to skip resubmitting this op since it is possible the row/col handle has been recycled\n // and now refers to a different position than when this op was originally submitted.\n if (this.isLatestPendingWrite(rowHandle, colHandle, localSeq)) {\n const row = this.rebasePosition(this.rows, setOp.row, rowsRefSeq, localSeq);\n const col = this.rebasePosition(this.cols, setOp.col, colsRefSeq, localSeq);\n\n if (row !== undefined && col !== undefined && row >= 0 && col >= 0) {\n this.sendSetCellOp(\n row,\n col,\n setOp.value,\n rowHandle,\n colHandle,\n localSeq,\n rowsRefSeq,\n colsRefSeq,\n );\n }\n }\n break;\n }\n }\n }\n\n protected onDisconnect() {}\n\n /**\n * {@inheritDoc @fluidframework/shared-object-base#SharedObject.loadCore}\n */\n protected async loadCore(storage: IChannelStorageService) {\n try {\n await this.rows.load(\n this.runtime,\n new ObjectStoragePartition(storage, SnapshotPath.rows),\n this.serializer);\n await this.cols.load(\n this.runtime,\n new ObjectStoragePartition(storage, SnapshotPath.cols),\n this.serializer);\n const [cellData, pendingCliSeqData] = await deserializeBlob(storage, SnapshotPath.cells, this.serializer);\n\n this.cells = SparseArray2D.load(cellData);\n this.pending = SparseArray2D.load(pendingCliSeqData);\n } catch (error) {\n this.logger.sendErrorEvent({ eventName: \"MatrixLoadFailed\" }, error);\n }\n }\n\n protected processCore(rawMessage: ISequencedDocumentMessage, local: boolean, localOpMetadata: unknown) {\n const msg = parseHandles(rawMessage, this.serializer);\n\n const contents = msg.contents;\n\n switch (contents.target) {\n case SnapshotPath.cols:\n this.cols.applyMsg(msg, local);\n break;\n case SnapshotPath.rows:\n this.rows.applyMsg(msg, local);\n break;\n default: {\n assert(contents.type === MatrixOp.set,\n 0x021 /* \"SharedMatrix message contents have unexpected type!\" */);\n\n const { row, col } = contents;\n\n if (local) {\n // We are receiving the ACK for a local pending set operation.\n const { rowHandle, colHandle, localSeq } = localOpMetadata as ISetOpMetadata;\n\n // If this is the most recent write to the cell by the local client, remove our\n // entry from 'pendingCliSeqs' to resume allowing remote writes.\n if (this.isLatestPendingWrite(rowHandle, colHandle, localSeq)) {\n this.pending.setCell(rowHandle, colHandle, undefined);\n }\n } else {\n const adjustedRow = this.rows.adjustPosition(row, rawMessage);\n\n if (adjustedRow !== undefined) {\n const adjustedCol = this.cols.adjustPosition(col, rawMessage);\n\n if (adjustedCol !== undefined) {\n const rowHandle = this.rows.getAllocatedHandle(adjustedRow);\n const colHandle = this.cols.getAllocatedHandle(adjustedCol);\n\n assert(isHandleValid(rowHandle) && isHandleValid(colHandle),\n 0x022 /* \"SharedMatrix row and/or col handles are invalid!\" */);\n\n // If there is a pending (unACKed) local write to the same cell, skip the current op\n // since it \"happened before\" the pending write.\n if (this.pending.getCell(rowHandle, colHandle) === undefined) {\n const { value } = contents;\n this.cells.setCell(rowHandle, colHandle, value);\n\n for (const consumer of this.consumers.values()) {\n consumer.cellsChanged(adjustedRow, adjustedCol, 1, 1, this);\n }\n }\n }\n }\n }\n }\n }\n }\n\n // Invoked by PermutationVector to notify IMatrixConsumers of row insertion/deletions.\n private readonly onRowDelta = (position: number, removedCount: number, insertedCount: number) => {\n for (const consumer of this.consumers) {\n consumer.rowsChanged(position, removedCount, insertedCount, this);\n }\n };\n\n // Invoked by PermutationVector to notify IMatrixConsumers of col insertion/deletions.\n private readonly onColDelta = (position: number, removedCount: number, insertedCount: number) => {\n for (const consumer of this.consumers) {\n consumer.colsChanged(position, removedCount, insertedCount, this);\n }\n };\n\n private readonly onRowHandlesRecycled = (rowHandles: Handle[]) => {\n for (const rowHandle of rowHandles) {\n this.cells.clearRows(/* rowStart: */ rowHandle, /* rowCount: */ 1);\n this.pending.clearRows(/* rowStart: */ rowHandle, /* rowCount: */ 1);\n }\n };\n\n private readonly onColHandlesRecycled = (colHandles: Handle[]) => {\n for (const colHandle of colHandles) {\n this.cells.clearCols(/* colStart: */ colHandle, /* colCount: */ 1);\n this.pending.clearCols(/* colStart: */ colHandle, /* colCount: */ 1);\n }\n };\n\n /**\n * Returns true if the latest pending write to the cell indicated by the given row/col handles\n * matches the given 'localSeq'.\n *\n * A return value of `true` indicates that there are no later local operations queued that will\n * clobber the write op at the given 'localSeq'. This includes later ops that overwrite the cell\n * with a different value as well as row/col removals that might recycled the given row/col handles.\n */\n private isLatestPendingWrite(rowHandle: Handle, colHandle: Handle, localSeq: number) {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const pendingLocalSeq = this.pending.getCell(rowHandle, colHandle)!;\n\n // Note while we're awaiting the ACK for a local set, it's possible for the row/col to be\n // locally removed and the row/col handles recycled. If this happens, the pendingLocalSeq will\n // be 'undefined' or > 'localSeq'.\n assert(!(pendingLocalSeq < localSeq),\n 0x023 /* \"The 'localSeq' of pending write (if any) must be <= the localSeq of the currently processed op.\" */);\n\n // If this is the most recent write to the cell by the local client, the stored localSeq\n // will be an exact match for the given 'localSeq'.\n return pendingLocalSeq === localSeq;\n }\n\n public toString() {\n let s = `client:${this.runtime.clientId}\\nrows: ${this.rows.toString()}\\ncols: ${this.cols.toString()}\\n\\n`;\n\n for (let r = 0; r < this.rowCount; r++) {\n s += ` [`;\n for (let c = 0; c < this.colCount; c++) {\n if (c > 0) {\n s += \", \";\n }\n\n s += `${this.serializer.stringify(this.getCell(r, c), this.handle)}`;\n }\n s += \"]\\n\";\n }\n\n return `${s}\\n`;\n }\n\n /**\n * {@inheritDoc @fluidframework/shared-object-base#SharedObjectCore.applyStashedOp}\n */\n protected applyStashedOp(content: any): unknown {\n if (content.target === SnapshotPath.cols || content.target === SnapshotPath.rows) {\n const op = content as IMergeTreeOp;\n const currentVector = content.target === SnapshotPath.cols ? this.cols : this.rows;\n const oppositeVector = content.target === SnapshotPath.cols ? this.rows : this.cols;\n const metadata = currentVector.applyStashedOp(op);\n const localSeq = currentVector.getCollabWindow().localSeq;\n const oppositeWindow = oppositeVector.getCollabWindow();\n\n assert(\n localSeq > oppositeWindow.localSeq,\n 0x2d9,\n /* \"The 'localSeq' of the vector applying stashed op must > the 'localSeq' of the other vector.\" */\n );\n\n oppositeWindow.localSeq = localSeq;\n\n return metadata;\n } else {\n assert(content.type === MatrixOp.set, 0x2da /* \"Unknown SharedMatrix 'op' type.\" */);\n\n const setOp = content as ISetOp<T>;\n const rowHandle = this.rows.getAllocatedHandle(setOp.row);\n const colHandle = this.cols.getAllocatedHandle(setOp.col);\n const rowsRefSeq = this.rows.getCollabWindow().currentSeq;\n const colsRefSeq = this.cols.getCollabWindow().currentSeq;\n if (this.undo !== undefined) {\n let oldValue = this.cells.getCell(rowHandle, colHandle);\n if (oldValue === null) {\n oldValue = undefined;\n }\n\n this.undo.cellSet(\n rowHandle,\n colHandle,\n oldValue);\n }\n\n this.cells.setCell(rowHandle, colHandle, setOp.value);\n const localSeq = this.nextLocalSeq();\n const metadata: ISetOpMetadata = {\n rowHandle,\n colHandle,\n localSeq,\n rowsRefSeq,\n colsRefSeq,\n };\n\n this.pending.setCell(rowHandle, colHandle, localSeq);\n return metadata;\n }\n }\n}\n"]}
@@ -5,5 +5,5 @@
5
5
  * THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY
6
6
  */
7
7
  export declare const pkgName = "@fluidframework/matrix";
8
- export declare const pkgVersion = "2.0.0-internal.2.4.0";
8
+ export declare const pkgVersion = "2.0.0-internal.3.0.0";
9
9
  //# sourceMappingURL=packageVersion.d.ts.map
@@ -5,5 +5,5 @@
5
5
  * THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY
6
6
  */
7
7
  export const pkgName = "@fluidframework/matrix";
8
- export const pkgVersion = "2.0.0-internal.2.4.0";
8
+ export const pkgVersion = "2.0.0-internal.3.0.0";
9
9
  //# sourceMappingURL=packageVersion.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"packageVersion.js","sourceRoot":"","sources":["../src/packageVersion.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,MAAM,CAAC,MAAM,OAAO,GAAG,wBAAwB,CAAC;AAChD,MAAM,CAAC,MAAM,UAAU,GAAG,sBAAsB,CAAC","sourcesContent":["/*!\n * Copyright (c) Microsoft Corporation and contributors. All rights reserved.\n * Licensed under the MIT License.\n *\n * THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY\n */\n\nexport const pkgName = \"@fluidframework/matrix\";\nexport const pkgVersion = \"2.0.0-internal.2.4.0\";\n"]}
1
+ {"version":3,"file":"packageVersion.js","sourceRoot":"","sources":["../src/packageVersion.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,MAAM,CAAC,MAAM,OAAO,GAAG,wBAAwB,CAAC;AAChD,MAAM,CAAC,MAAM,UAAU,GAAG,sBAAsB,CAAC","sourcesContent":["/*!\n * Copyright (c) Microsoft Corporation and contributors. All rights reserved.\n * Licensed under the MIT License.\n *\n * THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY\n */\n\nexport const pkgName = \"@fluidframework/matrix\";\nexport const pkgVersion = \"2.0.0-internal.3.0.0\";\n"]}
@@ -164,8 +164,8 @@ export class PermutationVector extends Client {
164
164
  }
165
165
  }
166
166
  };
167
- this.mergeTreeDeltaCallback = this.onDelta;
168
- this.mergeTreeMaintenanceCallback = this.onMaintenance;
167
+ this.on("delta", this.onDelta);
168
+ this.on("maintenance", this.onMaintenance);
169
169
  }
170
170
  insert(start, length) {
171
171
  return this.insertSegmentLocal(start, new PermutationSegment(length));
@@ -200,7 +200,7 @@ export class PermutationVector extends Client {
200
200
  return handle;
201
201
  }
202
202
  adjustPosition(pos, op) {
203
- const { segment, offset } = this.getContainingSegment(pos, op);
203
+ const { segment, offset } = this.getContainingSegment(pos, { referenceSequenceNumber: op.referenceSequenceNumber, clientId: op.clientId });
204
204
  // Note that until the MergeTree GCs, the segment is still reachable via `getContainingSegment()` with
205
205
  // a `refSeq` in the past. Prevent remote ops from accidentally allocating or using recycled handles
206
206
  // by checking for the presence of 'removedSeq'.
@@ -1 +1 @@
1
- {"version":3,"file":"permutationvector.js","sourceRoot":"","sources":["../src/permutationvector.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,MAAM,EAAE,MAAM,8BAA8B,CAAC;AACtD,OAAO,EAAE,WAAW,EAAE,MAAM,iCAAiC,CAAC;AAG9D,OAAO,EACH,WAAW,EAEX,MAAM,EAGN,kBAAkB,EAElB,wBAAwB,EACxB,aAAa,GAChB,MAAM,4BAA4B,CAAC;AAIpC,OAAO,EAAE,sBAAsB,EAAE,kBAAkB,EAAE,MAAM,+BAA+B,CAAC;AAE3F,OAAO,EAAE,WAAW,EAAU,aAAa,EAAE,MAAM,eAAe,CAAC;AACnE,OAAO,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAClD,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAU5C,MAAM,OAAO,kBAAmB,SAAQ,WAAW;IAW/C,YAAY,MAAc,EAAE,KAAK,gCAAqB;QAClD,KAAK,EAAE,CAAC;QAVJ,WAAM,iCAA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!\n * Copyright (c) Microsoft Corporation and contributors. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { assert } from \"@fluidframework/common-utils\";\nimport { ChildLogger } from \"@fluidframework/telemetry-utils\";\nimport { IFluidDataStoreRuntime, IChannelStorageService } from \"@fluidframework/datastore-definitions\";\nimport { ITelemetryBaseLogger } from \"@fluidframework/common-definitions\";\nimport {\n BaseSegment,\n ISegment,\n Client,\n IMergeTreeDeltaOpArgs,\n IMergeTreeDeltaCallbackArgs,\n MergeTreeDeltaType,\n IMergeTreeMaintenanceCallbackArgs,\n MergeTreeMaintenanceType,\n ReferenceType,\n} from \"@fluidframework/merge-tree\";\nimport { IFluidHandle } from \"@fluidframework/core-interfaces\";\nimport { IFluidSerializer } from \"@fluidframework/shared-object-base\";\nimport { ISummaryTreeWithStats } from \"@fluidframework/runtime-definitions\";\nimport { ObjectStoragePartition, SummaryTreeBuilder } from \"@fluidframework/runtime-utils\";\nimport { ISequencedDocumentMessage } from \"@fluidframework/protocol-definitions\";\nimport { HandleTable, Handle, isHandleValid } from \"./handletable\";\nimport { deserializeBlob } from \"./serialization\";\nimport { HandleCache } from \"./handlecache\";\nimport { VectorUndoProvider } from \"./undoprovider\";\n\nconst enum SnapshotPath {\n segments = \"segments\",\n handleTable = \"handleTable\",\n}\n\ntype PermutationSegmentSpec = [number, number];\n\nexport class PermutationSegment extends BaseSegment {\n public static readonly typeString: string = \"PermutationSegment\";\n private _start = Handle.unallocated;\n\n public static fromJSONObject(spec: any) {\n const [length, start] = spec as PermutationSegmentSpec;\n return new PermutationSegment(length, start);\n }\n\n public readonly type = PermutationSegment.typeString;\n\n constructor(length: number, start = Handle.unallocated) {\n super();\n this._start = start;\n this.cachedLength = length;\n }\n\n public get start() { return this._start; }\n public set start(value: Handle) {\n assert(this._start === Handle.unallocated, 0x024 /* \"Start of PermutationSegment already allocated!\" */);\n assert(isHandleValid(value), 0x025 /* \"Trying to set start of PermutationSegment to invalid handle!\" */);\n\n this._start = value;\n }\n\n /**\n * Invoked by '_undoRow/ColRemove' to prepare the newly inserted destination\n * segment to serve as the replacement for this removed segment. This moves handle\n * allocations from this segment to the replacement as well as maintains tracking\n * groups for the undo/redo stack.\n */\n public transferToReplacement(destination: PermutationSegment) {\n // When this segment was removed, it may have been split from a larger original\n // segment. In this case, it will have been added to an undo/redo tracking group\n // that associates all of the fragments from the original insertion.\n //\n // Move this association from the this removed segment to its replacement so that\n // it is included if the undo stack continues to unwind to the original insertion.\n //\n // Out of paranoia we link and unlink in separate loops to avoid mutating the underlying\n // set during enumeration. In practice, this is unlikely to matter since there should be\n // exactly 0 or 1 items in the enumeration.\n for (const group of this.trackingCollection.trackingGroups) {\n group.link(destination);\n }\n for (const group of this.trackingCollection.trackingGroups) {\n group.unlink(this);\n }\n\n // Move handle allocations from this segment to its replacement.\n destination._start = this._start;\n this.reset();\n }\n\n public reset() {\n this._start = Handle.unallocated;\n }\n\n public toJSONObject() {\n return [this.cachedLength, this.start];\n }\n\n public clone(start = 0, end = this.cachedLength) {\n const b = new PermutationSegment(\n /* length: */ end - start,\n /* start: */ this.start + start);\n this.cloneInto(b);\n return b;\n }\n\n public canAppend(segment: ISegment) {\n const asPerm = segment as PermutationSegment;\n\n return this.start === Handle.unallocated\n ? asPerm.start === Handle.unallocated\n : asPerm.start === this.start + this.cachedLength;\n }\n\n protected createSplitSegmentAt(pos: number) {\n assert(0 < pos && pos < this.cachedLength, 0x026 /* \"Trying to split segment at out-of-bounds position!\" */);\n\n const leafSegment = new PermutationSegment(\n /* length: */ this.cachedLength - pos,\n /* start: */ this.start === Handle.unallocated\n ? Handle.unallocated\n : this.start + pos);\n\n this.cachedLength = pos;\n\n return leafSegment;\n }\n\n public toString() {\n return this.start === Handle.unallocated\n ? `<${this.cachedLength} empty>`\n : `<${this.cachedLength}: ${this.start}..${this.start + this.cachedLength - 1}>`;\n }\n}\n\nexport class PermutationVector extends Client {\n private handleTable = new HandleTable<never>(); // Tracks available storage handles for rows.\n public readonly handleCache = new HandleCache(this);\n public undo: VectorUndoProvider | undefined;\n\n constructor(\n path: string,\n logger: ITelemetryBaseLogger,\n runtime: IFluidDataStoreRuntime,\n private readonly deltaCallback: (position: number, numRemoved: number, numInserted: number) => void,\n private readonly handlesRecycledCallback: (handles: Handle[]) => void,\n ) {\n super(\n PermutationSegment.fromJSONObject,\n ChildLogger.create(logger, `Matrix.${path}.MergeTreeClient`), {\n ...runtime.options,\n newMergeTreeSnapshotFormat: true, // Temporarily force new snapshot format until it is the default.\n }); // (See https://github.com/microsoft/FluidFramework/issues/84)\n\n this.mergeTreeDeltaCallback = this.onDelta;\n this.mergeTreeMaintenanceCallback = this.onMaintenance;\n }\n\n public insert(start: number, length: number) {\n return this.insertSegmentLocal(\n start,\n new PermutationSegment(length));\n }\n\n public insertRelative(segment: ISegment, length: number) {\n const inserted = new PermutationSegment(length);\n\n return {\n op: this.insertAtReferencePositionLocal(\n this.createLocalReferencePosition(segment, 0, ReferenceType.Transient, undefined),\n inserted),\n inserted,\n };\n }\n\n public remove(start: number, length: number) {\n return this.removeRangeLocal(start, start + length);\n }\n\n public getMaybeHandle(pos: number): Handle {\n assert(0 <= pos && pos < this.getLength(), 0x027 /* \"Trying to get handle of out-of-bounds position!\" */);\n\n return this.handleCache.getHandle(pos);\n }\n\n public getAllocatedHandle(pos: number): Handle {\n let handle = this.getMaybeHandle(pos);\n if (isHandleValid(handle)) {\n return handle;\n }\n\n this.walkSegments(\n (segment) => {\n const asPerm = segment as PermutationSegment;\n asPerm.start = handle = this.handleTable.allocate();\n return true;\n },\n pos,\n pos + 1,\n /* accum: */ undefined,\n /* splitRange: */ true);\n\n this.handleCache.addHandle(pos, handle);\n\n return handle;\n }\n\n public adjustPosition(pos: number, op: ISequencedDocumentMessage) {\n const { segment, offset } = this.getContainingSegment(pos, op);\n\n // Note that until the MergeTree GCs, the segment is still reachable via `getContainingSegment()` with\n // a `refSeq` in the past. Prevent remote ops from accidentally allocating or using recycled handles\n // by checking for the presence of 'removedSeq'.\n if (segment === undefined || segment.removedSeq !== undefined) {\n return undefined;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n return this.getPosition(segment) + offset!;\n }\n\n public handleToPosition(handle: Handle, localSeq = this.getCollabWindow().localSeq) {\n assert(localSeq <= this.getCollabWindow().localSeq,\n 0x028 /* \"'localSeq' for op being resubmitted must be <= the 'localSeq' of the last submitted op.\" */);\n\n // TODO: In theory, the MergeTree should be able to map the (position, refSeq, localSeq) from\n // the original operation to the current position for undo/redo scenarios. This is probably the\n // ideal solution, as we would no longer need to store row/col handles in the op metadata.\n //\n // Failing that, we could avoid the O(n) search below by building a temporary map in the\n // opposite direction from the handle to either it's current position or segment + offset\n // and reuse it for the duration of undo/redo. (Ideally, we would know when the undo/redo\n // ended so we could discard this map.)\n //\n // If we find that we frequently need a reverse handle -> position lookup, we could maintain\n // one using the Tiny-Calc adjust tree.\n let containingSegment!: PermutationSegment;\n let containingOffset: number;\n\n this.walkAllSegments(\n (segment) => {\n const { start, cachedLength } = segment as PermutationSegment;\n\n // If the segment is unallocated, skip it.\n if (!isHandleValid(start)) {\n return true;\n }\n\n const end = start + cachedLength;\n\n if (start <= handle && handle < end) {\n containingSegment = segment as PermutationSegment;\n containingOffset = handle - start;\n return false;\n }\n\n return true;\n });\n\n // We are guaranteed to find the handle in the PermutationVector, even if the corresponding\n // row/col has been removed, because handles are not recycled until the containing segment\n // is unlinked from the MergeTree.\n //\n // Therefore, either a row/col removal has been ACKed, in which case there will be no pending\n // ops that reference the stale handle, or the removal is unACKed, in which case the handle\n // has not yet been recycled.\n\n assert(isHandleValid(containingSegment.start), 0x029 /* \"Invalid handle at start of containing segment!\" */);\n\n // Once we know the current position of the handle, we can use the MergeTree to get the segment\n // containing this position and use 'findReconnectionPosition' to adjust for the local ops that\n // have not yet been submitted.\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n return this.findReconnectionPosition(containingSegment, localSeq) + containingOffset!;\n }\n\n // Constructs an ISummaryTreeWithStats for the cell data.\n public summarize(runtime: IFluidDataStoreRuntime, handle: IFluidHandle, serializer: IFluidSerializer):\n ISummaryTreeWithStats {\n const builder = new SummaryTreeBuilder();\n builder.addWithStats(SnapshotPath.segments, super.summarize(runtime, handle, serializer, /* catchUpMsgs: */[]));\n builder.addBlob(SnapshotPath.handleTable, serializer.stringify(this.handleTable.getSummaryContent(), handle));\n return builder.getSummaryTree();\n }\n\n public async load(\n runtime: IFluidDataStoreRuntime,\n storage: IChannelStorageService,\n serializer: IFluidSerializer,\n ) {\n const handleTableData = await deserializeBlob(storage, SnapshotPath.handleTable, serializer);\n\n this.handleTable = HandleTable.load<never>(handleTableData);\n\n return super.load(runtime, new ObjectStoragePartition(storage, SnapshotPath.segments), serializer);\n }\n\n private readonly onDelta = (\n opArgs: IMergeTreeDeltaOpArgs,\n { operation, deltaSegments }: IMergeTreeDeltaCallbackArgs,\n ) => {\n // Apply deltas in descending order to prevent positions from shifting.\n const ranges = deltaSegments\n .map(({ segment }) => ({\n segment: segment as PermutationSegment,\n position: this.getPosition(segment),\n }))\n .sort((left, right) => left.position - right.position);\n\n const isLocal = opArgs.sequencedMessage === undefined;\n\n // Notify the undo provider, if any is attached.\n if (this.undo !== undefined && isLocal) {\n this.undo.record(operation, ranges);\n }\n\n switch (operation) {\n case MergeTreeDeltaType.INSERT:\n // Pass 1: Perform any internal maintenance first to avoid reentrancy.\n for (const { segment, position } of ranges) {\n // HACK: We need to include the allocated handle in the segment's JSON representation\n // for snapshots, but need to ignore the remote client's handle allocations when\n // processing remote ops.\n segment.reset();\n\n this.handleCache.itemsChanged(\n position,\n /* deleteCount: */ 0,\n /* insertCount: */ segment.cachedLength);\n }\n\n // Pass 2: Notify the 'deltaCallback', which may involve callbacks into user code.\n for (const { segment, position } of ranges) {\n this.deltaCallback(position, /* numRemoved: */ 0, /* numInserted: */ segment.cachedLength);\n }\n break;\n\n case MergeTreeDeltaType.REMOVE: {\n // Pass 1: Perform any internal maintenance first to avoid reentrancy.\n for (const { segment, position } of ranges) {\n this.handleCache.itemsChanged(\n position, /* deleteCount: */\n segment.cachedLength,\n /* insertCount: */ 0);\n }\n\n // Pass 2: Notify the 'deltaCallback', which may involve callbacks into user code.\n for (const { segment, position } of ranges) {\n this.deltaCallback(position, /* numRemoved: */ segment.cachedLength, /* numInsert: */ 0);\n }\n break;\n }\n\n default:\n throw new Error(\"Unhandled MergeTreeDeltaType\");\n }\n };\n\n private readonly onMaintenance = (args: IMergeTreeMaintenanceCallbackArgs) => {\n if (args.operation === MergeTreeMaintenanceType.UNLINK) {\n let freed: number[] = [];\n\n for (const { segment } of args.deltaSegments) {\n const asPerm = segment as PermutationSegment;\n if (isHandleValid(asPerm.start)) {\n // Note: Using the spread operator with `.splice()` can exhaust the stack.\n freed = freed.concat(\n new Array(asPerm.cachedLength)\n .fill(0)\n .map((value, index) => index + asPerm.start),\n );\n }\n }\n\n // Notify matrix that handles are about to be freed. The matrix is responsible for clearing\n // the rows/cols prior to free to ensure recycled row/cols are initially empty.\n this.handlesRecycledCallback(freed);\n\n // Now that the physical storage has been cleared, add the recycled handles back to the free pool.\n for (const handle of freed) {\n this.handleTable.free(handle);\n }\n }\n };\n\n public toString() {\n const s: string[] = [];\n\n this.walkSegments((segment) => {\n s.push(`${segment}`);\n return true;\n });\n\n return s.join(\"\");\n }\n}\n"]}
1
+ {"version":3,"file":"permutationvector.js","sourceRoot":"","sources":["../src/permutationvector.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,MAAM,EAAE,MAAM,8BAA8B,CAAC;AACtD,OAAO,EAAE,WAAW,EAAE,MAAM,iCAAiC,CAAC;AAG9D,OAAO,EACH,WAAW,EAEX,MAAM,EAGN,kBAAkB,EAElB,wBAAwB,EACxB,aAAa,GAChB,MAAM,4BAA4B,CAAC;AAIpC,OAAO,EAAE,sBAAsB,EAAE,kBAAkB,EAAE,MAAM,+BAA+B,CAAC;AAE3F,OAAO,EAAE,WAAW,EAAU,aAAa,EAAE,MAAM,eAAe,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wB,EAAE,UAAU,CAAC,CAAC;IACvG,CAAC;IA0FM,QAAQ;QACX,MAAM,CAAC,GAAa,EAAE,CAAC;QAEvB,IAAI,CAAC,YAAY,CAAC,CAAC,OAAO,EAAE,EAAE;YAC1B,CAAC,CAAC,IAAI,CAAC,GAAG,OAAO,EAAE,CAAC,CAAC;YACrB,OAAO,IAAI,CAAC;QAChB,CAAC,CAAC,CAAC;QAEH,OAAO,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;IACtB,CAAC;CACJ","sourcesContent":["/*!\n * Copyright (c) Microsoft Corporation and contributors. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { assert } from \"@fluidframework/common-utils\";\nimport { ChildLogger } from \"@fluidframework/telemetry-utils\";\nimport { IFluidDataStoreRuntime, IChannelStorageService } from \"@fluidframework/datastore-definitions\";\nimport { ITelemetryBaseLogger } from \"@fluidframework/common-definitions\";\nimport {\n BaseSegment,\n ISegment,\n Client,\n IMergeTreeDeltaOpArgs,\n IMergeTreeDeltaCallbackArgs,\n MergeTreeDeltaType,\n IMergeTreeMaintenanceCallbackArgs,\n MergeTreeMaintenanceType,\n ReferenceType,\n} from \"@fluidframework/merge-tree\";\nimport { IFluidHandle } from \"@fluidframework/core-interfaces\";\nimport { IFluidSerializer } from \"@fluidframework/shared-object-base\";\nimport { ISummaryTreeWithStats } from \"@fluidframework/runtime-definitions\";\nimport { ObjectStoragePartition, SummaryTreeBuilder } from \"@fluidframework/runtime-utils\";\nimport { ISequencedDocumentMessage } from \"@fluidframework/protocol-definitions\";\nimport { HandleTable, Handle, isHandleValid } from \"./handletable\";\nimport { deserializeBlob } from \"./serialization\";\nimport { HandleCache } from \"./handlecache\";\nimport { VectorUndoProvider } from \"./undoprovider\";\n\nconst enum SnapshotPath {\n segments = \"segments\",\n handleTable = \"handleTable\",\n}\n\ntype PermutationSegmentSpec = [number, number];\n\nexport class PermutationSegment extends BaseSegment {\n public static readonly typeString: string = \"PermutationSegment\";\n private _start = Handle.unallocated;\n\n public static fromJSONObject(spec: any) {\n const [length, start] = spec as PermutationSegmentSpec;\n return new PermutationSegment(length, start);\n }\n\n public readonly type = PermutationSegment.typeString;\n\n constructor(length: number, start = Handle.unallocated) {\n super();\n this._start = start;\n this.cachedLength = length;\n }\n\n public get start() { return this._start; }\n public set start(value: Handle) {\n assert(this._start === Handle.unallocated, 0x024 /* \"Start of PermutationSegment already allocated!\" */);\n assert(isHandleValid(value), 0x025 /* \"Trying to set start of PermutationSegment to invalid handle!\" */);\n\n this._start = value;\n }\n\n /**\n * Invoked by '_undoRow/ColRemove' to prepare the newly inserted destination\n * segment to serve as the replacement for this removed segment. This moves handle\n * allocations from this segment to the replacement as well as maintains tracking\n * groups for the undo/redo stack.\n */\n public transferToReplacement(destination: PermutationSegment) {\n // When this segment was removed, it may have been split from a larger original\n // segment. In this case, it will have been added to an undo/redo tracking group\n // that associates all of the fragments from the original insertion.\n //\n // Move this association from the this removed segment to its replacement so that\n // it is included if the undo stack continues to unwind to the original insertion.\n //\n // Out of paranoia we link and unlink in separate loops to avoid mutating the underlying\n // set during enumeration. In practice, this is unlikely to matter since there should be\n // exactly 0 or 1 items in the enumeration.\n for (const group of this.trackingCollection.trackingGroups) {\n group.link(destination);\n }\n for (const group of this.trackingCollection.trackingGroups) {\n group.unlink(this);\n }\n\n // Move handle allocations from this segment to its replacement.\n destination._start = this._start;\n this.reset();\n }\n\n public reset() {\n this._start = Handle.unallocated;\n }\n\n public toJSONObject() {\n return [this.cachedLength, this.start];\n }\n\n public clone(start = 0, end = this.cachedLength) {\n const b = new PermutationSegment(\n /* length: */ end - start,\n /* start: */ this.start + start);\n this.cloneInto(b);\n return b;\n }\n\n public canAppend(segment: ISegment) {\n const asPerm = segment as PermutationSegment;\n\n return this.start === Handle.unallocated\n ? asPerm.start === Handle.unallocated\n : asPerm.start === this.start + this.cachedLength;\n }\n\n protected createSplitSegmentAt(pos: number) {\n assert(0 < pos && pos < this.cachedLength, 0x026 /* \"Trying to split segment at out-of-bounds position!\" */);\n\n const leafSegment = new PermutationSegment(\n /* length: */ this.cachedLength - pos,\n /* start: */ this.start === Handle.unallocated\n ? Handle.unallocated\n : this.start + pos);\n\n this.cachedLength = pos;\n\n return leafSegment;\n }\n\n public toString() {\n return this.start === Handle.unallocated\n ? `<${this.cachedLength} empty>`\n : `<${this.cachedLength}: ${this.start}..${this.start + this.cachedLength - 1}>`;\n }\n}\n\nexport class PermutationVector extends Client {\n private handleTable = new HandleTable<never>(); // Tracks available storage handles for rows.\n public readonly handleCache = new HandleCache(this);\n public undo: VectorUndoProvider | undefined;\n\n constructor(\n path: string,\n logger: ITelemetryBaseLogger,\n runtime: IFluidDataStoreRuntime,\n private readonly deltaCallback: (position: number, numRemoved: number, numInserted: number) => void,\n private readonly handlesRecycledCallback: (handles: Handle[]) => void,\n ) {\n super(\n PermutationSegment.fromJSONObject,\n ChildLogger.create(logger, `Matrix.${path}.MergeTreeClient`), {\n ...runtime.options,\n newMergeTreeSnapshotFormat: true, // Temporarily force new snapshot format until it is the default.\n }); // (See https://github.com/microsoft/FluidFramework/issues/84)\n\n this.on(\"delta\", this.onDelta);\n this.on(\"maintenance\", this.onMaintenance);\n }\n\n public insert(start: number, length: number) {\n return this.insertSegmentLocal(\n start,\n new PermutationSegment(length));\n }\n\n public insertRelative(segment: ISegment, length: number) {\n const inserted = new PermutationSegment(length);\n\n return {\n op: this.insertAtReferencePositionLocal(\n this.createLocalReferencePosition(segment, 0, ReferenceType.Transient, undefined),\n inserted),\n inserted,\n };\n }\n\n public remove(start: number, length: number) {\n return this.removeRangeLocal(start, start + length);\n }\n\n public getMaybeHandle(pos: number): Handle {\n assert(0 <= pos && pos < this.getLength(), 0x027 /* \"Trying to get handle of out-of-bounds position!\" */);\n\n return this.handleCache.getHandle(pos);\n }\n\n public getAllocatedHandle(pos: number): Handle {\n let handle = this.getMaybeHandle(pos);\n if (isHandleValid(handle)) {\n return handle;\n }\n\n this.walkSegments(\n (segment) => {\n const asPerm = segment as PermutationSegment;\n asPerm.start = handle = this.handleTable.allocate();\n return true;\n },\n pos,\n pos + 1,\n /* accum: */ undefined,\n /* splitRange: */ true);\n\n this.handleCache.addHandle(pos, handle);\n\n return handle;\n }\n\n public adjustPosition(pos: number, op: ISequencedDocumentMessage) {\n const { segment, offset } = this.getContainingSegment(pos, { referenceSequenceNumber: op.referenceSequenceNumber, clientId: op.clientId });\n\n // Note that until the MergeTree GCs, the segment is still reachable via `getContainingSegment()` with\n // a `refSeq` in the past. Prevent remote ops from accidentally allocating or using recycled handles\n // by checking for the presence of 'removedSeq'.\n if (segment === undefined || segment.removedSeq !== undefined) {\n return undefined;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n return this.getPosition(segment) + offset!;\n }\n\n public handleToPosition(handle: Handle, localSeq = this.getCollabWindow().localSeq) {\n assert(localSeq <= this.getCollabWindow().localSeq,\n 0x028 /* \"'localSeq' for op being resubmitted must be <= the 'localSeq' of the last submitted op.\" */);\n\n // TODO: In theory, the MergeTree should be able to map the (position, refSeq, localSeq) from\n // the original operation to the current position for undo/redo scenarios. This is probably the\n // ideal solution, as we would no longer need to store row/col handles in the op metadata.\n //\n // Failing that, we could avoid the O(n) search below by building a temporary map in the\n // opposite direction from the handle to either it's current position or segment + offset\n // and reuse it for the duration of undo/redo. (Ideally, we would know when the undo/redo\n // ended so we could discard this map.)\n //\n // If we find that we frequently need a reverse handle -> position lookup, we could maintain\n // one using the Tiny-Calc adjust tree.\n let containingSegment!: PermutationSegment;\n let containingOffset: number;\n\n this.walkAllSegments(\n (segment) => {\n const { start, cachedLength } = segment as PermutationSegment;\n\n // If the segment is unallocated, skip it.\n if (!isHandleValid(start)) {\n return true;\n }\n\n const end = start + cachedLength;\n\n if (start <= handle && handle < end) {\n containingSegment = segment as PermutationSegment;\n containingOffset = handle - start;\n return false;\n }\n\n return true;\n });\n\n // We are guaranteed to find the handle in the PermutationVector, even if the corresponding\n // row/col has been removed, because handles are not recycled until the containing segment\n // is unlinked from the MergeTree.\n //\n // Therefore, either a row/col removal has been ACKed, in which case there will be no pending\n // ops that reference the stale handle, or the removal is unACKed, in which case the handle\n // has not yet been recycled.\n\n assert(isHandleValid(containingSegment.start), 0x029 /* \"Invalid handle at start of containing segment!\" */);\n\n // Once we know the current position of the handle, we can use the MergeTree to get the segment\n // containing this position and use 'findReconnectionPosition' to adjust for the local ops that\n // have not yet been submitted.\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n return this.findReconnectionPosition(containingSegment, localSeq) + containingOffset!;\n }\n\n // Constructs an ISummaryTreeWithStats for the cell data.\n public summarize(runtime: IFluidDataStoreRuntime, handle: IFluidHandle, serializer: IFluidSerializer):\n ISummaryTreeWithStats {\n const builder = new SummaryTreeBuilder();\n builder.addWithStats(SnapshotPath.segments, super.summarize(runtime, handle, serializer, /* catchUpMsgs: */[]));\n builder.addBlob(SnapshotPath.handleTable, serializer.stringify(this.handleTable.getSummaryContent(), handle));\n return builder.getSummaryTree();\n }\n\n public async load(\n runtime: IFluidDataStoreRuntime,\n storage: IChannelStorageService,\n serializer: IFluidSerializer,\n ) {\n const handleTableData = await deserializeBlob(storage, SnapshotPath.handleTable, serializer);\n\n this.handleTable = HandleTable.load<never>(handleTableData);\n\n return super.load(runtime, new ObjectStoragePartition(storage, SnapshotPath.segments), serializer);\n }\n\n private readonly onDelta = (\n opArgs: IMergeTreeDeltaOpArgs,\n { operation, deltaSegments }: IMergeTreeDeltaCallbackArgs,\n ) => {\n // Apply deltas in descending order to prevent positions from shifting.\n const ranges = deltaSegments\n .map(({ segment }) => ({\n segment: segment as PermutationSegment,\n position: this.getPosition(segment),\n }))\n .sort((left, right) => left.position - right.position);\n\n const isLocal = opArgs.sequencedMessage === undefined;\n\n // Notify the undo provider, if any is attached.\n if (this.undo !== undefined && isLocal) {\n this.undo.record(operation, ranges);\n }\n\n switch (operation) {\n case MergeTreeDeltaType.INSERT:\n // Pass 1: Perform any internal maintenance first to avoid reentrancy.\n for (const { segment, position } of ranges) {\n // HACK: We need to include the allocated handle in the segment's JSON representation\n // for snapshots, but need to ignore the remote client's handle allocations when\n // processing remote ops.\n segment.reset();\n\n this.handleCache.itemsChanged(\n position,\n /* deleteCount: */ 0,\n /* insertCount: */ segment.cachedLength);\n }\n\n // Pass 2: Notify the 'deltaCallback', which may involve callbacks into user code.\n for (const { segment, position } of ranges) {\n this.deltaCallback(position, /* numRemoved: */ 0, /* numInserted: */ segment.cachedLength);\n }\n break;\n\n case MergeTreeDeltaType.REMOVE: {\n // Pass 1: Perform any internal maintenance first to avoid reentrancy.\n for (const { segment, position } of ranges) {\n this.handleCache.itemsChanged(\n position, /* deleteCount: */\n segment.cachedLength,\n /* insertCount: */ 0);\n }\n\n // Pass 2: Notify the 'deltaCallback', which may involve callbacks into user code.\n for (const { segment, position } of ranges) {\n this.deltaCallback(position, /* numRemoved: */ segment.cachedLength, /* numInsert: */ 0);\n }\n break;\n }\n\n default:\n throw new Error(\"Unhandled MergeTreeDeltaType\");\n }\n };\n\n private readonly onMaintenance = (args: IMergeTreeMaintenanceCallbackArgs) => {\n if (args.operation === MergeTreeMaintenanceType.UNLINK) {\n let freed: number[] = [];\n\n for (const { segment } of args.deltaSegments) {\n const asPerm = segment as PermutationSegment;\n if (isHandleValid(asPerm.start)) {\n // Note: Using the spread operator with `.splice()` can exhaust the stack.\n freed = freed.concat(\n new Array(asPerm.cachedLength)\n .fill(0)\n .map((value, index) => index + asPerm.start),\n );\n }\n }\n\n // Notify matrix that handles are about to be freed. The matrix is responsible for clearing\n // the rows/cols prior to free to ensure recycled row/cols are initially empty.\n this.handlesRecycledCallback(freed);\n\n // Now that the physical storage has been cleared, add the recycled handles back to the free pool.\n for (const handle of freed) {\n this.handleTable.free(handle);\n }\n }\n };\n\n public toString() {\n const s: string[] = [];\n\n this.walkSegments((segment) => {\n s.push(`${segment}`);\n return true;\n });\n\n return s.join(\"\");\n }\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fluidframework/matrix",
3
- "version": "2.0.0-internal.2.4.0",
3
+ "version": "2.0.0-internal.3.0.0",
4
4
  "description": "Distributed matrix",
5
5
  "homepage": "https://fluidframework.com",
6
6
  "repository": {
@@ -66,29 +66,29 @@
66
66
  "dependencies": {
67
67
  "@fluidframework/common-definitions": "^0.20.1",
68
68
  "@fluidframework/common-utils": "^1.0.0",
69
- "@fluidframework/core-interfaces": ">=2.0.0-internal.2.4.0 <2.0.0-internal.3.0.0",
70
- "@fluidframework/datastore-definitions": ">=2.0.0-internal.2.4.0 <2.0.0-internal.3.0.0",
71
- "@fluidframework/merge-tree": ">=2.0.0-internal.2.4.0 <2.0.0-internal.3.0.0",
69
+ "@fluidframework/core-interfaces": ">=2.0.0-internal.3.0.0 <2.0.0-internal.4.0.0",
70
+ "@fluidframework/datastore-definitions": ">=2.0.0-internal.3.0.0 <2.0.0-internal.4.0.0",
71
+ "@fluidframework/merge-tree": ">=2.0.0-internal.3.0.0 <2.0.0-internal.4.0.0",
72
72
  "@fluidframework/protocol-base": "^0.1038.2000",
73
73
  "@fluidframework/protocol-definitions": "^1.1.0",
74
- "@fluidframework/runtime-definitions": ">=2.0.0-internal.2.4.0 <2.0.0-internal.3.0.0",
75
- "@fluidframework/runtime-utils": ">=2.0.0-internal.2.4.0 <2.0.0-internal.3.0.0",
76
- "@fluidframework/shared-object-base": ">=2.0.0-internal.2.4.0 <2.0.0-internal.3.0.0",
77
- "@fluidframework/telemetry-utils": ">=2.0.0-internal.2.4.0 <2.0.0-internal.3.0.0",
74
+ "@fluidframework/runtime-definitions": ">=2.0.0-internal.3.0.0 <2.0.0-internal.4.0.0",
75
+ "@fluidframework/runtime-utils": ">=2.0.0-internal.3.0.0 <2.0.0-internal.4.0.0",
76
+ "@fluidframework/shared-object-base": ">=2.0.0-internal.3.0.0 <2.0.0-internal.4.0.0",
77
+ "@fluidframework/telemetry-utils": ">=2.0.0-internal.3.0.0 <2.0.0-internal.4.0.0",
78
78
  "@tiny-calc/nano": "0.0.0-alpha.5",
79
79
  "events": "^3.1.0",
80
80
  "tslib": "^1.10.0"
81
81
  },
82
82
  "devDependencies": {
83
- "@fluid-internal/test-dds-utils": ">=2.0.0-internal.2.4.0 <2.0.0-internal.3.0.0",
83
+ "@fluid-internal/test-dds-utils": ">=2.0.0-internal.3.0.0 <2.0.0-internal.4.0.0",
84
84
  "@fluid-tools/benchmark": "^0.45.0",
85
85
  "@fluid-tools/build-cli": "^0.8.0",
86
86
  "@fluidframework/build-common": "^1.1.0",
87
87
  "@fluidframework/build-tools": "^0.8.0",
88
88
  "@fluidframework/eslint-config-fluid": "^2.0.0",
89
89
  "@fluidframework/matrix-previous": "npm:@fluidframework/matrix@2.0.0-internal.2.2.0",
90
- "@fluidframework/mocha-test-setup": ">=2.0.0-internal.2.4.0 <2.0.0-internal.3.0.0",
91
- "@fluidframework/test-runtime-utils": ">=2.0.0-internal.2.4.0 <2.0.0-internal.3.0.0",
90
+ "@fluidframework/mocha-test-setup": ">=2.0.0-internal.3.0.0 <2.0.0-internal.4.0.0",
91
+ "@fluidframework/test-runtime-utils": ">=2.0.0-internal.3.0.0 <2.0.0-internal.4.0.0",
92
92
  "@microsoft/api-extractor": "^7.22.2",
93
93
  "@rushstack/eslint-config": "^2.5.1",
94
94
  "@tiny-calc/micro": "0.0.0-alpha.5",
@@ -110,9 +110,9 @@
110
110
  "uuid": "^8.3.1"
111
111
  },
112
112
  "typeValidation": {
113
- "version": "2.0.0-internal.2.3.0",
114
- "baselineRange": ">=2.0.0-internal.2.2.0 <2.0.0-internal.2.3.0",
115
- "baselineVersion": "2.0.0-internal.2.2.0",
113
+ "version": "2.0.0-internal.3.0.0",
114
+ "baselineRange": ">=2.0.0-internal.2.0.0 <2.0.0-internal.3.0.0",
115
+ "baselineVersion": "2.0.0-internal.2.1.1",
116
116
  "broken": {}
117
117
  }
118
118
  }
package/src/matrix.ts CHANGED
@@ -26,7 +26,7 @@ import {
26
26
  IMatrixReader,
27
27
  IMatrixWriter,
28
28
  } from "@tiny-calc/nano";
29
- import { MergeTreeDeltaType, IMergeTreeOp, SegmentGroup, ISegment } from "@fluidframework/merge-tree";
29
+ import { MergeTreeDeltaType, IMergeTreeOp, SegmentGroup, ISegment, Client } from "@fluidframework/merge-tree";
30
30
  import { MatrixOp } from "./ops";
31
31
  import { PermutationVector, PermutationSegment } from "./permutationvector";
32
32
  import { SparseArray2D } from "./sparsearray2d";
@@ -497,6 +497,21 @@ export class SharedMatrix<T = any>
497
497
  this.cols.startOrUpdateCollaboration(this.runtime.clientId as string);
498
498
  }
499
499
 
500
+ private rebasePosition(
501
+ client: Client,
502
+ pos: number,
503
+ referenceSequenceNumber: number,
504
+ localSeq: number
505
+ ): number | undefined {
506
+ const { clientId } = client.getCollabWindow();
507
+ const { segment, offset } = client.getContainingSegment(pos, { referenceSequenceNumber, clientId: client.getLongClientId(clientId) }, localSeq);
508
+ if (segment === undefined || offset === undefined) {
509
+ return;
510
+ }
511
+
512
+ return client.findReconnectionPosition(segment, localSeq) + offset;
513
+ }
514
+
500
515
  protected reSubmitCore(content: any, localOpMetadata: unknown) {
501
516
  switch (content.target) {
502
517
  case SnapshotPath.cols:
@@ -519,8 +534,8 @@ export class SharedMatrix<T = any>
519
534
  // to skip resubmitting this op since it is possible the row/col handle has been recycled
520
535
  // and now refers to a different position than when this op was originally submitted.
521
536
  if (this.isLatestPendingWrite(rowHandle, colHandle, localSeq)) {
522
- const row = this.rows.rebasePositionWithoutSegmentSlide(setOp.row, rowsRefSeq, localSeq);
523
- const col = this.cols.rebasePositionWithoutSegmentSlide(setOp.col, colsRefSeq, localSeq);
537
+ const row = this.rebasePosition(this.rows, setOp.row, rowsRefSeq, localSeq);
538
+ const col = this.rebasePosition(this.cols, setOp.col, colsRefSeq, localSeq);
524
539
 
525
540
  if (row !== undefined && col !== undefined && row >= 0 && col >= 0) {
526
541
  this.sendSetCellOp(
@@ -665,7 +680,6 @@ export class SharedMatrix<T = any>
665
680
  // locally removed and the row/col handles recycled. If this happens, the pendingLocalSeq will
666
681
  // be 'undefined' or > 'localSeq'.
667
682
  assert(!(pendingLocalSeq < localSeq),
668
- // eslint-disable-next-line max-len
669
683
  0x023 /* "The 'localSeq' of pending write (if any) must be <= the localSeq of the currently processed op." */);
670
684
 
671
685
  // If this is the most recent write to the cell by the local client, the stored localSeq
@@ -6,4 +6,4 @@
6
6
  */
7
7
 
8
8
  export const pkgName = "@fluidframework/matrix";
9
- export const pkgVersion = "2.0.0-internal.2.4.0";
9
+ export const pkgVersion = "2.0.0-internal.3.0.0";
@@ -153,8 +153,8 @@ export class PermutationVector extends Client {
153
153
  newMergeTreeSnapshotFormat: true, // Temporarily force new snapshot format until it is the default.
154
154
  }); // (See https://github.com/microsoft/FluidFramework/issues/84)
155
155
 
156
- this.mergeTreeDeltaCallback = this.onDelta;
157
- this.mergeTreeMaintenanceCallback = this.onMaintenance;
156
+ this.on("delta", this.onDelta);
157
+ this.on("maintenance", this.onMaintenance);
158
158
  }
159
159
 
160
160
  public insert(start: number, length: number) {
@@ -207,7 +207,7 @@ export class PermutationVector extends Client {
207
207
  }
208
208
 
209
209
  public adjustPosition(pos: number, op: ISequencedDocumentMessage) {
210
- const { segment, offset } = this.getContainingSegment(pos, op);
210
+ const { segment, offset } = this.getContainingSegment(pos, { referenceSequenceNumber: op.referenceSequenceNumber, clientId: op.clientId });
211
211
 
212
212
  // Note that until the MergeTree GCs, the segment is still reachable via `getContainingSegment()` with
213
213
  // a `refSeq` in the past. Prevent remote ops from accidentally allocating or using recycled handles