The personal finance app for everyone (by everyone)
Ruby
Page through SnapTrade account activities instead of stopping at 1000 (#5036)
arnaurodondev1d919f0894a7
diff --git a/app/models/provider/snaptrade.rb b/app/models/provider/snaptrade.rbindex 6c7fdd04dd..94d804acb7 100644--- a/app/models/provider/snaptrade.rb+++ b/app/models/provider/snaptrade.rb@@ -67,6 +67,12 @@ class Provider::Snaptrade# equity-like kinds added later still import rather than being dropped.UNSUPPORTED_INSTRUMENT_KINDS = %w[option future cfd].freeze+ # GET /accounts/{id}/activities returns at most 1000 rows per request.+ ACTIVITIES_PAGE_SIZE = 1000+ # Safety cap on activity pages per account (100k rows), so a server that+ # ignores offset can't loop forever.+ MAX_ACTIVITY_PAGES = 100+class << self# Some OAuth flow is available. The device flow needs nothing but the public# client id, so this is what gates syncing and the provider panel; only the@@ -388,12 +394,64 @@ class Provider::Snaptraderesults.reject { |position| unsupported_instrument?(position) }end- # Returns raw JSON: paginated form is {"data" => [...]}, may also be a plain Array+ # Returns raw JSON: paginated form is {"data" => [...]}, may also be a plain Array.+ #+ # The endpoint returns at most ACTIVITIES_PAGE_SIZE rows per request, so this+ # walks offset/limit until every page is fetched and returns the first page's+ # body with "data" holding all of them.def get_account_activities(account_id:, start_date: nil, end_date: nil)- params = {}+ params = { limit: ACTIVITIES_PAGE_SIZE }params[:startDate] = start_date.to_date.to_s if start_dateparams[:endDate] = end_date.to_date.to_s if end_date- get_json("/api/v1/accounts/#{account_id}/activities", params)+ path = "/api/v1/accounts/#{account_id}/activities"++ first_response = nil+ previous_first = nil+ first_page_size = nil+ known_total = nil+ activities = []++ MAX_ACTIVITY_PAGES.times do |page|+ response = get_json(path, params.merge(offset: activities.size))+ unless response.is_a?(Hash) && response["data"].is_a?(Array)+ return response if first_response.nil?+ # With rows still missing, a partial history would move the sync cursor past them.+ raise incomplete_activities_error(account_id, "SnapTrade activities page at offset #{activities.size} was not a paged response") if known_total+ break+ end++ first_response ||= response+ rows = response["data"]+ total = response.dig("pagination", "total")+ known_total = total if total.is_a?(Integer)++ # A server that ignores offset returns the same page again.+ if previous_first && rows.first == previous_first+ raise incomplete_activities_error(account_id, "SnapTrade activities repeated a page at offset #{activities.size}") if known_total && activities.size < known_total+ break+ end++ previous_first = rows.first+ activities.concat(rows)+ first_page_size ||= rows.size++ # Without a total, a page shorter than the first one is the last; the server may return fewer rows than asked.+ more = known_total ? activities.size < known_total : rows.size >= first_page_size+ raise incomplete_activities_error(account_id, "SnapTrade activities page at offset #{activities.size} was empty, total #{known_total}") if rows.empty? && more && page.positive?+ return first_response.merge("data" => activities) if rows.empty? || !more++ # Every page so far was full and distinct. With a total, rows are still missing; without one, they may be+ # (exactly 100 full pages also lands here). Either way, raise rather than move the cursor past them.+ if page == MAX_ACTIVITY_PAGES - 1+ raise incomplete_activities_error(+ account_id,+ "SnapTrade activities for account #{account_id} hit the page cap " \+ "(#{MAX_ACTIVITY_PAGES} pages, #{activities.size} rows, total #{known_total.inspect})"+ )+ end+ end++ first_response.merge("data" => activities)end# Cross-account activities endpoint. Returns Array<Hash>.@@ -522,6 +580,25 @@ class Provider::Snaptraderaiseend+ # Captured for support: the importer keeps the stored history and cursor+ # when the fetch fails, but would otherwise only log why.+ def incomplete_activities_error(account_id, message)+ capture_activities_log(account_id, message, level: :error)+ ApiError.new(message)+ end++ def capture_activities_log(account_id, message, level:)+ DebugLogEntry.capture(+ category: "provider_sync",+ level: level,+ message: message,+ source: "Provider::Snaptrade",+ provider_key: "snaptrade",+ family: snaptrade_item.try(:family),+ metadata: { snaptrade_item_id: snaptrade_item.try(:id), snaptrade_account_id: account_id }+ )+ end+def mark_requires_update!snaptrade_item.update!(status: :requires_update)rescue StandardError => ediff --git a/app/models/snaptrade_item/importer.rb b/app/models/snaptrade_item/importer.rbindex 0d0d4d057c..b4f0f5123f 100644--- a/app/models/snaptrade_item/importer.rb+++ b/app/models/snaptrade_item/importer.rb@@ -327,7 +327,9 @@ class SnaptradeItem::ImporterRails.logger.error "SnaptradeItem::Importer - Failed to fetch activities: #{e.class} - #{e.message}"Rails.logger.error e.backtrace.first(5).join("\n") if e.backtraceregister_error(e, context: "activities", account_id: snaptrade_account.id)- 0+ # nil, not 0: a fetch that failed is not SnapTrade still syncing, and+ # must not queue the background job to repeat it.+ nilendenddiff --git a/test/jobs/snaptrade_activities_fetch_job_test.rb b/test/jobs/snaptrade_activities_fetch_job_test.rbnew file mode 100644index 0000000000..c2cb108d31--- /dev/null+++ b/test/jobs/snaptrade_activities_fetch_job_test.rb@@ -0,0 +1,34 @@+require "test_helper"++class SnaptradeActivitiesFetchJobTest < ActiveJob::TestCase+ setup do+ @snaptrade_account = snaptrade_accounts(:fidelity_401k)+ @snaptrade_account.update!(activities_fetch_pending: true)+ @provider = mock("snaptrade_provider")+ SnaptradeItem.any_instance.stubs(:snaptrade_provider).returns(@provider)+ SnaptradeItem.any_instance.stubs(:broadcast_sync_complete)+ end++ # Provider::Snaptrade returns an empty first page as it is, even when its+ # total is positive, so a connection SnapTrade is still importing is polled.+ test "an empty result is fetched again later" do+ @provider.expects(:get_account_activities).returns({ "data" => [], "pagination" => { "total" => 50 } })++ assert_enqueued_with(job: SnaptradeActivitiesFetchJob) do+ SnaptradeActivitiesFetchJob.perform_now(@snaptrade_account, start_date: 1.year.ago.to_date)+ end+ assert @snaptrade_account.reload.activities_fetch_pending?+ end++ # A raised fetch ends the job without another attempt, which is why the+ # provider must not raise on that empty first page.+ test "a fetch that raises is not retried and clears the pending flag" do+ @provider.expects(:get_account_activities).raises(Provider::Snaptrade::ApiError.new("incomplete"))++ assert_no_enqueued_jobs(only: SnaptradeActivitiesFetchJob) do+ SnaptradeActivitiesFetchJob.perform_now(@snaptrade_account, start_date: 1.year.ago.to_date)+ end+ assert_not @snaptrade_account.reload.activities_fetch_pending?+ assert_nil @snaptrade_account.last_activities_sync+ end+enddiff --git a/test/models/provider/snaptrade_oauth_test.rb b/test/models/provider/snaptrade_oauth_test.rbindex f7f92cac07..65394d5298 100644--- a/test/models/provider/snaptrade_oauth_test.rb+++ b/test/models/provider/snaptrade_oauth_test.rb@@ -55,6 +55,27 @@ class Provider::SnaptradeOauthTest < ActiveSupport::TestCase}.to_jsonend+ # Each GET to the activities endpoint yields its own request and returns the+ # next page body. Returns the yielded requests so tests can inspect params.+ def stub_activity_pages(provider, pages)+ requests = []+ connection = mock("faraday")+ pages.each do |page|+ request = OpenStruct.new(headers: {}, params: {})+ requests << request+ connection.expects(:get)+ .with("#{Provider::Snaptrade::API_BASE_URL}/api/v1/accounts/acct-1/activities")+ .yields(request).returns(faraday_response(status: 200, body: page.to_json))+ .in_sequence(activity_sequence)+ end+ provider.stubs(:api_connection).returns(connection)+ requests+ end++ def activity_sequence+ @activity_sequence ||= sequence("activity pages")+ end+def faraday_response(status:, body:)OpenStruct.new(status: status, body: body, success?: (200..299).cover?(status))end@@ -205,6 +226,184 @@ class Provider::SnaptradeOauthTest < ActiveSupport::TestCaseassert_match "no results array", error.messageend+ test "get_account_activities follows offset pagination until every page is fetched" do+ configure_oauth!+ provider = Provider::Snaptrade.new(fake_item)++ first_page = Array.new(1000) { |i| { "id" => "a#{i}" } }+ second_page = [ { "id" => "a1000" }, { "id" => "a1001" } ]+ requests = stub_activity_pages(provider, [+ { data: first_page, pagination: { offset: 0, limit: 1000, total: 1002 } },+ { data: second_page, pagination: { offset: 1000, limit: 1000, total: 1002 } }+ ])++ response = provider.get_account_activities(account_id: "acct-1", start_date: Date.new(2024, 1, 1))++ assert_equal 1002, response["data"].size+ assert_equal %w[a0 a1001], [ response["data"].first["id"], response["data"].last["id"] ]+ assert_equal [ 0, 1000 ], requests.map { |r| r.params[:offset] }+ assert requests.all? { |r| r.params[:limit] == 1000 && r.params[:startDate] == "2024-01-01" }+ end++ test "get_account_activities makes a single request when one page holds everything" do+ configure_oauth!+ provider = Provider::Snaptrade.new(fake_item)++ requests = stub_activity_pages(provider, [+ { data: [ { "id" => "a0" }, { "id" => "a1" } ], pagination: { offset: 0, limit: 1000, total: 2 } }+ ])++ response = provider.get_account_activities(account_id: "acct-1")++ assert_equal %w[a0 a1], response["data"].map { |a| a["id"] }+ assert_equal 1, requests.size+ end++ test "get_account_activities raises when a later page is not a paged body" do+ configure_oauth!+ provider = Provider::Snaptrade.new(fake_item)++ stub_activity_pages(provider, [+ { data: Array.new(1000) { |i| { "id" => "a#{i}" } }, pagination: { offset: 0, limit: 1000, total: 1500 } },+ [ { "id" => "b0" } ]+ ])++ assert_raises(Provider::Snaptrade::ApiError) { provider.get_account_activities(account_id: "acct-1") }+ end++ test "get_account_activities stops when the server repeats a page" do+ configure_oauth!+ provider = Provider::Snaptrade.new(fake_item)++ page = { data: Array.new(1000) { |i| { "id" => "a#{i}" } } }+ requests = stub_activity_pages(provider, [ page, page ])++ assert_equal 1000, provider.get_account_activities(account_id: "acct-1")["data"].size+ assert_equal 2, requests.size+ end++ test "get_account_activities without a total pages until an empty page" do+ configure_oauth!+ provider = Provider::Snaptrade.new(fake_item)++ requests = stub_activity_pages(provider, [+ { data: Array.new(500) { |i| { "id" => "a#{i}" } } },+ { data: Array.new(500) { |i| { "id" => "b#{i}" } } },+ { data: [] }+ ])++ assert_equal 1000, provider.get_account_activities(account_id: "acct-1")["data"].size+ assert_equal [ 0, 500, 1000 ], requests.map { |r| r.params[:offset] }+ end++ test "get_account_activities without a total stops at a short page or an empty reply" do+ configure_oauth!+ provider = Provider::Snaptrade.new(fake_item)++ requests = stub_activity_pages(provider, [+ { data: Array.new(1000) { |i| { "id" => "a#{i}" } } },+ { data: Array.new(300) { |i| { "id" => "b#{i}" } } }+ ])+ assert_equal 1300, provider.get_account_activities(account_id: "acct-1")["data"].size+ assert_equal 2, requests.size++ provider = Provider::Snaptrade.new(fake_item)+ stub_activity_pages(provider, [ { data: Array.new(1000) { |i| { "id" => "c#{i}" } } }, {} ])+ assert_equal 1000, provider.get_account_activities(account_id: "acct-1")["data"].size+ end++ test "get_account_activities raises when a repeated page leaves rows the total reports" do+ configure_oauth!+ provider = Provider::Snaptrade.new(fake_item)++ page = { data: Array.new(1000) { |i| { "id" => "a#{i}" } }, pagination: { offset: 0, limit: 1000, total: 1500 } }+ stub_activity_pages(provider, [ page, page ])++ assert_raises(Provider::Snaptrade::ApiError) { provider.get_account_activities(account_id: "acct-1") }+ end++ test "get_account_activities raises when an empty page leaves rows the total reports" do+ configure_oauth!+ provider = Provider::Snaptrade.new(fake_item)++ stub_activity_pages(provider, [+ { data: Array.new(1000) { |i| { "id" => "a#{i}" } }, pagination: { offset: 0, limit: 1000, total: 1500 } },+ { data: [], pagination: { offset: 1000, limit: 1000, total: 1500 } }+ ])++ assert_difference -> { DebugLogEntry.where(provider_key: "snaptrade").count }, 1 do+ assert_raises(Provider::Snaptrade::ApiError) { provider.get_account_activities(account_id: "acct-1") }+ end+ end++ test "get_account_activities returns an empty account whose total is zero" do+ configure_oauth!+ provider = Provider::Snaptrade.new(fake_item)++ stub_activity_pages(provider, [ { data: [], pagination: { offset: 0, limit: 1000, total: 0 } } ])++ assert_equal [], provider.get_account_activities(account_id: "acct-1")["data"]+ end++ test "get_account_activities raises at the page cap while the total reports more rows" do+ configure_oauth!+ provider = Provider::Snaptrade.new(fake_item)++ pages = Array.new(3) do |page|+ { data: Array.new(2) { |i| { "id" => "p#{page}-#{i}" } }, pagination: { offset: page * 2, limit: 2, total: 100 } }+ end+ requests = stub_activity_pages(provider, pages)++ assert_difference -> { DebugLogEntry.where(provider_key: "snaptrade").count }, 1 do+ assert_raises(Provider::Snaptrade::ApiError) do+ stub_const(Provider::Snaptrade, :ACTIVITIES_PAGE_SIZE, 2) do+ stub_const(Provider::Snaptrade, :MAX_ACTIVITY_PAGES, 3) do+ provider.get_account_activities(account_id: "acct-1")+ end+ end+ end+ end+ assert_equal 3, requests.size+ end++ # Reaching the cap needs every page to be full and distinct, so rows are+ # almost certainly still missing; returning them would move the importer's+ # sync cursor past the rest.+ test "get_account_activities raises at the page cap without a total" do+ configure_oauth!+ provider = Provider::Snaptrade.new(fake_item)++ pages = Array.new(3) do |page|+ { data: Array.new(2) { |i| { "id" => "p#{page}-#{i}" } } }+ end+ requests = stub_activity_pages(provider, pages)++ assert_difference -> { DebugLogEntry.where(provider_key: "snaptrade", level: "error").count }, 1 do+ assert_raises(Provider::Snaptrade::ApiError) do+ stub_const(Provider::Snaptrade, :ACTIVITIES_PAGE_SIZE, 2) do+ stub_const(Provider::Snaptrade, :MAX_ACTIVITY_PAGES, 3) do+ provider.get_account_activities(account_id: "acct-1")+ end+ end+ end+ end+ assert_equal 3, requests.size+ end++ # An empty first page is how a new connection looks while SnapTrade is still+ # importing it. Raising would end SnaptradeActivitiesFetchJob's polling.+ test "get_account_activities returns an empty first page even when the total is positive" do+ configure_oauth!+ provider = Provider::Snaptrade.new(fake_item)++ requests = stub_activity_pages(provider, [ { data: [], pagination: { offset: 0, limit: 1000, total: 50 } } ])++ assert_no_difference -> { DebugLogEntry.count } do+ assert_equal [], provider.get_account_activities(account_id: "acct-1")["data"]+ end+ assert_equal 1, requests.size+ end+test "get_positions filters out instrument kinds the holdings pipeline cannot model" doconfigure_oauth!provider = Provider::Snaptrade.new(fake_item)diff --git a/test/models/snaptrade_item/importer_test.rb b/test/models/snaptrade_item/importer_test.rbindex 2ce222a52a..6a10858f26 100644--- a/test/models/snaptrade_item/importer_test.rb+++ b/test/models/snaptrade_item/importer_test.rb@@ -76,4 +76,32 @@ class SnaptradeItem::ImporterTest < ActiveSupport::TestCaseassert_equal [ "SnaptradeItem::Importer", "provider_sync", family, @snaptrade_account.account_provider, @snaptrade_account.id ],[ entry.source, entry.category, entry.family, entry.account_provider, entry.metadata["snaptrade_account_id"] ]end++ # An incomplete fetch (the provider's page cap or a missing page) raises, so+ # the stored history and its sync cursor stay as they were.+ test "a fetch that raises keeps the stored activities and the sync cursor" do+ synced_at = 2.days.ago.change(usec: 0)+ stored = Array.new(SnaptradeItem::Importer::MINIMUM_HISTORY_FOR_INCREMENTAL) { |i| { "id" => "a#{i}" } }+ @snaptrade_account.update!(raw_activities_payload: stored, last_activities_sync: synced_at)+ snaptrade_items(:configured_item).update!(last_synced_at: synced_at)+ @provider.stubs(:get_account_activities).raises(Provider::Snaptrade::ApiError.new("hit the page cap"))++ @importer.send(:import_activities, @snaptrade_account)++ @snaptrade_account.reload+ assert_equal stored, @snaptrade_account.raw_activities_payload+ assert_equal synced_at, @snaptrade_account.last_activities_sync+ end++ # A failed fetch is not SnapTrade still syncing: the job would repeat the+ # whole fetch (up to the page cap) only to fail the same way.+ test "a fresh account whose fetch raises is not flagged and queues no background fetch" do+ @provider.stubs(:get_account_activities).raises(Provider::Snaptrade::ApiError.new("hit the page cap"))++ assert_no_enqueued_jobs(only: SnaptradeActivitiesFetchJob) do+ @importer.send(:import_activities, @snaptrade_account)+ end++ assert_not @snaptrade_account.reload.activities_fetch_pending?+ endend