townos-api 0.0.2

Client for the Town OS control plane (systemcontroller) HTTP API
Documentation
use serde::Deserialize;

/// An RFC 9457 problem detail, when the server sent one.
///
/// The control plane emits these for most refusals; older handlers still answer
/// with echo's `{"message": ...}`. [`ApiError::detail`] reads either, so callers
/// that only want something to show a user never have to tell them apart.
#[derive(Debug, Clone, Deserialize)]
pub struct Problem {
    #[serde(default)]
    pub r#type: String,
    #[serde(default)]
    pub title: String,
    #[serde(default)]
    pub status: u16,
    #[serde(default)]
    pub detail: String,
}

#[derive(Debug, thiserror::Error)]
pub enum Error {
    /// The server answered with a non-200 status.
    ///
    /// The control plane returns 200 for every success, including the ones that
    /// carry no body, so anything else is a refusal worth surfacing.
    #[error("{method} {path}: {detail}")]
    Status {
        method: &'static str,
        path: String,
        status: u16,
        detail: String,
        /// Boxed because this variant otherwise sets the size of every `Result`
        /// the crate returns, and `Problem` is 80 bytes of it. Every method here
        /// is fallible, so the cost is paid on every call and the refusal that
        /// needs the allocation is the rare path.
        problem: Option<Box<Problem>>,
        body: String,
    },

    #[error("transport: {0}")]
    Transport(#[from] reqwest::Error),

    #[error("decoding {path}: {source}")]
    Decode {
        path: String,
        #[source]
        source: serde_json::Error,
    },

    #[error("invalid base URL: {0}")]
    BaseUrl(String),

    /// A local file could not be read or written. Only the two archive calls
    /// touch the filesystem, and a failure there is the user's disk rather than
    /// the box, so it must not read as an API error.
    #[error("{path}: {source}")]
    Io {
        path: String,
        #[source]
        source: std::io::Error,
    },

    /// The box did not answer within the deadline.
    ///
    /// Distinct from `Transport` on purpose. A transport error means something
    /// said no — the connection was refused, the name did not resolve, TLS was
    /// rejected — and the user can usually act on it. This means the box said
    /// nothing at all, which points at a different set of causes: a tunnel that
    /// is down, a machine that is asleep, a box under load. Telling a user
    /// "it did not answer" when the truth is "it refused" sends them looking in
    /// the wrong place.
    #[error("{verb} {path}: no answer within {after:?}")]
    Timeout {
        verb: &'static str,
        path: String,
        after: std::time::Duration,
    },

    /// No session token is set but the endpoint requires one.
    #[error("not authenticated")]
    Unauthenticated,
}

impl Error {
    pub(crate) fn status(method: &'static str, path: &str, status: u16, body: String) -> Self {
        let problem = serde_json::from_str::<Problem>(&body)
            .ok()
            .filter(|p| !p.r#type.is_empty() && p.status != 0)
            .map(Box::new);

        let detail = problem
            .as_ref()
            .map(|p| p.detail.clone())
            .filter(|d| !d.is_empty())
            .or_else(|| {
                serde_json::from_str::<serde_json::Value>(&body)
                    .ok()
                    .and_then(|v| {
                        v.get("detail")
                            .or_else(|| v.get("message"))
                            .and_then(|m| m.as_str().map(str::to_owned))
                    })
            })
            .filter(|d| !d.is_empty())
            .unwrap_or_else(|| {
                if body.trim().is_empty() {
                    format!("status {status}")
                } else {
                    body.trim().to_owned()
                }
            });

        Error::Status {
            method,
            path: path.to_owned(),
            status,
            detail,
            problem,
            body,
        }
    }

    /// The HTTP status, when this was a refusal from the server.
    pub fn http_status(&self) -> Option<u16> {
        match self {
            Error::Status { status, .. } => Some(*status),
            _ => None,
        }
    }

    /// Whether the session token was rejected, so the UI should send the user
    /// back to the sign-in screen rather than showing an error.
    ///
    /// A 401 is a token the server will not accept at all; a 403 is a token it
    /// accepts from an account that lacks the grant, which is a real answer and
    /// not a reason to sign out.
    pub fn is_unauthenticated(&self) -> bool {
        matches!(self, Error::Unauthenticated) || self.http_status() == Some(401)
    }

    /// Whether the account is authenticated but lacks the grant this endpoint
    /// needs. Most write paths are admin-only, so a read-only account hits this
    /// routinely and it should read as "not yours to change", not as a fault.
    pub fn is_forbidden(&self) -> bool {
        self.http_status() == Some(403)
    }

    /// Whether the box could not be reached at all, as opposed to answering
    /// with something the user needs to know about.
    ///
    /// Both of these mean "there is nothing to talk to here": a transport
    /// failure is a refusal, a timeout is a silence. The UI groups them because
    /// the user's next move is the same for both — check the address, check the
    /// tunnel — and neither is worth the alarm of a red error on a first run
    /// against a box that is simply not up yet.
    pub fn is_unreachable(&self) -> bool {
        matches!(self, Error::Transport(_) | Error::Timeout { .. })
    }

    /// A message fit to put in front of a user.
    pub fn detail(&self) -> String {
        match self {
            Error::Status { detail, .. } => detail.clone(),
            other => other.to_string(),
        }
    }
}

pub type Result<T> = std::result::Result<T, Error>;