objstore 0.1.0-alpha.1

Core objstore crate: common traits, types, and APIs used by storage backend implementations.
Documentation
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
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
use std::collections::HashMap;

use bytes::Bytes;
use time::OffsetDateTime;

/// Byte stream.
pub type ValueStream = futures::stream::BoxStream<'static, Result<Bytes, anyhow::Error>>;

/// Stream of key-name pages (as returned by `list_keys`).
pub type KeyStream<'a> = futures::stream::BoxStream<'a, Result<KeyPage, anyhow::Error>>;

/// Stream of metadata pages (as returned by `list`).
pub type MetaStream = futures::stream::BoxStream<'static, Result<ObjectMetaPage, anyhow::Error>>;

/// Object metadata.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct ObjectMeta {
    pub key: String,
    pub etag: Option<String>,
    pub size: Option<u64>,
    pub created_at: Option<OffsetDateTime>,
    pub updated_at: Option<OffsetDateTime>,
    pub hash_md5: Option<[u8; 16]>,
    pub hash_sha256: Option<[u8; 32]>,
    /// Optional MIME content type of the object.
    pub mime_type: Option<String>,

    pub extra: HashMap<String, serde_json::Value>,
}

impl ObjectMeta {
    pub fn new(key: String) -> Self {
        Self {
            key,
            etag: None,
            size: None,
            created_at: None,
            updated_at: None,
            hash_md5: None,
            hash_sha256: None,
            mime_type: None,
            extra: HashMap::new(),
        }
    }

    pub fn key(&self) -> &str {
        &self.key
    }

    /// Round the timestamps to the nearest second.
    ///
    /// Useful for normalizing timestamps due to differing precisions in the backend.
    pub fn round_timestamps_second(&mut self) {
        if let Some(ts) = self.created_at.as_mut()
            && let Ok(new) = ts.replace_millisecond(0)
        {
            *ts = new;
        }
        if let Some(ts) = self.updated_at.as_mut()
            && let Ok(new) = ts.replace_millisecond(0)
        {
            *ts = new;
        }
    }

    /// Round the timestamps to the nearest minute.
    ///
    /// Useful for normalizing timestamps due to differing precisions in the backend.
    pub fn round_timestamps_minute(&mut self) {
        if let Some(ts) = self.created_at.as_mut()
            && let Ok(new1) = ts.replace_millisecond(0)
            && let Ok(new) = new1.replace_minute(0)
        {
            *ts = new;
        }
        if let Some(ts) = self.updated_at.as_mut()
            && let Ok(new) = ts.replace_millisecond(0)
            && let Ok(new) = new.replace_minute(0)
        {
            *ts = new;
        }
    }

    pub fn with_rounded_timestamps_minute(mut self) -> Self {
        self.round_timestamps_minute();
        self
    }
}

#[derive(Clone, Debug)]
pub struct ObjectMetaPage {
    pub items: Vec<ObjectMeta>,
    pub next_cursor: Option<String>,

    pub prefixes: Option<Vec<String>>,
}

#[derive(Clone, Debug)]
pub struct KeyPage {
    pub items: Vec<String>,
    pub next_cursor: Option<String>,
}

#[derive(Clone, Debug, Default)]
pub struct ListArgs {
    prefix: Option<String>,
    limit: Option<u64>,
    cursor: Option<String>,
    delimiter: Option<String>,
}

impl ListArgs {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn prefix(&self) -> Option<&str> {
        self.prefix.as_deref()
    }

    pub fn set_prefix(&mut self, prefix: impl Into<String>) {
        let prefix = prefix.into();
        if !prefix.is_empty() {
            self.prefix = Some(prefix);
        } else {
            self.prefix = None;
        }
    }

    pub fn with_prefix(mut self, prefix: impl Into<String>) -> Self {
        let prefix = prefix.into();
        if !prefix.is_empty() {
            self.prefix = Some(prefix);
        }
        self
    }

    pub fn delimiter(&self) -> Option<&str> {
        self.delimiter.as_deref()
    }

    pub fn set_delimiter(&mut self, delimiter: impl Into<String>) {
        let delimiter = delimiter.into();
        if !delimiter.is_empty() {
            self.delimiter = Some(delimiter);
        } else {
            self.delimiter = None;
        }
    }

    pub fn with_delimiter(mut self, delimiter: impl Into<String>) -> Self {
        self.set_delimiter(delimiter);
        self
    }

    pub fn limit(&self) -> Option<u64> {
        self.limit
    }

    pub fn set_limit(&mut self, limit: u64) {
        if limit > 0 {
            self.limit = Some(limit);
        } else {
            self.limit = None;
        }
    }

    pub fn with_limit(mut self, limit: u64) -> Self {
        self.set_limit(limit);
        self
    }

    pub fn cursor(&self) -> Option<&str> {
        self.cursor.as_deref()
    }

    pub fn with_cursor(mut self, cursor: impl Into<String>) -> Self {
        self.cursor = Some(cursor.into());
        self
    }

    pub fn with_cursor_opt(mut self, cursor: Option<String>) -> Self {
        self.cursor = cursor;
        self
    }
}

pub enum DataSource {
    Data(Bytes),
    Stream(ValueStream),
}

impl std::fmt::Debug for DataSource {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Data(_) => f.write_str("DataSource::Data(...)"),
            Self::Stream(_) => f.write_str("DataSource::Stream(...)"),
        }
    }
}

impl From<Bytes> for DataSource {
    fn from(data: Bytes) -> Self {
        Self::Data(data)
    }
}

impl From<ValueStream> for DataSource {
    fn from(stream: ValueStream) -> Self {
        Self::Stream(stream)
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ObjectMatch {
    Any,
    Items(Vec<String>),
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum MatchValue {
    Any,
    Tags(Vec<String>),
}

impl MatchValue {
    pub fn any() -> Self {
        Self::Any
    }

    pub fn tags(tags: impl IntoIterator<Item = impl Into<String>>) -> Self {
        let mut clean_tags = Vec::new();
        for tag in tags {
            let tag = tag.into();
            if !tag.trim().is_empty() {
                clean_tags.push(tag);
            }
        }
        if clean_tags.is_empty() {
            Self::Any
        } else {
            Self::Tags(clean_tags)
        }
    }

    pub fn is_any(&self) -> bool {
        matches!(self, Self::Any)
    }

    pub fn as_tags(&self) -> Option<&[String]> {
        if let Self::Tags(tags) = self {
            Some(tags)
        } else {
            None
        }
    }
}

#[derive(Clone, Debug, Default)]
#[non_exhaustive]
pub struct Conditions {
    pub if_match: Option<MatchValue>,
    pub if_none_match: Option<MatchValue>,
    pub if_modified_since: Option<OffsetDateTime>,
    pub if_unmodified_since: Option<OffsetDateTime>,
}

impl Conditions {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn if_not_exists(mut self) -> Self {
        self.if_match = Some(MatchValue::Any);
        self
    }

    pub fn if_match_any(mut self) -> Self {
        self.if_match = Some(MatchValue::Any);
        self
    }

    pub fn if_match_tags(mut self, tags: impl IntoIterator<Item = impl Into<String>>) -> Self {
        let mut clean_tags = Vec::<String>::new();
        for tag in tags {
            let tag = tag.into();
            if tag == "*" {
                return self.if_match_any();
            }
            if tag.trim().is_empty() {
                continue; // Skip empty tags
            }

            clean_tags.push(tag);
        }

        if !clean_tags.is_empty() {
            self.if_match = Some(MatchValue::Tags(clean_tags));
        }
        self
    }

    pub fn if_none_match_tags(mut self, tags: impl IntoIterator<Item = impl Into<String>>) -> Self {
        let mut clean_tags = Vec::<String>::new();
        for tag in tags {
            let tag = tag.into();
            if tag == "*" {
                self.if_match = Some(MatchValue::Any);
                return self;
            }
            if tag.trim().is_empty() {
                continue; // Skip empty tags
            }
            clean_tags.push(tag);
        }

        if !clean_tags.is_empty() {
            self.if_none_match = Some(MatchValue::Tags(clean_tags));
        }
        self
    }

    pub fn if_unmodified_since(mut self, value: OffsetDateTime) -> Self {
        self.if_unmodified_since = Some(value);
        self
    }

    pub fn sanitize(&mut self) {
        if let Some(MatchValue::Tags(tags)) = &mut self.if_match {
            tags.retain(|tag| !tag.trim().is_empty());
            let has_any = tags.iter().any(|tag| tag == "*");
            if has_any {
                self.if_match = Some(MatchValue::Any);
            } else if !tags.is_empty() {
                self.if_match = Some(MatchValue::Tags(tags.clone()));
            } else {
                self.if_match = None;
            }
        }

        if let Some(MatchValue::Tags(tags)) = &mut self.if_none_match {
            tags.retain(|tag| !tag.trim().is_empty());
            let has_any = tags.iter().any(|tag| tag == "*");
            if has_any {
                self.if_match = Some(MatchValue::Any);
                self.if_none_match = None;
            } else if !tags.is_empty() {
                self.if_none_match = Some(MatchValue::Tags(tags.clone()));
            } else {
                self.if_none_match = None;
            }
        }
    }
}

#[derive(Debug)]
#[non_exhaustive]
pub struct Put {
    pub key: String,
    pub data: DataSource,
    pub conditions: Conditions,
    /// Optional MIME type to associate with the object.
    pub mime_type: Option<String>,
}

/// Request to copy an object from one key to another.
#[derive(Debug)]
#[non_exhaustive]
pub struct Copy {
    /// Source key to copy from.
    pub source_key: String,
    /// Destination key to copy to.
    pub target_key: String,
    /// Conditions to apply to the copy operation.
    pub conditions: Conditions,
    // TODO: add source/target bucket support?
}

impl Copy {
    /// Create a new copy request from `src` to `dest`.
    pub fn new(src: impl Into<String>, dest: impl Into<String>) -> Self {
        Self {
            source_key: src.into(),
            target_key: dest.into(),
            conditions: Conditions::default(),
        }
    }
}

impl Put {
    pub fn new(key: impl Into<String>, data: impl Into<DataSource>) -> Self {
        Self {
            key: key.into(),
            data: data.into(),
            conditions: Conditions::default(),
            mime_type: None,
        }
    }
}

/// Arguments for generating a download URL for an object.
#[derive(Debug)]
#[non_exhaustive]
pub struct DownloadUrlArgs {
    pub key: String,

    pub valid_for: std::time::Duration,

    pub response_content_type: Option<String>,
    pub response_content_disposition: Option<String>,
    pub response_content_encoding: Option<String>,
    pub response_content_language: Option<String>,
    pub response_cache_control: Option<String>,
}

impl DownloadUrlArgs {
    pub fn new(key: impl Into<String>, valid_for: std::time::Duration) -> Self {
        Self {
            key: key.into(),
            valid_for,
            response_content_type: None,
            response_content_disposition: None,
            response_content_encoding: None,
            response_content_language: None,
            response_cache_control: None,
        }
    }
}