aion-server 0.13.6

Aion workflow server library: HTTP, gRPC, WebSocket, and worker endpoints. Run it with the `aion` binary from the aion-cli crate.
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
558
559
560
561
use std::io;
use std::path::{Component, Path};

use aion_awl::{Span, TypeBody, parse, print, semantic};
use serde::{Deserialize, Serialize};

use crate::filesystem::ConfinedDir;

#[derive(Debug, Deserialize)]
pub struct CheckRequest {
    pub source: String,
    pub path: Option<String>,
}

#[derive(Debug, Serialize)]
pub struct CheckResponse {
    pub ok: bool,
    pub deploys_green: bool,
    pub steps: Option<usize>,
    pub diagnostics: Vec<Diagnostic>,
    pub semantic: Option<SemanticIndex>,
}

#[derive(Debug, Clone, Serialize)]
pub struct Diagnostic {
    pub class: DiagnosticClass,
    pub message: String,
    pub line: usize,
    pub column: usize,
}

#[derive(Debug, Clone, Copy, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum DiagnosticClass {
    Error,
}

#[derive(Debug, Deserialize)]
pub struct FormatRequest {
    pub source: String,
}

#[derive(Debug, Serialize)]
pub struct FormatResponse {
    pub formatted: String,
}

#[derive(Debug, Serialize)]
pub struct SemanticIndex {
    pub entries: Vec<SemanticEntry>,
    pub graph: super::projection::GraphProjection,
    pub studio: super::studio_projection::StudioProjection,
}

#[derive(Debug, Serialize)]
pub struct SemanticEntry {
    pub span: SourceSpan,
    #[serde(rename = "type")]
    pub type_text: Option<String>,
    pub declaration: Option<SemanticDeclaration>,
}

#[derive(Debug, Serialize)]
pub struct SemanticDeclaration {
    pub name: String,
    pub kind: String,
    pub documentation: Option<String>,
    pub span: SourceSpan,
}

#[derive(Debug, Clone, Copy, Serialize)]
pub struct SourceSpan {
    pub start: usize,
    pub end: usize,
    pub line: usize,
    pub column: usize,
}

pub fn check_source(request: &CheckRequest) -> CheckResponse {
    check_source_at(request, None)
}

/// Checks `source` with schema imports resolved against `root`, carrying no
/// workspace document path.
///
/// The deployed-AWL read surface uses this: its schemas come out of the
/// deployed archive and are staged into a directory of their own, so there is
/// a root but deliberately no workspace path — a deployed document is not a
/// workspace document and must never be resolved as one.
pub(crate) fn check_source_at_root(source: &str, root: Option<&Path>) -> CheckResponse {
    check_source_at(
        &CheckRequest {
            source: source.to_owned(),
            path: None,
        },
        root,
    )
}

fn check_source_at(request: &CheckRequest, root: Option<&Path>) -> CheckResponse {
    let document = match parse(&request.source) {
        Ok(document) => document,
        Err(error) => {
            return CheckResponse {
                ok: false,
                deploys_green: false,
                steps: None,
                diagnostics: vec![diagnostic(
                    DiagnosticClass::Error,
                    error.message,
                    error.span,
                )],
                semantic: None,
            };
        }
    };
    let analysis = root.map_or_else(
        || semantic::analyze(&document),
        |root| semantic::analyze_in(&document, root),
    );
    let diagnostics: Vec<_> = analysis
        .diagnostics()
        .iter()
        .map(|error| diagnostic(DiagnosticClass::Error, error.message.clone(), error.span))
        .collect();
    if !diagnostics.is_empty() {
        return CheckResponse {
            ok: false,
            deploys_green: false,
            steps: None,
            diagnostics,
            semantic: None,
        };
    }
    let graph = super::projection::build(&document, analysis.step_kinds());
    let studio = super::studio_projection::build(&document);
    let semantic = SemanticIndex {
        entries: analysis
            .iter()
            .map(|info| SemanticEntry {
                span: info.span.into(),
                type_text: info.ty.clone(),
                declaration: info
                    .declaration
                    .as_ref()
                    .map(|declaration| SemanticDeclaration {
                        name: declaration.name.clone(),
                        kind: declaration.kind.as_str().to_owned(),
                        documentation: declaration.documentation.clone(),
                        span: declaration.span.into(),
                    }),
            })
            .collect(),
        graph,
        studio,
    };
    CheckResponse {
        ok: true,
        deploys_green: diagnostics.is_empty(),
        steps: Some(document.steps.len()),
        diagnostics,
        semantic: Some(semantic),
    }
}

pub async fn check_source_in_workspace(
    workspace_root: &Path,
    request: &CheckRequest,
) -> Result<CheckResponse, super::documents::DocumentError> {
    let Some(requested_path) = request.path.as_deref() else {
        return Ok(check_source(request));
    };
    let workspace_root = workspace_root.to_owned();
    let source = request.source.clone();
    let requested_path = requested_path.to_owned();
    tokio::task::spawn_blocking(move || {
        let Ok(_) = parse(&source) else {
            return Ok(check_source(&CheckRequest {
                source,
                path: Some(requested_path),
            }));
        };
        let (_staging, staged_root) =
            stage_schema_imports(&workspace_root, &requested_path, &source)?;
        Ok(check_source_at(
            &CheckRequest {
                source,
                path: Some(requested_path),
            },
            Some(&staged_root),
        ))
    })
    .await
    .map_err(|error| {
        super::documents::DocumentError::Io(io::Error::other(format!(
            "AWL check task failed: {error}"
        )))
    })?
}

pub(crate) fn stage_schema_imports(
    workspace_root: &Path,
    requested_path: &str,
    source: &str,
) -> Result<(tempfile::TempDir, std::path::PathBuf), super::documents::DocumentError> {
    let document_path = super::documents::document_path(requested_path)?;
    let document = parse(source)
        .map_err(|error| super::documents::DocumentError::InvalidPath(error.message))?;
    // A workspace directory that does not exist yet is a NORMAL state on a
    // fresh server — the default workspace is materialized on first write.
    // No directory means no schema files can exist to import, so the check
    // proceeds against an empty staged root instead of failing with a raw
    // errno (mirrors `documents::list` on the same absence).
    let workspace = match ConfinedDir::open(workspace_root) {
        Ok(workspace) => Some(workspace),
        Err(error) if error.kind() == io::ErrorKind::NotFound => None,
        Err(error) => return Err(super::documents::DocumentError::Io(error)),
    };
    let staging = tempfile::Builder::new().prefix("aion-schema-").tempdir()?;
    let document_parent = document_path.parent().unwrap_or_else(|| Path::new(""));
    let analysis_root = staging.path().join(document_parent);
    std::fs::create_dir_all(&analysis_root)?;
    let Some(workspace) = workspace else {
        return Ok((staging, analysis_root));
    };
    for declaration in &document.types {
        let TypeBody::SchemaImport { path, .. } = &declaration.body else {
            continue;
        };
        let import = Path::new(path);
        if path.is_empty()
            || import
                .components()
                .any(|component| !matches!(component, Component::Normal(_)))
        {
            continue;
        }
        let bytes = match workspace.read(&document_parent.join(import)) {
            Ok(bytes) => bytes,
            Err(error) if error.kind() == io::ErrorKind::NotFound => continue,
            Err(error)
                if matches!(
                    error.kind(),
                    io::ErrorKind::InvalidInput | io::ErrorKind::NotADirectory
                ) || error.raw_os_error() == Some(rustix::io::Errno::LOOP.raw_os_error()) =>
            {
                return Err(super::documents::DocumentError::InvalidPath(format!(
                    "schema import `{path}` contains a link: {error}"
                )));
            }
            Err(error) => return Err(super::documents::DocumentError::Io(error)),
        };
        let staged = analysis_root.join(import);
        if let Some(parent) = staged.parent() {
            std::fs::create_dir_all(parent)?;
        }
        std::fs::write(staged, bytes)?;
    }
    Ok((staging, analysis_root))
}

pub fn format_source(request: &FormatRequest) -> Result<FormatResponse, Diagnostic> {
    parse(&request.source)
        .map(|document| FormatResponse {
            formatted: print(&document),
        })
        .map_err(|error| diagnostic(DiagnosticClass::Error, error.message, error.span))
}

fn diagnostic(class: DiagnosticClass, message: String, span: Span) -> Diagnostic {
    Diagnostic {
        class,
        message,
        line: span.line,
        column: span.column,
    }
}

impl From<Span> for SourceSpan {
    fn from(span: Span) -> Self {
        Self {
            start: span.start,
            end: span.end,
            line: span.line,
            column: span.column,
        }
    }
}

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

    const HAPPY: &str =
        include_str!("../../../aion-awl/tests/fixtures/rev2/dag-fork/valid/after_single.awl");
    const INVALID: &str = include_str!(
        "../../../aion-awl/tests/fixtures/rev2/dag-fork/invalid/unknown_after_target.awl"
    );
    const EMIT_REFUSED: &str = "//! Emitter refusal probe.\nworkflow emit_refused\n  outcome done: type Result, route success\n\ntype Result { value: String }\n\nworker work\n  action make() -> Result\n\nstep finish\n  make() -> result\n  route done(value: result.value)\n  on failure\n    route done(value: \"failed\")\n";

    #[test]
    fn check_happy_path_returns_steps_and_semantics() {
        let response = check_source(&CheckRequest {
            source: HAPPY.to_owned(),
            path: None,
        });
        assert!(response.ok);
        assert!(response.deploys_green);
        assert_eq!(response.steps, Some(2));
        assert!(response.diagnostics.is_empty());
        assert!(
            response
                .semantic
                .is_some_and(|semantic| !semantic.entries.is_empty())
        );
    }

    #[test]
    fn checker_message_surfaces_verbatim() -> Result<(), Box<dyn std::error::Error>> {
        let document = parse(INVALID)?;
        let expected = aion_awl::check(&document)
            .first()
            .ok_or("fixture unexpectedly checks cleanly")?
            .message
            .clone();
        let response = check_source(&CheckRequest {
            source: INVALID.to_owned(),
            path: None,
        });
        assert!(!response.ok);
        assert_eq!(response.diagnostics[0].message, expected);
        assert!(matches!(
            response.diagnostics[0].class,
            DiagnosticClass::Error
        ));
        Ok(())
    }

    #[test]
    fn checker_only_check_does_not_consult_the_legacy_emitter() {
        let response = check_source(&CheckRequest {
            source: EMIT_REFUSED.to_owned(),
            path: None,
        });
        assert!(response.ok, "diagnostics: {:?}", response.diagnostics);
        assert!(response.deploys_green);
        assert!(response.diagnostics.is_empty());
    }

    /// A fresh server's default workspace directory does not exist until the
    /// first write materializes it. A check that names a `path` must still
    /// succeed against that absence — no directory means no schema files to
    /// import, not a raw errno.
    #[tokio::test]
    async fn a_pathed_check_succeeds_when_the_workspace_does_not_exist_yet()
    -> Result<(), Box<dyn std::error::Error>> {
        let parent = crate::test_support::private_tempdir()?;
        let workspace = parent.path().join("never-created");
        assert!(!workspace.exists());
        let response = check_source_in_workspace(
            &workspace,
            &CheckRequest {
                source: HAPPY.to_owned(),
                path: Some("drafts/after_single.awl".to_owned()),
            },
        )
        .await?;
        assert!(response.ok, "diagnostics: {:?}", response.diagnostics);
        assert!(response.deploys_green);
        assert!(
            !workspace.exists(),
            "a check must not materialize the workspace"
        );
        Ok(())
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn http_check_confines_document_paths_and_schema_imports()
    -> Result<(), Box<dyn std::error::Error>> {
        use std::os::unix::fs::symlink;

        let workspace = crate::test_support::private_tempdir()?;
        let fixture_dir = Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("../aion-awl/tests/fixtures/rev2/schema-doors/valid");
        let source = std::fs::read_to_string(fixture_dir.join("mixed_doors.awl"))?;
        let schema = std::fs::read(fixture_dir.join("intake.schema.json"))?;
        std::fs::create_dir(workspace.path().join("nested"))?;
        std::fs::write(workspace.path().join("nested/intake.schema.json"), &schema)?;
        std::fs::write(workspace.path().join("intake.schema.json"), &schema)?;

        let valid = check_source_in_workspace(
            workspace.path(),
            &CheckRequest {
                source: source.clone(),
                path: Some("nested/mixed_doors.awl".to_owned()),
            },
        )
        .await?;
        assert!(valid.ok, "confined import failed: {:?}", valid.diagnostics);

        let missing_name = "missing-intake.schema.json";
        std::fs::write(workspace.path().join(missing_name), &schema)?;
        let missing = check_source_in_workspace(
            workspace.path(),
            &CheckRequest {
                source: source.replace("intake.schema.json", missing_name),
                path: Some("nested/mixed_doors.awl".to_owned()),
            },
        )
        .await?;
        let missing_reason = missing
            .diagnostics
            .iter()
            .map(|diagnostic| diagnostic.message.as_str())
            .collect::<Vec<_>>()
            .join("\n");
        assert!(!missing.ok);
        assert!(missing_reason.contains(missing_name));
        assert!(!missing_reason.contains("AWL workspace I/O failed"));

        let outside = workspace.path().parent().ok_or("workspace had no parent")?;
        let absolute_source = source.replace(
            "intake.schema.json",
            &outside.join("outside.schema.json").to_string_lossy(),
        );
        let absolute = check_source_in_workspace(
            workspace.path(),
            &CheckRequest {
                source: absolute_source,
                path: Some("nested/mixed_doors.awl".to_owned()),
            },
        )
        .await?;
        assert!(!absolute.ok);
        assert!(absolute.diagnostics[0].message.contains("relative path"));

        let traversal = check_source_in_workspace(
            workspace.path(),
            &CheckRequest {
                source: source.replace("intake.schema.json", "../outside.schema.json"),
                path: Some("nested/mixed_doors.awl".to_owned()),
            },
        )
        .await?;
        assert!(!traversal.ok);
        assert!(traversal.diagnostics[0].message.contains("no `..`"));

        let absolute_document = check_source_in_workspace(
            workspace.path(),
            &CheckRequest {
                source: source.clone(),
                path: Some("/tmp/mixed_doors.awl".to_owned()),
            },
        )
        .await;
        assert!(matches!(
            absolute_document,
            Err(super::super::documents::DocumentError::InvalidPath(_))
        ));

        let external_schema = outside.join("external.schema.json");
        std::fs::write(&external_schema, b"{\"type\":\"object\"}")?;
        symlink(
            &external_schema,
            workspace.path().join("nested/linked.schema.json"),
        )?;
        let linked = check_source_in_workspace(
            workspace.path(),
            &CheckRequest {
                source: source.replace("intake.schema.json", "linked.schema.json"),
                path: Some("nested/mixed_doors.awl".to_owned()),
            },
        )
        .await;
        let Err(error) = linked else {
            return Err("schema symlink was followed".into());
        };
        assert!(matches!(
            error,
            super::super::documents::DocumentError::InvalidPath(reason)
                if reason.contains("contains a link")
        ));
        Ok(())
    }

    #[test]
    fn format_is_canonical_and_idempotent() -> Result<(), Diagnostic> {
        let once = format_source(&FormatRequest {
            source: HAPPY.replace("type Summary  {", "type Summary {"),
        })?;
        let twice = format_source(&FormatRequest {
            source: once.formatted.clone(),
        })?;
        assert_eq!(once.formatted, twice.formatted);
        assert_eq!(once.formatted, HAPPY);
        Ok(())
    }

    #[test]
    fn every_valid_fixture_projects_without_mutating_source()
    -> Result<(), Box<dyn std::error::Error>> {
        let fixtures = Path::new(env!("CARGO_MANIFEST_DIR")).join("../aion-awl/tests/fixtures");
        let mut paths = Vec::new();
        collect_valid_fixtures(&fixtures, &mut paths)?;
        assert!(!paths.is_empty());
        for path in paths {
            let source = std::fs::read_to_string(&path)?;
            let original = source.clone();
            let document = parse(&source)
                .map_err(|error| format!("{} did not parse: {}", path.display(), error.message))?;
            let canonical = print(&document);
            assert_eq!(print(&parse(&canonical)?), canonical, "{}", path.display());
            let response = check_source_at(
                &CheckRequest {
                    source: source.clone(),
                    path: Some(path.to_string_lossy().into_owned()),
                },
                path.parent(),
            );
            assert_eq!(source, original, "projection mutated {}", path.display());
            assert!(
                response.ok,
                "{}: {:?}",
                path.display(),
                response.diagnostics
            );
            let graph = response
                .semantic
                .ok_or("valid fixture had no semantics")?
                .graph;
            assert_eq!(
                graph.steps.len(),
                document.steps.len(),
                "{}",
                path.display()
            );
        }
        Ok(())
    }

    fn collect_valid_fixtures(
        directory: &Path,
        found: &mut Vec<std::path::PathBuf>,
    ) -> std::io::Result<()> {
        for entry in std::fs::read_dir(directory)? {
            let entry = entry?;
            let path = entry.path();
            if path.is_dir() {
                collect_valid_fixtures(&path, found)?;
            } else if path.extension().is_some_and(|extension| extension == "awl")
                && path
                    .components()
                    .any(|component| component.as_os_str() == "valid")
            {
                found.push(path);
            }
        }
        Ok(())
    }
}