Skip to main content

basaltic/
request.rs

1use crate::{
2    ApiError, ApiResponse, Error, Page, RequestOptions, Result, WebSocketConnection,
3    error::invalid,
4    transport::{Core, json_response},
5};
6use futures_util::{
7    StreamExt, TryStreamExt,
8    stream::{self, BoxStream},
9};
10use serde::de::DeserializeOwned;
11use serde_json::Value;
12use std::{collections::HashSet, marker::PhantomData};
13
14pub(crate) enum Extract {
15    Normal,
16    Envelope(&'static str),
17    ReferenceList(&'static str),
18}
19
20/// An owned, typed JSON request. Constructing a request performs no network IO.
21#[must_use = "Requests are executed by calling send().await"]
22pub struct Request<T> {
23    core: Result<Core>,
24    extract: Extract,
25    marker: PhantomData<T>,
26}
27impl<T: DeserializeOwned> Request<T> {
28    pub(crate) fn new(core: Result<Core>) -> Self {
29        Self {
30            core,
31            extract: Extract::Normal,
32            marker: PhantomData,
33        }
34    }
35    pub(crate) fn reference(core: Result<Core>, extract: Extract) -> Self {
36        Self {
37            core,
38            extract,
39            marker: PhantomData,
40        }
41    }
42    pub fn options(mut self, options: RequestOptions) -> Self {
43        if let Ok(core) = &mut self.core {
44            core.options = options;
45        }
46        self
47    }
48    pub async fn send(self) -> Result<ApiResponse<T>> {
49        let response = json_response(self.core?.send().await?).await?;
50        let value = match self.extract {
51            Extract::Normal => response.data.clone(),
52            Extract::Envelope(key) => response
53                .data
54                .get(key)
55                .cloned()
56                .ok_or_else(|| Error::Protocol("Missing resource envelope".into()))?,
57            Extract::ReferenceList(key) => {
58                let items = response
59                    .data
60                    .get(key)
61                    .and_then(Value::as_array)
62                    .ok_or_else(|| Error::Protocol("Missing resource collection".into()))?;
63                if items.len() > 1
64                    || response
65                        .data
66                        .pointer("/meta/has_more")
67                        .and_then(Value::as_bool)
68                        == Some(true)
69                {
70                    return Err(Error::AmbiguousReference);
71                }
72                items.first().cloned().ok_or_else(|| {
73                    Error::Api(Box::new(ApiError {
74                        status: 404,
75                        code: "REFERENCE_NOT_FOUND".into(),
76                        message: "No resource matches the reference".into(),
77                        request_id: response.request_id().into(),
78                        operation: "resolve_reference".into(),
79                        headers: response.headers.clone(),
80                    }))
81                })?
82            }
83        };
84        let data = serde_json::from_value(value)?;
85        Ok(response.map(data))
86    }
87}
88
89#[must_use = "Requests are executed by calling send().await or consuming their stream"]
90pub struct PagedRequest<T, I> {
91    core: Result<Core>,
92    items_key: &'static str,
93    marker: PhantomData<(T, I)>,
94}
95impl<T: DeserializeOwned + Send + 'static, I: DeserializeOwned + Send + 'static>
96    PagedRequest<T, I>
97{
98    pub(crate) fn new(core: Result<Core>, items_key: &'static str) -> Self {
99        Self {
100            core,
101            items_key,
102            marker: PhantomData,
103        }
104    }
105    pub fn options(mut self, options: RequestOptions) -> Self {
106        if let Ok(core) = &mut self.core {
107            core.options = options;
108        }
109        self
110    }
111    pub async fn send(self) -> Result<Page<T, I>> {
112        let response = json_response(self.core?.send().await?).await?;
113        let values = response
114            .data
115            .get(self.items_key)
116            .filter(|v| v.is_array())
117            .ok_or_else(|| Error::Protocol("List response is missing its items array".into()))?;
118        let items = serde_json::from_value(values.clone())?;
119        let has_more = response
120            .data
121            .pointer("/meta/has_more")
122            .and_then(Value::as_bool)
123            == Some(true);
124        let marker = response
125            .data
126            .pointer("/meta/marker")
127            .and_then(Value::as_str)
128            .map(str::to_owned);
129        let data = serde_json::from_value(response.data.clone())?;
130        Ok(Page {
131            response: response.map(data),
132            items,
133            has_more,
134            marker,
135        })
136    }
137    /// Lazily request subsequent pages and fail if a marker does not advance.
138    pub fn pages(self) -> BoxStream<'static, Result<Page<T, I>>> {
139        let items_key = self.items_key;
140        let initial = self
141            .core
142            .as_ref()
143            .ok()
144            .and_then(|c| c.query.get("marker"))
145            .and_then(Value::as_str)
146            .unwrap_or("")
147            .to_string();
148        stream::try_unfold(
149            (self.core, HashSet::from([initial]), false),
150            move |(core, mut seen, done)| async move {
151                if done {
152                    return Ok(None);
153                }
154                let mut core = core?;
155                let page = PagedRequest::<T, I>::new(core.try_clone(), items_key)
156                    .send()
157                    .await?;
158                let next = page.next_marker(&mut seen)?;
159                let done = next.is_none();
160                if let Some(marker) = next {
161                    core.query
162                        .as_object_mut()
163                        .ok_or_else(|| invalid("Pagination requires an object query"))?
164                        .insert("marker".into(), Value::String(marker));
165                }
166                Ok(Some((page, (Ok(core), seen, done))))
167            },
168        )
169        .boxed()
170    }
171    pub fn items(self) -> BoxStream<'static, Result<I>> {
172        self.pages()
173            .map_ok(|p| stream::iter(p.items.into_iter().map(Ok)))
174            .try_flatten()
175            .boxed()
176    }
177}
178
179/// Streaming binary/HEAD response. Consume bytes/chunks or drop it to close.
180#[must_use = "Requests are executed by calling send().await"]
181pub struct BinaryRequest {
182    core: Result<Core>,
183}
184impl BinaryRequest {
185    pub(crate) fn new(core: Result<Core>) -> Self {
186        Self { core }
187    }
188    pub fn options(mut self, options: RequestOptions) -> Self {
189        if let Ok(core) = &mut self.core {
190            core.options = options;
191        }
192        self
193    }
194    pub async fn send(self) -> Result<reqwest::Response> {
195        self.core?.send().await
196    }
197}
198#[must_use = "Requests are executed by calling send().await"]
199pub struct EmptyRequest {
200    core: Result<Core>,
201}
202impl EmptyRequest {
203    pub(crate) fn new(core: Result<Core>) -> Self {
204        Self { core }
205    }
206    pub fn options(mut self, options: RequestOptions) -> Self {
207        if let Ok(core) = &mut self.core {
208            core.options = options;
209        }
210        self
211    }
212    pub async fn send(self) -> Result<ApiResponse<()>> {
213        let response = self.core?.send().await?;
214        Ok(ApiResponse {
215            data: (),
216            status: response.status().as_u16(),
217            headers: response.headers().clone(),
218        })
219    }
220}
221#[must_use = "Call prepare().await to obtain connection parameters"]
222pub struct WebSocketRequest {
223    core: Result<Core>,
224}
225impl WebSocketRequest {
226    pub(crate) fn new(core: Result<Core>) -> Self {
227        Self { core }
228    }
229    pub fn options(mut self, options: RequestOptions) -> Self {
230        if let Ok(core) = &mut self.core {
231            core.options = options;
232        }
233        self
234    }
235    pub async fn prepare(self) -> Result<WebSocketConnection> {
236        self.core?.websocket().await
237    }
238}
239
240pub(crate) fn reference_core(
241    get: Result<Core>,
242    list: Result<Core>,
243    reference: &str,
244    has_name: bool,
245    envelope: Option<&'static str>,
246    items_key: &'static str,
247) -> (Result<Core>, Extract) {
248    if reference.is_empty() {
249        return (
250            Err(invalid("Resource reference cannot be empty")),
251            Extract::Normal,
252        );
253    }
254    if reference.len() == 36 && uuid::Uuid::parse_str(reference).is_ok() {
255        return (
256            get,
257            envelope.map(Extract::Envelope).unwrap_or(Extract::Normal),
258        );
259    }
260    let kind = if reference.starts_with("crn:") {
261        if reference.split(':').count() != 5 {
262            return (
263                Err(invalid("A CRN requires five colon-separated segments")),
264                Extract::Normal,
265            );
266        }
267        "crn"
268    } else {
269        if !has_name {
270            return (
271                Err(invalid("This resource requires a UUID or CRN")),
272                Extract::Normal,
273            );
274        }
275        "name"
276    };
277    let core = list.and_then(|mut core| {
278        let query = core
279            .query
280            .as_object_mut()
281            .ok_or_else(|| invalid("Reference scope must be an object"))?;
282        for name in ["name", "crn", "marker"] {
283            query.remove(name);
284        }
285        query.insert(kind.into(), Value::String(reference.into()));
286        if core.op.query_encoding.iter().any(|e| e.name == "limit") {
287            query.insert("limit".into(), Value::Number(2.into()));
288        }
289        Ok(core)
290    });
291    (core, Extract::ReferenceList(items_key))
292}