All files / json-crdt/log/codec LogDecoder.ts

84.07% Statements 95/113
55% Branches 22/40
100% Functions 10/10
94.44% Lines 85/90

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 2031x 1x 1x 1x 1x                                               1x 87x     44x   22x 22x 22x       22x 22x 22x           22x 22x 22x 22x 22x 22x 88x 88x 88x   22x       22x 22x 22x 22x 22x 88x 22x       46x 46x 46x 46x 46x 45x 45x 44x 1x 1x 1x 1x 1x 1x 1x 1x 1x       1x 1x 1x 1x         46x       45x 45x 45x 131x         131x   45x 45x 45x 45x 45x   45x 45x       131x 131x 86x 44x 44x 44x   42x 42x 42x 42x           47x 47x 29x 15x 15x 15x   14x 14x 14x 14x                                                                                                      
import {Model} from '../../model';
import {Log} from '../Log';
import {Patch} from '../../../json-crdt-patch';
import {FileModelEncoding} from './constants';
import {SESSION} from '../../../json-crdt-patch/constants';
import type * as types from './types';
import type {CborDecoder} from '@jsonjoy.com/json-pack/lib/cbor/CborDecoder';
import type {JsonDecoder} from '@jsonjoy.com/json-pack/lib/json/JsonDecoder';
import type {Decoder as SidecarDecoder} from '../../codec/sidecar/binary/Decoder';
import type {Decoder as StructuralDecoderCompact} from '../../codec/structural/compact/Decoder';
import type {Decoder as StructuralDecoderVerbose} from '../../codec/structural/verbose/Decoder';
import type {decode as decodeCompact} from '../../../json-crdt-patch/codec/compact/decode';
import type {decode as decodeVerbose} from '../../../json-crdt-patch/codec/verbose/decode';
import type {CompactCodecPatch} from '../../../json-crdt-patch/codec/compact';
import type {JsonCodecPatch} from '../../../json-crdt-patch/codec/verbose';
import type {JsonCrdtCompactDocument} from '../../codec/structural/compact';
import type {JsonCrdtVerboseDocument} from '../../codec/structural/verbose';
 
export interface LogDecoderOpts {
  jsonDecoder?: JsonDecoder;
  cborDecoder?: CborDecoder;
  structuralCompactDecoder?: StructuralDecoderCompact;
  structuralVerboseDecoder?: StructuralDecoderVerbose;
  sidecarDecoder?: SidecarDecoder;
  patchCompactDecoder?: typeof decodeCompact;
  patchVerboseDecoder?: typeof decodeVerbose;
}
 
export class LogDecoder {
  constructor(protected readonly opts: LogDecoderOpts = {}) {}
 
  public decode(blob: Uint8Array, params: DecodeParams = {}): DecodeResult {
    switch (params.format) {
      case 'ndjson': {
        const components = this.decodeNdjsonComponents(blob);
        const result = this.deserialize(components, params);
        return result;
      }
      default: {
        // 'seq.cbor'
        const components = this.decodeSeqCborComponents(blob);
        const result = this.deserialize(components, params);
        return result;
      }
    }
  }
 
  public decodeNdjsonComponents(blob: Uint8Array): types.LogComponentsWithFrontier {
    const decoder = this.opts.jsonDecoder;
    Iif (!decoder) throw new Error('NO_JSON_DECODER');
    const reader = decoder.reader;
    reader.reset(blob);
    const components: unknown[] = [];
    while (reader.x < blob.length) {
      components.push(decoder.readAny());
      const nl = reader.u8();
      Iif (nl !== '\n'.charCodeAt(0)) throw new Error('NDJSON_UNEXPECTED_NEWLINE');
    }
    return components as types.LogComponentsWithFrontier;
  }
 
  public decodeSeqCborComponents(blob: Uint8Array): types.LogComponentsWithFrontier {
    const decoder = this.opts.cborDecoder;
    Iif (!decoder) throw new Error('NO_CBOR_DECODER');
    const reader = decoder.reader;
    reader.reset(blob);
    const components: unknown[] = [];
    while (reader.x < blob.length) components.push(decoder.val());
    return components as types.LogComponentsWithFrontier;
  }
 
  public deserialize(components: types.LogComponentsWithFrontier, params: DeserializeParams = {}): DecodeResult {
    const [view, metadata, model, , ...frontier] = components;
    const result: DecodeResult = {};
    Iif (params.view) result.view = view;
    if (params.history) result.history = this.deserializeHistory(components);
    if (params.frontier) {
      Iif (!model) result.history = this.deserializeHistory(components);
      if (result.history) {
        result.frontier = result.history;
      } else if (model) {
        const modelFormat = metadata[1];
        const start = (): Model => {
          const isSidecar = modelFormat === FileModelEncoding.SidecarBinary;
          if (isSidecar) {
            const decoder = this.opts.sidecarDecoder;
            Iif (!decoder) throw new Error('NO_SIDECAR_DECODER');
            Iif (!(model instanceof Uint8Array)) throw new Error('NOT_BLOB');
            return decoder.decode(view, model);
          }
          return this.deserializeModel(model);
        };
        const log = new Log(start);
        const end = log.end;
        if (frontier && frontier.length) for (const patch of frontier) end.applyPatch(this.deserializePatch(patch));
        result.frontier = log;
      } else E{
        throw new Error('NO_MODEL');
      }
    }
    return result;
  }
 
  public deserializeHistory(components: types.LogComponentsWithFrontier): Log {
    const [, , , history, ...frontier] = components;
    const [startSerialized] = history;
    const start = (): Model => {
      Iif (!history || !startSerialized) {
        // TODO: Handle case where new model should be started with server clock: `return Model.withServerClock()`.
        // TODO: Handle case where model has to be started with extensions...
        return Model.withLogicalClock(SESSION.GLOBAL);
      }
      return this.deserializeModel(startSerialized);
    };
    const log = new Log(start);
    const end = log.end;
    if (history) {
      const [, patches] = history;
      if (patches) for (const patch of patches) end.applyPatch(this.deserializePatch(patch));
    }
    if (frontier.length) for (const patch of frontier) end.applyPatch(this.deserializePatch(patch));
    return log;
  }
 
  public deserializeModel(serialized: unknown): Model {
    Iif (!serialized) throw new Error('NO_MODEL');
    if (serialized instanceof Uint8Array) return Model.fromBinary(serialized);
    if (Array.isArray(serialized)) {
      const decoder = this.opts.structuralCompactDecoder;
      Iif (!decoder) throw new Error('NO_STRUCTURAL_COMPACT_DECODER');
      return decoder.decode(<JsonCrdtCompactDocument>serialized);
    }
    if (typeof serialized === 'object') {
      const decoder = this.opts.structuralVerboseDecoder;
      Iif (!decoder) throw new Error('NO_STRUCTURAL_VERBOSE_DECODER');
      return decoder.decode(<JsonCrdtVerboseDocument>serialized);
    }
    throw new Error('UNKNOWN_MODEL');
  }
 
  public deserializePatch(serialized: unknown): Patch {
    Iif (!serialized) throw new Error('NO_MODEL');
    if (serialized instanceof Uint8Array) return Patch.fromBinary(serialized);
    if (Array.isArray(serialized)) {
      const decodeCompact = this.opts.patchCompactDecoder;
      Iif (!decodeCompact) throw new Error('NO_PATCH_COMPACT_DECODER');
      return decodeCompact(<CompactCodecPatch>serialized);
    }
    if (typeof serialized === 'object') {
      const decodeVerbose = this.opts.patchVerboseDecoder;
      Iif (!decodeVerbose) throw new Error('NO_PATCH_VERBOSE_DECODER');
      return decodeVerbose(<JsonCodecPatch>serialized);
    }
    throw new Error('UNKNOWN_MODEL');
  }
}
 
export interface DeserializeParams {
  /**
   * Whether to return decoded `view` of the end state of the log as a POJO in
   * the {@link DecodeResult}.
   */
  view?: boolean;
 
  /**
   * Whether to return decoded frontier of the log in the {@link DecodeResult}.
   */
  frontier?: boolean;
 
  /**
   * Whether to return the full history of the log in the {@link DecodeResult}.
   */
  history?: boolean;
}
 
export interface DecodeParams extends DeserializeParams {
  /**
   * The format of the input binary blob, whether it is NDJSON or CBOR-Sequence
   * format.
   */
  format?: 'ndjson' | 'seq.cbor';
}
 
/**
 * Decoding result of a log binary blob.
 */
export interface DecodeResult {
  /**
   * Plain POJO view of the end state of the log.
   */
  view?: unknown;
 
  /**
   * Final state of the log, the end state of the document.
   */
  frontier?: Log;
 
  /**
   * The full history of the log, from the start to the end state.
   */
  history?: Log;
}