Skip to content

Commit 7b14376

Browse files
committed
feat(reactive-rpc): 🎸 remove old blocks after some period of time
1 parent 34368c4 commit 7b14376

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

src/server/services/blocks/BlocksServices.ts

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,15 @@ import {StorePatch} from './types';
33
import {RpcError, RpcErrorCodes} from '../../../reactive-rpc/common/rpc/caller';
44
import type {Services} from '../Services';
55

6+
const BLOCK_TTL = 1000 * 60 * 20; // 20 minutes
7+
68
export class BlocksServices {
79
protected readonly store = new MemoryStore();
810

911
constructor(protected readonly services: Services) {}
1012

1113
public async create(id: string, patches: StorePatch[]) {
14+
this.maybeGc();
1215
const {store} = this;
1316
const {block} = await store.create(id, patches);
1417
const data = {
@@ -45,6 +48,7 @@ export class BlocksServices {
4548
}
4649

4750
public async edit(id: string, patches: any[]) {
51+
this.maybeGc();
4852
if (!Array.isArray(patches)) throw RpcError.validation('patches must be an array');
4953
if (!patches.length) throw RpcError.validation('patches must not be empty');
5054
const seq = patches[0].seq;
@@ -69,4 +73,18 @@ export class BlocksServices {
6973
public stats() {
7074
return this.store.stats();
7175
}
76+
77+
private maybeGc(): void {
78+
if (Math.random() < 0.05)
79+
this.gc().catch((error) => {
80+
// tslint:disable-next-line:no-console
81+
console.error('Error running gc', error);
82+
});
83+
}
84+
85+
private async gc(): Promise<void> {
86+
const ts = Date.now() - BLOCK_TTL;
87+
const {store} = this;
88+
await store.removeOlderThan(ts);
89+
}
7290
}

src/server/services/blocks/MemoryStore.ts

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,10 @@ export class MemoryStore implements types.Store {
7272

7373
public async remove(id: string): Promise<void> {
7474
await new Promise((resolve) => setImmediate(resolve));
75+
this.removeSync(id);
76+
}
77+
78+
private removeSync(id: string): void {
7579
this.blocks.delete(id);
7680
this.patches.delete(id);
7781
}
@@ -82,4 +86,9 @@ export class MemoryStore implements types.Store {
8286
patches: [...this.patches.values()].reduce((acc, v) => acc + v.length, 0),
8387
};
8488
}
89+
90+
public async removeOlderThan(ts: number): Promise<void> {
91+
await new Promise((resolve) => setImmediate(resolve));
92+
for (const [id, block] of this.blocks) if (block.created < ts) this.removeSync(id);
93+
}
8594
}

0 commit comments

Comments
 (0)