aion-rs 0.2.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
//! cancel/complete/fail transitions

use std::sync::Arc;

use aion_core::{Payload, RunId, WorkflowError, WorkflowId};
use aion_store::EventStore;
use aion_store::visibility::VisibilityStore;
use chrono::Utc;

use crate::EngineError;
use crate::registry::{Registry, TerminalOutcome, WorkflowHandle};
use crate::runtime::RuntimeHandle;

use super::visibility::upsert_workflow_visibility;

/// Dependencies required to drive a workflow to a terminal lifecycle state.
pub struct TerminateWorkflowContext<'a> {
    /// Runtime boundary used to cancel live workflow processes.
    pub runtime: &'a RuntimeHandle,
    /// Durable event store used to rebuild visibility projections.
    pub store: Arc<dyn EventStore>,
    /// Visibility index updated after state-changing workflow events.
    pub visibility_store: Arc<dyn VisibilityStore>,
    /// Active execution registry keyed by workflow/run identifiers.
    pub registry: &'a Registry,
}

/// Completes a live workflow run with its terminal result payload.
///
/// # Errors
///
/// Returns [`EngineError::WorkflowNotFound`] when the `(workflow, run)` pair is
/// not registered. Recorder and registry failures surface as their typed
/// [`EngineError`] variants.
pub async fn complete(
    context: TerminateWorkflowContext<'_>,
    id: &WorkflowId,
    run: &RunId,
    result: Payload,
) -> Result<(), EngineError> {
    let handle = registered_handle(context.registry, id, run)?;
    {
        let recorder = handle.recorder();
        let mut recorder = recorder.lock().await;
        ensure_no_recorded_terminal(&context.store, id, run).await?;
        recorder
            .record_workflow_completed(Utc::now(), result.clone())
            .await?;
    }
    upsert_workflow_visibility(context.store, context.visibility_store, id, run).await?;

    handle
        .completion()
        .notify(TerminalOutcome::Completed(result));
    context.registry.remove(id, run)?;
    Ok(())
}

/// Fails a live workflow run with its terminal workflow error.
///
/// # Errors
///
/// Returns [`EngineError::WorkflowNotFound`] when the `(workflow, run)` pair is
/// not registered. Recorder and registry failures surface as their typed
/// [`EngineError`] variants.
pub async fn fail(
    context: TerminateWorkflowContext<'_>,
    id: &WorkflowId,
    run: &RunId,
    error: WorkflowError,
) -> Result<(), EngineError> {
    let handle = registered_handle(context.registry, id, run)?;
    {
        let recorder = handle.recorder();
        let mut recorder = recorder.lock().await;
        ensure_no_recorded_terminal(&context.store, id, run).await?;
        recorder
            .record_workflow_failed(Utc::now(), error.clone())
            .await?;
    }
    upsert_workflow_visibility(context.store, context.visibility_store, id, run).await?;

    handle.completion().notify(TerminalOutcome::Failed(error));
    context.registry.remove(id, run)?;
    Ok(())
}

/// Cancels a live workflow run, relying on runtime link propagation to tear down
/// any linked activity children.
///
/// # Errors
///
/// Returns [`EngineError::WorkflowNotFound`] when the `(workflow, run)` pair is
/// not registered. Runtime cancellation, recorder, and registry failures surface
/// as their typed [`EngineError`] variants.
pub async fn cancel(
    context: TerminateWorkflowContext<'_>,
    id: &WorkflowId,
    run: &RunId,
    reason: impl Into<String>,
) -> Result<(), EngineError> {
    let handle = registered_handle(context.registry, id, run)?;
    let reason = reason.into();
    // Record the durable cancellation BEFORE killing the process: the exit
    // monitor records WorkflowFailed for any kill it observes without a
    // terminal event already in history.
    {
        let recorder = handle.recorder();
        let mut recorder = recorder.lock().await;
        ensure_no_recorded_terminal(&context.store, id, run).await?;
        recorder
            .record_workflow_cancelled(Utc::now(), reason.clone())
            .await?;
    }
    if let Err(error) = context.runtime.cancel_pid(handle.pid()) {
        // The process exited between the durable cancel record and the kill;
        // its exit monitor reconciles against the recorded cancellation.
        tracing::debug!(
            workflow_id = %id,
            run_id = %run,
            error = %error,
            "workflow process already exited during cancel"
        );
    }
    upsert_workflow_visibility(context.store, context.visibility_store, id, run).await?;

    handle
        .completion()
        .notify(TerminalOutcome::Cancelled(reason));
    context.registry.remove(id, run)?;
    Ok(())
}

/// Rejects a terminal transition when the run already recorded one.
///
/// Must be called while holding the handle's recorder lock: the exit monitor
/// records terminal events through the same recorder, and only the lock makes
/// this check-then-record atomic against it.
async fn ensure_no_recorded_terminal(
    store: &Arc<dyn EventStore>,
    id: &WorkflowId,
    run: &RunId,
) -> Result<(), EngineError> {
    let history = store.read_history(id).await?;
    if super::completion::terminal_outcome_from_history(&history, run).is_some() {
        return Err(EngineError::Runtime {
            reason: format!("workflow {id} run {run} already recorded a terminal event"),
        });
    }
    Ok(())
}

fn registered_handle(
    registry: &Registry,
    id: &WorkflowId,
    run: &RunId,
) -> Result<WorkflowHandle, EngineError> {
    registry
        .get(id, run)?
        .ok_or_else(|| EngineError::WorkflowNotFound {
            workflow_type: format!("{id}/{run}"),
        })
}

#[cfg(test)]
mod tests {
    use std::sync::Arc;

    use aion_core::{Event, Payload, WorkflowStatus};
    use aion_package::ContentHash;
    use aion_store::visibility::VisibilityStore;
    use aion_store::{EventStore, InMemoryStore};
    use serde_json::json;

    use super::{TerminateWorkflowContext, cancel, complete, fail};
    use crate::EngineError;
    use crate::durability::Recorder;
    use crate::registry::{
        CompletionNotifier, HandleResidency, Registry, TerminalOutcome, WorkflowHandle,
        WorkflowHandleParts,
    };
    use crate::runtime::{RuntimeConfig, RuntimeHandle};

    struct ActiveWorkflow {
        store: Arc<dyn EventStore>,
        visibility_store: Arc<dyn VisibilityStore>,
        runtime: RuntimeHandle,
        registry: Registry,
        handle: WorkflowHandle,
    }

    fn payload(label: &str) -> Result<Payload, aion_core::PayloadError> {
        Payload::from_json(&json!({ "label": label }))
    }

    fn workflow_error(message: &str) -> aion_core::WorkflowError {
        aion_core::WorkflowError {
            message: message.to_owned(),
            details: None,
        }
    }

    async fn active_workflow() -> Result<ActiveWorkflow, Box<dyn std::error::Error>> {
        let backing = Arc::new(InMemoryStore::default());
        let store: Arc<dyn EventStore> = Arc::clone(&backing) as Arc<dyn EventStore>;
        let visibility_store: Arc<dyn VisibilityStore> = backing;
        let runtime = RuntimeHandle::new(RuntimeConfig::new(Some(1)))?;
        let registry = Registry::default();
        let workflow_id = aion_core::WorkflowId::new_v4();
        let run_id = aion_core::RunId::new_v4();
        let mut recorder = Recorder::new(workflow_id.clone(), Arc::clone(&store));
        recorder
            .record_workflow_started(
                chrono::Utc::now(),
                crate::durability::WorkflowStartRecord {
                    workflow_type: "checkout".to_owned(),
                    input: payload("input")?,
                    run_id: aion_core::RunId::new(uuid::Uuid::from_u128(1)),
                    parent_run_id: None,
                    package_version: aion_core::PackageVersion::new("a".repeat(64)),
                },
            )
            .await?;
        let pid = runtime.spawn_test_process_with_trap_exit(true)?;
        let completion = CompletionNotifier::new();
        let handle = WorkflowHandle::new(WorkflowHandleParts {
            workflow_id: workflow_id.clone(),
            run_id: run_id.clone(),
            pid,
            workflow_type: "checkout".to_owned(),
            loaded_version: ContentHash::from_bytes([9; 32]),
            cached_status: WorkflowStatus::Running,
            residency: HandleResidency::Resident,
            recorder,
            completion,
        });
        registry.insert((workflow_id, run_id), handle.clone())?;

        Ok(ActiveWorkflow {
            store,
            visibility_store,
            runtime,
            registry,
            handle,
        })
    }

    fn context<'a>(
        runtime: &'a RuntimeHandle,
        store: Arc<dyn EventStore>,
        visibility_store: Arc<dyn VisibilityStore>,
        registry: &'a Registry,
    ) -> TerminateWorkflowContext<'a> {
        TerminateWorkflowContext {
            runtime,
            store,
            visibility_store,
            registry,
        }
    }

    #[tokio::test]
    async fn complete_records_notifies_and_deregisters() -> Result<(), Box<dyn std::error::Error>> {
        let active = active_workflow().await?;
        let result = payload("result")?;
        let mut receiver = active.handle.completion().subscribe();

        complete(
            context(
                &active.runtime,
                active.store.clone(),
                active.visibility_store.clone(),
                &active.registry,
            ),
            active.handle.workflow_id(),
            active.handle.run_id(),
            result.clone(),
        )
        .await?;
        receiver.changed().await?;

        assert_eq!(
            receiver.borrow().clone(),
            Some(TerminalOutcome::Completed(result.clone()))
        );
        assert_eq!(
            active
                .registry
                .get(active.handle.workflow_id(), active.handle.run_id())?,
            None
        );
        let history = active
            .store
            .read_history(active.handle.workflow_id())
            .await?;
        match history.as_slice() {
            [
                Event::WorkflowStarted { .. },
                Event::WorkflowCompleted {
                    envelope,
                    result: recorded,
                },
            ] => {
                assert_eq!(envelope.seq, 2);
                assert_eq!(recorded, &result);
            }
            other => return Err(format!("expected started then completed, found {other:?}").into()),
        }
        active.runtime.shutdown()?;
        Ok(())
    }

    #[tokio::test]
    async fn fail_records_notifies_and_deregisters() -> Result<(), Box<dyn std::error::Error>> {
        let active = active_workflow().await?;
        let error = workflow_error("workflow failed");
        let mut receiver = active.handle.completion().subscribe();

        fail(
            context(
                &active.runtime,
                active.store.clone(),
                active.visibility_store.clone(),
                &active.registry,
            ),
            active.handle.workflow_id(),
            active.handle.run_id(),
            error.clone(),
        )
        .await?;
        receiver.changed().await?;

        assert_eq!(
            receiver.borrow().clone(),
            Some(TerminalOutcome::Failed(error.clone()))
        );
        assert_eq!(
            active
                .registry
                .get(active.handle.workflow_id(), active.handle.run_id())?,
            None
        );
        let history = active
            .store
            .read_history(active.handle.workflow_id())
            .await?;
        match history.as_slice() {
            [
                Event::WorkflowStarted { .. },
                Event::WorkflowFailed {
                    envelope,
                    error: recorded,
                },
            ] => {
                assert_eq!(envelope.seq, 2);
                assert_eq!(recorded, &error);
            }
            other => return Err(format!("expected started then failed, found {other:?}").into()),
        }
        active.runtime.shutdown()?;
        Ok(())
    }

    #[tokio::test]
    async fn cancel_kills_linked_children_records_notifies_and_deregisters()
    -> Result<(), Box<dyn std::error::Error>> {
        let active = active_workflow().await?;
        let child = active
            .runtime
            .spawn_linked_test_process(active.handle.pid())?;
        let reason = String::from("caller requested cancellation");
        let mut receiver = active.handle.completion().subscribe();

        cancel(
            context(
                &active.runtime,
                active.store.clone(),
                active.visibility_store.clone(),
                &active.registry,
            ),
            active.handle.workflow_id(),
            active.handle.run_id(),
            reason.clone(),
        )
        .await?;
        receiver.changed().await?;

        assert!(!active.runtime.is_live(active.handle.pid()));
        assert!(!active.runtime.is_live(child));
        assert_eq!(
            receiver.borrow().clone(),
            Some(TerminalOutcome::Cancelled(reason.clone()))
        );
        assert_eq!(
            active
                .registry
                .get(active.handle.workflow_id(), active.handle.run_id())?,
            None
        );
        let history = active
            .store
            .read_history(active.handle.workflow_id())
            .await?;
        match history.as_slice() {
            [
                Event::WorkflowStarted { .. },
                Event::WorkflowCancelled {
                    envelope,
                    reason: recorded,
                },
            ] => {
                assert_eq!(envelope.seq, 2);
                assert_eq!(recorded, &reason);
            }
            other => return Err(format!("expected started then cancelled, found {other:?}").into()),
        }
        active.runtime.shutdown()?;
        Ok(())
    }

    #[tokio::test]
    async fn cancel_unknown_workflow_returns_not_found() -> Result<(), Box<dyn std::error::Error>> {
        let runtime = RuntimeHandle::new(RuntimeConfig::new(Some(1)))?;
        let registry = Registry::default();
        let workflow_id = aion_core::WorkflowId::new_v4();
        let run_id = aion_core::RunId::new_v4();

        let result = cancel(
            context(
                &runtime,
                Arc::new(InMemoryStore::default()),
                Arc::new(InMemoryStore::default()),
                &registry,
            ),
            &workflow_id,
            &run_id,
            "missing workflow",
        )
        .await;

        assert!(matches!(result, Err(EngineError::WorkflowNotFound { .. })));
        runtime.shutdown()?;
        Ok(())
    }
}