use std::net::SocketAddr;
use std::path::Path;
use super::claim::IntendedAddresses;
use super::incarnation;
use super::pid_file::{IncarnationState, PidRecord, pid_file_path};
pub(super) type TestResult = Result<(), Box<dyn std::error::Error>>;
pub(super) const HTTP: &str = "127.0.0.1:8080";
pub(super) const GRPC: &str = "127.0.0.1:50051";
pub(super) fn intended() -> Result<IntendedAddresses, std::net::AddrParseError> {
Ok(IntendedAddresses {
http: HTTP.parse()?,
grpc: GRPC.parse()?,
})
}
pub(super) fn other_intended() -> Result<IntendedAddresses, std::net::AddrParseError> {
Ok(IntendedAddresses {
http: "127.0.0.1:18080".parse()?,
grpc: "127.0.0.1:15005".parse()?,
})
}
pub(super) fn own_birth_record() -> Result<PidRecord, Box<dyn std::error::Error>> {
let me = incarnation::self_identity()?;
Ok(PidRecord {
pid: me.pid,
started_at_unix_secs: me.started_at_unix_secs,
binary_sha256: me.binary_sha256,
version: env!("CARGO_PKG_VERSION").to_owned(),
commit: "test-commit".to_owned(),
state: IncarnationState::Booting,
http_address: None,
grpc_address: None,
intended_http_address: None,
intended_grpc_address: None,
stage: None,
stage_detail: None,
stage_seq: 0,
stage_updated_at_unix_secs: 0,
drain_timeout_seconds: 0,
})
}
pub(super) fn own_serving_record(
http: Option<SocketAddr>,
grpc: Option<SocketAddr>,
) -> Result<PidRecord, Box<dyn std::error::Error>> {
let mut record = own_birth_record()?;
record.state = IncarnationState::Serving;
record.http_address = Some(match http {
Some(address) => address,
None => HTTP.parse()?,
});
record.grpc_address = Some(match grpc {
Some(address) => address,
None => GRPC.parse()?,
});
record.drain_timeout_seconds = 30;
Ok(record)
}
pub(super) fn dead_record() -> Result<PidRecord, Box<dyn std::error::Error>> {
let mut child = std::process::Command::new("true").spawn()?;
let pid = child.id();
child.wait()?;
let mut record = own_serving_record(None, None)?;
record.pid = pid;
record.started_at_unix_secs = 0;
Ok(record)
}
pub(super) fn plant(home: &Path, record: &PidRecord) -> TestResult {
let path = pid_file_path(home);
std::fs::create_dir_all(path.parent().ok_or("pid path must have a parent")?)?;
std::fs::write(&path, format!("{}\n", serde_json::to_string(record)?))?;
Ok(())
}