ironflow-api 2.31.10

REST API for ironflow run management and observability
Documentation
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
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
//! SSE endpoint for per-run workflow event streaming.

use std::convert::Infallible;
use std::pin::Pin;
use std::time::Duration;

use axum::extract::{Path, Query, State};
use axum::response::sse::{Event as SseEvent, KeepAlive, Sse};
use futures_util::stream::{Stream, StreamExt};
use serde::Deserialize;
use serde::de::{self, Deserializer};
use tokio_stream::wrappers::BroadcastStream;
use uuid::Uuid;

use crate::error::ApiError;
use crate::state::AppState;
use ironflow_auth::extractor::Authenticated;
use ironflow_engine::notify::WorkflowEvent;

/// Deserialize a comma-separated string into `Option<Vec<String>>`.
fn deserialize_comma_strings<'de, D>(deserializer: D) -> Result<Option<Vec<String>>, D::Error>
where
    D: Deserializer<'de>,
{
    let opt: Option<String> = Option::deserialize(deserializer)?;
    match opt {
        None => Ok(None),
        Some(raw) => {
            let all_types = [
                WorkflowEvent::STEP_STARTED,
                WorkflowEvent::STEP_COMPLETED,
                WorkflowEvent::STEP_FAILED,
                WorkflowEvent::APPROVAL_REQUIRED,
                WorkflowEvent::AGENT_STEP_TOKENS_USED,
            ];

            let kinds: Vec<String> = raw
                .split(',')
                .map(|s| s.trim())
                .filter(|s| !s.is_empty())
                .map(|s| {
                    if all_types.contains(&s) {
                        Ok(s.to_string())
                    } else {
                        Err(de::Error::custom(format!(
                            "unknown workflow event type: {s}"
                        )))
                    }
                })
                .collect::<Result<Vec<_>, _>>()?;

            Ok(Some(kinds))
        }
    }
}

/// Query parameters for the per-run SSE events endpoint.
///
/// # Examples
///
/// ```
/// use ironflow_api::routes::run_events::RunEventsQuery;
///
/// let query = RunEventsQuery { types: None };
/// ```
#[derive(Debug, Deserialize)]
pub struct RunEventsQuery {
    /// Comma-separated list of workflow event types to include
    /// (e.g. `?types=step_started,step_completed`).
    #[serde(default, deserialize_with = "deserialize_comma_strings")]
    pub types: Option<Vec<String>>,
}

/// `GET /api/v1/runs/{id}/events` -- per-run Server-Sent Events stream.
///
/// Streams [`WorkflowEvent`]s for a specific workflow run in real time.
/// Supports optional filtering via `?types=step_started,step_completed`.
///
/// Each SSE message has:
/// - `event:` set to the event type (e.g. `step_started`)
/// - `data:` JSON-serialized event payload
///
/// A keep-alive comment is sent every 30 seconds.
///
/// # Errors
///
/// Returns 401 if the request is not authenticated.
/// Returns 404 if the run does not exist.
#[cfg_attr(
    feature = "openapi",
    utoipa::path(
        get,
        path = "/api/v1/runs/{id}/events",
        tags = ["runs"],
        params(
            ("id" = Uuid, Path, description = "Run ID"),
            ("types" = Option<String>, Query, description = "Comma-separated workflow event types to filter (e.g. step_started,step_completed)")
        ),
        responses(
            (status = 200, description = "SSE stream of workflow events"),
            (status = 401, description = "Unauthorized"),
            (status = 404, description = "Run not found")
        ),
        security(("Bearer" = []))
    )
)]
pub async fn run_events(
    _auth: Authenticated,
    State(state): State<AppState>,
    Path(id): Path<Uuid>,
    Query(query): Query<RunEventsQuery>,
) -> Result<Sse<impl Stream<Item = Result<SseEvent, Infallible>>>, ApiError> {
    state.get_run_or_404(id).await?;

    let type_filter = query.types;

    let stream: Pin<Box<dyn Stream<Item = Result<SseEvent, Infallible>> + Send>> = match state
        .event_bus
    {
        Some(ref bus) => {
            let receiver = bus.subscribe(id);

            Box::pin(BroadcastStream::new(receiver).filter_map(
                move |result: Result<WorkflowEvent, _>| {
                    let type_filter = type_filter.clone();
                    async move {
                        let event = result.ok()?;

                        if let Some(ref kinds) = type_filter {
                            let event_type = event.event_type();
                            if !kinds.iter().any(|k| k == event_type) {
                                return None;
                            }
                        }

                        let data = serde_json::to_string(&event).ok()?;
                        let sse_event = SseEvent::default().event(event.event_type()).data(data);

                        Some(Ok::<_, Infallible>(sse_event))
                    }
                },
            ))
        }
        None => Box::pin(futures_util::stream::empty()),
    };

    Ok(Sse::new(stream).keep_alive(KeepAlive::new().interval(Duration::from_secs(30))))
}

#[cfg(test)]
mod tests {
    use std::collections::HashMap;
    use std::sync::Arc;
    use std::time::Duration;

    use axum::Router;
    use axum::routing::get;
    use chrono::Utc;
    use ironflow_auth::jwt::AccessToken;
    use ironflow_core::providers::claude::ClaudeCodeProvider;
    use ironflow_engine::engine::Engine;
    use ironflow_engine::notify::{Event, WorkflowEvent, WorkflowEventBus};
    use ironflow_store::memory::InMemoryStore;
    use ironflow_store::models::{NewRun, TriggerKind};
    use serde_json::json;
    use tokio::io::AsyncBufReadExt;
    use tokio::io::BufReader;
    use tokio::net::TcpListener;
    use tokio::sync::broadcast;
    use tokio::time::{sleep, timeout};
    use uuid::Uuid;

    use super::run_events;
    use crate::state::AppState;

    fn test_state_with_bus() -> (AppState, WorkflowEventBus) {
        let store = Arc::new(InMemoryStore::new());
        let provider = Arc::new(ClaudeCodeProvider::new());
        let engine = Arc::new(Engine::new(store.clone(), provider));
        let jwt_config = Arc::new(ironflow_auth::jwt::JwtConfig {
            secret: "test-secret".to_string(),
            access_token_ttl_secs: 900,
            refresh_token_ttl_secs: 604800,
            cookie_domain: None,
            cookie_secure: false,
        });
        let (event_sender, _) = broadcast::channel::<Event>(16);
        let bus = WorkflowEventBus::new();
        let state = AppState::new(
            store,
            engine,
            jwt_config,
            "test-worker-token".to_string(),
            event_sender,
        )
        .with_event_bus(bus.clone());
        (state, bus)
    }

    fn make_auth_token(state: &AppState) -> String {
        let user_id = Uuid::now_v7();
        let token = AccessToken::for_user(user_id, "testuser", false, &state.jwt_config).unwrap();
        format!("Bearer {}", token.0)
    }

    async fn create_run(state: &AppState) -> Uuid {
        state
            .store
            .create_run(NewRun {
                created_by: None,
                workflow_name: "test".to_string(),
                trigger: TriggerKind::Manual,
                payload: json!({}),
                max_retries: 0,
                handler_version: None,
                labels: HashMap::new(),
                scheduled_at: None,
                idempotency_key: None,
                max_cost_usd: None,
            })
            .await
            .unwrap()
            .into_run()
            .id
    }

    async fn start_sse_server(state: AppState) -> (String, String) {
        let auth = make_auth_token(&state);
        let app = Router::new()
            .route("/{id}/events", get(run_events))
            .with_state(state);

        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap().to_string();
        tokio::spawn(async move {
            axum::serve(listener, app).await.unwrap();
        });
        (addr, auth)
    }

    async fn connect_sse(addr: &str, path: &str, auth: &str) -> BufReader<tokio::net::TcpStream> {
        let stream = tokio::net::TcpStream::connect(addr).await.unwrap();
        let (reader, mut writer) = stream.into_split();

        use tokio::io::AsyncWriteExt;
        writer
            .write_all(
                format!(
                    "GET {path} HTTP/1.1\r\nHost: {addr}\r\nAccept: text/event-stream\r\nAuthorization: {auth}\r\n\r\n"
                )
                .as_bytes(),
            )
            .await
            .unwrap();

        BufReader::new(reader.reunite(writer).unwrap())
    }

    async fn read_until_contains(
        reader: &mut BufReader<tokio::net::TcpStream>,
        needle: &str,
        dur: Duration,
    ) -> String {
        let mut accumulated = String::new();
        let result = timeout(dur, async {
            loop {
                let mut line = String::new();
                let n = reader.read_line(&mut line).await.unwrap();
                if n == 0 {
                    break;
                }
                accumulated.push_str(&line);
                if accumulated.contains(needle) {
                    break;
                }
            }
        })
        .await;
        if result.is_err() {
            panic!("timeout waiting for '{needle}' in SSE stream. Data so far:\n{accumulated}");
        }
        accumulated
    }

    #[tokio::test]
    async fn sse_stream_receives_workflow_events() {
        let (state, bus) = test_state_with_bus();
        let run_id = create_run(&state).await;
        let (addr, auth) = start_sse_server(state).await;

        let mut reader = connect_sse(&addr, &format!("/{run_id}/events"), &auth).await;
        sleep(Duration::from_millis(50)).await;

        bus.publish(
            run_id,
            WorkflowEvent::StepStarted {
                step_name: "build".to_string(),
                step_index: 0,
                timestamp: Utc::now(),
            },
        );

        let text = read_until_contains(&mut reader, "build", Duration::from_secs(5)).await;

        assert!(text.contains("event: step_started"));
        assert!(text.contains("build"));
    }

    #[tokio::test]
    async fn returns_404_for_unknown_run() {
        let (state, _bus) = test_state_with_bus();
        let (addr, auth) = start_sse_server(state).await;

        let unknown = Uuid::nil();
        let mut reader = connect_sse(&addr, &format!("/{unknown}/events"), &auth).await;

        let text = read_until_contains(&mut reader, "404", Duration::from_secs(5)).await;
        assert!(text.contains("404"));
    }

    #[tokio::test]
    async fn rejects_unauthenticated() {
        let (state, _bus) = test_state_with_bus();
        let run_id = create_run(&state).await;
        let (addr, _auth) = start_sse_server(state).await;

        let stream = tokio::net::TcpStream::connect(&addr).await.unwrap();
        let (reader, mut writer) = stream.into_split();

        use tokio::io::AsyncWriteExt;
        writer
            .write_all(
                format!(
                    "GET /{run_id}/events HTTP/1.1\r\nHost: {addr}\r\nAccept: text/event-stream\r\n\r\n"
                )
                .as_bytes(),
            )
            .await
            .unwrap();

        let mut buf_reader = BufReader::new(reader.reunite(writer).unwrap());
        let text = read_until_contains(&mut buf_reader, "401", Duration::from_secs(5)).await;
        assert!(text.contains("401"));
    }

    #[tokio::test]
    async fn filters_by_event_type() {
        let (state, bus) = test_state_with_bus();
        let run_id = create_run(&state).await;
        let (addr, auth) = start_sse_server(state).await;

        let mut reader = connect_sse(
            &addr,
            &format!("/{run_id}/events?types=step_completed"),
            &auth,
        )
        .await;
        sleep(Duration::from_millis(50)).await;

        bus.publish(
            run_id,
            WorkflowEvent::StepStarted {
                step_name: "build".to_string(),
                step_index: 0,
                timestamp: Utc::now(),
            },
        );
        bus.publish(
            run_id,
            WorkflowEvent::StepCompleted {
                step_name: "build".to_string(),
                step_index: 0,
                duration_ms: 1234,
                output_summary: None,
            },
        );

        let text = read_until_contains(&mut reader, "step_completed", Duration::from_secs(5)).await;

        assert!(text.contains("step_completed"));
        assert!(!text.contains("event: step_started"));
    }

    #[tokio::test]
    async fn events_isolated_between_runs() {
        let (state, bus) = test_state_with_bus();
        let run_a = create_run(&state).await;
        let run_b = create_run(&state).await;
        let (addr, auth) = start_sse_server(state).await;

        let mut reader_a = connect_sse(&addr, &format!("/{run_a}/events"), &auth).await;
        sleep(Duration::from_millis(50)).await;

        bus.publish(
            run_b,
            WorkflowEvent::StepStarted {
                step_name: "only-for-b".to_string(),
                step_index: 0,
                timestamp: Utc::now(),
            },
        );
        bus.publish(
            run_a,
            WorkflowEvent::StepStarted {
                step_name: "only-for-a".to_string(),
                step_index: 0,
                timestamp: Utc::now(),
            },
        );

        let text = read_until_contains(&mut reader_a, "only-for-a", Duration::from_secs(5)).await;

        assert!(text.contains("only-for-a"));
        assert!(!text.contains("only-for-b"));
    }
}