Skip to content

Commit

Permalink
bug(caching) - Add cache key version to Subscriptions::ChargeCacheSer…
Browse files Browse the repository at this point in the history
…vice (#2756)

## Description

If fees were present in the cache they would be duplicated when moving
to the new caching scheme.
this PR adds a key that we can bump when making changes to the caching.
  • Loading branch information
nudded authored Oct 30, 2024
1 parent 660fa7a commit 0d19bbc
Show file tree
Hide file tree
Showing 3 changed files with 8 additions and 2 deletions.
5 changes: 5 additions & 0 deletions app/services/subscriptions/charge_cache_service.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

module Subscriptions
class ChargeCacheService
CACHE_KEY_VERSION = '1'

def self.expire_for_subscription(subscription)
subscription.plan.charges.includes(:filters)
.find_each { expire_for_subscription_charge(subscription:, charge: _1) }
Expand All @@ -21,9 +23,12 @@ def initialize(subscription:, charge:, charge_filter: nil)
@charge_filter = charge_filter
end

# IMPORTANT
# when making changes here, please make sure to bump the cache key so old values are immediately invalidated!
def cache_key
[
'charge-usage',
CACHE_KEY_VERSION,
charge.id,
subscription.id,
charge.updated_at.iso8601,
Expand Down
1 change: 1 addition & 0 deletions spec/services/invoices/customer_usage_service_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@
it 'uses the Rails cache' do
key = [
'charge-usage',
Subscriptions::ChargeCacheService::CACHE_KEY_VERSION,
charge.id,
subscription.id,
charge.updated_at.iso8601
Expand Down
4 changes: 2 additions & 2 deletions spec/services/subscriptions/charge_cache_service_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,15 @@
describe '#cache_key' do
it 'returns the cache key' do
expect(cache_service.cache_key)
.to eq("charge-usage/#{charge.id}/#{subscription.id}/#{charge.updated_at.iso8601}")
.to eq("charge-usage/#{described_class::CACHE_KEY_VERSION}/#{charge.id}/#{subscription.id}/#{charge.updated_at.iso8601}")
end

context 'with a charge filter' do
let(:charge_filter) { create(:charge_filter) }

it 'returns the cache key with the charge filter' do
expect(cache_service.cache_key)
.to eq("charge-usage/#{charge.id}/#{subscription.id}/#{charge.updated_at.iso8601}/#{charge_filter.id}/#{charge_filter.updated_at.iso8601}")
.to eq("charge-usage/#{described_class::CACHE_KEY_VERSION}/#{charge.id}/#{subscription.id}/#{charge.updated_at.iso8601}/#{charge_filter.id}/#{charge_filter.updated_at.iso8601}")
end
end
end
Expand Down

0 comments on commit 0d19bbc

Please sign in to comment.