Class: TinyDTLS::SessionManager
- Inherits:
-
Object
- Object
- TinyDTLS::SessionManager
- Defined in:
- lib/tinydtls/session_manager.rb
Overview
This class is used to manage established tinydtls sessions. It stores instances of the TinyDTLS::Session class.
While memory allocated for sessions is automatically freed by tinydtls, if it receive an alert from the peer associated with that session, memory isn’t freed if the peer doesn’t send an alert. Therefore this class starts a background thread automatically freeing memory associated with sessions which haven’t been used since a specified duration.
Constant Summary collapse
- DEFAULT_TIMEOUT =
Default timeout for the cleanup thread in seconds.
(5 * 60).freeze
Instance Attribute Summary collapse
-
#timeout ⇒ Object
readonly
Timeout used by the cleanup thread.
Instance Method Summary collapse
-
#[](addrinfo, &f) ⇒ Object
Retrieve a session from the session manager.
-
#close ⇒ Object
Kills the background thread.
-
#initialize(context, timeout = DEFAULT_TIMEOUT) ⇒ SessionManager
constructor
Creates a new instance of this class.
Constructor Details
#initialize(context, timeout = DEFAULT_TIMEOUT) ⇒ SessionManager
Creates a new instance of this class. A tinydtls ‘context_t` pointer is required to free sessions in the background thread.
Memory for sessions created using #[] needs to be explicitly freed by calling #close as soons as this class instance is no longer needed.
25 26 27 28 29 30 31 32 33 |
# File 'lib/tinydtls/session_manager.rb', line 25 def initialize(context, timeout = DEFAULT_TIMEOUT) @store = {} @mutex = Mutex.new @timeout = timeout @context = context start_thread end |
Instance Attribute Details
#timeout ⇒ Object (readonly)
Timeout used by the cleanup thread. If a session hasn’t been used within ‘timeout * 2` seconds it will be freed automatically.
17 18 19 |
# File 'lib/tinydtls/session_manager.rb', line 17 def timeout @timeout end |
Instance Method Details
#[](addrinfo, &f) ⇒ Object
Retrieve a session from the session manager.
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
# File 'lib/tinydtls/session_manager.rb', line 36 def [](addrinfo, &f) unless addrinfo.is_a? Addrinfo raise TypeError end key = addrinfo.getnameinfo @mutex.synchronize do if @store.has_key? key sess, _ = @store[key] else sess = Session.new(addrinfo) @store[key] = [sess, true] end f.call(sess) end end |
#close ⇒ Object
Kills the background thread. All established sessions are closed as well, see Session#close.
56 57 58 59 60 61 62 63 64 |
# File 'lib/tinydtls/session_manager.rb', line 56 def close @mutex.synchronize do @thread.kill @store.each_value do |value| sess, _ = value sess.close(@context) end end end |