Skip to content

Instantly share code, notes, and snippets.

@justinko
Created May 9, 2017 23:20
Show Gist options
  • Save justinko/1f7519b70b2fcfa96e7af323151abfc3 to your computer and use it in GitHub Desktop.
Save justinko/1f7519b70b2fcfa96e7af323151abfc3 to your computer and use it in GitHub Desktop.
Distributed Mutex with sidekiq-ent
class DistributedMutex
Blocked = Class.new(StandardError)
DEFAULT_OPTIONS = {
wait_timeout: 0,
lock_timeout: 30,
policy: :raise,
ttl: 1.hour
}
def self.blocking(key, options = {}, &block)
new(key, options, &block).blocking
end
attr_reader :key, :options, :block
def initialize(key, options, &block)
@options = options.reverse_merge(DEFAULT_OPTIONS)
@key, @block = key, block
end
def blocking
blocker.within_limit &block
rescue Sidekiq::Limiter::OverLimit
raise Blocked, key
end
private
def blocker
Sidekiq::Limiter.concurrent(
"distributed-mutex-#{key}".parameterize, 1, options
)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment