Исправить замечания ревью кода: убрать повтор в AppendOnce за счёт запаса у чистки ключей, вынести MessagePayload и SameContent, принять X-Request-Id от балансировщика, упростить фоновые задачи сервера, сократить комментарии

This commit is contained in:
2026-11-04 12:19:49 +03:00
parent c9d0f73221
commit 7fbd781ca3
25 changed files with 207 additions and 247 deletions
+16 -4
View File
@@ -193,10 +193,22 @@ func TestSuccessResponseHeadersAndEscaping(t *testing.T) {
}
}
func TestRequestIDIsGeneratedNotEchoed(t *testing.T) {
rec, _ := do(t, newEngine(t, nil), http.MethodGet, "/ok", "", map[string]string{"X-Request-Id": "client-chosen"})
if got := rec.Header().Get("X-Request-Id"); got == "" || got == "client-chosen" {
t.Fatalf("X-Request-Id = %q, want a server generated value", got)
// The balancer sets X-Request-Id on every request, overwriting what the
// client sent; the API keeps it so that one id spans both logs.
func TestRequestIDFromTheBalancerIsKept(t *testing.T) {
const fromLB = "0123456789abcdef0123456789abcdef"
rec, _ := do(t, newEngine(t, nil), http.MethodGet, "/ok", "", map[string]string{"X-Request-Id": fromLB})
if got := rec.Header().Get("X-Request-Id"); got != fromLB {
t.Fatalf("X-Request-Id = %q, want %q", got, fromLB)
}
}
func TestMalformedRequestIDIsReplaced(t *testing.T) {
for _, bad := range []string{"has space", "semi;colon", "tab\there", strings.Repeat("a", 65)} {
rec, _ := do(t, newEngine(t, nil), http.MethodGet, "/ok", "", map[string]string{"X-Request-Id": bad})
if got := rec.Header().Get("X-Request-Id"); got == "" || got == bad {
t.Errorf("X-Request-Id for %q = %q, want a generated value", bad, got)
}
}
}
+17 -13
View File
@@ -7,6 +7,7 @@ import (
"fmt"
"log/slog"
"net/http"
"regexp"
"runtime/debug"
"time"
@@ -22,22 +23,17 @@ func instance(id string) gin.HandlerFunc {
}
}
// requestID assigns a fresh identifier to every request.
//
// An incoming X-Request-Id is deliberately not reused. This service is
// client-facing: there is no trusted upstream that could have minted the
// value, so honouring it would let any caller pick an arbitrary string that
// ends up in logs (log injection, unbounded length) or collides with another
// request and corrupts log correlation. Reusing the header is the right
// choice only when the caller is a trusted proxy or a sibling service that
// propagates one id across a chain of calls.
var requestIDPattern = regexp.MustCompile(`^[A-Za-z0-9-]{1,64}$`)
// requestID keeps the X-Request-Id set by the load balancer, which overwrites
// any value a client sends; a malformed value is replaced, so a direct caller
// cannot inject into the logs.
func requestID(log *slog.Logger) gin.HandlerFunc {
return func(c *gin.Context) {
var raw [16]byte
if _, err := rand.Read(raw[:]); err != nil {
panic("httpx: random source unavailable: " + err.Error())
id := c.GetHeader("X-Request-Id")
if !requestIDPattern.MatchString(id) {
id = newRequestID()
}
id := hex.EncodeToString(raw[:])
c.Set(keyRequestID, id)
c.Set(keyLogger, log)
c.Writer.Header().Set("X-Request-Id", id)
@@ -45,6 +41,14 @@ func requestID(log *slog.Logger) gin.HandlerFunc {
}
}
func newRequestID() string {
var raw [16]byte
if _, err := rand.Read(raw[:]); err != nil {
panic("httpx: random source unavailable: " + err.Error())
}
return hex.EncodeToString(raw[:])
}
// accessLog writes one line per request at a level that follows the
// outcome (2xx debug, 4xx info, 5xx error), so the ordinary log level decides
// how much traffic is recorded. Headers, query strings and bodies are never