stats

package
v0.6.7 Latest Latest
Warning

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

Go to latest
Published: Nov 18, 2026 License: MIT Imports: 18 Imported by: 0 modules, 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 stats collects per-client call counters for the panel.

A "client" is whoever asked: a harness in stdio mode ("opencode", "claude-code", …) or a caller of the HTTP endpoint (key id plus the User-Agent product token). Counters live in memory; the panel reads them and the ring of recent calls for the tail of the dashboard.

Токены не учитываются: у MCP-ответа нет стандартного поля usage, а формы _meta у серверов разные, поэтому счётчик намеренно без токенов.

Index

Constants

View Source
const (
	// RawDays — сколько суток хранится сырой журнал: сегодня плюс RawDays.
	RawDays = 7
	// DayDays — сколько суток живёт суточная агрегация; старше — только месяц.
	DayDays = 30
)
View Source
const (
	PeriodToday   = "today"
	Period7d      = "7d"
	Period30d     = "30d"
	PeriodArchive = "archive"
)

Периоды, которые принимает панель.

View Source
const AnonymousLabel = "(аноним)"

AnonymousLabel заменяет метку клиента в редакции для открытого набора.

View Source
const MaxCounters = 4096

MaxCounters — жёсткий потолок числа счётчиков. Пара (клиент, инструмент) создаётся по запросу, и без потолка память растёт от каждого нового User-Agent. Лишние пары падают в один счётчик OtherLabel.

View Source
const MaxLabelBytes = 64

MaxLabelBytes — потолок метки клиента и имени инструмента: и то и другое приходит снаружи (заголовок User-Agent, clientInfo из initialize, имя инструмента в invoke_command), поэтому длина не доверяется.

View Source
const MaxLatencySamples = 256

MaxLatencySamples bounds the per-(client, tool) latency reservoir used for percentiles. A call beyond the bound overwrites a slot round-robin, so the percentiles describe recent traffic rather than all of it.

View Source
const MaxMessageBytes = 512

MaxMessageBytes — потолок текста ошибки в кольце вызовов. Текст приходит от апстрима и может нести тело запроса (до 4 МиБ), а кольцо — 512 записей: без потолка один набор занимал бы гигабайты.

View Source
const OtherLabel = "(прочее)"

OtherLabel — метка счётчика, вбирающего пары сверх MaxCounters.

View Source
const ServiceCallHeader = "X-MCPRig-Caller"

ServiceCallHeader marks a request the panel makes to its own set (health probe, catalog load): such a call is counted nowhere — no counters, no tail, no history.

View Source
const ServiceCallerPanel = "panel"

ServiceCallerPanel is the value the manager sends on its own set requests.

Variables

This section is empty.

Functions

func CleanLabel

func CleanLabel(s string) string

CleanLabel обрезает внешнюю метку до MaxLabelBytes, выбрасывает управляющие символы и чинит разрезанную на границе руну. Тот же вид получает подпись ключа в API: счётчик и /api/sets показывают одно и то же.

func ClientAddr added in v0.5.0

func ClientAddr(ctx context.Context) string

ClientAddr reports the address set by the transport; empty for stdio.

func ClientFrom

func ClientFrom(ctx context.Context, fallback string) string

ClientFrom reports the label set by the transport, or fallback.

func ClientKey added in v0.5.0

func ClientKey(ctx context.Context) string

ClientKey reports the fingerprint set by the transport; empty for a request that carried no key (an open set, or stdio).

func Fingerprint

func Fingerprint(token string) string

Fingerprint — 6 hex от sha256 токена. По нему ключ узнаётся в метке клиента, а сам токен в статистику и в конфиг набора не попадает.

func Label

func Label(keyID, userAgent string) string

Label builds the HTTP client label: "key:<id>" plus the User-Agent product token, so two harnesses sharing one key stay distinguishable.

func Rotate

func Rotate(dir string, now time.Time, log ...*slog.Logger) error

Rotate применяет ретенцию на момент now и идемпотентен: законченные сутки получают day-файл из сырого журнала, дни старше DayDays уходят в месяц, сырой журнал старше RawDays удаляется. log необязателен: битый day-файл пропускается с предупреждением, а не останавливает всю уборку.

func ServiceCall added in v0.6.0

func ServiceCall(ctx context.Context) bool

ServiceCall reports whether the transport marked this request as the panel's.

func TailFromDir added in v0.6.0

func TailFromDir(dir string, limit int) (tail []Call, counters []Counter)

TailFromDir читает сырой журнал каталога и отдаёт хвост вызовов и счётчики по тройкам — для панели, когда процесс набора остановлен.

Окно — сегодня и RawDays-1 предыдущих суток, ровно как period=7d у /api/stats. Строки идут по убыванию времени и не длиннее limit; счётчики — агрегат по всему окну, процентили точные, как у запроса за 7 суток. Каталога нет — пустые срезы: недоступное чтение не ошибка, а битая строка журнала пропускается так же, как при свёртке.

shortcut: читает всё окно ради 512 строк, резать по дням от новых к старым, если панель начнёт греться.

func TokensOf

func TokensOf(bytes int64) int64

TokensOf estimates the context cost of an answer at four bytes per token, rounded up: the panel's rough yardstick, not a tokenizer.

func WithClient

func WithClient(ctx context.Context, client string) context.Context

WithClient labels the call in flight with the harness behind it: a key id plus User-Agent product token for HTTP callers. The request's _meta client info wins over this label when it is present. The recorder falls back to "unknown".

func WithClientAddr added in v0.5.0

func WithClientAddr(ctx context.Context, addr string) context.Context

WithClientAddr carries the caller's address, port stripped, for an open set: with no key there is nothing else to bucket a rate limit by. Behind a proxy this is the proxy's address — a coarse divider, not a defence.

func WithClientKey added in v0.5.0

func WithClientKey(ctx context.Context, fp string) context.Context

WithClientKey carries the access key's fingerprint down the request. It is separate from the display label on purpose: the label can be a note the owner gave the key or a clientInfo the caller sends, and neither identifies a key. The rate limiter buckets by this value, so a caller cannot mint quotas by changing what it calls itself.

func WithServiceCall added in v0.6.0

func WithServiceCall(ctx context.Context) context.Context

WithServiceCall marks the request as the panel's own.

shortcut: держатель ключа набора может послать этот заголовок и скрыть свои вызовы из статистики; подписанный маркер, если это станет важно.

Types

type Call

type Call struct {
	Time    time.Time `json:"time"`
	Client  string    `json:"client"`
	Set     string    `json:"set,omitempty"`
	Server  string    `json:"server"`
	Tool    string    `json:"tool"`
	Millis  int64     `json:"ms"`
	Failed  bool      `json:"failed"`
	Message string    `json:"error,omitempty"`
}

Call is one finished invocation, kept for the dashboard's tail.

type Counter

type Counter struct {
	Client   string `json:"client"`
	Server   string `json:"server"`
	Tool     string `json:"tool"`
	Calls    int64  `json:"calls"`
	Failures int64  `json:"failures"`
	TotalMs  int64  `json:"total_ms"`
	// Перцентили заполняются при сборке Snapshot: в Record это стоило бы
	// сортировки резерва на каждый вызов.
	P50Ms int64 `json:"p50ms"`
	P95Ms int64 `json:"p95ms"`
	// contains filtered or unexported fields
}

Counter is the aggregate for one (client, server, tool) triple.

func (Counter) P50

func (c Counter) P50() int64

P50 and P95 are computed from the latency reservoir; 0 when there is none.

func (Counter) P95

func (c Counter) P95() int64

type Hist

type Hist [len(histBounds) + 1]int64

Hist — гистограмма латентности в фиксированных корзинах.

type History

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

History пишет историю в один каталог. Одна горутина пишет и раз в сутки применяет ретенцию; вызывающие только кладут строку в канал.

func OpenHistory

func OpenHistory(dir string, log *slog.Logger) (*History, error)

OpenHistory создаёт каталог истории и запускает писателя. Ротация идёт в его горутине: набор мог не работать сутки и дольше, но старт из-за уборки ждать не должен.

func (*History) Close

func (h *History) Close() error

Close drains the queue and stops the writer.

func (*History) Dropped

func (h *History) Dropped() int64

Dropped reports lines lost to a full queue since start.

func (*History) Record

func (h *History) Record(client, server, tool string, ms int64, err error)

Record queues one finished call. A full queue drops the line and counts it: the tool call never waits for the disk. Текст ошибки обрезается до maxErrText.

type HistoryStats

type HistoryStats struct {
	Dropped int64 `json:"dropped"`
}

HistoryStats is the disk-history health the panel shows as stats.dropped.

type Point

type Point struct {
	T        time.Time `json:"t"`
	Calls    int64     `json:"calls"`
	Failures int64     `json:"failures"`
	P50Ms    int64     `json:"p50ms"`
	P95Ms    int64     `json:"p95ms"`
}

Point is one point of the series.

type Query

type Query struct {
	Period string
	// Bucket — шаг графика. hour|day; где данные грубее, шаг задаёт источник.
	Bucket string
	Server string
	Tool   string
	Client string
}

Query is one slice of the history: period, series step and filters.

type Recorder

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

Recorder is safe for concurrent use.

func NewRecorder

func NewRecorder(set string, tailCap int) *Recorder

NewRecorder makes a recorder for one set. tailCap bounds the recent-call ring (0 means 512).

func (*Recorder) Record

func (r *Recorder) Record(client, server, tool string, d time.Duration, err error)

Record accounts one finished invocation. Метки приходят от клиента, поэтому сначала чистятся, а пары сверх потолка складываются в OtherLabel.

func (*Recorder) RecordThrottled added in v0.5.0

func (r *Recorder) RecordThrottled(server, tool string)

RecordThrottled accounts one call refused by the set's rate limit. The tool counter stops growing at MaxCounters: the name comes from the caller.

func (*Recorder) SetClientLabel

func (r *Recorder) SetClientLabel(label string)

SetClientLabel fixes the client name for a process that has exactly one client: in stdio the transport is the boundary, so the history line says "stdio" rather than whatever the harness calls itself.

func (*Recorder) SetHistory

func (r *Recorder) SetHistory(h *History)

SetHistory mirrors every recorded call to the on-disk history.

func (*Recorder) SetSchema

func (r *Recorder) SetSchema(s Schema)

SetSchema replaces the list_commands weight the panel shows for this set. The proxy pushes it whenever a tool cache changes, so /stats stays a plain snapshot and no extra downstream call is made.

func (*Recorder) Snapshot

func (r *Recorder) Snapshot() Snapshot

Snapshot copies the state. Counters are sorted by client, server, then tool, and carry their percentiles.

func (*Recorder) SnapshotRedacted

func (r *Recorder) SnapshotRedacted() Snapshot

SnapshotRedacted — снимок для анонимного читателя открытого набора: тексты ошибок апстрима и метки клиентов не выходят наружу, остальное (счётчики, латентности, хвост) остаётся.

type Result

type Result struct {
	Period string    `json:"period"`
	From   time.Time `json:"from"`
	To     time.Time `json:"to"`
	// Approximate: процентили посчитаны по гистограмме (30d и архив), а не по
	// точным значениям сырого журнала.
	Approximate bool    `json:"approximate"`
	Totals      Totals  `json:"totals"`
	Series      []Point `json:"series"`
	Tools       []Row   `json:"tools"`
	Servers     []Row   `json:"servers"`
	Clients     []Row   `json:"clients"`
	// BySet — разрез по наборам; только у ответа «все наборы», и только по
	// наборам, где в этом периоде были вызовы.
	BySet       []SetRow `json:"bySet,omitempty"`
	Unreachable []string `json:"unreachable,omitempty"`
}

Result is the panel answer for one period.

func QuerySets

func QuerySets(sources []Source, q Query, now time.Time) Result

QuerySets answers one period from the given sources — one directory per set, so set=all is just every source. A missing directory contributes nothing, a broken journal line is skipped. With a set attached to each source the answer carries the bySet breakdown, counted in the same pass as the totals.

type Row

type Row struct {
	Client   string `json:"client,omitempty"`
	Server   string `json:"server,omitempty"`
	Tool     string `json:"tool,omitempty"`
	Calls    int64  `json:"calls"`
	Failures int64  `json:"failures"`
	P50Ms    int64  `json:"p50ms"`
	P95Ms    int64  `json:"p95ms"`
}

Row is one line of the tools, servers or clients breakdown.

type Schema

type Schema struct {
	Bytes  int64 `json:"schemaBytes"`
	Tokens int64 `json:"schemaTokens"`
	Tools  int   `json:"tools"`
}

Schema is what list_commands costs the caller's context: the JSON of the whole-set answer in bytes, and the same in tokens at four bytes per token.

type SetRow

type SetRow struct {
	Set      string `json:"set"`
	Calls    int64  `json:"calls"`
	Failures int64  `json:"failures"`
	TotalMs  int64  `json:"totalMs"`
}

SetRow is one set's share of an aggregate answer: the panel's set table needs the counters per row, and one query serves both it and the totals.

type Snapshot

type Snapshot struct {
	Set      string    `json:"set,omitempty"`
	Counters []Counter `json:"counters"`
	Tail     []Call    `json:"tail"`
	// Throttled — сколько вызовов отверг лимит частоты, всего и по парам.
	Throttled      int64            `json:"throttled,omitempty"`
	ThrottledTools map[string]int64 `json:"throttledTools,omitempty"`
	// Schema — вес list_commands набора, если прокси уже снял его с кэша.
	Schema *Schema `json:"schema,omitempty"`
	// Stats — состояние истории на диске: сколько строк потерял полный канал.
	Stats *HistoryStats `json:"stats,omitempty"`
}

Snapshot is the panel view: counters with percentiles, newest tail first.

type Source

type Source struct {
	Set string
	Dir string
}

Source is one set's history directory. The set name labels the answer's bySet rows, so an aggregate answer says where the calls came from.

type Totals

type Totals struct {
	Calls    int64 `json:"calls"`
	Failures int64 `json:"failures"`
	P50Ms    int64 `json:"p50ms"`
	P95Ms    int64 `json:"p95ms"`
}

Totals is the invariant part of every answer.

type Triple

type Triple struct {
	Client   string `json:"client"`
	Server   string `json:"server"`
	Tool     string `json:"tool"`
	Calls    int64  `json:"calls"`
	Failures int64  `json:"failures"`
	TotalMs  int64  `json:"totalMs"`
	Hist     Hist   `json:"hist"`
	LastMs   int64  `json:"lastMs"`
}

Triple is one (client, server, tool) aggregate in a day or month file.

Jump to

Keyboard shortcuts

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