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                        let mut field = field;
102
103                        #[cfg(feature = "unblock")]
104                        {
105                            use std::io::SeekFrom;
106
107                            use blocking::Unblock;
108                            use futures_util::{AsyncSeekExt, AsyncWriteExt};
109
110                            let mut file =
111                                Unblock::new(tempfile::tempfile().map_err(ParseRequestError::Io)?);
112                            while let Some(chunk) = field.chunk().await? {
113                                file.write_all(&chunk)
114                                    .await
115                                    .map_err(ParseRequestError::Io)?;
116                            }
117                            file.seek(SeekFrom::Start(0))
118                                .await
119                                .map_err(ParseRequestError::Io)?;
120                            file.into_inner().await
121                        }
122
123                        #[cfg(not(feature = "unblock"))]
124                        {
125                            use std::io::{Seek, Write};
126
127                            let mut file = tempfile::tempfile().map_err(ParseRequestError::Io)?;
128                            while let Some(chunk) = field.chunk().await? {
129                                file.write_all(&chunk).map_err(ParseRequestError::Io)?;
130                            }
131                            file.rewind()?;
132                            file
133                        }
134                    };
135
136                    #[cfg(not(feature = "tempfile"))]
137                    let content = field.bytes().await?;
138
139                    files.push((name, filename, content_type, content));
140                }
141            }
142        }
143    }
144
145    let mut request: BatchRequest = request.ok_or(ParseRequestError::MissingOperatorsPart)?;
146    let map = map.as_mut().ok_or(ParseRequestError::MissingMapPart)?;
147
148    for (name, filename, content_type, file) in files {
149        if let Some(var_paths) = map.remove(&name) {
150            let upload = UploadValue {
151                filename,
152                content_type,
153                content: file,
154            };
155
156            for var_path in var_paths {
157                match &mut request {
158                    BatchRequest::Single(request) => {
159                        request.set_upload(&var_path, upload.try_clone()?);
160                    }
161                    BatchRequest::Batch(requests) => {
162                        let mut s = var_path.splitn(2, '.');
163                        let idx = s.next().and_then(|idx| idx.parse::<usize>().ok());
164                        let path = s.next();
165
166                        if let (Some(idx), Some(path)) = (idx, path)
167                            && let Some(request) = requests.get_mut(idx)
168                        {
169                            request.set_upload(path, upload.try_clone()?);
170                        }
171                    }
172                }
173            }
174        }
175    }
176
177    if !map.is_empty() {
178        return Err(ParseRequestError::MissingFiles);
179    }
180
181    Ok(request)
182}
183
184pin_project! {
185    pub(crate) struct ReaderStream<T> {
186        buf: [u8; 2048],
187        #[pin]
188        reader: T,
189    }
190}
191
192impl<T> ReaderStream<T> {
193    pub(crate) fn new(reader: T) -> Self {
194        Self {
195            buf: [0; 2048],
196            reader,
197        }
198    }
199}
200
201impl<T: AsyncRead> Stream for ReaderStream<T> {
202    type Item = io::Result<Vec<u8>>;
203
204    fn poll_next(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
205        let this = self.project();
206
207        Poll::Ready(
208            match futures_util::ready!(this.reader.poll_read(cx, this.buf)?) {
209                0 => None,
210                size => Some(Ok(this.buf[..size].to_vec())),
211            },
212        )
213    }
214}