Skip to main content

Client

Struct Client 

Source
pub struct Client { /* private fields */ }
Available on crate feature client only.
Expand description

Calls Centrifugo’s HTTP server API: a method per API method, taking its request and returning its result.

It is cheap to clone, and safe for concurrent use: create one and share it. It runs on tokio: calls are made from a tokio runtime, the one its first call was made from, whose tasks send its automatic batches and own its connections. A program with several runtimes creates a client per runtime; one without any uses blocking::Client.

let client = cent::Client::new(cent::Config::new("http://localhost:8000/api").api_key("secret"))?;
let data = cent::json(&serde_json::json!({"text": "hello"}))?;
let res = client.publish(cent::PublishRequest::new("news").data(data)).await?;
println!("published at offset {}", res.offset);

Implementations§

Source§

impl Client

Source

pub fn new_batch(&self, options: BatchOptions) -> Batch

Returns an empty batch, sent by this client and run as options say. BatchOptions::default() runs the commands one by one, in the order they were added.

Source§

impl Client

Source

pub fn new(config: Config) -> Result<Self, Error>

Returns a client for config, or an Error::InvalidConfig naming what is wrong with it.

Source

pub fn with_timeout(&self, timeout: Duration) -> Self

Returns a handle to the same client whose calls each time out after timeout: the call’s own timeout, which replaces the configured request_timeout for it, longer or shorter (spec 3.2). Zero is refused: the calls fail with Error::InvalidConfig. A deadline set with with_deadline still ends a call sooner. It is cheap: make one per call that needs it.

use std::time::Duration;
let info = client.with_timeout(Duration::from_millis(500)).info(cent::InfoRequest::new()).await?;

A timeout around a call’s future - tokio::time::timeout - ends it too, by dropping it; within an automatic batch, a call dropped before its batch is sent leaves without being sent. The client’s own timeout lets it report the timeout to Config::on_request, and a batch know how long its calls wait.

Source

pub fn with_deadline(&self, deadline: Instant) -> Self

Returns a handle to the same client whose calls end at deadline at the latest - for several calls sharing one, such as the attempts of a retry loop and the waits between them (see wait).

A deadline only shortens a call, never extends it (spec 3.2): each call still times out after request_timeout, or its own with_timeout, when that comes first. A handle with a deadline already keeps the earlier of the two.

Source

pub async fn close(&self, timeout: Duration) -> Result<(), Error>

Stops the client: calls made from now on return Error::Closed, and close waits for the calls in progress to end - requests on their way, calls queued for an automatic batch, batches sent for callers who left. A broadcast being retried stops at its next attempt. It returns Error::Timeout when timeout passes first; the calls left go on then. With its default HTTP client the client then closes its idle connections. It may be called again: it waits as the first call did.

Call it when the application shuts down - on SIGTERM - so that what was accepted is sent before the process exits.

Source§

impl Client

Source

pub fn history_all(&self, request: HistoryRequest) -> Pager<HistoryItem>

The publications of a channel’s history, oldest first, limit at a time: from since when it is set, from the start of what the channel keeps otherwise. A page is read when the iteration reaches it, and the iteration ends after a page shorter than limit. Each item is a HistoryItem: the publication, which it derefs to, and its position, to resume from.

// Read what came after a publication.
let published = client.publish(cent::PublishRequest::new("news").data(data)).await?;
let mut after = client.history_all(
    cent::HistoryRequest::new("news").limit(100).since(published.position()),
);
let mut last = None;
while let Some(item) = after.next().await {
    let item = item?;
    println!("{}", item.offset);
    last = Some(item.position()); // to resume from later
}

limit is the page size, so it must be 1 or more, and reverse is refused: since reads forward only. Either fails with Error::InvalidRequest before anything is sent. A publication made while iterating may or may not be seen. A position whose epoch is no longer the stream’s - the history was lost, with a Redis restart say - fails with code 112, ApiError::UNRECOVERABLE_POSITION: the publications after the last one seen are gone, and reading again from the start is the only way on.

Source

pub fn device_list_all(&self, request: DeviceListRequest) -> Pager<Device>

Every device request selects, a page at a time, each page read when the iteration reaches it: limit is the page size, the server’s default when unset. A device registered or removed while iterating may or may not be seen.

Centrifugo PRO only.

Source

pub fn device_topic_list_all( &self, request: DeviceTopicListRequest, ) -> Pager<DeviceTopic>

Every device topic request selects, a page at a time, as device_list_all reads devices.

Centrifugo PRO only.

Source

pub fn user_topic_list_all( &self, request: UserTopicListRequest, ) -> Pager<UserTopic>

Every user topic request selects, a page at a time, as device_list_all reads devices.

Centrifugo PRO only.

Source

pub fn map_read_state_all( &self, request: MapReadStateRequest, ) -> Pager<MapStateItem>

Every entry of a map channel’s state, a page at a time, each page read when the iteration reaches it: limit is the page size.

Every page after the first is read at the first one’s revision - its position, as revision_offset and revision_epoch, unless request sets either - so that the map’s stream reset between pages fails with code 112, ApiError::UNRECOVERABLE_POSITION, instead of mixing two states: read again from the start then. Entries changed while iterating may be seen in either version; for a consistent view, read the changes since the first page’s position with map_read_stream, from the state every MapStateItem carries. Each item derefs to its MapEntry.

Source§

impl Client

Source

pub async fn broadcast( &self, request: BroadcastRequest, ) -> Result<BroadcastResult, Error>

Publishes the same data into many channels in one request: the way to send one message to many channels, Centrifugo doing the work of all the publications at once.

Channels succeed or fail on their own. It returns every channel’s outcome when every channel got the publication, and otherwise an error:

  • Error::BroadcastFailedChannels when Centrifugo carried the broadcast out and one or more channels failed, up to all; it holds every channel’s outcome.
  • Any other error when the broadcast failed as a whole: no channel got a reply. After a timeout or a network error Centrifugo may still have published it.

To go on despite some failed channels:

match client.broadcast(request).await {
    Ok(_) => {}
    Err(cent::Error::BroadcastFailedChannels(e)) => {
        for (channel, err) in e.errors() {
            eprintln!("not published into {channel}: {err}");
        }
    }
    Err(e) => return Err(e), // no channel got a reply
}

Retry a broadcast with broadcast_with_retry: it sends again only the channels which may still succeed, with one idempotency_key. Calling broadcast again after some channels failed sends the publication to every channel again, those which got it included - twice, without an idempotency_key or with the NATS broker, which ignores keys.

Source

pub async fn broadcast_with_retry( &self, request: BroadcastRequest, options: BroadcastRetryOptions, ) -> Result<BroadcastResult, Error>

Broadcasts as broadcast does, and retries the channels which failed for a temporary reason - see retryable - up to options’ max_attempts.

  • Only the channels which may still succeed are sent again. A channel which failed for good, an unknown channel say, is not, and when only such channels are left, it stops.
  • Every attempt carries the same idempotency_key, so that a channel which got the publication in an earlier attempt - even one reported as failed, after a timeout - does not get it again. When the request has none, a random one is made for the call. The memory, Redis and PostgreSQL brokers keep keys; with the NATS broker a retry may publish again.
  • The result holds every channel’s last outcome: the publication’s position from whichever attempt succeeded, or the error of its last attempt. Its idempotency_key is the key the attempts used: retrying the broadcast later with it, after this call gave up, publishes only into the channels which did not get it yet.

Each attempt is a request of its own, timing out after attempt_timeout, or request_timeout. The call’s deadline - the handle’s with_timeout from the call’s start, or its with_deadline, whichever comes first - bounds the whole call, the waits between attempts included: an attempt ends at it, and once it passes no attempt follows. Without either, max_attempts and the attempts’ timeouts bound the call.

It returns as broadcast does: every channel’s outcome when every channel got the publication, an Error::BroadcastFailedChannels listing those which still failed when some attempt got a reply, and otherwise the last attempt’s error. When the retries stop early - by the callback, or by the deadline while waiting - the error is an Error::RetryStopped holding the broadcast’s error.

Source§

impl Client

Source

pub async fn publish( &self, request: PublishRequest, ) -> Result<PublishResult, Error>

Publishes data into a channel.

Source

pub async fn subscribe( &self, request: SubscribeRequest, ) -> Result<SubscribeResult, Error>

Subscribes active sessions of a user to a channel (server-side subscription). It does not create a streaming subscription for the caller.

Source

pub async fn unsubscribe( &self, request: UnsubscribeRequest, ) -> Result<UnsubscribeResult, Error>

Unsubscribes a user from a channel.

Source

pub async fn disconnect( &self, request: DisconnectRequest, ) -> Result<DisconnectResult, Error>

Disconnects a user’s connections.

Source

pub async fn presence( &self, request: PresenceRequest, ) -> Result<PresenceResult, Error>

Returns the online presence of a channel: all clients currently subscribed to it. Presence must be enabled for the channel.

Source

pub async fn presence_stats( &self, request: PresenceStatsRequest, ) -> Result<PresenceStatsResult, Error>

Returns short presence information of a channel: the number of clients and of unique users. Presence must be enabled for the channel.

Source

pub async fn history( &self, request: HistoryRequest, ) -> Result<HistoryResult, Error>

Returns publications from the history of a channel. History must be enabled for the channel.

Source

pub async fn history_remove( &self, request: HistoryRemoveRequest, ) -> Result<HistoryRemoveResult, Error>

Removes publications from the history of a channel. The current top stream position is kept, so clients do not get disconnected because of insufficient state.

Source

pub async fn info(&self, request: InfoRequest) -> Result<InfoResult, Error>

Returns information about the running Centrifugo nodes.

Source

pub async fn refresh( &self, request: RefreshRequest, ) -> Result<RefreshResult, Error>

Refreshes a user’s connections, mostly useful with unidirectional transports. Without expire_at the connections become non-expiring.

Source

pub async fn channels( &self, request: ChannelsRequest, ) -> Result<ChannelsResult, Error>

Returns active channels (with one or more subscribers). It can be heavy on large deployments: there is no pagination.

Source

pub async fn connections( &self, request: ConnectionsRequest, ) -> Result<ConnectionsResult, Error>

Returns information about active connections, without the need to enable presence. At least one of user, expression or label_filter must be set. Centrifugo PRO only.

Centrifugo PRO only.

Source

pub async fn update_user_status( &self, request: UpdateUserStatusRequest, ) -> Result<UpdateUserStatusResult, Error>

Marks users as active and online now, and sets their state when one is given. Centrifugo PRO only.

Centrifugo PRO only.

Source

pub async fn get_user_status( &self, request: GetUserStatusRequest, ) -> Result<GetUserStatusResult, Error>

Returns the status of users. Centrifugo PRO only.

Centrifugo PRO only.

Source

pub async fn delete_user_status( &self, request: DeleteUserStatusRequest, ) -> Result<DeleteUserStatusResult, Error>

Deletes the status of users. Centrifugo PRO only.

Centrifugo PRO only.

Source

pub async fn block_user( &self, request: BlockUserRequest, ) -> Result<BlockUserResult, Error>

Blocks a user: the user is disconnected and can not connect again until unblocked or the block expires. Centrifugo PRO only.

Centrifugo PRO only.

Source

pub async fn unblock_user( &self, request: UnblockUserRequest, ) -> Result<UnblockUserResult, Error>

Unblocks a user. Centrifugo PRO only.

Centrifugo PRO only.

Source

pub async fn revoke_token( &self, request: RevokeTokenRequest, ) -> Result<RevokeTokenResult, Error>

Revokes a token by its unique ID (jti claim of a JWT). Clients using the token are disconnected shortly, and can not connect with it again. Centrifugo PRO only.

Centrifugo PRO only.

Source

pub async fn invalidate_user_tokens( &self, request: InvalidateUserTokensRequest, ) -> Result<InvalidateUserTokensResult, Error>

Revokes all tokens of a user issued before a certain time (based on the iat claim of a JWT). Centrifugo PRO only.

Centrifugo PRO only.

Source

pub async fn device_register( &self, request: DeviceRegisterRequest, ) -> Result<DeviceRegisterResult, Error>

Registers a device for push notifications, or updates a registered one. Centrifugo PRO only.

Centrifugo PRO only.

Source

pub async fn device_update( &self, request: DeviceUpdateRequest, ) -> Result<DeviceUpdateResult, Error>

Updates registered devices, selected by ids and/or users. Centrifugo PRO only.

Centrifugo PRO only.

Source

pub async fn device_remove( &self, request: DeviceRemoveRequest, ) -> Result<DeviceRemoveResult, Error>

Removes devices, selected by ids and/or users. Centrifugo PRO only.

Centrifugo PRO only.

Source

pub async fn device_list( &self, request: DeviceListRequest, ) -> Result<DeviceListResult, Error>

Returns a paginated list of registered devices. Centrifugo PRO only.

Centrifugo PRO only.

Source

pub async fn device_topic_list( &self, request: DeviceTopicListRequest, ) -> Result<DeviceTopicListResult, Error>

Returns a paginated list of device topic subscriptions. Centrifugo PRO only.

Centrifugo PRO only.

Source

pub async fn device_topic_update( &self, request: DeviceTopicUpdateRequest, ) -> Result<DeviceTopicUpdateResult, Error>

Changes the topics of a device. The device topic list is what decides who gets a push sent to a topic. Centrifugo PRO only.

Centrifugo PRO only.

Source

pub async fn user_topic_list( &self, request: UserTopicListRequest, ) -> Result<UserTopicListResult, Error>

Returns a paginated list of user topic subscriptions. Centrifugo PRO only.

Centrifugo PRO only.

Source

pub async fn user_topic_update( &self, request: UserTopicUpdateRequest, ) -> Result<UserTopicUpdateResult, Error>

Changes the topics of a user. The change is also applied to the user’s registered devices. Centrifugo PRO only.

Centrifugo PRO only.

Source

pub async fn send_push_notification( &self, request: SendPushNotificationRequest, ) -> Result<SendPushNotificationResult, Error>

Sends a push notification. The request is queued and sent to the provider by Centrifugo workers. Centrifugo PRO only.

Centrifugo PRO only.

Source

pub async fn update_push_status( &self, request: UpdatePushStatusRequest, ) -> Result<UpdatePushStatusResult, Error>

Saves the delivery or interaction status of a push notification to analytics. Experimental. Centrifugo PRO only.

Centrifugo PRO only.

Source

pub async fn cancel_push( &self, request: CancelPushRequest, ) -> Result<CancelPushResult, Error>

Cancels a delayed push notification (sent with send_at). Centrifugo PRO only.

Centrifugo PRO only.

Source

pub async fn map_publish( &self, request: MapPublishRequest, ) -> Result<MapPublishResult, Error>

Publishes or updates a key in a map channel.

Source

pub async fn map_remove( &self, request: MapRemoveRequest, ) -> Result<MapRemoveResult, Error>

Removes a key from a map channel.

Source

pub async fn map_read_state( &self, request: MapReadStateRequest, ) -> Result<MapReadStateResult, Error>

Reads the current state of a map channel, with optional pagination.

Source

pub async fn map_read_stream( &self, request: MapReadStreamRequest, ) -> Result<MapReadStreamResult, Error>

Reads the change stream of a map channel.

Source

pub async fn map_stats( &self, request: MapStatsRequest, ) -> Result<MapStatsResult, Error>

Returns statistics about a map channel.

Source

pub async fn map_clear( &self, request: MapClearRequest, ) -> Result<MapClearResult, Error>

Removes all state and stream data of a map channel.

Source

pub async fn shared_poll_publish( &self, request: SharedPollPublishRequest, ) -> Result<SharedPollPublishResult, Error>

Pushes data for a key directly to clients of a shared poll channel, without waiting for the next poll cycle. Requires versioned mode and publish_enabled on the namespace.

Trait Implementations§

Source§

impl Clone for Client

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Client

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more