|
| 1 | +import {File, FileOptions} from "../file/File"; |
| 2 | +import {CborEncoder} from "../../json-pack/cbor/CborEncoder"; |
| 3 | +import type {CrudApi} from "memfs/lib/crud/types"; |
| 4 | +import type {Locks} from "thingies/es2020/Locks"; |
| 5 | +import type {Patch} from "../../json-crdt-patch"; |
| 6 | +import type {PatchLog} from "./PatchLog"; |
| 7 | +import type {LocalHistory} from "./types"; |
| 8 | + |
| 9 | +export const genId = (octets: number = 8): string => { |
| 10 | + const uint8 = crypto.getRandomValues(new Uint8Array(octets)); |
| 11 | + let hex = ''; |
| 12 | + for (let i = 0; i < octets; i++) hex += uint8[i].toString(16).padStart(2, '0'); |
| 13 | + return hex; |
| 14 | +}; |
| 15 | + |
| 16 | +const STATE_FILE_NAME = 'state.seq.cbor'; |
| 17 | + |
| 18 | +export class LocalHistoryCrud implements LocalHistory { |
| 19 | + protected fileOpts: FileOptions = { |
| 20 | + cborEncoder: new CborEncoder(), |
| 21 | + }; |
| 22 | + |
| 23 | + constructor( |
| 24 | + protected readonly crud: CrudApi, |
| 25 | + protected readonly locks: Locks, |
| 26 | + ) {} |
| 27 | + |
| 28 | + public async create(collection: string[], log: PatchLog): Promise<{id: string}> { |
| 29 | + // TODO: Remove `log.end`, just `log` should be enough. |
| 30 | + const file = new File(log.end, log, this.fileOpts); |
| 31 | + const blob = file.toBinary({ |
| 32 | + format: "seq.cbor", |
| 33 | + model: 'binary', |
| 34 | + }); |
| 35 | + const id = genId(); |
| 36 | + await this.lock(collection, id, async () => { |
| 37 | + await this.crud.put([...collection, id], STATE_FILE_NAME, blob, {throwIf: 'exists'}); |
| 38 | + }); |
| 39 | + return {id}; |
| 40 | + } |
| 41 | + |
| 42 | + public async read(collection: string[], id: string): Promise<{log: PatchLog, cursor: string}> { |
| 43 | + const blob = await this.crud.get([...collection, id], STATE_FILE_NAME); |
| 44 | + const {log} = File.fromSeqCbor(blob); |
| 45 | + return { |
| 46 | + log, |
| 47 | + cursor: '', |
| 48 | + }; |
| 49 | + } |
| 50 | + |
| 51 | + public readHistory(collection: string[], id: string, cursor: string): Promise<{log: PatchLog, cursor: string}> { |
| 52 | + throw new Error('Method not implemented.'); |
| 53 | + } |
| 54 | + |
| 55 | + public update(collection: string[], id: string, patches: Patch[]): Promise<void> { |
| 56 | + throw new Error('Method not implemented.'); |
| 57 | + } |
| 58 | + |
| 59 | + public async delete(collection: string[], id: string): Promise<void> { |
| 60 | + await this.lock(collection, id, async () => { |
| 61 | + await this.crud.drop(collection, true); |
| 62 | + }); |
| 63 | + } |
| 64 | + |
| 65 | + protected async lock(collection: string[], id: string, fn: () => Promise<void>): Promise<void> { |
| 66 | + const key = collection.join('/') + '/' + id; |
| 67 | + await this.locks.lock(key, 250, 500)(async () => { |
| 68 | + await fn(); |
| 69 | + }); |
| 70 | + } |
| 71 | +} |
0 commit comments