Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Cache Reports, serve them while they rebuild, and build the usual periods after each sync (#5404)

jezmore72740ce2cd4
diff --git a/.env.example b/.env.example
index ebf44a330e..13ea40d865 100644
--- a/.env.example
+++ b/.env.example
@@ -20,6 +20,16 @@ SECRET_KEY_BASE=secret-value
# Optional self-hosting vars
# --------------------------------------------------------------------------------------------------------
+# Optional: days a cached page (Reports) is kept when nobody opens it. Also
+# settable on the Self-Hosting page, like the two below.
+# PAGE_CACHE_DAYS=7
+# Optional: the most all cached pages may take together, in MB. The pages opened
+# longest ago are dropped first when it would be exceeded.
+# PAGE_CACHE_MAX_MB=100
+# Optional: after its data changes, a cached page is still shown while it is
+# rebuilt in the background, at most once in this many minutes (0: every change).
+# PAGE_CACHE_COOLDOWN_MINUTES=60
+
# Optional: OpenAI-compatible API endpoint config
OPENAI_ACCESS_TOKEN=
OPENAI_MODEL=
diff --git a/app/controllers/reports_controller.rb b/app/controllers/reports_controller.rb
index b837fdc951..50eb12aecb 100644
--- a/app/controllers/reports_controller.rb
+++ b/app/controllers/reports_controller.rb
@@ -3,6 +3,19 @@ class ReportsController < ApplicationController
SIGN_AGNOSTIC_EXPENSE_KINDS = %w[loan_payment investment_contribution].freeze
+ # Bump when the body's markup changes, so a deploy never serves the old one.
+ REPORT_BODY_CACHE_VERSION = 5
+ # Every parameter the body is built from, as a background rebuild repeats
+ # it and as part of the cache key: the period, the tag and entry filters
+ # and the breakdown's sort. Blank ones are dropped, so a default period
+ # keeps one key.
+ REPORT_BODY_PARAMS = %i[
+ period_type start_date end_date sort_by sort_direction filter_category_id filter_account_id
+ filter_amount_min filter_amount_max filter_date_start filter_date_end
+ ].freeze
+ # The views warmed after each sync, as their URLs carry them.
+ WARMED_PERIOD_TYPES = %i[monthly quarterly ytd last_6_months all_time].freeze
+
# Allow API key authentication for exports (for Google Sheets integration)
# Note: We run authentication_for_export which handles both session and API key auth
skip_authentication only: :export_transactions
@@ -10,11 +23,29 @@ class ReportsController < ApplicationController
helper_method :filter_tags
+ # The report body is served from PageCache: at once when a build exists, even
+ # one from before the latest data (it is rebuilt in the background then), and
+ # built while the member waits only the first time or on `refresh`.
def index
- setup_report_data(show_flash: true)
-
- # Build reports sections for collapsible/reorderable UI
- @reports_sections = build_reports_sections
+ setup_report_period(show_flash: true)
+ refresh = params[:refresh].present?
+ served = PageCache.serve(
+ report_body_cache_key,
+ version: report_body_version,
+ family: Current.family,
+ user: Current.user,
+ refresh: refresh,
+ rebuild_later: -> { RebuildReportJob.perform_later(Current.user, report_query, I18n.locale.to_s) }
+ ) { render_report_body }
+ # A refresh is rebuilt above; drop it from the URL so reloading doesn't
+ # rebuild again. A page too big to keep is shown as built instead, since
+ # the redirect would only build it a second time.
+ return redirect_to(reports_path(request.query_parameters.except("refresh"))) if refresh && served.kept
+
+ @report = served.body
+ @report_built_at = served.built_at
+ @report_stale = served.stale
+ @reports_sections = order_reports_sections(@report[:sections])
@breadcrumbs = [ [ t("breadcrumbs.home"), root_path ], [ t("breadcrumbs.reports"), nil ] ]
end
@@ -25,6 +56,35 @@ class ReportsController < ApplicationController
render layout: "print"
end
+ # Builds and caches the report body for `user` outside a request, so a
+ # background job can have it ready before anyone opens Reports. `query` is
+ # what the page's URL would carry (period_type, start_date, end_date,
+ # filter_tag_ids). Returns whether it had to build the body: one already
+ # built from the current data is left alone.
+ # `locale` is the one the cached build was made in, when a request chose it
+ # (a ?locale= or the browser's language); without it the member's own applies.
+ def self.warm_body_cache(user:, query: {}, locale: nil)
+ controller = new
+ url_query = locale.present? ? query.merge(locale: locale) : query
+ request = ActionDispatch::Request.new(Rack::MockRequest.env_for("/reports?#{url_query.to_query}"))
+ request.routes = _routes
+ controller.set_request!(request)
+ controller.set_response!(make_response!(request))
+
+ # Current memoizes the member's accounts, and Current.set doesn't clear
+ # that, so it is reset around each member: a job warming several members
+ # must never build one member's report from another's accounts. Only call
+ # this outside a request.
+ Current.reset
+ Current.session = Session.new(user: user)
+ # The member's locale and time zone, chosen as a request would choose them.
+ controller.send(:switch_locale) do
+ controller.send(:switch_timezone) { controller.send(:warm_report_body) }
+ end
+ ensure
+ Current.reset
+ end
+
def update_preferences
# `require` passes a scalar through, and indexing a String by key raises,
# so a body whose `preferences` is not an object is refused here.
@@ -106,7 +166,7 @@ class ReportsController < ApplicationController
end
private
- def setup_report_data(show_flash: false)
+ def setup_report_period(show_flash: false)
@period_type = params[:period_type]&.to_sym || :monthly
@start_date = parse_date_param(:start_date) || default_start_date
@end_date = parse_date_param(:end_date) || default_end_date
@@ -121,6 +181,13 @@ class ReportsController < ApplicationController
@tags = Current.family.tags.alphabetically
@filter_tags = filter_tags
+ # Build navigation links for period switching
+ @nav = build_period_navigation
+ end
+
+ def setup_report_data(show_flash: false)
+ setup_report_period(show_flash: show_flash)
+
# Get aggregated data
@income_statement = Current.family.income_statement(user: Current.user)
@current_income_totals = @income_statement.income_totals(period: @period)
@@ -155,9 +222,117 @@ class ReportsController < ApplicationController
# Flags for view rendering
@has_accounts = accessible_accounts.any?
+ end
- # Build navigation links for period switching
- @nav = build_period_navigation
+ # The report's figures, rendered: the exchange rate notes, the summary and
+ # each section's content. Section order, which are collapsed and the
+ # section frames are drawn when the page is served, so arranging the page
+ # never invalidates it.
+ def render_report_body
+ setup_report_data(show_flash: false)
+ html = ->(partial, locals) { render_to_string(partial: partial, locals: locals, formats: [ :html ]) }
+
+ {
+ notes: html.call("shared/exchange_rate_notes", { family: Current.family }),
+ has_transactions: Current.family.transactions.any?,
+ summary: html.call("reports/summary_dashboard", { metrics: @summary_metrics, period_type: @period_type }),
+ sections: build_reports_sections.map do |section|
+ section.except(:partial, :locals).merge(html: (html.call(section[:partial], section[:locals]) if section[:visible]))
+ end
+ }
+ end
+
+ def warm_report_body
+ setup_report_period(show_flash: false)
+ key = report_body_cache_key
+ version = report_body_version
+ return false if PageCache.current?(key, version: version, family: Current.family, user: Current.user)
+
+ started_at = Time.current
+ PageCache.write(key, render_report_body, version: version, family: Current.family, user: Current.user, started_at: started_at)
+ true
+ end
+
+ def report_query
+ query = params.permit(*REPORT_BODY_PARAMS, filter_tag_ids: []).to_h.symbolize_keys
+ query[:filter_tag_ids] = filter_tags.map(&:id).sort if filter_tags.any?
+ query.except!(:filter_tag_ids) if filter_tags.none?
+ # The page opens on this month when no period is given; naming it keeps one
+ # key for /reports and its warmed ?period_type=monthly build.
+ query[:period_type] = "monthly" if query[:period_type].blank?
+ query.compact_blank.sort.to_h
+ end
+
+ # Names the report whatever data it is built from: whose it is (family and
+ # member: PageCache also enforces both on every read), the
+ # member's settings that change its figures, and the period and filters as
+ # the URL gave them. A default period ("this year") keeps its key from one
+ # day to the next, so yesterday's build is served while today's is made.
+ #
+ # The accounts the member may see are part of the name, not the version: a
+ # build from before a change of access is never served, even stale, so a
+ # report can't show an account the member has just lost.
+ def report_body_cache_key
+ [
+ "reports_body", REPORT_BODY_CACHE_VERSION, Current.family.id, Current.user.id, report_member_version,
+ report_family_settings_version, I18n.locale,
+ report_access_digest, Digest::SHA256.hexdigest(report_query.to_query),
+ report_period_start_key
+ ].join("/")
+ end
+
+ # A default period starts afresh each month, quarter or year, and the new
+ # one is a different report, not a stale copy of the last, so its start is
+ # part of the name. The end date isn't, so "this year" keeps its build from
+ # one day to the next. All time's start moves whenever older history
+ # arrives; that build is replaced in the background, not while the member
+ # waits, so it's left out.
+ def report_period_start_key
+ @start_date unless @period_type == :all_time
+ end
+
+ def report_access_digest
+ Digest::SHA256.hexdigest([
+ accessible_accounts.map(&:id).sort.join(","),
+ Current.user.finance_accounts.pluck(:id).sort.join(",")
+ ].join("|"))
+ end
+
+ # The family's settings that change a report's figures or how it reads
+ # (currency is already in family.build_cache_key). Part of the key, not the
+ # version: a build made under other settings is never served.
+ def report_family_settings_version
+ family = Current.family
+ Digest::SHA256.hexdigest([
+ family.investment_contributions_as_spending, family.month_start_day, family.date_format,
+ family.household_budget_enabled, family.personal_budgets, family.moniker
+ ].join("|"))
+ end
+
+ # The member's settings that change a report's figures. Section order and
+ # collapse state are left out: they are applied when the page is served.
+ def report_member_version
+ user = Current.user
+ [ user.reports_biggest_expenses_limit, user.preview_features_enabled?, user.role ].join(",")
+ end
+
+ # Everything the body is drawn from: the family's data (a completed sync,
+ # any entry, category, tag or tagging, account or budget change), exchange
+ # rates, the dates the period resolves to and today's date. A build from a
+ # different version is served stale and rebuilt.
+ def report_body_version
+ family = Current.family
+ Digest::SHA256.hexdigest([
+ family.build_cache_key("reports_body", invalidate_on_data_updates: true),
+ family.entries_version,
+ family.tags_version,
+ family.holdings_version,
+ ExchangeRate.updated_at_version,
+ family.budgets.maximum(:updated_at)&.to_f,
+ BudgetCategory.joins(:budget).where(budgets: { family_id: family.id }).maximum(:updated_at)&.to_f,
+ accessible_accounts.map(&:updated_at).max&.to_f,
+ @start_date, @end_date, Date.current
+ ].join("|"))
end
def preferences_params
@@ -241,7 +416,12 @@ class ReportsController < ApplicationController
}
]
- # Order sections according to user preference
+ order_reports_sections(all_sections)
+ end
+
+ # Puts sections in the member's saved order. Kept apart from building them,
+ # so a cached report is reordered when served rather than rebuilt.
+ def order_reports_sections(all_sections)
section_order = Current.user.reports_section_order
ordered_sections = section_order.map do |key|
all_sections.find { |s| s[:key] == key }
diff --git a/app/controllers/settings/hostings_controller.rb b/app/controllers/settings/hostings_controller.rb
index b176af2692..71c77f2a59 100644
--- a/app/controllers/settings/hostings_controller.rb
+++ b/app/controllers/settings/hostings_controller.rb
@@ -295,6 +295,17 @@ class Settings::HostingsController < ApplicationController
Setting.jev_model = hosting_params[:jev_model].presence
end
+ Setting::PAGE_CACHE_SETTINGS.each do |key, (range, _default)|
+ next unless hosting_params.key?(key) && Setting.page_cache_env_value(key).nil?
+
+ raw = hosting_params[key].to_s.strip
+ value = raw.presence && (Integer(raw, 10) rescue nil)
+ if raw.present? && !range.cover?(value)
+ raise Setting::ValidationError, t(".invalid_#{key}", minimum: range.min, maximum: range.max)
+ end
+ Setting.public_send("#{key}=", value)
+ end
+
LLM_NUMERIC_MINIMUMS.each do |key, minimum|
next unless hosting_params.key?(key)
raw = hosting_params[key].to_s.strip
@@ -369,7 +380,7 @@ class Settings::HostingsController < ApplicationController
# Strong parameters for the self-hosting settings form.
def hosting_params
return ActionController::Parameters.new unless params.key?(:setting)
- params.require(:setting).permit(:onboarding_state, :require_email_confirmation, :invite_only_default_family_id, :demo_family_refresh_enabled, :demo_family_refresh_family_id, :brand_fetch_client_id, :brand_fetch_high_res_logos, :twelve_data_api_key, :tiingo_api_key, :eodhd_api_key, :alpha_vantage_api_key, :tinkoff_invest_api_key, :mansa_api_key, :rentcast_api_key, :realie_api_key, :chimnie_api_key, :terrascoutx_api_key, :openai_access_token, :openai_uri_base, :openai_model, :openai_json_mode, :anthropic_access_token, :anthropic_base_url, :anthropic_model, :jev_api_key, :jev_endpoint, :jev_model, :llm_provider, :llm_context_window, :llm_max_response_tokens, :llm_max_items_per_call, :openai_request_timeout, :ai_response_timeout, :ai_health_probe_timeout, :exchange_rate_provider, :securities_provider, :syncs_include_pending, :auto_sync_enabled, :auto_sync_time, :market_data_sync_enabled, :market_data_sync_time, :external_assistant_url, :external_assistant_token, :external_assistant_model, securities_providers: [])
+ params.require(:setting).permit(:onboarding_state, :require_email_confirmation, :invite_only_default_family_id, :demo_family_refresh_enabled, :demo_family_refresh_family_id, :brand_fetch_client_id, :brand_fetch_high_res_logos, :twelve_data_api_key, :tiingo_api_key, :eodhd_api_key, :alpha_vantage_api_key, :tinkoff_invest_api_key, :mansa_api_key, :rentcast_api_key, :realie_api_key, :chimnie_api_key, :terrascoutx_api_key, :openai_access_token, :openai_uri_base, :openai_model, :openai_json_mode, :anthropic_access_token, :anthropic_base_url, :anthropic_model, :jev_api_key, :jev_endpoint, :jev_model, :llm_provider, :llm_context_window, :llm_max_response_tokens, :llm_max_items_per_call, :openai_request_timeout, :ai_response_timeout, :ai_health_probe_timeout, :exchange_rate_provider, :securities_provider, :syncs_include_pending, :auto_sync_enabled, :auto_sync_time, :market_data_sync_enabled, :market_data_sync_time, :page_cache_days, :page_cache_max_mb, :page_cache_cooldown_minutes, :external_assistant_url, :external_assistant_token, :external_assistant_model, securities_providers: [])
end
def load_external_assistant_models
diff --git a/app/jobs/apply_rules_job.rb b/app/jobs/apply_rules_job.rb
index 0d64356a8a..854f4202dc 100644
--- a/app/jobs/apply_rules_job.rb
+++ b/app/jobs/apply_rules_job.rb
@@ -6,11 +6,15 @@ class ApplyRulesJob < ApplicationJob
# A failing rule is recorded as a failed RuleRun and the remaining rules still
# run. The job itself does not fail, because a retry would re-run every rule.
- def perform(family, execution_type: "scheduled")
+ # `warm_reports` (after a sync) builds the usual Reports views once the
+ # rules are done, so they aren't cached from entries the rules still change.
+ def perform(family, execution_type: "scheduled", warm_reports: false)
Rule::Runner.new(
family,
rules: family.rules.where(active: true),
execution_type: execution_type
).run
+
+ WarmReportsCacheJob.perform_later(family) if warm_reports
end
end
diff --git a/app/jobs/rebuild_report_job.rb b/app/jobs/rebuild_report_job.rb
new file mode 100644
index 0000000000..9cb1e858f8
--- /dev/null
+++ b/app/jobs/rebuild_report_job.rb
@@ -0,0 +1,11 @@
+# Rebuilds one member's Reports view whose cached build is from older data,
+# while they keep seeing that build. Queued by ReportsController#index through
+# PageCache, at most once per cooldown.
+class RebuildReportJob < ApplicationJob
+ queue_as :low_priority
+
+ # `locale` keeps the rebuild in the language the stale build was made in.
+ def perform(user, query, locale = nil)
+ ReportsController.warm_body_cache(user: user, query: query, locale: locale)
+ end
+end
diff --git a/app/jobs/warm_reports_cache_job.rb b/app/jobs/warm_reports_cache_job.rb
new file mode 100644
index 0000000000..2bd5eaa9d4
--- /dev/null
+++ b/app/jobs/warm_reports_cache_job.rb
@@ -0,0 +1,17 @@
+# Builds the Reports views each member most often opens, so they are cached
+# before anyone asks. ApplyRulesJob enqueues it after a family sync, once the
+# sync's rules have run.
+class WarmReportsCacheJob < ApplicationJob
+ queue_as :low_priority
+
+ def perform(family)
+ family.users.find_each do |user|
+ ReportsController::WARMED_PERIOD_TYPES.each do |period_type|
+ ReportsController.warm_body_cache(user: user, query: { period_type: period_type })
+ rescue StandardError => e
+ # One view failing to build leaves it to be built when opened; the rest still warm.
+ Rails.logger.warn("[WarmReportsCacheJob] #{period_type} for user #{user.id} failed: #{e.class}: #{e.message}")
+ end
+ end
+ end
+end
diff --git a/app/models/family.rb b/app/models/family.rb
index d6fe91ebd5..b8de3d04e2 100644
--- a/app/models/family.rb
+++ b/app/models/family.rb
@@ -755,6 +755,15 @@ class Family < ApplicationRecord
"#{tag_count}-#{tag_max_at&.to_f}-#{tagging_count}-#{tagging_max_at&.to_f}"
end
+ # Editing a holding (its manual cost basis, or unlocking it) changes
+ # neither its account nor any entry, so caches whose results depend on
+ # holdings, such as the Reports body's gains, key on this too. The count
+ # catches a removed holding.
+ def holdings_version
+ count, max_at = holdings.pick(Arel.sql("count(*)"), Arel.sql('max("holdings"."updated_at")'))
+ "#{count}-#{max_at&.to_f}"
+ end
+
# Used for invalidating caches keyed on recurring transactions (e.g. the
# transactions index's projected recurring list). See #entries_version for
# why .count is included alongside the timestamp.
diff --git a/app/models/family/syncer.rb b/app/models/family/syncer.rb
index 6d98712604..c5bb12cf51 100644
--- a/app/models/family/syncer.rb
+++ b/app/models/family/syncer.rb
@@ -24,7 +24,7 @@ class Family::Syncer
family.backfill_provider_merchant_logos
Rails.logger.info("Applying rules for family #{family.id}")
- ApplyRulesJob.perform_later(family)
+ ApplyRulesJob.perform_later(family, warm_reports: true)
end
# Every `*_items` association whose model is Syncable, found by reflection
diff --git a/app/models/financekit/downstream.rb b/app/models/financekit/downstream.rb
index 1c00e2be83..4b125da02c 100644
--- a/app/models/financekit/downstream.rb
+++ b/app/models/financekit/downstream.rb
@@ -51,7 +51,7 @@ class Financekit::Downstream
# Anything failing after it is the publisher's, so drop the attribution.
account_provider = nil
@item.family.auto_match_transfers!
- ApplyRulesJob.perform_later(@item.family)
+ ApplyRulesJob.perform_later(@item.family, warm_reports: true)
FinancekitBatch.where(id: pending)
.update_all(downstream_completed_at: completed_at, updated_at: completed_at)
diff --git a/app/models/page_cache.rb b/app/models/page_cache.rb
new file mode 100644
index 0000000000..14b32c611c
--- /dev/null
+++ b/app/models/page_cache.rb
@@ -0,0 +1,251 @@
+# Pages that are slow to build (today the Reports body), kept in Rails.cache
+# and served stale while a newer version is built in the background.
+#
+# Each page is stored under a key that names the page (whose, which period and
+# filters), together with the `version` of the data it was built from. When the
+# data has moved on, the stored page is still served at once, marked stale, and
+# a rebuild is queued, no sooner than Setting.page_cache_cooldown after the last
+# build of that page finished, whether or not it was kept. Only a
+# page that was never built, or an explicit refresh, is built while the member
+# waits.
+#
+# A page belongs to one member of one family, and that is enforced, not assumed:
+# it is encrypted with a key derived for its family from SECRET_KEY_BASE and
+# bound to its cache key, and carries its family and member ids, which are
+# checked on every read. A page that doesn't decrypt with the reader's family
+# key, or names anyone else, is treated as missing. Nothing readable is stored
+# in the cache, and PageCacheEntry holds only keys, sizes and times.
+#
+# A PageCacheEntry records each page's size and last use, so the pages are held
+# under Setting.page_cache_max_mb together: when a new page would go over it,
+# the pages served longest ago are dropped first. A page bigger than the whole
+# limit is served but never kept.
+#
+# Replacing a page and renewing its expiry hold a lock on its key, so a slower,
+# older build or a renewal can never put back a page that was just replaced.
+# Under the lock the page is read from the shared store, not from what Rails'
+# per-request local cache kept from earlier in the request.
+class PageCache
+ # `kept` is whether the page is in the cache after serving it.
+ Served = Data.define(:body, :built_at, :stale, :kept)
+
+ # A served page records its use at most this often, so reading the cache
+ # doesn't mean a write on every page view.
+ TOUCH_INTERVAL = 1.hour
+ # How long a queued rebuild holds its claim; a job that dies frees it then.
+ REBUILD_CLAIM_TTL = 30.minutes
+ PAGE_LOCK_NAMESPACE = 4015
+
+ class << self
+ # `rebuild_later` queues the background rebuild; it is called only when the
+ # stored page is stale, past its cooldown and no rebuild is claimed yet.
+ def serve(key, version:, family:, user:, rebuild_later:, refresh: false)
+ entry = read(key, family: family, user: user) unless refresh
+
+ if entry.nil?
+ started_at = Time.current
+ body = yield
+ kept = write(key, body, version: version, family: family, user: user, started_at: started_at)
+ return Served.new(body: body, built_at: Time.current, stale: false, kept: kept)
+ end
+
+ stale = entry[:version] != version
+ if stale && entry[:built_at] <= Setting.page_cache_cooldown.ago && !cooling_down?(key) && claim_rebuild(key)
+ queue_rebuild(key, rebuild_later)
+ end
+
+ Served.new(body: entry[:body], built_at: entry[:built_at], stale: stale, kept: true)
+ end
+
+ def current?(key, version:, family:, user:)
+ read(key, family: family, user: user, touch: false)&.dig(:version) == version
+ end
+
+ # Returns whether the page was kept. `started_at` is when its build began:
+ # a build that began before the stored page's did is from older data, so a
+ # slow builder finishing last never replaces a newer page.
+ def write(key, body, version:, family:, user:, started_at: Time.current)
+ release_rebuild(key)
+ start_cooldown(key)
+ kept = with_page_lock(key) do
+ stored = read(key, family: family, user: user, touch: false, shared: true)
+ next false if stored && stored[:started_at] > started_at
+
+ entry = {
+ family_id: family.id, user_id: user.id, version: version,
+ started_at: started_at.iso8601(6), built_at: Time.current.iso8601(6), body: body
+ }
+ sealed = encryptor_for(family).encrypt_and_sign(entry, purpose: key)
+ bytes = sealed.bytesize
+
+ # Too big to keep: not stored, and an earlier build of this page stays.
+ # It is still served (stale) rather than leaving the next visitor to
+ # wait for a build.
+ next false if bytes > max_bytes
+
+ next false unless Rails.cache.write(key, sealed, expires_in: Setting.page_cache_ttl)
+
+ PageCacheEntry.upsert(
+ { page_key: key, family_id: family.id, bytes: bytes, last_used_at: Time.current },
+ unique_by: :page_key
+ )
+ true
+ end
+
+ evict_to_fit if kept
+ kept
+ end
+
+ def total_bytes
+ PageCacheEntry.sum(:bytes)
+ end
+
+ def max_bytes
+ Setting.page_cache_max_mb_in_effect.megabytes
+ end
+
+ private
+ def read(key, family:, user:, touch: true, shared: false)
+ sealed = shared ? read_shared(key) : Rails.cache.read(key)
+ entry = unseal(sealed, key: key, family: family)
+ return unless entry && entry[:family_id] == family.id && entry[:user_id] == user.id
+
+ touch(key, sealed) if touch
+ entry.merge(
+ built_at: Time.zone.parse(entry[:built_at]),
+ started_at: entry[:started_at] ? Time.zone.parse(entry[:started_at]) : Time.zone.parse(entry[:built_at])
+ )
+ end
+
+ # Records the use, at most once per TOUCH_INTERVAL, and renews the cache
+ # store's expiry with it: a page kept "for N days unopened" must not
+ # expire N days after it was built while it is still being opened. The
+ # store can only renew by writing the page again, so that happens only
+ # while the page read is still the one stored.
+ def touch(key, sealed)
+ touched = PageCacheEntry.where(page_key: key, last_used_at: ...TOUCH_INTERVAL.ago).update_all(last_used_at: Time.current)
+ return unless touched.positive?
+
+ with_page_lock(key) do
+ Rails.cache.write(key, sealed, expires_in: Setting.page_cache_ttl) if read_shared(key) == sealed
+ end
+ end
+
+ # Another process may have replaced the page since this request first read
+ # it, so the store itself is read: an empty local cache for the read forgets
+ # what this request kept, and stores without one read the store anyway.
+ def read_shared(key)
+ return Rails.cache.read(key) unless Rails.cache.respond_to?(:with_local_cache)
+
+ Rails.cache.with_local_cache { Rails.cache.read(key) }
+ end
+
+ # Held until the transaction ends, by every process sharing the database.
+ def with_page_lock(key)
+ PageCacheEntry.transaction do
+ PageCacheEntry.connection.execute(
+ PageCacheEntry.sanitize_sql_array([ "SELECT pg_advisory_xact_lock(?, hashtext(?))", PAGE_LOCK_NAMESPACE, key ])
+ )
+ yield
+ end
+ end
+
+ # A rebuild that can't be queued leaves the stale page served and the
+ # claim released, so the next visit tries again.
+ def queue_rebuild(key, rebuild_later)
+ rebuild_later.call
+ rescue StandardError => e
+ release_rebuild(key)
+ Rails.logger.error("[PageCache] could not queue a rebuild of #{key}: #{e.class}: #{e.message}")
+ end
+
+ def unseal(sealed, key:, family:)
+ return unless sealed.is_a?(String)
+
+ encryptor_for(family).decrypt_and_verify(sealed, purpose: key)
+ rescue ActiveSupport::MessageEncryptor::InvalidMessage, ActiveSupport::MessageVerifier::InvalidSignature
+ nil
+ end
+
+ def encryptor_for(family)
+ key = Rails.application.key_generator.generate_key("page_cache/#{family.id}", 32)
+ ActiveSupport::MessageEncryptor.new(key, serializer: CompressedJson)
+ end
+
+ def claim_rebuild(key)
+ Rails.cache.write(rebuild_claim_key(key), true, unless_exist: true, expires_in: REBUILD_CLAIM_TTL)
+ end
+
+ def release_rebuild(key)
+ Rails.cache.delete(rebuild_claim_key(key))
+ end
+
+ def rebuild_claim_key(key)
+ "#{key}/rebuilding"
+ end
+
+ # A build that isn't kept (too big, or older than the stored page) leaves
+ # the stored page's built_at as it was, so the cooldown is also counted
+ # from when the last build finished. A cooldown of 0 never holds one back.
+ def start_cooldown(key)
+ cooldown = Setting.page_cache_cooldown
+ Rails.cache.write(rebuild_cooldown_key(key), true, expires_in: cooldown) if cooldown.positive?
+ end
+
+ def cooling_down?(key)
+ Rails.cache.exist?(rebuild_cooldown_key(key))
+ end
+
+ def rebuild_cooldown_key(key)
+ "#{key}/rebuilt"
+ end
+
+ def evict_to_fit
+ forget(PageCacheEntry.where(last_used_at: ...Setting.page_cache_ttl.ago))
+
+ # A page renewed or replaced since it was chosen is skipped, so choose
+ # again from what remains until the cache fits or nothing is left to drop.
+ tried = []
+ while (excess = total_bytes - max_bytes).positive?
+ freed = 0
+ chosen = PageCacheEntry.where.not(id: tried).order(:last_used_at).pluck(:id, :page_key, :bytes, :last_used_at).take_while do |_, _, bytes, _|
+ (freed < excess).tap { freed += bytes }
+ end
+ break if chosen.empty?
+
+ forget_rows(chosen)
+ tried.concat(chosen.map(&:first))
+ end
+ end
+
+ def forget(entries)
+ forget_rows(entries.pluck(:id, :page_key, :bytes, :last_used_at))
+ end
+
+ # Each page is dropped under its lock, and only if its entry is still the
+ # one chosen: a page replaced meanwhile keeps its new copy and its entry.
+ def forget_rows(rows)
+ rows.each do |id, key, bytes, last_used_at|
+ with_page_lock(key) do
+ next unless PageCacheEntry.where(id: id, bytes: bytes, last_used_at: last_used_at).delete_all.positive?
+
+ Rails.cache.delete(key)
+ end
+ end
+ end
+ end
+
+ # Compressed before it is encrypted: the cache store's own compression can't
+ # shrink ciphertext, and a page's HTML compresses about tenfold. JSON rather
+ # than Marshal, so loading a page can never run code; keys come back as
+ # symbols, and times are stored as ISO 8601 strings.
+ module CompressedJson
+ def self.dump(value)
+ Zlib::Deflate.deflate(JSON.generate(value))
+ end
+
+ def self.load(data)
+ JSON.parse(Zlib::Inflate.inflate(data)).deep_symbolize_keys
+ end
+ end
+end
diff --git a/app/models/page_cache_entry.rb b/app/models/page_cache_entry.rb
new file mode 100644
index 0000000000..75c8f3573e
--- /dev/null
+++ b/app/models/page_cache_entry.rb
@@ -0,0 +1,5 @@
+# One page kept by PageCache: where it is in Rails.cache, how big it is and
+# when it was last served, so the cache can be held under its size limit.
+class PageCacheEntry < ApplicationRecord
+ belongs_to :family
+end
diff --git a/app/models/setting.rb b/app/models/setting.rb
index 60b1167783..abbe684140 100644
--- a/app/models/setting.rb
+++ b/app/models/setting.rb
@@ -259,6 +259,57 @@ class Setting < RailsSettings::Base
# config/schedule.yml entry (22:00 UTC, ~1h after NYSE close) so existing
# installations see no behavior change unless they actively reconfigure it.
field :market_data_sync_enabled, type: :boolean, default: ENV.fetch("MARKET_DATA_SYNC_ENABLED", "1") == "1"
+
+ # The page cache (see PageCache). Each value comes from its environment
+ # variable when that is set and in range, else from the Self-Hosting form,
+ # else the default; an out-of-range value from either is ignored.
+ #
+ # How long a cached page is kept when nobody opens it.
+ PAGE_CACHE_DAYS_DEFAULT = 7
+ PAGE_CACHE_DAYS_RANGE = 1..365
+ field :page_cache_days, type: :integer
+ # The most all cached pages may take together, in megabytes.
+ PAGE_CACHE_MAX_MB_DEFAULT = 100
+ PAGE_CACHE_MAX_MB_RANGE = 1..100_000
+ field :page_cache_max_mb, type: :integer
+ # After its data changes, a cached page is still served while it is rebuilt
+ # in the background, but rebuilt at most once in this many minutes. 0
+ # rebuilds on the first visit after every change.
+ PAGE_CACHE_COOLDOWN_MINUTES_DEFAULT = 60
+ PAGE_CACHE_COOLDOWN_MINUTES_RANGE = 0..10_080
+ field :page_cache_cooldown_minutes, type: :integer
+
+ PAGE_CACHE_SETTINGS = {
+ page_cache_days: [ PAGE_CACHE_DAYS_RANGE, PAGE_CACHE_DAYS_DEFAULT ],
+ page_cache_max_mb: [ PAGE_CACHE_MAX_MB_RANGE, PAGE_CACHE_MAX_MB_DEFAULT ],
+ page_cache_cooldown_minutes: [ PAGE_CACHE_COOLDOWN_MINUTES_RANGE, PAGE_CACHE_COOLDOWN_MINUTES_DEFAULT ]
+ }.freeze
+
+ def self.page_cache_value(name)
+ range, default = PAGE_CACHE_SETTINGS.fetch(name)
+ page_cache_env_value(name) || [ public_send(name) ].find { |value| value && range.cover?(value) } || default
+ end
+
+ # The environment's value when it is a usable override (a whole number in
+ # range), else nil: an invalid one is ignored, so it neither applies nor
+ # locks the setting.
+ def self.page_cache_env_value(name)
+ range, _default = PAGE_CACHE_SETTINGS.fetch(name)
+ from_env = Integer(ENV[name.to_s.upcase].to_s.strip, 10, exception: false)
+ from_env if from_env && range.cover?(from_env)
+ end
+
+ def self.page_cache_ttl
+ page_cache_value(:page_cache_days).days
+ end
+
+ def self.page_cache_max_mb_in_effect
+ page_cache_value(:page_cache_max_mb)
+ end
+
+ def self.page_cache_cooldown
+ page_cache_value(:page_cache_cooldown_minutes).minutes
+ end
field :market_data_sync_time, type: :string, default: ENV.fetch("MARKET_DATA_SYNC_TIME", "22:00")
field :market_data_sync_timezone, type: :string, default: ENV.fetch("MARKET_DATA_SYNC_TIMEZONE", "UTC")
diff --git a/app/views/reports/_body.html.erb b/app/views/reports/_body.html.erb
new file mode 100644
index 0000000000..6e3330d780
--- /dev/null
+++ b/app/views/reports/_body.html.erb
@@ -0,0 +1,24 @@
+<%# locals: (report:, sections:) %>
+<%# `report` is ReportsController#render_report_body, usually from the cache. %>
+<div class="w-full space-y-6 lg:pb-6">
+ <%= report[:notes].html_safe %>
+
+ <% if report[:has_transactions] %>
+ <%# Summary Dashboard - Always visible, not collapsible %>
+ <section class="@container">
+ <%= report[:summary].html_safe %>
+ </section>
+
+ <%# Collapsible & Reorderable Sections %>
+ <%= render "shared/reorderable_sections",
+ sections: sections,
+ namespace: "reports",
+ url: update_preferences_reports_path,
+ i18n_scope: "reports.index" %>
+ <% else %>
+ <%# Empty State %>
+ <section>
+ <%= render partial: "reports/empty_state" %>
+ </section>
+ <% end %>
+</div>
diff --git a/app/views/reports/index.html.erb b/app/views/reports/index.html.erb
index 4947f6cd4d..057272cc4e 100644
--- a/app/views/reports/index.html.erb
+++ b/app/views/reports/index.html.erb
@@ -159,31 +159,18 @@
</div>
</div>
<% end %>
+
+ <%# When the report was built. A stale one is being rebuilt in the
+ background; Refresh rebuilds it now, while the member waits. %>
+ <div class="flex items-center gap-2 text-xs text-secondary" data-testid="report-built-at">
+ <span><%= t("reports.index.built_at", time: time_ago_in_words(@report_built_at)) %></span>
+ <% if @report_stale %>
+ <span>· <%= t("reports.index.updating") %></span>
+ <% end %>
+ <span aria-hidden="true">·</span>
+ <%= render DS::Link.new(text: t("reports.index.refresh"), href: reports_path(request.query_parameters.merge(refresh: 1))) %>
+ </div>
</div>
<% end %>
-<div class="w-full space-y-6 lg:pb-6">
- <%= render "shared/exchange_rate_notes", family: Current.family %>
-
- <% if Current.family.transactions.any? %>
- <%# Summary Dashboard - Always visible, not collapsible %>
- <section class="@container">
- <%= render partial: "reports/summary_dashboard", locals: {
- metrics: @summary_metrics,
- period_type: @period_type
- } %>
- </section>
-
- <%# Collapsible & Reorderable Sections %>
- <%= render "shared/reorderable_sections",
- sections: @reports_sections,
- namespace: "reports",
- url: update_preferences_reports_path,
- i18n_scope: "reports.index" %>
- <% else %>
- <%# Empty State %>
- <section>
- <%= render partial: "reports/empty_state" %>
- </section>
- <% end %>
-</div>
+<%= render "reports/body", report: @report, sections: @reports_sections %>
diff --git a/app/views/settings/hostings/_page_cache_setting.html.erb b/app/views/settings/hostings/_page_cache_setting.html.erb
new file mode 100644
index 0000000000..e6d0b68e0d
--- /dev/null
+++ b/app/views/settings/hostings/_page_cache_setting.html.erb
@@ -0,0 +1,25 @@
+<%# locals: (name:, label:, description:) %>
+<%# One page cache number (see Setting::PAGE_CACHE_SETTINGS), saved on change. %>
+<% range, default = Setting::PAGE_CACHE_SETTINGS.fetch(name) %>
+<% from_env = Setting.page_cache_env_value(name).present? %>
+<div class="flex items-center justify-between gap-4">
+ <div class="space-y-1">
+ <p class="text-sm"><%= label %></p>
+ <p class="text-secondary text-sm"><%= description %></p>
+ </div>
+
+ <%= form_with model: Setting.new,
+ url: settings_hosting_path,
+ method: :patch,
+ data: { controller: "auto-submit-form", auto_submit_form_trigger_event_value: "change" } do |form| %>
+ <%= form.label name, label, class: "sr-only" %>
+ <%= form.number_field name,
+ value: from_env ? Setting.page_cache_value(name) : Setting.public_send(name),
+ placeholder: default,
+ min: range.min,
+ max: range.max,
+ disabled: from_env,
+ class: "rounded-lg border border-primary px-3 py-2 text-sm bg-container text-primary w-24",
+ data: { auto_submit_form_target: "auto" } %>
+ <% end %>
+</div>
diff --git a/app/views/settings/hostings/_sync_settings.html.erb b/app/views/settings/hostings/_sync_settings.html.erb
index b34026e8d1..7fb549af92 100644
--- a/app/views/settings/hostings/_sync_settings.html.erb
+++ b/app/views/settings/hostings/_sync_settings.html.erb
@@ -86,6 +86,19 @@
<% end %>
</div>
+ <%# The page cache's three numbers: each from its env variable when set (the
+ field is then disabled and shows the value in effect), else this form. %>
+ <% {
+ page_cache_days: t(".page_cache_days_description", default_days: Setting::PAGE_CACHE_DAYS_DEFAULT),
+ page_cache_cooldown_minutes: t(".page_cache_cooldown_minutes_description", default_minutes: Setting::PAGE_CACHE_COOLDOWN_MINUTES_DEFAULT),
+ page_cache_max_mb: t(".page_cache_max_mb_description",
+ default_mb: Setting::PAGE_CACHE_MAX_MB_DEFAULT,
+ used: number_to_human_size(PageCache.total_bytes),
+ limit: number_to_human_size(PageCache.max_bytes))
+ }.each do |name, description| %>
+ <%= render "settings/hostings/page_cache_setting", name: name, label: t(".#{name}_label"), description: description %>
+ <% end %>
+
<% if env_configured %>
<%= render DS::Alert.new(message: t(".env_configured_message"), variant: :warning) %>
<% end %>
diff --git a/app/views/shared/_reorderable_sections.html.erb b/app/views/shared/_reorderable_sections.html.erb
index ea33077622..bf6fa21fe9 100644
--- a/app/views/shared/_reorderable_sections.html.erb
+++ b/app/views/shared/_reorderable_sections.html.erb
@@ -80,7 +80,8 @@
</span>
</div>
<% end %>
- <%= render partial: section[:partial], locals: section[:locals] %>
+ <%# A cached page (Reports) hands over its section content already rendered. %>
+ <%= section[:html] ? section[:html].html_safe : render(partial: section[:partial], locals: section[:locals]) %>
<% end %>
</section>
<% end %>
diff --git a/config/locales/views/reports/en.yml b/config/locales/views/reports/en.yml
index 82c360b69d..b9a074bf42 100644
--- a/config/locales/views/reports/en.yml
+++ b/config/locales/views/reports/en.yml
@@ -15,6 +15,9 @@ en:
apply: Apply
section_aria: "%{title} section. Press Enter or Space to grab for reordering, then use arrow keys to move."
sections_aria: Reports sections
+ built_at: Updated %{time} ago
+ updating: updating in the background
+ refresh: Refresh
periods:
monthly: Monthly
quarterly: Quarterly
diff --git a/config/locales/views/settings/hostings/en.yml b/config/locales/views/settings/hostings/en.yml
index 7574d0d262..39c3a3f2c7 100644
--- a/config/locales/views/settings/hostings/en.yml
+++ b/config/locales/views/settings/hostings/en.yml
@@ -338,6 +338,9 @@ en:
invalid_onboarding_state: Invalid onboarding state
invalid_sync_time: Invalid sync time format. Please use HH:MM format (e.g., 02:30).
invalid_llm_budget: "%{field} must be a whole number ≥ %{minimum}."
+ invalid_page_cache_days: "Days to keep cached pages must be a whole number from %{minimum} to %{maximum}."
+ invalid_page_cache_max_mb: "Max cache size must be a whole number of megabytes from %{minimum} to %{maximum}."
+ invalid_page_cache_cooldown_minutes: "Minutes between rebuilds must be a whole number from %{minimum} to %{maximum}."
invalid_anthropic_base_url: Anthropic Base URL must be an http(s) URL.
anthropic_model_required_for_base_url: Anthropic Model is required when a custom Base URL is set.
invalid_jev_endpoint: Jev Endpoint must be an https URL. Plain http is accepted only for localhost.
@@ -367,6 +370,12 @@ en:
market_data_sync_description: When enabled, security prices are imported automatically once a day (Monday-Friday) at the specified time.
market_data_sync_time_label: Market data import time (HH:MM)
market_data_sync_time_description: Specify the time of day when the daily security price import should run — e.g. shortly after your primary exchange closes.
+ page_cache_days_label: Keep cached pages for (days)
+ page_cache_days_description: "Reports are built ahead of time after each sync and kept for this many days if nobody opens them. Default: %{default_days}. PAGE_CACHE_DAYS overrides this field."
+ page_cache_cooldown_minutes_label: Rebuild cached pages at most every (minutes)
+ page_cache_cooldown_minutes_description: "When the data behind a cached page changes, the page you had is still shown while a new one is built in the background, at most once in this many minutes. Refresh on the page rebuilds it straight away. 0 rebuilds after every change. Default: %{default_minutes}. PAGE_CACHE_COOLDOWN_MINUTES overrides this field."
+ page_cache_max_mb_label: Max cache size (MB)
+ page_cache_max_mb_description: "The most cached pages may take together. When a new page would go over it, the pages opened longest ago are dropped first; a page bigger than the whole limit is shown but not kept. Using %{used} of %{limit}. Default: %{default_mb}. PAGE_CACHE_MAX_MB overrides this field."
include_pending_label: Include pending transactions
include_pending_description: When enabled, pending (uncleared) transactions will be imported and automatically reconciled when they post. Disable if your bank provides unreliable pending data.
env_configured_message: This setting is disabled because a provider environment variable (SIMPLEFIN_INCLUDE_PENDING or PLAID_INCLUDE_PENDING) is set. Remove it to enable this setting.
diff --git a/db/migrate/20261121110000_create_page_cache_entries.rb b/db/migrate/20261121110000_create_page_cache_entries.rb
new file mode 100644
index 0000000000..abb65540bc
--- /dev/null
+++ b/db/migrate/20261121110000_create_page_cache_entries.rb
@@ -0,0 +1,14 @@
+class CreatePageCacheEntries < ActiveRecord::Migration[8.1]
+ def change
+ create_table :page_cache_entries, id: :uuid do |t|
+ t.references :family, null: false, foreign_key: { on_delete: :cascade }, type: :uuid
+ t.string :page_key, null: false
+ t.integer :bytes, null: false
+ t.datetime :last_used_at, null: false
+ t.timestamps
+ end
+
+ add_index :page_cache_entries, :page_key, unique: true
+ add_index :page_cache_entries, :last_used_at
+ end
+end
diff --git a/db/schema.rb b/db/schema.rb
index a8e8ce6c9a..bb2e9b2096 100644
--- a/db/schema.rb
+++ b/db/schema.rb
@@ -10,7 +10,7 @@
#
# It's strongly recommended that you check this file into your version control system.
-ActiveRecord::Schema[8.1].define(version: 2026_11_20_100000) do
+ActiveRecord::Schema[8.1].define(version: 2026_11_21_110000) do
# These are extensions that must be enabled in order to support this database
enable_extension "pg_catalog.plpgsql"
enable_extension "pgcrypto"
@@ -1929,6 +1929,18 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_20_100000) do
t.datetime "updated_at", null: false
end
+ create_table "page_cache_entries", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|
+ t.integer "bytes", null: false
+ t.datetime "created_at", null: false
+ t.uuid "family_id", null: false
+ t.datetime "last_used_at", null: false
+ t.string "page_key", null: false
+ t.datetime "updated_at", null: false
+ t.index ["family_id"], name: "index_page_cache_entries_on_family_id"
+ t.index ["last_used_at"], name: "index_page_cache_entries_on_last_used_at"
+ t.index ["page_key"], name: "index_page_cache_entries_on_page_key", unique: true
+ end
+
create_table "plaid_accounts", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|
t.decimal "available_balance", precision: 19, scale: 4
t.datetime "created_at", null: false
@@ -3274,6 +3286,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_20_100000) do
add_foreign_key "oidc_identities", "users"
add_foreign_key "onchain_wallet_accounts", "onchain_wallet_items"
add_foreign_key "onchain_wallet_items", "families"
+ add_foreign_key "page_cache_entries", "families", on_delete: :cascade
add_foreign_key "plaid_accounts", "plaid_items"
add_foreign_key "plaid_items", "families"
add_foreign_key "plaid_items", "users", column: "owner_id", on_delete: :nullify
diff --git a/test/controllers/reports_controller_test.rb b/test/controllers/reports_controller_test.rb
index f8ccc18afa..df353d9edf 100644
--- a/test/controllers/reports_controller_test.rb
+++ b/test/controllers/reports_controller_test.rb
@@ -379,6 +379,296 @@ class ReportsControllerTest < ActionDispatch::IntegrationTest
assert_response :ok
end
+ test "a body warmed outside a request is what the page serves" do
+ with_memory_cache do
+ assert ReportsController.warm_body_cache(user: @user, query: { period_type: :ytd })
+ assert_not ReportsController.warm_body_cache(user: @user, query: { period_type: :ytd }), "already warm"
+
+ ReportsController.any_instance.expects(:setup_report_data).never
+ get reports_path(period_type: :ytd)
+
+ assert_response :ok
+ assert_select "[data-sortable-list-target=item]"
+ end
+ end
+
+ test "a built body is kept for as many days as the page cache setting says" do
+ with_env_overrides PAGE_CACHE_DAYS: nil do
+ Setting.stubs(:page_cache_days).returns(30)
+ store = ActiveSupport::Cache::MemoryStore.new
+ Rails.stubs(:cache).returns(store)
+ store.stubs(:write).returns(true)
+ store.expects(:write).with(regexp_matches(/\Areports_body\//), anything, expires_in: 30.days).returns(true)
+
+ assert ReportsController.warm_body_cache(user: @user, query: { period_type: :ytd })
+ end
+ end
+
+ test "after the data changes, the old build is served while a rebuild is queued" do
+ with_memory_cache do
+ get reports_path(period_type: :ytd)
+ assert_select "[data-testid=report-built-at]", text: /#{I18n.t("reports.index.updating")}/, count: 0
+
+ travel Setting.page_cache_cooldown + 1.minute do
+ @family.entries.first.touch
+ ReportsController.any_instance.expects(:render_report_body).never
+
+ assert_enqueued_with(job: RebuildReportJob, args: [ @user, { period_type: "ytd" }, "en" ]) do
+ get reports_path(period_type: :ytd)
+ end
+ assert_response :ok
+ assert_select "[data-sortable-list-target=item]"
+ assert_select "[data-testid=report-built-at]", text: /#{I18n.t("reports.index.updating")}/
+
+ assert_no_enqueued_jobs(only: RebuildReportJob) { get reports_path(period_type: :ytd) }
+ end
+ end
+ end
+
+ test "a stale build is not rebuilt again within the cooldown" do
+ with_memory_cache do
+ get reports_path(period_type: :ytd)
+ @family.entries.first.touch
+
+ assert_no_enqueued_jobs(only: RebuildReportJob) { get reports_path(period_type: :ytd) }
+ assert_select "[data-testid=report-built-at]", text: /#{I18n.t("reports.index.updating")}/
+ end
+ end
+
+ test "refresh rebuilds the report straight away and drops itself from the URL" do
+ with_memory_cache do
+ get reports_path(period_type: :ytd)
+ @family.entries.first.touch
+
+ ReportsController.any_instance.expects(:render_report_body).once
+ .returns({ notes: "", has_transactions: true, summary: "<p id=rebuilt></p>", sections: [] })
+ get reports_path(period_type: :ytd, refresh: 1)
+ assert_redirected_to reports_path(period_type: :ytd)
+
+ follow_redirect!
+ assert_select "#rebuilt"
+ assert_select "[data-testid=report-built-at]", text: /#{I18n.t("reports.index.updating")}/, count: 0
+ end
+ end
+
+ test "refresh shows a report too big to keep as built, without building it again" do
+ with_memory_cache do
+ PageCache.stubs(:max_bytes).returns(0)
+
+ ReportsController.any_instance.expects(:render_report_body).once
+ .returns({ notes: "", has_transactions: true, summary: "<p id=rebuilt></p>", sections: [] })
+ get reports_path(period_type: :ytd, refresh: 1)
+
+ assert_response :ok
+ assert_select "#rebuilt"
+ end
+ end
+
+ test "a default period keeps its cached build from one day to the next" do
+ with_memory_cache do
+ get reports_path(period_type: :all_time)
+
+ travel 1.day do
+ ReportsController.any_instance.expects(:render_report_body).never
+ get reports_path(period_type: :all_time)
+
+ assert_response :ok
+ assert_select "[data-testid=report-built-at]", text: /#{I18n.t("reports.index.updating")}/
+ end
+ end
+ end
+
+ test "arranging the sections reorders the cached report rather than rebuilding it" do
+ with_memory_cache do
+ ReportsController.warm_body_cache(user: @user, query: { period_type: :ytd })
+ @user.update!(preferences: (@user.preferences || {}).merge(
+ "reports_section_order" => %w[transactions_breakdown trends_insights],
+ "reports_collapsed_sections" => { "trends_insights" => true }
+ ))
+
+ ReportsController.any_instance.expects(:render_report_body).never
+ get reports_path(period_type: :ytd)
+
+ keys = css_select("[data-sortable-list-target=item]").map { |node| node["data-section-key"] }
+ assert_equal %w[transactions_breakdown trends_insights], keys.first(2)
+ assert_select "section[data-section-key=trends_insights] details:not([open])"
+ end
+ end
+
+ test "warming several members builds each one's report from their own accounts" do
+ member = users(:family_member)
+ @family.accounts.create!(name: "Admin only", balance: 0, currency: "USD", accountable: Depository.new, owner: @user)
+ assert_not_equal @user.accessible_accounts.pluck(:id).sort, member.accessible_accounts.pluck(:id).sort
+
+ seen = {}
+ ReportsController.any_instance.stubs(:render_report_body).with do
+ seen[Current.user.id] = Current.accessible_accounts.map(&:id).sort
+ true
+ end.returns({ notes: "", has_transactions: false, summary: "", sections: [] })
+
+ with_memory_cache do
+ ReportsController.warm_body_cache(user: @user, query: { period_type: :ytd })
+ ReportsController.warm_body_cache(user: member, query: { period_type: :ytd })
+ end
+
+ assert_equal @user.accessible_accounts.pluck(:id).sort, seen[@user.id]
+ assert_equal member.accessible_accounts.pluck(:id).sort, seen[member.id]
+ end
+
+ test "losing access to an account is never answered with a report built before" do
+ member = users(:family_member)
+ sign_in member
+
+ with_memory_cache do
+ get reports_path(period_type: :ytd)
+ assert_response :ok
+
+ account_shares(:depository_shared_with_member).destroy!
+ ReportsController.any_instance.expects(:render_report_body).once
+ .returns({ notes: "", has_transactions: true, summary: "<p id=rebuilt></p>", sections: [] })
+ get reports_path(period_type: :ytd)
+
+ assert_select "#rebuilt"
+ assert_select "[data-testid=report-built-at]", text: /#{I18n.t("reports.index.updating")}/, count: 0
+ end
+ end
+
+ test "each sort and filter of the breakdown is its own cached report" do
+ with_memory_cache do
+ get reports_path(period_type: :ytd)
+
+ ReportsController.any_instance.expects(:render_report_body).twice
+ .returns({ notes: "", has_transactions: true, summary: "<p id=rebuilt></p>", sections: [] })
+ get reports_path(period_type: :ytd, sort_by: "count", sort_direction: "asc")
+ assert_select "#rebuilt"
+ get reports_path(period_type: :ytd, filter_account_id: accounts(:depository).id)
+ assert_select "#rebuilt"
+ end
+ end
+
+ test "a background rebuild repeats the page's sort and filters" do
+ with_memory_cache do
+ get reports_path(period_type: :ytd, sort_by: "count", filter_account_id: accounts(:depository).id)
+
+ travel Setting.page_cache_cooldown + 1.minute do
+ @family.entries.first.touch
+ assert_enqueued_with(job: RebuildReportJob,
+ args: [ @user, { filter_account_id: accounts(:depository).id, period_type: "ytd", sort_by: "count" }, "en" ]) do
+ get reports_path(period_type: :ytd, sort_by: "count", filter_account_id: accounts(:depository).id)
+ end
+ end
+ end
+ end
+
+ test "a report warmed in the background is in the member's own language" do
+ @user.update!(locale: "de")
+
+ with_memory_cache do
+ ReportsController.warm_body_cache(user: @user, query: { period_type: :ytd })
+
+ ReportsController.any_instance.expects(:render_report_body).never
+ get reports_path(period_type: :ytd)
+ assert_response :ok
+ end
+ end
+
+ test "a stale build in the language the page asked for is rebuilt in that language" do
+ with_memory_cache do
+ get reports_path(period_type: :ytd, locale: "de")
+
+ travel Setting.page_cache_cooldown + 1.minute do
+ @family.entries.first.touch
+ assert_enqueued_with(job: RebuildReportJob, args: [ @user, { period_type: "ytd" }, "de" ]) do
+ get reports_path(period_type: :ytd, locale: "de")
+ end
+ perform_enqueued_jobs(only: RebuildReportJob)
+
+ ReportsController.any_instance.expects(:render_report_body).never
+ get reports_path(period_type: :ytd, locale: "de")
+ assert_select "[data-testid=report-built-at]", text: /#{I18n.t("reports.index.updating", locale: :de)}/, count: 0
+ end
+ end
+ end
+
+ test "the plain Reports page is served from the build warmed for this month" do
+ with_memory_cache do
+ ReportsController.warm_body_cache(user: @user, query: { period_type: :monthly })
+
+ ReportsController.any_instance.expects(:render_report_body).never
+ get reports_path
+ assert_response :ok
+ end
+ end
+
+ test "changing whether investment contributions count as spending builds the report again" do
+ with_memory_cache do
+ get reports_path(period_type: :ytd)
+ @family.update!(investment_contributions_as_spending: [email protected]_contributions_as_spending)
+
+ ReportsController.any_instance.expects(:render_report_body).once.returns({ notes: "", has_transactions: false, summary: "", sections: [] })
+ get reports_path(period_type: :ytd)
+ end
+ end
+
+ test "assigning a tag marks the cached report stale" do
+ with_memory_cache do
+ get reports_path(period_type: :ytd)
+
+ travel Setting.page_cache_cooldown + 1.minute do
+ transactions(:one).update!(tag_ids: [ tags(:one).id ])
+ assert_enqueued_with(job: RebuildReportJob) { get reports_path(period_type: :ytd) }
+ end
+ end
+ end
+
+ test "a new month's report is built, not served from last month's" do
+ with_memory_cache do
+ travel_to Date.new(2026, 11, 30).noon do
+ get reports_path
+ end
+
+ travel_to Date.new(2026, 12, 1).noon do
+ ReportsController.any_instance.expects(:render_report_body).once.returns({ notes: "", has_transactions: false, summary: "", sections: [] })
+ get reports_path
+ end
+ end
+ end
+
+ test "year to date keeps its build from one day to the next, though it ends today" do
+ with_memory_cache do
+ travel_to Date.new(2026, 11, 20).noon do
+ get reports_path(period_type: :ytd)
+ end
+
+ travel_to Date.new(2026, 11, 21).noon do
+ ReportsController.any_instance.expects(:render_report_body).never
+ get reports_path(period_type: :ytd)
+ assert_response :ok
+ end
+ end
+ end
+
+ test "editing a holding's cost basis marks the cached report stale" do
+ with_memory_cache do
+ get reports_path(period_type: :ytd)
+
+ travel Setting.page_cache_cooldown + 1.minute do
+ holdings(:one).set_manual_cost_basis!(80)
+ assert_enqueued_with(job: RebuildReportJob) { get reports_path(period_type: :ytd) }
+ end
+ end
+ end
+
+ test "each member gets their own cached body" do
+ with_memory_cache do
+ ReportsController.warm_body_cache(user: @user, query: { period_type: :ytd })
+ other = @family.users.where.not(id: @user.id).first
+ assert other, "fixtures need a second member"
+
+ assert ReportsController.warm_body_cache(user: other, query: { period_type: :ytd })
+ end
+ end
+
test "all time runs from the member's first transaction or trade to today" do
first = @family.earliest_activity_date
assert first, "fixtures need a transaction or trade"
@@ -1690,6 +1980,11 @@ class ReportsControllerTest < ActionDispatch::IntegrationTest
end
private
+ def with_memory_cache
+ Rails.stubs(:cache).returns(ActiveSupport::Cache::MemoryStore.new)
+ yield
+ end
+
def biggest_expenses_reports_path(**params)
reports_path(period_type: :custom, start_date: BIGGEST_MONTH, end_date: BIGGEST_MONTH.end_of_month, **params)
end
diff --git a/test/controllers/settings/hostings_controller_test.rb b/test/controllers/settings/hostings_controller_test.rb
index 98fc89fdf4..c86e533baa 100644
--- a/test/controllers/settings/hostings_controller_test.rb
+++ b/test/controllers/settings/hostings_controller_test.rb
@@ -34,7 +34,7 @@ class Settings::HostingsControllerTest < ActionDispatch::IntegrationTest
# These tests persist global Setting.* values; reset them so state can't
# leak into later (order-dependent) tests.
%i[anthropic_access_token anthropic_base_url anthropic_model jev_api_key jev_endpoint jev_model llm_provider twelve_data_api_key openai_access_token openai_request_timeout ai_response_timeout ai_health_probe_timeout external_assistant_url external_assistant_token external_assistant_model external_assistant_agent_id rentcast_api_key realie_api_key chimnie_api_key terrascoutx_api_key demo_family_refresh_enabled demo_family_refresh_family_id
- market_data_sync_enabled market_data_sync_time market_data_sync_timezone].each do |key|
+ market_data_sync_enabled market_data_sync_time market_data_sync_timezone page_cache_days page_cache_max_mb page_cache_cooldown_minutes].each do |key|
Setting.public_send("#{key}=", nil)
end
end
@@ -1385,6 +1385,86 @@ class Settings::HostingsControllerTest < ActionDispatch::IntegrationTest
Setting.ai_health_probe_timeout = nil
end
+ test "saves how long cached pages are kept, and a blank goes back to the default" do
+ with_self_hosting do
+ patch settings_hosting_url, params: { setting: { page_cache_days: "30" } }
+
+ assert_redirected_to settings_hosting_url
+ assert_equal 30, Setting.page_cache_days
+ assert_equal 30.days, Setting.page_cache_ttl
+
+ patch settings_hosting_url, params: { setting: { page_cache_days: "" } }
+
+ assert_nil Setting.page_cache_days
+ assert_equal Setting::PAGE_CACHE_DAYS_DEFAULT.days, Setting.page_cache_ttl
+ end
+ end
+
+ test "saves the page cache's size limit and rebuild cooldown" do
+ with_self_hosting do
+ patch settings_hosting_url, params: { setting: { page_cache_max_mb: "250", page_cache_cooldown_minutes: "0" } }
+
+ assert_redirected_to settings_hosting_url
+ assert_equal 250.megabytes, PageCache.max_bytes
+ assert_equal 0.minutes, Setting.page_cache_cooldown
+
+ patch settings_hosting_url, params: { setting: { page_cache_max_mb: "", page_cache_cooldown_minutes: "" } }
+
+ assert_equal Setting::PAGE_CACHE_MAX_MB_DEFAULT.megabytes, PageCache.max_bytes
+ assert_equal Setting::PAGE_CACHE_COOLDOWN_MINUTES_DEFAULT.minutes, Setting.page_cache_cooldown
+ end
+ end
+
+ test "an environment value the cache ignores doesn't lock its setting" do
+ with_self_hosting do
+ with_env_overrides("PAGE_CACHE_MAX_MB" => "0") do
+ get settings_hosting_url
+ assert_select "input[name='setting[page_cache_max_mb]'][disabled]", count: 0
+
+ patch settings_hosting_url, params: { setting: { page_cache_max_mb: "250" } }
+ assert_equal 250, Setting.page_cache_max_mb
+ end
+ end
+ end
+
+ test "a valid environment value locks its setting" do
+ with_self_hosting do
+ with_env_overrides("PAGE_CACHE_MAX_MB" => "300") do
+ get settings_hosting_url
+ assert_select "input[name='setting[page_cache_max_mb]'][disabled]"
+
+ patch settings_hosting_url, params: { setting: { page_cache_max_mb: "250" } }
+ assert_not_equal 250, Setting.page_cache_max_mb
+ assert_equal 300.megabytes, PageCache.max_bytes
+ end
+ end
+ end
+
+ test "rejects a cache size or cooldown out of range" do
+ with_self_hosting do
+ { page_cache_max_mb: %w[0 100001], page_cache_cooldown_minutes: %w[-1 10081] }.each do |key, values|
+ values.each do |value|
+ patch settings_hosting_url, params: { setting: { key => value } }
+
+ assert_response :unprocessable_entity
+ assert_nil Setting.public_send(key)
+ end
+ end
+ end
+ end
+
+ test "rejects a cache length outside 1 to 365 days" do
+ with_self_hosting do
+ %w[0 366 soon].each do |value|
+ patch settings_hosting_url, params: { setting: { page_cache_days: value } }
+
+ assert_response :unprocessable_entity
+ assert_equal I18n.t("settings.hostings.update.invalid_page_cache_days", minimum: 1, maximum: 365), flash[:alert]
+ assert_nil Setting.page_cache_days
+ end
+ end
+ end
+
test "rejects llm budget below field minimum" do
with_self_hosting do
patch settings_hosting_url, params: { setting: { llm_context_window: "0" } }
diff --git a/test/jobs/apply_rules_job_test.rb b/test/jobs/apply_rules_job_test.rb
index 64dc4f237b..a4e6cf0a28 100644
--- a/test/jobs/apply_rules_job_test.rb
+++ b/test/jobs/apply_rules_job_test.rb
@@ -39,6 +39,26 @@ class ApplyRulesJobTest < ActiveJob::TestCase
end
end
+ test "after a sync, warms Reports once the rules have run" do
+ create_rule(active: true)
+
+ assert_enqueued_with(job: WarmReportsCacheJob, args: [ @family ]) do
+ ApplyRulesJob.perform_now(@family, warm_reports: true)
+ end
+ assert_equal @groceries, @transaction.reload.category
+
+ assert_no_enqueued_jobs(only: WarmReportsCacheJob) { ApplyRulesJob.perform_now(@family) }
+ end
+
+ test "a rule run that must retry warms Reports only when it finishes" do
+ Rule::Runner.any_instance.stubs(:run).raises(Rule::Runner::LockBusy)
+
+ assert_no_enqueued_jobs(only: WarmReportsCacheJob) do
+ ApplyRulesJob.perform_now(@family, warm_reports: true)
+ end
+ assert_enqueued_with(job: ApplyRulesJob, args: [ @family, { warm_reports: true } ])
+ end
+
private
def create_rule(active:)
@family.rules.create!(
diff --git a/test/jobs/rebuild_report_job_test.rb b/test/jobs/rebuild_report_job_test.rb
new file mode 100644
index 0000000000..e198e3c2fa
--- /dev/null
+++ b/test/jobs/rebuild_report_job_test.rb
@@ -0,0 +1,17 @@
+require "test_helper"
+
+class RebuildReportJobTest < ActiveJob::TestCase
+ test "rebuilds the member's report for the query their page carried" do
+ user = users(:family_admin)
+ ReportsController.expects(:warm_body_cache).with(user: user, query: { period_type: "ytd" }, locale: "de").once
+
+ RebuildReportJob.perform_now(user, { period_type: "ytd" }, "de")
+ end
+
+ test "a rebuild queued before the locale was passed along still runs" do
+ user = users(:family_admin)
+ ReportsController.expects(:warm_body_cache).with(user: user, query: { period_type: "ytd" }, locale: nil).once
+
+ RebuildReportJob.perform_now(user, { period_type: "ytd" })
+ end
+end
diff --git a/test/jobs/warm_reports_cache_job_test.rb b/test/jobs/warm_reports_cache_job_test.rb
new file mode 100644
index 0000000000..0b6995decf
--- /dev/null
+++ b/test/jobs/warm_reports_cache_job_test.rb
@@ -0,0 +1,24 @@
+require "test_helper"
+
+class WarmReportsCacheJobTest < ActiveJob::TestCase
+ setup do
+ @family = families(:dylan_family)
+ end
+
+ test "warms every usual period for every member of the family" do
+ @family.users.each do |user|
+ ReportsController::WARMED_PERIOD_TYPES.each do |period_type|
+ ReportsController.expects(:warm_body_cache).with(user: user, query: { period_type: period_type }).once
+ end
+ end
+
+ WarmReportsCacheJob.perform_now(@family)
+ end
+
+ test "one view failing to build does not stop the rest" do
+ attempts = @family.users.count * ReportsController::WARMED_PERIOD_TYPES.size
+ ReportsController.expects(:warm_body_cache).times(attempts).raises(StandardError, "boom").then.returns(true)
+
+ assert_nothing_raised { WarmReportsCacheJob.perform_now(@family) }
+ end
+end
diff --git a/test/models/family/syncer_test.rb b/test/models/family/syncer_test.rb
index e1865c88bd..9fd31f19d5 100644
--- a/test/models/family/syncer_test.rb
+++ b/test/models/family/syncer_test.rb
@@ -56,7 +56,7 @@ class Family::SyncerTest < ActiveSupport::TestCase
test "applies rules in one ordered run per family after sync" do
syncer = Family::Syncer.new(@family)
- assert_enqueued_with(job: ApplyRulesJob, args: [ @family ]) do
+ assert_enqueued_with(job: ApplyRulesJob, args: [ @family, { warm_reports: true } ]) do
syncer.perform_post_sync
end
assert_no_enqueued_jobs(only: RuleJob)
@@ -73,7 +73,7 @@ class Family::SyncerTest < ActiveSupport::TestCase
test "a logo backfill failure does not stop rules from being applied" do
ProviderMerchant.stubs(:backfill_logos).raises(StandardError, "boom")
- assert_enqueued_with(job: ApplyRulesJob, args: [ @family ]) do
+ assert_enqueued_with(job: ApplyRulesJob, args: [ @family, { warm_reports: true } ]) do
Family::Syncer.new(@family).perform_post_sync
end
end
diff --git a/test/models/family_test.rb b/test/models/family_test.rb
index ed7b82098a..eea94666a1 100644
--- a/test/models/family_test.rb
+++ b/test/models/family_test.rb
@@ -273,6 +273,16 @@ class FamilyTest < ActiveSupport::TestCase
assert_tags_version_changes(family) { tag.destroy! }
end
+ test "holdings_version changes when a holding is edited or removed, and only then" do
+ family = families(:dylan_family)
+ holding = holdings(:one)
+
+ assert_equal family.holdings_version, family.holdings_version, "stable while nothing changes"
+ assert_holdings_version_changes(family) { holding.set_manual_cost_basis!(80) }
+ assert_holdings_version_changes(family) { holding.unlock_cost_basis! }
+ assert_holdings_version_changes(family) { holdings(:two).destroy! }
+ end
+
test "entries_cache_version changes when an older entry is destroyed" do
family = families(:dylan_family)
newer_entry = entries(:transaction)
@@ -961,6 +971,12 @@ class FamilyTest < ActiveSupport::TestCase
assert_not_equal before, family.reload.tags_version
end
+ def assert_holdings_version_changes(family)
+ before = family.holdings_version
+ yield
+ assert_not_equal before, family.holdings_version
+ end
+
def set_preview_features(user, enabled)
user.update!(preferences: (user.preferences || {}).merge("preview_features_enabled" => enabled))
end
diff --git a/test/models/financekit/inbox_test.rb b/test/models/financekit/inbox_test.rb
index 3fb2dfe1cd..840dbfe093 100644
--- a/test/models/financekit/inbox_test.rb
+++ b/test/models/financekit/inbox_test.rb
@@ -227,6 +227,15 @@ class Financekit::InboxTest < ActiveSupport::TestCase
assert_not_nil second.reload.downstream_completed_at
end
+ test "the rules run after a capture warms Reports once they finish" do
+ batch, = accept_batch
+ assert Financekit::Processor.new(@item).apply_next!.present?
+
+ assert_enqueued_with(job: ApplyRulesJob, args: [ @item.family, { warm_reports: true } ]) do
+ Financekit::Downstream.new(@item, FinancekitBatch.where(id: batch.id)).perform!
+ end
+ end
+
test "overlapping downstream workers fan out once" do
batch, = accept_batch
assert Financekit::Processor.new(@item).apply_next!.present?
diff --git a/test/models/page_cache_test.rb b/test/models/page_cache_test.rb
new file mode 100644
index 0000000000..9ab701bb58
--- /dev/null
+++ b/test/models/page_cache_test.rb
@@ -0,0 +1,350 @@
+require "test_helper"
+
+class PageCacheTest < ActiveSupport::TestCase
+ # Keeps serialized entries the way RedisCacheStore does, so reads go through
+ # Rails' per-request LocalCache. MemoryStore keeps objects and never reaches it.
+ class SerializingStore < ActiveSupport::Cache::Store
+ prepend ActiveSupport::Cache::Strategy::LocalCache
+
+ def initialize(options = nil)
+ super
+ @data = {}
+ end
+
+ private
+ def read_entry(key, **options)
+ deserialize_entry(read_serialized_entry(key, **options), **options)
+ end
+
+ def read_serialized_entry(key, **)
+ @data[key]
+ end
+
+ def write_entry(key, entry, **options)
+ write_serialized_entry(key, serialize_entry(entry, **options), **options)
+ end
+
+ def write_serialized_entry(key, payload, unless_exist: false, **)
+ return false if unless_exist && @data.key?(key)
+
+ @data[key] = payload
+ true
+ end
+
+ def delete_entry(key, **)
+ [email protected](key).nil?
+ end
+ end
+
+ setup do
+ @family = families(:dylan_family)
+ @user = users(:family_admin)
+ Rails.stubs(:cache).returns(ActiveSupport::Cache::MemoryStore.new)
+ end
+
+ test "a page that was never built is built and kept" do
+ served = PageCache.serve("page/a", version: "v1", family: @family, user: @user, rebuild_later: -> { flunk "nothing to rebuild" }) { "body" }
+
+ assert_equal "body", served.body
+ assert_not served.stale
+ assert PageCacheEntry.exists?(page_key: "page/a")
+ end
+
+ test "a page built from older data is served stale and rebuilt once its cooldown has passed" do
+ PageCache.serve("page/a", version: "v1", family: @family, user: @user, rebuild_later: -> { }) { "old" }
+ rebuilds = 0
+
+ served = PageCache.serve("page/a", version: "v2", family: @family, user: @user, rebuild_later: -> { rebuilds += 1 }) { flunk "must not build" }
+ assert_equal [ "old", true, 0 ], [ served.body, served.stale, rebuilds ], "within the cooldown"
+
+ travel Setting.page_cache_cooldown + 1.minute do
+ 2.times { PageCache.serve("page/a", version: "v2", family: @family, user: @user, rebuild_later: -> { rebuilds += 1 }) { flunk "must not build" } }
+ assert_equal 1, rebuilds, "one rebuild is claimed, however many visits"
+
+ PageCache.write("page/a", "new", version: "v2", family: @family, user: @user)
+ served = PageCache.serve("page/a", version: "v2", family: @family, user: @user, rebuild_later: -> { flunk "current" }) { flunk "current" }
+ assert_equal [ "new", false ], [ served.body, served.stale ]
+ end
+ end
+
+ test "refresh builds the page even when a current one is kept" do
+ PageCache.serve("page/a", version: "v1", family: @family, user: @user, rebuild_later: -> { }) { "old" }
+
+ served = PageCache.serve("page/a", version: "v1", family: @family, user: @user, rebuild_later: -> { }, refresh: true) { "fresh" }
+
+ assert_equal "fresh", served.body
+ end
+
+ # The 99 MB page, then a 2 MB one, under a 100 MB limit, scaled down.
+ test "going over the limit drops the pages served longest ago" do
+ # Random text, so compression can't shrink it much.
+ PageCache.stubs(:max_bytes).returns(200_000)
+ PageCache.write("page/big", SecureRandom.alphanumeric(140_000), version: "v1", family: @family, user: @user)
+ assert_equal %w[page/big], PageCacheEntry.pluck(:page_key)
+
+ travel 1.minute do
+ PageCache.write("page/small", SecureRandom.alphanumeric(20_000), version: "v1", family: @family, user: @user)
+ end
+
+ assert_equal %w[page/small], PageCacheEntry.pluck(:page_key)
+ assert_nil Rails.cache.read("page/big")
+ assert_operator PageCache.total_bytes, :<=, 200_000
+ end
+
+ test "a page bigger than the whole limit is served but not kept" do
+ PageCache.stubs(:max_bytes).returns(1_000)
+ PageCache.write("page/small", "x" * 100, version: "v1", family: @family, user: @user)
+
+ served = PageCache.serve("page/huge", version: "v1", family: @family, user: @user, rebuild_later: -> { }) { SecureRandom.alphanumeric(5_000) }
+
+ assert_equal 5_000, served.body.bytesize
+ assert_nil Rails.cache.read("page/huge")
+ assert_equal %w[page/small], PageCacheEntry.pluck(:page_key), "the pages already kept stay"
+ end
+
+ test "a rebuild too big to keep leaves the earlier build in place" do
+ PageCache.write("page/a", "x" * 100, version: "v1", family: @family, user: @user)
+ PageCache.stubs(:max_bytes).returns(1_000)
+
+ assert_not PageCache.write("page/a", SecureRandom.alphanumeric(5_000), version: "v2", family: @family, user: @user)
+
+ served = PageCache.serve("page/a", version: "v2", family: @family, user: @user, rebuild_later: -> { }) { flunk "built while a stored page exists" }
+ assert_equal "x" * 100, served.body
+ assert served.stale
+ assert_equal %w[page/a], PageCacheEntry.pluck(:page_key)
+ end
+
+ test "the cooldown counts from when the last rebuild finished, even one too big to keep" do
+ PageCache.write("page/a", "x" * 100, version: "v1", family: @family, user: @user)
+ PageCache.stubs(:max_bytes).returns(1_000)
+ rebuilds = 0
+ visit = -> { PageCache.serve("page/a", version: "v2", family: @family, user: @user, rebuild_later: -> { rebuilds += 1 }) { flunk "stale is served" } }
+
+ travel Setting.page_cache_cooldown + 1.minute do
+ visit.call
+ assert_equal 1, rebuilds, "the stored page is past its cooldown"
+ assert_not PageCache.write("page/a", SecureRandom.alphanumeric(5_000), version: "v2", family: @family, user: @user)
+
+ visit.call
+ assert_equal 1, rebuilds, "within the cooldown of the rebuild that just finished"
+ end
+
+ travel 2 * Setting.page_cache_cooldown + 2.minutes do
+ visit.call
+ assert_equal 2, rebuilds, "a cooldown after that rebuild finished"
+ end
+ end
+
+ test "eviction leaves a page that was replaced after it was chosen" do
+ PageCache.write("page/a", "old", version: "v1", family: @family, user: @user)
+ chosen = PageCacheEntry.where(page_key: "page/a").pluck(:id, :page_key, :bytes, :last_used_at)
+
+ travel 1.minute do
+ PageCache.write("page/a", "replacement body", version: "v2", family: @family, user: @user)
+ PageCache.send(:forget_rows, chosen)
+
+ served = PageCache.serve("page/a", version: "v2", family: @family, user: @user, rebuild_later: -> { }) { flunk "kept" }
+ assert_equal "replacement body", served.body
+ assert PageCacheEntry.exists?(page_key: "page/a")
+ end
+ end
+
+ test "eviction chooses another page when the one it chose was renewed meanwhile" do
+ PageCache.write("page/a", SecureRandom.alphanumeric(20_000), version: "v1", family: @family, user: @user)
+ travel 1.minute do
+ PageCache.write("page/b", SecureRandom.alphanumeric(20_000), version: "v1", family: @family, user: @user)
+ end
+ PageCache.stubs(:max_bytes).returns(PageCache.total_bytes - 1)
+
+ renewing = Module.new do
+ attr_accessor :renew_on_lock
+
+ def with_page_lock(key, &block)
+ PageCacheEntry.where(page_key: renew_on_lock).update_all(last_used_at: 1.hour.from_now) if key == renew_on_lock
+ super
+ end
+ end
+ PageCache.singleton_class.prepend(renewing)
+ PageCache.renew_on_lock = "page/a"
+
+ begin
+ PageCache.send(:evict_to_fit)
+ ensure
+ PageCache.renew_on_lock = nil
+ end
+
+ assert_equal %w[page/a], PageCacheEntry.pluck(:page_key)
+ assert_operator PageCache.total_bytes, :<=, PageCache.max_bytes
+ assert_nil Rails.cache.read("page/b")
+ end
+
+ test "a page the cache store refuses is served but not kept" do
+ Rails.cache.stubs(:write).returns(false)
+
+ served = PageCache.serve("page/a", version: "v1", family: @family, user: @user, rebuild_later: -> { }) { "body" }
+
+ assert_equal "body", served.body
+ assert_not served.kept
+ assert_not PageCacheEntry.exists?(page_key: "page/a")
+ end
+
+ test "pages unopened for longer than the keep time are forgotten" do
+ PageCache.write("page/old", "old", version: "v1", family: @family, user: @user)
+
+ travel Setting.page_cache_ttl + 1.day do
+ PageCache.write("page/new", "new", version: "v1", family: @family, user: @user)
+ end
+
+ assert_equal %w[page/new], PageCacheEntry.pluck(:page_key)
+ end
+
+ test "a page is never served to another family, even under the same key" do
+ other_family = families(:empty)
+ other_user = users(:empty)
+ PageCache.write("page/shared-key", "dylan's report", version: "v1", family: @family, user: @user)
+
+ served = PageCache.serve("page/shared-key", version: "v1", family: other_family, user: other_user, rebuild_later: -> { }) { "their own" }
+
+ assert_equal "their own", served.body
+ end
+
+ test "a page is never served to another member of the same family" do
+ member = @family.users.where.not(id: @user.id).first
+ PageCache.write("page/a", "admin's report", version: "v1", family: @family, user: @user)
+
+ served = PageCache.serve("page/a", version: "v1", family: @family, user: member, rebuild_later: -> { }) { "member's own" }
+
+ assert_equal "member's own", served.body
+ end
+
+ test "the cache holds the page encrypted and bound to its key" do
+ PageCache.write("page/a", "Total income 12,345", version: "v1", family: @family, user: @user)
+ sealed = Rails.cache.read("page/a")
+
+ assert_not_includes sealed, "12,345"
+ assert_not_includes Base64.decode64(sealed.split("--").first), "12,345"
+
+ Rails.cache.write("page/b", sealed)
+ served = PageCache.serve("page/b", version: "v1", family: @family, user: @user, rebuild_later: -> { }) { "rebuilt" }
+ assert_equal "rebuilt", served.body, "a sealed page moved under another key does not open"
+ end
+
+ test "a tampered page is treated as missing" do
+ PageCache.write("page/a", "report", version: "v1", family: @family, user: @user)
+ Rails.cache.write("page/a", Rails.cache.read("page/a").reverse)
+
+ served = PageCache.serve("page/a", version: "v1", family: @family, user: @user, rebuild_later: -> { }) { "rebuilt" }
+
+ assert_equal "rebuilt", served.body
+ end
+
+ test "a page is compressed before it is encrypted" do
+ body = "<tr><td>Groceries</td><td>$123.45</td></tr>" * 2_000
+ PageCache.write("page/a", body, version: "v1", family: @family, user: @user)
+
+ assert_operator PageCacheEntry.find_by!(page_key: "page/a").bytes, :<, body.bytesize / 10
+ assert_equal body, PageCache.serve("page/a", version: "v1", family: @family, user: @user, rebuild_later: -> { }) { flunk "kept" }.body
+ end
+
+ test "opening a page renews how long it is kept" do
+ PageCache.write("page/a", "report", version: "v1", family: @family, user: @user)
+
+ travel Setting.page_cache_ttl - 1.day do
+ PageCache.serve("page/a", version: "v1", family: @family, user: @user, rebuild_later: -> { }) { flunk "kept" }
+ end
+
+ travel Setting.page_cache_ttl + 2.days do
+ served = PageCache.serve("page/a", version: "v1", family: @family, user: @user, rebuild_later: -> { }) { "rebuilt" }
+ assert_equal "report", served.body, "opened a day before it would have expired"
+ end
+ end
+
+ test "renewing a page that was replaced meanwhile never puts the earlier one back" do
+ PageCache.write("page/a", "earlier", version: "v1", family: @family, user: @user)
+ earlier = Rails.cache.read("page/a")
+
+ travel PageCache::TOUCH_INTERVAL + 1.minute do
+ PageCache.write("page/a", "newer", version: "v2", family: @family, user: @user)
+ PageCacheEntry.where(page_key: "page/a").update_all(last_used_at: 1.day.ago)
+
+ PageCache.send(:touch, "page/a", earlier)
+
+ served = PageCache.serve("page/a", version: "v2", family: @family, user: @user, rebuild_later: -> { }) { flunk "kept" }
+ assert_equal "newer", served.body
+ end
+ end
+
+ test "a build that began before the stored page's never replaces it" do
+ slow_started = Time.current
+ travel 1.minute do
+ PageCache.write("page/a", "newer", version: "v2", family: @family, user: @user, started_at: Time.current)
+ end
+
+ travel 2.minutes do
+ assert_not PageCache.write("page/a", "older", version: "v1", family: @family, user: @user, started_at: slow_started)
+ served = PageCache.serve("page/a", version: "v2", family: @family, user: @user, rebuild_later: -> { }) { flunk "kept" }
+ assert_equal "newer", served.body
+ end
+ end
+
+ # In production each request reads through Rails' per-request local cache,
+ # which keeps what it first read. These run as a request (with_local_cache)
+ # while another process (around the local cache) replaces the page.
+ test "a request renewing a page it read earlier never puts it back over a newer build" do
+ Rails.stubs(:cache).returns(SerializingStore.new)
+ PageCache.write("page/a", "earlier", version: "v1", family: @family, user: @user)
+
+ travel PageCache::TOUCH_INTERVAL + 1.minute do
+ Rails.cache.with_local_cache do
+ earlier = Rails.cache.read("page/a")
+ in_another_process { PageCache.write("page/a", "newer", version: "v2", family: @family, user: @user) }
+ PageCacheEntry.where(page_key: "page/a").update_all(last_used_at: 1.day.ago)
+
+ PageCache.send(:touch, "page/a", earlier)
+ end
+
+ served = PageCache.serve("page/a", version: "v2", family: @family, user: @user, rebuild_later: -> { }) { flunk "kept" }
+ assert_equal "newer", served.body
+ end
+ end
+
+ test "a request whose build began first never replaces a page another process stored meanwhile" do
+ Rails.stubs(:cache).returns(SerializingStore.new)
+ slow_started = Time.current
+
+ Rails.cache.with_local_cache do
+ assert_nil Rails.cache.read("page/a"), "the request saw no page"
+ travel 1.minute do
+ in_another_process { PageCache.write("page/a", "newer", version: "v2", family: @family, user: @user, started_at: Time.current) }
+ end
+
+ travel 2.minutes do
+ assert_not PageCache.write("page/a", "older", version: "v1", family: @family, user: @user, started_at: slow_started)
+ end
+ end
+
+ served = PageCache.serve("page/a", version: "v2", family: @family, user: @user, rebuild_later: -> { }) { flunk "kept" }
+ assert_equal "newer", served.body
+ end
+
+ test "a rebuild that can't be queued still serves the stale page and tries again next time" do
+ PageCache.write("page/a", "old", version: "v1", family: @family, user: @user)
+ attempts = 0
+ failing = -> { attempts += 1; raise "queue down" }
+
+ travel Setting.page_cache_cooldown + 1.minute do
+ 2.times do
+ served = PageCache.serve("page/a", version: "v2", family: @family, user: @user, rebuild_later: failing) { flunk "stale is served" }
+ assert_equal [ "old", true ], [ served.body, served.stale ]
+ end
+ end
+
+ assert_equal 2, attempts, "the failed attempt released its claim"
+ end
+
+ private
+ # Another process's cache calls don't go through this request's local cache
+ def in_another_process(&block)
+ Rails.cache.send(:bypass_local_cache, &block)
+ end
+end
diff --git a/test/models/setting_test.rb b/test/models/setting_test.rb
index 964860d0cc..53ca052452 100644
--- a/test/models/setting_test.rb
+++ b/test/models/setting_test.rb
@@ -348,6 +348,26 @@ class SettingTest < ActiveSupport::TestCase
assert_raises(ArgumentError) { Setting.reencrypt_secrets_from("") }
end
+ test "a page cache env variable wins over the saved value, and bad values from either are ignored" do
+ Setting.page_cache_max_mb = 250
+ assert_equal 250, Setting.page_cache_max_mb_in_effect
+
+ with_env_overrides PAGE_CACHE_MAX_MB: "10" do
+ assert_equal 10, Setting.page_cache_max_mb_in_effect
+ end
+
+ with_env_overrides PAGE_CACHE_MAX_MB: "0", PAGE_CACHE_DAYS: "lots", PAGE_CACHE_COOLDOWN_MINUTES: "0" do
+ assert_equal 250, Setting.page_cache_max_mb_in_effect, "0 MB is out of range, so the saved value stands"
+ assert_equal Setting::PAGE_CACHE_DAYS_DEFAULT.days, Setting.page_cache_ttl
+ assert_equal 0.minutes, Setting.page_cache_cooldown, "0 is a valid cooldown"
+ end
+
+ Setting.page_cache_max_mb = 999_999
+ assert_equal Setting::PAGE_CACHE_MAX_MB_DEFAULT, Setting.page_cache_max_mb_in_effect
+ ensure
+ Setting.page_cache_max_mb = nil
+ end
+
private
def old_setting_encryptor(secret_key_base)