LCOV - code coverage report
Current view: top level - matchscore/realtime - subscriptions.clj Coverage Total Hit
Test: lcov.info Lines: 95.6 % 203 194
Test Date: 2026-11-23 18:11:10 Functions: - 0 0

            Line data    Source code
       1            4 : (ns matchscore.realtime.subscriptions
       2              :   (:require
       3              :    [cheshire.core :as json]
       4              :    [clojure.string :as str]
       5              :    [taoensso.carmine :as car]
       6              :    [taoensso.telemere :as t]))
       7              : 
       8              : 
       9              : ;; Subscriptions are keyed by user-uuid (delivery targets uids via the Sente
      10              : ;; send-fn), but a single user may hold several connections at once (multiple
      11              : ;; devices / tabs). Two relations are tracked:
      12              : ;;
      13              : ;;   * DELIVERY: the `subs` set (`subscriptions:{event}`) holds users with at least
      14              : ;;     one connection that still qualifies for delivery (`delivers?*` — online, OR
      15              : ;;     away but still heart-beating) — the realtime delivery audience. Delivery is
      16              : ;;     intentionally decoupled from the online/away DISPLAY status: a backgrounded
      17              : ;;     / unfocused tab whose socket is alive keeps receiving pushes (so it stays
      18              : ;;     fresh) and is dropped only once it disconnects or goes stale.
      19              : ;;
      20              : ;;   * PRESENCE / display: the per-(event, user) connection registry is a Redis
      21              : ;;     HASH (`subscriptions:{event}:conns:{user}`) keyed by client-id whose
      22              : ;;     values are JSON device descriptors. It RETAINS recently-disconnected
      23              : ;;     connections (stamped `:offline-at`) for `retain-offline-ms` so the UI can
      24              : ;;     show "recently online" devices. Two indexes track presence: the `present`
      25              : ;;     set (`subscriptions:{event}:present`) — users with a retained device on an
      26              : ;;     event — and its per-user inverse `user-subs` (`user-subscriptions:{user}`)
      27              : ;;     — events on which a user has a retained device. `user-subs` spans retained
      28              : ;;     (online OR offline/away) connections, NOT just online ones, so a heartbeat
      29              : ;;     can refresh an away connection's `:last-seen` and the reaper can age a
      30              : ;;     gone-away connection to offline.
      31              : ;;
      32              : ;; Liveness is heartbeat-based, NOT disconnect-based: Sente only fires
      33              : ;; `:chsk/uidport-close` when a user's LAST connection drops, so closes of
      34              : ;; individual connections are never observed. Every inbound message refreshes a
      35              : ;; connection's `:last-seen` (`touch-connection!`); a connection that stops
      36              : ;; sending Sente's ws keepalive is flipped to offline after `online-after-ms`
      37              : ;; and finally removed after `retain-offline-ms`, by `reconcile-presence!`.
      38              : 
      39              : 
      40              : ;; No heartbeat within this window => the connection is considered offline.
      41            8 : (def ^:private online-after-ms 75000)
      42              : 
      43              : 
      44              : ;; Keep an offline connection visible (as "recently online") for this long
      45              : ;; before removing it entirely.
      46            8 : (def ^:private retain-offline-ms 600000)
      47              : 
      48              : 
      49           12 : (defn- subs-key [event-uuid] (str "subscriptions:" event-uuid))
      50              : 
      51              : 
      52           12 : (defn- user-subs-key [user-uuid] (str "user-subscriptions:" user-uuid))
      53              : 
      54              : 
      55            4 : (defn- conns-key
      56              :   "Hash of `client-id` -> device JSON for `user-uuid`'s connections (online or
      57              :   recently-offline) on `event-uuid`."
      58              :   [event-uuid user-uuid]
      59           12 :   (str "subscriptions:" event-uuid ":conns:" user-uuid))
      60              : 
      61              : 
      62            4 : (defn- present-key
      63              :   "Set of user-uuids with at least one retained device on `event-uuid`."
      64              :   [event-uuid]
      65           10 :   (str "subscriptions:" event-uuid ":present"))
      66              : 
      67              : 
      68            8 : (def ^:private subscribe-script
      69              :   "Atomically registers one online connection (`client-id`) with its device
      70              :   descriptor and records the user in the event's delivery + presence sets. Drops
      71              :   a legacy/wrong-type conns key first (the registry used to be a SET before it
      72              :   carried device metadata) so an old key left over across a deploy cannot cause
      73              :   WRONGTYPE. KEYS: conns-key, subs-key, user-subs-key, present-key. ARGV:
      74              :   client-id, device-json, user-uuid, event-uuid. Returns the connection count."
      75              :   "local t = redis.call('TYPE', KEYS[1])['ok']
      76              : if t ~= 'hash' and t ~= 'none' then
      77              :   redis.call('DEL', KEYS[1])
      78              : end
      79              : redis.call('HSET', KEYS[1], ARGV[1], ARGV[2])
      80              : redis.call('SADD', KEYS[2], ARGV[3])
      81              : redis.call('SADD', KEYS[3], ARGV[4])
      82              : redis.call('SADD', KEYS[4], ARGV[3])
      83              : return redis.call('HLEN', KEYS[1])")
      84              : 
      85              : 
      86            8 : (defn- now-ms [] (System/currentTimeMillis))
      87              : 
      88              : 
      89            4 : (defn- read-conns
      90              :   "Return the conns hash as a seq of [client-id device-map]."
      91              :   [redis k]
      92            2 :   (->>
      93           78 :     (car/wcar redis (car/hgetall k))
      94            6 :     (partition 2)
      95            2 :     (map
      96            2 :      (fn [[client-id v]]
      97           12 :       [client-id (json/parse-string v true)]))))
      98              : 
      99              : 
     100            4 : (defn- online?*
     101              :   [now device]
     102           42 :   (and (nil? (:offline-at device)) (<= (- now (or (:last-seen device) 0)) online-after-ms)))
     103              : 
     104              : 
     105            4 : (defn- stale?*
     106              :   "True when no heartbeat has refreshed this connection within the online window
     107              :   — i.e. the socket has gone quiet, regardless of its current status. An ONLINE
     108              :   stale connection has dropped silently; an AWAY stale connection (one that
     109              :   stopped heart-beating after stepping away) is genuinely gone, not just idle."
     110              :   [now device]
     111           11 :   (> (- now (or (:last-seen device) 0)) online-after-ms))
     112              : 
     113              : 
     114            4 : (defn- delivers?*
     115              :   "True when this connection should still receive realtime pushes. Delivery is
     116              :   decoupled from the online/away DISPLAY status: a connection that is online, or
     117              :   merely AWAY but still heart-beating (a backgrounded / unfocused tab whose socket
     118              :   is alive), keeps getting events so it stays fresh. Only a plain-offline
     119              :   (disconnected) connection, or an away one that has since gone quiet (stale), is
     120              :   dropped from the delivery audience."
     121              :   [now device]
     122           40 :   (or (online?* now device) (and (= "away" (:offline-reason device)) (not (stale?* now device)))))
     123              : 
     124              : 
     125            4 : (defn- expired?*
     126              :   [now device]
     127           28 :   (and (:offline-at device) (> (- now (:offline-at device)) retain-offline-ms)))
     128              : 
     129              : 
     130            4 : (defn- present-device
     131              :   "Shape a stored device for callers: keep :client-id/:device-name/:connected-at/
     132              :   :last-seen and attach a derived :status flag (:online, :away, or :offline).
     133              :   :offline-reason is nil for an online device (it has no reason to be offline);
     134              :   for a disconnected one it carries :away or :offline."
     135              :   [_now [client-id device]]
     136           14 :   (let [online?        (nil? (:offline-at device))
     137           26 :         offline-reason (when-not online? (keyword (or (:offline-reason device) "offline")))
     138           13 :         status         (cond online? :online
     139            6 :                              (= offline-reason :away) :away
     140              :                              :else :offline)]
     141           16 :     {:client-id      client-id
     142            6 :      :device-name    (:device-name device)
     143            6 :      :connected-at   (:connected-at device)
     144            6 :      :last-seen      (:last-seen device)
     145            2 :      :offline-reason offline-reason
     146            2 :      :status         status}))
     147              : 
     148              : 
     149            4 : (defn subscribe!
     150              :  "Subscribe one of a user's connections (`client-id`) to an event's realtime
     151              :   updates as ONLINE, recording the optional `device-name`. Idempotent; a
     152              :   reconnecting client-id is moved back to online (its :offline-at is cleared).
     153              :   `instance-id` records which backend pod currently owns this connection, kept
     154              :   for observability/debugging."
     155           16 :  ([redis event-uuid user-uuid client-id] (subscribe! redis event-uuid user-uuid client-id nil nil))
     156              :  ([redis event-uuid user-uuid client-id device-name]
     157            8 :   (subscribe! redis event-uuid user-uuid client-id device-name nil))
     158              :  ([redis event-uuid user-uuid client-id device-name instance-id]
     159           44 :   (t/log! :debug (str "Subscribe " user-uuid "/" client-id " to " event-uuid))
     160            6 :   (let [now    (now-ms)
     161            4 :         device (json/generate-string
     162           22 :                 {:client-id    (or client-id user-uuid)
     163            2 :                  :device-name  device-name
     164            2 :                  :instance-id  instance-id
     165            2 :                  :connected-at now
     166            2 :                  :last-seen    now})]
     167           70 :     (car/wcar
     168            2 :      redis
     169            6 :      (car/eval
     170            2 :       subscribe-script
     171              :       4
     172            8 :       (conns-key event-uuid user-uuid)
     173            6 :       (subs-key event-uuid)
     174            6 :       (user-subs-key user-uuid)
     175            6 :       (present-key event-uuid)
     176           10 :       (or client-id user-uuid)
     177            2 :       device
     178            2 :       user-uuid
     179            2 :       event-uuid)))))
     180              : 
     181              : 
     182            4 : (defn- recompute-delivery!
     183              :   "Drop `user-uuid` from the event's DELIVERY set (`subs-key`) when none of their
     184              :   retained connections still qualify for delivery (`delivers?*` — online, or away
     185              :   but still heart-beating). Called after a connection's status changes. An away
     186              :   connection whose socket is still alive KEEPS the user in the delivery set, so a
     187              :   backgrounded / unfocused tab keeps receiving realtime pushes; it is dropped only
     188              :   once it disconnects or goes stale. The per-user presence index (`user-subs-key`)
     189              :   is left intact while the user still has a retained (online OR offline/away)
     190              :   connection — `touch-connection!` walks it to refresh the `:last-seen` of away
     191              :   connections so the reaper can tell an away-but-alive device from one that has
     192              :   actually gone. It is cleaned up in `reconcile-conns!` once the user's last
     193              :   connection ages out."
     194              :   [redis event-uuid user-uuid]
     195            6 :   (let [now (now-ms)]
     196            5 :     (when-not
     197            4 :       (some
     198            2 :        (fn [[_ d]]
     199            8 :         (delivers?* now d))
     200           14 :        (read-conns redis (conns-key event-uuid user-uuid)))
     201           42 :       (car/wcar redis (car/srem (subs-key event-uuid) user-uuid)))))
     202              : 
     203              : 
     204            4 : (defn unsubscribe!
     205              :  "Mark one of a user's connections (`client-id`) OFFLINE for an event. The
     206              :   device is retained for display until it ages out; delivery membership is
     207              :   dropped once the user has no remaining online connection. `reason` is
     208              :   `:offline` (default, heartbeat timeout / disconnect) or `:away` (client
     209              :   explicitly went inactive).
     210              : 
     211              :   `_owner-instance-id` is accepted (and ignored) only for call-site
     212              :   compatibility with the disconnect handler. (A previous attempt to scope the
     213              :   offline to the owning pod — to stop a stale cross-pod close from clobbering a
     214              :   reconnected connection — was removed: it relied on sticky routing and silently
     215              :   dropped legitimate disconnects whose close was observed on a different pod than
     216              :   the subscribe.)"
     217              :  ([redis event-uuid user-uuid client-id]
     218            8 :   (unsubscribe! redis event-uuid user-uuid client-id :offline nil))
     219              :  ([redis event-uuid user-uuid client-id reason]
     220            8 :   (unsubscribe! redis event-uuid user-uuid client-id reason nil))
     221              :  ([redis event-uuid user-uuid client-id reason _owner-instance-id]
     222           44 :   (t/log!
     223              :    :debug
     224            0 :    (str "Unsubscribe " user-uuid "/" client-id " from " event-uuid " (reason: " reason ")"))
     225           10 :   (let [k   (conns-key event-uuid user-uuid)
     226           10 :         cid (or client-id user-uuid)
     227           80 :         raw (car/wcar redis (car/hget k cid))]
     228            6 :     (when raw
     229            6 :       (let [now    (now-ms)
     230           18 :             device (assoc (json/parse-string raw true)
     231            2 :                     :offline-at     now
     232            6 :                     :offline-reason (name reason)
     233            2 :                     :last-seen      now)]
     234           86 :         (car/wcar redis (car/hset k cid (json/generate-string device)))
     235           10 :         (recompute-delivery! redis event-uuid user-uuid))))))
     236              : 
     237              : 
     238            4 : (defn unsubscribe-all!
     239              :  "Remove ALL presence for a user across every event entirely (e.g. an admin
     240              :   purge). Unlike `unsubscribe!` this does not retain offline devices."
     241              :  [redis user-uuid]
     242           42 :  (let [event-uuids (car/wcar redis (car/smembers (user-subs-key user-uuid)))]
     243            5 :    (when (seq event-uuids)
     244           22 :      (t/log! :debug (str "Cleaning up " (count event-uuids) " subscriptions for " user-uuid))
     245           35 :      (car/wcar
     246            1 :       redis
     247           26 :       (doseq [event-uuid event-uuids]
     248            6 :         (car/srem (subs-key event-uuid) user-uuid)
     249            6 :         (car/srem (present-key event-uuid) user-uuid)
     250            6 :         (car/del (conns-key event-uuid user-uuid)))
     251            5 :       (car/del (user-subs-key user-uuid))))))
     252              : 
     253              : 
     254            4 : (defn unsubscribe-all-for-connection!
     255              :  "Mark a single connection (`client-id`) OFFLINE across every event the user is
     256              :   online on, preserving the user's other connections. Returns the seq of
     257              :   affected event-uuids so callers can broadcast the resulting presence changes.
     258              :   `owner-instance-id` (optional) is forwarded to `unsubscribe!` so a stale close
     259              :   from a previous pod cannot clobber a connection that reconnected elsewhere."
     260              :  ([redis user-uuid client-id]
     261           14 :   (unsubscribe-all-for-connection! redis user-uuid client-id :offline nil))
     262              :  ([redis user-uuid client-id reason]
     263            7 :   (unsubscribe-all-for-connection! redis user-uuid client-id reason nil))
     264              :  ([redis user-uuid client-id reason owner-instance-id]
     265           84 :   (let [event-uuids (car/wcar redis (car/smembers (user-subs-key user-uuid)))]
     266           10 :     (when (seq event-uuids)
     267           44 :       (t/log!
     268              :        :debug
     269            0 :        (str "Cleaning up " (count event-uuids) " subscriptions for " user-uuid "/" client-id))
     270           52 :       (doseq [event-uuid event-uuids]
     271           16 :         (unsubscribe! redis event-uuid user-uuid client-id reason owner-instance-id)))
     272            6 :     (vec event-uuids))))
     273              : 
     274              : 
     275            4 : (defn touch-connection!
     276              :  "Refresh the `:last-seen` of one of a user's ONLINE or AWAY connections across
     277              :   every event it has a retained connection on. Called on every inbound message
     278              :   (incl. Sente's ws keepalive).
     279              : 
     280              :   This NEVER changes status — it does not clear `:offline-at`/`:offline-reason`,
     281              :   so an away connection stays away (a hidden tab / collapsed mini app whose
     282              :   socket lingers must NOT be revived to online by a keepalive). It only stamps
     283              :   liveness: a still-heart-beating away connection keeps a fresh `:last-seen`, so
     284              :   the reaper leaves it away, whereas one that has gone quiet ages to offline.
     285              : 
     286              :   Plain-offline connections (`:offline-reason \"offline\"`) are left frozen so
     287              :   their displayed \"last seen\" reflects when they were actually last seen."
     288              :  [redis user-uuid client-id]
     289            3 :  (when client-id
     290           42 :    (let [event-uuids (car/wcar redis (car/smembers (user-subs-key user-uuid)))
     291            2 :          now         (now-ms)]
     292           26 :      (doseq [event-uuid event-uuids]
     293            5 :        (let [k   (conns-key event-uuid user-uuid)
     294           40 :              raw (car/wcar redis (car/hget k client-id))]
     295            3 :          (when raw
     296            5 :            (let [device (json/parse-string raw true)]
     297           17 :              (when (or (nil? (:offline-at device)) (= "away" (:offline-reason device)))
     298           35 :                (car/wcar
     299            1 :                 redis
     300           11 :                 (car/hset k client-id (json/generate-string (assoc device :last-seen now))))))))))))
     301              : 
     302              : 
     303            4 : (defn get-subscribers
     304              :  "Get the set of user UUIDs in the event's realtime delivery audience — those
     305              :   with at least one connection that still qualifies for delivery (`delivers?*`:
     306              :   online, or away but still heart-beating). See `recompute-delivery!`."
     307              :  [redis event-uuid]
     308           86 :  (set (car/wcar redis (car/smembers (subs-key event-uuid)))))
     309              : 
     310              : 
     311            4 : (defn- read-conns-safe
     312              :   "Like `read-conns` but skips entries whose JSON value cannot be parsed,
     313              :   logging a warning with the provided context."
     314              :   [redis k event-uuid user-uuid]
     315            2 :   (->>
     316           78 :     (car/wcar redis (car/hgetall k))
     317            6 :     (partition 2)
     318            2 :     (keep
     319            2 :      (fn [[client-id v]]
     320            2 :       (try
     321            2 :         [client-id (json/parse-string v true)]
     322              :         (catch Exception e
     323            0 :           (t/log!
     324              :            :warn
     325            0 :            (str
     326            0 :             "Malformed device JSON in subscriptions: event=" event-uuid
     327            0 :             " user="   user-uuid
     328            0 :             " client=" client-id
     329            0 :             ": "       (.getMessage e)))
     330              :           nil))))))
     331              : 
     332              : 
     333            4 : (defn get-user-devices
     334              :  "Get the vector of retained device descriptors
     335              :   ({:client-id :device-name :last-seen :status}) for `user-uuid` on
     336              :   `event-uuid`, excluding any that have aged past retention. Empty when the user
     337              :   has no retained connection."
     338              :  [redis event-uuid user-uuid]
     339            6 :  (let [now (now-ms)]
     340            2 :    (->>
     341           18 :      (read-conns-safe redis (conns-key event-uuid user-uuid) event-uuid user-uuid)
     342            4 :      (remove
     343            2 :       (fn [[_ d]]
     344            8 :        (expired?* now d)))
     345           10 :      (mapv (partial present-device now)))))
     346              : 
     347              : 
     348            4 : (defn get-event-presence
     349              :  "Snapshot of who is connected to an event (including recently-offline devices):
     350              :   {user-uuid [{:client-id :device-name :last-seen :status} ...]} for every user
     351              :   with at least one retained device."
     352              :  [redis event-uuid]
     353            2 :  (reduce
     354            1 :   (fn [acc user-uuid]
     355            6 :    (let [devices (get-user-devices redis event-uuid user-uuid)]
     356            9 :      (if (seq devices) (assoc acc user-uuid devices) acc)))
     357            1 :   {}
     358           43 :   (set (car/wcar redis (car/smembers (present-key event-uuid))))))
     359              : 
     360              : 
     361            4 : (defn- parse-conns-key
     362              :   "Pull [event-uuid user-uuid] out of a \"subscriptions:{event}:conns:{user}\"
     363              :   key. UUIDs contain no colons, so a plain split is unambiguous."
     364              :   [k]
     365            5 :   (let [parts (str/split k #":")]
     366           21 :     (when (and (= 4 (count parts)) (= "conns" (nth parts 2))) [(nth parts 1) (nth parts 3)])))
     367              : 
     368              : 
     369            4 : (defn- reconcile-conns!
     370              :   "Reconcile one (event, user) registry: flip connections that have stopped
     371              :   heartbeating to offline — both ONLINE ones that dropped silently and AWAY ones
     372              :   whose socket has since gone quiet (the user stepped away and then actually
     373              :   left) — delete offline connections past retention, and keep the
     374              :   delivery/presence sets consistent. Returns {:changed? bool :devices [...]}
     375              :   where :devices is the remaining retained set."
     376              :   [redis event-uuid user-uuid]
     377            5 :   (let [k       (conns-key event-uuid user-uuid)
     378            2 :         now     (now-ms)
     379            4 :         entries (read-conns redis k)
     380            1 :         delete  (->>
     381            1 :                   entries
     382            2 :                   (filter
     383            1 :                    (fn [[_ d]]
     384            4 :                     (expired?* now d)))
     385            2 :                   (mapv first))
     386              :         ;; Online-stale (dropped silently) and away-stale (stepped away, then the
     387              :         ;; socket went quiet) both become plain offline. An online connection
     388              :         ;; gets its :offline-at stamped now; an away one keeps the :offline-at it
     389              :         ;; got when it stepped away, so its retention countdown is unchanged.
     390            1 :         offline (->>
     391            1 :                   entries
     392            2 :                   (remove
     393            1 :                    (fn [[_ d]]
     394            4 :                     (expired?* now d)))
     395            2 :                   (filter
     396            1 :                    (fn [[_ d]]
     397           14 :                     (and (stale?* now d) (not= "offline" (:offline-reason d)))))
     398            1 :                   (mapv
     399            1 :                    (fn [[cid d]]
     400            2 :                     [cid
     401            6 :                      (assoc d
     402            8 :                       :offline-at     (or (:offline-at d) now)
     403              :                       :offline-reason "offline")])))]
     404           46 :     (when (seq delete) (car/wcar redis (apply car/hdel k delete)))
     405           69 :     (doseq [[cid d] offline] (car/wcar redis (car/hset k cid (json/generate-string d))))
     406           17 :     (when (or (seq offline) (seq delete)) (recompute-delivery! redis event-uuid user-uuid))
     407            5 :     (let [remaining (read-conns redis k)]
     408            5 :       (when (empty? remaining)
     409           35 :         (car/wcar
     410            1 :          redis
     411            3 :          (car/del k)
     412            6 :          (car/srem (present-key event-uuid) user-uuid)
     413            6 :          (car/srem (user-subs-key user-uuid) event-uuid)))
     414           14 :       {:changed? (boolean (or (seq offline) (seq delete)))
     415            7 :        :devices  (mapv (partial present-device now) remaining)})))
     416              : 
     417              : 
     418            4 : (defn reconcile-presence!
     419              :  "Sweep every (event, user) connection registry: flip connections that stopped
     420              :   heartbeating to offline and drop offline ones past retention. Returns a seq of
     421              :   {:event-uuid :user-uuid :devices} for the users whose set changed, so the
     422              :   caller can broadcast the resulting presence updates. This periodic sweep is
     423              :   what eventually removes connections that closed silently (Sente hides
     424              :   per-connection closes)."
     425              :  [redis]
     426            5 :  (let [keys (car/scan-keys redis "subscriptions:*:conns:*")]
     427            2 :    (reduce
     428            1 :     (fn [acc k]
     429            8 :      (if-let [[event-uuid user-uuid] (parse-conns-key k)]
     430            6 :        (let [{:keys [changed? devices]} (reconcile-conns! redis event-uuid user-uuid)]
     431            2 :          (if changed?
     432            2 :            (conj
     433            1 :             acc
     434            5 :             {:event-uuid event-uuid
     435            1 :              :user-uuid  user-uuid
     436            1 :              :devices    devices})
     437            1 :            acc))
     438            0 :        acc))
     439            1 :     []
     440            1 :     keys)))
        

Generated by: LCOV version 2.0-1