ironflow-api 2.31.4

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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
//! `GET /api/v1/workflows/:name` — Get workflow details.

use std::collections::{HashMap, HashSet};

use axum::extract::{Path, State};
use axum::response::IntoResponse;
use ironflow_auth::extractor::Authenticated;
use rust_decimal::Decimal;
use serde::Serialize;
use serde_json::Value;

use crate::error::ApiError;
use crate::response::ok;
use crate::state::AppState;

/// Sub-workflow detail included in the workflow response.
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[derive(Debug, Serialize)]
pub struct SubWorkflowDetail {
    /// Sub-workflow name.
    pub name: String,
    /// Human-readable description.
    pub description: String,
    /// Optional Rust source code of the handler.
    pub source_code: Option<String>,
}

/// Workflow detail response.
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[derive(Debug, Serialize)]
pub struct WorkflowDetailResponse {
    /// Workflow name.
    pub name: String,
    /// Human-readable description.
    pub description: String,
    /// Optional Rust source code of the handler.
    pub source_code: Option<String>,
    /// Sub-workflows invoked by this handler (recursive, depth-limited).
    pub sub_workflows: Vec<SubWorkflowDetail>,
    /// Optional `/`-separated category path used to group workflows.
    pub category: Option<String>,
    /// Current handler version.
    pub version: Option<String>,
    /// Versions accepted for replay without `force`.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub compatible_versions: Vec<String>,
    /// JSON Schema describing the expected input payload.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub input_schema: Option<Value>,
    /// Labels automatically applied to every run of this workflow.
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub default_labels: HashMap<String, String>,
    /// Optional 6-field cron expression for automatic execution.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub schedule: Option<String>,
    /// Default cumulative cost cap applied to runs of this workflow, in USD.
    ///
    /// Overridden by a cap supplied at run creation. `None` means the workflow
    /// declares no default and falls back to the server default (if any).
    #[cfg_attr(feature = "openapi", schema(value_type = Option<f64>))]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub default_max_cost_usd: Option<Decimal>,
}

/// Get details about a registered workflow.
///
/// # Errors
///
/// - 404 if the workflow is not registered
#[cfg_attr(
    feature = "openapi",
    utoipa::path(
        get,
        path = "/api/v1/workflows/{name}",
        tags = ["workflows"],
        params(("name" = String, Path, description = "Workflow name")),
        responses(
            (status = 200, description = "Workflow details", body = WorkflowDetailResponse),
            (status = 401, description = "Unauthorized"),
            (status = 404, description = "Workflow not found")
        ),
        security(("Bearer" = []))
    )
)]
pub async fn get_workflow(
    _auth: Authenticated,
    State(state): State<AppState>,
    Path(name): Path<String>,
) -> Result<impl IntoResponse, ApiError> {
    let info = state
        .engine
        .handler_info(&name)
        .ok_or_else(|| ApiError::WorkflowNotFound(name.clone()))?;

    let mut sub_workflows = Vec::new();
    let mut visited = HashSet::new();
    visited.insert(name.clone());
    collect_sub_workflows(
        &state,
        &info.sub_workflows,
        &mut sub_workflows,
        &mut visited,
        5,
    );

    Ok(ok(WorkflowDetailResponse {
        name,
        description: info.description,
        source_code: info.source_code,
        sub_workflows,
        category: info.category,
        version: info.version,
        compatible_versions: info.compatible_versions,
        input_schema: info.input_schema,
        default_labels: info.default_labels,
        schedule: info.schedule.map(|s| s.as_str().to_string()),
        default_max_cost_usd: info.default_max_cost_usd,
    }))
}

fn collect_sub_workflows(
    state: &AppState,
    names: &[String],
    result: &mut Vec<SubWorkflowDetail>,
    visited: &mut HashSet<String>,
    depth: usize,
) {
    if depth == 0 {
        return;
    }
    for sub_name in names {
        if !visited.insert(sub_name.clone()) {
            continue;
        }
        if let Some(sub_info) = state.engine.handler_info(sub_name) {
            collect_sub_workflows(state, &sub_info.sub_workflows, result, visited, depth - 1);
            result.push(SubWorkflowDetail {
                name: sub_name.clone(),
                description: sub_info.description,
                source_code: sub_info.source_code,
            });
        }
    }
}

#[cfg(test)]
mod tests {
    use axum::Router;
    use axum::body::Body;
    use axum::http::{Request, StatusCode};
    use axum::routing::get;
    use http_body_util::BodyExt;
    use ironflow_auth::jwt::AccessToken;
    use ironflow_core::providers::claude::ClaudeCodeProvider;
    use ironflow_engine::context::WorkflowContext;
    use ironflow_engine::engine::Engine;
    use ironflow_engine::handler::{HandlerFuture, WorkflowHandler};
    use ironflow_engine::notify::Event;
    use ironflow_store::memory::InMemoryStore;
    use serde_json::Value as JsonValue;
    use std::sync::Arc;
    use tokio::sync::broadcast;
    use tower::ServiceExt;
    use uuid::Uuid;

    use super::*;

    struct DescribedWorkflow;
    impl WorkflowHandler for DescribedWorkflow {
        fn name(&self) -> &str {
            "my-workflow"
        }
        fn execute<'a>(&'a self, _ctx: &'a mut WorkflowContext) -> HandlerFuture<'a> {
            Box::pin(async move { Ok(()) })
        }
    }

    struct CategorizedWorkflow;
    impl WorkflowHandler for CategorizedWorkflow {
        fn name(&self) -> &str {
            "cat-workflow"
        }
        fn category(&self) -> Option<&str> {
            Some("data/etl")
        }
        fn execute<'a>(&'a self, _ctx: &'a mut WorkflowContext) -> HandlerFuture<'a> {
            Box::pin(async move { Ok(()) })
        }
    }

    fn test_state() -> AppState {
        let store = Arc::new(InMemoryStore::new());
        Arc::new(InMemoryStore::new());
        let provider = Arc::new(ClaudeCodeProvider::new());
        let mut engine = Engine::new(store.clone(), provider);
        engine.register(DescribedWorkflow).unwrap();
        engine.register(CategorizedWorkflow).unwrap();
        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>(1);
        AppState::new(
            store,
            Arc::new(engine),
            jwt_config,
            "test-worker-token".to_string(),
            event_sender,
        )
    }

    fn make_auth_header(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)
    }

    #[tokio::test]
    async fn get_workflow_found() {
        let state = test_state();
        let auth_header = make_auth_header(&state);
        let app = Router::new()
            .route("/{name}", get(get_workflow))
            .with_state(state);

        let req = Request::builder()
            .uri("/my-workflow")
            .header("authorization", auth_header)
            .body(Body::empty())
            .unwrap();

        let resp = app.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::OK);

        let body = resp.into_body().collect().await.unwrap().to_bytes();
        let json_val: JsonValue = serde_json::from_slice(&body).unwrap();
        assert_eq!(json_val["data"]["name"], "my-workflow");
    }

    #[tokio::test]
    async fn get_workflow_returns_category_when_set() {
        let state = test_state();
        let auth_header = make_auth_header(&state);
        let app = Router::new()
            .route("/{name}", get(get_workflow))
            .with_state(state);

        let req = Request::builder()
            .uri("/cat-workflow")
            .header("authorization", auth_header)
            .body(Body::empty())
            .unwrap();

        let resp = app.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        let body = resp.into_body().collect().await.unwrap().to_bytes();
        let json_val: JsonValue = serde_json::from_slice(&body).unwrap();
        assert_eq!(json_val["data"]["category"], "data/etl");
    }

    #[tokio::test]
    async fn get_workflow_category_null_when_uncategorized() {
        let state = test_state();
        let auth_header = make_auth_header(&state);
        let app = Router::new()
            .route("/{name}", get(get_workflow))
            .with_state(state);

        let req = Request::builder()
            .uri("/my-workflow")
            .header("authorization", auth_header)
            .body(Body::empty())
            .unwrap();

        let resp = app.oneshot(req).await.unwrap();
        let body = resp.into_body().collect().await.unwrap().to_bytes();
        let json_val: JsonValue = serde_json::from_slice(&body).unwrap();
        assert!(json_val["data"]["category"].is_null());
    }

    struct CappedWorkflow;

    impl WorkflowHandler for CappedWorkflow {
        fn name(&self) -> &str {
            "capped-workflow"
        }
        fn default_max_cost_usd(&self) -> Option<Decimal> {
            Some(Decimal::new(325, 2))
        }
        fn execute<'a>(&'a self, _ctx: &'a mut WorkflowContext) -> HandlerFuture<'a> {
            Box::pin(async move { Ok(()) })
        }
    }

    #[tokio::test]
    async fn get_workflow_returns_handler_default_max_cost() {
        let state = {
            let store = Arc::new(InMemoryStore::new());
            let provider = Arc::new(ClaudeCodeProvider::new());
            let mut engine = Engine::new(store.clone(), provider);
            engine.register(DescribedWorkflow).unwrap();
            engine.register(CappedWorkflow).unwrap();
            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>(1);
            AppState::new(
                store,
                Arc::new(engine),
                jwt_config,
                "test-worker-token".to_string(),
                event_sender,
            )
        };
        let auth_header = make_auth_header(&state);
        let app = Router::new()
            .route("/{name}", get(get_workflow))
            .with_state(state);

        let req = Request::builder()
            .uri("/capped-workflow")
            .header("authorization", auth_header.clone())
            .body(Body::empty())
            .unwrap();

        let resp = app.clone().oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        let body = resp.into_body().collect().await.unwrap().to_bytes();
        let json_val: JsonValue = serde_json::from_slice(&body).unwrap();
        assert_eq!(json_val["data"]["default_max_cost_usd"], 3.25);

        // A handler without a declared cap omits the field entirely.
        let req = Request::builder()
            .uri("/my-workflow")
            .header("authorization", auth_header)
            .body(Body::empty())
            .unwrap();

        let resp = app.oneshot(req).await.unwrap();
        let body = resp.into_body().collect().await.unwrap().to_bytes();
        let json_val: JsonValue = serde_json::from_slice(&body).unwrap();
        assert!(json_val["data"].get("default_max_cost_usd").is_none());
    }

    struct ScheduledWorkflow {
        schedule: ironflow_engine::prelude::CronSchedule,
    }
    impl ScheduledWorkflow {
        fn new() -> Self {
            Self {
                schedule: ironflow_engine::prelude::CronSchedule::new("0 0 * * * *").unwrap(),
            }
        }
    }
    impl WorkflowHandler for ScheduledWorkflow {
        fn name(&self) -> &str {
            "sched-workflow"
        }
        fn schedule(&self) -> Option<&ironflow_engine::prelude::CronSchedule> {
            Some(&self.schedule)
        }
        fn execute<'a>(&'a self, _ctx: &'a mut WorkflowContext) -> HandlerFuture<'a> {
            Box::pin(async move { Ok(()) })
        }
    }

    fn test_state_with_schedule() -> AppState {
        let store = Arc::new(InMemoryStore::new());
        let provider = Arc::new(ClaudeCodeProvider::new());
        let mut engine = Engine::new(store.clone(), provider);
        engine.register(DescribedWorkflow).unwrap();
        engine.register(ScheduledWorkflow::new()).unwrap();
        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>(1);
        AppState::new(
            store,
            Arc::new(engine),
            jwt_config,
            "test-worker-token".to_string(),
            event_sender,
        )
    }

    #[tokio::test]
    async fn get_workflow_returns_schedule_when_set() {
        let state = test_state_with_schedule();
        let auth_header = make_auth_header(&state);
        let app = Router::new()
            .route("/{name}", get(get_workflow))
            .with_state(state);

        let req = Request::builder()
            .uri("/sched-workflow")
            .header("authorization", auth_header)
            .body(Body::empty())
            .unwrap();

        let resp = app.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        let body = resp.into_body().collect().await.unwrap().to_bytes();
        let json_val: JsonValue = serde_json::from_slice(&body).unwrap();
        assert_eq!(json_val["data"]["schedule"], "0 0 * * * *");
    }

    #[tokio::test]
    async fn get_workflow_schedule_null_when_unscheduled() {
        let state = test_state_with_schedule();
        let auth_header = make_auth_header(&state);
        let app = Router::new()
            .route("/{name}", get(get_workflow))
            .with_state(state);

        let req = Request::builder()
            .uri("/my-workflow")
            .header("authorization", auth_header)
            .body(Body::empty())
            .unwrap();

        let resp = app.oneshot(req).await.unwrap();
        let body = resp.into_body().collect().await.unwrap().to_bytes();
        let json_val: JsonValue = serde_json::from_slice(&body).unwrap();
        assert!(json_val["data"]["schedule"].is_null());
    }

    #[tokio::test]
    async fn get_workflow_not_found() {
        let state = test_state();
        let auth_header = make_auth_header(&state);
        let app = Router::new()
            .route("/{name}", get(get_workflow))
            .with_state(state);

        let req = Request::builder()
            .uri("/nonexistent")
            .header("authorization", auth_header)
            .body(Body::empty())
            .unwrap();

        let resp = app.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::NOT_FOUND);
    }
}