use std::path::PathBuf;
use righ_dm_rs::RighIpv4Addr;
use tokio::{
io::{AsyncReadExt, AsyncWriteExt},
net::UnixStream,
};
use crate::{
types::ValorID,
uds::{UdsRegistrationResponse, UdsWorkerRegistration},
};
pub struct UdsClientTool;
impl UdsClientTool {
pub async fn register_worker(
worker_id: &ValorID,
ipv4_addr: RighIpv4Addr,
uds_path: &PathBuf,
) -> anyhow::Result<UdsRegistrationResponse> {
tracing::info!(
"UDS Client Tool: Registering worker {}@{}",
worker_id,
ipv4_addr
);
let registration = UdsWorkerRegistration {
worker_id: worker_id.clone(),
ipv4_addr,
};
tracing::info!(
"UDS Client Tool: Sending worker registration to master's UDS server: {:?}",
registration
);
let mut stream = UnixStream::connect(uds_path).await?;
let registration_bytes = serde_json::to_vec(®istration)?;
stream.write_all(®istration_bytes).await?;
stream.shutdown().await?;
tracing::info!(
"UDS Client Tool: Worker registration request sent to master for worker {}",
worker_id
);
let mut buffer = Vec::new();
let mut chunk = [0u8; 1024];
loop {
match stream.read(&mut chunk).await {
Ok(n) => {
if n == 0 {
break; }
buffer.extend_from_slice(&chunk[..n]);
}
Err(e) => {
tracing::error!("Error reading response from UDS stream: {}", e);
break;
}
}
}
match serde_json::from_slice::<UdsRegistrationResponse>(&buffer) {
Ok(response) => {
tracing::info!(
"UDS Client Tool: Received response from master for worker {}: {:?}",
worker_id,
response
);
Ok(response)
}
Err(e) => {
tracing::error!("Failed to deserialize response: {}", e);
Err(anyhow::anyhow!("Failed to deserialize response: {}", e))
}
}
}
}