cymometer 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +7 -0
- data/.ruby-version +1 -0
- data/LICENSE.txt +21 -0
- data/README.md +313 -0
- data/Rakefile +10 -0
- data/lib/cymometer/configuration.rb +13 -0
- data/lib/cymometer/counter.rb +148 -0
- data/lib/cymometer/helper.rb +170 -0
- data/lib/cymometer/version.rb +5 -0
- data/lib/cymometer.rb +9 -0
- data/sig/cymometer.rbs +4 -0
- metadata +58 -0
checksums.yaml
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
---
|
|
2
|
+
SHA256:
|
|
3
|
+
metadata.gz: 150360c27078f80b80d9531315d4889593e0351fcca5a6a91825ac293ea9d56a
|
|
4
|
+
data.tar.gz: 3933828dedeed48b056b6e9e61e8c0e31ad66ea193734ee79df2aa817cd3a05d
|
|
5
|
+
SHA512:
|
|
6
|
+
metadata.gz: a558786ac975e737ae70e32fe1c4293f6f55faad9294a1208871a1c3f06d09e2325437b9b60aa7b9a269280949696fbbda8d03b5b1ca669eedf4a40d49c528c2
|
|
7
|
+
data.tar.gz: 47fefe6630bb6303a31e8359597e606391296257218670492342b8b7f3793ff97cf78fb10f9dfbe21a2f09c7ff3ed9c6c5be68b6140c86c9b743f22ffec7cb44
|
data/.ruby-version
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
3.3.4
|
data/LICENSE.txt
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
The MIT License (MIT)
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024 Charlton Trezevant
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in
|
|
13
|
+
all copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
|
21
|
+
THE SOFTWARE.
|
data/README.md
ADDED
|
@@ -0,0 +1,313 @@
|
|
|
1
|
+
# Cymometer
|
|
2
|
+
|
|
3
|
+
<img src="./.github/cymometer.jpg" width="230" />
|
|
4
|
+
|
|
5
|
+
Cymometer is a decaying counter for rate limiting using Redis. It provides a simple and efficient mechanism for counting events over a sliding time window, which is useful in applications such as rate limiting.
|
|
6
|
+
|
|
7
|
+
Cymometer uses Redis sorted sets and Lua scripts to maintain atomic increment and decrement operations, ensuring accurate and thread-safe counting in distributed systems.
|
|
8
|
+
|
|
9
|
+
### Features
|
|
10
|
+
|
|
11
|
+
- **Atomic Operations:** Uses Redis Lua scripts for atomic increment and decrement.
|
|
12
|
+
- **Configurable Limits:** Set custom limits and time windows for your counters.
|
|
13
|
+
- **Transaction Support:** Execute blocks of code only if the counter can be incremented.
|
|
14
|
+
- **No Redis Client Dependency:** Works with any Redis client, as long as you assign it to `Cymometer.redis`.
|
|
15
|
+
- **Helper DSL:** Optional, makes it easy to add per-class, named rate limiters to jobs, service objects, or any Ruby class.
|
|
16
|
+
|
|
17
|
+
## Installation
|
|
18
|
+
|
|
19
|
+
```ruby
|
|
20
|
+
gem 'cymometer'
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
## Usage
|
|
24
|
+
|
|
25
|
+
### Configuration
|
|
26
|
+
|
|
27
|
+
First, assign a Redis client to `Cymometer.redis` before using the gem:
|
|
28
|
+
|
|
29
|
+
```ruby
|
|
30
|
+
require 'redis'
|
|
31
|
+
require 'cymometer'
|
|
32
|
+
|
|
33
|
+
# Initialize Redis client
|
|
34
|
+
redis = Redis.new(host: 'localhost', port: 6379, db: 0)
|
|
35
|
+
|
|
36
|
+
# Assign Redis client to Cymometer
|
|
37
|
+
Cymometer.redis = redis
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
The Cymometer gem does not specify a dependency on a particular Redis client. You can configure a default Redis client to be used by all Cymometer counters, or supply one to the `Cymometer::Counter` initializer.
|
|
41
|
+
|
|
42
|
+
#### Global Configuration
|
|
43
|
+
|
|
44
|
+
```ruby
|
|
45
|
+
custom_redis = Redis.new(host: 'localhost', port: 6379, db: 1)
|
|
46
|
+
Cymometer.redis = custom_redis
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
#### Per-Counter Configuration
|
|
50
|
+
|
|
51
|
+
```ruby
|
|
52
|
+
custom_redis = Redis.new(host: 'localhost', port: 6379, db: 1)
|
|
53
|
+
|
|
54
|
+
counter = Cymometer::Counter.new(
|
|
55
|
+
key_namespace: 'api',
|
|
56
|
+
key: 'user_456',
|
|
57
|
+
limit: 500,
|
|
58
|
+
window: 1800, # 30 minutes
|
|
59
|
+
redis: custom_redis
|
|
60
|
+
)
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
### Create a Counter
|
|
64
|
+
|
|
65
|
+
Create a new counter with a namespace, key, limit, and window size:
|
|
66
|
+
|
|
67
|
+
```ruby
|
|
68
|
+
counter = Cymometer::Counter.new(
|
|
69
|
+
key_namespace: 'api',
|
|
70
|
+
key: 'user_123',
|
|
71
|
+
limit: 1000, # Maximum allowed actions in the time window
|
|
72
|
+
window: 3600 # Time window in seconds (e.g., 1 hour)
|
|
73
|
+
)
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
#### Options
|
|
77
|
+
|
|
78
|
+
- `key_namespace`: A namespace to group related counters.
|
|
79
|
+
- `key`: A unique identifier for the counter (e.g., user ID).
|
|
80
|
+
- `limit`: The maximum number of allowed actions within the time window.
|
|
81
|
+
- `window`: The time window in seconds over which the actions are counted.
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
### Increment a Counter
|
|
85
|
+
|
|
86
|
+
To increment the counter and check if the limit has been exceeded:
|
|
87
|
+
|
|
88
|
+
```ruby
|
|
89
|
+
begin
|
|
90
|
+
count = counter.increment!
|
|
91
|
+
puts "Counter incremented. Current count: #{count}"
|
|
92
|
+
rescue Cymometer::Counter::LimitExceeded => e
|
|
93
|
+
puts "Rate limit exceeded: #{e.message}"
|
|
94
|
+
end
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
If the limit is not exceeded, increment! returns the current count. Otherwise, a `Cymometer::Counter::LimitExceeded` exception is raised.
|
|
98
|
+
|
|
99
|
+
### Decrement a Counter
|
|
100
|
+
|
|
101
|
+
If you need to undo an action (e.g., due to an error), you can decrement the counter:
|
|
102
|
+
|
|
103
|
+
```ruby
|
|
104
|
+
count = counter.decrement!
|
|
105
|
+
puts "Counter decremented. Current count: #{count}"
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
The `decrement!` method safely decrements the counter by removing the oldest entry. If the counter is already at zero, it remains unchanged.
|
|
109
|
+
|
|
110
|
+
### Getting the Current Count
|
|
111
|
+
|
|
112
|
+
To retrieve the current count without modifying the counter:
|
|
113
|
+
|
|
114
|
+
```ruby
|
|
115
|
+
puts "Current count: #{counter.count}"
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
### Using Transactions
|
|
119
|
+
|
|
120
|
+
Transactions allow you to execute a block of code only if the counter can be incremented:
|
|
121
|
+
|
|
122
|
+
```ruby
|
|
123
|
+
begin
|
|
124
|
+
result = counter.transaction do
|
|
125
|
+
# Your rate-limited code goes here
|
|
126
|
+
perform_api_call
|
|
127
|
+
"Success"
|
|
128
|
+
end
|
|
129
|
+
puts result
|
|
130
|
+
rescue Cymometer::Counter::LimitExceeded => e
|
|
131
|
+
puts "Rate limit exceeded: #{e.message}"
|
|
132
|
+
rescue => e
|
|
133
|
+
puts "An error occurred: #{e.message}"
|
|
134
|
+
end
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
If the counter can be incremented, the block is executed. If the block raises an exception, the counter is decremented automatically, and the exception is re-raised. If the limit is exceeded, the block is not executed, and `Cymometer::Counter::LimitExceeded` is raised.
|
|
138
|
+
|
|
139
|
+
#### Rollback Behavior
|
|
140
|
+
|
|
141
|
+
If you want the counter to remain incremented even when an exception occurs (i.e., not roll back the increment), set `rollback` to false:
|
|
142
|
+
|
|
143
|
+
```ruby
|
|
144
|
+
begin
|
|
145
|
+
result = counter.transaction(rollback: false) do
|
|
146
|
+
# Your rate-limited code here
|
|
147
|
+
perform_api_call
|
|
148
|
+
"Success"
|
|
149
|
+
end
|
|
150
|
+
puts result
|
|
151
|
+
rescue Cymometer::Counter::LimitExceeded => e
|
|
152
|
+
puts "Rate limit exceeded: #{e.message}"
|
|
153
|
+
rescue => e
|
|
154
|
+
puts "An error occurred: #{e.message}"
|
|
155
|
+
# The counter remains incremented despite the exception
|
|
156
|
+
end
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
###### Rollback Enabled (default)
|
|
160
|
+
|
|
161
|
+
Useful when you want to ensure that only successful actions count against the rate limit (e.g., API endpoints where you don’t want failed requests (due to server errors) to penalize the user).
|
|
162
|
+
|
|
163
|
+
###### Rollback Disabled (with `rollback: false`)
|
|
164
|
+
|
|
165
|
+
Useful when you want all attempts, successful or not, to count against the rate limit to prevent abuse (e.g., login attempts where you need to prevent brute-force attacks by limiting the number of attempts regardless of success).
|
|
166
|
+
|
|
167
|
+
### Cymometer::Helper DSL
|
|
168
|
+
|
|
169
|
+
The `Cymometer::Helper` DSL makes it easy to add per-class, named rate limiters to jobs, service objects, or any Ruby class. Counters are lazily instantiated and memoized per instance, so repeat calls are efficient. You declare your counters and options up front with a simple block, then access them with the counter method. No boilerplate required!
|
|
170
|
+
|
|
171
|
+
#### When to Use
|
|
172
|
+
- **Background jobs:** Limit how often certain work can be performed per job type or account.
|
|
173
|
+
- **Custom service classes:** Rate limit expensive or risky operations across different classes or namespaces.
|
|
174
|
+
- **Dynamic keys:** Build counter keys from instance data (e.g., a user ID, IP address, etc) at runtime.
|
|
175
|
+
|
|
176
|
+
#### How It Works
|
|
177
|
+
1. Include the module in your class.
|
|
178
|
+
2. Declare counters and options in a configure_cymometer block using a simple DSL.
|
|
179
|
+
3. Access counters by name with counter(:counter_name) anywhere in your class.
|
|
180
|
+
|
|
181
|
+
#### DSL Options
|
|
182
|
+
- `namespace "my_app"`: Sets a prefix for all counter keys.
|
|
183
|
+
- `counter :name do ... end`: Defines a new counter. Inside the block, you can specify:
|
|
184
|
+
- `limit`: Max actions per window.
|
|
185
|
+
- `window`: Time window in seconds.
|
|
186
|
+
- `key { ... }`: (Optional) Block to dynamically build the counter's unique key using instance data.
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
Here's an example:
|
|
190
|
+
|
|
191
|
+
```ruby
|
|
192
|
+
class MyJob
|
|
193
|
+
include Cymometer::Helper
|
|
194
|
+
|
|
195
|
+
configure_cymometer do
|
|
196
|
+
namespace "my_app"
|
|
197
|
+
|
|
198
|
+
counter :fast_calls do
|
|
199
|
+
limit 10 # max 10 per window
|
|
200
|
+
window 30 # 30 seconds
|
|
201
|
+
end
|
|
202
|
+
|
|
203
|
+
counter :slow_calls do
|
|
204
|
+
limit 3
|
|
205
|
+
window 300 # 5 minutes
|
|
206
|
+
key { some_dynamic_method } # key is built at runtime
|
|
207
|
+
end
|
|
208
|
+
end
|
|
209
|
+
|
|
210
|
+
def perform
|
|
211
|
+
# Increment and check the :fast_calls rate limit
|
|
212
|
+
counter(:fast_calls).increment!
|
|
213
|
+
|
|
214
|
+
# Use a transaction for the :slow_calls counter
|
|
215
|
+
counter(:slow_calls).transaction do
|
|
216
|
+
do_something_slow
|
|
217
|
+
end
|
|
218
|
+
end
|
|
219
|
+
|
|
220
|
+
private
|
|
221
|
+
|
|
222
|
+
def some_dynamic_method
|
|
223
|
+
"user_#{user_id}"
|
|
224
|
+
end
|
|
225
|
+
end
|
|
226
|
+
```
|
|
227
|
+
|
|
228
|
+
> [!NOTE]
|
|
229
|
+
> Centralizing your rate limits into configuration (e.g, `Rails.application.config_for(:rate_limits)[:my_job][:fast_calls]` in Rails) is a great way to keep them clear, maintainable, and easy to test.
|
|
230
|
+
|
|
231
|
+
#### Testing with Cymometer::Helper
|
|
232
|
+
|
|
233
|
+
<details>
|
|
234
|
+
|
|
235
|
+
<summary> 🛠️ Tips and Tricks </summary>
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
`Cymometer::Helper` makes it very straightforward to test rate limiting configuration and behavior in your test suite. We'll use RSpec for these examples, but you could achieve the same result with Minitest or your preferred test suite.
|
|
239
|
+
|
|
240
|
+
To start, create a `Cymometer::Counter` test double:
|
|
241
|
+
|
|
242
|
+
```ruby
|
|
243
|
+
let(:test_counter) { instance_double("Cymometer::Counter") }
|
|
244
|
+
```
|
|
245
|
+
|
|
246
|
+
Then, add some stubs. In the example below, we configure spy methods to return our test double from `Cymometer::Counter#new`, and configure the `transaction` and `increment!` methods to increment an instance variable counter for our tests.
|
|
247
|
+
|
|
248
|
+
```ruby
|
|
249
|
+
allow(Cymometer::Counter).to receive(:new).and_return(test_counter)
|
|
250
|
+
@transactions_counter = 0
|
|
251
|
+
|
|
252
|
+
allow(test_counter).to receive(:transaction) do |&block|
|
|
253
|
+
@transactions_counter += 1
|
|
254
|
+
block&.call
|
|
255
|
+
end
|
|
256
|
+
|
|
257
|
+
allow(test_counter).to receive(:increment!) { @transactions_counter += 1 }
|
|
258
|
+
```
|
|
259
|
+
|
|
260
|
+
You can then wire up tests for rate limiting behavior. Here's an example:
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
```ruby
|
|
264
|
+
describe "rate limiting behavior" do
|
|
265
|
+
before do
|
|
266
|
+
@transactions_counter = 0
|
|
267
|
+
end
|
|
268
|
+
|
|
269
|
+
# Tests for configuration
|
|
270
|
+
it "configures and uses Cymometer counters for rate limiting" do
|
|
271
|
+
counters = described_class.cymometer_counters
|
|
272
|
+
|
|
273
|
+
expect(counters[:hour_api_calls]).not_to be_nil
|
|
274
|
+
expect(counters[:hour_api_calls][:limit]).to equal(Rails.application.config_for(:rate_limits)[:api_calls_job][:per_hour])
|
|
275
|
+
expect(counters[:hour_api_calls][:window]).to equal(1.hour.to_i)
|
|
276
|
+
end
|
|
277
|
+
|
|
278
|
+
# Tests for behavior
|
|
279
|
+
context "for a project in trial mode" do
|
|
280
|
+
let(:job) { described_class.new }
|
|
281
|
+
|
|
282
|
+
before do
|
|
283
|
+
allow(project).to receive(:trial_mode?).and_return(true)
|
|
284
|
+
end
|
|
285
|
+
|
|
286
|
+
it "increments all counters" do
|
|
287
|
+
@transactions_counter = 0
|
|
288
|
+
|
|
289
|
+
described_class.perform_now(backlog_entry)
|
|
290
|
+
|
|
291
|
+
expect(@transactions_counter).to eq(2)
|
|
292
|
+
end
|
|
293
|
+
end
|
|
294
|
+
end
|
|
295
|
+
|
|
296
|
+
```
|
|
297
|
+
|
|
298
|
+
</details>
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
## Development
|
|
302
|
+
|
|
303
|
+
After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake test` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
|
|
304
|
+
|
|
305
|
+
To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
|
|
306
|
+
|
|
307
|
+
## Contributing
|
|
308
|
+
|
|
309
|
+
Bug reports and pull requests are welcome on GitHub at https://github.com/packfiles/cymometer.
|
|
310
|
+
|
|
311
|
+
## License
|
|
312
|
+
|
|
313
|
+
The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
|
data/Rakefile
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
module Cymometer
|
|
2
|
+
class RedisNotConfigured < StandardError; end
|
|
3
|
+
|
|
4
|
+
class << self
|
|
5
|
+
attr_writer :redis
|
|
6
|
+
|
|
7
|
+
def redis
|
|
8
|
+
raise RedisNotConfigured, "Please assign a Redis client to Cymometer.redis before using the gem." unless @redis
|
|
9
|
+
|
|
10
|
+
@redis
|
|
11
|
+
end
|
|
12
|
+
end
|
|
13
|
+
end
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
require "securerandom"
|
|
2
|
+
|
|
3
|
+
module Cymometer
|
|
4
|
+
class Counter
|
|
5
|
+
class LimitExceeded < StandardError; end
|
|
6
|
+
|
|
7
|
+
DEFAULT_WINDOW = 3600 # Default window is 1 hour
|
|
8
|
+
|
|
9
|
+
attr_reader :window, :limit, :key
|
|
10
|
+
|
|
11
|
+
INCREMENT_LUA_SCRIPT = <<-LUA
|
|
12
|
+
local key = KEYS[1]
|
|
13
|
+
local current_time = tonumber(ARGV[1])
|
|
14
|
+
local window = tonumber(ARGV[2])
|
|
15
|
+
local limit = tonumber(ARGV[3])
|
|
16
|
+
|
|
17
|
+
-- Remove entries older than the window size
|
|
18
|
+
redis.call('ZREMRANGEBYSCORE', key, 0, current_time - window)
|
|
19
|
+
|
|
20
|
+
-- Get the current count
|
|
21
|
+
local count = redis.call('ZCOUNT', key, current_time - window, '+inf')
|
|
22
|
+
|
|
23
|
+
if count >= limit then
|
|
24
|
+
-- Limit exceeded, do not increment
|
|
25
|
+
return {0, count}
|
|
26
|
+
else
|
|
27
|
+
-- Increment the counter
|
|
28
|
+
redis.call('ZADD', key, current_time, current_time)
|
|
29
|
+
redis.call('EXPIRE', key, math.floor(window / 1000000))
|
|
30
|
+
return {1, count + 1}
|
|
31
|
+
end
|
|
32
|
+
LUA
|
|
33
|
+
|
|
34
|
+
DECREMENT_LUA_SCRIPT = <<-LUA
|
|
35
|
+
local key = KEYS[1]
|
|
36
|
+
local current_time = tonumber(ARGV[1])
|
|
37
|
+
local window = tonumber(ARGV[2])
|
|
38
|
+
|
|
39
|
+
-- Remove entries older than the window size
|
|
40
|
+
redis.call('ZREMRANGEBYSCORE', key, 0, current_time - window)
|
|
41
|
+
|
|
42
|
+
-- Attempt to remove the entry with the lowest score (oldest entry)
|
|
43
|
+
local entries = redis.call('ZRANGEBYSCORE', key, current_time - window, '+inf', 'LIMIT', 0, 1)
|
|
44
|
+
|
|
45
|
+
if next(entries) == nil then
|
|
46
|
+
-- No entries to remove, safe no-op
|
|
47
|
+
local count = 0
|
|
48
|
+
return {1, count}
|
|
49
|
+
else
|
|
50
|
+
local member = entries[1]
|
|
51
|
+
redis.call('ZREM', key, member)
|
|
52
|
+
local count = redis.call('ZCOUNT', key, current_time - window, '+inf')
|
|
53
|
+
return {1, count}
|
|
54
|
+
end
|
|
55
|
+
LUA
|
|
56
|
+
|
|
57
|
+
def initialize(key_namespace: nil, key: nil, limit: nil, window: nil, redis: nil)
|
|
58
|
+
@redis = redis || Cymometer.redis
|
|
59
|
+
@key = "#{key_namespace || "cymometer"}:#{key || generate_key}"
|
|
60
|
+
@window = window || DEFAULT_WINDOW
|
|
61
|
+
@limit = limit || 1
|
|
62
|
+
@increment_sha = nil
|
|
63
|
+
@decrement_sha = nil
|
|
64
|
+
end
|
|
65
|
+
|
|
66
|
+
# Atomically increments the counter and checks the limit
|
|
67
|
+
def increment!
|
|
68
|
+
current_time = (Time.now.to_f * 1_000_000).to_i # Microseconds
|
|
69
|
+
window = @window * 1_000_000 # Convert to microseconds
|
|
70
|
+
|
|
71
|
+
result = evalsha_with_fallback(
|
|
72
|
+
:increment,
|
|
73
|
+
INCREMENT_LUA_SCRIPT,
|
|
74
|
+
keys: [@key],
|
|
75
|
+
argv: [current_time, window, @limit]
|
|
76
|
+
)
|
|
77
|
+
|
|
78
|
+
success = result[0] == 1
|
|
79
|
+
count = result[1].to_i
|
|
80
|
+
|
|
81
|
+
raise LimitExceeded, "Limit of #{@limit} exceeded with count #{count}" unless success
|
|
82
|
+
|
|
83
|
+
count
|
|
84
|
+
end
|
|
85
|
+
|
|
86
|
+
# Atomically decrements the counter by removing the oldest entry
|
|
87
|
+
def decrement!
|
|
88
|
+
current_time = (Time.now.to_f * 1_000_000).to_i
|
|
89
|
+
window = @window * 1_000_000
|
|
90
|
+
|
|
91
|
+
result = evalsha_with_fallback(
|
|
92
|
+
:decrement,
|
|
93
|
+
DECREMENT_LUA_SCRIPT,
|
|
94
|
+
keys: [@key],
|
|
95
|
+
argv: [current_time, window]
|
|
96
|
+
)
|
|
97
|
+
|
|
98
|
+
result[1].to_i
|
|
99
|
+
end
|
|
100
|
+
|
|
101
|
+
# Returns the current count
|
|
102
|
+
def count
|
|
103
|
+
current_time = (Time.now.to_f * 1_000_000).to_i
|
|
104
|
+
window = @window * 1_000_000
|
|
105
|
+
|
|
106
|
+
# Clean expired entries
|
|
107
|
+
@redis.zremrangebyscore(@key, 0, current_time - window)
|
|
108
|
+
@redis.zcount(@key, current_time - window, "+inf").to_i
|
|
109
|
+
end
|
|
110
|
+
|
|
111
|
+
# Executes a block if the counter can be incremented.
|
|
112
|
+
# If the block raises an exception, decrements the counter and re-raises the exception.
|
|
113
|
+
def transaction(rollback: true)
|
|
114
|
+
increment!
|
|
115
|
+
begin
|
|
116
|
+
yield
|
|
117
|
+
rescue => e
|
|
118
|
+
decrement! if rollback
|
|
119
|
+
raise e
|
|
120
|
+
end
|
|
121
|
+
end
|
|
122
|
+
|
|
123
|
+
private
|
|
124
|
+
|
|
125
|
+
def generate_key
|
|
126
|
+
SecureRandom.uuid
|
|
127
|
+
end
|
|
128
|
+
|
|
129
|
+
def evalsha_with_fallback(type, script, keys:, argv:)
|
|
130
|
+
sha_var = (type == :increment) ? :@increment_sha : :@decrement_sha
|
|
131
|
+
|
|
132
|
+
sha = instance_variable_get(sha_var)
|
|
133
|
+
begin
|
|
134
|
+
# Try EVALSHA first
|
|
135
|
+
sha ||= @redis.script(:load, script)
|
|
136
|
+
instance_variable_set(sha_var, sha)
|
|
137
|
+
@redis.evalsha(sha, keys: keys, argv: argv)
|
|
138
|
+
rescue Redis::CommandError => e
|
|
139
|
+
raise unless e.message.include?("NOSCRIPT")
|
|
140
|
+
|
|
141
|
+
# If the script wasn't loaded, reload and try again
|
|
142
|
+
sha = @redis.script(:load, script)
|
|
143
|
+
instance_variable_set(sha_var, sha)
|
|
144
|
+
@redis.evalsha(sha, keys: keys, argv: argv)
|
|
145
|
+
end
|
|
146
|
+
end
|
|
147
|
+
end
|
|
148
|
+
end
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
# Helpers for configuring/working with Cymometer::Counters in classes
|
|
2
|
+
# (like background jobs) that require rate limit accounting
|
|
3
|
+
module Cymometer
|
|
4
|
+
module Helper
|
|
5
|
+
def self.included(base)
|
|
6
|
+
base.extend ClassMethods
|
|
7
|
+
end
|
|
8
|
+
|
|
9
|
+
# ------------------------------------------------------
|
|
10
|
+
# 1) Class-level methods
|
|
11
|
+
# ------------------------------------------------------
|
|
12
|
+
module ClassMethods
|
|
13
|
+
#
|
|
14
|
+
# DSL entrypoint
|
|
15
|
+
#
|
|
16
|
+
# configure_cymometer do
|
|
17
|
+
# namespace "my_namespace"
|
|
18
|
+
# redis MyCustomRedis
|
|
19
|
+
#
|
|
20
|
+
# counter :some_counter do
|
|
21
|
+
# limit 10
|
|
22
|
+
# window 60
|
|
23
|
+
# key { "dynamic_key_for_#{self.object_id}" }
|
|
24
|
+
# end
|
|
25
|
+
# end
|
|
26
|
+
#
|
|
27
|
+
def configure_cymometer(&block)
|
|
28
|
+
DSL.new(self).instance_eval(&block)
|
|
29
|
+
end
|
|
30
|
+
|
|
31
|
+
#
|
|
32
|
+
# Access the counters hash
|
|
33
|
+
#
|
|
34
|
+
def cymometer_counters
|
|
35
|
+
@cymometer_counters ||= {}
|
|
36
|
+
end
|
|
37
|
+
|
|
38
|
+
#
|
|
39
|
+
# Accessors for the optional shared namespace & redis client
|
|
40
|
+
#
|
|
41
|
+
def cymometer_namespace
|
|
42
|
+
@cymometer_namespace
|
|
43
|
+
end
|
|
44
|
+
|
|
45
|
+
def cymometer_redis
|
|
46
|
+
@cymometer_redis
|
|
47
|
+
end
|
|
48
|
+
|
|
49
|
+
#
|
|
50
|
+
# Retrieve the stored counter config (hash) by name
|
|
51
|
+
#
|
|
52
|
+
def counter_config(name)
|
|
53
|
+
cymometer_counters[name.to_sym]
|
|
54
|
+
end
|
|
55
|
+
end
|
|
56
|
+
|
|
57
|
+
# ------------------------------------------------------
|
|
58
|
+
# 2) Instance-level method to fetch a configured counter
|
|
59
|
+
# ------------------------------------------------------
|
|
60
|
+
#
|
|
61
|
+
# def perform
|
|
62
|
+
# c = counter(:some_counter)
|
|
63
|
+
# c.increment!
|
|
64
|
+
# end
|
|
65
|
+
#
|
|
66
|
+
def counter(name)
|
|
67
|
+
config = self.class.counter_config(name)
|
|
68
|
+
raise "No Cymometer counter named #{name.inspect} in #{self.class}" unless config
|
|
69
|
+
|
|
70
|
+
# Memoize per-instance so we only build once
|
|
71
|
+
@__cymometer_counter_cache ||= {}
|
|
72
|
+
@__cymometer_counter_cache[name.to_sym] ||= build_cymometer_counter(config)
|
|
73
|
+
end
|
|
74
|
+
|
|
75
|
+
private
|
|
76
|
+
|
|
77
|
+
def build_cymometer_counter(config)
|
|
78
|
+
# Evaluate the 'key' if it's a Proc/Block
|
|
79
|
+
real_key =
|
|
80
|
+
if config[:key].respond_to?(:call)
|
|
81
|
+
instance_exec(&config[:key]) # The block is run in instance context
|
|
82
|
+
elsif config[:key]
|
|
83
|
+
config[:key].to_s
|
|
84
|
+
else
|
|
85
|
+
config[:name].to_s # Fallback to the counter's name
|
|
86
|
+
end
|
|
87
|
+
|
|
88
|
+
Cymometer::Counter.new(
|
|
89
|
+
key_namespace: config[:namespace] || self.class.cymometer_namespace || "cymometer",
|
|
90
|
+
key: real_key,
|
|
91
|
+
limit: config[:limit] || 1,
|
|
92
|
+
window: config[:window] || 3600,
|
|
93
|
+
redis: config[:redis] || self.class.cymometer_redis || Cymometer.redis
|
|
94
|
+
)
|
|
95
|
+
end
|
|
96
|
+
|
|
97
|
+
# ------------------------------------------------------
|
|
98
|
+
# 3) DSL builder classes for configure_cymometer
|
|
99
|
+
# ------------------------------------------------------
|
|
100
|
+
class DSL
|
|
101
|
+
def initialize(klass)
|
|
102
|
+
@klass = klass
|
|
103
|
+
end
|
|
104
|
+
|
|
105
|
+
def namespace(ns)
|
|
106
|
+
@klass.instance_variable_set(:@cymometer_namespace, ns)
|
|
107
|
+
end
|
|
108
|
+
|
|
109
|
+
def redis(client)
|
|
110
|
+
@klass.instance_variable_set(:@cymometer_redis, client)
|
|
111
|
+
end
|
|
112
|
+
|
|
113
|
+
def counter(name, &block)
|
|
114
|
+
conf = CounterConfig.new(name)
|
|
115
|
+
conf.instance_eval(&block) if block
|
|
116
|
+
|
|
117
|
+
# Merge into class's counters
|
|
118
|
+
new_counters = @klass.cymometer_counters.dup
|
|
119
|
+
new_counters[name.to_sym] = conf.to_h
|
|
120
|
+
@klass.instance_variable_set(:@cymometer_counters, new_counters)
|
|
121
|
+
end
|
|
122
|
+
end
|
|
123
|
+
|
|
124
|
+
class CounterConfig
|
|
125
|
+
attr_accessor :name, :limit, :window, :key, :redis, :namespace
|
|
126
|
+
|
|
127
|
+
def initialize(name)
|
|
128
|
+
@name = name.to_s
|
|
129
|
+
end
|
|
130
|
+
|
|
131
|
+
# standard:disable Lint/DuplicateMethods
|
|
132
|
+
# standard:disable Style/TrivialAccessors
|
|
133
|
+
|
|
134
|
+
# DSL methods
|
|
135
|
+
def limit(val)
|
|
136
|
+
@limit = val
|
|
137
|
+
end
|
|
138
|
+
|
|
139
|
+
def window(val)
|
|
140
|
+
@window = val
|
|
141
|
+
end
|
|
142
|
+
|
|
143
|
+
def key(val = nil, &block)
|
|
144
|
+
@key = block || val
|
|
145
|
+
end
|
|
146
|
+
|
|
147
|
+
def redis(client)
|
|
148
|
+
@redis = client
|
|
149
|
+
end
|
|
150
|
+
|
|
151
|
+
def namespace(ns)
|
|
152
|
+
@namespace = ns
|
|
153
|
+
end
|
|
154
|
+
|
|
155
|
+
# standard:enable Lint/DuplicateMethods
|
|
156
|
+
# standard:enable Style/TrivialAccessors
|
|
157
|
+
|
|
158
|
+
def to_h
|
|
159
|
+
{
|
|
160
|
+
name: @name,
|
|
161
|
+
limit: @limit,
|
|
162
|
+
window: @window,
|
|
163
|
+
key: @key,
|
|
164
|
+
redis: @redis,
|
|
165
|
+
namespace: @namespace
|
|
166
|
+
}
|
|
167
|
+
end
|
|
168
|
+
end
|
|
169
|
+
end
|
|
170
|
+
end
|
data/lib/cymometer.rb
ADDED
data/sig/cymometer.rbs
ADDED
metadata
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
--- !ruby/object:Gem::Specification
|
|
2
|
+
name: cymometer
|
|
3
|
+
version: !ruby/object:Gem::Version
|
|
4
|
+
version: 1.2.0
|
|
5
|
+
platform: ruby
|
|
6
|
+
authors:
|
|
7
|
+
- Charlton Trezevant
|
|
8
|
+
autorequire:
|
|
9
|
+
bindir: exe
|
|
10
|
+
cert_chain: []
|
|
11
|
+
date: 2025-06-11 00:00:00.000000000 Z
|
|
12
|
+
dependencies: []
|
|
13
|
+
description: A simple, atomic, memory-efficient frequency counter backed by Redis
|
|
14
|
+
Sorted Sets.
|
|
15
|
+
email:
|
|
16
|
+
- charlton@packfiles.io
|
|
17
|
+
executables: []
|
|
18
|
+
extensions: []
|
|
19
|
+
extra_rdoc_files: []
|
|
20
|
+
files:
|
|
21
|
+
- ".ruby-version"
|
|
22
|
+
- LICENSE.txt
|
|
23
|
+
- README.md
|
|
24
|
+
- Rakefile
|
|
25
|
+
- lib/cymometer.rb
|
|
26
|
+
- lib/cymometer/configuration.rb
|
|
27
|
+
- lib/cymometer/counter.rb
|
|
28
|
+
- lib/cymometer/helper.rb
|
|
29
|
+
- lib/cymometer/version.rb
|
|
30
|
+
- sig/cymometer.rbs
|
|
31
|
+
homepage: https://github.com/packfiles/cymometer
|
|
32
|
+
licenses:
|
|
33
|
+
- MIT
|
|
34
|
+
metadata:
|
|
35
|
+
homepage_uri: https://github.com/packfiles/cymometer
|
|
36
|
+
source_code_uri: https://github.com/packfiles/cymometer
|
|
37
|
+
changelog_uri: https://github.com/packfiles/cymometer
|
|
38
|
+
post_install_message:
|
|
39
|
+
rdoc_options: []
|
|
40
|
+
require_paths:
|
|
41
|
+
- lib
|
|
42
|
+
required_ruby_version: !ruby/object:Gem::Requirement
|
|
43
|
+
requirements:
|
|
44
|
+
- - ">="
|
|
45
|
+
- !ruby/object:Gem::Version
|
|
46
|
+
version: 3.0.0
|
|
47
|
+
required_rubygems_version: !ruby/object:Gem::Requirement
|
|
48
|
+
requirements:
|
|
49
|
+
- - ">="
|
|
50
|
+
- !ruby/object:Gem::Version
|
|
51
|
+
version: '0'
|
|
52
|
+
requirements: []
|
|
53
|
+
rubygems_version: 3.5.11
|
|
54
|
+
signing_key:
|
|
55
|
+
specification_version: 4
|
|
56
|
+
summary: A simple, atomic, memory-efficient frequency counter backed by Redis Sorted
|
|
57
|
+
Sets.
|
|
58
|
+
test_files: []
|