Skip to content

Commit f22dc50

Browse files
Dev AgentQinYuuuu
authored andcommitted
Fix request id dup in rsp header
1 parent d040474 commit f22dc50

File tree

5 files changed

+29
-24
lines changed

5 files changed

+29
-24
lines changed

api/handler/internal_service_proxy.go

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import (
66

77
"github.com/gin-gonic/gin"
88
"opencsg.com/csghub-server/builder/proxy"
9+
"opencsg.com/csghub-server/common/utils/trace"
910
)
1011

1112
type InternalServiceProxyHandler struct {
@@ -25,6 +26,9 @@ func (h *InternalServiceProxyHandler) Proxy(ctx *gin.Context) {
2526
// Log the request URL and header
2627
slog.Debug("http request", slog.Any("request", ctx.Request.URL), slog.Any("header", ctx.Request.Header))
2728

29+
// Propagate trace ID to backend service
30+
trace.PropagateTrace(ctx.Request.Context(), ctx.Request.Header)
31+
2832
// Serve the request using the router
2933
h.rp.ServeHTTP(ctx.Writer, ctx.Request, "", "")
3034
}
@@ -37,6 +41,10 @@ func (h *InternalServiceProxyHandler) Proxy(ctx *gin.Context) {
3741
func (h *InternalServiceProxyHandler) ProxyToApi(api string, originParams ...string) gin.HandlerFunc {
3842
return func(ctx *gin.Context) {
3943
slog.Info("proxy user request", slog.Any("request", ctx.Request.URL), slog.Any("header", ctx.Request.Header))
44+
45+
// Propagate trace ID to backend service
46+
trace.PropagateTrace(ctx.Request.Context(), ctx.Request.Header)
47+
4048
finalApi := api
4149
if len(originParams) > 0 {
4250
var params []any

api/middleware/log.go

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,8 +30,6 @@ func Log() gin.HandlerFunc {
3030
slog.Any("auth_type", httpbase.GetAuthType(ctx)),
3131
slog.String("url", ctx.Request.URL.RequestURI()),
3232
slog.String("full_path", ctx.FullPath()),
33-
slog.String("req_header_range", ctx.GetHeader("Range")),
34-
slog.String("rsp_content_range", ctx.Writer.Header().Get("Content-Range")),
3533
)
3634
}
3735
}

builder/proxy/reverse_proxy.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import (
77
"net/url"
88

99
"github.com/openai/openai-go/v3"
10+
"opencsg.com/csghub-server/common/utils/trace"
1011
)
1112

1213
type ReverseProxy interface {
@@ -74,6 +75,9 @@ func (rp *reverseProxyImpl) ServeHTTP(w http.ResponseWriter, r *http.Request, ap
7475
resp.Header.Del("Access-Control-Allow-Headers")
7576
resp.Header.Del("Access-Control-Allow-Methods")
7677
resp.Header.Del("Access-Control-Allow-Origin")
78+
// remove duplicate X-Request-Id header from downstream response
79+
// because it is already set by the gateway middleware
80+
resp.Header.Del(trace.HeaderRequestID)
7781

7882
return nil
7983
}

builder/rpc/http_client.go

Lines changed: 4 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,7 @@ import (
1919
slogmulti "github.com/samber/slog-multi"
2020
"go.opentelemetry.io/contrib/bridges/otelslog"
2121
"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
22-
"opencsg.com/csghub-server/api/httpbase"
2322
"opencsg.com/csghub-server/common/config"
24-
"opencsg.com/csghub-server/common/errorx"
2523
)
2624

2725
type HttpDoer interface {
@@ -112,7 +110,7 @@ func (c *HttpClient) Get(ctx context.Context, path string, outObj interface{}) e
112110
fullPath := fmt.Sprintf("%s%s", c.endpoint, path)
113111
req, err := http.NewRequestWithContext(ctx, http.MethodGet, fullPath, nil)
114112
if err != nil {
115-
return fmt.Errorf("failed to create request: %w", errorx.ErrInternalServerError)
113+
return fmt.Errorf("failed to create request: %w", err)
116114
}
117115
for _, opt := range c.authOpts {
118116
opt.Set(req)
@@ -125,17 +123,11 @@ func (c *HttpClient) Get(ctx context.Context, path string, outObj interface{}) e
125123
defer resp.Body.Close()
126124

127125
if resp.StatusCode != http.StatusOK {
128-
var errResp httpbase.R
129-
jsonErr := json.NewDecoder(resp.Body).Decode(&errResp)
130-
if jsonErr == nil {
131-
customErr := errorx.ParseError(errResp.Msg, errorx.ErrRemoteServiceFail, errResp.Context)
132-
return customErr
133-
}
134126
return fmt.Errorf("failed to get response, path:%s, status:%d", path, resp.StatusCode)
135127
}
136128
err = json.NewDecoder(resp.Body).Decode(outObj)
137129
if err != nil {
138-
return fmt.Errorf("failed to decode resp body in HttpClient.Get, err:%w", errorx.ErrInternalServerError)
130+
return fmt.Errorf("failed to decode resp body in HttpClient.Get, err:%w", err)
139131
}
140132
return nil
141133
}
@@ -170,19 +162,13 @@ func (c *HttpClient) Post(ctx context.Context, path string, data interface{}, ou
170162
defer resp.Body.Close()
171163

172164
if resp.StatusCode != http.StatusOK {
173-
var errResp httpbase.R
174-
jsonErr := json.NewDecoder(resp.Body).Decode(&errResp)
175-
if jsonErr == nil {
176-
customErr := errorx.ParseError(errResp.Msg, errorx.ErrRemoteServiceFail, errResp.Context)
177-
return customErr
178-
}
179165
return fmt.Errorf("failed to get response, path:%s, status:%d", path, resp.StatusCode)
180166
}
181167

182168
if outObj != nil {
183169
err = json.NewDecoder(resp.Body).Decode(outObj)
184170
if err != nil {
185-
return fmt.Errorf("failed to decode resp body in HttpClient.Post, err:%w", errorx.ErrInternalServerError)
171+
return fmt.Errorf("failed to decode resp body in HttpClient.Post, err:%w", err)
186172
}
187173
}
188174

@@ -192,11 +178,7 @@ func (c *HttpClient) Post(ctx context.Context, path string, data interface{}, ou
192178
func (c *HttpClient) Do(req *http.Request) (resp *http.Response, err error) {
193179
ctx := req.Context()
194180
fullPath := req.URL.String()
195-
traceID, traceParent, _ := trace.GetOrGenTraceIDFromContext(ctx)
196-
if traceParent != "" {
197-
req.Header.Set(trace.HeaderTraceparent, traceParent)
198-
}
199-
181+
traceID := trace.PropagateTrace(ctx, req.Header)
200182
startTime := time.Now()
201183
retryTime := time.Now()
202184
err = retry.Do(

common/utils/trace/trace.go

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import (
55
"crypto/rand"
66
"encoding/hex"
77
"fmt"
8+
"net/http"
89
"strings"
910

1011
"github.com/gin-gonic/gin"
@@ -189,3 +190,15 @@ func GetOrGenTraceIDFromContext(ctx context.Context) (traceID, traceParent strin
189190

190191
return traceID, traceParent, true
191192
}
193+
194+
// PropagateTrace propagates the trace ID and traceparent to the http header.
195+
func PropagateTrace(ctx context.Context, header http.Header) string {
196+
traceID, traceParent, _ := GetOrGenTraceIDFromContext(ctx)
197+
if traceParent != "" {
198+
header.Set(HeaderTraceparent, traceParent)
199+
}
200+
if traceID != "" {
201+
header.Set(HeaderRequestID, traceID)
202+
}
203+
return traceID
204+
}

0 commit comments

Comments
 (0)