Skip to content

Commit

Permalink
fix: set request in hook context before send request, in case of error (
Browse files Browse the repository at this point in the history
#1016)

This will be added to wundergraph/cosmo#1445, to
ensure that it's more resilient

Previously, we weren't setting the request (even when we really should
have had access), because in error cases we were exiting before setting
the request/response context. This ensures that we can pass the correct
information to the access logs
  • Loading branch information
df-wg authored Dec 16, 2024
1 parent 2d960bf commit e41bdef
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 4 deletions.
14 changes: 13 additions & 1 deletion v2/pkg/engine/datasource/httpclient/nethttpclient.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,9 +79,19 @@ func InjectResponseContext(ctx context.Context) (context.Context, *ResponseConte
return context.WithValue(ctx, responseContextKey{}, value), value
}

func setRequest(ctx context.Context, request *http.Request) {
if value, ok := ctx.Value(responseContextKey{}).(*ResponseContext); ok {
value.Request = request
}
}

func setResponseStatus(ctx context.Context, request *http.Request, response *http.Response) {
if value, ok := ctx.Value(responseContextKey{}).(*ResponseContext); ok {
value.StatusCode = response.StatusCode
if response != nil {
value.StatusCode = response.StatusCode
} else {
value.StatusCode = 0
}
value.Request = request
value.Response = response
}
Expand Down Expand Up @@ -189,6 +199,8 @@ func makeHTTPRequest(client *http.Client, ctx context.Context, url, method, head
request.Header.Set(AcceptEncodingHeader, EncodingGzip)
request.Header.Add(AcceptEncodingHeader, EncodingDeflate)

setRequest(ctx, request)

response, err := client.Do(request)
if err != nil {
return err
Expand Down
13 changes: 10 additions & 3 deletions v2/pkg/engine/resolve/loader.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,9 +62,16 @@ func newResponseInfo(res *result, subgraphError error) *ResponseInfo {
// We're using the response.Request here, because the body will be nil (since the response was read) and won't
// cause a memory leak.
if res.httpResponseContext.Response != nil {
responseInfo.Request = res.httpResponseContext.Response.Request
responseInfo.ResponseHeaders = res.httpResponseContext.Response.Header.Clone()
} else {
if res.httpResponseContext.Response.Request != nil {
responseInfo.Request = res.httpResponseContext.Response.Request
}

if res.httpResponseContext.Response.Header != nil {
responseInfo.ResponseHeaders = res.httpResponseContext.Response.Header.Clone()
}
}

if responseInfo.Request == nil {
// In cases where the request errors, the response will be nil, and so we need to get the original request
responseInfo.Request = res.httpResponseContext.Request
}
Expand Down

0 comments on commit e41bdef

Please sign in to comment.