All files / json-crdt-server/src/services/blocks/store/level LevelStore.ts

89.83% Statements 168/187
68.11% Branches 47/69
89.65% Functions 26/29
96.4% Lines 161/167

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 2986x 6x 6x 6x 6x               6x   62x 62x 62x       4670x       2448x       268x       1938x       1625x 1625x       843x       840x         1598x 1598x 1598x 1598x 1569x 1569x                     110x 110x 110x 110x 110x 110x 110x 110x 106x 106x 106x 15430x 15430x     110x               24x 24x 24x       313x 313x 313x 313x 306x 306x 306x 306x 306x                 70x 49x 49x   70x 70x 70x 70x 70x 70x 70x 68x 68x         68x 68x 49x 49x         49x 49x 49x 49x 49x   68x 68x               756x 756x 756x 756x 756x 756x 756x 756x 756x 756x 756x 756x 756x 756x 756x 756x         756x 756x 756x         756x 756x         90x 90x 90x 90x 90x 90x 90x 90x 90x   90x 91x 91x     90x 90x 90x 90x 90x         214x 214x 214x 214x 214x 10478x 10478x   214x       20x 20x 16x 16x 16x 16x 16x             16x   16x                       1x 1x 1x 1x 1x 1x 2x 2x 1x 1x 1x 1x         8x 2x 2x 2x 2x 2x 2x 2x 9x 9x 3x 3x   6x 6x 3x 3x 3x     2x 2x 3x 3x 3x                  
import {RpcError} from '@jsonjoy.com/rpc-error';
import {Writer} from '@jsonjoy.com/buffers/lib/Writer';
import {CborJsonValueCodec} from '@jsonjoy.com/json-pack/lib/codecs/cbor';
import {AvlMap} from 'sonic-forest/lib/avl/AvlMap';
import {Mutex} from '../../../../util/Mutex';
import type {AbstractBatchOperation, AbstractLevel} from 'abstract-level';
import type {JsonValueCodec} from '@jsonjoy.com/json-pack/lib/codecs/types';
import type * as types from '../types';
 
type BinStrLevel = AbstractLevel<any, string, Uint8Array>;
type BinStrLevelOperation = AbstractBatchOperation<BinStrLevel, string, Uint8Array>;
 
export class LevelStore implements types.Store {
  constructor(
    protected readonly kv: BinStrLevel,
    protected readonly codec: JsonValueCodec = new CborJsonValueCodec(new Writer() as any),
    protected readonly mutex: Mutex = new Mutex(),
  ) {}
 
  protected keyBase(id: string) {
    return 'b!' + id + '!';
  }
 
  protected endKey(id: string) {
    return this.keyBase(id) + 'e';
  }
 
  protected startKey(id: string) {
    return this.keyBase(id) + 's';
  }
 
  protected batchBase(id: string) {
    return this.keyBase(id) + 'b!';
  }
 
  protected batchKey(id: string, seq: number) {
    const seqFormatted = seq.toString(36).padStart(6, '0');
    return this.batchBase(id) + seqFormatted;
  }
 
  protected touchKeyBase() {
    return 'u!';
  }
 
  protected touchKey(id: string) {
    return this.touchKeyBase() + id + '!';
  }
 
  /** @todo Add in-memory cache on read. */
  public async get(id: string): Promise<types.StoreGetResult | undefined> {
    const key = this.endKey(id);
    try {
      const blob = await this.kv.get(key);
      if (!blob) return;
      const block = this.codec.decoder.decode(blob) as types.StoreBlock;
      return {block};
    } catch (error) {
      if (error && typeof error === 'object' && (error as any).code === 'LEVEL_NOT_FOUND') return;
      throw error;
    }
  }
 
  public async getSnapshot(
    id: string,
    seq: number,
  ): Promise<{snapshot: types.StoreSnapshot; batches: types.StoreBatch[]}> {
    const {kv, codec} = this;
    const {decoder} = codec;
    const key = this.startKey(id);
    try {
      const blob = await kv.get(key);
      const snapshot = decoder.decode(blob as any) as types.StoreSnapshot;
      const batches: types.StoreBatch[] = [];
      if (snapshot.seq < seq) {
        const gte = this.batchKey(id, snapshot.seq + 1);
        const lte = this.batchKey(id, seq);
        for await (const blob of kv.values({gte, lte: lte})) {
          const batch = decoder.decode(blob) as types.StoreBatch;
          batches.push(batch);
        }
      }
      return {snapshot, batches};
    } catch (error) {
      if (error && typeof error === 'object' && (error as any).code === 'LEVEL_NOT_FOUND') throw RpcError.notFound();
      throw error;
    }
  }
 
  public async exists(id: string): Promise<boolean> {
    const key = this.endKey(id);
    const existing = await this.kv.keys({gte: key, lte: key, limit: 1}).all();
    return existing && existing.length > 0;
  }
 
  public async seq(id: string): Promise<number | undefined> {
    return await this.mutex.acquire(id, async () => {
      const base = this.batchBase(id);
      const keys = await this.kv.keys({gte: base, lt: base + '~', limit: 1, reverse: true}).all();
      if (!keys || keys.length < 1) return;
      const key = keys[0].slice(base.length);
      Iif (!key) return;
      const seq = Number.parseInt(key, 36);
      Iif (seq !== seq) return;
      return seq;
    });
  }
 
  public async create(
    start: types.StoreSnapshot,
    end: types.StoreSnapshot,
    incomingBatch?: types.StoreIncomingBatch,
  ): Promise<types.StoreCreateResult> {
    if (incomingBatch) {
      const {patches} = incomingBatch;
      Iif (!Array.isArray(patches) || patches.length < 1) throw new Error('NO_PATCHES');
    }
    const {id} = end;
    const key = this.endKey(id);
    const now = end.ts;
    const encoder = this.codec.encoder;
    return await this.mutex.acquire(id, async () => {
      const existing = await this.kv.keys({gte: key, lte: key, limit: 1}).all();
      if (existing && existing.length > 0) throw RpcError.conflict();
      const block: types.StoreBlock = {id, snapshot: end, tip: [], ts: now, uts: now};
      const ops: BinStrLevelOperation[] = [
        {type: 'put', key: this.startKey(id), value: encoder.encode(start)},
        {type: 'put', key, value: encoder.encode(block)},
        {type: 'put', key: this.touchKey(id), value: encoder.encode(now)},
      ];
      const response: types.StoreCreateResult = {block};
      if (incomingBatch) {
        const {cts, patches} = incomingBatch;
        const batch: types.StoreBatch = {
          seq: 0,
          ts: end.ts,
          patches,
        };
        Iif (cts !== void 0) batch.cts = cts;
        const batchBlob = encoder.encode(batch);
        const batchKey = this.batchKey(id, 0);
        ops.push({type: 'put', key: batchKey, value: batchBlob});
        response.batch = batch;
      }
      await this.kv.batch(ops);
      return response;
    });
  }
 
  public async push(
    snapshot0: types.StoreIncomingSnapshot,
    batch0: types.StoreIncomingBatch,
  ): Promise<types.StorePushResult> {
    const {id, seq} = snapshot0;
    const {patches} = batch0;
    Iif (!Array.isArray(patches) || !patches.length) throw new Error('NO_PATCHES');
    return await this.mutex.acquire(id, async () => {
      const block = await this.get(id);
      Iif (!block) throw RpcError.notFound();
      const blockData = block.block;
      const snapshot = blockData.snapshot;
      Iif (snapshot.seq + 1 !== seq) throw new Error('PATCH_SEQ_INV');
      const now = Date.now();
      blockData.uts = now;
      snapshot.seq = seq;
      snapshot.ts = now;
      snapshot.blob = snapshot0.blob;
      const encoder = this.codec.encoder;
      const batch1: types.StoreBatch = {
        seq,
        ts: now,
        patches,
      };
      const cts = batch0.cts;
      Iif (cts !== void 0) batch1.cts = cts;
      const ops: BinStrLevelOperation[] = [
        {type: 'put', key: this.endKey(id), value: encoder.encode(blockData)},
        {type: 'put', key: this.batchKey(id, seq), value: encoder.encode(batch1)},
        {type: 'put', key: this.touchKey(id), value: encoder.encode(now)},
      ];
      await this.kv.batch(ops);
      return {snapshot, batch: batch1};
    });
  }
 
  public async compact(id: string, to: number, advance: types.Advance): Promise<void> {
    const {kv, codec} = this;
    const {encoder, decoder} = codec;
    const key = this.startKey(id);
    await this.mutex.acquire(id + '.trunc', async () => {
      const start = decoder.decode((await kv.get(key)) as any) as types.StoreSnapshot;
      Iif (start.seq >= to) return;
      const gt = this.batchKey(id, start.seq);
      const lte = this.batchKey(id, to);
      const ops: BinStrLevelOperation[] = [];
      async function* iterator() {
        for await (const [key, blob] of kv.iterator({gt, lte})) {
          ops.push({type: 'del', key});
          yield decoder.decode(blob) as types.StoreBatch;
        }
      }
      start.blob = await advance(start.blob, iterator());
      start.ts = Date.now();
      start.seq = to;
      ops.push({type: 'put', key, value: encoder.encode(start)});
      await kv.batch(ops);
    });
  }
 
  public async scan(id: string, min: number, max: number): Promise<types.StoreBatch[]> {
    const from = this.batchKey(id, min);
    const to = this.batchKey(id, max);
    const list: types.StoreBatch[] = [];
    const decoder = this.codec.decoder;
    for await (const blob of this.kv.values({gte: from, lte: to})) {
      const batch = decoder.decode(blob) as types.StoreBatch;
      list.push(batch);
    }
    return list;
  }
 
  public async remove(id: string): Promise<boolean> {
    const exists = await this.exists(id);
    if (!exists) return false;
    const base = this.keyBase(id);
    const touchKey = this.touchKey(id);
    const kv = this.kv;
    const success = await this.mutex.acquire(id, async () => {
      await Promise.allSettled([
        kv.clear({
          gte: base,
          lte: base + '~',
        }),
        kv.del(touchKey),
      ]);
      return true;
    });
    return success;
  }
 
  /** @todo Make this method async and return something useful. */
  public stats(): {blocks: number; batches: number} {
    return {blocks: 0, batches: 0};
  }
 
  /**
   * @todo Need to add GC tests.
   */
  public async removeAccessedBefore(ts: number, limit: number = 10): Promise<void> {
    const keyBase = this.touchKeyBase();
    const from = keyBase + '';
    const to = keyBase + '~';
    const decoder = this.codec.decoder;
    let cnt = 0;
    for await (const [key, blob] of this.kv.iterator({gte: from, lte: to})) {
      const value = Number(decoder.decode(blob));
      if (value >= ts) continue;
      cnt++;
      const id = key.slice(keyBase.length, -1);
      this.remove(id).catch(() => {});
      Iif (cnt >= limit) return;
    }
  }
 
  public async removeOldest(x: number): Promise<void> {
    const heap = new AvlMap<number, string>((a, b) => b - a);
    const keyBase = this.touchKeyBase();
    const gte = keyBase + '';
    const lte = keyBase + '~';
    const kv = this.kv;
    const decoder = this.codec.decoder;
    let first = heap.first();
    for await (const [key, value] of kv.iterator({gte, lte})) {
      const time = decoder.decode(value) as number;
      if (heap.size() < x) {
        heap.set(time, key);
        continue;
      }
      if (!first) first = heap.first();
      if (first && time < first.k) {
        heap.del(first.k);
        first = undefined;
        heap.set(time, key);
      }
    }
    Iif (!heap.size()) return;
    for (const {v} of heap.entries()) {
      try {
        const id = v.slice(keyBase.length, -1);
        await this.remove(id);
      } catch {}
    }
  }
 
  public async stop() {
    await this.kv.close();
  }
}