All files / json-crdt-server/src/services/blocks BlocksServices.ts

86.87% Statements 139/160
70.65% Branches 65/92
80.76% Functions 21/26
92.48% Lines 123/133

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 2686x 6x 6x 6x 6x 6x     6x     6x 1313x 1313x 1313x 1313x 1313x 1337x                                                   6x       105x 105x 105x         105x       107x 107x 31x 31x           31x 31x 31x   76x 76x 76x           79x 76x           76x 76x 76x 76x 76x       107x 107x             1310x 1310x             133x 133x 133x 89x       3x 3x 3x 3x 3x       24x 24x 24x       24x                 24x 24x 24x 24x 24x 24x 24x 1x       23x 23x 23x         23x       23x 23x 11x 11x         12x               468x 468x   468x 468x 9x 3x 3x   6x   459x 456x 453x 453x 300x 300x       1240x 3x 3x 3x 3x 3x     1237x 1237x 1237x 1237x 1234x 1234x 1234x 1234x 1234x 1255x 1255x   1234x         1234x 1234x 1234x 180x   1234x 1234x 1234x             180x 180x 180x 180x 180x 182x 180x         15x 15x 15x       1x       1341x 1341x 4x              
import {RpcError} from '@jsonjoy.com/rpc-error';
import {MemoryStore} from './store/MemoryStore';
import {Model, Patch} from 'json-joy/lib/json-crdt';
import {go} from 'thingies/lib/go';
import {storageSpaceReclaimDecision} from './util';
import * as fs from 'fs';
import type {StoreSnapshot, StoreIncomingBatch, StoreBatch, StoreIncomingSnapshot, Store} from './store/types';
import type {Services} from '../Services';
import {filter, type Observable} from 'rxjs';
import type {TBlockEvent, TBlockUpdateEvent, TBlockDeleteEvent, TBlockCreateEvent} from '../../routes/block/schema';
 
const validateBatch = (batch: StoreIncomingBatch) => {
  Iif (!batch || typeof batch !== 'object' || Array.isArray(batch)) throw RpcError.validation('INVALID_BATCH');
  const {patches} = batch;
  Iif (!Array.isArray(patches)) throw RpcError.validation('INVALID_PATCHES');
  Iif (patches.length > 100) throw RpcError.validation('TOO_MANY_PATCHES');
  Iif (patches.length < 1) throw RpcError.validation('TOO_FEW_PATCHES');
  for (const patch of patches) Iif (patch.blob.length > 20000) throw RpcError.validation('PATCH_TOO_LARGE');
};
 
export interface BlocksServicesOpts {
  /**
   * How many historic batches to keep per block.
   */
  historyPerBlock: number;
 
  /**
   * @param seq Current block sequence number.
   * @param pushSize The total blob size of the patches bushed by the latest push.
   * @returns Whether to compact the history.
   */
  historyCompactionDecision: (seq: number, pushSize: number) => boolean;
 
  /**
   * As part of GC, check if we need to delete some of the oldest blocks.
   * Returns the number of oldest blocks to delete. If 0, no blocks will be
   * deleted.
   *
   * @returns The number of oldest blocks to delete.
   */
  spaceReclaimDecision?: () => Promise<number>;
}
 
export class BlocksServices {
  protected readonly spaceReclaimDecision: Required<BlocksServicesOpts>['spaceReclaimDecision'];
 
  constructor(
    protected readonly services: Services,
    protected readonly store: Store = new MemoryStore(),
    protected readonly opts: BlocksServicesOpts = {
      historyPerBlock: 10000,
      historyCompactionDecision: (seq, pushSize) => pushSize > 250 || !(seq % 100),
    },
  ) {
    this.spaceReclaimDecision = opts.spaceReclaimDecision ?? storageSpaceReclaimDecision(fs.promises);
  }
 
  public async create(id: string, clientId: number, batch?: StoreIncomingBatch) {
    const now = Date.now();
    if (!batch) {
      const model = Model.create(void 0, 2 /* SESSION.GLOBAL */);
      const snapshot: StoreSnapshot = {
        id,
        seq: -1,
        blob: model.toBinary(),
        ts: now,
      };
      this.__emitNew(id);
      go(() => this.gc());
      return await this.store.create(snapshot, snapshot);
    }
    validateBatch(batch);
    const model = Model.create(void 0, 2 /* SESSION.GLOBAL */);
    const start: StoreSnapshot = {
      id,
      seq: -1,
      ts: now,
      blob: model.toBinary(),
    };
    for (const patch of batch.patches) model.applyPatch(Patch.fromBinary(patch.blob));
    const end: StoreSnapshot = {
      id,
      seq: 0,
      ts: now,
      blob: model.toBinary(),
    };
    const res = await this.store.create(start, end, batch);
    this.__emitNew(id);
    Eif (res.batch) this.__emitUpd(id, res.batch, clientId);
    go(() => this.gc());
    return res;
  }
 
  private __emitNew(id: string) {
    const msg: TBlockCreateEvent = ['new'];
    this.services.pubsub.publish(`__block:${id}`, msg).catch((error) => {
      // tslint:disable-next-line:no-console
      console.error('Error publishing new block', error);
    });
  }
 
  private __emitUpd(id: string, batch: StoreBatch, clientId: number) {
    const msg: TBlockUpdateEvent = ['upd', {batch}, clientId];
    this.services.pubsub.publish(`__block:${id}`, msg).catch((error) => {
      // tslint:disable-next-line:no-console
      console.error('Error publishing block patches', error);
    });
  }
 
  public async get(id: string) {
    const {store} = this;
    const result = await store.get(id);
    if (!result) throw RpcError.notFound();
    return result;
  }
 
  public async view(id: string) {
    const {store} = this;
    const result = await store.get(id);
    Iif (!result) throw RpcError.notFound();
    const model = Model.load(result.block.snapshot.blob);
    return model.view();
  }
 
  public async remove(id: string) {
    const deleted = await this.store.remove(id);
    const msg: TBlockDeleteEvent = ['del'];
    this.services.pubsub.publish(`__block:${id}`, msg).catch((error) => {
      // tslint:disable-next-line:no-console
      console.error('Error publishing block deletion', error);
    });
    return deleted;
  }
 
  public async scan(
    id: string,
    includeStartSnapshot: boolean,
    offset: number | undefined,
    limit: number | undefined = 10,
  ) {
    const {store} = this;
    Iif (typeof offset !== 'number') offset = await store.seq(id);
    Iif (typeof offset !== 'number') throw RpcError.notFound();
    let min = 0,
      max = 0;
    Iif (limit !== 0 && (!limit || Math.round(limit) !== limit)) throw RpcError.badRequest('INVALID_LIMIT');
    if (limit === 0) {
      return includeStartSnapshot
        ? {snapshot: (await store.getSnapshot(id, Number(offset) || 0)).snapshot, batches: []}
        : {batches: []};
    }
    if (limit > 0) {
      min = Number(offset) || 0;
      max = min + limit - 1;
    } else E{
      max = Number(offset) || 0;
      min = max + limit + 1;
    }
    Iif (min < 0) {
      min = 0;
      max = Math.abs(limit);
    }
    const batches = await store.scan(id, min, max);
    if (includeStartSnapshot) {
      const snap = await store.getSnapshot(id, min - 1);
      return {
        snapshot: snap.snapshot,
        batches: snap.batches.concat(batches),
      };
    }
    return {batches};
  }
 
  public async pull(
    id: string,
    lastKnownSeq: number,
    create = false,
  ): Promise<{batches: StoreBatch[]; snapshot?: StoreSnapshot}> {
    const {store} = this;
    Iif (typeof lastKnownSeq !== 'number' || lastKnownSeq !== Math.round(lastKnownSeq) || lastKnownSeq < -1)
      throw RpcError.validation('INVALID_SEQ');
    const seq = await store.seq(id);
    if (seq === undefined) {
      if (create) {
        const res = await this.create(id, 0);
        return {snapshot: res.block.snapshot, batches: res.batch ? [res.batch] : []};
      }
      throw RpcError.notFound();
    }
    if (lastKnownSeq > seq) return await store.getSnapshot(id, seq);
    if (lastKnownSeq === seq) return {batches: []};
    const delta = seq - lastKnownSeq;
    if (lastKnownSeq === -1 || delta > 100) return await store.getSnapshot(id, seq);
    const batches = await store.scan(id, lastKnownSeq + 1, seq);
    return {batches};
  }
 
  public async edit(id: string, batch: StoreIncomingBatch, createIfNotExists: boolean, clientId: number) {
    if (createIfNotExists) {
      const exists = await this.store.exists(id);
      Eif (!exists) {
        const res = await this.create(id, 0, batch);
        Iif (!res.batch) throw RpcError.internal('Batch not returned');
        return {snapshot: res.block.snapshot, batch: res.batch!};
      }
    }
    validateBatch(batch);
    const {store} = this;
    const get = await store.get(id);
    if (!get) throw RpcError.notFound();
    const snapshot = get.block.snapshot;
    const seq = snapshot.seq + 1;
    const model = Model.fromBinary(snapshot.blob);
    let blobSize = 0;
    for (const {blob} of batch.patches) {
      blobSize += blob.length;
      model.applyPatch(Patch.fromBinary(blob));
    }
    const newSnapshot: StoreIncomingSnapshot = {
      id,
      seq,
      blob: model.toBinary(),
    };
    const res = await store.push(newSnapshot, batch);
    const opts = this.opts;
    if (seq > opts.historyPerBlock && store.compact && opts.historyCompactionDecision(seq, blobSize)) {
      go(() => this.compact(id, seq - opts.historyPerBlock));
    }
    this.__emitUpd(id, res.batch, clientId);
    go(() => this.gc());
    return {
      snapshot: res.snapshot,
      batch: res.batch,
    };
  }
 
  protected async compact(id: string, to: number) {
    const store = this.store;
    Iif (!store.compact) return;
    await store.compact!(id, to, async (blob, iterator) => {
      const model = Model.fromBinary(blob);
      for await (const batch of iterator)
        for (const patch of batch.patches) model.applyPatch(Patch.fromBinary(patch.blob));
      return model.toBinary();
    });
  }
 
  public listen(id: string, clientId: number): Observable<TBlockEvent> {
    let obs = this.services.pubsub.listen$(`__block:${id}`) as Observable<TBlockEvent>;
    if (clientId) obs = obs.pipe(filter(([, , c]) => c !== clientId));
    return obs;
  }
 
  public stats() {
    return this.store.stats();
  }
 
  protected async gc(): Promise<void> {
    const blocksToDelete = await this.spaceReclaimDecision();
    if (blocksToDelete <= 0) return;
    await this.store.removeOldest(blocksToDelete);
  }
 
  public async stop() {
    await this.store.stop?.();
  }
}