From 479066807cbd1c7a8abe69253a605a0d52139548 Mon Sep 17 00:00:00 2001 From: Rodrigo Serradura Date: Sun, 28 Jan 2024 01:59:40 -0300 Subject: [PATCH] WIP --- .github/workflows/main.yml | 2 +- .rubocop.yml | 11 +++ examples/transitions_listener/Rakefile | 78 +++++++++++++++++++ .../app/models/account/member/record.rb | 12 +++ .../app/models/account/owner_creation.rb | 60 ++++++++++++++ .../app/models/account/record.rb | 13 ++++ .../app/models/user/creation.rb | 65 ++++++++++++++++ .../app/models/user/record.rb | 17 ++++ .../app/models/user/token/creation.rb | 49 ++++++++++++ .../app/models/user/token/record.rb | 9 +++ examples/transitions_listener/config.rb | 27 +++++++ examples/transitions_listener/config/boot.rb | 16 ++++ .../config/initializers/bcdd.rb | 11 +++ examples/transitions_listener/db/setup.rb | 47 +++++++++++ .../lib/bcdd/result/rollback_on_failure.rb | 15 ++++ .../my_bcdd_result_transitions_listener.rb | 35 +++++++++ lib/bcdd/result/config.rb | 7 +- lib/bcdd/result/transitions.rb | 5 +- lib/bcdd/result/transitions/config.rb | 30 +++++++ lib/bcdd/result/transitions/listener.rb | 27 +++++++ lib/bcdd/result/transitions/tracking.rb | 11 ++- .../result/transitions/tracking/disabled.rb | 4 + .../result/transitions/tracking/enabled.rb | 72 ++++++++++++----- test/test_helper.rb | 3 +- 24 files changed, 599 insertions(+), 27 deletions(-) create mode 100644 examples/transitions_listener/Rakefile create mode 100644 examples/transitions_listener/app/models/account/member/record.rb create mode 100644 examples/transitions_listener/app/models/account/owner_creation.rb create mode 100644 examples/transitions_listener/app/models/account/record.rb create mode 100644 examples/transitions_listener/app/models/user/creation.rb create mode 100644 examples/transitions_listener/app/models/user/record.rb create mode 100644 examples/transitions_listener/app/models/user/token/creation.rb create mode 100644 examples/transitions_listener/app/models/user/token/record.rb create mode 100644 examples/transitions_listener/config.rb create mode 100644 examples/transitions_listener/config/boot.rb create mode 100644 examples/transitions_listener/config/initializers/bcdd.rb create mode 100644 examples/transitions_listener/db/setup.rb create mode 100644 examples/transitions_listener/lib/bcdd/result/rollback_on_failure.rb create mode 100644 examples/transitions_listener/lib/my_bcdd_result_transitions_listener.rb create mode 100644 lib/bcdd/result/transitions/config.rb create mode 100644 lib/bcdd/result/transitions/listener.rb diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 534c8578..77f7bb93 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -40,4 +40,4 @@ jobs: if: ${{ matrix.ruby == 3.2 }} - uses: paambaati/codeclimate-action@v5 - if: ${{ matrix.ruby == 3.2 }} + if: ${{ matrix.ruby == 3.2 && !github.base_ref }} diff --git a/.rubocop.yml b/.rubocop.yml index 3534aa45..9d025cce 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -8,6 +8,13 @@ require: AllCops: NewCops: enable TargetRubyVersion: 2.7 + Exclude: + - 'examples/**/*' + - 'vendor/**/*' + - 'spec/fixtures/**/*' + - 'tmp/**/*' + - '.git/**/*' + - 'bin/*' Lint/RescueException: Exclude: @@ -25,6 +32,10 @@ Layout/MultilineMethodCallIndentation: Lint/UnderscorePrefixedVariableName: Enabled: false +Lint/UnusedMethodArgument: + Exclude: + - lib/bcdd/result/transitions/listener.rb + Style/AccessModifierDeclarations: Enabled: false diff --git a/examples/transitions_listener/Rakefile b/examples/transitions_listener/Rakefile new file mode 100644 index 00000000..4ae3f7f3 --- /dev/null +++ b/examples/transitions_listener/Rakefile @@ -0,0 +1,78 @@ +# frozen_string_literal: true + +if RUBY_VERSION <= '3.1' + puts 'This example requires Ruby 3.1 or higher.' + exit! 1 +end + +task default: %i[bcdd_result_transitions] + +task :config do + require_relative 'config' +end + +desc 'creates an account and an owner user through BCDD::Result' +task bcdd_result_transitions: %i[config] do + BCDD::Result.configuration do |config| + config.feature.disable!(:transitions) if ENV['DISABLE_TRANSITIONS'] + + config.transitions.listener = MyBCDDResultTransitionsListener unless ENV['DISABLE_LISTENER'] + end + + result = nil + + bench = Benchmark.measure do + result = Account::OwnerCreation.new.call( + owner: { + name: "\tJohn Doe \n", + email: ' JOHN.doe@email.com', + password: '123123123', + password_confirmation: '123123123' + } + ) + end + + puts "BCDD::Result benchmark: #{bench}" +end + +desc 'creates an account and an owner user directly through ActiveRecord' +task raw_active_record: %i[config] do + require_relative 'config' + + result = nil + + bench = Benchmark.measure do + email = 'john.doe@email.com' + + ActiveRecord::Base.transaction do + User::Record.exists?(email:) and raise "User with email #{email} already exists" + + user = User::Record.create!( + uuid: ::SecureRandom.uuid, + name: 'John Doe', + email:, + password: '123123123', + password_confirmation: '123123123' + ) + + executed_at = ::Time.current + + user.token.nil? or raise "User with email #{email} already has a token" + + user.create_token!( + access_token: ::SecureRandom.hex(24), + refresh_token: ::SecureRandom.hex(24), + access_token_expires_at: executed_at + 15.days, + refresh_token_expires_at: executed_at + 30.days + ) + + account = Account::Record.create!(uuid: ::SecureRandom.uuid) + + Account::Member::Record.create!(account: account, user: user, role: :owner) + + result = { account: account, user: user } + end + end + + puts "ActiveRecord benchmark: #{bench}" +end diff --git a/examples/transitions_listener/app/models/account/member/record.rb b/examples/transitions_listener/app/models/account/member/record.rb new file mode 100644 index 00000000..1b06ddd8 --- /dev/null +++ b/examples/transitions_listener/app/models/account/member/record.rb @@ -0,0 +1,12 @@ +# frozen_string_literal: true + +class Account::Member + class Record < ActiveRecord::Base + self.table_name = 'account_memberships' + + enum role: { owner: 0, admin: 1, contributor: 2 } + + belongs_to :user, inverse_of: :memberships, class_name: 'User::Record' + belongs_to :account, inverse_of: :memberships, class_name: 'Account::Record' + end +end diff --git a/examples/transitions_listener/app/models/account/owner_creation.rb b/examples/transitions_listener/app/models/account/owner_creation.rb new file mode 100644 index 00000000..acaf8b72 --- /dev/null +++ b/examples/transitions_listener/app/models/account/owner_creation.rb @@ -0,0 +1,60 @@ +# frozen_string_literal: true + +module Account + class OwnerCreation + include BCDD::Context.mixin + include BCDD::Result::RollbackOnFailure + + def call(**input) + BCDD::Result.transitions(name: self.class.name) do + Given(input) + .and_then(:normalize_input) + .and_then(:validate_input) + .then { |result| + rollback_on_failure { + result + .and_then(:create_owner) + .and_then(:create_account) + .and_then(:link_owner_to_account) + } + }.and_expose(:account_owner_created, %i[user account]) + end + end + + private + + def normalize_input(**options) + uuid = String(options.fetch(:uuid) { ::SecureRandom.uuid }).strip.downcase + + Continue(uuid:) + end + + def validate_input(uuid:, owner:) + err = ::Hash.new { |hash, key| hash[key] = [] } + + err[:uuid] << 'must be an UUID' unless uuid.match?(/\A[0-9a-f]{8}-([0-9a-f]{4}-){3}[0-9a-f]{12}\z/i) + err[:owner] << 'must be a Hash' unless owner.is_a?(::Hash) + + err.empty? ? Continue() : Failure(:invalid_input, **err) + end + + def create_owner(owner:, **) + ::User::Creation.new.call(**owner).handle do |on| + on.success { |output| Continue(user: { record: output[:user], token: output[:token] }) } + on.failure { |output| Failure(:invalid_owner, **output) } + end + end + + def create_account(uuid:, **) + account = Record.create(uuid:) + + account.persisted? ? Continue(account:) : Failure(:invalid_record, **account.errors.messages) + end + + def link_owner_to_account(account:, user:, **) + Member::Record.create!(account:, user: user.fetch(:record), role: :owner) + + Continue() + end + end +end diff --git a/examples/transitions_listener/app/models/account/record.rb b/examples/transitions_listener/app/models/account/record.rb new file mode 100644 index 00000000..ef05187d --- /dev/null +++ b/examples/transitions_listener/app/models/account/record.rb @@ -0,0 +1,13 @@ +# frozen_string_literal: true + +class Account::Record < ActiveRecord::Base + self.table_name = 'accounts' + + has_many :memberships, inverse_of: :account, dependent: :destroy, class_name: '::Account::Member::Record' + has_many :users, through: :memberships, inverse_of: :accounts, class_name: '::User::Record' + + where_ownership = -> { where(account_memberships: {role: :owner}) } + + has_one :ownership, where_ownership, dependent: nil, inverse_of: :account, class_name: '::Account::Member::Record' + has_one :owner, through: :ownership, source: :user, class_name: '::User::Record' +end diff --git a/examples/transitions_listener/app/models/user/creation.rb b/examples/transitions_listener/app/models/user/creation.rb new file mode 100644 index 00000000..c735b1ba --- /dev/null +++ b/examples/transitions_listener/app/models/user/creation.rb @@ -0,0 +1,65 @@ +# frozen_string_literal: true + +module User + class Creation + include BCDD::Context.mixin + include BCDD::Result::RollbackOnFailure + + def call(**input) + BCDD::Result.transitions(name: self.class.name) do + Given(input) + .and_then(:normalize_input) + .and_then(:validate_input) + .and_then(:validate_email_uniqueness) + .then { |result| + rollback_on_failure { + result + .and_then(:create_user) + .and_then(:create_user_token) + } + } + .and_expose(:user_created, %i[user token]) + end + end + + private + + def normalize_input(name:, email:, **options) + name = String(name).strip.gsub(/\s+/, ' ') + email = String(email).strip.downcase + + uuid = String(options.fetch(:uuid) { ::SecureRandom.uuid }).strip.downcase + + Continue(uuid:, name:, email:) + end + + def validate_input(uuid:, name:, email:, password:, password_confirmation:) + err = ::Hash.new { |hash, key| hash[key] = [] } + + err[:uuid] << 'must be an UUID' unless uuid.match?(/\A[0-9a-f]{8}-([0-9a-f]{4}-){3}[0-9a-f]{12}\z/i) + err[:name] << 'must be present' if name.blank? + err[:email] << 'must be email' unless email.match?(::URI::MailTo::EMAIL_REGEXP) + err[:password] << 'must be present' if password.blank? + err[:password_confirmation] << 'must be present' if password_confirmation.blank? + + err.empty? ? Continue() : Failure(:invalid_input, **err) + end + + def validate_email_uniqueness(email:, **) + Record.exists?(email:) ? Failure(:email_already_taken) : Continue() + end + + def create_user(uuid:, name:, email:, password:, password_confirmation:) + user = Record.create(uuid:, name:, email:, password:, password_confirmation:) + + user.persisted? ? Continue(user:) : Failure(:invalid_record, **user.errors.messages) + end + + def create_user_token(user:, **) + Token::Creation.new.call(user: user).handle do |on| + on.success { |output| Continue(token: output[:token]) } + on.failure { raise 'Token creation failed' } + end + end + end +end diff --git a/examples/transitions_listener/app/models/user/record.rb b/examples/transitions_listener/app/models/user/record.rb new file mode 100644 index 00000000..fd172dc3 --- /dev/null +++ b/examples/transitions_listener/app/models/user/record.rb @@ -0,0 +1,17 @@ +# frozen_string_literal: true + +class User::Record < ActiveRecord::Base + self.table_name = 'users' + + has_secure_password + + has_many :memberships, inverse_of: :user, dependent: :destroy, class_name: '::Account::Member::Record' + has_many :accounts, through: :memberships, inverse_of: :users, class_name: '::Account::Record' + + where_ownership = -> { where(account_memberships: { role: :owner }) } + + has_one :ownership, where_ownership, inverse_of: :user, class_name: '::Account::Member::Record' + has_one :account, through: :ownership, inverse_of: :owner, class_name: '::Account::Record' + + has_one :token, inverse_of: :user, dependent: :destroy, class_name: '::User::Token::Record' +end diff --git a/examples/transitions_listener/app/models/user/token/creation.rb b/examples/transitions_listener/app/models/user/token/creation.rb new file mode 100644 index 00000000..c3742790 --- /dev/null +++ b/examples/transitions_listener/app/models/user/token/creation.rb @@ -0,0 +1,49 @@ +# frozen_string_literal: true + +module User::Token + class Creation + include BCDD::Context.mixin + + def call(**input) + BCDD::Result.transitions(name: self.class.name) do + Given(input) + .and_then(:normalize_input) + .and_then(:validate_input) + .and_then(:validate_token_existence) + .and_then(:create_token) + .and_expose(:token_created, %i[token]) + end + end + + private + + def normalize_input(**options) + Continue(executed_at: options.fetch(:executed_at) { ::Time.current }) + end + + def validate_input(user:, executed_at:) + err = ::Hash.new { |hash, key| hash[key] = [] } + + err[:user] << 'must be a User::Record' unless user.is_a?(::User::Record) + err[:user] << 'must be persisted' unless user.try(:persisted?) + err[:executed_at] << 'must be a time' unless executed_at.is_a?(::Time) + + err.empty? ? Continue() : Failure(:invalid_user, **err) + end + + def validate_token_existence(user:, **) + user.token.nil? ? Continue() : Failure(:token_already_exists) + end + + def create_token(user:, executed_at:, **) + token = user.create_token( + access_token: ::SecureRandom.hex(24), + refresh_token: ::SecureRandom.hex(24), + access_token_expires_at: executed_at + 15.days, + refresh_token_expires_at: executed_at + 30.days + ) + + token.persisted? ? Continue(token:) : Failure(:token_creation_failed, **token.errors.messages) + end + end +end diff --git a/examples/transitions_listener/app/models/user/token/record.rb b/examples/transitions_listener/app/models/user/token/record.rb new file mode 100644 index 00000000..2827b969 --- /dev/null +++ b/examples/transitions_listener/app/models/user/token/record.rb @@ -0,0 +1,9 @@ +# frozen_string_literal: true + +module User::Token + class Record < ActiveRecord::Base + self.table_name = 'user_tokens' + + belongs_to :user, class_name: 'User::Record', inverse_of: :token + end +end diff --git a/examples/transitions_listener/config.rb b/examples/transitions_listener/config.rb new file mode 100644 index 00000000..6b9fb0ea --- /dev/null +++ b/examples/transitions_listener/config.rb @@ -0,0 +1,27 @@ +# frozen_string_literal: true + +require 'bundler/inline' + +$LOAD_PATH.unshift(__dir__) + +require_relative 'config/boot' +require_relative 'config/initializers/bcdd' + +require 'db/setup' + +require 'lib/bcdd/result/rollback_on_failure' +require 'lib/my_bcdd_result_transitions_listener' + +module Account + require 'app/models/account/record' + require 'app/models/account/owner_creation' + require 'app/models/account/member/record' +end + +module User + require 'app/models/user/record' + require 'app/models/user/creation' + + require 'app/models/user/token/record' + require 'app/models/user/token/creation' +end diff --git a/examples/transitions_listener/config/boot.rb b/examples/transitions_listener/config/boot.rb new file mode 100644 index 00000000..098c0622 --- /dev/null +++ b/examples/transitions_listener/config/boot.rb @@ -0,0 +1,16 @@ +# frozen_string_literal: true + +require 'bundler/inline' + +$LOAD_PATH.unshift(__dir__) + +gemfile do + source 'https://rubygems.org' + + gem 'sqlite3', '~> 1.7' + gem 'bcrypt', '~> 3.1.20' + gem 'activerecord', '~> 7.1', '>= 7.1.3', require: 'active_record' + gem 'bcdd-result', path: '../../' +end + +require 'active_support/all' diff --git a/examples/transitions_listener/config/initializers/bcdd.rb b/examples/transitions_listener/config/initializers/bcdd.rb new file mode 100644 index 00000000..f0caa1a2 --- /dev/null +++ b/examples/transitions_listener/config/initializers/bcdd.rb @@ -0,0 +1,11 @@ +# frozen_string_literal: true + +BCDD::Result.config.then do |config| + config.addon.enable!(:continue) + + config.constant_alias.enable!('BCDD::Context') + + config.pattern_matching.disable!(:nil_as_valid_value_checking) + + # config.feature.disable!(:expectations) if Rails.env.production? +end diff --git a/examples/transitions_listener/db/setup.rb b/examples/transitions_listener/db/setup.rb new file mode 100644 index 00000000..b0c2fc89 --- /dev/null +++ b/examples/transitions_listener/db/setup.rb @@ -0,0 +1,47 @@ +# frozen_string_literal: true + +require 'active_support/all' + +ActiveRecord::Base.establish_connection( + host: 'localhost', + adapter: 'sqlite3', + database: ':memory:' +) + +ActiveRecord::Schema.define do + create_table :accounts do |t| + t.string :uuid, null: false, index: {unique: true} + + t.timestamps + end + + create_table :users do |t| + t.string :uuid, null: false, index: {unique: true} + t.string :name, null: false + t.string :email, null: false, index: {unique: true} + t.string :password_digest, null: false + + t.timestamps + end + + create_table :user_tokens do |t| + t.belongs_to :user, null: false, foreign_key: true, index: true + t.string :access_token, null: false + t.string :refresh_token, null: false + t.datetime :access_token_expires_at, null: false + t.datetime :refresh_token_expires_at, null: false + + t.timestamps + end + + create_table :account_memberships do |t| + t.integer :role, null: false, default: 0 + t.belongs_to :user, null: false, foreign_key: true, index: true + t.belongs_to :account, null: false, foreign_key: true, index: true + + t.timestamps + + t.index %i[account_id role], unique: true, where: "(role = 0)" + t.index %i[account_id user_id], unique: true + end +end diff --git a/examples/transitions_listener/lib/bcdd/result/rollback_on_failure.rb b/examples/transitions_listener/lib/bcdd/result/rollback_on_failure.rb new file mode 100644 index 00000000..dbf40b7a --- /dev/null +++ b/examples/transitions_listener/lib/bcdd/result/rollback_on_failure.rb @@ -0,0 +1,15 @@ +# frozen_string_literal: true + +module BCDD::Result::RollbackOnFailure + def rollback_on_failure(model: ::ActiveRecord::Base) + result = nil + + model.transaction do + result = yield + + raise ::ActiveRecord::Rollback if result.failure? + end + + result + end +end diff --git a/examples/transitions_listener/lib/my_bcdd_result_transitions_listener.rb b/examples/transitions_listener/lib/my_bcdd_result_transitions_listener.rb new file mode 100644 index 00000000..722b3e83 --- /dev/null +++ b/examples/transitions_listener/lib/my_bcdd_result_transitions_listener.rb @@ -0,0 +1,35 @@ +# frozen_string_literal: true + +class MyBCDDResultTransitionsListener + include BCDD::Result::Transitions::Listener + + def initialize + @buffer = [] + end + + def around_execution(scope:) + scope => { id:, name:, desc: } + + @buffer << "#{" " * id}##{id} #{name} - #{desc}".chomp('- ') + + yield + end + + # def around_and_then(scope:, and_then:) + # yield + # end + + def after_record(record:) + record => { current: { id: }, result: { kind:, type: } } + + method_name = record.dig(:and_then, :method_name) + + @buffer << "#{" " * (id + 1)}#{kind}(#{type}) from method: #{method_name}".chomp('from method: ') + end + + def after_finish(transitions:) + puts @buffer.join("\n") + end + + # def before_interruption(exception:, transitions:); end +end diff --git a/lib/bcdd/result/config.rb b/lib/bcdd/result/config.rb index 38d0051b..ddc530bd 100644 --- a/lib/bcdd/result/config.rb +++ b/lib/bcdd/result/config.rb @@ -9,7 +9,7 @@ class BCDD::Result class Config - include Singleton + include ::Singleton attr_reader :addon, :feature, :constant_alias, :pattern_matching @@ -21,6 +21,10 @@ def initialize @and_then_ = CallableAndThen::Config.new end + def transitions + Transitions::Config.instance + end + def and_then! @and_then_ end @@ -31,6 +35,7 @@ def freeze constant_alias.freeze pattern_matching.freeze and_then!.freeze + transitions.freeze super end diff --git a/lib/bcdd/result/transitions.rb b/lib/bcdd/result/transitions.rb index f8c0c949..006f6830 100644 --- a/lib/bcdd/result/transitions.rb +++ b/lib/bcdd/result/transitions.rb @@ -4,6 +4,7 @@ class BCDD::Result module Transitions require_relative 'transitions/tree' require_relative 'transitions/tracking' + require_relative 'transitions/config' THREAD_VAR_NAME = :bcdd_result_transitions_tracking @@ -21,8 +22,6 @@ def self.tracking def self.transitions(name: nil, desc: nil, &block) Transitions.tracking.exec(name, desc, &block) rescue ::Exception => e - Transitions.tracking.reset! - - raise e + Transitions.tracking.err!(e) end end diff --git a/lib/bcdd/result/transitions/config.rb b/lib/bcdd/result/transitions/config.rb new file mode 100644 index 00000000..2df45850 --- /dev/null +++ b/lib/bcdd/result/transitions/config.rb @@ -0,0 +1,30 @@ +# frozen_string_literal: true + +module BCDD::Result::Transitions + require_relative 'listener' + + class Config + include ::Singleton + + attr_reader :listener, :trace_id + + def initialize + @trace_id = -> {} + @listener = Listener::Null.new + end + + def listener=(arg) + unless (arg.is_a?(::Class) && arg < Listener) || arg.is_a?(Listener) + raise ::ArgumentError, "#{arg.inspect} must be a #{Listener}" + end + + @listener = arg + end + + def trace_id=(arg) + raise ::ArgumentError, 'must be a lambda with arity 0' unless arg.is_a?(::Proc) && arg.lambda? && arg.arity.zero? + + @trace_id = arg + end + end +end diff --git a/lib/bcdd/result/transitions/listener.rb b/lib/bcdd/result/transitions/listener.rb new file mode 100644 index 00000000..b7bf72be --- /dev/null +++ b/lib/bcdd/result/transitions/listener.rb @@ -0,0 +1,27 @@ +# frozen_string_literal: true + +module BCDD::Result::Transitions + module Listener + def around_execution(scope:) + yield + end + + def around_and_then(scope:, and_then:) + yield + end + + def after_record(record:); end + + def after_finish(transitions:); end + + def before_interruption(exception:, transitions:); end + end + + module Listener::Null + extend Listener + + def self.new + self + end + end +end diff --git a/lib/bcdd/result/transitions/tracking.rb b/lib/bcdd/result/transitions/tracking.rb index c95ddbd1..bb749925 100644 --- a/lib/bcdd/result/transitions/tracking.rb +++ b/lib/bcdd/result/transitions/tracking.rb @@ -6,14 +6,19 @@ module Tracking require_relative 'tracking/enabled' require_relative 'tracking/disabled' + VERSION = 1 + EMPTY_ARRAY = [].freeze EMPTY_HASH = {}.freeze EMPTY_TREE = Tree.new(nil).freeze - VERSION = 1 - EMPTY = { version: VERSION, records: EMPTY_ARRAY, metadata: { duration: 0, tree_map: EMPTY_ARRAY } }.freeze + EMPTY = { + version: VERSION, + records: EMPTY_ARRAY, + metadata: { duration: 0, tree_map: EMPTY_ARRAY, trace_id: nil }.freeze + }.freeze def self.instance - Config.instance.feature.enabled?(:transitions) ? Tracking::Enabled.new : Tracking::Disabled + ::BCDD::Result::Config.instance.feature.enabled?(:transitions) ? Tracking::Enabled.new : Tracking::Disabled end end end diff --git a/lib/bcdd/result/transitions/tracking/disabled.rb b/lib/bcdd/result/transitions/tracking/disabled.rb index f651d30a..3bbe261f 100644 --- a/lib/bcdd/result/transitions/tracking/disabled.rb +++ b/lib/bcdd/result/transitions/tracking/disabled.rb @@ -6,6 +6,10 @@ def self.exec(_name, _desc) EnsureResult[yield] end + def self.err!(err) + raise err + end + def self.reset!; end def self.record(result); end diff --git a/lib/bcdd/result/transitions/tracking/enabled.rb b/lib/bcdd/result/transitions/tracking/enabled.rb index 67d555ff..d04085be 100644 --- a/lib/bcdd/result/transitions/tracking/enabled.rb +++ b/lib/bcdd/result/transitions/tracking/enabled.rb @@ -2,24 +2,36 @@ module BCDD::Result::Transitions class Tracking::Enabled - attr_accessor :tree, :records, :root_started_at + attr_accessor :tree, :records, :root_started_at, :listener - private :tree, :tree=, :records, :records=, :root_started_at, :root_started_at= + private :tree, :tree=, :records, :records=, :root_started_at, :root_started_at=, :listener, :listener= def exec(name, desc) start(name, desc) - transition_node = tree.current + result = nil - result = EnsureResult[yield] + listener.around_execution(scope: tree.current_value[0]) do + transition_node = tree.current - tree.move_to_root! if transition_node.root? + result = EnsureResult[yield] - finish(result) + tree.move_to_root! if transition_node.root? + + finish(result) + end result end + def err!(exception) + listener.before_interruption(exception: exception, transitions: map_transitions) + + reset! + + raise exception + end + def reset! self.tree = Tracking::EMPTY_TREE end @@ -30,17 +42,19 @@ def record(result) track(result, time: ::Time.now.getutc) end - def record_and_then(type_arg, arg) + def record_and_then(type_arg, arg, &block) + return yield if tree.frozen? + type = type_arg.instance_of?(::Method) ? :method : type_arg - unless tree.frozen? - current_and_then = { type: type, arg: arg } - current_and_then[:method_name] = type_arg.name if type == :method + current_and_then = { type: type, arg: arg } + current_and_then[:method_name] = type_arg.name if type == :method - tree.current.value[1] = current_and_then - end + tree.current.value[1] = current_and_then + + scope, and_then = tree.current_value - yield + listener.around_and_then(scope: scope, and_then: and_then, &block) end def reset_and_then! @@ -64,13 +78,13 @@ def finish(result) return unless node.root? - duration = (now_in_milliseconds - root_started_at) - - metadata = { duration: duration, tree_map: tree.nested_ids } + transitions = map_transitions - result.send(:transitions=, version: Tracking::VERSION, records: records, metadata: metadata) + result.send(:transitions=, map_transitions) reset! + + listener.after_finish(transitions: transitions) end TreeNodeValueNormalizer = ->(id, (nam, des)) { [{ id: id, name: nam, desc: des }, Tracking::EMPTY_HASH] } @@ -78,12 +92,24 @@ def finish(result) def root_start(name_and_desc) self.root_started_at = now_in_milliseconds + self.listener = Config.instance.listener.new + self.records = [] self.tree = Tree.new(name_and_desc, normalizer: TreeNodeValueNormalizer) end def track(result, time:) + record = track_record(result, time) + + records << record + + listener.after_record(record: record) + + record + end + + def track_record(result, time) result_data = result.data.to_h result_data[:source] = result.send(:source) @@ -91,11 +117,21 @@ def track(result, time:) parent, = tree.parent_value current, and_then = tree.current_value - records << { root: root, parent: parent, current: current, result: result_data, and_then: and_then, time: time } + { root: root, parent: parent, current: current, result: result_data, and_then: and_then, time: time } end def now_in_milliseconds ::Process.clock_gettime(::Process::CLOCK_MONOTONIC, :millisecond) end + + def map_transitions + duration = (now_in_milliseconds - root_started_at) + + trace_id = Config.instance.trace_id.call + + metadata = { duration: duration, tree_map: tree.nested_ids, trace_id: trace_id } + + { version: Tracking::VERSION, records: records, metadata: metadata } + end end end diff --git a/test/test_helper.rb b/test/test_helper.rb index 41e3fdae..b7caa9c2 100644 --- a/test/test_helper.rb +++ b/test/test_helper.rb @@ -112,10 +112,11 @@ def assert_transitions_metadata(result) metadata = result.transitions[:metadata] - assert_equal(%i[duration tree_map], metadata.keys.sort) + assert_equal(%i[duration trace_id tree_map], metadata.keys.sort) assert_instance_of(Integer, metadata[:duration]) assert_instance_of(Array, metadata[:tree_map]) + assert_nil(metadata[:trace_id]) end TimeValue = ->(value) { value.is_a?(::Time) && value.utc? }