All files / json-crdt/log Log.ts

88.26% Statements 173/196
89.28% Branches 50/56
53.57% Functions 15/28
92.12% Lines 152/165

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 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 4143x 3x 3x 3x 3x 3x 3x 3x                         3x                                 3x                         74x 74x 213x   74x 74x 74x                                               132x                                 132x               132x       132x 211x 211x 211x   132x 132x 132x 132x               3x 3x                   44x 48x 44x                             15x 15x 15x 33x 20x   15x                       4x 4x 7x 7x 4x 4x 7x 12x   7x                       4x 4x 9x 6x   1x               11x 11x 11x 11x 11x 56x 56x 56x 56x   11x                                                             3x 3x 3x 3x 3x 3x 3x 3x 7x 7x 7x   3x                                     3x 3x 3x 3x 3x                         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, prev} from 'sonic-forest/lib/util';
import {printTree} from 'tree-dump/lib/printTree';
import {listToUint8} from '@jsonjoy.com/util/lib/buffers/concat';
import {cloneBinary} from '@jsonjoy.com/util/lib/json-clone/cloneBinary';
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>, Metadata extends Record<string, unknown> = Record<string, unknown>>
  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.create()` 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(undefined, sid) as unknown 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);
  }
 
  /**
   * Custom metadata associated with the log, it will be stored in the log's
   * header when serialized with {@link LogEncoder} and can be used to store
   * additional information about the log.
   */
  public metadata: Metadata;
 
  /**
   * 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 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(),
 
    metadata?: Metadata,
  ) {
    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);
    this.metadata = metadata ?? ({} as Metadata);
  }
 
  /**
   * 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();
  }
 
  /**
   * 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;
    };
  }
 
  /**
   * Finds the latest patch for a given session ID.
   *
   * @param sid Session ID to find the latest patch for.
   * @return The latest patch for the given session ID, or `undefined` if no
   *     such patch exists.
   */
  public findMax(sid: number): Patch | undefined {
    let curr = this.patches.max;
    while (curr) {
      if (curr.k.sid === sid) return curr.v;
      curr = prev(curr);
    }
    return;
  }
 
  /**
   * @returns A deep clone of the log, including the start function, metadata,
   *     patches, and the end model.
   */
  public clone(): Log<N, Metadata> {
    const start = this.start;
    const metadata = cloneBinary(this.metadata) as Metadata;
    const end = this.end.clone();
    const log = new Log(start, end, metadata);
    for (const {v} of this.patches.entries()) {
      const patch = v.clone();
      const id = patch.getId();
      Iif (!id) continue;
      log.patches.set(id, patch);
    }
    return log;
  }
 
  // /**
  //  * Adds a batch of patches to the log, without applying them to the `end`
  //  * model. It is assumed that the patches are already applied to the `end`
  //  * model, this method only adds them to the internal patch collection.
  //  *
  //  * If you need to apply patches to the `end` model, use `end.applyBatch(batch)`,
  //  * it will apply them to the model and add them to the log automatically.
  //  *
  //  * @param batch Array of patches to add to the log.
  //  */
  // public add(batch: Patch[]): void {
  //   const patches = this.patches;
  //   for (const patch of batch) {
  //     const id = patch.getId();
  //     if (id) patches.set(id, patch);
  //   }
  // }
 
  /**
   * Rebase a batch of patches on top of the current end of the log, or on top
   * of the latest patch for a given session ID.
   *
   * @param batch A batch of patches to rebase.
   * @param sid Session ID to find the latest patch for rebasing. If not provided,
   *     the latest patch in the log is used.
   * @returns The rebased patches.
   */
  public rebaseBatch(batch: Patch[], sid?: number): Patch[] {
    const rebasePatch = sid ? this.findMax(sid) : this.patches.max?.v;
    Iif (!rebasePatch) return batch;
    const rebaseId = rebasePatch.getId();
    Iif (!rebaseId) return batch;
    let nextTime = rebaseId.time + rebasePatch.span();
    const rebased: Patch[] = [];
    const length = batch.length;
    for (let i = 0; i < length; i++) {
      const patch = batch[i].rebase(nextTime);
      nextTime += patch.span();
      rebased.push(patch);
    }
    return rebased;
  }
 
  /**
   * Resets the log to the state of another log. Consumes all state fron the `to`
   * log. The `to` log will be destroyed and should not be used after calling
   * this method.
   *
   * If you want to preserve the `to` log, use `.clone()` method first.
   *
   * ```ts
   * const log1 = new Log();
   * const log2 = new Log();
   * log1.reset(log2.clone());
   * ```
   *
   * @param to The log to consume the state from.
   */
  public reset(to: Log<N, Metadata>): void {
    this.start = to.start;
    this.metadata = to.metadata;
    this.patches = to.patches;
    this.end.reset(to.end);
    to.destroy();
  }
 
  /**
   * 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.con(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)]),
      ])
    );
  }
}