Fix performance of media attachment queries in admin instance page (#40515)

This commit is contained in:
Kazuki Nagasawa
2026-09-16 16:14:18 +00:00
committed by GitHub
parent 07dc097f42
commit f466632ac0
2 changed files with 11 additions and 5 deletions

View File

@@ -47,7 +47,7 @@ class Admin::Metrics::Measure::InstanceMediaAttachmentsMeasure < Admin::Metrics:
SELECT #{media_size_total} AS size
FROM media_attachments
INNER JOIN accounts ON accounts.id = media_attachments.account_id
WHERE date_trunc('day', media_attachments.created_at)::date = axis.period
WHERE media_attachments.id >= (date_part('epoch', date_trunc('day', axis.period)::date) * 1000)::bigint << 16 AND media_attachments.id < ((date_part('epoch', date_trunc('day', axis.period)::date + ('1 day')::interval)) * 1000)::bigint << 16
AND #{account_domain_sql(params[:include_subdomains])}
)
SELECT COALESCE(SUM(size), 0) FROM new_media_attachments

View File

@@ -16,6 +16,11 @@ RSpec.describe Admin::Metrics::Measure::InstanceMediaAttachmentsMeasure do
let(:remote_account_on_subdomain) { Fabricate(:account, domain: "foo.#{domain}") }
before do
travel_to 2.days.ago do
# We specify the `id` because `travel_to` doesn't affect the database
remote_account.media_attachments.create!(id: Mastodon::Snowflake.id_at(Time.now.utc), file: attachment_fixture('attachment.jpg'))
end
remote_account.media_attachments.create!(file: attachment_fixture('attachment.jpg'))
remote_account_on_subdomain.media_attachments.create!(file: attachment_fixture('attachment.jpg'))
end
@@ -47,14 +52,15 @@ RSpec.describe Admin::Metrics::Measure::InstanceMediaAttachmentsMeasure do
.to eq(3)
expect(subject.data.map(&:symbolize_keys))
.to contain_exactly(
include(date: 2.days.ago.midnight.to_time, value: '0'),
include(date: 2.days.ago.midnight.to_time, value: expected_domain_only_total_on(2.days.ago).to_s),
include(date: 1.day.ago.midnight.to_time, value: '0'),
include(date: 0.days.ago.midnight.to_time, value: expected_domain_only_total.to_s)
include(date: 0.days.ago.midnight.to_time, value: expected_domain_only_total_on(0.days.ago).to_s)
)
end
def expected_domain_only_total
remote_account.media_attachments.sum(:file_file_size) + remote_account.media_attachments.sum(:thumbnail_file_size)
def expected_domain_only_total_on(date)
attachments = remote_account.media_attachments.where(created_at: date.all_day)
attachments.sum(:file_file_size) + attachments.sum(:thumbnail_file_size)
end
end
end