Brain Docs

Reference

Rust SDKInstallationHTTP clientWire client
ErrorsRetriesPagination
Brain/Docs
✦ ASKBrain on GitHubDashboard
Rust SDKWire client

Wire client

BrainClient over the BRN0 protocol — connect, ClientConfig, the two auth methods, act_as, multiplexing, the pool, and the id helpers.

PURPOSE

BrainClient speaks Brain's native binary protocol: a 32-byte BRN0 frame header, a CBOR payload, and an optional trailing little-endian f32 vector section, over TCP. One connection multiplexes many concurrent requests. This page covers connecting, configuring, and the two things the HTTP tier cannot do.

Connecting

Handshake credentialstable
async fn connect(addr: SocketAddr, auth: Auth) -> Result<Self>
async fn connect_with(addr: SocketAddr, config: ClientConfig) -> Result<Self>

connect takes just a credential and the default transport settings; connect_with takes a full ClientConfig. The handshake — HELLO, version negotiation, AUTH — runs inside both. A server that negotiates a version the client did not offer fails with BrainError::VersionMismatch rather than proceeding.

ClientConfig

ParameterTypeRequired
authAuthrequired

The credential. The server resolves the connection's identity from it.

client_idStringoptional

Identifies the client to the server.

supported_versionsVec<u8>optional

Wire versions this client accepts. Defaults to [1].

capabilitiesHelloCapabilitiesoptional

Streaming on, zstd compression off, server push off.

connect_timeout / request_timeoutOption<Duration>optional

Deadlines for the handshake and for an ordinary request.

derived_write_timeoutOption<Duration>optional

Deadline for an encode under WaitMode::Derived only — 120 s by default, because the ordinary request timeout would fire before the derivation pipeline finished.

ClientConfig::new(auth) builds one with every other field defaulted.

Auth

Token or mTLS, the same two methods the other SDKs expose. A token is bytes, not a string.

use brain_db_sdk::{BrainClient, Auth, ClientConfig};

let client = BrainClient::connect_with(
    "127.0.0.1:9090".parse()?,
    ClientConfig::new(Auth::token(std::env::var("BRAIN_API_KEY")?.into_bytes())),
)
.await?;

// ... verbs

client.close().await?;   // sends BYE, then closes

Connection facts

client.connection() borrows the ConnectionInfo the handshake established, with no round trip: space_id, server_id, chosen_version, connection_id, bound_shard_id, permissions, namespace and server_features. client.namespace(), client.space_id() and client.is_closed() are shorthands.

bound_shard_id matters: the connection is pinned to one shard, and a request for data on another is WrongShard, not a transparent redirect.

Multiplexing

One connection carries many concurrent requests, demultiplexed by stream_id. Because every verb takes &self, you can share one client across tasks and issue calls concurrently without a mutex:

let (answer, entities, caps) = tokio::try_join!(
    client.recall(&recall_req),
    client.list_entities(&list_req),
    client.capabilities(),
)?;

Streaming verbs — anything with a *_frames form, plus subscribe — each occupy one stream for their duration. cancel_stream ends one early.

act_as

Every tenant-scoped wire request carries an optional act_as selector — namespace, space, and an optional grant. It is what lets one connection serve many spaces: the credential fixes the namespace, and act_as selects the space per request. The builders expose .act_as(namespace, space); hand-built requests set the field directly.

act_as is a grant, not a claim

A principal without the act-as grant — or one naming a namespace outside its allowlist — gets a BrainError::Server carrying ErrorCodeWire::ActAsDenied (0x0033). BrainError::is_act_as_denied() tests for it without matching the variant by hand.

This is the mechanism behind per-tenant isolation at scale: one pooled connection, a storage-key prefix per end user, and no credential per user. See Namespaces.

Pool

A fixed-size set of connections handed out round-robin.

ParameterTypeRequired
Pool::connect(addr, size, auth)Result<Pool>required

Opens size connections, each running its own handshake.

Pool::connect_with(addr, size, &config)Result<Pool>optional

The same, from an explicit ClientConfig template cloned per connection, rather than a bare credential.

pool.get()Arc<BrainClient>required

The next connection, round-robin. No liveness check.

pool.get_healthy()Result<Arc<BrainClient>>required

The next connection, reconnected first if its socket died. Concurrent callers landing on the same dead slot share one reconnect rather than opening a socket each.

pool.size()usizeoptional
How many members.
pool.close()()optional

BYE on every member, best-effort. Consumes the pool — a closed pool has nothing left to hand out — and is infallible: there is no recovery a caller could perform with the error, and the socket closes on drop either way.

Prefer get_healthy for anything long-lived

A pooled member outlives any single request, so a server restart leaves every borrower holding the same dead socket until the process is bounced.

close skips a member you are still holding

BrainClient::close consumes the client, so the pool can only send BYE for a member it solely owns. A connection still held from get() is dropped without one, and its socket closes when the last clone drops. Close the pool where nothing is borrowed and the distinction never arises. Python and TypeScript have no such rule, because their close needs no ownership.

Id helpers

ParameterTypeRequired
new_id()[u8; 16]required

A fresh random id, for request_id and txn_id on hand-built requests. The builders call it for you.

derive_space_id(namespace, space)[u8; 16]optional

The space id the server derives at ingress: UUIDv5(UUIDv5(ROOT, namespace), space). Folding the namespace in is what makes equal space strings under different namespaces diverge.

Do not let the derived space id leave Brain

Clients only ever send the space string. It is Brain's internal identifier, not your control plane's; using it as an external key couples two id spaces that are deliberately separate.

See also
HTTP clientTransactionsNamespaces

Was this page helpful?

HTTP client

BrainHttpClient — construction, the builder configuration methods, borrowed inputs, and what the HTTP tier cannot do.

encode

Store a memory from text — the write verb, its wait modes, and the deduplication result.

On this page

ConnectingClientConfigAuthConnection factsMultiplexingact_asPoolId helpers
Suggest an editOpen in Playground