refactor(web_ui): split into a module dir by concern, serve stays in mod.rs
This commit is contained in:
parent
efaf56c2d5
commit
bdfeac80a7
8 changed files with 1311 additions and 1232 deletions
70
hive-ag3nt/src/web_ui/stream.rs
Normal file
70
hive-ag3nt/src/web_ui/stream.rs
Normal file
|
|
@ -0,0 +1,70 @@
|
|||
//! Live SSE event stream + history endpoints.
|
||||
|
||||
use std::convert::Infallible;
|
||||
|
||||
use axum::Json;
|
||||
use axum::extract::{Query, State};
|
||||
use axum::response::sse::{Event, KeepAlive, Sse};
|
||||
use serde::Deserialize;
|
||||
use tokio_stream::{Stream, StreamExt, wrappers::BroadcastStream};
|
||||
|
||||
use super::AppState;
|
||||
|
||||
/// Query params for the paginated history endpoint.
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub(super) struct HistoryParams {
|
||||
/// Cursor: only return events with sqlite row id < `before`.
|
||||
/// Omit for the initial (most-recent) page.
|
||||
before: Option<i64>,
|
||||
/// Page size (default 100, capped at `HISTORY_CAPACITY`).
|
||||
limit: Option<usize>,
|
||||
}
|
||||
|
||||
pub(super) async fn events_history(
|
||||
State(state): State<AppState>,
|
||||
Query(params): Query<HistoryParams>,
|
||||
) -> Json<serde_json::Value> {
|
||||
use crate::events::HISTORY_CAPACITY;
|
||||
let limit = params.limit.unwrap_or(100).min(HISTORY_CAPACITY);
|
||||
let before = params.before;
|
||||
let is_initial = before.is_none();
|
||||
|
||||
// Capture seq *before* the read on initial loads so the SSE dedupe
|
||||
// window is "drop buffered events you've already seen in history",
|
||||
// never "lose an event that fired between the read and the seq."
|
||||
// On paginated loads (`before` is set) seq is not needed.
|
||||
let seq = if is_initial {
|
||||
Some(state.bus.current_seq())
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let (events, min_id, has_more) = state.bus.history_page(before, limit);
|
||||
let mut resp = serde_json::json!({
|
||||
"events": events,
|
||||
"min_id": min_id,
|
||||
"has_more": has_more,
|
||||
});
|
||||
if let Some(s) = seq {
|
||||
resp["seq"] = serde_json::json!(s);
|
||||
}
|
||||
Json(resp)
|
||||
}
|
||||
|
||||
pub(super) async fn events_stream(
|
||||
State(state): State<AppState>,
|
||||
) -> Sse<impl Stream<Item = Result<Event, Infallible>>> {
|
||||
tracing::info!("sse: client subscribed");
|
||||
let rx = state.bus.subscribe();
|
||||
// Drop a "hello" note into the bus so every new subscriber sees at
|
||||
// least one event immediately and can clear the connecting placeholder.
|
||||
state.bus.emit(crate::events::LiveEvent::Note {
|
||||
text: "live stream attached".into(),
|
||||
});
|
||||
let stream = BroadcastStream::new(rx).filter_map(|res| {
|
||||
let ev = res.ok()?;
|
||||
let json = serde_json::to_string(&ev).ok()?;
|
||||
Some(Ok(Event::default().data(json)))
|
||||
});
|
||||
Sse::new(stream).keep_alive(KeepAlive::default())
|
||||
}
|
||||
Loading…
Reference in a new issue