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#[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#[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 pub index: u64,
66 #[serde(skip_serializing_if = "Option::is_none")]
68 pub rollback: Option<u64>,
69 pub head: String,
71 pub lines: Vec<Line>,
72 pub date: DateTime<Utc>,
73 pub spec: Spec,
75 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
107pub struct RepositoryMachine {
108 pub id: u64,
109 pub status: MachineStatus,
110}
111
112#[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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
126pub struct Origin {
127 pub url: String,
129 pub branch: String,
131 pub status: OriginStatus,
132 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 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#[derive(Debug, Clone)]
150#[allow(clippy::large_enum_variant)]
151pub enum FileOrFiles {
152 File(File),
153 Files(Vec<File>),
154}
155
156#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
159#[serde(rename_all = "camelCase")]
160pub struct SecretRequest {
161 pub id: u64,
162 pub name: String,
163 #[serde(default)]
165 pub description: String,
166 #[serde(default)]
168 pub sites: Vec<String>,
169 #[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#[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 pub machine: Option<RepositoryMachine>,
192 pub secrets: Vec<u64>,
195 pub requests: Vec<SecretRequest>,
197 pub origin: Option<Origin>,
199
200 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 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 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 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 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 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 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 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#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
444pub struct Source {
445 pub url: String,
447 #[serde(default, skip_serializing_if = "Option::is_none")]
449 pub branch: Option<String>,
450}
451
452#[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#[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
484pub 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}