sidekiq-tasks 0.1.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.
Files changed (41) hide show
  1. checksums.yaml +7 -0
  2. data/.rspec +3 -0
  3. data/.rubocop.yml +59 -0
  4. data/.simplecov +16 -0
  5. data/CHANGELOG.md +5 -0
  6. data/CODE_OF_CONDUCT.md +132 -0
  7. data/LICENSE.txt +21 -0
  8. data/README.md +178 -0
  9. data/Rakefile +12 -0
  10. data/docs/task.png +0 -0
  11. data/lib/sidekiq/sidekiq-tasks.rb +1 -0
  12. data/lib/sidekiq/tasks/config.rb +47 -0
  13. data/lib/sidekiq/tasks/errors.rb +12 -0
  14. data/lib/sidekiq/tasks/job.rb +19 -0
  15. data/lib/sidekiq/tasks/set.rb +57 -0
  16. data/lib/sidekiq/tasks/storage.rb +85 -0
  17. data/lib/sidekiq/tasks/strategies/base.rb +91 -0
  18. data/lib/sidekiq/tasks/strategies/rake_task.rb +26 -0
  19. data/lib/sidekiq/tasks/strategies/rules/base.rb +19 -0
  20. data/lib/sidekiq/tasks/strategies/rules/enable_with_comment.rb +29 -0
  21. data/lib/sidekiq/tasks/strategies/rules/task_from_lib.rb +13 -0
  22. data/lib/sidekiq/tasks/strategies/rules.rb +11 -0
  23. data/lib/sidekiq/tasks/strategies.rb +10 -0
  24. data/lib/sidekiq/tasks/task.rb +42 -0
  25. data/lib/sidekiq/tasks/task_metadata.rb +27 -0
  26. data/lib/sidekiq/tasks/validations.rb +37 -0
  27. data/lib/sidekiq/tasks/version.rb +7 -0
  28. data/lib/sidekiq/tasks/web/extension.rb +45 -0
  29. data/lib/sidekiq/tasks/web/helpers/application_helper.rb +17 -0
  30. data/lib/sidekiq/tasks/web/helpers/task_helper.rb +29 -0
  31. data/lib/sidekiq/tasks/web/locales/en.yml +19 -0
  32. data/lib/sidekiq/tasks/web/locales/fr.yml +19 -0
  33. data/lib/sidekiq/tasks/web/params.rb +44 -0
  34. data/lib/sidekiq/tasks/web/search.rb +53 -0
  35. data/lib/sidekiq/tasks/web/views/_pagination.html.erb +25 -0
  36. data/lib/sidekiq/tasks/web/views/_task.html.erb +84 -0
  37. data/lib/sidekiq/tasks/web/views/tasks.html.erb +53 -0
  38. data/lib/sidekiq/tasks/web.rb +18 -0
  39. data/lib/sidekiq/tasks.rb +37 -0
  40. data/sig/sidekiq/tasks.rbs +6 -0
  41. metadata +283 -0
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: c2e154e5c7dce24a8e35fe82c1bf604aecdceb88bcdc09949bee07b250666044
4
+ data.tar.gz: 79f0abe2f5d49378ab319b8c4889e35603773616a3c83e4acc12c16a3ad5bf5d
5
+ SHA512:
6
+ metadata.gz: 46a46f7d5fe0aad48100eb29756bdf9161a6516716a2f0c2e9bfc9ee5d9ffb054ff9cd7c4d19c88032f30fcef2b4eb2253f231ebc752769b54ccd5d9b212e873
7
+ data.tar.gz: 3381e43c02d4b3c7766ce818fa5b3a8a0272e1a605c2f404fc7ac758b09a420833c4fe90fa83047e9acfdf07568d0609d4168dfc9ffec1b28c5a9705a355ac9f
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,59 @@
1
+ AllCops:
2
+ TargetRubyVersion: 3.1
3
+ NewCops: disable
4
+ SuggestExtensions: false
5
+
6
+ Layout/SpaceInsideHashLiteralBraces:
7
+ EnforcedStyle: no_space
8
+
9
+ Metrics/AbcSize:
10
+ Exclude:
11
+ - lib/sidekiq/tasks/web/extension.rb
12
+
13
+ Metrics/BlockLength:
14
+ Exclude:
15
+ - spec/**/*
16
+ - sidekiq-tasks.gemspec
17
+
18
+ Metrics/MethodLength:
19
+ Exclude:
20
+ - lib/sidekiq/tasks/web/extension.rb
21
+
22
+ Metrics/ParameterLists:
23
+ Exclude:
24
+ - spec/**/*
25
+
26
+ Naming/FileName:
27
+ Exclude:
28
+ - lib/sidekiq/sidekiq-tasks.rb
29
+
30
+ Naming/MemoizedInstanceVariableName:
31
+ Enabled: false
32
+
33
+ Style/Documentation:
34
+ Enabled: false
35
+
36
+ Style/FrozenStringLiteralComment:
37
+ Enabled: false
38
+
39
+ Style/GlobalVars:
40
+ Exclude:
41
+ - spec/**/*
42
+
43
+ Style/ModuleFunction:
44
+ Enabled: false
45
+
46
+ Style/ParallelAssignment:
47
+ Enabled: false
48
+
49
+ Style/StringLiterals:
50
+ EnforcedStyle: double_quotes
51
+
52
+ Style/StringLiteralsInInterpolation:
53
+ EnforcedStyle: double_quotes
54
+
55
+ Style/TrailingCommaInArrayLiteral:
56
+ EnforcedStyleForMultiline: consistent_comma
57
+
58
+ Style/TrailingCommaInHashLiteral:
59
+ EnforcedStyleForMultiline: consistent_comma
data/.simplecov ADDED
@@ -0,0 +1,16 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "simplecov_json_formatter"
4
+ require "sidekiq/tasks"
5
+
6
+ SimpleCov.formatters = SimpleCov::Formatter::MultiFormatter.new(
7
+ [
8
+ SimpleCov::Formatter::HTMLFormatter,
9
+ SimpleCov::Formatter::JSONFormatter,
10
+ ]
11
+ )
12
+
13
+ SimpleCov.start do
14
+ add_filter "spec/"
15
+ add_group "Sidekiq-Tasks", "lib/"
16
+ end
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## Changelog
2
+
3
+ ### [0.1.0] - 2025-02-23
4
+
5
+ - Initial release
@@ -0,0 +1,132 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our
6
+ community a harassment-free experience for everyone, regardless of age, body
7
+ size, visible or invisible disability, ethnicity, sex characteristics, gender
8
+ identity and expression, level of experience, education, socio-economic status,
9
+ nationality, personal appearance, race, caste, color, religion, or sexual
10
+ identity and orientation.
11
+
12
+ We pledge to act and interact in ways that contribute to an open, welcoming,
13
+ diverse, inclusive, and healthy community.
14
+
15
+ ## Our Standards
16
+
17
+ Examples of behavior that contributes to a positive environment for our
18
+ community include:
19
+
20
+ * Demonstrating empathy and kindness toward other people
21
+ * Being respectful of differing opinions, viewpoints, and experiences
22
+ * Giving and gracefully accepting constructive feedback
23
+ * Accepting responsibility and apologizing to those affected by our mistakes,
24
+ and learning from the experience
25
+ * Focusing on what is best not just for us as individuals, but for the overall
26
+ community
27
+
28
+ Examples of unacceptable behavior include:
29
+
30
+ * The use of sexualized language or imagery, and sexual attention or advances of
31
+ any kind
32
+ * Trolling, insulting or derogatory comments, and personal or political attacks
33
+ * Public or private harassment
34
+ * Publishing others' private information, such as a physical or email address,
35
+ without their explicit permission
36
+ * Other conduct which could reasonably be considered inappropriate in a
37
+ professional setting
38
+
39
+ ## Enforcement Responsibilities
40
+
41
+ Community leaders are responsible for clarifying and enforcing our standards of
42
+ acceptable behavior and will take appropriate and fair corrective action in
43
+ response to any behavior that they deem inappropriate, threatening, offensive,
44
+ or harmful.
45
+
46
+ Community leaders have the right and responsibility to remove, edit, or reject
47
+ comments, commits, code, wiki edits, issues, and other contributions that are
48
+ not aligned to this Code of Conduct, and will communicate reasons for moderation
49
+ decisions when appropriate.
50
+
51
+ ## Scope
52
+
53
+ This Code of Conduct applies within all community spaces, and also applies when
54
+ an individual is officially representing the community in public spaces.
55
+ Examples of representing our community include using an official email address,
56
+ posting via an official social media account, or acting as an appointed
57
+ representative at an online or offline event.
58
+
59
+ ## Enforcement
60
+
61
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
62
+ reported to the community leaders responsible for enforcement at
63
+ [INSERT CONTACT METHOD].
64
+ All complaints will be reviewed and investigated promptly and fairly.
65
+
66
+ All community leaders are obligated to respect the privacy and security of the
67
+ reporter of any incident.
68
+
69
+ ## Enforcement Guidelines
70
+
71
+ Community leaders will follow these Community Impact Guidelines in determining
72
+ the consequences for any action they deem in violation of this Code of Conduct:
73
+
74
+ ### 1. Correction
75
+
76
+ **Community Impact**: Use of inappropriate language or other behavior deemed
77
+ unprofessional or unwelcome in the community.
78
+
79
+ **Consequence**: A private, written warning from community leaders, providing
80
+ clarity around the nature of the violation and an explanation of why the
81
+ behavior was inappropriate. A public apology may be requested.
82
+
83
+ ### 2. Warning
84
+
85
+ **Community Impact**: A violation through a single incident or series of
86
+ actions.
87
+
88
+ **Consequence**: A warning with consequences for continued behavior. No
89
+ interaction with the people involved, including unsolicited interaction with
90
+ those enforcing the Code of Conduct, for a specified period of time. This
91
+ includes avoiding interactions in community spaces as well as external channels
92
+ like social media. Violating these terms may lead to a temporary or permanent
93
+ ban.
94
+
95
+ ### 3. Temporary Ban
96
+
97
+ **Community Impact**: A serious violation of community standards, including
98
+ sustained inappropriate behavior.
99
+
100
+ **Consequence**: A temporary ban from any sort of interaction or public
101
+ communication with the community for a specified period of time. No public or
102
+ private interaction with the people involved, including unsolicited interaction
103
+ with those enforcing the Code of Conduct, is allowed during this period.
104
+ Violating these terms may lead to a permanent ban.
105
+
106
+ ### 4. Permanent Ban
107
+
108
+ **Community Impact**: Demonstrating a pattern of violation of community
109
+ standards, including sustained inappropriate behavior, harassment of an
110
+ individual, or aggression toward or disparagement of classes of individuals.
111
+
112
+ **Consequence**: A permanent ban from any sort of public interaction within the
113
+ community.
114
+
115
+ ## Attribution
116
+
117
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage],
118
+ version 2.1, available at
119
+ [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
120
+
121
+ Community Impact Guidelines were inspired by
122
+ [Mozilla's code of conduct enforcement ladder][Mozilla CoC].
123
+
124
+ For answers to common questions about this code of conduct, see the FAQ at
125
+ [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at
126
+ [https://www.contributor-covenant.org/translations][translations].
127
+
128
+ [homepage]: https://www.contributor-covenant.org
129
+ [v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
130
+ [Mozilla CoC]: https://github.com/mozilla/diversity
131
+ [FAQ]: https://www.contributor-covenant.org/faq
132
+ [translations]: https://www.contributor-covenant.org/translations
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2025 Victor
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,178 @@
1
+ # Sidekiq::Tasks
2
+
3
+ [![CI Status](https://github.com/victorauthiat/sidekiq-tasks/actions/workflows/ci.yml/badge.svg)](https://github.com/victorauthiat/sidekiq-tasks/actions/workflows/ci.yml)
4
+ [![Maintainability](https://api.codeclimate.com/v1/badges/079e91362a810b4ef80d/maintainability)](https://codeclimate.com/github/VictorAuthiat/sidekiq-tasks/maintainability)
5
+ [![Test Coverage](https://api.codeclimate.com/v1/badges/079e91362a810b4ef80d/test_coverage)](https://codeclimate.com/github/VictorAuthiat/sidekiq-tasks/test_coverage)
6
+
7
+ > A [Sidekiq](https://github.com/sidekiq/sidekiq) extension for task management.
8
+
9
+ Sidekiq-Tasks extends Sidekiq by providing an interface to enqueue tasks directly from the web interface. By default it works with Rake tasks but it can be easily extended to support other task execution systems.
10
+
11
+ ![Task view](docs/task.png)
12
+
13
+ ## Installation
14
+
15
+ ```bash
16
+ bundle add sidekiq-tasks
17
+ ```
18
+
19
+ If bundler is not being used to manage dependencies, install the gem by executing:
20
+
21
+ ```bash
22
+ gem install sidekiq-tasks
23
+ ```
24
+
25
+ Add the following to your `config/routes.rb` file:
26
+
27
+ ```ruby
28
+ require "sidekiq/web"
29
+ require "sidekiq/tasks/web"
30
+ ```
31
+
32
+ Now you can access the web interface at `/sidekiq/tasks` and you'll see a list of all the available tasks.
33
+ Once you've found your task, you can access the task details page to see the metadata, history and form to enqueue the task.
34
+
35
+ ## Prerequisites
36
+
37
+ Sidekiq Tasks is based on the concept of **strategies** and **rules** to manage **tasks**.
38
+
39
+ - A **task** represents a unit of work that can be enqueued and executed.
40
+ - A **strategy** defines how tasks are loaded, built, enqueued, and executed.
41
+ - A **rule** is a condition given to a strategy to determine which tasks are available.
42
+
43
+ By default, it comes with the `Sidekiq::Tasks::Strategies::RakeTask` strategy, which allows you to enqueue and execute Rake tasks with their arguments.
44
+
45
+ > [!NOTE]
46
+ > In accordance with the principle of least privilege, it has the following rules:
47
+ > - **`TaskFromLib`** Only tasks from the `lib` folder are loaded.
48
+ > - **`EnableWithComment`** Only tasks explicitly enabled with a magic comment are loaded.
49
+
50
+ Example of an available task in `lib/tasks/my_task.rake`:
51
+
52
+ ```ruby
53
+ # sidekiq-tasks:enable
54
+ task :my_task do
55
+ puts "my_task"
56
+ end
57
+ ```
58
+
59
+ ## Strategies configuration
60
+
61
+ Strategies can be configured through the `config.strategies` option.
62
+ For example if you want to remove the `EnableWithComment` rule from the default strategy and enable all tasks from the `lib` folder:
63
+
64
+ ```ruby
65
+ Sidekiq::Tasks.configure do |config|
66
+ config.strategies = [
67
+ Sidekiq::Tasks::Strategies::RakeTask.new(
68
+ rules: [
69
+ Sidekiq::Tasks::Strategies::Rules::TaskFromLib.new,
70
+ ]
71
+ )
72
+ ]
73
+ end
74
+ ```
75
+
76
+ You can also define your own strategy creating a subclass of `Sidekiq::Tasks::Strategies::Base`.
77
+
78
+ Each strategy must implement the following methods:
79
+
80
+ - `load_tasks`: Returns all the raw tasks that should be filtered.
81
+ - `build_task_metadata`: Build metadata for a task.
82
+ - `execute_task`: Execute a task.
83
+
84
+ A strategy has a `tasks` method that filters the loaded tasks according to the rules and builds `Sidekiq::Tasks::Task` instances with `build_task_metadata` for each raw task.
85
+
86
+ **Example:**
87
+
88
+ Here is an example of a strategy that loads tasks from a YAML configuration file, builds metadata and executes them as system commands:
89
+
90
+ ```ruby
91
+ class ScriptStrategy < Sidekiq::Tasks::Strategies::Base
92
+ def load_tasks
93
+ YAML.load_file("config/scripts.yml")
94
+ end
95
+
96
+ def build_task_metadata(task)
97
+ Sidekiq::Tasks::TaskMetadata.new(
98
+ name: task["name"],
99
+ desc: task["desc"],
100
+ args: task["args"],
101
+ file: task["file"]
102
+ )
103
+ end
104
+
105
+ def execute_task(name, args = {})
106
+ system "ruby #{name} #{args.values.join(" ")}"
107
+ end
108
+ end
109
+
110
+ Sidekiq::Tasks.configure do |config|
111
+ config.strategies = [ScriptStrategy.new]
112
+ end
113
+ ```
114
+
115
+ > [!CAUTION]
116
+ > This is an example, executing tasks via system exposes your application to command injection risks.
117
+ > Never execute user input directly without strict validation.
118
+
119
+ ## Strategy rules
120
+
121
+ Strategies can use rules to determine which tasks should be loaded.
122
+ Rules must inherit from `Sidekiq::Tasks::Strategies::Rules::Base` and implement the `respected?` method.
123
+ Here is an example of a rule that filters only scripts that match 'foo' in their filename:
124
+
125
+ ```ruby
126
+ class FileMatchesFoo < Sidekiq::Tasks::Strategies::Rules::Base
127
+ def respected?(task)
128
+ task["file"].match?(/foo/)
129
+ end
130
+ end
131
+
132
+ Sidekiq::Tasks.configure do |config|
133
+ config.strategies = [ScriptStrategy.new(rules: [FileMatchesFoo.new])]
134
+ end
135
+ ```
136
+
137
+ ## Strategy enqueuing
138
+
139
+ By default, strategies enqueue tasks using the `Sidekiq::Tasks::Job` class.
140
+ You can configure `sidekiq_options` as follows:
141
+
142
+ ```ruby
143
+ Sidekiq::Tasks.configure do |config|
144
+ # Default options are {queue: "default", retry: false}
145
+ config.sidekiq_options = {queue: "low", retry: false}
146
+ end
147
+ ```
148
+
149
+ You can also override the `enqueue_task` method to implement your own enqueuing logic for your strategy:
150
+
151
+ ```ruby
152
+ class ScriptStrategy < Sidekiq::Tasks::Strategies::Base
153
+ def enqueue_task(name, params = {})
154
+ ScriptJob.perform_async(name, params)
155
+ end
156
+ end
157
+ ```
158
+
159
+ > [!WARNING]
160
+ > Ensure that `enqueue_task` returns the JID of the Sidekiq job that will execute the task.
161
+
162
+ ## Development
163
+
164
+ 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.
165
+
166
+ 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).
167
+
168
+ ## Contributing
169
+
170
+ Bug reports and pull requests are welcome on GitHub at https://github.com/victorauthiat/sidekiq-tasks. 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/victorauthiat/sidekiq-tasks/blob/master/CODE_OF_CONDUCT.md).
171
+
172
+ ## License
173
+
174
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
175
+
176
+ ## Code of Conduct
177
+
178
+ Everyone interacting in the Sidekiq::Tasks project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/victorauthiat/sidekiq-tasks/blob/master/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rspec/core/rake_task"
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ require "rubocop/rake_task"
9
+
10
+ RuboCop::RakeTask.new
11
+
12
+ task default: %i[spec rubocop]
data/docs/task.png ADDED
Binary file
@@ -0,0 +1 @@
1
+ require "sidekiq/tasks"
@@ -0,0 +1,47 @@
1
+ module Sidekiq
2
+ module Tasks
3
+ class Config
4
+ DEFAULT_SIDEKIQ_OPTIONS = {
5
+ queue: "default",
6
+ retry: false,
7
+ }.freeze
8
+
9
+ DEFAULT_STRATEGIES = [
10
+ Sidekiq::Tasks::Strategies::RakeTask.new(
11
+ rules: [
12
+ Sidekiq::Tasks::Strategies::Rules::TaskFromLib.new,
13
+ Sidekiq::Tasks::Strategies::Rules::EnableWithComment.new,
14
+ ]
15
+ ),
16
+ ].freeze
17
+
18
+ include Sidekiq::Tasks::Validations
19
+
20
+ attr_reader :strategies, :sidekiq_options
21
+
22
+ def initialize
23
+ @sidekiq_options = DEFAULT_SIDEKIQ_OPTIONS
24
+ @strategies = DEFAULT_STRATEGIES
25
+ end
26
+
27
+ # @see https://github.com/sidekiq/sidekiq/wiki/Advanced-Options#jobs
28
+ def sidekiq_options=(options)
29
+ validate_class!(options, [Hash], "sidekiq_options")
30
+ validate_hash_option!(options, :queue, [String])
31
+ validate_hash_option!(options, :retry, [TrueClass, FalseClass])
32
+ validate_hash_option!(options, :dead, [NilClass, TrueClass, FalseClass])
33
+ validate_hash_option!(options, :backtrace, [NilClass, TrueClass, FalseClass, Integer])
34
+ validate_hash_option!(options, :pool, [NilClass, String])
35
+ validate_hash_option!(options, :tags, [NilClass, Array])
36
+
37
+ @sidekiq_options = options
38
+ end
39
+
40
+ def strategies=(strategies)
41
+ validate_array_classes!(strategies, [Sidekiq::Tasks::Strategies::Base], "strategies")
42
+
43
+ @strategies = strategies
44
+ end
45
+ end
46
+ end
47
+ end
@@ -0,0 +1,12 @@
1
+ module Sidekiq
2
+ module Tasks
3
+ class NotFoundError < StandardError
4
+ end
5
+
6
+ class ArgumentError < StandardError
7
+ end
8
+
9
+ class NotImplementedError < StandardError
10
+ end
11
+ end
12
+ end
@@ -0,0 +1,19 @@
1
+ require "sidekiq"
2
+
3
+ module Sidekiq
4
+ module Tasks
5
+ class Job
6
+ include Sidekiq::Job
7
+
8
+ sidekiq_options Sidekiq::Tasks.config.sidekiq_options
9
+
10
+ # @param name [String] The name of the task to execute.
11
+ # @param args [Hash] The arguments to pass to the task.
12
+ # @raise [Sidekiq::Tasks::TaskNotFoundError] If the task is not found.
13
+ def perform(name, args)
14
+ symbolized_args = JSON.parse(args, symbolize_names: true)
15
+ Sidekiq::Tasks.tasks.find_by!(name: name).execute(symbolized_args, jid: jid)
16
+ end
17
+ end
18
+ end
19
+ end
@@ -0,0 +1,57 @@
1
+ module Sidekiq
2
+ module Tasks
3
+ class Set
4
+ include Enumerable
5
+
6
+ def self.match?(object, attributes)
7
+ attributes.any? do |attribute, value|
8
+ [nil, ""].include?(value) || object.public_send(attribute)&.match?(value)
9
+ end
10
+ end
11
+
12
+ attr_reader :objects
13
+
14
+ def initialize(objects)
15
+ @objects = objects
16
+ end
17
+
18
+ def each(&block)
19
+ objects.each(&block)
20
+ end
21
+
22
+ def where(attributes = {})
23
+ reflect(objects.select { |object| self.class.match?(object, attributes) })
24
+ end
25
+
26
+ def find_by(name: nil)
27
+ where(name: name).first
28
+ end
29
+
30
+ def find_by!(name: nil)
31
+ find_by(name: name) || raise(NotFoundError, "'#{name}' not found")
32
+ end
33
+
34
+ def size
35
+ objects.size
36
+ end
37
+
38
+ def first
39
+ objects[0]
40
+ end
41
+
42
+ def last
43
+ objects[-1]
44
+ end
45
+
46
+ def empty?
47
+ objects.empty?
48
+ end
49
+
50
+ private
51
+
52
+ def reflect(objects)
53
+ self.class.new(objects)
54
+ end
55
+ end
56
+ end
57
+ end
@@ -0,0 +1,85 @@
1
+ module Sidekiq
2
+ module Tasks
3
+ class Storage
4
+ JID_PREFIX = "task".freeze
5
+ HISTORY_LIMIT = 10
6
+
7
+ attr_reader :task_name
8
+
9
+ def initialize(task_name)
10
+ @task_name = task_name
11
+ end
12
+
13
+ def jid_key
14
+ "#{JID_PREFIX}:#{task_name}"
15
+ end
16
+
17
+ def history_key
18
+ "#{jid_key}:history"
19
+ end
20
+
21
+ def last_enqueue_at
22
+ stored_time("last_enqueue_at")
23
+ end
24
+
25
+ def last_execution_at
26
+ stored_time("last_execution_at")
27
+ end
28
+
29
+ def history
30
+ redis_history = Sidekiq.redis { |conn| conn.lrange(history_key, 0, -1) }&.map do |raw|
31
+ entry = Sidekiq.load_json(raw)
32
+ entry["enqueued_at"] = Time.at(entry["enqueued_at"]) if entry["enqueued_at"]
33
+ entry["executed_at"] = Time.at(entry["executed_at"]) if entry["executed_at"]
34
+ entry
35
+ end
36
+
37
+ redis_history || []
38
+ end
39
+
40
+ def store_history(jid, task_args, time)
41
+ Sidekiq.redis do |conn|
42
+ task_trace = {jid: jid, name: task_name, args: task_args, enqueued_at: time.to_i}
43
+ conn.lpush(history_key, Sidekiq.dump_json(task_trace))
44
+ conn.ltrim(history_key, 0, HISTORY_LIMIT - 1)
45
+ end
46
+ end
47
+
48
+ def store_enqueue(jid, args)
49
+ time = Time.now
50
+ store_time(time, "last_enqueue_at")
51
+ store_history(jid, args, time)
52
+ end
53
+
54
+ def store_execution(jid)
55
+ time = Time.now
56
+ store_time(time, "last_execution_at")
57
+ store_execution_time_in_history(jid, time)
58
+ end
59
+
60
+ private
61
+
62
+ def store_time(time, time_key)
63
+ Sidekiq.redis { |conn| conn.hset(jid_key, time_key, time.to_i) }
64
+ end
65
+
66
+ def stored_time(time_key)
67
+ timestamp = Sidekiq.redis { |conn| conn.hget(jid_key, time_key) }
68
+
69
+ [nil, ""].include?(timestamp) ? nil : Time.at(timestamp.to_i)
70
+ end
71
+
72
+ def store_execution_time_in_history(jid, time)
73
+ Sidekiq.redis do |conn|
74
+ conn.lrange(history_key, 0, -1).each_with_index do |raw, index|
75
+ entry = Sidekiq.load_json(raw)
76
+ next unless entry["jid"] == jid
77
+
78
+ conn.lset(history_key, index, Sidekiq.dump_json(entry.merge("executed_at" => time.to_i)))
79
+ break
80
+ end
81
+ end
82
+ end
83
+ end
84
+ end
85
+ end