Sha256: 1b699dffe1fb775118d096776e7b19e5af3de5abaa93c21a6eea2f3f64bf7de1

Contents?: true

Size: 1.77 KB

Versions: 1

Compression:

Stored size: 1.77 KB

Contents

module Mongo
  class Lock
    module Drivers
      class Moped < Base

        def self.release_collection collection, owner=nil
          selector = if owner then { owner: owner } else {} end
          collection.find(selector).remove_all
        end

        def self.ensure_indexes collection
          collection.indexes.create({ key: 1, owner: 1, expires_at: 1 })
          collection.indexes.create({ ttl: 1 }, { expireAfterSeconds: 0 })
        end

        def self.clear_expired collection
          collection.find(expires_at: { '$lt' => Time.now }).remove_all
        end

        def find_and_modify options
          operation = options[:insert] ? '$setOnInsert' : '$set'
          existing_lock = lock.configuration.collection.
            find(query).
            modify({
              operation => {
                key: key,
                owner: options[:owner],
                expires_at: options[:expire_at],
                ttl: options[:expire_at]
              }
            }, { upsert: !!options[:insert] })
          existing_lock = nil if existing_lock == {} # Moped returns {} for an empty result

          if existing_lock
            lock.expires_at = existing_lock['expires_at']
          else
            lock.expires_at = options[:expire_at]
          end

          existing_lock
        end

        def remove options
          lock.configuration.collection.find( key: key, owner: options[:owner] ).remove_all
        end

        def find_already_acquired
          lock.configuration.collection.find({
            key: key,
            owner: lock.configuration.owner,
            expires_at: { '$gt' => Time.now }
          })
        end

        def find_existing
          lock.configuration.collection.find(query).first
        end

      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
mongo-lock-1.2.0 lib/mongo-lock/drivers/moped.rb