Files
magpie/internal/usage/otel.go
T
yetone 2f02a767b7 otel: request and response bodies can go with a call's span, as Langfuse's input and output, behind a switch that is off by default (#538: Langfuse 似乎无法看到请求体,如果技术上好实现的话,希望可以加一个开关) — the OTLP export sent only an allowlist of metadata (model, tokens, status, timing), never a body, so a Langfuse trace had no Input or Output. Settings → Observability has a new row, "Include request and response bodies" (otel.bodies, MAGPIE_OTEL_BODIES overriding it as the other MAGPIE_OTEL_* do, and counted in the "environment variables override" note). When it and the export are on, the gateway hands the call's captured request and reply (the Recent-calls capture, first 256 KiB each, "… (cut here by magpie)" added when cut) to its usage record as BodyIn/BodyOut, json:"-" so they never reach usage.jsonl, scrubbed with redact.ScrubJSON as the request archive's are (on top of Mask secrets' placeholders); the span carries them as langfuse.observation.input and langfuse.observation.output. A streamed reply's output is its text put together from the events (Chat's choices[].delta.content, Responses' response.output_text.delta, Anthropic's content_block_delta), a reply that isn't a stream or has no text (tool calls only) going as it came. This is filled for the final record, a locally turned-away request, and an attempt refused before another account was tried (its refusal as output); draw/video/decide and Codex's own-login passthrough still send metadata only. Queued records keep the config they were queued under, so turning bodies off drops any not yet sent, and spans with bodies go four to a request so a batch stays well inside a collector's size limit. The OTLP export row's text now says credentials stay local and prompts and replies too unless bodies are included. Nothing was sent to a real collector or Langfuse. TestOTelExportsBodiesWhenOn (off: no input/output and no prompt in the export; on: the request as input, the reply as output, a streamed reply's text as output, a key in the request scrubbed) fails without the gateway change, and without the scrub; TestBodiesStayOutOfTheLog, TestOTelReplyText, TestOTelSettingsAndOverrides (MAGPIE_OTEL_BODIES) and otel.test.cjs (the row off at first, en and zh, a click saves bodies:true without scrolling, kept through another preference's save; WebKit) pass. go vet ./internal/..., go build -tags nogui (darwin, GOOS=linux), GOOS=windows go build, go test -tags nogui -count=1 ./... under a temp HOME pass.
2026-10-02 16:48:26 +08:00

241 lines
6.0 KiB
Go

package usage
import (
"bytes"
"context"
"crypto/rand"
"encoding/json"
"io"
"log"
"net/http"
"reflect"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/yetone/magpie/internal/netproxy"
"github.com/yetone/magpie/internal/settings"
)
const otelQueueSize = 128
const otelBatchSize = 32
const otelBodiesBatch = 4
var otel atomic.Pointer[otelExporter]
type otelItem struct {
record Record
config settings.OTel
}
type otelExporter struct {
queue chan otelItem
stop, done chan struct{}
ctx context.Context
cancel context.CancelFunc
client *http.Client
salt [8]byte
last time.Time
dropped atomic.Uint64
}
// StartOTel runs only in the process serving the gateway. Stopping drains
// accepted metadata for at most three seconds, after in-flight calls finish.
func StartOTel() func() {
e := newOTelExporter()
otel.Store(e)
if _, err := settings.OTelExport(); err != nil {
log.Printf("otel: %s", err)
}
go e.run()
var once sync.Once
return func() {
once.Do(func() {
otel.CompareAndSwap(e, nil)
close(e.stop)
timer := time.NewTimer(3 * time.Second)
defer timer.Stop()
select {
case <-e.done:
case <-timer.C:
e.cancel()
<-e.done
}
})
}
}
func newOTelExporter() *otelExporter {
ctx, cancel := context.WithCancel(context.Background())
e := &otelExporter{queue: make(chan otelItem, otelQueueSize), stop: make(chan struct{}), done: make(chan struct{}), ctx: ctx, cancel: cancel,
last: time.Now(), client: &http.Client{Timeout: 3 * time.Second,
Transport: &http.Transport{Proxy: netproxy.Func, MaxIdleConnsPerHost: 2, IdleConnTimeout: 90 * time.Second},
CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}}
rand.Read(e.salt[:])
return e
}
func offerOTel(r Record) {
e := otel.Load()
if e == nil {
return
}
config, err := settings.OTelExport()
if err != nil || !config.Enabled {
return
}
if !config.Bodies {
r.BodyIn, r.BodyOut = "", ""
}
e.offer(otelItem{record: r, config: config})
}
// OTelBodies is whether calls' request and reply bodies go with their
// spans (#538): the gateway fills Record.BodyIn/BodyOut only then
func OTelBodies() bool {
if otel.Load() == nil {
return false
}
config, err := settings.OTelExport()
return err == nil && config.Enabled && config.Bodies
}
func (e *otelExporter) offer(item otelItem) {
select {
case e.queue <- item:
default:
e.dropped.Add(1) // telemetry must never wait for a slow collector
}
}
func (e *otelExporter) run() {
defer close(e.done)
defer e.cancel()
defer e.client.CloseIdleConnections()
ticker := time.NewTicker(5 * time.Second)
defer ticker.Stop()
batch := make([]otelItem, 0, otelBatchSize)
flush := func() { e.flush(batch); batch = batch[:0] }
for {
select {
case it := <-e.queue:
batch = append(batch, it)
if len(batch) == otelBatchSize {
flush()
}
case <-ticker.C:
flush()
case <-e.stop:
for {
select {
case it := <-e.queue:
batch = append(batch, it)
if len(batch) == otelBatchSize {
flush()
}
default:
flush()
return
}
}
}
}
}
func (e *otelExporter) flush(batch []otelItem) {
if len(batch) == 0 {
return
}
config, err := settings.OTelExport()
if err != nil || !config.Enabled {
return
}
var records []Record
for _, it := range batch {
// Never send queued records to a new destination or with changed credentials.
if reflect.DeepEqual(it.config, config) {
records = append(records, it.record)
}
}
if len(records) == 0 {
return
}
now := time.Now()
// spans carrying bodies (up to 256 KiB each way) go a few at a time,
// so one request stays well inside a collector's size limit
step := len(records)
if config.Bodies {
step = otelBodiesBatch
}
for i := 0; i < len(records); i += step {
e.send(config, "traces", e.traces(records[i:min(i+step, len(records))]))
}
if config.Metrics {
e.send(config, "metrics", otelMetrics(records, e.last, now))
}
e.last = now
}
func (e *otelExporter) send(config settings.OTel, signal string, payload any) {
b, _ := json.Marshal(payload)
base := strings.TrimRight(config.Endpoint, "/")
base = strings.TrimSuffix(strings.TrimSuffix(base, "/v1/traces"), "/v1/metrics")
endpoint := base + "/v1/" + signal
delay := time.Second
for attempt := 0; attempt < 3; attempt++ {
current, err := settings.OTelExport()
if err != nil || !current.Enabled || !reflect.DeepEqual(current, config) {
return
}
req, err := http.NewRequestWithContext(e.ctx, "POST", endpoint, bytes.NewReader(b))
if err != nil {
return
}
for k, v := range config.Headers {
req.Header.Set(k, v)
}
req.Header.Set("Content-Type", "application/json")
res, err := e.client.Do(req)
retry := err != nil
if res != nil {
response, _ := io.ReadAll(io.LimitReader(res.Body, 64<<10))
res.Body.Close()
if res.StatusCode == http.StatusOK {
var result struct {
PartialSuccess struct {
RejectedSpans json.Number `json:"rejectedSpans"`
RejectedDataPoints json.Number `json:"rejectedDataPoints"`
} `json:"partialSuccess"`
}
json.Unmarshal(response, &result)
if result.PartialSuccess.RejectedSpans != "" && result.PartialSuccess.RejectedSpans != "0" || result.PartialSuccess.RejectedDataPoints != "" && result.PartialSuccess.RejectedDataPoints != "0" {
log.Printf("otel: %s export partially rejected", signal)
}
return
}
retry = res.StatusCode == 429 || res.StatusCode == 502 || res.StatusCode == 503 || res.StatusCode == 504
if n, err := strconv.Atoi(res.Header.Get("Retry-After")); err == nil && n > 0 {
delay = time.Duration(min(n, 60)) * time.Second
} else if at, err := http.ParseTime(res.Header.Get("Retry-After")); err == nil && time.Until(at) > 0 {
delay = time.Until(at)
}
}
if !retry || attempt == 2 {
if e.ctx.Err() == nil {
log.Printf("otel: %s export failed; batch dropped", signal)
}
return
}
timer := time.NewTimer(min(delay, 60*time.Second))
select {
case <-e.ctx.Done():
timer.Stop()
return
case <-timer.C:
}
delay *= 2
}
}