add custom Ready and Lazy futures

This commit is contained in:
Nikolay Kim 2021-04-02 20:40:59 +06:00
parent 8e76c100b4
commit d56309c64f
19 changed files with 189 additions and 181 deletions

View file

@ -1,5 +1,11 @@
# Changes
## [0.1.7] - 2021-04-02
* drop futures-util dependency
* add custom Ready and Lazy futures
## [0.1.6] - 2021-03-26
* Add .on_shutdown() callback to fn_service

View file

@ -1,6 +1,6 @@
[package]
name = "ntex-service"
version = "0.1.6"
version = "0.1.7"
authors = ["ntex contributors <team@ntex.rs>"]
description = "ntex service"
keywords = ["network", "framework", "async", "futures"]
@ -16,7 +16,6 @@ name = "ntex_service"
path = "src/lib.rs"
[dependencies]
futures-util = "0.3.13"
pin-project-lite = "0.2.4"
[dev-dependencies]

View file

@ -1,7 +1,4 @@
use std::future::Future;
use std::pin::Pin;
use std::rc::Rc;
use std::task::{Context, Poll};
use std::{future::Future, pin::Pin, rc::Rc, task::Context, task::Poll};
use super::{Service, ServiceFactory};
@ -272,12 +269,9 @@ where
#[cfg(test)]
mod tests {
use std::cell::Cell;
use std::rc::Rc;
use std::task::{Context, Poll};
use futures_util::future::{lazy, ok, ready, Ready};
use std::{cell::Cell, rc::Rc, task::Context, task::Poll};
use crate::util::{lazy, Ready};
use crate::{fn_factory, pipeline, pipeline_factory, Service, ServiceFactory};
struct Srv1(Rc<Cell<usize>>);
@ -286,7 +280,7 @@ mod tests {
type Request = &'static str;
type Response = &'static str;
type Error = ();
type Future = Ready<Result<Self::Response, ()>>;
type Future = Ready<Self::Response, ()>;
fn poll_ready(&self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.0.set(self.0.get() + 1);
@ -294,7 +288,7 @@ mod tests {
}
fn call(&self, req: &'static str) -> Self::Future {
ok(req)
Ready::ok(req)
}
}
@ -305,7 +299,7 @@ mod tests {
type Request = &'static str;
type Response = (&'static str, &'static str);
type Error = ();
type Future = Ready<Result<Self::Response, ()>>;
type Future = Ready<Self::Response, ()>;
fn poll_ready(&self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.0.set(self.0.get() + 1);
@ -313,7 +307,7 @@ mod tests {
}
fn call(&self, req: &'static str) -> Self::Future {
ok((req, "srv2"))
Ready::ok((req, "srv2"))
}
}
@ -344,10 +338,11 @@ mod tests {
async fn test_factory() {
let cnt = Rc::new(Cell::new(0));
let cnt2 = cnt.clone();
let new_srv =
pipeline_factory(fn_factory(move || ready(Ok::<_, ()>(Srv1(cnt2.clone())))))
.and_then(move || ready(Ok(Srv2(cnt.clone()))))
.clone();
let new_srv = pipeline_factory(fn_factory(move || {
Ready::result(Ok::<_, ()>(Srv1(cnt2.clone())))
}))
.and_then(move || Ready::result(Ok(Srv2(cnt.clone()))))
.clone();
let srv = new_srv.new_service(()).await.unwrap();
let res = srv.call("srv1").await;

View file

@ -1,8 +1,6 @@
use std::future::Future;
use std::marker::PhantomData;
use std::pin::Pin;
use std::rc::Rc;
use std::task::{Context, Poll};
use std::{
future::Future, marker::PhantomData, pin::Pin, rc::Rc, task::Context, task::Poll,
};
use crate::{Service, ServiceFactory};
@ -294,8 +292,7 @@ where
mod tests {
use super::*;
use futures_util::future::{lazy, ok, Ready, TryFutureExt};
use crate::util::{lazy, Ready};
use crate::{fn_service, pipeline, pipeline_factory, Service, ServiceFactory};
#[derive(Clone)]
@ -304,22 +301,23 @@ mod tests {
type Request = ();
type Response = ();
type Error = ();
type Future = Ready<Result<(), ()>>;
type Future = Ready<(), ()>;
fn poll_ready(&self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(()))
}
fn call(&self, _: Self::Request) -> Self::Future {
ok(())
Ready::ok(())
}
}
#[ntex::test]
async fn test_service() {
let srv = pipeline(ok)
let srv = pipeline(Ready::<_, ()>::ok)
.and_then_apply_fn(Srv, |req: &'static str, s| {
s.call(()).map_ok(move |res| (req, res))
let f = s.call(());
async move { f.await.map(move |res| (req, res)) }
})
.clone();
let res = lazy(|cx| srv.poll_ready(cx)).await;
@ -335,12 +333,16 @@ mod tests {
#[ntex::test]
async fn test_service_factory() {
let new_srv = pipeline_factory(|| ok::<_, ()>(fn_service(ok)))
.and_then_apply_fn(
|| ok(Srv),
|req: &'static str, s| s.call(()).map_ok(move |res| (req, res)),
)
.clone();
let new_srv =
pipeline_factory(|| Ready::<_, ()>::ok(fn_service(Ready::<_, ()>::ok)))
.and_then_apply_fn(
|| Ready::ok(Srv),
|req: &'static str, s| {
let f = s.call(());
async move { f.await.map(move |res| (req, res)) }
},
)
.clone();
let srv = new_srv.new_service(()).await.unwrap();
let res = lazy(|cx| srv.poll_ready(cx)).await;
assert_eq!(res, Poll::Ready(Ok(())));

View file

@ -1,7 +1,4 @@
use std::future::Future;
use std::marker::PhantomData;
use std::pin::Pin;
use std::task::{Context, Poll};
use std::{future::Future, marker::PhantomData, pin::Pin, task::Context, task::Poll};
use super::{IntoService, IntoServiceFactory, Service, ServiceFactory};
@ -216,10 +213,10 @@ where
mod tests {
use std::task::{Context, Poll};
use futures_util::future::{lazy, ok, Ready};
use super::*;
use crate::{pipeline, pipeline_factory, Service, ServiceFactory};
use crate::{
pipeline, pipeline_factory, util::lazy, util::Ready, Service, ServiceFactory,
};
#[derive(Clone)]
struct Srv;
@ -228,14 +225,14 @@ mod tests {
type Request = ();
type Response = ();
type Error = ();
type Future = Ready<Result<(), ()>>;
type Future = Ready<(), ()>;
fn poll_ready(&self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(()))
}
fn call(&self, _: ()) -> Self::Future {
ok(())
Ready::ok(())
}
}
@ -267,7 +264,7 @@ mod tests {
async fn test_new_service() {
let new_srv = pipeline_factory(
apply_fn_factory(
|| ok::<_, ()>(Srv),
|| Ready::<_, ()>::ok(Srv),
|req: &'static str, srv| {
let fut = srv.call(());
async move {

View file

@ -1,8 +1,6 @@
use std::future::Future;
use std::marker::PhantomData;
use std::pin::Pin;
use std::rc::Rc;
use std::task::{Context, Poll};
use std::{
future::Future, marker::PhantomData, pin::Pin, rc::Rc, task::Context, task::Poll,
};
use crate::{Service, ServiceFactory};
@ -229,12 +227,10 @@ where
#[cfg(test)]
mod tests {
use futures_util::future::ok;
use std::cell::Cell;
use std::rc::Rc;
use std::{cell::Cell, rc::Rc};
use super::*;
use crate::{fn_service, Service};
use crate::{fn_service, util::Ready, Service};
#[ntex::test]
async fn test_apply() {
@ -242,7 +238,7 @@ mod tests {
let item2 = item.clone();
let srv = apply_cfg(
fn_service(move |item: usize| ok::<_, ()>(item + 1)),
fn_service(move |item: usize| Ready::<_, ()>::ok(item + 1)),
move |_: (), srv| {
let id = item2.get();
let fut = srv.call(id);
@ -250,7 +246,7 @@ mod tests {
async move {
item.set(fut.await.unwrap());
Ok::<_, ()>(fn_service(|id: usize| ok::<_, ()>(id * 2)))
Ok::<_, ()>(fn_service(|id: usize| Ready::<_, ()>::ok(id * 2)))
}
},
)
@ -269,7 +265,7 @@ mod tests {
let item2 = item.clone();
let srv = apply_cfg_factory(
fn_service(move |item: usize| ok::<_, ()>(item + 1)),
fn_service(move |item: usize| Ready::<_, ()>::ok(item + 1)),
move |_: (), srv| {
let id = item2.get();
let fut = srv.call(id);
@ -277,7 +273,7 @@ mod tests {
async move {
item.set(fut.await.unwrap());
Ok::<_, ()>(fn_service(|id: usize| ok::<_, ()>(id * 2)))
Ok::<_, ()>(fn_service(|id: usize| Ready::<_, ()>::ok(id * 2)))
}
},
)

View file

@ -1,8 +1,4 @@
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
use futures_util::future::FutureExt;
use std::{future::Future, pin::Pin, task::Context, task::Poll};
use crate::{Service, ServiceFactory};
@ -114,11 +110,11 @@ where
type Future = BoxFuture<Self::Service, Self::InitError>;
fn new_service(&self, cfg: C) -> Self::Future {
Box::pin(
self.factory
.new_service(cfg)
.map(|res| res.map(ServiceWrapper::boxed)),
)
let fut = self.factory.new_service(cfg);
Box::pin(async move {
let srv = fut.await?;
Ok(ServiceWrapper::boxed(srv))
})
}
}

View file

@ -1,11 +1,7 @@
use std::cell::{Cell, RefCell};
use std::future::Future;
use std::marker::PhantomData;
use std::task::{Context, Poll};
use std::{cell::Cell, cell::RefCell, future::Future, marker::PhantomData};
use futures_util::future::{ok, Ready};
use crate::{IntoService, IntoServiceFactory, Service, ServiceFactory};
use crate::{util::Ready, IntoService, IntoServiceFactory, Service, ServiceFactory};
#[inline]
/// Create `ServiceFactory` for function that can act as a `Service`
@ -37,7 +33,6 @@ where
/// ```rust
/// use std::io;
/// use ntex_service::{fn_factory, fn_service, Service, ServiceFactory};
/// use futures_util::future::ok;
///
/// /// Service that divides two usize values.
/// async fn div((x, y): (usize, usize)) -> Result<usize, io::Error> {
@ -52,7 +47,7 @@ where
/// async fn main() -> io::Result<()> {
/// // Create service factory that produces `div` services
/// let factory = fn_factory(|| {
/// ok::<_, io::Error>(fn_service(div))
/// async {Ok::<_, io::Error>(fn_service(div))}
/// });
///
/// // construct new service
@ -88,14 +83,13 @@ where
/// ```rust
/// use std::io;
/// use ntex_service::{fn_factory_with_config, fn_service, Service, ServiceFactory};
/// use futures_util::future::ok;
///
/// #[ntex::main]
/// async fn main() -> io::Result<()> {
/// // Create service factory. factory uses config argument for
/// // services it generates.
/// let factory = fn_factory_with_config(|y: usize| {
/// ok::<_, io::Error>(fn_service(move |x: usize| ok::<_, io::Error>(x * y)))
/// async move { Ok::<_, io::Error>(fn_service(move |x: usize| async move { Ok::<_, io::Error>(x * y) })) }
/// });
///
/// // construct new service with config argument
@ -322,14 +316,14 @@ where
type Config = Cfg;
type Service = FnService<F, Fut, Req, Res, Err, FShut>;
type InitError = ();
type Future = Ready<Result<Self::Service, Self::InitError>>;
type Future = Ready<Self::Service, Self::InitError>;
#[inline]
fn new_service(&self, _: Cfg) -> Self::Future {
let f = self.f_shutdown.take();
self.f_shutdown.set(f.clone());
ok(FnService {
Ready::ok(FnService {
f: self.f.clone(),
f_shutdown: Cell::new(f),
_t: PhantomData,
@ -531,15 +525,13 @@ where
mod tests {
use std::{rc::Rc, task::Poll};
use futures_util::future::{lazy, ok};
use super::*;
use crate::{Service, ServiceFactory};
use crate::{util::lazy, Service, ServiceFactory};
#[ntex::test]
async fn test_fn_service() {
let shutdown = Rc::new(RefCell::new(false));
let new_srv = fn_service(|()| ok::<_, ()>("srv"))
let new_srv = fn_service(|()| async { Ok::<_, ()>("srv") })
.on_shutdown(|| {
*shutdown.borrow_mut() = true;
})
@ -565,7 +557,7 @@ mod tests {
#[ntex::test]
async fn test_fn_mut_service() {
let srv = fn_mut_service(|()| ok::<_, ()>("srv")).clone();
let srv = fn_mut_service(|()| async { Ok::<_, ()>("srv") }).clone();
let res = srv.call(()).await;
assert_eq!(lazy(|cx| srv.poll_ready(cx)).await, Poll::Ready(Ok(())));
@ -576,7 +568,7 @@ mod tests {
#[ntex::test]
async fn test_fn_service_service() {
let shutdown = Rc::new(RefCell::new(false));
let srv = fn_service(|()| ok::<_, ()>("srv"))
let srv = fn_service(|()| async { Ok::<_, ()>("srv") })
.on_shutdown(|| {
*shutdown.borrow_mut() = true;
})
@ -595,8 +587,10 @@ mod tests {
#[ntex::test]
async fn test_fn_service_with_config() {
let new_srv = fn_factory_with_config(|cfg: usize| {
ok::<_, ()>(fn_service(move |()| ok::<_, ()>(("srv", cfg))))
let new_srv = fn_factory_with_config(|cfg: usize| async move {
Ok::<_, ()>(fn_service(
move |()| async move { Ok::<_, ()>(("srv", cfg)) },
))
})
.clone();

View file

@ -1,7 +1,6 @@
use futures_util::future::{ok, Ready};
use std::{future::Future, marker::PhantomData};
use crate::{apply_fn, dev::Apply, Service, Transform};
use crate::{apply_fn, dev::Apply, util::Ready, Service, Transform};
/// Use function as transform service
pub fn fn_transform<S, F, R, Req, Res, Err>(
@ -47,10 +46,10 @@ where
type Error = Err;
type Transform = Apply<S, F, R, Req, Res, Err>;
type InitError = ();
type Future = Ready<Result<Self::Transform, Self::InitError>>;
type Future = Ready<Self::Transform, Self::InitError>;
fn new_transform(&self, service: S) -> Self::Future {
ok(apply_fn(service, self.f.clone()))
Ready::ok(apply_fn(service, self.f.clone()))
}
}
@ -68,11 +67,10 @@ where
#[cfg(test)]
#[allow(clippy::redundant_clone)]
mod tests {
use futures_util::future::{lazy, ok};
use std::task::{Context, Poll};
use super::*;
use crate::Service;
use crate::{util::lazy, Service};
#[derive(Clone)]
struct Srv;
@ -81,14 +79,14 @@ mod tests {
type Request = usize;
type Response = usize;
type Error = ();
type Future = Ready<Result<usize, ()>>;
type Future = Ready<usize, ()>;
fn poll_ready(&self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(()))
}
fn call(&self, i: usize) -> Self::Future {
ok(i * 2)
Ready::ok(i * 2)
}
}

32
ntex-service/src/lazy.rs Normal file
View file

@ -0,0 +1,32 @@
use std::{future::Future, pin::Pin, task::Context, task::Poll};
/// Future for the [`lazy`] function.
#[derive(Debug)]
#[must_use = "futures do nothing unless you `.await` or poll them"]
pub struct Lazy<F> {
f: Option<F>,
}
// safe because we never generate `Pin<&mut F>`
impl<F> Unpin for Lazy<F> {}
/// Creates a new future that allows delayed execution of a closure.
///
/// The provided closure is only run once the future is polled.
pub fn lazy<F, R>(f: F) -> Lazy<F>
where
F: FnOnce(&mut Context<'_>) -> R,
{
Lazy { f: Some(f) }
}
impl<F, R> Future for Lazy<F>
where
F: FnOnce(&mut Context<'_>) -> R,
{
type Output = R;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<R> {
Poll::Ready((self.f.take().expect("Lazy polled after completion"))(cx))
}
}

View file

@ -21,6 +21,9 @@ mod then;
mod transform;
mod transform_err;
mod lazy;
mod ready;
pub use self::apply::{apply_fn, apply_fn_factory};
pub use self::fn_service::{
fn_factory, fn_factory_with_config, fn_mut_service, fn_service,
@ -337,6 +340,11 @@ where
tp.into_service()
}
pub mod util {
pub use crate::lazy::{lazy, Lazy};
pub use crate::ready::Ready;
}
pub mod dev {
pub use crate::apply::{Apply, ApplyServiceFactory};
pub use crate::fn_service::{

View file

@ -1,7 +1,4 @@
use std::future::Future;
use std::marker::PhantomData;
use std::pin::Pin;
use std::task::{Context, Poll};
use std::{future::Future, marker::PhantomData, pin::Pin, task::Context, task::Poll};
use super::{Service, ServiceFactory};
@ -209,10 +206,8 @@ where
#[cfg(test)]
mod tests {
use futures_util::future::{lazy, ok, Ready};
use super::*;
use crate::{IntoServiceFactory, Service, ServiceFactory};
use crate::{util::lazy, util::Ready, IntoServiceFactory, Service, ServiceFactory};
#[derive(Clone)]
struct Srv;
@ -221,14 +216,14 @@ mod tests {
type Request = ();
type Response = ();
type Error = ();
type Future = Ready<Result<(), ()>>;
type Future = Ready<(), ()>;
fn poll_ready(&self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(()))
}
fn call(&self, _: ()) -> Self::Future {
ok(())
Ready::ok(())
}
}
@ -262,7 +257,10 @@ mod tests {
#[ntex::test]
async fn test_factory() {
let new_srv = (|| ok::<_, ()>(Srv)).into_factory().map(|_| "ok").clone();
let new_srv = (|| async { Ok::<_, ()>(Srv) })
.into_factory()
.map(|_| "ok")
.clone();
let srv = new_srv.new_service(&()).await.unwrap();
let res = srv.call(()).await;
assert!(res.is_ok());
@ -271,9 +269,10 @@ mod tests {
#[ntex::test]
async fn test_pipeline_factory() {
let new_srv = crate::pipeline_factory((|| ok::<_, ()>(Srv)).into_factory())
.map(|_| "ok")
.clone();
let new_srv =
crate::pipeline_factory((|| async { Ok::<_, ()>(Srv) }).into_factory())
.map(|_| "ok")
.clone();
let srv = new_srv.new_service(&()).await.unwrap();
let res = srv.call(()).await;
assert!(res.is_ok());

View file

@ -1,11 +1,5 @@
use std::cell::RefCell;
use std::future::Future;
use std::marker::PhantomData;
use std::pin::Pin;
use std::rc::Rc;
use std::task::{Context, Poll};
use futures_util::ready;
use std::{cell::RefCell, future::Future, marker::PhantomData, pin::Pin, rc::Rc};
use super::{IntoServiceFactory, Service, ServiceFactory};
@ -273,21 +267,31 @@ where
match this.state.as_mut().project() {
ResponseStateProject::CreateMapper { fut } => {
let mapper = ready!(fut.poll(cx))?;
let mapper = match fut.poll(cx) {
Poll::Ready(result) => result?,
Poll::Pending => return Poll::Pending,
};
*this.inner.mapper.borrow_mut() = Some(mapper);
this.state.set(ResponseState::MapReady);
self.poll(cx)
}
ResponseStateProject::MapReady => {
let mapper = this.inner.mapper.borrow();
ready!(mapper.as_ref().unwrap().poll_ready(cx))?;
match mapper.as_ref().unwrap().poll_ready(cx) {
Poll::Ready(result) => result?,
Poll::Pending => return Poll::Pending,
};
let fut = mapper.as_ref().unwrap().call(this.config.take().unwrap());
this.state.set(ResponseState::MapConfig { fut });
drop(mapper);
self.poll(cx)
}
ResponseStateProject::MapConfig { fut } => {
let config = ready!(fut.poll(cx))?;
let config = match fut.poll(cx) {
Poll::Ready(result) => result?,
Poll::Pending => return Poll::Pending,
};
let fut = this.inner.a.new_service(config);
this.state.set(ResponseState::CreateService { fut });
self.poll(cx)
@ -300,22 +304,22 @@ where
#[cfg(test)]
#[allow(clippy::redundant_closure)]
mod tests {
use futures_util::future::ok;
use std::cell::Cell;
use std::rc::Rc;
use std::{cell::Cell, rc::Rc};
use super::*;
use crate::{fn_factory_with_config, fn_service, ServiceFactory};
use crate::{fn_factory_with_config, fn_service, util::Ready, ServiceFactory};
#[ntex::test]
async fn test_map_config() {
let item = Rc::new(Cell::new(1usize));
let factory =
map_config(fn_service(|item: usize| ok::<_, ()>(item)), |t: usize| {
let factory = map_config(
fn_service(|item: usize| Ready::<_, ()>::ok(item)),
|t: usize| {
item.set(item.get() + t);
})
.clone();
},
)
.clone();
let _ = factory.new_service(10).await;
assert_eq!(item.get(), 11);
@ -323,7 +327,7 @@ mod tests {
#[ntex::test]
async fn test_unit_config() {
let _ = unit_config(fn_service(|item: usize| ok::<_, ()>(item)))
let _ = unit_config(fn_service(|item: usize| Ready::<_, ()>::ok(item)))
.clone()
.new_service(10)
.await;
@ -339,10 +343,10 @@ mod tests {
let item = item2.clone();
async move {
item.set(next);
Ok::<_, ()>(fn_service(|id: usize| ok::<_, ()>(id * 2)))
Ok::<_, ()>(fn_service(|id: usize| Ready::<_, ()>::ok(id * 2)))
}
}),
fn_service(move |item: usize| ok::<_, ()>(item + 1)),
fn_service(move |item: usize| Ready::<_, ()>::ok(item + 1)),
)
.clone()
.new_service(10)

View file

@ -1,7 +1,4 @@
use std::future::Future;
use std::marker::PhantomData;
use std::pin::Pin;
use std::task::{Context, Poll};
use std::{future::Future, marker::PhantomData, pin::Pin, task::Context, task::Poll};
use super::{Service, ServiceFactory};
@ -210,9 +207,8 @@ where
#[cfg(test)]
mod tests {
use futures_util::future::{err, lazy, ok, Ready};
use super::*;
use crate::util::{lazy, Ready};
use crate::{IntoServiceFactory, Service, ServiceFactory};
#[derive(Clone)]
@ -222,14 +218,14 @@ mod tests {
type Request = ();
type Response = ();
type Error = ();
type Future = Ready<Result<(), ()>>;
type Future = Ready<(), ()>;
fn poll_ready(&self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Err(()))
}
fn call(&self, _: ()) -> Self::Future {
err(())
Ready::err(())
}
}
@ -261,7 +257,7 @@ mod tests {
#[ntex::test]
async fn test_factory() {
let new_srv = (|| ok::<_, ()>(Srv))
let new_srv = (|| Ready::<_, ()>::ok(Srv))
.into_factory()
.map_err(|_| "error")
.clone();
@ -273,9 +269,10 @@ mod tests {
#[ntex::test]
async fn test_pipeline_factory() {
let new_srv = crate::pipeline_factory((|| ok::<_, ()>(Srv)).into_factory())
.map_err(|_| "error")
.clone();
let new_srv =
crate::pipeline_factory((|| async { Ok::<_, ()>(Srv) }).into_factory())
.map_err(|_| "error")
.clone();
let srv = new_srv.new_service(&()).await.unwrap();
let res = srv.call(()).await;
assert!(res.is_err());

View file

@ -1,7 +1,4 @@
use std::future::Future;
use std::marker::PhantomData;
use std::pin::Pin;
use std::task::{Context, Poll};
use std::{future::Future, marker::PhantomData, pin::Pin, task::Context, task::Poll};
use super::ServiceFactory;
@ -97,8 +94,6 @@ where
#[cfg(test)]
mod tests {
use futures_util::future::ok;
use crate::{fn_factory_with_config, fn_service, pipeline_factory, ServiceFactory};
#[ntex::test]
@ -107,7 +102,7 @@ mod tests {
if err {
Err(())
} else {
Ok(fn_service(|i: usize| ok::<_, ()>(i * 2)))
Ok(fn_service(|i: usize| async move { Ok::<_, ()>(i * 2) }))
}
}))
.map_init_err(|_| std::io::Error::new(std::io::ErrorKind::Other, "err"))

View file

@ -1,7 +1,4 @@
use std::future::Future;
use std::pin::Pin;
use std::rc::Rc;
use std::task::{Context, Poll};
use std::{future::Future, pin::Pin, rc::Rc, task::Context, task::Poll};
use super::{Service, ServiceFactory};
@ -259,13 +256,11 @@ where
#[cfg(test)]
mod tests {
use std::cell::Cell;
use std::rc::Rc;
use std::task::{Context, Poll};
use std::{cell::Cell, rc::Rc, task::Context, task::Poll};
use futures_util::future::{err, lazy, ok, ready, Ready};
use crate::{pipeline, pipeline_factory, Service, ServiceFactory};
use crate::{
pipeline, pipeline_factory, util::lazy, util::Ready, Service, ServiceFactory,
};
#[derive(Clone)]
struct Srv1(Rc<Cell<usize>>);
@ -274,7 +269,7 @@ mod tests {
type Request = Result<&'static str, &'static str>;
type Response = &'static str;
type Error = ();
type Future = Ready<Result<Self::Response, Self::Error>>;
type Future = Ready<Self::Response, Self::Error>;
fn poll_ready(&self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.0.set(self.0.get() + 1);
@ -283,8 +278,8 @@ mod tests {
fn call(&self, req: Result<&'static str, &'static str>) -> Self::Future {
match req {
Ok(msg) => ok(msg),
Err(_) => err(()),
Ok(msg) => Ready::ok(msg),
Err(_) => Ready::err(()),
}
}
}
@ -295,7 +290,7 @@ mod tests {
type Request = Result<&'static str, ()>;
type Response = (&'static str, &'static str);
type Error = ();
type Future = Ready<Result<Self::Response, ()>>;
type Future = Ready<Self::Response, ()>;
fn poll_ready(&self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.0.set(self.0.get() + 1);
@ -304,8 +299,8 @@ mod tests {
fn call(&self, req: Result<&'static str, ()>) -> Self::Future {
match req {
Ok(msg) => ok((msg, "ok")),
Err(()) => ok(("srv2", "err")),
Ok(msg) => Ready::ok((msg, "ok")),
Err(()) => Ready::ok(("srv2", "err")),
}
}
}
@ -339,9 +334,9 @@ mod tests {
async fn test_factory() {
let cnt = Rc::new(Cell::new(0));
let cnt2 = cnt.clone();
let blank = move || ready(Ok::<_, ()>(Srv1(cnt2.clone())));
let blank = move || Ready::<_, ()>::ok(Srv1(cnt2.clone()));
let factory = pipeline_factory(blank)
.then(move || ready(Ok(Srv2(cnt.clone()))))
.then(move || Ready::ok(Srv2(cnt.clone())))
.clone();
let srv = factory.new_service(&()).await.unwrap();
let res = srv.call(Ok("srv1")).await;

View file

@ -1,7 +1,4 @@
use std::future::Future;
use std::pin::Pin;
use std::rc::Rc;
use std::task::{Context, Poll};
use std::{future::Future, pin::Pin, rc::Rc, task::Context, task::Poll};
use crate::transform_err::TransformMapInitErr;
use crate::{IntoServiceFactory, Service, ServiceFactory};
@ -64,7 +61,7 @@ where
///
/// Factory for `Timeout` middleware from the above example could look like this:
///
/// ```rust,,ignore
/// ```rust,ignore
/// pub struct TimeoutTransform {
/// timeout: Duration,
/// }
@ -236,10 +233,8 @@ where
#[cfg(test)]
#[allow(clippy::redundant_clone)]
mod tests {
use futures_util::future::{lazy, ok, Ready};
use super::*;
use crate::{fn_service, Service, ServiceFactory};
use crate::{fn_service, util::lazy, util::Ready, Service, ServiceFactory};
#[derive(Clone)]
struct Tr;
@ -251,10 +246,10 @@ mod tests {
type Transform = Srv<S>;
type InitError = ();
type Future = Ready<Result<Self::Transform, Self::InitError>>;
type Future = Ready<Self::Transform, Self::InitError>;
fn new_transform(&self, service: S) -> Self::Future {
ok(Srv(service))
Ready::ok(Srv(service))
}
}
@ -280,7 +275,7 @@ mod tests {
async fn transform() {
let factory = apply(
Rc::new(Tr.map_init_err(|_| ()).clone()),
fn_service(|i: usize| ok::<_, ()>(i * 2)),
fn_service(|i: usize| Ready::<_, ()>::ok(i * 2)),
)
.clone();

View file

@ -3,7 +3,6 @@ pub mod counter;
mod extensions;
pub mod inflight;
pub mod keepalive;
mod ready;
pub mod sink;
pub mod stream;
pub mod time;
@ -11,7 +10,8 @@ pub mod timeout;
pub mod variant;
pub use self::extensions::Extensions;
pub use self::ready::Ready;
pub use ntex_service::util::{lazy, Lazy, Ready};
pub use bytes::{Buf, BufMut, Bytes, BytesMut};
pub use bytestring::ByteString;