use tokio::sync::oneshot;
use crate::sync::{
error::SyncError,
protocol::{SyncRequest, SyncResponse},
};
pub struct ServerState {
running: bool,
shutdown: Option<oneshot::Sender<()>>,
address: Option<String>,
}
impl Default for ServerState {
fn default() -> Self {
Self::new()
}
}
impl ServerState {
pub fn new() -> Self {
Self {
running: false,
shutdown: None,
address: None,
}
}
pub fn is_running(&self) -> bool {
self.running
}
pub fn get_address(&self) -> Result<String, SyncError> {
if let Some(addr) = &self.address {
Ok(addr.clone())
} else {
Err(SyncError::ServerNotRunning)
}
}
pub fn server_started(&mut self, address: String, shutdown_sender: oneshot::Sender<()>) {
self.running = true;
self.address = Some(address);
self.shutdown = Some(shutdown_sender);
}
pub fn stop_server(&mut self) {
if let Some(tx) = self.shutdown.take() {
let _ = tx.send(());
}
self.running = false;
self.address = None;
}
}
pub struct JsonHandler;
impl JsonHandler {
pub fn serialize_request(request: &SyncRequest) -> Result<Vec<u8>, SyncError> {
serde_json::to_vec(request)
.map_err(|e| SyncError::Network(format!("Failed to serialize request: {e}")))
}
pub fn serialize_response(response: &SyncResponse) -> Result<Vec<u8>, SyncError> {
serde_json::to_vec(response)
.map_err(|e| SyncError::Network(format!("Failed to serialize response: {e}")))
}
pub fn deserialize_request(bytes: &[u8]) -> Result<SyncRequest, SyncError> {
serde_json::from_slice(bytes)
.map_err(|e| SyncError::Network(format!("Failed to deserialize request: {e}")))
}
pub fn deserialize_response(bytes: &[u8]) -> Result<SyncResponse, SyncError> {
serde_json::from_slice(bytes)
.map_err(|e| SyncError::Network(format!("Failed to deserialize response: {e}")))
}
}
pub async fn wait_for_ready(
ready_rx: oneshot::Receiver<()>,
address: &str,
) -> Result<(), SyncError> {
ready_rx.await.map_err(|_| SyncError::ServerBind {
address: address.to_string(),
reason: "Server startup failed".to_string(),
})
}