aboutsummaryrefslogtreecommitdiff
path: root/src/server/storage/backend/disk.rs
blob: 313737653a098b335ba80e3760ccfe85c3c4ea27 (plain)
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
use super::StorageBackend;
use crate::server::blobref::BlobRef;
use crate::server::storage::{Error, Result};
use log::debug;
use serde::{Deserialize, Serialize};
use std::{fs, io::ErrorKind, path::PathBuf};

pub struct Disk {
    bucket: String,
    pub root: PathBuf,
}

#[derive(Serialize, Deserialize)]
pub struct Config {
    pub root: PathBuf,
}

impl StorageBackend for Disk {
    type Config = Config;

    fn new(bucket: &str, config: &Self::Config) -> Self {
        Self {
            bucket: bucket.to_string(),
            root: config.root.clone().join(bucket),
        }
    }

    fn put(&self, data: &[u8]) -> Result<BlobRef> {
        let blobref = BlobRef::for_bytes(data);
        debug!("Preparing {blobref}");

        if !self.exists(&blobref) {
            let blobpath = self.root.join(blobref.path());
            let blobdir = blobpath.parent().expect("blobpath should have a parent");
            debug!("Writing blob to {blobpath:?}");

            fs::create_dir_all(blobdir).map_err(|_| Error::Io)?;
            fs::write(blobpath, data).map_err(|_| Error::Io)?;
        }

        Ok(blobref)
    }

    fn get(&self, blobref: &BlobRef) -> Result<Option<Vec<u8>>> {
        let blobpath = self.root.join(blobref.path());

        match fs::read(blobpath) {
            Ok(contents) => Ok(Some(contents)),
            Err(e) if e.kind() == ErrorKind::NotFound => Ok(None),
            Err(e) => Err(Error::Io),
        }
    }

    fn exists(&self, blobref: &BlobRef) -> bool {
        self.root.join(blobref.path()).exists()
    }
}

impl Iterator for Disk {
    type Item = BlobRef;

    fn next(&mut self) -> Option<Self::Item> {
        todo!()
    }
}