Skip to main content

brep_plm/api/
backups.rs

1//! Backups and exports over HTTP — administrators only. The work is in
2//! [`crate::backup`].
3
4use axum::extract::{Path, Query, State};
5use axum::http::{header, HeaderMap, HeaderValue};
6use axum::response::{IntoResponse, Response};
7use axum::Json;
8use serde::Deserialize;
9use serde_json::{json, Value};
10
11use super::{blocking, require_admin, Shared};
12use crate::backup;
13use crate::Error;
14
15/// What is configured, the last backup, and the saved ones.
16pub async fn status(State(db): State<Shared>, headers: HeaderMap) -> Result<Json<Value>, Error> {
17    require_admin(&db, &headers)?;
18    let config = &db.security().config;
19    let saved = config.backup_dir.as_deref().map(backup::saved).unwrap_or_default();
20    Ok(Json(json!({
21        "dir": config.backup_dir.as_ref().map(|d| d.display().to_string()),
22        "every_minutes": config.backup_every_minutes,
23        "keep": if config.backup_keep == 0 { backup::DEFAULT_KEEP } else { config.backup_keep },
24        "running": db.backups().running(),
25        "last": db.backups().last(),
26        "saved": saved,
27    })))
28}
29
30/// "Back up now" into the backup directory.
31pub async fn run(State(db): State<Shared>, headers: HeaderMap) -> Result<Json<Value>, Error> {
32    require_admin(&db, &headers)?;
33    let last = blocking(move || db.backup_now("button")).await?;
34    Ok(Json(json!({ "ok": true, "last": last })))
35}
36
37/// Stream a file from disk; with `remove`, unlink it once it is open (the
38/// open handle keeps it readable until the stream ends).
39async fn stream_file(path: &std::path::Path, name: &str, media: &'static str, remove: bool) -> Result<Response, Error> {
40    let file = tokio::fs::File::open(path).await.map_err(Error::internal)?;
41    let size = file.metadata().await.map_err(Error::internal)?.len();
42    if remove {
43        let _ = tokio::fs::remove_file(path).await;
44    }
45    let mut response = super::body_io::file_body(file, 256 * 1024).into_response();
46    let h = response.headers_mut();
47    h.insert(header::CONTENT_TYPE, HeaderValue::from_static(media));
48    h.insert(header::CONTENT_LENGTH, HeaderValue::from(size));
49    if let Ok(value) = HeaderValue::from_str(&format!("attachment; filename=\"{name}\"")) {
50        h.insert(header::CONTENT_DISPOSITION, value);
51    }
52    Ok(response)
53}
54
55/// Download a saved backup by name.
56pub async fn saved_file(
57    State(db): State<Shared>,
58    headers: HeaderMap,
59    Path(name): Path<String>,
60) -> Result<Response, Error> {
61    require_admin(&db, &headers)?;
62    if !backup::is_backup_name(&name) {
63        return Err(Error::bad_request("not a backup name"));
64    }
65    let dir = db.security().config.backup_dir.clone().ok_or_else(|| Error::not_found("backup directory"))?;
66    let path = dir.join(&name);
67    if !path.is_file() {
68        return Err(Error::not_found("backup"));
69    }
70    stream_file(&path, &name, "application/gzip", false).await
71}
72
73/// Take a fresh backup and download it; nothing is kept on the server.
74pub async fn download(State(db): State<Shared>, headers: HeaderMap) -> Result<Response, Error> {
75    require_admin(&db, &headers)?;
76    let (path, _) = blocking(move || db.backup_to_temp()).await?;
77    let name = path.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| "backup.tar.gz".into());
78    // The temporary name carries an id after the time; offer the plain one.
79    let offered = match name.rsplit_once('-') {
80        Some((head, _)) => format!("{head}{}", backup::SUFFIX),
81        None => name,
82    };
83    stream_file(&path, &offered, "application/gzip", true).await
84}
85
86#[derive(Debug, Deserialize, Default)]
87pub struct ExportQuery {
88    /// `json` (default), `parts-csv` or `structure-csv`.
89    #[serde(default)]
90    pub format: String,
91}
92
93/// The metadata export, as a download.
94pub async fn export(
95    State(db): State<Shared>,
96    headers: HeaderMap,
97    Query(query): Query<ExportQuery>,
98) -> Result<Response, Error> {
99    require_admin(&db, &headers)?;
100    let stamp = backup::stamp(crate::db::now());
101    let (body, media, name) = match query.format.as_str() {
102        "" | "json" => (
103            db.read(|state| serde_json::to_string_pretty(&backup::export_json(state))).map_err(Error::internal)?,
104            "application/json",
105            format!("brep-plm-export-{stamp}.json"),
106        ),
107        "parts-csv" => (db.read(backup::parts_csv), "text/csv; charset=utf-8", format!("brep-plm-parts-{stamp}.csv")),
108        "structure-csv" => (
109            db.read(backup::structure_csv),
110            "text/csv; charset=utf-8",
111            format!("brep-plm-structure-{stamp}.csv"),
112        ),
113        other => return Err(Error::bad_request(format!("format is json, parts-csv or structure-csv, not '{other}'"))),
114    };
115    let mut response = body.into_response();
116    let h = response.headers_mut();
117    h.insert(header::CONTENT_TYPE, HeaderValue::from_static(media));
118    if let Ok(value) = HeaderValue::from_str(&format!("attachment; filename=\"{name}\"")) {
119        h.insert(header::CONTENT_DISPOSITION, value);
120    }
121    Ok(response)
122}