Skip to content

Simplify Service Trait with Async Trait in Next Major Version #670

@cyborg42

Description

@cyborg42

The current Service trait is defined as:

pub trait Service<Req> {
    type Response;
    type Error;
    type Future: Future<Output = Result<Self::Response, Self::Error>>;

    fn poll_ready(&self, ctx: &mut task::Context<'_>) -> Poll<Result<(), Self::Error>>;
    fn call(&self, req: Req) -> Self::Future;
}

In the next major version, we could leverage async traits to simplify the trait definition and improve ergonomics. Proposed change:

pub trait Service<Req> {
    type Response;
    type Error;

    fn poll_ready(&self, ctx: &mut task::Context<'_>) -> Poll<Result<(), Self::Error>>;
    fn call(&self, req: Req) -> impl Future<Output = Result<Self::Response, Self::Error>>;
}

This allows implementations like:

struct MyMiddleware;

impl<Req> Service<Req> for MyMiddleware {
    type Response = ();
    type Error = ();
    
    fn poll_ready(&self, ctx: &mut task::Context<'_>) -> Poll<Result<(), Self::Error>> {
        todo!()
    }
    
    async fn call(&self, req: Req) -> Result<Self::Response, Self::Error> {
        todo!()
    }
}

Benefits:

  • Eliminates the need to define a Future associated type.
  • Simplifies implementation by using async fn directly.
  • Improves readability and maintainability.

We can also use async trait for ServiceFactory and Transform

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions