Files
magpie/internal/usage/observe.go
T
yetone 9916a94608 gateway, usage, plugins: OTel export is the first plugin on the gateway's observer point (P3)
P3 of docs/subsystems/plugin-runtime.md opens the gateway to plugins. The
observer point is first: it only reads, so it carries the least risk.
With plugins/otel off, the gateway exports nothing and does no observing
work. It keeps no reply whole and adds no request context.

- usage.Observer:
  - Methods: Serve, Bodies, Begin(Request) Watch and Ledger(Record). Watch
    has Attempt and End.
  - Observe(o) registers an observer until its remove is called.
  - ServeObservers is counted, and only Server.ListenAndServe calls it.
  - ObservedBodies takes the most any observer wants.
  - Record.SkipOTel becomes Watched, set by appendUsage for a request an
    observer watched.
- The gateway's otel.go becomes observe.go:
  - observeRequest asks each observer through Begin.
  - attempt and end call each Watch. Bodies are added only when an
    observer asks for them, and the whole reply only for WholeBodies.
- internal/otlp: the exporter (otel*.go) moves out of internal/usage, and
  the gateway's per-request span state moves into request.go. otlp.New()
  is an Exporter, a usage.Observer. What it sends is unchanged.
- plugins/otel:
  - Apply registers otlp.New() and disposes of it when turned off.
  - InUse is 1 while settings.OTelExport says to send. A user who exports
    only through MAGPIE_OTEL_* keeps the plugin on under Essentials.
- pluginrt.KeepFresh: the process serving the gateway refreshes every 2s
  when plugins.yml or settings.json changes. A switch made in the window or
  the CLI reaches a running gateway, or a headless serve, without a restart.
- docs: plugin-runtime.md gets a P3 section, a gateway runtime path and an
  updated failure section; reference.md says the export is the otel plugin.

Run at this tree on origin/main 82f48f093 (rebased onto 52ee84761 after,
which touches only the Linux tray icon):
- gofmt -l is clean. go vet passes on darwin, GOOS=linux -tags nogui and
  GOOS=windows.
- go test -count=1 -timeout 25m ./...: ok, 55 packages, none failed.
- New tests:
  - usage: TestObserverServesWithTheGateway and TestObserverLedgerAndBodies.
  - gateway: TestObserverPoint, covering unwatched, no bodies, captured,
    whole and whole streamed.
  - plugins/otel: TestOnExportsOffSendsNothing (on, off, on, with a real
    collector) and TestInUseByEnvironment.
  - pluginrt: TestKeepFreshFollowsPluginsYml.
  - The OTel tests moved with their code to internal/otlp.

Broken by hand, each red, then restored:
- Apply without Observe, and without its dispose.
- KeepFresh refreshing only once.
- InUse reading settings.json only.
- Ledger keeping Watched rows: 3 gateway OTel tests red.
- ObservedBodies taking the last observer's answer.
- Observe not serving a late registration.
- appendUsage not setting Watched.
- Whole bodies never kept.
- Bodies always on with no observer asking.
2026-10-15 05:39:01 +08:00

162 lines
4.1 KiB
Go

package usage
import (
"net/http"
"slices"
"sync"
)
// Observer is the gateway's observer point (P3 of
// docs/subsystems/plugin-runtime.md): it watches what the gateway serves
// and what the ledger is written, and never changes either. A plugin
// registers one with Observe while it is on (plugins/otel registers
// internal/otlp's exporter); with none registered the gateway does no
// observing work at all, not even keeping a reply's whole body.
//
// It lives here, not in the gateway, because every row it sees is a usage
// Record and the ledger's other writers (budget, routing decisions) reach
// it too.
type Observer interface {
// Serve runs it while this process serves the gateway; stop ends it,
// after the calls in flight have finished
Serve() (stop func())
// Bodies is how much of a request's bodies it wants now
Bodies() Bodies
// Begin is asked as each gateway request starts; nil leaves the
// request unwatched by it
Begin(Request) Watch
// Ledger is each row Append writes. A row of a request some observer
// watched has Watched set.
Ledger(Record)
}
// Watch is one request an Observer watches.
type Watch interface {
// Attempt is each routing attempt, unbilled failures and retries
// included, timed as the attempt and not the whole request
Attempt(Record)
// End is the request's end: its time, agent, model, status and length
End(Record)
}
// Request is what an Observer is told of a request as it starts.
type Request struct {
Header http.Header
// Agent the agent that sent it, Session its native session when it
// names one, else magpie's
Agent, Session string
// Kind its call kind ("web_search", "vision", …), "auxiliary" for
// Claude's tool-less small helper calls, "" for an agent's own turn
Kind string
// Plain is a loopback request with no gateway key, not passed on from
// another magpie: one the agent's own transcript can hold
Plain bool
}
// Bodies is how much of a request's and reply's bodies an observer wants.
type Bodies int
const (
NoBodies Bodies = iota
CapturedBodies // the first 256 KiB Recent calls keeps
WholeBodies // uncut: the reply is spooled as it streams
)
var (
obsMu sync.Mutex
observers []*observing
serving int // ServeObservers calls not yet stopped
)
type observing struct {
o Observer
stop func() // while serving
}
// Observe registers o until remove is called. While this process serves
// the gateway it is started at once.
func Observe(o Observer) (remove func()) {
obsMu.Lock()
ob := &observing{o: o}
if serving > 0 {
ob.stop = o.Serve()
}
observers = append(observers, ob)
obsMu.Unlock()
var once sync.Once
return func() {
once.Do(func() {
obsMu.Lock()
observers = slices.DeleteFunc(slices.Clone(observers), func(x *observing) bool { return x == ob })
stop := ob.stop
ob.stop = nil
obsMu.Unlock()
if stop != nil {
stop()
}
})
}
}
// ServeObservers starts every observer registered, and each one
// registered later, until stop: the gateway calls it as it starts serving.
func ServeObservers() (stop func()) {
obsMu.Lock()
serving++
if serving == 1 {
for _, ob := range observers {
ob.stop = ob.o.Serve()
}
}
obsMu.Unlock()
var once sync.Once
return func() {
once.Do(func() {
obsMu.Lock()
serving--
var stops []func()
if serving == 0 {
for _, ob := range observers {
if ob.stop != nil {
stops = append(stops, ob.stop)
ob.stop = nil
}
}
}
obsMu.Unlock()
for _, stop := range stops {
stop()
}
})
}
}
// Observers are the observers registered now.
func Observers() []Observer {
obsMu.Lock()
defer obsMu.Unlock()
out := make([]Observer, len(observers))
for i, ob := range observers {
out[i] = ob.o
}
return out
}
// ObservedBodies is the most of a request's bodies any observer wants now.
func ObservedBodies() Bodies {
b := NoBodies
for _, o := range Observers() {
b = max(b, o.Bodies())
}
return b
}
func observeLedger(r Record) {
for _, o := range Observers() {
o.Ledger(r)
}
}
// BodyCut ends a body the gateway captured only the start of.
const BodyCut = "\n… (cut here by magpie)"