-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproduction_streaming.rs
More file actions
392 lines (344 loc) · 13.7 KB
/
Copy pathproduction_streaming.rs
File metadata and controls
392 lines (344 loc) · 13.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
//! # Production Streaming: Axum SSE + Postgres Checkpointing
//!
//! The **golden path** reference example for production web-server consumers.
//!
//! Demonstrates the complete pattern for a production web server that:
//!
//! - Compiles a [`GraphBuilder`] with [`RuntimeConfig`] once at startup
//! - Shares the compiled [`App`] across concurrent requests via [`Arc`]
//! - Checkpoints state to Postgres via [`PostgresCheckpointer`] for durable resumption
//! - Streams workflow events to HTTP clients via Server-Sent Events (SSE)
//! - Terminates the SSE stream cleanly on [`STREAM_END_SCOPE`]
//! - Supports per-request cancellation via [`InvocationHandle::abort`]
//! - Handles node errors uniformly with [`NodeError::Other`]
//!
//! ## Architecture
//!
//! ```text
//! HTTP Client GET /run?prompt=hello
//! │
//! ▼
//! ┌──────────────────────────────────────────────────────┐
//! │ Axum Handler run_handler() │
//! │ ┌─ app.invoke_streaming(state) ──────────────────┐ │
//! │ │ Returns (InvocationHandle, EventStream) │ │
//! │ │ Workflow runs in background tokio task │ │
//! │ └────────────────────────────────────────────────┘ │
//! │ Returns Sse<impl Stream<Item=SseEvent>> │
//! └──────────────────────────────────────────────────────┘
//! │
//! │ data: {"kind":"llm","message":"token1",...}
//! │ data: {"kind":"diagnostic","scope":"__weavegraph_stream_end__",...}
//! │ [stream closed by server]
//! ▼
//! HTTP Client
//! ```
//!
//! ## Per-Request Isolation
//!
//! Each request gets its own [`AppRunner`] (and therefore its own [`EventBus`])
//! via [`App::invoke_streaming`]. The [`App`] itself is a cheap [`Arc`] clone.
//! This is the canonical concurrency pattern for streaming workflows.
//!
//! ## Feature Requirements
//!
//! ```bash
//! cargo run --example production_streaming --features postgres-migrations,examples
//! ```
//!
//! Set `DATABASE_URL` before running:
//!
//! ```bash
//! export DATABASE_URL="postgres://postgres:postgres@localhost/weavegraph"
//! cargo run --example production_streaming --features postgres-migrations,examples
//! ```
//!
//! ## Testing
//!
//! ```bash
//! curl -N "http://localhost:3000/run?prompt=hello+world"
//! ```
use std::{convert::Infallible, sync::Arc, time::Duration};
use async_trait::async_trait;
use axum::{
Router,
extract::{Query, State},
response::{
IntoResponse,
sse::{Event as SseEvent, KeepAlive, Sse},
},
routing::get,
};
use futures_util::{Stream, StreamExt};
use serde::{Deserialize, Serialize};
use tracing::{error, info, warn};
use tracing_subscriber::{EnvFilter, layer::SubscriberExt, util::SubscriberInitExt};
use weavegraph::{
app::{App, InvocationHandle},
channels::Channel,
event_bus::{Event, EventStream, STREAM_END_SCOPE},
graphs::GraphBuilder,
message::{Message, Role},
node::{Node, NodeContext, NodeError, NodePartial, NodeResultExt},
runtimes::{EventBusConfig, PostgresCheckpointer, RuntimeConfig},
state::{StateSnapshot, VersionedState},
types::NodeKind,
};
type BoxError = Box<dyn std::error::Error + Send + Sync>;
// ============================================================================
// Node definitions
// ============================================================================
/// Simulates an LLM node that streams a response token by token.
///
/// In a real application this would call an LLM provider and emit each
/// chunk via [`NodeContext::emit`] so clients receive tokens as they arrive.
#[derive(Clone)]
struct LlmNode;
#[async_trait]
impl Node for LlmNode {
async fn run(
&self,
snapshot: StateSnapshot,
ctx: NodeContext,
) -> Result<NodePartial, NodeError> {
let prompt = snapshot
.messages
.last()
.map(|m| m.content.as_str())
.unwrap_or("(no input)");
// Simulate token streaming — in production, replace with your LLM call.
// Note: ctx.emit() produces a NodeEvent (SSE kind="node"). Real LLM
// provider streaming via the `rig` feature produces Event::LLM (kind="llm").
let tokens = [
"Hello",
", ",
"I",
" am",
" a",
" streaming",
" assistant",
"!",
];
for token in tokens {
ctx.emit("llm.token", format!("Response to '{}': {}", prompt, token))?;
// Simulate token generation latency.
tokio::time::sleep(Duration::from_millis(150)).await;
}
Ok(NodePartial::new().with_messages(vec![Message::with_role(
Role::Assistant,
&format!("Response to '{}'", prompt),
)]))
}
}
/// A validation node demonstrating `NodeError::Other` for recoverable failures.
///
/// Input validation belongs at the node boundary where the error context is
/// richest. Use [`NodeResultExt::node_err`] to lift arbitrary errors into
/// [`NodeError::Other`] without losing the original message.
#[derive(Clone)]
struct ValidateNode;
#[async_trait]
impl Node for ValidateNode {
async fn run(
&self,
snapshot: StateSnapshot,
_ctx: NodeContext,
) -> Result<NodePartial, NodeError> {
let prompt = snapshot
.messages
.last()
.map(|m| m.content.as_str())
.unwrap_or("");
if prompt.trim().is_empty() {
return Err(NodeError::Other("prompt must not be empty".into()));
}
if prompt.len() > 4096 {
return Err(NodeError::Other(
format!("prompt too long: {} chars (max 4096)", prompt.len()).into(),
));
}
// Use NodeResultExt for fallible stdlib operations.
let _validated = std::str::from_utf8(prompt.as_bytes()).node_err()?;
Ok(NodePartial::new())
}
}
// ============================================================================
// Application state
// ============================================================================
/// Shared application state injected into every Axum handler.
#[derive(Clone)]
struct AppState {
app: Arc<App>,
}
// ============================================================================
// HTTP handlers
// ============================================================================
#[derive(Debug, Deserialize)]
struct RunQuery {
#[serde(default = "default_prompt")]
prompt: String,
}
fn default_prompt() -> String {
"Hello, weavegraph!".to_string()
}
/// `GET /run?prompt=...`
///
/// Starts a workflow invocation and returns an SSE stream of events.
///
/// Each event is a JSON-serialized [`weavegraph::event_bus::Event`].
/// The stream terminates with a special diagnostic event whose scope is
/// [`STREAM_END_SCOPE`]; consumers should close the connection on receipt.
///
/// ## Per-Request Isolation
///
/// Each request gets its own [`AppRunner`] (via `App::invoke_streaming`).
/// The shared [`App`] is a cheap [`Arc`] clone; only the runner (with its
/// own [`EventBus`]) is created per request. This is the canonical pattern
/// for concurrent SSE in production.
async fn run_handler(
State(state): State<AppState>,
Query(query): Query<RunQuery>,
) -> impl IntoResponse {
info!(prompt = %query.prompt, "starting workflow invocation");
let initial_state = VersionedState::new_with_user_message(&query.prompt);
// invoke_streaming returns immediately; the workflow runs in a background task.
let (handle, event_stream) = state.app.invoke_streaming(initial_state).await;
// Convert the EventStream into an SSE-compatible futures Stream.
let sse_stream = build_sse_stream(handle, event_stream);
Sse::new(sse_stream).keep_alive(
KeepAlive::new()
.interval(Duration::from_secs(15))
.text("keep-alive"),
)
}
/// Wraps the weavegraph [`EventStream`] as a futures [`Stream`] of SSE frames.
///
/// - Serializes each event to JSON and wraps it in an `SseEvent`.
/// - Watches for [`STREAM_END_SCOPE`] to terminate the stream gracefully.
/// - Aborts the workflow task via [`InvocationHandle`] if the client disconnects.
fn build_sse_stream(
handle: InvocationHandle,
event_stream: EventStream,
) -> impl Stream<Item = Result<SseEvent, Infallible>> {
let handle = Arc::new(tokio::sync::Mutex::new(Some(handle)));
// Convert EventStream into an async stream of SseEvent.
let stream = event_stream.into_async_stream().map(move |event| {
let is_end = event
.scope_label()
.map(|s| s == STREAM_END_SCOPE)
.unwrap_or(false);
let payload = serde_json::to_string(&SsePayload::from(&event))
.unwrap_or_else(|_| r#"{"error":"serialization failed"}"#.to_string());
let sse = SseEvent::default().data(payload);
(sse, is_end)
});
// Take-while inclusive: emit the STREAM_END event, then stop.
futures_util::stream::unfold(
(stream.boxed(), false, handle),
move |(mut stream, done, handle)| async move {
if done {
// Join the workflow handle so its task is properly reaped.
if let Some(h) = handle.lock().await.take() {
match h.join().await {
Ok(state) => info!(
messages = state.messages.len(),
"workflow completed successfully"
),
Err(e) => warn!(error = %e, "workflow ended with error"),
}
}
return None;
}
match stream.next().await {
Some((sse, is_end)) => Some((Ok(sse), (stream, is_end, handle))),
None => {
// Stream closed unexpectedly (e.g., workflow panicked).
error!("event stream closed without STREAM_END_SCOPE");
None
}
}
},
)
}
/// Lightweight SSE payload wrapping the weavegraph event.
///
/// In production you may want to normalise the shape further — this keeps
/// the full event detail available while adding a top-level discriminant.
#[derive(Debug, Serialize)]
struct SsePayload {
kind: &'static str,
message: String,
scope: Option<String>,
}
impl From<&Event> for SsePayload {
fn from(event: &Event) -> Self {
Self {
kind: match event {
Event::Node(_) => "node",
Event::Diagnostic(_) => "diagnostic",
Event::LLM(_) => "llm",
},
message: event.message().to_string(),
scope: event.scope_label().map(str::to_string),
}
}
}
/// `GET /healthz` — liveness probe for container orchestration.
async fn healthz() -> &'static str {
"ok"
}
// ============================================================================
// Startup and graph compilation
// ============================================================================
/// Build and compile the workflow graph with Postgres checkpointing.
///
/// This runs **once** at startup. The compiled [`App`] is wrapped in [`Arc`]
/// and shared across all handlers for the lifetime of the server. Graph
/// compilation is O(V+E) and negligible relative to request handling.
async fn build_app() -> Result<App, BoxError> {
dotenvy::dotenv().ok();
let db_url = std::env::var("DATABASE_URL")
.unwrap_or_else(|_| "postgres://postgres:postgres@localhost/weavegraph".to_string());
// Connect to Postgres. When the `postgres-migrations` feature is enabled,
// schema migrations are run automatically on connect.
let pg = PostgresCheckpointer::connect(&db_url).await?;
// Attach the postgres checkpointer via checkpointer_custom().
// This takes precedence over any CheckpointerType enum variant.
let runtime_config = RuntimeConfig::new(None, None)
.checkpointer_custom(Arc::new(pg))
.with_event_bus(EventBusConfig::with_stdout_only());
let app = GraphBuilder::new()
.add_node(NodeKind::Custom("validate".into()), ValidateNode)
.add_node(NodeKind::Custom("llm".into()), LlmNode)
.add_edge(NodeKind::Start, NodeKind::Custom("validate".into()))
.add_edge(
NodeKind::Custom("validate".into()),
NodeKind::Custom("llm".into()),
)
.add_edge(NodeKind::Custom("llm".into()), NodeKind::End)
.with_runtime_config(runtime_config)
.compile()?;
info!(db_url = %db_url, "graph compiled with postgres checkpointing");
Ok(app)
}
// ============================================================================
// Main entry point
// ============================================================================
#[tokio::main]
async fn main() -> Result<(), BoxError> {
tracing_subscriber::registry()
.with(tracing_subscriber::fmt::layer())
.with(EnvFilter::from_default_env().add_directive("info".parse().unwrap()))
.init();
let app = build_app().await?;
let state = AppState { app: Arc::new(app) };
let router = Router::new()
.route("/run", get(run_handler))
.route("/healthz", get(healthz))
.with_state(state);
let addr = "0.0.0.0:3000";
info!(addr, "production_streaming server listening");
let listener = tokio::net::TcpListener::bind(addr).await?;
axum::serve(listener, router).await?;
Ok(())
}