walr/
checkpoint.rs

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
// Authors: Robert Lopez

use crate::{
    error::Error,
    util::{
        encode::serialize,
        fs::{rename, write_file},
    },
    WAL,
};
use serde::{Deserialize, Serialize};

impl<Log, State> WAL<Log, State>
where
    Log: Serialize + for<'a> Deserialize<'a>,
    State: Default + Serialize + for<'a> Deserialize<'a>,
{
    /// Returns if over or equal to max size and should call the
    /// `checkpoint` method
    ///
    /// ---
    /// Example Usage:
    /// ```
    ///
    /// let mut wal: WAL::<TreeLog, Tree> = ...;
    /// let tree: Tree = ...;
    ///
    /// if wal.should_checkpoint() {
    ///     wal.checkpoint(&tree).await?;
    /// }
    /// ```
    pub fn should_checkpoint(&self) -> bool {
        self.size >= self.options.max_size
    }

    /// Checkpoints the current state of the persisted data to
    /// disk, then truncates the WAL to 0
    ///
    /// ---
    /// Example Usage:
    /// ```
    ///
    /// let mut wal: WAL::<TreeLog, Tree> = ...;
    /// let tree: Tree = ...;
    ///
    /// if wal.should_checkpoint() {
    ///     wal.checkpoint(&tree).await?;
    /// }
    /// ```
    pub async fn checkpoint(&mut self, state: &State) -> Result<(), Error> {
        write_file(&self.temporary_checkpoint_path, &serialize(state)?).await?;
        rename(&self.temporary_checkpoint_path, &self.checkpoint_path).await?;

        self.truncate(0).await?;

        Ok(())
    }
}