Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

Added universal collection caching for Platform/Storefront API (#11245)

Damian Legawiec727d9ddc2364
diff --git a/.circleci/config.yml b/.circleci/config.yml
index 39137afae4..ab6634c800 100644
--- a/.circleci/config.yml
+++ b/.circleci/config.yml
@@ -10,11 +10,13 @@ defaults: &defaults
working_directory: ~/spree
docker:
- image: &ruby_image circleci/ruby:2.7-node-browsers
+ - image: &redis_image circleci/redis:6.2-alpine
defaults_3_0: &defaults_3_0
<<: *defaults
docker:
- image: &ruby_3_0_image circleci/ruby:3.0-node-browsers
+ - image: *redis_image
run_tests: &run_tests
<<: *defaults
@@ -104,6 +106,7 @@ jobs:
DB_USERNAME: postgres
docker:
- image: *ruby_image
+ - image: *redis_image
- image: &postgres_image circleci/postgres:12-alpine
environment:
POSTGRES_USER: postgres
@@ -115,6 +118,7 @@ jobs:
docker:
- image: *ruby_3_0_image
- image: *postgres_image
+ - image: *redis_image
tests_postgres_rails_6_0:
<<: *tests_postgres
@@ -183,6 +187,7 @@ jobs:
COVERAGE_DIR: /tmp/workspace/simplecov
docker:
- image: *ruby_image
+ - image: *redis_image
- image: &mysql_image circleci/mysql:8-ram
tests_mysql_ruby_3_0:
@@ -191,6 +196,7 @@ jobs:
<<: *mysql_environment
docker:
- image: *ruby_3_0_image
+ - image: *redis_image
- image: *mysql_image
command: [--default-authentication-plugin=mysql_native_password]
steps:
diff --git a/api/app/controllers/concerns/spree/api/v2/caching.rb b/api/app/controllers/concerns/spree/api/v2/caching.rb
new file mode 100644
index 0000000000..85ad4dad76
--- /dev/null
+++ b/api/app/controllers/concerns/spree/api/v2/caching.rb
@@ -0,0 +1,33 @@
+module Spree
+ module Api
+ module V2
+ module Caching
+ extend ActiveSupport::Concern
+
+ def collection_cache_key(collection)
+ unscoped_collection = collection.unscope(:includes).unscope(:order)
+ cache_key_parts = [
+ self.class.to_s,
+ unscoped_collection.maximum(:updated_at),
+ unscoped_collection.ids,
+ resource_includes,
+ sparse_fields,
+ serializer_params,
+ params[:sort]&.strip,
+ params[:page]&.strip,
+ params[:per_page]&.strip,
+ ].flatten.join('-')
+
+ Digest::MD5.hexdigest(cache_key_parts)
+ end
+
+ def collection_cache_opts
+ {
+ namespace: Spree::Api::Config[:api_v2_collection_cache_namespace],
+ expires_in: Spree::Api::Config[:api_v2_collection_cache_ttl],
+ }
+ end
+ end
+ end
+ end
+end
diff --git a/api/app/controllers/spree/api/v2/resource_controller.rb b/api/app/controllers/spree/api/v2/resource_controller.rb
index f93969b5fc..c9661e7360 100644
--- a/api/app/controllers/spree/api/v2/resource_controller.rb
+++ b/api/app/controllers/spree/api/v2/resource_controller.rb
@@ -3,9 +3,14 @@ module Spree
module V2
class ResourceController < ::Spree::Api::V2::BaseController
include Spree::Api::V2::CollectionOptionsHelpers
+ include Spree::Api::V2::Caching
def index
- render_serialized_payload { serialize_collection(paginated_collection) }
+ render_serialized_payload do
+ Rails.cache.fetch(collection_cache_key(paginated_collection), collection_cache_opts) do
+ serialize_collection(paginated_collection)
+ end
+ end
end
def show
diff --git a/api/app/controllers/spree/api/v2/storefront/account/orders_controller.rb b/api/app/controllers/spree/api/v2/storefront/account/orders_controller.rb
index 3609b54eb8..5119b3b6de 100644
--- a/api/app/controllers/spree/api/v2/storefront/account/orders_controller.rb
+++ b/api/app/controllers/spree/api/v2/storefront/account/orders_controller.rb
@@ -38,6 +38,10 @@ module Spree
def resource_finder
Spree::Api::Dependencies.storefront_completed_order_finder.constantize
end
+
+ def model_class
+ Spree::Order
+ end
end
end
end
diff --git a/api/app/models/spree/api_configuration.rb b/api/app/models/spree/api_configuration.rb
index de34fafeaf..ddaf6f9cda 100644
--- a/api/app/models/spree/api_configuration.rb
+++ b/api/app/models/spree/api_configuration.rb
@@ -1,7 +1,9 @@
module Spree
class ApiConfiguration < Preferences::Configuration
preference :requires_authentication, :boolean, default: true
- preference :api_v2_cache_ttl, :integer, default: 3600 # 1 hour in seconds
+ preference :api_v2_serializers_cache_ttl, :integer, default: 3600 # 1 hour in seconds
+ preference :api_v2_collection_cache_ttl, :integer, default: 3600 # 1 hour in seconds
+ preference :api_v2_collection_cache_namespace, :string, default: 'api_v2_collection_cache'
preference :api_v2_content_type, :string, default: 'application/vnd.api+json'
preference :api_v2_per_page_limit, :integer, default: 100
end
diff --git a/api/app/serializers/spree/api/v2/base_serializer.rb b/api/app/serializers/spree/api/v2/base_serializer.rb
index c439b82c54..bce162ea4b 100644
--- a/api/app/serializers/spree/api/v2/base_serializer.rb
+++ b/api/app/serializers/spree/api/v2/base_serializer.rb
@@ -7,7 +7,7 @@ module Spree
# to learn more about caching, please refer to:
# https://github.com/jsonapi-serializer/jsonapi-serializer#caching
# https://guides.rubyonrails.org/caching_with_rails.html#low-level-caching
- cache_options(store: Rails.cache, namespace: 'jsonapi-serializer', expires_in: Spree::Api::Config[:api_v2_cache_ttl])
+ cache_options(store: Rails.cache, namespace: 'jsonapi-serializer', expires_in: Spree::Api::Config[:api_v2_serializers_cache_ttl])
def self.record_cache_options(options, fieldset, include_list, params)
opts = options.dup
diff --git a/api/app/serializers/spree/api/v2/platform/product_serializer.rb b/api/app/serializers/spree/api/v2/platform/product_serializer.rb
index 748adcebc3..b492f430b1 100644
--- a/api/app/serializers/spree/api/v2/platform/product_serializer.rb
+++ b/api/app/serializers/spree/api/v2/platform/product_serializer.rb
@@ -59,7 +59,7 @@ module Spree
has_many :variants
has_many :option_types
has_many :product_properties
- has_many :taxons do |object, params|
+ has_many :taxons, serializer: :taxon, record_type: :taxon do |object, params|
object.taxons_for_store(params[:store])
end
diff --git a/api/app/serializers/spree/v2/storefront/product_serializer.rb b/api/app/serializers/spree/v2/storefront/product_serializer.rb
index 25cfbfd7a7..409b0ca619 100644
--- a/api/app/serializers/spree/v2/storefront/product_serializer.rb
+++ b/api/app/serializers/spree/v2/storefront/product_serializer.rb
@@ -48,7 +48,7 @@ module Spree
has_many :option_types
has_many :product_properties
- has_many :taxons do |object, params|
+ has_many :taxons, serializer: :taxon, record_type: :taxon do |object, params|
object.taxons_for_store(params[:store])
end
diff --git a/api/spec/requests/spree/api/v2/caching_spec.rb b/api/spec/requests/spree/api/v2/caching_spec.rb
index c92721bf21..2af046053f 100644
--- a/api/spec/requests/spree/api/v2/caching_spec.rb
+++ b/api/spec/requests/spree/api/v2/caching_spec.rb
@@ -1,55 +1,149 @@
require 'spec_helper'
describe 'API v2 Caching spec', type: :request do
+ include_context 'API v2 tokens'
+
let!(:product) { create(:product, name: 'Some name', stores: [store]) }
let(:store) { Spree::Store.default }
- let(:cache_store) { Spree::V2::Storefront::ProductSerializer.cache_store_instance }
- let(:cache_entry) { cache_store.read(product, namespace: cache_namespace) }
+ before(:all) { ActionController::Base.perform_caching = true }
+ after(:all) { ActionController::Base.perform_caching = false }
before do
- ActionController::Base.perform_caching = true
+ store.update!(supported_currencies: 'USD,CAD')
+ Rails.cache.clear
end
after do
- ActionController::Base.perform_caching = false
Rails.cache.clear
end
- context 'auto expiration' do
- let(:cache_namespace) { "jsonapi-serializer-usd-en-#{store.cache_key_with_version}" }
+ context 'collections caching' do
+ let(:cache_namespace) { 'api_v2_collection_cache' }
+ let!(:products) { create_list(:product_in_stock, 5, stores: [store]) }
+ let(:user) { create(:user) }
+
+ before do
+ products.each { |product| product.update_columns(updated_at: 1.day.ago, created_at: 1.day.ago) }
+ products.last.update(name: 'Updated name')
+ end
+
+ def cache_entries
+ Rails.cache.redis.keys.find_all { |k| k.start_with?(cache_namespace) }
+ end
+
+ it 'caches collection' do
+ expect(cache_entries).to be_empty
+
+ get '/api/v2/storefront/products'
+
+ expect(cache_entries).not_to be_empty
+ expect(cache_entries.size).to eq(1)
+
+ get '/api/v2/storefront/products?include=variants'
+ expect(cache_entries.size).to eq(2)
+
+ get '/api/v2/storefront/products'
+ expect(cache_entries.size).to eq(2)
+
+ get '/api/v2/storefront/products?page=2'
+ expect(cache_entries.size).to eq(3)
+
+ get '/api/v2/storefront/products?page=2'
+ expect(cache_entries.size).to eq(3)
+
+ get '/api/v2/storefront/products?per_page=1'
+ expect(cache_entries.size).to eq(4)
+
+ get '/api/v2/storefront/products?per_page=1'
+ expect(cache_entries.size).to eq(4)
+
+ get '/api/v2/storefront/products?currency=CAD'
+ expect(cache_entries.size).to eq(5)
+
+ get '/api/v2/storefront/products?currency=CAD'
+ expect(cache_entries.size).to eq(5)
- it 'auto expire cache after record being updated' do
- get "/api/v2/storefront/products/#{product.id}"
+ get '/api/v2/storefront/products?filter[name]=Updated'
+ expect(cache_entries.size).to eq(6)
- expect(json_response['data']).to have_attribute('name').with_value('Some name')
+ get '/api/v2/storefront/products', headers: headers_bearer
+ expect(cache_entries.size).to eq(7)
+ end
+
+ it 'auto expires cache when store is updated' do
+ get '/api/v2/storefront/products'
+ expect(cache_entries.size).to eq(1)
+
+ # expire all cache when store is updates
+ store.update_column(:updated_at, 1.day.ago)
+
+ get '/api/v2/storefront/products'
+ expect(cache_entries.size).to eq(2)
+ end
+
+ it 'auto expires when new record is added to collection' do
+ get '/api/v2/storefront/products'
+ expect(cache_entries.size).to eq(1)
+
+ create(:product, name: 'Updated name', stores: [store])
+
+ get '/api/v2/storefront/products'
+ expect(cache_entries.size).to eq(2)
+ end
- expect(cache_entry).not_to be_nil
- expect(cache_entry[:attributes].as_json).to eq(json_response[:data][:attributes])
+ it 'auto expires when record is updated' do
+ get '/api/v2/storefront/products'
+ expect(cache_entries.size).to eq(1)
- product.update(name: 'Something else')
- expect(cache_store.read(product, namespace: cache_namespace)).to be_nil
+ Timecop.travel Time.current + 1.day do
+ products.last.touch
+ end
- get "/api/v2/storefront/products/#{product.id}"
- expect(cache_store.read(product, namespace: cache_namespace)).not_to be_nil
- expect(json_response['data']).to have_attribute('name').with_value('Something else')
+ get '/api/v2/storefront/products'
+ expect(cache_entries.size).to eq(2)
end
end
- context 'currency and user' do
- include_context 'API v2 tokens'
+ context 'serialiers caching' do
+ let(:cache_store) { Spree::V2::Storefront::ProductSerializer.cache_store_instance }
+ let(:cache_entry) { cache_store.read(product, namespace: cache_namespace) }
+
+ context 'auto expiration' do
+ let(:cache_namespace) { "jsonapi-serializer-usd-en-#{store.cache_key_with_version}" }
+
+ it 'auto expire cache after record being updated' do
+ get "/api/v2/storefront/products/#{product.id}"
+
+ expect(json_response['data']).to have_attribute('name').with_value('Some name')
+
+ expect(cache_entry).not_to be_nil
+ expect(cache_entry[:attributes].as_json).to eq(json_response[:data][:attributes])
+
+ product.update(name: 'Something else')
+ expect(cache_store.read(product, namespace: cache_namespace)).to be_nil
+
+ get "/api/v2/storefront/products/#{product.id}"
+ expect(cache_store.read(product, namespace: cache_namespace)).not_to be_nil
+ expect(json_response['data']).to have_attribute('name').with_value('Something else')
+ end
+ end
+
+ context 'currency and user' do
+ include_context 'API v2 tokens'
- before { store.update!(supported_currencies: 'USD,EUR', supported_locales: 'en,de') }
+ before { store.update!(supported_currencies: 'USD,EUR', supported_locales: 'en,de') }
- let!(:user) { create(:user) }
- let(:currency) { 'EUR' }
- let(:locale) { 'de' }
- let(:cache_namespace) { "jsonapi-serializer-eur-de-#{store.cache_key_with_version}-#{user.cache_key_with_version}" }
+ let!(:user) { create(:user) }
+ let(:currency) { 'EUR' }
+ let(:locale) { 'de' }
+ let(:cache_namespace) { "jsonapi-serializer-eur-de-#{store.cache_key_with_version}-#{user.cache_key_with_version}" }
- it 'includes currency and signed user in the cache key' do
- get "/api/v2/storefront/products/#{product.id}?currency=#{currency}&locale=#{locale}", headers: headers_bearer
+ it 'includes currency and signed user in the cache key' do
+ get "/api/v2/storefront/products/#{product.id}?currency=#{currency}&locale=#{locale}", headers: headers_bearer
- expect(cache_entry).not_to be_nil
+ expect(cache_entry).not_to be_nil
+ end
end
end
end
diff --git a/common_spree_dependencies.rb b/common_spree_dependencies.rb
index f89cea9212..b670e11210 100644
--- a/common_spree_dependencies.rb
+++ b/common_spree_dependencies.rb
@@ -46,6 +46,7 @@ end
group :test, :development do
gem 'awesome_print'
gem 'gem-release'
+ gem 'redis'
gem 'rubocop', '~> 1.0.0', require: false # bumped
gem 'rubocop-rspec', require: false
gem 'pry-byebug'
diff --git a/core/lib/generators/spree/dummy/templates/rails/test.rb b/core/lib/generators/spree/dummy/templates/rails/test.rb
index eb005f5cff..486b3a594b 100644
--- a/core/lib/generators/spree/dummy/templates/rails/test.rb
+++ b/core/lib/generators/spree/dummy/templates/rails/test.rb
@@ -35,4 +35,6 @@ Dummy::Application.configure do
config.active_support.deprecation = :stderr
config.active_job.queue_adapter = :test
+
+ config.cache_store = :redis_cache_store
end
diff --git a/core/lib/spree/testing_support/rspec_retry_config.rb b/core/lib/spree/testing_support/rspec_retry_config.rb
index fb529791d0..73f6686743 100644
--- a/core/lib/spree/testing_support/rspec_retry_config.rb
+++ b/core/lib/spree/testing_support/rspec_retry_config.rb
@@ -7,4 +7,9 @@ RSpec.configure do |config|
config.around :each, type: :feature do |ex|
ex.run_with_retry retry: ENV.fetch('RSPEC_RETRY_RETRY_COUNT', 3).to_i
end
+
+ # callback to be run between retries
+ config.retry_callback = proc do |ex|
+ Rails.cache.clear
+ end
end