use std::time::Duration;
use base64::Engine as _;
use serde_json::Value;
use crate::error::{Error, Result, SetupFailure, is_error_document};
use crate::types::{EgressPolicy, RmResponse};
pub(crate) const DEFAULT_BASE_URL: &str = "https://exe.dev";
pub(crate) const READ_TIMEOUT: Duration = Duration::from_secs(600);
pub(crate) const CONNECT_TIMEOUT: Duration = Duration::from_secs(30);
pub const MAX_OUTPUT: usize = 8 * 1024 * 1024;
pub(crate) const MAX_LINE: usize = 64 * 1024;
pub(crate) const MAX_FRAME: usize = 1024 * 1024;
pub(crate) const EXEC_LIMIT: usize = 64 * 1024;
pub(crate) const PART_SIZE: usize = 63 * 1024;
pub(crate) const PARALLEL: usize = 8;
pub(crate) const MISSING: i32 = 2;
pub(crate) const IS_DIRECTORY: i32 = 3;
pub(crate) const RUNNING: i32 = 3;
pub fn quote(s: &str) -> String {
if s.is_empty() {
return "''".to_string();
}
let safe = |c: char| c.is_ascii_alphanumeric() || "_@%+=:,./-".contains(c);
if s.chars().all(safe) {
return s.to_string();
}
format!("'{}'", s.replace('\'', r#"'"'"'"#))
}
pub(crate) fn join(words: &[&str]) -> String {
words.iter().map(|w| quote(w)).collect::<Vec<_>>().join(" ")
}
pub(crate) struct Line {
path: &'static str,
flags: Vec<String>,
args: Vec<String>,
err: Option<Error>,
}
impl Line {
pub(crate) fn new(path: &'static str) -> Line {
Line {
path,
flags: Vec::new(),
args: Vec::new(),
err: None,
}
}
fn fail(&mut self, message: String) {
if self.err.is_none() {
self.err = Some(Error::invalid(format!("{}: {message}", self.path)));
}
}
pub(crate) fn bool(&mut self, name: &str, value: Option<bool>) {
match value {
Some(true) => self.flags.push(format!("--{name}")),
Some(false) => self.flags.push(format!("--{name}=false")),
None => {}
}
}
pub(crate) fn string(&mut self, name: &str, value: Option<String>) {
if let Some(v) = value {
self.flags.push(format!("--{name}={}", quote(&v)));
}
}
pub(crate) fn number(&mut self, name: &str, value: Option<i64>) {
if let Some(v) = value {
self.flags.push(format!("--{name}={v}"));
}
}
pub(crate) fn repeated(&mut self, name: &str, values: Option<Vec<String>>) {
for v in values.unwrap_or_default() {
self.flags.push(format!("--{name}={}", quote(&v)));
}
}
pub(crate) fn nonempty(&mut self, name: &str, values: Option<Vec<String>>) {
match values {
Some(v) if v.is_empty() || v.iter().any(String::is_empty) => {
self.fail(format!("{name}: an empty list or value; omit it instead"));
}
v => self.repeated(name, v),
}
}
pub(crate) fn list(&mut self, name: &str, values: Option<Vec<String>>) {
let Some(values) = values else { return };
if values.is_empty() {
return self.fail(format!("{name}: an empty list; omit it for the default"));
}
if let Some(v) = values.iter().find(|v| v.is_empty() || v.contains(',')) {
return self.fail(format!("{name}: {v:?} is empty or has a comma"));
}
self.flags.push(format!("--{name}={}", quote(&values.join(","))));
}
pub(crate) fn arg(&mut self, value: impl Into<String>) {
self.args.push(value.into());
}
pub(crate) fn opt_arg(&mut self, value: Option<String>) {
if let Some(v) = value {
self.args.push(v);
}
}
pub(crate) fn args(&mut self, name: &str, values: Vec<String>, required: bool) {
if required && values.is_empty() {
return self.fail(format!("expected at least one {name}"));
}
self.args.extend(values);
}
pub(crate) fn finish(self) -> Result<String> {
if let Some(err) = self.err {
return Err(err);
}
let mut words = vec![self.path.to_string()];
words.extend(self.flags);
if self.args.iter().any(|a| a.starts_with('-')) {
words.push("--".to_string());
}
words.extend(self.args.iter().map(|a| quote(a)));
Ok(words.join(" "))
}
}
pub(crate) fn on_off(value: bool) -> String {
if value { "on" } else { "off" }.to_string()
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Command {
Shell(String),
Argv(Vec<String>),
}
impl Command {
pub(crate) fn line(&self) -> Result<String> {
match self {
Command::Shell(s) => Ok(s.clone()),
Command::Argv(words) if words.is_empty() => Err(Error::invalid("an empty argument list")),
Command::Argv(words) => Ok(words.iter().map(|w| quote(w)).collect::<Vec<_>>().join(" ")),
}
}
}
impl From<&str> for Command {
fn from(s: &str) -> Command {
Command::Shell(s.to_string())
}
}
impl From<String> for Command {
fn from(s: String) -> Command {
Command::Shell(s)
}
}
impl From<&String> for Command {
fn from(s: &String) -> Command {
Command::Shell(s.clone())
}
}
impl<S: AsRef<str>, const N: usize> From<[S; N]> for Command {
fn from(words: [S; N]) -> Command {
Command::Argv(words.iter().map(|w| w.as_ref().to_string()).collect())
}
}
impl<S: AsRef<str>> From<&[S]> for Command {
fn from(words: &[S]) -> Command {
Command::Argv(words.iter().map(|w| w.as_ref().to_string()).collect())
}
}
impl<S: AsRef<str>> From<Vec<S>> for Command {
fn from(words: Vec<S>) -> Command {
Command::Argv(words.iter().map(|w| w.as_ref().to_string()).collect())
}
}
pub(crate) fn shell_command(command: &Command, cwd: Option<&str>, env: &[(String, String)]) -> Result<String> {
let line = command.line()?;
let mut parts = Vec::new();
if let Some(cwd) = cwd {
if cwd.is_empty() {
return Err(Error::invalid("cwd must be a nonempty path"));
}
parts.push(format!("cd {} || exit", quote(cwd)));
}
for (key, value) in env {
if !is_env_name(key) {
return Err(Error::invalid(format!("{key:?} is not an environment variable name")));
}
parts.push(format!("export {key}={}", quote(value)));
}
parts.push(line);
Ok(parts.join("; "))
}
fn is_env_name(s: &str) -> bool {
let mut chars = s.chars();
chars.next().is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
&& chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
}
pub(crate) fn env_flags(env: Vec<(String, String)>) -> Result<Option<Vec<String>>> {
if env.is_empty() {
return Ok(None);
}
let mut out = Vec::new();
for (key, value) in env {
if key.is_empty() || key.contains('=') {
return Err(Error::invalid("new: env names must be nonempty, without ="));
}
out.push(format!("{key}={value}"));
}
Ok(Some(out))
}
pub(crate) fn is_vm_name(name: &str) -> bool {
let mut chars = name.chars();
chars.next().is_some_and(|c| c.is_ascii_alphanumeric()) && chars.all(|c| c.is_ascii_alphanumeric() || c == '-')
}
pub(crate) fn vm_name(name: &str) -> Result<&str> {
if is_vm_name(name) {
Ok(name)
} else {
Err(Error::invalid(format!("{name:?} is not a VM name")))
}
}
pub(crate) fn sh(script: &str, args: &[&str]) -> String {
let mut words = vec!["sh", "-c", script, "sh"];
words.extend_from_slice(args);
join(&words)
}
pub(crate) fn ssh_line(vm: &str, command: &str) -> String {
format!("ssh {} {}", quote(vm), quote(command))
}
pub(crate) fn fits(vm: &str, command: &str) -> bool {
ssh_line(vm, command).len() <= EXEC_LIMIT
}
pub(crate) fn remote_path(path: &str) -> Result<String> {
if path.is_empty() || path.contains('\0') {
return Err(Error::invalid("a path on the VM must be nonempty, without NUL"));
}
let p = if path == "~" || path.starts_with("~/") {
format!(".{}", &path[1..])
} else {
path.to_string()
};
Ok(if p.starts_with('-') { format!("./{p}") } else { p })
}
pub(crate) fn pack(raw: &[u8]) -> (Vec<u8>, bool) {
if raw.len() > PART_SIZE {
use std::io::Write as _;
let mut gz = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::new(6));
if gz.write_all(raw).is_ok()
&& let Ok(packed) = gz.finish()
&& (packed.len() as f64) < raw.len() as f64 * 0.9
{
return (packed, true);
}
}
(raw.to_vec(), false)
}
pub(crate) fn b64(data: &[u8]) -> String {
base64::engine::general_purpose::STANDARD.encode(data)
}
pub(crate) fn random_hex(n: usize) -> String {
let mut bytes = vec![0u8; n];
rand::fill(&mut bytes[..]);
bytes.iter().map(|b| format!("{b:02x}")).collect()
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Stream {
Stdout,
Stderr,
}
pub(crate) struct Output {
pub(crate) capture: bool,
max_output: usize,
pub(crate) exit_code: Option<i32>,
stdout: Vec<u8>,
stderr: Vec<u8>,
buffer: Vec<u8>,
partial: [Vec<u8>; 2],
}
#[derive(Debug)]
pub(crate) enum StreamFailure {
Protocol,
OutputLimit,
Error(String),
}
impl Output {
pub(crate) fn new(capture: bool, max_output: usize) -> Output {
Output {
capture,
max_output,
exit_code: None,
stdout: Vec::new(),
stderr: Vec::new(),
buffer: Vec::new(),
partial: [Vec::new(), Vec::new()],
}
}
pub(crate) fn feed(&mut self, data: &[u8]) -> std::result::Result<Vec<(Stream, Vec<u8>)>, StreamFailure> {
self.buffer.extend_from_slice(data);
let mut out = Vec::new();
let mut start = 0;
while let Some(i) = self.buffer[start..].iter().position(|&b| b == b'\n') {
let end = start + i;
let line = self.buffer[start..end].to_vec();
if let Some(frame) = self.frame(&line)? {
out.push(frame);
}
start = end + 1;
}
self.buffer.drain(..start);
if self.buffer.len() > MAX_FRAME {
return Err(StreamFailure::Protocol);
}
Ok(out)
}
pub(crate) fn finish(&mut self) -> std::result::Result<Vec<(Stream, Vec<u8>)>, Option<StreamFailure>> {
let line = std::mem::take(&mut self.buffer);
let frame = self.frame(&line).map_err(Some)?;
if self.exit_code.is_none() {
return Err(None);
}
Ok(frame.into_iter().collect())
}
fn frame(&mut self, line: &[u8]) -> std::result::Result<Option<(Stream, Vec<u8>)>, StreamFailure> {
if line.iter().all(u8::is_ascii_whitespace) {
return Ok(None);
}
if self.exit_code.is_some() || line.len() > MAX_FRAME {
return Err(StreamFailure::Protocol);
}
let frame: Value = serde_json::from_slice(line).map_err(|_| StreamFailure::Protocol)?;
let obj = frame
.as_object()
.filter(|o| o.len() == 1)
.ok_or(StreamFailure::Protocol)?;
let (key, value) = obj.iter().next().ok_or(StreamFailure::Protocol)?;
match (key.as_str(), value) {
("stdout" | "stderr", Value::String(s)) => {
let stream = if key == "stdout" {
Stream::Stdout
} else {
Stream::Stderr
};
let data = base64::engine::general_purpose::STANDARD
.decode(s)
.map_err(|_| StreamFailure::Protocol)?;
if self.capture {
if self.stdout.len() + self.stderr.len() + data.len() > self.max_output {
return Err(StreamFailure::OutputLimit);
}
match stream {
Stream::Stdout => self.stdout.extend_from_slice(&data),
Stream::Stderr => self.stderr.extend_from_slice(&data),
}
}
Ok(Some((stream, data)))
}
("exit_code", Value::Number(n)) => {
let code = n
.as_u64()
.filter(|&c| c <= i32::MAX as u64)
.ok_or(StreamFailure::Protocol)?;
self.exit_code = Some(code as i32);
Ok(None)
}
("error", Value::String(s)) => Err(StreamFailure::Error(s.clone())),
_ => Err(StreamFailure::Protocol),
}
}
pub(crate) fn lines(&mut self, stream: Stream, data: &[u8], last: bool) -> Vec<String> {
let partial = &mut self.partial[stream as usize];
partial.extend_from_slice(data);
let mut lines = Vec::new();
let mut start = 0;
while let Some(i) = partial[start..].iter().position(|&b| b == b'\n') {
let mut line = &partial[start..start + i];
if line.last() == Some(&b'\r') {
line = &line[..line.len() - 1];
}
split_line(line, &mut lines);
start += i + 1;
}
partial.drain(..start);
while partial.len() > MAX_LINE {
let cut = utf8_cut(partial, MAX_LINE);
lines.push(String::from_utf8_lossy(&partial[..cut]).into_owned());
partial.drain(..cut);
}
if last && !partial.is_empty() {
lines.push(String::from_utf8_lossy(partial).into_owned());
partial.clear();
}
lines
}
pub(crate) fn interrupted(&mut self, kind: crate::error::InterruptKind, reason: Option<String>) -> Error {
Error::Interrupted(Box::new(crate::error::Interrupted {
kind,
captured: self.capture,
stdout: std::mem::take(&mut self.stdout),
stderr: std::mem::take(&mut self.stderr),
reason,
timeout: None,
}))
}
pub(crate) fn result(&mut self) -> crate::vm::CommandResult {
crate::vm::CommandResult {
exit_code: self.exit_code.unwrap_or(-1),
stdout: std::mem::take(&mut self.stdout),
stderr: std::mem::take(&mut self.stderr),
captured: self.capture,
}
}
}
fn split_line(line: &[u8], out: &mut Vec<String>) {
if line.is_empty() {
out.push(String::new());
return;
}
let mut rest = line;
while !rest.is_empty() {
let cut = if rest.len() > MAX_LINE {
utf8_cut(rest, MAX_LINE)
} else {
rest.len()
};
out.push(String::from_utf8_lossy(&rest[..cut]).into_owned());
rest = &rest[cut..];
}
}
fn utf8_cut(data: &[u8], n: usize) -> usize {
let mut cut = n;
while cut > n.saturating_sub(3) && cut > 0 && cut < data.len() && (data[cut] & 0xc0) == 0x80 {
cut -= 1;
}
if cut == 0 { n } else { cut }
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct VmInfo {
pub(crate) name: String,
pub(crate) status: String,
pub(crate) ssh_dest: String,
pub(crate) https_url: String,
pub(crate) tags: Vec<String>,
pub(crate) region: Option<String>,
pub(crate) comment: String,
pub(crate) created_at: Option<String>,
pub(crate) egress: Option<EgressPolicy>,
pub(crate) prompt_error: Option<String>,
}
pub(crate) fn vm_info(value: &Value, operation: &str) -> Result<VmInfo> {
let bad = || Error::protocol(operation);
let obj = value.as_object().ok_or_else(bad)?;
let string = |key: &str, required: bool| -> Result<Option<String>> {
match obj.get(key) {
None | Some(Value::Null) if !required => Ok(None),
Some(Value::String(s)) if !(required && s.is_empty()) => Ok(Some(s.clone())),
_ => Err(bad()),
}
};
let cp = operation == "cp";
let name = string(if cp { "name" } else { "vm_name" }, true)?.unwrap_or_default();
if !is_vm_name(&name) {
return Err(bad());
}
let tags = match obj.get("tags") {
None | Some(Value::Null) => Vec::new(),
Some(Value::Array(a)) => a
.iter()
.map(|t| t.as_str().map(str::to_string).ok_or_else(bad))
.collect::<Result<_>>()?,
_ => return Err(bad()),
};
Ok(VmInfo {
name,
status: string(if cp { "state" } else { "status" }, operation == "ls")?
.unwrap_or_else(|| "starting".to_string()),
ssh_dest: string(if cp { "ssh" } else { "ssh_dest" }, true)?.unwrap_or_default(),
https_url: string("https_url", true)?.unwrap_or_default(),
tags,
region: string("region", false)?,
comment: string("comment", false)?.unwrap_or_default(),
created_at: string("created_at", false)?.filter(|s| !s.is_empty()),
egress: egress_policy(obj.get("egress_policy")),
prompt_error: string("error", false)?,
})
}
pub(crate) fn egress_policy(value: Option<&Value>) -> Option<EgressPolicy> {
match value?.as_str()? {
"integrations" => Some(EgressPolicy::Integrations),
"all" => Some(EgressPolicy::All),
_ => None,
}
}
pub(crate) fn vm_list(value: &Value) -> Result<Vec<VmInfo>> {
let vms = value
.get("vms")
.and_then(Value::as_array)
.ok_or_else(|| Error::protocol("ls"))?;
vms.iter().map(|v| vm_info(v, "ls")).collect()
}
pub(crate) fn rm_result(docs: Option<Vec<Value>>) -> Result<RmResponse> {
let summary: Vec<Value> = docs
.unwrap_or_default()
.into_iter()
.filter(|d| !is_error_document(d))
.collect();
match <[Value; 1]>::try_from(summary) {
Ok([doc]) => serde_json::from_value(doc).map_err(|_| Error::protocol("rm")),
Err(_) => Err(Error::protocol("rm")),
}
}
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum SetupState {
Pending,
Done,
Failed(SetupFailure),
}
pub(crate) fn setup_state(output: &str) -> Result<SetupState> {
let mut sections = output.split("\n---\n");
let head = sections.next().unwrap_or_default();
let journal: Vec<&str> = sections.collect();
let mut p = std::collections::HashMap::new();
for line in head.split('\n') {
if let Some((key, value)) = line.split_once('=')
&& !key.is_empty()
{
p.insert(key, value.trim());
}
}
let get = |key: &str| p.get(key).copied();
let number = |key: &str| -> Option<i64> {
get(key)
.filter(|v| !v.is_empty() && v.bytes().all(|b| b.is_ascii_digit()))
.and_then(|v| v.parse().ok())
};
let script = match get("Setup") {
Some("present") => true,
Some("absent") => false,
_ => return Err(Error::protocol("ssh setup probe")),
};
let failure = |result: &str| SetupFailure {
result: result.to_string(),
exit_code: None,
signal: None,
output: String::new(),
};
let state = get("State");
if state == Some("booting") {
return Ok(if script { SetupState::Pending } else { SetupState::Done });
}
if state == Some("unsupported") || get("LoadState") == Some("not-found") {
return Ok(if script {
SetupState::Failed(failure("unsupported"))
} else {
SetupState::Done
});
}
let active = get("ActiveState").unwrap_or_default();
if get("LoadState").unwrap_or_default().is_empty() || active.is_empty() {
return Err(Error::protocol("ssh setup probe"));
}
if matches!(active, "activating" | "deactivating" | "reloading") {
return Ok(SetupState::Pending);
}
let exited = number("ExecMainExitTimestampMonotonic").is_some_and(|n| n != 0);
if active == "failed" || (exited && get("Result") != Some("success")) {
let (code, status) = (number("ExecMainCode"), number("ExecMainStatus").map(|s| s as i32));
return Ok(SetupState::Failed(SetupFailure {
result: get("Result").filter(|r| !r.is_empty()).unwrap_or("failed").to_string(),
exit_code: if code == Some(1) { status } else { None },
signal: if matches!(code, Some(2 | 3)) { status } else { None },
output: journal.join("\n---\n"),
}));
}
if exited {
return Ok(SetupState::Done);
}
if number("ConditionTimestampMonotonic").is_some_and(|n| n != 0) && get("ConditionResult") == Some("no") {
return Ok(SetupState::Done);
}
if !script {
return Ok(SetupState::Done);
}
if !matches!(get("Job"), None | Some("" | "0")) || matches!(get("SystemState"), Some("initializing" | "starting")) {
return Ok(SetupState::Pending);
}
Ok(SetupState::Failed(failure("not-run")))
}
pub(crate) fn retry_delay(retry_after: Option<&str>, attempt: u32) -> Duration {
let after = retry_after.and_then(|s| s.trim().parse::<f64>().ok()).unwrap_or(0.0);
let backoff = 0.5 * 2f64.powi(attempt as i32);
let jitter = rand::random::<f64>() * backoff / 2.0;
Duration::from_secs_f64((after.max(backoff) + jitter).min(60.0))
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct ProcessState {
pub(crate) pid: u32,
pub(crate) exit_code: Option<i32>,
pub(crate) lost: bool,
}
pub(crate) fn process_state(line: &str) -> Result<ProcessState> {
let words: Vec<&str> = line.split_whitespace().collect();
let bad = || Error::protocol("process state");
let pid = words.first().and_then(|w| w.parse().ok()).ok_or_else(bad)?;
match words[1..] {
["running"] => Ok(ProcessState {
pid,
exit_code: None,
lost: false,
}),
["lost"] => Ok(ProcessState {
pid,
exit_code: None,
lost: true,
}),
["exited", code] => Ok(ProcessState {
pid,
exit_code: Some(code.parse().map_err(|_| bad())?),
lost: false,
}),
_ => Err(bad()),
}
}
pub(crate) fn process_name(name: &str) -> Result<&str> {
let ok = name.len() <= 64
&& name.chars().next().is_some_and(|c| c.is_ascii_alphanumeric())
&& name.chars().all(|c| c.is_ascii_alphanumeric() || "_.-".contains(c));
if ok {
Ok(name)
} else {
Err(Error::invalid(format!(
"{name:?} is not a process name: use letters, digits, '.', '_', and '-'"
)))
}
}
pub(crate) fn signal_name(sig: &str) -> Result<String> {
let s = sig.strip_prefix("SIG").unwrap_or(sig);
let number = s.parse::<u8>().is_ok_and(|n| (1..128).contains(&n));
let name = s.chars().next().is_some_and(|c| c.is_ascii_uppercase())
&& s.chars()
.all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '+' || c == '-');
if number || name {
Ok(s.to_string())
} else {
Err(Error::invalid(format!("{sig:?} is not a signal")))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn quoting() {
assert_eq!(quote(""), "''");
assert_eq!(quote("a-b_c/d.e:f,g=h+i@j%k"), "a-b_c/d.e:f,g=h+i@j%k");
assert_eq!(quote("it's here"), r#"'it'"'"'s here'"#);
assert_eq!(join(&["sh", "-c", "echo $1"]), "sh -c 'echo $1'");
}
#[test]
fn lines() {
let mut l = Line::new("new");
l.string("name", Some("my vm".into()));
l.bool("no-email", Some(true));
l.bool("copy-tags", Some(false));
l.bool("qr", None);
l.number("cpu", Some(4));
l.repeated("tag", Some(vec!["a".into(), "b c".into()]));
l.list("cmds", Some(vec!["ls".into(), "share show".into()]));
assert_eq!(
l.finish().unwrap(),
"new --name='my vm' --no-email --copy-tags=false --cpu=4 --tag=a --tag='b c' --cmds='ls,share show'"
);
let mut l = Line::new("comment");
l.arg("box");
l.arg("-x");
assert_eq!(l.finish().unwrap(), "comment -- box -x");
let mut l = Line::new("tag");
l.args("tag name", vec![], true);
assert!(matches!(l.finish(), Err(Error::InvalidArgument(_))));
let mut l = Line::new("ssh-key add");
l.nonempty("vm", Some(vec![]));
assert!(l.finish().is_err());
let mut l = Line::new("x");
l.list("cmds", Some(vec!["a,b".into()]));
assert!(l.finish().is_err());
}
#[test]
fn shell_commands() {
let c = Command::from(["echo", "a b"]);
assert_eq!(shell_command(&c, None, &[]).unwrap(), "echo 'a b'");
let env = vec![("CI".to_string(), "1 2".to_string())];
assert_eq!(
shell_command(&"make".into(), Some("/app dir"), &env).unwrap(),
"cd '/app dir' || exit; export CI='1 2'; make"
);
let bad = vec![("A-B".to_string(), String::new())];
assert!(shell_command(&"x".into(), None, &bad).is_err());
assert!(Command::Argv(vec![]).line().is_err());
}
#[test]
fn paths() {
assert_eq!(remote_path("~/x").unwrap(), "./x");
assert_eq!(remote_path("-x").unwrap(), "./-x");
assert_eq!(remote_path("/etc/hosts").unwrap(), "/etc/hosts");
assert!(remote_path("").is_err());
}
fn frame(key: &str, data: &[u8]) -> Vec<u8> {
format!("{{\"{key}\": \"{}\"}}\n", b64(data)).into_bytes()
}
#[test]
fn output_frames() {
let mut o = Output::new(true, 100);
let mut body = frame("stdout", b"hi \xc3");
body.extend(b"\n");
body.extend(frame("stderr", b"warn\n"));
body.extend(frame("stdout", b"\xa9\n"));
body.extend(b"{\"exit_code\": 7}");
let mut got = Vec::new();
for chunk in body.chunks(5) {
got.extend(o.feed(chunk).unwrap());
}
got.extend(o.finish().unwrap());
assert_eq!(got.len(), 3);
let r = o.result();
assert_eq!(
(r.exit_code, r.stdout.as_slice(), r.stderr.as_slice()),
(7, &b"hi \xc3\xa9\n"[..], &b"warn\n"[..])
);
}
#[test]
fn output_failures() {
let mut o = Output::new(true, 3);
assert!(matches!(
o.feed(&frame("stdout", b"toolong")),
Err(StreamFailure::OutputLimit)
));
let mut o = Output::new(false, 3);
assert!(o.feed(&frame("stdout", b"toolong")).is_ok());
assert!(matches!(o.finish(), Err(None)));
let mut o = Output::new(true, 100);
assert!(matches!(
o.feed(b"{\"error\": \"gone\"}\n"),
Err(StreamFailure::Error(_))
));
let mut o = Output::new(true, 100);
assert!(matches!(o.feed(b"{\"stdout\": 1}\n"), Err(StreamFailure::Protocol)));
let mut o = Output::new(true, 100);
assert!(matches!(
o.feed(b"{\"exit_code\": 0}\n{\"exit_code\": 0}\n"),
Err(StreamFailure::Protocol)
));
}
#[test]
fn output_lines() {
let mut o = Output::new(true, 100);
assert_eq!(o.lines(Stream::Stdout, b"a\r\nb", false), vec!["a"]);
assert_eq!(o.lines(Stream::Stdout, b"c\xc3", false), Vec::<String>::new());
assert_eq!(o.lines(Stream::Stdout, b"\xa9\n\n", false), vec!["bcé", ""]);
assert_eq!(o.lines(Stream::Stdout, b"end", true), vec!["end"]);
let long = vec![b'x'; MAX_LINE + 5];
let got = o.lines(Stream::Stderr, &long, true);
assert_eq!(got.iter().map(String::len).collect::<Vec<_>>(), vec![MAX_LINE, 5]);
}
#[test]
fn vm_infos() {
let ls = serde_json::json!({"vms": [{"vm_name": "a", "status": "running", "ssh_dest": "a.exe.xyz",
"https_url": "https://a.exe.xyz/", "region": "pdx", "region_display": "Oregon", "tags": ["x"],
"egress_policy": "something-new"}]});
let vms = vm_list(&ls).unwrap();
assert_eq!(
(vms[0].name.as_str(), vms[0].tags.clone(), vms[0].egress.clone()),
("a", vec!["x".to_string()], None)
);
let cp = serde_json::json!({"name": "b", "state": "starting", "source": "a", "ssh": "b.exe.xyz",
"https_url": "https://b.exe.xyz/", "tags": [], "egress_policy": "all", "elapsed": 1.5});
let info = vm_info(&cp, "cp").unwrap();
assert_eq!((info.name.as_str(), info.egress), ("b", Some(EgressPolicy::All)));
assert!(vm_info(&serde_json::json!({"vm_name": "-bad"}), "new").is_err());
}
#[test]
fn setup_states() {
let s = |text: &str| setup_state(text).unwrap();
assert_eq!(s("Setup=present\nState=booting"), SetupState::Pending);
assert_eq!(s("Setup=absent\nState=unsupported"), SetupState::Done);
assert!(matches!(s("Setup=present\nState=unsupported"), SetupState::Failed(f) if f.result == "unsupported"));
assert_eq!(
s("Setup=present\nLoadState=loaded\nActiveState=activating"),
SetupState::Pending
);
let failed = "Setup=absent\nLoadState=loaded\nActiveState=failed\nResult=exit-code\nExecMainCode=1\nExecMainStatus=3\n---\noops";
assert_eq!(
s(failed),
SetupState::Failed(SetupFailure {
result: "exit-code".into(),
exit_code: Some(3),
signal: None,
output: "oops".into()
})
);
let done =
"Setup=absent\nLoadState=loaded\nActiveState=inactive\nResult=success\nExecMainExitTimestampMonotonic=5";
assert_eq!(s(done), SetupState::Done);
let not_run = "Setup=present\nLoadState=loaded\nActiveState=inactive\nJob=\nSystemState=running";
assert!(matches!(s(not_run), SetupState::Failed(f) if f.result == "not-run"));
assert!(setup_state("garbage").is_err());
}
#[test]
fn process_states() {
assert_eq!(
process_state("12 running").unwrap(),
ProcessState {
pid: 12,
exit_code: None,
lost: false
}
);
assert_eq!(process_state("12 exited 3").unwrap().exit_code, Some(3));
assert!(process_state("0 lost").unwrap().lost);
assert!(process_state("x").is_err());
assert!(process_name("web.1").is_ok());
assert!(process_name("-x").is_err());
assert_eq!(signal_name("SIGTERM").unwrap(), "TERM");
assert_eq!(signal_name("9").unwrap(), "9");
assert!(signal_name("term; rm").is_err());
}
}