use std::fmt;
use std::future::Future;
use std::sync::Arc;
use std::time::Duration;
use encore_sdk_core::api;
use crate::opentelemetry::trace::FutureExt;
use crate::opentelemetry::Context;
use crate::{services, ErrCode, Error};
#[doc(hidden)]
pub mod grpc;
#[doc(hidden)]
pub mod http;
#[doc(hidden)]
pub mod protobuf;
pub use grpc::{BidiStreaming, ClientStreaming, ServerStreaming, Streaming, Unary};
pub use futures_core::Stream;
#[doc(hidden)]
pub use prost;
#[doc(hidden)]
pub use prost_types;
#[doc(hidden)]
pub use serde;
#[doc(hidden)]
pub use serde_json;
#[doc(hidden)]
pub use tonic;
#[doc(hidden)]
pub use tonic_prost;
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct CallError {
pub code: ErrCode,
pub message: String,
pub status: u16,
pub graphql_errors: Vec<serde_json::Value>,
pub grpc_details: Vec<prost_types::Any>,
source: Option<Arc<dyn std::error::Error + Send + Sync>>,
}
impl CallError {
pub fn new(code: ErrCode, message: impl Into<String>) -> Self {
CallError {
code,
message: message.into(),
status: api::ErrCode::from(code).http_status(),
graphql_errors: Vec::new(),
grpc_details: Vec::new(),
source: None,
}
}
pub(crate) fn failed(code: ErrCode, message: impl Into<String>) -> Self {
CallError::new(code, message).with_status(0)
}
pub(crate) fn caused_by(
mut self,
source: impl std::error::Error + Send + Sync + 'static,
) -> Self {
self.source = Some(Arc::new(source));
self
}
#[doc(hidden)]
pub fn with_status(mut self, status: u16) -> Self {
self.status = status;
self
}
}
impl fmt::Display for CallError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{}: {}",
api::ErrCode::from(self.code).as_str(),
self.message
)
}
}
impl std::error::Error for CallError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
self.source
.as_deref()
.map(|e| e as &(dyn std::error::Error + 'static))
}
}
pub trait UnlessNotFound<T> {
fn unless_not_found(self) -> Result<Option<T>, CallError>;
}
impl<T> UnlessNotFound<T> for Result<T, CallError> {
fn unless_not_found(self) -> Result<Option<T>, CallError> {
match self {
Ok(v) => Ok(Some(v)),
Err(err) if err.code == ErrCode::NotFound => Ok(None),
Err(err) => Err(err),
}
}
}
impl From<CallError> for Error {
fn from(err: CallError) -> Self {
Error::new(err.code, err.message)
}
}
#[doc(hidden)]
pub fn sent<F: Future>(call: F) -> impl Future<Output = F::Output> {
let called_in = Context::current();
async move {
let polled_in = Context::current();
let cx = if services::carries_context(&polled_in) {
polled_in
} else {
called_in
};
call.with_context(cx).await
}
}
#[derive(Debug, Clone, Default)]
pub struct Settings {
base_url: Option<String>,
timeout: Option<Option<Duration>>,
headers: Vec<(String, String)>,
}
impl Settings {
pub const fn new() -> Self {
Settings {
base_url: None,
timeout: None,
headers: Vec::new(),
}
}
pub fn base_url(mut self, url: impl Into<String>) -> Self {
let mut url = url.into();
url.truncate(url.trim_end_matches('/').len());
self.base_url = Some(url);
self
}
pub fn timeout(mut self, timeout: Duration) -> Self {
self.timeout = Some(Some(timeout));
self
}
pub fn no_timeout(mut self) -> Self {
self.timeout = Some(None);
self
}
fn limit(&self) -> Option<Duration> {
self.timeout.flatten()
}
pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
self.headers.push((name.into(), value.into()));
self
}
fn under(&self, client: &Settings) -> Settings {
Settings {
base_url: client.base_url.clone(),
timeout: self.timeout.or(client.timeout),
headers: client
.headers
.iter()
.chain(&self.headers)
.cloned()
.collect(),
}
}
}
fn base_url_of<'s>(
service: &services::Client,
settings: &'s Settings,
) -> Result<&'s str, CallError> {
let found = service.try_base_url();
match (settings.base_url.as_deref(), found) {
(Some(base), _) | (None, Some(base)) => Ok(base),
(None, None) => Err(CallError::failed(
ErrCode::Unavailable,
services::unknown_service(service.name()),
)),
}
}
fn invalid_header(name: &str, err: impl fmt::Display) -> CallError {
CallError::failed(
ErrCode::InvalidArgument,
format!("invalid header {name:?}: {err}"),
)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_calls_settings_go_over_its_clients() {
let client = Settings::new()
.base_url("http://mock/")
.timeout(Duration::from_secs(1))
.header("a", "client");
let call = Settings::new().header("a", "call").header("b", "call");
let merged = call.under(&client);
assert_eq!(merged.base_url.as_deref(), Some("http://mock"));
assert_eq!(merged.limit(), Some(Duration::from_secs(1)));
assert_eq!(
merged.headers,
[("a", "client"), ("a", "call"), ("b", "call")]
.map(|(k, v)| (k.to_string(), v.to_string()))
);
let call = Settings::new().timeout(Duration::from_secs(2));
assert_eq!(call.under(&client).limit(), Some(Duration::from_secs(2)));
let call = Settings::new().no_timeout();
assert_eq!(call.under(&client).limit(), None);
}
#[test]
fn unless_not_found_makes_not_found_none() {
let found: Result<u8, CallError> = Ok(1);
assert_eq!(found.unless_not_found().unwrap(), Some(1));
let missing: Result<u8, CallError> = Err(CallError::new(ErrCode::NotFound, "gone"));
assert_eq!(missing.unless_not_found().unwrap(), None);
let failed: Result<u8, CallError> = Err(CallError::new(ErrCode::Unavailable, "down"));
assert_eq!(
failed.unless_not_found().unwrap_err().code,
ErrCode::Unavailable
);
}
#[test]
fn errors_keep_their_code_and_message() {
let err = CallError::new(ErrCode::NotFound, "no such product");
assert_eq!(err.status, 404);
assert_eq!(err.to_string(), "not_found: no such product");
assert_eq!(invalid_header("a b", "bad").status, 0);
let err = Error::from(err);
assert_eq!(err.code, ErrCode::NotFound);
assert_eq!(err.message, "no such product");
}
}