nle-cloud-sdk 0.1.1

Unofficial asynchronous Rust SDK for the NLECloud (新大陆物联网云平台) IoT platform
Documentation
//! Core HTTP client, configuration builder, and request execution logic.

use crate::envelope::{ApiEnvelope, EmptyEnvelope};
use crate::error::{Result, SdkError};
use reqwest::Method;
use reqwest::header::{CONTENT_TYPE, HeaderMap, HeaderValue};
use serde::de::DeserializeOwned;
use std::time::Duration;
use url::Url;

/// Default API endpoint for the NLECloud platform.
pub const DEFAULT_BASE_URL: &str = "http://api.nlecloud.com";

/// Default request timeout (15 seconds).
pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(15);

/// An asynchronous, thread-safe client for the NLECloud IoT API.
#[derive(Debug, Clone)]
pub struct NleCloudClient {
    pub(crate) http_client: reqwest::Client,
    pub(crate) base_url: Url,
    pub(crate) token: Option<String>,
}

impl NleCloudClient {
    /// Returns a new `NleCloudClientBuilder` with default configurations.
    pub fn builder() -> NleCloudClientBuilder {
        NleCloudClientBuilder::new()
    }

    /// Creates a new client with the default base URL and no token.
    pub fn new() -> Result<Self> {
        Self::builder().build()
    }

    /// Creates a new client with a specified base URL.
    pub fn with_base_url(base_url: impl AsRef<str>) -> Result<Self> {
        Self::builder().base_url(base_url.as_ref()).build()
    }

    /// Returns a new immutable client clone configured with the given authentication token.
    pub fn with_token(&self, token: impl Into<String>) -> Self {
        Self {
            http_client: self.http_client.clone(),
            base_url: self.base_url.clone(),
            token: Some(token.into()),
        }
    }

    /// Returns the configured base URL.
    pub fn base_url(&self) -> &Url {
        &self.base_url
    }

    /// Returns the currently active authentication token, if any.
    pub fn token(&self) -> Option<&str> {
        self.token.as_deref()
    }

    /// Resolves an endpoint path against the client's base URL.
    pub(crate) fn build_url(&self, path: &str) -> Result<Url> {
        let clean_path = path.trim_start_matches('/');
        // Ensure base_url has trailing slash for path appending
        let base_str = self.base_url.as_str();
        let formatted_base = if base_str.ends_with('/') {
            self.base_url.clone()
        } else {
            Url::parse(&format!("{}/", base_str))?
        };
        Ok(formatted_base.join(clean_path)?)
    }

    /// Resolves the effective token (explicit override or fallback to client token).
    pub(crate) fn resolve_token<'a>(&'a self, explicit: Option<&'a str>) -> Result<&'a str> {
        if let Some(t) = explicit.filter(|t| !t.trim().is_empty()) {
            return Ok(t);
        }
        self.token.as_deref().ok_or_else(|| {
            SdkError::Authentication(
                "AccessToken is required but was not provided or configured".to_string(),
            )
        })
    }

    /// Internal request execution for endpoints returning typed envelope payloads.
    pub(crate) async fn request_with_envelope<T: DeserializeOwned>(
        &self,
        method: Method,
        path: &str,
        query: &[(&str, &str)],
        body: Option<serde_json::Value>,
        token_override: Option<&str>,
        require_auth: bool,
    ) -> Result<T> {
        let mut url = self.build_url(path)?;
        if !query.is_empty() {
            let mut pairs = url.query_pairs_mut();
            for (k, v) in query {
                pairs.append_pair(k, v);
            }
        }

        let mut headers = HeaderMap::new();
        headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));

        if require_auth {
            let token = self.resolve_token(token_override)?;
            let val = HeaderValue::from_str(token).map_err(|e| {
                SdkError::InvalidParameter(format!("Invalid AccessToken header value: {e}"))
            })?;
            headers.insert("AccessToken", val);
        }

        let mut request = self.http_client.request(method, url).headers(headers);

        if let Some(b) = body {
            request = request.json(&b);
        }

        let response = request.send().await?;
        let envelope: ApiEnvelope<T> = response.json().await?;
        envelope.into_result()
    }

    /// Internal request execution for void/status-only operations.
    pub(crate) async fn request_empty(
        &self,
        method: Method,
        path: &str,
        query: &[(&str, &str)],
        body: Option<serde_json::Value>,
        token_override: Option<&str>,
        require_auth: bool,
    ) -> Result<()> {
        let mut url = self.build_url(path)?;
        if !query.is_empty() {
            let mut pairs = url.query_pairs_mut();
            for (k, v) in query {
                pairs.append_pair(k, v);
            }
        }

        let mut headers = HeaderMap::new();
        headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));

        if require_auth {
            let token = self.resolve_token(token_override)?;
            let val = HeaderValue::from_str(token).map_err(|e| {
                SdkError::InvalidParameter(format!("Invalid AccessToken header value: {e}"))
            })?;
            headers.insert("AccessToken", val);
        }

        let mut request = self.http_client.request(method, url).headers(headers);

        if let Some(b) = body {
            request = request.json(&b);
        }

        let response = request.send().await?;
        let envelope: EmptyEnvelope = response.json().await?;
        envelope.into_result()
    }
}

/// Builder for constructing [`NleCloudClient`] instances with customized settings.
#[derive(Debug, Clone)]
pub struct NleCloudClientBuilder {
    base_url: Option<String>,
    token: Option<String>,
    timeout: Option<Duration>,
    custom_client: Option<reqwest::Client>,
}

impl Default for NleCloudClientBuilder {
    fn default() -> Self {
        Self::new()
    }
}

impl NleCloudClientBuilder {
    /// Creates a new builder initialized with defaults.
    pub fn new() -> Self {
        Self {
            base_url: None,
            token: None,
            timeout: None,
            custom_client: None,
        }
    }

    /// Sets the API base URL.
    pub fn base_url(mut self, url: impl Into<String>) -> Self {
        self.base_url = Some(url.into());
        self
    }

    /// Sets the default authentication access token.
    pub fn token(mut self, token: impl Into<String>) -> Self {
        self.token = Some(token.into());
        self
    }

    /// Sets the request timeout duration.
    pub fn timeout(mut self, timeout: Duration) -> Self {
        self.timeout = Some(timeout);
        self
    }

    /// Configures a custom `reqwest::Client` instance.
    pub fn custom_client(mut self, client: reqwest::Client) -> Self {
        self.custom_client = Some(client);
        self
    }

    /// Builds and returns the configured [`NleCloudClient`].
    pub fn build(self) -> Result<NleCloudClient> {
        let base_url = match self.base_url {
            Some(ref u) => Url::parse(u)?,
            None => Url::parse(DEFAULT_BASE_URL)?,
        };

        let http_client = match self.custom_client {
            Some(c) => c,
            None => {
                let timeout = self.timeout.unwrap_or(DEFAULT_TIMEOUT);
                reqwest::Client::builder().timeout(timeout).build()?
            }
        };

        Ok(NleCloudClient {
            http_client,
            base_url,
            token: self.token,
        })
    }
}