Skip to main content

link_cli/engine/lsm/native/
mod.rs

1//! Selected exclusive native directory, independent of SQL or a coordinator.
2mod device;
3mod directory;
4#[cfg(test)]
5mod fault_tests;
6mod files;
7#[cfg(test)]
8mod open_tests;
9#[cfg(test)]
10mod process_tests;
11mod read_only;
12#[cfg(test)]
13mod read_only_tests;
14#[cfg(test)]
15mod test_support;
16use super::{invalid, LsmStoreOptions, PhysicalLsmJournalStore};
17use crate::engine::{
18    cluster::{AtomicJournalStore, JournalVersion},
19    maintenance::{JournalMaintenanceStore, JournalNamespaceEntry, JournalScanOptions},
20    paged::CheckpointPagedLog,
21};
22use crate::{LinkError, ReplaceableTransitionLogStore, TransitionLogStore};
23use device::Device;
24use files::{Files, Namespace};
25use std::{
26    path::Path,
27    sync::{Arc, Mutex},
28};
29
30/// Fixed mirror modes and finite resource bounds, checked before filesystem I/O.
31#[derive(Clone, Copy, Debug)]
32pub struct FileLsmOptions {
33    pub store: LsmStoreOptions,
34    pub max_pages: u64,
35    pub mirrored_root: bool,
36    pub mirrored_banks: bool,
37    pub mirrored_tables: bool,
38}
39impl Default for FileLsmOptions {
40    fn default() -> Self {
41        Self {
42            store: LsmStoreOptions::default(),
43            max_pages: 16_384,
44            mirrored_root: false,
45            mirrored_banks: false,
46            mirrored_tables: false,
47        }
48    }
49}
50type Store = PhysicalLsmJournalStore<CheckpointPagedLog<Device, Device>, Namespace>;
51/// Owns `.lsm-writer` before bounded discovery and all child leases. Complete
52/// read-only physical/semantic validation precedes constructor repair effects.
53/// Close attempts all children before removing the outer fence. An uncertain
54/// raw close is cached rather than retried. Never steals crashed ownership.
55/// Windows supports file-content sync but advertises no durable namespace.
56pub struct FileLsmJournalStore {
57    inner: Option<Store>,
58    files: Arc<Mutex<Files>>,
59}
60struct ReadOnlyWal(Vec<String>);
61impl TransitionLogStore for ReadOnlyWal {
62    fn supports_durable_flush(&self) -> bool {
63        false
64    }
65    fn read_log_entries(&mut self) -> Result<Vec<String>, LinkError> {
66        Ok(self.0.clone())
67    }
68    fn append_log_entry(&mut self, _: &str) -> Result<(), LinkError> {
69        Err(invalid("read-only native LSM WAL"))
70    }
71    fn flush_log(&mut self) -> Result<(), LinkError> {
72        Err(invalid("read-only native LSM WAL"))
73    }
74}
75impl ReplaceableTransitionLogStore for ReadOnlyWal {
76    fn supports_replacement(&self) -> bool {
77        true
78    }
79    fn replace_log_entries(&mut self, _: &[String]) -> Result<bool, LinkError> {
80        Err(invalid("read-only native LSM WAL"))
81    }
82}
83impl FileLsmJournalStore {
84    pub fn open(directory: impl AsRef<Path>, options: FileLsmOptions) -> Result<Self, LinkError> {
85        options.store.limits.validate()?;
86        if !(1..=65_536).contains(&options.max_pages)
87            || !(2..=65_536).contains(&options.store.max_namespace_entries)
88        {
89            return Err(invalid("native LSM admission bounds"));
90        }
91        let files = Arc::new(Mutex::new(Files::new(directory.as_ref(), options)?));
92        let build = (|| {
93            let records = {
94                let mut files = files
95                    .lock()
96                    .map_err(|_| invalid("native LSM discovery mutex poisoned"))?;
97                let names = files.list(options.store.max_namespace_entries)?;
98                let (mut root, mut banks) = files.wal(true)?;
99                let records =
100                    CheckpointPagedLog::inspect(&mut root, &mut banks, options.max_pages)?;
101                if records.is_empty() && !names.is_empty() {
102                    return Err(invalid(
103                        "uninitialized native LSM namespace contains tables",
104                    ));
105                }
106                records
107            };
108            if !records.is_empty() {
109                let mut validation = PhysicalLsmJournalStore::open(
110                    ReadOnlyWal(records),
111                    Namespace {
112                        files: files.clone(),
113                        read_only: true,
114                    },
115                    options.store,
116                )?;
117                validation.close()?;
118            }
119            let (root, banks) = {
120                let mut files = files
121                    .lock()
122                    .map_err(|_| invalid("native LSM discovery mutex poisoned"))?;
123                files.close_readers()?;
124                files.wal(false)?
125            };
126            let wal = CheckpointPagedLog::with_max_pages(root, banks, options.max_pages)?;
127            PhysicalLsmJournalStore::open(
128                wal,
129                Namespace {
130                    files: files.clone(),
131                    read_only: false,
132                },
133                options.store,
134            )
135        })();
136        match build {
137            Ok(inner) => Ok(Self {
138                inner: Some(inner),
139                files,
140            }),
141            Err(cause) => {
142                let cleanup = files
143                    .lock()
144                    .map_err(|_| invalid("native LSM cleanup mutex poisoned"))?
145                    .close(Vec::new());
146                match cleanup {
147                    Ok(()) => Err(cause),
148                    Err(cleanup) => Err(invalid(&format!("{cause}; native cleanup: {cleanup}"))),
149                }
150            }
151        }
152    }
153    fn store(&mut self) -> Result<&mut Store, LinkError> {
154        self.inner
155            .as_mut()
156            .ok_or_else(|| invalid("closed native LSM store"))
157    }
158    pub fn flush(&mut self) -> Result<(), LinkError> {
159        self.store()?.flush()
160    }
161    pub fn compact(&mut self) -> Result<(), LinkError> {
162        self.store()?.compact()
163    }
164    /// Does not flush implicitly; successful CAS already acknowledges the WAL.
165    pub fn close(&mut self) -> Result<(), LinkError> {
166        let mut errors = Vec::new();
167        if let Some(mut store) = self.inner.take() {
168            if let Err(error) = store.close() {
169                errors.push(error.to_string());
170            }
171        }
172        self.files
173            .lock()
174            .map_err(|_| invalid("native LSM cleanup mutex poisoned"))?
175            .close(errors)
176    }
177}
178impl Drop for FileLsmJournalStore {
179    fn drop(&mut self) {
180        let _ = self.close();
181    }
182}
183impl AtomicJournalStore for FileLsmJournalStore {
184    fn supports_durable_flush(&self) -> bool {
185        self.inner
186            .as_ref()
187            .is_some_and(AtomicJournalStore::supports_durable_flush)
188    }
189    fn read(&mut self, keys: &[String]) -> Result<Vec<JournalVersion>, LinkError> {
190        self.store()?.read(keys)
191    }
192    fn compare_exchange(
193        &mut self,
194        keys: &[String],
195        expected: &[JournalVersion],
196        updates: &[Option<Vec<String>>],
197    ) -> Result<bool, LinkError> {
198        self.store()?.compare_exchange(keys, expected, updates)
199    }
200}
201impl JournalMaintenanceStore for FileLsmJournalStore {
202    fn scan_namespace(
203        &mut self,
204        options: JournalScanOptions,
205    ) -> Result<Vec<JournalNamespaceEntry>, LinkError> {
206        self.store()?.scan_namespace(options)
207    }
208    fn compare_delete(&mut self, key: &str, expected: u64) -> Result<bool, LinkError> {
209        self.store()?.compare_delete(key, expected)
210    }
211}