droboticflow/internal/api/diagnostic_trace.go

65 lines
2.1 KiB
Go

package api
import (
"crypto/rand"
"droboticflow/internal/store"
"encoding/hex"
"encoding/json"
"log"
"net/http"
"strings"
"time"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
)
// Correlate customer diagnostics without recording credentials, URLs, bodies,
// account identifiers or presigned storage links. Never trust a caller's ID.
// Any /api request slower than slowRequestLogThreshold also logs method, path
// and duration (path only, never the query string) so page-level latency
// regressions surface without per-handler instrumentation.
const slowRequestLogThreshold = time.Second
func diagnosticTrace(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !strings.HasPrefix(r.URL.Path, "/api/") {
next.ServeHTTP(w, r)
return
}
var entropy [16]byte
if _, err := rand.Read(entropy[:]); err != nil {
next.ServeHTTP(w, r)
return
}
id := hex.EncodeToString(entropy[:])
ctx, observation := store.WithReadObservation(r.Context(), id)
r = r.WithContext(ctx)
w.Header().Set("X-Request-ID", id)
started := time.Now()
wrapped := middleware.NewWrapResponseWriter(w, r.ProtoMajor)
next.ServeHTTP(wrapped, r)
elapsed := time.Since(started)
kind := ""
if r.URL.Path == "/api/auth/login" {
kind = "login"
} else if r.Header.Get("X-Diagnostic-Request") == "1" {
kind = "diagnostic"
}
metrics, _ := json.Marshal(observation.Snapshot())
if kind != "" {
log.Printf("request_trace id=%s kind=%s status=%d elapsed_ms=%d observations=%s", id, kind, wrapped.Status(), elapsed.Milliseconds(), metrics)
} else if elapsed >= slowRequestLogThreshold || wrapped.Status() >= 500 {
route := "/api/<unmatched>"
if rc := chi.RouteContext(r.Context()); rc != nil && rc.RoutePattern() != "" {
route = rc.RoutePattern()
}
reason := "slow"
if elapsed < slowRequestLogThreshold {
reason = "failed"
}
log.Printf("request_trace id=%s kind=%s method=%s path=%s status=%d elapsed_ms=%d observations=%s", id, reason, r.Method, route, wrapped.Status(), elapsed.Milliseconds(), metrics)
}
})
}