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
Dynflow/dynflow
https://github.com/Dynflow/dynflow/blob/e14dcdfe57cec99cc78b2f6ab521f00809b1408a/lib/dynflow/executors/sidekiq/internal_job_base.rb
lib/dynflow/executors/sidekiq/internal_job_base.rb
# frozen_string_literal: true module Dynflow module Executors module Sidekiq class InternalJobBase include ::Sidekiq::Worker extend ::Dynflow::Executors::Sidekiq::Serialization::WorkerExtension::ClassMethods sidekiq_options retry: false, backtrace: true def self.inherited(klass) klass.prepend(::Dynflow::Executors::Sidekiq::Serialization::WorkerExtension) end def worker_id ::Sidekiq::Logging.tid end def telemetry_options(work_item) { queue: work_item.queue.to_s, world: Dynflow.process_world.id, worker: worker_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/lib/dynflow/actors/execution_plan_cleaner.rb
lib/dynflow/actors/execution_plan_cleaner.rb
# frozen_string_literal: true module Dynflow module Actors class ExecutionPlanCleaner attr_reader :core def initialize(world, options = {}) @world = world @options = options end def core_class Core end def spawn Concurrent::Promises.resolvable_future.tap do |initialized| @core = core_class.spawn(:name => 'execution-plan-cleaner', :args => [@world, @options], :initialized => initialized) end end def clean! core.tell([:clean!]) end class Core < Actor def initialize(world, options = {}) @world = world default_age = 60 * 60 * 24 # One day by default @poll_interval = options.fetch(:poll_interval, default_age) @max_age = options.fetch(:max_age, default_age) start end def start set_clock clean! end def clean! plans = @world.persistence.find_old_execution_plans(Time.now.utc - @max_age) report(plans) @world.persistence.delete_execution_plans(uuid: plans.map(&:id)) end def report(plans) @world.logger.info("Execution plan cleaner removing #{plans.count} execution plans.") end def set_clock @world.clock.ping(self, @poll_interval, :start) end 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/world/invalidation.rb
lib/dynflow/world/invalidation.rb
# frozen_string_literal: true module Dynflow class World module Invalidation # Invalidate another world, that left some data in the runtime, # but it's not really running # # @param world [Coordinator::ClientWorld, Coordinator::ExecutorWorld] coordinator record # left behind by the world we're trying to invalidate # @return [void] def invalidate(world) Type! world, Coordinator::ClientWorld, Coordinator::ExecutorWorld coordinator.acquire(Coordinator::WorldInvalidationLock.new(self, world)) do coordinator.find_locks(class: Coordinator::PlanningLock.name, owner_id: 'world:' + world.id).each do |lock| invalidate_planning_lock lock end if world.is_a? Coordinator::ExecutorWorld old_execution_locks = coordinator.find_locks(class: Coordinator::ExecutionLock.name, owner_id: "world:#{world.id}") coordinator.deactivate_world(world) old_execution_locks.each do |execution_lock| invalidate_execution_lock(execution_lock) end end prune_execution_inhibition_locks! pruned = persistence.prune_envelopes(world.id) logger.error("Pruned #{pruned} envelopes for invalidated world #{world.id}") unless pruned.zero? coordinator.delete_world(world) end end # Prunes execution inhibition locks which got somehow left behind. # Any execution inhibition locks, which have their corresponding execution # plan in stopped state, will be removed. def prune_execution_inhibition_locks! locks = coordinator.find_locks(class: Coordinator::ExecutionInhibitionLock.name) uuids = locks.map { |lock| lock.data[:execution_plan_id] } plan_uuids = persistence.find_execution_plans(filters: { uuid: uuids, state: 'stopped' }).map(&:id) locks.select { |lock| plan_uuids.include? lock.data[:execution_plan_id] }.each do |lock| coordinator.release(lock) end end def invalidate_planning_lock(planning_lock) with_valid_execution_plan_for_lock(planning_lock) do |plan| plan.steps.values.each { |step| invalidate_step step } state = if plan.plan_steps.any? && plan.plan_steps.all? { |step| step.state == :success } :planned else :stopped end plan.update_state(state) if plan.state != state coordinator.release(planning_lock) execute(plan.id) if plan.state == :planned end end # Invalidate an execution lock, left behind by a executor that # was executing an execution plan when it was terminated. # # @param execution_lock [Coordinator::ExecutionLock] the lock to invalidate # @return [void] def invalidate_execution_lock(execution_lock) with_valid_execution_plan_for_lock(execution_lock) do |plan| plan.steps.values.each { |step| invalidate_step step } plan.execution_history.add('terminate execution', execution_lock.world_id) plan.update_state(:paused, history_notice: false) if plan.state == :running plan.save coordinator.release(execution_lock) if plan.error? new_state = plan.prepare_for_rescue execute(plan.id) if new_state == :running else if coordinator.find_worlds(true).any? # Check if there are any executors client_dispatcher.tell([:dispatch_request, Dispatcher::Execution[execution_lock.execution_plan_id], execution_lock.client_world_id, execution_lock.request_id]) end end end rescue Errors::PersistenceError logger.error "failed to write data while invalidating execution lock #{execution_lock}" end # Tries to load an execution plan using id stored in the # lock. If the execution plan cannot be loaded or is invalid, # the lock is released. If the plan gets loaded successfully, it # is yielded to a given block. # # @param execution_lock [Coordinator::ExecutionLock] the lock for which we're trying # to load the execution plan # @yieldparam [ExecutionPlan] execution_plan the successfully loaded execution plan # @return [void] def with_valid_execution_plan_for_lock(execution_lock) begin plan = persistence.load_execution_plan(execution_lock.execution_plan_id) rescue => e if e.is_a?(KeyError) logger.error "invalidated execution plan #{execution_lock.execution_plan_id} missing, skipping" else logger.error e logger.error "unexpected error when invalidating execution plan #{execution_lock.execution_plan_id}, skipping" end coordinator.release(execution_lock) coordinator.release_by_owner(execution_lock.id) return end unless plan.valid? logger.error "invalid plan #{plan.id}, skipping" coordinator.release(execution_lock) coordinator.release_by_owner(execution_lock.id) return end yield plan end # Performs world validity checks # # @return [Integer] number of invalidated worlds def perform_validity_checks world_invalidation_result = worlds_validity_check locks_validity_check.each do |lock| case lock when ::Dynflow::Coordinator::PlanningLock invalidate_planning_lock(lock) when ::Dynflow::Coordinator::ExecutionLock invalidate_execution_lock(lock) end end pruned = connector.prune_undeliverable_envelopes(self) logger.error("Pruned #{pruned} undeliverable envelopes") unless pruned.zero? world_invalidation_result.values.select { |result| result == :invalidated }.size end # Checks if all worlds are valid and optionally invalidates them # # @param auto_invalidate [Boolean] whether automatic invalidation should be performed # @param worlds_filter [Hash] hash of filters to select only matching worlds # @return [Hash{String=>Symbol}] hash containg validation results, mapping world id to a result def worlds_validity_check(auto_invalidate = true, worlds_filter = {}) worlds = coordinator.find_worlds(false, worlds_filter) world_checks = worlds.reduce({}) do |hash, world| hash.update(world => ping_without_cache(world.id, self.validity_check_timeout)) end world_checks.values.each(&:wait) results = {} world_checks.each do |world, check| if check.fulfilled? result = :valid else if auto_invalidate begin invalidate(world) result = :invalidated rescue => e logger.error e result = e.message end else result = :invalid end end results[world.id] = result end unless results.values.all? { |result| result == :valid } logger.error "invalid worlds found #{results.inspect}" end return results end # Cleans up locks which don't have a resource # # @return [Array<Coordinator::Lock>] the removed locks def locks_validity_check orphaned_locks = coordinator.clean_orphaned_locks unless orphaned_locks.empty? logger.error "invalid coordinator locks found and invalidated: #{orphaned_locks.inspect}" end return orphaned_locks end private def invalidate_step(step) if step.state == :running step.error = ExecutionPlan::Steps::Error.new("Abnormal termination (previous state: #{step.state})") step.state = :error step.save end 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/utils/priority_queue.rb
lib/dynflow/utils/priority_queue.rb
# frozen_string_literal: true module Dynflow module Utils # Heavily inspired by rubyworks/pqueue class PriorityQueue def initialize(&block) # :yields: a, b @backing_store = [] @comparator = block || :<=>.to_proc end def size @backing_store.size end def top @backing_store.last end def push(element) @backing_store << element reposition_element(@backing_store.size - 1) end def pop @backing_store.pop end def to_a @backing_store end private # The element at index k will be repositioned to its proper place. def reposition_element(index) return if size <= 1 element = @backing_store.delete_at(index) index = binary_index(@backing_store, element) @backing_store.insert(index, element) end # Find index where a new element should be inserted using binary search def binary_index(array, target) upper = array.size - 1 lower = 0 while upper >= lower center = lower + (upper - lower) / 2 case @comparator.call(target, array[center]) when 0 return center when 1 lower = center + 1 when -1 upper = center - 1 end end lower 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/utils/indifferent_hash.rb
lib/dynflow/utils/indifferent_hash.rb
# frozen_string_literal: true module Dynflow module Utils # Heavily inpired by ActiveSupport::HashWithIndifferentAccess, # reasons we don't want to use the original implementation: # 1. we don't want any core_ext extensions # 2. some users are not happy about seeing the ActiveSupport as # our depednency class IndifferentHash < Hash def initialize(constructor = {}) if constructor.respond_to?(:to_hash) super() update(constructor) else super(constructor) end end def default(key = nil) if key.is_a?(Symbol) && include?(key = key.to_s) self[key] else super end end def self.[](*args) new.merge!(Hash[*args]) end alias_method :regular_writer, :[]= unless method_defined?(:regular_writer) alias_method :regular_update, :update unless method_defined?(:regular_update) def []=(key, value) regular_writer(convert_key(key), convert_value(value, for: :assignment)) end alias_method :store, :[]= def update(other_hash) if other_hash.is_a? IndifferentHash super(other_hash) else other_hash.to_hash.each_pair do |key, value| if block_given? && key?(key) value = yield(convert_key(key), self[key], value) end regular_writer(convert_key(key), convert_value(value)) end self end end alias_method :merge!, :update def key?(key) super(convert_key(key)) end alias_method :include?, :key? alias_method :has_key?, :key? alias_method :member?, :key? def fetch(key, *extras) super(convert_key(key), *extras) end def values_at(*indices) indices.collect { |key| self[convert_key(key)] } end def dup self.class.new(self).tap do |new_hash| new_hash.default = default end end def merge(hash, &block) self.dup.update(hash, &block) end def reverse_merge(other_hash) super(self.class.new_from_hash_copying_default(other_hash)) end def reverse_merge!(other_hash) replace(reverse_merge(other_hash)) end def replace(other_hash) super(self.class.new_from_hash_copying_default(other_hash)) end def delete(key) super(convert_key(key)) end def stringify_keys!; self end def deep_stringify_keys!; self end def stringify_keys; dup end def deep_stringify_keys; dup end def to_options!; self end def select(*args, &block) dup.tap { |hash| hash.select!(*args, &block) } end def reject(*args, &block) dup.tap { |hash| hash.reject!(*args, &block) } end # Convert to a regular hash with string keys. def to_hash _new_hash = Hash.new(default) each do |key, value| _new_hash[key] = convert_value(value, for: :to_hash) end _new_hash end protected def convert_key(key) key.kind_of?(Symbol) ? key.to_s : key end def convert_value(value, options = {}) if value.is_a? Hash if options[:for] == :to_hash value.to_hash else Utils.indifferent_hash(value) end elsif value.is_a?(Array) unless options[:for] == :assignment value = value.dup end value.map! { |e| convert_value(e, options) } else 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/lib/dynflow/connectors/direct.rb
lib/dynflow/connectors/direct.rb
# frozen_string_literal: true module Dynflow module Connectors class Direct < Abstract class Core < Actor def initialize(connector) @connector = connector @worlds = {} @executor_round_robin = RoundRobin.new end def start_listening(world) @worlds[world.id] = world @executor_round_robin.add(world) if world.executor end def stop_receiving_new_work(world) @executor_round_robin.delete(world) end def stop_listening(world) @worlds.delete(world.id) @executor_round_robin.delete(world) if world.executor reference.tell(:terminate!) if @worlds.empty? end def handle_envelope(envelope) if world = find_receiver(envelope) @connector.receive(world, envelope) else log(Logger::ERROR, "Receiver for envelope #{envelope} not found") end end private def find_receiver(envelope) receiver = if Dispatcher::AnyExecutor === envelope.receiver_id @executor_round_robin.next else @worlds[envelope.receiver_id] end raise Dynflow::Error, "No executor available" unless receiver return receiver end end def initialize(world = nil) @core = Core.spawn('connector-direct-core', self) start_listening(world) if world end def start_listening(world) @core.ask([:start_listening, world]) end def stop_receiving_new_work(world, timeout = nil) @core.ask([:stop_receiving_new_work, world]).wait(timeout) end def stop_listening(world, timeout = nil) @core.ask([:stop_listening, world]).wait(timeout) end def send(envelope) Telemetry.with_instance { |t| t.increment_counter(:dynflow_connector_envelopes, 1, :world => envelope.sender_id) } @core.ask([:handle_envelope, envelope]) end def prune_undeliverable_envelopes(_world) # This is a noop 0 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/connectors/abstract.rb
lib/dynflow/connectors/abstract.rb
# frozen_string_literal: true module Dynflow module Connectors class Abstract include Algebrick::TypeCheck include Algebrick::Matching def start_listening(world) raise NotImplementedError end def stop_receiving_new_work(_, timeout = nil) raise NotImplementedError end def stop_listening(world, timeout = nil) raise NotImplementedError end def terminate raise NotImplementedError end def send(envelope) raise NotImplementedError end def prune_undeliverable_envelopes(world) raise NotImplementedError end # we need to pass the world, as the connector can be shared # between words: we need to know the one to send the message to def receive(world, envelope) Type! envelope, Dispatcher::Envelope Telemetry.with_instance { |t| t.increment_counter(:dynflow_connector_envelopes, 1, :world => world.id, :direction => 'incoming') } match(envelope.message, (on Dispatcher::Ping do response_envelope = envelope.build_response_envelope(Dispatcher::Pong, world) send(response_envelope) end), (on Dispatcher::Request do world.executor_dispatcher.tell([:handle_request, envelope]) end), (on Dispatcher::Response do world.client_dispatcher.tell([:dispatch_response, envelope]) end)) 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/connectors/database.rb
lib/dynflow/connectors/database.rb
# frozen_string_literal: true module Dynflow module Connectors class Database < Abstract class PostgresListerner def initialize(core, world_id, db) @core = core @db = db @world_id = world_id @started = Concurrent::AtomicReference.new end def self.notify_supported?(db) db.class.name == "Sequel::Postgres::Database" end def started? @started.get end def start @started.set true @thread = Thread.new do @db.listen("world:#{@world_id}", :loop => true) do if started? @core << :check_inbox else break # the listener is stopped: don't continue listening end end end end def notify(world_id) @db.notify("world:#{world_id}") end def stop @started.set false notify(@world_id) end end class Core < Actor attr_reader :polling_interval def initialize(connector, polling_interval) @connector = connector @world = nil @executor_round_robin = RoundRobin.new @stopped = false @polling_interval = polling_interval end def stopped? !!@stopped end def start_listening(world) @world = world @stopped = false postgres_listen_start self << :periodic_check_inbox end def stop_receiving_new_work @world.coordinator.deactivate_world(@world.registered_world) end def stop_listening @stopped = true postgres_listen_stop end def periodic_check_inbox self << :check_inbox @world.clock.ping(self, polling_interval, :periodic_check_inbox) unless @stopped end def check_inbox return unless @world receive_envelopes end def handle_envelope(envelope) world_id = find_receiver(envelope) if world_id == @world.id if @stopped log(Logger::ERROR, "Envelope #{envelope} received for stopped world") else @connector.receive(@world, envelope) end else send_envelope(update_receiver_id(envelope, world_id)) end end private def postgres_listen_start if PostgresListerner.notify_supported?(@world.persistence.adapter.db) @postgres_listener ||= PostgresListerner.new(self, @world.id, @world.persistence.adapter.db) @postgres_listener.start unless @postgres_listener.started? end end def postgres_listen_stop @postgres_listener.stop if @postgres_listener end def receive_envelopes @world.persistence.pull_envelopes(@world.id).each do |envelope| self.tell([:handle_envelope, envelope]) end rescue => e log(Logger::ERROR, "Receiving envelopes failed on #{e}") end def send_envelope(envelope) @world.persistence.push_envelope(envelope) if @postgres_listener @postgres_listener.notify(envelope.receiver_id) end rescue => e log(Logger::ERROR, "Sending envelope failed on #{e}") end def update_receiver_id(envelope, new_receiver_id) Dispatcher::Envelope[envelope.request_id, envelope.sender_id, new_receiver_id, envelope.message] end def find_receiver(envelope) if Dispatcher::AnyExecutor === envelope.receiver_id any_executor.id else envelope.receiver_id end end def any_executor @executor_round_robin.data = @world.coordinator.find_worlds(true) @executor_round_robin.next or raise Dynflow::Error, "No executor available" end end def initialize(world = nil, polling_interval = nil) polling_interval ||= begin if world && PostgresListerner.notify_supported?(world.persistence.adapter.db) 30 # when the notify is supported, we don't need that much polling else 1 end end @core = Core.spawn('connector-database-core', self, polling_interval) start_listening(world) if world end def start_listening(world) @core.ask([:start_listening, world]) end def stop_receiving_new_work(_, timeout = nil) @core.ask(:stop_receiving_new_work).wait(timeout) end def stop_listening(_, timeout = nil) @core.ask(:stop_listening).then { @core.ask(:terminate!) }.wait(timeout) end def send(envelope) Telemetry.with_instance { |t| t.increment_counter(:dynflow_connector_envelopes, 1, :world => envelope.sender_id, :direction => 'outgoing') } @core.ask([:handle_envelope, envelope]) end def prune_undeliverable_envelopes(world) world.persistence.prune_undeliverable_envelopes 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/semaphores/dummy.rb
lib/dynflow/semaphores/dummy.rb
# frozen_string_literal: true module Dynflow module Semaphores class Dummy < Abstract def wait(thing) true end def get_waiting nil end def has_waiting? false end def release(*args) end def save end def get(n) n end def free 1 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/semaphores/aggregating.rb
lib/dynflow/semaphores/aggregating.rb
# frozen_string_literal: true module Dynflow module Semaphores class Aggregating < Abstract attr_reader :children, :waiting def initialize(children) @children = children @waiting = [] end def wait(thing) if get > 0 true else @waiting << thing false end end def get_waiting @waiting.shift end def has_waiting? !@waiting.empty? end def save @children.values.each(&:save) end def get(n = 1) available = free if n > available drain else @children.values.each { |child| child.get n } n end end def drain available = free @children.values.each { |child| child.get available } available end def free @children.values.map(&:free).reduce { |acc, cur| cur < acc ? cur : acc } end def release(n = 1, key = nil) if key.nil? @children.values.each { |child| child.release n } else @children[key].release n end 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/semaphores/abstract.rb
lib/dynflow/semaphores/abstract.rb
# frozen_string_literal: true module Dynflow module Semaphores class Abstract # Tries to get ticket from the semaphore # Returns true if thing got a ticket # Rturns false otherwise and puts the thing into the semaphore's queue def wait(thing) raise NotImplementedError end # Gets first object from the queue def get_waiting raise NotImplementedError end # Checks if there are objects in the queue def has_waiting? raise NotImpelementedError end # Returns n tickets to the semaphore def release(n = 1) raise NotImplementedError end # Saves the semaphore's state to some persistent storage def save raise NotImplementedError end # Tries to get n tickets # Returns n if the semaphore has free >= n # Returns free if n > free def get(n = 1) raise NotImplementedErrorn end # Requests all tickets # Returns all free tickets from the semaphore def drain raise NotImplementedError 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/semaphores/stateful.rb
lib/dynflow/semaphores/stateful.rb
# frozen_string_literal: true module Dynflow module Semaphores class Stateful < Abstract attr_reader :free, :tickets, :waiting, :meta def initialize(tickets, free = tickets, meta = {}) @tickets = tickets @free = free @waiting = [] @meta = meta end def wait(thing) if get > 0 true else @waiting << thing false end end def get_waiting @waiting.shift end def has_waiting? !@waiting.empty? end def release(n = 1) @free += n @free = @tickets unless @tickets.nil? || @free <= @tickets save end def save end def get(n = 1) if n > @free drain else @free -= n save n end end def drain @free.tap do @free = 0 save end end def to_hash { :tickets => @tickets, :free => @free, :meta => @meta } end def self.new_from_hash(hash) self.new(*hash.values_at(:tickets, :free, :meta)) 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/delayed_executors/polling.rb
lib/dynflow/delayed_executors/polling.rb
# frozen_string_literal: true module Dynflow module DelayedExecutors class Polling < Abstract def core_class Dynflow::DelayedExecutors::PollingCore end end class PollingCore < AbstractCore attr_reader :poll_interval def configure(options) super(options) @poll_interval = options[:poll_interval] end def start check_delayed_plans end def check_delayed_plans check_time = time plans = delayed_execution_plans(check_time) process plans, check_time world.clock.ping(self, poll_interval, :check_delayed_plans) 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/delayed_executors/abstract_core.rb
lib/dynflow/delayed_executors/abstract_core.rb
# frozen_string_literal: true module Dynflow module DelayedExecutors class AbstractCore < Actor include Algebrick::TypeCheck attr_reader :world, :logger def initialize(world, options = {}) @world = Type! world, World @logger = world.logger configure(options) end def start raise NotImplementedError end def configure(options) @time_source = options.fetch(:time_source, -> { Time.now.utc }) end def check_delayed_plans raise NotImplementedError end private def time @time_source.call() end def delayed_execution_plans(time) with_error_handling([]) do world.persistence.find_ready_delayed_plans(time) end end def with_error_handling(error_retval = nil, &block) block.call rescue Exception => e @logger.warn e.message @logger.debug e.backtrace.join("\n") error_retval end def process(delayed_plans, check_time) processed_plan_uuids = [] dispatched_plan_uuids = [] planning_locks = world.coordinator.find_records(class: Coordinator::PlanningLock.name) delayed_plans.each do |plan| next if plan.frozen || locked_for_planning?(planning_locks, plan) fix_plan_state(plan) with_error_handling do if plan.execution_plan.state != :scheduled # in case the previous process was terminated after running the plan, but before deleting the delayed plan record. @logger.info("Execution plan #{plan.execution_plan_uuid} is expected to be in 'scheduled' state, was '#{plan.execution_plan.state}', skipping") processed_plan_uuids << plan.execution_plan_uuid else @logger.debug "Executing plan #{plan.execution_plan_uuid}" world.plan_request(plan.execution_plan_uuid) dispatched_plan_uuids << plan.execution_plan_uuid end end end world.persistence.delete_delayed_plans(:execution_plan_uuid => processed_plan_uuids) unless processed_plan_uuids.empty? end private # handle the case, where the process was termintated while planning was in progress before # TODO: Doing execution plan updates in orchestrator is bad def fix_plan_state(plan) if plan.execution_plan.state == :planning @logger.info("Execution plan #{plan.execution_plan_uuid} is expected to be in 'scheduled' state, was '#{plan.execution_plan.state}', auto-fixing") plan.execution_plan.set_state(:scheduled, true) plan.execution_plan.save end end def locked_for_planning?(planning_locks, plan) planning_locks.any? { |lock| lock.execution_plan_id == plan.execution_plan_uuid } 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/delayed_executors/abstract.rb
lib/dynflow/delayed_executors/abstract.rb
# frozen_string_literal: true module Dynflow module DelayedExecutors class Abstract attr_reader :core def initialize(world, options = {}) @world = world @options = options @started = false spawn end def started? @started end def start @core.ask(:start).tap do @started = true end end def terminate @core.ask(:terminate!) end def spawn Concurrent::Promises.resolvable_future.tap do |initialized| @core = core_class.spawn name: 'delayed-executor', args: [@world, @options], initialized: initialized end end private def core_class raise NotImplementedError 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/testing/in_thread_world.rb
lib/dynflow/testing/in_thread_world.rb
# frozen_string_literal: true module Dynflow module Testing class InThreadWorld < Dynflow::World 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 yield config if block_given? return config end def self.persistence_adapter @persistence_adapter ||= begin db_config = ENV['DB_CONN_STRING'] || 'sqlite:/' puts "Using database configuration: #{db_config}" Dynflow::PersistenceAdapters::Sequel.new(db_config) end end def self.logger_adapter @adapter ||= Dynflow::LoggerAdapters::Simple.new $stderr, 4 end def self.coordinator_adapter ->(world, _) { CoordiationAdapterWithLog.new(world) } end # The worlds created by this method are getting terminated after each test run def self.instance(&block) @instance ||= self.new(test_world_config(&block)) end def initialize(*args) super @clock = ManagedClock.new @executor = InThreadExecutor.new(self) end def execute(execution_plan_id, done = Concurrent::Promises.resolvable_future) @executor.execute(execution_plan_id, done) end def terminate(future = Concurrent::Promises.resolvable_future) run_before_termination_hooks @executor.terminate coordinator.delete_world(registered_world) future.fulfill true @terminated.resolve rescue => e future.reject e end def event(execution_plan_id, step_id, event, done = Concurrent::Promises.resolvable_future, optional: false) @executor.event(execution_plan_id, step_id, event, done, optional: optional) end def plan_event(execution_plan_id, step_id, event, time, done = Concurrent::Promises.resolvable_future, optional: false) if time.nil? || time < Time.now event(execution_plan_id, step_id, event, done, optional: optional) else clock.ping(executor, time, Director::Event[SecureRandom.uuid, execution_plan_id, step_id, event, done, optional], :delayed_event) end 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/testing/assertions.rb
lib/dynflow/testing/assertions.rb
# frozen_string_literal: true module Dynflow module Testing module Assertions # assert that +assert_actioned_plan+ was planned by +action+ with arguments +plan_input+ # alternatively plan-input can be asserted with +block+ def assert_action_planned_with(action, planned_action_class, *plan_input, &block) found_classes = assert_action_planned(action, planned_action_class) found = found_classes.select do |a| if plan_input.empty? block.call a.plan_input else a.plan_input == plan_input end end assert(!found.empty?, "Action #{planned_action_class} with plan_input #{plan_input} was not planned, " + "there were only #{found_classes.map(&:plan_input)}") found end # assert that +assert_actioned_plan+ was planned by +action+ def assert_action_planned(action, planned_action_class) Match! action.phase, Action::Plan Match! action.state, :success found = action.execution_plan.planned_plan_steps .select { |a| a.is_a?(planned_action_class) } assert(!found.empty?, "Action #{planned_action_class} was not planned") found end def refute_action_planned(action, planned_action_class) Match! action.phase, Action::Plan Match! action.state, :success found = action.execution_plan.planned_plan_steps .select { |a| a.is_a?(planned_action_class) } assert(found.empty?, "Action #{planned_action_class} was planned") found end alias :assert_action_planed_with :assert_action_planned_with alias :assert_action_planed :assert_action_planned alias :refute_action_planed :refute_action_planned # assert that +action+ has run-phase planned def assert_run_phase(action, input = nil, &block) Match! action.phase, Action::Plan Match! action.state, :success _(action.execution_plan.planned_run_steps).must_include action _(action.input).must_equal Utils.stringify_keys(input) if input block.call action.input if block end # refute that +action+ has run-phase planned def refute_run_phase(action) Match! action.phase, Action::Plan Match! action.state, :success _(action.execution_plan.planned_run_steps).wont_include action end # assert that +action+ has finalize-phase planned def assert_finalize_phase(action) Match! action.phase, Action::Plan Match! action.state, :success _(action.execution_plan.planned_finalize_steps).must_include action end # refute that +action+ has finalize-phase planned def refute_finalize_phase(action) Match! action.phase, Action::Plan Match! action.state, :success _(action.execution_plan.planned_finalize_steps).wont_include action 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/testing/dummy_planned_action.rb
lib/dynflow/testing/dummy_planned_action.rb
# frozen_string_literal: true module Dynflow module Testing class DummyPlannedAction attr_accessor :output, :plan_input include Mimic def initialize(klass) mimic! klass @output = ExecutionPlan::OutputReference.new( Testing.get_id.to_s, Testing.get_id, Testing.get_id ) end def execute(execution_plan, event, from_subscription, *args) @plan_input = args self end def run_step_id @run_step_id ||= Testing.get_id 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/testing/dummy_executor.rb
lib/dynflow/testing/dummy_executor.rb
# frozen_string_literal: true module Dynflow module Testing class DummyExecutor attr_reader :world, :events_to_process def initialize(world) @world = world @events_to_process = [] end def event(execution_plan_id, step_id, event, future = Concurrent::Promises.resolvable_future) @events_to_process << [execution_plan_id, step_id, event, future] end def delayed_event(director_event) @events_to_process << [director_event.execution_plan_id, director_event.step_id, director_event.event, director_event.result] end def plan_events(delayed_events) delayed_events.each do |event| world.plan_event(event.execution_plan_id, event.step_id, event.event, event.time) end end def execute(action, event = nil) action.execute event plan_events(action.delayed_events.dup) action.delayed_events.clear end # returns true if some event was processed. def progress events = @events_to_process.dup clear events.each do |execution_plan_id, step_id, event, future| future.fulfill true if event && world.action.state != :suspended return false end execute(world.action, event) end end def clear @events_to_process.clear 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/testing/in_thread_executor.rb
lib/dynflow/testing/in_thread_executor.rb
# frozen_string_literal: true module Dynflow module Testing class InThreadExecutor def initialize(world) @world = world @director = Director.new(@world) @work_items = Queue.new end def execute(execution_plan_id, finished = Concurrent::Promises.resolvable_future, _wait_for_acceptance = true) feed_queue(@director.start_execution(execution_plan_id, finished)) process_work_items finished end def process_work_items until @work_items.empty? feed_queue(handle_work(@work_items.pop)) clock_tick end end def plan_events(delayed_events) delayed_events.each do |event| @world.plan_event(event.execution_plan_id, event.step_id, event.event, event.time) end end def handle_work(work_item) work_item.execute step = work_item.step if work_item.is_a?(Director::StepWorkItem) plan_events(step && step.delayed_events) if step && step.delayed_events @director.work_finished(work_item) end def event(execution_plan_id, step_id, event, future = Concurrent::Promises.resolvable_future, optional: false) event = (Director::Event[SecureRandom.uuid, execution_plan_id, step_id, event, future, optional]) @director.handle_event(event).each do |work_item| @work_items << work_item end future end def delayed_event(director_event) @director.handle_event(director_event).each do |work_item| @work_items << work_item end director_event.result end def clock_tick @world.clock.progress_all([:periodic_check_inbox]) end def feed_queue(work_items) work_items.each do |work_item| work_item.world = @world @work_items.push(work_item) end end def terminate(future = Concurrent::Promises.resolvable_future) @director.terminate future.fulfill true rescue => e future.reject e 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/testing/factories.rb
lib/dynflow/testing/factories.rb
# frozen_string_literal: true module Dynflow module Testing module Factories include Algebrick::TypeCheck # @return [Action::PlanPhase] def create_action(action_class, trigger = nil) execution_plan = DummyExecutionPlan.new step = DummyStep.new action_class.new( { step: DummyStep.new, execution_plan_id: execution_plan.id, id: Testing.get_id, phase: Action::Plan, plan_step_id: step.id, run_step_id: nil, finalize_step_id: nil }, execution_plan.world ).tap do |action| action.set_plan_context(execution_plan, trigger, false) end end def create_action_presentation(action_class) execution_plan = DummyExecutionPlan.new action_class.new( { execution_plan: execution_plan, execution_plan_id: execution_plan.id, id: Testing.get_id, phase: Action::Present, plan_step_id: 1, run_step_id: nil, finalize_step_id: nil, input: nil }, execution_plan.world ) end # @return [Action::PlanPhase] def plan_action(plan_action, *args, &block) Match! plan_action.phase, Action::Plan plan_action.execute(*args, &block) raise plan_action.error if plan_action.error plan_action end def create_and_plan_action(action_class, *args, &block) plan_action create_action(action_class), *args, &block end def plan_events(world, delayed_events) delayed_events.each { |event| world.plan_event(event.execution_plan_id, event.step_id, event.event, event.time) } end # @return [Action::RunPhase] def run_action(plan_action, event = nil, &stubbing) Match! plan_action.phase, Action::Plan, Action::Run step = DummyStep.new run_action = if plan_action.phase == Action::Plan plan_action.class.new( { step: step, execution_plan_id: plan_action.execution_plan_id, id: plan_action.id, plan_step_id: plan_action.plan_step_id, run_step_id: step.id, finalize_step_id: nil, phase: Action::Run, input: plan_action.input }, plan_action.world ) else plan_action end run_action.world.action ||= run_action run_action.world.clock.clear stubbing.call run_action if stubbing run_action.world.executor.execute(run_action, event) raise run_action.error if run_action.error run_action end # @return [Action::FinalizePhase] def finalize_action(run_action, &stubbing) Match! run_action.phase, Action::Plan, Action::Run step = DummyStep.new finalize_action = run_action.class.new( { step: step, execution_plan_id: run_action.execution_plan_id, id: run_action.id, plan_step_id: run_action.plan_step_id, run_step_id: run_action.run_step_id, finalize_step_id: step.id, phase: Action::Finalize, input: run_action.input }, run_action.world ) stubbing.call finalize_action if stubbing finalize_action.execute finalize_action end def progress_action_time(action) Match! action.phase, Action::Run if action.world.clock.progress return action.world.executor.progress end 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/testing/managed_clock.rb
lib/dynflow/testing/managed_clock.rb
# frozen_string_literal: true module Dynflow module Testing class ManagedClock attr_reader :pending_pings include Algebrick::Types def initialize @pending_pings = [] end def ping(who, time, with_what = nil, where = :<<) time = current_time + time if time.is_a? Numeric with = with_what.nil? ? None : Some[Object][with_what] @pending_pings << Clock::Timer[who, time, with, where] @pending_pings.sort! end def progress(ignored_subjects = []) if next_ping = @pending_pings.shift if !next_ping.what.respond_to?(:value) || !ignored_subjects.include?(next_ping.what.value) # we are testing an isolated system = we can move in time # without actually waiting @current_time = next_ping.when next_ping.apply end end end def progress_all(ignored_subjects = []) progress(ignored_subjects) until @pending_pings.empty? end def current_time @current_time ||= Time.now end def clear @pending_pings.clear 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/testing/dummy_world.rb
lib/dynflow/testing/dummy_world.rb
# frozen_string_literal: true module Dynflow module Testing class DummyWorld extend Mimic mimic! World attr_reader :clock, :executor, :middleware, :coordinator, :delayed_executor attr_accessor :action def initialize(_config = nil) @logger_adapter = Testing.logger_adapter @clock = ManagedClock.new @executor = DummyExecutor.new(self) @middleware = Middleware::World.new @coordinator = DummyCoordinator.new end def action_logger @logger_adapter.action_logger end def logger @logger_adapter.dynflow_logger end def silence_logger! action_logger.level = 4 end def subscribed_actions(klass) [] end def event(execution_plan_id, step_id, event, future = Concurrent::Promises.resolvable_future) executor.event execution_plan_id, step_id, event, future end def plan_event(execution_plan_id, step_id, event, time, accepted = Concurrent::Promises.resolvable_future) if time.nil? || time < Time.now event(execution_plan_id, step_id, event, accepted) else clock.ping(executor, time, Director::Event[SecureRandom.uuid, execution_plan_id, step_id, event, accepted], :delayed_event) end end def persistence nil 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/testing/dummy_coordinator.rb
lib/dynflow/testing/dummy_coordinator.rb
# frozen_string_literal: true module Dynflow module Testing class DummyCoordinator def find_records(*args) [] 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/testing/dummy_execution_plan.rb
lib/dynflow/testing/dummy_execution_plan.rb
# frozen_string_literal: true module Dynflow module Testing class DummyExecutionPlan extend Mimic mimic! ExecutionPlan attr_reader :id, :planned_plan_steps, :planned_run_steps, :planned_finalize_steps def initialize @id = Testing.get_id.to_s @planned_plan_steps = [] @planned_run_steps = [] @planned_finalize_steps = [] @planned_action_stubbers = {} end def world @world ||= DummyWorld.new end # Allows modify the DummyPlannedAction returned by plan_action def stub_planned_action(klass, &block) @planned_action_stubbers[klass] = block end def add_plan_step(klass, _) dummy_planned_action(klass).tap do |action| @planned_plan_steps << action end end def add_run_step(action) @planned_run_steps << action action end def add_finalize_step(action) @planned_finalize_steps << action action end def dummy_planned_action(klass) DummyPlannedAction.new(klass).tap do |action| if planned_action_stubber = @planned_action_stubbers[klass] planned_action_stubber.call(action) end end end def switch_flow(*args, &block) block.call 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/testing/dummy_step.rb
lib/dynflow/testing/dummy_step.rb
# frozen_string_literal: true module Dynflow module Testing class DummyStep extend Mimic mimic! ExecutionPlan::Steps::Abstract attr_accessor :state, :error attr_reader :id def initialize @state = :pending @id = Testing.get_id end def save(_options = {}) 1 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/testing/mimic.rb
lib/dynflow/testing/mimic.rb
# frozen_string_literal: true module Dynflow module Testing # when extended into Class or an_object it makes all instances of the class or the object # mimic the supplied types. It does so by hooking into kind_of? method. # @example # m = mock('product') # m.is_a? ::Product # => false # m.extend Mimic # m.mimic! ::Product # m.is_a? ::Product # => true module Mimic class ::Module def ===(v) v.kind_of? self end end def mimic!(*types) define = ->_ do define_method :mimic_types do types end define_method :kind_of? do |type| types.any? { |t| t <= type } || super(type) end alias_method :is_a?, :kind_of? end if self.kind_of? ::Class self.class_eval(&define) else self.singleton_class.class_eval(&define) end self 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/execution_plan/dependency_graph.rb
lib/dynflow/execution_plan/dependency_graph.rb
# frozen_string_literal: true module Dynflow class ExecutionPlan::DependencyGraph def initialize @graph = Hash.new { |h, k| h[k] = Set.new } end # adds dependencies to graph that +step+ has based # on the steps referenced in its +input+ def add_dependencies(step, action) action.required_step_ids.each do |required_step_id| @graph[step.id] << required_step_id end end def required_step_ids(step_id) @graph[step_id] end def mark_satisfied(step_id, required_step_id) @graph[step_id].delete(required_step_id) end def unresolved? @graph.any? { |step_id, required_step_ids| required_step_ids.any? } end end end
ruby
MIT
e14dcdfe57cec99cc78b2f6ab521f00809b1408a
2026-01-04T17:50:16.326730Z
false
Dynflow/dynflow
https://github.com/Dynflow/dynflow/blob/e14dcdfe57cec99cc78b2f6ab521f00809b1408a/lib/dynflow/execution_plan/steps.rb
lib/dynflow/execution_plan/steps.rb
# frozen_string_literal: true module Dynflow module ExecutionPlan::Steps require 'dynflow/execution_plan/steps/error' require 'dynflow/execution_plan/steps/abstract' require 'dynflow/execution_plan/steps/abstract_flow_step' require 'dynflow/execution_plan/steps/plan_step' require 'dynflow/execution_plan/steps/run_step' require 'dynflow/execution_plan/steps/finalize_step' end end
ruby
MIT
e14dcdfe57cec99cc78b2f6ab521f00809b1408a
2026-01-04T17:50:16.326730Z
false
Dynflow/dynflow
https://github.com/Dynflow/dynflow/blob/e14dcdfe57cec99cc78b2f6ab521f00809b1408a/lib/dynflow/execution_plan/hooks.rb
lib/dynflow/execution_plan/hooks.rb
# frozen_string_literal: true module Dynflow class ExecutionPlan module Hooks HOOK_KINDS = (ExecutionPlan.states + [:success, :failure]).freeze # A register holding information about hook classes and events # which should trigger the hooks. # # @attr_reader hooks [Hash<Class, Set<Symbol>>] a hash mapping hook classes to events which should trigger the hooks class Register attr_reader :hooks def initialize(hooks = {}) @hooks = hooks end # Sets a hook to be run on certain events # # @param class_name [Class] class of the hook to be run # @param on [Symbol, Array<Symbol>] when should the hook be run, one of {HOOK_KINDS} # @return [void] def use(class_name, on: ExecutionPlan.states) on = Array[on] unless on.kind_of?(Array) validate_kinds!(on) if hooks[class_name] hooks[class_name] += on else hooks[class_name] = on end end # Disables a hook from being run on certain events # # @param class_name [Class] class of the hook to disable # @param on [Symbol, Array<Symbol>] when should the hook be disabled, one of {HOOK_KINDS} # @return [void] def do_not_use(class_name, on: HOOK_KINDS) on = Array[on] unless on.kind_of?(Array) validate_kinds!(on) if hooks[class_name] hooks[class_name] -= on hooks.delete(class_name) if hooks[class_name].empty? end end # Performs a deep clone of the hooks register # # @return [Register] new deeply cloned register def dup new_hooks = hooks.reduce({}) do |acc, (key, value)| acc.update(key => value.dup) end self.class.new(new_hooks) end # Runs the registered hooks # # @param execution_plan [ExecutionPlan] the execution plan which triggered the hooks # @param action [Action] the action which triggered the hooks # @param kind [Symbol] the kind of hooks to run, one of {HOOK_KINDS} def run(execution_plan, action, kind) hooks = on(kind) return if hooks.empty? Executors.run_user_code do hooks.each do |hook| begin action.send(hook, execution_plan) rescue => e execution_plan.logger.error "Failed to run hook '#{hook}' for action '#{action.class}'" execution_plan.logger.error e end end end end # Returns which hooks should be run on certain event. # # @param kind [Symbol] what kind of hook are we looking for # @return [Array<Class>] list of hook classes to execute def on(kind) hooks.select { |_key, on| on.include? kind }.keys end private def validate_kinds!(kinds) kinds.each do |kind| raise "Unknown hook kind '#{kind}'" unless HOOK_KINDS.include?(kind) 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/lib/dynflow/execution_plan/output_reference.rb
lib/dynflow/execution_plan/output_reference.rb
# frozen_string_literal: true module Dynflow class ExecutionPlan::OutputReference < Serializable include Algebrick::TypeCheck # dereferences all OutputReferences in Hash-Array structure def self.dereference(object, persistence) case object when Hash object.reduce(Utils.indifferent_hash({})) do |h, (key, val)| h.update(key => dereference(val, persistence)) end when Array object.map { |val| dereference(val, persistence) } when self object.dereference(persistence) else object end end # dereferences all hashes representing OutputReferences in Hash-Array structure def self.deserialize(value) case value when Hash if value[:class] == self.to_s new_from_hash(value) else value.reduce(Utils.indifferent_hash({})) do |h, (key, val)| h.update(key => deserialize(val)) end end when Array value.map { |val| deserialize(val) } else value end end attr_reader :execution_plan_id, :step_id, :action_id, :subkeys def initialize(execution_plan_id, step_id, action_id, subkeys = []) @execution_plan_id = Type! execution_plan_id, String @step_id = Type! step_id, Integer @action_id = Type! action_id, Integer Type! subkeys, Array @subkeys = subkeys.map { |v| Type!(v, String, Symbol).to_s }.freeze end def [](subkey) self.class.new(execution_plan_id, step_id, action_id, subkeys + [subkey]) end def to_hash recursive_to_hash class: self.class.to_s, execution_plan_id: execution_plan_id, step_id: step_id, action_id: action_id, subkeys: subkeys end def to_s "Step(#{step_id}).output".dup.tap do |ret| ret << subkeys.map { |k| "[:#{k}]" }.join('') if subkeys.any? end end alias_method :inspect, :to_s def dereference(persistence) action_data = persistence.adapter.load_action(execution_plan_id, action_id) @subkeys.reduce(action_data[:output]) { |v, k| v.fetch k } end protected def self.new_from_hash(hash) check_class_matching hash new(hash.fetch(:execution_plan_id), hash.fetch(:step_id), hash.fetch(:action_id), hash.fetch(:subkeys)) end end end
ruby
MIT
e14dcdfe57cec99cc78b2f6ab521f00809b1408a
2026-01-04T17:50:16.326730Z
false
Dynflow/dynflow
https://github.com/Dynflow/dynflow/blob/e14dcdfe57cec99cc78b2f6ab521f00809b1408a/lib/dynflow/execution_plan/steps/plan_step.rb
lib/dynflow/execution_plan/steps/plan_step.rb
# frozen_string_literal: true module Dynflow module ExecutionPlan::Steps class PlanStep < Abstract attr_reader :children # @param [Array] children is a private API parameter def initialize(execution_plan_id, id, state, action_class, action_id, error, world, started_at = nil, ended_at = nil, execution_time = 0.0, real_time = 0.0, children = []) super execution_plan_id, id, state, action_class, action_id, error, world, started_at, ended_at, execution_time, real_time children.all? { |child| Type! child, Integer } @children = children end def planned_steps(execution_plan) @children.map { |id| execution_plan.steps.fetch(id) } end def phase Action::Plan end def to_hash super.merge recursive_to_hash(:children => children) end def delay(delay_options, args) @action.execute_delay(delay_options, *args) persistence.save_action(execution_plan_id, @action) @action.serializer ensure save end # @return [Action] def execute(execution_plan, trigger, from_subscription, *args) unless @action raise "The action was not initialized, you might forgot to call initialize_action method" end @action.set_plan_context(execution_plan, trigger, from_subscription) Type! execution_plan, ExecutionPlan with_meta_calculation(@action) do @action.execute(*args) end persistence.save_action(execution_plan_id, @action) return @action end def self.state_transitions @state_transitions ||= { scheduling: [:pending, :error, :cancelled], pending: [:running, :error, :cancelled], running: [:success, :error, :cancelled], success: [], suspended: [], skipped: [], cancelled: [], error: [] } end def self.new_from_hash(hash, execution_plan_id, world) check_class_matching hash new execution_plan_id, hash[:id], hash[:state], Action.constantize(hash[:action_class]), hash[:action_id], hash_to_error(hash[:error]), world, string_to_time(hash[:started_at]), string_to_time(hash[:ended_at]), hash[:execution_time], hash[:real_time], hash[:children] end def load_action @action = @world.persistence.load_action(self) end def initialize_action(caller_action = nil) attributes = { execution_plan_id: execution_plan_id, id: action_id, step: self, plan_step_id: self.id, run_step_id: nil, finalize_step_id: nil, phase: phase } if caller_action if caller_action.execution_plan_id != execution_plan_id attributes.update(caller_execution_plan_id: caller_action.execution_plan_id) end attributes.update(caller_action_id: caller_action.id) end @action = action_class.new(attributes, world) persistence.save_action(execution_plan_id, @action) @action 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/execution_plan/steps/finalize_step.rb
lib/dynflow/execution_plan/steps/finalize_step.rb
# frozen_string_literal: true module Dynflow module ExecutionPlan::Steps class FinalizeStep < AbstractFlowStep def self.state_transitions @state_transitions ||= { pending: [:running, :skipped], # :skipped when its run_step is skipped running: [:success, :error], success: [:pending], # when restarting finalize phase suspended: [], skipped: [], error: [:pending, :skipped] # pending when restarting finalize phase } end def update_from_action(action) super self.progress_weight = action.finalize_progress_weight end def phase Action::Finalize end def mark_to_skip self.state = :skipped self.save 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/execution_plan/steps/run_step.rb
lib/dynflow/execution_plan/steps/run_step.rb
# frozen_string_literal: true module Dynflow module ExecutionPlan::Steps class RunStep < AbstractFlowStep def self.state_transitions @state_transitions ||= { pending: [:running, :skipped, :error], # :skipped when it cannot be run because it depends on skipping step running: [:success, :error, :suspended], success: [:suspended], # after not-done process_update suspended: [:running, :error], # process_update, e.g. error in setup_progress_updates skipping: [:error, :skipped], # waiting for the skip method to be called skipped: [], error: [:skipping, :running] } end def update_from_action(action) super self.progress_weight = action.run_progress_weight end def phase Action::Run end def cancellable? [:suspended, :running].include?(self.state) && self.action_class < Action::Cancellable end def with_sub_plans? self.action_class < Action::WithSubPlans end def mark_to_skip case self.state when :error self.state = :skipping when :pending self.state = :skipped else raise "Skipping step in #{self.state} is not supported" end self.save 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/execution_plan/steps/abstract.rb
lib/dynflow/execution_plan/steps/abstract.rb
# frozen_string_literal: true module Dynflow module ExecutionPlan::Steps class Abstract < Serializable include Algebrick::TypeCheck include Stateful attr_reader :execution_plan_id, :id, :state, :action_class, :action_id, :world, :started_at, :ended_at, :execution_time, :real_time, :queue, :delayed_events attr_accessor :error # rubocop:disable Metrics/ParameterLists def initialize(execution_plan_id, id, state, action_class, action_id, error, world, started_at = nil, ended_at = nil, execution_time = 0.0, real_time = 0.0, progress_done = nil, progress_weight = nil, queue = nil) @id = id || raise(ArgumentError, 'missing id') @execution_plan_id = Type! execution_plan_id, String @world = Type! world, World @error = Type! error, ExecutionPlan::Steps::Error, NilClass @started_at = Type! started_at, Time, NilClass @ended_at = Type! ended_at, Time, NilClass @execution_time = Type! execution_time, Numeric @real_time = Type! real_time, Numeric @progress_done = Type! progress_done, Numeric, NilClass @progress_weight = Type! progress_weight, Numeric, NilClass @queue = Type! queue, Symbol, NilClass self.state = state.to_sym Child! action_class, Action @action_class = action_class @action_id = action_id || raise(ArgumentError, 'missing action_id') end # rubocop:enable Metrics/ParameterLists def ==(other) other.class == self.class && other.execution_plan_id == self.execution_plan_id && other.id == self.id end def action_logger @world.action_logger end def phase raise NotImplementedError end def mark_to_skip raise NotImplementedError end def persistence world.persistence end def save(conditions = {}) persistence.save_step(self, conditions) end def self.states @states ||= [:scheduling, :pending, :running, :success, :suspended, :skipping, :skipped, :error, :cancelled] end def execute(*args) raise NotImplementedError end def to_s "#<#{self.class.name}:#{execution_plan_id}:#{id}>" end def to_hash recursive_to_hash execution_plan_uuid: execution_plan_id, id: id, state: state, class: self.class.to_s, action_class: action_class.to_s, action_id: action_id, error: error, started_at: started_at, ended_at: ended_at, execution_time: execution_time, real_time: real_time, progress_done: progress_done, progress_weight: progress_weight, queue: queue end def progress_done default_progress_done || @progress_done || 0 end # in specific states it's clear what progress the step is in def default_progress_done case self.state when :success, :skipped 1 when :pending 0 end end def progress_weight @progress_weight || 0 # 0 means not calculated yet end attr_writer :progress_weight # to allow setting the weight from planning # @return [Action] in presentation mode, intended for retrieving: progress information, # details, human outputs, etc. def action(execution_plan) world.persistence.load_action_for_presentation(execution_plan, action_id, self) end def skippable? self.state == :error end def cancellable? false end def with_sub_plans? false end protected def self.new_from_hash(hash, execution_plan_id, world) check_class_matching hash new(execution_plan_id, hash[:id], hash[:state], Action.constantize(hash[:action_class]), hash[:action_id], hash_to_error(hash[:error]), world, string_to_time(hash[:started_at]), string_to_time(hash[:ended_at]), hash[:execution_time].to_f, hash[:real_time].to_f, hash[:progress_done].to_f, hash[:progress_weight].to_f, (hash[:queue] && hash[:queue].to_sym)) end private def with_meta_calculation(action, &block) start = Time.now.utc @started_at ||= start block.call ensure calculate_progress(action) @ended_at = Time.now.utc current_execution_time = @ended_at - start @execution_time += current_execution_time @real_time = @ended_at - @started_at update_step_telemetry(current_execution_time) end def calculate_progress(action) @progress_done, @progress_weight = action.calculated_progress if @progress_done.is_a?(Float) && !@progress_done.finite? action_logger.error("Unexpected progress value #{@progress_done} for step #{execution_plan_id}##{id}") @progress_done = 0 end end def update_step_telemetry(current_execution_time) Dynflow::Telemetry.with_instance do |t| if [:success, :skipped].include?(state) t.observe_histogram(:dynflow_step_real_time, real_time * 1000, :action => action_class.to_s, :phase => phase.to_s_humanized) end t.observe_histogram(:dynflow_step_execution_time, current_execution_time * 1000, :action => action_class.to_s, :phase => phase.to_s_humanized) end 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/execution_plan/steps/abstract_flow_step.rb
lib/dynflow/execution_plan/steps/abstract_flow_step.rb
# frozen_string_literal: true module Dynflow module ExecutionPlan::Steps class AbstractFlowStep < Abstract # Method called when initializing the step to customize the behavior based on the # action definition during the planning phase def update_from_action(action) @queue = action.queue @queue ||= action.triggering_action.queue if action.triggering_action @queue ||= :default end def execute(*args) return self if [:skipped, :success].include? self.state open_action do |action| with_meta_calculation(action) do action.execute(*args) @delayed_events = action.delayed_events end end end def clone self.class.from_hash(to_hash, execution_plan_id, world) end private def open_action action = persistence.load_action(self) yield action persistence.save_action(execution_plan_id, action) persistence.save_output_chunks(execution_plan_id, action.id, action.pending_output_chunks) save return self 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/execution_plan/steps/error.rb
lib/dynflow/execution_plan/steps/error.rb
# frozen_string_literal: true module Dynflow module ExecutionPlan::Steps class Error < Serializable extend Algebrick::Matching include Algebrick::TypeCheck attr_reader :exception_class, :message, :backtrace def self.new(*args) case args.size when 1 match obj = args.first, (on String do super(StandardError, obj, caller, nil) end), (on Exception do super(obj.class, obj.message, obj.backtrace, obj) end) when 3, 4 super(*args.values_at(0..3)) else raise ArgumentError, "wrong number of arguments #{args}" end end def initialize(exception_class, message, backtrace, exception) @exception_class = Child! exception_class, Exception @message = Type! message, String @backtrace = Type! backtrace, Array @exception = Type! exception, Exception, NilClass end def self.new_from_hash(hash) exception_class = begin Utils.constantize(hash[:exception_class]) rescue NameError Errors::UnknownError.for_exception_class(hash[:exception_class]) end self.new(exception_class, hash[:message], hash[:backtrace], nil) end def to_hash recursive_to_hash class: self.class.name, exception_class: exception_class.to_s, message: message, backtrace: backtrace end def to_s format '%s (%s)\n%s', (@exception || self).message, (@exception ? @exception.class : exception_class), (@exception || self).backtrace end def exception @exception || exception_class.exception(message).tap { |e| e.set_backtrace backtrace } 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/transaction_adapters/active_record.rb
lib/dynflow/transaction_adapters/active_record.rb
# frozen_string_literal: true module Dynflow module TransactionAdapters class ActiveRecord < Abstract def transaction(&block) ::ActiveRecord::Base.transaction(&block) end def rollback raise ::ActiveRecord::Rollback 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/transaction_adapters/none.rb
lib/dynflow/transaction_adapters/none.rb
# frozen_string_literal: true module Dynflow module TransactionAdapters class None < Abstract def transaction(&block) block.call end def rollback 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/transaction_adapters/abstract.rb
lib/dynflow/transaction_adapters/abstract.rb
# frozen_string_literal: true module Dynflow module TransactionAdapters class Abstract # start transaction around +block+ def transaction(&block) raise NotImplementedError end # rollback the transaction def rollback raise NotImplementedError 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/director/sequence_cursor.rb
lib/dynflow/director/sequence_cursor.rb
# frozen_string_literal: true module Dynflow class Director class SequenceCursor def initialize(flow_manager, sequence, parent_cursor = nil) @flow_manager = flow_manager @sequence = sequence @parent_cursor = parent_cursor @todo = [] @index = -1 # starts before first element @no_error_so_far = true end # @param [ExecutionPlan::Steps::Abstract, SequenceCursor] work # step or sequence cursor that was done # @param [true, false] success was the work finished successfully # @return [Array<Integer>] new step_ids that can be done next def what_is_next(work = nil, success = true) unless work.nil? || @todo.delete(work) raise "marking as done work that was not expected: #{work.inspect}" end @no_error_so_far &&= success if done_here? return next_steps else return [] end end # return true if we can't move the cursor further, either when # everyting is done in the sequence or there was some failure # that prevents us from moving def done? (!@no_error_so_far && done_here?) || @index == @sequence.size end protected # steps we can do right now without waiting for anything def steps_todo @todo.map do |item| case item when SequenceCursor item.steps_todo else item end end.flatten end def move @index += 1 next_flow = @sequence.sub_flows[@index] add_todo(next_flow) end private def done_here? @todo.empty? end def next_steps move if @no_error_so_far return steps_todo unless done? if @parent_cursor return @parent_cursor.what_is_next(self, @no_error_so_far) else return [] end end def add_todo(flow) case flow when Flows::Sequence @todo << SequenceCursor.new(@flow_manager, flow, self).tap do |cursor| cursor.move end when Flows::Concurrence flow.sub_flows.each { |sub_flow| add_todo(sub_flow) } when Flows::Atom @flow_manager.cursor_index[flow.step_id] = self @todo << @flow_manager.execution_plan.steps[flow.step_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/lib/dynflow/director/sequential_manager.rb
lib/dynflow/director/sequential_manager.rb
# frozen_string_literal: true module Dynflow class Director class SequentialManager attr_reader :execution_plan, :world def initialize(world, execution_plan) @world = world @execution_plan = execution_plan @done = false end def run with_state_updates do dispatch(execution_plan.run_flow) finalize end return execution_plan end def finalize reset_finalize_steps unless execution_plan.error? step_id = execution_plan.finalize_flow.all_step_ids.first action_class = execution_plan.steps[step_id].action_class world.middleware.execute(:finalize_phase, action_class, execution_plan) do dispatch(execution_plan.finalize_flow) end end @done = true end def finalize_steps execution_plan.finalize_flow.all_step_ids.map do |step_id| execution_plan.steps[step_id] end end def reset_finalize_steps finalize_steps.each do |step| step.state = :pending if [:success, :error].include? step.state end end def done! @done = true end def done? @done end private def dispatch(flow) case flow when Flows::Sequence run_in_sequence(flow.flows) when Flows::Concurrence run_in_concurrence(flow.flows) when Flows::Atom run_step(execution_plan.steps[flow.step_id]) else raise ArgumentError, "Don't know how to run #{flow}" end end def run_in_sequence(steps) steps.all? { |s| dispatch(s) } end def run_in_concurrence(steps) run_in_sequence(steps) end def run_step(step) step.execute return step.state != :error end def with_state_updates(&block) execution_plan.update_state(:running) block.call execution_plan.update_state(execution_plan.error? ? :paused : :stopped) 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/director/execution_plan_manager.rb
lib/dynflow/director/execution_plan_manager.rb
# frozen_string_literal: true module Dynflow class Director class ExecutionPlanManager include Algebrick::TypeCheck include Algebrick::Matching attr_reader :execution_plan, :future def initialize(world, execution_plan, future) @world = Type! world, World @execution_plan = Type! execution_plan, ExecutionPlan @future = Type! future, Concurrent::Promises::ResolvableFuture @running_steps_manager = RunningStepsManager.new(world) @halted = false unless [:planned, :paused].include? execution_plan.state raise "execution_plan is not in pending or paused state, it's #{execution_plan.state}" end execution_plan.update_state(:running) end def start raise "The future was already set" if @future.resolved? start_run or start_finalize or finish end def halt @halted = true @running_steps_manager.terminate end def restart @run_manager = nil @finalize_manager = nil start end def prepare_next_step(step) StepWorkItem.new(execution_plan.id, step, step.queue, @world.id).tap do |work| @running_steps_manager.add(step, work) end end # @return [Array<WorkItem>] of Work items to continue with def what_is_next(work) Type! work, WorkItem case work when StepWorkItem step = work.step update_steps([step]) suspended, work = @running_steps_manager.done(step) work = compute_next_from_step(step) unless suspended work when FinalizeWorkItem if work.finalize_steps_data steps = work.finalize_steps_data.map do |step_data| Serializable.from_hash(step_data, execution_plan.id, @world) end update_steps(steps) end raise "Finalize work item without @finalize_manager ready" unless @finalize_manager @finalize_manager.done! finish else raise "Unexpected work #{work}" end end def event(event) Type! event, Event unless event.execution_plan_id == @execution_plan.id raise "event #{event.inspect} doesn't belong to plan #{@execution_plan.id}" end @running_steps_manager.event(event) end def done? @halted || (!@run_manager || @run_manager.done?) && (!@finalize_manager || @finalize_manager.done?) end def terminate @running_steps_manager.terminate end private def update_steps(steps) steps.each { |step| execution_plan.steps[step.id] = step } end def compute_next_from_step(step) raise "run manager not set" unless @run_manager raise "run manager already done" if @run_manager.done? return [] if @halted next_steps = @run_manager.what_is_next(step) if @run_manager.done? start_finalize or finish else next_steps.map { |s| prepare_next_step(s) } end end def no_work raise "No work but not done" unless done? [] end def start_run return if execution_plan.run_flow.empty? raise 'run phase already started' if @run_manager @run_manager = FlowManager.new(execution_plan, execution_plan.run_flow) @run_manager.start.map { |s| prepare_next_step(s) }.tap { |a| raise if a.empty? } end def start_finalize return if execution_plan.finalize_flow.empty? raise 'finalize phase already started' if @finalize_manager @finalize_manager = SequentialManager.new(@world, execution_plan) [FinalizeWorkItem.new(execution_plan.id, execution_plan.finalize_steps.first.queue, @world.id)] end def finish return no_work 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/director/flow_manager.rb
lib/dynflow/director/flow_manager.rb
# frozen_string_literal: true module Dynflow class Director class FlowManager include Algebrick::TypeCheck attr_reader :execution_plan, :cursor_index def initialize(execution_plan, flow) @execution_plan = Type! execution_plan, ExecutionPlan @flow = flow @cursor_index = {} @cursor = build_root_cursor end def done? @cursor.done? end # @return [Set] of steps to continue with def what_is_next(flow_step) return [] if flow_step.state == :suspended success = flow_step.state != :error return cursor_index[flow_step.id].what_is_next(flow_step, success) end # @return [Set] of steps to continue with def start return @cursor.what_is_next.tap do |steps| raise 'invalid state' if steps.empty? && !done? end end private def build_root_cursor # the root cursor has to always run against sequence sequence = @flow.is_a?(Flows::Sequence) ? @flow : Flows::Sequence.new([@flow]) return SequenceCursor.new(self, sequence, nil) 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/director/queue_hash.rb
lib/dynflow/director/queue_hash.rb
# frozen_string_literal: true module Dynflow class Director class QueueHash include Algebrick::TypeCheck def initialize(key_type = Object, value_type = Object) @key_type = key_type @value_type = value_type @stash = Hash.new { |hash, key| hash[key] = [] } end def push(key, value) Type! key, @key_type Type! value, @value_type @stash[key].push value end def shift(key) return nil unless present? key @stash[key].shift.tap { @stash.delete(key) if @stash[key].empty? } end def present?(key) @stash.key?(key) end def empty?(key) !present?(key) end def clear ret = @stash.dup @stash.clear ret end def size(key) return 0 if empty?(key) @stash[key].size end def first(key) return nil if empty?(key) @stash[key].first 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/director/running_steps_manager.rb
lib/dynflow/director/running_steps_manager.rb
# frozen_string_literal: true module Dynflow class Director # Handles the events generated while running actions, makes sure # the events are sent to the action only when in suspended state class RunningStepsManager include Algebrick::TypeCheck def initialize(world) @world = Type! world, World @running_steps = {} # enqueued work items by step id @work_items = QueueHash.new(Integer, WorkItem) # enqueued events by step id - we delay creating work items from events until execution time # to handle potential updates of the step object (that is part of the event) @events = QueueHash.new(Integer, Director::Event) @events_by_request_id = {} @halted = false end def terminate pending_work = @work_items.clear.values.flatten(1) pending_work.each do |w| finish_event_result(w) do |result| result.reject UnprocessableEvent.new("dropping due to termination") end end end def halt @halted = true end def add(step, work) Type! step, ExecutionPlan::Steps::RunStep @running_steps[step.id] = step # we make sure not to run any event when the step is still being executed @work_items.push(step.id, work) self end # @returns [TrueClass|FalseClass, Array<WorkItem>] def done(step) Type! step, ExecutionPlan::Steps::RunStep # update the step based on the latest finished work @running_steps[step.id] = step @work_items.shift(step.id).tap do |work| finish_event_result(work) { |f| f.fulfill true } end if step.state == :suspended return true, [create_next_event_work_item(step)].compact else while (work = @work_items.shift(step.id)) @world.logger.debug "step #{step.execution_plan_id}:#{step.id} dropping event #{work.request_id}/#{work.event}" finish_event_result(work) do |f| f.reject(UnprocessableEvent.new("Message dropped").tap { |e| e.set_backtrace(caller) }) end end while (event = @events.shift(step.id)) @world.logger.debug "step #{step.execution_plan_id}:#{step.id} dropping event #{event.request_id}/#{event}" if event.result event.result.reject(UnprocessableEvent.new("Message dropped").tap { |e| e.set_backtrace(caller) }) end end unless @work_items.empty?(step.id) && @events.empty?(step.id) raise "Unexpected item in @work_items (#{@work_items.inspect}) or @events (#{@events.inspect})" end @running_steps.delete(step.id) return false, [] end end def try_to_terminate @running_steps.delete_if do |_, step| step.state != :running end return @running_steps.empty? end # @returns [Array<WorkItem>] def event(event) Type! event, Event step = @running_steps[event.step_id] unless step event.result.reject UnprocessableEvent.new('step is not suspended, it cannot process events') return [] end if @halted event.result.reject UnprocessableEvent.new('execution plan is halted, it cannot receive events') return [] end can_run_event = @work_items.empty?(step.id) @events_by_request_id[event.request_id] = event @events.push(step.id, event) if can_run_event [create_next_event_work_item(step)] else [] end end # turns the first event from the queue to the next work item to work on def create_next_event_work_item(step) event = @events.shift(step.id) return unless event work = EventWorkItem.new(event.request_id, event.execution_plan_id, step, event.event, step.queue, @world.id) @work_items.push(step.id, work) work end # @yield [Concurrent.resolvable_future] in case the work item has an result future assigned # and deletes the tracked event def finish_event_result(work_item) return unless EventWorkItem === work_item if event = @events_by_request_id.delete(work_item.request_id) yield event.result if event.result end 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/telemetry_adapters/statsd.rb
lib/dynflow/telemetry_adapters/statsd.rb
# frozen_string_literal: true module Dynflow module TelemetryAdapters class StatsD < Abstract def initialize(host = '127.0.0.1:8125') require 'statsd-instrument' @instances = {} @host = host ::StatsD.backend = ::StatsD::Instrument::Backends::UDPBackend.new(host, :statsd) end def add_counter(name, description, instance_labels) raise "Metric already registered: #{name}" if @instances[name] @instances[name] = instance_labels end def add_gauge(name, description, instance_labels) raise "Metric already registered: #{name}" if @instances[name] @instances[name] = instance_labels end def add_histogram(name, description, instance_labels, buckets = DEFAULT_BUCKETS) raise "Metric already registered: #{name}" if @instances[name] @instances[name] = instance_labels end def increment_counter(name, value, tags) ::StatsD.increment(name_tag_mapping(name, tags), value) end def set_gauge(name, value, tags) ::StatsD.gauge(name_tag_mapping(name, tags), value) end def observe_histogram(name, value, tags) ::StatsD.measure(name_tag_mapping(name, tags), value) end private def name_tag_mapping(name, tags) instances = @instances[name] return name if instances.nil? || instances.empty? (name.to_s + '.' + instances.map { |x| tags[x] }.compact.join('.')).tr('-:/ ', '____') 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/telemetry_adapters/dummy.rb
lib/dynflow/telemetry_adapters/dummy.rb
# frozen_string_literal: true module Dynflow module TelemetryAdapters # Telemetry adapter which does not evaluate blocks passed to {#with_instance}. class Dummy < Abstract # Does nothing with the block passed to it # # @return void def with_instance # Do nothing end def measure(_name, _tags = {}) # Just call the block yield 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/telemetry_adapters/abstract.rb
lib/dynflow/telemetry_adapters/abstract.rb
# frozen_string_literal: true module Dynflow module TelemetryAdapters class Abstract # Default buckets to use when defining a histogram DEFAULT_BUCKETS = [0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 20, 30, 60, 120, 300, 600, 1200].freeze # Configures a counter to be collected # # @param [String] name Name of the counter # @param [String] description Human-readable description of the counter # @param [Array<String>] instance_labels Labels which will be assigned to the collected data # @return [void] def add_counter(name, description, instance_labels = []) end # Configures a gauge to be collected # # @param [String] name Name of the gauge # @param [String] description Human-readable description of the gauge # @param [Array<String>] instance_labels Labels which will be assigned to the collected data # @return [void] def add_gauge(name, description, instance_labels = []) end # Configures a histogram to be collected # # @param [String] name Name of the histogram # @param [String] description Human-readable description of the histogram # @param [Array<String>] instance_labels Labels which will be assigned to the collected data # @param [Array<Integer>] buckest Buckets to fit the value into # @return [void] def add_histogram(name, description, instance_labels = [], buckets = DEFAULT_BUCKETS) end # Increments a counter # # @param [String,Symbol] name Name of the counter to increment # @param [Integer] value Step to increment by # @param [Hash{Symbol=>String}] tags Tags to apply to this record # @return [void] def increment_counter(name, value = 1, tags = {}) end # Modifies a gauge # # @param [String,Symbol] name Name of the gauge to increment # @param [String,Integer] value Step to change by # @param [Hash{Symbol=>String}] tags Tags to apply to this record # @return [void] def set_gauge(name, value, tags = {}) end # Records a histogram entry # # @param [String,Symbol] name Name of the histogram # @param [String,Integer] value Value to record # @param [Hash{Symbol=>String}] tags Tags to apply to this record # @return [void] def observe_histogram(name, value, tags = {}) end # Passes self into the block and evaulates it # # @yieldparam [Abstract] adapter the current telemetry adapter # @return [void] def with_instance yield self if block_given? end def measure(name, tags = {}) before = Process.clock_gettime(Process::CLOCK_MONOTONIC) yield ensure after = Process.clock_gettime(Process::CLOCK_MONOTONIC) duration = (after - before) * 1000 # In miliseconds observe_histogram(name, duration, tags) 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/active_job/queue_adapter.rb
lib/dynflow/active_job/queue_adapter.rb
# frozen_string_literal: true module Dynflow module ActiveJob module QueueAdapters module QueueMethods def enqueue(job) ::Rails.application.dynflow.world.trigger do |world| job.provider_job_id = job.job_id world.plan_with_options(id: job.provider_job_id, action_class: JobWrapper, args: [job.serialize]) end end def enqueue_at(job, timestamp) job.provider_job_id = job.job_id ::Rails.application.dynflow.world .delay_with_options(id: job.provider_job_id, action_class: JobWrapper, delay_options: { :start_at => Time.at(timestamp) }, args: [job.serialize]) end end # To use Dynflow, set the queue_adapter config to +:dynflow+. # # Rails.application.config.active_job.queue_adapter = :dynflow class DynflowAdapter # For ActiveJob >= 5 include QueueMethods # For ActiveJob <= 4 extend QueueMethods end class JobWrapper < Dynflow::Action def queue input[:queue].to_sym end def plan(attributes) input[:job_class] = attributes['job_class'] input[:queue] = attributes['queue_name'] input[:job_data] = attributes plan_self end def run ::ActiveJob::Base.execute(input[:job_data]) end def label input[:job_class] end def rescue_strategy Action::Rescue::Skip end 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/debug/telemetry/persistence.rb
lib/dynflow/debug/telemetry/persistence.rb
# frozen_string_literal: true module Dynflow module Debug module Telemetry module Persistence methods = [ :load_action, :load_actions, :load_action_for_presentation, :load_action, :load_actions, :load_action_for_presentation, :load_actions_attributes, :save_action, :find_execution_plans, :find_execution_plan_counts, :delete_execution_plans, :load_execution_plan, :save_execution_plan, :find_old_execution_plans, :find_ready_delayed_plans, :delete_delayed_plans, :save_delayed_plan, :set_delayed_plan_frozen, :load_delayed_plan, :load_step, :load_steps, :save_step, :push_envelope, :pull_envelopes ] methods.each do |name| define_method(name) do |*args| Dynflow::Telemetry.measure(:dynflow_persistence, :method => name, :world => @world.id) { super(*args) } end end end end end end ::Dynflow::Persistence.prepend ::Dynflow::Debug::Persistence
ruby
MIT
e14dcdfe57cec99cc78b2f6ab521f00809b1408a
2026-01-04T17:50:16.326730Z
false
Dynflow/dynflow
https://github.com/Dynflow/dynflow/blob/e14dcdfe57cec99cc78b2f6ab521f00809b1408a/lib/dynflow/logger_adapters/delegator.rb
lib/dynflow/logger_adapters/delegator.rb
# frozen_string_literal: true module Dynflow module LoggerAdapters class Delegator < Abstract attr_reader :action_logger, :dynflow_logger def initialize(action_logger, dynflow_logger, formatters = [Formatters::Exception]) @action_logger = apply_formatters action_logger, formatters @dynflow_logger = apply_formatters dynflow_logger, formatters 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/logger_adapters/formatters.rb
lib/dynflow/logger_adapters/formatters.rb
# frozen_string_literal: true module Dynflow module LoggerAdapters module Formatters require 'dynflow/logger_adapters/formatters/abstract' require 'dynflow/logger_adapters/formatters/exception' end end end
ruby
MIT
e14dcdfe57cec99cc78b2f6ab521f00809b1408a
2026-01-04T17:50:16.326730Z
false
Dynflow/dynflow
https://github.com/Dynflow/dynflow/blob/e14dcdfe57cec99cc78b2f6ab521f00809b1408a/lib/dynflow/logger_adapters/simple.rb
lib/dynflow/logger_adapters/simple.rb
# frozen_string_literal: true require 'English' module Dynflow module LoggerAdapters class Simple < Abstract require 'logger' attr_reader :logger, :action_logger, :dynflow_logger def initialize(output = $stdout, level = Logger::DEBUG, formatters = [Formatters::Exception]) @logger = Logger.new(output) @logger.level = level @logger.formatter = method(:formatter).to_proc @action_logger = apply_formatters ProgNameWrapper.new(@logger, ' action'), formatters @dynflow_logger = apply_formatters ProgNameWrapper.new(@logger, 'dynflow'), formatters end def level @logger.level end def level=(v) @logger.level = v end private def formatter(severity, datetime, prog_name, msg) format "[%s #%d] %5s -- %s%s\n", datetime.strftime('%Y-%m-%d %H:%M:%S.%L'), $PID, severity, (prog_name ? prog_name + ': ' : ''), msg.to_s end class ProgNameWrapper def initialize(logger, prog_name) @logger = logger @prog_name = prog_name end { fatal: 4, error: 3, warn: 2, info: 1, debug: 0 }.each do |method, level| define_method method do |message = nil, &block| @logger.add level, message, @prog_name, &block end end def respond_to_missing?(method_name, include_private = false) @logger.respond_to?(method_name, include_private) || super end def method_missing(name, *args, &block) if @logger.respond_to?(name) @logger.send(name, *args, &block) else super end end def level=(v) @logger.level = v end def level @logger.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/lib/dynflow/logger_adapters/abstract.rb
lib/dynflow/logger_adapters/abstract.rb
# frozen_string_literal: true module Dynflow module LoggerAdapters class Abstract # @returns [#fatal, #error, #warn, #info, #debug] logger object for logging errors from action execution def action_logger raise NotImplementedError end # @returns [#fatal, #error, #warn, #info, #debug] logger object for logging Dynflow errors def dynflow_logger raise NotImplementedError end def level raise NotImplementedError end def level=(v) raise NotImplementedError end private def apply_formatters(base, formatters) formatters.reduce(base) { |base, formatter| formatter.new(base) } 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/logger_adapters/formatters/exception.rb
lib/dynflow/logger_adapters/formatters/exception.rb
# frozen_string_literal: true module Dynflow module LoggerAdapters module Formatters class Exception < Abstract def format(message) if ::Exception === message backtrace = Actor::BacktraceCollector.full_backtrace(message.backtrace) "#{message.message} (#{message.class})\n#{backtrace.join("\n")}" else message 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/lib/dynflow/logger_adapters/formatters/abstract.rb
lib/dynflow/logger_adapters/formatters/abstract.rb
# frozen_string_literal: true module Dynflow module LoggerAdapters module Formatters class Abstract def initialize(base) @base = base end [:fatal, :error, :warn, :info, :debug].each do |method| define_method method do |message = nil, &block| if block @base.send method, &-> { format(block.call) } else @base.send method, format(message) end end end def level=(v) @base.level = v end def level @base.level end def format(message) raise NotImplementedError end 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/web/filtering_helpers.rb
lib/dynflow/web/filtering_helpers.rb
# frozen_string_literal: true module Dynflow module Web module FilteringHelpers def supported_filter?(filter_attr) world.persistence.adapter.filtering_by.any? do |attr| attr.to_s == filter_attr.to_s end end def filtering_options(show_all = false) return @filtering_options if @filtering_options if params[:filters] params[:filters].map do |key, value| unless supported_filter?(key) halt 400, "Unsupported ordering" end end filters = params[:filters] elsif supported_filter?('state') excluded_states = show_all ? [] : ['stopped'] filters = { 'state' => ExecutionPlan.states.map(&:to_s) - excluded_states } else filters = {} end @filtering_options = Utils.indifferent_hash(filters: filters) return @filtering_options end def load_worlds(executors_only = false) @worlds = world.coordinator.find_worlds(executors_only) @executors, @clients = @worlds.partition(&:executor?) end def find_execution_plans_options(show_all = false) options = Utils.indifferent_hash({}) options.merge!(filtering_options(show_all)) options.merge!(pagination_options) options.merge!(ordering_options) end def paginate? world.persistence.adapter.pagination? end def page (params[:page] || 0).to_i end def per_page (params[:per_page] || 10).to_i end def pagination_options if paginate? { page: page, per_page: per_page } else if params[:page] || params[:per_page] halt 400, "The persistence doesn't support pagination" end return {} end end def supported_ordering?(ord_attr) world.persistence.adapter.ordering_by.any? do |attr| attr.to_s == ord_attr.to_s end end def ordering_options return @ordering_options if @ordering_options if params[:order_by] unless supported_ordering?(params[:order_by]) halt 400, "Unsupported ordering" end @ordering_options = { order_by: params[:order_by], desc: (params[:desc] == 'true') } elsif supported_ordering?('started_at') @ordering_options = { order_by: 'started_at', desc: true } else @ordering_options = {} end return @ordering_options 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/web/console.rb
lib/dynflow/web/console.rb
# frozen_string_literal: true module Dynflow module Web class Console < Sinatra::Base set :public_folder, Web.web_dir('assets') set :views, Web.web_dir('views') set :per_page, 10 helpers ERB::Util helpers Web::FilteringHelpers helpers Web::WorldHelpers helpers Web::ConsoleHelpers get('/') do options = find_execution_plans_options @plans = world.persistence.find_execution_plans(options) erb :index end get('/:execution_plan_id/actions/:action_id/sub_plans') do |execution_plan_id, action_id| options = find_execution_plans_options(true) options[:filters].update('caller_execution_plan_id' => execution_plan_id, 'caller_action_id' => action_id) @plans = world.persistence.find_execution_plans(options) erb :index end get('/status') do # TODO: create a separate page for the overall status, linking # to the more detailed pages redirect to '/worlds' end get('/worlds') do load_worlds erb :worlds end post('/worlds/execution_status') do load_worlds @executors.each do |w| hash = world.get_execution_status(w.data['id'], nil, 5).value! w.data.update(:status => hash) end erb :worlds end post('/worlds/check') do @validation_results = world.worlds_validity_check(params[:invalidate]) load_worlds erb :worlds end post('/worlds/:id/check') do |id| @validation_results = world.worlds_validity_check(params[:invalidate], id: params[:id]) load_worlds erb :worlds end get('/:id') do |id| @plan = world.persistence.load_execution_plan(id) erb :show end post('/:id/resume') do |id| plan = world.persistence.load_execution_plan(id) if plan.state != :paused redirect(url "/#{plan.id}?notice=#{url_encode('The exeuction has to be paused to be able to resume')}") else world.execute(plan.id) redirect(url "/#{plan.id}?notice=#{url_encode('The execution was resumed')}") end end post('/:id/cancel') do |id| plan = world.persistence.load_execution_plan(id) cancel_events = plan.cancel if cancel_events.empty? redirect(url "/#{plan.id}?notice=#{url_encode('Not possible to cancel at the moment')}") else redirect(url "/#{plan.id}?notice=#{url_encode("The cancel event has been propagated")}") end end post('/:id/skip/:step_id') do |id, step_id| plan = world.persistence.load_execution_plan(id) step = plan.steps[step_id.to_i] if plan.state != :paused redirect(url "/#{plan.id}?notice=#{url_encode('The exeuction has to be paused to be able to skip')}") elsif step.state != :error redirect(url "/#{plan.id}?notice=#{url_encode('The step has to be failed to be able to skip')}") else plan.skip(step) redirect(url "/#{plan.id}") end end post('/:id/cancel/:step_id') do |id, step_id| plan = world.persistence.load_execution_plan(id) step = plan.steps[step_id.to_i] if step.cancellable? world.event(plan.id, step.id, Dynflow::Action::Cancellable::Cancel) redirect(url "/#{plan.id}?notice=#{url_encode('The step was asked to cancel')}") else redirect(url "/#{plan.id}?notice=#{url_encode('The step does not support cancelling')}") end 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/web/console_helpers.rb
lib/dynflow/web/console_helpers.rb
# frozen_string_literal: true module Dynflow module Web module ConsoleHelpers def validation_result_css_class(result) if result == :valid "success" else "danger" end end def value_field(key, value) strip_heredoc(<<-HTML) <p> <b>#{key}:</b> #{h(value)} </p> HTML end def strip_heredoc(str) strip_size = str.lines.reject { |l| l =~ /^\s*$/ }.map { |l| l[/^\s*/].length }.min str.lines.map do |line| line[strip_size..-1] || '' end.join end def prettify_value(value) YAML.dump(value) end def prettyprint(value) value = prettyprint_references(value) if value pretty_value = prettify_value(value) <<-HTML <pre class="prettyprint lang-yaml">#{h(pretty_value)}</pre> HTML else "" end end def prettyprint_references(value) case value when Hash value.reduce({}) do |h, (key, val)| h.update(key => prettyprint_references(val)) end when Array value.map { |val| prettyprint_references(val) } when ExecutionPlan::OutputReference value.inspect else value end end def duration_to_s(duration) h("%0.2fs" % duration) end def load_action(step) world.persistence.load_action_for_presentation(@plan, step.action_id, step) end def step_error(step) if step.error ['<pre>', "#{h(step.error.message)} (#{h(step.error.exception_class)})\n", h(step.error.backtrace.join("\n")), '</pre>'].join end end def show_world(world_id) if registered_world = world.coordinator.find_worlds(false, id: world_id).first "%{world_id} %{world_meta}" % { world_id: world_id, world_meta: registered_world.meta.inspect } else world_id end end def show_action_data(label, value) value_html = prettyprint(value) if !value_html.empty? <<-HTML <p> <b>#{h(label)}</b> #{value_html} </p> HTML else "" end end def atom_css_classes(atom) classes = ["atom"] step = @plan.steps[atom.step_id] case step.state when :success classes << "success" when :error classes << "error" when :skipped, :skipping classes << "skipped" end return classes.join(" ") end def flow_css_classes(flow, sub_flow = nil) classes = [] case flow when Flows::Sequence classes << "sequence" when Flows::Concurrence classes << "concurrence" when Flows::Atom classes << atom_css_classes(flow) else raise "Unknown run plan #{run_plan.inspect}" end classes << atom_css_classes(sub_flow) if sub_flow.is_a? Flows::Atom return classes.join(" ") end def step_css_class(step) case step.state when :success "success" when :error "danger" when :cancelled "warning" else "default" end end def progress_width(step) if step.state == :error 100 # we want to show the red bar in full width else step.progress_done * 100 end end def step(step_id) @plan.steps[step_id] end def updated_url(new_params) url(request.path_info + "?" + Rack::Utils.build_nested_query(params.merge(Utils.stringify_keys(new_params)))) end def paginated_url(delta) h(updated_url(page: [0, page + delta].max.to_s)) end def order_link(attr, label) return h(label) unless supported_ordering?(attr) new_ordering_options = { order_by: attr.to_s, desc: false } arrow = "" if ordering_options[:order_by].to_s == attr.to_s arrow = ordering_options[:desc] ? "&#9660;" : "&#9650;" new_ordering_options[:desc] = !ordering_options[:desc] end url = updated_url(new_ordering_options) return %{<a href="#{url}"> #{arrow} #{h(label)}</a>} end def filter_checkbox(field, values) out = "<p>#{field}: %s</p>" checkboxes = values.map do |value| field_filter = filtering_options[:filters][field] checked = field_filter && field_filter.include?(value) %{<input type="checkbox" name="filters[#{field}][]" value="#{value}" #{"checked" if checked}/>#{value}} end.join(' ') out %= checkboxes return out 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/web/world_helpers.rb
lib/dynflow/web/world_helpers.rb
# frozen_string_literal: true module Dynflow module Web module WorldHelpers def world settings.world end end end end
ruby
MIT
e14dcdfe57cec99cc78b2f6ab521f00809b1408a
2026-01-04T17:50:16.326730Z
false
Dynflow/dynflow
https://github.com/Dynflow/dynflow/blob/e14dcdfe57cec99cc78b2f6ab521f00809b1408a/doc/pages/plugins/div_tag.rb
doc/pages/plugins/div_tag.rb
# frozen_string_literal: true module Jekyll class DivTag < Liquid::Block def render(context) content = super <<-HTML.gsub(/^ +\|/, '') |<#{tag} class="#{@markup}"> | #{render_content context, content} |</#{tag}> HTML end def tag @tag_name.split('_').first end def render_content(context, content) context.registers[:site].converters.find { |c| c.is_a? Jekyll::Converters::Markdown }.convert(content) end end end Liquid::Template.register_tag('div_tag', Jekyll::DivTag) Liquid::Template.register_tag('span_tag', Jekyll::DivTag)
ruby
MIT
e14dcdfe57cec99cc78b2f6ab521f00809b1408a
2026-01-04T17:50:16.326730Z
false
Dynflow/dynflow
https://github.com/Dynflow/dynflow/blob/e14dcdfe57cec99cc78b2f6ab521f00809b1408a/doc/pages/plugins/graphviz.rb
doc/pages/plugins/graphviz.rb
# frozen_string_literal: true # taken from https://raw.githubusercontent.com/kui/octopress-graphviz/master/graphviz_block.rb require 'open3' module Jekyll class GraphvizBlock < Liquid::Block DIV_CLASS_ATTR = 'graphviz-wrapper' DEFAULT_GRAPH_NAME = 'Graphviz' DOT_OPTS = '-Tsvg' DOT_EXEC = 'dot' DOT_EXTS = (ENV['PATHEXT'] || '.exe;.bat;.com').split(";") DOT_EXTS.unshift '' DOT_PATH = ENV['PATH'].split(File::PATH_SEPARATOR) .map { |a| File.join a, DOT_EXEC } .map { |a| DOT_EXTS.map { |ex| a + ex } }.flatten .find { |c| File.executable_real? c } raise "not found a executable file: #{DOT_EXEC}" if DOT_PATH.nil? DOT_CMD = "#{DOT_PATH} #{DOT_OPTS}" def initialize(tag_name, markup, tokens) super @tag_name = tag_name @title = markup or "" @title.strip! @src = "" end def render(context) code = super title = if @title.empty? then DEFAULT_GRAPH_NAME else @title end case @tag_name when 'graphviz' then render_graphviz code when 'graph' then render_graph 'graph', title, code when 'digraph' then render_graph 'digraph', title, code else raise "unknown liquid tag name: #{@tag_name}" end end def render_graphviz(code) @src = code svg = generate_svg code filter_for_inline_svg svg end def filter_for_inline_svg(code) code = remove_declarations code code = remove_xmlns_attrs code code = add_desc_attrs code code = insert_desc_elements code code = wrap_with_div code code = code.gsub(/<polygon fill="white" stroke="none"/, '<polygon fill="transparent" stroke="none"') code end def generate_svg code Open3.popen3(DOT_CMD) do |stdin, stdout, stderr| stdout.binmode stdin.print code stdin.close err = stderr.read if not (err.nil? || err.strip.empty?) raise "Error from #{DOT_CMD}:\n#{err}" end svg = stdout.read svg.force_encoding 'UTF-8' return svg end end def remove_declarations(svg) svg.sub(/<!DOCTYPE .+?>/im, '').sub(/<\?xml .+?\?>/im, '') end def remove_xmlns_attrs(svg) svg.sub(%[xmlns="http://www.w3.org/2000/svg"], '') .sub(%[xmlns:xlink="http://www.w3.org/1999/xlink"], '') end def add_desc_attrs(svg) svg.sub!("<svg", %[<svg aria-label="#{CGI::escapeHTML @title}"]) svg.sub!("<svg", %[<svg role="img"]) return svg end def insert_desc_elements(svg) inserted_elements = %[<title>#{CGI::escapeHTML @title}</title>\n] inserted_elements << %[<desc>#{CGI::escapeHTML @src}</desc>\n] svg.sub!(/(<svg [^>]*>)/, "\\1\n#{inserted_elements}") return svg end def wrap_with_div(svg) %[<div class="#{DIV_CLASS_ATTR}">#{svg}</div>] end def render_graph(type, title, code) render_graphviz %[#{type} "#{title}" { #{code} }] end end end Liquid::Template.register_tag('graphviz', Jekyll::GraphvizBlock) Liquid::Template.register_tag('graph', Jekyll::GraphvizBlock) Liquid::Template.register_tag('digraph', Jekyll::GraphvizBlock)
ruby
MIT
e14dcdfe57cec99cc78b2f6ab521f00809b1408a
2026-01-04T17:50:16.326730Z
false
Dynflow/dynflow
https://github.com/Dynflow/dynflow/blob/e14dcdfe57cec99cc78b2f6ab521f00809b1408a/doc/pages/plugins/play.rb
doc/pages/plugins/play.rb
# frozen_string_literal: true require 'pp' require 'pry' module Jekyll class Play < Generator def generate(site) # pp site # binding.pry end end end
ruby
MIT
e14dcdfe57cec99cc78b2f6ab521f00809b1408a
2026-01-04T17:50:16.326730Z
false
Dynflow/dynflow
https://github.com/Dynflow/dynflow/blob/e14dcdfe57cec99cc78b2f6ab521f00809b1408a/doc/pages/plugins/toc.rb
doc/pages/plugins/toc.rb
# frozen_string_literal: true module Jekyll module FancyToCFilter def fancytoc(input) converter = @context.registers[:site].converters.find { |c| c.is_a? Jekyll::Converters::Markdown } extensions = converter.instance_variable_get(:@parser).instance_variable_get(:@redcarpet_extensions) toc_generator = Redcarpet::Markdown.new(Redcarpet::Render::HTML_TOC, extensions) toc = toc_generator.render(input) <<-HTML unless toc.empty? <div class="toc well" data-spy="affix" data-offset-top="0" data-offset-bottom="0"> <h4>Table of content</h4> #{toc} </div> HTML end end end Liquid::Template.register_filter(Jekyll::FancyToCFilter)
ruby
MIT
e14dcdfe57cec99cc78b2f6ab521f00809b1408a
2026-01-04T17:50:16.326730Z
false
Dynflow/dynflow
https://github.com/Dynflow/dynflow/blob/e14dcdfe57cec99cc78b2f6ab521f00809b1408a/doc/pages/plugins/alert_block.rb
doc/pages/plugins/alert_block.rb
# frozen_string_literal: true require_relative 'div_tag' module Jekyll class AlertBlock < DivTag def initialize(tag_name, markup, tokens) @alert_type = tag_name.split('_').first super tag_name, markup + ' alert alert-' + @alert_type, tokens end def tag 'div' end HEADER = { 'info' => 'Note', 'warning' => 'Warning', 'danger' => 'Danger' } def render_content(context, content) super context, "**#{HEADER[@alert_type]}** \n" + content end end end Liquid::Template.register_tag('info_block', Jekyll::AlertBlock) Liquid::Template.register_tag('warning_block', Jekyll::AlertBlock) Liquid::Template.register_tag('danger_block', Jekyll::AlertBlock) # Liquid::Template.register_tag('success_block', Jekyll::AlertBlock)
ruby
MIT
e14dcdfe57cec99cc78b2f6ab521f00809b1408a
2026-01-04T17:50:16.326730Z
false
Dynflow/dynflow
https://github.com/Dynflow/dynflow/blob/e14dcdfe57cec99cc78b2f6ab521f00809b1408a/doc/pages/plugins/plantuml.rb
doc/pages/plugins/plantuml.rb
# frozen_string_literal: true # Title: PlantUML Code Blocks for Jekyll # Author: YJ Park (yjpark@gmail.com) # https://github.com/yjpark/jekyll-plantuml # Description: Integrate PlantUML into Jekyll and Octopress. # # Syntax: # {% plantuml %} # plantuml code # {% endplantuml %} # require 'open3' require 'fileutils' module Jekyll class PlantUMLBlock < Liquid::Block attr_reader :config def render(context) site = context.registers[:site] self.config = site.config['plantuml'] tmproot = File.expand_path(tmp_folder) folder = "/images/plantuml/" create_tmp_folder(tmproot, folder) code = nodelist.join + background_color filename = Digest::MD5.hexdigest(code) + ".png" filepath = tmproot + folder + filename if !File.exist?(filepath) plantuml_jar = File.expand_path(plantuml_jar_path) cmd = "java -Djava.awt.headless=true -jar " + plantuml_jar + dot_cmd + " -pipe > " + filepath result, status = Open3.capture2e(cmd, :stdin_data => code) Jekyll.logger.debug(filepath + " -->\t" + status.inspect() + "\t" + result) end site.static_files << Jekyll::StaticFile.new(site, tmproot, folder, filename) # source = "<img class=\"img-thumbnail\" src='" + folder + filename + "'>" source = "<img src='" + folder + filename + "'>" end private def config=(cfg) @config = cfg || Jekyll.logger.abort_with("Missing 'plantuml' configurations.") end def background_color config['background_color'].nil? ? '' : " skinparam backgroundColor " + config['background_color'] end def plantuml_jar_path config['plantuml_jar'] || Jekyll.logger.abort_with("Missing configuration 'plantuml.plantuml_jar'.") end def tmp_folder config['tmp_folder'] || Jekyll.logger.abort_with("Missing configuration 'plantuml.tmp_folder'.") end def dot_cmd @dot_cmd ||= begin dotpath = File.expand_path(config['dot_exe'] || '__NULL__') if File.exist?(dotpath) # Jekyll.logger.info("PlantUML: Use graphviz dot: " + dotpath) " -graphvizdot " + dotpath else # Jekyll.logger.info("PlantUML: Assume graphviz dot is in PATH.") '' end end end def create_tmp_folder(tmproot, folder) folderpath = tmproot + folder if !File.exist?(folderpath) FileUtils::mkdir_p folderpath Jekyll.logger.info("Create PlantUML image folder: " + folderpath) end end end # PlantUMLBlock end Liquid::Template.register_tag('plantuml', Jekyll::PlantUMLBlock)
ruby
MIT
e14dcdfe57cec99cc78b2f6ab521f00809b1408a
2026-01-04T17:50:16.326730Z
false
Dynflow/dynflow
https://github.com/Dynflow/dynflow/blob/e14dcdfe57cec99cc78b2f6ab521f00809b1408a/doc/pages/plugins/tags.rb
doc/pages/plugins/tags.rb
# frozen_string_literal: true require 'nuggets/range/quantile' require 'erb' module Jekyll class Tagger < Generator safe true attr_accessor :site @types = [:page, :feed] class << self; attr_accessor :types, :site; end def generate(site) self.class.site = self.site = site generate_tag_pages add_tag_cloud end private # Generates a page per tag and adds them to all the pages of +site+. # A <tt>tag_page_layout</tt> have to be defined in your <tt>_config.yml</tt> # to use this. def generate_tag_pages active_tags.each { |tag, posts| new_tag(tag, posts) } end def new_tag(tag, posts) self.class.types.each { |type| if layout = site.config["tag_#{type}_layout"] data = { 'layout' => layout, 'posts' => posts.sort.reverse!, 'tag' => tag, 'title' => tag } name = yield data if block_given? name ||= tag tag_dir = site.config["tag_#{type}_dir"] tag_dir = File.join(tag_dir, (pretty? ? name : '')) page_name = "#{pretty? ? 'index' : name}#{site.layouts[data['layout']].ext}" site.pages << TagPage.new( site, site.source, tag_dir, page_name, data ) end } end def add_tag_cloud(num = 5, name = 'tag_data') s, t = site, { name => calculate_tag_cloud(num) } s.respond_to?(:add_payload) ? s.add_payload(t) : s.config.update(t) end # Calculates the css class of every tag for a tag cloud. The possible # classes are: set-1..set-5. # # [[<TAG>, <CLASS>], ...] def calculate_tag_cloud(num = 5) range = 0 tags = active_tags.map { |tag, posts| [tag.to_s, range < (size = posts.size) ? range = size : size] } range = 1..range tags.sort!.map! { |tag, size| [tag, range.quantile(size, num)] } end def active_tags return site.tags unless site.config["ignored_tags"] site.tags.reject { |t| site.config["ignored_tags"].include? t[0] } end def pretty? @pretty ||= (site.permalink_style == :pretty || site.config['tag_permalink_style'] == 'pretty') end end class TagPage < Page def initialize(site, base, dir, name, data = {}) self.content = data.delete('content') || '' self.data = data super(site, base, dir[-1, 1] == '/' ? dir : '/' + dir, name) end def read_yaml(*) # Do nothing end end module Filters def tag_cloud(site) active_tag_data.map { |tag, set| tag_link(tag, tag_url(tag), :class => "set-#{set} label label-default") }.join(' ') end def tag_link(tag, url = tag_url(tag), html_opts = nil) html_opts &&= ' ' << html_opts.map { |k, v| %Q{#{k}="#{v}"} }.join(' ') %Q{<a href="#{url}"#{html_opts}>#{tag}</a>} end def tag_url(tag, type = :page, site = Tagger.site) # FIXME generate full url for atom.xml page url = File.join('', site.config["tag_#{type}_dir"], ERB::Util.u(tag)) site.permalink_style == :pretty || site.config['tag_permalink_style'] == 'pretty' ? url : url << '.html' end def tags(obj) tags = obj['tags'].dup tags.map! { |t| t.first } if tags.first.is_a?(Array) tags.map! { |t| tag_link(t, tag_url(t), rel: 'tag', class: 'label label-default') if t.is_a?(String) }.compact! tags.join(' ') end def keywords(obj) return '' if not obj['tags'] tags = obj['tags'].dup tags.join(',') end def active_tag_data(site = Tagger.site) return site.config['tag_data'] unless site.config["ignored_tags"] site.config["tag_data"].reject { |tag, set| site.config["ignored_tags"].include? tag } end end end
ruby
MIT
e14dcdfe57cec99cc78b2f6ab521f00809b1408a
2026-01-04T17:50:16.326730Z
false
aidewoode/wahwah
https://github.com/aidewoode/wahwah/blob/c451fbe9a49d04e1dd8743e904215f1a7cdb9918/test/wahwah_test.rb
test/wahwah_test.rb
# frozen_string_literal: true require "test_helper" require "fileutils" class WahWahTest < Minitest::Test def test_not_exist_file assert_raises(WahWah::WahWahArgumentError) do WahWah.open("fake.mp3") end end def test_not_supported_formate assert_raises(WahWah::WahWahArgumentError) do WahWah.open("test/files/cover.jpeg") end end def test_empty_file assert_raises(WahWah::WahWahArgumentError) do WahWah.open("test/files/empty.mp3") end end def test_path_string_as_argument tag = WahWah.open("test/files/id3v1.mp3") assert_instance_of WahWah::Mp3Tag, tag assert file_io_closed?(tag) end def test_path_name_as_argument tag = WahWah.open(Pathname.new("test/files/id3v1.mp3")) assert_instance_of WahWah::Mp3Tag, tag assert file_io_closed?(tag) end def test_opened_file_as_argument File.open "test/files/id3v1.mp3" do |file| tag = WahWah.open(file) assert_instance_of WahWah::Mp3Tag, tag assert !file.closed? end end def test_support_formats assert_equal %w[mp3 ogg oga opus wav flac wma m4a].sort, WahWah.support_formats.sort end def test_return_correct_instance WahWah::FORMATE_MAPPING.values.flatten.each do |format| FileUtils.touch("invalid.#{format}") `echo 'te' > invalid.#{format}` end assert_instance_of WahWah::Mp3Tag, WahWah.open("invalid.mp3") assert_instance_of WahWah::OggTag, WahWah.open("invalid.ogg") assert_instance_of WahWah::OggTag, WahWah.open("invalid.oga") assert_instance_of WahWah::OggTag, WahWah.open("invalid.opus") assert_instance_of WahWah::RiffTag, WahWah.open("invalid.wav") assert_instance_of WahWah::FlacTag, WahWah.open("invalid.flac") assert_instance_of WahWah::AsfTag, WahWah.open("invalid.wma") assert_instance_of WahWah::Mp4Tag, WahWah.open("invalid.m4a") ensure WahWah::FORMATE_MAPPING.values.flatten.each do |format| FileUtils.remove_file("invalid.#{format}") end end end
ruby
MIT
c451fbe9a49d04e1dd8743e904215f1a7cdb9918
2026-01-04T17:50:26.827863Z
false
aidewoode/wahwah
https://github.com/aidewoode/wahwah/blob/c451fbe9a49d04e1dd8743e904215f1a7cdb9918/test/test_helper.rb
test/test_helper.rb
# frozen_string_literal: true require "simplecov" SimpleCov.start do add_filter "/test/" if ENV["CI"] require "simplecov-lcov" SimpleCov::Formatter::LcovFormatter.config do |c| c.report_with_single_file = true c.single_report_path = "coverage/lcov.info" end formatter SimpleCov::Formatter::LcovFormatter end end $LOAD_PATH.unshift File.expand_path("../../lib", __FILE__) require "wahwah" require "minitest/autorun" module TestHelpers def binary_data(file_path) File.read(file_path).force_encoding("BINARY").strip end def file_io_closed?(tag) tag.instance_variable_get(:@file_io).closed? end end Minitest::Test.send(:include, TestHelpers)
ruby
MIT
c451fbe9a49d04e1dd8743e904215f1a7cdb9918
2026-01-04T17:50:26.827863Z
false
aidewoode/wahwah
https://github.com/aidewoode/wahwah/blob/c451fbe9a49d04e1dd8743e904215f1a7cdb9918/test/wahwah/tag_test.rb
test/wahwah/tag_test.rb
# frozen_string_literal: true require "test_helper" class WahWah::TagTest < Minitest::Test class SubTag < WahWah::Tag; end class SubTagWithParse < WahWah::Tag def parse end end def test_sub_class_not_implemented_parse_method assert_raises(WahWah::WahWahNotImplementedError) do File.open "test/files/id3v1.mp3" do |file| SubTag.new(file) end end end def test_have_necessary_attributes_method File.open "test/files/id3v1.mp3" do |file| tag = SubTagWithParse.new(file) assert_respond_to tag, :title assert_respond_to tag, :artist assert_respond_to tag, :album assert_respond_to tag, :albumartist assert_respond_to tag, :composer assert_respond_to tag, :comments assert_respond_to tag, :track assert_respond_to tag, :track_total assert_respond_to tag, :duration assert_respond_to tag, :file_size assert_respond_to tag, :genre assert_respond_to tag, :year assert_respond_to tag, :disc assert_respond_to tag, :disc_total assert_respond_to tag, :images assert_respond_to tag, :sample_rate assert_respond_to tag, :bit_depth assert_respond_to tag, :lyrics end end def test_initialized_attributes File.open "test/files/id3v1.mp3" do |file| tag = SubTagWithParse.new(file) assert_equal file.size, tag.file_size assert_equal [], tag.comments assert_equal [], tag.images end end def test_inspect File.open "test/files/id3v1.mp3" do |file| tag_inspect = SubTagWithParse.new(file).inspect WahWah::Tag::INTEGER_ATTRIBUTES.each do |attr_name| assert_includes tag_inspect, "#{attr_name}: " end end end def test_io_rewound_before_parse File.open "test/files/id3v1.mp3" do |file| file.read(10) tag = SubTagWithParse.new(file) assert tag.instance_variable_get(:@file_io).pos.zero? end end end
ruby
MIT
c451fbe9a49d04e1dd8743e904215f1a7cdb9918
2026-01-04T17:50:26.827863Z
false
aidewoode/wahwah
https://github.com/aidewoode/wahwah/blob/c451fbe9a49d04e1dd8743e904215f1a7cdb9918/test/wahwah/mp4_tag_test.rb
test/wahwah/mp4_tag_test.rb
# frozen_string_literal: true require "test_helper" class WahWah::Mp4TagTest < Minitest::Test def test_parse_meta_on_udta_atom File.open "test/files/udta_meta.m4a" do |file| tag = WahWah::Mp4Tag.new(file) meta_atom = WahWah::Mp4::Atom.find(File.open(file.path), "moov", "udta", "meta") image = tag.images.first assert meta_atom.valid? assert_equal "China Girl", tag.title assert_equal "Iggy Pop", tag.artist assert_equal "Iggy Pop", tag.albumartist assert_equal "Iggy Pop", tag.composer assert_equal "The Idiot", tag.album assert_equal "1977", tag.year assert_equal "Rock", tag.genre assert_equal 5, tag.track assert_equal 8, tag.track_total assert_equal 1, tag.disc assert_equal 1, tag.disc_total assert_equal ["Iggy Pop Rocks"], tag.comments assert_equal "image/jpeg", image[:mime_type] assert_equal :cover, image[:type] assert_equal binary_data("test/files/cover.jpeg"), image[:data].strip assert_equal 8.057324263038549, tag.duration assert_equal 128, tag.bitrate assert_equal 44100, tag.sample_rate assert_equal "I'm feeling tragic like I'm Marlon Brando", tag.lyrics assert_nil tag.bit_depth end end def test_parse_meta_on_moov_atom File.open "test/files/moov_meta.m4a" do |file| tag = WahWah::Mp4Tag.new(file) meta_atom = WahWah::Mp4::Atom.find(File.open(file.path), "moov", "meta") udta_meta_atom = WahWah::Mp4::Atom.find(File.open(file.path), "moov", "udta", "meta") image = tag.images.first assert meta_atom.valid? assert !udta_meta_atom.valid? assert_equal "China Girl", tag.title assert_equal "Iggy Pop", tag.artist assert_equal "Iggy Pop", tag.albumartist assert_equal "Iggy Pop", tag.composer assert_equal "The Idiot", tag.album assert_equal "1977", tag.year assert_equal "Rock", tag.genre assert_equal 5, tag.track assert_equal 8, tag.track_total assert_equal 1, tag.disc assert_equal 1, tag.disc_total assert_equal ["Iggy Pop Rocks"], tag.comments assert_equal "image/jpeg", image[:mime_type] assert_equal :cover, image[:type] assert_equal binary_data("test/files/cover.jpeg"), image[:data].strip assert_equal 285.04816326530613, tag.duration assert_equal 256, tag.bitrate assert_equal 44100, tag.sample_rate assert_equal "I'm feeling tragic like I'm Marlon Brando", tag.lyrics assert_nil tag.bit_depth end end def test_parse_alac_encoded File.open "test/files/alac.m4a" do |file| tag = WahWah::Mp4Tag.new(file) image = tag.images.first assert_equal "China Girl", tag.title assert_equal "Iggy Pop", tag.artist assert_equal "Iggy Pop", tag.albumartist assert_equal "Iggy Pop", tag.composer assert_equal "The Idiot", tag.album assert_equal "1977", tag.year assert_equal "Rock", tag.genre assert_equal 5, tag.track assert_equal 1, tag.disc assert_equal 8.0, tag.duration assert_equal 3, tag.bitrate assert_equal 16, tag.bit_depth assert_equal 44100, tag.sample_rate assert_equal "I'm feeling tragic like I'm Marlon Brando", tag.lyrics assert_equal "image/jpeg", image[:mime_type] assert_equal :cover, image[:type] assert_equal binary_data("test/files/cover.jpeg"), image[:data].strip end end def test_parse_extended_header_atom File.open "test/files/extended_header_atom.m4a" do |file| tag = WahWah::Mp4Tag.new(file) meta_atom = WahWah::Mp4::Atom.find(File.open(file.path), "moov", "udta", "meta") image = tag.images.first assert meta_atom.valid? assert_equal "Test Recording 123", tag.title assert_equal "The Exemplars", tag.artist assert_equal "The Exemplars", tag.albumartist assert_equal "The Exemplars", tag.albumartist assert_equal "The Example Album", tag.album assert_equal "2024", tag.year assert_equal "Books & Spoken", tag.genre assert_equal 1, tag.track assert_equal 1, tag.track_total assert_equal 1, tag.disc assert_equal 1, tag.disc_total assert_equal ["This is an example comment"], tag.comments assert_equal "image/png", image[:mime_type] assert_equal :cover, image[:type] assert_equal 3.0399583333333333, tag.duration assert_equal 64, tag.bitrate assert_equal 48000, tag.sample_rate assert_equal "Test 123, Test 123.", tag.lyrics assert_nil tag.bit_depth end end end
ruby
MIT
c451fbe9a49d04e1dd8743e904215f1a7cdb9918
2026-01-04T17:50:26.827863Z
false
aidewoode/wahwah
https://github.com/aidewoode/wahwah/blob/c451fbe9a49d04e1dd8743e904215f1a7cdb9918/test/wahwah/riff_tag_test.rb
test/wahwah/riff_tag_test.rb
# frozen_string_literal: true require "test_helper" class WahWah::RiffTagTest < Minitest::Test def test_id3_tag_file File.open "test/files/id3v2.wav" do |file| tag = WahWah::RiffTag.new(file) image = tag.images.first assert_equal "China Girl", tag.title assert_equal "Iggy Pop", tag.artist assert_equal "Iggy Pop", tag.albumartist assert_equal "Iggy Pop", tag.composer assert_equal "The Idiot", tag.album assert_equal "1977", tag.year assert_equal "Rock", tag.genre assert_equal 5, tag.track assert_equal 8, tag.track_total assert_equal 1, tag.disc assert_equal 1, tag.disc_total assert_equal ["Iggy Pop Rocks"], tag.comments assert_equal "image/jpeg", image[:mime_type] assert_equal :cover_front, image[:type] assert_equal binary_data("test/files/cover.jpeg"), image[:data].strip assert_equal 8.001133947554926, tag.duration assert_equal 1411, tag.bitrate assert_equal "Stereo", tag.channel_mode assert_equal 44100, tag.sample_rate assert_equal 16, tag.bit_depth end end def test_riff_info_tag_file File.open "test/files/riff_info.wav" do |file| tag = WahWah::RiffTag.new(file) assert_equal "China Girl", tag.title assert_equal "Iggy Pop", tag.artist assert_equal "The Idiot", tag.album assert_equal "1977", tag.year assert_equal "Rock", tag.genre assert_equal ["Iggy Pop Rocks"], tag.comments assert_equal 8.001133947554926, tag.duration assert_equal 1411, tag.bitrate assert_equal "Stereo", tag.channel_mode assert_equal 44100, tag.sample_rate assert_equal 16, tag.bit_depth end end def test_tag_that_riff_chunk_without_data_chunk File.open "test/files/riff_chunk_without_data_chunk.wav" do |file| tag = WahWah::RiffTag.new(file) assert_equal "China Girl", tag.title assert_equal "Iggy Pop", tag.artist assert_equal "The Idiot", tag.album assert_equal "1977", tag.year assert_equal "Rock", tag.genre assert_equal ["Iggy Pop Rocks"], tag.comments assert_equal 8, tag.duration.round assert_equal 1411, tag.bitrate assert_equal "Stereo", tag.channel_mode assert_equal 44100, tag.sample_rate assert_equal 16, tag.bit_depth end end end
ruby
MIT
c451fbe9a49d04e1dd8743e904215f1a7cdb9918
2026-01-04T17:50:26.827863Z
false
aidewoode/wahwah
https://github.com/aidewoode/wahwah/blob/c451fbe9a49d04e1dd8743e904215f1a7cdb9918/test/wahwah/tag_delegate_test.rb
test/wahwah/tag_delegate_test.rb
# frozen_string_literal: true require "test_helper" class WahWah::TagDelegateTest < Minitest::Test class BaseTag attr_reader :title def initialize @title = "title" end end class Tag < BaseTag extend WahWah::TagDelegate tag_delegate :@tag, :title end def setup @tag = Object.new @tag.define_singleton_method(:title) { "tag_title" } end def test_attibute_method_delegate_to_tag tag = Tag.new tag.instance_variable_set(:@tag, @tag) assert_equal "tag_title", tag.title end def test_not_delegate_when_tag_is_nil tag = Tag.new tag.instance_variable_set(:@tag, nil) assert_equal "title", tag.title end def test_not_delegate_when_tag_not_defined tag = Tag.new assert_equal "title", tag.title end end
ruby
MIT
c451fbe9a49d04e1dd8743e904215f1a7cdb9918
2026-01-04T17:50:26.827863Z
false
aidewoode/wahwah
https://github.com/aidewoode/wahwah/blob/c451fbe9a49d04e1dd8743e904215f1a7cdb9918/test/wahwah/flac_tag_test.rb
test/wahwah/flac_tag_test.rb
# frozen_string_literal: true require "test_helper" class WahWah::FlacTagTest < Minitest::Test def test_vorbis_comment_tag_file File.open "test/files/vorbis_comment.flac" do |file| tag = WahWah::FlacTag.new(file) image = tag.images.first assert_equal "China Girl", tag.title assert_equal "Iggy Pop", tag.artist assert_equal "Iggy Pop", tag.albumartist assert_equal "Iggy Pop", tag.composer assert_equal "The Idiot", tag.album assert_equal "1977", tag.year assert_equal "Rock", tag.genre assert_equal 5, tag.track assert_equal 1, tag.disc assert_equal 8.0, tag.duration assert_equal 705, tag.bitrate assert_equal 16, tag.bit_depth assert_equal 44100, tag.sample_rate assert_equal "image/jpeg", image[:mime_type] assert_equal :cover_front, image[:type] assert_equal binary_data("test/files/cover.jpeg"), image[:data].strip assert_equal "I'm feeling tragic like I'm Marlon Brando", tag.lyrics end end def test_id3_header_tag_file File.open "test/files/id3_header.flac" do |file| tag = WahWah::FlacTag.new(file) assert_equal "ID3", File.read("test/files/id3_header.flac", 3) assert_equal "China Girl", tag.title assert_equal "Iggy Pop", tag.artist assert_equal "Iggy Pop", tag.albumartist assert_equal "Iggy Pop", tag.composer assert_equal "The Idiot", tag.album assert_equal "1977", tag.year assert_equal "Rock", tag.genre assert_equal 5, tag.track assert_equal 1, tag.disc assert_equal 0.45351473922902497, tag.duration assert_equal 705, tag.bitrate assert_equal 16, tag.bit_depth assert_equal 44100, tag.sample_rate assert_equal "I'm feeling tragic like I'm Marlon Brando", tag.lyrics end end def test_invalid_tag_file File.open "test/files/invalid_tag.flac" do |file| tag = WahWah::FlacTag.new(file) assert_nil tag.title assert_nil tag.artist assert_nil tag.albumartist assert_nil tag.composer assert_nil tag.album assert_nil tag.year assert_nil tag.genre assert_nil tag.track assert_nil tag.disc assert_equal 3.684716553287982, tag.duration assert_equal 705, tag.bitrate assert_equal 16, tag.bit_depth assert_equal 44100, tag.sample_rate end end end
ruby
MIT
c451fbe9a49d04e1dd8743e904215f1a7cdb9918
2026-01-04T17:50:26.827863Z
false
aidewoode/wahwah
https://github.com/aidewoode/wahwah/blob/c451fbe9a49d04e1dd8743e904215f1a7cdb9918/test/wahwah/lazy_read_test.rb
test/wahwah/lazy_read_test.rb
# frozen_string_literal: true require "test_helper" class WahWah::LazyReadTest < Minitest::Test class Tag prepend WahWah::LazyRead def initialize @file_io.read(4) @size = 34 end end def setup content = StringIO.new("\x00\x00\x00\"\x10\x00\x10\x00\x00\x00\x0E\x00\x00\x10\n\xC4B\xF0\x00\x05b d\xA9\xFD\x7Fl\xB0\xE1\xC9Z\xFE\xCD\xF3\xA3iqO".b) @tag = Tag.new(content) end def test_reposond_to_size_method assert_respond_to @tag, :size end def test_get_data assert_equal "\x10\x00\x10\x00\x00\x00\x0E\x00\x00\x10\n\xC4B\xF0\x00\x05b d\xA9\xFD\x7Fl\xB0\xE1\xC9Z\xFE\xCD\xF3\xA3iqO".b, @tag.data end def test_skip_data @tag.skip assert_equal 38, @tag.instance_variable_get(:@file_io).send(:pos) end def test_get_data_when_string_io_closed string_io = StringIO.new("\x00\x00\x00\"\x10\x00\x10\x00\x00\x00\x0E\x00\x00\x10\n\xC4B\xF0\x00\x05b d\xA9\xFD\x7Fl\xB0\xE1\xC9Z\xFE\xCD\xF3\xA3iqO".b) tag = Tag.new(string_io) string_io.close assert_equal "\x10\x00\x10\x00\x00\x00\x0E\x00\x00\x10\n\xC4B\xF0\x00\x05b d\xA9\xFD\x7Fl\xB0\xE1\xC9Z\xFE\xCD\xF3\xA3iqO".b, tag.data assert string_io.closed? end def test_get_data_when_file_io_closed file_io = File.open "test/files/id3v1.mp3" tag = Tag.new(file_io) file_io.close assert_equal "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00Xi".b, tag.data assert file_io.closed? end end
ruby
MIT
c451fbe9a49d04e1dd8743e904215f1a7cdb9918
2026-01-04T17:50:26.827863Z
false
aidewoode/wahwah
https://github.com/aidewoode/wahwah/blob/c451fbe9a49d04e1dd8743e904215f1a7cdb9918/test/wahwah/helper_test.rb
test/wahwah/helper_test.rb
# frozen_string_literal: true require "test_helper" class WahWah::HelperTest < Minitest::Test def test_encode_to_utf8 test_string = "àáâãäåæçèéêëìíîï" iso_8859_1_string = test_string.encode("ISO-8859-1").b utf_16_string = test_string.encode("UTF-16").b utf_16_be_string = test_string.encode("UTF-16BE").b utf_8_string = test_string.encode("UTF-8").b assert_equal test_string, WahWah::Helper.encode_to_utf8(iso_8859_1_string, source_encoding: "ISO-8859-1") assert_equal test_string, WahWah::Helper.encode_to_utf8(utf_16_string, source_encoding: "UTF-16") assert_equal test_string, WahWah::Helper.encode_to_utf8(utf_16_be_string, source_encoding: "UTF-16BE") assert_equal test_string, WahWah::Helper.encode_to_utf8(utf_8_string) assert_equal "", WahWah::Helper.encode_to_utf8(utf_16_string) end def test_id3_size_caculate bits_string = "00000001000000010000000100000001" assert_equal 2113665, WahWah::Helper.id3_size_caculate(bits_string) assert_equal 16843009, WahWah::Helper.id3_size_caculate(bits_string, has_zero_bit: false) end def test_split_with_terminator assert_equal [], WahWah::Helper.split_with_terminator("hi there".b, 1) assert_equal ["hi", "there\x00!"], WahWah::Helper.split_with_terminator("hi\x00there\x00!".b, 1) assert_equal ["hi", "there\x00\x00!"], WahWah::Helper.split_with_terminator("hi\x00\x00there\x00\x00!".b, 2) assert_equal ["h\x00", "there\x00\x00!"], WahWah::Helper.split_with_terminator("h\x00\x00\x00there\x00\x00!".b, 2) end def test_file_format_with_extension expected_formats = { "alac.m4a" => "m4a", "id3v1.mp3" => "mp3", "id3v24.mp3" => "mp3", "vorbis_comment.flac" => "flac", "vorbis_tag.ogg" => "ogg", "id3v2.wav" => "wav", "riff_info.wav" => "wav", "test.wma" => "wma" } expected_formats.each do |filename, file_format| File.open File.join("test/files", filename) do |file| assert_equal file_format, WahWah::Helper.file_format(file), "Failed to recognize \"#{filename}\"" end end end def test_file_format_without_extension expected_formats = { "alac.m4a" => "m4a", "id3v1.mp3" => "mp3", "id3v24.mp3" => "mp3", "vorbis_comment.flac" => "flac", "vorbis_tag.ogg" => "ogg", "id3v2.wav" => "wav", "riff_info.wav" => "wav", "test.wma" => "wma" } expected_formats.each do |filename, file_format| File.open File.join("test/files", filename) do |file| file.stub :path, nil do assert_equal file_format, WahWah::Helper.file_format(file), "Failed to recognize \"#{filename}\"" assert file.pos.zero? end end end end def test_byte_string_to_guid assert_equal "8CABDCA1-A947-11CF-8EE4-00C00C205365", WahWah::Helper.byte_string_to_guid("\xA1\xDC\xAB\x8CG\xA9\xCF\x11\x8E\xE4\x00\xC0\f Se".b) end end
ruby
MIT
c451fbe9a49d04e1dd8743e904215f1a7cdb9918
2026-01-04T17:50:26.827863Z
false
aidewoode/wahwah
https://github.com/aidewoode/wahwah/blob/c451fbe9a49d04e1dd8743e904215f1a7cdb9918/test/wahwah/asf_tag_test.rb
test/wahwah/asf_tag_test.rb
# frozen_string_literal: true require "test_helper" class WahWah::AsfTagTest < Minitest::Test def test_parse File.open "test/files/test.wma" do |file| tag = WahWah::AsfTag.new(file) assert_equal "China Girl", tag.title assert_equal "Iggy Pop", tag.artist assert_equal "Iggy Pop", tag.albumartist assert_equal "Iggy Pop", tag.composer assert_equal "The Idiot", tag.album assert_equal "1977", tag.year assert_equal "Rock", tag.genre assert_equal 5, tag.track assert_equal 1, tag.disc assert_equal ["Iggy Pop Rocks"], tag.comments assert_equal 8.033, tag.duration assert_equal 192, tag.bitrate assert_equal 44100, tag.sample_rate assert_equal 16, tag.bit_depth assert_equal "I'm feeling tragic like I'm Marlon Brando", tag.lyrics end end end
ruby
MIT
c451fbe9a49d04e1dd8743e904215f1a7cdb9918
2026-01-04T17:50:26.827863Z
false
aidewoode/wahwah
https://github.com/aidewoode/wahwah/blob/c451fbe9a49d04e1dd8743e904215f1a7cdb9918/test/wahwah/ogg_tag_test.rb
test/wahwah/ogg_tag_test.rb
# frozen_string_literal: true require "test_helper" class WahWah::OggTagTest < Minitest::Test def test_vorbis_tag_file File.open "test/files/vorbis_tag.ogg" do |file| tag = WahWah::OggTag.new(file) assert_instance_of WahWah::Ogg::VorbisTag, tag.instance_variable_get(:@tag) assert_equal "China Girl", tag.title assert_equal "Iggy Pop", tag.artist assert_equal "Iggy Pop", tag.albumartist assert_equal "Iggy Pop", tag.composer assert_equal "The Idiot", tag.album assert_equal "1977", tag.year assert_equal "Rock", tag.genre assert_equal 5, tag.track assert_equal 1, tag.disc assert_equal 8.0, tag.duration assert_equal 192, tag.bitrate assert_equal 44100, tag.sample_rate assert_nil tag.bit_depth assert_equal "I'm feeling tragic like I'm Marlon Brando", tag.lyrics end end def test_opus_tag_file File.open "test/files/opus_tag.opus" do |file| tag = WahWah::OggTag.new(file) assert_instance_of WahWah::Ogg::OpusTag, tag.instance_variable_get(:@tag) assert_equal "China Girl", tag.title assert_equal "Iggy Pop", tag.artist assert_equal "Iggy Pop", tag.albumartist assert_equal "Iggy Pop", tag.composer assert_equal "The Idiot", tag.album assert_equal "1977", tag.year assert_equal "Rock", tag.genre assert_equal 5, tag.track assert_equal 1, tag.disc assert_equal 8.000020833333334, tag.duration assert_equal 2, tag.bitrate assert_equal 48000, tag.sample_rate assert_nil tag.bit_depth assert_equal "I'm feeling tragic like I'm Marlon Brando", tag.lyrics end end def test_flac_tag_file File.open "test/files/flac_tag.oga" do |file| tag = WahWah::OggTag.new(file) assert_instance_of WahWah::Ogg::FlacTag, tag.instance_variable_get(:@tag) assert_equal "China Girl", tag.title assert_equal "Iggy Pop", tag.artist assert_equal "Iggy Pop", tag.albumartist assert_equal "Iggy Pop", tag.composer assert_equal "The Idiot", tag.album assert_equal "1977", tag.year assert_equal "Rock", tag.genre assert_equal 5, tag.track assert_equal 1, tag.disc assert_equal 8.0, tag.duration assert_equal 705, tag.bitrate assert_equal 44100, tag.sample_rate assert_equal 16, tag.bit_depth assert_equal "I'm feeling tragic like I'm Marlon Brando", tag.lyrics end end def test_lazy_duration File.open("test/files/vorbis_tag.ogg", "rb") do |file| tag = WahWah::OggTag.new(file) assert tag.instance_variable_get(:@file_io).pos < file.size assert_nil tag.instance_variable_get(:@duration) tag.duration assert_equal 8.0, tag.instance_variable_get(:@duration) end end def test_lazy_bitrate File.open("test/files/vorbis_tag.ogg", "rb") do |file| tag = WahWah::OggTag.new(file) assert tag.instance_variable_get(:@file_io).pos < file.size assert_nil tag.instance_variable_get(:@bitrate) tag.bitrate assert_equal 192, tag.instance_variable_get(:@bitrate) end end def test_eager_duration_and_bitrate File.open("test/files/vorbis_tag.ogg", "rb") do |file| tag = WahWah::OggTag.new(file, from_path: true) assert_equal 8.0, tag.instance_variable_get(:@duration) assert_equal 192, tag.instance_variable_get(:@bitrate) end end end
ruby
MIT
c451fbe9a49d04e1dd8743e904215f1a7cdb9918
2026-01-04T17:50:26.827863Z
false
aidewoode/wahwah
https://github.com/aidewoode/wahwah/blob/c451fbe9a49d04e1dd8743e904215f1a7cdb9918/test/wahwah/mp3_tag_test.rb
test/wahwah/mp3_tag_test.rb
# frozen_string_literal: true require "test_helper" class WahWah::Mp3TagTest < Minitest::Test def test_id3v1_tag_file File.open "test/files/id3v1.mp3" do |file| tag = WahWah::Mp3Tag.new(file) assert !tag.id3v2? assert tag.is_vbr? assert_equal "v1", tag.id3_version assert_equal "China Girl", tag.title assert_equal "Iggy Pop", tag.artist assert_equal "The Idiot", tag.album assert_equal "1977", tag.year assert_equal "Rock", tag.genre assert_equal 5, tag.track assert_equal ["Iggy Pop Rocks"], tag.comments assert_equal 8.045714285714286, tag.duration assert_equal 32, tag.bitrate assert_equal "MPEG1", tag.mpeg_version assert_equal "layer3", tag.mpeg_layer assert_equal "Joint Stereo", tag.channel_mode assert_equal 44100, tag.sample_rate assert_nil tag.bit_depth end end def test_id3v22_tag_file File.open "test/files/id3v22.mp3" do |file| tag = WahWah::Mp3Tag.new(file) image = tag.images.first assert tag.id3v2? assert !tag.is_vbr? assert_equal "v2.2", tag.id3_version assert_equal "You Are The One", tag.title assert_equal "Shiny Toy Guns", tag.artist assert_nil tag.albumartist assert_nil tag.composer assert_equal "We Are Pilots", tag.album assert_equal "2006", tag.year assert_equal "Alternative", tag.genre assert_equal 1, tag.track assert_equal 11, tag.track_total assert_nil tag.disc assert_nil tag.disc_total assert_equal "0", tag.comments.first assert_equal "image/jpeg", image[:mime_type] assert_equal :other, image[:type] assert_equal binary_data("test/files/id3v22_cover.jpeg"), image[:data].strip assert_equal 0.36354166666666665, tag.duration assert_equal 192, tag.bitrate assert_equal "MPEG1", tag.mpeg_version assert_equal "layer3", tag.mpeg_layer assert_equal "Stereo", tag.channel_mode assert_equal 44100, tag.sample_rate assert tag.lyrics.start_with?("Black rose") assert_nil tag.bit_depth end end def test_id3v23_tag_file File.open "test/files/id3v23.mp3" do |file| tag = WahWah::Mp3Tag.new(file) image = tag.images.first assert tag.id3v2? assert tag.is_vbr? assert_equal "v2.3", tag.id3_version assert_equal "China Girl", tag.title assert_equal "Iggy Pop", tag.artist assert_equal "Iggy Pop", tag.albumartist assert_equal "Iggy Pop", tag.composer assert_equal "The Idiot", tag.album assert_equal "1977", tag.year assert_equal "Rock", tag.genre assert_equal 5, tag.track assert_equal 8, tag.track_total assert_equal 1, tag.disc assert_equal 1, tag.disc_total assert_equal ["Iggy Pop Rocks"], tag.comments assert_equal "image/jpeg", image[:mime_type] assert_equal :cover_front, image[:type] assert_equal binary_data("test/files/cover.jpeg"), image[:data].strip assert_equal 8.045714285714286, tag.duration assert_equal 32, tag.bitrate assert_equal "MPEG1", tag.mpeg_version assert_equal "layer3", tag.mpeg_layer assert_equal "Joint Stereo", tag.channel_mode assert_equal 44100, tag.sample_rate assert_equal "I'm feeling tragic like I'm Marlon Brando", tag.lyrics assert_nil tag.bit_depth end end def test_id3v24_tag_file File.open "test/files/id3v24.mp3" do |file| tag = WahWah::Mp3Tag.new(file) image = tag.images.first assert tag.id3v2? assert tag.is_vbr? assert_equal "v2.4", tag.id3_version assert_equal "China Girl", tag.title assert_equal "Iggy Pop", tag.artist assert_equal "Iggy Pop", tag.albumartist assert_equal "Iggy Pop", tag.composer assert_equal "The Idiot", tag.album assert_equal "1977", tag.year assert_equal "Custom Genre", tag.genre assert_equal 5, tag.track assert_equal 8, tag.track_total assert_equal 1, tag.disc assert_equal 1, tag.disc_total assert_equal ["Iggy Pop Rocks"], tag.comments assert_equal "image/jpeg", image[:mime_type] assert_equal :cover_front, image[:type] assert_equal binary_data("test/files/cover.jpeg"), image[:data].strip assert_equal 8.045714285714286, tag.duration assert_equal 32, tag.bitrate assert_equal "MPEG1", tag.mpeg_version assert_equal "layer3", tag.mpeg_layer assert_equal "Joint Stereo", tag.channel_mode assert_equal 44100, tag.sample_rate assert_equal "I'm feeling tragic like I'm Marlon Brando", tag.lyrics assert_nil tag.bit_depth end end def test_id3v2_with_extented_tag_file File.open "test/files/id3v2_extended_header.mp3" do |file| tag = WahWah::Mp3Tag.new(file) assert tag.id3v2? assert !tag.is_vbr? assert_equal "v2.4", tag.id3_version assert_equal "title", tag.title assert_equal 0.4963125, tag.duration assert_equal 128, tag.bitrate assert_equal "MPEG2", tag.mpeg_version assert_equal "layer3", tag.mpeg_layer assert_equal "Single Channel", tag.channel_mode assert_equal 22050, tag.sample_rate assert_nil tag.bit_depth end end def test_vbri_header_file File.open "test/files/vbri_header.mp3" do |file| tag = WahWah::Mp3Tag.new(file) assert tag.id3v2? assert tag.is_vbr? assert_equal "v2.3", tag.id3_version assert_equal "China Girl", tag.title assert_equal "Iggy Pop", tag.artist assert_equal "Iggy Pop", tag.albumartist assert_equal "Iggy Pop", tag.composer assert_equal "The Idiot", tag.album assert_equal "1977", tag.year assert_equal "Rock", tag.genre assert_equal 5, tag.track assert_equal 8, tag.track_total assert_equal 1, tag.disc assert_equal 1, tag.disc_total assert_equal ["Iggy Pop Rocks"], tag.comments assert_equal 222.19755102040818, tag.duration assert_equal 233, tag.bitrate assert_equal "MPEG1", tag.mpeg_version assert_equal "layer3", tag.mpeg_layer assert_equal "Stereo", tag.channel_mode assert_equal 44100, tag.sample_rate assert_nil tag.bit_depth end end def test_invalid_id3_file tag = WahWah.open("test/files/invalid_id3.mp3") assert tag.invalid_id3? assert !tag.id3v2? assert !tag.is_vbr? assert_nil tag.id3_version assert_nil tag.title assert_nil tag.artist assert_nil tag.albumartist assert_nil tag.composer assert_nil tag.album assert_nil tag.year assert_nil tag.genre assert_nil tag.track assert_nil tag.track_total assert_nil tag.disc assert_nil tag.disc_total assert_equal [], tag.comments assert_nil tag.duration assert_equal 0, tag.bitrate assert_equal "MPEG1", tag.mpeg_version assert_equal "layer1", tag.mpeg_layer assert_equal "Stereo", tag.channel_mode assert_equal 44100, tag.sample_rate assert_nil tag.bit_depth assert file_io_closed?(tag) end def test_compressed_image_file tag = WahWah.open("test/files/compressed_image.mp3") image = tag.images.first assert_equal binary_data("test/files/compressed_cover.bmp"), image[:data].strip assert file_io_closed?(tag) end def test_incomplete_file tag = WahWah.open("test/files/incomplete.mp3") assert tag.invalid_id3? assert !tag.id3v2? assert !tag.is_vbr? assert_nil tag.id3_version assert_nil tag.title assert_nil tag.artist assert_nil tag.albumartist assert_nil tag.composer assert_nil tag.album assert_nil tag.year assert_nil tag.genre assert_nil tag.track assert_nil tag.track_total assert_nil tag.disc assert_nil tag.disc_total assert_equal [], tag.comments assert_nil tag.duration assert_nil tag.bitrate assert_nil tag.mpeg_version assert_nil tag.mpeg_layer assert_nil tag.channel_mode assert_nil tag.sample_rate assert_nil tag.bit_depth assert file_io_closed?(tag) end def test_invalid_encoding_string_file tag = WahWah.open("test/files/invalid_encoding_string.mp3") assert !tag.invalid_id3? assert tag.id3v2? assert !tag.is_vbr? assert_equal "v2.4", tag.id3_version assert_nil tag.title assert_equal "Paso a paso", tag.artist assert_equal "S/T", tag.album assert_nil tag.albumartist assert_nil tag.composer assert_equal "2003", tag.year assert_equal "Acustico", tag.genre assert_equal 1, tag.track assert_equal 21, tag.track_total assert_equal 0, tag.disc assert_equal 0, tag.disc_total assert_equal [], tag.comments assert_nil tag.duration assert_nil tag.bitrate assert_nil tag.mpeg_version assert_nil tag.mpeg_layer assert_nil tag.channel_mode assert_nil tag.sample_rate assert_nil tag.bit_depth assert file_io_closed?(tag) end def test_utf16_string_file tag = WahWah.open("test/files/utf16.mp3") assert !tag.invalid_id3? assert tag.id3v2? assert !tag.is_vbr? assert_equal "v2.3", tag.id3_version assert_equal "Lemonworld", tag.title assert_equal "The National", tag.artist assert_equal "High Violet", tag.album assert_nil tag.albumartist assert_nil tag.composer assert_equal "2010", tag.year assert_equal "Indie", tag.genre assert_equal 7, tag.track assert_equal 11, tag.track_total assert_nil tag.disc assert_nil tag.disc_total assert_equal ["Track 7"], tag.comments assert_nil tag.duration assert_nil tag.bitrate assert_nil tag.mpeg_version assert_nil tag.mpeg_layer assert_nil tag.channel_mode assert_nil tag.sample_rate assert_nil tag.bit_depth assert file_io_closed?(tag) end def test_image_with_description_file tag = WahWah.open("test/files/image_with_description.mp3") image = tag.images.first assert_equal "image/jpeg", image[:mime_type] assert_equal :cover_front, image[:type] assert_equal binary_data("test/files/cover.jpeg"), image[:data].strip assert file_io_closed?(tag) end end
ruby
MIT
c451fbe9a49d04e1dd8743e904215f1a7cdb9918
2026-01-04T17:50:26.827863Z
false
aidewoode/wahwah
https://github.com/aidewoode/wahwah/blob/c451fbe9a49d04e1dd8743e904215f1a7cdb9918/test/wahwah/ogg/page_test.rb
test/wahwah/ogg/page_test.rb
# frozen_string_literal: true require "test_helper" class WahWah::Ogg::PageTest < Minitest::Test def test_parse content = StringIO.new("OggS\u0000\u0002\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000'\xBD\xAA\xC7\u0000\u0000\u0000\u0000\u0018\u0012\xA8\n\u0001\u001E\u0001vorbis\u0000\u0000\u0000\u0000\u0002D\xAC\u0000\u0000\u0000\u0000\u0000\u0000\u0000\xEE\u0002\u0000\u0000\u0000\u0000\u0000\xB8\u0001".b) page = WahWah::Ogg::Page.new(content) assert page.valid? assert_equal 0, page.granule_position assert_equal ["\x01vorbis\x00\x00\x00\x00\x02D\xAC\x00\x00\x00\x00\x00\x00\x00\xEE\x02\x00\x00\x00\x00\x00\xB8\x01".b], page.segments end def test_invalid_page content = StringIO.new("oggs\u0000\u0002\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000'\xBD\xAA\xC7\u0000\u0000\u0000\u0000\u0018\u0012\xA8\n\u0001\u001E\u0001vorbis\u0000\u0000\u0000\u0000\u0002D\xAC\u0000\u0000\u0000\u0000\u0000\u0000\u0000\xEE\u0002\u0000\u0000\u0000\u0000\u0000\xB8\u0001".b) page = WahWah::Ogg::Page.new(content) assert !page.valid? end end
ruby
MIT
c451fbe9a49d04e1dd8743e904215f1a7cdb9918
2026-01-04T17:50:26.827863Z
false
aidewoode/wahwah
https://github.com/aidewoode/wahwah/blob/c451fbe9a49d04e1dd8743e904215f1a7cdb9918/test/wahwah/ogg/vorbis_tag_test.rb
test/wahwah/ogg/vorbis_tag_test.rb
# frozen_string_literal: true require "test_helper" class WahWah::Ogg::VorbisTagTest < Minitest::Test def test_parse identification_packet = "\x01vorbis\x00\x00\x00\x00\x02D\xAC\x00\x00\x00\x00\x00\x00\x00\xEE\x02\x00\x00\x00\x00\x00\xB8\x01".b comment_packet = "\u0003vorbis0\u0000\u0000\u0000BS; LancerMod(SSE3) (based on aoTuV 6.03 (2018))\t\u0000\u0000\u0000\u000F\u0000\u0000\u0000ALBUM=The Idiot\u0014\u0000\u0000\u0000ALBUMARTIST=Iggy Pop\u000F\u0000\u0000\u0000ARTIST=Iggy Pop\u0011\u0000\u0000\u0000COMPOSER=Iggy Pop\t\u0000\u0000\u0000DATE=1977\u0010\u0000\u0000\u0000TITLE=China Girl\r\u0000\u0000\u0000TRACKNUMBER=5\n\u0000\u0000\u0000GENRE=Rock\f\u0000\u0000\u0000DISCNUMBER=1\u0001".b tag = WahWah::Ogg::VorbisTag.new(identification_packet, comment_packet) assert_equal "China Girl", tag.title assert_equal "Iggy Pop", tag.artist assert_equal "Iggy Pop", tag.albumartist assert_equal "Iggy Pop", tag.composer assert_equal "The Idiot", tag.album assert_equal "1977", tag.year assert_equal "Rock", tag.genre assert_equal 5, tag.track assert_equal 1, tag.disc assert_equal 44100, tag.sample_rate assert_equal 192, tag.bitrate end def test_invalid_comment_packet identification_packet = "\x01vorbis\x00\x00\x00\x00\x02D\xAC\x00\x00\x00\x00\x00\x00\x00\xEE\x02\x00\x00\x00\x00\x00\xB8\x01".b comment_packet = "\u0002vorbisTITLE=China Girl\r\u0000\u0000\u0000TRACKNUMBER=5\n\u0000\u0000\u0000GENRE=Rock\f\u0000\u0000\u0000DISCNUMBER=1\u0001".b tag = WahWah::Ogg::VorbisTag.new(identification_packet, comment_packet) assert_nil tag.title assert_nil tag.artist assert_nil tag.albumartist assert_nil tag.composer assert_nil tag.album assert_nil tag.year assert_nil tag.genre assert_nil tag.track assert_nil tag.disc assert_equal 44100, tag.sample_rate assert_equal 192, tag.bitrate end end
ruby
MIT
c451fbe9a49d04e1dd8743e904215f1a7cdb9918
2026-01-04T17:50:26.827863Z
false
aidewoode/wahwah
https://github.com/aidewoode/wahwah/blob/c451fbe9a49d04e1dd8743e904215f1a7cdb9918/test/wahwah/ogg/flac_tag_test.rb
test/wahwah/ogg/flac_tag_test.rb
# frozen_string_literal: true require "test_helper" class WahWah::Ogg::FlacTagTest < Minitest::Test def test_parse identification_packet = "\x7FFLAC\x01\x00\x00\x02fLaC\x00\x00\x00\"\x10\x00\x10\x00\x00\x00\x0E\x00\x00\x10\n\xC4B\xF0\x00\x05b d\xA9\xFD\x7Fl\xB0\xE1\xC9Z\xFE\xCD\xF3\xA3iqO".b comment_packet = "\x04\x00\x00\xCB \x00\x00\x00reference libFLAC 1.3.2 20170101\t\x00\x00\x00\x0F\x00\x00\x00ALBUM=The Idiot\x14\x00\x00\x00ALBUMARTIST=Iggy Pop\x0F\x00\x00\x00ARTIST=Iggy Pop\x11\x00\x00\x00COMPOSER=Iggy Pop\t\x00\x00\x00DATE=1977\f\x00\x00\x00DISCNUMBER=1\n\x00\x00\x00GENRE=Rock\x10\x00\x00\x00TITLE=China Girl\r\x00\x00\x00TRACKNUMBER=5".b tag = WahWah::Ogg::FlacTag.new(identification_packet, comment_packet) assert_equal "China Girl", tag.title assert_equal "Iggy Pop", tag.artist assert_equal "Iggy Pop", tag.albumartist assert_equal "Iggy Pop", tag.composer assert_equal "The Idiot", tag.album assert_equal "1977", tag.year assert_equal "Rock", tag.genre assert_equal 5, tag.track assert_equal 1, tag.disc assert_equal 8.0, tag.duration assert_equal 705, tag.bitrate assert_equal 44100, tag.sample_rate assert_equal 16, tag.bit_depth end def test_invalid_identification_packet identification_packet = "\x7FFLAC\x01\x00\x00\x02flac\x00\x00\x00\"\x10\x00\x10\x00\x00\x00\x0E\x00\x00\x10\n\xC4B\xF0\x00\x05b d\xA9\xFD\x7Fl\xB0\xE1\xC9Z\xFE\xCD\xF3\xA3iqO".b comment_packet = "\x04\x00\x00\xCB \x00\x00\x00reference libFLAC 1.3.2 20170101\t\x00\x00\x00\x0F\x00\x00\x00ALBUM=The Idiot\x14\x00\x00\x00ALBUMARTIST=Iggy Pop\x0F\x00\x00\x00ARTIST=Iggy Pop\x11\x00\x00\x00COMPOSER=Iggy Pop\t\x00\x00\x00DATE=1977\f\x00\x00\x00DISCNUMBER=1\n\x00\x00\x00GENRE=Rock\x10\x00\x00\x00TITLE=China Girl\r\x00\x00\x00TRACKNUMBER=5".b tag = WahWah::Ogg::FlacTag.new(identification_packet, comment_packet) assert_nil tag.title assert_nil tag.artist assert_nil tag.albumartist assert_nil tag.composer assert_nil tag.album assert_nil tag.year assert_nil tag.genre assert_nil tag.track assert_nil tag.disc assert_nil tag.duration assert_nil tag.bitrate assert_nil tag.sample_rate assert_nil tag.bit_depth end end
ruby
MIT
c451fbe9a49d04e1dd8743e904215f1a7cdb9918
2026-01-04T17:50:26.827863Z
false
aidewoode/wahwah
https://github.com/aidewoode/wahwah/blob/c451fbe9a49d04e1dd8743e904215f1a7cdb9918/test/wahwah/ogg/packets_test.rb
test/wahwah/ogg/packets_test.rb
# frozen_string_literal: true require "test_helper" class WahWah::Ogg::PacketsTest < Minitest::Test def setup @packets = WahWah::Ogg::Packets.new(File.open("test/files/vorbis_tag.ogg")) end def test_packets_enumerable assert_kind_of Enumerable, @packets end def test_packets_content first_packet, second_packet = @packets.first(2) assert_equal "\x01vorbis\x00\x00\x00\x00\x02D\xAC\x00\x00\x00\x00\x00\x00\x00\xEE\x02\x00\x00\x00\x00\x00\xB8\x01".b, first_packet assert_equal "\u0003vorbis0\u0000\u0000\u0000BS; LancerMod(SSE3) (based on aoTuV 6.03 (2018))\n\u0000\u0000\u0000\u000F\u0000\u0000\u0000ALBUM=The Idiot\u0014\u0000\u0000\u0000ALBUMARTIST=Iggy Pop\u000F\u0000\u0000\u0000ARTIST=Iggy Pop\u0011\u0000\u0000\u0000COMPOSER=Iggy Pop\t\u0000\u0000\u0000DATE=1977\u0010\u0000\u0000\u0000TITLE=China Girl\r\u0000\u0000\u0000TRACKNUMBER=5\n\u0000\u0000\u0000GENRE=Rock\f\u0000\u0000\u0000DISCNUMBER=10\u0000\u0000\u0000LYRICS=I'm feeling tragic like I'm Marlon Brando\u0001".b, second_packet end end
ruby
MIT
c451fbe9a49d04e1dd8743e904215f1a7cdb9918
2026-01-04T17:50:26.827863Z
false
aidewoode/wahwah
https://github.com/aidewoode/wahwah/blob/c451fbe9a49d04e1dd8743e904215f1a7cdb9918/test/wahwah/ogg/opus_tag_test.rb
test/wahwah/ogg/opus_tag_test.rb
# frozen_string_literal: true require "test_helper" class WahWah::Ogg::OpusTagTest < Minitest::Test def test_parse identification_packet = "OpusHead\x01\x028\x01\x80\xBB\x00\x00\x00\x00\x00".b comment_packet = "OpusTags\r\u0000\u0000\u0000libopus 1.3.1\t\u0000\u0000\u0000\u000F\u0000\u0000\u0000ALBUM=The Idiot\u0014\u0000\u0000\u0000ALBUMARTIST=Iggy Pop\u000F\u0000\u0000\u0000ARTIST=Iggy Pop\u0011\u0000\u0000\u0000COMPOSER=Iggy Pop\t\u0000\u0000\u0000DATE=1977\f\u0000\u0000\u0000DISCNUMBER=1\n\u0000\u0000\u0000GENRE=Rock\u0010\u0000\u0000\u0000TITLE=China Girl\r\u0000\u0000\u0000TRACKNUMBER=5".b tag = WahWah::Ogg::OpusTag.new(identification_packet, comment_packet) assert_equal "China Girl", tag.title assert_equal "Iggy Pop", tag.artist assert_equal "Iggy Pop", tag.albumartist assert_equal "Iggy Pop", tag.composer assert_equal "The Idiot", tag.album assert_equal "1977", tag.year assert_equal "Rock", tag.genre assert_equal 5, tag.track assert_equal 1, tag.disc assert_equal 48000, tag.sample_rate assert_equal 312, tag.pre_skip end def test_invalid_comment_packet identification_packet = "OpusHead\x01\x028\x01\x80\xBB\x00\x00\x00\x00\x00".b comment_packet = "opustags\r\u0000\u0000\u0000libopus 1.3.1\t\u0000\u0000\u0000\u000F\u0000\u0000\u0000ALBUM=The Idiot\u0014\u0000\u0000\u0000ALBUMARTIST=Iggy Pop\u000F\u0000\u0000\u0000ARTIST=Iggy Pop\u0011\u0000\u0000\u0000COMPOSER=Iggy Pop\t\u0000\u0000\u0000DATE=1977\f\u0000\u0000\u0000DISCNUMBER=1\n\u0000\u0000\u0000GENRE=Rock\u0010\u0000\u0000\u0000TITLE=China Girl\r\u0000\u0000\u0000TRACKNUMBER=5".b tag = WahWah::Ogg::OpusTag.new(identification_packet, comment_packet) assert_nil tag.title assert_nil tag.artist assert_nil tag.albumartist assert_nil tag.composer assert_nil tag.album assert_nil tag.year assert_nil tag.genre assert_nil tag.track assert_nil tag.disc assert_equal 48000, tag.sample_rate assert_equal 312, tag.pre_skip end end
ruby
MIT
c451fbe9a49d04e1dd8743e904215f1a7cdb9918
2026-01-04T17:50:26.827863Z
false
aidewoode/wahwah
https://github.com/aidewoode/wahwah/blob/c451fbe9a49d04e1dd8743e904215f1a7cdb9918/test/wahwah/ogg/vorbis_comment_test.rb
test/wahwah/ogg/vorbis_comment_test.rb
# frozen_string_literal: true require "test_helper" class WahWah::Ogg::VorbisCommentTest < Minitest::Test class Tag include WahWah::Ogg::VorbisComment def initialize(comment_content) parse_vorbis_comment(comment_content) end end def test_parse tag = Tag.new("\r\u0000\u0000\u0000libopus 1.3.1\n\u0000\u0000\u0000\u000F\u0000\u0000\u0000ALBUM=The Idiot\u0014\u0000\u0000\u0000ALBUMARTIST=Iggy Pop\u000F\u0000\u0000\u0000ARTIST=Iggy Pop\u0011\u0000\u0000\u0000COMPOSER=Iggy Pop\t\u0000\u0000\u0000DATE=1977\f\u0000\u0000\u0000DISCNUMBER=1\n\u0000\u0000\u0000GENRE=Rock0\u0000\u0000\u0000LYRICS=I'm feeling tragic like I'm Marlon Brando\u0010\u0000\u0000\u0000TITLE=China Girl\r\u0000\u0000\u0000TRACKNUMBER=5".b) assert_equal "China Girl", tag.instance_variable_get(:@title) assert_equal "Iggy Pop", tag.instance_variable_get(:@artist) assert_equal "Iggy Pop", tag.instance_variable_get(:@albumartist) assert_equal "Iggy Pop", tag.instance_variable_get(:@composer) assert_equal "The Idiot", tag.instance_variable_get(:@album) assert_equal "1977", tag.instance_variable_get(:@year) assert_equal "Rock", tag.instance_variable_get(:@genre) assert_equal 5, tag.instance_variable_get(:@track) assert_equal 1, tag.instance_variable_get(:@disc) assert_equal "I'm feeling tragic like I'm Marlon Brando", tag.instance_variable_get(:@lyrics) end def test_parse_lowercase_field_name tag = Tag.new("\r\u0000\u0000\u0000libopus 1.3.1\n\u0000\u0000\u0000\u000F\u0000\u0000\u0000Album=The Idiot\u0014\u0000\u0000\u0000Albumartist=Iggy Pop\u000F\u0000\u0000\u0000Artist=Iggy Pop\u0011\u0000\u0000\u0000Composer=Iggy Pop\t\u0000\u0000\u0000Date=1977\f\u0000\u0000\u0000Discnumber=1\n\u0000\u0000\u0000Genre=Rock0\u0000\u0000\u0000Lyrics=I'm feeling tragic like I'm Marlon Brando\u0010\u0000\u0000\u0000Title=China Girl\r\u0000\u0000\u0000Tracknumber=5".b) assert_equal "China Girl", tag.instance_variable_get(:@title) assert_equal "Iggy Pop", tag.instance_variable_get(:@artist) assert_equal "Iggy Pop", tag.instance_variable_get(:@albumartist) assert_equal "Iggy Pop", tag.instance_variable_get(:@composer) assert_equal "The Idiot", tag.instance_variable_get(:@album) assert_equal "1977", tag.instance_variable_get(:@year) assert_equal "Rock", tag.instance_variable_get(:@genre) assert_equal 5, tag.instance_variable_get(:@track) assert_equal 1, tag.instance_variable_get(:@disc) assert_equal "I'm feeling tragic like I'm Marlon Brando", tag.instance_variable_get(:@lyrics) end def test_invalid_encoding_comment tag = Tag.new("\x1D\x00\x00\x00Xiph.Org libVorbis I 20050304\x01\x00\x00\x00\x18\x00\x00\x00\x03\x00\x00\x00\x00\x00 @\x00\x00\x96B\x00\x00\x80?\x00@\x00 \x00\x00\x00@\x01".b) assert_nil tag.instance_variable_get(:@title) assert_nil tag.instance_variable_get(:@artist) assert_nil tag.instance_variable_get(:@albumartist) assert_nil tag.instance_variable_get(:@composer) assert_nil tag.instance_variable_get(:@album) assert_nil tag.instance_variable_get(:@year) assert_nil tag.instance_variable_get(:@genre) assert_nil tag.instance_variable_get(:@track) assert_nil tag.instance_variable_get(:@disc) end end
ruby
MIT
c451fbe9a49d04e1dd8743e904215f1a7cdb9918
2026-01-04T17:50:26.827863Z
false
aidewoode/wahwah
https://github.com/aidewoode/wahwah/blob/c451fbe9a49d04e1dd8743e904215f1a7cdb9918/test/wahwah/ogg/pages_test.rb
test/wahwah/ogg/pages_test.rb
# frozen_string_literal: true require "test_helper" class WahWah::Ogg::PagesTest < Minitest::Test def setup @pages = WahWah::Ogg::Pages.new(File.open("test/files/vorbis_tag.ogg")) end def test_pages_enumerable assert_kind_of Enumerable, @pages end def test_each_page @pages.each do |page| assert_instance_of WahWah::Ogg::Page, page end end end
ruby
MIT
c451fbe9a49d04e1dd8743e904215f1a7cdb9918
2026-01-04T17:50:26.827863Z
false
aidewoode/wahwah
https://github.com/aidewoode/wahwah/blob/c451fbe9a49d04e1dd8743e904215f1a7cdb9918/test/wahwah/riff/chunk_test.rb
test/wahwah/riff/chunk_test.rb
# frozen_string_literal: true require "test_helper" class WahWah::Riff::ChunkTest < Minitest::Test def test_normal_chunk content = StringIO.new("fmt \x10\x00\x00\x00\x01\x00\x02\x00D\xAC\x00\x00\x10\xB1\x02\x00\x04\x00\x10\x00".b) chunk = WahWah::Riff::Chunk.new(content) assert_equal "fmt", chunk.id assert_equal 16, chunk.size assert_nil chunk.type end def test_riff_and_list_chunk riff_chunk_content = StringIO.new("RIFFX\x89\x15\x00WAVE".b) list_chunk_content = StringIO.new("LIST\xAC\x00\x00\x00INFO".b) riff_chunk = WahWah::Riff::Chunk.new(riff_chunk_content) list_chunk = WahWah::Riff::Chunk.new(list_chunk_content) assert_equal "RIFF", riff_chunk.id assert_equal "LIST", list_chunk.id assert_equal "WAVE", riff_chunk.type assert_equal "INFO", list_chunk.type assert_equal 1411416, riff_chunk.instance_variable_get(:@size) assert_equal 172, list_chunk.instance_variable_get(:@size) # The real size should not include chunk type data assert_equal 1411412, riff_chunk.size assert_equal 168, list_chunk.size end def test_odd_size_chunk content = StringIO.new("IART\t\x00\x00\x00Iggy".b) chunk = WahWah::Riff::Chunk.new(content) assert_equal 10, chunk.size end def test_invalid_chunk content = StringIO.new("\x00\x00\x00\x00\x00\x00invalid".b) chunk = WahWah::Riff::Chunk.new(content) assert !chunk.valid? end end
ruby
MIT
c451fbe9a49d04e1dd8743e904215f1a7cdb9918
2026-01-04T17:50:26.827863Z
false
aidewoode/wahwah
https://github.com/aidewoode/wahwah/blob/c451fbe9a49d04e1dd8743e904215f1a7cdb9918/test/wahwah/mp3/vbri_header_test.rb
test/wahwah/mp3/vbri_header_test.rb
# frozen_string_literal: true require "test_helper" class WahWah::Mp3::VbriHeaderTest < Minitest::Test def test_prase content = StringIO.new("VBRI\x00\x01\r\xB1\x00d\x00b\xDB\x91\x00\x00!:\x00\x84\x00\x01\x00\x02\x00@\x98\xB1\xBD\xA8\xBB6".b) header = WahWah::Mp3::VbriHeader.new(content) assert_equal 8506, header.frames_count assert_equal 6478737, header.bytes_count assert header.valid? end def test_invalid_header content = StringIO.new("\x00\x01VBRI\x00\x01\r\xB1\x00d\x00b\xDB\x91\x00\x00!:\x00\x84\x00\x01\x00\x02\x00@\x98\xB1\xBD\xA8\xBB6".b) header = WahWah::Mp3::VbriHeader.new(content) assert !header.valid? end end
ruby
MIT
c451fbe9a49d04e1dd8743e904215f1a7cdb9918
2026-01-04T17:50:26.827863Z
false
aidewoode/wahwah
https://github.com/aidewoode/wahwah/blob/c451fbe9a49d04e1dd8743e904215f1a7cdb9918/test/wahwah/mp3/mpeg_frame_header_test.rb
test/wahwah/mp3/mpeg_frame_header_test.rb
# frozen_string_literal: true require "test_helper" class WahWah::Mp3::MpegFrameHeaderTest < Minitest::Test def test_prase content = StringIO.new("\x00\x00\x00\x00\xFF\xFB\x90d\x00\x00".b) header = WahWah::Mp3::MpegFrameHeader.new(content) assert_equal "MPEG1", header.version assert_equal "layer3", header.layer assert_equal "MPEG1 layer3", header.kind assert_equal "Joint Stereo", header.channel_mode assert_equal 128, header.frame_bitrate assert_equal 44100, header.sample_rate assert_equal 1152, header.samples_per_frame end def test_invalid_mpeg_frame_header content = StringIO.new("\x00\x00\x00\x00\x90d\x00\x00".b) header = WahWah::Mp3::MpegFrameHeader.new(content) assert !header.valid? assert_equal 0, header.position assert_nil header.version assert_nil header.layer assert_nil header.kind assert_nil header.channel_mode assert_nil header.frame_bitrate assert_nil header.sample_rate assert_nil header.samples_per_frame end end
ruby
MIT
c451fbe9a49d04e1dd8743e904215f1a7cdb9918
2026-01-04T17:50:26.827863Z
false
aidewoode/wahwah
https://github.com/aidewoode/wahwah/blob/c451fbe9a49d04e1dd8743e904215f1a7cdb9918/test/wahwah/mp3/xing_header_test.rb
test/wahwah/mp3/xing_header_test.rb
# frozen_string_literal: true require "test_helper" class WahWah::Mp3::XingHeaderTest < Minitest::Test def test_prase content = StringIO.new("Xing\x00\x00\x00\x0F\x00\x00\x014\x00\x00~\xC1\x00\x03\x05\b\n\r\x0F\x12\x14\x17\x19\x1C\x1E".b) header = WahWah::Mp3::XingHeader.new(content) assert_equal 308, header.frames_count assert_equal 32449, header.bytes_count assert header.valid? end def test_invalid_header content = StringIO.new("\x00\x00\x00Xing\x00\x00\x00\x0F\x00".b) header = WahWah::Mp3::XingHeader.new(content) assert !header.valid? end end
ruby
MIT
c451fbe9a49d04e1dd8743e904215f1a7cdb9918
2026-01-04T17:50:26.827863Z
false
aidewoode/wahwah
https://github.com/aidewoode/wahwah/blob/c451fbe9a49d04e1dd8743e904215f1a7cdb9918/test/wahwah/flac/streaminfo_block_test.rb
test/wahwah/flac/streaminfo_block_test.rb
# frozen_string_literal: true require "test_helper" class WahWah::Flac::StreaminfoBlockTest < Minitest::Test class Block include WahWah::Flac::StreaminfoBlock def initialize(block_data) parse_streaminfo_block(block_data) end end def test_parse block = Block.new("\x10\x00\x10\x00\x00\x00\x0E\x00\x00\x10\n\xC4B\xF0\x00\x05b d\xA9\xFD\x7Fl\xB0\xE1\xC9Z\xFE\xCD\xF3\xA3iqO".b) assert_equal 8.0, block.instance_variable_get(:@duration) assert_equal 705, block.instance_variable_get(:@bitrate) assert_equal 44100, block.instance_variable_get(:@sample_rate) assert_equal 16, block.instance_variable_get(:@bit_depth) end end
ruby
MIT
c451fbe9a49d04e1dd8743e904215f1a7cdb9918
2026-01-04T17:50:26.827863Z
false
aidewoode/wahwah
https://github.com/aidewoode/wahwah/blob/c451fbe9a49d04e1dd8743e904215f1a7cdb9918/test/wahwah/flac/block_test.rb
test/wahwah/flac/block_test.rb
# frozen_string_literal: true require "test_helper" class WahWah::Flac::BlockTest < Minitest::Test def test_parse content = StringIO.new("\x00\x00\x00\"\x10\x00\x10\x00\x00\x00\x0E\x00\x00\x10\n\xC4B\xF0\x00\x05b d\xA9\xFD\x7Fl\xB0\xE1\xC9Z\xFE\xCD\xF3\xA3iqO".b) block = WahWah::Flac::Block.new(content) assert !block.is_last? assert_equal "STREAMINFO", block.type assert_equal 34, block.size end def test_invalid_block content = StringIO.new("\x06\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\timage/png\x00\x00\x00\fUntitled.png".b) block = WahWah::Flac::Block.new(content) assert !block.valid? end end
ruby
MIT
c451fbe9a49d04e1dd8743e904215f1a7cdb9918
2026-01-04T17:50:26.827863Z
false
aidewoode/wahwah
https://github.com/aidewoode/wahwah/blob/c451fbe9a49d04e1dd8743e904215f1a7cdb9918/test/wahwah/mp4/atom_test.rb
test/wahwah/mp4/atom_test.rb
# frozen_string_literal: true require "test_helper" class WahWah::Mp4::AtomTest < Minitest::Test def test_find_atom io = File.open("test/files/udta_meta.m4a") atom = WahWah::Mp4::Atom.find(io, "moov", "udta") assert_equal "udta", atom.type assert_equal 5174, atom.size end def test_return_invalid_atom_when_not_found io = File.open("test/files/udta_meta.m4a") atom = WahWah::Mp4::Atom.find(io, "moov", "uuuu") assert_instance_of WahWah::Mp4::Atom, atom assert !atom.valid? end def test_parse content = StringIO.new("\x00\x00\x00gstsd\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00Wmp4a\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x10\x00\x00\x00\x00\xACD\x00\x00\x00\x00\x003esds\x00\x00\x00\x00\x03\x80\x80\x80\"\x00\x00\x00\x04\x80\x80\x80\x14@\x14\x00\x18\x00\x00\x00\b\x10\x00\x01\xF4\x00\x05\x80\x80\x80\x02\x12\x10\x06\x80\x80\x80\x01\x02".b) atom = WahWah::Mp4::Atom.new(content) assert_equal 95, atom.size assert_equal "stsd", atom.type end def test_invalid_atom content = StringIO.new("\x00\x00\x00\x00invalid".b) atom = WahWah::Mp4::Atom.new(content) assert !atom.valid? end def test_find_child_atom_from_atom io = File.open("test/files/udta_meta.m4a") atom = WahWah::Mp4::Atom.find(io, "moov", "trak", "mdia") child_atom = atom.find("minf", "stbl", "stsd") assert_equal "stsd", child_atom.type assert_equal 95, child_atom.size end def test_return_invalid_atom_when_not_found_from_atom io = File.open("test/files/udta_meta.m4a") atom = WahWah::Mp4::Atom.find(io, "moov", "trak", "mdia") child_atom = atom.find("minf", "stbl", "uuuu") assert_instance_of WahWah::Mp4::Atom, child_atom assert !child_atom.valid? end def test_get_atom_children_atoms io = File.open("test/files/udta_meta.m4a") atom = WahWah::Mp4::Atom.find(io, "moov", "udta", "meta") children = atom.children assert_equal 3, children.count assert_equal "hdlr", children[0].type assert_equal "ilst", children[1].type assert_equal "free", children[2].type end end
ruby
MIT
c451fbe9a49d04e1dd8743e904215f1a7cdb9918
2026-01-04T17:50:26.827863Z
false
aidewoode/wahwah
https://github.com/aidewoode/wahwah/blob/c451fbe9a49d04e1dd8743e904215f1a7cdb9918/test/wahwah/id3/frame_test.rb
test/wahwah/id3/frame_test.rb
# frozen_string_literal: true require "test_helper" class WahWah::ID3::FrameTest < Minitest::Test def test_v2_2_frame content = StringIO.new("TT2\x00\x00\x11\x00China Girl\x00".b) frame = WahWah::ID3::Frame.new(content, 2) assert frame.valid? assert !frame.compressed? assert !frame.data_length_indicator? assert_equal :title, frame.name assert_equal "China Girl", frame.value end def test_v2_3_frame content = StringIO.new("TIT2\x00\x00\x00\x17\x00\x00\x01\xFF\xFEC\x00h\x00i\x00n\x00a\x00 \x00G\x00i\x00r\x00l\x00".b) frame = WahWah::ID3::Frame.new(content, 3) assert frame.valid? assert !frame.compressed? assert !frame.data_length_indicator? assert_equal :title, frame.name assert_equal "China Girl", frame.value end def test_v2_4_frame content = StringIO.new("TIT2\x00\x00\x00\x17\x00\x00\x01\xFF\xFEC\x00h\x00i\x00n\x00a\x00 \x00G\x00i\x00r\x00l\x00".b) frame = WahWah::ID3::Frame.new(content, 4) assert frame.valid? assert !frame.compressed? assert !frame.data_length_indicator? assert_equal :title, frame.name assert_equal "China Girl", frame.value end def test_invalid_frame content = StringIO.new("tit2\x00\x00\x00\x17\x00\x00\x01\xFF\xFEC\x00h\x00i\x00n\x00a\x00 \x00G\x00i\x00r\x00l\x00".b) frame = WahWah::ID3::Frame.new(content, 4) assert !frame.valid? end def test_data_length_indicator_frame content = StringIO.new("TIT2\x00\x00\x00\n\x00\x01\x00\x00\x00\x06\x03title\x00".b) frame = WahWah::ID3::Frame.new(content, 4) assert frame.valid? assert !frame.compressed? assert frame.data_length_indicator? assert_equal :title, frame.name assert_equal "title", frame.value end def test_compressed_frame content = StringIO.new("TIT2\x00\x00\x00\"\x00\x80\x00\x00\x00\x9Bx\x9Cc\xFC\xFF\xCF\x99!\x83!\x93!\x8F!\x91A\x81\xC1\x1D\xC8*b\xC8a\x00\x00Q(\x05\x90".b) frame = WahWah::ID3::Frame.new(content, 3) assert frame.valid? assert frame.compressed? assert !frame.data_length_indicator? assert_equal :title, frame.name assert_equal "China Girl", frame.value end end
ruby
MIT
c451fbe9a49d04e1dd8743e904215f1a7cdb9918
2026-01-04T17:50:26.827863Z
false
aidewoode/wahwah
https://github.com/aidewoode/wahwah/blob/c451fbe9a49d04e1dd8743e904215f1a7cdb9918/test/wahwah/id3/lyrics_frame_body_test.rb
test/wahwah/id3/lyrics_frame_body_test.rb
# frozen_string_literal: true require "test_helper" class WahWah::ID3::LyricsFrameBodyTest < Minitest::Test def test_iso_8859_1_encode_comment value = WahWah::ID3::LyricsFrameBody.new("\x00eng\x00Iggy Pop Rocks".b, 4).value assert_equal "Iggy Pop Rocks", value assert_equal "UTF-8", value.encoding.name end def test_utf_16_encode_comment value = WahWah::ID3::LyricsFrameBody.new("\x01eng\xFF\xFE\x00\x00\xFF\xFEI\x00g\x00g\x00y\x00 \x00P\x00o\x00p\x00 \x00R\x00o\x00c\x00k\x00s\x00".b, 4).value assert_equal "Iggy Pop Rocks", value assert_equal "UTF-8", value.encoding.name end def test_utf_16be_encode_comment value = WahWah::ID3::LyricsFrameBody.new("\x02eng\x00\x00\x00I\x00g\x00g\x00y\x00 \x00P\x00o\x00p\x00 \x00R\x00o\x00c\x00k\x00s".b, 4).value assert_equal "Iggy Pop Rocks", value assert_equal "UTF-8", value.encoding.name end def test_utf_8_encode_comment value = WahWah::ID3::LyricsFrameBody.new("\x03eng\x00Iggy Pop Rocks".b, 4).value assert_equal "Iggy Pop Rocks", value assert_equal "UTF-8", value.encoding.name end end
ruby
MIT
c451fbe9a49d04e1dd8743e904215f1a7cdb9918
2026-01-04T17:50:26.827863Z
false
aidewoode/wahwah
https://github.com/aidewoode/wahwah/blob/c451fbe9a49d04e1dd8743e904215f1a7cdb9918/test/wahwah/id3/genre_frame_body_test.rb
test/wahwah/id3/genre_frame_body_test.rb
# frozen_string_literal: true require "test_helper" class WahWah::ID3::GenreFrameBodyTest < Minitest::Test def test_text_value_genre value = WahWah::ID3::GenreFrameBody.new("\x00Rock".b, 4).value assert_equal "Rock", value end def test_numeric_value_genre value = WahWah::ID3::GenreFrameBody.new("\x0017".b, 4).value assert_equal "Rock", value end def test_numeric_value_in_parens_genre value = WahWah::ID3::GenreFrameBody.new("\x00(17)".b, 4).value assert_equal "Rock", value end end
ruby
MIT
c451fbe9a49d04e1dd8743e904215f1a7cdb9918
2026-01-04T17:50:26.827863Z
false
aidewoode/wahwah
https://github.com/aidewoode/wahwah/blob/c451fbe9a49d04e1dd8743e904215f1a7cdb9918/test/wahwah/id3/v2_test.rb
test/wahwah/id3/v2_test.rb
# frozen_string_literal: true require "test_helper" class WahWah::ID3::V2Test < Minitest::Test def test_parse content = StringIO.new("ID3\x04\x00\x00\x00\x00\x00-TIT2\x00\x00\x00\v\x00\x00\x03China GirlTRCK\x00\x00\x00\x02\x00\x00\x035TPOS\x00\x00\x00\x02\x00\x00\x031".b) tag = WahWah::ID3::V2.new(content) assert_equal content.size, tag.size assert_equal "China Girl", tag.title assert_equal 5, tag.track assert_equal 1, tag.disc assert_nil tag.track_total assert_nil tag.disc_total assert !tag.has_extended_header? assert_equal "v2.4", tag.version end def test_with_track_total_and_disc_total content = StringIO.new("ID3\x04\x00\x00\x00\x00\x00GTIT2\x00\x00\x00\x17\x00\x00\x01\xFF\xFEC\x00h\x00i\x00n\x00a\x00 \x00G\x00i\x00r\x00l\x00TRCK\x00\x00\x00\t\x00\x00\x01\xFF\xFE5\x00/\x008\x00TPOS\x00\x00\x00\t\x00\x00\x01\xFF\xFE1\x00/\x001\x00".b) tag = WahWah::ID3::V2.new(content) assert_equal content.size, tag.size assert_equal "China Girl", tag.title assert_equal 5, tag.track assert_equal 1, tag.disc assert_equal 8, tag.track_total assert_equal 1, tag.disc_total assert !tag.has_extended_header? assert_equal "v2.4", tag.version end def test_invalid_tag content = StringIO.new("id3TPE1\x00\x00\x00\x13\x00\x00\x01\xFF\xFEI\x00g\x00g\x00y\x00 \x00P\x00o\x00p\x00TIT2\x00\x00\x00\x17\x00\x00\x01\xFF\xFEC\x00h\x00i\x00n\x00a\x00 \x00G\x00i\x00r\x00l\x00TALB\x00\x00\x00\x15\x00\x00\x01\xFF\xFET\x00h\x00e\x00 \x00I\x00d\x00i\x00o\x00t\x00TPE2\x00\x00\x00\x13\x00\x00\x01\xFF\xFEI\x00g\x00g\x00y\x00 \x00P\x00o\x00p\x00TRCK\x00\x00\x00\t\x00\x00\x01\xFF\xFE5\x00/\x008\x00TPOS".b) tag = WahWah::ID3::V2.new(content) assert !tag.valid? end def test_extended_header_tag content = StringIO.new("ID3\x04\x00@\x00\x00\x00 \x00\x00\x00\f\x01 \x05\x065uMxTIT2\x00\x00\x00\n\x00\x01\x00\x00\x00\x06\x03title".b) tag = WahWah::ID3::V2.new(content) assert_equal content.size, tag.size assert_equal "title", tag.title assert_equal "v2.4", tag.version assert tag.has_extended_header? end end
ruby
MIT
c451fbe9a49d04e1dd8743e904215f1a7cdb9918
2026-01-04T17:50:26.827863Z
false
aidewoode/wahwah
https://github.com/aidewoode/wahwah/blob/c451fbe9a49d04e1dd8743e904215f1a7cdb9918/test/wahwah/id3/text_frame_body_test.rb
test/wahwah/id3/text_frame_body_test.rb
# frozen_string_literal: true require "test_helper" class WahWah::ID3::TextFrameBodyTest < Minitest::Test def test_iso_8859_1_encode_text value = WahWah::ID3::TextFrameBody.new("\x00China Girl".b, 4).value assert_equal "China Girl", value assert_equal "UTF-8", value.encoding.name end def test_utf_16_encode_text value = WahWah::ID3::TextFrameBody.new("\x01\xFF\xFEC\x00h\x00i\x00n\x00a\x00 \x00G\x00i\x00r\x00l\x00".b, 4).value assert_equal "China Girl", value assert_equal "UTF-8", value.encoding.name end def test_utf_16be_encode_text value = WahWah::ID3::TextFrameBody.new("\x02\x00C\x00h\x00i\x00n\x00a\x00 \x00G\x00i\x00r\x00l".b, 4).value assert_equal "China Girl", value assert_equal "UTF-8", value.encoding.name end def test_utf_8_encode_text value = WahWah::ID3::TextFrameBody.new("\x03China Girl".b, 4).value assert_equal "China Girl", value assert_equal "UTF-8", value.encoding.name end end
ruby
MIT
c451fbe9a49d04e1dd8743e904215f1a7cdb9918
2026-01-04T17:50:26.827863Z
false
aidewoode/wahwah
https://github.com/aidewoode/wahwah/blob/c451fbe9a49d04e1dd8743e904215f1a7cdb9918/test/wahwah/id3/frame_body_test.rb
test/wahwah/id3/frame_body_test.rb
# frozen_string_literal: true require "test_helper" class WahWah::ID3::FrameBodyTest < Minitest::Test class SubFrameBody < WahWah::ID3::FrameBody; end class SubFrameBodyWithParse < WahWah::ID3::FrameBody def parse end end def test_sub_class_not_implemented_parse_method assert_raises(WahWah::WahWahNotImplementedError) do SubFrameBody.new("content", 3) end end def test_have_value_method frame_body = SubFrameBodyWithParse.new("content", 3) assert_respond_to frame_body, :value end end
ruby
MIT
c451fbe9a49d04e1dd8743e904215f1a7cdb9918
2026-01-04T17:50:26.827863Z
false