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
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
// Code generated by "go run ./cmd/gensdkrs" in the exe.dev repository. DO NOT EDIT.

//! VMs: running commands, files, and background processes.

use std::future::IntoFuture;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;

use futures_util::TryStreamExt as _;
use serde_json::Value;
use tokio::time::Instant;

use crate::client::{BoxFuture, SshOptions, Transport, find};
use crate::error::{ApiErrorKind, CommandError, Error, InterruptKind, Result, VmNotReady, error_code};
use crate::process::Process;
use crate::scripts::*;
use crate::types::EgressPolicy;
use crate::wire::{
    self, Command, IS_DIRECTORY, MAX_OUTPUT, MISSING, PARALLEL, PART_SIZE, RUNNING, SetupState, VmInfo, sh,
};

/// What to wait for after creating, copying, or starting a VM.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
pub enum WaitUntil {
    /// Until it runs commands over SSH (by default). Requires ssh
    /// permission.
    #[default]
    Ssh,
    /// Until its setup script (exeuntu's exe-setup.service) has finished,
    /// too. A failed script is [`VmNotReady`] with
    /// [`setup`](VmNotReady::setup) set; so is a script on an image without
    /// that unit (anything not built on exeuntu), which never runs.
    Setup,
    /// Not at all: until exe.dev has created it.
    Created,
}

impl WaitUntil {
    pub(crate) fn timeout(self, timeout: Option<Duration>) -> Result<Duration> {
        match timeout {
            Some(t) if t.is_zero() => Err(Error::invalid("timeout must be positive")),
            Some(t) => Ok(t),
            None if self == WaitUntil::Setup => Ok(Duration::from_secs(600)),
            None => Ok(Duration::from_secs(60)),
        }
    }
}

/// How a command run on a VM ended, and what it wrote.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CommandResult {
    /// Its exit status. A command killed by a signal has 128 plus the
    /// signal's number, as in a shell.
    pub exit_code: i32,
    /// Its standard output, unless [`Run::capture`] was false.
    pub stdout: Vec<u8>,
    /// Its standard error, unless [`Run::capture`] was false.
    pub stderr: Vec<u8>,
    /// Whether output was captured.
    pub captured: bool,
}

impl CommandResult {
    /// Whether the exit status is 0.
    pub fn success(&self) -> bool {
        self.exit_code == 0
    }

    /// 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()
    }

    /// Self, or [`Error::Command`] if the exit status is not 0.
    pub fn check(self) -> Result<CommandResult> {
        if self.success() {
            Ok(self)
        } else {
            Err(Error::Command(Box::new(CommandError { result: self })))
        }
    }
}

/// A VM on exe.dev.
///
/// Get one from [`Client::new_vm`](crate::Client::new_vm),
/// [`Client::vms`](crate::Client::vms), [`Client::vm`](crate::Client::vm),
/// or [`Vm::copy`]. Its attributes are a snapshot: the SDK's own operations
/// keep them current, and [`refresh`](Vm::refresh) fetches the rest. It is
/// cheap to clone; a clone's snapshot is its own.
///
/// Dropping a `Vm` does not delete the VM: [`delete`](Vm::delete) does.
#[derive(Clone)]
pub struct Vm {
    pub(crate) t: Arc<Transport>,
    pub(crate) info: VmInfo,
}

impl std::fmt::Debug for Vm {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Vm")
            .field("name", &self.info.name)
            .field("status", &self.info.status)
            .finish_non_exhaustive()
    }
}

impl Vm {
    pub(crate) fn new(t: Arc<Transport>, info: VmInfo) -> Vm {
        Vm { t, info }
    }

    /// Its name.
    pub fn name(&self) -> &str {
        &self.info.name
    }

    /// Such as `"starting"`, `"running"`, or `"paused"`, when last seen.
    pub fn status(&self) -> &str {
        &self.info.status
    }

    /// The host to reach it at with SSH, such as `"name.exe.xyz"`.
    pub fn ssh_dest(&self) -> &str {
        &self.info.ssh_dest
    }

    /// Its HTTPS URL, which reaches its default port through exe.dev's proxy.
    pub fn https_url(&self) -> &str {
        &self.info.https_url
    }

    /// Its tags.
    pub fn tags(&self) -> &[String] {
        &self.info.tags
    }

    /// Its comment, or "".
    pub fn comment(&self) -> &str {
        &self.info.comment
    }

    /// The region it runs in, such as `"pdx"`, if the server said.
    pub fn region(&self) -> Option<&str> {
        self.info.region.as_deref()
    }

    /// What it may reach on the internet, if the server said, and this SDK
    /// knows the policy.
    pub fn egress(&self) -> Option<EgressPolicy> {
        self.info.egress.clone()
    }

    /// When it was created, as RFC 3339, if the server said (see
    /// [`refresh`](Vm::refresh)).
    pub fn created_at(&self) -> Option<&str> {
        self.info.created_at.as_deref()
    }

    /// Why [`new_vm`](crate::Client::new_vm)'s prompt did not reach Shelley,
    /// when it did not.
    pub fn prompt_error(&self) -> Option<&str> {
        self.info.prompt_error.as_deref()
    }

    /// A URL that reaches the VM through exe.dev's HTTPS proxy.
    ///
    /// Without a port, it reaches the VM's default port (see `share().port()`).
    /// With one, it reaches that port; the proxy serves ports 3000 to 9999.
    /// path must start with `/`. Who may visit depends on how the VM is
    /// shared.
    pub fn url(&self, port: Option<u16>, path: &str) -> Result<String> {
        if port == Some(0) {
            return Err(Error::invalid("port must be from 1 to 65535"));
        }
        if !path.starts_with('/') {
            return Err(Error::invalid("path must start with /"));
        }
        let url = &self.info.https_url;
        let (scheme, rest) = url.split_once("://").ok_or_else(|| Error::protocol("https_url"))?;
        let authority = rest.split(['/', '?', '#']).next().unwrap_or_default();
        let authority = match port {
            None => authority.to_string(),
            Some(port) => {
                let host = match authority.rsplit_once(':') {
                    Some((host, p)) if !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit()) => host,
                    _ => authority,
                };
                format!("{host}:{port}")
            }
        };
        Ok(format!("{scheme}://{authority}{path}"))
    }

    /// Takes the status, comment, tags, and egress policy a command reports
    /// for this VM into the snapshot.
    pub(crate) fn absorb(&mut self, result: &Value) {
        let Some(obj) = result.as_object() else { return };
        if obj.get("vm_name").and_then(Value::as_str) != Some(self.info.name.as_str()) {
            return;
        }
        if let Some(status) = obj.get("status").and_then(Value::as_str) {
            self.info.status = status.to_string();
        }
        if let Some(comment) = obj.get("comment").and_then(Value::as_str) {
            self.info.comment = comment.to_string();
        }
        if let Some(egress) = wire::egress_policy(obj.get("egress_policy")) {
            self.info.egress = Some(egress);
        }
        if let Some(tags) = obj.get("tags").and_then(Value::as_array)
            && let Some(tags) = tags
                .iter()
                .map(|t| t.as_str().map(str::to_string))
                .collect::<Option<Vec<_>>>()
        {
            self.info.tags = tags;
        }
    }

    /// Takes a new name, and the destinations that change with it.
    pub(crate) fn renamed(&mut self, result: &Value) -> Result<()> {
        let get = |key: &str| result.get(key).and_then(Value::as_str).filter(|s| !s.is_empty());
        let (Some(name), Some(ssh_dest), Some(https_url)) = (get("new_name"), get("ssh_dest"), get("https_url")) else {
            return Err(Error::protocol("rename"));
        };
        if !wire::is_vm_name(name) {
            return Err(Error::protocol("rename"));
        }
        self.info.name = name.to_string();
        self.info.ssh_dest = ssh_dest.to_string();
        self.info.https_url = https_url.to_string();
        Ok(())
    }

    /// Runs a command on the VM, once, and returns how it ended.
    ///
    /// A string is a shell command line, which the VM user's login shell
    /// runs as a login shell, so PATH is as in a terminal. An array or
    /// vector of strings is an argument list, which is quoted for you:
    /// `vm.run(["cat", path])`.
    ///
    /// A nonzero exit status is a result, not an error, unless
    /// [`check`](Run::check) is set. Output is captured, up to 8 MiB in all
    /// by default; stream long output with [`on_stdout`](Run::on_stdout)
    /// and [`capture(false)`](Run::capture).
    ///
    /// The future resolves once the command has exited and its output has
    /// closed, so a process left running in the background with stdout or
    /// stderr open keeps it waiting: start those with [`spawn`](Vm::spawn).
    /// Dropping the future closes the connection, which stops the command
    /// and every process it started.
    ///
    /// If the connection breaks first, [`Error::Interrupted`]: whether the
    /// command finished is unknown. A command line too long for one request
    /// is uploaded as a file first. Requires ssh permission.
    ///
    /// ```no_run
    /// # async fn f(vm: &exedev::Vm) -> exedev::Result<()> {
    /// let result = vm.run("make test").cwd("/app").check(true).await?;
    /// println!("{}", result.stdout_lossy());
    /// vm.run("npm ci").on_stdout(|line| println!("{line}")).await?;
    /// # Ok(()) }
    /// ```
    pub fn run(&self, command: impl Into<Command>) -> Run<'_> {
        Run {
            vm: self,
            command: command.into(),
            check: false,
            cwd: None,
            env: Vec::new(),
            options: SshOptions::default(),
        }
    }

    /// line, made into a command by make, or if that does not fit in a
    /// request, make of a command line that runs line from a file uploaded
    /// first.
    async fn fit(&self, line: String, make: impl Fn(&str) -> String) -> Result<String> {
        let command = make(&line);
        if wire::fits(&self.info.name, &command) {
            return Ok(command);
        }
        let path = format!("/tmp/.exedev-command-{}", wire::random_hex(8));
        self.write_file(&path, line.into_bytes()).await?;
        Ok(make(&UPLOADED_COMMAND.replace("{path}", &path)))
    }

    /// Runs one of the SDK's scripts. An exit status other than 0 or those
    /// in ok is [`Error::Command`].
    pub(crate) async fn script(&self, command: &str, max_output: usize, ok: &[i32]) -> Result<CommandResult> {
        let options = SshOptions {
            max_output,
            ..SshOptions::default()
        };
        let result = self.t.ssh(&self.info.name, command, options).await?;
        if result.exit_code != 0 && !ok.contains(&result.exit_code) {
            return Err(Error::Command(Box::new(CommandError { result })));
        }
        Ok(result)
    }

    fn file_error(&self, exit_code: i32, path: &str) -> Result<()> {
        let (vm, path) = (self.info.name.clone(), path.to_string());
        match exit_code {
            MISSING => Err(Error::FileNotFound { vm, path }),
            IS_DIRECTORY => Err(Error::IsADirectory { vm, path }),
            _ => Ok(()),
        }
    }

    /// Writes a file on the VM, replacing it, and making its directory if
    /// need be.
    ///
    /// path is relative to the home directory unless it is absolute.
    /// [`mode`](WriteFile::mode), such as `0o755`, sets its permissions.
    ///
    /// A request carries at most 64 KB, so a large file goes in parts,
    /// several at a time. The VM needs base64, and gzip for a large file.
    /// Requires ssh permission.
    pub fn write_file(&self, path: &str, data: impl Into<Vec<u8>>) -> WriteFile<'_> {
        WriteFile {
            vm: self,
            path: path.to_string(),
            data: data.into(),
            mode: None,
        }
    }

    async fn write(&self, path: &str, data: &[u8], mode: Option<u32>) -> Result<()> {
        let remote = wire::remote_path(path)?;
        let mode = match mode {
            None => String::new(),
            Some(m) if m <= 0o7777 => format!("{m:o}"),
            Some(_) => return Err(Error::invalid("mode must be at most 0o7777")),
        };
        let (packed, gz) = wire::pack(data);
        let encoded = wire::b64(&packed);
        let gz = if gz { "gz" } else { "" };
        let command = sh(WRITE_SCRIPT, &[&remote, &encoded, &mode, gz, ""]);
        if wire::fits(&self.info.name, &command) {
            self.script(&command, MAX_OUTPUT, &[]).await?;
            return Ok(());
        }
        drop(command);
        let parts = format!("/tmp/.exedev-upload-{}", wire::random_hex(8));
        let commands: Vec<String> = encoded
            .as_bytes()
            .chunks(PART_SIZE)
            .enumerate()
            .map(|(i, chunk)| {
                // Base64 is ASCII, so any split is on a character boundary.
                let chunk = std::str::from_utf8(chunk).expect("base64");
                sh(PART_SCRIPT, &[&parts, &format!("{i:06}"), chunk])
            })
            .collect();
        let sent = futures_util::stream::iter(commands.iter().map(Ok))
            .try_for_each_concurrent(PARALLEL, |command| async move {
                self.script(command, MAX_OUTPUT, &[]).await.map(drop)
            })
            .await;
        if let Err(err) = sent {
            let options = SshOptions {
                capture: false,
                timeout: Some(Duration::from_secs(30)),
                ..SshOptions::default()
            };
            let _ = self.t.ssh(&self.info.name, &format!("rm -rf {parts}"), options).await;
            return Err(err);
        }
        self.script(&sh(WRITE_SCRIPT, &[&remote, "", &mode, gz, &parts]), MAX_OUTPUT, &[])
            .await?;
        Ok(())
    }

    /// The contents of a file on the VM; [`Error::FileNotFound`] if there is
    /// none. path is relative to the home directory unless it is absolute.
    /// Requires ssh permission.
    pub async fn read_file(&self, path: &str) -> Result<Vec<u8>> {
        let command = sh(READ_SCRIPT, &[&wire::remote_path(path)?]);
        let result = self.script(&command, usize::MAX, &[MISSING, IS_DIRECTORY]).await?;
        self.file_error(result.exit_code, path)?;
        Ok(result.stdout)
    }

    /// Copies a local file or directory to the VM.
    ///
    /// A file is written to remote, with its permissions. A directory's
    /// contents are copied into remote, which is made if need be;
    /// [`exclude`](Upload::exclude) leaves out files and directories whose
    /// names match any of its patterns, such as `[".git", "target"]`. The VM
    /// needs tar for a directory. Requires ssh permission.
    pub fn upload(&self, local: impl AsRef<Path>, remote: &str) -> Upload<'_> {
        Upload {
            vm: self,
            local: local.as_ref().to_path_buf(),
            remote: remote.to_string(),
            exclude: Vec::new(),
        }
    }

    /// Copies a file or directory from the VM.
    ///
    /// A file is written to local. A directory's contents are copied into
    /// local, which is made if need be; entries that would land outside it,
    /// or that are not files, directories, or links within it, are refused.
    /// A path on the VM that does not exist is [`Error::FileNotFound`]. The
    /// VM needs tar for a directory. Requires ssh permission.
    pub async fn download(&self, remote: &str, local: impl AsRef<Path>) -> Result<()> {
        let command = sh(DOWNLOAD_SCRIPT, &[&wire::remote_path(remote)?]);
        let mut result = self.script(&command, usize::MAX, &[MISSING]).await?;
        self.file_error(result.exit_code, remote)?;
        let local = local.as_ref().to_path_buf();
        let data = std::mem::take(&mut result.stdout);
        match data.first() {
            Some(b'D') => tokio::task::spawn_blocking(move || crate::archive::untar(&data[1..], &local))
                .await
                .map_err(|_| Error::protocol("download"))?,
            Some(b'F') => tokio::fs::write(&local, &data[1..])
                .await
                .map_err(|e| Error::io(format!("writing {}", local.display()), e)),
            _ => Err(Error::protocol("download")),
        }
    }

    /// Starts a command in the background, and returns at once.
    ///
    /// The command runs as [`run`](Vm::run) runs it, but on its own: until
    /// it exits, or is killed, whatever becomes of this program or its
    /// connection. Its output goes to files on the VM; see
    /// [`Process::logs`].
    ///
    /// [`name`](Spawn::name) identifies the process, so that
    /// [`process`](Vm::process) finds it again later, from anywhere; by
    /// default, it is random. It must not be the name of a process still
    /// running. Requires ssh permission, and setsid on the VM.
    pub fn spawn(&self, command: impl Into<Command>) -> Spawn<'_> {
        Spawn {
            vm: self,
            command: command.into(),
            name: None,
            cwd: None,
            env: Vec::new(),
        }
    }

    /// The process that [`spawn`](Vm::spawn) started with this name,
    /// running or not; [`Error::NoSuchProcess`] if there is none. Requires
    /// ssh permission.
    pub async fn process(&self, name: &str) -> Result<Process> {
        let command = sh(STATE_SCRIPT, &[wire::process_name(name)?]);
        let result = self.script(&command, MAX_OUTPUT, &[MISSING]).await?;
        if result.exit_code == MISSING {
            return Err(self.no_such_process(name));
        }
        let state = wire::process_state(&result.stdout_lossy())?;
        Ok(Process::new(self.clone(), name.to_string(), state))
    }

    pub(crate) fn no_such_process(&self, name: &str) -> Error {
        Error::NoSuchProcess {
            process: name.to_string(),
            vm: self.info.name.clone(),
        }
    }

    /// The processes [`spawn`](Vm::spawn) has started, running or not.
    /// Requires ssh permission.
    pub async fn processes(&self) -> Result<Vec<Process>> {
        let result = self.script(&sh(LIST_SCRIPT, &[]), MAX_OUTPUT, &[]).await?;
        let mut processes = Vec::new();
        for line in result.stdout_lossy().lines() {
            let (name, state) = line.split_once(' ').ok_or_else(|| Error::protocol("processes"))?;
            let name = wire::process_name(name).map_err(|_| Error::protocol("processes"))?;
            processes.push(Process::new(
                self.clone(),
                name.to_string(),
                wire::process_state(state)?,
            ));
        }
        Ok(processes)
    }

    /// Fetches the VM's attributes. Requires ls permission.
    pub async fn refresh(&mut self) -> Result<()> {
        self.info = find(&self.t, &self.info.name).await?;
        Ok(())
    }

    /// Waits until the VM runs commands: it probes SSH with `true` until it
    /// succeeds. With [`WaitUntil::Setup`], it then waits for the VM's setup
    /// script to finish. This does not wait for servers the VM starts.
    ///
    /// The timeout is 60 seconds by default, or 10 minutes for setup.
    /// Fails with [`Error::VmNotReady`]. Requires ssh permission.
    pub fn wait_until_ready(&mut self) -> WaitUntilReady<'_> {
        WaitUntilReady {
            vm: self,
            until: WaitUntil::Ssh,
            timeout: None,
        }
    }

    fn not_ready(&self, failure: impl Into<String>, source: Option<Error>) -> Error {
        Error::VmNotReady(Box::new(VmNotReady {
            name: self.info.name.clone(),
            vm: Some(self.clone()),
            failure: failure.into(),
            setup: None,
            source,
        }))
    }

    async fn wait(&mut self, until: WaitUntil, timeout: Duration) -> Result<()> {
        let deadline = Instant::now() + timeout;
        let mut backoff = Duration::from_millis(100);
        let setup = until == WaitUntil::Setup;
        let probe = if setup { SETUP_PROBE } else { "true" };
        let mut last = None;
        loop {
            let remaining = deadline.saturating_duration_since(Instant::now());
            if remaining.is_zero() {
                break;
            }
            let options = SshOptions {
                capture: setup,
                max_output: 1 << 20,
                timeout: Some(remaining),
                ..SshOptions::default()
            };
            match self.t.ssh(&self.info.name, probe, options).await {
                Ok(result) => {
                    if result.exit_code != 0 {
                        return Err(self.not_ready("is not SSH-ready", Some(Error::protocol("ssh readiness probe"))));
                    }
                    let state = if setup {
                        wire::setup_state(&result.stdout_lossy())
                            .map_err(|e| self.not_ready("is not SSH-ready", Some(e)))?
                    } else {
                        SetupState::Done
                    };
                    match state {
                        SetupState::Done => {
                            // It answered over SSH, so it is running, whatever new or cp said then.
                            self.info.status = "running".to_string();
                            return Ok(());
                        }
                        SetupState::Failed(failure) => {
                            let mut err = VmNotReady::setup_failed(&self.info.name, failure);
                            err.vm = Some(self.clone());
                            return Err(Error::VmNotReady(Box::new(err)));
                        }
                        SetupState::Pending => backoff = backoff.max(Duration::from_secs(1)),
                    }
                }
                Err(Error::Interrupted(i)) if i.kind == InterruptKind::Timeout => {
                    last = Some(Error::Interrupted(i));
                    break;
                }
                // The probe is safe to rerun after a lost connection.
                Err(Error::Interrupted(i)) if i.kind == InterruptKind::Disconnected => {
                    last = Some(Error::Interrupted(i))
                }
                Err(err @ Error::Network { .. }) => last = Some(err),
                Err(Error::Api(err)) if err.kind() == ApiErrorKind::PermissionDenied => {
                    return Err(self.not_ready(
                        "is not known to be ready: this token may not run ssh, which readiness needs \
                         (use WaitUntil::Created)",
                        Some(Error::Api(err)),
                    ));
                }
                // /exec reports vm_unreachable before a remote command
                // starts. Others (not found, no SSH configured) fail fast.
                Err(Error::Api(err))
                    if err.status == 422 && error_code(&err.body).as_deref() == Some("vm_unreachable") =>
                {
                    last = Some(Error::Api(err));
                }
                Err(err @ (Error::Api(_) | Error::Interrupted(_) | Error::Protocol { .. })) => {
                    return Err(self.not_ready("is not SSH-ready", Some(err)));
                }
                Err(err) => return Err(err),
            }
            let remaining = deadline.saturating_duration_since(Instant::now());
            tokio::time::sleep(backoff.min(remaining)).await;
            backoff = (backoff * 2).min(Duration::from_secs(2));
        }
        let what = if setup {
            "setup did not finish in time"
        } else {
            "SSH readiness timed out"
        };
        Err(self.not_ready(format!("is not ready: {what}"), last))
    }

    pub(crate) async fn ready(&mut self, until: WaitUntil, timeout: Option<Duration>) -> Result<()> {
        let timeout = until.timeout(timeout)?;
        if until == WaitUntil::Created {
            return Ok(());
        }
        self.wait(until, timeout).await
    }

    /// Waits until a VM that new or cp made is ready. If that fails, or the
    /// future is dropped, deletes it: the caller never received it.
    pub(crate) async fn created(
        mut self,
        until: WaitUntil,
        timeout: Option<Duration>,
        keep_on_failure: bool,
    ) -> Result<Vm> {
        let mut guard = DeleteGuard {
            t: Some(self.t.clone()),
            name: self.info.name.clone(),
        };
        match self.ready(until, timeout).await {
            Ok(()) => {
                guard.t = None;
                Ok(self)
            }
            Err(err @ Error::VmNotReady(_)) if keep_on_failure => {
                guard.t = None;
                Err(err)
            }
            Err(mut err) => {
                guard.t = None;
                self.t.remove(&self.info.name).await;
                if let Error::VmNotReady(e) = &mut err {
                    e.vm = None;
                }
                Err(err)
            }
        }
    }

    /// Flushes the VM's recent writes to its disk, if it is running. Best
    /// effort.
    pub(crate) async fn flush(&self) {
        let options = SshOptions {
            capture: false,
            timeout: Some(Duration::from_secs(60)),
            ..SshOptions::default()
        };
        let _ = self.t.ssh(&self.info.name, &sh(FLUSH_SCRIPT, &[]), options).await;
    }
}

/// Deletes a VM if dropped while armed.
struct DeleteGuard {
    t: Option<Arc<Transport>>,
    name: String,
}

impl Drop for DeleteGuard {
    fn drop(&mut self) {
        let Some(t) = self.t.take() else { return };
        let Ok(runtime) = tokio::runtime::Handle::try_current() else {
            return;
        };
        let name = std::mem::take(&mut self.name);
        runtime.spawn(async move { t.remove(&name).await });
    }
}

/// [`Vm::run`]: a command to run on a VM.
#[must_use = "a command does nothing until it is awaited"]
pub struct Run<'a> {
    vm: &'a Vm,
    command: Command,
    check: bool,
    cwd: Option<String>,
    env: Vec<(String, String)>,
    options: SshOptions<'a>,
}

impl<'a> Run<'a> {
    /// Makes a nonzero exit status [`Error::Command`].
    pub fn check(mut self, check: bool) -> Self {
        self.check = check;
        self
    }

    /// Stops the command, with every process it started, if it is still
    /// running after this long: [`Error::Interrupted`] with
    /// [`InterruptKind::Timeout`]. Without one, a command may run for as
    /// long as it likes.
    pub fn timeout(mut self, timeout: Duration) -> Self {
        self.options.timeout = Some(timeout);
        self
    }

    /// The directory to run it in.
    pub fn cwd(mut self, dir: impl Into<String>) -> Self {
        self.cwd = Some(dir.into());
        self
    }

    /// Sets an environment variable for it.
    pub fn env(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.env.push((key.into(), value.into()));
        self
    }

    /// Called with each line of standard output as it arrives, without its
    /// line ending; invalid UTF-8 becomes U+FFFD.
    pub fn on_stdout(mut self, f: impl FnMut(&str) + Send + 'a) -> Self {
        self.options.on_stdout = Some(Box::new(f));
        self
    }

    /// Called with each line of standard error as it arrives.
    pub fn on_stderr(mut self, f: impl FnMut(&str) + Send + 'a) -> Self {
        self.options.on_stderr = Some(Box::new(f));
        self
    }

    /// Called with standard output as the bytes the command wrote, split
    /// wherever it happens to arrive: for output that is not text.
    pub fn on_stdout_bytes(mut self, f: impl FnMut(&[u8]) + Send + 'a) -> Self {
        self.options.on_stdout_bytes = Some(Box::new(f));
        self
    }

    /// Called with standard error as the bytes the command wrote.
    pub fn on_stderr_bytes(mut self, f: impl FnMut(&[u8]) + Send + 'a) -> Self {
        self.options.on_stderr_bytes = Some(Box::new(f));
        self
    }

    /// Whether to capture output in the result (by default, true). For long
    /// or large output, capture none and stream it.
    pub fn capture(mut self, capture: bool) -> Self {
        self.options.capture = capture;
        self
    }

    /// The most output to capture, in bytes, stdout and stderr together: 8
    /// MiB by default. More stops the command: [`Error::Interrupted`] with
    /// [`InterruptKind::OutputLimit`].
    pub fn max_output(mut self, bytes: usize) -> Self {
        self.options.max_output = bytes;
        self
    }
}

impl<'a> IntoFuture for Run<'a> {
    type Output = Result<CommandResult>;
    type IntoFuture = BoxFuture<'a, Self::Output>;

    fn into_future(self) -> Self::IntoFuture {
        Box::pin(async move {
            let line = wire::shell_command(&self.command, self.cwd.as_deref(), &self.env)?;
            let script = self.vm.fit(line, |line| sh(RUN_SCRIPT, &[line])).await?;
            let result = self.vm.t.ssh(&self.vm.info.name, &script, self.options).await?;
            if self.check { result.check() } else { Ok(result) }
        })
    }
}

/// [`Vm::write_file`]: a file to write.
#[must_use = "a request does nothing until it is awaited"]
pub struct WriteFile<'a> {
    vm: &'a Vm,
    path: String,
    data: Vec<u8>,
    mode: Option<u32>,
}

impl WriteFile<'_> {
    /// Its permissions, such as `0o755`.
    pub fn mode(mut self, mode: u32) -> Self {
        self.mode = Some(mode);
        self
    }
}

impl<'a> IntoFuture for WriteFile<'a> {
    type Output = Result<()>;
    type IntoFuture = BoxFuture<'a, Self::Output>;

    fn into_future(self) -> Self::IntoFuture {
        Box::pin(async move { self.vm.write(&self.path, &self.data, self.mode).await })
    }
}

/// [`Vm::upload`]: a local file or directory to copy to a VM.
#[must_use = "a request does nothing until it is awaited"]
pub struct Upload<'a> {
    vm: &'a Vm,
    local: PathBuf,
    remote: String,
    exclude: Vec<String>,
}

impl Upload<'_> {
    /// Leaves out files and directories whose names match any of these
    /// patterns, such as `[".git", "target", "*.log"]`.
    pub fn exclude<I, S>(mut self, patterns: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.exclude.extend(patterns.into_iter().map(Into::into));
        self
    }
}

impl<'a> IntoFuture for Upload<'a> {
    type Output = Result<()>;
    type IntoFuture = BoxFuture<'a, Self::Output>;

    fn into_future(self) -> Self::IntoFuture {
        Box::pin(async move {
            let destination = wire::remote_path(&self.remote)?;
            let local = self.local.clone();
            let meta = tokio::fs::metadata(&local)
                .await
                .map_err(|e| Error::io(format!("reading {}", local.display()), e))?;
            if meta.is_dir() {
                let exclude = self.exclude.clone();
                let archive = tokio::task::spawn_blocking(move || crate::archive::tar_directory(&local, &exclude))
                    .await
                    .map_err(|_| Error::invalid("archiving failed"))??;
                let temporary = format!("/tmp/.exedev-upload-{}.tgz", wire::random_hex(8));
                self.vm.write(&temporary, &archive, None).await?;
                self.vm
                    .script(&sh(UNTAR_SCRIPT, &[&temporary, &destination]), MAX_OUTPUT, &[])
                    .await?;
                return Ok(());
            }
            let data = tokio::fs::read(&local)
                .await
                .map_err(|e| Error::io(format!("reading {}", local.display()), e))?;
            self.vm
                .write(&self.remote, &data, Some(crate::archive::file_mode(&meta)))
                .await
        })
    }
}

/// [`Vm::spawn`]: a command to start in the background.
#[must_use = "a request does nothing until it is awaited"]
pub struct Spawn<'a> {
    vm: &'a Vm,
    command: Command,
    name: Option<String>,
    cwd: Option<String>,
    env: Vec<(String, String)>,
}

impl Spawn<'_> {
    /// Its name, which [`Vm::process`] finds it by: letters, digits, `.`,
    /// `_`, and `-`. By default, it is random.
    pub fn name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }

    /// The directory to run it in.
    pub fn cwd(mut self, dir: impl Into<String>) -> Self {
        self.cwd = Some(dir.into());
        self
    }

    /// Sets an environment variable for it.
    pub fn env(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.env.push((key.into(), value.into()));
        self
    }
}

impl<'a> IntoFuture for Spawn<'a> {
    type Output = Result<Process>;
    type IntoFuture = BoxFuture<'a, Self::Output>;

    fn into_future(self) -> Self::IntoFuture {
        Box::pin(async move {
            let name = self.name.unwrap_or_else(|| wire::random_hex(4));
            wire::process_name(&name)?;
            let line = wire::shell_command(&self.command, self.cwd.as_deref(), &self.env)?;
            let script = self.vm.fit(line, |line| sh(SPAWN_SCRIPT, &[&name, line])).await?;
            let result = self.vm.script(&script, MAX_OUTPUT, &[RUNNING]).await?;
            if result.exit_code == RUNNING {
                return Err(Error::invalid(format!(
                    "a process named {name} is already running on VM {}",
                    self.vm.name()
                )));
            }
            let pid = result
                .stdout_lossy()
                .trim()
                .parse()
                .map_err(|_| Error::protocol("spawn"))?;
            let state = wire::ProcessState {
                pid,
                exit_code: None,
                lost: false,
            };
            Ok(Process::new(self.vm.clone(), name, state))
        })
    }
}

/// [`Vm::wait_until_ready`].
#[must_use = "a request does nothing until it is awaited"]
pub struct WaitUntilReady<'a> {
    vm: &'a mut Vm,
    until: WaitUntil,
    timeout: Option<Duration>,
}

impl WaitUntilReady<'_> {
    /// What to wait for; by default, [`WaitUntil::Ssh`].
    pub fn until(mut self, until: WaitUntil) -> Self {
        self.until = until;
        self
    }

    /// How long to wait: by default, 60 seconds, or 10 minutes for setup.
    pub fn timeout(mut self, timeout: Duration) -> Self {
        self.timeout = Some(timeout);
        self
    }
}

impl<'a> IntoFuture for WaitUntilReady<'a> {
    type Output = Result<()>;
    type IntoFuture = BoxFuture<'a, Self::Output>;

    fn into_future(self) -> Self::IntoFuture {
        Box::pin(async move { self.vm.ready(self.until, self.timeout).await })
    }
}

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

    fn vm(https_url: &str) -> Vm {
        let client = crate::Client::new("t").unwrap();
        Vm::new(
            client.t,
            VmInfo {
                name: "box".into(),
                status: "running".into(),
                ssh_dest: "box.exe.xyz".into(),
                https_url: https_url.into(),
                tags: vec![],
                region: None,
                comment: String::new(),
                created_at: None,
                egress: None,
                prompt_error: None,
            },
        )
    }

    #[test]
    fn urls() {
        let v = vm("https://box.exe.xyz/");
        assert_eq!(v.url(None, "/").unwrap(), "https://box.exe.xyz/");
        assert_eq!(v.url(Some(8080), "/api").unwrap(), "https://box.exe.xyz:8080/api");
        assert!(v.url(None, "x").is_err());
        let v = vm("http://localhost:1234");
        assert_eq!(v.url(Some(3000), "/").unwrap(), "http://localhost:3000/");
    }

    #[test]
    fn absorbing() {
        let mut v = vm("https://box.exe.xyz/");
        v.absorb(&serde_json::json!({"vm_name": "box", "status": "paused", "tags": ["a"], "egress_policy": "all"}));
        assert_eq!(
            (v.status(), v.tags(), v.egress()),
            ("paused", &["a".to_string()][..], Some(EgressPolicy::All))
        );
        v.absorb(&serde_json::json!({"vm_name": "other", "status": "running"}));
        assert_eq!(v.status(), "paused");
        v.renamed(&serde_json::json!({"new_name": "b2", "ssh_dest": "b2.exe.xyz", "https_url": "https://b2.exe.xyz/"}))
            .unwrap();
        assert_eq!(v.name(), "b2");
        assert!(v.renamed(&serde_json::json!({"new_name": "b3"})).is_err());
    }

    #[test]
    fn results() {
        let r = CommandResult {
            exit_code: 1,
            stdout: b"out".to_vec(),
            stderr: b"first\nlast line\n".to_vec(),
            captured: true,
        };
        assert!(!r.success());
        let err = r.check().unwrap_err();
        assert_eq!(err.to_string(), "command exited with status 1: last line");
    }
}