@@ -3,12 +3,15 @@ import {StorePatch} from './types';
33import { RpcError , RpcErrorCodes } from '../../../reactive-rpc/common/rpc/caller' ;
44import type { Services } from '../Services' ;
55
6+ const BLOCK_TTL = 1000 * 60 * 20 ; // 20 minutes
7+
68export 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}
0 commit comments