second-brain-api 0.11.0

HTTP API server for second-brain: REST endpoints for recall, remember, and ingest
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
//! Keeps agent writes off the SQLite writer while store maintenance holds
//! it. A write that arrives then is saved to the write queue and answered
//! 202; once maintenance ends, writes keep queueing behind the saved ones
//! until the replayer has sent them all, so none lands out of order.

use std::path::PathBuf;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex, MutexGuard};
use std::time::Duration;

use axum::Json;
use axum::body::{Body, Bytes};
use axum::extract::{Request, State};
use axum::http::request::Parts;
use axum::http::{HeaderValue, Method, StatusCode, header};
use axum::middleware::Next;
use axum::response::{IntoResponse, Response};
use second_brain_core::redact::redact;
use serde_json::{Value, json};
use tokio::sync::Notify;

use crate::AppState;
use crate::write_queue::{self, Entry};

/// Set by the replayer, so a queued write it sends is never queued again.
pub const REPLAY_HEADER: &str = "x-second-brain-replay";
pub const QUEUED_REASON: &str = "store maintenance is running; the write is saved when it finishes";
const RETRY_AFTER_SECS: u64 = 300;
const MAX_QUEUED_BODY: usize = 8 * 1024 * 1024;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Mode {
    Open,
    Closed,
    /// Maintenance ended but queued writes are still unsent.
    Draining,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Class {
    Read,
    /// An agent write the replayer can send later.
    Queueable(&'static str),
    /// A write whose caller needs the answer now; it retries later.
    Refused,
}

pub struct WriteGate {
    queue_dir: Option<PathBuf>,
    mode: Mutex<Mode>,
    in_flight: AtomicUsize,
    maintenance: Mutex<()>,
    reopened: Notify,
}

impl Default for WriteGate {
    fn default() -> Self {
        Self::with_queue(None)
    }
}

pub struct WriteSlot<'a>(&'a WriteGate);

impl Drop for WriteSlot<'_> {
    fn drop(&mut self) {
        self.0.in_flight.fetch_sub(1, Ordering::SeqCst);
    }
}

/// Held for the length of a maintenance run; dropping it lets writes back
/// in behind whatever was queued meanwhile.
pub struct Closed<'a> {
    gate: &'a WriteGate,
    _serial: MutexGuard<'a, ()>,
}

impl Drop for Closed<'_> {
    fn drop(&mut self) {
        *self.gate.mode() = Mode::Draining;
        self.gate.reopened.notify_one();
    }
}

enum Admission<'a> {
    Live(WriteSlot<'a>),
    Queue,
    Busy,
}

impl WriteGate {
    pub fn new(queue_dir: PathBuf) -> Self {
        Self::with_queue(Some(queue_dir))
    }

    fn with_queue(queue_dir: Option<PathBuf>) -> Self {
        Self {
            queue_dir,
            mode: Mutex::new(Mode::Open),
            in_flight: AtomicUsize::new(0),
            maintenance: Mutex::new(()),
            reopened: Notify::new(),
        }
    }

    pub fn is_closed(&self) -> bool {
        *self.mode() == Mode::Closed
    }

    /// Room for an incidental write, such as recall's access count, which
    /// is skipped rather than queued while maintenance runs.
    pub fn try_enter(&self) -> Option<WriteSlot<'_>> {
        match self.admit(Class::Refused, true) {
            Admission::Live(slot) => Some(slot),
            Admission::Queue | Admission::Busy => None,
        }
    }

    /// Stops new writes and waits for those in flight, so the caller has the
    /// SQLite writer to itself. Maintenance runs one at a time.
    pub fn close(&self) -> Closed<'_> {
        let serial = match self.maintenance.lock() {
            Ok(g) => g,
            Err(poisoned) => poisoned.into_inner(),
        };
        *self.mode() = Mode::Closed;
        while self.in_flight.load(Ordering::SeqCst) > 0 {
            std::thread::sleep(Duration::from_millis(20));
        }
        Closed {
            gate: self,
            _serial: serial,
        }
    }

    /// Resolves once maintenance has ended and queued writes wait to be sent.
    pub async fn reopened(&self) {
        self.reopened.notified().await;
    }

    /// Lets writes through again once nothing is left queued; `queue_empty`
    /// runs under the gate's lock, so no write can be queued after it looked.
    pub fn open_when_drained(&self, queue_empty: impl FnOnce() -> bool) {
        let mut mode = self.mode();
        if *mode == Mode::Draining && queue_empty() {
            *mode = Mode::Open;
        }
    }

    fn admit(&self, class: Class, replay: bool) -> Admission<'_> {
        let mode = self.mode();
        let admission = match (*mode, class) {
            (Mode::Open, _) => Admission::Live(WriteSlot(self)),
            (Mode::Closed, Class::Queueable(_)) if !replay => Admission::Queue,
            (Mode::Closed, _) => Admission::Busy,
            (Mode::Draining, Class::Queueable(_)) if !replay => Admission::Queue,
            (Mode::Draining, _) => Admission::Live(WriteSlot(self)),
        };
        if matches!(admission, Admission::Live(_)) {
            self.in_flight.fetch_add(1, Ordering::SeqCst);
        }
        admission
    }

    /// Ok(false) when the gate opened since the caller was told to queue.
    fn enqueue(&self, entry: &Entry) -> anyhow::Result<bool> {
        let mode = self.mode();
        if *mode == Mode::Open {
            return Ok(false);
        }
        let Some(dir) = &self.queue_dir else {
            anyhow::bail!("this daemon has no write queue");
        };
        write_queue::push(dir, entry)?;
        Ok(true)
    }

    fn mode(&self) -> MutexGuard<'_, Mode> {
        match self.mode.lock() {
            Ok(g) => g,
            Err(poisoned) => poisoned.into_inner(),
        }
    }
}

/// GET routes and the POST routes that only read pass untouched, as does
/// the vacuum route, which closes the gate itself.
fn classify(method: &Method, path: &str) -> Class {
    if method == Method::GET || method == Method::HEAD {
        return Class::Read;
    }
    match (method.as_str(), path) {
        (
            "POST",
            "/v1/recall"
            | "/v1/context"
            | "/v1/daily/memories"
            | "/v1/sync/export"
            | "/v1/maintenance/vacuum",
        ) => Class::Read,
        ("POST", "/v1/remember") => Class::Queueable("remember"),
        ("POST", "/v1/associate") => Class::Queueable("associate"),
        ("POST", "/v1/ingest") => Class::Queueable("ingest"),
        ("DELETE", p) if p.starts_with("/v1/memory/") => Class::Queueable("forget"),
        _ => Class::Refused,
    }
}

pub async fn hold_writes(State(state): State<Arc<AppState>>, req: Request, next: Next) -> Response {
    let class = classify(req.method(), req.uri().path());
    if class == Class::Read {
        return next.run(req).await;
    }
    let replay = req.headers().contains_key(REPLAY_HEADER);
    let mut req = req;
    loop {
        match state.gate.admit(class, replay) {
            Admission::Live(slot) => {
                let response = next.run(req).await;
                drop(slot);
                return response;
            }
            Admission::Busy => return busy(),
            Admission::Queue => {}
        }
        let Class::Queueable(tool) = class else {
            return busy();
        };
        let (parts, body) = req.into_parts();
        let bytes = match axum::body::to_bytes(body, MAX_QUEUED_BODY).await {
            Ok(b) => b,
            Err(e) => return error(StatusCode::PAYLOAD_TOO_LARGE, &format!("{e}")),
        };
        let entry = match queued_entry(tool, &parts, &bytes) {
            Ok(entry) => entry,
            Err(e) => return error(StatusCode::BAD_REQUEST, &e),
        };
        let saved = {
            let (state, entry) = (state.clone(), entry.clone());
            tokio::task::spawn_blocking(move || state.gate.enqueue(&entry)).await
        };
        match saved {
            Ok(Ok(true)) => return queued(&entry),
            Ok(Ok(false)) => req = Request::from_parts(parts, Body::from(bytes)),
            Ok(Err(e)) => {
                tracing::warn!("cannot queue a {tool} during store maintenance: {e:#}");
                return busy();
            }
            Err(e) => {
                tracing::warn!("queueing a {tool} during store maintenance failed: {e}");
                return busy();
            }
        }
    }
}

/// A remember queued without a client id gets one here, so the caller can
/// name the note before it is stored. Text is redacted before it reaches the
/// queue file, as the handler would before storing it.
fn queued_entry(tool: &str, parts: &Parts, bytes: &Bytes) -> Result<Entry, String> {
    let mut body: Option<Value> = if bytes.is_empty() {
        None
    } else {
        Some(serde_json::from_slice(bytes).map_err(|e| format!("invalid JSON body: {e}"))?)
    };
    if tool == "remember" {
        let Some(Value::Object(fields)) = body.as_mut() else {
            return Err("a remember needs a JSON object body".to_string());
        };
        if !fields.get("id").is_some_and(Value::is_string) {
            fields.insert(
                "id".to_string(),
                Value::String(uuid::Uuid::new_v4().to_string()),
            );
        }
    }
    if let Some(body) = body.as_mut() {
        redact_strings(body);
    }
    Ok(Entry {
        tool: tool.to_string(),
        method: parts.method.to_string(),
        path: parts.uri.path().to_string(),
        query: parts.uri.query().map(redact_query),
        body,
    })
}

fn redact_strings(value: &mut Value) {
    match value {
        Value::String(s) => *s = redact(s).text,
        Value::Array(items) => items.iter_mut().for_each(redact_strings),
        Value::Object(fields) => fields.values_mut().for_each(redact_strings),
        _ => {}
    }
}

fn redact_query(query: &str) -> String {
    let Ok(mut url) = reqwest::Url::parse(&format!("http://queue/?{query}")) else {
        return redact(query).text;
    };
    let pairs: Vec<(String, String)> = url
        .query_pairs()
        .map(|(k, v)| (k.into_owned(), redact(&v).text))
        .collect();
    url.query_pairs_mut().clear().extend_pairs(pairs);
    url.query().unwrap_or_default().to_string()
}

fn queued(entry: &Entry) -> Response {
    let mut reply = json!({ "queued": true, "reason": QUEUED_REASON });
    if entry.tool == "remember"
        && let Some(id) = entry.body.as_ref().and_then(|b| b["id"].as_str())
    {
        reply["id"] = Value::String(id.to_string());
    }
    (StatusCode::ACCEPTED, Json(reply)).into_response()
}

fn busy() -> Response {
    let mut response = error(
        StatusCode::SERVICE_UNAVAILABLE,
        "store maintenance is running; retry later",
    );
    response
        .headers_mut()
        .insert(header::RETRY_AFTER, HeaderValue::from(RETRY_AFTER_SECS));
    response
}

fn error(status: StatusCode, message: &str) -> Response {
    (status, Json(json!({ "error": message }))).into_response()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn writes_are_told_apart_from_reads() {
        let post = Method::POST;
        assert_eq!(classify(&Method::GET, "/v1/redaction"), Class::Read);
        assert_eq!(classify(&post, "/v1/recall"), Class::Read);
        assert_eq!(classify(&post, "/v1/maintenance/vacuum"), Class::Read);
        assert_eq!(
            classify(&post, "/v1/remember"),
            Class::Queueable("remember")
        );
        assert_eq!(
            classify(&Method::DELETE, "/v1/memory/x"),
            Class::Queueable("forget")
        );
        assert_eq!(classify(&post, "/v1/sync/import"), Class::Refused);
        assert_eq!(classify(&post, "/v1/some-new-route"), Class::Refused);
    }

    #[test]
    fn a_queued_write_holds_no_secret() {
        let token = ["gh", "p_"].concat() + "Qq7k3Jd9XwL2pVb8NzR4tYc6MhF1sGa5UeT0";
        let remember = axum::http::Request::builder()
            .method("POST")
            .uri("/v1/remember")
            .body(())
            .unwrap()
            .into_parts()
            .0;
        let body = json!({"content": format!("deploy with {token}"), "tags": [token.clone()]});
        let entry = queued_entry("remember", &remember, &Bytes::from(body.to_string())).unwrap();
        let forget = axum::http::Request::builder()
            .method("DELETE")
            .uri(format!("/v1/memory/x?hard=false&reason=leaked%20{token}"))
            .body(())
            .unwrap()
            .into_parts()
            .0;
        let forget = queued_entry("forget", &forget, &Bytes::new()).unwrap();
        let saved =
            serde_json::to_string(&entry).unwrap() + &serde_json::to_string(&forget).unwrap();
        assert!(!saved.contains(&token), "{saved}");
        assert!(saved.contains("[REDACTED:github_token]"));
        assert!(entry.body.unwrap()["id"].is_string());
        assert!(forget.query.unwrap().starts_with("hard=false&reason="));
    }

    #[test]
    fn closing_waits_for_writes_in_flight() {
        let gate = Arc::new(WriteGate::default());
        let slot_gate = gate.clone();
        let (entered, wait) = std::sync::mpsc::channel();
        let writer = std::thread::spawn(move || {
            let _slot = slot_gate.try_enter().unwrap();
            entered.send(()).unwrap();
            std::thread::sleep(Duration::from_millis(200));
        });
        wait.recv().unwrap();
        let started = std::time::Instant::now();
        let closed = gate.close();
        assert!(started.elapsed() >= Duration::from_millis(100));
        assert!(gate.try_enter().is_none());
        writer.join().unwrap();
        drop(closed);
        assert!(gate.try_enter().is_some());
    }

    #[test]
    fn after_maintenance_writes_queue_until_the_queue_drains() {
        let gate = WriteGate::default();
        drop(gate.close());
        assert!(matches!(
            gate.admit(Class::Queueable("remember"), false),
            Admission::Queue
        ));
        assert!(matches!(
            gate.admit(Class::Queueable("remember"), true),
            Admission::Live(_)
        ));
        gate.open_when_drained(|| false);
        assert!(matches!(
            gate.admit(Class::Queueable("remember"), false),
            Admission::Queue
        ));
        gate.open_when_drained(|| true);
        assert!(matches!(
            gate.admit(Class::Queueable("remember"), false),
            Admission::Live(_)
        ));
    }
}