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,
};
pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
pub const VERSION: &str = env!("CARGO_PKG_VERSION");
pub(crate) const USER_AGENT: &str = concat!("exedev-rust/", env!("CARGO_PKG_VERSION"));
pub(crate) type LineCallback<'a> = Box<dyn FnMut(&str) + Send + 'a>;
pub(crate) type BytesCallback<'a> = Box<dyn FnMut(&[u8]) + Send + 'a>;
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);
}
}
}
}
pub(crate) fn decode<T: DeserializeOwned>(operation: &str, value: Value) -> Result<T> {
serde_json::from_value(value).map_err(|e| Error::undecodable(operation, &e))
}
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 {
f.debug_struct("Transport")
.field("url", &self.url)
.finish_non_exhaustive()
}
}
impl Transport {
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;
}
}
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))
}
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)
})
}
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))
}
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)
}
pub(crate) async fn remove(&self, name: &str) {
let _ = self.documents("rm", &format!("rm {}", quote(name))).await;
}
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;
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,
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 {
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())
}
}
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;
}
});
}
}
#[derive(Clone, Debug)]
pub struct Client {
pub(crate) t: Arc<Transport>,
}
impl Client {
pub fn new(token: impl Into<String>) -> Result<Client> {
Client::builder().token(token).build()
}
pub fn from_env() -> Result<Client> {
Client::builder().build()
}
pub fn builder() -> ClientBuilder {
ClientBuilder::default()
}
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))
}
pub fn vms(&self) -> Vms<'_> {
Vms {
client: self,
pattern: None,
}
}
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,
}
}
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)
}
}
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())
}
#[must_use = "a request does nothing until it is awaited"]
pub struct Vms<'a> {
client: &'a Client,
pattern: Option<String>,
}
impl Vms<'_> {
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())
})
}
}
#[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 {
pub fn token(mut self, token: impl Into<String>) -> Self {
self.token = Some(token.into());
self
}
pub fn base_url(mut self, url: impl Into<String>) -> Self {
self.base_url = Some(url.into());
self
}
pub fn http_client(mut self, client: reqwest::Client) -> Self {
self.http = Some(client);
self
}
pub fn max_retries(mut self, retries: u32) -> Self {
self.retries = Some(retries);
self
}
pub fn user_agent(mut self, product: impl Into<String>) -> Self {
self.user_agent = Some(product.into());
self
}
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,
}),
})
}
}
fn user_agent(product: Option<&str>) -> Result<reqwest::header::HeaderValue> {
let Some(product) = product else {
return Ok(reqwest::header::HeaderValue::from_static(USER_AGENT));
};
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 _};
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}"));
}
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}");
}
}