kiqchestra 1.0.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.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: ee0fcc0d1b95edbe89f701de4360704c050c1cd66bc19825afb9f7c94da758a7
4
+ data.tar.gz: 54828682b4d25ed828f8cd3a531dc86d8475e43fe42f863d28ec975e6e57e876
5
+ SHA512:
6
+ metadata.gz: ae4249497721d90095c82d977a0b7e5d968d2ce10ee90e1a07b4bfa74b33e9053d2f9d3ef8eccc456088038646f09ff289200404c4e1d9cc71df8dbfe9ee1018
7
+ data.tar.gz: 70b2a244001ec267bea317316a6f5a31ea2fab82c109561bcf3260226a75667990f4c902fa80d4a30fa20bacd0548bb170f986e5e972d888b7bd89234a43080e
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,17 @@
1
+ AllCops:
2
+ TargetRubyVersion: 3.0
3
+
4
+ Layout/LineLength:
5
+ Exclude:
6
+ - Gemfile
7
+
8
+ Metrics/BlockLength:
9
+ Exclude:
10
+ - kiqchestra.gemspec
11
+ - spec/**/*
12
+
13
+ Style/StringLiterals:
14
+ EnforcedStyle: double_quotes
15
+
16
+ Style/StringLiteralsInInterpolation:
17
+ EnforcedStyle: double_quotes
data/CHANGELOG.md ADDED
@@ -0,0 +1,19 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
+
7
+ ## [1.0.0] - 2025-01-17
8
+
9
+ ### Added
10
+
11
+ - Initial release of Kiqchestra, a Sidekiq-based job orchestration framework.
12
+ - Support for defining workflows with job dependencies.
13
+ - Redis-based default metadata store for job and workflow progress tracking.
14
+ - Ability to implement custom stores for workflow metadata and progress.
15
+ - Progress tracking for workflows.
16
+
17
+ ### Documentation
18
+
19
+ - Comprehensive README with usage examples, installation instructions, and contribution guidelines.
@@ -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 aries
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,97 @@
1
+ # Kiqchestra - Sidekiq Job Orchestration Framework
2
+
3
+ Kiqchestra is a lightweight Sidekiq-based job orchestration framework that allows you to manage complex job workflows with dependencies between tasks. Unlike traditional background job frameworks, Kiqchestra simplifies job orchestration by allowing jobs to be executed based on the completion of other jobs, ensuring smooth and controlled execution of task sequences.
4
+
5
+ ## Features
6
+
7
+ - **Job Dependencies**: Easily manage dependency relationship between jobs and ensure they run in the correct order.
8
+ - **Progress Tracking**: Track the progress of each job in a workflow. Customizable for your need.
9
+
10
+ ## Installation
11
+
12
+ Add the following line to your `Gemfile`:
13
+
14
+ ```ruby
15
+ gem 'kiqchestra'
16
+ ```
17
+
18
+ Run `bundle install` to install the gem.
19
+ Alternatively, you can install the gem manually:
20
+
21
+ ```bash
22
+ gem install kiqchestra
23
+ ```
24
+
25
+ ## Configuration
26
+
27
+ By default, Kiqchestra uses a Redis-backed store (`DefaultWorkflowStore`) that caches workflow metadata and progress for 7 days, but you can provide your own custom store if needed. To use `DefaultWorkflowStore`, make sure to have `ENV[REDIS_URL]` - if not defined, `redis://localhost:6379/0` will be used (see [Kiqchestra::RedisClient](https://github.com/ariesjchang/kiqchestra/blob/main/lib/kiqchestra/redis_client.rb)).
28
+
29
+ ### Customizing WorkflowStore
30
+
31
+ You can create your own store by subclassing Kiqchestra::WorkflowStore and implementing the required methods (`read_metadata`, `write_metadata`, `read_progress`, `write_progress`).
32
+
33
+ For example:
34
+
35
+ ```ruby
36
+ class MyCustomWorkflowStore < Kiqchestra::WorkflowStore
37
+ def read_metadata(workflow_id)
38
+ # Your implementation
39
+ end
40
+
41
+ def write_metadata(workflow_id, metadata)
42
+ # Your implementation
43
+ end
44
+
45
+ def read_progress(workflow_id)
46
+ # Your implementation
47
+ end
48
+
49
+ def write_progress(workflow_id, progress)
50
+ # Your implementation
51
+ end
52
+ end
53
+
54
+ Kiqchestra.configure do |config|
55
+ config.store = MyCustomWorkflowStore.new
56
+ end
57
+ ```
58
+
59
+ ## Usage
60
+
61
+ ### Defining a Workflow
62
+
63
+ A workflow is defined by a unique workflow_id and a set of metadata that describes the jobs and their dependencies. The metadata for each job should include:
64
+ - `deps`: An array of jobs that must complete before the current job can start.
65
+ - `args`: Arguments to be passed to the job.
66
+
67
+ Here's an example of a workflow metadata definition:
68
+
69
+ ```ruby
70
+ metadata = {
71
+ a_job: { deps: [], args: [1, 2, 3] },
72
+ b_job: { deps: [:a_job], args: [4, 5] },
73
+ c_job: { deps: [:a_job], args: nil },
74
+ d_job: { deps: [:b_job, :c_job], args: [6] }
75
+ }
76
+ ```
77
+
78
+ Make sure each job name corresponds to an actual existing class that is a subclass of `Kiqchestra::BaseJob` (ex. `a_job` would be `AJob`).
79
+ You can create and run a workflow by:
80
+
81
+ ```ruby
82
+ workflow = Kiqchestra::Workflow.new('workflow_123', metadata)
83
+ workflow.execute
84
+ ```
85
+
86
+ ## Contributing
87
+ Contributions to Kiqchestra are welcome! To contribute:
88
+
89
+ 1. Fork the repository.
90
+ 2. Create a new branch.
91
+ 3. Make your changes.
92
+ 4. Run tests.
93
+ 5. Open a pull request.
94
+
95
+ ## License
96
+
97
+ Kiqchestra is released under the MIT License.
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]
@@ -0,0 +1,83 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "sidekiq"
4
+ require "kiqchestra/workflow"
5
+
6
+ module Kiqchestra
7
+ # BaseJob provides a standard interface for all workflow jobs.
8
+ # It includes the necessary callback mechanism to notify the Workflow
9
+ # once a job has completed and trigger any follow-up jobs based on the dependencies.
10
+ #
11
+ # Subclasses are expected to implement the `perform` method to define
12
+ # the specific logic for the job. This method will be automatically
13
+ # invoked as part of the job execution flow, and callbacks like `on_complete`
14
+ # will be triggered when the job finishes.
15
+ class BaseJob
16
+ include Sidekiq::Worker
17
+
18
+ # Perform the job and trigger workflow callbacks on completion.
19
+ #
20
+ # @param workflow_id [String] The unique ID for the workflow
21
+ # @param args [Array] Arguments to be passed to the specific job's perform method
22
+ def perform(workflow_id, *args)
23
+ @workflow_id = workflow_id
24
+ @args = args
25
+
26
+ log_info "Starting job #{job_name} in workflow #{@workflow_id} with args: #{@args.inspect}"
27
+
28
+ begin
29
+ # Delegate the actual job work to the subclass's perform method
30
+ perform_job(*@args)
31
+
32
+ workflow.handle_completed_job job_name
33
+ rescue StandardError => e
34
+ log_error "#{job_name} failed: #{e.message}"
35
+
36
+ # Re-raise to let Sidekiq handle retries
37
+ raise e
38
+ end
39
+ end
40
+
41
+ # Subclasses should define the actual job logic here.
42
+ # This is called by the `perform` method of BaseJob.
43
+ #
44
+ # @param args [Array] Arguments passed to the job
45
+ def perform_job(*args)
46
+ raise NotImplementedError, "Subclasses must implement `perform_job`"
47
+ end
48
+
49
+ private
50
+
51
+ # Fetch the workflow instance lazily, using pre-fetched workflow data.
52
+ def workflow
53
+ @workflow ||= Workflow.new @workflow_id, metadata
54
+ end
55
+
56
+ # Extract job name from the class
57
+ # Equivalent to Rails's .demodulize.underscore
58
+ def job_name
59
+ self.class.name.split("::").last.gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2')
60
+ .gsub(/([a-z\d])([A-Z])/, '\1_\2').tr("-", "_").downcase
61
+ end
62
+
63
+ # Fetch the cached workflow data from redis
64
+ def metadata
65
+ return @metadata if @metadata&.present?
66
+
67
+ metadata = Kiqchestra.config.store.read_metadata @workflow_id
68
+ @metadata = metadata.transform_keys(&:to_sym).transform_values do |data|
69
+ { deps: data["deps"].map(&:to_sym), args: data["args"] }
70
+ end
71
+ end
72
+
73
+ # Logs an info-level message
74
+ def log_info(message)
75
+ Sidekiq.logger.info "kiqchestra: #{message}"
76
+ end
77
+
78
+ # Logs an error-level message
79
+ def log_error(message)
80
+ Sidekiq.logger.error "kiqchestra: #{message}"
81
+ end
82
+ end
83
+ end
@@ -0,0 +1,28 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "kiqchestra/default_workflow_store"
4
+
5
+ module Kiqchestra
6
+ # The Config class provides a configuration object for Kiqchestra, allowing users
7
+ # to customize various aspects of the library's behavior.
8
+ #
9
+ # By default, it initializes with a DefaultWorkflowStore instance for managing
10
+ # workflow storage (dependencies, progress, etc.). Users can override this with
11
+ # a custom store by setting the `workflow_store` attribute.
12
+ #
13
+ # Attributes:
14
+ # - `workflow_store`: The object responsible for storing workflow-related data.
15
+ # Defaults to an instance of `DefaultWorkflowStore`.
16
+ #
17
+ # Example Usage:
18
+ # Kiqchestra.configure do |config|
19
+ # config.store = MyCustomWorkflowStore.new
20
+ # end
21
+ class Config
22
+ attr_accessor :store
23
+
24
+ def initialize
25
+ @store = DefaultWorkflowStore.new
26
+ end
27
+ end
28
+ end
@@ -0,0 +1,82 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "kiqchestra/redis_client"
5
+ require "kiqchestra/workflow_store"
6
+
7
+ module Kiqchestra
8
+ # The DefaultWorkflowStore class is the default implementation of WorkflowStore
9
+ # for storing workflow dependencies, progress, and arguments in a Redis-backed store.
10
+ #
11
+ # This implementation uses Redis for persistence, providing an efficient and
12
+ # scalable storage system for workflows. Users can customize this by implementing
13
+ # their own subclass of WorkflowStore if needed.
14
+ #
15
+ # Example Usage:
16
+ # store = Kiqchestra::DefaultWorkflowStore.new
17
+ # store.write_metadata "workflow_123", { a_job: { deps: [], args: [1, 2, 3] } }
18
+ # metadata = store.read_metadata "workflow_123"
19
+ # store.write_progress "workflow_123", { a_job: "complete" }
20
+ # progress = store.read_progress "workflow_123"
21
+ class DefaultWorkflowStore < WorkflowStore
22
+ # Reads the metadata for a workflow from Redis.
23
+ #
24
+ # @param workflow_id [String] The workflow ID to retrieve workflow data for.
25
+ # @return [Hash] A hash representing the workflow metadata, where each key is
26
+ # a task ID and the value is a hash with keys `:deps` and `:args`.
27
+ def read_metadata(workflow_id)
28
+ raw_data = Kiqchestra::RedisClient.client.get metadata_key(workflow_id)
29
+ JSON.parse(raw_data || "{}")
30
+ end
31
+
32
+ # Writes the metadata for a workflow to Redis.
33
+ #
34
+ # @param workflow_id [String] The workflow ID to store dependencies for.
35
+ # @param metadata [Hash] A hash representing the metadata to store.
36
+ # @example { a_job: { deps: [], args: [1, 2, 3] }, b_job: { deps: [:a_job], args: nil } }
37
+ def write_metadata(workflow_id, metadata)
38
+ Kiqchestra::RedisClient.client.set metadata_key(workflow_id),
39
+ metadata.to_json,
40
+ ex: 604_800 # Default TTL: 7 days
41
+ end
42
+
43
+ # Reads the progress of a workflow from Redis.
44
+ #
45
+ # @param workflow_id [String] The workflow ID to retrieve progress for.
46
+ # @return [Hash] A hash representing the progress of the workflow, where each
47
+ # key is a task ID and the value indicates the status.
48
+ def read_progress(workflow_id)
49
+ raw_data = Kiqchestra::RedisClient.client.get progress_key(workflow_id)
50
+ JSON.parse(raw_data || "{}")
51
+ end
52
+
53
+ # Writes the progress of a workflow to Redis.
54
+ #
55
+ # @param workflow_id [String] The workflow ID to store progress for.
56
+ # @param progress [Hash] A hash representing the progress to store.
57
+ # @example { a_worker: "complete", b_worker: "in_progress" }
58
+ def write_progress(workflow_id, progress)
59
+ Kiqchestra::RedisClient.client.set progress_key(workflow_id),
60
+ progress.to_json,
61
+ ex: 604_800 # Default TTL: 7 days
62
+ end
63
+
64
+ private
65
+
66
+ # Generates the Redis key for storing metadata of a specific workflow.
67
+ #
68
+ # @param workflow_id [String] The workflow ID.
69
+ # @return [String] The Redis key for metadata.
70
+ def metadata_key(workflow_id)
71
+ "workflow:#{workflow_id}:metadata"
72
+ end
73
+
74
+ # Generates the Redis key for storing progress of a specific workflow.
75
+ #
76
+ # @param workflow_id [String] The workflow ID.
77
+ # @return [String] The Redis key for progress.
78
+ def progress_key(workflow_id)
79
+ "workflow:#{workflow_id}:progress"
80
+ end
81
+ end
82
+ end
@@ -0,0 +1,15 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "redis"
4
+
5
+ module Kiqchestra
6
+ # Redis client used for caching workflow dependencies and progress.
7
+ #
8
+ # Dependencies:
9
+ # - `redis` gem: Ensure this is included in your Gemfile.
10
+ class RedisClient
11
+ def self.client
12
+ @client ||= Redis.new(url: ENV["REDIS_URL"] || "redis://localhost:6379/0")
13
+ end
14
+ end
15
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Kiqchestra
4
+ VERSION = "1.0.0"
5
+ end
@@ -0,0 +1,185 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "sidekiq"
4
+ require "redis"
5
+
6
+ module Kiqchestra
7
+ # The Workflow class provides functionality for orchestrating
8
+ # Sidekiq-based job workflows. It manages task dependencies
9
+ # and tracks their completion status.
10
+ class Workflow
11
+ # Initializes the workflow with workflow id and data.
12
+ #
13
+ # @param workflow_id [String] Unique ID for the workflow
14
+ # @param metadata [Hash] Hash defining jobs' dependencies and arguments
15
+ # @example {
16
+ # a_job: { deps: [], args: a_job_args },
17
+ # b_job: { deps: [:a_job], args: b_job_args },
18
+ # c_job: { deps: [:a_job], args: c_job_args },
19
+ # d_job: { deps: %i[b_job c_job], args: d_job_args }
20
+ # }
21
+ def initialize(workflow_id, metadata)
22
+ @workflow_id = workflow_id
23
+ @metadata = metadata
24
+ @logger = Logger.new($stdout)
25
+
26
+ validate_metadata
27
+ cache_metadata metadata
28
+ end
29
+
30
+ # Starts the workflow execution.
31
+ def execute
32
+ read_progress
33
+ @metadata.each do |job, job_data|
34
+ process_job job, job_data
35
+ end
36
+
37
+ conclude_workflow if workflow_complete?
38
+ end
39
+
40
+ # Handles the completion of a job and triggers the next jobs if dependencies are met.
41
+ #
42
+ # @param job [String] The completed job name (ex. "example_job")
43
+ def handle_completed_job(job)
44
+ update_progress job, "complete"
45
+ log_info "#{job} completed for workflow #{@workflow_id}"
46
+
47
+ execute
48
+ end
49
+
50
+ private
51
+
52
+ # Validates the workflow data structure for a workflow.
53
+ # Ensures that all job metadata, dependencies, and arguments conform to the expected format.
54
+ def validate_metadata
55
+ # Ensure the root structure is a hash
56
+ raise ArgumentError, "Metadata must be a hash" unless @metadata.is_a?(Hash)
57
+
58
+ # Validate each job's metadata
59
+ @metadata.each do |job, data|
60
+ validate_job_metadata job, data
61
+ end
62
+ end
63
+
64
+ # Validates the metadata for a specific job.
65
+ # Ensures that the metadata is a hash and its components (deps and args) are correctly structured.
66
+ #
67
+ # @param job [Symbol, String] The job identifier
68
+ # @param data [Hash] Metadata for the job (includes deps and args)
69
+ def validate_job_metadata(job, data)
70
+ # Check if the metadata is a hash
71
+ raise ArgumentError, "Metadata for #{job} must be a hash" unless data.is_a?(Hash)
72
+
73
+ # Validate dependencies and arguments separately
74
+ validate_deps job, data[:deps]
75
+ validate_args job, data[:args]
76
+ end
77
+
78
+ # Validates the dependencies (`deps`) for a specific job.
79
+ # Ensures that dependencies are an array of symbols or strings.
80
+ #
81
+ # @param job [Symbol, String] The job identifier
82
+ # @param deps [Array<Symbol, String>] Dependencies for the job
83
+ def validate_deps(job, deps)
84
+ return if deps.is_a?(Array) && deps.all? { |dep| dep.is_a?(String) || dep.is_a?(Symbol) }
85
+
86
+ raise ArgumentError, "Dependencies for #{job} must be an array of strings or symbols"
87
+ end
88
+
89
+ # Validates the arguments (`args`) for a specific job.
90
+ # Ensures that arguments are either an array or nil.
91
+ #
92
+ # @param job [Symbol, String] The job identifier
93
+ # @param args [Array, nil] Arguments for the job
94
+ def validate_args(job, args)
95
+ return if args.nil? || args.is_a?(Array)
96
+
97
+ raise ArgumentError, "Arguments for #{job} must be an array or nil"
98
+ end
99
+
100
+ # Caches the workflow data using the configured workflow store.
101
+ def cache_metadata(metadata)
102
+ Kiqchestra.config.store.write_metadata @workflow_id, metadata
103
+ end
104
+
105
+ # Processes a single job during workflow execution.
106
+ #
107
+ # @param job [String] The job identifier
108
+ # @param job_metadata [Hash] Metadata for the job (dependencies and arguments)
109
+ def process_job(job, job_metadata)
110
+ return if job_already_processed? job
111
+
112
+ return unless ready_to_execute? job_metadata[:deps]
113
+
114
+ args = job_metadata[:args] || []
115
+ enqueue_job job, args
116
+ end
117
+
118
+ # Checks if a job is already processed (completed or in_progress).
119
+ #
120
+ # @param job [String] The job identifier
121
+ # @return [Boolean] True if the job is completed or in progress
122
+ def job_already_processed?(job)
123
+ progress = read_progress
124
+ %w[complete in_progress].include? progress[job.to_s]
125
+ end
126
+
127
+ # Checks if a job is ready for execution (no dependencies or all dependencies completed).
128
+ #
129
+ # @param deps [Array<Symbol, String>] Dependencies for the job
130
+ # @return [Boolean] True if the job is ready to execute
131
+ def ready_to_execute?(deps)
132
+ progress = read_progress
133
+ deps.empty? || deps.all? { |dep| progress[dep.to_s] == "complete" }
134
+ end
135
+
136
+ # Enqueues a Sidekiq job for execution and saves the job's status as "in_progress".
137
+ #
138
+ # @param job [String] Job name in snake_case.
139
+ # @param args [Array] Arguments to pass to the job's perform method (default: empty array).
140
+ def enqueue_job(job, args = [])
141
+ return if job_already_processed? job
142
+
143
+ update_progress job, "in_progress"
144
+
145
+ job_class_name = job.to_s.split("_").map(&:capitalize).join
146
+ job_class = Object.const_get(job_class_name)
147
+ job_class.perform_async @workflow_id, *args
148
+ rescue NameError
149
+ raise "Class for job '#{job}' not defined"
150
+ end
151
+
152
+ # Logs a message if a logger is configured.
153
+ def log_info(message)
154
+ @logger&.info "kiqchestra: #{message}"
155
+ end
156
+
157
+ # Updates the workflow progress for a job.
158
+ #
159
+ # @param job [String] job name in snake_case
160
+ # @param status [String] job status ("in_progress", "completed")
161
+ def update_progress(job, status)
162
+ progress = read_progress
163
+ progress[job] = status
164
+ Kiqchestra.config.store.write_progress @workflow_id, progress
165
+ end
166
+
167
+ # Reads the current workflow progress from Redis.
168
+ #
169
+ # @return [Hash] The current progress of the workflow
170
+ def read_progress
171
+ Kiqchestra.config.store.read_progress @workflow_id
172
+ end
173
+
174
+ # Checks if the workflow is complete (all jobs are completed) and logs the workflow's end.
175
+ def workflow_complete?
176
+ progress = read_progress
177
+ @metadata.keys.all? { |job| progress[job.to_s] == "complete" }
178
+ end
179
+
180
+ # Executes the customizable on-complete procedure for the workflow.
181
+ def conclude_workflow
182
+ log_info "Workflow #{@workflow_id} has completed successfully."
183
+ end
184
+ end
185
+ end
@@ -0,0 +1,55 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Kiqchestra
4
+ # The WorkflowStore class serves as an abstract base class for implementing
5
+ # custom storage mechanisms for workflow progress, dependencies, and arguments.
6
+ # It defines abstract methods that must be implemented by subclasses.
7
+ #
8
+ # By default, Kiqchestra uses DefaultWorkflowStore. Users are free to create
9
+ # their own custom implementation of WorkflowStore to change storage system
10
+ # (file-based, database, etc.) or specific details of implementations.
11
+ class WorkflowStore
12
+ # Ensures subclasses properly implement required methods.
13
+ def initialize(*_args)
14
+ # No initialization logic here
15
+ end
16
+
17
+ # Reads the workflow data for a workflow.
18
+ #
19
+ # @return [Hash] A hash representing the metadata for the workflow, where each key
20
+ # is a task ID and the value is a hash with keys `:deps` and `:args`.
21
+ # @raise [NotImplementedError] This method must be implemented by a subclass.
22
+ def read_metadata
23
+ raise NotImplementedError, "Subclasses must implement the read_workflow_data method"
24
+ end
25
+
26
+ # Writes the workflow data for a workflow to the store.
27
+ #
28
+ # @param workflow_data [Hash] A hash representing the workflow data to store, where each key
29
+ # is a task ID and the value is a hash with keys `:deps` and `:args`.
30
+ # @example { a_job: { deps: [], args: [1, 2, 3] }, b_job: { deps: [:a_job], args: nil } }
31
+ # @raise [NotImplementedError] This method must be implemented by a subclass.
32
+ def write_metadata(_metadata)
33
+ raise NotImplementedError, "Subclasses must implement the write_workflow_data method"
34
+ end
35
+
36
+ # Reads the progress of a workflow.
37
+ #
38
+ # @return [Hash] A hash representing the progress of the workflow, where each key
39
+ # is a task ID and the value indicates the completion status.
40
+ # @raise [NotImplementedError] This method must be implemented by a subclass.
41
+ def read_progress
42
+ raise NotImplementedError, "Subclasses must implement the read_progress method"
43
+ end
44
+
45
+ # Writes the progress of a workflow to the store.
46
+ #
47
+ # @param progress [Hash] A hash representing the progress to store, where each key
48
+ # is a task ID and the value indicates the completion status.
49
+ # @example { a_worker: 'complete', b_worker: 'in_progress' }
50
+ # @raise [NotImplementedError] This method must be implemented by a subclass.
51
+ def write_progress(_progress)
52
+ raise NotImplementedError, "Subclasses must implement the write_progress method"
53
+ end
54
+ end
55
+ end
data/lib/kiqchestra.rb ADDED
@@ -0,0 +1,26 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "sidekiq"
4
+ require "kiqchestra/base_job"
5
+ require "kiqchestra/config"
6
+ require "kiqchestra/version"
7
+ require "kiqchestra/workflow"
8
+ require "kiqchestra/workflow_store"
9
+
10
+ # Kiqchestra is a Sidekiq-based job orchestration framework designed for
11
+ # workflows where tasks depend on the completion of other tasks.
12
+ # It simplifies the process of managing complex job dependencies, enabling developers
13
+ # to focus on business logic rather than the intricacies of dependency management.
14
+ module Kiqchestra
15
+ class << self
16
+ # Yields the configuration object to allow customization of settings.
17
+ def configure
18
+ yield config
19
+ end
20
+
21
+ # Returns the configuration object, initializing it if necessary.
22
+ def config
23
+ @config ||= Config.new
24
+ end
25
+ end
26
+ end
@@ -0,0 +1,4 @@
1
+ module Kiqchestra
2
+ VERSION: String
3
+ # See the writing guide of rbs: https://github.com/ruby/rbs#guides
4
+ end
metadata ADDED
@@ -0,0 +1,78 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: kiqchestra
3
+ version: !ruby/object:Gem::Version
4
+ version: 1.0.0
5
+ platform: ruby
6
+ authors:
7
+ - aries
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2025-01-17 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: sidekiq
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: 6.5.5
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: 6.5.5
27
+ description: Kiqchestra enhances the power of Sidekiq by introducing a job orchestration
28
+ framework designed to handle complex workflows with ease and efficiency.
29
+ email:
30
+ - edwardjhchang@gmail.com
31
+ executables: []
32
+ extensions: []
33
+ extra_rdoc_files: []
34
+ files:
35
+ - ".rspec"
36
+ - ".rubocop.yml"
37
+ - CHANGELOG.md
38
+ - CODE_OF_CONDUCT.md
39
+ - LICENSE.txt
40
+ - README.md
41
+ - Rakefile
42
+ - lib/kiqchestra.rb
43
+ - lib/kiqchestra/base_job.rb
44
+ - lib/kiqchestra/config.rb
45
+ - lib/kiqchestra/default_workflow_store.rb
46
+ - lib/kiqchestra/redis_client.rb
47
+ - lib/kiqchestra/version.rb
48
+ - lib/kiqchestra/workflow.rb
49
+ - lib/kiqchestra/workflow_store.rb
50
+ - sig/kiqchestra.rbs
51
+ homepage: https://github.com/ariesjchang/kiqchestra.
52
+ licenses:
53
+ - MIT
54
+ metadata:
55
+ allowed_push_host: https://rubygems.org
56
+ homepage_uri: https://github.com/ariesjchang/kiqchestra
57
+ source_code_uri: https://github.com/ariesjchang/kiqchestra
58
+ changelog_uri: https://github.com/ariesjchang/kiqchestra/blob/main/CHANGELOG.md
59
+ post_install_message:
60
+ rdoc_options: []
61
+ require_paths:
62
+ - lib
63
+ required_ruby_version: !ruby/object:Gem::Requirement
64
+ requirements:
65
+ - - ">="
66
+ - !ruby/object:Gem::Version
67
+ version: 3.0.0
68
+ required_rubygems_version: !ruby/object:Gem::Requirement
69
+ requirements:
70
+ - - ">="
71
+ - !ruby/object:Gem::Version
72
+ version: '0'
73
+ requirements: []
74
+ rubygems_version: 3.5.16
75
+ signing_key:
76
+ specification_version: 4
77
+ summary: Job Workflow Orchestration Layer for Sidekiq
78
+ test_files: []