Write cache.json on startup if it doesn't exist.

Write mempool and block data to cache on every new block
fixes #146
This commit is contained in:
softsimon 2020-10-27 00:05:06 +07:00
parent 6a8deff706
commit d260a1ed73
No known key found for this signature in database
GPG Key ID: 488D7DCFB5A430D7
2 changed files with 46 additions and 10 deletions

View File

@ -3,6 +3,7 @@ import logger from '../logger';
import memPool from './mempool';
import { Block, TransactionExtended, TransactionMinerInfo } from '../interfaces';
import { Common } from './common';
import diskCache from './disk-cache';
class Blocks {
private static INITIAL_BLOCK_AMOUNT = 8;
@ -99,6 +100,7 @@ class Blocks {
if (this.newBlockCallbacks.length) {
this.newBlockCallbacks.forEach((cb) => cb(block, txIds, transactions));
}
diskCache.$saveCacheToDiskAsync();
}
}

View File

@ -6,10 +6,16 @@ import blocks from './blocks';
import logger from '../logger';
class DiskCache {
static FILE_NAME = './cache.json';
private static FILE_NAME = './cache.json';
private enabled = true;
constructor() {
if (process.env.workerId === '0' || !config.MEMPOOL.SPAWN_CLUSTER_PROCS) {
if (!fs.existsSync(DiskCache.FILE_NAME)) {
fs.closeSync(fs.openSync(DiskCache.FILE_NAME, 'w'));
logger.info('Disk cache file created');
}
process.on('SIGINT', () => {
this.saveCacheToDisk();
process.exit(2);
@ -19,19 +25,28 @@ class DiskCache {
this.saveCacheToDisk();
process.exit(2);
});
} else {
this.enabled = false;
}
}
saveCacheToDisk() {
this.saveData(JSON.stringify({
mempool: memPool.getMempool(),
blocks: blocks.getBlocks(),
}));
logger.info('Mempool and blocks data saved to disk cache');
async $saveCacheToDiskAsync(): Promise<void> {
if (!this.enabled) {
return;
}
try {
await this.$saveDataAsync(JSON.stringify({
mempool: memPool.getMempool(),
blocks: blocks.getBlocks(),
}));
logger.info('Mempool and blocks data saved to disk cache');
} catch (e) {
logger.warn('Error writing to cache file asynchronously');
}
}
loadMempoolCache() {
const cacheData = this.loadData();
const cacheData = this.loadDataSync();
if (cacheData) {
logger.info('Restoring mempool and blocks data from disk cache');
const data = JSON.parse(cacheData);
@ -40,11 +55,30 @@ class DiskCache {
}
}
private saveData(dataBlob: string) {
private saveCacheToDisk() {
this.saveDataSync(JSON.stringify({
mempool: memPool.getMempool(),
blocks: blocks.getBlocks(),
}));
logger.info('Mempool and blocks data saved to disk cache');
}
private $saveDataAsync(dataBlob: string): Promise<void> {
return new Promise((resolve, reject) => {
fs.writeFile(DiskCache.FILE_NAME, dataBlob, (err) => {
if (err) {
return reject(err);
}
resolve();
});
});
}
private saveDataSync(dataBlob: string) {
fs.writeFileSync(DiskCache.FILE_NAME, dataBlob, 'utf8');
}
private loadData(): string {
private loadDataSync(): string {
return fs.readFileSync(DiskCache.FILE_NAME, 'utf8');
}
}