FIx: Write cache sync on exit.

This commit is contained in:
softsimon 2020-11-02 22:06:51 +07:00
parent ce582eefc6
commit c03073bddd
No known key found for this signature in database
GPG Key ID: 488D7DCFB5A430D7

View File

@ -9,23 +9,17 @@ import logger from '../logger';
class DiskCache { class DiskCache {
private static FILE_NAME = './cache.json'; private static FILE_NAME = './cache.json';
private static FILE_NAME_2 = './cache2.json'; private static FILE_NAME_2 = './cache2.json';
private static CHUNK_SIZE = 50000;
constructor() { constructor() {
if (!cluster.isMaster) { if (!cluster.isMaster) {
return; return;
} }
/* process.on('SIGINT', () => {
if (!fs.existsSync(DiskCache.FILE_NAME)) { this.saveCacheToDiskSync();
fs.closeSync(fs.openSync(DiskCache.FILE_NAME, 'w'));
logger.info('Disk cache file created');
}
*/
process.on('SIGINT', async () => {
await this.$saveCacheToDisk();
process.exit(2); process.exit(2);
}); });
process.on('SIGTERM', () => {
process.on('SIGTERM', async () => { this.saveCacheToDiskSync();
await this.$saveCacheToDisk();
process.exit(2); process.exit(2);
}); });
} }
@ -35,9 +29,9 @@ class DiskCache {
return; return;
} }
try { try {
logger.debug('Writing mempool and blocks data to disk cache...'); logger.debug('Writing mempool and blocks data to disk cache (async)...');
const mempoolChunk_1 = Object.fromEntries(Object.entries(memPool.getMempool()).splice(0, 50000)); const mempoolChunk_1 = Object.fromEntries(Object.entries(memPool.getMempool()).splice(0, DiskCache.CHUNK_SIZE));
const mempoolChunk_2 = Object.fromEntries(Object.entries(memPool.getMempool()).splice(50000)); const mempoolChunk_2 = Object.fromEntries(Object.entries(memPool.getMempool()).splice(DiskCache.CHUNK_SIZE));
await fsPromises.writeFile(DiskCache.FILE_NAME, JSON.stringify({ await fsPromises.writeFile(DiskCache.FILE_NAME, JSON.stringify({
blocks: blocks.getBlocks(), blocks: blocks.getBlocks(),
mempool: mempoolChunk_1 mempool: mempoolChunk_1
@ -51,6 +45,24 @@ class DiskCache {
} }
} }
saveCacheToDiskSync(): void {
try {
logger.debug('Writing mempool and blocks data to disk cache...');
const mempoolChunk_1 = Object.fromEntries(Object.entries(memPool.getMempool()).splice(0, DiskCache.CHUNK_SIZE));
const mempoolChunk_2 = Object.fromEntries(Object.entries(memPool.getMempool()).splice(DiskCache.CHUNK_SIZE));
fs.writeFileSync(DiskCache.FILE_NAME, JSON.stringify({
blocks: blocks.getBlocks(),
mempool: mempoolChunk_1
}), {flag: 'w'});
fs.writeFileSync(DiskCache.FILE_NAME_2, JSON.stringify({
mempool: mempoolChunk_2
}), {flag: 'w'});
logger.debug('Mempool and blocks data saved to disk cache');
} catch (e) {
logger.warn('Error writing to cache file: ' + e.message || e);
}
}
loadMempoolCache() { loadMempoolCache() {
if (!fs.existsSync(DiskCache.FILE_NAME)) { if (!fs.existsSync(DiskCache.FILE_NAME)) {
return; return;