FIX: Treat corrupt cache as cache miss

Currently when a cache entry is corrupt, we log the event without doing
anything else. It means the cache is still corrupt, and the proper value
isn’t computed again.

Normally, it’s very rare the cache becomes corrupt, but it can happen
when upgrading Rails for example and the cache format changes. This is
normally handled automatically by Rails but since we’re using a custom
cache class, we have to do it ourselves.

This patch takes the same approach the Rails team did, when a cache
entry is corrupt, we treat it as a miss, recomputing the proper value
and caching it in the new format.
This commit is contained in:
Loïc Guitaut
2024-06-18 11:48:00 +02:00
committed by Loïc Guitaut
parent f904acbc85
commit 2a22a3b51d
2 changed files with 42 additions and 31 deletions

View File

@ -3,9 +3,7 @@
require "cache"
RSpec.describe Cache do
let :cache do
Cache.new
end
subject(:cache) { Cache.new }
it "supports exist?" do
cache.write("testing", 1.1)
@ -104,4 +102,24 @@ RSpec.describe Cache do
expect(cache.redis.ttl("#{cache.namespace}:foo:bar")).to eq(180)
end
describe ".fetch" do
subject(:fetch_value) { cache.fetch("my_key") { "bob" } }
context "when the cache is corrupt" do
before do
cache.delete("my_key")
Discourse.redis.setex(cache.normalize_key("my_key"), described_class::MAX_CACHE_AGE, "")
end
it "runs and return the provided block" do
expect(fetch_value).to eq("bob")
end
it "generates a new cache entry" do
fetch_value
expect(cache.read("my_key")).to eq("bob")
end
end
end
end