Compare commits

...

11 commits

Author SHA1 Message Date
Nikolay Kim
01d3a2440b
Prepare net release (#550) 2025-03-28 21:26:07 +01:00
Nikolay Kim
f5ee55d598
Handle socket close for poll driver (#549) 2025-03-28 21:06:11 +01:00
Nikolay Kim
e4f24ee41f Handle flaky tests 2025-03-28 11:39:24 +01:00
Nikolay Kim
f6fe9c3e10
Improve tests (#548) 2025-03-28 10:07:10 +01:00
Nikolay Kim
30928d019c
Improve tests (#547) 2025-03-28 09:11:59 +01:00
Nikolay Kim
e9a1284151
Better worker availability handling (#546) 2025-03-28 08:51:44 +01:00
Nikolay Kim
8f2d5056c9
Return PayloadError::Incomplete on server disconnect (#545) 2025-03-28 02:10:25 +01:00
Nikolay Kim
f647ad2eac
Update tests (#544) 2025-03-27 22:16:51 +01:00
Ruangyot Nanchiang
728ab919a3
Expose WebStack for external wrapper support in downstream crates (#542)
* add public ServiceConfig::register constructor to support external configuration (#250)

* fix: doctest ServiceConfig::register() error (#250)

* add unit testing for ServiceConfig::register()

* replace pub(crate) to pub in ServiceConfig::new() (#250)

* replace pub to pub(crate) for ServiceConfig::new() and add pub for mod ntex::web::stack instead

* remove unsed DefaultError import in config.rs tests

---------

Co-authored-by: RuangyotN <ruangyotn@skyller.co>
2025-03-27 22:12:34 +01:00
Nikolay Kim
b2915f4868
Improve tests (#543) 2025-03-27 20:45:43 +01:00
Nikolay Kim
eb4ec4b3e1
Add Arbiter::get_value() helper method (#541) 2025-03-26 14:40:05 +01:00
26 changed files with 360 additions and 217 deletions

View file

@ -46,7 +46,10 @@ ntex-compio = { path = "ntex-compio" }
ntex-tokio = { path = "ntex-tokio" } ntex-tokio = { path = "ntex-tokio" }
[workspace.dependencies] [workspace.dependencies]
async-channel = "2"
async-task = "4.5.0" async-task = "4.5.0"
atomic-waker = "1.1"
core_affinity = "0.8"
bitflags = "2" bitflags = "2"
cfg_aliases = "0.2.1" cfg_aliases = "0.2.1"
cfg-if = "1.0.0" cfg-if = "1.0.0"
@ -57,7 +60,8 @@ fxhash = "0.2"
libc = "0.2.164" libc = "0.2.164"
log = "0.4" log = "0.4"
io-uring = "0.7.4" io-uring = "0.7.4"
polling = "3.3.0" oneshot = "0.1"
polling = "3.7.4"
nohash-hasher = "0.2.0" nohash-hasher = "0.2.0"
scoped-tls = "1.0.1" scoped-tls = "1.0.1"
slab = "0.4.9" slab = "0.4.9"

View file

@ -28,4 +28,3 @@ pin-project-lite = "0.2"
[dev-dependencies] [dev-dependencies]
ntex = "2" ntex = "2"
rand = "0.8" rand = "0.8"
env_logger = "0.11"

View file

@ -537,7 +537,9 @@ impl IoContext {
self.0.tag(), self.0.tag(),
nbytes nbytes
); );
inner.dispatch_task.wake(); if !inner.dispatch_task.wake_checked() {
log::error!("Dispatcher waker is not registered");
}
} else { } else {
if nbytes >= hw { if nbytes >= hw {
// read task is paused because of read back-pressure // read task is paused because of read back-pressure
@ -735,22 +737,6 @@ impl IoContext {
false false
} }
pub fn is_write_ready(&self) -> bool {
if let Some(waker) = self.0 .0.write_task.take() {
let ready = self
.0
.filter()
.poll_write_ready(&mut Context::from_waker(&waker));
if !matches!(
ready,
Poll::Ready(WriteStatus::Ready | WriteStatus::Shutdown)
) {
return true;
}
}
false
}
pub fn with_read_buf<F>(&self, f: F) -> Poll<()> pub fn with_read_buf<F>(&self, f: F) -> Poll<()>
where where
F: FnOnce(&mut BytesVec) -> Poll<io::Result<usize>>, F: FnOnce(&mut BytesVec) -> Poll<io::Result<usize>>,
@ -803,7 +789,9 @@ impl IoContext {
self.0.tag(), self.0.tag(),
nbytes nbytes
); );
inner.dispatch_task.wake(); if !inner.dispatch_task.wake_checked() {
log::error!("Dispatcher waker is not registered");
}
} else { } else {
if nbytes >= hw { if nbytes >= hw {
// read task is paused because of read back-pressure // read task is paused because of read back-pressure

View file

@ -18,4 +18,3 @@ proc-macro2 = "^1"
[dev-dependencies] [dev-dependencies]
ntex = "2" ntex = "2"
futures = "0.3" futures = "0.3"
env_logger = "0.11"

View file

@ -1,5 +1,13 @@
# Changes # Changes
## [2.5.10] - 2025-03-28
* Better closed sockets handling
## [2.5.9] - 2025-03-27
* Handle closed sockets
## [2.5.8] - 2025-03-25 ## [2.5.8] - 2025-03-25
* Update neon runtime * Update neon runtime

View file

@ -1,6 +1,6 @@
[package] [package]
name = "ntex-net" name = "ntex-net"
version = "2.5.8" version = "2.5.10"
authors = ["ntex contributors <team@ntex.rs>"] authors = ["ntex contributors <team@ntex.rs>"]
description = "ntexwork utils for ntex framework" description = "ntexwork utils for ntex framework"
keywords = ["network", "framework", "async", "futures"] keywords = ["network", "framework", "async", "futures"]
@ -40,7 +40,7 @@ ntex-util = "2.5"
ntex-tokio = { version = "0.5.3", optional = true } ntex-tokio = { version = "0.5.3", optional = true }
ntex-compio = { version = "0.2.4", optional = true } ntex-compio = { version = "0.2.4", optional = true }
ntex-neon = { version = "0.1.10", optional = true } ntex-neon = { version = "0.1.15", optional = true }
bitflags = { workspace = true } bitflags = { workspace = true }
cfg-if = { workspace = true } cfg-if = { workspace = true }
@ -57,4 +57,3 @@ polling = { workspace = true, optional = true }
[dev-dependencies] [dev-dependencies]
ntex = "2" ntex = "2"
env_logger = "0.11"

View file

@ -1,5 +1,5 @@
use std::os::fd::{AsRawFd, RawFd}; use std::os::fd::{AsRawFd, RawFd};
use std::{cell::Cell, cell::RefCell, future::Future, io, rc::Rc, task, task::Poll}; use std::{cell::Cell, cell::RefCell, future::Future, io, mem, rc::Rc, task, task::Poll};
use ntex_neon::driver::{DriverApi, Event, Handler}; use ntex_neon::driver::{DriverApi, Event, Handler};
use ntex_neon::{syscall, Runtime}; use ntex_neon::{syscall, Runtime};
@ -16,8 +16,8 @@ pub(crate) struct StreamCtl<T> {
bitflags::bitflags! { bitflags::bitflags! {
#[derive(Copy, Clone, Debug)] #[derive(Copy, Clone, Debug)]
struct Flags: u8 { struct Flags: u8 {
const RD = 0b0000_0001; const RD = 0b0000_0001;
const WR = 0b0000_0010; const WR = 0b0000_0010;
} }
} }
@ -100,20 +100,20 @@ impl<T> Clone for StreamOps<T> {
impl<T> Handler for StreamOpsHandler<T> { impl<T> Handler for StreamOpsHandler<T> {
fn event(&mut self, id: usize, ev: Event) { fn event(&mut self, id: usize, ev: Event) {
log::debug!("FD event {:?} event: {:?}", id, ev);
self.inner.with(|streams| { self.inner.with(|streams| {
if !streams.contains(id) { if !streams.contains(id) {
return; return;
} }
let item = &mut streams[id]; let item = &mut streams[id];
if item.io.is_none() {
return;
}
log::debug!("{}: FD event {:?} event: {:?}", item.tag(), id, ev);
// handle HUP // handle HUP
if ev.is_interrupt() { if ev.is_interrupt() {
item.context.stopped(None); item.context.stopped(None);
if item.io.take().is_some() { close(id as u32, item, &self.inner.api, None, true);
close(id as u32, item.fd, &self.inner.api);
}
return; return;
} }
@ -165,7 +165,7 @@ impl<T> Handler for StreamOpsHandler<T> {
let item = &mut streams[id as usize]; let item = &mut streams[id as usize];
item.ref_count -= 1; item.ref_count -= 1;
if item.ref_count == 0 { if item.ref_count == 0 {
let item = streams.remove(id as usize); let mut item = streams.remove(id as usize);
log::debug!( log::debug!(
"{}: Drop ({}), {:?}, has-io: {}", "{}: Drop ({}), {:?}, has-io: {}",
item.tag(), item.tag(),
@ -173,9 +173,7 @@ impl<T> Handler for StreamOpsHandler<T> {
item.fd, item.fd,
item.io.is_some() item.io.is_some()
); );
if item.io.is_some() { close(id, &mut item, &self.inner.api, None, true);
close(id, item.fd, &self.inner.api);
}
} }
} }
self.inner.delayd_drop.set(false); self.inner.delayd_drop.set(false);
@ -186,11 +184,14 @@ impl<T> Handler for StreamOpsHandler<T> {
fn error(&mut self, id: usize, err: io::Error) { fn error(&mut self, id: usize, err: io::Error) {
self.inner.with(|streams| { self.inner.with(|streams| {
if let Some(item) = streams.get_mut(id) { if let Some(item) = streams.get_mut(id) {
log::debug!("FD is failed ({}) {:?}, err: {:?}", id, item.fd, err); log::debug!(
item.context.stopped(Some(err)); "{}: FD is failed ({}) {:?}, err: {:?}",
if item.io.take().is_some() { item.tag(),
close(id as u32, item.fd, &self.inner.api); id,
} item.fd,
err
);
close(id as u32, item, &self.inner.api, Some(err), false);
} }
}) })
} }
@ -208,27 +209,39 @@ impl<T> StreamOpsInner<T> {
} }
} }
fn close(id: u32, fd: RawFd, api: &DriverApi) -> ntex_rt::JoinHandle<io::Result<i32>> { fn close<T>(
api.detach(fd, id); id: u32,
ntex_rt::spawn_blocking(move || { item: &mut StreamItem<T>,
syscall!(libc::shutdown(fd, libc::SHUT_RDWR))?; api: &DriverApi,
syscall!(libc::close(fd)) error: Option<io::Error>,
}) shutdown: bool,
) -> Option<ntex_rt::JoinHandle<io::Result<i32>>> {
if let Some(io) = item.io.take() {
log::debug!("{}: Closing ({}), {:?}", item.tag(), id, item.fd);
mem::forget(io);
if let Some(err) = error {
item.context.stopped(Some(err));
}
let fd = item.fd;
api.detach(fd, id);
Some(ntex_rt::spawn_blocking(move || {
if shutdown {
let _ = syscall!(libc::shutdown(fd, libc::SHUT_RDWR));
}
syscall!(libc::close(fd))
}))
} else {
None
}
} }
impl<T> StreamCtl<T> { impl<T> StreamCtl<T> {
pub(crate) fn close(self) -> impl Future<Output = io::Result<()>> { pub(crate) fn close(self) -> impl Future<Output = io::Result<()>> {
let id = self.id as usize; let id = self.id as usize;
let (io, fd) = self let fut = self.inner.with(|streams| {
.inner let item = &mut streams[id];
.with(|streams| (streams[id].io.take(), streams[id].fd)); close(self.id, item, &self.inner.api, None, false)
let fut = if let Some(io) = io { });
log::debug!("Closing ({}), {:?}", id, fd);
std::mem::forget(io);
Some(close(self.id, fd, &self.inner.api))
} else {
None
};
async move { async move {
if let Some(fut) = fut { if let Some(fut) = fut {
fut.await fut.await
@ -336,7 +349,7 @@ impl<T> Drop for StreamCtl<T> {
let id = self.id as usize; let id = self.id as usize;
streams[id].ref_count -= 1; streams[id].ref_count -= 1;
if streams[id].ref_count == 0 { if streams[id].ref_count == 0 {
let item = streams.remove(id); let mut item = streams.remove(id);
log::debug!( log::debug!(
"{}: Drop io ({}), {:?}, has-io: {}", "{}: Drop io ({}), {:?}, has-io: {}",
item.tag(), item.tag(),
@ -344,9 +357,7 @@ impl<T> Drop for StreamCtl<T> {
item.fd, item.fd,
item.io.is_some() item.io.is_some()
); );
if item.io.is_some() { close(self.id, &mut item, &self.inner.api, None, true);
close(self.id, item.fd, &self.inner.api);
}
} }
self.inner.streams.set(Some(streams)); self.inner.streams.set(Some(streams));
} else { } else {

View file

@ -33,6 +33,12 @@ struct StreamItem<T> {
wr_op: Option<NonZeroU32>, wr_op: Option<NonZeroU32>,
} }
impl<T> StreamItem<T> {
fn tag(&self) -> &'static str {
self.context.tag()
}
}
enum Operation { enum Operation {
Recv { Recv {
id: usize, id: usize,
@ -249,7 +255,7 @@ impl<T> Handler for StreamOpsHandler<T> {
if storage.streams[id].ref_count == 0 { if storage.streams[id].ref_count == 0 {
let mut item = storage.streams.remove(id); let mut item = storage.streams.remove(id);
log::debug!("{}: Drop io ({}), {:?}", item.context.tag(), id, item.fd); log::debug!("{}: Drop io ({}), {:?}", item.tag(), id, item.fd);
if let Some(io) = item.io.take() { if let Some(io) = item.io.take() {
mem::forget(io); mem::forget(io);
@ -273,7 +279,7 @@ impl<T> StreamOpsStorage<T> {
if let Poll::Ready(mut buf) = item.context.get_read_buf() { if let Poll::Ready(mut buf) = item.context.get_read_buf() {
log::debug!( log::debug!(
"{}: Recv resume ({}), {:?} rem: {:?}", "{}: Recv resume ({}), {:?} rem: {:?}",
item.context.tag(), item.tag(),
id, id,
item.fd, item.fd,
buf.remaining_mut() buf.remaining_mut()
@ -306,7 +312,7 @@ impl<T> StreamOpsStorage<T> {
if let Poll::Ready(buf) = item.context.get_write_buf() { if let Poll::Ready(buf) = item.context.get_write_buf() {
log::debug!( log::debug!(
"{}: Send resume ({}), {:?} len: {:?}", "{}: Send resume ({}), {:?} len: {:?}",
item.context.tag(), item.tag(),
id, id,
item.fd, item.fd,
buf.len() buf.len()
@ -396,12 +402,7 @@ impl<T> StreamCtl<T> {
if let Some(rd_op) = item.rd_op { if let Some(rd_op) = item.rd_op {
if !item.flags.contains(Flags::RD_CANCELING) { if !item.flags.contains(Flags::RD_CANCELING) {
log::debug!( log::debug!("{}: Recv to pause ({}), {:?}", item.tag(), self.id, item.fd);
"{}: Recv to pause ({}), {:?}",
item.context.tag(),
self.id,
item.fd
);
item.flags.insert(Flags::RD_CANCELING); item.flags.insert(Flags::RD_CANCELING);
self.inner.api.cancel(rd_op.get()); self.inner.api.cancel(rd_op.get());
} }
@ -426,12 +427,7 @@ impl<T> Drop for StreamCtl<T> {
if storage.streams[self.id].ref_count == 0 { if storage.streams[self.id].ref_count == 0 {
let mut item = storage.streams.remove(self.id); let mut item = storage.streams.remove(self.id);
if let Some(io) = item.io.take() { if let Some(io) = item.io.take() {
log::debug!( log::debug!("{}: Close io ({}), {:?}", item.tag(), self.id, item.fd);
"{}: Close io ({}), {:?}",
item.context.tag(),
self.id,
item.fd
);
mem::forget(io); mem::forget(io);
let id = storage.ops.insert(Operation::Close { tx: None }); let id = storage.ops.insert(Operation::Close { tx: None });

View file

@ -1,5 +1,9 @@
# Changes # Changes
## [0.4.29] - 2025-03-26
* Add Arbiter::get_value() helper method
## [0.4.27] - 2025-03-14 ## [0.4.27] - 2025-03-14
* Add srbiters pings ttl * Add srbiters pings ttl

View file

@ -1,6 +1,6 @@
[package] [package]
name = "ntex-rt" name = "ntex-rt"
version = "0.4.28" version = "0.4.29"
authors = ["ntex contributors <team@ntex.rs>"] authors = ["ntex contributors <team@ntex.rs>"]
description = "ntex runtime" description = "ntex runtime"
keywords = ["network", "framework", "async", "futures"] keywords = ["network", "framework", "async", "futures"]
@ -32,8 +32,8 @@ neon = ["ntex-neon"]
[dependencies] [dependencies]
async-channel = "2" async-channel = "2"
futures-timer = "3.0" futures-timer = "3.0"
log = "0.4"
oneshot = "0.1" oneshot = "0.1"
log = "0.4"
compio-driver = { version = "0.6", optional = true } compio-driver = { version = "0.6", optional = true }
compio-runtime = { version = "0.6", optional = true } compio-runtime = { version = "0.6", optional = true }
@ -42,7 +42,4 @@ tok-io = { version = "1", package = "tokio", default-features = false, features
"net", "net",
], optional = true } ], optional = true }
ntex-neon = { version = "0.1.1", optional = true } ntex-neon = { version = "0.1.14", optional = true }
[dev-dependencies]
env_logger = "0.11"

View file

@ -286,6 +286,25 @@ impl Arbiter {
}) })
} }
/// Get a type previously inserted to this runtime or create new one.
pub fn get_value<T, F>(f: F) -> T
where
T: Clone + 'static,
F: FnOnce() -> T,
{
STORAGE.with(move |cell| {
let mut st = cell.borrow_mut();
if let Some(boxed) = st.get(&TypeId::of::<T>()) {
if let Some(val) = (&**boxed as &(dyn Any + 'static)).downcast_ref::<T>() {
return val.clone();
}
}
let val = f();
st.insert(TypeId::of::<T>(), Box::new(val.clone()));
val
})
}
/// Wait for the event loop to stop by joining the underlying thread (if have Some). /// Wait for the event loop to stop by joining the underlying thread (if have Some).
pub fn join(&mut self) -> thread::Result<()> { pub fn join(&mut self) -> thread::Result<()> {
if let Some(thread_handle) = self.thread_handle.take() { if let Some(thread_handle) = self.thread_handle.take() {
@ -355,6 +374,7 @@ mod tests {
assert!(Arbiter::get_item::<&'static str, _, _>(|s| *s == "test")); assert!(Arbiter::get_item::<&'static str, _, _>(|s| *s == "test"));
assert!(Arbiter::get_mut_item::<&'static str, _, _>(|s| *s == "test")); assert!(Arbiter::get_mut_item::<&'static str, _, _>(|s| *s == "test"));
assert!(Arbiter::contains_item::<&'static str>()); assert!(Arbiter::contains_item::<&'static str>());
assert!(Arbiter::get_value(|| 64u64) == 64);
assert!(format!("{:?}", Arbiter::current()).contains("Arbiter")); assert!(format!("{:?}", Arbiter::current()).contains("Arbiter"));
} }
} }

View file

@ -112,6 +112,8 @@ mod tokio {
/// ///
/// This function panics if ntex system is not running. /// This function panics if ntex system is not running.
#[inline] #[inline]
#[doc(hidden)]
#[deprecated]
pub fn spawn_fn<F, R>(f: F) -> tok_io::task::JoinHandle<R::Output> pub fn spawn_fn<F, R>(f: F) -> tok_io::task::JoinHandle<R::Output>
where where
F: FnOnce() -> R + 'static, F: FnOnce() -> R + 'static,
@ -196,6 +198,8 @@ mod compio {
/// ///
/// This function panics if ntex system is not running. /// This function panics if ntex system is not running.
#[inline] #[inline]
#[doc(hidden)]
#[deprecated]
pub fn spawn_fn<F, R>(f: F) -> JoinHandle<R::Output> pub fn spawn_fn<F, R>(f: F) -> JoinHandle<R::Output>
where where
F: FnOnce() -> R + 'static, F: FnOnce() -> R + 'static,
@ -323,6 +327,8 @@ mod neon {
/// ///
/// This function panics if ntex system is not running. /// This function panics if ntex system is not running.
#[inline] #[inline]
#[doc(hidden)]
#[deprecated]
pub fn spawn_fn<F, R>(f: F) -> Task<R::Output> pub fn spawn_fn<F, R>(f: F) -> Task<R::Output>
where where
F: FnOnce() -> R + 'static, F: FnOnce() -> R + 'static,
@ -377,7 +383,7 @@ mod neon {
impl<T> JoinHandle<T> { impl<T> JoinHandle<T> {
pub fn is_finished(&self) -> bool { pub fn is_finished(&self) -> bool {
false self.fut.is_none()
} }
} }

View file

@ -1,5 +1,13 @@
# Changes # Changes
## [2.7.3] - 2025-03-28
* Better worker availability handling
## [2.7.2] - 2025-03-27
* Handle paused state
## [2.7.1] - 2025-02-28 ## [2.7.1] - 2025-02-28
* Fix set core affinity out of worker start #508 * Fix set core affinity out of worker start #508

View file

@ -1,6 +1,6 @@
[package] [package]
name = "ntex-server" name = "ntex-server"
version = "2.7.1" version = "2.7.4"
authors = ["ntex contributors <team@ntex.rs>"] authors = ["ntex contributors <team@ntex.rs>"]
description = "Server for ntex framework" description = "Server for ntex framework"
keywords = ["network", "framework", "async", "futures"] keywords = ["network", "framework", "async", "futures"]
@ -22,13 +22,13 @@ ntex-service = "3.4"
ntex-rt = "0.4" ntex-rt = "0.4"
ntex-util = "2.8" ntex-util = "2.8"
async-channel = "2" async-channel = { workspace = true }
async-broadcast = "0.7" atomic-waker = { workspace = true }
core_affinity = "0.8" core_affinity = { workspace = true }
polling = "3.3" oneshot = { workspace = true }
log = "0.4" polling = { workspace = true }
socket2 = "0.5" log = { workspace = true }
oneshot = { version = "0.1", default-features = false, features = ["async"] } socket2 = { workspace = true }
[dev-dependencies] [dev-dependencies]
ntex = "2" ntex = "2"

View file

@ -139,7 +139,6 @@ impl<F: ServerConfiguration> ServerManager<F> {
fn start_worker<F: ServerConfiguration>(mgr: ServerManager<F>, cid: Option<CoreId>) { fn start_worker<F: ServerConfiguration>(mgr: ServerManager<F>, cid: Option<CoreId>) {
let _ = ntex_rt::spawn(async move { let _ = ntex_rt::spawn(async move {
let id = mgr.next_id(); let id = mgr.next_id();
let mut wrk = Worker::start(id, mgr.factory(), cid); let mut wrk = Worker::start(id, mgr.factory(), cid);
loop { loop {
@ -181,7 +180,7 @@ impl<F: ServerConfiguration> HandleCmdState<F> {
fn process(&mut self, mut item: F::Item) { fn process(&mut self, mut item: F::Item) {
loop { loop {
if !self.workers.is_empty() { if !self.workers.is_empty() {
if self.next > self.workers.len() { if self.next >= self.workers.len() {
self.next = self.workers.len() - 1; self.next = self.workers.len() - 1;
} }
match self.workers[self.next].send(item) { match self.workers[self.next].send(item) {
@ -212,10 +211,9 @@ impl<F: ServerConfiguration> HandleCmdState<F> {
match upd { match upd {
Update::Available(worker) => { Update::Available(worker) => {
self.workers.push(worker); self.workers.push(worker);
self.workers.sort();
if self.workers.len() == 1 { if self.workers.len() == 1 {
self.mgr.resume(); self.mgr.resume();
} else {
self.workers.sort();
} }
} }
Update::Unavailable(worker) => { Update::Unavailable(worker) => {
@ -234,6 +232,9 @@ impl<F: ServerConfiguration> HandleCmdState<F> {
if let Err(item) = self.workers[0].send(item) { if let Err(item) = self.workers[0].send(item) {
self.backlog.push_back(item); self.backlog.push_back(item);
self.workers.remove(0); self.workers.remove(0);
if self.workers.is_empty() {
self.mgr.pause();
}
break; break;
} }
} }

View file

@ -92,12 +92,14 @@ impl AcceptLoop {
/// Start accept loop /// Start accept loop
pub fn start(mut self, socks: Vec<(Token, Listener)>, srv: Server) { pub fn start(mut self, socks: Vec<(Token, Listener)>, srv: Server) {
let (tx, rx_start) = oneshot::channel();
let (rx, poll) = self let (rx, poll) = self
.inner .inner
.take() .take()
.expect("AcceptLoop cannot be used multiple times"); .expect("AcceptLoop cannot be used multiple times");
Accept::start( Accept::start(
tx,
rx, rx,
poll, poll,
socks, socks,
@ -105,6 +107,8 @@ impl AcceptLoop {
self.notify.clone(), self.notify.clone(),
self.status_handler.take(), self.status_handler.take(),
); );
let _ = rx_start.recv();
} }
} }
@ -121,6 +125,7 @@ impl fmt::Debug for AcceptLoop {
struct Accept { struct Accept {
poller: Arc<Poller>, poller: Arc<Poller>,
rx: mpsc::Receiver<AcceptorCommand>, rx: mpsc::Receiver<AcceptorCommand>,
tx: Option<oneshot::Sender<()>>,
sockets: Vec<ServerSocketInfo>, sockets: Vec<ServerSocketInfo>,
srv: Server, srv: Server,
notify: AcceptNotify, notify: AcceptNotify,
@ -131,6 +136,7 @@ struct Accept {
impl Accept { impl Accept {
fn start( fn start(
tx: oneshot::Sender<()>,
rx: mpsc::Receiver<AcceptorCommand>, rx: mpsc::Receiver<AcceptorCommand>,
poller: Arc<Poller>, poller: Arc<Poller>,
socks: Vec<(Token, Listener)>, socks: Vec<(Token, Listener)>,
@ -145,11 +151,12 @@ impl Accept {
.name("ntex-server accept loop".to_owned()) .name("ntex-server accept loop".to_owned())
.spawn(move || { .spawn(move || {
System::set_current(sys); System::set_current(sys);
Accept::new(rx, poller, socks, srv, notify, status_handler).poll() Accept::new(tx, rx, poller, socks, srv, notify, status_handler).poll()
}); });
} }
fn new( fn new(
tx: oneshot::Sender<()>,
rx: mpsc::Receiver<AcceptorCommand>, rx: mpsc::Receiver<AcceptorCommand>,
poller: Arc<Poller>, poller: Arc<Poller>,
socks: Vec<(Token, Listener)>, socks: Vec<(Token, Listener)>,
@ -175,6 +182,7 @@ impl Accept {
notify, notify,
srv, srv,
status_handler, status_handler,
tx: Some(tx),
backpressure: true, backpressure: true,
backlog: VecDeque::new(), backlog: VecDeque::new(),
} }
@ -192,19 +200,23 @@ impl Accept {
// Create storage for events // Create storage for events
let mut events = Events::with_capacity(NonZeroUsize::new(512).unwrap()); let mut events = Events::with_capacity(NonZeroUsize::new(512).unwrap());
let mut timeout = Some(Duration::ZERO);
loop { loop {
if let Err(e) = self.poller.wait(&mut events, None) { if let Err(e) = self.poller.wait(&mut events, timeout) {
if e.kind() == io::ErrorKind::Interrupted { if e.kind() != io::ErrorKind::Interrupted {
continue;
} else {
panic!("Cannot wait for events in poller: {}", e) panic!("Cannot wait for events in poller: {}", e)
} }
} else if timeout.is_some() {
timeout = None;
let _ = self.tx.take().unwrap().send(());
} }
for event in events.iter() { for idx in 0..self.sockets.len() {
let readd = self.accept(event.key); if self.sockets[idx].registered.get() {
if readd { let readd = self.accept(idx);
self.add_source(event.key); if readd {
self.add_source(idx);
}
} }
} }

View file

@ -2,8 +2,8 @@ use std::sync::atomic::{AtomicBool, Ordering};
use std::task::{ready, Context, Poll}; use std::task::{ready, Context, Poll};
use std::{cmp, future::poll_fn, future::Future, hash, pin::Pin, sync::Arc}; use std::{cmp, future::poll_fn, future::Future, hash, pin::Pin, sync::Arc};
use async_broadcast::{self as bus, broadcast};
use async_channel::{unbounded, Receiver, Sender}; use async_channel::{unbounded, Receiver, Sender};
use atomic_waker::AtomicWaker;
use core_affinity::CoreId; use core_affinity::CoreId;
use ntex_rt::{spawn, Arbiter}; use ntex_rt::{spawn, Arbiter};
@ -99,10 +99,10 @@ impl<T> Worker<T> {
log::debug!("Creating server instance in {:?}", id); log::debug!("Creating server instance in {:?}", id);
let factory = cfg.create().await; let factory = cfg.create().await;
log::debug!("Server instance has been created in {:?}", id);
match create(id, rx1, rx2, factory, avail_tx).await { match create(id, rx1, rx2, factory, avail_tx).await {
Ok((svc, wrk)) => { Ok((svc, wrk)) => {
log::debug!("Server instance has been created in {:?}", id);
run_worker(svc, wrk).await; run_worker(svc, wrk).await;
} }
Err(e) => { Err(e) => {
@ -151,10 +151,8 @@ impl<T> Worker<T> {
if self.failed.load(Ordering::Acquire) { if self.failed.load(Ordering::Acquire) {
WorkerStatus::Failed WorkerStatus::Failed
} else { } else {
// cleanup updates self.avail.wait_for_update().await;
while self.avail.notify.try_recv().is_ok() {} if self.avail.failed() {
if self.avail.notify.recv_direct().await.is_err() {
self.failed.store(true, Ordering::Release); self.failed.store(true, Ordering::Release);
} }
self.status() self.status()
@ -196,52 +194,85 @@ impl Future for WorkerStop {
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
struct WorkerAvailability { struct WorkerAvailability {
notify: bus::Receiver<()>, inner: Arc<Inner>,
available: Arc<AtomicBool>,
} }
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
struct WorkerAvailabilityTx { struct WorkerAvailabilityTx {
notify: bus::Sender<()>, inner: Arc<Inner>,
available: Arc<AtomicBool>, }
#[derive(Debug)]
struct Inner {
waker: AtomicWaker,
updated: AtomicBool,
available: AtomicBool,
failed: AtomicBool,
} }
impl WorkerAvailability { impl WorkerAvailability {
fn create() -> (Self, WorkerAvailabilityTx) { fn create() -> (Self, WorkerAvailabilityTx) {
let (mut tx, rx) = broadcast(16); let inner = Arc::new(Inner {
tx.set_overflow(true); waker: AtomicWaker::new(),
updated: AtomicBool::new(false),
available: AtomicBool::new(false),
failed: AtomicBool::new(false),
});
let avail = WorkerAvailability { let avail = WorkerAvailability {
notify: rx, inner: inner.clone(),
available: Arc::new(AtomicBool::new(false)),
};
let avail_tx = WorkerAvailabilityTx {
notify: tx,
available: avail.available.clone(),
}; };
let avail_tx = WorkerAvailabilityTx { inner };
(avail, avail_tx) (avail, avail_tx)
} }
fn failed(&self) -> bool {
self.inner.failed.load(Ordering::Acquire)
}
fn available(&self) -> bool { fn available(&self) -> bool {
self.available.load(Ordering::Acquire) self.inner.available.load(Ordering::Acquire)
}
async fn wait_for_update(&self) {
poll_fn(|cx| {
if self.inner.updated.load(Ordering::Acquire) {
self.inner.updated.store(false, Ordering::Release);
Poll::Ready(())
} else {
self.inner.waker.register(cx.waker());
Poll::Pending
}
})
.await;
} }
} }
impl WorkerAvailabilityTx { impl WorkerAvailabilityTx {
fn set(&self, val: bool) { fn set(&self, val: bool) {
let old = self.available.swap(val, Ordering::Release); let old = self.inner.available.swap(val, Ordering::Release);
if !old && val { if old != val {
let _ = self.notify.try_broadcast(()); self.inner.updated.store(true, Ordering::Release);
self.inner.waker.wake();
} }
} }
} }
impl Drop for WorkerAvailabilityTx {
fn drop(&mut self) {
self.inner.failed.store(true, Ordering::Release);
self.inner.updated.store(true, Ordering::Release);
self.inner.available.store(false, Ordering::Release);
self.inner.waker.wake();
}
}
/// Service worker /// Service worker
/// ///
/// Worker accepts message via unbounded channel and starts processing. /// Worker accepts message via unbounded channel and starts processing.
struct WorkerSt<T, F: ServiceFactory<T>> { struct WorkerSt<T, F: ServiceFactory<T>> {
id: WorkerId, id: WorkerId,
rx: Pin<Box<dyn Stream<Item = T>>>, rx: Receiver<T>,
stop: Pin<Box<dyn Stream<Item = Shutdown>>>, stop: Pin<Box<dyn Stream<Item = Shutdown>>>,
factory: F, factory: F,
availability: WorkerAvailabilityTx, availability: WorkerAvailabilityTx,
@ -253,25 +284,43 @@ where
F: ServiceFactory<T> + 'static, F: ServiceFactory<T> + 'static,
{ {
loop { loop {
let mut recv = std::pin::pin!(wrk.rx.recv());
let fut = poll_fn(|cx| { let fut = poll_fn(|cx| {
ready!(svc.poll_ready(cx)?); match svc.poll_ready(cx) {
Poll::Ready(Ok(())) => {
if let Some(item) = ready!(Pin::new(&mut wrk.rx).poll_next(cx)) { wrk.availability.set(true);
let fut = svc.call(item); }
let _ = spawn(async move { Poll::Ready(Err(err)) => {
let _ = fut.await; wrk.availability.set(false);
}); return Poll::Ready(Err(err));
}
Poll::Pending => {
wrk.availability.set(false);
return Poll::Pending;
}
}
match ready!(recv.as_mut().poll(cx)) {
Ok(item) => {
let fut = svc.call(item);
let _ = spawn(async move {
let _ = fut.await;
});
Poll::Ready(Ok::<_, F::Error>(true))
}
Err(_) => {
log::error!("Server is gone");
Poll::Ready(Ok(false))
}
} }
Poll::Ready(Ok::<(), F::Error>(()))
}); });
match select(fut, stream_recv(&mut wrk.stop)).await { match select(fut, stream_recv(&mut wrk.stop)).await {
Either::Left(Ok(())) => continue, Either::Left(Ok(true)) => continue,
Either::Left(Err(_)) => { Either::Left(Err(_)) => {
let _ = ntex_rt::spawn(async move { let _ = ntex_rt::spawn(async move {
svc.shutdown().await; svc.shutdown().await;
}); });
wrk.availability.set(false);
} }
Either::Right(Some(Shutdown { timeout, result })) => { Either::Right(Some(Shutdown { timeout, result })) => {
wrk.availability.set(false); wrk.availability.set(false);
@ -285,7 +334,8 @@ where
stop_svc(wrk.id, svc, timeout, Some(result)).await; stop_svc(wrk.id, svc, timeout, Some(result)).await;
return; return;
} }
Either::Right(None) => { Either::Left(Ok(false)) | Either::Right(None) => {
wrk.availability.set(false);
stop_svc(wrk.id, svc, STOP_TIMEOUT, None).await; stop_svc(wrk.id, svc, STOP_TIMEOUT, None).await;
return; return;
} }
@ -295,7 +345,6 @@ where
loop { loop {
match select(wrk.factory.create(()), stream_recv(&mut wrk.stop)).await { match select(wrk.factory.create(()), stream_recv(&mut wrk.stop)).await {
Either::Left(Ok(service)) => { Either::Left(Ok(service)) => {
wrk.availability.set(true);
svc = Pipeline::new(service).bind(); svc = Pipeline::new(service).bind();
break; break;
} }
@ -336,8 +385,6 @@ where
{ {
availability.set(false); availability.set(false);
let factory = factory?; let factory = factory?;
let rx = Box::pin(rx);
let mut stop = Box::pin(stop); let mut stop = Box::pin(stop);
let svc = match select(factory.create(()), stream_recv(&mut stop)).await { let svc = match select(factory.create(()), stream_recv(&mut stop)).await {
@ -356,9 +403,9 @@ where
svc, svc,
WorkerSt { WorkerSt {
id, id,
rx,
factory, factory,
availability, availability,
rx: Box::pin(rx),
stop: Box::pin(stop), stop: Box::pin(stop),
}, },
)) ))

View file

@ -1,5 +1,11 @@
# Changes # Changes
## [2.12.4] - 2025-03-28
* http: Return PayloadError::Incomplete on server disconnect
* web: Expose WebStack for external wrapper support in downstream crates #542
## [2.12.3] - 2025-03-22 ## [2.12.3] - 2025-03-22
* web: Export web::app_service::AppService #534 * web: Export web::app_service::AppService #534

View file

@ -1,6 +1,6 @@
[package] [package]
name = "ntex" name = "ntex"
version = "2.12.3" version = "2.12.4"
authors = ["ntex contributors <team@ntex.rs>"] authors = ["ntex contributors <team@ntex.rs>"]
description = "Framework for composable network services" description = "Framework for composable network services"
readme = "README.md" readme = "README.md"
@ -68,11 +68,11 @@ ntex-service = "3.4"
ntex-macros = "0.1" ntex-macros = "0.1"
ntex-util = "2.8" ntex-util = "2.8"
ntex-bytes = "0.1.27" ntex-bytes = "0.1.27"
ntex-server = "2.7" ntex-server = "2.7.4"
ntex-h2 = "1.8.6" ntex-h2 = "1.8.6"
ntex-rt = "0.4.27" ntex-rt = "0.4.27"
ntex-io = "2.11" ntex-io = "2.11"
ntex-net = "2.5.8" ntex-net = "2.5.10"
ntex-tls = "2.3" ntex-tls = "2.3"
base64 = "0.22" base64 = "0.22"
@ -114,6 +114,7 @@ flate2 = { version = "1.0", optional = true }
[dev-dependencies] [dev-dependencies]
rand = "0.8" rand = "0.8"
time = "0.3" time = "0.3"
oneshot = "0.1"
futures-util = "0.3" futures-util = "0.3"
tls-openssl = { version = "0.10", package = "openssl" } tls-openssl = { version = "0.10", package = "openssl" }
tls-rustls = { version = "0.23", package = "rustls", features = ["ring", "std"], default-features = false } tls-rustls = { version = "0.23", package = "rustls", features = ["ring", "std"], default-features = false }

View file

@ -1,13 +1,11 @@
use std::{ use std::{future::poll_fn, io, io::Write, pin::Pin, task, task::Poll, time::Instant};
future::poll_fn, io, io::Write, pin::Pin, task::Context, task::Poll, time::Instant,
};
use crate::http::body::{BodySize, MessageBody}; use crate::http::body::{BodySize, MessageBody};
use crate::http::error::PayloadError; use crate::http::error::PayloadError;
use crate::http::h1;
use crate::http::header::{HeaderMap, HeaderValue, HOST}; use crate::http::header::{HeaderMap, HeaderValue, HOST};
use crate::http::message::{RequestHeadType, ResponseHead}; use crate::http::message::{RequestHeadType, ResponseHead};
use crate::http::payload::{Payload, PayloadStream}; use crate::http::payload::{Payload, PayloadStream};
use crate::http::{h1, Version};
use crate::io::{IoBoxed, RecvError}; use crate::io::{IoBoxed, RecvError};
use crate::time::{timeout_checked, Millis}; use crate::time::{timeout_checked, Millis};
use crate::util::{ready, BufMut, Bytes, BytesMut, Stream}; use crate::util::{ready, BufMut, Bytes, BytesMut, Stream};
@ -101,7 +99,13 @@ where
Ok((head, Payload::None)) Ok((head, Payload::None))
} }
_ => { _ => {
let pl: PayloadStream = Box::pin(PlStream::new(io, codec, created, pool)); let pl: PayloadStream = Box::pin(PlStream::new(
io,
codec,
created,
pool,
head.version == Version::HTTP_10,
));
Ok((head, pl.into())) Ok((head, pl.into()))
} }
} }
@ -137,6 +141,7 @@ pub(super) struct PlStream {
io: Option<IoBoxed>, io: Option<IoBoxed>,
codec: h1::ClientPayloadCodec, codec: h1::ClientPayloadCodec,
created: Instant, created: Instant,
http_10: bool,
pool: Option<Acquired>, pool: Option<Acquired>,
} }
@ -146,12 +151,14 @@ impl PlStream {
codec: h1::ClientCodec, codec: h1::ClientCodec,
created: Instant, created: Instant,
pool: Option<Acquired>, pool: Option<Acquired>,
http_10: bool,
) -> Self { ) -> Self {
PlStream { PlStream {
io: Some(io), io: Some(io),
codec: codec.into_payload_codec(), codec: codec.into_payload_codec(),
created, created,
pool, pool,
http_10,
} }
} }
} }
@ -161,41 +168,46 @@ impl Stream for PlStream {
fn poll_next( fn poll_next(
mut self: Pin<&mut Self>, mut self: Pin<&mut Self>,
cx: &mut Context<'_>, cx: &mut task::Context<'_>,
) -> Poll<Option<Self::Item>> { ) -> Poll<Option<Self::Item>> {
let mut this = self.as_mut(); let mut this = self.as_mut();
loop { loop {
return Poll::Ready(Some( let item = ready!(this.io.as_ref().unwrap().poll_recv(&this.codec, cx));
match ready!(this.io.as_ref().unwrap().poll_recv(&this.codec, cx)) { return Poll::Ready(Some(match item {
Ok(chunk) => { Ok(chunk) => {
if let Some(chunk) = chunk { if let Some(chunk) = chunk {
Ok(chunk) Ok(chunk)
} else { } else {
release_connection( release_connection(
this.io.take().unwrap(), this.io.take().unwrap(),
!this.codec.keepalive(), !this.codec.keepalive(),
this.created, this.created,
this.pool.take(), this.pool.take(),
); );
return Poll::Ready(None); return Poll::Ready(None);
}
} }
Err(RecvError::KeepAlive) => { }
Err(io::Error::new(io::ErrorKind::TimedOut, "Keep-alive").into()) Err(RecvError::KeepAlive) => {
Err(io::Error::new(io::ErrorKind::TimedOut, "Keep-alive").into())
}
Err(RecvError::Stop) => {
Err(io::Error::new(io::ErrorKind::Other, "Dispatcher stopped").into())
}
Err(RecvError::WriteBackpressure) => {
ready!(this.io.as_ref().unwrap().poll_flush(cx, false))?;
continue;
}
Err(RecvError::Decoder(err)) => Err(err),
Err(RecvError::PeerGone(Some(err))) => {
Err(PayloadError::Incomplete(Some(err)))
}
Err(RecvError::PeerGone(None)) => {
if this.http_10 {
return Poll::Ready(None);
} }
Err(RecvError::Stop) => { Err(PayloadError::Incomplete(None))
Err(io::Error::new(io::ErrorKind::Other, "Dispatcher stopped") }
.into()) }));
}
Err(RecvError::WriteBackpressure) => {
ready!(this.io.as_ref().unwrap().poll_flush(cx, false))?;
continue;
}
Err(RecvError::Decoder(err)) => Err(err),
Err(RecvError::PeerGone(Some(err))) => Err(err.into()),
Err(RecvError::PeerGone(None)) => return Poll::Ready(None),
},
));
} }
} }
} }

View file

@ -387,8 +387,8 @@ impl Future for ReadBody {
let this = self.get_mut(); let this = self.get_mut();
loop { loop {
return match Pin::new(&mut this.stream).poll_next(cx)? { return match Pin::new(&mut this.stream).poll_next(cx) {
Poll::Ready(Some(chunk)) => { Poll::Ready(Some(Ok(chunk))) => {
if this.limit > 0 && (this.buf.len() + chunk.len()) > this.limit { if this.limit > 0 && (this.buf.len() + chunk.len()) > this.limit {
Poll::Ready(Err(PayloadError::Overflow)) Poll::Ready(Err(PayloadError::Overflow))
} else { } else {
@ -397,6 +397,7 @@ impl Future for ReadBody {
} }
} }
Poll::Ready(None) => Poll::Ready(Ok(this.buf.split().freeze())), Poll::Ready(None) => Poll::Ready(Ok(this.buf.split().freeze())),
Poll::Ready(Some(Err(err))) => Poll::Ready(Err(err)),
Poll::Pending => { Poll::Pending => {
if this.timeout.poll_elapsed(cx).is_ready() { if this.timeout.poll_elapsed(cx).is_ready() {
Poll::Ready(Err(PayloadError::Incomplete(Some( Poll::Ready(Err(PayloadError::Incomplete(Some(

View file

@ -252,6 +252,7 @@ where
Ok(()) Ok(())
}) })
}); });
thread::sleep(std::time::Duration::from_millis(150));
let (system, server, addr) = rx.recv().unwrap(); let (system, server, addr) = rx.recv().unwrap();

View file

@ -82,7 +82,7 @@ mod route;
mod scope; mod scope;
mod server; mod server;
mod service; mod service;
mod stack; pub mod stack;
pub mod test; pub mod test;
pub mod types; pub mod types;
mod util; mod util;

View file

@ -508,19 +508,21 @@ async fn test_client_gzip_encoding_large() {
async fn test_client_gzip_encoding_large_random() { async fn test_client_gzip_encoding_large_random() {
let data = rand::thread_rng() let data = rand::thread_rng()
.sample_iter(&rand::distributions::Alphanumeric) .sample_iter(&rand::distributions::Alphanumeric)
.take(100_000) .take(1_048_500)
.map(char::from) .map(char::from)
.collect::<String>(); .collect::<String>();
let srv = test::server(|| { let srv = test::server(|| {
App::new().service(web::resource("/").route(web::to(|data: Bytes| async move { App::new()
let mut e = GzEncoder::new(Vec::new(), Compression::default()); .state(web::types::PayloadConfig::default().limit(1_048_576))
e.write_all(&data).unwrap(); .service(web::resource("/").route(web::to(|data: Bytes| async move {
let data = e.finish().unwrap(); let mut e = GzEncoder::new(Vec::new(), Compression::default());
HttpResponse::Ok() e.write_all(&data).unwrap();
.header("content-encoding", "gzip") let data = e.finish().unwrap();
.body(data) HttpResponse::Ok()
}))) .header("content-encoding", "gzip")
.body(data)
})))
}); });
// client request // client request
@ -528,7 +530,7 @@ async fn test_client_gzip_encoding_large_random() {
assert!(response.status().is_success()); assert!(response.status().is_success());
// read response // read response
let bytes = response.body().await.unwrap(); let bytes = response.body().limit(1_048_576).await.unwrap();
assert_eq!(bytes, Bytes::from(data)); assert_eq!(bytes, Bytes::from(data));
} }

View file

@ -1,5 +1,6 @@
#![cfg(feature = "openssl")] #![cfg(feature = "openssl")]
use std::{io, sync::atomic::AtomicUsize, sync::atomic::Ordering, sync::Arc}; use std::io;
use std::sync::{atomic::AtomicUsize, atomic::Ordering, Arc, Mutex};
use futures_util::stream::{once, Stream, StreamExt}; use futures_util::stream::{once, Stream, StreamExt};
use tls_openssl::ssl::{AlpnError, SslAcceptor, SslFiletype, SslMethod}; use tls_openssl::ssl::{AlpnError, SslAcceptor, SslFiletype, SslMethod};
@ -424,11 +425,12 @@ async fn test_h2_service_error() {
assert_eq!(bytes, Bytes::from_static(b"error")); assert_eq!(bytes, Bytes::from_static(b"error"));
} }
struct SetOnDrop(Arc<AtomicUsize>); struct SetOnDrop(Arc<AtomicUsize>, Arc<Mutex<Option<::oneshot::Sender<()>>>>);
impl Drop for SetOnDrop { impl Drop for SetOnDrop {
fn drop(&mut self) { fn drop(&mut self) {
self.0.fetch_add(1, Ordering::Relaxed); self.0.fetch_add(1, Ordering::Relaxed);
let _ = self.1.lock().unwrap().take().unwrap().send(());
} }
} }
@ -436,17 +438,20 @@ impl Drop for SetOnDrop {
async fn test_h2_client_drop() -> io::Result<()> { async fn test_h2_client_drop() -> io::Result<()> {
let count = Arc::new(AtomicUsize::new(0)); let count = Arc::new(AtomicUsize::new(0));
let count2 = count.clone(); let count2 = count.clone();
let (tx, rx) = ::oneshot::channel();
let tx = Arc::new(Mutex::new(Some(tx)));
let srv = test_server(move || { let srv = test_server(move || {
let tx = tx.clone();
let count = count2.clone(); let count = count2.clone();
HttpService::build() HttpService::build()
.h2(move |req: Request| { .h2(move |req: Request| {
let count = count.clone(); let st = SetOnDrop(count.clone(), tx.clone());
async move { async move {
let _st = SetOnDrop(count);
assert!(req.peer_addr().is_some()); assert!(req.peer_addr().is_some());
assert_eq!(req.version(), Version::HTTP_2); assert_eq!(req.version(), Version::HTTP_2);
sleep(Seconds(100)).await; sleep(Seconds(30)).await;
drop(st);
Ok::<_, io::Error>(Response::Ok().finish()) Ok::<_, io::Error>(Response::Ok().finish())
} }
}) })
@ -454,9 +459,9 @@ async fn test_h2_client_drop() -> io::Result<()> {
.map_err(|_| ()) .map_err(|_| ())
}); });
let result = timeout(Millis(250), srv.srequest(Method::GET, "/").send()).await; let result = timeout(Millis(1500), srv.srequest(Method::GET, "/").send()).await;
assert!(result.is_err()); assert!(result.is_err());
sleep(Millis(150)).await; let _ = timeout(Millis(1500), rx).await;
assert_eq!(count.load(Ordering::Relaxed), 1); assert_eq!(count.load(Ordering::Relaxed), 1);
Ok(()) Ok(())
} }
@ -539,13 +544,19 @@ async fn test_ws_transport() {
async fn test_h2_graceful_shutdown() -> io::Result<()> { async fn test_h2_graceful_shutdown() -> io::Result<()> {
let count = Arc::new(AtomicUsize::new(0)); let count = Arc::new(AtomicUsize::new(0));
let count2 = count.clone(); let count2 = count.clone();
let (tx, rx) = ::oneshot::channel();
let tx = Arc::new(Mutex::new(Some(tx)));
let srv = test_server(move || { let srv = test_server(move || {
let tx = tx.clone();
let count = count2.clone(); let count = count2.clone();
HttpService::build() HttpService::build()
.h2(move |_| { .h2(move |_| {
let count = count.clone(); let count = count.clone();
count.fetch_add(1, Ordering::Relaxed); count.fetch_add(1, Ordering::Relaxed);
if count.load(Ordering::Relaxed) == 2 {
let _ = tx.lock().unwrap().take().unwrap().send(());
}
async move { async move {
sleep(Millis(1000)).await; sleep(Millis(1000)).await;
count.fetch_sub(1, Ordering::Relaxed); count.fetch_sub(1, Ordering::Relaxed);
@ -566,7 +577,7 @@ async fn test_h2_graceful_shutdown() -> io::Result<()> {
let _ = req.send().await.unwrap(); let _ = req.send().await.unwrap();
sleep(Millis(100000)).await; sleep(Millis(100000)).await;
}); });
sleep(Millis(150)).await; let _ = rx.await;
assert_eq!(count.load(Ordering::Relaxed), 2); assert_eq!(count.load(Ordering::Relaxed), 2);
let (tx, rx) = oneshot::channel(); let (tx, rx) = oneshot::channel();
@ -574,8 +585,6 @@ async fn test_h2_graceful_shutdown() -> io::Result<()> {
srv.stop().await; srv.stop().await;
let _ = tx.send(()); let _ = tx.send(());
}); });
sleep(Millis(150)).await;
assert_eq!(count.load(Ordering::Relaxed), 2);
let _ = rx.await; let _ = rx.await;
assert_eq!(count.load(Ordering::Relaxed), 0); assert_eq!(count.load(Ordering::Relaxed), 0);

View file

@ -1,4 +1,4 @@
use std::sync::{atomic::AtomicUsize, atomic::Ordering, Arc}; use std::sync::{atomic::AtomicUsize, atomic::Ordering, Arc, Mutex};
use std::{io, io::Read, io::Write, net}; use std::{io, io::Read, io::Write, net};
use futures_util::future::{self, FutureExt}; use futures_util::future::{self, FutureExt};
@ -723,11 +723,12 @@ async fn test_h1_service_error() {
assert_eq!(bytes, Bytes::from_static(b"error")); assert_eq!(bytes, Bytes::from_static(b"error"));
} }
struct SetOnDrop(Arc<AtomicUsize>); struct SetOnDrop(Arc<AtomicUsize>, Option<::oneshot::Sender<()>>);
impl Drop for SetOnDrop { impl Drop for SetOnDrop {
fn drop(&mut self) { fn drop(&mut self) {
self.0.fetch_add(1, Ordering::Relaxed); self.0.fetch_add(1, Ordering::Relaxed);
let _ = self.1.take().unwrap().send(());
} }
} }
@ -735,24 +736,28 @@ impl Drop for SetOnDrop {
async fn test_h1_client_drop() -> io::Result<()> { async fn test_h1_client_drop() -> io::Result<()> {
let count = Arc::new(AtomicUsize::new(0)); let count = Arc::new(AtomicUsize::new(0));
let count2 = count.clone(); let count2 = count.clone();
let (tx, rx) = ::oneshot::channel();
let tx = Arc::new(Mutex::new(Some(tx)));
let srv = test_server(move || { let srv = test_server(move || {
let tx = tx.clone();
let count = count2.clone(); let count = count2.clone();
HttpService::build().h1(move |req: Request| { HttpService::build().h1(move |req: Request| {
let tx = tx.clone();
let count = count.clone(); let count = count.clone();
async move { async move {
let _st = SetOnDrop(count); let _st = SetOnDrop(count, tx.lock().unwrap().take());
assert!(req.peer_addr().is_some()); assert!(req.peer_addr().is_some());
assert_eq!(req.version(), Version::HTTP_11); assert_eq!(req.version(), Version::HTTP_11);
sleep(Millis(500)).await; sleep(Millis(50000)).await;
Ok::<_, io::Error>(Response::Ok().finish()) Ok::<_, io::Error>(Response::Ok().finish())
} }
}) })
}); });
let result = timeout(Millis(100), srv.request(Method::GET, "/").send()).await; let result = timeout(Millis(1500), srv.request(Method::GET, "/").send()).await;
assert!(result.is_err()); assert!(result.is_err());
sleep(Millis(1000)).await; let _ = rx.await;
assert_eq!(count.load(Ordering::Relaxed), 1); assert_eq!(count.load(Ordering::Relaxed), 1);
Ok(()) Ok(())
} }
@ -761,12 +766,18 @@ async fn test_h1_client_drop() -> io::Result<()> {
async fn test_h1_gracefull_shutdown() { async fn test_h1_gracefull_shutdown() {
let count = Arc::new(AtomicUsize::new(0)); let count = Arc::new(AtomicUsize::new(0));
let count2 = count.clone(); let count2 = count.clone();
let (tx, rx) = ::oneshot::channel();
let tx = Arc::new(Mutex::new(Some(tx)));
let srv = test_server(move || { let srv = test_server(move || {
let tx = tx.clone();
let count = count2.clone(); let count = count2.clone();
HttpService::build().h1(move |_: Request| { HttpService::build().h1(move |_: Request| {
let count = count.clone(); let count = count.clone();
count.fetch_add(1, Ordering::Relaxed); count.fetch_add(1, Ordering::Relaxed);
if count.load(Ordering::Relaxed) == 2 {
let _ = tx.lock().unwrap().take().unwrap().send(());
}
async move { async move {
sleep(Millis(1000)).await; sleep(Millis(1000)).await;
count.fetch_sub(1, Ordering::Relaxed); count.fetch_sub(1, Ordering::Relaxed);
@ -781,7 +792,7 @@ async fn test_h1_gracefull_shutdown() {
let mut stream2 = net::TcpStream::connect(srv.addr()).unwrap(); let mut stream2 = net::TcpStream::connect(srv.addr()).unwrap();
let _ = stream2.write_all(b"GET /index.html HTTP/1.1\r\n\r\n"); let _ = stream2.write_all(b"GET /index.html HTTP/1.1\r\n\r\n");
sleep(Millis(150)).await; let _ = rx.await;
assert_eq!(count.load(Ordering::Relaxed), 2); assert_eq!(count.load(Ordering::Relaxed), 2);
let (tx, rx) = oneshot::channel(); let (tx, rx) = oneshot::channel();
@ -789,8 +800,6 @@ async fn test_h1_gracefull_shutdown() {
srv.stop().await; srv.stop().await;
let _ = tx.send(()); let _ = tx.send(());
}); });
sleep(Millis(150)).await;
assert_eq!(count.load(Ordering::Relaxed), 2);
let _ = rx.await; let _ = rx.await;
assert_eq!(count.load(Ordering::Relaxed), 0); assert_eq!(count.load(Ordering::Relaxed), 0);
@ -800,12 +809,18 @@ async fn test_h1_gracefull_shutdown() {
async fn test_h1_gracefull_shutdown_2() { async fn test_h1_gracefull_shutdown_2() {
let count = Arc::new(AtomicUsize::new(0)); let count = Arc::new(AtomicUsize::new(0));
let count2 = count.clone(); let count2 = count.clone();
let (tx, rx) = ::oneshot::channel();
let tx = Arc::new(Mutex::new(Some(tx)));
let srv = test_server(move || { let srv = test_server(move || {
let tx = tx.clone();
let count = count2.clone(); let count = count2.clone();
HttpService::build().finish(move |_: Request| { HttpService::build().finish(move |_: Request| {
let count = count.clone(); let count = count.clone();
count.fetch_add(1, Ordering::Relaxed); count.fetch_add(1, Ordering::Relaxed);
if count.load(Ordering::Relaxed) == 2 {
let _ = tx.lock().unwrap().take().unwrap().send(());
}
async move { async move {
sleep(Millis(1000)).await; sleep(Millis(1000)).await;
count.fetch_sub(1, Ordering::Relaxed); count.fetch_sub(1, Ordering::Relaxed);
@ -820,17 +835,14 @@ async fn test_h1_gracefull_shutdown_2() {
let mut stream2 = net::TcpStream::connect(srv.addr()).unwrap(); let mut stream2 = net::TcpStream::connect(srv.addr()).unwrap();
let _ = stream2.write_all(b"GET /index.html HTTP/1.1\r\n\r\n"); let _ = stream2.write_all(b"GET /index.html HTTP/1.1\r\n\r\n");
sleep(Millis(150)).await; let _ = rx.await;
assert_eq!(count.load(Ordering::Relaxed), 2); assert_eq!(count.load(Ordering::Acquire), 2);
let (tx, rx) = oneshot::channel(); let (tx, rx) = oneshot::channel();
rt::spawn(async move { rt::spawn(async move {
srv.stop().await; srv.stop().await;
let _ = tx.send(()); let _ = tx.send(());
}); });
sleep(Millis(150)).await;
assert_eq!(count.load(Ordering::Relaxed), 2);
let _ = rx.await; let _ = rx.await;
assert_eq!(count.load(Ordering::Relaxed), 0); assert_eq!(count.load(Ordering::Relaxed), 0);
} }