1use 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#[derive(Debug, Deserialize)]
26#[cfg_attr(feature = "openapi", derive(utoipa::IntoParams, utoipa::ToSchema))]
27pub struct GetRunLogsQuery {
28 pub step_id: Option<Uuid>,
30 pub stream: Option<LogStream>,
32 pub cursor: Option<Uuid>,
34 pub limit: Option<u32>,
36}
37
38#[derive(Debug, Serialize)]
40#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
41pub struct LogCursorMeta {
42 pub next_cursor: Option<Uuid>,
44 pub has_more: bool,
46}
47
48#[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 max_cost_usd: None,
182 })
183 .await
184 .unwrap()
185 .into_run()
186 .id
187 }
188
189 async fn push_logs(state: &AppState, run_id: Uuid, step_id: Uuid, stream: LogStream, n: usize) {
190 state
191 .store
192 .append_logs(NewLogEntries {
193 ids: (0..n).map(|_| Uuid::now_v7()).collect(),
194 run_id,
195 step_id,
196 step_name: "build".to_string(),
197 stream,
198 lines: (0..n).map(|i| format!("line {i}")).collect(),
199 })
200 .await
201 .unwrap();
202 }
203
204 #[tokio::test]
205 async fn returns_persisted_logs() {
206 let state = test_state();
207 let auth_header = create_user_auth_header(&state, "testuser", false).await;
208 let run_id = create_run(&state).await;
209 let step_id = Uuid::now_v7();
210
211 push_logs(&state, run_id, step_id, LogStream::Stdout, 3).await;
212
213 let app = Router::new()
214 .route("/runs/{id}/logs", get(get_run_logs))
215 .with_state(state);
216
217 let req = Request::builder()
218 .uri(format!("/runs/{run_id}/logs"))
219 .header("authorization", auth_header)
220 .body(Body::empty())
221 .unwrap();
222
223 let resp = app.oneshot(req).await.unwrap();
224 assert_eq!(resp.status(), StatusCode::OK);
225
226 let body = resp.into_body().collect().await.unwrap().to_bytes();
227 let json_val: JsonValue = from_slice(&body).unwrap();
228 assert_eq!(json_val["data"].as_array().unwrap().len(), 3);
229 assert_eq!(json_val["data"][0]["line"], "line 0");
230 assert_eq!(json_val["data"][0]["stream"], "stdout");
231 assert_eq!(json_val["meta"]["has_more"], false);
232 assert!(json_val["meta"]["next_cursor"].is_null());
233 }
234
235 #[tokio::test]
236 async fn filters_by_step_id() {
237 let state = test_state();
238 let auth_header = create_user_auth_header(&state, "testuser", false).await;
239 let run_id = create_run(&state).await;
240 let step_a = Uuid::now_v7();
241 let step_b = Uuid::now_v7();
242
243 push_logs(&state, run_id, step_a, LogStream::Stdout, 2).await;
244 push_logs(&state, run_id, step_b, LogStream::Stdout, 3).await;
245
246 let app = Router::new()
247 .route("/runs/{id}/logs", get(get_run_logs))
248 .with_state(state);
249
250 let req = Request::builder()
251 .uri(format!("/runs/{run_id}/logs?step_id={step_a}"))
252 .header("authorization", auth_header)
253 .body(Body::empty())
254 .unwrap();
255
256 let resp = app.oneshot(req).await.unwrap();
257 assert_eq!(resp.status(), StatusCode::OK);
258
259 let body = resp.into_body().collect().await.unwrap().to_bytes();
260 let json_val: JsonValue = from_slice(&body).unwrap();
261 assert_eq!(json_val["data"].as_array().unwrap().len(), 2);
262 }
263
264 #[tokio::test]
265 async fn filters_by_stream() {
266 let state = test_state();
267 let auth_header = create_user_auth_header(&state, "testuser", false).await;
268 let run_id = create_run(&state).await;
269 let step_id = Uuid::now_v7();
270
271 push_logs(&state, run_id, step_id, LogStream::Stdout, 2).await;
272 push_logs(&state, run_id, step_id, LogStream::Stderr, 1).await;
273
274 let app = Router::new()
275 .route("/runs/{id}/logs", get(get_run_logs))
276 .with_state(state);
277
278 let req = Request::builder()
279 .uri(format!("/runs/{run_id}/logs?stream=stderr"))
280 .header("authorization", auth_header)
281 .body(Body::empty())
282 .unwrap();
283
284 let resp = app.oneshot(req).await.unwrap();
285 let body = resp.into_body().collect().await.unwrap().to_bytes();
286 let json_val: JsonValue = from_slice(&body).unwrap();
287 assert_eq!(json_val["data"].as_array().unwrap().len(), 1);
288 assert_eq!(json_val["data"][0]["stream"], "stderr");
289 }
290
291 #[tokio::test]
292 async fn cursor_based_pagination() {
293 let state = test_state();
294 let auth_header = create_user_auth_header(&state, "testuser", false).await;
295 let run_id = create_run(&state).await;
296 let step_id = Uuid::now_v7();
297
298 push_logs(&state, run_id, step_id, LogStream::Stdout, 5).await;
299
300 let app = Router::new()
301 .route("/runs/{id}/logs", get(get_run_logs))
302 .with_state(state);
303
304 let req = Request::builder()
305 .uri(format!("/runs/{run_id}/logs?limit=2"))
306 .header("authorization", &auth_header)
307 .body(Body::empty())
308 .unwrap();
309
310 let resp = app.clone().oneshot(req).await.unwrap();
311 let body = resp.into_body().collect().await.unwrap().to_bytes();
312 let page1: JsonValue = from_slice(&body).unwrap();
313 assert_eq!(page1["data"].as_array().unwrap().len(), 2);
314 assert_eq!(page1["meta"]["has_more"], true);
315
316 let cursor = page1["meta"]["next_cursor"].as_str().unwrap();
317
318 let req = Request::builder()
319 .uri(format!("/runs/{run_id}/logs?limit=2&cursor={cursor}"))
320 .header("authorization", &auth_header)
321 .body(Body::empty())
322 .unwrap();
323
324 let resp = app.clone().oneshot(req).await.unwrap();
325 let body = resp.into_body().collect().await.unwrap().to_bytes();
326 let page2: JsonValue = from_slice(&body).unwrap();
327 assert_eq!(page2["data"].as_array().unwrap().len(), 2);
328 assert_eq!(page2["data"][0]["line"], "line 2");
329 assert_eq!(page2["meta"]["has_more"], true);
330
331 let cursor = page2["meta"]["next_cursor"].as_str().unwrap();
332
333 let req = Request::builder()
334 .uri(format!("/runs/{run_id}/logs?limit=2&cursor={cursor}"))
335 .header("authorization", &auth_header)
336 .body(Body::empty())
337 .unwrap();
338
339 let resp = app.oneshot(req).await.unwrap();
340 let body = resp.into_body().collect().await.unwrap().to_bytes();
341 let page3: JsonValue = from_slice(&body).unwrap();
342 assert_eq!(page3["data"].as_array().unwrap().len(), 1);
343 assert_eq!(page3["meta"]["has_more"], false);
344 assert!(page3["meta"]["next_cursor"].is_null());
345 }
346
347 #[tokio::test]
348 async fn run_not_found_returns_404() {
349 let state = test_state();
350 let auth_header = create_user_auth_header(&state, "testuser", false).await;
351 let app = Router::new()
352 .route("/runs/{id}/logs", get(get_run_logs))
353 .with_state(state);
354
355 let req = Request::builder()
356 .uri(format!("/runs/{}/logs", Uuid::now_v7()))
357 .header("authorization", auth_header)
358 .body(Body::empty())
359 .unwrap();
360
361 let resp = app.oneshot(req).await.unwrap();
362 assert_eq!(resp.status(), StatusCode::NOT_FOUND);
363 }
364
365 #[tokio::test]
366 async fn unauthenticated_returns_401() {
367 let state = test_state();
368 let run_id = create_run(&state).await;
369 let app = Router::new()
370 .route("/runs/{id}/logs", get(get_run_logs))
371 .with_state(state);
372
373 let req = Request::builder()
374 .uri(format!("/runs/{run_id}/logs"))
375 .body(Body::empty())
376 .unwrap();
377
378 let resp = app.oneshot(req).await.unwrap();
379 assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
380 }
381
382 #[tokio::test]
383 async fn limit_capped_at_1000() {
384 let state = test_state();
385 let auth_header = create_user_auth_header(&state, "testuser", false).await;
386 let run_id = create_run(&state).await;
387 let step_id = Uuid::now_v7();
388
389 push_logs(&state, run_id, step_id, LogStream::Stdout, 2).await;
390
391 let app = Router::new()
392 .route("/runs/{id}/logs", get(get_run_logs))
393 .with_state(state);
394
395 let req = Request::builder()
396 .uri(format!("/runs/{run_id}/logs?limit=5000"))
397 .header("authorization", auth_header)
398 .body(Body::empty())
399 .unwrap();
400
401 let resp = app.oneshot(req).await.unwrap();
402 assert_eq!(resp.status(), StatusCode::OK);
403
404 let body = resp.into_body().collect().await.unwrap().to_bytes();
405 let json_val: JsonValue = from_slice(&body).unwrap();
406 assert_eq!(json_val["data"].as_array().unwrap().len(), 2);
407 }
408
409 #[tokio::test]
410 async fn empty_logs_returns_empty_array() {
411 let state = test_state();
412 let auth_header = create_user_auth_header(&state, "testuser", false).await;
413 let run_id = create_run(&state).await;
414
415 let app = Router::new()
416 .route("/runs/{id}/logs", get(get_run_logs))
417 .with_state(state);
418
419 let req = Request::builder()
420 .uri(format!("/runs/{run_id}/logs"))
421 .header("authorization", auth_header)
422 .body(Body::empty())
423 .unwrap();
424
425 let resp = app.oneshot(req).await.unwrap();
426 assert_eq!(resp.status(), StatusCode::OK);
427
428 let body = resp.into_body().collect().await.unwrap().to_bytes();
429 let json_val: JsonValue = from_slice(&body).unwrap();
430 assert_eq!(json_val["data"].as_array().unwrap().len(), 0);
431 assert_eq!(json_val["meta"]["has_more"], false);
432 }
433}