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(crate) async fn ws_ping(&self) -> Result<()> {
100 match self {
101 Transport::Polling(_) => Ok(()),
102 Transport::Websocket(t) => t.ping().await,
103 }
104 }
105
106 pub fn kind(&self) -> TransportKind {
107 match self {
108 Transport::Polling(_) => TransportKind::Polling,
109 Transport::Websocket(_) => TransportKind::Websocket,
110 }
111 }
112}
113
114impl Stream for Transport {
115 type Item = Result<Frame>;
116
117 fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
118 match self.get_mut() {
119 Transport::Polling(t) => t
120 .poll_next_unpin(cx)
121 .map(|item| item.map(|r| r.map(Frame::Text))),
122 Transport::Websocket(t) => t.poll_next_unpin(cx),
123 }
124 }
125}