Documentation

Presence

List connections in a segment and observe presence notifications, which are not a complete user roster.

Video: Presence (examples in JavaScript). The YouTube player loads when you click play.

Before you start: complete Messaging. Use its channel and chat values, with credentials that grant read access to chat. You can register listeners before or after you connect. Request a listing only after the channel is connected.

Presence describes connections, not unique people. A user with three connections appears three times, each with its own connection_id.

1. Register a listener and hold presence interest

let presence_listener = chat.on_presence(|event| {
    println!("Joined: {} {} {}", event.joined, event.token_reference, event.connection_id);
});

let presence_subscription = chat.subscribe_presence()?;

on_presence registers a local listener. subscribe_presence requests notifications. Notifications arrive only while you hold a presence subscription. Keep both until this part of your application is finished. event.joined is false when the connection left. event.timestamp is an i64 value in Unix milliseconds.

A presence subscription needs read access to the segment. Without it, the server sends a PermissionDeniedError to your error listener. The SDK keeps the subscription and requests it again after each reconnect, so cancel a subscription that the server refuses.

A presence subscription does not join the segment. It does not give you messages, and your connection does not show in the presence of that segment because of it. To receive the messages of the segment, also call subscribe(). A publish does not join the segment. A connection that only publishes does not show in the presence of that segment.

The server sends presence events as follows:

  • A connection does not get the join event that it causes. A different connection of the same token gets it.
  • When a connection unsubscribes from a segment, watchers get a leave event with the same connection_id as the join. The connection stays connected.
  • On default, a connection causes a join when it connects and a leave when it closes. The default presence list includes all connections of the channel.
  • After a reconnect, watchers get a leave for the previous connection_id and a join for the new one. The SDK subscribes again to the presence that you hold with subscribe_presence. The leave for the old connection can arrive after the join for the new one. After a dropped network connection, it can arrive up to about a minute later.

2. Fetch a snapshot

After you connect, request the first page:

let page = chat.presence_list(1, 25).await?;

println!("Connections: {}", page.total);
println!("Page: {}", page.current_page);

for connection in &page.connections {
    println!("{} {}", connection.token_reference, connection.connection_id);
}

A query requires an established connection and read permission, but no held presence subscription.

Read the result fields by their types:

FieldRust typeMeaning
totali32Reported connection count
per_pagei32Page size reported by the server
current_pagei32Current page number
from, toi32Range reported for this page
connectionsVec<PresenceConnection>Connection records, not unique users
connections[i].timestampi64Unix milliseconds for that connection

3. Paginate and handle failures

page must be at least 1, and per_page must be from 1 to 100. Other values return CelerisError::Configuration. The SDK does not convert or clamp them.

use useceleris_client::{CelerisError, PresenceConnection, Segment};

async fn list_connections(segment: &Segment) -> Result<Vec<PresenceConnection>, CelerisError> {
    let mut connections = Vec::new();

    for page_number in 1.. {
        let page = segment.presence_list(page_number, 25).await?;
        let last_page = page.connections.is_empty() || page.to >= page.total;

        connections.extend(page.connections);

        if last_page {
            break;
        }
    }

    Ok(connections)
}

A listener is a plain closure, not an async function. To refresh a listing when presence changes, start a task from the listener:

let refresh_segment = chat.clone();

let refresh_listener = chat.on_presence(move |_event| {
    let segment = refresh_segment.clone();

    tokio::spawn(async move {
        match list_connections(&segment).await {
            Ok(connections) => println!("Records fetched: {}", connections.len()),
            Err(error) => println!("Presence query failed: {error}"),
        }
    });
});

Only one query can be in flight per channel, even across segments. A second query returns CelerisError::OperationInProgress, so serialize refreshes that can overlap. A query also returns CelerisError::Backpressure while the writer is full or paused after a rate limit.

A server refusal returns a CelerisError::Server from presence_list directly, with sub_type Some("PRES_LIST"). The refusal does not also reach on_error. The default query deadline (presence_query_timeout) is 10 seconds. A timeout (CelerisError::Timeout) or a dropped future frees the query slot and does not close the connection. The SDK ignores a late reply. The SDK does not retry queries automatically. A connection loss during a query returns CelerisError::Transport. Issue a new query after recovery. While the channel is not connected, a query returns CelerisError::NotConnected. See Reconnection and Recovery.

Past the last page, connections is empty, and from > to. Do not interpret that as a protocol error. In an empty segment, total, from, and to are all 0.

Listings aggregate across the cluster, but pages are not an atomic snapshot. Connections can join or leave between requests, so a multi-page result can omit or repeat records. Presence events go to watchers on all server nodes of the channel. Presence events are not replayed. You get no event for a change that happened before you subscribed or while you were disconnected. A join can also arrive again for a connection that is already present, so handle joins by connection ID. Each presence event and each listing counts as a message for rate limits and usage. Refresh listings when current state matters, and do not treat presence as a durable user roster.

4. Release presence resources

presence_subscription.cancel();
refresh_listener.remove();
presence_listener.remove();

Close the channel when its owner no longer needs it. The default segment has automatic message membership, but it still needs subscribe_presence() to request presence events.

Next: Errors and troubleshooting.

We use Google cookies for analytics and for advertising measurement, only if you allow them. Until you choose, Google sets no cookies. Refer to our Cookie Policy.