Skip to content

A platform for community discussion. Free, open, simple.

PERF: extract shared DiskCacheEviction utility for disk caches (#37842)

Joffrey JAFFEUX1267b818a3e6
diff --git a/app/controllers/user_avatars_controller.rb b/app/controllers/user_avatars_controller.rb
index b18497a5624..b7c623df818 100644
--- a/app/controllers/user_avatars_controller.rb
+++ b/app/controllers/user_avatars_controller.rb
@@ -163,6 +163,9 @@ class UserAvatarsController < ApplicationController
end
PROXY_PATH = Rails.root + "tmp/avatar_proxy"
+ PROXY_CACHE_MAX_ENTRIES = 10_000
+ PROXY_CACHE_EVICT_COUNT = 1000
+
def proxy_avatar(url, last_modified)
url = (SiteSetting.force_https ? "https:" : "http:") + url if url[0..1] == "//"
@@ -184,12 +187,19 @@ class UserAvatarsController < ApplicationController
return render_blank if tmp.nil?
FileUtils.mv tmp.path, path
+ DiskCacheEviction.evict(
+ dir: PROXY_PATH,
+ max_entries: PROXY_CACHE_MAX_ENTRIES,
+ evict_count: PROXY_CACHE_EVICT_COUNT,
+ )
end
response.headers["Last-Modified"] = last_modified.httpdate
response.headers["Content-Length"] = File.size(path).to_s
immutable_for(1.year)
send_file path, disposition: nil
+ rescue Errno::ENOENT, ActionController::MissingFile
+ render_blank
end
def redirect_s3_avatar(url)
diff --git a/lib/disk_cache_eviction.rb b/lib/disk_cache_eviction.rb
new file mode 100644
index 00000000000..b4c0ed903f0
--- /dev/null
+++ b/lib/disk_cache_eviction.rb
@@ -0,0 +1,18 @@
+# frozen_string_literal: true
+
+class DiskCacheEviction
+ def self.evict(dir:, max_entries:, evict_count:)
+ pattern = File.join(dir.to_s, "*")
+ files = Dir.glob(pattern)
+ return if files.length <= max_entries
+
+ oldest =
+ files.min_by(evict_count) do |f|
+ File.mtime(f)
+ rescue Errno::ENOENT
+ Time.new(0)
+ end
+
+ FileUtils.rm_f(oldest)
+ end
+end
diff --git a/lib/file_store/base_store.rb b/lib/file_store/base_store.rb
index c9d2da60608..d2c4e1f43b5 100644
--- a/lib/file_store/base_store.rb
+++ b/lib/file_store/base_store.rb
@@ -191,6 +191,7 @@ module FileStore
CACHE_DIR = "#{Rails.root}/tmp/download_cache/"
CACHE_MAXIMUM_SIZE = 500
+ CACHE_EVICT_COUNT = 100
def get_cache_path_for(filename)
"#{CACHE_DIR}#{filename}"
@@ -207,18 +208,11 @@ module FileStore
FileUtils.mkdir_p(dir) unless Dir.exist?(dir)
FileUtils.cp(file.path, path)
- # Remove all but CACHE_MAXIMUM_SIZE most recent files
- files = Dir.glob("#{CACHE_DIR}*")
- files.sort_by! do |f|
- begin
- File.mtime(f)
- rescue Errno::ENOENT
- Time.new(0)
- end
- end
- files.pop(CACHE_MAXIMUM_SIZE)
-
- FileUtils.rm(files, force: true)
+ DiskCacheEviction.evict(
+ dir: CACHE_DIR,
+ max_entries: CACHE_MAXIMUM_SIZE,
+ evict_count: CACHE_EVICT_COUNT,
+ )
end
private
diff --git a/spec/lib/disk_cache_eviction_spec.rb b/spec/lib/disk_cache_eviction_spec.rb
new file mode 100644
index 00000000000..eb33104b824
--- /dev/null
+++ b/spec/lib/disk_cache_eviction_spec.rb
@@ -0,0 +1,55 @@
+# frozen_string_literal: true
+
+RSpec.describe DiskCacheEviction do
+ let(:cache_dir) { Dir.mktmpdir }
+
+ after { FileUtils.rm_rf(cache_dir) }
+
+ def create_files(count, prefix: "file", age_offset: 0)
+ count.times.map do |i|
+ path = File.join(cache_dir, "#{prefix}_#{i}.tmp")
+ File.write(path, "data_#{i}")
+ FileUtils.touch(path, mtime: Time.now - (age_offset + count - i).hours)
+ path
+ end
+ end
+
+ describe ".evict" do
+ it "does nothing when file count is under the limit" do
+ create_files(3)
+ described_class.evict(dir: cache_dir, max_entries: 5, evict_count: 2)
+ expect(Dir.glob(File.join(cache_dir, "*")).length).to eq(3)
+ end
+
+ it "does nothing when file count equals the limit" do
+ create_files(5)
+ described_class.evict(dir: cache_dir, max_entries: 5, evict_count: 2)
+ expect(Dir.glob(File.join(cache_dir, "*")).length).to eq(5)
+ end
+
+ it "evicts the oldest files when over the limit" do
+ old_files = create_files(3, prefix: "old", age_offset: 10)
+ new_files = create_files(3, prefix: "new", age_offset: 0)
+
+ described_class.evict(dir: cache_dir, max_entries: 5, evict_count: 2)
+
+ expect(File.exist?(old_files[0])).to eq(false)
+ expect(File.exist?(old_files[1])).to eq(false)
+ expect(File.exist?(old_files[2])).to eq(true)
+ new_files.each { |f| expect(File.exist?(f)).to eq(true) }
+ end
+
+ it "handles files vanishing between glob and stat" do
+ files = create_files(6, prefix: "race")
+ vanishing = files.first
+
+ # Simulate race: file is in glob results but gone when File.mtime is called
+ File.stubs(:mtime).with(anything).returns(Time.now)
+ File.stubs(:mtime).with(vanishing).raises(Errno::ENOENT)
+
+ expect {
+ described_class.evict(dir: cache_dir, max_entries: 5, evict_count: 2)
+ }.not_to raise_error
+ end
+ end
+end
diff --git a/spec/lib/file_store/base_store_spec.rb b/spec/lib/file_store/base_store_spec.rb
index 78fe40f8c0d..1c4dbe4829e 100644
--- a/spec/lib/file_store/base_store_spec.rb
+++ b/spec/lib/file_store/base_store_spec.rb
@@ -245,6 +245,46 @@ RSpec.describe FileStore::BaseStore do
end
end
+ describe "#cache_file" do
+ let(:store) { FileStore::BaseStore.new }
+ let(:cache_dir) { FileStore::BaseStore::CACHE_DIR }
+
+ before { FileUtils.rm_rf(cache_dir) }
+
+ after { FileUtils.rm_rf(cache_dir) }
+
+ it "evicts oldest files in batch when over the cache limit" do
+ FileUtils.mkdir_p(cache_dir)
+
+ stub_const(FileStore::BaseStore, "CACHE_MAXIMUM_SIZE", 5) do
+ stub_const(FileStore::BaseStore, "CACHE_EVICT_COUNT", 2) do
+ 6.times do |i|
+ file = Tempfile.new("test_cache_#{i}")
+ file.write("data_#{i}")
+ file.rewind
+ store.cache_file(file, "cached_#{i}.tmp")
+ path = store.get_cache_path_for("cached_#{i}.tmp")
+ FileUtils.touch(path, mtime: Time.now - (10 - i).hours)
+ file.close!
+ end
+
+ trigger = Tempfile.new("trigger")
+ trigger.write("trigger")
+ trigger.rewind
+ store.cache_file(trigger, "trigger.tmp")
+ trigger.close!
+ end
+ end
+
+ remaining = Dir.glob("#{cache_dir}*")
+ expect(remaining.length).to eq(5)
+ expect(File.exist?(store.get_cache_path_for("cached_0.tmp"))).to eq(false)
+ expect(File.exist?(store.get_cache_path_for("cached_1.tmp"))).to eq(false)
+ expect(File.exist?(store.get_cache_path_for("cached_5.tmp"))).to eq(true)
+ expect(File.exist?(store.get_cache_path_for("trigger.tmp"))).to eq(true)
+ end
+ end
+
describe "#download_safe" do
before do
setup_s3
diff --git a/spec/requests/user_avatars_controller_spec.rb b/spec/requests/user_avatars_controller_spec.rb
index 549a184cffb..3fc9878da3f 100644
--- a/spec/requests/user_avatars_controller_spec.rb
+++ b/spec/requests/user_avatars_controller_spec.rb
@@ -17,6 +17,70 @@ RSpec.describe UserAvatarsController do
end
end
+ describe "#proxy_avatar cache eviction" do
+ let(:proxy_path) { UserAvatarsController::PROXY_PATH }
+
+ before { FileUtils.rm_rf(proxy_path) }
+
+ after { FileUtils.rm_rf(proxy_path) }
+
+ it "evicts oldest cached files in batch when the cache grows beyond the limit" do
+ FileUtils.mkdir_p(proxy_path)
+
+ old_files =
+ 5.times.map do |i|
+ path = "#{proxy_path}/old_file_#{i}.png"
+ File.write(path, "old_data_#{i}")
+ path
+ end
+ old_files.each_with_index { |f, i| FileUtils.touch(f, mtime: Time.now - (10 - i).days) }
+
+ stub_request(:get, "https://avatars.discourse-cdn.com/v3/letter/a/aaaaaa/360.png").to_return(
+ body: "image",
+ )
+
+ stub_const(UserAvatarsController, "PROXY_CACHE_MAX_ENTRIES", 5) do
+ stub_const(UserAvatarsController, "PROXY_CACHE_EVICT_COUNT", 2) do
+ get "/letter_avatar_proxy/v3/letter/a/aaaaaa/360.png"
+ end
+ end
+ expect(response.status).to eq(200)
+
+ remaining = Dir.glob("#{proxy_path}/*")
+ expect(remaining.length).to eq(4)
+ expect(File.exist?(old_files[0])).to eq(false)
+ expect(File.exist?(old_files[1])).to eq(false)
+ expect(File.exist?(old_files[2])).to eq(true)
+ expect(File.exist?(old_files[4])).to eq(true)
+
+ new_file_sha =
+ Digest::SHA1.hexdigest("https://avatars.discourse-cdn.com/v3/letter/a/aaaaaa/360.png")
+ expect(File.exist?("#{proxy_path}/#{new_file_sha}.png")).to eq(true)
+ end
+
+ it "renders blank avatar when send_file fails because the cached file vanished" do
+ url = "https://avatars.discourse-cdn.com/v3/letter/b/bbbbbb/360.png"
+ sha = Digest::SHA1.hexdigest(url)
+ path = "#{proxy_path}/#{sha}.png"
+
+ FileUtils.mkdir_p(proxy_path)
+ File.write(path, "image")
+
+ allow_any_instance_of(UserAvatarsController).to receive(
+ :send_file,
+ ).and_wrap_original do |original, *args|
+ raise ActionController::MissingFile, "Cannot read file #{path}" if args.first == path
+
+ original.call(*args)
+ end
+
+ get "/letter_avatar_proxy/v3/letter/b/bbbbbb/360.png"
+
+ expect(response.status).to eq(200)
+ expect(response.headers["Last-Modified"]).to eq(Time.new(1990, 01, 01).httpdate)
+ end
+ end
+
describe "#show" do
context "when invalid" do
after { FileUtils.rm(Discourse.store.path_for(upload)) }