ironflow-engine 2.50.0

Workflow orchestration engine for ironflow with FSM-based run lifecycle
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
//! [`RunCreator`] trait and [`CreateRunOpts`] builder -- centralised run creation.
//!
//! [`RunCreator`] is a minimal trait with a single method: create a run from
//! a [`NewRun`]. It is intentionally thinner than [`RunStore`] so that any
//! store implementation can be used as a run creator through the blanket impl.
//!
//! [`CreateRunOpts`] is a builder for the optional fields of a run creation
//! request. Combined with [`WorkflowHandler::create_run`](crate::handler::WorkflowHandler::create_run), it assembles a
//! [`NewRun`] from the handler's own metadata, removing duplication across
//! call sites.
//!
//! # Examples
//!
//! ```no_run
//! use ironflow_engine::run_creator::{CreateRunOpts, RunCreator};
//! use ironflow_store::entities::TriggerKind;
//! use ironflow_store::memory::InMemoryStore;
//!
//! # async fn example() -> Result<(), ironflow_engine::error::EngineError> {
//! let store = InMemoryStore::new();
//! let creator: &dyn RunCreator = &store;
//!
//! let new_run = CreateRunOpts::new()
//!     .trigger(TriggerKind::Api)
//!     .build("deploy", Some("1.0.0"), None);
//!
//! let creation = creator.create_run(new_run).await?;
//! # Ok(())
//! # }
//! ```

use std::collections::HashMap;
use std::future::Future;
use std::pin::Pin;

use chrono::{DateTime, Utc};
use rust_decimal::Decimal;
use serde_json::Value;

use ironflow_store::entities::{NewRun, RunActor, RunCreation, TriggerKind, normalize_worker_tags};
use ironflow_store::store::RunStore;

use crate::error::EngineError;

/// Future returned by [`RunCreator::create_run`].
pub type RunCreatorFuture<'a> =
    Pin<Box<dyn Future<Output = Result<RunCreation, EngineError>> + Send + 'a>>;

/// Minimal trait for creating workflow runs.
///
/// Automatically implemented for every [`RunStore`] via a blanket impl,
/// so any store (InMemory, Postgres, ApiRunStore) is a valid [`RunCreator`].
///
/// # Examples
///
/// ```no_run
/// use ironflow_engine::run_creator::RunCreator;
/// use ironflow_store::entities::{NewRun, TriggerKind};
///
/// # async fn example(creator: &dyn RunCreator) -> Result<(), ironflow_engine::error::EngineError> {
/// let new_run = NewRun {
///     workflow_name: "deploy".to_string(),
///     trigger: TriggerKind::Manual,
///     payload: serde_json::json!({}),
///     max_retries: 0,
///     handler_version: None,
///     labels: Default::default(),
///     scheduled_at: None,
///     created_by: None,
///     idempotency_key: None,
///     concurrency_key: None,
///     concurrency_limits: Vec::new(),
///     max_cost_usd: None,
///     worker_tags: Vec::new(),
/// };
/// let creation = creator.create_run(new_run).await?;
/// # Ok(())
/// # }
/// ```
pub trait RunCreator: Send + Sync {
    /// Create a new workflow run.
    ///
    /// # Errors
    ///
    /// Returns [`EngineError`] if the run could not be created.
    fn create_run(&self, req: NewRun) -> RunCreatorFuture<'_>;
}

impl<T: RunStore + ?Sized> RunCreator for T {
    fn create_run(&self, req: NewRun) -> RunCreatorFuture<'_> {
        Box::pin(async move {
            RunStore::create_run(self, req)
                .await
                .map_err(EngineError::from)
        })
    }
}

/// Builder for optional run creation fields.
///
/// Builds a [`NewRun`] from handler metadata plus user-supplied overrides.
/// Use with [`WorkflowHandler::create_run`] to avoid duplicating workflow
/// name, version, and cost cap at every call site.
///
/// [`WorkflowHandler::create_run`]: crate::handler::WorkflowHandler::create_run
///
/// # Examples
///
/// ```
/// use ironflow_engine::run_creator::CreateRunOpts;
/// use ironflow_store::entities::TriggerKind;
/// use serde_json::json;
///
/// let new_run = CreateRunOpts::new()
///     .trigger(TriggerKind::Webhook { path: "/hooks/gh".to_string() })
///     .payload(json!({"ref": "main"}))
///     .max_retries(3)
///     .build("deploy", Some("2.0.0"), None);
///
/// assert_eq!(new_run.workflow_name, "deploy");
/// assert_eq!(new_run.max_retries, 3);
/// assert_eq!(new_run.handler_version, Some("2.0.0".to_string()));
/// ```
#[derive(Debug, Clone, Default)]
pub struct CreateRunOpts {
    trigger: Option<TriggerKind>,
    payload: Option<Value>,
    max_retries: Option<u32>,
    scheduled_at: Option<DateTime<Utc>>,
    created_by: Option<RunActor>,
    idempotency_key: Option<String>,
    concurrency_key: Option<String>,
    labels: Option<HashMap<String, String>>,
    max_cost_usd: Option<Decimal>,
    worker_tags: Vec<String>,
}

impl CreateRunOpts {
    /// Create a new builder with all fields unset.
    ///
    /// # Examples
    ///
    /// ```
    /// use ironflow_engine::run_creator::CreateRunOpts;
    ///
    /// let opts = CreateRunOpts::new();
    /// let new_run = opts.build("my-workflow", None, None);
    /// assert_eq!(new_run.workflow_name, "my-workflow");
    /// ```
    pub fn new() -> Self {
        Self::default()
    }

    /// Set how the run was triggered.
    ///
    /// Defaults to [`TriggerKind::Manual`] if not set.
    pub fn trigger(mut self, trigger: TriggerKind) -> Self {
        self.trigger = Some(trigger);
        self
    }

    /// Set the trigger-specific payload.
    ///
    /// Defaults to `json!({})` if not set.
    pub fn payload(mut self, payload: Value) -> Self {
        self.payload = Some(payload);
        self
    }

    /// Set the maximum retry attempts.
    ///
    /// Defaults to `0` if not set.
    pub fn max_retries(mut self, max_retries: u32) -> Self {
        self.max_retries = Some(max_retries);
        self
    }

    /// Schedule the run for later execution.
    pub fn scheduled_at(mut self, at: DateTime<Utc>) -> Self {
        self.scheduled_at = Some(at);
        self
    }

    /// Set the authenticated principal creating this run.
    pub fn created_by(mut self, actor: RunActor) -> Self {
        self.created_by = Some(actor);
        self
    }

    /// Set an idempotency key to prevent duplicate runs.
    pub fn idempotency_key(mut self, key: impl Into<String>) -> Self {
        self.idempotency_key = Some(key.into());
        self
    }

    /// Set a concurrency key: the store refuses the run while another
    /// non-terminal run holds the same key.
    ///
    /// # Examples
    ///
    /// ```
    /// use ironflow_engine::run_creator::CreateRunOpts;
    ///
    /// let new_run = CreateRunOpts::new()
    ///     .concurrency_key("issue:12")
    ///     .build("deploy", None, None);
    /// assert_eq!(new_run.concurrency_key.as_deref(), Some("issue:12"));
    /// ```
    pub fn concurrency_key(mut self, key: impl Into<String>) -> Self {
        self.concurrency_key = Some(key.into());
        self
    }

    /// Set user-defined labels for categorization.
    pub fn labels(mut self, labels: HashMap<String, String>) -> Self {
        self.labels = Some(labels);
        self
    }

    /// Set the maximum cumulative cost allowed for this run.
    pub fn max_cost_usd(mut self, cap: Decimal) -> Self {
        self.max_cost_usd = Some(cap);
        self
    }

    /// Add worker tags the run requires. Extends the tags already set.
    ///
    /// Tags are trimmed, sorted and deduplicated by [`build`](Self::build).
    /// The store refuses invalid ones when the run is created.
    ///
    /// # Examples
    ///
    /// ```
    /// use ironflow_engine::run_creator::CreateRunOpts;
    ///
    /// let new_run = CreateRunOpts::new()
    ///     .worker_tags(["region:eu", "gpu"])
    ///     .worker_tags(["gpu"])
    ///     .build("transcode", None, None);
    /// assert_eq!(new_run.worker_tags, vec!["gpu".to_string(), "region:eu".to_string()]);
    /// ```
    pub fn worker_tags<I, S>(mut self, tags: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.worker_tags.extend(tags.into_iter().map(Into::into));
        self
    }

    /// Assemble a [`NewRun`] from these options and handler metadata.
    ///
    /// * `workflow_name` -- typically from [`WorkflowHandler::name`].
    /// * `handler_version` -- typically from [`WorkflowHandler::version`].
    /// * `default_max_cost_usd` -- typically from [`WorkflowHandler::default_max_cost_usd`].
    ///   Applied only when [`max_cost_usd`](Self::max_cost_usd) was not set.
    ///
    /// [`WorkflowHandler::name`]: crate::handler::WorkflowHandler::name
    /// [`WorkflowHandler::version`]: crate::handler::WorkflowHandler::version
    /// [`WorkflowHandler::default_max_cost_usd`]: crate::handler::WorkflowHandler::default_max_cost_usd
    ///
    /// # Examples
    ///
    /// ```
    /// use ironflow_engine::run_creator::CreateRunOpts;
    /// use rust_decimal::Decimal;
    ///
    /// let new_run = CreateRunOpts::new()
    ///     .build("my-handler", Some("3.0.0"), Some(Decimal::new(1000, 2)));
    ///
    /// assert_eq!(new_run.workflow_name, "my-handler");
    /// assert_eq!(new_run.handler_version, Some("3.0.0".to_string()));
    /// assert_eq!(new_run.max_cost_usd, Some(Decimal::new(1000, 2)));
    /// ```
    pub fn build(
        self,
        workflow_name: &str,
        handler_version: Option<&str>,
        default_max_cost_usd: Option<Decimal>,
    ) -> NewRun {
        NewRun {
            workflow_name: workflow_name.to_string(),
            trigger: self.trigger.unwrap_or(TriggerKind::Manual),
            payload: self.payload.unwrap_or_else(|| serde_json::json!({})),
            max_retries: self.max_retries.unwrap_or(0),
            handler_version: handler_version.map(str::to_string),
            labels: self.labels.unwrap_or_default(),
            scheduled_at: self.scheduled_at,
            created_by: self.created_by,
            idempotency_key: self.idempotency_key,
            concurrency_key: self.concurrency_key,
            concurrency_limits: Vec::new(),
            max_cost_usd: self.max_cost_usd.or(default_max_cost_usd),
            worker_tags: normalize_worker_tags(self.worker_tags),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    #[test]
    fn create_run_opts_default_produces_correct_defaults() {
        let opts = CreateRunOpts::new();
        let new_run = opts.build("test-workflow", None, None);

        assert_eq!(new_run.workflow_name, "test-workflow");
        assert_eq!(new_run.trigger, TriggerKind::Manual);
        assert_eq!(new_run.payload, json!({}));
        assert_eq!(new_run.max_retries, 0);
        assert_eq!(new_run.handler_version, None);
        assert!(new_run.labels.is_empty());
        assert_eq!(new_run.scheduled_at, None);
        assert_eq!(new_run.created_by, None);
        assert_eq!(new_run.idempotency_key, None);
        assert_eq!(new_run.concurrency_key, None);
        assert_eq!(new_run.max_cost_usd, None);
    }

    #[test]
    fn create_run_opts_without_worker_tags_requires_none() {
        let new_run = CreateRunOpts::new().build("test-workflow", None, None);
        assert!(new_run.worker_tags.is_empty());
    }

    #[test]
    fn create_run_opts_worker_tags_are_merged_and_normalized() {
        let new_run = CreateRunOpts::new()
            .worker_tags(["region:eu", " gpu "])
            .worker_tags(vec!["gpu".to_string()])
            .build("test-workflow", None, None);
        assert_eq!(
            new_run.worker_tags,
            vec!["gpu".to_string(), "region:eu".to_string()]
        );
    }

    #[test]
    fn create_run_opts_builder_sets_all_fields() {
        let labels = HashMap::from([("env".to_string(), "prod".to_string())]);
        let scheduled = Utc::now();

        let new_run = CreateRunOpts::new()
            .trigger(TriggerKind::Webhook {
                path: "/hooks/gh".to_string(),
            })
            .payload(json!({"ref": "main"}))
            .max_retries(3)
            .scheduled_at(scheduled)
            .idempotency_key("key-123")
            .labels(labels.clone())
            .max_cost_usd(Decimal::new(500, 2))
            .build("deploy", Some("2.0.0"), None);

        assert_eq!(new_run.workflow_name, "deploy");
        assert_eq!(
            new_run.trigger,
            TriggerKind::Webhook {
                path: "/hooks/gh".to_string()
            }
        );
        assert_eq!(new_run.payload, json!({"ref": "main"}));
        assert_eq!(new_run.max_retries, 3);
        assert_eq!(new_run.handler_version, Some("2.0.0".to_string()));
        assert_eq!(new_run.scheduled_at, Some(scheduled));
        assert_eq!(new_run.idempotency_key, Some("key-123".to_string()));
        assert_eq!(new_run.labels, labels);
        assert_eq!(new_run.max_cost_usd, Some(Decimal::new(500, 2)));
    }

    #[test]
    fn create_run_opts_build_carries_the_concurrency_key() {
        let new_run = CreateRunOpts::new()
            .concurrency_key("issue:12")
            .build("deploy", None, None);

        assert_eq!(new_run.concurrency_key.as_deref(), Some("issue:12"));
        assert_eq!(new_run.idempotency_key, None);
    }

    #[test]
    fn create_run_opts_build_uses_handler_metadata() {
        let new_run =
            CreateRunOpts::new().build("my-handler", Some("3.0.0"), Some(Decimal::new(1000, 2)));

        assert_eq!(new_run.workflow_name, "my-handler");
        assert_eq!(new_run.handler_version, Some("3.0.0".to_string()));
        assert_eq!(new_run.max_cost_usd, Some(Decimal::new(1000, 2)));
    }

    #[test]
    fn create_run_opts_explicit_max_cost_overrides_handler_default() {
        let new_run = CreateRunOpts::new()
            .max_cost_usd(Decimal::new(200, 2))
            .build("handler", Some("1"), Some(Decimal::new(1000, 2)));

        assert_eq!(new_run.max_cost_usd, Some(Decimal::new(200, 2)));
    }

    #[tokio::test]
    async fn run_creator_blanket_impl_with_in_memory_store() {
        use ironflow_store::memory::InMemoryStore;

        let store = InMemoryStore::new();
        let creator: &dyn RunCreator = &store;

        let new_run =
            CreateRunOpts::new()
                .trigger(TriggerKind::Api)
                .build("blanket-test", None, None);

        let creation = creator.create_run(new_run).await.expect("create_run");
        let run = creation.into_run();
        assert_eq!(run.workflow_name, "blanket-test");
    }

    #[tokio::test]
    async fn create_run_with_reused_idempotency_key_returns_existing() {
        use ironflow_store::memory::InMemoryStore;

        let store = InMemoryStore::new();
        let creator: &dyn RunCreator = &store;

        let first = creator
            .create_run(CreateRunOpts::new().idempotency_key("dedup-1").build(
                "idem-test",
                None,
                None,
            ))
            .await
            .expect("first create_run");
        assert!(first.is_created());

        let second = creator
            .create_run(CreateRunOpts::new().idempotency_key("dedup-1").build(
                "idem-test",
                None,
                None,
            ))
            .await
            .expect("second create_run");
        assert!(!second.is_created());
        assert_eq!(first.into_run().id, second.into_run().id);
    }
}