Files
magpie/plugins/otel/otel_test.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

129 lines
3.6 KiB
Go

package otel
import (
"io"
"net/http"
"net/http/httptest"
"path/filepath"
"strings"
"testing"
"time"
"github.com/yetone/magpie/internal/otlp"
"github.com/yetone/magpie/internal/pluginrt"
"github.com/yetone/magpie/internal/testenv"
"github.com/yetone/magpie/internal/usage"
)
func TestMain(m *testing.M) { testenv.Main(m) }
func manifest(t *testing.T) pluginrt.Manifest {
t.Helper()
for _, m := range pluginrt.Registered() {
if m.ID == "otel" {
return m
}
}
t.Fatal("otel not registered")
return pluginrt.Manifest{}
}
// On, the plugin's exporter observes the gateway and a ledger row reaches
// the collector; off, there is no observer and nothing is sent, though
// settings still say to send.
func TestOnExportsOffSendsNothing(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", filepath.Join(t.TempDir(), "config"))
received := make(chan string, 8)
collector := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
b, _ := io.ReadAll(r.Body)
received <- string(b)
io.WriteString(w, `{}`)
}))
defer collector.Close()
t.Setenv("MAGPIE_OTEL_ENABLED", "true")
t.Setenv("MAGPIE_OTEL_ENDPOINT", collector.URL)
t.Setenv("MAGPIE_OTEL_HEADERS", "")
t.Setenv("MAGPIE_OTEL_METRICS", "false")
every := otlp.OTelEvery
otlp.OTelEvery = 50 * time.Millisecond
t.Cleanup(func() { otlp.OTelEvery = every })
stop := usage.ServeObservers()
defer stop()
rt := pluginrt.New([]pluginrt.Manifest{manifest(t)})
defer rt.Stop()
// seen is every model the collector got until want came, or "" when it
// didn't within 10s (the first export prices its rows, which loads the
// catalog)
seen := func(want string) string {
var got strings.Builder
deadline := time.After(10 * time.Second)
for {
select {
case b := <-received:
got.WriteString(b)
if strings.Contains(b, want) {
return got.String()
}
case <-deadline:
return ""
}
}
}
row := func(model string) {
usage.Append(usage.Record{Time: time.Now(), Agent: "pi", Via: "office", Model: model, Input: 1, Status: 200})
}
on := func() {
t.Helper()
rt.Reconcile(map[string]bool{"otel": true}, nil)
if !rt.Active("otel") {
t.Fatalf("otel not active: %+v", rt.Statuses())
}
if obs := usage.Observers(); len(obs) != 1 {
t.Fatalf("observers on: %d, want 1", len(obs))
} else if _, ok := obs[0].(*otlp.Exporter); !ok {
t.Fatalf("observer is %T", obs[0])
}
}
on()
row("model-on")
if seen("model-on") == "" {
t.Fatal("on: the row was not exported")
}
rt.Reconcile(map[string]bool{"otel": false}, nil)
if obs := usage.Observers(); len(obs) != 0 {
t.Fatalf("observers off: %d, want 0", len(obs))
}
if usage.ObservedBodies() != usage.NoBodies {
t.Fatal("off: the gateway still keeps bodies")
}
row("model-off")
// on again: what comes is what came after, never the row sent while off
on()
row("model-again")
got := seen("model-again")
if got == "" {
t.Fatal("on again: the row was not exported")
}
if strings.Contains(got, "model-off") {
t.Fatal("off: the row was exported")
}
}
// MAGPIE_OTEL_ENABLED alone keeps it on, as settings.json's switch does:
// off, an export set up only in the environment would send nothing.
func TestInUseByEnvironment(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", filepath.Join(t.TempDir(), "config"))
m := manifest(t)
t.Setenv("MAGPIE_OTEL_ENABLED", "false")
if n, err := m.InUse(); err != nil || n != 0 {
t.Fatalf("off: %d %v", n, err)
}
t.Setenv("MAGPIE_OTEL_ENDPOINT", "http://127.0.0.1:1")
t.Setenv("MAGPIE_OTEL_ENABLED", "true")
if n, err := m.InUse(); err != nil || n != 1 {
t.Fatalf("on by the environment: %d %v", n, err)
}
}