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 /// Tags a worker must carry to take this run, sorted. Empty when any
86 /// worker can take it.
87 #[serde(default)]
88 pub worker_tags: Vec<String>,
89 /// Typed output the handler set with `WorkflowContext::set_output`.
90 ///
91 /// Written when the run ends (completed, warning, failed or cancelled).
92 /// Omitted when the handler set no output.
93 #[serde(default, skip_serializing_if = "Option::is_none")]
94 pub output: Option<Value>,
95}
96
97impl From<Run> for RunResponse {
98 fn from(run: Run) -> Self {
99 let created_by = CreatedBy::from(&run);
100 RunResponse {
101 id: run.id,
102 workflow_name: run.workflow_name,
103 status: run.status.state,
104 trigger: run.trigger,
105 error: run.error,
106 retry_count: run.retry_count,
107 max_retries: run.max_retries,
108 cost_usd: run.cost_usd,
109 duration_ms: run.duration_ms,
110 created_at: run.created_at,
111 updated_at: run.updated_at,
112 started_at: run.started_at,
113 completed_at: run.completed_at,
114 handler_version: run.handler_version,
115 labels: run.labels,
116 scheduled_at: run.scheduled_at,
117 capacity_wait_kind: run.capacity_wait_kind,
118 created_by,
119 idempotency_key: run.idempotency_key,
120 concurrency_key: run.concurrency_key,
121 concurrency_limits: run.concurrency_limits,
122 max_cost_usd: run.max_cost_usd,
123 worker_tags: run.worker_tags,
124 output: run.output,
125 }
126 }
127}
128
129/// Run detail response — includes steps and payload.
130#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
131#[derive(Debug, Serialize)]
132pub struct RunDetailResponse {
133 /// The run.
134 pub run: RunResponse,
135 /// Associated steps, ordered by position.
136 pub steps: Vec<StepResponse>,
137 /// Input payload that triggered this run.
138 pub payload: serde_json::Value,
139 /// Sub-workflow runs below this run, at any depth, that are not finished:
140 /// cancelling the run cancels them too.
141 pub active_descendant_count: u64,
142 /// Workers seen recently that could take the run. Only filled while the
143 /// run waits in the queue (`pending` or `retrying`), so a run no worker
144 /// can take is visible instead of waiting in silence.
145 #[serde(default, skip_serializing_if = "Option::is_none")]
146 pub worker_routing: Option<WorkerRouting>,
147}
148
149/// Workers the API saw recently, as seen from one queued run.
150///
151/// Counted from the pick requests received in the last few minutes by this
152/// API process: with several replicas, each one only counts the workers that
153/// polled it.
154///
155/// # Examples
156///
157/// ```
158/// use ironflow_api::entities::WorkerRouting;
159///
160/// let routing = WorkerRouting {
161/// seen_workers: 2,
162/// eligible_workers: 0,
163/// };
164/// assert!(routing.eligible_workers < routing.seen_workers);
165/// ```
166#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
167#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
168pub struct WorkerRouting {
169 /// Workers that asked for a run recently.
170 pub seen_workers: u32,
171 /// Among them, the workers that registered the run's workflow and carry
172 /// every tag it requires.
173 pub eligible_workers: u32,
174}
175
176/// Response of `POST /api/v1/runs/:id/cancel`: the cancelled run, with the
177/// sub-workflow runs cancelled along with it.
178///
179/// The run's fields stay at the top level, as before the descendants were
180/// listed, so existing clients read the same document.
181#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
182#[derive(Debug, Serialize)]
183pub struct CancelRunResponse {
184 /// The cancelled run.
185 #[serde(flatten)]
186 pub run: RunResponse,
187 /// Sub-workflow runs below it that this request cancelled, oldest first.
188 /// Empty when none was still active.
189 pub cancelled_descendants: Vec<Uuid>,
190}
191
192/// Query parameters for listing runs.
193#[cfg_attr(feature = "openapi", derive(utoipa::IntoParams, utoipa::ToSchema))]
194#[derive(Debug, Deserialize)]
195pub struct ListRunsQuery {
196 /// Filter by workflow name.
197 pub workflow: Option<String>,
198 /// Filter by run status.
199 pub status: Option<RunStatus>,
200 /// Filter by step presence (only applies to completed/cancelled runs).
201 /// Non-terminal runs (pending, running, etc.) are always included.
202 /// When `true`, only return completed/cancelled runs that have steps.
203 /// When `false`, only return completed/cancelled runs without steps.
204 pub has_steps: Option<bool>,
205 /// Filter by labels. Comma-separated `key:value` pairs.
206 pub label: Option<String>,
207 /// Filter by author: the user ID that triggered the run.
208 ///
209 /// Also matches runs triggered by one of that user's API keys.
210 pub created_by: Option<Uuid>,
211 /// Filter by concurrency group: only runs that belong to this group.
212 pub concurrency_group: Option<String>,
213 /// Page number (1-based).
214 pub page: Option<u32>,
215 /// Items per page.
216 pub per_page: Option<u32>,
217}
218
219impl ListRunsQuery {
220 /// Parse the comma-separated `label` param into a `HashMap`.
221 pub fn parse_labels(&self) -> Option<HashMap<String, String>> {
222 parse_label_param(&self.label)
223 }
224}
225
226/// Parse a comma-separated `key:value` label query param into a `HashMap`.
227///
228/// Entries without a `:` are ignored. Returns `None` when the param is
229/// absent or contains no valid entry.
230pub(crate) fn parse_label_param(raw: &Option<String>) -> Option<HashMap<String, String>> {
231 raw.as_ref().and_then(|raw| {
232 let mut map = HashMap::new();
233 for entry in raw.split(',') {
234 let entry = entry.trim();
235 if let Some((k, v)) = entry.split_once(':') {
236 map.insert(k.to_string(), v.to_string());
237 }
238 }
239 if map.is_empty() { None } else { Some(map) }
240 })
241}