eidetica/sync/transports/
shared.rs1use tokio::sync::oneshot;
7
8use crate::sync::{
9 error::SyncError,
10 protocol::{SyncRequest, SyncResponse},
11};
12
13pub struct ServerState {
18 running: bool,
20 shutdown: Option<oneshot::Sender<()>>,
22 address: Option<String>,
24}
25
26impl Default for ServerState {
27 fn default() -> Self {
28 Self::new()
29 }
30}
31
32impl ServerState {
33 pub fn new() -> Self {
35 Self {
36 running: false,
37 shutdown: None,
38 address: None,
39 }
40 }
41
42 pub fn is_running(&self) -> bool {
44 self.running
45 }
46
47 pub fn get_address(&self) -> Result<String, SyncError> {
49 if let Some(addr) = &self.address {
50 Ok(addr.clone())
51 } else {
52 Err(SyncError::ServerNotRunning)
53 }
54 }
55
56 pub fn server_started(&mut self, address: String, shutdown_sender: oneshot::Sender<()>) {
59 self.running = true;
60 self.address = Some(address);
61 self.shutdown = Some(shutdown_sender);
62 }
63
64 pub fn stop_server(&mut self) {
67 if let Some(tx) = self.shutdown.take() {
69 let _ = tx.send(());
70 }
71 self.running = false;
73 self.address = None;
74 }
75}
76
77pub struct JsonHandler;
79
80impl JsonHandler {
81 pub fn serialize_request(request: &SyncRequest) -> Result<Vec<u8>, SyncError> {
83 serde_json::to_vec(request)
84 .map_err(|e| SyncError::Network(format!("Failed to serialize request: {e}")))
85 }
86
87 pub fn serialize_response(response: &SyncResponse) -> Result<Vec<u8>, SyncError> {
89 serde_json::to_vec(response)
90 .map_err(|e| SyncError::Network(format!("Failed to serialize response: {e}")))
91 }
92
93 pub fn deserialize_request(bytes: &[u8]) -> Result<SyncRequest, SyncError> {
95 serde_json::from_slice(bytes)
96 .map_err(|e| SyncError::Network(format!("Failed to deserialize request: {e}")))
97 }
98
99 pub fn deserialize_response(bytes: &[u8]) -> Result<SyncResponse, SyncError> {
101 serde_json::from_slice(bytes)
102 .map_err(|e| SyncError::Network(format!("Failed to deserialize response: {e}")))
103 }
104}
105
106pub async fn wait_for_ready(
108 ready_rx: oneshot::Receiver<()>,
109 address: &str,
110) -> Result<(), SyncError> {
111 ready_rx.await.map_err(|_| SyncError::ServerBind {
112 address: address.to_string(),
113 reason: "Server startup failed".to_string(),
114 })
115}