use isothrum_runner::{
Download, DownloadRemoval, DownloadToAdopt, DownloadsToRemove, InputVariable, MachineUsage, NativeConsole, Op, Park, RunName, ServiceEndpoint,
ShellCommand, Status,
};
use serde::{Deserialize, Serialize};
use crate::v1::{Event, EventCursor, OperationId, OperationRow, RunRow};
mod console;
mod target;
pub use console::{ConsoleEndpoint, ReachedConsole};
pub use target::{OpOptions, Target};
pub const PROTOCOL: u32 = 1;
pub const MAX_LINE: usize = 16 * 1024 * 1024;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Request {
pub id: u64,
#[serde(flatten)]
pub command: Command,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "cmd", rename_all = "snake_case")]
#[non_exhaustive]
pub enum Command {
Hello {
protocol: u32,
},
Up {
target: Target,
#[serde(default)]
options: OpOptions,
#[serde(default, skip_serializing_if = "Option::is_none")]
lifetime_s: Option<u64>,
},
Down {
target: Target,
#[serde(default)]
options: OpOptions,
},
Park {
target: Target,
#[serde(default)]
options: OpOptions,
mode: Park,
},
Resume {
target: Target,
#[serde(default)]
options: OpOptions,
},
Update {
target: Target,
#[serde(default)]
options: OpOptions,
},
Attach {
target: Target,
#[serde(default)]
options: OpOptions,
machine: String,
},
Retire {
target: Target,
#[serde(default)]
options: OpOptions,
machine: String,
},
Package {
target: Target,
#[serde(default)]
options: OpOptions,
machine: String,
output: std::path::PathBuf,
},
Provision {
target: Target,
#[serde(default)]
options: OpOptions,
#[serde(default, skip_serializing_if = "Option::is_none")]
machine: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
with: Option<String>,
},
Exec {
target: Target,
#[serde(default)]
options: OpOptions,
machine: String,
argv: Vec<String>,
},
Status {
run: RunName,
#[serde(default, skip_serializing_if = "Option::is_none")]
target: Option<Target>,
#[serde(default, skip_serializing_if = "OpOptions::is_empty")]
options: OpOptions,
},
Variables {
target: Target,
},
List,
Record {
run: RunName,
},
Forget {
run: RunName,
},
Expired,
ConsoleCommand {
run: RunName,
#[serde(default, skip_serializing_if = "Option::is_none")]
target: Option<Target>,
machine: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
user: Option<String>,
},
GraphicalConsole {
run: RunName,
#[serde(default, skip_serializing_if = "Option::is_none")]
target: Option<Target>,
#[serde(default, skip_serializing_if = "OpOptions::is_empty")]
options: OpOptions,
machine: String,
},
NativeConsole {
run: RunName,
#[serde(default, skip_serializing_if = "Option::is_none")]
target: Option<Target>,
#[serde(default, skip_serializing_if = "OpOptions::is_empty")]
options: OpOptions,
machine: String,
},
ServiceEndpoints {
run: RunName,
#[serde(default, skip_serializing_if = "Option::is_none")]
target: Option<Target>,
#[serde(default, skip_serializing_if = "OpOptions::is_empty")]
options: OpOptions,
},
Usage {
run: RunName,
#[serde(default, skip_serializing_if = "Option::is_none")]
target: Option<Target>,
#[serde(default, skip_serializing_if = "OpOptions::is_empty")]
options: OpOptions,
},
PublicKey,
Downloads,
RemoveDownloads {
which: DownloadsToRemove,
},
AdoptDownloads {
adopted: Vec<DownloadToAdopt>,
},
AddressBlocksInUse {
#[serde(default, skip_serializing_if = "Option::is_none")]
except: Option<RunName>,
#[serde(default, skip_serializing_if = "Option::is_none")]
docker_context: Option<String>,
},
Operations {
run: RunName,
limit: u32,
},
Cancel {
operation: OperationId,
},
Subscribe {
#[serde(default, skip_serializing_if = "Option::is_none")]
run: Option<RunName>,
#[serde(default, skip_serializing_if = "Option::is_none")]
after: Option<EventCursor>,
},
Unsubscribe,
Shutdown,
ShutdownIfIdle,
}
impl Command {
#[must_use]
pub fn op(&self) -> Option<Op> {
Some(match self {
Command::Up { .. } => Op::Up,
Command::Down { .. } => Op::Down,
Command::Park { .. } => Op::Park,
Command::Resume { .. } => Op::Resume,
Command::Update { .. } => Op::Update,
Command::Attach { .. } => Op::Attach,
Command::Retire { .. } => Op::Retire,
Command::Package { .. } => Op::Package,
Command::Provision { .. } => Op::Provision,
Command::Exec { .. } => Op::Check,
_ => return None,
})
}
#[must_use]
pub fn is_question(&self) -> bool {
matches!(
self,
Command::Status { .. }
| Command::Record { .. }
| Command::Forget { .. }
| Command::Expired
| Command::ConsoleCommand { .. }
| Command::GraphicalConsole { .. }
| Command::NativeConsole { .. }
| Command::PublicKey
| Command::ServiceEndpoints { .. }
| Command::Usage { .. }
| Command::Downloads
| Command::RemoveDownloads { .. }
| Command::AdoptDownloads { .. }
| Command::AddressBlocksInUse { .. }
)
}
#[must_use]
pub fn target(&self) -> Option<(&Target, &OpOptions)> {
match self {
Command::Up { target, options, .. }
| Command::Down { target, options }
| Command::Park { target, options, .. }
| Command::Resume { target, options }
| Command::Update { target, options }
| Command::Attach { target, options, .. }
| Command::Retire { target, options, .. }
| Command::Package { target, options, .. }
| Command::Provision { target, options, .. }
| Command::Exec { target, options, .. } => Some((target, options)),
_ => None,
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "reply", rename_all = "snake_case")]
#[non_exhaustive]
pub enum Reply {
Hello {
id: u64,
protocol: u32,
version: String,
},
Accepted {
id: u64,
operation: OperationId,
run: RunName,
position: u32,
},
Status {
id: u64,
status: Box<Status>,
},
Variables {
id: u64,
variables: Vec<InputVariable>,
},
Runs {
id: u64,
runs: Vec<RunRow>,
},
Run {
id: u64,
run: Option<Box<RunRow>>,
},
Shell {
id: u64,
command: ShellCommand,
},
Console {
id: u64,
console: Box<ReachedConsole>,
},
ConsoleClosed {
id: u64,
reason: String,
},
Native {
id: u64,
console: NativeConsole,
},
Endpoints {
id: u64,
endpoints: Vec<ServiceEndpoint>,
},
Usage {
id: u64,
machines: Vec<MachineUsage>,
},
PublicKey {
id: u64,
key: String,
},
Downloads {
id: u64,
downloads: Vec<Download>,
},
DownloadsRemoved {
id: u64,
removed: Vec<DownloadRemoval>,
},
DownloadsAdopted {
id: u64,
adopted: Vec<Download>,
},
AddressBlocks {
id: u64,
blocks: Vec<String>,
},
Operations {
id: u64,
operations: Vec<OperationRow>,
},
Ok {
id: u64,
},
Error {
id: u64,
#[serde(flatten)]
report: isothrum_runner::ErrorReport,
},
Busy {
id: u64,
operations: Vec<OperationId>,
},
Event {
cursor: EventCursor,
event: Box<Event>,
},
}
impl Reply {
#[must_use]
pub fn id(&self) -> Option<u64> {
match self {
Reply::Hello { id, .. }
| Reply::Accepted { id, .. }
| Reply::Status { id, .. }
| Reply::Runs { id, .. }
| Reply::Run { id, .. }
| Reply::Shell { id, .. }
| Reply::Console { id, .. }
| Reply::ConsoleClosed { id, .. }
| Reply::Native { id, .. }
| Reply::Endpoints { id, .. }
| Reply::Usage { id, .. }
| Reply::PublicKey { id, .. }
| Reply::Variables { id, .. }
| Reply::Operations { id, .. }
| Reply::Downloads { id, .. }
| Reply::DownloadsRemoved { id, .. }
| Reply::DownloadsAdopted { id, .. }
| Reply::AddressBlocks { id, .. }
| Reply::Ok { id }
| Reply::Busy { id, .. }
| Reply::Error { id, .. } => Some(*id),
Reply::Event { .. } => None,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::fmt;
use std::net::SocketAddr;
use isothrum_runner::{ConsoleProtocol, Format};
use serde_json::json;
fn round_trip<T: Serialize + serde::de::DeserializeOwned + PartialEq + fmt::Debug>(value: &T) -> serde_json::Value {
let line = serde_json::to_string(value).unwrap();
assert!(!line.contains('\n'), "one line: {line}");
assert_eq!(&serde_json::from_str::<T>(&line).unwrap(), value, "{line}");
serde_json::from_str(&line).unwrap()
}
#[test]
fn a_request_is_one_flat_json_object() {
let up = Request {
id: 7,
command: Command::Up {
target: Target::new("/stacks/web", Some(RunName::new("web").unwrap())).with_format(Format::Compose),
options: OpOptions::default(),
lifetime_s: Some(3600),
},
};
assert_eq!(
round_trip(&up),
json!({"id": 7, "cmd": "up", "target": {"path": "/stacks/web", "name": "web", "format": "compose"}, "options": {}, "lifetime_s": 3600})
);
let park = round_trip(&Request {
id: 8,
command: Command::Park {
target: Target::new("/stacks/web", None),
options: OpOptions::default(),
mode: Park::Pause,
},
});
assert_eq!((&park["cmd"], &park["mode"]), (&json!("park"), &json!("pause")), "{park}");
round_trip(&Request { id: 9, command: Command::List });
assert_eq!(
round_trip(&Request {
id: 10,
command: Command::Subscribe {
run: None,
after: Some(EventCursor(41)),
},
}),
json!({"id": 10, "cmd": "subscribe", "after": 41})
);
}
#[test]
fn a_secret_is_never_in_the_debug_form() {
let options = OpOptions {
secrets: [("TOKEN".to_owned(), "hunter2".to_owned())].into(),
..OpOptions::default()
};
let shown = format!("{options:?}");
assert!(shown.contains("TOKEN") && !shown.contains("hunter2"), "{shown}");
}
#[test]
fn reveal_is_off_unless_asked_and_travels_only_when_on() {
assert_eq!(serde_json::to_string(&OpOptions::default()).unwrap(), "{}");
let on = OpOptions {
reveal: true,
..OpOptions::default()
};
let json = serde_json::to_string(&on).unwrap();
assert_eq!(json, r#"{"reveal":true}"#);
assert!(serde_json::from_str::<OpOptions>(&json).unwrap().reveal);
assert!(!serde_json::from_str::<OpOptions>("{}").unwrap().reveal, "off when not said");
}
#[test]
fn replies_round_trip() {
let accepted = round_trip(&Reply::Accepted {
id: 1,
operation: OperationId(4),
run: RunName::new("web").unwrap(),
position: 1,
});
assert_eq!(accepted, json!({"reply": "accepted", "id": 1, "operation": 4, "run": "web", "position": 1}));
let refused = round_trip(&Reply::Error {
id: 2,
report: isothrum_runner::ErrorReport::new(isothrum_runner::ErrorCode::Usage, "no").unchanged(),
});
assert_eq!(refused, json!({"reply": "error", "id": 2, "code": "usage", "message": "no", "changed": false}));
let run = RunName::new("web").unwrap();
let event = crate::v1::phase_event(&run, (Op::Down, OperationId(4)), crate::v1::OperationPhase::Started, None, None);
let frame = round_trip(&Reply::Event {
cursor: EventCursor(12),
event: Box::new(event),
});
assert_eq!(
(&frame["reply"], &frame["cursor"], &frame["event"]["v"]),
(&json!("event"), &json!(12), &json!(1)),
"{frame}"
);
}
#[test]
fn the_home_s_other_questions_are_flat_objects_too() {
let run = RunName::new("web").unwrap();
assert_eq!(
round_trip(&Request {
id: 4,
command: Command::Forget { run: run.clone() },
}),
json!({"id": 4, "cmd": "forget", "run": "web"})
);
assert_eq!(
round_trip(&Request {
id: 5,
command: Command::Expired
}),
json!({"id": 5, "cmd": "expired"})
);
assert_eq!(
round_trip(&Request {
id: 6,
command: Command::PublicKey
}),
json!({"id": 6, "cmd": "public_key"})
);
let console = round_trip(&Request {
id: 7,
command: Command::GraphicalConsole {
run: run.clone(),
target: None,
options: OpOptions::default(),
machine: "desktop".into(),
},
});
assert_eq!(console, json!({"id": 7, "cmd": "graphical_console", "run": "web", "machine": "desktop"}));
round_trip(&Request {
id: 8,
command: Command::ConsoleCommand {
run,
target: Some(Target::new("/stacks/web", None)),
machine: "web".into(),
user: Some("root".into()),
},
});
for command in [
Command::Record {
run: RunName::new("web").unwrap(),
},
Command::Expired,
Command::PublicKey,
] {
assert_eq!(command.op(), None, "{command:?} queues nothing");
assert!(command.is_question(), "{command:?} is a question");
}
}
#[test]
fn the_downloads_and_their_removal_are_flat_objects_too() {
assert_eq!(
round_trip(&Request {
id: 3,
command: Command::Downloads
}),
json!({"id": 3, "cmd": "downloads"})
);
let remove = |which| Request {
id: 4,
command: Command::RemoveDownloads { which },
};
assert_eq!(
round_trip(&remove(DownloadsToRemove::All)),
json!({"id": 4, "cmd": "remove_downloads", "which": "all"})
);
assert_eq!(
round_trip(&remove(DownloadsToRemove::Only(vec![isothrum_runner::DownloadId(7)]))),
json!({"id": 4, "cmd": "remove_downloads", "which": {"only": [7]}})
);
assert!(Command::Downloads.is_question() && Command::Downloads.op().is_none());
assert!(remove(DownloadsToRemove::All).command.is_question());
let image = json!({"id": 7, "kind": "image", "reference": "nginx:1.27", "image_id": "sha256:a", "docker_context": "orbstack",
"run": "web", "fetched_at": "2026-11-17T10:00:00Z", "size_bytes": 187_654_321});
let listed = json!({"reply": "downloads", "id": 5, "downloads": [image.clone()]});
let downloads: Reply = serde_json::from_value(listed.clone()).unwrap();
assert_eq!(round_trip(&downloads), listed);
assert_eq!(downloads.id(), Some(5));
let removed = json!({"reply": "downloads_removed", "id": 6, "removed": [
{"id": 7, "outcome": "failed", "reason": "in use", "download": image},
{"id": 8, "outcome": "not_recorded"}
]});
let outcomes: Reply = serde_json::from_value(removed.clone()).unwrap();
assert_eq!(round_trip(&outcomes), removed);
}
#[test]
fn a_reached_console_s_secrets_travel_but_never_show() {
let reached = ReachedConsole {
machine: "pve".into(),
protocol: ConsoleProtocol::Vnc,
endpoint: ConsoleEndpoint::ProxmoxVnc {
websocket: "wss://server/vnc?ticket=t0p".into(),
port: 5900,
ticket: "t0p".into(),
header: "Authorization".into(),
authorization: "PVEAPIToken=hunter2".into(),
insecure: false,
},
user: None,
password: Some("t0p".into()),
note: None,
tunnelled: false,
};
let frame = round_trip(&Reply::Console {
id: 9,
console: Box::new(reached.clone()),
});
assert_eq!(
(&frame["console"]["endpoint"]["at"], &frame["console"]["password"]),
(&json!("proxmox_vnc"), &json!("t0p"))
);
let shown = format!("{reached:?}");
assert!(!shown.contains("t0p") && !shown.contains("hunter2"), "{shown}");
let loopback = ConsoleEndpoint::Loopback {
address: SocketAddr::from(([127, 0, 0, 1], 5901)),
};
assert_eq!(serde_json::to_value(&loopback).unwrap(), json!({"at": "loopback", "address": "127.0.0.1:5901"}));
}
#[test]
fn the_frames_every_protocol_keeps_read_as_written() {
let hello = r#"{"id":0,"cmd":"hello","protocol":7}"#;
assert_eq!(serde_json::from_str::<Request>(hello).unwrap().command, Command::Hello { protocol: 7 });
assert_eq!(
round_trip(&Request {
id: 3,
command: Command::ShutdownIfIdle,
}),
json!({"id": 3, "cmd": "shutdown_if_idle"})
);
let hello_reply = round_trip(&Reply::Hello {
id: 0,
protocol: 7,
version: "9.0.0".into(),
});
assert_eq!(hello_reply, json!({"reply": "hello", "id": 0, "protocol": 7, "version": "9.0.0"}));
let busy = round_trip(&Reply::Busy {
id: 3,
operations: vec![OperationId(4), OperationId(9)],
});
assert_eq!(busy, json!({"reply": "busy", "id": 3, "operations": [4, 9]}));
assert_eq!(round_trip(&Reply::Ok { id: 3 }), json!({"reply": "ok", "id": 3}));
}
}