~ knotless Search/
↑↓ move↵ open⇧↵ all results

chadtmiller.com/hud

A remote MCP server that shows atproto records as interactive UI inside MCP Apps hosts

0
0
685 lines · 27.1 KB Raw History
//! The lines the server logs, kept to read back, for its operators
//! (`HUD_LOGS=on`): `place.hud.getLogs`, and the MCP tool `admin_logs`.
//!
//! Each line the server writes to stderr (`telemetry::keep_lines`) is kept
//! here too, in a SQLite file, `<HUD_DATA_DIR>/logs.db`, mode 0600, written
//! a second at a time off the requests' way. A write that can't keep up
//! lets the oldest lines it holds go, and never makes a request wait.
//!
//! What is kept is what stderr has (no token, query secret, header or
//! body), and for no longer than the journal keeps it: lines at info and
//! below, the most numerous, only the last [`KEEP`] (`HUD_LOGS_KEEP`);
//! every line only [`DAYS`] days. Operators are the DIDs
//! `HUD_OPERATOR_DIDS` names. A read is itself logged, `logs read`, with
//! who asked and for what.

use crate::Hud;
use crate::oauth::Account;
use crate::telemetry::{self, Fields, Level};
use crate::tools::{Args, Output, Refusal};
use rusqlite::{Connection, OptionalExtension, params};
use serde_json::{Map, Value, json};
use std::collections::VecDeque;
use std::path::Path;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant, SystemTime};

/// How often the lines logged are written.
pub const FLUSH: Duration = Duration::from_secs(1);

/// How often the oldest are let go.
pub const PRUNE: Duration = Duration::from_secs(60);

/// How many lines at info and below are kept, unless `HUD_LOGS_KEEP` says.
pub const KEEP: u64 = 500_000;

/// How many days any line is kept.
pub const DAYS: u64 = 30;

/// The most lines held between writes: a write that can't keep up lets
/// the oldest go rather than grow without end.
const PENDING_MAX: usize = 50_000;

/// The most lines a read answers.
pub const LIMIT_MAX: u64 = 500;

pub struct Logs {
    db: Mutex<Connection>,
    pending: Mutex<VecDeque<Vec<u8>>>,
    keep: u64,
}

impl Logs {
    /// The lines kept at `path`, a file of mode 0600, keeping `keep` at
    /// info and below.
    pub fn open(path: &Path, keep: u64) -> Result<Logs, String> {
        Logs::opened(path, keep).map_err(|e| format!("the logs at {}: {e}", path.display()))
    }

    fn opened(path: &Path, keep: u64) -> Result<Logs, Box<dyn std::error::Error>> {
        std::fs::create_dir_all(path.parent().unwrap_or(Path::new(".")))?;
        // Made 0600 before SQLite opens it, which gives its WAL the same.
        let mut o = std::fs::OpenOptions::new();
        o.create(true).append(true);
        #[cfg(unix)]
        std::os::unix::fs::OpenOptionsExt::mode(&mut o, 0o600);
        o.open(path)?;
        let db = Connection::open(path)?;
        db.busy_timeout(Duration::from_secs(5))?;
        db.execute_batch(
            "PRAGMA journal_mode = WAL;
             PRAGMA synchronous = NORMAL;
             CREATE TABLE IF NOT EXISTS line (
               id INTEGER PRIMARY KEY, at INTEGER NOT NULL, level INTEGER NOT NULL,
               message TEXT NOT NULL, trace TEXT, ms INTEGER, line TEXT NOT NULL);
             CREATE INDEX IF NOT EXISTS line_trace ON line (trace) WHERE trace IS NOT NULL;
             CREATE INDEX IF NOT EXISTS line_level ON line (level, id);
             CREATE INDEX IF NOT EXISTS line_message ON line (message, id);
             CREATE INDEX IF NOT EXISTS line_at ON line (at);",
        )?;
        Ok(Logs {
            db: Mutex::new(db),
            pending: Mutex::default(),
            keep,
        })
    }

    fn held(&self) -> std::sync::MutexGuard<'_, VecDeque<Vec<u8>>> {
        self.pending
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
    }

    fn db(&self) -> std::sync::MutexGuard<'_, Connection> {
        self.db
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
    }

    /// Holds `line`, one line as logged, for the next write.
    pub fn keep(&self, line: &[u8]) {
        let mut pending = self.held();
        if pending.len() >= PENDING_MAX {
            pending.pop_front();
        }
        pending.push_back(line.to_vec());
    }

    /// Writes the lines held, each with its level, message, trace and
    /// duration beside it, to find it by. A line that isn't JSON is kept as
    /// a message of its own. Lines a write fails to keep, as when another
    /// server holds the file past the busy timeout, are held again, ahead
    /// of those logged since, for the next. The file is held before the
    /// lines are taken, so two flushes write them in the order logged.
    pub fn flush(&self) -> rusqlite::Result<()> {
        let mut db = self.db();
        let batch = std::mem::take(&mut *self.held());
        let written = write(&mut db, &batch);
        if written.is_err() {
            let mut pending = self.held();
            let since = std::mem::replace(&mut *pending, batch);
            pending.extend(since);
            let over = pending.len().saturating_sub(PENDING_MAX);
            pending.drain(..over);
        }
        written
    }

    /// Lets go of what is past keeping: lines at info and below past the
    /// last `keep` of them, and any line older than [`DAYS`].
    pub fn prune(&self) -> rusqlite::Result<()> {
        let db = self.db();
        let since = now() - (86_400 * DAYS) as i64;
        db.execute("DELETE FROM line WHERE at < ?1", [since])?;
        let found = db.query_row(
            "SELECT id FROM line WHERE level <= ?1 ORDER BY id DESC LIMIT 1 OFFSET ?2",
            params![rank("INFO"), self.keep as i64],
            |r| r.get(0),
        );
        let last: Option<i64> = found.optional()?;
        let past = db.execute(
            "DELETE FROM line WHERE level <= ?1 AND id <= ?2",
            params![rank("INFO"), last.unwrap_or(0)],
        );
        past.map(|_| ())
    }

    /// The lines `asked` names, oldest first: all of one request's, by
    /// its trace, up to [`LIMIT_MAX`] unless asked for fewer, or the last
    /// of those of a message, a level or a duration.
    pub fn read(&self, asked: &Asked) -> rusqlite::Result<Vec<Value>> {
        let unasked = match asked.trace {
            Some(_) => LIMIT_MAX,
            None => 100,
        };
        let limit = asked.limit.unwrap_or(unasked).clamp(1, LIMIT_MAX) as i64;
        let db = self.db();
        let level = asked.level.as_deref().map_or(0, rank);
        // A statement for each way of asking, each by its own index: one
        // asking `?2 IS NULL OR message = ?2` could use none, and read
        // every line kept, newest first, for a message seldom logged.
        let sql = match (&asked.trace, &asked.message) {
            (Some(_), _) => {
                "SELECT line FROM line WHERE trace = ?1 AND level >= ?3 AND (?2 IS NULL OR message = ?2)
                 AND (?4 IS NULL OR ms >= ?4) ORDER BY id DESC LIMIT ?5"
            }
            (None, Some(_)) => {
                "SELECT line FROM line INDEXED BY line_message
                 WHERE message = ?2 AND level >= ?3 AND (?4 IS NULL OR ms >= ?4)
                 ORDER BY id DESC LIMIT ?5"
            }
            (None, None) => {
                "SELECT line FROM line WHERE level >= ?3 AND (?4 IS NULL OR ms >= ?4)
                 ORDER BY id DESC LIMIT ?5"
            }
        };
        let mut stmt = db.prepare_cached(sql)?;
        let min_ms = asked.min_ms.map(|ms| ms as i64);
        let p = params![asked.trace, asked.message, level, min_ms, limit];
        let rows = stmt.query_map(p, |r| r.get::<_, String>(0))?;
        let lines: rusqlite::Result<Vec<Value>> = rows
            .map(|r| r.map(|text| serde_json::from_str(&text).unwrap_or_default()))
            .collect();
        let mut lines = lines?;
        lines.reverse();
        Ok(lines)
    }

    /// Writes the lines held, saying to stderr alone why it couldn't: they
    /// are written with the next, unless too many wait.
    pub fn write_held(&self) {
        wrote(self.flush());
    }
}

/// Writes `pending` to `db` in one transaction: all of it or none.
fn write(db: &mut Connection, pending: &VecDeque<Vec<u8>>) -> rusqlite::Result<()> {
    let at = now();
    let tx = db.transaction()?;
    let mut stmt = tx.prepare_cached("INSERT INTO line VALUES (NULL, ?1, ?2, ?3, ?4, ?5, ?6)")?;
    for line in pending {
        let text = String::from_utf8_lossy(line);
        let v: Value =
            serde_json::from_str(text.trim()).unwrap_or_else(|_| json!({ "message": text.trim() }));
        let level = rank(v["level"].as_str().unwrap_or("INFO"));
        let message = v["message"].as_str().unwrap_or_default();
        let ms = v["duration_ms"].as_i64();
        let trace = v["trace_id"].as_str();
        stmt.execute(params![at, level, message, trace, ms, v.to_string()])?;
    }
    drop(stmt);
    tx.commit()
}

/// A level, as a number to compare: `ERROR` the highest.
fn rank(level: &str) -> i64 {
    match level.to_ascii_uppercase().as_str() {
        "ERROR" => 5,
        "WARN" => 4,
        "INFO" => 3,
        "DEBUG" => 2,
        _ => 1,
    }
}

/// Now, in seconds since the epoch: when a line was written.
fn now() -> i64 {
    let since = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH);
    since.unwrap_or_default().as_secs() as i64
}

/// Writes the lines held every `every`, and lets go of the oldest every
/// [`PRUNE`], at once the first time.
pub async fn flushing(logs: Arc<Logs>, every: Duration) {
    let mut pruned: Option<Instant> = None;
    loop {
        logs.write_held();
        if pruned.is_none_or(|t| t.elapsed() >= PRUNE) {
            wrote(logs.prune());
            pruned = Some(Instant::now());
        }
        tokio::time::sleep(every).await;
    }
}

/// Says, to stderr alone, why the lines were not written or let go: a
/// line logged about the log would be kept, and fail again.
fn wrote(done: rusqlite::Result<()>) {
    if let Err(err) = done {
        eprintln!("logs not kept: {err:#}");
    }
}

/// What a read asks for: at least one of `trace`, `message`, `level` and
/// `min_ms`.
#[derive(Default, Debug, PartialEq)]
pub struct Asked {
    /// All of one request's lines.
    pub trace: Option<String>,
    /// Only lines with this message: `request`, `outgoing`, `mcp tool`.
    pub message: Option<String>,
    /// Only lines at this level or above.
    pub level: Option<String>,
    /// Only lines that took this many milliseconds or more.
    pub min_ms: Option<u64>,
    /// How many, the last of them: at most 500, and unless asked, 100, or
    /// for a trace, 500.
    pub limit: Option<u64>,
}

/// The names a read is asked by, as `place.hud.getLogs` and `admin_logs`
/// take them.
const ASKED_BY: [&str; 5] = ["trace", "message", "level", "minMs", "limit"];

impl Asked {
    /// What `given` asks, each value checked. A name not in [`ASKED_BY`]
    /// is its caller's to refuse: the method's lexicon, or the tool's
    /// arguments (`Args::of`).
    pub fn of(given: &Map<String, Value>) -> Result<Asked, String> {
        let args = Args(given);
        let number = |name: &str, least: u64, most: u64| match given.get(name) {
            None | Some(Value::Null) => Ok(None),
            Some(v) => v
                .as_u64()
                .filter(|n| (least..=most).contains(n))
                .map(Some)
                .ok_or_else(|| format!("{name} must be an integer from {least} to {most}")),
        };
        let asked = Asked {
            trace: args.text("trace")?.map(str::to_string),
            message: args.text("message")?.map(str::to_string),
            level: args.text("level")?.map(str::to_string),
            min_ms: number("minMs", 0, u64::MAX)?,
            limit: number("limit", 1, LIMIT_MAX)?,
        };
        match asked.said().is_empty() {
            true => Err("Ask for a trace, a message, a level or minMs".into()),
            false => Ok(asked),
        }
    }

    /// What it asks, as the line telling of the read says it.
    fn said(&self) -> String {
        let parts = [
            self.trace.as_ref().map(|t| format!("trace={t}")),
            self.message.as_ref().map(|m| format!("message={m}")),
            self.level.as_ref().map(|l| format!("level={l}")),
            self.min_ms.map(|ms| format!("minMs={ms}")),
        ];
        parts.into_iter().flatten().collect::<Vec<_>>().join(" ")
    }
}

/// Why a read of the kept lines answered none.
#[derive(Debug, PartialEq)]
pub enum Unread {
    /// The caller is none of `HUD_OPERATOR_DIDS`.
    Forbidden,
    /// The server keeps none (`HUD_LOGS` off).
    NotKept,
    /// What was asked can't be read, as said.
    Invalid(String),
    /// The file could not be read or written.
    Failed(String),
}

impl Unread {
    /// What the caller is told.
    pub fn message(&self) -> String {
        match self {
            Unread::Forbidden => "Only HUD's operators read its logs".into(),
            Unread::NotKept => "This server keeps no logs (HUD_LOGS)".into(),
            Unread::Invalid(why) => why.clone(),
            Unread::Failed(why) => format!("The logs could not be read: {why}"),
        }
    }
}

/// `admin_logs`, the MCP tool an operator reads the kept lines with.
/// Listed for operators alone.
pub fn definition() -> Value {
    let text = |description: &str| json!({ "type": "string", "maxLength": 200, "description": description });
    json!({
        "name": "admin_logs",
        "title": "Read HUD's logs",
        "description": "As one of HUD's operators, the lines this server logged, oldest first, as JSON: all of one request's by its trace (the request, its tool call and the calls it made, with their times), or the last of a message, a level or a duration. Ask for at least one. Kept across deploys, for 30 days at most, fewer at info. Each read is logged, with who asked.",
        "inputSchema": {
            "type": "object",
            "properties": {
                "trace": text("All of one request's lines, by the trace ID each carries and its answer's x-trace-id names."),
                "message": text("Only lines with this message: request, outgoing, mcp tool, mcp tool failed, logs read."),
                "level": text("Only lines at this level or above: error, warn, info, debug or trace."),
                "minMs": { "type": "integer", "minimum": 0,
                           "description": "Only lines that took this many milliseconds or more." },
                "limit": { "type": "integer", "minimum": 1, "maximum": LIMIT_MAX,
                           "description": "How many, the last of those asked for: unless given, 500 for a trace and 100 otherwise." },
            },
            "additionalProperties": false,
        },
        "annotations": { "title": "Read HUD's logs", "readOnlyHint": true,
                         "destructiveHint": false, "idempotentHint": false, "openWorldHint": false },
    })
}

impl Hud {
    /// Whether `account` is one of HUD's operators (`HUD_OPERATOR_DIDS`).
    pub fn operator(&self, account: Option<&Account>) -> bool {
        account.is_some_and(|a| self.config.operators.contains(&a.did))
    }

    /// The lines `given` asks for ([`Asked::of`]), read by `account`: an
    /// operator's alone, and logged, `logs read`, with who asked and for
    /// what. What was logged up to now is written first, this read's own
    /// line with it.
    pub async fn read_logs(
        &self,
        account: &Account,
        given: &Map<String, Value>,
    ) -> Result<Vec<Value>, Unread> {
        if !self.operator(Some(account)) {
            return Err(Unread::Forbidden);
        }
        let logs = self.logs.clone().ok_or(Unread::NotKept)?;
        let asked = Asked::of(given).map_err(Unread::Invalid)?;
        let f = Fields {
            did: Some(&account.did),
            reason: Some(&asked.said()),
            ..Fields::default()
        };
        telemetry::note(Level::INFO, "logs read", &f);
        // SQLite's work, off the async workers.
        let read =
            tokio::task::spawn_blocking(move || logs.flush().and_then(|()| logs.read(&asked)));
        let read = read.await.expect("a read of the logs does not panic");
        read.map_err(|e| Unread::Failed(e.to_string()))
    }

    /// `admin_logs`: [`Hud::read_logs`] as a tool, asking the caller to sign
    /// in first.
    pub(crate) async fn admin_logs_tool(
        &self,
        arguments: Option<&Value>,
        account: Option<&Account>,
    ) -> Result<Output, Refusal> {
        let account = account.ok_or(Refusal::SignIn)?;
        let given = Args::of(arguments, &ASKED_BY)?;
        let lines = self
            .read_logs(account, given.0)
            .await
            .map_err(|e| Refusal::Error(e.message()))?;
        Ok(Output {
            text: format!("Lines logged: {}.", lines.len()),
            structured: json!({ "lines": lines }),
            meta: json!({}),
        })
    }
}

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

    fn line(level: &str, message: &str, trace: Option<&str>, ms: Option<u64>) -> Vec<u8> {
        let v = json!({ "timestamp": "2026-11-18T12:00:00Z", "level": level,
            "message": message, "trace_id": trace, "duration_ms": ms });
        format!("{v}\n").into_bytes()
    }

    fn asked(given: Value) -> Asked {
        Asked::of(given.as_object().unwrap()).unwrap()
    }

    fn messages(lines: &[Value]) -> Vec<String> {
        lines
            .iter()
            .map(|l| l["message"].as_str().unwrap_or("?").to_string())
            .collect()
    }

    #[test]
    fn keeps_reads_and_lets_go() {
        let dir = std::env::temp_dir().join(format!("hud-logs-{}", atproto::jose::random(6)));
        let path = dir.join("logs.db");
        let logs = Logs::open(&path, 3).unwrap();
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let mode = std::fs::metadata(&path).unwrap().permissions().mode();
            assert_eq!(mode & 0o777, 0o600);
        }
        logs.keep(&line("WARN", "outgoing", Some("t0"), Some(5000)));
        for i in 0..5u64 {
            logs.keep(&line("INFO", "request", Some("t1"), Some(i * 100)));
        }
        logs.keep(&line("WARN", "mcp tool failed", Some("t1"), Some(400)));
        logs.keep(&line("DEBUG", "outgoing", Some("t1"), Some(20)));
        logs.keep(b"not json\n");
        logs.flush().unwrap();
        // Again: a write with nothing held writes nothing.
        logs.write_held();
        let read = |given: Value| logs.read(&asked(given)).unwrap();
        let trace = read(json!({ "trace": "t1" }));
        assert_eq!(trace.len(), 7);
        assert_eq!(messages(&trace)[5..], ["mcp tool failed", "outgoing"]);
        let one = read(json!({ "trace": "t1", "message": "outgoing", "minMs": 10 }));
        assert_eq!(messages(&one), ["outgoing"]);
        let slow = read(json!({ "minMs": 400 }));
        assert_eq!(messages(&slow), ["outgoing", "request", "mcp tool failed"]);
        let warned = read(json!({ "level": "warn", "limit": 1 }));
        assert_eq!(messages(&warned), ["mcp tool failed"]);
        let plain = read(json!({ "message": "not json" }));
        assert_eq!(plain[0]["message"], "not json");

        // Past keeping: all but the last three at info and below; what
        // warned stays.
        logs.prune().unwrap();
        let left = read(json!({ "level": "trace" }));
        assert_eq!(
            messages(&left),
            [
                "outgoing",
                "request",
                "mcp tool failed",
                "outgoing",
                "not json"
            ]
        );
        // With nothing past keeping, nothing goes.
        logs.prune().unwrap();
        assert_eq!(read(json!({ "level": "trace" })).len(), 5);
        // A line older than the days kept goes, whatever its level.
        logs.db()
            .execute("UPDATE line SET at = 0 WHERE level = 4", [])
            .unwrap();
        logs.prune().unwrap();
        assert_eq!(read(json!({ "level": "trace" })).len(), 3);
        // Opened again, the lines are there.
        drop(logs);
        let again = Logs::open(&path, 3).unwrap();
        assert_eq!(
            again
                .read(&asked(json!({ "level": "trace" })))
                .unwrap()
                .len(),
            3
        );
        std::fs::remove_dir_all(dir).unwrap();
    }

    /// A write that fails keeps what it held, ahead of what was logged
    /// since, for the next; and still holds only so many.
    #[test]
    fn a_failed_write_keeps_its_lines() {
        let dir = std::env::temp_dir().join(format!("hud-logs-{}", atproto::jose::random(6)));
        let path = dir.join("logs.db");
        let logs = Logs::open(&path, KEEP).unwrap();
        let other = Connection::open(&path).unwrap();
        logs.keep(&line("INFO", "first", Some("t"), None));
        other
            .execute_batch("ALTER TABLE line RENAME TO away")
            .unwrap();
        assert!(logs.flush().is_err());
        assert!(logs.prune().is_err());
        assert!(logs.read(&Asked::default()).is_err());
        logs.keep(&line("INFO", "second", Some("t"), None));
        other
            .execute_batch("ALTER TABLE away RENAME TO line")
            .unwrap();
        logs.flush().unwrap();
        let trace = logs.read(&asked(json!({ "trace": "t" }))).unwrap();
        assert_eq!(messages(&trace), ["first", "second"]);

        other
            .execute_batch("ALTER TABLE line RENAME TO away")
            .unwrap();
        for _ in 0..PENDING_MAX {
            logs.keep(b"{}");
        }
        logs.write_held();
        logs.keep(b"{}");
        assert_eq!(logs.held().len(), PENDING_MAX);
        std::fs::remove_dir_all(dir).unwrap();
    }

    /// A trace reads up to the most a read answers unless asked for
    /// fewer; anything else, the last 100.
    #[test]
    fn a_trace_reads_whole() {
        let dir = std::env::temp_dir().join(format!("hud-logs-{}", atproto::jose::random(6)));
        let logs = Logs::open(&dir.join("logs.db"), KEEP).unwrap();
        for _ in 0..150 {
            logs.keep(&line("INFO", "request", Some("t"), None));
        }
        logs.flush().unwrap();
        let read = |given: Value| logs.read(&asked(given)).unwrap().len();
        assert_eq!(read(json!({ "trace": "t" })), 150);
        assert_eq!(read(json!({ "trace": "t", "limit": 10 })), 10);
        assert_eq!(read(json!({ "message": "request" })), 100);
        std::fs::remove_dir_all(dir).unwrap();
    }

    #[test]
    fn a_file_that_cannot_be_opened() {
        let dir = std::env::temp_dir().join(format!("hud-logs-{}", atproto::jose::random(6)));
        std::fs::create_dir_all(dir.join("logs.db")).unwrap();
        let why = Logs::open(&dir.join("logs.db"), KEEP).err().unwrap();
        assert!(why.starts_with("the logs at "), "{why}");
        // Nor where its directory would be a file.
        std::fs::write(dir.join("file"), "").unwrap();
        assert!(Logs::open(&dir.join("file/logs.db"), KEEP).is_err());
        // Nor a file that isn't SQLite.
        std::fs::write(dir.join("text"), "not a database, at all, no").unwrap();
        assert!(Logs::open(&dir.join("text"), KEEP).is_err());
        std::fs::remove_dir_all(dir).unwrap();
    }

    #[test]
    fn asking() {
        let refused = |given: Value| Asked::of(given.as_object().unwrap()).unwrap_err();
        assert_eq!(
            refused(json!({})),
            "Ask for a trace, a message, a level or minMs"
        );
        assert_eq!(
            refused(json!({ "limit": 5 })),
            "Ask for a trace, a message, a level or minMs"
        );
        assert_eq!(refused(json!({ "level": 3 })), "level must be a string");
        assert_eq!(
            refused(json!({ "trace": "t", "limit": 501 })),
            "limit must be an integer from 1 to 500"
        );
        assert_eq!(
            refused(json!({ "minMs": -1 })),
            format!("minMs must be an integer from 0 to {}", u64::MAX)
        );
        let all = asked(json!({ "trace": "t", "message": "request", "level": "warn",
            "minMs": 100, "limit": null }));
        assert_eq!(all.said(), "trace=t message=request level=warn minMs=100");
        let ranks: Vec<i64> = ["ERROR", "warn", "INFO", "DEBUG", "TRACE"]
            .into_iter()
            .map(rank)
            .collect();
        assert_eq!(ranks, [5, 4, 3, 2, 1]);
        wrote(Ok(()));
        wrote(Err(rusqlite::Error::InvalidQuery));
        assert_eq!(
            Unread::NotKept.message(),
            "This server keeps no logs (HUD_LOGS)"
        );
        assert_eq!(
            Unread::Forbidden.message(),
            "Only HUD's operators read its logs"
        );
        assert_eq!(
            Unread::Failed("locked".into()).message(),
            "The logs could not be read: locked"
        );
        assert_eq!(definition()["name"], "admin_logs");
    }

    /// `admin_logs` as `/mcp` calls it: the operator's alone, asking whoever
    /// is signed out to sign in; and a server keeping no lines says so.
    #[tokio::test]
    async fn the_tool_reads_for_operators() {
        let pds = "http://127.0.0.1:9";
        let server = |logs: bool| {
            crate::tests::hud_with(pds, |c| {
                c.oauth = true;
                c.logs = logs;
                c.operators = vec![crate::tests::ALICE.into()];
            })
        };
        let hud = server(true);
        let auth = hud.oauth.as_ref().unwrap();
        let account = |did: &str| {
            let token = auth.signed_in_offline_at(did, None, false, pds);
            auth.account(&token).unwrap()
        };
        let (alice, bob) = (account(crate::tests::ALICE), account("did:plc:bob"));
        let call = |args: Value, who: Option<&Account>| {
            let (hud, who) = (hud.clone(), who.cloned());
            async move {
                let called = hud.call_tool("admin_logs", Some(&args), who.as_ref());
                called.await.unwrap()
            }
        };
        let refused = |why: &str| Some(Refusal::Error(why.into()));
        let warned = json!({ "level": "warn" });
        assert_eq!(
            call(warned.clone(), None).await.err(),
            Some(Refusal::SignIn)
        );
        assert_eq!(
            call(warned.clone(), Some(&bob)).await.err(),
            refused("Only HUD's operators read its logs")
        );
        assert_eq!(
            call(json!({ "who": 1 }), Some(&alice)).await.err(),
            refused("Unknown argument: who")
        );
        let logs = hud.logs.as_ref().unwrap();
        logs.keep(&line("WARN", "outgoing", Some("t"), Some(2000)));
        let out = call(warned, Some(&alice)).await.unwrap();
        assert_eq!(out.text, "Lines logged: 1.");
        assert_eq!(out.structured["lines"][0]["message"], "outgoing");
        assert_eq!(out.meta["viewer"]["did"], crate::tests::ALICE);
        let none = server(false);
        let given = json!({ "level": "info" });
        let read = none.read_logs(&alice, given.as_object().unwrap()).await;
        assert_eq!(read, Err(Unread::NotKept));
    }

    #[tokio::test]
    async fn flushes_and_prunes_as_it_goes() {
        let dir = std::env::temp_dir().join(format!("hud-logs-{}", atproto::jose::random(6)));
        let logs = Arc::new(Logs::open(&dir.join("logs.db"), KEEP).unwrap());
        logs.keep(&line("INFO", "flushed", None, None));
        let going = tokio::spawn(flushing(logs.clone(), Duration::from_millis(10)));
        tokio::time::sleep(Duration::from_millis(100)).await;
        going.abort();
        let read = logs.read(&asked(json!({ "message": "flushed" }))).unwrap();
        assert_eq!(read.len(), 1);
        std::fs::remove_dir_all(dir).unwrap();
    }
}