OXYGENHUB

Coverage / crates/spectra-mcp/src/api.rs 91.9%

465 of 506 lines run, 74 of 162 functions · run #28 on main · run missed

1
//! The JSON API (spec §18): what spectra-vscode, scripts and SpectraHub
2
//! read and write. Every request is a signed request (spec §8.5); a read
3
//! may instead carry the owner's Radar session. Errors are RFC 7807
4
//! problems; lists page with `?after=`; reads carry an ETag.
5
6
use crate::http::{AppState, PeerInfo};
7
use axum::body::Bytes;
8
use axum::extract::connect_info::ConnectInfo;
9
use axum::extract::{Path, Query, State};
10
use axum::http::{header, HeaderMap, StatusCode};
11
use axum::response::sse::{Event as SseEvent, KeepAlive, Sse};
12
use axum::response::{IntoResponse, Response};
13
use axum::routing::{get, post};
14
use axum::Router;
15
use futures::StreamExt;
16
use serde::Deserialize;
17
use spectra_api as api;
18
use spectra_core::authn::Caller;
19
use spectra_core::conversation::{self as conv, Author, Post, Posted, Signer};
20
use spectra_core::event::{Auth, Method};
21
use spectra_core::ids::now_ms;
22
use spectra_core::principals::Principal;
23
use std::time::Duration;
24
2520×
pub fn router(state: AppState) -> Router {
2620×
    Router::new()
2720×
        .route("/api/v1/health", get(health))
2820×
        .route("/api/v1/version", get(version))
2920×
        .route("/api/v1/brief", get(brief))
3020×
        .route("/api/v1/agents", get(agents))
3120×
        .route("/api/v1/projects", get(projects))
3220×
        .route("/api/v1/channels", get(channels))
3320×
        .route("/api/v1/channels/{name}/messages", get(messages).post(post_message))
3420×
        .route("/api/v1/threads/{id}", get(thread))
3520×
        .route("/api/v1/inbox", get(inbox))
3620×
        .route("/api/v1/inbox/ack", post(ack))
3720×
        .route("/api/v1/search", get(search))
3820×
        .route("/api/v1/events", get(events))
3920×
        .route("/api/v1/admin/verify", get(admin_verify))
4020×
        .route("/api/v1/briefs", get(briefs).put(set_brief))
4120×
        .with_state(state)
4220×
}
43
44
/// An RFC 7807 problem.
456×
pub fn problem(status: StatusCode, title: &str, detail: Option<String>) -> Response {
466×
    let p = api::Problem { kind: "about:blank".into(), title: title.into(), status: status.as_u16(), detail };
476×
    let mut r = (status, axum::Json(p)).into_response();
486×
    r.headers_mut().insert(header::CONTENT_TYPE, "application/problem+json".parse().unwrap());
496×
    r
506×
}
51
521×
fn bad(e: anyhow::Error) -> Response {
531×
    problem(StatusCode::BAD_REQUEST, "the request cannot be done", Some(format!("{e:#}")))
541×
}
55
56
/// JSON with an ETag; 304 when the client has it already.
5739×
fn json_etag<T: serde::Serialize>(headers: &HeaderMap, v: &T) -> Response {
5839×
    let body = serde_json::to_vec(v).unwrap_or_default();
5939×
    let tag = format!("\"{}\"", &blake3_hex(&body)[..32]);
6039×
    if headers.get(header::IF_NONE_MATCH).and_then(|h| h.to_str().ok()) == Some(tag.as_str()) {
611×
        return StatusCode::NOT_MODIFIED.into_response();
6238×
    }
6338×
    ([(header::CONTENT_TYPE, "application/json".to_string()), (header::ETAG, tag)], body).into_response()
6439×
}
65
6639×
fn blake3_hex(b: &[u8]) -> String {
6739×
    hex::encode(*spectra_core::event::hash_body_plain(b))
6839×
}
69
70
/// Who is asking: a signed request, or for a read the owner's session.
7159×
async fn caller(
7259×
    st: &AppState,
7359×
    peer: PeerInfo,
7459×
    headers: &HeaderMap,
7559×
    method_path: &str,
7659×
    body: &[u8],
7759×
    read: bool,
7859×
) -> Result<Caller, Response> {
7959×
    if read && headers.get("spectra-key").is_none() {
801×
        let cookie = headers.get(header::COOKIE).and_then(|c| c.to_str().ok()).unwrap_or("");
811×
        let id = cookie.split(';').map(str::trim).find_map(|kv| kv.strip_prefix("spectra_session=")).unwrap_or("");
821×
        if let Some(s) = st.sessions.get(id, now_ms()) {
830×
            if !crate::http::origin_ok(headers, &st.origins) {
840×
                return Err(problem(StatusCode::FORBIDDEN, "this origin may not read Spectra", None));
850×
            }
860×
            let key = spectra_core::identity::KeyId(s.key);
870×
            let principal = st
880×
                .daemon
890×
                .principals
900×
                .read()
910×
                .await
920×
                .principal(&key, now_ms())
930×
                .map_err(|why| problem(StatusCode::UNAUTHORIZED, "not authenticated", Some(why)))?;
940×
            return Ok(Caller {
950×
                principal,
960×
                auth: Auth { key: Some(s.key), method: Method::Session, assurance: 2, proof: Some(s.proof) },
970×
                learn_uid: None,
980×
            });
991×
        }
10058×
    }
10159×
    let signed = headers.get("spectra-key").is_some();
10259×
    crate::http::authenticate_why(st, peer, headers, method_path, body).await.map_err(|(status, why)| {
1032×
        if status == StatusCode::FORBIDDEN {
1040×
            problem(status, "this origin may not call Spectra", None)
1052×
        } else if signed {
106
            // A signed request is told why its signature was not enough.
1071×
            problem(StatusCode::UNAUTHORIZED, "not authenticated", Some(why))
108
        } else {
1091×
            problem(
110
                StatusCode::UNAUTHORIZED,
1111×
                "not authenticated",
1121×
                Some("sign the request with your key (spectra's client does), or open Radar with `spectra open`".into()),
113
            )
114
        }
1152×
    })
11659×
}
117
11859×
fn path_of(uri: &axum::http::Uri) -> String {
11959×
    uri.path_and_query().map(|p| p.as_str().to_string()).unwrap_or_else(|| uri.path().to_string())
12059×
}
121
122
macro_rules! who {
123
    ($st:expr, $peer:expr, $headers:expr, $uri:expr, $method:literal, $body:expr, $read:expr) => {
124
        match caller(&$st, $peer, &$headers, &format!("{} {}", $method, path_of(&$uri)), $body, $read).await {
125
            Ok(c) => c,
126
            Err(r) => return r,
127
        }
128
    };
129
}
130
131
/// `GET /api/v1/admin/verify`: the owner asks the daemon to verify its
132
/// ledger (spec §8.6): what `spectra admin verify` prints, from afar.
1331×
async fn admin_verify(
1341×
    State(st): State<AppState>,
1351×
    ConnectInfo(peer): ConnectInfo<PeerInfo>,
1361×
    headers: HeaderMap,
1371×
    uri: axum::http::Uri,
1381×
) -> Response {
1391×
    let c = who!(st, peer, headers, uri, "GET", b"", false);
1401×
    if !matches!(c.principal, Principal::Owner { .. }) {
1410×
        return problem(StatusCode::FORBIDDEN, "only the owner verifies the ledger", None);
1421×
    }
1431×
    let ledger = match spectra_core::ledger::Ledger::open_read_only(&st.daemon.data.join("spectra.db")).await {
1441×
        Ok(l) => l,
1450×
        Err(e) => return bad(e),
146
    };
1471×
    match ledger.verify(&mut spectra_core::principals::Principals::default()).await {
1481×
        Ok(v) => axum::Json(v).into_response(),
1490×
        Err(e) => bad(e),
150
    }
1511×
}
152
153
/// `GET /api/v1/briefs`: the overall brief and every project's (spec §12.1).
1542×
async fn briefs(
1552×
    State(st): State<AppState>,
1562×
    ConnectInfo(peer): ConnectInfo<PeerInfo>,
1572×
    headers: HeaderMap,
1582×
    uri: axum::http::Uri,
1592×
) -> Response {
1602×
    let _ = who!(st, peer, headers, uri, "GET", b"", true);
1612×
    let pool = st.daemon.ledger.pool();
1622×
    let overall = spectra_core::rules::layer(pool, None).await.ok().flatten();
1632×
    let rows: Vec<(String, String)> = sqlx::query_as("SELECT project, text FROM briefs WHERE layer = 'project' ORDER BY project")
1642×
        .fetch_all(pool)
1652×
        .await
1662×
        .unwrap_or_default();
1672×
    json_etag(
1682×
        &headers,
1694×
        &api::Briefs { overall, projects: rows.into_iter().map(|(project, text)| api::ProjectBrief { project, text }).collect() },
170
    )
1712×
}
172
173
/// `PUT /api/v1/briefs`: the owner sets a brief; the signed request is the
174
/// event's proof.
1753×
async fn set_brief(
1763×
    State(st): State<AppState>,
1773×
    ConnectInfo(peer): ConnectInfo<PeerInfo>,
1783×
    headers: HeaderMap,
1793×
    uri: axum::http::Uri,
1803×
    body: Bytes,
1813×
) -> Response {
1823×
    let c = who!(st, peer, headers, uri, "PUT", &body, false);
1833×
    if !matches!(c.principal, Principal::Owner { .. }) {
1841×
        return problem(StatusCode::FORBIDDEN, "only the owner sets a brief", None);
1852×
    }
1862×
    let b: api::SetBrief = match serde_json::from_slice(&body) {
1872×
        Ok(b) => b,
1880×
        Err(e) => return problem(StatusCode::BAD_REQUEST, "not a brief", Some(e.to_string())),
189
    };
1902×
    if let Err(e) = spectra_core::rules::check(&b.text) {
1910×
        return problem(StatusCode::BAD_REQUEST, "too long", Some(e.to_string()));
1922×
    }
1932×
    let project = b.project.filter(|p| !p.is_empty());
1942×
    if let Some(p) = &project {
1952×
        let known: Option<String> = sqlx::query_scalar("SELECT name FROM projects WHERE name = ?")
1962×
            .bind(p)
1972×
            .fetch_optional(st.daemon.ledger.pool())
1982×
            .await
1992×
            .unwrap_or(None);
2002×
        if known.is_none() {
2011×
            return problem(StatusCode::NOT_FOUND, "no such project", Some(p.clone()));
2021×
        }
2030×
    }
2041×
    let mut e = spectra_core::event::NewEvent::system("brief.set", serde_json::json!({ "project": project, "text": b.text }))
2051×
        .by(c.principal.actor(), c.auth.clone());
2061×
    e.project = project.clone();
2071×
    match st.daemon.ledger.append_one(e).await {
2081×
        Ok(ev) => axum::Json(serde_json::json!({ "seq": ev.seq })).into_response(),
2090×
        Err(e) => bad(e),
210
    }
2113×
}
212
2131×
async fn health() -> Response {
2141×
    axum::Json(serde_json::json!({ "ok": true })).into_response()
2151×
}
216
2171×
async fn version() -> Response {
218
    axum::Json(api::Version {
2191×
        version: env!("CARGO_PKG_VERSION").into(),
220
        ledger_format: spectra_core::LEDGER_FORMAT,
2214×
        mcp_protocol_versions: crate::PROTOCOL_VERSIONS.iter().map(|v| v.to_string()).collect(),
222
    })
2231×
    .into_response()
2241×
}
225
22612×
async fn agent_list(st: &AppState) -> Vec<api::Agent> {
227
    #[allow(clippy::type_complexity)]
22812×
    let rows: Vec<(String, String, String, String, String, Option<String>, Option<i64>)> = sqlx::query_as(
22912×
        "SELECT a.name, a.owner_name, a.key, a.kind, a.project, p.status_text, a.disabled_ms FROM agents a LEFT JOIN presence p ON p.agent = a.name ORDER BY a.name",
23012×
    )
23112×
    .fetch_all(st.daemon.ledger.pool())
23212×
    .await
23312×
    .unwrap_or_default();
23412×
    let presence = st.daemon.presence.lock().await;
23512×
    let principals = st.daemon.principals.read().await;
23612×
    let now = now_ms();
23712×
    rows.into_iter()
23813×
        .map(|(name, owner, key, kind, project, status, disabled)| {
23913×
            let k = spectra_core::identity::KeyId::from_hex(&key);
24013×
            let state = match k.map(|k| principals.principal(&k, now)) {
24112×
                Some(Ok(_)) => "ok".to_string(),
2421×
                Some(Err(why)) => why,
2430×
                None => "a malformed key".into(),
244
            };
24513×
            let delegation_expires = k.and_then(|k| principals.owner().and_then(|o| o.delegate(&k)).and_then(|d| d.expires));
246
            api::Agent {
24713×
                display: format!("{name} · {owner}'s agent"),
24813×
                presence: if disabled.is_some() { "offline".into() } else { presence.state(&name, now).into() },
24913×
                disabled: disabled.is_some(),
25013×
                name,
25113×
                owner,
25213×
                key,
25313×
                kind,
25413×
                project,
25513×
                status,
25613×
                state,
25713×
                delegation_expires,
258
            }
25913×
        })
26012×
        .collect()
26112×
}
262
26311×
async fn agents(
26411×
    State(st): State<AppState>,
26511×
    ConnectInfo(peer): ConnectInfo<PeerInfo>,
26611×
    headers: HeaderMap,
26711×
    uri: axum::http::Uri,
26811×
) -> Response {
26911×
    let _ = who!(st, peer, headers, uri, "GET", b"", true);
2709×
    json_etag(&headers, &agent_list(&st).await)
27111×
}
272
27312×
async fn projects(
27412×
    State(st): State<AppState>,
27512×
    ConnectInfo(peer): ConnectInfo<PeerInfo>,
27612×
    headers: HeaderMap,
27712×
    uri: axum::http::Uri,
27812×
) -> Response {
27912×
    let _ = who!(st, peer, headers, uri, "GET", b"", true);
28012×
    let pool = st.daemon.ledger.pool();
28112×
    let rows: Vec<(String, Option<String>, String, Option<String>)> =
28212×
        sqlx::query_as("SELECT name, path, description, url FROM projects ORDER BY name").fetch_all(pool).await.unwrap_or_default();
28312×
    let mut out = Vec::new();
28413×
    for (name, path, description, url) in rows {
28513×
        let depends_on = sqlx::query_scalar("SELECT depends_on FROM project_relations WHERE project = ? ORDER BY 1")
28613×
            .bind(&name)
28713×
            .fetch_all(pool)
28813×
            .await
28913×
            .unwrap_or_default();
29013×
        let depended_on_by = sqlx::query_scalar("SELECT project FROM project_relations WHERE depends_on = ? ORDER BY 1")
29113×
            .bind(&name)
29213×
            .fetch_all(pool)
29313×
            .await
29413×
            .unwrap_or_default();
29513×
        let agents = sqlx::query_scalar("SELECT name FROM agents WHERE project = ? AND disabled_ms IS NULL ORDER BY name")
29613×
            .bind(&name)
29713×
            .fetch_all(pool)
29813×
            .await
29913×
            .unwrap_or_default();
30013×
        out.push(api::Project { name, path, description, url, depends_on, depended_on_by, agents });
301
    }
30212×
    json_etag(&headers, &out)
30312×
}
304
3051×
async fn channels(
3061×
    State(st): State<AppState>,
3071×
    ConnectInfo(peer): ConnectInfo<PeerInfo>,
3081×
    headers: HeaderMap,
3091×
    uri: axum::http::Uri,
3101×
) -> Response {
3111×
    let c = who!(st, peer, headers, uri, "GET", b"", true);
3121×
    let all = match conv::channels(&st.daemon.ledger).await {
3131×
        Ok(a) => a,
3140×
        Err(e) => return bad(e),
315
    };
3161×
    let mut out = Vec::new();
3174×
    for ch in all.into_iter().filter(|ch| conv::can_read(&c.principal, ch)) {
3184×
        let n: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM messages WHERE channel = ?")
3194×
            .bind(&ch.id)
3204×
            .fetch_one(st.daemon.ledger.pool())
3214×
            .await
3224×
            .unwrap_or(0);
3234×
        out.push(api::Channel { display: ch.display(), id: ch.id, name: ch.name, kind: ch.kind, purpose: ch.purpose, messages: n });
324
    }
3251×
    json_etag(&headers, &out)
3261×
}
327
3284×
async fn to_api(st: &AppState, m: conv::Message, ch: &str) -> api::Message {
329
    api::Message {
3304×
        author_display: conv::display_name(&st.daemon.ledger, &m.author).await,
3314×
        mentions: serde_json::from_str(&m.mentions).unwrap_or_default(),
3324×
        refs: serde_json::from_str(&m.refs).unwrap_or_default(),
3334×
        redacted: m.redacted.is_some(),
3344×
        id: m.id,
3354×
        channel: ch.to_string(),
3364×
        reply_to: m.reply_to,
3374×
        author: m.author,
3384×
        kind: m.kind,
3394×
        body: m.body,
3404×
        at_ms: m.at_ms,
3414×
        replies: m.replies,
342
    }
3434×
}
344
345
#[derive(Deserialize)]
346
struct PageQuery {
347
    after: Option<String>,
348
    limit: Option<u32>,
349
}
350
3511×
async fn messages(
3521×
    State(st): State<AppState>,
3531×
    ConnectInfo(peer): ConnectInfo<PeerInfo>,
3541×
    headers: HeaderMap,
3551×
    uri: axum::http::Uri,
3561×
    Path(name): Path<String>,
3571×
    Query(q): Query<PageQuery>,
3581×
) -> Response {
3591×
    let c = who!(st, peer, headers, uri, "GET", b"", true);
3601×
    let limit = q.limit.unwrap_or(50).clamp(1, 500);
3611×
    match conv::read(&st.daemon.ledger, &c.principal, Some(&name), None, q.after.as_deref(), limit).await {
3621×
        Ok((ch, msgs)) => {
3631×
            let next = (msgs.len() as u32 == limit).then(|| msgs.last().map(|m| m.id.clone())).flatten();
3641×
            let mut items = Vec::new();
3652×
            for m in msgs {
3662×
                items.push(to_api(&st, m, &ch.display()).await);
367
            }
3681×
            json_etag(&headers, &api::Messages { channel: ch.display(), items, next })
369
        }
3700×
        Err(e) => problem(StatusCode::NOT_FOUND, "no such channel, or not yours to read", Some(format!("{e:#}"))),
371
    }
3721×
}
373
3741×
async fn thread(
3751×
    State(st): State<AppState>,
3761×
    ConnectInfo(peer): ConnectInfo<PeerInfo>,
3771×
    headers: HeaderMap,
3781×
    uri: axum::http::Uri,
3791×
    Path(id): Path<String>,
3801×
    Query(q): Query<PageQuery>,
3811×
) -> Response {
3821×
    let c = who!(st, peer, headers, uri, "GET", b"", true);
3831×
    let limit = q.limit.unwrap_or(200).clamp(1, 500);
3841×
    match conv::read(&st.daemon.ledger, &c.principal, None, Some(&id), q.after.as_deref(), limit).await {
3851×
        Ok((ch, msgs)) => {
3861×
            let next = (msgs.len() as u32 == limit).then(|| msgs.last().map(|m| m.id.clone())).flatten();
3871×
            let mut items = Vec::new();
3882×
            for m in msgs {
3892×
                items.push(to_api(&st, m, &ch.display()).await);
390
            }
3911×
            json_etag(&headers, &api::Messages { channel: ch.display(), items, next })
392
        }
3930×
        Err(e) => problem(StatusCode::NOT_FOUND, "no such thread, or not yours to read", Some(format!("{e:#}"))),
394
    }
3951×
}
396
39710×
async fn post_message(
39810×
    State(st): State<AppState>,
39910×
    ConnectInfo(peer): ConnectInfo<PeerInfo>,
40010×
    headers: HeaderMap,
40110×
    uri: axum::http::Uri,
40210×
    Path(name): Path<String>,
40310×
    body: Bytes,
40410×
) -> Response {
40510×
    let c = who!(st, peer, headers, uri, "POST", &body, false);
40610×
    let n: api::NewMessage = match serde_json::from_slice(&body) {
40710×
        Ok(n) => n,
4080×
        Err(e) => return problem(StatusCode::BAD_REQUEST, "not a message", Some(e.to_string())),
409
    };
41010×
    let author = Author { principal: c.principal.clone(), signer: Signer::Request(c.auth.clone()) };
41110×
    let post = Post {
41210×
        channel: if n.reply_to.is_some() { None } else { Some(name) },
41310×
        body: n.body,
41410×
        reply_to: n.reply_to,
41510×
        kind: n.kind,
41610×
        ..Default::default()
417
    };
41810×
    match conv::post(&st.daemon.ledger, &author, post, now_ms()).await {
4199×
        Ok(Posted::Message { id, channel }) => {
4209×
            (StatusCode::CREATED, axum::Json(api::Posted { id, channel, duplicate: false })).into_response()
421
        }
4220×
        Ok(Posted::Duplicate { id }) => axum::Json(api::Posted { id, channel: String::new(), duplicate: true }).into_response(),
4231×
        Err(e) => bad(e),
424
    }
42510×
}
426
4278×
async fn inbox_items(st: &AppState, actor: &str) -> Vec<api::InboxItem> {
4288×
    let mut out = Vec::new();
4298×
    for i in conv::inbox(&st.daemon.ledger, actor, None).await.unwrap_or_default() {
4306×
        let from_display = conv::display_name(&st.daemon.ledger, &i.from).await;
4316×
        out.push(api::InboxItem {
4326×
            id: i.id,
4336×
            kind: i.kind,
4346×
            at_ms: i.at_ms,
4356×
            from: i.from,
4366×
            from_display,
4376×
            channel: i.channel,
4386×
            summary: i.summary,
4396×
        });
440
    }
4418×
    out
4428×
}
443
4445×
async fn inbox(State(st): State<AppState>, ConnectInfo(peer): ConnectInfo<PeerInfo>, headers: HeaderMap, uri: axum::http::Uri) -> Response {
4455×
    let c = who!(st, peer, headers, uri, "GET", b"", true);
4465×
    json_etag(&headers, &inbox_items(&st, &c.principal.actor()).await)
4475×
}
448
4491×
async fn ack(
4501×
    State(st): State<AppState>,
4511×
    ConnectInfo(peer): ConnectInfo<PeerInfo>,
4521×
    headers: HeaderMap,
4531×
    uri: axum::http::Uri,
4541×
    body: Bytes,
4551×
) -> Response {
4561×
    let c = who!(st, peer, headers, uri, "POST", &body, false);
4571×
    let a: api::Ack = match serde_json::from_slice(&body) {
4581×
        Ok(a) => a,
4590×
        Err(e) => return problem(StatusCode::BAD_REQUEST, "not an ack", Some(e.to_string())),
460
    };
4611×
    let author = Author { principal: c.principal, signer: Signer::Request(c.auth) };
4621×
    match conv::ack(&st.daemon.ledger, &author, &a.ids, a.reaction.as_deref()).await {
4631×
        Ok(n) => axum::Json(serde_json::json!({ "read": n })).into_response(),
4640×
        Err(e) => bad(e),
465
    }
4661×
}
467
4683×
async fn brief(State(st): State<AppState>, ConnectInfo(peer): ConnectInfo<PeerInfo>, headers: HeaderMap, uri: axum::http::Uri) -> Response {
4693×
    let c = who!(st, peer, headers, uri, "GET", b"", true);
4703×
    let project = match &c.principal {
4711×
        Principal::Agent { project, .. } => Some(project.clone()),
4722×
        _ => None,
473
    };
4743×
    let rules = spectra_core::rules::compile(st.daemon.ledger.pool(), project.as_deref()).await.map(|r| r.version).unwrap_or_default();
4753×
    let inbox = inbox_items(&st, &c.principal.actor()).await;
4763×
    let b = api::Brief {
4773×
        you: c.principal.display(),
4783×
        actor: c.principal.actor(),
4793×
        project,
4803×
        rules_version: rules,
4813×
        unread: inbox.len() as i64,
4823×
        inbox,
4833×
        agents: agent_list(&st).await,
4843×
        head: st.daemon.ledger.head().await.0,
485
    };
4863×
    json_etag(&headers, &b)
4873×
}
488
489
#[derive(Deserialize)]
490
struct SearchQuery {
491
    q: String,
492
    channel: Option<String>,
493
    author: Option<String>,
494
    since: Option<String>,
495
    limit: Option<u32>,
496
}
497
4983×
async fn search(
4993×
    State(st): State<AppState>,
5003×
    ConnectInfo(peer): ConnectInfo<PeerInfo>,
5013×
    headers: HeaderMap,
5023×
    uri: axum::http::Uri,
5033×
    Query(q): Query<SearchQuery>,
5043×
) -> Response {
5053×
    let c = who!(st, peer, headers, uri, "GET", b"", true);
5063×
    let since = q.since.as_deref().and_then(|s| crate::tools::parse_since(s, now_ms()));
5073×
    match conv::search(&st.daemon.ledger, &c.principal, &q.q, q.channel.as_deref(), q.author.as_deref(), since, q.limit.unwrap_or(20)).await
508
    {
5093×
        Ok(hits) => {
5103×
            let mut out: Vec<api::Hit> = Vec::new();
5115×
            for h in hits {
5125×
                let author_display = conv::display_name(&st.daemon.ledger, &h.author).await;
5135×
                out.push(api::Hit {
5145×
                    id: h.id,
5155×
                    channel: h.channel,
5165×
                    author: h.author,
5175×
                    at_ms: h.at_ms,
5185×
                    snippet: h.snippet,
5195×
                    thread: h.thread,
5205×
                    author_display,
5215×
                });
522
            }
5233×
            json_etag(&headers, &out)
524
        }
5250×
        Err(e) => bad(e),
526
    }
5273×
}
528
529
#[derive(Deserialize)]
530
struct EventsQuery {
531
    after: Option<u64>,
532
    kind: Option<String>,
533
    limit: Option<u32>,
534
    follow: Option<u8>,
535
    /// With `follow`, end the stream after this many events.
536
    max: Option<usize>,
537
}
538
53913×
fn summary(e: &spectra_core::event::Event) -> api::EventSummary {
54013×
    api::EventSummary {
54113×
        seq: e.seq,
54213×
        id: e.id.clone(),
54313×
        at_ms: e.at_ms,
54413×
        kind: e.kind.clone(),
54513×
        actor: e.actor.clone(),
54613×
        subject: e.subject.clone(),
54713×
        method: e.auth.method.name().into(),
54813×
        assurance: e.auth.assurance,
54913×
        hash: hex::encode(e.hash),
55013×
    }
55113×
}
552
553
/// The log as summaries; `follow=1` streams new ones as SSE instead.
5545×
async fn events(
5555×
    State(st): State<AppState>,
5565×
    ConnectInfo(peer): ConnectInfo<PeerInfo>,
5575×
    headers: HeaderMap,
5585×
    uri: axum::http::Uri,
5595×
    Query(q): Query<EventsQuery>,
5605×
) -> Response {
5615×
    let c = who!(st, peer, headers, uri, "GET", b"", true);
562
    // The log is the owner's to read; an agent reads what concerns it
563
    // through the conversation and its inbox.
5645×
    if !matches!(c.principal, Principal::Owner { .. }) {
5651×
        return problem(StatusCode::FORBIDDEN, "the event log is the owner's", None);
5664×
    }
5674×
    if q.follow == Some(1) {
5682×
        let kind = q.kind.clone();
5692×
        let rx = st.daemon.ledger.subscribe();
5702×
        let stream = tokio_stream::wrappers::BroadcastStream::new(rx)
5714×
            .filter_map(move |e| {
5724×
                let kind = kind.clone();
5734×
                async move {
5744×
                    let e = e.ok()?;
5754×
                    if kind.as_ref().is_some_and(|k| *k != e.kind) {
5762×
                        return None;
5772×
                    }
5782×
                    Some(Ok::<_, std::convert::Infallible>(
5792×
                        SseEvent::default().data(serde_json::to_string(&summary(&e)).unwrap_or_default()),
5802×
                    ))
5814×
                }
5824×
            })
5832×
            .take(q.max.unwrap_or(usize::MAX));
584
        // A comment first: the follower knows it is subscribed, so it can
585
        // read the state and miss nothing that happens after.
5862×
        let hello = futures::stream::once(async { Ok::<_, std::convert::Infallible>(SseEvent::default().comment("subscribed")) });
5872×
        return Sse::new(hello.chain(stream)).keep_alive(KeepAlive::new().interval(Duration::from_secs(15))).into_response();
5882×
    }
5892×
    let limit = q.limit.unwrap_or(100).clamp(1, 1000);
5902×
    let from = q.after.map(|a| a + 1).unwrap_or(1);
5912×
    let evs = match &q.kind {
5921×
        Some(k) => st.daemon.ledger.events_of_kinds(from, &[k.as_str()], limit).await,
5931×
        None => st.daemon.ledger.events(from, limit).await,
594
    };
5952×
    match evs {
5962×
        Ok(evs) => {
5972×
            let next = (evs.len() as u32 == limit).then(|| evs.last().map(|e| e.seq)).flatten();
5982×
            json_etag(&headers, &api::Events { items: evs.iter().map(summary).collect(), next })
599
        }
6000×
        Err(e) => bad(e),
601
    }
6025×
}