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::{AccessToken, 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
146    fn test_state() -> AppState {
147        let store = Arc::new(InMemoryStore::new());
148        let provider = Arc::new(ClaudeCodeProvider::new());
149        let engine = Arc::new(Engine::new(store.clone(), provider));
150        let jwt_config = Arc::new(JwtConfig {
151            secret: "test-secret".to_string(),
152            access_token_ttl_secs: 900,
153            refresh_token_ttl_secs: 604800,
154            cookie_domain: None,
155            cookie_secure: false,
156        });
157        let (event_sender, _) = broadcast::channel::<Event>(1);
158        AppState::new(
159            store,
160            engine,
161            jwt_config,
162            "test-worker-token".to_string(),
163            event_sender,
164        )
165    }
166
167    fn make_auth_header(state: &AppState) -> String {
168        let user_id = Uuid::now_v7();
169        let token = AccessToken::for_user(user_id, "testuser", false, &state.jwt_config).unwrap();
170        format!("Bearer {}", token.0)
171    }
172
173    async fn create_run(state: &AppState) -> Uuid {
174        state
175            .store
176            .create_run(NewRun {
177                created_by: None,
178                workflow_name: "test".to_string(),
179                trigger: TriggerKind::Manual,
180                payload: json!({}),
181                max_retries: 0,
182                handler_version: None,
183                labels: HashMap::new(),
184                scheduled_at: None,
185                idempotency_key: None,
186                max_cost_usd: None,
187            })
188            .await
189            .unwrap()
190            .into_run()
191            .id
192    }
193
194    async fn push_logs(state: &AppState, run_id: Uuid, step_id: Uuid, stream: LogStream, n: usize) {
195        state
196            .store
197            .append_logs(NewLogEntries {
198                run_id,
199                step_id,
200                step_name: "build".to_string(),
201                stream,
202                lines: (0..n).map(|i| format!("line {i}")).collect(),
203            })
204            .await
205            .unwrap();
206    }
207
208    #[tokio::test]
209    async fn returns_persisted_logs() {
210        let state = test_state();
211        let auth_header = make_auth_header(&state);
212        let run_id = create_run(&state).await;
213        let step_id = Uuid::now_v7();
214
215        push_logs(&state, run_id, step_id, LogStream::Stdout, 3).await;
216
217        let app = Router::new()
218            .route("/runs/{id}/logs", get(get_run_logs))
219            .with_state(state);
220
221        let req = Request::builder()
222            .uri(format!("/runs/{run_id}/logs"))
223            .header("authorization", auth_header)
224            .body(Body::empty())
225            .unwrap();
226
227        let resp = app.oneshot(req).await.unwrap();
228        assert_eq!(resp.status(), StatusCode::OK);
229
230        let body = resp.into_body().collect().await.unwrap().to_bytes();
231        let json_val: JsonValue = from_slice(&body).unwrap();
232        assert_eq!(json_val["data"].as_array().unwrap().len(), 3);
233        assert_eq!(json_val["data"][0]["line"], "line 0");
234        assert_eq!(json_val["data"][0]["stream"], "stdout");
235        assert_eq!(json_val["meta"]["has_more"], false);
236        assert!(json_val["meta"]["next_cursor"].is_null());
237    }
238
239    #[tokio::test]
240    async fn filters_by_step_id() {
241        let state = test_state();
242        let auth_header = make_auth_header(&state);
243        let run_id = create_run(&state).await;
244        let step_a = Uuid::now_v7();
245        let step_b = Uuid::now_v7();
246
247        push_logs(&state, run_id, step_a, LogStream::Stdout, 2).await;
248        push_logs(&state, run_id, step_b, LogStream::Stdout, 3).await;
249
250        let app = Router::new()
251            .route("/runs/{id}/logs", get(get_run_logs))
252            .with_state(state);
253
254        let req = Request::builder()
255            .uri(format!("/runs/{run_id}/logs?step_id={step_a}"))
256            .header("authorization", auth_header)
257            .body(Body::empty())
258            .unwrap();
259
260        let resp = app.oneshot(req).await.unwrap();
261        assert_eq!(resp.status(), StatusCode::OK);
262
263        let body = resp.into_body().collect().await.unwrap().to_bytes();
264        let json_val: JsonValue = from_slice(&body).unwrap();
265        assert_eq!(json_val["data"].as_array().unwrap().len(), 2);
266    }
267
268    #[tokio::test]
269    async fn filters_by_stream() {
270        let state = test_state();
271        let auth_header = make_auth_header(&state);
272        let run_id = create_run(&state).await;
273        let step_id = Uuid::now_v7();
274
275        push_logs(&state, run_id, step_id, LogStream::Stdout, 2).await;
276        push_logs(&state, run_id, step_id, LogStream::Stderr, 1).await;
277
278        let app = Router::new()
279            .route("/runs/{id}/logs", get(get_run_logs))
280            .with_state(state);
281
282        let req = Request::builder()
283            .uri(format!("/runs/{run_id}/logs?stream=stderr"))
284            .header("authorization", auth_header)
285            .body(Body::empty())
286            .unwrap();
287
288        let resp = app.oneshot(req).await.unwrap();
289        let body = resp.into_body().collect().await.unwrap().to_bytes();
290        let json_val: JsonValue = from_slice(&body).unwrap();
291        assert_eq!(json_val["data"].as_array().unwrap().len(), 1);
292        assert_eq!(json_val["data"][0]["stream"], "stderr");
293    }
294
295    #[tokio::test]
296    async fn cursor_based_pagination() {
297        let state = test_state();
298        let auth_header = make_auth_header(&state);
299        let run_id = create_run(&state).await;
300        let step_id = Uuid::now_v7();
301
302        push_logs(&state, run_id, step_id, LogStream::Stdout, 5).await;
303
304        let app = Router::new()
305            .route("/runs/{id}/logs", get(get_run_logs))
306            .with_state(state);
307
308        let req = Request::builder()
309            .uri(format!("/runs/{run_id}/logs?limit=2"))
310            .header("authorization", &auth_header)
311            .body(Body::empty())
312            .unwrap();
313
314        let resp = app.clone().oneshot(req).await.unwrap();
315        let body = resp.into_body().collect().await.unwrap().to_bytes();
316        let page1: JsonValue = from_slice(&body).unwrap();
317        assert_eq!(page1["data"].as_array().unwrap().len(), 2);
318        assert_eq!(page1["meta"]["has_more"], true);
319
320        let cursor = page1["meta"]["next_cursor"].as_str().unwrap();
321
322        let req = Request::builder()
323            .uri(format!("/runs/{run_id}/logs?limit=2&cursor={cursor}"))
324            .header("authorization", &auth_header)
325            .body(Body::empty())
326            .unwrap();
327
328        let resp = app.clone().oneshot(req).await.unwrap();
329        let body = resp.into_body().collect().await.unwrap().to_bytes();
330        let page2: JsonValue = from_slice(&body).unwrap();
331        assert_eq!(page2["data"].as_array().unwrap().len(), 2);
332        assert_eq!(page2["data"][0]["line"], "line 2");
333        assert_eq!(page2["meta"]["has_more"], true);
334
335        let cursor = page2["meta"]["next_cursor"].as_str().unwrap();
336
337        let req = Request::builder()
338            .uri(format!("/runs/{run_id}/logs?limit=2&cursor={cursor}"))
339            .header("authorization", &auth_header)
340            .body(Body::empty())
341            .unwrap();
342
343        let resp = app.oneshot(req).await.unwrap();
344        let body = resp.into_body().collect().await.unwrap().to_bytes();
345        let page3: JsonValue = from_slice(&body).unwrap();
346        assert_eq!(page3["data"].as_array().unwrap().len(), 1);
347        assert_eq!(page3["meta"]["has_more"], false);
348        assert!(page3["meta"]["next_cursor"].is_null());
349    }
350
351    #[tokio::test]
352    async fn run_not_found_returns_404() {
353        let state = test_state();
354        let auth_header = make_auth_header(&state);
355        let app = Router::new()
356            .route("/runs/{id}/logs", get(get_run_logs))
357            .with_state(state);
358
359        let req = Request::builder()
360            .uri(format!("/runs/{}/logs", Uuid::now_v7()))
361            .header("authorization", auth_header)
362            .body(Body::empty())
363            .unwrap();
364
365        let resp = app.oneshot(req).await.unwrap();
366        assert_eq!(resp.status(), StatusCode::NOT_FOUND);
367    }
368
369    #[tokio::test]
370    async fn unauthenticated_returns_401() {
371        let state = test_state();
372        let run_id = create_run(&state).await;
373        let app = Router::new()
374            .route("/runs/{id}/logs", get(get_run_logs))
375            .with_state(state);
376
377        let req = Request::builder()
378            .uri(format!("/runs/{run_id}/logs"))
379            .body(Body::empty())
380            .unwrap();
381
382        let resp = app.oneshot(req).await.unwrap();
383        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
384    }
385
386    #[tokio::test]
387    async fn limit_capped_at_1000() {
388        let state = test_state();
389        let auth_header = make_auth_header(&state);
390        let run_id = create_run(&state).await;
391        let step_id = Uuid::now_v7();
392
393        push_logs(&state, run_id, step_id, LogStream::Stdout, 2).await;
394
395        let app = Router::new()
396            .route("/runs/{id}/logs", get(get_run_logs))
397            .with_state(state);
398
399        let req = Request::builder()
400            .uri(format!("/runs/{run_id}/logs?limit=5000"))
401            .header("authorization", auth_header)
402            .body(Body::empty())
403            .unwrap();
404
405        let resp = app.oneshot(req).await.unwrap();
406        assert_eq!(resp.status(), StatusCode::OK);
407
408        let body = resp.into_body().collect().await.unwrap().to_bytes();
409        let json_val: JsonValue = from_slice(&body).unwrap();
410        assert_eq!(json_val["data"].as_array().unwrap().len(), 2);
411    }
412
413    #[tokio::test]
414    async fn empty_logs_returns_empty_array() {
415        let state = test_state();
416        let auth_header = make_auth_header(&state);
417        let run_id = create_run(&state).await;
418
419        let app = Router::new()
420            .route("/runs/{id}/logs", get(get_run_logs))
421            .with_state(state);
422
423        let req = Request::builder()
424            .uri(format!("/runs/{run_id}/logs"))
425            .header("authorization", auth_header)
426            .body(Body::empty())
427            .unwrap();
428
429        let resp = app.oneshot(req).await.unwrap();
430        assert_eq!(resp.status(), StatusCode::OK);
431
432        let body = resp.into_body().collect().await.unwrap().to_bytes();
433        let json_val: JsonValue = from_slice(&body).unwrap();
434        assert_eq!(json_val["data"].as_array().unwrap().len(), 0);
435        assert_eq!(json_val["meta"]["has_more"], false);
436    }
437}