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
use std::fmt;
use std::io::{self, Cursor};
use std::path::PathBuf;
use std::{borrow::Cow, collections::BTreeMap};
use async_compression::tokio::bufread::ZstdEncoder;
use bytes::Bytes;
use futures_util::StreamExt;
use objectstore_types::metadata::Metadata;
use reqwest::Body;
use serde::Deserialize;
use tokio::fs::File;
use tokio::io::{AsyncRead, BufReader};
use tokio_util::io::{ReaderStream, StreamReader};
pub use objectstore_types::metadata::{Compression, ExpirationPolicy};
use crate::{ClientStream, ObjectKey, Session};
/// The response returned from the service after uploading an object.
#[derive(Debug, Deserialize)]
pub struct PutResponse {
/// The key of the object, as stored.
pub key: ObjectKey,
}
pub(crate) enum PutBody {
Buffer(Bytes),
Stream(ClientStream),
File(File),
Path(PathBuf),
}
impl fmt::Debug for PutBody {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("PutBody").finish_non_exhaustive()
}
}
impl Session {
fn put_body(&self, body: PutBody) -> PutBuilder {
let metadata = Metadata {
expiration_policy: self.scope.usecase().expiration_policy(),
compression: self.scope.usecase().compression(),
..Default::default()
};
PutBuilder {
session: self.clone(),
metadata,
key: None,
body,
}
}
/// Creates or replaces an object using a [`Bytes`]-like payload.
pub fn put(&self, body: impl Into<Bytes>) -> PutBuilder {
self.put_body(PutBody::Buffer(body.into()))
}
/// Creates or replaces an object using a streaming payload.
pub fn put_stream(&self, body: ClientStream) -> PutBuilder {
self.put_body(PutBody::Stream(body))
}
/// Creates or replaces an object using an [`AsyncRead`] payload.
pub fn put_read<R>(&self, body: R) -> PutBuilder
where
R: AsyncRead + Send + Sync + 'static,
{
let stream = ReaderStream::new(body).boxed();
self.put_body(PutBody::Stream(stream))
}
/// Creates or replaces an object using the contents of an opened file.
///
/// The file descriptor is held open from the moment this method is called until the
/// upload completes. When enqueueing many files via [`Session::many`], prefer
/// [`put_path`](Session::put_path) instead: it defers opening the file until just before
/// upload, keeping file descriptor usage within the active concurrency window and avoiding
/// OS file descriptor limit (e.g., macOS's default `ulimit -n`) exhaustion.
pub fn put_file(&self, file: File) -> PutBuilder {
self.put_body(PutBody::File(file))
}
/// Creates or replaces an object using the contents of the file at `path`.
///
/// Unlike [`put_file`](Session::put_file), this method defers opening the file until the
/// request is actually sent. When enqueueing many file uploads via [`Session::many`], this
/// ensures that file descriptors are opened only within the active concurrency window,
/// preventing the process from exhausting the OS file descriptor limit (e.g., macOS's
/// default `ulimit -n`).
///
/// Prefer `put_path` over [`put_file`](Session::put_file) whenever you are lining up a
/// large number of files for upload.
pub fn put_path(&self, path: impl Into<PathBuf>) -> PutBuilder {
self.put_body(PutBody::Path(path.into()))
}
}
/// A [`put`](Session::put) request builder.
#[derive(Debug)]
pub struct PutBuilder {
pub(crate) session: Session,
pub(crate) metadata: Metadata,
pub(crate) key: Option<ObjectKey>,
pub(crate) body: PutBody,
}
impl PutBuilder {
/// 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 an explicit compression algorithm to be used for this payload.
///
/// [`None`] should be used if no compression should be performed by the client,
/// either because the payload is uncompressible (such as a media format), or if the user
/// will handle any kind of compression, without the clients knowledge.
///
/// By default, the compression algorithm set on this Session's Usecase is used.
pub fn compression(mut self, compression: impl Into<Option<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: 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.put("data")
/// .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 filename of the object.
///
/// When present, the server will include a `Content-Disposition: attachment; filename="<filename>"`
/// header in GET responses, prompting browsers and download tools to save the file under
/// this name.
pub fn filename(mut self, filename: impl Into<String>) -> Self {
self.metadata.filename = Some(filename.into());
self
}
/// This 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 they `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
}
}
/// Compresses the body if compression is specified.
pub(crate) async fn maybe_compress(
body: PutBody,
compression: Option<Compression>,
) -> io::Result<Body> {
Ok(match (compression, body) {
(Some(Compression::Zstd), PutBody::Buffer(bytes)) => {
let cursor = Cursor::new(bytes);
let encoder = ZstdEncoder::new(cursor);
let stream = ReaderStream::new(encoder);
Body::wrap_stream(stream)
}
(Some(Compression::Zstd), PutBody::Stream(stream)) => {
let stream = StreamReader::new(stream);
let encoder = ZstdEncoder::new(stream);
let stream = ReaderStream::new(encoder);
Body::wrap_stream(stream)
}
(Some(Compression::Zstd), PutBody::File(file)) => {
let reader = BufReader::new(file);
let encoder = ZstdEncoder::new(reader);
let stream = ReaderStream::new(encoder);
Body::wrap_stream(stream)
}
(Some(Compression::Zstd), PutBody::Path(file)) => {
let file = File::open(file).await?;
let reader = BufReader::new(file);
let encoder = ZstdEncoder::new(reader);
let stream = ReaderStream::new(encoder);
Body::wrap_stream(stream)
}
(None, PutBody::Buffer(bytes)) => bytes.into(),
(None, PutBody::Stream(stream)) => Body::wrap_stream(stream),
(None, PutBody::File(file)) => {
let stream = ReaderStream::new(file);
Body::wrap_stream(stream)
}
(None, PutBody::Path(path)) => {
let stream = ReaderStream::new(File::open(path).await?);
Body::wrap_stream(stream)
}
})
}
// TODO: instead of a separate `send` method, it would be nice to just implement `IntoFuture`.
// However, `IntoFuture` needs to define the resulting future as an associated type,
// and "impl trait in associated type position" is not yet stable :-(
impl PutBuilder {
/// Sends the built put request to the upstream service.
pub async fn send(self) -> crate::Result<PutResponse> {
let method = match self.key {
Some(_) => reqwest::Method::PUT,
None => reqwest::Method::POST,
};
let mut builder = self
.session
.request(method, self.key.as_deref().unwrap_or_default())?;
let body = maybe_compress(self.body, self.metadata.compression).await?;
builder = builder.headers(self.metadata.to_headers("")?);
let response = builder.body(body).send().await?;
Ok(response.error_for_status()?.json().await?)
}
}