Skip to main content

libkeri_http/
client.rs

1//! Async HTTP client for talking to KERI witnesses and OOBI endpoints, the
2//! Rust counterpart of keripy's `httping` + `agenting.Receiptor` HTTP calls.
3//! Plain `async fn`s: the caller owns the runtime and the libkeri state.
4
5use crate::{
6    split, CesrRequest, CodecError, CESR_ATTACHMENT_HEADER, CESR_CONTENT_TYPE,
7    CESR_CONTENT_TYPE_V2, CESR_DESTINATION_HEADER,
8};
9
10#[derive(Debug, thiserror::Error)]
11pub enum ClientError {
12    #[error("http: {0}")]
13    Http(#[from] reqwest::Error),
14    #[error("{0}")]
15    Codec(#[from] CodecError),
16    #[error("{url} returned HTTP {status}: {body}")]
17    Status { url: String, status: u16, body: String },
18}
19
20/// Response to submitting an event to a witness's `/receipts`.
21#[derive(Debug)]
22pub enum ReceiptResponse {
23    /// The witness receipted the event: `rct` message with its signature.
24    Receipted(Vec<u8>),
25    /// The witness accepted the request but has not (yet) receipted (HTTP 202).
26    Pending,
27}
28
29#[derive(Clone, Default)]
30pub struct Client {
31    http: reqwest::Client,
32}
33
34impl Client {
35    pub fn new() -> Self {
36        Self::default()
37    }
38
39    /// GET an OOBI URL and return the CESR stream it serves.
40    pub async fn get_oobi(&self, url: &str) -> Result<Vec<u8>, ClientError> {
41        let rep = self.http.get(url).send().await?;
42        let status = rep.status();
43        let body = rep.bytes().await?;
44        if !status.is_success() {
45            return Err(ClientError::Status {
46                url: url.to_string(),
47                status: status.as_u16(),
48                body: String::from_utf8_lossy(&body).to_string(),
49            });
50        }
51        Ok(body.to_vec())
52    }
53
54    /// POST one event (with its attachments) to `{base_url}receipts`, as keripy's
55    /// `Receiptor.receipt` does with `streamCESRRequests(path="receipts")`.
56    pub async fn post_receipt(
57        &self,
58        base_url: &str,
59        dest: &str,
60        event: &[u8],
61    ) -> Result<ReceiptResponse, ClientError> {
62        let mut reqs = split(event)?;
63        if reqs.len() != 1 {
64            return Err(CodecError::MissingVersion.into());
65        }
66        let req = reqs.remove(0);
67        let url = join_url(base_url, "receipts");
68        let rep = self.post_cesr(&url, dest, &req).await?;
69        let status = rep.status().as_u16();
70        let body = rep.bytes().await?.to_vec();
71        match status {
72            200 => Ok(ReceiptResponse::Receipted(body)),
73            202 => Ok(ReceiptResponse::Pending),
74            _ => Err(ClientError::Status {
75                url,
76                status,
77                body: String::from_utf8_lossy(&body).to_string(),
78            }),
79        }
80    }
81
82    /// Send every message in a CESR stream to `{base_url}` (keripy `HttpEnd`),
83    /// one CESR-over-HTTP POST per message, as keripy `streamCESRRequests`
84    /// does. Not PUT: keripy's `HttpEnd.on_put` reads only the raw body and
85    /// ignores the `CESR-ATTACHMENT` header, so attachments would be lost.
86    pub async fn send(&self, base_url: &str, dest: &str, stream: &[u8]) -> Result<(), ClientError> {
87        let url = join_url(base_url, "");
88        for req in split(stream)? {
89            let rep = self.post_cesr(&url, dest, &req).await?;
90            if !rep.status().is_success() {
91                let status = rep.status().as_u16();
92                return Err(ClientError::Status {
93                    url,
94                    status,
95                    body: rep.text().await.unwrap_or_default(),
96                });
97            }
98        }
99        Ok(())
100    }
101}
102
103impl Client {
104    /// POST one CESR-over-HTTP request. keripy 1.x and main name the content
105    /// type differently and each answers 406 to the other's, so on 406 the
106    /// request is sent once more with the other name.
107    async fn post_cesr(
108        &self,
109        url: &str,
110        dest: &str,
111        req: &CesrRequest,
112    ) -> Result<reqwest::Response, ClientError> {
113        let mut rep = None;
114        for content_type in [CESR_CONTENT_TYPE, CESR_CONTENT_TYPE_V2] {
115            let r = self
116                .http
117                .post(url)
118                .header("Content-Type", content_type)
119                .header(CESR_ATTACHMENT_HEADER, req.attachments.clone())
120                .header(CESR_DESTINATION_HEADER, dest)
121                .body(req.body.clone())
122                .send()
123                .await?;
124            if r.status().as_u16() != 406 {
125                return Ok(r);
126            }
127            rep = Some(r);
128        }
129        Ok(rep.expect("at least one attempt"))
130    }
131}
132
133fn join_url(base: &str, path: &str) -> String {
134    format!("{}/{}", base.trim_end_matches('/'), path)
135}
136
137#[cfg(test)]
138mod tests {
139    use super::*;
140
141    #[test]
142    fn joins_urls() {
143        assert_eq!(join_url("http://127.0.0.1:5642/", "receipts"), "http://127.0.0.1:5642/receipts");
144        assert_eq!(join_url("http://127.0.0.1:5642", "receipts"), "http://127.0.0.1:5642/receipts");
145        assert_eq!(join_url("http://127.0.0.1:5642/", ""), "http://127.0.0.1:5642/");
146    }
147}