fauna-api 1.0.854

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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
use std::collections::HashMap;
use std::sync::Arc;

use chrono::{DateTime, Utc};
use futures_util::{SinkExt, StreamExt};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use tokio::sync::mpsc;
use tokio_tungstenite::tungstenite::Message;

use crate::authentification::{Credentials, PartialProfile, Profile};
use crate::billing::PageQuery;
use crate::error::{Error, Result};
use crate::groups::NamedGroup;
use crate::http::{client, encode, ok, websocket};
use crate::private::authentification::Account;
use crate::tickets::{optional, parse_date};

// 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)
}

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))
}

/// Ban an account, or lift its ban with `banned` false. A ban covers its email, its phone and
/// the addresses its sessions came from, signs it out everywhere and stops what it runs.
pub async fn ban(credentials: &Credentials, profile: &Profile, banned: bool) -> Result<Account> {
    let response = client()
        .post(format!("{}/authentification/ban", get_url()))
        .header("Authorization", format!("Token {}", credentials.token))
        .json(&json!({ "email": profile.email, "banned": banned }))
        .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 x_tweet_spread: f64,
    pub x_user_spread: f64,
}

/// Termite's percents on Google's price for machines and storage, and its egress spread.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct TermiteSpreads {
    pub machine_spread_percent: f64,
    pub storage_spread_percent: f64,
    pub egress_spread_per_gb: 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 termite: TermiteSpreads,
    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,
    Termite,
    Maps,
    Travel,
    Payments,
    Global,
}

impl SpreadApp {
    fn as_str(self) -> &'static str {
        match self {
            SpreadApp::Parrot => "parrot",
            SpreadApp::Marmot => "marmot",
            SpreadApp::Termite => "termite",
            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?)
}

/// A newsletter to send: its subject, its plain text and, optionally, its HTML. Without HTML,
/// Fauna's email layout carries the text. `test` sends it only to yourself.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct NewsletterDraft {
    pub subject: String,
    pub text: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub html: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub test: Option<bool>,
}

/// A send that started: the newsletter (None for a test) and how many people it's going to.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct NewsletterSend {
    pub id: Option<String>,
    pub recipients: u64,
}

impl NewsletterSend {
    pub fn from_json(json: &Value) -> NewsletterSend {
        NewsletterSend {
            id: match &json["id"] {
                Value::Null => None,
                Value::String(id) => Some(id.clone()),
                id => Some(id.to_string()),
            },
            recipients: json["recipients"].as_u64().unwrap_or(0),
        }
    }
}

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum NewsletterStatus {
    #[default]
    Sending,
    Sent,
    Failed,
}

/// One newsletter and how far its send has got. `skipped` counts people who were
/// unverified, unsubscribed or banned by the time it reached them.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Newsletter {
    pub id: String,
    pub subject: String,
    pub created_at: DateTime<Utc>,
    pub status: NewsletterStatus,
    pub recipients: u64,
    pub sent: u64,
    pub skipped: u64,
    pub failed: u64,
    pub finished_at: Option<DateTime<Utc>>,
}

impl Newsletter {
    pub fn from_json(json: &Value) -> Newsletter {
        let count = |key: &str| json[key].as_u64().unwrap_or(0);
        Newsletter {
            id: match &json["id"] {
                Value::String(id) => id.clone(),
                id => id.to_string(),
            },
            subject: json["subject"].as_str().unwrap_or_default().to_string(),
            created_at: parse_date(&json["createdAt"]).unwrap_or_default(),
            status: serde_json::from_value(json["status"].clone()).unwrap_or_default(),
            recipients: count("recipients"),
            sent: count("sent"),
            skipped: count("skipped"),
            failed: count("failed"),
            finished_at: parse_date(&json["finishedAt"]),
        }
    }
}

/// How many people a newsletter would reach now, and every newsletter sent, newest first.
#[derive(Debug, Clone, Serialize)]
pub struct Newsletters {
    pub audience: u64,
    pub newsletters: Vec<Newsletter>,
}

impl Newsletters {
    pub fn from_json(json: &Value) -> Newsletters {
        Newsletters {
            audience: json["audience"].as_u64().unwrap_or(0),
            newsletters: json["newsletters"]
                .as_array()
                .map(|rows| rows.iter().map(Newsletter::from_json).collect())
                .unwrap_or_default(),
        }
    }
}

/// Send a newsletter to every account with a verified email that hasn't unsubscribed and
/// isn't banned, one email a second, or with `test`, only to yourself. Every email carries
/// an unsubscribe link.
pub async fn send_newsletter(
    credentials: &Credentials,
    draft: &NewsletterDraft,
) -> Result<NewsletterSend> {
    let response = client()
        .post(format!("{}/newsletter", get_url()))
        .header("Authorization", format!("Token {}", credentials.token))
        .json(draft)
        .send()
        .await?;
    let json: Value = ok(response).await?.json().await?;
    Ok(NewsletterSend::from_json(&json))
}

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

/// A suite the Tests card runs on the CI runner, through tests.yml.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum TestSuite {
    #[default]
    BlackBox,
    Termite,
    Providers,
    Live,
    Bench,
    Big,
    Gpu,
    Acceptance,
}

/// `Queued` until the runner reports its start, `Running` until its end, then whether it all
/// passed.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum TestRunStatus {
    #[default]
    Queued,
    Running,
    Passed,
    Failed,
}

/// One run of a suite: who started it, what it may spend and what its tests spent, in dollars.
/// `reason` is why it failed beyond its tests: GitHub didn't start it, or the runner broke.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TestRun {
    pub id: String,
    pub suite: TestSuite,
    pub limit: f64,
    pub by: String,
    pub status: TestRunStatus,
    pub passed: u64,
    pub failed: u64,
    pub skipped: u64,
    pub spent: f64,
    pub reason: Option<String>,
    pub created_at: DateTime<Utc>,
    pub finished_at: Option<DateTime<Utc>>,
}

impl TestRun {
    pub fn from_json(json: &Value) -> TestRun {
        let count = |key: &str| json[key].as_u64().unwrap_or(0);
        let dollars = |key: &str| json[key].as_f64().unwrap_or(0.0);
        TestRun {
            id: text_id(&json["id"]),
            suite: serde_json::from_value(json["suite"].clone()).unwrap_or_default(),
            limit: dollars("limit"),
            by: json["by"].as_str().unwrap_or_default().to_string(),
            status: serde_json::from_value(json["status"].clone()).unwrap_or_default(),
            passed: count("passed"),
            failed: count("failed"),
            skipped: count("skipped"),
            spent: dollars("spent"),
            reason: optional(&json["reason"]),
            created_at: parse_date(&json["createdAt"]).unwrap_or_default(),
            finished_at: parse_date(&json["finishedAt"]),
        }
    }
}

fn text_id(id: &Value) -> String {
    match id {
        Value::String(id) => id.clone(),
        id => id.to_string(),
    }
}

/// The run started on the runner, with the job's log when it runs in GitHub Actions.
#[derive(Debug, Clone, Serialize)]
pub struct TestStarted {
    pub id: String,
    pub at: DateTime<Utc>,
    pub logs: Option<String>,
}

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum TestOutcomeStatus {
    #[default]
    Passed,
    Failed,
    Skipped,
}

/// A test ended: its estimate and what it spent, in dollars, and why it failed or was skipped.
#[derive(Debug, Clone, Serialize)]
pub struct TestOutcome {
    pub id: String,
    pub at: DateTime<Utc>,
    pub name: String,
    pub status: TestOutcomeStatus,
    pub estimate: f64,
    pub cost: f64,
    pub reason: Option<String>,
}

/// The run ended, with its totals, and why when it broke before its suite did.
#[derive(Debug, Clone, Serialize)]
pub struct TestFinished {
    pub id: String,
    pub at: DateTime<Utc>,
    pub passed: u64,
    pub failed: u64,
    pub skipped: u64,
    pub spent: f64,
    pub limit: f64,
    pub reason: Option<String>,
}

/// What a run's runner reported, in order.
#[derive(Debug, Clone, Serialize)]
#[serde(tag = "event", rename_all = "lowercase")]
pub enum TestEvent {
    Started(TestStarted),
    Test(TestOutcome),
    Finished(TestFinished),
}

impl TestEvent {
    pub fn from_json(json: &Value) -> Result<TestEvent> {
        let id = text_id(&json["id"]);
        let at = parse_date(&json["at"]).unwrap_or_default();
        let count = |key: &str| json[key].as_u64().unwrap_or(0);
        let dollars = |key: &str| json[key].as_f64().unwrap_or(0.0);
        let reason = optional(&json["reason"]);
        match json["event"].as_str() {
            Some("started") => Ok(TestEvent::Started(TestStarted {
                id,
                at,
                logs: optional(&json["logs"]),
            })),
            Some("test") => Ok(TestEvent::Test(TestOutcome {
                id,
                at,
                name: json["name"].as_str().unwrap_or_default().to_string(),
                status: serde_json::from_value(json["status"].clone()).unwrap_or_default(),
                estimate: dollars("estimate"),
                cost: dollars("cost"),
                reason,
            })),
            Some("finished") => Ok(TestEvent::Finished(TestFinished {
                id,
                at,
                passed: count("passed"),
                failed: count("failed"),
                skipped: count("skipped"),
                spent: dollars("spent"),
                limit: dollars("limit"),
                reason,
            })),
            event => Err(Error::Message(format!(
                "{} isn't a test event.",
                event.unwrap_or("undefined")
            ))),
        }
    }
}

/// Run `suite` on the CI runner, spending at most `limit` dollars (up to 100). Fauna dispatches
/// tests.yml on main with the run's id and a one time token the runner reports its events with.
pub async fn run_tests(credentials: &Credentials, suite: TestSuite, limit: f64) -> Result<TestRun> {
    let response = client()
        .post(format!("{}/production/tests", get_url()))
        .header("Authorization", format!("Token {}", credentials.token))
        .json(&json!({ "suite": suite, "limit": limit }))
        .send()
        .await?;
    let json: Value = ok(response).await?.json().await?;
    Ok(TestRun::from_json(&json))
}

/// Test runs, newest first.
pub async fn test_runs(credentials: &Credentials, query: PageQuery) -> Result<Vec<TestRun>> {
    let response = client()
        .get(format!(
            "{}/production/tests?cursor={}&max={}",
            get_url(),
            query.cursor,
            query.max
        ))
        .header("Authorization", format!("Token {}", credentials.token))
        .send()
        .await?;
    let rows: Vec<Value> = ok(response).await?.json().await?;
    Ok(rows.iter().map(TestRun::from_json).collect())
}

/// A run's room hooks: the run as it was when the room opened, then each event its runner
/// reported, those already in first. Fauna closes the room after the run's end. Every method
/// defaults to a no-op, like the optional members of the TypeScript `TestRunHooks`.
pub trait TestRunHooks: Send + Sync {
    fn on_connection(&self, _run: &TestRun) {}
    fn on_event(&self, _event: &TestEvent) {}
    fn on_error(&self, _message: &str) {}
    fn on_close(&self) {}
}

impl TestRunHooks for () {}

/// One run's events as they land.
pub struct TestRunRoom {
    closing: mpsc::UnboundedSender<()>,
}

impl TestRunRoom {
    /// Opens run `id`'s room; resolves once it's open.
    pub async fn connect(
        credentials: &Credentials,
        id: &str,
        hooks: Option<Arc<dyn TestRunHooks>>,
    ) -> Result<TestRunRoom> {
        let hooks = hooks.unwrap_or_else(|| Arc::new(()));
        let params = json!({ "Authorization": format!("Token {}", credentials.token) });
        let url = format!(
            "{}/production/tests/live?run={}&authorization={}",
            websocket(&get_url()),
            encode(id),
            encode(&params.to_string())
        );
        let (stream, _) = tokio_tungstenite::connect_async(url).await?;
        let (mut write, mut read) = stream.split();
        let (closing, mut closed) = mpsc::unbounded_channel::<()>();
        tokio::spawn(async move {
            loop {
                tokio::select! {
                    Some(()) = closed.recv() => {
                        let _ = write.close().await;
                        break;
                    }
                    message = read.next() => match message {
                        Some(Ok(Message::Text(text))) => deliver(hooks.as_ref(), text.as_str()),
                        Some(Ok(Message::Close(_))) | None => break,
                        Some(Ok(_)) => {}
                        Some(Err(_)) => {
                            hooks.on_error("WebSocket connection failed");
                            break;
                        }
                    },
                }
            }
            hooks.on_close();
        });
        Ok(TestRunRoom { closing })
    }

    pub fn close(&self) {
        let _ = self.closing.send(());
    }
}

fn deliver(hooks: &dyn TestRunHooks, text: &str) {
    let Ok(packet) = serde_json::from_str::<Value>(text) else {
        return;
    };
    match packet["event"].as_str() {
        Some("connection") => hooks.on_connection(&TestRun::from_json(&packet["run"])),
        Some("started" | "test" | "finished") => {
            if let Ok(event) = TestEvent::from_json(&packet) {
                hooks.on_event(&event);
            }
        }
        Some("error") => hooks.on_error(packet["message"].as_str().unwrap_or_default()),
        _ => {}
    }
}