Sha256: 4d0d4648f3d0a424c8cb9813660e6cc0cf38bb3d38f0bee3b349f34e3714a6e6

Contents?: true

Size: 929 Bytes

Versions: 1

Compression:

Stored size: 929 Bytes

Contents

# frozen_string_literal: true

module Wso2Toolbox
  module TokenManager
    module Adapters
      module LockFile
        FileLockedError = Class.new(StandardError)

        ATTEMPTS = 5
        TIME_INTERVAL = 1
        FILE_PATH = 'tmp/localstorage.json'

        def with_free_localstorage
          ATTEMPTS.times do |i|
            locked_file = lock_file do |localstorage|
              yield(localstorage)
            end

            raise FileLockedError if !locked_file && i == (ATTEMPTS - 1)

            !locked_file ? sleep(TIME_INTERVAL) : break
          end
        end

        def lock_file
          File.open(FILE_PATH, 'a+') do |file|
            lock_status = file.flock(File::LOCK_EX | File::LOCK_NB)

            if lock_status
              block_value = yield(file)

              file.flock(File::LOCK_UN)
              block_value
            end
          end
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

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