All files / json-crdt/__tests__/fuzzer SessionLogical.ts

94.18% Statements 162/172
82.69% Branches 43/52
100% Functions 10/10
100% Lines 143/143

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 2216x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x     6x 6x 6x 6x 6x   6x   6x 6x 6x 6x 6x 6x 6x 6x   6x 1000x 1000x     1000x 1000x 1000x   1000x     1000x 1000x   1000x 1000x 3553x 3553x 3553x 3553x 3553x         1000x 3553x         3553x 3553x 21459x         21459x 21459x 21459x 21459x 14138x 8267x 5580x 5246x 4643x 16816x 16816x 16816x 13804x 13804x 13804x 13804x     16816x 16816x       7321x 7321x 7321x 7321x 5868x 5868x 5868x 5868x 1453x 1453x 1453x 1453x 1453x 1453x   7321x       5871x 5871x 5871x 5871x 3177x 3177x 3177x 3177x 2694x 2694x 2694x 2694x 2694x 2694x   5871x       2687x 2687x 2687x 1517x                         1517x 1517x     1170x   2687x       334x 334x 334x 334x 205x 205x 205x   157x 157x   157x 157x       129x 129x 129x 129x   334x       603x   603x     603x 603x       1000x 3553x 3553x 2669x 2669x 2669x 2669x   3553x 15571x 15571x 74017x     3553x   1000x 3553x 3553x 16816x     1000x      
import {decode as decodeBinary, encode as encodeBinary} from '../../../json-crdt-patch/codec/binary';
import {decode as decodeCompact} from '../../../json-crdt-patch/codec/compact/decode';
import {decode as decodeJson} from '../../../json-crdt-patch/codec/verbose/decode';
import {Decoder as BinaryDecoder} from '../../codec/structural/binary/Decoder';
import {Decoder as CompactDecoder} from '../../codec/structural/compact/Decoder';
import {Decoder as JsonDecoder} from '../../codec/structural/verbose/Decoder';
import {DelOp, InsObjOp, InsStrOp, InsBinOp, InsArrOp} from '../../../json-crdt-patch/operations';
import {encode as encodeCompact} from '../../../json-crdt-patch/codec/compact/encode';
import {encode as encodeJson} from '../../../json-crdt-patch/codec/verbose/encode';
import {Encoder as BinaryEncoder} from '../../codec/structural/binary/Encoder';
import {Encoder as CompactEncoder} from '../../codec/structural/compact/Encoder';
import {Encoder as JsonEncoder} from '../../codec/structural/verbose/Encoder';
import {Encoder as IndexedBinaryEncoder} from '../../codec/indexed/binary/Encoder';
import {Decoder as IndexedBinaryDecoder} from '../../codec/indexed/binary/Decoder';
import {generateInteger} from './util';
import type {Model} from '../..';
import type {Patch} from '../../../json-crdt-patch/Patch';
import {PatchBuilder} from '../../../json-crdt-patch/PatchBuilder';
import {RandomJson} from '@jsonjoy.com/util/lib/json-random/RandomJson';
import {randomU32} from 'hyperdyperid/lib/randomU32';
import {StrNode, ValNode, ObjNode, ArrNode, BinNode} from '../../nodes';
import {interval} from '../../../json-crdt-patch/clock';
import type {JsonCrdtFuzzer} from './JsonCrdtFuzzer';
import {Fuzzer} from '@jsonjoy.com/util/lib/Fuzzer';
 
const jsonEncoder = new JsonEncoder();
const jsonDecoder = new JsonDecoder();
const compactEncoder = new CompactEncoder();
const compactDecoder = new CompactDecoder();
const binaryEncoder = new BinaryEncoder();
const binaryDecoder = new BinaryDecoder();
const indexedBinaryEncoder = new IndexedBinaryEncoder();
const indexedBinaryDecoder = new IndexedBinaryDecoder();
 
export class SessionLogical {
  public models: Model[] = [];
  public patches: Patch[][] = [];
 
  public modelStart: unknown;
  public modelsStart: unknown[] = [];
  public modelsEnd: unknown[] = [];
  public patchesSerialized: unknown[][] = [];
 
  public readonly debug = false;
 
  public constructor(
    public fuzzer: JsonCrdtFuzzer,
    public concurrency: number,
  ) {
    Iif (this.debug) this.modelStart = jsonEncoder.encode(fuzzer.model);
    for (let i = 0; i < concurrency; i++) {
      const model = fuzzer.model.fork();
      this.models.push(model);
      Iif (this.debug) this.modelsStart.push(jsonEncoder.encode(model));
      this.patches.push([]);
      this.patchesSerialized.push([]);
    }
  }
 
  public generateEdits() {
    for (let i = 0; i < this.concurrency; i++) {
      this.generatePeerEdits(i);
    }
  }
 
  private generatePeerEdits(peer: number) {
    const patchCount = generateInteger(...this.fuzzer.opts.patchesPerPeer);
    for (let patchIndex = 0; patchIndex < patchCount; patchIndex++) {
      this.generatePatchForPeer(peer);
    }
  }
 
  private generatePatchForPeer(peer: number) {
    const model = this.models[peer];
    const node = this.fuzzer.picker.pickNode(model);
    let patch: Patch | null = null;
    if (node instanceof StrNode) patch = this.generateStringPatch(model, node);
    else if (node instanceof BinNode) patch = this.generateBinaryPatch(model, node);
    else if (node instanceof ObjNode) patch = this.generateObjectPatch(model, node);
    else if (node instanceof ArrNode) patch = this.generateArrayPatch(model, node);
    else if (node instanceof ValNode) patch = this.generateValuePatch(model, node);
    else return;
    Iif (!patch) return;
    model.applyPatch(patch);
    if (this.fuzzer.opts.testCodecs) {
      if (patch.span()) {
        if (randomU32(0, 1)) patch = decodeJson(encodeJson(patch));
        if (randomU32(0, 1)) patch = decodeCompact(encodeCompact(patch));
        if (randomU32(0, 1)) patch = decodeBinary(encodeBinary(patch));
      }
    }
    this.patches[peer].push(patch);
    Iif (this.debug) this.patchesSerialized[peer].push(encodeJson(patch));
  }
 
  private generateStringPatch(model: Model, node: StrNode): Patch | null {
    const opcode = this.fuzzer.picker.pickStringOperation(node);
    const builder = new PatchBuilder(model.clock);
    const size = node.length();
    if (opcode === InsStrOp) {
      const substring = this.fuzzer.picker.generateSubstring();
      const pos = !size ? 0 : Math.min(size - 1, Math.floor(Math.random() * (size + 1)));
      const posId = !size ? node.id : node.find(pos)!;
      builder.insStr(node.id, posId, substring);
    } else if (opcode === DelOp) {
      Iif (!size) return null;
      const pos = randomU32(0, size - 1);
      const length = randomU32(1, size - pos);
      const spans = node.findInterval(pos, length);
      builder.del(node.id, spans);
    }
    return builder.patch;
  }
 
  private generateBinaryPatch(model: Model, node: BinNode): Patch | null {
    const opcode = this.fuzzer.picker.pickBinaryOperation(node);
    const builder = new PatchBuilder(model.clock);
    const size = node.length();
    if (opcode === InsBinOp) {
      const substring = this.fuzzer.picker.generateBinaryData();
      const pos = !size ? 0 : Math.min(size - 1, Math.floor(Math.random() * (size + 1)));
      const posId = !size ? node.id : node.find(pos)!;
      builder.insBin(node.id, posId, substring);
    } else if (opcode === DelOp) {
      Iif (!size) return null;
      const pos = randomU32(0, size - 1);
      const length = randomU32(1, size - pos);
      const spans = node.findInterval(pos, length);
      builder.del(node.id, spans);
    }
    return builder.patch;
  }
 
  private generateObjectPatch(model: Model, node: ObjNode): Patch {
    const [key, opcode] = this.fuzzer.picker.pickObjectOperation(node);
    const builder = new PatchBuilder(model.clock);
    if (opcode === InsObjOp) {
      const json = RandomJson.generate({
        nodeCount: 3,
        odds: {
          null: 1,
          boolean: 2,
          number: 10,
          string: 8,
          binary: 4,
          array: 2,
          object: 2,
        },
      });
      // console.log('ADDING KEY', key, json);
      const valueId = builder.json(json);
      builder.insObj(node.id, [[key, valueId]]);
    } else {
      // console.log('DELETING KEY', JSON.stringify(key))
      builder.insObj(node.id, [[key, builder.const(undefined)]]);
    }
    return builder.patch;
  }
 
  private generateArrayPatch(model: Model, node: ArrNode): Patch {
    const opcode = this.fuzzer.picker.pickArrayOperation(node);
    const builder = new PatchBuilder(model.clock);
    const length = node.length();
    if (opcode === InsArrOp) {
      const json = RandomJson.generate({nodeCount: Math.ceil(Math.random() * 5)});
      const valueId = builder.json(json);
      if (!length) builder.insArr(node.id, node.id, [valueId]);
      else {
        const pos = Math.ceil(Math.random() * length);
        Iif (!pos) builder.insArr(node.id, node.id, [valueId]);
        else {
          const afterId = node.find(pos - 1)!;
          builder.insArr(node.id, afterId, [valueId]);
        }
      }
    } else {
      Iif (!length) return builder.patch;
      const pos = Math.floor(Math.random() * length);
      const valueId = node.find(pos)!;
      builder.del(node.id, [interval(valueId, 0, 1)]);
    }
    return builder.patch;
  }
 
  private generateValuePatch(model: Model, node: ValNode): Patch {
    const builder = new PatchBuilder(model.clock);
    const value =
      Math.random() > 0.1
        ? Fuzzer.pick([0, 1, -1, 5, -5, 1111, -2222, 4444444444, -888888888888, RandomJson.genNumber()])
        : RandomJson.generate();
    builder.setVal(node.id, builder.constOrJson(value));
    return builder.patch;
  }
 
  public synchronize() {
    for (let i = 0; i < this.concurrency; i++) {
      let model = this.models[i];
      if (this.fuzzer.opts.testCodecs) {
        if (randomU32(0, 1)) model = jsonDecoder.decode(jsonEncoder.encode(model));
        if (randomU32(0, 1)) model = compactDecoder.decode(compactEncoder.encode(model));
        if (randomU32(0, 1)) model = binaryDecoder.decode(binaryEncoder.encode(model));
        if (randomU32(0, 1)) model = indexedBinaryDecoder.decode(indexedBinaryEncoder.encode(model));
      }
      for (let j = 0; j < this.concurrency; j++) {
        const patches = this.patches[j];
        for (const patch of patches) {
          model.applyPatch(patch);
        }
      }
      this.models[i] = model;
    }
    for (let j = 0; j < this.concurrency; j++) {
      const patches = this.patches[j];
      for (const patch of patches) {
        this.fuzzer.model.applyPatch(patch);
      }
    }
    Iif (this.debug) for (const model of this.models) this.modelsEnd.push(jsonEncoder.encode(model));
  }
}