discourse/lib/disk_cache_eviction.rb
Joffrey JAFFEUX 1267b818a3
PERF: extract shared DiskCacheEviction utility for disk caches (#37842)
- Extracts a shared `DiskCacheEviction.evict` utility used by both
avatar proxy cache (`tmp/avatar_proxy/`) and download cache
(`tmp/download_cache/`)
- `base_store.rb` no longer sorts the entire file list on every
`cache_file` call, eviction only runs when count exceeds the limit
- Fixes a concurrency bug in `proxy_avatar` where a file could be
evicted between `File.exist?` and `send_file`, now rescues
`Errno::ENOENT` / `ActionController::MissingFile` and falls back to
`render_blank`
2026-02-16 12:24:38 +01:00

18 lines
387 B
Ruby

# 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