Skip to content

Commit f551712

Browse files
authored
Merge pull request rails#55418 from jrochkind/rate_limit_notification_payload
rate_limit notification instrumentation to include more payload
2 parents ed1e55b + 920309a commit f551712

File tree

3 files changed

+30
-2
lines changed

3 files changed

+30
-2
lines changed

actionpack/CHANGELOG.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,9 @@
1+
* `rate_limit.action_controller` notification has additional payload
2+
3+
additonal values: count, to, within, by, name, cache_key
4+
5+
*Jonathan Rochkind*
6+
17
* Add JSON support to the built-in health controller.
28

39
The health controller now responds to JSON requests with a structured response

actionpack/lib/action_controller/metal/rate_limiting.rb

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -59,10 +59,18 @@ def rate_limit(to:, within:, by: -> { request.remote_ip }, with: -> { head :too_
5959

6060
private
6161
def rate_limiting(to:, within:, by:, with:, store:, name:)
62-
cache_key = ["rate-limit", controller_path, name, instance_exec(&by)].compact.join(":")
62+
by = instance_exec(&by)
63+
cache_key = ["rate-limit", controller_path, name, by].compact.join(":")
6364
count = store.increment(cache_key, 1, expires_in: within)
6465
if count && count > to
65-
ActiveSupport::Notifications.instrument("rate_limit.action_controller", request: request) do
66+
ActiveSupport::Notifications.instrument("rate_limit.action_controller",
67+
request: request,
68+
count: count,
69+
to: to,
70+
within: within,
71+
by: by,
72+
name: name,
73+
cache_key: cache_key) do
6674
instance_exec(&with)
6775
end
6876
end

actionpack/test/controller/rate_limiting_test.rb

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,20 @@ class RateLimitingTest < ActionController::TestCase
3333
assert_response :too_many_requests
3434
end
3535

36+
test "notification on limit action" do
37+
get :limited
38+
get :limited
39+
40+
assert_notification("rate_limit.action_controller",
41+
count: 3,
42+
to: 2,
43+
within: 2.seconds,
44+
name: nil,
45+
by: request.remote_ip) do
46+
get :limited
47+
end
48+
end
49+
3650
test "multiple rate limits" do
3751
get :limited
3852
get :limited

0 commit comments

Comments
 (0)