-
Notifications
You must be signed in to change notification settings - Fork 55
Map proxy errors to specific status codes instead of always 502 #131
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
alexspeller
wants to merge
1
commit into
basecamp:main
Choose a base branch
from
alexspeller:client-closed-request-status
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,171 @@ | ||
| package internal | ||
|
|
||
| import ( | ||
| "bytes" | ||
| "context" | ||
| "errors" | ||
| "fmt" | ||
| "log/slog" | ||
| "net" | ||
| "net/http" | ||
| "net/http/httptest" | ||
| "net/url" | ||
| "testing" | ||
|
|
||
| "github.com/stretchr/testify/assert" | ||
| "github.com/stretchr/testify/require" | ||
| ) | ||
|
|
||
| func TestProxyErrorHandler_clientCancellationReturnsClientClosedRequest(t *testing.T) { | ||
| handler := ProxyErrorHandler("") | ||
|
|
||
| w := httptest.NewRecorder() | ||
| r := httptest.NewRequest("GET", "/", nil) | ||
|
|
||
| handler(w, r, context.Canceled) | ||
|
|
||
| assert.Equal(t, StatusClientClosedRequest, w.Code) | ||
| assert.Empty(t, w.Body.String()) | ||
| } | ||
|
|
||
| func TestProxyErrorHandler_wrappedClientCancellationReturnsClientClosedRequest(t *testing.T) { | ||
| handler := ProxyErrorHandler("") | ||
|
|
||
| w := httptest.NewRecorder() | ||
| r := httptest.NewRequest("GET", "/", nil) | ||
|
|
||
| handler(w, r, fmt.Errorf("proxying request: %w", context.Canceled)) | ||
|
|
||
| assert.Equal(t, StatusClientClosedRequest, w.Code) | ||
| } | ||
|
|
||
| func TestProxyErrorHandler_clientCancellationIsNotLoggedAsProxyError(t *testing.T) { | ||
| var buf bytes.Buffer | ||
| original := slog.Default() | ||
| slog.SetDefault(slog.New(slog.NewJSONHandler(&buf, &slog.HandlerOptions{Level: slog.LevelInfo}))) | ||
| defer slog.SetDefault(original) | ||
|
|
||
| handler := ProxyErrorHandler("") | ||
| handler(httptest.NewRecorder(), httptest.NewRequest("GET", "/", nil), context.Canceled) | ||
|
|
||
| assert.NotContains(t, buf.String(), "Unable to proxy request") | ||
| } | ||
|
|
||
| func TestProxyErrorHandler_upstreamErrorReturnsBadGateway(t *testing.T) { | ||
| handler := ProxyErrorHandler("") | ||
|
|
||
| w := httptest.NewRecorder() | ||
| r := httptest.NewRequest("GET", "/", nil) | ||
|
|
||
| handler(w, r, errors.New("dial tcp [::1]:3000: connect: connection refused")) | ||
|
|
||
| assert.Equal(t, http.StatusBadGateway, w.Code) | ||
| } | ||
|
|
||
| func TestProxyErrorHandler_connectionRefusedReturnsBadGateway(t *testing.T) { | ||
| handler := ProxyErrorHandler("") | ||
|
|
||
| w := httptest.NewRecorder() | ||
| r := httptest.NewRequest("GET", "/", nil) | ||
|
|
||
| // A real connection-refused error is a net.Error, but it is not a timeout, | ||
| // so it must still be treated as a bad gateway rather than a 504. | ||
| err := &net.OpError{Op: "dial", Net: "tcp", Err: errors.New("connect: connection refused")} | ||
| require.False(t, err.Timeout()) | ||
|
|
||
| handler(w, r, err) | ||
|
|
||
| assert.Equal(t, http.StatusBadGateway, w.Code) | ||
| } | ||
|
|
||
| func TestProxyErrorHandler_upstreamTimeoutReturnsGatewayTimeout(t *testing.T) { | ||
| handler := ProxyErrorHandler("") | ||
|
|
||
| w := httptest.NewRecorder() | ||
| r := httptest.NewRequest("GET", "/", nil) | ||
|
|
||
| // context.DeadlineExceeded satisfies net.Error with Timeout() == true, the | ||
| // same shape the transport returns when an upstream read/dial times out. | ||
| handler(w, r, context.DeadlineExceeded) | ||
|
|
||
| assert.Equal(t, http.StatusGatewayTimeout, w.Code) | ||
| } | ||
|
|
||
| func TestProxyErrorHandler_chunkedEncodingErrorReturnsBadRequest(t *testing.T) { | ||
| handler := ProxyErrorHandler("") | ||
|
|
||
| w := httptest.NewRecorder() | ||
| r := httptest.NewRequest("GET", "/", nil) | ||
|
|
||
| handler(w, r, errors.New("malformed chunked encoding")) | ||
|
|
||
| assert.Equal(t, http.StatusBadRequest, w.Code) | ||
| } | ||
|
|
||
| func TestProxyErrorHandler_entityTooLargeReturnsRequestEntityTooLarge(t *testing.T) { | ||
| handler := ProxyErrorHandler("") | ||
|
|
||
| w := httptest.NewRecorder() | ||
| r := httptest.NewRequest("GET", "/", nil) | ||
|
|
||
| handler(w, r, &http.MaxBytesError{}) | ||
|
|
||
| assert.Equal(t, http.StatusRequestEntityTooLarge, w.Code) | ||
| } | ||
|
|
||
| // End-to-end: a client that disconnects mid-request must be recorded as a | ||
| // client-closed request (499), not an upstream failure (502). | ||
| func TestProxyHandler_clientDisconnectIsRecordedAsClientClosedRequest(t *testing.T) { | ||
| upstreamReached := make(chan struct{}) | ||
| upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
| close(upstreamReached) | ||
| <-r.Context().Done() // block until the client goes away | ||
| })) | ||
| defer upstream.Close() | ||
|
|
||
| targetUrl, err := url.Parse(upstream.URL) | ||
| require.NoError(t, err) | ||
|
|
||
| proxy := NewProxyHandler(targetUrl, "", false) | ||
|
|
||
| var capturedStatus int | ||
| done := make(chan struct{}) | ||
| front := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
| recorder := &statusRecorder{ResponseWriter: w, status: http.StatusOK} | ||
| proxy.ServeHTTP(recorder, r) | ||
| capturedStatus = recorder.status | ||
| close(done) | ||
| })) | ||
| defer front.Close() | ||
|
|
||
| ctx, cancel := context.WithCancel(context.Background()) | ||
| req, err := http.NewRequestWithContext(ctx, "GET", front.URL, nil) | ||
| require.NoError(t, err) | ||
|
|
||
| clientDone := make(chan struct{}) | ||
| go func() { | ||
| defer close(clientDone) | ||
| resp, err := http.DefaultClient.Do(req) | ||
| if resp != nil { | ||
| _ = resp.Body.Close() | ||
| } | ||
| _ = err // the client cancels the request, so an error is expected | ||
| }() | ||
|
|
||
| <-upstreamReached | ||
| cancel() | ||
| <-done | ||
| <-clientDone | ||
|
|
||
| assert.Equal(t, StatusClientClosedRequest, capturedStatus) | ||
| } | ||
|
|
||
| type statusRecorder struct { | ||
| http.ResponseWriter | ||
| status int | ||
| } | ||
|
|
||
| func (r *statusRecorder) WriteHeader(status int) { | ||
| r.status = status | ||
| r.ResponseWriter.WriteHeader(status) | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.