second-brain-core 0.13.5

Core library for second-brain: SQLite storage with vector and lexical indexes, BGE embeddings, and hybrid retrieval
Documentation
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use std::io::ErrorKind;
use std::path::Path;
use uuid::Uuid;

const MACHINE_FILE: &str = "machine.toml";

pub fn data_dir() -> Result<std::path::PathBuf> {
    let home = dirs::home_dir().context("cannot determine home directory")?;
    Ok(home.join(".second-brain"))
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MachineIdentity {
    pub id: String,
    pub name: String,
}

impl MachineIdentity {
    pub fn load_or_create(config_dir: &Path) -> Result<Self> {
        if let Some(identity) = Self::load(config_dir)? {
            return Ok(identity);
        }
        let identity = Self::fresh();
        std::fs::create_dir_all(config_dir).context("creating config directory")?;
        std::fs::write(
            config_dir.join(MACHINE_FILE),
            toml::to_string_pretty(&identity)?,
        )
        .context("writing machine.toml")?;
        Ok(identity)
    }

    /// None when `config_dir` holds no machine.toml.
    pub fn load(config_dir: &Path) -> Result<Option<Self>> {
        let content = match std::fs::read_to_string(config_dir.join(MACHINE_FILE)) {
            Ok(content) => content,
            Err(e) if e.kind() == ErrorKind::NotFound => return Ok(None),
            Err(e) => return Err(e).context("reading machine.toml"),
        };
        toml::from_str(&content)
            .map(Some)
            .context("parsing machine.toml")
    }

    /// Replaces `machine.toml` with a fresh machine id, atomically.
    pub(crate) fn mint(config_dir: &Path) -> Result<Self> {
        let identity = Self::fresh();
        let temp = config_dir.join(format!(".{MACHINE_FILE}.{}.tmp", Uuid::new_v4().simple()));
        std::fs::write(&temp, toml::to_string_pretty(&identity)?)
            .and_then(|()| std::fs::File::open(&temp)?.sync_all())
            .and_then(|()| std::fs::rename(&temp, config_dir.join(MACHINE_FILE)))
            .with_context(|| format!("writing a new machine id into {}", config_dir.display()))
            .inspect_err(|_| {
                if let Err(e) = std::fs::remove_file(&temp)
                    && e.kind() != ErrorKind::NotFound
                {
                    tracing::warn!("cannot remove {}: {e}", temp.display());
                }
            })?;
        std::fs::File::open(config_dir)
            .and_then(|d| d.sync_all())
            .with_context(|| format!("syncing {}", config_dir.display()))?;
        Ok(identity)
    }

    fn fresh() -> Self {
        let name = hostname::get()
            .map(|h| h.to_string_lossy().to_string())
            .unwrap_or_else(|_| "unknown".to_string());
        MachineIdentity {
            id: Uuid::new_v4().to_string(),
            name,
        }
    }

    pub fn config_dir() -> Result<std::path::PathBuf> {
        let home = dirs::home_dir().context("cannot determine home directory")?;
        Ok(home.join(".second-brain"))
    }
}