Sha256: 1672e5a2cd0a4db790967ed26a7f48f490b71f19ab962d8300beca1a6aa5feb1

Contents?: true

Size: 1.01 KB

Versions: 1

Compression:

Stored size: 1.01 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

          yield

          FileUtils.rm_r(LOCK_PATH, force: true)
        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.1 lib/wso2_toolbox/token_manager/adapters/lock_file.rb