use serde::{Deserialize, Serialize};
use super::RemoteActionTarget;
use super::server_account::Refusal;
use crate::api::ActionAddress;
pub const PROVIDER: &str = "tilo.environment";
pub const RESOURCE: &str = "environment";
pub const RUN: &str = "run";
pub const LIVE_TAIL: usize = 32 * 1024;
#[must_use]
pub fn target() -> RemoteActionTarget {
RemoteActionTarget {
provider: PROVIDER.to_owned(),
address: ActionAddress::new(RESOURCE, RUN),
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct CommandRequest {
pub session: String,
pub command: String,
#[serde(default)]
pub agent: bool,
pub account: String,
pub size: String,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub secrets: Vec<VmSecret>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub person: Option<Person>,
}
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct VmSecret {
pub variable: String,
pub value: String,
}
impl std::fmt::Debug for VmSecret {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("VmSecret")
.field("variable", &self.variable)
.finish_non_exhaustive()
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Person {
pub name: String,
pub address: String,
}
impl Person {
#[must_use]
pub fn of(name: &str, host: &str) -> Self {
let name = name.trim();
let name = if name.is_empty() {
UNNAMED_ACTOR.to_owned()
} else {
name.to_owned()
};
let local = slug(&name, &['.', '_']);
let local = if local.is_empty() {
"member".to_owned()
} else {
local
};
let host = slug(host_name(host), &['.']);
let host = if host.is_empty() {
"tilo".to_owned()
} else {
host
};
Self {
name,
address: format!("{local}@{host}"),
}
}
}
const UNNAMED_ACTOR: &str = "Tilo member";
fn host_name(host: &str) -> &str {
let host = host.trim();
let host = host.split_once("://").map_or(host, |(_, rest)| rest);
let host = host.split('/').next().unwrap_or(host);
match host.rsplit_once(':') {
Some((name, port)) if !port.is_empty() && port.bytes().all(|b| b.is_ascii_digit()) => name,
_ => host,
}
}
fn slug(text: &str, keep: &[char]) -> String {
let mut out = String::new();
for c in text.trim().chars().flat_map(char::to_lowercase) {
if out.len() >= 63 {
break;
}
if c.is_ascii_alphanumeric() || keep.contains(&c) {
out.push(c);
} else if !out.is_empty() && !out.ends_with('-') {
out.push('-');
}
}
out.trim_matches('-').to_owned()
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct CommandOutput {
pub total: u64,
pub tail: String,
}
impl CommandOutput {
#[must_use]
pub fn of(printed: &[u8]) -> Self {
let from = printed.len().saturating_sub(LIVE_TAIL);
Self {
total: u64::try_from(printed.len()).unwrap_or(u64::MAX),
tail: String::from_utf8_lossy(printed.get(from..).unwrap_or_default()).into_owned(),
}
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct CommandRan {
pub command: String,
pub cwd: String,
pub exit: i32,
pub output: String,
#[serde(default)]
pub truncated: bool,
#[serde(default)]
pub cancelled: bool,
pub started_ms: i64,
pub ended_ms: i64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub refusal: Option<Refusal>,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_secret_prints_its_name_and_never_its_value() {
let secret = VmSecret {
variable: "GITHUB_TOKEN".into(),
value: "sk-the-value".into(),
};
let printed = format!("{secret:?}");
assert!(printed.contains("GITHUB_TOKEN"), "{printed}");
assert!(!printed.contains("sk-the-value"), "{printed}");
}
#[test]
fn live_output_keeps_the_newest_bytes_and_counts_them_all() {
let printed = "x".repeat(LIVE_TAIL + 10) + "é end";
let live = CommandOutput::of(printed.as_bytes());
assert_eq!(live.total, u64::try_from(printed.len()).unwrap());
assert!(live.tail.ends_with("é end"));
assert!(
live.tail.len() <= LIVE_TAIL + 3,
"a cut character is replaced, not kept"
);
}
#[test]
fn a_person_is_addressed_by_their_name_at_their_workspaces_host() {
let ada = Person::of("Ada Lovelace", "https://eu1.tilo.sh/");
assert_eq!(ada.name, "Ada Lovelace");
assert_eq!(ada.address, "ada-lovelace@eu1.tilo.sh");
let with_port = Person::of("Ada", "http://eu1.tilo.sh:8080");
assert_eq!(with_port.address, "ada@eu1.tilo.sh");
let unnamed = Person::of(" ", "");
assert_eq!(unnamed.name, "Tilo member");
assert_eq!(unnamed.address, "tilo-member@tilo");
let odd = Person::of("Ada O'Neil!!", "Ada's server");
assert_eq!(odd.address, "ada-o-neil@ada-s-server");
let written = Person::of("Мария", "team.tilo");
assert_eq!(written.name, "Мария");
assert_eq!(written.address, "member@team.tilo");
}
}