ntex_io/ioref.rs
1use std::{any, fmt, hash, io};
2
3use ntex_bytes::{BytePage, BytePages, BytesMut};
4use ntex_codec::{Decoder, Encoder};
5use ntex_service::cfg::SharedCfg;
6use ntex_util::time::Seconds;
7
8use crate::io::Close;
9use crate::ops::{Id, Iops, TimerHandle};
10use crate::waiters::{TAG_DISCONNECT, TAG_WRITE, Waiter};
11use crate::{
12 CloseReason, Decoded, Filter, FilterBuf, Flags, Handle, IoConfig, IoContext, IoRef, types,
13};
14
15impl IoRef {
16 #[inline]
17 /// Gets the ID.
18 pub fn id(&self) -> Id {
19 self.0.id()
20 }
21
22 #[inline]
23 /// Gets the I/O tag.
24 pub fn tag(&self) -> &'static str {
25 self.0.tag()
26 }
27
28 #[doc(hidden)]
29 /// Gets the state flags. (for debug purpose only)
30 pub fn flags(&self) -> Flags {
31 self.0.flags.clone()
32 }
33
34 #[inline]
35 /// Gets the current filter.
36 pub(crate) fn filter(&self) -> &dyn Filter {
37 self.0.filter()
38 }
39
40 #[inline]
41 /// Gets the configuration.
42 ///
43 /// The reference must not be used after
44 /// [`Io::set_config`](crate::Io::set_config).
45 pub fn cfg(&self) -> &IoConfig {
46 self.0.cfg()
47 }
48
49 #[inline]
50 /// Gets the shared configuration.
51 pub fn shared(&self) -> SharedCfg {
52 self.0.cfg().shared()
53 }
54
55 /// Returns the tracker charged with the read buffers of the connection.
56 ///
57 /// Returns `None` if [`BufTracker::Disabled`](crate::BufTracker)
58 /// is configured. A per-connection tracker is created on first use.
59 ///
60 /// Other buffers can be attributed to the connection by charging them
61 /// to the tracker, see
62 /// [`BytesMut::with_page_size_in`](ntex_bytes::BytesMut::with_page_size_in)
63 /// and [`BytesMut::set_tracker`](ntex_bytes::BytesMut::set_tracker).
64 ///
65 /// The reference must not be used after
66 /// [`Io::set_config`](crate::Io::set_config).
67 #[cfg(feature = "tracker")]
68 #[cfg_attr(docsrs, doc(cfg(feature = "tracker")))]
69 #[must_use]
70 pub fn buf_tracker(&self) -> Option<&ntex_bytes::BytesTracker> {
71 self.0.buf_tracker()
72 }
73
74 #[inline]
75 /// Checks whether the I/O stream is active.
76 ///
77 /// This becomes `false` as soon as the connection leaves its active
78 /// state, whether it was closed locally, force-terminated, or the
79 /// transport reported the peer as gone. Closing is not instantaneous, so
80 /// buffered output may still be flushing and buffered input stays
81 /// readable after this goes `false`; use
82 /// [`is_closed`](Self::is_closed) to ask whether closing has finished.
83 pub fn is_active(&self) -> bool {
84 self.0.flags.is_active()
85 }
86
87 #[inline]
88 /// Checks whether the transport read half reached clean EOF.
89 ///
90 /// Buffered input remains available and the write half may still be used.
91 pub fn is_read_eof(&self) -> bool {
92 self.0.flags.is_read_eof()
93 }
94
95 #[inline]
96 /// Checks whether the I/O stream is closed.
97 ///
98 /// This becomes `true` once the backend released the underlying socket
99 /// and transport teardown has finished, so nothing further can be read
100 /// from or delivered to the peer. Every way a connection can end reaches
101 /// this state, whether it closed gracefully, was force-terminated or the
102 /// peer disappeared. Use [`is_active`](Self::is_active) to also cover a
103 /// close that is still in progress.
104 ///
105 /// Buffered input that was already received stays readable.
106 pub fn is_closed(&self) -> bool {
107 self.0.flags.is_closed()
108 }
109
110 #[inline]
111 /// Checks whether read back-pressure is enabled.
112 ///
113 /// This becomes `true` once unread data in the application-facing read
114 /// buffer reaches the configured high watermark, which parks the transport
115 /// read task.
116 ///
117 /// Two different paths release it. Consuming through
118 /// [`decode`](Self::decode), [`with_buf`](Self::with_buf),
119 /// [`with_read_src`](Self::with_read_src) or
120 /// [`with_read_dst`](Self::with_read_dst) releases it once the buffer has
121 /// fallen to at most half the high watermark. Asking for more input through
122 /// [`Io::poll_read_more`](crate::Io::poll_read_more), and the methods built
123 /// on it, releases it immediately however much data is still buffered.
124 pub fn is_rd_backpressure(&self) -> bool {
125 self.0.flags.is_rd_backpressure()
126 }
127
128 #[inline]
129 /// Checks whether write back-pressure is enabled.
130 ///
131 /// This becomes `true` once outstanding output reaches the configured high
132 /// watermark. Outstanding output includes buffered data and data that the
133 /// transport owns but has not yet written to the peer. It is released once
134 /// the outstanding size falls to half the high watermark.
135 ///
136 /// Nothing enforces the signal: encoding continues to succeed while it is
137 /// set. Producers that are not driven by a dispatcher should check this
138 /// before encoding more, or the write buffer grows without bound. See
139 /// [`encode`](Self::encode) and [`write_ready`](Self::write_ready).
140 pub fn is_wr_backpressure(&self) -> bool {
141 self.0.flags.is_wr_backpressure()
142 }
143
144 /// Reports why the connection is closing.
145 ///
146 /// Only the first reported reason is kept. It is counted in
147 /// [`IoMetrics`](crate::IoMetrics) when the connection state is released.
148 /// A connection closed without a reason counts as an I/O error if the
149 /// transport failed, and as `other` otherwise.
150 pub fn set_close_reason(&self, reason: CloseReason) {
151 if let Close::Unset = self.0.close.get() {
152 self.0.close.set(Close::Reason(reason));
153 }
154 }
155
156 /// Returns the reason reported with [`set_close_reason`](Self::set_close_reason).
157 pub fn close_reason(&self) -> Option<CloseReason> {
158 if let Close::Reason(reason) = self.0.close.get() {
159 Some(reason)
160 } else {
161 None
162 }
163 }
164
165 #[inline]
166 /// Checks whether the filter chain is not ready, see
167 /// [`Filter::poll_ready`](crate::Filter::poll_ready).
168 ///
169 /// Transport reads are paused and output the chain holds does not reach
170 /// the transport during the pause. It is not caused by the peer, so read
171 /// and write timeouts should not run. The dispatcher is notified when the
172 /// pause starts and when it ends.
173 pub fn is_filter_paused(&self) -> bool {
174 self.0.flags.is_filter_paused()
175 }
176
177 /// Waits until the write buffer can accept more output.
178 ///
179 /// Completes immediately unless write back-pressure is enabled. While it
180 /// is, waits until the outstanding output falls to the release threshold
181 /// (half of the high watermark), the level at which the dispatcher
182 /// releases back-pressure. Any number of tasks can wait at once, the
183 /// write task wakes them without involving the dispatcher.
184 ///
185 /// Producers that are not driven by a dispatcher can await this before
186 /// encoding more, so the write buffer does not grow without bound.
187 ///
188 /// Fails once the connection is closing or closed, and with
189 /// [`io::ErrorKind::TimedOut`] if the
190 /// [write timeout](crate::IoConfig::set_write_timeout) is set and expires
191 /// first.
192 pub async fn write_ready(&self) -> io::Result<()> {
193 self.0.write_ready().await
194 }
195
196 /// Gracefully closes the connection.
197 ///
198 /// Initiates the I/O stream shutdown process.
199 pub fn close(&self) {
200 self.0.start_shutdown();
201 }
202
203 /// Force-closes the connection.
204 ///
205 /// The dispatcher does not wait for incomplete responses. The I/O stream is
206 /// terminated without any graceful period, and whatever is still buffered
207 /// is discarded.
208 ///
209 /// The transport aborts the connection instead of closing it gracefully, so
210 /// the peer most likely observes an `RST` rather than a clean end of
211 /// stream, and output that has not been acknowledged yet is lost. That is
212 /// what keeps a truncated response distinguishable from a complete one, but
213 /// it also means this must not be used to end a connection normally. Use
214 /// [`close`](Self::close) for that.
215 pub fn terminate(&self) {
216 log::trace!("{}: Terminate io stream object", self.tag());
217 self.0.force_close_connection();
218 }
219
220 /// Queries filter-specific data.
221 pub fn query<T: 'static>(&self) -> types::QueryItem<T> {
222 let _borrow = self.0.buffer.borrow();
223 types::QueryItem::new(self.filter().query(any::TypeId::of::<T>()))
224 }
225
226 #[inline]
227 /// Encodes an item into the write buffer.
228 ///
229 /// # `Ok` does not mean the item was buffered
230 ///
231 /// This method reports codec errors only. Any `io::Error` produced while
232 /// buffering is discarded: if the connection is already closing or closed
233 /// (for example after [`close`](Self::close)), the item is **silently
234 /// dropped** and `Ok(())` is returned. A transport or filter error raised
235 /// by an eager backend write is dropped the same way. Such errors remain
236 /// observable later through [`crate::Io::poll_flush`] or
237 /// [`crate::Io::poll_recv`].
238 ///
239 /// When delivery matters, check [`is_active`](Self::is_active) before
240 /// encoding, or encode into a buffer with the codec yourself and write it
241 /// with [`encode_bytes`](Self::encode_bytes) or
242 /// [`encode_slice`](Self::encode_slice), which return these errors at the
243 /// call site.
244 ///
245 /// # Back-pressure is advisory
246 ///
247 /// Encoding never blocks and never refuses. Once buffered output reaches
248 /// the configured high watermark this arms write back-pressure and wakes
249 /// the dispatch task, but the item is still buffered and `Ok` is still
250 /// returned. A caller that keeps encoding without consulting
251 /// [`is_wr_backpressure`](Self::is_wr_backpressure), or awaiting
252 /// [`Io::poll_status_update`](crate::Io::poll_status_update) or
253 /// [`Io::poll_flush`](crate::Io::poll_flush), will grow the write buffer
254 /// without bound, because a slow peer cannot slow the producer down on its
255 /// own. Honouring the signal is the caller's responsibility.
256 pub fn encode<U>(&self, item: U::Item, codec: &U) -> Result<(), <U as Encoder>::Error>
257 where
258 U: Encoder,
259 {
260 self.with_write_src(|buf| codec.encode(item, buf))
261 .unwrap_or_else(|_| Ok(()))
262 }
263
264 #[inline]
265 /// Encodes the slice into the write buffer.
266 ///
267 /// If this triggers an eager backend write, any transport or filter error
268 /// from that write is returned immediately.
269 ///
270 /// Write back-pressure is advisory here too; see [`encode`](Self::encode).
271 pub fn encode_slice(&self, src: &[u8]) -> io::Result<()> {
272 self.with_write_src(|buf| buf.extend_from_slice(src))
273 }
274
275 #[inline]
276 /// Writes bytes to the write buffer.
277 ///
278 /// If this triggers an eager backend write, any transport or filter error
279 /// from that write is returned immediately.
280 ///
281 /// Write back-pressure is advisory here too; see [`encode`](Self::encode).
282 pub fn encode_bytes<B>(&self, src: B) -> io::Result<()>
283 where
284 BytePage: From<B>,
285 {
286 self.with_write_src(|buf| buf.append(src))
287 }
288
289 /// Attempts to decode a frame from the read buffer.
290 ///
291 /// Once the transport reached eof this uses [`Decoder::decode_eof`]
292 /// instead of [`Decoder::decode`].
293 ///
294 /// This mutates the read state: it clears read readiness, and consuming
295 /// enough bytes may release read backpressure. It also cancels a pause
296 /// installed by [`Io::poll_read_pause`](crate::Io::poll_read_pause) and wakes the transport
297 /// read task.
298 ///
299 /// Decoded frames that share the read buffer's allocation keep the whole
300 /// buffer alive, see [`IoConfig::set_read_size`](crate::IoConfig::set_read_size).
301 pub fn decode<U>(
302 &self,
303 codec: &U,
304 ) -> Result<Option<<U as Decoder>::Item>, <U as Decoder>::Error>
305 where
306 U: Decoder,
307 {
308 let res = self.0.buffer.with_read_dst(self, |buf| {
309 let res = self.decode_buf(codec, buf);
310 self.0.flags.unset_read_ready();
311 self.update_read_destination(buf);
312 res
313 });
314 self.0.sync_read_buffered();
315 res
316 }
317
318 /// Attempts to decode a frame from the read buffer.
319 ///
320 /// `Decoded::consumed` reports the bytes taken by this attempt and
321 /// `Decoded::remains` the bytes left in the application-facing read
322 /// buffer. Once the transport reached eof this uses
323 /// [`Decoder::decode_eof`] instead of [`Decoder::decode`].
324 ///
325 /// Like [`decode`](Self::decode), this mutates the read state: it clears
326 /// read readiness, may release read backpressure, and cancels a pause
327 /// installed by [`Io::poll_read_pause`](crate::Io::poll_read_pause).
328 pub fn decode_item<U>(
329 &self,
330 codec: &U,
331 ) -> Result<Decoded<<U as Decoder>::Item>, <U as Decoder>::Error>
332 where
333 U: Decoder,
334 {
335 let res = self.0.buffer.with_read_dst(self, |buf| {
336 let len = buf.len();
337 let res = self.decode_buf(codec, buf).map(|item| Decoded {
338 item,
339 remains: buf.len(),
340 consumed: len - buf.len(),
341 });
342 self.0.flags.unset_read_ready();
343 self.update_read_destination(buf);
344 res
345 });
346 self.0.sync_read_buffered();
347 res
348 }
349
350 fn decode_buf<U: Decoder>(
351 &self,
352 codec: &U,
353 buf: &mut BytesMut,
354 ) -> Result<Option<U::Item>, U::Error> {
355 if self.0.flags.is_read_eof() {
356 codec.decode_eof(buf)
357 } else {
358 codec.decode(buf)
359 }
360 }
361
362 /// Sends the write buffer to the I/O layer.
363 ///
364 /// Requires the underlying runtime to implement `.write()`;
365 /// otherwise, no action is taken.
366 pub fn send_buf(&self) -> io::Result<()> {
367 self.consolidate_write_state(true)
368 }
369
370 pub(crate) fn ops_send_buf(&self) {
371 let st = &self.0;
372 #[cfg(feature = "trace")]
373 log::trace!(
374 "{}: ops-send == buf:{} flags:{:?}",
375 st.tag(),
376 st.buffer.write_buf_size(),
377 st.flags
378 );
379
380 if st.flags.is_wr_send_scheduled() {
381 st.flags.unset_wr_send_scheduled();
382
383 if st.flags.is_write_paused() {
384 // call `Handle::write()`.
385 // if write task is not paused, io write is pending
386 // need to wake write task for io completion
387 if self.call_write() == WakeWriteTask::Yes {
388 st.wake_write_task();
389 st.flags.unset_write_paused();
390 }
391 } else {
392 st.wake_write_task();
393 }
394 }
395 }
396
397 /// Provides temporary access to the outermost filter buffers.
398 ///
399 /// Filter callbacks run before and after `f`, and any produced write data
400 /// is scheduled for delivery after the closure returns. Errors from an
401 /// eager backend write are returned to the caller.
402 ///
403 /// The destination exposed by
404 /// [`FilterBuf::with_read_buffers`](crate::FilterBuf::with_read_buffers) is
405 /// the application-facing read destination, so consuming enough of it
406 /// releases read backpressure and cancels an installed read pause.
407 ///
408 /// Buffer access is not reentrant. The closure must not use this
409 /// connection to access an overlapping read or write buffer, or change the
410 /// filter chain.
411 pub fn with_buf<F, R>(&self, f: F) -> io::Result<R>
412 where
413 F: FnOnce(&mut FilterBuf<'_>) -> R,
414 {
415 self.with_callbacks(|cb| cb.before_processing(self));
416 let result = self.0.buffer.with_filter(self, |ctx| ctx.with_buffer(f));
417 self.with_callbacks(|cb| cb.after_processing(self));
418 self.release_read_destination();
419 self.0.sync_read_buffered();
420
421 self.consolidate_write_state(false)?;
422 Ok(result)
423 }
424
425 /// Provides mutable access to the application-facing read destination.
426 ///
427 /// This holds the decoded bytes the application consumes; see
428 /// [`with_read_src`](Self::with_read_src) for the transport-facing source.
429 ///
430 /// This mutates the read state whether or not `f` consumes anything. While
431 /// read back-pressure is active nothing is released until the buffer has
432 /// fallen to at most half the high watermark, so until then read readiness
433 /// and any installed read pause are left in place. Once it has, or when
434 /// back-pressure was not active, read readiness is cleared and a pause
435 /// installed by [`Io::poll_read_pause`](crate::Io::poll_read_pause) is
436 /// cancelled, waking the transport read task.
437 ///
438 /// Use [`crate::Io::poll_read_more`] rather than this method to check
439 /// whether data is available.
440 ///
441 /// The closure must not access this connection's application-facing read
442 /// destination again. Nested access is unsupported and may terminate the
443 /// connection or lose nested buffer changes.
444 pub fn with_read_dst<F, R>(&self, f: F) -> R
445 where
446 F: FnOnce(&mut BytesMut) -> R,
447 {
448 let res = self.0.buffer.with_read_dst(self, |buf| {
449 let res = f(buf);
450 self.update_read_destination(buf);
451 res
452 });
453 self.0.sync_read_buffered();
454 res
455 }
456
457 #[inline]
458 /// Returns the size of the application-facing read destination.
459 ///
460 /// Unlike [`with_read_dst`](Self::with_read_dst) this does not change the
461 /// read state, read readiness, read back-pressure and an installed read
462 /// pause are left in place, and no buffer is allocated. Returns `0` when
463 /// called from inside [`with_read_dst`](Self::with_read_dst).
464 pub fn read_dst_size(&self) -> usize {
465 self.0.buffer.read_dst_size()
466 }
467
468 /// Provides mutable access to the application-facing write source.
469 ///
470 /// This holds the bytes the application produces; see
471 /// [`with_write_dst`](Self::with_write_dst) for the transport-facing
472 /// destination.
473 ///
474 /// Returns an error without invoking `f` if the connection is closing or
475 /// closed. Data appended by `f` is scheduled for delivery. If that starts
476 /// an eager backend write, its transport or filter error is returned.
477 ///
478 /// # Panics
479 ///
480 /// Panics if the closure accesses the same application-facing write
481 /// buffer again.
482 pub fn with_write_src<F, R>(&self, f: F) -> io::Result<R>
483 where
484 F: FnOnce(&mut BytePages) -> R,
485 {
486 let st = &self.0;
487
488 if st.flags.is_active() {
489 let (result, size) = st.buffer.with_write_src(self, f);
490 self.consolidate_write_state_for(size, false)?;
491 Ok(result)
492 } else if st.flags.is_peer_gone() {
493 Err(st.error_or_disconnected())
494 } else {
495 Err(io::Error::other("I/O stream is closing"))
496 }
497 }
498
499 #[inline]
500 /// Provides mutable access to the transport-facing read source.
501 ///
502 /// This is the buffer the transport fills; it is the counterpart of the
503 /// application-facing destination exposed by
504 /// [`with_read_dst`](Self::with_read_dst). Primarily intended for transport
505 /// and filter implementations.
506 ///
507 /// Without a filter installed this is the same buffer as the
508 /// application-facing destination, so consuming enough of it releases read
509 /// backpressure and cancels an installed read pause. Unlike
510 /// [`with_read_dst`](Self::with_read_dst) it never clears read readiness.
511 ///
512 /// The closure must not access this connection's transport-facing read
513 /// source again. Nested access is unsupported and may terminate the
514 /// connection or lose nested buffer changes.
515 pub fn with_read_src<F, R>(&self, f: F) -> R
516 where
517 F: FnOnce(&mut BytesMut) -> R,
518 {
519 let result = self.0.buffer.with_read_src(self, f);
520 self.release_read_destination();
521 self.0.sync_read_buffered();
522 result
523 }
524
525 #[inline]
526 /// Provides mutable access to the transport-facing write destination.
527 ///
528 /// This is the buffer the transport drains; it is the counterpart of the
529 /// application-facing source exposed by
530 /// [`with_write_src`](Self::with_write_src). Primarily intended for
531 /// transport and filter implementations.
532 ///
533 /// # Panics
534 ///
535 /// Panics if the closure accesses the same transport-facing write buffer
536 /// again.
537 pub fn with_write_dst<F, R>(&self, f: F) -> R
538 where
539 F: FnOnce(&mut BytePages) -> R,
540 {
541 self.0.buffer.with_write_dst(self, f)
542 }
543
544 /// Ends the connection after the filter chain failed.
545 ///
546 /// Output the application queued can not be encoded anymore and is
547 /// discarded. The chain gets one last write pass, so that output it
548 /// produced before the failure, for example a TLS alert, moves toward
549 /// the transport; any error from that pass is the same failure. After
550 /// that the chain is not called again, output it still holds is
551 /// discarded, and the connection skips filter shutdown: the transport
552 /// shutdown phase delivers the transport-facing output, bounded by the
553 /// shutdown deadline.
554 pub(crate) fn fail_filters(&self, err: io::Error) {
555 let st = &self.0;
556 st.set_shutdown_error(err);
557 if st.flags.is_aborted() || st.flags.is_filter_failed() {
558 return;
559 }
560 log::trace!("{}: Filter chain failed, flags:{:?}", st.tag(), st.flags);
561
562 st.buffer.discard_app_output();
563 let _ = st.buffer.process_write_buf_force(self);
564 st.flags.set_filter_failed();
565 st.buffer.discard_filter_output();
566 st.sync_write_buffered();
567 st.filters_stopped();
568 }
569
570 /// Schedules buffered output for delivery and updates write state.
571 ///
572 /// When output is buffered and the write task is paused, this either
573 /// performs an eager in-place write through the transport handle or
574 /// schedules a write operation. An eager write requires direct writes to be
575 /// enabled and, unless `force` is set, at least
576 /// [`IoConfig::write_buf_threshold`](crate::IoConfig::write_buf_threshold)
577 /// bytes to be buffered; `force` makes any non-empty buffer eligible. A
578 /// write operation is scheduled when an eager write leaves data behind, or
579 /// when no eager write was attempted.
580 ///
581 /// Returns the connection error once the connection is stopping or
582 /// terminating with an error set. This is how a failed eager write or
583 /// filter reaches the caller, and it also prevents further eager writes on
584 /// a connection that is already gone.
585 ///
586 /// Finally enables write back-pressure and wakes the dispatcher if buffered
587 /// output has reached the configured high watermark. The size is re-read
588 /// first because an eager write may have drained it.
589 #[inline]
590 pub(crate) fn consolidate_write_state(&self, force: bool) -> io::Result<()> {
591 self.consolidate_write_state_for(self.0.buffer.write_buf_size(), force)
592 }
593
594 /// Same as [`consolidate_write_state`](Self::consolidate_write_state),
595 /// `size` is the current `Stack::write_buf_size()`.
596 fn consolidate_write_state_for(&self, size: usize, force: bool) -> io::Result<()> {
597 let st = &self.0;
598
599 // set when a direct write may have changed the outstanding output
600 let mut wrote = false;
601
602 #[cfg(feature = "trace")]
603 log::trace!("{}: write-upd == buf:{size} flags:{:?}", st.tag(), st.flags);
604
605 if size > 0 && st.flags.is_write_paused() {
606 // The app encodes data in response to incoming data,
607 // continuing to fill the write buffer until all data
608 // has been processed. Only then can the runtime wake
609 // the write task to send the buffered data.
610 //
611 // By that time, the buffer may have accumulated a large
612 // amount of data, causing it to be sent in large bursts,
613 // which introduces latency. To prevent this behavior and
614 // flatten data delivery to the peer, IoRef can initiate
615 // out-of-order writes based on a configured threshold.
616 if st.flags.is_direct_wr_enabled() && (force || size >= st.cfg().write_buf_threshold())
617 {
618 // Send data in-place
619 wrote = true;
620 let partial = self.call_write() == WakeWriteTask::Yes;
621 st.metrics().eager_write(partial);
622 if partial {
623 #[cfg(feature = "trace")]
624 log::trace!(
625 "{}: write-upd == schedule(more):{} flags:{:?}",
626 st.tag(),
627 st.buffer.write_buf_size(),
628 st.flags
629 );
630 if !st.flags.is_wr_send_scheduled() {
631 // More data needs to be sent
632 st.flags.set_wr_send_scheduled();
633 Iops::schedule_write(st.id());
634 }
635 } else {
636 st.flags.unset_wr_send_scheduled();
637 }
638 } else if !st.flags.is_wr_send_scheduled() {
639 #[cfg(feature = "trace")]
640 log::trace!("{}: write-upd == schedule(too small)", st.tag());
641 st.metrics().scheduled_write();
642 st.flags.set_wr_send_scheduled();
643 Iops::schedule_write(st.id());
644 }
645 }
646
647 if !st.flags.is_active()
648 && let Some(err) = st.error()
649 {
650 return Err(err);
651 }
652
653 // A direct write may have changed the amount of buffered data.
654 // In-flight output counts too: it has not reached the peer yet.
655 let mut outstanding = if wrote {
656 st.write_outstanding()
657 } else {
658 size + st.wr_inflight.get() as usize
659 };
660 if st.enable_wr_backpressure_for(outstanding) {
661 outstanding = st.write_outstanding();
662 }
663 st.sync_write_buffered_for(outstanding);
664 Ok(())
665 }
666
667 /// Updates read state after the application-facing destination was accessed.
668 ///
669 /// While read back-pressure is active nothing is released until `buf` has
670 /// fallen to at most half the high watermark. Until then read readiness and
671 /// any installed read pause are deliberately left in place, keeping the
672 /// transport read task parked. Once it has, read readiness and
673 /// back-pressure are cleared together; without back-pressure only read
674 /// readiness is cleared.
675 ///
676 /// Whenever something is released, a pause installed by
677 /// [`Io::poll_read_pause`](crate::Io::poll_read_pause) is cancelled and the
678 /// transport read task is woken.
679 ///
680 /// See [`release_read_destination`](Self::release_read_destination) for the
681 /// variant used when the caller may have drained a different buffer of the
682 /// filter chain.
683 fn update_read_destination(&self, buf: &mut BytesMut) {
684 let st = &self.0;
685
686 #[cfg(feature = "trace")]
687 log::trace!(
688 "{}: read-upd == buf:{} flags:{:?}",
689 st.tag(),
690 buf.len(),
691 st.flags
692 );
693
694 if st.flags.is_rd_backpressure() {
695 // Keep reads paused until enough buffered data has been consumed.
696 if !st.should_disable_rd_backpressure(buf.len()) {
697 return;
698 }
699 st.unset_read_ready_and_backpressure();
700 } else {
701 st.flags.unset_read_ready();
702 }
703
704 if st.flags.is_read_paused() {
705 st.resume_read_task();
706 }
707 }
708
709 /// Releases read backpressure and any installed read pause.
710 ///
711 /// Used by the accessors that can drain the application-facing read
712 /// destination without going through
713 /// [`with_read_dst`](Self::with_read_dst). Unlike
714 /// `update_read_destination()` this never clears read readiness, because
715 /// the caller may have touched a different buffer of the chain. It only
716 /// removes a stale pause, so it can never suppress a wakeup.
717 fn release_read_destination(&self) {
718 let st = &self.0;
719
720 if st.flags.is_rd_backpressure() {
721 if !st.should_disable_rd_backpressure(st.buffer.read_dst_size()) {
722 return;
723 }
724 st.unset_read_ready_and_backpressure();
725 }
726
727 if st.flags.is_read_paused() {
728 st.resume_read_task();
729 }
730 }
731
732 /// Wakeup dispatcher
733 pub fn notify_dispatcher(&self) {
734 log::trace!("{}: Timer, notify dispatcher", self.tag());
735 self.0.wake_dispatch_task();
736 }
737
738 /// Wakeup dispatcher and send Timeout error
739 pub fn notify_timeout(&self) {
740 self.0.notify_timeout();
741 }
742
743 /// Returns the currently registered dispatcher timer handle.
744 ///
745 /// [`TimerHandle::ZERO`] is returned when no timer is registered.
746 pub fn timer_handle(&self) -> TimerHandle {
747 self.0.timeout.get()
748 }
749
750 /// Starts or updates the dispatcher timer.
751 ///
752 /// The timer uses second-granularity deadlines. When it expires,
753 /// [`poll_status_update`](crate::Io::poll_status_update) reports
754 /// [`IoStatusUpdate::Timeout`](crate::IoStatusUpdate::Timeout).
755 ///
756 /// A zero timeout cancels the current timer but does not consume a timeout
757 /// notification that has already been delivered. Use
758 /// [`stop_timer`](Self::stop_timer) when leaving a protocol phase to also
759 /// clear such a notification.
760 pub fn start_timer(&self, timeout: Seconds) -> TimerHandle {
761 let cur_hnd = self.0.timeout.get();
762
763 if timeout.is_zero() {
764 if cur_hnd.is_set() {
765 self.0.timeout.set(TimerHandle::ZERO);
766 cur_hnd.unregister(self);
767 }
768 TimerHandle::ZERO
769 } else if cur_hnd.is_set() {
770 let hnd = cur_hnd.update(timeout, self);
771 if hnd != cur_hnd {
772 log::trace!("{}: Update timer {:?}", self.tag(), timeout);
773 self.0.timeout.set(hnd);
774 }
775 hnd
776 } else {
777 log::trace!("{}: Start timer {:?}", self.tag(), timeout);
778 let hnd = TimerHandle::register(timeout, self);
779 self.0.timeout.set(hnd);
780 hnd
781 }
782 }
783
784 /// Stops the timer and clears any pending timeout notification.
785 pub fn stop_timer(&self) {
786 self.0.flags.check_dispatcher_timeout();
787
788 let hnd = self.0.timeout.get();
789 if hnd.is_set() {
790 log::trace!("{}: Stop timer", self.tag());
791 self.0.timeout.set(TimerHandle::ZERO);
792 hnd.unregister(self);
793 }
794 }
795
796 /// Returns a future that resolves when the complete I/O stream disconnects.
797 ///
798 /// A clean peer read EOF does not resolve this future because the write
799 /// half remains usable. It resolves once the transport backend reports
800 /// that teardown has finished, which happens after local shutdown or
801 /// force termination. [`terminate`](Self::terminate) requests that
802 /// teardown but does not itself resolve the future.
803 pub fn on_disconnect(&self) -> Waiter<'static> {
804 Waiter::new_static(self.clone(), TAG_DISCONNECT)
805 }
806
807 /// Wakes all [`Waiter`](crate::Waiter) waiters of the tag.
808 ///
809 /// Tags reserved for internal use are ignored.
810 pub fn wake(&self, tag: usize) {
811 if tag < TAG_WRITE {
812 self.0.extensions.wake(tag);
813 }
814 }
815
816 /// Creates a [`Waiter`](crate::Waiter) for the tag.
817 ///
818 /// The waiter registers on its first poll.
819 ///
820 /// # Panics
821 ///
822 /// Panics in debug builds if the tag is reserved for internal use,
823 /// `usize::MAX - 1` and `usize::MAX - 2` are reserved.
824 pub fn waiter(&self, tag: usize) -> Waiter<'_> {
825 Waiter::new(self, tag)
826 }
827
828 #[doc(hidden)]
829 /// Register filter callbacks
830 ///
831 /// The callbacks are discarded once the connection is closed or its `Io`
832 /// has been dropped. They are released together with the `Io`, so storing
833 /// them afterwards could keep the connection state alive through an
834 /// `IoRef` they hold.
835 pub fn register_filter_callbacks<F: crate::IoCallbacks + 'static>(&self, f: F) {
836 if !self.0.flags.is_closed() && !self.0.is_io_dropped() {
837 self.0.flags.unset_plain_filter();
838 self.0.extensions.register_filter_callbacks(f);
839 }
840 }
841
842 #[doc(hidden)]
843 /// Returns `true` while filter callbacks of this connection run.
844 pub fn is_in_filter_callbacks(&self) -> bool {
845 self.0.flags.is_in_callbacks()
846 }
847
848 /// Call handle write method, returns true if `write-paused` is still set
849 fn call_write(&self) -> WakeWriteTask {
850 if let Some(hnd) = self.0.handle.take() {
851 self.0.flags.unset_write_paused();
852 #[cfg(feature = "trace")]
853 log::trace!(
854 "{}: call-write ({}), flags:{:?}",
855 self.tag(),
856 self.0.buffer.write_buf_size(),
857 self.0.flags
858 );
859 hnd.write(IoContext::from_ref(self));
860 self.restore_handle(hnd);
861 }
862 if self.0.flags.is_write_paused() {
863 WakeWriteTask::No
864 } else {
865 WakeWriteTask::Yes
866 }
867 }
868
869 /// Reinstalls the transport handle after a reentrant transport callback.
870 ///
871 /// The handle is taken for the duration of the call so that a nested
872 /// `call_write()` or query cannot reenter the transport. If the
873 /// callback terminated the connection, `terminate_connection()` and
874 /// `stop_connection()` found the slot empty and could not release the
875 /// transport, so the handle is dropped here instead of being reinstalled.
876 /// A graceful shutdown keeps it: the write task still needs the transport
877 /// to shut it down.
878 pub(crate) fn restore_handle(&self, hnd: Box<dyn Handle>) {
879 if self.0.flags.is_terminating() || self.0.flags.is_closed() {
880 drop(hnd);
881 } else {
882 self.0.handle.set(Some(hnd));
883 }
884 }
885
886 pub(crate) fn with_callbacks<F>(&self, f: F)
887 where
888 F: FnOnce(&dyn crate::IoCallbacks),
889 {
890 self.0.extensions.with_callbacks(|cb| {
891 let _guard = CallbacksGuard::enter(&self.0.flags);
892 f(cb);
893 });
894 }
895}
896
897/// Marks filter callbacks as running until dropped, unwinding included.
898struct CallbacksGuard<'a>(Option<&'a Flags>);
899
900impl<'a> CallbacksGuard<'a> {
901 fn enter(flags: &'a Flags) -> Self {
902 // a nested run leaves the flag to the outer run
903 if flags.is_in_callbacks() {
904 Self(None)
905 } else {
906 flags.set_in_callbacks();
907 Self(Some(flags))
908 }
909 }
910}
911
912impl Drop for CallbacksGuard<'_> {
913 fn drop(&mut self) {
914 if let Some(flags) = self.0 {
915 flags.unset_in_callbacks();
916 }
917 }
918}
919
920#[derive(Copy, Clone, PartialEq, Eq, Debug)]
921enum WakeWriteTask {
922 Yes,
923 No,
924}
925
926impl Eq for IoRef {}
927
928impl PartialEq for IoRef {
929 #[inline]
930 fn eq(&self, other: &Self) -> bool {
931 self.0.eq(&other.0)
932 }
933}
934
935impl hash::Hash for IoRef {
936 #[inline]
937 fn hash<H: hash::Hasher>(&self, state: &mut H) {
938 self.0.hash(state);
939 }
940}
941
942impl fmt::Debug for IoRef {
943 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
944 f.debug_struct("IoRef")
945 .field("state", self.0.as_ref())
946 .finish()
947 }
948}
949
950#[cfg(test)]
951mod tests {
952 use std::cell::{Cell, RefCell};
953 use std::{future::Future, future::poll_fn, pin::Pin, rc::Rc, task::Poll};
954
955 use ntex_bytes::Bytes;
956 use ntex_codec::BytesCodec;
957 use ntex_util::future::{Either, lazy};
958 use ntex_util::time::{Millis, sleep, timeout};
959
960 use super::*;
961
962 /// STATEMENT: Active, terminating, and closed predicates describe independent lifecycle properties.
963 ///
964 /// HOW:
965 /// - Terminate an active connection and check it becomes inactive before transport closure.
966 /// - Gracefully shut down another connection and verify it closes without reporting termination.
967 #[ntex::test]
968 async fn lifecycle_predicates_are_independent() {
969 // a force termination starts: it ends abnormally and is closing, but
970 // the backend still holds the socket
971 let (_client, server) = IoTest::create();
972 let io = Io::from(server);
973 assert!(io.is_active() && !io.flags().is_terminating() && !io.is_closed());
974
975 io.terminate();
976 assert!(!io.is_active());
977 assert!(io.flags().is_terminating());
978 assert!(!io.is_closed(), "socket released before teardown ran");
979
980 // a graceful shutdown also releases the socket, without ever being an
981 // abnormal ending
982 let (client, server) = IoTest::create();
983 client.remote_buffer_cap(1024);
984 let io = Io::from(server);
985 io.shutdown().await.unwrap();
986 assert!(io.is_closed());
987 assert!(!io.is_active());
988 assert!(
989 !io.flags().is_terminating(),
990 "a graceful shutdown reported as an abort"
991 );
992 }
993 use crate::{FilterCtx, Io, testing::IoTest};
994
995 const BIN: &[u8] = b"GET /test HTTP/1\r\n\r\n";
996 const TEXT: &str = "GET /test HTTP/1\r\n\r\n";
997
998 /// STATEMENT: Connection references preserve identity and propagate data, I/O errors, and termination.
999 ///
1000 /// HOW:
1001 /// - Compare references and formatting, exchange bytes through receive/decode and encode/send APIs.
1002 /// - Inject read/write errors, check closed-state errors, then terminate and shut down a fresh connection.
1003 #[ntex::test]
1004 async fn utils() {
1005 let (client, server) = IoTest::create();
1006 client.remote_buffer_cap(1024);
1007 client.write(TEXT);
1008
1009 let state = Io::from(server);
1010 assert_eq!(state.get_ref(), state.get_ref());
1011
1012 let msg = state.recv(&BytesCodec).await.unwrap().unwrap();
1013 assert_eq!(msg, Bytes::from_static(BIN));
1014 assert_eq!(state.get_ref(), state.as_ref().clone());
1015 assert!(format!("{state:?}").find("Io {").is_some());
1016 assert!(format!("{:?}", state.get_ref()).find("IoRef {").is_some());
1017
1018 let res = poll_fn(|cx| Poll::Ready(state.poll_recv(&BytesCodec, cx))).await;
1019 assert!(res.is_pending());
1020 client.write(TEXT);
1021 sleep(Millis(50)).await;
1022 let res = poll_fn(|cx| Poll::Ready(state.poll_recv(&BytesCodec, cx))).await;
1023 if let Poll::Ready(msg) = res {
1024 assert_eq!(msg.unwrap(), Bytes::from_static(BIN));
1025 }
1026
1027 client.read_error(io::Error::other("err"));
1028 let msg = state.recv(&BytesCodec).await;
1029 assert!(msg.is_err());
1030 assert!(state.flags().is_closed());
1031
1032 let (client, server) = IoTest::create();
1033 client.remote_buffer_cap(1024);
1034 let state = Io::from(server);
1035
1036 client.read_error(io::Error::other("err"));
1037 let res = poll_fn(|cx| Poll::Ready(state.poll_recv(&BytesCodec, cx))).await;
1038 if let Poll::Ready(msg) = res {
1039 assert!(msg.is_err());
1040 assert!(state.flags().is_closed());
1041 }
1042
1043 let (client, server) = IoTest::create();
1044 client.remote_buffer_cap(1024);
1045 let state = Io::from(server);
1046 assert_eq!(0, state.with_write_dst(|b| b.len()));
1047 state.encode_slice(b"test").unwrap();
1048 assert_eq!(4, state.with_write_dst(|b| b.len()));
1049 let buf = client.read().await.unwrap();
1050 assert_eq!(buf, Bytes::from_static(b"test"));
1051
1052 client.write(b"test");
1053 state.read_more().await.unwrap();
1054 let buf = state.decode(&BytesCodec).unwrap().unwrap();
1055 assert_eq!(buf, Bytes::from_static(b"test"));
1056
1057 client.write_error(io::Error::other("err"));
1058 let err = state
1059 .send(Bytes::from_static(b"test"), &BytesCodec)
1060 .await
1061 .unwrap_err();
1062 assert!(matches!(
1063 err,
1064 Either::Right(ref err)
1065 if err.kind() == io::ErrorKind::Other && err.to_string() == "err"
1066 ));
1067 assert!(state.flags().is_closed());
1068
1069 let res = state.send(Bytes::from_static(b"test"), &BytesCodec).await;
1070 assert!(res.is_err());
1071
1072 let (client, server) = IoTest::create();
1073 client.remote_buffer_cap(1024);
1074 let state = Io::from(server);
1075 state.terminate();
1076 assert!(state.flags().is_terminating());
1077 assert!(!state.flags().is_stopping());
1078 assert!(!state.flags().is_closed());
1079 state.shutdown().await.unwrap();
1080 assert!(state.flags().is_closed());
1081 }
1082
1083 /// STATEMENT: A zero-byte transport write fails sending with `WriteZero` and closes the connection.
1084 ///
1085 /// HOW:
1086 /// - Configure a zero-byte write, send a frame, and check the error kind and closed state.
1087 #[ntex::test]
1088 async fn zero_byte_write_reports_write_zero() {
1089 let (client, server) = IoTest::create();
1090 client.remote_buffer_cap(1024);
1091 let state = Io::from(server);
1092
1093 client.write_zero();
1094 let err = state
1095 .send(Bytes::from_static(b"test"), &BytesCodec)
1096 .await
1097 .unwrap_err();
1098
1099 assert!(matches!(
1100 err,
1101 Either::Right(ref err) if err.kind() == io::ErrorKind::WriteZero
1102 ));
1103 assert!(state.flags().is_closed());
1104 }
1105
1106 /// STATEMENT: Disconnect waiters resolve on transport closure, not merely read EOF.
1107 ///
1108 /// HOW:
1109 /// - Poll original and cloned waiters, close peer input, and verify both still wait.
1110 /// - Finish shutdown and check both complete; repeat with a read error and post-close registrations.
1111 #[ntex::test]
1112 #[allow(clippy::unit_cmp)]
1113 async fn on_disconnect() {
1114 let (client, server) = IoTest::create();
1115 let state = Io::from(server);
1116 let mut waiter = state.on_disconnect();
1117 assert_eq!(
1118 lazy(|cx| Pin::new(&mut waiter).poll(cx)).await,
1119 Poll::Pending
1120 );
1121 let mut waiter2 = waiter.clone();
1122 assert_eq!(
1123 lazy(|cx| Pin::new(&mut waiter2).poll(cx)).await,
1124 Poll::Pending
1125 );
1126 client.close().await;
1127 assert!(state.is_read_eof());
1128 assert!(state.is_active());
1129 assert_eq!(
1130 lazy(|cx| Pin::new(&mut waiter).poll(cx)).await,
1131 Poll::Pending
1132 );
1133 assert_eq!(
1134 lazy(|cx| Pin::new(&mut waiter2).poll(cx)).await,
1135 Poll::Pending
1136 );
1137
1138 timeout(Millis(1000), state.shutdown())
1139 .await
1140 .expect("stream shutdown did not complete")
1141 .unwrap();
1142 timeout(Millis(1000), waiter)
1143 .await
1144 .expect("disconnect waiter was not notified");
1145 timeout(Millis(1000), waiter2)
1146 .await
1147 .expect("cloned disconnect waiter was not notified");
1148
1149 let mut waiter = state.on_disconnect();
1150 assert_eq!(
1151 lazy(|cx| Pin::new(&mut waiter).poll(cx)).await,
1152 Poll::Ready(())
1153 );
1154
1155 let (client, server) = IoTest::create();
1156 let state = Io::from(server);
1157 let mut waiter = state.on_disconnect();
1158 assert_eq!(
1159 lazy(|cx| Pin::new(&mut waiter).poll(cx)).await,
1160 Poll::Pending
1161 );
1162 client.read_error(io::Error::other("err"));
1163 assert_eq!(waiter.await, ());
1164
1165 let mut waiter = state.on_disconnect();
1166 assert_eq!(
1167 lazy(|cx| Pin::new(&mut waiter).poll(cx)).await,
1168 Poll::Ready(())
1169 );
1170 }
1171
1172 /// STATEMENT: Terminated connections reject all tested application write entrypoints.
1173 ///
1174 /// HOW:
1175 /// - Terminate a connection and check slice encoding, byte encoding, and write-buffer access fail.
1176 #[ntex::test]
1177 async fn write_to_closed_io() {
1178 let (_client, server) = IoTest::create();
1179 let state = Io::from(server);
1180 state.terminate();
1181
1182 assert!(!state.is_active());
1183 assert!(state.encode_slice(TEXT.as_bytes()).is_err());
1184 assert!(state.encode_bytes(Bytes::from_static(BIN)).is_err());
1185 assert!(
1186 state
1187 .with_write_src(|buf| buf.extend_from_slice(BIN))
1188 .is_err()
1189 );
1190 }
1191
1192 #[derive(Debug)]
1193 struct Counter<F> {
1194 layer: F,
1195 idx: usize,
1196 out_bytes: Rc<Cell<usize>>,
1197 read_order: Rc<RefCell<Vec<usize>>>,
1198 write_order: Rc<RefCell<Vec<usize>>>,
1199 }
1200
1201 impl<F: Filter> Filter for Counter<F> {
1202 fn process_read_buf(&self, ctx: &mut FilterCtx<'_>) -> io::Result<()> {
1203 self.read_order.borrow_mut().push(self.idx);
1204 self.layer.process_read_buf(ctx)
1205 }
1206
1207 fn process_write_buf(&self, ctx: &mut FilterCtx<'_>) -> io::Result<()> {
1208 self.write_order.borrow_mut().push(self.idx);
1209 ctx.with_buffer(|buf| {
1210 buf.with_write_buffers(|src, _| {
1211 self.out_bytes.set(self.out_bytes.get() + src.len());
1212 });
1213 });
1214 self.layer.process_write_buf(ctx)
1215 }
1216
1217 crate::forward_ready!(layer);
1218 crate::forward_query!(layer);
1219 crate::forward_shutdown!(layer);
1220 }
1221
1222 /// STATEMENT: A mapped and sealed filter continues processing reads and queued output.
1223 ///
1224 /// HOW:
1225 /// - Exchange data through a counting wrapper, then receive again.
1226 /// - Check payloads and that output was observed in whole four-byte passes at least twice.
1227 #[ntex::test]
1228 async fn filter() {
1229 let out_bytes = Rc::new(Cell::new(0));
1230 let read_order = Rc::new(RefCell::new(Vec::new()));
1231 let write_order = Rc::new(RefCell::new(Vec::new()));
1232
1233 let (client, server) = IoTest::create();
1234 let io = Io::from(server)
1235 .map_filter(|layer| Counter {
1236 layer,
1237 idx: 1,
1238 out_bytes: out_bytes.clone(),
1239 read_order: read_order.clone(),
1240 write_order: write_order.clone(),
1241 })
1242 .seal();
1243
1244 client.remote_buffer_cap(1024);
1245 client.write(TEXT);
1246 let msg = io.recv(&BytesCodec).await.unwrap().unwrap();
1247 assert_eq!(msg, Bytes::from_static(BIN));
1248
1249 io.send(Bytes::from_static(b"test"), &BytesCodec)
1250 .await
1251 .unwrap();
1252 let buf = client.read().await.unwrap();
1253 assert_eq!(buf, Bytes::from_static(b"test"));
1254
1255 client.write(TEXT);
1256 let msg = io.recv(&BytesCodec).await.unwrap().unwrap();
1257 assert_eq!(msg, Bytes::from_static(BIN));
1258
1259 // the number of write passes depends on how often the runtime polls
1260 // `send()`, each pass sees the 4 queued bytes until the transport
1261 // writes them, at least once from `send()` and once from the transport
1262 assert!(out_bytes.get() >= 8, "{}", out_bytes.get());
1263 assert_eq!(out_bytes.get() % 4, 0, "{}", out_bytes.get());
1264 }
1265
1266 /// STATEMENT: Sealing nested filter wrappers preserves processing order and releases their state.
1267 ///
1268 /// HOW:
1269 /// - Exchange bytes through two counting wrappers and verify output accounting and a drained buffer.
1270 /// - Drop the connection, check released counter references, and inspect ordered read/write callbacks.
1271 #[ntex::test]
1272 async fn boxed_filter() {
1273 let out_bytes = Rc::new(Cell::new(0));
1274 let read_order = Rc::new(RefCell::new(Vec::new()));
1275 let write_order = Rc::new(RefCell::new(Vec::new()));
1276
1277 let (client, server) = IoTest::create();
1278 let state = Io::from(server)
1279 .map_filter(|layer| Counter {
1280 layer,
1281 idx: 2,
1282 out_bytes: out_bytes.clone(),
1283 read_order: read_order.clone(),
1284 write_order: write_order.clone(),
1285 })
1286 .map_filter(|layer| Counter {
1287 layer,
1288 idx: 1,
1289 out_bytes: out_bytes.clone(),
1290 read_order: read_order.clone(),
1291 write_order: write_order.clone(),
1292 });
1293 let state = state.seal();
1294
1295 client.remote_buffer_cap(1024);
1296 client.write(TEXT);
1297 let msg = state.recv(&BytesCodec).await.unwrap().unwrap();
1298 assert_eq!(msg, Bytes::from_static(BIN));
1299
1300 state
1301 .send(Bytes::from_static(b"test"), &BytesCodec)
1302 .await
1303 .unwrap();
1304 let buf = client.read().await.unwrap();
1305 assert_eq!(buf, Bytes::from_static(b"test"));
1306
1307 // the number of write passes depends on how often the runtime polls
1308 // `send()`, each pass sees the 4 queued bytes in both layers until the
1309 // transport writes them, at least once from `send()` and once from the
1310 // transport
1311 assert!(out_bytes.get() >= 16, "{}", out_bytes.get());
1312 assert_eq!(out_bytes.get() % 8, 0, "{}", out_bytes.get());
1313 assert_eq!(state.0.buffer.with_write_dst(&state, |b| b.len()), 0);
1314
1315 // refs
1316 assert_eq!(Rc::strong_count(&out_bytes), 3);
1317 drop(state);
1318 assert_eq!(Rc::strong_count(&out_bytes), 1);
1319 assert_eq!(*read_order.borrow(), &[1, 2][..]);
1320 let write_order = write_order.borrow();
1321 assert!(write_order.len() >= 6, "{write_order:?}");
1322 assert!(
1323 write_order.chunks(2).all(|c| c == [1, 2]),
1324 "{write_order:?}"
1325 );
1326 }
1327
1328 /// STATEMENT: Connection timers reuse unchanged deadlines, update changed ones, and cancel at zero.
1329 ///
1330 /// HOW:
1331 /// - Start and repeat a timer, change its timeout, and compare handles and remaining durations.
1332 /// - Share a deadline with another connection, cancel both, and check timer-handle duration arithmetic.
1333 #[ntex::test]
1334 async fn timer_start_update_and_stop() {
1335 let (_client, server) = IoTest::create();
1336 let io = Io::new(server, SharedCfg::new("TIMER"));
1337 assert_eq!(io.shared().tag(), "TIMER");
1338 assert_eq!(io.timer_handle(), TimerHandle::ZERO);
1339
1340 let hnd = io.start_timer(Seconds(5));
1341 assert!(hnd.is_set());
1342 assert_eq!(io.timer_handle(), hnd);
1343 assert!(hnd.remains() >= Seconds(4) && hnd.remains() <= Seconds(5));
1344 assert!(hnd.instant() > TimerHandle::ZERO.instant());
1345
1346 // the same timeout keeps the registration
1347 assert_eq!(io.start_timer(Seconds(5)), hnd);
1348 assert_eq!(io.timer_handle(), hnd);
1349
1350 // a different timeout moves it
1351 let hnd2 = io.start_timer(Seconds(30));
1352 assert_ne!(hnd2, hnd);
1353 assert_eq!(io.timer_handle(), hnd2);
1354 assert!(hnd2.remains() >= Seconds(29));
1355
1356 // a second io can share the deadline slot
1357 let (_client2, server2) = IoTest::create();
1358 let io2 = Io::from(server2);
1359 assert!(io2.start_timer(Seconds(30)).is_set());
1360
1361 // zero timeout cancels the timer
1362 assert_eq!(io.start_timer(Seconds::ZERO), TimerHandle::ZERO);
1363 assert_eq!(io.timer_handle(), TimerHandle::ZERO);
1364 assert_eq!(io.start_timer(Seconds::ZERO), TimerHandle::ZERO);
1365 io2.stop_timer();
1366
1367 let hnd = TimerHandle::ZERO + Seconds(3);
1368 assert!(hnd.is_set());
1369 assert_eq!(
1370 hnd.instant() - TimerHandle::ZERO.instant(),
1371 std::time::Duration::from_secs(3)
1372 );
1373 }
1374
1375 /// STATEMENT: Dispatcher notification wakes a status waiter without manufacturing a status update.
1376 ///
1377 /// HOW:
1378 /// - Register a flag-setting waker with a pending status poll and notify the dispatcher.
1379 /// - Check the flag is set while the next status poll remains pending.
1380 #[ntex::test]
1381 async fn notify_dispatcher_wakes_status_poll() {
1382 use std::sync::{Arc, atomic::AtomicBool, atomic::Ordering};
1383
1384 struct Flag(AtomicBool);
1385
1386 impl std::task::Wake for Flag {
1387 fn wake(self: Arc<Self>) {
1388 self.0.store(true, Ordering::Relaxed);
1389 }
1390 }
1391
1392 let (_client, server) = IoTest::create();
1393 let io = Io::from(server);
1394
1395 let flag = Arc::new(Flag(AtomicBool::new(false)));
1396 let waker = std::task::Waker::from(flag.clone());
1397 let mut cx = std::task::Context::from_waker(&waker);
1398 assert!(io.poll_status_update(&mut cx).is_pending());
1399
1400 io.notify_dispatcher();
1401 assert!(flag.0.load(Ordering::Relaxed));
1402 // a plain wakeup reports no status update
1403 assert!(lazy(|cx| io.poll_status_update(cx)).await.is_pending());
1404 }
1405
1406 /// STATEMENT: Connection and reference hashing distinguish identities while deduplicating the same connection.
1407 ///
1408 /// HOW:
1409 /// - Insert repeated references to one connection and a distinct connection into separate hash sets.
1410 /// - Check duplicate insertion fails for both `IoRef` and borrowed `Io` keys.
1411 #[ntex::test]
1412 #[allow(clippy::mutable_key_type)]
1413 async fn io_ref_hash() {
1414 let (_client, server) = IoTest::create();
1415 let io = Io::from(server);
1416 let (_client2, server2) = IoTest::create();
1417 let io2 = Io::from(server2);
1418
1419 let mut set = std::collections::HashSet::new();
1420 assert!(set.insert(io.get_ref()));
1421 assert!(!set.insert(io.get_ref()));
1422 assert!(set.insert(io2.get_ref()));
1423
1424 let mut set = std::collections::HashSet::new();
1425 assert!(set.insert(&io));
1426 assert!(!set.insert(&io));
1427 assert!(set.insert(&io2));
1428 }
1429}