azure-devops 0.1.0

Idiomatic Rust client for Azure DevOps REST APIs
Documentation
use crate::auth::Credentials;
use crate::error::{ AzureDevOpsError, Result };
use reqwest::{ Method, StatusCode };
use serde::de::DeserializeOwned;
use serde::Serialize;
use tracing::debug;
use url::Url;

/// Shared HTTP layer that handles authentication, URL construction,
/// API version headers, serialization, and error mapping.
#[derive(Debug, Clone)]
pub(crate) struct HttpClient {
    inner: reqwest::Client,
    base_url: Url,
    credentials: Credentials,
    api_version: String,
}

impl HttpClient {
    pub(crate) fn new(
        inner: reqwest::Client,
        base_url: Url,
        credentials: Credentials,
        api_version: String
    ) -> Self {
        Self {
            inner,
            base_url,
            credentials,
            api_version,
        }
    }

    /// Get the base URL for constructing public URLs (e.g. status badges).
    pub(crate) fn base_url(&self) -> &Url {
        &self.base_url
    }

    /// Build a request URL for an Azure DevOps REST API endpoint.
    ///
    /// Format: `{base_url}/{organization}/_apis/{path}?api-version={version}`
    /// Additional query parameters are appended as needed.
    pub(crate) fn build_url(&self, path: &str, query: &[(&str, &str)]) -> Result<Url> {
        let mut url = self.base_url.join(path)?;

        {
            let mut params = url.query_pairs_mut();
            params.append_pair(crate::constants::hdr::API_VERSION, &self.api_version);
            for (key, value) in query {
                params.append_pair(key, value);
            }
        }

        debug!("built URL: {url}");
        Ok(url)
    }

    /// Perform a GET request and deserialize the response.
    pub(crate) async fn get<T: DeserializeOwned>(
        &self,
        path: &str,
        query: &[(&str, &str)]
    ) -> Result<T> {
        let url = self.build_url(path, query)?;
        self.execute::<(), T>(Method::GET, url, crate::constants::ct::JSON, None).await
    }

    /// Perform a POST request with a JSON body and deserialize the response.
    pub(crate) async fn post<B: Serialize, T: DeserializeOwned>(
        &self,
        path: &str,
        query: &[(&str, &str)],
        body: Option<&B>
    ) -> Result<T> {
        let url = self.build_url(path, query)?;
        self.execute(Method::POST, url, crate::constants::ct::JSON, body).await
    }

    /// Perform a POST request with `application/json-patch+json` content type.
    ///
    /// Used for Azure DevOps JSON Patch operations (creating/updating work items).
    pub(crate) async fn post_json_patch<T: DeserializeOwned>(
        &self,
        path: &str,
        query: &[(&str, &str)],
        body: &serde_json::Value
    ) -> Result<T> {
        let url = self.build_url(path, query)?;
        self.execute::<serde_json::Value, T>(
            Method::POST,
            url,
            crate::constants::ct::JSON_PATCH,
            Some(body)
        ).await
    }

    /// Perform a PATCH request with a JSON body and deserialize the response.
    pub(crate) async fn patch<B: Serialize, T: DeserializeOwned>(
        &self,
        path: &str,
        query: &[(&str, &str)],
        body: Option<&B>
    ) -> Result<T> {
        let url = self.build_url(path, query)?;
        self.execute(Method::PATCH, url, crate::constants::ct::JSON, body).await
    }

    /// Perform a PATCH request with `application/json-patch+json` content type.
    ///
    /// Used for Azure DevOps JSON Patch operations (updating work items).
    pub(crate) async fn patch_json_patch<T: DeserializeOwned>(
        &self,
        path: &str,
        query: &[(&str, &str)],
        body: &serde_json::Value
    ) -> Result<T> {
        let url = self.build_url(path, query)?;
        self.execute::<serde_json::Value, T>(
            Method::PATCH,
            url,
            crate::constants::ct::JSON_PATCH,
            Some(body)
        ).await
    }

    /// Perform a PUT request with a JSON body and deserialize the response.
    pub(crate) async fn put<B: Serialize, T: DeserializeOwned>(
        &self,
        path: &str,
        query: &[(&str, &str)],
        body: &B
    ) -> Result<T> {
        let url = self.build_url(path, query)?;
        self.execute(Method::PUT, url, crate::constants::ct::JSON, Some(body)).await
    }

    /// Perform a DELETE request and deserialize the response.
    pub(crate) async fn delete<T: DeserializeOwned>(
        &self,
        path: &str,
        query: &[(&str, &str)]
    ) -> Result<T> {
        let url = self.build_url(path, query)?;
        self.execute::<(), T>(Method::DELETE, url, crate::constants::ct::JSON, None).await
    }

    /// Core execution method: applies auth, sends request, handles errors.
    async fn execute<B: Serialize, T: DeserializeOwned>(
        &self,
        method: Method,
        url: Url,
        content_type: &str,
        body: Option<&B>
    ) -> Result<T> {
        let mut request = self.inner.request(method.clone(), url.clone());

        request = self.credentials.apply(request);

        request = request.header(crate::constants::hdr::ACCEPT, crate::constants::ct::JSON);

        if let Some(b) = body {
            request = request.header(crate::constants::hdr::CONTENT_TYPE, content_type);
            request = request.json(b);
        }

        debug!("{} {}", method, url);

        let response = request.send().await?;

        let status = response.status();

        if status.is_success() {
            // 204 No Content — return unit-like default
            if status == StatusCode::NO_CONTENT {
                return serde_json
                    ::from_str(crate::constants::NULL_JSON)
                    .map_err(AzureDevOpsError::from);
            }
            let text = response.text().await?;
            debug!("response body: {text}");
            match serde_json::from_str::<T>(&text) {
                Ok(val) => Ok(val),
                Err(direct_err) => {
                    // Azure DevOps wraps list responses in {"count": N, "value": [...]}.
                    // If direct deserialization fails (e.g. expected Vec<T> but got a map),
                    // try extracting just the "value" array.
                    if let Ok(json) = serde_json::from_str::<serde_json::Value>(&text) {
                        if let Some(value) = json.get("value") {
                            if let Ok(unwrapped) = serde_json::from_value::<T>(value.clone()) {
                                return Ok(unwrapped);
                            }
                        }
                    }
                    Err(AzureDevOpsError::from(direct_err))
                }
            }
        } else if status == StatusCode::UNAUTHORIZED || status == StatusCode::FORBIDDEN {
            let body = response.text().await.unwrap_or_default();
            Err(AzureDevOpsError::Auth(body))
        } else if status == StatusCode::TOO_MANY_REQUESTS {
            let retry_after = response
                .headers()
                .get(crate::constants::hdr::RETRY_AFTER)
                .and_then(|v| v.to_str().ok())
                .and_then(|v| v.parse::<u64>().ok());
            Err(AzureDevOpsError::RateLimited { retry_after })
        } else {
            let body = response.text().await.unwrap_or_default();
            // Attempt to extract the Azure DevOps error message
            let message = serde_json
                ::from_str::<serde_json::Value>(&body)
                .ok()
                .and_then(|v| v.get(crate::constants::JSON_MESSAGE_KEY).cloned())
                .and_then(|m| m.as_str().map(String::from))
                .unwrap_or(body);
            Err(AzureDevOpsError::Api {
                status: status.as_u16(),
                message,
            })
        }
    }
}