fauna-api 1.0.759

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

use serde::{Deserialize, Serialize};
use serde_json::{Value, json};

use crate::authentification::{Credentials, PartialProfile};
use crate::error::Result;
use crate::http::{client, encode, ok};
use crate::integrations::Platform;

// Private production-admin module. Unlike the rest of fauna-api this keeps its
// own route so the dev app can aim it at the prod Cloud Run server while
// set_route stays pointed at localhost.

static ROUTE: crate::route::Cell = crate::route::cell();

pub fn set_route(route: &str) {
    crate::route::set(&ROUTE, route);
}

pub fn get_url() -> String {
    crate::route::url(&ROUTE)
}

/// One of an account's API keys as an admin sees it: its id, never the key itself.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct AccountKey {
    pub id: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    pub balance: f64,
}

impl AccountKey {
    pub fn from_json(json: &Value) -> AccountKey {
        AccountKey {
            id: match &json["id"] {
                Value::String(id) => id.clone(),
                id => id.to_string(),
            },
            name: json["name"].as_str().map(str::to_string),
            balance: json["balance"].as_f64().unwrap_or(0.0),
        }
    }
}

/// An account as an admin sees it: profile, verification, permissions and
/// balances. No secrets.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Account {
    pub email: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub display_name: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub icon: Option<String>,
    pub phone: String,
    pub email_verified: bool,
    pub phone_verified: bool,
    pub permissions: Vec<String>,
    pub integrations: Vec<Platform>,
    pub balance: f64,
    pub api_keys: Vec<AccountKey>,
}

impl Account {
    pub fn from_json(json: &Value) -> Account {
        let list = |key: &str| json[key].as_array().cloned().unwrap_or_default();
        Account {
            email: match &json["email"] {
                Value::String(email) => email.clone(),
                email => email.to_string(),
            },
            display_name: json["displayName"].as_str().map(str::to_string),
            icon: json["icon"].as_str().map(str::to_string),
            phone: json["phone"].as_str().unwrap_or_default().to_string(),
            email_verified: json["emailVerified"].as_bool() == Some(true),
            phone_verified: json["phoneVerified"].as_bool() == Some(true),
            permissions: list("permissions")
                .iter()
                .map(|permission| match permission {
                    Value::String(permission) => permission.clone(),
                    permission => permission.to_string(),
                })
                .collect(),
            integrations: list("integrations")
                .into_iter()
                .filter_map(|platform| serde_json::from_value(platform).ok())
                .collect(),
            balance: json["balance"].as_f64().unwrap_or(0.0),
            api_keys: list("apiKeys").iter().map(AccountKey::from_json).collect(),
        }
    }
}

pub async fn authorize_token(token: &str) -> Result<Credentials> {
    let response = client()
        .post(format!("{}/authentification/authorize", get_url()))
        .header("Authorization", format!("Token {token}"))
        .send()
        .await?;
    let mut credentials: Credentials = ok(response).await?.json().await?;
    credentials.token = token.to_string();
    Ok(credentials)
}

/// Uses up a handoff code from the production login for the new session token it passes.
pub async fn redeem_handoff(code: &str) -> Result<String> {
    let response = client()
        .post(format!("{}/authentification/handoff/redeem", get_url()))
        .json(&json!({ "code": code }))
        .send()
        .await?;
    Ok(ok(response).await?.text().await?)
}

pub async fn query(credentials: &Credentials, profile: &PartialProfile) -> Result<Vec<Account>> {
    let response = client()
        .post(format!("{}/authentification/query", get_url()))
        .header("Authorization", format!("Token {}", credentials.token))
        .json(&json!({ "email": profile.email, "displayName": profile.display_name }))
        .send()
        .await?;
    let rows: Vec<Value> = ok(response).await?.json().await?;
    Ok(rows.iter().map(Account::from_json).collect())
}

#[derive(Debug, Clone, Deserialize)]
pub struct SessionToken {
    pub token: String,
}

pub async fn session(credentials: &Credentials, email: &str) -> Result<SessionToken> {
    let response = client()
        .post(format!("{}/authentification/session", get_url()))
        .header("Authorization", format!("Token {}", credentials.token))
        .json(&json!({ "email": email }))
        .send()
        .await?;
    Ok(ok(response).await?.json().await?)
}

/// `{ tier } | { permissions } | { credit, group?, apiKey? }` in the TypeScript SDK.
#[derive(Debug, Clone)]
pub enum Grant {
    Tier(String),
    Permissions(Vec<String>),
    /// Dollars to the user's wallet, or to one of their groups (its id) or API
    /// keys (its `AccountKey` id).
    Credit {
        credit: f64,
        group: Option<String>,
        api_key: Option<String>,
    },
}

/// Set a user's tier or permissions, or give them credit.
pub async fn grant(credentials: &Credentials, email: &str, update: &Grant) -> Result<Account> {
    let body = match update {
        Grant::Tier(tier) => json!({ "email": email, "tier": tier }),
        Grant::Permissions(permissions) => json!({ "email": email, "permissions": permissions }),
        Grant::Credit {
            credit,
            group,
            api_key,
        } => {
            let mut body = json!({ "email": email, "credit": credit });
            if let Some(group) = group {
                body["group"] = json!(group);
            }
            if let Some(api_key) = api_key {
                body["apiKey"] = json!(api_key);
            }
            body
        }
    };
    let response = client()
        .post(format!("{}/authentification/grant", get_url()))
        .header("Authorization", format!("Token {}", credentials.token))
        .json(&body)
        .send()
        .await?;
    let json: Value = ok(response).await?.json().await?;
    Ok(Account::from_json(&json))
}

pub async fn remove(credentials: &Credentials, email: &str) -> Result<bool> {
    let response = client()
        .delete(format!(
            "{}/authentification?email={}",
            get_url(),
            encode(email)
        ))
        .header("Authorization", format!("Token {}", credentials.token))
        .send()
        .await?;
    ok(response).await?;
    Ok(true)
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct ParrotSpreads {
    pub llm_spread: f64,
    pub embedder_spread: f64,
    pub image_spread: f64,
    pub video_spread: f64,
    pub audio_spread: f64,
    pub voice_spread: f64,
    pub tts_spread: f64,
    pub decision_spread: f64,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct MarmotSpreads {
    pub search_spread: f64,
    pub proxy_datacenter_per_gb: f64,
    pub proxy_residential_per_gb: f64,
    pub render_per_page: f64,
    pub puppeteer_per_action: f64,
    pub x_tweet_spread: f64,
    pub x_user_spread: f64,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct MapsSpreads {
    pub geocode_spread: f64,
    pub places_spread: f64,
    pub autocomplete_spread: f64,
    pub routes_spread: f64,
    pub weather_spread: f64,
    pub tiles_per_1000_spread: f64,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct TravelSpreads {
    pub flights_spread: f64,
    pub hotels_spread: f64,
}

/// Fauna Payments' fee: percent of the amount plus a fixed dollar part, card cost
/// and spread.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct PaymentsSpreads {
    pub card_percent: f64,
    pub card_fixed: f64,
    pub spread_percent: f64,
    pub spread_fixed: f64,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct GlobalSpreads {
    pub demo_budget_per_day: f64,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct Spreads {
    pub parrot: ParrotSpreads,
    pub marmot: MarmotSpreads,
    pub maps: MapsSpreads,
    pub travel: TravelSpreads,
    pub payments: PaymentsSpreads,
    pub global: GlobalSpreads,
}

pub async fn list_spread(credentials: &Credentials) -> Result<Spreads> {
    let response = client()
        .get(format!("{}/spread", get_url()))
        .header("Authorization", format!("Token {}", credentials.token))
        .send()
        .await?;
    Ok(ok(response).await?.json().await?)
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum SpreadApp {
    Parrot,
    Marmot,
    Maps,
    Travel,
    Payments,
    Global,
}

impl SpreadApp {
    fn as_str(self) -> &'static str {
        match self {
            SpreadApp::Parrot => "parrot",
            SpreadApp::Marmot => "marmot",
            SpreadApp::Maps => "maps",
            SpreadApp::Travel => "travel",
            SpreadApp::Payments => "payments",
            SpreadApp::Global => "global",
        }
    }
}

#[derive(Debug, Clone, Deserialize)]
pub struct SpreadConfig {
    pub app: SpreadApp,
    pub config: HashMap<String, f64>,
}

pub async fn set_spread(
    credentials: &Credentials,
    app: SpreadApp,
    config: &HashMap<String, f64>,
) -> Result<SpreadConfig> {
    let response = client()
        .put(format!("{}/spread/{}", get_url(), encode(app.as_str())))
        .header("Authorization", format!("Token {}", credentials.token))
        .json(&json!({ "config": config }))
        .send()
        .await?;
    Ok(ok(response).await?.json().await?)
}

#[derive(Debug, Clone, Serialize)]
pub struct SpreadUsagePoint {
    pub app: String,
    pub service: String,
    pub day: String,
    pub base: f64,
    pub spread: f64,
    pub samples: f64,
}

#[derive(Debug, Clone, Serialize)]
pub struct SpreadUsage {
    pub since: String,
    pub usage: Vec<SpreadUsagePoint>,
}

// Global usage rollup (all apps/services/days) for the admin spread dashboard.
pub async fn usage_spread(credentials: &Credentials, days: Option<u32>) -> Result<SpreadUsage> {
    let response = client()
        .get(format!(
            "{}/spread/usage?days={}",
            get_url(),
            encode(&days.unwrap_or(30).to_string())
        ))
        .header("Authorization", format!("Token {}", credentials.token))
        .send()
        .await?;
    let value: Value = ok(response).await?.json().await?;
    Ok(SpreadUsage {
        since: value["since"].as_str().unwrap_or_default().to_string(),
        usage: value["usage"]
            .as_array()
            .into_iter()
            .flatten()
            .map(|point| SpreadUsagePoint {
                app: point["app"].as_str().unwrap_or_default().to_string(),
                service: point["service"].as_str().unwrap_or_default().to_string(),
                day: point["day"].as_str().unwrap_or_default().to_string(),
                base: point["baseMicros"].as_f64().unwrap_or(0.0) / 1_000_000.0,
                spread: point["spreadMicros"].as_f64().unwrap_or(0.0) / 1_000_000.0,
                samples: point["samples"].as_f64().unwrap_or(0.0),
            })
            .collect(),
    })
}

/// An add-on as billing.yaml defines it: its Stripe price and the permissions it
/// grants while paid for.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AddonDefinition {
    pub id: String,
    pub name: String,
    pub stripe_price_id: String,
    pub capabilities: Vec<String>,
    pub active: bool,
}

pub async fn list_addons(credentials: &Credentials) -> Result<Vec<AddonDefinition>> {
    let response = client()
        .get(format!("{}/billing/admin/addons", get_url()))
        .header("Authorization", format!("Token {}", credentials.token))
        .send()
        .await?;
    Ok(ok(response).await?.json().await?)
}