droboticflow/internal/api/diagnostic_trace.go
d-robotics ba5c9909e5 ⚡ Fix annotation-center slow loads across roles: filter pushdown, per-task draft join, manager fast path, workload cache, slow-request tracing
- Task pool: push status/supplier/workflow/run/node/artifact equality filters into ListAnnotationTasksFiltered (new store method, backed by organizationId+createdAt indexes) instead of post-filtering an organization-wide scan
- Human items join: ListHumanItemsByLegacyTaskIDs fetches only the listed tasks' items via the organizationId+legacyTaskId index; TaskListProjection now drops annotationDraft too
- Draft progress: ListHumanItemDraftProgress loads slice/segment drafts per filtered task only (batched $in, new projection reads just legacyTaskId + draft payload); draft overrides revision only when the human item was touched after the latest slice revision
- Manager fast path: admin views skip the request-scoped batch snapshot, membership and supplier-pool reads entirely
- Workload summary: 45s per-user response cache (any /api write invalidates), mirroring the dashboard workforce route
- Tracing: any /api request over 1s now logs method/path/duration so page-level latency regressions surface without per-handler instrumentation; task list log gains drafts_ms segment
- Tests: draft-progress override semantics, manager scan-free path, store filter pushdown; v5 fixture users get SupplierID to match the supplier-unified account model (pre-existing red since c92bca16, 18 stock failures recovered green)

Co-authored-by: AgentTeams slow-page-fix-round3
2026-10-11 22:14:43 +05:30

51 lines
1.6 KiB
Go

package api
import (
"crypto/rand"
"encoding/hex"
"log"
"net/http"
"strings"
"time"
"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[:])
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"
}
if kind != "" {
log.Printf("request_trace id=%s kind=%s status=%d elapsed_ms=%d", id, kind, wrapped.Status(), elapsed.Milliseconds())
} else if elapsed >= slowRequestLogThreshold {
log.Printf("request_trace id=%s kind=slow method=%s path=%s status=%d elapsed_ms=%d", id, r.Method, r.URL.Path, wrapped.Status(), elapsed.Milliseconds())
}
})
}