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