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.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Improve Products API response times (#13722)
Damian Legawiecb3f63051f773
diff --git a/spree/api/app/controllers/concerns/spree/api/v3/http_caching.rb b/spree/api/app/controllers/concerns/spree/api/v3/http_caching.rbindex 9723f016b6..5f3afbba82 100644--- a/spree/api/app/controllers/concerns/spree/api/v3/http_caching.rb+++ b/spree/api/app/controllers/concerns/spree/api/v3/http_caching.rb@@ -12,7 +12,7 @@ module Spreeextend ActiveSupport::Concernincluded do- before_action :set_vary_headers+ after_action :set_vary_headersendprotected@@ -69,13 +69,13 @@ module Spreeprivate# Build a cache key for a collection- # Includes: query params, pagination, expand, currency, locale- # Strips order to avoid PostgreSQL errors with DISTINCT + subquery ORDER BY expressions+ # Includes: latest updated_at, total count, query params, pagination, expand, currency, localedef collection_cache_key(collection)parts = [- collection.reorder(nil).cache_key_with_version,+ collection.map(&:updated_at).max&.to_i,+ @pagy&.count,params[:expand],- params[:q],+ params[:q]&.to_json,params[:page],params[:limit],current_currency,diff --git a/spree/api/app/controllers/spree/api/v3/resource_controller.rb b/spree/api/app/controllers/spree/api/v3/resource_controller.rbindex 4e5e387fc2..a5f891949b 100644--- a/spree/api/app/controllers/spree/api/v3/resource_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/resource_controller.rb@@ -103,6 +103,7 @@ module Spreeend# Override in subclass to disable distinct (e.g., for custom sorting with computed columns)+ # @return [Boolean] whether to apply distinct to the collectiondef collection_distinct?trueend@@ -112,6 +113,8 @@ module Spreecollectionend+ # Override in subclass to specify collection includes+ # @return [Array<Symbol>] the includes to apply to the collectiondef collection_includes[]end@@ -122,16 +125,19 @@ module Spreeend# Pagination parameters+ # @return [Integer] the current page numberdef pageparams[:page]&.to_i || 1end+ # @return [Integer] the number of items per pagedef limitlimit_param = params[:limit]&.to_i || 25[limit_param, 100].min # Max 100 per pageend# Metadata for collection responses+ # @return [Hash] pagination metadatadef collection_meta(_collection)return {} unless @pagydiff --git a/spree/api/spec/controllers/concerns/spree/api/v3/http_caching_spec.rb b/spree/api/spec/controllers/concerns/spree/api/v3/http_caching_spec.rbnew file mode 100644index 0000000000..2e4663d46e--- /dev/null+++ b/spree/api/spec/controllers/concerns/spree/api/v3/http_caching_spec.rb@@ -0,0 +1,207 @@+require 'spec_helper'++RSpec.describe Spree::Api::V3::Store::ProductsController, type: :controller do+ render_views++ include_context 'API v3 Store'++ let!(:product) { create(:product, stores: [store], status: 'active') }+ let!(:product2) { create(:product, stores: [store], status: 'active') }++ before do+ request.headers['X-Spree-Api-Key'] = api_key.token+ end++ describe 'Spree::Api::V3::HttpCaching' do+ describe 'Vary headers' do+ context 'for guest users' do+ it 'sets Vary header for CDN caching' do+ get :index++ expect(response.headers['Vary']).to eq('Accept, x-spree-currency, x-spree-locale')+ end+ end++ context 'for authenticated users' do+ before do+ request.headers['Authorization'] = "Bearer #{jwt_token}"+ end++ it 'sets Cache-Control to private, no-store' do+ get :index++ expect(response.headers['Cache-Control']).to include('private')+ expect(response.headers['Cache-Control']).to include('no-store')+ end++ it 'does not set Vary header' do+ get :index++ expect(response.headers['Vary']).to be_nil+ end+ end+ end++ describe '#cache_collection' do+ context 'for guest users' do+ it 'sets ETag header' do+ get :index++ expect(response.headers['ETag']).to be_present+ end++ it 'sets Cache-Control with public and max-age' do+ get :index++ expect(response.headers['Cache-Control']).to include('public')+ expect(response.headers['Cache-Control']).to include('max-age=300')+ end++ it 'sets stale-while-revalidate' do+ get :index++ expect(response.headers['Cache-Control']).to include('stale-while-revalidate=30')+ end++ it 'returns 200 when ETag does not match' do+ request.headers['If-None-Match'] = '"stale-etag"'+ get :index++ expect(response).to have_http_status(:ok)+ end++ it 'changes ETag when a product is updated' do+ get :index+ original_etag = response.headers['ETag']++ Timecop.travel(1.minute.from_now) do+ product.update!(name: 'Updated Product Name')++ get :index+ new_etag = response.headers['ETag']++ expect(new_etag).not_to eq(original_etag)+ end+ end++ it 'changes ETag when a product is added' do+ get :index+ original_etag = response.headers['ETag']++ create(:product, stores: [store], status: 'active')++ get :index+ new_etag = response.headers['ETag']++ expect(new_etag).not_to eq(original_etag)+ end++ it 'changes ETag when query params change' do+ get :index+ original_etag = response.headers['ETag']++ get :index, params: { q: { name_cont: 'test' } }+ filtered_etag = response.headers['ETag']++ expect(filtered_etag).not_to eq(original_etag)+ end++ it 'changes ETag when page changes' do+ get :index, params: { page: 1, limit: 1 }+ page1_etag = response.headers['ETag']++ get :index, params: { page: 2, limit: 1 }+ page2_etag = response.headers['ETag']++ expect(page2_etag).not_to eq(page1_etag)+ end++ it 'changes ETag when currency changes' do+ get :index+ original_etag = response.headers['ETag']++ request.headers['x-spree-currency'] = 'EUR'+ get :index+ eur_etag = response.headers['ETag']++ expect(eur_etag).not_to eq(original_etag)+ end+ end++ context 'for authenticated users' do+ before do+ request.headers['Authorization'] = "Bearer #{jwt_token}"+ end++ it 'does not set ETag header' do+ get :index++ expect(response.headers['ETag']).to be_nil+ end++ it 'does not return 304' do+ get :index++ expect(response).to have_http_status(:ok)+ end+ end+ end++ describe '#cache_resource' do+ context 'for guest users' do+ it 'sets ETag header' do+ get :show, params: { id: product.prefixed_id }++ expect(response.headers['ETag']).to be_present+ end++ it 'sets Cache-Control with public' do+ get :show, params: { id: product.prefixed_id }++ expect(response.headers['Cache-Control']).to include('public')+ end++ it 'returns 304 Not Modified when resource has not changed' do+ get :show, params: { id: product.prefixed_id }+ etag = response.headers['ETag']++ request.headers['If-None-Match'] = etag+ get :show, params: { id: product.prefixed_id }++ expect(response).to have_http_status(:not_modified)+ end++ it 'returns 200 when resource has changed' do+ get :show, params: { id: product.prefixed_id }+ etag = response.headers['ETag']++ product.update!(name: 'Updated Name')++ request.headers['If-None-Match'] = etag+ get :show, params: { id: product.prefixed_id }++ expect(response).to have_http_status(:ok)+ end+ end++ context 'for authenticated users' do+ before do+ request.headers['Authorization'] = "Bearer #{jwt_token}"+ end++ it 'does not set ETag header' do+ get :show, params: { id: product.prefixed_id }++ expect(response.headers['ETag']).to be_nil+ end++ it 'sets Cache-Control to private, no-store' do+ get :show, params: { id: product.prefixed_id }++ expect(response.headers['Cache-Control']).to include('private')+ expect(response.headers['Cache-Control']).to include('no-store')+ end+ end+ end+ end+enddiff --git a/spree/core/app/models/concerns/spree/product_scopes.rb b/spree/core/app/models/concerns/spree/product_scopes.rbindex 98d10fe994..59571ffb2c 100644--- a/spree/core/app/models/concerns/spree/product_scopes.rb+++ b/spree/core/app/models/concerns/spree/product_scopes.rb@@ -268,7 +268,7 @@ module Spreedef self.not_discontinued(only_not_discontinued = true)if only_not_discontinued != '0' && only_not_discontinued- where(discontinue_on: [nil, Time.current..])+ where(discontinue_on: [nil, Time.current.beginning_of_minute..])elseallend@@ -286,7 +286,10 @@ module Spree# Can't use add_search_scope for this as it needs a default argumentdef self.available(available_on = nil, currency = nil)scope = not_discontinued.where(status: 'active')- scope = scope.where("#{Product.quoted_table_name}.available_on <= ?", available_on) if available_on+ if available_on+ available_on = available_on.beginning_of_minute if available_on.respond_to?(:beginning_of_minute)+ scope = scope.where("#{Product.quoted_table_name}.available_on <= ?", available_on)+ endunless Spree::Config.show_products_without_pricecurrency ||= Spree::Store.default.default_currencydiff --git a/spree/core/app/models/spree/variant.rb b/spree/core/app/models/spree/variant.rbindex dbbe670b82..9c213e209b 100644--- a/spree/core/app/models/spree/variant.rb+++ b/spree/core/app/models/spree/variant.rb@@ -103,7 +103,7 @@ module Spreescope :not_discontinued, lambda {where(arel_table[:discontinue_on].eq(nil).or(- arel_table[:discontinue_on].gteq(Time.current)+ arel_table[:discontinue_on].gteq(Time.current.beginning_of_minute)))}