use std::path::{Path, PathBuf};
use futures::future;
use crate::ControlError;
use crate::endpoint::ControlEndpoint;
use crate::protocol::{
PROTOCOL_VERSION, ProtocolVersion, Request, Response, SessionInfo,
supports_versioned_subscriptions,
};
#[cfg(unix)]
use crate::{PROBE_TIMEOUT, REQUEST_TIMEOUT, read_message, write_message};
pub struct Client {
#[cfg(unix)]
conn: crate::Framing<tokio::net::UnixStream>,
}
pub struct Subscription {
#[cfg(unix)]
conn: crate::Framing<tokio::net::UnixStream>,
#[cfg(unix)]
read_timeout: Option<std::time::Duration>,
}
#[derive(Debug, Clone)]
pub struct EndpointProbe {
pub endpoint: ControlEndpoint,
pub result: EndpointProbeResult,
}
#[derive(Debug, Clone)]
pub enum EndpointProbeResult {
Session(Box<SessionInfo>),
Absent(String),
ProtocolMismatch {
peer: ProtocolVersion,
ours: ProtocolVersion,
},
Unreachable(String),
}
#[must_use]
pub fn answering_session_probes(probes: &[EndpointProbe]) -> Vec<(ControlEndpoint, SessionInfo)> {
probes
.iter()
.filter_map(|probe| match &probe.result {
EndpointProbeResult::Session(info) => Some((probe.endpoint.clone(), (**info).clone())),
EndpointProbeResult::Absent(_)
| EndpointProbeResult::ProtocolMismatch { .. }
| EndpointProbeResult::Unreachable(_) => None,
})
.collect()
}
#[must_use]
pub fn unique_answering_session_probes(
probes: &[EndpointProbe],
) -> Vec<(ControlEndpoint, SessionInfo)> {
let mut sessions = Vec::<(ControlEndpoint, SessionInfo)>::new();
for (endpoint, info) in answering_session_probes(probes) {
if !sessions
.iter()
.any(|(_, existing)| existing.is_same_instance(&info))
{
sessions.push((endpoint, info));
}
}
sessions
}
impl Client {
#[cfg_attr(
not(unix),
expect(
clippy::unused_async,
reason = "Unix has the async transport implementation; unsupported platforms keep the same API shape"
)
)]
pub async fn connect(endpoint: &ControlEndpoint) -> Result<Self, ControlError> {
match endpoint {
#[cfg(unix)]
ControlEndpoint::Unix(path) => {
let stream =
tokio::time::timeout(REQUEST_TIMEOUT, tokio::net::UnixStream::connect(path))
.await
.map_err(|_| ControlError::Timeout)??;
Ok(Self {
conn: crate::framed(stream),
})
}
#[cfg(not(unix))]
ControlEndpoint::Unix(_) => Err(ControlError::Unsupported),
ControlEndpoint::WindowsNamedPipe(_) => Err(ControlError::Unsupported),
}
}
#[cfg_attr(
not(unix),
expect(
clippy::unused_async,
reason = "Unix has the async transport implementation; unsupported platforms keep the same API shape"
)
)]
pub async fn request(&mut self, request: Request) -> Result<Response, ControlError> {
#[cfg(unix)]
{
write_message(&mut self.conn, &request).await?;
let read =
tokio::time::timeout(REQUEST_TIMEOUT, read_message::<_, Response>(&mut self.conn))
.await
.map_err(|_| ControlError::Timeout)?;
match read? {
Some(response) => Ok(response),
None => Err(ControlError::Closed),
}
}
#[cfg(not(unix))]
{
let _ = request;
Err(ControlError::Unsupported)
}
}
pub async fn subscribe(endpoint: &ControlEndpoint) -> Result<Subscription, ControlError> {
Self::subscribe_request(endpoint, Request::Subscribe, None).await
}
pub async fn subscribe_for_version(
endpoint: &ControlEndpoint,
peer: ProtocolVersion,
) -> Result<Subscription, ControlError> {
let version_aware = supports_versioned_subscriptions(peer);
let request = if version_aware {
Request::SubscribeWithVersion {
protocol_version: PROTOCOL_VERSION,
}
} else {
Request::Subscribe
};
let read_timeout = version_aware.then_some(crate::SUBSCRIPTION_READ_TIMEOUT);
Self::subscribe_request(endpoint, request, read_timeout).await
}
#[cfg_attr(
not(unix),
expect(
clippy::unused_async,
reason = "Unix has the async transport implementation; unsupported platforms keep the same API shape"
)
)]
async fn subscribe_request(
endpoint: &ControlEndpoint,
request: Request,
read_timeout: Option<std::time::Duration>,
) -> Result<Subscription, ControlError> {
#[cfg(unix)]
{
let ControlEndpoint::Unix(path) = endpoint else {
return Err(ControlError::Unsupported);
};
let stream =
tokio::time::timeout(REQUEST_TIMEOUT, tokio::net::UnixStream::connect(path))
.await
.map_err(|_| ControlError::Timeout)??;
let mut conn = crate::framed(stream);
write_message(&mut conn, &request).await?;
Ok(Subscription { conn, read_timeout })
}
#[cfg(not(unix))]
{
let _ = (endpoint, request, read_timeout);
Err(ControlError::Unsupported)
}
}
pub async fn describe(&mut self) -> Result<SessionInfo, ControlError> {
match self.request(Request::Describe).await? {
Response::Description(info) => {
if PROTOCOL_VERSION.is_compatible_with(info.protocol_version) {
Ok(info)
} else {
Err(ControlError::ProtocolMismatch {
peer: info.protocol_version,
ours: PROTOCOL_VERSION,
})
}
}
other => Err(ControlError::Unexpected(format!("{other:?}"))),
}
}
pub async fn health_history(
&mut self,
service: &str,
) -> Result<Vec<micromux::HealthAttempt>, ControlError> {
match self
.request(Request::GetHealthHistory {
service: service.to_string(),
})
.await?
{
Response::HealthHistory { attempts } => Ok(attempts),
other => Err(ControlError::Unexpected(format!("{other:?}"))),
}
}
}
impl Subscription {
#[cfg_attr(
not(unix),
expect(
clippy::unused_async,
reason = "Unix reads from an async subscription stream; unsupported platforms keep the same API shape"
)
)]
pub async fn recv(&mut self) -> Result<Option<micromux::SessionChange>, ControlError> {
#[cfg(unix)]
{
let response = if let Some(timeout) = self.read_timeout {
tokio::time::timeout(timeout, read_message::<_, Response>(&mut self.conn))
.await
.map_err(|_| ControlError::Timeout)??
} else {
read_message::<_, Response>(&mut self.conn).await?
};
match response {
Some(Response::Change(change)) => Ok(Some(change)),
Some(Response::Error { code, message }) => Err(ControlError::Unexpected(format!(
"subscription error {code:?}: {message}"
))),
Some(other) => Err(ControlError::Unexpected(format!("{other:?}"))),
None => Ok(None),
}
}
#[cfg(not(unix))]
{
Err(ControlError::Unsupported)
}
}
}
pub async fn probe_runtime_dir(runtime_dir: &Path) -> Result<Vec<EndpointProbe>, ControlError> {
#[cfg(unix)]
{
let endpoints = runtime_dir_endpoints(runtime_dir);
Ok(probe_endpoints(&endpoints).await)
}
#[cfg(not(unix))]
{
let _ = runtime_dir;
Err(ControlError::Unsupported)
}
}
pub async fn probe_runtime_dirs(
runtime_dirs: &[PathBuf],
) -> Result<Vec<EndpointProbe>, ControlError> {
#[cfg(unix)]
{
let mut endpoints = Vec::new();
for runtime_dir in runtime_dirs {
endpoints.extend(runtime_dir_endpoints(runtime_dir));
}
Ok(probe_endpoints(&endpoints).await)
}
#[cfg(not(unix))]
{
let _ = runtime_dirs;
Err(ControlError::Unsupported)
}
}
pub async fn probe_endpoints(endpoints: &[ControlEndpoint]) -> Vec<EndpointProbe> {
future::join_all(endpoints.iter().map(probe_endpoint)).await
}
pub async fn probe_endpoint(endpoint: &ControlEndpoint) -> EndpointProbe {
#[cfg(unix)]
{
enum ProbeError {
Connect(ControlError),
Describe(ControlError),
}
let outcome = tokio::time::timeout(PROBE_TIMEOUT, async {
let mut client = Client::connect(endpoint)
.await
.map_err(ProbeError::Connect)?;
client.describe().await.map_err(ProbeError::Describe)
})
.await;
match outcome {
Err(_) => EndpointProbe {
endpoint: endpoint.clone(),
result: EndpointProbeResult::Unreachable("probe timed out".to_string()),
},
Ok(Ok(info)) => EndpointProbe {
endpoint: endpoint.clone(),
result: EndpointProbeResult::Session(Box::new(info)),
},
Ok(Err(ProbeError::Describe(ControlError::ProtocolMismatch { peer, ours }))) => {
EndpointProbe {
endpoint: endpoint.clone(),
result: EndpointProbeResult::ProtocolMismatch { peer, ours },
}
}
Ok(Err(ProbeError::Connect(ControlError::Io(err))))
if is_hard_connection_error(&err) || !endpoint_path_is_socket(endpoint) =>
{
EndpointProbe {
endpoint: endpoint.clone(),
result: EndpointProbeResult::Absent(format!("connect: {err}")),
}
}
Ok(Err(ProbeError::Describe(ControlError::Io(err))))
if is_hard_connection_error(&err) =>
{
EndpointProbe {
endpoint: endpoint.clone(),
result: EndpointProbeResult::Absent(format!("describe: {err}")),
}
}
Ok(Err(ProbeError::Describe(ControlError::Closed))) => EndpointProbe {
endpoint: endpoint.clone(),
result: EndpointProbeResult::Unreachable("closed before Describe".to_string()),
},
Ok(Err(ProbeError::Connect(err) | ProbeError::Describe(err))) => EndpointProbe {
endpoint: endpoint.clone(),
result: EndpointProbeResult::Unreachable(err.to_string()),
},
}
}
#[cfg(not(unix))]
{
EndpointProbe {
endpoint: endpoint.clone(),
result: EndpointProbeResult::Unreachable(
"the control plane is not supported on this platform".to_string(),
),
}
}
}
#[cfg(unix)]
fn is_hard_connection_error(err: &std::io::Error) -> bool {
matches!(
err.kind(),
std::io::ErrorKind::NotFound | std::io::ErrorKind::ConnectionRefused
)
}
#[cfg(unix)]
fn endpoint_path_is_socket(endpoint: &ControlEndpoint) -> bool {
use std::os::unix::fs::FileTypeExt as _;
match endpoint {
ControlEndpoint::Unix(path) => {
std::fs::metadata(path).is_ok_and(|metadata| metadata.file_type().is_socket())
}
ControlEndpoint::WindowsNamedPipe(_) => false,
}
}
#[cfg(unix)]
fn runtime_dir_endpoints(runtime_dir: &Path) -> Vec<ControlEndpoint> {
let Ok(entries) = std::fs::read_dir(runtime_dir) else {
return Vec::new();
};
let mut endpoints = Vec::new();
for entry in entries.flatten() {
let path = entry.path();
if path.extension().and_then(|ext| ext.to_str()) != Some("sock") {
continue;
}
endpoints.push(ControlEndpoint::Unix(path));
}
endpoints.sort();
endpoints
}
#[cfg(test)]
mod tests {
use super::*;
#[cfg(unix)]
use color_eyre::eyre;
use similar_asserts::assert_eq;
use std::path::PathBuf;
fn session(id: &str, pid: u32, start_time: u64, name: &str) -> SessionInfo {
SessionInfo {
protocol_version: PROTOCOL_VERSION,
id: id.to_string(),
pid,
start_time,
name: name.to_string(),
working_dir: ".".to_string(),
config_path: "/project/micromux.yaml".to_string(),
services: Vec::new(),
services_truncated: false,
micromux_version: env!("CARGO_PKG_VERSION").to_string(),
capabilities: None,
}
}
#[test]
fn unique_answering_session_probes_dedupes_aliases() {
let first = session("aaa", 42, 100, "first");
let alias = session("aaa", 42, 100, "alias");
let second = session("bbb", 43, 101, "second");
let probes = vec![
EndpointProbe {
endpoint: ControlEndpoint::Unix(PathBuf::from("/first.sock")),
result: EndpointProbeResult::Session(Box::new(first)),
},
EndpointProbe {
endpoint: ControlEndpoint::Unix(PathBuf::from("/alias.sock")),
result: EndpointProbeResult::Session(Box::new(alias)),
},
EndpointProbe {
endpoint: ControlEndpoint::Unix(PathBuf::from("/second.sock")),
result: EndpointProbeResult::Session(Box::new(second)),
},
];
let sessions = unique_answering_session_probes(&probes);
assert_eq!(sessions.len(), 2);
assert_eq!(sessions[0].1.name, "first");
assert_eq!(sessions[1].1.name, "second");
}
#[cfg(unix)]
#[test]
fn runtime_dir_endpoints_are_sorted() -> eyre::Result<()> {
let dir = tempfile::tempdir()?;
std::fs::write(dir.path().join("z.sock"), b"")?;
std::fs::write(dir.path().join("a.sock"), b"")?;
std::fs::write(dir.path().join("ignore.txt"), b"")?;
let endpoints = runtime_dir_endpoints(dir.path());
assert_eq!(
endpoints,
vec![
ControlEndpoint::Unix(dir.path().join("a.sock")),
ControlEndpoint::Unix(dir.path().join("z.sock")),
],
);
Ok(())
}
#[cfg(unix)]
#[tokio::test]
async fn probe_reports_a_leaked_non_socket_file_as_absent() -> eyre::Result<()> {
let dir = tempfile::tempdir()?;
let leaked = dir.path().join("dead.sock");
std::fs::write(&leaked, b"")?;
let probe = probe_endpoint(&ControlEndpoint::Unix(leaked)).await;
assert!(
matches!(probe.result, EndpointProbeResult::Absent(_)),
"a non-socket file must be absent, got {:?}",
probe.result
);
Ok(())
}
#[cfg(not(unix))]
#[tokio::test]
async fn connect_reports_unsupported_transport_off_unix() {
let pipe = ControlEndpoint::WindowsNamedPipe(r"\\.\pipe\micromux-test".to_string());
assert!(matches!(
Client::connect(&pipe).await,
Err(ControlError::Unsupported)
));
let socket = ControlEndpoint::Unix(PathBuf::from("/never/bound.sock"));
assert!(matches!(
Client::connect(&socket).await,
Err(ControlError::Unsupported)
));
}
}