2020-09-29 19:25:43 +02:00
|
|
|
const config = require('../../mempool-config.json');
|
2019-07-21 16:59:47 +02:00
|
|
|
import * as fs from 'fs';
|
2020-09-29 19:25:43 +02:00
|
|
|
import * as process from 'process';
|
2020-02-26 11:49:53 +01:00
|
|
|
import memPool from './mempool';
|
2020-02-29 15:52:04 +01:00
|
|
|
import blocks from './blocks';
|
2020-10-13 10:27:52 +02:00
|
|
|
import logger from '../logger';
|
2019-07-21 16:59:47 +02:00
|
|
|
|
|
|
|
class DiskCache {
|
|
|
|
static FILE_NAME = './cache.json';
|
|
|
|
|
2020-02-26 11:49:53 +01:00
|
|
|
constructor() {
|
2020-09-29 19:25:43 +02:00
|
|
|
if (process.env.workerId === '0' || !config.CLUSTER_NUM_CORES || config.CLUSTER_NUM_CORES === 1) {
|
|
|
|
process.on('SIGINT', () => {
|
|
|
|
this.saveCacheToDisk();
|
|
|
|
process.exit(2);
|
|
|
|
});
|
|
|
|
|
|
|
|
process.on('SIGTERM', () => {
|
|
|
|
this.saveCacheToDisk();
|
|
|
|
process.exit(2);
|
|
|
|
});
|
|
|
|
}
|
2020-03-01 17:09:33 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
saveCacheToDisk() {
|
|
|
|
this.saveData(JSON.stringify({
|
|
|
|
mempool: memPool.getMempool(),
|
|
|
|
blocks: blocks.getBlocks(),
|
|
|
|
}));
|
2020-10-13 10:27:52 +02:00
|
|
|
logger.info('Mempool and blocks data saved to disk cache');
|
2020-02-26 11:49:53 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
loadMempoolCache() {
|
|
|
|
const cacheData = this.loadData();
|
|
|
|
if (cacheData) {
|
2020-10-13 10:27:52 +02:00
|
|
|
logger.info('Restoring mempool and blocks data from disk cache');
|
2020-02-29 15:52:04 +01:00
|
|
|
const data = JSON.parse(cacheData);
|
2020-09-29 18:13:22 +02:00
|
|
|
memPool.setMempool(data.mempool);
|
|
|
|
blocks.setBlocks(data.blocks);
|
2020-02-26 11:49:53 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
private saveData(dataBlob: string) {
|
2019-07-21 16:59:47 +02:00
|
|
|
fs.writeFileSync(DiskCache.FILE_NAME, dataBlob, 'utf8');
|
|
|
|
}
|
|
|
|
|
2020-02-26 11:49:53 +01:00
|
|
|
private loadData(): string {
|
2019-07-21 16:59:47 +02:00
|
|
|
return fs.readFileSync(DiskCache.FILE_NAME, 'utf8');
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export default new DiskCache();
|