# 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