-
Notifications
You must be signed in to change notification settings - Fork 99
/
Copy pathstream.rs
7446 lines (6327 loc) · 273 KB
/
stream.rs
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
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2023 The TQUIC Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#![allow(dead_code)]
use std::any::Any;
use std::cmp;
use std::collections::btree_map;
use std::collections::hash_map;
use std::collections::BTreeMap;
use std::collections::BinaryHeap;
use std::collections::VecDeque;
use std::ops::Range;
use std::time;
use std::time::Instant;
use bytes::Buf;
use bytes::BufMut;
use bytes::Bytes;
use bytes::BytesMut;
use enumflags2::bitflags;
use enumflags2::BitFlags;
use log::*;
use rustc_hash::FxHashMap;
use rustc_hash::FxHashSet;
use smallvec::SmallVec;
use self::StreamFlags::*;
use crate::connection::flowcontrol;
use crate::ranges;
use crate::Error;
use crate::Event;
use crate::EventQueue;
use crate::Result;
use crate::Shutdown;
use crate::TransportParams;
use crate::MAX_STREAMS_PER_TYPE;
pub type StreamIdHashMap<V> = FxHashMap<u64, V>;
pub type StreamIdHashSet = FxHashSet<u64>;
#[cfg(test)]
const SEND_BUFFER_SIZE: usize = 5;
#[cfg(not(test))]
const SEND_BUFFER_SIZE: usize = 4096;
// Receiver stream flow control window default value, 32KB.
const DEFAULT_STREAM_WINDOW: u64 = 32 * 1024;
// Receiver stream flow control window max value, 6MB.
pub const MAX_STREAM_WINDOW: u64 = 6 * 1024 * 1024;
// Receiver connection flow control window default value, 48KB.
// Note that here we set the default value of the connection-level flow control window
// to be 1.5 times the size of the stream-level flow control window, i.e. 1.5 * 32KB.
pub const DEFAULT_CONNECTION_WINDOW: u64 = 48 * 1024;
// The maximum size of the receiver connection flow control window.
pub const MAX_CONNECTION_WINDOW: u64 = 15 * 1024 * 1024;
/// Stream manager for keeps track of streams on a QUIC Connection.
#[derive(Default)]
pub struct StreamMap {
/// Whether it serves as a server.
is_server: bool,
/// Collection of streams that are organized and accessed by stream ID.
streams: StreamIdHashMap<Stream>,
/// Streams that have outstanding data ready to be sent to the peer,
/// and categorized by their urgency, lower value means higher priority.
sendable: BTreeMap<u8, StreamPriorityQueue>,
/// Streams that have outstanding data can be read by the application.
readable: StreamIdHashSet,
/// Streams that have enough flow control capacity to be written to,
/// and is not finished.
writable: StreamIdHashSet,
/// Streams that are shutdown on the send side by the application prematurely
/// or received STOP_SENDING frame from the peer.
///
/// Current endpoint should send a RESET_STREAM frame with the error code and
/// final size values in the tuple of the map elements to the peer.
reset: StreamIdHashMap<(u64, u64)>,
/// Streams that are shutdown on the receive side, and need to send
/// a STOP_SENDING frame.
stopped: StreamIdHashMap<u64>,
/// Keep track of IDs of previously closed streams. It can grow and use up a
/// lot of memory, so it is used only in unit tests.
#[cfg(test)]
closed: StreamIdHashSet,
/// Streams that peer are almost out of flow control capacity, and
/// need local endpoint to send a MAX_STREAM_DATA frame to the peer.
almost_full: StreamIdHashSet,
/// Streams that are blocked on the send-side, and need to send a
/// STREAM_DATA_BLOCKED frame to the peer. The value of the map elements is
/// the stream offset at which the stream is blocked.
data_blocked: StreamIdHashMap<u64>,
/// Streams concurrency control.
concurrency_control: ConcurrencyControl,
/// Connection receive-side flow control.
flow_control: flowcontrol::FlowControl,
/// Connection send-side flow control.
send_capacity: SendCapacity,
/// The maximum stream receive-side flow control window, it is inherited
/// from the connection configuration, and applies to all streams.
max_stream_window: u64,
/// Connection received-side flow control capacity almost full,
/// local endpoint should issue more credit by sending a MAX_DATA
/// frame to the peer.
pub rx_almost_full: bool,
/// Stream id for next bidirectional stream.
next_stream_id_bidi: u64,
/// Stream id for next unidirectional stream.
next_stream_id_uni: u64,
/// Peer transport parameters.
peer_transport_params: StreamTransportParams,
/// Local transport parameters.
local_transport_params: StreamTransportParams,
/// Events sent to the endpoint.
pub(super) events: EventQueue,
/// Unique trace id for debug logging.
trace_id: String,
}
impl StreamMap {
/// Create a new `StreamMap`.
pub fn new(
is_server: bool,
max_connection_window: u64,
max_stream_window: u64,
local_params: StreamTransportParams,
) -> StreamMap {
StreamMap {
is_server,
concurrency_control: ConcurrencyControl::new(
local_params.initial_max_streams_bidi,
local_params.initial_max_streams_uni,
),
flow_control: flowcontrol::FlowControl::new(
local_params.initial_max_data,
max_connection_window,
),
send_capacity: SendCapacity::default(),
max_stream_window,
rx_almost_full: false,
next_stream_id_bidi: if is_server { 1 } else { 0 },
next_stream_id_uni: if is_server { 3 } else { 2 },
local_transport_params: local_params,
peer_transport_params: StreamTransportParams::default(),
..StreamMap::default()
}
}
/// Set trace id.
pub fn set_trace_id(&mut self, trace_id: &str) {
self.trace_id = trace_id.to_string();
}
/// Return a reference to the stream with the given ID if it exists, or `None`.
fn get(&self, id: u64) -> Option<&Stream> {
self.streams.get(&id)
}
/// Return a mutable reference to the stream with the given ID if it exists,
/// or `None`.
pub fn get_mut(&mut self, id: u64) -> Option<&mut Stream> {
self.streams.get_mut(&id)
}
/// Create a new bidirectional stream with given stream priority.
/// Return id of the created stream upon success.
pub fn stream_bidi_new(&mut self, urgency: u8, incremental: bool) -> Result<u64> {
let stream_id = self.next_stream_id_bidi;
match self.stream_set_priority(stream_id, urgency, incremental) {
Ok(_) => Ok(stream_id),
Err(e) => Err(e),
}
}
/// Create a new undirectional stream with given stream priority.
/// Return id of the created stream upon success.
pub fn stream_uni_new(&mut self, urgency: u8, incremental: bool) -> Result<u64> {
let stream_id = self.next_stream_id_uni;
match self.stream_set_priority(stream_id, urgency, incremental) {
Ok(_) => Ok(stream_id),
Err(e) => Err(e),
}
}
/// Get the lowest offset of data to be read.
pub fn stream_read_offset(&mut self, stream_id: u64) -> Option<u64> {
match self.get_mut(stream_id) {
Some(stream) => Some(stream.recv.read_off()),
None => None,
}
}
/// Read contiguous data from the stream's receive buffer into the given buffer.
///
/// Return the number of bytes read and the `fin` flag if read successfully.
/// Return `StreamStateError` if the stream closed or never opened.
/// Return `Done` if the stream is not readable.
pub fn stream_read(&mut self, stream_id: u64, out: &mut [u8]) -> Result<(usize, bool)> {
// Local initiated unidirectional streams are send-only, so we can't read from them.
if !is_bidi(stream_id) && is_local(stream_id, self.is_server) {
return Err(Error::StreamStateError);
}
// If the stream is not exist, it may not be opened yet, or it was closed,
// return `StreamStateError`.
let stream = self.get_mut(stream_id).ok_or(Error::StreamStateError)?;
// If stream is not readable, return `Done`.
if !stream.is_readable() {
trace!("{} stream is not readable", stream.trace_id);
return Err(Error::Done);
}
let local = stream.local;
let (read, fin) = match stream.recv.read(out) {
Ok(v) => v,
Err(e) => {
trace!("{} stream read error: {:?}", stream.trace_id, e);
// Stream recv-side maybe reset by peer, if it is complete, we should
// remove it from the stream map, and collect it to `closed` streams set.
if stream.is_complete() {
self.mark_closed(stream_id, local);
}
self.mark_readable(stream_id, false);
return Err(e);
}
};
// We can't move these two lines of code after the connection-level
// flow_control check, otherwise there will be a variable borrowing problem.
let readable = stream.is_readable();
let complete = stream.is_complete();
// Check if we need to send a `MAX_STREAM_DATA` frame to update
// stream-level flow control.
if stream.recv.should_send_max_data() {
self.mark_almost_full(stream_id, true);
}
// Update connection-level flow control consumption, and check if we should
// send a `MAX_DATA` frame to update connection-level flow control limit.
self.flow_control.increase_read_off(read as u64);
if self.flow_control.should_send_max_data() {
self.rx_almost_full = true;
}
// After reading, we should remove it from the readable queue if it is not
// readable at the present.
if !readable {
self.mark_readable(stream_id, false);
}
// If the stream is complete, we should remove it from the streams map and
// collect it to the `closed` streams set.
if complete {
self.mark_closed(stream_id, local);
}
Ok((read, fin))
}
/// Get the maximum offset of data written by application
pub fn stream_write_offset(&mut self, stream_id: u64) -> Option<u64> {
match self.get_mut(stream_id) {
Some(stream) => Some(stream.send.write_off()),
None => None,
}
}
/// Write data to the stream's send buffer.
pub fn stream_write(&mut self, stream_id: u64, mut buf: Bytes, fin: bool) -> Result<usize> {
// Peer initiated unidirectional streams are receive-only, so we can't write to them.
if !is_bidi(stream_id) && !is_local(stream_id, self.is_server) {
return Err(Error::StreamStateError);
}
// If the connection-level flow control credit is not enough, mark the
// the connection as blocked and schedule a `DATA_BLOCKED` frame to be sent.
if self.max_tx_data_left() < buf.len() as u64 {
self.update_data_blocked_at(Some(self.send_capacity.max_data));
}
let expect_written = buf.len();
let capacity = self.send_capacity.capacity;
// Get or create the stream if it was not created before.
// If the stream was closed, return `Done`.
let stream = self.get_or_create(stream_id, true)?;
let was_writable = stream.is_writable();
let was_sendable = stream.is_sendable();
// When the connection's capacity is exhausted, if the input buffer is not empty,
// return `Done`.
if capacity == 0 && !buf.is_empty() {
// Stream blocked by the connection's send capacity, must not affect
// its writable state.
if was_writable {
self.mark_writable(stream_id, true);
}
// Stream blocked, but it still want to write, so we should mark it as want-write.
let _ = self.want_write(stream_id, true);
return Err(Error::Done);
}
// If the connection's send capacity is not enough, truncate the input
// buffer with the capacity.
let (fin, blocked_by_cap) = if capacity < buf.len() {
buf.truncate(capacity);
(false, true)
} else {
(fin, false)
};
// Save the buffer's length before its ownership moved.
let buf_len = buf.len();
let written = match stream.send.write(buf, fin) {
Ok(v) => v,
Err(e) => {
self.mark_writable(stream_id, false);
return Err(e);
}
};
let urgency = stream.urgency;
let incremental = stream.incremental;
let sendable = stream.is_sendable();
let writable = stream.is_writable();
let empty_fin = buf_len == 0 && fin;
if written < buf_len {
let max_data = stream.send.max_data();
if stream.send.blocked_at() != Some(max_data) {
stream.send.update_blocked_at(Some(max_data));
self.mark_blocked(stream_id, true, max_data);
}
} else {
stream.send.update_blocked_at(None);
self.mark_blocked(stream_id, false, 0);
}
// If the stream is sendable and it wasn't sendable before, push it to
// the sendable queue.
// Note: Buffer an empty block data with fin should be treated as sendable.
if (sendable || empty_fin) && !was_sendable {
self.push_sendable(stream_id, urgency, incremental);
}
if !writable {
self.mark_writable(stream_id, false);
} else if was_writable && blocked_by_cap {
// Stream blocked by the connection's send capacity, must not affect
// its writable state.
self.mark_writable(stream_id, true);
}
self.send_capacity.capacity -= written;
self.send_capacity.tx_data += written as u64;
// Write partial data, mark the stream as want-write.
if written < expect_written {
let _ = self.want_write(stream_id, true);
}
// No data was written, it maybe limited by the stream-level flow control.
if written == 0 && buf_len > 0 {
return Err(Error::Done);
}
Ok(written)
}
/// Shutdown stream receive-side or send-side.
pub fn stream_shutdown(&mut self, stream_id: u64, direction: Shutdown, err: u64) -> Result<()> {
// We can't move this line to the match arm because of the borrow checker.
let is_server = self.is_server;
// If the stream was not created before or has been closed, return `Done`.
let stream = self.get_mut(stream_id).ok_or(Error::Done)?;
match direction {
Shutdown::Read => {
// Local initiated uni stream should not be shutdown in the receive-side.
if is_local(stream_id, is_server) && !is_bidi(stream_id) {
return Err(Error::StreamStateError);
}
let unread_len = stream.recv.shutdown()?;
// If the stream doesn't enter terminal state, sending a `STOP_SENDING`
// frame to prompt closure of the stream in the opposite direction.
if !stream.recv.is_fin() {
self.mark_stopped(stream_id, true, err);
}
// Stream should not be readable if it is shutdown in the receive-side.
self.mark_readable(stream_id, false);
// When a stream's receive-side shutdown, all unread data will be
// discarded, we consider them as consumed, which might trigger a
// connection-level flow control update.
self.flow_control.increase_read_off(unread_len);
if self.flow_control.should_send_max_data() {
self.rx_almost_full = true;
}
}
Shutdown::Write => {
// Peer initiated uni stream should not be shutdown in the send-side.
if !is_local(stream_id, is_server) && !is_bidi(stream_id) {
return Err(Error::StreamStateError);
}
let (final_size, unsent) = stream.send.shutdown()?;
// Give back some flow control credit by deducting the data that
// was buffered but not actually sent before the stream send-side
// was shutdown.
self.send_capacity.tx_data = self.send_capacity.tx_data.saturating_sub(unsent);
// Update connection-level send capacity.
self.send_capacity.update_capacity();
self.mark_reset(stream_id, true, err, final_size);
// Stream should not be writable after it is shutdown in the send-side.
self.mark_writable(stream_id, false);
}
}
Ok(())
}
/// Set priority for a stream.
pub fn stream_set_priority(
&mut self,
stream_id: u64,
urgency: u8,
incremental: bool,
) -> Result<()> {
// Get or create the stream if it was not created before.
let stream = match self.get_or_create(stream_id, true) {
Ok(v) => v,
// Stream has been closed, just ignore the prioritization.
Err(Error::Done) => return Ok(()),
Err(e) => return Err(e),
};
if stream.urgency == urgency && stream.incremental == incremental {
return Ok(());
}
stream.urgency = urgency;
stream.incremental = incremental;
Ok(())
}
/// Get the stream's send-side capacity, in units of bytes.
/// The capacity is the minimum of the connection-level flow control credit
/// and the stream-level flow control credit.
pub fn stream_capacity(&self, stream_id: u64) -> Result<usize> {
match self.get(stream_id) {
Some(s) => Ok(cmp::min(self.send_capacity.capacity, s.send.capacity()?)),
None => Err(Error::StreamStateError),
}
}
/// Return true if the stream has more than `len` bytes of send-side capacity.
pub fn stream_writable(&mut self, stream_id: u64, len: usize) -> Result<bool> {
if self.stream_capacity(stream_id)? >= len {
return Ok(true);
}
// The connection-level flow control credit is not enough, mark the connection
// blocked and schedule a DATA_BLOCKED frame to be sent to the peer.
if self.max_tx_data_left() < len as u64 {
self.update_data_blocked_at(Some(self.send_capacity.max_data));
}
// We have confirmed that the stream is existing when calling `stream_capacity`,
// so it is safe to unwrap.
let stream = self.get_mut(stream_id).unwrap();
stream.write_thresh = cmp::max(1, len);
let is_writable = stream.is_writable();
// If the stream-level flow control credit is not enough, mark the stream
// blocked and schedule a STREAM_DATA_BLOCKED frame to be sent to the peer.
//
// Note that we should mark the stream blocked at max_data, otherwise the
// peer may ignore the STREAM_DATA_BLOCKED frame.
if stream.send.capacity()? < len {
let max_data = stream.send.max_data();
if stream.send.blocked_at() != Some(max_data) {
stream.send.update_blocked_at(Some(max_data));
self.mark_blocked(stream_id, true, max_data);
}
} else if is_writable {
self.mark_writable(stream_id, true);
}
Ok(false)
}
/// Return true if the stream has outstanding data to read.
pub fn stream_readable(&self, stream_id: u64) -> bool {
match self.get(stream_id) {
Some(s) => s.is_readable(),
None => false,
}
}
/// Return true if the stream's receive-side final size is known, and the
/// application has read all data from the stream.
///
/// Note that this function also return true if the stream is reset by the peer.
pub fn stream_finished(&self, stream_id: u64) -> bool {
match self.get(stream_id) {
Some(s) => s.recv.is_fin(),
None => true,
}
}
/// Set user context for a stream.
pub fn stream_set_context<T: Any + Send + Sync>(
&mut self,
stream_id: u64,
ctx: T,
) -> Result<()> {
// Get or create the stream if it was not created before.
let stream = match self.get_or_create(stream_id, true) {
Ok(v) => v,
Err(Error::Done) => return Ok(()), // stream closed
Err(e) => return Err(e),
};
stream.context = Some(Box::new(ctx));
Ok(())
}
/// Return the stream's user context.
pub fn stream_context(&mut self, stream_id: u64) -> Option<&mut dyn Any> {
if let Some(s) = self.get_mut(stream_id) {
match s.context {
Some(ref mut ctx) => Some(ctx.as_mut()),
None => None,
}
} else {
None
}
}
/// Get the maximum amount of data that the stream can receive and sent.
/// Return a tuple of (max_rx_data, max_tx_data).
fn max_stream_data_limit(
local: bool,
bidi: bool,
local_params: &StreamTransportParams,
peer_params: &StreamTransportParams,
) -> (u64, u64) {
// Based on the initiator(local/remote) and stream type(uni/bidi) to determine the
// maximum amount of data that can be received and sent by the local endpoint.
match (local, bidi) {
// Local initiated bidirectional stream, can send and receive data.
(true, true) => (
local_params.initial_max_stream_data_bidi_local,
peer_params.initial_max_stream_data_bidi_remote,
),
// Local initiated unidirectional stream, can send data only.
(true, false) => (0, peer_params.initial_max_stream_data_uni),
// Peer initiated bidirectional stream, can receive and send data.
(false, true) => (
local_params.initial_max_stream_data_bidi_remote,
peer_params.initial_max_stream_data_bidi_local,
),
// Peer initiated unidirectional stream, can receive data only.
(false, false) => (local_params.initial_max_stream_data_uni, 0),
}
}
/// Return a mutable reference to the stream with the given ID if it exists,
/// or create a new one with given paras otherwise if it is allowed.
fn get_or_create(&mut self, id: u64, local: bool) -> Result<&mut Stream> {
// A stream ID is a 62-bit integer (0 to 2^62-1) that is unique for all
// streams on a connection.
if id > crate::codec::VINT_MAX {
return Err(Error::ProtocolViolation);
}
let closed = self.is_closed(id);
match self.streams.entry(id) {
// 1.Can not find any stream with the given stream ID.
// It may not be created yet or it has been closed.
hash_map::Entry::Vacant(v) => {
// Stream has already been closed and collected into `closed`.
if closed {
return Err(Error::Done);
}
// Requested stream ID is not valid with the current role.
if local != is_local(id, self.is_server) {
return Err(Error::StreamStateError);
}
let bidi = is_bidi(id);
// Get the maximum amount of data that the new stream can receive and sent.
let (max_rx_data, max_tx_data) = Self::max_stream_data_limit(
local,
bidi,
&self.local_transport_params,
&self.peer_transport_params,
);
// Check if the stream ID complies with the stream limits of the current
// role, and try to update the stream count if it is valid.
self.concurrency_control
.check_concurrency_limits(id, self.is_server)?;
// Create a new stream.
let mut new_stream = Stream::new(
bidi,
local,
max_tx_data,
max_rx_data,
self.max_stream_window,
);
let trace_id = format!("{}-{}", &self.trace_id, id);
new_stream.set_trace_id(&trace_id);
// Stream might already be writable due to initial flow control credit.
if new_stream.is_writable() {
self.writable.insert(id);
}
// Update stream id for next bidirectional/unidirectional stream.
if bidi {
self.next_stream_id_bidi = cmp::max(self.next_stream_id_bidi, id);
self.next_stream_id_bidi = self.next_stream_id_bidi.saturating_add(4);
} else {
self.next_stream_id_uni = cmp::max(self.next_stream_id_uni, id);
self.next_stream_id_uni = self.next_stream_id_uni.saturating_add(4);
}
self.concurrency_control.remove_avail_id(id, self.is_server);
self.events.add(Event::StreamCreated(id));
Ok(v.insert(new_stream))
}
// 2.Stream already exists.
hash_map::Entry::Occupied(v) => Ok(v.into_mut()),
}
}
/// Return true if we should send `MAX_DATA` frame to peer to update
/// the connection level flow control limit.
pub fn need_send_max_data(&self) -> bool {
self.rx_almost_full && self.max_rx_data() < self.max_rx_data_next()
}
/// Return true if need to send stream frames.
pub fn need_send_stream_frames(&self) -> bool {
self.has_sendable_streams()
|| self.need_send_max_data()
|| self.data_blocked_at().is_some()
|| self.should_send_max_streams()
|| self.has_almost_full_streams()
|| self.has_blocked_streams()
|| self.has_reset_streams()
|| self.has_stopped_streams()
|| self.streams_blocked()
}
/// Push the stream ID to the sendable queue with the given urgency and
/// incremental flag.
///
/// If the given stream ID is already in the queue, this function must
/// not be called to ensure the fairness of the scheduling and avoid the
/// spurious cycles through the queue.
fn push_sendable(&mut self, stream_id: u64, urgency: u8, incremental: bool) {
// 1.Get priority queue with the given urgency, if it does not exist, create a new one.
let queue = match self.sendable.entry(urgency) {
btree_map::Entry::Vacant(v) => v.insert(StreamPriorityQueue::default()),
btree_map::Entry::Occupied(v) => v.into_mut(),
};
// 2.Push the element to the queue corresponding to the given incremental flag.
if !incremental {
// Non-incremental streams are scheduled in order of their stream ID.
queue.non_incremental.push(cmp::Reverse(stream_id))
} else {
// Incremental streams are scheduled in a round-robin fashion.
queue.incremental.push_back(stream_id)
};
}
/// Return the first stream ID from the sendable queue with the highest priority.
///
/// Note that the caller should call `remove_sendable` to remove the stream from the
/// queue if it is no longer sendable after sending some of its outstanding data.
pub fn peek_sendable(&mut self) -> Option<u64> {
let queue = match self.sendable.iter_mut().next() {
Some((_, queue)) => queue,
None => return None,
};
// 1.Try to get the non-incremental stream with the lowest stream ID.
match queue.non_incremental.peek().map(|x| x.0) {
Some(stream_id) => Some(stream_id),
None => {
// 2.Try to get the incremental stream from the front of the queue.
// Incremental streams are scheduled in a round-robin fashion, So
// we should move the current peeked incremental stream to the end
// of the queue.
match queue.incremental.pop_front() {
Some(stream_id) => {
queue.incremental.push_back(stream_id);
Some(stream_id)
}
// Should never happen.
None => None,
}
}
}
}
/// Remove the last peeked stream from the sendable streams queue.
pub fn remove_sendable(&mut self) {
// Get the first entry which is the queue with the highest priority.
let mut entry = match self.sendable.first_entry() {
Some(entry) => entry,
// Should never happen, as `peek_sendable()` must be called priorly.
None => return,
};
let queue = entry.get_mut();
queue
.non_incremental
.pop()
.map(|x| x.0)
.or_else(|| queue.incremental.pop_back());
// Remove the queue from the queues list if it is empty at present time,
// so that the next time `peek_sendable()` is invoked, the next non-empty
// queue is selected.
if queue.non_incremental.is_empty() && queue.incremental.is_empty() {
entry.remove();
}
}
/// Add or remove the stream ID to/from the `readable` streams set.
///
/// Do nothing if `readable` is true but the stream was already in the list.
fn mark_readable(&mut self, stream_id: u64, readable: bool) {
match readable {
true => self.readable.insert(stream_id),
false => self.readable.remove(&stream_id),
};
}
/// Add or remove the stream ID to/from the `writable` streams set.
///
/// Do nothing if `writable` is true but the stream was already in the list.
fn mark_writable(&mut self, stream_id: u64, writable: bool) {
match writable {
true => self.writable.insert(stream_id),
false => self.writable.remove(&stream_id),
};
}
/// Add or remove the stream ID to/from the `almost_full` streams set.
///
/// Do nothing if `almost_full` is true but the stream was already in the list.
pub fn mark_almost_full(&mut self, stream_id: u64, almost_full: bool) {
match almost_full {
true => self.almost_full.insert(stream_id),
false => self.almost_full.remove(&stream_id),
};
}
/// Add or remove the stream ID to/from the `data_blocked` streams set with the
/// given offset value.
///
/// If `blocked` is true but the stream was already in the list, the offset value
/// will be updated.
pub fn mark_blocked(&mut self, stream_id: u64, blocked: bool, off: u64) {
match blocked {
true => self.data_blocked.insert(stream_id, off),
false => self.data_blocked.remove(&stream_id),
};
}
/// Add or remove the stream ID to/from the `reset` streams set with the
/// given error code and final size values.
///
/// If `reset` is true but the stream was already in the list, the error code
/// and final size values will be updated.
pub fn mark_reset(&mut self, stream_id: u64, reset: bool, error_code: u64, final_size: u64) {
match reset {
true => self.reset.insert(stream_id, (error_code, final_size)),
false => self.reset.remove(&stream_id),
};
}
/// Add or remove the stream ID to/from the `stop` streams set with the
/// given error code.
///
/// If `stopped` is true but the stream was already in the list, the error code
/// will be updated.
pub fn mark_stopped(&mut self, stream_id: u64, stopped: bool, error_code: u64) {
match stopped {
true => self.stopped.insert(stream_id, error_code),
false => self.stopped.remove(&stream_id),
};
}
/// Remove the stream ID from the readable and writable streams sets, and
/// adds it to the closed streams set.
///
/// Note that this method does not check if the stream id is complied with
/// the role of the endpoint.
fn mark_closed(&mut self, stream_id: u64, local: bool) {
if self.is_closed(stream_id) {
return;
}
// Give back a max_streams credit if the stream was initiated by the peer.
if !local {
if is_bidi(stream_id) {
self.concurrency_control
.increase_max_streams_credits(true, 1);
} else {
self.concurrency_control
.increase_max_streams_credits(false, 1);
}
}
self.mark_readable(stream_id, false);
self.mark_writable(stream_id, false);
if let Some(stream) = self.get_mut(stream_id) {
stream.mark_closed();
}
#[cfg(test)]
self.closed.insert(stream_id);
if self.events.add(Event::StreamClosed(stream_id)) {
// When event queue is enabled, inform the Endpoint to process
// StreamClosed event and destroy the stream object.
return;
}
self.stream_destroy(stream_id);
}
/// Destroy the closed stream.
pub(crate) fn stream_destroy(&mut self, stream_id: u64) {
self.streams.remove(&stream_id);
}
/// Get the maximum streams that the peer allows the local endpoint to open.
pub fn peer_max_streams(&self, bidi: bool) -> u64 {
self.concurrency_control.peer_max_streams(bidi)
}
/// After sending a MAX_STREAMS(type: 0x12..0x13) frame, update local max_streams limit.
pub fn update_local_max_streams(&mut self, bidi: bool) {
self.concurrency_control.update_local_max_streams(bidi);
}
/// Get the maximum streams that the local endpoint allow the peer to open.
pub fn max_streams(&self, bidi: bool) -> u64 {
match bidi {
true => self.concurrency_control.local_max_streams_bidi,
false => self.concurrency_control.local_max_streams_uni,
}
}
/// Get the next max streams limit that will be sent to the peer
/// in a MAX_STREAMS(type:0x12..0x13) frame.
pub fn max_streams_next(&self, bidi: bool) -> u64 {
match bidi {
true => self.concurrency_control.local_max_streams_bidi_next,
false => self.concurrency_control.local_max_streams_uni_next,
}
}
/// Return true if we should send a MAX_STREAMS(type: 0x12..0x13) frame to the peer.
pub fn should_send_max_streams(&self) -> bool {
self.concurrency_control
.should_update_local_max_streams(true)
|| self
.concurrency_control
.should_update_local_max_streams(false)
}
/// Return true if the max streams limit should be updated
/// by sending a MAX_STREAMS(type: 0x12..0x13) frame to the peer.
pub fn should_update_local_max_streams(&self, bidi: bool) -> bool {
self.concurrency_control
.should_update_local_max_streams(bidi)
}
/// Get the last offset at which the connection send-side was blocked, if any.
pub fn data_blocked_at(&self) -> Option<u64> {
self.send_capacity.blocked_at
}
pub fn streams_blocked(&self) -> bool {
self.concurrency_control.streams_blocked_at_bidi.is_some()
|| self.concurrency_control.streams_blocked_at_uni.is_some()
}
pub fn streams_blocked_at(&self, bidi: bool) -> Option<u64> {
match bidi {
true => self.concurrency_control.streams_blocked_at_bidi,
false => self.concurrency_control.streams_blocked_at_uni,
}
}
/// Return an iterator over all the existing streams.
pub fn iter(&self) -> StreamIter {
StreamIter {
streams: self.streams.keys().copied().collect(),
}
}
/// Return an iterator over streams that have outstanding data to be read
/// by the application.
pub fn readable_iter(&self) -> StreamIter {
StreamIter::from(&self.readable)
}
/// Return true if there are any streams that have data to read.
pub fn has_readable(&self) -> bool {
let iter = StreamIter::from(&self.readable);
for stream_id in iter {
if self.check_readable(stream_id) {
trace!("{} has readable stream {}", self.trace_id, stream_id);
return true;
}
}
trace!("{} no any readable stream", self.trace_id);
false
}
/// Return an iterator over streams that have available send capacity of stream level.