Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions lib/identity_cache.rb
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,11 @@ class << self
mattr_accessor :fetch_read_only_records
self.fetch_read_only_records = true

# Raise an exception if the record returned from the cache don't match the id
# the user expected
mattr_accessor :raise_on_id_mismatch
self.raise_on_id_mismatch = false

mattr_accessor :lazy_load_associated_classes
self.lazy_load_associated_classes = Gem::Version.new(IdentityCache::VERSION) >= Gem::Version.new("0.6")

Expand Down
7 changes: 6 additions & 1 deletion lib/identity_cache/query_api.rb
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
module IdentityCache
class CorruptedCache < StandardError
end

module QueryAPI
extend ActiveSupport::Concern

Expand Down Expand Up @@ -27,7 +30,9 @@ def fetch_by_id(id, options={})
coder = IdentityCache.fetch(rails_cache_key(id)){ coder_from_record(object = resolve_cache_miss(id)) }
object ||= record_from_coder(coder)
if object && object.id.to_s != id.to_s
IdentityCache.logger.error "[IDC id mismatch] fetch_by_id_requested=#{id} fetch_by_id_got=#{object.id} for #{object.inspect[(0..100)]}"
message = "[IDC id mismatch] fetch_by_id_requested=#{id} fetch_by_id_got=#{object.id} for #{object.inspect[(0..100)]}"
IdentityCache.logger.error message
raise CorruptedCache.new(message) if IdentityCache.raise_on_id_mismatch
end
object
end
Expand Down
9 changes: 9 additions & 0 deletions test/fetch_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,15 @@ def test_fetch_with_garbage_input
assert_nil Item.fetch_by_id('garbage')
end

def test_fetch_with_corrupted_cache
attributes = @record.attributes_before_type_cast
attributes["id"] += 1
IdentityCache.cache.expects(:fetch).with(@blob_key).returns(class: @record.class.name, attributes: attributes)

IdentityCache.raise_on_id_mismatch = true
assert_raises(IdentityCache::CorruptedCache) { Item.fetch(1) }
end

def test_fetch_cache_hit
IdentityCache.cache.expects(:fetch).with(@blob_key).returns(@cached_value)

Expand Down