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