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:
fn_layerorapply_fnfor wrappers that only adapt calls;ntex::web::middleware::from_fnis the equivalent for web middleware.forward!for manual implementations with one or several service fields.Pipeline::bind_toinSelf::bindforPipelinefields.
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§
Required Methods§
Sourceasync fn call(
&self,
req: Req,
ctx: Ctx<'_, Self, St>,
) -> Result<Self::Res, Self::Error>
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§
Sourcefn bind(&self, ctx: BindCtx<'_>)
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.
Sourcefn ready(
&self,
ctx: Ctx<'_, Self, St>,
) -> impl Future<Output = Result<(), Self::Error>>
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.
Sourcefn shutdown(&self, ctx: Ctx<'_, Self, St>) -> impl Future<Output = ()>
fn shutdown(&self, ctx: Ctx<'_, Self, St>) -> impl Future<Output = ()>
Shuts down the service.
Returns when the service has been properly shut down.
Sourcefn map<F, Res>(self, f: F) -> ServiceChain<Map<F, Self, Res>, St, Req>
fn map<F, Res>(self, f: F) -> ServiceChain<Map<F, Self, Res>, St, Req>
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.
Sourcefn map_err<F, E>(self, f: F) -> ServiceChain<MapErr<F, Self, E>, St, Req>
fn map_err<F, E>(self, f: F) -> ServiceChain<MapErr<F, Self, E>, St, Req>
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.
Sourcefn and_then<Next, F>(self, f: F) -> ServiceChain<AndThen<Self, Next>, St, Req>
fn and_then<Next, F>(self, f: F) -> ServiceChain<AndThen<Self, Next>, St, Req>
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.
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety".
Implementations on Foreign Types§
§fn call(
&self,
req: A,
ctx: Ctx<'_, Connector<A, S>, SharedCfg>,
) -> impl Future<Output = Result<<Connector<A, S> as Service<SharedCfg, A>>::Res, <Connector<A, S> as Service<SharedCfg, A>>::Error>>
fn call( &self, req: A, ctx: Ctx<'_, Connector<A, S>, SharedCfg>, ) -> impl Future<Output = Result<<Connector<A, S> as Service<SharedCfg, A>>::Res, <Connector<A, S> as Service<SharedCfg, A>>::Error>>
Connects to an HTTP/2 server.