forked from open-telemetry/opentelemetry-collector
-
Notifications
You must be signed in to change notification settings - Fork 0
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
Add rate limit to confighttp #1
Merged
Merged
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 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 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,51 @@ | ||
// Copyright The OpenTelemetry Authors | ||
// SPDX-License-Identifier: Apache-2.0 | ||
|
||
package confighttp // import "go.opentelemetry.io/collector/config/confighttp" | ||
|
||
import ( | ||
"context" | ||
"fmt" | ||
"net/http" | ||
|
||
"go.opentelemetry.io/collector/component" | ||
"go.opentelemetry.io/collector/extension" | ||
) | ||
|
||
// RateLimit defines rate limiter settings for the receiver. | ||
type RateLimit struct { | ||
// RateLimiterID specifies the name of the extension to use in order to rate limit the incoming data point. | ||
RateLimiterID component.ID `mapstructure:"rate_limiter"` | ||
} | ||
|
||
type rateLimiter interface { | ||
extension.Extension | ||
|
||
Take(context.Context, string, http.Header) error | ||
} | ||
|
||
// rateLimiter attempts to select the appropriate rateLimiter from the list of extensions, | ||
// based on the component id of the extension. If a rateLimiter is not found, an error is returned. | ||
func (rl RateLimit) rateLimiter(extensions map[component.ID]component.Component) (rateLimiter, error) { | ||
if ext, found := extensions[rl.RateLimiterID]; found { | ||
if limiter, ok := ext.(rateLimiter); ok { | ||
return limiter, nil | ||
} | ||
return nil, fmt.Errorf("extension %q is not a rate limit", rl.RateLimiterID) | ||
} | ||
return nil, fmt.Errorf("rate limit %q not found", rl.RateLimiterID) | ||
} | ||
|
||
// rateLimitInterceptor adds interceptor for rate limit check. | ||
// It returns TooManyRequests(429) status code if rate limiter rejects the request. | ||
func rateLimitInterceptor(next http.Handler, limiter rateLimiter) http.Handler { | ||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
err := limiter.Take(r.Context(), r.URL.Path, r.Header) | ||
if err != nil { | ||
http.Error(w, http.StatusText(http.StatusTooManyRequests), http.StatusTooManyRequests) | ||
return | ||
} | ||
|
||
next.ServeHTTP(w, r) | ||
}) | ||
} |
This file contains 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,111 @@ | ||
// Copyright The OpenTelemetry Authors | ||
// SPDX-License-Identifier: Apache-2.0 | ||
|
||
package confighttp | ||
|
||
import ( | ||
"context" | ||
"errors" | ||
"fmt" | ||
"net/http" | ||
"net/http/httptest" | ||
"testing" | ||
|
||
"github.com/stretchr/testify/assert" | ||
"github.com/stretchr/testify/require" | ||
"go.opentelemetry.io/collector/component" | ||
"go.opentelemetry.io/collector/component/componenttest" | ||
) | ||
|
||
func TestServerRateLimit(t *testing.T) { | ||
// prepare | ||
hss := HTTPServerSettings{ | ||
Endpoint: "localhost:0", | ||
RateLimit: &RateLimit{ | ||
RateLimiterID: component.NewID("mock"), | ||
}, | ||
} | ||
|
||
limiter := &mockRateLimiter{} | ||
|
||
host := &mockHost{ | ||
ext: map[component.ID]component.Component{ | ||
component.NewID("mock"): limiter, | ||
}, | ||
} | ||
|
||
var handlerCalled bool | ||
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
handlerCalled = true | ||
}) | ||
|
||
srv, err := hss.ToServer(host, componenttest.NewNopTelemetrySettings(), handler) | ||
require.NoError(t, err) | ||
|
||
// test | ||
srv.Handler.ServeHTTP(&httptest.ResponseRecorder{}, httptest.NewRequest("GET", "/", nil)) | ||
|
||
// verify | ||
assert.True(t, handlerCalled) | ||
assert.Equal(t, 1, limiter.calls) | ||
} | ||
|
||
func TestInvalidServerRateLimit(t *testing.T) { | ||
hss := HTTPServerSettings{ | ||
RateLimit: &RateLimit{ | ||
RateLimiterID: component.NewID("non-existing"), | ||
}, | ||
} | ||
|
||
srv, err := hss.ToServer(componenttest.NewNopHost(), componenttest.NewNopTelemetrySettings(), http.NewServeMux()) | ||
require.Error(t, err) | ||
require.Nil(t, srv) | ||
} | ||
|
||
func TestRejectedServerRateLimit(t *testing.T) { | ||
// prepare | ||
hss := HTTPServerSettings{ | ||
Endpoint: "localhost:0", | ||
RateLimit: &RateLimit{ | ||
RateLimiterID: component.NewID("mock"), | ||
}, | ||
} | ||
host := &mockHost{ | ||
ext: map[component.ID]component.Component{ | ||
component.NewID("mock"): &mockRateLimiter{ | ||
err: errors.New("rate limited"), | ||
}, | ||
}, | ||
} | ||
|
||
srv, err := hss.ToServer(host, componenttest.NewNopTelemetrySettings(), http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})) | ||
require.NoError(t, err) | ||
|
||
// test | ||
response := &httptest.ResponseRecorder{} | ||
srv.Handler.ServeHTTP(response, httptest.NewRequest("GET", "/", nil)) | ||
|
||
// verify | ||
assert.Equal(t, response.Result().StatusCode, http.StatusTooManyRequests) | ||
assert.Equal(t, response.Result().Status, fmt.Sprintf("%v %s", http.StatusTooManyRequests, http.StatusText(http.StatusTooManyRequests))) | ||
} | ||
|
||
// Mocks | ||
|
||
type mockRateLimiter struct { | ||
calls int | ||
err error | ||
} | ||
|
||
func (m *mockRateLimiter) Take(context.Context, string, http.Header) error { | ||
m.calls++ | ||
return m.err | ||
} | ||
|
||
func (m *mockRateLimiter) Start(_ context.Context, _ component.Host) error { | ||
return nil | ||
} | ||
|
||
func (m *mockRateLimiter) Shutdown(_ context.Context) error { | ||
return nil | ||
} |
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Do we want to support a condition where
err
is not nil but its also not a rate limited error either?Would we want to be able to surface other runtime errors via the interceptor or should we surface it another way?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I also thought about it. in-memory limiter, which is a backoff limiter, will not return any errors other than rate-limited. So I was wondering if I need an extra condition in here?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Hmm the in memory limiter could still return other errors. Like for instance there could be runtime errors from misconfiguration (ie a default limiter not being set for a limiter type).