fauna-api 1.0.888

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
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};

use super::os::MachineStatus;
use super::spec::Spec;
use crate::authentification::CredentialsOrApiKey;
use crate::billing::PageQuery;
use crate::drive::{DriveAuthorization, File, FileDates, Progress, parse_stream, wrap};
use crate::error::{Error, Result};
use crate::groups::Group;
use crate::http::{client, encode, ok};
use crate::marmot::media::mime_from_file_name;
use crate::shared::schema::Schema;

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Return {
    pub code: u16,
    pub description: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub body: Option<Schema>,
}

/// `'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'` in the TypeScript SDK.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum RouteMethod {
    Get,
    Post,
    Put,
    Patch,
    Delete,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Route {
    pub method: RouteMethod,
    pub path: String,
    pub description: String,
    pub deprecated: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub body: Option<Schema>,
    pub r#return: Vec<Return>,
}

/// `'ADDITION' | 'DELETION'` in the TypeScript SDK.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum LineKind {
    Addition,
    Deletion,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Line {
    pub path: String,
    pub index: u64,
    pub kind: LineKind,
}

#[derive(Debug, Clone, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Revision {
    /// 1, 2, 3 ... within the repository. This is what `rollback` takes.
    pub index: u64,
    /// Set when this revision rolled the repository back to an earlier one.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub rollback: Option<u64>,
    /// Git commit sha of /repository, '' when the machine never answered.
    pub head: String,
    pub lines: Vec<Line>,
    pub date: DateTime<Utc>,
    /// What the machine that saved it was granted. A rollback keeps its target's.
    pub spec: Spec,
    /// Everything the repository stores as of this revision: its layers and its latest memory.
    pub stored_bytes: u64,
}

impl Revision {
    pub fn from_json(json: &Value) -> Revision {
        Revision {
            index: json["index"].as_f64().unwrap_or_default() as u64,
            rollback: json["rollback"]
                .as_f64()
                .filter(|rollback| *rollback != 0.0)
                .map(|rollback| rollback as u64),
            head: match &json["head"] {
                Value::Null => String::new(),
                Value::String(head) => head.clone(),
                head => head.to_string(),
            },
            lines: json["lines"]
                .as_array()
                .into_iter()
                .flatten()
                .filter_map(|line| serde_json::from_value(line.clone()).ok())
                .collect(),
            date: crate::tickets::parse_date(&json["date"]).unwrap_or_default(),
            spec: Spec::from_json(&json["spec"]),
            stored_bytes: json["storedBytes"].as_f64().unwrap_or_default() as u64,
        }
    }
}

/// `{ id, status }` in the TypeScript SDK: a repository's live machine.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct RepositoryMachine {
    pub id: u64,
    pub status: MachineStatus,
}

/// `'IMPORTING' | 'READY' | 'FAILED'` in the TypeScript SDK.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum OriginStatus {
    Importing,
    Ready,
    Failed,
}

/// Where a repository was imported from, and how the import went. An import boots the
/// repository's first machine, clones into `/repository` and saves: `Importing` until then,
/// `Ready` once the clone is saved, or `Failed` with why. The clone keeps its own `.git`, so
/// pulling and pushing afterwards are plain git inside the machine. Nothing syncs by itself.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Origin {
    /// The GitHub repository, `https://github.com/{owner}/{name}`.
    pub url: String,
    /// The branch that was asked for, empty for the repository's own default.
    pub branch: String,
    pub status: OriginStatus,
    /// Why the import failed, empty otherwise.
    pub error: String,
}

impl Origin {
    pub fn from_json(json: &Value) -> Origin {
        Origin {
            url: json["url"].as_str().unwrap_or_default().to_string(),
            branch: json["branch"].as_str().unwrap_or_default().to_string(),
            // A status this SDK doesn't know reads as failed, so nothing waits on it forever.
            status: serde_json::from_value(json["status"].clone()).unwrap_or(OriginStatus::Failed),
            error: json["error"].as_str().unwrap_or_default().to_string(),
        }
    }
}

/// `File | File[]` in the TypeScript SDK.
#[derive(Debug, Clone)]
#[allow(clippy::large_enum_variant)]
pub enum FileOrFiles {
    File(File),
    Files(Vec<File>),
}

/// A secret a repository's agent asked its owner for, waiting until the owner switches on a
/// secret by that name (`Repository::set_secret`) or declines it (`Repository::decline`).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SecretRequest {
    pub id: u64,
    pub name: String,
    /// What the agent said it's for.
    #[serde(default)]
    pub description: String,
    /// Where the agent proposed it be typed in, as hosts.
    #[serde(default)]
    pub sites: Vec<String>,
    /// Where the agent proposed programs send it, as hosts.
    #[serde(default)]
    pub hosts: Vec<String>,
    pub created_at: DateTime<Utc>,
}

impl SecretRequest {
    pub fn from_json(json: &Value) -> Option<SecretRequest> {
        serde_json::from_value(json.clone()).ok()
    }
}

/// A saved machine: a numbered, principal owned chain of disk revisions on the
/// one Termite base image. `/repository` inside it is a git folder whose history
/// is `revisions()`. Start it with `os::MachineRoom::start`.
#[derive(Debug, Clone)]
pub struct Repository {
    pub id: u64,
    pub name: String,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
    /// Its machine while one is booting, running, or saving.
    pub machine: Option<RepositoryMachine>,
    /// The ids of its owner's secrets switched on for it (`crate::secrets`): its machines get
    /// them.
    pub secrets: Vec<u64>,
    /// The secrets its agent asked for, still waiting for the owner.
    pub requests: Vec<SecretRequest>,
    /// The GitHub repository it was imported from, `None` when it wasn't imported.
    pub origin: Option<Origin>,

    /// The group that owns it, when it isn't personal.
    pub group: Option<Group>,

    authorization: CredentialsOrApiKey,
}

impl Repository {
    pub fn from_json(
        json: &Value,
        authorization: &CredentialsOrApiKey,
        group: Option<&Group>,
    ) -> Repository {
        Repository {
            authorization: authorization.clone(),
            group: group.cloned(),
            id: json["id"].as_f64().unwrap_or_default() as u64,
            name: json["name"].as_str().unwrap_or_default().to_string(),
            created_at: crate::tickets::parse_date(&json["createdAt"]).unwrap_or_default(),
            updated_at: crate::tickets::parse_date(&json["updatedAt"]).unwrap_or_default(),
            machine: if json["machine"].is_object() {
                serde_json::from_value(json!({
                    "id": json["machine"]["id"].as_f64().unwrap_or_default() as u64,
                    "status": json["machine"]["status"],
                }))
                .ok()
            } else {
                None
            },
            secrets: json["secrets"]
                .as_array()
                .map(|ids| ids.iter().filter_map(Value::as_u64).collect())
                .unwrap_or_default(),
            requests: json["requests"]
                .as_array()
                .map(|rows| rows.iter().filter_map(SecretRequest::from_json).collect())
                .unwrap_or_default(),
            origin: json["origin"]
                .is_object()
                .then(|| Origin::from_json(&json["origin"])),
        }
    }

    fn request(&self, request: reqwest::RequestBuilder) -> reqwest::RequestBuilder {
        let request = request.header(
            "Authorization",
            match &self.authorization {
                CredentialsOrApiKey::Credentials(credentials) => {
                    format!("Token {}", credentials.token)
                }
                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
            },
        );
        match &self.group {
            Some(group) => request.header("Group", &group.id),
            None => request,
        }
    }

    pub fn routes(&self) -> Result<Vec<Route>> {
        Err(Error::Message(
            "Termite routes are not implemented.".to_string(),
        ))
    }

    /// Revisions newest first. `cursor: 0` is the latest revision.
    pub async fn revisions(&self, query: PageQuery) -> Result<Vec<Revision>> {
        let response = self
            .request(client().get(format!(
                "{}/termite/repositories/{}/revisions?cursor={}&max={}",
                super::get_url(),
                self.id,
                query.cursor,
                query.max
            )))
            .send()
            .await?;
        let parts = parse_stream(ok(response).await?, None::<fn(u64)>).await?;
        parts
            .iter()
            .filter(|part| !part.is_empty())
            .map(|part| Ok(Revision::from_json(&serde_json::from_slice(part)?)))
            .collect()
    }

    fn file_authorization(&self, path: &str) -> DriveAuthorization {
        DriveAuthorization::Repository {
            authorization: self.authorization.clone(),
            repository: self.id,
            path: path.to_string(),
            group: self.group.as_ref().map(|group| group.id.clone()),
        }
    }

    /// A folder gives one `File` per entry, a file gives its own `File`. Nothing
    /// downloads until asked. `path` defaults to `/`.
    pub async fn open(&self, path: Option<&str>) -> Result<FileOrFiles> {
        let tail = path
            .unwrap_or("/")
            .split('/')
            .filter(|segment| !segment.is_empty())
            .map(encode)
            .collect::<Vec<_>>()
            .join("/");
        let response = self
            .request(client().get(format!(
                "{}/termite/repositories/{}/files{}",
                super::get_url(),
                self.id,
                if tail.is_empty() {
                    String::new()
                } else {
                    format!("/{tail}")
                }
            )))
            .send()
            .await?;
        let json: Value = ok(response).await?.json().await?;
        let entry = |entry: &Value| {
            File::from_json(
                entry,
                self.file_authorization(entry["path"].as_str().unwrap_or_default()),
            )
        };
        Ok(match &json {
            Value::Array(entries) => FileOrFiles::Files(entries.iter().map(entry).collect()),
            json => FileOrFiles::File(entry(json)),
        })
    }

    /// Create or overwrite a file under /repository, running or not. A stopped machine takes it
    /// when it next starts, still resuming where it left off, and reads show it meanwhile.
    pub async fn write(
        &self,
        path: &str,
        data: impl AsRef<[u8]>,
        on_progress: Option<Progress>,
    ) -> Result<File> {
        let name = path
            .split('/')
            .rfind(|segment| !segment.is_empty())
            .unwrap_or_default();
        let mut file = wrap(
            self.file_authorization(path),
            name,
            mime_from_file_name(name).unwrap_or("application/octet-stream"),
            data.as_ref().to_vec(),
            FileDates::default(),
        )
        .await?;
        file.upload(on_progress).await?;
        Ok(file)
    }

    /// Record a new revision whose disk is exactly revision `index`'s, dropping writes waiting for
    /// the next start. Refused while a machine is live.
    pub async fn rollback(&self, index: u64) -> Result<()> {
        let response = self
            .request(client().post(format!(
                "{}/termite/repositories/{}/rollback",
                super::get_url(),
                self.id
            )))
            .json(&json!({ "index": index }))
            .send()
            .await?;
        ok(response).await?;
        Ok(())
    }

    /// Rename it. Returns the repository with its new name.
    pub async fn rename(&self, name: &str) -> Result<Repository> {
        let response = self
            .request(client().patch(format!(
                "{}/termite/repositories/{}",
                super::get_url(),
                self.id
            )))
            .json(&json!({ "name": name }))
            .send()
            .await?;
        let json: Value = ok(response).await?.json().await?;
        Ok(Repository::from_json(
            &json,
            &self.authorization,
            self.group.as_ref(),
        ))
    }

    /// Switch one of its owner's secrets on or off for it. A running machine takes it at once,
    /// and switching one on answers the requests waiting for its name. A signed in session of
    /// the owner, or of a direct admin of the group that owns it.
    pub async fn set_secret(&self, id: u64, on: bool) -> Result<Repository> {
        let response = self
            .request(client().patch(format!(
                "{}/termite/repositories/{}",
                super::get_url(),
                self.id
            )))
            .json(&json!({ "secrets": { id.to_string(): on } }))
            .send()
            .await?;
        let json: Value = ok(response).await?.json().await?;
        Ok(Repository::from_json(
            &json,
            &self.authorization,
            self.group.as_ref(),
        ))
    }

    /// Decline secrets its agent asked for. Who can switch secrets can decline them.
    pub async fn decline(&self, requests: &[u64]) -> Result<Repository> {
        let response = self
            .request(client().patch(format!(
                "{}/termite/repositories/{}",
                super::get_url(),
                self.id
            )))
            .json(&json!({ "decline": requests }))
            .send()
            .await?;
        let json: Value = ok(response).await?.json().await?;
        Ok(Repository::from_json(
            &json,
            &self.authorization,
            self.group.as_ref(),
        ))
    }

    pub async fn delete(&self) -> Result<()> {
        let response = self
            .request(client().delete(format!(
                "{}/termite/repositories/{}",
                super::get_url(),
                self.id
            )))
            .send()
            .await?;
        ok(response).await?;
        Ok(())
    }
}

/// `{ url, branch? }` in the TypeScript SDK: the GitHub repository a `create` imports.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Source {
    /// `https://github.com/{owner}/{name}`.
    pub url: String,
    /// The branch to check out, when it isn't the repository's default.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub branch: Option<String>,
}

/// The `opts` argument of `create`.
#[derive(Debug, Clone, Default)]
pub struct CreateOptions {
    pub name: Option<String>,
    pub group: Option<Group>,
    pub source: Option<Source>,
}

/// The `opts` argument of `get` and `list`: `group` for a group's repositories.
#[derive(Debug, Clone, Default)]
pub struct GroupOptions {
    pub group: Option<Group>,
}

fn authorized(
    request: reqwest::RequestBuilder,
    authorization: &CredentialsOrApiKey,
    group: Option<&Group>,
) -> reqwest::RequestBuilder {
    let request = request.header(
        "Authorization",
        match authorization {
            CredentialsOrApiKey::Credentials(credentials) => format!("Token {}", credentials.token),
            CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
        },
    );
    match group {
        Some(group) => request.header("Group", &group.id),
        None => request,
    }
}

/// A new repository: a fresh machine on the Termite base image. With `source` it is imported
/// from GitHub (`https://github.com/{owner}/{name}`, and a `branch` to check out other than its
/// default): its first machine boots at once, billed like any machine, clones it and saves,
/// and `origin` says how that went. A public repository needs nothing more. A private one
/// needs its owner's linked GitHub account (`integrations::link_platform`), and only a
/// personal repository can import one. Without a `name` an import takes the GitHub repository's.
pub async fn create(
    authorization: &CredentialsOrApiKey,
    opts: CreateOptions,
) -> Result<Repository> {
    let mut body = json!({ "name": opts.name });
    if let Some(source) = &opts.source {
        body["source"] = json!(source);
    }
    let response = authorized(
        client().post(format!("{}/termite/repositories", super::get_url())),
        authorization,
        opts.group.as_ref(),
    )
    .json(&body)
    .send()
    .await?;
    let json: Value = ok(response).await?.json().await?;
    Ok(Repository::from_json(
        &json,
        authorization,
        opts.group.as_ref(),
    ))
}

pub async fn get(
    authorization: &CredentialsOrApiKey,
    id: u64,
    opts: GroupOptions,
) -> Result<Repository> {
    let response = authorized(
        client().get(format!("{}/termite/repositories/{id}", super::get_url())),
        authorization,
        opts.group.as_ref(),
    )
    .send()
    .await?;
    let json: Value = ok(response).await?.json().await?;
    Ok(Repository::from_json(
        &json,
        authorization,
        opts.group.as_ref(),
    ))
}

pub async fn list(
    authorization: &CredentialsOrApiKey,
    opts: GroupOptions,
) -> Result<Vec<Repository>> {
    let response = authorized(
        client().get(format!("{}/termite/repositories", super::get_url())),
        authorization,
        opts.group.as_ref(),
    )
    .send()
    .await?;
    let json: Value = ok(response).await?.json().await?;
    Ok(json
        .as_array()
        .into_iter()
        .flatten()
        .map(|row| Repository::from_json(row, authorization, opts.group.as_ref()))
        .collect())
}