Skip to main content

encore/services/
clients.rs

1//! The errors, settings and calls of the service clients Encore generates,
2//! which [`services`](crate::services) re-exports the errors and calls of: see
3//! it. The rest is for the generated code, which reaches each crate it uses
4//! through the SDK, so a service needs only `encore-dev` to compile it: its
5//! API may change with the generator's.
6
7use std::fmt;
8use std::future::Future;
9use std::sync::Arc;
10use std::time::Duration;
11
12use encore_sdk_core::api;
13
14use crate::opentelemetry::trace::FutureExt;
15use crate::opentelemetry::Context;
16use crate::{services, ErrCode, Error};
17
18#[doc(hidden)]
19pub mod grpc;
20#[doc(hidden)]
21pub mod http;
22#[doc(hidden)]
23pub mod protobuf;
24
25pub use grpc::{BidiStreaming, ClientStreaming, ServerStreaming, Streaming, Unary};
26
27/// The Stream trait a gRPC API's streams implement and its client streams
28/// take.
29pub use futures_core::Stream;
30
31// For the generated code, which reaches each crate it uses through the SDK.
32#[doc(hidden)]
33pub use prost;
34#[doc(hidden)]
35pub use prost_types;
36#[doc(hidden)]
37pub use serde;
38#[doc(hidden)]
39pub use serde_json;
40#[doc(hidden)]
41pub use tonic;
42#[doc(hidden)]
43pub use tonic_prost;
44
45/// A call to another service that failed: an error answer, or none at all.
46#[derive(Debug, Clone)]
47#[non_exhaustive]
48pub struct CallError {
49    /// The failure's code: the one the service answered with, in Encore's
50    /// error body or as its gRPC status; `Unavailable` when no answer came;
51    /// `DeadlineExceeded` when the call took longer than its timeout; else
52    /// the one the answer's HTTP status means, as `NotFound` for 404, or for
53    /// a gRPC call as gRPC maps it, as `Unavailable` for a proxy's 502.
54    pub code: ErrCode,
55    /// What went wrong, as the service said, or as the client saw.
56    pub message: String,
57    /// The HTTP status of the service's answer: the answer's own, when it was
58    /// an error status, else (a gRPC or GraphQL error) the one Encore answers
59    /// `code` with. 0 when the call got no answer, or failed before it was
60    /// sent or while its answer was read.
61    pub status: u16,
62    /// A GraphQL answer's errors, as it sent them: each an object with a
63    /// `message`, and often `path`, `locations` and `extensions`. Empty for
64    /// any other failure. Its code is the first error's `extensions.code`
65    /// when that is one of Encore's codes, and `Unknown` otherwise.
66    pub graphql_errors: Vec<serde_json::Value>,
67    /// A gRPC status's details, as the service sent them: each an `Any`,
68    /// which `to_msg` decodes as the message it holds, as a generated
69    /// client's messages. Empty for any other failure.
70    pub grpc_details: Vec<prost_types::Any>,
71    /// The error the call failed with, when there was one: reqwest's, tonic's
72    /// status, or serde_json's for an answer that does not decode.
73    source: Option<Arc<dyn std::error::Error + Send + Sync>>,
74}
75
76impl CallError {
77    /// An error with `code` and `message`, and the HTTP status Encore
78    /// answers `code` with: as a mock of a call returns one.
79    pub fn new(code: ErrCode, message: impl Into<String>) -> Self {
80        CallError {
81            code,
82            message: message.into(),
83            status: api::ErrCode::from(code).http_status(),
84            graphql_errors: Vec::new(),
85            grpc_details: Vec::new(),
86            source: None,
87        }
88    }
89
90    /// The error of a call that failed before or without an answer, as the
91    /// client saw it: with `code` and `message`, and no status.
92    pub(crate) fn failed(code: ErrCode, message: impl Into<String>) -> Self {
93        CallError::new(code, message).with_status(0)
94    }
95
96    /// The error with `source` as the one it failed with.
97    pub(crate) fn caused_by(
98        mut self,
99        source: impl std::error::Error + Send + Sync + 'static,
100    ) -> Self {
101        self.source = Some(Arc::new(source));
102        self
103    }
104
105    /// The error with `status` in place of the one its code has.
106    #[doc(hidden)]
107    pub fn with_status(mut self, status: u16) -> Self {
108        self.status = status;
109        self
110    }
111}
112
113impl fmt::Display for CallError {
114    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
115        write!(
116            f,
117            "{}: {}",
118            api::ErrCode::from(self.code).as_str(),
119            self.message
120        )
121    }
122}
123
124/// The error the call failed with, as reqwest's, tonic's or serde_json's, when
125/// there was one: an error answer has none.
126impl std::error::Error for CallError {
127    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
128        self.source
129            .as_deref()
130            .map(|e| e as &(dyn std::error::Error + 'static))
131    }
132}
133
134/// Makes a `NotFound` failure of a call `None`, for a call for something that
135/// may not be there:
136///
137/// ```ignore
138/// use encore::services::UnlessNotFound;
139///
140/// let product = catalog::openapi::get_product("xyz").await.unless_not_found()?;
141/// ```
142pub trait UnlessNotFound<T> {
143    /// `Some` of what the call answered, `None` when it failed with a
144    /// [`CallError`] whose code is `NotFound`, and any other failure as it
145    /// is.
146    fn unless_not_found(self) -> Result<Option<T>, CallError>;
147}
148
149impl<T> UnlessNotFound<T> for Result<T, CallError> {
150    fn unless_not_found(self) -> Result<Option<T>, CallError> {
151        match self {
152            Ok(v) => Ok(Some(v)),
153            Err(err) if err.code == ErrCode::NotFound => Ok(None),
154            Err(err) => Err(err),
155        }
156    }
157}
158
159/// The callee's code and message, so `?` in a handler answers as the service
160/// it called did. Match on [`CallError::code`] first to answer something
161/// else.
162impl From<CallError> for Error {
163    fn from(err: CallError) -> Self {
164        Error::new(err.code, err.message)
165    }
166}
167
168/// `call`, run in the context `sent` is called in, unless the one it is
169/// polled in holds a trace or Request Context, as
170/// `services::RequestBuilder::send` chooses. A call's `into_future` is made of
171/// it, so a call spawned, and so polled in a task of its own, still carries
172/// the context of the code that made it.
173#[doc(hidden)]
174pub fn sent<F: Future>(call: F) -> impl Future<Output = F::Output> {
175    let called_in = Context::current();
176    async move {
177        let polled_in = Context::current();
178        let cx = if services::carries_context(&polled_in) {
179            polled_in
180        } else {
181            called_in
182        };
183        call.with_context(cx).await
184    }
185}
186
187/// The settings of a generated client, or of one call: what a module's
188/// `Client`, and each call, hold. Each one left unset keeps the default.
189#[derive(Debug, Clone, Default)]
190pub struct Settings {
191    base_url: Option<String>,
192    /// The timeout, `Some(None)` for none at all, unset by `None`.
193    timeout: Option<Option<Duration>>,
194    headers: Vec<(String, String)>,
195}
196
197impl Settings {
198    /// No settings: the service's own base URL, no timeout, no headers.
199    pub const fn new() -> Self {
200        Settings {
201            base_url: None,
202            timeout: None,
203            headers: Vec::new(),
204        }
205    }
206
207    /// Calls the service at `url` in place of the base URL Encore gives it,
208    /// as a mock server. Its calls carry the Request Context only to the
209    /// origin the app's services are reached at, where Encore serves nothing
210    /// else: a mock server's carry none.
211    pub fn base_url(mut self, url: impl Into<String>) -> Self {
212        let mut url = url.into();
213        url.truncate(url.trim_end_matches('/').len());
214        self.base_url = Some(url);
215        self
216    }
217
218    /// Fails a call that takes longer than `timeout`, with
219    /// `DeadlineExceeded`. A gRPC call sends it as its deadline, which holds
220    /// until its answer's last message.
221    pub fn timeout(mut self, timeout: Duration) -> Self {
222        self.timeout = Some(Some(timeout));
223        self
224    }
225
226    /// Sets no timeout, in place of its client's for a call.
227    pub fn no_timeout(mut self) -> Self {
228        self.timeout = Some(None);
229        self
230    }
231
232    /// The timeout a call with these settings has.
233    fn limit(&self) -> Option<Duration> {
234        self.timeout.flatten()
235    }
236
237    /// Sends a header with every call, in place of one of the same name
238    /// that it would send otherwise. To a gRPC API, a name ending in `-bin`
239    /// is binary metadata, whose value is base64, as gRPC sends it.
240    pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
241        self.headers.push((name.into(), value.into()));
242        self
243    }
244
245    /// The settings a call with `self`'s, made with a client with
246    /// `client`'s, has: its own timeout and headers over the client's.
247    fn under(&self, client: &Settings) -> Settings {
248        Settings {
249            base_url: client.base_url.clone(),
250            timeout: self.timeout.or(client.timeout),
251            headers: client
252                .headers
253                .iter()
254                .chain(&self.headers)
255                .cloned()
256                .collect(),
257        }
258    }
259}
260
261/// The base URL a call to `service` with `settings` goes to: theirs, or the
262/// service's, and `Unavailable` when the runtime knows no such service. The
263/// service is looked up for a base URL of the caller's too, as `services`
264/// does, which records its origin, but need not be found.
265fn base_url_of<'s>(
266    service: &services::Client,
267    settings: &'s Settings,
268) -> Result<&'s str, CallError> {
269    let found = service.try_base_url();
270    match (settings.base_url.as_deref(), found) {
271        (Some(base), _) | (None, Some(base)) => Ok(base),
272        (None, None) => Err(CallError::failed(
273            ErrCode::Unavailable,
274            services::unknown_service(service.name()),
275        )),
276    }
277}
278
279/// The error a header that is no header is.
280fn invalid_header(name: &str, err: impl fmt::Display) -> CallError {
281    CallError::failed(
282        ErrCode::InvalidArgument,
283        format!("invalid header {name:?}: {err}"),
284    )
285}
286
287#[cfg(test)]
288mod tests {
289    use super::*;
290
291    #[test]
292    fn a_calls_settings_go_over_its_clients() {
293        let client = Settings::new()
294            .base_url("http://mock/")
295            .timeout(Duration::from_secs(1))
296            .header("a", "client");
297        let call = Settings::new().header("a", "call").header("b", "call");
298        let merged = call.under(&client);
299        assert_eq!(merged.base_url.as_deref(), Some("http://mock"));
300        assert_eq!(merged.limit(), Some(Duration::from_secs(1)));
301        assert_eq!(
302            merged.headers,
303            [("a", "client"), ("a", "call"), ("b", "call")]
304                .map(|(k, v)| (k.to_string(), v.to_string()))
305        );
306        let call = Settings::new().timeout(Duration::from_secs(2));
307        assert_eq!(call.under(&client).limit(), Some(Duration::from_secs(2)));
308        let call = Settings::new().no_timeout();
309        assert_eq!(call.under(&client).limit(), None);
310    }
311
312    #[test]
313    fn unless_not_found_makes_not_found_none() {
314        let found: Result<u8, CallError> = Ok(1);
315        assert_eq!(found.unless_not_found().unwrap(), Some(1));
316        let missing: Result<u8, CallError> = Err(CallError::new(ErrCode::NotFound, "gone"));
317        assert_eq!(missing.unless_not_found().unwrap(), None);
318        let failed: Result<u8, CallError> = Err(CallError::new(ErrCode::Unavailable, "down"));
319        assert_eq!(
320            failed.unless_not_found().unwrap_err().code,
321            ErrCode::Unavailable
322        );
323    }
324
325    #[test]
326    fn errors_keep_their_code_and_message() {
327        let err = CallError::new(ErrCode::NotFound, "no such product");
328        assert_eq!(err.status, 404);
329        assert_eq!(err.to_string(), "not_found: no such product");
330        assert_eq!(invalid_header("a b", "bad").status, 0);
331        let err = Error::from(err);
332        assert_eq!(err.code, ErrCode::NotFound);
333        assert_eq!(err.message, "no such product");
334    }
335}