Skip to main content

BrainClient

Struct BrainClient 

Source
pub struct BrainClient { /* private fields */ }
Expand description

A connected, handshaken Brain client over a multiplexed connection. Verbs take &self and are safe to call concurrently from many tasks.

Implementations§

Source§

impl BrainClient

Source

pub async fn connect(addr: SocketAddr, auth: Auth) -> Result<Self>

Connect to addr with the given credential and default transport settings, then run the handshake. The credential is mandatory — the server resolves the connection’s identity from it.

Source

pub async fn connect_with( addr: SocketAddr, config: ClientConfig, ) -> Result<Self>

Connect to addr with an explicit configuration and run the handshake.

Source

pub fn is_closed(&self) -> bool

Whether this connection is dead (the server closed it, e.g. on restart, or the socket failed). Requests on it fail at once; reconnect.

Source

pub fn connection(&self) -> &ConnectionInfo

The negotiated connection.

Source

pub fn space_id(&self) -> [u8; 16]

The space id this connection acts as.

Source

pub fn namespace(&self) -> &str

The owning tenant the server bound this connection to (server-derived from auth). Empty when the connection resolves to the reserved brain system namespace. Read-only — the client never sends a namespace.

Source

pub async fn encode(&self, request: &EncodeRequest) -> Result<EncodeResponse>

Store a memory from text (ENCODE).

Source

pub async fn recall(&self, request: &RecallRequest) -> Result<RecallAnswer>

Retrieve a memory by cue. RECALL streams one or more RECALL_RESP frames terminated by EOS; this drains them into one RecallAnswer. answer_kind is the final frame’s verdict; memories is concatenated across every frame in order. Recall is not always top-k: the answer may be a single memory, many memories, or none. For the raw streamed frames (cumulative counts, estimated_remaining), use Self::recall_frames.

Source

pub async fn recall_frames( &self, request: &RecallRequest, ) -> Result<Vec<RecallResponseFrame>>

Retrieve memories by cue, returning each decoded RECALL_RESP frame as streamed (preserving is_final, cumulative_count, estimated_remaining). The last frame carries the EOS flag.

Source

pub async fn forget(&self, request: &ForgetRequest) -> Result<ForgetResponse>

Forget a memory (soft tombstone or hard zeroing, per the request).

Create or reweight an edge between two memories (LINK). Returns whether the edge already existed (LINK overwrote its weight).

Remove an edge identified by (source, kind, target) (UNLINK). Idempotent: removing a non-existent edge succeeds with removed = false.

Source

pub async fn plan(&self, request: &PlanRequest) -> Result<Vec<PlanStep>>

Plan a path from start to goal (PLAN), flattening every streamed frame’s steps into one ordered list. For the raw streamed frames (is_final, terminal plan_status), use Self::plan_frames.

Source

pub async fn plan_frames( &self, request: &PlanRequest, ) -> Result<Vec<PlanResponseFrame>>

Plan a path, returning each decoded PLAN_RESP frame as streamed (preserving is_final and the terminal plan_status).

Source

pub async fn reason( &self, request: &ReasonRequest, ) -> Result<Vec<InferenceStep>>

Reason about an observation (REASON), flattening every streamed frame’s inferences into one ordered list. For the raw streamed frames (is_final, terminal reason_status), use Self::reason_frames.

Source

pub async fn reason_frames( &self, request: &ReasonRequest, ) -> Result<Vec<ReasonResponseFrame>>

Reason about an observation, returning each decoded REASON_RESP frame as streamed (preserving is_final and the terminal reason_status).

Source

pub async fn create_entity( &self, request: &EntityCreateRequest, ) -> Result<EntityCreateResponse>

Create a typed entity (ENTITY_CREATE).

Source

pub async fn update_entity( &self, request: &EntityUpdateRequest, ) -> Result<EntityUpdateResponse>

Replace an entity’s name, aliases, and attributes (ENTITY_UPDATE).

Source

pub async fn rename_entity( &self, request: &EntityRenameRequest, ) -> Result<EntityRenameResponse>

Rename an entity, optionally keeping the old name as an alias (ENTITY_RENAME).

Source

pub async fn merge_entities( &self, request: &EntityMergeRequest, ) -> Result<EntityMergeResponse>

Merge two entities that are the same real-world thing (ENTITY_MERGE). Reversible within the returned grace window via Self::unmerge_entity.

Source

pub async fn unmerge_entity( &self, request: &EntityUnmergeRequest, ) -> Result<EntityUnmergeResponse>

Undo a merge within its grace window (ENTITY_UNMERGE).

Source

pub async fn tombstone_entity( &self, request: &EntityTombstoneRequest, ) -> Result<EntityTombstoneResponse>

Retire an entity with an audit reason (ENTITY_TOMBSTONE). Soft: the row survives but drops out of resolution and traversal.

Source

pub async fn create_statement( &self, request: &StatementCreateRequest, ) -> Result<StatementCreateResponse>

Create a statement (STATEMENT_CREATE). The response reports any auto-superseded prior statement and the supersession chain root.

Source

pub async fn create_relation( &self, request: &RelationCreateRequest, ) -> Result<RelationCreateResponse>

Create a relation between two entities (RELATION_CREATE).

Source

pub async fn upload_schema( &self, request: &SchemaUploadRequest, ) -> Result<SchemaUploadResponse>

Upload a schema document (SCHEMA_UPLOAD). With dry_run set the server validates without applying; the response carries any validation errors and a backward-compatibility verdict.

Source

pub async fn get_relation( &self, request: &RelationGetRequest, ) -> Result<RelationGetResponse>

Fetch one relation by id (RELATION_GET). follow_supersession returns the current chain head when the id has been superseded.

Source

pub async fn supersede_relation( &self, request: &RelationSupersedeRequest, ) -> Result<RelationSupersedeResponse>

Revise a relation, keeping both on one chain (RELATION_SUPERSEDE).

Source

pub async fn tombstone_relation( &self, request: &RelationTombstoneRequest, ) -> Result<RelationTombstoneResponse>

Soft-retire a relation with a reason (RELATION_TOMBSTONE).

Source

pub async fn traverse_relations( &self, request: &RelationTraverseRequest, ) -> Result<Vec<TraversalPathWire>>

Multi-hop walk of the relation graph from an entity (RELATION_TRAVERSE), flattening every streamed frame’s paths. For the raw frames (with truncated / total_paths), use Self::traverse_relations_frames.

Source

pub async fn traverse_relations_frames( &self, request: &RelationTraverseRequest, ) -> Result<Vec<RelationTraverseResponseFrame>>

Traverse the relation graph, returning each decoded RELATION_TRAVERSE frame.

Source

pub async fn query_explain( &self, request: &QueryExplainRequest, ) -> Result<QueryExplainResponse>

Return a query’s plan without running it (QUERY_EXPLAIN).

Source

pub async fn query_trace( &self, request: &QueryTraceRequest, ) -> Result<QueryTraceResponse>

Run a query and return its per-stage execution trace (QUERY_TRACE).

Source

pub async fn encode_vector_direct( &self, request: &EncodeVectorDirectRequest, ) -> Result<EncodeResponse>

Write a pre-computed embedding directly (ENCODE_VECTOR_DIRECT), bypassing the server’s owned embedding. The vector rides the trailing raw f32 section of the frame, not the CBOR map.

Source

pub async fn materialize_procedural( &self, request: &MaterializeProceduralRequest, ) -> Result<MaterializeProceduralResponse>

Materialize a procedural-memory system block (MATERIALIZE_PROCEDURAL).

Source

pub async fn capabilities( &self, request: &GetCapabilitiesRequest, ) -> Result<GetCapabilitiesResponse>

Introspect the connected shard’s live capabilities (GET_CAPABILITIES): whether the reranker is loaded, which extractor tiers are enabled, the active user schema namespaces, and the embedding dimensionality.

Source

pub async fn extractor_list( &self, request: &ExtractorListRequest, ) -> Result<ExtractorListResponseFrame>

List the always-on extractors registered on the connected shard (EXTRACTOR_LIST): id, namespace, name, kind, schema version, and creation time. Read-only introspection — extraction is always-on and cannot be toggled.

Source

pub async fn get_entity( &self, request: &EntityGetRequest, ) -> Result<EntityGetResponse>

Fetch one entity by id (ENTITY_GET).

Source

pub async fn memory_inspect( &self, request: &MemoryInspectRequest, ) -> Result<MemoryInspectResponse>

Inspect one memory’s durable write-artifact bundle (MEMORY_INSPECT): its text plus the per-stage record of what the write built — the embedding vector, the stored record, the analyzed keyword terms, the write-time HyPE questions, and the extracted knowledge graph. Returns found = false (with an empty artifact) for an id that doesn’t exist under the caller’s scope.

Source

pub async fn resolve_entity( &self, request: &EntityResolveRequest, ) -> Result<EntityResolveResponse>

Resolve a candidate name to an entity (ENTITY_RESOLVE). The server currently requires entity_type_hint != 0 and resolves by exact canonical name; allow_create lets it mint a new entity on a miss.

Source

pub async fn get_statement( &self, request: &StatementGetRequest, ) -> Result<StatementGetResponse>

Fetch one statement by id (STATEMENT_GET). With follow_supersession set, the server may redirect to the current entry in the chain.

Source

pub async fn get_schema( &self, request: &SchemaGetRequest, ) -> Result<SchemaGetResponse>

Fetch one schema version (SCHEMA_GET). version == 0 selects the active version.

Source

pub async fn validate_schema( &self, request: &SchemaValidateRequest, ) -> Result<SchemaValidateResponse>

Validate a schema document without persisting it (SCHEMA_VALIDATE).

Source

pub async fn replace_schema( &self, request: &SchemaReplaceRequest, ) -> Result<SchemaReplaceResponse>

Replace a namespace’s schema wholesale (SCHEMA_REPLACE).

DESTRUCTIVE. Every declared row in the namespace is dropped before the new document lands; entities whose type disappears survive as orphans, readable as plain memories but no longer enriched from the typed-graph tables. Use Self::upload_schema for the additive, versioned path — this is the one you reach for when the shape itself is wrong.

force_drop_existing MUST be true; the server rejects false with InvalidRequest. The SDK does not default it, so the destructive intent is written at the call site.

Source

pub async fn drop_schema( &self, request: &SchemaDropRequest, ) -> Result<SchemaDropResponse>

Drop a single declared predicate or relation_type (SCHEMA_DROP).

The surgical counterpart to Self::replace_schema: it narrows the active schema by one type rather than swapping the whole namespace. Existing rows on the dropped type survive as orphans, readable as plain memories but no longer enriched from the typed-graph tables.

force is required only when the target still has live rows; the server rejects false in that case with Conflict and mutates nothing. The SDK does not default it, so the destructive intent is written at the call site.

Source

pub async fn ping( &self, client_timestamp_unix_nanos: Option<u64>, ) -> Result<PongResponse>

Client-initiated liveness probe (PING → PONG).

Distinct from the server’s idle-timer SERVER_PING keepalive, which the mux auto-answers with CLIENT_PONG: this is an on-demand round-trip whose PONG routes back by stream id through the normal unary path. client_timestamp_unix_nanos defaults to the current wall clock when None; the PONG echoes it back alongside the server’s timestamp, so the caller can measure RTT.

Source

pub async fn cancel_stream( &self, target_stream_id: u32, reason: CancellationReason, ) -> Result<CancelStreamAck>

Cancel an in-flight stream (CANCEL_STREAM).

target_stream_id is the id of the stream to stop — take it from the frames a streaming call is yielding (*_frames methods expose stream_id). The request travels on its OWN stream id, so it does not queue behind the frames it is cancelling; the server replies CANCEL_STREAM_ACK and stops emitting for the target.

This is why it cannot use the unary helper’s request/response pairing on a single stream: the acknowledgement and the cancelled stream are deliberately different streams.

Cancelling a stream that already finished is not an error — the server acknowledges it regardless, so a racing consumer does not have to coordinate with the reader loop.

Source

pub async fn list_entities( &self, request: &EntityListRequest, ) -> Result<Vec<EntityListItem>>

List entities (ENTITY_LIST), flattening every streamed frame’s items into one ordered list. For the raw streamed frames (cursors, cumulative counts, is_final), use Self::list_entities_frames.

Source

pub async fn list_entities_frames( &self, request: &EntityListRequest, ) -> Result<Vec<EntityListResponseFrame>>

List entities, returning each decoded ENTITY_LIST_RESP frame as streamed (preserving next_cursor, cumulative_count, is_final).

Source

pub async fn memory_list( &self, request: &MemoryListRequest, ) -> Result<Vec<MemoryListItem>>

List memories (MEMORY_LIST), flattening every streamed frame’s items into one ordered list. This is a pure paginated enumeration of the caller’s (namespace, space) memories — no query, no ranking. For the raw streamed frames (cursors, cumulative counts, is_final), use Self::memory_list_frames.

Source

pub async fn memory_list_frames( &self, request: &MemoryListRequest, ) -> Result<Vec<MemoryListResponseFrame>>

List memories, returning each decoded MEMORY_LIST_RESP frame as streamed (preserving next_cursor, cumulative_count, is_final).

Source

pub async fn graph_fetch( &self, request: &GraphFetchRequest, ) -> Result<(Vec<GraphNode>, Vec<GraphEdge>)>

Export the caller’s typed graph (GRAPH_FETCH), flattening every streamed frame’s nodes + edges into two ordered lists. Nodes/edges may repeat across pages (completeness, not disjointness) — dedup by id if needed. For the raw streamed frames (cursors, is_final), use Self::graph_fetch_frames.

Source

pub async fn graph_fetch_frames( &self, request: &GraphFetchRequest, ) -> Result<Vec<GraphFetchResponseFrame>>

Export the typed graph, returning each decoded GRAPH_FETCH_RESP frame as streamed (preserving next_cursor, is_final).

Source

pub async fn list_statements( &self, request: &StatementListRequest, ) -> Result<Vec<StatementView>>

List statements (STATEMENT_LIST), flattening every streamed frame’s items. For the raw frames, use Self::list_statements_frames.

Source

pub async fn list_statements_frames( &self, request: &StatementListRequest, ) -> Result<Vec<StatementListResponseFrame>>

List statements, returning each decoded STATEMENT_LIST_RESP frame.

Source

pub async fn supersede_statement( &self, request: &StatementSupersedeRequest, ) -> Result<StatementSupersedeResponse>

Replace a statement with a revised one (STATEMENT_SUPERSEDE), keeping both on the same chain so history is preserved.

Source

pub async fn tombstone_statement( &self, request: &StatementTombstoneRequest, ) -> Result<StatementTombstoneResponse>

Retire a statement with a coded reason (STATEMENT_TOMBSTONE). Soft and recoverable.

Source

pub async fn retract_statement( &self, request: &StatementRetractRequest, ) -> Result<StatementRetractResponse>

Assert a statement was wrong (STATEMENT_RETRACT). Unlike a tombstone, retraction schedules a hard-zero so a genuine mistake gets scrubbed.

Source

pub async fn statement_history( &self, request: &StatementHistoryRequest, ) -> Result<Vec<StatementView>>

Walk a claim’s full version chain (STATEMENT_HISTORY), flattening every streamed frame’s items. For the raw frames, use Self::statement_history_frames.

Source

pub async fn statement_history_frames( &self, request: &StatementHistoryRequest, ) -> Result<Vec<StatementHistoryResponseFrame>>

Walk a claim’s version chain, returning each decoded STATEMENT_HISTORY frame (with total_versions / is_final).

Source

pub async fn list_relations_from( &self, request: &RelationListFromRequest, ) -> Result<Vec<RelationView>>

List relations originating from an entity (RELATION_LIST_FROM), flattening every streamed frame’s items. For the raw frames, use Self::list_relations_from_frames.

Source

pub async fn list_relations_from_frames( &self, request: &RelationListFromRequest, ) -> Result<Vec<RelationListFromResponseFrame>>

List relations from an entity, returning each decoded RELATION_LIST_FROM_RESP frame.

Source

pub async fn list_relations_to( &self, request: &RelationListToRequest, ) -> Result<Vec<RelationView>>

List relations pointing to an entity (RELATION_LIST_TO), flattening every streamed frame’s items. For the raw frames, use Self::list_relations_to_frames.

Source

pub async fn list_relations_to_frames( &self, request: &RelationListToRequest, ) -> Result<Vec<RelationListToResponseFrame>>

List relations to an entity, returning each decoded RELATION_LIST_TO_RESP frame.

Source

pub async fn list_schemas( &self, request: &SchemaListRequest, ) -> Result<Vec<SchemaListItemWire>>

List schema versions in a namespace (SCHEMA_LIST), flattening every streamed frame’s items. For the raw frames, use Self::list_schemas_frames.

Source

pub async fn list_schemas_frames( &self, request: &SchemaListRequest, ) -> Result<Vec<SchemaListResponseFrame>>

List schema versions, returning each decoded SCHEMA_LIST_RESP frame.

Source

pub async fn txn_begin( &self, request: &TxnBeginRequest, ) -> Result<TxnBeginResponse>

Begin a transaction (TXN_BEGIN). The client mints txn_id; subsequent writes carry it to enroll in the transaction until commit or abort.

Source

pub async fn txn_commit( &self, request: &TxnCommitRequest, ) -> Result<TxnCommitResponse>

Commit a transaction (TXN_COMMIT). The response reports how many operations were applied.

Source

pub async fn txn_abort( &self, request: &TxnAbortRequest, ) -> Result<TxnAbortResponse>

Abort a transaction (TXN_ABORT), discarding its buffered operations.

Source

pub async fn create_space( &self, request: &SpaceCreateRequest, ) -> Result<SpaceCreateResponse>

Provision the caller’s effective space explicitly (SPACE_CREATE). Idempotent: a create for an existing space returns the existing row with created = false.

Source

pub async fn list_spaces( &self, request: &SpaceListRequest, ) -> Result<SpaceListResponse>

List the caller’s namespace’s spaces (SPACE_LIST). cross_shard_complete is false while the listing covers only the caller’s shard.

Source

pub async fn delete_space( &self, request: &SpaceDeleteRequest, ) -> Result<SpaceDeleteResponse>

Erase the caller’s effective space and every row under it (SPACE_DELETE). Hard/immediate GDPR erasure.

Source

pub async fn create_session( &self, request: &SessionCreateRequest, ) -> Result<SessionCreateResponse>

Provision a session under the caller’s effective space explicitly (SESSION_CREATE). Idempotent.

Source

pub async fn list_sessions( &self, request: &SessionListRequest, ) -> Result<SessionListResponse>

List one space’s sessions newest-first (SESSION_LIST). A first-class end-user feature — the client’s session picker reads this.

Source

pub async fn delete_session( &self, request: &SessionDeleteRequest, ) -> Result<SessionDeleteResponse>

Delete a session’s memories + graph rows (SESSION_DELETE). Soft by default (7-day grace); hard = true zeroes immediately. The default session (session_id = 0) is non-deletable.

Source

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

Open a long-lived change-feed subscription (SUBSCRIBE). Returns a Subscription handle the caller drains with next().await; call unsubscribe().await for a clean teardown. The server pushes SUBSCRIBE_EVENT frames until the subscription is torn down, so this does not block on a single response.

Source

pub async fn close(self) -> Result<()>

Send BYE and drop the connection.

Trait Implementations§

Source§

impl Debug for BrainClient

Source§

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

Prints the session, never the socket or the credential.

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<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

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> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

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