encore-dev 2.0.0-beta.16

Rust SDK for Encore applications
Documentation
//! Supporting types for Encore's generated service clients.
//!
//! User-facing call and error types are re-exported from
//! [`services`](crate::services). Internal items are used by generated client
//! code and may change between releases.

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

/// Re-export of [`futures_core::Stream`] used by generated gRPC streaming calls.
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;

/// Error returned when a generated service client call fails.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct CallError {
    /// Canonical Encore error code for the failure.
    ///
    /// Taken from the service's Encore error body or gRPC status when present;
    /// otherwise mapped from the HTTP status (for example, `NotFound` for 404,
    /// or `Unavailable` for a proxy 502 on gRPC), `DeadlineExceeded` on
    /// timeout, or `Unavailable` when no response was received.
    pub code: ErrCode,
    /// Human-readable error message from the service or client.
    pub message: String,
    /// HTTP status code associated with the error.
    ///
    /// For HTTP error responses this is the returned status code; for gRPC and
    /// GraphQL errors it is the HTTP status mapped from `code`; `0` if the
    /// call failed before receiving a response or while reading the body.
    pub status: u16,
    /// Raw error entries from a GraphQL response (each typically containing
    /// `message`, and optionally `path`, `locations`, and `extensions`). Empty
    /// for non-GraphQL errors.
    ///
    /// For GraphQL failures, `code` is taken from the first error's
    /// `extensions.code` if it matches an Encore error code, or `Unknown`
    /// otherwise.
    pub graphql_errors: Vec<serde_json::Value>,
    /// Structured `google.rpc.Status` error details returned by a gRPC service
    /// (decode each `Any` with `to_msg`). Empty for non-gRPC errors.
    pub grpc_details: Vec<prost_types::Any>,
    /// Underlying transport or decoding error, if any.
    source: Option<Arc<dyn std::error::Error + Send + Sync>>,
}

impl CallError {
    /// Creates a `CallError` with `code`, `message`, and the default HTTP
    /// status for `code` (useful for mocking calls in tests).
    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))
    }
}

/// Extension trait that converts a [`CallError`] with code
/// [`ErrCode::NotFound`] into `Ok(None)`.
///
/// ```ignore
/// use encore::services::UnlessNotFound;
///
/// let product = catalog::openapi::get_product("xyz").await.unless_not_found()?;
/// ```
pub trait UnlessNotFound<T> {
    /// Maps `Ok(v)` to `Ok(Some(v))`, `Err(e)` with `e.code == ErrCode::NotFound`
    /// to `Ok(None)`, and leaves all other errors unchanged.
    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),
        }
    }
}

/// Preserves the callee's error code and message so `?` in a handler forwards
/// the error directly. Match on [`CallError::code`] beforehand to handle
/// specific errors differently.
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
    }
}

/// Configuration shared by a generated client or an individual call.
///
/// Unset fields inherit defaults from the parent client or runtime.
#[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 {
    /// Creates empty settings (service default base URL, no timeout, no extra
    /// headers).
    pub const fn new() -> Self {
        Settings {
            base_url: None,
            timeout: None,
            headers: Vec::new(),
        }
    }

    /// Overrides the service's base URL (for example, to point at a mock
    /// server in tests).
    ///
    /// Request Context headers are only sent to origins belonging to
    /// application services, so requests to a custom mock server 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
    }

    /// Sets a timeout for the call, failing with [`ErrCode::DeadlineExceeded`]
    /// if exceeded.
    ///
    /// For gRPC calls, this is sent as the RPC deadline and covers the entire
    /// call through the final response message.
    pub fn timeout(mut self, timeout: Duration) -> Self {
        self.timeout = Some(Some(timeout));
        self
    }

    /// Disables any timeout inherited from the parent client for this 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()
    }

    /// Adds a header to every call, overriding any previous header with the
    /// same name.
    ///
    /// For gRPC APIs, header names ending in `-bin` are treated as binary
    /// metadata and expect base64-encoded values.
    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");
    }
}