aion-server 0.31.0

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
use aion_proto::WireError;
use axum::{
    Json,
    extract::{Path, State},
    http::StatusCode,
    response::{IntoResponse, Response},
};
use serde::Serialize;

use super::auth::HttpCaller;
use super::authoring::AuthoringHttpError;
use super::error::{HttpWireError, Refusal};
use crate::ServerState;
use crate::awl::{
    self, CheckRequest, CheckResponse, CreateDocumentRequest, CreateDocumentResponse, Diagnostic,
    DocumentEntry, DocumentResponse, EditRequest, EditResponse, FormatRequest, FormatResponse,
    PutDocumentRequest,
};

pub(crate) async fn check(
    State(state): State<ServerState>,
    HttpCaller(caller): HttpCaller,
    Json(request): Json<CheckRequest>,
) -> Result<Json<CheckResponse>, Refusal> {
    require_authenticated(&caller)?;
    let root = workspace(&state).map_err(Refusal::of)?;
    awl::check_source_in_workspace(&root, &request)
        .await
        .map(Json)
        .map_err(|error| Refusal::of(DocumentHttpError(error)))
}

/// `POST /awl/doc` — the documentation model of a workspace document.
///
/// The workspace half of the one model: `GET /awl/deployed/{type}/{hash}/doc`
/// answers for a deployed revision, this answers for a buffer an author is
/// editing, and `aion awl doc` prints the same thing from a file. Three
/// callers, one derivation.
pub(crate) async fn doc(
    State(state): State<ServerState>,
    HttpCaller(caller): HttpCaller,
    Json(request): Json<CheckRequest>,
) -> Result<Json<awl::DocResponse>, Refusal> {
    require_authenticated(&caller)?;
    let root = workspace(&state).map_err(Refusal::of)?;
    awl::doc_source_in_workspace(&root, &request)
        .await
        .map(Json)
        .map_err(|error| Refusal::of(DocumentHttpError(error)))
}

pub(crate) async fn edit(
    HttpCaller(caller): HttpCaller,
    Json(request): Json<EditRequest>,
) -> Result<Json<EditResponse>, Refusal> {
    require_authenticated(&caller)?;
    Ok(Json(awl::edit_source(&request)))
}

pub(crate) async fn scaffold(
    State(state): State<ServerState>,
    HttpCaller(caller): HttpCaller,
    Json(request): Json<awl::scaffold::ScaffoldRequest>,
) -> Result<Json<awl::scaffold::ScaffoldResponse>, Refusal> {
    require_authenticated(&caller)?;
    let root = workspace(&state).map_err(Refusal::of)?;
    let scaffolded = tokio::task::spawn_blocking(move || awl::scaffold::scaffold(&request, &root))
        .await
        .map_err(|error| {
            Refusal::of(DocumentHttpError(awl::documents::DocumentError::Io(
                std::io::Error::other(format!("AWL scaffold task failed: {error}")),
            )))
        })?;
    scaffolded
        .map(Json)
        .map_err(|error| Refusal::of(DocumentHttpError(error)))
}

pub(crate) async fn format(
    HttpCaller(caller): HttpCaller,
    Json(request): Json<FormatRequest>,
) -> Result<Json<FormatResponse>, Refusal> {
    require_authenticated(&caller)?;
    awl::format_source(&request)
        .map(Json)
        .map_err(|diagnostic| Refusal::of(FormatHttpError { diagnostic }))
}

pub(crate) async fn list_documents(
    State(state): State<ServerState>,
    HttpCaller(caller): HttpCaller,
) -> Result<Json<Vec<DocumentEntry>>, Refusal> {
    require_authenticated(&caller)?;
    let root = workspace(&state).map_err(Refusal::of)?;
    awl::documents::list(&root)
        .await
        .map(Json)
        .map_err(|error| Refusal::of(DocumentHttpError(error)))
}

pub(crate) async fn create_document(
    State(state): State<ServerState>,
    HttpCaller(caller): HttpCaller,
    Json(request): Json<CreateDocumentRequest>,
) -> Result<(StatusCode, Json<CreateDocumentResponse>), Refusal> {
    require_mutation(&state, &caller)?;
    let root = workspace(&state).map_err(Refusal::of)?;
    awl::documents::create(&root, request)
        .await
        .map(|response| (StatusCode::CREATED, Json(response)))
        .map_err(|error| Refusal::of(DocumentHttpError(error)))
}

pub(crate) async fn get_document(
    State(state): State<ServerState>,
    HttpCaller(caller): HttpCaller,
    Path(path): Path<String>,
) -> Result<Json<DocumentResponse>, Refusal> {
    require_authenticated(&caller)?;
    let root = workspace(&state).map_err(Refusal::of)?;
    awl::documents::read(&root, &path)
        .await
        .map(Json)
        .map_err(|error| Refusal::of(DocumentHttpError(error)))
}

pub(crate) async fn put_document(
    State(state): State<ServerState>,
    HttpCaller(caller): HttpCaller,
    Path(path): Path<String>,
    Json(request): Json<PutDocumentRequest>,
) -> Result<Json<DocumentResponse>, Refusal> {
    require_mutation(&state, &caller)?;
    let root = workspace(&state).map_err(Refusal::of)?;
    awl::documents::write(&root, &path, request)
        .await
        .map(Json)
        .map_err(|error| Refusal::of(DocumentHttpError(error)))
}

pub(crate) async fn get_layout(
    State(state): State<ServerState>,
    HttpCaller(caller): HttpCaller,
    Path(path): Path<String>,
) -> Result<Json<awl::layout::LayoutRecord>, Refusal> {
    require_authenticated(&caller)?;
    let root = workspace(&state)
        .map_err(|error| Refusal::of(LayoutHttpError::not_configured(&error.0)))?;
    awl::layout::read(&root, &path, caller.subject())
        .await
        .map(Json)
        .map_err(|error| Refusal::of(LayoutHttpError(error)))
}

pub(crate) async fn put_layout(
    State(state): State<ServerState>,
    HttpCaller(caller): HttpCaller,
    Path(path): Path<String>,
    Json(request): Json<awl::layout::LayoutRecord>,
) -> Result<Json<awl::layout::LayoutRecord>, Refusal> {
    require_mutation(&state, &caller)?;
    let root = workspace(&state)
        .map_err(|error| Refusal::of(LayoutHttpError::not_configured(&error.0)))?;
    awl::layout::write(&root, &path, caller.subject(), request)
        .await
        .map(Json)
        .map_err(|error| Refusal::of(LayoutHttpError(error)))
}

pub(crate) async fn emit(
    State(state): State<ServerState>,
    HttpCaller(caller): HttpCaller,
    Json(request): Json<awl::run_loop::EmitRequest>,
) -> Result<Json<awl::run_loop::EmitResponse>, Refusal> {
    awl::run_loop::emit(&state, &caller, &request)
        .map(Json)
        .map_err(|error| Refusal::of(RunLoopHttpError::RunLoop(error)))
}

pub(crate) async fn deploy_authoring(
    State(state): State<ServerState>,
    HttpCaller(caller): HttpCaller,
    Json(request): Json<awl::run_loop::DeployAuthoringRequest>,
) -> Result<Json<awl::run_loop::DeployAuthoringResponse>, Refusal> {
    let root =
        workspace(&state).map_err(|error| Refusal::of(RunLoopHttpError::Document(error.0)))?;
    awl::run_loop::deploy(&state, &caller, &root, "http", request)
        .await
        .map(Json)
        .map_err(|error| Refusal::of(RunLoopHttpError::RunLoop(error)))
}

pub(crate) async fn get_revision(
    State(state): State<ServerState>,
    HttpCaller(caller): HttpCaller,
    Path(hash): Path<String>,
) -> Result<Json<awl::revisions::Revision>, Refusal> {
    require_authenticated(&caller)?;
    let root =
        workspace(&state).map_err(|error| Refusal::of(RunLoopHttpError::Document(error.0)))?;
    awl::revisions::fetch(&root, &hash)
        .await
        .map(Json)
        .map_err(|error| Refusal::of(RunLoopHttpError::RunLoop(error.into())))
}

pub(crate) async fn get_run_status(
    State(state): State<ServerState>,
    HttpCaller(caller): HttpCaller,
    Path(deployment_id): Path<String>,
) -> Result<Json<awl::run_loop::RunStatusResponse>, Refusal> {
    require_authenticated(&caller)?;
    let root =
        workspace(&state).map_err(|error| Refusal::of(RunLoopHttpError::Document(error.0)))?;
    awl::run_loop::status(&root, &deployment_id)
        .await
        .map(Json)
        .map_err(|error| Refusal::of(RunLoopHttpError::RunLoop(error)))
}

pub(crate) async fn bind_run(
    State(state): State<ServerState>,
    HttpCaller(caller): HttpCaller,
    Path(deployment_id): Path<String>,
    Json(request): Json<awl::run_loop::BindRunRequest>,
) -> Result<Json<awl::revisions::DeploymentRecord>, Refusal> {
    require_mutation(&state, &caller)?;
    let root =
        workspace(&state).map_err(|error| Refusal::of(RunLoopHttpError::Document(error.0)))?;
    awl::revisions::bind_run(&root, &deployment_id, request.workflow_id, request.run_id)
        .await
        .map(Json)
        .map_err(|error| Refusal::of(RunLoopHttpError::RunLoop(error.into())))
}

pub(crate) async fn worker_availability(
    State(state): State<ServerState>,
    HttpCaller(caller): HttpCaller,
    Json(request): Json<awl::run_loop::WorkerAvailabilityRequest>,
) -> Result<Json<awl::run_loop::WorkerAvailabilityResponse>, Refusal> {
    require_authenticated(&caller)?;
    state
        .namespace_guard()
        .authorize_namespace(&caller, &request.namespace)
        .map_err(|error| Refusal::of(HttpWireError(error.to_wire_error())))?;
    awl::run_loop::worker_availability(&state, request)
        .map(Json)
        .map_err(|error| Refusal::of(RunLoopHttpError::RunLoop(error)))
}

pub(crate) enum RunLoopHttpError {
    Document(awl::documents::DocumentError),
    RunLoop(awl::run_loop::RunLoopError),
}

impl IntoResponse for RunLoopHttpError {
    fn into_response(self) -> Response {
        match self {
            // Both document arms render identically: a deploy that failed on
            // the workspace document (e.g. the path does not exist) is the
            // same refusal, with the same status and error_type, as the
            // document routes' own.
            Self::Document(error) | Self::RunLoop(awl::run_loop::RunLoopError::Document(error)) => {
                DocumentHttpError(error).into_response()
            }
            Self::RunLoop(awl::run_loop::RunLoopError::Authoring(error)) => {
                AuthoringHttpError(error).into_response()
            }
            Self::RunLoop(error) => {
                let status = match error {
                    awl::run_loop::RunLoopError::WorkerRegistry(_) => {
                        StatusCode::INTERNAL_SERVER_ERROR
                    }
                    _ => StatusCode::UNPROCESSABLE_ENTITY,
                };
                (status, Json(awl::run_loop::wire_error(&error))).into_response()
            }
        }
    }
}

pub(super) struct AwlAuthorizationError(WireError);

impl From<AwlAuthorizationError> for Refusal {
    fn from(error: AwlAuthorizationError) -> Self {
        Self::of(HttpWireError(error.0))
    }
}

pub(super) fn require_authenticated(
    caller: &crate::CallerIdentity,
) -> Result<(), AwlAuthorizationError> {
    if let Some(reason) = caller.denial_reason() {
        return Err(AwlAuthorizationError(WireError::namespace_denied(format!(
            "AWL studio requires an authenticated caller: {reason}"
        ))));
    }
    Ok(())
}

fn require_mutation(
    state: &ServerState,
    caller: &crate::CallerIdentity,
) -> Result<(), AwlAuthorizationError> {
    state
        .deploy_guard()
        .authorize(caller)
        .map_err(|error| AwlAuthorizationError(error.to_wire_error()))
}

/// Thin HTTP shell over the one shared workspace derivation
/// ([`awl::workspace::workspace_root`]); this adds only the HTTP error wrapper.
pub(super) fn workspace(state: &ServerState) -> Result<std::path::PathBuf, DocumentHttpError> {
    awl::workspace::workspace_root(state).map_err(DocumentHttpError)
}

pub(crate) struct FormatHttpError {
    diagnostic: Diagnostic,
}

#[derive(Serialize)]
struct DiagnosticsBody {
    diagnostics: Vec<Diagnostic>,
}

impl IntoResponse for FormatHttpError {
    fn into_response(self) -> Response {
        (
            StatusCode::UNPROCESSABLE_ENTITY,
            Json(DiagnosticsBody {
                diagnostics: vec![self.diagnostic],
            }),
        )
            .into_response()
    }
}

pub(crate) struct LayoutHttpError(pub(crate) awl::layout::LayoutError);

impl LayoutHttpError {
    fn not_configured(error: &awl::documents::DocumentError) -> Self {
        Self(awl::layout::LayoutError::DocumentNotFound(
            error.to_string(),
        ))
    }
}

impl IntoResponse for LayoutHttpError {
    fn into_response(self) -> Response {
        let (status, error_type, message) = match self.0 {
            awl::layout::LayoutError::InvalidPath(message) => {
                (StatusCode::BAD_REQUEST, "InvalidLayoutPath", message)
            }
            awl::layout::LayoutError::DocumentNotFound(message) => {
                (StatusCode::NOT_FOUND, "DocumentNotFound", message)
            }
            awl::layout::LayoutError::Io(error) => (
                StatusCode::INTERNAL_SERVER_ERROR,
                "LayoutIoError",
                error.to_string(),
            ),
        };
        (
            status,
            Json(WireError::invalid_input(message).with_error_type(error_type)),
        )
            .into_response()
    }
}

pub(crate) struct DocumentHttpError(pub(crate) awl::documents::DocumentError);

impl IntoResponse for DocumentHttpError {
    fn into_response(self) -> Response {
        let status = match self.0 {
            awl::documents::DocumentError::InvalidPath(_)
            | awl::documents::DocumentError::InvalidName(_)
            | awl::documents::DocumentError::Unparseable(_) => StatusCode::BAD_REQUEST,
            awl::documents::DocumentError::NotFound(_) => StatusCode::NOT_FOUND,
            awl::documents::DocumentError::Exists(_) => StatusCode::CONFLICT,
            awl::documents::DocumentError::WorkspaceUnconfigured => StatusCode::SERVICE_UNAVAILABLE,
            // `CreateRollbackFailed` deliberately keeps its own error type
            // rather than folding into a generic I/O failure: the workspace
            // has been left holding a document that was never successfully
            // created, so every retry of this create will come back as
            // `DocumentExists`, and the message names the file that has to be
            // removed by hand.
            awl::documents::DocumentError::Io(_)
            | awl::documents::DocumentError::CreateRollbackFailed { .. } => {
                StatusCode::INTERNAL_SERVER_ERROR
            }
        };
        let error_type = self.0.error_type();
        let message = match self.0 {
            awl::documents::DocumentError::InvalidPath(message)
            | awl::documents::DocumentError::InvalidName(message)
            | awl::documents::DocumentError::Unparseable(message)
            | awl::documents::DocumentError::NotFound(message)
            | awl::documents::DocumentError::Exists(message) => message,
            // The I/O body renders the inner error ALONE — no "AWL workspace
            // I/O failed" prefix — exactly as it did before `error_type` was
            // shared; `DocumentIoError` already classifies it.
            awl::documents::DocumentError::Io(error) => error.to_string(),
            error => error.to_string(),
        };
        (
            status,
            Json(WireError::invalid_input(message).with_error_type(error_type)),
        )
            .into_response()
    }
}

#[cfg(test)]
mod tests {
    use axum::response::IntoResponse;

    use super::DocumentHttpError;
    use crate::awl::documents::DocumentError;

    /// Pins the pre-refactor rendering of an I/O failure: the body's message
    /// is the inner error ALONE. The `Display` of `DocumentError::Io`
    /// prepends "AWL workspace I/O failed: ", and a fallthrough that rendered
    /// `Display` silently changed every I/O body once already — this stops
    /// the next refactor doing it again.
    #[tokio::test]
    async fn an_io_error_body_carries_the_inner_message_without_a_prefix()
    -> Result<(), Box<dyn std::error::Error>> {
        let response = DocumentHttpError(DocumentError::Io(std::io::Error::other("disk full")))
            .into_response();
        assert_eq!(
            response.status(),
            axum::http::StatusCode::INTERNAL_SERVER_ERROR
        );
        let bytes = axum::body::to_bytes(response.into_body(), usize::MAX).await?;
        let body: serde_json::Value = serde_json::from_slice(&bytes)?;
        assert_eq!(body["message"], "disk full", "{body}");
        assert_eq!(body["error_type"], "DocumentIoError", "{body}");
        Ok(())
    }
}