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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
mod control;
mod stream;
use crate::{
Config,
DEFAULT_CREDIT,
WindowUpdateMode,
error::ConnectionError,
frame::{self, Frame},
frame::header::{self, CONNECTION_ID, Data, GoAway, Header, Ping, StreamId, Tag, WindowUpdate},
pause::Pausable
};
use futures::{
channel::{mpsc, oneshot},
future::{self, Either},
prelude::*,
stream::{Fuse, FusedStream}
};
use nohash_hasher::IntMap;
use std::{fmt, sync::Arc, task::{Context, Poll}};
pub use control::Control;
pub use stream::{Packet, State, Stream};
const MAX_COMMAND_BACKLOG: usize = 32;
type Result<T> = std::result::Result<T, ConnectionError>;
#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
pub enum Mode {
Client,
Server
}
#[derive(Clone, Copy)]
pub(crate) struct Id(u32);
impl Id {
pub(crate) fn random() -> Self {
Id(rand::random())
}
}
impl fmt::Debug for Id {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:08x}", self.0)
}
}
impl fmt::Display for Id {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:08x}", self.0)
}
}
pub struct Connection<T> {
id: Id,
mode: Mode,
config: Arc<Config>,
socket: Fuse<frame::Io<T>>,
next_id: u32,
streams: IntMap<StreamId, Stream>,
control_sender: mpsc::Sender<ControlCommand>,
control_receiver: Pausable<mpsc::Receiver<ControlCommand>>,
stream_sender: mpsc::Sender<StreamCommand>,
stream_receiver: mpsc::Receiver<StreamCommand>,
garbage: Vec<StreamId>,
shutdown: Shutdown,
is_closed: bool
}
#[derive(Debug)]
pub(crate) enum ControlCommand {
OpenStream(oneshot::Sender<Result<Stream>>),
CloseConnection(oneshot::Sender<()>)
}
#[derive(Debug)]
pub(crate) enum StreamCommand {
SendFrame(Frame<Either<Data, WindowUpdate>>),
CloseStream { id: StreamId, ack: bool }
}
#[derive(Debug)]
enum Action {
None,
New(Stream, Option<Frame<WindowUpdate>>),
Update(Frame<WindowUpdate>),
Ping(Frame<Ping>),
Reset(Frame<Data>),
Terminate(Frame<GoAway>)
}
#[derive(Debug)]
enum Shutdown {
NotStarted,
InProgress(oneshot::Sender<()>),
Complete
}
impl Shutdown {
fn has_not_started(&self) -> bool {
if let Shutdown::NotStarted = self {
true
} else {
false
}
}
fn is_in_progress(&self) -> bool {
if let Shutdown::InProgress(_) = self {
true
} else {
false
}
}
fn is_complete(&self) -> bool {
if let Shutdown::Complete = self {
true
} else {
false
}
}
}
impl<T> fmt::Debug for Connection<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("Connection")
.field("id", &self.id)
.field("mode", &self.mode)
.field("streams", &self.streams.len())
.field("next_id", &self.next_id)
.field("is_closed", &self.is_closed)
.finish()
}
}
impl<T> fmt::Display for Connection<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "(Connection {} {:?} (streams {}))", self.id, self.mode, self.streams.len())
}
}
impl<T: AsyncRead + AsyncWrite + Unpin> Connection<T> {
pub fn new(socket: T, cfg: Config, mode: Mode) -> Self {
let id = Id::random();
log::debug!("new connection: {} ({:?})", id, mode);
let (stream_sender, stream_receiver) = mpsc::channel(MAX_COMMAND_BACKLOG);
let (control_sender, control_receiver) = mpsc::channel(MAX_COMMAND_BACKLOG);
let socket = frame::Io::new(id, socket, cfg.max_buffer_size).fuse();
Connection {
id,
mode,
config: Arc::new(cfg),
socket,
streams: IntMap::default(),
control_sender,
control_receiver: Pausable::new(control_receiver),
stream_sender,
stream_receiver,
next_id: match mode {
Mode::Client => 1,
Mode::Server => 2
},
garbage: Vec::new(),
shutdown: Shutdown::NotStarted,
is_closed: false
}
}
pub fn control(&self) -> Control {
Control::new(self.control_sender.clone())
}
pub async fn next_stream(&mut self) -> Result<Option<Stream>> {
if self.is_closed {
log::debug!("{}: connection is closed", self.id);
return Ok(None)
}
let result = self.next().await;
if let Ok(Some(_)) = result {
return result
}
self.is_closed = true;
if !self.control_receiver.stream().is_terminated() {
self.control_receiver.stream().close();
self.control_receiver.unpause();
while let Some(cmd) = self.control_receiver.next().await {
match cmd {
ControlCommand::OpenStream(reply) => {
let _ = reply.send(Err(ConnectionError::Closed));
}
ControlCommand::CloseConnection(reply) => {
let _ = reply.send(());
}
}
}
}
self.drop_all_streams();
if !self.stream_receiver.is_terminated() {
self.stream_receiver.close();
while let Some(_cmd) = self.stream_receiver.next().await {
}
}
if let Err(ConnectionError::Closed) = result {
return Ok(None)
}
result
}
async fn next(&mut self) -> Result<Option<Stream>> {
loop {
self.garbage_collect().await?;
let mut num_terminated = 0;
let mut next_inbound_frame =
if self.socket.is_terminated() {
num_terminated += 1;
Either::Left(future::pending())
} else {
Either::Right(self.socket.try_next().err_into())
};
let mut next_stream_command =
if self.stream_receiver.is_terminated() {
num_terminated += 1;
Either::Left(future::pending())
} else {
Either::Right(self.stream_receiver.next())
};
let mut next_control_command =
if self.control_receiver.is_terminated() {
num_terminated += 1;
Either::Left(future::pending())
} else {
Either::Right(self.control_receiver.next())
};
if num_terminated == 3 {
log::debug!("{}: socket and channels are terminated", self.id);
return Err(ConnectionError::Closed)
}
let next_item =
future::poll_fn(move |cx: &mut Context| {
let a = next_stream_command.poll_unpin(cx);
let b = next_control_command.poll_unpin(cx);
let c = next_inbound_frame.poll_unpin(cx);
if a.is_pending() && b.is_pending() && c.is_pending() {
return Poll::Pending
}
Poll::Ready((a, b, c))
});
let (stream_command, control_command, inbound_frame) = next_item.await;
if let Poll::Ready(cmd) = control_command {
self.on_control_command(cmd).await?
}
if let Poll::Ready(cmd) = stream_command {
self.on_stream_command(cmd).await?
}
if let Poll::Ready(frame) = inbound_frame {
if let Some(stream) = self.on_frame(frame).await? {
self.socket.get_mut().flush().await.or(Err(ConnectionError::Closed))?;
return Ok(Some(stream))
}
}
self.socket.get_mut().flush().await.or(Err(ConnectionError::Closed))?
}
}
async fn on_control_command(&mut self, cmd: Option<ControlCommand>) -> Result<()> {
match cmd {
Some(ControlCommand::OpenStream(reply)) => {
if self.shutdown.is_complete() {
let _ = reply.send(Err(ConnectionError::Closed));
return Ok(())
}
if self.streams.len() >= self.config.max_num_streams {
log::error!("{}: maximum number of streams reached", self.id);
let _ = reply.send(Err(ConnectionError::TooManyStreams));
return Ok(())
}
log::trace!("{}: creating new outbound stream", self.id);
let id = self.next_stream_id()?;
let extra_credit = self.config.receive_window - DEFAULT_CREDIT;
if extra_credit > 0 {
let mut frame = Frame::window_update(id, extra_credit);
frame.header_mut().syn();
log::trace!("{}: sending initial {}", self.id, frame.header());
self.socket.get_mut().send(&frame).await.or(Err(ConnectionError::Closed))?
}
let stream = {
let config = self.config.clone();
let sender = self.stream_sender.clone();
let window = self.config.receive_window;
let mut stream = Stream::new(id, self.id, config, window, DEFAULT_CREDIT, sender);
if extra_credit == 0 {
stream.set_flag(stream::Flag::Syn)
}
stream
};
if reply.send(Ok(stream.clone())).is_ok() {
log::debug!("{}: new outbound {} of {}", self.id, stream, self);
self.streams.insert(id, stream);
} else {
log::debug!("{}: open stream {} has been cancelled", self.id, id);
if extra_credit > 0 {
let mut header = Header::data(id, 0);
header.rst();
let frame = Frame::new(header);
self.socket.get_mut().send(&frame).await.or(Err(ConnectionError::Closed))?
}
}
}
Some(ControlCommand::CloseConnection(reply)) => {
if self.shutdown.is_complete() {
let _ = reply.send(());
return Ok(())
}
debug_assert!(self.shutdown.has_not_started());
self.shutdown = Shutdown::InProgress(reply);
log::trace!("{}: shutting down connection", self.id);
self.control_receiver.pause();
self.stream_receiver.close()
}
None => {
debug_assert!(self.shutdown.is_complete());
self.socket.get_mut().close().await.or(Err(ConnectionError::Closed))?;
return Err(ConnectionError::Closed)
}
}
Ok(())
}
async fn on_stream_command(&mut self, cmd: Option<StreamCommand>) -> Result<()> {
match cmd {
Some(StreamCommand::SendFrame(frame)) => {
log::trace!("{}: sending: {}", self.id, frame.header());
self.socket.get_mut().send(&frame).await.or(Err(ConnectionError::Closed))?
}
Some(StreamCommand::CloseStream { id, ack }) => {
log::trace!("{}: closing stream {} of {}", self.id, id, self);
let mut header = Header::data(id, 0);
header.fin();
if ack { header.ack() }
let frame = Frame::new(header);
self.socket.get_mut().send(&frame).await.or(Err(ConnectionError::Closed))?
}
None => {
debug_assert!(self.shutdown.is_in_progress());
log::debug!("{}: closing {}", self.id, self);
let frame = Frame::term();
self.socket.get_mut().send(&frame).await.or(Err(ConnectionError::Closed))?;
let shutdown = std::mem::replace(&mut self.shutdown, Shutdown::Complete);
if let Shutdown::InProgress(tx) = shutdown {
let _ = tx.send(());
}
debug_assert!(self.control_receiver.is_paused());
self.control_receiver.unpause();
self.control_receiver.stream().close()
}
}
Ok(())
}
async fn on_frame(&mut self, frame: Result<Option<Frame<()>>>) -> Result<Option<Stream>> {
match frame {
Ok(Some(frame)) => {
log::trace!("{}: received: {}", self.id, frame.header());
let action = match frame.header().tag() {
Tag::Data => self.on_data(frame.into_data()),
Tag::WindowUpdate => self.on_window_update(&frame.into_window_update()),
Tag::Ping => self.on_ping(&frame.into_ping()),
Tag::GoAway => return Err(ConnectionError::Closed)
};
match action {
Action::None => {}
Action::New(stream, update) => {
log::trace!("{}: new inbound {} of {}", self.id, stream, self);
if let Some(f) = update {
log::trace!("{}/{}: sending update", self.id, f.header().stream_id());
self.socket.get_mut().send(&f).await.or(Err(ConnectionError::Closed))?
}
return Ok(Some(stream))
}
Action::Update(f) => {
log::trace!("{}/{}: sending update", self.id, f.header().stream_id());
self.socket.get_mut().send(&f).await.or(Err(ConnectionError::Closed))?
}
Action::Ping(f) => {
log::trace!("{}/{}: pong", self.id, f.header().stream_id());
self.socket.get_mut().send(&f).await.or(Err(ConnectionError::Closed))?
}
Action::Reset(f) => {
log::trace!("{}/{}: sending reset", self.id, f.header().stream_id());
self.socket.get_mut().send(&f).await.or(Err(ConnectionError::Closed))?
}
Action::Terminate(f) => {
log::trace!("{}: sending term", self.id);
self.socket.get_mut().send(&f).await.or(Err(ConnectionError::Closed))?
}
}
Ok(None)
}
Ok(None) => {
log::debug!("{}: socket eof", self.id);
Err(ConnectionError::Closed)
}
Err(e) if e.io_kind() == Some(std::io::ErrorKind::ConnectionReset) => {
log::debug!("{}: connection reset", self.id);
Err(ConnectionError::Closed)
}
Err(e) => {
log::error!("{}: socket error: {}", self.id, e);
Err(e)
}
}
}
fn on_data(&mut self, frame: Frame<Data>) -> Action {
let stream_id = frame.header().stream_id();
if frame.header().flags().contains(header::RST) {
if let Some(s) = self.streams.get_mut(&stream_id) {
let mut shared = s.shared();
shared.update_state(self.id, stream_id, State::Closed);
if let Some(w) = shared.reader.take() {
w.wake()
}
if let Some(w) = shared.writer.take() {
w.wake()
}
}
return Action::None
}
let is_finish = frame.header().flags().contains(header::FIN);
if frame.header().flags().contains(header::SYN) {
if !self.is_valid_remote_id(stream_id, Tag::Data) {
log::error!("{}: invalid stream id {}", self.id, stream_id);
return Action::Terminate(Frame::protocol_error())
}
if frame.body().len() > DEFAULT_CREDIT as usize {
log::error!("{}/{}: 1st body of stream exceeds default credit", self.id, stream_id);
return Action::Terminate(Frame::protocol_error())
}
if self.streams.contains_key(&stream_id) {
log::error!("{}/{}: stream already exists", self.id, stream_id);
return Action::Terminate(Frame::protocol_error())
}
if self.streams.len() == self.config.max_num_streams {
log::error!("{}: maximum number of streams reached", self.id);
return Action::Terminate(Frame::internal_error())
}
let mut stream = {
let config = self.config.clone();
let credit = DEFAULT_CREDIT;
let sender = self.stream_sender.clone();
Stream::new(stream_id, self.id, config, credit, credit, sender)
};
let window_update;
{
let mut shared = stream.shared();
if is_finish {
shared.update_state(self.id, stream_id, State::RecvClosed);
}
shared.window = shared.window.saturating_sub(frame.body_len());
shared.buffer.push(frame.into_body());
if !is_finish
&& shared.window == 0
&& self.config.window_update_mode == WindowUpdateMode::OnReceive
{
shared.window = self.config.receive_window;
let mut frame = Frame::window_update(stream_id, self.config.receive_window);
frame.header_mut().ack();
window_update = Some(frame)
} else {
window_update = None
}
}
if window_update.is_none() {
stream.set_flag(stream::Flag::Ack)
}
self.streams.insert(stream_id, stream.clone());
return Action::New(stream, window_update)
}
if let Some(stream) = self.streams.get_mut(&stream_id) {
let mut shared = stream.shared();
if frame.body().len() > shared.window as usize {
log::error!("{}/{}: frame body larger than window of stream", self.id, stream_id);
return Action::Terminate(Frame::protocol_error())
}
if is_finish {
shared.update_state(self.id, stream_id, State::RecvClosed);
}
let max_buffer_size = self.config.max_buffer_size;
if shared.buffer.len().map(move |n| n >= max_buffer_size).unwrap_or(true) {
log::error!("{}/{}: buffer of stream grows beyond limit", self.id, stream_id);
let mut header = Header::data(stream_id, 0);
header.rst();
return Action::Reset(Frame::new(header))
}
shared.window = shared.window.saturating_sub(frame.body_len());
shared.buffer.push(frame.into_body());
if let Some(w) = shared.reader.take() {
w.wake()
}
if !is_finish
&& shared.window == 0
&& self.config.window_update_mode == WindowUpdateMode::OnReceive
{
shared.window = self.config.receive_window;
let frame = Frame::window_update(stream_id, self.config.receive_window);
return Action::Update(frame)
}
} else if !is_finish {
log::debug!("{}/{}: data for unknown stream, ignoring", self.id, stream_id);
}
Action::None
}
fn on_window_update(&mut self, frame: &Frame<WindowUpdate>) -> Action {
let stream_id = frame.header().stream_id();
if frame.header().flags().contains(header::RST) {
if let Some(s) = self.streams.get_mut(&stream_id) {
let mut shared = s.shared();
shared.update_state(self.id, stream_id, State::Closed);
if let Some(w) = shared.reader.take() {
w.wake()
}
if let Some(w) = shared.writer.take() {
w.wake()
}
}
return Action::None
}
let is_finish = frame.header().flags().contains(header::FIN);
if frame.header().flags().contains(header::SYN) {
if !self.is_valid_remote_id(stream_id, Tag::WindowUpdate) {
log::error!("{}: invalid stream id {}", self.id, stream_id);
return Action::Terminate(Frame::protocol_error())
}
if self.streams.contains_key(&stream_id) {
log::error!("{}/{}: stream already exists", self.id, stream_id);
return Action::Terminate(Frame::protocol_error())
}
if self.streams.len() == self.config.max_num_streams {
log::error!("{}: maximum number of streams reached", self.id);
return Action::Terminate(Frame::protocol_error())
}
let stream = {
let credit = frame.header().credit() + DEFAULT_CREDIT;
let config = self.config.clone();
let sender = self.stream_sender.clone();
let mut stream = Stream::new(stream_id, self.id, config, DEFAULT_CREDIT, credit, sender);
stream.set_flag(stream::Flag::Ack);
stream
};
if is_finish {
stream.shared().update_state(self.id, stream_id, State::RecvClosed);
}
self.streams.insert(stream_id, stream.clone());
return Action::New(stream, None)
}
if let Some(stream) = self.streams.get_mut(&stream_id) {
let mut shared = stream.shared();
shared.credit += frame.header().credit();
if is_finish {
shared.update_state(self.id, stream_id, State::RecvClosed);
}
if let Some(w) = shared.writer.take() {
w.wake()
}
} else if !is_finish {
log::debug!("{}/{}: window update for unknown stream", self.id, stream_id);
}
Action::None
}
fn on_ping(&mut self, frame: &Frame<Ping>) -> Action {
let stream_id = frame.header().stream_id();
if frame.header().flags().contains(header::ACK) {
return Action::None
}
if stream_id == CONNECTION_ID || self.streams.contains_key(&stream_id) {
let mut hdr = Header::ping(frame.header().nonce());
hdr.ack();
return Action::Ping(Frame::new(hdr))
}
log::debug!("{}/{}: ping for unknown stream", self.id, stream_id);
Action::None
}
fn next_stream_id(&mut self) -> Result<StreamId> {
let proposed = StreamId::new(self.next_id);
self.next_id = self.next_id.checked_add(2).ok_or(ConnectionError::NoMoreStreamIds)?;
match self.mode {
Mode::Client => assert!(proposed.is_client()),
Mode::Server => assert!(proposed.is_server())
}
Ok(proposed)
}
fn is_valid_remote_id(&self, id: StreamId, tag: Tag) -> bool {
if tag == Tag::Ping || tag == Tag::GoAway {
return id.is_session()
}
match self.mode {
Mode::Client => id.is_server(),
Mode::Server => id.is_client()
}
}
async fn garbage_collect(&mut self) -> Result<()> {
let conn_id = self.id;
let win_update_mode = self.config.window_update_mode;
for stream in self.streams.values_mut() {
if stream.strong_count() > 1 {
continue
}
log::trace!("{}: removing dropped {}", conn_id, stream);
let stream_id = stream.id();
let frame = {
let mut shared = stream.shared();
let frame = match shared.update_state(conn_id, stream_id, State::Closed) {
State::Open => {
let mut header = Header::data(stream_id, 0);
header.rst();
Some(Frame::new(header))
}
State::RecvClosed => {
let mut header = Header::data(stream_id, 0);
header.fin();
Some(Frame::new(header))
}
State::SendClosed =>
if win_update_mode == WindowUpdateMode::OnRead && shared.window == 0 {
let mut header = Header::data(stream_id, 0);
header.rst();
Some(Frame::new(header))
} else {
None
}
State::Closed => None
};
if let Some(w) = shared.reader.take() {
w.wake()
}
if let Some(w) = shared.writer.take() {
w.wake()
}
frame
};
if let Some(f) = frame {
log::trace!("{}: sending: {}", self.id, f.header());
self.socket.get_mut().send(&f).await.or(Err(ConnectionError::Closed))?
}
self.garbage.push(stream_id)
}
for id in self.garbage.drain(..) {
self.streams.remove(&id);
}
Ok(())
}
}
impl<T> Connection<T> {
fn drop_all_streams(&mut self) {
for (id, s) in self.streams.drain() {
let mut shared = s.shared();
shared.update_state(self.id, id, State::Closed);
if let Some(w) = shared.reader.take() {
w.wake()
}
if let Some(w) = shared.writer.take() {
w.wake()
}
}
}
}
impl<T> Drop for Connection<T> {
fn drop(&mut self) {
self.drop_all_streams()
}
}
pub fn into_stream<T>(c: Connection<T>) -> impl futures::stream::Stream<Item = Result<Stream>>
where
T: AsyncRead + AsyncWrite + Unpin
{
futures::stream::unfold(c, |mut c| async {
match c.next_stream().await {
Ok(None) => None,
Ok(Some(stream)) => Some((Ok(stream), c)),
Err(e) => Some((Err(e), c))
}
})
}