Skip to main content

async_graphql/http/
multipart.rs

1use std::{
2    collections::HashMap,
3    io,
4    pin::Pin,
5    task::{Context, Poll},
6};
7
8use futures_util::{io::AsyncRead, stream::Stream};
9use multer::{Constraints, Multipart, SizeLimit};
10use pin_project_lite::pin_project;
11
12use crate::{BatchRequest, ParseRequestError, UploadValue};
13
14/// Options for `receive_multipart`.
15#[derive(Default, Clone, Copy)]
16#[non_exhaustive]
17pub struct MultipartOptions {
18    /// The maximum file size.
19    pub max_file_size: Option<usize>,
20    /// The maximum number of files.
21    pub max_num_files: Option<usize>,
22}
23
24impl MultipartOptions {
25    /// Set maximum file size.
26    #[must_use]
27    pub fn max_file_size(self, size: usize) -> Self {
28        MultipartOptions {
29            max_file_size: Some(size),
30            ..self
31        }
32    }
33
34    /// Set maximum number of files.
35    #[must_use]
36    pub fn max_num_files(self, n: usize) -> Self {
37        MultipartOptions {
38            max_num_files: Some(n),
39            ..self
40        }
41    }
42}
43
44pub(super) async fn receive_batch_multipart(
45    body: impl AsyncRead + Send,
46    boundary: impl Into<String>,
47    opts: MultipartOptions,
48) -> Result<BatchRequest, ParseRequestError> {
49    let mut multipart = Multipart::with_constraints(
50        ReaderStream::new(body),
51        boundary,
52        Constraints::new().size_limit({
53            let mut limit = SizeLimit::new();
54            if let (Some(max_file_size), Some(max_num_files)) =
55                (opts.max_file_size, opts.max_num_files)
56            {
57                limit = limit.whole_stream((max_file_size * max_num_files) as u64);
58            }
59            if let Some(max_file_size) = opts.max_file_size {
60                limit = limit.per_field(max_file_size as u64);
61            }
62            limit
63        }),
64    );
65
66    let mut request = None;
67    let mut map = None;
68    let mut files = Vec::new();
69
70    while let Some(field) = multipart.next_field().await? {
71        // in multipart, each field / file can actually have a own Content-Type.
72        // We use this to determine the encoding of the graphql query
73        let content_type = field
74            .content_type()
75            // default to json
76            .unwrap_or(&mime::APPLICATION_JSON)
77            .clone();
78        match field.name() {
79            Some("operations") => {
80                let body = field.bytes().await?;
81                request = Some(
82                    super::receive_batch_body_no_multipart(&content_type, body.as_ref()).await?,
83                )
84            }
85            Some("map") => {
86                let map_bytes = field.bytes().await?;
87
88                map = Some(
89                    serde_json::from_slice::<HashMap<String, Vec<String>>>(&map_bytes)
90                        .map_err(|e| ParseRequestError::InvalidFilesMap(Box::new(e)))?,
91                );
92            }
93            _ => {
94                if let Some(name) = field.name().map(ToString::to_string)
95                    && let Some(filename) = field.file_name().map(ToString::to_string)
96                {
97                    let content_type = field.content_type().map(ToString::to_string);
98
99                    #[cfg(feature = "tempfile")]
100                    let content = {
101                        use std::io::SeekFrom;
102
103                        use blocking::Unblock;
104                        use futures_util::{AsyncSeekExt, AsyncWriteExt};
105
106                        let mut field = field;
107
108                        let mut file =
109                            Unblock::new(tempfile::tempfile().map_err(ParseRequestError::Io)?);
110                        while let Some(chunk) = field.chunk().await? {
111                            file.write_all(&chunk)
112                                .await
113                                .map_err(ParseRequestError::Io)?;
114                        }
115                        file.seek(SeekFrom::Start(0))
116                            .await
117                            .map_err(ParseRequestError::Io)?;
118                        file.into_inner().await
119                    };
120
121                    #[cfg(not(feature = "tempfile"))]
122                    let content = field.bytes().await?;
123
124                    files.push((name, filename, content_type, content));
125                }
126            }
127        }
128    }
129
130    let mut request: BatchRequest = request.ok_or(ParseRequestError::MissingOperatorsPart)?;
131    let map = map.as_mut().ok_or(ParseRequestError::MissingMapPart)?;
132
133    for (name, filename, content_type, file) in files {
134        if let Some(var_paths) = map.remove(&name) {
135            let upload = UploadValue {
136                filename,
137                content_type,
138                content: file,
139            };
140
141            for var_path in var_paths {
142                match &mut request {
143                    BatchRequest::Single(request) => {
144                        request.set_upload(&var_path, upload.try_clone()?);
145                    }
146                    BatchRequest::Batch(requests) => {
147                        let mut s = var_path.splitn(2, '.');
148                        let idx = s.next().and_then(|idx| idx.parse::<usize>().ok());
149                        let path = s.next();
150
151                        if let (Some(idx), Some(path)) = (idx, path)
152                            && let Some(request) = requests.get_mut(idx)
153                        {
154                            request.set_upload(path, upload.try_clone()?);
155                        }
156                    }
157                }
158            }
159        }
160    }
161
162    if !map.is_empty() {
163        return Err(ParseRequestError::MissingFiles);
164    }
165
166    Ok(request)
167}
168
169pin_project! {
170    pub(crate) struct ReaderStream<T> {
171        buf: [u8; 2048],
172        #[pin]
173        reader: T,
174    }
175}
176
177impl<T> ReaderStream<T> {
178    pub(crate) fn new(reader: T) -> Self {
179        Self {
180            buf: [0; 2048],
181            reader,
182        }
183    }
184}
185
186impl<T: AsyncRead> Stream for ReaderStream<T> {
187    type Item = io::Result<Vec<u8>>;
188
189    fn poll_next(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
190        let this = self.project();
191
192        Poll::Ready(
193            match futures_util::ready!(this.reader.poll_read(cx, this.buf)?) {
194                0 => None,
195                size => Some(Ok(this.buf[..size].to_vec())),
196            },
197        )
198    }
199}