Class: CrmNavbarLiveUsers

Inherits:
Object
  • Object
show all
Defined in:
app/services/crm_navbar_live_users.rb

Overview

Tracks which CRM users currently have the navbar mounted (i.e. are sitting on
a CRM page right now). The navbar's Stimulus controller heartbeats this
endpoint roughly every minute; entries auto-expire after TTL_SECONDS so a
user who closes the tab or sleeps the laptop drops out without explicit
cleanup.

Stored as a single Redis sorted-set whose score is a unix timestamp. Reads
transparently garbage-collect entries older than the TTL.

This registry exists so that broadcasters can short-circuit before doing any
rendering work — there's no point computing a per-user badge for someone who
isn't on a CRM page.

Constant Summary collapse

KEY =
'crm_navbar:live_users'
TTL_SECONDS =
90

Class Method Summary collapse

Class Method Details

.listObject

Returns the array of user IDs (Integer) currently considered live.
Garbage-collects expired entries as a side effect.



36
37
38
39
40
41
42
# File 'app/services/crm_navbar_live_users.rb', line 36

def list
  cutoff = (Time.current - TTL_SECONDS).to_f
  with_redis do |r|
    r.zremrangebyscore(KEY, '-inf', "(#{cutoff}")
    r.zrange(KEY, 0, -1).map(&:to_i)
  end
end

.live?(user_id) ⇒ Boolean

Returns:

  • (Boolean)


44
45
46
47
48
# File 'app/services/crm_navbar_live_users.rb', line 44

def live?(user_id)
  cutoff = (Time.current - TTL_SECONDS).to_f
  score = with_redis { |r| r.zscore(KEY, user_id.to_s) }
  score.present? && score >= cutoff
end

.reset!Object

Test helper.



51
52
53
# File 'app/services/crm_navbar_live_users.rb', line 51

def reset!
  with_redis { |r| r.del(KEY) }
end

.touch(user_id) ⇒ Object

Mark a user as currently viewing the CRM. Idempotent — repeated calls
just bump the timestamp.



22
23
24
25
26
27
28
29
30
31
32
# File 'app/services/crm_navbar_live_users.rb', line 22

def touch(user_id)
  now = Time.current.to_f
  with_redis do |r|
    r.zadd(KEY, now, user_id.to_s)
    # Bound the size of the sorted set; stale entries are garbage collected
    # on every list/live? read but adding a TTL guards against a long-idle
    # Redis still holding ancient entries.
    r.expire(KEY, 1.day.to_i)
  end
  true
end