Skip to content
Merged
Show file tree
Hide file tree
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
43 changes: 15 additions & 28 deletions pm-stack/aggregator/scripts/gather-quota.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,6 @@
// disables the Turso sink (default on; token resolved by name
// via the resolveBwsSecret plumbing:
// turso.fleet-platform-rw-token).
import { existsSync } from "node:fs";
import { execFile } from "node:child_process";
import { access, appendFile, mkdir, readFile, rename, writeFile } from "node:fs/promises";
import { homedir } from "node:os";
Expand Down Expand Up @@ -135,6 +134,7 @@ import { SnapshotStore, isSnapshotRecord, snapshotKey } from "../src/snapshots.t
import { safeProviderReason } from "../src/credential-lifecycle.ts";
import { renewOpenDesignSession, type OpenDesignCredentialLike } from "../src/opendesign-renewal.ts";
import { ensureLibDependencies } from "../src/lib-deps.ts";
import { loadOpenChamberLib, resolveLibDir as resolveOpenChamberLib } from "../src/openchamber-lib.ts";
import { readProviderAuthAlerts } from "../src/provider-auth-alerts.ts";
import { renewMetaSession } from "../src/meta-renewal.ts";
import { classEnabled, getAlertsStore } from "../src/alerts.ts";
Expand All @@ -144,22 +144,19 @@ const PKG = join(dirname(fileURLToPath(import.meta.url)), "..");
const HOME = homedir();
const HIDDEN = join(HOME, "workspace/goals/keep-the-four-repos-healthy/hidden_files");

/** The OpenDesign keeper's credential-store accessors live in the
* OpenChamber lib (the managed store's home). Store plumbing for ONE
* credential the keeper maintains — never a quota reading path: all
* readings come from the subcommand (see the header). */
function resolveLibDir(): string {
const candidates = [
/** Candidate checkouts for the OpenDesign keeper's managed credential
* store (the OpenChamber lib). Store plumbing for ONE credential the
* keeper maintains, never a quota reading path: all readings come from
* the subcommand (see the header). Each candidate must be a clean main
* checkout (src/openchamber-lib.ts), so a parked or stale checkout is
* rejected rather than imported. */
function openChamberLibCandidates(): string[] {
return [
process.env.OPENCHAMBER_LIB_DIR,
join(HOME, "git/devtoday-openchamber/packages/web/server/lib"),
join(HOME, "git/openchamber-fork/packages/web/server/lib"),
].filter((d): d is string => typeof d === "string" && d !== "");
for (const dir of candidates) {
if (existsSync(join(dir, "quota/index.js"))) return dir;
}
return candidates[0];
}
const libDir = resolveLibDir();
const currentPath = process.env.QUOTA_CURRENT_PATH ?? join(PKG, "quota-current.json");
const heartbeatPath = process.env.QUOTA_HEARTBEAT_PATH ?? join(PKG, "quota-gatherer-heartbeat.json");
const statePath = process.env.QUOTA_GATHERER_STATE_PATH ?? join(PKG, "quota-gatherer-state.json");
Expand Down Expand Up @@ -294,15 +291,6 @@ async function resolveBwsSecret(key: string): Promise<string | null> {
}
}

/** Managed-credential accessors for the OpenDesign keeper (libDir). */
interface OpenDesignCredentialsModule {
readManagedCredential: (providerId: string) => OpenDesignCredentialLike | null;
writeManagedCredential: (providerId: string, value: OpenDesignCredentialLike) => unknown;
}
interface OpenDesignProviderModule {
fetchOpenDesignQuota: (credential: OpenDesignCredentialLike) => Promise<unknown>;
}

/**
* The OpenDesign session keeper run. Runs before the subcommand so a
* credential renewed this tick is the one the tick's OpenDesign read
Expand All @@ -315,6 +303,10 @@ interface OpenDesignProviderModule {
async function runOpenDesignRenewal(tickAt: string): Promise<void> {
if (process.env.OPENDESIGN_RENEWAL_DISABLED === "1") return;
try {
// Resolve first: a parked, dirty or non-main checkout is rejected
// here, before anything from it is installed or imported. The keeper
// then fails soft and the subcommand readings still run.
const lib = await resolveOpenChamberLib(openChamberLibCandidates());
// #8759: the lib checkout is a plain clone; if its declared
// dependencies were never installed, every import below fails
// with "Cannot find package ..." and Bun caches that failure
Expand All @@ -338,16 +330,11 @@ async function runOpenDesignRenewal(tickAt: string): Promise<void> {
}
: undefined;
await ensureLibDependencies({
libDir,
libDir: lib.dir,
log: (line) => console.log("quota-gatherer: " + line),
...(install ? { install } : {}),
});
const credentials = (await import(
join(libDir, "quota/credentials/providers.js")
)) as unknown as OpenDesignCredentialsModule;
const provider = (await import(
join(libDir, "quota/providers/opendesign.js")
)) as unknown as OpenDesignProviderModule;
const { credentials, provider } = await loadOpenChamberLib(lib);
const state = await renewOpenDesignSession({
readCredential: () => credentials.readManagedCredential("opendesign"),
writeCredential: (value) => {
Expand Down
136 changes: 136 additions & 0 deletions pm-stack/aggregator/src/openchamber-lib.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
import { execFile } from "node:child_process";
import { existsSync } from "node:fs";
import { resolve } from "node:path";
import { pathToFileURL } from "node:url";
import type { OpenDesignCredentialLike } from "./opendesign-renewal.ts";

export type GitRun = (cwd: string, args: string[]) => Promise<string>;

export interface OpenChamberCredentialsModule {
readManagedCredential: (providerId: string) => OpenDesignCredentialLike | null;
writeManagedCredential: (providerId: string, value: OpenDesignCredentialLike) => unknown;
}

export interface OpenChamberProviderModule {
fetchOpenDesignQuota: (credential: OpenDesignCredentialLike) => Promise<unknown>;
}

export interface ResolvedOpenChamberLib {
dir: string;
root: string;
revision: string;
}

export interface ResolveLibOptions {
gitRun?: GitRun;
log?: (message: string) => void;
}

export interface OpenChamberLibModules {
credentials: OpenChamberCredentialsModule;
provider: OpenChamberProviderModule;
}

const REQUIRED_MODULE_EXPORTS = [
{
path: "quota/credentials/providers.js",
names: ["readManagedCredential", "writeManagedCredential"],
},
{ path: "quota/providers/opendesign.js", names: ["fetchOpenDesignQuota"] },
] as const;

const defaultGitRun: GitRun = (cwd, args) =>
new Promise((resolveOutput, reject) => {
execFile("git", args, { cwd, timeout: 10_000, maxBuffer: 1 << 20 }, (err, stdout) => {
if (err) reject(err);
else resolveOutput(stdout.trim());
});
});

async function inspectCandidate(dir: string, gitRun: GitRun): Promise<ResolvedOpenChamberLib> {
if (!existsSync(resolve(dir, "quota/index.js"))) {
throw new Error("quota/index.js is missing");
}

const root = (await gitRun(dir, ["rev-parse", "--show-toplevel"])).trim();
if (!root) throw new Error("Git returned an empty checkout root");

const branch = (await gitRun(root, ["branch", "--show-current"])).trim();
if (branch !== "main") {
throw new Error(`checkout is on ${branch ? `branch ${branch}` : "a detached HEAD"}, not main`);
}

const changes = (await gitRun(root, ["status", "--porcelain", "--untracked-files=normal"])).trim();
if (changes) throw new Error("checkout has a dirty working tree");

const revision = (await gitRun(root, ["rev-parse", "--verify", "HEAD^{commit}"])).trim();
if (!/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(revision)) {
throw new Error(`Git returned an invalid HEAD revision ${JSON.stringify(revision)}`);
}

return { dir, root, revision };
}

/** Pick the first clean main checkout. Imports nothing: the caller installs
* the checkout's dependencies (src/lib-deps.ts) before loading its modules. */
export async function resolveLibDir(
candidates: string[],
{ gitRun = defaultGitRun, log = console.warn }: ResolveLibOptions = {},
): Promise<ResolvedOpenChamberLib> {
const rejected: string[] = [];
const seen = new Set<string>();

for (const candidate of candidates) {
const dir = resolve(candidate);
if (seen.has(dir)) continue;
seen.add(dir);
try {
const lib = await inspectCandidate(dir, gitRun);
log(`quota-gatherer: OpenChamber lib dir=${lib.dir} branch=main rev=${lib.revision}`);
return lib;
} catch (err) {
const reason = err instanceof Error ? err.message : String(err);
rejected.push(`${dir}: ${reason}`);
log(`quota-gatherer: rejected OpenChamber lib ${dir}: ${reason}`);
}
}

const detail = rejected.length ? rejected.join("; ") : "no candidates were configured";
throw new Error(`no usable clean main OpenChamber lib checkout found (${detail})`);
}

async function importRequiredModule(dir: string, path: string): Promise<Record<string, unknown>> {
try {
return (await import(pathToFileURL(resolve(dir, path)).href)) as Record<string, unknown>;
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
const missing =
message.match(/does not provide an export named ['"]([^'"]+)['"]/i) ??
message.match(/export named ['"]([^'"]+)['"] not found/i);
if (missing) {
throw new Error(`missing required export "${missing[1]}" while importing ${path}`);
}
throw new Error(`could not import ${path}: ${message}`);
}
}

/** Import the credential APIs from a resolved checkout and name any missing export. */
export async function loadOpenChamberLib(lib: ResolvedOpenChamberLib): Promise<OpenChamberLibModules> {
const [credentials, provider] = await Promise.all(
REQUIRED_MODULE_EXPORTS.map(({ path }) => importRequiredModule(lib.dir, path)),
);
const modules = [credentials, provider];
for (let index = 0; index < REQUIRED_MODULE_EXPORTS.length; index += 1) {
const required = REQUIRED_MODULE_EXPORTS[index];
const module = modules[index];
for (const name of required.names) {
if (typeof module[name] !== "function") {
throw new Error(`missing required export "${name}" in ${required.path}`);
}
}
}
return {
credentials: credentials as unknown as OpenChamberCredentialsModule,
provider: provider as unknown as OpenChamberProviderModule,
};
}
12 changes: 10 additions & 2 deletions pm-stack/aggregator/test/gather-quota.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -535,8 +535,8 @@ test("an uninstalled lib checkout dependency is installed and the OpenDesign kee
usage: { windows: { weekly: { usedPercent: null } } },
};

// A plain-clone lib checkout: manifest + lockfile declare fake-dep,
// but node_modules was never installed — the #8759 defect shape.
// A clean main lib checkout (#5721 gate): manifest + lockfile declare
// fake-dep, but node_modules was never installed — the #8759 defect shape.
await mkdir(join(libDir, "quota/credentials"), { recursive: true });
await mkdir(join(libDir, "quota/providers"), { recursive: true });
await writeFile(
Expand All @@ -560,6 +560,14 @@ test("an uninstalled lib checkout dependency is installed and the OpenDesign kee
"export async function fetchOpenDesignQuota() { return {}; }\n",
"utf8",
);
await writeFile(join(checkoutRoot, ".gitignore"), "node_modules/\n", "utf8");
const git = (...args: string[]) => {
const r = spawnSync("git", ["-c", "user.name=t", "-c", "user.email=t@t", ...args], { cwd: checkoutRoot, encoding: "utf8" });
if (r.status !== 0) throw new Error(`git ${args.join(" ")} failed: ${r.stderr}`);
};
git("init", "-q", "-b", "main");
git("add", "-A");
git("commit", "-q", "-m", "lib checkout");
// The install step (OPENCHAMBER_LIB_INSTALL_CMD seam; production
// default is bun install at the checkout root): materialize the
// declared package under the cwd the gatherer gives it — the root.
Expand Down
Loading