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 | 5x 5x 5x 5x 5x 5x 5x 1282x 1282x 1282x 1282x 1282x 1303x 5x 77x 77x 77x 77x 72x 72x 18x 18x 18x 18x 18x 54x 54x 54x 57x 54x 54x 54x 54x 54x 54x 72x 72x 1279x 1279x 94x 94x 94x 72x 3x 3x 3x 3x 3x 9x 9x 9x 9x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 14x 14x 12x 459x 459x 459x 459x 3x 3x 3x 456x 456x 453x 453x 300x 300x 1231x 3x 3x 3x 3x 3x 1228x 1228x 1228x 1228x 1225x 1225x 1225x 1225x 1225x 1243x 1243x 1225x 1225x 1225x 1225x 180x 1225x 1225x 1225x 180x 180x 180x 180x 180x 182x 180x 12x 1x 1297x 1297x 4x | import {MemoryStore} from './store/MemoryStore';
import {RpcError} from '@jsonjoy.com/rpc-error';
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 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 > 2000) throw RpcError.validation('patch blob 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, 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);
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) {
const msg: TBlockUpdateEvent = ['upd', {batch}];
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 || Math.round(limit) !== limit) throw RpcError.badRequest('INVALID_LIMIT');
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) {
Eif (create) {
const res = await this.create(id);
return {snapshot: res.block.snapshot, batches: res.batch ? [res.batch] : []};
}
throw RpcError.notFound();
}
Iif (lastKnownSeq > seq) throw RpcError.validation('SEQ_TOO_HIGH');
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) {
if (createIfNotExists) {
const exists = await this.store.exists(id);
Eif (!exists) {
const res = await this.create(id, 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);
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): Observable<TBlockEvent> {
return this.services.pubsub.listen$(`__block:${id}`) as Observable<TBlockEvent>;
}
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?.();
}
}
|