Skip to main content

encore/services/
clients.rs

1//! Supporting types for Encore's generated service clients.
2//!
3//! User-facing call and error types are re-exported from
4//! [`services`](crate::services). Internal items are used by generated client
5//! code and may change between releases.
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/// Re-export of [`futures_core::Stream`] used by generated gRPC streaming calls.
28pub use futures_core::Stream;
29
30// For the generated code, which reaches each crate it uses through the SDK.
31#[doc(hidden)]
32pub use prost;
33#[doc(hidden)]
34pub use prost_types;
35#[doc(hidden)]
36pub use serde;
37#[doc(hidden)]
38pub use serde_json;
39#[doc(hidden)]
40pub use tonic;
41#[doc(hidden)]
42pub use tonic_prost;
43
44/// Error returned when a generated service client call fails.
45#[derive(Debug, Clone)]
46#[non_exhaustive]
47pub struct CallError {
48    /// Canonical Encore error code for the failure.
49    ///
50    /// Taken from the service's Encore error body or gRPC status when present;
51    /// otherwise mapped from the HTTP status (for example, `NotFound` for 404,
52    /// or `Unavailable` for a proxy 502 on gRPC), `DeadlineExceeded` on
53    /// timeout, or `Unavailable` when no response was received.
54    pub code: ErrCode,
55    /// Human-readable error message from the service or client.
56    pub message: String,
57    /// HTTP status code associated with the error.
58    ///
59    /// For HTTP error responses this is the returned status code; for gRPC and
60    /// GraphQL errors it is the HTTP status mapped from `code`; `0` if the
61    /// call failed before receiving a response or while reading the body.
62    pub status: u16,
63    /// Raw error entries from a GraphQL response (each typically containing
64    /// `message`, and optionally `path`, `locations`, and `extensions`). Empty
65    /// for non-GraphQL errors.
66    ///
67    /// For GraphQL failures, `code` is taken from the first error's
68    /// `extensions.code` if it matches an Encore error code, or `Unknown`
69    /// otherwise.
70    pub graphql_errors: Vec<serde_json::Value>,
71    /// Structured `google.rpc.Status` error details returned by a gRPC service
72    /// (decode each `Any` with `to_msg`). Empty for non-gRPC errors.
73    pub grpc_details: Vec<prost_types::Any>,
74    /// Underlying transport or decoding error, if any.
75    source: Option<Arc<dyn std::error::Error + Send + Sync>>,
76}
77
78impl CallError {
79    /// Creates a `CallError` with `code`, `message`, and the default HTTP
80    /// status for `code` (useful for mocking calls in tests).
81    pub fn new(code: ErrCode, message: impl Into<String>) -> Self {
82        CallError {
83            code,
84            message: message.into(),
85            status: api::ErrCode::from(code).http_status(),
86            graphql_errors: Vec::new(),
87            grpc_details: Vec::new(),
88            source: None,
89        }
90    }
91
92    /// The error of a call that failed before or without an answer, as the
93    /// client saw it: with `code` and `message`, and no status.
94    pub(crate) fn failed(code: ErrCode, message: impl Into<String>) -> Self {
95        CallError::new(code, message).with_status(0)
96    }
97
98    /// The error with `source` as the one it failed with.
99    pub(crate) fn caused_by(
100        mut self,
101        source: impl std::error::Error + Send + Sync + 'static,
102    ) -> Self {
103        self.source = Some(Arc::new(source));
104        self
105    }
106
107    /// The error with `status` in place of the one its code has.
108    #[doc(hidden)]
109    pub fn with_status(mut self, status: u16) -> Self {
110        self.status = status;
111        self
112    }
113}
114
115impl fmt::Display for CallError {
116    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
117        write!(
118            f,
119            "{}: {}",
120            api::ErrCode::from(self.code).as_str(),
121            self.message
122        )
123    }
124}
125
126/// The error the call failed with, as reqwest's, tonic's or serde_json's, when
127/// there was one: an error answer has none.
128impl std::error::Error for CallError {
129    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
130        self.source
131            .as_deref()
132            .map(|e| e as &(dyn std::error::Error + 'static))
133    }
134}
135
136/// Extension trait that converts a [`CallError`] with code
137/// [`ErrCode::NotFound`] into `Ok(None)`.
138///
139/// ```ignore
140/// use encore::services::UnlessNotFound;
141///
142/// let product = catalog::openapi::get_product("xyz").await.unless_not_found()?;
143/// ```
144pub trait UnlessNotFound<T> {
145    /// Maps `Ok(v)` to `Ok(Some(v))`, `Err(e)` with `e.code == ErrCode::NotFound`
146    /// to `Ok(None)`, and leaves all other errors unchanged.
147    fn unless_not_found(self) -> Result<Option<T>, CallError>;
148}
149
150impl<T> UnlessNotFound<T> for Result<T, CallError> {
151    fn unless_not_found(self) -> Result<Option<T>, CallError> {
152        match self {
153            Ok(v) => Ok(Some(v)),
154            Err(err) if err.code == ErrCode::NotFound => Ok(None),
155            Err(err) => Err(err),
156        }
157    }
158}
159
160/// Preserves the callee's error code and message so `?` in a handler forwards
161/// the error directly. Match on [`CallError::code`] beforehand to handle
162/// specific errors differently.
163impl From<CallError> for Error {
164    fn from(err: CallError) -> Self {
165        Error::new(err.code, err.message)
166    }
167}
168
169/// `call`, run in the context `sent` is called in, unless the one it is
170/// polled in holds a trace or Request Context, as
171/// `services::RequestBuilder::send` chooses. A call's `into_future` is made of
172/// it, so a call spawned, and so polled in a task of its own, still carries
173/// the context of the code that made it.
174#[doc(hidden)]
175pub fn sent<F: Future>(call: F) -> impl Future<Output = F::Output> {
176    let called_in = Context::current();
177    async move {
178        let polled_in = Context::current();
179        let cx = if services::carries_context(&polled_in) {
180            polled_in
181        } else {
182            called_in
183        };
184        call.with_context(cx).await
185    }
186}
187
188/// Configuration shared by a generated client or an individual call.
189///
190/// Unset fields inherit defaults from the parent client or runtime.
191#[derive(Debug, Clone, Default)]
192pub struct Settings {
193    base_url: Option<String>,
194    /// The timeout, `Some(None)` for none at all, unset by `None`.
195    timeout: Option<Option<Duration>>,
196    headers: Vec<(String, String)>,
197}
198
199impl Settings {
200    /// Creates empty settings (service default base URL, no timeout, no extra
201    /// headers).
202    pub const fn new() -> Self {
203        Settings {
204            base_url: None,
205            timeout: None,
206            headers: Vec::new(),
207        }
208    }
209
210    /// Overrides the service's base URL (for example, to point at a mock
211    /// server in tests).
212    ///
213    /// Request Context headers are only sent to origins belonging to
214    /// application services, so requests to a custom mock server carry none.
215    pub fn base_url(mut self, url: impl Into<String>) -> Self {
216        let mut url = url.into();
217        url.truncate(url.trim_end_matches('/').len());
218        self.base_url = Some(url);
219        self
220    }
221
222    /// Sets a timeout for the call, failing with [`ErrCode::DeadlineExceeded`]
223    /// if exceeded.
224    ///
225    /// For gRPC calls, this is sent as the RPC deadline and covers the entire
226    /// call through the final response message.
227    pub fn timeout(mut self, timeout: Duration) -> Self {
228        self.timeout = Some(Some(timeout));
229        self
230    }
231
232    /// Disables any timeout inherited from the parent client for this call.
233    pub fn no_timeout(mut self) -> Self {
234        self.timeout = Some(None);
235        self
236    }
237
238    /// The timeout a call with these settings has.
239    fn limit(&self) -> Option<Duration> {
240        self.timeout.flatten()
241    }
242
243    /// Adds a header to every call, overriding any previous header with the
244    /// same name.
245    ///
246    /// For gRPC APIs, header names ending in `-bin` are treated as binary
247    /// metadata and expect base64-encoded values.
248    pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
249        self.headers.push((name.into(), value.into()));
250        self
251    }
252
253    /// The settings a call with `self`'s, made with a client with
254    /// `client`'s, has: its own timeout and headers over the client's.
255    fn under(&self, client: &Settings) -> Settings {
256        Settings {
257            base_url: client.base_url.clone(),
258            timeout: self.timeout.or(client.timeout),
259            headers: client
260                .headers
261                .iter()
262                .chain(&self.headers)
263                .cloned()
264                .collect(),
265        }
266    }
267}
268
269/// The base URL a call to `service` with `settings` goes to: theirs, or the
270/// service's, and `Unavailable` when the runtime knows no such service. The
271/// service is looked up for a base URL of the caller's too, as `services`
272/// does, which records its origin, but need not be found.
273fn base_url_of<'s>(
274    service: &services::Client,
275    settings: &'s Settings,
276) -> Result<&'s str, CallError> {
277    let found = service.try_base_url();
278    match (settings.base_url.as_deref(), found) {
279        (Some(base), _) | (None, Some(base)) => Ok(base),
280        (None, None) => Err(CallError::failed(
281            ErrCode::Unavailable,
282            services::unknown_service(service.name()),
283        )),
284    }
285}
286
287/// The error a header that is no header is.
288fn invalid_header(name: &str, err: impl fmt::Display) -> CallError {
289    CallError::failed(
290        ErrCode::InvalidArgument,
291        format!("invalid header {name:?}: {err}"),
292    )
293}
294
295#[cfg(test)]
296mod tests {
297    use super::*;
298
299    #[test]
300    fn a_calls_settings_go_over_its_clients() {
301        let client = Settings::new()
302            .base_url("http://mock/")
303            .timeout(Duration::from_secs(1))
304            .header("a", "client");
305        let call = Settings::new().header("a", "call").header("b", "call");
306        let merged = call.under(&client);
307        assert_eq!(merged.base_url.as_deref(), Some("http://mock"));
308        assert_eq!(merged.limit(), Some(Duration::from_secs(1)));
309        assert_eq!(
310            merged.headers,
311            [("a", "client"), ("a", "call"), ("b", "call")]
312                .map(|(k, v)| (k.to_string(), v.to_string()))
313        );
314        let call = Settings::new().timeout(Duration::from_secs(2));
315        assert_eq!(call.under(&client).limit(), Some(Duration::from_secs(2)));
316        let call = Settings::new().no_timeout();
317        assert_eq!(call.under(&client).limit(), None);
318    }
319
320    #[test]
321    fn unless_not_found_makes_not_found_none() {
322        let found: Result<u8, CallError> = Ok(1);
323        assert_eq!(found.unless_not_found().unwrap(), Some(1));
324        let missing: Result<u8, CallError> = Err(CallError::new(ErrCode::NotFound, "gone"));
325        assert_eq!(missing.unless_not_found().unwrap(), None);
326        let failed: Result<u8, CallError> = Err(CallError::new(ErrCode::Unavailable, "down"));
327        assert_eq!(
328            failed.unless_not_found().unwrap_err().code,
329            ErrCode::Unavailable
330        );
331    }
332
333    #[test]
334    fn errors_keep_their_code_and_message() {
335        let err = CallError::new(ErrCode::NotFound, "no such product");
336        assert_eq!(err.status, 404);
337        assert_eq!(err.to_string(), "not_found: no such product");
338        assert_eq!(invalid_header("a b", "bad").status, 0);
339        let err = Error::from(err);
340        assert_eq!(err.code, ErrCode::NotFound);
341        assert_eq!(err.message, "no such product");
342    }
343}