encore-dev 2.0.0-beta.10

Rust SDK for Encore applications
Documentation
//! The errors, settings and calls of the service clients Encore generates,
//! which [`services`](crate::services) re-exports the errors and calls of: see
//! it. The rest is for the generated code, which reaches each crate it uses
//! through the SDK, so a service needs only `encore-dev` to compile it: its
//! API may change with the generator's.

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};

/// The Stream trait a gRPC API's streams implement and its client streams
/// take.
pub use futures_core::Stream;

// For the generated code, which reaches each crate it uses through the SDK.
#[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;

/// A call to another service that failed: an error answer, or none at all.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct CallError {
    /// The failure's code: the one the service answered with, in Encore's
    /// error body or as its gRPC status; `Unavailable` when no answer came;
    /// `DeadlineExceeded` when the call took longer than its timeout; else
    /// the one the answer's HTTP status means, as `NotFound` for 404, or for
    /// a gRPC call as gRPC maps it, as `Unavailable` for a proxy's 502.
    pub code: ErrCode,
    /// What went wrong, as the service said, or as the client saw.
    pub message: String,
    /// The HTTP status of the service's answer: the answer's own, when it was
    /// an error status, else (a gRPC or GraphQL error) the one Encore answers
    /// `code` with. 0 when the call got no answer, or failed before it was
    /// sent or while its answer was read.
    pub status: u16,
    /// A GraphQL answer's errors, as it sent them: each an object with a
    /// `message`, and often `path`, `locations` and `extensions`. Empty for
    /// any other failure. Its code is the first error's `extensions.code`
    /// when that is one of Encore's codes, and `Unknown` otherwise.
    pub graphql_errors: Vec<serde_json::Value>,
    /// A gRPC status's details, as the service sent them: each an `Any`,
    /// which `to_msg` decodes as the message it holds, as a generated
    /// client's messages. Empty for any other failure.
    pub grpc_details: Vec<prost_types::Any>,
    /// The error the call failed with, when there was one: reqwest's, tonic's
    /// status, or serde_json's for an answer that does not decode.
    source: Option<Arc<dyn std::error::Error + Send + Sync>>,
}

impl CallError {
    /// An error with `code` and `message`, and the HTTP status Encore
    /// answers `code` with: as a mock of a call returns one.
    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,
        }
    }

    /// The error of a call that failed before or without an answer, as the
    /// client saw it: with `code` and `message`, and no status.
    pub(crate) fn failed(code: ErrCode, message: impl Into<String>) -> Self {
        CallError::new(code, message).with_status(0)
    }

    /// The error with `source` as the one it failed with.
    pub(crate) fn caused_by(
        mut self,
        source: impl std::error::Error + Send + Sync + 'static,
    ) -> Self {
        self.source = Some(Arc::new(source));
        self
    }

    /// The error with `status` in place of the one its code has.
    #[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
        )
    }
}

/// The error the call failed with, as reqwest's, tonic's or serde_json's, when
/// there was one: an error answer has none.
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))
    }
}

/// Makes a `NotFound` failure of a call `None`, for a call for something that
/// may not be there:
///
/// ```ignore
/// use encore::services::UnlessNotFound;
///
/// let product = catalog::openapi::get_product("xyz").await.unless_not_found()?;
/// ```
pub trait UnlessNotFound<T> {
    /// `Some` of what the call answered, `None` when it failed with a
    /// [`CallError`] whose code is `NotFound`, and any other failure as it
    /// is.
    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),
        }
    }
}

/// The callee's code and message, so `?` in a handler answers as the service
/// it called did. Match on [`CallError::code`] first to answer something
/// else.
impl From<CallError> for Error {
    fn from(err: CallError) -> Self {
        Error::new(err.code, err.message)
    }
}

/// `call`, run in the context `sent` is called in, unless the one it is
/// polled in holds a trace or Request Context, as
/// `services::RequestBuilder::send` chooses. A call's `into_future` is made of
/// it, so a call spawned, and so polled in a task of its own, still carries
/// the context of the code that made it.
#[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
    }
}

/// The settings of a generated client, or of one call: what a module's
/// `Client`, and each call, hold. Each one left unset keeps the default.
#[derive(Debug, Clone, Default)]
pub struct Settings {
    base_url: Option<String>,
    /// The timeout, `Some(None)` for none at all, unset by `None`.
    timeout: Option<Option<Duration>>,
    headers: Vec<(String, String)>,
}

impl Settings {
    /// No settings: the service's own base URL, no timeout, no headers.
    pub const fn new() -> Self {
        Settings {
            base_url: None,
            timeout: None,
            headers: Vec::new(),
        }
    }

    /// Calls the service at `url` in place of the base URL Encore gives it,
    /// as a mock server. Its calls carry the Request Context only to the
    /// origin the app's services are reached at, where Encore serves nothing
    /// else: a mock server's carry none.
    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
    }

    /// Fails a call that takes longer than `timeout`, with
    /// `DeadlineExceeded`. A gRPC call sends it as its deadline, which holds
    /// until its answer's last message.
    pub fn timeout(mut self, timeout: Duration) -> Self {
        self.timeout = Some(Some(timeout));
        self
    }

    /// Sets no timeout, in place of its client's for a call.
    pub fn no_timeout(mut self) -> Self {
        self.timeout = Some(None);
        self
    }

    /// The timeout a call with these settings has.
    fn limit(&self) -> Option<Duration> {
        self.timeout.flatten()
    }

    /// Sends a header with every call, in place of one of the same name
    /// that it would send otherwise. To a gRPC API, a name ending in `-bin`
    /// is binary metadata, whose value is base64, as gRPC sends it.
    pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
        self.headers.push((name.into(), value.into()));
        self
    }

    /// The settings a call with `self`'s, made with a client with
    /// `client`'s, has: its own timeout and headers over the client's.
    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(),
        }
    }
}

/// The base URL a call to `service` with `settings` goes to: theirs, or the
/// service's, and `Unavailable` when the runtime knows no such service. The
/// service is looked up for a base URL of the caller's too, as `services`
/// does, which records its origin, but need not be found.
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()),
        )),
    }
}

/// The error a header that is no header is.
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");
    }
}