usage

package
v0.30.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 23, 2026 License: Apache-2.0 Imports: 12 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package usage defines the per-request usage Event, the Sink and Reader interfaces its storage backends implement, and the in-memory filtering and aggregation shared by scan-style backends.

Index

Constants

View Source
const (
	DefaultFacetLimit = 50
	MaxFacetLimit     = 200
	MaxFacetDims      = 16
)

Facet request bounds: values per dimension (default and cap) and dimensions per request.

View Source
const DefaultEventLimit = 100

DefaultEventLimit caps an unbounded Events query so a misconfigured caller doesn't try to deserialize the whole log file at once.

View Source
const ErrorKindUpstream = "upstream_error"

ErrorKindUpstream is the kind of an event whose provider answered with an error status (Status >= 400), whether relay passed the response through, gave up after trying every key, or was told about the call by a client.

View Source
const GroupByNone = "none"

GroupByNone aggregates the whole filtered slice into one row whose Group is an empty map. It is not a dimension, so ValidGroupBy leaves it out.

View Source
const MaxBuckets = 5_000

MaxBuckets caps the number of time buckets a single TimeSeries query may span (range / interval). Guards against a tiny interval over a huge range producing an unbounded result. The HTTP layer rejects with 400 before hitting a backend.

View Source
const MaxEventLimit = 10_000

MaxEventLimit clamps Limit to avoid OOM on a hostile request.

View Source
const MaxTagKeyLen = 64

MaxTagKeyLen caps a single tag key. Enforced at write time (app/usagelog tag validation) and reused by MapGroupKey so an unwritable key can't become a group dimension.

Variables

View Source
var ErrNoPreviousWindow = errors.New("usage: comparing with the previous window needs a window with a start that is not after its end")

ErrNoPreviousWindow rejects a comparison whose window has no lower bound or ends before it starts: neither has a previous window of equal length.

View Source
var ValidDistinct = []string{
	"relay_key_hash",
	"relay_key",
	"principal_id",
	"credential_id",
	"pool_id",
	"account_id",
	"lane_account_id",
	"via_account_id",
	"project_id",
	"team_id",
	"model_id",
	"host_id",
}

ValidDistinct lists the dimensions SummaryQuery.Distinct and TimeSeriesQuery.Distinct may count. Each is also the column name in the SQL schemas.

View Source
var ValidGroupBy = []string{
	"relay_key_hash",
	"policy_id",
	"pool_id",
	"account_id",
	"lane_account_id",
	"via_account_id",
	"model_id",
	"host_id",
	"host_key_id",
	"source",
	"finish_reason",
	"error_kind",
	"refusal",
	"model",
	"host",
	"policy",
	"provider",
	"project_id",
	"team_id",
	"principal_id",
	"credential_id",
	"project",
	"team",
	"principal",
	"relay_key",
}

ValidGroupBy lists the accepted static GroupBy values. Used by the HTTP endpoint to reject typos with a clear 400 instead of silently grouping on nothing. "tags.<key>" and "extras.<key>" are additionally accepted as dynamic dimensions — see MapGroupKey.

Functions

func CountEvents added in v0.11.1

func CountEvents(events []Event, q EventQuery, limit int) int64

CountEvents counts the events FilterEvents would keep for q, ignoring q's cursor, and stops past limit (<= 0 counts all). It is Reader.Count for the scan-style backends.

func CountsRefused added in v0.20.0

func CountsRefused(q EventQuery, groupBy string) bool

CountsRefused reports whether an aggregate over q grouped by groupBy counts relay's own refusals: only one that filters or groups by refusal, so every other aggregate keeps its served-request numbers.

func DistinctColumn added in v0.11.1

func DistinctColumn(dim string) (column string, ok bool)

DistinctColumn returns the column counted for a ValidDistinct dimension; ok is false for anything else. SQL backends embed only the returned allowlist entry, never the caller's string.

func FacetLimit added in v0.11.1

func FacetLimit(limit int) int

FacetLimit clamps a requested facet limit to [1, MaxFacetLimit], defaulting to DefaultFacetLimit.

func Facets added in v0.11.1

func Facets(ctx context.Context, r Reader, q EventQuery, dims []string, limit int) (map[string][]FacetValue, error)

Facets runs one Facet query per dimension, each with q minus that dimension's own filter (WithoutFilter), so a dropdown lists the values the other filters still allow.

func GroupLabel added in v0.11.1

func GroupLabel(groupBy, value string) map[string]string

GroupLabel is a row's Group map: nil for "", {} for GroupByNone, {groupBy: value} otherwise. Every backend builds labels through it so the shape cannot drift.

func Grouped added in v0.11.1

func Grouped(groupBy string) bool

Grouped reports whether groupBy splits rows by a dimension; "" (one ungrouped series) and GroupByNone do not.

func IsValidFacetDim added in v0.11.1

func IsValidFacetDim(dim string) bool

IsValidFacetDim reports whether dim can be faceted: any group dimension except GroupByNone.

func IsValidGroupBy

func IsValidGroupBy(g string) bool

IsValidGroupBy reports whether g is GroupByNone or one of the supported group dimensions (a ValidGroupBy entry or a dynamic map one).

func LabelColumn added in v0.11.1

func LabelColumn(dim string) (string, bool)

LabelColumn returns the slug column that names values of the id dimension dim. ok is false for slug dimensions and ids without a slug (host_key_id). The column is itself a group dimension, so it is safe to embed in SQL.

func MapGroupKey added in v0.9.15

func MapGroupKey(g string) (column, key string, ok bool)

MapGroupKey splits a dynamic map group dimension — "tags.<key>" (caller tags) or "extras.<key>" (relay-stamped provenance: instance, client_ip, resolved_via) — into the Event map column and the key within it. ok is false when g isn't map-shaped or the key is empty / over MaxTagKeyLen. Backends MUST bind the returned key as a query parameter, never splice it into SQL text; column is one of the two fixed names and safe to embed.

func PreviousWindow added in v0.11.1

func PreviousWindow(from, to time.Time) (time.Time, time.Time)

PreviousWindow is the window of the same length as [from, to] that ends at from. The returned end is exclusive, so no event falls in both windows.

func ResolveWindow added in v0.11.1

func ResolveWindow(q EventQuery, now time.Time) (from, to time.Time, err error)

ResolveWindow returns q's absolute bounds as every backend applies them: the lower bound is From, else now-Since; the upper bound is To, else now.

func SortTimeSeriesRows

func SortTimeSeriesRows(rows []TimeSeriesRow, totals map[string]int64, groupBy string)

SortTimeSeriesRows orders series by total request count desc, with the group value as a stable tiebreak. totals is keyed by the series key (the groupBy dimension value, or "" for the single-series case). Shared by the in-memory Bucketize path and the SQL backends so all readers return series in the same order.

Types

type BatchWriter added in v0.11.7

type BatchWriter interface {
	// WriteBatch delivers evs in order. An error may leave a prefix of the
	// batch written; the Emitter logs it and moves on, as for Write.
	WriteBatch(evs []Event) error
}

BatchWriter is the optional bulk path of a Sink: the Emitter hands each drained batch to WriteBatch in one call, and falls back to one Write per event for a Sink without it. The slice is reused once the call returns.

type Closer

type Closer interface {
	Close() error
}

Closer is the optional shutdown contract for a Sink. The Emitter type-asserts each sink for it on Close and, when present, calls Close after the queue drains — giving buffered/remote backends (ClickHouse, valkey) a chance to flush their final batch before exit.

type DurationStats

type DurationStats struct {
	Avg int64 `json:"avg" doc:"Mean."`
	P50 int64 `json:"p50" doc:"Median."`
	P95 int64 `json:"p95" doc:"95th percentile."`
	P99 int64 `json:"p99" doc:"99th percentile."`
	Max int64 `json:"max" doc:"Maximum."`
}

DurationStats holds latency aggregates in milliseconds.

type Event

type Event struct {
	// Identity / trace
	RequestID string `json:"request_id" doc:"Request id."`
	Source    string `` // "pipeline" | "proxy" | "ws" | "batch" | "count" | "otlp"
	/* 242-byte string literal not displayed */
	Timestamp time.Time `json:"ts"         doc:"When the request started."`

	// Outcome
	Status       int    ``                                                                                                /* 224-byte string literal not displayed */
	DurationMs   int64  `json:"duration_ms"             doc:"Milliseconds from request start until the response closed."` // total: start → response closed
	Streamed     bool   `json:"streamed,omitempty"      doc:"The response was streamed."`
	FinishReason string `json:"finish_reason,omitempty" doc:"Why generation stopped: stop, length, tool_calls, content_filter, refusal or other."` // "stop"|"length"|"tool_calls"|"content_filter"|"refusal"|"other"
	Attempts     int    `json:"attempts,omitempty"      doc:"Upstream attempts, counting failover; 0 when not tracked."`                           // upstream tries (pipeline failover); 0 = not tracked
	ErrorKind    string ``                                                                                                                         /* 134-byte string literal not displayed */
	Refusal      string ``                                                                                                                         /* 494-byte string literal not displayed */
	ErrorMessage string `json:"error_message,omitempty" doc:"Error message of a failed request."`

	// Upstream is the upstream-leg timing breakdown. Nil when the request
	// never reached upstream (routing/pre-flight failure). The total
	// (start → close) is DurationMs; this adds the finer marks DurationMs
	// can't express. See UpstreamTiming for unit + how to derive TTFT.
	Upstream *sdkusage.UpstreamTiming `json:"upstream,omitempty" doc:"Upstream timing marks; absent when the request never reached an upstream."`

	// Reasoning is the reasoning span (when the model emitted reasoning
	// content). Nil unless the response was a canonical-observed stream
	// that carried reasoning. Microseconds from start, like Upstream.
	Reasoning *sdkusage.ReasoningTiming `json:"reasoning,omitempty" doc:"The reasoning span, for a translated stream that carried reasoning."`

	// Attribution — UUIDs (stable, snapshot-resolvable to slugs at
	// query time). Hash of the inbound bearer is included so the
	// plaintext is never logged.
	RelayKeyHash   string `json:"relay_key_hash,omitempty"  doc:"Hash of the relay key presented; empty for tokens and anonymous proxy traffic."`
	PolicyID       string `json:"policy_id,omitempty"       doc:"Id of the innermost caller policy that governed the request."`
	ModelID        string `json:"model_id,omitempty"        doc:"Id of the resolved model."`
	RequestedModel string `json:"requested_model,omitempty" doc:"The model string as the caller sent it."` // model string as the caller sent it
	HostID         string `json:"host_id,omitempty"         doc:"Id of the host that served the request."`
	// HostKeyID is the hash of the upstream credential's value (the key the
	// keypool breaker is keyed by), not the HostKey row id: a rotated key
	// records a new value.
	HostKeyID string `` /* 141-byte string literal not displayed */
	// PoolID and AccountID are the pool the serving credential was drawn from and the provider account it belongs to; empty when it was linked on its own or holds no account. PolicyID is the innermost caller policy.
	PoolID    string `` /* 132-byte string literal not displayed */
	AccountID string `` /* 191-byte string literal not displayed */
	// ViaAccountID is the shared account the request reached the key through; grouping by it splits account_id's total by holder.
	ViaAccountID string `` /* 262-byte string literal not displayed */

	// Tenancy + principal attribution as resolved at request entry.
	// Project/Team/Principal are the event-time slugs beside their ids —
	// same denormalization rationale as Model/Host/Policy below. Principal
	// is empty for a user principal (users live in Postgres, not the
	// snapshot the entry reads). CredentialKind/CredentialID name the
	// credential presented, not the subject; RelayKeyHash stays the hash of
	// the inbound bearer and is empty for token credentials.
	ProjectID      string `json:"project_id,omitempty"      doc:"Id of the caller's project."`
	Project        string `json:"project,omitempty"         doc:"The project's slug at request time."`
	TeamID         string `json:"team_id,omitempty"         doc:"Id of the caller's team."`
	Team           string `json:"team,omitempty"            doc:"The team's slug at request time."`
	PrincipalKind  string `json:"principal_kind,omitempty"  enum:"serviceaccount,user" doc:"Kind of the principal the request acted as."`
	PrincipalID    string `json:"principal_id,omitempty"    doc:"Id of the principal."`
	Principal      string `json:"principal,omitempty"       doc:"The service account's slug at request time; empty for a user."`
	CredentialKind string `json:"credential_kind,omitempty" doc:"Kind of credential presented, such as key or token."`
	CredentialID   string `json:"credential_id,omitempty"   doc:"Id of the credential presented: the relay key's id or the token's jti."`
	LaneAccountID  string `` /* 216-byte string literal not displayed */

	// Token usage as reported by the upstream. Empty on error or when
	// the adapter could not extract.
	Tokens sdkusage.Tokens `json:"tokens,omitempty" doc:"Token counts by kind (input, output, cache_read, reasoning, …) as the upstream reported them."`

	// Free-form per-runner tags (client_ip for anonymous proxy, etc.)
	Extras map[string]string `json:"extras,omitempty" doc:"Relay-recorded details, such as client_ip for anonymous proxy traffic."`

	// Tags are caller-owned (X-WR-Request-Tags, validated post-flight);
	// Extras stays relay-stamped — the provenance split queries rely on.
	Tags map[string]string `json:"tags,omitempty" doc:"Tags the caller sent in X-WR-Request-Tags."`

	// Model, Host, Policy are the entities' slugs (metadata.name) at
	// event time, denormalized so events stay self-describing when the
	// catalog entity is gone (deleted, renamed, re-seeded). The *_id
	// fields above remain the precise keys.
	Model  string `json:"model,omitempty"  doc:"The model's slug at request time."`
	Host   string `json:"host,omitempty"   doc:"The host's slug at request time."`
	Policy string `json:"policy,omitempty" doc:"The policy's slug at request time."`

	// Provider is the model's owning provider slug at event time — same
	// denormalization rationale as Model/Host/Policy above.
	Provider string `json:"provider,omitempty" doc:"The model provider's slug at request time."`

	// RelayKey is the inbound key's slug at event time, beside RelayKeyHash
	// and CredentialID — same denormalization rationale as Model/Host/Policy
	// above. Empty when no key was presented (token, anonymous proxy).
	RelayKey string `json:"relay_key,omitempty" doc:"The relay key's slug at request time; empty when no key was presented."`

	// Cost, stamped once at emit time from the pricing then in effect.
	// CostNanos is integer nano-USD (1 USD = 1e9) — integer so sums never
	// drift; USD-only by decision, so no currency field. nil = unpriced
	// (no pricing resolved, or no priceable tokens — error/LogOnly rows),
	// which MUST stay distinguishable from a true $0: never collapse nil
	// to 0. CostBreakdown is per-meter nanos (keys like "tokens.input");
	// Pricing is the rate sheet's slug, stamped whenever one resolved
	// (even if the row ended up unpriced) for audit.
	CostNanos     *int64           `` /* 173-byte string literal not displayed */
	CostBreakdown map[string]int64 `json:"cost_breakdown,omitempty" doc:"Cost in nano-USD per meter, such as tokens.input."`
	Pricing       string           `json:"pricing,omitempty"        doc:"Slug of the pricing sheet that applied."`
}

Event is the canonical per-request usage record: attribution, token counts, and the cost stamped once at emit time. Cost is a historical fact computed from the pricing in effect when the request ran — never recomputed at read time (pricing is mutable config). This package only carries the stamped fields; pricing resolution and the cost math live elsewhere (app/usagelog + pkg/catalogkind/pricing).

It lives in pkg/usage (not app/) so every sink/reader backend (file, ClickHouse, valkey, postgres) can consume it as a vendorable type without importing app/ — preserving the pkg-purity rule. The app/usagelog package re-exports it (type alias) for its lifecycle observers.

Field order is fixed (Go marshals in struct order) so JSONL / jq / ClickHouse column mapping stays stable across releases.

func FilterEvents

func FilterEvents(events []Event, q EventQuery) []Event

FilterEvents returns the subset of events matching q's time cutoff, dimension filters, and status range. It does not sort or apply Limit; use SortAndLimit for that.

func SortAndLimit

func SortAndLimit(events []Event, limit int) []Event

SortAndLimit sorts events newest-first and caps to limit (clamped to [DefaultEventLimit, MaxEventLimit] when out of range).

func (Event) Aggregated added in v0.20.0

func (e Event) Aggregated(refusals bool) bool

Aggregated reports whether an aggregate counts e: every row but a log-only one, and a log-only relay refusal too when refusals is set.

func (Event) LogOnly added in v0.3.0

func (e Event) LogOnly() bool

LogOnly reports whether the event records a request rejected before any upstream was reached: a relay refusal (which carries the status relay answered), or status 0 with an ErrorKind set. Such events stay visible in event listings (the logs view) but are excluded from Summary and TimeSeries aggregation — they carry no usage and would otherwise pollute stats as phantom unattributed requests.

type EventQuery

type EventQuery struct {
	// Time bounds. Lower bound resolution: From if set, else now()-Since,
	// else unbounded. Upper bound: To if set, else unbounded. From/To are
	// absolute and take precedence over the relative Since.
	Since time.Duration
	From  time.Time
	To    time.Time
	// Before is an exclusive upper bound (ts < Before), ANDed with To. It lets two adjacent windows split on one instant without counting an event on it twice.
	Before time.Time

	// RequestID is an exact single-value lookup (deep-link one event).
	RequestID string

	// Categorical filters — match any value in the slice (SQL IN / set
	// membership). Empty slice means no filter on that dimension.
	RelayKeyHash  []string
	PolicyID      []string
	PoolID        []string
	AccountID     []string
	LaneAccountID []string
	ViaAccountID  []string
	ProjectID     []string
	TeamID        []string
	PrincipalID   []string
	ModelID       []string
	HostID        []string
	Source        []string // "pipeline" | "proxy" | "ws" | "batch" | "count" | "otlp"
	FinishReason  []string
	ErrorKind     []string
	Refusal       []string

	// StatusMin / StatusMax restrict by HTTP status. Zero values mean
	// unbounded on that side. StatusMin=400 picks errors only;
	// StatusMin=200, StatusMax=299 picks successes only.
	StatusMin int
	StatusMax int
	// Status matches exact HTTP status codes (IN). Empty = no filter.
	// Composes with StatusMin/Max (AND).
	Status []int

	// More categorical filters (set membership; empty = no filter).
	HostKeyID      []string
	RequestedModel []string

	// Slug filters — match the denormalized entity names (Event.Model /
	// Host / Policy / Provider / RelayKey) recorded at event time.
	Model    []string
	Host     []string
	Policy   []string
	Provider []string
	RelayKey []string

	// Tags filters on caller-supplied event tags: key → accepted values.
	// AND across keys, OR within a key's values. An event with the key
	// missing matches only an explicit "" value. Nil/empty = no filter.
	Tags map[string][]string

	// Streamed / ErrorsOnly are tri-state: nil = no filter, else match the
	// bool. ErrorsOnly true matches status>=400 OR error_kind!="" (false
	// matches the complement — "successes only").
	Streamed   *bool
	ErrorsOnly *bool

	// AttemptsMin filters by upstream try count (failover). 0 = no filter.
	AttemptsMin int

	// DurationMsMin / DurationMsMax bound total request duration (ms).
	DurationMsMin int64
	DurationMsMax int64

	// TTFTMsMin / TTFTMsMax bound upstream time-to-first-byte (ms), derived
	// from Upstream.ResponseStart (µs from start). Events with no upstream
	// timing are excluded when either bound is set.
	TTFTMsMin int64
	TTFTMsMax int64

	// Q is a free-text needle matched (case-insensitive substring) against
	// request_id, model_id, requested_model, and source.
	Q string

	// Limit caps the number of events returned. <=0 → DefaultEventLimit.
	Limit int

	// ScopeProjectID / ScopeRelayKeyHash / ScopePrincipalID narrow the
	// stream to the slice of events the caller is authorized to read.
	// Unlike every other filter they are a DISJUNCTION: an event matches
	// when its project, its bearer hash or its principal is listed. All
	// empty means no scope narrowing — a caller who may read nothing must
	// be short-circuited by the handler, never passed through as
	// "unfiltered".
	ScopeProjectID    []string
	ScopeRelayKeyHash []string
	ScopePrincipalID  []string

	// CursorTS / CursorID implement keyset pagination for Events. When
	// CursorTS is non-zero, only events strictly older than the cursor are
	// returned — i.e. (ts, request_id) < (CursorTS, CursorID) under the
	// (ts DESC, request_id DESC) ordering. Set only on the Events path;
	// ignored by Summary / TimeSeries.
	CursorTS time.Time
	CursorID string
}

EventQuery filters the raw event stream. All fields are optional; zero values mean "no filter on this dimension."

func WithoutFilter added in v0.11.1

func WithoutFilter(q EventQuery, dim string) EventQuery

WithoutFilter returns q with its filter on dim removed and every other filter kept. Scope fields are never cleared, and neither are filters that only touch dim indirectly (q, status, error).

type FacetQuery added in v0.11.1

type FacetQuery struct {
	EventQuery
	Dim   string
	Limit int
}

FacetQuery asks for the most frequent values of one dimension over the rows matching EventQuery. Dim must be a group dimension other than GroupByNone.

type FacetValue added in v0.11.1

type FacetValue struct {
	Value    string `json:"value"           doc:"The dimension value, as filters accept it."`
	Label    string `json:"label,omitempty" doc:"Display name for an id value, such as its slug."`
	Requests int64  `json:"requests"        doc:"Requests with this value in the window."`
}

FacetValue is one value of a facet dimension and the number of requests that carry it. Label is the latest non-empty event-time slug for an id dimension (see LabelColumn), empty otherwise.

func TopValues added in v0.11.1

func TopValues(events []Event, dim string, limit int, refusals bool) ([]FacetValue, error)

TopValues counts the (already-filtered) events by dim and returns the most frequent values, requests desc then value asc. LogOnly events are skipped, as in Summarize; refusals keeps relay's own refusals among them (CountsRefused).

type FacetsResult added in v0.11.1

type FacetsResult struct {
	Facets map[string][]FacetValue `json:"facets" doc:"Top values per requested dimension, busiest first."`
	From   time.Time               `json:"from"   doc:"Start of the window the counts cover."`
	To     time.Time               `json:"to"     doc:"End of the window the counts cover."`
}

FacetsResult maps each requested dimension to its top values, with the window the query covered.

type LatestLabels added in v0.11.1

type LatestLabels struct {
	// contains filtered or unexported fields
}

LatestLabels keeps the newest non-empty label per non-empty group value. The zero value is ready to use.

func (*LatestLabels) Add added in v0.11.1

func (l *LatestLabels) Add(value, label string, ts time.Time)

Add records label for value as seen at ts, unless a newer one is already held.

func (*LatestLabels) Get added in v0.11.1

func (l *LatestLabels) Get(value string) string

Get returns value's label, empty when none was recorded.

func (*LatestLabels) Map added in v0.11.1

func (l *LatestLabels) Map() map[string]string

Map returns value → label, nil when nothing was recorded.

type Reader

type Reader interface {
	// Events returns raw events matching q, in reverse-chronological
	// order (newest first), capped at q.Limit.
	Events(ctx context.Context, q EventQuery) ([]Event, error)

	// Count returns how many events Events would match without a page limit, LogOnly events included; q.Limit and the cursor are ignored. Counting stops past limit (<= 0 counts all), so a caller passes cap+1 and reads n > cap as "more than cap".
	Count(ctx context.Context, q EventQuery, limit int) (int64, error)

	// Summary returns aggregated rows grouped by q.GroupBy. Each row
	// carries totals + latency percentiles over the events matching
	// the filter. Rows are sorted by Requests descending. LogOnly
	// events (pre-upstream rejections) are excluded from aggregation —
	// every backend must apply the Event.LogOnly predicate. The same
	// exclusion applies to TimeSeries; Events listings keep them.
	Summary(ctx context.Context, q SummaryQuery) (SummaryResult, error)

	// TimeSeries returns one or more series of time-bucketed aggregates
	// over the filtered set. With an empty GroupBy a single series is
	// returned; with a GroupBy dimension, one series per distinct value.
	// Buckets are aligned to the Unix epoch by q.Interval and ordered
	// oldest-first within each series.
	TimeSeries(ctx context.Context, q TimeSeriesQuery) (TimeSeriesResult, error)

	// Facet returns the most frequent values of q.Dim over the filtered set with their request counts, requests desc then value asc, capped at FacetLimit(q.Limit). It counts what Summary counts (LogOnly excluded) and nothing else; the empty value is a value like any other.
	Facet(ctx context.Context, q FacetQuery) ([]FacetValue, error)
}

Reader is the read-side counterpart to Sink. Implementations satisfy this against whatever backing store carries usage events — JSONL file, ClickHouse, valkey, in-memory for tests. Consumers (HTTP endpoints, CLI) depend on the interface, not the backend.

type Sink

type Sink interface {
	// Write delivers one event. The error is logged by the Emitter;
	// returning non-nil does not stop subsequent events.
	Write(ev Event) error
}

Sink consumes usage events. Implementations are expected to be non-blocking from the Emitter drain goroutine's perspective — slow I/O belongs inside the sink's own buffering, not in the caller.

A backend that needs a graceful drain (flush buffered rows, close a remote connection) additionally implements Closer; the Emitter calls Close after draining at shutdown.

type SummaryPrevious added in v0.11.1

type SummaryPrevious struct {
	Requests   int64            `json:"requests"           doc:"Requests in the previous window."`
	ErrorCount int64            `json:"error_count"        doc:"Requests with status 400 or above."`
	Errors4xx  int64            `json:"errors_4xx"         doc:"Requests with a 4xx status."`
	Errors5xx  int64            `json:"errors_5xx"         doc:"Requests with a status of 500 or above."`
	Throttled  int64            `json:"throttled"          doc:"Requests answered 429; part of errors_4xx."`
	Tokens     map[string]int64 `json:"tokens"             doc:"Token sums by kind."`
	CostNanos  int64            `json:"cost_nanos"         doc:"Cost of the priced requests, in nano-USD."`
	Unpriced   int64            `json:"unpriced"           doc:"Requests with no cost, left out of cost_nanos."`
	DurationMs DurationStats    `json:"duration_ms"        doc:"Request duration statistics in milliseconds."`
	TTFTMs     *DurationStats   `` /* 135-byte string literal not displayed */
	Distinct   *int64           `json:"distinct,omitempty" doc:"Distinct non-empty values of the distinct dimension. Present only with distinct set."`
}

SummaryPrevious is one summary row's numbers over the previous window, with the same meaning as the SummaryRow fields of the same name.

type SummaryQuery

type SummaryQuery struct {
	EventQuery

	// GroupBy is the dimension to group on. Valid values:
	// "relay_key_hash", "policy_id", "pool_id", "account_id", "lane_account_id", "via_account_id", "model_id", "host_id",
	// "host_key_id", "source", "finish_reason", "error_kind", "refusal",
	// "model", "host", "policy", "provider", "project", "team",
	// "principal", "relay_key" (event-time slugs), "project_id", "team_id",
	// "principal_id", "credential_id",
	// or "tags.<key>" (dynamic, groups on a caller tag's value).
	// GroupByNone → one row over the whole filtered slice, Group {}.
	// Empty → "source".
	GroupBy string

	// Distinct, when set, is a ValidDistinct dimension whose distinct non-empty values each row counts in SummaryRow.Distinct.
	Distinct string
}

SummaryQuery is EventQuery + group dimension. The filter fields are embedded so reader implementations can share filter logic.

type SummaryResult

type SummaryResult struct {
	Rows []SummaryRow `json:"rows" doc:"One row per group, by request count descending."`
	// Labels maps a group value to the latest non-empty event-time slug beside it when GroupBy is an id dimension (see LabelColumn); flat because the ids are UUIDs or hashes. Nil for any other grouping.
	Labels map[string]string `` /* 130-byte string literal not displayed */
	From   time.Time         `json:"from"             doc:"Start of the window."`
	To     time.Time         `json:"to"               doc:"End of the window."`
	// PreviousFrom / PreviousTo bound the window rows' Previous covers: the one the caller gave, or the requested window's length ending where it starts. PreviousTo is exclusive. Zero unless SummaryWithPrevious built the result.
	PreviousFrom time.Time `json:"previous_from,omitzero" doc:"Start of the window rows' previous covers; with a comparison only."`
	PreviousTo   time.Time `json:"previous_to,omitzero"   doc:"End (exclusive) of the window rows' previous covers; with a comparison only."`
}

SummaryResult wraps the rows with the resolved time range so the caller can render "events from X to Y" without re-deriving from the query.

func Summarize

func Summarize(events []Event, groupBy string) (SummaryResult, error)

Summarize groups the (already-filtered) events by groupBy and builds per-group totals + latency percentiles, sorted by request count desc. LogOnly events (pre-upstream rejections) are skipped — they belong to the logs view, not usage stats — except relay refusals when grouping by refusal. Returns an error for an unknown groupBy dimension.

func SummarizeWithDistinct added in v0.11.1

func SummarizeWithDistinct(events []Event, groupBy, distinct string, refusals bool) (SummaryResult, error)

SummarizeWithDistinct is Summarize plus SummaryRow.Distinct over the distinct dimension (a ValidDistinct entry; "" for none). refusals counts relay's log-only refusals too (CountsRefused).

func SummaryWithPrecedingWindow added in v0.11.1

func SummaryWithPrecedingWindow(ctx context.Context, r Reader, q SummaryQuery) (SummaryResult, error)

SummaryWithPrecedingWindow is SummaryWithPrevious over the window of equal length right before q's. q's window is resolved once and both queries use it, so a relative Since cannot drift between them.

func SummaryWithPrevious added in v0.11.1

func SummaryWithPrevious(ctx context.Context, r Reader, q SummaryQuery, prevFrom, prevTo time.Time) (SummaryResult, error)

SummaryWithPrevious runs q, and q's filters over [prevFrom, prevTo) concurrently, and attaches each current row's previous numbers by group. The previous window may have any length and may overlap q's: the caller picks it.

type SummaryRow

type SummaryRow struct {
	Group      map[string]string `json:"group"       doc:"The group's dimension values, keyed by dimension; empty for group_by=none."`
	Requests   int64             `json:"requests"    doc:"Requests in the group."`
	ErrorCount int64             `json:"error_count" doc:"Requests with status 400 or above; equals errors_4xx + errors_5xx."`
	// ErrorCount counts status >= 400 and always equals Errors4xx + Errors5xx: every status >= 500 (600+ included) lands in Errors5xx. Throttled counts status 429 and is a subset of Errors4xx.
	Errors4xx  int64            `json:"errors_4xx"  doc:"Requests with a 4xx status."`
	Errors5xx  int64            `json:"errors_5xx"  doc:"Requests with a status of 500 or above."`
	Throttled  int64            `json:"throttled"   doc:"Requests answered 429; part of errors_4xx."`
	Tokens     map[string]int64 `json:"tokens"      doc:"Token sums by kind."`
	DurationMs DurationStats    `json:"duration_ms" doc:"Request duration statistics in milliseconds."`
	// TTFTMs aggregates upstream time-to-first-byte (ms, derived from
	// Upstream.ResponseStart) over the subset of events that carry upstream
	// timing. Nil when no event in the group has it — a pointer so "no
	// samples" is distinguishable from "all-zero latency".
	TTFTMs    *DurationStats `` /* 134-byte string literal not displayed */
	FirstSeen time.Time      `json:"first_seen"        doc:"Earliest request in the group."`
	LastSeen  time.Time      `json:"last_seen"         doc:"Latest request in the group."`
	// CostNanos sums Event.CostNanos over the group's priced events
	// (nano-USD). Unpriced counts the events that carried no cost stamp —
	// reported instead of folding them into the sum as silent zeros, so a
	// cost total always says how complete it is.
	CostNanos int64 `json:"cost_nanos" doc:"Cost of the priced requests, in nano-USD."`
	Unpriced  int64 `json:"unpriced"   doc:"Requests with no cost, left out of cost_nanos."`
	// Previous is the same group over the previous window, set only by SummaryWithPrevious. Nil when the group had no traffic there; a group seen only in the previous window has no row at all.
	Previous *SummaryPrevious `` /* 139-byte string literal not displayed */

	Distinct *int64 `` /* 181-byte string literal not displayed */
}

SummaryRow is one grouped aggregate. The Group map carries the grouping dimension(s) keyed by their column name — single-key today, extensible to multi-key grouping later without changing the type.

type TimeSeriesPoint

type TimeSeriesPoint struct {
	Bucket     time.Time `json:"bucket"      doc:"Start of the bucket."`
	Requests   int64     `json:"requests"    doc:"Requests in the bucket."`
	ErrorCount int64     `json:"error_count" doc:"Requests with status 400 or above; equals errors_4xx + errors_5xx."`
	// Errors4xx / Errors5xx / Throttled — same invariant as SummaryRow: ErrorCount = Errors4xx + Errors5xx, Throttled (429) within Errors4xx.
	Errors4xx  int64            `json:"errors_4xx"  doc:"Requests with a 4xx status."`
	Errors5xx  int64            `json:"errors_5xx"  doc:"Requests with a status of 500 or above."`
	Throttled  int64            `json:"throttled"   doc:"Requests answered 429; part of errors_4xx."`
	Tokens     map[string]int64 `json:"tokens"      doc:"Token sums by kind."`
	DurationMs DurationStats    `json:"duration_ms" doc:"Request duration statistics in milliseconds."`
	// TTFTMs — see SummaryRow.TTFTMs; nil when no event in the bucket
	// carries upstream timing.
	TTFTMs *DurationStats `` /* 134-byte string literal not displayed */
	// CostNanos / Unpriced — see SummaryRow.
	CostNanos int64 `json:"cost_nanos" doc:"Cost of the priced requests, in nano-USD."`
	Unpriced  int64 `json:"unpriced"   doc:"Requests with no cost, left out of cost_nanos."`

	Distinct *int64 `` /* 243-byte string literal not displayed */
}

TimeSeriesPoint is one time bucket's aggregates. Bucket is the bucket's start instant (UTC, epoch-aligned). Empty buckets are omitted — the frontend zero-fills gaps against the resolved From/To range.

type TimeSeriesQuery

type TimeSeriesQuery struct {
	EventQuery

	// Interval is the bucket width. Must be > 0.
	Interval time.Duration

	// GroupBy splits the result into one series per dimension value. Empty means a single series with a nil Group; GroupByNone means the same single series with Group {}. Otherwise IsValidGroupBy applies.
	GroupBy string

	// Distinct — see SummaryQuery.Distinct; counted per point in TimeSeriesPoint.Distinct.
	Distinct string
}

TimeSeriesQuery is EventQuery + a bucket width + optional group dimension. Interval is required (zero is rejected by readers). GroupBy is optional: empty yields a single series, a valid dimension yields one series per distinct value.

type TimeSeriesResult

type TimeSeriesResult struct {
	Rows []TimeSeriesRow `json:"rows" doc:"One series per group, or a single series without group_by."`
	// Labels — see SummaryResult.Labels; the slug is the latest across the whole window, not per bucket.
	Labels   map[string]string `json:"labels,omitempty" doc:"For an id group_by: each series value's latest slug across the window."`
	Interval string            `json:"interval"         doc:"Bucket width, as requested."`
	From     time.Time         `json:"from"             doc:"Start of the window."`
	To       time.Time         `json:"to"               doc:"End of the window."`
}

TimeSeriesResult wraps the series with the resolved interval (echoed as a string, e.g. "1h") and time range so the caller can zero-fill and label the axis without re-deriving from the query.

func Bucketize

func Bucketize(events []Event, interval time.Duration, groupBy string) (TimeSeriesResult, error)

Bucketize groups the (already-filtered) events into time buckets of width interval, optionally split into one series per groupBy dimension. Buckets align to the Unix epoch (bucketStart = floor(unix/intervalSec)); empty buckets are omitted. Points within a series are ordered oldest-first; series (rows) are ordered by total request count desc. Returns an error for a non-positive interval or unknown groupBy.

func BucketizeWithDistinct added in v0.11.1

func BucketizeWithDistinct(events []Event, interval time.Duration, groupBy, distinct string, refusals bool) (TimeSeriesResult, error)

BucketizeWithDistinct is Bucketize plus TimeSeriesPoint.Distinct over the distinct dimension (a ValidDistinct entry; "" for none). refusals counts relay's log-only refusals too (CountsRefused).

type TimeSeriesRow

type TimeSeriesRow struct {
	Group  map[string]string `json:"group,omitzero" doc:"The series' dimension values; absent without group_by."`
	Points []TimeSeriesPoint `json:"points"         doc:"Non-empty buckets in time order; zero-fill the gaps."`
}

TimeSeriesRow is one series. Group is nil for the single-series case, {} for GroupByNone, and carries the grouping dimension keyed by column name otherwise; omitzero drops only the nil case, so none still emits "group": {}.

Directories

Path Synopsis
Package clickhouse provides a ClickHouse-backed implementation of usage.Sink, usage.Reader, and usage.Closer.
Package clickhouse provides a ClickHouse-backed implementation of usage.Sink, usage.Reader, and usage.Closer.
Package file is the JSONL file backend for usage logging: a Sink that appends one event per line and a Reader that scans the same file.
Package file is the JSONL file backend for usage logging: a Sink that appends one event per line and a Reader that scans the same file.
Package postgres implements usage.Sink, usage.Reader, and usage.Closer backed by PostgreSQL.
Package postgres implements usage.Sink, usage.Reader, and usage.Closer backed by PostgreSQL.
Package usagetest is the conformance suite every usage.Reader backend runs: one fixed event fixture, one table of queries per Reader method, and the results every backend must return for them.
Package usagetest is the conformance suite every usage.Reader backend runs: one fixed event fixture, one table of queries per Reader method, and the results every backend must return for them.
Package valkey is a TTL-bounded usage Sink + Reader backed by pkg/kv.
Package valkey is a TTL-bounded usage Sink + Reader backed by pkg/kv.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL