Skip to main content

ironflow_api/entities/
run.rs

1//! Run-related DTOs and query parameters.
2
3use std::collections::HashMap;
4
5use chrono::{DateTime, Utc};
6use ironflow_store::models::{ConcurrencyLimit, ProviderKind, Run, RunStatus, TriggerKind};
7use rust_decimal::Decimal;
8use serde::{Deserialize, Serialize};
9use serde_json::Value;
10use uuid::Uuid;
11
12use super::{CreatedBy, StepResponse};
13
14/// Run response DTO — public API representation of a run.
15///
16/// Maps from the internal [`Run`] model, exposing only necessary fields.
17///
18/// # Examples
19///
20/// ```
21/// use ironflow_store::models::{Run, RunStatus, TriggerKind};
22/// use ironflow_api::entities::RunResponse;
23/// ```
24#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
25#[derive(Debug, Serialize, Deserialize)]
26pub struct RunResponse {
27    /// Unique run identifier.
28    pub id: Uuid,
29    /// Workflow name.
30    pub workflow_name: String,
31    /// Current status.
32    pub status: RunStatus,
33    /// How the run was triggered.
34    pub trigger: TriggerKind,
35    /// Optional error message.
36    pub error: Option<String>,
37    /// Number of times retried.
38    pub retry_count: u32,
39    /// Maximum allowed retries.
40    pub max_retries: u32,
41    /// Aggregated cost in USD.
42    #[cfg_attr(feature = "openapi", schema(value_type = f64))]
43    pub cost_usd: Decimal,
44    /// Total duration in milliseconds.
45    pub duration_ms: u64,
46    /// When created.
47    pub created_at: DateTime<Utc>,
48    /// When last updated.
49    pub updated_at: DateTime<Utc>,
50    /// When execution started.
51    pub started_at: Option<DateTime<Utc>>,
52    /// When execution completed.
53    pub completed_at: Option<DateTime<Utc>>,
54    /// Version of the handler that created this run.
55    pub handler_version: Option<String>,
56    /// User-defined key-value labels.
57    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
58    pub labels: HashMap<String, String>,
59    /// Scheduled execution time. `None` means the run executed immediately.
60    #[serde(default, skip_serializing_if = "Option::is_none")]
61    pub scheduled_at: Option<DateTime<Utc>>,
62    /// Provider kind the run is waiting capacity for, set only while the
63    /// run is `sleeping` because every targeted Provider Account is rate
64    /// limited. `scheduled_at` then holds when the run wakes.
65    #[serde(default, skip_serializing_if = "Option::is_none")]
66    #[cfg_attr(feature = "openapi", schema(value_type = Option<String>))]
67    pub capacity_wait_kind: Option<ProviderKind>,
68    /// Who triggered the run. Always present.
69    pub created_by: CreatedBy,
70    /// Idempotency key that produced this run, when one was supplied.
71    #[serde(default, skip_serializing_if = "Option::is_none")]
72    pub idempotency_key: Option<String>,
73    /// Exclusivity key held by this run until it reaches a terminal state,
74    /// when one was supplied.
75    #[serde(default, skip_serializing_if = "Option::is_none")]
76    pub concurrency_key: Option<String>,
77    /// Concurrency groups the run belongs to, with the limit it was created
78    /// with. Omitted when the run belongs to no group.
79    #[serde(default, skip_serializing_if = "Vec::is_empty")]
80    pub concurrency_limits: Vec<ConcurrencyLimit>,
81    /// Cumulative cost cap for this run, in USD. `None` means no cap.
82    #[cfg_attr(feature = "openapi", schema(value_type = Option<f64>))]
83    #[serde(default, skip_serializing_if = "Option::is_none")]
84    pub max_cost_usd: Option<Decimal>,
85    /// Typed output the handler set with `WorkflowContext::set_output`.
86    ///
87    /// Written when the run ends (completed, warning, failed or cancelled).
88    /// Omitted when the handler set no output.
89    #[serde(default, skip_serializing_if = "Option::is_none")]
90    pub output: Option<Value>,
91}
92
93impl From<Run> for RunResponse {
94    fn from(run: Run) -> Self {
95        let created_by = CreatedBy::from(&run);
96        RunResponse {
97            id: run.id,
98            workflow_name: run.workflow_name,
99            status: run.status.state,
100            trigger: run.trigger,
101            error: run.error,
102            retry_count: run.retry_count,
103            max_retries: run.max_retries,
104            cost_usd: run.cost_usd,
105            duration_ms: run.duration_ms,
106            created_at: run.created_at,
107            updated_at: run.updated_at,
108            started_at: run.started_at,
109            completed_at: run.completed_at,
110            handler_version: run.handler_version,
111            labels: run.labels,
112            scheduled_at: run.scheduled_at,
113            capacity_wait_kind: run.capacity_wait_kind,
114            created_by,
115            idempotency_key: run.idempotency_key,
116            concurrency_key: run.concurrency_key,
117            concurrency_limits: run.concurrency_limits,
118            max_cost_usd: run.max_cost_usd,
119            output: run.output,
120        }
121    }
122}
123
124/// Run detail response — includes steps and payload.
125#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
126#[derive(Debug, Serialize)]
127pub struct RunDetailResponse {
128    /// The run.
129    pub run: RunResponse,
130    /// Associated steps, ordered by position.
131    pub steps: Vec<StepResponse>,
132    /// Input payload that triggered this run.
133    pub payload: serde_json::Value,
134    /// Sub-workflow runs below this run, at any depth, that are not finished:
135    /// cancelling the run cancels them too.
136    pub active_descendant_count: u64,
137}
138
139/// Response of `POST /api/v1/runs/:id/cancel`: the cancelled run, with the
140/// sub-workflow runs cancelled along with it.
141///
142/// The run's fields stay at the top level, as before the descendants were
143/// listed, so existing clients read the same document.
144#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
145#[derive(Debug, Serialize)]
146pub struct CancelRunResponse {
147    /// The cancelled run.
148    #[serde(flatten)]
149    pub run: RunResponse,
150    /// Sub-workflow runs below it that this request cancelled, oldest first.
151    /// Empty when none was still active.
152    pub cancelled_descendants: Vec<Uuid>,
153}
154
155/// Query parameters for listing runs.
156#[cfg_attr(feature = "openapi", derive(utoipa::IntoParams, utoipa::ToSchema))]
157#[derive(Debug, Deserialize)]
158pub struct ListRunsQuery {
159    /// Filter by workflow name.
160    pub workflow: Option<String>,
161    /// Filter by run status.
162    pub status: Option<RunStatus>,
163    /// Filter by step presence (only applies to completed/cancelled runs).
164    /// Non-terminal runs (pending, running, etc.) are always included.
165    /// When `true`, only return completed/cancelled runs that have steps.
166    /// When `false`, only return completed/cancelled runs without steps.
167    pub has_steps: Option<bool>,
168    /// Filter by labels. Comma-separated `key:value` pairs.
169    pub label: Option<String>,
170    /// Filter by author: the user ID that triggered the run.
171    ///
172    /// Also matches runs triggered by one of that user's API keys.
173    pub created_by: Option<Uuid>,
174    /// Filter by concurrency group: only runs that belong to this group.
175    pub concurrency_group: Option<String>,
176    /// Page number (1-based).
177    pub page: Option<u32>,
178    /// Items per page.
179    pub per_page: Option<u32>,
180}
181
182impl ListRunsQuery {
183    /// Parse the comma-separated `label` param into a `HashMap`.
184    pub fn parse_labels(&self) -> Option<HashMap<String, String>> {
185        parse_label_param(&self.label)
186    }
187}
188
189/// Parse a comma-separated `key:value` label query param into a `HashMap`.
190///
191/// Entries without a `:` are ignored. Returns `None` when the param is
192/// absent or contains no valid entry.
193pub(crate) fn parse_label_param(raw: &Option<String>) -> Option<HashMap<String, String>> {
194    raw.as_ref().and_then(|raw| {
195        let mut map = HashMap::new();
196        for entry in raw.split(',') {
197            let entry = entry.trim();
198            if let Some((k, v)) = entry.split_once(':') {
199                map.insert(k.to_string(), v.to_string());
200            }
201        }
202        if map.is_empty() { None } else { Some(map) }
203    })
204}