|
| 1 | +use pp_core::{Command, CommandType, State}; |
| 2 | +use pp_protocol::{ClientMessage, ServerMessage}; |
| 3 | +use pp_save::{load::Loadable, SaveFile}; |
| 4 | +use std::{cell::RefCell, io::Cursor, rc::Rc}; |
| 5 | +use wasm_bindgen::{prelude::*, JsCast}; |
| 6 | +use web_sys::{CloseEvent, ErrorEvent, MessageEvent, WebSocket}; |
| 7 | + |
| 8 | +#[wasm_bindgen] |
| 9 | +pub struct SyncConnectionConfig { |
| 10 | + /// The hostname of the server |
| 11 | + server_url: String, |
| 12 | + /// The document ID on the server |
| 13 | + doc_id: String, |
| 14 | +} |
| 15 | + |
| 16 | +#[wasm_bindgen] |
| 17 | +impl SyncConnectionConfig { |
| 18 | + #[wasm_bindgen(constructor)] |
| 19 | + pub fn new(server_url: String, doc_id: String) -> Self { |
| 20 | + Self { server_url, doc_id } |
| 21 | + } |
| 22 | +} |
| 23 | + |
| 24 | +/// Manages WebSocket connection to the pp_server for real-time sync |
| 25 | +#[derive(Debug)] |
| 26 | +pub struct SyncManager { |
| 27 | + ws: WebSocket, |
| 28 | +} |
| 29 | + |
| 30 | +impl SyncManager { |
| 31 | + /// Connect to a pp_server WebSocket endpoint for a specific document |
| 32 | + pub fn connect( |
| 33 | + state: Rc<RefCell<State>>, |
| 34 | + config: &SyncConnectionConfig, |
| 35 | + ) -> Result<Self, JsValue> { |
| 36 | + let ws_url = format!("{}/documents/{}", config.server_url, config.doc_id); |
| 37 | + log::info!("Connecting to WebSocket: {}", ws_url); |
| 38 | + |
| 39 | + let ws = WebSocket::new(&ws_url)?; |
| 40 | + |
| 41 | + // Clone references for closures |
| 42 | + let state_clone = Rc::clone(&state); |
| 43 | + let doc_id_clone = config.doc_id.clone(); |
| 44 | + |
| 45 | + // Handle incoming messages from server |
| 46 | + let on_message = Closure::wrap(Box::new(move |e: MessageEvent| { |
| 47 | + if let Ok(text) = e.data().dyn_into::<js_sys::JsString>() { |
| 48 | + let text: String = text.into(); |
| 49 | + match serde_json::from_str::<ServerMessage>(&text) { |
| 50 | + Ok(ServerMessage::Joined { |
| 51 | + state: state_bytes, version, client_count, .. |
| 52 | + }) => { |
| 53 | + log::info!( |
| 54 | + "Joined document (version: {}, clients: {})", |
| 55 | + version, |
| 56 | + client_count |
| 57 | + ); |
| 58 | + // Load initial state from server |
| 59 | + if let Ok(save_file) = SaveFile::from_reader(Cursor::new(state_bytes)) { |
| 60 | + if let Ok(loaded_state) = State::load(save_file) { |
| 61 | + state_clone.replace(loaded_state); |
| 62 | + log::info!("Loaded initial state from server"); |
| 63 | + } |
| 64 | + } |
| 65 | + } |
| 66 | + Ok(ServerMessage::Command { client_id, command, rollback, .. }) => { |
| 67 | + log::info!("Received command from {}: {:?}", client_id, command); |
| 68 | + // Apply command from another client |
| 69 | + let mut state = state_clone.borrow_mut(); |
| 70 | + if let Err(e) = match rollback { |
| 71 | + true => command.rollback(&mut state), |
| 72 | + false => command.execute(&mut state), |
| 73 | + } { |
| 74 | + log::error!("Failed to apply remote command: {:?}", e); |
| 75 | + } |
| 76 | + } |
| 77 | + Ok(ServerMessage::StateSync { state, version }) => { |
| 78 | + log::info!("Received state sync (version: {})", version); |
| 79 | + if let Ok(save_file) = SaveFile::from_reader(Cursor::new(state)) { |
| 80 | + if let Ok(loaded_state) = State::load(save_file) { |
| 81 | + state_clone.replace(loaded_state); |
| 82 | + } |
| 83 | + } |
| 84 | + } |
| 85 | + Ok(ServerMessage::ClientJoined { client_id, client_count }) => { |
| 86 | + log::info!("Client {} joined ({} total)", client_id, client_count); |
| 87 | + } |
| 88 | + Ok(ServerMessage::ClientLeft { client_id, client_count }) => { |
| 89 | + log::info!("Client {} left ({} remaining)", client_id, client_count); |
| 90 | + } |
| 91 | + Err(e) => { |
| 92 | + log::error!("Failed to parse server message: {:?}", e); |
| 93 | + } |
| 94 | + } |
| 95 | + } |
| 96 | + }) as Box<dyn FnMut(MessageEvent)>); |
| 97 | + |
| 98 | + let on_error = Closure::wrap(Box::new(move |e: ErrorEvent| { |
| 99 | + log::error!("WebSocket error: {:?}", e); |
| 100 | + }) as Box<dyn FnMut(ErrorEvent)>); |
| 101 | + |
| 102 | + let on_close = Closure::wrap(Box::new(move |e: CloseEvent| { |
| 103 | + log::info!("WebSocket closed: code={}, reason={}", e.code(), e.reason()); |
| 104 | + }) as Box<dyn FnMut(CloseEvent)>); |
| 105 | + |
| 106 | + // Set event handlers |
| 107 | + ws.set_onmessage(Some(on_message.as_ref().unchecked_ref())); |
| 108 | + ws.set_onerror(Some(on_error.as_ref().unchecked_ref())); |
| 109 | + ws.set_onclose(Some(on_close.as_ref().unchecked_ref())); |
| 110 | + // Keep all the closures alive |
| 111 | + on_message.forget(); |
| 112 | + on_error.forget(); |
| 113 | + on_close.forget(); |
| 114 | + |
| 115 | + // Set up onopen to send Join message |
| 116 | + let ws_clone = ws.clone(); |
| 117 | + let on_open = Closure::once(Box::new(move || { |
| 118 | + log::info!("WebSocket connected, sending Join message"); |
| 119 | + let join_msg = ClientMessage::Join { doc_id: doc_id_clone }; |
| 120 | + if let Ok(json) = serde_json::to_string(&join_msg) { |
| 121 | + let _ = ws_clone.send_with_str(&json); |
| 122 | + } |
| 123 | + }) as Box<dyn FnOnce()>); |
| 124 | + |
| 125 | + ws.set_onopen(Some(on_open.as_ref().unchecked_ref())); |
| 126 | + on_open.forget(); // Keep the closure alive |
| 127 | + |
| 128 | + Ok(Self { ws }) |
| 129 | + } |
| 130 | + |
| 131 | + /// Send a command to the server |
| 132 | + pub fn send_command(&self, command: &CommandType, rollback: bool) -> Result<(), JsValue> { |
| 133 | + // log::info!("{:?}", command); |
| 134 | + let msg = ClientMessage::Command { command: command.clone(), rollback }; |
| 135 | + let json = serde_json::to_string(&msg).map_err(|e| { |
| 136 | + log::error!("{:?}", e); |
| 137 | + JsValue::from_str(&format!("Failed to serialize command: {:?}", e)) |
| 138 | + })?; |
| 139 | + self.ws.send_with_str(&json)?; |
| 140 | + Ok(()) |
| 141 | + } |
| 142 | + |
| 143 | + /// Check if the WebSocket is currently connected |
| 144 | + pub fn is_connected(&self) -> bool { |
| 145 | + self.ws.ready_state() == WebSocket::OPEN |
| 146 | + } |
| 147 | + |
| 148 | + /// Close the WebSocket connection |
| 149 | + pub fn close(&self) -> Result<(), JsValue> { |
| 150 | + self.ws.close() |
| 151 | + } |
| 152 | +} |
| 153 | + |
| 154 | +impl Drop for SyncManager { |
| 155 | + fn drop(&mut self) { |
| 156 | + let _ = self.ws.close(); |
| 157 | + } |
| 158 | +} |
0 commit comments