Sha256: 91a07d35130e22f1300eb6dd3bc5fc43fbcb5e31b03860903ae98e202650bcd9

Contents?: true

Size: 887 Bytes

Versions: 10

Compression:

Stored size: 887 Bytes

Contents

require 'English'
require 'timeout'
require 'pathname'

module Shipit
  class Flock
    TimeoutError = Class.new(::Timeout::Error)

    attr_reader :path

    def initialize(path)
      @path = Pathname.new(path)
    end

    def lock(timeout:)
      path.parent.mkpath
      path.open('w') do |file|
        if retrying(timeout: timeout) { file.flock(File::LOCK_EX | File::LOCK_NB) }
          file.write($PROCESS_ID.to_s)
          return yield
        else
          raise TimeoutError, "Couldn't acquire lock for #{path} in #{timeout} seconds"
        end
      end
    end

    private

    def retrying(timeout:, breathing_time: 0.01)
      started_at = Time.now.to_f

      loop do
        if yield
          return true
        elsif Time.now.to_f - started_at < timeout
          sleep(breathing_time)
        else
          return false
        end
      end
    end
  end
end

Version data entries

10 entries across 10 versions & 1 rubygems

Version Path
shipit-engine-0.31.0 lib/shipit/flock.rb
shipit-engine-0.30.0 lib/shipit/flock.rb
shipit-engine-0.29.0 lib/shipit/flock.rb
shipit-engine-0.28.1 lib/shipit/flock.rb
shipit-engine-0.28.0 lib/shipit/flock.rb
shipit-engine-0.27.1 lib/shipit/flock.rb
shipit-engine-0.27.0 lib/shipit/flock.rb
shipit-engine-0.26.0 lib/shipit/flock.rb
shipit-engine-0.25.1 lib/shipit/flock.rb
shipit-engine-0.25.0 lib/shipit/flock.rb