reasoninglayer 1.0.3

Rust client SDK for the Reasoning Layer API
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
//! Internal HTTP client wrapping `reqwest` with auth header injection, retry-with-backoff, and
//! timeout enforcement. Not part of the public API.

use std::sync::Arc;
use std::time::Duration;

use reqwest::header::{HeaderName, HeaderValue, AUTHORIZATION, CONTENT_TYPE};
use reqwest::{Method, StatusCode};
use serde::de::DeserializeOwned;
use serde::Serialize;
use serde_json::Value;

use crate::config::{ResolvedConfig, SDK_LANGUAGE, SDK_VERSION};
use crate::error::{ApiError, ApiErrorKind, Error};
use crate::types::common::{ApiResponse, RateLimitInfo, RequestOptions};

const API_PREFIX: &str = "/api/v1";
const MAX_BACKOFF: Duration = Duration::from_secs(30);
const BASE_BACKOFF_MS: u64 = 1_000;

/// HTTP methods supported by the SDK.
#[derive(Debug, Clone, Copy)]
pub(crate) enum HttpMethod {
    Get,
    Post,
    Put,
    Delete,
    #[allow(dead_code)]
    Patch,
}

impl From<HttpMethod> for Method {
    fn from(m: HttpMethod) -> Self {
        match m {
            HttpMethod::Get => Method::GET,
            HttpMethod::Post => Method::POST,
            HttpMethod::Put => Method::PUT,
            HttpMethod::Delete => Method::DELETE,
            HttpMethod::Patch => Method::PATCH,
        }
    }
}

/// Internal HTTP client used by resource clients.
#[derive(Debug, Clone)]
pub(crate) struct HttpClient {
    pub(crate) inner: reqwest::Client,
    pub(crate) config: Arc<ResolvedConfig>,
}

impl HttpClient {
    /// Build a new client from resolved config.
    pub(crate) fn new(config: ResolvedConfig) -> Result<Self, Error> {
        let inner = reqwest::Client::builder()
            .build()
            .map_err(|err| Error::Network {
                message: err.to_string(),
                source: Some(Box::new(err)),
            })?;
        Ok(Self {
            inner,
            config: Arc::new(config),
        })
    }

    pub(crate) async fn get<Resp>(
        &self,
        path: &str,
        query: Option<&[(&str, &str)]>,
        opts: Option<&RequestOptions>,
    ) -> Result<Resp, Error>
    where
        Resp: DeserializeOwned,
    {
        let response = self
            .request_raw::<()>(HttpMethod::Get, path, query, None, opts)
            .await?;
        decode_value(response.data)
    }

    pub(crate) async fn post<Body, Resp>(
        &self,
        path: &str,
        body: &Body,
        opts: Option<&RequestOptions>,
    ) -> Result<Resp, Error>
    where
        Body: Serialize + ?Sized,
        Resp: DeserializeOwned,
    {
        let response = self
            .request_raw(HttpMethod::Post, path, None, Some(body), opts)
            .await?;
        decode_value(response.data)
    }

    pub(crate) async fn put<Body, Resp>(
        &self,
        path: &str,
        body: &Body,
        opts: Option<&RequestOptions>,
    ) -> Result<Resp, Error>
    where
        Body: Serialize + ?Sized,
        Resp: DeserializeOwned,
    {
        let response = self
            .request_raw(HttpMethod::Put, path, None, Some(body), opts)
            .await?;
        decode_value(response.data)
    }

    pub(crate) async fn delete<Resp>(
        &self,
        path: &str,
        query: Option<&[(&str, &str)]>,
        opts: Option<&RequestOptions>,
    ) -> Result<Resp, Error>
    where
        Resp: DeserializeOwned,
    {
        let response = self
            .request_raw::<()>(HttpMethod::Delete, path, query, None, opts)
            .await?;
        decode_value(response.data)
    }

    pub(crate) async fn patch<Body, Resp>(
        &self,
        path: &str,
        body: &Body,
        opts: Option<&RequestOptions>,
    ) -> Result<Resp, Error>
    where
        Body: Serialize + ?Sized,
        Resp: DeserializeOwned,
    {
        let response = self
            .request_raw(HttpMethod::Patch, path, None, Some(body), opts)
            .await?;
        decode_value(response.data)
    }

    pub(crate) async fn post_with_query<Body, Resp>(
        &self,
        path: &str,
        query: Option<&[(&str, &str)]>,
        body: &Body,
        opts: Option<&RequestOptions>,
    ) -> Result<Resp, Error>
    where
        Body: Serialize + ?Sized,
        Resp: DeserializeOwned,
    {
        let response = self
            .request_raw(HttpMethod::Post, path, query, Some(body), opts)
            .await?;
        decode_value(response.data)
    }

    /// Execute an HTTP request, handling auth, retries, and timeouts. Returns the JSON-parsed body
    /// plus response metadata. Most resource methods go through this path.
    pub(crate) async fn request_raw<Body>(
        &self,
        method: HttpMethod,
        path: &str,
        query: Option<&[(&str, &str)]>,
        body: Option<&Body>,
        opts: Option<&RequestOptions>,
    ) -> Result<ApiResponse<Value>, Error>
    where
        Body: Serialize + ?Sized,
    {
        let raw = self
            .request_raw_bytes(method, path, query, body, opts)
            .await?;
        let data = if raw.data.is_empty() {
            Value::Null
        } else {
            serde_json::from_slice(&raw.data)?
        };
        Ok(ApiResponse {
            data,
            status: raw.status,
            headers: raw.headers,
            rate_limit: raw.rate_limit,
        })
    }

    /// Convenience wrapper for endpoints whose response body is `text/plain` (e.g. GraphViz DOT,
    /// Prometheus metrics). Returns the body as a UTF-8 string after the same auth/retry/timeout
    /// handling as JSON requests.
    pub(crate) async fn get_text(
        &self,
        path: &str,
        opts: Option<&RequestOptions>,
    ) -> Result<String, Error> {
        let raw = self
            .request_raw_bytes::<()>(HttpMethod::Get, path, None, None, opts)
            .await?;
        String::from_utf8(raw.data.to_vec()).map_err(|err| Error::Network {
            message: format!("response body was not valid UTF-8: {err}"),
            source: Some(Box::new(err)),
        })
    }

    /// GET with a typed query DTO. The query struct is serialized via `serde_urlencoded` and
    /// appended to the path; the rest of the request flow is identical to [`get`](Self::get).
    pub(crate) async fn get_with_typed_query<Q, Resp>(
        &self,
        path: &str,
        query: &Q,
        opts: Option<&RequestOptions>,
    ) -> Result<Resp, Error>
    where
        Q: Serialize + ?Sized,
        Resp: DeserializeOwned,
    {
        let qs = serde_urlencoded::to_string(query)
            .map_err(|e| Error::validation_msg(format!("invalid query parameters: {e}")))?;
        let full_path = if qs.is_empty() {
            path.to_string()
        } else {
            format!("{path}?{qs}")
        };
        self.get(&full_path, None, opts).await
    }

    /// Workhorse: send the request with auth/retry/timeout handling and return the response body
    /// as raw bytes. Higher-level wrappers ([`request_raw`](Self::request_raw),
    /// [`get_text`](Self::get_text)) decode those bytes as JSON or text.
    async fn request_raw_bytes<Body>(
        &self,
        method: HttpMethod,
        path: &str,
        query: Option<&[(&str, &str)]>,
        body: Option<&Body>,
        opts: Option<&RequestOptions>,
    ) -> Result<ApiResponse<bytes::Bytes>, Error>
    where
        Body: Serialize + ?Sized,
    {
        let max_retries = opts
            .and_then(|o| o.retries)
            .unwrap_or(self.config.max_retries);
        let timeout = opts.and_then(|o| o.timeout).unwrap_or(self.config.timeout);

        let resolved_path = resolve_path(path);
        let url = format!("{}{}", self.config.base_url, resolved_path);

        let serialized_body = match body {
            Some(b) => Some(serde_json::to_vec(b)?),
            None => None,
        };

        let mut attempt: u32 = 0;
        loop {
            let mut request = self
                .inner
                .request(method.into(), &url)
                .timeout(timeout)
                .header(CONTENT_TYPE, "application/json")
                .header(HeaderName::from_static("accept"), "application/json")
                .header(HeaderName::from_static("x-sdk-version"), SDK_VERSION)
                .header(HeaderName::from_static("x-sdk-language"), SDK_LANGUAGE)
                .header(
                    HeaderName::from_static("x-tenant-id"),
                    &self.config.tenant_id,
                );

            if let Some(user_id) = opts
                .and_then(|o| o.user_id.as_deref())
                .or(self.config.user_id.as_deref())
            {
                request = request.header(HeaderName::from_static("x-user-id"), user_id);
            }
            if let Some(namespace_id) = opts
                .and_then(|o| o.namespace_id.as_deref())
                .or(self.config.namespace_id.as_deref())
            {
                request = request.header(HeaderName::from_static("x-namespace-id"), namespace_id);
            }
            if let Some(user) = self.config.authenticated_user.as_deref() {
                request = request.header(HeaderName::from_static("x-authenticated-user"), user);
            }
            if let crate::config::AuthConfig::Bearer(token) = &self.config.auth {
                let value = HeaderValue::from_str(&format!("Bearer {token}")).map_err(|_| {
                    Error::validation("auth", "invalid characters in bearer token")
                })?;
                request = request.header(AUTHORIZATION, value);
            }
            for (name, value) in &self.config.extra_headers {
                request = request.header(name.as_str(), value.as_str());
            }
            if let Some(q) = query {
                request = request.query(q);
            }
            if let Some(bytes) = &serialized_body {
                request = request.body(bytes.clone());
            }

            match request.send().await {
                Ok(response) => {
                    let status = response.status();
                    let headers = response.headers().clone();
                    let rate_limit = RateLimitInfo::from_headers(&headers);

                    if status.is_success() {
                        if status == StatusCode::NO_CONTENT {
                            return Ok(ApiResponse {
                                data: bytes::Bytes::new(),
                                status,
                                headers,
                                rate_limit,
                            });
                        }
                        let body_bytes = response
                            .bytes()
                            .await
                            .map_err(|err| map_runtime(err, timeout))?;
                        return Ok(ApiResponse {
                            data: body_bytes,
                            status,
                            headers,
                            rate_limit,
                        });
                    }

                    let body_bytes = response
                        .bytes()
                        .await
                        .map_err(|err| map_runtime(err, timeout))?;
                    let body_value: Option<Value> = if body_bytes.is_empty() {
                        None
                    } else {
                        serde_json::from_slice(&body_bytes).ok()
                    };
                    let api_error = ApiError::from_response(status, body_value, headers);

                    if should_retry_status(status, self.config.retry_on_503)
                        && attempt < max_retries
                    {
                        let delay = retry_delay_from_api_error(&api_error, attempt + 1);
                        attempt += 1;
                        tokio::time::sleep(delay).await;
                        continue;
                    }
                    return Err(Error::from(api_error));
                }
                Err(err) => {
                    if err.is_timeout() {
                        return Err(Error::Timeout { timeout });
                    }
                    if attempt < max_retries && is_retryable_network_error(&err) {
                        let delay = backoff_delay(attempt + 1);
                        attempt += 1;
                        tokio::time::sleep(delay).await;
                        continue;
                    }
                    return Err(map_runtime(err, timeout));
                }
            }
        }
    }
}

fn decode_value<T: DeserializeOwned>(v: Value) -> Result<T, Error> {
    serde_json::from_value(v).map_err(Error::Serde)
}

/// Paths that are rooted at the server (no `/api/v1` prefix).
const ABSOLUTE_PREFIXES: &[&str] = &[
    "/api/",
    "/health",
    "/ready",
    "/live",
    "/metrics",
    "/ws/",
    "/api-docs",
    "/swagger-ui",
];

/// Resolve a user-supplied path: prepend `/api/v1` unless the path is already absolute.
/// The caller is responsible for URL-encoding path parameters.
pub(crate) fn resolve_path_public(path: &str) -> String {
    resolve_path(path)
}

fn resolve_path(path: &str) -> String {
    if ABSOLUTE_PREFIXES
        .iter()
        .any(|p| path == *p || path.starts_with(p))
    {
        path.to_string()
    } else if path.starts_with('/') {
        format!("{API_PREFIX}{path}")
    } else {
        format!("{API_PREFIX}/{path}")
    }
}

fn should_retry_status(status: StatusCode, retry_on_503: bool) -> bool {
    if status == StatusCode::TOO_MANY_REQUESTS {
        return true;
    }
    if status == StatusCode::SERVICE_UNAVAILABLE && retry_on_503 {
        return true;
    }
    false
}

fn retry_delay_from_api_error(err: &ApiError, attempt: u32) -> Duration {
    if err.kind == ApiErrorKind::RateLimit {
        if let Some(rl) = err.rate_limit() {
            if let Some(secs) = rl.retry_after {
                return Duration::from_secs(secs);
            }
        }
    }
    backoff_delay(attempt)
}

/// Exponential backoff with jitter: `min(1000 * 2^(attempt-1) + random(0..=1000), 30_000)` ms.
fn backoff_delay(attempt: u32) -> Duration {
    use rand::Rng;
    let shift = attempt.saturating_sub(1).min(16);
    let exp = BASE_BACKOFF_MS.saturating_mul(1u64 << shift);
    let jitter: u64 = rand::thread_rng().gen_range(0..=1_000);
    let total = exp.saturating_add(jitter);
    let capped = total.min(MAX_BACKOFF.as_millis() as u64);
    Duration::from_millis(capped)
}

fn is_retryable_network_error(err: &reqwest::Error) -> bool {
    err.is_connect() || err.is_request() || err.is_body()
}

fn map_runtime(err: reqwest::Error, timeout: Duration) -> Error {
    if err.is_timeout() {
        return Error::Timeout { timeout };
    }
    Error::Network {
        message: err.to_string(),
        source: Some(Box::new(err)),
    }
}