Something went wrong. Try again.
small gleam coding and persistent agent daemon with a detachable cli and a canvas ui forked from okami.mom/albedo
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347import { 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<T> { 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<UsageSummary>; limits: Resource<Quota[]>; /** 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<T> { data: T | null; state: Resource<T>['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<typeof setTimeout> | undefined; timeout: ReturnType<typeof setTimeout> | undefined; ask: (signal: AbortSignal) => Promise<T>; /** 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<UsageSummary> { query: UsageQuery;}
interface Listener { on: (reading: Reading) => void; key: string;}
const listeners = new Set<Listener>();/** One read per query, shared by every caller asking for it, dropped when its last caller goes. */const usages = new Map<string, UsageSlot>();/** The limits do not depend on a query: one read serves them all. */let limits: Slot<Quota[]> | undefined;let clock: ReturnType<typeof setTimeout> | 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<T>( ask: (signal: AbortSignal) => Promise<T>, tell: () => void,): Slot<T> { 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<T>(slot: Slot<T>): Resource<T> { return { data: slot.data, state: slot.state, refreshedAt: slot.refreshedAt };}
const nothing = <T>(): Resource<T> => ({ data: null, state: 'loading', refreshedAt: null,});
function readingFor(listener: Listener): Reading { const usage = usages.get(listener.key); return { usage: usage ? resource(usage) : nothing<UsageSummary>(), limits: limits ? resource(limits) : nothing<Quota[]>(), 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<T>(slot: Slot<T>) { 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<T>(slot: Slot<T>) { 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<T>(slot: Slot<T>) { 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<T>( slot: Slot<T>, 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<T>(slot: Slot<T>) { 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<T>(slot: Slot<T>): 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();}