16.9 KiB · text History 2977adf
//! Vigil's Sentry-compatible `/api/0` API.
//!
//! Every call carries `Authorization: Bearer <token>`. Paths end in a
//! slash, as Sentry's do. Each response is kept in both its raw and its
//! parsed form: `--json` prints exactly what the server said, while the
//! human renderers work off the structs.

pub mod models;

use anyhow::{Context, Result, anyhow};
use reqwest::blocking::Client as Http;
use reqwest::{Method, StatusCode};
use serde::de::DeserializeOwned;
use serde_json::{Value, json};
use std::ops::Deref;
use std::time::Duration;
use url::Url;

use models::*;

/// A response in both forms: what the server sent, and what it means.
pub struct Res<T> {
    pub raw: Value,
    pub data: T,
    /// The `next` cursor of Sentry's `Link` header, when there are more.
    pub next_cursor: Option<String>,
}

impl<T> Deref for Res<T> {
    type Target = T;

    fn deref(&self) -> &T {
        &self.data
    }
}

pub struct Client {
    http: Http,
    base: Url,
}

impl Client {
    pub fn new(url: &str, token: &str) -> Result<Self> {
        let base = Url::parse(url).with_context(|| format!("{url} is not a URL"))?;

        let mut auth = reqwest::header::HeaderValue::from_str(&format!("Bearer {token}"))
            .context("the API token has characters that can't go in a header")?;
        auth.set_sensitive(true);

        let mut headers = reqwest::header::HeaderMap::new();
        headers.insert(reqwest::header::AUTHORIZATION, auth);
        headers.insert(
            reqwest::header::ACCEPT,
            reqwest::header::HeaderValue::from_static("application/json"),
        );

        let http = Http::builder()
            .user_agent(concat!("vgl/", env!("CARGO_PKG_VERSION")))
            .default_headers(headers)
            .connect_timeout(Duration::from_secs(15))
            .timeout(Duration::from_secs(60))
            .build()
            .context("building the HTTP client")?;

        Ok(Self { http, base })
    }

    /// `<base>/api/0/<segments…>/`, each segment percent-encoded so a
    /// release version such as `web@1.0+build/7` survives as one.
    pub fn endpoint(&self, segments: &[&str], query: &[(&str, String)]) -> Result<Url> {
        let mut url = self.base.clone();
        {
            let mut path = url
                .path_segments_mut()
                .map_err(|_| anyhow!("{} cannot have a path", self.base))?;
            path.pop_if_empty();
            path.extend(["api", "0"]);
            path.extend(segments);
            // The trailing slash Sentry's paths carry.
            path.push("");
        }
        if !query.is_empty() {
            let mut pairs = url.query_pairs_mut();
            for (k, v) in query {
                pairs.append_pair(k, v);
            }
        }
        Ok(url)
    }

    fn send<T: DeserializeOwned>(
        &self,
        method: Method,
        url: Url,
        body: Option<Value>,
    ) -> Result<Res<T>> {
        let mut req = self.http.request(method, url.clone());
        if let Some(body) = body {
            req = req.json(&body);
        }

        let res = req
            .send()
            .with_context(|| format!("couldn't reach {}", redact(&url)))?;
        let status = res.status();
        let next_cursor = res
            .headers()
            .get(reqwest::header::LINK)
            .and_then(|v| v.to_str().ok())
            .and_then(next_cursor);
        let text = res.text().context("reading the response body")?;

        if !status.is_success() {
            return Err(ApiFailure::new(status, &text).into());
        }

        // 204: no body. Callers that expect one ask for `Value`.
        let raw: Value = if text.trim().is_empty() {
            Value::Null
        } else {
            serde_json::from_str(&text)
                .with_context(|| format!("{} returned something that isn't JSON", redact(&url)))?
        };
        let data = serde_json::from_value(raw.clone()).with_context(|| {
            format!(
                "{} returned JSON this client doesn't understand",
                redact(&url)
            )
        })?;
        Ok(Res {
            raw,
            data,
            next_cursor,
        })
    }

    fn get<T: DeserializeOwned>(
        &self,
        segments: &[&str],
        query: &[(&str, String)],
    ) -> Result<Res<T>> {
        self.send(Method::GET, self.endpoint(segments, query)?, None)
    }

    /// Every page of a list, following `Link` cursors, up to `limit` items.
    fn get_all<T: DeserializeOwned>(
        &self,
        segments: &[&str],
        query: &[(&str, String)],
        limit: Option<usize>,
    ) -> Result<Res<Vec<T>>> {
        let mut raw = Vec::new();
        let mut cursor: Option<String> = None;
        loop {
            let mut q = query.to_vec();
            if let Some(c) = &cursor {
                q.push(("cursor", c.clone()));
            }
            let page: Res<Vec<Value>> = self.get(segments, &q)?;
            raw.extend(page.data);
            if limit.is_some_and(|n| raw.len() >= n) {
                raw.truncate(limit.unwrap_or(usize::MAX));
                break;
            }
            match page.next_cursor {
                Some(next) => cursor = Some(next),
                None => break,
            }
        }
        let data = serde_json::from_value(Value::Array(raw.clone()))
            .context("the server returned JSON this client doesn't understand")?;
        Ok(Res {
            raw: Value::Array(raw),
            data,
            next_cursor: None,
        })
    }

    fn post<T: DeserializeOwned>(&self, segments: &[&str], body: Value) -> Result<Res<T>> {
        self.send(Method::POST, self.endpoint(segments, &[])?, Some(body))
    }

    fn put<T: DeserializeOwned>(
        &self,
        segments: &[&str],
        query: &[(&str, String)],
        body: Value,
    ) -> Result<Res<T>> {
        self.send(Method::PUT, self.endpoint(segments, query)?, Some(body))
    }

    fn delete(&self, segments: &[&str]) -> Result<()> {
        self.send::<Value>(Method::DELETE, self.endpoint(segments, &[])?, None)
            .map(|_| ())
    }

    // ── identity ─────────────────────────────────────────────────────

    pub fn root(&self) -> Result<Res<Root>> {
        self.get(&[], &[])
    }

    // ── organizations and teams ──────────────────────────────────────

    pub fn organizations(&self) -> Result<Res<Vec<Organization>>> {
        self.get_all(&["organizations"], &[], None)
    }

    pub fn teams(&self, org: &str) -> Result<Res<Vec<Team>>> {
        self.get_all(&["organizations", org, "teams"], &[], None)
    }

    // ── projects ─────────────────────────────────────────────────────

    pub fn projects(&self, org: &str) -> Result<Res<Vec<Project>>> {
        self.get_all(&["organizations", org, "projects"], &[], None)
    }

    pub fn project(&self, org: &str, project: &str) -> Result<Res<Project>> {
        self.get(&["projects", org, project], &[])
    }

    pub fn create_project(
        &self,
        org: &str,
        team: &str,
        name: &str,
        slug: Option<&str>,
        platform: Option<&str>,
    ) -> Result<Res<Project>> {
        let mut body = json!({ "name": name });
        if let Some(slug) = slug {
            body["slug"] = json!(slug);
        }
        if let Some(platform) = platform {
            body["platform"] = json!(platform);
        }
        self.post(&["teams", org, team, "projects"], body)
    }

    pub fn update_project(&self, org: &str, project: &str, changes: Value) -> Result<Res<Project>> {
        self.put(&["projects", org, project], &[], changes)
    }

    pub fn delete_project(&self, org: &str, project: &str) -> Result<()> {
        self.delete(&["projects", org, project])
    }

    // ── keys ─────────────────────────────────────────────────────────

    pub fn keys(&self, org: &str, project: &str) -> Result<Res<Vec<Key>>> {
        self.get_all(&["projects", org, project, "keys"], &[], None)
    }

    pub fn create_key(&self, org: &str, project: &str, name: Option<&str>) -> Result<Res<Key>> {
        let body = match name {
            Some(name) => json!({ "name": name }),
            None => json!({}),
        };
        self.post(&["projects", org, project, "keys"], body)
    }

    pub fn update_key(
        &self,
        org: &str,
        project: &str,
        key: &str,
        changes: Value,
    ) -> Result<Res<Key>> {
        self.put(&["projects", org, project, "keys", key], &[], changes)
    }

    pub fn delete_key(&self, org: &str, project: &str, key: &str) -> Result<()> {
        self.delete(&["projects", org, project, "keys", key])
    }

    // ── issues ───────────────────────────────────────────────────────

    pub fn issues(
        &self,
        org: &str,
        project: &str,
        query: &str,
        limit: usize,
    ) -> Result<Res<Vec<Issue>>> {
        let q = [
            ("query", query.to_string()),
            ("per_page", limit.min(100).to_string()),
        ];
        self.get_all(&["projects", org, project, "issues"], &q, Some(limit))
    }

    /// Sets the status of the issues named by `ids` (short ids or UUIDs).
    /// `false` when none of them matched.
    pub fn set_issue_status(
        &self,
        org: &str,
        project: &str,
        ids: &[String],
        status: &str,
    ) -> Result<bool> {
        let query: Vec<(&str, String)> = ids.iter().map(|id| ("id", id.clone())).collect();
        let res: Res<Value> = self.put(
            &["projects", org, project, "issues"],
            &query,
            json!({ "status": status }),
        )?;
        Ok(!res.raw.is_null())
    }

    // ── releases and monitors ────────────────────────────────────────

    pub fn releases(
        &self,
        org: &str,
        project: Option<&str>,
        limit: usize,
    ) -> Result<Res<Vec<Release>>> {
        let q = [("per_page", limit.min(100).to_string())];
        match project {
            Some(p) => self.get_all(&["projects", org, p, "releases"], &q, Some(limit)),
            None => self.get_all(&["organizations", org, "releases"], &q, Some(limit)),
        }
    }

    pub fn release(&self, org: &str, version: &str) -> Result<Res<Release>> {
        self.get(&["organizations", org, "releases", version], &[])
    }

    pub fn monitors(&self, org: &str) -> Result<Res<Vec<Monitor>>> {
        self.get_all(&["organizations", org, "monitors"], &[], None)
    }

    pub fn uptime(&self, org: &str) -> Result<Res<Vec<UptimeMonitor>>> {
        self.get_all(&["organizations", org, "uptime"], &[], None)
    }
}

/// The `next` cursor of a Sentry `Link` header, if it says there are
/// results there.
pub fn next_cursor(link: &str) -> Option<String> {
    link.split(',').find_map(|part| {
        let attrs: Vec<&str> = part.split(';').map(str::trim).collect();
        let has = |want: &str| attrs.contains(&want);
        if !has(r#"rel="next""#) || !has(r#"results="true""#) {
            return None;
        }
        attrs.iter().find_map(|a| {
            a.strip_prefix("cursor=\"")
                .and_then(|c| c.strip_suffix('"'))
                .map(str::to_string)
        })
    })
}

/// A failed request, with the reason the server gave.
#[derive(Debug)]
pub struct ApiFailure {
    pub status: StatusCode,
    /// Sentry's `{"detail": "…"}`.
    pub detail: Option<String>,
    /// A validation failure's `{"field": ["reason", …]}`, flattened.
    pub fields: Vec<(String, String)>,
}

impl ApiFailure {
    pub fn new(status: StatusCode, body: &str) -> Self {
        let parsed: Option<Value> = serde_json::from_str(body).ok();
        let detail = parsed
            .as_ref()
            .and_then(|v| v.get("detail"))
            .and_then(|d| match d {
                Value::String(s) => Some(s.clone()),
                Value::Array(items) => items.first().and_then(|i| i.as_str()).map(str::to_string),
                _ => None,
            })
            .filter(|d| !d.trim().is_empty());

        let mut fields = Vec::new();
        if detail.is_none()
            && let Some(Value::Object(map)) = &parsed
        {
            for (field, reasons) in map {
                let reasons = match reasons {
                    Value::Array(items) => items
                        .iter()
                        .map(|i| i.as_str().map_or_else(|| i.to_string(), str::to_string))
                        .collect::<Vec<_>>()
                        .join(", "),
                    Value::String(s) => s.clone(),
                    other => other.to_string(),
                };
                fields.push((field.clone(), reasons));
            }
        }

        Self {
            status,
            detail,
            fields,
        }
    }
}

impl std::fmt::Display for ApiFailure {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let code = self.status.as_u16();
        if let Some(detail) = &self.detail {
            return write!(f, "{detail} ({code})");
        }
        if !self.fields.is_empty() {
            write!(f, "the server refused these values ({code}):")?;
            for (field, reason) in &self.fields {
                write!(f, "\n  {field}: {reason}")?;
            }
            return Ok(());
        }
        match self.status {
            StatusCode::UNAUTHORIZED => {
                write!(f, "the token was rejected; run `vgl login` again ({code})")
            }
            status => write!(f, "HTTP {status}"),
        }
    }
}

impl std::error::Error for ApiFailure {}

/// Query strings never carry the token, but drop them from URLs in error
/// messages all the same.
fn redact(url: &Url) -> String {
    let mut url = url.clone();
    url.set_query(None);
    url.to_string()
}

#[cfg(test)]
mod tests {
    use super::*;

    fn client(base: &str) -> Client {
        Client::new(base, "vgl_test").unwrap()
    }

    #[test]
    fn builds_api_paths_with_trailing_slashes() {
        let url = client("https://vigil.example.com")
            .endpoint(&["projects", "acme", "web", "keys"], &[])
            .unwrap();
        assert_eq!(
            url.as_str(),
            "https://vigil.example.com/api/0/projects/acme/web/keys/"
        );

        let root = client("https://vigil.example.com/")
            .endpoint(&[], &[])
            .unwrap();
        assert_eq!(root.as_str(), "https://vigil.example.com/api/0/");
    }

    #[test]
    fn keeps_a_path_prefix_and_encodes_segments() {
        let url = client("https://example.com/vigil")
            .endpoint(
                &["organizations", "acme", "releases", "web@1.0+build/7"],
                &[("query", "is:unresolved level:error".into())],
            )
            .unwrap();
        assert_eq!(
            url.as_str(),
            "https://example.com/vigil/api/0/organizations/acme/releases/web@1.0+build%2F7/?query=is%3Aunresolved+level%3Aerror"
        );
    }

    #[test]
    fn repeats_query_keys() {
        let url = client("http://localhost:4000")
            .endpoint(
                &["projects", "o", "p", "issues"],
                &[("id", "1".into()), ("id", "2".into())],
            )
            .unwrap();
        assert_eq!(url.query(), Some("id=1&id=2"));
    }

    #[test]
    fn follows_only_next_links_with_results() {
        let link = r#"<http://x/?cursor=0:0:1>; rel="previous"; results="false"; cursor="0:0:1", <http://x/?cursor=0:100:0>; rel="next"; results="true"; cursor="0:100:0""#;
        assert_eq!(next_cursor(link).as_deref(), Some("0:100:0"));

        let last = r#"<http://x/>; rel="previous"; results="true"; cursor="0:0:1", <http://x/>; rel="next"; results="false"; cursor="0:200:0""#;
        assert_eq!(next_cursor(last), None);
    }

    #[test]
    fn failures_carry_the_servers_detail_or_fields() {
        let denied = ApiFailure::new(
            StatusCode::FORBIDDEN,
            r#"{"detail":"You do not have permission to perform this action."}"#,
        );
        assert_eq!(
            denied.to_string(),
            "You do not have permission to perform this action. (403)"
        );

        let invalid = ApiFailure::new(
            StatusCode::BAD_REQUEST,
            r#"{"slug":["is taken"],"platform":["is invalid"]}"#,
        );
        assert_eq!(
            invalid.to_string(),
            "the server refused these values (400):\n  platform: is invalid\n  slug: is taken"
        );

        assert_eq!(
            ApiFailure::new(StatusCode::BAD_GATEWAY, "<html>").to_string(),
            "HTTP 502 Bad Gateway"
        );
    }
}