alien-commands 3.3.64

Alien Commands protocol implementation
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
use alien_bindings::presigned::PresignedRequest;
use chrono::{DateTime, Utc};

use crate::types::*;

/// Helper functions for creating test data structures
///
/// These functions provide convenient builders for creating command types
/// with sensible defaults for testing. They help reduce boilerplate
/// in test code and ensure consistent test data.

/// Create a test command with inline params
pub fn test_inline_params(data: &[u8]) -> BodySpec {
    BodySpec::inline(data)
}

/// Create a test command with inline JSON params
pub fn test_json_params(json: &serde_json::Value) -> BodySpec {
    let bytes = serde_json::to_vec(json).expect("Valid JSON");
    BodySpec::inline(&bytes)
}

/// Create a test command with storage params
pub fn test_storage_params(size: u64) -> BodySpec {
    BodySpec::storage(size)
}

/// Create test response handling configuration
pub fn test_response_handling(command_id: &str) -> ResponseHandling {
    ResponseHandling {
        max_inline_bytes: crate::INLINE_MAX_BYTES as u64,
        submit_response_url: format!(
            "https://commands.test.example.com/v1/commands/{}/response",
            command_id
        ),
        storage_upload_request: PresignedRequest::new_http(
            format!(
                "https://storage.test.example.com/commands/{}/response",
                command_id
            ),
            "PUT".to_string(),
            std::collections::HashMap::new(),
            alien_bindings::presigned::PresignedOperation::Put,
            format!("commands/{}/response", command_id),
            Utc::now() + chrono::Duration::hours(1),
        ),
    }
}

/// Create a test command envelope
pub fn test_envelope(command_id: &str, command: &str, params: BodySpec) -> Envelope {
    test_envelope_for_agent("test-agent", command_id, command, params)
}

/// Create a test command envelope for a specific deployment
pub fn test_envelope_for_agent(
    deployment_id: &str,
    command_id: &str,
    command: &str,
    params: BodySpec,
) -> Envelope {
    Envelope::new(
        deployment_id,
        // Matches the default target auto-registered by `TestCommandServer`.
        CommandTarget::new("test-worker", CommandTargetType::Worker),
        command_id,
        1,
        None,
        command,
        params,
        test_response_handling(command_id),
    )
}

/// Create a simple test envelope with empty params
pub fn test_simple_envelope(command_id: &str, command: &str) -> Envelope {
    test_envelope(command_id, command, BodySpec::inline(b"{}"))
}

/// Create a test envelope with large storage params
pub fn test_large_envelope(command_id: &str, command: &str, size: u64) -> Envelope {
    test_envelope(command_id, command, BodySpec::storage(size))
}

/// Create a test success response
pub fn test_success_response(data: &[u8]) -> CommandResponse {
    CommandResponse::success(data)
}

/// Create a test JSON success response
pub fn test_json_success_response(json: &serde_json::Value) -> CommandResponse {
    CommandResponse::success_json(json).expect("Valid JSON")
}

/// Create a test error response
pub fn test_error_response(code: &str, message: &str) -> CommandResponse {
    CommandResponse::error(code, message)
}

/// Create a test storage success response (for large responses)
pub fn test_storage_success_response(size: u64) -> CommandResponse {
    CommandResponse::success_storage(size)
}

/// Create a test create command request with inline params
pub fn test_inline_create_command(deployment_id: &str, command: &str) -> CreateCommandRequest {
    let (request, _) = test_inline_create_command_with_params(deployment_id, command);
    request
}

/// Create a test create command request with inline params and return the raw params data
pub fn test_inline_create_command_with_params(
    deployment_id: &str,
    command: &str,
) -> (CreateCommandRequest, Vec<u8>) {
    // Create a small but meaningful params body (under 150KB inline limit)
    let test_params = serde_json::json!({
        "testData": "This is test command params for validation",
        "timestamp": chrono::Utc::now().to_rfc3339(),
        "metadata": {
            "testType": "inline-params",
            "size": "small"
        },
        "items": (0..100).map(|i| format!("item-{}", i)).collect::<Vec<_>>()
    });

    let params_bytes = serde_json::to_vec(&test_params).expect("Valid JSON serialization");

    let request = CreateCommandRequest {
        deployment_id: deployment_id.to_string(),
        command: command.to_string(),
        params: BodySpec::inline(&params_bytes),
        deadline: None,
        idempotency_key: None,
        target_resource_id: None,
        operation_result_contract: None,
    };

    (request, params_bytes)
}

/// Create a test create command request with storage params
pub fn test_storage_create_command(
    deployment_id: &str,
    command: &str,
    size: usize,
) -> CreateCommandRequest {
    CreateCommandRequest {
        deployment_id: deployment_id.to_string(),
        command: command.to_string(),
        params: BodySpec::storage(size as u64),
        deadline: None,
        idempotency_key: None,
        target_resource_id: None,
        operation_result_contract: None,
    }
}

/// Create a test create command request
pub fn test_create_command(
    deployment_id: &str,
    command: &str,
    params: BodySpec,
) -> CreateCommandRequest {
    CreateCommandRequest {
        deployment_id: deployment_id.to_string(),
        command: command.to_string(),
        params,
        deadline: None,
        idempotency_key: None,
        target_resource_id: None,
        operation_result_contract: None,
    }
}

/// Create a test create command request with deadline
pub fn test_create_command_with_deadline(
    deployment_id: &str,
    command: &str,
    params: BodySpec,
    deadline: DateTime<Utc>,
) -> CreateCommandRequest {
    CreateCommandRequest {
        deployment_id: deployment_id.to_string(),
        command: command.to_string(),
        params,
        deadline: Some(deadline),
        idempotency_key: None,
        target_resource_id: None,
        operation_result_contract: None,
    }
}

/// Create a test upload complete request
pub fn test_upload_complete_request(size: u64) -> UploadCompleteRequest {
    UploadCompleteRequest { size }
}

/// Assert that a body is inline and contains expected data
pub fn assert_inline_body(body: &BodySpec, expected: &[u8]) {
    match body {
        BodySpec::Inline { .. } => {
            let decoded = body.decode_inline().expect("Should be decodable");
            assert_eq!(decoded, expected, "Inline body content mismatch");
        }
        _ => panic!("Expected inline body, but got storage body"),
    }
}

/// Assert that a body is storage mode with expected size
pub fn assert_storage_body(body: &BodySpec, expected_size: Option<u64>) {
    match body {
        BodySpec::Storage { size, .. } => {
            if let Some(expected) = expected_size {
                assert_eq!(*size, Some(expected), "Storage body size mismatch");
            }
        }
        _ => panic!("Expected storage body, but got inline body"),
    }
}

/// Assert that a storage body contains the expected content by downloading it
pub async fn assert_storage_body_content(body: &BodySpec, expected_content: &[u8]) {
    match body {
        BodySpec::Storage {
            storage_get_request,
            size,
            ..
        } => {
            assert!(
                storage_get_request.is_some(),
                "Storage body should have storage_get_request"
            );

            let get_request = storage_get_request.as_ref().unwrap();
            let response = get_request
                .execute(None)
                .await
                .expect("Should be able to download storage response");

            assert_eq!(response.status_code, 200, "Storage download should succeed");

            let actual_content = response.body.expect("Storage response should have body");
            assert_eq!(
                actual_content.as_ref(),
                expected_content,
                "Storage content should match expected"
            );

            if let Some(expected_size) = size {
                assert_eq!(
                    *expected_size,
                    expected_content.len() as u64,
                    "Size should match content length"
                );
            }
        }
        _ => panic!("Expected storage body, but got inline body"),
    }
}

/// Assert that an envelope has the expected command ID
pub fn assert_envelope_command_id(envelope: &Envelope, expected_command_id: &str) {
    assert_eq!(
        envelope.command_id, expected_command_id,
        "Envelope command ID mismatch"
    );
}

/// Assert that an envelope has the expected command name
pub fn assert_envelope_command(envelope: &Envelope, expected_command: &str) {
    assert_eq!(
        envelope.command, expected_command,
        "Envelope command name mismatch"
    );
}

/// Assert that a command response is a success
pub fn assert_success_response(response: &CommandResponse) {
    assert!(
        response.is_success(),
        "Expected success response, got error"
    );
}

/// Assert that a command response is an error with expected code
pub fn assert_error_response(response: &CommandResponse, expected_code: &str) {
    match response {
        CommandResponse::Error { code, .. } => {
            assert_eq!(code, expected_code, "Error code mismatch");
        }
        _ => panic!("Expected error response, got success"),
    }
}

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

    #[test]
    fn test_body_spec_handling() {
        // Test inline body creation and validation
        let inline_params = test_inline_params(b"test data");
        assert_eq!(inline_params.mode(), "inline");
        assert_inline_body(&inline_params, b"test data");

        // Test storage body creation and validation
        let storage_params = test_storage_params(1024);
        assert_eq!(storage_params.mode(), "storage");
        assert_storage_body(&storage_params, Some(1024));

        // Test JSON params
        let json_value = serde_json::json!({"test": "value", "number": 42});
        let json_params = test_json_params(&json_value);
        assert_eq!(json_params.mode(), "inline");

        let decoded = json_params.decode_inline().expect("Should decode");
        let parsed: serde_json::Value =
            serde_json::from_slice(&decoded).expect("Should parse JSON");
        assert_eq!(parsed["test"], "value");
        assert_eq!(parsed["number"], 42);
    }

    #[test]
    fn test_response_creation() {
        // Test successful response
        let success = test_success_response(b"result");
        assert!(success.is_success());

        // Test JSON success response
        let json_value = serde_json::json!({"result": "ok", "count": 5});
        let json_success = test_json_success_response(&json_value);
        assert!(json_success.is_success());

        // Test error response
        let error = test_error_response("TEST_ERROR", "Something failed");
        assert!(error.is_error());

        if let CommandResponse::Error { code, message, .. } = error {
            assert_eq!(code, "TEST_ERROR");
            assert_eq!(message, "Something failed");
        }

        // Test storage success response
        let storage_success = test_storage_success_response(50000);
        assert!(storage_success.is_success());
    }

    #[test]
    fn test_envelope_creation() {
        // Test complete envelope creation
        let params = test_json_params(&serde_json::json!({"key": "value"}));
        let envelope = test_envelope("cmd_123", "test-command", params);

        assert_envelope_command_id(&envelope, "cmd_123");
        assert_envelope_command(&envelope, "test-command");

        // Verify response handling configuration
        assert!(envelope
            .response_handling
            .submit_response_url
            .contains("cmd_123"));
        assert_eq!(
            envelope.response_handling.max_inline_bytes,
            crate::INLINE_MAX_BYTES as u64
        );

        // Test simple envelope helper
        let simple_envelope = test_simple_envelope("cmd_simple", "simple-command");
        assert_envelope_command_id(&simple_envelope, "cmd_simple");
        assert_envelope_command(&simple_envelope, "simple-command");

        // Test large envelope helper
        let large_envelope = test_large_envelope("cmd_large", "large-command", 100_000);
        assert_storage_body(&large_envelope.params, Some(100_000));
    }

    #[test]
    fn test_create_command_variations() {
        // Test inline create command
        let create_cmd = test_inline_create_command("agent-1", "process-data");
        assert_eq!(create_cmd.deployment_id, "agent-1");
        assert_eq!(create_cmd.command, "process-data");
        assert!(create_cmd.deadline.is_none());
        assert!(create_cmd.idempotency_key.is_none());
        assert!(matches!(create_cmd.params, BodySpec::Inline { .. }));

        // Test create command with storage params
        let storage_create = test_storage_create_command("agent-2", "upload-file", 2048);
        assert_eq!(storage_create.deployment_id, "agent-2");
        assert_storage_body(&storage_create.params, Some(2048));

        // Test create command with deadline
        let deadline = Utc::now() + chrono::Duration::hours(1);
        let deadline_create = test_create_command_with_deadline(
            "agent-3",
            "time-sensitive",
            BodySpec::inline(b"{}"),
            deadline,
        );
        assert_eq!(deadline_create.deadline, Some(deadline));
    }
}