-
Notifications
You must be signed in to change notification settings - Fork 2
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
Extract Adapters #18
Merged
Merged
Extract Adapters #18
Changes from all commits
Commits
Show all changes
36 commits
Select commit
Hold shift + click to select a range
6ba0cc7
Rework how adapters are stored
julik 4b63934
Start extracting adapter tests
julik 8aa5984
Add a memory adapter
julik a43958e
Allow multiple adapters to be instantiated
julik 038f2be
Slowly moving on
julik 48a22d7
We need some threading tests but this is not "it"
julik cf75a16
Add stubs for locking in memory adapter
julik 4ae93dd
Extract lock
julik 349d38a
Rename test
julik 83568dc
Rename leaky bucket test
julik fe231c7
Getting along
julik 6c0e529
Even NOW() is different
julik eccd557
Seems to work. Mostly.
julik 1d67a32
And one more done
julik c84453f
Disallow block_for <= 0
julik bf36b41
Use memory adapter for cached throttle test
julik 1e706d1
Script comment
julik c064c81
Tweak a little
julik 17eeb81
Still getting there
julik 6c2d7f3
That mostly works
julik da9daff
A bit more Volkswagening
julik c824e29
Make Pecorino.adapter pluggable
julik ff8ee92
Structure tests a bit better still
julik 4356734
Add Redis in CI
julik cbae5f0
Reformat
julik 145258a
Remove unneeded lint step
julik 6087ba9
Just on push is sufficient
julik 6e5c6e9
Document Redis is available now
julik e8298a7
Zap DatabaseAdapter
julik 6d4fc1b
Remove database from block_test.rb
julik 538842a
Allow negative values for Block.set!
julik 5a4bb2b
Bump version and changelog
julik 3898531
Add YARD comments to BaseAdapter
julik 73f6be5
Better pruning assertions
julik 9662a33
Document adapter= and adapter
julik 047c9f0
Improve memory store cleanup
julik 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
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
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,66 @@ | ||
# frozen_string_literal: true | ||
|
||
# An adapter allows Pecorino throttles, leaky buckets and other | ||
# resources to interfact to a data storage backend - a database, usually. | ||
class Pecorino::Adapters::BaseAdapter | ||
# Returns the state of a leaky bucket. The state should be a tuple of two | ||
# values: the current level (Float) and whether the bucket is now at capacity (Boolean) | ||
# | ||
# @param key[String] the key of the leaky bucket | ||
# @param capacity[Float] the capacity of the leaky bucket to limit to | ||
# @param leak_rate[Float] how many tokens leak out of the bucket per second | ||
# @return [Array] | ||
def state(key:, capacity:, leak_rate:) | ||
[0, false] | ||
end | ||
|
||
# Adds tokens to the leaky bucket. The return value is a tuple of two | ||
# values: the current level (Float) and whether the bucket is now at capacity (Boolean) | ||
# | ||
# @param key[String] the key of the leaky bucket | ||
# @param capacity[Float] the capacity of the leaky bucket to limit to | ||
# @param leak_rate[Float] how many tokens leak out of the bucket per second | ||
# @param n_tokens[Float] how many tokens to add | ||
# @return [Array] | ||
def add_tokens(key:, capacity:, leak_rate:, n_tokens:) | ||
[0, false] | ||
end | ||
|
||
# Adds tokens to the leaky bucket conditionally. If there is capacity, the tokens will | ||
# be added. If there isn't - the fillup will be rejected. The return value is a triplet of | ||
# the current level (Float), whether the bucket is now at capacity (Boolean) | ||
# and whether the fillup was accepted (Boolean) | ||
# | ||
# @param key[String] the key of the leaky bucket | ||
# @param capacity[Float] the capacity of the leaky bucket to limit to | ||
# @param leak_rate[Float] how many tokens leak out of the bucket per second | ||
# @param n_tokens[Float] how many tokens to add | ||
# @return [Array] | ||
def add_tokens_conditionally(key:, capacity:, leak_rate:, n_tokens:) | ||
[0, false, false] | ||
end | ||
|
||
# Sets a timed block for the given key - this is used when a throttle fires. The return value | ||
# is not defined - the call should always succeed. | ||
# @param key[String] the key of the block | ||
# @param block_for[#to_f, Active Support Duration] the duration of the block, in seconds | ||
def set_block(key:, block_for:) | ||
end | ||
|
||
# Returns the time until which a block for a given key is in effect. If there is no block in | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. nitpick: it's cool that you're writting these comments, but would it be better to have yard definitions here instead? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Why not both? 😆 good one |
||
# effect, the method should return `nil`. The return value is either a `Time` or `nil` | ||
# @param key[String] the key of the block | ||
def blocked_until(key:) | ||
end | ||
|
||
# Deletes leaky buckets which have an expiry value prior to now and throttle blocks which have | ||
# now lapsed | ||
# @return [void] | ||
def prune | ||
julik marked this conversation as resolved.
Show resolved
Hide resolved
|
||
end | ||
|
||
# Creates the database tables for Pecorino to operate, or initializes other | ||
# schema-like resources the adapter needs to operate | ||
def create_tables(active_record_schema) | ||
end | ||
end |
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,147 @@ | ||
# frozen_string_literal: true | ||
|
||
# A memory store for leaky buckets and blocks | ||
class Pecorino::Adapters::MemoryAdapter | ||
class KeyedLock | ||
def initialize | ||
@locked_keys = Set.new | ||
@lock_mutex = Mutex.new | ||
end | ||
|
||
def lock(key) | ||
loop do | ||
@lock_mutex.synchronize do | ||
next if @locked_keys.include?(key) | ||
@locked_keys << key | ||
return | ||
end | ||
end | ||
end | ||
|
||
def unlock(key) | ||
@lock_mutex.synchronize do | ||
@locked_keys.delete(key) | ||
end | ||
end | ||
|
||
def with(key) | ||
lock(key) | ||
yield | ||
ensure | ||
unlock(key) | ||
end | ||
end | ||
|
||
def initialize | ||
@buckets = {} | ||
@blocks = {} | ||
@lock = KeyedLock.new | ||
end | ||
|
||
# Returns the state of a leaky bucket. The state should be a tuple of two | ||
# values: the current level (Float) and whether the bucket is now at capacity (Boolean) | ||
def state(key:, capacity:, leak_rate:) | ||
@lock.lock(key) | ||
level, ts = @buckets[key] | ||
@lock.unlock(key) | ||
|
||
return [0, false] unless level | ||
|
||
dt = get_mono_time - ts | ||
level_after_leak = [0, level - (leak_rate * dt)].max | ||
[level_after_leak.to_f, (level_after_leak - capacity) >= 0] | ||
end | ||
|
||
# Adds tokens to the leaky bucket. The return value is a tuple of two | ||
# values: the current level (Float) and whether the bucket is now at capacity (Boolean) | ||
def add_tokens(key:, capacity:, leak_rate:, n_tokens:) | ||
add_tokens_with_lock(key, capacity, leak_rate, n_tokens, _conditionally = false) | ||
end | ||
|
||
# Adds tokens to the leaky bucket conditionally. If there is capacity, the tokens will | ||
# be added. If there isn't - the fillup will be rejected. The return value is a triplet of | ||
# the current level (Float), whether the bucket is now at capacity (Boolean) | ||
# and whether the fillup was accepted (Boolean) | ||
def add_tokens_conditionally(key:, capacity:, leak_rate:, n_tokens:) | ||
add_tokens_with_lock(key, capacity, leak_rate, n_tokens, _conditionally = true) | ||
end | ||
|
||
# Sets a timed block for the given key - this is used when a throttle fires. The return value | ||
# is not defined - the call should always succeed. | ||
def set_block(key:, block_for:) | ||
raise ArgumentError, "block_for must be positive" unless block_for > 0 | ||
@lock.lock(key) | ||
@blocks[key] = get_mono_time + block_for.to_f | ||
Time.now + block_for.to_f | ||
ensure | ||
@lock.unlock(key) | ||
end | ||
|
||
# Returns the time until which a block for a given key is in effect. If there is no block in | ||
# effect, the method should return `nil`. The return value is either a `Time` or `nil` | ||
def blocked_until(key:) | ||
blocked_until_monotonic = @blocks[key] | ||
return unless blocked_until_monotonic | ||
|
||
now_monotonic = get_mono_time | ||
return unless blocked_until_monotonic > now_monotonic | ||
|
||
Time.now + (blocked_until_monotonic - now_monotonic) | ||
end | ||
|
||
# Deletes leaky buckets which have an expiry value prior to now and throttle blocks which have | ||
# now lapsed | ||
def prune | ||
now_monotonic = get_mono_time | ||
|
||
@blocks.keys.each do |key| | ||
@lock.with(key) do | ||
@blocks.delete(key) if @blocks[key] && @blocks[key] < now_monotonic | ||
end | ||
end | ||
|
||
@buckets.keys.each do |key| | ||
@lock.with(key) do | ||
_level, expire_at_monotonic = @buckets[key] | ||
@buckets.delete(key) if expire_at_monotonic && expire_at_monotonic < now_monotonic | ||
end | ||
end | ||
end | ||
|
||
# No-op | ||
def create_tables(active_record_schema) | ||
end | ||
|
||
private | ||
|
||
def add_tokens_with_lock(key, capacity, leak_rate, n_tokens, conditionally) | ||
@lock.lock(key) | ||
now = get_mono_time | ||
level, ts, _ = @buckets[key] || [0.0, now] | ||
|
||
dt = now - ts | ||
level_after_leak = clamp(0, level - (leak_rate * dt), capacity) | ||
level_after_fillup = level_after_leak + n_tokens | ||
if level_after_fillup > capacity && conditionally | ||
return [level_after_leak, level_after_leak >= capacity, _did_accept = false] | ||
end | ||
|
||
clamped_level_after_fillup = clamp(0, level_after_fillup, capacity) | ||
expire_after = now + (level_after_fillup / leak_rate) | ||
@buckets[key] = [clamped_level_after_fillup, now, expire_after] | ||
|
||
[clamped_level_after_fillup, clamped_level_after_fillup == capacity, _did_accept = true] | ||
ensure | ||
@lock.unlock(key) | ||
end | ||
|
||
def get_mono_time | ||
Process.clock_gettime(Process::CLOCK_MONOTONIC) | ||
end | ||
|
||
def clamp(min, value, max) | ||
return min if value < min | ||
return max if value > max | ||
value | ||
end | ||
end |
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.
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.
nitpick: might be a good idea to explain how to redefine adapter - in case of redis, as example, adapter will not be inherited from ActiveRecord and requires a manual configuration.
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.
None of them inherit from ActiveRecord anymore, some just use the ActiveRecord classes as means of passing connection configuration (and to piggyback on escaping)
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.
Why are you saying that? there is a
default_adapter_from_main_database
method still defined.https://github.com/cheddar-me/pecorino/pull/18/files#diff-3ae95d36dd505f2d90c28bab102aceb7c117caee072c2a5910685a35fb1f777bR49
But it would be great to add a section about how to configure adapter for pecorino and which settings are being configured by default.
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.
There is that method indeed (to let users have their adapter picked automatically), but nothing inherits anything there?..
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.
Sorry for the confusion, indeed wrong use of the word "inherits".