| 1 | |
|
| 2 | |
|
| 3 | |
|
| 4 | |
|
| 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 | |
|
| 25 | 21× | pub fn router(state: AppState) -> Router { |
| 26 | 21× | Router::new() |
| 27 | 21× | .route("/api/v1/health", get(health)) |
| 28 | 21× | .route("/api/v1/version", get(version)) |
| 29 | 21× | .route("/api/v1/brief", get(brief)) |
| 30 | 21× | .route("/api/v1/agents", get(agents)) |
| 31 | 21× | .route("/api/v1/projects", get(projects)) |
| 32 | 21× | .route("/api/v1/channels", get(channels)) |
| 33 | 21× | .route("/api/v1/channels/{name}/messages", get(messages).post(post_message)) |
| 34 | 21× | .route("/api/v1/threads/{id}", get(thread)) |
| 35 | 21× | .route("/api/v1/inbox", get(inbox)) |
| 36 | 21× | .route("/api/v1/inbox/ack", post(ack)) |
| 37 | 21× | .route("/api/v1/search", get(search)) |
| 38 | 21× | .route("/api/v1/events", get(events)) |
| 39 | 21× | .route("/api/v1/admin/verify", get(admin_verify)) |
| 40 | 21× | .route("/api/v1/briefs", get(briefs).put(set_brief)) |
| 41 | 21× | .with_state(state) |
| 42 | 21× | } |
| 43 | |
|
| 44 | |
|
| 45 | 6× | pub fn problem(status: StatusCode, title: &str, detail: Option<String>) -> Response { |
| 46 | 6× | let p = api::Problem { kind: "about:blank".into(), title: title.into(), status: status.as_u16(), detail }; |
| 47 | 6× | let mut r = (status, axum::Json(p)).into_response(); |
| 48 | 6× | r.headers_mut().insert(header::CONTENT_TYPE, "application/problem+json".parse().unwrap()); |
| 49 | 6× | r |
| 50 | 6× | } |
| 51 | |
|
| 52 | 1× | fn bad(e: anyhow::Error) -> Response { |
| 53 | 1× | problem(StatusCode::BAD_REQUEST, "the request cannot be done", Some(format!("{e:#}"))) |
| 54 | 1× | } |
| 55 | |
|
| 56 | |
|
| 57 | 41× | fn json_etag<T: serde::Serialize>(headers: &HeaderMap, v: &T) -> Response { |
| 58 | 41× | let body = serde_json::to_vec(v).unwrap_or_default(); |
| 59 | 41× | let tag = format!("\"{}\"", &blake3_hex(&body)[..32]); |
| 60 | 41× | if headers.get(header::IF_NONE_MATCH).and_then(|h| h.to_str().ok()) == Some(tag.as_str()) { |
| 61 | 1× | return StatusCode::NOT_MODIFIED.into_response(); |
| 62 | 40× | } |
| 63 | 40× | ([(header::CONTENT_TYPE, "application/json".to_string()), (header::ETAG, tag)], body).into_response() |
| 64 | 41× | } |
| 65 | |
|
| 66 | 41× | fn blake3_hex(b: &[u8]) -> String { |
| 67 | 41× | hex::encode(*spectra_core::event::hash_body_plain(b)) |
| 68 | 41× | } |
| 69 | |
|
| 70 | |
|
| 71 | 62× | async fn caller( |
| 72 | 62× | st: &AppState, |
| 73 | 62× | peer: PeerInfo, |
| 74 | 62× | headers: &HeaderMap, |
| 75 | 62× | method_path: &str, |
| 76 | 62× | body: &[u8], |
| 77 | 62× | read: bool, |
| 78 | 62× | ) -> Result<Caller, Response> { |
| 79 | 62× | if read && headers.get("spectra-key").is_none() { |
| 80 | 1× | let cookie = headers.get(header::COOKIE).and_then(|c| c.to_str().ok()).unwrap_or(""); |
| 81 | 1× | let id = cookie.split(';').map(str::trim).find_map(|kv| kv.strip_prefix("spectra_session=")).unwrap_or(""); |
| 82 | 1× | if let Some(s) = st.sessions.get(id, now_ms()) { |
| 83 | 0× | if !crate::http::origin_ok(headers, &st.origins) { |
| 84 | 0× | return Err(problem(StatusCode::FORBIDDEN, "this origin may not read Spectra", None)); |
| 85 | 0× | } |
| 86 | 0× | let key = spectra_core::identity::KeyId(s.key); |
| 87 | 0× | let principal = st |
| 88 | 0× | .daemon |
| 89 | 0× | .principals |
| 90 | 0× | .read() |
| 91 | 0× | .await |
| 92 | 0× | .principal(&key, now_ms()) |
| 93 | 0× | .map_err(|why| problem(StatusCode::UNAUTHORIZED, "not authenticated", Some(why)))?; |
| 94 | 0× | return Ok(Caller { |
| 95 | 0× | principal, |
| 96 | 0× | auth: Auth { key: Some(s.key), method: Method::Session, assurance: 2, proof: Some(s.proof) }, |
| 97 | 0× | learn_uid: None, |
| 98 | 0× | }); |
| 99 | 1× | } |
| 100 | 61× | } |
| 101 | 62× | let signed = headers.get("spectra-key").is_some(); |
| 102 | 62× | crate::http::authenticate_why(st, peer, headers, method_path, body).await.map_err(|(status, why)| { |
| 103 | 2× | if status == StatusCode::FORBIDDEN { |
| 104 | 0× | problem(status, "this origin may not call Spectra", None) |
| 105 | 2× | } else if signed { |
| 106 | | |
| 107 | 1× | problem(StatusCode::UNAUTHORIZED, "not authenticated", Some(why)) |
| 108 | | } else { |
| 109 | 1× | problem( |
| 110 | | StatusCode::UNAUTHORIZED, |
| 111 | 1× | "not authenticated", |
| 112 | 1× | Some("sign the request with your key (spectra's client does), or open Radar with `spectra open`".into()), |
| 113 | | ) |
| 114 | | } |
| 115 | 2× | }) |
| 116 | 62× | } |
| 117 | |
|
| 118 | 62× | fn path_of(uri: &axum::http::Uri) -> String { |
| 119 | 62× | uri.path_and_query().map(|p| p.as_str().to_string()).unwrap_or_else(|| uri.path().to_string()) |
| 120 | 62× | } |
| 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 | |
|
| 132 | |
|
| 133 | 1× | async fn admin_verify( |
| 134 | 1× | State(st): State<AppState>, |
| 135 | 1× | ConnectInfo(peer): ConnectInfo<PeerInfo>, |
| 136 | 1× | headers: HeaderMap, |
| 137 | 1× | uri: axum::http::Uri, |
| 138 | 1× | ) -> Response { |
| 139 | 1× | let c = who!(st, peer, headers, uri, "GET", b"", false); |
| 140 | 1× | if !matches!(c.principal, Principal::Owner { .. }) { |
| 141 | 0× | return problem(StatusCode::FORBIDDEN, "only the owner verifies the ledger", None); |
| 142 | 1× | } |
| 143 | 1× | let ledger = match spectra_core::ledger::Ledger::open_read_only(&st.daemon.data.join("spectra.db")).await { |
| 144 | 1× | Ok(l) => l, |
| 145 | 0× | Err(e) => return bad(e), |
| 146 | | }; |
| 147 | 1× | match ledger.verify(&mut spectra_core::principals::Principals::default()).await { |
| 148 | 1× | Ok(v) => axum::Json(v).into_response(), |
| 149 | 0× | Err(e) => bad(e), |
| 150 | | } |
| 151 | 1× | } |
| 152 | |
|
| 153 | |
|
| 154 | 3× | async fn briefs( |
| 155 | 3× | State(st): State<AppState>, |
| 156 | 3× | ConnectInfo(peer): ConnectInfo<PeerInfo>, |
| 157 | 3× | headers: HeaderMap, |
| 158 | 3× | uri: axum::http::Uri, |
| 159 | 3× | ) -> Response { |
| 160 | 3× | let _ = who!(st, peer, headers, uri, "GET", b"", true); |
| 161 | 3× | let pool = st.daemon.ledger.pool(); |
| 162 | 3× | let overall = spectra_core::rules::layer(pool, None).await.ok().flatten(); |
| 163 | 3× | let rows: Vec<(String, String)> = sqlx::query_as("SELECT project, text FROM briefs WHERE layer = 'project' ORDER BY project") |
| 164 | 3× | .fetch_all(pool) |
| 165 | 3× | .await |
| 166 | 3× | .unwrap_or_default(); |
| 167 | 3× | json_etag( |
| 168 | 3× | &headers, |
| 169 | 4× | &api::Briefs { overall, projects: rows.into_iter().map(|(project, text)| api::ProjectBrief { project, text }).collect() }, |
| 170 | | ) |
| 171 | 3× | } |
| 172 | |
|
| 173 | |
|
| 174 | |
|
| 175 | 4× | async fn set_brief( |
| 176 | 4× | State(st): State<AppState>, |
| 177 | 4× | ConnectInfo(peer): ConnectInfo<PeerInfo>, |
| 178 | 4× | headers: HeaderMap, |
| 179 | 4× | uri: axum::http::Uri, |
| 180 | 4× | body: Bytes, |
| 181 | 4× | ) -> Response { |
| 182 | 4× | let c = who!(st, peer, headers, uri, "PUT", &body, false); |
| 183 | 4× | if !matches!(c.principal, Principal::Owner { .. }) { |
| 184 | 1× | return problem(StatusCode::FORBIDDEN, "only the owner sets a brief", None); |
| 185 | 3× | } |
| 186 | 3× | let b: api::SetBrief = match serde_json::from_slice(&body) { |
| 187 | 3× | Ok(b) => b, |
| 188 | 0× | Err(e) => return problem(StatusCode::BAD_REQUEST, "not a brief", Some(e.to_string())), |
| 189 | | }; |
| 190 | 3× | if let Err(e) = spectra_core::rules::check(&b.text) { |
| 191 | 0× | return problem(StatusCode::BAD_REQUEST, "too long", Some(e.to_string())); |
| 192 | 3× | } |
| 193 | 3× | let project = b.project.filter(|p| !p.is_empty()); |
| 194 | 3× | if let Some(p) = &project { |
| 195 | 2× | let known: Option<String> = sqlx::query_scalar("SELECT name FROM projects WHERE name = ?") |
| 196 | 2× | .bind(p) |
| 197 | 2× | .fetch_optional(st.daemon.ledger.pool()) |
| 198 | 2× | .await |
| 199 | 2× | .unwrap_or(None); |
| 200 | 2× | if known.is_none() { |
| 201 | 1× | return problem(StatusCode::NOT_FOUND, "no such project", Some(p.clone())); |
| 202 | 1× | } |
| 203 | 1× | } |
| 204 | 2× | let mut e = spectra_core::event::NewEvent::system("brief.set", serde_json::json!({ "project": project, "text": b.text })) |
| 205 | 2× | .by(c.principal.actor(), c.auth.clone()); |
| 206 | 2× | e.project = project.clone(); |
| 207 | 2× | match st.daemon.ledger.append_one(e).await { |
| 208 | 2× | Ok(ev) => axum::Json(serde_json::json!({ "seq": ev.seq })).into_response(), |
| 209 | 0× | Err(e) => bad(e), |
| 210 | | } |
| 211 | 4× | } |
| 212 | |
|
| 213 | 1× | async fn health() -> Response { |
| 214 | 1× | axum::Json(serde_json::json!({ "ok": true })).into_response() |
| 215 | 1× | } |
| 216 | |
|
| 217 | 1× | async fn version() -> Response { |
| 218 | | axum::Json(api::Version { |
| 219 | 1× | version: env!("CARGO_PKG_VERSION").into(), |
| 220 | | ledger_format: spectra_core::LEDGER_FORMAT, |
| 221 | 4× | mcp_protocol_versions: crate::PROTOCOL_VERSIONS.iter().map(|v| v.to_string()).collect(), |
| 222 | | }) |
| 223 | 1× | .into_response() |
| 224 | 1× | } |
| 225 | |
|
| 226 | 13× | async fn agent_list(st: &AppState) -> Vec<api::Agent> { |
| 227 | | #[allow(clippy::type_complexity)] |
| 228 | 13× | let rows: Vec<(String, String, String, String, String, Option<String>, Option<i64>)> = sqlx::query_as( |
| 229 | 13× | "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", |
| 230 | 13× | ) |
| 231 | 13× | .fetch_all(st.daemon.ledger.pool()) |
| 232 | 13× | .await |
| 233 | 13× | .unwrap_or_default(); |
| 234 | 13× | let presence = st.daemon.presence.lock().await; |
| 235 | 13× | let principals = st.daemon.principals.read().await; |
| 236 | 13× | let now = now_ms(); |
| 237 | 13× | rows.into_iter() |
| 238 | 14× | .map(|(name, owner, key, kind, project, status, disabled)| { |
| 239 | 14× | let k = spectra_core::identity::KeyId::from_hex(&key); |
| 240 | 14× | let state = match k.map(|k| principals.principal(&k, now)) { |
| 241 | 13× | Some(Ok(_)) => "ok".to_string(), |
| 242 | 1× | Some(Err(why)) => why, |
| 243 | 0× | None => "a malformed key".into(), |
| 244 | | }; |
| 245 | 14× | let delegation_expires = k.and_then(|k| principals.owner().and_then(|o| o.delegate(&k)).and_then(|d| d.expires)); |
| 246 | | api::Agent { |
| 247 | 14× | display: format!("{name} · {owner}'s agent"), |
| 248 | 14× | presence: if disabled.is_some() { "offline".into() } else { presence.state(&name, now).into() }, |
| 249 | 14× | disabled: disabled.is_some(), |
| 250 | 14× | name, |
| 251 | 14× | owner, |
| 252 | 14× | key, |
| 253 | 14× | kind, |
| 254 | 14× | project, |
| 255 | 14× | status, |
| 256 | 14× | state, |
| 257 | 14× | delegation_expires, |
| 258 | | } |
| 259 | 14× | }) |
| 260 | 13× | .collect() |
| 261 | 13× | } |
| 262 | |
|
| 263 | 11× | async fn agents( |
| 264 | 11× | State(st): State<AppState>, |
| 265 | 11× | ConnectInfo(peer): ConnectInfo<PeerInfo>, |
| 266 | 11× | headers: HeaderMap, |
| 267 | 11× | uri: axum::http::Uri, |
| 268 | 11× | ) -> Response { |
| 269 | 11× | let _ = who!(st, peer, headers, uri, "GET", b"", true); |
| 270 | 9× | json_etag(&headers, &agent_list(&st).await) |
| 271 | 11× | } |
| 272 | |
|
| 273 | 12× | async fn projects( |
| 274 | 12× | State(st): State<AppState>, |
| 275 | 12× | ConnectInfo(peer): ConnectInfo<PeerInfo>, |
| 276 | 12× | headers: HeaderMap, |
| 277 | 12× | uri: axum::http::Uri, |
| 278 | 12× | ) -> Response { |
| 279 | 12× | let _ = who!(st, peer, headers, uri, "GET", b"", true); |
| 280 | 12× | let pool = st.daemon.ledger.pool(); |
| 281 | 12× | let rows: Vec<(String, Option<String>, String, Option<String>)> = |
| 282 | 12× | sqlx::query_as("SELECT name, path, description, url FROM projects ORDER BY name").fetch_all(pool).await.unwrap_or_default(); |
| 283 | 12× | let mut out = Vec::new(); |
| 284 | 13× | for (name, path, description, url) in rows { |
| 285 | 13× | let depends_on = sqlx::query_scalar("SELECT depends_on FROM project_relations WHERE project = ? ORDER BY 1") |
| 286 | 13× | .bind(&name) |
| 287 | 13× | .fetch_all(pool) |
| 288 | 13× | .await |
| 289 | 13× | .unwrap_or_default(); |
| 290 | 13× | let depended_on_by = sqlx::query_scalar("SELECT project FROM project_relations WHERE depends_on = ? ORDER BY 1") |
| 291 | 13× | .bind(&name) |
| 292 | 13× | .fetch_all(pool) |
| 293 | 13× | .await |
| 294 | 13× | .unwrap_or_default(); |
| 295 | 13× | let agents = sqlx::query_scalar("SELECT name FROM agents WHERE project = ? AND disabled_ms IS NULL ORDER BY name") |
| 296 | 13× | .bind(&name) |
| 297 | 13× | .fetch_all(pool) |
| 298 | 13× | .await |
| 299 | 13× | .unwrap_or_default(); |
| 300 | 13× | out.push(api::Project { name, path, description, url, depends_on, depended_on_by, agents }); |
| 301 | | } |
| 302 | 12× | json_etag(&headers, &out) |
| 303 | 12× | } |
| 304 | |
|
| 305 | 1× | async fn channels( |
| 306 | 1× | State(st): State<AppState>, |
| 307 | 1× | ConnectInfo(peer): ConnectInfo<PeerInfo>, |
| 308 | 1× | headers: HeaderMap, |
| 309 | 1× | uri: axum::http::Uri, |
| 310 | 1× | ) -> Response { |
| 311 | 1× | let c = who!(st, peer, headers, uri, "GET", b"", true); |
| 312 | 1× | let all = match conv::channels(&st.daemon.ledger).await { |
| 313 | 1× | Ok(a) => a, |
| 314 | 0× | Err(e) => return bad(e), |
| 315 | | }; |
| 316 | 1× | let mut out = Vec::new(); |
| 317 | 4× | for ch in all.into_iter().filter(|ch| conv::can_read(&c.principal, ch)) { |
| 318 | 4× | let n: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM messages WHERE channel = ?") |
| 319 | 4× | .bind(&ch.id) |
| 320 | 4× | .fetch_one(st.daemon.ledger.pool()) |
| 321 | 4× | .await |
| 322 | 4× | .unwrap_or(0); |
| 323 | 4× | out.push(api::Channel { display: ch.display(), id: ch.id, name: ch.name, kind: ch.kind, purpose: ch.purpose, messages: n }); |
| 324 | | } |
| 325 | 1× | json_etag(&headers, &out) |
| 326 | 1× | } |
| 327 | |
|
| 328 | 4× | async fn to_api(st: &AppState, m: conv::Message, ch: &str) -> api::Message { |
| 329 | | api::Message { |
| 330 | 4× | author_display: conv::display_name(&st.daemon.ledger, &m.author).await, |
| 331 | 4× | mentions: serde_json::from_str(&m.mentions).unwrap_or_default(), |
| 332 | 4× | refs: serde_json::from_str(&m.refs).unwrap_or_default(), |
| 333 | 4× | redacted: m.redacted.is_some(), |
| 334 | 4× | id: m.id, |
| 335 | 4× | channel: ch.to_string(), |
| 336 | 4× | reply_to: m.reply_to, |
| 337 | 4× | author: m.author, |
| 338 | 4× | kind: m.kind, |
| 339 | 4× | body: m.body, |
| 340 | 4× | at_ms: m.at_ms, |
| 341 | 4× | replies: m.replies, |
| 342 | | } |
| 343 | 4× | } |
| 344 | |
|
| 345 | | #[derive(Deserialize)] |
| 346 | | struct PageQuery { |
| 347 | | after: Option<String>, |
| 348 | | limit: Option<u32>, |
| 349 | | } |
| 350 | |
|
| 351 | 1× | async fn messages( |
| 352 | 1× | State(st): State<AppState>, |
| 353 | 1× | ConnectInfo(peer): ConnectInfo<PeerInfo>, |
| 354 | 1× | headers: HeaderMap, |
| 355 | 1× | uri: axum::http::Uri, |
| 356 | 1× | Path(name): Path<String>, |
| 357 | 1× | Query(q): Query<PageQuery>, |
| 358 | 1× | ) -> Response { |
| 359 | 1× | let c = who!(st, peer, headers, uri, "GET", b"", true); |
| 360 | 1× | let limit = q.limit.unwrap_or(50).clamp(1, 500); |
| 361 | 1× | match conv::read(&st.daemon.ledger, &c.principal, Some(&name), None, q.after.as_deref(), limit).await { |
| 362 | 1× | Ok((ch, msgs)) => { |
| 363 | 1× | let next = (msgs.len() as u32 == limit).then(|| msgs.last().map(|m| m.id.clone())).flatten(); |
| 364 | 1× | let mut items = Vec::new(); |
| 365 | 2× | for m in msgs { |
| 366 | 2× | items.push(to_api(&st, m, &ch.display()).await); |
| 367 | | } |
| 368 | 1× | json_etag(&headers, &api::Messages { channel: ch.display(), items, next }) |
| 369 | | } |
| 370 | 0× | Err(e) => problem(StatusCode::NOT_FOUND, "no such channel, or not yours to read", Some(format!("{e:#}"))), |
| 371 | | } |
| 372 | 1× | } |
| 373 | |
|
| 374 | 1× | async fn thread( |
| 375 | 1× | State(st): State<AppState>, |
| 376 | 1× | ConnectInfo(peer): ConnectInfo<PeerInfo>, |
| 377 | 1× | headers: HeaderMap, |
| 378 | 1× | uri: axum::http::Uri, |
| 379 | 1× | Path(id): Path<String>, |
| 380 | 1× | Query(q): Query<PageQuery>, |
| 381 | 1× | ) -> Response { |
| 382 | 1× | let c = who!(st, peer, headers, uri, "GET", b"", true); |
| 383 | 1× | let limit = q.limit.unwrap_or(200).clamp(1, 500); |
| 384 | 1× | match conv::read(&st.daemon.ledger, &c.principal, None, Some(&id), q.after.as_deref(), limit).await { |
| 385 | 1× | Ok((ch, msgs)) => { |
| 386 | 1× | let next = (msgs.len() as u32 == limit).then(|| msgs.last().map(|m| m.id.clone())).flatten(); |
| 387 | 1× | let mut items = Vec::new(); |
| 388 | 2× | for m in msgs { |
| 389 | 2× | items.push(to_api(&st, m, &ch.display()).await); |
| 390 | | } |
| 391 | 1× | json_etag(&headers, &api::Messages { channel: ch.display(), items, next }) |
| 392 | | } |
| 393 | 0× | Err(e) => problem(StatusCode::NOT_FOUND, "no such thread, or not yours to read", Some(format!("{e:#}"))), |
| 394 | | } |
| 395 | 1× | } |
| 396 | |
|
| 397 | 10× | async fn post_message( |
| 398 | 10× | State(st): State<AppState>, |
| 399 | 10× | ConnectInfo(peer): ConnectInfo<PeerInfo>, |
| 400 | 10× | headers: HeaderMap, |
| 401 | 10× | uri: axum::http::Uri, |
| 402 | 10× | Path(name): Path<String>, |
| 403 | 10× | body: Bytes, |
| 404 | 10× | ) -> Response { |
| 405 | 10× | let c = who!(st, peer, headers, uri, "POST", &body, false); |
| 406 | 10× | let n: api::NewMessage = match serde_json::from_slice(&body) { |
| 407 | 10× | Ok(n) => n, |
| 408 | 0× | Err(e) => return problem(StatusCode::BAD_REQUEST, "not a message", Some(e.to_string())), |
| 409 | | }; |
| 410 | 10× | let author = Author { principal: c.principal.clone(), signer: Signer::Request(c.auth.clone()) }; |
| 411 | 10× | let post = Post { |
| 412 | 10× | channel: if n.reply_to.is_some() { None } else { Some(name) }, |
| 413 | 10× | body: n.body, |
| 414 | 10× | reply_to: n.reply_to, |
| 415 | 10× | kind: n.kind, |
| 416 | 10× | ..Default::default() |
| 417 | | }; |
| 418 | 10× | match conv::post(&st.daemon.ledger, &author, post, now_ms()).await { |
| 419 | 9× | Ok(Posted::Message { id, channel }) => { |
| 420 | 9× | (StatusCode::CREATED, axum::Json(api::Posted { id, channel, duplicate: false })).into_response() |
| 421 | | } |
| 422 | 0× | Ok(Posted::Duplicate { id }) => axum::Json(api::Posted { id, channel: String::new(), duplicate: true }).into_response(), |
| 423 | 1× | Err(e) => bad(e), |
| 424 | | } |
| 425 | 10× | } |
| 426 | |
|
| 427 | 9× | async fn inbox_items(st: &AppState, actor: &str) -> Vec<api::InboxItem> { |
| 428 | 9× | let mut out = Vec::new(); |
| 429 | 9× | for i in conv::inbox(&st.daemon.ledger, actor, None).await.unwrap_or_default() { |
| 430 | 6× | let from_display = conv::display_name(&st.daemon.ledger, &i.from).await; |
| 431 | 6× | out.push(api::InboxItem { |
| 432 | 6× | id: i.id, |
| 433 | 6× | kind: i.kind, |
| 434 | 6× | at_ms: i.at_ms, |
| 435 | 6× | from: i.from, |
| 436 | 6× | from_display, |
| 437 | 6× | channel: i.channel, |
| 438 | 6× | summary: i.summary, |
| 439 | 6× | }); |
| 440 | | } |
| 441 | 9× | out |
| 442 | 9× | } |
| 443 | |
|
| 444 | 5× | async fn inbox(State(st): State<AppState>, ConnectInfo(peer): ConnectInfo<PeerInfo>, headers: HeaderMap, uri: axum::http::Uri) -> Response { |
| 445 | 5× | let c = who!(st, peer, headers, uri, "GET", b"", true); |
| 446 | 5× | json_etag(&headers, &inbox_items(&st, &c.principal.actor()).await) |
| 447 | 5× | } |
| 448 | |
|
| 449 | 1× | async fn ack( |
| 450 | 1× | State(st): State<AppState>, |
| 451 | 1× | ConnectInfo(peer): ConnectInfo<PeerInfo>, |
| 452 | 1× | headers: HeaderMap, |
| 453 | 1× | uri: axum::http::Uri, |
| 454 | 1× | body: Bytes, |
| 455 | 1× | ) -> Response { |
| 456 | 1× | let c = who!(st, peer, headers, uri, "POST", &body, false); |
| 457 | 1× | let a: api::Ack = match serde_json::from_slice(&body) { |
| 458 | 1× | Ok(a) => a, |
| 459 | 0× | Err(e) => return problem(StatusCode::BAD_REQUEST, "not an ack", Some(e.to_string())), |
| 460 | | }; |
| 461 | 1× | let author = Author { principal: c.principal, signer: Signer::Request(c.auth) }; |
| 462 | 1× | match conv::ack(&st.daemon.ledger, &author, &a.ids, a.reaction.as_deref()).await { |
| 463 | 1× | Ok(n) => axum::Json(serde_json::json!({ "read": n })).into_response(), |
| 464 | 0× | Err(e) => bad(e), |
| 465 | | } |
| 466 | 1× | } |
| 467 | |
|
| 468 | 4× | async fn brief(State(st): State<AppState>, ConnectInfo(peer): ConnectInfo<PeerInfo>, headers: HeaderMap, uri: axum::http::Uri) -> Response { |
| 469 | 4× | let c = who!(st, peer, headers, uri, "GET", b"", true); |
| 470 | 4× | let project = match &c.principal { |
| 471 | 1× | Principal::Agent { project, .. } => Some(project.clone()), |
| 472 | 3× | _ => None, |
| 473 | | }; |
| 474 | 4× | let rules = spectra_core::rules::compile(st.daemon.ledger.pool(), project.as_deref()).await.map(|r| r.version).unwrap_or_default(); |
| 475 | 4× | let inbox = inbox_items(&st, &c.principal.actor()).await; |
| 476 | 4× | let b = api::Brief { |
| 477 | 4× | you: c.principal.display(), |
| 478 | 4× | actor: c.principal.actor(), |
| 479 | 4× | project, |
| 480 | 4× | rules_version: rules, |
| 481 | 4× | unread: inbox.len() as i64, |
| 482 | 4× | inbox, |
| 483 | 4× | agents: agent_list(&st).await, |
| 484 | 4× | head: st.daemon.ledger.head().await.0, |
| 485 | | }; |
| 486 | 4× | json_etag(&headers, &b) |
| 487 | 4× | } |
| 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 | |
|
| 498 | 3× | async fn search( |
| 499 | 3× | State(st): State<AppState>, |
| 500 | 3× | ConnectInfo(peer): ConnectInfo<PeerInfo>, |
| 501 | 3× | headers: HeaderMap, |
| 502 | 3× | uri: axum::http::Uri, |
| 503 | 3× | Query(q): Query<SearchQuery>, |
| 504 | 3× | ) -> Response { |
| 505 | 3× | let c = who!(st, peer, headers, uri, "GET", b"", true); |
| 506 | 3× | let since = q.since.as_deref().and_then(|s| crate::tools::parse_since(s, now_ms())); |
| 507 | 3× | 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 | | { |
| 509 | 3× | Ok(hits) => { |
| 510 | 3× | let mut out: Vec<api::Hit> = Vec::new(); |
| 511 | 5× | for h in hits { |
| 512 | 5× | let author_display = conv::display_name(&st.daemon.ledger, &h.author).await; |
| 513 | 5× | out.push(api::Hit { |
| 514 | 5× | id: h.id, |
| 515 | 5× | channel: h.channel, |
| 516 | 5× | author: h.author, |
| 517 | 5× | at_ms: h.at_ms, |
| 518 | 5× | snippet: h.snippet, |
| 519 | 5× | thread: h.thread, |
| 520 | 5× | author_display, |
| 521 | 5× | }); |
| 522 | | } |
| 523 | 3× | json_etag(&headers, &out) |
| 524 | | } |
| 525 | 0× | Err(e) => bad(e), |
| 526 | | } |
| 527 | 3× | } |
| 528 | |
|
| 529 | | #[derive(Deserialize)] |
| 530 | | struct EventsQuery { |
| 531 | | after: Option<u64>, |
| 532 | | kind: Option<String>, |
| 533 | | limit: Option<u32>, |
| 534 | | follow: Option<u8>, |
| 535 | | |
| 536 | | max: Option<usize>, |
| 537 | | } |
| 538 | |
|
| 539 | 13× | fn summary(e: &spectra_core::event::Event) -> api::EventSummary { |
| 540 | 13× | api::EventSummary { |
| 541 | 13× | seq: e.seq, |
| 542 | 13× | id: e.id.clone(), |
| 543 | 13× | at_ms: e.at_ms, |
| 544 | 13× | kind: e.kind.clone(), |
| 545 | 13× | actor: e.actor.clone(), |
| 546 | 13× | subject: e.subject.clone(), |
| 547 | 13× | method: e.auth.method.name().into(), |
| 548 | 13× | assurance: e.auth.assurance, |
| 549 | 13× | hash: hex::encode(e.hash), |
| 550 | 13× | } |
| 551 | 13× | } |
| 552 | |
|
| 553 | |
|
| 554 | 5× | async fn events( |
| 555 | 5× | State(st): State<AppState>, |
| 556 | 5× | ConnectInfo(peer): ConnectInfo<PeerInfo>, |
| 557 | 5× | headers: HeaderMap, |
| 558 | 5× | uri: axum::http::Uri, |
| 559 | 5× | Query(q): Query<EventsQuery>, |
| 560 | 5× | ) -> Response { |
| 561 | 5× | let c = who!(st, peer, headers, uri, "GET", b"", true); |
| 562 | | |
| 563 | | |
| 564 | 5× | if !matches!(c.principal, Principal::Owner { .. }) { |
| 565 | 1× | return problem(StatusCode::FORBIDDEN, "the event log is the owner's", None); |
| 566 | 4× | } |
| 567 | 4× | if q.follow == Some(1) { |
| 568 | 2× | let kind = q.kind.clone(); |
| 569 | 2× | let rx = st.daemon.ledger.subscribe(); |
| 570 | 2× | let stream = tokio_stream::wrappers::BroadcastStream::new(rx) |
| 571 | 4× | .filter_map(move |e| { |
| 572 | 4× | let kind = kind.clone(); |
| 573 | 4× | async move { |
| 574 | 4× | let e = e.ok()?; |
| 575 | 4× | if kind.as_ref().is_some_and(|k| *k != e.kind) { |
| 576 | 2× | return None; |
| 577 | 2× | } |
| 578 | 2× | Some(Ok::<_, std::convert::Infallible>( |
| 579 | 2× | SseEvent::default().data(serde_json::to_string(&summary(&e)).unwrap_or_default()), |
| 580 | 2× | )) |
| 581 | 4× | } |
| 582 | 4× | }) |
| 583 | 2× | .take(q.max.unwrap_or(usize::MAX)); |
| 584 | | |
| 585 | | |
| 586 | 2× | let hello = futures::stream::once(async { Ok::<_, std::convert::Infallible>(SseEvent::default().comment("subscribed")) }); |
| 587 | 2× | return Sse::new(hello.chain(stream)).keep_alive(KeepAlive::new().interval(Duration::from_secs(15))).into_response(); |
| 588 | 2× | } |
| 589 | 2× | let limit = q.limit.unwrap_or(100).clamp(1, 1000); |
| 590 | 2× | let from = q.after.map(|a| a + 1).unwrap_or(1); |
| 591 | 2× | let evs = match &q.kind { |
| 592 | 1× | Some(k) => st.daemon.ledger.events_of_kinds(from, &[k.as_str()], limit).await, |
| 593 | 1× | None => st.daemon.ledger.events(from, limit).await, |
| 594 | | }; |
| 595 | 2× | match evs { |
| 596 | 2× | Ok(evs) => { |
| 597 | 2× | let next = (evs.len() as u32 == limit).then(|| evs.last().map(|e| e.seq)).flatten(); |
| 598 | 2× | json_etag(&headers, &api::Events { items: evs.iter().map(summary).collect(), next }) |
| 599 | | } |
| 600 | 0× | Err(e) => bad(e), |
| 601 | | } |
| 602 | 5× | } |