Skip to main content

reddb_client/connector/
http.rs

1//! HTTP/HTTPS REST client.
2//!
3//! Talks to `red`'s HTTP listener (`POST /query` with a JSON body).
4//! Bearer auth via the `Authorization` header. HTTPS uses rustls
5//! through ureq's `rustls` feature; certificate validation is on by
6//! default, no implicit "skip verify".
7//!
8//! ureq is synchronous; the bin offloads each call onto
9//! `tokio::task::spawn_blocking` so the current-thread runtime
10//! stays responsive.
11
12use std::fmt;
13
14use reddb_wire::auth::{bearer_authorization_value, AUTHORIZATION_HEADER};
15
16#[derive(Debug, Clone)]
17pub enum Auth {
18    Anonymous,
19    Bearer(String),
20}
21
22#[derive(Debug)]
23pub enum HttpError {
24    Network(String),
25    Http { status: u16, body: String },
26    Decode(String),
27}
28
29impl fmt::Display for HttpError {
30    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
31        match self {
32            Self::Network(m) => write!(f, "network: {m}"),
33            Self::Http { status, body } => write!(f, "HTTP {status}: {body}"),
34            Self::Decode(m) => write!(f, "decode: {m}"),
35        }
36    }
37}
38
39impl std::error::Error for HttpError {}
40
41type Result<T> = std::result::Result<T, HttpError>;
42
43/// Single-shot query: POST `<base_url>/query` with a JSON body and
44/// return the response body as a string. The caller decides what to
45/// do with the response shape (typically pretty-print it).
46///
47/// Synchronous: callers from an async context should wrap in
48/// `tokio::task::spawn_blocking`.
49pub fn query_one_shot(base_url: &str, sql: &str, auth: &Auth) -> Result<String> {
50    let url = format!("{}/query", base_url.trim_end_matches('/'));
51    let body = serde_json::json!({ "query": sql }).to_string();
52    let mut req = ureq::post(&url).header("content-type", "application/json");
53    if let Auth::Bearer(token) = auth {
54        req = req.header(AUTHORIZATION_HEADER, &bearer_authorization_value(token));
55    }
56    let mut resp = req
57        .send(body.as_bytes())
58        .map_err(|e| HttpError::Network(e.to_string()))?;
59    let status = resp.status().as_u16();
60    let body_text = resp
61        .body_mut()
62        .read_to_string()
63        .map_err(|e| HttpError::Decode(e.to_string()))?;
64    if status >= 400 {
65        return Err(HttpError::Http {
66            status,
67            body: body_text,
68        });
69    }
70    Ok(body_text)
71}