gateway: a display reads routing as it happens at /v1/magpie/route-events (#3387)

joe21_eee (sywyyhykkk on GitHub) wrote this for an ESP32 screen that
shows each agent's requests live: started, each try, the first content,
fallback, done. Ported from their route-events branch (42e1fa43f) with
the changes below.

What a display gets (route_events.go):
- GET /v1/magpie/route-events/snapshot: cursor, active, routes (every
  request the trace has that is still going).
- GET /v1/magpie/route-events?after=<cursor> (or Last-Event-ID): SSE,
  one "route" event a change, id = cursor, from a 512-change ring under
  trace.mu, so a short request is told step by step. 409
  snapshot_required for a cursor not this process's or too old, "event:
  reset" for a reader that fell behind, a heartbeat every 15s, a 10s
  write deadline.
- A route is routeActivity, an allow list: trace id (base 36), time,
  agent label, the provider of the seat the last try went to (never the
  seat id, which names an account or a key fingerprint), model, attempt,
  fallback, phase, status, failed, ms, ttft_ms. No session, account,
  key, folder, prompt, reply or error text.
- firstToken.onFirst tells the first content as it comes (serve and the
  ChatGPT backend's reads), written to an unexported Try.firstMs so the
  full trace's TTFT is unchanged.

Changed from the branch:
- No new key type. The branch added an "sk-magpie-route-" key, its CLI
  flag and its own Authenticate path through access, identifyCaller and
  corsGuard. main has read-only keys now (readOnlyGuard), and the feed
  is answered as /v1/magpie/usage is: this computer, and another machine
  with an enabled key while shared; a held key is refused (refuseHeld).
  Both GETs are in readOnlyRoutes, so the display gets
  `magpie gateway-key add Screen --read-only`. A full key already reads
  more than this (every call's usage). access, cli, cors.go and lan.go
  are untouched.
- A route the trace drops unfinished (drop: an unrouted request's
  stand-in once its own route begins; trim past twice traceKeep) is told
  request_dropped and marked offFeed. The branch kept its own active map
  that only "done" cleared, so a stand-in stayed going forever. The
  snapshot is read from t.routes, no second map.
- A stream ends when the gateway stops serving (Server.streamsEnding,
  closed first thing in ListenAndServe's drain). Before, an open stream
  held srv.Shutdown for its whole drain, 15 minutes on a handover.
- Revocation is access.On(KeyID) (identifyCaller swaps the secret out
  before handlers see it), asked at most once a second when there are
  changes and at every heartbeat, and remoteKeyed for a remote reader. A
  rotated key keeps its id, so its open stream goes on until it
  reconnects (said in the docs).

Docs: gateway-routing.md "Route events for a display" and the
read-only key's route list; reference.md beside the usage API.

Run at the pushed head on mote (Go 1.26.8):
- At daaafeb6e (rebased on ffc4aa684): gofmt -l internal/gateway empty;
  GOOS=linux go vet -tags nogui and GOOS=windows go vet of
  ./internal/gateway ./internal/access ok; go test -race -run
  'TestRouteEvents|TestReadOnlyKeyEveryRoute' ./internal/gateway ok.
- At daaafeb6e, every package that imports the gateway: internal/agent,
  browsermcp, cli, davsync, imagemcp, library, settingsapi, tui,
  access and the root package ok. internal/gui: one red,
  TestMainWindowCorners/macOS_26_SDK, which is #3949 (mote runs macOS
  27; this change touches no GUI code).
- Before the rebase (eb779ce92 base; gateway and access are the same
  at ffc4aa684): go build ./..., go vet, and the whole internal/gateway
  package, -timeout 45m. All ok except TestCodexPoolSaysTheClientsVersion,
  which is #4807 (red in a full package run on mote, passes alone; it
  passes alone at origin/main bf05291e2 too).
- At the pushed head (rebased on 443e53d6b, which changed search.go):
  gofmt, go vet ./internal/gateway and the -race run above again, ok.
- Not run: go test ./... in full. Other sessions' suites had mote at
  load 60 to 120.

Broken by hand (each on mote, then restored), the test that went red:
- serve's onFirst line removed: TestRouteEventsLiveFallback.
- drop's request_dropped removed: TestRouteEventsDroppedRouteGoes.
- the offFeed check removed: TestRouteEventsDroppedRouteGoes.
- the streamsEnding case removed: TestRouteEventsEndWithTheGateway.
- refuseHeld skipped: TestRouteEventsTold.
- the access.On recheck skipped: TestRouteEventsReplayAndRevocation.
- the snapshot taken out of readOnlyRoutes: TestRouteEventsTold,
  ReplayAndRevocation, LiveFallback.
- the seat's id told for its provider: TestRouteEventsReplayAndRevocation.
- the handler's own local/sharedWith gate removed: still green, since
  lanGuard refuses another machine first when not shared. It stays, as
  usage's does.

Not tried: an ESP32 or any real display, a real gateway with real
agents (tests drive httptest servers and fake upstreams), a handover
between two real magpie processes.

Co-authored-by: Junyu Zhou <feijifeibudao@gmail.com>
This commit is contained in:
yetone
2026-11-03 11:06:59 +08:00
co-authored by Junyu Zhou
parent 443e53d6b2
commit 8819beeb0e
9 changed files with 908 additions and 7 deletions
+17
View File
@@ -2411,6 +2411,23 @@ itself, so it can be polled every second. It answers as
`/v1/magpie/quotas` does: this machine, another only with a gateway key,
and never a held key.
Each request as it is routed, live, for a display that shows them
(#3387): `GET /v1/magpie/route-events/snapshot` answers `cursor`, `active`
and `routes`, the requests going now; then
`GET /v1/magpie/route-events?after=<cursor>` streams each change after that
cursor as server-sent events, one `route` event a change (`id` is its
cursor, `kind` what changed, `route` the request as it is now: `id`,
`time`, `agent`, `provider`, `model`, `attempt`, `fallback`, `phase`,
`status`, `failed`, `ms`, `ttft_ms`). A display replaces its request of
that `id` and drops it once `phase` is `done` or `dropped`. A 409
`snapshot_required`, an `event: reset`, a restart of magpie or a dropped
connection means: take a snapshot again. No session, account, key, folder,
prompt, reply or error text is in it. It answers as `/v1/magpie/usage`
does: this machine, another only with a gateway key while magpie is
shared, and never a held key. Give a display a read-only key,
`magpie gateway-key add Screen --read-only`, which can spend nothing. See
the [route event contract](subsystems/gateway-routing.md#route-events-for-a-display).
An app that calls its vendor itself, not through magpie, can report those
calls so the Usage page counts them: `POST /v1/magpie/usage/requests` with
`Content-Type: application/json`. The body is one record or an array of up
+77 -1
View File
@@ -494,7 +494,8 @@ and before `withCaller` and `keyLimited`, so nothing is read, reserved or
sent first. It judges the pattern `ServeMux.Handler` routes the request to
against `readOnlyRoutes` (`GET /`, `/v1`, the quotas, their history and
cards, the usage summary and its requests, the key's limit, the key
page and its data, and the concurrency) and refuses every other with 403 `gateway_key_read_only`:
page and its data, the concurrency, and the route events' snapshot and
stream) and refuses every other with 403 `gateway_key_read_only`:
every model route, `count_tokens`, the Responses WebSocket's upgrade, every
MCP server, Codex's and Gemini's backends, the catch-all and every write
(`POST /v1/magpie/usage/requests`, the quotas' refresh). A route added later
@@ -867,6 +868,81 @@ told its own calls and limit alone:
| `POST`/`GET /v1/magpie/keys`, `DELETE /v1/magpie/keys/{id}` | short-lived keys, above |
| `POST /v1/magpie/keys/oidc` | an OIDC token traded for a short-lived key, above |
### Route events for a display
A display on the network (#3387, joe21_eee: an ESP32 screen) shows every
agent's requests as they are routed, live, without knowing their sessions,
which `/v1/magpie/route` asks for, and without the full trace
(`/v1/magpie/trace`), which names accounts, folders and errors and stays
loopback-only. [`route_events.go`](../../internal/gateway/route_events.go)
serves two GETs:
- `GET /v1/magpie/route-events/snapshot`: `cursor`, `active` and `routes`,
every request the trace has that is still going, read together with the
cursor under `trace.mu`.
- `GET /v1/magpie/route-events?after=<cursor>` (or `Last-Event-ID`, which
wins): SSE. Each `route` event has an `id` equal to its JSON `cursor`, a
`kind`, the `active` count after the change and one `route`, which
replaces the display's route of that `id`. A display removes it when its
`phase` is `done` or `dropped`.
A route is `routeActivity`, an allow list, never a `Route` with fields
taken out: its id (the trace's, base 36, two requests of one session are
two ids), start `time`, `agent` (the caller's label), the `provider` of the
seat its last try went to (never the seat's id, which names an account or
a key's fingerprint), `model` (the served one once the reply names it),
`attempt` (from 1), `fallback` (a later attempt, a retry on the same
provider included), `phase` (`started`, `attempt`, `responding`,
`attempt_done`, `done`, `dropped`), `status`, `failed`, `ms` (the finished
try's, or the request's once done) and `ttft_ms`. No session, account, key,
folder, prompt, reply or error text. Kinds: `request_started`,
`attempt_started`, `first_content`, `attempt_finished`, `request_finished`,
`request_dropped`, `route_changed`.
Changes are recorded in `trace.begin` and `trace.update` (a diff of
`activityOf` before and after) into a ring of the last 512, under
`trace.mu`; writes to the socket hold no lock. The first content is told as
it comes: `firstToken.onFirst` (`s.trace.firstContent`, set per try in
`serve` and for the ChatGPT backend's reads in
[`codex_backend.go`](../../internal/gateway/codex_backend.go)) writes the
try's unexported `firstMs`, so the full trace's `TTFT`, told once the try
is done, is unchanged. A route that leaves the trace unfinished (`drop`: an
unrouted request's stand-in once its own route begins; `trim` past twice
`traceKeep`) is told `request_dropped` and marked `offFeed`, so later writes
to it by the request holding it are told no more: without it a display
showed a stand-in going forever.
A cursor that isn't this process's (the ring's `epoch`), or older than the
ring, is answered 409 `{"error":"snapshot_required"}`; a reader that falls
behind mid-stream gets `event: reset` and the stream ends. Take a snapshot
in either case. A heartbeat comes every 15 seconds; a write waits at most
10. The stream ends when the client goes, when the gateway stops serving
(`Server.streamsEnding`, closed first thing in `ListenAndServe`'s drain, so
`Shutdown` doesn't wait its whole drain, 15 minutes on a handover, for a
display), when the key it came with is turned off, removed or runs out
(`access.On`, asked at most once a second when there are changes and at
each heartbeat), and when magpie stops being shared with a reader on
another machine (`remoteKeyed`). A key rotated keeps its id, so a stream
open under the old secret goes on until it reconnects. Nothing is kept on
disk.
Who reads it is who reads the usage log (`routeEventsAllowed`, as
`usageSummary`): this computer, and another machine with an enabled gateway
key while magpie is shared; never a key held to a budget, models or
accounts (`refuseHeld`), which is told no one else's requests. A read-only
key reads it (`readOnlyRoutes`), so a display is given
`magpie gateway-key add Screen --read-only`: it can spend nothing. Every
route's guards come first (`lanGuard`, `corsGuard`): a page sending
`Origin: null`, a `*.localhost` page, a rebound name and a proxy's client
are refused it without a key. A separate key type, as the community patch
had, was left out: the read-only key already reads more than this feed
(every call's usage), and is the key for a display.
`TestRouteEventsTold`, `TestRouteEventsReplayAndRevocation`,
`TestRouteEventsDroppedRouteGoes`, `TestRouteEventsEndWithTheGateway`,
`TestRouteEventsLiveFallback` in
[`route_events_test.go`](../../internal/gateway/route_events_test.go), and
`TestReadOnlyKeyEveryRoute`.
## Turning provider search off
[Settings](../../internal/settings/settings.go)' `searcher: "off"` disables magpie's provider-assisted search,
+2 -1
View File
@@ -1045,6 +1045,7 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st
if m := noteMasked(r, "chat", maskedHits, sentOf(maskedHits, body), tr.ID, "openai", model); m != nil {
s.trace.update(tr, func(t *Route) { t.Masked = m })
}
first.onFirst = s.trace.firstContent(tr)
promptRead := s.inspectPrompt(tr, provider.Responses, body, body, sentWhole)
end = func(status int, msg string, tokens, out int) {
ms := time.Since(start).Milliseconds()
@@ -1153,7 +1154,7 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st
again := t.Tries[0]
t.Tries = append(t.Tries, Try{ID: again.ID, Model: again.Model, Effort: again.Effort, Start: began})
})
first, titleReply = firstToken{start: start}, capturedBody{}
first, titleReply = firstToken{start: start, onFirst: s.trace.firstContent(tr)}, capturedBody{}
return true
}
var sniff *usageSniffer
+11
View File
@@ -466,6 +466,13 @@ type Call struct {
// Server is the gateway.
type Server struct {
client *http.Client
// ending closes once the gateway stops serving, for a stream with no
// end of its own (routeEvents) to end before Shutdown, which would
// wait its whole drain for it (streamsEnding)
ending chan struct{}
endingOnce sync.Once
endOnce sync.Once
mu sync.Mutex
recent []Call
calls uint64 // the last Call.ID given
@@ -837,6 +844,7 @@ func (s *Server) ListenAndServe(ctx context.Context) error {
go func() {
defer close(drained)
<-ctx.Done()
s.endStreams()
c, cancel := context.WithTimeout(context.Background(), s.drainFor())
defer cancel()
if s.handingOver() {
@@ -929,6 +937,8 @@ func (s *Server) routes() *routeMux {
mux.HandleFunc("POST "+provider.RemoteRefreshPath, s.quotaCardsRefresh)
mux.HandleFunc("GET /v1/magpie/route", s.sessionRoute)
mux.HandleFunc("GET /v1/magpie/trace", s.gatewayTrace)
mux.HandleFunc("GET "+routeSnapshotPath, s.routeSnapshot)
mux.HandleFunc("GET "+routeEventsPath, s.routeEvents)
mux.HandleFunc("GET /v1/magpie/concurrency", s.concurrency)
mux.HandleFunc("GET /v1/magpie/limit", s.keyLimit)
mux.HandleFunc("GET "+OwnMCPPath, s.ownMCPList)
@@ -3098,6 +3108,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
firstBegan = began
}
hw.first.start = began
hw.first.onFirst = s.trace.firstContent(tr)
// when the request that last went out began to (GetConn), and
// when its body was written
var asking, asked, wrote atomic.Int64
+8 -4
View File
@@ -19,10 +19,12 @@ import (
// method or path spelling reaches them. TestReadOnlyKeyEveryRoute fails
// when a route is neither here nor in its list of refused ones.
//
// What it reads is what a key held to nothing reads: the usage summary
// and every account's quotas (it is no one else's to spend, so heldKey
// What it reads is what a key held to nothing reads: the usage summary,
// every account's quotas (it is no one else's to spend, so heldKey
// leaves it alone unless it is held to a budget, models or accounts as
// well). None of these routes tells a gateway key's secret.
// well) and the routing as it happens, redacted (route_events.go,
// joe21_eee's display, #3387). None of these routes tells a gateway
// key's secret.
var readOnlyRoutes = map[string]bool{
"GET /{$}": true,
"GET /v1": true,
@@ -34,6 +36,8 @@ var readOnlyRoutes = map[string]bool{
"GET /v1/magpie/usage/requests": true,
"GET /v1/magpie/limit": true,
"GET /v1/magpie/concurrency": true,
"GET " + routeSnapshotPath: true,
"GET " + routeEventsPath: true,
"GET " + OwnMCPPath: true,
"GET " + KeyPagePath: true,
"GET " + keyPageData: true,
@@ -64,7 +68,7 @@ func readOnlyGuard(mux *routeMux, next http.Handler) http.Handler {
if _, pattern := mux.Handler(r); !readOnlyRoutes[pattern] {
log.Printf("refused %s %s: gateway key %q is read-only", r.Method, r.URL.Path, who.KeyName)
writeJSON(w, http.StatusForbidden, map[string]any{"error": map[string]any{
"message": "this gateway key is read-only: it may read magpie's quotas and usage (GET /v1/magpie/quotas, /v1/magpie/quotas/history, /v1/magpie/usage, /v1/magpie/usage/requests, /v1/magpie/limit) and use no model, MCP server or write. Use a key with full access for that (Gateway → Gateway keys, or magpie gateway-key access <id> full)",
"message": "this gateway key is read-only: it may read magpie's quotas and usage (GET /v1/magpie/quotas, /v1/magpie/quotas/history, /v1/magpie/usage, /v1/magpie/usage/requests, /v1/magpie/limit, /v1/magpie/route-events) and use no model, MCP server or write. Use a key with full access for that (Gateway → Gateway keys, or magpie gateway-key access <id> full)",
"type": "permission_error", "code": ReadOnlyCode}})
return
}
+365
View File
@@ -0,0 +1,365 @@
package gateway
import (
"cmp"
"crypto/rand"
"encoding/json"
"fmt"
"net/http"
"strconv"
"strings"
"time"
"github.com/yetone/magpie/internal/access"
"github.com/yetone/magpie/internal/provider"
)
// The route-events feed (#3387, joe21_eee on Discord, sywyyhykkk on
// GitHub): a display on the LAN, an ESP32 screen, shows every agent's
// requests as they are routed (started, each try, its first content,
// fallback, done) without knowing their sessions, which
// /v1/magpie/route asks for, and without the full trace, which names
// accounts, folders and errors and is told to this computer alone.
//
// GET routeSnapshotPath is the requests going now and a cursor; GET
// routeEventsPath?after=<cursor> streams each change after it as SSE. A
// route here is routeActivity, an allow list of fields, never a Route
// with some taken out. They are told as the usage log is: to this
// computer, and to another with an enabled gateway key while magpie is
// shared (a read-only key reads them too, readOnlyRoutes), never to a
// key held to a budget, models or accounts, which is told no one else's
// requests.
const (
routeSnapshotPath = "/v1/magpie/route-events/snapshot"
routeEventsPath = "/v1/magpie/route-events"
// routeEventsKeep is how many changes the feed keeps for a reader
// that fell behind, or reconnects with the cursor it last had
routeEventsKeep = 512
// routeEventsBeat is how often an idle stream is sent a heartbeat,
// and the longest a key turned off keeps an idle stream open
routeEventsBeat = 15 * time.Second
)
// routeEventsRecheck is how often a stream with changes to send asks
// again whether its key is still on (a var for the tests)
var routeEventsRecheck = time.Second
// routeEventsRefused is what another machine is told while magpie isn't
// shared with it.
const routeEventsRefused = "magpie's routing events are told to another machine only when magpie is shared on the local network (Settings → Network and sharing → Share on local network) and the request carries an enabled gateway key (Authorization: Bearer <key> or x-api-key: <key>); a read-only key reads them too"
// routeActivity is what the feed tells of a request. ID is the route's,
// never a session's, an account's or a key's; Attempt counts from 1.
type routeActivity struct {
ID string `json:"id"`
Time time.Time `json:"time"`
Agent string `json:"agent"`
Provider string `json:"provider,omitempty"`
Model string `json:"model,omitempty"`
Attempt int `json:"attempt"`
Fallback bool `json:"fallback"`
Phase string `json:"phase"`
Status int `json:"status,omitempty"`
Failed bool `json:"failed,omitempty"`
Millis int64 `json:"ms,omitempty"`
TTFT int64 `json:"ttft_ms,omitempty"`
}
// The phases a route is in.
const (
phaseStarted = "started" // no try yet
phaseAttempt = "attempt" // its last try is out
phaseResponding = "responding" // its last try's content is coming
phaseTryDone = "attempt_done" // its last try ended, the next not yet out
phaseDone = "done" // answered, one way or the other
phaseDropped = "dropped" // gone from the trace unfinished (drop, trim)
)
func activityOf(r *Route) routeActivity {
a := routeActivity{ID: strconv.FormatInt(r.ID, 36), Time: r.Time, Agent: r.Agent,
Phase: phaseStarted, Attempt: len(r.Tries)}
if n := len(r.Tries); n > 0 {
tr := r.Tries[n-1]
a.Model, a.Status, a.Millis, a.TTFT = cmp.Or(tr.Served, tr.Model), tr.Status, tr.Millis, cmp.Or(tr.TTFT, tr.firstMs)
a.Failed, a.Fallback, a.Phase = tr.Error != "" || tr.Status >= 400, n > 1, phaseAttempt
// a try's ID is its seat's, which names an account or a key's
// fingerprint: only the seat's provider is told
for _, seat := range r.Order {
if seat.ID == tr.ID && seat.Model == tr.Model {
a.Provider = seat.Provider
break
}
}
if a.TTFT > 0 {
a.Phase = phaseResponding
}
if tr.Done {
a.Phase = phaseTryDone
}
}
if r.Done {
a.Phase, a.Status, a.Millis = phaseDone, r.Status, r.Millis
a.Failed = r.Status >= 400 || r.Error != ""
}
return a
}
func activityChange(before, after routeActivity) string {
switch {
case after.Phase == phaseDone && before.Phase != phaseDone:
return "request_finished"
case after.Attempt > before.Attempt:
return "attempt_started"
case after.Phase == phaseTryDone && before.Phase != phaseTryDone:
return "attempt_finished"
case after.TTFT > 0 && before.TTFT == 0:
return "first_content"
default:
return "route_changed"
}
}
// firstContent is a try's firstToken.onFirst: it tells the route's last
// try, still going, that its first content came ms after it began.
func (t *trace) firstContent(r *Route) func(int64) {
return func(ms int64) {
t.update(r, func(r *Route) {
if n := len(r.Tries); n > 0 && !r.Tries[n-1].Done {
r.Tries[n-1].firstMs = max(ms, 1)
}
})
}
}
type routeActivityEvent struct {
Cursor string `json:"cursor"`
Kind string `json:"kind"`
// Active is how many requests were going once this change was made
Active int `json:"active"`
Route routeActivity `json:"route"`
}
// routeActivityLog is the feed's last routeEventsKeep changes, a ring
// held under trace.mu: a request that begins and ends between two reads
// is told step by step, not as its end alone. epoch is this process's,
// so a cursor from before a restart is told to take a snapshot.
type routeActivityLog struct {
epoch string
seq int64
events []routeActivityEvent
}
func (l *routeActivityLog) init() {
if l.epoch == "" {
l.epoch = rand.Text()
l.events = make([]routeActivityEvent, routeEventsKeep)
}
}
func (l *routeActivityLog) cursor() string {
return l.epoch + ":" + strconv.FormatInt(l.seq, 10)
}
// after is every change after cursor; false when cursor isn't one of
// this process's, or the changes after it are no longer all kept.
func (l *routeActivityLog) after(cursor string) ([]routeActivityEvent, bool) {
epoch, raw, ok := strings.Cut(cursor, ":")
n, err := strconv.ParseInt(raw, 10, 64)
if !ok || err != nil || epoch != l.epoch || n < 0 || n > l.seq || n < l.seq-routeEventsKeep {
return nil, false
}
out := make([]routeActivityEvent, 0, l.seq-n)
for i := n; i < l.seq; i++ {
out = append(out, l.events[i%routeEventsKeep])
}
return out, true
}
// noteActivity records a change of r, under t.mu: none once r left the
// trace unfinished and the feed was told it went (noteDropped), though
// the request that holds r goes on writing to it.
func (t *trace) noteActivity(r *Route, kind string) {
if r.offFeed {
return
}
l := &t.activity
l.init()
l.seq++
l.events[(l.seq-1)%routeEventsKeep] = routeActivityEvent{l.cursor(), kind, t.going(), activityOf(r)}
}
// noteDropped tells the feed r left the trace unfinished, under t.mu,
// after it was taken off t.routes.
func (t *trace) noteDropped(r *Route) {
if r.offFeed {
return
}
l := &t.activity
l.init()
l.seq++
a := activityOf(r)
a.Phase = phaseDropped
l.events[(l.seq-1)%routeEventsKeep] = routeActivityEvent{l.cursor(), "request_dropped", t.going(), a}
r.offFeed = true
}
// going counts the requests still going, under t.mu.
func (t *trace) going() int {
n := 0
for _, r := range t.routes {
if !r.Done {
n++
}
}
return n
}
// routeEventsAllowed: r may read the feed. It is answered as the usage
// log's routes are (usageSummary), and refused otherwise.
func routeEventsAllowed(w http.ResponseWriter, r *http.Request) bool {
if !local(r) && !sharedWith(r) {
writeError(w, provider.Chat, http.StatusForbidden, routeEventsRefused)
return false
}
return !refuseHeld(w, r, "this gateway key is held to a budget, models or accounts, so it is told no one else's routing: GET /v1/magpie/usage/requests tells it its own calls")
}
// activitySnapshot is the requests going now, by id, and the cursor of
// the last change, read together.
func (t *trace) activitySnapshot() (string, []routeActivity) {
t.mu.Lock()
defer t.mu.Unlock()
t.activity.init()
routes := []routeActivity{}
for _, r := range t.routes {
if !r.Done && !r.offFeed {
routes = append(routes, activityOf(r))
}
}
return t.activity.cursor(), routes
}
func (s *Server) routeSnapshot(w http.ResponseWriter, r *http.Request) {
if !routeEventsAllowed(w, r) {
return
}
cursor, routes := s.trace.activitySnapshot()
w.Header().Set("Cache-Control", "no-store")
writeJSON(w, http.StatusOK, map[string]any{"cursor": cursor, "active": len(routes), "routes": routes})
}
// routeEvents streams the feed's changes after a cursor (Last-Event-ID,
// else ?after=). It ends when the client goes, when the gateway stops
// serving (streamsEnding: Shutdown would wait its whole drain for it),
// when the key it came with is turned off, removed or runs out, and when
// magpie stops being shared with a reader on another machine.
func (s *Server) routeEvents(w http.ResponseWriter, r *http.Request) {
if !routeEventsAllowed(w, r) {
return
}
cursor := r.Header.Get("Last-Event-ID")
if cursor == "" {
cursor = r.URL.Query().Get("after")
}
keyID, remote := access.Caller(r.Context()).KeyID, !local(r)
// still: the reader may still be told the feed, read again at most
// once routeEventsRecheck, as it reads the key store and settings
// from disk under the lock every request's key check takes
var checked time.Time
still := func() bool {
if time.Since(checked) < routeEventsRecheck {
return true
}
checked = time.Now()
return (keyID == "" || access.On(keyID)) && (!remote || remoteKeyed())
}
t := &s.trace
beat := time.NewTicker(routeEventsBeat)
defer beat.Stop()
rc := http.NewResponseController(w)
defer rc.SetWriteDeadline(time.Time{})
started := false
write := func(event, id string, data any) bool {
b, err := json.Marshal(data)
if err != nil {
return false
}
_ = rc.SetWriteDeadline(time.Now().Add(10 * time.Second))
if id != "" {
if _, err = fmt.Fprintf(w, "id: %s\n", id); err != nil {
return false
}
}
_, err = fmt.Fprintf(w, "event: %s\ndata: %s\n\n", event, b)
return err == nil
}
for {
t.mu.Lock()
t.activity.init()
events, ok := t.activity.after(cursor)
if t.wake == nil {
t.wake = make(chan struct{})
}
wake := t.wake
t.mu.Unlock()
if !ok {
reset := map[string]string{"error": "snapshot_required", "snapshot": routeSnapshotPath}
if started {
write("reset", "", reset)
rc.Flush()
} else {
writeJSON(w, http.StatusConflict, reset)
}
return
}
if !started {
_ = rc.SetWriteDeadline(time.Now().Add(10 * time.Second))
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-store")
w.Header().Set("X-Accel-Buffering", "no")
w.WriteHeader(http.StatusOK)
if err := rc.Flush(); err != nil {
return
}
started = true
}
if len(events) > 0 {
if !still() {
return
}
for _, event := range events {
if !write("route", event.Cursor, event) {
return
}
cursor = event.Cursor
}
if rc.Flush() != nil {
return
}
}
select {
case <-r.Context().Done():
return
case <-s.streamsEnding():
return
case <-wake:
case <-beat.C:
checked = time.Time{}
if !still() || !write("heartbeat", "", struct{}{}) || rc.Flush() != nil {
return
}
}
}
}
// streamsEnding closes once the gateway stops serving.
func (s *Server) streamsEnding() <-chan struct{} {
s.endingOnce.Do(func() { s.ending = make(chan struct{}) })
return s.ending
}
// endStreams ends every stream waiting on streamsEnding.
func (s *Server) endStreams() {
s.streamsEnding()
s.endOnce.Do(func() { close(s.ending) })
}
+400
View File
@@ -0,0 +1,400 @@
package gateway
import (
"bufio"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"time"
"github.com/yetone/magpie/internal/access"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/settings"
)
// displayKey is a read-only gateway key, magpie shared on the LAN, as a
// display on another machine is given (#3387).
func displayKey(t *testing.T) (access.Key, string) {
t.Helper()
keys, secrets := newCaller(t, "Display")
if _, err := access.Update("access-key", access.Change{Key: keys[0].ID, ReadOnly: true}); err != nil {
t.Fatal(err)
}
return keys[0], secrets[0]
}
// The feed is told as the usage log is: to this computer, and to another
// machine with an enabled gateway key while magpie is shared; a
// read-only key reads it and nothing it may not; a key held to a budget,
// models or accounts is told no one else's routing; and a page reaching
// the gateway (Origin null, a *.localhost name, a rebound name, a
// foreign site) or a proxy's client is refused it without a key, as
// every other route is.
func TestRouteEventsTold(t *testing.T) {
fresh(t)
t.Setenv("MAGPIE_ADDR", "")
t.Setenv("MAGPIE_PUBLIC_URL", "")
_, display := displayKey(t)
keys, secrets := newCaller(t, "Laptop", "Held")
full, held := secrets[0], secrets[1]
if _, err := access.Update("models-key", access.Change{Key: keys[1].ID, Models: []string{"plan/m1"}}); err != nil {
t.Fatal(err)
}
h := lanGuard(New().Handler())
do := func(method, path, from, host, key string, hdr ...string) *httptest.ResponseRecorder {
t.Helper()
r := httptest.NewRequest(method, path, strings.NewReader(chatReq))
r.RemoteAddr, r.Host = from, host
if key != "" {
r.Header.Set("Authorization", "Bearer "+key)
}
for i := 0; i+1 < len(hdr); i += 2 {
r.Header.Set(hdr[i], hdr[i+1])
}
w := httptest.NewRecorder()
h.ServeHTTP(w, r)
return w
}
const lan, here, gw = "192.168.1.9:1234", "127.0.0.1:50123", "127.0.0.1:3425"
// no cursor: a stream is told to take a snapshot, 409, before it begins
for _, tc := range []struct {
name, from, host, key string
path string
want int
}{
{"read-only key, LAN", lan, "192.168.1.10:3425", display, routeSnapshotPath, 200},
{"read-only key, LAN, stream", lan, "192.168.1.10:3425", display, routeEventsPath, 409},
{"full key, LAN", lan, "192.168.1.10:3425", full, routeSnapshotPath, 200},
{"this computer, no key", here, gw, "", routeSnapshotPath, 200},
{"this computer, read-only key", here, gw, display, routeEventsPath, 409},
{"another machine, no key", lan, "192.168.1.10:3425", "", routeSnapshotPath, 401},
{"another machine, no key, stream", lan, "192.168.1.10:3425", "", routeEventsPath, 401},
{"another machine, a wrong key", lan, "192.168.1.10:3425", "sk-magpie-wrong", routeSnapshotPath, 401},
{"held key, LAN", lan, "192.168.1.10:3425", held, routeSnapshotPath, 403},
{"held key, LAN, stream", lan, "192.168.1.10:3425", held, routeEventsPath, 403},
{"held key, this computer", here, gw, held, routeSnapshotPath, 403},
} {
if w := do("GET", tc.path, tc.from, tc.host, tc.key); w.Code != tc.want {
t.Errorf("%s: %d, want %d: %.300s", tc.name, w.Code, tc.want, w.Body)
}
}
safari := []string{"User-Agent", "Mozilla/5.0 (Macintosh) AppleWebKit/605.1.15 Version/27.2 Safari/605.1.15", "Sec-Fetch-Site", "cross-site", "Sec-Fetch-Mode", "cors"}
// a rebound page's own GET: its name now answers at loopback, so it
// is same-origin and sends no Origin
rebound := []string{"User-Agent", safari[1], "Sec-Fetch-Site", "same-origin", "Sec-Fetch-Mode", "cors"}
for _, path := range []string{routeSnapshotPath, routeEventsPath} {
for _, tc := range []struct {
name, host string
hdr []string
}{
{"a foreign page", gw, append([]string{"Origin", "https://evil.example"}, safari...)},
{"Origin null", gw, append([]string{"Origin", "null"}, safari...)},
{"a localhost subdomain", gw, append([]string{"Origin", "http://evil.localhost"}, safari...)},
{"a rebound page's GET", "rebind.attacker.example:3425", rebound},
{"a page rebound at a localhost subdomain", "evil.localhost:3425", rebound},
{"a proxy's client", gw, []string{"X-Forwarded-For", "203.0.113.9"}},
} {
if w := do("GET", path, here, tc.host, "", tc.hdr...); w.Code != http.StatusForbidden && w.Code != http.StatusUnauthorized {
t.Errorf("%s %s with no key: %d %.300s", tc.name, path, w.Code, w.Body)
}
}
}
// the read-only key reaches nothing else it didn't before
for _, tc := range []struct{ method, path string }{
{"POST", "/v1/chat/completions"}, {"POST", "/v1/responses"}, {"POST", "/v1/messages"},
{"GET", "/v1/models"}, {"GET", "/v1/magpie/trace"}, {"POST", "/mcp/magpie/web-search"},
} {
if w := do(tc.method, tc.path, lan, "192.168.1.10:3425", display); w.Code != http.StatusForbidden || !strings.Contains(w.Body.String(), ReadOnlyCode) {
t.Errorf("read-only key: %s %s: %d %.200s", tc.method, tc.path, w.Code, w.Body)
}
}
// no longer shared: another machine is refused it, even with a key
if err := settings.Save(settings.Settings{LAN: false}); err != nil {
t.Fatal(err)
}
if w := do("GET", routeSnapshotPath, lan, "192.168.1.10:3425", display); w.Code != http.StatusForbidden && w.Code != http.StatusUnauthorized {
t.Errorf("not shared: the display's key from the LAN: %d %.300s", w.Code, w.Body)
}
}
type routeSnap struct {
Cursor string `json:"cursor"`
Active int `json:"active"`
Routes []routeActivity `json:"routes"`
}
func activitySnapshot(t *testing.T, base, key string) routeSnap {
t.Helper()
req, _ := http.NewRequest("GET", base+routeSnapshotPath, nil)
if key != "" {
req.Header.Set("Authorization", "Bearer "+key)
}
res, err := (&http.Client{Timeout: 10 * time.Second}).Do(req)
if err != nil {
t.Fatal(err)
}
defer res.Body.Close()
var got routeSnap
if err := json.NewDecoder(res.Body).Decode(&got); err != nil || res.StatusCode != 200 || got.Active != len(got.Routes) || got.Routes == nil {
t.Fatalf("snapshot: status %d, %+v, %v", res.StatusCode, got, err)
}
return got
}
func activityStream(t *testing.T, base, key, cursor string) *http.Response {
t.Helper()
req, _ := http.NewRequest("GET", base+routeEventsPath, nil)
if key != "" {
req.Header.Set("Authorization", "Bearer "+key)
}
req.Header.Set("Last-Event-ID", cursor)
res, err := (&http.Client{Timeout: 20 * time.Second}).Do(req)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { res.Body.Close() })
return res
}
// nextActivity is the stream's next change, false once it ended.
func nextActivity(t *testing.T, scan *bufio.Scanner) (routeActivityEvent, bool) {
t.Helper()
for scan.Scan() {
if data, ok := strings.CutPrefix(scan.Text(), "data: "); ok {
var ev routeActivityEvent
if err := json.Unmarshal([]byte(data), &ev); err != nil {
t.Fatal(err)
}
if ev.Cursor != "" {
return ev, true
}
}
}
return routeActivityEvent{}, false
}
func mustActivity(t *testing.T, scan *bufio.Scanner) routeActivityEvent {
t.Helper()
ev, ok := nextActivity(t, scan)
if !ok {
t.Fatalf("event stream ended: %v", scan.Err())
}
return ev
}
// A display reconnecting with its cursor is told each change it missed,
// two requests of one session apart, and nothing of their session,
// folder, account or error; a key turned off ends its stream; a cursor
// too old, or from before a restart, is told to take a snapshot.
func TestRouteEventsReplayAndRevocation(t *testing.T) {
fresh(t)
was := routeEventsRecheck
routeEventsRecheck = 0
t.Cleanup(func() { routeEventsRecheck = was })
k, key := displayKey(t)
s := New()
srv := httptest.NewServer(lanGuard(s.Handler()))
t.Cleanup(srv.Close) // after each stream's body is closed
cursor := activitySnapshot(t, srv.URL, key).Cursor
for i := 0; i < 2; i++ {
r := s.trace.begin(Route{Time: time.Now(), Agent: "codex", Session: "private-session", Folder: "private-folder",
Model: "m", Order: []Weighed{{ID: "private-account", Who: "private-email", Provider: "p", Model: "m"}}})
s.trace.update(r, func(r *Route) { r.Tries = []Try{{ID: "private-account", Model: "m", Start: time.Now()}} })
s.trace.update(r, func(r *Route) { r.Done, r.Status, r.Error = true, 500, "private-error" })
}
res := activityStream(t, srv.URL, key, cursor)
if res.StatusCode != 200 || res.Header.Get("Content-Type") != "text/event-stream" {
t.Fatal(res.Status, res.Header)
}
scan := bufio.NewScanner(res.Body)
ids := map[string]bool{}
for i := 0; i < 6; i++ {
ev := mustActivity(t, scan)
b, _ := json.Marshal(ev)
if strings.Contains(string(b), "private-") {
t.Fatalf("private metadata in event: %s", b)
}
if ev.Kind == "request_finished" {
ids[ev.Route.ID] = true
if !ev.Route.Failed || ev.Route.Status != 500 || ev.Active != 0 || ev.Route.Provider != "p" {
t.Fatal(ev)
}
}
}
if len(ids) != 2 {
t.Fatal("two requests of one session were told as one", ids)
}
if _, err := access.Update("off-key", access.Change{Key: k.ID}); err != nil {
t.Fatal(err)
}
s.trace.begin(Route{Time: time.Now(), Agent: "codex"}) // wakes the stream
if ev, ok := nextActivity(t, scan); ok {
t.Fatal("a key turned off was told another change", ev)
}
res.Body.Close()
if _, err := access.Update("on-key", access.Change{Key: k.ID}); err != nil {
t.Fatal(err)
}
for i := 0; i < routeEventsKeep; i++ {
r := s.trace.begin(Route{Time: time.Now()})
s.trace.update(r, func(r *Route) { r.Done = true })
}
if res := activityStream(t, srv.URL, key, cursor); res.StatusCode != 409 {
t.Fatal("a cursor too old was taken", res.Status)
}
restarted := httptest.NewServer(lanGuard(New().Handler()))
t.Cleanup(restarted.Close)
if res := activityStream(t, restarted.URL, key, cursor); res.StatusCode != 409 {
t.Fatal("a cursor from the gateway before was taken", res.Status)
}
}
// A route that leaves the trace unfinished, as an unrouted request's
// stand-in does once its own route begins (drop), is told gone, and
// isn't in the next snapshot: a display would show it going forever.
func TestRouteEventsDroppedRouteGoes(t *testing.T) {
fresh(t)
s := New()
srv := httptest.NewServer(lanGuard(s.Handler()))
t.Cleanup(srv.Close) // after each stream's body is closed
cursor := activitySnapshot(t, srv.URL, "").Cursor
stand := s.trace.begin(Route{Time: time.Now(), Agent: "codex"})
if snap := activitySnapshot(t, srv.URL, ""); snap.Active != 1 {
t.Fatal("the stand-in isn't going", snap)
}
s.trace.drop(stand)
// written to after it went, as a request holding it may: not told
s.trace.update(stand, func(r *Route) { r.Done, r.Status = true, 200 })
if snap := activitySnapshot(t, srv.URL, ""); snap.Active != 0 || len(snap.Routes) != 0 {
t.Fatal("a dropped route is still going", snap)
}
res := activityStream(t, srv.URL, "", cursor)
scan := bufio.NewScanner(res.Body)
if ev := mustActivity(t, scan); ev.Kind != "request_started" {
t.Fatal(ev)
}
ev := mustActivity(t, scan)
if ev.Kind != "request_dropped" || ev.Route.Phase != phaseDropped || ev.Active != 0 {
t.Fatal("not told the route went:", ev)
}
s.trace.begin(Route{Time: time.Now(), Agent: "next"})
if ev := mustActivity(t, scan); ev.Kind != "request_started" || ev.Route.Agent != "next" {
t.Fatal("told of the dropped route after it went:", ev)
}
}
// A stream ends once the gateway stops serving, for Shutdown not to
// wait its whole drain (15 minutes when handed over) for a display.
func TestRouteEventsEndWithTheGateway(t *testing.T) {
fresh(t)
s := New()
srv := httptest.NewServer(lanGuard(s.Handler()))
t.Cleanup(srv.Close) // after each stream's body is closed
res := activityStream(t, srv.URL, "", activitySnapshot(t, srv.URL, "").Cursor)
ended := make(chan struct{})
go func() {
defer close(ended)
io.Copy(io.Discard, res.Body)
}()
s.endStreams()
select {
case <-ended:
case <-time.After(10 * time.Second):
t.Fatal("the stream outlived the gateway's end")
}
}
// A request that falls back from a member refusing it to one that
// streams is told live, its first content as it comes, with the
// provider and model that answered, while another request goes beside
// it; and none of their prompts or replies.
func TestRouteEventsLiveFallback(t *testing.T) {
fresh(t)
_, key := displayKey(t)
release := make(chan struct{})
var once sync.Once
finish := func() { once.Do(func() { close(release) }) }
defer finish()
slowOn(t, "a", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Error(w, "quota exhausted", 429)
}))
slowOn(t, "b", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
io.WriteString(w, "data: {\"choices\":[{\"delta\":{\"content\":\"private-reply\"}}]}\n\n")
w.(http.Flusher).Flush()
select {
case <-release:
case <-r.Context().Done():
}
io.WriteString(w, "data: [DONE]\n\n")
}))
if err := provider.SaveGroup(provider.Group{Name: "G", Members: []string{"a/m", "b/m"}, Routing: provider.Ordered}); err != nil {
t.Fatal(err)
}
s := New()
srv := httptest.NewServer(lanGuard(s.Handler()))
t.Cleanup(srv.Close) // after each stream's body is closed
defer finish()
stream := activityStream(t, srv.URL, key, activitySnapshot(t, srv.URL, key).Cursor)
scan := bufio.NewScanner(stream.Body)
done := make(chan error, 2)
for i := 0; i < 2; i++ {
go func() {
req, _ := http.NewRequest("POST", srv.URL+"/v1/chat/completions", strings.NewReader(`{"model":"group/g","stream":true,"messages":[{"role":"user","content":"private-prompt"}]}`))
req.Header.Set("Authorization", "Bearer "+Token)
req.Header.Set(SessionHeader, "private-session")
res, err := (&http.Client{Timeout: 20 * time.Second}).Do(req)
if err == nil {
_, err = io.Copy(io.Discard, res.Body)
res.Body.Close()
}
done <- err
}()
}
first := map[string]bool{}
fallback := false
for len(first) < 2 {
ev := mustActivity(t, scan)
if ev.Kind == "first_content" {
if ev.Route.Provider != "b" || ev.Route.Model != "m" || ev.Route.TTFT <= 0 || ev.Route.Phase != phaseResponding {
t.Fatal(ev)
}
first[ev.Route.ID] = true
fallback = fallback || ev.Route.Fallback
}
if b, _ := json.Marshal(ev); strings.Contains(string(b), "private-") {
t.Fatalf("content leaked: %s", b)
}
}
if snap := activitySnapshot(t, srv.URL, key); len(snap.Routes) != 2 || !fallback {
t.Fatalf("live requests: %d, fallback: %v", len(snap.Routes), fallback)
}
finish()
for n := 0; n < 2; {
if ev := mustActivity(t, scan); ev.Kind == "request_finished" {
n++
}
}
for i := 0; i < 2; i++ {
if err := <-done; err != nil {
t.Fatal(err)
}
}
if snap := activitySnapshot(t, srv.URL, key); len(snap.Routes) != 0 {
t.Fatal(snap)
}
// the full trace's TTFT is the try's own, told once it is done
s.trace.mu.Lock()
defer s.trace.mu.Unlock()
for _, r := range s.trace.routes {
for _, tr := range r.Tries {
if tr.Done && tr.Status == 200 && tr.TTFT <= 0 {
t.Errorf("a streamed try's TTFT: %+v", tr)
}
}
}
}
+24 -1
View File
@@ -55,8 +55,11 @@ type Route struct {
imageProvider string
// turn: a request of an agent's turn, for the notification that it is
// done (turns); dirOf, the folder its body says, read once as a turn
// starts; tools, whether its reply called a tool
// starts; tools, whether its reply called a tool; offFeed, it left
// the trace unfinished (drop, trim) and the route-events feed was
// told it went, so it hears no more of it
turn bool
offFeed bool
dirOf func() string
tools *toolScan
Seq int64 `json:"seq"` // the trace's count when it last changed
@@ -405,6 +408,10 @@ type Try struct {
// first text, when it streamed any (#196)
TTFT int64 `json:"ttft,omitempty"`
FirstText int64 `json:"firstText,omitempty"`
// firstMs: ms from Start to the first content, as it came, while the
// try still streams (firstContent); the route-events feed's alone,
// TTFT being told once the try is done
firstMs int64
// SentBy: what sent its request to the vendor when magpie's own
// client didn't, so it has no Net and the Routing page says why
// (sentBy)
@@ -572,6 +579,8 @@ type trace struct {
routes []*Route
wake chan struct{}
totals Totals
// activity is the route-events feed's last changes (route_events.go)
activity routeActivityLog
// bodies are the last requests' masked bodies, for their prompts'
// text (PromptText): in memory only, never in the history
bodies []keptBody
@@ -675,6 +684,7 @@ func (t *trace) begin(r Route) *Route {
t.trim()
t.changed()
rp.Seq = t.seq
t.noteActivity(rp, "request_started")
return rp
}
@@ -748,7 +758,13 @@ func (t *trace) trim() {
}
i = 0
}
gone := t.routes[i]
t.routes = slices.Delete(t.routes, i, i+1)
if !gone.Done {
// a request still going is dropped only past twice traceKeep:
// the route-events feed is told it went, as it hears of no end
t.noteDropped(gone)
}
}
}
@@ -760,6 +776,9 @@ func (t *trace) drop(rt *Route) {
if i := slices.Index(t.routes, rt); i >= 0 {
t.routes = slices.Delete(t.routes, i, i+1)
t.changed()
if !rt.Done {
t.noteDropped(rt)
}
}
}
@@ -781,6 +800,7 @@ func (t *trace) update(r *Route, f func(r *Route)) {
t.mu.Lock()
defer t.mu.Unlock()
done := r.Done
before := activityOf(r)
f(r)
if r.Done && !done {
t.totals.Requests++
@@ -804,6 +824,9 @@ func (t *trace) update(r *Route, f func(r *Route)) {
}
t.changed()
r.Seq = t.seq
if after := activityOf(r); before != after {
t.noteActivity(r, activityChange(before, after))
}
}
// gatewayTrace tells this gateway's routing to another magpie on the same
+4
View File
@@ -22,6 +22,7 @@ const firstMost = 8 << 20
// firstToken times a stream's first content and first text from start,
// and when the rest of its content came (flowMs).
type firstToken struct {
onFirst func(int64)
start time.Time
first time.Duration // to the first content; 0 until it comes
text time.Duration // to the first text
@@ -92,6 +93,9 @@ func (f *firstToken) see(b []byte) {
}
if f.first == 0 {
f.first = d
if f.onFirst != nil {
f.onFirst(d.Milliseconds())
}
}
f.mark(d, len(ev))
if text {