use std::collections::BTreeMap;
use std::path::PathBuf;
use serde::{Deserialize, Serialize};
use unitype_core::{Ident, Metadata};
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "k", rename_all = "snake_case")]
pub enum Reach {
Here,
Subprocess {
command: String,
#[serde(default)]
args: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
cwd: Option<PathBuf>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
env: BTreeMap<String, String>,
#[serde(default = "default_timeout")]
timeout_ms: u64,
#[serde(default)]
persistent: bool,
},
Wasm {
module: PathBuf,
#[serde(default, skip_serializing_if = "Option::is_none")]
fuel: Option<u64>,
},
Remote {
endpoint: String,
#[serde(default = "default_timeout")]
timeout_ms: u64,
},
}
fn default_timeout() -> u64 {
30_000
}
impl Reach {
pub fn kind(&self) -> &'static str {
match self {
Reach::Here => "here",
Reach::Subprocess { .. } => "subprocess",
Reach::Wasm { .. } => "wasm",
Reach::Remote { .. } => "remote",
}
}
pub fn timeout_ms(&self) -> Option<u64> {
match self {
Reach::Subprocess { timeout_ms, .. } | Reach::Remote { timeout_ms, .. } => {
Some(*timeout_ms)
}
Reach::Here | Reach::Wasm { .. } => None,
}
}
pub fn is_persistent(&self) -> bool {
matches!(
self,
Reach::Subprocess {
persistent: true,
..
}
)
}
pub fn overhead(&self) -> u8 {
match self {
Reach::Here => 0,
Reach::Wasm { .. } => 1,
Reach::Subprocess {
persistent: true, ..
} => 2,
Reach::Subprocess { .. } => 3,
Reach::Remote { .. } => 4,
}
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Environment {
pub id: Ident,
pub language: Ident,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub doc: Option<String>,
pub reach: Reach,
#[serde(default, skip_serializing_if = "Metadata::is_empty")]
pub meta: Metadata,
}
impl Environment {
pub fn here() -> Self {
Self {
id: Ident::new("here").expect("a valid name"),
language: Ident::new("rust").expect("a valid name"),
doc: Some(
"This process. Compiled-in functions and interpreted bodies run here.".to_string(),
),
reach: Reach::Here,
meta: Metadata::default(),
}
}
pub fn subprocess(id: &str, language: &str, command: &str, args: &[&str]) -> Self {
Self {
id: Ident::new(id).expect("a valid name"),
language: Ident::new(language).expect("a valid name"),
doc: None,
reach: Reach::Subprocess {
command: command.to_string(),
args: args.iter().map(|s| s.to_string()).collect(),
cwd: None,
env: BTreeMap::new(),
timeout_ms: default_timeout(),
persistent: false,
},
meta: Metadata::default(),
}
}
pub fn wasm(id: &str, language: &str, module: impl Into<PathBuf>) -> Self {
Self {
id: Ident::new(id).expect("a valid name"),
language: Ident::new(language).expect("a valid name"),
doc: None,
reach: Reach::Wasm {
module: module.into(),
fuel: None,
},
meta: Metadata::default(),
}
}
pub fn is_here(&self) -> bool {
matches!(self.reach, Reach::Here)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn this_process_is_always_an_environment() {
let here = Environment::here();
assert!(here.is_here());
assert_eq!(here.reach.overhead(), 0);
assert_eq!(
here.reach.timeout_ms(),
None,
"there is nothing to wait for"
);
}
#[test]
fn staying_in_the_process_costs_less_than_leaving_it() {
let ordered = [
Reach::Here,
Reach::Wasm {
module: "x.wasm".into(),
fuel: None,
},
Reach::Subprocess {
command: "python3".into(),
args: vec![],
cwd: None,
env: BTreeMap::new(),
timeout_ms: 1000,
persistent: true,
},
Reach::Subprocess {
command: "python3".into(),
args: vec![],
cwd: None,
env: BTreeMap::new(),
timeout_ms: 1000,
persistent: false,
},
Reach::Remote {
endpoint: "https://elsewhere".into(),
timeout_ms: 1000,
},
];
for pair in ordered.windows(2) {
assert!(
pair[0].overhead() < pair[1].overhead(),
"{} should cost less than {}",
pair[0].kind(),
pair[1].kind()
);
}
}
#[test]
fn the_same_language_can_be_reached_more_than_one_way() {
let spawned = Environment::subprocess("py_local", "python", "python3", &["-u"]);
let hosted = Environment {
id: Ident::new("py_remote").unwrap(),
language: Ident::new("python").unwrap(),
doc: None,
reach: Reach::Remote {
endpoint: "http://localhost:9000".into(),
timeout_ms: 5_000,
},
meta: Metadata::default(),
};
assert_eq!(spawned.language, hosted.language);
assert_ne!(spawned.reach.kind(), hosted.reach.kind());
}
#[test]
fn a_worker_already_running_is_cheaper_to_reach_than_one_that_must_start() {
let started_each_time = Environment::subprocess("py", "python", "python3", &[]);
let mut kept_alive = started_each_time.clone();
if let Reach::Subprocess { persistent, .. } = &mut kept_alive.reach {
*persistent = true;
}
assert!(kept_alive.reach.is_persistent());
assert!(!started_each_time.reach.is_persistent());
assert!(kept_alive.reach.overhead() < started_each_time.reach.overhead());
}
#[test]
fn a_process_is_started_afresh_unless_asked_otherwise() {
let manifest: Environment = serde_json::from_str(
r#"{"id":"py","language":"python",
"reach":{"k":"subprocess","command":"python3"}}"#,
)
.expect("reads");
assert!(!manifest.reach.is_persistent());
}
#[test]
fn an_environment_round_trips_through_json() {
let env = Environment::subprocess("node", "typescript", "node", &["harness.js"]);
let text = serde_json::to_string(&env).unwrap();
assert_eq!(serde_json::from_str::<Environment>(&text).unwrap(), env);
}
#[test]
fn waiting_has_a_limit_wherever_waiting_happens() {
let env = Environment::subprocess("py", "python", "python3", &[]);
assert_eq!(env.reach.timeout_ms(), Some(30_000));
}
}