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