1use std::path::PathBuf;
7use std::sync::atomic::{AtomicUsize, Ordering};
8use std::sync::{Arc, Mutex, MutexGuard};
9use std::time::Duration;
10
11use age::x25519::Recipient;
12use axum::Json;
13use axum::body::{Body, Bytes};
14use axum::extract::{Request, State};
15use axum::http::request::Parts;
16use axum::http::{HeaderValue, Method, StatusCode, header};
17use axum::middleware::Next;
18use axum::response::{IntoResponse, Response};
19use second_brain_core::redact::redact;
20use serde_json::{Value, json};
21use tokio::sync::Notify;
22
23use crate::AppState;
24use crate::clock_gate::ClockGate;
25use crate::write_queue::{self, Entry};
26
27pub const REPLAY_HEADER: &str = "x-second-brain-replay";
29pub const QUEUED_REASON: &str = "store maintenance is running; the write is saved when it finishes";
30const RETRY_AFTER_SECS: u64 = 300;
31pub const CLOCK_HELD_REASON: &str =
32 "clock not yet trusted: writes are held until time sync is confirmed; retry later";
33const CLOCK_RETRY_AFTER_SECS: u64 = 30;
34const MAX_QUEUED_BODY: usize = 8 * 1024 * 1024;
35
36#[derive(Debug, Clone, Copy, PartialEq, Eq)]
37enum Mode {
38 Open,
39 Closed,
40 Draining,
42}
43
44#[derive(Debug, Clone, Copy, PartialEq, Eq)]
45enum Class {
46 Read,
47 Queueable(&'static str),
49 Refused,
51}
52
53pub struct WriteGate {
54 queue_dir: Option<PathBuf>,
55 recipient: Option<Recipient>,
56 mode: Mutex<Mode>,
57 in_flight: AtomicUsize,
58 maintenance: Mutex<()>,
59 reopened: Notify,
60}
61
62impl Default for WriteGate {
63 fn default() -> Self {
64 Self::with_queue(None)
65 }
66}
67
68pub struct WriteSlot<'a>(&'a WriteGate);
69
70impl Drop for WriteSlot<'_> {
71 fn drop(&mut self) {
72 self.0.in_flight.fetch_sub(1, Ordering::SeqCst);
73 }
74}
75
76pub struct Closed<'a> {
79 gate: &'a WriteGate,
80 _serial: MutexGuard<'a, ()>,
81}
82
83impl Drop for Closed<'_> {
84 fn drop(&mut self) {
85 *self.gate.mode() = Mode::Draining;
86 self.gate.reopened.notify_one();
87 }
88}
89
90enum Admission<'a> {
91 Live(WriteSlot<'a>),
92 Queue,
93 Busy,
94}
95
96impl WriteGate {
97 pub fn new(queue_dir: PathBuf) -> Self {
98 Self::with_queue(Some(queue_dir))
99 }
100
101 fn with_queue(queue_dir: Option<PathBuf>) -> Self {
102 Self {
103 queue_dir,
104 recipient: None,
105 mode: Mutex::new(Mode::Open),
106 in_flight: AtomicUsize::new(0),
107 maintenance: Mutex::new(()),
108 reopened: Notify::new(),
109 }
110 }
111
112 pub fn sealing_to(mut self, recipient: Recipient) -> Self {
113 self.recipient = Some(recipient);
114 self
115 }
116
117 pub fn is_closed(&self) -> bool {
118 *self.mode() == Mode::Closed
119 }
120
121 pub fn try_enter(&self) -> Option<WriteSlot<'_>> {
124 match self.admit(Class::Refused, true) {
125 Admission::Live(slot) => Some(slot),
126 Admission::Queue | Admission::Busy => None,
127 }
128 }
129
130 pub fn close(&self) -> Closed<'_> {
133 let serial = match self.maintenance.lock() {
134 Ok(g) => g,
135 Err(poisoned) => poisoned.into_inner(),
136 };
137 *self.mode() = Mode::Closed;
138 while self.in_flight.load(Ordering::SeqCst) > 0 {
139 std::thread::sleep(Duration::from_millis(20));
140 }
141 Closed {
142 gate: self,
143 _serial: serial,
144 }
145 }
146
147 pub async fn reopened(&self) {
149 self.reopened.notified().await;
150 }
151
152 pub fn open_when_drained(&self, queue_empty: impl FnOnce() -> bool) {
155 let mut mode = self.mode();
156 if *mode == Mode::Draining && queue_empty() {
157 *mode = Mode::Open;
158 }
159 }
160
161 fn admit(&self, class: Class, replay: bool) -> Admission<'_> {
162 let mode = self.mode();
163 let admission = match (*mode, class) {
164 (Mode::Open, _) => Admission::Live(WriteSlot(self)),
165 (Mode::Closed, Class::Queueable(_)) if !replay => Admission::Queue,
166 (Mode::Closed, _) => Admission::Busy,
167 (Mode::Draining, Class::Queueable(_)) if !replay => Admission::Queue,
168 (Mode::Draining, _) => Admission::Live(WriteSlot(self)),
169 };
170 if matches!(admission, Admission::Live(_)) {
171 self.in_flight.fetch_add(1, Ordering::SeqCst);
172 }
173 admission
174 }
175
176 fn enqueue(&self, entry: &Entry) -> anyhow::Result<bool> {
178 let mode = self.mode();
179 if *mode == Mode::Open {
180 return Ok(false);
181 }
182 let Some(dir) = &self.queue_dir else {
183 anyhow::bail!("this daemon has no write queue");
184 };
185 write_queue::push(dir, entry, self.recipient.as_ref())?;
186 Ok(true)
187 }
188
189 fn mode(&self) -> MutexGuard<'_, Mode> {
190 match self.mode.lock() {
191 Ok(g) => g,
192 Err(poisoned) => poisoned.into_inner(),
193 }
194 }
195}
196
197fn classify(method: &Method, path: &str) -> Class {
200 if method == Method::GET || method == Method::HEAD {
201 return Class::Read;
202 }
203 match (method.as_str(), path) {
204 (
205 "POST",
206 "/v1/recall"
207 | "/v1/context"
208 | "/v1/daily/memories"
209 | "/v1/sync/export"
210 | "/v1/sync/snapshot"
211 | "/v1/sync/snapshot/apply"
212 | "/v1/maintenance/vacuum",
213 ) => Class::Read,
214 ("POST", "/v1/remember") => Class::Queueable("remember"),
215 ("POST", "/v1/notes") => Class::Queueable("note"),
216 ("POST", "/v1/associate") => Class::Queueable("associate"),
217 ("POST", "/v1/correct") => Class::Queueable("correct"),
218 ("POST", "/v1/ingest") => Class::Queueable("ingest"),
219 ("DELETE", p) if p.starts_with("/v1/memory/") => Class::Queueable("forget"),
220 _ => Class::Refused,
221 }
222}
223
224pub async fn hold_writes(State(state): State<Arc<AppState>>, req: Request, next: Next) -> Response {
225 let class = classify(req.method(), req.uri().path());
226 if class == Class::Read {
227 return next.run(req).await;
228 }
229 let exempt = passes_closed_clock(req.uri().path());
230 if !exempt && !state.clock.is_open() {
231 return clock_held();
232 }
233 let replay = req.headers().contains_key(REPLAY_HEADER);
234 let mut req = req;
235 loop {
236 match state.gate.admit(class, replay) {
237 Admission::Live(slot) => {
238 let response = next.run(req).await;
239 drop(slot);
240 return unless_clock_closed(&state.clock, exempt, response);
241 }
242 Admission::Busy => return busy(),
243 Admission::Queue => {}
244 }
245 let Class::Queueable(tool) = class else {
246 return busy();
247 };
248 let (parts, body) = req.into_parts();
249 let bytes = match axum::body::to_bytes(body, MAX_QUEUED_BODY).await {
250 Ok(b) => b,
251 Err(e) => return error(StatusCode::PAYLOAD_TOO_LARGE, &format!("{e}")),
252 };
253 let entry = match queued_entry(tool, &parts, &bytes) {
254 Ok(entry) => entry,
255 Err(e) => return error(StatusCode::BAD_REQUEST, &e),
256 };
257 let saved = {
258 let (state, entry) = (state.clone(), entry.clone());
259 tokio::task::spawn_blocking(move || state.gate.enqueue(&entry)).await
260 };
261 match saved {
262 Ok(Ok(true)) => return queued(&entry),
263 Ok(Ok(false)) => req = Request::from_parts(parts, Body::from(bytes)),
264 Ok(Err(e)) => {
265 tracing::warn!("cannot queue a {tool} during store maintenance: {e:#}");
266 return busy();
267 }
268 Err(e) => {
269 tracing::warn!("queueing a {tool} during store maintenance failed: {e}");
270 return busy();
271 }
272 }
273 }
274}
275
276fn queued_entry(tool: &str, parts: &Parts, bytes: &Bytes) -> Result<Entry, String> {
280 let mut body: Option<Value> = if bytes.is_empty() {
281 None
282 } else {
283 Some(serde_json::from_slice(bytes).map_err(|e| format!("invalid JSON body: {e}"))?)
284 };
285 if names_its_write(tool) {
286 let Some(Value::Object(fields)) = body.as_mut() else {
287 return Err(format!("a {tool} needs a JSON object body"));
288 };
289 if !fields.get("id").is_some_and(Value::is_string) {
290 fields.insert(
291 "id".to_string(),
292 Value::String(uuid::Uuid::new_v4().to_string()),
293 );
294 }
295 }
296 if let Some(body) = body.as_mut() {
297 redact_strings(body);
298 }
299 Ok(Entry {
300 tool: tool.to_string(),
301 method: parts.method.to_string(),
302 path: parts.uri.path().to_string(),
303 query: parts.uri.query().map(redact_query),
304 body,
305 })
306}
307
308fn names_its_write(tool: &str) -> bool {
311 matches!(tool, "remember" | "note" | "correct")
312}
313
314fn redact_strings(value: &mut Value) {
315 match value {
316 Value::String(s) => *s = redact(s).text,
317 Value::Array(items) => items.iter_mut().for_each(redact_strings),
318 Value::Object(fields) => fields.values_mut().for_each(redact_strings),
319 _ => {}
320 }
321}
322
323fn redact_query(query: &str) -> String {
324 let Ok(mut url) = reqwest::Url::parse(&format!("http://queue/?{query}")) else {
325 return redact(query).text;
326 };
327 let pairs: Vec<(String, String)> = url
328 .query_pairs()
329 .map(|(k, v)| (k.into_owned(), redact(&v).text))
330 .collect();
331 url.query_pairs_mut().clear().extend_pairs(pairs);
332 url.query().unwrap_or_default().to_string()
333}
334
335fn queued(entry: &Entry) -> Response {
336 let mut reply = json!({ "queued": true, "reason": QUEUED_REASON });
337 if names_its_write(&entry.tool)
338 && let Some(id) = entry.body.as_ref().and_then(|b| b["id"].as_str())
339 {
340 reply["id"] = Value::String(id.to_string());
341 }
342 (StatusCode::ACCEPTED, Json(reply)).into_response()
343}
344
345fn busy() -> Response {
346 let mut response = error(
347 StatusCode::SERVICE_UNAVAILABLE,
348 "store maintenance is running; retry later",
349 );
350 response
351 .headers_mut()
352 .insert(header::RETRY_AFTER, HeaderValue::from(RETRY_AFTER_SECS));
353 response
354}
355
356fn passes_closed_clock(path: &str) -> bool {
359 matches!(
360 path,
361 "/v1/sync/import"
362 | "/v1/sync/state"
363 | "/v1/sync/hello"
364 | "/v1/sync/accept-hello"
365 | "/v1/sync/ack"
366 | "/v1/sync/peer-in"
367 | "/v1/sync/push-report"
368 )
369}
370
371pub(crate) fn clock_held() -> Response {
372 let mut response = error(StatusCode::SERVICE_UNAVAILABLE, CLOCK_HELD_REASON);
373 response.headers_mut().insert(
374 header::RETRY_AFTER,
375 HeaderValue::from(CLOCK_RETRY_AFTER_SECS),
376 );
377 response
378}
379
380fn unless_clock_closed(clock: &ClockGate, exempt: bool, response: Response) -> Response {
385 if !exempt && response.status() == StatusCode::INTERNAL_SERVER_ERROR && !clock.is_open() {
386 clock_held()
387 } else {
388 response
389 }
390}
391
392fn error(status: StatusCode, message: &str) -> Response {
393 (status, Json(json!({ "error": message }))).into_response()
394}
395
396#[cfg(test)]
397mod tests {
398 use second_brain_core::sqlite_store::clock::ClockUntrusted;
399
400 use super::*;
401
402 #[test]
403 fn writes_are_told_apart_from_reads() {
404 let post = Method::POST;
405 assert_eq!(classify(&Method::GET, "/v1/redaction"), Class::Read);
406 assert_eq!(classify(&post, "/v1/recall"), Class::Read);
407 assert_eq!(classify(&post, "/v1/maintenance/vacuum"), Class::Read);
408 assert_eq!(
409 classify(&post, "/v1/remember"),
410 Class::Queueable("remember")
411 );
412 assert_eq!(classify(&post, "/v1/notes"), Class::Queueable("note"));
413 assert_eq!(classify(&Method::GET, "/v1/notes"), Class::Read);
414 assert_eq!(
415 classify(&Method::DELETE, "/v1/memory/x"),
416 Class::Queueable("forget")
417 );
418 assert_eq!(classify(&post, "/v1/correct"), Class::Queueable("correct"));
419 assert_eq!(classify(&post, "/v1/sync/import"), Class::Refused);
420 assert_eq!(classify(&post, "/v1/some-new-route"), Class::Refused);
421 }
422
423 #[test]
424 fn a_queued_write_holds_no_secret() {
425 let token = ["gh", "p_"].concat() + "Qq7k3Jd9XwL2pVb8NzR4tYc6MhF1sGa5UeT0";
426 let remember = axum::http::Request::builder()
427 .method("POST")
428 .uri("/v1/remember")
429 .body(())
430 .unwrap()
431 .into_parts()
432 .0;
433 let body = json!({"content": format!("deploy with {token}"), "tags": [token.clone()]});
434 let entry = queued_entry("remember", &remember, &Bytes::from(body.to_string())).unwrap();
435 let forget = axum::http::Request::builder()
436 .method("DELETE")
437 .uri(format!("/v1/memory/x?hard=false&reason=leaked%20{token}"))
438 .body(())
439 .unwrap()
440 .into_parts()
441 .0;
442 let forget = queued_entry("forget", &forget, &Bytes::new()).unwrap();
443 let saved =
444 serde_json::to_string(&entry).unwrap() + &serde_json::to_string(&forget).unwrap();
445 assert!(!saved.contains(&token), "{saved}");
446 assert!(saved.contains("[REDACTED:github_token]"));
447 assert!(entry.body.unwrap()["id"].is_string());
448 assert!(forget.query.unwrap().starts_with("hard=false&reason="));
449 }
450
451 #[test]
452 fn a_queued_note_is_named_before_it_is_stored() {
453 let notes = axum::http::Request::builder()
454 .method("POST")
455 .uri("/v1/notes")
456 .body(())
457 .unwrap()
458 .into_parts()
459 .0;
460 let body = json!({"session_id": "s", "decision": "d"});
461 let entry = queued_entry("note", ¬es, &Bytes::from(body.to_string())).unwrap();
462 let id = entry.body.as_ref().unwrap()["id"]
463 .as_str()
464 .unwrap()
465 .to_string();
466 assert_eq!(queued(&entry).status(), StatusCode::ACCEPTED);
467 let again = queued_entry(
468 "note",
469 ¬es,
470 &Bytes::from(entry.body.unwrap().to_string()),
471 );
472 assert_eq!(again.unwrap().body.unwrap()["id"], id.as_str());
473 }
474
475 #[test]
476 fn a_queued_correct_gets_a_client_id_it_reports() {
477 let parts = axum::http::Request::builder()
478 .method("POST")
479 .uri("/v1/correct")
480 .body(())
481 .unwrap()
482 .into_parts()
483 .0;
484 let body = json!({"memory_id": "m", "content": "fixed", "evidence": "src/lib.rs:4"});
485 let entry = queued_entry("correct", &parts, &Bytes::from(body.to_string())).unwrap();
486 let id = entry.body.as_ref().unwrap()["id"]
487 .as_str()
488 .unwrap()
489 .to_string();
490 assert!(uuid::Uuid::parse_str(&id).is_ok());
491 let reply = queued(&entry);
492 assert_eq!(reply.status(), StatusCode::ACCEPTED);
493 }
494
495 struct NeverSynced;
496
497 impl crate::clock_gate::TimeSignals for NeverSynced {
498 fn now_micros(&self) -> i64 {
499 0
500 }
501
502 fn ntp_synced(&self) -> bool {
503 false
504 }
505
506 fn rtc_secs(&self) -> Option<i64> {
507 None
508 }
509 }
510
511 fn closed_clock(dir: &std::path::Path) -> Arc<ClockGate> {
512 ClockGate::new(dir, Arc::new(NeverSynced), i64::MAX)
513 }
514
515 fn retry_after(response: &Response) -> Option<&str> {
516 response
517 .headers()
518 .get(header::RETRY_AFTER)
519 .map(|v| v.to_str().unwrap())
520 }
521
522 #[test]
523 fn only_sync_routes_that_mint_nothing_or_carry_a_hello_pass_a_closed_clock() {
524 for path in [
525 "/v1/sync/import",
526 "/v1/sync/state",
527 "/v1/sync/hello",
528 "/v1/sync/accept-hello",
529 "/v1/sync/ack",
530 "/v1/sync/peer-in",
531 "/v1/sync/push-report",
532 ] {
533 assert!(passes_closed_clock(path), "{path}");
534 }
535 for path in [
536 "/v1/remember",
537 "/v1/ingest",
538 "/v1/memory/x",
539 "/v1/sync/compact",
540 "/v1/sync/prune-relations",
541 "/v1/maintenance/repair",
542 ] {
543 assert!(!passes_closed_clock(path), "{path}");
544 }
545 }
546
547 #[test]
548 fn a_held_write_is_told_to_retry_in_thirty_seconds() {
549 let held = clock_held();
550 assert_eq!(held.status(), StatusCode::SERVICE_UNAVAILABLE);
551 assert_eq!(retry_after(&held), Some("30"));
552 }
553
554 #[test]
555 fn a_server_error_while_the_clock_is_closed_is_answered_as_a_held_write() {
556 let dir = tempfile::tempdir().unwrap();
557 let closed = closed_clock(dir.path());
558 assert!(!closed.is_open());
559 let failed = || error(StatusCode::INTERNAL_SERVER_ERROR, "store write failed");
560 let held = unless_clock_closed(&closed, false, failed());
561 assert_eq!(held.status(), StatusCode::SERVICE_UNAVAILABLE);
562 assert_eq!(retry_after(&held), Some("30"));
563
564 let refused = unless_clock_closed(&closed, false, error(StatusCode::BAD_REQUEST, "bad"));
565 assert_eq!(refused.status(), StatusCode::BAD_REQUEST);
566
567 let open = ClockGate::open_for_tests();
568 let failed = unless_clock_closed(&open, false, failed());
569 assert_eq!(failed.status(), StatusCode::INTERNAL_SERVER_ERROR);
570 }
571
572 #[test]
573 fn a_server_error_on_a_sync_route_that_passes_a_closed_clock_stays_a_server_error() {
574 let dir = tempfile::tempdir().unwrap();
575 let closed = closed_clock(dir.path());
576 let failed = error(StatusCode::INTERNAL_SERVER_ERROR, "disk I/O error");
577 let response = unless_clock_closed(&closed, passes_closed_clock("/v1/sync/import"), failed);
578 assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
579 assert_eq!(retry_after(&response), None);
580 }
581
582 #[test]
583 fn a_handler_error_carrying_clock_untrusted_is_a_held_write() {
584 let untrusted = anyhow::Error::new(ClockUntrusted).context("storing a memory");
585 let held = crate::routes::internal_error(untrusted);
586 assert_eq!(held.status(), StatusCode::SERVICE_UNAVAILABLE);
587 assert_eq!(retry_after(&held), Some("30"));
588
589 let other = crate::routes::internal_error(anyhow::anyhow!("database is locked"));
590 assert_eq!(other.status(), StatusCode::INTERNAL_SERVER_ERROR);
591 }
592
593 #[test]
594 fn closing_waits_for_writes_in_flight() {
595 let gate = Arc::new(WriteGate::default());
596 let slot_gate = gate.clone();
597 let (entered, wait) = std::sync::mpsc::channel();
598 let writer = std::thread::spawn(move || {
599 let _slot = slot_gate.try_enter().unwrap();
600 entered.send(()).unwrap();
601 std::thread::sleep(Duration::from_millis(200));
602 });
603 wait.recv().unwrap();
604 let started = std::time::Instant::now();
605 let closed = gate.close();
606 assert!(started.elapsed() >= Duration::from_millis(100));
607 assert!(gate.try_enter().is_none());
608 writer.join().unwrap();
609 drop(closed);
610 assert!(gate.try_enter().is_some());
611 }
612
613 #[test]
614 fn after_maintenance_writes_queue_until_the_queue_drains() {
615 let gate = WriteGate::default();
616 drop(gate.close());
617 assert!(matches!(
618 gate.admit(Class::Queueable("remember"), false),
619 Admission::Queue
620 ));
621 assert!(matches!(
622 gate.admit(Class::Queueable("remember"), true),
623 Admission::Live(_)
624 ));
625 gate.open_when_drained(|| false);
626 assert!(matches!(
627 gate.admit(Class::Queueable("remember"), false),
628 Admission::Queue
629 ));
630 gate.open_when_drained(|| true);
631 assert!(matches!(
632 gate.admit(Class::Queueable("remember"), false),
633 Admission::Live(_)
634 ));
635 }
636}