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#[doc(hidden)]
23pub mod protobuf;
24
25pub use grpc::{BidiStreaming, ClientStreaming, ServerStreaming, Streaming, Unary};
26
27pub use futures_core::Stream;
30
31#[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#[derive(Debug, Clone)]
47#[non_exhaustive]
48pub struct CallError {
49 pub code: ErrCode,
55 pub message: String,
57 pub status: u16,
62 pub graphql_errors: Vec<serde_json::Value>,
67 pub grpc_details: Vec<prost_types::Any>,
71 source: Option<Arc<dyn std::error::Error + Send + Sync>>,
74}
75
76impl CallError {
77 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 pub(crate) fn failed(code: ErrCode, message: impl Into<String>) -> Self {
93 CallError::new(code, message).with_status(0)
94 }
95
96 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 #[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
124impl 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
134pub trait UnlessNotFound<T> {
143 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
159impl From<CallError> for Error {
163 fn from(err: CallError) -> Self {
164 Error::new(err.code, err.message)
165 }
166}
167
168#[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#[derive(Debug, Clone, Default)]
190pub struct Settings {
191 base_url: Option<String>,
192 timeout: Option<Option<Duration>>,
194 headers: Vec<(String, String)>,
195}
196
197impl Settings {
198 pub const fn new() -> Self {
200 Settings {
201 base_url: None,
202 timeout: None,
203 headers: Vec::new(),
204 }
205 }
206
207 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 pub fn timeout(mut self, timeout: Duration) -> Self {
222 self.timeout = Some(Some(timeout));
223 self
224 }
225
226 pub fn no_timeout(mut self) -> Self {
228 self.timeout = Some(None);
229 self
230 }
231
232 fn limit(&self) -> Option<Duration> {
234 self.timeout.flatten()
235 }
236
237 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 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
261fn 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
279fn 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}