Skip to main content

clickhouse_loom/
call.rs

1use std::time::Duration;
2
3use reqwest::header::HeaderMap;
4
5use crate::{Error, RetryPolicy};
6
7/// Overrides for one logical call. Unset fields use the client's defaults.
8///
9/// Retry overrides leave the client's separate 429 pacing budget in effect.
10#[derive(Clone, Debug, Default)]
11#[non_exhaustive]
12pub struct CallOptions {
13    /// Timeout per complete HTTP attempt, including the response body.
14    pub timeout: Option<Duration>,
15    pub retry: Option<RetryPolicy>,
16    /// Applies to declared idempotent writes. Reuse only with the same operation and payload.
17    pub idempotency_key: Option<String>,
18    /// 1–64 letters, digits, dots, underscores or hyphens.
19    pub request_id: Option<String>,
20}
21
22impl CallOptions {
23    pub fn timeout(mut self, timeout: Duration) -> Self {
24        self.timeout = Some(timeout);
25        self
26    }
27
28    pub fn retry(mut self, retry: RetryPolicy) -> Self {
29        self.retry = Some(retry);
30        self
31    }
32
33    pub fn idempotency_key(mut self, key: impl Into<String>) -> Self {
34        self.idempotency_key = Some(key.into());
35        self
36    }
37
38    pub fn request_id(mut self, id: impl Into<String>) -> Self {
39        self.request_id = Some(id.into());
40        self
41    }
42
43    pub(crate) fn validate(&self, replayable: bool) -> Result<(), Error> {
44        if self.timeout.is_some_and(|timeout| timeout.is_zero()) {
45            return Err(Error::Input("call timeout must be positive".into()));
46        }
47        if let Some(retry) = &self.retry {
48            retry.validate()?;
49        }
50        if self.idempotency_key.is_some() && !replayable {
51            return Err(Error::Input(
52                "idempotency_key requires a declared idempotent write".into(),
53            ));
54        }
55        if let Some(id) = &self.request_id {
56            if id.is_empty()
57                || id.len() > 64
58                || !id
59                    .bytes()
60                    .all(|b| b.is_ascii_alphanumeric() || b"._-".contains(&b))
61            {
62                return Err(Error::Input(
63                    "request_id must be 1–64 letters, digits, dots, underscores or hyphens".into(),
64                ));
65            }
66        }
67        if let Some(key) = &self.idempotency_key {
68            if key.is_empty() || !key.bytes().all(|b| b.is_ascii_graphic()) {
69                return Err(Error::Input(
70                    "idempotency_key must contain visible ASCII characters".into(),
71                ));
72            }
73        }
74        Ok(())
75    }
76}
77
78/// X-RateLimit-* values on a response; reset is measured in seconds.
79#[derive(Clone, Debug, PartialEq, Eq)]
80#[non_exhaustive]
81pub struct RateLimit {
82    pub limit: i64,
83    pub remaining: i64,
84    pub reset_s: i64,
85}
86
87/// Metadata from the final HTTP attempt, including incomplete responses.
88#[derive(Clone, Debug)]
89#[non_exhaustive]
90pub struct CallMetadata {
91    pub sent_request_id: String,
92    /// The echoed request ID, or the sent ID when no echo is present.
93    pub request_id: String,
94    /// None when no response headers arrived.
95    pub status: Option<u16>,
96    pub schema_version: Option<String>,
97    /// Duration of the app metric in Server-Timing, in milliseconds.
98    pub server_timing_ms: Option<f64>,
99    /// None when any rate-limit header is missing or invalid.
100    pub rate_limit: Option<RateLimit>,
101    /// All HTTP attempts, including retries and 429 pacing rounds.
102    pub attempts: u64,
103    pub hint: Option<String>,
104    pub hint_code: Option<String>,
105}
106
107impl CallMetadata {
108    pub(crate) fn new(sent_id: &str, attempts: u64) -> Self {
109        Self {
110            sent_request_id: sent_id.to_owned(),
111            request_id: sent_id.to_owned(),
112            status: None,
113            schema_version: None,
114            server_timing_ms: None,
115            rate_limit: None,
116            attempts,
117            hint: None,
118            hint_code: None,
119        }
120    }
121
122    pub(crate) fn record_response(&mut self, status: u16, headers: &HeaderMap) {
123        self.status = Some(status);
124        self.request_id =
125            text(headers, "x-request-id").unwrap_or_else(|| self.sent_request_id.clone());
126        self.schema_version = text(headers, "x-schema-version");
127        self.server_timing_ms = text(headers, "server-timing")
128            .as_deref()
129            .and_then(app_duration_ms);
130        self.rate_limit = rate_limit(headers);
131        self.hint = text(headers, "x-loom-hint");
132        self.hint_code = text(headers, "x-loom-hint-code");
133    }
134}
135
136/// A typed response with metadata from its final successful HTTP attempt.
137#[derive(Debug)]
138#[non_exhaustive]
139pub struct CallResult<T> {
140    pub data: T,
141    pub metadata: CallMetadata,
142}
143
144/// The original error and its final attempt's metadata.
145#[derive(Debug, derive_more::Display)]
146#[display("{error}")]
147#[non_exhaustive]
148pub struct CallFailure {
149    pub error: Error,
150    /// None for validation or encoding failures before dispatch.
151    pub metadata: Option<Box<CallMetadata>>,
152}
153
154impl From<Error> for CallFailure {
155    fn from(error: Error) -> Self {
156        Self {
157            error,
158            metadata: None,
159        }
160    }
161}
162
163impl std::error::Error for CallFailure {
164    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
165        Some(&self.error)
166    }
167}
168
169pub(crate) fn rate_limit(headers: &HeaderMap) -> Option<RateLimit> {
170    let number = |key| text(headers, key)?.parse().ok();
171    Some(RateLimit {
172        limit: number("x-ratelimit-limit")?,
173        remaining: number("x-ratelimit-remaining")?,
174        reset_s: number("x-ratelimit-reset")?,
175    })
176}
177
178fn text(headers: &HeaderMap, key: &str) -> Option<String> {
179    headers
180        .get(key)?
181        .to_str()
182        .ok()
183        .filter(|v| !v.is_empty())
184        .map(str::to_owned)
185}
186
187fn app_duration_ms(raw: &str) -> Option<f64> {
188    for metric in raw.split(',') {
189        let mut parts = metric.split(';').map(str::trim);
190        if parts.next() != Some("app") {
191            continue;
192        }
193        for part in parts {
194            if let Some((key, value)) = part.split_once('=') {
195                if key.trim() == "dur" {
196                    return value
197                        .trim()
198                        .parse::<f64>()
199                        .ok()
200                        .filter(|d| d.is_finite() && *d >= 0.0);
201                }
202            }
203        }
204    }
205    None
206}
207
208#[cfg(test)]
209mod tests {
210    use super::*;
211
212    #[test]
213    fn metadata_preserves_absence_and_rejects_invalid_headers() {
214        let mut headers = HeaderMap::new();
215        let mut metadata = CallMetadata::new("sent", 2);
216        metadata.record_response(200, &headers);
217        assert_eq!(metadata.request_id, "sent");
218        assert!(metadata.schema_version.is_none());
219        assert!(metadata.hint.is_none());
220        assert!(metadata.rate_limit.is_none());
221        for (key, value) in [
222            ("x-request-id", ""),
223            ("x-schema-version", ""),
224            ("x-ratelimit-limit", "10"),
225            ("x-ratelimit-remaining", "2"),
226            ("x-ratelimit-reset", "bad"),
227        ] {
228            headers.insert(key, value.parse().unwrap());
229        }
230        metadata.record_response(200, &headers);
231        assert_eq!(metadata.request_id, "sent");
232        assert!(metadata.schema_version.is_none());
233        assert!(metadata.rate_limit.is_none());
234        headers.insert("x-ratelimit-reset", "8".parse().unwrap());
235        assert_eq!(rate_limit(&headers).unwrap().reset_s, 8);
236        headers.remove("x-ratelimit-limit");
237        assert!(rate_limit(&headers).is_none());
238        for (raw, expected) in [
239            ("db;dur=9, app;desc=handler; dur = 12.5", Some(12.5)),
240            ("app;dur=0", Some(0.0)),
241            ("application;dur=5", None),
242            ("app;dur=NaN", None),
243            ("app;dur=inf", None),
244            ("app;dur=-1", None),
245            ("app;dur=bad", None),
246        ] {
247            assert_eq!(app_duration_ms(raw), expected, "{raw}");
248        }
249    }
250}