Files
magpie/internal/gateway/usage_ingest.go
T
yetone d4c2512d2d usage: apps report their own calls with POST /v1/magpie/usage/requests, backfill included (#1874)
What changed
- POST /v1/magpie/usage/requests (internal/gateway/usage_ingest.go) takes
  one record or an array, in usage.jsonl's shape:
  - the post may carry up to 5000 records and 32 MiB;
  - t, agent, provider, model and rid are required.
  Each field is checked: unknown fields, quoted numbers, negative or absurd
  counts, a status outside 100-599, a cost over 10000 USD, and a t more
  than an hour ahead or before 2000-01-01T00:00:00Z. Any fault refuses the
  whole post with a 400 that names error.index and error.param, and nothing
  is written. A past t is otherwise taken as given, so history can be
  backfilled. The reply gives accepted and skipped counts and each
  record's index, rid and status.
- Access: lanGuard's rule (this machine, or another with a key while
  shared, behind the Host check). A browser page also needs a key, since
  corsGuard lets localhost pages and Origin null through. A held key is
  refused.
- usage.IngestReported writes under usage.mu to the same file as
  usage.Append. Rows carry source "reported" and no caller key. A rid
  already reported is skipped, as is one repeated in the post. The set of
  reported rids is read back from the log: one scan after a restart (lines
  without the reported mark aren't parsed), then only what was appended.
- Pricing: a record with cost keeps it (Record.OwnCost, the rowOwnCost
  flag; packed flags widened to uint16). Otherwise it is priced at
  magpie's prices.
- Display:
  - SourceReported is a source of its own: RequestPage.Reported,
    ?via=reported, and Ledger now honours via.
  - The Requests tab gains a fourth cell "reported by apps", shown once
    there are some, and a "Reported" badge (en, zh, zh-TW, ja, de).
- Nothing live: Record.IsReported keeps reported rows out of:
  - a key's budget/spend limit (budget.counts);
  - window holds, and the log start that decides whether a window can be
    reckoned (logSnapshot.firstOwn);
  - gateway sessions and Vias;
  - Codex's sealed answers and remembered model.
  There is no OTel span, rate limit, rest or alert for them.
- Docs: gateway-sessions.md, reference.md (with a curl), integrating.md,
  site integrate.html (en, zh).

Why: the reporter's apps call vendors directly, and their usage (and
history) should show on the Usage page without becoming live traffic.

Run, in a worktree with sandbox HOME and a private GOCACHE
- gofmt -l: clean.
- go vet ./...: darwin, GOOS=linux -tags nogui, and GOOS=windows.
- go test internal/usage, usageapi, budget, gateway, gui: ok.
- -race -count=3 of the new usage/gateway tests: ok.
- GUI with playwright 1.62.0:
  - usage-ledger-reported.test.cjs, 26/26 in chromium and webkit (5
    languages, 1180 and 420 wide, light and dark);
  - usage-ledger*.test.cjs, ledger-*.test.cjs, usage-sum-whole,
    usage-unpriced-sum and i18n-keys: all pass.
- Timings with 200k reported rows (47 MB log, darwin):
  - 40 posts of 5000 took 0.40 s (worst batch 18 ms);
  - the first post after a restart took 0.45 s (rid rescan), a later one
    1.6 ms;
  - the cold index build took 2.1 s (as for gateway rows);
  - page all took 27 ms warm, page 30d 39 ms, all via=reported 0.53 s;
  - summary all took 215 ms, 30d 20 ms.

Broken by hand, each went red, then restored
- Go: dedupe against stored rids; the restart scan; CostAt ignoring own
  cost; the block pricer overwriting own cost; the Reported split;
  fromBrowser's key rule; skipping bad records instead of refusing; the
  max-records and body limits; the ingest lock (race); both locks;
  firstOwn -> first; the IsReported guards in windowHolds,
  buildGatewaySessions, buildVias, budget.counts and loggedAnswers.
- GUI: the fourth cell, the --vias column count and the badge class.

Not shown red on its own: the remote-no-key and evil.example refusals come
from lanGuard and corsGuard before the handler, so breaking only the
handler's own check stays green. The codex_memory guard is not tested
alone: a reported row has no Requested there anyway. Not tried: a real
client against a live gateway, Windows/Linux runs of the tests, the full
GUI suite.
2026-10-13 06:32:03 +08:00

347 lines
12 KiB
Go

package gateway
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"math"
"mime"
"net/http"
"slices"
"strings"
"time"
"unicode/utf8"
"github.com/yetone/magpie/internal/access"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/usage"
)
// POST /v1/magpie/usage/requests (#1874): a client that calls its vendor
// itself, not through magpie, tells magpie of its calls, so the Usage page
// counts them with the rest. It takes one record, or an array of them, in
// the shape usage.jsonl has, and writes each beside the gateway's own,
// marked source "reported": counted in the totals, and told apart, and
// filtered (?via=reported), on the page and over GET.
//
// A record's rid is required, and one already reported is skipped, after
// a restart too, since what was reported is read from the log itself. A
// record with no cost is priced at magpie's prices, as a gateway call is.
// A batch is all or nothing: one bad record answers 400, naming it and its
// field, and none is written.
//
// It writes into what this computer's usage says, so it is let in as
// GET /v1/magpie/usage is: this computer, or another with an enabled
// gateway key while magpie is shared. A request with a browser's marks
// needs an enabled gateway key even from this computer: corsGuard lets
// a page on localhost or 127.0.0.1 (any port) and an opaque origin
// through, and none of them should be able to write what the page counts.
const (
// ingestMaxBody is the most a post may carry: a full batch of
// ingestMaxRecords at a few hundred bytes each is a few MiB, so this
// leaves room for records that carry an err text too.
ingestMaxBody = 32 << 20
// ingestMaxRecords is the most records one post may carry: a few
// thousand, for a backfill of a client's history (#1874) sent in
// batches, each answered record by record.
ingestMaxRecords = 5000
// ingestMaxTokens is the most of any token count one call may say:
// more than any model's context, so a larger number is a mistake.
ingestMaxTokens = 100_000_000
// ingestMaxMillis is the longest a call may say it took: a day.
ingestMaxMillis = int64(24 * time.Hour / time.Millisecond)
// ingestMaxCost is the most one call may say it cost, in USD.
ingestMaxCost = 10_000.0
// ingestMaxText is the longest a name (agent, provider, model, rid…)
// may be.
ingestMaxText = 256
// ingestFuture is how far ahead of this computer's clock a call's
// time may be, for a client's clock that runs ahead.
ingestFuture = time.Hour
)
// ingestEarliest is the earliest a call may be dated. A past time is taken
// as given, so a client's history can be backfilled and lands on its own
// day; this bound only stops a zero or mistyped year.
var ingestEarliest = time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC)
// ingestFields are the fields a reported record may carry, of the ones
// usage.jsonl has: what a client can know of a call it made itself.
var ingestFields = []string{"t", "agent", "provider", "model", "in", "out", "cache_read", "cache_write", "cache_write_1h", "reasoning", "ms", "ttft_ms", "status", "rid", "cost", "effort", "session", "err"}
// ingestFault is what is wrong with one record of a post.
type ingestFault struct {
index int
field string
msg string
}
func (f *ingestFault) Error() string {
return fmt.Sprintf("record %d: %s: %s", f.index, f.field, f.msg)
}
func (s *Server) usageIngest(w http.ResponseWriter, r *http.Request) {
if !local(r) && !sharedWith(r) {
writeError(w, provider.Chat, http.StatusForbidden, usageRefused)
return
}
who := access.Caller(r.Context())
if fromBrowser(r) && who.KeyID == "" {
// lanGuard identified only a remote or managed key; a page on this
// computer with a key is looked up here
for _, k := range callerKeys(r) {
if id, ok := access.Authenticate(k); ok {
who = id
break
}
}
if who.KeyID == "" {
writeError(w, provider.Chat, http.StatusForbidden, "a browser page may report usage only with an enabled magpie gateway key (Authorization: Bearer <key>): a page has no say in what this computer's usage counts")
return
}
}
if heldKey(who) {
writeError(w, provider.Chat, http.StatusForbidden, "this gateway key is held to a budget, models or accounts, so it may not report usage")
return
}
if mt, _, err := mime.ParseMediaType(r.Header.Get("Content-Type")); err != nil || mt != "application/json" {
writeError(w, provider.Chat, http.StatusUnsupportedMediaType, "send the records as JSON, with Content-Type: application/json")
return
}
body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, ingestMaxBody))
if err != nil {
var tooBig *http.MaxBytesError
if errors.As(err, &tooBig) {
writeError(w, provider.Chat, http.StatusRequestEntityTooLarge, fmt.Sprintf("the body is over %d bytes: send at most %d records a post", ingestMaxBody, ingestMaxRecords))
return
}
writeError(w, provider.Chat, http.StatusBadRequest, "the body could not be read")
return
}
recs, fault := parseIngest(body, time.Now())
if fault != nil {
v := map[string]any{"message": fault.Error(), "type": "invalid_request_error", "param": fault.field}
if fault.index >= 0 {
v["index"] = fault.index
}
writeJSON(w, http.StatusBadRequest, map[string]any{"error": v})
return
}
took, err := usage.IngestReported(recs)
if err != nil {
writeError(w, provider.Chat, http.StatusInternalServerError, "the records could not be written: "+err.Error())
return
}
type result struct {
Index int `json:"index"`
RID string `json:"rid"`
Status string `json:"status"`
}
out := struct {
Accepted int `json:"accepted"`
Skipped int `json:"skipped"`
Records []result `json:"records"`
}{Records: make([]result, len(recs))}
for i, rec := range recs {
st := "skipped"
if took[i] {
st = "accepted"
out.Accepted++
} else {
out.Skipped++
}
out.Records[i] = result{i, rec.RequestID, st}
}
writeJSON(w, 200, out)
}
// parseIngest reads a post's records: one object, or an array of them.
// The first bad one is the answer, with its index (-1 for the body as a
// whole) and its field.
func parseIngest(body []byte, now time.Time) ([]usage.Record, *ingestFault) {
body = bytes.TrimSpace(body)
var raws []json.RawMessage
switch {
case len(body) > 0 && body[0] == '[':
if err := json.Unmarshal(body, &raws); err != nil {
return nil, &ingestFault{-1, "body", "not a JSON array of records: " + err.Error()}
}
if len(raws) == 0 {
return nil, &ingestFault{-1, "body", "the array has no records"}
}
if len(raws) > ingestMaxRecords {
return nil, &ingestFault{-1, "body", fmt.Sprintf("%d records: send at most %d a post", len(raws), ingestMaxRecords)}
}
case len(body) > 0 && body[0] == '{':
raws = []json.RawMessage{body}
default:
return nil, &ingestFault{-1, "body", "send a JSON record, or an array of them"}
}
out := make([]usage.Record, 0, len(raws))
for i, raw := range raws {
rec, fault := parseReported(i, raw, now)
if fault != nil {
return nil, fault
}
out = append(out, rec)
}
return out, nil
}
// parseReported reads one record, field by field, so what is wrong with it
// is said by the field's name.
func parseReported(i int, raw json.RawMessage, now time.Time) (usage.Record, *ingestFault) {
var rec usage.Record
var fields map[string]json.RawMessage
if err := json.Unmarshal(raw, &fields); err != nil || fields == nil {
return rec, &ingestFault{i, "record", "not a JSON object"}
}
keys := make([]string, 0, len(fields))
for k := range fields {
keys = append(keys, k)
}
slices.Sort(keys) // the same field is named for the same body every time
for _, k := range keys {
if !slices.Contains(ingestFields, k) {
return rec, &ingestFault{i, k, "not a field a reported record takes (" + strings.Join(ingestFields, ", ") + ")"}
}
}
text := func(k string, need bool) (string, *ingestFault) {
v, ok := fields[k]
if !ok || string(v) == "null" {
if need {
return "", &ingestFault{i, k, "required"}
}
return "", nil
}
var s string
if json.Unmarshal(v, &s) != nil {
return "", &ingestFault{i, k, "must be a string"}
}
s = strings.TrimSpace(s)
switch {
case need && s == "":
return "", &ingestFault{i, k, "required"}
case utf8.RuneCountInString(s) > ingestMaxText && k != "err":
return "", &ingestFault{i, k, fmt.Sprintf("longer than %d characters", ingestMaxText)}
case strings.ContainsFunc(s, func(r rune) bool { return r < 0x20 || r == 0x7f }) && k != "err":
return "", &ingestFault{i, k, "has a control character"}
}
return s, nil
}
whole := func(k string, max int64, need bool) (int64, *ingestFault) {
v, ok := fields[k]
if !ok || string(v) == "null" {
if need {
return 0, &ingestFault{i, k, "required"}
}
return 0, nil
}
var n json.Number
// a Number takes a quoted one too, which is a string here
if v[0] == '"' || json.Unmarshal(v, &n) != nil {
return 0, &ingestFault{i, k, "must be a number"}
}
x, err := n.Int64()
if err != nil {
return 0, &ingestFault{i, k, "must be a whole number"}
}
if x < 0 {
return 0, &ingestFault{i, k, "must not be negative"}
}
if x > max {
return 0, &ingestFault{i, k, fmt.Sprintf("over %d, more than one call can be", max)}
}
return x, nil
}
var f *ingestFault
if rec.RequestID, f = text("rid", true); f != nil {
return rec, f
}
if rec.Agent, f = text("agent", true); f != nil {
return rec, f
}
if rec.Provider, f = text("provider", true); f != nil {
return rec, f
}
if rec.Model, f = text("model", true); f != nil {
return rec, f
}
if rec.Effort, f = text("effort", false); f != nil {
return rec, f
}
if rec.Session, f = text("session", false); f != nil {
return rec, f
}
if rec.Error, f = text("err", false); f != nil {
return rec, f
}
if len(rec.Error) > 4096 {
rec.Error = strings.ToValidUTF8(rec.Error[:4096], "")
}
t, ok := fields["t"]
if !ok || string(t) == "null" {
return rec, &ingestFault{i, "t", "required"}
}
var ts string
if json.Unmarshal(t, &ts) != nil {
return rec, &ingestFault{i, "t", "must be an RFC 3339 time, as a string"}
}
when, err := time.Parse(time.RFC3339Nano, ts)
if err != nil {
return rec, &ingestFault{i, "t", "must be an RFC 3339 time (2026-10-13T08:00:00Z)"}
}
if when.After(now.Add(ingestFuture)) {
return rec, &ingestFault{i, "t", "is in the future"}
}
if when.Before(ingestEarliest) {
return rec, &ingestFault{i, "t", "is before 2000-01-01T00:00:00Z, the earliest a call may be dated"}
}
rec.Time = when
counts := []struct {
k string
to *int
}{{"in", &rec.Input}, {"out", &rec.Output}, {"cache_read", &rec.CacheRead}, {"cache_write", &rec.CacheWrite}, {"cache_write_1h", &rec.CacheWrite1h}, {"reasoning", &rec.Reasoning}}
for _, c := range counts {
n, f := whole(c.k, ingestMaxTokens, false)
if f != nil {
return rec, f
}
*c.to = int(n)
}
if rec.CacheWrite1h > rec.CacheWrite {
return rec, &ingestFault{i, "cache_write_1h", "more than cache_write, which counts it"}
}
if rec.Millis, f = whole("ms", ingestMaxMillis, false); f != nil {
return rec, f
}
if rec.TTFT, f = whole("ttft_ms", ingestMaxMillis, false); f != nil {
return rec, f
}
st, f := whole("status", 599, true)
if f != nil {
return rec, f
}
if st < 100 {
return rec, &ingestFault{i, "status", "must be an HTTP status, 100 to 599"}
}
rec.Status = int(st)
if v, ok := fields["cost"]; ok && string(v) != "null" {
var c float64
if json.Unmarshal(v, &c) != nil {
return rec, &ingestFault{i, "cost", "must be a number of USD"}
}
if math.IsNaN(c) || math.IsInf(c, 0) || c < 0 {
return rec, &ingestFault{i, "cost", "must not be negative"}
}
if c > ingestMaxCost {
return rec, &ingestFault{i, "cost", fmt.Sprintf("over %g USD, more than one call can cost", ingestMaxCost)}
}
rec.OwnCost = &c
}
return rec, nil
}