From 7157fb7b60eb661f2525fba189a0ae3aafcf741c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Benjam=C3=ADn=20Silva?= Date: Fri, 12 Apr 2024 17:10:32 -0400 Subject: [PATCH] Initialize project --- .github/workflows/main.yml | 27 ++++ .gitignore | 12 ++ .rspec | 3 + .standard.yml | 3 + CHANGELOG.md | 3 + CODE_OF_CONDUCT.md | 84 ++++++++++ Gemfile | 6 + Gemfile.lock | 114 ++++++++++++++ LICENSE.txt | 21 +++ README.md | 81 ++++++++++ Rakefile | 10 ++ bin/console | 11 ++ bin/setup | 8 + lib/sidekiq_job_controller.rb | 11 ++ lib/sidekiq_job_controller/controller.rb | 57 +++++++ .../server_middleware.rb | 35 +++++ lib/sidekiq_job_controller/version.rb | 5 + sidekiq_job_controller.gemspec | 46 ++++++ sig/sidekiq_job_controller.rbs | 4 + spec/sidekiq_job_controller_spec.rb | 148 ++++++++++++++++++ spec/spec_helper.rb | 42 +++++ 21 files changed, 731 insertions(+) create mode 100644 .github/workflows/main.yml create mode 100644 .gitignore create mode 100644 .rspec create mode 100644 .standard.yml create mode 100644 CHANGELOG.md create mode 100644 CODE_OF_CONDUCT.md create mode 100644 Gemfile create mode 100644 Gemfile.lock create mode 100644 LICENSE.txt create mode 100644 README.md create mode 100644 Rakefile create mode 100755 bin/console create mode 100755 bin/setup create mode 100644 lib/sidekiq_job_controller.rb create mode 100644 lib/sidekiq_job_controller/controller.rb create mode 100644 lib/sidekiq_job_controller/server_middleware.rb create mode 100644 lib/sidekiq_job_controller/version.rb create mode 100644 sidekiq_job_controller.gemspec create mode 100644 sig/sidekiq_job_controller.rbs create mode 100644 spec/sidekiq_job_controller_spec.rb create mode 100644 spec/spec_helper.rb diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml new file mode 100644 index 0000000..630fa00 --- /dev/null +++ b/.github/workflows/main.yml @@ -0,0 +1,27 @@ +name: Ruby + +on: + push: + branches: + - main + + pull_request: + +jobs: + build: + runs-on: ubuntu-latest + name: Ruby ${{ matrix.ruby }} + strategy: + matrix: + ruby: + - '3.3.0' + + steps: + - uses: actions/checkout@v4 + - name: Set up Ruby + uses: ruby/setup-ruby@v1 + with: + ruby-version: ${{ matrix.ruby }} + bundler-cache: true + - name: RSpec + run: bundle exec rspec diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..a362df0 --- /dev/null +++ b/.gitignore @@ -0,0 +1,12 @@ +/.bundle/ +/.yardoc +/_yardoc/ +/coverage/ +/doc/ +/pkg/ +/spec/reports/ +/tmp/ + +# rspec failure tracking +.rspec_status +.idea diff --git a/.rspec b/.rspec new file mode 100644 index 0000000..34c5164 --- /dev/null +++ b/.rspec @@ -0,0 +1,3 @@ +--format documentation +--color +--require spec_helper diff --git a/.standard.yml b/.standard.yml new file mode 100644 index 0000000..8825305 --- /dev/null +++ b/.standard.yml @@ -0,0 +1,3 @@ +# For available configuration options, see: +# https://github.com/standardrb/standard +ruby_version: 2.6 diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..87e120d --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,3 @@ +## [0.1.0] - 2024-04-12 + +- Initial release diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..47e9d56 --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,84 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community. + +## Our Standards + +Examples of behavior that contributes to a positive environment for our community include: + +* Demonstrating empathy and kindness toward other people +* Being respectful of differing opinions, viewpoints, and experiences +* Giving and gracefully accepting constructive feedback +* Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience +* Focusing on what is best not just for us as individuals, but for the overall community + +Examples of unacceptable behavior include: + +* The use of sexualized language or imagery, and sexual attention or + advances of any kind +* Trolling, insulting or derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or email + address, without their explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Enforcement Responsibilities + +Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful. + +Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate. + +## Scope + +This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement as an Issue in this repository. All complaints will be reviewed and investigated promptly and fairly. + +All community leaders are obligated to respect the privacy and security of the reporter of any incident. + +## Enforcement Guidelines + +Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct: + +### 1. Correction + +**Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community. + +**Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested. + +### 2. Warning + +**Community Impact**: A violation through a single incident or series of actions. + +**Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban. + +### 3. Temporary Ban + +**Community Impact**: A serious violation of community standards, including sustained inappropriate behavior. + +**Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban. + +### 4. Permanent Ban + +**Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals. + +**Consequence**: A permanent ban from any sort of public interaction within the community. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0, +available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. + +Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity). + +[homepage]: https://www.contributor-covenant.org + +For answers to common questions about this code of conduct, see the FAQ at +https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations. diff --git a/Gemfile b/Gemfile new file mode 100644 index 0000000..86f6f3c --- /dev/null +++ b/Gemfile @@ -0,0 +1,6 @@ +# frozen_string_literal: true + +source "https://rubygems.org" + +# Specify your gem's dependencies in sidekiq_job_controller.gemspec +gemspec diff --git a/Gemfile.lock b/Gemfile.lock new file mode 100644 index 0000000..6da78fe --- /dev/null +++ b/Gemfile.lock @@ -0,0 +1,114 @@ +PATH + remote: . + specs: + sidekiq_job_controller (0.1.0) + activejob (>= 6.0) + sidekiq (>= 6.0) + +GEM + remote: https://rubygems.org/ + specs: + activejob (7.1.3.2) + activesupport (= 7.1.3.2) + globalid (>= 0.3.6) + activesupport (7.1.3.2) + base64 + bigdecimal + concurrent-ruby (~> 1.0, >= 1.0.2) + connection_pool (>= 2.2.5) + drb + i18n (>= 1.6, < 2) + minitest (>= 5.1) + mutex_m + tzinfo (~> 2.0) + ast (2.4.2) + base64 (0.2.0) + bigdecimal (3.1.7) + concurrent-ruby (1.2.3) + connection_pool (2.2.5) + diff-lcs (1.5.1) + drb (2.2.1) + fakeredis (0.8.0) + redis (~> 4.1) + globalid (1.2.1) + activesupport (>= 6.1) + i18n (1.14.4) + concurrent-ruby (~> 1.0) + json (2.7.2) + language_server-protocol (3.17.0.3) + lint_roller (1.1.0) + minitest (5.22.3) + mutex_m (0.2.0) + parallel (1.24.0) + parser (3.3.0.5) + ast (~> 2.4.1) + racc + racc (1.7.3) + rack (2.2.6.4) + rainbow (3.1.1) + redis (4.2.5) + regexp_parser (2.9.0) + rexml (3.2.6) + rspec (3.13.0) + rspec-core (~> 3.13.0) + rspec-expectations (~> 3.13.0) + rspec-mocks (~> 3.13.0) + rspec-core (3.13.0) + rspec-support (~> 3.13.0) + rspec-expectations (3.13.0) + diff-lcs (>= 1.2.0, < 2.0) + rspec-support (~> 3.13.0) + rspec-mocks (3.13.0) + diff-lcs (>= 1.2.0, < 2.0) + rspec-support (~> 3.13.0) + rspec-support (3.13.1) + rubocop (1.62.1) + json (~> 2.3) + language_server-protocol (>= 3.17.0) + parallel (~> 1.10) + parser (>= 3.3.0.2) + rainbow (>= 2.2.2, < 4.0) + regexp_parser (>= 1.8, < 3.0) + rexml (>= 3.2.5, < 4.0) + rubocop-ast (>= 1.31.1, < 2.0) + ruby-progressbar (~> 1.7) + unicode-display_width (>= 2.4.0, < 3.0) + rubocop-ast (1.31.2) + parser (>= 3.3.0.4) + rubocop-performance (1.20.2) + rubocop (>= 1.48.1, < 2.0) + rubocop-ast (>= 1.30.0, < 2.0) + ruby-progressbar (1.13.0) + sidekiq (6.2.0) + connection_pool (>= 2.2.2) + rack (~> 2.0) + redis (>= 4.2.0) + standard (1.35.1) + language_server-protocol (~> 3.17.0.2) + lint_roller (~> 1.0) + rubocop (~> 1.62.0) + standard-custom (~> 1.0.0) + standard-performance (~> 1.3) + standard-custom (1.0.2) + lint_roller (~> 1.0) + rubocop (~> 1.50) + standard-performance (1.3.1) + lint_roller (~> 1.1) + rubocop-performance (~> 1.20.2) + tzinfo (2.0.6) + concurrent-ruby (~> 1.0) + unicode-display_width (2.5.0) + +PLATFORMS + arm64-darwin-23 + x86_64-linux + +DEPENDENCIES + activesupport (>= 7.1) + fakeredis (>= 0.8) + rspec + sidekiq_job_controller! + standard (>= 1.3) + +BUNDLED WITH + 2.4.19 diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 0000000..721ac63 --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2024 Circle.so + +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/README.md b/README.md new file mode 100644 index 0000000..5fcc88e --- /dev/null +++ b/README.md @@ -0,0 +1,81 @@ +# SidekiqJobController + +I bet there have been multiple occasions where an specific Job failures go out of control (by an introduced bug, or a broken dependency, external service or whatever) and you didn't have the ability to simply stop processing jobs for that job class or postpone their execution. + +Sidekiq has a nice retry mechanism, but it is also too aggressive at first, every job wants to be retried very quickly, and sometimes you need to stop the job from being executed for a while. + +Usually, the solution was to create a new Sidekiq queue in `sidekiq.yml`, deploy the change, which would give the ability to stop it, clear it, or whatever. +Or edit the job class to early return or avoid the error until you figure out what's going on. + +That can work, but it can be slow, since you need to deploy the change to your infrastructure. + +If you need something you can activate quickly, this Sidekiq Middleware is what you are looking for. + +This middleware works for both Sidekiq workers and ActiveJob jobs. + +## Installation + +`bundle add sidekiq_job_controller` + +In your `config/initializers/sidekiq.rb`: + +```ruby +config.server_middleware do |chain| + chain.add SidekiqJobController::ServerMiddleware +end +```` + +## Usage + +In brief, we are adding a Sidekiq middleware that checks if a job/worker class has to be skipped all together, or re-queued for later execution. + +This is useful to run in the console when a job is failing too much (or stressing the database too much), we can skip the execution or delay it for later. + +**Example**: There’s a bug in production that causes `SomeJob` to fail many times per minute, causing a lot of errors in your error reporting tool and/or stressing your db. + +You would do: + +```ruby +SidekiqJobController::Controller.new(class_name: SomeJob).requeue_job!(45.minutes) +``` + +This will push every single `SomeJob` that Sidekiq wants to perform to be executed in 45 minutes instead of now. + +Then you have 45 minutes to fix and deploy the changes. +If you take more than 45 minutes the jobs will be rescheduled for 45 more minutes, no problem. + +Once you fix the problem and it’s in production, **`MAKE SURE`** to return the Job to its normal state: + +```ruby +SidekiqJobController::Controller.new(class_name: SomeJob).resume_job! +``` + +If for any reason you need or prefer to just skip (discard, drop) the jobs execution (equivalent to return nil in the `perform`’s first line of code) you would need to run: + +```ruby +SidekiqJobController::Controller.new(class_name: SomeJob).skip_job! +``` + +You can always check the status of a job using: + +```ruby +SidekiqJobController::Controller.new(class_name: SomeJob).status +``` + +## Development + +After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment. + +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). + +## Contributing + +Bug reports and pull requests are welcome on GitHub at https://github.com/circleco/sidekiq_job_controller. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/circleco/sidekiq_job_controller/blob/main/CODE_OF_CONDUCT.md). + +## License + +The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT). + +## Code of Conduct + +Everyone interacting in the SidekiqJobController project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/circleco/sidekiq_job_controller/blob/main/CODE_OF_CONDUCT.md). diff --git a/Rakefile b/Rakefile new file mode 100644 index 0000000..df40677 --- /dev/null +++ b/Rakefile @@ -0,0 +1,10 @@ +# frozen_string_literal: true + +require "bundler/gem_tasks" +require "rspec/core/rake_task" + +RSpec::Core::RakeTask.new(:spec) + +require "standard/rake" + +task default: %i[spec standard] diff --git a/bin/console b/bin/console new file mode 100755 index 0000000..f2c5259 --- /dev/null +++ b/bin/console @@ -0,0 +1,11 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +require "bundler/setup" +require "sidekiq_job_controller" + +# You can add fixtures and/or initialization code here to make experimenting +# with your gem easier. You can also use a different console, if you like. + +require "irb" +IRB.start(__FILE__) diff --git a/bin/setup b/bin/setup new file mode 100755 index 0000000..dce67d8 --- /dev/null +++ b/bin/setup @@ -0,0 +1,8 @@ +#!/usr/bin/env bash +set -euo pipefail +IFS=$'\n\t' +set -vx + +bundle install + +# Do any other automated setup that you need to do here diff --git a/lib/sidekiq_job_controller.rb b/lib/sidekiq_job_controller.rb new file mode 100644 index 0000000..39fb5ed --- /dev/null +++ b/lib/sidekiq_job_controller.rb @@ -0,0 +1,11 @@ +# frozen_string_literal: true + +require "sidekiq" +require "active_job" + +module SidekiqJobController +end + +require "sidekiq_job_controller/controller" +require "sidekiq_job_controller/server_middleware" + diff --git a/lib/sidekiq_job_controller/controller.rb b/lib/sidekiq_job_controller/controller.rb new file mode 100644 index 0000000..38dc54f --- /dev/null +++ b/lib/sidekiq_job_controller/controller.rb @@ -0,0 +1,57 @@ +module SidekiqJobController + class Controller + attr_reader :class_name, :job, :payload + + def initialize(class_name:, job: nil, payload: nil) + @class_name = class_name + @job = job + @payload = payload + end + + def resume_job! + Sidekiq.redis do |conn| + conn.del(job_controller_key) + end + status + end + + def skip_job! + Sidekiq.redis do |conn| + conn.mapped_hmset(job_controller_key, { action: :skip }) + end + status + end + + def requeue_job!(seconds) + Sidekiq.redis do |conn| + conn.mapped_hmset(job_controller_key, { action: :requeue, in: seconds.to_i }) + end + status + end + + def status + "#{class_name} jobs are #{current_state}" + end + + def fetch_execution_action + Sidekiq.redis do |conn| + conn.hgetall(job_controller_key) + end + end + + private + def job_controller_key + "sidekiq:job_controller:#{class_name}" + end + + def current_state + controller_result = fetch_execution_action + + return "running" unless controller_result.present? + return "skipped" if controller_result["action"] == "skip" + return "requeued in #{controller_result["in"].to_i} seconds" if controller_result["action"] == "requeue" + + "in unknown state: #{controller_result["action"]}" + end + end +end diff --git a/lib/sidekiq_job_controller/server_middleware.rb b/lib/sidekiq_job_controller/server_middleware.rb new file mode 100644 index 0000000..8cbcc98 --- /dev/null +++ b/lib/sidekiq_job_controller/server_middleware.rb @@ -0,0 +1,35 @@ +# frozen_string_literal: true + +module SidekiqJobController + class ServerMiddleware + def call(job, payload, _queue) + class_name = payload["wrapped"] || payload["class"] + + controller_result = SidekiqJobController::Controller.new( + class_name: class_name, job: job, payload: payload + ).fetch_execution_action + + if controller_result.blank? + yield + elsif controller_result["action"] == "skip" + log("FORCED SKIP ACTIVATED: Skipped performing job #{class_name} - #{job.jid}") + elsif controller_result["action"] == "requeue" + log("FORCED REQUEUE ACTIVATED: Requeuing job in #{controller_result["in"].to_i} seconds - #{class_name} - #{job.jid}") + Sidekiq::Client.push(payload.merge("at" => Time.now.to_i + controller_result["in"].to_i)) + else + log("UNEXPECTED ACTION: #{controller_result["action"]} is not recognized in #{class_name} - #{job.jid}") + yield + end + end + + private + + def log(message) + if defined?(Rails) + Rails.logger.info message + else + puts message + end + end + end +end diff --git a/lib/sidekiq_job_controller/version.rb b/lib/sidekiq_job_controller/version.rb new file mode 100644 index 0000000..8408129 --- /dev/null +++ b/lib/sidekiq_job_controller/version.rb @@ -0,0 +1,5 @@ +# frozen_string_literal: true + +module SidekiqJobController + VERSION = "0.1.0" +end diff --git a/sidekiq_job_controller.gemspec b/sidekiq_job_controller.gemspec new file mode 100644 index 0000000..6a7f6d6 --- /dev/null +++ b/sidekiq_job_controller.gemspec @@ -0,0 +1,46 @@ +# frozen_string_literal: true + +require_relative "lib/sidekiq_job_controller/version" + +Gem::Specification.new do |spec| + spec.name = "sidekiq_job_controller" + spec.version = SidekiqJobController::VERSION + spec.authors = ["Benjamín Silva"] + + spec.summary = "Sidekiq middleware to manually skip or delay Sidekiq jobs." + spec.description = "Sidekiq middleware that allows for immediate control over job processing in Sidekiq, providing tools to skip, delay, or modify job executions directly from the console, ideal for handling job failures or system stress without needing deployment." + spec.homepage = "https://github.com/circleco/sidekiq_job_controller" + spec.license = "MIT" + spec.required_ruby_version = ">= 2.6.0" + + spec.metadata["allowed_push_host"] = "https://rubygems.org" + + spec.metadata["homepage_uri"] = spec.homepage + spec.metadata["source_code_uri"] = "https://github.com/circleco/sidekiq_job_controller" + spec.metadata["changelog_uri"] = "https://github.com/circleco/sidekiq_job_controller/blob/main/CHANGELOG.md" + + # Specify which files should be added to the gem when it is released. + # The `git ls-files -z` loads the files in the RubyGem that have been added into git. + spec.files = Dir.chdir(__dir__) do + `git ls-files -z`.split("\x0").reject do |f| + (File.expand_path(f) == __FILE__) || + f.start_with?(*%w[bin/ test/ spec/ features/ .git .github appveyor Gemfile]) + end + end + spec.bindir = "exe" + spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) } + spec.require_paths = ["lib"] + + # Gem dependencies + spec.add_runtime_dependency "sidekiq", ">= 6.0" + spec.add_runtime_dependency "activejob", ">= 6.0" + + # Development dependencies + spec.add_development_dependency "rspec" + spec.add_development_dependency "standard", ">= 1.3" + spec.add_development_dependency "activesupport", ">= 7.1" + spec.add_development_dependency "fakeredis", ">= 0.8" + + # For more information and examples about making a new gem, check out our + # guide at: https://bundler.io/guides/creating_gem.html +end diff --git a/sig/sidekiq_job_controller.rbs b/sig/sidekiq_job_controller.rbs new file mode 100644 index 0000000..cdce2fc --- /dev/null +++ b/sig/sidekiq_job_controller.rbs @@ -0,0 +1,4 @@ +module SidekiqJobController + VERSION: String + # See the writing guide of rbs: https://github.com/ruby/rbs#guides +end diff --git a/spec/sidekiq_job_controller_spec.rb b/spec/sidekiq_job_controller_spec.rb new file mode 100644 index 0000000..75fa660 --- /dev/null +++ b/spec/sidekiq_job_controller_spec.rb @@ -0,0 +1,148 @@ +# frozen_string_literal: true + +require "spec_helper" + +RSpec.describe SidekiqJobController::ServerMiddleware do + before do + stub_const("ConditionalTestWorker", worker_class) + stub_const("ConditionalTestJob", job_class) + end + + let(:worker_class) do + Class.new do + include Sidekiq::Worker + + def perform(param_1, param_2) + Sidekiq.redis do |conn| + conn.set("worker_class_output", "Performing job with #{param_1} - #{param_2}") + end + end + end + end + + let(:job_class) do + Class.new(ActiveJob::Base) do + queue_as :default + + def perform(param_1, param_2:) + Sidekiq.redis do |conn| + conn.set("job_class_output", "Performing job with #{param_1} - #{param_2}") + end + end + end + end + + # This is the sidekiq worker class we want to test with + let(:sidekiq_worker_class) { ConditionalTestWorker } + # This is the job controller we will use to control the sidekiq workers + let(:sidekiq_worker_controller) { SidekiqJobController::Controller.new(class_name: sidekiq_worker_class) } + # This is the active job class we want to test with + let(:active_job_class) { ConditionalTestJob } + # Active jobs run in a wrapper class inside sidekiq. + let(:job_wrapper_class) { ActiveJob::QueueAdapters::SidekiqAdapter::JobWrapper } + # This is the job controller we will use to control the active jobs + let(:active_job_controller) { SidekiqJobController::Controller.new(class_name: active_job_class) } + + describe "resuming jobs" do + context "when the job is an ActiveJob" do + before { active_job_controller.resume_job! } + + it "performs the job", aggregate_failures: true do + enqueue_active_job + expect(active_job_controller.status).to eq("ConditionalTestJob jobs are running") + expect(Sidekiq.redis { |conn| conn.get("job_class_output") }).to eq("Performing job with hello - world") # the job perform method ran + expect(enqueued_active_jobs.size).to eq(0) # the job is not enqueued anymore + end + end + + context "when the job is a Sidekiq Worker" do + before { sidekiq_worker_controller.resume_job! } + + it "performs the job", aggregate_failures: true do + enqueue_sidekiq_worker + expect(sidekiq_worker_controller.status).to eq("ConditionalTestWorker jobs are running") + expect(Sidekiq.redis { |conn| conn.get("worker_class_output") }).to eq("Performing job with hello - world") # the job perform method ran + expect(sidekiq_worker_class.jobs.size).to eq(0) # the job is not enqueued anymore + end + end + end + + describe "skipping jobs" do + context "when the job is an ActiveJob" do + before { active_job_controller.skip_job! } + + it "skips performing the job", aggregate_failures: true do + enqueue_active_job + expect(active_job_controller.status).to eq("ConditionalTestJob jobs are skipped") + expect(Sidekiq.redis { |conn| conn.get("job_class_output") }).to be_nil # the job perform method didn't run + # the job is not enqueued for performing again (it was skipped forever) + expect(enqueued_active_jobs.size).to eq(0) + end + end + + context "when the job is a Sidekiq Worker" do + before { sidekiq_worker_controller.skip_job! } + + it "does not perform the job", aggregate_failures: true do + enqueue_sidekiq_worker + expect(sidekiq_worker_controller.status).to eq("ConditionalTestWorker jobs are skipped") + expect(Sidekiq.redis { |conn| conn.get("worker_class_output") }).to be_nil # the job perform method didn't run + # the job is not enqueued for performing again (it was skipped forever) + expect(sidekiq_worker_class.jobs.size).to eq(0) + end + end + end + + describe "requeuing jobs" do + context "when the job is an ActiveJob" do + before { active_job_controller.requeue_job!(5.minutes) } + + it "requeues the job", aggregate_failures: true do + freeze_time do + enqueue_active_job + expect(active_job_controller.status).to eq("ConditionalTestJob jobs are requeued in 300 seconds") + expect(Sidekiq.redis { |conn| conn.get("job_class_output") }).to be_nil # the job perform method didn't run + expect(enqueued_active_jobs.size).to eq(1) # there is one job enqueued for performing again + expect(enqueued_active_jobs.first["at"]).to eq(Time.now.to_i + 5.minutes) # and will be performed 5 minutes from now + end + end + end + + context "when the job is a Sidekiq Worker" do + before { sidekiq_worker_controller.requeue_job!(5.minutes) } + + it "requeues the job", aggregate_failures: true do + freeze_time do + enqueue_sidekiq_worker + expect(sidekiq_worker_controller.status).to eq("ConditionalTestWorker jobs are requeued in 300 seconds") + expect(Sidekiq.redis { |conn| conn.get("worker_class_output") }).to be_nil # the job perform method didn't run + expect(sidekiq_worker_class.jobs.size).to eq(1) # there is one job enqueued for performing again + # and will be performed 5 minutes from now + expect(sidekiq_worker_class.jobs.first["at"]).to eq(Time.now.to_i + 5.minutes) + end + end + end + end + + def enqueue_sidekiq_worker + use_sidekiq_fake do + Sidekiq::Worker.clear_all # clear all enqueued jobs before running the test + sidekiq_worker_class.perform_async("hello", "world") # enqueues the job + expect(sidekiq_worker_class.jobs.size).to eq(1) # the job is enqueued + sidekiq_worker_class.perform_one # tries to perform the job + end + end + + def enqueue_active_job + use_sidekiq_fake do + Sidekiq::Worker.clear_all # clear all enqueued jobs before running the test + active_job_class.perform_later("hello", param_2: "world") # enqueues the job + expect(enqueued_active_jobs.size).to eq(1) # the job is enqueued + job_wrapper_class.perform_one # tries to perform the job + end + end + + def enqueued_active_jobs + job_wrapper_class.jobs.select { |job| job["wrapped"] == active_job_class.to_s } + end +end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb new file mode 100644 index 0000000..5b91b59 --- /dev/null +++ b/spec/spec_helper.rb @@ -0,0 +1,42 @@ +# frozen_string_literal: true + +require "sidekiq_job_controller" +require "sidekiq/testing" +require "fakeredis/rspec" +require "active_support/testing/time_helpers" + + +RSpec.configure do |config| + config.include ActiveSupport::Testing::TimeHelpers + # Enable flags like --only-failures and --next-failure + config.example_status_persistence_file_path = ".rspec_status" + + # Disable RSpec exposing methods globally on `Module` and `main` + config.disable_monkey_patching! + + config.expect_with :rspec do |c| + c.syntax = :expect + end + + + config.before(:suite) do + Sidekiq::Testing.server_middleware do |chain| + chain.add SidekiqJobController::ServerMiddleware + end + end + + config.before(:each) do + Sidekiq::Worker.clear_all + Sidekiq.redis(&:flushdb) + end +end + +def use_sidekiq_fake + old_job_adapter = ActiveJob::Base.queue_adapter + ActiveJob::Base.queue_adapter = :sidekiq + Sidekiq::Testing.fake! do + yield + ensure + ActiveJob::Base.queue_adapter = old_job_adapter + end +end