http_mel/upload.rs
1//! Uploads of data while it is produced, to prepared requests, such as presigned by object
2//! storage: in parts of growing sizes (multipart uploads), or in one request of known size.
3//!
4//! Parts are cut ahead of their upload, so that programs can have a request prepared for each
5//! of them, connections in a program never looping back.
6
7use crate::client::*;
8use melodium_core::{common::executive::Output, *};
9use melodium_macro::{mel_function, mel_treatment};
10use std::sync::Arc;
11
12/// Return the size of the part `part_number` of an upload, from 1.
13///
14/// Parts are 8 MiB for parts 1 to 1,000, then double every 1,000 parts, up to 4 GiB for parts
15/// 9,001 to 10,000: the 10,000 parts object storage takes hold about 8 TiB.
16/// This is the size `cut` gives its parts, to tell when preparing requests for them.
17#[mel_function]
18pub fn part_size(part_number: u32) -> u64 {
19 crate::transfer::part_size(part_number)
20}
21
22/// Cut data into parts to upload.
23///
24/// The bytes received through `data` are given through `parts` in parts of the sizes
25/// `|part_size` gives, the last one being shorter. There is always at least one part, empty
26/// when there is no data.
27///
28/// Once `data` ends and every part is given, `completed` is emitted. If the data needs more
29/// than 10,000 parts, `failed` is emitted and `error` contains the reason.
30/// `finished` is emitted in every case.
31///
32/// Memory holds the part being cut, and those given but not taken yet.
33///
34/// ```mermaid
35/// graph LR
36/// T("cut()")
37/// B["β¦ π¦ π¦ π¦ π¦ π¦"] -->|data| T
38///
39/// T -->|parts| P["β¦ [π¦ π¦] [π¦ π¦ π¦]"]
40///
41/// style B fill:#ffffff,stroke:#ffffff
42/// style P fill:#ffffff,stroke:#ffffff
43/// ```
44#[mel_treatment(
45 input data Stream<byte>
46 output parts Stream<Vec<byte>>
47 output completed Block<void>
48 output failed Block<void>
49 output finished Block<void>
50 output error Block<string>
51)]
52pub async fn cut() {
53 let mut cutter = crate::transfer::Cutter::new(crate::transfer::part_size);
54 let result: Result<bool, String> = async {
55 while let Ok(bytes) = data.recv_many_as::<u8>().await {
56 for part in cutter.push(&bytes)? {
57 if !give(&**parts, part).await {
58 return Ok(false);
59 }
60 }
61 }
62 Ok(match cutter.finish() {
63 Some(part) => give(&**parts, part).await,
64 None => true,
65 })
66 }
67 .await;
68
69 data.close();
70 parts.close().await;
71 match result {
72 Ok(true) => {
73 let _ = completed.send_one(().into()).await;
74 }
75 Ok(false) => {}
76 Err(reason) => {
77 let _ = failed.send_one(().into()).await;
78 let _ = error.send_one(reason.into()).await;
79 }
80 }
81 let _ = finished.send_one(().into()).await;
82}
83
84/// Gives `part` through `parts`, telling whether it was taken.
85async fn give(parts: &dyn Output, part: Vec<u8>) -> bool {
86 parts
87 .send_one(Value::Packed(PackedArray::Byte(Arc::new(part))))
88 .await
89 .is_ok()
90}
91
92/// Upload parts, each to its prepared request.
93///
94/// Each part received through `parts`, such as `cut` gives, is sent with the request received
95/// through `requests` in the same position, such as one presigned for that part number, with
96/// its length. The value of the header named `tag_header` in each answer, such as `etag` for
97/// object storage, is given through `tags`, in the order of the parts, to complete the upload.
98///
99/// A part refused with `5xx`, `429` or `408`, or whose connection fails, is sent again up to
100/// `retries` times, waiting longer each time: it is kept until it is uploaded. Memory holds that
101/// part, and those given but not taken yet.
102///
103/// Once `parts` ends and every part is uploaded, `completed` is emitted. If a part is refused
104/// otherwise, retries are exhausted, an answer has no `tag_header`, or a part has no request,
105/// `failed` is emitted and `error` contains the reason, with the status and the `<Code>` of
106/// XML error bodies, never the URL. `finished` is emitted in every case.
107///
108/// Requests are made as given, without the headers of any `HttpClient`.
109///
110/// ```mermaid
111/// graph LR
112/// T("parts()")
113/// P["β¦ [π¦ π¦] [π¦ π¦ π¦]"] -->|parts| T
114/// R["β¦ π¨ π¨"] -->|requests| T
115/// H["γetagγ"] -->|tag_header| T
116///
117/// T -->|tags| O["β¦ πͺ πͺ"]
118/// T -->|completed| C["γπ©γ"]
119///
120/// style P fill:#ffffff,stroke:#ffffff
121/// style R fill:#ffffff,stroke:#ffffff
122/// style H fill:#ffffff,stroke:#ffffff
123/// style O fill:#ffffff,stroke:#ffffff
124/// style C fill:#ffffff,stroke:#ffffff
125/// ```
126#[mel_treatment(
127 default retries 5
128 input parts Stream<Vec<byte>>
129 input requests Stream<PreparedRequest>
130 input tag_header Block<string>
131 output tags Stream<string>
132 output completed Block<void>
133 output failed Block<void>
134 output finished Block<void>
135 output error Block<string>
136)]
137pub async fn parts(retries: u32) {
138 let result: Result<bool, String> = async {
139 let tag_header = tag_header
140 .recv_one_as::<String>()
141 .await
142 .map_err(|_| "no tag header was given".to_string())?;
143 let mut number = 0;
144 while let Ok(part) = parts.recv_one().await {
145 number += 1;
146 let part = match part {
147 Value::Packed(PackedArray::Byte(bytes)) => bytes,
148 Value::Vec(values) => Arc::new(
149 values
150 .into_iter()
151 .map(|value| match value {
152 Value::Byte(byte) => Some(byte),
153 _ => None,
154 })
155 .collect::<Option<Vec<u8>>>()
156 .ok_or_else(|| format!("part {number} is not bytes"))?,
157 ),
158 _ => return Err(format!("part {number} is not bytes")),
159 };
160 let request = requests
161 .recv_one_as::<Arc<PreparedRequest>>()
162 .await
163 .map_err(|_| format!("part {number} has no prepared request"))?;
164
165 #[cfg(feature = "real")]
166 let tag = crate::transfer::upload_part(
167 crate::transfer::client(),
168 &request,
169 &part,
170 &tag_header,
171 retries,
172 )
173 .await
174 .map_err(|reason| format!("part {number}: {reason}"))?;
175 #[cfg(feature = "mock")]
176 let tag: String = {
177 let _ = (&request, &part, &tag_header, retries);
178 return Err("uploads are not available in mock mode".to_string());
179 };
180
181 if tags.send_one(tag.into()).await.is_err() {
182 return Ok(false);
183 }
184 }
185 Ok(true)
186 }
187 .await;
188
189 parts.close();
190 requests.close();
191 tags.close().await;
192 match result {
193 Ok(true) => {
194 let _ = completed.send_one(().into()).await;
195 }
196 Ok(false) => {}
197 Err(reason) => {
198 let _ = failed.send_one(().into()).await;
199 let _ = error.send_one(reason.into()).await;
200 }
201 }
202 let _ = finished.send_one(().into()).await;
203}
204
205/// Upload data of known size in one prepared request.
206///
207/// The bytes received through `data` are sent with `request`, such as one presigned for a
208/// small file, while they come, with `size` as length: nothing is kept, so a failed upload is
209/// not sent again.
210///
211/// Once the data is sent and accepted, `completed` is emitted. If the data is longer or
212/// shorter than `size`, the request is refused, or its connection fails, `failed` is emitted
213/// and `error` contains the reason, with the status and the `<Code>` of XML error bodies, never
214/// the URL. `finished` is emitted in every case.
215///
216/// The request is made as given, without the headers of any `HttpClient`.
217///
218/// ```mermaid
219/// graph LR
220/// T("put()")
221/// R["γπ¨γ"] -->|request| T
222/// S["γ11γ"] -->|size| T
223/// B["β¦ π¦ π¦ π¦"] -->|data| T
224///
225/// T -->|completed| C["γπ©γ"]
226///
227/// style R fill:#ffffff,stroke:#ffffff
228/// style S fill:#ffffff,stroke:#ffffff
229/// style B fill:#ffffff,stroke:#ffffff
230/// style C fill:#ffffff,stroke:#ffffff
231/// ```
232#[mel_treatment(
233 input request Block<PreparedRequest>
234 input size Block<u64>
235 input data Stream<byte>
236 output completed Block<void>
237 output failed Block<void>
238 output finished Block<void>
239 output error Block<string>
240)]
241pub async fn put() {
242 let result: Result<(), String> = async {
243 let request = request
244 .recv_one_as::<Arc<PreparedRequest>>()
245 .await
246 .map_err(|_| "no prepared request was given".to_string())?;
247 let size = size
248 .recv_one_as::<u64>()
249 .await
250 .map_err(|_| "no size was given".to_string())?;
251
252 #[cfg(feature = "real")]
253 return crate::transfer::put(crate::transfer::client(), &request, size, || async {
254 data.recv_many_as::<u8>().await.ok()
255 })
256 .await;
257 #[cfg(feature = "mock")]
258 {
259 let _ = (&request, size);
260 Err("uploads are not available in mock mode".to_string())
261 }
262 }
263 .await;
264
265 data.close();
266 match result {
267 Ok(()) => {
268 let _ = completed.send_one(().into()).await;
269 }
270 Err(reason) => {
271 let _ = failed.send_one(().into()).await;
272 let _ = error.send_one(reason.into()).await;
273 }
274 }
275 let _ = finished.send_one(().into()).await;
276}