graph_flow/runner.rs
1//! FlowRunner – convenience wrapper that loads a session, executes exactly **one** graph step, and
2//! persists the updated session back to storage.
3//!
4//! ## When should you use `FlowRunner`?
5//! * **Interactive workflows / web services**: you usually want to run _one_ step per HTTP
6//! request, send the assistant's reply back to the client, and have the session automatically
7//! saved for the next roundtrip. `FlowRunner` makes that a one-liner.
8//! * **CLI demos & examples**: keeps example code tiny; no need to repeat the
9//! load-execute-save boilerplate.
10//!
11//! ## When should you use `Graph::execute_session` directly?
12//! * **Batch processing** where you intentionally want to run many steps in a tight loop and save
13//! once at the end to reduce I/O.
14//! * **Custom persistence logic** (e.g. optimistic locking, distributed transactions).
15//! * **Advanced diagnostics** where you want to inspect the intermediate `Session` before saving.
16//!
17//! Both APIs are 100 % compatible – `FlowRunner` merely builds on top of the low-level function.
18//!
19//! ## Patterns for Stateless HTTP Services
20//!
21//! ### Pattern 1: Shared FlowRunner (RECOMMENDED)
22//! Create `FlowRunner` once at startup, share across all requests:
23//! ```rust,no_run
24//! use graph_flow::FlowRunner;
25//! use std::sync::Arc;
26//!
27//! // At startup
28//! struct AppState {
29//! flow_runner: FlowRunner,
30//! }
31//!
32//! // In request handler (async context)
33//! # async fn example(state: AppState, session_id: String) -> Result<(), Box<dyn std::error::Error>> {
34//! let result = state.flow_runner.run(&session_id).await?;
35//! # Ok(())
36//! # }
37//! ```
38//! **Pros**: Most efficient, zero allocation per request
39//! **Cons**: Requires the same graph for all requests
40//!
41//! ### Pattern 2: Per-Request FlowRunner
42//! Create `FlowRunner` fresh for each request:
43//! ```rust,no_run
44//! use graph_flow::{FlowRunner, Graph, InMemorySessionStorage};
45//! use std::sync::Arc;
46//!
47//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
48//! # let graph = Arc::new(Graph::new("my-graph"));
49//! # let storage: Arc<dyn graph_flow::SessionStorage> = Arc::new(InMemorySessionStorage::new());
50//! # let session_id = "test-session";
51//! // In request handler
52//! let runner = FlowRunner::new(graph.clone(), storage.clone());
53//! let result = runner.run(&session_id).await?;
54//! # Ok(())
55//! # }
56//! ```
57//! **Pros**: Flexible, can use different graphs per request
58//! **Cons**: Tiny allocation cost per request (still very cheap)
59//!
60//! ### Pattern 3: Manual (Original)
61//! Use `Graph::execute_session` directly:
62//! ```rust,no_run
63//! use graph_flow::{Graph, SessionStorage, InMemorySessionStorage};
64//! use std::sync::Arc;
65//!
66//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
67//! # let graph = Arc::new(Graph::new("my-graph"));
68//! # let storage: Arc<dyn SessionStorage> = Arc::new(InMemorySessionStorage::new());
69//! # let session_id = "test-session";
70//! let mut session = storage.get(&session_id).await?.unwrap();
71//! let result = graph.execute_session(&mut session).await?;
72//! storage.save(session).await?;
73//! # Ok(())
74//! # }
75//! ```
76//! **Pros**: Maximum control
77//! **Cons**: More boilerplate, easy to forget session.save()
78//!
79//! ## Performance Characteristics
80//! - **FlowRunner creation cost**: ~2 pointer copies (negligible)
81//! - **Memory overhead**: 16 bytes (2 × `Arc<T>`)
82//! - **Runtime cost**: Identical to manual approach
83//!
84//! For high-throughput services, Pattern 1 is recommended. For services with different
85//! graphs per request or complex routing, Pattern 2 is perfectly fine.
86//!
87//! # Examples
88//!
89//! ## Basic Usage
90//!
91//! ```rust,no_run
92//! use graph_flow::{FlowRunner, Graph, InMemorySessionStorage};
93//! use std::sync::Arc;
94//!
95//! # #[tokio::main]
96//! # async fn main() -> graph_flow::Result<()> {
97//! let graph = Arc::new(Graph::new("my_workflow"));
98//! let storage = Arc::new(InMemorySessionStorage::new());
99//! let runner = FlowRunner::new(graph, storage);
100//!
101//! // Execute workflow step (note: this will fail if session doesn't exist)
102//! let result = runner.run("session_id").await?;
103//! println!("Response: {:?}", result.response);
104//! # Ok(())
105//! # }
106//! ```
107//!
108//! ## Shared Runner Pattern (Recommended for Web Services)
109//!
110//! ```rust
111//! use graph_flow::FlowRunner;
112//! use std::sync::Arc;
113//!
114//! // Application state
115//! struct AppState {
116//! flow_runner: Arc<FlowRunner>,
117//! }
118//!
119//! impl AppState {
120//! fn new(runner: FlowRunner) -> Self {
121//! Self {
122//! flow_runner: Arc::new(runner),
123//! }
124//! }
125//! }
126//!
127//! // Request handler
128//! async fn handle_request(
129//! state: Arc<AppState>,
130//! session_id: String,
131//! ) -> Result<String, Box<dyn std::error::Error>> {
132//! let result = state.flow_runner.run(&session_id).await?;
133//! Ok(result.response.unwrap_or_default())
134//! }
135//! ```
136
137use std::sync::Arc;
138
139use crate::{
140 error::{GraphError, Result},
141 graph::{ExecutionResult, Graph},
142 storage::SessionStorage,
143};
144
145/// High-level helper that orchestrates the common _load → execute → save_ pattern.
146///
147/// `FlowRunner` provides a convenient wrapper around the lower-level graph execution
148/// API. It automatically handles session loading, execution, and persistence.
149///
150/// # When to Use FlowRunner
151///
152/// - **Web services**: Execute one step per HTTP request
153/// - **Interactive applications**: Step-by-step workflow progression
154/// - **Simple demos**: Minimal boilerplate for common use cases
155///
156/// # Performance
157///
158/// `FlowRunner` is lightweight and efficient:
159/// - Creation cost: ~2 pointer copies (negligible)
160/// - Memory overhead: 16 bytes (2 × `Arc<T>`)
161/// - Runtime cost: Identical to manual approach
162///
163/// # Examples
164///
165/// ## Basic Usage
166///
167/// ```rust,no_run
168/// use graph_flow::{FlowRunner, Graph, InMemorySessionStorage, Session, SessionStorage};
169/// use std::sync::Arc;
170///
171/// # #[tokio::main]
172/// # async fn main() -> graph_flow::Result<()> {
173/// let graph = Arc::new(Graph::new("my_workflow"));
174/// let storage = Arc::new(InMemorySessionStorage::new());
175/// let runner = FlowRunner::new(graph, storage.clone());
176///
177/// // Create a session first
178/// let session = Session::new_from_task("session_id".to_string(), "start_task");
179/// storage.save(session).await?;
180///
181/// // Execute workflow step
182/// let result = runner.run("session_id").await?;
183/// println!("Response: {:?}", result.response);
184/// # Ok(())
185/// # }
186/// ```
187///
188/// ## Shared Runner Pattern (Recommended for Web Services)
189///
190/// ```rust
191/// use graph_flow::FlowRunner;
192/// use std::sync::Arc;
193///
194/// // Application state
195/// struct AppState {
196/// flow_runner: Arc<FlowRunner>,
197/// }
198///
199/// impl AppState {
200/// fn new(runner: FlowRunner) -> Self {
201/// Self {
202/// flow_runner: Arc::new(runner),
203/// }
204/// }
205/// }
206///
207/// // Request handler
208/// async fn handle_request(
209/// state: Arc<AppState>,
210/// session_id: String,
211/// ) -> Result<String, Box<dyn std::error::Error>> {
212/// let result = state.flow_runner.run(&session_id).await?;
213/// Ok(result.response.unwrap_or_default())
214/// }
215/// ```
216#[derive(Clone)]
217pub struct FlowRunner {
218 graph: Arc<Graph>,
219 storage: Arc<dyn SessionStorage>,
220}
221
222impl FlowRunner {
223 /// Create a new `FlowRunner` from an `Arc<Graph>` and any `SessionStorage` implementation.
224 ///
225 /// # Parameters
226 ///
227 /// * `graph` - The workflow graph to execute
228 /// * `storage` - Storage backend for session persistence
229 ///
230 /// # Examples
231 ///
232 /// ```rust
233 /// use graph_flow::{FlowRunner, Graph, InMemorySessionStorage};
234 /// use std::sync::Arc;
235 ///
236 /// let graph = Arc::new(Graph::new("my_workflow"));
237 /// let storage = Arc::new(InMemorySessionStorage::new());
238 /// let runner = FlowRunner::new(graph, storage);
239 /// ```
240 ///
241 /// ## With PostgreSQL Storage
242 ///
243 /// Enable the `postgres` Cargo feature to use this backend.
244 ///
245 /// ```rust,no_run
246 /// # #[cfg(feature = "postgres")]
247 /// # mod postgres_example {
248 /// use graph_flow::{FlowRunner, Graph, PostgresSessionStorage};
249 /// use std::sync::Arc;
250 ///
251 /// # #[tokio::main]
252 /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
253 /// let graph = Arc::new(Graph::new("my_workflow"));
254 /// let storage = Arc::new(
255 /// PostgresSessionStorage::connect("postgresql://localhost/mydb").await?
256 /// );
257 /// let runner = FlowRunner::new(graph, storage);
258 /// # Ok(())
259 /// # }
260 /// # }
261 /// ```
262 pub fn new(graph: Arc<Graph>, storage: Arc<dyn SessionStorage>) -> Self {
263 Self { graph, storage }
264 }
265
266 /// Execute **exactly one** task for the given `session_id` and persist the updated session.
267 ///
268 /// This method:
269 /// 1. Loads the session from storage
270 /// 2. Executes the current task
271 /// 3. Saves the updated session back to storage
272 /// 4. Returns the execution result
273 ///
274 /// # Parameters
275 ///
276 /// * `session_id` - Unique identifier for the session to execute
277 ///
278 /// # Returns
279 ///
280 /// Returns the same [`ExecutionResult`] that `Graph::execute_session` does, so callers can
281 /// inspect the assistant's response and the status (`WaitingForInput`, `Completed`, etc.).
282 ///
283 /// # Errors
284 ///
285 /// Returns an error if:
286 /// - The session doesn't exist
287 /// - Task execution fails
288 /// - Storage operations fail
289 ///
290 /// # Concurrency
291 ///
292 /// Sessions are protected by optimistic locking: if another `run` call (or
293 /// any other writer) saved the same session between this call's load and
294 /// save, the save fails with [`crate::GraphError::SessionConflict`]
295 /// instead of silently losing the other writer's update. On conflict,
296 /// retry by calling `run` again (it reloads the latest session state).
297 /// Note that the *task's* side effects from the conflicting attempt are
298 /// not rolled back, so tasks should be idempotent if concurrent runs are
299 /// possible.
300 ///
301 /// # Examples
302 ///
303 /// ## Basic Execution
304 ///
305 /// ```rust,no_run
306 /// # use graph_flow::{FlowRunner, Graph, InMemorySessionStorage, Session, SessionStorage};
307 /// # use std::sync::Arc;
308 /// # #[tokio::main]
309 /// # async fn main() -> graph_flow::Result<()> {
310 /// # let graph = Arc::new(Graph::new("test"));
311 /// # let storage = Arc::new(InMemorySessionStorage::new());
312 /// # let runner = FlowRunner::new(graph, storage.clone());
313 /// # let session = Session::new_from_task("test_session".to_string(), "start_task");
314 /// # storage.save(session).await?;
315 /// let result = runner.run("test_session").await?;
316 ///
317 /// match result.status {
318 /// graph_flow::ExecutionStatus::Completed => {
319 /// println!("Workflow completed: {:?}", result.response);
320 /// }
321 /// graph_flow::ExecutionStatus::WaitingForInput => {
322 /// println!("Waiting for user input: {:?}", result.response);
323 /// }
324 /// graph_flow::ExecutionStatus::Paused { next_task_id, reason } => {
325 /// println!("Paused, next task: {}, reason: {}", next_task_id, reason);
326 /// }
327 /// }
328 /// # Ok(())
329 /// # }
330 /// ```
331 ///
332 /// ## Interactive Loop
333 ///
334 /// ```rust,no_run
335 /// # use graph_flow::{FlowRunner, ExecutionStatus, Session, SessionStorage};
336 /// # use std::sync::Arc;
337 /// # #[tokio::main]
338 /// # async fn main() -> graph_flow::Result<()> {
339 /// # let storage = Arc::new(graph_flow::InMemorySessionStorage::new());
340 /// # let runner = FlowRunner::new(Arc::new(graph_flow::Graph::new("test")), storage.clone());
341 /// # let session = Session::new_from_task("session_id".to_string(), "start_task");
342 /// # storage.save(session).await?;
343 /// loop {
344 /// let result = runner.run("session_id").await?;
345 ///
346 /// match result.status {
347 /// ExecutionStatus::Completed => break,
348 /// ExecutionStatus::WaitingForInput => {
349 /// // Get user input and update context
350 /// // Then continue loop
351 /// break; // For demo
352 /// }
353 /// ExecutionStatus::Paused { .. } => {
354 /// // Continue to next step
355 /// continue;
356 /// }
357 /// }
358 /// }
359 /// # Ok(())
360 /// # }
361 /// ```
362 ///
363 /// ## Error Handling
364 ///
365 /// ```rust,no_run
366 /// # use graph_flow::{FlowRunner, GraphError};
367 /// # use std::sync::Arc;
368 /// # #[tokio::main]
369 /// # async fn main() {
370 /// # let runner = FlowRunner::new(Arc::new(graph_flow::Graph::new("test")), Arc::new(graph_flow::InMemorySessionStorage::new()));
371 /// match runner.run("nonexistent_session").await {
372 /// Ok(result) => {
373 /// println!("Success: {:?}", result.response);
374 /// }
375 /// Err(GraphError::SessionNotFound(session_id)) => {
376 /// eprintln!("Session not found: {}", session_id);
377 /// }
378 /// Err(GraphError::TaskExecutionFailed(msg)) => {
379 /// eprintln!("Task failed: {}", msg);
380 /// }
381 /// Err(e) => {
382 /// eprintln!("Other error: {}", e);
383 /// }
384 /// }
385 /// # }
386 /// ```
387 pub async fn run(&self, session_id: &str) -> Result<ExecutionResult> {
388 // 1. Load session
389 let mut session = self
390 .storage
391 .get(session_id)
392 .await?
393 .ok_or_else(|| GraphError::SessionNotFound(session_id.to_string()))?;
394
395 // 2. Execute current task (exactly one step)
396 let result = self.graph.execute_session(&mut session).await?;
397
398 // 3. Persist new state so the next call starts where we left off
399 self.storage.save(session).await?;
400
401 Ok(result)
402 }
403}