1use alloc::string::String;
17
18use crate::endpoint::{ClientConfig, ClientCore, ClientEvent, State};
19use crate::packet::DATA_HEADER;
20use crate::ws::{WebSocket, WsMessage, WsOptions, WsState};
21use crate::{Error, Stats};
22
23#[cfg(any(windows, target_os = "linux", target_vendor = "apple"))]
24use alloc::{collections::VecDeque, sync::Arc, vec::Vec};
25#[cfg(any(windows, target_os = "linux", target_vendor = "apple"))]
26use core::sync::atomic::{AtomicBool, Ordering};
27
28#[cfg(any(windows, target_os = "linux", target_vendor = "apple"))]
30const UDP_QUEUE: usize = 4096;
31
32const CLOSE_BACKLOG: u16 = 1011;
35
36#[derive(Clone, Debug, PartialEq, Eq)]
38pub enum Endpoint {
39 Udp(plat::net::SocketAddr),
41 WebSocket(String),
43}
44
45#[cfg(any(windows, target_os = "linux", target_vendor = "apple"))]
46struct Udp {
47 sock: Arc<plat::net::UdpSocket>,
48 server: plat::net::SocketAddr,
49 inbox: Arc<plat::sync::Mutex<VecDeque<Vec<u8>>>>,
50 stop: Arc<AtomicBool>,
51}
52
53enum Io {
54 #[cfg(any(windows, target_os = "linux", target_vendor = "apple"))]
55 Udp(Udp),
56 Ws { ws: WebSocket, started: bool, max_unsent: usize },
57}
58
59pub struct Client {
61 core: ClientCore,
62 io: Io,
63}
64
65fn now() -> u64 {
66 plat::time_us()
67}
68
69#[cfg(any(windows, target_os = "linux", target_vendor = "apple"))]
70fn udp_reader(sock: Arc<plat::net::UdpSocket>, server: plat::net::SocketAddr, inbox: Arc<plat::sync::Mutex<VecDeque<Vec<u8>>>>, stop: Arc<AtomicBool>, max: usize) {
71 let mut buf = alloc::vec![0u8; 65536];
72 while !stop.load(Ordering::Acquire) {
73 match sock.recv_from(&mut buf, 100) {
74 Ok((n, from)) if from == server && n <= max => {
77 let mut q = inbox.lock();
78 if q.len() < UDP_QUEUE {
79 q.push_back(buf[..n].to_vec());
80 }
81 drop(q);
82 plat::wake();
83 }
84 Ok(_) => {}
85 Err(e) if e.kind == plat::net::NetErrorKind::TimedOut => {}
86 Err(_) => plat::sleep_ms(5),
88 }
89 }
90}
91
92impl Client {
93 pub fn connect(ep: Endpoint, cfg: ClientConfig) -> Result<Client, Error> {
96 match ep {
97 Endpoint::Udp(addr) => {
98 #[cfg(any(windows, target_os = "linux", target_vendor = "apple"))]
99 {
100 use plat::net::{IpAddr, SocketAddr, UdpSocket};
101 if !plat::policy::net_connect_allowed(&addr) {
102 return Err(Error::Net(plat::net::NetError::new(plat::net::NetErrorKind::Denied, 0)));
103 }
104 let any = if matches!(addr.ip, IpAddr::V4(_)) { IpAddr::UNSPECIFIED_V4 } else { IpAddr::V6([0; 16]) };
105 let sock = Arc::new(UdpSocket::bind(&SocketAddr::new(any, 0))?);
106 let inbox = Arc::new(plat::sync::Mutex::new(VecDeque::new()));
107 let stop = Arc::new(AtomicBool::new(false));
108 let (s, i, st) = (sock.clone(), inbox.clone(), stop.clone());
109 let max = crate::packet::max_datagram(cfg.max_payload.clamp(1, crate::packet::MAX_UDP_PAYLOAD));
110 if !crate::reap::spawn(128 * 1024, move || udp_reader(s, addr, i, st, max)) {
111 return Err(Error::Net(plat::net::NetError::new(plat::net::NetErrorKind::Other, 0)));
112 }
113 let mut core = ClientCore::new(cfg, plat::random_bytes::<32>(), false);
114 core.start(now());
115 let mut c = Client { core, io: Io::Udp(Udp { sock, server: addr, inbox, stop }) };
116 c.flush();
117 Ok(c)
118 }
119 #[cfg(not(any(windows, target_os = "linux", target_vendor = "apple")))]
120 {
121 let _ = (addr, cfg);
122 Err(Error::Unsupported)
123 }
124 }
125 Endpoint::WebSocket(url) => {
126 let o = WsOptions { max_message: cfg.max_payload + DATA_HEADER, connect_ms: cfg.connect_ms, idle_ms: cfg.timeout_ms.saturating_mul(2), ping_ms: 0, ..WsOptions::default() };
127 let ws = WebSocket::connect_with(&url, o)?;
128 Ok(Client { core: ClientCore::new(cfg, ws_random(), true), io: Io::Ws { ws, started: false, max_unsent: o.max_unsent } })
129 }
130 }
131 }
132
133 fn pump(&mut self) {
135 let t = now();
136 match &mut self.io {
137 #[cfg(any(windows, target_os = "linux", target_vendor = "apple"))]
138 Io::Udp(u) => {
139 let got: Vec<Vec<u8>> = u.inbox.lock().drain(..).collect();
140 for d in got {
141 self.core.packet(&d, t);
142 }
143 }
144 Io::Ws { ws, started, .. } => {
145 if !*started && ws.state() == WsState::Open {
146 *started = true;
147 self.core.start(t);
148 }
149 while let Some(m) = ws.recv() {
150 if let WsMessage::Binary(b) = m {
151 self.core.packet(&b, t);
152 }
153 }
154 if ws.state() == WsState::Closed {
155 let code = ws.close_info().map(|c| c.0).unwrap_or(1006);
156 self.core.transport_closed(code);
157 }
158 }
159 }
160 self.core.tick(t);
161 self.flush();
162 }
163
164 fn flush(&mut self) {
165 while let Some(b) = self.core.take_out() {
166 match &self.io {
167 #[cfg(any(windows, target_os = "linux", target_vendor = "apple"))]
168 Io::Udp(u) => {
169 let _ = u.sock.send_to(&b, &u.server);
170 }
171 Io::Ws { ws, .. } => match ws.send_binary(&b) {
172 Ok(()) => {}
173 Err(Error::Backlog) => {
179 ws.close(CLOSE_BACKLOG, "backlog");
180 self.core.transport_closed(CLOSE_BACKLOG);
181 while self.core.take_out().is_some() {}
182 return;
183 }
184 Err(_) => {
186 while self.core.take_out().is_some() {}
187 return;
188 }
189 },
190 }
191 }
192 }
193
194 pub fn poll(&mut self) -> Option<ClientEvent> {
197 if let Some(e) = self.core.poll_event() {
198 return Some(e);
199 }
200 self.pump();
201 self.core.poll_event()
202 }
203
204 pub fn send(&mut self, payload: &[u8]) -> Result<u16, Error> {
207 let backlog = match &self.io {
208 Io::Ws { ws, max_unsent, .. } => ws.unsent() + payload.len() + DATA_HEADER > *max_unsent,
209 #[cfg(any(windows, target_os = "linux", target_vendor = "apple"))]
210 Io::Udp(_) => false,
211 };
212 if backlog {
213 return Err(Error::Backlog);
214 }
215 let seq = self.core.send(payload, now())?;
216 self.flush();
217 Ok(seq)
218 }
219
220 pub fn send_reliable(&mut self, payload: &[u8]) -> Result<(), Error> {
224 self.core.send_reliable(payload, now())?;
225 self.flush();
226 Ok(())
227 }
228
229 pub fn state(&self) -> State {
231 self.core.state()
232 }
233
234 pub fn reliable(&self) -> bool {
236 self.core.reliable()
237 }
238
239 pub fn max_payload(&self) -> usize {
241 self.core.max_payload()
242 }
243
244 pub fn stats(&self) -> Stats {
246 self.core.stats()
247 }
248
249 pub fn rtt_ms(&self) -> f32 {
251 self.core.stats().rtt_ms
252 }
253
254 pub fn disconnect(&mut self) {
256 self.core.disconnect();
257 self.flush();
258 match &self.io {
259 Io::Ws { ws, .. } => ws.close(1000, ""),
260 #[cfg(any(windows, target_os = "linux", target_vendor = "apple"))]
261 Io::Udp(_) => {}
262 }
263 }
264}
265
266impl Drop for Client {
267 fn drop(&mut self) {
268 if self.core.state() == State::Connected {
269 self.disconnect();
270 }
271 #[cfg(any(windows, target_os = "linux", target_vendor = "apple"))]
272 if let Io::Udp(u) = &self.io {
273 u.stop.store(true, Ordering::Release);
274 }
275 }
276}
277
278fn ws_random() -> [u8; 32] {
282 #[cfg(any(windows, target_os = "linux", target_vendor = "apple", target_os = "android"))]
283 {
284 plat::random_bytes::<32>()
285 }
286 #[cfg(not(any(windows, target_os = "linux", target_vendor = "apple", target_os = "android")))]
287 {
288 let mut r = [0u8; 32];
289 r[..8].copy_from_slice(&(plat::time_us() ^ 0x9e37_79b9_7f4a_7c15).to_le_bytes());
290 r
291 }
292}