async_flow 0.1.1

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 1a0932062a6d0085091f25f44e444db319e317e1377c233a4095c456d5acd838
4
+ data.tar.gz: 8615aa42a70845450fb12698b02dac8b8e14b2c76bf4f327b6a2b9d77f0aaf7c
5
+ SHA512:
6
+ metadata.gz: 44a09088ac5946e38fc2bdf357edb0f9f34ee9d00e0f77330c7153076237aa0cd22597261e6a70075ff3161e3076ec92bc0a6b735097f6a0b9fd1ebf4459dbc5
7
+ data.tar.gz: c808ab2503937f11fe357c002f532a6ce077e491d7a096c4291b051a6ba03a835f92840fb94d96d363007d864a93f29449cfa576941083d38eadbba2caae718f
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format progress
2
+ --color
3
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,25 @@
1
+ require:
2
+ - rubocop-rspec
3
+ - rubocop-performance
4
+ - rubocop-rake
5
+
6
+ AllCops:
7
+ NewCops: enable
8
+ TargetRubyVersion: 3.0
9
+
10
+ Style/StringLiterals:
11
+ Enabled: true
12
+ EnforcedStyle: double_quotes
13
+ ConsistentQuotesInMultiline: false
14
+
15
+ Style/Documentation:
16
+ Enabled: false
17
+
18
+ RSpec/MultipleExpectations:
19
+ Enabled: false
20
+
21
+ RSpec/ExampleLength:
22
+ Enabled: false
23
+
24
+ RSpec/FilePath:
25
+ Enabled: false
@@ -0,0 +1,84 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ 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.
6
+
7
+ We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
8
+
9
+ ## Our Standards
10
+
11
+ Examples of behavior that contributes to a positive environment for our community include:
12
+
13
+ * Demonstrating empathy and kindness toward other people
14
+ * Being respectful of differing opinions, viewpoints, and experiences
15
+ * Giving and gracefully accepting constructive feedback
16
+ * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
17
+ * Focusing on what is best not just for us as individuals, but for the overall community
18
+
19
+ Examples of unacceptable behavior include:
20
+
21
+ * The use of sexualized language or imagery, and sexual attention or
22
+ advances of any kind
23
+ * Trolling, insulting or derogatory comments, and personal or political attacks
24
+ * Public or private harassment
25
+ * Publishing others' private information, such as a physical or email
26
+ address, without their explicit permission
27
+ * Other conduct which could reasonably be considered inappropriate in a
28
+ professional setting
29
+
30
+ ## Enforcement Responsibilities
31
+
32
+ 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.
33
+
34
+ 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.
35
+
36
+ ## Scope
37
+
38
+ 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.
39
+
40
+ ## Enforcement
41
+
42
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at laertis.pappas@gmail.com. All complaints will be reviewed and investigated promptly and fairly.
43
+
44
+ All community leaders are obligated to respect the privacy and security of the reporter of any incident.
45
+
46
+ ## Enforcement Guidelines
47
+
48
+ Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
49
+
50
+ ### 1. Correction
51
+
52
+ **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
53
+
54
+ **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.
55
+
56
+ ### 2. Warning
57
+
58
+ **Community Impact**: A violation through a single incident or series of actions.
59
+
60
+ **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.
61
+
62
+ ### 3. Temporary Ban
63
+
64
+ **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
65
+
66
+ **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.
67
+
68
+ ### 4. Permanent Ban
69
+
70
+ **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.
71
+
72
+ **Consequence**: A permanent ban from any sort of public interaction within the community.
73
+
74
+ ## Attribution
75
+
76
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
77
+ available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
78
+
79
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
80
+
81
+ [homepage]: https://www.contributor-covenant.org
82
+
83
+ For answers to common questions about this code of conduct, see the FAQ at
84
+ https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
data/Gemfile ADDED
@@ -0,0 +1,15 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+
5
+ # Specify your gem's dependencies in async_flow.gemspec
6
+ gemspec
7
+
8
+ gem "rake"
9
+ gem "rspec"
10
+ gem "rubocop"
11
+ gem "rubocop-performance"
12
+ gem "rubocop-rake"
13
+ gem "rubocop-rspec"
14
+ gem "rubycritic"
15
+ gem "simplecov", require: false, group: :test
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2023 Laertis Pappas
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/Makefile ADDED
@@ -0,0 +1,4 @@
1
+ .PHONY: flow
2
+
3
+ test:
4
+ @bundle exec rspec spec
data/README.md ADDED
@@ -0,0 +1,37 @@
1
+ # Airflow
2
+
3
+ Welcome to your new gem! In this directory, you'll find the files you need to be able to package up your Ruby library into a gem. Put your Ruby code in the file `lib/airflow`. To experiment with that code, run `bin/console` for an interactive prompt.
4
+
5
+ TODO: Delete this and the text above, and describe your gem
6
+
7
+ ## Installation
8
+
9
+ Install the gem and add to the application's Gemfile by executing:
10
+
11
+ $ bundle add airflow
12
+
13
+ If bundler is not being used to manage dependencies, install the gem by executing:
14
+
15
+ $ gem install airflow
16
+
17
+ ## Usage
18
+
19
+ TODO: Write usage instructions here
20
+
21
+ ## Development
22
+
23
+ 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.
24
+
25
+ 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).
26
+
27
+ ## Contributing
28
+
29
+ Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/airflow. 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/[USERNAME]/async_flow/blob/master/CODE_OF_CONDUCT.md).
30
+
31
+ ## License
32
+
33
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
34
+
35
+ ## Code of Conduct
36
+
37
+ Everyone interacting in the Airflow project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/async_flow/blob/master/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,8 @@
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
+ task default: :spec
@@ -0,0 +1,35 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "lib/async_flow/version"
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = "async_flow"
7
+ spec.version = Airflow::VERSION
8
+ spec.authors = ["Laertis Pappas"]
9
+ spec.email = ["laertis.pappas@gmail.com"]
10
+
11
+ spec.summary = "Durable async workflow orchestration engine for Ruby"
12
+ spec.description = "Durable async workflow orchestration engine for Ruby"
13
+ spec.homepage = "https://github.com/laertispappas/airflow"
14
+ spec.license = "MIT"
15
+ spec.required_ruby_version = ">= 3.0"
16
+
17
+ spec.metadata["homepage_uri"] = spec.homepage
18
+ spec.metadata["source_code_uri"] = spec.homepage
19
+ spec.metadata["changelog_uri"] = spec.homepage
20
+
21
+ # Specify which files should be added to the gem when it is released.
22
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
23
+ spec.files = Dir.chdir(__dir__) do
24
+ `git ls-files -z`.split("\x0").reject do |f|
25
+ (f == __FILE__) || f.match(%r{\A(?:(?:bin|test|spec|features)/|\.(?:git|travis|circleci)|appveyor)})
26
+ end
27
+ end
28
+ spec.bindir = "bin"
29
+ spec.executables = []
30
+ spec.require_paths = ["lib"]
31
+ spec.metadata["rubygems_mfa_required"] = "true"
32
+
33
+ spec.add_dependency "async"
34
+ spec.add_dependency "mediator-rb"
35
+ end
@@ -0,0 +1,51 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "async_flow/commands"
4
+ require "async_flow/models"
5
+ require "mediator"
6
+ require "forwardable"
7
+
8
+ module Airflow
9
+ class Client
10
+ class ResultWrapper
11
+ extend Forwardable
12
+
13
+ attr_reader :client, :workflow_id
14
+
15
+ def initialize(client, workflow_id)
16
+ @client = client
17
+ @workflow_id = workflow_id
18
+ end
19
+
20
+ def workflow_info
21
+ @client.workflow_info(@workflow_id)
22
+ end
23
+
24
+ def result
25
+ @client.result(@workflow_id)
26
+ end
27
+ end
28
+
29
+ def start_workflow(workflow_name_or_class, workflow_id:)
30
+ workflow_name = Workflow.definitions.get(workflow_name_or_class)._type
31
+ cmd = Commands::StartWorkflow.new(workflow_name: workflow_name, workflow_id: workflow_id, queue: "default")
32
+ Airflow.mediator.accept(cmd).then do
33
+ ResultWrapper.new(self, workflow_id)
34
+ end
35
+ end
36
+
37
+ def workflow_info(workflow_id)
38
+ run = Persistence.workflow_runs.find_by_workflow_id(workflow_id)
39
+ Workflow::Info.from(run)
40
+ end
41
+
42
+ def result(workflow_id)
43
+ run = Persistence.workflow_runs.find_by_workflow_id(workflow_id)
44
+ until run.completed?
45
+ sleep(1) # TODO: Notify instead of polling from DB
46
+ run = Persistence.workflow_runs.find_by_workflow_id(workflow_id)
47
+ end
48
+ run.result
49
+ end
50
+ end
51
+ end
@@ -0,0 +1,10 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Airflow
4
+ module Commands
5
+ StartWorkflow = Struct.new(:workflow_name, :workflow_id, :queue, keyword_init: true)
6
+ GetWorkflowInfo = Struct.new(:workflow_id, keyword_init: true)
7
+
8
+ CompleteTaskCommand = Struct.new(:task_id, :result, keyword_init: true)
9
+ end
10
+ end
@@ -0,0 +1,22 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Airflow
4
+ module Definition
5
+ def self.included(base)
6
+ base.extend(ClassMethods)
7
+ end
8
+
9
+ module ClassMethods
10
+ def definitions
11
+ (@definitions ||= Set.new).tap do |arr|
12
+ arr.instance_eval do
13
+ def get(name_or_class)
14
+ definition = find { |spec| spec == name_or_class || spec._type == name_or_class }
15
+ definition || raise(Error, "#{self} #{name_or_class} not registered")
16
+ end
17
+ end
18
+ end
19
+ end
20
+ end
21
+ end
22
+ end
@@ -0,0 +1,51 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Airflow
4
+ module Executors
5
+ # TODO: Replace with ruby-concurrent
6
+ # TODO: min, masx threads
7
+ # TODO: queue size
8
+ class ThreadPoolExecutor
9
+ include Utils::Logger
10
+
11
+ def initialize(size)
12
+ @jobs = Queue.new
13
+ @pool = Array.new(size) do
14
+ Thread.new do
15
+ poll
16
+ end
17
+ end
18
+ end
19
+
20
+ def post(*args, &block)
21
+ # assert!
22
+ jobs << [block, args]
23
+ end
24
+
25
+ def shutdown
26
+ logger.info "shutting down executor"
27
+ pool.size.times do
28
+ post { throw :exit }
29
+ end
30
+
31
+ pool.each(&:join)
32
+ logger.info "executor shut down"
33
+ end
34
+
35
+ private
36
+
37
+ attr_reader :jobs, :pool
38
+
39
+ def poll
40
+ catch(:exit) do
41
+ loop do
42
+ job, args = jobs.pop
43
+ job.call(*args)
44
+ rescue StandardError => e # do not kill thread on errors
45
+ logger.error("Executor error: #{e.inspect} \n #{e.backtrace&.join("\n")}")
46
+ end
47
+ end
48
+ end
49
+ end
50
+ end
51
+ end
@@ -0,0 +1,49 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Airflow
4
+ class Future
5
+ def initialize
6
+ @task = Async do |task|
7
+ task.annotate "Future"
8
+ @result = yield
9
+ end
10
+ end
11
+
12
+ def value
13
+ @task.wait
14
+ @result
15
+ end
16
+
17
+ def ready?
18
+ @task.completed?
19
+ end
20
+ end
21
+
22
+ # class Future
23
+ # def initialize(&block)
24
+ # @result = nil
25
+ # @completed = false
26
+ # @mutex = Mutex.new
27
+ # @condition = ConditionVariable.new
28
+ #
29
+ # Thread.new do
30
+ # @result = block.call
31
+ # @mutex.synchronize do
32
+ # @completed = true
33
+ # @condition.signal
34
+ # end
35
+ # end
36
+ # end
37
+ #
38
+ # def value
39
+ # @mutex.synchronize do
40
+ # @condition.wait(@mutex) until @completed
41
+ # @result
42
+ # end
43
+ # end
44
+ #
45
+ # def ready?
46
+ # @completed
47
+ # end
48
+ # end
49
+ end
@@ -0,0 +1,26 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "async_flow/workflow"
4
+
5
+ module Airflow
6
+ module Handlers
7
+ class StartWorkflowHandler
8
+ def call(cmd)
9
+ run = Models::WorkflowRun.new(
10
+ workflow_id: cmd.workflow_id,
11
+ workflow_name: cmd.workflow_name
12
+ )
13
+ run.start
14
+ Persistence.workflow_runs.create!(run)
15
+ end
16
+ end
17
+
18
+ class CompleteTaskCommandHandler
19
+ def call(cmd)
20
+ run = Persistence.workflow_runs.find_run_by_task_id(cmd.task_id)
21
+ run.complete_task(cmd.task_id, cmd.result)
22
+ Persistence.workflow_runs.save!(run)
23
+ end
24
+ end
25
+ end
26
+ end
@@ -0,0 +1,11 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "logger"
4
+
5
+ module Airflow
6
+ class Logger < ::Logger
7
+ module Formatters
8
+ class Base < ::Logger::Formatter; end
9
+ end
10
+ end
11
+ end
@@ -0,0 +1,57 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Airflow
4
+ module Models
5
+ # TODO: Model queues, state, priority?
6
+ WorkflowRun = Struct.new(:id, :workflow_id, :workflow_name, :created_at, :updated_at, :status, :tasks,
7
+ keyword_init: true) do
8
+ def initialize(...)
9
+ super
10
+ self.tasks = []
11
+ end
12
+
13
+ def start
14
+ self.status = "started"
15
+ start_task(task_name: nil, is_workflow_task: true)
16
+ end
17
+
18
+ def start_task(task_name:, is_workflow_task:)
19
+ task = Models::Task.new(
20
+ task_name: task_name,
21
+ is_workflow_task: is_workflow_task,
22
+ status: "scheduled",
23
+ workflow_name: workflow_name,
24
+ workflow_id: workflow_id
25
+ )
26
+ tasks << task
27
+ task
28
+ end
29
+
30
+ def complete_task(task_id, result)
31
+ task = tasks.find { |t| t.id == task_id }
32
+ task.complete!
33
+ task.result = result
34
+ complete! if tasks.all?(&:completed?)
35
+ end
36
+
37
+ def complete!
38
+ self.status = "completed"
39
+ end
40
+
41
+ def completed?
42
+ status == "completed"
43
+ end
44
+ end
45
+
46
+ Task = Struct.new(:id, :workflow_id, :workflow_name, :task_name, :is_workflow_task, :queue, :status, :result,
47
+ :created_at, :updated_at, keyword_init: true) do
48
+ def complete!
49
+ self.status = "completed"
50
+ end
51
+
52
+ def completed?
53
+ status == "completed"
54
+ end
55
+ end
56
+ end
57
+ end
@@ -0,0 +1,76 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "securerandom"
4
+
5
+ module Airflow
6
+ module Persistence
7
+ EntityNotFound = Class.new(StandardError)
8
+ # TODO: Define persistence interfaces.
9
+
10
+ def self.clear
11
+ workflow_runs.clear
12
+ end
13
+
14
+ def self.workflow_runs
15
+ @workflow_runs ||= WorkflowRunRepository.new
16
+ end
17
+
18
+ class InMemoryRepository
19
+ attr_reader :store
20
+
21
+ def initialize(store = {})
22
+ @store = store
23
+ end
24
+
25
+ def all
26
+ store.values
27
+ end
28
+
29
+ def find(id)
30
+ @store[id] || raise(EntityNotFound, "missing entity with id #{id}")
31
+ end
32
+
33
+ def clear
34
+ @store = {}
35
+ end
36
+
37
+ private
38
+
39
+ def next_id
40
+ SecureRandom.uuid
41
+ end
42
+ end
43
+
44
+ class WorkflowRunRepository < InMemoryRepository
45
+ def create!(run)
46
+ run.tasks.each { |task| task.id = next_id }
47
+ run.id = next_id
48
+ @store[run.id] = run
49
+ end
50
+
51
+ def save!(run)
52
+ run.tasks.each { |task| task.id = next_id if task.id.nil? }
53
+ end
54
+
55
+ def find_run_by_task_id(task_id)
56
+ @store.values.find { |run| run.tasks.find { |task| task.id == task_id } }
57
+ end
58
+
59
+ def find_task(task_id)
60
+ @store.values.flat_map(&:tasks).find { |record| record.id == task_id } || raise(EntityNotFound)
61
+ end
62
+
63
+ def find_by_workflow_id(id)
64
+ @store.values.find { |run| run.workflow_id == id } || raise(EntityNotFound)
65
+ end
66
+
67
+ def next_task(is_workflow_task:)
68
+ task = @store.values.flat_map(&:tasks).find do |record|
69
+ record.is_workflow_task == is_workflow_task && record.status == "scheduled"
70
+ end
71
+ task.status = "TODO" if task
72
+ task
73
+ end
74
+ end
75
+ end
76
+ end
@@ -0,0 +1,90 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "async"
4
+ require "singleton"
5
+ require "async_flow/utils"
6
+ require "async_flow/state"
7
+ module Airflow
8
+ class Reactor
9
+ include Utils::Logger
10
+ include Singleton
11
+
12
+ class AsyncWrapper
13
+ def initialize(async_task)
14
+ @async_task = async_task
15
+ end
16
+
17
+ def schedule
18
+ task = async_task.async { |subtask| yield(AsyncWrapper.new(subtask)) }
19
+ AsyncWrapper.new(task)
20
+ end
21
+
22
+ # TODO: Unused
23
+ def wait
24
+ async_task.wait
25
+ end
26
+
27
+ private
28
+
29
+ attr_reader :async_task
30
+ end
31
+
32
+ def initialize
33
+ @commands = Queue.new
34
+ @mutex = Mutex.new
35
+ @thread = nil
36
+ @state = State.bg_state
37
+ start
38
+ end
39
+
40
+ def stop
41
+ mutex.synchronize do
42
+ return if state.stopped?
43
+
44
+ logger.info "stopping reactor"
45
+ schedule { state.stop! }
46
+ thread.join
47
+ logger.info "reactor thread stopped"
48
+ end
49
+ end
50
+
51
+ def schedule(&block)
52
+ raise Error, "reactor is in #{state.state} state" unless state.running?
53
+
54
+ commands << block
55
+ end
56
+
57
+ def start
58
+ logger.info "starting reactor"
59
+ mutex.synchronize do
60
+ return if state.running?
61
+
62
+ @thread = spawn_thread { run_reactor }
63
+ state.running!
64
+ logger.info "reactor started"
65
+ end
66
+ end
67
+
68
+ private
69
+
70
+ attr_reader :commands, :mutex, :thread, :state
71
+
72
+ def run_reactor
73
+ reactor = Async::Reactor.new
74
+ reactor.run do |task|
75
+ while state.running?
76
+ cmd = commands.pop
77
+ task.async { |subtask| cmd.call(AsyncWrapper.new(subtask)) }
78
+ end
79
+ end
80
+ ensure
81
+ # logger.info "stopping async reactor"
82
+ reactor.stop
83
+ end
84
+
85
+ def spawn_thread(&block)
86
+ Thread.current.name = "reactor"
87
+ Thread.new(&block)
88
+ end
89
+ end
90
+ end
@@ -0,0 +1,125 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "async_flow/utils"
4
+ require "async_flow/persistence"
5
+
6
+ module Airflow
7
+ module Runner
8
+ class Poller
9
+ attr_accessor :is_workflow_task
10
+
11
+ def initialize(persistence)
12
+ @persistence = persistence
13
+ @queue = Queue.new
14
+ end
15
+
16
+ def next_task
17
+ task = persistence.next_task(is_workflow_task: is_workflow_task)
18
+ yield(task) if task
19
+ # TODO: Add db notification
20
+ sleep(1)
21
+ end
22
+
23
+ private
24
+
25
+ attr_reader :persistence
26
+ end
27
+
28
+ class BaseRunner
29
+ include Utils::Logger
30
+
31
+ def initialize(definitions)
32
+ @poller = Poller.new(Persistence.workflow_runs)
33
+ @executor = Executors::ThreadPoolExecutor.new(1)
34
+ @definitions = definitions
35
+ @mutex = Mutex.new
36
+ end
37
+
38
+ # should already run parallel with the main worker
39
+ def run(reactor)
40
+ logger.info "starting runner #{self}"
41
+ running!
42
+ _loop(reactor)
43
+ end
44
+
45
+ def stop
46
+ executor&.shutdown
47
+ @running = false # TODO: Investigate why putting this on top does not stop the runner
48
+ logger.info "runner #{self} stopped"
49
+ end
50
+
51
+ private
52
+
53
+ attr_reader :poller, :executor, :definitions
54
+
55
+ def _loop(reactor) # rubocop:disable Metrics/MethodLength
56
+ while @running
57
+ poller.next_task do |dto|
58
+ reactor.schedule do
59
+ definition(dto).then do |user_task|
60
+ executor.post do
61
+ logger.debug "Runner<#{self}> executing user task<#{dto}> #{user_task}"
62
+ # TODO: handle failures
63
+ result = user_task.execute # TODO: task executor strategy, TODO: execute with input
64
+ cmd = Commands::CompleteTaskCommand.new(task_id: dto.id, result: result)
65
+ Airflow.mediator.accept(cmd)
66
+ logger.debug "Runner<#{self} >Finished executing user task<#{dto}> #{user_task}"
67
+ end
68
+ end
69
+ end
70
+ end
71
+ end
72
+ end
73
+
74
+ def running!
75
+ @mutex.synchronize do
76
+ raise Error, "Runner already running" if @running
77
+
78
+ @running = true
79
+ end
80
+ end
81
+ end
82
+
83
+ # TODO: Remove reference to worker, not used
84
+ class TaskRunner < BaseRunner
85
+ def initialize(...)
86
+ super
87
+ poller.is_workflow_task = false
88
+ end
89
+
90
+ private
91
+
92
+ def definition(dto)
93
+ klass = definitions.find { |task| task._type == dto.task_name }
94
+ raise Error, "Task #{dto.task_name} not registered. Available tasks #{definitions.map(&:_type)}" unless klass
95
+
96
+ klass.new
97
+ end
98
+
99
+ def running!
100
+ @mutex.synchronize do
101
+ raise Error, "Runner already running" if @running
102
+
103
+ @running = true
104
+ end
105
+ end
106
+ end
107
+
108
+ class WorkflowRunner < BaseRunner
109
+ def initialize(...)
110
+ super
111
+ poller.is_workflow_task = true
112
+ end
113
+
114
+ def definition(dto)
115
+ klass = definitions.find { |task| task._type == dto.workflow_name }
116
+ unless klass
117
+ raise Error,
118
+ "Workflow definition #{dto.workflow_name} not registered. Available tasks #{definitions.map(&:_type)}"
119
+ end
120
+
121
+ klass.new(dto)
122
+ end
123
+ end
124
+ end
125
+ end
@@ -0,0 +1,43 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Airflow
4
+ class SigHandler
5
+ include Utils::Logger
6
+
7
+ SIGNAL_HANDLERS = {
8
+ "INT" => ->(_subject) { raise Interrupt },
9
+ "TERM" => ->(_subject) { raise Interrupt }
10
+ }.freeze
11
+
12
+ def initialize(subject)
13
+ @subject = subject
14
+ @read_io, @write_io = IO.pipe
15
+ end
16
+
17
+ def call
18
+ trap
19
+ yield
20
+ wait
21
+ end
22
+
23
+ private
24
+
25
+ attr_reader :read_io, :write_io, :subject
26
+
27
+ def trap
28
+ SIGNAL_HANDLERS.each_key do |sig|
29
+ Signal.trap(sig) { write_io.puts(sig) }
30
+ end
31
+ end
32
+
33
+ def wait
34
+ while read_io.wait_readable
35
+ signal = read_io.gets.strip
36
+ logger.info "Handling signal #{signal}"
37
+ SIGNAL_HANDLERS.fetch(signal).call(subject)
38
+ end
39
+ rescue Interrupt => _e
40
+ subject.stop
41
+ end
42
+ end
43
+ end
@@ -0,0 +1,47 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Airflow
4
+ class State
5
+ BG_RUNNER_TRANSITIONS = {
6
+ init: :init,
7
+ stop: :stopped,
8
+ running: :running
9
+ }.freeze
10
+
11
+ def self.bg_state
12
+ new(BG_RUNNER_TRANSITIONS)
13
+ end
14
+
15
+ attr_reader :state
16
+
17
+ def initialize(transitions)
18
+ @transitions = transitions
19
+ define_methods
20
+ end
21
+
22
+ def state?(state)
23
+ public_send("#{state}?")
24
+ end
25
+
26
+ def transition!(new_state)
27
+ public_send("#{new_state}!")
28
+ end
29
+
30
+ private
31
+
32
+ attr_reader :transitions
33
+ attr_writer :state
34
+
35
+ def define_methods
36
+ transitions.each do |action, state|
37
+ self.class.send(:define_method, "#{action}!") do
38
+ self.state = state
39
+ end
40
+
41
+ self.class.send(:define_method, "#{state}?") do
42
+ self.state == state
43
+ end
44
+ end
45
+ end
46
+ end
47
+ end
@@ -0,0 +1,27 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "async_flow/definition"
4
+
5
+ module Airflow
6
+ module Task
7
+ include Definition
8
+ class Base
9
+ def self.task_name(name)
10
+ @_type = name
11
+ end
12
+
13
+ def self._type
14
+ @_type || name
15
+ end
16
+
17
+ def self.inherited(subclass)
18
+ Airflow::Task.definitions << subclass
19
+ super
20
+ end
21
+
22
+ def execute
23
+ raise NotImplementedError, "Abstract method"
24
+ end
25
+ end
26
+ end
27
+ end
@@ -0,0 +1,11 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Airflow
4
+ module Utils
5
+ module Logger
6
+ def logger
7
+ Airflow.logger
8
+ end
9
+ end
10
+ end
11
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Airflow
4
+ VERSION = "0.1.1"
5
+ end
@@ -0,0 +1,67 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "async_flow/utils"
4
+ require "async_flow/sig_handler"
5
+ require "async_flow/runner"
6
+ require "async_flow/executors"
7
+ require "async_flow/task"
8
+ require "async_flow/workflow"
9
+
10
+ module Airflow
11
+ class Worker
12
+ include Utils::Logger
13
+
14
+ # TODO: Add path to load workflows and task definitions.
15
+ # TODO: Assert definitions to be present
16
+ def initialize(workflows: Airflow::Workflow.definitions, tasks: Airflow::Task.definitions)
17
+ @workflows = workflows
18
+ @tasks = tasks
19
+ @reactor = Reactor.instance
20
+ @sig_handler = SigHandler.new(self)
21
+ @mutex = Mutex.new
22
+ @state = State.bg_state
23
+ @workflow_runner = Runner::WorkflowRunner.new(workflows)
24
+ @task_runner = Runner::TaskRunner.new(tasks)
25
+
26
+ Process.setproctitle("ruby-flow-worker")
27
+ end
28
+
29
+ def start(wait_interrupt: true)
30
+ running!
31
+ reactor.start
32
+ reactor.schedule do |parent|
33
+ parent.schedule { |subtask| workflow_runner.run(subtask) }
34
+ parent.schedule { |subtask| task_runner.run(subtask) }
35
+ end
36
+
37
+ sig_handler.call { logger.info "Flow Worker started. Use Ctrl-C to stop" } if wait_interrupt
38
+ end
39
+
40
+ def stop
41
+ logger.info "stopping worker"
42
+ mutex.synchronize { state.stop! }
43
+ task_runner.stop
44
+ workflow_runner.stop
45
+ # reactor.stop
46
+ # raise(Error.new("Stopping"))
47
+ # TODO
48
+ # launcher.stop
49
+ # task_execution&.drain
50
+ # workflow_execution&.drain
51
+
52
+ logger.info "worker stopped"
53
+ end
54
+
55
+ private
56
+
57
+ attr_reader :workflows, :tasks, :reactor, :executor, :sig_handler, :mutex, :state, :workflow_runner, :task_runner
58
+
59
+ def running!
60
+ mutex.synchronize do
61
+ raise Error, "worker already started" if state.running?
62
+
63
+ state.running!
64
+ end
65
+ end
66
+ end
67
+ end
@@ -0,0 +1,60 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "async_flow/definition"
4
+ require "async_flow/future"
5
+
6
+ module Airflow
7
+ module Workflow
8
+ include Definition
9
+
10
+ class Base
11
+ def self.workflow_name(name)
12
+ @_type = name
13
+ end
14
+
15
+ def self._type
16
+ @_type || name
17
+ end
18
+
19
+ def self.inherited(subclass)
20
+ Airflow::Workflow.definitions << subclass
21
+ super
22
+ end
23
+
24
+ def execute
25
+ raise NotImplementedError, "abstract method"
26
+ end
27
+
28
+ def initialize(task)
29
+ @task = task
30
+ end
31
+
32
+ def execute_task(task_name)
33
+ Future.new do
34
+ run = Persistence.workflow_runs.find_run_by_task_id(@task.id)
35
+ task = run.start_task(task_name: task_name, is_workflow_task: false)
36
+ Persistence.workflow_runs.save!(run)
37
+ until task.completed?
38
+ sleep(1) # TODO: Notify instead of polling from DB
39
+ task = Persistence.workflow_runs.find_task(task.id)
40
+ end
41
+ task.result
42
+ end
43
+ end
44
+
45
+ def workflow
46
+ self
47
+ end
48
+ end
49
+
50
+ Info = Struct.new(:workflow_name, :workflow_id, :queue, :status, keyword_init: true) do
51
+ def self.from(workflow)
52
+ new(
53
+ workflow_name: workflow.workflow_name,
54
+ workflow_id: workflow.id,
55
+ status: workflow.status
56
+ )
57
+ end
58
+ end
59
+ end
60
+ end
data/lib/async_flow.rb ADDED
@@ -0,0 +1,33 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "async_flow/version"
4
+ require "async_flow/workflow"
5
+ require "async_flow/task"
6
+ require "async_flow/client"
7
+ require "async_flow/reactor"
8
+ require "async_flow/worker"
9
+ require "async_flow/logger"
10
+ require "mediator"
11
+ require "async_flow/commands"
12
+ require "async_flow/handlers"
13
+
14
+ module Airflow
15
+ class Error < StandardError; end
16
+
17
+ def self.logger
18
+ @logger ||= Logger.new($stdout, level: :debug, progname: "async-flow").tap do |log|
19
+ log.formatter = Airflow::Logger::Formatters::Base.new
20
+ end
21
+ end
22
+
23
+ def self.logger=(logger)
24
+ @logger = logger
25
+ end
26
+
27
+ def self.mediator
28
+ @mediator ||= Mediator.init
29
+ end
30
+
31
+ mediator.handle(Commands::StartWorkflow, Handlers::StartWorkflowHandler.new)
32
+ mediator.handle(Commands::CompleteTaskCommand, Handlers::CompleteTaskCommandHandler.new)
33
+ end
data/sig/airflow.rbs ADDED
@@ -0,0 +1,4 @@
1
+ module Airflow
2
+ VERSION: String
3
+ # See the writing guide of rbs: https://github.com/ruby/rbs#guides
4
+ end
metadata ADDED
@@ -0,0 +1,104 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: async_flow
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.1
5
+ platform: ruby
6
+ authors:
7
+ - Laertis Pappas
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2023-03-09 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: async
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '0'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: '0'
27
+ - !ruby/object:Gem::Dependency
28
+ name: mediator-rb
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - ">="
32
+ - !ruby/object:Gem::Version
33
+ version: '0'
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - ">="
39
+ - !ruby/object:Gem::Version
40
+ version: '0'
41
+ description: Durable async workflow orchestration engine for Ruby
42
+ email:
43
+ - laertis.pappas@gmail.com
44
+ executables: []
45
+ extensions: []
46
+ extra_rdoc_files: []
47
+ files:
48
+ - ".rspec"
49
+ - ".rubocop.yml"
50
+ - CODE_OF_CONDUCT.md
51
+ - Gemfile
52
+ - LICENSE.txt
53
+ - Makefile
54
+ - README.md
55
+ - Rakefile
56
+ - async_flow.gemspec
57
+ - lib/async_flow.rb
58
+ - lib/async_flow/client.rb
59
+ - lib/async_flow/commands.rb
60
+ - lib/async_flow/definition.rb
61
+ - lib/async_flow/executors.rb
62
+ - lib/async_flow/future.rb
63
+ - lib/async_flow/handlers.rb
64
+ - lib/async_flow/logger.rb
65
+ - lib/async_flow/models.rb
66
+ - lib/async_flow/persistence.rb
67
+ - lib/async_flow/reactor.rb
68
+ - lib/async_flow/runner.rb
69
+ - lib/async_flow/sig_handler.rb
70
+ - lib/async_flow/state.rb
71
+ - lib/async_flow/task.rb
72
+ - lib/async_flow/utils.rb
73
+ - lib/async_flow/version.rb
74
+ - lib/async_flow/worker.rb
75
+ - lib/async_flow/workflow.rb
76
+ - sig/airflow.rbs
77
+ homepage: https://github.com/laertispappas/airflow
78
+ licenses:
79
+ - MIT
80
+ metadata:
81
+ homepage_uri: https://github.com/laertispappas/airflow
82
+ source_code_uri: https://github.com/laertispappas/airflow
83
+ changelog_uri: https://github.com/laertispappas/airflow
84
+ rubygems_mfa_required: 'true'
85
+ post_install_message:
86
+ rdoc_options: []
87
+ require_paths:
88
+ - lib
89
+ required_ruby_version: !ruby/object:Gem::Requirement
90
+ requirements:
91
+ - - ">="
92
+ - !ruby/object:Gem::Version
93
+ version: '3.0'
94
+ required_rubygems_version: !ruby/object:Gem::Requirement
95
+ requirements:
96
+ - - ">="
97
+ - !ruby/object:Gem::Version
98
+ version: '0'
99
+ requirements: []
100
+ rubygems_version: 3.3.7
101
+ signing_key:
102
+ specification_version: 4
103
+ summary: Durable async workflow orchestration engine for Ruby
104
+ test_files: []