Files
magpie/internal/gateway/capture.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

175 lines
4.2 KiB
Go

package gateway
import (
"bytes"
"io"
"net/http"
"os"
"github.com/yetone/magpie/internal/redact"
"github.com/yetone/magpie/internal/usage"
)
// Recent-call bodies are diagnostics, not an unbounded traffic log. Keeping the
// first 256 KiB is enough to inspect ordinary prompts and responses while
// preventing images or long streams from multiplying into tens of MiB across
// 40 calls.
const callBodyLimit = 256 << 10
// wholeBodyLimit asks a spool for every byte it is given, for a body the OTLP
// export wants uncut (#538).
const wholeBodyLimit = -1
type capturedBody struct {
buf bytes.Buffer
truncated bool
}
func (c *capturedBody) add(p []byte) {
if c.buf.Len() >= callBodyLimit {
c.truncated = c.truncated || len(p) > 0
return
}
n := min(len(p), callBodyLimit-c.buf.Len())
_, _ = c.buf.Write(p[:n])
if n < len(p) {
c.truncated = true
}
}
func (c *capturedBody) text() string { return c.buf.String() }
func captureRequestBody(p []byte) (string, bool) {
var c capturedBody
c.add(p)
return c.text(), c.truncated
}
type captureResponseWriter struct {
http.ResponseWriter
body capturedBody
// full: the whole body, for the request archive, when it is on
full *spool
// whole: the whole body, for an observer that asks for it uncut (#538)
whole *spool
// tools: whether the reply calls a tool, for a turn's end (turns)
tools *toolScan
}
func (w *captureResponseWriter) Write(p []byte) (int, error) {
w.body.add(p)
w.tools.add(p)
if w.full != nil {
w.full.add(p)
}
if w.whole != nil {
w.whole.add(p)
}
return w.ResponseWriter.Write(p)
}
// spool keeps a body whole for the request archive, beyond the first 256
// KiB Recent calls holds: in a temporary file, not in memory, up to limit
// bytes; past that only its size is counted. A negative limit keeps every
// byte (#538). A file that can't be written leaves what was kept so far, cut.
type spool struct {
pattern string // empty uses the request archive
f *os.File
limit, kept int64
size int64 // every byte that came, kept or not
failed bool
}
func (s *spool) add(p []byte) {
s.size += int64(len(p))
if s.failed || (s.limit >= 0 && s.kept >= s.limit) || len(p) == 0 {
return
}
if s.f == nil {
pattern := s.pattern
if pattern == "" {
pattern = "magpie-archive-*"
}
f, err := os.CreateTemp("", pattern)
if err != nil {
s.failed = true
return
}
s.f = f
}
n := int64(len(p))
if s.limit >= 0 {
n = min(n, s.limit-s.kept)
}
if _, err := s.f.Write(p[:n]); err != nil {
s.failed = true
return
}
s.kept += n
}
// cut is whether less than the whole body was kept.
func (s *spool) cut() bool { return s.kept < s.size }
// read is what was kept, the file gone after.
func (s *spool) read() ([]byte, error) {
if s.f == nil {
return nil, nil
}
defer s.discard()
if _, err := s.f.Seek(0, io.SeekStart); err != nil {
return nil, err
}
return io.ReadAll(io.LimitReader(s.f, s.kept))
}
// discard removes the file: nothing is kept.
func (s *spool) discard() {
if s.f != nil {
s.f.Close()
os.Remove(s.f.Name())
s.f = nil
}
}
func (w *captureResponseWriter) Flush() {
if f, ok := w.ResponseWriter.(http.Flusher); ok {
f.Flush()
}
}
// withBodies hands a call's captured request and reply to its usage
// record while an observer wants them (the OTLP export's bodies, #538) —
// their secrets scrubbed as the request archive's are, on top of the
// placeholders Mask secrets puts in — and leaves the record without them
// otherwise. A call captured whole (usage.WholeBodies) carries them in
// wholeIn/wholeOut; otherwise the first 256 KiB Recent calls keeps is what
// goes.
func withBodies(rec *usage.Record, c *Call) {
if usage.ObservedBodies() == usage.NoBodies {
return
}
in, inCut := c.RequestBody, c.RequestTruncated
if c.wholeIn != nil {
in, inCut = string(c.wholeIn), c.wholeInCut
}
out, outCut := c.ResponseBody, c.ResponseTruncated
if c.wholeOut != nil {
out, outCut = string(c.wholeOut), c.wholeOutCut
}
rec.BodyIn = bodyForExport(in, inCut)
rec.BodyOut = bodyForExport(out, outCut)
}
func bodyForExport(body string, cut bool) string {
if body == "" {
return ""
}
body = string(redact.ScrubJSON([]byte(body)))
if cut {
body += usage.BodyCut
}
return body
}