OXYGENHUB

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

467 of 489 lines run, 74 of 158 functions · run #35 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::ids::now_ms;
21
use spectra_core::principals::Principal;
22
use std::time::Duration;
23
2422×
pub fn router(state: AppState) -> Router {
2522×
    Router::new()
2622×
        .route("/api/v1/health", get(health))
2722×
        .route("/api/v1/version", get(version))
2822×
        .route("/api/v1/brief", get(brief))
2922×
        .route("/api/v1/agents", get(agents))
3022×
        .route("/api/v1/projects", get(projects))
3122×
        .route("/api/v1/channels", get(channels))
3222×
        .route("/api/v1/channels/{name}/messages", get(messages).post(post_message))
3322×
        .route("/api/v1/threads/{id}", get(thread))
3422×
        .route("/api/v1/inbox", get(inbox))
3522×
        .route("/api/v1/inbox/ack", post(ack))
3622×
        .route("/api/v1/search", get(search))
3722×
        .route("/api/v1/events", get(events))
3822×
        .route("/api/v1/admin/verify", get(admin_verify))
3922×
        .route("/api/v1/briefs", get(briefs).put(set_brief))
4022×
        .with_state(state)
4122×
}
42
43
/// An RFC 7807 problem.
446×
pub fn problem(status: StatusCode, title: &str, detail: Option<String>) -> Response {
456×
    let p = api::Problem { kind: "about:blank".into(), title: title.into(), status: status.as_u16(), detail };
466×
    let mut r = (status, axum::Json(p)).into_response();
476×
    r.headers_mut().insert(header::CONTENT_TYPE, "application/problem+json".parse().unwrap());
486×
    r
496×
}
50
511×
fn bad(e: anyhow::Error) -> Response {
521×
    problem(StatusCode::BAD_REQUEST, "the request cannot be done", Some(format!("{e:#}")))
531×
}
54
55
/// JSON with an ETag; 304 when the client has it already.
5648×
fn json_etag<T: serde::Serialize>(headers: &HeaderMap, v: &T) -> Response {
5748×
    let body = serde_json::to_vec(v).unwrap_or_default();
5848×
    let tag = format!("\"{}\"", &blake3_hex(&body)[..32]);
5948×
    if headers.get(header::IF_NONE_MATCH).and_then(|h| h.to_str().ok()) == Some(tag.as_str()) {
601×
        return StatusCode::NOT_MODIFIED.into_response();
6147×
    }
6247×
    ([(header::CONTENT_TYPE, "application/json".to_string()), (header::ETAG, tag)], body).into_response()
6348×
}
64
6548×
fn blake3_hex(b: &[u8]) -> String {
6648×
    hex::encode(*spectra_core::event::hash_body_plain(b))
6748×
}
68
69
/// Who is asking: every request is signed (spec §8.5).
7069×
async fn caller(
7169×
    st: &AppState,
7269×
    peer: PeerInfo,
7369×
    headers: &HeaderMap,
7469×
    method_path: &str,
7569×
    body: &[u8],
7669×
    read: bool,
7769×
) -> Result<Caller, Response> {
7869×
    let _ = read;
7969×
    let signed = headers.get("spectra-key").is_some();
8069×
    crate::http::authenticate_why(st, peer, headers, method_path, body).await.map_err(|(status, why)| {
812×
        if status == StatusCode::FORBIDDEN {
820×
            problem(status, "this origin may not call Spectra", None)
832×
        } else if signed {
84
            // A signed request is told why its signature was not enough.
851×
            problem(StatusCode::UNAUTHORIZED, "not authenticated", Some(why))
86
        } else {
871×
            problem(
88
                StatusCode::UNAUTHORIZED,
891×
                "not authenticated",
901×
                Some("sign the request with your key: spectra's own client, its shims and `spectra bridge` do".into()),
91
            )
92
        }
932×
    })
9469×
}
95
9669×
fn path_of(uri: &axum::http::Uri) -> String {
9769×
    uri.path_and_query().map(|p| p.as_str().to_string()).unwrap_or_else(|| uri.path().to_string())
9869×
}
99
100
macro_rules! who {
101
    ($st:expr, $peer:expr, $headers:expr, $uri:expr, $method:literal, $body:expr, $read:expr) => {
102
        match caller(&$st, $peer, &$headers, &format!("{} {}", $method, path_of(&$uri)), $body, $read).await {
103
            Ok(c) => c,
104
            Err(r) => return r,
105
        }
106
    };
107
}
108
109
/// `GET /api/v1/admin/verify`: the owner asks the daemon to verify its
110
/// ledger (spec §8.6): what `spectra admin verify` prints, from afar.
1111×
async fn admin_verify(
1121×
    State(st): State<AppState>,
1131×
    ConnectInfo(peer): ConnectInfo<PeerInfo>,
1141×
    headers: HeaderMap,
1151×
    uri: axum::http::Uri,
1161×
) -> Response {
1171×
    let c = who!(st, peer, headers, uri, "GET", b"", false);
1181×
    if !matches!(c.principal, Principal::Owner { .. }) {
1190×
        return problem(StatusCode::FORBIDDEN, "only the owner verifies the ledger", None);
1201×
    }
1211×
    let ledger = match spectra_core::ledger::Ledger::open_read_only(&st.daemon.data.join("spectra.db")).await {
1221×
        Ok(l) => l,
1230×
        Err(e) => return bad(e),
124
    };
1251×
    match ledger.verify(&mut spectra_core::principals::Principals::default()).await {
1261×
        Ok(v) => axum::Json(v).into_response(),
1270×
        Err(e) => bad(e),
128
    }
1291×
}
130
131
/// `GET /api/v1/briefs`: the overall brief and every project's (spec §12.1).
1323×
async fn briefs(
1333×
    State(st): State<AppState>,
1343×
    ConnectInfo(peer): ConnectInfo<PeerInfo>,
1353×
    headers: HeaderMap,
1363×
    uri: axum::http::Uri,
1373×
) -> Response {
1383×
    let _ = who!(st, peer, headers, uri, "GET", b"", true);
1393×
    let pool = st.daemon.ledger.pool();
1403×
    let overall = spectra_core::rules::layer(pool, None).await.ok().flatten();
1413×
    let rows: Vec<(String, String)> = sqlx::query_as("SELECT project, text FROM briefs WHERE layer = 'project' ORDER BY project")
1423×
        .fetch_all(pool)
1433×
        .await
1443×
        .unwrap_or_default();
1453×
    json_etag(
1463×
        &headers,
1474×
        &api::Briefs { overall, projects: rows.into_iter().map(|(project, text)| api::ProjectBrief { project, text }).collect() },
148
    )
1493×
}
150
151
/// `PUT /api/v1/briefs`: the owner sets a brief; the signed request is the
152
/// event's proof.
1534×
async fn set_brief(
1544×
    State(st): State<AppState>,
1554×
    ConnectInfo(peer): ConnectInfo<PeerInfo>,
1564×
    headers: HeaderMap,
1574×
    uri: axum::http::Uri,
1584×
    body: Bytes,
1594×
) -> Response {
1604×
    let c = who!(st, peer, headers, uri, "PUT", &body, false);
1614×
    if !matches!(c.principal, Principal::Owner { .. }) {
1621×
        return problem(StatusCode::FORBIDDEN, "only the owner sets a brief", None);
1633×
    }
1643×
    let b: api::SetBrief = match serde_json::from_slice(&body) {
1653×
        Ok(b) => b,
1660×
        Err(e) => return problem(StatusCode::BAD_REQUEST, "not a brief", Some(e.to_string())),
167
    };
1683×
    if let Err(e) = spectra_core::rules::check(&b.text) {
1690×
        return problem(StatusCode::BAD_REQUEST, "too long", Some(e.to_string()));
1703×
    }
1713×
    let project = b.project.filter(|p| !p.is_empty());
1723×
    if let Some(p) = &project {
1732×
        let known: Option<String> = sqlx::query_scalar("SELECT name FROM projects WHERE name = ?")
1742×
            .bind(p)
1752×
            .fetch_optional(st.daemon.ledger.pool())
1762×
            .await
1772×
            .unwrap_or(None);
1782×
        if known.is_none() {
1791×
            return problem(StatusCode::NOT_FOUND, "no such project", Some(p.clone()));
1801×
        }
1811×
    }
1822×
    let mut e = spectra_core::event::NewEvent::system("brief.set", serde_json::json!({ "project": project, "text": b.text }))
1832×
        .by(c.principal.actor(), c.auth.clone());
1842×
    e.project = project.clone();
1852×
    match st.daemon.ledger.append_one(e).await {
1862×
        Ok(ev) => axum::Json(serde_json::json!({ "seq": ev.seq })).into_response(),
1870×
        Err(e) => bad(e),
188
    }
1894×
}
190
1911×
async fn health() -> Response {
1921×
    axum::Json(serde_json::json!({ "ok": true })).into_response()
1931×
}
194
1951×
async fn version() -> Response {
196
    axum::Json(api::Version {
1971×
        version: env!("CARGO_PKG_VERSION").into(),
198
        ledger_format: spectra_core::LEDGER_FORMAT,
1994×
        mcp_protocol_versions: crate::PROTOCOL_VERSIONS.iter().map(|v| v.to_string()).collect(),
200
    })
2011×
    .into_response()
2021×
}
203
20417×
async fn agent_list(st: &AppState) -> Vec<api::Agent> {
205
    #[allow(clippy::type_complexity)]
20617×
    let rows: Vec<(String, String, String, String, String, Option<String>, Option<i64>, String)> = sqlx::query_as(
20717×
        "SELECT a.name, a.owner_name, a.key, a.kind, a.project, p.status_text, a.disabled_ms, a.scopes FROM agents a LEFT JOIN presence p ON p.agent = a.name ORDER BY a.name",
20817×
    )
20917×
    .fetch_all(st.daemon.ledger.pool())
21017×
    .await
21117×
    .unwrap_or_default();
21217×
    let presence = st.daemon.presence.lock().await;
21317×
    let principals = st.daemon.principals.read().await;
21417×
    let now = now_ms();
21517×
    rows.into_iter()
21619×
        .map(|(name, owner, key, kind, project, status, disabled, scopes)| {
21719×
            let channels = serde_json::from_str::<Vec<String>>(&scopes)
21819×
                .unwrap_or_default()
21919×
                .into_iter()
220154×
                .filter_map(|s| s.strip_prefix("channel:").map(String::from))
22119×
                .collect();
22219×
            let k = spectra_core::identity::KeyId::from_hex(&key);
22319×
            let state = match k.map(|k| principals.principal(&k, now)) {
22418×
                Some(Ok(_)) => "ok".to_string(),
2251×
                Some(Err(why)) => why,
2260×
                None => "a malformed key".into(),
227
            };
22819×
            let delegation_expires = k.and_then(|k| principals.owner().and_then(|o| o.delegate(&k)).and_then(|d| d.expires));
229
            api::Agent {
23019×
                display: format!("{name} · {owner}'s agent"),
23119×
                presence: if disabled.is_some() { "offline".into() } else { presence.state(&name, now).into() },
23219×
                disabled: disabled.is_some(),
23319×
                name,
23419×
                owner,
23519×
                key,
23619×
                kind,
23719×
                project,
23819×
                status,
23919×
                state,
24019×
                delegation_expires,
24119×
                channels,
242
            }
24319×
        })
24417×
        .collect()
24517×
}
246
24715×
async fn agents(
24815×
    State(st): State<AppState>,
24915×
    ConnectInfo(peer): ConnectInfo<PeerInfo>,
25015×
    headers: HeaderMap,
25115×
    uri: axum::http::Uri,
25215×
) -> Response {
25315×
    let _ = who!(st, peer, headers, uri, "GET", b"", true);
25413×
    json_etag(&headers, &agent_list(&st).await)
25515×
}
256
25716×
async fn projects(
25816×
    State(st): State<AppState>,
25916×
    ConnectInfo(peer): ConnectInfo<PeerInfo>,
26016×
    headers: HeaderMap,
26116×
    uri: axum::http::Uri,
26216×
) -> Response {
26316×
    let _ = who!(st, peer, headers, uri, "GET", b"", true);
26416×
    let pool = st.daemon.ledger.pool();
26516×
    let rows: Vec<(String, Option<String>, String, Option<String>)> =
26616×
        sqlx::query_as("SELECT name, path, description, url FROM projects ORDER BY name").fetch_all(pool).await.unwrap_or_default();
26716×
    let mut out = Vec::new();
26819×
    for (name, path, description, url) in rows {
26919×
        let depends_on = sqlx::query_scalar("SELECT depends_on FROM project_relations WHERE project = ? ORDER BY 1")
27019×
            .bind(&name)
27119×
            .fetch_all(pool)
27219×
            .await
27319×
            .unwrap_or_default();
27419×
        let depended_on_by = sqlx::query_scalar("SELECT project FROM project_relations WHERE depends_on = ? ORDER BY 1")
27519×
            .bind(&name)
27619×
            .fetch_all(pool)
27719×
            .await
27819×
            .unwrap_or_default();
27919×
        let agents = sqlx::query_scalar("SELECT name FROM agents WHERE project = ? AND disabled_ms IS NULL ORDER BY name")
28019×
            .bind(&name)
28119×
            .fetch_all(pool)
28219×
            .await
28319×
            .unwrap_or_default();
28419×
        out.push(api::Project { name, path, description, url, depends_on, depended_on_by, agents });
285
    }
28616×
    json_etag(&headers, &out)
28716×
}
288
2891×
async fn channels(
2901×
    State(st): State<AppState>,
2911×
    ConnectInfo(peer): ConnectInfo<PeerInfo>,
2921×
    headers: HeaderMap,
2931×
    uri: axum::http::Uri,
2941×
) -> Response {
2951×
    let c = who!(st, peer, headers, uri, "GET", b"", true);
2961×
    let all = match conv::channels(&st.daemon.ledger).await {
2971×
        Ok(a) => a,
2980×
        Err(e) => return bad(e),
299
    };
3001×
    let mut out = Vec::new();
3014×
    for ch in all.into_iter().filter(|ch| conv::can_read(&c.principal, ch)) {
3024×
        let n: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM messages WHERE channel = ?")
3034×
            .bind(&ch.id)
3044×
            .fetch_one(st.daemon.ledger.pool())
3054×
            .await
3064×
            .unwrap_or(0);
3074×
        out.push(api::Channel { display: ch.display(), id: ch.id, name: ch.name, kind: ch.kind, purpose: ch.purpose, messages: n });
308
    }
3091×
    json_etag(&headers, &out)
3101×
}
311
3124×
async fn to_api(st: &AppState, m: conv::Message, ch: &str) -> api::Message {
313
    api::Message {
3144×
        author_display: conv::display_name(&st.daemon.ledger, &m.author).await,
3154×
        mentions: serde_json::from_str(&m.mentions).unwrap_or_default(),
3164×
        refs: serde_json::from_str(&m.refs).unwrap_or_default(),
3174×
        redacted: m.redacted.is_some(),
3184×
        id: m.id,
3194×
        channel: ch.to_string(),
3204×
        reply_to: m.reply_to,
3214×
        author: m.author,
3224×
        kind: m.kind,
3234×
        body: m.body,
3244×
        at_ms: m.at_ms,
3254×
        replies: m.replies,
326
    }
3274×
}
328
329
#[derive(Deserialize)]
330
struct PageQuery {
331
    after: Option<String>,
332
    limit: Option<u32>,
333
}
334
3351×
async fn messages(
3361×
    State(st): State<AppState>,
3371×
    ConnectInfo(peer): ConnectInfo<PeerInfo>,
3381×
    headers: HeaderMap,
3391×
    uri: axum::http::Uri,
3401×
    Path(name): Path<String>,
3411×
    Query(q): Query<PageQuery>,
3421×
) -> Response {
3431×
    let c = who!(st, peer, headers, uri, "GET", b"", true);
3441×
    let limit = q.limit.unwrap_or(50).clamp(1, 500);
3451×
    match conv::read(&st.daemon.ledger, &c.principal, Some(&name), None, q.after.as_deref(), limit).await {
3461×
        Ok((ch, msgs)) => {
3471×
            let next = (msgs.len() as u32 == limit).then(|| msgs.last().map(|m| m.id.clone())).flatten();
3481×
            let mut items = Vec::new();
3492×
            for m in msgs {
3502×
                items.push(to_api(&st, m, &ch.display()).await);
351
            }
3521×
            json_etag(&headers, &api::Messages { channel: ch.display(), items, next })
353
        }
3540×
        Err(e) => problem(StatusCode::NOT_FOUND, "no such channel, or not yours to read", Some(format!("{e:#}"))),
355
    }
3561×
}
357
3581×
async fn thread(
3591×
    State(st): State<AppState>,
3601×
    ConnectInfo(peer): ConnectInfo<PeerInfo>,
3611×
    headers: HeaderMap,
3621×
    uri: axum::http::Uri,
3631×
    Path(id): Path<String>,
3641×
    Query(q): Query<PageQuery>,
3651×
) -> Response {
3661×
    let c = who!(st, peer, headers, uri, "GET", b"", true);
3671×
    let limit = q.limit.unwrap_or(200).clamp(1, 500);
3681×
    match conv::read(&st.daemon.ledger, &c.principal, None, Some(&id), q.after.as_deref(), limit).await {
3691×
        Ok((ch, msgs)) => {
3701×
            let next = (msgs.len() as u32 == limit).then(|| msgs.last().map(|m| m.id.clone())).flatten();
3711×
            let mut items = Vec::new();
3722×
            for m in msgs {
3732×
                items.push(to_api(&st, m, &ch.display()).await);
374
            }
3751×
            json_etag(&headers, &api::Messages { channel: ch.display(), items, next })
376
        }
3770×
        Err(e) => problem(StatusCode::NOT_FOUND, "no such thread, or not yours to read", Some(format!("{e:#}"))),
378
    }
3791×
}
380
38110×
async fn post_message(
38210×
    State(st): State<AppState>,
38310×
    ConnectInfo(peer): ConnectInfo<PeerInfo>,
38410×
    headers: HeaderMap,
38510×
    uri: axum::http::Uri,
38610×
    Path(name): Path<String>,
38710×
    body: Bytes,
38810×
) -> Response {
38910×
    let c = who!(st, peer, headers, uri, "POST", &body, false);
39010×
    let n: api::NewMessage = match serde_json::from_slice(&body) {
39110×
        Ok(n) => n,
3920×
        Err(e) => return problem(StatusCode::BAD_REQUEST, "not a message", Some(e.to_string())),
393
    };
39410×
    let author = Author { principal: c.principal.clone(), signer: Signer::Request(c.auth.clone()) };
39510×
    let post = Post {
39610×
        channel: if n.reply_to.is_some() { None } else { Some(name) },
39710×
        body: n.body,
39810×
        reply_to: n.reply_to,
39910×
        kind: n.kind,
40010×
        ..Default::default()
401
    };
40210×
    match conv::post(&st.daemon.ledger, &author, post, now_ms()).await {
4039×
        Ok(Posted::Message { id, channel }) => {
4049×
            (StatusCode::CREATED, axum::Json(api::Posted { id, channel, duplicate: false })).into_response()
405
        }
4060×
        Ok(Posted::Duplicate { id }) => axum::Json(api::Posted { id, channel: String::new(), duplicate: true }).into_response(),
4071×
        Err(e) => bad(e),
408
    }
40910×
}
410
4119×
async fn inbox_items(st: &AppState, actor: &str) -> Vec<api::InboxItem> {
4129×
    let mut out = Vec::new();
4139×
    for i in conv::inbox(&st.daemon.ledger, actor, None).await.unwrap_or_default() {
4146×
        let from_display = conv::display_name(&st.daemon.ledger, &i.from).await;
4156×
        out.push(api::InboxItem {
4166×
            id: i.id,
4176×
            kind: i.kind,
4186×
            at_ms: i.at_ms,
4196×
            from: i.from,
4206×
            from_display,
4216×
            channel: i.channel,
4226×
            summary: i.summary,
4236×
        });
424
    }
4259×
    out
4269×
}
427
4285×
async fn inbox(State(st): State<AppState>, ConnectInfo(peer): ConnectInfo<PeerInfo>, headers: HeaderMap, uri: axum::http::Uri) -> Response {
4295×
    let c = who!(st, peer, headers, uri, "GET", b"", true);
4305×
    json_etag(&headers, &inbox_items(&st, &c.principal.actor()).await)
4315×
}
432
4331×
async fn ack(
4341×
    State(st): State<AppState>,
4351×
    ConnectInfo(peer): ConnectInfo<PeerInfo>,
4361×
    headers: HeaderMap,
4371×
    uri: axum::http::Uri,
4381×
    body: Bytes,
4391×
) -> Response {
4401×
    let c = who!(st, peer, headers, uri, "POST", &body, false);
4411×
    let a: api::Ack = match serde_json::from_slice(&body) {
4421×
        Ok(a) => a,
4430×
        Err(e) => return problem(StatusCode::BAD_REQUEST, "not an ack", Some(e.to_string())),
444
    };
4451×
    let author = Author { principal: c.principal, signer: Signer::Request(c.auth) };
4461×
    match conv::ack(&st.daemon.ledger, &author, &a.ids, a.reaction.as_deref()).await {
4471×
        Ok(n) => axum::Json(serde_json::json!({ "read": n })).into_response(),
4480×
        Err(e) => bad(e),
449
    }
4501×
}
451
4524×
async fn brief(State(st): State<AppState>, ConnectInfo(peer): ConnectInfo<PeerInfo>, headers: HeaderMap, uri: axum::http::Uri) -> Response {
4534×
    let c = who!(st, peer, headers, uri, "GET", b"", true);
4544×
    let project = match &c.principal {
4551×
        Principal::Agent { project, .. } => Some(project.clone()),
4563×
        _ => None,
457
    };
4584×
    let rules = spectra_core::rules::compile(st.daemon.ledger.pool(), project.as_deref()).await.map(|r| r.version).unwrap_or_default();
4594×
    let inbox = inbox_items(&st, &c.principal.actor()).await;
4604×
    let b = api::Brief {
4614×
        you: c.principal.display(),
4624×
        actor: c.principal.actor(),
4634×
        project,
4644×
        rules_version: rules,
4654×
        unread: inbox.len() as i64,
4664×
        inbox,
4674×
        agents: agent_list(&st).await,
4684×
        head: st.daemon.ledger.head().await.0,
469
    };
4704×
    json_etag(&headers, &b)
4714×
}
472
473
#[derive(Deserialize)]
474
struct SearchQuery {
475
    q: String,
476
    channel: Option<String>,
477
    author: Option<String>,
478
    since: Option<String>,
479
    limit: Option<u32>,
480
}
481
4822×
async fn search(
4832×
    State(st): State<AppState>,
4842×
    ConnectInfo(peer): ConnectInfo<PeerInfo>,
4852×
    headers: HeaderMap,
4862×
    uri: axum::http::Uri,
4872×
    Query(q): Query<SearchQuery>,
4882×
) -> Response {
4892×
    let c = who!(st, peer, headers, uri, "GET", b"", true);
4902×
    let since = q.since.as_deref().and_then(|s| crate::tools::parse_since(s, now_ms()));
4912×
    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
492
    {
4932×
        Ok(hits) => {
4942×
            let mut out: Vec<api::Hit> = Vec::new();
4954×
            for h in hits {
4964×
                let author_display = conv::display_name(&st.daemon.ledger, &h.author).await;
4974×
                out.push(api::Hit {
4984×
                    id: h.id,
4994×
                    channel: h.channel,
5004×
                    author: h.author,
5014×
                    at_ms: h.at_ms,
5024×
                    snippet: h.snippet,
5034×
                    thread: h.thread,
5044×
                    author_display,
5054×
                });
506
            }
5072×
            json_etag(&headers, &out)
508
        }
5090×
        Err(e) => bad(e),
510
    }
5112×
}
512
513
#[derive(Deserialize)]
514
struct EventsQuery {
515
    after: Option<u64>,
516
    kind: Option<String>,
517
    limit: Option<u32>,
518
    follow: Option<u8>,
519
    /// With `follow`, end the stream after this many events.
520
    max: Option<usize>,
521
}
522
52313×
fn summary(e: &spectra_core::event::Event) -> api::EventSummary {
52413×
    api::EventSummary {
52513×
        seq: e.seq,
52613×
        id: e.id.clone(),
52713×
        at_ms: e.at_ms,
52813×
        kind: e.kind.clone(),
52913×
        actor: e.actor.clone(),
53013×
        subject: e.subject.clone(),
53113×
        method: e.auth.method.name().into(),
53213×
        assurance: e.auth.assurance,
53313×
        hash: hex::encode(e.hash),
53413×
    }
53513×
}
536
537
/// The log as summaries; `follow=1` streams new ones as SSE instead.
5385×
async fn events(
5395×
    State(st): State<AppState>,
5405×
    ConnectInfo(peer): ConnectInfo<PeerInfo>,
5415×
    headers: HeaderMap,
5425×
    uri: axum::http::Uri,
5435×
    Query(q): Query<EventsQuery>,
5445×
) -> Response {
5455×
    let c = who!(st, peer, headers, uri, "GET", b"", true);
546
    // The log is the owner's to read; an agent reads what concerns it
547
    // through the conversation and its inbox.
5485×
    if !matches!(c.principal, Principal::Owner { .. }) {
5491×
        return problem(StatusCode::FORBIDDEN, "the event log is the owner's", None);
5504×
    }
5514×
    if q.follow == Some(1) {
5522×
        let kind = q.kind.clone();
5532×
        let rx = st.daemon.ledger.subscribe();
5542×
        let stream = tokio_stream::wrappers::BroadcastStream::new(rx)
5554×
            .filter_map(move |e| {
5564×
                let kind = kind.clone();
5574×
                async move {
5584×
                    let e = e.ok()?;
5594×
                    if kind.as_ref().is_some_and(|k| *k != e.kind) {
5602×
                        return None;
5612×
                    }
5622×
                    Some(Ok::<_, std::convert::Infallible>(
5632×
                        SseEvent::default().data(serde_json::to_string(&summary(&e)).unwrap_or_default()),
5642×
                    ))
5654×
                }
5664×
            })
5672×
            .take(q.max.unwrap_or(usize::MAX));
568
        // A comment first: the follower knows it is subscribed, so it can
569
        // read the state and miss nothing that happens after.
5702×
        let hello = futures::stream::once(async { Ok::<_, std::convert::Infallible>(SseEvent::default().comment("subscribed")) });
5712×
        return Sse::new(hello.chain(stream)).keep_alive(KeepAlive::new().interval(Duration::from_secs(15))).into_response();
5722×
    }
5732×
    let limit = q.limit.unwrap_or(100).clamp(1, 1000);
5742×
    let from = q.after.map(|a| a + 1).unwrap_or(1);
5752×
    let evs = match &q.kind {
5761×
        Some(k) => st.daemon.ledger.events_of_kinds(from, &[k.as_str()], limit).await,
5771×
        None => st.daemon.ledger.events(from, limit).await,
578
    };
5792×
    match evs {
5802×
        Ok(evs) => {
5812×
            let next = (evs.len() as u32 == limit).then(|| evs.last().map(|e| e.seq)).flatten();
5822×
            json_etag(&headers, &api::Events { items: evs.iter().map(summary).collect(), next })
583
        }
5840×
        Err(e) => bad(e),
585
    }
5865×
}