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::{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    /// Who triggered the run. Always present.
63    pub created_by: CreatedBy,
64    /// Idempotency key that produced this run, when one was supplied.
65    #[serde(default, skip_serializing_if = "Option::is_none")]
66    pub idempotency_key: Option<String>,
67    /// Exclusivity key held by this run until it reaches a terminal state,
68    /// when one was supplied.
69    #[serde(default, skip_serializing_if = "Option::is_none")]
70    pub concurrency_key: Option<String>,
71    /// Cumulative cost cap for this run, in USD. `None` means no cap.
72    #[cfg_attr(feature = "openapi", schema(value_type = Option<f64>))]
73    #[serde(default, skip_serializing_if = "Option::is_none")]
74    pub max_cost_usd: Option<Decimal>,
75    /// Typed output the handler set with `WorkflowContext::set_output`.
76    ///
77    /// Written when the run ends (completed, warning, failed or cancelled).
78    /// Omitted when the handler set no output.
79    #[serde(default, skip_serializing_if = "Option::is_none")]
80    pub output: Option<Value>,
81}
82
83impl From<Run> for RunResponse {
84    fn from(run: Run) -> Self {
85        let created_by = CreatedBy::from(&run);
86        RunResponse {
87            id: run.id,
88            workflow_name: run.workflow_name,
89            status: run.status.state,
90            trigger: run.trigger,
91            error: run.error,
92            retry_count: run.retry_count,
93            max_retries: run.max_retries,
94            cost_usd: run.cost_usd,
95            duration_ms: run.duration_ms,
96            created_at: run.created_at,
97            updated_at: run.updated_at,
98            started_at: run.started_at,
99            completed_at: run.completed_at,
100            handler_version: run.handler_version,
101            labels: run.labels,
102            scheduled_at: run.scheduled_at,
103            created_by,
104            idempotency_key: run.idempotency_key,
105            concurrency_key: run.concurrency_key,
106            max_cost_usd: run.max_cost_usd,
107            output: run.output,
108        }
109    }
110}
111
112/// Run detail response — includes steps and payload.
113#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
114#[derive(Debug, Serialize)]
115pub struct RunDetailResponse {
116    /// The run.
117    pub run: RunResponse,
118    /// Associated steps, ordered by position.
119    pub steps: Vec<StepResponse>,
120    /// Input payload that triggered this run.
121    pub payload: serde_json::Value,
122}
123
124/// Query parameters for listing runs.
125#[cfg_attr(feature = "openapi", derive(utoipa::IntoParams, utoipa::ToSchema))]
126#[derive(Debug, Deserialize)]
127pub struct ListRunsQuery {
128    /// Filter by workflow name.
129    pub workflow: Option<String>,
130    /// Filter by run status.
131    pub status: Option<RunStatus>,
132    /// Filter by step presence (only applies to completed/cancelled runs).
133    /// Non-terminal runs (pending, running, etc.) are always included.
134    /// When `true`, only return completed/cancelled runs that have steps.
135    /// When `false`, only return completed/cancelled runs without steps.
136    pub has_steps: Option<bool>,
137    /// Filter by labels. Comma-separated `key:value` pairs.
138    pub label: Option<String>,
139    /// Filter by author: the user ID that triggered the run.
140    ///
141    /// Also matches runs triggered by one of that user's API keys.
142    pub created_by: Option<Uuid>,
143    /// Page number (1-based).
144    pub page: Option<u32>,
145    /// Items per page.
146    pub per_page: Option<u32>,
147}
148
149impl ListRunsQuery {
150    /// Parse the comma-separated `label` param into a `HashMap`.
151    pub fn parse_labels(&self) -> Option<HashMap<String, String>> {
152        parse_label_param(&self.label)
153    }
154}
155
156/// Parse a comma-separated `key:value` label query param into a `HashMap`.
157///
158/// Entries without a `:` are ignored. Returns `None` when the param is
159/// absent or contains no valid entry.
160pub(crate) fn parse_label_param(raw: &Option<String>) -> Option<HashMap<String, String>> {
161    raw.as_ref().and_then(|raw| {
162        let mut map = HashMap::new();
163        for entry in raw.split(',') {
164            let entry = entry.trim();
165            if let Some((k, v)) = entry.split_once(':') {
166                map.insert(k.to_string(), v.to_string());
167            }
168        }
169        if map.is_empty() { None } else { Some(map) }
170    })
171}