diff --git a/internal/gateway/held_report.go b/internal/gateway/held_report.go index 1c8f92da5..400735246 100644 --- a/internal/gateway/held_report.go +++ b/internal/gateway/held_report.go @@ -118,9 +118,9 @@ func HeldReport(name string) (string, error) { } // heldReport is the report of u's request, held for held and stopped. -func (s *Server) heldReport(u *unroutedHold, held time.Duration, who, asked, where string) string { +func (s *Server) heldReport(u *unroutedHold, held time.Duration, status int, who, asked, where string) string { var b strings.Builder - fmt.Fprintf(&b, "magpie held a request before routing it, and stopped it with 504\n\n") + fmt.Fprintf(&b, "magpie held a request before routing it, and stopped it with %d\n\n", status) fmt.Fprintf(&b, "time: %s\n", time.Now().UTC().Format(time.RFC3339)) fmt.Fprintf(&b, "magpie: %s (%s/%s, served by %s)\n", cmpOr(Version, "dev"), runtime.GOOS, runtime.GOARCH, cmpOr(Serves, "?")) fmt.Fprintf(&b, "request: %s %s\n", u.r.Method, u.r.URL.Path) @@ -128,6 +128,9 @@ func (s *Server) heldReport(u *unroutedHold, held time.Duration, who, asked, whe fmt.Fprintf(&b, "agent: %s\n", who) fmt.Fprintf(&b, "held: %s,%s\n", held, where) fmt.Fprintf(&b, "known waits:%s\n", cmpOr(strings.TrimPrefix(u.waitsSaid(), ";"), " none")) + // a slow body from a body that stopped coming: what had come, and + // when the last of it did + fmt.Fprintf(&b, "body read: %s\n", u.bodySaid()) bodyRoom.mu.Lock() fmt.Fprintf(&b, "body room: %d of %d bytes held (%s), %d waiting\n", bodyRoom.held, bodyRoom.room, cmpOr(bodyRoom.why, "unset"), len(bodyRoom.queue)) bodyRoom.mu.Unlock() diff --git a/internal/gateway/unrouted.go b/internal/gateway/unrouted.go index 921aef9d4..a33985d55 100644 --- a/internal/gateway/unrouted.go +++ b/internal/gateway/unrouted.go @@ -207,6 +207,12 @@ type unroutedHold struct { // masking counts the maskings under way for it: one held there waits // for Settings → Privacy's local model, and its error says so masking atomic.Int32 + // the body as it arrives (waitedBody): the bytes read, when the last + // came (unix nanoseconds), and stopped once magpie answered for it + // while it was still arriving, so its handler reads no more of it + bodyRead atomic.Int64 + bodyLast atomic.Int64 + bodyStopped atomic.Bool // the waits magpie knows it is in (noteWait), under wmu: how many are // under way, since when one has been, the time spent in one before @@ -439,9 +445,64 @@ type waitedBody struct { } func (b waitedBody) Read(p []byte) (int, error) { + if b.u.bodyStopped.Load() { + return 0, errBodyStopped + } done := b.u.wait("body") defer done() - return b.ReadCloser.Read(p) + n, err := b.ReadCloser.Read(p) + if n > 0 { + b.u.bodyRead.Add(int64(n)) + b.u.bodyLast.Store(time.Now().UnixNano()) + } + return n, err +} + +// errBodyStopped is a body read after magpie answered for its request +// while the body was still arriving. +var errBodyStopped = errors.New("magpie stopped reading this request's body: it was still arriving when magpie answered for it") + +// inBody is whether u's request is reading its body now. +func (u *unroutedHold) inBody() bool { + u.wmu.Lock() + defer u.wmu.Unlock() + for _, k := range u.kinds { + if k.kind == "body" { + return k.n > 0 + } + } + return false +} + +// bodySaid is how much of u's request's body had come, and when the last +// of it did: "12 KB of 3 MB, the last 2s ago". +func (u *unroutedHold) bodySaid() string { + n, of := u.bodyRead.Load(), "" + if d := u.r.ContentLength; d > 0 { + of = " of " + byteWord(d) + } + if n == 0 { + return "none" + of + } + return fmt.Sprintf("%s%s, the last %s ago", byteWord(n), of, time.Since(time.Unix(0, u.bodyLast.Load())).Round(100*time.Millisecond)) +} + +// byteWord is n bytes in B, KB or MB. +func byteWord(n int64) string { + switch { + case n >= 1<<20: + return fmt.Sprintf("%.1f MB", float64(n)/(1<<20)) + case n >= 1<<10: + return fmt.Sprintf("%.1f KB", float64(n)/(1<<10)) + } + return fmt.Sprintf("%d bytes", n) +} + +// unroutedBodyMsg is the error of a request whose body was still arriving +// when it had been held for held: the time went to the client sending it, +// not to magpie, and it says so. +func unroutedBodyMsg(held time.Duration, body string) string { + return fmt.Sprintf("magpie stopped this request after %s because its body was still arriving from the client (read: %s), before it could be routed to any provider. The client is sending its body slowly (or a proxy between them is). Send it again. "+heldSay, held, body, heldWhere()) } // watchUnrouted watches r, counted as f, until the func it answers is @@ -535,17 +596,29 @@ func (u *unroutedHold) giveUp(unknown bool) { return } held := time.Since(f.start).Round(time.Second) - msg, where := unroutedMsg(held, u.masking.Load() > 0), "" + msg, where, status := unroutedMsg(held, u.masking.Load() > 0), "", http.StatusGatewayTimeout switch { case unknown: where = fmt.Sprintf(" %s of it in no wait magpie knows of", unroutedUnknown) case u.masking.Load() > 0: where = " masking it" + case u.inBody(): + // the client was still sending it (heatonz on Discord: 2m0s + // "without routing" with the body half in): a 408 says whose + // the time was, and an SDK sends it again at once + where = " its body still arriving (" + u.bodySaid() + ")" + msg, status = unroutedBodyMsg(held, u.bodySaid()), http.StatusRequestTimeout } - if !u.w.answer(unroutedProto(u.r.URL.Path), http.StatusGatewayTimeout, msg) { + if !u.w.answer(unroutedProto(u.r.URL.Path), status, msg) { f.mu.Unlock() return // the handler is answering } + if status == http.StatusRequestTimeout { + // and the handler reads no more of it: its read ends now, not at + // the next idle limit, and the connection goes with the answer + u.bodyStopped.Store(true) + _ = http.NewResponseController(u.w.w).SetReadDeadline(time.Now()) + } u.ended = true if u.shown == nil { u.showLocked() @@ -553,14 +626,14 @@ func (u *unroutedHold) giveUp(unknown bool) { shown := u.shown f.mu.Unlock() u.s.trace.update(shown, func(r *Route) { - r.Done, r.Status, r.Error, r.Millis = true, http.StatusGatewayTimeout, msg, time.Since(r.Time).Milliseconds() + r.Done, r.Status, r.Error, r.Millis = true, status, msg, time.Since(r.Time).Milliseconds() }) // the report is taken while it is still held: once its context ends, // what held it lets go, and the stacks would show it gone asked, _ := u.asked.Load().(string) who := cmpOr(u.agent, cmpOr(f.agent, "?")) where = cmpOr(where, " not masking it") - report := u.s.heldReport(u, held, who, asked, where) + report := u.s.heldReport(u, held, status, who, asked, where) u.cancel(errUnrouted) name, err := writeHeld(report) saved := "" @@ -570,7 +643,7 @@ func (u *unroutedHold) giveUp(unknown bool) { saved = "; its report is " + filepath.Join(HeldDir(), name) u.s.trace.update(shown, func(r *Route) { r.Held = name }) } - log.Printf("gateway: %s %s for %s from %s held %s before routing,%s%s; stopped with 504%s%s", u.r.Method, u.r.URL.Path, cmpOr(asked, "?"), who, held, where, u.waitsSaid(), saved, unroutedStacks()) + log.Printf("gateway: %s %s for %s from %s held %s before routing,%s%s; stopped with %d%s%s", u.r.Method, u.r.URL.Path, cmpOr(asked, "?"), who, held, where, u.waitsSaid(), status, saved, unroutedStacks()) } // unroutedMsg is the error of a request held for held before routing: diff --git a/internal/gateway/unrouted_body_test.go b/internal/gateway/unrouted_body_test.go new file mode 100644 index 000000000..a5de17857 --- /dev/null +++ b/internal/gateway/unrouted_body_test.go @@ -0,0 +1,101 @@ +package gateway + +import ( + "bufio" + "fmt" + "io" + "net" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" +) + +// heatonz on Discord (Hermes Agent to magpie in Docker): requests held +// 2m0s "without routing it to any provider", the report's one wait "body +// 2m0s (under way)". A body that keeps coming, a byte at a time and never +// idle for the read's own limit, reached unroutedMost while it was still +// being read. It is answered 408, saying the body was still arriving and +// how much had come, and its read ends with the answer: the handler +// doesn't go on reading a body nobody will route. +func TestUnroutedTrickledBodyAnswered408(t *testing.T) { + t.Setenv("XDG_CACHE_HOME", t.TempDir()) + unroutedLimits(t, 20*time.Millisecond, 500*time.Millisecond) + s, _ := slowEyed(t, 0) + srv := httptest.NewServer(s.Handler()) + t.Cleanup(srv.Close) + + // 40 bytes a second for 400 bytes: ten seconds, far past unroutedMost + body := unroutedHi + strings.Repeat(" ", 400-len(unroutedHi)) + conn, err := net.Dial("tcp", strings.TrimPrefix(srv.URL, "http://")) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { conn.Close() }) + conn.SetDeadline(time.Now().Add(20 * time.Second)) + fmt.Fprintf(conn, "POST /v1/chat/completions HTTP/1.1\r\nHost: 127.0.0.1\r\nContent-Type: application/json\r\nContent-Length: %d\r\n\r\n", len(body)) + stop := make(chan struct{}) + t.Cleanup(func() { close(stop) }) + go func() { + for i := 0; i < len(body); i++ { + select { + case <-stop: + return + case <-time.After(25 * time.Millisecond): + } + if _, err := conn.Write([]byte{body[i]}); err != nil { + return + } + } + }() + + br := bufio.NewReader(conn) + res, err := http.ReadResponse(br, nil) + if err != nil { + t.Fatal(err) + } + b, _ := io.ReadAll(res.Body) + res.Body.Close() + answered := time.Now() + if res.StatusCode != http.StatusRequestTimeout || !strings.Contains(string(b), "its body was still arriving") || !strings.Contains(string(b), "of 400 bytes, the last") { + t.Fatalf("a body still arriving at unroutedMost was answered %d %s", res.StatusCode, b) + } + // the connection ends with the answer, long before the body would + if _, err := br.ReadByte(); err != io.EOF && !isClosedConn(err) { + t.Fatalf("after the 408 the connection read %v, not its end", err) + } + if waited := time.Since(answered); waited > 3*time.Second { + t.Fatalf("the connection ended %v after the 408: its handler read on", waited) + } + + // the model isn't read yet, so its route names none; the report is + // saved after the answer + for deadline := time.Now().Add(10 * time.Second); ; time.Sleep(10 * time.Millisecond) { + for _, r := range routesOf(s, "") { + if r.Held == "" { + continue + } + if r.Status != http.StatusRequestTimeout { + t.Errorf("its route says %d", r.Status) + } + text, err := HeldReport(r.Held) + if err != nil { + t.Fatal(err) + } + for _, want := range []string{"stopped it with 408", "body read: ", "of 400 bytes, the last", "body still arriving"} { + if !strings.Contains(text, want) { + t.Errorf("the report doesn't say %q:\n%.1500s", want, text) + } + } + return + } + if time.Now().After(deadline) { + t.Fatal("no route names the report") + } + } +} + +func isClosedConn(err error) bool { + return err != nil && (strings.Contains(err.Error(), "connection reset") || strings.Contains(err.Error(), "closed")) +}