Skip to main content

lora_database/database/
builder.rs

1//! Constructors for [`Database<InMemoryGraph>`] and [`Database<S>`].
2//!
3//! Five public entry points live here:
4//!
5//! * [`Database::in_memory`] — fresh empty in-memory database.
6//! * [`Database::open_with_wal`] — open or create a WAL-backed database.
7//! * [`Database::open_with_wal_snapshots`] — same, with managed snapshots.
8//! * [`Database::open_named`] — open a portable `.loradb` archive.
9//! * [`Database::recover`] — restore from a snapshot then replay the WAL.
10//! * [`Database::new`] / [`Database::from_graph`] — build from a generic store.
11//!
12//! All four WAL paths share the same "install recorder, assemble
13//! Database" tail; that is captured in the private
14//! [`Database::from_graph_with_wal`] helper to keep the public
15//! constructors focused on the recovery decisions specific to each
16//! entry point.
17
18use std::any::Any;
19use std::fs::File;
20use std::io::BufReader;
21use std::path::Path;
22use std::sync::{Arc, Mutex};
23
24use lora_store::{GraphStorage, GraphStorageMut, InMemoryGraph, MutationRecorder};
25use lora_wal::{replay_dir, Lsn, Wal, WalConfig, WalMirror, WalRecorder};
26
27use crate::database::Database;
28use crate::error::{LoraError, LoraErrorCode};
29use crate::live_store::LiveStore;
30use crate::named::{DatabaseName, DatabaseOpenOptions};
31use crate::plan_cache::PlanCache;
32use crate::snapshot::{ManagedSnapshotStore, SnapshotConfig};
33use crate::wal::archive::WalArchive;
34
35use super::replay::replay_into;
36
37impl Database<InMemoryGraph> {
38    /// Convenience constructor: a fresh, empty in-memory graph database.
39    pub fn in_memory() -> Self {
40        Self::from_graph(InMemoryGraph::new())
41    }
42
43    /// Open or create a WAL-enabled in-memory database from a fresh
44    /// graph.
45    ///
46    /// `WalConfig::Disabled` falls back to [`Database::in_memory`].
47    /// Otherwise, opens the WAL directory, replays any committed
48    /// events into a fresh graph, installs a [`WalRecorder`] on the
49    /// graph, and returns a database ready to serve queries.
50    ///
51    /// To restore from a snapshot in addition to the WAL, use
52    /// [`Database::recover`] instead.
53    pub fn open_with_wal(wal_config: WalConfig) -> Result<Self, LoraError> {
54        match wal_config {
55            WalConfig::Disabled => Ok(Self::in_memory()),
56            WalConfig::Enabled {
57                dir,
58                sync_mode,
59                segment_target_bytes,
60            } => {
61                let mut graph = InMemoryGraph::new();
62                let (wal, events) = Wal::open(dir, sync_mode, segment_target_bytes, Lsn::ZERO)?;
63                replay_into(&mut graph, events).map_err(LoraError::from_anyhow)?;
64                let recorder = Arc::new(WalRecorder::new(wal));
65                Ok(Self::from_graph_with_wal(graph, recorder, None))
66            }
67        }
68    }
69
70    /// Open or create a WAL-backed database with managed snapshots beside it.
71    ///
72    /// Recovery loads the newest managed snapshot first, then replays WAL
73    /// records above the snapshot's LSN fence. Checkpoints are written through
74    /// [`Self::checkpoint_managed`] / [`Self::sync`], or automatically when
75    /// `snapshot_config.checkpoint_every_commits` is set.
76    pub fn open_with_wal_snapshots(
77        wal_config: WalConfig,
78        snapshot_config: SnapshotConfig,
79    ) -> Result<Self, LoraError> {
80        let snapshot_store =
81            Arc::new(ManagedSnapshotStore::open(snapshot_config).map_err(LoraError::from_anyhow)?);
82        let mut graph = InMemoryGraph::new();
83
84        match wal_config {
85            WalConfig::Disabled => Err(LoraError::new(
86                LoraErrorCode::Config,
87                "managed snapshots require WAL enabled",
88            )),
89            WalConfig::Enabled {
90                dir,
91                sync_mode,
92                segment_target_bytes,
93            } => {
94                let snapshot_lsn = snapshot_store
95                    .load_latest(&mut graph)
96                    .map_err(LoraError::from_anyhow)?;
97                let (wal, events) = Wal::open(dir, sync_mode, segment_target_bytes, snapshot_lsn)?;
98                replay_into(&mut graph, events).map_err(LoraError::from_anyhow)?;
99                let recorder = Arc::new(WalRecorder::new(wal));
100                Ok(Self::from_graph_with_wal(
101                    graph,
102                    recorder,
103                    Some(snapshot_store),
104                ))
105            }
106        }
107    }
108
109    /// Open or create a named portable database rooted under
110    /// `options.database_dir`.
111    ///
112    /// The database name may be either a portable basename (`app` or
113    /// `app.loradb`) or a safe relative path (`tenant/app`). It is resolved
114    /// under `options.database_dir` before the WAL archive backend opens.
115    pub fn open_named(
116        database_name: impl AsRef<str>,
117        options: DatabaseOpenOptions,
118    ) -> Result<Self, LoraError> {
119        let name = DatabaseName::parse(database_name.as_ref())?;
120        let archive = Arc::new(WalArchive::open(
121            options.database_path_for(&name),
122            options.max_database_bytes,
123        )?);
124        let mut graph = InMemoryGraph::new();
125        let (wal, events) = Wal::open(
126            archive.work_dir(),
127            options.sync_mode,
128            options.segment_target_bytes,
129            Lsn::ZERO,
130        )?;
131        replay_into(&mut graph, events).map_err(LoraError::from_anyhow)?;
132        let mirror: Arc<dyn WalMirror> = archive;
133        let recorder = Arc::new(WalRecorder::new_with_mirror(wal, Some(mirror)));
134        // Mark the archive dirty so a fresh named database is materialized as
135        // a portable ZIP. Follow-up writes refresh the archive on explicit
136        // `sync()` / checkpoint and on clean database drop.
137        recorder.flush()?;
138        Ok(Self::from_graph_with_wal(graph, recorder, None))
139    }
140
141    /// Restore from a snapshot file then replay any WAL records past
142    /// it.
143    ///
144    /// The snapshot's `wal_lsn` (when set) becomes the replay fence —
145    /// events at or below that LSN are already represented in the
146    /// loaded snapshot and are skipped. A missing snapshot file is
147    /// treated as "fresh start" so operators can pass the same path
148    /// on every boot.
149    ///
150    /// If the WAL contains a checkpoint marker newer than the
151    /// snapshot's `wal_lsn`, a one-line warning is printed to stderr
152    /// — the snapshot is stale relative to a more recent checkpoint
153    /// the operator is presumably aware of. Recovery still proceeds
154    /// from the snapshot's fence (replay re-applies every record
155    /// above it, which is conservative-correct); a tighter contract
156    /// is deferred to v2 because verifying that the marker's
157    /// snapshot file actually exists and is loadable is a separate
158    /// observability concern.
159    pub fn recover(
160        snapshot_path: impl AsRef<Path>,
161        wal_config: WalConfig,
162    ) -> Result<Self, LoraError> {
163        let snapshot_path = snapshot_path.as_ref();
164        let mut graph = InMemoryGraph::new();
165        let snapshot_lsn = match File::open(snapshot_path) {
166            Ok(f) => {
167                let reader = BufReader::new(f);
168                let (payload, info) = crate::snapshot::read_snapshot_from(reader, None)?;
169                graph.load_snapshot_payload(payload)?;
170                info.wal_lsn.map(Lsn::new).unwrap_or(Lsn::ZERO)
171            }
172            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Lsn::ZERO,
173            Err(e) => return Err(e.into()),
174        };
175
176        match wal_config {
177            WalConfig::Disabled => Ok(Self::from_graph(graph)),
178            WalConfig::Enabled {
179                dir,
180                sync_mode,
181                segment_target_bytes,
182            } => {
183                // Diagnostic peek at the WAL's newest checkpoint
184                // marker so we can warn the operator about a stale
185                // snapshot before we start replaying. Treat any error
186                // as "no marker" — the subsequent `Wal::open` will
187                // surface the real failure if there is one.
188                if dir.exists() {
189                    if let Ok(outcome) = replay_dir(&dir, Lsn::ZERO) {
190                        if let Some(marker) = outcome.checkpoint_lsn_observed {
191                            if marker > snapshot_lsn {
192                                eprintln!(
193                                    "lora-wal: snapshot at LSN {} is older than the newest \
194                                     checkpoint marker on disk (LSN {}). Replaying every WAL \
195                                     record above LSN {}; consider passing the more recent \
196                                     snapshot to --restore-from.",
197                                    snapshot_lsn.raw(),
198                                    marker.raw(),
199                                    snapshot_lsn.raw()
200                                );
201                            }
202                        }
203                    }
204                }
205
206                let (wal, events) = Wal::open(dir, sync_mode, segment_target_bytes, snapshot_lsn)?;
207                replay_into(&mut graph, events).map_err(LoraError::from_anyhow)?;
208                let recorder = Arc::new(WalRecorder::new(wal));
209                Ok(Self::from_graph_with_wal(graph, recorder, None))
210            }
211        }
212    }
213
214    /// Install the durable recorder on `graph` and assemble the
215    /// `Database` envelope. Shared by every WAL-backed constructor.
216    fn from_graph_with_wal(
217        mut graph: InMemoryGraph,
218        recorder: Arc<WalRecorder>,
219        snapshots: Option<Arc<ManagedSnapshotStore>>,
220    ) -> Self {
221        graph.set_mutation_recorder(Some(recorder.clone() as Arc<dyn MutationRecorder>));
222        Self {
223            store: Arc::new(LiveStore::new(Arc::new(graph))),
224            writer: Arc::new(Mutex::new(())),
225            lock_table: Arc::new(lora_store::LockTable::new()),
226            wal: Some(recorder),
227            snapshots,
228            plan_cache: Arc::new(PlanCache::new()),
229        }
230    }
231}
232
233impl<S> Database<S>
234where
235    S: GraphStorage + GraphStorageMut + Any + Clone + Send + Sync + 'static,
236{
237    /// Build a database from a pre-wrapped, shared store.
238    pub(crate) fn new(store: Arc<LiveStore<S>>) -> Self {
239        Self {
240            store,
241            writer: Arc::new(Mutex::new(())),
242            lock_table: Arc::new(lora_store::LockTable::new()),
243            wal: None,
244            snapshots: None,
245            plan_cache: Arc::new(PlanCache::new()),
246        }
247    }
248
249    /// Build a database by taking ownership of a bare graph store.
250    pub fn from_graph(graph: S) -> Self {
251        Self::new(Arc::new(LiveStore::new(Arc::new(graph))))
252    }
253}