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::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
25pub use futures_core::Stream;
28
29#[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#[derive(Debug, Clone)]
45#[non_exhaustive]
46pub struct CallError {
47 pub code: ErrCode,
52 pub message: String,
54 pub status: u16,
59 pub graphql_errors: Vec<serde_json::Value>,
64 source: Option<Arc<dyn std::error::Error + Send + Sync>>,
67}
68
69impl CallError {
70 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 pub(crate) fn failed(code: ErrCode, message: impl Into<String>) -> Self {
85 CallError::new(code, message).with_status(0)
86 }
87
88 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 #[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
116impl 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
126pub trait UnlessNotFound<T> {
135 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
151impl From<CallError> for Error {
155 fn from(err: CallError) -> Self {
156 Error::new(err.code, err.message)
157 }
158}
159
160#[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#[derive(Debug, Clone, Default)]
182pub struct Settings {
183 base_url: Option<String>,
184 timeout: Option<Option<Duration>>,
186 headers: Vec<(String, String)>,
187}
188
189impl Settings {
190 pub const fn new() -> Self {
192 Settings {
193 base_url: None,
194 timeout: None,
195 headers: Vec::new(),
196 }
197 }
198
199 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 pub fn timeout(mut self, timeout: Duration) -> Self {
213 self.timeout = Some(Some(timeout));
214 self
215 }
216
217 pub fn no_timeout(mut self) -> Self {
219 self.timeout = Some(None);
220 self
221 }
222
223 fn limit(&self) -> Option<Duration> {
225 self.timeout.flatten()
226 }
227
228 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 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
251fn 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
269fn 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}