wellfriend-document-sdk 1.0.0

Official async Rust SDK for the Wellfriend document API: typed document tools, pipelines, streaming uploads and downloads, retries and webhook verification.
Documentation
use std::fmt;
use std::time::Duration;

use reqwest::header::HeaderMap;
use serde::Deserialize;

use crate::models::Operation;
use crate::Object;

/// The result type of every fallible call in this crate.
pub type Result<T, E = Error> = std::result::Result<T, E>;

/// Where to create an API key, quoted in the missing-key error.
pub(crate) const KEYS_URL: &str = "https://wellfriend.dev/dashboard/developer-api/keys";

/// Every error this SDK returns.
///
/// HTTP errors from the API are split by status into [`Error::BadRequest`], [`Error::Validation`],
/// [`Error::Authentication`], [`Error::PermissionDenied`], [`Error::NotFound`],
/// [`Error::Conflict`], [`Error::RateLimit`] and [`Error::Server`]; any other status is
/// [`Error::Api`]. Each carries an [`ApiError`] with the status, code, message, reference id,
/// details and response headers. Use [`Error::status`], [`Error::code`] and
/// [`Error::reference_id`] to inspect any variant without matching.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
    /// 400: the request was malformed.
    #[error("{0}")]
    BadRequest(Box<ApiError>),
    /// 422, or a 400 that reports invalid input (for example an invalid tool parameter).
    #[error("{0}")]
    Validation(Box<ApiError>),
    /// 401: the API key is missing, invalid, expired or revoked.
    #[error("{0}")]
    Authentication(Box<ApiError>),
    /// 403: the key lacks a scope, or the plan does not include the feature.
    #[error("{0}")]
    PermissionDenied(Box<ApiError>),
    /// 404: the resource does not exist in this workspace and environment.
    #[error("{0}")]
    NotFound(Box<ApiError>),
    /// 409: the request conflicts with the resource's current state.
    #[error("{0}")]
    Conflict(Box<ApiError>),
    /// 429: too many requests. [`ApiError::retry_after`] says how long to wait.
    #[error("{0}")]
    RateLimit(Box<ApiError>),
    /// 5xx: the API failed. These are retried automatically before they reach you.
    #[error("{0}")]
    Server(Box<ApiError>),
    /// Any other HTTP error status (for example 413 for a file above the size limit).
    #[error("{0}")]
    Api(Box<ApiError>),
    /// The request could not be sent or the response could not be read (DNS, TCP, TLS).
    #[error("connection error: {0}")]
    Connection(#[source] Box<dyn std::error::Error + Send + Sync>),
    /// The server did not answer within the request timeout.
    #[error("request timed out after {0:?}")]
    Timeout(Duration),
    /// An operation or workflow run ended failed or cancelled.
    #[error("{0}")]
    OperationFailed(Box<OperationFailure>),
    /// Waiting for an operation or run took longer than the wait limit. The work goes on
    /// server-side; resume with [`DocumentOperations::wait`](crate::DocumentOperations::wait)
    /// or [`WorkflowRuns::wait`](crate::WorkflowRuns::wait).
    #[error("{kind} {id} did not finish within {waited:?}; it is still running and you can wait for it again")]
    WaitTimeout {
        /// `operation` or `workflow run`.
        kind: &'static str,
        /// The id to resume waiting on.
        id: String,
        /// How long this call waited.
        waited: Duration,
    },
    /// A webhook delivery failed signature or timestamp verification.
    #[error("webhook verification failed: {0}")]
    WebhookVerification(String),
    /// The arguments cannot be sent as given (checked before any request is made).
    #[error("invalid input: {0}")]
    InvalidInput(String),
    /// Reading or writing a local file failed.
    #[error("file error: {0}")]
    Io(#[from] std::io::Error),
    /// A response body could not be decoded into the expected type.
    #[error("unexpected response from the API: {0}")]
    Decode(String),
}

impl Error {
    /// The HTTP status of an API error.
    pub fn status(&self) -> Option<u16> {
        self.api_error().map(|error| error.status)
    }

    /// The machine-readable error code: the API's `error.code`, or the code an operation
    /// failed with.
    pub fn code(&self) -> Option<&str> {
        match self {
            Error::OperationFailed(failure) => Some(failure.code.as_str()),
            other => other.api_error().map(|error| error.code.as_str()),
        }
    }

    /// The reference id to quote to support.
    pub fn reference_id(&self) -> Option<&str> {
        self.api_error()
            .and_then(|error| error.reference_id.as_deref())
    }

    /// The API error behind any HTTP error variant.
    pub fn api_error(&self) -> Option<&ApiError> {
        match self {
            Error::BadRequest(error)
            | Error::Validation(error)
            | Error::Authentication(error)
            | Error::PermissionDenied(error)
            | Error::NotFound(error)
            | Error::Conflict(error)
            | Error::RateLimit(error)
            | Error::Server(error)
            | Error::Api(error) => Some(error),
            _ => None,
        }
    }

    /// How long the API asked to wait before retrying (429 and some 503 responses).
    pub fn retry_after(&self) -> Option<Duration> {
        self.api_error().and_then(|error| error.retry_after)
    }

    /// Whether the same call may succeed if sent again later.
    pub fn is_retryable(&self) -> bool {
        match self {
            Error::Connection(_) | Error::Timeout(_) => true,
            // Unless the API says otherwise (an exhausted balance is a final 429).
            Error::RateLimit(error) | Error::Server(error) => {
                error.retryable || error.retry_after.is_some() || error.code.starts_with("HTTP_")
            }
            other => other
                .api_error()
                .is_some_and(|error| error.retryable || matches!(error.status, 408)),
        }
    }

    pub(crate) fn connection(error: impl std::error::Error + Send + Sync + 'static) -> Self {
        Error::Connection(Box::new(error))
    }

    pub(crate) fn decode(context: &str, error: impl fmt::Display) -> Self {
        Error::Decode(format!("{context}: {error}"))
    }

    pub(crate) fn missing_api_key() -> Self {
        Error::Authentication(Box::new(ApiError {
            status: 401,
            code: "API_KEY_MISSING".into(),
            message: format!(
                "No API key is configured. Set WELLFRIEND_API_KEY or call Wellfriend::builder().api_key(..). Create a key at {KEYS_URL}"
            ),
            reference_id: None,
            retryable: false,
            details: None,
            retry_after: None,
            headers: HeaderMap::new(),
        }))
    }

    /// Builds the error for an HTTP error response.
    pub(crate) fn from_api(error: ApiError) -> Self {
        let error = Box::new(error);
        match error.status {
            400 if is_validation_code(&error.code) => Error::Validation(error),
            400 => Error::BadRequest(error),
            401 => Error::Authentication(error),
            403 => Error::PermissionDenied(error),
            404 => Error::NotFound(error),
            409 => Error::Conflict(error),
            422 => Error::Validation(error),
            429 => Error::RateLimit(error),
            500..=599 => Error::Server(error),
            _ => Error::Api(error),
        }
    }
}

/// A 400 whose code says the input itself is invalid counts as a validation error, so a bad
/// tool parameter is an [`Error::Validation`] whichever of 400 or 422 the endpoint uses.
fn is_validation_code(code: &str) -> bool {
    code.ends_with("_INPUT_INVALID")
        || code.ends_with("_PARAMETERS_INVALID")
        || code.contains("VALIDATION")
}

/// An error response from the API.
#[derive(Clone)]
#[non_exhaustive]
pub struct ApiError {
    /// The HTTP status.
    pub status: u16,
    /// The machine-readable code, for example `OPERATION_INPUT_INVALID`.
    pub code: String,
    /// The human-readable message.
    pub message: String,
    /// The reference id to quote to support.
    pub reference_id: Option<String>,
    /// Whether the API says the same request may succeed later.
    pub retryable: bool,
    /// Structured details, when the API sends them.
    pub details: Option<Object>,
    /// The parsed `Retry-After` header.
    pub retry_after: Option<Duration>,
    /// The response headers.
    pub headers: HeaderMap,
}

impl fmt::Debug for ApiError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ApiError")
            .field("status", &self.status)
            .field("code", &self.code)
            .field("message", &self.message)
            .field("reference_id", &self.reference_id)
            .field("retryable", &self.retryable)
            .field("details", &self.details)
            .field("retry_after", &self.retry_after)
            .finish_non_exhaustive()
    }
}

impl fmt::Display for ApiError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.message)?;
        if let Some(reference) = &self.reference_id {
            write!(f, " (reference {reference})")?;
        }
        Ok(())
    }
}

#[derive(Deserialize)]
struct Envelope {
    error: Option<Body>,
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct Body {
    #[serde(default)]
    code: String,
    #[serde(default)]
    message: String,
    reference_id: Option<String>,
    #[serde(default)]
    retryable: bool,
    details: Option<Object>,
}

impl ApiError {
    /// Parses an error response body. Bodies that are not the API's error envelope (for example
    /// an HTML page from a proxy) still give a useful error.
    pub(crate) fn from_parts(status: u16, headers: HeaderMap, body: &[u8]) -> Self {
        let retry_after = crate::retry::parse_retry_after(&headers);
        match serde_json::from_slice::<Envelope>(body)
            .ok()
            .and_then(|envelope| envelope.error)
        {
            Some(parsed) => ApiError {
                status,
                code: if parsed.code.is_empty() {
                    format!("HTTP_{status}")
                } else {
                    parsed.code
                },
                message: if parsed.message.is_empty() {
                    default_message(status)
                } else {
                    parsed.message
                },
                reference_id: parsed.reference_id.filter(|value| !value.is_empty()),
                retryable: parsed.retryable,
                details: parsed.details,
                retry_after,
                headers,
            },
            None => {
                let text = String::from_utf8_lossy(body);
                let snippet: String = text.trim().chars().take(200).collect();
                ApiError {
                    status,
                    code: format!("HTTP_{status}"),
                    message: if snippet.is_empty() || snippet.starts_with('<') {
                        default_message(status)
                    } else {
                        format!("{}: {snippet}", default_message(status))
                    },
                    reference_id: None,
                    retryable: false,
                    details: None,
                    retry_after,
                    headers,
                }
            }
        }
    }
}

fn default_message(status: u16) -> String {
    let reason = reqwest::StatusCode::from_u16(status)
        .ok()
        .and_then(|code| code.canonical_reason())
        .unwrap_or("error");
    format!("The API answered {status} {reason}")
}

/// Why an operation or workflow run failed.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct OperationFailure {
    /// The error code, for example `PDF_DANGEROUS_CONTENT`.
    pub code: String,
    /// The error message.
    pub message: String,
    /// The operation id (for a pipeline, the step that failed), or the workflow run id.
    pub id: String,
    /// For a pipeline, the step that failed (1-based).
    pub step: Option<usize>,
    /// The final state of the operation, when it was an operation.
    pub operation: Option<Box<Operation>>,
    /// The final workflow run, when it was a pipeline or workflow.
    pub run: Option<Box<crate::models::WorkflowRun>>,
}

impl fmt::Display for OperationFailure {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.message.is_empty() {
            write!(f, "{} failed with {}", self.id, self.code)
        } else {
            write!(f, "{} failed with {}: {}", self.id, self.code, self.message)
        }
    }
}