1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
use std::borrow::Cow;
use std::collections::BTreeMap;
use base64::Engine as _;
use bytes::Bytes;
use futures_util::StreamExt as _;
use objectstore_types::metadata::Metadata;
use objectstore_types::multipart::{
CompleteErrorDetail, CompleteRequest, CompleteSuccessResponse, InitiateResponse,
ListPartsResponse, UploadPartResponse,
};
use reqwest::Body;
use serde::Deserialize;
use tokio::io::AsyncRead;
use tokio_util::io::ReaderStream;
use crate::{ClientStream, ObjectKey, Session};
pub use objectstore_types::multipart::CompletePart;
pub use objectstore_types::multipart::ETag;
pub use objectstore_types::multipart::PartInfo;
pub use objectstore_types::multipart::PartNumber;
pub use objectstore_types::multipart::UploadId;
#[derive(Deserialize)]
#[serde(untagged)]
enum CompleteResponse {
Error { error: CompleteErrorDetail },
Success(CompleteSuccessResponse),
}
impl Session {
/// Creates a builder for initiating a multipart upload.
///
/// The returned [`InitiateMultipartBuilder`] inherits the session's default compression
/// and expiration settings.
///
/// IMPORTANT: unlike single-object uploads, the client does not automatically compress the
/// contents of [`MultipartUpload::put`]/[`MultipartUpload::put_stream`] based on the
/// configured `compression`.
/// The caller is responsible to compress the payload in accordance with the configured
/// `compression`.
/// That's because we require `content_length` on each part to be the length of the compressed
/// content, which we wouldn't be able to know beforehand if `objectstore_client` automatically
/// compressed payloads on the fly.
pub fn initiate_multipart_upload(&self) -> InitiateMultipartBuilder {
let metadata = Metadata {
expiration_policy: self.scope.usecase().expiration_policy(),
compression: self.scope.usecase().compression(),
..Default::default()
};
InitiateMultipartBuilder {
session: self.clone(),
metadata,
key: None,
}
}
/// Resumes an existing multipart upload from its key and upload ID.
///
/// This reconstructs a [`MultipartUpload`] handle from previously obtained identifiers, and
/// doesn't make any network calls.
/// Use this to resume an upload after a process restart or to continue an upload initiated elsewhere.
pub fn resume_multipart_upload(
&self,
key: impl Into<ObjectKey>,
upload_id: impl Into<String>,
) -> crate::Result<MultipartUpload> {
Ok(MultipartUpload {
session: self.clone(),
key: key.into(),
upload_id: UploadId::new(upload_id.into())?,
})
}
}
/// A builder for initiating a multipart upload.
#[derive(Debug)]
pub struct InitiateMultipartBuilder {
session: Session,
metadata: Metadata,
key: Option<ObjectKey>,
}
impl InitiateMultipartBuilder {
/// Sets an explicit object key.
///
/// If a key is specified, the object will be stored under that key. Otherwise, the Objectstore
/// server will automatically assign a random key, which is then returned from this request.
pub fn key(mut self, key: impl Into<ObjectKey>) -> Self {
self.key = Some(key.into()).filter(|k| !k.is_empty());
self
}
/// Sets the compression algorithm recorded in this object's metadata.
///
/// IMPORTANT: unlike single-object uploads, the client does not automatically compress the
/// contents of [`MultipartUpload::put`]/[`MultipartUpload::put_stream`] based on the
/// configured `compression`.
/// The caller is responsible to compress the payload in accordance with the configured
/// `compression`.
///
/// By default, the compression algorithm set on this Session's Usecase is used.
pub fn compression(mut self, compression: impl Into<Option<crate::Compression>>) -> Self {
self.metadata.compression = compression.into();
self
}
/// Sets the expiration policy of the object to be uploaded.
///
/// By default, the expiration policy set on this Session's Usecase is used.
pub fn expiration_policy(mut self, expiration_policy: crate::ExpirationPolicy) -> Self {
self.metadata.expiration_policy = expiration_policy;
self
}
/// Sets the content type of the object to be uploaded.
///
/// You can use the utility function [`crate::utils::guess_mime_type`] to attempt to guess a
/// `content_type` based on magic bytes.
pub fn content_type(mut self, content_type: impl Into<Cow<'static, str>>) -> Self {
self.metadata.content_type = content_type.into();
self
}
/// Sets the origin of the object, typically the IP address of the original source.
///
/// This is an optional but encouraged field that tracks where the payload was
/// originally obtained from. For example, the IP address of the Sentry SDK or CLI
/// that uploaded the data.
///
/// # Example
///
/// ```no_run
/// # async fn example(session: objectstore_client::Session) {
/// session.initiate_multipart_upload()
/// .origin("203.0.113.42")
/// .send()
/// .await
/// .unwrap();
/// # }
/// ```
pub fn origin(mut self, origin: impl Into<String>) -> Self {
self.metadata.origin = Some(origin.into());
self
}
/// Sets the custom metadata to the provided map.
///
/// It will clear any previously set metadata.
pub fn set_metadata(mut self, metadata: impl Into<BTreeMap<String, String>>) -> Self {
self.metadata.custom = metadata.into();
self
}
/// Appends the `key`/`value` to the custom metadata of this object.
pub fn append_metadata(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
self.metadata.custom.insert(key.into(), value.into());
self
}
/// Sends the initiate request and returns a [`MultipartUpload`] handle.
pub async fn send(self) -> crate::Result<MultipartUpload> {
let method = match self.key {
Some(_) => reqwest::Method::PUT,
None => reqwest::Method::POST,
};
let mut builder =
self.session
.multipart_request(method, None, self.key.as_deref(), None)?;
builder = builder.headers(self.metadata.to_headers("")?);
let response: InitiateResponse = builder.send().await?.error_for_status()?.json().await?;
Ok(MultipartUpload {
session: self.session,
key: response.key,
upload_id: response.upload_id,
})
}
}
/// Represents an ongoing Multipart Upload, tied to a specific [`Session`] and [`UploadId`].
///
/// Create a Multipart Upload handle using [`Session::initiate_multipart_upload`] or [`Session::resume_multipart_upload`].
#[derive(Debug)]
pub struct MultipartUpload {
session: Session,
key: String,
upload_id: UploadId,
}
impl MultipartUpload {
/// Returns the upload session identifier.
pub fn upload_id(&self) -> &UploadId {
&self.upload_id
}
/// Returns the key of the object that this upload will create.
pub fn key(&self) -> &ObjectKey {
&self.key
}
/// Uploads a part using a [`Bytes`]-like payload.
///
/// IMPORTANT: unlike single-object uploads, the client does not automatically compress
/// contents based on this upload's `Metadata::compression`.
/// The caller is responsible to compress the payload in accordance with the `compression`,
/// and, optionally, to pass the `content_md5` of the compressed payload.
pub async fn put(
&self,
body: impl Into<Bytes>,
part_number: u32,
content_md5: Option<&[u8; 16]>,
) -> crate::Result<CompletePart> {
let bytes = body.into();
let content_length = bytes.len() as u64;
self.upload_part(bytes.into(), part_number, content_length, content_md5)
.await
}
/// Uploads a part using a streaming payload.
///
/// IMPORTANT: unlike single-object uploads, the client does not automatically compress
/// contents based on this upload's `Metadata::compression`.
/// The caller is responsible to compress the payload in accordance with the `compression`,
/// and to pass the `content_length` and, optionally, `content_md5` of the compressed payload.
pub async fn put_stream(
&self,
stream: ClientStream,
part_number: u32,
content_length: u64,
content_md5: Option<&[u8; 16]>,
) -> crate::Result<CompletePart> {
self.upload_part(
Body::wrap_stream(stream),
part_number,
content_length,
content_md5,
)
.await
}
/// Uploads a part from an [`AsyncRead`] source.
///
/// IMPORTANT: unlike single-object uploads, the client does not automatically compress
/// contents based on this upload's `Metadata::compression`.
/// The caller is responsible to compress the payload in accordance with the `compression`,
/// and to pass the `content_length` and, optionally, `content_md5` of the compressed payload.
pub async fn put_read<R>(
&self,
reader: R,
part_number: u32,
content_length: u64,
content_md5: Option<&[u8; 16]>,
) -> crate::Result<CompletePart>
where
R: AsyncRead + Send + Sync + 'static,
{
let stream = ReaderStream::new(reader).boxed();
self.put_stream(stream, part_number, content_length, content_md5)
.await
}
async fn upload_part(
&self,
body: Body,
part_number: u32,
content_length: u64,
content_md5: Option<&[u8; 16]>,
) -> crate::Result<CompletePart> {
let part_number =
PartNumber::new(part_number).ok_or(crate::Error::InvalidPartNumber(part_number))?;
let mut builder = self
.session
.multipart_request(
reqwest::Method::PUT,
Some("parts"),
Some(&self.key),
Some(vec![
("upload_id", self.upload_id.to_string()),
("part_number", part_number.to_string()),
]),
)?
.header(reqwest::header::CONTENT_LENGTH, content_length)
.body(body);
if let Some(md5) = content_md5 {
let encoded = base64::engine::general_purpose::STANDARD.encode(md5);
builder = builder.header("content-md5", encoded);
}
let response: UploadPartResponse = builder.send().await?.error_for_status()?.json().await?;
Ok(CompletePart {
part_number,
etag: response.etag,
})
}
/// Lists all parts that have been uploaded for this multipart upload.
pub async fn list_parts(&self) -> crate::Result<Vec<PartInfo>> {
let mut all_parts = Vec::new();
let mut marker = None;
loop {
let page = self.list_parts_page(None, marker).await?;
all_parts.extend(page.parts);
if !page.is_truncated {
return Ok(all_parts);
}
marker = page.next_part_number_marker;
if marker.is_none() {
return Err(crate::Error::MalformedResponse(
"server returned is_truncated=true but no next_part_number_marker. Please report a bug.".into(),
));
}
}
}
async fn list_parts_page(
&self,
max_parts: Option<u32>,
part_number_marker: Option<PartNumber>,
) -> crate::Result<ListPartsResponse> {
let mut params: Vec<(&str, String)> = vec![("upload_id", self.upload_id.to_string())];
if let Some(max) = max_parts {
params.push(("max_parts", max.to_string()));
}
if let Some(marker) = part_number_marker {
params.push(("part_number_marker", marker.to_string()));
}
let builder = self.session.multipart_request(
reqwest::Method::GET,
Some("parts"),
Some(&self.key),
Some(params),
)?;
let response: ListPartsResponse = builder.send().await?.error_for_status()?.json().await?;
Ok(response)
}
/// Aborts this multipart upload.
pub async fn abort(self) -> crate::Result<()> {
let builder = self.session.multipart_request(
reqwest::Method::DELETE,
None,
Some(&self.key),
Some(vec![("upload_id", self.upload_id.to_string())]),
)?;
builder.send().await?.error_for_status()?;
Ok(())
}
/// Completes the multipart upload, assembling all parts into the final object.
pub async fn complete(
self,
parts: impl IntoIterator<Item = CompletePart>,
) -> crate::Result<ObjectKey> {
let mut parts: Vec<_> = parts.into_iter().collect();
parts.sort_by_key(|p| p.part_number);
let builder = self
.session
.multipart_request(
reqwest::Method::POST,
Some("complete"),
Some(&self.key),
Some(vec![("upload_id", self.upload_id.to_string())]),
)?
.json(&CompleteRequest { parts });
let response = builder.send().await?.error_for_status()?;
match response.json::<CompleteResponse>().await? {
CompleteResponse::Success(s) => Ok(s.key),
CompleteResponse::Error { error } => Err(crate::Error::MultipartComplete {
code: error.code,
message: error.message,
}),
}
}
}