Class: Legion::Gaia::SessionStore

Inherits:
Object
  • Object
show all
Defined in:
lib/legion/gaia/session_store.rb

Defined Under Namespace

Classes: Session

Constant Summary collapse

UUID_PATTERN =
/\A[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\z/i

Instance Method Summary collapse

Constructor Details

#initialize(ttl: 86_400) ⇒ SessionStore

Returns a new instance of SessionStore.



17
18
19
20
21
22
23
24
# File 'lib/legion/gaia/session_store.rb', line 17

def initialize(ttl: 86_400)
  @sessions = {}
  @identity_index = {}
  @canonical_to_uuid = {}
  @session_identity_index = {}
  @ttl = ttl
  @mutex = Mutex.new
end

Instance Method Details

#find_or_create(identity:, canonical_name: nil) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/legion/gaia/session_store.rb', line 26

def find_or_create(identity:, canonical_name: nil)
  @mutex.synchronize do
    normalized = normalize_identity(identity)
    session_id = resolve_session_id(normalized, canonical_name: canonical_name)

    if session_id && @sessions[session_id]
      session = @sessions[session_id]
      return session unless expired?(session)

      remove_unlocked(session_id)
    end

    session = Session.new(identity: normalized)
    @sessions[session.id] = session
    @identity_index[normalized] = session.id
    @session_identity_index[session.id] = [normalized]
    @canonical_to_uuid[canonical_name.to_s.downcase] = normalized if canonical_name && uuid?(normalized)
    session
  end
end

#get(session_id) ⇒ Object



65
66
67
# File 'lib/legion/gaia/session_store.rb', line 65

def get(session_id)
  @mutex.synchronize { @sessions[session_id] }
end

#prune_expiredObject



77
78
79
80
81
82
83
# File 'lib/legion/gaia/session_store.rb', line 77

def prune_expired
  @mutex.synchronize do
    expired_ids = @sessions.select { |_, s| expired?(s) }.keys
    expired_ids.each { |id| remove_unlocked(id) }
    expired_ids.size
  end
end

#remove(session_id) ⇒ Object



69
70
71
# File 'lib/legion/gaia/session_store.rb', line 69

def remove(session_id)
  @mutex.synchronize { remove_unlocked(session_id) }
end

#sizeObject



73
74
75
# File 'lib/legion/gaia/session_store.rb', line 73

def size
  @mutex.synchronize { @sessions.size }
end

#touch(session_id, channel_id: nil) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/legion/gaia/session_store.rb', line 47

def touch(session_id, channel_id: nil)
  @mutex.synchronize do
    session = @sessions[session_id]
    return nil unless session

    history = channel_id ? (session.channel_history + [channel_id]).uniq : session.channel_history
    updated = Session.new(
      id: session.id,
      identity: session.identity,
      channel_history: history,
      created_at: session.created_at,
      last_active_at: Time.now.utc
    )
    @sessions[session_id] = updated
    updated
  end
end