Skip to main content

second_brain_api/
bootstrap.rs

1use std::path::Path;
2use std::sync::Mutex;
3use std::sync::atomic::{AtomicU8, Ordering};
4
5use anyhow::Result;
6use second_brain_core::sqlite_store::{BootstrapState, SqliteStore};
7use second_brain_sync::pairing::JOIN_PENDING_FILE;
8
9const NONE: u8 = 0;
10const PENDING: u8 = 1;
11const INGEST_DUE: u8 = 2;
12
13/// Whether this device still waits for its first snapshot from the device
14/// that paired it, so nothing is ingested before it holds the identity's rows.
15/// The state lives in the store; this caches it so ingest paths can check it
16/// without a query.
17#[derive(Default)]
18pub struct Bootstrap {
19    state: AtomicU8,
20    writing: Mutex<()>,
21}
22
23impl Bootstrap {
24    pub fn load(sqlite: &SqliteStore) -> Result<Self> {
25        let bootstrap = Self::default();
26        bootstrap
27            .state
28            .store(encode(sqlite.bootstrap_state()?), Ordering::SeqCst);
29        Ok(bootstrap)
30    }
31
32    /// The daemon's own at start: `load`, after `sb setup`'s join marker in
33    /// `data_dir` holds an empty store pending (and is then removed). A
34    /// state it cannot read holds ingest back rather than risk ingesting
35    /// before a bootstrap; founding an identity or a finished join ends it.
36    pub fn start(sqlite: &SqliteStore, data_dir: &Path) -> Self {
37        if let Err(e) = take_join_marker(sqlite, data_dir) {
38            tracing::error!("cannot read the join marker from sb setup: {e:#}");
39        }
40        Self::load(sqlite).unwrap_or_else(|e| {
41            tracing::error!(
42                "cannot read the pairing bootstrap state, holding ingest until this device \
43                 pairs: {e:#}"
44            );
45            let bootstrap = Self::default();
46            bootstrap.state.store(PENDING, Ordering::SeqCst);
47            bootstrap
48        })
49    }
50
51    pub fn is_pending(&self) -> bool {
52        self.state.load(Ordering::SeqCst) == PENDING
53    }
54
55    /// The bootstrap finished and the full ingest pass after it has not.
56    pub fn ingest_due(&self) -> bool {
57        self.state.load(Ordering::SeqCst) == INGEST_DUE
58    }
59
60    pub fn mark_pending(&self, sqlite: &SqliteStore) -> Result<()> {
61        let _writing = self.writing.lock().unwrap_or_else(|e| e.into_inner());
62        sqlite.set_bootstrap_state(Some(BootstrapState::Pending))?;
63        self.state.store(PENDING, Ordering::SeqCst);
64        Ok(())
65    }
66
67    /// Ends a pending bootstrap; true when one was pending.
68    pub fn finish(&self, sqlite: &SqliteStore) -> Result<bool> {
69        let _writing = self.writing.lock().unwrap_or_else(|e| e.into_inner());
70        if !self.is_pending() {
71            return Ok(false);
72        }
73        sqlite.set_bootstrap_state(Some(BootstrapState::IngestDue))?;
74        self.state.store(INGEST_DUE, Ordering::SeqCst);
75        Ok(true)
76    }
77
78    /// Ends a pending bootstrap with no ingest pass due, as when this device
79    /// founds its own identity instead of joining one; true when one was
80    /// pending.
81    pub fn cancel(&self, sqlite: &SqliteStore) -> Result<bool> {
82        let _writing = self.writing.lock().unwrap_or_else(|e| e.into_inner());
83        if !self.is_pending() {
84            return Ok(false);
85        }
86        sqlite.set_bootstrap_state(None)?;
87        self.state.store(NONE, Ordering::SeqCst);
88        Ok(true)
89    }
90
91    /// Records the full ingest pass as run; a no-op unless one was due, so a
92    /// bootstrap marked pending meanwhile stays pending.
93    pub fn ingest_done(&self, sqlite: &SqliteStore) -> Result<()> {
94        let _writing = self.writing.lock().unwrap_or_else(|e| e.into_inner());
95        if !self.ingest_due() {
96            return Ok(());
97        }
98        sqlite.set_bootstrap_state(None)?;
99        self.state.store(NONE, Ordering::SeqCst);
100        Ok(())
101    }
102}
103
104fn take_join_marker(sqlite: &SqliteStore, data_dir: &Path) -> Result<()> {
105    let marker = data_dir.join(JOIN_PENDING_FILE);
106    if !marker.try_exists()? {
107        return Ok(());
108    }
109    if !sqlite.holds_replicated_rows()? {
110        sqlite.set_bootstrap_state(Some(BootstrapState::Pending))?;
111    }
112    std::fs::remove_file(&marker)?;
113    Ok(())
114}
115
116fn encode(state: Option<BootstrapState>) -> u8 {
117    match state {
118        None => NONE,
119        Some(BootstrapState::Pending) => PENDING,
120        Some(BootstrapState::IngestDue) => INGEST_DUE,
121    }
122}