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 secret a repository's agent asked its owner for, waiting until the owner switches on a
121/// secret by that name (`Repository::set_secret`) or declines it (`Repository::decline`).
122#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
123#[serde(rename_all = "camelCase")]
124pub struct SecretRequest {
125    pub id: u64,
126    pub name: String,
127    /// What the agent said it's for.
128    #[serde(default)]
129    pub description: String,
130    /// Where the agent proposed it be typed in, as hosts.
131    #[serde(default)]
132    pub sites: Vec<String>,
133    /// Where the agent proposed programs send it, as hosts.
134    #[serde(default)]
135    pub hosts: Vec<String>,
136    pub created_at: DateTime<Utc>,
137}
138
139impl SecretRequest {
140    pub fn from_json(json: &Value) -> Option<SecretRequest> {
141        serde_json::from_value(json.clone()).ok()
142    }
143}
144
145/// A saved machine: a numbered, principal owned chain of disk revisions on the
146/// one Termite base image. `/repository` inside it is a git folder whose history
147/// is `revisions()`. Start it with `os::MachineRoom::start`.
148#[derive(Debug, Clone)]
149pub struct Repository {
150    pub id: u64,
151    pub name: String,
152    pub created_at: DateTime<Utc>,
153    pub updated_at: DateTime<Utc>,
154    /// Its machine while one is booting, running, or saving.
155    pub machine: Option<RepositoryMachine>,
156    /// The ids of its owner's secrets switched on for it (`crate::secrets`): its machines get
157    /// them.
158    pub secrets: Vec<u64>,
159    /// The secrets its agent asked for, still waiting for the owner.
160    pub requests: Vec<SecretRequest>,
161
162    /// The group that owns it, when it isn't personal.
163    pub group: Option<Group>,
164
165    authorization: CredentialsOrApiKey,
166}
167
168impl Repository {
169    pub fn from_json(
170        json: &Value,
171        authorization: &CredentialsOrApiKey,
172        group: Option<&Group>,
173    ) -> Repository {
174        Repository {
175            authorization: authorization.clone(),
176            group: group.cloned(),
177            id: json["id"].as_f64().unwrap_or_default() as u64,
178            name: json["name"].as_str().unwrap_or_default().to_string(),
179            created_at: crate::tickets::parse_date(&json["createdAt"]).unwrap_or_default(),
180            updated_at: crate::tickets::parse_date(&json["updatedAt"]).unwrap_or_default(),
181            machine: if json["machine"].is_object() {
182                serde_json::from_value(json!({
183                    "id": json["machine"]["id"].as_f64().unwrap_or_default() as u64,
184                    "status": json["machine"]["status"],
185                }))
186                .ok()
187            } else {
188                None
189            },
190            secrets: json["secrets"]
191                .as_array()
192                .map(|ids| ids.iter().filter_map(Value::as_u64).collect())
193                .unwrap_or_default(),
194            requests: json["requests"]
195                .as_array()
196                .map(|rows| rows.iter().filter_map(SecretRequest::from_json).collect())
197                .unwrap_or_default(),
198        }
199    }
200
201    fn request(&self, request: reqwest::RequestBuilder) -> reqwest::RequestBuilder {
202        let request = request.header(
203            "Authorization",
204            match &self.authorization {
205                CredentialsOrApiKey::Credentials(credentials) => {
206                    format!("Token {}", credentials.token)
207                }
208                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
209            },
210        );
211        match &self.group {
212            Some(group) => request.header("Group", &group.id),
213            None => request,
214        }
215    }
216
217    pub fn routes(&self) -> Result<Vec<Route>> {
218        Err(Error::Message(
219            "Termite routes are not implemented.".to_string(),
220        ))
221    }
222
223    /// Revisions newest first. `cursor: 0` is the latest revision.
224    pub async fn revisions(&self, query: PageQuery) -> Result<Vec<Revision>> {
225        let response = self
226            .request(client().get(format!(
227                "{}/termite/repositories/{}/revisions?cursor={}&max={}",
228                super::get_url(),
229                self.id,
230                query.cursor,
231                query.max
232            )))
233            .send()
234            .await?;
235        let parts = parse_stream(ok(response).await?, None::<fn(u64)>).await?;
236        parts
237            .iter()
238            .filter(|part| !part.is_empty())
239            .map(|part| Ok(Revision::from_json(&serde_json::from_slice(part)?)))
240            .collect()
241    }
242
243    fn file_authorization(&self, path: &str) -> DriveAuthorization {
244        DriveAuthorization::Repository {
245            authorization: self.authorization.clone(),
246            repository: self.id,
247            path: path.to_string(),
248            group: self.group.as_ref().map(|group| group.id.clone()),
249        }
250    }
251
252    /// A folder gives one `File` per entry, a file gives its own `File`. Nothing
253    /// downloads until asked. `path` defaults to `/`.
254    pub async fn open(&self, path: Option<&str>) -> Result<FileOrFiles> {
255        let tail = path
256            .unwrap_or("/")
257            .split('/')
258            .filter(|segment| !segment.is_empty())
259            .map(encode)
260            .collect::<Vec<_>>()
261            .join("/");
262        let response = self
263            .request(client().get(format!(
264                "{}/termite/repositories/{}/files{}",
265                super::get_url(),
266                self.id,
267                if tail.is_empty() {
268                    String::new()
269                } else {
270                    format!("/{tail}")
271                }
272            )))
273            .send()
274            .await?;
275        let json: Value = ok(response).await?.json().await?;
276        let entry = |entry: &Value| {
277            File::from_json(
278                entry,
279                self.file_authorization(entry["path"].as_str().unwrap_or_default()),
280            )
281        };
282        Ok(match &json {
283            Value::Array(entries) => FileOrFiles::Files(entries.iter().map(entry).collect()),
284            json => FileOrFiles::File(entry(json)),
285        })
286    }
287
288    /// Create or overwrite a file under /repository, running or not. A stopped machine takes it
289    /// when it next starts, still resuming where it left off, and reads show it meanwhile.
290    pub async fn write(
291        &self,
292        path: &str,
293        data: impl AsRef<[u8]>,
294        on_progress: Option<Progress>,
295    ) -> Result<File> {
296        let name = path
297            .split('/')
298            .rfind(|segment| !segment.is_empty())
299            .unwrap_or_default();
300        let mut file = wrap(
301            self.file_authorization(path),
302            name,
303            mime_from_file_name(name).unwrap_or("application/octet-stream"),
304            data.as_ref().to_vec(),
305            FileDates::default(),
306        )
307        .await?;
308        file.upload(on_progress).await?;
309        Ok(file)
310    }
311
312    /// Record a new revision whose disk is exactly revision `index`'s, dropping writes waiting for
313    /// the next start. Refused while a machine is live.
314    pub async fn rollback(&self, index: u64) -> Result<()> {
315        let response = self
316            .request(client().post(format!(
317                "{}/termite/repositories/{}/rollback",
318                super::get_url(),
319                self.id
320            )))
321            .json(&json!({ "index": index }))
322            .send()
323            .await?;
324        ok(response).await?;
325        Ok(())
326    }
327
328    /// Rename it. Returns the repository with its new name.
329    pub async fn rename(&self, name: &str) -> Result<Repository> {
330        let response = self
331            .request(client().patch(format!(
332                "{}/termite/repositories/{}",
333                super::get_url(),
334                self.id
335            )))
336            .json(&json!({ "name": name }))
337            .send()
338            .await?;
339        let json: Value = ok(response).await?.json().await?;
340        Ok(Repository::from_json(
341            &json,
342            &self.authorization,
343            self.group.as_ref(),
344        ))
345    }
346
347    /// Switch one of its owner's secrets on or off for it. A running machine takes it at once,
348    /// and switching one on answers the requests waiting for its name. A signed in session of
349    /// the owner, or of a direct admin of the group that owns it.
350    pub async fn set_secret(&self, id: u64, on: bool) -> Result<Repository> {
351        let response = self
352            .request(client().patch(format!(
353                "{}/termite/repositories/{}",
354                super::get_url(),
355                self.id
356            )))
357            .json(&json!({ "secrets": { id.to_string(): on } }))
358            .send()
359            .await?;
360        let json: Value = ok(response).await?.json().await?;
361        Ok(Repository::from_json(
362            &json,
363            &self.authorization,
364            self.group.as_ref(),
365        ))
366    }
367
368    /// Decline secrets its agent asked for. Who can switch secrets can decline them.
369    pub async fn decline(&self, requests: &[u64]) -> Result<Repository> {
370        let response = self
371            .request(client().patch(format!(
372                "{}/termite/repositories/{}",
373                super::get_url(),
374                self.id
375            )))
376            .json(&json!({ "decline": requests }))
377            .send()
378            .await?;
379        let json: Value = ok(response).await?.json().await?;
380        Ok(Repository::from_json(
381            &json,
382            &self.authorization,
383            self.group.as_ref(),
384        ))
385    }
386
387    pub async fn delete(&self) -> Result<()> {
388        let response = self
389            .request(client().delete(format!(
390                "{}/termite/repositories/{}",
391                super::get_url(),
392                self.id
393            )))
394            .send()
395            .await?;
396        ok(response).await?;
397        Ok(())
398    }
399}
400
401/// The `opts` argument of `create`.
402#[derive(Debug, Clone, Default)]
403pub struct CreateOptions {
404    pub name: Option<String>,
405    pub group: Option<Group>,
406}
407
408/// The `opts` argument of `get` and `list`: `group` for a group's repositories.
409#[derive(Debug, Clone, Default)]
410pub struct GroupOptions {
411    pub group: Option<Group>,
412}
413
414fn authorized(
415    request: reqwest::RequestBuilder,
416    authorization: &CredentialsOrApiKey,
417    group: Option<&Group>,
418) -> reqwest::RequestBuilder {
419    let request = request.header(
420        "Authorization",
421        match authorization {
422            CredentialsOrApiKey::Credentials(credentials) => format!("Token {}", credentials.token),
423            CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
424        },
425    );
426    match group {
427        Some(group) => request.header("Group", &group.id),
428        None => request,
429    }
430}
431
432pub async fn create(
433    authorization: &CredentialsOrApiKey,
434    opts: CreateOptions,
435) -> Result<Repository> {
436    let response = authorized(
437        client().post(format!("{}/termite/repositories", super::get_url())),
438        authorization,
439        opts.group.as_ref(),
440    )
441    .json(&json!({ "name": opts.name }))
442    .send()
443    .await?;
444    let json: Value = ok(response).await?.json().await?;
445    Ok(Repository::from_json(
446        &json,
447        authorization,
448        opts.group.as_ref(),
449    ))
450}
451
452pub async fn get(
453    authorization: &CredentialsOrApiKey,
454    id: u64,
455    opts: GroupOptions,
456) -> Result<Repository> {
457    let response = authorized(
458        client().get(format!("{}/termite/repositories/{id}", super::get_url())),
459        authorization,
460        opts.group.as_ref(),
461    )
462    .send()
463    .await?;
464    let json: Value = ok(response).await?.json().await?;
465    Ok(Repository::from_json(
466        &json,
467        authorization,
468        opts.group.as_ref(),
469    ))
470}
471
472pub async fn list(
473    authorization: &CredentialsOrApiKey,
474    opts: GroupOptions,
475) -> Result<Vec<Repository>> {
476    let response = authorized(
477        client().get(format!("{}/termite/repositories", super::get_url())),
478        authorization,
479        opts.group.as_ref(),
480    )
481    .send()
482    .await?;
483    let json: Value = ok(response).await?.json().await?;
484    Ok(json
485        .as_array()
486        .into_iter()
487        .flatten()
488        .map(|row| Repository::from_json(row, authorization, opts.group.as_ref()))
489        .collect())
490}