alien-commands-client 1.10.3

Rust client SDK for invoking commands on Alien deployments
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
use std::time::Duration;

use base64::{engine::general_purpose, Engine as _};
use chrono::{DateTime, Utc};
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use tracing::debug;

use crate::error::CommandError;

/// Configuration for the commands client.
pub struct CommandsClientConfig {
    /// Command timeout (default: 60s)
    pub timeout: Duration,
    /// Polling interval (default: 500ms)
    pub poll_interval: Duration,
    /// Max polling interval (default: 5s)
    pub max_poll_interval: Duration,
    /// Backoff multiplier (default: 1.5)
    pub poll_backoff: f64,
    /// Allow local file:// storage backends (dev only)
    pub allow_local_storage: bool,
}

impl Default for CommandsClientConfig {
    fn default() -> Self {
        Self {
            timeout: Duration::from_secs(60),
            poll_interval: Duration::from_millis(500),
            max_poll_interval: Duration::from_secs(5),
            poll_backoff: 1.5,
            allow_local_storage: false,
        }
    }
}

/// Options for a single invoke call.
pub struct InvokeOptions {
    /// Override the default timeout for this invocation.
    pub timeout: Option<Duration>,
    /// Set a deadline for the command (server-side expiry).
    pub deadline: Option<DateTime<Utc>>,
    /// Idempotency key to prevent duplicate commands.
    pub idempotency_key: Option<String>,
}

/// High-level client for invoking commands on Alien deployments.
pub struct CommandsClient {
    manager_url: String,
    deployment_id: String,
    http_client: reqwest::Client,
    config: CommandsClientConfig,
}

// -- API response types (internal) --

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct CreateCommandResponse {
    command_id: String,
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct CommandStatusResponse {
    state: String,
    #[serde(default)]
    response: Option<CommandResponseBody>,
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct CommandResponseBody {
    #[serde(default)]
    response: Option<BodySpecResponse>,
    #[serde(default)]
    code: Option<String>,
    #[serde(default)]
    message: Option<String>,
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct BodySpecResponse {
    mode: String,
    #[serde(default)]
    inline_base64: Option<String>,
    #[serde(default)]
    storage_get_request: Option<StorageGetRequest>,
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct StorageGetRequest {
    backend: StorageBackend,
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct StorageBackend {
    #[serde(rename = "type")]
    backend_type: String,
    #[serde(default)]
    url: Option<String>,
    #[serde(default)]
    method: Option<String>,
    #[serde(default)]
    headers: Option<std::collections::HashMap<String, String>>,
    #[serde(default, rename = "filePath")]
    file_path: Option<String>,
}

impl CommandsClient {
    /// Create a new commands client with default config.
    pub fn new(manager_url: &str, deployment_id: &str, token: &str) -> Self {
        Self::with_config(
            manager_url,
            deployment_id,
            token,
            CommandsClientConfig::default(),
        )
    }

    /// Create a new commands client with custom config.
    pub fn with_config(
        manager_url: &str,
        deployment_id: &str,
        token: &str,
        config: CommandsClientConfig,
    ) -> Self {
        let mut headers = reqwest::header::HeaderMap::new();
        headers.insert(
            reqwest::header::AUTHORIZATION,
            reqwest::header::HeaderValue::from_str(&format!("Bearer {}", token))
                .expect("invalid token"),
        );

        let http_client = reqwest::Client::builder()
            .default_headers(headers)
            .build()
            .expect("failed to build HTTP client");

        Self {
            manager_url: manager_url.trim_end_matches('/').to_string(),
            deployment_id: deployment_id.to_string(),
            http_client,
            config,
        }
    }

    /// Build a client over a caller-supplied HTTP client, reusing the headers
    /// it already carries (the auth header, and the workspace header used in
    /// platform mode). `with_config` builds a token-only client and can't add
    /// those.
    pub fn with_http_client(
        manager_url: &str,
        deployment_id: &str,
        http_client: reqwest::Client,
        config: CommandsClientConfig,
    ) -> Self {
        Self {
            manager_url: manager_url.trim_end_matches('/').to_string(),
            deployment_id: deployment_id.to_string(),
            http_client,
            config,
        }
    }

    /// Invoke a command and wait for the result.
    ///
    /// Sends params inline, polls for completion, and decodes the response.
    pub async fn invoke<P: Serialize, R: DeserializeOwned>(
        &self,
        command: &str,
        params: P,
    ) -> Result<R, CommandError> {
        self.invoke_with_options(command, params, None).await
    }

    /// Invoke a command with options and wait for the result.
    pub async fn invoke_with_options<P: Serialize, R: DeserializeOwned>(
        &self,
        command: &str,
        params: P,
        options: Option<InvokeOptions>,
    ) -> Result<R, CommandError> {
        let timeout = options
            .as_ref()
            .and_then(|o| o.timeout)
            .unwrap_or(self.config.timeout);

        // Step 1: Create the command (always inline — server handles storage)
        let command_id = self.create(command, params, options.as_ref()).await?;

        debug!(command_id = %command_id, command = %command, "Command created, polling for result");

        // Step 2: Poll for completion with exponential backoff
        let start = tokio::time::Instant::now();
        let mut interval = self.config.poll_interval;

        loop {
            if start.elapsed() > timeout {
                return Err(CommandError::Timeout {
                    command_id,
                    last_state: "polling".to_string(),
                });
            }

            tokio::time::sleep(interval).await;

            let status = self.get_status(&command_id).await?;

            match status.state.as_str() {
                "SUCCEEDED" => {
                    return self.decode_response(&command_id, status.response).await;
                }
                "FAILED" => {
                    let (code, message) = status
                        .response
                        .as_ref()
                        .map(|r| {
                            (
                                r.code.clone().unwrap_or_default(),
                                r.message.clone().unwrap_or_default(),
                            )
                        })
                        .unwrap_or_default();
                    return Err(CommandError::DeploymentError {
                        command_id,
                        code,
                        message,
                    });
                }
                "EXPIRED" => {
                    return Err(CommandError::Expired { command_id });
                }
                _ => {
                    // Still in progress — backoff
                    interval = Duration::from_secs_f64(
                        (interval.as_secs_f64() * self.config.poll_backoff)
                            .min(self.config.max_poll_interval.as_secs_f64()),
                    );
                }
            }
        }
    }

    /// Create a command without waiting for the result. Returns the command ID.
    pub async fn create<P: Serialize>(
        &self,
        command: &str,
        params: P,
        options: Option<&InvokeOptions>,
    ) -> Result<String, CommandError> {
        let params_json = serde_json::to_vec(&params)?;
        let params_base64 = general_purpose::STANDARD.encode(&params_json);

        let mut body = serde_json::json!({
            "deploymentId": self.deployment_id,
            "command": command,
            "params": {
                "mode": "inline",
                "inlineBase64": params_base64,
            },
        });

        if let Some(opts) = options {
            if let Some(deadline) = opts.deadline {
                body["deadline"] = serde_json::Value::String(deadline.to_rfc3339());
            }
            if let Some(ref key) = opts.idempotency_key {
                body["idempotencyKey"] = serde_json::Value::String(key.clone());
            }
        }

        let url = format!("{}/commands", self.manager_url);
        let resp = self.http_client.post(&url).json(&body).send().await?;

        if !resp.status().is_success() {
            let status = resp.status().as_u16();
            let body = resp.text().await.unwrap_or_default();
            return Err(CommandError::CreationFailed { status, body });
        }

        let result: CreateCommandResponse = resp.json().await?;
        Ok(result.command_id)
    }

    /// Poll for a command's status.
    async fn get_status(&self, command_id: &str) -> Result<CommandStatusResponse, CommandError> {
        let url = format!("{}/commands/{}", self.manager_url, command_id);
        let resp = self.http_client.get(&url).send().await?;

        if !resp.status().is_success() {
            let status = resp.status().as_u16();
            let body = resp.text().await.unwrap_or_default();
            return Err(CommandError::CreationFailed { status, body });
        }

        Ok(resp.json().await?)
    }

    // -- Internal helpers --

    async fn decode_response<R: DeserializeOwned>(
        &self,
        command_id: &str,
        response: Option<CommandResponseBody>,
    ) -> Result<R, CommandError> {
        let resp = response.ok_or_else(|| CommandError::ResponseDecodingFailed {
            command_id: command_id.to_string(),
            reason: "No response body in SUCCEEDED status".to_string(),
        })?;

        let body = resp
            .response
            .ok_or_else(|| CommandError::ResponseDecodingFailed {
                command_id: command_id.to_string(),
                reason: "No response field in success response".to_string(),
            })?;

        let bytes = match body.mode.as_str() {
            "inline" => {
                let base64_data =
                    body.inline_base64
                        .ok_or_else(|| CommandError::ResponseDecodingFailed {
                            command_id: command_id.to_string(),
                            reason: "Inline response missing inlineBase64 field".to_string(),
                        })?;

                general_purpose::STANDARD
                    .decode(&base64_data)
                    .map_err(|e| CommandError::ResponseDecodingFailed {
                        command_id: command_id.to_string(),
                        reason: format!("Base64 decode failed: {}", e),
                    })?
            }
            "storage" => {
                let get_request = body.storage_get_request.ok_or_else(|| {
                    CommandError::ResponseDecodingFailed {
                        command_id: command_id.to_string(),
                        reason: "Storage response missing storageGetRequest".to_string(),
                    }
                })?;

                self.download_from_storage(&get_request).await?
            }
            other => {
                return Err(CommandError::ResponseDecodingFailed {
                    command_id: command_id.to_string(),
                    reason: format!("Unknown response mode: {}", other),
                })
            }
        };

        serde_json::from_slice(&bytes).map_err(|e| CommandError::ResponseDecodingFailed {
            command_id: command_id.to_string(),
            reason: format!("JSON decode failed: {}", e),
        })
    }

    async fn download_from_storage(
        &self,
        get_request: &StorageGetRequest,
    ) -> Result<Vec<u8>, CommandError> {
        match get_request.backend.backend_type.as_str() {
            "http" => {
                let url = get_request.backend.url.as_deref().ok_or_else(|| {
                    CommandError::StorageOperationFailed {
                        reason: "HTTP storage backend missing url".to_string(),
                    }
                })?;

                let method = get_request.backend.method.as_deref().unwrap_or("GET");

                // Use a plain client (no auth headers — presigned URL carries auth)
                let plain_http = reqwest::Client::new();
                let mut req = match method {
                    "PUT" => plain_http.put(url),
                    "POST" => plain_http.post(url),
                    _ => plain_http.get(url),
                };

                if let Some(headers) = &get_request.backend.headers {
                    for (k, v) in headers {
                        req = req.header(k.as_str(), v.as_str());
                    }
                }

                let resp = req
                    .send()
                    .await
                    .map_err(|e| CommandError::StorageOperationFailed {
                        reason: format!("Storage download failed: {}", e),
                    })?;

                if !resp.status().is_success() {
                    return Err(CommandError::StorageOperationFailed {
                        reason: format!("Storage download returned HTTP {}", resp.status()),
                    });
                }

                resp.bytes().await.map(|b| b.to_vec()).map_err(|e| {
                    CommandError::StorageOperationFailed {
                        reason: format!("Failed to read storage response bytes: {}", e),
                    }
                })
            }
            "local" if self.config.allow_local_storage => {
                let file_path = get_request.backend.file_path.as_deref().ok_or_else(|| {
                    CommandError::StorageOperationFailed {
                        reason: "Local storage backend missing filePath".to_string(),
                    }
                })?;

                let path = std::path::Path::new(file_path);
                if path.is_absolute() || file_path.contains("..") {
                    return Err(CommandError::StorageOperationFailed {
                        reason: "Local storage path traversal detected".to_string(),
                    });
                }

                tokio::fs::read(file_path)
                    .await
                    .map_err(|e| CommandError::StorageOperationFailed {
                        reason: format!("Failed to read local file {}: {}", file_path, e),
                    })
            }
            "local" => Err(CommandError::StorageOperationFailed {
                reason: "Local storage backend not allowed (set allow_local_storage: true)"
                    .to_string(),
            }),
            other => Err(CommandError::StorageOperationFailed {
                reason: format!("Unknown storage backend type: {}", other),
            }),
        }
    }
}