1use std::fmt;
8use std::future::Future;
9use std::sync::Arc;
10use std::time::Duration;
11
12use encore_sdk_core::api;
13
14use crate::opentelemetry::Context;
15use crate::opentelemetry::trace::FutureExt;
16use crate::{ErrCode, Error, services};
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
27pub use futures_core::Stream;
29
30#[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#[derive(Debug, Clone)]
46#[non_exhaustive]
47pub struct CallError {
48 pub code: ErrCode,
55 pub message: String,
57 pub status: u16,
63 pub graphql_errors: Vec<serde_json::Value>,
71 pub grpc_details: Vec<prost_types::Any>,
74 source: Option<Arc<dyn std::error::Error + Send + Sync>>,
76}
77
78impl CallError {
79 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 pub(crate) fn failed(code: ErrCode, message: impl Into<String>) -> Self {
95 CallError::new(code, message).with_status(0)
96 }
97
98 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 #[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
126impl 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
136pub trait UnlessNotFound<T> {
145 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
160impl From<CallError> for Error {
164 fn from(err: CallError) -> Self {
165 Error::new(err.code, err.message)
166 }
167}
168
169#[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#[derive(Debug, Clone, Default)]
192pub struct Settings {
193 base_url: Option<String>,
194 timeout: Option<Option<Duration>>,
196 headers: Vec<(String, String)>,
197}
198
199impl Settings {
200 pub const fn new() -> Self {
203 Settings {
204 base_url: None,
205 timeout: None,
206 headers: Vec::new(),
207 }
208 }
209
210 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 pub fn timeout(mut self, timeout: Duration) -> Self {
228 self.timeout = Some(Some(timeout));
229 self
230 }
231
232 pub fn no_timeout(mut self) -> Self {
234 self.timeout = Some(None);
235 self
236 }
237
238 fn limit(&self) -> Option<Duration> {
240 self.timeout.flatten()
241 }
242
243 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 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
269fn 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
287fn 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}