feat(platform): tag requests, logs and api errors with a request id
A well-formed X-Request-ID from a proxy is kept, otherwise a UUIDv7 is generated. The ID is echoed in the response header, added to every log record written with the request context and returned in API error bodies. Closes #44 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
This commit is contained in:
1 parent
b6843330a8
commit
c485d1a96f
6 files changed
+191
-12
No files matched your search
@@ -0,0 +1,53 @@
|
||||
// Package requestid assigns every HTTP request an ID that ties together the
|
||||
// response, all log lines written for it and error reports from users.
|
||||
package requestid
|
||||
|
||||
import (
|
||||
"context"
|
||||
"regexp"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// Header carries the ID in both directions.
|
||||
const Header = "X-Request-ID"
|
||||
|
||||
// Incoming IDs end up in logs and response headers, so anything beyond a
|
||||
// conservative token alphabet is replaced rather than passed through.
|
||||
var valid = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
|
||||
|
||||
type ctxKey struct{}
|
||||
|
||||
// NewContext returns ctx carrying id.
|
||||
func NewContext(ctx context.Context, id string) context.Context {
|
||||
return context.WithValue(ctx, ctxKey{}, id)
|
||||
}
|
||||
|
||||
// FromContext returns the request ID in ctx, or "" outside a request.
|
||||
func FromContext(ctx context.Context) string {
|
||||
id, _ := ctx.Value(ctxKey{}).(string)
|
||||
return id
|
||||
}
|
||||
|
||||
// Middleware keeps a well-formed X-Request-ID set by a proxy in front of us
|
||||
// and otherwise generates a time-ordered UUIDv7, so IDs sort by arrival.
|
||||
// It must run before any middleware that logs.
|
||||
func Middleware() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
id := c.GetHeader(Header)
|
||||
if !valid.MatchString(id) {
|
||||
id = newID()
|
||||
}
|
||||
c.Request = c.Request.WithContext(NewContext(c.Request.Context(), id))
|
||||
c.Header(Header, id)
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
func newID() string {
|
||||
if id, err := uuid.NewV7(); err == nil {
|
||||
return id.String()
|
||||
}
|
||||
return uuid.NewString()
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package requestid
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func TestMiddleware(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
incoming string
|
||||
keep bool
|
||||
}{
|
||||
{name: "none", incoming: "", keep: false},
|
||||
{name: "uuid from proxy", incoming: "0b9a7c3e-6a43-4d2c-9a55-2f3b1c0d4e5f", keep: true},
|
||||
{name: "trace style", incoming: "Root=1-5759e988-bd862e3fe1be46a994272793", keep: false},
|
||||
{name: "opaque token", incoming: "edge:abc.123_X", keep: true},
|
||||
{name: "header injection", incoming: "abc\r\nSet-Cookie: x=y", keep: false},
|
||||
{name: "too long", incoming: strings.Repeat("a", 129), keep: false},
|
||||
}
|
||||
gin.SetMode(gin.TestMode)
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
var seen string
|
||||
r := gin.New()
|
||||
r.Use(Middleware())
|
||||
r.GET("/", func(c *gin.Context) { seen = FromContext(c.Request.Context()) })
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/", nil)
|
||||
if tt.incoming != "" {
|
||||
req.Header.Set(Header, tt.incoming)
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
got := w.Header().Get(Header)
|
||||
if got != seen {
|
||||
t.Errorf("response header %q != context ID %q", got, seen)
|
||||
}
|
||||
if tt.keep {
|
||||
if got != tt.incoming {
|
||||
t.Errorf("ID = %q, want incoming %q", got, tt.incoming)
|
||||
}
|
||||
return
|
||||
}
|
||||
if u, err := uuid.Parse(got); err != nil || u.Version() != 7 {
|
||||
t.Errorf("ID = %q, want generated UUIDv7", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user