exedev 0.1.0

Official Rust SDK for exe.dev: create VMs, run commands on them, and run every exe.dev command
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
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
// Code generated by "go run ./cmd/gensdkrs" in the exe.dev repository. DO NOT EDIT.

//! Errors. Every error the SDK returns is an [`Error`].
//!
//! Messages never contain the token, the command line, or a command's
//! output: they are safe to log. What may contain secrets (a response body,
//! captured output) is in fields and methods, which you read on purpose.

use std::fmt;
use std::time::Duration;

use serde_json::Value;

use crate::vm::{CommandResult, Vm};

/// The SDK's result type.
pub type Result<T, E = Error> = std::result::Result<T, E>;

/// Everything that can go wrong.
///
/// Match on the variant for what happened, or use the helpers:
/// [`Error::status`], [`Error::is_not_found`], and so on.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
    /// exe.dev refused or failed a request.
    #[error(transparent)]
    Api(#[from] ApiError),
    /// The request failed before a complete response arrived. Whether the
    /// operation took effect is unknown: `new_vm` may have created a VM (give
    /// it a name to find it again).
    #[error("network error during {operation}{}; whether it took effect is unknown", code_suffix(.source))]
    Network {
        /// The command, such as `"new"` or `"share add"`.
        operation: String,
        /// What failed.
        #[source]
        source: reqwest::Error,
    },
    /// The server's response was not what this SDK understands. Perhaps the
    /// server is newer than the SDK, or something between them changed the
    /// response.
    #[error("invalid {operation} response{}", detail.as_ref().map(|d| format!(": {d}")).unwrap_or_default())]
    Protocol {
        /// The command, such as `"new"` or `"ssh"`.
        operation: String,
        /// What was wrong with it, if the SDK knows: such as a missing
        /// field. It never contains the response's values.
        detail: Option<String>,
    },
    /// [`Run::check`](crate::vm::Run::check): the command exited with a
    /// nonzero status.
    #[error(transparent)]
    Command(Box<CommandError>),
    /// A command run on a VM did not report its exit status: see
    /// [`Interrupted`].
    #[error(transparent)]
    Interrupted(Box<Interrupted>),
    /// A VM did not become ready.
    #[error(transparent)]
    VmNotReady(Box<VmNotReady>),
    /// A process started with [`Vm::spawn`] ended without an exit status:
    /// the VM restarted, or something killed the process that was watching it.
    #[error("process {process} on VM {vm} ended without an exit status")]
    ProcessLost {
        /// The process's name.
        process: String,
        /// The VM's name.
        vm: String,
    },
    /// A file or directory on a VM does not exist.
    #[error("no such file or directory on VM {vm}: {path}")]
    FileNotFound {
        /// The VM's name.
        vm: String,
        /// The path, as given.
        path: String,
    },
    /// A path on a VM, which was to be read as a file, is a directory.
    #[error("is a directory on VM {vm}: {path}")]
    IsADirectory {
        /// The VM's name.
        vm: String,
        /// The path, as given.
        path: String,
    },
    /// No process started with [`Vm::spawn`] has this name.
    #[error("no process {process} on VM {vm}")]
    NoSuchProcess {
        /// The process's name.
        process: String,
        /// The VM's name.
        vm: String,
    },
    /// [`Process::wait`](crate::process::Process::wait) with a timeout:
    /// the process is still running.
    #[error("process {process} on VM {vm} is still running")]
    ProcessTimeout {
        /// The process's name.
        process: String,
        /// The VM's name.
        vm: String,
    },
    /// An argument the SDK refused before sending anything.
    #[error("{0}")]
    InvalidArgument(String),
    /// The client could not be set up: no token, or a bad base URL.
    #[error("{0}")]
    Config(String),
    /// A local operation failed: reading or writing a local file, running
    /// `ssh-keygen`, or archiving a directory.
    #[error("{context}: {source}")]
    Io {
        /// What the SDK was doing.
        context: String,
        /// What failed.
        #[source]
        source: std::io::Error,
    },
}

impl Error {
    /// The HTTP status of an [`Error::Api`], or 404 for a VM the server
    /// reported missing.
    pub fn status(&self) -> Option<u16> {
        match self {
            Error::Api(e) => Some(e.status),
            _ => None,
        }
    }

    /// The [`ApiError`], if exe.dev refused or failed the request.
    pub fn api(&self) -> Option<&ApiError> {
        match self {
            Error::Api(e) => Some(e),
            _ => None,
        }
    }

    /// Whether a VM, command, file, or process was not found.
    pub fn is_not_found(&self) -> bool {
        matches!(self, Error::FileNotFound { .. } | Error::NoSuchProcess { .. })
            || self.api().is_some_and(|e| e.kind() == ApiErrorKind::NotFound)
    }

    /// Whether the token may not run this command (403).
    pub fn is_permission_denied(&self) -> bool {
        self.api().is_some_and(|e| e.kind() == ApiErrorKind::PermissionDenied)
    }

    /// Whether a command run on a VM, or a wait, ran out of time.
    pub fn is_timeout(&self) -> bool {
        match self {
            Error::Interrupted(e) => e.kind == InterruptKind::Timeout,
            Error::ProcessTimeout { .. } => true,
            Error::Network { source, .. } => source.is_timeout(),
            _ => false,
        }
    }

    pub(crate) fn protocol(operation: &str) -> Error {
        Error::Protocol {
            operation: operation.to_string(),
            detail: None,
        }
    }

    /// A result that did not decode as its type. The detail names the
    /// problem but not the value, which may be a secret, such as a token.
    pub(crate) fn undecodable(operation: &str, err: &serde_json::Error) -> Error {
        let msg = err.to_string();
        let msg = msg.split(" at line ").next().unwrap_or_default();
        let detail = if let Some(rest) = msg.strip_prefix("invalid type: ") {
            // invalid type: string "VALUE", expected ...
            let kind = rest.split([' ', ',']).next().unwrap_or_default();
            let expected = rest
                .rsplit_once(", expected ")
                .map(|(_, e)| e)
                .unwrap_or("something else");
            format!("invalid type: {kind}, expected {expected}")
        } else if msg.starts_with("missing field ") {
            msg.to_string()
        } else {
            "unexpected shape".to_string()
        };
        Error::Protocol {
            operation: operation.to_string(),
            detail: Some(detail),
        }
    }

    pub(crate) fn invalid(message: impl Into<String>) -> Error {
        Error::InvalidArgument(message.into())
    }

    pub(crate) fn io(context: impl Into<String>, source: std::io::Error) -> Error {
        Error::Io {
            context: context.into(),
            source,
        }
    }
}

fn code_suffix(err: &reqwest::Error) -> String {
    if err.is_timeout() {
        " (timeout)".to_string()
    } else if err.is_connect() {
        " (connect)".to_string()
    } else {
        String::new()
    }
}

/// What kind of failure an [`ApiError`] is.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum ApiErrorKind {
    /// 401: the token is missing, malformed, expired, or revoked.
    Authentication,
    /// 403: the token may not run this command, or not on this VM.
    PermissionDenied,
    /// 404: no such command or VM.
    NotFound,
    /// 429: too many requests, even after the client's retries.
    RateLimited,
    /// [`Vm::run`] on a VM that is not running: it may be paused
    /// ([`Vm::resume`] it) or stopped ([`Vm::restart`] it).
    VmNotRunning,
    /// Anything else.
    Other,
}

/// exe.dev refused or failed a request.
///
/// The message carries the server's reason, shortened to one line; the
/// request and the full response body stay out of it.
#[derive(Debug, Clone)]
pub struct ApiError {
    /// The command that failed, such as `"new"` or `"share add"`.
    pub operation: String,
    /// The HTTP status, or 404 for a VM the server reported missing.
    pub status: u16,
    /// The full response body. It may contain secrets; it does not establish
    /// whether the operation ran.
    pub body: String,
    kind: ApiErrorKind,
    vm: Option<String>,
}

impl ApiError {
    pub(crate) fn new(operation: &str, status: u16, body: String) -> ApiError {
        let kind = match status {
            401 => ApiErrorKind::Authentication,
            403 => ApiErrorKind::PermissionDenied,
            404 => ApiErrorKind::NotFound,
            429 => ApiErrorKind::RateLimited,
            _ => ApiErrorKind::Other,
        };
        ApiError {
            operation: operation.to_string(),
            status,
            body,
            kind,
            vm: None,
        }
    }

    /// The error for an ssh command that did not start. /exec reports a
    /// missing or stopped VM as 422, with a code.
    pub(crate) fn ssh(vm: &str, status: u16, body: String) -> ApiError {
        if status == 422 {
            match error_code(&body).as_deref() {
                Some("vm_not_found") => return ApiError::new("ssh", 404, body),
                Some("vm_not_running") => {
                    let mut e = ApiError::new("ssh", 422, body);
                    e.kind = ApiErrorKind::VmNotRunning;
                    e.vm = Some(vm.to_string());
                    return e;
                }
                _ => {}
            }
        }
        ApiError::new("ssh", status, body)
    }

    /// What kind of failure this is.
    pub fn kind(&self) -> ApiErrorKind {
        self.kind
    }

    /// The server's code for the failure, such as `"vm_unreachable"`, if it
    /// gave one. Act on this, not on the error's wording.
    pub fn code(&self) -> Option<String> {
        error_code(&self.body)
    }
}

impl fmt::Display for ApiError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "exe.dev API error ({}) during {}", self.status, self.operation)?;
        if let Some(vm) = &self.vm {
            return write!(f, ": VM {vm} is not running");
        }
        if let Some(reason) = error_text(&self.body) {
            write!(f, ": {reason}")?;
        }
        Ok(())
    }
}

impl std::error::Error for ApiError {}

/// [`Run::check`](crate::vm::Run::check): the command exited with a nonzero
/// status. The message ends with the last line of its standard error, if any.
#[derive(Debug, Clone)]
pub struct CommandError {
    /// How the command ended, and what it wrote.
    pub result: CommandResult,
}

impl fmt::Display for CommandError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "command exited with status {}", self.result.exit_code)?;
        let stderr = self.result.stderr_lossy();
        if let Some(last) = stderr.lines().rev().find(|l| !l.trim().is_empty()).and_then(one_line) {
            write!(f, ": {last}")?;
        }
        Ok(())
    }
}

impl std::error::Error for CommandError {}

/// Why a command's exit status is unknown.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum InterruptKind {
    /// The connection ended, or the VM did not report the exit status,
    /// before the command finished.
    Disconnected,
    /// The output exceeded [`Run::max_output`](crate::vm::Run::max_output),
    /// so the SDK stopped reading it, which stops the command.
    OutputLimit,
    /// The command did not finish within its timeout, so the SDK closed the
    /// connection, which stops it and every process it started.
    Timeout,
}

/// A command run on a VM did not report its exit status.
///
/// It may have finished, or may still have been running when the
/// connection closed (which stops it, and what it started). Do not blindly
/// retry a command that is not safe to run twice. The output captured before
/// the interruption is here; it is only a prefix.
#[derive(Debug, Clone)]
pub struct Interrupted {
    /// Why.
    pub kind: InterruptKind,
    /// Whether output was captured; see [`Run::capture`](crate::vm::Run::capture).
    pub captured: bool,
    /// Standard output, as far as it arrived.
    pub stdout: Vec<u8>,
    /// Standard error, as far as it arrived.
    pub stderr: Vec<u8>,
    /// The server's explanation, if it sent one. It may contain secrets.
    pub reason: Option<String>,
    /// The timeout, for [`InterruptKind::Timeout`].
    pub timeout: Option<Duration>,
}

impl Interrupted {
    /// Standard output as text; invalid UTF-8 becomes U+FFFD.
    pub fn stdout_lossy(&self) -> String {
        String::from_utf8_lossy(&self.stdout).into_owned()
    }

    /// Standard error as text; invalid UTF-8 becomes U+FFFD.
    pub fn stderr_lossy(&self) -> String {
        String::from_utf8_lossy(&self.stderr).into_owned()
    }
}

impl fmt::Display for Interrupted {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self.kind {
            InterruptKind::Disconnected => "the connection ended before the command's exit status arrived",
            InterruptKind::OutputLimit => "the command's output exceeded max_output",
            InterruptKind::Timeout => "the command did not finish within its timeout",
        })
    }
}

impl std::error::Error for Interrupted {}

/// How a VM's setup script failed.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SetupFailure {
    /// systemd's Result for exe-setup.service, such as `"exit-code"`,
    /// `"signal"`, or `"timeout"`; or `"unsupported"` when the VM's image does
    /// not run setup scripts (only exeuntu and images built on it do), and
    /// `"not-run"` when the script is in place but was not run this boot.
    pub result: String,
    /// The script's exit status, if it exited.
    pub exit_code: Option<i32>,
    /// The signal that killed it, if one did.
    pub signal: Option<i32>,
    /// The end of the script's journal, when it ran. It may contain secrets.
    pub output: String,
}

/// A VM did not become ready.
///
/// [`Client::new_vm`](crate::Client::new_vm) and [`Vm::copy`] delete the VM
/// first, unless told to keep it with `keep_on_failure`.
#[derive(Debug)]
pub struct VmNotReady {
    /// The VM's name.
    pub name: String,
    /// The VM, when it was kept (see `keep_on_failure`), or when waiting with
    /// [`Vm::wait_until_ready`]: inspect it, retry, or delete it.
    pub vm: Option<Vm>,
    /// What went wrong, as in the message.
    pub failure: String,
    /// Set when the setup script failed, or did not run.
    pub setup: Option<SetupFailure>,
    /// What the last attempt ran into.
    pub source: Option<Error>,
}

impl fmt::Display for VmNotReady {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "VM {} {}", self.name, self.failure)
    }
}

impl std::error::Error for VmNotReady {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        self.source.as_ref().map(|e| e as &(dyn std::error::Error + 'static))
    }
}

impl VmNotReady {
    pub(crate) fn setup_failed(name: &str, setup: SetupFailure) -> VmNotReady {
        let failure = if setup.result == "unsupported" {
            "setup script did not run: this VM's image does not run setup scripts".to_string()
        } else if setup.result == "not-run" {
            "setup script did not run".to_string()
        } else if let Some(code) = setup.exit_code {
            format!("setup script failed (exit code {code})")
        } else if let Some(sig) = setup.signal {
            format!("setup script failed (signal {sig})")
        } else {
            format!("setup script failed ({})", setup.result)
        };
        VmNotReady {
            name: name.to_string(),
            vm: None,
            failure,
            setup: Some(setup),
            source: None,
        }
    }
}

/// A response body's JSON documents: one JSON value, or NDJSON. None for
/// other text.
pub(crate) fn parse_documents(body: &str) -> Option<Vec<Value>> {
    let text = body.trim();
    if text.is_empty() {
        return None;
    }
    if let Ok(v) = serde_json::from_str::<Value>(text) {
        return Some(vec![v]);
    }
    text.lines()
        .filter(|l| !l.trim().is_empty())
        .map(serde_json::from_str::<Value>)
        .collect::<std::result::Result<Vec<_>, _>>()
        .ok()
}

/// Whether doc is an error report: an object whose only key is error.
pub(crate) fn is_error_document(doc: &Value) -> bool {
    doc.as_object().is_some_and(|o| o.len() == 1 && o.contains_key("error"))
}

fn error_string(doc: &Value) -> Option<&str> {
    doc.get("error").and_then(Value::as_str)
}

/// The server's first error text, on one line, without control characters,
/// and at most 200 characters.
pub(crate) fn error_text(body: &str) -> Option<String> {
    let docs = parse_documents(body)?;
    let doc = docs
        .iter()
        .find(|d| is_error_document(d))
        .or_else(|| docs.iter().find(|d| error_string(d).is_some()))?;
    one_line(error_string(doc)?)
}

/// The server's code for the failure in body, if it gave one.
pub(crate) fn error_code(body: &str) -> Option<String> {
    let docs = parse_documents(body)?;
    let doc = docs.iter().find(|d| error_string(d).is_some())?;
    doc.get("code").and_then(Value::as_str).map(str::to_string)
}

/// text on one line, without terminal escapes or control characters, and at
/// most 200 characters: server text that reaches a log or a terminal cannot
/// restyle or rewrite it.
pub(crate) fn one_line(text: &str) -> Option<String> {
    let text = strip_escapes(text);
    let mut out = String::new();
    let mut space = false;
    for c in text.chars() {
        if c.is_whitespace() {
            space = true;
            continue;
        }
        if is_control(c) {
            continue;
        }
        if space && !out.is_empty() {
            out.push(' ');
        }
        space = false;
        out.push(c);
    }
    if out.chars().count() > 200 {
        let mut short: String = out.chars().take(199).collect();
        short.push('…');
        return Some(short);
    }
    (!out.is_empty()).then_some(out)
}

fn is_control(c: char) -> bool {
    c.is_control() || matches!(c, '\u{200e}' | '\u{200f}' | '\u{202a}'..='\u{202e}' | '\u{2066}'..='\u{2069}')
}

/// Removes terminal escape sequences: CSI, OSC, and two-byte ESC sequences.
fn strip_escapes(text: &str) -> String {
    let chars: Vec<char> = text.chars().collect();
    let mut out = String::with_capacity(text.len());
    let mut i = 0;
    while i < chars.len() {
        if chars[i] != '\x1b' || i + 1 >= chars.len() {
            out.push(chars[i]);
            i += 1;
            continue;
        }
        match chars[i + 1] {
            '[' => {
                // CSI: parameters 0x30-0x3f, intermediates 0x20-0x2f, a final 0x40-0x7e.
                let mut j = i + 2;
                while j < chars.len() && ('0'..='?').contains(&chars[j]) {
                    j += 1;
                }
                while j < chars.len() && (' '..='/').contains(&chars[j]) {
                    j += 1;
                }
                if j < chars.len() && ('@'..='~').contains(&chars[j]) {
                    i = j + 1;
                } else {
                    out.push(chars[i]);
                    i += 1;
                }
            }
            ']' => {
                // OSC, ended by BEL or ST, or by the end of the text.
                let mut j = i + 2;
                while j < chars.len() && chars[j] != '\x07' && chars[j] != '\x1b' {
                    j += 1;
                }
                if j < chars.len() && chars[j] == '\x07' {
                    j += 1;
                } else if j + 1 < chars.len() && chars[j] == '\x1b' && chars[j + 1] == '\\' {
                    j += 2;
                }
                i = j;
            }
            '@'..='Z' | '\\'..='_' => i += 2,
            _ => {
                out.push(chars[i]);
                i += 1;
            }
        }
    }
    out
}

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

    #[test]
    fn undecodable_results_name_the_problem_not_the_value() {
        #[derive(Debug, serde::Deserialize)]
        #[allow(dead_code)]
        struct Key {
            token: u32,
            label: String,
        }
        let err = serde_json::from_value::<Key>(serde_json::json!({"token": "exe0.secret", "label": "x"})).unwrap_err();
        let msg = Error::undecodable("ssh-key generate-api-key", &err).to_string();
        assert_eq!(
            msg,
            "invalid ssh-key generate-api-key response: invalid type: string, expected u32"
        );
        let err = serde_json::from_value::<Key>(serde_json::json!({"token": 1})).unwrap_err();
        let msg = Error::undecodable("whoami", &err).to_string();
        assert_eq!(msg, "invalid whoami response: missing field `label`");
    }

    #[test]
    fn error_text_is_one_safe_line() {
        let body = r#"{"error": "bad\n\u001b[31mthing\u001b[0m \u202e here"}"#;
        assert_eq!(error_text(body).as_deref(), Some("bad thing here"));
        let long = format!(r#"{{"error": "{}"}}"#, "x".repeat(300));
        assert_eq!(error_text(&long).unwrap().chars().count(), 200);
        assert_eq!(error_text("not json"), None);
        assert_eq!(
            error_text("{\"ok\": 1}\n{\"error\": \"second\"}").as_deref(),
            Some("second")
        );
    }

    #[test]
    fn api_error_kinds() {
        assert_eq!(
            ApiError::new("ls", 403, String::new()).kind(),
            ApiErrorKind::PermissionDenied
        );
        let e = ApiError::ssh(
            "box",
            422,
            r#"{"error": "VM \"box\" not found", "code": "vm_not_found"}"#.into(),
        );
        assert_eq!((e.kind(), e.status), (ApiErrorKind::NotFound, 404));
        let e = ApiError::ssh("box", 422, r#"{"error": "x", "code": "vm_not_running"}"#.into());
        assert_eq!(e.kind(), ApiErrorKind::VmNotRunning);
        assert_eq!(
            e.to_string(),
            "exe.dev API error (422) during ssh: VM box is not running"
        );
        let e = ApiError::new("new", 400, r#"{"error": "no such image"}"#.into());
        assert_eq!(e.to_string(), "exe.dev API error (400) during new: no such image");
    }
}