Skip to main content

tonic/
request.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 crate::metadata::{MetadataMap, MetadataValue};
26#[cfg(feature = "server")]
27use crate::transport::server::TcpConnectInfo;
28#[cfg(all(feature = "server", feature = "_tls-any"))]
29use crate::transport::server::TlsConnectInfo;
30use http::Extensions;
31#[cfg(feature = "server")]
32use std::net::SocketAddr;
33#[cfg(all(feature = "server", feature = "_tls-any"))]
34use std::sync::Arc;
35use std::time::Duration;
36
37#[cfg(all(feature = "server", feature = "_tls-any"))]
38use tokio_rustls::rustls::pki_types::CertificateDer;
39use tokio_stream::Stream;
40use tokio_util::sync::CancellationToken;
41
42/// A gRPC request and metadata from an RPC call.
43#[derive(Debug)]
44pub struct Request<T> {
45    metadata: MetadataMap,
46    message: T,
47    extensions: Extensions,
48}
49
50/// Trait implemented by RPC request types.
51///
52/// Types implementing this trait can be used as arguments to client RPC
53/// methods without explicitly wrapping them into `tonic::Request`s. The purpose
54/// is to make client calls slightly more convenient to write.
55///
56/// Tonic's code generation and blanket implementations handle this for you,
57/// so it is not necessary to implement this trait directly.
58///
59/// # Example
60///
61/// Given the following gRPC method definition:
62/// ```proto
63/// rpc GetFeature(Point) returns (Feature) {}
64/// ```
65///
66/// we can call `get_feature` in two equivalent ways:
67/// ```rust
68/// # pub struct Point {}
69/// # pub struct Client {}
70/// # impl Client {
71/// #   fn get_feature(&self, r: impl tonic::IntoRequest<Point>) {}
72/// # }
73/// # let client = Client {};
74/// use tonic::Request;
75///
76/// client.get_feature(Point {});
77/// client.get_feature(Request::new(Point {}));
78/// ```
79pub trait IntoRequest<T>: sealed::Sealed {
80    /// Wrap the input message `T` in a `tonic::Request`
81    fn into_request(self) -> Request<T>;
82}
83
84/// Trait implemented by RPC streaming request types.
85///
86/// Types implementing this trait can be used as arguments to client streaming
87/// RPC methods without explicitly wrapping them into `tonic::Request`s. The
88/// purpose is to make client calls slightly more convenient to write.
89///
90/// Tonic's code generation and blanket implementations handle this for you,
91/// so it is not necessary to implement this trait directly.
92///
93/// # Example
94///
95/// Given the following gRPC service method definition:
96/// ```proto
97/// rpc RecordRoute(stream Point) returns (RouteSummary) {}
98/// ```
99/// we can call `record_route` in two equivalent ways:
100///
101/// ```rust
102/// # #[derive(Clone)]
103/// # pub struct Point {};
104/// # pub struct Client {};
105/// # impl Client {
106/// #   fn record_route(&self, r: impl tonic::IntoStreamingRequest<Message = Point>) {}
107/// # }
108/// # let client = Client {};
109/// use tonic::Request;
110///
111/// let messages = vec![Point {}, Point {}];
112///
113/// client.record_route(Request::new(tokio_stream::iter(messages.clone())));
114/// client.record_route(tokio_stream::iter(messages));
115/// ```
116pub trait IntoStreamingRequest: sealed::Sealed {
117    /// The RPC request stream type
118    type Stream: Stream<Item = Self::Message> + Send + 'static;
119
120    /// The RPC request type
121    type Message;
122
123    /// Wrap the stream of messages in a `tonic::Request`
124    fn into_streaming_request(self) -> Request<Self::Stream>;
125}
126
127impl<T> Request<T> {
128    /// Create a new gRPC request.
129    ///
130    /// ```rust
131    /// # use tonic::Request;
132    /// # pub struct HelloRequest {
133    /// #   pub name: String,
134    /// # }
135    /// Request::new(HelloRequest {
136    ///    name: "Bob".into(),
137    /// });
138    /// ```
139    pub fn new(message: T) -> Self {
140        Request {
141            metadata: MetadataMap::new(),
142            message,
143            extensions: Extensions::new(),
144        }
145    }
146
147    /// Get a reference to the message
148    pub fn get_ref(&self) -> &T {
149        &self.message
150    }
151
152    /// Get a mutable reference to the message
153    pub fn get_mut(&mut self) -> &mut T {
154        &mut self.message
155    }
156
157    /// Get a reference to the custom request metadata.
158    pub fn metadata(&self) -> &MetadataMap {
159        &self.metadata
160    }
161
162    /// Get a mutable reference to the request metadata.
163    pub fn metadata_mut(&mut self) -> &mut MetadataMap {
164        &mut self.metadata
165    }
166
167    /// Consumes `self`, returning the message
168    pub fn into_inner(self) -> T {
169        self.message
170    }
171
172    /// Consumes `self` returning the parts of the request.
173    pub fn into_parts(self) -> (MetadataMap, Extensions, T) {
174        (self.metadata, self.extensions, self.message)
175    }
176
177    /// Create a new gRPC request from metadata, extensions and message.
178    pub fn from_parts(metadata: MetadataMap, extensions: Extensions, message: T) -> Self {
179        Self {
180            metadata,
181            extensions,
182            message,
183        }
184    }
185
186    pub(crate) fn from_http_parts(parts: http::request::Parts, message: T) -> Self {
187        Request {
188            metadata: MetadataMap::from_headers(parts.headers),
189            message,
190            extensions: parts.extensions,
191        }
192    }
193
194    /// Convert an HTTP request to a gRPC request
195    pub fn from_http(http: http::Request<T>) -> Self {
196        let (parts, message) = http.into_parts();
197        Request::from_http_parts(parts, message)
198    }
199
200    pub(crate) fn into_http(
201        self,
202        uri: http::Uri,
203        method: http::Method,
204        version: http::Version,
205        sanitize_headers: SanitizeHeaders,
206    ) -> http::Request<T> {
207        let mut request = http::Request::new(self.message);
208
209        *request.version_mut() = version;
210        *request.method_mut() = method;
211        *request.uri_mut() = uri;
212        *request.headers_mut() = match sanitize_headers {
213            SanitizeHeaders::Yes => self.metadata.into_sanitized_headers(),
214            SanitizeHeaders::No => self.metadata.into_headers(),
215        };
216        *request.extensions_mut() = self.extensions;
217
218        request
219    }
220
221    #[doc(hidden)]
222    pub fn map<F, U>(self, f: F) -> Request<U>
223    where
224        F: FnOnce(T) -> U,
225    {
226        let message = f(self.message);
227
228        Request {
229            metadata: self.metadata,
230            message,
231            extensions: self.extensions,
232        }
233    }
234
235    /// Get the local address of this connection.
236    ///
237    /// This will return `None` if the `IO` type used
238    /// does not implement `Connected` or when using a unix domain socket.
239    /// This currently only works on the server side.
240    #[cfg(feature = "server")]
241    pub fn local_addr(&self) -> Option<SocketAddr> {
242        let addr = self
243            .extensions()
244            .get::<TcpConnectInfo>()
245            .and_then(|i| i.local_addr());
246
247        #[cfg(feature = "_tls-any")]
248        let addr = addr.or_else(|| {
249            self.extensions()
250                .get::<TlsConnectInfo<TcpConnectInfo>>()
251                .and_then(|i| i.get_ref().local_addr())
252        });
253
254        addr
255    }
256
257    /// Get the remote address of this connection.
258    ///
259    /// This will return `None` if the `IO` type used
260    /// does not implement `Connected` or when using a unix domain socket.
261    /// This currently only works on the server side.
262    #[cfg(feature = "server")]
263    pub fn remote_addr(&self) -> Option<SocketAddr> {
264        let addr = self
265            .extensions()
266            .get::<TcpConnectInfo>()
267            .and_then(|i| i.remote_addr());
268
269        #[cfg(feature = "_tls-any")]
270        let addr = addr.or_else(|| {
271            self.extensions()
272                .get::<TlsConnectInfo<TcpConnectInfo>>()
273                .and_then(|i| i.get_ref().remote_addr())
274        });
275
276        addr
277    }
278
279    /// Get the peer certificates of the connected client.
280    ///
281    /// This is used to fetch the certificates from the TLS session
282    /// and is mostly used for mTLS. This currently only returns
283    /// `Some` on the server side of the `transport` server with
284    /// TLS enabled connections.
285    #[cfg(all(feature = "server", feature = "_tls-any"))]
286    pub fn peer_certs(&self) -> Option<Arc<Vec<CertificateDer<'static>>>> {
287        self.extensions()
288            .get::<TlsConnectInfo<TcpConnectInfo>>()
289            .and_then(|i| i.peer_certs())
290    }
291
292    /// Set the max duration the request is allowed to take.
293    ///
294    /// Requires the server to support the `grpc-timeout` metadata, which Tonic does.
295    ///
296    /// The duration will be formatted according to [the spec] and use the most precise unit
297    /// possible.
298    ///
299    /// Example:
300    ///
301    /// ```rust
302    /// use std::time::Duration;
303    /// use tonic::Request;
304    ///
305    /// let mut request = Request::new(());
306    ///
307    /// request.set_timeout(Duration::from_secs(30));
308    ///
309    /// let value = request.metadata().get("grpc-timeout").unwrap();
310    ///
311    /// assert_eq!(
312    ///     value,
313    ///     // equivalent to 30 seconds
314    ///     "30000000u"
315    /// );
316    /// ```
317    ///
318    /// [the spec]: https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md
319    pub fn set_timeout(&mut self, deadline: Duration) {
320        let value: MetadataValue<_> = duration_to_grpc_timeout(deadline).parse().unwrap();
321        self.metadata_mut()
322            .insert(crate::metadata::GRPC_TIMEOUT_HEADER, value);
323    }
324
325    /// Returns a reference to the associated extensions.
326    pub fn extensions(&self) -> &Extensions {
327        &self.extensions
328    }
329
330    /// Returns a mutable reference to the associated extensions.
331    ///
332    /// # Example
333    ///
334    /// Extensions can be set in interceptors:
335    ///
336    /// ```no_run
337    /// use tonic::{Request, Status};
338    ///
339    /// #[derive(Clone)] // Extensions must be Clone
340    /// struct MyExtension {
341    ///     some_piece_of_data: String,
342    /// }
343    ///
344    /// fn intercept(mut request: Request<()>) -> Result<Request<()>, Status> {
345    ///     request.extensions_mut().insert(MyExtension {
346    ///         some_piece_of_data: "foo".to_string(),
347    ///     });
348    ///
349    ///     Ok(request)
350    /// }
351    /// ```
352    ///
353    /// And picked up by RPCs:
354    ///
355    /// ```no_run
356    /// use tonic::{async_trait, Status, Request, Response};
357    /// #
358    /// # struct Output {}
359    /// # struct Input;
360    /// # struct MyService;
361    /// # struct MyExtension;
362    /// # #[async_trait]
363    /// # trait TestService {
364    /// #     async fn handler(&self, req: Request<Input>) -> Result<Response<Output>, Status>;
365    /// # }
366    ///
367    /// #[async_trait]
368    /// impl TestService for MyService {
369    ///     async fn handler(&self, req: Request<Input>) -> Result<Response<Output>, Status> {
370    ///         let value: &MyExtension = req.extensions().get::<MyExtension>().unwrap();
371    ///
372    ///         Ok(Response::new(Output {}))
373    ///     }
374    /// }
375    /// ```
376    pub fn extensions_mut(&mut self) -> &mut Extensions {
377        &mut self.extensions
378    }
379
380    /// Get a cancellation handle for this request.
381    ///
382    /// Cancellation is only supported on the client side. Calling `cancel` on
383    /// the handle will abort the request by sending an HTTP/2 RST_STREAM.
384    pub fn cancellation_handle(&mut self) -> CancellationHandle {
385        self.extensions
386            .get_or_insert(CancellationHandle {
387                token: CancellationToken::new(),
388            })
389            .clone()
390    }
391
392    pub(crate) fn remove_cancellation_handle(&mut self) -> Option<CancellationHandle> {
393        self.extensions_mut().remove()
394    }
395}
396
397impl<T> IntoRequest<T> for T {
398    fn into_request(self) -> Request<Self> {
399        Request::new(self)
400    }
401}
402
403impl<T> IntoRequest<T> for Request<T> {
404    fn into_request(self) -> Request<T> {
405        self
406    }
407}
408
409impl<T> IntoStreamingRequest for T
410where
411    T: Stream + Send + 'static,
412{
413    type Stream = T;
414    type Message = T::Item;
415
416    fn into_streaming_request(self) -> Request<Self> {
417        Request::new(self)
418    }
419}
420
421impl<T> IntoStreamingRequest for Request<T>
422where
423    T: Stream + Send + 'static,
424{
425    type Stream = T;
426    type Message = T::Item;
427
428    fn into_streaming_request(self) -> Self {
429        self
430    }
431}
432
433impl<T> sealed::Sealed for T {}
434
435mod sealed {
436    pub trait Sealed {}
437}
438
439fn duration_to_grpc_timeout(duration: Duration) -> String {
440    fn try_format<T: Into<u128>>(
441        duration: Duration,
442        unit: char,
443        convert: impl FnOnce(Duration) -> T,
444    ) -> Option<String> {
445        // The gRPC spec specifies that the timeout most be at most 8 digits. So this is the largest a
446        // value can be before we need to use a bigger unit.
447        let max_size: u128 = 99_999_999; // exactly 8 digits
448
449        let value = convert(duration).into();
450        if value > max_size {
451            None
452        } else {
453            Some(format!("{value}{unit}"))
454        }
455    }
456
457    // pick the most precise unit that is less than or equal to 8 digits as per the gRPC spec
458    try_format(duration, 'n', |d| d.as_nanos())
459        .or_else(|| try_format(duration, 'u', |d| d.as_micros()))
460        .or_else(|| try_format(duration, 'm', |d| d.as_millis()))
461        .or_else(|| try_format(duration, 'S', |d| d.as_secs()))
462        .or_else(|| try_format(duration, 'M', |d| d.as_secs() / 60))
463        .or_else(|| {
464            try_format(duration, 'H', |d| {
465                let minutes = d.as_secs() / 60;
466                minutes / 60
467            })
468        })
469        // duration has to be more than 11_415 years for this to happen
470        .expect("duration is unrealistically large")
471}
472
473/// When converting a `tonic::Request` into a `http::Request` should reserved
474/// headers be removed?
475pub(crate) enum SanitizeHeaders {
476    Yes,
477    No,
478}
479
480/// A handle that allows triggering the cancellation of an outbound request
481/// stream.
482///
483/// This handle can be stored by the user and invoked to abort the request.
484///
485/// Cancellation is only supported on the client side.
486#[derive(Debug, Clone)]
487pub struct CancellationHandle {
488    token: CancellationToken,
489}
490
491impl CancellationHandle {
492    /// Cancel the stream.
493    ///
494    /// This will result in the outbound stream getting cancelled with an
495    /// RST_STREAM frame, if it hasn't gracefully closed.
496    ///
497    /// Consumes `self` to ensure cancellation is only requested once.
498    pub fn cancel(self) {
499        self.token.cancel();
500    }
501
502    pub(crate) fn into_token(self) -> CancellationToken {
503        self.token
504    }
505}
506
507#[cfg(test)]
508mod tests {
509    use super::*;
510    use crate::metadata::{MetadataKey, MetadataValue};
511
512    use http::Uri;
513
514    #[test]
515    fn reserved_headers_are_excluded() {
516        let mut r = Request::new(1);
517
518        for header in &MetadataMap::GRPC_RESERVED_HEADERS {
519            r.metadata_mut().insert(
520                MetadataKey::unchecked_from_header_name(header.clone()),
521                MetadataValue::from_static("invalid"),
522            );
523        }
524
525        let http_request = r.into_http(
526            Uri::default(),
527            http::Method::POST,
528            http::Version::HTTP_2,
529            SanitizeHeaders::Yes,
530        );
531        assert!(http_request.headers().is_empty());
532    }
533
534    #[test]
535    fn preserves_user_agent() {
536        let mut r = Request::new(1);
537
538        r.metadata_mut().insert(
539            MetadataKey::from_static("user-agent"),
540            MetadataValue::from_static("Custom/1.2.3"),
541        );
542
543        let http_request = r.into_http(
544            Uri::default(),
545            http::Method::POST,
546            http::Version::HTTP_2,
547            SanitizeHeaders::Yes,
548        );
549        let user_agent = http_request.headers().get("user-agent").unwrap();
550        assert_eq!(user_agent, "Custom/1.2.3");
551    }
552
553    #[test]
554    fn duration_to_grpc_timeout_less_than_second() {
555        let timeout = Duration::from_millis(500);
556        let value = duration_to_grpc_timeout(timeout);
557        assert_eq!(value, format!("{}u", timeout.as_micros()));
558    }
559
560    #[test]
561    fn duration_to_grpc_timeout_more_than_second() {
562        let timeout = Duration::from_secs(30);
563        let value = duration_to_grpc_timeout(timeout);
564        assert_eq!(value, format!("{}u", timeout.as_micros()));
565    }
566
567    #[test]
568    fn duration_to_grpc_timeout_a_very_long_time() {
569        let one_hour = Duration::from_secs(60 * 60);
570        let value = duration_to_grpc_timeout(one_hour);
571        assert_eq!(value, format!("{}m", one_hour.as_millis()));
572    }
573
574    #[test]
575    fn test_cancellation() {
576        let mut req = Request::new(());
577        let handle = req.cancellation_handle();
578
579        let token = req.cancellation_handle().into_token();
580
581        assert!(!token.is_cancelled());
582
583        handle.cancel();
584
585        assert!(token.is_cancelled());
586    }
587
588    #[test]
589    fn test_cancellation_clone() {
590        let mut req = Request::new(());
591        let handle1 = req.cancellation_handle();
592        let handle2 = req.cancellation_handle();
593
594        let token = req.cancellation_handle().into_token();
595
596        assert!(!token.is_cancelled());
597
598        handle1.cancel();
599
600        assert!(token.is_cancelled());
601        assert!(handle2.into_token().is_cancelled());
602    }
603}