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
use std::{collections::HashMap, convert::TryFrom};
use js_sys::{Array, Date as JsDate, JsString, Object as JsObject, Uint8Array};
use wasm_bindgen::{JsCast, JsValue};
use wasm_bindgen_futures::JsFuture;
use worker_sys::r2::{
R2Bucket as EdgeR2Bucket, R2HttpMetadata as R2HttpMetadataSys, R2Object as EdgeR2Object,
R2Range as R2RangeSys,
};
use crate::{Date, Error, ObjectInner, Objects, Result};
use super::{Data, Object};
pub struct GetOptionsBuilder<'bucket> {
pub(crate) edge_bucket: &'bucket EdgeR2Bucket,
pub(crate) key: String,
pub(crate) only_if: Option<Conditional>,
pub(crate) range: Option<Range>,
}
impl<'bucket> GetOptionsBuilder<'bucket> {
pub fn only_if(mut self, only_if: Conditional) -> Self {
self.only_if = Some(only_if);
self
}
pub fn range(mut self, range: Range) -> Self {
self.range = Some(range);
self
}
pub async fn execute(self) -> Result<Option<Object>> {
let name: String = self.key;
let get_promise = self.edge_bucket.get(
name,
js_object! {
"onlyIf" => self.only_if.map(JsObject::from),
"range" => self.range.map(JsObject::from),
}
.into(),
);
let value = JsFuture::from(get_promise).await?;
if value.is_null() {
return Ok(None);
}
let res: EdgeR2Object = value.into();
let inner = if JsString::from("bodyUsed").js_in(&res) {
ObjectInner::Body(res.unchecked_into())
} else {
ObjectInner::NoBody(res)
};
Ok(Some(Object { inner }))
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Conditional {
pub etag_matches: Option<String>,
pub etag_does_not_match: Option<String>,
pub uploaded_before: Option<Date>,
pub uploaded_after: Option<Date>,
}
impl From<Conditional> for JsObject {
fn from(val: Conditional) -> Self {
js_object! {
"etagMatches" => JsValue::from(val.etag_matches),
"etagDoesNotMatch" => JsValue::from(val.etag_does_not_match),
"uploadedBefore" => JsValue::from(val.uploaded_before.map(JsDate::from)),
"uploadedAfter" => JsValue::from(val.uploaded_after.map(JsDate::from)),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Range {
OffsetWithLength { offset: u32, length: u32 },
OffsetWithOptionalLength { offset: u32, length: Option<u32> },
OptionalOffsetWithLength { offset: Option<u32>, length: u32 },
Suffix { suffix: u32 },
}
impl From<Range> for JsObject {
fn from(val: Range) -> Self {
match val {
Range::OffsetWithLength { offset, length } => js_object! {
"offset" => Some(offset),
"length" => Some(length),
"suffix" => JsValue::UNDEFINED,
},
Range::OffsetWithOptionalLength { offset, length } => js_object! {
"offset" => Some(offset),
"length" => length,
"suffix" => JsValue::UNDEFINED,
},
Range::OptionalOffsetWithLength { offset, length } => js_object! {
"offset" => offset,
"length" => Some(length),
"suffix" => JsValue::UNDEFINED,
},
Range::Suffix { suffix } => js_object! {
"offset" => JsValue::UNDEFINED,
"length" => JsValue::UNDEFINED,
"suffix" => Some(suffix),
},
}
}
}
impl TryFrom<R2RangeSys> for Range {
type Error = Error;
fn try_from(val: R2RangeSys) -> Result<Self> {
Ok(match (val.offset, val.length, val.suffix) {
(Some(offset), Some(length), None) => Self::OffsetWithLength { offset, length },
(Some(offset), None, None) => Self::OffsetWithOptionalLength {
offset,
length: None,
},
(None, Some(length), None) => Self::OptionalOffsetWithLength {
offset: None,
length,
},
(None, None, Some(suffix)) => Self::Suffix { suffix },
_ => return Err(Error::JsError("invalid range".into())),
})
}
}
pub struct PutOptionsBuilder<'bucket> {
pub(crate) edge_bucket: &'bucket EdgeR2Bucket,
pub(crate) key: String,
pub(crate) value: Data,
pub(crate) http_metadata: Option<HttpMetadata>,
pub(crate) custom_metadata: Option<HashMap<String, String>>,
pub(crate) md5: Option<Vec<u8>>,
}
impl<'bucket> PutOptionsBuilder<'bucket> {
pub fn http_metadata(mut self, metadata: HttpMetadata) -> Self {
self.http_metadata = Some(metadata);
self
}
pub fn custom_metdata(mut self, metadata: impl Into<HashMap<String, String>>) -> Self {
self.custom_metadata = Some(metadata.into());
self
}
pub fn md5(mut self, bytes: impl Into<Vec<u8>>) -> Self {
self.md5 = Some(bytes.into());
self
}
pub async fn execute(self) -> Result<Object> {
let value: JsValue = self.value.into();
let name: String = self.key;
let put_promise = self.edge_bucket.put(
name,
value,
js_object! {
"httpMetadata" => self.http_metadata.map(JsObject::from),
"customMetadata" => match self.custom_metadata {
Some(metadata) => {
let obj = JsObject::new();
for (k, v) in metadata.into_iter() {
js_sys::Reflect::set(&obj, &JsString::from(k), &JsString::from(v))?;
}
obj.into()
}
None => JsValue::UNDEFINED,
},
"md5" => self.md5.map(|bytes| {
let arr = Uint8Array::new_with_length(bytes.len() as _);
arr.copy_from(&bytes);
arr.buffer()
})
}
.into(),
);
let res: EdgeR2Object = JsFuture::from(put_promise).await?.into();
let inner = if JsString::from("bodyUsed").js_in(&res) {
ObjectInner::Body(res.unchecked_into())
} else {
ObjectInner::NoBody(res)
};
Ok(Object { inner })
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct HttpMetadata {
pub content_type: Option<String>,
pub content_language: Option<String>,
pub content_disposition: Option<String>,
pub content_encoding: Option<String>,
pub cache_control: Option<String>,
pub cache_expiry: Option<Date>,
}
impl From<HttpMetadata> for JsObject {
fn from(val: HttpMetadata) -> Self {
js_object! {
"contentType" => val.content_type,
"contentLanguage" => val.content_language,
"contentDisposition" => val.content_disposition,
"contentEncoding" => val.content_encoding,
"cacheControl" => val.cache_control,
"cacheExpiry" => val.cache_expiry.map(JsDate::from),
}
}
}
impl From<R2HttpMetadataSys> for HttpMetadata {
fn from(val: R2HttpMetadataSys) -> Self {
Self {
content_type: val.content_type(),
content_language: val.content_language(),
content_disposition: val.content_disposition(),
content_encoding: val.content_encoding(),
cache_control: val.cache_control(),
cache_expiry: val.cache_expiry().map(Into::into),
}
}
}
pub struct ListOptionsBuilder<'bucket> {
pub(crate) edge_bucket: &'bucket EdgeR2Bucket,
pub(crate) limit: Option<u32>,
pub(crate) prefix: Option<String>,
pub(crate) cursor: Option<String>,
pub(crate) delimiter: Option<String>,
pub(crate) include: Option<Vec<Include>>,
}
impl<'bucket> ListOptionsBuilder<'bucket> {
pub fn limit(mut self, limit: u32) -> Self {
self.limit = Some(limit);
self
}
pub fn prefix(mut self, prefix: impl Into<String>) -> Self {
self.prefix = Some(prefix.into());
self
}
pub fn cursor(mut self, cursor: impl Into<String>) -> Self {
self.cursor = Some(cursor.into());
self
}
pub fn delimiter(mut self, delimiter: impl Into<String>) -> Self {
self.delimiter = Some(delimiter.into());
self
}
pub fn include(mut self, include: Vec<Include>) -> Self {
self.include = Some(include);
self
}
pub async fn execute(self) -> Result<Objects> {
let list_promise = self.edge_bucket.list(
js_object! {
"limit" => self.limit,
"prefix" => self.prefix,
"cursor" => self.cursor,
"delimiter" => self.delimiter,
"include" => self
.include
.map(|include| {
let arr = Array::new();
for include in include {
arr.push(&JsString::from(match include {
Include::HttpMetadata => "httpMetadata",
Include::CustomMetadata => "customMetadata",
}));
}
arr.into()
})
.unwrap_or(JsValue::UNDEFINED),
}
.into(),
);
let inner = JsFuture::from(list_promise).await?.into();
Ok(Objects { inner })
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Include {
HttpMetadata,
CustomMetadata,
}
macro_rules! js_object {
{$($key: expr => $value: expr),* $(,)?} => {{
let obj = JsObject::new();
$(
{
let res = ::js_sys::Reflect::set(&obj, &JsString::from($key), &JsValue::from($value));
debug_assert!(res.is_ok(), "setting properties should never fail on our dictionary objects");
}
)*
obj
}};
}
pub(crate) use js_object;