ntex_io/io/stream.rs
1use std::task::{Context, Poll};
2use std::{future::poll_fn, io};
3
4use ntex_codec::{Decoder, Encoder};
5use ntex_util::future::Either;
6
7use crate::{Decoded, IoStatusUpdate, RecvError};
8
9use super::Io;
10#[cfg(doc)]
11use super::IoRef;
12
13impl<F> Io<F> {
14 /// Reads and decodes the next item from the incoming stream.
15 ///
16 /// Returns `Ok(None)` when the connection closed before another item could
17 /// be decoded and nothing was left undecoded, whether the peer
18 /// disconnected or the shutdown was started locally.
19 ///
20 /// If the peer closed its write half while the codec still held a partial
21 /// item, the stream was truncated and this returns
22 /// [`io::ErrorKind::UnexpectedEof`] in [`Either::Right`] rather than
23 /// `Ok(None)`, so that a cut-off frame is not mistaken for a clean end of
24 /// stream. Undecodable bytes left after a locally started shutdown are not
25 /// treated as truncation.
26 ///
27 /// Codec errors are returned in [`Either::Left`]. Dispatcher timeouts and
28 /// connection errors are returned in [`Either::Right`]; a connection error
29 /// may originate from the transport, a filter, or shutdown.
30 ///
31 /// If write backpressure prevents further reads, this method first waits
32 /// for the write buffer to fall below its configured threshold. A
33 /// dispatcher timeout that fires during this wait is returned as well.
34 pub async fn recv<U>(&self, codec: &U) -> Result<Option<U::Item>, Either<U::Error, io::Error>>
35 where
36 U: Decoder,
37 {
38 loop {
39 return match poll_fn(|cx| self.poll_recv(codec, cx)).await {
40 Ok(item) => Ok(Some(item)),
41 Err(RecvError::Timeout) => Err(Either::Right(io::Error::new(
42 io::ErrorKind::TimedOut,
43 "Timeout",
44 ))),
45 Err(RecvError::WriteBackpressure) => {
46 let timed_out = poll_fn(|cx| {
47 if self.st().flags.check_dispatcher_timeout() {
48 Poll::Ready(Ok(true))
49 } else {
50 self.poll_flush(cx, false).map_ok(|()| false)
51 }
52 })
53 .await
54 .map_err(Either::Right)?;
55
56 if timed_out {
57 Err(Either::Right(io::Error::new(
58 io::ErrorKind::TimedOut,
59 "Timeout",
60 )))
61 } else {
62 continue;
63 }
64 }
65 Err(RecvError::Decoder(err)) => Err(Either::Left(err)),
66 Err(RecvError::PeerGone(Some(err))) => Err(Either::Right(err)),
67 Err(RecvError::PeerGone(None)) => Ok(None),
68 };
69 }
70 }
71
72 /// Reads exactly enough bytes from this I/O stream to fill `dst`.
73 ///
74 /// If there is not enough data available, waits for incoming data.
75 /// If clean EOF or an error-free shutdown occurs before `dst` is filled,
76 /// this returns [`io::ErrorKind::UnexpectedEof`]. Transport errors are
77 /// passed through unchanged.
78 ///
79 /// Each wait goes through [`read_more`](Self::read_more), so this releases
80 /// read backpressure unconditionally rather than waiting for the read
81 /// buffer to drain to half the high watermark.
82 pub async fn read_exact(&self, dst: &mut [u8]) -> io::Result<()> {
83 loop {
84 let completed = self.with_read_dst(|buf| {
85 if buf.len() >= dst.len() {
86 let _ = io::Read::read(buf, dst).expect("Cannot fail");
87 true
88 } else {
89 false
90 }
91 });
92 if completed {
93 return Ok(());
94 }
95 // No more bytes will arrive after clean EOF or shutdown.
96 if self.read_more().await?.is_none() {
97 return Err(io::Error::new(io::ErrorKind::UnexpectedEof, "Disconnected"));
98 }
99 }
100 }
101
102 #[inline]
103 /// Waits until application-facing data is available and allows the
104 /// transport to read more data.
105 ///
106 /// If reads are paused or under backpressure, calling this method resumes
107 /// the read task. This is not a passive check of the current buffer, and
108 /// read backpressure is released however much data is still buffered.
109 ///
110 /// Returns `Ok(Some(()))` when input that has not been reported yet is
111 /// available, `Ok(None)` when no further input will be reported, and `Err`
112 /// if the transport failed. See [`poll_read_more`](Self::poll_read_more)
113 /// for what `None` means after a clean EOF.
114 pub async fn read_more(&self) -> io::Result<Option<()>> {
115 poll_fn(|cx| self.poll_read_more(cx)).await
116 }
117
118 #[inline]
119 /// Waits for the next read from the transport.
120 ///
121 /// Use this when a filter needs more source bytes. Unlike
122 /// [`read_more`](Self::read_more), data already waiting in the application
123 /// buffer does not complete this wait. If the read task is paused, this
124 /// method wakes it.
125 ///
126 /// Returns `Some(())` when the transport provides more input. If clean EOF
127 /// leaves final data in the application buffer, it returns `Some(())` once
128 /// and `None` afterward. A transport error is returned unchanged.
129 pub async fn read_notify(&self) -> io::Result<Option<()>> {
130 poll_fn(|cx| self.poll_read_notify(cx)).await
131 }
132
133 #[inline]
134 /// Encodes an item and sends it to the peer, fully flushing the write buffer.
135 ///
136 /// The flush is bounded by the
137 /// [write timeout](crate::IoConfig::set_write_timeout), if one is set;
138 /// when it expires this returns [`io::ErrorKind::TimedOut`] in
139 /// [`Either::Right`].
140 ///
141 /// The item is encoded with [`IoRef::encode`], so on a connection that is
142 /// already closing or closed it is silently dropped and `Ok(())` is
143 /// returned. See [`IoRef::encode`] for details.
144 pub async fn send<U>(&self, item: U::Item, codec: &U) -> Result<(), Either<U::Error, io::Error>>
145 where
146 U: Encoder,
147 {
148 self.encode(item, codec).map_err(Either::Left)?;
149
150 self.st()
151 .with_write_timeout(|cx| self.poll_flush(cx, true))
152 .await
153 .map_err(Either::Right)?;
154
155 Ok(())
156 }
157
158 #[inline]
159 /// Wakes the write task and requests a flush of queued output.
160 ///
161 /// This is the asynchronous counterpart to `poll_flush`. A full flush
162 /// completes once all output has reached the peer, including output a
163 /// transport has taken ownership of but not yet written. In-flight output
164 /// is counted up to 4 GiB, see [`Io::poll_flush`].
165 ///
166 /// The wait is bounded by the
167 /// [write timeout](crate::IoConfig::set_write_timeout), if one is set;
168 /// when it expires this returns [`io::ErrorKind::TimedOut`].
169 pub async fn flush(&self, full: bool) -> io::Result<()> {
170 self.st()
171 .with_write_timeout(|cx| self.poll_flush(cx, full))
172 .await
173 }
174
175 #[inline]
176 /// Gracefully shuts down the I/O stream.
177 ///
178 /// Shutdown runs in two phases, bounded together by a single
179 /// [`IoConfig::set_shutdown_timeout`]. First the filters shut down while
180 /// both directions stay open, so a filter can emit its closing data and
181 /// read the peer's. Then the transport drains the remaining output, pauses
182 /// the read side, and closes the connection.
183 ///
184 /// This completes once the transport backend has finished its shutdown
185 /// operation, not merely once the output has been drained.
186 ///
187 /// If the shutdown deadline expires in either phase, this returns an
188 /// [`io::ErrorKind::TimedOut`] error once the transport has stopped.
189 ///
190 /// [`IoConfig::set_shutdown_timeout`]: crate::IoConfig::set_shutdown_timeout
191 pub async fn shutdown(&self) -> io::Result<()> {
192 poll_fn(|cx| self.poll_shutdown(cx)).await
193 }
194
195 #[inline]
196 /// Polls for application-facing data and allows the transport to read more.
197 ///
198 /// If reads are paused or under backpressure, this resumes the read task.
199 /// It therefore changes the read state and should not be used as a passive
200 /// buffer check.
201 ///
202 /// The release is unconditional: unlike consumption through
203 /// [`IoRef::decode`], [`IoRef::with_buf`], [`IoRef::with_read_src`] or
204 /// [`IoRef::with_read_dst`], which waits for the read buffer to fall to at
205 /// most half the high watermark, this releases read backpressure however
206 /// much data is still buffered. Asking for more input
207 /// is taken as the dispatcher declaring itself able to accept it. This
208 /// also resumes reads paused because output produced by reading, for
209 /// example replies to peer pings, has not drained yet.
210 ///
211 /// # Returns
212 ///
213 /// - `Poll::Pending` while waiting for more data.
214 /// - `Poll::Ready(Ok(Some(())))` when input that has not been reported yet
215 /// is available.
216 /// - `Poll::Ready(Ok(None))` when no further input will be reported: after
217 /// a clean EOF once the available input has been reported, or when the
218 /// stream closes without an error. Clean EOF leaves the write half open.
219 ///
220 /// This reports arrivals, not buffer contents. Input that has already
221 /// been reported stays in the read buffer and remains decodable through
222 /// [`IoRef::decode`] and [`IoRef::with_read_dst`], so `None` does not
223 /// imply that the read buffer is empty.
224 /// - `Poll::Ready(Err(e))` if the transport failed.
225 pub fn poll_read_more(&self, cx: &mut Context<'_>) -> Poll<io::Result<Option<()>>> {
226 let st = self.st();
227
228 if st.flags.is_peer_gone() {
229 if let Some(err) = st.error() {
230 Poll::Ready(Err(err))
231 } else {
232 Poll::Ready(Ok(None))
233 }
234 } else {
235 let ready = st.flags.is_read_ready();
236
237 if st.flags.is_read_eof() && !ready {
238 return Poll::Ready(Ok(None));
239 }
240
241 // If the dispatcher requests more data but no read occurs,
242 // restart the read task.
243 if st.flags.is_read_paused_or_backpressure() || st.flags.is_read_wr_backpressure() {
244 st.unset_read_ready_and_backpressure();
245 st.flags.unset_read_paused();
246 st.flags.unset_read_wr_backpressure();
247 st.wake_read_task();
248 if ready {
249 Poll::Ready(Ok(Some(())))
250 } else {
251 st.dispatch_task.register(cx.waker());
252 Poll::Pending
253 }
254 } else if ready {
255 Poll::Ready(Ok(Some(())))
256 } else {
257 st.dispatch_task.register(cx.waker());
258 Poll::Pending
259 }
260 }
261 }
262
263 #[inline]
264 /// Polls for the next read from the transport.
265 ///
266 /// This is the polling version of [`read_notify`](Self::read_notify).
267 /// Existing application data does not make it ready. When another transport
268 /// read is needed, this wakes the read task and registers the current waker.
269 ///
270 /// `Some(())` means that more input arrived. Clean EOF may produce one last
271 /// `Some(())` when filters leave final application data; later polls return
272 /// `None`. Transport errors are returned unchanged.
273 ///
274 /// Paused or back-pressured reads are resumed through
275 /// [`poll_read_more`](Self::poll_read_more), which releases read
276 /// backpressure unconditionally.
277 pub fn poll_read_notify(&self, cx: &mut Context<'_>) -> Poll<io::Result<Option<()>>> {
278 let st = self.st();
279 if st.flags.is_stopping_or_terminating() {
280 if let Some(err) = st.error() {
281 Poll::Ready(Err(err))
282 } else {
283 Poll::Ready(Ok(None))
284 }
285 } else if st.flags.is_read_eof() {
286 let notified = st.flags.take_read_notified();
287 if notified && st.flags.is_read_ready() {
288 Poll::Ready(Ok(Some(())))
289 } else {
290 Poll::Ready(Ok(None))
291 }
292 } else if st.flags.take_read_notified() {
293 Poll::Ready(Ok(Some(())))
294 } else {
295 st.flags.set_read_notify();
296 // Resumes the read task if reads are paused. The result is
297 // discarded on purpose: buffered application data does not
298 // complete this wait, and the eof and closed cases are handled
299 // by the branches above.
300 let _ = self.poll_read_more(cx);
301 st.dispatch_task.register(cx.waker());
302 Poll::Pending
303 }
304 }
305
306 #[inline]
307 /// Decodes the next item from the incoming byte stream.
308 ///
309 /// Returns `Poll::Pending` when the codec needs more input, after going
310 /// through [`poll_read_more`](Self::poll_read_more), which wakes the read
311 /// task and releases read backpressure unconditionally.
312 ///
313 /// An error return does not register the waker. A clean peer EOF that
314 /// leaves undecodable bytes is reported as `RecvError::PeerGone` with an
315 /// [`io::ErrorKind::UnexpectedEof`] error, see
316 /// [`poll_recv_decode`](Self::poll_recv_decode).
317 pub fn poll_recv<U>(
318 &self,
319 codec: &U,
320 cx: &mut Context<'_>,
321 ) -> Poll<Result<U::Item, RecvError<U>>>
322 where
323 U: Decoder,
324 {
325 let decoded = self.poll_recv_decode(codec, cx)?;
326
327 if let Some(item) = decoded.item {
328 Poll::Ready(Ok(item))
329 } else {
330 Poll::Pending
331 }
332 }
333
334 #[inline]
335 /// Attempts to decode an item and reports buffer progress.
336 ///
337 /// `Decoded::consumed` is the number of bytes consumed by this decode
338 /// attempt and `Decoded::remains` is the number left in the
339 /// application-facing read buffer. If the codec needs more input, this
340 /// returns `Ok` with `item` set to `None` after arranging for `cx` to be
341 /// woken when progress is possible.
342 ///
343 /// An error return does not register the waker. While the connection is
344 /// open, an expired dispatcher timer and then active write backpressure are
345 /// reported before the read buffer is decoded, so an error never follows a
346 /// decode attempt and `Decoded` is never lost. The caller decides whether
347 /// input received together with a timeout is decoded first, see
348 /// [`IoRef::decode_item`]. Once the connection
349 /// is closing neither is reported, the buffered input is decoded and
350 /// `RecvError::PeerGone` is returned when no item is left.
351 ///
352 /// If the peer closed its write half cleanly while undecodable bytes
353 /// remain in the read buffer, the stream was truncated mid-frame and
354 /// `RecvError::PeerGone` carries an [`io::ErrorKind::UnexpectedEof`] error
355 /// instead of `None`. A recorded connection error takes precedence.
356 ///
357 /// When the codec needs more input this goes through
358 /// [`poll_read_more`](Self::poll_read_more), which releases read
359 /// backpressure unconditionally.
360 pub fn poll_recv_decode<U>(
361 &self,
362 codec: &U,
363 cx: &mut Context<'_>,
364 ) -> Result<Decoded<U::Item>, RecvError<U>>
365 where
366 U: Decoder,
367 {
368 let st = self.st();
369 st.flags.unset_read_ready();
370
371 let closed = st.flags.is_stopping() || st.flags.is_terminating();
372 if !closed {
373 if st.flags.check_dispatcher_timeout() {
374 return Err(RecvError::Timeout);
375 } else if st.flags.is_wr_backpressure() {
376 return Err(RecvError::WriteBackpressure);
377 }
378 }
379
380 let decoded = self
381 .decode_item(codec)
382 .map_err(|err| RecvError::Decoder(err))?;
383
384 if decoded.item.is_some() {
385 Ok(decoded)
386 } else if st.flags.is_stopping() || st.flags.is_terminating() {
387 Err(RecvError::PeerGone(st.error().or_else(|| self.truncated())))
388 } else {
389 match self.poll_read_more(cx) {
390 Poll::Pending | Poll::Ready(Ok(Some(()))) => {
391 #[cfg(feature = "trace")]
392 if decoded.remains != 0 {
393 log::trace!("{}: Not enough data to decode next frame", self.tag());
394 }
395 Ok(decoded)
396 }
397 Poll::Ready(Err(e)) => Err(RecvError::PeerGone(Some(e))),
398 Poll::Ready(Ok(None)) => Err(RecvError::PeerGone(self.truncated())),
399 }
400 }
401 }
402
403 /// Reports a stream the peer closed cleanly in the middle of a frame.
404 fn truncated(&self) -> Option<io::Error> {
405 let st = self.st();
406 if st.flags.is_read_eof() && st.buffer.read_dst_size() != 0 {
407 Some(io::Error::new(
408 io::ErrorKind::UnexpectedEof,
409 "bytes remaining on stream",
410 ))
411 } else {
412 None
413 }
414 }
415
416 #[inline]
417 /// Wakes the write task and instructs it to flush data.
418 ///
419 /// A full flush waits until all output has reached the peer.
420 ///
421 /// Otherwise this returns immediately while the outstanding size is below
422 /// the configured high watermark. Reaching that watermark enables write
423 /// backpressure, and the call then waits until the outstanding size falls
424 /// to half of it.
425 ///
426 /// Output that a completion based transport has taken ownership of counts
427 /// as outstanding until it reaches the peer, so a full flush does not
428 /// complete while a write is still in flight.
429 ///
430 /// In-flight output is counted up to 4 GiB (`u32::MAX` bytes). If more
431 /// than that is in flight at once, a full flush may complete before all
432 /// of it reaches the peer. Respecting write backpressure keeps the
433 /// outstanding size far below this limit.
434 pub fn poll_flush(&self, cx: &mut Context<'_>, full: bool) -> Poll<io::Result<()>> {
435 let st = self.st();
436
437 // flush filter state
438 st.buffer.process_write_buf_force(self)?;
439 self.consolidate_write_state(false)?;
440
441 let len = st.write_outstanding();
442 if len > 0 {
443 if st.flags.is_peer_gone() {
444 return Poll::Ready(Err(st.error_or_disconnected()));
445 } else if full {
446 st.flags.set_wants_write_flush();
447 st.dispatch_task.register(cx.waker());
448 return Poll::Pending;
449 } else if st.flags.is_wr_backpressure() {
450 if !st.should_disable_wr_backpressure(len) {
451 st.dispatch_task.register(cx.waker());
452 return Poll::Pending;
453 }
454 } else if st.is_wr_backpressure_needed(len) {
455 st.set_wr_backpressure();
456 st.dispatch_task.register(cx.waker());
457 return Poll::Pending;
458 }
459 }
460 if st.flags.is_peer_gone() && !st.flags.is_write_flush() {
461 Poll::Ready(Err(st.error_or_disconnected()))
462 } else {
463 st.unset_wr_backpressure_and_flush();
464 Poll::Ready(Ok(()))
465 }
466 }
467
468 #[inline]
469 /// Polls graceful shutdown through transport completion.
470 ///
471 /// `Poll::Ready` is returned only after the transport backend marks the
472 /// connection stopped, not merely when filter shutdown and flushing finish.
473 pub fn poll_shutdown(&self, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
474 let st = self.st();
475
476 if st.flags.is_closed() {
477 if let Some(err) = st.error() {
478 Poll::Ready(Err(err))
479 } else {
480 Poll::Ready(Ok(()))
481 }
482 } else {
483 if !st.flags.is_terminating() && !st.flags.is_stopping_filters() {
484 st.start_shutdown();
485 }
486 // Reads must keep running during shutdown so that the transport can
487 // observe a peer EOF and filters can complete their shutdown
488 // handshake. `BUF_R_READY` is deliberately left alone: it marks
489 // input the dispatcher has not consumed yet.
490 //
491 // Only the pause is cleared. Backpressure means the read buffer is
492 // full, which the shutdown must still respect: clearing it on every
493 // poll would let a peer that keeps sending grow the buffer without
494 // bound, and would hide the blocked shutdown detection in
495 // `poll_filters_shutdown`, which tests for exactly that flag.
496 //
497 // The tasks are woken only when this changes their state:
498 // `start_shutdown` wakes both. Waking them on every poll would let
499 // a caller that is polled spuriously keep the runtime busy with
500 // wakeups; compio then never polls for I/O completions.
501 if st.flags.is_read_paused() {
502 st.resume_read_task();
503 }
504 st.dispatch_task.register(cx.waker());
505 Poll::Pending
506 }
507 }
508
509 #[inline]
510 /// Pauses the read task and polls for a status update.
511 ///
512 /// The transport stops reading until the pause is cancelled. There is no
513 /// explicit resume: the pause is cancelled implicitly by any operation that
514 /// touches the read buffer or asks for more input, namely
515 /// [`read_more`](Self::read_more), [`poll_read_more`](Self::poll_read_more),
516 /// [`IoRef::decode`], [`IoRef::decode_item`], and [`IoRef::with_read_dst`].
517 /// Releasing read backpressure cancels it as well. Because those methods
518 /// are available through every [`IoRef`] clone, the pause holds only while
519 /// no other holder touches the read buffer.
520 ///
521 /// See [`poll_status_update`](Self::poll_status_update) for the reported
522 /// updates.
523 pub fn poll_read_pause(&self, cx: &mut Context<'_>) -> Poll<IoStatusUpdate> {
524 let st = self.st();
525 if !st.flags.is_read_paused() {
526 st.wake_read_task();
527 st.flags.set_read_paused();
528 }
529 self.poll_status_update(cx)
530 }
531
532 #[inline]
533 /// Polls for available status updates.
534 ///
535 /// `Timeout` consumes the pending dispatcher-timeout notification.
536 /// `WriteBackpressure` is reported while backpressure is active. The poll
537 /// that observes the write buffer falling below its release threshold
538 /// releases backpressure and reports no status update, matching
539 /// [`poll_flush`](Self::poll_flush). `PeerGone` is returned once the
540 /// connection has closed, whether the peer disconnected, the transport
541 /// failed, or the shutdown was started locally.
542 pub fn poll_status_update(&self, cx: &mut Context<'_>) -> Poll<IoStatusUpdate> {
543 let st = self.st();
544 st.dispatch_task.register(cx.waker());
545 if st.flags.is_peer_gone() {
546 Poll::Ready(IoStatusUpdate::PeerGone(st.error()))
547 } else if st.flags.check_dispatcher_timeout() {
548 Poll::Ready(IoStatusUpdate::Timeout)
549 } else if st.flags.is_wr_backpressure() {
550 // write backpressure is enabled and outstanding output is smaller than half
551 if st.should_disable_wr_backpressure(st.write_outstanding()) {
552 st.unset_wr_backpressure();
553 Poll::Pending
554 } else {
555 Poll::Ready(IoStatusUpdate::WriteBackpressure)
556 }
557 } else {
558 Poll::Pending
559 }
560 }
561
562 #[inline]
563 /// Registers a dispatch task.
564 pub fn register_dispatch(&self, cx: &mut Context<'_>) {
565 self.st().dispatch_task.register(cx.waker());
566 }
567}