Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Add a super-admin reset of instance-wide market data (#4760)

GFRae99732ec643
diff --git a/app/controllers/settings/hostings_controller.rb b/app/controllers/settings/hostings_controller.rb
index 86fefe2d23..34057ed1f3 100644
--- a/app/controllers/settings/hostings_controller.rb
+++ b/app/controllers/settings/hostings_controller.rb
@@ -19,6 +19,7 @@ class Settings::HostingsController < ApplicationController
before_action :ensure_admin, only: [ :update, :clear_cache, :disconnect_external_assistant ]
before_action :ensure_instance_settings_manager, only: [ :update, :disconnect_external_assistant ]
before_action :ensure_super_admin_for_onboarding, only: :update
+ before_action :ensure_super_admin, only: :reset_market_data
def show
@breadcrumbs = [
@@ -341,6 +342,14 @@ class Settings::HostingsController < ApplicationController
redirect_to settings_hosting_path, notice: t(".cache_cleared")
end
+ def reset_market_data
+ case MarketDataResetJob.enqueue_once
+ when :queued then redirect_to settings_hosting_path, notice: t(".market_data_reset")
+ when :already_queued then redirect_to settings_hosting_path, notice: t(".market_data_reset_already_queued")
+ else redirect_to settings_hosting_path, alert: t(".market_data_reset_failed")
+ end
+ end
+
def disconnect_external_assistant
Setting.external_assistant_url = nil
Setting.external_assistant_token = nil
@@ -518,6 +527,10 @@ class Settings::HostingsController < ApplicationController
redirect_to settings_hosting_path, alert: t(".not_authorized") unless Current.user.manages_instance_settings?
end
+ def ensure_super_admin
+ redirect_to settings_hosting_path, alert: t("settings.hostings.not_authorized") unless Current.user.super_admin?
+ end
+
def ensure_super_admin_for_onboarding
onboarding_params = %i[onboarding_state invite_only_default_family_id]
return unless onboarding_params.any? { |p| hosting_params.key?(p) }
diff --git a/app/jobs/market_data_reset_job.rb b/app/jobs/market_data_reset_job.rb
new file mode 100644
index 0000000000..30ed5d14b9
--- /dev/null
+++ b/app/jobs/market_data_reset_job.rb
@@ -0,0 +1,185 @@
+# Instance-wide counterpart to DataCacheClearJob, reserved for super admins.
+#
+# Exchange rates and security prices are shared by every family, so after
+# deleting them we re-import everything the instance needs before the accounts
+# rebuild. Otherwise parallel account syncs race to re-import the same pairs and
+# other families see unconverted (1:1) totals until the next scheduled import.
+#
+# Only data the import fetches again is deleted: the windows MarketDataImporter
+# requests, clamped to how far back each provider reaches. Prices and rates
+# outside them (offline securities, providers without history, dates nothing
+# needs) stay as they are.
+class MarketDataResetJob < ApplicationJob
+ queue_as :scheduled
+ # A retry would delete the freshly re-imported data again. ApplicationJob's
+ # deadlock retry stays: a deadlock can only come from the deletes, before
+ # anything is imported.
+ sidekiq_options retry: false
+
+ ENQUEUE_GUARD_KEY = "market_data_reset_job:enqueued".freeze
+ ENQUEUE_GUARD_TTL = 12.hours
+ ADVISORY_LOCK_KEY = Digest::MD5.hexdigest(name).to_i(16) % (2**62)
+ # Deletes the guard only while it still holds the caller's token, so a run
+ # whose guard expired cannot release the guard of a reset queued later.
+ RELEASE_GUARD_SCRIPT = <<~LUA.freeze
+ if redis.call("GET", KEYS[1]) == ARGV[1] then return redis.call("DEL", KEYS[1]) else return 0 end
+ LUA
+
+ # Queues the reset unless one is already queued or running, so a second
+ # click does not delete and re-import everything again. The guard lives in
+ # Redis, which every web and worker process shares. Returns :queued,
+ # :already_queued or :failed.
+ def self.enqueue_once
+ token = SecureRandom.uuid
+ return :already_queued unless Sidekiq.redis { |conn| conn.call("SET", guard_key, token, "NX", "EX", ENQUEUE_GUARD_TTL.to_i) }
+
+ return :queued if perform_later(token)
+
+ release_guard(token)
+ :failed
+ rescue => e
+ Rails.logger.error("MarketDataResetJob could not be queued: #{e.class}: #{e.message}")
+ release_guard(token)
+ :failed
+ end
+
+ def self.guard_key
+ ENQUEUE_GUARD_KEY
+ end
+
+ # The guard expires on its own, so a failure to release it only delays the
+ # next reset. Without a token (a job queued before guards had one, a run
+ # from the console) the guard is released whoever set it.
+ def self.release_guard(token)
+ Sidekiq.redis do |conn|
+ token ? conn.call("EVAL", RELEASE_GUARD_SCRIPT, 1, guard_key, token) : conn.call("DEL", guard_key)
+ end
+ rescue => e
+ Rails.logger.error("MarketDataResetJob could not release its enqueue guard: #{e.class}: #{e.message}")
+ end
+
+ # The guard is released after the advisory lock, so a reset queued in
+ # between always finds the lock free. A run that finds another reset running
+ # leaves the guard to that run. A run Sidekiq requeues for a shutdown, or
+ # that ApplicationJob retries after a deadlock, keeps it for the next
+ # attempt, which carries the same token.
+ def perform(guard_token = nil)
+ release = with_advisory_lock { reset_market_data }
+ rescue Sidekiq::Shutdown, ActiveRecord::Deadlocked
+ release = false
+ raise
+ rescue
+ release = true
+ raise
+ ensure
+ self.class.release_guard(guard_token) if release
+ end
+
+ private
+ def reset_market_data
+ # clear_cache ignores the stored coverage of the old data, so the
+ # provider is asked for the whole window again.
+ importer = MarketDataImporter.new(mode: :full, clear_cache: true)
+ price_windows = importer.required_security_price_windows
+ rate_pairs = importer.required_exchange_rate_pairs
+
+ delete_security_prices(price_windows)
+ delete_exchange_rates(rate_pairs, end_date: importer.end_date)
+
+ # Import each kind on its own so a failure in one still leaves the other
+ # in place before the accounts rebuild.
+ import_step(:security_prices) { importer.import_security_prices }
+ import_step(:exchange_rates) { importer.import_exchange_rates }
+
+ # Account syncs fetch any rates and prices still missing (also the
+ # currencies of foreign security prices) and rebuild balances and
+ # holdings. They are queued per account, not through the family syncs,
+ # which skip the accounts of a connection whose provider fails.
+ Account.find_each do |account|
+ account.sync_later
+ rescue => e
+ Rails.logger.error("MarketDataResetJob failed to sync account #{account.id}: #{e.message}")
+ end
+ end
+
+ def delete_security_prices(windows)
+ Security.online.where(id: windows.keys).find_each do |security|
+ provider = security.price_data_provider
+ next unless provider
+
+ window = windows.fetch(security.id)
+ start_date = history_start(window.start_date, provider.max_history_days)
+ next if start_date > window.end_date
+
+ security.prices.where(date: start_date..window.end_date).delete_all
+ end
+ end
+
+ def delete_exchange_rates(pairs, end_date:)
+ provider = exchange_rate_provider
+ return unless provider
+
+ pairs.each do |pair|
+ start_date = history_start(pair[:start_date], provider.max_history_days)
+ next if start_date > end_date
+
+ ExchangeRate.where(from_currency: pair[:source], to_currency: pair[:target], date: start_date..end_date).delete_all
+ end
+ end
+
+ # A provider with a limited history (or none, like a latest-quote-only API)
+ # cannot restore older rows, so those are kept.
+ def history_start(start_date, max_history_days)
+ return start_date if max_history_days.nil?
+
+ [ start_date, Date.current - max_history_days.days ].max
+ end
+
+ def exchange_rate_provider
+ ExchangeRate.provider
+ rescue Provider::Registry::Error
+ nil
+ end
+
+ # Only one reset runs at a time, also when two were queued. Returns false
+ # when another reset holds the lock.
+ def with_advisory_lock
+ lock_key = ADVISORY_LOCK_KEY
+
+ unless try_advisory_lock(lock_key)
+ Rails.logger.warn("MarketDataResetJob skipped: another reset is running")
+ return false
+ end
+
+ begin
+ yield
+ true
+ ensure
+ ActiveRecord::Base.connection.execute(
+ ActiveRecord::Base.sanitize_sql_array([ "SELECT pg_advisory_unlock(?)", lock_key ])
+ )
+ end
+ end
+
+ def try_advisory_lock(lock_key)
+ ActiveRecord::Base.connection.select_value(
+ ActiveRecord::Base.sanitize_sql_array([ "SELECT pg_try_advisory_lock(?)", lock_key ])
+ )
+ end
+
+ # A failed import must not stop the account syncs: they fetch any rates and
+ # prices that are still missing.
+ def import_step(step)
+ yield
+ rescue => e
+ Rails.logger.error("MarketDataResetJob #{step} import failed: #{e.class}: #{e.message}")
+ Sentry.capture_exception(e) if defined?(Sentry)
+ DebugLogEntry.capture(
+ category: "market_data",
+ level: "error",
+ message: "Market data re-import after reset failed; continuing with account syncs",
+ source: self.class.name,
+ metadata: { step: step, error_class: e.class.name }
+ )
+ end
+end
diff --git a/app/models/market_data_importer.rb b/app/models/market_data_importer.rb
index 0b483f5484..03cf7ee777 100644
--- a/app/models/market_data_importer.rb
+++ b/app/models/market_data_importer.rb
@@ -173,4 +173,9 @@ class MarketDataImporter
mode.to_sym
end
+
+ # The windows and pairs import_security_prices and import_exchange_rates
+ # request, and the last date they request; MarketDataResetJob deletes only
+ # those before re-importing.
+ public :required_security_price_windows, :required_exchange_rate_pairs, :end_date
end
diff --git a/app/views/settings/hostings/_danger_zone_settings.html.erb b/app/views/settings/hostings/_danger_zone_settings.html.erb
index 23e26644e8..d3b3a2212f 100644
--- a/app/views/settings/hostings/_danger_zone_settings.html.erb
+++ b/app/views/settings/hostings/_danger_zone_settings.html.erb
@@ -16,5 +16,28 @@
}}
%>
</div>
+
+ <% if Current.user.super_admin? %>
+ <div class="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
+ <div class="w-full md:w-2/3">
+ <h3 class="font-medium text-primary"><%= t("settings.hostings.show.reset_market_data") %></h3>
+ <p class="text-secondary text-sm"><%= t("settings.hostings.show.reset_market_data_warning") %></p>
+ </div>
+ <%= render DS::Button.new(
+ text: t("settings.hostings.show.reset_market_data"),
+ variant: :destructive,
+ href: reset_market_data_settings_hosting_path,
+ method: :delete,
+ class: "w-full md:w-auto",
+ confirm: CustomConfirm.new(
+ destructive: true,
+ high_severity: true,
+ title: t("settings.hostings.show.confirm_reset_market_data.title"),
+ body: t("settings.hostings.show.confirm_reset_market_data.body"),
+ btn_text: t("settings.hostings.show.reset_market_data")
+ )
+ ) %>
+ </div>
+ <% end %>
</div>
<% end %>
diff --git a/config/locales/views/settings/hostings/de.yml b/config/locales/views/settings/hostings/de.yml
index f7951eba15..19c7cfa7c9 100644
--- a/config/locales/views/settings/hostings/de.yml
+++ b/config/locales/views/settings/hostings/de.yml
@@ -29,6 +29,11 @@ de:
confirm_clear_cache:
title: Daten-Cache leeren?
body: Bist du sicher, dass du den Daten-Cache leeren möchtest? Dadurch werden alle Wechselkurse, Wertpapierpreise, Kontostände und andere Daten entfernt. Diese Aktion kann nicht rückgängig gemacht werden.
+ reset_market_data: Marktdaten für alle Familien zurücksetzen
+ reset_market_data_warning: Löscht die Wechselkurse und Wertpapierpreise, die deine Anbieter neu laden können, lädt sie neu und synchronisiert danach jedes Konto. Bis der Import fertig ist, werden Fremdwährungsbeträge eventuell unumgerechnet angezeigt.
+ confirm_reset_market_data:
+ title: Marktdaten für alle Familien zurücksetzen?
+ body: Dadurch werden die Wechselkurse und Wertpapierpreise, die deine Anbieter neu laden können, für jede Familie dieser Instanz gelöscht und neu geladen. Bis der Import fertig ist, werden Fremdwährungsbeträge eventuell unumgerechnet angezeigt. Diese Aktion kann nicht rückgängig gemacht werden.
ai_assistant: KI-Assistent
property_valuation_providers: Anbieter für Immobilienbewertung
provider_selection:
@@ -149,6 +154,10 @@ de:
invalid_llm_budget: "%{field} muss eine ganze Zahl ≥ %{minimum} sein."
clear_cache:
cache_cleared: Daten-Cache wurde geleert. Dies kann einige Augenblicke dauern.
+ reset_market_data:
+ market_data_reset: Zurücksetzen der Marktdaten eingeplant. Kurse und Preise werden neu geladen, danach werden alle Konten synchronisiert.
+ market_data_reset_already_queued: Ein Zurücksetzen der Marktdaten ist bereits eingeplant oder läuft.
+ market_data_reset_failed: Das Zurücksetzen der Marktdaten konnte nicht eingeplant werden. Es wurde nichts gelöscht, bitte versuche es erneut.
not_authorized: Du bist nicht berechtigt, diese Aktion auszuführen.
sync_settings:
auto_sync_label: Automatische Synchronisierung aktivieren
diff --git a/config/locales/views/settings/hostings/en.yml b/config/locales/views/settings/hostings/en.yml
index f4c0cfbc97..731dcebdc0 100644
--- a/config/locales/views/settings/hostings/en.yml
+++ b/config/locales/views/settings/hostings/en.yml
@@ -39,6 +39,11 @@ en:
confirm_clear_cache:
title: Clear data cache?
body: Are you sure you want to clear the data cache? This will remove all exchange rates, security prices, account balances, and other data. This action cannot be undone.
+ reset_market_data: Reset market data for all families
+ reset_market_data_warning: Deletes the exchange rates and security prices your providers can load again, re-imports them, and then syncs every account. Foreign-currency totals may show unconverted until the import finishes.
+ confirm_reset_market_data:
+ title: Reset market data for all families?
+ body: This deletes the exchange rates and security prices your providers can load again, for every family on this instance, and re-imports them. Until the import finishes, foreign-currency amounts may be shown unconverted. This action cannot be undone.
provider_selection:
exchange_rate_title: Exchange Rate Provider
exchange_rate_description: Select a single provider for fetching currency exchange rates.
@@ -334,6 +339,10 @@ en:
external_assistant_disconnected: External assistant disconnected
clear_cache:
cache_cleared: Data cache has been cleared. This may take a few moments to complete.
+ reset_market_data:
+ market_data_reset: Market data reset queued. Rates and prices will be re-imported, then all accounts will sync.
+ market_data_reset_already_queued: A market data reset is already queued or running.
+ market_data_reset_failed: The market data reset could not be queued. Nothing was deleted; please try again.
not_authorized: You are not authorized to perform this action
ensure_admin:
not_authorized: You are not authorized to perform this action
diff --git a/config/routes.rb b/config/routes.rb
index 5a5422cb81..011368cfdd 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -411,6 +411,7 @@ Rails.application.routes.draw do
end
resource :hosting, only: %i[show update] do
delete :clear_cache, on: :collection
+ delete :reset_market_data, on: :collection
delete :disconnect_external_assistant, on: :collection
end
resource :payment, only: :show
diff --git a/test/controllers/settings/hostings_controller_test.rb b/test/controllers/settings/hostings_controller_test.rb
index e3cf42586f..40668375e6 100644
--- a/test/controllers/settings/hostings_controller_test.rb
+++ b/test/controllers/settings/hostings_controller_test.rb
@@ -863,6 +863,75 @@ class Settings::HostingsControllerTest < ActionDispatch::IntegrationTest
assert_not Balance.exists?(account_balance.id)
end
+ test "super admin can reset market data for the whole instance" do
+ sign_in users(:sure_support_staff)
+ MarketDataResetJob.stubs(:guard_key).returns("market_data_reset_job:test:#{SecureRandom.hex(8)}")
+
+ with_self_hosting do
+ assert_enqueued_with(job: MarketDataResetJob) do
+ delete reset_market_data_settings_hosting_url
+ end
+ end
+
+ assert_redirected_to settings_hosting_url
+ assert_equal I18n.t("settings.hostings.reset_market_data.market_data_reset"), flash[:notice]
+ ensure
+ Sidekiq.redis { |conn| conn.call("DEL", MarketDataResetJob.guard_key) }
+ end
+
+ test "a second market data reset is not queued while one is pending" do
+ sign_in users(:sure_support_staff)
+ MarketDataResetJob.stubs(:enqueue_once).returns(:already_queued)
+
+ with_self_hosting do
+ delete reset_market_data_settings_hosting_url
+ end
+
+ assert_redirected_to settings_hosting_url
+ assert_equal I18n.t("settings.hostings.reset_market_data.market_data_reset_already_queued"), flash[:notice]
+ end
+
+ test "a market data reset that cannot be queued says so" do
+ sign_in users(:sure_support_staff)
+ MarketDataResetJob.stubs(:enqueue_once).returns(:failed)
+
+ with_self_hosting do
+ delete reset_market_data_settings_hosting_url
+ end
+
+ assert_redirected_to settings_hosting_url
+ assert_equal I18n.t("settings.hostings.reset_market_data.market_data_reset_failed"), flash[:alert]
+ end
+
+ test "family admin cannot reset market data for the whole instance" do
+ users(:family_admin).update!(role: :admin)
+
+ with_self_hosting do
+ assert_no_enqueued_jobs only: MarketDataResetJob do
+ delete reset_market_data_settings_hosting_url
+ end
+ end
+
+ assert_redirected_to settings_hosting_url
+ assert_equal I18n.t("settings.hostings.not_authorized"), flash[:alert]
+ end
+
+ test "only super admins see the market data reset" do
+ users(:family_admin).update!(role: :admin)
+
+ with_self_hosting do
+ get settings_hosting_url
+ assert_response :success
+ assert_select "form[action='#{reset_market_data_settings_hosting_path}']", count: 0
+ assert_select "form[action='#{clear_cache_settings_hosting_path}']", count: 1
+
+ sign_in users(:sure_support_staff)
+ get settings_hosting_url
+ assert_response :success
+ assert_select "form[action='#{reset_market_data_settings_hosting_path}']", count: 1
+ end
+ end
+
test "can update assistant type to external" do
with_self_hosting do
assert_equal "builtin", users(:family_admin).family.assistant_type
diff --git a/test/jobs/market_data_reset_job_test.rb b/test/jobs/market_data_reset_job_test.rb
new file mode 100644
index 0000000000..b26b544d47
--- /dev/null
+++ b/test/jobs/market_data_reset_job_test.rb
@@ -0,0 +1,249 @@
+require "test_helper"
+
+class MarketDataResetJobTest < ActiveJob::TestCase
+ class OtherSession < ActiveRecord::Base
+ self.abstract_class = true
+ end
+
+ Window = Security::Price::ImportWindows::Window
+
+ setup do
+ @security = securities(:aapl)
+ @price_in_window = @security.prices.create!(date: 20.days.ago.to_date, price: 200, currency: "USD")
+ @price_before_window = @security.prices.create!(date: 2.years.ago.to_date, price: 150, currency: "USD")
+ @rate_in_window = exchange_rates(:one)
+ @rate_before_window = ExchangeRate.create!(from_currency: "EUR", to_currency: "GBP", date: 2.years.ago.to_date, rate: 0.9)
+
+ @securities_provider = stub(max_history_days: nil)
+ @exchange_rate_provider = stub(max_history_days: nil)
+ Security.stubs(:providers).returns([ @securities_provider ])
+ ExchangeRate.stubs(:provider).returns(@exchange_rate_provider)
+
+ MarketDataImporter.any_instance.stubs(:required_security_price_windows)
+ .returns(@security.id => Window.new(start_date: 1.year.ago.to_date, end_date: Date.current))
+ MarketDataImporter.any_instance.stubs(:required_exchange_rate_pairs)
+ .returns([ { source: "EUR", target: "GBP", start_date: 1.year.ago.to_date } ])
+ end
+
+ test "deletes the data the import requests, re-imports it, then syncs every account" do
+ sequence = sequence("reset")
+ MarketDataImporter.any_instance.expects(:import_security_prices).in_sequence(sequence).with do
+ assert_not Security::Price.exists?(@price_in_window.id), "prices must be gone before the re-import"
+ true
+ end
+ MarketDataImporter.any_instance.expects(:import_exchange_rates).in_sequence(sequence).with do
+ assert_not ExchangeRate.exists?(@rate_in_window.id), "rates must be gone before the re-import"
+ assert_no_enqueued_jobs only: SyncJob
+ true
+ end
+
+ MarketDataResetJob.perform_now
+
+ assert Security::Price.exists?(@price_before_window.id), "prices outside the import window stay"
+ assert ExchangeRate.exists?(@rate_before_window.id), "rates outside the import window stay"
+ assert_enqueued_jobs Account.count, only: SyncJob
+ end
+
+ test "imports with the cache cleared so stored coverage does not shorten the request" do
+ importer = MarketDataImporter.new(mode: :full, clear_cache: true)
+ MarketDataImporter.expects(:new).with(mode: :full, clear_cache: true).returns(importer)
+ stub_imports
+
+ MarketDataResetJob.perform_now
+ end
+
+ test "keeps prices and rates older than the provider's history" do
+ stub_imports
+ @securities_provider.stubs(:max_history_days).returns(10)
+ @exchange_rate_provider.stubs(:max_history_days).returns(0)
+
+ MarketDataResetJob.perform_now
+
+ assert Security::Price.exists?(@price_in_window.id), "20 days back is beyond a 10-day history"
+ assert ExchangeRate.exists?(@rate_before_window.id)
+ assert_not ExchangeRate.exists?(@rate_in_window.id), "today's rate is within a latest-only history"
+ end
+
+ test "keeps data that no configured provider can fetch again" do
+ stub_imports
+ ExchangeRate.stubs(:provider).returns(nil)
+ Security.stubs(:providers).returns([])
+
+ MarketDataResetJob.perform_now
+
+ assert ExchangeRate.exists?(@rate_in_window.id)
+ assert Security::Price.exists?(@price_in_window.id)
+ end
+
+ test "keeps offline securities, balances and holdings" do
+ stub_imports
+ offline = Security.create!(ticker: "OFFL", name: "Offline Co", offline: true)
+ offline_price = offline.prices.create!(date: 20.days.ago.to_date, price: 10, currency: "USD")
+ MarketDataImporter.any_instance.stubs(:required_security_price_windows)
+ .returns(offline.id => Window.new(start_date: 1.year.ago.to_date, end_date: Date.current))
+ balance = accounts(:depository).balances.create!(date: Date.current, balance: 1000, currency: "USD")
+ holding = accounts(:investment).holdings.first
+
+ MarketDataResetJob.perform_now
+
+ assert Security::Price.exists?(offline_price.id)
+ assert Balance.exists?(balance.id)
+ assert Holding.exists?(holding.id)
+ end
+
+ test "still imports exchange rates and syncs every account when the price import fails" do
+ MarketDataImporter.any_instance.stubs(:import_security_prices).raises(StandardError, "provider down")
+ MarketDataImporter.any_instance.expects(:import_exchange_rates).once
+
+ assert_difference -> { DebugLogEntry.where(source: "MarketDataResetJob", level: "error").count }, 1 do
+ MarketDataResetJob.perform_now
+ end
+
+ assert_enqueued_jobs Account.count, only: SyncJob
+ end
+
+ test "enqueue_once queues one reset until it has run" do
+ use_own_guard_key
+ stub_imports
+
+ assert_enqueued_jobs 1, only: MarketDataResetJob do
+ assert_equal :queued, MarketDataResetJob.enqueue_once
+ assert_equal :already_queued, MarketDataResetJob.enqueue_once
+ end
+
+ perform_enqueued_jobs(only: MarketDataResetJob)
+ assert_enqueued_jobs 1, only: MarketDataResetJob do
+ assert_equal :queued, MarketDataResetJob.enqueue_once
+ end
+ ensure
+ clear_guard
+ end
+
+ test "a run that finds another reset running keeps the guard" do
+ use_own_guard_key
+ stub_imports
+ assert_equal :queued, MarketDataResetJob.enqueue_once
+ # A separate session: the test's own connection would re-enter its lock.
+ OtherSession.establish_connection(ActiveRecord::Base.connection_db_config)
+ begin
+ OtherSession.connection.select_value("SELECT pg_advisory_lock(#{MarketDataResetJob::ADVISORY_LOCK_KEY})")
+ perform_enqueued_jobs(only: MarketDataResetJob)
+ ensure
+ OtherSession.remove_connection
+ end
+
+ assert_equal :already_queued, MarketDataResetJob.enqueue_once
+ ensure
+ clear_guard
+ end
+
+ test "the guard is released after the advisory lock" do
+ use_own_guard_key
+ stub_imports
+ advisory_locks_at_release = []
+ MarketDataResetJob.stubs(:release_guard).with do
+ advisory_locks_at_release << ActiveRecord::Base.connection.select_value("SELECT count(*) FROM pg_locks WHERE locktype = 'advisory' AND pid = pg_backend_pid()")
+ true
+ end
+
+ MarketDataResetJob.perform_now
+
+ assert_equal [ 0 ], advisory_locks_at_release
+ end
+
+ test "a run that cannot check the advisory lock releases the guard" do
+ use_own_guard_key
+ assert_equal :queued, MarketDataResetJob.enqueue_once
+ MarketDataResetJob.any_instance.stubs(:try_advisory_lock).raises(ActiveRecord::ConnectionNotEstablished)
+
+ assert_raises(ActiveRecord::ConnectionNotEstablished) { perform_enqueued_jobs(only: MarketDataResetJob) }
+
+ assert_equal :queued, MarketDataResetJob.enqueue_once
+ ensure
+ clear_guard
+ end
+
+ test "a run stopped by a Sidekiq shutdown keeps the guard for the requeued job" do
+ use_own_guard_key
+ assert_equal :queued, MarketDataResetJob.enqueue_once
+ MarketDataImporter.any_instance.stubs(:import_security_prices).raises(Sidekiq::Shutdown)
+
+ assert_raises(Sidekiq::Shutdown) { perform_enqueued_jobs(only: MarketDataResetJob) }
+
+ assert_equal :already_queued, MarketDataResetJob.enqueue_once
+ ensure
+ clear_guard
+ end
+
+ test "a run does not release the guard of a reset queued after its own guard expired" do
+ use_own_guard_key
+ stub_imports
+ assert_equal :queued, MarketDataResetJob.enqueue_once
+ clear_guard
+ assert_equal :queued, MarketDataResetJob.enqueue_once
+
+ MarketDataResetJob.perform_now(enqueued_jobs.first[:args].first)
+
+ assert_equal :already_queued, MarketDataResetJob.enqueue_once
+ ensure
+ clear_guard
+ end
+
+ test "a deadlock in the deletes is retried and keeps the guard for the retry" do
+ use_own_guard_key
+ stub_imports
+ assert_equal :queued, MarketDataResetJob.enqueue_once
+ token = enqueued_jobs.first[:args].first
+ MarketDataResetJob.any_instance.stubs(:delete_security_prices).raises(ActiveRecord::Deadlocked)
+
+ assert_enqueued_with(job: MarketDataResetJob, args: [ token ]) do
+ MarketDataResetJob.perform_now(token)
+ end
+ assert_equal :already_queued, MarketDataResetJob.enqueue_once
+ ensure
+ clear_guard
+ end
+
+ test "a run without a token, queued before guards had one, still releases the guard" do
+ use_own_guard_key
+ stub_imports
+ Sidekiq.redis { |conn| conn.call("SET", MarketDataResetJob.guard_key, "1") }
+
+ MarketDataResetJob.perform_now
+
+ assert_equal :queued, MarketDataResetJob.enqueue_once
+ ensure
+ clear_guard
+ end
+
+ test "enqueue_once reports a failure instead of raising when the job or the guard cannot be written" do
+ use_own_guard_key
+ MarketDataResetJob.stubs(:perform_later).raises(RedisClient::CannotConnectError).then.returns(false).then.returns(MarketDataResetJob.new)
+
+ assert_equal :failed, MarketDataResetJob.enqueue_once
+ assert_equal :failed, MarketDataResetJob.enqueue_once
+ assert_equal :queued, MarketDataResetJob.enqueue_once
+ clear_guard
+
+ Sidekiq.stubs(:redis).raises(RedisClient::CannotConnectError)
+ assert_equal :failed, MarketDataResetJob.enqueue_once
+ ensure
+ Sidekiq.unstub(:redis)
+ clear_guard
+ end
+
+ private
+ # Parallel test processes share Redis, so each test guards its own key.
+ def use_own_guard_key
+ MarketDataResetJob.stubs(:guard_key).returns("market_data_reset_job:test:#{SecureRandom.hex(8)}")
+ end
+
+ def clear_guard
+ Sidekiq.redis { |conn| conn.call("DEL", MarketDataResetJob.guard_key) }
+ end
+
+ def stub_imports
+ MarketDataImporter.any_instance.stubs(:import_security_prices)
+ MarketDataImporter.any_instance.stubs(:import_exchange_rates)
+ end
+end