Skip to main content

ironflow_api/routes/
get_run_logs.rs

1//! `GET /api/v1/runs/:id/logs` -- Retrieve persisted log lines for a run.
2
3use std::collections::HashMap;
4
5use axum::Json;
6use axum::extract::{Path, Query, State};
7use axum::response::IntoResponse;
8use serde::{Deserialize, Serialize};
9use serde_json::Value;
10use uuid::Uuid;
11
12use ironflow_auth::extractor::Authenticated;
13#[cfg(feature = "openapi")]
14use ironflow_store::entities::LogEntry;
15use ironflow_store::entities::{LogFilter, LogStream};
16use ironflow_types::{ApiMeta, ApiResponse};
17
18use crate::error::ApiError;
19use crate::state::AppState;
20
21const MAX_LIMIT: u32 = 1000;
22const DEFAULT_LIMIT: u32 = 100;
23
24/// Query parameters for listing run logs.
25#[derive(Debug, Deserialize)]
26#[cfg_attr(feature = "openapi", derive(utoipa::IntoParams, utoipa::ToSchema))]
27pub struct GetRunLogsQuery {
28    /// Filter by step ID.
29    pub step_id: Option<Uuid>,
30    /// Filter by output stream (`stdout`, `stderr`, `system`).
31    pub stream: Option<LogStream>,
32    /// Cursor for pagination (last entry ID from previous page).
33    pub cursor: Option<Uuid>,
34    /// Number of entries to return (default: 100, max: 1000).
35    pub limit: Option<u32>,
36}
37
38/// Cursor-based pagination metadata for log entries.
39#[derive(Debug, Serialize)]
40#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
41pub struct LogCursorMeta {
42    /// Cursor to pass for the next page. `None` when there are no more entries.
43    pub next_cursor: Option<Uuid>,
44    /// Whether more entries exist after this page.
45    pub has_more: bool,
46}
47
48/// Retrieve persisted log lines for a run with cursor-based pagination.
49///
50/// Returns log entries ordered by time (UUID v7 ascending). Use the
51/// `cursor` query parameter with the last entry's `id` to fetch the
52/// next page.
53#[cfg_attr(
54    feature = "openapi",
55    utoipa::path(
56        get,
57        path = "/api/v1/runs/{id}/logs",
58        tags = ["runs"],
59        params(
60            ("id" = Uuid, Path, description = "Run ID"),
61            GetRunLogsQuery,
62        ),
63        responses(
64            (status = 200, description = "Log entries with cursor-based pagination", body = Vec<LogEntry>),
65            (status = 401, description = "Unauthorized"),
66            (status = 404, description = "Run not found")
67        ),
68        security(("Bearer" = []))
69    )
70)]
71pub async fn get_run_logs(
72    _auth: Authenticated,
73    State(state): State<AppState>,
74    Path(run_id): Path<Uuid>,
75    Query(params): Query<GetRunLogsQuery>,
76) -> Result<impl IntoResponse, ApiError> {
77    state.get_run_or_404(run_id).await?;
78
79    let limit = match params.limit {
80        Some(0) | None => DEFAULT_LIMIT,
81        Some(l) => l.min(MAX_LIMIT),
82    };
83
84    let filter = LogFilter {
85        step_id: params.step_id,
86        stream: params.stream,
87    };
88
89    let entries = state
90        .store
91        .get_logs(run_id, filter, params.cursor, limit + 1)
92        .await?;
93
94    let has_more = entries.len() > limit as usize;
95    let entries: Vec<_> = entries.into_iter().take(limit as usize).collect();
96    let next_cursor = if has_more {
97        entries.last().map(|e| e.id)
98    } else {
99        None
100    };
101
102    let cursor_meta = LogCursorMeta {
103        next_cursor,
104        has_more,
105    };
106    let extra = match serde_json::to_value(cursor_meta) {
107        Ok(Value::Object(map)) => map.into_iter().collect(),
108        _ => HashMap::new(),
109    };
110
111    Ok(Json(ApiResponse {
112        data: entries,
113        meta: Some(ApiMeta {
114            page: None,
115            per_page: None,
116            total: None,
117            extra,
118        }),
119    }))
120}
121
122#[cfg(test)]
123mod tests {
124    use std::collections::HashMap;
125    use std::sync::Arc;
126
127    use axum::Router;
128    use axum::body::Body;
129    use axum::http::{Request, StatusCode};
130    use axum::routing::get;
131    use http_body_util::BodyExt;
132    use serde_json::{Value as JsonValue, from_slice, json};
133    use tokio::sync::broadcast;
134    use tower::ServiceExt;
135    use uuid::Uuid;
136
137    use ironflow_auth::jwt::JwtConfig;
138    use ironflow_core::providers::claude::ClaudeCodeProvider;
139    use ironflow_engine::engine::Engine;
140    use ironflow_engine::notify::Event;
141    use ironflow_store::entities::{LogStream, NewLogEntries, NewRun, TriggerKind};
142    use ironflow_store::memory::InMemoryStore;
143
144    use super::*;
145    use crate::routes::test_helpers::create_user_auth_header;
146
147    fn test_state() -> AppState {
148        let store = Arc::new(InMemoryStore::new());
149        let provider = Arc::new(ClaudeCodeProvider::new());
150        let engine = Arc::new(Engine::new(store.clone(), provider));
151        let jwt_config = Arc::new(JwtConfig {
152            secret: "test-secret".to_string(),
153            access_token_ttl_secs: 900,
154            refresh_token_ttl_secs: 604800,
155            cookie_domain: None,
156            cookie_secure: false,
157        });
158        let (event_sender, _) = broadcast::channel::<Event>(1);
159        AppState::new(
160            store,
161            engine,
162            jwt_config,
163            "test-worker-token".to_string(),
164            event_sender,
165        )
166    }
167
168    async fn create_run(state: &AppState) -> Uuid {
169        state
170            .store
171            .create_run(NewRun {
172                created_by: None,
173                workflow_name: "test".to_string(),
174                trigger: TriggerKind::Manual,
175                payload: json!({}),
176                max_retries: 0,
177                handler_version: None,
178                labels: HashMap::new(),
179                scheduled_at: None,
180                idempotency_key: None,
181                concurrency_key: None,
182                max_cost_usd: None,
183            })
184            .await
185            .unwrap()
186            .into_run()
187            .id
188    }
189
190    async fn push_logs(state: &AppState, run_id: Uuid, step_id: Uuid, stream: LogStream, n: usize) {
191        state
192            .store
193            .append_logs(NewLogEntries {
194                ids: (0..n).map(|_| Uuid::now_v7()).collect(),
195                run_id,
196                step_id,
197                step_name: "build".to_string(),
198                stream,
199                lines: (0..n).map(|i| format!("line {i}")).collect(),
200            })
201            .await
202            .unwrap();
203    }
204
205    #[tokio::test]
206    async fn returns_persisted_logs() {
207        let state = test_state();
208        let auth_header = create_user_auth_header(&state, "testuser", false).await;
209        let run_id = create_run(&state).await;
210        let step_id = Uuid::now_v7();
211
212        push_logs(&state, run_id, step_id, LogStream::Stdout, 3).await;
213
214        let app = Router::new()
215            .route("/runs/{id}/logs", get(get_run_logs))
216            .with_state(state);
217
218        let req = Request::builder()
219            .uri(format!("/runs/{run_id}/logs"))
220            .header("authorization", auth_header)
221            .body(Body::empty())
222            .unwrap();
223
224        let resp = app.oneshot(req).await.unwrap();
225        assert_eq!(resp.status(), StatusCode::OK);
226
227        let body = resp.into_body().collect().await.unwrap().to_bytes();
228        let json_val: JsonValue = from_slice(&body).unwrap();
229        assert_eq!(json_val["data"].as_array().unwrap().len(), 3);
230        assert_eq!(json_val["data"][0]["line"], "line 0");
231        assert_eq!(json_val["data"][0]["stream"], "stdout");
232        assert_eq!(json_val["meta"]["has_more"], false);
233        assert!(json_val["meta"]["next_cursor"].is_null());
234    }
235
236    #[tokio::test]
237    async fn filters_by_step_id() {
238        let state = test_state();
239        let auth_header = create_user_auth_header(&state, "testuser", false).await;
240        let run_id = create_run(&state).await;
241        let step_a = Uuid::now_v7();
242        let step_b = Uuid::now_v7();
243
244        push_logs(&state, run_id, step_a, LogStream::Stdout, 2).await;
245        push_logs(&state, run_id, step_b, LogStream::Stdout, 3).await;
246
247        let app = Router::new()
248            .route("/runs/{id}/logs", get(get_run_logs))
249            .with_state(state);
250
251        let req = Request::builder()
252            .uri(format!("/runs/{run_id}/logs?step_id={step_a}"))
253            .header("authorization", auth_header)
254            .body(Body::empty())
255            .unwrap();
256
257        let resp = app.oneshot(req).await.unwrap();
258        assert_eq!(resp.status(), StatusCode::OK);
259
260        let body = resp.into_body().collect().await.unwrap().to_bytes();
261        let json_val: JsonValue = from_slice(&body).unwrap();
262        assert_eq!(json_val["data"].as_array().unwrap().len(), 2);
263    }
264
265    #[tokio::test]
266    async fn filters_by_stream() {
267        let state = test_state();
268        let auth_header = create_user_auth_header(&state, "testuser", false).await;
269        let run_id = create_run(&state).await;
270        let step_id = Uuid::now_v7();
271
272        push_logs(&state, run_id, step_id, LogStream::Stdout, 2).await;
273        push_logs(&state, run_id, step_id, LogStream::Stderr, 1).await;
274
275        let app = Router::new()
276            .route("/runs/{id}/logs", get(get_run_logs))
277            .with_state(state);
278
279        let req = Request::builder()
280            .uri(format!("/runs/{run_id}/logs?stream=stderr"))
281            .header("authorization", auth_header)
282            .body(Body::empty())
283            .unwrap();
284
285        let resp = app.oneshot(req).await.unwrap();
286        let body = resp.into_body().collect().await.unwrap().to_bytes();
287        let json_val: JsonValue = from_slice(&body).unwrap();
288        assert_eq!(json_val["data"].as_array().unwrap().len(), 1);
289        assert_eq!(json_val["data"][0]["stream"], "stderr");
290    }
291
292    #[tokio::test]
293    async fn cursor_based_pagination() {
294        let state = test_state();
295        let auth_header = create_user_auth_header(&state, "testuser", false).await;
296        let run_id = create_run(&state).await;
297        let step_id = Uuid::now_v7();
298
299        push_logs(&state, run_id, step_id, LogStream::Stdout, 5).await;
300
301        let app = Router::new()
302            .route("/runs/{id}/logs", get(get_run_logs))
303            .with_state(state);
304
305        let req = Request::builder()
306            .uri(format!("/runs/{run_id}/logs?limit=2"))
307            .header("authorization", &auth_header)
308            .body(Body::empty())
309            .unwrap();
310
311        let resp = app.clone().oneshot(req).await.unwrap();
312        let body = resp.into_body().collect().await.unwrap().to_bytes();
313        let page1: JsonValue = from_slice(&body).unwrap();
314        assert_eq!(page1["data"].as_array().unwrap().len(), 2);
315        assert_eq!(page1["meta"]["has_more"], true);
316
317        let cursor = page1["meta"]["next_cursor"].as_str().unwrap();
318
319        let req = Request::builder()
320            .uri(format!("/runs/{run_id}/logs?limit=2&cursor={cursor}"))
321            .header("authorization", &auth_header)
322            .body(Body::empty())
323            .unwrap();
324
325        let resp = app.clone().oneshot(req).await.unwrap();
326        let body = resp.into_body().collect().await.unwrap().to_bytes();
327        let page2: JsonValue = from_slice(&body).unwrap();
328        assert_eq!(page2["data"].as_array().unwrap().len(), 2);
329        assert_eq!(page2["data"][0]["line"], "line 2");
330        assert_eq!(page2["meta"]["has_more"], true);
331
332        let cursor = page2["meta"]["next_cursor"].as_str().unwrap();
333
334        let req = Request::builder()
335            .uri(format!("/runs/{run_id}/logs?limit=2&cursor={cursor}"))
336            .header("authorization", &auth_header)
337            .body(Body::empty())
338            .unwrap();
339
340        let resp = app.oneshot(req).await.unwrap();
341        let body = resp.into_body().collect().await.unwrap().to_bytes();
342        let page3: JsonValue = from_slice(&body).unwrap();
343        assert_eq!(page3["data"].as_array().unwrap().len(), 1);
344        assert_eq!(page3["meta"]["has_more"], false);
345        assert!(page3["meta"]["next_cursor"].is_null());
346    }
347
348    #[tokio::test]
349    async fn run_not_found_returns_404() {
350        let state = test_state();
351        let auth_header = create_user_auth_header(&state, "testuser", false).await;
352        let app = Router::new()
353            .route("/runs/{id}/logs", get(get_run_logs))
354            .with_state(state);
355
356        let req = Request::builder()
357            .uri(format!("/runs/{}/logs", Uuid::now_v7()))
358            .header("authorization", auth_header)
359            .body(Body::empty())
360            .unwrap();
361
362        let resp = app.oneshot(req).await.unwrap();
363        assert_eq!(resp.status(), StatusCode::NOT_FOUND);
364    }
365
366    #[tokio::test]
367    async fn unauthenticated_returns_401() {
368        let state = test_state();
369        let run_id = create_run(&state).await;
370        let app = Router::new()
371            .route("/runs/{id}/logs", get(get_run_logs))
372            .with_state(state);
373
374        let req = Request::builder()
375            .uri(format!("/runs/{run_id}/logs"))
376            .body(Body::empty())
377            .unwrap();
378
379        let resp = app.oneshot(req).await.unwrap();
380        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
381    }
382
383    #[tokio::test]
384    async fn limit_capped_at_1000() {
385        let state = test_state();
386        let auth_header = create_user_auth_header(&state, "testuser", false).await;
387        let run_id = create_run(&state).await;
388        let step_id = Uuid::now_v7();
389
390        push_logs(&state, run_id, step_id, LogStream::Stdout, 2).await;
391
392        let app = Router::new()
393            .route("/runs/{id}/logs", get(get_run_logs))
394            .with_state(state);
395
396        let req = Request::builder()
397            .uri(format!("/runs/{run_id}/logs?limit=5000"))
398            .header("authorization", auth_header)
399            .body(Body::empty())
400            .unwrap();
401
402        let resp = app.oneshot(req).await.unwrap();
403        assert_eq!(resp.status(), StatusCode::OK);
404
405        let body = resp.into_body().collect().await.unwrap().to_bytes();
406        let json_val: JsonValue = from_slice(&body).unwrap();
407        assert_eq!(json_val["data"].as_array().unwrap().len(), 2);
408    }
409
410    #[tokio::test]
411    async fn empty_logs_returns_empty_array() {
412        let state = test_state();
413        let auth_header = create_user_auth_header(&state, "testuser", false).await;
414        let run_id = create_run(&state).await;
415
416        let app = Router::new()
417            .route("/runs/{id}/logs", get(get_run_logs))
418            .with_state(state);
419
420        let req = Request::builder()
421            .uri(format!("/runs/{run_id}/logs"))
422            .header("authorization", auth_header)
423            .body(Body::empty())
424            .unwrap();
425
426        let resp = app.oneshot(req).await.unwrap();
427        assert_eq!(resp.status(), StatusCode::OK);
428
429        let body = resp.into_body().collect().await.unwrap().to_bytes();
430        let json_val: JsonValue = from_slice(&body).unwrap();
431        assert_eq!(json_val["data"].as_array().unwrap().len(), 0);
432        assert_eq!(json_val["meta"]["has_more"], false);
433    }
434}