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;
#[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)
}
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
}
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(())
}
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)
}
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)
}
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,
}
}