fauna-api 1.0.807

The Fauna SDK for Rust: accounts, Drive, groups, calendar, chats, payments, Parrot and live rooms.
Documentation
use std::sync::LazyLock;

use percent_encoding::{AsciiSet, NON_ALPHANUMERIC, utf8_percent_encode};

use crate::error::{Error, Result};

static CLIENT: LazyLock<reqwest::Client> = LazyLock::new(reqwest::Client::new);

/// Characters `encodeURIComponent` leaves alone.
const COMPONENT: &AsciiSet = &NON_ALPHANUMERIC
    .remove(b'-')
    .remove(b'_')
    .remove(b'.')
    .remove(b'!')
    .remove(b'~')
    .remove(b'*')
    .remove(b'\'')
    .remove(b'(')
    .remove(b')');

pub(crate) fn client() -> &'static reqwest::Client {
    &CLIENT
}

pub(crate) fn encode(value: &str) -> String {
    utf8_percent_encode(value, COMPONENT).to_string()
}

/// `if (!response.ok) throw new Error(await response.text())`.
pub(crate) async fn ok(response: reqwest::Response) -> Result<reqwest::Response> {
    if response.status().is_success() {
        return Ok(response);
    }
    let status = response.status().as_u16();
    let body = response.text().await.unwrap_or_default();
    Err(Error::Http { status, body })
}

/// The WebSocket form of an http(s) route: `http` becomes `ws`, `https` becomes `wss`.
pub(crate) fn websocket(url: &str) -> String {
    if let Some(rest) = url.strip_prefix("https://") {
        return format!("wss://{rest}");
    }
    if let Some(rest) = url.strip_prefix("http://") {
        return format!("ws://{rest}");
    }
    url.to_string()
}

/// A request body that reports upload progress, from 0 to 1, as it streams.
pub(crate) fn progress_body(
    data: Vec<u8>,
    on_progress: Option<crate::drive::Progress>,
) -> reqwest::Body {
    const CHUNK: usize = 64 * 1024;
    let total = data.len();
    let chunks: Vec<Vec<u8>> = data.chunks(CHUNK).map(<[u8]>::to_vec).collect();
    let mut sent = 0usize;
    reqwest::Body::wrap_stream(futures_util::stream::iter(chunks.into_iter().map(
        move |chunk| {
            sent += chunk.len();
            if let Some(progress) = &on_progress
                && total > 0
            {
                progress(sent as f64 / total as f64);
            }
            Ok::<_, std::io::Error>(chunk)
        },
    )))
}

/// `new Date(value)` for serde: the ISO strings and epoch milliseconds the server sends.
pub(crate) fn deserialize_date<'de, D: serde::Deserializer<'de>>(
    deserializer: D,
) -> std::result::Result<chrono::DateTime<chrono::Utc>, D::Error> {
    let value = <serde_json::Value as serde::Deserialize>::deserialize(deserializer)?;
    Ok(crate::tickets::parse_date(&value).unwrap_or_default())
}

/// `date.toISOString()` for serde.
pub(crate) fn serialize_date<S: serde::Serializer>(
    date: &chrono::DateTime<chrono::Utc>,
    serializer: S,
) -> std::result::Result<S::Ok, S::Error> {
    serializer.serialize_str(&date.to_rfc3339_opts(chrono::SecondsFormat::Millis, true))
}