Skip to main content

encore/services/clients/
grpc.rs

1//! The calls of a generated gRPC client: one per kind of RPC, each sent by
2//! `.await`, over one tonic channel per service that the SDK keeps.
3
4use std::collections::HashMap;
5use std::future::{Future, IntoFuture};
6use std::marker::PhantomData;
7use std::pin::Pin;
8use std::sync::{Mutex, OnceLock};
9use std::task::{Context, Poll};
10use std::time::{Duration, Instant};
11
12use futures_core::Stream;
13use tonic::client::Grpc;
14use tonic::codegen::http::uri::PathAndQuery;
15use tonic::metadata::{MetadataKey, MetadataValue};
16use tonic::transport::{Channel, Endpoint};
17use tonic_prost::ProstCodec;
18use tower_layer::Layer;
19
20use super::{base_url_of, invalid_header, CallError, Settings};
21use crate::services::{self, Propagate, PropagateLayer};
22use crate::ErrCode;
23
24/// A call's future.
25type Sending<'c, T> = Pin<Box<dyn Future<Output = Result<T, CallError>> + Send + 'c>>;
26
27/// What every kind of call holds: where it goes, and its settings.
28struct Call<'c> {
29    service: &'c services::Client,
30    client: &'c Settings,
31    settings: Settings,
32    path: &'static str,
33}
34
35/// A call ready to send.
36struct Prepared<T> {
37    /// The channel it goes over.
38    grpc: Grpc<Propagate<Channel>>,
39    /// The request it sends its message or messages in.
40    request: tonic::Request<T>,
41    /// When it times out.
42    deadline: Option<Instant>,
43}
44
45impl Call<'_> {
46    /// The call, sending `message`.
47    fn prepare<T>(&self, message: T) -> Result<Prepared<T>, CallError> {
48        let settings = self.settings.under(self.client);
49        let grpc = grpc(base_url_of(self.service, &settings)?)?;
50        let mut request = tonic::Request::new(message);
51        for (name, value) in &settings.headers {
52            let key = MetadataKey::from_bytes(name.to_ascii_lowercase().as_bytes())
53                .map_err(|e| invalid_header(name, e))?;
54            let value =
55                MetadataValue::try_from(value.as_str()).map_err(|e| invalid_header(name, e))?;
56            request.metadata_mut().insert(key, value);
57        }
58        let deadline = deadline(&mut request, settings.limit());
59        Ok(Prepared {
60            grpc,
61            request,
62            deadline,
63        })
64    }
65
66    fn path(&self) -> PathAndQuery {
67        PathAndQuery::from_static(self.path)
68    }
69}
70
71/// The client calls to `base` go over: the service's channel, which tells
72/// the app's services from others by `base`'s origin.
73fn grpc(base: &str) -> Result<Grpc<Propagate<Channel>>, CallError> {
74    static CHANNELS: OnceLock<Mutex<HashMap<String, Channel>>> = OnceLock::new();
75    let origin: http::Uri = base.parse().map_err(|e| {
76        CallError::failed(
77            ErrCode::InvalidArgument,
78            format!("invalid base URL {base:?}: {e}"),
79        )
80    })?;
81    let mut channels = CHANNELS
82        .get_or_init(Default::default)
83        .lock()
84        .unwrap_or_else(|e| e.into_inner());
85    let channel = match channels.get(base) {
86        Some(channel) => channel.clone(),
87        None => {
88            let endpoint = Endpoint::from_shared(base.to_string()).map_err(|e| {
89                CallError::failed(
90                    ErrCode::InvalidArgument,
91                    format!("invalid base URL {base:?}: {e}"),
92                )
93            })?;
94            // On the core's runtime, which outlives the one a call is made
95            // in, as each test's does: the channel's worker runs there.
96            let _runtime = crate::runtime::core().tokio_handle().enter();
97            let channel = endpoint.connect_lazy();
98            channels.insert(base.to_string(), channel.clone());
99            channel
100        }
101    };
102    Ok(Grpc::with_origin(PropagateLayer.layer(channel), origin))
103}
104
105/// The longest timeout gRPC can send: 8 digits of hours.
106const MAX_TIMEOUT: Duration = Duration::from_secs(99_999_999 * 3600);
107
108/// When a call with `timeout` times out, sent with `request` as its
109/// deadline. A timeout longer than gRPC can send, or than the clock counts
110/// to, is none.
111fn deadline<T>(request: &mut tonic::Request<T>, timeout: Option<Duration>) -> Option<Instant> {
112    let timeout = timeout.filter(|t| *t <= MAX_TIMEOUT)?;
113    let deadline = Instant::now().checked_add(timeout)?;
114    request.set_timeout(timeout);
115    Some(deadline)
116}
117
118/// The error a failed call's status is. tonic fails a call past its
119/// deadline as `Cancelled`, which is `DeadlineExceeded` here. A status tonic
120/// made of an error of its own, which it keeps as the status's source, or of
121/// the deadline, is no answer: it has no HTTP status.
122fn status_error(status: tonic::Status, deadline: Option<Instant>) -> CallError {
123    let past_deadline = deadline.is_some_and(|d| Instant::now() >= d);
124    let answered = std::error::Error::source(&status).is_none()
125        && !(past_deadline && status.code() == tonic::Code::Cancelled);
126    let code = match status.code() {
127        tonic::Code::Ok | tonic::Code::Unknown => ErrCode::Unknown,
128        tonic::Code::Cancelled if past_deadline => ErrCode::DeadlineExceeded,
129        tonic::Code::Cancelled => ErrCode::Canceled,
130        tonic::Code::InvalidArgument => ErrCode::InvalidArgument,
131        tonic::Code::DeadlineExceeded => ErrCode::DeadlineExceeded,
132        tonic::Code::NotFound => ErrCode::NotFound,
133        tonic::Code::AlreadyExists => ErrCode::AlreadyExists,
134        tonic::Code::PermissionDenied => ErrCode::PermissionDenied,
135        tonic::Code::ResourceExhausted => ErrCode::ResourceExhausted,
136        tonic::Code::FailedPrecondition => ErrCode::FailedPrecondition,
137        tonic::Code::Aborted => ErrCode::Aborted,
138        tonic::Code::OutOfRange => ErrCode::OutOfRange,
139        tonic::Code::Unimplemented => ErrCode::Unimplemented,
140        tonic::Code::Internal => ErrCode::Internal,
141        tonic::Code::Unavailable => ErrCode::Unavailable,
142        tonic::Code::DataLoss => ErrCode::DataLoss,
143        tonic::Code::Unauthenticated => ErrCode::Unauthenticated,
144    };
145    let message = status.message().to_string();
146    let err = if answered {
147        CallError::new(code, message)
148    } else {
149        CallError::failed(code, message)
150    };
151    err.caused_by(status)
152}
153
154/// Waits for the channel to take a call.
155async fn ready(grpc: &mut Grpc<Propagate<Channel>>) -> Result<(), CallError> {
156    grpc.ready().await.map_err(|err| {
157        CallError::failed(ErrCode::Unavailable, format!("connecting: {err}")).caused_by(err)
158    })
159}
160
161/// The settings methods every kind of call has.
162macro_rules! settings {
163    () => {
164        /// Fails the call when it takes longer than `timeout`, with
165        /// `DeadlineExceeded`, in place of its client's timeout. It is sent
166        /// as the call's deadline.
167        pub fn timeout(mut self, timeout: Duration) -> Self {
168            self.call.settings = self.call.settings.timeout(timeout);
169            self
170        }
171
172        /// Sets the call no timeout, in place of its client's.
173        pub fn no_timeout(mut self) -> Self {
174            self.call.settings = self.call.settings.no_timeout();
175            self
176        }
177
178        /// Sends a header, as gRPC metadata, in place of one of the same
179        /// name its client would send.
180        pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
181            self.call.settings = self.call.settings.header(name, value);
182            self
183        }
184    };
185}
186
187/// A unary call: one message each way.
188#[must_use = "a call is sent only when awaited"]
189pub struct Unary<'c, Req, Resp> {
190    call: Call<'c>,
191    message: Req,
192    answer: PhantomData<fn() -> Resp>,
193}
194
195impl<'c, Req, Resp> Unary<'c, Req, Resp> {
196    /// A call of `path`, `/package.Service/Method`, sending `message`.
197    #[doc(hidden)]
198    pub fn new(
199        service: &'c services::Client,
200        client: &'c Settings,
201        path: &'static str,
202        message: Req,
203    ) -> Self {
204        Unary {
205            call: Call {
206                service,
207                client,
208                settings: Settings::new(),
209                path,
210            },
211            message,
212            answer: PhantomData,
213        }
214    }
215
216    settings!();
217}
218
219impl<'c, Req, Resp> IntoFuture for Unary<'c, Req, Resp>
220where
221    Req: prost::Message + Send + Sync + 'static,
222    Resp: prost::Message + Default + Send + Sync + 'static,
223{
224    type Output = Result<Resp, CallError>;
225    type IntoFuture = Sending<'c, Resp>;
226
227    /// Sends the call in the context `into_future` is called in, as awaiting
228    /// it does, so a call spawned still carries the context of the code that
229    /// made it.
230    fn into_future(self) -> Self::IntoFuture {
231        Box::pin(super::sent(async move {
232            let Prepared {
233                mut grpc,
234                request,
235                deadline,
236            } = self.call.prepare(self.message)?;
237            ready(&mut grpc).await?;
238            let codec = ProstCodec::<Req, Resp>::default();
239            grpc.unary(request, self.call.path(), codec)
240                .await
241                .map(tonic::Response::into_inner)
242                .map_err(|s| status_error(s, deadline))
243        }))
244    }
245}
246
247/// A call answered with a stream of messages.
248#[must_use = "a call is sent only when awaited"]
249pub struct ServerStreaming<'c, Req, Resp> {
250    call: Call<'c>,
251    message: Req,
252    answer: PhantomData<fn() -> Resp>,
253}
254
255impl<'c, Req, Resp> ServerStreaming<'c, Req, Resp> {
256    /// A call of `path`, `/package.Service/Method`, sending `message`.
257    #[doc(hidden)]
258    pub fn new(
259        service: &'c services::Client,
260        client: &'c Settings,
261        path: &'static str,
262        message: Req,
263    ) -> Self {
264        ServerStreaming {
265            call: Call {
266                service,
267                client,
268                settings: Settings::new(),
269                path,
270            },
271            message,
272            answer: PhantomData,
273        }
274    }
275
276    settings!();
277}
278
279impl<'c, Req, Resp> IntoFuture for ServerStreaming<'c, Req, Resp>
280where
281    Req: prost::Message + Send + Sync + 'static,
282    Resp: prost::Message + Default + Send + Sync + 'static,
283{
284    type Output = Result<Streaming<Resp>, CallError>;
285    type IntoFuture = Sending<'c, Streaming<Resp>>;
286
287    /// Sends the call in the context `into_future` is called in, as awaiting
288    /// it does, so a call spawned still carries the context of the code that
289    /// made it.
290    fn into_future(self) -> Self::IntoFuture {
291        Box::pin(super::sent(async move {
292            let Prepared {
293                mut grpc,
294                request,
295                deadline,
296            } = self.call.prepare(self.message)?;
297            ready(&mut grpc).await?;
298            let codec = ProstCodec::<Req, Resp>::default();
299            let inner = grpc
300                .server_streaming(request, self.call.path(), codec)
301                .await
302                .map_err(|s| status_error(s, deadline))?
303                .into_inner();
304            Ok(Streaming { inner, deadline })
305        }))
306    }
307}
308
309/// A call sending a stream of messages, answered with one.
310#[must_use = "a call is sent only when awaited"]
311pub struct ClientStreaming<'c, S, Resp> {
312    call: Call<'c>,
313    messages: S,
314    answer: PhantomData<fn() -> Resp>,
315}
316
317impl<'c, S, Resp> ClientStreaming<'c, S, Resp> {
318    /// A call of `path`, `/package.Service/Method`, sending `messages`.
319    #[doc(hidden)]
320    pub fn new(
321        service: &'c services::Client,
322        client: &'c Settings,
323        path: &'static str,
324        messages: S,
325    ) -> Self {
326        ClientStreaming {
327            call: Call {
328                service,
329                client,
330                settings: Settings::new(),
331                path,
332            },
333            messages,
334            answer: PhantomData,
335        }
336    }
337
338    settings!();
339}
340
341impl<'c, S, Resp> IntoFuture for ClientStreaming<'c, S, Resp>
342where
343    S: Stream + Send + 'static,
344    S::Item: prost::Message + Send + Sync + 'static,
345    Resp: prost::Message + Default + Send + Sync + 'static,
346{
347    type Output = Result<Resp, CallError>;
348    type IntoFuture = Sending<'c, Resp>;
349
350    /// Sends the call in the context `into_future` is called in, as awaiting
351    /// it does, so a call spawned still carries the context of the code that
352    /// made it.
353    fn into_future(self) -> Self::IntoFuture {
354        Box::pin(super::sent(async move {
355            let Prepared {
356                mut grpc,
357                request,
358                deadline,
359            } = self.call.prepare(self.messages)?;
360            ready(&mut grpc).await?;
361            let codec = ProstCodec::<S::Item, Resp>::default();
362            grpc.client_streaming(request, self.call.path(), codec)
363                .await
364                .map(tonic::Response::into_inner)
365                .map_err(|s| status_error(s, deadline))
366        }))
367    }
368}
369
370/// A call sending a stream of messages, answered with another.
371#[must_use = "a call is sent only when awaited"]
372pub struct BidiStreaming<'c, S, Resp> {
373    call: Call<'c>,
374    messages: S,
375    answer: PhantomData<fn() -> Resp>,
376}
377
378impl<'c, S, Resp> BidiStreaming<'c, S, Resp> {
379    /// A call of `path`, `/package.Service/Method`, sending `messages`.
380    #[doc(hidden)]
381    pub fn new(
382        service: &'c services::Client,
383        client: &'c Settings,
384        path: &'static str,
385        messages: S,
386    ) -> Self {
387        BidiStreaming {
388            call: Call {
389                service,
390                client,
391                settings: Settings::new(),
392                path,
393            },
394            messages,
395            answer: PhantomData,
396        }
397    }
398
399    settings!();
400}
401
402impl<'c, S, Resp> IntoFuture for BidiStreaming<'c, S, Resp>
403where
404    S: Stream + Send + 'static,
405    S::Item: prost::Message + Send + Sync + 'static,
406    Resp: prost::Message + Default + Send + Sync + 'static,
407{
408    type Output = Result<Streaming<Resp>, CallError>;
409    type IntoFuture = Sending<'c, Streaming<Resp>>;
410
411    /// Sends the call in the context `into_future` is called in, as awaiting
412    /// it does, so a call spawned still carries the context of the code that
413    /// made it.
414    fn into_future(self) -> Self::IntoFuture {
415        Box::pin(super::sent(async move {
416            let Prepared {
417                mut grpc,
418                request,
419                deadline,
420            } = self.call.prepare(self.messages)?;
421            ready(&mut grpc).await?;
422            let codec = ProstCodec::<S::Item, Resp>::default();
423            let inner = grpc
424                .streaming(request, self.call.path(), codec)
425                .await
426                .map_err(|s| status_error(s, deadline))?
427                .into_inner();
428            Ok(Streaming { inner, deadline })
429        }))
430    }
431}
432
433/// The messages a call is answered with: a [`Stream`] of them, which ends
434/// after the last, or with the call's error.
435pub struct Streaming<T> {
436    inner: tonic::Streaming<T>,
437    deadline: Option<Instant>,
438}
439
440impl<T> Streaming<T> {
441    /// The next message; `None` after the last.
442    pub async fn message(&mut self) -> Result<Option<T>, CallError> {
443        std::future::poll_fn(|cx| Pin::new(&mut *self).poll_next(cx))
444            .await
445            .transpose()
446    }
447}
448
449impl<T> std::fmt::Debug for Streaming<T> {
450    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
451        f.debug_struct("Streaming").finish_non_exhaustive()
452    }
453}
454
455impl<T> Stream for Streaming<T> {
456    type Item = Result<T, CallError>;
457
458    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
459        let deadline = self.deadline;
460        Pin::new(&mut self.inner)
461            .poll_next(cx)
462            .map(|item| item.map(|r| r.map_err(|s| status_error(s, deadline))))
463    }
464}
465
466#[cfg(test)]
467mod tests {
468    use super::*;
469
470    #[test]
471    fn a_cancel_past_the_deadline_is_deadline_exceeded() {
472        let past = Some(Instant::now() - Duration::from_millis(1));
473        let future = Some(Instant::now() + Duration::from_secs(60));
474        assert_eq!(
475            status_error(tonic::Status::cancelled("Timeout expired"), past).code,
476            ErrCode::DeadlineExceeded
477        );
478        assert_eq!(
479            status_error(tonic::Status::cancelled("Timeout expired"), future).code,
480            ErrCode::Canceled
481        );
482        assert_eq!(
483            status_error(tonic::Status::cancelled("Timeout expired"), None).code,
484            ErrCode::Canceled
485        );
486        let err = status_error(tonic::Status::not_found("no such product"), None);
487        assert_eq!((err.code, err.status), (ErrCode::NotFound, 404));
488        assert_eq!(err.message, "no such product");
489    }
490
491    #[test]
492    fn a_timeout_too_long_to_send_is_none() {
493        let mut request = tonic::Request::new(());
494        assert_eq!(deadline(&mut request, Some(Duration::MAX)), None);
495        assert!(request.metadata().get("grpc-timeout").is_none());
496        assert!(deadline(&mut request, Some(Duration::from_secs(1))).is_some());
497        assert!(request.metadata().get("grpc-timeout").is_some());
498    }
499
500    #[test]
501    fn only_a_status_the_service_sent_has_an_http_status() {
502        let past = Some(Instant::now() - Duration::from_millis(1));
503        let timed_out = status_error(tonic::Status::cancelled("Timeout expired"), past);
504        assert_eq!(timed_out.status, 0);
505        let refused = tonic::Status::from_error(Box::new(std::io::Error::from(
506            std::io::ErrorKind::ConnectionRefused,
507        )));
508        assert_eq!(status_error(refused, None).status, 0);
509        let sent = status_error(tonic::Status::unavailable("draining"), None);
510        assert_eq!((sent.code, sent.status), (ErrCode::Unavailable, 503));
511    }
512}