Files
magpie/internal/gateway/middleware.go
T
yetone 5a94eec3ae gateway: a request held 30s before routing in no known wait is answered then
sharwowwow on X: "转圈两分钟才报 504,这个超时阈值本身就很折磨人。网关要是能
早点失败、早点给明确错误,排查能省不少时间。" A request held before any
route was answered 504 only after unroutedMost (2m), whatever held it.

Now the time a request spends in a wait magpie knows of is added up as it
happens (noteWait/waited, the union of overlapping waits), and a request
held unroutedUnknown (30s) outside them gets the same 504 and message
then. unroutedMost (2m) stays the cap for one in known waits. Known waits,
each read from the code between counted and noteRoute:
- the request's body arriving: r.Body is wrapped (waitedBody), so every
  read of it (keyLimited, requestBody, readRequestBody) counts;
- masking (noteMasking);
- System One's or the decision model's classifier (askWaited);
- an image's description (seenBody);
- Codex's auto reset before the route (autoReset);
- plugins' gateway hooks / plugin host start (GatewayBegin) and JS
  gateway middleware (Begin, Request);
- every notePhase (slot, rpm, upstream); these come after the route for
  watched requests today, so it only guards a future change.
What is left is magpie's own work (catalog build, parsing, planning,
affine, reading the usage log), ~8.5s at its slowest (a cold catalog
sync); 30s is about three times that, with room for a loaded machine.
The log says "30s of it in no wait magpie knows of".

Run at this tree (rebased on origin/main 9120acaff):
- gofmt -l internal/gateway: clean.
- go vet ./internal/gateway/... on darwin, GOOS=linux, GOOS=windows: ok.
- go test -timeout 45m ./internal/gateway/...: ok (478.0s).
  Also ok on the earlier bases a5ce158e5 (655.8s) and 7d075df9d (448.1s).
Not run: the full go test ./... and go vet ./..., because the machine's
disk was full (under 1GB free for over 20 minutes; a build and one
gateway run failed with "no space left on device", every red naming it). No -race run.

Broken by hand, each test red, then restored:
- without the 30s answer (u.giveUp(true)),
  TestUnroutedUnknownHoldAnsweredSooner: not answered before unroutedMost;
- without the body wrap, TestUnroutedSlowBodyNotCutOff: answered 504
  while its body was still arriving;
- without masking's excuse, TestUnroutedMaskingNotCutOff: answered 504
  while it was masked.
TestUnroutedSlotWaitNotCutOff stays green without notePhase's excuse (the
slot wait is after the route); it guards that a slot wait is never cut.

Not tried: no test of its own for the classifier, auto reset, gateway
hook, JS middleware or image-description excuses; no run in the real app
or against a real provider.
2026-10-26 19:04:27 +08:00

145 lines
4.9 KiB
Go

package gateway
import (
"context"
"net/http"
"slices"
"github.com/yetone/magpie/internal/access"
"github.com/yetone/magpie/internal/gwmw"
"github.com/yetone/magpie/internal/middleware"
"github.com/yetone/magpie/internal/plugin"
"github.com/yetone/magpie/internal/provider"
)
// serveAgent is serve for a request an agent sent: the agent middleware
// of the gateway's middleware point (gwmw.Agents: the JS gateway middleware
// plugins, internal/middleware, while plugins/middleware is on) see its
// body first, and its reply on the way back, in the agent's own API.
// magpie's own requests through serve (titles, the router's classifier,
// search and vision stand-ins) go without them, as their replies are
// magpie's to read.
func (s *Server) serveAgent(w http.ResponseWriter, r *http.Request, from provider.Protocol, body []byte) {
withGatewaySession(w, r)
w, recorded := recordConversation(w, r, from, body)
defer recorded()
// a conversation going round one tool call is answered here, before
// anything of it is asked of a hook, a middleware or a provider
if s.stoppedToolLoop(w, r, from, body) {
return
}
w, body, hooked := gatewayHooks(w, r, from, body)
defer hooked()
agents := gwmw.AgentsWanted(middlewareWanted)
if len(agents) == 0 {
s.serve(w, r, from, body)
return
}
info := gwmw.Info{Protocol: string(from), Model: modelOf(body), Stream: streamOf(body), Path: r.URL.Path, Agent: agentOf(r)}
var tried []gwmw.Tried
for _, a := range agents {
// the user's middleware runs before a route is begun: a wait
// magpie knows of (unrouted.go)
waited := noteWait(r.Context())
run := a.Begin(info)
if run == nil {
waited()
continue
}
defer run.End()
if t, ok := run.(gwmw.Tried); ok {
tried = append(tried, t)
}
var turned *gwmw.Reject
body, turned = run.Request(body)
waited()
if turned != nil {
writeError(w, from, turned.Status, turned.Message)
return
}
var done func()
w, done = run.Wrap(w)
defer done()
}
if len(tried) > 0 {
r = r.WithContext(context.WithValue(r.Context(), triedKey{}, tried))
}
s.serve(w, r, from, body)
}
type triedKey struct{}
// triedOn is body as it goes to model on p, in the agent's API: what each
// middleware of the request that is also gwmw.Tried (the JS chain's
// onProvider) made of it for that provider. Each try starts from the body
// it is given, so a change for one provider never reaches another's.
func triedOn(ctx context.Context, p provider.Provider, model string, body []byte) []byte {
tried, _ := ctx.Value(triedKey{}).([]gwmw.Tried)
if len(tried) == 0 {
return body
}
to := gwmw.To{ID: p.ID, Name: p.Name, Account: accountAgent(p), Model: model}
for _, t := range tried {
body = t.Tried(body, to)
}
return body
}
// middlewareWanted: plugins.json has a JS middleware on, so plugins/middleware
// is in use.
func middlewareWanted() bool { return middleware.On() > 0 }
// gatewayHooks runs the asynchronous request hooks (OpenCode plugins'
// gateway entries, in the plugin host) on an agent's request: the body they
// leave is the one served, and they see the reply the agent got once it is
// whole. Its writer wraps the middleware's, so what they see is what the
// agent was given. With no hook it is the request as it came.
func gatewayHooks(w http.ResponseWriter, r *http.Request, from provider.Protocol, body []byte) (http.ResponseWriter, []byte, func()) {
if !plugin.HasGateway() {
return w, body, func() {}
}
info := plugin.GatewayContext{Origin: gatewayOrigin(r), Protocol: string(from), Model: modelOf(body), Stream: streamOf(body), Path: r.URL.Path, Agent: agentOf(r), Session: sessionOf(r.Header)}
if req, err := parse(from, body); err == nil {
info.Cwd = workDir(req)
info.Query = gatewayQuery(req)
}
// the plugin host, started for it if need be: a wait magpie knows of
// before a route is begun (unrouted.go)
waited := noteWait(r.Context())
run := plugin.GatewayBegin(r.Context(), body, info)
waited()
if run == nil {
return w, body, func() {}
}
w, done := gatewayResponse(w, r, from, run.Body, run)
return w, run.Body, func() { done(); run.Close() }
}
// gatewayQuery uses the same user-authored words as routing, excluding
// agent context, tool results and images. Tool-only increments have none.
func gatewayQuery(req *Request) string {
for i := len(req.Messages) - 1; i >= 0; i-- {
m := req.Messages[i]
if m.Role != "user" {
continue
}
if query := userSaid(m); query != "" {
return query
}
}
return ""
}
// gatewayOrigin exposes provenance, never credentials or peer addresses.
// Forwarded traffic remains remote even when the administrator trusts its
// proxy for authentication: that trust does not establish conversation ownership.
func gatewayOrigin(r *http.Request) string {
if access.Caller(r.Context()).KeyID != "" || managedKey(r) {
return "gateway-key"
}
if local(r) && !slices.ContainsFunc(forwardHeaders, func(h string) bool { return r.Header.Get(h) != "" }) {
return "local"
}
return "remote"
}