@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
139 lines • 5.94 kB
JavaScript
/**
* Process-wide cache for compiled extension module graphs.
*
* A module registry has no eviction API, so every extension source evaluated under a fresh
* importer generation stays resident for the life of the process. A daemon that loads extensions
* per session therefore pays that cost per session forever (senpi#1948). The graph is a pure
* function of its source files, so this cache keeps ONE live generation and hands the same factory
* to every later load whose sources are byte-for-byte unchanged; every load still runs the factory,
* so sessions keep their own extension instances.
*
* Freshness is preserved by invalidation: a changed, added or removed source file drops the
* generation, and the next load compiles a new one. An importer that cannot report the files it
* compiled (the Node jiti path) is never cached, because its graph cannot be checked for staleness.
*
* The check runs on every cached lookup - once per extension per session open - so it must not
* re-read the graph (senpi#6256: hashing a large extension graph cost ~10 ms per extension per open).
* A file whose content was proven to match is remembered with its stat identity; a later lookup
* re-hashes it only when that identity moved. ctime cannot be set from userland and moves on every
* write, and a file modified too recently to trust its timestamps is never remembered (git's "racy
* clean" rule), so an edit within one timestamp tick is still caught by the hash.
*
* @module core/extensions/extension-module-cache
*/
import { createHash } from "node:crypto";
import { readFileSync, statSync } from "node:fs";
let generation;
let pendingImporter;
let generationsCreated = 0;
/** A timestamp younger than this may still be followed by a same-tick write that leaves it unchanged. */
const RACY_TIMESTAMP_MS = 2_000;
/** file -> `<fingerprint>\0<stat identity>` it was last proven to hold. */
const verifiedSources = new Map();
function fingerprintOf(file) {
try {
return createHash("sha256").update(readFileSync(file, "utf8")).digest("hex");
}
catch {
return undefined;
}
}
/** Stat identity, or undefined when the file is gone or too recently modified to be remembered. */
function stableIdentityOf(file) {
try {
const stats = statSync(file, { bigint: true });
const newest = Number((stats.mtimeNs > stats.ctimeNs ? stats.mtimeNs : stats.ctimeNs) / 1000000n);
return {
key: `${stats.dev}:${stats.ino}:${stats.size}:${stats.mtimeNs}:${stats.ctimeNs}`,
stable: Date.now() - newest > RACY_TIMESTAMP_MS,
};
}
catch {
return undefined;
}
}
function sourceUnchanged(file, fingerprint) {
const identity = stableIdentityOf(file);
if (identity === undefined)
return false;
const proven = `${fingerprint}\0${identity.key}`;
if (verifiedSources.get(file) === proven)
return true;
if (fingerprintOf(file) !== fingerprint)
return false;
// The identity was read BEFORE the hash: a write landing in between moves it, so the next lookup re-hashes.
if (identity.stable)
verifiedSources.set(file, proven);
else
verifiedSources.delete(file);
return true;
}
/** Stale means a file this generation already compiled changed or disappeared. */
function sourcesUnchanged(live) {
for (const [file, fingerprint] of live.importer.compiledSources?.() ?? []) {
if (!sourceUnchanged(file, fingerprint))
return false;
}
return true;
}
/**
* Stop REUSING a generation; never revoke it. A session loaded under it can still lazily
* `import()` from its graph long after its factory returned, and disposing the importer makes
* that throw. Its modules stay registered either way - that residue is the price of a source edit,
* not something a dispose could reclaim.
*/
function dropGeneration() {
generation = undefined;
pendingImporter = undefined;
}
/**
* The cached factory for this source, or `undefined` when it must be compiled.
*
* A source change invalidates the whole generation: its modules already reference each other, so
* one stale file makes every factory in that generation suspect.
*/
export function cachedExtensionFactory(resolvedPath) {
if (!generation)
return undefined;
if (!sourcesUnchanged(generation)) {
dropGeneration();
return undefined;
}
return generation.factories.get(resolvedPath);
}
/** The live importer, created on demand. Callers share one generation until it is invalidated. */
export async function extensionModuleImporter(create) {
if (generation)
return generation.importer;
pendingImporter ??= create().then((importer) => {
generation = { importer, factories: new Map() };
generationsCreated++;
pendingImporter = undefined;
return importer;
});
return pendingImporter;
}
/**
* Remember a freshly compiled factory. Source identity belongs to the importer: reading disk
* here would label an old compiled module with newer bytes if a dependency changed meanwhile.
*
* `compiledBy` is the importer that produced the factory: a load already in flight when a source
* change dropped the generation must not file its result under the successor, whose fingerprint
* describes different bytes.
*/
export function rememberExtensionFactory(resolvedPath, factory, compiledBy) {
if (!generation || generation.importer !== compiledBy)
return;
if (generation.importer.compiledSources === undefined)
return;
generation.factories.set(resolvedPath, factory);
}
export function clearExtensionCache() {
dropGeneration();
verifiedSources.clear();
}
/** Test seam: how many module generations this process has compiled. */
export function extensionModuleGenerationCount() {
return generationsCreated;
}
//# sourceMappingURL=extension-module-cache.js.map