Skip to main content

fauna_api/termite/
versioning.rs

1use chrono::{DateTime, Utc};
2use serde::{Deserialize, Serialize};
3use serde_json::{Value, json};
4
5use super::os::MachineStatus;
6use crate::authentification::CredentialsOrApiKey;
7use crate::billing::PageQuery;
8use crate::drive::{DriveAuthorization, File, FileDates, Progress, parse_stream, wrap};
9use crate::error::{Error, Result};
10use crate::groups::Group;
11use crate::http::{client, encode, ok};
12use crate::marmot::media::mime_from_file_name;
13use crate::shared::schema::Schema;
14
15#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
16pub struct Return {
17    pub code: u16,
18    pub description: String,
19    #[serde(default, skip_serializing_if = "Option::is_none")]
20    pub body: Option<Schema>,
21}
22
23/// `'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'` in the TypeScript SDK.
24#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
25#[serde(rename_all = "UPPERCASE")]
26pub enum RouteMethod {
27    Get,
28    Post,
29    Put,
30    Patch,
31    Delete,
32}
33
34#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
35pub struct Route {
36    pub method: RouteMethod,
37    pub path: String,
38    pub description: String,
39    pub deprecated: bool,
40    #[serde(default, skip_serializing_if = "Option::is_none")]
41    pub body: Option<Schema>,
42    pub r#return: Vec<Return>,
43}
44
45/// `'ADDITION' | 'DELETION'` in the TypeScript SDK.
46#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
47#[serde(rename_all = "UPPERCASE")]
48pub enum LineKind {
49    Addition,
50    Deletion,
51}
52
53#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
54pub struct Line {
55    pub path: String,
56    pub index: u64,
57    pub kind: LineKind,
58}
59
60#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
61pub struct Change {
62    /// 1, 2, 3 ... within the repository. This is what `rollback` takes.
63    pub revision: u64,
64    /// Set when this revision rolled the repository back to an earlier one.
65    #[serde(skip_serializing_if = "Option::is_none")]
66    pub rollback: Option<u64>,
67    /// Git commit sha of /repository, '' when the machine never answered.
68    pub head: String,
69    pub lines: Vec<Line>,
70    pub date: DateTime<Utc>,
71}
72
73impl Change {
74    pub fn from_json(json: &Value) -> Change {
75        Change {
76            revision: json["revision"].as_f64().unwrap_or_default() as u64,
77            rollback: json["rollback"]
78                .as_f64()
79                .filter(|rollback| *rollback != 0.0)
80                .map(|rollback| rollback as u64),
81            head: match &json["head"] {
82                Value::Null => String::new(),
83                Value::String(head) => head.clone(),
84                head => head.to_string(),
85            },
86            lines: json["lines"]
87                .as_array()
88                .into_iter()
89                .flatten()
90                .filter_map(|line| serde_json::from_value(line.clone()).ok())
91                .collect(),
92            date: crate::tickets::parse_date(&json["date"]).unwrap_or_default(),
93        }
94    }
95}
96
97/// `{ id, status }` in the TypeScript SDK: a repository's live machine.
98#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
99pub struct RepositoryMachine {
100    pub id: u64,
101    pub status: MachineStatus,
102}
103
104/// `File | File[]` in the TypeScript SDK.
105#[derive(Debug, Clone)]
106#[allow(clippy::large_enum_variant)]
107pub enum FileOrFiles {
108    File(File),
109    Files(Vec<File>),
110}
111
112/// A saved machine: a numbered, principal owned chain of disk revisions on the
113/// one Termite base image. `/repository` inside it is a git folder whose history
114/// is `changes()`. Start it with `os::MachineRoom::start`.
115#[derive(Debug, Clone)]
116pub struct Repository {
117    pub id: u64,
118    pub name: String,
119    pub size_bytes: u64,
120    pub created_at: DateTime<Utc>,
121    pub updated_at: DateTime<Utc>,
122    /// Its machine while one is booting, running, or saving.
123    pub machine: Option<RepositoryMachine>,
124
125    /// The group that owns it, when it isn't personal.
126    pub group: Option<Group>,
127
128    authorization: CredentialsOrApiKey,
129}
130
131impl Repository {
132    pub fn from_json(
133        json: &Value,
134        authorization: &CredentialsOrApiKey,
135        group: Option<&Group>,
136    ) -> Repository {
137        Repository {
138            authorization: authorization.clone(),
139            group: group.cloned(),
140            id: json["id"].as_f64().unwrap_or_default() as u64,
141            name: json["name"].as_str().unwrap_or_default().to_string(),
142            size_bytes: json["sizeBytes"].as_f64().unwrap_or_default() as u64,
143            created_at: crate::tickets::parse_date(&json["createdAt"]).unwrap_or_default(),
144            updated_at: crate::tickets::parse_date(&json["updatedAt"]).unwrap_or_default(),
145            machine: if json["machine"].is_object() {
146                serde_json::from_value(json!({
147                    "id": json["machine"]["id"].as_f64().unwrap_or_default() as u64,
148                    "status": json["machine"]["status"],
149                }))
150                .ok()
151            } else {
152                None
153            },
154        }
155    }
156
157    fn request(&self, request: reqwest::RequestBuilder) -> reqwest::RequestBuilder {
158        let request = request.header(
159            "Authorization",
160            match &self.authorization {
161                CredentialsOrApiKey::Credentials(credentials) => {
162                    format!("Token {}", credentials.token)
163                }
164                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
165            },
166        );
167        match &self.group {
168            Some(group) => request.header("Group", &group.id),
169            None => request,
170        }
171    }
172
173    pub fn routes(&self) -> Result<Vec<Route>> {
174        Err(Error::Message(
175            "Termite routes are not implemented.".to_string(),
176        ))
177    }
178
179    /// Revisions newest first. `cursor: 0` is the latest revision.
180    pub async fn changes(&self, query: PageQuery) -> Result<Vec<Change>> {
181        let response = self
182            .request(client().get(format!(
183                "{}/termite/repositories/{}/changes?cursor={}&max={}",
184                super::get_url(),
185                self.id,
186                query.cursor,
187                query.max
188            )))
189            .send()
190            .await?;
191        let parts = parse_stream(ok(response).await?, None::<fn(u64)>).await?;
192        parts
193            .iter()
194            .filter(|part| !part.is_empty())
195            .map(|part| Ok(Change::from_json(&serde_json::from_slice(part)?)))
196            .collect()
197    }
198
199    fn file_authorization(&self, path: &str) -> DriveAuthorization {
200        DriveAuthorization::Repository {
201            authorization: self.authorization.clone(),
202            repository: self.id,
203            path: path.to_string(),
204            group: self.group.as_ref().map(|group| group.id.clone()),
205        }
206    }
207
208    /// A folder gives one `File` per entry, a file gives its own `File`. Nothing
209    /// downloads until asked. `path` defaults to `/`.
210    pub async fn open(&self, path: Option<&str>) -> Result<FileOrFiles> {
211        let tail = path
212            .unwrap_or("/")
213            .split('/')
214            .filter(|segment| !segment.is_empty())
215            .map(encode)
216            .collect::<Vec<_>>()
217            .join("/");
218        let response = self
219            .request(client().get(format!(
220                "{}/termite/repositories/{}/files{}",
221                super::get_url(),
222                self.id,
223                if tail.is_empty() {
224                    String::new()
225                } else {
226                    format!("/{tail}")
227                }
228            )))
229            .send()
230            .await?;
231        let json: Value = ok(response).await?.json().await?;
232        let entry = |entry: &Value| {
233            File::from_json(
234                entry,
235                self.file_authorization(entry["path"].as_str().unwrap_or_default()),
236            )
237        };
238        Ok(match &json {
239            Value::Array(entries) => FileOrFiles::Files(entries.iter().map(entry).collect()),
240            json => FileOrFiles::File(entry(json)),
241        })
242    }
243
244    /// Create or overwrite a file under /repository, running or not.
245    pub async fn write(
246        &self,
247        path: &str,
248        data: impl AsRef<[u8]>,
249        on_progress: Option<Progress>,
250    ) -> Result<File> {
251        let name = path
252            .split('/')
253            .rfind(|segment| !segment.is_empty())
254            .unwrap_or_default();
255        let mut file = wrap(
256            self.file_authorization(path),
257            name,
258            mime_from_file_name(name).unwrap_or("application/octet-stream"),
259            data.as_ref().to_vec(),
260            FileDates::default(),
261        )
262        .await?;
263        file.upload(on_progress).await?;
264        Ok(file)
265    }
266
267    /// Record a new revision whose disk is exactly `revision`'s. Refused while a machine is live.
268    pub async fn rollback(&self, revision: u64) -> Result<()> {
269        let response = self
270            .request(client().post(format!(
271                "{}/termite/repositories/{}/rollback",
272                super::get_url(),
273                self.id
274            )))
275            .json(&json!({ "revision": revision }))
276            .send()
277            .await?;
278        ok(response).await?;
279        Ok(())
280    }
281
282    /// Rename it. Returns the repository with its new name.
283    pub async fn rename(&self, name: &str) -> Result<Repository> {
284        let response = self
285            .request(client().patch(format!(
286                "{}/termite/repositories/{}",
287                super::get_url(),
288                self.id
289            )))
290            .json(&json!({ "name": name }))
291            .send()
292            .await?;
293        let json: Value = ok(response).await?.json().await?;
294        Ok(Repository::from_json(
295            &json,
296            &self.authorization,
297            self.group.as_ref(),
298        ))
299    }
300
301    pub async fn delete(&self) -> Result<()> {
302        let response = self
303            .request(client().delete(format!(
304                "{}/termite/repositories/{}",
305                super::get_url(),
306                self.id
307            )))
308            .send()
309            .await?;
310        ok(response).await?;
311        Ok(())
312    }
313}
314
315/// The `opts` argument of `create`.
316#[derive(Debug, Clone, Default)]
317pub struct CreateOptions {
318    pub name: Option<String>,
319    pub group: Option<Group>,
320}
321
322/// The `opts` argument of `get` and `list`: `group` for a group's repositories.
323#[derive(Debug, Clone, Default)]
324pub struct GroupOptions {
325    pub group: Option<Group>,
326}
327
328fn authorized(
329    request: reqwest::RequestBuilder,
330    authorization: &CredentialsOrApiKey,
331    group: Option<&Group>,
332) -> reqwest::RequestBuilder {
333    let request = request.header(
334        "Authorization",
335        match authorization {
336            CredentialsOrApiKey::Credentials(credentials) => format!("Token {}", credentials.token),
337            CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
338        },
339    );
340    match group {
341        Some(group) => request.header("Group", &group.id),
342        None => request,
343    }
344}
345
346pub async fn create(
347    authorization: &CredentialsOrApiKey,
348    opts: CreateOptions,
349) -> Result<Repository> {
350    let response = authorized(
351        client().post(format!("{}/termite/repositories", super::get_url())),
352        authorization,
353        opts.group.as_ref(),
354    )
355    .json(&json!({ "name": opts.name }))
356    .send()
357    .await?;
358    let json: Value = ok(response).await?.json().await?;
359    Ok(Repository::from_json(
360        &json,
361        authorization,
362        opts.group.as_ref(),
363    ))
364}
365
366pub async fn get(
367    authorization: &CredentialsOrApiKey,
368    id: u64,
369    opts: GroupOptions,
370) -> Result<Repository> {
371    let response = authorized(
372        client().get(format!("{}/termite/repositories/{id}", super::get_url())),
373        authorization,
374        opts.group.as_ref(),
375    )
376    .send()
377    .await?;
378    let json: Value = ok(response).await?.json().await?;
379    Ok(Repository::from_json(
380        &json,
381        authorization,
382        opts.group.as_ref(),
383    ))
384}
385
386pub async fn list(
387    authorization: &CredentialsOrApiKey,
388    opts: GroupOptions,
389) -> Result<Vec<Repository>> {
390    let response = authorized(
391        client().get(format!("{}/termite/repositories", super::get_url())),
392        authorization,
393        opts.group.as_ref(),
394    )
395    .send()
396    .await?;
397    let json: Value = ok(response).await?.json().await?;
398    Ok(json
399        .as_array()
400        .into_iter()
401        .flatten()
402        .map(|row| Repository::from_json(row, authorization, opts.group.as_ref()))
403        .collect())
404}