Skip to main content

clickhouse_loom/
client.rs

1use std::{
2    collections::HashMap,
3    env, fmt,
4    sync::Arc,
5    time::{Duration, Instant},
6};
7
8use reqwest::{
9    header::{HeaderMap, HeaderValue, AUTHORIZATION},
10    redirect::Policy,
11    Client as HttpClient, Url,
12};
13use serde::{de::DeserializeOwned, Serialize};
14use serde_json::{json, Value};
15
16use crate::{
17    ApiError, CallFailure, CallMetadata, CallOptions, CallResult, DeleteResponse, Error,
18    GetResponse, RetryPolicy, SearchRequest, SearchResponse, SetRequest, SetResponse,
19};
20use tokio::sync::Mutex;
21
22const DEFAULT_URL: &str = "http://localhost:7777";
23
24macro_rules! typed_call {
25    ($method:ident, $with_options:ident, $request:ty, $response:ty, $op:literal) => {
26        pub async fn $method(&self, request: $request) -> Result<$response, Error> {
27            self.$with_options(request, CallOptions::default())
28                .await
29                .map(|result| result.data)
30                .map_err(|failure| failure.error)
31        }
32
33        /// Call with per-request controls and final-attempt metadata.
34        pub async fn $with_options(
35            &self,
36            request: $request,
37            options: CallOptions,
38        ) -> Result<CallResult<$response>, CallFailure> {
39            self.call($op, &request, options).await
40        }
41    };
42}
43
44/// A client for ClickHouse Loom, bound to one identity.
45///
46/// Clones share a connection pool and may issue requests concurrently.
47#[derive(Clone)]
48pub struct Client {
49    http: HttpClient,
50    base_url: Url,
51    authorization: Option<HeaderValue>,
52    identity: Value,
53    retry: RetryPolicy,
54    pacing: bool,
55    ratelimit_max_wait: Duration,
56    rate_state: Arc<Mutex<HashMap<String, Duration>>>,
57}
58
59/// Explicit endpoint and token options override LOOM_BASE_URL and LOOM_API_KEY.
60pub struct ClientBuilder {
61    base_url: Option<String>,
62    api_key: Option<String>,
63    identity: Value,
64    timeout: Duration,
65    retry: RetryPolicy,
66    pacing: bool,
67    ratelimit_max_wait: Duration,
68}
69
70impl Client {
71    typed_call!(
72        health,
73        health_with_options,
74        crate::OpsHealthInput,
75        crate::OpsHealthOutput,
76        "ops.health"
77    );
78    typed_call!(
79        capabilities,
80        capabilities_with_options,
81        crate::OpsCapabilitiesInput,
82        crate::OpsCapabilitiesOutput,
83        "ops.capabilities"
84    );
85
86    pub fn builder(
87        org: impl Into<String>,
88        namespace: impl Into<String>,
89        agent: impl Into<String>,
90    ) -> ClientBuilder {
91        ClientBuilder {
92            base_url: None,
93            api_key: None,
94            identity: json!({"org": org.into(), "namespace": namespace.into(), "agent": agent.into()}),
95            timeout: Duration::from_secs(60),
96            retry: RetryPolicy::default(),
97            pacing: true,
98            ratelimit_max_wait: Duration::from_secs(15),
99        }
100    }
101
102    /// Fetch capabilities and report missing operations and request fields.
103    ///
104    /// Each probe fetches a fresh report. Only call failures return an error.
105    pub async fn probe(&self, request: crate::ProbeRequest) -> Result<crate::ProbeReport, Error> {
106        self.probe_with_options(request, CallOptions::default())
107            .await
108            .map(|result| result.data)
109            .map_err(|failure| failure.error)
110    }
111
112    /// Probe with per-request controls and final-attempt metadata.
113    pub async fn probe_with_options(
114        &self,
115        request: crate::ProbeRequest,
116        options: CallOptions,
117    ) -> Result<CallResult<crate::ProbeReport>, CallFailure> {
118        let result = self
119            .capabilities_with_options(crate::OpsCapabilitiesInput::new(), options)
120            .await?;
121        Ok(CallResult {
122            data: crate::capabilities::compare(request, result.data),
123            metadata: result.metadata,
124        })
125    }
126
127    pub async fn set(&self, request: SetRequest) -> Result<SetResponse, Error> {
128        self.set_with_options(request, CallOptions::default())
129            .await
130            .map(|result| result.data)
131            .map_err(|failure| failure.error)
132    }
133
134    /// Save memory with per-call options and response or failure metadata.
135    pub async fn set_with_options(
136        &self,
137        request: SetRequest,
138        options: CallOptions,
139    ) -> Result<CallResult<SetResponse>, CallFailure> {
140        self.call("memory.set", &request, options).await
141    }
142
143    pub async fn get(&self, memory_key: &str) -> Result<GetResponse, Error> {
144        self.get_with_options(memory_key, CallOptions::default())
145            .await
146            .map(|result| result.data)
147            .map_err(|failure| failure.error)
148    }
149
150    /// Read memory with per-call options and response or failure metadata.
151    pub async fn get_with_options(
152        &self,
153        memory_key: &str,
154        options: CallOptions,
155    ) -> Result<CallResult<GetResponse>, CallFailure> {
156        self.call(
157            "memory.get",
158            &crate::MemoryGetInput::new(memory_key),
159            options,
160        )
161        .await
162    }
163
164    pub async fn search(&self, request: SearchRequest) -> Result<SearchResponse, Error> {
165        self.search_with_options(request, CallOptions::default())
166            .await
167            .map(|result| result.data)
168            .map_err(|failure| failure.error)
169    }
170
171    /// Search memory with per-call options and response or failure metadata.
172    pub async fn search_with_options(
173        &self,
174        request: SearchRequest,
175        options: CallOptions,
176    ) -> Result<CallResult<SearchResponse>, CallFailure> {
177        self.call("memory.search", &request, options).await
178    }
179
180    pub async fn delete(&self, memory_key: &str) -> Result<DeleteResponse, Error> {
181        self.delete_with_options(memory_key, CallOptions::default())
182            .await
183            .map(|result| result.data)
184            .map_err(|failure| failure.error)
185    }
186
187    /// Delete memory with per-call options and response or failure metadata.
188    pub async fn delete_with_options(
189        &self,
190        memory_key: &str,
191        options: CallOptions,
192    ) -> Result<CallResult<DeleteResponse>, CallFailure> {
193        self.call(
194            "memory.delete",
195            &crate::MemoryDeleteInput::new(memory_key),
196            options,
197        )
198        .await
199    }
200
201    /// Return a client with another policy, sharing the pool and rate-limit state.
202    /// Use this clone for calls needing an override; the original is unchanged.
203    pub fn with_retry(&self, retry: RetryPolicy) -> Result<Self, Error> {
204        retry.validate()?;
205        Ok(Self {
206            retry,
207            ..self.clone()
208        })
209    }
210
211    /// Call any dotted wire operation, decoding its response as `T`.
212    ///
213    /// Known operations use generated identity and retry policies. Unknown operations
214    /// receive bound org/namespace and retry only failures before connection.
215    pub async fn call<T: DeserializeOwned>(
216        &self,
217        op: &str,
218        request: &impl Serialize,
219        options: CallOptions,
220    ) -> Result<CallResult<T>, CallFailure> {
221        if !valid_operation(op) {
222            return Err(Error::Input("operation must be a dotted identifier".into()).into());
223        }
224        let policy = crate::wire_models::OP_POLICIES
225            .iter()
226            .find(|(name, _, _, _, _)| *name == op);
227        let idempotent = policy.is_some_and(|(_, idempotent, _, _, _)| *idempotent);
228        let replayable = policy.is_some_and(|(_, idem, read_only, _, _)| *idem && !*read_only);
229        options.validate(replayable)?;
230        let retry = options.retry.as_ref().unwrap_or(&self.retry);
231        let mut body = serde_json::to_value(request)
232            .map_err(|e| Error::Input(format!("cannot encode request: {e}")))?;
233        let fields = body
234            .as_object_mut()
235            .ok_or_else(|| Error::Input("request must be an object".into()))?;
236        if op == "memory.set" && fields.get("value").is_some_and(Value::is_null) {
237            return Err(Error::Input("memory.set value cannot be null".into()).into());
238        }
239        if op == "collection.delete"
240            && fields
241                .get("namespace")
242                .and_then(Value::as_str)
243                .is_none_or(|target| target.trim().is_empty())
244        {
245            return Err(
246                Error::Input("collection.delete requires a target namespace".into()).into(),
247            );
248        }
249        if op == "memory.search" {
250            // Search identity fields are filters; write authorship must not narrow recall.
251            fields.entry("agent").or_insert_with(|| json!("*"));
252            for key in ["org", "namespace"] {
253                fields.insert(key.into(), self.identity[key].clone());
254            }
255        }
256        // Only declared identity fields are stamped; optional reader filters survive.
257        let identity_fields = policy.map_or(&["org", "namespace"][..], |(_, _, _, keys, _)| *keys);
258        for key in identity_fields {
259            if let Some(value) = self.identity.get(*key) {
260                fields.insert((*key).into(), value.clone());
261            }
262        }
263        if let Some((_, _, _, _, defaults)) = policy {
264            for key in *defaults {
265                if let Some(value) = self.identity.get(*key) {
266                    fields.entry(*key).or_insert_with(|| value.clone());
267                }
268            }
269        }
270        let url = self
271            .base_url
272            .join(&format!("v1/{op}"))
273            .map_err(|_| Error::Configuration("cannot construct operation URL".into()))?;
274        let idempotency_key = options
275            .idempotency_key
276            .or_else(|| replayable.then(request_id));
277        let request_id = options.request_id.unwrap_or_else(request_id);
278        if self.pacing {
279            let delay = self
280                .rate_state
281                .lock()
282                .await
283                .get(op)
284                .copied()
285                .unwrap_or_default();
286            if !delay.is_zero() {
287                log::warn!(target: "clickhouse_loom", "{op} pacing wait_ms={} rid={request_id}", delay.as_millis());
288                tokio::time::sleep(delay).await;
289            }
290        }
291        let started = Instant::now();
292        let mut sent = 0_u64;
293        let mut attempt = 0_u32;
294        let mut slept = Duration::ZERO;
295        let mut paced = Duration::ZERO;
296        loop {
297            attempt += 1;
298            let mut request = self
299                .http
300                .post(url.clone())
301                .json(&body)
302                .header("x-request-id", &request_id)
303                .header("x-loom-retry-count", sent.to_string())
304                .header(
305                    "user-agent",
306                    concat!("loom-rust/", env!("CARGO_PKG_VERSION")),
307                )
308                .header(
309                    "x-loom-sdk",
310                    concat!("loom-rust/", env!("CARGO_PKG_VERSION")),
311                )
312                .header(
313                    "x-loom-runtime",
314                    format!("rust {} {}", env::consts::OS, env::consts::ARCH),
315                );
316            if let Some(key) = &idempotency_key {
317                request = request.header("idempotency-key", key);
318            }
319            if let Some(run_id) = self.identity.get("run_id").and_then(Value::as_str) {
320                request = request.header("x-loom-run-id", run_id);
321            }
322            if let Some(timeout) = options.timeout {
323                request = request.timeout(timeout);
324            }
325            if let Some(authorization) = &self.authorization {
326                request = request.header(AUTHORIZATION, authorization);
327            }
328            sent += 1;
329            let mut metadata = CallMetadata::new(&request_id, sent);
330            log::debug!(target: "clickhouse_loom", "{op} attempt={attempt} sent={sent} rid={request_id}");
331            let received = async {
332                let response = request.send().await?;
333                let status = response.status();
334                let headers = response.headers().clone();
335                // Keep received headers even if reading the response body fails.
336                metadata.record_response(status.as_u16(), &headers);
337                let bytes = response.bytes().await?;
338                Ok::<_, reqwest::Error>((status, headers, bytes))
339            }
340            .await;
341            let (error, allowed, hint) = match received {
342                Err(error) => {
343                    let allowed = retry.retries_transport(&error, replayable)
344                        && (error.is_connect() || idempotent);
345                    (Error::Transport(error.without_url()), allowed, None)
346                }
347                Ok((status, headers, bytes)) => {
348                    self.record_rate_state(op, &headers).await;
349                    if status.is_success() {
350                        let result =
351                            serde_json::from_slice(&bytes).map_err(|source| Error::Protocol {
352                                status: status.as_u16(),
353                                source,
354                            });
355                        if result.is_ok() {
356                            log::info!(target: "clickhouse_loom", "{op} status={} elapsed_ms={} attempts={sent} rid={request_id}", status.as_u16(), started.elapsed().as_millis());
357                        } else {
358                            log::error!(target: "clickhouse_loom", "{op} invalid_response status={} attempts={sent} rid={request_id}", status.as_u16());
359                        }
360                        return match result {
361                            Ok(data) => Ok(CallResult { data, metadata }),
362                            Err(error) => Err(CallFailure {
363                                error,
364                                metadata: Some(Box::new(metadata)),
365                            }),
366                        };
367                    }
368                    let mut error = ApiError::from_response(status.as_u16(), &headers, &bytes);
369                    error.request_id.get_or_insert_with(|| request_id.clone());
370                    if status.as_u16() == 429 && self.pacing && idempotent {
371                        let delay = pacing_delay(
372                            error.retry_after_s,
373                            self.ratelimit_max_wait.saturating_sub(paced),
374                        );
375                        if !delay.is_zero() {
376                            log::warn!(target: "clickhouse_loom", "{op} status=429 wait_ms={} attempts={sent} rid={request_id}", delay.as_millis());
377                            tokio::time::sleep(delay).await;
378                            paced += delay;
379                            attempt = 0;
380                            slept = Duration::ZERO;
381                            continue;
382                        }
383                    }
384                    let allowed = idempotent
385                        && status.as_u16() != 429
386                        && retry.statuses.contains(&status.as_u16())
387                        && !error.forbids_retry();
388                    let hint = error.retry_after_s;
389                    (Error::Api(Box::new(error)), allowed, hint)
390                }
391            };
392            let delay = retry.delay(attempt, hint);
393            let status = match &error {
394                Error::Api(api) => api.status,
395                _ => 0,
396            };
397            if !allowed
398                || attempt >= retry.max_attempts
399                || retry
400                    .total_backoff_budget
401                    .is_some_and(|budget| delay > budget.saturating_sub(slept))
402            {
403                log::error!(target: "clickhouse_loom", "{op} failed status={status} elapsed_ms={} attempts={sent} rid={request_id}", started.elapsed().as_millis());
404                return Err(CallFailure {
405                    error,
406                    metadata: Some(Box::new(metadata)),
407                });
408            }
409            log::warn!(target: "clickhouse_loom", "{op} retry status={status} attempt={attempt} wait_ms={} rid={request_id}", delay.as_millis());
410            tokio::time::sleep(delay).await;
411            slept = slept.saturating_add(delay);
412        }
413    }
414
415    async fn record_rate_state(&self, op: &str, headers: &HeaderMap) {
416        if let Some(rate) = crate::call::rate_limit(headers) {
417            let delay = if rate.remaining < 1 {
418                Duration::from_secs_f64(
419                    (rate.reset_s as f64 / rate.limit.max(1) as f64).clamp(0.0, 5.0),
420                )
421            } else {
422                Duration::ZERO
423            };
424            self.rate_state.lock().await.insert(op.to_owned(), delay);
425        }
426    }
427}
428
429impl ClientBuilder {
430    pub fn base_url(mut self, base_url: impl Into<String>) -> Self {
431        self.base_url = Some(base_url.into());
432        self
433    }
434
435    /// An empty explicit token disables authorization, including the environment token.
436    pub fn api_key(mut self, api_key: impl Into<String>) -> Self {
437        self.api_key = Some(api_key.into());
438        self
439    }
440
441    pub fn user_id(mut self, user_id: impl Into<String>) -> Self {
442        self.identity["user_id"] = json!(user_id.into());
443        self
444    }
445
446    pub fn session_id(mut self, session_id: impl Into<String>) -> Self {
447        self.identity["session_id"] = json!(session_id.into());
448        self
449    }
450
451    pub fn run_id(mut self, run_id: impl Into<String>) -> Self {
452        self.identity["run_id"] = json!(run_id.into());
453        self
454    }
455
456    pub fn timeout(mut self, timeout: Duration) -> Self {
457        self.timeout = timeout;
458        self
459    }
460
461    pub fn retry(mut self, retry: RetryPolicy) -> Self {
462        self.retry = retry;
463        self
464    }
465
466    /// Wait on 429 responses and recorded rate-limit headers (default: true).
467    pub fn pacing(mut self, pacing: bool) -> Self {
468        self.pacing = pacing;
469        self
470    }
471
472    /// Total 429 sleep budget per call (default: 15 seconds).
473    pub fn ratelimit_max_wait(mut self, wait: Duration) -> Self {
474        self.ratelimit_max_wait = wait;
475        self
476    }
477
478    pub fn build(self) -> Result<Client, Error> {
479        self.retry.validate()?;
480        for key in ["org", "namespace", "agent"] {
481            if self.identity[key].as_str().unwrap_or("").trim().is_empty() {
482                return Err(Error::Configuration(format!("{key} must not be empty")));
483            }
484        }
485        if self.timeout.is_zero() {
486            return Err(Error::Configuration("timeout must be positive".into()));
487        }
488        if let Some(run_id) = self.identity.get("run_id").and_then(Value::as_str) {
489            HeaderValue::from_str(run_id)
490                .map_err(|_| Error::Configuration("invalid run ID header".into()))?;
491        }
492        let endpoint = self
493            .base_url
494            .or_else(|| env_value("LOOM_BASE_URL"))
495            .unwrap_or_else(|| DEFAULT_URL.into());
496        let mut base_url =
497            Url::parse(&endpoint).map_err(|_| Error::Configuration("invalid base URL".into()))?;
498        if !matches!(base_url.scheme(), "http" | "https")
499            || base_url.host_str().is_none()
500            || !base_url.username().is_empty()
501            || base_url.password().is_some()
502            || base_url.query().is_some()
503            || base_url.fragment().is_some()
504        {
505            return Err(Error::Configuration(
506                "base URL must be HTTP(S) with no credentials, query or fragment".into(),
507            ));
508        }
509        if !base_url.path().ends_with('/') {
510            let path = format!("{}/", base_url.path());
511            base_url.set_path(&path);
512        }
513        let token = self.api_key.or_else(|| env_value("LOOM_API_KEY"));
514        let authorization = token
515            .filter(|s| !s.trim().is_empty())
516            .map(|token| {
517                let mut header = HeaderValue::from_str(&format!("Bearer {}", token.trim()))
518                    .map_err(|_| Error::Configuration("invalid bearer token".into()))?;
519                header.set_sensitive(true);
520                Ok(header)
521            })
522            .transpose()?;
523        let http = HttpClient::builder()
524            .redirect(Policy::none())
525            .retry(reqwest::retry::never())
526            .timeout(self.timeout)
527            .build()
528            .map_err(|e| Error::Transport(e.without_url()))?;
529        Ok(Client {
530            http,
531            base_url,
532            authorization,
533            identity: self.identity,
534            retry: self.retry,
535            pacing: self.pacing,
536            ratelimit_max_wait: self.ratelimit_max_wait,
537            rate_state: Arc::new(Mutex::new(HashMap::new())),
538        })
539    }
540}
541
542fn request_id() -> String {
543    uuid::Uuid::new_v4().to_string()
544}
545
546fn valid_operation(op: &str) -> bool {
547    op.contains('.')
548        && op.split('.').all(|part| {
549            part.as_bytes().first().is_some_and(u8::is_ascii_alphabetic)
550                && part.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_')
551        })
552}
553
554fn pacing_delay(hint: Option<f64>, budget: Duration) -> Duration {
555    let hint = hint
556        .filter(|s| s.is_finite() && *s <= 60.0)
557        .unwrap_or(1.0)
558        .max(0.0);
559    Duration::from_secs_f64(hint)
560        .min(Duration::from_secs(5))
561        .min(budget)
562}
563
564fn env_value(name: &str) -> Option<String> {
565    env::var(name).ok().filter(|v| !v.trim().is_empty())
566}
567
568impl fmt::Debug for Client {
569    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
570        f.debug_struct("Client")
571            .field("base_url", &self.base_url)
572            .field("identity", &self.identity)
573            .finish_non_exhaustive()
574    }
575}
576
577impl fmt::Debug for ClientBuilder {
578    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
579        // An unvalidated URL can contain credentials, so omit it along with the token.
580        f.debug_struct("ClientBuilder")
581            .field("identity", &self.identity)
582            .field("timeout", &self.timeout)
583            .finish_non_exhaustive()
584    }
585}
586
587#[cfg(test)]
588mod tests {
589    use super::*;
590
591    #[test]
592    fn default_timeout_matches_python_and_can_be_overridden() {
593        let builder = Client::builder("org", "ns", "bot");
594        assert_eq!(builder.timeout, Duration::from_secs(60));
595        assert_eq!(
596            builder.timeout(Duration::from_secs(2)).timeout,
597            Duration::from_secs(2)
598        );
599    }
600
601    #[tokio::test]
602    async fn rate_state_updates_capacity_and_ignores_incomplete_readings() {
603        let client = Client::builder("org", "ns", "bot")
604            .api_key("")
605            .build()
606            .unwrap();
607        for (limit, remaining, reset, expected) in [
608            ("10", "0", "10", Duration::from_secs(1)),
609            ("10", "1", "10", Duration::ZERO),
610            ("0", "0", "10", Duration::from_secs(5)),
611            ("10", "-1", "-10", Duration::ZERO),
612        ] {
613            let mut headers = HeaderMap::new();
614            for (key, value) in [
615                ("x-ratelimit-limit", limit),
616                ("x-ratelimit-remaining", remaining),
617                ("x-ratelimit-reset", reset),
618            ] {
619                headers.insert(key, value.parse().unwrap());
620            }
621            client.record_rate_state("memory.get", &headers).await;
622            assert_eq!(client.rate_state.lock().await["memory.get"], expected);
623            assert!(!client.rate_state.lock().await.contains_key("memory.search"));
624            headers.insert("x-ratelimit-reset", "invalid".parse().unwrap());
625            client.record_rate_state("memory.get", &headers).await;
626            assert_eq!(client.rate_state.lock().await["memory.get"], expected);
627            headers.remove("x-ratelimit-reset");
628            client.record_rate_state("memory.get", &headers).await;
629            assert_eq!(client.rate_state.lock().await["memory.get"], expected);
630        }
631    }
632
633    #[test]
634    fn pacing_caps_hints_and_budget_and_does_not_spin_on_zero() {
635        for (hint, budget, expected) in [
636            (None, 15, 1),
637            (Some(61.0), 15, 1),
638            (Some(60.0), 15, 5),
639            (Some(30.0), 2, 2),
640            (Some(0.0), 15, 0),
641            (Some(1.0), 0, 0),
642            (Some(-1.0), 15, 0),
643            (Some(f64::NAN), 15, 1),
644        ] {
645            assert_eq!(
646                pacing_delay(hint, Duration::from_secs(budget)),
647                Duration::from_secs(expected)
648            );
649        }
650    }
651}