second-brain-api 0.13.0

HTTP API server for second-brain: REST endpoints for recall, remember, and ingest
Documentation
use std::path::Path;
use std::sync::Mutex;
use std::sync::atomic::{AtomicU8, Ordering};

use anyhow::Result;
use second_brain_core::sqlite_store::{BootstrapState, SqliteStore};
use second_brain_sync::pairing::JOIN_PENDING_FILE;

const NONE: u8 = 0;
const PENDING: u8 = 1;
const INGEST_DUE: u8 = 2;

/// Whether this device still waits for its first snapshot from the device
/// that paired it, so nothing is ingested before it holds the identity's rows.
/// The state lives in the store; this caches it so ingest paths can check it
/// without a query.
#[derive(Default)]
pub struct Bootstrap {
    state: AtomicU8,
    writing: Mutex<()>,
}

impl Bootstrap {
    pub fn load(sqlite: &SqliteStore) -> Result<Self> {
        let bootstrap = Self::default();
        bootstrap
            .state
            .store(encode(sqlite.bootstrap_state()?), Ordering::SeqCst);
        Ok(bootstrap)
    }

    /// The daemon's own at start: `load`, after `sb setup`'s join marker in
    /// `data_dir` holds an empty store pending (and is then removed). A
    /// state it cannot read holds ingest back rather than risk ingesting
    /// before a bootstrap; founding an identity or a finished join ends it.
    pub fn start(sqlite: &SqliteStore, data_dir: &Path) -> Self {
        if let Err(e) = take_join_marker(sqlite, data_dir) {
            tracing::error!("cannot read the join marker from sb setup: {e:#}");
        }
        Self::load(sqlite).unwrap_or_else(|e| {
            tracing::error!(
                "cannot read the pairing bootstrap state, holding ingest until this device \
                 pairs: {e:#}"
            );
            let bootstrap = Self::default();
            bootstrap.state.store(PENDING, Ordering::SeqCst);
            bootstrap
        })
    }

    pub fn is_pending(&self) -> bool {
        self.state.load(Ordering::SeqCst) == PENDING
    }

    /// The bootstrap finished and the full ingest pass after it has not.
    pub fn ingest_due(&self) -> bool {
        self.state.load(Ordering::SeqCst) == INGEST_DUE
    }

    pub fn mark_pending(&self, sqlite: &SqliteStore) -> Result<()> {
        let _writing = self.writing.lock().unwrap_or_else(|e| e.into_inner());
        sqlite.set_bootstrap_state(Some(BootstrapState::Pending))?;
        self.state.store(PENDING, Ordering::SeqCst);
        Ok(())
    }

    /// Ends a pending bootstrap; true when one was pending.
    pub fn finish(&self, sqlite: &SqliteStore) -> Result<bool> {
        let _writing = self.writing.lock().unwrap_or_else(|e| e.into_inner());
        if !self.is_pending() {
            return Ok(false);
        }
        sqlite.set_bootstrap_state(Some(BootstrapState::IngestDue))?;
        self.state.store(INGEST_DUE, Ordering::SeqCst);
        Ok(true)
    }

    /// Ends a pending bootstrap with no ingest pass due, as when this device
    /// founds its own identity instead of joining one; true when one was
    /// pending.
    pub fn cancel(&self, sqlite: &SqliteStore) -> Result<bool> {
        let _writing = self.writing.lock().unwrap_or_else(|e| e.into_inner());
        if !self.is_pending() {
            return Ok(false);
        }
        sqlite.set_bootstrap_state(None)?;
        self.state.store(NONE, Ordering::SeqCst);
        Ok(true)
    }

    /// Records the full ingest pass as run; a no-op unless one was due, so a
    /// bootstrap marked pending meanwhile stays pending.
    pub fn ingest_done(&self, sqlite: &SqliteStore) -> Result<()> {
        let _writing = self.writing.lock().unwrap_or_else(|e| e.into_inner());
        if !self.ingest_due() {
            return Ok(());
        }
        sqlite.set_bootstrap_state(None)?;
        self.state.store(NONE, Ordering::SeqCst);
        Ok(())
    }
}

fn take_join_marker(sqlite: &SqliteStore, data_dir: &Path) -> Result<()> {
    let marker = data_dir.join(JOIN_PENDING_FILE);
    if !marker.try_exists()? {
        return Ok(());
    }
    if !sqlite.holds_replicated_rows()? {
        sqlite.set_bootstrap_state(Some(BootstrapState::Pending))?;
    }
    std::fs::remove_file(&marker)?;
    Ok(())
}

fn encode(state: Option<BootstrapState>) -> u8 {
    match state {
        None => NONE,
        Some(BootstrapState::Pending) => PENDING,
        Some(BootstrapState::IngestDue) => INGEST_DUE,
    }
}