kovlet 0.1.0

Kovlet's portable sync client core: sign-in, sync, merge, outbox and files for Rust, Tauri, Swift and Kotlin apps
Documentation
//! Authenticated REST calls: bearer token, device proof, one retry after a 401.

use std::sync::Arc;

use serde_json::Value;

use crate::auth::{rest_error, Auth};
use crate::error::{Error, Result};
use crate::transport::{Body, HttpRequest, HttpResponse};

#[derive(Clone)]
pub(crate) struct Api {
    pub auth: Arc<Auth>,
    /// Wait for a sign-in (true) or fail with `signed_out` straight away.
    pub wait: bool,
}

/// Percent-encodes one path segment (record ids may hold `/`, `?`, unicode).
pub(crate) fn seg(s: &str) -> String {
    form_urlencoded::byte_serialize(s.as_bytes()).collect::<String>().replace('+', "%20")
}

impl Api {
    /// This API, failing with `signed_out` instead of waiting when `wait` is false.
    pub fn waiting(&self, wait: bool) -> Api {
        Api { auth: self.auth.clone(), wait }
    }

    pub fn base(&self) -> &str {
        &self.auth.base
    }

    /// Sends a request with the session's credentials.
    pub async fn send(&self, method: &str, path: &str, json: Option<&Value>) -> Result<HttpResponse> {
        for attempt in 0..2 {
            let creds = if self.wait { self.auth.credentials().await? } else { self.auth.try_credentials().await? };
            let mut headers = vec![
                ("authorization".to_string(), format!("Bearer {}", creds.token)),
                ("accept".to_string(), "application/json".to_string()),
            ];
            if let Some(p) = creds.proof()? {
                headers.push(("kovlet-device-proof".into(), p));
            }
            let body = match json {
                Some(v) => {
                    headers.push(("content-type".into(), "application/json".into()));
                    Body::Bytes(serde_json::to_vec(v)?)
                }
                None => Body::Empty,
            };
            let url = if path.starts_with("http") { path.to_string() } else { format!("{}{}", self.auth.base, path) };
            let res = self
                .auth
                .transport()
                .http(HttpRequest { method: method.into(), url, headers, body, save_to: None })
                .await
                .inspect_err(|_| self.auth.mark_reachable(false))?;
            self.auth.mark_reachable(true);
            if res.status == 401 && attempt == 0 && self.auth.unauthorized(&creds.token).await {
                continue;
            }
            return Ok(res);
        }
        unreachable!()
    }

    /// A JSON request; non-2xx answers become errors.
    pub async fn json(&self, method: &str, path: &str, body: Option<&Value>) -> Result<Value> {
        let res = self.send(method, path, body).await?;
        if !(200..300).contains(&res.status) {
            return Err(rest_error(res.status, &res.body));
        }
        if res.body.is_empty() {
            return Ok(Value::Null);
        }
        serde_json::from_slice(&res.body).map_err(|e| Error::new("invalid_response", e.to_string()))
    }
}