Sha256: db663c01797ea6a65ead4723488ea5a5a98082bebef967f10a3fd86ce31ae4ad

Contents?: true

Size: 1.05 KB

Versions: 1

Compression:

Stored size: 1.05 KB

Contents

# frozen_string_literal: true

require 'fileutils'

module Wso2Toolbox
  module TokenManager
    module Adapters
      module LockFile
        LockFileExistError = Class.new(StandardError)
        ATTEMPTS = 30
        TIME_INTERVAL = 1
        LOCK_PATH = 'tmp/localstorage.lock'

        def try_unlock
          ATTEMPTS.times do |i|
            raise LockFileExistError if lock_valid? && i == (ATTEMPTS - 1)

            if lock_valid?
              sleep(TIME_INTERVAL)
            else
              FileUtils.rm_r(LOCK_PATH, force: true)
              break
            end
          end
        end

        def lock_file
          File.open(LOCK_PATH, 'a+') do |f|
            f.write File.basename(LOCK_PATH, '.*')
          end

          block_value = yield

          FileUtils.rm_r(LOCK_PATH, force: true)

          block_value
        end

        def lock_valid?
          return false unless File.exist?(LOCK_PATH)

          file_modified = File.ctime(LOCK_PATH)
          file_modified + 1.minutes < Time.current
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
wso2_toolbox-0.3.2 lib/wso2_toolbox/token_manager/adapters/lock_file.rb