Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby
6.6 KB
Raw Blame
# There are hundreds of thousands of market securities that Sure must handle.
# Due to the always-changing nature of the market, the health checker is responsible
# for periodically checking active securities to ensure we can still fetch prices for them.
#
# Each security goes through some basic health checks.  If failed, this class is responsible for:
# - Marking failed attempts and incrementing the failed attempts counter
# - Marking the security offline if enough consecutive failed checks occur
# - When we move a security "offline", delete its prices ONLY if it never had a
#   successfully-fetched price — an established history isn't suddenly "bad data"
#   just because the provider can't currently be reached
#
# The health checker is run daily through SecurityHealthCheckJob (see config/schedule.yml), but not all
# securities will be checked every day (we run in batches)
class Security::HealthChecker
  MAX_CONSECUTIVE_FAILURES = 5
  HEALTH_CHECK_INTERVAL = 7.days
  DAILY_BATCH_SIZE = 1000
  LOOKBACK_DAYS = 10

  class << self
    def check_all
      # No daily limit for unchecked securities (they are prioritized)
      never_checked_scope.find_each do |security|
        new(security).run_check
      end

      # Daily limit for checked securities
      due_for_check_scope.limit(DAILY_BATCH_SIZE).each do |security|
        new(security).run_check
      end
    end

    private
      # If a security has never had a health check, we prioritize it, regardless of batch size
      def never_checked_scope
        Security.standard.where(last_health_check_at: nil)
      end

      # Any securities not checked for 30 days are due
      # We only process the batch size, which means some "due" securities will not be checked today
      # This is by design, to prevent all securities from coming due at the same time
      def due_for_check_scope
        Security.standard.where(last_health_check_at: ..HEALTH_CHECK_INTERVAL.ago)
                         .order(last_health_check_at: :asc)
      end
  end

  def initialize(security)
    @security = security
  end

  def run_check
    Rails.logger.info("Running health check for #{security.ticker}")

    # Nothing to check — either no provider is assigned, or the assigned
    # provider is currently disabled/unavailable (Setting.enabled_securities_providers).
    # This is NOT a fetch failure: counting it as one would eventually overwrite
    # a more specific offline_reason (e.g. "provider_disabled", set explicitly
    # when an admin disables a provider) with the generic "health_check_failed",
    # which then makes the bulk reactivation-on-re-enable in
    # Settings::HostingsController#update stop finding this security.
    return if provider.blank?

    if latest_provider_price
      handle_success
    else
      handle_failure
    end
  rescue => e
    Sentry.capture_exception(e) do |scope|
      scope.set_tags(security_id: @security.id)
    end
  ensure
    security.update!(last_health_check_at: Time.current)
  end

  private
    attr_reader :security

    def provider
      security.price_data_provider
    end

    # Some providers (e.g., Alpha Vantage) have very low daily limits and no
    # lightweight endpoint — each health check burns a full API call that
    # fetches ~100 data points. Skip health checks for those providers to
    # avoid exhausting their quota on monitoring alone.
    def skip_health_check?
      provider.present? && provider.respond_to?(:max_history_days) &&
        provider.is_a?(Provider::AlphaVantage)
    end

    def latest_provider_price
      return nil unless provider.present?
      return true if skip_health_check? # treat as healthy — quota too precious

      response = provider.fetch_security_prices(
        symbol: security.ticker,
        exchange_operating_mic: security.exchange_operating_mic,
        start_date: Date.current - LOOKBACK_DAYS,
        end_date: Date.current
      )

      return nil unless response.success?

      latest = Array(response.data)
                 .select { |price| price.price.present? && price.price.to_f > 0 }
                 .max_by(&:date)
      latest&.price
    end

    # On success, reset any failure counters and ensure it is "online"
    def handle_success
      security.update!(
        offline: false,
        failed_fetch_count: 0,
        failed_fetch_at: nil
      )
    end

    def handle_failure
      new_failure_count = security.failed_fetch_count.to_i + 1
      new_failure_at = Time.current

      if new_failure_count > MAX_CONSECUTIVE_FAILURES
        convert_to_offline_security!
      else
        security.update!(
          failed_fetch_count: new_failure_count,
          failed_fetch_at: new_failure_at
        )

        DebugLogEntry.capture(
          category: "security_health_check",
          level: "warn",
          message: "Security health check failed (#{new_failure_count}/#{MAX_CONSECUTIVE_FAILURES})",
          source: self.class.name,
          provider: provider,
          metadata: {
            security_id: security.id,
            ticker: security.ticker,
            exchange_operating_mic: security.exchange_operating_mic,
            failed_fetch_count: new_failure_count
          }
        )
      end
    end

    # The "offline" state tells our MarketDataImporter (daily cron) to skip this security when fetching prices
    def convert_to_offline_security!
      had_price_history = security.prices.exists?

      Security.transaction do
        security.update!(
          offline: true,
          offline_reason: "health_check_failed",
          failed_fetch_count: MAX_CONSECUTIVE_FAILURES + 1,
          failed_fetch_at: Time.current
        )
        # Only delete prices when the security never had a successfully-fetched
        # one — five failed *new* fetches say nothing about the correctness of
        # *existing* history. Deleting a track record just because the provider
        # is temporarily unreachable would be a silent, hard-to-notice data loss.
        security.prices.delete_all unless had_price_history
      end

      DebugLogEntry.capture(
        category: "security_health_check",
        level: "error",
        message: had_price_history ?
          "Security marked offline after #{MAX_CONSECUTIVE_FAILURES} consecutive health check failures; existing price history preserved" :
          "Security marked offline after #{MAX_CONSECUTIVE_FAILURES} consecutive health check failures; no prior price history to preserve",
        source: self.class.name,
        provider: provider,
        metadata: {
          security_id: security.id,
          ticker: security.ticker,
          exchange_operating_mic: security.exchange_operating_mic,
          had_price_history: had_price_history
        }
      )
    end
end