diff --git a/src/main.ts b/src/main.ts index afc5fbf0..ecf504a1 100644 --- a/src/main.ts +++ b/src/main.ts @@ -63,9 +63,18 @@ import { CodexThroughputReader, newestCodexSession, renderCodexThroughput } from // A downstream reader that closes the pipe early (`| head`, quitting `less`, or // a missing command) makes stdout writes fail with EPIPE. Exit cleanly rather // than crashing with an unhandled error event. +// +// The exit still drains outstanding credential rotations first. `codeburn quota +// | head` is the ordinary way to read that command, and a token grant the +// server has already accepted must reach disk whichever door the process +// leaves through. The drain resolves immediately when nothing is outstanding, +// which is every other command. process.stdout.on('error', (err: NodeJS.ErrnoException) => { - if (err.code === 'EPIPE') process.exit(0) - throw err + if (err.code !== 'EPIPE') throw err + void import('./quota/security.js') + .then(({ awaitCredentialWrites }) => awaitCredentialWrites()) + .catch(() => undefined) + .then(() => process.exit(0)) }) function collect(val: string, acc: string[]): string[] { @@ -2618,15 +2627,20 @@ program .action(async (opts) => { const { collectQuota, renderQuotaTable } = await import('./quota/index.js') const { awaitCredentialWrites } = await import('./quota/security.js') - const report = await collectQuota() - const out = opts.format === 'json' - ? JSON.stringify(report, null, 2) + '\n' - : renderQuotaTable(report, { color: opts.color }) + '\n' - await new Promise(resolve => { process.stdout.write(out, () => resolve()) }) - // A provider the per-provider timeout gave up on may still be between an - // accepted token grant and the credential file it has to rewrite. That - // token is already dead on disk, so exiting through it signs the user out. - await awaitCredentialWrites() + try { + const report = await collectQuota() + const out = opts.format === 'json' + ? JSON.stringify(report, null, 2) + '\n' + : renderQuotaTable(report, { color: opts.color }) + '\n' + await new Promise(resolve => { process.stdout.write(out, () => resolve()) }) + } finally { + // A provider the per-provider timeout gave up on may still be between an + // accepted token grant and the credential file it has to rewrite. That + // token is already dead on disk, so exiting through it signs the user out. + // In a finally because a throw anywhere above leaves through the same + // door: one provider failing must not strand another's rotation. + await awaitCredentialWrites() + } // A keychain lookup or local-server probe abandoned by the per-provider // timeout keeps its child alive long past the output, so leave on purpose // once the output has flushed and nothing is mid-rotation. diff --git a/src/quota/security.ts b/src/quota/security.ts index c2de797c..4d4d191b 100644 --- a/src/quota/security.ts +++ b/src/quota/security.ts @@ -194,8 +194,11 @@ export function atomicWriteSecureFileSync(filePath: string, contents: string): v } } +/// How long a quota request, including a token grant, is given to answer. +export const QUOTA_REQUEST_TIMEOUT_MS = 30_000 + export function quotaRequestSignal(parent?: AbortSignal): AbortSignal { - const timeout = AbortSignal.timeout(30_000) + const timeout = AbortSignal.timeout(QUOTA_REQUEST_TIMEOUT_MS) return parent ? AbortSignal.any([parent, timeout]) : timeout } @@ -209,10 +212,13 @@ export function quotaRequestSignal(parent?: AbortSignal): AbortSignal { /// has to drain this first. const outstandingCredentialWrites = new Set>() -/// Past this an exit stops waiting. A grant that has not answered in this long -/// is not going to, and a command that never returns the shell is worse than -/// the rotation it was protecting. -export const CREDENTIAL_DRAIN_TIMEOUT_MS = 15_000 +/// Past this an exit stops waiting. It has to outlast the request it is waiting +/// on, or the guard expires while the very case it was built for is still in +/// flight: a grant answering at twenty seconds is exactly the slow reply that +/// costs the user their login. Derived from the request timeout rather than +/// written as a number, so the two cannot drift apart, plus a margin for the +/// write that follows the reply. +export const CREDENTIAL_DRAIN_TIMEOUT_MS = QUOTA_REQUEST_TIMEOUT_MS + 5_000 /** Registers a rotation for {@link awaitCredentialWrites} to wait on. Returns * the same promise, so a caller can keep awaiting it exactly as before. */ @@ -243,7 +249,17 @@ export async function awaitCredentialWrites(timeoutMs = CREDENTIAL_DRAIN_TIMEOUT // rotation while the first is still draining. while (outstandingCredentialWrites.size > 0) { const drained = Promise.all([...outstandingCredentialWrites]).then(() => 'drained' as const) - if (await Promise.race([drained, expired]) === 'timeout') return + if (await Promise.race([drained, expired]) === 'timeout') { + // Giving up here can retire a login, so it is said out loud rather than + // left for the user to discover the next time a provider asks them to + // sign in again. + process.stderr.write( + 'codeburn: a provider login was still being refreshed after ' + + `${Math.round(timeoutMs / 1000)}s and was not saved. ` + + 'If that provider signs you out, sign in again with its own CLI.\n', + ) + return + } } } finally { if (timer) clearTimeout(timer) diff --git a/tests/quota-codex-refresh.test.ts b/tests/quota-codex-refresh.test.ts index e15b4a0c..8e2a509c 100644 --- a/tests/quota-codex-refresh.test.ts +++ b/tests/quota-codex-refresh.test.ts @@ -7,7 +7,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { collectQuota } from '../src/quota/index.js' import { fetchCodexQuota } from '../src/quota/codex.js' -import { awaitCredentialWrites, pendingCredentialWrites } from '../src/quota/security.js' +import { CREDENTIAL_DRAIN_TIMEOUT_MS, QUOTA_REQUEST_TIMEOUT_MS, awaitCredentialWrites, pendingCredentialWrites } from '../src/quota/security.js' const NOW = Date.parse('2026-09-02T12:00:00.000Z') const OLD_REFRESH = 'refresh-token-that-the-grant-retires' @@ -192,6 +192,42 @@ describe('Codex quota credential rotation', () => { await awaitCredentialWrites(0) }) + // A guard that expires before the thing it guards is no guard at all: a grant answering at + // twenty seconds is exactly the slow reply the drain exists for, and the old fifteen second + // wait gave up on it while it was still in flight. + it('waits longer than the request it is waiting on', () => { + expect(CREDENTIAL_DRAIN_TIMEOUT_MS).toBeGreaterThan(QUOTA_REQUEST_TIMEOUT_MS) + }) + + it('says so on stderr rather than losing a login in silence', async () => { + await writeAuth(authDoc()) + const written: string[] = [] + const stderr = vi.spyOn(process.stderr, 'write').mockImplementation((chunk: unknown) => { + written.push(String(chunk)) + return true + }) + let grantStarted = (): void => {} + const reachedGrant = new Promise(resolve => { grantStarted = resolve }) + let releaseGrant = (): void => {} + const heldGrant = new Promise(resolve => { releaseGrant = resolve }) + + const pending = fetchCodexQuota({ + authPath, + now: () => NOW, + fetch: routes({ + token: async () => { grantStarted(); await heldGrant; return rotatedGrant() }, + usage: usagePayload, + }), + }) + await reachedGrant + await awaitCredentialWrites(10) + + expect(written.join('')).toMatch(/still being refreshed.*was not saved/s) + stderr.mockRestore() + releaseGrant() + await pending + }) + it('stops waiting on a grant that never answers', async () => { await writeAuth(authDoc()) vi.spyOn(console, 'warn').mockImplementation(() => undefined)