Skip to content

Commit

Permalink
Handle max_age: nil
Browse files Browse the repository at this point in the history
  • Loading branch information
brian-kephart committed Jan 3, 2024
1 parent ef6be0a commit 044f4a7
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 9 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ Solid Cache supports these options in addition to the standard `ActiveSupport::C
- `error_handler` - a Proc to call to handle any `ActiveRecord::ActiveRecordError`s that are raises (default: log errors as warnings)
- `expiry_batch_size` - the batch size to use when deleting old records (default: `100`)
- `expiry_method` - what expiry method to use `thread` or `job` (default: `thread`)
- `max_age` - the maximum age of entries in the cache (default: `2.weeks.to_i`)
- `max_age` - the maximum age of entries in the cache (default: `2.weeks.to_i`). Can be set to `nil`, but this is not recommended unless using `max_entries` to limit the size of the cache.
- `max_entries` - the maximum number of entries allowed in the cache (default: `nil`, meaning no limit)
- `cluster` - a Hash of options for the cache database cluster, e.g `{ shards: [:database1, :database2, :database3] }`
- `clusters` - and Array of Hashes for multiple cache clusters (ignored if `:cluster` is set)
Expand Down
25 changes: 18 additions & 7 deletions app/models/solid_cache/entry.rb
Original file line number Diff line number Diff line change
Expand Up @@ -140,14 +140,25 @@ def to_binary(key)

def expiry_candidate_ids(count, max_age:, max_entries:)
cache_full = max_entries && max_entries < id_range
min_created_at = max_age.seconds.ago

uncached do
order(:id)
.limit(count * 3)
.pluck(:id, :created_at)
.filter_map { |id, created_at| id if cache_full || created_at < min_created_at }
.sample(count)
if max_age
min_created_at = max_age.seconds.ago

uncached do
order(:id)
.limit(count * 3)
.pluck(:id, :created_at)
.filter_map { |id, created_at| id if cache_full || created_at < min_created_at }
.sample(count)
end
elsif cache_full
uncached do
order(:id)
.limit(count)
.pluck(:id)
end
else
[]
end
end
end
Expand Down
2 changes: 1 addition & 1 deletion test/unit/expiry_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ class SolidCache::ExpiryTest < ActiveSupport::TestCase
end

test "expires records when the cache is full (#{expiry_method})" do
@cache = lookup_store(expiry_batch_size: 3, max_age: 2.weeks, max_entries: 2, expiry_method: expiry_method)
@cache = lookup_store(expiry_batch_size: 3, max_age: nil, max_entries: 2, expiry_method: expiry_method)
default_shard_keys = shard_keys(@cache, :default)
@cache.write(default_shard_keys[0], 1)
@cache.write(default_shard_keys[1], 2)
Expand Down

0 comments on commit 044f4a7

Please sign in to comment.