| 1 | //! KB 事件流(SSE):文档摄入/抽取状态与审核队列变化的实时推送。 |
| 2 | //! 前端收到事件只做 react-query 失效重取——事件本身不带业务数据,天然幂等。 |
| 3 | |
| 4 | use axum::extract::{Path, State}; |
| 5 | use axum::response::sse::{Event, KeepAlive, Sse}; |
| 6 | use futures_util::Stream; |
| 7 | use std::convert::Infallible; |
| 8 | use tokio::sync::broadcast; |
| 9 | use utopia_core::models::Role; |
| 10 | use uuid::Uuid; |
| 11 | |
| 12 | use crate::auth::AuthUser; |
| 13 | use crate::error::ApiResult; |
| 14 | use crate::state::AppState; |
| 15 | |
| 16 | pub async fn kb_events( |
| 17 | State(state): State<AppState>, |
| 18 | AuthUser(user): AuthUser, |
| 19 | Path(kb_id): Path<Uuid>, |
| 20 | ) -> ApiResult<Sse<impl Stream<Item = Result<Event, Infallible>>>> { |
| 21 | utopia_store::access::require_kb(&state.pool, &user, kb_id, Role::Viewer).await?; |
| 22 | |
| 23 | let mut rx = state.events.subscribe(); |
| 24 | let stream = async_stream::stream! { |
| 25 | loop { |
| 26 | match rx.recv().await { |
| 27 | Ok(ev) if ev.kb_id == Some(kb_id) => { |
| 28 | yield Ok(Event::default() |
| 29 | .event(ev.kind) |
| 30 | .data(serde_json::to_string(&ev).unwrap_or_else(|_| "{}".into()))); |
| 31 | } |
| 32 | Ok(_) => continue, |
| 33 | // 消费落后被跳帧:无所谓,事件只是"该刷新了"的信号 |
| 34 | Err(broadcast::error::RecvError::Lagged(_)) => continue, |
| 35 | Err(broadcast::error::RecvError::Closed) => return, |
| 36 | } |
| 37 | } |
| 38 | }; |
| 39 | Ok(Sse::new(stream).keep_alive(KeepAlive::default())) |
| 40 | } |