ntex_io/io/mod.rs
1use std::cell::{Cell, UnsafeCell};
2use std::{fmt, hash, io, marker, mem, ops, ptr, rc::Rc, sync::Arc};
3
4use ntex_bytes::BytePageSize;
5use ntex_service::cfg::{Cfg, SharedCfg};
6use ntex_util::{task::LocalWaker, time::Sleep};
7
8use crate::buf::Stack;
9use crate::cfg::IoConfig;
10use crate::ctx::IoContext;
11use crate::filter::{Base, Filter, Layer};
12use crate::filterptr::FilterPtr;
13use crate::flags::Flags;
14use crate::metrics::{CloseReason, IoMetrics};
15use crate::ops::{Id, IoManager, TimerHandle};
16use crate::seal::{IoBoxed, Sealed};
17use crate::utils::Extensions;
18use crate::{FilterLayer, Handle, IoStream};
19
20mod state;
21mod stream;
22#[cfg(test)]
23mod tests;
24
25/// Read batches in a row small enough for a smaller page before the read page
26/// size shrinks.
27const RD_SHRINK_BATCHES: u8 = 4;
28
29/// Buffered, filterable interface to an underlying I/O stream.
30///
31/// `Io` is the main handle for a connection. The runtime fills its read buffer
32/// and drains its write buffer, while protocol code uses this handle to decode
33/// requests and encode responses.
34///
35/// Reads and writes go through buffers rather than directly to the socket.
36/// When the read buffer grows too large, ntex pauses the transport.
37/// [`read_more`](Self::read_more) can resume it, so calling that method asks
38/// for more input; it does more than check whether data is already available.
39///
40/// If the peer cleanly closes its read side, any buffered input remains
41/// available and responses can still be written. [`shutdown`](Self::shutdown)
42/// closes the connection gracefully and waits for the runtime to finish.
43/// [`terminate`](IoRef::terminate) closes it immediately.
44///
45/// The `F` parameter keeps track of the installed filters. Adding or mapping a
46/// filter changes the type. Use [`seal`](Self::seal) or [`boxed`](Self::boxed)
47/// when the concrete filter type does not need to be exposed.
48///
49/// Use [`get_ref`](Self::get_ref) to share access to the connection. The
50/// returned [`IoRef`] points to the same buffers and state; it does not create
51/// another connection. Dropping `Io` terminates the connection even if an
52/// `IoRef` is still alive.
53pub struct Io<F = Base>(UnsafeCell<IoRef>, marker::PhantomData<F>);
54
55/// A cheap, cloneable handle to an [`Io`] connection.
56///
57/// All clones point to the same connection. Changes to its buffers,
58/// configuration, timers, errors, or shutdown state are visible through every
59/// clone. Cloning `IoRef` never clones the socket.
60///
61/// Use it to inspect the connection, access its buffers, queue output, or start
62/// graceful or immediate shutdown. These methods are also available directly
63/// on `Io`, which dereferences to `IoRef`.
64///
65/// Keeping an `IoRef` alive does not keep the connection open after its `Io`
66/// owner is dropped. Like `Io`, it stays on the local runtime thread and is
67/// neither `Send` nor `Sync`.
68#[derive(Clone)]
69pub struct IoRef(pub(super) Rc<IoState>);
70
71// `repr(C)` keeps the fields read on every I/O event, `flags`, `wr_inflight`
72// and the head of `buffer`, together at the start. The rest is ordered by
73// alignment, so no padding is added.
74#[repr(C)]
75pub(crate) struct IoState {
76 pub(super) flags: Flags,
77 /// Bytes handed to the transport that have not reached the peer yet.
78 ///
79 /// Completion based transports take ownership of write pages and keep them
80 /// until the operation completes, so those bytes are no longer in
81 /// `buffer`. They are still outstanding output and must be accounted for.
82 ///
83 /// The count saturates at `u32::MAX`. More than 4 GiB in flight is not
84 /// tracked exactly, see [`Io::poll_flush`].
85 pub(super) wr_inflight: Cell<u32>,
86 pub(super) buffer: Stack,
87 pub(super) read_task: LocalWaker,
88 pub(super) write_task: LocalWaker,
89 dispatch_task: LocalWaker,
90 filter: FilterPtr,
91 pub(super) id: Cell<Id>,
92 /// Replaced only by [`Io::set_config`], read through [`IoState::cfg()`].
93 cfg: UnsafeCell<Cfg<IoConfig>>,
94 pub(super) error: Cell<Option<io::Error>>,
95 pub(super) handle: Cell<Option<Box<dyn Handle>>>,
96 pub(super) shutdown_timeout: Cell<Option<Sleep>>,
97 pub(super) extensions: Extensions,
98 metrics: UnsafeCell<Arc<IoMetrics>>,
99 /// Per-connection read buffer tracker, created on first use, see
100 /// [`IoState::buf_tracker`].
101 #[cfg(feature = "tracker")]
102 rd_tracker: UnsafeCell<Option<ntex_bytes::BytesTracker>>,
103 pub(super) timeout: Cell<TimerHandle>,
104 /// Input read since the last read that did not fill its buffer.
105 rd_batch: Cell<u32>,
106 /// Read buffer size last reported to `metrics`, saturated at `u32::MAX`.
107 rd_buffered: Cell<u32>,
108 /// Read buffer capacity last reported to `metrics`, saturated at
109 /// `u32::MAX`.
110 rd_capacity: Cell<u32>,
111 /// Write buffer size last reported to `metrics`, saturated at `u32::MAX`.
112 wr_buffered: Cell<u32>,
113 /// Page size of new read buffers.
114 ///
115 /// It adapts to the input between the configured min and max read sizes,
116 /// see [`IoState::track_read`].
117 rd_size: Cell<BytePageSize>,
118 /// Consecutive read batches small enough for a smaller page.
119 rd_small: Cell<u8>,
120 pub(super) close: Cell<Close>,
121}
122
123/// Close reason of a connection, counted in `metrics` on drop.
124#[derive(Copy, Clone, Debug)]
125pub(super) enum Close {
126 Unset,
127 Reason(CloseReason),
128 /// Placeholder state of a taken `Io`, not a connection.
129 Uncounted,
130}
131
132impl Io {
133 /// Creates a new `Io` instance.
134 pub fn new<I: IoStream, T: Into<SharedCfg>>(stream: I, cfg: T) -> Self {
135 let cfg = cfg.into().get::<IoConfig>();
136 let size = cfg.write_size();
137 let flags = Flags::new(cfg.write_buf_threshold() > 0);
138 let metrics = cfg.metrics();
139
140 let inner = Rc::new(IoState {
141 cfg: UnsafeCell::new(cfg),
142 flags,
143 id: Cell::new(Id::default()),
144 filter: FilterPtr::null(),
145 error: Cell::new(None),
146 dispatch_task: LocalWaker::new(),
147 read_task: LocalWaker::new(),
148 write_task: LocalWaker::new(),
149 buffer: Stack::new(size),
150 handle: Cell::new(None),
151 timeout: Cell::new(TimerHandle::default()),
152 shutdown_timeout: Cell::new(None),
153 wr_inflight: Cell::new(0),
154 rd_size: Cell::new(BytePageSize::Size4),
155 rd_batch: Cell::new(0),
156 rd_small: Cell::new(0),
157 #[cfg(feature = "tracker")]
158 rd_tracker: UnsafeCell::new(None),
159 extensions: Extensions::default(),
160 metrics: UnsafeCell::new(metrics),
161 rd_buffered: Cell::new(0),
162 rd_capacity: Cell::new(0),
163 wr_buffered: Cell::new(0),
164 close: Cell::new(Close::Unset),
165 });
166 inner.reset_read_size();
167 inner.filter.set(Base::new(IoRef(inner.clone())));
168
169 let ioref = IoRef(inner);
170 ioref.0.id.set(IoManager::register(&ioref));
171
172 // `Io` owns the state before the stream starts, so that a panic in
173 // `IoStream::start` drops the filter and unregisters the connection
174 let io = Io(UnsafeCell::new(ioref), marker::PhantomData);
175
176 // start io tasks
177 let hnd = stream.start(IoContext::new(io.io_ref().clone()));
178 io.st().handle.set(Some(hnd));
179 io
180 }
181}
182
183impl<I: IoStream> From<I> for Io {
184 #[inline]
185 fn from(io: I) -> Io {
186 Io::new(io, SharedCfg::default())
187 }
188}
189
190impl IoRef {
191 fn create_empty() -> IoRef {
192 IoRef(Rc::new(IoState {
193 id: Cell::new(Id::default()),
194 cfg: UnsafeCell::new(SharedCfg::default().get::<IoConfig>()),
195 filter: FilterPtr::null(),
196 flags: Flags::new_stopped(),
197 error: Cell::new(None),
198 dispatch_task: LocalWaker::new(),
199 read_task: LocalWaker::new(),
200 write_task: LocalWaker::new(),
201 buffer: Stack::new(BytePageSize::Size16),
202 handle: Cell::new(None),
203 timeout: Cell::new(TimerHandle::default()),
204 shutdown_timeout: Cell::new(None),
205 wr_inflight: Cell::new(0),
206 rd_size: Cell::new(BytePageSize::Size4),
207 rd_batch: Cell::new(0),
208 rd_small: Cell::new(0),
209 #[cfg(feature = "tracker")]
210 rd_tracker: UnsafeCell::new(None),
211 extensions: Extensions::default(),
212 metrics: UnsafeCell::new(IoMetrics::detached()),
213 rd_buffered: Cell::new(0),
214 rd_capacity: Cell::new(0),
215 wr_buffered: Cell::new(0),
216 close: Cell::new(Close::Uncounted),
217 }))
218 }
219}
220
221impl<F> Io<F> {
222 #[inline]
223 /// Returns a cloneable reference to this connection's shared state.
224 pub fn get_ref(&self) -> IoRef {
225 self.io_ref().clone()
226 }
227
228 #[inline]
229 #[must_use]
230 /// Transfers the live connection state into a new `Io` object.
231 ///
232 /// This does not clone the connection. `self` is replaced with a stopped
233 /// placeholder and should no longer be used for I/O.
234 ///
235 /// # Safety
236 ///
237 /// No reference derived from `self` may be alive across this call, the
238 /// filter returned by [`Io::filter`], the `IoRef` it dereferences to and
239 /// the config returned by [`IoRef::cfg`] all borrow the transferred state,
240 /// which is dropped together with the returned `Io`.
241 pub unsafe fn take(&self) -> Self {
242 Self(UnsafeCell::new(self.take_io_ref()), marker::PhantomData)
243 }
244
245 fn take_io_ref(&self) -> IoRef {
246 // SAFETY: Callers exclude borrows of this slot; transferred state is retained or leaked.
247 unsafe { mem::replace(&mut *self.0.get(), IoRef::create_empty()) }
248 }
249
250 /// Moves the shared state out of `self` without a placeholder, `Drop`
251 /// does not run for `self`.
252 fn into_io_ref(self) -> IoRef {
253 let this = mem::ManuallyDrop::new(self);
254 // SAFETY: `this` is not used or dropped afterwards
255 unsafe { ptr::read(this.0.get()) }
256 }
257
258 /// Panics if the filter chain is in use, it cannot be changed then.
259 #[track_caller]
260 fn check_not_borrowed(&self) {
261 if self.st().buffer.is_borrowed() {
262 let tag = self.tag();
263 // the state is leaked, dropping `self` while unwinding would
264 // drop the filter that is in use
265 mem::forget(self.take_io_ref());
266 panic!("{tag}: filter chain is changed while it is in use");
267 }
268 }
269
270 fn st(&self) -> &IoState {
271 // SAFETY: The slot owns this live state; replacing it requires excluding outstanding borrows.
272 unsafe { &(*self.0.get()).0 }
273 }
274
275 fn io_ref(&self) -> &IoRef {
276 // SAFETY: The slot stays initialized and is not replaced while its `IoRef` is borrowed.
277 unsafe { &*self.0.get() }
278 }
279
280 #[inline]
281 /// Replaces this connection's shared I/O configuration.
282 ///
283 /// The write-buffer page size and eager-write enablement are updated
284 /// immediately, the read page size restarts at the new min read size.
285 /// Existing allocated buffers and an already registered timer are not
286 /// recreated.
287 ///
288 /// With the `tracker` feature, the read buffers held by the connection
289 /// are charged to the tracker of the new `BufTracker` mode, a per-connection
290 /// tracker is kept if both configs use one. A read buffer taken by the
291 /// transport for an in-flight read keeps its charge, buffers stay
292 /// charged to the old tracker if the new mode is disabled.
293 ///
294 /// # Safety
295 ///
296 /// No reference obtained from [`IoRef::cfg`], `IoRef::buf_tracker`
297 /// or `IoContext::buf_tracker` for this connection may be live when
298 /// this method is called or used afterward. Replacing the configuration
299 /// may release the allocation backing those references.
300 pub unsafe fn set_config<T: Into<SharedCfg>>(&self, cfg: T) {
301 let cfg = cfg.into().get::<IoConfig>();
302 let page_size = cfg.write_size();
303 if self.cfg().write_size() != page_size {
304 self.st().buffer.set_page_size(page_size);
305 }
306 self.st()
307 .flags
308 .set_direct_wr_enabled(cfg.write_buf_threshold() > 0);
309 let st = self.st();
310 let metrics = cfg.metrics();
311 if !ptr::eq(st.metrics(), Arc::as_ptr(&metrics)) {
312 st.metrics().move_to(
313 &metrics,
314 st.flags.is_rd_backpressure(),
315 st.flags.is_wr_backpressure(),
316 st.rd_buffered.get(),
317 st.rd_capacity.get(),
318 st.wr_buffered.get(),
319 );
320 // SAFETY: the caller guarantees no reference into the state is live
321 unsafe {
322 *st.metrics.get() = metrics;
323 }
324 }
325 #[cfg(feature = "tracker")]
326 st.update_buf_tracker(&cfg);
327 // SAFETY: The caller guarantees no references into the previous configuration remain live.
328 unsafe {
329 *st.cfg.get() = cfg;
330 }
331 st.reset_read_size();
332 }
333}
334
335impl<F: FilterLayer, T: Filter> Io<Layer<F, T>> {
336 #[inline]
337 /// Returns a reference to a filter.
338 pub fn filter(&self) -> &F {
339 &self.st().filter.filter::<Layer<F, T>>().0
340 }
341}
342
343impl<F: Filter> Io<F> {
344 #[inline]
345 /// Converts the current I/O stream into a sealed version.
346 ///
347 /// # Panics
348 ///
349 /// Panics if called while the connection's filters or buffers are in use,
350 /// for example from a closure, codec or filter invoked by this connection.
351 pub fn seal(self) -> Io<Sealed> {
352 self.check_not_borrowed();
353 let state = self.into_io_ref();
354 state.0.filter.seal::<F>();
355
356 Io(UnsafeCell::new(state), marker::PhantomData)
357 }
358
359 #[inline]
360 /// Converts the current I/O stream into a boxed version.
361 pub fn boxed(self) -> IoBoxed {
362 IoBoxed(self.seal())
363 }
364
365 #[inline]
366 /// Adds a new processing layer to the current filter chain.
367 ///
368 /// # Panics
369 ///
370 /// Panics if called while the connection's filters or buffers are in use,
371 /// for example from a closure, codec or filter invoked by this connection.
372 pub fn add_filter<U>(self, nf: U) -> Io<Layer<U, F>>
373 where
374 U: FilterLayer,
375 {
376 self.check_not_borrowed();
377 self.with_callbacks(|cb| cb.before_processing(&self));
378
379 // Write buffer processing may be delayed,
380 // call the filter chain to process pending writes
381 if let Err(e) = self.st().buffer.process_write_buf_no_cb(&self) {
382 self.fail_filters(e);
383 }
384
385 let state = self.into_io_ref();
386
387 // Add the buffers layer
388 state.0.buffer.add_layer(state.0.cfg().write_size());
389
390 // Replace current filter
391 state.0.flags.unset_plain_filter();
392 state.0.filter.add_filter::<F, U>(nf);
393
394 let io = Io(UnsafeCell::new(state), marker::PhantomData);
395
396 // push read data into new filter
397 if let Err(e) = io.st().buffer.process_read_buf_no_cb(&io) {
398 io.fail_filters(e);
399 }
400 io.with_callbacks(|cb| cb.after_processing(&io));
401
402 io
403 }
404
405 #[allow(clippy::items_after_statements)]
406 /// Wraps the current layer with a wrapper.
407 ///
408 /// # Panics
409 ///
410 /// Panics if called while the connection's filters or buffers are in use,
411 /// for example from a closure, codec or filter invoked by this connection.
412 pub fn map_filter<U, R>(self, f: U) -> Io<R>
413 where
414 U: FnOnce(F) -> R,
415 R: Filter,
416 {
417 self.check_not_borrowed();
418 self.with_callbacks(|cb| cb.before_processing(&self));
419
420 // Write buffer processing may be delayed,
421 // call the filter chain to process pending writes
422 if let Err(e) = self.st().buffer.process_write_buf(&self) {
423 self.fail_filters(e);
424 }
425
426 // `f` owns the filter, if it unwinds the filter chain is gone and the
427 // connection must be torn down here, `Drop for Io` skips it without
428 // a filter
429 struct Guard<'a>(&'a IoRef);
430
431 impl Drop for Guard<'_> {
432 fn drop(&mut self) {
433 let st = &self.0.0;
434 st.force_close_connection();
435 st.buffer.release();
436 st.sync_read_buffered();
437 drop(st.extensions.take_callbacks());
438 }
439 }
440
441 let guard = Guard(self.io_ref());
442 self.st().flags.unset_plain_filter();
443 self.st().filter.map_filter::<F, U, R>(f);
444 mem::forget(guard);
445
446 let state = self.into_io_ref();
447 let io = Io(UnsafeCell::new(state), marker::PhantomData);
448 io.with_callbacks(|cb| cb.after_processing(&io));
449 io
450 }
451}
452
453impl<F> AsRef<IoRef> for Io<F> {
454 #[inline]
455 fn as_ref(&self) -> &IoRef {
456 self.io_ref()
457 }
458}
459
460impl<F> Eq for Io<F> {}
461
462impl<F> PartialEq for Io<F> {
463 #[inline]
464 fn eq(&self, other: &Self) -> bool {
465 self.io_ref().eq(other.io_ref())
466 }
467}
468
469impl<F> hash::Hash for Io<F> {
470 #[inline]
471 fn hash<H: hash::Hasher>(&self, state: &mut H) {
472 self.io_ref().hash(state);
473 }
474}
475
476impl<F> fmt::Debug for Io<F> {
477 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
478 f.debug_struct("Io").field("state", self.st()).finish()
479 }
480}
481
482impl<F> ops::Deref for Io<F> {
483 type Target = IoRef;
484
485 #[inline]
486 fn deref(&self) -> &Self::Target {
487 self.io_ref()
488 }
489}
490
491impl<F> Drop for Io<F> {
492 fn drop(&mut self) {
493 let st = self.st();
494 self.stop_timer();
495
496 // code run by the filter chain dropped the `Io`, the filter is in use
497 let in_use = st.filter.is_set() && st.buffer.is_borrowed();
498
499 if st.filter.is_set() {
500 if in_use {
501 // the filter cannot be dropped, it is leaked
502 st.force_close_connection();
503 st.filter.leak();
504 } else {
505 // filter is unsafe and must be dropped explicitly,
506 // and won't be dropped without special attention
507 if !st.flags.is_closed() {
508 log::trace!("{}: Io is dropped, terminate connection", st.tag());
509 }
510
511 if st.write_outstanding() == 0 {
512 // Everything the application wrote has reached the transport,
513 // so the connection can end with a normal FIN and the peer
514 // sees a clean end of stream.
515 st.terminate_connection(None);
516 } else {
517 // Output is still buffered and the filter chain is about to go
518 // away, so it can never be delivered. Abort instead, so that
519 // the peer cannot mistake a truncated stream for a complete
520 // one.
521 st.force_close_connection();
522 }
523 st.filter.drop_filter::<F>();
524 }
525
526 // Nothing can consume buffered input or deliver buffered output
527 // anymore, but the state may outlive the `Io` for a while, held by
528 // the transport while it closes or by other `IoRef` handles.
529 st.buffer.release();
530 st.sync_read_buffered();
531
532 // Callbacks may hold an `IoRef` to this connection, which would keep
533 // the state alive through a reference cycle. They are dropped outside
534 // the extensions borrow, because their destructor may use the `IoRef`.
535 drop(st.extensions.take_callbacks());
536 }
537
538 IoManager::unregister(self.io_ref());
539
540 // a panic while unwinding would abort
541 assert!(
542 !in_use || std::thread::panicking(),
543 "{}: Io is dropped while its filter is in use",
544 st.tag()
545 );
546 }
547}