systemprompt_api/routes/stream/
mod.rs1use axum::extract::Extension;
2use axum::response::sse::Sse;
3use axum::response::IntoResponse;
4use axum::routing::get;
5use axum::Router;
6use std::convert::Infallible;
7use std::sync::{Arc, LazyLock};
8use systemprompt_agent::services::ContextProviderService;
9use systemprompt_events::{
10 standard_keep_alive, Broadcaster, ConnectionGuard, GenericBroadcaster, ToSse, A2A_BROADCASTER,
11 AGUI_BROADCASTER,
12};
13use systemprompt_models::RequestContext;
14use systemprompt_runtime::AppContext;
15use tokio::sync::mpsc;
16use tokio_stream::wrappers::UnboundedReceiverStream;
17
18pub mod contexts;
19
20#[derive(Clone, Debug)]
21pub struct StreamState {
22 pub context_provider: Arc<ContextProviderService>,
23}
24
25pub fn stream_router(ctx: &AppContext) -> Router {
26 let state = StreamState {
27 context_provider: Arc::new(ContextProviderService::new(ctx.db_pool().clone())),
28 };
29
30 Router::new()
31 .route("/contexts", get(contexts::stream_context_state))
32 .route("/agui", get(stream_agui_events))
33 .route("/a2a", get(stream_a2a_events))
34 .with_state(state)
35}
36
37pub async fn stream_a2a_events(
38 Extension(request_context): Extension<RequestContext>,
39) -> impl IntoResponse {
40 create_sse_stream(&request_context, &A2A_BROADCASTER, "A2A").await
41}
42
43pub async fn stream_agui_events(
44 Extension(request_context): Extension<RequestContext>,
45) -> impl IntoResponse {
46 create_sse_stream(&request_context, &AGUI_BROADCASTER, "AgUI").await
47}
48
49#[derive(Debug)]
50pub struct StreamWithGuard<E: ToSse + Clone + Send + Sync + 'static> {
51 stream: UnboundedReceiverStream<Result<axum::response::sse::Event, Infallible>>,
52 _cleanup_guard: ConnectionGuard<E>,
53}
54
55impl<E: ToSse + Clone + Send + Sync + 'static> StreamWithGuard<E> {
56 pub fn new(
57 stream: UnboundedReceiverStream<Result<axum::response::sse::Event, Infallible>>,
58 cleanup_guard: ConnectionGuard<E>,
59 ) -> Self {
60 Self {
61 stream,
62 _cleanup_guard: cleanup_guard,
63 }
64 }
65}
66
67impl<E: ToSse + Clone + Send + Sync + 'static> futures_util::Stream for StreamWithGuard<E> {
68 type Item = Result<axum::response::sse::Event, Infallible>;
69
70 fn poll_next(
71 mut self: std::pin::Pin<&mut Self>,
72 cx: &mut std::task::Context<'_>,
73 ) -> std::task::Poll<Option<Self::Item>> {
74 std::pin::Pin::new(&mut self.stream).poll_next(cx)
75 }
76}
77
78pub async fn create_sse_stream<E: ToSse + Clone + Send + Sync + 'static>(
79 request_context: &RequestContext,
80 broadcaster: &'static LazyLock<GenericBroadcaster<E>>,
81 stream_name: &str,
82) -> impl IntoResponse {
83 let user_id = request_context.user_id().clone();
84 let user_id_str = user_id.to_string();
85 let conn_id = uuid::Uuid::new_v4().to_string();
86
87 tracing::info!(user_id = %user_id_str, conn_id = %conn_id, stream = %stream_name, "SSE stream opened");
88
89 let (tx, rx) = mpsc::unbounded_channel();
90
91 broadcaster.register(&user_id, &conn_id, tx.clone()).await;
92
93 let cleanup_guard = ConnectionGuard::new(broadcaster, user_id, conn_id.clone());
94 let stream = UnboundedReceiverStream::new(rx);
95 let stream_with_guard = StreamWithGuard::<E>::new(stream, cleanup_guard);
96
97 tracing::info!(user_id = %user_id_str, conn_id = %conn_id, stream = %stream_name, "SSE stream ready");
98
99 Sse::new(stream_with_guard)
100 .keep_alive(standard_keep_alive())
101 .into_response()
102}