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
use std::{
    collections::VecDeque,
    fs::File,
    io::{Read, Write},
    path::PathBuf,
};

use massa_models::slot::Slot;
use rocksdb::{DBCompressionType, Options};

/// A trait that defines the interface for a storage backend for the dump-block
/// feature.
pub trait StorageBackend: Send + Sync {
    /// Writes the given value to the storage backend.
    /// The slot is used as the key to the value.
    fn write(&mut self, slot: &Slot, value: &[u8]);

    /// Reads the value from the storage backend.
    /// The slot is used as the key to the value.
    fn read(&self, slot: &Slot) -> Option<Vec<u8>>;
}

/// A storage backend that uses the file system as the underlying storage engine.
pub struct FileStorageBackend {
    folder: PathBuf,
    slots_saved: VecDeque<Slot>,
    max_blocks: u64,
}
impl FileStorageBackend {
    /// Creates a new instance of `FileStorageBackend` with the given path.
    pub fn new(path: PathBuf, max_blocks: u64) -> Self {
        Self {
            folder: path,
            slots_saved: VecDeque::new(),
            max_blocks,
        }
    }
}

impl StorageBackend for FileStorageBackend {
    fn write(&mut self, slot: &Slot, value: &[u8]) {
        if self.slots_saved.len() >= self.max_blocks as usize {
            let slot_to_remove = self.slots_saved.pop_front().unwrap();
            let block_file_path = self.folder.join(format!(
                "block_slot_{}_{}.bin",
                slot_to_remove.thread, slot_to_remove.period
            ));
            std::fs::remove_file(block_file_path).expect("Unable to delete block from disk");
        }
        let block_file_path = self
            .folder
            .join(format!("block_slot_{}_{}.bin", slot.thread, slot.period));

        let mut file = File::create(block_file_path.clone())
            .unwrap_or_else(|_| panic!("Cannot create file: {:?}", block_file_path));

        file.write_all(value).expect("Unable to write to disk");
        self.slots_saved.push_back(*slot);
    }

    fn read(&self, slot: &Slot) -> Option<Vec<u8>> {
        let block_file_path = self
            .folder
            .join(format!("block_slot_{}_{}.bin", slot.thread, slot.period));

        let file = File::open(block_file_path.clone())
            .unwrap_or_else(|_| panic!("Cannot open file: {:?}", block_file_path));
        let mut reader = std::io::BufReader::new(file);
        let mut buffer = Vec::new();
        reader
            .read_to_end(&mut buffer)
            .expect("Unable to read from disk");

        Some(buffer)
    }
}

/// A storage backend that uses RocksDB as the underlying storage engine.
pub struct RocksDBStorageBackend {
    db: rocksdb::DB,
    slots_saved: VecDeque<Slot>,
    max_blocks: u64,
}

impl RocksDBStorageBackend {
    /// Creates a new instance of `RocksDBStorageBackend` with the given path.
    pub fn new(path: PathBuf, max_blocks: u64) -> Self {
        let mut opts = Options::default();
        opts.create_if_missing(true);
        opts.set_compression_type(DBCompressionType::Lz4);

        let db = rocksdb::DB::open(&opts, path.clone())
            .unwrap_or_else(|_| panic!("Failed to create storage db at {:?}", path));

        Self {
            db,
            slots_saved: VecDeque::new(),
            max_blocks,
        }
    }
}

impl StorageBackend for RocksDBStorageBackend {
    fn write(&mut self, slot: &Slot, value: &[u8]) {
        if self.slots_saved.len() >= self.max_blocks as usize {
            let slot_to_remove = self.slots_saved.pop_front().unwrap();
            self.db
                .delete(slot_to_remove.to_bytes_key())
                .expect("Unable to delete block from db");
        }
        self.db
            .put(slot.to_bytes_key(), value)
            .expect("Unable to write block to db");
        self.slots_saved.push_back(*slot);
    }

    fn read(&self, slot: &Slot) -> Option<Vec<u8>> {
        match self.db.get(slot.to_bytes_key()) {
            Ok(val) => val,
            Err(e) => {
                println!("Error: {} reading key {:?}", e, slot.to_bytes_key());
                None
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_file_storage_backend() {
        let slot = Slot {
            thread: 1,
            period: 1,
        };
        let value = vec![1, 2, 3];

        let mut storage = FileStorageBackend::new(PathBuf::from(""), 100);
        storage.write(&slot, &value);

        let storage = FileStorageBackend::new(PathBuf::from(""), 100);
        let data = storage.read(&slot);
        assert_eq!(data, Some(value));
    }

    #[test]
    fn test_rocksdb_storage_backend() {
        let slot = Slot {
            thread: 1,
            period: 1,
        };
        let slot_2 = Slot {
            thread: 1,
            period: 2,
        };
        let slot_3 = Slot {
            thread: 1,
            period: 3,
        };
        let value = vec![1, 2, 3];

        let mut storage = RocksDBStorageBackend::new(PathBuf::from("test_db"), 2);
        storage.write(&slot, &value);
        storage.write(&slot_2, &value);
        storage.write(&slot_3, &value);
        drop(storage);

        let storage = RocksDBStorageBackend::new(PathBuf::from("test_db"), 2);
        let data = storage.read(&slot);
        assert_eq!(data, None);
        let data = storage.read(&slot_2);
        assert_eq!(data, Some(value.clone()));
        let data = storage.read(&slot_3);
        assert_eq!(data, Some(value.clone()));
    }
}