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
- func CleanLabel(s string) string
- func ClientAddr(ctx context.Context) string
- func ClientFrom(ctx context.Context, fallback string) string
- func ClientKey(ctx context.Context) string
- func Fingerprint(token string) string
- func Label(keyID, userAgent string) string
- func Rotate(dir string, now time.Time, log ...*slog.Logger) error
- func ServiceCall(ctx context.Context) bool
- func TailFromDir(dir string, limit int) (tail []Call, counters []Counter)
- func TokensOf(bytes int64) int64
- func WithClient(ctx context.Context, client string) context.Context
- func WithClientAddr(ctx context.Context, addr string) context.Context
- func WithClientKey(ctx context.Context, fp string) context.Context
- func WithServiceCall(ctx context.Context) context.Context
- type Call
- type Counter
- type Hist
- type History
- type HistoryStats
- type Point
- type Query
- type Recorder
- func (r *Recorder) Record(client, server, tool string, d time.Duration, err error)
- func (r *Recorder) RecordThrottled(server, tool string)
- func (r *Recorder) SetClientLabel(label string)
- func (r *Recorder) SetHistory(h *History)
- func (r *Recorder) SetSchema(s Schema)
- func (r *Recorder) Snapshot() Snapshot
- func (r *Recorder) SnapshotRedacted() Snapshot
- type Result
- type Row
- type Schema
- type SetRow
- type Snapshot
- type Source
- type Totals
- type Triple
Constants ¶
const ( // RawDays — сколько суток хранится сырой журнал: сегодня плюс RawDays. RawDays = 7 // DayDays — сколько суток живёт суточная агрегация; старше — только месяц. DayDays = 30 )
const ( PeriodToday = "today" Period7d = "7d" Period30d = "30d" PeriodArchive = "archive" )
Периоды, которые принимает панель.
const AnonymousLabel = "(аноним)"
AnonymousLabel заменяет метку клиента в редакции для открытого набора.
const MaxCounters = 4096
MaxCounters — жёсткий потолок числа счётчиков. Пара (клиент, инструмент) создаётся по запросу, и без потолка память растёт от каждого нового User-Agent. Лишние пары падают в один счётчик OtherLabel.
const MaxLabelBytes = 64
MaxLabelBytes — потолок метки клиента и имени инструмента: и то и другое приходит снаружи (заголовок User-Agent, clientInfo из initialize, имя инструмента в invoke_command), поэтому длина не доверяется.
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.
const MaxMessageBytes = 512
MaxMessageBytes — потолок текста ошибки в кольце вызовов. Текст приходит от апстрима и может нести тело запроса (до 4 МиБ), а кольцо — 512 записей: без потолка один набор занимал бы гигабайты.
const OtherLabel = "(прочее)"
OtherLabel — метка счётчика, вбирающего пары сверх MaxCounters.
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.
const ServiceCallerPanel = "panel"
ServiceCallerPanel is the value the manager sends on its own set requests.
Variables ¶
This section is empty.
Functions ¶
func CleanLabel ¶
CleanLabel обрезает внешнюю метку до MaxLabelBytes, выбрасывает управляющие символы и чинит разрезанную на границе руну. Тот же вид получает подпись ключа в API: счётчик и /api/sets показывают одно и то же.
func ClientAddr ¶ added in v0.5.0
ClientAddr reports the address set by the transport; empty for stdio.
func ClientFrom ¶
ClientFrom reports the label set by the transport, or fallback.
func ClientKey ¶ added in v0.5.0
ClientKey reports the fingerprint set by the transport; empty for a request that carried no key (an open set, or stdio).
func Fingerprint ¶
Fingerprint — 6 hex от sha256 токена. По нему ключ узнаётся в метке клиента, а сам токен в статистику и в конфиг набора не попадает.
func Label ¶
Label builds the HTTP client label: "key:<id>" plus the User-Agent product token, so two harnesses sharing one key stay distinguishable.
func Rotate ¶
Rotate применяет ретенцию на момент now и идемпотентен: законченные сутки получают day-файл из сырого журнала, дни старше DayDays уходят в месяц, сырой журнал старше RawDays удаляется. log необязателен: битый day-файл пропускается с предупреждением, а не останавливает всю уборку.
func ServiceCall ¶ added in v0.6.0
ServiceCall reports whether the transport marked this request as the panel's.
func TailFromDir ¶ added in v0.6.0
TailFromDir читает сырой журнал каталога и отдаёт хвост вызовов и счётчики по тройкам — для панели, когда процесс набора остановлен.
Окно — сегодня и RawDays-1 предыдущих суток, ровно как period=7d у /api/stats. Строки идут по убыванию времени и не длиннее limit; счётчики — агрегат по всему окну, процентили точные, как у запроса за 7 суток. Каталога нет — пустые срезы: недоступное чтение не ошибка, а битая строка журнала пропускается так же, как при свёртке.
shortcut: читает всё окно ради 512 строк, резать по дням от новых к старым, если панель начнёт греться.
func TokensOf ¶
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 ¶
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
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
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.
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.
type History ¶
type History struct {
// contains filtered or unexported fields
}
History пишет историю в один каталог. Одна горутина пишет и раз в сутки применяет ретенцию; вызывающие только кладут строку в канал.
func OpenHistory ¶
OpenHistory создаёт каталог истории и запускает писателя. Ротация идёт в его горутине: набор мог не работать сутки и дольше, но старт из-за уборки ждать не должен.
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 ¶
NewRecorder makes a recorder for one set. tailCap bounds the recent-call ring (0 means 512).
func (*Recorder) Record ¶
Record accounts one finished invocation. Метки приходят от клиента, поэтому сначала чистятся, а пары сверх потолка складываются в OtherLabel.
func (*Recorder) RecordThrottled ¶ added in v0.5.0
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 ¶
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 ¶
SetHistory mirrors every recorded call to the on-disk history.
func (*Recorder) SetSchema ¶
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 ¶
Snapshot copies the state. Counters are sorted by client, server, then tool, and carry their percentiles.
func (*Recorder) SnapshotRedacted ¶
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 ¶
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 ¶
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.