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
use std::collections::HashMap;
use std::fmt::Formatter;
use std::io;
use std::ops::Bound;
use std::path::Path;
use std::sync::Arc;
use std::{fmt, fs};

use anyhow::Result;

use async_trait::async_trait;

use bytes::Bytes;

use futures::Stream;

use serde::{Deserialize, Serialize};
use time::OffsetDateTime;

fn file_to_base64<P: AsRef<Path>>(path: P) -> Result<String> {
    Ok(base64::encode(fs::read(path.as_ref())?))
}

#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct CertificateInfo {
    pub certificate_b64: String,
    pub private_key_b64: String,
}

impl CertificateInfo {
    pub fn from_path<P: AsRef<Path>, Q: AsRef<Path>>(
        certificate_path: P,
        private_key_path: Q,
    ) -> Result<CertificateInfo> {
        Ok(Self {
            certificate_b64: file_to_base64(certificate_path)?,
            private_key_b64: file_to_base64(private_key_path)?,
        })
    }
}

/// Metadata accepted when indexing a blob.
#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct BlobMetaRequest {
    /// The key/value pairs for this blob.
    pub fields: HashMap<String, FieldValue>,

    /// The tags for this blob.
    pub tags: Vec<String>,
}

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

    #[must_use]
    pub fn with_field<S: Into<String>, T: Into<FieldValue>>(mut self, key: S, value: T) -> Self {
        self.fields.insert(key.into(), value.into());
        self
    }

    #[must_use]
    pub fn with_tag<S: Into<String>>(mut self, s: S) -> Self {
        self.tags.push(s.into());
        self
    }

    pub fn into_meta(
        self,
        created_at: OffsetDateTime,
        modified_at: OffsetDateTime,
        size: u64,
    ) -> BlobMeta {
        BlobMeta {
            fields: self.fields,
            tags: self.tags,
            size,
            created_at,
            modified_at,
        }
    }
}

#[derive(Clone, Debug, Deserialize, Hash, Serialize, PartialEq, Eq)]
#[serde(untagged)]
pub enum FieldValue {
    Str(String),
    Numeric(i64),
}

#[derive(Clone, Debug, Deserialize, Hash, Serialize, PartialEq, Eq)]
pub enum TaggedFieldValue {
    Str(String),
    Numeric(i64),
}

impl From<FieldValue> for TaggedFieldValue {
    fn from(v: FieldValue) -> Self {
        match v {
            FieldValue::Str(s) => TaggedFieldValue::Str(s),
            FieldValue::Numeric(i) => TaggedFieldValue::Numeric(i),
        }
    }
}

impl From<TaggedFieldValue> for FieldValue {
    fn from(v: TaggedFieldValue) -> Self {
        match v {
            TaggedFieldValue::Str(s) => FieldValue::Str(s),
            TaggedFieldValue::Numeric(i) => FieldValue::Numeric(i),
        }
    }
}

impl From<String> for FieldValue {
    fn from(v: String) -> Self {
        Self::Str(v)
    }
}

impl From<&str> for FieldValue {
    fn from(v: &str) -> Self {
        Self::Str(String::from(v))
    }
}

impl From<&String> for FieldValue {
    fn from(v: &String) -> Self {
        Self::Str(String::from(v))
    }
}

impl From<i64> for FieldValue {
    fn from(v: i64) -> Self {
        Self::Numeric(v)
    }
}

impl fmt::Display for FieldValue {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            Self::Str(s) => write!(f, "\"{}\"", s),
            Self::Numeric(i) => write!(f, "{}", i),
        }
    }
}

/// Metadata associated with a blob.
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct BlobMeta {
    /// The key/value pairs for this blob.
    pub fields: HashMap<String, FieldValue>,

    /// The tags for this blob.
    pub tags: Vec<String>,

    /// This blob's size, in bytes.
    pub size: u64,

    /// This blob's creation time.
    #[serde(with = "time::serde::rfc3339")]
    pub created_at: OffsetDateTime,

    /// This blob's last modified time.
    #[serde(with = "time::serde::rfc3339")]
    pub modified_at: OffsetDateTime,
}

impl From<BlobMeta> for BlobMetaRequest {
    fn from(m: BlobMeta) -> Self {
        Self {
            fields: m.fields,
            tags: m.tags,
        }
    }
}

impl Default for BlobMeta {
    fn default() -> Self {
        Self {
            fields: Default::default(),
            tags: Default::default(),
            size: 0,
            created_at: OffsetDateTime::now_utc(),
            modified_at: OffsetDateTime::now_utc(),
        }
    }
}

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

    #[must_use]
    pub fn with_field<S: Into<String>, T: Into<FieldValue>>(mut self, key: S, value: T) -> Self {
        self.fields.insert(key.into(), value.into());
        self
    }

    #[must_use]
    pub fn with_tag<S: Into<String>>(mut self, s: S) -> Self {
        self.tags.push(s.into());
        self
    }

    #[must_use]
    pub fn with_size(mut self, size: u64) -> Self {
        self.size = size;
        self
    }
}

/// Tagged version of the metadata associated with a blob.
///
/// This is used to persist the metadata in the sled tree.
/// bincode doesn't like untagged enums, so we have to make a tagged alternative.
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct TaggedBlobMeta {
    /// The key/value pairs for this blob.
    pub fields: HashMap<String, TaggedFieldValue>,

    /// The tags for this blob.
    pub tags: Vec<String>,

    /// This blob's size, in bytes.
    pub size: u64,

    /// This blob's creation time.
    #[serde(with = "crate::timestamp_nanos")]
    pub created_at: OffsetDateTime,

    /// This blob's last modified time.
    #[serde(with = "crate::timestamp_nanos")]
    pub modified_at: OffsetDateTime,
}

impl From<BlobMeta> for TaggedBlobMeta {
    fn from(m: BlobMeta) -> Self {
        Self {
            fields: m
                .fields
                .into_iter()
                .map(|(k, v)| (k, v.into()))
                .collect::<HashMap<_, _>>(),
            tags: m.tags,
            size: m.size,
            created_at: m.created_at,
            modified_at: m.modified_at,
        }
    }
}

impl From<TaggedBlobMeta> for BlobMeta {
    fn from(m: TaggedBlobMeta) -> Self {
        Self {
            fields: m
                .fields
                .into_iter()
                .map(|(k, v)| (k, v.into()))
                .collect::<HashMap<_, _>>(),
            tags: m.tags,
            size: m.size,
            created_at: m.created_at,
            modified_at: m.modified_at,
        }
    }
}

#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct BlobInfoRequest {
    pub meta_request: BlobMetaRequest,
    pub owner: String,
    pub size: u64,
}

impl BlobInfoRequest {
    pub fn into_blob_info(
        self,
        created_at: OffsetDateTime,
        modified_at: OffsetDateTime,
    ) -> BlobInfo {
        BlobInfo {
            meta: self
                .meta_request
                .into_meta(created_at, modified_at, self.size),
            owner: self.owner,
        }
    }
}

#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct BlobInfo {
    pub meta: BlobMeta,
    pub owner: String,
}

#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct TaggedBlobInfo {
    pub meta: TaggedBlobMeta,
    pub owner: String,
}

impl From<BlobInfo> for TaggedBlobInfo {
    fn from(v: BlobInfo) -> Self {
        Self {
            meta: v.meta.into(),
            owner: v.owner,
        }
    }
}

impl From<TaggedBlobInfo> for BlobInfo {
    fn from(v: TaggedBlobInfo) -> Self {
        Self {
            meta: v.meta.into(),
            owner: v.owner,
        }
    }
}

pub struct Blob {
    pub stream: Box<dyn Stream<Item = Result<Bytes, io::Error>> + Send>,
    pub current_chunk_size: u64,
    pub total_blob_size: u64,
    pub info: BlobInfo,
}

#[async_trait]
pub trait StorageNode {
    async fn put(
        &self,
        id: String,
        info: BlobInfoRequest,
        stream: Option<Box<dyn Stream<Item = Result<Bytes, io::Error>> + Send + Sync + Unpin>>,
    ) -> Result<()>;

    async fn write(
        &self,
        id: String,
        range: (Bound<u64>, Bound<u64>),
        bytes: Bytes,
        username: &str,
    ) -> Result<()>;

    async fn get(&self, blob_id: String, range: Option<(Bound<u64>, Bound<u64>)>) -> Result<Blob>;

    async fn update_meta(&self, blob_id: String, info: BlobInfoRequest) -> Result<()>;

    async fn delete(&self, blob_id: String, username: &str) -> Result<()>;

    async fn get_certificates(&self) -> Option<CertificateInfo>;

    async fn fsync(&self, blob_id: String, username: &str) -> Result<()>;

    async fn flush(&self) -> Result<()>;
}

pub type DynStorageNode = Arc<dyn StorageNode + Send + Sync>;