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
// Code generated by "go run ./cmd/gensdkrs" in the exe.dev repository. DO NOT EDIT.

//! The client, and the transport under it: POST /exec with the command
//! line as the body.

use std::future::{Future, IntoFuture};
use std::pin::Pin;
use std::sync::Arc;
use std::time::Duration;

use serde::de::DeserializeOwned;
use serde_json::Value;
use tokio::time::Instant;

use crate::error::{ApiError, Error, InterruptKind, Result, is_error_document, parse_documents};
use crate::types::RmResponse;
use crate::vm::{CommandResult, Vm};
use crate::wire::{
    self, CONNECT_TIMEOUT, DEFAULT_BASE_URL, Line, Output, READ_TIMEOUT, Stream, StreamFailure, VmInfo, quote,
};

/// A boxed future, as the SDK's request builders resolve to.
pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;

/// The SDK's version, from its Cargo.toml.
pub const VERSION: &str = env!("CARGO_PKG_VERSION");

/// Requests say which SDK sent them, and its version.
pub(crate) const USER_AGENT: &str = concat!("exedev-rust/", env!("CARGO_PKG_VERSION"));

/// Called with each line of output, without its line ending.
pub(crate) type LineCallback<'a> = Box<dyn FnMut(&str) + Send + 'a>;
/// Called with output as the bytes the command wrote.
pub(crate) type BytesCallback<'a> = Box<dyn FnMut(&[u8]) + Send + 'a>;

/// How to run a command over ssh.
pub(crate) struct SshOptions<'a> {
    pub(crate) capture: bool,
    pub(crate) max_output: usize,
    pub(crate) timeout: Option<Duration>,
    pub(crate) on_stdout: Option<LineCallback<'a>>,
    pub(crate) on_stderr: Option<LineCallback<'a>>,
    pub(crate) on_stdout_bytes: Option<BytesCallback<'a>>,
    pub(crate) on_stderr_bytes: Option<BytesCallback<'a>>,
}

impl Default for SshOptions<'_> {
    fn default() -> Self {
        SshOptions {
            capture: true,
            max_output: wire::MAX_OUTPUT,
            timeout: None,
            on_stdout: None,
            on_stderr: None,
            on_stdout_bytes: None,
            on_stderr_bytes: None,
        }
    }
}

impl SshOptions<'_> {
    fn deliver(&mut self, output: &mut Output, stream: Stream, data: &[u8], last: bool) {
        let (bytes, lines) = match stream {
            Stream::Stdout => (&mut self.on_stdout_bytes, &mut self.on_stdout),
            Stream::Stderr => (&mut self.on_stderr_bytes, &mut self.on_stderr),
        };
        if let Some(f) = bytes
            && !data.is_empty()
        {
            f(data);
        }
        if let Some(f) = lines {
            for line in output.lines(stream, data, last) {
                f(&line);
            }
        }
    }
}

/// Decodes a command's JSON result as its type.
pub(crate) fn decode<T: DeserializeOwned>(operation: &str, value: Value) -> Result<T> {
    serde_json::from_value(value).map_err(|e| Error::undecodable(operation, &e))
}

/// Runs exe.dev commands over HTTPS.
pub(crate) struct Transport {
    url: String,
    token: String,
    http: reqwest::Client,
    retries: u32,
    user_agent: reqwest::header::HeaderValue,
}

impl std::fmt::Debug for Transport {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        // Not the token.
        f.debug_struct("Transport")
            .field("url", &self.url)
            .finish_non_exhaustive()
    }
}

impl Transport {
    /// POSTs a command line, retrying while the server says 429, which it
    /// does before running anything.
    async fn send(&self, body: &str) -> std::result::Result<reqwest::Response, reqwest::Error> {
        let mut attempt = 0;
        loop {
            let response = self
                .http
                .post(&self.url)
                .bearer_auth(&self.token)
                .header(reqwest::header::CONTENT_TYPE, "text/plain")
                .header(reqwest::header::ACCEPT, "application/json, application/x-ndjson")
                .header(reqwest::header::USER_AGENT, self.user_agent.clone())
                .body(body.to_string())
                .send()
                .await?;
            if response.status() != reqwest::StatusCode::TOO_MANY_REQUESTS || attempt >= self.retries {
                return Ok(response);
            }
            let after = response
                .headers()
                .get(reqwest::header::RETRY_AFTER)
                .and_then(|v| v.to_str().ok());
            let delay = wire::retry_delay(after, attempt);
            drop(response);
            tokio::time::sleep(delay).await;
            attempt += 1;
        }
    }

    /// A successful response's status, body, and JSON documents, including
    /// in-band error documents.
    pub(crate) async fn documents(&self, operation: &str, line: &str) -> Result<(u16, String, Option<Vec<Value>>)> {
        let network = |source| Error::Network {
            operation: operation.to_string(),
            source,
        };
        let response = self.send(line).await.map_err(network)?;
        let status = response.status().as_u16();
        let success = response.status().is_success();
        let body = response.text().await.map_err(network)?;
        if !success {
            return Err(ApiError::new(operation, status, body).into());
        }
        let docs = parse_documents(&body);
        Ok((status, body, docs))
    }

    /// Runs a command: its JSON document (an array of them, if it reports
    /// several), or its text output as a JSON string if it is not JSON.
    pub(crate) async fn call(&self, operation: &str, line: &str) -> Result<Value> {
        let (status, body, docs) = self.documents(operation, line).await?;
        let Some(mut docs) = docs else {
            return Ok(Value::String(body));
        };
        if docs.iter().any(is_error_document) {
            return Err(ApiError::new(operation, status, body).into());
        }
        Ok(if docs.len() == 1 {
            docs.remove(0)
        } else {
            Value::Array(docs)
        })
    }

    /// Runs a command whose result is JSON of a known shape.
    pub(crate) async fn call_json<T: DeserializeOwned>(&self, operation: &str, line: &str) -> Result<T> {
        let (status, body, docs) = self.documents(operation, line).await?;
        let mut docs = docs.ok_or_else(|| Error::protocol(operation))?;
        if docs.iter().any(is_error_document) {
            return Err(ApiError::new(operation, status, body).into());
        }
        if docs.len() != 1 {
            return Err(Error::protocol(operation));
        }
        decode(operation, docs.remove(0))
    }

    /// Runs new or cp: the VM it created. If the caller drops the future
    /// before the response, the request carries on, and the VM it creates is
    /// deleted: no one else would know of it.
    pub(crate) async fn create(self: &Arc<Self>, operation: &'static str, line: String) -> Result<VmInfo> {
        let t = self.clone();
        let handle = tokio::spawn(async move { t.call(operation, &line).await });
        let mut guard = CreateGuard {
            t: self.clone(),
            operation,
            handle: Some(handle),
        };
        let result = guard.handle.as_mut().expect("handle").await;
        guard.handle = None;
        let value = result.map_err(|_| Error::protocol(operation))??;
        wire::vm_info(&value, operation)
    }

    /// Deletes a VM, or tries to; for cleanup.
    pub(crate) async fn remove(&self, name: &str) {
        let _ = self.documents("rm", &format!("rm {}", quote(name))).await;
    }

    /// Runs command on vm over ssh, streaming its output.
    pub(crate) async fn ssh(&self, vm: &str, command: &str, mut o: SshOptions<'_>) -> Result<CommandResult> {
        let mut output = Output::new(o.capture, o.max_output);
        let Some(timeout) = o.timeout else {
            return self.ssh_stream(vm, command, &mut output, &mut o).await;
        };
        if timeout.is_zero() {
            return Err(Error::invalid("timeout must be positive"));
        }
        let deadline = Instant::now() + timeout;
        let result = tokio::time::timeout_at(deadline, self.ssh_stream(vm, command, &mut output, &mut o)).await;
        // Dropping the stream closed the connection, which stops the command.
        result.unwrap_or_else(|_| {
            let mut err = output.interrupted(InterruptKind::Timeout, None);
            if let Error::Interrupted(i) = &mut err {
                i.timeout = Some(timeout);
            }
            Err(err)
        })
    }

    async fn ssh_stream(
        &self,
        vm: &str,
        command: &str,
        output: &mut Output,
        o: &mut SshOptions<'_>,
    ) -> Result<CommandResult> {
        let mut response = match self.send(&wire::ssh_line(vm, command)).await {
            Ok(r) => r,
            // The request may have reached the VM: whether the command ran is unknown.
            Err(_) => return Err(output.interrupted(InterruptKind::Disconnected, None)),
        };
        if !response.status().is_success() {
            let status = response.status().as_u16();
            let body = response.text().await.map_err(|source| Error::Network {
                operation: "ssh".into(),
                source,
            })?;
            return Err(ApiError::ssh(vm, status, body).into());
        }
        let ndjson = response
            .headers()
            .get(reqwest::header::CONTENT_TYPE)
            .and_then(|v| v.to_str().ok())
            .and_then(|v| v.split(';').next())
            .is_some_and(|v| v.trim().eq_ignore_ascii_case("application/x-ndjson"));
        if !ndjson {
            // An older server may be streaming the command's raw output,
            // which can be endless: do not read it as an error, or claim the
            // command did not run.
            return Err(Error::protocol("ssh"));
        }
        let fail = |output: &mut Output, f: StreamFailure| match f {
            StreamFailure::Protocol => Error::protocol("ssh"),
            StreamFailure::OutputLimit => output.interrupted(InterruptKind::OutputLimit, None),
            StreamFailure::Error(reason) => output.interrupted(InterruptKind::Disconnected, Some(reason)),
        };
        loop {
            let chunk = match response.chunk().await {
                Ok(Some(chunk)) => chunk,
                Ok(None) => break,
                Err(_) => return Err(output.interrupted(InterruptKind::Disconnected, None)),
            };
            let frames = output.feed(&chunk).map_err(|f| fail(output, f))?;
            for (stream, data) in frames {
                o.deliver(output, stream, &data, false);
            }
        }
        let frames = match output.finish() {
            Ok(frames) => frames,
            Err(Some(f)) => return Err(fail(output, f)),
            Err(None) => return Err(output.interrupted(InterruptKind::Disconnected, None)),
        };
        for (stream, data) in frames {
            o.deliver(output, stream, &data, false);
        }
        o.deliver(output, Stream::Stdout, b"", true);
        o.deliver(output, Stream::Stderr, b"", true);
        Ok(output.result())
    }
}

/// Deletes the VM a create request makes, if the caller gave up on it.
struct CreateGuard {
    t: Arc<Transport>,
    operation: &'static str,
    handle: Option<tokio::task::JoinHandle<Result<Value>>>,
}

impl Drop for CreateGuard {
    fn drop(&mut self) {
        let Some(handle) = self.handle.take() else { return };
        let Ok(runtime) = tokio::runtime::Handle::try_current() else {
            return handle.abort();
        };
        let (t, operation) = (self.t.clone(), self.operation);
        runtime.spawn(async move {
            if let Ok(Ok(value)) = handle.await
                && let Ok(info) = wire::vm_info(&value, operation)
            {
                t.remove(&info.name).await;
            }
        });
    }
}

/// An exe.dev API client.
///
/// It is cheap to clone: clones share one connection pool.
///
/// The token's permissions decide which methods work. Without a cmds claim,
/// a token may not run commands on VMs or delete them, and
/// [`new_vm`](Client::new_vm) runs a command to wait for its VM. This one may
/// create, list, run commands on, and delete VMs, those tagged sdk only:
///
/// ```sh
/// ssh exe.dev ssh-key generate-api-key --tag=sdk --cmds=new,ls,ssh,rm
/// ```
///
/// [`sign_token`](crate::sign_token) makes one without a request.
#[derive(Clone, Debug)]
pub struct Client {
    pub(crate) t: Arc<Transport>,
}

impl Client {
    /// A client with this token, for <https://exe.dev>.
    pub fn new(token: impl Into<String>) -> Result<Client> {
        Client::builder().token(token).build()
    }

    /// A client with the token in the EXE_TOKEN environment variable.
    pub fn from_env() -> Result<Client> {
        Client::builder().build()
    }

    /// Configures a client: its token, base URL, HTTP client, and retries.
    pub fn builder() -> ClientBuilder {
        ClientBuilder::default()
    }

    /// The VM with this name. [`Error::is_not_found`] if there is none.
    /// Requires ls permission.
    pub async fn vm(&self, name: &str) -> Result<Vm> {
        let info = find(&self.t, wire::vm_name(name)?).await?;
        Ok(Vm::new(self.t.clone(), info))
    }

    /// Your VMs; [`Vms::pattern`] selects some. Requires ls permission.
    pub fn vms(&self) -> Vms<'_> {
        Vms {
            client: self,
            pattern: None,
        }
    }

    /// Runs a command line as it is, as typed after `ssh exe.dev`, for what
    /// has no method yet: `exe.exec("whoami")`. Quote values put in it with
    /// [`quote`](crate::quote). Returns its JSON result, or its text, as a
    /// JSON string, if it has none. Run commands on a VM with [`Vm::run`],
    /// not this.
    pub async fn exec(&self, command: &str) -> Result<Value> {
        let first = command.split_whitespace().next();
        match first {
            None => Err(Error::invalid("exec takes a nonempty command line")),
            Some("ssh") => Err(Error::invalid("run commands on a VM with Vm::run, not exec")),
            Some(_) => self.t.call("exec", command).await,
        }
    }

    /// Deletes VMs in one request.
    ///
    /// Unlike [`Vm::delete`], VMs that were missing or could not be deleted
    /// are not an error: they are listed in failed, with reasons in errors.
    /// Requires rm permission.
    pub async fn delete<I, S>(&self, vms: I) -> Result<RmResponse>
    where
        I: IntoIterator<Item = S>,
        S: AsRef<str>,
    {
        let mut names: Vec<String> = Vec::new();
        for vm in vms {
            let name = wire::vm_name(vm.as_ref())?.to_string();
            if !names.contains(&name) {
                names.push(name);
            }
        }
        if names.is_empty() {
            return serde_json::from_value(serde_json::json!({"deleted": [], "failed": []}))
                .map_err(|_| Error::protocol("rm"));
        }
        let mut line = Line::new("rm");
        line.args("vmname", names, true);
        let (_, _, docs) = self.t.documents("rm", &line.finish()?).await?;
        wire::rm_result(docs)
    }
}

/// Finds the VM with this name.
pub(crate) async fn find(t: &Transport, name: &str) -> Result<VmInfo> {
    let result = t.call("ls", &format!("ls {}", quote(name))).await?;
    wire::vm_list(&result)?
        .into_iter()
        .find(|info| info.name == name)
        .ok_or_else(|| ApiError::new("ls", 404, format!(r#"{{"error": "VM {name} not found"}}"#)).into())
}

/// [`Client::vms`]: your VMs.
#[must_use = "a request does nothing until it is awaited"]
pub struct Vms<'a> {
    client: &'a Client,
    pattern: Option<String>,
}

impl Vms<'_> {
    /// Only the VMs that this name or pattern, such as `"web-*"`, matches.
    pub fn pattern(mut self, pattern: impl Into<String>) -> Self {
        self.pattern = Some(pattern.into());
        self
    }
}

impl<'a> IntoFuture for Vms<'a> {
    type Output = Result<Vec<Vm>>;
    type IntoFuture = BoxFuture<'a, Self::Output>;

    fn into_future(self) -> Self::IntoFuture {
        Box::pin(async move {
            let mut line = Line::new("ls");
            line.opt_arg(self.pattern);
            let result = self.client.t.call("ls", &line.finish()?).await?;
            let t = &self.client.t;
            Ok(wire::vm_list(&result)?
                .into_iter()
                .map(|info| Vm::new(t.clone(), info))
                .collect())
        })
    }
}

/// Configures a [`Client`].
#[derive(Default)]
pub struct ClientBuilder {
    token: Option<String>,
    base_url: Option<String>,
    http: Option<reqwest::Client>,
    retries: Option<u32>,
    user_agent: Option<String>,
}

impl ClientBuilder {
    /// The API token; by default, the EXE_TOKEN environment variable.
    pub fn token(mut self, token: impl Into<String>) -> Self {
        self.token = Some(token.into());
        self
    }

    /// The exe.dev server; by default, <https://exe.dev>.
    pub fn base_url(mut self, url: impl Into<String>) -> Self {
        self.base_url = Some(url.into());
        self
    }

    /// The HTTP client to send requests with, for proxies, custom TLS, or
    /// tests. By default, one with a 30s connect timeout and a 10 minute
    /// read timeout. Its own timeouts apply to every request: a total
    /// timeout would also cut off long commands on VMs.
    pub fn http_client(mut self, client: reqwest::Client) -> Self {
        self.http = Some(client);
        self
    }

    /// How many times to retry a request refused for exceeding the rate
    /// limit, which runs nothing, with backoff. By default, 5.
    pub fn max_retries(mut self, retries: u32) -> Self {
        self.retries = Some(retries);
        self
    }

    /// Names the product built on the SDK in the User-Agent header of
    /// every request, so that exe.dev can tell its traffic apart: a product
    /// token, such as `"t3exe/0.1.1"`, which comes before the SDK's own,
    /// making the header `"t3exe/0.1.1 exedev-rust/0.1.0"`. By default the
    /// header is the SDK's alone. It may be visible ASCII, with spaces or
    /// tabs between parts; [`build`](Self::build) fails if it is not.
    pub fn user_agent(mut self, product: impl Into<String>) -> Self {
        self.user_agent = Some(product.into());
        self
    }

    /// The client.
    pub fn build(self) -> Result<Client> {
        let user_agent = user_agent(self.user_agent.as_deref())?;
        let token = match self.token {
            Some(t) => t,
            None => std::env::var("EXE_TOKEN").unwrap_or_default(),
        };
        let token = token.trim().to_string();
        if token.is_empty() {
            return Err(Error::Config(
                "an exe.dev API token is required: pass one, or set EXE_TOKEN".into(),
            ));
        }
        let base = self.base_url.unwrap_or_else(|| DEFAULT_BASE_URL.to_string());
        let base = base.trim_end_matches('/');
        if !(base.starts_with("https://") || base.starts_with("http://")) {
            return Err(Error::Config(format!("{base:?} is not an http(s) URL")));
        }
        let http = match self.http {
            Some(c) => c,
            None => reqwest::Client::builder()
                .connect_timeout(CONNECT_TIMEOUT)
                .read_timeout(READ_TIMEOUT)
                .build()
                .map_err(|e| Error::Config(format!("cannot make an HTTP client: {e}")))?,
        };
        Ok(Client {
            t: Arc::new(Transport {
                url: format!("{base}/exec"),
                token,
                http,
                retries: self.retries.unwrap_or(5),
                user_agent,
            }),
        })
    }
}

/// The User-Agent header: the caller's product, if any, then the SDK.
fn user_agent(product: Option<&str>) -> Result<reqwest::header::HeaderValue> {
    let Some(product) = product else {
        return Ok(reqwest::header::HeaderValue::from_static(USER_AGENT));
    };
    // The same rule as the other exe.dev SDKs: visible ASCII, with spaces
    // or tabs only between parts (^[\x21-\x7e]+(?:[ \t]+[\x21-\x7e]+)*$).
    if product.is_empty() {
        return Err(Error::Config(
            "the user agent is empty: name a product, such as \"my-tool/1.0\", or leave it unset".into(),
        ));
    }
    if let Some(c) = product
        .chars()
        .find(|c| !(c.is_ascii_graphic() || *c == ' ' || *c == '\t'))
    {
        return Err(Error::Config(format!(
            "the user agent {product:?} has {c:?}, which an HTTP header cannot carry"
        )));
    }
    if !product.starts_with(|c: char| c.is_ascii_graphic()) || !product.ends_with(|c: char| c.is_ascii_graphic()) {
        return Err(Error::Config(format!(
            "the user agent {product:?} starts or ends with whitespace"
        )));
    }
    reqwest::header::HeaderValue::from_str(&format!("{product} {USER_AGENT}"))
        .map_err(|_| Error::Config(format!("the user agent {product:?} is not a valid HTTP header value")))
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};

    /// Serves one request with a JSON body, and returns the request's head.
    async fn serve_one(listener: tokio::net::TcpListener, body: &'static str) -> String {
        let (mut conn, _) = listener.accept().await.unwrap();
        let mut request = Vec::new();
        let mut buf = [0u8; 4096];
        while !request.windows(4).any(|w| w == b"\r\n\r\n") {
            let n = conn.read(&mut buf).await.unwrap();
            assert!(n > 0, "connection closed mid-request");
            request.extend_from_slice(&buf[..n]);
        }
        let response = format!(
            "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
            body.len()
        );
        conn.write_all(response.as_bytes()).await.unwrap();
        let head = String::from_utf8_lossy(&request).into_owned();
        head[..head.find("\r\n\r\n").unwrap()].to_string()
    }

    #[test]
    fn version_is_the_packages() {
        assert_eq!(VERSION, env!("CARGO_PKG_VERSION"));
        assert!(!VERSION.is_empty());
        assert_eq!(USER_AGENT, format!("exedev-rust/{VERSION}"));
    }

    /// The headers of the request a client built with this builder sends.
    async fn request_headers(builder: ClientBuilder) -> Vec<(String, String)> {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let base = format!("http://{}", listener.local_addr().unwrap());
        let server = tokio::spawn(serve_one(listener, r#"{"email":"a@example.com"}"#));
        let exe = builder.token("test-token").base_url(base).build().unwrap();
        let result = exe.exec("whoami").await.unwrap();
        assert_eq!(result["email"], "a@example.com");
        let head = server.await.unwrap();
        assert!(head.starts_with("POST /exec "), "{head}");
        head.lines()
            .skip(1)
            .filter_map(|l| l.split_once(':'))
            .map(|(k, v)| (k.trim().to_ascii_lowercase(), v.trim().to_string()))
            .collect()
    }

    fn header<'h>(headers: &'h [(String, String)], name: &str) -> Vec<&'h str> {
        headers
            .iter()
            .filter(|(k, _)| k == name)
            .map(|(_, v)| v.as_str())
            .collect()
    }

    #[tokio::test]
    async fn requests_say_which_sdk_sent_them() {
        let headers = request_headers(Client::builder()).await;
        let sdk = format!("exedev-rust/{}", env!("CARGO_PKG_VERSION"));
        assert_eq!(header(&headers, "user-agent"), [sdk.as_str()]);
        assert_eq!(header(&headers, "authorization"), ["Bearer test-token"]);
    }

    #[tokio::test]
    async fn requests_say_which_product_sent_them_first() {
        let headers = request_headers(Client::builder().user_agent("t3exe/0.1.1")).await;
        let want = format!("t3exe/0.1.1 exedev-rust/{}", env!("CARGO_PKG_VERSION"));
        assert_eq!(header(&headers, "user-agent"), [want.as_str()]);
    }

    #[test]
    fn user_agents_must_fit_in_a_header() {
        let sdk = format!("exedev-rust/{VERSION}");
        assert_eq!(user_agent(None).unwrap(), sdk.as_str());
        let ua = user_agent(Some("my-tool/2.0 (+https://example.com)")).unwrap();
        assert_eq!(ua, format!("my-tool/2.0 (+https://example.com) {sdk}").as_str());
        let ua = user_agent(Some("a/1\tb/2")).unwrap();
        assert_eq!(ua, format!("a/1\tb/2 {sdk}").as_str());
        let bad = [
            "",
            " ",
            " a/1",
            "a/1 ",
            "a/1\t",
            "t3exe/1\r\nX-Evil: 1",
            "t3exe/1\n",
            "caf\u{e9}/1",
            "nul\0",
            "del\x7f",
        ];
        for bad in bad {
            let err = Client::builder().token("t").user_agent(bad).build().unwrap_err();
            assert!(matches!(err, Error::Config(_)), "{bad:?}: {err:?}");
        }
        let err = Client::builder().token("t").user_agent("a\r\nb").build().unwrap_err();
        assert_eq!(err.to_string().lines().count(), 1, "{err}");
    }
}