cent
Rust SDK for the HTTP server API
of Centrifugo: every API method,
including those of Centrifugo PRO, in an async Client and a blocking one;
connection, subscription and server API tokens; the proxy handlers and the
endpoints client SDKs call. For a real-time client over WebSocket, see
centrifuge-rust.
| Version | |
|---|---|
| Rust | 1.85 or newer |
| Centrifugo | v6, any release |
| Map and shared poll methods | Centrifugo v6.8.0 or newer |
ApiError::temporary, code 111 (too many requests), refused requests reported as such rather than as internal errors |
Centrifugo v6.10.0 or newer |
Ed25519 tokens verified without JWKS, by client.token.ed25519_public_key |
Centrifugo v6.10.2 or newer |
| Methods marked "Centrifugo PRO only" | Centrifugo PRO v6 |
| Feature | Default | What |
|---|---|---|
client |
yes | The async Client, on tokio, with hyper and rustls (the operating system's trust store) |
token |
yes | Connection, subscription and API tokens, JWKS, shared poll signatures |
blocking |
blocking::Client, for code without an async runtime |
|
tower |
The HTTP handlers as tower::Services, for axum, hyper and tower stacks |
cent implements the Centrifugo server SDK specification, version 0.2, whose reference implementation is gocent.
Example
use ;
use json;
# async
Every API method is a Client method taking its request and returning its
result: a struct generated from Centrifugo's api.proto, with its
documentation. A request's new takes the fields Centrifugo requires, and a
method per field sets the others. Create the client once and share it: it is
cheap to clone, and safe for concurrent use.
Payloads
data, info, meta and the other payloads are JSON, as Box<RawValue> of
serde_json - in requests, and in results, where a payload is kept exactly as
Centrifugo sent it, number text included. A payload from a reply sent back
unchanged is the same JSON value. Encode any serde type with cent::json;
pass JSON you already have - from a database, a queue - with
RawValue::from_string(text), which checks it is JSON; decode one with
PayloadExt::decode. A payload set to JSON null is sent as null; one not
set is not sent.
use PayloadExt;
#
serde_json writes NaN and infinities as null, which the client cannot tell
from a null you meant: check floats before encoding them. Binary data goes
base64-encoded in the b64 fields, such as b64data.
Write integers which may pass 2^53 - a 64-bit ID, say - as JSON strings: browsers and JavaScript backends decode JSON numbers as doubles, and round larger integers silently.
Timeouts
Each call is bounded by one deadline: the client's request_timeout, ten
seconds by default, or one of its own:
# async
The deadline bounds the whole call - the endpoint and token functions,
connecting, the reply read, a reply trickling in included. However a call
times out, the error is Error::Timeout. with_deadline gives several calls
one deadline, such as the attempts of a retry loop and the waits between
them. A timeout around a call's future, tokio::time::timeout, ends it too.
broadcast_with_retry makes several requests in one call: its deadline bounds
them all, waits between them included, and attempt_timeout each one.
Errors
Error |
Meaning |
|---|---|
Api |
Centrifugo refused the request or failed to carry it out: code, message, temporary. Compare err.api_code() with ApiError::UNKNOWN_CHANNEL and the other constants |
BroadcastFailedChannels, BatchFailedCommands |
some parts of a broadcast or batch failed - see below |
Http |
the request did not reach the API method: status, body, headers; err.is_unauthorized() for refused credentials |
Decode |
the reply was not Centrifugo's - usually api_endpoint points elsewhere |
InvalidRequest |
the client could tell the request is wrong and did not send it |
InvalidConfig |
the client was not created, or is used where it cannot work: the message names the option and the fix |
Timeout, Network, Closed |
as their names say |
Callback |
the application's api_endpoint or bearer_token function failed |
Centrifugo adds error codes over time: an unknown code is still an
Error::Api, so match the codes you handle and treat the rest by kind.
Retries
cent::retryable(&err), or err.is_retryable(), reports whether a new
attempt, with time left, may succeed: the error came from a temporary
condition - a broker being unavailable, a rate limit, the network - not from
the request.
A temporary error does not mean nothing was done: after a timeout, or even an
internal error, the publication may have happened. So retry a publication only
with an idempotency_key, and back off between a bounded number of attempts:
# async
Choosing keys:
- One key per publication or broadcast, reused only to retry that same one. A broadcast needs one key, not one per channel.
- Centrifugo remembers a key per channel, for five minutes by default. A retry
within that time is answered with the first result and not published again -
and so is a different publication into the same channel under the same
key. A key built from an ID must name the event too:
order-42-paid, notorder-42. - The memory, Redis and PostgreSQL brokers keep keys. The NATS broker ignores them, so with it a retry publishes again.
Retry a broadcast with broadcast_with_retry rather than a loop: see below.
Broadcast and batch
broadcast publishes the same data into many channels in one request; a batch
sends many commands at once. Both return an error unless every part succeeded:
# async
Parts succeed or fail on their own. When Centrifugo carried the request out
and some parts failed, up to all, the error is Error::BroadcastFailedChannels
or Error::BatchFailedCommands: its failed() lists them, and its result()
holds every part's outcome. Any other error means the request failed as a
whole - the network, the credentials, an invalid request - and no part got a
reply; after a timeout or a network error Centrifugo may still have carried it
out.
A partial error is not an error of its parts: err.api_code() is None for a
broadcast in which a channel was unknown, also one into a single channel -
publish is the call for one channel. To go on despite some failed parts:
# async
Retrying:
-
a broadcast:
broadcast_with_retrydoes it. It sends again only the channels which may still succeed, all attempts with oneidempotency_key- made for the call when the request has none - and returns every channel's last outcome, asbroadcastdoes. By default it retries once, after about 100 milliseconds:# asyncThe callback returns a
Retry: the default wait, a wait of its own, or stop - so a callback which only logs cannot stop the retries by accident. AnError::Httpina.errorcarries the reply'sheaders: wait at least itsRetry-Afterto honour one.res.idempotency_keyis the key the attempts used: to retry the broadcast later, after it gave up - from a job queue, say- send it with that key. Repeating
broadcaston any error would instead send it to every channel again, those which already got it included.
- send it with that key. Repeating
-
a batch: build a new one, with the same keys, from the commands whose error is retryable. A batch is sent once:
sendtakes it.
BatchOptions::default() runs the commands one by one, in order;
.parallel(true) runs them concurrently. Centrifugo PRO sends a batch's
publications to its broker together: each channel's publications still take
effect in order, but publications into different channels may not, unless the
namespace sets publication_grouping_disabled.
Automatic batching
With auto_batch, calls made concurrently go out together once enough
requests are in flight - with no delay otherwise, since nothing waits for a
timer:
#
It is for processes making many calls at once - a server publishing for every
request it serves, a worker draining a queue concurrently. Choose
max_in_flight at about half the calls the process makes at once: above them
it never batches, and just below it batches calls one at a time, only
limiting them.
Every call still gets its own result or error, and keeps its own deadline. Calls sharing a batch share its request, though: if the request itself fails
- the network, a body too large for a proxy in front of Centrifugo (nginx
refuses bodies over 1 MB by default) - every call in it fails. Lower
max_batch_size, 1000 by default, or raise the proxy's limit.
Authentication
api_key is sent in the X-API-Key header. bearer_token instead sends a
token as Authorization: Bearer, for Centrifugo PRO's JWKS authentication -
it is called for every request, so return a cached token. Leave both unset
when mutual TLS, set up in your HttpClient, or a proxy authenticates
instead.
To sign the tokens yourself, token::ApiTokens issues them and reuses each for
half its lifetime:
#
Centrifugo PRO accepts a token signed with any key of http_api.jwks.endpoint,
and checks the audience, issuer and scope only when configured to. So keep API
tokens apart from the connection and subscription tokens your users hold - or
any user can call the server API with their connection token:
- publish the API keys with
endpoints::jwks(&api_keys)at an endpoint of their own, not the one ofclient.token.jwks_public_endpoint; - set
http_api.jwks.audienceandhttp_api.jwks.scopeto values only API tokens carry -token::apirefuses claims with neither.
Refused credentials make every call fail with Error::Http 401:
err.is_unauthorized().
HTTP client, tracing and metrics
The default HTTP client is hyper with rustls, verifying certificates with the
operating system's trust store. It keeps up to 256 connections to Centrifugo
alive, keeps all of them while idle, closes idle ones after 50 seconds, speaks
HTTP/2 where TLS negotiates it, and never follows redirects - a redirect is an
Error::Http with a hint to check the endpoint. It sets no timeouts of its
own: each call's deadline bounds it. It does not read the HTTP_PROXY
variables: give the client an HttpClient of your own to go through a proxy.
An HttpClient is any function from an http::Request<Bytes> to a future of
the response - for tracing, wrap the default one:
#
on_request is told of every request - method, commands and how many failed,
duration, status, error - for metrics without a dependency of the crate's. It
and the handlers' on_error must not panic: a panic is the call's, or the
handler's.
Testing your code
Code using the client is tested without Centrifugo by giving the client an
HttpClient answering as Centrifugo does: a method's reply is
{"result": {...}} or {"error": {"code": ..., "message": ...}}; a
broadcast's, {"result": {"responses": [...]}} with one response per channel;
a batch's, {"replies": [...]} with one reply per command, {"<method>": {...}}
or {"error": {...}}.
# async
The partial-failure errors and the results they carry are constructible for
test doubles of your own: BroadcastResult::new, ChannelResult::new,
BroadcastFailedChannelsError::new, BatchResult::new, FailedCommand::new,
BatchFailedCommandsError::new, Pending::new.
Shutdown
client.close(timeout) refuses new calls with Error::Closed and waits for
the ones in progress, automatic batches included, so that what was accepted is
sent before the process exits. It returns Error::Timeout when calls are still
in progress after timeout; they go on.
The blocking client
cent::blocking::Client - with the blocking feature - has the same methods,
options, errors and behaviour, and returns results instead of futures. It
runs the async client on a tokio runtime of its own. After a fork, a client
used in the child starts a runtime and connections of its own.
The async Client runs on the tokio runtime 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 - the client says so
rather than failing with the runtime's error.
HTTP handlers
The proxy handlers, the endpoints client SDKs call and the JWKS endpoint are
each a Handler: one function, handler.handle(http::Request<Bytes>), from a
request with its body to a response, holding all of the endpoint's behaviour.
With the tower feature a Handler is a tower::Service: in axum,
Router::new().route_service("/centrifugo/connect", handler). From any other
framework, build the http::Request and turn the response back. The function
a handler calls gets the request's http::request::Parts: headers, URI and
extensions - where a middleware puts the authenticated user.
Proxy
cent::proxy is the backend side of Centrifugo's HTTP proxy, which calls your
application when a client connects, subscribes, publishes or makes an RPC
call: a handler per proxy type, taking an async function.
use ;
let handlers = new.on_error;
let subscribe = handlers.subscribe;
#
Return a result to accept the request, a proxy::Error - a code in
[400, 1999] - to reject it with an error the client receives, or a
proxy::Disconnect - a code in [4000, 4999], those in [4500, 4999] telling the
client not to reconnect, and a reason of at most 32 bytes - to close the
client's connection. Any other error, which ? turns into a rejection, fails
the request with 500 and goes to on_error to be logged. Keep proxy endpoints
reachable by Centrifugo only: whoever can call them can claim to be any user.
Tokens
cent::token issues the JWTs Centrifugo authenticates clients with -
connection and subscription tokens, with Centrifugo's claims, signed with
HMAC, RSA, ECDSA or Ed25519 - and cent::endpoints serves the endpoints the
getToken callbacks of client SDKs call:
use Duration;
use ;
use ;
let key = hmac?; // client.token.hmac_secret_key
let connection_token = new.connection_token;
# Ok::
An expiry is required: Expiry::At(time), or Expiry::Never for a token
accepted forever, chosen explicitly. A connection token's meta is never shown
to other clients, but the user owning the token can read it: put nothing in it
that user must not see. subscription_token serves subscription tokens the same
way, with the channel the client asks for.
With RSA, ECDSA or Ed25519 keys - Key::from_pem, Key::ed25519 -
endpoints::jwks(&keys) publishes the public keys for Centrifugo's
jwks_public_endpoint: the way to rotate keys without restarting Centrifugo.
Publish a new key next to the old one; sign with it only once every instance
of the application publishes it - from an activation time set ahead, or in a
second deploy; drop the old key once its tokens expired. Never give a key's ID
to another key: Centrifugo caches keys by ID. The backend example rotates by
activation time.
Shared poll signatures
Clients tracking keys of a shared poll
channel need a signature from the backend. cent::sharedpoll::sign makes one,
and endpoints::Handlers::shared_poll_signature serves the endpoint a
subscription's getSignature callback calls. Shared poll subscriptions are
experimental in Centrifugo, and the module follows their changes.
use Duration;
use ;
let secret = b"shared_poll.hmac_secret_key".to_vec; // from your config
let signature = new.shared_poll_signature;
#
Commands for async consumers
Command::publish(request) - a function per API method - checks a request as
the client would and encodes it, for Centrifugo's async
consumers: its method() and
payload() for an outbox table, or to_json() for a Kafka message.
let data = from_string.unwrap;
let cmd = publish?;
// INSERT INTO centrifugo_outbox (method, payload, partition) VALUES ($1, $2::jsonb, 0)
assert_eq!;
# Ok::
A consumer keeps commands in order only within a partition: to keep a channel's commands in order, derive their partition from the channel the same way in every writer.
Streaming AI output
Publish a model's output into a channel of its own, in a namespace with history
and recovery, from one task - each publish waiting for the previous one - in
chunks of what arrived every 50 ms or so, not a publication per token: the
stream example. See Centrifugo for AI
apps, which also covers
sizing history for a whole response.
More
- API documentation, and the examples.
- Docs for agents and LLMs: centrifugal.dev/llms.txt, an index of the current (v6) documentation.
- Development: see CONTRIBUTING.md and AGENTS.md.
MIT license. Centrifugo PRO, which the methods marked "Centrifugo PRO only" call, is commercial software under its own license.