fauna-api 1.0.786

The Fauna SDK for Rust: accounts, Drive, groups, calendar, chats, payments, Parrot and live rooms.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
use std::collections::HashMap;

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

use crate::authentification::{Credentials, PartialProfile};
use crate::error::Result;
use crate::groups::NamedGroup;
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. `balance`
/// is money paid in and `credit` what Fauna gave, both in dollars.
#[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,
    pub credit: 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),
            credit: json["credit"].as_f64().unwrap_or(0.0),
        }
    }
}

/// An account as an admin sees it: profile, verification, permissions and
/// balances. No secrets. `balance` is money paid in and `credit` what Fauna
/// gave, both in dollars.
#[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 credit: 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),
            credit: json["credit"].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?)
}

/// What an admin's `query` found: how many accounts there are, and up to 20 of them.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct AccountQuery {
    pub total: u64,
    pub accounts: Vec<Account>,
}

impl AccountQuery {
    pub fn from_json(json: &Value) -> AccountQuery {
        AccountQuery {
            total: json["total"].as_u64().unwrap_or(0),
            accounts: json["accounts"]
                .as_array()
                .map(|rows| rows.iter().map(Account::from_json).collect())
                .unwrap_or_default(),
        }
    }
}

/// Accounts matching a partial email or name, best first. An empty search lists
/// the first 20 by name, then email.
pub async fn query(credentials: &Credentials, profile: &PartialProfile) -> Result<AccountQuery> {
    let response = client()
        .post(format!("{}/credentials/query", get_url()))
        .header("Authorization", format!("Token {}", credentials.token))
        .json(&json!({ "email": profile.email, "displayName": profile.display_name }))
        .send()
        .await?;
    let json: Value = ok(response).await?.json().await?;
    Ok(AccountQuery::from_json(&json))
}

#[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, 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 API keys (its
    /// `AccountKey` id).
    Credit {
        credit: f64,
        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, api_key } => {
            let mut body = json!({ "email": email, "credit": credit });
            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))
}

/// Give a group `credit` dollars, by its id. Resolves to the group as an admin
/// finds it.
pub async fn grant_group(
    credentials: &Credentials,
    group: &str,
    credit: f64,
) -> Result<NamedGroup> {
    let response = client()
        .post(format!("{}/authentification/grant", get_url()))
        .header("Authorization", format!("Token {}", credentials.token))
        .json(&json!({ "group": group, "credit": credit }))
        .send()
        .await?;
    let json: Value = ok(response).await?.json().await?;
    Ok(NamedGroup::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: the card cost (a percent of the amount plus a fixed dollar
/// part) and Fauna's percent.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct PaymentsSpreads {
    pub card_percent: f64,
    pub card_fixed: f64,
    pub spread_percent: 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?)
}

/// One app's service on one UTC day of Fauna's money, in dollars, signed (refunds
/// count negative). `revenue` is money people paid as it earned: usage paid with
/// bought money, debt repaid, invoices, payment fees. `cost` is what Fauna paid
/// providers and Stripe. `credit` is the given credit spent, which earns nothing.
/// Profit is revenue less cost.
#[derive(Debug, Clone, Serialize)]
pub struct SpreadUsage {
    pub app: String,
    pub service: String,
    pub day: String,
    pub revenue: f64,
    pub cost: f64,
    pub credit: f64,
}

/// Fauna's money by app, service and day, every day there is, oldest first.
pub async fn usage_spread(credentials: &Credentials) -> Result<Vec<SpreadUsage>> {
    let response = client()
        .get(format!("{}/spread/usage", get_url()))
        .header("Authorization", format!("Token {}", credentials.token))
        .send()
        .await?;
    let rows: Vec<Value> = ok(response).await?.json().await?;
    let dollars = |row: &Value, key: &str| row[key].as_f64().unwrap_or(0.0) / 1_000_000.0;
    Ok(rows
        .iter()
        .map(|row| SpreadUsage {
            app: row["app"].as_str().unwrap_or_default().to_string(),
            service: row["service"].as_str().unwrap_or_default().to_string(),
            day: row["day"].as_str().unwrap_or_default().to_string(),
            revenue: dollars(row, "revenueMicros"),
            cost: dollars(row, "costMicros"),
            credit: dollars(row, "creditMicros"),
        })
        .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?)
}