repo
stringlengths
5
92
file_url
stringlengths
80
287
file_path
stringlengths
5
197
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:37:27
2026-01-04 17:58:21
truncated
bool
2 classes
wireframe/backgrounded
https://github.com/wireframe/backgrounded/blob/a0bb67902aecd76e51d613910cf9df54286fd506/spec/spec_helper.rb
spec/spec_helper.rb
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__) require 'active_record' require 'yaml' require_relative 'support/setup_database' require 'backgrounded' # This file was generated by the `rspec --init` command. Conventionally, all # specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`. # The generated `.rspec` file contains `--require spec_helper` which will cause # this file to always be loaded, without a need to explicitly require it in any # files. # # Given that it is always loaded, you are encouraged to keep this file as # light-weight as possible. Requiring heavyweight dependencies from this file # will add to the boot time of your test suite on EVERY test run, even for an # individual file that may not need all of that loaded. Instead, consider making # a separate helper file that requires the additional dependencies and performs # the additional setup, and require it from the spec files that actually need # it. # # The `.rspec` file also contains a few flags that are not defaults but that # users commonly want. # # See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration RSpec.configure do |config| # rspec-expectations config goes here. You can use an alternate # assertion/expectation library such as wrong or the stdlib/minitest # assertions if you prefer. config.expect_with :rspec do |expectations| # This option will default to `true` in RSpec 4. It makes the `description` # and `failure_message` of custom matchers include text for helper methods # defined using `chain`, e.g.: # be_bigger_than(2).and_smaller_than(4).description # # => "be bigger than 2 and smaller than 4" # ...rather than: # # => "be bigger than 2" expectations.include_chain_clauses_in_custom_matcher_descriptions = true end # rspec-mocks config goes here. You can use an alternate test double # library (such as bogus or mocha) by changing the `mock_with` option here. config.mock_with :rspec do |mocks| # Prevents you from mocking or stubbing a method that does not exist on # a real object. This is generally recommended, and will default to # `true` in RSpec 4. mocks.verify_partial_doubles = true end # The settings below are suggested to provide a good initial experience # with RSpec, but feel free to customize to your heart's content. =begin # These two settings work together to allow you to limit a spec run # to individual examples or groups you care about by tagging them with # `:focus` metadata. When nothing is tagged with `:focus`, all examples # get run. config.filter_run :focus config.run_all_when_everything_filtered = true # Allows RSpec to persist some state between runs in order to support # the `--only-failures` and `--next-failure` CLI options. We recommend # you configure your source control system to ignore this file. config.example_status_persistence_file_path = "spec/examples.txt" # Limits the available syntax to the non-monkey patched syntax that is # recommended. For more details, see: # - http://rspec.info/blog/2012/06/rspecs-new-expectation-syntax/ # - http://www.teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/ # - http://rspec.info/blog/2014/05/notable-changes-in-rspec-3/#zero-monkey-patching-mode config.disable_monkey_patching! # This setting enables warnings. It's recommended, but in some cases may # be too noisy due to issues in dependencies. config.warnings = true # Many RSpec users commonly either run the entire suite or an individual # file, and it's useful to allow more verbose output when running an # individual spec file. if config.files_to_run.one? # Use the documentation formatter for detailed output, # unless a formatter has already been configured # (e.g. via a command-line flag). config.default_formatter = 'doc' end # Print the 10 slowest examples and example groups at the # end of the spec run, to help surface which specs are running # particularly slow. config.profile_examples = 10 # Run specs in random order to surface order dependencies. If you find an # order dependency and want to debug it, you can fix the order by providing # the seed, which is printed after each run. # --seed 1234 config.order = :random # Seed global randomization in this process using the `--seed` CLI option. # Setting this allows you to use `--seed` to deterministically reproduce # test failures related to randomization by passing the same `--seed` value # as the one that triggered the failure. Kernel.srand config.seed =end end
ruby
MIT
a0bb67902aecd76e51d613910cf9df54286fd506
2026-01-04T17:50:17.165552Z
false
wireframe/backgrounded
https://github.com/wireframe/backgrounded/blob/a0bb67902aecd76e51d613910cf9df54286fd506/spec/support/setup_database.rb
spec/support/setup_database.rb
config = YAML::load(IO.read(File.join(File.dirname(__FILE__), 'database.yml'))) ActiveRecord::Base.logger = Logger.new(File.join(File.dirname(__FILE__), "debug.log")) ActiveRecord::Base.establish_connection(config[ENV['DB'] || 'sqlite']) ActiveRecord::Schema.define(:version => 1) do create_table :blogs, :force => true do |t| t.column :title, :string t.column :body, :string end create_table :users, :force => true do |t| t.column :name, :string end end
ruby
MIT
a0bb67902aecd76e51d613910cf9df54286fd506
2026-01-04T17:50:17.165552Z
false
wireframe/backgrounded
https://github.com/wireframe/backgrounded/blob/a0bb67902aecd76e51d613910cf9df54286fd506/spec/backgrounded/object_extensions_spec.rb
spec/backgrounded/object_extensions_spec.rb
RSpec.describe Backgrounded::ObjectExtensions do class Dog def do_stuff end def self.do_something_else end end describe '.backgrounded' do it 'is defined' do expect(Dog).to respond_to(:backgrounded) end it 'returns instance of Backgrounded::Proxy' do @result = Dog.backgrounded expect(@result).to be_kind_of(Backgrounded::Proxy) end end describe '#backgrounded' do it 'is defined' do dog = Dog.new expect(dog).to respond_to(:backgrounded) end it 'return instance of Backgrounded::Proxy' do @dog = Dog.new @result = @dog.backgrounded expect(@result).to be_kind_of(Backgrounded::Proxy) end context 'invoking with options' do before do @dog = Dog.new expect(Backgrounded.handler).to receive(:request).with(@dog, :do_stuff, [], {:priority => :high}) @dog.backgrounded(:priority => :high).do_stuff end it 'pass options onto Backgrounded.handler' do end # see expectations end end end
ruby
MIT
a0bb67902aecd76e51d613910cf9df54286fd506
2026-01-04T17:50:17.165552Z
false
wireframe/backgrounded
https://github.com/wireframe/backgrounded/blob/a0bb67902aecd76e51d613910cf9df54286fd506/spec/backgrounded/proxy_spec.rb
spec/backgrounded/proxy_spec.rb
RSpec.describe Backgrounded::Proxy do class Person def self.do_something_else end def do_stuff(name, place, location) end def do_stuff_without_arguments end end context 'invoking delegate method' do context 'with arguments and options' do before do @delegate = Person.new expect(Backgrounded.handler).to receive(:request).with(@delegate, :do_stuff, ['foo', 1, 'bar'], {:option_one => 'alpha'}) @proxy = Backgrounded::Proxy.new @delegate, :option_one => 'alpha' @result = @proxy.do_stuff 'foo', 1, 'bar' end it 'invokes Backgrounded.handler with delegate, method and args' do end #see expectations it 'return nil' do expect(@result).to be_nil end end context 'with arguments' do before do @delegate = Person.new expect(Backgrounded.handler).to receive(:request).with(@delegate, :do_stuff, ['foo', 1, 'bar'], {}) @proxy = Backgrounded::Proxy.new @delegate @result = @proxy.do_stuff 'foo', 1, 'bar' end it 'invokes Backgrounded.handler with delegate, method and args' do end #see expectations it 'return nil' do expect(@result).to be_nil end end context 'with no arguments' do before do @delegate = Person.new expect(Backgrounded.handler).to receive(:request).with(@delegate, :do_stuff_without_arguments, [], {}) @proxy = Backgrounded::Proxy.new @delegate @result = @proxy.do_stuff_without_arguments end it 'invokes Backgrounded.handler with delegate, method and args' do end #see expectations it 'return nil' do expect(@result).to be_nil end end end end
ruby
MIT
a0bb67902aecd76e51d613910cf9df54286fd506
2026-01-04T17:50:17.165552Z
false
wireframe/backgrounded
https://github.com/wireframe/backgrounded/blob/a0bb67902aecd76e51d613910cf9df54286fd506/spec/backgrounded/active_record_extension_spec.rb
spec/backgrounded/active_record_extension_spec.rb
RSpec.describe Backgrounded::ActiveRecordExtension do class Blog < ActiveRecord::Base include Backgrounded::ActiveRecordExtension after_commit_backgrounded :do_something_else def do_something_else end end class User < ActiveRecord::Base include Backgrounded::ActiveRecordExtension after_commit_backgrounded :do_stuff, :backgrounded => {:priority => :high} def do_stuff end end describe '.after_commit_backgrounded' do context 'without options' do before do @blog = Blog.new expect(Backgrounded.handler).to receive(:request).with(@blog, :do_something_else, [], {}) @blog.save! end it 'invoke Backgrounded.handler with no options' do end # see expectations end context 'with options[:backgrounded]' do before do @user = User.new expect(Backgrounded.handler).to receive(:request).with(@user, :do_stuff, [], {:priority => :high}) @user.save! end it 'pass options[:backgrounded] to Backgrounded.handler' do end # see expectations end end end
ruby
MIT
a0bb67902aecd76e51d613910cf9df54286fd506
2026-01-04T17:50:17.165552Z
false
wireframe/backgrounded
https://github.com/wireframe/backgrounded/blob/a0bb67902aecd76e51d613910cf9df54286fd506/lib/backgrounded.rb
lib/backgrounded.rb
require 'logger' require_relative 'backgrounded/handler/inprocess_handler' require_relative 'backgrounded/object_extensions' require_relative 'backgrounded/active_record_extension' require_relative 'backgrounded/railtie' if defined?(Rails) module Backgrounded class << self attr_accessor :logger, :handler def configure yield configuration end def configuration self end end end # default library configuration Backgrounded.configure do |config| # default handler to the basic in process handler config.handler = Backgrounded::Handler::InprocessHandler.new # configure default logger to standard out with info log level logger = Logger.new(STDOUT) logger.level = Logger::INFO config.logger = logger end
ruby
MIT
a0bb67902aecd76e51d613910cf9df54286fd506
2026-01-04T17:50:17.165552Z
false
wireframe/backgrounded
https://github.com/wireframe/backgrounded/blob/a0bb67902aecd76e51d613910cf9df54286fd506/lib/backgrounded/version.rb
lib/backgrounded/version.rb
module Backgrounded VERSION = '2.1.2' end
ruby
MIT
a0bb67902aecd76e51d613910cf9df54286fd506
2026-01-04T17:50:17.165552Z
false
wireframe/backgrounded
https://github.com/wireframe/backgrounded/blob/a0bb67902aecd76e51d613910cf9df54286fd506/lib/backgrounded/proxy.rb
lib/backgrounded/proxy.rb
module Backgrounded class Proxy attr_reader :delegate, :options def initialize(delegate, options={}) @delegate = delegate @options = options || {} end def method_missing(method_name, *args) Backgrounded.logger.debug("Requesting #{Backgrounded.handler} backgrounded method: #{method_name} for instance #{delegate} with options: #{options}") Backgrounded.handler.request(delegate, method_name, args, options) nil end end end
ruby
MIT
a0bb67902aecd76e51d613910cf9df54286fd506
2026-01-04T17:50:17.165552Z
false
wireframe/backgrounded
https://github.com/wireframe/backgrounded/blob/a0bb67902aecd76e51d613910cf9df54286fd506/lib/backgrounded/active_record_extension.rb
lib/backgrounded/active_record_extension.rb
require 'active_support/concern' module Backgrounded module ActiveRecordExtension extend ActiveSupport::Concern class_methods do # execute a method in the background after the object is committed to the database # @option options [Hash] :backgrounded (optional) options to pass into the backgrounded handler # @see after_commit def after_commit_backgrounded(method_name, options={}) after_commit options.except(:backgrounded) do |instance| instance.backgrounded(options[:backgrounded]).send(method_name) end end end end end
ruby
MIT
a0bb67902aecd76e51d613910cf9df54286fd506
2026-01-04T17:50:17.165552Z
false
wireframe/backgrounded
https://github.com/wireframe/backgrounded/blob/a0bb67902aecd76e51d613910cf9df54286fd506/lib/backgrounded/railtie.rb
lib/backgrounded/railtie.rb
require_relative 'active_record_extension' module Backgrounded class Railtie < Rails::Railtie initializer 'backgrounded.configure' do ActiveSupport.on_load(:active_record) do include Backgrounded::ActiveRecordExtension end end end end
ruby
MIT
a0bb67902aecd76e51d613910cf9df54286fd506
2026-01-04T17:50:17.165552Z
false
wireframe/backgrounded
https://github.com/wireframe/backgrounded/blob/a0bb67902aecd76e51d613910cf9df54286fd506/lib/backgrounded/object_extensions.rb
lib/backgrounded/object_extensions.rb
require 'active_support/concern' require_relative 'proxy' module Backgrounded # mixin to add backgrounded proxy builder to all ruby objects module ObjectExtensions extend ActiveSupport::Concern # @param options (optional) options to pass into the backgrounded handler def backgrounded(options={}) Backgrounded::Proxy.new self, options end class_methods do # @see Backgrounded::Concern#backgrounded def backgrounded(options={}) Backgrounded::Proxy.new self, options end end end end Object.send(:include, Backgrounded::ObjectExtensions)
ruby
MIT
a0bb67902aecd76e51d613910cf9df54286fd506
2026-01-04T17:50:17.165552Z
false
wireframe/backgrounded
https://github.com/wireframe/backgrounded/blob/a0bb67902aecd76e51d613910cf9df54286fd506/lib/backgrounded/handler/inprocess_handler.rb
lib/backgrounded/handler/inprocess_handler.rb
module Backgrounded module Handler #simple handler to process synchronously and not actually in the background #useful for testing class InprocessHandler def request(object, method, args, options={}) object.send method, *args end end end end
ruby
MIT
a0bb67902aecd76e51d613910cf9df54286fd506
2026-01-04T17:50:17.165552Z
false
wireframe/backgrounded
https://github.com/wireframe/backgrounded/blob/a0bb67902aecd76e51d613910cf9df54286fd506/lib/backgrounded/handler/no_op_handler.rb
lib/backgrounded/handler/no_op_handler.rb
module Backgrounded module Handler # throw requests out the window # useful for test environment to avoid any background work class NoOpHandler def request(object, method, args, options={}) # do nothing end end end end
ruby
MIT
a0bb67902aecd76e51d613910cf9df54286fd506
2026-01-04T17:50:17.165552Z
false
mtgrosser/nodo
https://github.com/mtgrosser/nodo/blob/2b99a77bf12a8e3f343579d3b8e758c41f7b0c36/test/test_helper.rb
test/test_helper.rb
ENV['NODE_ENV'] = ENV['RAILS_ENV'] = 'test' require 'rubygems' require 'bundler/setup' Bundler.require(:default) require 'debug' require 'minitest/reporters' Minitest::Reporters.use! Minitest::Reporters::SpecReporter.new require 'minitest/autorun' require 'nodo' # Enable to print debug messages # Nodo.debug = true
ruby
MIT
2b99a77bf12a8e3f343579d3b8e758c41f7b0c36
2026-01-04T17:50:17.196434Z
false
mtgrosser/nodo
https://github.com/mtgrosser/nodo/blob/2b99a77bf12a8e3f343579d3b8e758c41f7b0c36/test/nodo_test.rb
test/nodo_test.rb
require_relative 'test_helper' class NodoTest < Minitest::Test def test_function nodo = Class.new(Nodo::Core) do function :say_hi, "(name) => `Hello ${name}!`" end assert_equal 'Hello Nodo!', nodo.new.say_hi('Nodo') end def test_require nodo = Class.new(Nodo::Core) do require :fs function :exists_file, "(file) => fs.existsSync(file)" end assert_equal true, nodo.instance.exists_file(__FILE__) assert_equal false, nodo.instance.exists_file('FOOBARFOO') end def test_require_npm nodo = Class.new(Nodo::Core) do require :uuid function :v4, "() => uuid.v4()" end assert uuid = nodo.new.v4 assert_equal 36, uuid.size end def test_const nodo = Class.new(Nodo::Core) do const :FOOBAR, 123 function :get_const, "() => FOOBAR" end assert_equal 123, nodo.new.get_const end def test_script nodo = Class.new(Nodo::Core) do script "var somevar = 99;" function :get_somevar, "() => somevar" end assert_equal 99, nodo.new.get_somevar end def test_deferred_script_definition_by_block nodo = Class.new(Nodo::Core) do singleton_class.attr_accessor :value script do "var somevar = #{value.to_json};" end function :get_somevar, "() => somevar" end nodo.value = 123 assert_equal 123, nodo.new.get_somevar end def test_cannot_define_both_code_and_block_for_script assert_raises ArgumentError do Class.new(Nodo::Core) do script 'var foo;' do 'var bar;' end end end end def test_async_await nodo = Class.new(Nodo::Core) do function :do_something, "async () => { return await 'resolved'; }" end assert_equal 'resolved', nodo.new.do_something end def test_inheritance klass = Class.new(Nodo::Core) do function :foo, "() => 'superclass'" end subclass = Class.new(klass) do function :bar, "() => { return 'calling' + foo() }" end subsubclass = Class.new(subclass) do function :foo, "() => 'subsubclass'" end assert_equal 'superclass', klass.new.foo assert_equal 'callingsuperclass', subclass.new.bar assert_equal 'callingsubsubclass', subsubclass.new.bar end def test_class_function nodo = Class.new(Nodo::Core) do function :hello, "() => 'world'" class_function :hello end assert_equal 'world', nodo.hello end def test_syntax nodo = Class.new(Nodo::Core) do function :test, timeout: nil, code: <<~'JS' () => [1, 2, 3] JS end assert_equal [1, 2, 3], nodo.new.test end def test_deferred_function_definition_by_block nodo = lambda do Class.new(Nodo::Core) do singleton_class.attr_accessor :value function :test, timeout: nil do <<~JS () => [1, #{value}, 3] JS end end end assert_equal [1, nil, 3], nodo.().new.test assert_equal [1, 222, 3], nodo.().tap { |klass| klass.value = 222 }.new.test end def test_cannot_define_both_code_and_block_for_function assert_raises ArgumentError do Class.new(Nodo::Core) do function :test, code: '() => true' do '() => false' end end end end def test_code_is_required assert_raises ArgumentError do Class.new(Nodo::Core) do function :test, code: <<~'JS' JS end end end def test_timeout nodo = Class.new(Nodo::Core) do function :sleep, timeout: 1, code: <<~'JS' async (sec) => await new Promise(resolve => setTimeout(resolve, sec * 1000)) JS end assert_raises Nodo::TimeoutError do nodo.new.sleep(2) end end def test_internal_method_names_are_reserved assert_raises ArgumentError do Class.new(Nodo::Core) do function :tmpdir, code: "() => '.'" end end end def test_logging with_logger test_logger do assert_raises(Nodo::JavaScriptError) do Class.new(Nodo::Core) { function :bork, code: "() => {;;;" }.new end assert_equal 1, Nodo.logger.errors.size assert_match /Nodo::JavaScriptError/, Nodo.logger.errors.first end end def test_require_dependency_error with_logger nil do nodo = Class.new(Nodo::Core) do require 'foobarfoo' end assert_raises Nodo::DependencyError do nodo.new end end end def test_evaluation assert_equal 8, Class.new(Nodo::Core).new.evaluate('3 + 5') end def test_evaluation_can_access_constants nodo = Class.new(Nodo::Core) do const :FOO, 'bar' end assert_equal 'barfoo', nodo.new.evaluate('FOO + "foo"') end def test_evaluation_can_access_functions nodo = Class.new(Nodo::Core) do function :hello, code: "(name) => `Hello ${name}!`" end assert_equal 'Hello World!', nodo.new.evaluate('hello("World")') end def test_evaluation_contexts_properties_are_shared_between_instances nodo = Class.new(Nodo::Core) do const :LIST, [] function :list, code: "() => LIST" end one = nodo.new two = nodo.new one.evaluate("LIST.push('one')") two.evaluate("LIST.push('two')") assert_equal %w[one two], one.evaluate('list()') assert_equal %w[one two], two.evaluate('list()') end def test_evaluation_contexts_locals_are_separated_by_instance nodo = Class.new(Nodo::Core) one = nodo.new two = nodo.new one.evaluate("const list = []; list.push('one')") two.evaluate("const list = []; list.push('two')") assert_equal %w[one], one.evaluate('list') assert_equal %w[two], two.evaluate('list') end def test_evaluation_can_require_on_its_own nodo = Class.new(Nodo::Core).new nodo.evaluate('const uuid = require("uuid")') uuid = nodo.evaluate('uuid.v4()') assert_uuid uuid end def test_evaluation_can_access_requires nodo = Class.new(Nodo::Core) { require :uuid } uuid = nodo.new.evaluate('uuid.v4()') assert_uuid uuid end def test_cannot_instantiate_core assert_raises Nodo::ClassError do Nodo::Core.new end end def test_dynamic_imports_in_functions klass = Class.new(Nodo::Core) do function :v4, <<~JS async () => { const uuid = await nodo.import('uuid'); return await uuid.v4() } JS def self.name; "UUIDGen"; end end nodo = klass.new assert_uuid uuid_1 = nodo.v4 assert_uuid uuid_2 = nodo.v4 assert uuid_1 != uuid_2 end def test_dynamic_imports_in_evaluation nodo = Class.new(Nodo::Core) uuid = nodo.new.evaluate("nodo.import('uuid').then((uuid) => uuid.v4()).catch((e) => null)") assert_uuid uuid end def test_import nodo = Class.new(Nodo::Core) do import :fs function :exists_file, "(file) => fs.existsSync(file)" end assert_equal true, nodo.instance.exists_file(__FILE__) assert_equal false, nodo.instance.exists_file('FOOBARFOO') end def test_import_npm nodo = Class.new(Nodo::Core) do import :uuid function :v4, "() => uuid.v4()" end assert uuid = nodo.new.v4 assert_equal 36, uuid.size end def test_import_dependency_error with_logger nil do nodo = Class.new(Nodo::Core) do import 'foobarfoo' end assert_raises Nodo::DependencyError do nodo.new end end end def test_evaluation_can_access_imports nodo = Class.new(Nodo::Core) { import :uuid } uuid = nodo.new.evaluate('uuid.v4()') assert_uuid uuid end private def test_logger Object.new.instance_exec do def errors; @errors ||= []; end def error(msg); errors << msg; end self end end def with_logger(logger) prev_logger = Nodo.logger Nodo.logger = logger yield ensure Nodo.logger = prev_logger end def assert_uuid(obj) assert_match /\A\w{8}-\w{4}-\w{4}-\w{4}-\w{12}\z/, obj end end
ruby
MIT
2b99a77bf12a8e3f343579d3b8e758c41f7b0c36
2026-01-04T17:50:17.196434Z
false
mtgrosser/nodo
https://github.com/mtgrosser/nodo/blob/2b99a77bf12a8e3f343579d3b8e758c41f7b0c36/lib/nodo.rb
lib/nodo.rb
require 'pathname' require 'json' require 'fileutils' require 'tmpdir' require 'tempfile' require 'logger' require 'socket' require 'forwardable' module Nodo class << self attr_accessor :modules_root, :env, :binary, :args, :logger, :debug, :timeout end self.modules_root = './node_modules' self.env = {} self.binary = 'node' self.args = nil self.logger = Logger.new(STDOUT) self.debug = false self.timeout = 60 end require_relative 'nodo/version' require_relative 'nodo/errors' require_relative 'nodo/dependency' require_relative 'nodo/function' require_relative 'nodo/script' require_relative 'nodo/constant' require_relative 'nodo/client' require_relative 'nodo/core' require_relative 'nodo/railtie' if defined?(Rails::Railtie)
ruby
MIT
2b99a77bf12a8e3f343579d3b8e758c41f7b0c36
2026-01-04T17:50:17.196434Z
false
mtgrosser/nodo
https://github.com/mtgrosser/nodo/blob/2b99a77bf12a8e3f343579d3b8e758c41f7b0c36/lib/nodo/core.rb
lib/nodo/core.rb
module Nodo class Core SOCKET_NAME = 'nodo.sock' DEFINE_METHOD = '__nodo_define_class__'.freeze EVALUATE_METHOD = '__nodo_evaluate__'.freeze GC_METHOD = '__nodo_gc__'.freeze INTERNAL_METHODS = [DEFINE_METHOD, EVALUATE_METHOD, GC_METHOD].freeze LAUNCH_TIMEOUT = 5 ARRAY_CLASS_ATTRIBUTES = %i[dependencies constants scripts].freeze HASH_CLASS_ATTRIBUTES = %i[functions].freeze CLASS_ATTRIBUTES = (ARRAY_CLASS_ATTRIBUTES + HASH_CLASS_ATTRIBUTES).freeze @@node_pid = nil @@tmpdir = nil @@mutex = Mutex.new @@exiting = nil class << self extend Forwardable attr_accessor :class_defined def inherited(subclass) CLASS_ATTRIBUTES.each do |attr| subclass.send "#{attr}=", send(attr).dup end end def instance @instance ||= new end def class_defined? !!class_defined end def clsid name || "Class:0x#{object_id.to_s(0x10)}" end CLASS_ATTRIBUTES.each do |attr| define_method "#{attr}=" do |value| instance_variable_set :"@#{attr}", value end protected "#{attr}=" end ARRAY_CLASS_ATTRIBUTES.each do |attr| define_method "#{attr}" do instance_variable_get(:"@#{attr}") || instance_variable_set(:"@#{attr}", []) end end HASH_CLASS_ATTRIBUTES.each do |attr| define_method "#{attr}" do instance_variable_get(:"@#{attr}") || instance_variable_set(:"@#{attr}", {}) end end def generate_core_code <<~JS global.nodo = require(#{nodo_js}); const socket = process.argv[1]; if (!socket) { process.stderr.write('Socket path is required\\n'); process.exit(1); } process.title = `nodo-core ${socket}`; const shutdown = () => { nodo.core.close(() => { process.exit(0) }); }; // process.on('SIGINT', shutdown); process.on('SIGTERM', shutdown); nodo.core.run(socket); JS end def generate_class_code <<~JS (async () => { const __nodo_klass__ = { nodo: global.nodo }; #{dependencies.map(&:to_js).join} #{constants.map(&:to_js).join} #{functions.values.map(&:to_js).join} #{scripts.map(&:to_js).join} return __nodo_klass__; })() JS end protected def finalize_context(context_id) proc do if not @@exiting and core = @instance puts "finalize_context #{context_id}" core.send(:call_js_method, GC_METHOD, context_id) end end end private { require: :cjs, import: :esm }.each do |method, type| define_method method do |*mods| deps = mods.last.is_a?(Hash) ? mods.pop : {} mods = mods.map { |m| [m, m] }.to_h self.dependencies = dependencies + mods.merge(deps).map { |name, package| Dependency.new(name, package, type: type) } end private method end def function(name, _code = nil, timeout: Nodo.timeout, code: nil, &block) raise ArgumentError, "reserved method name #{name.inspect}" if reserved_method_name?(name) loc = caller_locations(1, 1)[0] source_location = "#{loc.path}:#{loc.lineno}: in `#{name}'" self.functions = functions.merge(name => Function.new(name, _code || code, source_location, timeout, &block)) define_method(name) { |*args| call_js_method(name, args) } end def class_function(*methods) singleton_class.def_delegators(:instance, *methods) end def const(name, value) self.constants = constants + [Constant.new(name, value)] end def script(code = nil, &block) self.scripts = scripts + [Script.new(code, &block)] end def nodo_js Pathname.new(__FILE__).dirname.join('nodo.cjs').to_s.to_json end def reserved_method_name?(name) Nodo::Core.method_defined?(name, false) || Nodo::Core.private_method_defined?(name, false) || name.to_s == DEFINE_METHOD end end def initialize raise ClassError, :new if self.class == Nodo::Core @@mutex.synchronize do ensure_process_is_spawned wait_for_socket ensure_class_is_defined end end def evaluate(code) ensure_context_is_defined call_js_method(EVALUATE_METHOD, code) end private def node_pid @@node_pid end def tmpdir @@tmpdir end def socket_path tmpdir && tmpdir.join(SOCKET_NAME) end def clsid self.class.clsid end def context_defined? @context_defined end def log_exception(e) return unless logger = Nodo.logger message = "\n#{e.class} (#{e.message})" message << ":\n\n#{e.backtrace.join("\n")}" if e.backtrace logger.error message end def ensure_process_is_spawned return if node_pid spawn_process end def ensure_class_is_defined return if self.class.class_defined? call_js_method(DEFINE_METHOD, self.class.generate_class_code) self.class.class_defined = true end def ensure_context_is_defined return if context_defined? @@mutex.synchronize do call_js_method(EVALUATE_METHOD, '') ObjectSpace.define_finalizer(self, self.class.send(:finalize_context, self.object_id)) @context_defined = true end end def spawn_process @@tmpdir = Pathname.new(Dir.mktmpdir('nodo')) env = Nodo.env.merge('NODE_PATH' => Nodo.modules_root.to_s) env['NODO_DEBUG'] = '1' if Nodo.debug @@node_pid = Process.spawn(env, Nodo.binary, '-e', self.class.generate_core_code, *Nodo.args, '--', socket_path.to_s, err: :out) at_exit do @@exiting = true Process.kill(:SIGTERM, node_pid) rescue Errno::ECHILD Process.wait(node_pid) rescue Errno::ECHILD FileUtils.remove_entry(tmpdir) if File.directory?(tmpdir) end end def wait_for_socket start = Time.now socket = nil while Time.now - start < LAUNCH_TIMEOUT begin break if socket = UNIXSocket.new(socket_path.to_s) rescue Errno::ENOENT, Errno::ECONNREFUSED, Errno::ENOTDIR Kernel.sleep(0.2) end end socket.close if socket raise TimeoutError, "could not connect to socket #{socket_path}" unless socket end def call_js_method(method, args) raise CallError, 'Node process not ready' unless node_pid raise CallError, "Class #{clsid} not defined" unless self.class.class_defined? || INTERNAL_METHODS.include?(method) function = self.class.functions[method] raise NameError, "undefined function `#{method}' for #{self.class}" unless function || INTERNAL_METHODS.include?(method) context_id = case method when DEFINE_METHOD then 0 when GC_METHOD then args else object_id end request = Net::HTTP::Post.new("/#{clsid}/#{context_id}/#{method}", 'Content-Type': 'application/json') request.body = JSON.dump(args) client = Client.new("unix://#{socket_path}") client.read_timeout = function&.timeout || Nodo.timeout response = client.request(request) if response.is_a?(Net::HTTPOK) parse_response(response) else handle_error(response, function) end rescue Net::ReadTimeout raise TimeoutError, "function call #{self.class}##{method} timed out" rescue Errno::EPIPE, IOError # TODO: restart or something? If this happens the process is completely broken raise Error, 'Node process failed' end def handle_error(response, function) if response.body result = parse_response(response) error = if result.is_a?(Hash) && result['error'].is_a?(Hash) attrs = result['error'] (attrs['nodo_dependency'] ? DependencyError : JavaScriptError).new(attrs, function) end end error ||= CallError.new("Node returned #{response.code}") log_exception(error) raise error end def parse_response(response) data = response.body.force_encoding('UTF-8') JSON.parse(data) unless data == '' end def with_tempfile(name) ext = File.extname(name) result = nil Tempfile.create([File.basename(name, ext), ext], tmpdir) do |file| result = yield(file) end result end end end
ruby
MIT
2b99a77bf12a8e3f343579d3b8e758c41f7b0c36
2026-01-04T17:50:17.196434Z
false
mtgrosser/nodo
https://github.com/mtgrosser/nodo/blob/2b99a77bf12a8e3f343579d3b8e758c41f7b0c36/lib/nodo/script.rb
lib/nodo/script.rb
module Nodo class Script attr_reader :code def initialize(code = nil, &block) raise ArgumentError, 'cannot give code when block is given' if code && block @code = code || block end def to_js js = code.respond_to?(:call) ? code.call : code "#{js}\n" end end end
ruby
MIT
2b99a77bf12a8e3f343579d3b8e758c41f7b0c36
2026-01-04T17:50:17.196434Z
false
mtgrosser/nodo
https://github.com/mtgrosser/nodo/blob/2b99a77bf12a8e3f343579d3b8e758c41f7b0c36/lib/nodo/version.rb
lib/nodo/version.rb
module Nodo VERSION = '1.8.2' end
ruby
MIT
2b99a77bf12a8e3f343579d3b8e758c41f7b0c36
2026-01-04T17:50:17.196434Z
false
mtgrosser/nodo
https://github.com/mtgrosser/nodo/blob/2b99a77bf12a8e3f343579d3b8e758c41f7b0c36/lib/nodo/errors.rb
lib/nodo/errors.rb
module Nodo class Error < StandardError; end class TimeoutError < Error; end class CallError < Error; end class ClassError < Error def initialize(method = nil) super("Cannot call method `#{method}' on Nodo::Core, use subclass instead") end end class JavaScriptError < Error attr_reader :attributes def initialize(attributes = {}, function = nil) @attributes = attributes || {} if backtrace = generate_backtrace(attributes['stack']) backtrace.unshift function.source_location if function && function.source_location set_backtrace backtrace end @message = generate_message end def to_s @message end private # "filename:lineNo: in `method''' or “filename:lineNo.'' def generate_backtrace(stack) backtrace = [] if stack and lines = stack.split("\n") lines.shift lines.each do |line| if match = line.match(/\A *at (?<call>.+) \((?<src>.*):(?<line>\d+):(?<column>\d+)\)/) backtrace << "#{match[:src]}:#{match[:line]}:in `#{match[:call]}'" end end end backtrace unless backtrace.empty? end def generate_message message = "#{attributes['message'] || attributes['name'] || 'Unknown error'}" message << format_location(attributes['loc']) end def format_location(loc) return '' unless loc loc.inject(+' in') { |s, (key, value)| s << " #{key}: #{value}" } end end class DependencyError < JavaScriptError private def generate_message message = "#{attributes['message'] || attributes['name'] || 'Dependency error'}\n" message << "The specified dependency '#{attributes['nodo_dependency']}' could not be loaded. " message << "Run 'yarn add #{attributes['nodo_dependency']}' to install it.\n" end end end
ruby
MIT
2b99a77bf12a8e3f343579d3b8e758c41f7b0c36
2026-01-04T17:50:17.196434Z
false
mtgrosser/nodo
https://github.com/mtgrosser/nodo/blob/2b99a77bf12a8e3f343579d3b8e758c41f7b0c36/lib/nodo/railtie.rb
lib/nodo/railtie.rb
require 'rails/railtie' require 'active_support' class Nodo::Railtie < Rails::Railtie initializer 'nodo' do |app| Nodo.env['NODE_ENV'] = Rails.env.to_s Nodo.logger = Rails.logger end end
ruby
MIT
2b99a77bf12a8e3f343579d3b8e758c41f7b0c36
2026-01-04T17:50:17.196434Z
false
mtgrosser/nodo
https://github.com/mtgrosser/nodo/blob/2b99a77bf12a8e3f343579d3b8e758c41f7b0c36/lib/nodo/constant.rb
lib/nodo/constant.rb
module Nodo class Constant attr_reader :name, :value def initialize(name, value) @name, @value = name, value end def to_js "const #{name} = __nodo_klass__.#{name} = #{value.to_json};\n" end end end
ruby
MIT
2b99a77bf12a8e3f343579d3b8e758c41f7b0c36
2026-01-04T17:50:17.196434Z
false
mtgrosser/nodo
https://github.com/mtgrosser/nodo/blob/2b99a77bf12a8e3f343579d3b8e758c41f7b0c36/lib/nodo/function.rb
lib/nodo/function.rb
module Nodo class Function attr_reader :name, :code, :source_location, :timeout def initialize(name, code, source_location, timeout, &block) raise ArgumentError, 'cannot give code when block is given' if code && block code = code.strip if code raise ArgumentError, 'function code is required' if '' == code raise ArgumentError, 'code is required' unless code || block @name, @code, @source_location, @timeout = name, code || block, source_location, timeout end def to_js js = code.respond_to?(:call) ? code.call.strip : code "const #{name} = __nodo_klass__.#{name} = (#{js});\n" end end end
ruby
MIT
2b99a77bf12a8e3f343579d3b8e758c41f7b0c36
2026-01-04T17:50:17.196434Z
false
mtgrosser/nodo
https://github.com/mtgrosser/nodo/blob/2b99a77bf12a8e3f343579d3b8e758c41f7b0c36/lib/nodo/client.rb
lib/nodo/client.rb
require 'net/http' module Nodo class Client < Net::HTTP UNIX_REGEXP = /\Aunix:\/\//i def initialize(address, port = nil) super(address, port) case address when UNIX_REGEXP @socket_type = 'unix' @socket_path = address.sub(UNIX_REGEXP, '') # Host header is required for HTTP/1.1 @address = 'localhost' @port = 80 else @socket_type = 'inet' end end def connect if @socket_type == 'unix' connect_unix else super end end def connect_unix s = Timeout.timeout(@open_timeout) { UNIXSocket.open(@socket_path) } @socket = Net::BufferedIO.new(s, read_timeout: @read_timeout, write_timeout: @write_timeout, continue_timeout: @continue_timeout, debug_output: @debug_output) on_connect end end end
ruby
MIT
2b99a77bf12a8e3f343579d3b8e758c41f7b0c36
2026-01-04T17:50:17.196434Z
false
mtgrosser/nodo
https://github.com/mtgrosser/nodo/blob/2b99a77bf12a8e3f343579d3b8e758c41f7b0c36/lib/nodo/dependency.rb
lib/nodo/dependency.rb
module Nodo class Dependency attr_reader :name, :package, :type def initialize(name, package, type:) @name, @package, @type = name, package, type end def to_js case type when :cjs then to_cjs when :esm then to_esm else raise "Unknown dependency type: #{type}" end end private def to_cjs <<~JS const #{name} = __nodo_klass__.#{name} = (() => { try { return require(#{package.to_json}); } catch(e) { e.nodo_dependency = #{package.to_json}; throw e; } })(); JS end def to_esm <<~JS const #{name} = __nodo_klass__.#{name} = await (async () => { try { return await nodo.import(#{package.to_json}); } catch(e) { e.nodo_dependency = #{package.to_json}; throw e; } })(); JS end end end
ruby
MIT
2b99a77bf12a8e3f343579d3b8e758c41f7b0c36
2026-01-04T17:50:17.196434Z
false
discourse/discourse-oauth2-basic
https://github.com/discourse/discourse-oauth2-basic/blob/f0261c88bc5a26aa142ec4b0af9ce3a21cfb3dc8/plugin.rb
plugin.rb
# frozen_string_literal: true # name: discourse-oauth2-basic # about: Allows users to login to your forum using a basic OAuth2 provider. # meta_topic_id: 33879 # version: 0.3 # authors: Robin Ward # url: https://github.com/discourse/discourse-oauth2-basic enabled_site_setting :oauth2_enabled require_relative "lib/omniauth/strategies/oauth2_basic" require_relative "lib/oauth2_faraday_formatter" require_relative "lib/oauth2_basic_authenticator" # You should use this register if you want to add custom paths to traverse the user details JSON. # We'll store the value in the user associated account's extra attribute hash using the full path as the key. DiscoursePluginRegistry.define_filtered_register :oauth2_basic_additional_json_paths # After authentication, we'll use this to confirm that the registered json paths are fulfilled, or display an error. # This requires SiteSetting.oauth2_fetch_user_details? to be true, and can be used with # DiscoursePluginRegistry.oauth2_basic_additional_json_paths. # # Example usage: # DiscoursePluginRegistry.register_oauth2_basic_required_json_path({ # path: "extra:data.is_allowed_user", # required_value: true, # error_message: I18n.t("auth.user_not_allowed") # }, self) DiscoursePluginRegistry.define_filtered_register :oauth2_basic_required_json_paths auth_provider title_setting: "oauth2_button_title", authenticator: OAuth2BasicAuthenticator.new require_relative "lib/validators/oauth2_basic/oauth2_fetch_user_details_validator"
ruby
MIT
f0261c88bc5a26aa142ec4b0af9ce3a21cfb3dc8
2026-01-04T17:50:22.408324Z
false
discourse/discourse-oauth2-basic
https://github.com/discourse/discourse-oauth2-basic/blob/f0261c88bc5a26aa142ec4b0af9ce3a21cfb3dc8/db/migrate/20190724055909_move_to_managed_authenticator.rb
db/migrate/20190724055909_move_to_managed_authenticator.rb
# frozen_string_literal: true class MoveToManagedAuthenticator < ActiveRecord::Migration[5.2] def up execute <<~SQL INSERT INTO user_associated_accounts ( provider_name, provider_uid, user_id, created_at, updated_at ) SELECT 'oauth2_basic', replace(key, 'oauth2_basic_user_', ''), (value::json->>'user_id')::integer, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP FROM plugin_store_rows WHERE plugin_name = 'oauth2_basic' AND value::json->>'user_id' ~ '^[0-9]+$' ON CONFLICT (provider_name, user_id) DO NOTHING SQL end def down raise ActiveRecord::IrreversibleMigration end end
ruby
MIT
f0261c88bc5a26aa142ec4b0af9ce3a21cfb3dc8
2026-01-04T17:50:22.408324Z
false
discourse/discourse-oauth2-basic
https://github.com/discourse/discourse-oauth2-basic/blob/f0261c88bc5a26aa142ec4b0af9ce3a21cfb3dc8/spec/plugin_spec.rb
spec/plugin_spec.rb
# frozen_string_literal: true require "rails_helper" describe OAuth2BasicAuthenticator do describe "after_authenticate" do before { SiteSetting.oauth2_user_json_url = "https://provider.com/user" } let(:user) { Fabricate(:user) } let(:authenticator) { OAuth2BasicAuthenticator.new } let(:auth) do OmniAuth::AuthHash.new( "provider" => "oauth2_basic", "credentials" => { token: "token", }, "uid" => "123456789", "info" => { id: "id", }, "extra" => { }, ) end before(:each) { SiteSetting.oauth2_email_verified = true } it "finds user by email" do authenticator.expects(:fetch_user_details).returns(email: user.email) result = authenticator.after_authenticate(auth) expect(result.user).to eq(user) end it "validates user email if provider has verified" do SiteSetting.oauth2_email_verified = false authenticator.stubs(:fetch_user_details).returns(email: user.email, email_verified: true) result = authenticator.after_authenticate(auth) expect(result.email_valid).to eq(true) end it "doesn't validate user email if provider hasn't verified" do SiteSetting.oauth2_email_verified = false authenticator.stubs(:fetch_user_details).returns(email: user.email, email_verified: nil) result = authenticator.after_authenticate(auth) expect(result.email_valid).to eq(false) end it "doesn't affect the site setting" do SiteSetting.oauth2_email_verified = true authenticator.stubs(:fetch_user_details).returns(email: user.email, email_verified: false) result = authenticator.after_authenticate(auth) expect(result.email_valid).to eq(true) end it "handles true/false strings from identity provider" do SiteSetting.oauth2_email_verified = false authenticator.stubs(:fetch_user_details).returns(email: user.email, email_verified: "true") result = authenticator.after_authenticate(auth) expect(result.email_valid).to eq(true) authenticator.stubs(:fetch_user_details).returns(email: user.email, email_verified: "false") result = authenticator.after_authenticate(auth) expect(result.email_valid).to eq(false) end describe "fetch_user_details" do before(:each) do SiteSetting.oauth2_fetch_user_details = true SiteSetting.oauth2_user_json_url = "https://provider.com/user" SiteSetting.oauth2_user_json_url_method = "GET" SiteSetting.oauth2_json_email_path = "account.email" end let(:success_response) do { status: 200, body: '{"account":{"email":"newemail@example.com"}}' } end let(:fail_response) { { status: 403 } } it "works" do stub_request(:get, SiteSetting.oauth2_user_json_url).to_return(success_response) result = authenticator.after_authenticate(auth) expect(result.email).to eq("newemail@example.com") SiteSetting.oauth2_user_json_url_method = "POST" stub_request(:post, SiteSetting.oauth2_user_json_url).to_return(success_response) result = authenticator.after_authenticate(auth) expect(result.email).to eq("newemail@example.com") end it "returns an standardised result if the http request fails" do stub_request(:get, SiteSetting.oauth2_user_json_url).to_return(fail_response) result = authenticator.after_authenticate(auth) expect(result.failed).to eq(true) SiteSetting.oauth2_user_json_url_method = "POST" stub_request(:post, SiteSetting.oauth2_user_json_url).to_return(fail_response) result = authenticator.after_authenticate(auth) expect(result.failed).to eq(true) end describe "fetch custom attributes" do after { DiscoursePluginRegistry.reset_register!(:oauth2_basic_additional_json_paths) } let(:response) do { status: 200, body: '{"account":{"email":"newemail@example.com","custom_attr":"received"}}', } end it "stores custom attributes in the user associated account" do custom_path = "account.custom_attr" DiscoursePluginRegistry.register_oauth2_basic_additional_json_path( custom_path, Plugin::Instance.new, ) stub_request(:get, SiteSetting.oauth2_user_json_url).to_return(response) result = authenticator.after_authenticate(auth) associated_account = UserAssociatedAccount.last expect(associated_account.extra[custom_path]).to eq("received") end end describe "required attributes" do after { DiscoursePluginRegistry.reset_register!(:oauth2_basic_required_json_paths) } it "'authenticates' successfully if required json path is fulfilled" do DiscoursePluginRegistry.register_oauth2_basic_additional_json_path( "account.is_legit", Plugin::Instance.new, ) DiscoursePluginRegistry.register_oauth2_basic_required_json_path( { path: "extra:account.is_legit", required_value: true }, Plugin::Instance.new, ) response = { status: 200, body: '{"account":{"email":"newemail@example.com","is_legit":true}}', } stub_request(:get, SiteSetting.oauth2_user_json_url).to_return(response) result = authenticator.after_authenticate(auth) expect(result.failed).to eq(false) end it "fails 'authentication' if required json path is unfulfilled" do DiscoursePluginRegistry.register_oauth2_basic_additional_json_path( "account.is_legit", Plugin::Instance.new, ) DiscoursePluginRegistry.register_oauth2_basic_required_json_path( { path: "extra:account.is_legit", required_value: true, error_message: "You're not legit", }, Plugin::Instance.new, ) response = { status: 200, body: '{"account":{"email":"newemail@example.com","is_legit":false}}', } stub_request(:get, SiteSetting.oauth2_user_json_url).to_return(response) result = authenticator.after_authenticate(auth) expect(result.failed).to eq(true) expect(result.failed_reason).to eq("You're not legit") end end end describe "avatar downloading" do before do Jobs.run_later! SiteSetting.oauth2_fetch_user_details = true SiteSetting.oauth2_email_verified = true end let(:job_klass) { Jobs::DownloadAvatarFromUrl } before do png = Base64.decode64( "R0lGODlhAQABALMAAAAAAIAAAACAAICAAAAAgIAAgACAgMDAwICAgP8AAAD/AP//AAAA//8A/wD//wBiZCH5BAEAAA8ALAAAAAABAAEAAAQC8EUAOw==", ) stub_request(:get, "http://avatar.example.com/avatar.png").to_return( body: png, headers: { "Content-Type" => "image/png", }, ) end it "enqueues a download_avatar_from_url job for existing user" do authenticator.expects(:fetch_user_details).returns( email: user.email, avatar: "http://avatar.example.com/avatar.png", ) expect { authenticator.after_authenticate(auth) }.to change { job_klass.jobs.count }.by(1) job_args = job_klass.jobs.last["args"].first expect(job_args["url"]).to eq("http://avatar.example.com/avatar.png") expect(job_args["user_id"]).to eq(user.id) expect(job_args["override_gravatar"]).to eq(false) end it "enqueues a download_avatar_from_url job for new user" do authenticator.expects(:fetch_user_details).returns( email: "unknown@user.com", avatar: "http://avatar.example.com/avatar.png", ) auth_result = nil expect { auth_result = authenticator.after_authenticate(auth) }.not_to change { job_klass.jobs.count } expect { authenticator.after_create_account(user, auth_result) }.to change { job_klass.jobs.count }.by(1) job_args = job_klass.jobs.last["args"].first expect(job_args["url"]).to eq("http://avatar.example.com/avatar.png") expect(job_args["user_id"]).to eq(user.id) expect(job_args["override_gravatar"]).to eq(false) end end end it "can walk json" do authenticator = OAuth2BasicAuthenticator.new json_string = '{"user":{"id":1234,"email":{"address":"test@example.com"}}}' SiteSetting.oauth2_json_email_path = "user.email.address" result = authenticator.json_walk({}, JSON.parse(json_string), :email) expect(result).to eq "test@example.com" end it "allows keys containing dots, if wrapped in quotes" do authenticator = OAuth2BasicAuthenticator.new json_string = '{"www.example.com/uid": "myuid"}' SiteSetting.oauth2_json_user_id_path = '"www.example.com/uid"' result = authenticator.json_walk({}, JSON.parse(json_string), :user_id) expect(result).to eq "myuid" end it "allows keys containing dots, if escaped" do authenticator = OAuth2BasicAuthenticator.new json_string = '{"www.example.com/uid": "myuid"}' SiteSetting.oauth2_json_user_id_path = 'www\.example\.com/uid' result = authenticator.json_walk({}, JSON.parse(json_string), :user_id) expect(result).to eq "myuid" end it "allows keys containing literal backslashes, if escaped" do authenticator = OAuth2BasicAuthenticator.new # This 'single quoted heredoc' syntax means we don't have to escape backslashes in Ruby # What you see is exactly what the user would enter in the site settings json_string = <<~'_'.chomp {"www.example.com/uid\\": "myuid"} _ SiteSetting.oauth2_json_user_id_path = <<~'_'.chomp www\.example\.com/uid\\ _ result = authenticator.json_walk({}, JSON.parse(json_string), :user_id) expect(result).to eq "myuid" end it "can walk json that contains an array" do authenticator = OAuth2BasicAuthenticator.new json_string = '{"email":"test@example.com","identities":[{"user_id":"123456789","provider":"auth0","isSocial":false}]}' SiteSetting.oauth2_json_user_id_path = "identities.[].user_id" result = authenticator.json_walk({}, JSON.parse(json_string), :user_id) expect(result).to eq "123456789" end it "can walk json and handle an empty array" do authenticator = OAuth2BasicAuthenticator.new json_string = '{"email":"test@example.com","identities":[]}' SiteSetting.oauth2_json_user_id_path = "identities.[].user_id" result = authenticator.json_walk({}, JSON.parse(json_string), :user_id) expect(result).to eq nil end it "can walk json and find values by index in an array" do authenticator = OAuth2BasicAuthenticator.new json_string = '{"emails":[{"value":"test@example.com"},{"value":"test2@example.com"}]}' SiteSetting.oauth2_json_email_path = "emails[1].value" result = authenticator.json_walk({}, JSON.parse(json_string), :email) expect(result).to eq "test2@example.com" end it "can walk json and download avatar" do authenticator = OAuth2BasicAuthenticator.new json_string = '{"user":{"avatar":"http://example.com/1.png"}}' SiteSetting.oauth2_json_avatar_path = "user.avatar" result = authenticator.json_walk({}, JSON.parse(json_string), :avatar) expect(result).to eq "http://example.com/1.png" end it "can walk json and appropriately assign a `false`" do authenticator = OAuth2BasicAuthenticator.new json_string = '{"user":{"id":1234, "data": {"address":"test@example.com", "is_cat": false}}}' SiteSetting.oauth2_json_email_verified_path = "user.data.is_cat" result = authenticator.json_walk( {}, JSON.parse(json_string), "extra:user.data.is_cat", custom_path: "user.data.is_cat", ) expect(result).to eq false end describe "token_callback" do let(:user) { Fabricate(:user) } let(:strategy) { OmniAuth::Strategies::Oauth2Basic.new({}) } let(:authenticator) { OAuth2BasicAuthenticator.new } let(:auth) do OmniAuth::AuthHash.new( "provider" => "oauth2_basic", "credentials" => { "token" => "token", }, "uid" => "e028b1b918853eca7fba208a9d7e9d29a6e93c57", "info" => { "name" => "Sammy the Shark", "email" => "sammy@digitalocean.com", }, "extra" => { }, ) end let(:access_token) do { "params" => { "info" => { "name" => "Sammy the Shark", "email" => "sammy@digitalocean.com", "uuid" => "e028b1b918853eca7fba208a9d7e9d29a6e93c57", }, }, } end before(:each) do SiteSetting.oauth2_callback_user_id_path = "params.info.uuid" SiteSetting.oauth2_callback_user_info_paths = "name:params.info.name|email:params.info.email" end it "can retrieve user id from access token callback" do strategy.stubs(:access_token).returns(access_token) expect(strategy.uid).to eq "e028b1b918853eca7fba208a9d7e9d29a6e93c57" end it "can retrieve user properties from access token callback" do strategy.stubs(:access_token).returns(access_token) expect(strategy.info["name"]).to eq "Sammy the Shark" expect(strategy.info["email"]).to eq "sammy@digitalocean.com" end it "does apply user properties from access token callback in after_authenticate" do SiteSetting.oauth2_fetch_user_details = true authenticator.stubs(:fetch_user_details).returns(email: "sammy@digitalocean.com") result = authenticator.after_authenticate(auth) expect(result.extra_data[:uid]).to eq "e028b1b918853eca7fba208a9d7e9d29a6e93c57" expect(result.name).to eq "Sammy the Shark" expect(result.email).to eq "sammy@digitalocean.com" end it "does work if user details are not fetched" do SiteSetting.oauth2_fetch_user_details = false result = authenticator.after_authenticate(auth) expect(result.extra_data[:uid]).to eq "e028b1b918853eca7fba208a9d7e9d29a6e93c57" expect(result.name).to eq "Sammy the Shark" expect(result.email).to eq "sammy@digitalocean.com" end end end
ruby
MIT
f0261c88bc5a26aa142ec4b0af9ce3a21cfb3dc8
2026-01-04T17:50:22.408324Z
false
discourse/discourse-oauth2-basic
https://github.com/discourse/discourse-oauth2-basic/blob/f0261c88bc5a26aa142ec4b0af9ce3a21cfb3dc8/spec/system/core_features_spec.rb
spec/system/core_features_spec.rb
# frozen_string_literal: true RSpec.describe "Core features", type: :system do before { enable_current_plugin } it_behaves_like "having working core features" end
ruby
MIT
f0261c88bc5a26aa142ec4b0af9ce3a21cfb3dc8
2026-01-04T17:50:22.408324Z
false
discourse/discourse-oauth2-basic
https://github.com/discourse/discourse-oauth2-basic/blob/f0261c88bc5a26aa142ec4b0af9ce3a21cfb3dc8/spec/integration/overrides_email_spec.rb
spec/integration/overrides_email_spec.rb
# frozen_string_literal: true require "rails_helper" describe "OAuth2 Overrides Email", type: :request do fab!(:initial_email) { "initial@example.com" } fab!(:new_email) { "new@example.com" } fab!(:user) { Fabricate(:user, email: initial_email) } fab!(:uac) do UserAssociatedAccount.create!(user: user, provider_name: "oauth2_basic", provider_uid: "12345") end before do SiteSetting.oauth2_enabled = true SiteSetting.oauth2_callback_user_id_path = "uid" SiteSetting.oauth2_fetch_user_details = false SiteSetting.oauth2_email_verified = true OmniAuth.config.test_mode = true OmniAuth.config.mock_auth[:oauth2_basic] = OmniAuth::AuthHash.new( provider: "oauth2_basic", uid: "12345", info: OmniAuth::AuthHash::InfoHash.new(email: new_email), extra: { raw_info: OmniAuth::AuthHash.new(email_verified: true), }, credentials: OmniAuth::AuthHash.new, ) end it "doesn't update email by default" do expect(user.reload.email).to eq(initial_email) get "/auth/oauth2_basic/callback" expect(response.status).to eq(302) expect(session[:current_user_id]).to eq(user.id) expect(user.reload.email).to eq(initial_email) end it "updates user email if enabled" do SiteSetting.oauth2_overrides_email = true get "/auth/oauth2_basic/callback" expect(response.status).to eq(302) expect(session[:current_user_id]).to eq(user.id) expect(user.reload.email).to eq(new_email) end end
ruby
MIT
f0261c88bc5a26aa142ec4b0af9ce3a21cfb3dc8
2026-01-04T17:50:22.408324Z
false
discourse/discourse-oauth2-basic
https://github.com/discourse/discourse-oauth2-basic/blob/f0261c88bc5a26aa142ec4b0af9ce3a21cfb3dc8/lib/oauth2_faraday_formatter.rb
lib/oauth2_faraday_formatter.rb
# frozen_string_literal: true require "faraday/logging/formatter" class OAuth2FaradayFormatter < Faraday::Logging::Formatter def request(env) warn <<~LOG OAuth2 Debugging: request #{env.method.upcase} #{env.url} Headers: #{env.request_headers.to_yaml} Body: #{env[:body].to_yaml} LOG end def response(env) warn <<~LOG OAuth2 Debugging: response status #{env.status} From #{env.method.upcase} #{env.url} Headers: #{env.request_headers.to_yaml} Body: #{env[:body].to_yaml} LOG end end
ruby
MIT
f0261c88bc5a26aa142ec4b0af9ce3a21cfb3dc8
2026-01-04T17:50:22.408324Z
false
discourse/discourse-oauth2-basic
https://github.com/discourse/discourse-oauth2-basic/blob/f0261c88bc5a26aa142ec4b0af9ce3a21cfb3dc8/lib/oauth2_basic_authenticator.rb
lib/oauth2_basic_authenticator.rb
# frozen_string_literal: true class OAuth2BasicAuthenticator < Auth::ManagedAuthenticator def name "oauth2_basic" end def can_revoke? SiteSetting.oauth2_allow_association_change end def can_connect_existing_user? SiteSetting.oauth2_allow_association_change end def register_middleware(omniauth) omniauth.provider :oauth2_basic, name: name, setup: lambda { |env| opts = env["omniauth.strategy"].options opts[:client_id] = SiteSetting.oauth2_client_id opts[:client_secret] = SiteSetting.oauth2_client_secret opts[:provider_ignores_state] = SiteSetting.oauth2_disable_csrf opts[:client_options] = { authorize_url: SiteSetting.oauth2_authorize_url, token_url: SiteSetting.oauth2_token_url, token_method: SiteSetting.oauth2_token_url_method.downcase.to_sym, } opts[:authorize_options] = SiteSetting .oauth2_authorize_options .split("|") .map(&:to_sym) if SiteSetting.oauth2_authorize_signup_url.present? && ActionDispatch::Request.new(env).params["signup"].present? opts[:client_options][ :authorize_url ] = SiteSetting.oauth2_authorize_signup_url end if SiteSetting.oauth2_send_auth_header? && SiteSetting.oauth2_send_auth_body? # For maximum compatibility we include both header and body auth by default # This is a little unusual, and utilising multiple authentication methods # is technically disallowed by the spec (RFC2749 Section 5.2) opts[:client_options][:auth_scheme] = :request_body opts[:token_params] = { headers: { "Authorization" => basic_auth_header, }, } elsif SiteSetting.oauth2_send_auth_header? opts[:client_options][:auth_scheme] = :basic_auth else opts[:client_options][:auth_scheme] = :request_body end if SiteSetting.oauth2_scope.present? opts[:scope] = SiteSetting.oauth2_scope end opts[:client_options][:connection_build] = lambda do |builder| if SiteSetting.oauth2_debug_auth && defined?(OAuth2FaradayFormatter) builder.response :logger, Rails.logger, { bodies: true, formatter: OAuth2FaradayFormatter } end builder.request :url_encoded # form-encode POST params builder.adapter FinalDestination::FaradayAdapter # make requests with FinalDestination::HTTP end } end def basic_auth_header "Basic " + Base64.strict_encode64("#{SiteSetting.oauth2_client_id}:#{SiteSetting.oauth2_client_secret}") end def walk_path(fragment, segments, seg_index = 0) first_seg = segments[seg_index] return if first_seg.blank? || fragment.blank? return nil unless fragment.is_a?(Hash) || fragment.is_a?(Array) first_seg = segments[seg_index].scan(/([\d+])/).length > 0 ? first_seg.split("[")[0] : first_seg if fragment.is_a?(Hash) deref = fragment[first_seg] else array_index = 0 if (seg_index > 0) last_index = segments[seg_index - 1].scan(/([\d+])/).flatten() || [0] array_index = last_index.length > 0 ? last_index[0].to_i : 0 end if fragment.any? && fragment.length >= array_index - 1 deref = fragment[array_index][first_seg] else deref = nil end end if deref.blank? || seg_index == segments.size - 1 deref else seg_index += 1 walk_path(deref, segments, seg_index) end end def json_walk(result, user_json, prop, custom_path: nil) path = custom_path || SiteSetting.public_send("oauth2_json_#{prop}_path") if path.present? #this.[].that is the same as this.that, allows for both this[0].that and this.[0].that path styles path = path.gsub(".[].", ".").gsub(".[", "[") segments = parse_segments(path) val = walk_path(user_json, segments) # [] should be nil, false should be false result[prop] = val.presence || (val == [] ? nil : val) end end def parse_segments(path) segments = [+""] quoted = false escaped = false path .split("") .each do |char| next_char_escaped = false if !escaped && (char == '"') quoted = !quoted elsif !escaped && !quoted && (char == ".") segments.append +"" elsif !escaped && (char == '\\') next_char_escaped = true else segments.last << char end escaped = next_char_escaped end segments end def log(info) Rails.logger.warn("OAuth2 Debugging: #{info}") if SiteSetting.oauth2_debug_auth end def fetch_user_details(token, id) user_json_url = SiteSetting.oauth2_user_json_url.sub(":token", token.to_s).sub(":id", id.to_s) user_json_method = SiteSetting.oauth2_user_json_url_method.downcase.to_sym bearer_token = "Bearer #{token}" connection = Faraday.new { |f| f.adapter FinalDestination::FaradayAdapter } headers = { "Authorization" => bearer_token, "Accept" => "application/json" } user_json_response = connection.run_request(user_json_method, user_json_url, nil, headers) log <<-LOG user_json request: #{user_json_method} #{user_json_url} request headers: #{headers} response status: #{user_json_response.status} response body: #{user_json_response.body} LOG if user_json_response.status == 200 user_json = JSON.parse(user_json_response.body) log("user_json:\n#{user_json.to_yaml}") result = {} if user_json.present? json_walk(result, user_json, :user_id) json_walk(result, user_json, :username) json_walk(result, user_json, :name) json_walk(result, user_json, :email) json_walk(result, user_json, :email_verified) json_walk(result, user_json, :avatar) DiscoursePluginRegistry.oauth2_basic_additional_json_paths.each do |detail| prop = "extra:#{detail}" json_walk(result, user_json, prop, custom_path: detail) end end result else nil end end def primary_email_verified?(auth) return true if SiteSetting.oauth2_email_verified verified = auth["info"]["email_verified"] verified = true if verified == "true" verified = false if verified == "false" verified end def always_update_user_email? SiteSetting.oauth2_overrides_email end def after_authenticate(auth, existing_account: nil) log <<-LOG after_authenticate response: creds: #{auth["credentials"].to_hash.to_yaml} uid: #{auth["uid"]} info: #{auth["info"].to_hash.to_yaml} extra: #{auth["extra"].to_hash.to_yaml} LOG if SiteSetting.oauth2_fetch_user_details? && SiteSetting.oauth2_user_json_url.present? if fetched_user_details = fetch_user_details(auth["credentials"]["token"], auth["uid"]) auth["uid"] = fetched_user_details[:user_id] if fetched_user_details[:user_id] auth["info"]["nickname"] = fetched_user_details[:username] if fetched_user_details[ :username ] auth["info"]["image"] = fetched_user_details[:avatar] if fetched_user_details[:avatar] %w[name email email_verified].each do |property| auth["info"][property] = fetched_user_details[property.to_sym] if fetched_user_details[ property.to_sym ] end DiscoursePluginRegistry.oauth2_basic_additional_json_paths.each do |detail| auth["extra"][detail] = fetched_user_details["extra:#{detail}"] end DiscoursePluginRegistry.oauth2_basic_required_json_paths.each do |x| if fetched_user_details[x[:path]] != x[:required_value] result = Auth::Result.new result.failed = true result.failed_reason = x[:error_message] return result end end else result = Auth::Result.new result.failed = true result.failed_reason = I18n.t("login.authenticator_error_fetch_user_details") return result end end super(auth, existing_account: existing_account) end def enabled? SiteSetting.oauth2_enabled end end
ruby
MIT
f0261c88bc5a26aa142ec4b0af9ce3a21cfb3dc8
2026-01-04T17:50:22.408324Z
false
discourse/discourse-oauth2-basic
https://github.com/discourse/discourse-oauth2-basic/blob/f0261c88bc5a26aa142ec4b0af9ce3a21cfb3dc8/lib/validators/oauth2_basic/oauth2_fetch_user_details_validator.rb
lib/validators/oauth2_basic/oauth2_fetch_user_details_validator.rb
# frozen_string_literal: true class Oauth2FetchUserDetailsValidator def initialize(opts = {}) @opts = opts end def valid_value?(val) return true if val == "t" SiteSetting.oauth2_callback_user_id_path.length > 0 end def error_message I18n.t("site_settings.errors.oauth2_fetch_user_details") end end
ruby
MIT
f0261c88bc5a26aa142ec4b0af9ce3a21cfb3dc8
2026-01-04T17:50:22.408324Z
false
discourse/discourse-oauth2-basic
https://github.com/discourse/discourse-oauth2-basic/blob/f0261c88bc5a26aa142ec4b0af9ce3a21cfb3dc8/lib/omniauth/strategies/oauth2_basic.rb
lib/omniauth/strategies/oauth2_basic.rb
# frozen_string_literal: true class OmniAuth::Strategies::Oauth2Basic < ::OmniAuth::Strategies::OAuth2 option :name, "oauth2_basic" uid do if path = SiteSetting.oauth2_callback_user_id_path.split(".") recurse(access_token, [*path]) if path.present? end end info do if paths = SiteSetting.oauth2_callback_user_info_paths.split("|") result = Hash.new paths.each do |p| segments = p.split(":") if segments.length == 2 key = segments.first path = [*segments.last.split(".")] result[key] = recurse(access_token, path) end end result end end def callback_url Discourse.base_url_no_prefix + script_name + callback_path end def recurse(obj, keys) return nil if !obj k = keys.shift result = obj.respond_to?(k) ? obj.send(k) : obj[k] keys.empty? ? result : recurse(result, keys) end end
ruby
MIT
f0261c88bc5a26aa142ec4b0af9ce3a21cfb3dc8
2026-01-04T17:50:22.408324Z
false
Dynflow/dynflow
https://github.com/Dynflow/dynflow/blob/e14dcdfe57cec99cc78b2f6ab521f00809b1408a/test/round_robin_test.rb
test/round_robin_test.rb
# -*- coding: utf-8 -*- # frozen_string_literal: true require_relative 'test_helper' module Dynflow module RoundRobinTest describe RoundRobin do let(:rr) { Dynflow::RoundRobin.new } specify do assert_nil rr.next assert_nil rr.next _(rr).must_be_empty rr.add 1 _(rr.next).must_equal 1 _(rr.next).must_equal 1 rr.add 2 _(rr.next).must_equal 2 _(rr.next).must_equal 1 _(rr.next).must_equal 2 rr.delete 1 _(rr.next).must_equal 2 _(rr.next).must_equal 2 rr.delete 2 assert_nil rr.next _(rr).must_be_empty end end end end
ruby
MIT
e14dcdfe57cec99cc78b2f6ab521f00809b1408a
2026-01-04T17:50:16.326730Z
false
Dynflow/dynflow
https://github.com/Dynflow/dynflow/blob/e14dcdfe57cec99cc78b2f6ab521f00809b1408a/test/daemon_test.rb
test/daemon_test.rb
# frozen_string_literal: true require 'test_helper' require 'active_support' require 'mocha/minitest' require 'logging' require 'dynflow/testing' require 'ostruct' require_relative '../lib/dynflow/rails' class StdIOWrapper def initialize(logger, error = false) @logger = logger @error = error end def puts(msg = nil) if @error @logger.error(msg) else @logger.info(msg) end end end class DaemonTest < ActiveSupport::TestCase setup do @dynflow_memory_watcher = mock('memory_watcher') @daemons = mock('daemons') @daemon = ::Dynflow::Rails::Daemon.new( @dynflow_memory_watcher, @daemons ) logger = WorldFactory.logger_adapter.logger @daemon.stubs(:stdout).returns(StdIOWrapper.new(logger, false)) @daemon.stubs(:stderr).returns(StdIOWrapper.new(logger, true)) @world_class = mock('dummy world factory') @dummy_world = ::Dynflow::Testing::DummyWorld.new @dummy_world.stubs(:id => '123') @dummy_world.stubs(:auto_execute) @dummy_world.stubs(:perform_validity_checks => 0) @event = Concurrent::Promises.resolvable_event @dummy_world.stubs(:terminated).returns(@event) @world_class.stubs(:new).returns(@dummy_world) @dynflow = ::Dynflow::Rails.new( @world_class, ::Dynflow::Rails::Configuration.new ) ::Rails.stubs(:application).returns(::OpenStruct.new(:dynflow => @dynflow)) ::Rails.stubs(:root).returns('support/rails') ::Rails.stubs(:logger).returns(logger) @dynflow.require! @dynflow.config.stubs(:increase_db_pool_size? => false) @daemon.stubs(:sleep).returns(true) # don't pause the execution @current_folder = File.expand_path('../support/rails/', __FILE__) ::ActiveRecord::Base.configurations = { 'development' => {} } ::Dynflow::Rails::Configuration.any_instance.stubs(:initialize_persistence) .returns(WorldFactory.persistence_adapter) end teardown do @event.resolve @event.wait end test 'run command works without memory_limit option specified' do @daemon.run(@current_folder) @dynflow.initialize! end test 'runs post_initialization when there are invalid worlds detected' do @dummy_world.stubs(:perform_validity_checks => 1) @dummy_world.expects(:post_initialization) @daemon.run(@current_folder) @dynflow.initialize! end test 'run command creates a watcher if memory_limit option specified' do @dynflow_memory_watcher.expects(:new).with do |_world, memory_limit, _watcher_options| memory_limit == 1000 end @daemon.run(@current_folder, memory_limit: 1000) # initialization should be performed inside the foreman environment, # which is mocked here @dynflow.initialize! end test 'run command sets parameters to watcher' do @dynflow_memory_watcher.expects(:new).with do |_world, memory_limit, watcher_options| memory_limit == 1000 && watcher_options[:polling_interval] == 100 && watcher_options[:initial_wait] == 200 end @daemon.run( @current_folder, memory_limit: 1000, memory_polling_interval: 100, memory_init_delay: 200 ) @dynflow.initialize! end test 'run_background command executes run with all params set as a daemon' do @daemon.expects(:run).twice.with do |_folder, options| options[:memory_limit] == 1000 && options[:memory_init_delay] == 100 && options[:memory_polling_interval] == 200 && options[:force_kill_waittime] == 40 end @daemons.expects(:run_proc).twice.yields @daemon.run_background( 'start', executors_count: 2, memory_limit: 1000, memory_init_delay: 100, memory_polling_interval: 200, force_kill_waittime: 40 ) end test 'default options read values from ENV' do ENV['EXECUTORS_COUNT'] = '2' ENV['EXECUTOR_MEMORY_LIMIT'] = '1gb' ENV['EXECUTOR_MEMORY_MONITOR_DELAY'] = '3' ENV['EXECUTOR_MEMORY_MONITOR_INTERVAL'] = '4' ENV['EXECUTOR_FORCE_KILL_WAITTIME'] = '40' actual = @daemon.send(:default_options) assert_equal 2, actual[:executors_count] assert_equal 1.gigabytes, actual[:memory_limit] assert_equal 3, actual[:memory_init_delay] assert_equal 4, actual[:memory_polling_interval] assert_equal 40, actual[:force_kill_waittime] end end
ruby
MIT
e14dcdfe57cec99cc78b2f6ab521f00809b1408a
2026-01-04T17:50:16.326730Z
false
Dynflow/dynflow
https://github.com/Dynflow/dynflow/blob/e14dcdfe57cec99cc78b2f6ab521f00809b1408a/test/v2_sub_plans_test.rb
test/v2_sub_plans_test.rb
# frozen_string_literal: true require_relative 'test_helper' require 'mocha/minitest' module Dynflow module V2SubPlansTest describe 'V2 sub-plans' do include PlanAssertions include Dynflow::Testing::Assertions include Dynflow::Testing::Factories include TestHelpers let(:world) { WorldFactory.create_world } class ChildAction < ::Dynflow::Action def run end end class ParentAction < ::Dynflow::Action include Dynflow::Action::V2::WithSubPlans def plan(count, concurrency_level = nil) limit_concurrency_level!(concurrency_level) if concurrency_level plan_self :count => count end def create_sub_plans output[:batch_count] ||= 0 output[:batch_count] += 1 current_batch.map { |i| trigger(ChildAction) } end def batch(from, size) (1..total_count).to_a.slice(from, size) end def batch_size 5 end def total_count input[:count] end end describe 'normal operation' do it 'spawns all sub-plans in one go with high-enough batch size and polls until they are done' do action = create_and_plan_action ParentAction, 3 action.world.expects(:trigger).times(3) action = run_action action _(action.output['total_count']).must_equal 3 _(action.output['planned_count']).must_equal 3 _(action.output['pending_count']).must_equal 3 ping = action.world.clock.pending_pings.first _(ping.what.value.event).must_equal Dynflow::Action::V2::WithSubPlans::Ping _(ping.when).must_be_within_delta(Time.now + action.polling_interval, 1) persistence = mock() persistence.stubs(:find_execution_plan_counts).returns(0) action.world.stubs(:persistence).returns(persistence) action.world.clock.progress action.world.executor.progress ping = action.world.clock.pending_pings.first _(ping.what.value.event).must_equal Dynflow::Action::V2::WithSubPlans::Ping _(ping.when).must_be_within_delta(Time.now + action.polling_interval * 2, 1) persistence = mock() persistence.stubs(:find_execution_plan_counts).returns(0).then.returns(3) action.world.stubs(:persistence).returns(persistence) action.world.clock.progress action.world.executor.progress _(action.state).must_equal :success _(action.done?).must_equal true end it 'spawns sub-plans in multiple batches and polls until they are done' do action = create_and_plan_action ParentAction, 7 action.world.expects(:trigger).times(5) action = run_action action _(action.output['total_count']).must_equal 7 _(action.output['planned_count']).must_equal 5 _(action.output['pending_count']).must_equal 5 _(action.world.clock.pending_pings).must_be :empty? _, _, event, * = action.world.executor.events_to_process.first _(event).must_equal Dynflow::Action::V2::WithSubPlans::Ping persistence = mock() # Simulate 3 finished persistence.stubs(:find_execution_plan_counts).returns(0).then.returns(3) action.world.stubs(:persistence).returns(persistence) action.world.expects(:trigger).times(2) action.world.executor.progress ping = action.world.clock.pending_pings.first _(ping.what.value.event).must_equal Dynflow::Action::V2::WithSubPlans::Ping _(ping.when).must_be_within_delta(Time.now + action.polling_interval, 1) persistence.stubs(:find_execution_plan_counts).returns(0).then.returns(7) action.world.stubs(:persistence).returns(persistence) action.world.clock.progress action.world.executor.progress _(action.state).must_equal :success _(action.done?).must_equal true end end describe 'with concurrency control' do include Dynflow::Testing it 'allows storage and retrieval' do action = create_and_plan_action ParentAction, 0 action = run_action action _(action.concurrency_limit).must_be_nil _(action.concurrency_limit_capacity).must_be_nil action = create_and_plan_action ParentAction, 0, 1 action = run_action action _(action.input['dynflow']['concurrency_limit']).must_equal 1 _(action.concurrency_limit).must_equal 1 _(action.concurrency_limit_capacity).must_equal 1 end it 'reduces the batch size to fit within the concurrency limit' do action = create_and_plan_action ParentAction, 5, 2 # Plan first 2 sub-plans action.world.expects(:trigger).times(2) action = run_action action _(action.output['total_count']).must_equal 5 _(action.output['planned_count']).must_equal 2 _(action.output['pending_count']).must_equal 2 _(action.concurrency_limit_capacity).must_equal 0 _(action.output['batch_count']).must_equal 1 ping = action.world.clock.pending_pings.first _(ping.what.value.event).must_equal Dynflow::Action::V2::WithSubPlans::Ping _(ping.when).must_be_within_delta(Time.now + action.polling_interval, 1) persistence = mock() # Simulate 1 sub-plan finished persistence.stubs(:find_execution_plan_counts).returns(0).then.returns(1) action.world.stubs(:persistence).returns(persistence) # Only 1 sub-plans fits into the capacity action.world.expects(:trigger).times(1) action.world.clock.progress action.world.executor.progress _(action.output['planned_count']).must_equal 3 persistence = mock() persistence.stubs(:find_execution_plan_counts).returns(0).then.returns(2) action.world.stubs(:persistence).returns(persistence) action.world.expects(:trigger).times(1) action.world.clock.progress action.world.executor.progress _(action.output['planned_count']).must_equal 4 persistence = mock() persistence.stubs(:find_execution_plan_counts).returns(0).then.returns(4) action.world.stubs(:persistence).returns(persistence) action.world.expects(:trigger).times(1) action.world.clock.progress action.world.executor.progress _(action.output['planned_count']).must_equal 5 _(action.concurrency_limit_capacity).must_equal 1 persistence = mock() persistence.stubs(:find_execution_plan_counts).returns(0).then.returns(5) action.world.stubs(:persistence).returns(persistence) action.world.expects(:trigger).never action.world.clock.progress action.world.executor.progress _(action.state).must_equal :success _(action.done?).must_equal true _(action.concurrency_limit_capacity).must_equal 2 end end end end end
ruby
MIT
e14dcdfe57cec99cc78b2f6ab521f00809b1408a
2026-01-04T17:50:16.326730Z
false
Dynflow/dynflow
https://github.com/Dynflow/dynflow/blob/e14dcdfe57cec99cc78b2f6ab521f00809b1408a/test/concurrency_control_test.rb
test/concurrency_control_test.rb
# frozen_string_literal: true require_relative 'test_helper' module Dynflow module ConcurrencyControlTest describe 'Concurrency Control' do include PlanAssertions include Dynflow::Testing::Assertions include Dynflow::Testing::Factories include TestHelpers class FailureSimulator def self.should_fail? @should_fail || false end def self.will_fail! @should_fail = true end def self.wont_fail! @should_fail = false end def self.will_sleep! @should_sleep = true end def self.wont_sleep! @should_sleep = false end def self.should_sleep? @should_sleep end end before do FailureSimulator.wont_fail! FailureSimulator.wont_sleep! end after do klok.clear end class ChildAction < ::Dynflow::Action def plan(should_sleep = false) raise "Simulated failure" if FailureSimulator.should_fail? plan_self :should_sleep => should_sleep end def run(event = nil) unless output[:slept] output[:slept] = true suspend { |suspended| world.clock.ping(suspended, 100, [:run]) } if input[:should_sleep] end end end class ParentAction < ::Dynflow::Action include Dynflow::Action::WithSubPlans def plan(count, concurrency_level = nil, time_span = nil, should_sleep = nil) limit_concurrency_level(concurrency_level) unless concurrency_level.nil? distribute_over_time(time_span, count) unless time_span.nil? plan_self :count => count, :should_sleep => should_sleep end def create_sub_plans input[:count].times.map { |i| trigger(::Dynflow::ConcurrencyControlTest::ChildAction, input[:should_sleep]) } end end let(:klok) { Dynflow::Testing::ManagedClock.new } let(:world) do WorldFactory.create_world do |config| config.throttle_limiter = proc { |world| LoggingThrottleLimiter.new world } end end def check_step(plan, total, finished) _(world.throttle_limiter.observe(plan.id).length).must_equal(total - finished) _(plan.sub_plans.select { |sub| planned? sub }.count).must_equal(total - finished) _(plan.sub_plans.select { |sub| successful? sub }.count).must_equal finished end def planned?(plan) plan.state == :planned && plan.result == :pending end def successful?(plan) plan.state == :stopped && plan.result == :success end class LoggingThrottleLimiter < Dynflow::ThrottleLimiter class LoggingCore < Dynflow::ThrottleLimiter::Core attr_reader :running def initialize(*args) @running = [0] super(*args) end def release(*args) # Discard semaphores without tickets, find the one with least tickets from the rest if @semaphores.key? args.first tickets = @semaphores[args.first].children.values.map { |sem| sem.tickets }.compact.min # Add running count to the log @running << (tickets - @semaphores[args.first].free) unless tickets.nil? end super(*args) end end def core_class LoggingThrottleLimiter::LoggingCore end end it 'can be disabled' do total = 10 plan = world.plan(ParentAction, 10) future = world.execute plan.id wait_for { future.resolved? } plan.sub_plans.all? { |sub| successful? sub } _(world.throttle_limiter.core.ask!(:running)).must_equal [0] end it 'limits by concurrency level' do total = 10 level = 4 plan = world.plan(ParentAction, total, level) future = world.execute plan.id wait_for { future.resolved? } _(world.throttle_limiter.core.ask!(:running).max).must_be :<=, level end it 'allows to cancel' do total = 5 world.stub :clock, klok do plan = world.plan(ParentAction, total, 0) triggered = world.execute(plan.id) wait_for { plan.sub_plans_count == total } world.event(plan.id, plan.steps.values.last.id, ::Dynflow::Action::Cancellable::Cancel) wait_for { triggered.resolved? } plan = world.persistence.load_execution_plan(plan.id) _(plan.entry_action.output[:failed_count]).must_equal total _(world.throttle_limiter.core.ask!(:running).max).must_be :<=, 0 end end it 'calculates time interval correctly' do world.stub :clock, klok do total = 10 get_interval = ->(plan) do plan = world.persistence.load_execution_plan(plan.id) plan.entry_action.input[:concurrency_control][:time][:meta][:interval] end plan = world.plan(ParentAction, total, 1, 10) world.execute(plan.id) wait_for { plan.sub_plans_count == total } wait_for { klok.progress; plan.sub_plans.all? { |sub| successful? sub } } # 10 tasks over 10 seconds, one task at a time, 1 task every second _(get_interval.call(plan)).must_equal 1.0 plan = world.plan(ParentAction, total, 4, 10) world.execute(plan.id) wait_for { plan.sub_plans_count == total } wait_for { klok.progress; plan.sub_plans.all? { |sub| successful? sub } } # 10 tasks over 10 seconds, four tasks at a time, 1 task every 0.25 second _(get_interval.call(plan)).must_equal 0.25 plan = world.plan(ParentAction, total, nil, 10) world.execute(plan.id) wait_for { plan.sub_plans_count == total } wait_for { klok.progress; plan.sub_plans.all? { |sub| successful? sub } } # 1o tasks over 10 seconds, one task at a time (default), 1 task every second _(get_interval.call(plan)).must_equal 1.0 end end it 'uses the throttle limiter to handle the plans' do world.stub :clock, klok do time_span = 10.0 total = 10 level = 2 plan = world.plan(ParentAction, total, level, time_span) start_time = klok.current_time world.execute(plan.id) wait_for { plan.sub_plans_count == total } wait_for { plan.sub_plans.select { |sub| successful? sub }.count == level } finished = 2 check_step(plan, total, finished) world.throttle_limiter.observe(plan.id).dup.each do |triggered| triggered.future.tap do |future| klok.progress wait_for { future.resolved? } end finished += 1 check_step(plan, total, finished) end end_time = klok.current_time _((end_time - start_time)).must_equal 4 _(world.throttle_limiter.observe(plan.id)).must_equal [] _(world.throttle_limiter.core.ask!(:running).max).must_be :<=, level end end it 'fails tasks which failed to plan immediately' do FailureSimulator.will_fail! total = 5 level = 1 time_span = 10 plan = world.plan(ParentAction, total, level, time_span) future = world.execute(plan.id) wait_for { future.resolved? } _(plan.sub_plans.all? { |sub| sub.result == :error }).must_equal true end it 'cancels tasks which could not be started within the time window' do world.stub :clock, klok do time_span = 10.0 level = 1 total = 10 plan = world.plan(ParentAction, total, level, time_span, true) future = world.execute(plan.id) wait_for { plan.sub_plans_count == total && plan.sub_plans.all? { |sub| sub.result == :pending } } planned, running = plan.sub_plans.partition { |sub| planned? sub } _(planned.count).must_equal total - level _(running.count).must_equal level _(world.throttle_limiter.observe(plan.id).length).must_equal(total - 1) 4.times { klok.progress } wait_for { future.resolved? } finished, stopped = plan.sub_plans.partition { |sub| successful? sub } _(finished.count).must_equal level _(stopped.count).must_equal(total - level) end end end end end
ruby
MIT
e14dcdfe57cec99cc78b2f6ab521f00809b1408a
2026-01-04T17:50:16.326730Z
false
Dynflow/dynflow
https://github.com/Dynflow/dynflow/blob/e14dcdfe57cec99cc78b2f6ab521f00809b1408a/test/middleware_test.rb
test/middleware_test.rb
# frozen_string_literal: true require_relative 'test_helper' module Dynflow module MiddlewareTest describe 'Middleware' do let(:world) { WorldFactory.create_world } let(:log) { Support::MiddlewareExample::LogMiddleware.log } before do Support::MiddlewareExample::LogMiddleware.reset_log end it "wraps the action method calls" do delay = world.delay(Support::MiddlewareExample::LoggingAction, { :start_at => Time.now.utc - 60 }, {}) plan = world.persistence.load_delayed_plan delay.execution_plan_id plan.plan plan.execute.future.wait _(log).must_equal %w[LogMiddleware::before_delay delay LogMiddleware::after_delay LogMiddleware::before_plan_phase LogMiddleware::before_plan plan LogMiddleware::after_plan LogMiddleware::after_plan_phase LogMiddleware::before_run run LogMiddleware::after_run LogMiddleware::before_finalize_phase LogMiddleware::before_finalize finalize LogMiddleware::after_finalize LogMiddleware::after_finalize_phase] end it "inherits the middleware" do world.trigger(Support::MiddlewareExample::SubAction, {}).finished.wait _(log).must_equal %w[LogRunMiddleware::before_run AnotherLogRunMiddleware::before_run run AnotherLogRunMiddleware::after_run LogRunMiddleware::after_run] end describe "world.middleware" do let(:world_with_middleware) do WorldFactory.create_world.tap do |world| world.middleware.use(Support::MiddlewareExample::AnotherLogRunMiddleware) end end it "puts the middleware to the beginning of the stack" do world_with_middleware.trigger(Support::MiddlewareExample::Action, {}).finished.wait _(log).must_equal %w[AnotherLogRunMiddleware::before_run LogRunMiddleware::before_run run LogRunMiddleware::after_run AnotherLogRunMiddleware::after_run] end end describe "rules" do describe "before" do specify do world.trigger(Support::MiddlewareExample::SubActionBeforeRule, {}).finished.wait _(log).must_equal %w[AnotherLogRunMiddleware::before_run LogRunMiddleware::before_run run LogRunMiddleware::after_run AnotherLogRunMiddleware::after_run] end end describe "after" do let(:world_with_middleware) do WorldFactory.create_world.tap do |world| world.middleware.use(Support::MiddlewareExample::AnotherLogRunMiddleware, after: Support::MiddlewareExample::LogRunMiddleware) end end specify do world_with_middleware.trigger(Support::MiddlewareExample::Action, {}).finished.wait _(log).must_equal %w[LogRunMiddleware::before_run AnotherLogRunMiddleware::before_run run AnotherLogRunMiddleware::after_run LogRunMiddleware::after_run] end end describe "replace" do specify do world.trigger(Support::MiddlewareExample::SubActionReplaceRule, {}).finished.wait _(log).must_equal %w[AnotherLogRunMiddleware::before_run run AnotherLogRunMiddleware::after_run] end end describe "remove" do specify do world.trigger(Support::MiddlewareExample::SubActionDoNotUseRule, {}).finished.wait _(log).must_equal %w[run] end end end it "allows access the running action" do world = WorldFactory.create_world world.middleware.use(Support::MiddlewareExample::ObservingMiddleware, replace: Support::MiddlewareExample::LogRunMiddleware) world.trigger(Support::MiddlewareExample::Action, message: 'hello').finished.wait _(log).must_equal %w[input#message:hello run output#message:finished] end it "allows modification of the running action when delaying execution" do world = WorldFactory.create_world world.middleware.use(Support::MiddlewareExample::AnotherObservingMiddleware, replace: Support::MiddlewareExample::LogRunMiddleware) delay = world.delay(Support::MiddlewareExample::Action, { :start_at => Time.now - 60 }) plan = world.persistence.load_delayed_plan delay.execution_plan_id plan.plan plan.execute.future.wait _(log).must_equal ["delay#set-input:#{world.id}", "plan#input:#{world.id}", "input#message:#{world.id}", 'run', 'output#message:finished'] end describe 'Presnet middleware' do let(:world_with_middleware) do WorldFactory.create_world.tap do |world| world.middleware.use(Support::MiddlewareExample::FilterSensitiveData) end end let :execution_plan do result = world.trigger(Support::CodeWorkflowExample::IncomingIssue, issue_data) _(result).must_be :planned? result.finished.value end let :execution_plan_2 do result = world.trigger(Support::MiddlewareExample::SecretAction) _(result).must_be :planned? result.finished.value end let :filtered_execution_plan do world_with_middleware.persistence.load_execution_plan(execution_plan.id) end let :issue_data do { 'author' => 'Harry Potter', 'text' => 'Lord Voldemort is comming' } end let :presenter do filtered_execution_plan.root_plan_step.action filtered_execution_plan end let :presenter_2 do execution_plan_2.root_plan_step.action execution_plan_2 end let :presenter_without_middleware do execution_plan.root_plan_step.action execution_plan end it 'filters the data ===' do _(presenter.input['text']).must_equal('You-Know-Who is comming') _(presenter_2.output['spell']).must_equal('***') end it "doesn't affect stored data" do _(presenter.input['text']).must_equal('You-Know-Who is comming') _(presenter_without_middleware.input['text']).must_equal('Lord Voldemort is comming') end end end end end
ruby
MIT
e14dcdfe57cec99cc78b2f6ab521f00809b1408a
2026-01-04T17:50:16.326730Z
false
Dynflow/dynflow
https://github.com/Dynflow/dynflow/blob/e14dcdfe57cec99cc78b2f6ab521f00809b1408a/test/redis_locking_test.rb
test/redis_locking_test.rb
# frozen_string_literal: true require_relative 'test_helper' require 'mocha/minitest' require 'minitest/stub_const' require 'ostruct' require 'sidekiq' require 'dynflow/executors/sidekiq/core' module Dynflow module RedisLockingTest describe Executors::Sidekiq::RedisLocking do class Orchestrator include Executors::Sidekiq::RedisLocking attr_accessor :logger def initialize(world, logger) @world = world @logger = logger end end class Logger attr_reader :logs def initialize @logs = [] end [:info, :error, :fatal].each do |key| define_method key do |message| @logs << [key, message] end end end after do ::Sidekiq.redis do |conn| conn.del Executors::Sidekiq::RedisLocking::REDIS_LOCK_KEY end end def redis_orchestrator_id ::Sidekiq.redis do |conn| conn.get Executors::Sidekiq::RedisLocking::REDIS_LOCK_KEY end end let(:world) { OpenStruct.new(:id => '12345') } let(:world2) { OpenStruct.new(:id => '67890') } let(:orchestrator) { Orchestrator.new(world, Logger.new) } let(:orchestrator2) { Orchestrator.new(world2, Logger.new) } it 'acquires the lock when it is not taken' do orchestrator.wait_for_orchestrator_lock logs = orchestrator.logger.logs _(redis_orchestrator_id).must_equal world.id _(logs).must_equal [[:info, 'Acquired orchestrator lock, entering active mode.']] end it 'reacquires the lock if it was lost' do orchestrator.reacquire_orchestrator_lock logs = orchestrator.logger.logs _(redis_orchestrator_id).must_equal world.id _(logs).must_equal [[:error, 'The orchestrator lock was lost, reacquired']] end it 'terminates the process if lock was stolen' do orchestrator.wait_for_orchestrator_lock Process.expects(:kill) orchestrator2.reacquire_orchestrator_lock logs = orchestrator2.logger.logs _(redis_orchestrator_id).must_equal world.id _(logs).must_equal [[:fatal, 'The orchestrator lock was stolen by 12345, aborting.']] end it 'polls for the lock availability' do Executors::Sidekiq::RedisLocking.stub_const(:REDIS_LOCK_TTL, 1) do Executors::Sidekiq::RedisLocking.stub_const(:REDIS_LOCK_POLL_INTERVAL, 0.5) do orchestrator.wait_for_orchestrator_lock _(redis_orchestrator_id).must_equal world.id orchestrator2.wait_for_orchestrator_lock end end _(redis_orchestrator_id).must_equal world2.id passive, active = orchestrator2.logger.logs _(passive).must_equal [:info, 'Orchestrator lock already taken, entering passive mode.'] _(active).must_equal [:info, 'Acquired orchestrator lock, entering active mode.'] end end end end
ruby
MIT
e14dcdfe57cec99cc78b2f6ab521f00809b1408a
2026-01-04T17:50:16.326730Z
false
Dynflow/dynflow
https://github.com/Dynflow/dynflow/blob/e14dcdfe57cec99cc78b2f6ab521f00809b1408a/test/rescue_test.rb
test/rescue_test.rb
# frozen_string_literal: true require_relative 'test_helper' module Dynflow module RescueTest describe 'on error' do Example = Support::RescueExample let(:world) { WorldFactory.create_world } def execute(*args) plan = world.plan(*args) raise plan.errors.first if plan.error? world.execute(plan.id).value end let :rescued_plan do world.persistence.load_execution_plan(execution_plan.id) end describe 'no auto rescue' do describe 'of simple skippable action in run phase' do let :execution_plan do execute(Example::ActionWithSkip, 1, :error_on_run) end it 'suggests skipping the action' do _(execution_plan.rescue_strategy).must_equal Action::Rescue::Skip end it "doesn't rescue" do _(rescued_plan.state).must_equal :paused end end describe 'of simple skippable action in finalize phase' do let :execution_plan do execute(Example::ActionWithSkip, 1, :error_on_finalize) end it 'suggests skipping the action' do _(execution_plan.rescue_strategy).must_equal Action::Rescue::Skip end it "doesn't rescue" do _(rescued_plan.state).must_equal :paused end end describe 'of complex action with skips in run phase' do let :execution_plan do execute(Example::ComplexActionWithSkip, :error_on_run) end it 'suggests skipping the action' do _(execution_plan.rescue_strategy).must_equal Action::Rescue::Skip end it "doesn't rescue" do _(rescued_plan.state).must_equal :paused end end describe 'of complex action with skips in finalize phase' do let :execution_plan do execute(Example::ComplexActionWithSkip, :error_on_finalize) end it 'suggests skipping the action' do _(execution_plan.rescue_strategy).must_equal Action::Rescue::Skip end it "doesn't rescue" do _(rescued_plan.state).must_equal :paused end end describe 'of complex action without skips' do let :execution_plan do execute(Example::ComplexActionWithoutSkip, :error_on_run) end it 'suggests pausing the plan' do _(execution_plan.rescue_strategy).must_equal Action::Rescue::Pause end it "doesn't rescue" do _(rescued_plan.state).must_equal :paused end end describe 'of complex action with fail' do let :execution_plan do execute(Example::ComplexActionWithFail, :error_on_run) end it 'suggests failing the plan' do _(execution_plan.rescue_strategy).must_equal Action::Rescue::Fail end it "doesn't rescue" do _(rescued_plan.state).must_equal :paused end end end describe 'auto rescue' do let(:world) do WorldFactory.create_world do |config| config.auto_rescue = true end end describe 'of simple skippable action in run phase' do let :execution_plan do execute(Example::ActionWithSkip, 1, :error_on_run) end it 'skips the action and continues' do _(rescued_plan.state).must_equal :stopped _(rescued_plan.result).must_equal :warning _(rescued_plan.entry_action.output[:message]) .must_equal "skipped because some error as you wish" end end describe 'of simple skippable action in finalize phase' do let :execution_plan do execute(Example::ActionWithSkip, 1, :error_on_finalize) end it 'skips the action and continues' do _(rescued_plan.state).must_equal :stopped _(rescued_plan.result).must_equal :warning _(rescued_plan.entry_action.output[:message]).must_equal "Been here" end end describe 'of plan with skips' do let :execution_plan do execute(Example::ComplexActionWithSkip, :error_on_run) end it 'skips the action and continues automatically' do _(execution_plan.state).must_equal :stopped _(execution_plan.result).must_equal :warning skipped_action = rescued_plan.actions.find do |action| action.run_step && action.run_step.state == :skipped end _(skipped_action.output[:message]).must_equal "skipped because some error as you wish" end end describe 'of complex action with skips in finalize phase' do let :execution_plan do execute(Example::ComplexActionWithSkip, :error_on_finalize) end it 'skips the action and continues' do _(rescued_plan.state).must_equal :stopped _(rescued_plan.result).must_equal :warning skipped_action = rescued_plan.actions.find do |action| action.steps.find { |step| step && step.state == :skipped } end _(skipped_action.output[:message]).must_equal "Been here" end end describe 'of plan faild on auto-rescue' do let :execution_plan do execute(Example::ActionWithSkip, 1, :error_on_skip) end it 'tried to rescue only once' do _(execution_plan.state).must_equal :paused _(execution_plan.result).must_equal :error end end describe 'of plan without skips' do let :execution_plan do execute(Example::ComplexActionWithoutSkip, :error_on_run) end it 'skips the action and continues automatically' do _(execution_plan.state).must_equal :paused _(execution_plan.result).must_equal :error expected_history = [['start execution', world.id], ['pause execution', world.id]] _(execution_plan.execution_history.map { |h| [h.name, h.world_id] }).must_equal(expected_history) end end describe 'of plan with fail' do let :execution_plan do execute(Example::ComplexActionWithFail, :error_on_run) end it 'fails the execution plan automatically' do _(execution_plan.state).must_equal :stopped _(execution_plan.result).must_equal :error _(execution_plan.steps_in_state(:success).count).must_equal 6 _(execution_plan.steps_in_state(:pending).count).must_equal 6 _(execution_plan.steps_in_state(:error).count).must_equal 1 expected_history = [['start execution', world.id], ['finish execution', world.id]] _(execution_plan.execution_history.map { |h| [h.name, h.world_id] }).must_equal(expected_history) end end end end end end
ruby
MIT
e14dcdfe57cec99cc78b2f6ab521f00809b1408a
2026-01-04T17:50:16.326730Z
false
Dynflow/dynflow
https://github.com/Dynflow/dynflow/blob/e14dcdfe57cec99cc78b2f6ab521f00809b1408a/test/activejob_adapter_test.rb
test/activejob_adapter_test.rb
# frozen_string_literal: true require_relative 'test_helper' require 'active_job' require 'dynflow/active_job/queue_adapter' module Dynflow class SampleJob < ::ActiveJob::Base queue_as :slow def perform(msg) puts "This job says #{msg}" puts "provider_job_id is #{provider_job_id}" end end describe 'running jobs' do include TestHelpers let :world do WorldFactory.create_world end before(:all) do ::ActiveJob::QueueAdapters.include ::Dynflow::ActiveJob::QueueAdapters ::ActiveJob::Base.queue_adapter = :dynflow dynflow_mock = Minitest::Mock.new dynflow_mock.expect(:world, world) rails_app_mock = Minitest::Mock.new rails_app_mock .expect(:dynflow, dynflow_mock) rails_mock = Minitest::Mock.new rails_mock.expect(:application, rails_app_mock) if defined? ::Rails @original_rails = ::Rails Object.send(:remove_const, 'Rails') end Object.const_set('Rails', rails_mock) end after(:all) do Object.send(:remove_const, 'Rails') Object.const_set('Rails', @original_rails) end it 'is able to run the job right away' do out, = capture_subprocess_io do SampleJob.perform_now 'hello' end assert_match(/job says hello/, out) end it 'enqueues the job' do job = nil out, = capture_subprocess_io do job = SampleJob.perform_later 'hello' wait_for do plan = world.persistence.load_execution_plan(job.provider_job_id) plan.state == :stopped end end assert_match(/Enqueued Dynflow::SampleJob/, out) assert_match(/provider_job_id is #{job.provider_job_id}/, out) end it 'schedules job in the future' do job = nil out, = capture_subprocess_io do job = SampleJob.set(:wait => 1.seconds).perform_later 'hello' end assert world.persistence.load_execution_plan(job.provider_job_id) assert_match(/Enqueued Dynflow::SampleJob.*at.*UTC/, out) end end end
ruby
MIT
e14dcdfe57cec99cc78b2f6ab521f00809b1408a
2026-01-04T17:50:16.326730Z
false
Dynflow/dynflow
https://github.com/Dynflow/dynflow/blob/e14dcdfe57cec99cc78b2f6ab521f00809b1408a/test/memory_cosumption_watcher_test.rb
test/memory_cosumption_watcher_test.rb
# frozen_string_literal: true require_relative 'test_helper' require 'fileutils' require 'dynflow/watchers/memory_consumption_watcher' module Dynflow module MemoryConsumptionWatcherTest describe ::Dynflow::Watchers::MemoryConsumptionWatcher do let(:world) { Minitest::Mock.new('world') } describe 'initialization' do it 'starts a timer on the world' do clock = Minitest::Mock.new('clock') world.expect(:clock, clock) init_interval = 1000 clock.expect(:ping, true) do |clock_who, clock_when, _| _(clock_when).must_equal init_interval end Dynflow::Watchers::MemoryConsumptionWatcher.new world, 1, initial_wait: init_interval clock.verify end end describe 'polling' do let(:memory_info_provider) { Minitest::Mock.new('memory_info_provider') } it 'continues to poll, if memory limit is not exceeded' do clock = Minitest::Mock.new('clock') # define method clock world.expect(:clock, clock) init_interval = 1000 polling_interval = 2000 clock.expect(:ping, true) do |clock_who, clock_when, _| _(clock_when).must_equal init_interval true end clock.expect(:ping, true) do |clock_who, clock_when, _| _(clock_when).must_equal polling_interval true end memory_info_provider.expect(:bytes, 0) # stub the clock method to always return our mock clock world.stub(:clock, clock) do watcher = Dynflow::Watchers::MemoryConsumptionWatcher.new( world, 1, initial_wait: init_interval, memory_info_provider: memory_info_provider, polling_interval: polling_interval ) watcher.check_memory_state end clock.verify memory_info_provider.verify end it 'terminates the world, if memory limit reached' do clock = Minitest::Mock.new('clock') # define method clock world.expect(:clock, clock) world.expect(:terminate, true) init_interval = 1000 clock.expect(:ping, true) do |clock_who, clock_when, _| _(clock_when).must_equal init_interval true end memory_info_provider.expect(:bytes, 10) # stub the clock method to always return our mock clock watcher = Dynflow::Watchers::MemoryConsumptionWatcher.new( world, 1, initial_wait: init_interval, memory_info_provider: memory_info_provider ) watcher.check_memory_state clock.verify memory_info_provider.verify world.verify end end end end end
ruby
MIT
e14dcdfe57cec99cc78b2f6ab521f00809b1408a
2026-01-04T17:50:16.326730Z
false
Dynflow/dynflow
https://github.com/Dynflow/dynflow/blob/e14dcdfe57cec99cc78b2f6ab521f00809b1408a/test/dead_letter_silencer_test.rb
test/dead_letter_silencer_test.rb
# frozen_string_literal: true require_relative 'test_helper' require 'ostruct' module Dynflow module DeadLetterSilencerTest describe ::Dynflow::DeadLetterSilencer do include Dynflow::Testing::Factories include TestHelpers let(:world) { WorldFactory.create_world } it 'is started for each world' do _(world.dead_letter_handler.actor_class) .must_equal ::Dynflow::DeadLetterSilencer end describe ::Dynflow::DeadLetterSilencer::Matcher do let(:any) { DeadLetterSilencer::Matcher::Any } let(:sender) { ::Dynflow::Clock } let(:msg) { :ping } let(:receiver) { ::Dynflow::DeadLetterSilencer } let(:letter) do OpenStruct.new(:sender => OpenStruct.new(:actor_class => sender), :message => msg, :address => OpenStruct.new(:actor_class => receiver)) end it 'matches any' do _(DeadLetterSilencer::Matcher.new(any, any, any).match?(letter)).must_equal true end it 'matches comparing for equality' do matcher = DeadLetterSilencer::Matcher.new(sender, msg, receiver) _(matcher.match?(letter)).must_equal true matcher = DeadLetterSilencer::Matcher.new(any, :bad, any) _(matcher.match?(letter)).must_equal false end it 'matches by calling the proc' do condition = proc { |actor_class| actor_class.is_a? Class } matcher = DeadLetterSilencer::Matcher.new(condition, any, condition) _(matcher.match?(letter)).must_equal true end end end end end
ruby
MIT
e14dcdfe57cec99cc78b2f6ab521f00809b1408a
2026-01-04T17:50:16.326730Z
false
Dynflow/dynflow
https://github.com/Dynflow/dynflow/blob/e14dcdfe57cec99cc78b2f6ab521f00809b1408a/test/execution_plan_cleaner_test.rb
test/execution_plan_cleaner_test.rb
# frozen_string_literal: true require_relative 'test_helper' require 'mocha/minitest' module Dynflow module ExecutionPlanCleanerTest describe ::Dynflow::Actors::ExecutionPlanCleaner do include Dynflow::Testing::Assertions include Dynflow::Testing::Factories include TestHelpers class SimpleAction < ::Dynflow::Action def plan; end end before do world.persistence.delete_execution_plans({}) end let(:default_world) { WorldFactory.create_world } let(:age) { 10 } let(:world) do WorldFactory.create_world do |config| config.execution_plan_cleaner = proc do |world| ::Dynflow::Actors::ExecutionPlanCleaner.new(world, :max_age => age) end end end let(:clock) { Testing::ManagedClock.new } it 'is disabled by default' do assert_nil default_world.execution_plan_cleaner _(world.execution_plan_cleaner) .must_be_instance_of ::Dynflow::Actors::ExecutionPlanCleaner end it 'periodically looks for old execution plans' do world.stub(:clock, clock) do _(clock.pending_pings.count).must_equal 0 world.execution_plan_cleaner.core.ask!(:start) _(clock.pending_pings.count).must_equal 1 world.persistence.expects(:find_old_execution_plans).returns([]) world.persistence.expects(:delete_execution_plans).with(:uuid => []) clock.progress wait_for { clock.pending_pings.count == 1 } end end it 'cleans up old plans' do world.stub(:clock, clock) do world.execution_plan_cleaner.core.ask!(:start) _(clock.pending_pings.count).must_equal 1 plans = (1..10).map { world.trigger SimpleAction } .each { |plan| plan.finished.wait } world.persistence.find_execution_plans(:uuid => plans.map(&:id)) .each do |plan| plan.instance_variable_set(:@ended_at, plan.ended_at - 15) plan.save end world.execution_plan_cleaner.core.ask!(:clean!) plans = world.persistence.find_execution_plans(:uuid => plans.map(&:id)) _(plans.count).must_equal 0 end end it 'leaves "new enough" plans intact' do world.stub(:clock, clock) do count = 10 world.execution_plan_cleaner.core.ask!(:start) _(clock.pending_pings.count).must_equal 1 plans = (1..10).map { world.trigger SimpleAction } .each { |plan| plan.finished.wait } world.execution_plan_cleaner.core.ask!(:clean!) plans = world.persistence.find_execution_plans(:uuid => plans.map(&:id)) _(plans.count).must_equal count end end end end end
ruby
MIT
e14dcdfe57cec99cc78b2f6ab521f00809b1408a
2026-01-04T17:50:16.326730Z
false
Dynflow/dynflow
https://github.com/Dynflow/dynflow/blob/e14dcdfe57cec99cc78b2f6ab521f00809b1408a/test/web_console_test.rb
test/web_console_test.rb
# frozen_string_literal: true require_relative 'test_helper' ENV['RACK_ENV'] = 'test' require 'dynflow/web' require 'rack/test' module Dynflow describe 'web console' do include Rack::Test::Methods let(:world) { WorldFactory.create_world } let :execution_plan_id do world.trigger(Support::CodeWorkflowExample::FastCommit, 'sha' => 'abc123') .tap { |o| o.finished.wait } .id end let :app do world = self.world Dynflow::Web.setup do set :world, world end end it 'lists all execution plans' do get '/' assert last_response.ok? end it 'show an execution plan' do get "/#{execution_plan_id}" assert last_response.ok? end end end
ruby
MIT
e14dcdfe57cec99cc78b2f6ab521f00809b1408a
2026-01-04T17:50:16.326730Z
false
Dynflow/dynflow
https://github.com/Dynflow/dynflow/blob/e14dcdfe57cec99cc78b2f6ab521f00809b1408a/test/coordinator_test.rb
test/coordinator_test.rb
# frozen_string_literal: true require_relative 'test_helper' require 'fileutils' module Dynflow module CoordinatorTest describe Coordinator do let(:world) { WorldFactory.create_world } let(:another_world) { WorldFactory.create_world } describe 'locks' do it 'unlocks the lock, when the block is passed' do world.coordinator.acquire(Coordinator::AutoExecuteLock.new(world)) {} expected_locks = ["lock auto-execute", "unlock auto-execute"] _(world.coordinator.adapter.lock_log).must_equal(expected_locks) end it "doesn't unlock, when the block is not passed" do world.coordinator.acquire(Coordinator::AutoExecuteLock.new(world)) expected_locks = ["lock auto-execute"] _(world.coordinator.adapter.lock_log).must_equal(expected_locks) end it 'supports unlocking by owner' do lock = Coordinator::AutoExecuteLock.new(world) tester = ConcurrentRunTester.new tester.while_executing do world.coordinator.acquire(lock) tester.pause end world.coordinator.release_by_owner("world:#{world.id}") world.coordinator.acquire(lock) # expected no error raised tester.finish end it 'supports checking about locks' do world.coordinator.acquire(Coordinator::AutoExecuteLock.new(world)) locks = world.coordinator.find_locks(Coordinator::AutoExecuteLock.unique_filter) _(locks.map(&:world_id)).must_equal([world.id]) end it 'deserializes the data from the adapter when searching for locks' do lock = Coordinator::AutoExecuteLock.new(world) world.coordinator.acquire(lock) found_locks = world.coordinator.find_locks(owner_id: lock.owner_id) _(found_locks.size).must_equal 1 _(found_locks.first.data).must_equal lock.data found_locks = world.coordinator.find_locks(class: lock.class.name, id: lock.id) _(found_locks.size).must_equal 1 _(found_locks.first.data).must_equal lock.data another_lock = Coordinator::AutoExecuteLock.new(another_world) found_locks = world.coordinator.find_locks(owner_id: another_lock.owner_id) _(found_locks.size).must_equal 0 end end describe 'records' do class DummyRecord < Coordinator::Record def initialize(id, value) super @data[:id] = value @data[:value] = value end def value @data[:value] end def value=(value) @data[:value] = (value) end end it 'allows CRUD record objects' do dummy_record = DummyRecord.new('dummy', 'Foo') world.coordinator.create_record(dummy_record) saved_dummy_record = world.coordinator.find_records(class: dummy_record.class.name).first _(saved_dummy_record).must_equal dummy_record dummy_record.value = 'Bar' world.coordinator.update_record(dummy_record) saved_dummy_record = world.coordinator.find_records(class: dummy_record.class.name).first _(saved_dummy_record.data).must_equal dummy_record.data world.coordinator.delete_record(dummy_record) _(world.coordinator.find_records(class: dummy_record.class.name)).must_equal [] end end describe 'on termination' do it 'removes all the locks assigned to the given world' do world.coordinator.acquire(Coordinator::AutoExecuteLock.new(world)) another_world.coordinator.acquire Coordinator::WorldInvalidationLock.new(another_world, another_world) world.terminate.wait expected_locks = ["lock auto-execute", "unlock auto-execute"] _(world.coordinator.adapter.lock_log).must_equal(expected_locks) end it 'prevents new locks to be acquired by the world being terminated' do world.terminate _(-> { world.coordinator.acquire(Coordinator::AutoExecuteLock.new(world)) }).must_raise(Errors::InactiveWorldError) end end def self.it_supports_global_records describe 'records handling' do it 'prevents saving the same record twice' do record = Coordinator::AutoExecuteLock.new(world) tester = ConcurrentRunTester.new tester.while_executing do adapter.create_record(record) tester.pause end _(-> { another_adapter.create_record(record) }).must_raise(Coordinator::DuplicateRecordError) tester.finish end it 'allows saving different records' do record = Coordinator::AutoExecuteLock.new(world) another_record = Coordinator::WorldInvalidationLock.new(world, another_world) tester = ConcurrentRunTester.new tester.while_executing do adapter.create_record(record) tester.pause end another_adapter.create_record(another_record) # expected no error raised tester.finish end it 'allows searching for the records on various criteria' do lock = Coordinator::AutoExecuteLock.new(world) adapter.create_record(lock) found_records = adapter.find_records(owner_id: lock.owner_id) _(found_records.size).must_equal 1 _(found_records.first).must_equal lock.data found_records = adapter.find_records(class: lock.class.name, id: lock.id) _(found_records.size).must_equal 1 _(found_records.first).must_equal lock.data another_lock = Coordinator::AutoExecuteLock.new(another_world) found_records = adapter.find_records(owner_id: another_lock.owner_id) _(found_records.size).must_equal 0 end end end describe CoordinatorAdapters::Sequel do let(:adapter) { CoordinatorAdapters::Sequel.new(world) } let(:another_adapter) { CoordinatorAdapters::Sequel.new(another_world) } it_supports_global_records end end end end
ruby
MIT
e14dcdfe57cec99cc78b2f6ab521f00809b1408a
2026-01-04T17:50:16.326730Z
false
Dynflow/dynflow
https://github.com/Dynflow/dynflow/blob/e14dcdfe57cec99cc78b2f6ab521f00809b1408a/test/clock_test.rb
test/clock_test.rb
# frozen_string_literal: true require_relative 'test_helper' require 'logger' clock_class = Dynflow::Clock describe clock_class do let(:clock) { clock_class.spawn 'clock' } it 'refuses who without #<< method' do _(-> { clock.ping Object.new, 0.1, :pong }).must_raise TypeError clock.ping [], 0.1, :pong end it 'pongs' do q = Queue.new start = Time.now clock.ping q, 0.1, o = Object.new assert_equal o, q.pop finish = Time.now assert_in_delta 0.1, finish - start, 0.08 end it 'pongs on expected times' do q = Queue.new start = Time.now clock.ping q, 0.3, :a clock.ping q, 0.1, :b clock.ping q, 0.2, :c assert_equal :b, q.pop assert_in_delta 0.1, Time.now - start, 0.08 assert_equal :c, q.pop assert_in_delta 0.2, Time.now - start, 0.08 assert_equal :a, q.pop assert_in_delta 0.3, Time.now - start, 0.08 end it 'works under stress' do threads = Array.new(4) do Thread.new do q = Queue.new times = 20 times.times { |i| clock.ping q, rand, i } assert_equal (0...times).to_a, Array.new(times) { q.pop }.sort end end threads.each(&:join) end end
ruby
MIT
e14dcdfe57cec99cc78b2f6ab521f00809b1408a
2026-01-04T17:50:16.326730Z
false
Dynflow/dynflow
https://github.com/Dynflow/dynflow/blob/e14dcdfe57cec99cc78b2f6ab521f00809b1408a/test/utils_test.rb
test/utils_test.rb
# frozen_string_literal: true require_relative 'test_helper' module Dynflow module UtilsTest describe ::Dynflow::Utils::PriorityQueue do let(:queue) { Utils::PriorityQueue.new } it 'can insert elements' do queue.push 1 _(queue.top).must_equal 1 queue.push 2 _(queue.top).must_equal 2 queue.push 3 _(queue.top).must_equal 3 _(queue.to_a).must_equal [1, 2, 3] end it 'can override the comparator' do queue = Utils::PriorityQueue.new { |a, b| b <=> a } queue.push 1 _(queue.top).must_equal 1 queue.push 2 _(queue.top).must_equal 1 queue.push 3 _(queue.top).must_equal 1 _(queue.to_a).must_equal [3, 2, 1] end it 'can inspect top element without removing it' do assert_nil queue.top queue.push(1) _(queue.top).must_equal 1 queue.push(3) _(queue.top).must_equal 3 queue.push(2) _(queue.top).must_equal 3 end it 'can report size' do count = 5 count.times { queue.push 1 } _(queue.size).must_equal count end it 'pops elements in correct order' do queue.push 1 queue.push 3 queue.push 2 _(queue.pop).must_equal 3 _(queue.pop).must_equal 2 _(queue.pop).must_equal 1 assert_nil queue.pop end end end end
ruby
MIT
e14dcdfe57cec99cc78b2f6ab521f00809b1408a
2026-01-04T17:50:16.326730Z
false
Dynflow/dynflow
https://github.com/Dynflow/dynflow/blob/e14dcdfe57cec99cc78b2f6ab521f00809b1408a/test/extensions_test.rb
test/extensions_test.rb
# frozen_string_literal: true require_relative 'test_helper' require 'active_support/all' module Dynflow module ExtensionsTest describe 'msgpack extensions' do before do Time.zone = ActiveSupport::TimeZone['Europe/Prague'] end after { Time.zone = nil } it 'allows {de,}serializing Time' do time = Time.now transformed = MessagePack.unpack(time.to_msgpack) assert_equal transformed, time assert_equal transformed.class, time.class end it 'allows {de,}serializing ActiveSupport::TimeWithZone' do time = Time.zone.now transformed = MessagePack.unpack(time.to_msgpack) assert_equal transformed, time assert_equal transformed.class, time.class end it 'allows {de,}serializing DateTime' do time = DateTime.now transformed = MessagePack.unpack(time.to_msgpack) assert_equal transformed, time assert_equal transformed.class, time.class end it 'allows {de,}serializing Date' do date = DateTime.current transformed = MessagePack.unpack(date.to_msgpack) assert_equal transformed, date assert_equal transformed.class, date.class end end end end
ruby
MIT
e14dcdfe57cec99cc78b2f6ab521f00809b1408a
2026-01-04T17:50:16.326730Z
false
Dynflow/dynflow
https://github.com/Dynflow/dynflow/blob/e14dcdfe57cec99cc78b2f6ab521f00809b1408a/test/test_helper.rb
test/test_helper.rb
# frozen_string_literal: true require 'bundler/setup' require 'minitest/reporters' require 'minitest/autorun' require 'minitest/spec' ENV['MT_NO_PLUGINS'] = 'true' MiniTest::Reporters.use! if ENV['RM_INFO'] load_path = File.expand_path(File.dirname(__FILE__)) $LOAD_PATH << load_path unless $LOAD_PATH.include? load_path require 'dynflow' require 'dynflow/testing' begin require 'pry'; rescue LoadError; nil end require 'support/code_workflow_example' require 'support/middleware_example' require 'support/rescue_example' require 'support/dummy_example' require 'support/test_execution_log' Concurrent.global_logger = lambda do |level, progname, message = nil, &block| ::Dynflow::Testing.logger_adapter.logger.add level, message, progname, &block end # To be able to stop a process in some step and perform assertions while paused class TestPause def self.setup @pause = Concurrent::Promises.resolvable_future @ready = Concurrent::Promises.resolvable_future end def self.teardown @pause = nil @ready = nil end # to be called from action def self.pause if !@pause raise 'the TestPause class was not setup' elsif @ready.resolved? raise 'you can pause only once' else @ready.fulfill(true) @pause.wait end end # in the block perform assertions def self.when_paused if @pause @ready.wait # wait till we are paused yield @pause.fulfill(true) # resume the run else raise 'the TestPause class was not setup' end end end class CoordiationAdapterWithLog < Dynflow::CoordinatorAdapters::Sequel attr_reader :lock_log def initialize(*args) @lock_log = [] super end def create_record(record) @lock_log << "lock #{record.id}" if record.is_a? Dynflow::Coordinator::Lock super end def delete_record(record) @lock_log << "unlock #{record.id}" if record.is_a? Dynflow::Coordinator::Lock super end end module WorldFactory def self.created_worlds @created_worlds ||= [] end def self.test_world_config config = Dynflow::Config.new config.persistence_adapter = persistence_adapter config.logger_adapter = logger_adapter config.coordinator_adapter = coordinator_adapter config.delayed_executor = nil config.auto_rescue = false config.auto_validity_check = false config.exit_on_terminate = false config.auto_execute = false config.auto_terminate = false config.backup_deleted_plans = false config.backup_dir = nil config.queues.add(:slow, :pool_size => 1) yield config if block_given? return config end # The worlds created by this method are getting terminated after each test run def self.create_world(klass = Dynflow::World, &block) klass.new(test_world_config(&block)).tap do |world| created_worlds << world end end # This world survives though the whole run of the test suite: careful with it, it can # introduce unnecessary test dependencies def self.logger_adapter ::Dynflow::Testing.logger_adapter end def self.persistence_adapter @persistence_adapter ||= begin db_config = ENV.fetch('DB_CONN_STRING') do case ENV['DB'] when 'postgresql' "postgres://postgres@localhost/#{ENV.fetch('POSTGRES_DB', 'ci_test')}" else 'sqlite:/' end end puts "Using database configuration: #{db_config}" Dynflow::PersistenceAdapters::Sequel.new(db_config) end end def self.coordinator_adapter ->(world, _) { CoordiationAdapterWithLog.new(world) } end def self.clean_coordinator_records persistence_adapter = WorldFactory.persistence_adapter persistence_adapter.find_coordinator_records({}).each do |w| ::Dynflow::Testing.logger_adapter.logger.warn "Unexpected coordinator record: #{w}" persistence_adapter.delete_coordinator_record(w[:class], w[:id]) end end def self.terminate_worlds created_worlds.map(&:terminate).map(&:wait) created_worlds.clear end end module TestHelpers # allows to create the world inside the tests, using the `connector` # and `persistence adapter` from the test context: usefull to create # multi-world topology for a signle test def create_world(with_executor = true, &block) WorldFactory.create_world do |config| config.connector = connector config.persistence_adapter = persistence_adapter unless with_executor config.executor = false end block.call(config) if block end end def connector_polling_interval(world) if world.persistence.adapter.db.class.name == "Sequel::Postgres::Database" 5 else 0.005 end end # get director for deeper investigation of the current execution state def get_director(world) core_context = world.executor.instance_variable_get('@core').instance_variable_get('@core').context core_context.instance_variable_get('@director') end # waits for the passed block to return non-nil value and reiterates it while getting false # (till some reasonable timeout). Useful for forcing the tests for some event to occur def wait_for(waiting_message = 'something to happen') 30.times do ret = yield return ret if ret sleep 0.3 end assert false, "waiting for #{waiting_message} was not successful" end def executor_id_for_plan(execution_plan_id) if lock = client_world.coordinator.find_locks(class: Dynflow::Coordinator::ExecutionLock.name, id: "execution-plan:#{execution_plan_id}").first lock.world_id end end def trigger_waiting_action triggered = client_world.trigger(Support::DummyExample::DeprecatedEventedAction) wait_for { executor_id_for_plan(triggered.id) } # waiting for the plan to be picked by an executor triggered end # trigger an action, and keep it running while yielding the block def while_executing_plan triggered = trigger_waiting_action executor_id = wait_for do executor_id_for_plan(triggered.id) end plan = client_world.persistence.load_execution_plan(triggered.id) step = plan.steps.values.last wait_for do client_world.persistence.load_step(step.execution_plan_id, step.id, client_world).state == :suspended end executor = WorldFactory.created_worlds.find { |e| e.id == executor_id } raise "Could not find an executor with id #{executor_id}" unless executor yield executor return triggered end # finish the plan triggered by the `while_executing_plan` method def finish_the_plan(triggered) wait_for do client_world.persistence.load_execution_plan(triggered.id).state == :running && client_world.persistence.load_step(triggered.id, 2, client_world).state == :suspended end client_world.event(triggered.id, 2, 'finish') return triggered.finished.value end def assert_plan_reexecuted(plan) assert_equal :stopped, plan.state assert_equal :success, plan.result assert_equal ['start execution', 'terminate execution', 'start execution', 'finish execution'], plan.execution_history.map(&:name) refute_equal plan.execution_history.first.world_id, plan.execution_history.to_a.last.world_id end end class MiniTest::Test def logger ::Dynflow::Testing.logger_adapter.logger end def setup logger.info(">>>>> #{location}") WorldFactory.clean_coordinator_records end def teardown WorldFactory.terminate_worlds logger.info("<<<<< #{location}") end end # ensure there are no unresolved events at the end or being GCed events_test = -> do event_creations = {} non_ready_events = {} Concurrent::Promises::Event.singleton_class.send :define_method, :new do |*args, &block| super(*args, &block).tap do |event| event_creations[event.object_id] = caller(4) end end [Concurrent::Promises::Event, Concurrent::Promises::ResolvableFuture].each do |future_class| original_resolved_method = future_class.instance_method :resolve_with future_class.send :define_method, :resolve_with do |*args| begin original_resolved_method.bind(self).call(*args) ensure event_creations.delete(self.object_id) end end end MiniTest.after_run do Concurrent::Actor.root.ask!(:terminate!) non_ready_events = ObjectSpace.each_object(Concurrent::Promises::Event).map do |event| event.wait(1) unless event.resolved? event.object_id end end.compact # make sure to include the ids that were garbage-collected already non_ready_events = (non_ready_events + event_creations.keys).uniq unless non_ready_events.empty? unified = non_ready_events.each_with_object({}) do |(id, _), h| backtrace_key = event_creations[id].hash h[backtrace_key] ||= [] h[backtrace_key] << id end raise("there were #{non_ready_events.size} non_ready_events:\n" + unified.map do |_, ids| "--- #{ids.size}: #{ids}\n#{event_creations[ids.first].join("\n")}" end.join("\n")) end end # time out all futures by default default_timeout = 8 wait_method = Concurrent::Promises::AbstractEventFuture.instance_method(:wait) Concurrent::Promises::AbstractEventFuture.class_eval do define_method :wait do |timeout = nil| wait_method.bind(self).call(timeout || default_timeout) end end end events_test.call class ConcurrentRunTester def initialize @enter_future, @exit_future = Concurrent::Promises.resolvable_future, Concurrent::Promises.resolvable_future end def while_executing(&block) @thread = Thread.new do block.call(self) end @enter_future.wait(1) end def pause @enter_future.fulfill(true) @exit_future.wait(1) end def finish @exit_future.fulfill(true) @thread.join end end module PlanAssertions def inspect_flow(execution_plan, flow) out = "".dup inspect_subflow(out, execution_plan, flow, "".dup) out.gsub(/ => /, '=>') end def inspect_plan_steps(execution_plan) out = "".dup inspect_plan_step(out, execution_plan, execution_plan.root_plan_step, "".dup) out end def assert_planning_success(execution_plan) execution_plan.plan_steps.all? { |plan_step| _(plan_step.state).must_equal :success, plan_step.error } end def assert_run_flow(expected, execution_plan) assert_planning_success(execution_plan) _(inspect_flow(execution_plan, execution_plan.run_flow).chomp).must_equal dedent(expected).chomp end def assert_finalize_flow(expected, execution_plan) assert_planning_success(execution_plan) _(inspect_flow(execution_plan, execution_plan.finalize_flow).chomp).must_equal dedent(expected).chomp end def assert_run_flow_equal(expected_plan, execution_plan) expected = inspect_flow(expected_plan, expected_plan.run_flow) current = inspect_flow(execution_plan, execution_plan.run_flow) assert_equal expected, current end def assert_steps_equal(expected, current) _(current.id).must_equal expected.id _(current.class).must_equal expected.class _(current.state).must_equal expected.state _(current.action_class).must_equal expected.action_class _(current.action_id).must_equal expected.action_id if expected.respond_to?(:children) _(current.children).must_equal(expected.children) end end def assert_plan_steps(expected, execution_plan) _(inspect_plan_steps(execution_plan).chomp).must_equal dedent(expected).chomp end def assert_finalized(action_class, input) assert_executed(:finalize, action_class, input) end def assert_executed(phase, action_class, input) log = TestExecutionLog.send(phase).log found_log = log.any? do |(logged_action_class, logged_input)| action_class == logged_action_class && input == logged_input end unless found_log message = ["#{action_class} with input #{input.inspect} not executed in #{phase} phase"] message << "following actions were executed:" log.each do |(logged_action_class, logged_input)| message << "#{logged_action_class} #{logged_input.inspect}" end raise message.join("\n") end end def inspect_subflow(out, execution_plan, flow, prefix) case flow when Dynflow::Flows::Atom out << prefix out << flow.step_id.to_s << ': ' step = execution_plan.steps[flow.step_id] out << step.action_class.to_s[/\w+\Z/] out << "(#{step.state})" out << ' ' action = execution_plan.world.persistence.load_action(step) out << action.input.inspect unless step.state == :pending out << ' --> ' out << action.output.inspect end out << "\n" else out << prefix << flow.class.name << "\n" flow.sub_flows.each do |sub_flow| inspect_subflow(out, execution_plan, sub_flow, prefix + ' ') end end out end def inspect_plan_step(out, execution_plan, plan_step, prefix) out << prefix out << plan_step.action_class.to_s[/\w+\Z/] out << "\n" plan_step.children.each do |sub_step_id| sub_step = execution_plan.steps[sub_step_id] inspect_plan_step(out, execution_plan, sub_step, prefix + ' ') end out end def dedent(string) dedent = string.scan(/^ */).map { |spaces| spaces.size }.min string.lines.map { |line| line[dedent..-1] }.join end end
ruby
MIT
e14dcdfe57cec99cc78b2f6ab521f00809b1408a
2026-01-04T17:50:16.326730Z
false
Dynflow/dynflow
https://github.com/Dynflow/dynflow/blob/e14dcdfe57cec99cc78b2f6ab521f00809b1408a/test/world_test.rb
test/world_test.rb
# frozen_string_literal: true require_relative 'test_helper' require 'fileutils' module Dynflow module WorldTest describe World do let(:world) { WorldFactory.create_world } let(:world_with_custom_meta) { WorldFactory.create_world { |c| c.meta = { 'fast' => true } } } describe '#meta' do it 'by default informs about the hostname and the pid running the world' do registered_world = world.coordinator.find_worlds(false, id: world.id).first registered_world.meta.delete('last_seen') _(registered_world.meta).must_equal('hostname' => Socket.gethostname, 'pid' => Process.pid, 'queues' => { 'default' => { 'pool_size' => 5 }, 'slow' => { 'pool_size' => 1 } }) end it 'is configurable' do registered_world = world.coordinator.find_worlds(false, id: world_with_custom_meta.id).first _(registered_world.meta['fast']).must_equal true end end describe '#get_execution_status' do let(:base) do { :default => { :pool_size => 5, :free_workers => 5, :queue_size => 0 }, :slow => { :pool_size => 1, :free_workers => 1, :queue_size => 0 } } end it 'retrieves correct execution items count' do _(world.get_execution_status(world.id, nil, 5).value!).must_equal(base) id = 'something like uuid' expected = base.dup expected[:default][:queue_size] = 0 expected[:slow][:queue_size] = 0 _(world.get_execution_status(world.id, id, 5).value!).must_equal(expected) end end describe '#terminate' do it 'fires an event after termination' do terminated_event = world.terminated _(terminated_event.resolved?).must_equal false world.terminate # wait for termination process to finish, but don't block # the test from running. terminated_event.wait(10) _(terminated_event.resolved?).must_equal true end end end end end
ruby
MIT
e14dcdfe57cec99cc78b2f6ab521f00809b1408a
2026-01-04T17:50:16.326730Z
false
Dynflow/dynflow
https://github.com/Dynflow/dynflow/blob/e14dcdfe57cec99cc78b2f6ab521f00809b1408a/test/dispatcher_test.rb
test/dispatcher_test.rb
# frozen_string_literal: true require_relative 'test_helper' module Dynflow module DispatcherTest describe "dispatcher" do include TestHelpers let(:persistence_adapter) { WorldFactory.persistence_adapter } def self.dispatcher_works_with_this_connector describe 'connector basics' do before do # just mention the executor to initialize it executor_world end describe 'execution passing' do it 'succeeds when expected' do result = client_world.trigger(Support::DummyExample::Dummy) assert_equal :success, result.finished.value.result end end describe 'event passing' do it 'succeeds when expected' do result = client_world.trigger(Support::DummyExample::DeprecatedEventedAction, :timeout => 3) step = wait_for do client_world.persistence.load_execution_plan(result.id) .steps_in_state(:suspended).first end client_world.event(step.execution_plan_id, step.id, 'finish') plan = result.finished.value assert_equal('finish', plan.actions.first.output[:event]) end it 'fails the future when the step is not accepting events' do result = client_world.trigger(Support::CodeWorkflowExample::Dummy, { :text => "dummy" }) plan = result.finished.value! step = plan.steps.values.first future = client_world.event(plan.id, step.id, 'finish') future.wait assert future.rejected? end it 'succeeds when executor acts as client' do result = client_world.trigger(Support::DummyExample::ComposedAction, :timeout => 3) plan = result.finished.value assert_equal('finish', plan.actions.first.output[:event]) end it 'does not error on dispatching an optional event' do request = client_world.event('123', 1, nil, optional: true) request.wait(20) assert_match(/Could not find an executor for optional .*, discarding/, request.reason.message) end end end end def self.supports_dynamic_retry before do # mention the executors to make sure they are initialized @executors = [executor_world, executor_world_2] end describe 'when some executor is terminated and client is notified about the failure' do specify 'client passes the work to another executor' do triggered = while_executing_plan { |executor| executor.terminate.wait } plan = finish_the_plan(triggered) assert_plan_reexecuted(plan) end end end def self.supports_ping_pong describe 'ping/pong' do it 'succeeds when the world is available' do ping_response = client_world.ping(executor_world.id, 0.5) ping_response.wait assert ping_response.fulfilled? end it 'succeeds when the world is available without cache' do ping_response = client_world.ping_without_cache(executor_world.id, 0.5) ping_response.wait assert ping_response.fulfilled? end it 'time-outs when the world is not responding' do executor_world.terminate.wait ping_response = client_world.ping(executor_world.id, 0.5) ping_response.wait assert ping_response.rejected? end it 'time-outs when the world is not responding without cache' do executor_world.terminate.wait ping_response = client_world.ping_without_cache(executor_world.id, 0.5) ping_response.wait assert ping_response.rejected? end it 'caches the pings and pongs' do # Spawn the worlds client_world executor_world ping_cache = Dynflow::Dispatcher::ClientDispatcher::PingCache.new(executor_world) # Records are fresh because of the heartbeat assert ping_cache.fresh_record?(client_world.id) assert ping_cache.fresh_record?(executor_world.id) # Expire the record ping_cache.add_record(executor_world.id, Time.now - 1000) refute ping_cache.fresh_record?(executor_world.id) end end end def self.handles_no_executor_available it 'fails to finish the future when no executor available' do client_world # just to initialize the client world before terminating the executors executor_world.terminate.wait executor_world_2.terminate.wait result = client_world.trigger(Support::DummyExample::Dummy) result.finished.wait assert result.finished.rejected? assert_match(/No executor available/, result.finished.reason.message) end end describe 'direct connector - all in one' do let(:connector) { Proc.new { |world| Connectors::Direct.new(world) } } let(:executor_world) { create_world } let(:client_world) { executor_world } dispatcher_works_with_this_connector supports_ping_pong end describe 'direct connector - multi executor multi client' do let(:shared_connector) { Connectors::Direct.new() } let(:connector) { Proc.new { |world| shared_connector.start_listening(world); shared_connector } } let(:executor_world) { create_world(true) } let(:executor_world_2) { create_world(true) } let(:client_world) { create_world(false) } let(:client_world_2) { create_world(false) } dispatcher_works_with_this_connector supports_dynamic_retry supports_ping_pong handles_no_executor_available end describe 'database connector - all in one' do let(:connector) { Proc.new { |world| Connectors::Database.new(world, connector_polling_interval(world)) } } let(:executor_world) { create_world } let(:client_world) { executor_world } dispatcher_works_with_this_connector supports_ping_pong end describe 'database connector - multi executor multi client' do let(:connector) { Proc.new { |world| Connectors::Database.new(world, connector_polling_interval(world)) } } let(:executor_world) { create_world(true) } let(:executor_world_2) { create_world(true) } let(:client_world) { create_world(false) } let(:client_world_2) { create_world(false) } dispatcher_works_with_this_connector supports_dynamic_retry supports_ping_pong handles_no_executor_available end end end end
ruby
MIT
e14dcdfe57cec99cc78b2f6ab521f00809b1408a
2026-01-04T17:50:16.326730Z
false
Dynflow/dynflow
https://github.com/Dynflow/dynflow/blob/e14dcdfe57cec99cc78b2f6ab521f00809b1408a/test/execution_plan_hooks_test.rb
test/execution_plan_hooks_test.rb
# frozen_string_literal: true require_relative 'test_helper' module Dynflow class ExecutionPlan describe Hooks do include PlanAssertions let(:world) { WorldFactory.create_world } class Flag class << self attr_accessor :raised_count def raise! self.raised_count ||= 0 self.raised_count += 1 end def raised? raised_count > 0 end def lower! self.raised_count = 0 end end end module FlagHook def raise_flag(_execution_plan) Flag.raise! end def controlled_failure(_execution_plan) Flag.raise! raise "A controlled failure" end def raise_flag_root_only(_execution_plan) Flag.raise! if root_action? end end class ActionWithHooks < ::Dynflow::Action include FlagHook execution_plan_hooks.use :raise_flag, :on => :success end class ActionOnStop < ::Dynflow::Action include FlagHook execution_plan_hooks.use :controlled_failure, :on => :stopped end class RootOnlyAction < ::Dynflow::Action include FlagHook execution_plan_hooks.use :raise_flag_root_only, :on => :stopped end class PendingAction < ::Dynflow::Action include FlagHook execution_plan_hooks.use :raise_flag, :on => :pending end class AllTransitionsAction < ::Dynflow::Action include FlagHook execution_plan_hooks.use :raise_flag end class ComposedAction < RootOnlyAction def plan plan_action(RootOnlyAction) plan_action(RootOnlyAction) end end class ActionOnFailure < ::Dynflow::Action include FlagHook execution_plan_hooks.use :raise_flag, :on => :failure end class ActionOnPause < ::Dynflow::Action include FlagHook def run error!("pause") end def rescue_strategy Dynflow::Action::Rescue::Pause end execution_plan_hooks.use :raise_flag, :on => :paused end class Inherited < ActionWithHooks; end class Overriden < ActionWithHooks execution_plan_hooks.do_not_use :raise_flag end before { Flag.lower! } after { world.persistence.delete_delayed_plans({}) } it 'runs the on_success hook' do refute Flag.raised? plan = world.trigger(ActionWithHooks) plan.finished.wait! assert Flag.raised? end it 'runs the on_pause hook' do refute Flag.raised? plan = world.trigger(ActionOnPause) plan.finished.wait! assert Flag.raised? end describe 'with auto_rescue' do let(:world) do WorldFactory.create_world do |config| config.auto_rescue = true end end it 'runs the on_pause hook' do refute Flag.raised? plan = world.trigger(ActionOnPause) plan.finished.wait! assert Flag.raised? end end it 'runs the on_failure hook on cancel' do refute Flag.raised? @start_at = Time.now.utc + 180 delay = world.delay(ActionOnFailure, { :start_at => @start_at }) delayed_plan = world.persistence.load_delayed_plan(delay.execution_plan_id) delayed_plan.execution_plan.cancel.each(&:wait) assert Flag.raised? end it 'does not alter the execution plan when exception happens in the hook' do refute Flag.raised? plan = world.plan(ActionOnStop) plan = world.execute(plan.id).wait!.value assert Flag.raised? _(plan.result).must_equal :success end it 'inherits the hooks when subclassing' do refute Flag.raised? plan = world.trigger(Inherited) plan.finished.wait! assert Flag.raised? end it 'can override the hooks from the child' do refute Flag.raised? plan = world.trigger(Overriden) plan.finished.wait! refute Flag.raised? end it 'can determine in side the hook, whether the hook is running for root action or sub-action' do refute Flag.raised? plan = world.trigger(ComposedAction) plan.finished.wait! _(Flag.raised_count).must_equal 1 end it 'runs the pending hooks when execution plan is created' do refute Flag.raised? plan = world.trigger(PendingAction) plan.finished.wait! _(Flag.raised_count).must_equal 1 end it 'runs the pending hooks when execution plan is created' do refute Flag.raised? delay = world.delay(PendingAction, { :start_at => Time.now.utc + 180 }) delayed_plan = world.persistence.load_delayed_plan(delay.execution_plan_id) delayed_plan.execution_plan.cancel.each(&:wait) _(Flag.raised_count).must_equal 1 end it 'runs the hook on every state transition' do refute Flag.raised? plan = world.trigger(AllTransitionsAction) plan.finished.wait! # There should be 5 transitions # nothing -> pending -> planning -> planned -> running -> stopped _(Flag.raised_count).must_equal 5 end end end end
ruby
MIT
e14dcdfe57cec99cc78b2f6ab521f00809b1408a
2026-01-04T17:50:16.326730Z
false
Dynflow/dynflow
https://github.com/Dynflow/dynflow/blob/e14dcdfe57cec99cc78b2f6ab521f00809b1408a/test/persistence_test.rb
test/persistence_test.rb
# frozen_string_literal: true require_relative 'test_helper' require 'tmpdir' require 'ostruct' module Dynflow module PersistenceTest describe 'persistence adapters' do let :execution_plans_data do [{ id: 'plan1', :label => 'test1', root_plan_step_id: 1, class: 'Dynflow::ExecutionPlan', state: 'paused' }, { id: 'plan2', :label => 'test2', root_plan_step_id: 1, class: 'Dynflow::ExecutionPlan', state: 'stopped' }, { id: 'plan3', :label => 'test3', root_plan_step_id: 1, class: 'Dynflow::ExecutionPlan', state: 'paused' }, { id: 'plan4', :label => 'test4', root_plan_step_id: 1, class: 'Dynflow::ExecutionPlan', state: 'paused' }] end let :action_data do { id: 1, caller_execution_plan_id: nil, caller_action_id: nil, class: 'Dynflow::Action', input: { key: 'value' }, output: { something: 'else' }, plan_step_id: 1, run_step_id: 2, finalize_step_id: 3 } end let :step_data do { id: 1, state: 'success', started_at: Time.now.utc - 60, ended_at: Time.now.utc - 30, real_time: 1.1, execution_time: 0.1, action_id: 1, progress_done: 1, progress_weight: 2.5 } end def prepare_plans execution_plans_data.map do |h| h.merge result: nil, started_at: Time.now.utc - 20, ended_at: Time.now.utc - 10, real_time: 0.0, execution_time: 0.0 end end def prepare_and_save_plans prepare_plans.each { |plan| adapter.save_execution_plan(plan[:id], plan) } end def format_time(time) time.strftime('%Y-%m-%d %H:%M:%S') end def prepare_action(plan) adapter.save_action(plan, action_data[:id], action_data) end def prepare_step(plan) step = step_data.dup step[:execution_plan_uuid] = plan step end def prepare_and_save_step(plan) step = prepare_step(plan) adapter.save_step(plan, step[:id], step) end def prepare_plans_with_actions prepare_and_save_plans.each do |plan| prepare_action(plan[:id]) end end def prepare_plans_with_steps prepare_plans_with_actions.map do |plan| prepare_and_save_step(plan[:id]) end end def assert_equal_attributes!(original, loaded) original.each do |key, value| loaded_value = loaded[key.to_s] if value.is_a?(Time) _(loaded_value).must_be_within_delta(value, 0.5) elsif value.is_a?(Hash) assert_equal_attributes!(value, loaded_value) elsif value.nil? assert_nil loaded[key.to_s] else _(loaded[key.to_s]).must_equal value end end end # rubocop:disable Metrics/AbcSize,Metrics/MethodLength def self.it_acts_as_persistence_adapter before do # the tests expect clean field adapter.delete_execution_plans({}) end describe '#find_execution_plans' do it 'supports pagination' do prepare_and_save_plans if adapter.pagination? loaded_plans = adapter.find_execution_plans(page: 0, per_page: 1) _(loaded_plans.map { |h| h[:id] }).must_equal ['plan1'] loaded_plans = adapter.find_execution_plans(page: 1, per_page: 1) _(loaded_plans.map { |h| h[:id] }).must_equal ['plan2'] end end it 'supports ordering' do prepare_and_save_plans if adapter.ordering_by.include?('state') loaded_plans = adapter.find_execution_plans(order_by: 'state') _(loaded_plans.map { |h| h[:id] }).must_equal %w(plan1 plan3 plan4 plan2) loaded_plans = adapter.find_execution_plans(order_by: 'state', desc: true) _(loaded_plans.map { |h| h[:id] }).must_equal %w(plan2 plan1 plan3 plan4) end end it 'supports filtering' do prepare_and_save_plans if adapter.ordering_by.include?('state') loaded_plans = adapter.find_execution_plans(filters: { label: ['test1'] }) _(loaded_plans.map { |h| h[:id] }).must_equal ['plan1'] loaded_plans = adapter.find_execution_plans(filters: { state: ['paused'] }) _(loaded_plans.map { |h| h[:id] }).must_equal ['plan1', 'plan3', 'plan4'] loaded_plans = adapter.find_execution_plans(filters: { state: ['stopped'] }) _(loaded_plans.map { |h| h[:id] }).must_equal ['plan2'] loaded_plans = adapter.find_execution_plans(filters: { state: [] }) _(loaded_plans.map { |h| h[:id] }).must_equal [] loaded_plans = adapter.find_execution_plans(filters: { state: ['stopped', 'paused'] }) _(loaded_plans.map { |h| h[:id] }).must_equal %w(plan1 plan2 plan3 plan4) loaded_plans = adapter.find_execution_plans(filters: { 'state' => ['stopped', 'paused'] }) _(loaded_plans.map { |h| h[:id] }).must_equal %w(plan1 plan2 plan3 plan4) loaded_plans = adapter.find_execution_plans(filters: { label: ['test1'], :delayed => true }) _(loaded_plans).must_be_empty adapter.save_delayed_plan('plan1', :execution_plan_uuid => 'plan1', :start_at => format_time(Time.now + 60), :start_before => format_time(Time.now - 60)) loaded_plans = adapter.find_execution_plans(filters: { label: ['test1'], :delayed => true }) _(loaded_plans.map { |h| h[:id] }).must_equal ['plan1'] end end end describe '#def find_execution_plan_statuses' do before do # the tests expect clean field adapter.delete_execution_plans({}) end it 'supports filtering' do prepare_and_save_plans if adapter.ordering_by.include?('state') loaded_plans = adapter.find_execution_plan_statuses(filters: { label: ['test1'] }) _(loaded_plans).must_equal({ 'plan1' => { state: 'paused', result: nil } }) loaded_plans = adapter.find_execution_plan_statuses(filters: { state: ['paused'] }) _(loaded_plans).must_equal({ "plan1" => { :state => "paused", :result => nil }, "plan3" => { :state => "paused", :result => nil }, "plan4" => { :state => "paused", :result => nil } }) loaded_plans = adapter.find_execution_plan_statuses(filters: { state: ['stopped'] }) _(loaded_plans).must_equal({ "plan2" => { :state => "stopped", :result => nil } }) loaded_plans = adapter.find_execution_plan_statuses(filters: { state: [] }) _(loaded_plans).must_equal({}) loaded_plans = adapter.find_execution_plan_statuses(filters: { state: ['stopped', 'paused'] }) _(loaded_plans).must_equal({ "plan1" => { :state => "paused", :result => nil }, "plan2" => { :state => "stopped", :result => nil }, "plan3" => { :state => "paused", :result => nil }, "plan4" => { :state => "paused", :result => nil } }) loaded_plans = adapter.find_execution_plan_statuses(filters: { 'state' => ['stopped', 'paused'] }) _(loaded_plans).must_equal({ "plan1" => { :state => "paused", :result => nil }, "plan2" => { :state => "stopped", :result => nil }, "plan3" => { :state => "paused", :result => nil }, "plan4" => { :state => "paused", :result => nil } }) loaded_plans = adapter.find_execution_plan_statuses(filters: { label: ['test1'], :delayed => true }) _(loaded_plans).must_equal({}) end end end describe '#def find_execution_plan_counts' do before do # the tests expect clean field adapter.delete_execution_plans({}) end it 'supports filtering' do prepare_and_save_plans if adapter.ordering_by.include?('state') loaded_plans = adapter.find_execution_plan_counts(filters: { label: ['test1'] }) _(loaded_plans).must_equal 1 loaded_plans = adapter.find_execution_plan_counts(filters: { state: ['paused'] }) _(loaded_plans).must_equal 3 loaded_plans = adapter.find_execution_plan_counts(filters: { state: ['stopped'] }) _(loaded_plans).must_equal 1 loaded_plans = adapter.find_execution_plan_counts(filters: { state: [] }) _(loaded_plans).must_equal 0 loaded_plans = adapter.find_execution_plan_counts(filters: { state: ['stopped', 'paused'] }) _(loaded_plans).must_equal 4 loaded_plans = adapter.find_execution_plan_counts(filters: { 'state' => ['stopped', 'paused'] }) _(loaded_plans).must_equal 4 loaded_plans = adapter.find_execution_plan_counts(filters: { label: ['test1'], :delayed => true }) _(loaded_plans).must_equal 0 adapter.save_delayed_plan('plan1', :execution_plan_uuid => 'plan1', :start_at => format_time(Time.now + 60), :start_before => format_time(Time.now - 60)) loaded_plans = adapter.find_execution_plan_counts(filters: { label: ['test1'], :delayed => true }) _(loaded_plans).must_equal 1 end end end describe '#load_execution_plan and #save_execution_plan' do it 'serializes/deserializes the plan data' do _(-> { adapter.load_execution_plan('plan1') }).must_raise KeyError plan = prepare_and_save_plans.first loaded_plan = adapter.load_execution_plan('plan1') _(loaded_plan[:id]).must_equal 'plan1' _(loaded_plan['id']).must_equal 'plan1' assert_equal_attributes!(plan, loaded_plan) adapter.save_execution_plan('plan1', nil) _(-> { adapter.load_execution_plan('plan1') }).must_raise KeyError end end describe '#delete_execution_plans' do it 'deletes selected execution plans, including steps and actions' do prepare_plans_with_steps _(adapter.delete_execution_plans('uuid' => 'plan1')).must_equal 1 _(-> { adapter.load_execution_plan('plan1') }).must_raise KeyError _(-> { adapter.load_action('plan1', action_data[:id]) }).must_raise KeyError _(-> { adapter.load_step('plan1', step_data[:id]) }).must_raise KeyError # testing that no other plans where affected adapter.load_execution_plan('plan2') adapter.load_action('plan2', action_data[:id]) adapter.load_step('plan2', step_data[:id]) prepare_plans_with_steps _(adapter.delete_execution_plans('state' => 'paused')).must_equal 3 _(-> { adapter.load_execution_plan('plan1') }).must_raise KeyError adapter.load_execution_plan('plan2') # nothing raised _(-> { adapter.load_execution_plan('plan3') }).must_raise KeyError end it 'creates backup dir and produce backup including steps and actions' do prepare_plans_with_steps Dir.mktmpdir do |backup_dir| _(adapter.delete_execution_plans({ 'uuid' => 'plan1' }, 100, backup_dir)).must_equal 1 plans = CSV.read(backup_dir + "/execution_plans.csv", :headers => true) assert_equal 1, plans.count assert_equal 'plan1', plans.first.to_hash['uuid'] actions = CSV.read(backup_dir + "/actions.csv", :headers => true) assert_equal 1, actions.count assert_equal 'plan1', actions.first.to_hash['execution_plan_uuid'] steps = CSV.read(backup_dir + "/steps.csv", :headers => true) assert_equal 1, steps.count assert_equal 'plan1', steps.first.to_hash['execution_plan_uuid'] end end end describe '#load_action and #save_action' do it 'serializes/deserializes the action data' do prepare_and_save_plans action = action_data.dup action_id = action_data[:id] _(-> { adapter.load_action('plan1', action_id) }).must_raise KeyError prepare_action('plan1') loaded_action = adapter.load_action('plan1', action_id) _(loaded_action[:id]).must_equal action_id assert_equal_attributes!(action, loaded_action) adapter.save_action('plan1', action_id, nil) _(-> { adapter.load_action('plan1', action_id) }).must_raise KeyError adapter.save_execution_plan('plan1', nil) end it 'allow to retrieve specific attributes using #load_actions_attributes' do prepare_and_save_plans prepare_action('plan1') loaded_data = adapter.load_actions_attributes('plan1', [:id, :run_step_id]).first _(loaded_data.keys.count).must_equal 2 _(loaded_data[:id]).must_equal action_data[:id] _(loaded_data[:run_step_id]).must_equal action_data[:run_step_id] end it 'allows to load actions in bulk using #load_actions' do prepare_and_save_plans prepare_action('plan1') action = action_data.dup loaded_actions = adapter.load_actions('plan1', [1]) _(loaded_actions.count).must_equal 1 loaded_action = loaded_actions.first assert_equal_attributes!(action, loaded_action) end end describe '#load_step and #save_step' do it 'serializes/deserializes the step data' do prepare_plans_with_actions step_id = step_data[:id] prepare_and_save_step('plan1') loaded_step = adapter.load_step('plan1', step_id) _(loaded_step[:id]).must_equal step_id assert_equal_attributes!(step_data, loaded_step) end end describe '#find_ready_delayed_plans' do it 'finds plans with start_before in past' do start_time = Time.now.utc prepare_and_save_plans adapter.save_delayed_plan('plan1', :execution_plan_uuid => 'plan1', :frozen => false, :start_at => format_time(start_time + 60), :start_before => format_time(start_time - 60)) adapter.save_delayed_plan('plan2', :execution_plan_uuid => 'plan2', :frozen => false, :start_at => format_time(start_time - 60)) adapter.save_delayed_plan('plan3', :execution_plan_uuid => 'plan3', :frozen => false, :start_at => format_time(start_time + 60)) adapter.save_delayed_plan('plan4', :execution_plan_uuid => 'plan4', :frozen => false, :start_at => format_time(start_time - 60), :start_before => format_time(start_time - 60)) plans = adapter.find_ready_delayed_plans(start_time) _(plans.length).must_equal 3 _(plans.map { |plan| plan[:execution_plan_uuid] }).must_equal %w(plan2 plan4 plan1) end it 'does not find plans that are frozen' do start_time = Time.now.utc prepare_and_save_plans adapter.save_delayed_plan('plan1', :execution_plan_uuid => 'plan1', :frozen => false, :start_at => format_time(start_time + 60), :start_before => format_time(start_time - 60)) adapter.save_delayed_plan('plan2', :execution_plan_uuid => 'plan2', :frozen => true, :start_at => format_time(start_time + 60), :start_before => format_time(start_time - 60)) plans = adapter.find_ready_delayed_plans(start_time) _(plans.length).must_equal 1 _(plans.first[:execution_plan_uuid]).must_equal 'plan1' end it 'finds plans with null start_at' do start_time = Time.now.utc prepare_and_save_plans adapter.save_delayed_plan('plan1', :execution_plan_uuid => 'plan1', :frozen => false) plans = adapter.find_ready_delayed_plans(start_time) _(plans.length).must_equal 1 _(plans.first[:execution_plan_uuid]).must_equal 'plan1' end it 'properly stored execution plan dependencies' do prepare_and_save_plans adapter.save_delayed_plan('plan1', :execution_plan_uuid => 'plan1', :frozen => false) adapter.chain_execution_plan('plan2', 'plan1') adapter.chain_execution_plan('plan3', 'plan1') dependencies = adapter.find_execution_plan_dependencies('plan1') _(dependencies.to_set).must_equal ['plan2', 'plan3'].to_set end it 'does not find blocked plans' do start_time = Time.now.utc prepare_and_save_plans adapter.save_delayed_plan('plan1', :execution_plan_uuid => 'plan1', :frozen => false) adapter.chain_execution_plan('plan2', 'plan1') adapter.chain_execution_plan('plan3', 'plan1') plans = adapter.find_ready_delayed_plans(start_time) _(plans.length).must_equal 0 end it 'finds plans which are no longer blocked' do start_time = Time.now.utc prepare_and_save_plans adapter.save_delayed_plan('plan1', :execution_plan_uuid => 'plan1', :frozen => false) adapter.chain_execution_plan('plan2', 'plan1') plans = adapter.find_ready_delayed_plans(start_time) _(plans.length).must_equal 1 _(plans.first[:execution_plan_uuid]).must_equal 'plan1' end it 'does not find plans which are no longer blocked but are frozen' do start_time = Time.now.utc prepare_and_save_plans adapter.save_delayed_plan('plan1', :execution_plan_uuid => 'plan1', :frozen => true) adapter.chain_execution_plan('plan2', 'plan1') plans = adapter.find_ready_delayed_plans(start_time) _(plans.length).must_equal 0 end it 'does not find plans which are no longer blocked but their start_at is in the future' do start_time = Time.now.utc prepare_and_save_plans adapter.save_delayed_plan('plan1', :execution_plan_uuid => 'plan1', :frozen => false, :start_at => start_time + 60) adapter.chain_execution_plan('plan2', 'plan1') # plan2 is already stopped plans = adapter.find_ready_delayed_plans(start_time) _(plans.length).must_equal 0 end end describe '#delete_output_chunks' do it 'deletes output chunks' do prepare_plans_with_actions adapter.save_output_chunks('plan1', 1, [{ chunk: "Hello", timestamp: Time.now }, { chunk: "Bye", timestamp: Time.now }]) chunks = adapter.load_output_chunks('plan1', 1) _(chunks.length).must_equal 2 deleted = adapter.delete_output_chunks('plan1', 1) _(deleted).must_equal 2 chunks = adapter.load_output_chunks('plan1', 1) _(chunks.length).must_equal 0 end end end describe Dynflow::PersistenceAdapters::Sequel do let(:adapter) { Dynflow::PersistenceAdapters::Sequel.new 'sqlite:/' } it_acts_as_persistence_adapter it 'allows inspecting the persisted content' do plans = prepare_and_save_plans plans.each do |original| stored = adapter.to_hash.fetch(:execution_plans).find { |ep| ep[:uuid].strip == original[:id] } adapter.class::META_DATA.fetch(:execution_plan).each do |name| value = original.fetch(name.to_sym) if value.nil? assert_nil stored.fetch(name.to_sym) elsif value.is_a?(Time) _(stored.fetch(name.to_sym)).must_be_within_delta(value, 0.5) else _(stored.fetch(name.to_sym)).must_equal value end end end end it "supports connector's needs for exchaning envelopes" do client_world_id = '5678' executor_world_id = '1234' envelope_hash = ->(envelope) { Dynflow::Utils.indifferent_hash(Dynflow.serializer.dump(envelope)) } executor_envelope = envelope_hash.call(Dispatcher::Envelope['123', client_world_id, executor_world_id, Dispatcher::Execution['111']]) client_envelope = envelope_hash.call(Dispatcher::Envelope['123', executor_world_id, client_world_id, Dispatcher::Accepted]) envelopes = [client_envelope, executor_envelope] envelopes.each { |e| adapter.push_envelope(e) } assert_equal [executor_envelope], adapter.pull_envelopes(executor_world_id) assert_equal [client_envelope], adapter.pull_envelopes(client_world_id) assert_equal [], adapter.pull_envelopes(client_world_id) assert_equal [], adapter.pull_envelopes(executor_world_id) end it 'supports pruning of envelopes of invalidated worlds' do client_world_id = '5678' executor_world_id = '1234' envelope_hash = ->(envelope) { Dynflow::Utils.indifferent_hash(Dynflow.serializer.dump(envelope)) } executor_envelope = envelope_hash.call(Dispatcher::Envelope['123', client_world_id, executor_world_id, Dispatcher::Execution['111']]) client_envelope = envelope_hash.call(Dispatcher::Envelope['123', executor_world_id, client_world_id, Dispatcher::Accepted]) envelopes = [client_envelope, executor_envelope] envelopes.each { |e| adapter.push_envelope(e) } assert_equal 1, adapter.prune_envelopes([executor_world_id]) assert_equal 0, adapter.prune_envelopes([executor_world_id]) assert_equal [], adapter.pull_envelopes(executor_world_id) assert_equal [client_envelope], adapter.pull_envelopes(client_world_id) end it 'supports pruning of orphaned envelopes' do client_world_id = '5678' executor_world_id = '1234' envelope_hash = ->(envelope) { Dynflow::Utils.indifferent_hash(Dynflow.serializer.dump(envelope)) } executor_envelope = envelope_hash.call(Dispatcher::Envelope['123', client_world_id, executor_world_id, Dispatcher::Execution['111']]) client_envelope = envelope_hash.call(Dispatcher::Envelope['123', executor_world_id, client_world_id, Dispatcher::Accepted]) envelopes = [client_envelope, executor_envelope] envelopes.each { |e| adapter.push_envelope(e) } adapter.insert_coordinator_record({ "class" => "Dynflow::Coordinator::ExecutorWorld", "id" => executor_world_id, "meta" => {}, "active" => true }) assert_equal 1, adapter.prune_undeliverable_envelopes assert_equal 0, adapter.prune_undeliverable_envelopes assert_equal [], adapter.pull_envelopes(client_world_id) assert_equal [executor_envelope], adapter.pull_envelopes(executor_world_id) assert_equal [], adapter.pull_envelopes(executor_world_id) end it 'supports reading data saved prior to normalization' do db = adapter.send(:db) # Prepare records for saving plan = prepare_plans.first step_data = prepare_step(plan[:id]) # We used to store times as strings plan[:started_at] = format_time plan[:started_at] plan[:ended_at] = format_time plan[:ended_at] step_data[:started_at] = format_time step_data[:started_at] step_data[:ended_at] = format_time step_data[:ended_at] plan_record = adapter.send(:prepare_record, :execution_plan, plan.merge(:uuid => plan[:id])) action_record = adapter.send(:prepare_record, :action, action_data.dup) step_record = adapter.send(:prepare_record, :step, step_data) # Insert the records db[:dynflow_execution_plans].insert plan_record.merge(:uuid => plan[:id]) db[:dynflow_actions].insert action_record.merge(:execution_plan_uuid => plan[:id], :id => action_data[:id]) db[:dynflow_steps].insert step_record.merge(:execution_plan_uuid => plan[:id], :id => step_data[:id]) # Load the saved records loaded_plan = adapter.load_execution_plan(plan[:id]) loaded_action = adapter.load_action(plan[:id], action_data[:id]) loaded_step = adapter.load_step(plan[:id], step_data[:id]) # Test assert_equal_attributes!(plan, loaded_plan) assert_equal_attributes!(action_data, loaded_action) assert_equal_attributes!(step_data, loaded_step) end it 'support updating data saved prior to normalization' do db = adapter.send(:db) plan = prepare_plans.first plan_data = plan.dup plan[:started_at] = format_time plan[:started_at] plan[:ended_at] = format_time plan[:ended_at] plan_record = adapter.send(:prepare_record, :execution_plan, plan.merge(:uuid => plan[:id])) # Save the plan the old way db[:dynflow_execution_plans].insert plan_record.merge(:uuid => plan[:id]) # Update and save the plan plan_data[:state] = 'stopped' plan_data[:result] = 'success' adapter.save_execution_plan(plan[:id], plan_data) # Check the plan has the changed columns populated raw_plan = db[:dynflow_execution_plans].where(:uuid => 'plan1').first _(raw_plan[:state]).must_equal 'stopped' _(raw_plan[:result]).must_equal 'success' # Load the plan and assert it doesn't read attributes from data loaded_plan = adapter.load_execution_plan(plan[:id]) assert_equal_attributes!(plan_data, loaded_plan) end it 'does not leak Sequel blobs' do db = adapter.send(:db) # Prepare records for saving plan = prepare_plans.first value = 'a' * 1000 adata = action_data.merge({ :output => { :key => value } }) plan_record = adapter.send(:prepare_record, :execution_plan, plan.merge(:uuid => plan[:id])) action_record = adapter.send(:prepare_record, :action, adata.dup) # Insert the records db[:dynflow_execution_plans].insert plan_record.merge(:uuid => plan[:id]) db[:dynflow_actions].insert action_record.merge(:execution_plan_uuid => plan[:id], :id => adata[:id]) # Load the saved records loaded_action = adapter.load_action(plan[:id], adata[:id]) _(loaded_action[:output][:key].class).must_equal String _(loaded_action[:output][:key]).must_equal value end end end end end
ruby
MIT
e14dcdfe57cec99cc78b2f6ab521f00809b1408a
2026-01-04T17:50:16.326730Z
false
Dynflow/dynflow
https://github.com/Dynflow/dynflow/blob/e14dcdfe57cec99cc78b2f6ab521f00809b1408a/test/testing_test.rb
test/testing_test.rb
# frozen_string_literal: true require_relative 'test_helper' module Dynflow CWE = Support::CodeWorkflowExample describe Testing do include Testing describe 'testing' do specify '#plan_action' do input = { 'input' => 'input' } action = create_and_plan_action Support::DummyExample::WeightedPolling, input _(action).must_be_kind_of Support::DummyExample::WeightedPolling _(action.phase).must_equal Action::Plan _(action.input).must_equal input _(action.execution_plan).must_be_kind_of Testing::DummyExecutionPlan _(action.state).must_equal :success assert_run_phase action assert_finalize_phase action assert_action_planned action, Support::DummyExample::Polling refute_action_planned action, CWE::DummyAnotherTrigger end specify 'stub_plan_action' do action = create_action Support::DummyExample::WeightedPolling action.execution_plan.stub_planned_action(Support::DummyExample::Polling) do |sub_action| sub_action.define_singleton_method(:test) { "test" } end plan_action(action, {}) stubbed_action = action.execution_plan.planned_plan_steps.first _(stubbed_action.test).must_equal "test" end specify '#create_action_presentation' do action = create_action_presentation(Support::DummyExample::WeightedPolling) action.output['message'] = 'make the world a better place' _(action.humanized_output).must_equal 'You should make the world a better place' end specify '#run_action without suspend' do input = { 'input' => 'input' } plan = create_and_plan_action Support::DummyExample::WeightedPolling, input action = run_action plan _(action).must_be_kind_of Support::DummyExample::WeightedPolling _(action.phase).must_equal Action::Run _(action.input).must_equal input _(action.world).must_equal plan.world _(action.run_step_id).wont_equal action.plan_step_id _(action.state).must_equal :success end specify '#run_action with suspend' do input = { 'input' => 'input' } plan = create_and_plan_action Support::DummyExample::Polling, input action = run_action plan _(action.output).must_equal 'task' => { 'progress' => 0, 'done' => false } _(action.run_progress).must_equal 0 3.times { progress_action_time action } _(action.output).must_equal('task' => { 'progress' => 30, 'done' => false }, 'poll_attempts' => { 'total' => 2, 'failed' => 0 }) _(action.run_progress).must_equal 0.3 run_action action, Dynflow::Action::Polling::Poll run_action action, Dynflow::Action::Polling::Poll _(action.output).must_equal('task' => { 'progress' => 50, 'done' => false }, 'poll_attempts' => { 'total' => 4, 'failed' => 0 }) _(action.run_progress).must_equal 0.5 5.times { progress_action_time action } _(action.output).must_equal('task' => { 'progress' => 100, 'done' => true }, 'poll_attempts' => { 'total' => 9, 'failed' => 0 }) _(action.run_progress).must_equal 1 end specify '#finalize_action' do input = { 'input' => 'input' } plan = create_and_plan_action Support::DummyExample::WeightedPolling, input run = run_action plan $dummy_heavy_progress = false action = finalize_action run _(action).must_be_kind_of Support::DummyExample::WeightedPolling _(action.phase).must_equal Action::Finalize _(action.input).must_equal input _(action.output).must_equal run.output _(action.world).must_equal plan.world _(action.finalize_step_id).wont_equal action.run_step_id _(action.state).must_equal :success _($dummy_heavy_progress).must_equal 'dummy_heavy_progress' end end describe 'testing examples' do describe CWE::Commit do it 'plans' do action = create_and_plan_action CWE::Commit, sha = 'commit-sha' _(action.input).must_equal({}) refute_run_phase action refute_finalize_phase action assert_action_planned action, CWE::Ci assert_action_planned_with action, CWE::Review do |_, name, _| name == 'Morfeus' end assert_action_planned_with action, CWE::Review, sha, 'Neo', true end end describe CWE::Review do let(:plan_input) { ['sha', 'name', true] } let(:input) { { commit: 'sha', reviewer: 'name', result: true } } let(:planned_action) { create_and_plan_action CWE::Review, *plan_input } let(:runned_action) { run_action planned_action } it 'plans' do _(planned_action.input).must_equal Utils.stringify_keys(input) assert_run_phase planned_action, { commit: "sha", reviewer: "name", result: true } refute_finalize_phase planned_action _(planned_action.execution_plan.planned_plan_steps).must_be_empty end it 'runs' do _(runned_action.output.fetch(:passed)).must_equal runned_action.input.fetch(:result) end end describe CWE::Merge do let(:plan_input) { { commit: 'sha', ci_result: true, review_results: [true, true] } } let(:input) { plan_input } let(:planned_action) { create_and_plan_action CWE::Merge, plan_input } let(:runned_action) { run_action planned_action } it 'plans' do assert_run_phase planned_action do |input| _(input[:commit]).must_equal "sha" end refute_finalize_phase planned_action _(planned_action.execution_plan.planned_plan_steps).must_be_empty end it 'runs' do _(runned_action.output.fetch(:passed)).must_equal true end describe 'when something fails' do def plan_input super.update review_results: [true, false] end it 'runs' do _(runned_action.output.fetch(:passed)).must_equal false end end end end describe 'in thread executor with unrelated events in clock' do class PollingAction < ::Dynflow::Action def run(event = nil) if output[:suspended].nil? output[:suspended] = true suspend do |action| world.clock.ping(action, 1000, nil) end end end end let :world do WorldFactory.create_world(Dynflow::Testing::InThreadWorld) end let :execution_plan do world.plan(PollingAction) end it 'processes unrelated events' do q = Queue.new 20.times { |i| world.clock.ping q, 0.0002, :periodic_check_inbox } f = world.execute(execution_plan.id) # This deadlocks the test f.wait f.value.tap do |plan| _(plan.state).must_equal :stopped end end end describe "in thread executor" do let :world do WorldFactory.create_world(Dynflow::Testing::InThreadWorld) end let :issues_data do [{ 'author' => 'Peter Smith', 'text' => 'Failing test' }, { 'author' => 'John Doe', 'text' => 'Internal server error' }] end let :failing_issues_data do [{ 'author' => 'Peter Smith', 'text' => 'Failing test' }, { 'author' => 'John Doe', 'text' => 'trolling' }] end let :finalize_failing_issues_data do [{ 'author' => 'Peter Smith', 'text' => 'Failing test' }, { 'author' => 'John Doe', 'text' => 'trolling in finalize' }] end let :execution_plan do world.plan(Support::CodeWorkflowExample::IncomingIssues, issues_data) end let :failed_execution_plan do plan = world.plan(Support::CodeWorkflowExample::IncomingIssues, failing_issues_data) plan = world.execute(plan.id).value _(plan.state).must_equal :paused plan end let :polling_execution_plan do world.plan(Support::DummyExample::Polling, { :external_task_id => '123' }) end it "is able to execute plans inside the thread" do world.execute(execution_plan.id).value.tap do |plan| _(plan.state).must_equal :stopped end end it "is able to handle errors in the plan" do world.execute(failed_execution_plan.id).value.tap do |plan| _(plan.state).must_equal :paused end end it "is able to handle when events" do world.execute(polling_execution_plan.id).value.tap do |plan| _(plan.state).must_equal :stopped end end describe 'auto rescue' do let(:world) do WorldFactory.create_world(Dynflow::Testing::InThreadWorld) do |config| config.auto_rescue = true end end describe 'of plan with skips' do let :execution_plan do plan = world.plan(Support::RescueExample::ComplexActionWithSkip, :error_on_run) world.execute(plan.id).value end it 'skips the action and continues automatically' do _(execution_plan.state).must_equal :stopped _(execution_plan.result).must_equal :warning end end end end end end
ruby
MIT
e14dcdfe57cec99cc78b2f6ab521f00809b1408a
2026-01-04T17:50:16.326730Z
false
Dynflow/dynflow
https://github.com/Dynflow/dynflow/blob/e14dcdfe57cec99cc78b2f6ab521f00809b1408a/test/abnormal_states_recovery_test.rb
test/abnormal_states_recovery_test.rb
# -*- coding: utf-8 -*- # frozen_string_literal: true require_relative 'test_helper' require 'ostruct' module Dynflow module ConsistencyCheckTest describe "consistency check" do include TestHelpers def with_invalidation_while_executing(finish) triggered = while_executing_plan do |executor| if Connectors::Direct === executor.connector # for better simulation of invalidation with direct executor executor.connector.stop_listening(executor) end client_world.invalidate(executor.registered_world) end plan = if finish finish_the_plan(triggered) else triggered.finished.wait client_world.persistence.load_execution_plan(triggered.id) end yield plan ensure # just to workaround state transition checks due to our simulation # of second world being inactive if plan plan.set_state(:running, true) plan.save end end let(:persistence_adapter) { WorldFactory.persistence_adapter } let(:shared_connector) { Connectors::Direct.new } let(:connector) { Proc.new { |world| shared_connector.start_listening(world); shared_connector } } let(:executor_world) { create_world(true) { |config| config.auto_validity_check = true } } let(:executor_world_2) { create_world(true) { |config| config.auto_validity_check = true } } let(:client_world) { create_world(false) } let(:client_world_2) { create_world(false) } describe "for plans assigned to invalid world" do before do # mention the executors to make sure they are initialized [executor_world, executor_world_2] end describe 'world invalidation' do it 'removes the world from the register' do client_world.invalidate(executor_world.registered_world) worlds = client_world.coordinator.find_worlds refute_includes(worlds, executor_world.registered_world) end it 'schedules the plans to be run on different executor' do with_invalidation_while_executing(true) do |plan| assert_plan_reexecuted(plan) end end it 'when no executor is available, marks the plans as paused' do executor_world_2.terminate.wait with_invalidation_while_executing(false) do |plan| _(plan.state).must_equal :paused _(plan.result).must_equal :pending expected_history = [['start execution', executor_world.id], ['terminate execution', executor_world.id]] _(plan.execution_history.map { |h| [h.name, h.world_id] }).must_equal(expected_history) end end it "honors rescue strategy when invalidating execution locks" do coordinator = executor_world_2.coordinator # Plan and action plan = client_world.plan(Support::DummyExample::SkippableDummy) plan.update_state :running plan.save # Simulate leaving behind an execution lock for it lock = Coordinator::ExecutionLock.new(executor_world, plan.id, client_world.id, 0) coordinator.acquire(lock) # Simulate abnormal termination step = plan.steps.values.last step.state = :error step.save # Invalidate the world's lock world_lock = coordinator.find_worlds(false, :id => executor_world.id).first executor_world_2.invalidate(world_lock) wait_for do plan = executor_world_2.persistence.load_execution_plan(plan.id) step = plan.steps.values.last plan.state == :stopped && step.state == :skipped end end it "prevents from running the invalidation twice on the same world" do client_world.invalidate(executor_world.registered_world) expected_locks = ["lock world-invalidation:#{executor_world.id}", "unlock world-invalidation:#{executor_world.id}"] _(client_world.coordinator.adapter.lock_log).must_equal(expected_locks) end it "prevents from running the consistency checks twice on the same world concurrently" do client_world.invalidate(executor_world.registered_world) expected_locks = ["lock world-invalidation:#{executor_world.id}", "unlock world-invalidation:#{executor_world.id}"] _(client_world.coordinator.adapter.lock_log).must_equal(expected_locks) end it "handles missing execution plans" do lock = Coordinator::ExecutionLock.new(executor_world, "missing", nil, nil) executor_world.coordinator.acquire(lock) client_world.invalidate(executor_world.registered_world) expected_locks = ["lock world-invalidation:#{executor_world.id}", "unlock execution-plan:missing", "unlock world-invalidation:#{executor_world.id}"] _(client_world.coordinator.adapter.lock_log).must_equal(expected_locks) end it 'releases singleton locks belonging to missing execution plan' do execution_plan_id = 'missing' action_class = 'ActionClass' locks = [Coordinator::ExecutionLock.new(executor_world, "missing", nil, nil), Coordinator::SingletonActionLock.new(action_class, execution_plan_id)] locks.each { |lock| executor_world.coordinator.acquire lock } client_world.invalidate(executor_world.registered_world) expected_locks = ["lock world-invalidation:#{executor_world.id}", "unlock execution-plan:#{execution_plan_id}", "unlock singleton-action:#{action_class}", "unlock world-invalidation:#{executor_world.id}"] _(client_world.coordinator.adapter.lock_log).must_equal(expected_locks) end describe 'planning locks' do it 'releases orphaned planning locks and executes associated execution plans' do plan = client_world.plan(Support::DummyExample::Dummy) plan.set_state(:planning, true) plan.save client_world.coordinator.acquire Coordinator::PlanningLock.new(client_world, plan.id) executor_world.invalidate(client_world.registered_world) expected_locks = ["lock world-invalidation:#{client_world.id}", "unlock execution-plan:#{plan.id}", # planning lock "lock execution-plan:#{plan.id}", # execution lock "unlock world-invalidation:#{client_world.id}"] _(executor_world.coordinator.adapter.lock_log).must_equal(expected_locks) wait_for do plan = client_world_2.persistence.load_execution_plan(plan.id) plan.state == :stopped end end it 'releases orphaned planning locks and stops associated execution plans which did not finish planning' do plan = client_world.plan(Support::DummyExample::Dummy) plan.set_state(:planning, true) plan.save step = plan.plan_steps.first step.set_state(:pending, true) step.save client_world.coordinator.acquire Coordinator::PlanningLock.new(client_world, plan.id) client_world_2.invalidate(client_world.registered_world) expected_locks = ["lock world-invalidation:#{client_world.id}", "unlock execution-plan:#{plan.id}", "unlock world-invalidation:#{client_world.id}"] _(client_world_2.coordinator.adapter.lock_log).must_equal(expected_locks) plan = client_world_2.persistence.load_execution_plan(plan.id) _(plan.state).must_equal :stopped end it 'releases orphaned planning locks without execution plans' do uuid = SecureRandom.uuid client_world.coordinator.acquire Coordinator::PlanningLock.new(client_world, uuid) client_world_2.invalidate(client_world.registered_world) expected_locks = ["lock world-invalidation:#{client_world.id}", "unlock execution-plan:#{uuid}", "unlock world-invalidation:#{client_world.id}"] _(client_world_2.coordinator.adapter.lock_log).must_equal(expected_locks) end end end end describe 'auto execute' do before do client_world.persistence.delete_execution_plans({}) end it "prevents from running the auto-execution twice" do client_world.auto_execute expected_locks = ["lock auto-execute", "unlock auto-execute"] _(client_world.coordinator.adapter.lock_log).must_equal(expected_locks) lock = Coordinator::AutoExecuteLock.new(client_world) client_world.coordinator.acquire(lock) _(client_world.auto_execute).must_equal [] end it "re-runs the plans that were planned but not executed" do triggered = client_world.trigger(Support::DummyExample::Dummy) triggered.finished.wait executor_world.auto_execute plan = wait_for do plan = client_world.persistence.load_execution_plan(triggered.id) if plan.state == :stopped plan end end expected_history = [['start execution', executor_world.id], ['finish execution', executor_world.id]] _(plan.execution_history.map { |h| [h.name, h.world_id] }).must_equal(expected_history) end it "re-runs the plans that were terminated but not re-executed (because no available executor)" do executor_world # mention it to get initialized triggered = while_executing_plan { |executor| executor.terminate.wait } executor_world_2.auto_execute finish_the_plan(triggered) plan = wait_for do plan = client_world.persistence.load_execution_plan(triggered.id) if plan.state == :stopped plan end end assert_plan_reexecuted(plan) end it "doesn't rerun the plans that were paused with error" do executor_world # mention it to get initialized triggered = client_world.trigger(Support::DummyExample::FailingDummy) triggered.finished.wait retries = executor_world.auto_execute retries.each(&:wait) plan = client_world.persistence.load_execution_plan(triggered.id) _(plan.state).must_equal :paused expected_history = [['start execution', executor_world.id], ['pause execution', executor_world.id]] _(plan.execution_history.map { |h| [h.name, h.world_id] }).must_equal(expected_history) end end describe '#worlds_validity_check' do describe 'the auto_validity_check is enabled' do let :invalid_world do Coordinator::ClientWorld.new(OpenStruct.new(id: '123', meta: {})) end let :invalid_world_2 do Coordinator::ClientWorld.new(OpenStruct.new(id: '456', meta: {})) end let :client_world do create_world(false) end let :world_with_auto_validity_check do create_world do |config| config.auto_validity_check = true config.validity_check_timeout = 0.2 end end it 'performs the validity check on world creation if auto_validity_check enabled' do client_world.coordinator.register_world(invalid_world) _(client_world.coordinator.find_worlds(false, id: invalid_world.id)).wont_be_empty world_with_auto_validity_check _(client_world.coordinator.find_worlds(false, id: invalid_world.id)).must_be_empty end it 'by default, the auto_validity_check is enabled only for executor words' do client_world_config = Config::ForWorld.new(Config.new.tap { |c| c.executor = false }, create_world) _(client_world_config.auto_validity_check).must_equal false executor_world_config = Config::ForWorld.new(Config.new.tap { |c| c.executor = Executors::Parallel::Core }, create_world) _(executor_world_config.auto_validity_check).must_equal true end it 'reports the validation status' do client_world.coordinator.register_world(invalid_world) results = client_world.worlds_validity_check _(client_world.coordinator.find_worlds(false, id: invalid_world.id)).must_be_empty _(results[invalid_world.id]).must_equal :invalidated _(results[client_world.id]).must_equal :valid end it 'allows checking only, without actual invalidation' do client_world.coordinator.register_world(invalid_world) results = client_world.worlds_validity_check(false) _(client_world.coordinator.find_worlds(false, id: invalid_world.id)).wont_be_empty _(results[invalid_world.id]).must_equal :invalid end it 'allows to filter the worlds to run the check on' do client_world.coordinator.register_world(invalid_world) client_world.coordinator.register_world(invalid_world_2) _(client_world.coordinator.find_worlds(false, id: [invalid_world.id, invalid_world_2.id]).size).must_equal 2 results = client_world.worlds_validity_check(true, :id => invalid_world.id) _(results).must_equal(invalid_world.id => :invalidated) _(client_world.coordinator.find_worlds(false, id: [invalid_world.id, invalid_world_2.id]).size).must_equal 1 end end end describe '#coordinator_validity_check' do describe 'the auto_validity_check is enabled' do let :world_with_auto_validity_check do create_world do |config| config.auto_validity_check = true end end let(:invalid_lock) { Coordinator::DelayedExecutorLock.new(OpenStruct.new(:id => 'invalid-world-id')) } let(:valid_lock) { Coordinator::AutoExecuteLock.new(client_world) } def current_locks client_world.coordinator.find_locks(id: [valid_lock.id, invalid_lock.id]) end before do client_world.coordinator.acquire(valid_lock) client_world.coordinator.acquire(invalid_lock) _(current_locks).must_include(valid_lock) _(current_locks).must_include(invalid_lock) end it 'performs the validity check on world creation if auto_validity_check enabled' do world_with_auto_validity_check _(current_locks).must_include(valid_lock) _(current_locks).wont_include(invalid_lock) end it 'performs the validity check on world creation if auto_validity_check enabled' do invalid_locks = client_world.locks_validity_check _(current_locks).must_include(valid_lock) _(current_locks).wont_include(invalid_lock) _(invalid_locks).must_include(invalid_lock) _(invalid_locks).wont_include(valid_lock) end end describe 'with singleton action locks' do def plan_in_state(state) plan = executor_world.persistence.load_execution_plan(trigger_waiting_action.id) step = plan.steps.values.last wait_for do executor_world.persistence.load_step(step.execution_plan_id, step.id, executor_world).state == :suspended end plan.state = state if plan.state != state plan.save plan end let(:sample_uuid) { '11111111-2222-3333-4444-555555555555' } let(:valid_plan) { plan_in_state :running } let(:invalid_plan) { plan_in_state :stopped } let(:valid_lock) { Coordinator::SingletonActionLock.new('MyClass1', valid_plan.id) } let(:invalid_lock) { Coordinator::SingletonActionLock.new('MyClass2', sample_uuid) } let(:invalid_lock2) { Coordinator::SingletonActionLock.new('MyClass3', invalid_plan.id) } it 'unlocks orphaned singleton action locks' do executor_world client_world.coordinator.acquire(valid_lock) client_world.coordinator.acquire(invalid_lock) client_world.coordinator.acquire(invalid_lock2) invalid_locks = client_world.coordinator.clean_orphaned_locks # It must invalidate locks which are missing or in paused/stopped _(invalid_locks).must_include(invalid_lock) _(invalid_locks).must_include(invalid_lock2) _(invalid_locks).wont_include(valid_lock) end end end end end end
ruby
MIT
e14dcdfe57cec99cc78b2f6ab521f00809b1408a
2026-01-04T17:50:16.326730Z
false
Dynflow/dynflow
https://github.com/Dynflow/dynflow/blob/e14dcdfe57cec99cc78b2f6ab521f00809b1408a/test/semaphores_test.rb
test/semaphores_test.rb
# frozen_string_literal: true require_relative 'test_helper' module Dynflow module SemaphoresTest describe ::Dynflow::Semaphores::Stateful do let(:semaphore_class) { ::Dynflow::Semaphores::Stateful } let(:tickets_count) { 5 } it 'can be used as counter' do expected_state = { :tickets => tickets_count, :free => 4, :meta => {} } semaphore = semaphore_class.new(tickets_count) _(semaphore.tickets).must_equal tickets_count _(semaphore.free).must_equal tickets_count _(semaphore.waiting).must_be_empty _(semaphore.get).must_equal 1 _(semaphore.free).must_equal tickets_count - 1 _(semaphore.get(3)).must_equal 3 _(semaphore.free).must_equal tickets_count - (3 + 1) _(semaphore.drain).must_equal 1 _(semaphore.free).must_equal tickets_count - (3 + 1 + 1) semaphore.release _(semaphore.free).must_equal tickets_count - (3 + 1) semaphore.release 3 _(semaphore.free).must_equal tickets_count - 1 _(semaphore.to_hash).must_equal expected_state end it 'can have things waiting on it' do semaphore = semaphore_class.new 1 allowed = semaphore.wait(1) _(allowed).must_equal true _(semaphore.free).must_equal 0 allowed = semaphore.wait(2) _(allowed).must_equal false allowed = semaphore.wait(3) _(allowed).must_equal false waiting = semaphore.get_waiting _(waiting).must_equal 2 waiting = semaphore.get_waiting _(waiting).must_equal 3 end end describe ::Dynflow::Semaphores::Dummy do let(:semaphore_class) { ::Dynflow::Semaphores::Dummy } it 'always has free' do semaphore = semaphore_class.new _(semaphore.free).must_equal 1 _(semaphore.get(5)).must_equal 5 _(semaphore.free).must_equal 1 end it 'cannot have things waiting on it' do semaphore = semaphore_class.new _(semaphore.wait(1)).must_equal true _(semaphore.has_waiting?).must_equal false end end describe ::Dynflow::Semaphores::Aggregating do let(:semaphore_class) { ::Dynflow::Semaphores::Aggregating } let(:child_class) { ::Dynflow::Semaphores::Stateful } let(:children) do { :child_A => child_class.new(3), :child_B => child_class.new(2) } end def assert_semaphore_state(semaphore, state_a, state_b) _(semaphore.children[:child_A].free).must_equal state_a _(semaphore.children[:child_B].free).must_equal state_b _(semaphore.free).must_equal [state_a, state_b].min end it 'can be used as counter' do semaphore = semaphore_class.new(children) assert_semaphore_state semaphore, 3, 2 _(semaphore.get).must_equal 1 assert_semaphore_state semaphore, 2, 1 _(semaphore.get).must_equal 1 assert_semaphore_state semaphore, 1, 0 _(semaphore.get).must_equal 0 assert_semaphore_state semaphore, 1, 0 semaphore.release assert_semaphore_state semaphore, 2, 1 semaphore.release(1, :child_B) assert_semaphore_state semaphore, 2, 2 _(semaphore.drain).must_equal 2 assert_semaphore_state semaphore, 0, 0 end end end end
ruby
MIT
e14dcdfe57cec99cc78b2f6ab521f00809b1408a
2026-01-04T17:50:16.326730Z
false
Dynflow/dynflow
https://github.com/Dynflow/dynflow/blob/e14dcdfe57cec99cc78b2f6ab521f00809b1408a/test/batch_sub_tasks_test.rb
test/batch_sub_tasks_test.rb
# frozen_string_literal: true require_relative 'test_helper' module Dynflow module BatchSubTaskTest describe 'Batch sub-tasks' do include PlanAssertions include Dynflow::Testing::Assertions include Dynflow::Testing::Factories include TestHelpers class FailureSimulator def self.should_fail? @should_fail end def self.should_fail! @should_fail = true end def self.wont_fail! @should_fail = false end end let(:world) { WorldFactory.create_world } class ChildAction < ::Dynflow::Action def plan(should_fail = false) raise "Simulated failure" if FailureSimulator.should_fail? plan_self end def run output[:run] = true end end class ParentAction < ::Dynflow::Action include Dynflow::Action::WithSubPlans include Dynflow::Action::WithBulkSubPlans def plan(count, concurrency_level = nil, time_span = nil) limit_concurrency_level(concurrency_level) unless concurrency_level.nil? distribute_over_time(time_span, count) unless time_span.nil? plan_self :count => count end def create_sub_plans output[:batch_count] ||= 0 output[:batch_count] += 1 current_batch.map { |i| trigger(ChildAction) } end def batch(from, size) (1..total_count).to_a.slice(from, size) end def batch_size 5 end def total_count input[:count] end end it 'starts tasks in batches' do FailureSimulator.wont_fail! plan = world.plan(ParentAction, 20) future = world.execute plan.id wait_for { future.resolved? } plan = world.persistence.load_execution_plan(plan.id) action = plan.entry_action _(action.output[:batch_count]).must_equal action.total_count / action.batch_size end it 'can resume tasks' do FailureSimulator.should_fail! plan = world.plan(ParentAction, 20) future = world.execute plan.id wait_for { future.resolved? } plan = world.persistence.load_execution_plan(plan.id) action = plan.entry_action _(action.output[:batch_count]).must_equal 1 _(future.value.state).must_equal :paused FailureSimulator.wont_fail! future = world.execute plan.id wait_for { future.resolved? } action = future.value.entry_action _(future.value.state).must_equal :stopped _(action.output[:batch_count]).must_equal (action.total_count / action.batch_size) + 1 _(action.output[:total_count]).must_equal action.total_count _(action.output[:success_count]).must_equal action.total_count end it 'is controlled only by total_count and output[:planned_count]' do plan = world.plan(ParentAction, 10) future = world.execute plan.id wait_for { future.resolved? } plan = world.persistence.load_execution_plan(plan.id) action = plan.entry_action _(action.send(:can_spawn_next_batch?)).must_equal false _(action.current_batch).must_be :empty? action.output[:pending_count] = 0 action.output[:success_count] = 5 _(action.send(:can_spawn_next_batch?)).must_equal false _(action.current_batch).must_be :empty? end end end end
ruby
MIT
e14dcdfe57cec99cc78b2f6ab521f00809b1408a
2026-01-04T17:50:16.326730Z
false
Dynflow/dynflow
https://github.com/Dynflow/dynflow/blob/e14dcdfe57cec99cc78b2f6ab521f00809b1408a/test/executor_test.rb
test/executor_test.rb
# -*- coding: utf-8 -*- # frozen_string_literal: true require_relative 'test_helper' require 'mocha/minitest' require 'sidekiq' require 'sidekiq/api' require 'sidekiq/testing' ::Sidekiq::Testing::inline! require 'dynflow/executors/sidekiq/core' module RedisMocks def release_orchestrator_lock; end def wait_for_orchestrator_lock; end def reacquire_orchestrator_lock; end end ::Dynflow::Executors::Sidekiq::Core.prepend RedisMocks module Dynflow module ExecutorTest [::Dynflow::Executors::Parallel::Core, ::Dynflow::Executors::Sidekiq::Core].each do |executor| describe executor do include PlanAssertions after do ::Dynflow.instance_variable_set('@process_world', nil) end before do executor.any_instance.stubs(:begin_startup!) end let(:world) do world = WorldFactory.create_world { |c| c.executor = executor } ::Dynflow.instance_variable_set('@process_world', world) world end let :issues_data do [{ 'author' => 'Peter Smith', 'text' => 'Failing test' }, { 'author' => 'John Doe', 'text' => 'Internal server error' }] end let :failing_issues_data do [{ 'author' => 'Peter Smith', 'text' => 'Failing test' }, { 'author' => 'John Doe', 'text' => 'trolling' }] end let :finalize_failing_issues_data do [{ 'author' => 'Peter Smith', 'text' => 'Failing test' }, { 'author' => 'John Doe', 'text' => 'trolling in finalize' }] end let :failed_execution_plan do plan = world.plan(Support::CodeWorkflowExample::IncomingIssues, failing_issues_data) plan = world.execute(plan.id).value _(plan.state).must_equal :paused plan end let :finalize_failed_execution_plan do plan = world.plan(Support::CodeWorkflowExample::IncomingIssues, finalize_failing_issues_data) plan = world.execute(plan.id).value _(plan.state).must_equal :paused plan end let :persisted_plan do world.persistence.load_execution_plan(execution_plan.id) end describe "execution plan state" do describe "after successful planning" do let :execution_plan do world.plan(Support::CodeWorkflowExample::IncomingIssues, issues_data) end it "is pending" do _(execution_plan.state).must_equal :planned end describe "when finished successfully" do it "is stopped" do world.execute(execution_plan.id).value.tap do |plan| _(plan.state).must_equal :stopped end end end describe "when finished with error" do it "is paused" do world.execute(failed_execution_plan.id).value.tap do |plan| _(plan.state).must_equal :paused end end end end describe "after error in planning" do class FailingAction < Dynflow::Action def plan raise "I failed" end end let :execution_plan do world.plan(FailingAction) end it "is stopped" do _(execution_plan.state).must_equal :stopped end end describe "when being executed" do include TestHelpers let :execution_plan do world.plan(Support::CodeWorkflowExample::IncomingIssue, { 'text' => 'get a break' }) end before do TestPause.setup @execution = world.execute(execution_plan.id) end after do @execution.wait TestPause.teardown end it "is running" do TestPause.when_paused do plan = world.persistence.load_execution_plan(execution_plan.id) _(plan.state).must_equal :running triage = plan.run_steps.find do |s| s.action_class == Support::CodeWorkflowExample::Triage end _(triage.state).must_equal :running _(world.persistence.load_step(triage.execution_plan_id, triage.id, world).state).must_equal :running end end it "fails when trying to execute again" do TestPause.when_paused do assert_raises(Dynflow::Error) { world.execute(execution_plan.id).value! } end end it "handles when the execution plan is deleted" do TestPause.when_paused do world.persistence.delete_execution_plans(uuid: [execution_plan.id]) end director = get_director(world) wait_for('execution plan removed from executor') do !director.current_execution_plan_ids.include?(execution_plan.id) end _(world.persistence.find_execution_plans(filters: { uuid: [execution_plan.id] })).must_be :empty? end end end describe "execution of run flow" do before do TestExecutionLog.setup end let :result do world.execute(execution_plan.id).value! end after do TestExecutionLog.teardown end def persisted_plan result super end describe 'cancellable action' do describe 'successful' do let :execution_plan do world.plan(Support::CodeWorkflowExample::CancelableSuspended, {}) end it "doesn't cause problems" do _(result.result).must_equal :success _(result.state).must_equal :stopped end end describe 'canceled' do let :execution_plan do world.plan(Support::CodeWorkflowExample::CancelableSuspended, { text: 'cancel-self' }) end it 'cancels' do _(result.result).must_equal :success _(result.state).must_equal :stopped action = world.persistence.load_action result.steps[2] _(action.output[:task][:progress]).must_equal 30 _(action.output[:task][:cancelled]).must_equal true end end describe 'canceled failed' do let :execution_plan do world.plan(Support::CodeWorkflowExample::CancelableSuspended, { text: 'cancel-fail cancel-self' }) end it 'fails' do _(result.result).must_equal :error _(result.state).must_equal :paused step = result.steps[2] _(step.error.message).must_equal 'action cancelled' action = world.persistence.load_action step _(action.output[:task][:progress]).must_equal 30 end end end describe 'suspended action' do describe 'handling errors in setup' do let :execution_plan do world.plan(Support::DummyExample::Polling, external_task_id: '123', text: 'troll setup') end it 'fails' do assert_equal :error, result.result assert_equal :paused, result.state assert_equal :error, result.run_steps.first.state end end describe 'events' do include TestHelpers let(:clock) { Dynflow::Testing::ManagedClock.new } let :execution_plan do world.plan(Support::DummyExample::PlanEventsAction, ping_time: 0.5) end it 'handles planning events' do world.stub(:clock, clock) do world.execute(execution_plan.id) ping = wait_for do clock.pending_pings.first end assert ping.what.value.is_a?(Director::Event) clock.progress wait_for do world.persistence.load_execution_plan(execution_plan.id).result == :success end end end end describe 'running' do let :execution_plan do world.plan(Support::DummyExample::Polling, { :external_task_id => '123' }) end it "doesn't cause problems" do _(result.result).must_equal :success _(result.state).must_equal :stopped end it 'does set times' do refute_nil result.started_at refute_nil result.ended_at _(result.execution_time).must_be :<, result.real_time step_sum = result.steps.values.map(&:execution_time).reduce(:+) # Storing floats can lead to slight deviations, 1ns precision should be enough _(result.execution_time).must_be_close_to step_sum, 0.000_001 plan_step = result.steps[1] refute_nil plan_step.started_at refute_nil plan_step.ended_at _(plan_step.execution_time).must_equal plan_step.real_time run_step = result.steps[2] refute_nil run_step.started_at refute_nil run_step.ended_at _(run_step.execution_time).must_be :<, run_step.real_time end end describe 'progress' do before do TestPause.setup @running_plan = world.execute(execution_plan.id) end after do @running_plan.wait TestPause.teardown end describe 'plan with one action' do let :execution_plan do world.plan(Support::DummyExample::Polling, { external_task_id: '123', text: 'pause in progress 20%' }) end it 'determines the progress of the execution plan in percents' do TestPause.when_paused do plan = world.persistence.load_execution_plan(execution_plan.id) _(plan.progress.round(2)).must_equal 0.2 end end end describe 'plan with more action' do let :execution_plan do world.plan(Support::DummyExample::WeightedPolling, { external_task_id: '123', text: 'pause in progress 20%' }) end it 'takes the steps weight in account' do TestPause.when_paused do plan = world.persistence.load_execution_plan(execution_plan.id) _(plan.progress.round(2)).must_equal 0.42 end end end end describe 'works when resumed after error' do let :execution_plan do world.plan(Support::DummyExample::Polling, { external_task_id: '123', text: 'troll progress' }) end specify do assert_equal :paused, result.state assert_equal :error, result.result assert_equal :error, result.run_steps.first.state ep = world.execute(result.id).value assert_equal :stopped, ep.state assert_equal :success, ep.result assert_equal :success, ep.run_steps.first.state end end end describe "action with empty flows" do let :execution_plan do world.plan(Support::CodeWorkflowExample::Dummy, { :text => "dummy" }).tap do |plan| assert_equal plan.run_flow.size, 0 assert_equal plan.finalize_flow.size, 0 end.tap do |w| w end end it "doesn't cause problems" do _(result.result).must_equal :success _(result.state).must_equal :stopped end it 'will not run again' do world.execute(execution_plan.id) assert_raises(Dynflow::Error) { world.execute(execution_plan.id).value! } end end describe 'action with empty run flow but some finalize flow' do let :execution_plan do world.plan(Support::CodeWorkflowExample::DummyWithFinalize, { :text => "dummy" }).tap do |plan| assert_equal plan.run_flow.size, 0 assert_equal plan.finalize_flow.size, 1 end end it "doesn't cause problems" do _(result.result).must_equal :success _(result.state).must_equal :stopped end end describe 'running' do let :execution_plan do world.plan(Support::CodeWorkflowExample::IncomingIssues, issues_data) end it "runs all the steps in the run flow" do assert_run_flow <<-EXECUTED_RUN_FLOW, persisted_plan Dynflow::Flows::Concurrence Dynflow::Flows::Sequence 4: Triage(success) {"author"=>"Peter Smith", "text"=>"Failing test"} --> {"classification"=>{"assignee"=>"John Doe", "severity"=>"medium"}} 7: UpdateIssue(success) {"author"=>"Peter Smith", "text"=>"Failing test", "assignee"=>"John Doe", "severity"=>"medium"} --> {} 9: NotifyAssignee(success) {"triage"=>{"classification"=>{"assignee"=>"John Doe", "severity"=>"medium"}}} --> {} Dynflow::Flows::Sequence 13: Triage(success) {"author"=>"John Doe", "text"=>"Internal server error"} --> {"classification"=>{"assignee"=>"John Doe", "severity"=>"medium"}} 16: UpdateIssue(success) {"author"=>"John Doe", "text"=>"Internal server error", "assignee"=>"John Doe", "severity"=>"medium"} --> {} 18: NotifyAssignee(success) {"triage"=>{"classification"=>{"assignee"=>"John Doe", "severity"=>"medium"}}} --> {} EXECUTED_RUN_FLOW end end end describe "execution of finalize flow" do before do TestExecutionLog.setup result = world.execute(execution_plan.id).value raise result if result.is_a? Exception end after do TestExecutionLog.teardown end describe "when run flow successful" do let :execution_plan do world.plan(Support::CodeWorkflowExample::IncomingIssues, issues_data) end it "runs all the steps in the finalize flow" do assert_finalized(Support::CodeWorkflowExample::IncomingIssues, { "issues" => [{ "author" => "Peter Smith", "text" => "Failing test" }, { "author" => "John Doe", "text" => "Internal server error" }] }) assert_finalized(Support::CodeWorkflowExample::Triage, { "author" => "Peter Smith", "text" => "Failing test" }) end end describe "when run flow failed" do let :execution_plan do failed_execution_plan end it "doesn't run the steps in the finalize flow" do _(TestExecutionLog.finalize.size).must_equal 0 end end end describe "re-execution of run flow after fix in run phase" do after do TestExecutionLog.teardown end let :resumed_execution_plan do failed_step = failed_execution_plan.steps.values.find do |step| step.state == :error end world.persistence.load_action(failed_step).tap do |action| action.input[:text] = "ok" world.persistence.save_action(failed_step.execution_plan_id, action) end TestExecutionLog.setup world.execute(failed_execution_plan.id).value end it "runs all the steps in the run flow" do _(resumed_execution_plan.state).must_equal :stopped _(resumed_execution_plan.result).must_equal :success run_triages = TestExecutionLog.run.find_all do |action_class, input| action_class == Support::CodeWorkflowExample::Triage end _(run_triages.size).must_equal 1 assert_run_flow <<-EXECUTED_RUN_FLOW, resumed_execution_plan Dynflow::Flows::Concurrence Dynflow::Flows::Sequence 4: Triage(success) {\"author\"=>\"Peter Smith\", \"text\"=>\"Failing test\"} --> {\"classification\"=>{\"assignee\"=>\"John Doe\", \"severity\"=>\"medium\"}} 7: UpdateIssue(success) {\"author\"=>\"Peter Smith\", \"text\"=>\"Failing test\", \"assignee\"=>\"John Doe\", \"severity\"=>\"medium\"} --> {} 9: NotifyAssignee(success) {\"triage\"=>{\"classification\"=>{\"assignee\"=>\"John Doe\", \"severity\"=>\"medium\"}}} --> {} Dynflow::Flows::Sequence 13: Triage(success) {\"author\"=>\"John Doe\", \"text\"=>\"ok\"} --> {\"classification\"=>{\"assignee\"=>\"John Doe\", \"severity\"=>\"medium\"}} 16: UpdateIssue(success) {\"author\"=>\"John Doe\", \"text\"=>\"trolling\", \"assignee\"=>\"John Doe\", \"severity\"=>\"medium\"} --> {} 18: NotifyAssignee(success) {\"triage\"=>{\"classification\"=>{\"assignee\"=>\"John Doe\", \"severity\"=>\"medium\"}}} --> {} EXECUTED_RUN_FLOW end end describe "re-execution of run flow after fix in finalize phase" do after do TestExecutionLog.teardown end let :resumed_execution_plan do failed_step = finalize_failed_execution_plan.steps.values.find do |step| step.state == :error end world.persistence.load_action(failed_step).tap do |action| action.input[:text] = "ok" world.persistence.save_action(failed_step.execution_plan_id, action) end TestExecutionLog.setup world.execute(finalize_failed_execution_plan.id).value end it "runs all the steps in the finalize flow" do _(resumed_execution_plan.state).must_equal :stopped _(resumed_execution_plan.result).must_equal :success run_triages = TestExecutionLog.finalize.find_all do |action_class, input| action_class == Support::CodeWorkflowExample::Triage end _(run_triages.size).must_equal 2 assert_finalize_flow <<-EXECUTED_RUN_FLOW, resumed_execution_plan Dynflow::Flows::Sequence 5: Triage(success) {\"author\"=>\"Peter Smith\", \"text\"=>\"Failing test\"} --> {\"classification\"=>{\"assignee\"=>\"John Doe\", \"severity\"=>\"medium\"}} 10: NotifyAssignee(success) {\"triage\"=>{\"classification\"=>{\"assignee\"=>\"John Doe\", \"severity\"=>\"medium\"}}} --> {} 14: Triage(success) {\"author\"=>\"John Doe\", \"text\"=>\"ok\"} --> {\"classification\"=>{\"assignee\"=>\"John Doe\", \"severity\"=>\"medium\"}} 19: NotifyAssignee(success) {\"triage\"=>{\"classification\"=>{\"assignee\"=>\"John Doe\", \"severity\"=>\"medium\"}}} --> {} 20: IncomingIssues(success) {\"issues\"=>[{\"author\"=>\"Peter Smith\", \"text\"=>\"Failing test\"}, {\"author\"=>\"John Doe\", \"text\"=>\"trolling in finalize\"}]} --> {} EXECUTED_RUN_FLOW end end describe "re-execution of run flow after skipping" do after do TestExecutionLog.teardown end let :resumed_execution_plan do failed_step = failed_execution_plan.steps.values.find do |step| step.state == :error end failed_execution_plan.skip(failed_step) TestExecutionLog.setup world.execute(failed_execution_plan.id).value end it "runs all pending steps except skipped" do _(resumed_execution_plan.state).must_equal :stopped _(resumed_execution_plan.result).must_equal :warning run_triages = TestExecutionLog.run.find_all do |action_class, input| action_class == Support::CodeWorkflowExample::Triage end _(run_triages.size).must_equal 0 assert_run_flow <<-EXECUTED_RUN_FLOW, resumed_execution_plan Dynflow::Flows::Concurrence Dynflow::Flows::Sequence 4: Triage(success) {\"author\"=>\"Peter Smith\", \"text\"=>\"Failing test\"} --> {\"classification\"=>{\"assignee\"=>\"John Doe\", \"severity\"=>\"medium\"}} 7: UpdateIssue(success) {\"author\"=>\"Peter Smith\", \"text\"=>\"Failing test\", \"assignee\"=>\"John Doe\", \"severity\"=>\"medium\"} --> {} 9: NotifyAssignee(success) {\"triage\"=>{\"classification\"=>{\"assignee\"=>\"John Doe\", \"severity\"=>\"medium\"}}} --> {} Dynflow::Flows::Sequence 13: Triage(skipped) {\"author\"=>\"John Doe\", \"text\"=>\"trolling\"} --> {} 16: UpdateIssue(skipped) {\"author\"=>\"John Doe\", \"text\"=>\"trolling\", \"assignee\"=>Step(13).output[:classification][:assignee], \"severity\"=>Step(13).output[:classification][:severity]} --> {} 18: NotifyAssignee(skipped) {\"triage\"=>Step(13).output} --> {} EXECUTED_RUN_FLOW assert_finalize_flow <<-FINALIZE_FLOW, resumed_execution_plan Dynflow::Flows::Sequence 5: Triage(success) {\"author\"=>\"Peter Smith\", \"text\"=>\"Failing test\"} --> {\"classification\"=>{\"assignee\"=>\"John Doe\", \"severity\"=>\"medium\"}} 10: NotifyAssignee(success) {\"triage\"=>{\"classification\"=>{\"assignee\"=>\"John Doe\", \"severity\"=>\"medium\"}}} --> {} 14: Triage(skipped) {\"author\"=>\"John Doe\", \"text\"=>\"trolling\"} --> {} 19: NotifyAssignee(skipped) {\"triage\"=>Step(13).output} --> {} 20: IncomingIssues(success) {\"issues\"=>[{\"author\"=>\"Peter Smith\", \"text\"=>\"Failing test\"}, {\"author\"=>\"John Doe\", \"text\"=>\"trolling\"}]} --> {} FINALIZE_FLOW end end describe 'FlowManager' do let :execution_plan do world.plan(Support::CodeWorkflowExample::IncomingIssues, issues_data) end let(:manager) { Director::FlowManager.new execution_plan, execution_plan.run_flow } def assert_next_steps(expected_next_step_ids, finished_step_id = nil, success = true) if finished_step_id step = manager.execution_plan.steps[finished_step_id] next_steps = manager.cursor_index[step.id].what_is_next(step, success) else next_steps = manager.start end next_step_ids = next_steps.map(&:id) assert_equal Set.new(expected_next_step_ids), Set.new(next_step_ids) end describe 'what_is_next' do it 'returns next steps after required steps were finished' do assert_next_steps([4, 13]) assert_next_steps([7], 4) assert_next_steps([9], 7) assert_next_steps([], 9) assert_next_steps([16], 13) assert_next_steps([18], 16) assert_next_steps([], 18) assert manager.done? end end describe 'what_is_next with errors' do it "doesn't return next steps if requirements failed" do assert_next_steps([4, 13]) assert_next_steps([], 4, false) end it "is not done while other steps can be finished" do assert_next_steps([4, 13]) assert_next_steps([], 4, false) assert !manager.done? assert_next_steps([], 13, false) assert manager.done? end end end describe 'Pool::JobStorage' do FakeStep ||= Struct.new(:execution_plan_id) let(:storage) { Dynflow::Executors::Parallel::Pool::JobStorage.new } it do _(storage).must_be_empty _(storage.queue_size).must_equal(0) assert_nil storage.pop assert_nil storage.pop storage.add s = FakeStep.new(1) _(storage.queue_size).must_equal(1) _(storage.pop).must_equal s _(storage).must_be_empty assert_nil storage.pop storage.add s11 = FakeStep.new(1) storage.add s12 = FakeStep.new(1) storage.add s13 = FakeStep.new(1) storage.add s21 = FakeStep.new(2) storage.add s22 = FakeStep.new(2) storage.add s31 = FakeStep.new(3) _(storage.queue_size(1)).must_equal(3) _(storage.queue_size(4)).must_equal(0) _(storage.queue_size).must_equal(6) _(storage.pop).must_equal s11 _(storage.pop).must_equal s12 _(storage.pop).must_equal s13 _(storage.pop).must_equal s21 _(storage.pop).must_equal s22 _(storage.pop).must_equal s31 _(storage).must_be_empty _(storage.queue_size).must_equal(0) assert_nil storage.pop end end end describe 'termination' do let(:world) { WorldFactory.create_world } it 'waits for currently running actions' do $slow_actions_done = 0 running = world.trigger(Support::DummyExample::Slow, 1) suspended = world.trigger(Support::DummyExample::DeprecatedEventedAction, :timeout => 3) sleep 0.2 world.terminate.wait _($slow_actions_done).must_equal 1 [running, suspended].each do |triggered| plan = world.persistence.load_execution_plan(triggered.id) _(plan.state).must_equal :paused _(plan.result).must_equal :pending end end describe 'before_termination hooks' do it 'runs before temination hooks' do hook_run = false world.before_termination { hook_run = true } world.terminate.wait assert hook_run end it 'continues when some hook fails' do run_hooks, failed_hooks = [], [] world.before_termination { run_hooks << 1 } world.before_termination { run_hooks << 2; failed_hooks << 2; raise 'error' } world.before_termination { run_hooks << 3 } world.terminate.wait _(run_hooks).must_equal [1, 2, 3] _(failed_hooks).must_equal [2] end end it 'does not accept new work' do assert world.terminate.wait ::Dynflow::Coordinator::PlanningLock.any_instance.stubs(:validate!) result = world.trigger(Support::DummyExample::Slow, 0.02) _(result).must_be :planned? result.finished.wait assert result.finished.rejected? _(result.finished.reason).must_be_kind_of Concurrent::Actor::ActorTerminated end it 'it terminates when no work right after initialization' do assert world.terminate.wait end it 'second terminate works' do assert world.terminate.wait assert world.terminate.wait end it 'second terminate works concurrently' do assert [world.terminate, world.terminate].map(&:value).all? end end describe 'halting' do include TestHelpers let(:world) { WorldFactory.create_world } it 'halts an execution plan with a suspended step' do triggered = world.trigger(Support::DummyExample::PlanEventsAction, ping_time: 1) plan = world.persistence.load_execution_plan(triggered.id) wait_for do plan = world.persistence.load_execution_plan(triggered.id) plan.state == :running end world.halt(triggered.id) wait_for('the execution plan to halt') do plan = world.persistence.load_execution_plan(triggered.id) plan.state == :stopped end _(plan.steps[2].state).must_equal :suspended end it 'halts a paused execution plan' do triggered = world.trigger(Support::DummyExample::FailingDummy) plan = world.persistence.load_execution_plan(triggered.id) wait_for do plan = world.persistence.load_execution_plan(triggered.id) plan.state == :paused end world.halt(plan.id) wait_for('the execution plan to halt') do plan = world.persistence.load_execution_plan(triggered.id) plan.state == :stopped end _(plan.steps[2].state).must_equal :error end it 'halts a planned execution plan' do plan = world.plan(Support::DummyExample::Dummy) wait_for do plan = world.persistence.load_execution_plan(plan.id) plan.state == :planned end world.halt(plan.id) wait_for('the execution plan to halt') do plan = world.persistence.load_execution_plan(plan.id) plan.state == :stopped end _(plan.steps[2].state).must_equal :pending end it 'halts a scheduled execution plan' do plan = world.delay(Support::DummyExample::Dummy, { start_at: Time.now + 120 }) wait_for do plan = world.persistence.load_execution_plan(plan.id) plan.state == :scheduled end world.halt(plan.id) wait_for('the execution plan to halt') do plan = world.persistence.load_execution_plan(plan.id) plan.state == :stopped end _(plan.delay_record).must_be :nil? _(plan.steps[1].state).must_equal :pending end it 'halts a pending execution plan' do plan = ExecutionPlan.new(world, nil) plan.save world.halt(plan.id) wait_for('the execution plan to halt') do plan = world.persistence.load_execution_plan(plan.id) plan.state == :stopped end end end describe 'execution inhibition locks' do include TestHelpers let(:world) { WorldFactory.create_world } it 'inhibits execution' do plan = world.plan(Support::DummyExample::Dummy) world.coordinator.acquire(Coordinator::ExecutionInhibitionLock.new(plan.id)) triggered = world.execute(plan.id) triggered.wait _(triggered).must_be :rejected? plan = world.persistence.load_execution_plan(plan.id) _(plan.state).must_equal :stopped locks = world.coordinator.find_locks({ class: Coordinator::ExecutionInhibitionLock.to_s, owner_id: "execution-plan:#{plan.id}" }) _(locks).must_be :empty? end end end end end
ruby
MIT
e14dcdfe57cec99cc78b2f6ab521f00809b1408a
2026-01-04T17:50:16.326730Z
false
Dynflow/dynflow
https://github.com/Dynflow/dynflow/blob/e14dcdfe57cec99cc78b2f6ab521f00809b1408a/test/execution_plan_test.rb
test/execution_plan_test.rb
# frozen_string_literal: true require_relative 'test_helper' module Dynflow module ExecutionPlanTest describe ExecutionPlan do include PlanAssertions let(:world) { WorldFactory.create_world } let :issues_data do [{ 'author' => 'Peter Smith', 'text' => 'Failing test' }, { 'author' => 'John Doe', 'text' => 'Internal server error' }] end describe 'serialization' do let :execution_plan do world.plan(Support::CodeWorkflowExample::FastCommit, 'sha' => 'abc123') end let :deserialized_execution_plan do world.persistence.load_execution_plan(execution_plan.id) end describe 'serialized execution plan' do before { execution_plan.save } after { world.persistence.delete_execution_plans(:uuid => execution_plan.id) } it 'restores the plan properly' do assert deserialized_execution_plan.valid? _(deserialized_execution_plan.id).must_equal execution_plan.id _(deserialized_execution_plan.label).must_equal execution_plan.label assert_steps_equal execution_plan.root_plan_step, deserialized_execution_plan.root_plan_step assert_equal execution_plan.steps.keys, deserialized_execution_plan.steps.keys deserialized_execution_plan.steps.each do |id, step| assert_steps_equal(step, execution_plan.steps[id]) end assert_run_flow_equal execution_plan, deserialized_execution_plan end it 'handles issues with loading the data' do world.persistence.adapter.send(:table, :step) .where(execution_plan_uuid: execution_plan.id).delete refute deserialized_execution_plan.valid? assert_equal Dynflow::Errors::DataConsistencyError, deserialized_execution_plan.exception.class [:label, :state, :started_at, :ended_at].each do |attr| assert_equal execution_plan.send(attr).to_s, deserialized_execution_plan.send(attr).to_s, "invalid plan is supposed to still store #{attr}" end [:execution_time, :real_time].each do |attr| assert_equal execution_plan.send(attr).to_f, deserialized_execution_plan.send(attr).to_f, "invalid plan is supposed to still store #{attr}" end assert_equal execution_plan.execution_history.events, deserialized_execution_plan.execution_history.events, "invalid plan is supposed to still store execution history" end end end describe '#label' do let :execution_plan do world.plan(Support::CodeWorkflowExample::FastCommit, 'sha' => 'abc123') end let :dummy_execution_plan do world.plan(Support::CodeWorkflowExample::Dummy) end it 'is determined by the action#label method of entry action' do _(execution_plan.label).must_equal 'Support::CodeWorkflowExample::FastCommit' _(dummy_execution_plan.label).must_equal 'dummy_action' end end describe '#result' do let :execution_plan do world.plan(Support::CodeWorkflowExample::FastCommit, 'sha' => 'abc123') end describe 'for error in planning phase' do before { execution_plan.steps[2].set_state :error, true } it 'should be :error' do _(execution_plan.result).must_equal :error _(execution_plan.error?).must_equal true end end describe 'for error in running phase' do before do step_id = execution_plan.run_flow.all_step_ids[2] execution_plan.steps[step_id].set_state :error, true end it 'should be :error' do _(execution_plan.result).must_equal :error end end describe 'for pending step in running phase' do before do step_id = execution_plan.run_flow.all_step_ids[2] execution_plan.steps[step_id].set_state :pending, true end it 'should be :pending' do _(execution_plan.result).must_equal :pending end end describe 'for all steps successful or skipped' do before do execution_plan.run_flow.all_step_ids.each_with_index do |step_id, index| step = execution_plan.steps[step_id] step.set_state (index == 2) ? :skipped : :success, true end end it 'should be :warning' do _(execution_plan.result).must_equal :warning end end end describe 'sub plans' do let(:execution_plan) do world.plan(Support::CodeWorkflowExample::IncomingIssues, issues_data) end it 'does not have itself as a sub plan' do assert execution_plan.actions.count >= 2 _(execution_plan.sub_plans).must_be :empty? end end describe 'plan steps' do let :execution_plan do world.plan(Support::CodeWorkflowExample::IncomingIssues, issues_data) end it 'stores the information about the sub actions' do assert_plan_steps <<-PLAN_STEPS, execution_plan IncomingIssues IncomingIssue Triage UpdateIssue NotifyAssignee IncomingIssue Triage UpdateIssue NotifyAssignee PLAN_STEPS end end describe 'persisted action' do let :execution_plan do world.plan(Support::CodeWorkflowExample::IncomingIssues, issues_data) end let :action do step = execution_plan.steps[4] world.persistence.load_action(step) end it 'stores the ids for plan, run and finalize steps' do _(action.plan_step_id).must_equal 3 _(action.run_step_id).must_equal 4 _(action.finalize_step_id).must_equal 5 end end describe 'custom plan id' do let(:sample_uuid) { '60366107-9910-4815-a6c6-bc45ee2ea2b8' } let :execution_plan do world.plan_with_options(action_class: Support::CodeWorkflowExample::IncomingIssues, args: [issues_data], id: sample_uuid) end it 'allows setting custom id for the execution plan' do _(execution_plan.id).must_equal sample_uuid end end describe 'planning algorithm' do describe 'single dependencies' do let :execution_plan do world.plan(Support::CodeWorkflowExample::IncomingIssues, issues_data) end it 'constructs the plan of actions to be executed in run phase' do assert_run_flow <<-RUN_FLOW, execution_plan Dynflow::Flows::Concurrence Dynflow::Flows::Sequence 4: Triage(pending) {"author"=>"Peter Smith", "text"=>"Failing test"} 7: UpdateIssue(pending) {"author"=>"Peter Smith", "text"=>"Failing test", "assignee"=>Step(4).output[:classification][:assignee], "severity"=>Step(4).output[:classification][:severity]} 9: NotifyAssignee(pending) {"triage"=>Step(4).output} Dynflow::Flows::Sequence 13: Triage(pending) {"author"=>"John Doe", "text"=>"Internal server error"} 16: UpdateIssue(pending) {"author"=>"John Doe", "text"=>"Internal server error", "assignee"=>Step(13).output[:classification][:assignee], "severity"=>Step(13).output[:classification][:severity]} 18: NotifyAssignee(pending) {"triage"=>Step(13).output} RUN_FLOW end end describe 'error in planning phase' do let :execution_plan do world.plan(Support::CodeWorkflowExample::IncomingIssues, [:fail] + issues_data) end it 'stops the planning right after the first error occurred' do _(execution_plan.steps.size).must_equal 2 end end describe 'multi dependencies' do let :execution_plan do world.plan(Support::CodeWorkflowExample::Commit, 'sha' => 'abc123') end it 'constructs the plan of actions to be executed in run phase' do assert_run_flow <<-RUN_FLOW, execution_plan Dynflow::Flows::Sequence Dynflow::Flows::Concurrence 3: Ci(pending) {"commit"=>{"sha"=>"abc123"}} 5: Review(pending) {"commit"=>{"sha"=>"abc123"}, "reviewer"=>"Morfeus", "result"=>true} 7: Review(pending) {"commit"=>{"sha"=>"abc123"}, "reviewer"=>"Neo", "result"=>true} 9: Merge(pending) {"commit"=>{"sha"=>"abc123"}, "ci_result"=>Step(3).output[:passed], "review_results"=>[Step(5).output[:passed], Step(7).output[:passed]]} RUN_FLOW end end describe 'sequence and concurrence keyword used' do let :execution_plan do world.plan(Support::CodeWorkflowExample::FastCommit, 'sha' => 'abc123') end it 'constructs the plan of actions to be executed in run phase' do assert_run_flow <<-RUN_FLOW, execution_plan Dynflow::Flows::Sequence Dynflow::Flows::Concurrence 3: Ci(pending) {"commit"=>{"sha"=>"abc123"}} 5: Review(pending) {"commit"=>{"sha"=>"abc123"}, "reviewer"=>"Morfeus", "result"=>true} 7: Merge(pending) {"commit"=>{"sha"=>"abc123"}, "ci_result"=>Step(3).output[:passed], "review_results"=>[Step(5).output[:passed]]} RUN_FLOW end end describe 'subscribed action' do let :execution_plan do world.plan(Support::CodeWorkflowExample::DummyTrigger, {}) end it 'constructs the plan of actions to be executed in run phase' do assert_run_flow <<-RUN_FLOW, execution_plan Dynflow::Flows::Concurrence 3: DummySubscribe(pending) {} 5: DummyMultiSubscribe(pending) {} RUN_FLOW end end describe 'finalize flow' do let :execution_plan do world.plan(Support::CodeWorkflowExample::IncomingIssues, issues_data) end it 'plans the finalize steps in a sequence' do assert_finalize_flow <<-RUN_FLOW, execution_plan Dynflow::Flows::Sequence 5: Triage(pending) {\"author\"=>\"Peter Smith\", \"text\"=>\"Failing test\"} 10: NotifyAssignee(pending) {\"triage\"=>Step(4).output} 14: Triage(pending) {\"author\"=>\"John Doe\", \"text\"=>\"Internal server error\"} 19: NotifyAssignee(pending) {\"triage\"=>Step(13).output} 20: IncomingIssues(pending) {\"issues\"=>[{\"author\"=>\"Peter Smith\", \"text\"=>\"Failing test\"}, {\"author\"=>\"John Doe\", \"text\"=>\"Internal server error\"}]} RUN_FLOW end end end describe '#cancel' do include TestHelpers let :execution_plan do world.plan(Support::CodeWorkflowExample::CancelableSuspended, { text: 'cancel-external' }) end it 'cancels' do finished = world.execute(execution_plan.id) plan = wait_for do plan = world.persistence.load_execution_plan(execution_plan.id) if plan.cancellable? plan end end cancel_events = plan.cancel _(cancel_events.size).must_equal 1 cancel_events.each(&:wait) finished.wait end it 'force cancels' do finished = world.execute(execution_plan.id) plan = wait_for do plan = world.persistence.load_execution_plan(execution_plan.id) if plan.cancellable? plan end end cancel_events = plan.cancel true _(cancel_events.size).must_equal 1 cancel_events.each(&:wait) finished.wait end end describe 'accessing actions results' do let :execution_plan do world.plan(Support::CodeWorkflowExample::IncomingIssues, issues_data) end it 'provides the access to the actions data via steps #action' do _(execution_plan.steps.size).must_equal 20 execution_plan.steps.each do |_, step| _(step.action(execution_plan).phase).must_equal Action::Present end end end describe ExecutionPlan::Steps::Error do it "doesn't fail when deserializing with missing class" do error = ExecutionPlan::Steps::Error.new_from_hash(exception_class: "RenamedError", message: "This errror is not longer here", backtrace: []) _(error.exception_class.name).must_equal "RenamedError" _(error.exception_class.to_s).must_equal "Dynflow::Errors::UnknownError[RenamedError]" _(error.exception.inspect).must_equal "Dynflow::Errors::UnknownError[RenamedError]: This errror is not longer here" end end describe 'with singleton actions' do class SingletonAction < ::Dynflow::Action include ::Dynflow::Action::Singleton def run if input[:fail] raise "Controlled Failure" end end end it 'unlocks the locks on transition to stopped' do plan = world.plan(SingletonAction) _(plan.state).must_equal :planned lock_filter = ::Dynflow::Coordinator::SingletonActionLock .unique_filter plan.entry_action.class.name _(world.coordinator.find_locks(lock_filter).count).must_equal 1 plan = world.execute(plan.id).wait!.value _(plan.state).must_equal :stopped _(plan.result).must_equal :success _(world.coordinator.find_locks(lock_filter).count).must_equal 0 end it 'unlocks the locks on transition to paused' do plan = world.plan(SingletonAction, :fail => true) _(plan.state).must_equal :planned lock_filter = ::Dynflow::Coordinator::SingletonActionLock .unique_filter plan.entry_action.class.name _(world.coordinator.find_locks(lock_filter).count).must_equal 1 plan = world.execute(plan.id).wait!.value _(plan.state).must_equal :paused _(plan.result).must_equal :error _(world.coordinator.find_locks(lock_filter).count).must_equal 0 end end end end end
ruby
MIT
e14dcdfe57cec99cc78b2f6ab521f00809b1408a
2026-01-04T17:50:16.326730Z
false
Dynflow/dynflow
https://github.com/Dynflow/dynflow/blob/e14dcdfe57cec99cc78b2f6ab521f00809b1408a/test/action_test.rb
test/action_test.rb
# frozen_string_literal: true require_relative 'test_helper' require 'mocha/minitest' module Dynflow describe 'action' do let(:world) { WorldFactory.create_world } describe Action::Missing do let :action_data do { class: 'RenamedAction', id: 1, input: {}, output: {}, execution_plan_id: '123', plan_step_id: 2, run_step_id: 3, finalize_step_id: nil, phase: Action::Run } end subject do step = ExecutionPlan::Steps::Abstract.allocate step.set_state :success, true Action.from_hash(action_data.merge(step: step), world) end specify { _(subject.class.name).must_equal 'RenamedAction' } specify { assert subject.is_a? Action } end describe 'children' do smart_action_class = Class.new(Dynflow::Action) smarter_action_class = Class.new(smart_action_class) specify { _(smart_action_class.all_children).must_include smarter_action_class } specify { _(smart_action_class.all_children.size).must_equal 1 } describe 'World#subscribed_actions' do event_action_class = Support::CodeWorkflowExample::Triage subscribed_action_class = Support::CodeWorkflowExample::NotifyAssignee specify { _(subscribed_action_class.subscribe).must_equal event_action_class } specify { _(world.subscribed_actions(event_action_class)).must_include subscribed_action_class } specify { _(world.subscribed_actions(event_action_class).size).must_equal 1 } end end describe Action::Present do let :execution_plan do result = world.trigger(Support::CodeWorkflowExample::IncomingIssues, issues_data) _(result).must_be :planned? result.finished.value end let :issues_data do [{ 'author' => 'Peter Smith', 'text' => 'Failing test' }, { 'author' => 'John Doe', 'text' => 'Internal server error' }] end let :presenter do execution_plan.root_plan_step.action execution_plan end specify { _(presenter.class).must_equal Support::CodeWorkflowExample::IncomingIssues } it 'allows aggregating data from other actions' do _(presenter.summary).must_equal(assignees: ["John Doe"]) end end describe 'serialization' do include Testing it 'fails when input is not serializable' do klass = Class.new(Dynflow::Action) _(-> { create_and_plan_action klass, key: Object.new }).must_raise NoMethodError end it 'fails when output is not serializable' do klass = Class.new(Dynflow::Action) do def run output.update key: Object.new end end action = create_and_plan_action klass, {} _(-> { run_action action }).must_raise NoMethodError end end describe '#humanized_state' do include Testing class ActionWithHumanizedState < Dynflow::Action def run(event = nil) suspend unless event end def humanized_state case state when :suspended "waiting" else super end end end it 'is customizable from an action' do plan = create_and_plan_action ActionWithHumanizedState, {} action = run_action(plan) _(action.humanized_state).must_equal "waiting" end end describe 'evented action' do include Testing class PlanEventedAction < Dynflow::Action def run(event = nil) case event when "ping" output[:status] = 'pinged' when nil plan_event('ping', input[:time]) suspend else self.output[:event] = event end end end it 'send planned event' do plan = create_and_plan_action(PlanEventedAction, { time: 0.5 }) action = run_action plan assert_nil action.output[:status] _(action.world.clock.pending_pings.first).wont_be_nil _(action.state).must_equal :suspended progress_action_time action _(action.output[:status]).must_equal 'pinged' _(action.world.clock.pending_pings.first).must_be_nil _(action.state).must_equal :success end it 'plans event immediately if no time is given' do plan = create_and_plan_action(PlanEventedAction, { time: nil }) action = run_action plan assert_nil action.output[:status] _(action.world.clock.pending_pings.first).must_be_nil _(action.world.executor.events_to_process.first).wont_be_nil _(action.state).must_equal :suspended action.world.executor.progress _(action.output[:status]).must_equal 'pinged' _(action.world.clock.pending_pings.first).must_be_nil _(action.state).must_equal :success end end describe 'polling action' do CWE = Support::CodeWorkflowExample include Dynflow::Testing class ExternalService def invoke(args) reset! end def poll(id) raise 'fail' if @current_state[:failing] @current_state[:progress] += 10 return @current_state end def reset! @current_state = { task_id: 123, progress: 0 } end def will_fail @current_state[:failing] = true end def wont_fail @current_state.delete(:failing) end end class TestPollingAction < Dynflow::Action class Config attr_accessor :external_service, :poll_max_retries, :poll_intervals, :attempts_before_next_interval def initialize @external_service = ExternalService.new @poll_max_retries = 2 @poll_intervals = [0.5, 1] @attempts_before_next_interval = 2 end end include Dynflow::Action::Polling def invoke_external_task external_service.invoke(input[:task_args]) end def poll_external_task external_service.poll(external_task[:task_id]) end def done? external_task && external_task[:progress] >= 100 end def poll_max_retries self.class.config.poll_max_retries end def poll_intervals self.class.config.poll_intervals end def attempts_before_next_interval self.class.config.attempts_before_next_interval end class << self def config @config ||= Config.new end attr_writer :config end def external_service self.class.config.external_service end end class NonRunningExternalService < ExternalService def poll(id) return { message: 'nothing changed' } end end class TestTimeoutAction < TestPollingAction class Config < TestPollingAction::Config def initialize super @external_service = NonRunningExternalService.new end end def done? self.state == :error end def invoke_external_task schedule_timeout(5) super end end describe 'without timeout' do let(:plan) do create_and_plan_action TestPollingAction, { task_args: 'do something' } end before do TestPollingAction.config = TestPollingAction::Config.new end def next_ping(action) action.world.clock.pending_pings.first end it 'initiates the external task' do action = run_action plan _(action.output[:task][:task_id]).must_equal 123 end it 'polls till the task is done' do action = run_action plan 9.times { progress_action_time action } _(action.done?).must_equal false _(next_ping(action)).wont_be_nil _(action.state).must_equal :suspended progress_action_time action _(action.done?).must_equal true _(next_ping(action)).must_be_nil _(action.state).must_equal :success end it 'tries to poll for the old task when resuming' do action = run_action plan _(action.output[:task][:progress]).must_equal 0 run_action action _(action.output[:task][:progress]).must_equal 10 end it 'invokes the external task again when polling on the old one fails' do action = run_action plan action.world.silence_logger! action.external_service.will_fail _(action.output[:task][:progress]).must_equal 0 run_action action _(action.output[:task][:progress]).must_equal 0 end it 'tolerates some failure while polling' do action = run_action plan action.external_service.will_fail action.world.silence_logger! TestPollingAction.config.poll_max_retries = 3 (1..2).each do |attempt| progress_action_time action _(action.poll_attempts[:failed]).must_equal attempt _(next_ping(action)).wont_be_nil _(action.state).must_equal :suspended end progress_action_time action _(action.poll_attempts[:failed]).must_equal 3 _(next_ping(action)).must_be_nil _(action.state).must_equal :error end it 'allows increasing poll interval in a time' do TestPollingAction.config.poll_intervals = [1, 2] TestPollingAction.config.attempts_before_next_interval = 2 action = run_action plan pings = [] pings << next_ping(action) progress_action_time action pings << next_ping(action) progress_action_time action pings << next_ping(action) progress_action_time action _((pings[1].when - pings[0].when)).must_be_close_to 1 _((pings[2].when - pings[1].when)).must_be_close_to 2 end end describe 'with timeout' do let(:plan) do create_and_plan_action TestTimeoutAction, { task_args: 'do something' } end before do TestTimeoutAction.config = TestTimeoutAction::Config.new TestTimeoutAction.config.poll_intervals = [2] end it 'timesout' do action = run_action plan iterations = 0 while progress_action_time action # we count the number of iterations till the timeout occurs iterations += 1 end _(action.state).must_equal :error # two polls in 2 seconds intervals untill the 5 seconds # timeout appears _(iterations).must_equal 3 end end end describe Action::WithSubPlans do class FailureSimulator class << self attr_accessor :fail_in_child_plan, :fail_in_child_run def reset! self.fail_in_child_plan = self.fail_in_child_run = false end end end class DummyAction < Dynflow::Action def run; end end class ParentAction < Dynflow::Action include Dynflow::Action::WithSubPlans def plan(*_) super plan_action(DummyAction, {}) end def create_sub_plans input[:count].times.map { trigger(ChildAction, suspend: input[:suspend]) } end def resume(*args) output[:custom_resume] = true super(*args) end end class ChildAction < Dynflow::Action include Dynflow::Action::Cancellable def plan(input) if FailureSimulator.fail_in_child_plan raise "Fail in child plan" end plan_action(DummyAction, {}) super end def run(event = nil) if FailureSimulator.fail_in_child_run raise "Fail in child run" end if event == Dynflow::Action::Cancellable::Abort output[:aborted] = true end if input[:suspend] && !cancel_event?(event) suspend end end def cancel_event?(event) event == Dynflow::Action::Cancellable::Cancel || event == Dynflow::Action::Cancellable::Abort end end class PollingParentAction < ParentAction include ::Dynflow::Action::WithPollingSubPlans end class PollingBulkParentAction < ParentAction include ::Dynflow::Action::WithBulkSubPlans include ::Dynflow::Action::WithPollingSubPlans def poll output[:poll] += 1 super end def on_planning_finished output[:poll] = 0 output[:planning_finished] ||= 0 output[:planning_finished] += 1 super end def total_count input[:count] end def batch_size 1 end def create_sub_plans current_batch.map { trigger(ChildAction, suspend: input[:suspend]) } end def batch(from, size) total_count.times.drop(from).take(size) end end let(:execution_plan) { world.trigger(ParentAction, count: 2).finished.value } before do FailureSimulator.reset! end specify "the sub-plan stores the information about its parent" do sub_plans = execution_plan.sub_plans _(sub_plans.size).must_equal 2 _(execution_plan.sub_plans_count).must_equal 2 sub_plans.each { |sub_plan| _(sub_plan.caller_execution_plan_id).must_equal execution_plan.id } end specify "the parent and sub-plan actions return root_action? properly" do assert execution_plan.actions.first.send(:root_action?), 'main action of parent task should be considered a root_action?' refute execution_plan.actions.last.send(:root_action?), 'sub action of parent task should not be considered a root_action?' sub_plan = execution_plan.sub_plans.first assert sub_plan.actions.first.send(:root_action?), 'main action of sub-task should be considered a root_action?' refute sub_plan.actions.last.send(:root_action?), 'sub action of sub-task should not be considered a root_action?' end specify "it saves the information about number for sub plans in the output" do _(execution_plan.entry_action.output).must_equal('total_count' => 2, 'failed_count' => 0, 'success_count' => 2, 'pending_count' => 0) end specify "when a sub plan fails, the caller action fails as well" do FailureSimulator.fail_in_child_run = true _(execution_plan.entry_action.output).must_equal('total_count' => 2, 'failed_count' => 2, 'success_count' => 0, 'pending_count' => 0) _(execution_plan.state).must_equal :paused _(execution_plan.result).must_equal :error end describe 'resuming' do specify "resuming the action depends on the resume method definition" do FailureSimulator.fail_in_child_plan = true _(execution_plan.state).must_equal :paused FailureSimulator.fail_in_child_plan = false resumed_plan = world.execute(execution_plan.id).value _(resumed_plan.entry_action.output[:custom_resume]).must_equal true end specify "by default, when no sub plans were planned successfully, it call create_sub_plans again" do FailureSimulator.fail_in_child_plan = true _(execution_plan.state).must_equal :paused FailureSimulator.fail_in_child_plan = false resumed_plan = world.execute(execution_plan.id).value _(resumed_plan.state).must_equal :stopped _(resumed_plan.result).must_equal :success end specify "by default, when any sub-plan was planned, it succeeds only when the sub-plans were already finished" do FailureSimulator.fail_in_child_run = true _(execution_plan.state).must_equal :paused sub_plans = execution_plan.sub_plans FailureSimulator.fail_in_child_run = false resumed_plan = world.execute(execution_plan.id).value _(resumed_plan.state).must_equal :paused world.execute(sub_plans.first.id).wait resumed_plan = world.execute(execution_plan.id).value _(resumed_plan.state).must_equal :paused sub_plans.drop(1).each { |sub_plan| world.execute(sub_plan.id).wait } resumed_plan = world.execute(execution_plan.id).value _(resumed_plan.state).must_equal :stopped _(resumed_plan.result).must_equal :success end describe ::Dynflow::Action::WithPollingSubPlans do include TestHelpers let(:clock) { Dynflow::Testing::ManagedClock.new } let(:polling_plan) { world.trigger(PollingParentAction, count: 2).finished.value } specify "by default, when no sub plans were planned successfully, it calls create_sub_plans again" do world.stub(:clock, clock) do total = 2 FailureSimulator.fail_in_child_plan = true triggered_plan = world.trigger(PollingParentAction, count: total) polling_plan = nil wait_for('the subplans to be spawned') do polling_plan = world.persistence.load_execution_plan(triggered_plan.id) polling_plan.sub_plans_count == total end # Moving the clock to make the parent check on sub plans _(clock.pending_pings.count).must_equal 1 clock.progress wait_for('the parent to realise the sub plans failed') do polling_plan = world.persistence.load_execution_plan(triggered_plan.id) polling_plan.state == :paused end FailureSimulator.fail_in_child_plan = false world.execute(polling_plan.id) # The actual resume wait_for('new generation of sub plans to be spawned') do polling_plan.sub_plans_count == 2 * total end # Move the clock again _(clock.pending_pings.count).must_equal 1 clock.progress wait_for('everything to finish successfully') do polling_plan = world.persistence.load_execution_plan(triggered_plan.id) polling_plan.state == :stopped && polling_plan.result == :success end end end specify "by default it starts polling again" do world.stub(:clock, clock) do total = 2 FailureSimulator.fail_in_child_run = true triggered_plan = world.trigger(PollingParentAction, count: total) polling_plan = world.persistence.load_execution_plan(triggered_plan.id) wait_for do # Waiting for the sub plans to be spawned polling_plan = world.persistence.load_execution_plan(triggered_plan.id) polling_plan.sub_plans_count == total && polling_plan.sub_plans.all? { |sub| sub.state == :paused } end # Moving the clock to make the parent check on sub plans _(clock.pending_pings.count).must_equal 1 clock.progress _(clock.pending_pings.count).must_equal 0 wait_for do # Waiting for the parent to realise the sub plans failed polling_plan = world.persistence.load_execution_plan(triggered_plan.id) polling_plan.state == :paused end FailureSimulator.fail_in_child_run = false # Resume the sub plans polling_plan.sub_plans.each do |sub| world.execute(sub.id) end wait_for do # Waiting for the child tasks to finish polling_plan.sub_plans.all? { |sub| sub.state == :stopped } end world.execute(polling_plan.id) # The actual resume wait_for do # Waiting for everything to finish successfully polling_plan = world.persistence.load_execution_plan(triggered_plan.id) polling_plan.state == :stopped && polling_plan.result == :success end end end end end describe 'cancelling' do include TestHelpers it "sends the cancel event to all actions that are running and support cancelling" do triggered_plan = world.trigger(ParentAction, count: 2, suspend: true) plan = wait_for do plan = world.persistence.load_execution_plan(triggered_plan.id) if plan.cancellable? plan end end plan.cancel triggered_plan.finished.wait _(triggered_plan.finished.value.state).must_equal :stopped _(triggered_plan.finished.value.result).must_equal :success end it "sends the abort event to all actions that are running and support cancelling" do triggered_plan = world.trigger(ParentAction, count: 2, suspend: true) plan = wait_for do plan = world.persistence.load_execution_plan(triggered_plan.id) if plan.cancellable? plan end end plan.cancel true triggered_plan.finished.wait _(triggered_plan.finished.value.state).must_equal :stopped _(triggered_plan.finished.value.result).must_equal :success plan.sub_plans.each do |sub_plan| _(sub_plan.entry_action.output[:aborted]).must_equal true end end end describe ::Dynflow::Action::WithPollingSubPlans do include TestHelpers include Testing let(:clock) { Dynflow::Testing::ManagedClock.new } specify 'polls for sub plans state' do world.stub :clock, clock do total = 2 plan = world.plan(PollingParentAction, count: total) _(plan.state).must_equal :planned _(clock.pending_pings.count).must_equal 0 world.execute(plan.id) wait_for do plan.sub_plans_count == total && plan.sub_plans.all? { |sub| sub.result == :success } end _(clock.pending_pings.count).must_equal 1 clock.progress wait_for do plan = world.persistence.load_execution_plan(plan.id) plan.state == :stopped end _(clock.pending_pings.count).must_equal 0 end end specify 'starts polling for sub plans at the beginning' do world.stub :clock, clock do total = 2 plan = world.plan(PollingBulkParentAction, count: total) assert_nil plan.entry_action.output[:planning_finished] _(clock.pending_pings.count).must_equal 0 world.execute(plan.id) wait_for do plan = world.persistence.load_execution_plan(plan.id) plan.entry_action.output[:planning_finished] == 1 end # Poll was set during #initiate _(clock.pending_pings.count).must_equal 1 # Wait for the sub plans to finish wait_for do plan.sub_plans_count == total && plan.sub_plans.all? { |sub| sub.result == :success } end # Poll again clock.progress wait_for do plan = world.persistence.load_execution_plan(plan.id) plan.state == :stopped end _(plan.entry_action.output[:poll]).must_equal 1 _(clock.pending_pings.count).must_equal 0 end end it 'handles empty sub plans when calculating progress' do action = create_and_plan_action(PollingBulkParentAction, :count => 0) _(action.run_progress).must_equal 0.1 end describe ::Dynflow::Action::Singleton do include TestHelpers let(:clock) { Dynflow::Testing::ManagedClock.new } class SingletonAction < ::Dynflow::Action include ::Dynflow::Action::Singleton end class SingletonActionWithRun < SingletonAction def run; end end class SingletonActionWithFinalize < SingletonAction def finalize; end end class SuspendedSingletonAction < SingletonAction def run(event = nil) unless output[:suspended] output[:suspended] = true suspend end end end class BadAction < SingletonAction def plan(break_locks = false) plan_self :break_locks => break_locks singleton_unlock! if break_locks end def run singleton_unlock! if input[:break_locks] end end it 'unlocks the locks after #plan if no #run or #finalize' do plan = world.plan(SingletonAction) _(plan.state).must_equal :planned lock_filter = ::Dynflow::Coordinator::SingletonActionLock .unique_filter plan.entry_action.class.name _(world.coordinator.find_locks(lock_filter).count).must_equal 1 plan = world.execute(plan.id).wait!.value _(plan.state).must_equal :stopped _(plan.result).must_equal :success _(world.coordinator.find_locks(lock_filter).count).must_equal 0 end it 'unlocks the locks after #finalize' do plan = world.plan(SingletonActionWithFinalize) _(plan.state).must_equal :planned lock_filter = ::Dynflow::Coordinator::SingletonActionLock .unique_filter plan.entry_action.class.name _(world.coordinator.find_locks(lock_filter).count).must_equal 1 plan = world.execute(plan.id).wait!.value _(plan.state).must_equal :stopped _(plan.result).must_equal :success _(world.coordinator.find_locks(lock_filter).count).must_equal 0 end it 'does not unlock when getting suspended' do plan = world.plan(SuspendedSingletonAction) _(plan.state).must_equal :planned lock_filter = ::Dynflow::Coordinator::SingletonActionLock .unique_filter plan.entry_action.class.name _(world.coordinator.find_locks(lock_filter).count).must_equal 1 future = world.execute(plan.id) wait_for do plan = world.persistence.load_execution_plan(plan.id) plan.state == :running && plan.result == :pending end _(world.coordinator.find_locks(lock_filter).count).must_equal 1 world.event(plan.id, 2, nil) plan = future.wait!.value _(plan.state).must_equal :stopped _(plan.result).must_equal :success _(world.coordinator.find_locks(lock_filter).count).must_equal 0 end it 'can be triggered only once' do # plan1 acquires the lock in plan phase plan1 = world.plan(SingletonActionWithRun) _(plan1.state).must_equal :planned _(plan1.result).must_equal :pending # plan2 tries to acquire the lock in plan phase and fails plan2 = world.plan(SingletonActionWithRun) _(plan2.state).must_equal :stopped _(plan2.result).must_equal :error _(plan2.errors.first.message).must_equal 'Action Dynflow::SingletonActionWithRun is already active' # Simulate some bad things happening plan1.entry_action.send(:singleton_unlock!) # plan3 acquires the lock in plan phase plan3 = world.plan(SingletonActionWithRun) # plan1 tries to relock on run # This should fail because the lock was taken by plan3 plan1 = world.execute(plan1.id).wait!.value _(plan1.state).must_equal :paused _(plan1.result).must_equal :error # plan3 can finish successfully because it holds the lock plan3 = world.execute(plan3.id).wait!.value _(plan3.state).must_equal :stopped _(plan3.result).must_equal :success # The lock was released when plan3 stopped lock_filter = ::Dynflow::Coordinator::SingletonActionLock .unique_filter plan3.entry_action.class.name _(world.coordinator.find_locks(lock_filter)).must_be :empty? end it 'cannot be unlocked by another action' do # plan1 doesn't keep its locks plan1 = world.plan(BadAction, true) _(plan1.state).must_equal :planned lock_filter = ::Dynflow::Coordinator::SingletonActionLock .unique_filter plan1.entry_action.class.name _(world.coordinator.find_locks(lock_filter).count).must_equal 0 plan2 = world.plan(BadAction, false) _(plan2.state).must_equal :planned _(world.coordinator.find_locks(lock_filter).count).must_equal 1 # The locks held by plan2 can't be unlocked by plan1 plan1.entry_action.singleton_unlock! _(world.coordinator.find_locks(lock_filter).count).must_equal 1 plan1 = world.execute(plan1.id).wait!.value _(plan1.state).must_equal :paused _(plan1.result).must_equal :error plan2 = world.execute(plan2.id).wait!.value _(plan2.state).must_equal :stopped _(plan2.result).must_equal :success end end end end describe 'output chunks' do include ::Dynflow::Testing::Factories class OutputChunkAction < ::Dynflow::Action def run(event = nil) output[:counter] ||= 0 case event when nil output_chunk("Chunk #{output[:counter]}") output[:counter] += 1 suspend when :exit return end end def finalize drop_output_chunks! end end it 'collects and drops output chunks' do action = create_and_plan_action(OutputChunkAction) assert_nil action.pending_output_chunks action = run_action(action) _(action.pending_output_chunks.count).must_equal 1 action = run_action(action) _(action.pending_output_chunks.count).must_equal 2 action = run_action(action, :exit) _(action.pending_output_chunks.count).must_equal 2 persistence = mock() persistence.expects(:delete_output_chunks).with(action.execution_plan_id, action.id) action.world.stubs(:persistence).returns(persistence) action = finalize_action(action) _(action.pending_output_chunks.count).must_equal 0 end end end end
ruby
MIT
e14dcdfe57cec99cc78b2f6ab521f00809b1408a
2026-01-04T17:50:16.326730Z
false
Dynflow/dynflow
https://github.com/Dynflow/dynflow/blob/e14dcdfe57cec99cc78b2f6ab521f00809b1408a/test/flows_test.rb
test/flows_test.rb
# frozen_string_literal: true require_relative 'test_helper' require 'mocha/minitest' module Dynflow describe 'flow' do class TestRegistry < Flows::Registry class << self def reset! @serialization_map = {} end end end after do TestRegistry.reset! end describe "registry" do it "allows registering values" do TestRegistry.register!(TestRegistry, 'TS') TestRegistry.register!(Integer, 'I') map = TestRegistry.instance_variable_get("@serialization_map") _(map).must_equal({ 'TS' => TestRegistry, 'I' => Integer }) end it "prevents overwriting values" do TestRegistry.register!(Integer, 'I') _(-> { TestRegistry.register!(Float, 'I') }).must_raise Flows::Registry::IdentifierTaken end it "encodes and decodes values" do TestRegistry.register!(Integer, 'I') _(TestRegistry.encode(Integer)).must_equal 'I' end it "raises an exception when unknown key is requested" do _(-> { TestRegistry.encode(Float) }).must_raise Flows::Registry::UnknownIdentifier _(-> { TestRegistry.decode('F') }).must_raise Flows::Registry::UnknownIdentifier end end end end
ruby
MIT
e14dcdfe57cec99cc78b2f6ab521f00809b1408a
2026-01-04T17:50:16.326730Z
false
Dynflow/dynflow
https://github.com/Dynflow/dynflow/blob/e14dcdfe57cec99cc78b2f6ab521f00809b1408a/test/future_execution_test.rb
test/future_execution_test.rb
# frozen_string_literal: true require_relative 'test_helper' require 'multi_json' module Dynflow module FutureExecutionTest describe 'Future Execution' do include PlanAssertions include Dynflow::Testing::Assertions include Dynflow::Testing::Factories describe 'action scheduling' do before do @start_at = Time.now.utc + 180 world.persistence.delete_delayed_plans({}) end let(:world) { WorldFactory.create_world } let(:delayed_plan) do delayed_plan = world.delay(::Support::DummyExample::Dummy, { :start_at => @start_at }) _(delayed_plan).must_be :scheduled? world.persistence.load_delayed_plan(delayed_plan.execution_plan_id) end let(:history_names) do ->(execution_plan) { execution_plan.execution_history.map(&:name) } end let(:execution_plan) { delayed_plan.execution_plan } describe 'abstract executor' do let(:abstract_delayed_executor) { DelayedExecutors::AbstractCore.new(world) } it 'handles plan in planning state' do delayed_plan.execution_plan.state = :planning abstract_delayed_executor.send(:process, [delayed_plan], @start_at) _(delayed_plan.execution_plan.state).must_equal :scheduled end it 'handles plan in running state' do delayed_plan.execution_plan.set_state(:running, true) abstract_delayed_executor.send(:process, [delayed_plan], @start_at) _(delayed_plan.execution_plan.state).must_equal :running _(world.persistence.load_delayed_plan(delayed_plan.execution_plan_uuid)).must_be :nil? end end it 'returns the progress as 0' do _(execution_plan.progress).must_equal 0 end it 'marks the plan as failed when issues in serialied phase' do world.persistence.delete_execution_plans({}) e = _(proc { world.delay(::Support::DummyExample::DummyCustomDelaySerializer, { :start_at => @start_at }, :fail) }).must_raise RuntimeError _(e.message).must_equal 'Enforced serializer failure' plan = world.persistence.find_execution_plans(page: 0, per_page: 1, order_by: :ended_at, desc: true).first _(plan.state).must_equal :stopped _(plan.result).must_equal :error end it 'delays the action' do _(execution_plan.steps.count).must_equal 1 _(delayed_plan.start_at.to_i).must_equal(@start_at.to_i) _(history_names.call(execution_plan)).must_equal ['delay'] end it 'allows cancelling the delayed plan' do _(execution_plan.state).must_equal :scheduled _(execution_plan.cancellable?).must_equal true execution_plan.cancel.each(&:wait) execution_plan = world.persistence.load_execution_plan(self.execution_plan.id) _(execution_plan.state).must_equal :stopped _(execution_plan.result).must_equal :cancelled assert_nil execution_plan.delay_record end it 'finds delayed plans' do @start_at = Time.now.utc - 100 delayed_plan past_delayed_plans = world.persistence.find_ready_delayed_plans(@start_at + 10) _(past_delayed_plans.length).must_equal 1 _(past_delayed_plans.first.execution_plan_uuid).must_equal execution_plan.id end it 'delayed plans can be planned and executed' do _(execution_plan.state).must_equal :scheduled delayed_plan.plan _(execution_plan.state).must_equal :planned _(execution_plan.result).must_equal :pending assert_planning_success execution_plan _(history_names.call(execution_plan)).must_equal ['delay'] delayed_plan.execute.future.wait executed = world.persistence.load_execution_plan(delayed_plan.execution_plan_uuid) _(executed.state).must_equal :stopped _(executed.result).must_equal :success _(executed.execution_history.count).must_equal 3 end it 'expired plans can be failed' do delayed_plan.timeout _(execution_plan.state).must_equal :stopped _(execution_plan.result).must_equal :error _(execution_plan.errors.first.message).must_match(/could not be started before set time/) _(history_names.call(execution_plan)).must_equal %W(delay timeout) end end describe 'polling delayed executor' do let(:dummy_world) { Dynflow::Testing::DummyWorld.new } let(:persistence) { MiniTest::Mock.new } let(:options) { { :poll_interval => 15, :time_source => -> { dummy_world.clock.current_time } } } let(:delayed_executor) { DelayedExecutors::Polling.new(dummy_world, options) } let(:klok) { dummy_world.clock } it 'checks for delayed plans in regular intervals' do start_time = klok.current_time persistence.expect(:find_ready_delayed_plans, [], [start_time]) persistence.expect(:find_ready_delayed_plans, [], [start_time + options[:poll_interval]]) dummy_world.stub :persistence, persistence do _(klok.pending_pings.length).must_equal 0 delayed_executor.start.wait _(klok.pending_pings.length).must_equal 1 _(klok.pending_pings.first.who.ref).must_be_same_as delayed_executor.core _(klok.pending_pings.first.when).must_equal start_time + options[:poll_interval] klok.progress delayed_executor.terminate.wait _(klok.pending_pings.length).must_equal 1 _(klok.pending_pings.first.who.ref).must_be_same_as delayed_executor.core _(klok.pending_pings.first.when).must_equal start_time + 2 * options[:poll_interval] klok.progress _(klok.pending_pings.length).must_equal 0 end end end describe 'serializers' do let(:args) { %w(arg1 arg2) } let(:serialized_serializer) { Dynflow::Serializers::Noop.new(nil, args) } let(:deserialized_serializer) { Dynflow::Serializers::Noop.new(args, nil) } let(:save_and_load) do ->(thing) { MultiJson.load(MultiJson.dump(thing)) } end let(:simulated_use) do lambda do |serializer_class, input| serializer = serializer_class.new(input) serializer.perform_serialization! serialized_args = save_and_load.call(serializer.serialized_args) serializer = serializer_class.new(nil, serialized_args) serializer.perform_deserialization! serializer.args end end it 'noop serializer [de]serializes correctly for simple types' do input = [1, 2.0, 'three', ['four-1', 'four-2'], { 'five' => 5 }] _(simulated_use.call(Dynflow::Serializers::Noop, input)).must_equal input end it 'args! raises if not deserialized' do _(proc { serialized_serializer.args! }).must_raise RuntimeError deserialized_serializer.args! # Must not raise end it 'serialized_args! raises if not serialized' do _(proc { deserialized_serializer.serialized_args! }).must_raise RuntimeError serialized_serializer.serialized_args! # Must not raise end it 'performs_serialization!' do deserialized_serializer.perform_serialization! _(deserialized_serializer.serialized_args!).must_equal args end it 'performs_deserialization!' do serialized_serializer.perform_deserialization! _(serialized_serializer.args).must_equal args end end describe 'delayed plan' do let(:args) { %w(arg1 arg2) } let(:serializer) { Dynflow::Serializers::Noop.new(nil, args) } let(:delayed_plan) do Dynflow::DelayedPlan.new(Dynflow::World.allocate, 'an uuid', nil, nil, serializer, false) end it "allows access to serializer's args" do _(serializer.args).must_be :nil? _(delayed_plan.args).must_equal args _(serializer.args).must_equal args end end describe 'execution plan chaining' do let(:world) do WorldFactory.create_world { |config| config.auto_rescue = true } end before do @preexisting = world.persistence.find_ready_delayed_plans(Time.now).map(&:execution_plan_uuid) end it 'chains two execution plans' do plan1 = world.plan(Support::DummyExample::Dummy) plan2 = world.chain(plan1.id, Support::DummyExample::Dummy) Concurrent::Promises.resolvable_future.tap do |promise| world.execute(plan1.id, promise) end.wait plan1 = world.persistence.load_execution_plan(plan1.id) _(plan1.state).must_equal :stopped ready = world.persistence.find_ready_delayed_plans(Time.now).reject { |p| @preexisting.include? p.execution_plan_uuid } _(ready.count).must_equal 1 _(ready.first.execution_plan_uuid).must_equal plan2.execution_plan_id end it 'chains onto multiple execution plans and waits for all to finish' do plan1 = world.plan(Support::DummyExample::Dummy) plan2 = world.plan(Support::DummyExample::Dummy) plan3 = world.chain([plan2.id, plan1.id], Support::DummyExample::Dummy) # Execute and complete plan1 Concurrent::Promises.resolvable_future.tap do |promise| world.execute(plan1.id, promise) end.wait plan1 = world.persistence.load_execution_plan(plan1.id) _(plan1.state).must_equal :stopped # plan3 should still not be ready because plan2 hasn't finished yet ready = world.persistence.find_ready_delayed_plans(Time.now).reject { |p| @preexisting.include? p.execution_plan_uuid } _(ready.count).must_equal 0 # Execute and complete plan2 Concurrent::Promises.resolvable_future.tap do |promise| world.execute(plan2.id, promise) end.wait plan2 = world.persistence.load_execution_plan(plan2.id) _(plan2.state).must_equal :stopped # Now plan3 should be ready since both plan1 and plan2 are complete ready = world.persistence.find_ready_delayed_plans(Time.now).reject { |p| @preexisting.include? p.execution_plan_uuid } _(ready.count).must_equal 1 _(ready.first.execution_plan_uuid).must_equal plan3.execution_plan_id end it 'cancels the chained plan if the prerequisite fails' do plan1 = world.plan(Support::DummyExample::FailingDummy) plan2 = world.chain(plan1.id, Support::DummyExample::Dummy) Concurrent::Promises.resolvable_future.tap do |promise| world.execute(plan1.id, promise) end.wait plan1 = world.persistence.load_execution_plan(plan1.id) _(plan1.state).must_equal :stopped _(plan1.result).must_equal :error # plan2 will appear in ready delayed plans ready = world.persistence.find_ready_delayed_plans(Time.now).reject { |p| @preexisting.include? p.execution_plan_uuid } _(ready.map(&:execution_plan_uuid)).must_equal [plan2.execution_plan_id] # Process the delayed plan through the director work_item = Dynflow::Director::PlanningWorkItem.new(plan2.execution_plan_id, :default, world.id) work_item.world = world work_item.execute # Now plan2 should be stopped with error due to failed dependency plan2 = world.persistence.load_execution_plan(plan2.execution_plan_id) _(plan2.state).must_equal :stopped _(plan2.result).must_equal :error _(plan2.errors.first.message).must_match(/prerequisite execution plans failed/) _(plan2.errors.first.message).must_match(/#{plan1.id}/) end it 'cancels the chained plan if at least one prerequisite fails' do plan1 = world.plan(Support::DummyExample::Dummy) plan2 = world.plan(Support::DummyExample::FailingDummy) plan3 = world.chain([plan1.id, plan2.id], Support::DummyExample::Dummy) # Execute and complete plan1 successfully Concurrent::Promises.resolvable_future.tap do |promise| world.execute(plan1.id, promise) end.wait plan1 = world.persistence.load_execution_plan(plan1.id) _(plan1.state).must_equal :stopped _(plan1.result).must_equal :success # plan3 should still not be ready because plan2 hasn't finished yet ready = world.persistence.find_ready_delayed_plans(Time.now).reject { |p| @preexisting.include? p.execution_plan_uuid } _(ready).must_equal [] # Execute and complete plan2 with failure Concurrent::Promises.resolvable_future.tap do |promise| world.execute(plan2.id, promise) end.wait plan2 = world.persistence.load_execution_plan(plan2.id) _(plan2.state).must_equal :stopped _(plan2.result).must_equal :error # plan3 will now appear in ready delayed plans even though one prerequisite failed ready = world.persistence.find_ready_delayed_plans(Time.now).reject { |p| @preexisting.include? p.execution_plan_uuid } _(ready.map(&:execution_plan_uuid)).must_equal [plan3.execution_plan_id] # Process the delayed plan through the director work_item = Dynflow::Director::PlanningWorkItem.new(plan3.execution_plan_id, :default, world.id) work_item.world = world work_item.execute # Now plan3 should be stopped with error due to failed dependency plan3 = world.persistence.load_execution_plan(plan3.execution_plan_id) _(plan3.state).must_equal :stopped _(plan3.result).must_equal :error _(plan3.errors.first.message).must_match(/prerequisite execution plans failed/) _(plan3.errors.first.message).must_match(/#{plan2.id}/) end it 'chains runs the chained plan if the prerequisite was halted' do plan1 = world.plan(Support::DummyExample::Dummy) plan2 = world.chain(plan1.id, Support::DummyExample::Dummy) world.halt(plan1.id) Concurrent::Promises.resolvable_future.tap do |promise| world.execute(plan1.id, promise) end.wait plan1 = world.persistence.load_execution_plan(plan1.id) _(plan1.state).must_equal :stopped _(plan1.result).must_equal :pending ready = world.persistence.find_ready_delayed_plans(Time.now).reject { |p| @preexisting.include? p.execution_plan_uuid } _(ready.count).must_equal 1 _(ready.first.execution_plan_uuid).must_equal plan2.execution_plan_id end end end end end
ruby
MIT
e14dcdfe57cec99cc78b2f6ab521f00809b1408a
2026-01-04T17:50:16.326730Z
false
Dynflow/dynflow
https://github.com/Dynflow/dynflow/blob/e14dcdfe57cec99cc78b2f6ab521f00809b1408a/test/support/test_execution_log.rb
test/support/test_execution_log.rb
# frozen_string_literal: true class TestExecutionLog include Enumerable def initialize @log = [] end def <<(action) @log << [action.class, action.input] end def log @log end def each(&block) @log.each(&block) end def size @log.size end def self.setup @run, @finalize = self.new, self.new end def self.teardown @run, @finalize = nil, nil end def self.run @run || [] end def self.finalize @finalize || [] end end
ruby
MIT
e14dcdfe57cec99cc78b2f6ab521f00809b1408a
2026-01-04T17:50:16.326730Z
false
Dynflow/dynflow
https://github.com/Dynflow/dynflow/blob/e14dcdfe57cec99cc78b2f6ab521f00809b1408a/test/support/rescue_example.rb
test/support/rescue_example.rb
# frozen_string_literal: true require 'logger' module Support module RescueExample class ComplexActionWithSkip < Dynflow::Action def plan(error_state) sequence do concurrence do plan_action(ActionWithSkip, 3, :success) plan_action(ActionWithSkip, 4, error_state) plan_action(ActionWithSkip, 5, error_state) end plan_action(ActionWithSkip, 6, :success) end end def rescue_strategy_for_self Dynflow::Action::Rescue::Skip end end class ComplexActionWithoutSkip < ComplexActionWithSkip def rescue_strategy_for_planned_action(action) # enforce pause even when error on skipable action Dynflow::Action::Rescue::Pause end end class AbstractAction < Dynflow::Action def plan(identifier, desired_state) plan_self(identifier: identifier, desired_state: desired_state) end def run case input[:desired_state].to_sym when :success, :error_on_finalize output[:message] = 'Been here' when :error_on_run, :error_on_skip raise 'some error as you wish' when :pending raise 'we were not supposed to get here' else raise "unkown desired state #{input[:desired_state]}" end end def finalize case input[:desired_state].to_sym when :error_on_finalize, :error_on_skip raise 'some error as you wish' end end end class ActionWithSkip < AbstractAction def run(event = nil) if event === Dynflow::Action::Skip output[:message] = "skipped because #{self.error.message}" raise 'we failed on skip as well' if input[:desired_state].to_sym == :error_on_skip else super() end end def rescue_strategy_for_self Dynflow::Action::Rescue::Skip end end class ActionWithFail < AbstractAction def rescue_strategy_for_self Dynflow::Action::Rescue::Fail end end class ComplexActionWithFail < ActionWithFail def plan(error_state) sequence do concurrence do plan_action(ActionWithFail, 3, :success) plan_action(ActionWithFail, 4, error_state) end plan_action(ActionWithFail, 5, :success) plan_action(ActionWithSkip, 6, :success) end end end end end
ruby
MIT
e14dcdfe57cec99cc78b2f6ab521f00809b1408a
2026-01-04T17:50:16.326730Z
false
Dynflow/dynflow
https://github.com/Dynflow/dynflow/blob/e14dcdfe57cec99cc78b2f6ab521f00809b1408a/test/support/middleware_example.rb
test/support/middleware_example.rb
# frozen_string_literal: true module Support module MiddlewareExample class LogMiddleware < Dynflow::Middleware def self.log @log end def self.reset_log @log = [] end def log(message) LogMiddleware.log << "#{self.class.name[/\w+$/]}::#{message}" end def delay(*args) log 'before_delay' pass(*args) log 'after_delay' end def plan(args) log 'before_plan' pass(args) log 'after_plan' end def run(*args) log 'before_run' pass(*args) ensure log 'after_run' end def finalize log 'before_finalize' pass log 'after_finalize' end def plan_phase(*_) log 'before_plan_phase' pass log 'after_plan_phase' end def finalize_phase(*_) log 'before_finalize_phase' pass log 'after_finalize_phase' end end class LogRunMiddleware < Dynflow::Middleware def log(message) LogMiddleware.log << "#{self.class.name[/\w+$/]}::#{message}" end def run(*args) log 'before_run' pass(*args) ensure log 'after_run' end end class AnotherLogRunMiddleware < LogRunMiddleware end class FilterSensitiveData < Dynflow::Middleware def present if action.respond_to?(:filter_sensitive_data) action.filter_sensitive_data end filter_sensitive_data(action.input) filter_sensitive_data(action.output) end def filter_sensitive_data(data) case data when Hash data.values.each { |value| filter_sensitive_data(value) } when Array data.each { |value| filter_sensitive_data(value) } when String data.gsub!('Lord Voldemort', 'You-Know-Who') end end end class SecretAction < Dynflow::Action middleware.use(FilterSensitiveData) def run output[:spell] = 'Wingardium Leviosa' end def filter_sensitive_data output[:spell] = '***'.dup end end class LoggingAction < Dynflow::Action middleware.use LogMiddleware def log(message) LogMiddleware.log << message end def delay(delay_options, *args) log 'delay' Dynflow::Serializers::Noop.new(args) end def plan(input) log 'plan' plan_self(input) end def run log 'run' end def finalize log 'finalize' end end class ObservingMiddleware < Dynflow::Middleware def log(message) LogMiddleware.log << message end def run(*args) log("input#message:#{action.input[:message]}") pass(*args) ensure log("output#message:#{action.output[:message]}") end end class AnotherObservingMiddleware < ObservingMiddleware def delay(*args) pass(*args).tap do log("delay#set-input:#{action.world.id}") action.input[:message] = action.world.id end end def plan(*args) log("plan#input:#{action.input[:message]}") pass(*args) end end class Action < Dynflow::Action middleware.use LogRunMiddleware def log(message) LogMiddleware.log << message end def run log("run") output[:message] = "finished" end end class SubAction < Action middleware.use AnotherLogRunMiddleware end class SubActionBeforeRule < Action middleware.use AnotherLogRunMiddleware, before: LogRunMiddleware end class SubActionReplaceRule < Action middleware.use AnotherLogRunMiddleware, replace: LogRunMiddleware end class SubActionDoNotUseRule < Action middleware.use AnotherLogRunMiddleware middleware.do_not_use AnotherLogRunMiddleware middleware.do_not_use LogRunMiddleware end class SubActionAfterRule < Action middleware.use AnotherLogRunMiddleware, after: LogRunMiddleware end end end
ruby
MIT
e14dcdfe57cec99cc78b2f6ab521f00809b1408a
2026-01-04T17:50:16.326730Z
false
Dynflow/dynflow
https://github.com/Dynflow/dynflow/blob/e14dcdfe57cec99cc78b2f6ab521f00809b1408a/test/support/dummy_example.rb
test/support/dummy_example.rb
# frozen_string_literal: true require 'logger' module Support module DummyExample class Dummy < Dynflow::Action def run; end end class SkippableDummy < Dummy def rescue_strategy_for_self Dynflow::Action::Rescue::Skip end end class MySerializer < Dynflow::Serializers::Noop def serialize(arg) raise 'Enforced serializer failure' if arg == :fail super arg end end class DummyCustomDelaySerializer < Dynflow::Action def delay(delay_options, *args) MySerializer.new(args) end def run; end end class FailingDummy < Dynflow::Action def run; raise 'error'; end def rescue_strategy Dynflow::Action::Rescue::Fail end end class Slow < Dynflow::Action def plan(seconds) sequence do plan_self interval: seconds plan_action Dummy end end def run sleep input[:interval] action_logger.debug 'done with sleeping' $slow_actions_done ||= 0 $slow_actions_done += 1 end def queue :slow end end class Polling < Dynflow::Action include Dynflow::Action::Polling def invoke_external_task error! 'Trolling detected' if input[:text] == 'troll setup' { progress: 0, done: false } end def poll_external_task if input[:text] == 'troll progress' && !output[:trolled] output[:trolled] = true error! 'Trolling detected' end if input[:text] =~ /pause in progress (\d+)/ TestPause.pause if external_task[:progress] == $1.to_i end progress = external_task[:progress] + 10 { progress: progress, done: progress >= 100 } end def done? external_task && external_task[:progress] >= 100 end def poll_interval 0.001 end def run_progress external_task && external_task[:progress].to_f / 100 end end class WeightedPolling < Dynflow::Action def plan(input) sequence do plan_self(input) plan_action(Polling, input) end end def run end def finalize $dummy_heavy_progress = 'dummy_heavy_progress' end def run_progress_weight 4 end def finalize_progress_weight 5 end def humanized_output "You should #{output['message']}" end end class DeprecatedEventedAction < Dynflow::Action def run(event = nil) case event when "timeout" output[:event] = 'timeout' raise "action timeouted" when nil suspend do |suspended_action| if input[:timeout] world.clock.ping suspended_action, input[:timeout], "timeout" end end else self.output[:event] = event end end end class PlanEventsAction < Dynflow::Action def run(event = nil) case event when 'ping' output[:result] = 'pinged' when nil plan_event('ping', input[:ping_time] || 0.5) suspend end end end class ComposedAction < Dynflow::Action def run(event = nil) match event, (on nil do sub_plan = world.trigger(Dummy) output[:sub_plan_id] = sub_plan.id suspend do |suspended_action| if input[:timeout] world.clock.ping suspended_action, input[:timeout], "timeout" end sub_plan.finished.on_fulfillment! { suspended_action << 'finish' } end end), (on 'finish' do output[:event] = 'finish' end), (on 'timeout' do output[:event] = 'timeout' end) end end end end
ruby
MIT
e14dcdfe57cec99cc78b2f6ab521f00809b1408a
2026-01-04T17:50:16.326730Z
false
Dynflow/dynflow
https://github.com/Dynflow/dynflow/blob/e14dcdfe57cec99cc78b2f6ab521f00809b1408a/test/support/code_workflow_example.rb
test/support/code_workflow_example.rb
# frozen_string_literal: true require 'logger' module Support module CodeWorkflowExample class IncomingIssues < Dynflow::Action def plan(issues) issues.each do |issue| plan_action(IncomingIssue, issue) end plan_self('issues' => issues) end input_format do param :issues, Array do param :author, String param :text, String end end def finalize TestExecutionLog.finalize << self end def summary # TODO fix, not a good pattern, it should delegate to IncomingIssue first triages = all_planned_actions(Triage) assignees = triages.map do |triage| triage.output[:classification] && triage.output[:classification][:assignee] end.compact.uniq { assignees: assignees } end end class IncomingIssue < Dynflow::Action def plan(issue) raise "You want me to fail" if issue == :fail plan_self(issue) plan_action(Triage, issue) end input_format do param :author, String param :text, String end end class Triage < Dynflow::Action def plan(issue) triage = plan_self(issue) plan_action(UpdateIssue, author: triage.input[:author], text: triage.input[:text], assignee: triage.output[:classification][:assignee], severity: triage.output[:classification][:severity]) end input_format do param :author, String param :text, String end output_format do param :classification, Hash do param :assignee, String param :severity, %w[low medium high] end end def run TestExecutionLog.run << self TestPause.pause if input[:text].include? 'get a break' error! 'Trolling detected' if input[:text] == "trolling" self.output[:classification] = { assignee: 'John Doe', severity: 'medium' } end def finalize error! 'Trolling detected' if input[:text] == "trolling in finalize" TestExecutionLog.finalize << self end end class UpdateIssue < Dynflow::Action input_format do param :author, String param :text, String param :assignee, String param :severity, %w[low medium high] end def run end end class NotifyAssignee < Dynflow::Action def self.subscribe Triage end input_format do param :triage, Triage.output_format end def plan(*args) plan_self(:triage => triggering_action.output) end def run end def finalize TestExecutionLog.finalize << self end end class Commit < Dynflow::Action input_format do param :sha, String end def plan(commit, reviews = { 'Morfeus' => true, 'Neo' => true }) sequence do ci, review_actions = concurrence do [plan_action(Ci, :commit => commit), reviews.map do |name, result| plan_action(Review, commit, name, result) end] end plan_action(Merge, commit: commit, ci_result: ci.output[:passed], review_results: review_actions.map { |ra| ra.output[:passed] }) end end end class FastCommit < Dynflow::Action def plan(commit) sequence do ci, review = concurrence do [plan_action(Ci, commit: commit), plan_action(Review, commit, 'Morfeus', true)] end plan_action(Merge, commit: commit, ci_result: ci.output[:passed], review_results: [review.output[:passed]]) end end input_format do param :sha, String end end class Ci < Dynflow::Action input_format do param :commit, Commit.input_format end output_format do param :passed, :boolean end def run output.update passed: true end end class Review < Dynflow::Action input_format do param :reviewer, String param :commit, Commit.input_format end output_format do param :passed, :boolean end def plan(commit, reviewer, result = true) plan_self commit: commit, reviewer: reviewer, result: result end def run output.update passed: input[:result] end end class Merge < Dynflow::Action input_format do param :commit, Commit.input_format param :ci_result, Ci.output_format param :review_results, array_of(Review.output_format) end def run output.update passed: (input.fetch(:ci_result) && input.fetch(:review_results).all?) end end class Dummy < Dynflow::Action def label 'dummy_action' end end class DummyWithFinalize < Dynflow::Action def finalize TestExecutionLog.finalize << self end end class DummyTrigger < Dynflow::Action end class DummyAnotherTrigger < Dynflow::Action end class DummySubscribe < Dynflow::Action def self.subscribe DummyTrigger end def run end end class DummyMultiSubscribe < Dynflow::Action def self.subscribe [DummyTrigger, DummyAnotherTrigger] end def run end end class CancelableSuspended < Dynflow::Action include Dynflow::Action::Polling include Dynflow::Action::Cancellable Cancel = Dynflow::Action::Cancellable::Cancel def invoke_external_task { progress: 0 } end def poll_external_task progress = external_task.fetch(:progress) new_progress = if progress == 30 if input[:text] =~ /cancel-external/ progress elsif input[:text] =~ /cancel-self/ world.event execution_plan_id, run_step_id, Cancel progress else progress + 10 end else progress + 10 end { progress: new_progress } end def cancel! if input[:text] !~ /cancel-fail/ self.external_task = external_task.merge(cancelled: true) else error! 'action cancelled' end end def done? external_task && external_task[:progress] >= 100 end def poll_interval 0.01 end def run_progress external_task && external_task[:progress].to_f / 100 end end end end
ruby
MIT
e14dcdfe57cec99cc78b2f6ab521f00809b1408a
2026-01-04T17:50:16.326730Z
false
Dynflow/dynflow
https://github.com/Dynflow/dynflow/blob/e14dcdfe57cec99cc78b2f6ab521f00809b1408a/test/support/rails/config/environment.rb
test/support/rails/config/environment.rb
# frozen_string_literal: true # This is a mock
ruby
MIT
e14dcdfe57cec99cc78b2f6ab521f00809b1408a
2026-01-04T17:50:16.326730Z
false
Dynflow/dynflow
https://github.com/Dynflow/dynflow/blob/e14dcdfe57cec99cc78b2f6ab521f00809b1408a/examples/memory_limit_watcher.rb
examples/memory_limit_watcher.rb
#!/usr/bin/env ruby # frozen_string_literal: true require_relative 'example_helper' example_description = <<~DESC Memory limit watcher Example =========================== In this example we are setting a watcher that will terminate our world object when process memory consumption exceeds a limit that will be set. DESC module MemorylimiterExample class SampleAction < Dynflow::Action def plan(memory_to_use) plan_self(number: memory_to_use) end def run array = Array.new(input[:number].to_i) puts "[action] allocated #{input[:number]} cells" end end end if $0 == __FILE__ puts example_description world = ExampleHelper.create_world do |config| config.exit_on_terminate = false end world.terminated.on_resolution do puts '[world] The world has been terminated' end require 'get_process_mem' memory_info_provider = GetProcessMem.new puts '[info] Preparing memory watcher: ' require 'dynflow/watchers/memory_consumption_watcher' puts "[info] now the process consumes #{memory_info_provider.bytes} bytes." limit = memory_info_provider.bytes + 500_000 puts "[info] Setting memory limit to #{limit} bytes" watcher = Dynflow::Watchers::MemoryConsumptionWatcher.new(world, limit, polling_interval: 1) puts '[info] Small action: ' world.trigger(MemorylimiterExample::SampleAction, 10) sleep 2 puts "[info] now the process consumes #{memory_info_provider.bytes} bytes." puts '[info] Big action: ' world.trigger(MemorylimiterExample::SampleAction, 500_000) sleep 2 puts "[info] now the process consumes #{memory_info_provider.bytes} bytes." puts '[info] Small action again - will not execute, the world is not accepting requests' world.trigger(MemorylimiterExample::SampleAction, 500_000) sleep 2 puts 'Done' end
ruby
MIT
e14dcdfe57cec99cc78b2f6ab521f00809b1408a
2026-01-04T17:50:16.326730Z
false
Dynflow/dynflow
https://github.com/Dynflow/dynflow/blob/e14dcdfe57cec99cc78b2f6ab521f00809b1408a/examples/sub_plans_v2.rb
examples/sub_plans_v2.rb
#!/usr/bin/env ruby # frozen_string_literal: true example_description = <<DESC Sub Plans Example =================== This example shows, how to trigger the execution plans from within a run method of some action and waing for them to finish. This is useful, when doing bulk actions, where having one big execution plan would not be effective, or in case all the data are not available by the time of original action planning. DESC require_relative 'example_helper' require_relative 'orchestrate_evented' COUNT = (ARGV[0] || 25).to_i class Foo < Dynflow::Action def plan plan_self end def run(event = nil) case event when nil rng = Random.new plan_event(:ping, rng.rand(25) + 1) suspend when :ping # Finish end end end class SubPlansExample < Dynflow::Action include Dynflow::Action::V2::WithSubPlans def initiate limit_concurrency_level! 3 super end def create_sub_plans current_batch.map { |i| trigger(Foo) } end def batch_size 15 end def batch(from, size) COUNT.times.drop(from).take(size) end def total_count COUNT end end if $0 == __FILE__ ExampleHelper.world.action_logger.level = Logger::DEBUG ExampleHelper.world t1 = ExampleHelper.world.trigger(SubPlansExample) puts example_description puts <<-MSG.gsub(/^.*\|/, '') | Execution plans #{t1.id} with sub plans triggered | You can see the details at | #{ExampleHelper::DYNFLOW_URL}/#{t1.id} MSG ExampleHelper.run_web_console end
ruby
MIT
e14dcdfe57cec99cc78b2f6ab521f00809b1408a
2026-01-04T17:50:16.326730Z
false
Dynflow/dynflow
https://github.com/Dynflow/dynflow/blob/e14dcdfe57cec99cc78b2f6ab521f00809b1408a/examples/halt.rb
examples/halt.rb
#!/usr/bin/env ruby # frozen_string_literal: true require_relative 'example_helper' example_description = <<DESC Halting example =================== This example shows, how halting works in Dynflow. It spawns a single action, which in turn spawns a few evented actions and a single action which occupies the executor for a long time. Once the halt event is sent, the execution plan is halted, suspended steps stay suspended forever, running steps stay running until they actually finish the current run and the execution state is flipped over to stopped state. You can see the details at #{ExampleHelper::DYNFLOW_URL} DESC class EventedCounter < Dynflow::Action def run(event = nil) output[:counter] ||= 0 output[:counter] += 1 action_logger.info "Iteration #{output[:counter]}" if output[:counter] < input[:count] plan_event(:tick, 5) suspend end action_logger.info "Done" end end class Sleeper < Dynflow::Action def run sleep input[:time] end end class Wrapper < Dynflow::Action def plan sequence do concurrence do 5.times { |i| plan_action(EventedCounter, :count => i + 1) } plan_action Sleeper, :time => 20 end plan_self end end def run # Noop end end if $PROGRAM_NAME == __FILE__ puts example_description ExampleHelper.world.action_logger.level = Logger::DEBUG ExampleHelper.world t = ExampleHelper.world.trigger(Wrapper) Thread.new do sleep 8 ExampleHelper.world.halt(t.id) end ExampleHelper.run_web_console end
ruby
MIT
e14dcdfe57cec99cc78b2f6ab521f00809b1408a
2026-01-04T17:50:16.326730Z
false
Dynflow/dynflow
https://github.com/Dynflow/dynflow/blob/e14dcdfe57cec99cc78b2f6ab521f00809b1408a/examples/future_execution.rb
examples/future_execution.rb
#!/usr/bin/env ruby # frozen_string_literal: true require_relative 'example_helper' class CustomPassedObject attr_reader :id, :name def initialize(id, name) @id = id @name = name end end class CustomPassedObjectSerializer < ::Dynflow::Serializers::Abstract def serialize(arg) # Serialized output can be anything that is representable as JSON: Array, Hash... { :id => arg.id, :name => arg.name } end def deserialize(arg) # Deserialized output must be an Array CustomPassedObject.new(arg[:id], arg[:name]) end end class DelayedAction < Dynflow::Action def delay(delay_options, *args) CustomPassedObjectSerializer.new(args) end def plan(passed_object) plan_self :object_id => passed_object.id, :object_name => passed_object.name end def run end end if $0 == __FILE__ ExampleHelper.world.action_logger.level = 1 ExampleHelper.world.logger.level = 0 past = Time.now - 200 near_future = Time.now + 29 future = Time.now + 180 object = CustomPassedObject.new(1, 'CPS') past_plan = ExampleHelper.world.delay(DelayedAction, { :start_at => past, :start_before => past }, object) near_future_plan = ExampleHelper.world.delay(DelayedAction, { :start_at => near_future, :start_before => future }, object) future_plan = ExampleHelper.world.delay(DelayedAction, { :start_at => future }, object) puts <<-MSG.gsub(/^.*\|/, '') | | Future Execution Example | ======================== | | This example shows the future execution functionality of Dynflow, which allows to plan actions to be executed at set time. | | Execution plans: | #{past_plan.id} is "delayed" to execute before #{past} and should timeout on the first run of the scheduler. | #{near_future_plan.id} is delayed to execute at #{near_future} and should run successfully. | #{future_plan.id} is delayed to execute at #{future} and should run successfully. | | Visit #{ExampleHelper::DYNFLOW_URL} to see their status. | MSG ExampleHelper.run_web_console end
ruby
MIT
e14dcdfe57cec99cc78b2f6ab521f00809b1408a
2026-01-04T17:50:16.326730Z
false
Dynflow/dynflow
https://github.com/Dynflow/dynflow/blob/e14dcdfe57cec99cc78b2f6ab521f00809b1408a/examples/clock_benchmark.rb
examples/clock_benchmark.rb
# frozen_string_literal: true require 'dynflow' require 'benchmark' class Receiver def initialize(limit, future) @limit = limit @future = future @counter = 0 end def null @counter += 1 @future.fulfill(true) if @counter >= @limit end end def test_case(count) future = Concurrent::Promises.resolvable_future clock = Dynflow::Clock.spawn(:name => 'clock') receiver = Receiver.new(count, future) count.times do clock.ping(receiver, 0, nil, :null) end future.wait end Benchmark.bm do |bm| bm.report(' 100') { test_case 100 } bm.report(' 1000') { test_case 1_000 } bm.report(' 5000') { test_case 5_000 } bm.report(' 10000') { test_case 10_000 } bm.report(' 50000') { test_case 50_000 } bm.report('100000') { test_case 100_000 } end
ruby
MIT
e14dcdfe57cec99cc78b2f6ab521f00809b1408a
2026-01-04T17:50:16.326730Z
false
Dynflow/dynflow
https://github.com/Dynflow/dynflow/blob/e14dcdfe57cec99cc78b2f6ab521f00809b1408a/examples/orchestrate_evented.rb
examples/orchestrate_evented.rb
#!/usr/bin/env ruby # frozen_string_literal: true require_relative 'example_helper' example_description = <<DESC Orchestrate Evented Example =========================== This example, how the `examples/orchestrate.rb` can be updated to not block the threads while waiting for external tasks. In this cases, we usually wait most of the time: and we can suspend the run of the action while waiting, for the event. Therefore we suspend the action in the run, ask the world.clock to wake us up few seconds later, so that the thread pool can do something useful in the meantime. Additional benefit besides being able to do more while waiting is allowing to send external events to the action while it's suspended. One use case is being able to cancel the action while it's running. Once the Sinatra web console starts, you can navigate to #{ExampleHelper::DYNFLOW_URL} to see what's happening in the Dynflow world. DESC module OrchestrateEvented class CreateInfrastructure < Dynflow::Action def plan(get_stuck = false) sequence do concurrence do plan_action(CreateMachine, 'host1', 'db', get_stuck: get_stuck) plan_action(CreateMachine, 'host2', 'storage') end plan_action(CreateMachine, 'host3', 'web_server', :db_machine => 'host1', :storage_machine => 'host2') end end end class CreateMachine < Dynflow::Action def plan(name, profile, config_options = {}) prepare_disk = plan_action(PrepareDisk, 'name' => name) create_vm = plan_action(CreateVM, :name => name, :disk => prepare_disk.output['path']) plan_action(AddIPtoHosts, :name => name, :ip => create_vm.output[:ip]) plan_action(ConfigureMachine, :ip => create_vm.output[:ip], :profile => profile, :config_options => config_options) plan_self(:name => name) end def finalize end end class Base < Dynflow::Action Finished = Algebrick.atom def run(event = nil) match(event, (on Finished do on_finish end), (on Dynflow::Action::Skip do # do nothing end), (on nil do suspend { |suspended_action| world.clock.ping suspended_action, rand(1), Finished } end)) end def on_finish raise NotImplementedError end end class PrepareDisk < Base input_format do param :name end output_format do param :path end def on_finish output[:path] = "/var/images/#{input[:name]}.img" end end class CreateVM < Base input_format do param :name param :disk end output_format do param :ip end def on_finish output[:ip] = "192.168.100.#{rand(256)}" end end class AddIPtoHosts < Base input_format do param :ip end def on_finish end end class ConfigureMachine < Base # thanks to this Dynflow knows this action can be politely # asked to get canceled include ::Dynflow::Action::Cancellable input_format do param :ip param :profile param :config_options end def run(event = nil) if event == Dynflow::Action::Cancellable::Cancel output[:message] = "I was cancelled but we don't care" else super end end def on_finish if input[:config_options][:get_stuck] puts <<-MSG.gsub(/^.*\|/, '') | Execution plan #{execution_plan_id} got stuck | You can cancel the stucked step at | #{ExampleHelper::DYNFLOW_URL}/#{execution_plan_id} MSG # we suspend the action but don't plan the wakeup event, # causing it to wait forever (till we cancel it) suspend end end end end if $0 == __FILE__ ExampleHelper.world.trigger(OrchestrateEvented::CreateInfrastructure) ExampleHelper.world.trigger(OrchestrateEvented::CreateInfrastructure, true) puts example_description ExampleHelper.run_web_console end
ruby
MIT
e14dcdfe57cec99cc78b2f6ab521f00809b1408a
2026-01-04T17:50:16.326730Z
false
Dynflow/dynflow
https://github.com/Dynflow/dynflow/blob/e14dcdfe57cec99cc78b2f6ab521f00809b1408a/examples/execution_plan_chaining.rb
examples/execution_plan_chaining.rb
#!/usr/bin/env ruby # frozen_string_literal: true require_relative 'example_helper' class DelayedAction < Dynflow::Action def plan(should_fail = false) plan_self :should_fail => should_fail end def run sleep 5 raise "Controlled failure" if input[:should_fail] end def rescue_strategy Dynflow::Action::Rescue::Fail end end if $PROGRAM_NAME == __FILE__ world = ExampleHelper.create_world do |config| config.auto_rescue = true end world.action_logger.level = 1 world.logger.level = 0 plan1 = world.trigger(DelayedAction) plan2 = world.chain(plan1.execution_plan_id, DelayedAction) plan3 = world.chain(plan2.execution_plan_id, DelayedAction) plan4 = world.chain(plan2.execution_plan_id, DelayedAction) plan5 = world.trigger(DelayedAction, true) plan6 = world.chain(plan5.execution_plan_id, DelayedAction) puts <<-MSG.gsub(/^.*\|/, '') | | Execution Plan Chaining example | ======================== | | This example shows the execution plan chaining functionality of Dynflow, which allows execution plans to wait until another execution plan finishes. | | Execution plans: | #{plan1.id} runs immediately and should run successfully. | #{plan2.id} is delayed and should run once #{plan1.id} finishes. | #{plan3.id} and #{plan4.id} are delayed and should run once #{plan2.id} finishes. | | #{plan5.id} runs immediately and is expected to fail. | #{plan6.id} should not run at all as its prerequisite failed. | | Visit #{ExampleHelper::DYNFLOW_URL} to see their status. | MSG ExampleHelper.run_web_console(world) end
ruby
MIT
e14dcdfe57cec99cc78b2f6ab521f00809b1408a
2026-01-04T17:50:16.326730Z
false
Dynflow/dynflow
https://github.com/Dynflow/dynflow/blob/e14dcdfe57cec99cc78b2f6ab521f00809b1408a/examples/orchestrate.rb
examples/orchestrate.rb
#!/usr/bin/env ruby # frozen_string_literal: true example_description = <<DESC Orchestrate Example =================== This example simulates a workflow of setting up an infrastructure, using more high-level steps in CreateInfrastructure, that expand to smaller steps of PrepareDisk, CraeteVM etc. It shows the possibility to run the independend actions concurrently, chaining the actions (passing the output of PrepareDisk action to CreateVM, automatically detecting the dependency making sure to run the one before the other). It also simulates a failure and demonstrates the Dynflow ability to rescue from the error and consinue with the run. Once the Sinatra web console starts, you can navigate to #{ExampleHelper::DYNFLOW_URL} to see what's happening in the Dynflow world. DESC require_relative 'example_helper' module Orchestrate class CreateInfrastructure < Dynflow::Action def plan sequence do concurrence do plan_action(CreateMachine, 'host1', 'db') plan_action(CreateMachine, 'host2', 'storage') end plan_action(CreateMachine, 'host3', 'web_server', :db_machine => 'host1', :storage_machine => 'host2') end end end class CreateMachine < Dynflow::Action def plan(name, profile, config_options = {}) prepare_disk = plan_action(PrepareDisk, 'name' => name) create_vm = plan_action(CreateVM, :name => name, :disk => prepare_disk.output['path']) plan_action(AddIPtoHosts, :name => name, :ip => create_vm.output[:ip]) plan_action(ConfigureMachine, :ip => create_vm.output[:ip], :profile => profile, :config_options => config_options) plan_self(:name => name) end def finalize # this is called after run methods of the actions in the # execution plan were finished end end class Base < Dynflow::Action def sleep! sleep(rand(2)) end end class PrepareDisk < Base def queue :slow end input_format do param :name end output_format do param :path end def run sleep! output[:path] = "/var/images/#{input[:name]}.img" end end class CreateVM < Base input_format do param :name param :disk end output_format do param :ip end def run sleep! output[:ip] = "192.168.100.#{rand(256)}" end end class AddIPtoHosts < Base input_format do param :ip end def run sleep! end end class ConfigureMachine < Base input_format do param :ip param :profile param :config_options end def run # for demonstration of resuming after error if ExampleHelper.something_should_fail? ExampleHelper.nothing_should_fail! puts <<-MSG.gsub(/^.*\|/, '') | Execution plan #{execution_plan_id} is failing | You can resume it at #{ExampleHelper::DYNFLOW_URL}/#{execution_plan_id} MSG raise "temporary unavailabe" end sleep! end end end if $0 == __FILE__ world = ExampleHelper.create_world ExampleHelper.set_world(world) ExampleHelper.world.action_logger.level = Logger::INFO ExampleHelper.something_should_fail! ExampleHelper.world.trigger(Orchestrate::CreateInfrastructure) Thread.new do 9.times do ExampleHelper.world.trigger(Orchestrate::CreateInfrastructure) end end puts example_description ExampleHelper.run_web_console end
ruby
MIT
e14dcdfe57cec99cc78b2f6ab521f00809b1408a
2026-01-04T17:50:16.326730Z
false
Dynflow/dynflow
https://github.com/Dynflow/dynflow/blob/e14dcdfe57cec99cc78b2f6ab521f00809b1408a/examples/remote_executor.rb
examples/remote_executor.rb
#!/usr/bin/env ruby # -*- coding: utf-8 -*- # frozen_string_literal: true # To run the observer: # # bundle exec ruby ./examples/remote_executor.rb observer # # To run the server: # # bundle exec ruby ./examples/remote_executor.rb server # # To run the client: # # bundle exec ruby ./examples/remote_executor.rb client # # Sidekiq # ======= # # In case of using Sidekiq as async job backend, use this instead of the server command # # To run the orchestrator: # # bundle exec sidekiq -r ./examples/remote_executor.rb -q dynflow_orchestrator # # To run the worker: # # bundle exec sidekiq -r ./examples/remote_executor.rb -q default require_relative 'example_helper' require_relative 'orchestrate_evented' require 'tmpdir' class SampleAction < Dynflow::Action def plan number = rand(1e10) puts "Plannin action: #{number}" plan_self(number: number) end def run puts "Running action: #{input[:number]}" end end class RemoteExecutorExample class << self def run_observer world = ExampleHelper.create_world do |config| config.persistence_adapter = persistence_adapter config.connector = connector config.executor = false end run(world) end def run_server world = ExampleHelper.create_world do |config| config.persistence_adapter = persistence_adapter config.connector = connector end run(world) end def initialize_sidekiq_orchestrator ExampleHelper.create_world do |config| config.persistence_adapter = persistence_adapter config.connector = connector config.executor = ::Dynflow::Executors::Sidekiq::Core config.auto_validity_check = false end end def initialize_sidekiq_worker Sidekiq.configure_server do |config| require 'sidekiq-reliable-fetch' # Use semi-reliable fetch # for details see https://gitlab.com/gitlab-org/sidekiq-reliable-fetch/blob/master/README.md config.options[:semi_reliable_fetch] = true # Do not requeue jobs after sidekiq shutdown config.options[:max_retries_after_interruption] = 0 # Do not store interrupted jobs, just discard them config.options[:interrupted_max_jobs] = 0 Sidekiq::ReliableFetch.setup_reliable_fetch!(config) end ExampleHelper.create_world do |config| config.persistence_adapter = persistence_adapter config.connector = connector config.executor = false end end def run(world) begin ExampleHelper.run_web_console(world) rescue Errno::EADDRINUSE require 'io/console' puts "Running without a web console. Press q<enter> to quit." until STDIN.gets.chomp == 'q' end end end def db_path File.expand_path("../remote_executor_db.sqlite", __FILE__) end def persistence_conn_string ENV['DB_CONN_STRING'] || "sqlite://#{db_path}" end def persistence_adapter Dynflow::PersistenceAdapters::Sequel.new persistence_conn_string end def connector Proc.new { |world| Dynflow::Connectors::Database.new(world) } end def run_client(count) world = ExampleHelper.create_world do |config| config.persistence_adapter = persistence_adapter config.executor = false config.connector = connector end (count || 1000).times do start_time = Time.now world.trigger(SampleAction).finished.wait finished_in = Time.now - start_time puts "Finished in #{finished_in}s" sleep 0.5 end end end end command = ARGV.first || 'server' if $0 == __FILE__ case command when 'observer' puts <<~MSG The observer starting…. You can see what's going on there MSG RemoteExecutorExample.run_observer when 'server' puts <<~MSG The server is starting…. You can send the work to it by running: #{$0} client MSG RemoteExecutorExample.run_server when 'client' RemoteExecutorExample.run_client(ARGV[1]&.to_i) else puts "Unknown command #{comment}" exit 1 end elsif defined?(Sidekiq) # TODO: Sidekiq.default_worker_options = { :retry => 0, 'backtrace' => true } # assuming the remote executor was required as part of initialization # of the ActiveJob worker queues = Sidekiq.configure_server { |c| c.options[:queues] } world = if queues.include?("dynflow_orchestrator") RemoteExecutorExample.initialize_sidekiq_orchestrator elsif (queues - ['dynflow_orchestrator']).any? RemoteExecutorExample.initialize_sidekiq_worker end Sidekiq.configure_server { |c| c.options[:dynflow_world] = world } end
ruby
MIT
e14dcdfe57cec99cc78b2f6ab521f00809b1408a
2026-01-04T17:50:16.326730Z
false
Dynflow/dynflow
https://github.com/Dynflow/dynflow/blob/e14dcdfe57cec99cc78b2f6ab521f00809b1408a/examples/chunked_output_benchmark.rb
examples/chunked_output_benchmark.rb
#!/usr/bin/env ruby # frozen_string_literal: true require_relative 'example_helper' require 'benchmark' WORDS = File.readlines('/usr/share/dict/words').map(&:chomp).freeze COUNT = WORDS.count module Common def main_loop if output[:current] < input[:limit] consumed = yield output[:current] += consumed plan_event(nil) suspend end end def batch WORDS.drop(output[:current]).take(input[:chunk]) end end class Regular < ::Dynflow::Action include Common def run(event = nil) output[:current] ||= 0 output[:words] ||= [] main_loop do words = batch output[:words] << words words.count end end end class Chunked < ::Dynflow::Action include Common def run(event = nil) output[:current] ||= 0 main_loop do words = batch output_chunk(words) words.count end end end if $0 == __FILE__ ExampleHelper.world.action_logger.level = 4 ExampleHelper.world.logger.level = 4 Benchmark.bm do |bm| bm.report('regular 1000 by 100') { ExampleHelper.world.trigger(Regular, limit: 1000, chunk: 100).finished.wait } bm.report('chunked 1000 by 100') { ExampleHelper.world.trigger(Chunked, limit: 1000, chunk: 100).finished.wait } bm.report('regular 10_000 by 100') { ExampleHelper.world.trigger(Regular, limit: 10_000, chunk: 100).finished.wait } bm.report('chunked 10_000 by 100') { ExampleHelper.world.trigger(Chunked, limit: 10_000, chunk: 100).finished.wait } bm.report('regular 10_000 by 1000') { ExampleHelper.world.trigger(Regular, limit: 10_000, chunk: 1000).finished.wait } bm.report('chunked 10_000 by 1000') { ExampleHelper.world.trigger(Chunked, limit: 10_000, chunk: 1000).finished.wait } bm.report('regular 100_000 by 100') { ExampleHelper.world.trigger(Regular, limit: 100_000, chunk: 100).finished.wait } bm.report('chunked 100_000 by 100') { ExampleHelper.world.trigger(Chunked, limit: 100_000, chunk: 100).finished.wait } bm.report('regular 100_000 by 1000') { ExampleHelper.world.trigger(Regular, limit: 100_000, chunk: 1000).finished.wait } bm.report('chunked 100_000 by 1000') { ExampleHelper.world.trigger(Chunked, limit: 100_000, chunk: 1000).finished.wait } bm.report('regular 100_000 by 10_000') { ExampleHelper.world.trigger(Regular, limit: 100_000, chunk: 10_000).finished.wait } bm.report('chunked 100_000 by 10_000') { ExampleHelper.world.trigger(Chunked, limit: 100_000, chunk: 10_000).finished.wait } end end
ruby
MIT
e14dcdfe57cec99cc78b2f6ab521f00809b1408a
2026-01-04T17:50:16.326730Z
false
Dynflow/dynflow
https://github.com/Dynflow/dynflow/blob/e14dcdfe57cec99cc78b2f6ab521f00809b1408a/examples/sub_plans.rb
examples/sub_plans.rb
#!/usr/bin/env ruby # frozen_string_literal: true example_description = <<DESC Sub Plans Example =================== This example shows, how to trigger the execution plans from within a run method of some action and waing for them to finish. This is useful, when doing bulk actions, where having one big execution plan would not be effective, or in case all the data are not available by the time of original action planning. DESC require_relative 'example_helper' require_relative 'orchestrate_evented' COUNT = (ARGV[0] || 25).to_i class SubPlansExample < Dynflow::Action include Dynflow::Action::WithSubPlans include Dynflow::Action::WithBulkSubPlans def create_sub_plans current_batch.map { |i| trigger(OrchestrateEvented::CreateMachine, "host-#{i}", 'web_server') } end def batch_size 5 end def batch(from, size) COUNT.times.drop(from).take(size) end def total_count COUNT end end class PollingSubPlansExample < SubPlansExample include Dynflow::Action::WithPollingSubPlans end if $0 == __FILE__ ExampleHelper.world.action_logger.level = Logger::INFO ExampleHelper.world t1 = ExampleHelper.world.trigger(SubPlansExample) t2 = ExampleHelper.world.trigger(PollingSubPlansExample) puts example_description puts <<-MSG.gsub(/^.*\|/, '') | Execution plans #{t1.id} and #{t2.id} with sub plans triggered | You can see the details at | #{ExampleHelper::DYNFLOW_URL}/#{t2.id} | #{ExampleHelper::DYNFLOW_URL}/#{t1.id} MSG ExampleHelper.run_web_console end
ruby
MIT
e14dcdfe57cec99cc78b2f6ab521f00809b1408a
2026-01-04T17:50:16.326730Z
false
Dynflow/dynflow
https://github.com/Dynflow/dynflow/blob/e14dcdfe57cec99cc78b2f6ab521f00809b1408a/examples/sub_plan_concurrency_control.rb
examples/sub_plan_concurrency_control.rb
#!/usr/bin/env ruby # frozen_string_literal: true example_description = <<DESC Sub-plan Concurrency Control Example ==================================== This example shows, how an action with sub-plans can be used to control concurrency level and tasks distribution over time. This is useful, when doing resource-intensive bulk actions, where running all actions at once would drain the system's resources. DESC require_relative 'example_helper' class CostyAction < Dynflow::Action SleepTime = 10 def plan(number) action_logger.info("#{number} PLAN") plan_self(:number => number) end def run(event = nil) unless output.key? :slept output[:slept] = true suspend do |suspended_action| action_logger.info("#{input[:number]} SLEEP") world.clock.ping(suspended_action, SleepTime) end end end def finalize action_logger.info("#{input[:number]} DONE") end end class ConcurrencyControlExample < Dynflow::Action include Dynflow::Action::WithSubPlans ConcurrencyLevel = 2 RunWithin = 2 * 60 def plan(count) limit_concurrency_level(ConcurrencyLevel) distribute_over_time(RunWithin) super(:count => count) end def create_sub_plans sleep 1 input[:count].times.map { |i| trigger(CostyAction, i) } end end if $0 == __FILE__ ExampleHelper.world.action_logger.level = Logger::INFO triggered = ExampleHelper.world.trigger(ConcurrencyControlExample, 10) puts example_description puts <<-MSG.gsub(/^.*\|/, '') | Execution plan #{triggered.id} with 10 sub plans triggered | You can see the details at #{ExampleHelper::DYNFLOW_URL}/#{triggered.id}/actions/1/sub_plans | Or simply watch in the console that there are never more than #{ConcurrencyControlExample::ConcurrencyLevel} running at the same time. | | The tasks are distributed over #{ConcurrencyControlExample::RunWithin} seconds. MSG ExampleHelper.run_web_console end
ruby
MIT
e14dcdfe57cec99cc78b2f6ab521f00809b1408a
2026-01-04T17:50:16.326730Z
false
Dynflow/dynflow
https://github.com/Dynflow/dynflow/blob/e14dcdfe57cec99cc78b2f6ab521f00809b1408a/examples/termination.rb
examples/termination.rb
#!/usr/bin/env ruby # frozen_string_literal: true require_relative 'example_helper' class Sleeper < Dynflow::Action def run(event = nil) sleep end end def report(msg) puts "===== #{Time.now}: #{msg}" end if $0 == __FILE__ ExampleHelper.world.action_logger.level = 1 ExampleHelper.world.logger.level = 0 ExampleHelper.world.trigger(Sleeper) report "Sleeping" sleep 5 report "Asking to terminate" ExampleHelper.world.terminate.wait report "Terminated" end
ruby
MIT
e14dcdfe57cec99cc78b2f6ab521f00809b1408a
2026-01-04T17:50:16.326730Z
false
Dynflow/dynflow
https://github.com/Dynflow/dynflow/blob/e14dcdfe57cec99cc78b2f6ab521f00809b1408a/examples/singletons.rb
examples/singletons.rb
#!/usr/bin/env ruby # frozen_string_literal: true example_description = <<DESC Sub Plans Example =================== This example shows, how singleton actions can be used for making sure there is only one instance of the action running at a time. Singleton actions try to obtain a lock at the beggining of their plan phase and fail if they can't do so. In run phase they check if they have the lock and try to acquire it again if they don't. These actions release the lock at the end of their finalize phase. DESC require_relative 'example_helper' class SingletonExample < Dynflow::Action include Dynflow::Action::Singleton def run sleep 10 end end class SingletonExampleA < SingletonExample; end class SingletonExampleB < SingletonExample; end if $0 == __FILE__ ExampleHelper.world.action_logger.level = Logger::INFO ExampleHelper.world t1 = ExampleHelper.world.trigger(SingletonExampleA) t2 = ExampleHelper.world.trigger(SingletonExampleA) ExampleHelper.world.trigger(SingletonExampleA) unless SingletonExampleA.singleton_locked?(ExampleHelper.world) t3 = ExampleHelper.world.trigger(SingletonExampleB) db = ExampleHelper.world.persistence.adapter.db puts example_description puts <<-MSG.gsub(/^.*\|/, '') | 3 execution plans were triggered: | #{t1.id} should finish successfully | #{t3.id} should finish successfully because it is a singleton of different class | #{t2.id} should fail because #{t1.id} holds the lock | | You can see the details at | #{ExampleHelper::DYNFLOW_URL}/#{t1.id} | #{ExampleHelper::DYNFLOW_URL}/#{t2.id} | #{ExampleHelper::DYNFLOW_URL}/#{t3.id} | MSG ExampleHelper.run_web_console end
ruby
MIT
e14dcdfe57cec99cc78b2f6ab521f00809b1408a
2026-01-04T17:50:16.326730Z
false
Dynflow/dynflow
https://github.com/Dynflow/dynflow/blob/e14dcdfe57cec99cc78b2f6ab521f00809b1408a/examples/example_helper.rb
examples/example_helper.rb
# frozen_string_literal: true $:.unshift(File.expand_path('../../lib', __FILE__)) require 'dynflow' class ExampleHelper CONSOLE_URL = 'http://localhost:4567' DYNFLOW_URL = "#{CONSOLE_URL}/dynflow" SIDEKIQ_URL = "#{CONSOLE_URL}/sidekiq" class << self def world @world ||= create_world end def set_world(world) @world = world end def create_world config = Dynflow::Config.new config.persistence_adapter = persistence_adapter config.logger_adapter = logger_adapter config.auto_rescue = false config.telemetry_adapter = telemetry_adapter config.queues.add(:slow, :pool_size => 3) yield config if block_given? Dynflow::World.new(config).tap do |world| puts "World #{world.id} started..." end end def persistence_conn_string ENV['DB_CONN_STRING'] || 'sqlite:/' end def telemetry_adapter if (host = ENV['TELEMETRY_STATSD_HOST']) Dynflow::TelemetryAdapters::StatsD.new host else Dynflow::TelemetryAdapters::Dummy.new end end def persistence_adapter Dynflow::PersistenceAdapters::Sequel.new persistence_conn_string end def logger_adapter Dynflow::LoggerAdapters::Simple.new $stdout, Logger::DEBUG end def run_web_console(world = ExampleHelper.world) require 'dynflow/web' dynflow_console = Dynflow::Web.setup do set :world, world end apps = { '/dynflow' => dynflow_console } puts "Starting Dynflow console at #{DYNFLOW_URL}" begin require 'sidekiq/web' apps['/sidekiq'] = Sidekiq::Web puts "Starting Sidekiq console at #{SIDEKIQ_URL}" rescue LoadError puts 'Sidekiq not around, not mounting the console' end app = Rack::URLMap.new(apps) Rack::Server.new(:app => app, :Host => '0.0.0.0', :Port => URI.parse(CONSOLE_URL).port).start end # for simulation of the execution failing for the first time def something_should_fail! @should_fail = true end # for simulation of the execution failing for the first time def something_should_fail? @should_fail end def nothing_should_fail! @should_fail = false end def terminate @world.terminate.wait if @world end end end at_exit { ExampleHelper.terminate }
ruby
MIT
e14dcdfe57cec99cc78b2f6ab521f00809b1408a
2026-01-04T17:50:16.326730Z
false
Dynflow/dynflow
https://github.com/Dynflow/dynflow/blob/e14dcdfe57cec99cc78b2f6ab521f00809b1408a/lib/dynflow.rb
lib/dynflow.rb
# frozen_string_literal: true require 'algebrick' require 'set' require 'base64' require 'concurrent' require 'concurrent-edge' logger = Logger.new($stderr) logger.level = Logger::INFO Concurrent.global_logger = lambda do |level, progname, message = nil, &block| logger.add level, message, progname, &block end # TODO validate in/output, also validate unknown keys # TODO performance testing, how many actions will it handle? # TODO profiling, find bottlenecks # FIND change ids to uuid, uuid-<action_id>, uuid-<action_id-(plan, run, finalize) module Dynflow class << self # Return the world that representing this process - this is mainly used by # Sidekiq deployments, where there is a need for a global-level context. # # @return [Dynflow::World, nil] def process_world return @process_world if defined? @process_world @process_world = Sidekiq.configure_server { |c| c[:dynflow_world] } raise "process world is not set" unless @process_world @process_world end end class Error < StandardError def to_hash { class: self.class.name, message: message, backtrace: backtrace } end def self.from_hash(hash) self.new(hash[:message]).tap { |e| e.set_backtrace(hash[:backtrace]) } end end require 'dynflow/utils' require 'dynflow/round_robin' require 'dynflow/dead_letter_silencer' require 'dynflow/actor' require 'dynflow/actors' require 'dynflow/errors' require 'dynflow/serializer' require 'dynflow/serializable' require 'dynflow/clock' require 'dynflow/stateful' require 'dynflow/transaction_adapters' require 'dynflow/coordinator' require 'dynflow/persistence' require 'dynflow/middleware' require 'dynflow/flows' require 'dynflow/execution_history' require 'dynflow/execution_plan' require 'dynflow/delayed_plan' require 'dynflow/action' require 'dynflow/director' require 'dynflow/executors' require 'dynflow/logger_adapters' require 'dynflow/world' require 'dynflow/connectors' require 'dynflow/dispatcher' require 'dynflow/serializers' require 'dynflow/delayed_executors' require 'dynflow/semaphores' require 'dynflow/throttle_limiter' require 'dynflow/telemetry' require 'dynflow/config' require 'dynflow/extensions' if defined? ::ActiveJob require 'dynflow/active_job/queue_adapter' class Railtie < ::Rails::Railtie config.before_initialize do ::ActiveJob::QueueAdapters.include Dynflow::ActiveJob::QueueAdapters end end end if defined? Rails require 'dynflow/rails' end end
ruby
MIT
e14dcdfe57cec99cc78b2f6ab521f00809b1408a
2026-01-04T17:50:16.326730Z
false
Dynflow/dynflow
https://github.com/Dynflow/dynflow/blob/e14dcdfe57cec99cc78b2f6ab521f00809b1408a/lib/dynflow/clock.rb
lib/dynflow/clock.rb
# frozen_string_literal: true module Dynflow class Clock < Actor include Algebrick::Types Timer = Algebrick.type do fields! who: Object, # to ping back when: Time, # to deliver what: Maybe[Object], # to send where: Symbol # it should be delivered, which method end module Timer def self.[](*fields) super(*fields).tap { |v| Match! v.who, ->who { who.respond_to? v.where } } end include Comparable def <=>(other) Type! other, self.class self.when <=> other.when end def eql?(other) object_id == other.object_id end def hash object_id end def apply if Algebrick::Some[Object] === what who.send where, what.value else who.send where end end end def initialize(logger = nil) @logger = logger @timers = Utils::PriorityQueue.new { |a, b| b <=> a } end def default_reference_class ClockReference end def on_event(event) wakeup if event == :terminated end def tick run_ready_timers sleep_to first_timer end def add_timer(timer) @timers.push timer if @timers.size == 1 sleep_to timer else wakeup if timer == first_timer end end private def run_ready_timers while first_timer && first_timer.when <= Time.now begin first_timer.apply rescue => e @logger && @logger.error("Failed to apply clock event #{first_timer}, exception: #{e}") end @timers.pop end end def first_timer @timers.top end def wakeup if @timer @timer.cancel tick unless terminating? end end def sleep_to(timer) return unless timer schedule(timer.when - Time.now) { reference.tell(:tick) unless terminating? } nil end def schedule(delay, &block) @timer = if delay.positive? Concurrent::ScheduledTask.execute(delay, &block) else yield nil end end end class ClockReference < Concurrent::Actor::Reference include Algebrick::Types def current_time Time.now end def ping(who, time, with_what = nil, where = :<<, optional: false) Type! time, Time, Numeric time = current_time + time if time.is_a? Numeric if who.is_a?(Action::Suspended) who.plan_event(with_what, time, optional: optional) else timer = Clock::Timer[who, time, with_what.nil? ? Algebrick::Types::None : Some[Object][with_what], where] self.tell([:add_timer, timer]) end end end end
ruby
MIT
e14dcdfe57cec99cc78b2f6ab521f00809b1408a
2026-01-04T17:50:16.326730Z
false
Dynflow/dynflow
https://github.com/Dynflow/dynflow/blob/e14dcdfe57cec99cc78b2f6ab521f00809b1408a/lib/dynflow/persistence.rb
lib/dynflow/persistence.rb
# frozen_string_literal: true require 'dynflow/persistence_adapters' module Dynflow class Persistence include Algebrick::TypeCheck attr_reader :adapter def initialize(world, persistence_adapter, options = {}) @world = world @adapter = persistence_adapter @adapter.register_world(world) @backup_deleted_plans = options.fetch(:backup_deleted_plans, false) @backup_dir = options.fetch(:backup_dir, './backup') end def load_action(step) attributes = adapter .load_action(step.execution_plan_id, step.action_id) .update(step: step, phase: step.phase) return Action.from_hash(attributes, step.world) end def load_actions(execution_plan, action_ids) attributes = adapter.load_actions(execution_plan.id, action_ids) attributes.map do |action| Action.from_hash(action.merge(phase: Action::Present, execution_plan: execution_plan), @world) end end def load_action_for_presentation(execution_plan, action_id, step = nil) attributes = adapter.load_action(execution_plan.id, action_id) Action.from_hash(attributes.update(phase: Action::Present, execution_plan: execution_plan, step: step), @world).tap do |present_action| @world.middleware.execute(:present, present_action) {} end end def load_actions_attributes(execution_plan_id, attributes) adapter.load_actions_attributes(execution_plan_id, attributes).reject(&:empty?) end def save_action(execution_plan_id, action) adapter.save_action(execution_plan_id, action.id, action.to_hash) end def save_output_chunks(execution_plan_id, action_id, chunks) return if chunks.empty? adapter.save_output_chunks(execution_plan_id, action_id, chunks) end def load_output_chunks(execution_plan_id, action_id) adapter.load_output_chunks(execution_plan_id, action_id) end def delete_output_chunks(execution_plan_id, action_id) adapter.delete_output_chunks(execution_plan_id, action_id) end def find_execution_plans(options) adapter.find_execution_plans(options).map do |execution_plan_hash| ExecutionPlan.new_from_hash(execution_plan_hash, @world) end end def find_execution_plan_statuses(options) adapter.find_execution_plan_statuses(options) end def find_execution_plan_counts(options) adapter.find_execution_plan_counts(options) end def find_execution_plan_counts_after(timestamp, options) adapter.find_execution_plan_counts_after(timestamp, options) end def delete_execution_plans(filters, batch_size = 1000, enforce_backup_dir = nil) backup_dir = enforce_backup_dir || current_backup_dir adapter.delete_execution_plans(filters, batch_size, backup_dir) end def current_backup_dir @backup_deleted_plans ? File.join(@backup_dir, Date.today.strftime('%Y%m%d')) : nil end def load_execution_plan(id) execution_plan_hash = adapter.load_execution_plan(id) ExecutionPlan.new_from_hash(execution_plan_hash, @world) end def save_execution_plan(execution_plan) adapter.save_execution_plan(execution_plan.id, execution_plan.to_hash) end def find_old_execution_plans(age) adapter.find_old_execution_plans(age).map do |plan| ExecutionPlan.new_from_hash(plan, @world) end end def find_execution_plan_dependencies(execution_plan_id) adapter.find_execution_plan_dependencies(execution_plan_id) end def find_blocked_execution_plans(execution_plan_id) adapter.find_blocked_execution_plans(execution_plan_id) end def find_ready_delayed_plans(time) adapter.find_ready_delayed_plans(time).map do |plan| DelayedPlan.new_from_hash(@world, plan) end end def delete_delayed_plans(filters, batch_size = 1000) adapter.delete_delayed_plans(filters, batch_size) end def save_delayed_plan(delayed_plan) adapter.save_delayed_plan(delayed_plan.execution_plan_uuid, delayed_plan.to_hash) end def set_delayed_plan_frozen(execution_plan_id, frozen = true, new_start_at = nil) plan = load_delayed_plan(execution_plan_id) plan.frozen = frozen plan.start_at = new_start_at if new_start_at save_delayed_plan(plan) end def load_delayed_plan(execution_plan_id) hash = adapter.load_delayed_plan(execution_plan_id) return nil unless hash DelayedPlan.new_from_hash(@world, hash) end def load_step(execution_plan_id, step_id, world) step_hash = adapter.load_step(execution_plan_id, step_id) ExecutionPlan::Steps::Abstract.from_hash(step_hash, execution_plan_id, world) end def load_steps(execution_plan_id, world) adapter.load_steps(execution_plan_id).map do |step_hash| ExecutionPlan::Steps::Abstract.from_hash(step_hash, execution_plan_id, world) end end def save_step(step, conditions = {}) adapter.save_step(step.execution_plan_id, step.id, step.to_hash, conditions) end def push_envelope(envelope) Type! envelope, Dispatcher::Envelope adapter.push_envelope(Dynflow.serializer.dump(envelope)) end def pull_envelopes(world_id) adapter.pull_envelopes(world_id).map do |data| envelope = Dynflow.serializer.load(data) Type! envelope, Dispatcher::Envelope envelope end end def prune_envelopes(receiver_ids) adapter.prune_envelopes(receiver_ids) end def prune_undeliverable_envelopes adapter.prune_undeliverable_envelopes end def chain_execution_plan(first, second) adapter.chain_execution_plan(first, second) end end end
ruby
MIT
e14dcdfe57cec99cc78b2f6ab521f00809b1408a
2026-01-04T17:50:16.326730Z
false
Dynflow/dynflow
https://github.com/Dynflow/dynflow/blob/e14dcdfe57cec99cc78b2f6ab521f00809b1408a/lib/dynflow/coordinator_adapters.rb
lib/dynflow/coordinator_adapters.rb
# frozen_string_literal: true module Dynflow module CoordinatorAdapters require 'dynflow/coordinator_adapters/abstract' require 'dynflow/coordinator_adapters/sequel' end end
ruby
MIT
e14dcdfe57cec99cc78b2f6ab521f00809b1408a
2026-01-04T17:50:16.326730Z
false
Dynflow/dynflow
https://github.com/Dynflow/dynflow/blob/e14dcdfe57cec99cc78b2f6ab521f00809b1408a/lib/dynflow/serializable.rb
lib/dynflow/serializable.rb
# frozen_string_literal: true require 'date' module Dynflow class Serializable TIME_FORMAT = '%Y-%m-%d %H:%M:%S.%L' LEGACY_TIME_FORMAT = '%Y-%m-%d %H:%M:%S' def self.from_hash(hash, *args) check_class_key_present hash constantize(hash[:class]).new_from_hash(hash, *args) end def to_hash raise NotImplementedError end # @api private def self.new_from_hash(hash, *args) raise NotImplementedError # new ... end def self.check_class_matching(hash) check_class_key_present hash unless self.to_s == hash[:class] raise ArgumentError, "class mismatch #{hash[:class]} != #{self}" end end def self.check_class_key_present(hash) raise ArgumentError, "missing :class in #{hash.inspect}" unless hash[:class] end def self.constantize(action_name) Utils.constantize(action_name) end private_class_method :check_class_matching, :check_class_key_present private # recursively traverses hash-array structure and converts all to hashes # accepts more hashes which are then merged def recursive_to_hash(*values) if values.size == 1 value = values.first case value when Hash value.inject({}) { |h, (k, v)| h.update k => recursive_to_hash(v) } when Array value.map { |v| recursive_to_hash v } when ->(v) { v.respond_to?(:to_msgpack) } value else value.to_hash end else values.all? { |v| Type! v, Hash, NilClass } recursive_to_hash(values.compact.reduce { |h, v| h.merge v }) end end def self.string_to_time(string) return if string.nil? return string if string.is_a?(Time) time = begin DateTime.strptime(string, TIME_FORMAT) rescue ArgumentError => _ DateTime.strptime(string, LEGACY_TIME_FORMAT) end time.to_time.utc end def time_to_str(time) return if time.nil? Type! time, Time time.utc.strftime(TIME_FORMAT) end def self.hash_to_error(hash) return nil if hash.nil? ExecutionPlan::Steps::Error.from_hash(hash) end private_class_method :string_to_time, :hash_to_error end end
ruby
MIT
e14dcdfe57cec99cc78b2f6ab521f00809b1408a
2026-01-04T17:50:16.326730Z
false
Dynflow/dynflow
https://github.com/Dynflow/dynflow/blob/e14dcdfe57cec99cc78b2f6ab521f00809b1408a/lib/dynflow/director.rb
lib/dynflow/director.rb
# frozen_string_literal: true module Dynflow # Director is responsible for telling what to do next when: # * new execution starts # * an event accurs # * some work is finished # # It's public methods (except terminate) return work items that the # executor should understand class Director include Algebrick::TypeCheck Event = Algebrick.type do fields! request_id: String, execution_plan_id: String, step_id: Integer, event: Object, result: Concurrent::Promises::ResolvableFuture, optional: Algebrick::Types::Boolean end UnprocessableEvent = Class.new(Dynflow::Error) class WorkItem < Serializable attr_reader :execution_plan_id, :queue, :sender_orchestrator_id def initialize(execution_plan_id, queue, sender_orchestrator_id) @execution_plan_id = execution_plan_id @queue = queue @sender_orchestrator_id = sender_orchestrator_id end def world raise "World expected but not set for the work item #{self}" unless @world @world end # the world to be used for execution purposes of the step. Setting it separately and explicitly # as the world can't be serialized def world=(world) @world = world end def execute raise NotImplementedError end def to_hash { class: self.class.name, execution_plan_id: execution_plan_id, queue: queue, sender_orchestrator_id: sender_orchestrator_id } end def self.new_from_hash(hash, *_args) self.new(hash[:execution_plan_id], hash[:queue], hash[:sender_orchestrator_id]) end end class StepWorkItem < WorkItem attr_reader :step def initialize(execution_plan_id, step, queue, sender_orchestrator_id) super(execution_plan_id, queue, sender_orchestrator_id) @step = step end def execute @step.execute(nil) end def to_hash super.merge(step: step.to_hash) end def self.new_from_hash(hash, *_args) self.new(hash[:execution_plan_id], Serializable.from_hash(hash[:step], hash[:execution_plan_id], Dynflow.process_world), hash[:queue], hash[:sender_orchestrator_id]) end end class EventWorkItem < StepWorkItem attr_reader :event, :request_id def initialize(request_id, execution_plan_id, step, event, queue, sender_orchestrator_id) super(execution_plan_id, step, queue, sender_orchestrator_id) @event = event @request_id = request_id end def execute @step.execute(@event) end def to_hash super.merge(request_id: @request_id, event: Dynflow.serializer.dump(@event)) end def self.new_from_hash(hash, *_args) self.new(hash[:request_id], hash[:execution_plan_id], Serializable.from_hash(hash[:step], hash[:execution_plan_id], Dynflow.process_world), Dynflow.serializer.load(hash[:event]), hash[:queue], hash[:sender_orchestrator_id]) end end class PlanningWorkItem < WorkItem def execute plan = world.persistence.load_delayed_plan(execution_plan_id) return if plan.nil? || plan.execution_plan.state != :scheduled if plan.start_before.nil? blocker_ids = world.persistence.find_execution_plan_dependencies(execution_plan_id) statuses = world.persistence.find_execution_plan_statuses({ filters: { uuid: blocker_ids } }) failed = statuses.select { |_uuid, status| status[:state] == 'stopped' && status[:result] == 'error' } if failed.any? plan.failed_dependencies(failed.keys) return end elsif plan.start_before < Time.now.utc() plan.timeout return end world.coordinator.acquire(Coordinator::PlanningLock.new(world, plan.execution_plan_uuid)) do plan.plan end plan.execute rescue => e world.logger.warn e.message world.logger.debug e.backtrace.join("\n") end end class FinalizeWorkItem < WorkItem attr_reader :finalize_steps_data # @param finalize_steps_data - used to pass the result steps from the worker back to orchestrator def initialize(execution_plan_id, queue, sender_orchestrator_id, finalize_steps_data = nil) super(execution_plan_id, queue, sender_orchestrator_id) @finalize_steps_data = finalize_steps_data end def execute execution_plan = world.persistence.load_execution_plan(execution_plan_id) manager = Director::SequentialManager.new(world, execution_plan) manager.finalize @finalize_steps_data = manager.finalize_steps.map(&:to_hash) end def to_hash super.merge(finalize_steps_data: @finalize_steps_data) end def self.new_from_hash(hash, *_args) self.new(*hash.values_at(:execution_plan_id, :queue, :sender_orchestrator_id, :finalize_steps_data)) end end require 'dynflow/director/queue_hash' require 'dynflow/director/sequence_cursor' require 'dynflow/director/flow_manager' require 'dynflow/director/execution_plan_manager' require 'dynflow/director/sequential_manager' require 'dynflow/director/running_steps_manager' attr_reader :logger def initialize(world) @world = world @logger = world.logger @execution_plan_managers = {} @rescued_steps = {} @planning_plans = Set.new end def current_execution_plan_ids @execution_plan_managers.keys end def handle_planning(execution_plan_uuid) return [] if @planning_plans.include? execution_plan_uuid @planning_plans << execution_plan_uuid [PlanningWorkItem.new(execution_plan_uuid, :default, @world.id)] end def start_execution(execution_plan_id, finished) manager = track_execution_plan(execution_plan_id, finished) return [] unless manager unless_done(manager, manager.start) end def handle_event(event) Type! event, Event execution_plan_manager = @execution_plan_managers[event.execution_plan_id] if execution_plan_manager execution_plan_manager.event(event) elsif event.optional event.result.reject "no manager for #{event.inspect}" [] else raise Dynflow::Error, "no manager for #{event.inspect}" end rescue Dynflow::Error => e event.result.reject e.message raise e end def work_finished(work) case work when PlanningWorkItem @planning_plans.delete(work.execution_plan_id) @world.persistence.delete_delayed_plans(:execution_plan_uuid => work.execution_plan_id) [] else manager = @execution_plan_managers[work.execution_plan_id] return [] unless manager # skip case when getting event from execution plan that is not running anymore unless_done(manager, manager.what_is_next(work)) end end # called when there was an unhandled exception during the execution # of the work (such as persistence issue) - in this case we just clean up the # runtime from the execution plan and let it go (common cause for this is the execution # plan being removed from database by external user) def work_failed(work) if (manager = @execution_plan_managers[work.execution_plan_id]) manager.terminate # Don't try to store when the execution plan went missing plan_missing = @world.persistence.find_execution_plans(:filters => { uuid: work.execution_plan_id }).empty? finish_manager(manager, store: !plan_missing) end end def terminate unless @execution_plan_managers.empty? logger.error "... cleaning #{@execution_plan_managers.size} execution plans ..." begin @execution_plan_managers.values.each do |manager| manager.terminate end rescue Errors::PersistenceError logger.error "could not to clean the data properly" end @execution_plan_managers.values.each do |manager| finish_manager(manager) end end end def halt(event) halt_execution(event.execution_plan_id) end private def halt_execution(execution_plan_id) manager = @execution_plan_managers[execution_plan_id] @logger.warn "Halting execution plan #{execution_plan_id}" return halt_inactive(execution_plan_id) unless manager manager.halt finish_manager manager end def halt_inactive(execution_plan_id) plan = @world.persistence.load_execution_plan(execution_plan_id) plan.update_state(:stopped) rescue => e @logger.error e end def unless_done(manager, work_items) return [] unless manager if manager.done? try_to_rescue(manager) || finish_manager(manager) else return work_items end end def try_to_rescue(manager) rescue!(manager) if rescue?(manager) end def finish_manager(manager, store: true) update_execution_plan_state(manager) if store return [] ensure @execution_plan_managers.delete(manager.execution_plan.id) set_future(manager) end def rescue?(manager) if @world.terminating? || !(@world.auto_rescue && manager.execution_plan.error?) false elsif !@rescued_steps.key?(manager.execution_plan.id) # we have not rescued this plan yet true else # we have rescued this plan already, but a different step has failed now # we do this check to prevent endless loop, if we always failed on the same steps failed_step_ids = manager.execution_plan.failed_steps.map(&:id).to_set (failed_step_ids - @rescued_steps[manager.execution_plan.id]).any? end end def rescue!(manager) # TODO: after moving to concurrent-ruby actors, there should be better place # to put this logic of making sure we don't run rescues in endless loop @rescued_steps[manager.execution_plan.id] ||= Set.new @rescued_steps[manager.execution_plan.id].merge(manager.execution_plan.failed_steps.map(&:id)) new_state = manager.execution_plan.prepare_for_rescue if new_state == :running return manager.restart else manager.execution_plan.update_state(new_state) return false end end def track_execution_plan(execution_plan_id, finished) execution_plan = @world.persistence.load_execution_plan(execution_plan_id) if @execution_plan_managers[execution_plan_id] raise Dynflow::Error, "cannot execute execution_plan_id:#{execution_plan_id} it's already running" end if execution_plan.state == :stopped raise Dynflow::Error, "cannot execute execution_plan_id:#{execution_plan_id} it's stopped" end lock_class = Coordinator::ExecutionInhibitionLock filters = { class: lock_class.to_s, owner_id: lock_class.lock_id(execution_plan_id) } if @world.coordinator.find_records(filters).any? halt_execution(execution_plan_id) raise Dynflow::Error, "cannot execute execution_plan_id:#{execution_plan_id} it's execution is inhibited" end @execution_plan_managers[execution_plan_id] = ExecutionPlanManager.new(@world, execution_plan, finished) rescue Dynflow::Error => e finished.reject e nil end def update_execution_plan_state(manager) execution_plan = manager.execution_plan case execution_plan.state when :running if execution_plan.error? execution_plan.update_state(:paused) elsif manager.done? execution_plan.update_state(:stopped) end # If the state is marked as running without errors but manager is not done, # we let the invalidation procedure to handle re-execution on other executor end end def set_future(manager) @rescued_steps.delete(manager.execution_plan.id) manager.future.fulfill manager.execution_plan end end end
ruby
MIT
e14dcdfe57cec99cc78b2f6ab521f00809b1408a
2026-01-04T17:50:16.326730Z
false
Dynflow/dynflow
https://github.com/Dynflow/dynflow/blob/e14dcdfe57cec99cc78b2f6ab521f00809b1408a/lib/dynflow/version.rb
lib/dynflow/version.rb
# frozen_string_literal: true module Dynflow VERSION = '2.0.0' end
ruby
MIT
e14dcdfe57cec99cc78b2f6ab521f00809b1408a
2026-01-04T17:50:16.326730Z
false
Dynflow/dynflow
https://github.com/Dynflow/dynflow/blob/e14dcdfe57cec99cc78b2f6ab521f00809b1408a/lib/dynflow/rails.rb
lib/dynflow/rails.rb
# -*- coding: utf-8 -*- # frozen_string_literal: true module Dynflow # Class for configuring and preparing the Dynflow runtime environment. class Rails require File.expand_path('../rails/configuration', __FILE__) require File.expand_path('../rails/daemon', __FILE__) attr_reader :config def initialize(world_class = nil, config = Rails::Configuration.new) @required = false @config = config @world_class = world_class end # call this method if your engine uses Dynflow def require! @required = true end def required? @required end def initialized? !@world.nil? end def initialize! return unless @required return @world if @world if config.lazy_initialization && defined?(::PhusionPassenger) config.dynflow_logger .warn('Dynflow: lazy loading with PhusionPassenger might lead to unexpected results') end init_world.tap do |world| @world = world config.run_on_init_hooks(false, world) config.increase_db_pool_size(world) unless config.remote? config.run_on_init_hooks(true, world) # leave this just for long-running executors unless config.rake_task_with_executor? invalidated_worlds = world.perform_validity_checks world.auto_execute world.post_initialization if invalidated_worlds > 0 if @world.delayed_executor && !@world.delayed_executor.started? @world.delayed_executor.start end config.run_post_executor_init_hooks(world) end end end end # Mark that the process is executor. This prevents the remote setting from # applying. Needs to be set up before the world is being initialized def executor! @executor = true end def executor? @executor end def reinitialize! @world = nil initialize! end def world return @world if @world initialize! if config.lazy_initialization unless @world raise 'The Dynflow world was not initialized yet. '\ 'If your plugin uses it, make sure to call Rails.application.dynflow.require! '\ 'in some initializer' end @world end attr_writer :world def eager_load_actions! config.eager_load_paths.each do |load_path| Dir.glob("#{load_path}/**/*.rb").sort.each do |file| unless loaded_paths.include?(file) require_dependency file loaded_paths << file end end end @world.reload! if @world end def loaded_paths @loaded_paths ||= Set.new end private def init_world return config.initialize_world(@world_class) if @world_class config.initialize_world end end end
ruby
MIT
e14dcdfe57cec99cc78b2f6ab521f00809b1408a
2026-01-04T17:50:16.326730Z
false
Dynflow/dynflow
https://github.com/Dynflow/dynflow/blob/e14dcdfe57cec99cc78b2f6ab521f00809b1408a/lib/dynflow/extensions.rb
lib/dynflow/extensions.rb
# frozen_string_literal: true module Dynflow module Extensions require 'dynflow/extensions/msgpack' end end
ruby
MIT
e14dcdfe57cec99cc78b2f6ab521f00809b1408a
2026-01-04T17:50:16.326730Z
false
Dynflow/dynflow
https://github.com/Dynflow/dynflow/blob/e14dcdfe57cec99cc78b2f6ab521f00809b1408a/lib/dynflow/throttle_limiter.rb
lib/dynflow/throttle_limiter.rb
# frozen_string_literal: true module Dynflow class ThrottleLimiter attr_reader :core def initialize(world) @world = world spawn end def initialize_plan(plan_id, semaphores_hash) core.tell([:initialize_plan, plan_id, semaphores_hash]) end def finish(plan_id) core.tell([:finish, plan_id]) end def handle_plans!(*args) core.ask!([:handle_plans, *args]) end def cancel!(plan_id) core.tell([:cancel, plan_id]) end def terminate core.ask(:terminate!) end def observe(parent_id = nil) core.ask!([:observe, parent_id]) end def core_class Core end private def spawn Concurrent::Promises.resolvable_future.tap do |initialized| @core = core_class.spawn(:name => 'throttle-limiter', :args => [@world], :initialized => initialized) end end class Core < Actor def initialize(world) @world = world @semaphores = {} end def initialize_plan(plan_id, semaphores_hash) @semaphores[plan_id] = create_semaphores(semaphores_hash) set_up_clock_for(plan_id, true) end def handle_plans(parent_id, planned_ids, failed_ids) failed = failed_ids.map do |plan_id| ::Dynflow::World::Triggered[plan_id, Concurrent::Promises.resolvable_future].tap do |triggered| execute_triggered(triggered) end end planned_ids.map do |child_id| ::Dynflow::World::Triggered[child_id, Concurrent::Promises.resolvable_future].tap do |triggered| triggered.future.on_resolution! { self << [:release, parent_id] } execute_triggered(triggered) if @semaphores[parent_id].wait(triggered) end end + failed end def observe(parent_id = nil) if parent_id.nil? @semaphores.reduce([]) do |acc, cur| acc << { cur.first => cur.last.waiting } end elsif @semaphores.key? parent_id @semaphores[parent_id].waiting else [] end end def release(plan_id, key = :level) return unless @semaphores.key? plan_id set_up_clock_for(plan_id) if key == :time semaphore = @semaphores[plan_id] semaphore.release(1, key) if semaphore.children.key?(key) if semaphore.has_waiting? && semaphore.get == 1 execute_triggered(semaphore.get_waiting) end end def cancel(parent_id, reason = nil) if @semaphores.key?(parent_id) reason ||= 'The task was cancelled.' @semaphores[parent_id].waiting.each do |triggered| cancel_plan_id(triggered.execution_plan_id, reason) triggered.future.reject(reason) end finish(parent_id) end end def finish(parent_id) @semaphores.delete(parent_id) end private def cancel_plan_id(plan_id, reason) plan = @world.persistence.load_execution_plan(plan_id) steps = plan.run_steps steps.each do |step| step.state = :error step.error = ::Dynflow::ExecutionPlan::Steps::Error.new(reason) step.save end plan.update_state(:stopped) plan.save end def execute_triggered(triggered) @world.execute(triggered.execution_plan_id, triggered.finished) end def set_up_clock_for(plan_id, initial = false) if @semaphores[plan_id].children.key? :time timeout_message = 'The task could not be started within the maintenance window.' interval = @semaphores[plan_id].children[:time].meta[:interval] timeout = @semaphores[plan_id].children[:time].meta[:time_span] @world.clock.ping(self, interval, [:release, plan_id, :time]) @world.clock.ping(self, timeout, [:cancel, plan_id, timeout_message]) if initial end end def create_semaphores(hash) semaphores = hash.keys.reduce(Utils.indifferent_hash({})) do |acc, key| acc.merge(key => ::Dynflow::Semaphores::Stateful.new_from_hash(hash[key])) end ::Dynflow::Semaphores::Aggregating.new(semaphores) end end end end
ruby
MIT
e14dcdfe57cec99cc78b2f6ab521f00809b1408a
2026-01-04T17:50:16.326730Z
false
Dynflow/dynflow
https://github.com/Dynflow/dynflow/blob/e14dcdfe57cec99cc78b2f6ab521f00809b1408a/lib/dynflow/errors.rb
lib/dynflow/errors.rb
# frozen_string_literal: true module Dynflow module Errors class RescueError < StandardError; end # placeholder in case the deserialized error is no longer available class UnknownError < StandardError def self.for_exception_class(class_name) Class.new(self) do define_singleton_method :name do class_name end end end def self.inspect "#{UnknownError.name}[#{name}]" end def self.to_s inspect end def inspect "#{self.class.inspect}: #{message}" end end class InactiveWorldError < Dynflow::Error def initialize(world) super("The world #{world.id} is not active (terminating or terminated)") end end class DataConsistencyError < Dynflow::Error end # any persistence errors class PersistenceError < Dynflow::Error def self.delegate(original_exception) self.new("caused by #{original_exception.class}: #{original_exception.message}").tap do |e| e.set_backtrace original_exception.backtrace end end end # persistence errors that can't be recovered from, such as continuous connection issues class FatalPersistenceError < PersistenceError end end end
ruby
MIT
e14dcdfe57cec99cc78b2f6ab521f00809b1408a
2026-01-04T17:50:16.326730Z
false
Dynflow/dynflow
https://github.com/Dynflow/dynflow/blob/e14dcdfe57cec99cc78b2f6ab521f00809b1408a/lib/dynflow/middleware.rb
lib/dynflow/middleware.rb
# frozen_string_literal: true module Dynflow class Middleware require 'dynflow/middleware/register' require 'dynflow/middleware/world' require 'dynflow/middleware/resolver' require 'dynflow/middleware/stack' require 'dynflow/middleware/common/transaction' require 'dynflow/middleware/common/singleton' include Algebrick::TypeCheck def initialize(stack) @stack = Type! stack, Stack end # call `pass` to get deeper with the call def pass(*args) @stack.pass(*args) end # to get the action object def action @stack.action or raise "the action is not available" end def delay(*args) pass(*args) end def run(*args) pass(*args) end def plan(*args) pass(*args) end def finalize(*args) pass(*args) end def plan_phase(*args) pass(*args) end def finalize_phase(*args) pass(*args) end def present pass end def hook(*args) pass(*args) end end end
ruby
MIT
e14dcdfe57cec99cc78b2f6ab521f00809b1408a
2026-01-04T17:50:16.326730Z
false
Dynflow/dynflow
https://github.com/Dynflow/dynflow/blob/e14dcdfe57cec99cc78b2f6ab521f00809b1408a/lib/dynflow/coordinator.rb
lib/dynflow/coordinator.rb
# frozen_string_literal: true require 'dynflow/coordinator_adapters' module Dynflow class Coordinator include Algebrick::TypeCheck class DuplicateRecordError < Dynflow::Error attr_reader :record def initialize(record) @record = record super("record #{record} already exists") end end class LockError < Dynflow::Error attr_reader :lock def initialize(lock) @lock = lock super("Unable to acquire lock #{lock}") end end class Record < Serializable attr_reader :data include Algebrick::TypeCheck def self.new_from_hash(hash) self.allocate.tap { |record| record.from_hash(hash) } end def self.constantize(name) Serializable.constantize(name) rescue NameError # If we don't find the lock name, return the most generic version Record end def initialize(*args) @data = {} @data = Utils.indifferent_hash(@data.merge(class: self.class.name)) end def from_hash(hash) @data = hash @from_hash = true end def to_hash @data end def id @data[:id] end # @api override # check to be performed before we try to acquire the lock def validate! Type! id, String Type! @data, Hash raise "The record id %{s} too large" % id if id.size > 100 raise "The record class name %{s} too large" % self.class.name if self.class.name.size > 100 end def to_s "#{self.class.name}: #{id}" end def ==(other_object) self.class == other_object.class && self.id == other_object.id end def hash [self.class, self.id].hash end end class WorldRecord < Record def initialize(world) super @data[:id] = world.id @data[:meta] = world.meta end def meta @data[:meta] end def executor? raise NotImplementedError end end class ExecutorWorld < WorldRecord def initialize(world) super self.active = !world.terminating? end def active? @data[:active] end def active=(value) Type! value, Algebrick::Types::Boolean @data[:active] = value end def executor? true end end class ClientWorld < WorldRecord def executor? false end end class Lock < Record def self.constantize(name) Serializable.constantize(name) rescue NameError # If we don't find the lock name, return the most generic version Lock end def to_s "#{self.class.name}: #{id} by #{owner_id}" end def owner_id @data[:owner_id] end # @api override # check to be performed before we try to acquire the lock def validate! super raise "Can't acquire the lock after deserialization" if @from_hash Type! owner_id, String end def unlock_on_shutdown? true end end class LockByWorld < Lock def initialize(world) super @world = world @data.merge!(owner_id: "world:#{world.id}", world_id: world.id) end def self.lock_id(*args) raise NoMethodError end def self.unique_filter(*args) { :class => self.name, :id => lock_id(*args) } end def validate! super raise Errors::InactiveWorldError.new(@world) if @world.terminating? end def world_id @data[:world_id] end def self.valid_owner_ids(coordinator) coordinator.find_worlds.map { |w| "world:#{w.id}" } end def self.valid_classes @valid_classes ||= [] end def self.inherited(klass) valid_classes << klass end end class DelayedExecutorLock < LockByWorld def initialize(world) super @data[:id] = self.class.lock_id end def self.lock_id "delayed-executor" end end class ExecutionPlanCleanerLock < LockByWorld def initialize(world) super @data[:id] = self.class.lock_id end def self.lock_id "execution-plan-cleaner" end end class WorldInvalidationLock < LockByWorld def initialize(world, invalidated_world) super(world) @data[:id] = self.class.lock_id(invalidated_world.id) end def self.lock_id(invalidated_world_id) "world-invalidation:#{invalidated_world_id}" end end class AutoExecuteLock < LockByWorld def initialize(*args) super @data[:id] = self.class.lock_id end def self.lock_id "auto-execute" end end # Used when there should be only one execution plan for a given action class class SingletonActionLock < Lock def initialize(action_class, execution_plan_id) super @data[:owner_id] = "execution-plan:#{execution_plan_id}" @data[:execution_plan_id] = execution_plan_id @data[:id] = self.class.lock_id(action_class) end def owner_id @data[:execution_plan_id] end def self.unique_filter(action_class) { :class => self.name, :id => self.lock_id(action_class) } end def self.lock_id(action_class) 'singleton-action:' + action_class end def self.valid_owner_ids(coordinator) lock_ids = coordinator.find_locks(:class => self.name).map(&:owner_id) plans = coordinator.adapter.find_execution_plans(:uuid => lock_ids) plans = Hash[*plans.map { |plan| [plan[:uuid], plan[:state]] }.flatten] lock_ids.select { |id| plans.key?(id) && !%w(stopped paused).include?(plans[id]) } .map { |id| 'execution-plan:' + id } end def self.valid_classes [self] end end class ExecutionInhibitionLock < Lock def initialize(execution_plan_id) super @data[:owner_id] = "execution-plan:#{execution_plan_id}" @data[:execution_plan_id] = execution_plan_id @data[:id] = self.class.lock_id(execution_plan_id) end def self.lock_id(execution_plan_id) "execution-plan:#{execution_plan_id}" end end class ExecutionLock < LockByWorld def initialize(world, execution_plan_id, client_world_id, request_id) super(world) @data.merge!(id: self.class.lock_id(execution_plan_id), execution_plan_id: execution_plan_id, client_world_id: client_world_id, request_id: request_id) end def self.lock_id(execution_plan_id) "execution-plan:#{execution_plan_id}" end # we need to store the following data in case of # invalidation of the lock from outside (after # the owner world terminated unexpectedly) def execution_plan_id @data[:execution_plan_id] end def client_world_id @data[:client_world_id] end def request_id @data[:request_id] end def unlock_on_shutdown? false end end class PlanningLock < LockByWorld def initialize(world, execution_plan_id) super(world) @data.merge!(id: self.class.lock_id(execution_plan_id), execution_plan_id: execution_plan_id) end def self.lock_id(execution_plan_id) 'execution-plan:' + execution_plan_id end def execution_plan_id @data[:execution_plan_id] end def unlock_on_shutdown? false end end attr_reader :adapter def initialize(coordinator_adapter) @adapter = coordinator_adapter end def acquire(lock, &block) Type! lock, Lock lock.validate! adapter.create_record(lock) if block begin block.call # We are looking for ::Sidekiq::Shutdown, but that may not be defined. We rely on it being a subclass of Interrupt # We don't really want to rescue it, but we need to bind it somehow so that we can check it in ensure rescue Interrupt => e raise e ensure release(lock) if !(defined?(::Sidekiq) && e.is_a?(::Sidekiq::Shutdown)) || lock.unlock_on_shutdown? end end rescue DuplicateRecordError => e raise LockError.new(e.record) end def release(lock) Type! lock, Lock adapter.delete_record(lock) end def release_by_owner(owner_id, on_termination = false) find_locks(owner_id: owner_id).map { |lock| release(lock) if !on_termination || lock.unlock_on_shutdown? } end def find_locks(filter_options) adapter.find_records(filter_options).map do |lock_data| Lock.from_hash(lock_data) end end def create_record(record) Type! record, Record adapter.create_record(record) end def update_record(record) Type! record, Record adapter.update_record(record) end def delete_record(record) Type! record, Record adapter.delete_record(record) end def find_records(filter) adapter.find_records(filter).map do |record_data| Record.from_hash(record_data) end end def find_worlds(active_executor_only = false, filters = {}) ret = find_records(filters.merge(class: Coordinator::ExecutorWorld.name)) if active_executor_only ret = ret.select(&:active?) else ret.concat(find_records(filters.merge(class: Coordinator::ClientWorld.name))) end ret end def register_world(world) Type! world, Coordinator::ClientWorld, Coordinator::ExecutorWorld create_record(world) end def delete_world(world, on_termination = false) Type! world, Coordinator::ClientWorld, Coordinator::ExecutorWorld release_by_owner("world:#{world.id}", on_termination) delete_record(world) end def deactivate_world(world) Type! world, Coordinator::ExecutorWorld world.active = false update_record(world) end def clean_orphaned_locks cleanup_classes = [LockByWorld, SingletonActionLock] ret = [] cleanup_classes.each do |cleanup_class| valid_owner_ids = cleanup_class.valid_owner_ids(self) valid_classes = cleanup_class.valid_classes.map(&:name) orphaned_locks = find_locks(class: valid_classes, exclude_owner_id: valid_owner_ids) # reloading the valid owner ids to avoid race conditions valid_owner_ids = cleanup_class.valid_owner_ids(self) orphaned_locks.each do |lock| unless valid_owner_ids.include?(lock.owner_id) release(lock) ret << lock end end end return ret end end end
ruby
MIT
e14dcdfe57cec99cc78b2f6ab521f00809b1408a
2026-01-04T17:50:16.326730Z
false
Dynflow/dynflow
https://github.com/Dynflow/dynflow/blob/e14dcdfe57cec99cc78b2f6ab521f00809b1408a/lib/dynflow/delayed_plan.rb
lib/dynflow/delayed_plan.rb
# frozen_string_literal: true module Dynflow class DelayedPlan < Serializable include Algebrick::TypeCheck attr_reader :execution_plan_uuid, :start_before attr_accessor :frozen, :start_at def initialize(world, execution_plan_uuid, start_at, start_before, args_serializer, frozen) @world = Type! world, World @execution_plan_uuid = Type! execution_plan_uuid, String @start_at = Type! start_at, Time, NilClass @start_before = Type! start_before, Time, NilClass @args_serializer = Type! args_serializer, Serializers::Abstract @frozen = Type! frozen, Algebrick::Types::Boolean end def execution_plan @execution_plan ||= @world.persistence.load_execution_plan(@execution_plan_uuid) end def plan execution_plan.root_plan_step.load_action execution_plan.generate_action_id execution_plan.generate_step_id execution_plan.plan(*@args_serializer.perform_deserialization!) end def timeout error("Execution plan could not be started before set time (#{@start_before})", 'timeout') end def failed_dependencies(uuids) bullets = uuids.map { |u| "- #{u}" }.join("\n") msg = "Execution plan could not be started because some of its prerequisite execution plans failed:\n#{bullets}" error(msg, 'failed-dependency') end def error(message, history_entry = nil) execution_plan.root_plan_step.state = :error execution_plan.root_plan_step.error = ::Dynflow::ExecutionPlan::Steps::Error.new(message) execution_plan.root_plan_step.save execution_plan.update_state :stopped, history_notice: history_entry end def cancel execution_plan.root_plan_step.state = :cancelled execution_plan.root_plan_step.save execution_plan.update_state :stopped, history_notice: "Delayed task cancelled" @world.persistence.delete_delayed_plans(:execution_plan_uuid => @execution_plan_uuid) return true end def execute(future = Concurrent::Promises.resolvable_future) @world.execute(@execution_plan_uuid, future) ::Dynflow::World::Triggered[@execution_plan_uuid, future] end def to_hash recursive_to_hash :execution_plan_uuid => @execution_plan_uuid, :start_at => @start_at, :start_before => @start_before, :serialized_args => @args_serializer.serialized_args, :args_serializer => @args_serializer.class.name, :frozen => @frozen end # Retrieves arguments from the serializer # # @return [Array] array of the original arguments def args @args_serializer.perform_deserialization! if @args_serializer.args.nil? @args_serializer.args end # @api private def self.new_from_hash(world, hash, *args) serializer = Utils.constantize(hash[:args_serializer]).new(nil, hash[:serialized_args]) self.new(world, hash[:execution_plan_uuid], string_to_time(hash[:start_at]), string_to_time(hash[:start_before]), serializer, hash[:frozen] || false) rescue NameError => e error(e.message) end end end
ruby
MIT
e14dcdfe57cec99cc78b2f6ab521f00809b1408a
2026-01-04T17:50:16.326730Z
false
Dynflow/dynflow
https://github.com/Dynflow/dynflow/blob/e14dcdfe57cec99cc78b2f6ab521f00809b1408a/lib/dynflow/flows.rb
lib/dynflow/flows.rb
# frozen_string_literal: true require 'forwardable' module Dynflow module Flows require 'dynflow/flows/registry' require 'dynflow/flows/abstract' require 'dynflow/flows/atom' require 'dynflow/flows/abstract_composed' require 'dynflow/flows/concurrence' require 'dynflow/flows/sequence' end end
ruby
MIT
e14dcdfe57cec99cc78b2f6ab521f00809b1408a
2026-01-04T17:50:16.326730Z
false