Documentation

Connection and Lifecycle

Fetch credentials, connect a channel, observe recovery, and release resources.

Before you start: add useceleris-client from the overview. Prepare an endpoint that signs credentials, as Authentication describes. A trusted backend can sign its own credentials instead. See Server-side usage.

1. Fetch credentials

The SDK has a built-in production endpoint. Supply a credential provider that calls your application's credential endpoint. This example uses reqwest, serde, and serde_json, which the client does not include:

cargo add reqwest --features json
cargo add serde --features derive
cargo add serde_json
use std::error::Error;

use serde::Deserialize;
use useceleris_client::{
    Client, ClientOptions, CredentialProvider, CredentialReason, CredentialRequest, Credentials,
    ProviderError,
};

#[derive(Deserialize)]
struct CredentialResponse {
    payload: String,
    signature: String,
}

async fn fetch_credentials(request: CredentialRequest) -> Result<Credentials, ProviderError> {
    let replay_lookback_milliseconds = match request.reason {
        CredentialReason::Initial => None,
        CredentialReason::Reconnect { replay_lookback, .. } => Some(replay_lookback.as_millis() as u64),
    };

    let response: CredentialResponse = reqwest::Client::new()
        .post("https://your-app.example/api/realtime-credentials")
        .bearer_auth("...")
        .json(&serde_json::json!({
            "channelReference": request.channel_reference,
            "replayLookbackMs": replay_lookback_milliseconds,
        }))
        .send()
        .await?
        .error_for_status()?
        .json()
        .await?;

    Ok(Credentials {
        payload: response.payload,
        signature: response.signature,
    })
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    let client = Client::new(ClientOptions::new(CredentialProvider::new(fetch_credentials)))?;
    let channel = client.channel("demo-room")?;

    // The steps below continue here.

    channel.close().await;

    Ok(())
}

The provider receives a CredentialRequest with channel_reference and reason. reason is CredentialReason::Initial for the attempt that connect starts. It is CredentialReason::Reconnect for automatic recovery, with disconnected_at (a SystemTime) and replay_lookback (a Duration). When the attempt's deadline passes or the channel closes, the SDK drops the provider's future. The SDK discards a result that arrives after that.

Debug shows Credentials as redacted. Return both values exactly as your backend signed them. Do not generate, cache, or inspect them. If the provider returns an error or panics, the SDK reports a safe CelerisError::Transport. The SDK does not forward the original failure details.

When you create a client, a channel, or a segment, the SDK does not open a connection. Use base_url only for local or self-hosted Celeris, not your application's credential endpoint. See the Rust client API for the options.

2. Observe state, then connect

let events = channel.events();

let state_listener = events.on_state_change(|state| println!("Connection: {state}"));
let error_listener = events.on_error(|error| println!("Error: {error}"));

if let Err(error) = channel.connect().await {
    println!("Initial connection failed: {error}");
}

The expected states are connecting, then connected. A failed initial attempt returns its error from connect and sets failed. The SDK does not also report that failure to on_error, and it does not retry the attempt automatically.

Once connected, the channel is automatically a member of default. Use channel.default_segment() to access that stream. Do not open another connection or call subscribe() just to join it. Register its message listener before or after you connect. Make sure that your credentials grant read/write access to default. See default-segment messaging.

StateWhat your program must do
ChannelState::IdleCall connect when ready
ChannelState::ConnectingWait. Do not make another connect call
ChannelState::ConnectedPublish, subscribe, and query
ChannelState::ReconnectingShow the connection status. A publish waits in the queue
ChannelState::FailedExplain the failure. Call connect again to retry
ChannelState::ClosingWait for cleanup
ChannelState::ClosedCreate a new channel if you need another connection

A connect call in the connected, connecting, or reconnecting state returns CelerisError::OperationInProgress.

To stop a connection attempt, drop its future, for example with a deadline from tokio::time::timeout. The channel then sets failed:

use std::time::Duration;

match tokio::time::timeout(Duration::from_secs(5), channel.connect()).await {
    Ok(Ok(())) => println!("Connected"),
    Ok(Err(error)) => println!("Connect failed: {error}"),
    Err(_elapsed) => println!("{}", channel.state()), // failed
}

The deadline bounds only the attempt. An established connection outlives it. The connect_timeout option, 15 seconds by default, bounds the credentials and the handshake together. When this timeout passes, connect returns CelerisError::Timeout. reconnect_timeout bounds a reconnect attempt and defaults to connect_timeout. Each timeout option accepts from 1 ms to 15 minutes, and None means the default. For any other value, Client::new returns CelerisError::Configuration.

3. Respond to recovery

Register a recovery listener once when you set up the channel:

let recovery_listener = events.on_recovery(|event| {
    println!("Recovered after retry {}", event.retry_index);
    // Reload your application's authoritative state here.
});

retry_index is the number of failed reconnect attempts already used in the current budget. It is 0 when recovery succeeds without an earlier failed attempt in that budget. possible_gaps and possible_duplicates are always true. Reload the authoritative state from your own API. Then reconcile new messages with an application-owned version.

Recovery stops after maximum_reconnect_attempts failed attempts in one budget. The default is 10, and the option accepts from 1 to 100. A new budget starts when a connection drops after 60 seconds or more in the connected state. Only Transport and Timeout failures count. Any other failure stops recovery at once. When recovery stops, on_error gets the cause, and the channel sets failed. Call connect to try again.

The SDK sends a WebSocket ping every 20 seconds, so the connection stays open while a listener runs. If a ping gets no answer within 15 seconds, the SDK treats the connection as dead and starts recovery. The SDK does not count the time that your listeners use.

Listeners survive reconnects. Do not register them again on every connected state. The SDK catches a panic in a listener and reports it through on_error. The SDK does not catch a panic in a task that your listener starts.

Replay sends at most the last 100 messages of each segment, for at most 2 minutes. default replays when the channel connects. Other segments replay when the connection joins them with subscribe. A publish starts no replay. If the reconnect credentials have no replay claim, the missed messages are not available, and the recovery event reports the gap. See Reconcile application data. See Replay.

See Reconnection and Recovery for triggers, timing, restored interests, and replay. The recovery event is not a replay-complete signal.

4. Release resources

Each registration returns a Registration, and its remove() removes the listener. Subscription handles have cancel(). The channel owns the socket.

channel.close().await;
recovery_listener.remove();
error_listener.remove();
state_listener.remove();

When you drop a Registration, the listener stays. You do not have to keep the Registration of a listener that stays for the life of the channel.

close is idempotent and permanent. It returns within about five seconds, even when the server does not answer. It fails queued publishes and presence queries with CelerisError::Cancelled. It cancels recovery and ends the channel's segment handles too. Listeners can still receive events that the SDK queued before close returned, such as the closed state change. Do not reuse a closed channel. Obtain a new one from the client.

Close each channel when you do not need it. When you drop all handles of a channel without close, its connection stops without the closing handshake.

Next: Messaging.

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.