tonic/client/service.rs
1/*
2 *
3 * Copyright 2025 gRPC authors.
4 *
5 * Permission is hereby granted, free of charge, to any person obtaining a copy
6 * of this software and associated documentation files (the "Software"), to
7 * deal in the Software without restriction, including without limitation the
8 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
9 * sell copies of the Software, and to permit persons to whom the Software is
10 * furnished to do so, subject to the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be included in
13 * all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21 * IN THE SOFTWARE.
22 *
23 */
24
25use http_body::Body;
26use std::future::Future;
27use std::task::{Context, Poll};
28use tower_service::Service;
29
30/// Definition of the gRPC trait alias for [`tower_service`].
31///
32/// This trait enforces that all tower services provided to [`Grpc`] implements
33/// the correct traits.
34///
35/// [`Grpc`]: ../client/struct.Grpc.html
36/// [`tower_service`]: https://docs.rs/tower-service
37pub trait GrpcService<ReqBody> {
38 /// Responses body given by the service.
39 type ResponseBody: Body;
40 /// Errors produced by the service.
41 type Error: Into<crate::BoxError>;
42 /// The future response value.
43 type Future: Future<Output = Result<http::Response<Self::ResponseBody>, Self::Error>>;
44
45 /// Returns `Ready` when the service is able to process requests.
46 ///
47 /// Reference [`Service::poll_ready`].
48 fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>>;
49
50 /// Process the request and return the response asynchronously.
51 ///
52 /// Reference [`Service::call`].
53 fn call(&mut self, request: http::Request<ReqBody>) -> Self::Future;
54}
55
56impl<T, ReqBody, ResBody> GrpcService<ReqBody> for T
57where
58 T: Service<http::Request<ReqBody>, Response = http::Response<ResBody>>,
59 T::Error: Into<crate::BoxError>,
60 ResBody: Body,
61 <ResBody as Body>::Error: Into<crate::BoxError>,
62{
63 type ResponseBody = ResBody;
64 type Error = T::Error;
65 type Future = T::Future;
66
67 fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
68 Service::poll_ready(self, cx)
69 }
70
71 fn call(&mut self, request: http::Request<ReqBody>) -> Self::Future {
72 Service::call(self, request)
73 }
74}