import { getLimits, getUsage, type Quota, type UsageSummary } from './api'; import { localOffset } from './usage'; // What the usage window and the top-bar menu show (robot-docs/web.md): totals // for the days and scope a caller asks for, and the limits, which are // account-wide and so are read once for everyone. Each source owns its read, // its timer and its abort, so a source that fails or hangs never holds another // one up, and reading is never stacked on reading: a poke during a read is // answered by that read. A read that outlives its slot (its last caller left, // or the tab went away) is aborted, and one that answers anyway says nothing // and schedules nothing. The page's clock is the one thing shared: while the // tab is visible it moves `now`, which is how a window says how old a reading // is without reading anything. /** The days a caller may ask for: today, the week the window charts, or a month. */ export type UsageDays = 1 | 7 | 30; /** What to read: the days, and the provider and account to narrow the totals to. */ export interface UsageQuery { days: UsageDays; provider?: string; account?: string; } /** One source's read: its data and freshness, or why it cannot be shown. */ export interface Resource { data: T | null; /** `loading` until the first read settles, then `ready`, `stale` (a later read failed), or `error` (the first one did). */ state: 'loading' | 'ready' | 'stale' | 'error'; /** When the browser's read of it succeeded, Unix milliseconds; a quota's own `observed_at` is the provider's time. */ refreshedAt: number | null; } /** One look at the usage: the totals and limits as read, on the page's own clock. */ export interface Reading { usage: Resource; limits: Resource; /** The page's clock when this reading was made, so a stale one can say how old it is. */ now: number; /** The minutes the page's clock is ahead of UTC, which is how the daemon cuts the days. */ offset: number; } /** How soon a source is read again, how long a read is given, and how often the page's clock moves. */ export const USAGE_MS = { shown: 30_000, retry: 10_000, timeout: 15_000, clock: 5_000, }; interface Slot { data: T | null; state: Resource['state']; refreshedAt: number | null; /** The read being asked for, or null. Its identity is how a read knows it still belongs to this slot. */ abort: AbortController | null; /** When this source reads next; and when the read in flight is given up on. */ timer: ReturnType | undefined; timeout: ReturnType | undefined; ask: (signal: AbortSignal) => Promise; /** Says what this source now holds, to the callers it serves. */ tell: () => void; /** * Whether anything still keeps this source. A slot is marked dead before its * last timer is cleared and its read aborted, so a read it told cannot arm it * again. */ alive: boolean; } interface UsageSlot extends Slot { query: UsageQuery; } interface Listener { on: (reading: Reading) => void; key: string; } const listeners = new Set(); /** One read per query, shared by every caller asking for it, dropped when its last caller goes. */ const usages = new Map(); /** The limits do not depend on a query: one read serves them all. */ let limits: Slot | undefined; let clock: ReturnType | undefined; let now = Date.now(); // A query is its days and scope as given: an empty account (a provider's own // unlabelled account) is a filter of its own, and not the same read as no // account at all. const keyOf = (query: UsageQuery): string => JSON.stringify([query.days, query.provider ?? null, query.account ?? null]); function empty( ask: (signal: AbortSignal) => Promise, tell: () => void, ): Slot { return { data: null, state: 'loading', refreshedAt: null, abort: null, timer: undefined, timeout: undefined, ask, tell, alive: true, }; } function usageSlot(key: string, query: UsageQuery): UsageSlot { const scope = query.provider === undefined && query.account === undefined ? undefined : { provider: query.provider, account: query.account }; // The offset is asked for at each read, so a page that travels or crosses a DST change // reads with the offset it has now. return { ...empty( (signal) => getUsage(query.days, localOffset(), signal, scope), () => tellKey(key), ), query, }; } function resource(slot: Slot): Resource { return { data: slot.data, state: slot.state, refreshedAt: slot.refreshedAt }; } const nothing = (): Resource => ({ data: null, state: 'loading', refreshedAt: null, }); function readingFor(listener: Listener): Reading { const usage = usages.get(listener.key); return { usage: usage ? resource(usage) : nothing(), limits: limits ? resource(limits) : nothing(), now, // The days a reading holds were cut at the offset it was read with, so it keeps naming // them that way until a read made at the page's new offset replaces it. offset: usage?.data?.utc_offset_minutes ?? localOffset(), }; } function tellKey(key: string) { for (const listener of listeners) if (listener.key === key) listener.on(readingFor(listener)); } function tellAll() { for (const listener of listeners) listener.on(readingFor(listener)); } function stopClock() { clearTimeout(clock); clock = undefined; } function tickClock() { clock = undefined; if (!listeners.size || document.hidden) return; const at = Date.now(); if (at !== now) { now = at; tellAll(); } clock = setTimeout(tickClock, USAGE_MS.clock); } function startClock() { if (clock === undefined && listeners.size && !document.hidden) clock = setTimeout(tickClock, USAGE_MS.clock); } /** Reads this source soon, and only it: a failing neighbour keeps its own timing. */ function arm(slot: Slot) { clearTimeout(slot.timer); slot.timer = undefined; if (!slot.alive || !listeners.size || document.hidden) return; const failed = slot.state === 'error' || slot.state === 'stale'; slot.timer = setTimeout( () => read(slot), failed ? USAGE_MS.retry : USAGE_MS.shown, ); } /** Puts a source's next read off until something asks for it again. */ function pause(slot: Slot) { clearTimeout(slot.timer); slot.timer = undefined; } /** * Stops a source reading, and stops hearing from the read it was waiting on: what * that read answers is neither this slot's news nor its next timing. Used when the * last caller of a source goes. */ function stop(slot: Slot) { slot.alive = false; clearTimeout(slot.timer); clearTimeout(slot.timeout); slot.timer = undefined; slot.timeout = undefined; const controller = slot.abort; slot.abort = null; controller?.abort(); } function settle( slot: Slot, controller: AbortController, value: T | null, ) { // A read this slot has stopped waiting for (it was dropped, or the tab went away) is not its news. if (slot.abort !== controller) return; slot.abort = null; clearTimeout(slot.timeout); slot.timeout = undefined; if (value !== null) { slot.data = value; slot.state = 'ready'; slot.refreshedAt = Date.now(); } else { slot.state = slot.data ? 'stale' : 'error'; } now = Date.now(); slot.tell(); // Telling can be what stops this slot, when a caller leaves from its own callback. if (slot.alive) arm(slot); } /** Asks this source now; a read already running for it is the answer, so pokes and subscriptions never stack one. */ function read(slot: Slot) { if (!slot.alive || slot.abort || !listeners.size || document.hidden) return; clearTimeout(slot.timer); slot.timer = undefined; const controller = new AbortController(); slot.abort = controller; // A read that hangs is given up on rather than left holding its slot in `loading` for ever. slot.timeout = setTimeout(() => { if (slot.abort !== controller) return; controller.abort(); settle(slot, controller, null); }, USAGE_MS.timeout); slot.ask(controller.signal).then( (value) => settle(slot, controller, value), () => settle(slot, controller, null), ); } /** Whether this source was read recently enough to leave alone for now. */ function fresh(slot: Slot): boolean { return ( slot.refreshedAt !== null && Date.now() - slot.refreshedAt < USAGE_MS.shown ); } function readEvery() { for (const usage of usages.values()) read(usage); if (limits) read(limits); } /** Stops every source's next read, leaving a read in flight to answer or time out. */ function pauseEvery() { for (const usage of usages.values()) pause(usage); if (limits) pause(limits); } function visibility() { if (document.hidden) { // Nothing new is read while the tab is away: each source's next read is put off, and one // already running is left to answer (it schedules nothing more while the tab is hidden). stopClock(); pauseEvery(); return; } // Back: say how old what is shown has become, and read now rather than after the wait. now = Date.now(); tellAll(); startClock(); readEvery(); } /** * Follows the usage and limits for `query`; `on` is told what is known at once * (loading, on the first read of a query) and each time a source it follows, or * the clock, changes the reading. Callers of one query share its read and share * the limits, and a source that was read a moment ago is not read again for a * new caller. Calling the returned function stops this caller; the last one to * leave stops the reads and drops what they kept. */ export function watchUsage( on: (reading: Reading) => void, query: UsageQuery = { days: 1 }, ): () => void { const key = keyOf(query); let usage = usages.get(key); if (!usage) { usage = usageSlot(key, query); usages.set(key, usage); } let quota = limits; if (!quota) { quota = empty((signal) => getLimits(signal), tellAll); limits = quota; } now = Date.now(); const listener: Listener = { on, key }; if (!listeners.size) document.addEventListener('visibilitychange', visibility); listeners.add(listener); on(readingFor(listener)); // Only what this caller cannot already be shown is read: a fresh source keeps its own timing. if (!fresh(usage)) read(usage); if (!fresh(quota)) read(quota); startClock(); return () => { if (!listeners.delete(listener)) return; if (![...listeners].some((other) => other.key === key)) { const dropped = usages.get(key); if (dropped) { stop(dropped); usages.delete(key); } } if (listeners.size) return; document.removeEventListener('visibilitychange', visibility); stopClock(); if (limits) { stop(limits); limits = undefined; } }; } /** Reads now, if anything is following the usage: what a window's "try again" asks for. A source already reading answers this too, so a poke never stacks one read on another. */ export function pokeUsage() { if (!listeners.size || document.hidden) return; // A source already being read answers this too: a poke refreshes what is known, it does not queue a second read. readEvery(); }