All files / json-crdt/log Log.ts

85.44% Statements 135/158
93.75% Branches 45/48
41.66% Functions 10/24
87.87% Lines 116/132

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 3023x 3x 3x 3x 3x 3x 3x                         3x                                 3x                     64x 64x 138x   64x 64x 64x                                 110x                                 110x               110x   110x 152x 152x 152x   110x 110x 110x                                       44x 48x 44x                             15x 15x 15x 33x 20x   15x                       4x 4x 7x 7x 4x 4x 7x 12x   7x                           13x 13x 13x 13x   16x 13x 13x 19x 19x 19x 3x 3x   16x   16x 1x 1x 1x 1x 1x   15x 4x 4x 4x   4x 2x 4x 4x 4x 4x         4x 4x 2x   11x 5x 5x 5x 5x 3x 3x 3x 3x 3x 3x 3x   3x 2x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x         1x 1x 1x 1x 1x   1x         13x                                                    
import {AvlMap} from 'sonic-forest/lib/avl/AvlMap';
import {first, next} from 'sonic-forest/lib/util';
import {printTree} from 'tree-dump/lib/printTree';
import {listToUint8} from '@jsonjoy.com/util/lib/buffers/concat';
import {Model} from '../model';
import {toSchema} from '../schema/toSchema';
import {
  DelOp,
  type ITimestampStruct,
  InsArrOp,
  InsBinOp,
  InsObjOp,
  InsStrOp,
  InsValOp,
  InsVecOp,
  type Patch,
  Timespan,
  compare,
} from '../../json-crdt-patch';
import {ArrNode, BinNode, ObjNode, StrNode, ValNode, VecNode} from '../nodes';
import type {FanOutUnsubscribe} from 'thingies/lib/fanout';
import type {Printable} from 'tree-dump/lib/types';
import type {JsonNode} from '../nodes/types';
 
/**
 * The `Log` represents a history of patches applied to a JSON CRDT model. It
 * consists of: (1) a starting {@link Model} instance, (2) a list of {@link Patch} instances,
 * that can be applied to the starting model to reach the current state of the
 * document, and (3) the current state of the document, the `end` {@link Model}.
 *
 * The log can be used to replay the history of patches to any point in time,
 * from the "start" to the "end" of the log, and return the resulting {@link Model}
 * state.
 *
 * @todo Make this implement UILifecycle (start, stop) interface.
 */
export class Log<N extends JsonNode = JsonNode<any>> implements Printable {
  /**
   * Creates a `PatchLog` instance from a newly JSON CRDT model. Checks if
   * the model API buffer has any initial operations applied, if yes, it
   * uses them to create the initial state of the log.
   *
   * @param model A new JSON CRDT model, just created with
   *              `Model.withLogicalClock()` or `Model.withServerClock()`.
   * @returns A new `PatchLog` instance.
   */
  public static fromNewModel<N extends JsonNode = JsonNode<any>>(model: Model<N>): Log<N> {
    const sid = model.clock.sid;
    const log = new Log<N>(
      () => Model.create<any>(undefined, sid) as Model<N>,
    ); /** @todo Maybe provide second arg to `new Log(...)` */
    const api = model.api;
    if (api.builder.patch.ops.length) log.end.applyPatch(api.flush());
    return log;
  }
 
  public static from<N extends JsonNode = JsonNode<any>>(model: Model<N>): Log<N> {
    const frozen = model.toBinary();
    const beginning = () => Model.fromBinary<N>(frozen);
    return new Log<N>(beginning, model);
  }
 
  /**
   * The collection of patches which are applied to the `start()` model to reach
   * the `end` model. The patches in the log, stored in an AVL tree for
   * efficient replaying. The patches are sorted by their logical timestamps
   * and applied in causal order.
   *
   * @readonly
   */
  public readonly patches = new AvlMap<ITimestampStruct, Patch>(compare);
 
  private __onPatch: FanOutUnsubscribe;
  private __onFlush: FanOutUnsubscribe;
 
  constructor(
    /**
     * Model factory function that creates a new JSON CRDT model instance, which
     * is used as the starting point of the log. It is called every time a new
     * model is needed to replay the log.
     *
     * @readonly Internally this function may be updated, but externally it is
     *           read-only.
     *
     * @todo Rename to something else to give way to a `start()` in UILifecycle.
     *     Call "snapshot". Maybe introduce `type Snapshot<N> = () => Model<N>;`.
     */
    public start: () => Model<N>,
 
    /**
     * The end of the log, the current state of the document. It is the model
     * instance that is used to apply new patches to the log.
     *
     * @readonly
     */
    public readonly end: Model<N> = start(),
  ) {
    const onPatch = (patch: Patch) => {
      const id = patch.getId();
      Iif (!id) return;
      this.patches.set(id, patch);
    };
    const api = end.api;
    this.__onPatch = api.onPatch.listen(onPatch);
    this.__onFlush = api.onFlush.listen(onPatch);
  }
 
  /**
   * Call this method to destroy the {@link Log} instance. It unsubscribes patch
   * and flush listeners from the `end` model and clears the patch log.
   */
  public destroy() {
    this.__onPatch();
    this.__onFlush();
    this.patches.clear();
  }
 
  /**
   * Creates a new model instance using the `start()` factory function and
   * replays all patches in the log to reach the current state of the document.
   *
   * @returns A new model instance with all patches replayed.
   */
  public replayToEnd(): Model<N> {
    const clone = this.start().clone();
    for (let node = first(this.patches.root); node; node = next(node)) clone.applyPatch(node.v);
    return clone;
  }
 
  /**
   * Replays the patch log until a specified timestamp, including the patch
   * at the given timestamp. The model returned is a new instance of `start()`
   * with patches replayed up to the given timestamp.
   *
   * @param ts Timestamp ID of the patch to replay to.
   * @param inclusive If `true`, the patch at the given timestamp `ts` is included,
   *     otherwise replays up to the patch before the given timestamp. Default is `true`.
   * @returns A new model instance with patches replayed up to the given timestamp.
   */
  public replayTo(ts: ITimestampStruct, inclusive: boolean = true): Model<N> {
    // TODO: PERF: Make `.clone()` implicit in `.start()`.
    const clone = this.start().clone();
    let cmp: number = 0;
    for (let node = first(this.patches.root); node && (cmp = compare(ts, node.k)) >= 0; node = next(node)) {
      if (cmp === 0 && !inclusive) break;
      clone.applyPatch(node.v);
    }
    return clone;
  }
 
  /**
   * Advance the start of the log to a specified timestamp, excluding the patch
   * at the given timestamp. This method removes all patches from the log that
   * are older than the given timestamp and updates the `start()` factory
   * function to replay the log from the new start.
   *
   * @param ts Timestamp ID of the patch to advance to.
   */
  public advanceTo(ts: ITimestampStruct): void {
    const newStartPatches: Patch[] = [];
    let node = first(this.patches.root);
    for (; node && compare(ts, node.k) >= 0; node = next(node)) newStartPatches.push(node.v);
    for (const patch of newStartPatches) this.patches.del(patch.getId()!);
    const oldStart = this.start;
    this.start = (): Model<N> => {
      const model = oldStart();
      for (const patch of newStartPatches) model.applyPatch(patch);
      /** @todo Freeze the old model here, by `model.toBinary()`, it needs to be cloned on .start() anyways. */
      return model;
    };
  }
 
  /**
   * Creates a patch which reverts the given patch. The RGA insertion operations
   * are reversed just by deleting the inserted values. All other operations
   * require time travel to the state just before the patch was applied, so that
   * a copy of a mutated object can be created and inserted back into the model.
   *
   * @param patch The patch to undo
   * @returns A new patch that undoes the given patch
   */
  public undo(patch: Patch): Patch {
    const ops = patch.ops;
    const length = ops.length;
    Iif (!length) throw new Error('EMPTY_PATCH');
    const id = patch.getId();
    let __model: Model<N> | undefined;
    const getModel = () => __model || (__model = this.replayTo(id!, false));
    const builder = this.end.api.builder;
    for (let i = length - 1; i >= 0; i--) {
      const op = ops[i];
      const opId = op.id;
      if (op instanceof InsStrOp || op instanceof InsArrOp || op instanceof InsBinOp) {
        builder.del(op.obj, [new Timespan(opId.sid, opId.time, op.span())]);
        continue;
      }
      const model = getModel();
      // TODO: Do not overwrite already deleted values? Or needed for concurrency? Orphaned nodes.
      if (op instanceof InsValOp) {
        const val = model.index.get(op.obj);
        if (val instanceof ValNode) {
          const schema = toSchema(val.node());
          const newId = schema.build(builder);
          builder.setVal(op.obj, newId);
        }
      } else if (op instanceof InsObjOp || op instanceof InsVecOp) {
        const data: (typeof op)['data'] = [];
        const container = model.index.get(op.obj);
        for (const [key] of op.data) {
          let value: JsonNode | undefined;
          if (container instanceof ObjNode) value = container.get(key + '');
          else if (container instanceof VecNode) value = container.get(+key);
          if (value) {
            const schema = toSchema(value);
            const newId = schema.build(builder);
            data.push([key, newId] as any);
          } else E{
            data.push([key, builder.const(undefined)] as any);
          }
        }
        if (data.length) {
          if (op instanceof InsObjOp) builder.insObj(op.obj, data as InsObjOp['data']);
          else if (op instanceof InsVecOp) builder.insVec(op.obj, data as InsVecOp['data']);
        }
      } else if (op instanceof DelOp) {
        const node = model.index.find(op.obj);
        if (node) {
          const rga = node.v;
          if (rga instanceof StrNode) {
            let str = '';
            for (const span of op.what) str += rga.spanView(span).join('');
            let after = op.obj;
            const firstDelSpan = op.what[0];
            if (firstDelSpan) {
              const after2 = rga.prevId(firstDelSpan);
              if (after2) after = after2;
            }
            builder.insStr(op.obj, after, str);
          } else if (rga instanceof BinNode) {
            const buffers: Uint8Array[] = [];
            for (const span of op.what) buffers.push(...rga.spanView(span));
            let after = op.obj;
            const firstDelSpan = op.what[0];
            if (firstDelSpan) {
              const after2 = rga.prevId(firstDelSpan);
              if (after2) after = after2;
            }
            const blob = listToUint8(buffers);
            builder.insBin(op.obj, after, blob);
          } else if (rga instanceof ArrNode) {
            const copies: ITimestampStruct[] = [];
            for (const span of op.what) {
              const ids2 = rga.spanView(span);
              for (const ids of ids2) {
                for (const id of ids) {
                  const node = model.index.get(id);
                  if (node) {
                    const schema = toSchema(node);
                    const newId = schema.build(builder);
                    copies.push(newId);
                  }
                }
              }
            }
            let after = op.obj;
            const firstDelSpan = op.what[0];
            if (firstDelSpan) {
              const after2 = rga.prevId(firstDelSpan);
              if (after2) after = after2;
            }
            builder.insArr(op.obj, after, copies);
          }
        }
      }
    }
    return builder.flush();
  }
 
  // ---------------------------------------------------------------- Printable
 
  public toString(tab?: string) {
    const patches: Patch[] = [];
    // biome-ignore lint: patches are not iterable
    this.patches.forEach(({v}) => patches.push(v));
    return (
      'log' +
      printTree(tab, [
        (tab) => 'start' + printTree(tab, [(tab) => this.start().toString(tab)]),
        () => '',
        (tab) =>
          'history' +
          printTree(
            tab,
            patches.map((patch, i) => (tab) => `${i}: ${patch.toString(tab)}`),
          ),
        () => '',
        (tab) => 'end' + printTree(tab, [(tab) => this.end.toString(tab)]),
      ])
    );
  }
}