use std::io::{Read as _, Write as _};
use std::net::{SocketAddr, TcpStream};
use std::path::{Path, PathBuf};
use std::process::{Command, ExitCode, Stdio};
use printobserver_types::serde::Deserialize;
const LAUNCH_FILE: &str = "launch.json";
const LOG_FILE: &str = "launcher.log";
const ANSWERED: &str = "200";
#[derive(Clone, Copy)]
enum Report {
Started,
Exited,
CompactionStarted,
CompactionExited,
}
impl Report {
const fn path(self) -> &'static str {
match self {
Self::Started => "/started",
Self::Exited => "/exited",
Self::CompactionStarted => "/compaction-started",
Self::CompactionExited => "/compaction-exited",
}
}
}
const COMPACT_PROMPT: &str = "/compact";
fn tell(control: SocketAddr, report: Report) -> Result<String, String> {
let failed = |error: std::io::Error| format!("{control} did not answer: {error}");
let mut stream = TcpStream::connect(control).map_err(failed)?;
let path = report.path();
stream
.write_all(
format!(
"POST {path} HTTP/1.1\r\nHost: {control}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
)
.as_bytes(),
)
.map_err(failed)?;
let mut answer = String::new();
stream.read_to_string(&mut answer).map_err(failed)?;
let (head, body) = answer
.split_once("\r\n\r\n")
.ok_or_else(|| format!("{control} answered {path} with no whole response"))?;
if head.split_whitespace().nth(1) != Some(ANSWERED) {
return Err(format!("{control} refused {path}: {head}"));
}
let declared = head.lines().find_map(|line| {
let (name, value) = line.split_once(':')?;
name.eq_ignore_ascii_case("content-length")
.then(|| value.trim().parse::<usize>().ok())?
});
if declared != Some(body.len()) {
return Err(format!("{control} answered {path} with no whole response"));
}
Ok(body.to_owned())
}
#[derive(Deserialize)]
#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
struct Launch {
control: SocketAddr,
program: PathBuf,
#[serde(default)]
arguments: Vec<String>,
}
fn launch() -> Result<Launch, String> {
let beside = std::env::current_exe()
.map_err(|error| format!("this program cannot find itself: {error}"))?
.with_file_name(LAUNCH_FILE);
let text = std::fs::read_to_string(&beside)
.map_err(|error| format!("{} is unreadable: {error}", beside.display()))?;
serde_json::from_str(&text)
.map_err(|error| format!("{} is no launch file: {error}", beside.display()))
}
fn run(launch: &Launch, record: &Path) -> Result<ExitCode, String> {
let program = launch.program.display();
let mut kept = std::fs::File::create(record)
.map_err(|error| format!("{} could not be created: {error}", record.display()))?;
let mut child = Command::new(&launch.program)
.args(&launch.arguments)
.args(std::env::args_os().skip(1))
.stdin(Stdio::inherit())
.stderr(Stdio::inherit())
.stdout(Stdio::piped())
.spawn()
.map_err(|error| format!("{program} could not be started: {error}"))?;
let mut from_child = child
.stdout
.take()
.ok_or_else(|| format!("{program} was started with no output to read"))?;
let mut to_caller = std::io::stdout();
let mut piece = [0_u8; 8192];
loop {
let count = from_child
.read(&mut piece)
.map_err(|error| format!("{program}'s output could not be read: {error}"))?;
let Some(read) = piece.get(..count).filter(|read| !read.is_empty()) else {
break;
};
to_caller
.write_all(read)
.and_then(|()| to_caller.flush())
.map_err(|error| format!("the output could not be passed on: {error}"))?;
kept.write_all(read)
.map_err(|error| format!("{} could not be written: {error}", record.display()))?;
}
let status = child
.wait()
.map_err(|error| format!("{program} could not be waited for: {error}"))?;
Ok(status
.code()
.and_then(|code| u8::try_from(code).ok())
.map_or(ExitCode::FAILURE, ExitCode::from))
}
fn launched() -> Result<ExitCode, String> {
let launch = launch()?;
let compacting = std::env::args().any(|argument| argument == COMPACT_PROMPT);
let (started, exited) = if compacting {
(Report::CompactionStarted, Report::CompactionExited)
} else {
(Report::Started, Report::Exited)
};
let record = tell(launch.control, started)?;
let status = run(&launch, Path::new(record.trim()))?;
tell(launch.control, exited)?;
Ok(status)
}
fn keep_the_reason(why: &str) {
let Ok(program) = std::env::current_exe() else {
return;
};
if let Ok(mut log) = std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(program.with_file_name(LOG_FILE))
{
let _ = writeln!(log, "{why}");
}
}
fn main() -> ExitCode {
launched().unwrap_or_else(|why| {
eprintln!("printobserver-server-turn-launcher: {why}");
keep_the_reason(&why);
ExitCode::FAILURE
})
}