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