1
use std::{fmt::Debug, sync::Arc};
2

            
3
use parking_lot::{Mutex, MutexGuard, RwLock};
4

            
5
use crate::chunk_cache::AnySendSync;
6

            
7
/// The current state of a tree file. Must be initialized before passing to
8
/// `TreeFile::new` if the file already exists.
9
85552
#[derive(Clone, Debug)]
10
#[must_use]
11
pub struct State<Root: super::Root> {
12
    reader: Arc<RwLock<Arc<ActiveState<Root>>>>,
13
    writer: Arc<Mutex<ActiveState<Root>>>,
14
}
15

            
16
impl<Root> State<Root>
17
where
18
    Root: super::Root,
19
{
20
    /// Returns an uninitialized state.
21
10154
    pub fn new(file_id: Option<u64>, max_order: Option<usize>, root: Root) -> Self {
22
10154
        let state = ActiveState {
23
10154
            file_id,
24
10154
            max_order,
25
10154
            current_position: 0,
26
10154
            root,
27
10154
        };
28
10154

            
29
10154
        Self {
30
10154
            reader: Arc::new(RwLock::new(Arc::new(state.clone()))),
31
10154
            writer: Arc::new(Mutex::new(state)),
32
10154
        }
33
10154
    }
34
    /// Returns an initialized state. This should only be used if you're
35
    /// creating a file from scratch.
36
    pub fn initialized(file_id: Option<u64>, max_order: Option<usize>, mut root: Root) -> Self {
37
        root.initialize_default();
38
        let state = ActiveState {
39
            file_id,
40
            max_order,
41
            current_position: 0,
42
            root,
43
        };
44

            
45
        Self {
46
            reader: Arc::new(RwLock::new(Arc::new(state.clone()))),
47
            writer: Arc::new(Mutex::new(state)),
48
        }
49
    }
50

            
51
    /// Locks the state for writing.
52
139067
    pub fn lock(&self) -> MutexGuard<'_, ActiveState<Root>> {
53
139067
        self.writer.lock()
54
139067
    }
55

            
56
    /// Reads the current state.
57
    #[must_use]
58
140960
    pub fn read(&self) -> Arc<ActiveState<Root>> {
59
140960
        let reader = self.reader.read();
60
140960
        reader.clone()
61
140960
    }
62
}
63

            
64
impl<Root> Default for State<Root>
65
where
66
    Root: super::Root + Default,
67
{
68
2042
    fn default() -> Self {
69
2042
        Self::new(None, None, Root::default())
70
2042
    }
71
}
72

            
73
pub trait AnyTreeState: AnySendSync + Debug {
74
    fn cloned(&self) -> Box<dyn AnyTreeState>;
75
    fn publish(&self);
76
}
77

            
78
impl<Root: super::Root> AnyTreeState for State<Root> {
79
24614
    fn cloned(&self) -> Box<dyn AnyTreeState> {
80
24614
        Box::new(self.clone())
81
24614
    }
82

            
83
24592
    fn publish(&self) {
84
24592
        let state = self.lock();
85
24592
        state.publish(self);
86
24592
    }
87
}
88

            
89
/// An active state for a tree file.
90
63877
#[derive(Clone, Debug, Default)]
91
pub struct ActiveState<Root: super::Root> {
92
    /// The current file id associated with this tree file. Database compaction
93
    /// will cause the file_id to be changed once the operation succeeds.
94
    pub file_id: Option<u64>,
95
    /// The current location within the file for data to be written.
96
    pub current_position: u64,
97
    /// The root of the B-Tree.
98
    pub root: Root,
99
    /// The maximum "order" of the B-Tree. This controls the maximum number of
100
    /// children any node in the tree may contain. Nebari will automatically
101
    /// scale up to this number as the database grows.
102
    pub max_order: Option<usize>,
103
}
104

            
105
impl<Root> ActiveState<Root>
106
where
107
    Root: super::Root,
108
{
109
    /// Returns true if the state has been initialized.
110
56586
    pub fn initialized(&self) -> bool {
111
56586
        self.root.initialized()
112
56586
    }
113

            
114
53723
    pub(crate) fn publish(&self, state: &State<Root>) {
115
53723
        let mut reader = state.reader.write();
116
53723
        *reader = Arc::new(self.clone());
117
53723
    }
118

            
119
3
    pub(crate) fn rollback(&mut self, state: &State<Root>) {
120
3
        let reader = state.reader.read();
121
3
        self.root = reader.root.clone();
122
3
    }
123
}