1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
use futures::{AsyncRead, AsyncWrite, Sink, Stream};
use smallvec::SmallVec;
use crate::{
Negotiated, NegotiationError, ProtocolError,
protocol::{Message, MessageIO, Protocol},
};
use std::{
mem,
pin::Pin,
task::{Context, Poll},
};
#[pin_project::pin_project]
pub struct ListenerSelectFuture<R, N> {
// 使用 smallvec, 在堆上分配内存之前,它会在栈上存储一定数量的元素。
protocols: SmallVec<[(N, Protocol); 8]>,
state: State<R, N>,
}
impl<R, N> ListenerSelectFuture<R, N>
where
R: AsyncRead + AsyncWrite + Unpin,
N: AsRef<str> + Clone,
{
pub fn new<I>(io: R, protocols: I) -> Self
where
I: Iterator<Item = N>,
{
let protocols =
protocols
.into_iter()
.filter_map(|n| match Protocol::try_from(n.as_ref()) {
Ok(p) => Some((n, p)),
Err(_) => None,
});
ListenerSelectFuture {
protocols: SmallVec::from_iter(protocols),
state: State::RecvMessage {
io: MessageIO::new(io),
},
}
}
}
enum State<R, N> {
RecvMessage {
io: MessageIO<R>,
},
SendMessage {
io: MessageIO<R>,
message: Message,
protocol: Option<N>,
},
Flush {
io: MessageIO<R>,
protocol: Option<N>,
},
Done,
}
impl<R, N> Future for ListenerSelectFuture<R, N>
where
R: AsyncRead + AsyncWrite + Unpin,
N: AsRef<str> + Clone,
{
type Output = Result<(N, Negotiated<R>), NegotiationError>;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = self.project();
loop {
match mem::replace(this.state, State::Done) {
State::RecvMessage { mut io } => {
let msg = match Pin::new(&mut io).poll_next(cx)? {
Poll::Ready(Some(msg)) => msg,
Poll::Ready(None) => {
return Poll::Ready(Err(NegotiationError::Failed));
}
Poll::Pending => {
*this.state = State::RecvMessage { io };
return Poll::Pending;
}
};
tracing::debug!("Received message: {:?}", msg);
match msg {
Message::Protocol(p) => {
// 查找匹配的协议
let protocol = this.protocols.iter().find_map(|(name, proto)| {
if &p == proto {
Some(name.clone())
} else {
None
}
});
let message = if protocol.is_some() {
Message::Protocol(p.clone())
} else {
Message::NotAvailable
};
*this.state = State::SendMessage {
io,
message,
protocol,
};
}
_ => return Poll::Ready(Err(ProtocolError::InvalidMessage.into())),
}
}
State::SendMessage {
mut io,
message,
protocol,
} => {
match Pin::new(&mut io).poll_ready(cx)? {
Poll::Ready(()) => {}
Poll::Pending => {
*this.state = State::SendMessage {
io,
message,
protocol,
};
return Poll::Pending;
}
};
if let Err(err) = Pin::new(&mut io).start_send(message) {
return Poll::Ready(Err(From::from(err)));
}
*this.state = State::Flush { io, protocol };
}
State::Flush { mut io, protocol } => {
match Pin::new(&mut io).poll_flush(cx)? {
Poll::Ready(()) => {}
Poll::Pending => {
*this.state = State::Flush { io, protocol };
return Poll::Pending;
}
};
if let Some(protocol) = protocol {
// 协议匹配成功,返回 Negotiated
let io = Negotiated::completed(io.into_inner());
tracing::trace!(
"Negotiation successful for protocol: {}",
protocol.as_ref()
);
return Poll::Ready(Ok((protocol, io)));
} else {
// 如果没有匹配的协议,继续接收消息
*this.state = State::RecvMessage { io }
}
}
_ => panic!("Unexpected state in ListenerSelectFuture"),
}
}
}
}