Skip to main content

Service

Trait Service 

Source
pub trait Service<St, Req> {
    type Res;
    type Error;

    // Required method
    async fn call(
        &self,
        req: Req,
        ctx: Ctx<'_, Self, St>,
    ) -> Result<Self::Res, Self::Error>;

    // Provided methods
    fn bind(&self, ctx: BindCtx<'_>) { ... }
    fn ready(
        &self,
        ctx: Ctx<'_, Self, St>,
    ) -> impl Future<Output = Result<(), Self::Error>> { ... }
    fn shutdown(&self, ctx: Ctx<'_, Self, St>) -> impl Future<Output = ()> { ... }
    fn map<F, Res>(self, f: F) -> ServiceChain<Map<F, Self, Res>, St, Req>
       where Self: Sized,
             F: Fn(Self::Res) -> Res { ... }
    fn map_err<F, E>(self, f: F) -> ServiceChain<MapErr<F, Self, E>, St, Req>
       where Self: Sized,
             F: Fn(Self::Error) -> E { ... }
    fn and_then<Next, F>(
        self,
        f: F,
    ) -> ServiceChain<AndThen<Self, Next>, St, Req>
       where Self: Sized,
             Next: Service<St, Self::Res, Error = Self::Error>,
             F: IntoService<Next, St, Self::Res> { ... }
    fn pipeline(self, st: St) -> Pipeline<Req, Self::Res, Self::Error>
       where Self: Sized + 'static,
             St: 'static,
             Req: 'static { ... }
}
Expand description

An asynchronous operation from a request to a response.

A service receives requests and asynchronously produces responses. Conceptually, it is similar to:

ⓘ
async fn(Request) -> Result<Response, Error>

The request and pipeline-state types are generic parameters. The response and error types are associated types, allowing one service type to implement Service for multiple request types.

Methods take &self, so implementations that mutate internal state must use interior mutability such as Cell, RefCell, or a synchronization primitive when appropriate.

The same abstraction can represent client- and server-side operations. Services focus on transformation, making them straightforward to test and compose.

A service call requires a Ctx and therefore runs through a Pipeline or from another service. The pipeline coordinates readiness across a composed service chain before dispatching a request.


struct MyService;

impl Service<(), u8> for MyService {
    type Res = u64;
    type Error = Infallible;

    async fn call(&self, req: u8, ctx: Ctx<'_, Self>) -> Result<Self::Res, Self::Error> {
        Ok(req as u64)
    }
}

Simple services do not need a manual trait implementation. The example above can be expressed with fn_service:

let service = fn_service(|req: u8| async move {
    Ok::<_, Infallible>(u64::from(req))
});
let pipeline = Pipeline::new((), service);

assert_eq!(pipeline.call(10).await?, 10);

§Wrapping services

The default Self::bind, Self::ready, and Self::shutdown bodies are only suitable for leaf services. A wrapper that owns another service and implements only Self::call still compiles, but its child is never bound, child readiness errors and capacity limits are bypassed, child readiness notifications never invalidate the wrapper’s cached readiness, and the child is never shut down.

Prefer helpers that forward the whole lifecycle:

Otherwise implement all three methods: bind every child with BindCtx::bind, check each child with Ctx::ready, and shut each child down with Ctx::shutdown. A wrapper that adds its own readiness, such as a capacity limit, must also subscribe a ReadyNotifier in Self::bind and notify it on every change; waking a task does not invalidate cached success.

§Framework guide

Required Associated Types§

Source

type Res

Response produced by the service.

Source

type Error

Error produced while checking readiness or processing a request.

Required Methods§

Source

async fn call( &self, req: Req, ctx: Ctx<'_, Self, St>, ) -> Result<Self::Res, Self::Error>

Processes a request and asynchronously returns the response.

The enclosing pipeline checks readiness before invoking this method. Implementations should not call their own ready method. A composed service can use Ctx::call to call an inner service using the closest upstream readiness cache. A service wrapped with ready() can be called directly to check its own cache instead.

Provided Methods§

Source

fn bind(&self, ctx: BindCtx<'_>)

Initializes the service within a Pipeline.

Called during pipeline construction or Ctx::create, before runtime operations on the new service.

The default is suitable for leaves without notification sources. Composites must bind every existing child, and services with changing readiness must subscribe to all their sources here. Lazily created children must be initialized through Ctx::create, which binds them explicitly before use. Register reusable ReadyCallback handles with BindCtx::on_notify to observe notifications reaching the service’s scope.

Binding is synchronous. Shared services can be bound to multiple parents; implementations must support repeated binding. forward! forwards to one or several service fields. Register Pipeline fields with Pipeline::bind_to. Ordinary readiness checks, calls, and shutdown do not add dependencies.

Source

fn ready( &self, ctx: Ctx<'_, Self, St>, ) -> impl Future<Output = Result<(), Self::Error>>

Waits until the service is ready to process a request.

If the service is at capacity, the returned future remains pending until capacity becomes available.

Pipeline readiness is coordinated across all services in a composed chain. A request is dispatched only when the chain is ready.

A Pipeline or ReadyBinding caches success until a subscribed ReadyNotifier invalidates it; calls do not consume that success. Subscribe in Self::bind and notify on every readiness-changing transition, including consuming or releasing capacity and external failures, before another caller can use stale cached readiness. A task wake schedules a pending check but does not invalidate a cached success. Services must not rely on this method being polled on every call to drive background progress.

Readiness checks and their wake sources run on the pipeline’s thread. This local-only requirement does not apply to task wakers supplied to Self::call or Self::shutdown.

Readiness may inspect Ctx::st, but it describes the shared gate, not a reservation for one request or state value. State-taking pipeline handles share the same cache; independent gates need separate pipelines or service bindings.

Source

fn shutdown(&self, ctx: Ctx<'_, Self, St>) -> impl Future<Output = ()>

Shuts down the service.

Returns when the service has been properly shut down.

Source

fn map<F, Res>(self, f: F) -> ServiceChain<Map<F, Self, Res>, St, Req>
where Self: Sized, F: Fn(Self::Res) -> Res,

Maps this service’s output to a different type, returning a new service.

This is similar to Option::map or Iterator::map, changing the output type of the underlying service.

This function consumes the original service and returns a wrapped version, following the pattern of standard library map methods.

Source

fn map_err<F, E>(self, f: F) -> ServiceChain<MapErr<F, Self, E>, St, Req>
where Self: Sized, F: Fn(Self::Error) -> E,

Maps this service’s error to a different type, returning a new service.

This is similar to Result::map_err, changing the error type of the underlying service. It is useful, for example, to ensure multiple services have the same error type.

This function consumes the original service and returns a wrapped version.

Source

fn and_then<Next, F>(self, f: F) -> ServiceChain<AndThen<Self, Next>, St, Req>
where Self: Sized, Next: Service<St, Self::Res, Error = Self::Error>, F: IntoService<Next, St, Self::Res>,

Calls another service after this service completes successfully.

The first service’s response becomes the second service’s request. If the first service returns an error, the second service is not called.

Source

fn pipeline(self, st: St) -> Pipeline<Req, Self::Res, Self::Error>
where Self: Sized + 'static, St: 'static, Req: 'static,

Wraps this service and its state in a Pipeline.

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety".

Implementations on Foreign Types§

Source§

impl<S, St, Req> Service<St, Req> for &S
where S: Service<St, Req>,

Source§

type Res = <S as Service<St, Req>>::Res

Source§

type Error = <S as Service<St, Req>>::Error

Source§

fn bind(&self, ctx: BindCtx<'_>)

Source§

fn ready( &self, ctx: Ctx<'_, Self, St>, ) -> impl Future<Output = Result<(), S::Error>>

Source§

fn call( &self, req: Req, ctx: Ctx<'_, Self, St>, ) -> impl Future<Output = Result<S::Res, S::Error>>

Source§

fn shutdown(&self, ctx: Ctx<'_, Self, St>) -> impl Future<Output = ()>

Source§

impl<S, St, Req> Service<St, Req> for Box<S>
where S: Service<St, Req>,

Source§

type Res = <S as Service<St, Req>>::Res

Source§

type Error = <S as Service<St, Req>>::Error

Source§

fn bind(&self, ctx: BindCtx<'_>)

Source§

fn ready( &self, ctx: Ctx<'_, Self, St>, ) -> impl Future<Output = Result<(), S::Error>>

Source§

fn call( &self, req: Req, ctx: Ctx<'_, Self, St>, ) -> impl Future<Output = Result<S::Res, S::Error>>

Source§

fn shutdown(&self, ctx: Ctx<'_, Self, St>) -> impl Future<Output = ()>

Source§

impl<S, St, Req> Service<St, Req> for Rc<S>
where S: Service<St, Req>,

Source§

type Res = <S as Service<St, Req>>::Res

Source§

type Error = <S as Service<St, Req>>::Error

Source§

fn bind(&self, ctx: BindCtx<'_>)

Source§

fn ready( &self, ctx: Ctx<'_, Self, St>, ) -> impl Future<Output = Result<(), S::Error>>

Source§

fn call( &self, req: Req, ctx: Ctx<'_, Self, St>, ) -> impl Future<Output = Result<S::Res, S::Error>>

Source§

fn shutdown(&self, ctx: Ctx<'_, Self, St>) -> impl Future<Output = ()>

Implementors§

Source§

impl<A, B, St, Req> Service<St, Req> for AndThen<A, B>
where A: Service<St, Req>, B: Service<St, A::Res, Error = A::Error>,

Source§

type Res = <B as Service<St, <A as Service<St, Req>>::Res>>::Res

Source§

type Error = <A as Service<St, Req>>::Error

Source§

impl<A, B, St, Req> Service<St, Req> for Then<A, B>
where A: Service<St, Req>, B: Service<St, Result<A::Res, A::Error>, Error = A::Error>,

Source§

type Res = <B as Service<St, Result<<A as Service<St, Req>>::Res, <A as Service<St, Req>>::Error>>>::Res

Source§

type Error = <B as Service<St, Result<<A as Service<St, Req>>::Res, <A as Service<St, Req>>::Error>>>::Error

Source§

impl<F, S, St, Req, E> Service<St, Req> for MapErr<F, S, E>
where S: Service<St, Req>, F: Fn(S::Error) -> E,

Source§

type Res = <S as Service<St, Req>>::Res

Source§

type Error = E

Source§

impl<F, S, St, Req, Res> Service<St, Req> for Map<F, S, Res>
where S: Service<St, Req>, F: Fn(S::Res) -> Res,

Source§

type Res = Res

Source§

type Error = <S as Service<St, Req>>::Error

Source§

impl<F, St, Req, Err> Service<St, Req> for FnReadiness<F, Err>
where F: AsyncFn(&St) -> Result<(), Err> + Clone,

Source§

type Res = Req

Source§

type Error = Err

Source§

impl<F, St, Req, Err> Service<St, Req> for FnShutdown<F, Err>
where F: AsyncFnOnce(&St),

Source§

type Res = Req

Source§

type Error = Err

Source§

impl<F, St, Req, Res, Err> Service<St, Req> for FnService<F, Req, Res, Err>
where F: AsyncFn(Req) -> Result<Res, Err>,

Source§

type Res = Res

Source§

type Error = Err

Source§

impl<F, St, Req, Res, Err> Service<St, Req> for FnServiceSt<F, St, Req, Res, Err>
where F: AsyncFn(&St, Req) -> Result<Res, Err>,

Source§

type Res = Res

Source§

type Error = Err

Source§

impl<OtSt, S, St, Req> Service<OtSt, Req> for MapState<S, St>
where S: Service<St, Req>,

Source§

type Res = <S as Service<St, Req>>::Res

Source§

type Error = <S as Service<St, Req>>::Error

Source§

impl<S, St, Req, F, In, Out, Err> Service<St, In> for Apply<S, St, Req, F, In, Out, Err>
where S: Service<St, Req>, F: AsyncFn(In, &ApplyCtx<'_, S, St, Req>) -> Result<Out, Err>, Err: From<S::Error>,

Source§

type Res = Out

Source§

type Error = Err

Source§

impl<S, St, Req> Service<St, Req> for Ready<S>
where S: Service<St, Req>,

Source§

type Res = <S as Service<St, Req>>::Res

Source§

type Error = <S as Service<St, Req>>::Error

Source§

impl<S, St, Req> Service<St, Req> for ReadyBinding<S>
where S: Service<St, Req>,

Source§

type Res = <S as Service<St, Req>>::Res

Source§

type Error = <S as Service<St, Req>>::Error

Source§

impl<S: Service<St, Req>, St, Req> Service<St, Req> for ServiceChain<S, St, Req>

Source§

type Res = <S as Service<St, Req>>::Res

Source§

type Error = <S as Service<St, Req>>::Error

Source§

impl<St, Req, Res, Err, const WORDS: usize> Service<St, Req> for BoxService<St, Req, Res, Err, WORDS>

Source§

type Res = Res

Source§

type Error = Err