second-brain-api 0.13.2

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

use anyhow::Result;
use second_brain_core::sqlite_store::SqliteStore;
use second_brain_sync::mdns::{self, Advert, Net, Responder};
use second_brain_sync::pairing::PairingHost;

use crate::pairing::Pairing;

const SSH_PORT: u16 = 22;

/// What this daemon answers mDNS queries with, read on each query (each
/// second on macOS): its sshd under its machine id once it holds a sync
/// identity, and the pairing listener while one is open. A listener handing
/// keys to a restore is never advertised, so no joining device dials it by
/// mistake. A store that cannot be read is warned about once until a read
/// succeeds, through `failing`.
pub fn adverts(
    sqlite: &SqliteStore,
    pairing: &Pairing,
    name: &str,
    failing: &AtomicBool,
) -> Vec<Advert> {
    let own = sqlite.machine_id();
    let mut adverts = Vec::new();
    match device_advert(sqlite) {
        Ok(advert) => {
            failing.store(false, Ordering::Relaxed);
            adverts.extend(advert);
        }
        Err(e) if !failing.swap(true, Ordering::Relaxed) => {
            tracing::warn!("cannot read what to advertise this device's sshd with: {e:#}")
        }
        Err(_) => {}
    }
    let pairs = |h: &&PairingHost| h.is_open() && !h.hands_over_keys();
    if let Some(port) = pairing.with_host(|host| host.filter(pairs).map(|h| h.port())) {
        adverts.push(mdns::pairing_advert(name, own, port));
    }
    adverts
}

/// The route the route advertiser keeps current goes first, so a stopped
/// or moved sshd shows without a new signed row.
fn device_advert(sqlite: &SqliteStore) -> Result<Option<Advert>> {
    let own = sqlite.machine_id();
    let Some(row) = sqlite.device_record(own)? else {
        return Ok(None);
    };
    if row.revoked {
        return Ok(None);
    }
    let record = row.current.record;
    let route = sqlite.device_route(own)?.unwrap_or_default();
    let Some(login) = route.ssh_login.or(record.ssh_login) else {
        return Ok(None);
    };
    let port = route
        .ssh_port
        .or(record.ssh_port)
        .filter(|port| *port != 0)
        .unwrap_or(SSH_PORT);
    Ok(Some(mdns::device_advert(own, &login, port)))
}

/// None, with a warning, when the responder cannot start (another program
/// holding port 5353 without sharing it, say); lookups by peers then fall
/// back to the addresses they hold.
pub fn spawn_responder(
    net: &Net,
    sqlite: Arc<SqliteStore>,
    pairing: Arc<Pairing>,
    name: String,
) -> Option<Responder> {
    let failing = AtomicBool::new(false);
    let adverts = Arc::new(move || adverts(&sqlite, &pairing, &name, &failing));
    match Responder::spawn(net, adverts) {
        Ok(responder) => Some(responder),
        Err(e) => {
            tracing::warn!("cannot answer mDNS lookups for this device: {e:#}");
            None
        }
    }
}