Skip to main content

encore/services/clients/
grpc.rs

1//! Call types for generated gRPC service clients, backed by pooled `tonic`
2//! channels (one per base URL).
3//!
4//! Calls speak gRPC over HTTP/2: cleartext HTTP/2 (`h2c` with prior knowledge)
5//! for `http://` base URLs, and TLS (ALPN `h2`, trusting system roots or
6//! `SSL_CERT_FILE`) for `https://` base URLs.
7//!
8//! Call timeouts are propagated as `grpc-timeout` deadlines and enforced across
9//! the entire call, including connection establishment and reading every
10//! message on a stream. Connection attempts also time out after
11//! [`CONNECT_TIMEOUT`] even when no call timeout is set.
12//!
13//! Connection failures (refused, reset, dropped, or non-HTTP/2 peers) return
14//! [`ErrCode::Unavailable`]. Non-gRPC HTTP responses (such as a proxy
15//! `502 Bad Gateway`) are mapped to the standard gRPC error code for their HTTP
16//! status and preserve that status. Decoded `google.rpc.Status` details from
17//! the service are exposed in [`CallError::grpc_details`].
18
19use std::collections::HashMap;
20use std::fmt;
21use std::future::{Future, IntoFuture};
22use std::marker::PhantomData;
23use std::pin::Pin;
24use std::sync::atomic::{AtomicBool, Ordering};
25use std::sync::{Arc, Mutex};
26use std::task::{Context, Poll};
27use std::time::{Duration, Instant};
28
29use futures_core::Stream;
30use http_body::Body as _;
31use tonic::body::Body;
32use tonic::client::Grpc;
33use tonic::codegen::http::uri::PathAndQuery;
34use tonic::metadata::MetadataMap;
35use tonic::transport::{Channel, ClientTlsConfig, Endpoint};
36use tonic_prost::ProstCodec;
37use tower_layer::Layer;
38use tower_service::Service;
39
40use crate::opentelemetry::trace::FutureExt as _;
41
42use super::{base_url_of, invalid_header, CallError, Settings};
43use crate::services::{self, Propagate, PropagateLayer};
44use crate::ErrCode;
45
46/// A call's future.
47type Sending<'c, T> = Pin<Box<dyn Future<Output = Result<T, CallError>> + Send + 'c>>;
48
49type BoxError = Box<dyn std::error::Error + Send + Sync>;
50
51/// Maximum duration for establishing a TCP connection and completing the TLS
52/// handshake to a gRPC service.
53pub const CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
54
55/// How many channels are kept, each for a base URL: past it, the one used
56/// longest ago is dropped.
57const MAX_CHANNELS: usize = 64;
58
59/// How long a channel no call has used is kept.
60const IDLE_CHANNEL: Duration = Duration::from_secs(5 * 60);
61
62/// How much of an answer that is not gRPC's is read for its message.
63const MAX_ERROR_BODY: usize = 4096;
64
65/// What every kind of call holds: where it goes, and its settings.
66struct Call<'c> {
67    service: &'c services::Client,
68    client: &'c Settings,
69    settings: Settings,
70    path: &'static str,
71}
72
73/// A call ready to send.
74struct Prepared<T> {
75    /// The channel it goes over.
76    grpc: Grpc<Watched>,
77    /// The request it sends its message or messages in.
78    request: tonic::Request<T>,
79    /// When it times out.
80    deadline: Option<Instant>,
81    /// What it has heard from the service.
82    heard: Arc<Heard>,
83}
84
85impl Call<'_> {
86    /// The call, sending `message`.
87    fn prepare<T>(&self, message: T) -> Result<Prepared<T>, CallError> {
88        let settings = self.settings.under(self.client);
89        let heard = Arc::new(Heard::default());
90        let grpc = grpc(base_url_of(self.service, &settings)?, &heard)?;
91        let mut request = tonic::Request::from_parts(
92            metadata(&settings.headers)?,
93            tonic::Extensions::default(),
94            message,
95        );
96        let deadline = deadline(&mut request, settings.limit());
97        Ok(Prepared {
98            grpc,
99            request,
100            deadline,
101            heard,
102        })
103    }
104
105    fn path(&self) -> PathAndQuery {
106        PathAndQuery::from_static(self.path)
107    }
108}
109
110/// The metadata a call with `headers` sends: each a header, but for one
111/// whose name ends in `-bin`, binary metadata, whose value must be base64,
112/// as gRPC sends it. A header replaces one of the same name before it.
113fn metadata(headers: &[(String, String)]) -> Result<MetadataMap, CallError> {
114    let mut map = http::HeaderMap::new();
115    for (name, value) in headers {
116        let key = http::HeaderName::from_bytes(name.to_ascii_lowercase().as_bytes())
117            .map_err(|e| invalid_header(name, e))?;
118        let value = http::HeaderValue::from_str(value).map_err(|e| invalid_header(name, e))?;
119        map.insert(key, value);
120    }
121    let metadata = MetadataMap::from_headers(map);
122    for (name, _) in headers {
123        let name = name.to_ascii_lowercase();
124        if !name.ends_with("-bin") {
125            continue;
126        }
127        if let Some(Err(err)) = metadata.get_bin(name.as_str()).map(|v| v.to_bytes()) {
128            return Err(invalid_header(
129                &name,
130                format_args!("binary metadata is sent base64-encoded: {err}"),
131            ));
132        }
133    }
134    Ok(metadata)
135}
136
137/// The client calls to `base` go over: the channel for `base`, which tells
138/// the app's services from others by its origin, noting what the call hears
139/// in `heard`.
140fn grpc(base: &str, heard: &Arc<Heard>) -> Result<Grpc<Watched>, CallError> {
141    static CHANNELS: Mutex<Channels<Channel>> = Mutex::new(Channels::new());
142    let origin: http::Uri = base.parse().map_err(|e| invalid_base(base, e))?;
143    let channel =
144        CHANNELS
145            .lock()
146            .unwrap_or_else(|e| e.into_inner())
147            .get(base, Instant::now(), || connect(base, &origin))?;
148    Ok(Grpc::with_origin(
149        Watched {
150            inner: PropagateLayer.layer(channel),
151            heard: heard.clone(),
152        },
153        origin,
154    ))
155}
156
157/// The error a base URL a call cannot be sent to is.
158fn invalid_base(base: &str, err: impl fmt::Display) -> CallError {
159    CallError::failed(
160        ErrCode::InvalidArgument,
161        format!("invalid base URL {base:?}: {err}"),
162    )
163}
164
165/// The channels kept, by base URL, with when a call last used each. One that
166/// no call has used for [`IDLE_CHANNEL`] is dropped, as is the one used
167/// longest ago when [`MAX_CHANNELS`] are kept: a call holding it keeps it
168/// until it ends.
169struct Channels<C> {
170    kept: Option<HashMap<String, (C, Instant)>>,
171}
172
173impl<C: Clone> Channels<C> {
174    const fn new() -> Self {
175        Channels { kept: None }
176    }
177
178    /// The channel for `base` at `now`: the one kept, or a new one, which
179    /// `connect` makes.
180    fn get(
181        &mut self,
182        base: &str,
183        now: Instant,
184        connect: impl FnOnce() -> Result<C, CallError>,
185    ) -> Result<C, CallError> {
186        let kept = self.kept.get_or_insert_with(HashMap::new);
187        kept.retain(|_, (_, used)| now.saturating_duration_since(*used) < IDLE_CHANNEL);
188        if let Some((channel, used)) = kept.get_mut(base) {
189            *used = now;
190            return Ok(channel.clone());
191        }
192        let channel = connect()?;
193        if kept.len() >= MAX_CHANNELS {
194            let oldest = kept
195                .iter()
196                .min_by_key(|(_, (_, used))| *used)
197                .map(|(base, _)| base.clone());
198            if let Some(oldest) = oldest {
199                kept.remove(&oldest);
200            }
201        }
202        kept.insert(base.to_string(), (channel.clone(), now));
203        Ok(channel)
204    }
205}
206
207/// A channel to `base`, which connects when a call first needs it: in the
208/// clear to an `http://` URL, with TLS to an `https://` one.
209fn connect(base: &str, origin: &http::Uri) -> Result<Channel, CallError> {
210    let mut endpoint = Endpoint::from_shared(base.to_string())
211        .map_err(|e| invalid_base(base, e))?
212        .connect_timeout(CONNECT_TIMEOUT);
213    match origin.scheme_str() {
214        Some("http") => {}
215        Some("https") => {
216            let tls = ClientTlsConfig::new()
217                .with_native_roots()
218                .timeout(CONNECT_TIMEOUT);
219            endpoint = endpoint.tls_config(tls).map_err(|err| {
220                CallError::failed(
221                    ErrCode::Unavailable,
222                    format!("configuring TLS for {base}: {err}"),
223                )
224                .caused_by(err)
225            })?;
226        }
227        _ => return Err(invalid_base(base, "gRPC is called at http:// or https://")),
228    }
229    // On the core's runtime, which outlives the one a call is made in, as
230    // each test's does: the channel's worker runs there.
231    let _runtime = crate::runtime::core().tokio_handle().enter();
232    Ok(endpoint.connect_lazy())
233}
234
235/// What a call has heard from the service.
236#[derive(Debug, Default)]
237struct Heard {
238    /// Whether its answer's headers arrived.
239    answered: AtomicBool,
240    /// Whether its gRPC status arrived, in the headers or the trailers.
241    status: AtomicBool,
242}
243
244/// The service a call goes through: its channel, with the trace and Request
245/// Context, noting in `heard` what the service answers, and failing the call
246/// with an answer that is not gRPC's as [`NotGrpc`].
247#[derive(Clone)]
248struct Watched {
249    inner: Propagate<Channel>,
250    heard: Arc<Heard>,
251}
252
253impl Service<http::Request<Body>> for Watched {
254    type Response = http::Response<Body>;
255    type Error = BoxError;
256    type Future = Pin<Box<dyn Future<Output = Result<Self::Response, BoxError>> + Send>>;
257
258    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), BoxError>> {
259        self.inner.poll_ready(cx).map_err(Into::into)
260    }
261
262    fn call(&mut self, request: http::Request<Body>) -> Self::Future {
263        let heard = self.heard.clone();
264        let response = self.inner.call(request);
265        Box::pin(async move {
266            let response = response.await?;
267            heard.answered.store(true, Ordering::Release);
268            if response.headers().contains_key("grpc-status") {
269                heard.status.store(true, Ordering::Release);
270            } else if let Some(not_grpc) = NotGrpc::of(&response) {
271                return Err(Box::new(not_grpc.read(response.into_body()).await) as BoxError);
272            }
273            Ok(response.map(|body| Body::new(Trailers { body, heard })))
274        })
275    }
276}
277
278/// An answer's body, noting in `heard` when its trailers carry the status.
279struct Trailers {
280    body: Body,
281    heard: Arc<Heard>,
282}
283
284impl http_body::Body for Trailers {
285    type Data = bytes::Bytes;
286    type Error = tonic::Status;
287
288    fn poll_frame(
289        mut self: Pin<&mut Self>,
290        cx: &mut Context<'_>,
291    ) -> Poll<Option<Result<http_body::Frame<bytes::Bytes>, tonic::Status>>> {
292        let frame = Pin::new(&mut self.body).poll_frame(cx);
293        if let Poll::Ready(Some(Ok(frame))) = &frame {
294            if frame
295                .trailers_ref()
296                .is_some_and(|t| t.contains_key("grpc-status"))
297            {
298                self.heard.status.store(true, Ordering::Release);
299            }
300        }
301        frame
302    }
303
304    fn is_end_stream(&self) -> bool {
305        self.body.is_end_stream()
306    }
307
308    fn size_hint(&self) -> http_body::SizeHint {
309        self.body.size_hint()
310    }
311}
312
313/// An answer that is not gRPC's: an HTTP status other than 200 without a
314/// gRPC status, as a proxy in the way answers, or a content type other than
315/// gRPC's. Its code is the one gRPC gives its HTTP status.
316#[derive(Debug)]
317struct NotGrpc {
318    status: http::StatusCode,
319    content_type: String,
320    code: ErrCode,
321    message: String,
322}
323
324impl NotGrpc {
325    /// The answer `response` is, when it is not gRPC's.
326    fn of<B>(response: &http::Response<B>) -> Option<NotGrpc> {
327        let status = response.status();
328        let content_type = response
329            .headers()
330            .get(http::header::CONTENT_TYPE)
331            .and_then(|v| v.to_str().ok())
332            .unwrap_or_default()
333            .to_ascii_lowercase();
334        let grpc = content_type
335            .strip_prefix("application/grpc")
336            .is_some_and(|rest| rest.is_empty() || rest.starts_with(['+', ';']));
337        if status == http::StatusCode::OK && grpc {
338            return None;
339        }
340        // As gRPC maps an HTTP status to a code.
341        let code = match status.as_u16() {
342            400 => ErrCode::Internal,
343            401 => ErrCode::Unauthenticated,
344            403 => ErrCode::PermissionDenied,
345            404 => ErrCode::Unimplemented,
346            429 | 502 | 503 | 504 => ErrCode::Unavailable,
347            _ => ErrCode::Unknown,
348        };
349        Some(NotGrpc {
350            status,
351            content_type,
352            code,
353            message: String::new(),
354        })
355    }
356
357    /// The answer, its message the start of `body` when that is text.
358    async fn read(mut self, mut body: Body) -> NotGrpc {
359        let mut text = Vec::new();
360        while text.len() < MAX_ERROR_BODY {
361            match std::future::poll_fn(|cx| Pin::new(&mut body).poll_frame(cx)).await {
362                Some(Ok(frame)) => {
363                    if let Ok(data) = frame.into_data() {
364                        text.extend_from_slice(&data);
365                    }
366                }
367                _ => break,
368            }
369        }
370        text.truncate(MAX_ERROR_BODY);
371        self.message = self.message_for(&String::from_utf8_lossy(&text));
372        self
373    }
374
375    /// The error's message, for an answer whose body starts with `text`:
376    /// the text, when the answer is text.
377    fn message_for(&self, text: &str) -> String {
378        if self.content_type.starts_with("text/") && !text.trim().is_empty() {
379            return text.trim().to_string();
380        }
381        let content_type = match self.content_type.as_str() {
382            "" => "no content type",
383            ct => ct,
384        };
385        format!(
386            "service responded with {} ({content_type}), not gRPC",
387            self.status
388        )
389    }
390
391    /// The call's error.
392    fn error(&self) -> CallError {
393        let err = CallError::new(self.code, self.message.clone());
394        if self.status.is_client_error() || self.status.is_server_error() {
395            err.with_status(self.status.as_u16())
396        } else {
397            err
398        }
399    }
400}
401
402impl fmt::Display for NotGrpc {
403    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
404        f.write_str(&self.message)
405    }
406}
407
408impl std::error::Error for NotGrpc {}
409
410/// The longest timeout gRPC can send: 8 digits of hours.
411const MAX_TIMEOUT: Duration = Duration::from_secs(99_999_999 * 3600);
412
413/// When a call with `timeout` times out, sent with `request` as its
414/// deadline. A timeout longer than gRPC can send, or than the clock counts
415/// to, is none.
416fn deadline<T>(request: &mut tonic::Request<T>, timeout: Option<Duration>) -> Option<Instant> {
417    let timeout = timeout.filter(|t| *t <= MAX_TIMEOUT)?;
418    let deadline = Instant::now().checked_add(timeout)?;
419    request.set_timeout(timeout);
420    Some(deadline)
421}
422
423/// `call`, failed with `DeadlineExceeded` if it has not ended by `deadline`.
424async fn within<T>(
425    deadline: Option<Instant>,
426    call: impl Future<Output = Result<T, CallError>>,
427) -> Result<T, CallError> {
428    let Some(deadline) = deadline else {
429        return call.await;
430    };
431    tokio::time::timeout_at(deadline.into(), call)
432        .await
433        .unwrap_or_else(|_| Err(timed_out()))
434}
435
436/// The error of a call past its deadline.
437fn timed_out() -> CallError {
438    CallError::failed(ErrCode::DeadlineExceeded, "call exceeded its timeout")
439}
440
441/// `google.rpc.Status`, which gRPC sends a status's details in.
442#[derive(Clone, PartialEq, prost::Message)]
443struct RpcStatus {
444    #[prost(int32, tag = "1")]
445    code: i32,
446    #[prost(string, tag = "2")]
447    message: String,
448    #[prost(message, repeated, tag = "3")]
449    details: Vec<prost_types::Any>,
450}
451
452/// The error a failed call's status is, after it heard `heard`.
453///
454/// A status the service sent keeps its code and details, and has the HTTP
455/// status Encore answers its code with. Any other, which tonic made of an
456/// error of its own, or of the deadline, is no answer, and has none: past
457/// the deadline it is `DeadlineExceeded`, as tonic fails a call then with
458/// `Cancelled`; for want of an answer, `Unavailable`; else, as when the
459/// service reset the call or its answer does not decode, the code tonic gave
460/// it.
461fn status_error(status: tonic::Status, deadline: Option<Instant>, heard: &Heard) -> CallError {
462    if let Some(not_grpc) = find::<NotGrpc>(&status) {
463        return not_grpc.error().caused_by(status);
464    }
465    let past_deadline = deadline.is_some_and(|d| Instant::now() >= d);
466    let sent = heard.status.load(Ordering::Acquire) && std::error::Error::source(&status).is_none();
467    let code = if past_deadline
468        && matches!(
469            status.code(),
470            tonic::Code::Cancelled | tonic::Code::DeadlineExceeded
471        ) {
472        ErrCode::DeadlineExceeded
473    } else if sent {
474        code_of(status.code())
475    } else if lost(&status, heard.answered.load(Ordering::Acquire)) {
476        ErrCode::Unavailable
477    } else {
478        code_of(status.code())
479    };
480    let message = status.message().to_string();
481    let err = if sent {
482        let mut err = CallError::new(code, message);
483        if let Ok(details) = <RpcStatus as prost::Message>::decode(status.details()) {
484            err.grpc_details = details.details;
485        }
486        err
487    } else {
488        CallError::failed(code, message)
489    };
490    err.caused_by(status)
491}
492
493/// Whether a call that failed with `status`, a status tonic made, got no
494/// answer: none came, or its connection was lost, but the service did not
495/// reset the call's stream, which gRPC gives a code by its reason.
496fn lost(status: &tonic::Status, answered: bool) -> bool {
497    match find::<h2::Error>(status) {
498        Some(err) if err.is_reset() && err.is_remote() => false,
499        Some(err) if err.is_io() || err.is_go_away() => true,
500        _ => !answered,
501    }
502}
503
504/// The first error of type `E` in `status`'s sources.
505fn find<E: std::error::Error + 'static>(status: &tonic::Status) -> Option<&E> {
506    let mut source = std::error::Error::source(status);
507    while let Some(err) = source {
508        if let Some(found) = err.downcast_ref::<E>() {
509            return Some(found);
510        }
511        source = err.source();
512    }
513    None
514}
515
516/// Encore's code for a gRPC status's.
517fn code_of(code: tonic::Code) -> ErrCode {
518    match code {
519        tonic::Code::Ok | tonic::Code::Unknown => ErrCode::Unknown,
520        tonic::Code::Cancelled => ErrCode::Canceled,
521        tonic::Code::InvalidArgument => ErrCode::InvalidArgument,
522        tonic::Code::DeadlineExceeded => ErrCode::DeadlineExceeded,
523        tonic::Code::NotFound => ErrCode::NotFound,
524        tonic::Code::AlreadyExists => ErrCode::AlreadyExists,
525        tonic::Code::PermissionDenied => ErrCode::PermissionDenied,
526        tonic::Code::ResourceExhausted => ErrCode::ResourceExhausted,
527        tonic::Code::FailedPrecondition => ErrCode::FailedPrecondition,
528        tonic::Code::Aborted => ErrCode::Aborted,
529        tonic::Code::OutOfRange => ErrCode::OutOfRange,
530        tonic::Code::Unimplemented => ErrCode::Unimplemented,
531        tonic::Code::Internal => ErrCode::Internal,
532        tonic::Code::Unavailable => ErrCode::Unavailable,
533        tonic::Code::DataLoss => ErrCode::DataLoss,
534        tonic::Code::Unauthenticated => ErrCode::Unauthenticated,
535    }
536}
537
538/// Waits for the channel to take a call.
539async fn ready(grpc: &mut Grpc<Watched>) -> Result<(), CallError> {
540    grpc.ready().await.map_err(|err| {
541        let status = tonic::Status::from_error(err);
542        CallError::failed(ErrCode::Unavailable, format!("connecting: {status}")).caused_by(status)
543    })
544}
545
546/// The settings methods every kind of call has.
547macro_rules! settings {
548    () => {
549        /// Sets a deadline for this call, overriding the client's default
550        /// timeout.
551        ///
552        /// The deadline covers connecting, waiting for headers, and reading
553        /// every message on a stream, failing with
554        /// [`ErrCode::DeadlineExceeded`] if exceeded.
555        pub fn timeout(mut self, timeout: Duration) -> Self {
556            self.call.settings = self.call.settings.timeout(timeout);
557            self
558        }
559
560        /// Disables any timeout inherited from the client for this call.
561        pub fn no_timeout(mut self) -> Self {
562            self.call.settings = self.call.settings.no_timeout();
563            self
564        }
565
566        /// Attaches a gRPC metadata header, overriding any header with the same
567        /// name set on the client.
568        ///
569        /// Names ending in `-bin` are treated as binary metadata and expect
570        /// base64-encoded values.
571        pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
572            self.call.settings = self.call.settings.header(name, value);
573            self
574        }
575    };
576}
577
578/// A unary gRPC call (one request message, one response message).
579#[must_use = "a call is not sent until awaited"]
580pub struct Unary<'c, Req, Resp> {
581    call: Call<'c>,
582    message: Req,
583    answer: PhantomData<fn() -> Resp>,
584}
585
586impl<'c, Req, Resp> Unary<'c, Req, Resp> {
587    /// A call of `path`, `/package.Service/Method`, sending `message`.
588    #[doc(hidden)]
589    pub fn new(
590        service: &'c services::Client,
591        client: &'c Settings,
592        path: &'static str,
593        message: Req,
594    ) -> Self {
595        Unary {
596            call: Call {
597                service,
598                client,
599                settings: Settings::new(),
600                path,
601            },
602            message,
603            answer: PhantomData,
604        }
605    }
606
607    settings!();
608}
609
610impl<'c, Req, Resp> IntoFuture for Unary<'c, Req, Resp>
611where
612    Req: prost::Message + Send + Sync + 'static,
613    Resp: prost::Message + Default + Send + Sync + 'static,
614{
615    type Output = Result<Resp, CallError>;
616    type IntoFuture = Sending<'c, Resp>;
617
618    /// Sends the call in the context `into_future` is called in, as awaiting
619    /// it does, so a call spawned still carries the context of the code that
620    /// made it.
621    fn into_future(self) -> Self::IntoFuture {
622        Box::pin(super::sent(async move {
623            let Prepared {
624                mut grpc,
625                request,
626                deadline,
627                heard,
628            } = self.call.prepare(self.message)?;
629            let path = self.call.path();
630            within(deadline, async move {
631                ready(&mut grpc).await?;
632                let codec = ProstCodec::<Req, Resp>::default();
633                grpc.unary(request, path, codec)
634                    .await
635                    .map(tonic::Response::into_inner)
636                    .map_err(|s| status_error(s, deadline, &heard))
637            })
638            .await
639        }))
640    }
641}
642
643/// A server-streaming gRPC call (one request message, stream of responses).
644#[must_use = "a call is not sent until awaited"]
645pub struct ServerStreaming<'c, Req, Resp> {
646    call: Call<'c>,
647    message: Req,
648    answer: PhantomData<fn() -> Resp>,
649}
650
651impl<'c, Req, Resp> ServerStreaming<'c, Req, Resp> {
652    /// A call of `path`, `/package.Service/Method`, sending `message`.
653    #[doc(hidden)]
654    pub fn new(
655        service: &'c services::Client,
656        client: &'c Settings,
657        path: &'static str,
658        message: Req,
659    ) -> Self {
660        ServerStreaming {
661            call: Call {
662                service,
663                client,
664                settings: Settings::new(),
665                path,
666            },
667            message,
668            answer: PhantomData,
669        }
670    }
671
672    settings!();
673}
674
675impl<'c, Req, Resp> IntoFuture for ServerStreaming<'c, Req, Resp>
676where
677    Req: prost::Message + Send + Sync + 'static,
678    Resp: prost::Message + Default + Send + Sync + 'static,
679{
680    type Output = Result<Streaming<Resp>, CallError>;
681    type IntoFuture = Sending<'c, Streaming<Resp>>;
682
683    /// Sends the call in the context `into_future` is called in, as awaiting
684    /// it does, so a call spawned still carries the context of the code that
685    /// made it.
686    fn into_future(self) -> Self::IntoFuture {
687        Box::pin(super::sent(async move {
688            let Prepared {
689                mut grpc,
690                request,
691                deadline,
692                heard,
693            } = self.call.prepare(self.message)?;
694            let path = self.call.path();
695            let inner = within(deadline, async {
696                ready(&mut grpc).await?;
697                let codec = ProstCodec::<Req, Resp>::default();
698                grpc.server_streaming(request, path, codec)
699                    .await
700                    .map_err(|s| status_error(s, deadline, &heard))
701            })
702            .await?
703            .into_inner();
704            Ok(Streaming::new(
705                State::Open(Box::new(inner)),
706                deadline,
707                heard,
708            ))
709        }))
710    }
711}
712
713/// A client-streaming gRPC call (stream of requests, one response message).
714#[must_use = "a call is not sent until awaited"]
715pub struct ClientStreaming<'c, S, Resp> {
716    call: Call<'c>,
717    messages: S,
718    answer: PhantomData<fn() -> Resp>,
719}
720
721impl<'c, S, Resp> ClientStreaming<'c, S, Resp> {
722    /// A call of `path`, `/package.Service/Method`, sending `messages`.
723    #[doc(hidden)]
724    pub fn new(
725        service: &'c services::Client,
726        client: &'c Settings,
727        path: &'static str,
728        messages: S,
729    ) -> Self {
730        ClientStreaming {
731            call: Call {
732                service,
733                client,
734                settings: Settings::new(),
735                path,
736            },
737            messages,
738            answer: PhantomData,
739        }
740    }
741
742    settings!();
743}
744
745impl<'c, S, Resp> IntoFuture for ClientStreaming<'c, S, Resp>
746where
747    S: Stream + Send + 'static,
748    S::Item: prost::Message + Send + Sync + 'static,
749    Resp: prost::Message + Default + Send + Sync + 'static,
750{
751    type Output = Result<Resp, CallError>;
752    type IntoFuture = Sending<'c, Resp>;
753
754    /// Sends the call in the context `into_future` is called in, as awaiting
755    /// it does, so a call spawned still carries the context of the code that
756    /// made it.
757    fn into_future(self) -> Self::IntoFuture {
758        Box::pin(super::sent(async move {
759            let Prepared {
760                mut grpc,
761                request,
762                deadline,
763                heard,
764            } = self.call.prepare(self.messages)?;
765            let path = self.call.path();
766            within(deadline, async move {
767                ready(&mut grpc).await?;
768                let codec = ProstCodec::<S::Item, Resp>::default();
769                grpc.client_streaming(request, path, codec)
770                    .await
771                    .map(tonic::Response::into_inner)
772                    .map_err(|s| status_error(s, deadline, &heard))
773            })
774            .await
775        }))
776    }
777}
778
779/// A bidirectional-streaming gRPC call (stream of requests, stream of
780/// responses).
781#[must_use = "a call is not sent until awaited"]
782pub struct BidiStreaming<'c, S, Resp> {
783    call: Call<'c>,
784    messages: S,
785    answer: PhantomData<fn() -> Resp>,
786}
787
788impl<'c, S, Resp> BidiStreaming<'c, S, Resp> {
789    /// A call of `path`, `/package.Service/Method`, sending `messages`.
790    #[doc(hidden)]
791    pub fn new(
792        service: &'c services::Client,
793        client: &'c Settings,
794        path: &'static str,
795        messages: S,
796    ) -> Self {
797        BidiStreaming {
798            call: Call {
799                service,
800                client,
801                settings: Settings::new(),
802                path,
803            },
804            messages,
805            answer: PhantomData,
806        }
807    }
808
809    settings!();
810}
811
812impl<'c, S, Resp> IntoFuture for BidiStreaming<'c, S, Resp>
813where
814    S: Stream + Send + 'static,
815    S::Item: prost::Message + Send + Sync + 'static,
816    Resp: prost::Message + Default + Send + Sync + 'static,
817{
818    type Output = Result<Streaming<Resp>, CallError>;
819    type IntoFuture = Sending<'c, Streaming<Resp>>;
820
821    /// Sends the call in the context `into_future` is called in, as awaiting
822    /// it does, so a call spawned still carries the context of the code that
823    /// made it.
824    ///
825    /// It is answered once the call is made, without waiting for the
826    /// service's answer, which a service may send only after it has read a
827    /// message: a failure of the call then ends the stream.
828    fn into_future(self) -> Self::IntoFuture {
829        Box::pin(super::sent(async move {
830            let Prepared {
831                mut grpc,
832                request,
833                deadline,
834                heard,
835            } = self.call.prepare(self.messages)?;
836            let path = self.call.path();
837            let answering = heard.clone();
838            let mut call: Answering<Resp> = Box::pin(
839                async move {
840                    ready(&mut grpc).await?;
841                    let codec = ProstCodec::<S::Item, Resp>::default();
842                    grpc.streaming(request, path, codec)
843                        .await
844                        .map(tonic::Response::into_inner)
845                        .map_err(|s| status_error(s, deadline, &answering))
846                }
847                .with_context(crate::opentelemetry::Context::current()),
848            );
849            // Sent, as far as it goes without waiting.
850            let state = std::future::poll_fn(|cx| match call.as_mut().poll(cx) {
851                Poll::Ready(Ok(messages)) => Poll::Ready(Ok(Some(messages))),
852                Poll::Ready(Err(err)) => Poll::Ready(Err(err)),
853                Poll::Pending => Poll::Ready(Ok(None)),
854            })
855            .await?;
856            let state = match state {
857                Some(messages) => State::Open(Box::new(messages)),
858                None => State::Answering(call),
859            };
860            Ok(Streaming::new(state, deadline, heard))
861        }))
862    }
863}
864
865/// Stream of response messages from a server-streaming or bidirectional gRPC
866/// call.
867///
868/// Implements [`Stream`] and also provides [`Streaming::message`]. The call's
869/// deadline applies to every message; if the deadline expires before the next
870/// message arrives, the stream terminates with [`ErrCode::DeadlineExceeded`].
871pub struct Streaming<T> {
872    state: State<T>,
873    deadline: Option<Instant>,
874    /// Wakes the stream at its deadline.
875    timer: Option<Pin<Box<tokio::time::Sleep>>>,
876    heard: Arc<Heard>,
877}
878
879/// A call waiting for its answer's headers.
880type Answering<T> = Pin<Box<dyn Future<Output = Result<tonic::Streaming<T>, CallError>> + Send>>;
881
882/// Where a stream of messages is.
883enum State<T> {
884    /// Its call is made, but not yet answered.
885    Answering(Answering<T>),
886    /// Its messages arrive.
887    Open(Box<tonic::Streaming<T>>),
888    /// It has ended, its call with it.
889    Ended,
890}
891
892impl<T> Streaming<T> {
893    fn new(state: State<T>, deadline: Option<Instant>, heard: Arc<Heard>) -> Self {
894        Streaming {
895            state,
896            deadline,
897            timer: deadline.map(|d| Box::pin(tokio::time::sleep_until(d.into()))),
898            heard,
899        }
900    }
901
902    /// The next message; `None` after the last.
903    pub async fn message(&mut self) -> Result<Option<T>, CallError> {
904        std::future::poll_fn(|cx| Pin::new(&mut *self).poll_next(cx))
905            .await
906            .transpose()
907    }
908}
909
910impl<T> std::fmt::Debug for Streaming<T> {
911    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
912        f.debug_struct("Streaming").finish_non_exhaustive()
913    }
914}
915
916impl<T> Stream for Streaming<T> {
917    type Item = Result<T, CallError>;
918
919    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
920        let this = &mut *self;
921        if matches!(this.state, State::Ended) {
922            return Poll::Ready(None);
923        }
924        let past_deadline = this
925            .timer
926            .as_mut()
927            .is_some_and(|timer| timer.as_mut().poll(cx).is_ready());
928        let item = loop {
929            if past_deadline {
930                break Some(Err(timed_out()));
931            }
932            match &mut this.state {
933                State::Answering(call) => match call.as_mut().poll(cx) {
934                    Poll::Ready(Ok(messages)) => this.state = State::Open(Box::new(messages)),
935                    Poll::Ready(Err(err)) => break Some(Err(err)),
936                    Poll::Pending => return Poll::Pending,
937                },
938                State::Open(messages) => match Pin::new(messages).poll_next(cx) {
939                    Poll::Ready(Some(Ok(message))) => return Poll::Ready(Some(Ok(message))),
940                    Poll::Ready(Some(Err(status))) => {
941                        break Some(Err(status_error(status, this.deadline, &this.heard)))
942                    }
943                    Poll::Ready(None) => break None,
944                    Poll::Pending => return Poll::Pending,
945                },
946                State::Ended => break None,
947            }
948        };
949        // The stream has ended: dropping its call cancels it, if it has not.
950        this.state = State::Ended;
951        this.timer = None;
952        Poll::Ready(item)
953    }
954}
955
956#[cfg(test)]
957mod tests {
958    use super::*;
959
960    /// What a call that the service answered with a status heard.
961    fn answered() -> Heard {
962        Heard {
963            answered: AtomicBool::new(true),
964            status: AtomicBool::new(true),
965        }
966    }
967
968    /// What a call that the service answered, but sent no status, heard.
969    fn headers_only() -> Heard {
970        Heard {
971            answered: AtomicBool::new(true),
972            status: AtomicBool::new(false),
973        }
974    }
975
976    #[test]
977    fn a_cancel_past_the_deadline_is_deadline_exceeded() {
978        let past = Some(Instant::now() - Duration::from_millis(1));
979        let future = Some(Instant::now() + Duration::from_secs(60));
980        let none = Heard::default();
981        assert_eq!(
982            status_error(tonic::Status::cancelled("Timeout expired"), past, &none).code,
983            ErrCode::DeadlineExceeded
984        );
985        assert_eq!(
986            status_error(
987                tonic::Status::cancelled("Timeout expired"),
988                future,
989                &answered()
990            )
991            .code,
992            ErrCode::Canceled
993        );
994        assert_eq!(
995            status_error(
996                tonic::Status::cancelled("Timeout expired"),
997                None,
998                &answered()
999            )
1000            .code,
1001            ErrCode::Canceled
1002        );
1003        let err = status_error(
1004            tonic::Status::not_found("no such product"),
1005            None,
1006            &answered(),
1007        );
1008        assert_eq!((err.code, err.status), (ErrCode::NotFound, 404));
1009        assert_eq!(err.message, "no such product");
1010    }
1011
1012    #[test]
1013    fn a_timeout_too_long_to_send_is_none() {
1014        let mut request = tonic::Request::new(());
1015        assert_eq!(deadline(&mut request, Some(Duration::MAX)), None);
1016        assert!(request.metadata().get("grpc-timeout").is_none());
1017        assert!(deadline(&mut request, Some(Duration::from_secs(1))).is_some());
1018        assert!(request.metadata().get("grpc-timeout").is_some());
1019    }
1020
1021    #[test]
1022    fn only_a_status_the_service_sent_has_an_http_status() {
1023        let past = Some(Instant::now() - Duration::from_millis(1));
1024        let timed_out = status_error(
1025            tonic::Status::cancelled("Timeout expired"),
1026            past,
1027            &Heard::default(),
1028        );
1029        assert_eq!(timed_out.status, 0);
1030        let refused = tonic::Status::from_error(Box::new(std::io::Error::from(
1031            std::io::ErrorKind::ConnectionRefused,
1032        )));
1033        assert_eq!(status_error(refused, None, &Heard::default()).status, 0);
1034        let sent = status_error(tonic::Status::unavailable("draining"), None, &answered());
1035        assert_eq!((sent.code, sent.status), (ErrCode::Unavailable, 503));
1036        // A status tonic made of an answer it could not read, as of one that
1037        // does not decode, is not the service's.
1038        let undecodable = status_error(tonic::Status::internal("bad frame"), None, &headers_only());
1039        assert_eq!(
1040            (undecodable.code, undecodable.status),
1041            (ErrCode::Internal, 0)
1042        );
1043    }
1044
1045    #[test]
1046    fn no_answer_is_unavailable() {
1047        // As tonic fails a call whose connection was refused or reset, or
1048        // whose peer speaks no HTTP/2, before any answer.
1049        for status in [
1050            tonic::Status::from_error(Box::new(std::io::Error::from(
1051                std::io::ErrorKind::ConnectionReset,
1052            ))),
1053            tonic::Status::from_error(Box::new(h2::Error::from(h2::Reason::PROTOCOL_ERROR))),
1054        ] {
1055            let err = status_error(status, None, &Heard::default());
1056            assert_eq!((err.code, err.status), (ErrCode::Unavailable, 0), "{err}");
1057        }
1058    }
1059
1060    #[test]
1061    fn a_status_keeps_its_details() {
1062        let detail = prost_types::Any {
1063            type_url: "type.googleapis.com/conformance.v1.Detail".into(),
1064            value: vec![0x0a, 0x03, b'w', b'h', b'y'],
1065        };
1066        let details = prost::Message::encode_to_vec(&RpcStatus {
1067            code: 5,
1068            message: "nope".into(),
1069            details: vec![detail.clone()],
1070        });
1071        let status = tonic::Status::with_details(tonic::Code::NotFound, "nope", details.into());
1072        let err = status_error(status, None, &answered());
1073        assert_eq!(
1074            (err.code, err.message.as_str()),
1075            (ErrCode::NotFound, "nope")
1076        );
1077        assert_eq!(err.grpc_details, [detail]);
1078        let err = status_error(tonic::Status::not_found("nope"), None, &answered());
1079        assert!(err.grpc_details.is_empty());
1080    }
1081
1082    #[test]
1083    fn an_answer_that_is_not_grpc_is_its_http_status() {
1084        let response = |status: u16, content_type: &str| {
1085            http::Response::builder()
1086                .status(status)
1087                .header("content-type", content_type)
1088                .body(())
1089                .unwrap()
1090        };
1091        assert!(NotGrpc::of(&response(200, "application/grpc")).is_none());
1092        assert!(NotGrpc::of(&response(200, "application/grpc+proto")).is_none());
1093        let mut bad_gateway = NotGrpc::of(&response(502, "text/plain")).unwrap();
1094        bad_gateway.message = bad_gateway.message_for("service down\n");
1095        let err = bad_gateway.error();
1096        assert_eq!(
1097            (err.code, err.status, err.message.as_str()),
1098            (ErrCode::Unavailable, 502, "service down")
1099        );
1100        // Through tonic, as the call sees it.
1101        let status = tonic::Status::from_error(Box::new(bad_gateway));
1102        let err = status_error(status, None, &Heard::default());
1103        assert_eq!((err.code, err.status), (ErrCode::Unavailable, 502));
1104
1105        for (status, code) in [
1106            (400, ErrCode::Internal),
1107            (401, ErrCode::Unauthenticated),
1108            (403, ErrCode::PermissionDenied),
1109            (404, ErrCode::Unimplemented),
1110            (429, ErrCode::Unavailable),
1111            (503, ErrCode::Unavailable),
1112            (504, ErrCode::Unavailable),
1113            (500, ErrCode::Unknown),
1114        ] {
1115            let answer = NotGrpc::of(&response(status, "application/json")).unwrap();
1116            assert_eq!(answer.code, code, "{status}");
1117            assert_eq!(answer.error().status, status);
1118        }
1119        let html = NotGrpc::of(&response(200, "text/html")).unwrap();
1120        assert_eq!(html.code, ErrCode::Unknown);
1121        assert_eq!(html.error().status, 500);
1122        assert_eq!(
1123            html.message_for(""),
1124            "service responded with 200 OK (text/html), not gRPC"
1125        );
1126    }
1127
1128    #[test]
1129    fn binary_metadata_is_base64() {
1130        let headers = |pairs: &[(&str, &str)]| -> Vec<(String, String)> {
1131            pairs
1132                .iter()
1133                .map(|(k, v)| (k.to_string(), v.to_string()))
1134                .collect()
1135        };
1136        let metadata = metadata(&headers(&[("X-Id-Bin", "AP8Q"), ("x-plain", "a")])).unwrap();
1137        assert_eq!(
1138            metadata.get_bin("x-id-bin").unwrap().to_bytes().unwrap(),
1139            &[0x00, 0xff, 0x10][..]
1140        );
1141        assert_eq!(metadata.get("x-plain").unwrap(), "a");
1142        let err = super::metadata(&headers(&[("x-id-bin", "not base64!")])).unwrap_err();
1143        assert_eq!(err.code, ErrCode::InvalidArgument);
1144        assert!(err.message.contains("base64"), "{err}");
1145        let err = super::metadata(&headers(&[("x y", "a")])).unwrap_err();
1146        assert_eq!(err.code, ErrCode::InvalidArgument);
1147    }
1148
1149    #[test]
1150    fn channels_are_dropped_when_idle_or_too_many() {
1151        let mut channels = Channels::<usize>::new();
1152        let start = Instant::now();
1153        let mut made = 0;
1154        let mut get = |channels: &mut Channels<usize>, base: &str, at: Duration| {
1155            channels
1156                .get(base, start + at, || {
1157                    made += 1;
1158                    Ok(made)
1159                })
1160                .unwrap()
1161        };
1162        assert_eq!(get(&mut channels, "http://a", Duration::ZERO), 1);
1163        assert_eq!(get(&mut channels, "http://a", Duration::from_secs(1)), 1);
1164        // Idle for longer than a channel is kept.
1165        let later = Duration::from_secs(1) + IDLE_CHANNEL;
1166        assert_eq!(get(&mut channels, "http://a", later), 2);
1167        for i in 0..MAX_CHANNELS * 2 {
1168            let at = later + Duration::from_millis(i as u64);
1169            get(&mut channels, &format!("http://{i}"), at);
1170        }
1171        let kept = channels.kept.as_ref().unwrap();
1172        assert_eq!(kept.len(), MAX_CHANNELS);
1173        // The ones used last.
1174        assert!(kept.contains_key(&format!("http://{}", MAX_CHANNELS * 2 - 1)));
1175        assert!(!kept.contains_key("http://0"));
1176    }
1177}