Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

use async trait to refactor the service #1

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions service-async/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ repository = "https://github.com/ihciah/service-async"
[dependencies]
param = { version = "0.1.2", path = "../param" }
futures-util = "0.3"
async-trait = "0"

[target.'cfg(unix)'.dev-dependencies]
monoio = { version = "0.1.5" }
Expand Down
72 changes: 72 additions & 0 deletions service-async/examples/async_trait_demo.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
#![feature(return_position_impl_trait_in_trait)]
#![feature(type_alias_impl_trait)]
// #![feature(async_fn_in_trait)]

// use std::{cell::UnsafeCell, future::Future, rc::Rc};

use async_trait::async_trait;

#[async_trait]
pub trait Service<Request>: Sync + Send {
type Response;
// /// Errors produced by the service.
type Error;
async fn call(&self, req: Request) -> Result<Self::Response, Self::Error>;
}

struct A;
#[async_trait]
impl Service<String> for A {
type Response = String;
type Error = ();

async fn call(&self, req: String) -> Result<Self::Response, Self::Error> {
Ok(format!("A -> {}", req))
}
}

struct B<S> {
inner: S,
}
#[async_trait]
impl<S> Service<String> for B<S>
where
S: Service<String, Response = String, Error = ()>,
{
type Response = String;
type Error = ();
async fn call(&self, req: String) -> Result<Self::Response, Self::Error> {
let req = format!("B -> {}", req);
self.inner.call(req).await
}
}

pub trait Layer<S> {
type Service;
fn layer(&self, inner: S) -> Self::Service;
}
struct LayerB;
impl<S> Layer<S> for LayerB
where
S: Service<String>,
{
type Service = B<S>;
fn layer(&self, inner: S) -> Self::Service {
B { inner }
}
}

#[monoio::main]
async fn main() {
let a = A;
let layer = LayerB;
let b = layer.layer(a);
let mut c = Vec::<Box<dyn Service<String, Response = String, Error = ()>>>::new();
c.push(Box::new(A));

let result = b.call(String::from("abcdfdssfd")).await;
println!("{:?}", result);
for d in c {
println!("d result: {:?}", d.call(String::from("abcd")).await)
}
}
60 changes: 25 additions & 35 deletions service-async/examples/demo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use std::{
sync::atomic::{AtomicUsize, Ordering},
};

use async_trait::async_trait;
use service_async::{
layer::{layer_fn, FactoryLayer},
stack::FactoryStack,
Expand All @@ -24,21 +25,17 @@ struct SvcA {
not_pass_flag: bool,
}

#[async_trait]
impl Service<()> for SvcA {
type Response = ();
type Error = Infallible;
type Future<'cx> = impl Future<Output = Result<Self::Response, Self::Error>> + 'cx
where
Self: 'cx;

fn call(&self, _req: ()) -> Self::Future<'_> {
async move {
println!(
"SvcA called! pass_flag = {}, not_pass_flag = {}",
self.pass_flag, self.not_pass_flag
);
Ok(())
}

async fn call(&self, _req: ()) -> Result<Self::Response, Self::Error> {
println!(
"SvcA called! pass_flag = {}, not_pass_flag = {}",
self.pass_flag, self.not_pass_flag
);
Ok(())
}
}

Expand Down Expand Up @@ -71,24 +68,20 @@ struct SvcB<T> {
inner: T,
}

#[async_trait]
impl<T> Service<usize> for SvcB<T>
where
T: Service<(), Error = Infallible>,
{
type Response = ();
type Error = Infallible;
type Future<'cx> = impl Future<Output = Result<Self::Response, Self::Error>> + 'cx
where
Self: 'cx;

fn call(&self, req: usize) -> Self::Future<'_> {
async move {
let old = self.counter.fetch_add(req, Ordering::AcqRel);
let new = old + req;
println!("SvcB called! {old}->{new}");
self.inner.call(()).await?;
Ok(())
}

async fn call(&self, req: usize) -> Result<Self::Response, Self::Error> {
let old = self.counter.fetch_add(req, Ordering::AcqRel);
let new = old + req;
println!("SvcB called! {old}->{new}");
self.inner.call(()).await?;
Ok(())
}
}

Expand Down Expand Up @@ -121,22 +114,19 @@ struct SvcC<T> {
inner: T,
}

#[async_trait]
impl<T, I> Service<I> for SvcC<T>
where
T: Service<I, Error = Infallible>,
I: Send + 'static,
{
type Response = ();
type Error = Infallible;
type Future<'cx> = impl Future<Output = Result<Self::Response, Self::Error>> + 'cx
where
Self: 'cx, I: 'cx;

fn call(&self, req: I) -> Self::Future<'_> {
async move {
println!("SvcC called!");
self.inner.call(req).await?;
Ok(())
}
async fn call(&self, req: I) -> Result<Self::Response, Self::Error> {
println!("SvcC called!");
self.inner.call(req).await?;
Ok(())
}
}

Expand Down Expand Up @@ -227,8 +217,8 @@ async fn main() {
new_svc.call(10).await.unwrap();

// also, BoxService can use it in this way too
let new_svc = new_stack.make_via_ref(boxed_svc.downcast_ref()).unwrap();
new_svc.call(10).await.unwrap();
// let new_svc = new_stack.make_via_ref(Some(boxed_svc)).unwrap();
// new_svc.call(10).await.unwrap();

// to make it more flexible, we can even make the factory a boxed type.
// so we can insert different layers and get a same type.
Expand Down
71 changes: 33 additions & 38 deletions service-async/src/boxed.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,13 @@ use std::{
marker::PhantomData,
};

use async_trait::async_trait;
pub use futures_util::future::LocalBoxFuture;

use crate::{MakeService, Service};

pub struct BoxedService<Request, Response, E> {
svc: *const (),
type_id: TypeId,
vtable: ServiceVtable<Request, Response, E>,
svc: Box<dyn Service<Request, Response = Response, Error = E>>,
}

impl<Request, Response, E> BoxedService<Request, Response, E> {
Expand All @@ -19,51 +18,47 @@ impl<Request, Response, E> BoxedService<Request, Response, E> {
S: Service<Request, Response = Response, Error = E> + 'static,
Request: 'static,
{
let type_id = s.type_id();
let svc = Box::into_raw(Box::new(s)) as *const ();
BoxedService {
svc,
type_id,
vtable: ServiceVtable {
call: call::<Request, S>,
drop: drop::<S>,
},
}
BoxedService { svc: Box::new(s) }
}

pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
let t = TypeId::of::<T>();
if self.type_id == t {
Some(unsafe { self.downcast_ref_unchecked() })
} else {
None
}
pub fn get_inner<S>(&self) -> &dyn Service<Request, Response = Response, Error = E> {
self.svc.as_ref()
}

/// # Safety
/// If you are sure the inner type is T, you can downcast it.
pub unsafe fn downcast_ref_unchecked<T: Any>(&self) -> &T {
&*(self.svc as *const () as *const T)
}
// pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
// let t = TypeId::of::<T>();
// if self.type_id == t {
// Some(unsafe { self.downcast_ref_unchecked() })
// } else {
// None
// }
// }

// /// # Safety
// /// If you are sure the inner type is T, you can downcast it.
// pub unsafe fn downcast_ref_unchecked<T: Any>(&self) -> &T {
// &*(self.svc as *const () as *const T)
// }
}

impl<Request, Response, E> Drop for BoxedService<Request, Response, E> {
#[inline]
fn drop(&mut self) {
unsafe { (self.vtable.drop)(self.svc) };
}
}
// impl<Request, Response, E> Drop for BoxedService<Request, Response, E> {
// #[inline]
// fn drop(&mut self) {
// unsafe { (self.vtable.drop)(self.svc) };
// }
// }

impl<Request, Response, E> Service<Request> for BoxedService<Request, Response, E> {
#[async_trait]
impl<Request, Response, E> Service<Request> for BoxedService<Request, Response, E>
where
Request: Send,
{
type Response = Response;
type Error = E;
type Future<'cx> = LocalBoxFuture<'cx, Result<Response, E>>
where
Self: 'cx, Request: 'cx;

#[inline]
fn call(&self, req: Request) -> Self::Future<'_> {
unsafe { (self.vtable.call)(self.svc, req) }
async fn call(&self, req: Request) -> Result<Self::Response, Self::Error> {
self.svc.call(req).await
}
}

Expand Down Expand Up @@ -140,7 +135,7 @@ where

fn make_via_ref(&self, old: Option<&Self::Service>) -> Result<Self::Service, Self::Error> {
let svc = match old {
Some(inner) => self.inner.make_via_ref(inner.downcast_ref())?,
Some(inner) => self.inner.make_via_ref(None)?,
None => self.inner.make()?,
};
Ok(svc.into_boxed())
Expand Down
14 changes: 7 additions & 7 deletions service-async/src/either.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
use std::{error::Error, fmt::Display, future::Future, pin::Pin};

use async_trait::async_trait;

use crate::{layer::FactoryLayer, MakeService, Service};

#[derive(Debug, Clone)]
Expand Down Expand Up @@ -65,23 +67,21 @@ where
}
}

#[async_trait]
impl<A, B, R> Service<R> for Either<A, B>
where
A: Service<R>,
B: Service<R, Response = A::Response, Error = A::Error>,
R: Send + 'static,
{
type Response = A::Response;
type Error = A::Error;
type Future<'cx> = Either<A::Future<'cx>, B::Future<'cx>>
where
Self: 'cx,
R: 'cx;

#[inline]
fn call(&self, req: R) -> Self::Future<'_> {
async fn call(&self, req: R) -> Result<Self::Response, Self::Error> {
match self {
Either::Left(s) => Either::Left(s.call(req)),
Either::Right(s) => Either::Right(s.call(req)),
Either::Left(s) => s.call(req).await,
Either::Right(s) => s.call(req).await,
}
}
}
Expand Down
33 changes: 22 additions & 11 deletions service-async/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,20 +15,31 @@ pub use map::MapTargetService;
mod boxed;
pub use boxed::{BoxService, BoxServiceFactory, BoxedService};

pub trait Service<Request> {
/// Responses given by the service.
// pub trait Service<Request> {
// /// Responses given by the service.
// type Response;
// /// Errors produced by the service.
// type Error;

// /// The future response value.
// type Future<'cx>: Future<Output = Result<Self::Response, Self::Error>>
// where
// Self: 'cx,
// Request: 'cx;

// /// Process the request and return the response asynchronously.
// fn call(&self, req: Request) -> Self::Future<'_>;
// }

use async_trait::async_trait;

#[async_trait]
pub trait Service<Request>: Sync + Send {
type Response;
/// Errors produced by the service.
// /// Errors produced by the service.
type Error;

/// The future response value.
type Future<'cx>: Future<Output = Result<Self::Response, Self::Error>>
where
Self: 'cx,
Request: 'cx;

/// Process the request and return the response asynchronously.
fn call(&self, req: Request) -> Self::Future<'_>;
async fn call(&self, req: Request) -> Result<Self::Response, Self::Error>;
}

pub trait MakeService {
Expand Down