1use alloc::string::String;
16use alloc::vec::Vec;
17
18use crate::Error;
19
20#[derive(Clone, Copy, Debug, PartialEq, Eq)]
22pub enum WsState {
23 Connecting,
25 Open,
27 Closing,
29 Closed,
31}
32
33#[derive(Clone, Debug, PartialEq, Eq)]
35pub enum WsMessage {
36 Text(String),
38 Binary(Vec<u8>),
40}
41
42#[derive(Clone, Copy, Debug)]
44pub struct WsOptions {
45 pub max_message: usize,
47 pub max_queued: usize,
49 pub max_unsent: usize,
51 pub connect_ms: u32,
53 pub idle_ms: u32,
55 pub ping_ms: u32,
57}
58
59impl Default for WsOptions {
60 fn default() -> Self {
61 WsOptions { max_message: 1 << 20, max_queued: 8 << 20, max_unsent: 4 << 20, connect_ms: 10_000, idle_ms: 60_000, ping_ms: 20_000 }
62 }
63}
64
65fn host_port(url: &str) -> Option<(String, u16)> {
67 let (scheme, rest) = url.split_once("://")?;
68 let default = if scheme.eq_ignore_ascii_case("ws") {
69 80
70 } else if scheme.eq_ignore_ascii_case("wss") {
71 443
72 } else {
73 return None;
74 };
75 let auth = &rest[..rest.find(['/', '?']).unwrap_or(rest.len())];
76 let (host, port) = if let Some(r) = auth.strip_prefix('[') {
77 r.split_once(']')?
78 } else {
79 match auth.find(':') {
80 Some(i) => (&auth[..i], &auth[i..]),
81 None => (auth, ""),
82 }
83 };
84 let port = match port.strip_prefix(':') {
85 Some(p) => p.parse().ok()?,
86 None if port.is_empty() => default,
87 None => return None,
88 };
89 (!host.is_empty()).then(|| (String::from(host), port))
90}
91
92#[cfg(target_arch = "wasm32")]
95mod imp {
96 use super::*;
97 use plat::net::{WsLimits, WsMessage as PMsg, WsState as PState};
98
99 pub struct Inner(plat::net::WebSocket);
100
101 impl Inner {
102 pub fn connect(url: &str, o: WsOptions) -> Result<Inner, Error> {
103 plat::net::WebSocket::connect_with(url, WsLimits { max_message: o.max_message, max_queued: o.max_queued }).map(Inner).map_err(|e| {
104 if e.kind == plat::net::NetErrorKind::Other { Error::Url(String::from(url)) } else { Error::Net(e) }
105 })
106 }
107
108 pub fn state(&self) -> WsState {
109 match self.0.state() {
110 PState::Connecting => WsState::Connecting,
111 PState::Open => WsState::Open,
112 PState::Closing => WsState::Closing,
113 PState::Closed => WsState::Closed,
114 }
115 }
116
117 pub fn send(&self, text: bool, data: &[u8]) -> Result<(), Error> {
118 let r = if text { self.0.send_text(core::str::from_utf8(data).map_err(|_| Error::Size)?) } else { self.0.send_binary(data) };
119 r.map_err(|_| Error::NotConnected)
120 }
121
122 pub fn recv(&self) -> Option<WsMessage> {
123 self.0.recv().map(|m| match m {
124 PMsg::Text(t) => WsMessage::Text(t),
125 PMsg::Binary(b) => WsMessage::Binary(b),
126 })
127 }
128
129 pub fn close(&self, code: u16, reason: &str) {
130 self.0.close(code, reason)
131 }
132
133 pub fn close_info(&self) -> Option<(u16, String)> {
134 self.0.close_info()
135 }
136
137 pub fn unsent(&self) -> usize {
138 0
139 }
140 }
141}
142
143#[cfg(any(windows, target_os = "linux", target_vendor = "apple"))]
146mod imp {
147 use super::*;
148 use alloc::collections::VecDeque;
149 use alloc::sync::Arc;
150 use core::sync::atomic::{AtomicU64, AtomicU8, Ordering};
151 use netio::ws::{self as nws, Message, WsError};
152 use plat::sync::{Condvar, Mutex};
153
154 const CONNECTING: u8 = 0;
155 const OPEN: u8 = 1;
156 const CLOSING: u8 = 2;
157 const CLOSED: u8 = 3;
158
159 struct Outbox {
160 q: VecDeque<(bool, Vec<u8>)>,
161 bytes: usize,
162 close: Option<(u16, String)>,
163 gone: bool,
164 }
165
166 struct Shared {
167 state: AtomicU8,
168 closing_since: AtomicU64,
169 inbox: Mutex<(VecDeque<WsMessage>, usize)>,
170 out: Mutex<Outbox>,
171 cv: Condvar,
172 end: Mutex<Option<(u16, String)>>,
173 o: WsOptions,
174 }
175
176 impl Shared {
177 fn finish(&self, code: u16, reason: String) {
178 let mut e = self.end.lock();
179 if e.is_none() {
180 *e = Some((code, reason));
181 }
182 drop(e);
183 self.state.store(CLOSED, Ordering::Release);
184 let mut o = self.out.lock();
185 o.gone = true;
186 drop(o);
187 self.cv.notify_all();
188 plat::wake();
189 }
190
191 fn request_close(&self, code: u16, reason: &str) {
192 let mut o = self.out.lock();
193 if o.close.is_none() {
194 o.close = Some((code, String::from(reason)));
195 }
196 drop(o);
197 let _ = self.state.compare_exchange(OPEN, CLOSING, Ordering::AcqRel, Ordering::Acquire);
198 let _ = self.state.compare_exchange(CONNECTING, CLOSING, Ordering::AcqRel, Ordering::Acquire);
199 let _ = self.closing_since.compare_exchange(0, plat::time_us().max(1), Ordering::AcqRel, Ordering::Acquire);
200 self.cv.notify_all();
201 }
202 }
203
204 pub struct Inner(Arc<Shared>);
205
206 impl Inner {
207 pub fn connect(url: &str, o: WsOptions) -> Result<Inner, Error> {
208 if nws::parse_url(url).is_none() {
209 return Err(Error::Url(String::from(url)));
210 }
211 let sh = Arc::new(Shared {
212 state: AtomicU8::new(CONNECTING),
213 closing_since: AtomicU64::new(0),
214 inbox: Mutex::new((VecDeque::new(), 0)),
215 out: Mutex::new(Outbox { q: VecDeque::new(), bytes: 0, close: None, gone: false }),
216 cv: Condvar::new(),
217 end: Mutex::new(None),
218 o,
219 });
220 let s = sh.clone();
221 let url = String::from(url);
222 if !crate::reap::spawn(256 * 1024, move || reader(s, url)) {
223 return Err(Error::Net(plat::net::NetError::new(plat::net::NetErrorKind::Other, 0)));
224 }
225 Ok(Inner(sh))
226 }
227
228 pub fn state(&self) -> WsState {
229 match self.0.state.load(Ordering::Acquire) {
230 CONNECTING => WsState::Connecting,
231 OPEN => WsState::Open,
232 CLOSING => WsState::Closing,
233 _ => WsState::Closed,
234 }
235 }
236
237 pub fn send(&self, text: bool, data: &[u8]) -> Result<(), Error> {
238 if self.0.state.load(Ordering::Acquire) != OPEN {
239 return Err(Error::NotConnected);
240 }
241 if text && core::str::from_utf8(data).is_err() {
242 return Err(Error::Size);
243 }
244 let mut o = self.0.out.lock();
245 if o.bytes + data.len() > self.0.o.max_unsent {
246 return Err(Error::Backlog);
247 }
248 o.bytes += data.len();
249 o.q.push_back((text, Vec::from(data)));
250 drop(o);
251 self.0.cv.notify_all();
252 Ok(())
253 }
254
255 pub fn recv(&self) -> Option<WsMessage> {
256 let mut i = self.0.inbox.lock();
257 let m = i.0.pop_front()?;
258 i.1 -= match &m {
259 WsMessage::Text(t) => t.len(),
260 WsMessage::Binary(b) => b.len(),
261 };
262 Some(m)
263 }
264
265 pub fn close(&self, code: u16, reason: &str) {
266 self.0.request_close(code, reason);
267 }
268
269 pub fn close_info(&self) -> Option<(u16, String)> {
270 if self.0.state.load(Ordering::Acquire) == CLOSED { self.0.end.lock().clone() } else { None }
271 }
272
273 pub fn unsent(&self) -> usize {
274 self.0.out.lock().bytes
275 }
276 }
277
278 impl Drop for Inner {
279 fn drop(&mut self) {
280 if self.0.state.load(Ordering::Acquire) != CLOSED {
281 self.0.request_close(nws::CLOSE_NORMAL, "");
282 }
283 }
284 }
285
286 fn end_of(e: &WsError) -> (u16, String) {
287 match e {
288 WsError::Closed(c, r) => (*c, r.clone()),
289 WsError::Protocol(c) => (*c, String::from("protocol error")),
290 WsError::TimedOut => (nws::CLOSE_GOING_AWAY, String::from("timed out")),
291 other => (nws::CLOSE_ABNORMAL, alloc::format!("{}", other)),
292 }
293 }
294
295 fn reader(sh: Arc<Shared>, url: String) {
297 let cfg = nws::ClientConfig {
298 limits: nws::Limits {
299 max_message: sh.o.max_message,
300 max_frame: sh.o.max_message,
301 idle_ms: sh.o.idle_ms,
302 ping_ms: sh.o.ping_ms,
303 handshake_ms: sh.o.connect_ms,
304 ..nws::Limits::default()
305 },
306 connect_ms: sh.o.connect_ms,
307 ..nws::ClientConfig::default()
308 };
309 let ws = match nws::connect(&url, &cfg) {
310 Ok(ws) => Arc::new(ws),
311 Err(e) => {
312 let (c, r) = end_of(&e);
313 sh.finish(c, r);
314 return;
315 }
316 };
317 if sh.state.compare_exchange(CONNECTING, OPEN, Ordering::AcqRel, Ordering::Acquire).is_ok() {
318 plat::wake();
319 }
320 let (s, w) = (sh.clone(), ws.clone());
321 if !crate::reap::spawn(128 * 1024, move || writer(s, w)) {
322 ws.close(nws::CLOSE_INTERNAL, "");
323 sh.finish(nws::CLOSE_INTERNAL, String::from("no writer thread"));
324 return;
325 }
326 loop {
327 match ws.recv_timeout(Some(200)) {
328 Ok(Some(m)) => {
329 let n = m.bytes().len();
330 let mut i = sh.inbox.lock();
331 if i.1 + n > sh.o.max_queued {
332 drop(i);
333 sh.request_close(nws::CLOSE_TOO_BIG, "queue over the limit");
334 continue;
335 }
336 i.1 += n;
337 i.0.push_back(match m {
338 Message::Text(t) => WsMessage::Text(t),
339 Message::Binary(b) => WsMessage::Binary(b),
340 });
341 drop(i);
342 plat::wake();
343 }
344 Ok(None) => {
345 let since = sh.closing_since.load(Ordering::Acquire);
347 if since != 0 && plat::time_us().saturating_sub(since) > 1_000_000 {
348 let (c, r) = sh.out.lock().close.clone().unwrap_or((nws::CLOSE_NORMAL, String::new()));
349 sh.finish(c, r);
350 return;
351 }
352 }
353 Err(e) => {
354 let (c, r) = end_of(&e);
355 sh.finish(c, r);
356 return;
357 }
358 }
359 }
360 }
361
362 fn writer(sh: Arc<Shared>, ws: Arc<nws::WebSocket>) {
364 loop {
365 let job = {
366 let mut o = sh.out.lock();
367 loop {
368 if let Some(item) = o.q.pop_front() {
369 o.bytes -= item.1.len();
370 break Some(item);
371 }
372 if o.close.is_some() || o.gone {
373 break None;
374 }
375 o = sh.cv.wait_timeout(o, Some(1000)).0;
376 }
377 };
378 match job {
379 Some((text, data)) => {
380 let r = if text { ws.send_text(core::str::from_utf8(&data).unwrap_or("")) } else { ws.send_binary(&data) };
381 if r.is_err() {
382 return;
383 }
384 }
385 None => {
386 let close = sh.out.lock().close.clone();
387 if let Some((c, r)) = close {
388 ws.close(c, &r);
389 }
390 return;
391 }
392 }
393 }
394 }
395}
396
397#[cfg(not(any(target_arch = "wasm32", windows, target_os = "linux", target_vendor = "apple")))]
400mod imp {
401 use super::*;
402
403 pub struct Inner;
404
405 impl Inner {
406 pub fn connect(_url: &str, _o: WsOptions) -> Result<Inner, Error> {
407 Err(Error::Unsupported)
408 }
409 pub fn state(&self) -> WsState {
410 WsState::Closed
411 }
412 pub fn send(&self, _text: bool, _data: &[u8]) -> Result<(), Error> {
413 Err(Error::Unsupported)
414 }
415 pub fn recv(&self) -> Option<WsMessage> {
416 None
417 }
418 pub fn close(&self, _code: u16, _reason: &str) {}
419 pub fn close_info(&self) -> Option<(u16, String)> {
420 None
421 }
422 pub fn unsent(&self) -> usize {
423 0
424 }
425 }
426}
427
428pub struct WebSocket {
430 inner: imp::Inner,
431}
432
433impl WebSocket {
434 pub fn connect(url: &str) -> Result<WebSocket, Error> {
436 WebSocket::connect_with(url, WsOptions::default())
437 }
438
439 pub fn connect_with(url: &str, o: WsOptions) -> Result<WebSocket, Error> {
441 if let Some((host, port)) = host_port(url) {
443 if !plat::policy::net_host_allowed(&host, port) {
444 return Err(Error::Net(plat::net::NetError::new(plat::net::NetErrorKind::Denied, 0)));
445 }
446 } else if !(cfg!(target_arch = "wasm32") && url.starts_with('/')) {
447 return Err(Error::Url(String::from(url)));
448 }
449 imp::Inner::connect(url, o).map(|inner| WebSocket { inner })
450 }
451
452 pub fn state(&self) -> WsState {
454 self.inner.state()
455 }
456
457 pub fn send_text(&self, s: &str) -> Result<(), Error> {
459 self.inner.send(true, s.as_bytes())
460 }
461
462 pub fn send_binary(&self, b: &[u8]) -> Result<(), Error> {
464 self.inner.send(false, b)
465 }
466
467 pub fn recv(&self) -> Option<WsMessage> {
469 self.inner.recv()
470 }
471
472 pub fn close(&self, code: u16, reason: &str) {
474 self.inner.close(code, reason)
475 }
476
477 pub fn close_info(&self) -> Option<(u16, String)> {
480 self.inner.close_info()
481 }
482
483 pub fn unsent(&self) -> usize {
485 self.inner.unsent()
486 }
487}