Skip to main content

clickhouse_loom/
lib.rs

1//! Use ClickHouse Loom's memory, knowledge and context operations from Rust.
2//!
3//! Loom is a self-hosted server for shared long-term AI agent memory, document
4//! search and code indexing. [`Client`] provides typed async methods for every
5//! registered operation. Method names replace dots with underscores.
6//! [`Client::call`] accepts a serializable request and a typed response,
7//! including `serde_json::Value`.
8//!
9//! Identity is bound once on [`Client`]. Calls return typed responses, and
10//! [`Error::Api`] preserves the server's error classification.
11//! Search defaults to all agents with no user or session filter. Set filters on
12//! [`SearchRequest`] explicitly. Builder identity values apply to declared identity
13//! fields; optional reader filters keep the values in the request.
14//! The default timeout covers each complete HTTP attempt for 60 seconds.
15//! Search hits preserve chunk parent keys and provenance. Check [`SearchResponse`]
16//! abstention, degradation and pending extraction before answering from the hits.
17//! Calls use the application's Tokio runtime. Cloned clients share a connection pool.
18//! [`RetryPolicy`] defaults to three attempts on connection failures, HTTP 408 and
19//! 5xx, with exponential backoff. Writes reuse an idempotency key and can retry
20//! incomplete responses; reads do not retry those failures by default.
21//! 429 pacing has a separate 15 second sleep budget. Use
22//! [`ClientBuilder::pacing`] and [`ClientBuilder::retry`] to configure both.
23//! [`Client::with_retry`] creates a policy override sharing connections and rate state.
24//! Dropping a call future cancels its retries and waits, but cannot undo a write.
25//! Logs use the `log` facade without installing a logger or recording payloads.
26//! Retries after dispatch require a known, declared idempotent operation.
27//! Unknown operations receive bound org and namespace and retry only connection
28//! failures. Operation names must be dotted identifiers.
29//!
30//! Enable the `blocking` feature for a synchronous client in the `blocking` module.
31//! It runs the async transport on a dedicated thread and rejects calls on Tokio
32//! runtime threads; use the async client there or call from a separate OS thread.
33//!
34//! # Capability probe
35//!
36//! [`Client::probe`] fetches fresh capabilities and reports missing operations
37//! and request fields. A mismatch returns [`ProbeReport`] with `ok = false`;
38//! HTTP and transport failures return [`Error`].
39//!
40//! ```
41//! use clickhouse_loom::{Client, Error, ProbeRequest};
42//!
43//! # async fn example(client: Client) -> Result<(), Error> {
44//! let report = client.probe(
45//!     ProbeRequest::new()
46//!         .ops(["memory.set", "memory.search"])
47//!         .fields("memory.set", ["tags"]),
48//! ).await?;
49//! println!("{}: {:?}", report.ok, report.missing_ops);
50//! # Ok(())
51//! # }
52//! ```
53//!
54//! # Per-call options and metadata
55//!
56//! [`CallOptions`] overrides timeout, retry policy and request identifiers for
57//! one call. The `*_with_options` methods return [`CallResult`] or [`CallFailure`].
58//! Both carry final-attempt metadata; validation failures have no attempt metadata.
59//! The original methods return their typed response and [`Error`].
60//!
61//! ```
62//! use clickhouse_loom::{CallFailure, CallOptions, Client, RetryPolicy};
63//! use std::time::Duration;
64//!
65//! # async fn example(client: Client) -> Result<(), CallFailure> {
66//! let options = CallOptions::default()
67//!     .timeout(Duration::from_secs(5))
68//!     .retry(RetryPolicy::disabled())
69//!     .request_id("recall-1");
70//! let result = client.get_with_options("preference", options).await?;
71//! assert_eq!(result.metadata.sent_request_id, "recall-1");
72//! println!("{} attempts={}", result.metadata.request_id, result.metadata.attempts);
73//! # Ok(())
74//! # }
75//! ```
76//!
77//! # Using public types
78//!
79//! Request, response and API error structs are non-exhaustive.
80//! Construct requests with `new`, then set their public options. Destructure responses
81//! with `..`. Match errors with a fallback arm and [`Error::Protocol`] with `..`.
82//!
83//! Response decoding ignores unknown JSON fields. Missing required fields produce
84//! [`Error::Protocol`].
85//! The memory facade preserves its public types and decoding defaults.
86//! Generated methods use full wire contracts such as [`MemorySetInput`] and
87//! [`MemoryGetOutput`], without changing [`SetRequest`] or [`GetResponse`].
88//!
89//! ```
90//! use clickhouse_loom::{ApiError, Error, GetResponse, SearchRequest, SetRequest};
91//!
92//! let mut write = SetRequest::new("preference", "Concise answers");
93//! write.tags = Some(vec!["style".into()]);
94//! let mut search = SearchRequest::new("answer style");
95//! search.top_k = Some(10);
96//!
97//! fn found(response: GetResponse) -> bool {
98//!     let GetResponse { found, .. } = response;
99//!     found
100//! }
101//!
102//! fn describe(error: Error) -> String {
103//!     match error {
104//!         Error::Api(api) => {
105//!             let ApiError { code, message, .. } = *api;
106//!             format!("{code}: {message}")
107//!         }
108//!         Error::Protocol { status, .. } => format!("Invalid response: {status}"),
109//!         other => other.to_string(),
110//!     }
111//! }
112//! ```
113//!
114//! Request structs cannot be constructed with a struct literal outside this crate:
115//!
116//! ```compile_fail,E0639
117//! use clickhouse_loom::SearchRequest;
118//!
119//! let request = SearchRequest {
120//!     query: "answer style".into(),
121//!     top_k: None,
122//!     tags: None,
123//!     memory_type: None,
124//!     search_mode: None,
125//!     agent_id: None,
126//!     namespace_scope: None,
127//!     user_id: None,
128//!     session_id: None,
129//! };
130//! ```
131//!
132//! Match [`Error`] with a fallback arm:
133//!
134//! ```compile_fail,E0004
135//! use clickhouse_loom::Error;
136//!
137//! fn describe(error: Error) -> String {
138//!     match error {
139//!         Error::Configuration(message) | Error::Input(message) => message,
140//!         Error::Transport(source) => source.to_string(),
141//!         Error::Protocol { source, .. } => source.to_string(),
142//!         Error::Api(api) => api.to_string(),
143//!     }
144//! }
145//! ```
146//!
147//! Destructure [`Error::Protocol`] with `..`:
148//!
149//! ```compile_fail,E0638
150//! use clickhouse_loom::Error;
151//!
152//! fn describe(error: Error) -> String {
153//!     match error {
154//!         Error::Protocol { status, source } => format!("{status}: {source}"),
155//!         other => other.to_string(),
156//!     }
157//! }
158//! ```
159
160mod call;
161mod capabilities;
162mod client;
163mod error;
164mod models;
165mod operations;
166mod retry;
167mod wire_models;
168
169#[cfg(feature = "blocking")]
170pub mod blocking;
171#[cfg(feature = "blocking")]
172mod blocking_operations;
173
174pub use call::{CallFailure, CallMetadata, CallOptions, CallResult, RateLimit};
175pub use capabilities::{ProbeReport, ProbeRequest};
176pub use client::{Client, ClientBuilder};
177pub use error::{ApiError, Error};
178pub use models::*;
179pub use retry::{RetryPolicy, RetryTimeouts};
180pub use wire_models::*;