Documentation

Rust Client API

The full reference for useceleris-client covers Client::new, Channel, Segment, the payload helpers, the types and the errors.

cargo add useceleris-client

The crate requires Rust 1.88 or newer, and the crate name is useceleris_client. It is async and runs on Tokio. Its WebSocket is tokio-tungstenite, and its TLS is rustls with the system's root certificates. A Client, its channels and their segments are cheap to clone and safe to use from many tasks. The generated documentation is on docs.rs.

Client::new()

impl Client {
    pub fn new(options: ClientOptions) -> Result<Client, CelerisError>;
}

pub struct ClientOptions {
    pub credential_provider: CredentialProvider,
    pub base_url: Option<String>,
    pub allow_insecure_loopback: bool,
    pub connect_timeout: Option<Duration>,
    pub reconnect_timeout: Option<Duration>,
    pub presence_query_timeout: Option<Duration>,
    pub publish_queue_size: Option<usize>,
    pub deduplication_window_size: Option<usize>,
    pub maximum_reconnect_attempts: Option<u32>,
}

impl ClientOptions {
    pub fn new(credential_provider: CredentialProvider) -> ClientOptions; // every default
}
FieldTypeDefaultDescription
credential_providerCredentialProviderNoneRequired. The SDK calls it for every connection attempt
base_urlOption<String>production endpointOnly for a local or self-hosted stack
allow_insecure_loopbackboolfalsePermits ws:// for loopback hosts. Never set it in production
connect_timeoutOption<Duration>15 sCovers credential acquisition and the handshake together. From 1 ms to 15 minutes
reconnect_timeoutOption<Duration>connect_timeoutThe same combined deadline for each reconnect attempt. From 1 ms to 15 minutes
presence_query_timeoutOption<Duration>10 sDeadline for one presence_list. From 1 ms to 15 minutes
publish_queue_sizeOption<usize>64Maximum number of publishes that wait for room in the writer. A full queue causes Backpressure. At least 1
deduplication_window_sizeOption<usize>1024Number of delivered message IDs that each channel keeps to drop replayed duplicates. At least 1
maximum_reconnect_attemptsOption<u32>10Failed reconnect attempts in one budget before the channel stops in Failed. From 1 to 100

Set the fields that you need and take the rest from ClientOptions::new:

let client = Client::new(ClientOptions {
    connect_timeout: Some(Duration::from_secs(5)),
    ..ClientOptions::new(provider)
})?;

Client::new performs no network work. None means the default. Client::new returns CelerisError::Configuration for a timeout outside 1 ms to 15 minutes, a size of 0, and a maximum_reconnect_attempts value outside 1 to 100. The message names every field that failed. base_url is the realtime socket endpoint, not your HTTP credential endpoint. It must be wss://, or ws:// to localhost or a loopback address with allow_insecure_loopback. The SDK always verifies TLS with its own rustls configuration. The TLS settings of your application have no effect on it.

Client

impl Client {
    pub fn channel(&self, reference: &str) -> Result<Channel, CelerisError>;
}

channel is side-effect free and returns a new connection handle on every call. A reference is 1 to 255 characters of [A-Za-z0-9_-]. Anything else returns CelerisError::Configuration.

Channel

impl Channel {
    pub fn reference(&self) -> &str;
    pub fn state(&self) -> ChannelState;
    pub fn events(&self) -> ChannelEventHandler;
    pub fn segment(&self, segment_id: &str) -> Result<Segment, CelerisError>;
    pub fn default_segment(&self) -> Segment; // segment("default")
    pub async fn connect(&self) -> Result<(), CelerisError>;
    pub async fn close(&self);
}

pub enum ChannelState {
    Idle,
    Connecting,
    Connected,
    Reconnecting,
    Failed,
    Closing,
    Closed,
}

impl ChannelState {
    pub fn as_str(self) -> &'static str; // "idle", "connecting", ...; Display prints the same
}
MemberNotes
stateThe current state. It can change as soon as it is read
connectReturns OperationInProgress if connecting, connected or reconnecting, NotConnected once closing or closed. An initial failure both returns and sets Failed. Dropping the future abandons the attempt and sets Failed.
closeIdempotent and terminal. Returns within about 5 s. Fails waiting publishes and queries with Cancelled. Ends every segment handle with the channel.
segment(id)Side-effect free. The id is required: non-empty, no CR or LF.
default_segment()The "default" segment every connection joins automatically.

A Channel is cheap to clone, and every clone is the same channel. You can recover a Failed channel when you call connect again. You cannot recover a Closed channel. The SDK does not automatically retry an initial connection failure. When you drop all handles of a channel without close, its connection stops without the closing handshake. See Reconnection and Recovery for triggers, deadlines, retry budgets and restored subscriptions.

A successful connect joins default. default_segment().on_message(listener) receives its messages without subscribe(). Read and write permissions still apply, and default membership includes no other segment and no presence subscription. The automatic join also happens on reconnect.

Segment

impl Segment {
    pub fn id(&self) -> &str;
    pub fn subscribe(&self) -> Result<Subscription, CelerisError>;
    pub fn subscribe_presence(&self) -> Result<Subscription, CelerisError>;
    pub fn on_message(&self, listener: impl Fn(&[u8], &MessageMetadata) + Send + Sync + 'static) -> Registration;
    pub fn on_presence(&self, listener: impl Fn(&PresenceEvent) + Send + Sync + 'static) -> Registration;
    pub async fn publish(&self, payload: impl AsRef<[u8]>) -> Result<(), CelerisError>;
    pub async fn publish_with_message_id(&self, payload: impl AsRef<[u8]>, message_id: &str) -> Result<(), CelerisError>;
    pub async fn presence_list(&self, page: i32, per_page: i32) -> Result<PresencePage, CelerisError>;
}

impl Subscription {
    pub fn cancel(&self); // idempotent; dropping a Subscription keeps the interest
}
MethodNotes
subscribeA real server operation, restored after every reconnect. Never sent for "default", which is joined automatically. Returns NotConnected once the channel is closing or closed.
on_message / on_presenceReturn a Registration that removes that listener. Handles for the same segment share one listener set. The payload is a borrowed slice. Copy it with to_vec() to keep it.
publishReturns on local acceptance only, with a generated message ID. An empty payload is valid. Returns Configuration for a command over 2 MiB encoded. The server enforces your plan's size limit afterwards. Does not join the connection to the segment. To receive messages, call subscribe. With read access only, the server does not accept the publish and sends a PermissionDeniedError through on_error. While the channel is Reconnecting, the publish waits in the publish queue. It goes out after the reconnect, after the restored subscriptions. Returns NotConnected before the first connect, during the first connect, and when the channel is Failed, Closing or Closed. Returns Backpressure when the publish queue is full. Dropping the future takes back a publish that the socket did not start to write.
publish_with_message_idpublish with your own ID: non-empty, no CR or LF. Receivers drop a repeated ID within their deduplication window.
subscribe_presenceTells the server to send join and leave events. It does not join the segment for messages, and it does not keep the segment. The watcher is not announced or listed because of it. Returns NotConnected once the channel is closing or closed.
presence_listOne in flight per channel. A second returns OperationInProgress. page is at least 1, per_page 1 to 100, both validated rather than clamped. A query the server refuses returns a Server error with sub_type Some("PRES_LIST") at once. A timeout or a dropped future frees the slot and leaves the connection up.

Payload helpers

pub fn text_payload(text: &str) -> Vec<u8>;
pub fn read_text(payload: &[u8]) -> Result<String, CelerisError>;

impl<Value, Failure> PayloadCodec<Value, Failure> {
    pub fn new(
        encode: impl Fn(&Value) -> Result<Vec<u8>, Failure> + Send + Sync + 'static,
        decode: impl Fn(&[u8]) -> Result<Value, Failure> + Send + Sync + 'static,
    ) -> PayloadCodec<Value, Failure>;
    pub fn encode_payload(&self, value: &Value) -> Result<Vec<u8>, Failure>;
    pub fn read_payload(&self, payload: &[u8]) -> Result<Value, Failure>;
}

text_payload encodes UTF-8 text. read_text returns Configuration for bytes that are not valid UTF-8. The crate depends on no serializer, so it has no JSON helper. Give serde_json::to_vec and serde_json::from_slice to PayloadCodec instead. The SDK returns errors from your own encode or decode unchanged. A PayloadCodec is cheap to clone. No size check happens here: publish enforces the encoded-command bound.

Types

pub struct MessageMetadata {
    pub token_reference: String,
    pub segment_id: String,
    pub message_id: String, // always present: the publisher's, or one the server assigned
    pub timestamp: i64,     // Unix milliseconds
}

pub struct PresenceEvent {
    pub segment_id: String,
    pub token_reference: String,
    pub connection_id: String,
    pub joined: bool, // false: the connection left
    pub timestamp: i64,
}

pub struct PresencePage {
    pub segment_id: String,
    pub total: i32,
    pub per_page: i32,
    pub current_page: i32,
    pub from: i32, // from > to past the last page
    pub to: i32,
    pub connections: Vec<PresenceConnection>,
}

pub struct PresenceConnection {
    pub token_reference: String,
    pub connection_id: String,
    pub timestamp: i64,
}

pub struct ServerNotice {
    pub timestamp: i64,
    pub payload: Vec<u8>,
}

pub struct RecoveryEvent {
    pub retry_index: u32,
    pub possible_gaps: bool,       // always true
    pub possible_duplicates: bool, // always true
}

pub struct CredentialRequest {
    pub channel_reference: String,
    pub reason: CredentialReason,
}

pub enum CredentialReason {
    Initial, // the attempt that connect starts
    Reconnect {
        disconnected_at: SystemTime,
        replay_lookback: Duration, // the outage plus 5 s
    },
}

pub struct Credentials {
    pub payload: String,
    pub signature: String,
}

impl CredentialProvider {
    pub fn new<Provide, Provided>(provide: Provide) -> CredentialProvider
    where
        Provide: Fn(CredentialRequest) -> Provided + Send + Sync + 'static,
        Provided: Future<Output = Result<Credentials, ProviderError>> + Send + 'static;
}

pub type ProviderError = Box<dyn std::error::Error + Send + Sync>;

Presence figures are signed 32-bit values as received. Timestamps are signed 64-bit Unix milliseconds. replay_lookback is whole milliseconds, at most 4294967295 ms. Debug shows Credentials as redacted. A provider must return non-empty values. Empty values return Configuration. The SDK reports any error the provider returns, or a panic, as Transport. When the attempt's deadline passes or the channel closes, the SDK drops the provider's future.

ChannelEventHandler

impl ChannelEventHandler {
    pub fn on_state_change(&self, listener: impl Fn(ChannelState) + Send + Sync + 'static) -> Registration;
    pub fn on_recovery(&self, listener: impl Fn(&RecoveryEvent) + Send + Sync + 'static) -> Registration;
    pub fn on_notice(&self, listener: impl Fn(&ServerNotice) + Send + Sync + 'static) -> Registration;
    pub fn on_error(&self, listener: impl Fn(&CelerisError) + Send + Sync + 'static) -> Registration;
    pub fn on_message(&self, listener: impl Fn(&[u8], &MessageMetadata) + Send + Sync + 'static) -> Registration;
}

impl Registration {
    pub fn remove(&self); // idempotent; dropping a Registration keeps the listener
}

Each registration returns a Registration, and remove removes that listener. Listeners run on Tokio's blocking thread pool, one at a time for each channel. They run in the order events happened, never under an SDK lock, and with no queue on your side. A slow listener delays delivery and does not grow a backlog. A listener can call subscribe, cancel and the listener methods directly. For an async method, it starts a task with tokio::spawn. The SDK catches a listener that panics and reports it through on_error. The SDK does not report a panic in an error listener. A recovery event follows the connected state change. It does not signal replay completion.

on_message receives all messages from all segments of the connection. It gets each message after the segment listeners, and it gets each message ID one time.

The Registration that on_message returns removes only this channel listener. The other channel listeners and the segment listeners continue to receive messages. The subscriptions do not change, and the SDK does not send a message to the server. When you call remove again, it has no effect.

on_error receives failures that no caller waits for. These are Server errors and SDK errors, such as an undecodable frame, a reconnect that gave up, or a listener that panicked. on_notice delivers raw server prose, such as subscription acknowledgments and refusals. It carries no segment id and no correlation id. Do not parse it.

Errors

#[non_exhaustive]
pub enum CelerisError {
    Configuration(String),
    Timeout(String),
    Cancelled(String),
    Transport(String),
    NotConnected(String),
    Backpressure(String),
    OperationInProgress(String),
    DeliveryUnknown(String),
    Protocol {
        message: String,
        field: &'static str,
        offset: usize, // zero-based byte offset into the server message
    },
    Server(ServerError),
}

CelerisError implements std::error::Error, Display, Clone and PartialEq. The message of an SDK variant says what failed and which rule or limit it broke, such as Invalid channel reference. Must not be empty.. The message never carries your input, credentials or server bytes. Match on the variant, never on message text. The enum is #[non_exhaustive], so a match needs a wildcard arm.

VariantReturned when
ConfigurationThe call is wrong, or a credential provider returned invalid credentials. Fix the code. Do not retry.
TimeoutThe connect deadline elapsed, or a presence query timed out
CancelledThe channel closed, or a newer attempt started, during a connect, a queued publish or a query
TransportHandshake or socket failure, a credential provider that failed or panicked, a listener that panicked, or a connection loss during a presence query
NotConnectedA publish before the first connect, during the first connect, or in Failed, Closing or Closed. A presence query while not Connected. A connect, subscribe or subscribe_presence once the channel is closing or closed
BackpressureThe publish queue (publish_queue_size, 64 by default) is full. A presence query also returns it while the writer is full or paused after a rate limit
OperationInProgressA second connect, or a second presence_list
DeliveryUnknownThe socket failed while writing a publish: acceptance genuinely unknown
ProtocolOne received frame could not be decoded. field and offset locate the failure
ServerAn error frame from the server. See ServerError

Protocol means the SDK could not decode one message. The SDK drops that message and reports the error, and the connection stays up. The SDK silently skips a command that this SDK version does not recognize, so a newer server cannot break a deployed client.

There is no authentication variant. The WebSocket handshake status is not exposed to the SDK, so it reports a refused handshake as Transport and does not guess.

ServerError

pub struct ServerError {
    pub error_type: ServerErrorType,
    pub sub_type: Option<String>, // the command it answers, e.g. "PUB"; None when none
    pub message: String,          // the server's own text, unchanged
    pub resource: ServerErrorResource,
}

#[non_exhaustive]
pub enum ServerErrorType {
    ParserError,
    SendError,
    PermissionDeniedError,
    RateLimitError,
    MessageSizeLimitError,
    InternalError,
    Other(String), // a type a newer server adds, exactly as sent
}

impl ServerErrorType {
    pub fn as_str(&self) -> &str; // the type as the server wrote it
}

pub enum ServerErrorResource {
    Null,
    Text(String),
    Integer32(i32),
    Integer64(i64),
    Array(Vec<ServerErrorResource>),
}

A ServerError is an error the server sent, with every field as sent, and the connection stays up. It arrives as CelerisError::Server through on_error, after the call that caused it, except for a presence query error, which presence_list returns instead. Keep a wildcard arm for types a newer server adds. Match the resource variant before you use it.

Errorsub_typeresource
A permission denial for a publish, subscribe or presence subscription"PUB", "SUB", "UNSUB", "PRES_SUB" or "PRES_UNSUB"The segment id
A refused or failed presence query"PRES_LIST"The query's request id, which the SDK sets
Anything elseNoneNull
error_typeSent when
PermissionDeniedErrorThe token lacks access to what the command tried
MessageSizeLimitErrorA command exceeded your plan's size limit
RateLimitErrorA per-second, per-hour, per-month or per-connection message limit was exceeded. The SDK pauses, then resends recent commands
ParserErrorThe server could not parse a command
SendErrorThe server failed to send
InternalErrorA fault inside the server, such as a failed presence read

Limits

LimitValue
Outbound command2 MiB encoded, rejected before any write
Encoded command, plan limitSet by your plan (Limits). Counts the framing, the identifiers and the payload. Enforced by the server
Writer bounds64 pending commands, 2 MiB of unsent data. Commands that do not fit wait. A subscription change goes ahead of queued publishes, but not ahead of an earlier publish to its own segment
Rate-limit recoveryPause of 1 s plus growing jitter (at most 31 s), then a resend of the last 2 s of commands (at most 64 publishes, each once). After 8 limits in a row, dropped subscriptions are retried after 1 min, doubling to 1 h
Duplicate filteringdeduplication_window_size message IDs per channel, 1024 by default. The window stays across reconnects and clears on connect
Publish queuepublish_queue_size publishes, 64 by default. Publishes that a dropped socket did not start to write go back to the front of the queue, even when the queue is full
Reconnectmaximum_reconnect_attempts failed attempts per budget, 10 by default, from 1 to 100. Full-jitter delays up to 30 s. Only Transport and Timeout failures count and retry. Other failures, such as invalid credentials, stop recovery at once. The budget resets at a drop after at least 60 s connected
Connect deadlineconnect_timeout, 15 s by default, covering credentials and handshake. A reconnect attempt uses reconnect_timeout, defaulting to it
Presence querypresence_query_timeout, 10 s by default, one in flight per channel
CloseAbout 5 s graceful, then forced
HeartbeatA WebSocket ping every 20 s keeps the connection open while a listener runs
Dead connectionA ping unanswered for 15 s of reading time, excluding time spent in listeners, means the path is dead: noticed within about 35 s, then recovered like any drop

The SDK does not check the size of received messages. They are already in memory when they arrive, so the SDK processes whatever the server sends. A publish rejected for your plan's size limit still counts toward your usage. A local encoded-command rejection sends nothing.

What this SDK will not do

The SDK does not do these tasks:

  • Confirm delivery. There are no receipts anywhere in the protocol.
  • Keep a durable offline queue. Publishes wait in an in-memory queue only while the channel is Reconnecting. The SDK resends publishes only after a rate limit, once each, with their original ID.
  • Provide durable history or global ordering. Replay is a bounded window, not a cursor.
  • Sign anything. The signer lives in useceleris-server.

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.