spacedb 0.1.2

A cryptographically verifiable data store and universal accumulator for the Spaces protocol.
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
// Uses flock on Unix and LockFile on Windows to ensure exclusive access to the database file.
// based on https://github.com/cberner/redb/tree/master/src/tree_store/page_store/file_backend
use crate::{
    db::{CHUNK_SIZE, EMPTY_RECORD, Record, SavePoint},
    node::Node,
};
use bincode::config;
use std::{
    fs::File,
    io,
    ops::{Index, IndexMut, RangeFrom},
    sync::*,
};

pub trait StorageBackend: Sync + Send {
    fn len(&self) -> Result<u64, io::Error>;
    fn is_empty(&self) -> Result<bool, io::Error> {
        Ok(self.len()? == 0)
    }
    fn set_len(&self, len: u64) -> Result<(), io::Error>;
    fn read(&self, offset: u64, len: usize) -> Result<Vec<u8>, io::Error>;
    fn sync_data(&self) -> Result<(), io::Error>;
    fn write(&self, offset: u64, data: &[u8]) -> Result<(), io::Error>;
}

#[derive(Debug, Default)]
pub struct MemoryBackend(RwLock<Vec<u8>>);

#[cfg(unix)]
use std::os::{fd::AsRawFd, unix::fs::FileExt};

#[cfg(windows)]
use std::os::windows::fs::FileExt;

#[cfg(not(any(windows, unix)))]
use std::sync::Mutex;

#[cfg(any(windows, unix))]
pub struct FileBackend {
    file: File,
    locked: bool,
}

#[cfg(unix)]
impl FileBackend {
    pub fn new(file: File) -> Result<Self, io::Error> {
        let fd = file.as_raw_fd();
        let result = unsafe { libc::flock(fd, libc::LOCK_EX | libc::LOCK_NB) };
        if result != 0 {
            let err = io::Error::last_os_error();
            if err.kind() == io::ErrorKind::WouldBlock {
                Err(io::Error::new(
                    io::ErrorKind::WouldBlock,
                    "Database already open for writing",
                ))
            } else {
                Err(err)
            }
        } else {
            Ok(Self { file, locked: true })
        }
    }

    pub fn read_only(file: File) -> Self {
        Self {
            file,
            locked: false,
        }
    }
}

#[cfg(unix)]
impl Drop for FileBackend {
    fn drop(&mut self) {
        if self.locked {
            unsafe { libc::flock(self.file.as_raw_fd(), libc::LOCK_UN) };
        }
    }
}

#[cfg(unix)]
impl StorageBackend for FileBackend {
    fn len(&self) -> Result<u64, io::Error> {
        Ok(self.file.metadata()?.len())
    }

    fn set_len(&self, len: u64) -> Result<(), io::Error> {
        self.file.set_len(len)
    }

    fn read(&self, offset: u64, len: usize) -> Result<Vec<u8>, io::Error> {
        let mut buffer = vec![0; len];
        self.file.read_exact_at(&mut buffer, offset)?;
        Ok(buffer)
    }

    fn sync_data(&self) -> Result<(), io::Error> {
        self.file.sync_data()
    }

    fn write(&self, offset: u64, data: &[u8]) -> Result<(), io::Error> {
        self.file.write_all_at(data, offset)
    }
}

#[cfg(windows)]
impl FileBackend {
    pub fn new(file: File) -> Result<Self, io::Error> {
        Ok(Self {
            file,
            locked: false,
        })
    }

    pub fn read_only(file: File) -> Self {
        Self {
            file,
            locked: false,
        }
    }
}

#[cfg(windows)]
impl StorageBackend for FileBackend {
    fn set_len(&self, len: u64) -> Result<(), io::Error> {
        self.file.set_len(len)
    }

    fn len(&self) -> Result<u64, io::Error> {
        Ok(self.file.metadata()?.len())
    }

    fn read(&self, mut offset: u64, len: usize) -> Result<Vec<u8>, io::Error> {
        let mut buffer = vec![0; len];
        let mut data_offset = 0;
        while data_offset < buffer.len() {
            let read = self.file.seek_read(&mut buffer[data_offset..], offset)?;
            offset += read as u64;
            data_offset += read;
        }
        Ok(buffer)
    }

    fn sync_data(&self) -> Result<(), io::Error> {
        self.file.sync_data()
    }

    fn write(&self, mut offset: u64, data: &[u8]) -> Result<(), io::Error> {
        let mut data_offset = 0;
        while data_offset < data.len() {
            let written = self.file.seek_write(&data[data_offset..], offset)?;
            offset += written as u64;
            data_offset += written;
        }
        Ok(())
    }
}

// We use a mutex based lock on platforms that don't support flock
#[cfg(not(any(windows, unix)))]
struct FileBackend {
    file: Mutex<File>,
}

#[cfg(not(any(windows, unix)))]
impl FileBackend {
    fn new(file: File) -> Result<Self, DatabaseError> {
        Ok(Self {
            file: Mutex::new(file),
        })
    }
}

#[cfg(not(any(windows, unix)))]
impl StorageBackend for FileBackend {
    fn set_len(&self, len: u64) -> Result<(), io::Error> {
        self.file.lock().unwrap().set_len(len)
    }

    fn len(&self) -> Result<u64, io::Error> {
        Ok(self.file.lock().unwrap().metadata()?.len())
    }

    fn sync_data(&self, eventual: bool) -> Result<(), io::Error> {
        self.file.lock().unwrap().sync_data()
    }

    fn write(&self, offset: u64, data: &[u8]) -> Result<(), io::Error> {
        let file = self.file.lock().unwrap();
        file.seek(SeekFrom::Start(offset))?;
        file.write_all(data)
    }

    fn read(&self, offset: u64, len: usize) -> Result<Vec<u8>, io::Error> {
        let mut result = vec![0; len];
        let file = self.file.lock().unwrap();
        file.seek(SeekFrom::Start(offset))?;
        file.read_exact(&mut result)?;
        Ok(result)
    }
}

impl MemoryBackend {
    fn out_of_range() -> io::Error {
        io::Error::new(io::ErrorKind::InvalidInput, "Index out-of-range.")
    }
}

impl MemoryBackend {
    /// Creates a new, empty memory backend.
    pub fn new() -> Self {
        Self::default()
    }

    /// Gets a read guard for this backend.
    fn read(&self) -> RwLockReadGuard<'_, Vec<u8>> {
        self.0.read().expect("Could not acquire read lock.")
    }

    /// Gets a write guard for this backend.
    fn write(&self) -> RwLockWriteGuard<'_, Vec<u8>> {
        self.0.write().expect("Could not acquire write lock.")
    }
}

impl StorageBackend for MemoryBackend {
    fn len(&self) -> Result<u64, io::Error> {
        Ok(self.read().len() as u64)
    }

    fn set_len(&self, len: u64) -> Result<(), io::Error> {
        let mut guard = self.write();
        let len = usize::try_from(len).map_err(|_| Self::out_of_range())?;
        if guard.len() < len {
            let additional = len - guard.len();
            guard.reserve(additional);
            for _ in 0..additional {
                guard.push(0);
            }
        } else {
            guard.truncate(len);
        }

        Ok(())
    }

    fn read(&self, offset: u64, len: usize) -> Result<Vec<u8>, io::Error> {
        let guard = self.read();
        let offset = usize::try_from(offset).map_err(|_| Self::out_of_range())?;
        if offset + len <= guard.len() {
            Ok(guard[offset..offset + len].to_owned())
        } else {
            Err(Self::out_of_range())
        }
    }

    fn sync_data(&self) -> Result<(), io::Error> {
        Ok(())
    }

    fn write(&self, offset: u64, data: &[u8]) -> Result<(), io::Error> {
        let mut guard = self.write();
        let offset = usize::try_from(offset).map_err(|_| Self::out_of_range())?;
        if offset + data.len() <= guard.len() {
            guard[offset..offset + data.len()].copy_from_slice(data);
            Ok(())
        } else {
            Err(Self::out_of_range())
        }
    }
}

// Callers hold `Arc<Box<dyn StorageBackend>>`; borrowing through the `Box`
// avoids forcing an extra manual deref at each call site.
#[allow(clippy::borrowed_box)]
pub struct WriteBuffer<'file, const SIZE: usize> {
    file: &'file Box<dyn StorageBackend>,
    buffer: Box<[u8; SIZE]>,
    len: usize,
    file_len: u64,
}

impl<'file, const SIZE: usize> WriteBuffer<'file, SIZE> {
    #[allow(clippy::borrowed_box)]
    pub(crate) fn new(file: &'file Box<dyn StorageBackend>, file_len: u64) -> Self {
        Self {
            file,
            buffer: Box::new([0u8; SIZE]),
            len: 0,
            file_len,
        }
    }

    fn remaining(&self) -> usize {
        SIZE - self.len
    }

    fn tail(&mut self) -> &mut [u8] {
        &mut self.buffer[self.len..]
    }

    pub(crate) fn flush(&mut self) -> Result<(), io::Error> {
        if self.len == 0 {
            return Ok(());
        }

        let aligned_len = self.len - (self.len % CHUNK_SIZE as usize);

        // Write all full pages in one go, if any
        if aligned_len > 0 {
            self.file.set_len(self.file_len + aligned_len as u64)?;
            self.file
                .write(self.file_len, &self.buffer[0..aligned_len])?;
            self.file_len += aligned_len as u64;
        }

        // Handle the remaining data and pad to a full page
        if aligned_len < self.len {
            let remaining_len = self.len - aligned_len;
            self.buffer.copy_within(aligned_len..self.len, 0);
            self.buffer[remaining_len..CHUNK_SIZE as usize].fill(0);

            self.file.set_len(self.file_len + CHUNK_SIZE)?;
            self.file
                .write(self.file_len, &self.buffer[0..CHUNK_SIZE as usize])?;
            self.file_len += CHUNK_SIZE;
        }

        self.len = 0;
        Ok(())
    }

    pub fn write_save_point(&mut self, save_point: &SavePoint) -> Result<Record, io::Error> {
        let config = config::standard();
        let size = bincode::encode_into_slice(save_point, self.tail(), config)
            .map_err(|e| io::Error::other(format!("Failed to encode save point: {}", e)))?;
        let record = Record {
            offset: self.file_len + self.len as u64,
            size: size as u32,
        };

        self.len += size;
        Ok(record)
    }

    pub fn write_node(&mut self, node: &mut Node) -> Result<Record, io::Error> {
        if self.remaining() < node.mem_size() {
            self.flush()?;
        }

        let config = config::standard();

        if node.inner.is_none() {
            if node.id != EMPTY_RECORD {
                return Ok(node.id);
            }
            return Err(io::Error::new(io::ErrorKind::NotFound, "Node not found"));
        }

        let size = {
            let inner = node.inner.as_mut().unwrap();
            bincode::encode_into_slice(inner, self.tail(), config)
                .map_err(|e| io::Error::other(format!("Failed to encode node: {}", e)))?
        };

        let node_id = Record {
            offset: self.file_len + self.len as u64,
            size: size as u32,
        };

        self.len += size;
        Ok(node_id)
    }
}

impl<'file, const SIZE: usize> Index<usize> for WriteBuffer<'file, SIZE> {
    type Output = u8;

    fn index(&self, index: usize) -> &Self::Output {
        &self.buffer[index]
    }
}

impl<'file, const SIZE: usize> Index<std::ops::Range<usize>> for WriteBuffer<'file, SIZE> {
    type Output = [u8];

    fn index(&self, range: std::ops::Range<usize>) -> &Self::Output {
        &self.buffer[range]
    }
}

impl<'file, const SIZE: usize> IndexMut<usize> for WriteBuffer<'file, SIZE> {
    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
        &mut self.buffer[index]
    }
}

impl<'file, const SIZE: usize> IndexMut<std::ops::Range<usize>> for WriteBuffer<'file, SIZE> {
    fn index_mut(&mut self, range: std::ops::Range<usize>) -> &mut Self::Output {
        &mut self.buffer[range]
    }
}

impl<'file, const SIZE: usize> Index<RangeFrom<usize>> for WriteBuffer<'file, SIZE> {
    type Output = [u8];

    fn index(&self, range: RangeFrom<usize>) -> &Self::Output {
        &self.buffer[range]
    }
}

impl<'file, const SIZE: usize> IndexMut<RangeFrom<usize>> for WriteBuffer<'file, SIZE> {
    fn index_mut(&mut self, range: RangeFrom<usize>) -> &mut Self::Output {
        &mut self.buffer[range]
    }
}