Skip to content
Merged
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
38 changes: 35 additions & 3 deletions tui.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,26 @@ import { clampPercent, fetchUsage, type Usage, type UsageWindow, type UsageWindo
const POLL_MS = 60_000
const CLOCK_MS = 30_000

/** Upper bound for a whole refresh cycle, credential lookup included. */
const REFRESH_TIMEOUT_MS = 15_000

/**
* Race a promise against a deadline. Resolves `undefined` when the deadline
* wins, so the caller can tell a timeout apart from a real result.
*/
async function withDeadline<T>(promise: Promise<T>, ms: number): Promise<T | undefined> {
let timer: ReturnType<typeof setTimeout> | undefined
const deadline = new Promise<undefined>((resolve) => {
timer = setTimeout(() => resolve(undefined), ms)
})

try {
return await Promise.race([promise, deadline])
} finally {
clearTimeout(timer)
}
}

const ROWS: { key: UsageWindowKind; label: string }[] = [
{ key: "rolling", label: "5h" },
{ key: "weekly", label: "7d" },
Expand Down Expand Up @@ -80,15 +100,27 @@ const Panel = (props: { theme: unknown }) => {
const palette = () => paletteOf(props.theme)

let disposed = false
let refreshing = false

const refresh = async () => {
if (refreshing) return
refreshing = true

try {
const result = await fetchUsage()
const result = await withDeadline(fetchUsage(), REFRESH_TIMEOUT_MS)
if (disposed) return

if (!result) {
setStatus({ kind: "error", message: "request timed out" })
return
}

setStatus(result.ok ? { kind: "ready", usage: result.usage } : { kind: "error", message: result.error })
} catch (error) {
} catch {
if (disposed) return
setStatus({ kind: "error", message: String(error).slice(0, 80) })
setStatus({ kind: "error", message: "unexpected error" })
} finally {
refreshing = false
}
}

Expand Down
Loading