Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby
9.0 KB
Raw Blame
# Runs a family's rules one after another, top to bottom (Rule#position).
#
# - Top rule wins: once a rule sets an attribute on a transaction, rules further
#   down leave that attribute alone in the same run, even when the value was
#   already set or the attribute is locked. Tags are additive and claim nothing.
# - Stop processing: a transaction matched by a rule with stop_processing is not
#   touched by any rule further down.
#
# Active rules above the ones requested run first, in order, so applying a
# single rule gives the same result as its turn in the full run (e.g. it sees
# a rename a rule above makes). Rules below the last requested rule don't run.
# Inactive rules above are skipped because they don't run nightly either.
# ignore_attribute_locks only applies to the requested rules.
#
# With transaction_ids every rule, including the active rules above, only
# looks at those transactions ("apply immediately" after a manual or API
# change). Rules that match none of them are skipped without a RuleRun, so
# editing doesn't fill the history. In such a run the active rules above don't
# send their emails: only rules marked "apply immediately" email right away,
# the others keep emailing from the nightly run (emails claim no attribute,
# so skipping them changes nothing for the rules below).
#
# One run per family at a time, guarded by a PostgreSQL advisory lock. A busy
# lock raises LockBusy so the calling job can retry instead of dropping the run.
class Rule::Runner
  LockBusy = Class.new(StandardError)

  # changed_now_count: transactions the run changed itself, without the ones
  # handed to AI jobs, which report their own changes (RuleRun#complete_job!).
  attr_reader :errors, :changed_now_count

  def self.advisory_lock_key(family_id)
    Digest::MD5.hexdigest("rule_runner:#{family_id}").to_i(16) % (2**62)
  end

  def initialize(family, rules:, execution_type:, ignore_attribute_locks: false, transaction_ids: nil)
    @family = family
    @transaction_ids = transaction_ids&.map(&:to_s)
    @rule_ids = rules.map(&:id).to_set
    @execution_type = execution_type
    @ignore_attribute_locks = ignore_attribute_locks
    @claimed_ids = Hash.new { |hash, attribute| hash[attribute] = Set.new }
    @stopped_ids = Set.new
    @errors = []
    @changed_now_count = 0
  end

  # Returns the RuleRun records created, one per executed rule.
  def run
    return [] if rule_ids.empty?

    rule_runs = nil
    acquired = with_family_lock { rule_runs = run_rules }
    raise LockBusy, "Rules are already running for family #{family.id}" unless acquired

    rule_runs
  end

  private
    attr_reader :family, :rule_ids, :execution_type, :ignore_attribute_locks, :claimed_ids, :stopped_ids, :transaction_ids

    def run_rules
      rule_runs = []
      remaining_ids = rule_ids.dup

      family.rules.ordered.includes(:family, :actions, conditions: :sub_conditions).each do |rule|
        break if remaining_ids.empty?

        if remaining_ids.delete?(rule.id)
          rule_runs << execute(rule, ignore_attribute_locks: ignore_attribute_locks)
        elsif rule.active?
          rule_runs << execute(rule, ignore_attribute_locks: false, skip_action_types: deferred_action_types)
        end
      end

      rule_runs.compact
    end

    def unstopped_scope(rule)
      Rule.excluding_transaction_ids(rule.matching_scope(within_ids: transaction_ids), stopped_ids)
    end

    def record_claims(rule, matched_ids)
      rule.actions.each do |action|
        reserved_attributes(action).each { |attribute| claimed_ids[attribute].merge(matched_ids) }
      end

      stopped_ids.merge(matched_ids) if rule.stop_processing?
    end

    # An action that cannot be resolved (e.g. an unknown action_type from an
    # import) sets nothing, so it claims nothing and must not abort the run.
    def reserved_attributes(action)
      return [] unless action.reserves_claimed_attributes?

      action.claimed_attributes
    rescue => e
      Rails.logger.error("Rule::Runner could not read claims of action #{action.id}: #{e.class}: #{e.message}")
      []
    end

    def deferred_action_types
      transaction_ids ? [ Rule::ActionExecutor::SendEmailNotification.key ] : []
    end

    def execute(rule, ignore_attribute_locks:, skip_action_types: [])
      executed_at = Time.current
      matched_ids = []
      rule_run = nil

      begin
        scope = unstopped_scope(rule)
        matched_ids = scope.pluck(:id)
        return nil if transaction_ids && matched_ids.empty?
        # Nothing left to run, but stop_processing still holds (see ensure).
        return nil if skip_action_types.any? && rule.actions.all? { |action| skip_action_types.include?(action.action_type) }

        rule_run = RuleRun.create!(
          rule: rule,
          rule_name: rule.name,
          execution_type: execution_type,
          status: "pending",
          transactions_queued: matched_ids.size,
          transactions_processed: 0,
          transactions_modified: 0,
          pending_jobs_count: 0,
          executed_at: executed_at
        )

        # Every action works on the transactions matched now, not on a scope
        # that re-checks the conditions: otherwise an action that changes a
        # matched field (e.g. the name) would hide the transactions from the
        # actions after it, while the claims below still reserve them.
        result = rule.apply(
          ignore_attribute_locks: ignore_attribute_locks,
          rule_run: rule_run,
          scope: rule.scope_for_transaction_ids(matched_ids),
          claimed_ids: claimed_ids,
          skip_action_types: skip_action_types
        )

        rule_run.update!(**run_counts(result, queued: matched_ids.size, rule: rule))
        @changed_now_count += changed_now(result)
      rescue => e
        rule_run = record_failure(rule, rule_run, e, executed_at: executed_at, queued: matched_ids.size)
      ensure
        # Claims hold even when the rule failed halfway, so a rule further down
        # never overwrites what this rule may already have set.
        record_claims(rule, matched_ids)
      end

      rule_run
    end

    def run_counts(result, queued:, rule:)
      if result.is_a?(Hash) && result[:async]
        # The async jobs report the modified count back via RuleRun#complete_job!
        { status: "pending", transactions_processed: result[:modified_count] || 0, pending_jobs_count: result[:jobs_count] || 0 }
      elsif result.is_a?(Integer)
        { status: "success", transactions_processed: queued, transactions_modified: result }
      else
        Rails.logger.warn("Rule::Runner: Unexpected result type from rule.apply: #{result.class} for rule #{rule.id}")
        { status: "success" }
      end
    end

    def changed_now(result)
      if result.is_a?(Hash) && result[:async]
        result[:changed_now_count] || 0
      elsif result.is_a?(Integer)
        result
      else
        0
      end
    end

    def record_failure(rule, rule_run, error, executed_at:, queued:)
      errors << error
      error_message = "#{error.class}: #{error.message}"
      Rails.logger.error("Rule::Runner failed for rule #{rule.id}: #{error_message}")
      # A failed rule, such as a pattern that timed out, is the user's to fix, so
      # support sees it in the debug log as RuleRun#fail_job! records its own.
      DebugLogEntry.capture(
        category: "rule_run",
        level: "error",
        message: "Rule run failed: #{error_message}",
        source: self.class.name,
        family: rule.family,
        metadata: {
          rule_id: rule.id,
          rule_name: rule.name,
          execution_type: execution_type,
          error_class: error.class.name,
          error_message: error.message,
          backtrace: Array(error.backtrace).first(10)
        }
      )

      if rule_run
        rule_run.update(status: "failed", error_message: error_message)
        rule_run
      else
        RuleRun.create!(
          rule: rule,
          rule_name: rule.name,
          execution_type: execution_type,
          status: "failed",
          transactions_queued: queued,
          transactions_processed: 0,
          transactions_modified: 0,
          pending_jobs_count: 0,
          executed_at: executed_at,
          error_message: error_message
        )
      end
    rescue => e
      Rails.logger.error("Rule::Runner: Failed to record RuleRun for rule #{rule.id}: #{e.message}")
      rule_run
    end

    # Same pattern as RecurringTransaction::Pipeline.with_family_lock: one
    # leased connection for lock and unlock, because the unlock must run on the
    # PostgreSQL session that took the lock.
    def with_family_lock
      lock_key = self.class.advisory_lock_key(family.id)
      connection = ActiveRecord::Base.lease_connection
      acquired = connection.select_value(
        ActiveRecord::Base.sanitize_sql_array([ "SELECT pg_try_advisory_lock(?)", lock_key ])
      )

      return false unless acquired

      begin
        yield
      ensure
        connection.execute(
          ActiveRecord::Base.sanitize_sql_array([ "SELECT pg_advisory_unlock(?)", lock_key ])
        )
      end
      true
    end
end