second-brain-api 0.13.3

HTTP API server for second-brain: REST endpoints for recall, remember, and ingest
Documentation
#![allow(dead_code)]

use std::path::Path;
use std::sync::{Arc, RwLock};

use axum::body::Body;
use axum::http::{Request, header};
use http_body_util::BodyExt;

use second_brain_api::clock_gate::ClockGate;
use second_brain_api::health::Health;
use second_brain_api::write_gate::WriteGate;
use second_brain_api::{AppState, routes};
use second_brain_core::machine::MachineIdentity;
use second_brain_core::retrieval::RetrievalTunables;
use second_brain_core::schema::SyncState;
use second_brain_core::sqlite_store::SqliteStore;
use second_brain_core::store::StoreAdmin;
use second_brain_sync::crypto::XChaChaEncryptor;
use second_brain_sync::keyring::{Continuity, LEGACY_KEY_FILE, migrate_sync_key};

pub fn app() -> axum::Router {
    app_with_store().0
}

pub fn app_with_store() -> (axum::Router, Arc<SqliteStore>) {
    app_with_parts(smoke_store(), fresh_health())
}

pub fn app_with_sqlite(store: SqliteStore) -> (axum::Router, Arc<SqliteStore>) {
    app_with_parts(store, fresh_health())
}

pub fn app_with_health(health: Arc<Health>) -> (axum::Router, Arc<SqliteStore>) {
    app_with_parts(smoke_store(), health)
}

pub fn state() -> Arc<AppState> {
    state_with(smoke_store(), fresh_health())
}

/// A state whose write gate queues into `queue_dir` during maintenance.
pub fn state_with_queue(queue_dir: std::path::PathBuf) -> Arc<AppState> {
    state_with_gate(smoke_store(), fresh_health(), WriteGate::new(queue_dir))
}

/// Like [`state_with_queue`], sealing what the gate queues to `recipient`.
pub fn state_with_sealing_queue(
    queue_dir: std::path::PathBuf,
    recipient: age::x25519::Recipient,
) -> Arc<AppState> {
    let gate = WriteGate::new(queue_dir).sealing_to(recipient);
    state_with_gate(smoke_store(), fresh_health(), gate)
}

/// `store` should mint through `clock` (`with_wall_clock`) for the gate to
/// hold its writes.
pub fn state_with_clock(store: SqliteStore, clock: Arc<ClockGate>) -> Arc<AppState> {
    let base =
        Arc::into_inner(state_with(store, fresh_health())).expect("a new state has one owner");
    Arc::new(AppState { clock, ..base })
}

/// Gives `store` device keys in `data_dir` and the identity a `sync.key`
/// holding `key` becomes on upgrade, after it synced with `knows`.
pub fn upgrade_from_sync_key(store: &SqliteStore, data_dir: &Path, key: [u8; 32], knows: &[&str]) {
    for peer in knows {
        store
            .set_sync_state(&SyncState {
                peer_id: peer.to_string(),
                last_seq: 0,
                last_sync_at: chrono::Utc::now(),
            })
            .unwrap();
    }
    second_brain_core::keys::ensure_device_keys(store, data_dir).unwrap();
    std::fs::write(
        data_dir.join(LEGACY_KEY_FILE),
        XChaChaEncryptor::new(key).key_base64(),
    )
    .unwrap();
    let continuity = migrate_sync_key(
        store,
        data_dir,
        store.machine_id(),
        chrono::Utc::now().timestamp_micros(),
    )
    .unwrap();
    assert!(
        matches!(continuity, Continuity::Migrated { .. }),
        "{continuity:?}"
    );
}

/// A daemon whose keys live in `data_dir`.
pub fn app_in(store: SqliteStore, data_dir: &Path) -> (axum::Router, Arc<SqliteStore>) {
    let state = state_in(store, data_dir, ClockGate::open_for_tests());
    let store = state.sqlite.clone();
    (routes::router().with_state(state), store)
}

pub fn state_in(store: SqliteStore, data_dir: &Path, clock: Arc<ClockGate>) -> Arc<AppState> {
    let base =
        Arc::into_inner(state_with(store, fresh_health())).expect("a new state has one owner");
    Arc::new(AppState {
        clock,
        data_dir: data_dir.to_path_buf(),
        ..base
    })
}

fn smoke_store() -> SqliteStore {
    SqliteStore::in_memory("smoke-machine".to_string()).unwrap()
}

fn fresh_health() -> Arc<Health> {
    Arc::new(Health::new(chrono::Utc::now(), None))
}

fn app_with_parts(store: SqliteStore, health: Arc<Health>) -> (axum::Router, Arc<SqliteStore>) {
    let state = state_with(store, health);
    let store = state.sqlite.clone();
    (routes::router().with_state(state), store)
}

fn state_with(store: SqliteStore, health: Arc<Health>) -> Arc<AppState> {
    state_with_gate(store, health, WriteGate::default())
}

fn state_with_gate(store: SqliteStore, health: Arc<Health>, gate: WriteGate) -> Arc<AppState> {
    let machine = MachineIdentity {
        id: store.machine_id().to_string(),
        name: "smoke".to_string(),
    };
    store.register_machine(&machine).unwrap();
    let sqlite = Arc::new(store);
    Arc::new(AppState {
        data_dir: std::env::temp_dir().join("second-brain-test-no-device-key"),
        pairing: Default::default(),
        bootstrap: Default::default(),
        device_access: Default::default(),
        gate: Arc::new(gate),
        store: sqlite.clone(),
        sqlite,
        indexes: None,
        raw_index: None,
        raw_coverage: None,
        archive: None,
        reranker: None,
        tunables: RetrievalTunables::default(),
        embedder: None,
        machine,
        maintenance: Arc::new(RwLock::new(None)),
        repair_tx: None,
        near_duplicate_threshold: 0.97,
        near_duplicates: std::sync::Arc::new(std::sync::RwLock::new(None)),
        health,
        clock: ClockGate::open_for_tests(),
    })
}

pub async fn json_body(response: axum::response::Response) -> serde_json::Value {
    let bytes = response.into_body().collect().await.unwrap().to_bytes();
    serde_json::from_slice(&bytes).unwrap()
}

pub fn post_json(uri: &str, body: serde_json::Value) -> Request<Body> {
    Request::builder()
        .method("POST")
        .uri(uri)
        .header(header::CONTENT_TYPE, "application/json")
        .body(Body::from(body.to_string()))
        .unwrap()
}

pub fn get(uri: &str) -> Request<Body> {
    Request::builder().uri(uri).body(Body::empty()).unwrap()
}

pub fn delete(uri: &str) -> Request<Body> {
    Request::builder()
        .method("DELETE")
        .uri(uri)
        .body(Body::empty())
        .unwrap()
}