fix(14.2-03): access log records a cancelled request's 5xx as 499

A client that goes away mid-request cancels the context; a handler then
fails on context.Canceled and writes a 500 nobody receives. The request
log now records it as 499 (client closed request) so a grep for 5xx shows
real server errors only.
This commit is contained in:
2026-10-11 20:27:56 +02:00
parent 66dbd5a64a
commit 4660f95e5c
4 changed files with 51 additions and 3 deletions

View File

@@ -2,6 +2,7 @@ package surf
import (
"bytes"
"context"
"encoding/json"
"log/slog"
"net/http"
@@ -122,3 +123,38 @@ func TestAccessLogSmoke(t *testing.T) {
t.Fatalf("http.access_log off still logged:\n%s", offBuf.String())
}
}
// A 5xx written after the client cancelled the request is logged as 499;
// a 5xx on a live request keeps its status.
func TestAccessLogClientClosedRequest(t *testing.T) {
for _, tc := range []struct {
name string
cancel bool
want float64
}{
{"cancelled", true, 499},
{"live", false, 500},
} {
t.Run(tc.name, func(t *testing.T) {
app := backpack.New(writeHTTPConfig(t, "access_log: true\n"))
var buf bytes.Buffer
if err := app.Publish(slog.New(slog.NewJSONHandler(&buf, nil))); err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
h := accessLog(app, http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
if tc.cancel {
cancel()
}
w.WriteHeader(http.StatusInternalServerError)
}))
req := httptest.NewRequest(http.MethodGet, "/blog/posts/7", nil).WithContext(ctx)
h.ServeHTTP(httptest.NewRecorder(), req)
recs := accessRecords(t, &buf)
if len(recs) != 1 || recs[0]["status"] != tc.want {
t.Fatalf("records=%v, want one with status %v", recs, tc.want)
}
})
}
}