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

use super::os::MachineStatus;
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, Eq, Serialize)]
pub struct Change {
    /// 1, 2, 3 ... within the repository. This is what `rollback` takes.
    pub revision: 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>,
}

impl Change {
    pub fn from_json(json: &Value) -> Change {
        Change {
            revision: json["revision"].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(),
        }
    }
}

/// `{ 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,
}

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

/// 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 `changes()`. Start it with `os::MachineRoom::start`.
#[derive(Debug, Clone)]
pub struct Repository {
    pub id: u64,
    pub name: String,
    pub size_bytes: u64,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
    /// Its machine while one is booting, running, or saving.
    pub machine: Option<RepositoryMachine>,

    /// 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(),
            size_bytes: json["sizeBytes"].as_f64().unwrap_or_default() as u64,
            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
            },
        }
    }

    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 changes(&self, query: PageQuery) -> Result<Vec<Change>> {
        let response = self
            .request(client().get(format!(
                "{}/termite/repositories/{}/changes?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(Change::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.
    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`'s. Refused while a machine is live.
    pub async fn rollback(&self, revision: u64) -> Result<()> {
        let response = self
            .request(client().post(format!(
                "{}/termite/repositories/{}/rollback",
                super::get_url(),
                self.id
            )))
            .json(&json!({ "revision": revision }))
            .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(),
        ))
    }

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

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

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

pub async fn create(
    authorization: &CredentialsOrApiKey,
    opts: CreateOptions,
) -> Result<Repository> {
    let response = authorized(
        client().post(format!("{}/termite/repositories", super::get_url())),
        authorization,
        opts.group.as_ref(),
    )
    .json(&json!({ "name": opts.name }))
    .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())
}