~singpolyma/sgx-jmp

ref: 023c87a11bbaa6bd3eaeb3977330b8ea80ded0cd sgx-jmp/lib/session_manager.rb -rw-r--r-- 834 bytes
023c87a1Stephen Paul Weber Quieter voicemail beep 7 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# frozen_string_literal: true

class SessionManager
	class Timeout < StandardError; end

	def initialize(blather, id_msg, timeout: 5, error_if: nil)
		@blather = blather
		@sessions = {}
		@id_msg = id_msg
		@timeout = timeout
		@error_if = error_if
	end

	def promise_for(stanza)
		id = "#{stanza.to.stripped}/#{stanza.public_send(@id_msg)}"
		@sessions.fetch(id) do
			@sessions[id] = EMPromise.new
			EM.add_timer(@timeout) do
				@sessions.delete(id)&.reject(Timeout.new)
			end
			@sessions[id]
		end
	end

	def write(stanza)
		promise = promise_for(stanza)
		@blather << stanza
		promise
	end

	def fulfill(stanza)
		id = "#{stanza.from.stripped}/#{stanza.public_send(@id_msg)}"
		if stanza.error? || @error_if&.call(stanza)
			@sessions.delete(id)&.reject(stanza)
		else
			@sessions.delete(id)&.fulfill(stanza)
		end
	end
end