From 652e254a514fed5460d8b882f239a0c4440fad45 Mon Sep 17 00:00:00 2001 From: Tom Johnell Date: Tue, 25 Apr 2017 20:20:21 -0400 Subject: [PATCH] Quick debounce initial implementation --- .gitignore | 15 +++++ Gemfile | 3 + LICENSE.txt | 7 ++ Rakefile | 7 ++ lib/sidekiq/quick_debounce.rb | 97 +++++++++++++++++++++++++++ lib/sidekiq/quick_debounce/version.rb | 5 ++ sidekiq-quick-debounce.gemspec | 31 +++++++++ spec/sidekiq/quick_debounce_spec.rb | 43 ++++++++++++ spec/sidekiq_helper.rb | 17 +++++ spec/spec_helper.rb | 7 ++ 10 files changed, 232 insertions(+) create mode 100644 .gitignore create mode 100644 Gemfile create mode 100644 LICENSE.txt create mode 100644 Rakefile create mode 100644 lib/sidekiq/quick_debounce.rb create mode 100644 lib/sidekiq/quick_debounce/version.rb create mode 100644 sidekiq-quick-debounce.gemspec create mode 100644 spec/sidekiq/quick_debounce_spec.rb create mode 100644 spec/sidekiq_helper.rb create mode 100644 spec/spec_helper.rb diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..4094caf --- /dev/null +++ b/.gitignore @@ -0,0 +1,15 @@ +/.idea/ +/.bundle/ +/.yardoc +/Gemfile.lock +/_yardoc/ +/coverage/ +/doc/ +/pkg/ +/spec/reports/ +/tmp/ +*.bundle +*.so +*.o +*.a +mkmf.log diff --git a/Gemfile b/Gemfile new file mode 100644 index 0000000..fa75df1 --- /dev/null +++ b/Gemfile @@ -0,0 +1,3 @@ +source 'https://rubygems.org' + +gemspec diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 0000000..d0cef8f --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,7 @@ +Copyright 2017 Tom Johnell + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/Rakefile b/Rakefile new file mode 100644 index 0000000..8c5cec8 --- /dev/null +++ b/Rakefile @@ -0,0 +1,7 @@ +require 'bundler/gem_tasks' +require 'rake/testtask' + +Rake::TestTask.new do |t| + t.pattern = 'spec/**/*_spec.rb' + t.libs << 'spec' +end diff --git a/lib/sidekiq/quick_debounce.rb b/lib/sidekiq/quick_debounce.rb new file mode 100644 index 0000000..15bfbe3 --- /dev/null +++ b/lib/sidekiq/quick_debounce.rb @@ -0,0 +1,97 @@ +require 'sidekiq/api' + +module Sidekiq + class QuickDebounce + CANCEL_EXPIRATION_BUFFER = 60 * 60 * 24 + + def call(worker, msg, _queue, redis_pool = nil) + @worker = worker.is_a?(String) ? worker.constantize : worker + @msg = msg + + return yield unless quick_debounce? + + block = Proc.new do |conn| + fetch_current_options(conn) + if current_jid + self.class.cancel!( + conn: conn, + jid: current_jid, + expires_at: current_runs_at + CANCEL_EXPIRATION_BUFFER + ) + end + jid = yield + update_options(conn, jid['jid'], @msg['at']) + jid + end + + if redis_pool + redis_pool.with(&block) + else + Sidekiq.redis(&block) + end + end + + private + + def quick_debounce? + (delayed? && quick_debounce_options) || false + end + + def quick_debounce_options + @quick_debounce_options ||= @worker.get_sidekiq_options['quick_debounce'] + end + + def update_options(conn, jid, runs_at) + # Don't debounce next job if current job is running right now + return if runs_at <= Time.now.to_f + + conn.setex( + worker_key, + runs_at.to_i - Time.now.to_i, + { jid: jid, runs_at: runs_at }.to_json + ) + end + + def fetch_current_options(conn) + @options ||= begin + options = conn.get(worker_key) + options ? JSON.parse(options) : {} + end + end + + def current_jid + @options['jid'] + end + + def current_runs_at + Time.at(@options['runs_at']) if @options['runs_at'] + end + + def worker_key + @worker_key ||= begin + hash = Digest::MD5.hexdigest(@msg['args'].to_json) + "sidekiq_quick_debounce:#{@worker.name}:#{hash}" + end + end + + def delayed? + !!@msg['at'] + end + + class << self + def cancelled?(jid:) + Sidekiq.redis { |conn| conn.exists(cancel_namespace_key(jid)) } + end + + def cancel!(conn:, jid:, expires_at:) + conn.setex(cancel_namespace_key(jid), expires_at.to_i - Time.now.to_i, 1) + end + + private + + def cancel_namespace_key(key) + "sidekiq_quick_debounce:cancelled:#{key}" + end + end + end +end diff --git a/lib/sidekiq/quick_debounce/version.rb b/lib/sidekiq/quick_debounce/version.rb new file mode 100644 index 0000000..e2a82af --- /dev/null +++ b/lib/sidekiq/quick_debounce/version.rb @@ -0,0 +1,5 @@ +module Sidekiq + class QuickDebounce + VERSION = '0.0.1' + end +end diff --git a/sidekiq-quick-debounce.gemspec b/sidekiq-quick-debounce.gemspec new file mode 100644 index 0000000..a6ecfd3 --- /dev/null +++ b/sidekiq-quick-debounce.gemspec @@ -0,0 +1,31 @@ +# coding: utf-8 +lib = File.expand_path('../lib', __FILE__) +$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) +require 'sidekiq/quick_debounce/version' + +Gem::Specification.new do |spec| + spec.name = 'sidekiq-quick-debounce' + spec.version = Sidekiq::QuickDebounce::VERSION + spec.authors = ['Tom Johnell'] + spec.email = ['tjohnell@gmail.com'] + spec.summary = 'A client-side middleware for quickly debouncing Sidekiq jobs' + spec.description = <<-TXT +TBD +TXT + spec.homepage = 'https://github.com/tldev/sidekiq-quick-debounce' + spec.license = 'MIT' + + spec.files = `git ls-files -z`.split("\x0") + spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } + spec.test_files = spec.files.grep(%r{^spec/}) + spec.require_paths = ['lib'] + + spec.add_dependency 'sidekiq', '>= 2.17' + spec.add_development_dependency 'rake', '~> 10.0' + spec.add_development_dependency 'bundler', '~> 1.6' + spec.add_development_dependency 'mock_redis' + spec.add_development_dependency 'mocha' + spec.add_development_dependency 'simplecov' + spec.add_development_dependency 'codeclimate-test-reporter', '~> 1.0.0' + spec.add_development_dependency 'minitest' +end diff --git a/spec/sidekiq/quick_debounce_spec.rb b/spec/sidekiq/quick_debounce_spec.rb new file mode 100644 index 0000000..0f1b077 --- /dev/null +++ b/spec/sidekiq/quick_debounce_spec.rb @@ -0,0 +1,43 @@ +require 'spec_helper' +require 'sidekiq/quick_debounce' +require 'sidekiq' + +class QuickDebouncedWorker + include Sidekiq::Worker + + sidekiq_options quick_debounce: true + + def perform(_a, _b); end +end + +describe Sidekiq::QuickDebounce do + after do + Sidekiq.redis(&:flushdb) + end + + let(:set) { Sidekiq::ScheduledSet.new } + + it 'queues a job normally at first' do + QuickDebouncedWorker.perform_in(60, 'foo', 'bar') + set.size.must_equal 1, 'set.size must be 1' + end + + it 'cancels existing job for repeat jobs within the debounce time' do + jid = QuickDebouncedWorker.perform_in(60, 'foo', 'bar') + QuickDebouncedWorker.perform_in(60, 'foo', 'bar') + Sidekiq::QuickDebounce.cancelled?(jid: jid).must_equal true, 'first jid must be cancelled' + set.size.must_equal 2, 'set.size must be 2' + end + + it 'debounces jobs based on their arguments' do + jid = QuickDebouncedWorker.perform_in(60, 'boo', 'far') + QuickDebouncedWorker.perform_in(60, 'foo', 'bar') + Sidekiq::QuickDebounce.cancelled?(jid: jid).must_equal false, 'first jid must not be cancelled' + set.size.must_equal 2, 'set.size must be 2' + end + + it 'creates the job immediately when given an instant job' do + QuickDebouncedWorker.perform_async('foo', 'bar') + set.size.must_equal 0, 'set.size must be 0' + end +end diff --git a/spec/sidekiq_helper.rb b/spec/sidekiq_helper.rb new file mode 100644 index 0000000..fa11102 --- /dev/null +++ b/spec/sidekiq_helper.rb @@ -0,0 +1,17 @@ +require 'sidekiq' +require 'sidekiq/testing' +require 'mock_redis' + +# Disable Sidekiq's testing mocks and use MockRedis instead +Sidekiq::Testing.disable! + +Sidekiq.configure_server do |config| + config.redis = ConnectionPool.new(size: 1) { MockRedis.new } +end +Sidekiq.configure_client do |config| + config.client_middleware do |chain| + chain.add Sidekiq::QuickDebounce + end + + config.redis = ConnectionPool.new(size: 1) { MockRedis.new } +end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb new file mode 100644 index 0000000..d068894 --- /dev/null +++ b/spec/spec_helper.rb @@ -0,0 +1,7 @@ +require 'simplecov' +SimpleCov.start + +require 'minitest/spec' +require 'minitest/autorun' +require 'mocha/mini_test' +require 'sidekiq_helper'