graphrun 0.1.3

Embedded durable workflow engine for Rust
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
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
//! Linear fluent graph builder.
//!
//! [`workflow`] starts a definition. [`region`] starts a nested body.
//! First step uses the run or region input; later steps use the previous
//! output. The published graph is still data.

use crate::binding::Condition;
use crate::builder::{
    ActivityRef, Branch, Case, NodeRef, Region, RegionBuilder, RegionGraphBuilder, SignalRef,
    TimedWaitRef, ValueRef, WorkflowBuilder,
};
use crate::catalog::Catalog;
use crate::error::{Error, Result};
use crate::ir::Definition;
use crate::schema::DurablePayload;
use crate::value::Value;
use std::time::Duration;

/// Nested region. First activity uses `scope.input`. Completes as node `done`.
pub fn region<I: DurablePayload>() -> Sequence<I, I> {
    let inner = RegionBuilder::new();
    let last = inner.input();
    Sequence {
        inner,
        last,
        last_activity: None,
    }
}

/// Root workflow named `id` at version 1. First activity uses `workflow.input`.
/// Completes as node `finish`.
///
/// ```
/// use graphrun::{payload, workflow, Catalog};
/// #[derive(Clone, serde::Serialize, serde::Deserialize)]
/// struct Counter { value: i64 }
/// payload!(Counter, "counter");
/// let catalog = Catalog::from_json(br#"{
///   "format": "graphrun.catalog/v1",
///   "schemas": {
///     "counter/v1": {
///       "type": "object",
///       "required": ["value"],
///       "additionalProperties": false,
///       "properties": {"value": {"type": "integer"}}
///     }
///   },
///   "activities": [{
///     "name": "counter.increment",
///     "version": 1,
///     "input_schema": "counter/v1",
///     "output_schema": "counter/v1",
///     "execution": "async",
///     "effects": "pure",
///     "recovery": "RetrySafe",
///     "error_codes": []
///   }]
/// }"#).unwrap();
/// let inc = catalog.activity_v1::<Counter, Counter>("counter.increment").unwrap();
/// let def = workflow::<Counter>("hello")
///     .activity("inc", &inc)
///     .unwrap()
///     .finish(&catalog)
///     .unwrap();
/// assert_eq!(def.id, "hello");
/// ```
pub fn workflow<I: DurablePayload>(id: impl Into<String>) -> Workflow<I, I> {
    let inner = RegionBuilder::new();
    let last = inner.workflow_input();
    Workflow {
        name: id.into(),
        seq: Sequence {
            inner,
            last,
            last_activity: None,
        },
    }
}

pub struct Sequence<I, Cur> {
    inner: RegionBuilder<I>,
    last: ValueRef<Cur>,
    last_activity: Option<NodeRef<Cur>>,
}

pub struct Workflow<I, Cur> {
    name: String,
    seq: Sequence<I, Cur>,
}

impl<I: DurablePayload, Cur: DurablePayload> Sequence<I, Cur> {
    pub fn activity<O: DurablePayload>(
        mut self,
        key: &str,
        activity: &ActivityRef<Cur, O>,
    ) -> Result<Sequence<I, O>> {
        let node = self.inner.activity(key, activity, self.last)?;
        Ok(Sequence {
            inner: self.inner,
            last: node.output(),
            last_activity: Some(node),
        })
    }

    pub fn compensate<U: DurablePayload>(mut self, activity: &ActivityRef<Cur, U>) -> Result<Self> {
        let node = self
            .last_activity
            .as_ref()
            .ok_or_else(|| Error::invalid("compensate must follow an activity"))?;
        self.inner.compensate(node, activity)?;
        Ok(self)
    }

    pub fn wait_signal<T: DurablePayload>(
        mut self,
        key: &str,
        signal: &SignalRef<T>,
        correlation: &str,
    ) -> Result<Sequence<I, T>> {
        let corr = self.inner.literal(correlation.to_owned())?;
        let node = self.inner.wait_signal(key, signal, corr)?;
        Ok(Sequence {
            inner: self.inner,
            last: node.output(),
            last_activity: None,
        })
    }

    pub fn while_lt(
        mut self,
        key: &str,
        path: &str,
        value: i64,
        body: Region<Cur, Cur>,
        max_iterations: u32,
    ) -> Result<Self> {
        let node = self.inner.while_loop(
            key,
            self.last.clone(),
            Condition::lt_loop(path, value),
            body,
            max_iterations,
        )?;
        Ok(Sequence {
            inner: self.inner,
            last: node.output(),
            last_activity: None,
        })
    }

    pub fn repeat(
        mut self,
        key: &str,
        count: i64,
        body: Region<Cur, Cur>,
        max_iterations: u32,
    ) -> Result<Self> {
        let n = self.inner.literal(count)?;
        let node = self
            .inner
            .repeat(key, n, self.last.clone(), body, max_iterations)?;
        Ok(Sequence {
            inner: self.inner,
            last: node.output(),
            last_activity: None,
        })
    }

    pub fn saga<B: DurablePayload>(
        mut self,
        key: &str,
        body: Region<Cur, B>,
    ) -> Result<Sequence<I, B>> {
        let node = self.inner.saga(key, self.last.clone(), body)?;
        Ok(Sequence {
            inner: self.inner,
            last: node.output(),
            last_activity: None,
        })
    }

    pub fn choose(self, key: impl Into<String>) -> Choose<I, Cur, Cur> {
        Choose {
            name: None,
            seq: self,
            key: key.into(),
            cases: Vec::new(),
        }
    }

    pub fn parallel(self, key: impl Into<String>) -> ParallelStart<I, Cur> {
        ParallelStart {
            name: None,
            seq: self,
            key: key.into(),
        }
    }

    pub fn fail<O: DurablePayload>(
        self,
        key: &str,
        code: &str,
        message: &str,
    ) -> Result<Region<I, O>> {
        self.inner.fail(key, code, message)
    }

    pub fn complete(self, key: &str) -> Result<Region<I, Cur>> {
        self.inner.complete(key, self.last)
    }

    /// Complete this region as node `done`.
    pub fn finish(self) -> Result<Region<I, Cur>> {
        self.complete("done")
    }
}

impl<I: DurablePayload, A: DurablePayload> Sequence<I, Vec<A>> {
    pub fn foreach<B: DurablePayload>(
        mut self,
        key: &str,
        body: Region<A, B>,
        max_items: u32,
        max_concurrency: u32,
    ) -> Result<Sequence<I, Vec<B>>> {
        let node = self
            .inner
            .foreach(key, self.last.clone(), body, max_items, max_concurrency)?;
        Ok(Sequence {
            inner: self.inner,
            last: node.output(),
            last_activity: None,
        })
    }
}

impl<I: DurablePayload, Cur: DurablePayload> Workflow<I, Cur> {
    pub fn activity<O: DurablePayload>(
        self,
        key: &str,
        activity: &ActivityRef<Cur, O>,
    ) -> Result<Workflow<I, O>> {
        Ok(Workflow {
            name: self.name,
            seq: self.seq.activity(key, activity)?,
        })
    }

    pub fn compensate<U: DurablePayload>(self, activity: &ActivityRef<Cur, U>) -> Result<Self> {
        Ok(Workflow {
            name: self.name,
            seq: self.seq.compensate(activity)?,
        })
    }

    pub fn wait_signal<T: DurablePayload>(
        self,
        key: &str,
        signal: &SignalRef<T>,
        correlation: &str,
    ) -> Result<Workflow<I, T>> {
        Ok(Workflow {
            name: self.name,
            seq: self.seq.wait_signal(key, signal, correlation)?,
        })
    }

    pub fn while_lt(
        self,
        key: &str,
        path: &str,
        value: i64,
        body: Region<Cur, Cur>,
        max_iterations: u32,
    ) -> Result<Self> {
        Ok(Workflow {
            name: self.name,
            seq: self.seq.while_lt(key, path, value, body, max_iterations)?,
        })
    }

    pub fn repeat(
        self,
        key: &str,
        count: i64,
        body: Region<Cur, Cur>,
        max_iterations: u32,
    ) -> Result<Self> {
        Ok(Workflow {
            name: self.name,
            seq: self.seq.repeat(key, count, body, max_iterations)?,
        })
    }

    pub fn saga<B: DurablePayload>(
        self,
        key: &str,
        body: Region<Cur, B>,
    ) -> Result<Workflow<I, B>> {
        Ok(Workflow {
            name: self.name,
            seq: self.seq.saga(key, body)?,
        })
    }

    pub fn choose(self, key: impl Into<String>) -> Choose<I, Cur, Cur> {
        let mut choose = self.seq.choose(key);
        choose.name = Some(self.name);
        choose
    }

    pub fn parallel(self, key: impl Into<String>) -> ParallelStart<I, Cur> {
        let mut parallel = self.seq.parallel(key);
        parallel.name = Some(self.name);
        parallel
    }

    /// Complete as node `finish` and compile.
    pub fn finish(self, catalog: &Catalog) -> Result<Definition> {
        let region = self.seq.complete("finish")?;
        WorkflowBuilder::new(self.name, 1, region).build(catalog)
    }
}

impl<I: DurablePayload> Workflow<I, I> {
    pub fn timed_wait<T: DurablePayload>(
        self,
        key: &str,
        signal: &SignalRef<T>,
        correlation: &str,
        timeout: Duration,
    ) -> Result<TimedWaitFlow<I, T>> {
        let mut graph = RegionGraphBuilder::<I>::new();
        let input = graph.workflow_input();
        let corr = graph.literal(correlation.to_owned())?;
        let wait = graph.declare_timed_wait(key, signal, corr, timeout)?;
        Ok(TimedWaitFlow {
            name: self.name,
            graph,
            wait,
            input,
        })
    }
}

impl<I: DurablePayload, A: DurablePayload> Workflow<I, Vec<A>> {
    pub fn foreach<B: DurablePayload>(
        self,
        key: &str,
        body: Region<A, B>,
        max_items: u32,
        max_concurrency: u32,
    ) -> Result<Workflow<I, Vec<B>>> {
        Ok(Workflow {
            name: self.name,
            seq: self.seq.foreach(key, body, max_items, max_concurrency)?,
        })
    }
}

pub struct Choose<I, A, B> {
    name: Option<String>,
    seq: Sequence<I, A>,
    key: String,
    cases: Vec<Case<A, B>>,
}

impl<I: DurablePayload, A: DurablePayload, B: DurablePayload> Choose<I, A, B> {
    pub fn when(
        mut self,
        case: impl Into<String>,
        condition: Condition,
        body: Region<A, B>,
    ) -> Self {
        self.cases.push(Case {
            name: case.into(),
            when: condition,
            body,
        });
        self
    }

    pub fn when_eq(
        self,
        case: impl Into<String>,
        path: &str,
        value: impl Into<Value>,
        body: Region<A, B>,
    ) -> Self {
        self.when(case, Condition::eq_input(path, value.into()), body)
    }

    pub fn when_true(self, case: impl Into<String>, path: &str, body: Region<A, B>) -> Self {
        self.when(case, Condition::flag_true(path), body)
    }

    pub fn otherwise(self, default: Region<A, B>) -> Result<AfterChoose<I, B>> {
        let workflow_name = self.name;
        let mut seq = self.seq;
        let node = seq.inner.choose(&self.key, seq.last, self.cases, default)?;
        let seq = Sequence {
            inner: seq.inner,
            last: node.output(),
            last_activity: None,
        };
        Ok(AfterChoose {
            name: workflow_name,
            seq,
        })
    }
}

pub struct AfterChoose<I, Cur> {
    name: Option<String>,
    seq: Sequence<I, Cur>,
}

impl<I: DurablePayload, Cur: DurablePayload> AfterChoose<I, Cur> {
    pub fn finish_region(self) -> Result<Region<I, Cur>> {
        self.seq.finish()
    }

    pub fn complete(self, key: &str) -> Result<Region<I, Cur>> {
        self.seq.complete(key)
    }

    pub fn finish(self, catalog: &Catalog) -> Result<Definition> {
        let name = self.name.ok_or_else(|| {
            Error::invalid("choose.otherwise().finish(catalog) needs workflow(..)")
        })?;
        let region = self.seq.complete("finish")?;
        WorkflowBuilder::new(name, 1, region).build(catalog)
    }

    pub fn into_sequence(self) -> Sequence<I, Cur> {
        self.seq
    }
}

pub struct ParallelStart<I, Cur> {
    name: Option<String>,
    seq: Sequence<I, Cur>,
    key: String,
}

impl<I: DurablePayload, Cur: DurablePayload> ParallelStart<I, Cur> {
    pub fn branch<A: DurablePayload>(
        self,
        name: impl Into<String>,
        body: Region<Cur, A>,
    ) -> ParallelOne<I, Cur, A> {
        ParallelOne {
            workflow_name: self.name,
            seq: self.seq,
            key: self.key,
            left_name: name.into(),
            left: body,
        }
    }
}

pub struct ParallelOne<I, Cur, A> {
    workflow_name: Option<String>,
    seq: Sequence<I, Cur>,
    key: String,
    left_name: String,
    left: Region<Cur, A>,
}

impl<I: DurablePayload, Cur: DurablePayload, A: DurablePayload> ParallelOne<I, Cur, A> {
    pub fn branch<B: DurablePayload>(
        self,
        name: impl Into<String>,
        body: Region<Cur, B>,
    ) -> Result<AfterParallel<I, (A, B)>> {
        let mut seq = self.seq;
        let input = seq.last.clone();
        let node = seq.inner.parallel2(
            &self.key,
            Branch {
                name: self.left_name,
                input: input.binding().clone(),
                body: self.left,
            },
            Branch {
                name: name.into(),
                input: input.binding().clone(),
                body,
            },
        )?;
        Ok(AfterParallel {
            name: self.workflow_name,
            seq: Sequence {
                inner: seq.inner,
                last: node.output(),
                last_activity: None,
            },
        })
    }
}

pub struct AfterParallel<I, Cur> {
    name: Option<String>,
    seq: Sequence<I, Cur>,
}

impl<I: DurablePayload, Cur: DurablePayload> AfterParallel<I, Cur> {
    pub fn finish(self, catalog: &Catalog) -> Result<Definition> {
        let name = self
            .name
            .ok_or_else(|| Error::invalid("parallel.finish(catalog) needs workflow(..)"))?;
        let region = self.seq.complete("finish")?;
        WorkflowBuilder::new(name, 1, region).build(catalog)
    }
}

pub struct TimedWaitFlow<I, T> {
    name: String,
    graph: RegionGraphBuilder<I>,
    wait: TimedWaitRef<T>,
    input: ValueRef<I>,
}

impl<I: DurablePayload, T: DurablePayload> TimedWaitFlow<I, T> {
    pub fn on_timeout<R: DurablePayload>(
        mut self,
        key: &str,
        activity: &ActivityRef<I, R>,
    ) -> Result<TimedWaitDone<I>> {
        let recover = self
            .graph
            .declare_activity(key, activity, self.input.clone())?;
        let finish = self.graph.declare_complete::<I>("finish", self.input)?;
        self.graph.start_at(self.wait.entry())?;
        self.graph
            .connect(self.wait.success_port(), finish.entry())?;
        self.graph
            .connect(self.wait.timeout_port(), recover.entry())?;
        self.graph.connect(recover.exit(), finish.entry())?;
        Ok(TimedWaitDone {
            name: self.name,
            graph: self.graph,
        })
    }
}

pub struct TimedWaitDone<I> {
    name: String,
    graph: RegionGraphBuilder<I>,
}

impl<I: DurablePayload> TimedWaitDone<I> {
    pub fn finish(self, catalog: &Catalog) -> Result<Definition> {
        let region = self.graph.finish::<I>()?;
        WorkflowBuilder::new(self.name, 1, region).build(catalog)
    }
}