socketio_next/engineio/
transport.rs1use std::fmt;
2use std::pin::Pin;
3use std::task::{Context, Poll};
4
5use bytes::Bytes;
6use futures_util::{Stream, StreamExt};
7use url::Url;
8
9use crate::engineio::error::Result;
10use crate::engineio::transports::{PollingTransport, WebsocketTransport};
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
14#[non_exhaustive]
15pub enum TransportKind {
16 Polling,
18 Websocket,
20}
21
22impl TransportKind {
23 pub fn as_str(self) -> &'static str {
25 match self {
26 TransportKind::Polling => "polling",
27 TransportKind::Websocket => "websocket",
28 }
29 }
30
31 pub(crate) fn is_polling(self) -> bool {
32 self == TransportKind::Polling
33 }
34}
35
36impl fmt::Display for TransportKind {
37 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
38 f.write_str(self.as_str())
39 }
40}
41
42#[derive(Debug, Clone, PartialEq, Eq)]
45#[non_exhaustive]
46pub enum Frame {
47 Text(Bytes),
49 Binary(Bytes),
51}
52
53impl From<Bytes> for Frame {
54 fn from(bytes: Bytes) -> Self {
55 Frame::Text(bytes)
56 }
57}
58
59#[derive(Debug, Clone)]
61#[non_exhaustive]
62pub enum Transport {
63 Polling(PollingTransport),
65 Websocket(WebsocketTransport),
67}
68
69impl From<PollingTransport> for Transport {
70 fn from(transport: PollingTransport) -> Self {
71 Transport::Polling(transport)
72 }
73}
74
75impl From<WebsocketTransport> for Transport {
76 fn from(transport: WebsocketTransport) -> Self {
77 Transport::Websocket(transport)
78 }
79}
80
81impl Transport {
82 pub async fn emit(&self, data: Bytes, is_binary_att: bool) -> Result<()> {
84 match self {
85 Transport::Polling(t) => t.emit(data, is_binary_att).await,
86 Transport::Websocket(t) => t.emit(data, is_binary_att).await,
87 }
88 }
89
90 pub async fn base_url(&self) -> Result<Url> {
92 match self {
93 Transport::Polling(t) => t.base_url().await,
94 Transport::Websocket(t) => t.base_url().await,
95 }
96 }
97
98 pub async fn set_base_url(&self, url: Url) -> Result<()> {
100 match self {
101 Transport::Polling(t) => t.set_base_url(url).await,
102 Transport::Websocket(t) => t.set_base_url(url).await,
103 }
104 }
105
106 pub(crate) async fn ws_ping(&self) -> Result<()> {
109 match self {
110 Transport::Polling(_) => Ok(()),
111 Transport::Websocket(t) => t.ping().await,
112 }
113 }
114
115 pub fn kind(&self) -> TransportKind {
116 match self {
117 Transport::Polling(_) => TransportKind::Polling,
118 Transport::Websocket(_) => TransportKind::Websocket,
119 }
120 }
121}
122
123impl Stream for Transport {
124 type Item = Result<Frame>;
125
126 fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
127 match self.get_mut() {
128 Transport::Polling(t) => t
129 .poll_next_unpin(cx)
130 .map(|item| item.map(|r| r.map(Frame::Text))),
131 Transport::Websocket(t) => t.poll_next_unpin(cx),
132 }
133 }
134}