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
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
use std::{
io::{self, Write},
pin::Pin,
sync::Arc,
task::{Context, Poll, Waker},
};
use futures::{AsyncRead, AsyncWrite};
use parking_lot::Mutex;
use super::State;
#[derive(Debug, Default, Clone)]
pub struct SubstreamState {
pub read_waker: Option<Waker>,
pub write_waker: Option<Waker>,
pub close_waker: Option<Waker>,
pub write_state: WriteState,
}
impl SubstreamState {
pub fn wake_all(&mut self) {
if let Some(waker) = self.read_waker.take() {
waker.wake();
}
if let Some(waker) = self.write_waker.take() {
waker.wake();
}
if let Some(waker) = self.close_waker.take() {
waker.wake();
}
}
}
#[derive(Debug)]
pub struct Substream {
id: quinn_proto::StreamId,
state: Arc<Mutex<State>>,
}
impl Substream {
pub fn new(id: quinn_proto::StreamId, state: Arc<Mutex<State>>) -> Self {
Self { id, state }
}
}
impl AsyncRead for Substream {
fn poll_read(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
mut buf: &mut [u8],
) -> Poll<io::Result<usize>> {
let mut state = self.state.lock();
let mut stream = state.connection.recv_stream(self.id);
let mut chunks = match stream.read(true) {
Ok(chunks) => chunks,
Err(quinn_proto::ReadableError::UnknownStream) => {
return Poll::Ready(Ok(0));
}
Err(quinn_proto::ReadableError::IllegalOrderedRead) => {
unreachable!(
"Illegal ordered read can only happen if `stream.read(false)` is used."
);
}
};
let mut bytes = 0;
let mut pending = false;
let mut error = None;
loop {
if buf.is_empty() {
break;
}
let chunk = match chunks.next(buf.len()) {
Ok(Some(chunk)) => chunk,
Ok(None) => break,
Err(err @ quinn_proto::ReadError::Reset(_)) => {
error = Some(Err(io::Error::new(io::ErrorKind::ConnectionReset, err)));
break;
}
Err(quinn_proto::ReadError::Blocked) => {
pending = true;
break;
}
};
buf.write_all(&chunk.bytes).expect("enough buffer space");
bytes += chunk.bytes.len();
}
if chunks.finalize().should_transmit() {
if let Some(waker) = state.poll_connection_waker.take() {
waker.wake();
}
}
if let Some(err) = error {
return Poll::Ready(err);
}
if pending && bytes == 0 {
let substream_state = state.unchecked_substream_state(self.id);
substream_state.read_waker = Some(cx.waker().clone());
return Poll::Pending;
}
Poll::Ready(Ok(bytes))
}
}
impl AsyncWrite for Substream {
fn poll_write(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &[u8],
) -> Poll<std::io::Result<usize>> {
let mut state = self.state.lock();
match state.connection.send_stream(self.id).write(buf) {
Ok(bytes) => {
if let Some(waker) = state.poll_connection_waker.take() {
waker.wake();
}
Poll::Ready(Ok(bytes))
}
Err(quinn_proto::WriteError::Blocked) => {
let substream_state = state.unchecked_substream_state(self.id);
substream_state.write_waker = Some(cx.waker().clone());
Poll::Pending
}
Err(err @ quinn_proto::WriteError::Stopped(_)) => {
Poll::Ready(Err(io::Error::new(io::ErrorKind::ConnectionReset, err)))
}
Err(quinn_proto::WriteError::UnknownStream) => {
Poll::Ready(Err(io::ErrorKind::BrokenPipe.into()))
}
}
}
fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
Poll::Ready(Ok(()))
}
fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
let mut inner = self.state.lock();
let substream_state = inner.unchecked_substream_state(self.id);
match substream_state.write_state {
WriteState::Open => {}
WriteState::Closing => {
substream_state.close_waker = Some(cx.waker().clone());
return Poll::Pending;
}
WriteState::Closed => return Poll::Ready(Ok(())),
WriteState::Stopped => {
let err = quinn_proto::FinishError::Stopped(0u32.into());
return Poll::Ready(Err(io::Error::new(io::ErrorKind::ConnectionReset, err)));
}
}
match inner.connection.send_stream(self.id).finish() {
Ok(()) => {
let substream_state = inner.unchecked_substream_state(self.id);
substream_state.close_waker = Some(cx.waker().clone());
substream_state.write_state = WriteState::Closing;
Poll::Pending
}
Err(err @ quinn_proto::FinishError::Stopped(_)) => {
Poll::Ready(Err(io::Error::new(io::ErrorKind::ConnectionReset, err)))
}
Err(quinn_proto::FinishError::UnknownStream) => {
Poll::Ready(Ok(()))
}
}
}
}
impl Drop for Substream {
fn drop(&mut self) {
let mut state = self.state.lock();
state.substreams.remove(&self.id);
let mut is_read_done = false;
if let Ok(mut chunks) = state.connection.recv_stream(self.id).read(true) {
if let Ok(chunk) = chunks.next(0) {
is_read_done = chunk.is_none();
}
let _ = chunks.finalize();
}
if !is_read_done {
let _ = state.connection.recv_stream(self.id).stop(0u32.into());
}
let mut send_stream = state.connection.send_stream(self.id);
match send_stream.finish() {
Ok(()) => {}
Err(quinn_proto::FinishError::UnknownStream) => {}
Err(quinn_proto::FinishError::Stopped(reason)) => {
let _ = send_stream.reset(reason);
}
}
}
}
#[derive(Debug, Default, Clone)]
pub enum WriteState {
#[default]
Open,
Closing,
Closed,
Stopped,
}