refactor: dirty flag added to file cache

This commit is contained in:
ppedziwiatr
2021-12-02 17:05:02 +01:00
parent 4c1bbb8902
commit 80164a509e
2 changed files with 14 additions and 5 deletions

View File

@@ -139,7 +139,7 @@ describe('Testing the SmartWeave client', () => {
function removeCacheDir() {
if (fs.existsSync(cacheDir)) {
fs.rmdirSync(cacheDir, { recursive: true });
fs.rmSync(cacheDir, { recursive: true });
}
}
});

View File

@@ -1,6 +1,6 @@
import fs from 'fs';
import path from 'path';
import { MemBlockHeightSwCache } from '@smartweave/cache';
import { BlockHeightKey, MemBlockHeightSwCache } from '@smartweave/cache';
import { Benchmark, LoggerFactory } from '@smartweave/logging';
/**
@@ -41,6 +41,8 @@ export class FileBlockHeightSwCache<V = any> extends MemBlockHeightSwCache<V> {
private isFlushing = false;
private isDirty = false;
constructor(
private readonly basePath = path.join(__dirname, 'storage', 'state'),
maxStoredInMemoryBlockHeights: number = Number.MAX_SAFE_INTEGER
@@ -88,9 +90,6 @@ export class FileBlockHeightSwCache<V = any> extends MemBlockHeightSwCache<V> {
}
private async saveCache() {
if (this.isFlushing) {
return;
}
this.isFlushing = true;
this.fLogger.info(`==== Persisting cache ====`);
// TODO: switch to async, as currently writing cache files may slow down contract execution.
@@ -115,6 +114,7 @@ export class FileBlockHeightSwCache<V = any> extends MemBlockHeightSwCache<V> {
);
}
}
this.isDirty = false;
} catch (e) {
this.fLogger.error('Error while flushing cache', e);
} finally {
@@ -123,7 +123,16 @@ export class FileBlockHeightSwCache<V = any> extends MemBlockHeightSwCache<V> {
}
}
async put({ cacheKey, blockHeight }: BlockHeightKey, value: V): Promise<void> {
this.isDirty = true;
return super.put({ cacheKey, blockHeight }, value);
}
async flush(): Promise<void> {
if (this.isFlushing || !this.isDirty) {
return;
}
await this.saveCache();
}
}