Debian Codegraph @

third_party/rust/neqo-http3/src/push_controller.rs

raw
1 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
2 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
3 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
4 // option. This file may not be copied, modified, or distributed
5 // except according to those terms.
6
7 use std::{
8 cell::RefCell,
9 collections::VecDeque,
10 fmt::{self, Debug, Display, Formatter},
11 mem,
12 rc::Rc,
13 slice::SliceIndex,
14 };
15
16 use neqo_common::{qerror, qinfo, qtrace, Header};
17 use neqo_transport::{Connection, StreamId};
18
19 use crate::{
20 client_events::{Http3ClientEvent, Http3ClientEvents},
21 connection::Http3Connection,
22 frames::HFrame,
23 CloseType, Error, Http3StreamInfo, HttpRecvStreamEvents, PushId, RecvStreamEvents, Res,
24 };
25
26 /// `PushStates`:
27 /// `Init`: there is no push stream nor a push promise. This state is only used to keep track of
28 /// opened and closed push streams.
29 /// `PushPromise`: the push has only ever receive a pushpromise frame
30 /// `OnlyPushStream`: there is only a push stream. All push stream events, i.e. `PushHeaderReady`
31 /// and `PushDataReadable` will be delayed until a push promise is received
32 /// (they are kept in `events`).
33 /// `Active`: there is a push steam and at least one push promise frame.
34 /// `Close`: the push stream has been closed or reset already.
35 #[derive(Debug, PartialEq, Clone)]
36 enum PushState {
37 Init,
38 PushPromise {
39 headers: Vec<Header>,
40 },
41 OnlyPushStream {
42 stream_id: StreamId,
43 events: Vec<Http3ClientEvent>,
44 },
45 Active {
46 stream_id: StreamId,
47 headers: Vec<Header>,
48 },
49 Closed,
50 }
51
52 /// `ActivePushStreams` holds information about push streams.
53 ///
54 /// `first_push_id` holds a `push_id` of the first element in `push_streams` if it is present.
55 /// `push_id` smaller than `first_push_id` have been already closed. `push_id` => `first_push_id`
56 /// are in `push_streams` or they are not yet opened.
57 #[derive(Debug)]
58 struct ActivePushStreams {
59 push_streams: VecDeque<PushState>,
60 first_push_id: PushId,
61 }
62
63 impl ActivePushStreams {
64 pub const fn new() -> Self {
65 Self {
66 push_streams: VecDeque::new(),
67 first_push_id: PushId::new(0),
68 }
69 }
70
71 /// Returns None if a stream has been closed already.
72 pub fn get_mut(
73 &mut self,
74 push_id: PushId,
75 ) -> Option<&mut <usize as SliceIndex<[PushState]>>::Output> {
76 if push_id < self.first_push_id {
77 return None;
78 }
79
80 let inx = usize::try_from(u64::from(push_id - self.first_push_id)).ok()?;
81 if inx >= self.push_streams.len() {
82 self.push_streams.resize(inx + 1, PushState::Init);
83 }
84 match self.push_streams.get_mut(inx) {
85 Some(PushState::Closed) => None,
86 e => e,
87 }
88 }
89
90 /// Returns None if a stream has been closed already.
91 pub fn get(&mut self, push_id: PushId) -> Option<&mut PushState> {
92 self.get_mut(push_id)
93 }
94
95 /// Returns the State of a closed push stream or None for already closed streams.
96 pub fn close(&mut self, push_id: PushId) -> Option<PushState> {
97 match self.get_mut(push_id) {
98 None | Some(PushState::Closed) => None,
99 Some(s) => {
100 let res = mem::replace(s, PushState::Closed);
101 while self.push_streams.front() == Some(&PushState::Closed) {
102 self.push_streams.pop_front();
103 self.first_push_id.next();
104 }
105 Some(res)
106 }
107 }
108 }
109
110 #[must_use]
111 pub fn number_done(&self) -> PushId {
112 self.first_push_id
113 + u64::try_from(
114 self.push_streams
115 .iter()
116 .filter(|&e| e == &PushState::Closed)
117 .count(),
118 )
119 .expect("usize fits in u64")
120 }
121
122 pub fn clear(&mut self) {
123 self.first_push_id = PushId::new(0);
124 self.push_streams.clear();
125 }
126 }
127
128 /// `PushController` keeps information about push stream states.
129 ///
130 /// A `PushStream` calls `add_new_push_stream` that may change the push state from Init to
131 /// `OnlyPushStream` or from `PushPromise` to `Active`. If a stream has already been closed
132 /// `add_new_push_stream` returns false (the `PushStream` will close the transport stream).
133 /// A `PushStream` calls `push_stream_reset` if the transport stream has been canceled.
134 /// When a push stream is done it calls `close`.
135 ///
136 /// The `PushController` handles:
137 /// `PUSH_PROMISE` frame: frames may change the push state from Init to `PushPromise` and from
138 /// `OnlyPushStream` to `Active`. Frames for a closed streams are ignored.
139 /// `CANCEL_PUSH` frame: (`handle_cancel_push` will be called). If a push is in state `PushPromise`
140 /// or `Active`, any posted events will be removed and a `PushCanceled` event
141 /// will be posted. If a push is in state `OnlyPushStream` or `Active` the
142 /// transport stream and the `PushStream` will be closed. The frame will be
143 /// ignored for already closed pushes. Application calling cancel: the actions are similar to the
144 /// `CANCEL_PUSH` frame. The difference is that `PushCanceled` will not
145 /// be posted and a `CANCEL_PUSH` frame may be sent.
146 #[derive(Debug)]
147 pub struct PushController {
148 max_concurent_push: u64,
149 current_max_push_id: PushId,
150 // push_streams holds the states of push streams.
151 // We keep a stream until the stream has been closed.
152 push_streams: ActivePushStreams,
153 // The keeps the next consecutive push_id that should be open.
154 // All push_id < next_push_id_to_open are in the push_stream lists. If they are not in the list
155 // they have been already closed.
156 conn_events: Http3ClientEvents,
157 }
158
159 impl Display for PushController {
160 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
161 write!(f, "Push controller")
162 }
163 }
164
165 impl PushController {
166 pub const fn new(max_concurent_push: u64, conn_events: Http3ClientEvents) -> Self {
167 Self {
168 max_concurent_push,
169 current_max_push_id: PushId::new(0),
170 push_streams: ActivePushStreams::new(),
171 conn_events,
172 }
173 }
174
175 /// A new `push_promise` has been received.
176 ///
177 /// # Errors
178 ///
179 /// `HttpId` if `push_id` greater than it is allowed has been received.
180 pub fn new_push_promise(
181 &mut self,
182 push_id: PushId,
183 ref_stream_id: StreamId,
184 new_headers: Vec<Header>,
185 ) -> Res<()> {
186 qtrace!(
187 "[{self}] New push promise push_id={push_id} headers={new_headers:?} max_push={}",
188 self.max_concurent_push
189 );
190
191 self.check_push_id(push_id)?;
192
193 match self.push_streams.get_mut(push_id) {
194 None => {
195 qtrace!("Push has been closed already {push_id}");
196 Ok(())
197 }
198 Some(push_state) => match push_state {
199 PushState::Init => {
200 self.conn_events
201 .push_promise(push_id, ref_stream_id, new_headers.clone());
202 *push_state = PushState::PushPromise {
203 headers: new_headers,
204 };
205 Ok(())
206 }
207 PushState::PushPromise { headers } | PushState::Active { headers, .. } => {
208 if new_headers != *headers {
209 return Err(Error::HttpGeneralProtocol);
210 }
211 self.conn_events
212 .push_promise(push_id, ref_stream_id, new_headers);
213 Ok(())
214 }
215 PushState::OnlyPushStream { stream_id, events } => {
216 let stream_id_tmp = *stream_id;
217 self.conn_events
218 .push_promise(push_id, ref_stream_id, new_headers.clone());
219
220 for e in events.drain(..) {
221 self.conn_events.insert(e);
222 }
223 *push_state = PushState::Active {
224 stream_id: stream_id_tmp,
225 headers: new_headers,
226 };
227 Ok(())
228 }
229 PushState::Closed => unreachable!("This is only internal; it is transfer to None"),
230 },
231 }
232 }
233
234 pub fn add_new_push_stream(&mut self, push_id: PushId, stream_id: StreamId) -> Res<bool> {
235 qtrace!("A new push stream with push_id={push_id} stream_id={stream_id}");
236 self.check_push_id(push_id)?;
237
238 self.push_streams.get_mut(push_id).map_or_else(
239 || {
240 qinfo!("Push has been closed already");
241 Ok(false)
242 },
243 |push_state| match push_state {
244 PushState::Init => {
245 *push_state = PushState::OnlyPushStream {
246 stream_id,
247 events: Vec::new(),
248 };
249 Ok(true)
250 }
251 PushState::PushPromise { headers } => {
252 let tmp = mem::take(headers);
253 *push_state = PushState::Active {
254 stream_id,
255 headers: tmp,
256 };
257 Ok(true)
258 }
259 // The following state have already have a push stream:
260 // PushState::OnlyPushStream | PushState::Active
261 _ => {
262 qerror!("Duplicate push stream");
263 Err(Error::HttpId)
264 }
265 },
266 )
267 }
268
269 fn check_push_id(&self, push_id: PushId) -> Res<()> {
270 // Check if push id is greater than what we allow.
271 if push_id > self.current_max_push_id {
272 qerror!("Push id is greater than current_max_push_id");
273 Err(Error::HttpId)
274 } else {
275 Ok(())
276 }
277 }
278
279 pub fn handle_cancel_push(
280 &mut self,
281 push_id: PushId,
282 conn: &mut Connection,
283 base_handler: &mut Http3Connection,
284 ) -> Res<()> {
285 qtrace!("CANCEL_PUSH frame has been received, push_id={push_id}");
286
287 self.check_push_id(push_id)?;
288
289 match self.push_streams.close(push_id) {
290 None => {
291 qtrace!("Push has already been closed (push_id={push_id})");
292 Ok(())
293 }
294 Some(ps) => match ps {
295 PushState::Init => Ok(()),
296 PushState::PushPromise { .. } => {
297 self.conn_events.remove_events_for_push_id(push_id);
298 self.conn_events.push_canceled(push_id);
299 Ok(())
300 }
301 PushState::OnlyPushStream { stream_id, .. }
302 | PushState::Active { stream_id, .. } => {
303 drop(base_handler.stream_stop_sending(
304 conn,
305 stream_id,
306 Error::HttpRequestCancelled.code(),
307 ));
308 self.conn_events.remove_events_for_push_id(push_id);
309 self.conn_events.push_canceled(push_id);
310 Ok(())
311 }
312 PushState::Closed => unreachable!("This is only internal; it is transfer to None"),
313 },
314 }
315 }
316
317 pub fn close(&mut self, push_id: PushId) {
318 qtrace!("Push stream has been closed");
319 if let Some(push_state) = self.push_streams.close(push_id) {
320 debug_assert!(matches!(push_state, PushState::Active { .. }));
321 } else {
322 debug_assert!(false, "Closing non existing push stream!");
323 }
324 }
325
326 pub fn cancel(
327 &mut self,
328 push_id: PushId,
329 conn: &mut Connection,
330 base_handler: &mut Http3Connection,
331 ) -> Res<()> {
332 qtrace!("Cancel push_id={push_id}");
333
334 self.check_push_id(push_id)?;
335
336 match self.push_streams.get(push_id) {
337 None => {
338 qtrace!("Push has already been closed");
339 // If we have some events for the push_id in the event queue, the caller still does
340 // not not know that the push has been closed. Otherwise return
341 // InvalidStreamId.
342 if self.conn_events.has_push(push_id) {
343 self.conn_events.remove_events_for_push_id(push_id);
344 Ok(())
345 } else {
346 Err(Error::InvalidStreamId)
347 }
348 }
349 Some(PushState::PushPromise { .. }) => {
350 self.conn_events.remove_events_for_push_id(push_id);
351 base_handler.queue_control_frame(&HFrame::CancelPush { push_id });
352 self.push_streams.close(push_id);
353 Ok(())
354 }
355 Some(PushState::Active { stream_id, .. }) => {
356 self.conn_events.remove_events_for_push_id(push_id);
357 // Cancel the stream. The transport stream may already be done, so ignore an error.
358 drop(base_handler.stream_stop_sending(
359 conn,
360 *stream_id,
361 Error::HttpRequestCancelled.code(),
362 ));
363 self.push_streams.close(push_id);
364 Ok(())
365 }
366 Some(_) => Err(Error::InvalidStreamId),
367 }
368 }
369
370 pub fn push_stream_reset(&mut self, push_id: PushId, close_type: CloseType) {
371 qtrace!("Push stream has been reset, push_id={push_id}");
372 if let Some(push_state) = self.push_streams.get(push_id) {
373 match push_state {
374 PushState::OnlyPushStream { .. } => {
375 self.push_streams.close(push_id);
376 }
377 PushState::Active { .. } => {
378 self.push_streams.close(push_id);
379 self.conn_events.remove_events_for_push_id(push_id);
380 if let CloseType::LocalError(app_error) = close_type {
381 self.conn_events.push_reset(push_id, app_error);
382 } else {
383 self.conn_events.push_canceled(push_id);
384 }
385 }
386 _ => {
387 debug_assert!(
388 false,
389 "Reset cannot actually happen because we do not have a stream"
390 );
391 }
392 }
393 }
394 }
395
396 pub fn get_active_stream_id(&mut self, push_id: PushId) -> Option<StreamId> {
397 match self.push_streams.get(push_id) {
398 Some(PushState::Active { stream_id, .. }) => Some(*stream_id),
399 _ => None,
400 }
401 }
402
403 pub fn maybe_send_max_push_id_frame(&mut self, base_handler: &mut Http3Connection) {
404 let push_done = self.push_streams.number_done();
405 if self.max_concurent_push > 0
406 && (self.current_max_push_id - push_done) <= (self.max_concurent_push / 2).into()
407 {
408 self.current_max_push_id = push_done + self.max_concurent_push;
409 base_handler.queue_control_frame(&HFrame::MaxPushId {
410 push_id: self.current_max_push_id,
411 });
412 }
413 }
414
415 pub fn handle_zero_rtt_rejected(&mut self) {
416 self.current_max_push_id = PushId::new(0);
417 }
418
419 pub fn clear(&mut self) {
420 self.push_streams.clear();
421 }
422
423 pub const fn can_receive_push(&self) -> bool {
424 self.max_concurent_push > 0
425 }
426
427 pub fn new_stream_event(&mut self, push_id: PushId, event: Http3ClientEvent) {
428 match self.push_streams.get_mut(push_id) {
429 None => {
430 debug_assert!(false, "Push has been closed already");
431 }
432 Some(PushState::OnlyPushStream { events, .. }) => {
433 events.push(event);
434 }
435 Some(PushState::Active { .. }) => {
436 self.conn_events.insert(event);
437 }
438 Some(_) => {
439 debug_assert!(false, "No record of a stream!");
440 }
441 }
442 }
443 }
444
445 /// `RecvPushEvents` relays a push stream events to `PushController`.
446 /// It informs `PushController` when a push stream is done or canceled.
447 /// Also when headers or data is ready and `PushController` decide whether to post
448 /// `PushHeaderReady` and `PushDataReadable` events or to postpone them if
449 /// a `push_promise` has not been yet received for the stream.
450 #[derive(Debug)]
451 pub struct RecvPushEvents {
452 push_id: PushId,
453 push_handler: Rc<RefCell<PushController>>,
454 }
455
456 impl RecvPushEvents {
457 pub const fn new(push_id: PushId, push_handler: Rc<RefCell<PushController>>) -> Self {
458 Self {
459 push_id,
460 push_handler,
461 }
462 }
463 }
464
465 impl RecvStreamEvents for RecvPushEvents {
466 fn data_readable(&self, _stream_info: Http3StreamInfo) {
467 self.push_handler.borrow_mut().new_stream_event(
468 self.push_id,
469 Http3ClientEvent::PushDataReadable {
470 push_id: self.push_id,
471 },
472 );
473 }
474
475 fn recv_closed(&self, _stream_info: Http3StreamInfo, close_type: CloseType) {
476 match close_type {
477 CloseType::ResetApp(_) => {}
478 CloseType::ResetRemote(_) | CloseType::LocalError(_) => self
479 .push_handler
480 .borrow_mut()
481 .push_stream_reset(self.push_id, close_type),
482 CloseType::Done => self.push_handler.borrow_mut().close(self.push_id),
483 }
484 }
485 }
486
487 impl HttpRecvStreamEvents for RecvPushEvents {
488 fn header_ready(
489 &self,
490 _stream_info: Http3StreamInfo,
491 headers: Vec<Header>,
492 interim: bool,
493 fin: bool,
494 ) {
495 self.push_handler.borrow_mut().new_stream_event(
496 self.push_id,
497 Http3ClientEvent::PushHeaderReady {
498 push_id: self.push_id,
499 headers,
500 interim,
501 fin,
502 },
503 );
504 }
505 }