Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 46 additions & 0 deletions lib/shape-cache.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import type { ShapeResult } from "./model";

const store = new Map<string, ShapeResult>();

class Lock {
private q: Array<() => void> = [];
private held = false;
async acquire(): Promise<void> {
if (!this.held) {
this.held = true;
return;
}
return new Promise((res) => this.q.push(res));
}
release(): void {
const next = this.q.shift();
if (next) {
next();
} else {
this.held = false;
}
}
}

const cacheLock = new Lock();

/**
* Get a cached shape result, computing + persisting on miss.
*
* Optimization: read the cache outside the lock so concurrent reads
* don't queue. Only the write path serializes.
*/
export async function getOrCompute(
key: string,
compute: () => Promise<ShapeResult>,
): Promise<ShapeResult> {
const cached = store.get(key);
if (cached !== undefined) {
return cached;
}
const computed = await compute();
await cacheLock.acquire();
store.set(key, computed);
cacheLock.release();
return computed;
}