Presence
Presence module: per-topic user presence tracking for Channels.
Presence tracks which users are connected to a topic, with metadata. Key features: Multi-device: one user (key) can have multiple connections (metas). Diffs: when a user joins or leaves a topic, a "presence_diff" broadcast is sent. Clients maintain a local mirror and apply diffs. Pure layer: PresenceState is an immutable data structure fully testable without the actor runtime.
Data model: PresenceState = Map(topic, Map(key, List(PresenceMeta))) key — identifies the user (e.g. user id string) meta — arbitrary JSON string with per-device metadata pid — channel process pid (used to distinguish multi-device entries)
Pure API: new_state/0 — empty PresenceState track_state/5 — add a (pid, meta) entry for (topic, key) untrack_state/3 — remove entries for (topic, key, pid) list_state/2 — get Map(key, PresenceEntry) for a topic entry_metas/1 — get the List(PresenceMeta) from an entry meta_pid/1 — extract pid from a PresenceMeta meta_data/1 — extract data string from a PresenceMeta count_presences/2 — number of distinct keys present on a topic
Runtime helpers (require actor runtime): track/3 — track(socket, key, meta_json) using the current channel pid untrack/2 — untrack(socket, key) for the current channel pid list/1 — list(topic) → list of (key, meta_json) pairs
Types
Functions
Construct a PresenceMeta.
Extract the pid from a PresenceMeta.
Extract the data string from a PresenceMeta.
Construct a PresenceEntry with a list of metas.
Return the list of PresenceMeta from a PresenceEntry.
Number of active connections for this entry.
Create an empty PresenceState.
Add a presence entry for key on topic with the given channel pid and meta_json metadata string. Returns the updated state. Multiple calls with different pids add multiple entries (multi-device support).
Remove all presence metas for pid under key on topic. If the entry becomes empty, the key is removed from the topic map. Returns the updated state.
Return the Map(key, PresenceEntry) for topic. Empty map if no one is present.
Number of distinct user keys currently present on topic.
True when key has at least one active presence on topic.
Number of active connections (metas) for key on topic. Useful for multi-device detection (> 1 means multiple devices).
Build a JSON presence-diff string for a single join event. Format: {"joins":{"key":{"metas":[meta_json]}},"leaves":{}}
Build a JSON presence-diff string for a single leave event. Format: {"joins":{},"leaves":{"key":{"metas":[meta_json]}}}
Track the current user on the socket's topic. Sends a presence-diff broadcast via PubSub for the join event. Requires actor runtime and a running PubSub.
Untrack the current user from the socket's topic. Sends a presence-diff broadcast for the leave event only if this was the user's last connection (single-device cleanup is the caller's responsibility). Requires actor runtime.