~singpolyma/sgx-jmp

sgx-jmp/lib/expiring_lock.rb -rw-r--r-- 366 bytes
94298f5dStephen Paul Weber Refactor alt top up to use FormTemplate 2 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# frozen_string_literal: true

class ExpiringLock
	def initialize(name, expiry: 60 * 60 * 24)
		@name = name
		@expiry = expiry
	end

	def with(els=nil)
		REDIS.set(@name, Time.now, "EX", @expiry, "NX").then do |result|
			next els&.call if result.nil?

			EMPromise.resolve(yield).catch do |err|
				REDIS.del(@name)
				EMPromise.reject(err)
			end
		end
	end
end