Sha256: 5a5372871c83adf0c43e1d68b9b84a38c91e6bbd4d5fd4e3297fa2852b398a09

Contents?: true

Size: 1.14 KB

Versions: 42

Compression:

Stored size: 1.14 KB

Contents

# frozen_string_literal: true

module Spree
  class OrderMutex < Spree::Base
    class LockFailed < StandardError; end

    belongs_to :order, class_name: "Spree::Order"

    scope :expired, -> { where(arel_table[:created_at].lteq(Spree::Config[:order_mutex_max_age].seconds.ago)) }

    class << self
      # Obtain a lock on an order, execute the supplied block and then release the lock.
      # Raise a LockFailed exception immediately if we cannot obtain the lock.
      # We raise instead of blocking to avoid tying up multiple server processes waiting for the lock.
      def with_lock!(order)
        raise ArgumentError, "order must be supplied" if order.nil?

        # limit the maximum lock time just in case a lock is somehow left in place accidentally
        expired.where(order: order).delete_all

        begin
          order_mutex = create!(order: order)
        rescue ActiveRecord::RecordNotUnique
          error = LockFailed.new("Could not obtain lock on order #{order.id}")
          logger.error error.inspect
          raise error
        end

        yield
      ensure
        order_mutex.destroy if order_mutex
      end
    end
  end
end

Version data entries

42 entries across 42 versions & 2 rubygems

Version Path
solidus_core-2.6.3 app/models/spree/order_mutex.rb
solidus_core-2.8.0 app/models/spree/order_mutex.rb
solidus_core-2.7.1 app/models/spree/order_mutex.rb
solidus_core-2.6.2 app/models/spree/order_mutex.rb
solidus_core_devise_token_auth-2.8.0.alpha.14 app/models/spree/order_mutex.rb
solidus_core_devise_token_auth-2.8.0.alpha.13 app/models/spree/order_mutex.rb
solidus_core_devise_token_auth-2.8.0.alpha.12 app/models/spree/order_mutex.rb
solidus_core_devise_token_auth-2.8.0.alpha.11 app/models/spree/order_mutex.rb
solidus_core_devise_token_auth-2.8.0.alpha.10 app/models/spree/order_mutex.rb
solidus_core_devise_token_auth-2.8.0.alpha.9 app/models/spree/order_mutex.rb
solidus_core_devise_token_auth-2.8.0.alpha.8 app/models/spree/order_mutex.rb
solidus_core_devise_token_auth-2.8.0.alpha.7 app/models/spree/order_mutex.rb
solidus_core_devise_token_auth-2.8.0.alpha.6 app/models/spree/order_mutex.rb
solidus_core_devise_token_auth-2.8.0.alpha.5 app/models/spree/order_mutex.rb
solidus_core_devise_token_auth-2.8.0.alpha.4 app/models/spree/order_mutex.rb
solidus_core_devise_token_auth-2.8.0.alpha.3 app/models/spree/order_mutex.rb
solidus_core_devise_token_auth-2.8.0.alpha.1 app/models/spree/order_mutex.rb
solidus_core_devise_token_auth-2.8.0.alpha.0 app/models/spree/order_mutex.rb
solidus_core-2.7.0 app/models/spree/order_mutex.rb
solidus_core-2.6.1 app/models/spree/order_mutex.rb