make loading cache synchronous
(avoids race conditions with closing cache before it's loaded)
This commit is contained in:
parent
faed6de27a
commit
5aff83a1df
1 changed files with 11 additions and 15 deletions
26
src/index.ts
26
src/index.ts
|
@ -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)) {
|
||||
|
|
Loading…
Reference in a new issue