aion-rs 0.4.0

Transport-agnostic Aion workflow engine with durability, replay, timers, and supervision.
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
use std::sync::{
    Arc, Mutex,
    atomic::{AtomicUsize, Ordering},
};

use aion_core::{
    ActivityError, ActivityErrorKind, ActivityId, Event, EventEnvelope, Payload, TimerId,
    WorkflowId,
};
use aion_store::{EventStore, InMemoryStore, ReadableEventStore};
use chrono::{DateTime, TimeZone, Utc};
use serde_json::json;
use uuid::Uuid;

use super::{
    HandoffOutcome, LiveActivityOutcome, LiveChildOutcome, LiveExecutor, resolve_or_execute_live,
};
use crate::durability::{
    Command, CorrelationKey, DurabilityError, HistoryCursor, Recorder, Resolution, Resolver,
};

fn workflow_id() -> WorkflowId {
    WorkflowId::new(Uuid::nil())
}

fn child_workflow_id() -> WorkflowId {
    WorkflowId::new(Uuid::from_u128(1))
}

fn timestamp(offset_seconds: i64) -> Result<DateTime<Utc>, Box<dyn std::error::Error>> {
    Utc.timestamp_opt(offset_seconds, 0)
        .single()
        .ok_or_else(|| "invalid timestamp".into())
}

fn envelope(seq: u64) -> Result<EventEnvelope, Box<dyn std::error::Error>> {
    Ok(EventEnvelope {
        seq,
        recorded_at: timestamp(0)?,
        workflow_id: workflow_id(),
    })
}

fn payload(label: &str) -> Result<Payload, Box<dyn std::error::Error>> {
    Ok(Payload::from_json(&json!({ "label": label }))?)
}

fn activity_scheduled(seq: u64, ordinal: u64) -> Result<Event, Box<dyn std::error::Error>> {
    Ok(Event::ActivityScheduled {
        envelope: envelope(seq)?,
        activity_id: ActivityId::from_sequence_position(ordinal),
        activity_type: "activity".to_owned(),
        input: payload("activity-input")?,
    })
}

fn activity_completed(
    seq: u64,
    ordinal: u64,
    result: Payload,
) -> Result<Event, Box<dyn std::error::Error>> {
    Ok(Event::ActivityCompleted {
        envelope: envelope(seq)?,
        activity_id: ActivityId::from_sequence_position(ordinal),
        result,
    })
}

fn timer_started(seq: u64, timer_id: TimerId) -> Result<Event, Box<dyn std::error::Error>> {
    Ok(Event::TimerStarted {
        envelope: envelope(seq)?,
        timer_id,
        fire_at: timestamp(10)?,
    })
}

fn timer_fired(seq: u64, timer_id: TimerId) -> Result<Event, Box<dyn std::error::Error>> {
    Ok(Event::TimerFired {
        envelope: envelope(seq)?,
        timer_id,
    })
}

fn signal_received(
    seq: u64,
    name: &str,
    payload: Payload,
) -> Result<Event, Box<dyn std::error::Error>> {
    Ok(Event::SignalReceived {
        envelope: envelope(seq)?,
        name: name.to_owned(),
        payload,
    })
}

fn child_started(seq: u64) -> Result<Event, Box<dyn std::error::Error>> {
    Ok(Event::ChildWorkflowStarted {
        envelope: envelope(seq)?,
        child_workflow_id: child_workflow_id(),
        workflow_type: "child".to_owned(),
        input: payload("child-input")?,
        package_version: aion_core::PackageVersion::new("a".repeat(64)),
    })
}

fn child_completed(seq: u64, result: Payload) -> Result<Event, Box<dyn std::error::Error>> {
    Ok(Event::ChildWorkflowCompleted {
        envelope: envelope(seq)?,
        child_workflow_id: child_workflow_id(),
        result,
    })
}

fn run_activity_command(ordinal: u64) -> Result<Command, Box<dyn std::error::Error>> {
    Ok(Command::RunActivity {
        key: CorrelationKey::Activity(ordinal),
        activity_type: "activity".to_owned(),
        input: payload("activity-input")?,
    })
}

fn resolver_for(events: Vec<Event>) -> Result<Resolver, DurabilityError> {
    Ok(Resolver::new(workflow_id(), HistoryCursor::new(events)?))
}

struct FailingExecutor;

#[async_trait::async_trait]
impl LiveExecutor for FailingExecutor {
    async fn run_activity(
        &self,
        activity_type: String,
        input: Payload,
    ) -> Result<LiveActivityOutcome, DurabilityError> {
        Err(DurabilityError::HistoryShape {
            reason: format!(
                "live activity must not run during recorded replay: {activity_type} {input:?}"
            ),
        })
    }

    async fn start_timer(
        &self,
        timer_id: TimerId,
        fire_at: DateTime<Utc>,
    ) -> Result<(), DurabilityError> {
        Err(DurabilityError::HistoryShape {
            reason: format!("live timer must not run during recorded replay: {timer_id} {fire_at}"),
        })
    }

    async fn await_signal(&self, name: String, index: usize) -> Result<Payload, DurabilityError> {
        Err(DurabilityError::HistoryShape {
            reason: format!("live signal must not run during recorded replay: {name} {index}"),
        })
    }

    async fn spawn_child(
        &self,
        workflow_type: String,
        input: Payload,
    ) -> Result<LiveChildOutcome, DurabilityError> {
        Err(DurabilityError::HistoryShape {
            reason: format!(
                "live child must not run during recorded replay: {workflow_type} {input:?}"
            ),
        })
    }
}

struct RecordingExecutor {
    activity_calls: AtomicUsize,
    activity_result: Payload,
    requests: Mutex<Vec<String>>,
}

impl RecordingExecutor {
    fn new(activity_result: Payload) -> Self {
        Self {
            activity_calls: AtomicUsize::new(0),
            activity_result,
            requests: Mutex::new(Vec::new()),
        }
    }

    fn activity_calls(&self) -> usize {
        self.activity_calls.load(Ordering::SeqCst)
    }

    fn record_request(&self, request: String) -> Result<(), DurabilityError> {
        let mut requests = self
            .requests
            .lock()
            .map_err(|error| DurabilityError::HistoryShape {
                reason: format!("recording executor request lock poisoned: {error}"),
            })?;
        requests.push(request);
        Ok(())
    }
}

#[async_trait::async_trait]
impl LiveExecutor for RecordingExecutor {
    async fn run_activity(
        &self,
        activity_type: String,
        input: Payload,
    ) -> Result<LiveActivityOutcome, DurabilityError> {
        self.record_request(format!("activity:{activity_type}:{input:?}"))?;
        self.activity_calls.fetch_add(1, Ordering::SeqCst);
        Ok(LiveActivityOutcome::Completed(self.activity_result.clone()))
    }

    async fn start_timer(
        &self,
        timer_id: TimerId,
        fire_at: DateTime<Utc>,
    ) -> Result<(), DurabilityError> {
        self.record_request(format!("timer:{timer_id}:{fire_at}"))?;
        Ok(())
    }

    async fn await_signal(&self, name: String, index: usize) -> Result<Payload, DurabilityError> {
        self.record_request(format!("signal:{name}:{index}"))?;
        payload("signal-live").map_err(|error| DurabilityError::HistoryShape {
            reason: error.to_string(),
        })
    }

    async fn spawn_child(
        &self,
        workflow_type: String,
        input: Payload,
    ) -> Result<LiveChildOutcome, DurabilityError> {
        self.record_request(format!("child:{workflow_type}:{input:?}"))?;
        Ok(LiveChildOutcome::Completed {
            child_workflow_id: child_workflow_id(),
            result: payload("child-live").map_err(|error| DurabilityError::HistoryShape {
                reason: error.to_string(),
            })?,
            package_version: aion_core::PackageVersion::new("a".repeat(64)),
        })
    }
}

struct RetryableFailureExecutor;

#[async_trait::async_trait]
impl LiveExecutor for RetryableFailureExecutor {
    async fn run_activity(
        &self,
        _activity_type: String,
        _input: Payload,
    ) -> Result<LiveActivityOutcome, DurabilityError> {
        Ok(LiveActivityOutcome::Failed(ActivityError {
            kind: ActivityErrorKind::Retryable,
            message: "retryable live failure must not be recorded as terminal".to_owned(),
            details: None,
        }))
    }

    async fn start_timer(
        &self,
        _timer_id: TimerId,
        _fire_at: DateTime<Utc>,
    ) -> Result<(), DurabilityError> {
        Err(DurabilityError::HistoryShape {
            reason: "retryable failure executor does not support timers".to_owned(),
        })
    }

    async fn await_signal(&self, _name: String, _index: usize) -> Result<Payload, DurabilityError> {
        Err(DurabilityError::HistoryShape {
            reason: "retryable failure executor does not support signals".to_owned(),
        })
    }

    async fn spawn_child(
        &self,
        _workflow_type: String,
        _input: Payload,
    ) -> Result<LiveChildOutcome, DurabilityError> {
        Err(DurabilityError::HistoryShape {
            reason: "retryable failure executor does not support children".to_owned(),
        })
    }
}

#[test]
fn live_executor_is_object_safe() {
    let _: Option<Arc<dyn LiveExecutor>> = None;
}

#[tokio::test]
async fn recorded_history_returns_resolutions_without_live_calls()
-> Result<(), Box<dyn std::error::Error>> {
    let activity_result = payload("activity-result")?;
    let signal_payload = payload("signal-payload")?;
    let child_result = payload("child-result")?;
    let timer_id = TimerId::anonymous(9);
    let mut resolver = resolver_for(vec![
        activity_scheduled(1, 0)?,
        activity_completed(2, 0, activity_result.clone())?,
        timer_started(3, timer_id.clone())?,
        timer_fired(4, timer_id.clone())?,
        signal_received(5, "ready", signal_payload.clone())?,
        child_started(6)?,
        child_completed(7, child_result.clone())?,
    ])?;
    let store: Arc<dyn EventStore> = Arc::new(InMemoryStore::default());
    let mut recorder = Recorder::new(workflow_id(), store);
    let executor = FailingExecutor;

    assert_eq!(
        resolve_or_execute_live(
            &mut resolver,
            &mut recorder,
            &executor,
            run_activity_command(0)?,
            timestamp(20)?,
        )
        .await?,
        HandoffOutcome::Resolved(Resolution::ActivityCompleted(activity_result))
    );
    assert_eq!(
        resolve_or_execute_live(
            &mut resolver,
            &mut recorder,
            &executor,
            Command::StartTimer {
                key: CorrelationKey::Timer(timer_id),
                fire_at: timestamp(10)?,
            },
            timestamp(20)?,
        )
        .await?,
        HandoffOutcome::Resolved(Resolution::TimerFired)
    );
    assert_eq!(
        resolve_or_execute_live(
            &mut resolver,
            &mut recorder,
            &executor,
            Command::AwaitSignal {
                key: CorrelationKey::Signal {
                    name: "ready".to_owned(),
                    index: 0,
                },
            },
            timestamp(20)?,
        )
        .await?,
        HandoffOutcome::Resolved(Resolution::SignalDelivered(signal_payload))
    );
    assert_eq!(
        resolve_or_execute_live(
            &mut resolver,
            &mut recorder,
            &executor,
            Command::SpawnChild {
                // Positional spawn ordinal: the first child of the run, not
                // the recorded ChildWorkflowStarted sequence number.
                key: CorrelationKey::Child(0),
                workflow_type: "child".to_owned(),
                input: payload("child-input")?,
            },
            timestamp(20)?,
        )
        .await?,
        HandoffOutcome::Resolved(Resolution::ChildStarted(child_workflow_id()))
    );
    assert_eq!(
        resolve_or_execute_live(
            &mut resolver,
            &mut recorder,
            &executor,
            Command::AwaitChild {
                child_workflow_id: child_workflow_id(),
            },
            timestamp(20)?,
        )
        .await?,
        HandoffOutcome::Resolved(Resolution::ChildCompleted(child_result))
    );
    Ok(())
}

#[tokio::test]
async fn resume_live_activity_rejects_retryable_failure_without_recording_terminal_outcome()
-> Result<(), Box<dyn std::error::Error>> {
    let store = Arc::new(InMemoryStore::default());
    let workflow_id = workflow_id();
    let store_for_recorder: Arc<dyn EventStore> = store.clone();
    let mut resolver = resolver_for(Vec::new())?;
    let mut recorder = Recorder::new(workflow_id.clone(), store_for_recorder);
    let executor = RetryableFailureExecutor;

    let error = resolve_or_execute_live(
        &mut resolver,
        &mut recorder,
        &executor,
        run_activity_command(0)?,
        timestamp(50)?,
    )
    .await
    .err()
    .ok_or_else(|| "retryable failure was unexpectedly accepted".to_owned())?;

    assert!(matches!(error, DurabilityError::HistoryShape { .. }));
    let history = store.read_history(&workflow_id).await?;
    assert_eq!(history.len(), 2);
    assert!(matches!(history[0], Event::ActivityScheduled { .. }));
    assert!(matches!(history[1], Event::ActivityStarted { .. }));
    assert!(
        history
            .iter()
            .all(|event| !matches!(event, Event::ActivityFailed { .. }))
    );
    Ok(())
}

#[tokio::test]
async fn resume_live_activity_records_result_and_replay_uses_cache()
-> Result<(), Box<dyn std::error::Error>> {
    let store = Arc::new(InMemoryStore::default());
    let store_for_recorder: Arc<dyn EventStore> = store.clone();
    let workflow_id = workflow_id();
    let live_result = payload("live-activity-result")?;
    let executor = RecordingExecutor::new(live_result.clone());
    let mut resolver = resolver_for(Vec::new())?;
    let mut recorder = Recorder::new(workflow_id.clone(), store_for_recorder);

    let outcome = resolve_or_execute_live(
        &mut resolver,
        &mut recorder,
        &executor,
        run_activity_command(0)?,
        timestamp(30)?,
    )
    .await?;

    assert_eq!(executor.activity_calls(), 1);
    assert_eq!(
        outcome,
        HandoffOutcome::Resolved(Resolution::ActivityCompleted(live_result.clone()))
    );
    let history = store.read_history(&workflow_id).await?;
    assert_eq!(history.len(), 3);
    assert!(matches!(history[0], Event::ActivityScheduled { .. }));
    assert!(matches!(history[1], Event::ActivityStarted { .. }));
    match &history[2] {
        Event::ActivityCompleted {
            envelope,
            activity_id,
            result,
        } => {
            assert_eq!(envelope.seq, 3);
            assert_eq!(activity_id.sequence_position(), 0);
            assert_eq!(result, &live_result);
        }
        other => {
            return Err(format!("expected ActivityCompleted, got {other:?}").into());
        }
    }

    let mut replay_resolver = Resolver::new(workflow_id.clone(), HistoryCursor::new(history)?);
    let store_for_replay_recorder: Arc<dyn EventStore> = store.clone();
    let mut replay_recorder = Recorder::resume_at(workflow_id, store_for_replay_recorder, 3);
    let replay_outcome = resolve_or_execute_live(
        &mut replay_resolver,
        &mut replay_recorder,
        &executor,
        run_activity_command(0)?,
        timestamp(40)?,
    )
    .await?;

    assert_eq!(executor.activity_calls(), 1);
    assert_eq!(
        replay_outcome,
        HandoffOutcome::Resolved(Resolution::ActivityCompleted(live_result))
    );
    Ok(())
}