Documentation
¶
Overview ¶
Package usagereport builds the token ledger read model: what each provider burned, which projects and people it was burned for, and where a given provider is actually used.
It lives here, rather than inside the providers page that first needed it, because the same ledger is read from two places that have nothing else in common — the Svelte providers UI and the server-rendered admin analytics page. Two renderers over one report is fine; two reports that "should" agree is how a host ends up with a $29.08 on one page and a $31.40 on another, with nobody able to say which is wrong.
Everything here is derived from the per-session usage.json files. The roll-up walks one small file per session, so it is cached per window: an analytics view that is a few seconds stale costs nobody anything, while re-walking thousands of sessions on every poll shows up as disk churn on a small box.
Index ¶
Constants ¶
const CacheTTL = 15 * time.Second
CacheTTL is how long a computed roll-up is reused. Short enough that a finished turn shows up while the user is still looking at the page, long enough that a dashboard polling every second does not walk the session tree every second.
Variables ¶
var WindowKeys = []string{"today", "7d", "30d", "90d", "1y", "all"}
WindowKeys lists the ranges in the order a UI should offer them — narrowest first, because the narrow ones are what people check repeatedly and the wide ones are what they check once.
Functions ¶
func ParseDate ¶
ParseDate reads a YYYY-MM-DD from a query string in the given location. A value it cannot read is a zero time, i.e. "no bound", which is the safe reading of a malformed date on a reporting page.
func SortSlices ¶
func SortSlices(rows []Slice)
SortSlices orders by cost, then by tokens, then by key — cost first because that is the question being asked, key last so the order is stable when two rows tie (a list that reshuffles between polls is unreadable).
Types ¶
type Builder ¶
type Builder struct {
Layout config.Layout
UserName func(id string) string
// Tags resolves a session id to what the roll-up groups and filters
// by. Optional: the default reads the session from disk. A caller
// that already keeps a cache of session facts (the admin analytics
// page does) should supply it and save the second walk — same data,
// read once.
Tags func(id string) store.SessionTags
// contains filtered or unexported fields
}
Builder computes and caches reports for one host.
UserName resolves a wick user id to a name; it comes from the caller because the mapping lives in the database and this package must stay free of it. Nil is fine — rows then show the id, which is still the truth about who spent it.
func (*Builder) Provider ¶
Provider builds the one-provider report, naming every session it was used in. A bare session id told a reader nothing — whose work it was and which project it belonged to is the whole question behind "where is this provider used".
type ProviderReport ¶
type ProviderReport struct {
Provider string `json:"provider"`
Window string `json:"window"`
WindowLabel string `json:"window_label"`
Since string `json:"since,omitempty"`
Windows []Option `json:"windows"`
Totals Totals `json:"totals"`
Turns int `json:"turns"`
// ByModel is this provider's own spend split by model — the same
// rows the fleet report carries, narrowed to this one door.
ByModel []Slice `json:"by_model,omitempty"`
Sessions []SessionUse `json:"sessions"`
Partial bool `json:"partial,omitempty"`
Note string `json:"note,omitempty"`
}
ProviderReport answers "what did THIS provider cost, and where was it used" for one provider key ("claude/default").
type Report ¶
type Report struct {
Window string `json:"window"`
WindowLabel string `json:"window_label"`
Since string `json:"since,omitempty"`
Until string `json:"until,omitempty"`
Windows []Option `json:"windows"`
Totals Totals `json:"totals"`
Turns int `json:"turns"`
Sessions int `json:"sessions"`
ByProvider []Slice `json:"by_provider"`
// ByModel goes one level below the provider: a provider is a door,
// and which model answered behind it is what decides both the bill
// and whether the answer was any good. Rows are (provider, model)
// pairs — see store.ModelRowKey.
ByModel []Slice `json:"by_model"`
ByProject []Slice `json:"by_project"`
ByUser []Slice `json:"by_user"`
// Partial says the window could not be reconstructed in full for
// every session — see store.UsageRollup.Partial. Carried into the
// DTO so the UI can say "at least" instead of implying a total.
Partial bool `json:"partial,omitempty"`
Note string `json:"note,omitempty"`
}
Report is the whole-fleet answer for one window.
type Scope ¶
type Scope struct {
Channels []string
// Instances narrows to specific bots ("slack:<owner id>"). It only
// means anything when the Builder's Tags resolver fills
// SessionTags.Instance — the default one cannot, so a caller using it
// must leave this empty rather than get an empty report that reads
// like a real answer.
Instances []string
}
Scope narrows the ledger the way a page's filter bar does: to certain channels, or to specific bots within them. Empty means everything.
It exists so a page with one filter bar has ONE answer below it. A token figure that ignored the channel filter would sit next to a chart that honoured it, and the two would disagree without either being wrong — the worst kind of dashboard bug, because nothing looks broken.
type SessionUse ¶
type SessionUse struct {
ID string `json:"id"`
Label string `json:"label,omitempty"`
ProjectID string `json:"project_id,omitempty"`
ProjectName string `json:"project_name,omitempty"`
UserID string `json:"user_id,omitempty"`
UserName string `json:"user_name,omitempty"`
LastAt string `json:"last_at,omitempty"`
Turns int `json:"turns,omitempty"`
Totals Totals `json:"totals"`
}
SessionUse is one line of "where is this provider used": which conversation, whose, under what project, and what it spent there.
type Slice ¶
type Slice struct {
Key string `json:"key"`
Label string `json:"label,omitempty"`
Totals Totals `json:"totals"`
Sessions int `json:"sessions,omitempty"`
// Turns is how many turns this row ran. Cost answers "what is
// expensive"; turns answer "what do we actually use" — and on a flat
// -rate plan, where every cost is zero, turns are the only answer
// there is.
Turns int `json:"turns,omitempty"`
// Group is the row this one hangs under: for a model row, the
// provider it was reached through. The same model id through two
// providers is two rows, and without this the UI cannot say why.
Group string `json:"group,omitempty"`
// drawn without the client summing the list first.
Share float64 `json:"share"`
}
Slice is one row of a breakdown, sorted by cost then tokens so the expensive row is always first.
func ModelSlices ¶
func ModelSlices(roll store.UsageRollup, grand int, provider string) []Slice
ModelSlices turns the roll-up's (provider, model) buckets into rows.
`provider` narrows to one door, or is empty for the whole fleet. The row's Label is the model id — the thing anyone reading this actually asked about — and Group names the provider it came through, so a model reached through two accounts reads as two rows rather than as a mystery duplicate.
type Totals ¶
type Totals struct {
Input int `json:"input"`
CacheRead int `json:"cache_read"`
CacheWrite int `json:"cache_write"`
Output int `json:"output"`
Total int `json:"total"`
CostUSD float64 `json:"cost_usd"`
// CacheHitPct is cache reads as a share of all input tokens — the
// single most actionable number here, because a collapsing hit rate
// is what turns a cheap session expensive.
CacheHitPct float64 `json:"cache_hit_pct"`
}
Totals mirrors store.UsageTotals plus the two derived numbers every renderer would otherwise recompute for itself.
func TotalsOf ¶
func TotalsOf(t store.UsageTotals) Totals
TotalsOf derives the presentation totals from the stored flows.
type Window ¶
type Window struct {
Key string `json:"key"`
Label string `json:"label"`
Since time.Time `json:"-"`
Until time.Time `json:"-"`
}
Window is one selectable range. A zero Since means all time; a zero Until means "up to now".
func CustomWindow ¶
CustomWindow bounds the ledger by explicit dates, so "1-7 Sep" on a page means the same seven days in its token figures.
Dates are whole days in the server's timezone, the way a date picker means them: `from` starts at its midnight, `to` ends at the last instant of its day. A `to` earlier than `from` is treated as no upper bound rather than as an empty range — an inverted pair is a typo, and answering "zero" to it looks like a fact.
func ParseWindow ¶
ParseWindow resolves a key to a window, falling back to all time for anything unrecognised (including ""). An unknown range must not be an error: it arrives from a URL, and answering the broadest question is more useful than refusing to answer.
func WindowFromQuery ¶
WindowFromQuery resolves the range a request asked for: explicit dates win, otherwise a named window, otherwise all time. One function so the two mounts that serve this report cannot disagree about what a query string means.