1
Fork 0

make loading cache synchronous

(avoids race conditions with closing cache before it's loaded)
This commit is contained in:
Conduitry 2020-10-25 12:33:03 -04:00
parent faed6de27a
commit 5aff83a1df

View file

@ -1,5 +1,5 @@
import { createHash } from 'crypto';
import { promises, writeFileSync } from 'fs';
import { readFileSync, writeFileSync } from 'fs';
import { resolve } from 'path';
import { serialize, deserialize } from 'v8';
@ -11,24 +11,20 @@ export const autocache = (path: string, mode: Mode) => {
let cache = <Cache>new Map();
const removing = new Set<string>();
const pending = new Map<string, any>();
const loading = promises
.readFile(path)
.then(deserialize)
.then((data) => {
if (data && typeof data === 'object' && data.schema === 1 && data.cache instanceof Map) {
cache = data.cache;
for (const [key, [, modes]] of cache) {
modes.delete(mode);
if (modes.size === 0) {
removing.add(key);
}
try {
const data = deserialize(readFileSync(path));
if (data && typeof data === 'object' && data.schema === 1 && data.cache instanceof Map) {
cache = data.cache;
for (const [key, [, modes]] of cache) {
modes.delete(mode);
if (modes.size === 0) {
removing.add(key);
}
}
})
.catch(() => {});
}
} catch {}
return {
async cache(key: string, compute_value: () => Promise<any>) {
await loading;
const key_hashed = createHash('sha1').update(key).digest('hex');
let value: any, modes: Set<Mode>;
if (cache.has(key_hashed)) {