usage

package
v0.11.5 Latest Latest
Warning

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

Go to latest
Published: Oct 18, 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",
	"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",
	"model_id",
	"host_id",
	"host_key_id",
	"source",
	"finish_reason",
	"error_kind",
	"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 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 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"`
	P50 int64 `json:"p50"`
	P95 int64 `json:"p95"`
	P99 int64 `json:"p99"`
	Max int64 `json:"max"`
}

DurationStats holds latency aggregates in milliseconds.

type Event

type Event struct {
	// Identity / trace
	RequestID string    `json:"request_id"`
	Source    string    `json:"source"` // "pipeline" | "proxy" | "ws" | "batch" | "count" | "otlp"
	Timestamp time.Time `json:"ts"`

	// Outcome
	Status       int    `json:"status"`
	DurationMs   int64  `json:"duration_ms"` // total: start → response closed
	Streamed     bool   `json:"streamed,omitempty"`
	FinishReason string `json:"finish_reason,omitempty"` // "stop"|"length"|"tool_calls"|"content_filter"|"refusal"|"other"
	Attempts     int    `json:"attempts,omitempty"`      // upstream tries (pipeline failover); 0 = not tracked
	ErrorKind    string `json:"error_kind,omitempty"`
	ErrorMessage string `json:"error_message,omitempty"`

	// 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"`

	// 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"`

	// 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"`
	PolicyID       string `json:"policy_id,omitempty"`
	ModelID        string `json:"model_id,omitempty"`
	RequestedModel string `json:"requested_model,omitempty"` // model string as the caller sent it
	HostID         string `json:"host_id,omitempty"`
	// 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 `json:"host_key_id,omitempty"`

	// 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"`
	Project        string `json:"project,omitempty"`
	TeamID         string `json:"team_id,omitempty"`
	Team           string `json:"team,omitempty"`
	PrincipalKind  string `json:"principal_kind,omitempty"`
	PrincipalID    string `json:"principal_id,omitempty"`
	Principal      string `json:"principal,omitempty"`
	CredentialKind string `json:"credential_kind,omitempty"`
	CredentialID   string `json:"credential_id,omitempty"`

	// Token usage as reported by the upstream. Empty on error or when
	// the adapter could not extract.
	Tokens sdkusage.Tokens `json:"tokens,omitempty"`

	// Free-form per-runner tags (client_ip for anonymous proxy, etc.)
	Extras map[string]string `json:"extras,omitempty"`

	// 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"`

	// 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"`
	Host   string `json:"host,omitempty"`
	Policy string `json:"policy,omitempty"`

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

	// 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"`

	// 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           `json:"cost_nanos,omitempty"`
	CostBreakdown map[string]int64 `json:"cost_breakdown,omitempty"`
	Pricing       string           `json:"pricing,omitempty"`
}

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 app-side (app/usagelog + app/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) 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: status 0 with an ErrorKind set (routing denials, auth/proxy gating, key-pool exhaustion). 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
	ProjectID    []string
	TeamID       []string
	PrincipalID  []string
	ModelID      []string
	HostID       []string
	Source       []string // "pipeline" | "proxy" | "ws" | "batch" | "count" | "otlp"
	FinishReason []string
	ErrorKind    []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"`
	Label    string `json:"label,omitempty"`
	Requests int64  `json:"requests"`
}

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) ([]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.

type FacetsResult added in v0.11.1

type FacetsResult struct {
	Facets map[string][]FacetValue `json:"facets"`
	From   time.Time               `json:"from"`
	To     time.Time               `json:"to"`
}

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"`
	ErrorCount int64            `json:"error_count"`
	Errors4xx  int64            `json:"errors_4xx"`
	Errors5xx  int64            `json:"errors_5xx"`
	Throttled  int64            `json:"throttled"`
	Tokens     map[string]int64 `json:"tokens"`
	CostNanos  int64            `json:"cost_nanos"`
	Unpriced   int64            `json:"unpriced"`
	DurationMs DurationStats    `json:"duration_ms"`
	TTFTMs     *DurationStats   `json:"ttft_ms,omitempty"`
	Distinct   *int64           `json:"distinct,omitempty"`
}

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", "model_id", "host_id",
	// "host_key_id", "source", "finish_reason", "error_kind",
	// "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"`
	// 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 `json:"labels,omitempty"`
	From   time.Time         `json:"from"`
	To     time.Time         `json:"to"`
	// 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"`
	PreviousTo   time.Time `json:"previous_to,omitzero"`
}

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. Returns an error for an unknown groupBy dimension.

func SummarizeWithDistinct added in v0.11.1

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

SummarizeWithDistinct is Summarize plus SummaryRow.Distinct over the distinct dimension (a ValidDistinct entry; "" for none).

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"`
	Requests   int64             `json:"requests"`
	ErrorCount int64             `json:"error_count"`
	// 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"`
	Errors5xx  int64            `json:"errors_5xx"`
	Throttled  int64            `json:"throttled"`
	Tokens     map[string]int64 `json:"tokens"`
	DurationMs DurationStats    `json:"duration_ms"`
	// 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 `json:"ttft_ms,omitempty"`
	FirstSeen time.Time      `json:"first_seen"`
	LastSeen  time.Time      `json:"last_seen"`
	// 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"`
	Unpriced  int64 `json:"unpriced"`
	// 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 `json:"previous,omitempty"`

	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"`
	Requests   int64     `json:"requests"`
	ErrorCount int64     `json:"error_count"`
	// Errors4xx / Errors5xx / Throttled — same invariant as SummaryRow: ErrorCount = Errors4xx + Errors5xx, Throttled (429) within Errors4xx.
	Errors4xx  int64            `json:"errors_4xx"`
	Errors5xx  int64            `json:"errors_5xx"`
	Throttled  int64            `json:"throttled"`
	Tokens     map[string]int64 `json:"tokens"`
	DurationMs DurationStats    `json:"duration_ms"`
	// TTFTMs — see SummaryRow.TTFTMs; nil when no event in the bucket
	// carries upstream timing.
	TTFTMs *DurationStats `json:"ttft_ms,omitempty"`
	// CostNanos / Unpriced — see SummaryRow.
	CostNanos int64 `json:"cost_nanos"`
	Unpriced  int64 `json:"unpriced"`

	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"`
	// Labels — see SummaryResult.Labels; the slug is the latest across the whole window, not per bucket.
	Labels   map[string]string `json:"labels,omitempty"`
	Interval string            `json:"interval"`
	From     time.Time         `json:"from"`
	To       time.Time         `json:"to"`
}

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) (TimeSeriesResult, error)

BucketizeWithDistinct is Bucketize plus TimeSeriesPoint.Distinct over the distinct dimension (a ValidDistinct entry; "" for none).

type TimeSeriesRow

type TimeSeriesRow struct {
	Group  map[string]string `json:"group,omitzero"`
	Points []TimeSeriesPoint `json:"points"`
}

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