Skip to content
Draft
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
31 changes: 28 additions & 3 deletions src/usage/log.ts
Original file line number Diff line number Diff line change
Expand Up @@ -852,18 +852,41 @@ function normalizeUsageEntry(entry: PersistedUsageEntry): PersistedUsageEntry {
};
}

let ensuredUsageLogDir: string | null = null;
let ensuredUsageLogFile: string | null = null;

function ensureUsageLogDir(): void {
const dir = getConfigDir();
if (ensuredUsageLogDir === dir) return;
Comment thread
coderabbitai[bot] marked this conversation as resolved.
recordOwnedConfigPath(dir, usageLogPath());
mkdirSync(dir, { recursive: true, mode: 0o700 });
try { chmodSync(dir, 0o700); } catch { /* best-effort on platforms that ignore chmod */ }
ensuredUsageLogDir = dir;
}

export function appendUsageEntry(entry: PersistedUsageEntry): void {
ensureUsageLogDir();
const line = `${JSON.stringify(normalizeUsageEntry(entry))}\n`;
const path = usageLogPath();
appendFileSync(path, `${JSON.stringify(normalizeUsageEntry(entry))}\n`, { encoding: "utf-8", mode: 0o600 });
try { chmodSync(path, 0o600); } catch { /* best-effort on platforms that ignore chmod */ }
const doAppend = (): void => {
ensureUsageLogDir();
const fileAlreadyEnsured = ensuredUsageLogFile === path;
appendFileSync(path, line, { encoding: "utf-8", mode: 0o600 });
if (!fileAlreadyEnsured) {
try { chmodSync(path, 0o600); } catch { /* best-effort on platforms that ignore chmod */ }
ensuredUsageLogFile = path;
}
};
try {
doAppend();
} catch (error: any) {
if (error?.code === "ENOENT") {
ensuredUsageLogDir = null;
ensuredUsageLogFile = null;
doAppend();
return;
}
throw error;
}
}

export type UsageLogRevision = {
Expand Down Expand Up @@ -1057,6 +1080,8 @@ export function resetUsageReadCacheForTests(): void {
managementUsageReadInflight?.abort.abort();
managementUsageReadInflight = null;
retainedUsageSnapshot = null;
ensuredUsageLogDir = null;
ensuredUsageLogFile = null;
}

function readExactly(fd: number, length: number, position: number): Buffer | null {
Expand Down
57 changes: 57 additions & 0 deletions tests/usage/usage-log.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1012,4 +1012,61 @@ describe("usage log", () => {

expect(readRecentUsageEntries(1)).toEqual([]);
}, STORE_BUDGET_MS);

test("appendUsageEntry avoids redundant mkdirSync and chmodSync on consecutive calls", async () => {
const nodeFs = await import("node:fs");
const mkdirSpy = spyOn(nodeFs, "mkdirSync");
const chmodSpy = spyOn(nodeFs, "chmodSync");
Comment thread
coderabbitai[bot] marked this conversation as resolved.

try {
for (let i = 0; i < 5; i++) {
appendUsageEntry({
requestId: `ocx-perf-${i}`,
timestamp: Date.now(),
provider: "openai",
model: "gpt-4o",
status: 200,
durationMs: 10,
usageStatus: "unreported",
});
}

expect(mkdirSpy.mock.calls.length).toBe(1);
expect(chmodSpy.mock.calls.length).toBeLessThanOrEqual(2);
} finally {
mkdirSpy.mockRestore();
chmodSpy.mockRestore();
}
});

test("appendUsageEntry recovers cleanly on ENOENT if usage directory is deleted between calls", () => {
const entry1: PersistedUsageEntry = {
requestId: "ocx-enoent-1",
timestamp: Date.now(),
provider: "openai",
model: "gpt-4o",
status: 200,
durationMs: 10,
usageStatus: "unreported",
};
appendUsageEntry(entry1);

// Simulate directory deletion by log rotation / cleanup while process is running
rmSync(testDir, { recursive: true, force: true });
expect(existsSync(testDir)).toBe(false);

const entry2: PersistedUsageEntry = {
requestId: "ocx-enoent-2",
timestamp: Date.now(),
provider: "openai",
model: "gpt-4o",
status: 200,
durationMs: 12,
usageStatus: "unreported",
};
expect(() => appendUsageEntry(entry2)).not.toThrow();
const readBack = readRecentUsageEntries(10);
expect(readBack.length).toBe(1);
expect(readBack[0].requestId).toBe("ocx-enoent-2");
});
});
Loading