feat(platform-api): return traceable timeout errors

This commit is contained in:
lingniu
2026-07-04 00:57:53 +08:00
parent 4bfaf8c4c8
commit 377cfcdfca
2 changed files with 99 additions and 1 deletions

View File

@@ -1,13 +1,16 @@
package app
import (
"bytes"
"context"
"database/sql"
"log"
"net/http"
"sync"
"time"
"lingniu/vehicle-data-platform/apps/api/internal/config"
"lingniu/vehicle-data-platform/apps/api/internal/httpx"
"lingniu/vehicle-data-platform/apps/api/internal/platform"
"lingniu/vehicle-data-platform/apps/api/internal/static"
)
@@ -42,5 +45,71 @@ func withRequestTimeout(next http.Handler, timeout time.Duration) http.Handler {
if timeout <= 0 {
return next
}
return http.TimeoutHandler(next, timeout, `{"error":{"code":"REQUEST_TIMEOUT","message":"请求处理超时"},"traceId":"timeout","timestamp":0}`)
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), timeout)
defer cancel()
buffered := newBufferedResponseWriter()
result := make(chan any, 1)
go func() {
defer func() {
result <- recover()
}()
next.ServeHTTP(buffered, r.WithContext(ctx))
}()
select {
case panicValue := <-result:
if panicValue != nil {
panic(panicValue)
}
buffered.writeTo(w)
case <-ctx.Done():
httpx.WriteError(w, http.StatusServiceUnavailable, "REQUEST_TIMEOUT", "请求处理超时", "", requestTraceID(r))
}
})
}
func requestTraceID(r *http.Request) string {
if value := r.Header.Get("X-Trace-Id"); value != "" {
return value
}
return "trace-" + time.Now().Format("20060102150405.000000")
}
type bufferedResponseWriter struct {
mu sync.Mutex
header http.Header
status int
body bytes.Buffer
}
func newBufferedResponseWriter() *bufferedResponseWriter {
return &bufferedResponseWriter{header: http.Header{}, status: http.StatusOK}
}
func (w *bufferedResponseWriter) Header() http.Header {
return w.header
}
func (w *bufferedResponseWriter) WriteHeader(statusCode int) {
w.mu.Lock()
defer w.mu.Unlock()
w.status = statusCode
}
func (w *bufferedResponseWriter) Write(body []byte) (int, error) {
w.mu.Lock()
defer w.mu.Unlock()
return w.body.Write(body)
}
func (w *bufferedResponseWriter) writeTo(target http.ResponseWriter) {
w.mu.Lock()
defer w.mu.Unlock()
for key, values := range w.header {
for _, value := range values {
target.Header().Add(key, value)
}
}
target.WriteHeader(w.status)
_, _ = target.Write(w.body.Bytes())
}

View File

@@ -1,6 +1,7 @@
package app
import (
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
@@ -27,3 +28,31 @@ func TestWithRequestTimeoutAddsContextDeadline(t *testing.T) {
t.Fatalf("status = %d", rec.Code)
}
}
func TestWithRequestTimeoutReturnsEnvelopeWithTraceID(t *testing.T) {
handler := withRequestTimeout(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
<-r.Context().Done()
}), time.Millisecond)
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/api/ops/health", nil)
req.Header.Set("X-Trace-Id", "trace-from-test")
handler.ServeHTTP(rec, req)
if rec.Code != http.StatusServiceUnavailable {
t.Fatalf("status = %d body=%s", rec.Code, rec.Body.String())
}
var body struct {
Error struct {
Code string `json:"code"`
Message string `json:"message"`
} `json:"error"`
TraceID string `json:"traceId"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
t.Fatalf("timeout response should be JSON: %v body=%s", err, rec.Body.String())
}
if body.Error.Code != "REQUEST_TIMEOUT" || body.Error.Message != "请求处理超时" || body.TraceID != "trace-from-test" {
t.Fatalf("unexpected timeout envelope: %+v body=%s", body, rec.Body.String())
}
}