1use 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 error: Option<String>,
22 message: Option<String>,
24 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
36pub 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
47pub 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 _ => 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
84pub async fn send<T: DeserializeOwned>(
86 rb: reqwest::RequestBuilder,
87) -> Result<T, XrpcError> {
88 parse(rb.send().await?).await
89}
90
91pub async fn send_unit(rb: reqwest::RequestBuilder) -> Result<(), XrpcError> {
93 parse_unit(rb.send().await?).await
94}
95
96pub async fn send_bytes(
99 rb: reqwest::RequestBuilder,
100) -> Result<Vec<u8>, XrpcError> {
101 parse_bytes(rb.send().await?).await
102}
103
104pub 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
118pub async fn parse_unit(res: reqwest::Response) -> Result<(), XrpcError> {
120 success_body(res).await.map(|_| ())
121}
122
123pub 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}