gateway: a held request's route is done before its 504 goes (#4200)
TestUnroutedRequestShownThenAnswered went red on ubuntu CI under -race atd4a6e9315: the client had the 504, and the held request's route still said Done:false, Status:0. Cause: giveUp wrote the answer (heldWriter.answer) and only then marked the route done, with its status, error and, after writeHeld, its report's name. A client that reads the 504 and looks at the Routing page at once (or the GUI's next poll) could find the request still routing and naming no report. Not a test-only race. The class: giveUp is the only path that answers for a held request (checkMost and checkUnknown both end there). answer is split in two: claim takes the reply under heldWriter.mu (false if the handler began one; the handler's writes go nowhere from then), and send writes it. giveUp now writes the report before taking f.mu again (out of f.mu, it is a file), claims the writer, marks the route Done/Status/Error/ Millis/Held in one update, and only then sends, all under f.mu as before so the handler can't return between claim and send. A report written for a request routed or answered meanwhile is removed. The #4300 order (report taken before the answer) is kept. heldAnswered (the tests' hook once the 504 is out) is an atomic.Pointer now: with the route final before the answer, a test can end while its giveUp still runs, and -race caught the plain var read against the test's cleanup. TestUnroutedRequestShownThenAnswered holds giveUp in that hook until it has read the route, so a route ended after the answer is seen undone every time; it also checks the route names its report as it is answered. The subsystem page says the route is final before the answer. Run (mote, Go 1.26.8, at base44b762d50): - Old giveUp, new test: go test -tags nogui -race -count=5 -run 'TestUnroutedRequestShownThenAnswered$' ./internal/gateway: 5 of 5 red, "the held request's route: ... Done:false Status:0" (the issue's text). - This change: the same test -race -count=50: ok. - Broken by hand (the route update moved back after send and the hook): -count=5, 5 of 5 red at unrouted_test.go:420. - go test -tags nogui -race -count=3 -run 'Unrouted|Held' ./internal/gateway: ok. - go test -tags nogui -count=1 -timeout 45m ./internal/gateway (under suite.lock): ok (801s). - go vet -tags nogui ./internal/gateway; GOOS=linux and GOOS=windows go vet -tags nogui ./...: clean. gofmt -l: clean. - Rebased on origin/main1cb3dc435(internal/pii only): go test -tags nogui -race -count=3 -run 'Unrouted|Held' ./internal/gateway: ok. Not tried: a real held request in the app; the full ./... suite. Fixes #4200
This commit is contained in:
@@ -455,7 +455,11 @@ recorded as a prediction failure (`noPrediction`).
|
||||
With no route and nothing written, the error is sent in its client's
|
||||
protocol, whole (`Content-Length`, `Connection: close`) so the client
|
||||
has it while the handler may still be held; its context ends with
|
||||
`errUnrouted`, its route ends with the error, and the log has every
|
||||
`errUnrouted`, its route ends with the error before the answer goes
|
||||
(`heldWriter.claim` takes the reply, the route is marked done with its
|
||||
status, error and report, then `send` writes it, all under `f.mu`, so
|
||||
a client that has the 504 never finds the route still routing, #4200),
|
||||
and the log has every
|
||||
goroutine's stack (at most once in 10 minutes). The handler's writes go
|
||||
through `heldWriter`, and nowhere once magpie has answered for it.
|
||||
The desktop app's log goes only to stderr, which its user can't reach
|
||||
@@ -465,7 +469,8 @@ recorded as a prediction failure (`noPrediction`).
|
||||
the request is still held, before it is answered (the answer says
|
||||
`Connection: close`, and a client that closes on it ends the request's
|
||||
context and lets its wait go, #4300), outside `f.mu`, in `HeldDir`
|
||||
(`<cache>/held`, mode 0700), written through a temp file and renamed,
|
||||
(`<cache>/held`, mode 0700; also before the answer, and removed if the
|
||||
request was routed or answered meanwhile), written through a temp file and renamed,
|
||||
the newest `heldKept` (5) kept. It has the time, version and system,
|
||||
method and path, the model and agent, how long it was held, each kind
|
||||
of known wait and its time ("(under way)" for the one it was in), the
|
||||
|
||||
@@ -28,7 +28,7 @@ func TestUnroutedHeldReportSaved(t *testing.T) {
|
||||
// closes; its request's context ends, and the description it was
|
||||
// held in lets go. Held here until it has, the report still says
|
||||
// what held it.
|
||||
heldAnswered = func(u *unroutedHold) {
|
||||
hook := func(u *unroutedHold) {
|
||||
select {
|
||||
case <-u.r.Context().Done():
|
||||
case <-time.After(10 * time.Second):
|
||||
@@ -42,7 +42,8 @@ func TestUnroutedHeldReportSaved(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
t.Cleanup(func() { heldAnswered = nil })
|
||||
heldAnswered.Store(&hook)
|
||||
t.Cleanup(func() { heldAnswered.Store(nil) })
|
||||
|
||||
const secret = "hunter2-held-report-secret"
|
||||
body := strings.Replace(pastedImage, `"text":"read"`, `"text":"`+secret+`"`, 1)
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"log"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime/pprof"
|
||||
"strconv"
|
||||
@@ -99,7 +100,8 @@ func unroutedProto(path string) provider.Protocol {
|
||||
|
||||
// heldAnswered, when set, is called as giveUp has answered a request, its
|
||||
// client free to read the answer and close: a test holds it there.
|
||||
var heldAnswered func(u *unroutedHold)
|
||||
// A pointer, as a giveUp of a test's request may run on after it.
|
||||
var heldAnswered atomic.Pointer[func(u *unroutedHold)]
|
||||
|
||||
// errUnrouted ends a request's context when magpie stopped holding it.
|
||||
var errUnrouted = errors.New("magpie held the request too long before routing it")
|
||||
@@ -179,16 +181,26 @@ func (h *heldWriter) FlushError() error {
|
||||
// Unwrap is for http.ResponseController's deadlines.
|
||||
func (h *heldWriter) Unwrap() http.ResponseWriter { return h.w }
|
||||
|
||||
// answer writes magpie's own reply, whole, unless the handler began one.
|
||||
// Its length is said, so the client has all of it while the handler may
|
||||
// still be held: a reply of no length ends only when the handler does.
|
||||
func (h *heldWriter) answer(proto provider.Protocol, status int, msg string) bool {
|
||||
// claim takes the reply for magpie, unless the handler began one: from
|
||||
// here the handler's writes go nowhere, and send writes magpie's answer.
|
||||
// Between the two its route is ended (#4200), so a client that has the
|
||||
// answer finds the request's route done.
|
||||
func (h *heldWriter) claim() bool {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
if h.wrote || h.gaveUp {
|
||||
return false
|
||||
}
|
||||
h.gaveUp = true
|
||||
return true
|
||||
}
|
||||
|
||||
// send writes magpie's own reply, whole, once claim took it. Its length
|
||||
// is said, so the client has all of it while the handler may still be
|
||||
// held: a reply of no length ends only when the handler does.
|
||||
func (h *heldWriter) send(proto provider.Protocol, status int, msg string) {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
rec := httptest.NewRecorder()
|
||||
writeError(rec, proto, status, msg)
|
||||
out := h.w.Header()
|
||||
@@ -200,7 +212,6 @@ func (h *heldWriter) answer(proto provider.Protocol, status int, msg string) boo
|
||||
h.w.WriteHeader(status)
|
||||
h.w.Write(rec.Body.Bytes())
|
||||
_ = http.NewResponseController(h.w).Flush()
|
||||
return true
|
||||
}
|
||||
|
||||
// unroutedHold is one watched request's watch: the route that shows it
|
||||
@@ -719,44 +730,53 @@ func (u *unroutedHold) giveUp(unknown bool) {
|
||||
said := cmpOr(where, " not masking it")
|
||||
waits := u.waitsSaid()
|
||||
report := u.s.heldReport(u, held, status, who, asked, said)
|
||||
// Saved before it is answered too, so the route the answer finds
|
||||
// names it (#4200); out of f.mu, as it is a file written.
|
||||
name, err := writeHeld(report)
|
||||
f.mu.Lock()
|
||||
if len(f.begun) > 0 || u.ended || u.over {
|
||||
// routed, answered or let go meanwhile
|
||||
if len(f.begun) > 0 || u.ended || u.over || !u.w.claim() {
|
||||
// routed, answered or let go meanwhile, or the handler is
|
||||
// answering: the report is of nothing stopped
|
||||
f.mu.Unlock()
|
||||
if err == nil {
|
||||
os.Remove(filepath.Join(HeldDir(), name))
|
||||
}
|
||||
return
|
||||
}
|
||||
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
|
||||
defer close(u.saved)
|
||||
if u.shown == nil {
|
||||
u.showLocked()
|
||||
}
|
||||
shown := u.shown
|
||||
f.mu.Unlock()
|
||||
if heldAnswered != nil {
|
||||
heldAnswered(u)
|
||||
}
|
||||
u.s.trace.update(shown, func(r *Route) {
|
||||
r.Done, r.Status, r.Error, r.Millis = true, status, msg, time.Since(r.Time).Milliseconds()
|
||||
})
|
||||
u.cancel(errUnrouted)
|
||||
name, err := writeHeld(report)
|
||||
// The route is final before the answer goes (#4200): a client that
|
||||
// reads the 504 and looks at the Routing page at once finds the
|
||||
// request stopped, with its error and its report, not still routing.
|
||||
saved := ""
|
||||
if err != nil {
|
||||
saved = "; its report could not be saved: " + err.Error()
|
||||
name = ""
|
||||
} else {
|
||||
saved = "; its report is " + filepath.Join(HeldDir(), name)
|
||||
u.s.trace.update(shown, func(r *Route) { r.Held = name })
|
||||
}
|
||||
u.s.trace.update(shown, func(r *Route) {
|
||||
r.Done, r.Status, r.Error, r.Millis = true, status, msg, time.Since(r.Time).Milliseconds()
|
||||
if name != "" {
|
||||
r.Held = name
|
||||
}
|
||||
})
|
||||
u.w.send(unroutedProto(u.r.URL.Path), status, msg)
|
||||
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())
|
||||
}
|
||||
f.mu.Unlock()
|
||||
if hook := heldAnswered.Load(); hook != nil {
|
||||
(*hook)(u)
|
||||
}
|
||||
u.cancel(errUnrouted)
|
||||
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, said, waits, status, saved, unroutedStacks())
|
||||
}
|
||||
|
||||
|
||||
@@ -359,6 +359,21 @@ func TestUnroutedRequestShownThenAnswered(t *testing.T) {
|
||||
heldSight(t, s)
|
||||
srv := httptest.NewServer(s.Handler())
|
||||
t.Cleanup(srv.Close)
|
||||
// #4200: giveUp is held once its 504 is out until the test has read
|
||||
// the route, so a route ended only after the answer is seen undone
|
||||
// every time, not when the client happens to be quick.
|
||||
looked := make(chan struct{})
|
||||
var lookedOnce sync.Once
|
||||
look := func() { lookedOnce.Do(func() { close(looked) }) }
|
||||
t.Cleanup(look)
|
||||
hook := func(*unroutedHold) {
|
||||
select {
|
||||
case <-looked:
|
||||
case <-time.After(10 * time.Second):
|
||||
}
|
||||
}
|
||||
heldAnswered.Store(&hook)
|
||||
t.Cleanup(func() { heldAnswered.Store(nil) })
|
||||
|
||||
type reply struct {
|
||||
code int
|
||||
@@ -404,6 +419,10 @@ func TestUnroutedRequestShownThenAnswered(t *testing.T) {
|
||||
if len(rs) != 1 || !rs[0].Done || rs[0].Status != http.StatusGatewayTimeout || !strings.Contains(rs[0].Error, "without routing") {
|
||||
t.Fatalf("the held request's route: %+v", rs)
|
||||
}
|
||||
if rs[0].Held == "" {
|
||||
t.Fatalf("the held request's route names no report as it is answered: %+v", rs)
|
||||
}
|
||||
look()
|
||||
heldSaved(t, s)
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user