The personal finance app for everyone (by everyone)
Ruby
Let the browser reuse sidebar sparklines until they change (#4692)
Nikolay Kopylov972e11708d4c
diff --git a/app/controllers/accountable_sparklines_controller.rb b/app/controllers/accountable_sparklines_controller.rbindex 4127a6f0b3..6f029c431c 100644--- a/app/controllers/accountable_sparklines_controller.rb+++ b/app/controllers/accountable_sparklines_controller.rb@@ -1,92 +1,16 @@class AccountableSparklinesController < ApplicationControllerdef show@accountable = Accountable.from_type(params[:accountable_type]&.classify)+ sparkline = AccountableSparkline.new(@accountable)- etag_key = cache_key+ # A URL carrying the current version can't go stale, so the browser may reuse it.+ expires_in 1.day if params[:v] == sparkline.version# Use HTTP conditional GET so the client receives 304 Not Modified when possible.- if stale?(etag: etag_key, last_modified: family.latest_sync_completed_at)- @series = Rails.cache.fetch(etag_key, expires_in: 24.hours) do- build_series- end+ if stale?(etag: sparkline.cache_key, last_modified: Current.family.latest_sync_completed_at)+ @series = sparkline.seriesrender layout: falseendend-- private- def family- @family ||= Current.family- end-- # Same accounts the sidebar group total sums: accessible to the current- # user, visible, included in reports and counted in their finances (owned,- # or shared with include_in_finances).- def account_scope- @account_scope ||= Current.accessible_accounts- .visible- .included_in_reports- .included_in_finances_for(Current.user)- .where(accountable_type: @accountable.name)- end-- def account_ids- @account_ids ||= account_identity_rows.map(&:first).uniq- end-- def account_identity_rows- @account_identity_rows ||= account_scope- .left_outer_joins(:account_providers)- .pluck(:id, :plaid_account_id, :simplefin_account_id, Arel.sql("account_providers.id"))- end-- def build_series- return aggregate_normalized_series if requires_normalized_aggregation?-- Balance::ChartSeriesBuilder.new(- account_ids: account_ids,- currency: family.currency,- period: Period.last_30_days,- favorable_direction: @accountable.favorable_direction,- interval: "1 day"- ).balance_series- end-- # balance_type is derived purely from accountable_type, so only Investment/Crypto- # can yield :investment. Short-circuit to avoid an N+1 `account.linked?` check- # on every account for non-investment accountable types (loan, credit_card, etc).- # The `Account.linked` scope is the SQL-level mirror of `Account#linked?`.- def requires_normalized_aggregation?- return false unless %w[Investment Crypto].include?(@accountable.name)-- account_identity_rows.any? do |_account_id, plaid_account_id, simplefin_account_id, account_provider_id|- plaid_account_id.present? || simplefin_account_id.present? || account_provider_id.present?- end- end-- def aggregate_normalized_series- Balance::LinkedInvestmentSeriesNormalizer.aggregate_account_ids(- account_ids: account_ids,- currency: family.currency,- period: Period.last_30_days,- favorable_direction: @accountable.favorable_direction,- interval: "1 day"- )- end-- # The series is built from exactly these account rows, so the key carries a- # digest of them. A share count/timestamp version can stay the same while- # the counted set changes (ownership moved by update_all, shares replaced- # with older timestamps, report exclusion toggled); the row digest changes- # whenever the set does and never repeats for a different set.- def cache_key- family.build_cache_key(- "#{@accountable.name}_sparkline_#{Account::Chartable::SPARKLINE_CACHE_VERSION}_#{account_rows_digest}",- invalidate_on_data_updates: true- )- end-- def account_rows_digest- Digest::SHA256.hexdigest(account_identity_rows.map { |row| row.join(":") }.sort.join(","))- endenddiff --git a/app/controllers/accounts_controller.rb b/app/controllers/accounts_controller.rbindex 7eb9dc39f4..f1cb4f4073 100644--- a/app/controllers/accounts_controller.rb+++ b/app/controllers/accounts_controller.rb@@ -236,6 +236,8 @@ class AccountsController < ApplicationControllerdef sparkline# Short-circuit with 304 Not Modified when the client already has the latest version.# We defer the expensive series computation until we know the content is stale.+ # A URL carrying the current version can't go stale, so the browser may reuse it.+ expires_in 1.day if params[:v] == @account.sparkline_versionif stale?(etag: @account.sparkline_cache_key)@sparkline_series = @account.sparkline_seriesrender layout: falsediff --git a/app/helpers/accounts_helper.rb b/app/helpers/accounts_helper.rbindex ed35f62745..73f861b80c 100644--- a/app/helpers/accounts_helper.rb+++ b/app/helpers/accounts_helper.rb@@ -46,6 +46,16 @@ module AccountsHelper# Both are pulled in a single SQL round-trip via `pick`. Note: Rails# returns the values as Strings for raw SQL fragments — that's fine# since they only feed into a cache key (concat-stable, never coerced).+ # Versions for the sidebar's sparkline URLs, keyed by account id and by group+ # accountable, computed together rather than per account.+ def sidebar_sparkline_versions(family)+ @sidebar_sparkline_versions ||= begin+ groups = family.balance_sheet.account_groups+ Account.sparkline_versions(groups.flat_map(&:accounts).map(&:account))+ .merge(AccountableSparkline.versions(groups.map(&:accountable_type).uniq))+ end+ end+def account_sidebar_tabs_cache_key(family:, active_tab:, mobile:)shares_version =if Current.user@@ -55,13 +65,20 @@ module AccountsHelper"#{count}-#{max_at}"end+ # Linking or unlinking a provider doesn't touch the account, but changes its sparkline versions.+ providers_version = AccountProvider.where(account_id: family.accounts.select(:id))+ .pick(Arel.sql("count(*)"), Arel.sql("max(account_providers.updated_at)"))+[- family.build_cache_key("account_sidebar_tabs_v6", invalidate_on_data_updates: true),+ family.build_cache_key("account_sidebar_tabs_v7", invalidate_on_data_updates: true),Current.user&.id,shares_version,+ providers_version,active_tab,mobile,I18n.locale,+ # Sparkline URLs carry a version that rolls over with the 30-day window.+ Date.current,sidebar_active_account_id,# Fold the per-user "start expanded by default" preference into the key# so toggling it in Settings busts the 12h fragment cache immediatelydiff --git a/app/models/account/chartable.rb b/app/models/account/chartable.rbindex 12e7944ca2..357ccd7620 100644--- a/app/models/account/chartable.rb+++ b/app/models/account/chartable.rb@@ -36,18 +36,60 @@ module Account::Chartable# Investment series are normalized from holdings and entries that can change outside# this account's syncs, so those keep the family-wide sync timestamp.def sparkline_cache_key- @sparkline_cache_key ||= [+ @sparkline_cache_key ||= sparkline_cache_key_from(+ balances_version: self.class.rows_version(balances.pick(*self.class.rows_version_columns(Balance))),+ providers_version: self.class.rows_version(account_providers.pick(*self.class.rows_version_columns(AccountProvider))),+ last_synced_at: last_synced_at+ )+ end++ def sparkline_cache_key_from(balances_version:, providers_version:, last_synced_at:)+ ["account_sparkline", SPARKLINE_CACHE_VERSION, id, updated_at.to_f, last_synced_at&.to_f,- rows_version(balances), rows_version(account_providers), Date.current,+ balances_version, providers_version, Date.current,(family.latest_sync_completed_at&.to_f if balance_type == :investment)].join("_")end- private- def rows_version(scope)- scope.pick(Arel.sql("count(*)"), Arel.sql("max(#{scope.table_name}.updated_at)")).map { |v| v&.to_f }.join("-")+ # Changes whenever the sparkline does; the sidebar puts it in the frame URL.+ def sparkline_version+ self.class.sparkline_version_for(sparkline_cache_key)+ end++ class_methods do+ # #sparkline_version of many accounts from three grouped queries instead of three per account.+ def sparkline_versions(accounts)+ ids = accounts.map(&:id)+ balances = Balance.where(account_id: ids).group(:account_id).pluck(:account_id, *rows_version_columns(Balance))+ providers = AccountProvider.where(account_id: ids).group(:account_id).pluck(:account_id, *rows_version_columns(AccountProvider))+ balances = balances.to_h { |id, *version| [ id, rows_version(version) ] }+ providers = providers.to_h { |id, *version| [ id, rows_version(version) ] }+ synced = Sync.latest_completed_by_syncable(accounts)++ accounts.to_h do |account|+ key = account.sparkline_cache_key_from(+ balances_version: balances.fetch(account.id) { rows_version([ 0, nil ]) },+ providers_version: providers.fetch(account.id) { rows_version([ 0, nil ]) },+ last_synced_at: synced[[ account.class.base_class.name, account.id ]]&.completed_at+ )+ [ account.id, sparkline_version_for(key) ]+ end+ end++ def sparkline_version_for(cache_key)+ Digest::SHA256.hexdigest("#{cache_key}_#{I18n.locale}").first(16)+ end++ def rows_version_columns(model)+ [ Arel.sql("count(*)"), Arel.sql("max(#{model.table_name}.updated_at)") ]end+ def rows_version(count_and_max_updated_at)+ count_and_max_updated_at.map { |v| v&.to_f }.join("-")+ end+ end++ privatedef normalize_linked_investment_series(series, view: :balance)Balance::LinkedInvestmentSeriesNormalizer.new(account: self, series: series, view: view).normalizeenddiff --git a/app/models/accountable_sparkline.rb b/app/models/accountable_sparkline.rbnew file mode 100644index 0000000000..9b4a4901ae--- /dev/null+++ b/app/models/accountable_sparkline.rb@@ -0,0 +1,107 @@+# The sidebar sparkline of one account group, over the accounts the current user sees there.+class AccountableSparkline+ IDENTITY_COLUMNS = [ :id, :plaid_account_id, :simplefin_account_id, Arel.sql("account_providers.id") ].freeze++ # #version of several groups, reading their account rows in one query.+ def self.versions(accountables)+ rows = scope.where(accountable_type: accountables.map(&:name))+ .left_outer_joins(:account_providers)+ .pluck(:accountable_type, *IDENTITY_COLUMNS)+ .group_by(&:first)++ accountables.to_h do |accountable|+ identity_rows = rows.fetch(accountable.name, []).map { |row| row.drop(1) }+ [ accountable, new(accountable, account_identity_rows: identity_rows).version ]+ end+ end++ # Same accounts the sidebar group total sums: accessible to the current+ # user, visible, included in reports and counted in their finances (owned,+ # or shared with include_in_finances).+ def self.scope+ Current.accessible_accounts.visible.included_in_reports.included_in_finances_for(Current.user)+ end++ def initialize(accountable, account_identity_rows: nil)+ @accountable = accountable+ @account_identity_rows = account_identity_rows+ end++ def series+ Rails.cache.fetch(cache_key, expires_in: 24.hours) { build_series }+ end++ # Changes whenever the sparkline does; the sidebar puts it in the frame URL.+ def version+ Digest::SHA256.hexdigest("#{cache_key}_#{I18n.locale}").first(16)+ end++ # The series is built from exactly these account rows, so the key carries a+ # digest of them. A share count/timestamp version can stay the same while+ # the counted set changes (ownership moved by update_all, shares replaced+ # with older timestamps, report exclusion toggled); the row digest changes+ # whenever the set does and never repeats for a different set.+ def cache_key+ @cache_key ||= family.build_cache_key(+ "#{@accountable.name}_sparkline_#{Account::Chartable::SPARKLINE_CACHE_VERSION}_#{Date.current}_#{account_rows_digest}",+ invalidate_on_data_updates: true+ )+ end++ private+ def family+ @family ||= Current.family+ end++ def account_scope+ @account_scope ||= self.class.scope.where(accountable_type: @accountable.name)+ end++ def account_ids+ @account_ids ||= account_identity_rows.map(&:first).uniq+ end++ def account_identity_rows+ @account_identity_rows ||= account_scope+ .left_outer_joins(:account_providers)+ .pluck(*IDENTITY_COLUMNS)+ end++ def build_series+ return aggregate_normalized_series if requires_normalized_aggregation?++ Balance::ChartSeriesBuilder.new(+ account_ids: account_ids,+ currency: family.currency,+ period: Period.last_30_days,+ favorable_direction: @accountable.favorable_direction,+ interval: "1 day"+ ).balance_series+ end++ # balance_type is derived purely from accountable_type, so only Investment/Crypto+ # can yield :investment. Short-circuit to avoid an N+1 `account.linked?` check+ # on every account for non-investment accountable types (loan, credit_card, etc).+ # The `Account.linked` scope is the SQL-level mirror of `Account#linked?`.+ def requires_normalized_aggregation?+ return false unless %w[Investment Crypto].include?(@accountable.name)++ account_identity_rows.any? do |_account_id, plaid_account_id, simplefin_account_id, account_provider_id|+ plaid_account_id.present? || simplefin_account_id.present? || account_provider_id.present?+ end+ end++ def aggregate_normalized_series+ Balance::LinkedInvestmentSeriesNormalizer.aggregate_account_ids(+ account_ids: account_ids,+ currency: family.currency,+ period: Period.last_30_days,+ favorable_direction: @accountable.favorable_direction,+ interval: "1 day"+ )+ end++ def account_rows_digest+ Digest::SHA256.hexdigest(account_identity_rows.map { |row| row.join(":") }.sort.join(","))+ end+enddiff --git a/app/views/accounts/_account_sidebar_tabs.html.erb b/app/views/accounts/_account_sidebar_tabs.html.erbindex a7fb4dfae3..f044fe9011 100644--- a/app/views/accounts/_account_sidebar_tabs.html.erb+++ b/app/views/accounts/_account_sidebar_tabs.html.erb@@ -4,7 +4,7 @@ERB dependency tracker mis-parses as a bogus "Ds/D" template dependencyand then logs "Couldn't find template for digesting: Ds/D" on every cachemiss. The cache key is already manually versioned via- account_sidebar_tabs_cache_key ("account_sidebar_tabs_v6",+ account_sidebar_tabs_cache_key ("account_sidebar_tabs_v7",invalidate_on_data_updates: true), so we opt out of automatic templatedigesting. Bump that version suffix when changing this template or itssidebar dependencies. %>diff --git a/app/views/accounts/_accountable_group.html.erb b/app/views/accounts/_accountable_group.html.erbindex 61d9b7b09c..28668cf01a 100644--- a/app/views/accounts/_accountable_group.html.erb+++ b/app/views/accounts/_accountable_group.html.erb@@ -14,7 +14,7 @@<div class="ml-auto text-right grow"><%= tag.p format_money(account_group.total_money), class: "text-sm font-medium text-primary privacy-sensitive" %><%= turbo_frame_tag "#{account_group.key}_sparkline",- src: accountable_sparkline_path(account_group.key),+ src: accountable_sparkline_path(account_group.key, v: sidebar_sparkline_versions(Current.family)[account_group.accountable_type]),loading: "lazy",data: sparkline_frame_data do %><div class="flex items-center w-8 h-4 ml-auto">@@ -80,7 +80,7 @@<div class="ml-auto text-right grow h-10"><%= tag.p format_money(account.balance_money), class: "text-sm font-medium text-primary whitespace-nowrap privacy-sensitive" %><%= turbo_frame_tag dom_id(account, :sparkline),- src: sparkline_account_path(account),+ src: sparkline_account_path(account, v: sidebar_sparkline_versions(Current.family)[account.id]),loading: "lazy",data: sparkline_frame_data do %><div class="flex items-center w-8 h-4 ml-auto">diff --git a/test/controllers/accounts_controller_test.rb b/test/controllers/accounts_controller_test.rbindex abb2e5dd38..5c83ad3ea3 100644--- a/test/controllers/accounts_controller_test.rb+++ b/test/controllers/accounts_controller_test.rb@@ -1296,6 +1296,52 @@ class AccountsControllerTest < ActionDispatch::IntegrationTestassert_response :successend+ test "sidebar sparkline URLs carry a version the browser may reuse" do+ get account_url(@account)++ [ sidebar_sparkline_src(dom_id(@account, :sparkline)), sidebar_sparkline_src("depository_sparkline") ].each do |src|+ assert_match(/[?&]v=\h{16}\z/, src)+ get src+ assert_response :success+ assert_includes response.headers["Cache-Control"], "max-age=86400"+ end+ end++ test "a sparkline URL with an outdated version must be revalidated" do+ get sparkline_account_url(@account, v: "outdated")+ assert_response :success+ assert_includes response.headers["Cache-Control"], "max-age=0"++ get accountable_sparkline_url("depository", v: "outdated")+ assert_response :success+ assert_includes response.headers["Cache-Control"], "max-age=0"+ end++ test "a sidebar sparkline URL changes when the account's balances do" do+ get account_url(@account)+ before = sidebar_sparkline_src(dom_id(@account, :sparkline))++ travel 1.minute do+ @account.balances.create!(date: 40.days.ago.to_date, balance: 1, currency: @account.currency)+ get account_url(@account)+ end++ assert_not_equal before, sidebar_sparkline_src(dom_id(@account, :sparkline))+ end++ test "sidebar sparkline URLs change the next day" do+ get account_url(@account)+ before = [ sidebar_sparkline_src(dom_id(@account, :sparkline)), sidebar_sparkline_src("depository_sparkline") ]++ travel 1.day do+ get account_url(@account)+ after = [ sidebar_sparkline_src(dom_id(@account, :sparkline)), sidebar_sparkline_src("depository_sparkline") ]++ assert_not_equal before[0], after[0]+ assert_not_equal before[1], after[1]+ end+ end+test "sparkline renders an empty series without a trend" doempty_series = Series.new(start_date: 1.day.ago.to_date,@@ -1801,6 +1847,10 @@ class AccountsControllerTest < ActionDispatch::IntegrationTestendprivate+ def sidebar_sparkline_src(frame_id)+ css_select("turbo-frame##{frame_id}").first["src"]+ end+def logo_icon(key, source, size, name: nil, body: "\x89PNG".b)Account::LogoFetcher::Icon.new(key:, source:, name:, body:, size:, content_type: "image/png", extension: "png")enddiff --git a/test/helpers/accounts_helper_test.rb b/test/helpers/accounts_helper_test.rbindex 34dae77ed0..c00e4f5007 100644--- a/test/helpers/accounts_helper_test.rb+++ b/test/helpers/accounts_helper_test.rb@@ -63,6 +63,23 @@ class AccountsHelperTest < ActionView::TestCaseassert_not_equal before, sidebar_keyend+ test "sidebar cache key changes the next day" do+ before = sidebar_key++ travel 1.day do+ assert_not_equal before, sidebar_key+ end+ end++ test "sidebar cache key changes when a provider link is removed" do+ link = AccountProvider.create!(account: accounts(:depository), provider: plaid_accounts(:one))+ before = sidebar_key++ link.destroy!++ assert_not_equal before, sidebar_key+ end+privatedef sidebar_keyaccount_sidebar_tabs_cache_key(family: @user.family, active_tab: "all", mobile: false)diff --git a/test/models/account/chartable_test.rb b/test/models/account/chartable_test.rbindex 5cb9da0842..e485fd3aaa 100644--- a/test/models/account/chartable_test.rb+++ b/test/models/account/chartable_test.rb@@ -1,6 +1,15 @@require "test_helper"class Account::ChartableTest < ActiveSupport::TestCase+ test "batched sparkline versions match each account's own" do+ AccountProvider.create!(account: accounts(:depository), provider: plaid_accounts(:one))+ accounts(:depository).balances.create!(date: 400.days.ago.to_date, balance: 1, currency: "USD")+ Sync.create!(syncable: accounts(:depository), status: "completed", completed_at: 1.hour.ago)+ all = Account.all.to_a++ assert_equal all.to_h { [ _1.id, Account.find(_1.id).sparkline_version ] }, Account.sparkline_versions(all)+ end+test "generates series and memoizes" doaccount = accounts(:depository)diff --git a/test/system/sidebar_sparklines_test.rb b/test/system/sidebar_sparklines_test.rbindex 003acf3f20..8963b99477 100644--- a/test/system/sidebar_sparklines_test.rb+++ b/test/system/sidebar_sparklines_test.rb@@ -69,11 +69,34 @@ class SidebarSparklinesTest < ApplicationSystemTestCaseendAccountsController.prepend(BrokenSparklines)+ # The shared browser caches versioned sparkline URLs for a day, so salt the+ # versions per test or the stalled/broken responses below are never requested.+ module FreshSparklineVersions+ mattr_accessor :salt++ module AccountKey+ def sparkline_cache_key_from(...)+ "#{super}#{FreshSparklineVersions.salt}"+ end+ end++ module GroupKey+ def cache_key+ "#{super}#{FreshSparklineVersions.salt}"+ end+ end+ end+ Account.prepend(FreshSparklineVersions::AccountKey)+ AccountableSparkline.prepend(FreshSparklineVersions::GroupKey)+setup do+ FreshSparklineVersions.salt = SecureRandom.hex(4)@user = users(:family_admin)sign_in @userend+ teardown { FreshSparklineVersions.salt = nil }+test "a frame that is never fetched keeps its placeholder instead of a timeout badge" dowith_short_sparkline_timeout dovisit root_path