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
Lock stock level counter reads that decide a write
Łukasz Adamczyk5a76ce118500
diff --git a/spree/api/app/controllers/spree/api/v3/admin/stock_levels_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/stock_levels_controller.rbindex e735e23793..92202e89b5 100644--- a/spree/api/app/controllers/spree/api/v3/admin/stock_levels_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/stock_levels_controller.rb@@ -24,7 +24,11 @@ module Spreereturn render_validation_error(count_on_hand_errors) if new_count.nil?end- ActiveRecord::Base.transaction do+ # Locked around the read: the delta is worked out from the count+ # this request first saw, so two admins correcting the same level at+ # once would otherwise each apply a delta measured against a shelf+ # the other had already moved, and both edits would land.+ @resource.with_lock do@resource.update!(attributes) if attributes.any?adjust_count_on_hand(new_count, reason) unless new_count.nil?enddiff --git a/spree/core/app/models/spree/stock_level.rb b/spree/core/app/models/spree/stock_level.rbindex 11be6196bf..f72e0cdcfe 100644--- a/spree/core/app/models/spree/stock_level.rb+++ b/spree/core/app/models/spree/stock_level.rb@@ -112,13 +112,20 @@ module Spree# not drive the counter below zero, which would make the level look more# available than it is.#+ # Locked, unlike its counterpart {#adjust_allocated_count}: the cap is read+ # from the same counter the write then moves, so two concurrent releases+ # reading before either writes would both pass a cap that only covered one+ # of them.+ ## @param units [Integer]# @return [void]def release_allocated_count(units)- withdrawn = [units.abs, allocated_count].min- return if withdrawn.zero?+ with_lock do+ withdrawn = [units.abs, allocated_count].min+ next if withdrawn.zero?- adjust_allocated_count(-withdrawn)+ adjust_allocated_count(-withdrawn)+ endend# Physical stock minus allocated units at this stock level. Distinct fromdiff --git a/spree/core/lib/tasks/typed_stock_movements_migration.rake b/spree/core/lib/tasks/typed_stock_movements_migration.rakeindex 71f4974f07..471b8a908a 100644--- a/spree/core/lib/tasks/typed_stock_movements_migration.rake+++ b/spree/core/lib/tasks/typed_stock_movements_migration.rake@@ -161,7 +161,10 @@ module Spreestock_level = fulfillment.stock_location.stock_level_or_create(variant)# A direct column write, not a `received` movement: no goods# arrived. The allocation below is what gives the jump a cause.- stock_level.update_columns(count_on_hand: stock_level.count_on_hand + quantity, updated_at: Time.current)+ #+ # Incremented in the database rather than read and written back, so a+ # count that moved since it was read is added to rather than replaced.+ Spree::StockLevel.update_counters(stock_level.id, count_on_hand: quantity, touch: true)fulfillment.stock_location.allocate(variant, quantity, fulfillment)endenddiff --git a/spree/core/spec/models/spree/stock_level_spec.rb b/spree/core/spec/models/spree/stock_level_spec.rbindex ac8cd55445..0deb528f39 100644--- a/spree/core/spec/models/spree/stock_level_spec.rb+++ b/spree/core/spec/models/spree/stock_level_spec.rb@@ -492,6 +492,39 @@ describe Spree::StockLevel, type: :model doexpect(subject.reload.allocated_count).to eq(0)end++ # The cap is read from the counter the write then moves, so it only holds+ # if both happen as one step. Needs a database with real parallel+ # connections and row locking, and needs to run outside the test+ # transaction — a transaction never blocks on its own FOR UPDATE, so+ # threads sharing one connection interleave freely and prove nothing.+ context 'released concurrently', if: ENV['DB'] == 'postgres' do+ self.use_transactional_tests = false++ let!(:concurrent_level) { create(:stock_level, adjust_count_on_hand: false) }++ after do+ location = concurrent_level.stock_location+ product = concurrent_level.variant.product+ Spree::StockMovement.where(stock_level_id: concurrent_level.id).delete_all+ location.really_destroy!+ product.really_destroy!+ end++ it 'never withdraws more promise than the level holds' do+ concurrent_level.adjust_allocated_count(5)++ 4.times.map do+ Thread.new do+ ActiveRecord::Base.connection_pool.with_connection do+ Spree::StockLevel.find(concurrent_level.id).release_allocated_count(5)+ end+ end+ end.each(&:join)++ expect(concurrent_level.reload.allocated_count).to eq(0)+ end+ endenddescribe '#available_count' do