alien-commands 1.0.9

Alien Commands protocol implementation
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
use std::sync::Arc;

use axum::{
    extract::{Path, State},
    http::StatusCode,
    response::{IntoResponse, Response},
    routing::{get, post, put},
    Json, Router,
};
use tracing::error;

use alien_error::AlienError;

use crate::{
    error::{Error, ErrorData},
    server::CommandServer,
    types::*,
};

/// Trait to extract CommandServer from any state type
pub trait HasCommandServer {
    fn command_server(&self) -> &Arc<CommandServer>;
}

impl HasCommandServer for Arc<CommandServer> {
    fn command_server(&self) -> &Arc<CommandServer> {
        self
    }
}

/// Create an Axum router with all ARC endpoints using a generic state type
pub fn create_axum_router<S>() -> Router<S>
where
    S: HasCommandServer + Clone + Send + Sync + 'static,
{
    Router::new()
        .route("/commands", post(create_command::<S>))
        .route(
            "/commands/{command_id}/upload-complete",
            post(upload_complete::<S>),
        )
        .route("/commands/{command_id}/response", put(submit_response::<S>))
        .route("/commands/{command_id}", get(get_command_status::<S>))
        .route(
            "/commands/{command_id}/payload",
            get(get_command_payload::<S>).put(store_command_payload::<S>),
        )
        .route("/commands/leases", post(acquire_leases::<S>))
        .route(
            "/commands/leases/{lease_id}/release",
            post(release_lease::<S>),
        )
}

/// Create a new ARC command
#[cfg_attr(feature = "openapi", utoipa::path(
    post,
    path = "/commands",
    request_body = CreateCommandRequest,
    responses(
        (status = 200, description = "Command created successfully", body = CreateCommandResponse),
        (status = 400, description = "Invalid command", body = ErrorResponse),
        (status = 500, description = "Internal server error", body = ErrorResponse),
    ),
    operation_id = "create_command",
    tag = "commands"
))]
async fn create_command<S>(
    State(state): State<S>,
    Json(request): Json<CreateCommandRequest>,
) -> Result<Json<CreateCommandResponse>, ErrorResponse>
where
    S: HasCommandServer,
{
    let response = state.command_server().create_command(request).await?;
    Ok(Json(response))
}

/// Mark upload as complete
#[cfg_attr(feature = "openapi", utoipa::path(
    post,
    path = "/commands/{command_id}/upload-complete",
    params(
        ("command_id" = String, Path, description = "Command identifier")
    ),
    request_body = UploadCompleteRequest,
    responses(
        (status = 200, description = "Upload marked complete", body = UploadCompleteResponse),
        (status = 400, description = "Invalid command or state", body = ErrorResponse),
        (status = 404, description = "Command not found", body = ErrorResponse),
        (status = 500, description = "Internal server error", body = ErrorResponse),
    ),
    operation_id = "upload_complete",
    tag = "commands"
))]
async fn upload_complete<S>(
    State(state): State<S>,
    Path(command_id): Path<String>,
    Json(upload_request): Json<UploadCompleteRequest>,
) -> Result<Json<UploadCompleteResponse>, ErrorResponse>
where
    S: HasCommandServer,
{
    let response = state
        .command_server()
        .upload_complete(&command_id, upload_request)
        .await?;
    Ok(Json(response))
}

/// Get command status
#[cfg_attr(feature = "openapi", utoipa::path(
    get,
    path = "/commands/{command_id}",
    params(
        ("command_id" = String, Path, description = "Command identifier")
    ),
    responses(
        (status = 200, description = "Command status", body = CommandStatusResponse),
        (status = 404, description = "Command not found", body = ErrorResponse),
        (status = 500, description = "Internal server error", body = ErrorResponse),
    ),
    operation_id = "get_command_status",
    tag = "commands"
))]
async fn get_command_status<S>(
    State(state): State<S>,
    Path(command_id): Path<String>,
) -> Result<Json<CommandStatusResponse>, ErrorResponse>
where
    S: HasCommandServer,
{
    let response = state
        .command_server()
        .get_command_status(&command_id)
        .await?;
    Ok(Json(response))
}

/// Payload response containing params and response data from KV
#[derive(Debug, serde::Serialize, serde::Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub struct CommandPayloadResponse {
    pub command_id: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub params: Option<BodySpec>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub response: Option<CommandResponse>,
}

/// Get command payload (params and response) from KV
///
/// Returns the raw params and response data stored in the manager's KV store.
/// Returns 404 if neither params nor response exist for this command.
#[cfg_attr(feature = "openapi", utoipa::path(
    get,
    path = "/commands/{command_id}/payload",
    params(
        ("command_id" = String, Path, description = "Command identifier")
    ),
    responses(
        (status = 200, description = "Command payload data", body = CommandPayloadResponse),
        (status = 404, description = "Command payload not found", body = ErrorResponse),
        (status = 500, description = "Internal server error", body = ErrorResponse),
    ),
    operation_id = "get_command_payload",
    tag = "commands"
))]
async fn get_command_payload<S>(
    State(state): State<S>,
    Path(command_id): Path<String>,
) -> Result<Json<CommandPayloadResponse>, ErrorResponse>
where
    S: HasCommandServer,
{
    let params = state.command_server().get_params(&command_id).await?;
    let response = state.command_server().get_response(&command_id).await?;

    // If neither params nor response exist, the command payload doesn't exist in this AM
    if params.is_none() && response.is_none() {
        return Err(AlienError::new(ErrorData::CommandNotFound {
            command_id: command_id.clone(),
        })
        .into());
    }

    Ok(Json(CommandPayloadResponse {
        command_id,
        params,
        response,
    }))
}

/// Request to store payload data directly in KV by command_id.
///
/// This bypasses the normal command lifecycle (create → dispatch → respond)
/// and writes params/response directly into KV. Used by the demo service
/// to populate payload data for commands created outside the ARC flow.
#[derive(Debug, serde::Serialize, serde::Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub struct StorePayloadRequest {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub params: Option<BodySpec>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub response: Option<CommandResponse>,
}

/// Store command payload data (params and/or response) directly into KV.
///
/// Bypasses the command registry — useful for populating demo data or
/// migrating payload data. Does not validate command existence or state.
#[cfg_attr(feature = "openapi", utoipa::path(
    put,
    path = "/commands/{command_id}/payload",
    params(
        ("command_id" = String, Path, description = "Command identifier")
    ),
    request_body = StorePayloadRequest,
    responses(
        (status = 200, description = "Payload stored successfully"),
        (status = 400, description = "Invalid request", body = ErrorResponse),
        (status = 500, description = "Internal server error", body = ErrorResponse),
    ),
    operation_id = "store_command_payload",
    tag = "commands"
))]
async fn store_command_payload<S>(
    State(state): State<S>,
    Path(command_id): Path<String>,
    Json(request): Json<StorePayloadRequest>,
) -> Result<StatusCode, ErrorResponse>
where
    S: HasCommandServer,
{
    if let Some(params) = &request.params {
        state
            .command_server()
            .store_params(&command_id, params)
            .await?;
    }

    if let Some(response) = &request.response {
        state
            .command_server()
            .store_response(&command_id, response)
            .await?;
    }

    Ok(StatusCode::OK)
}

/// Submit response from deployment
#[cfg_attr(feature = "openapi", utoipa::path(
    put,
    path = "/commands/{command_id}/response",
    params(
        ("command_id" = String, Path, description = "Command identifier")
    ),
    request_body = SubmitResponseRequest,
    responses(
        (status = 200, description = "Response submitted successfully"),
        (status = 400, description = "Invalid command or state", body = ErrorResponse),
        (status = 404, description = "Command not found", body = ErrorResponse),
        (status = 500, description = "Internal server error", body = ErrorResponse),
    ),
    operation_id = "submit_response",
    tag = "deployments"
))]
async fn submit_response<S>(
    State(state): State<S>,
    Path(command_id): Path<String>,
    Json(request): Json<SubmitResponseRequest>,
) -> Result<StatusCode, ErrorResponse>
where
    S: HasCommandServer,
{
    state
        .command_server()
        .submit_command_response(&command_id, request.response)
        .await?;
    Ok(StatusCode::OK)
}

/// Acquire leases for polling deployments
#[cfg_attr(feature = "openapi", utoipa::path(
    post,
    path = "/commands/leases",
    request_body = LeaseRequest,
    responses(
        (status = 200, description = "Leases acquired", body = LeaseResponse),
        (status = 500, description = "Internal server error", body = ErrorResponse),
    ),
    operation_id = "acquire_leases",
    tag = "leases"
))]
async fn acquire_leases<S>(
    State(state): State<S>,
    Json(lease_request): Json<LeaseRequest>,
) -> Result<Json<LeaseResponse>, ErrorResponse>
where
    S: HasCommandServer,
{
    let response = state
        .command_server()
        .acquire_lease(&lease_request.deployment_id, &lease_request)
        .await?;
    Ok(Json(response))
}

/// Release a lease
#[cfg_attr(feature = "openapi", utoipa::path(
    post,
    path = "/commands/leases/{lease_id}/release",
    params(
        ("lease_id" = String, Path, description = "Lease identifier")
    ),
    responses(
        (status = 200, description = "Lease released successfully"),
        (status = 404, description = "Lease not found", body = ErrorResponse),
        (status = 500, description = "Internal server error", body = ErrorResponse),
    ),
    operation_id = "release_lease",
    tag = "leases"
))]
async fn release_lease<S>(
    State(state): State<S>,
    Path(lease_id): Path<String>,
) -> Result<StatusCode, ErrorResponse>
where
    S: HasCommandServer,
{
    state
        .command_server()
        .release_lease_by_id(&lease_id)
        .await?;
    Ok(StatusCode::OK)
}

// Error handling

/// Error response wrapper for API endpoints
#[derive(Debug, serde::Serialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
struct ErrorResponse {
    pub code: String,
    pub message: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub details: Option<String>,
}

impl From<Error> for ErrorResponse {
    fn from(error: Error) -> Self {
        ErrorResponse {
            code: error.code.clone(),
            message: error.message.clone(),
            details: None,
        }
    }
}

impl IntoResponse for ErrorResponse {
    fn into_response(self) -> Response {
        let status = match self.code.as_str() {
            "INVALID_COMMAND" | "INVALID_STATE_TRANSITION" | "INVALID_ENVELOPE" => {
                StatusCode::BAD_REQUEST
            }
            "COMMAND_NOT_FOUND" | "LEASE_NOT_FOUND" => StatusCode::NOT_FOUND,
            "COMMAND_EXPIRED" => StatusCode::GONE,
            "CONFLICT" => StatusCode::CONFLICT,
            "OPERATION_NOT_SUPPORTED" => StatusCode::NOT_IMPLEMENTED,
            "STORAGE_OPERATION_FAILED"
            | "KV_OPERATION_FAILED"
            | "TRANSPORT_DISPATCH_FAILED"
            | "AGENT_ERROR"
            | "ARC_ERROR"
            | "SERIALIZATION_FAILED"
            | "HTTP_OPERATION_FAILED" => StatusCode::INTERNAL_SERVER_ERROR,
            _ => StatusCode::INTERNAL_SERVER_ERROR,
        };

        let body = match serde_json::to_string(&self) {
            Ok(json) => json,
            Err(e) => {
                error!("Failed to serialize error response: {}", e);
                r#"{"code":"ARC_ERROR","message":"Serialization error"}"#.to_string()
            }
        };

        (status, body).into_response()
    }
}

#[cfg(feature = "openapi")]
mod openapi {
    use super::*;
    use utoipa::OpenApi;

    #[derive(OpenApi)]
    #[openapi(
        paths(
            create_command,
            upload_complete,
            get_command_status,
            get_command_payload,
            store_command_payload,
            submit_response,
            acquire_leases,
            release_lease,
        ),
        components(
            schemas(
                CreateCommandRequest,
                CreateCommandResponse,
                UploadCompleteRequest,
                UploadCompleteResponse,
                CommandStatusResponse,
                CommandPayloadResponse,
                StorePayloadRequest,
                SubmitResponseRequest,
                CommandResponse,
                LeaseRequest,
                LeaseResponse,
                ReleaseRequest,
                ErrorResponse,
                // Re-export common types
                BodySpec,
                CommandState,
                StorageUpload,
                ResponseHandling,
                Envelope,
                LeaseInfo,
            )
        ),
        tags(
            (name = "commands", description = "ARC command management"),
            (name = "leases", description = "ARC lease management for polling deployments"),
            (name = "deployments", description = "Deployment response submission")
        ),
        info(
            title = "ARC API",
            description = "Alien Remote Call (ARC) Protocol API",
            version = "1.0.0"
        ),
    )]
    pub struct ApiDoc;
}

#[cfg(feature = "openapi")]
pub use openapi::ApiDoc;