Skip to main content

tangled_api/
xrpc.rs

1//! Transport helpers shared by the generated lexicon builder functions.
2//!
3//! The generated functions in [`crate::lexicon`] return plain
4//! [`reqwest::RequestBuilder`]s with the URL, HTTP method, and body already
5//! set. Callers attach whatever headers/auth they need (e.g.
6//! `.bearer_auth(token)`) and then either drive the request themselves or use
7//! [`send`] / [`send_unit`] / [`send_bytes`] for XRPC-aware status handling
8//! and typed deserialization.
9
10use serde::de::DeserializeOwned;
11use serde::Deserialize;
12
13#[derive(Debug, thiserror::Error)]
14pub enum XrpcError {
15    #[error(transparent)]
16    Transport(#[from] reqwest::Error),
17    #[error("{status}{}{}", error.as_deref().map(|e| format!(" {e}")).unwrap_or_default(), message.as_deref().map(|m| format!(": {m}")).unwrap_or_default())]
18    Status {
19        status: reqwest::StatusCode,
20        /// XRPC error code (the `error` field of the error body), if any.
21        error: Option<String>,
22        /// XRPC error message, if any.
23        message: Option<String>,
24        /// Raw response body.
25        body: String,
26    },
27    #[error("failed to decode response from {url}: {source}; body: {snippet}")]
28    Decode {
29        url: String,
30        snippet: String,
31        #[source]
32        source: serde_json::Error,
33    },
34}
35
36/// Builds `<base>/xrpc/<nsid>`, defaulting to `https://` when `base` has no
37/// scheme.
38pub fn xrpc_url(base: &str, nsid: &str) -> String {
39    let base = base.trim_end_matches('/');
40    if base.starts_with("http://") || base.starts_with("https://") {
41        format!("{base}/xrpc/{nsid}")
42    } else {
43        format!("https://{base}/xrpc/{nsid}")
44    }
45}
46
47/// Appends `params` to the request's query string.
48///
49/// `params` is serialized through `serde_json`; `null`s are skipped and
50/// arrays repeat the key (`?tag=a&tag=b`), matching XRPC conventions.
51pub fn push_query<T: serde::Serialize>(
52    mut rb: reqwest::RequestBuilder,
53    params: &T,
54) -> reqwest::RequestBuilder {
55    let value = match serde_json::to_value(params) {
56        Ok(serde_json::Value::Object(map)) => map,
57        // A params struct always serializes to an object; anything else is a
58        // programming error surfaced at request time by reqwest.
59        _ => return rb,
60    };
61    for (key, value) in value {
62        match value {
63            serde_json::Value::Null => {}
64            serde_json::Value::Array(items) => {
65                for item in items {
66                    rb = rb.query(&[(key.as_str(), scalar_to_string(&item))]);
67                }
68            }
69            other => {
70                rb = rb.query(&[(key.as_str(), scalar_to_string(&other))]);
71            }
72        }
73    }
74    rb
75}
76
77fn scalar_to_string(v: &serde_json::Value) -> String {
78    match v {
79        serde_json::Value::String(s) => s.clone(),
80        other => other.to_string(),
81    }
82}
83
84/// Sends the request and deserializes a JSON response body into `T`.
85pub async fn send<T: DeserializeOwned>(
86    rb: reqwest::RequestBuilder,
87) -> Result<T, XrpcError> {
88    parse(rb.send().await?).await
89}
90
91/// Sends the request, checking status but discarding any response body.
92pub async fn send_unit(rb: reqwest::RequestBuilder) -> Result<(), XrpcError> {
93    parse_unit(rb.send().await?).await
94}
95
96/// Sends the request and returns the raw response bytes (for binary outputs
97/// such as `com.atproto.sync.getBlob`).
98pub async fn send_bytes(
99    rb: reqwest::RequestBuilder,
100) -> Result<Vec<u8>, XrpcError> {
101    parse_bytes(rb.send().await?).await
102}
103
104/// Checks the status of an already-received response and deserializes its
105/// JSON body into `T`. Useful when the caller needs to inspect response
106/// headers (e.g. DPoP nonces) before handing off parsing.
107pub async fn parse<T: DeserializeOwned>(
108    res: reqwest::Response,
109) -> Result<T, XrpcError> {
110    let (url, body) = success_body(res).await?;
111    serde_json::from_slice(&body).map_err(|source| XrpcError::Decode {
112        url,
113        snippet: snippet(&body),
114        source,
115    })
116}
117
118/// Checks the status of an already-received response, discarding any body.
119pub async fn parse_unit(res: reqwest::Response) -> Result<(), XrpcError> {
120    success_body(res).await.map(|_| ())
121}
122
123/// Checks the status of an already-received response and returns the raw
124/// body bytes.
125pub async fn parse_bytes(res: reqwest::Response) -> Result<Vec<u8>, XrpcError> {
126    success_body(res).await.map(|(_, body)| body.to_vec())
127}
128
129async fn success_body(
130    res: reqwest::Response,
131) -> Result<(String, bytes::Bytes), XrpcError> {
132    let status = res.status();
133    let url = res.url().to_string();
134    let body = res.bytes().await?;
135    if status.is_success() {
136        return Ok((url, body));
137    }
138
139    #[derive(Deserialize)]
140    struct ErrorBody {
141        error: Option<String>,
142        message: Option<String>,
143    }
144    let parsed: Option<ErrorBody> = serde_json::from_slice(&body).ok();
145    Err(XrpcError::Status {
146        status,
147        error: parsed.as_ref().and_then(|e| e.error.clone()),
148        message: parsed.as_ref().and_then(|e| e.message.clone()),
149        body: String::from_utf8_lossy(&body).into_owned(),
150    })
151}
152
153fn snippet(body: &[u8]) -> String {
154    let s = String::from_utf8_lossy(body);
155    s.chars().take(300).collect()
156}