second-brain-api 0.13.5

HTTP API server for second-brain: REST endpoints for recall, remember, and ingest
Documentation
mod common;

use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};

use axum::body::Body;
use axum::http::{Request, StatusCode, header};
use serde_json::{Value, json};
use tower::ServiceExt;

use second_brain_api::clock_gate::{self, ClockGate, TimeSignals};
use second_brain_core::sqlite_store::SqliteStore;
use second_brain_core::store::Store;

const TOKEN: &str = "clock-gate-test-token";

#[derive(Default)]
struct Signals {
    synced: AtomicBool,
}

impl TimeSignals for Signals {
    fn now_micros(&self) -> i64 {
        chrono::Utc::now().timestamp_micros()
    }

    fn ntp_synced(&self) -> bool {
        self.synced.load(Ordering::SeqCst)
    }

    fn rtc_secs(&self) -> Option<i64> {
        None
    }
}

fn authed(method: &str, uri: &str, body: Option<Value>) -> Request<Body> {
    let builder = Request::builder()
        .method(method)
        .uri(uri)
        .header(header::AUTHORIZATION, format!("Bearer {TOKEN}"));
    match body {
        Some(body) => builder
            .header(header::CONTENT_TYPE, "application/json")
            .body(Body::from(body.to_string()))
            .unwrap(),
        None => builder.body(Body::empty()).unwrap(),
    }
}

async fn call(app: &axum::Router, req: Request<Body>) -> (StatusCode, Value, Option<String>) {
    let response = app.clone().oneshot(req).await.unwrap();
    let status = response.status();
    let retry_after = response
        .headers()
        .get(header::RETRY_AFTER)
        .map(|v| v.to_str().unwrap().to_string());
    let body = common::json_body(response).await;
    (status, body, retry_after)
}

fn remember() -> Request<Body> {
    authed(
        "POST",
        "/v1/remember",
        Some(
            json!({"content": "seqs wait for a trusted clock before they are minted", "source": "cli"}),
        ),
    )
}

#[tokio::test]
async fn a_closed_gate_holds_writes_and_shows_on_health_until_a_synced_peer_opens_it() {
    let dir = tempfile::tempdir().unwrap();
    let signals = Arc::new(Signals::default());
    let clock = ClockGate::new(dir.path(), signals.clone(), i64::MAX);
    let store = SqliteStore::in_memory("clock-machine".to_string())
        .unwrap()
        .with_wall_clock(clock.clone());
    let state = common::state_with_clock(store, clock.clone());
    clock_gate::report_to(&clock, state.health.clone(), state.sqlite.clone());
    clock.tick();
    let app = second_brain_api::app(state.clone(), TOKEN.to_string());

    let (status, body, retry_after) = call(&app, remember()).await;
    assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE, "{body}");
    assert_eq!(retry_after.as_deref(), Some("30"));
    let error = body["error"].as_str().unwrap();
    assert!(error.contains("clock not yet trusted"), "{error}");
    assert_eq!(state.sqlite.memory_count().unwrap(), 0);

    let (_, health, _) = call(&app, authed("GET", "/health", None)).await;
    let reason = health["reason"].as_str().unwrap_or_default();
    assert!(
        !reason.contains("clock"),
        "a brief hold is not flagged: {reason}"
    );

    state.health.clock_gate(
        Some(second_brain_api::health::CLOCK_HELD_GRACE),
        chrono::Utc::now(),
    );
    let (status, health, _) = call(&app, authed("GET", "/health", None)).await;
    assert_eq!(status, StatusCode::OK);
    assert_eq!(health["state"], "degraded", "{health}");
    let reason = health["reason"].as_str().unwrap();
    assert!(
        reason.contains("clock not yet trusted: writes held"),
        "{reason}"
    );

    let (status, body, _) = call(
        &app,
        authed(
            "POST",
            "/v1/recall",
            Some(json!({"query": "trusted clock"})),
        ),
    )
    .await;
    assert_eq!(status, StatusCode::OK, "reads pass a closed gate: {body}");

    clock.open_by_peer();
    clock.tick();

    let (status, body, _) = call(&app, remember()).await;
    assert_eq!(status, StatusCode::OK, "{body}");
    assert_eq!(state.sqlite.memory_count().unwrap(), 1);

    let (_, health, _) = call(&app, authed("GET", "/health", None)).await;
    let reason = health["reason"].as_str().unwrap_or_default();
    assert!(!reason.contains("clock"), "{reason}");
}