1use std::collections::{BTreeMap, BTreeSet};
57use std::fs;
58use std::io::{self, Read, Write};
59use std::path::{Component, Path, PathBuf};
60
61use serde::{Deserialize, Serialize};
62use serde_json::{json, Value};
63use sha2::{Digest, Sha256};
64
65use crate::db::State;
66use crate::model::{Part, Revision};
67
68pub const FORMAT: &str = "brep-plm-backup";
70pub const VERSION: u32 = 1;
72pub const ATTEMPTS: usize = 6;
74pub const ADJUST_AFTER: usize = 3;
77
78#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
79pub struct FileEntry {
80 pub path: String,
82 pub size: u64,
83 pub sha256: String,
84}
85
86#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
87pub struct Manifest {
88 pub format: String,
89 pub version: u32,
90 pub created_at: u64,
92 pub schema_version: i64,
94 pub counts: BTreeMap<String, i64>,
96 pub seq: u64,
98 pub attempts: usize,
100 #[serde(default, skip_serializing_if = "Vec::is_empty")]
104 pub adjusted: Vec<String>,
105 pub files: Vec<FileEntry>,
106}
107
108impl Manifest {
109 pub fn total_size(&self) -> u64 {
110 self.files.iter().map(|f| f.size).sum()
111 }
112
113 pub fn adjusted_notice(&self) -> Option<String> {
121 if self.adjusted.is_empty() {
122 return None;
123 }
124 let mut notice = format!(
125 "{} draft document(s) kept changing during the backup and were taken as copied, \
126 a moment after the snapshot (their recorded hashes were set to match):",
127 self.adjusted.len()
128 );
129 for path in &self.adjusted {
130 notice.push_str("\n ");
131 notice.push_str(path);
132 }
133 Some(notice)
134 }
135}
136
137
138fn now() -> u64 {
139 std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0)
140}
141
142fn other(message: impl ToString) -> io::Error {
143 io::Error::other(message.to_string())
144}
145
146pub fn hash_file(path: &Path) -> io::Result<(u64, String)> {
148 let mut file = fs::File::open(path)?;
149 let mut hasher = Sha256::new();
150 let mut buffer = vec![0u8; 256 * 1024];
151 let mut size = 0u64;
152 loop {
153 let n = file.read(&mut buffer)?;
154 if n == 0 {
155 break;
156 }
157 size += n as u64;
158 hasher.update(&buffer[..n]);
159 }
160 Ok((size, format!("{:x}", hasher.finalize())))
161}
162
163struct Wanted {
165 drafts: BTreeMap<String, String>,
168 frozen: BTreeMap<String, String>,
170 blobs: BTreeSet<String>,
171 seq: u64,
172 counts: BTreeMap<String, i64>,
173 schema_version: i64,
174}
175
176fn wanted(conn: &rusqlite::Connection) -> io::Result<Wanted> {
178 let mut drafts = BTreeMap::new();
179 let mut frozen = BTreeMap::new();
180 let mut blobs = BTreeSet::new();
181 let mut take_attachments = |body: &Value| {
182 if let Some(list) = body.get("attachments").and_then(Value::as_array) {
183 for a in list {
184 if let Some(sha) = a.get("sha256").and_then(Value::as_str) {
185 blobs.insert(sha.to_string());
186 }
187 }
188 }
189 for pointer in ["/thumbnail/sha256", "/player/sha256"] {
192 if let Some(sha) = body.pointer(pointer).and_then(Value::as_str) {
193 blobs.insert(sha.to_string());
194 }
195 }
196 };
197 {
198 let mut stmt = conn.prepare("SELECT body FROM parts").map_err(other_sql)?;
199 let rows = stmt.query_map([], |r| r.get::<_, String>(0)).map_err(other_sql)?;
200 for body in rows {
201 let body: Value = serde_json::from_str(&body.map_err(other_sql)?).map_err(other)?;
202 take_attachments(&body);
203 }
204 }
205 {
206 let mut stmt = conn.prepare("SELECT part_id, id, body FROM revisions").map_err(other_sql)?;
207 let rows = stmt
208 .query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?, r.get::<_, String>(2)?)))
209 .map_err(other_sql)?;
210 for row in rows {
211 let (part, revision, body) = row.map_err(other_sql)?;
212 let body: Value = serde_json::from_str(&body).map_err(other)?;
213 take_attachments(&body);
214 if let Some(hash) = body.get("content_hash").and_then(Value::as_str).filter(|h| !h.is_empty()) {
215 let path = crate::identity::model_path(&part, &revision).to_string_lossy().replace('\\', "/");
216 let in_work = matches!(body.get("lifecycle").and_then(Value::as_str), Some("draft" | "inreview"));
217 if in_work { drafts.insert(path, hash.to_string()) } else { frozen.insert(path, hash.to_string()) };
218 }
219 }
220 }
221 let mut stmt = conn.prepare("SELECT body FROM workspace").map_err(other_sql)?;
223 let rows = stmt.query_map([], |r| r.get::<_, String>(0)).map_err(other_sql)?;
224 for body in rows {
225 let body: Value = serde_json::from_str(&body.map_err(other_sql)?).map_err(other)?;
226 for v in body.get("versions").and_then(Value::as_array).into_iter().flatten() {
227 if let Some(sha) = v.get("sha256").and_then(Value::as_str) {
228 blobs.insert(sha.to_string());
229 }
230 }
231 }
232 let tools: Option<String> = conn
235 .query_row("SELECT value FROM meta WHERE key = 'state.tools'", [], |r| r.get(0))
236 .map(Some)
237 .or_else(|error| if error == rusqlite::Error::QueryReturnedNoRows { Ok(None) } else { Err(error) })
238 .map_err(other_sql)?;
239 if let Some(tools) = tools {
240 let tools: Value = serde_json::from_str(&tools).map_err(other)?;
241 for tool in tools.as_array().into_iter().flatten() {
242 if let Some(sha) = tool.pointer("/picture/sha256").and_then(Value::as_str) {
243 blobs.insert(sha.to_string());
244 }
245 }
246 }
247 let mut counts = BTreeMap::new();
248 let tables: Vec<String> = {
249 let mut stmt = conn
250 .prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' AND name NOT LIKE '%search%' ORDER BY name")
251 .map_err(other_sql)?;
252 let names = stmt.query_map([], |r| r.get::<_, String>(0)).map_err(other_sql)?;
253 names.collect::<Result<_, _>>().map_err(other_sql)?
254 };
255 for table in tables {
256 if !table.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_') {
257 continue;
258 }
259 let n: i64 = conn.query_row(&format!("SELECT count(*) FROM {table}"), [], |r| r.get(0)).unwrap_or(-1);
260 counts.insert(table, n);
261 }
262 let seq = conn
263 .query_row("SELECT value FROM meta WHERE key = 'seq'", [], |r| r.get::<_, String>(0))
264 .ok()
265 .and_then(|v| v.trim_matches('"').parse::<u64>().ok())
266 .unwrap_or(0);
267 let schema_version: i64 = conn.query_row("PRAGMA user_version", [], |r| r.get(0)).map_err(other_sql)?;
268 Ok(Wanted { drafts, frozen, blobs, seq, counts, schema_version })
269}
270
271fn other_sql(error: rusqlite::Error) -> io::Error {
272 other(error.to_string())
273}
274
275fn walk(dir: &Path) -> io::Result<Vec<String>> {
277 let mut out = Vec::new();
278 if !dir.exists() {
279 return Ok(out);
280 }
281 let mut stack = vec![PathBuf::new()];
282 while let Some(relative) = stack.pop() {
283 for entry in fs::read_dir(dir.join(&relative))? {
284 let entry = entry?;
285 let name = entry.file_name();
286 if name == ".git" {
287 continue;
288 }
289 let path = relative.join(&name);
290 let kind = entry.file_type()?;
291 if kind.is_dir() {
292 stack.push(path);
293 } else if kind.is_file() {
294 out.push(path.to_string_lossy().replace('\\', "/"));
295 }
296 }
297 }
298 out.sort();
299 Ok(out)
300}
301
302struct Stage {
304 dir: PathBuf,
305}
306
307impl Drop for Stage {
308 fn drop(&mut self) {
309 let _ = fs::remove_dir_all(&self.dir);
310 }
311}
312
313fn copy_hashed(from: &Path, to: &Path) -> io::Result<Option<(u64, String)>> {
315 fs::create_dir_all(to.parent().expect("a staged file has a directory"))?;
316 let mut source = match fs::File::open(from) {
317 Ok(file) => file,
318 Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None),
319 Err(error) => return Err(error),
320 };
321 let mut target = fs::File::create(to)?;
322 let mut hasher = Sha256::new();
323 let mut buffer = vec![0u8; 256 * 1024];
324 let mut size = 0u64;
325 loop {
326 let n = source.read(&mut buffer)?;
327 if n == 0 {
328 break;
329 }
330 size += n as u64;
331 hasher.update(&buffer[..n]);
332 target.write_all(&buffer[..n])?;
333 }
334 Ok(Some((size, format!("{:x}", hasher.finalize()))))
335}
336
337pub enum Attempt {
339 Done(Manifest),
340 Retry(String),
341}
342
343pub type Hold<'a> = &'a dyn Fn(&mut dyn FnMut() -> io::Result<Attempt>) -> io::Result<Attempt>;
347
348pub fn unheld(f: &mut dyn FnMut() -> io::Result<Attempt>) -> io::Result<Attempt> {
350 f()
351}
352
353fn attempt(data: &Path, scripts: &Path, stage: &Path, hold: Hold<'_>, adjust: bool) -> io::Result<Attempt> {
354 let _ = fs::remove_dir_all(stage);
355 fs::create_dir_all(stage)?;
356 let snapshot = stage.join(crate::db::SQLITE_FILE);
357 let mut files = Vec::new();
358 let mut adjusted: Vec<String> = Vec::new();
359 use rusqlite::{Connection, OpenFlags};
360 let source = data.join(crate::db::SQLITE_FILE);
361 if !source.exists() {
362 return Err(other(format!("{} has no {}", data.display(), crate::db::SQLITE_FILE)));
363 }
364 let conn = Connection::open_with_flags(&source, OpenFlags::SQLITE_OPEN_READ_ONLY).map_err(other_sql)?;
365 conn.busy_timeout(std::time::Duration::from_secs(30)).map_err(other_sql)?;
366 let mut moved: Vec<(String, Option<(u64, String)>)> = Vec::new();
367 let mut found: Option<Wanted> = None;
377 let first = hold(&mut || {
378 conn.execute_batch("BEGIN").map_err(other_sql)?;
379 let wanted = wanted(&conn)?;
380 for (path, expected) in &wanted.drafts {
381 match copy_hashed(&data.join(path), &stage.join(path))? {
382 None if adjust => moved.push((path.clone(), None)),
383 None => return Ok(Attempt::Retry(format!("{path} is gone"))),
384 Some((size, got)) if &got != expected => {
385 if !adjust {
386 return Ok(Attempt::Retry(format!("{path} changed during the copy")));
387 }
388 moved.push((path.clone(), Some((size, got.clone()))));
389 files.push(FileEntry { path: path.clone(), size, sha256: got });
390 }
391 Some((size, sha256)) => files.push(FileEntry { path: path.clone(), size, sha256 }),
392 }
393 }
394 found = Some(wanted);
395 Ok(Attempt::Done(Manifest {
396 format: String::new(),
397 version: 0,
398 created_at: 0,
399 schema_version: 0,
400 counts: BTreeMap::new(),
401 seq: 0,
402 attempts: 0,
403 adjusted: Vec::new(),
404 files: Vec::new(),
405 }))
406 })?;
407 if let Attempt::Retry(why) = first {
408 let _ = conn.execute_batch("ROLLBACK");
409 return Ok(Attempt::Retry(why));
410 }
411 let wanted = found.expect("the held step read the snapshot");
412
413 for (path, expected) in &wanted.frozen {
417 match copy_hashed(&data.join(path), &stage.join(path))? {
418 None => return Ok(Attempt::Retry(format!("{path} is gone"))),
419 Some((_, got)) if &got != expected => {
420 return Err(other(format!("{path} does not match the hash its released revision records")))
421 }
422 Some((size, sha256)) => files.push(FileEntry { path: path.clone(), size, sha256 }),
423 }
424 }
425 for sha in &wanted.blobs {
426 if !crate::attach::is_sha256(sha) {
427 return Err(other(format!("the snapshot names a blob '{sha}' that is not a SHA-256")));
428 }
429 let path = format!("blobs/{}/{sha}", &sha[..2]);
430 match copy_hashed(&data.join(&path), &stage.join(&path))? {
431 None => return Ok(Attempt::Retry(format!("{path} is gone"))),
432 Some((_, got)) if &got != sha => return Err(other(format!("{path} does not hash to its name"))),
433 Some((size, sha256)) => files.push(FileEntry { path, size, sha256 }),
434 }
435 }
436 {
437 let mut copy = Connection::open(&snapshot).map_err(other_sql)?;
440 let backup = rusqlite::backup::Backup::new(&conn, &mut copy).map_err(other_sql)?;
441 backup.step(-1).map_err(other_sql)?;
442 drop(backup);
443 copy.pragma_update(None, "journal_mode", "DELETE").map_err(other_sql)?;
445 }
446 conn.execute_batch("COMMIT").map_err(other_sql)?;
447 drop(conn);
448 if !moved.is_empty() {
449 adjust_snapshot(&snapshot, &moved)?;
450 adjusted = moved.into_iter().map(|(p, _)| p).collect();
451 }
452 let (size, sha256) = hash_file(&snapshot)?;
453 files.insert(0, FileEntry { path: crate::db::SQLITE_FILE.to_string(), size, sha256 });
454 for relative in walk(scripts)? {
455 let path = format!("scripts/{relative}");
456 if let Some((size, sha256)) = copy_hashed(&scripts.join(&relative), &stage.join(&path))? {
457 files.push(FileEntry { path, size, sha256 });
458 }
459 }
460 Ok(Attempt::Done(Manifest {
461 format: FORMAT.into(),
462 version: VERSION,
463 created_at: now(),
464 schema_version: wanted.schema_version,
465 counts: wanted.counts,
466 seq: wanted.seq,
467 attempts: 0,
468 adjusted,
469 files,
470 }))
471}
472
473fn adjust_snapshot(snapshot: &Path, moved: &[(String, Option<(u64, String)>)]) -> io::Result<()> {
477 let conn = rusqlite::Connection::open(snapshot).map_err(other_sql)?;
478 for (path, now) in moved {
479 let segments: Vec<_> = path.split('/').collect();
480 let (part, revision) = match segments.as_slice() {
481 ["models", part, revision] => (
482 crate::identity::unsegment(part).ok_or_else(|| other("invalid model part path"))?,
483 crate::identity::unsegment(revision.strip_suffix(".json").ok_or_else(|| other("invalid model revision path"))?).ok_or_else(|| other("invalid model revision path"))?,
484 ),
485 _ => return Err(other("invalid model path")),
486 };
487 let body: String = conn
488 .query_row("SELECT body FROM revisions WHERE part_id = ?1 AND id = ?2", [&part, &revision], |r| r.get(0))
489 .map_err(other_sql)?;
490 let mut body: Value = serde_json::from_str(&body).map_err(other)?;
491 let (size, hash) = now.clone().unwrap_or((0, String::new()));
492 body["content_hash"] = json!(hash);
493 body["size"] = json!(size);
494 conn.execute("UPDATE revisions SET body = ?1 WHERE part_id = ?2 AND id = ?3", [body.to_string(), part, revision]).map_err(other_sql)?;
495 }
496 Ok(())
497}
498
499pub fn backup(data: &Path, scripts: Option<&Path>, out: &Path) -> io::Result<Manifest> {
503 backup_held(data, scripts, out, &unheld)
504}
505
506pub fn backup_held(data: &Path, scripts: Option<&Path>, out: &Path, hold: Hold<'_>) -> io::Result<Manifest> {
508 let scripts = scripts.map(Path::to_path_buf).unwrap_or_else(|| data.join("scripts"));
509 let parent = out.parent().filter(|p| !p.as_os_str().is_empty()).unwrap_or(Path::new("."));
510 fs::create_dir_all(parent)?;
511 let stage = Stage { dir: parent.join(format!(".brep-backup-{}", crate::auth::new_id())) };
512 let mut last = String::new();
513 for tries in 1..=ATTEMPTS {
514 let adjust = tries > ADJUST_AFTER;
516 match attempt(data, &scripts, &stage.dir, hold, adjust)? {
517 Attempt::Retry(why) => {
518 last = why;
519 std::thread::sleep(std::time::Duration::from_millis(20 * tries as u64));
520 }
521 Attempt::Done(mut manifest) => {
522 manifest.attempts = tries;
523 write_archive(&stage.dir, &manifest, out)?;
524 return Ok(manifest);
525 }
526 }
527 }
528 Err(other(format!(
529 "could not take a consistent backup in {ATTEMPTS} tries — the store kept changing ({last}). \
530 A backup taken by the server itself (the Backups page, or --backup-dir) holds writes off briefly and always succeeds"
531 )))
532}
533
534fn write_archive(stage: &Path, manifest: &Manifest, out: &Path) -> io::Result<()> {
535 let partial = out.with_extension("partial");
536 {
537 let file = fs::File::create(&partial)?;
538 let gz = flate2::write::GzEncoder::new(io::BufWriter::new(file), flate2::Compression::default());
539 let mut tar = tar::Builder::new(gz);
540 let text = serde_json::to_vec_pretty(manifest).map_err(other)?;
541 let mut header = tar::Header::new_gnu();
542 header.set_size(text.len() as u64);
543 header.set_mode(0o644);
544 header.set_mtime(manifest.created_at);
545 header.set_cksum();
546 tar.append_data(&mut header, "manifest.json", text.as_slice())?;
547 for entry in &manifest.files {
548 let mut file = fs::File::open(stage.join(&entry.path))?;
549 tar.append_file(&entry.path, &mut file)?;
550 }
551 let gz = tar.into_inner()?;
552 let mut writer = gz.finish()?;
553 writer.flush()?;
554 writer.into_inner().map_err(|e| e.into_error())?.sync_all()?;
555 }
556 fs::rename(&partial, out)
557}
558
559fn safe_relative(raw: &Path) -> io::Result<PathBuf> {
561 let mut out = PathBuf::new();
562 for part in raw.components() {
563 match part {
564 Component::Normal(p) => out.push(p),
565 Component::CurDir => {}
566 _ => return Err(other(format!("the archive names an unsafe path: {}", raw.display()))),
567 }
568 }
569 if out.as_os_str().is_empty() {
570 return Err(other("the archive names an empty path"));
571 }
572 Ok(out)
573}
574
575pub fn read_manifest(archive: &Path) -> io::Result<Manifest> {
577 let file = fs::File::open(archive)?;
578 let mut tar = tar::Archive::new(flate2::read::GzDecoder::new(io::BufReader::new(file)));
579 let mut entries = tar.entries()?;
580 let first = entries.next().ok_or_else(|| other("the archive is empty"))??;
581 if first.path()?.as_ref() != Path::new("manifest.json") {
582 return Err(other("the archive does not start with manifest.json — is it a brep-plm backup?"));
583 }
584 let manifest: Manifest = serde_json::from_reader(first).map_err(other)?;
585 if manifest.format != FORMAT {
586 return Err(other(format!("the archive's format is '{}', not '{FORMAT}'", manifest.format)));
587 }
588 if manifest.version != VERSION || manifest.schema_version != i64::from(crate::sql::schema_version()) {
589 return Err(other(format!("the archive is version {}, different from this server's {VERSION}", manifest.version)));
590 }
591 Ok(manifest)
592}
593
594pub fn restore(archive: &Path, data: &Path) -> io::Result<Manifest> {
597 let existed = data.exists();
598 if existed && fs::read_dir(data)?.next().is_some() {
599 return Err(other(format!("{} is not empty — restore into a new directory", data.display())));
600 }
601 fs::create_dir_all(data)?;
602 match restore_into(archive, data) {
603 Ok(manifest) => Ok(manifest),
604 Err(error) => {
605 if existed {
607 if let Ok(entries) = fs::read_dir(data) {
608 for entry in entries.flatten() {
609 let path = entry.path();
610 let _ = if path.is_dir() { fs::remove_dir_all(&path) } else { fs::remove_file(&path) };
611 }
612 }
613 } else {
614 let _ = fs::remove_dir_all(data);
615 }
616 Err(error)
617 }
618 }
619}
620
621fn restore_into(archive: &Path, data: &Path) -> io::Result<Manifest> {
622 let file = fs::File::open(archive)?;
623 let mut tar = tar::Archive::new(flate2::read::GzDecoder::new(io::BufReader::new(file)));
624 let mut entries = tar.entries()?;
625 let first = entries.next().ok_or_else(|| other("the archive is empty"))??;
626 if first.path()?.as_ref() != Path::new("manifest.json") {
627 return Err(other("the archive does not start with manifest.json — is it a brep-plm backup?"));
628 }
629 let manifest: Manifest = serde_json::from_reader(first).map_err(other)?;
630 if manifest.format != FORMAT || manifest.version != VERSION || manifest.schema_version != i64::from(crate::sql::schema_version()) {
631 return Err(other("the archive is not a backup this server can restore"));
632 }
633 let listed: BTreeMap<&str, &FileEntry> = manifest.files.iter().map(|f| (f.path.as_str(), f)).collect();
634 let mut seen = BTreeSet::new();
635 for entry in entries {
636 let mut entry = entry?;
637 if !entry.header().entry_type().is_file() {
638 return Err(other("the archive holds something that is not a file"));
639 }
640 let raw = entry.path()?.into_owned();
641 let relative = safe_relative(&raw)?;
642 let key = relative.to_string_lossy().replace('\\', "/");
643 let Some(expected) = listed.get(key.as_str()) else {
644 return Err(other(format!("{key} is in the archive but not in its manifest")));
645 };
646 if !seen.insert(key.clone()) {
647 return Err(other(format!("{key} is in the archive twice")));
648 }
649 let target = data.join(&relative);
650 fs::create_dir_all(target.parent().expect("a file has a directory"))?;
651 let mut out = fs::File::create(&target)?;
652 let mut hasher = Sha256::new();
653 let mut buffer = vec![0u8; 256 * 1024];
654 let mut size = 0u64;
655 loop {
656 let n = entry.read(&mut buffer)?;
657 if n == 0 {
658 break;
659 }
660 size += n as u64;
661 hasher.update(&buffer[..n]);
662 out.write_all(&buffer[..n])?;
663 }
664 out.sync_all()?;
665 let sha = format!("{:x}", hasher.finalize());
666 if size != expected.size || sha != expected.sha256 {
667 return Err(other(format!("{key} does not match its manifest (size or SHA-256) — the backup is damaged")));
668 }
669 }
670 for file in &manifest.files {
671 if !seen.contains(&file.path) {
672 return Err(other(format!("{} is in the manifest but missing from the archive", file.path)));
673 }
674 }
675 {
676 use rusqlite::{Connection, OpenFlags};
677 let conn = Connection::open_with_flags(data.join(crate::db::SQLITE_FILE), OpenFlags::SQLITE_OPEN_READ_ONLY)
678 .map_err(other_sql)?;
679 let check: String = conn.query_row("PRAGMA integrity_check", [], |r| r.get(0)).map_err(other_sql)?;
680 if check != "ok" {
681 return Err(other(format!("the restored database fails its integrity check: {check}")));
682 }
683 }
684 Ok(manifest)
685}
686
687pub const EXPORT_FORMAT: &str = "brep-plm-export";
693pub const EXPORT_VERSION: u32 = 1;
694
695fn revision_json(state: &State, part: &Part, revision: &Revision) -> Value {
696 let mut value = serde_json::to_value(revision).unwrap_or(Value::Null);
697 if let Some(object) = value.as_object_mut() {
698 object.remove("lock");
700 object.insert("document_key".into(), json!(revision.document_key(&part.id)));
701 let uses: Vec<Value> = revision
702 .uses
703 .iter()
704 .map(|u| {
705 let child = state.part(&u.part);
706 let child_revision = child.and_then(|c| if u.revision.is_empty() { None } else { c.revision(&u.revision) });
707 let mut line = serde_json::to_value(u).unwrap_or(Value::Null);
708 line["part_number"] = json!(child.map(|c| c.number.clone()).unwrap_or_default());
709 line["revision_label"] = json!(child_revision.map(|r| r.label.clone()).unwrap_or_default());
710 line
711 })
712 .collect();
713 object.insert("uses".into(), Value::Array(uses));
714 }
715 value
716}
717
718pub fn export_json(state: &State) -> Value {
724 let users: Vec<Value> = state
725 .users
726 .iter()
727 .map(|u| {
728 json!({
729 "id": u.id, "username": u.username, "display_name": u.display_name,
730 "email": u.email, "groups": u.groups, "active": u.active, "created_at": u.created_at,
731 })
732 })
733 .collect();
734 let parts: Vec<Value> = state
735 .parts
736 .iter()
737 .map(|part| {
738 let mut value = serde_json::to_value(part).unwrap_or(Value::Null);
739 value["category_path"] = json!(crate::catalog::path_name(&state.categories, &part.category));
740 value["revisions"] = Value::Array(part.revisions.iter().map(|r| revision_json(state, part, r)).collect());
741 value
742 })
743 .collect();
744 json!({
745 "format": EXPORT_FORMAT,
746 "version": EXPORT_VERSION,
747 "exported_at": now(),
748 "seq": state.seq,
749 "settings": state.settings,
750 "part_types": state.part_types,
751 "categories": state.categories,
752 "manufacturers": state.manufacturers,
753 "suppliers": state.suppliers,
754 "users": users,
755 "parts": parts,
756 })
757}
758
759pub fn parts_csv(state: &State) -> String {
761 let mut out = String::from(
762 "Number,Name,Type,Class,Category,Tags,Description,Latest rev,Latest state,Current release,Revisions,MPN,Manufacturer,Attributes\n",
763 );
764 for part in state.parts.iter() {
765 let latest = part.latest();
766 let preferred = part.sourcing.iter().find(|m| m.preferred).or(part.sourcing.first());
767 let maker = preferred
768 .and_then(|m| state.manufacturers.iter().find(|c| c.id == m.manufacturer))
769 .map(|c| c.name.clone())
770 .unwrap_or_default();
771 let attributes: Vec<String> = part.attributes.iter().map(|(k, v)| {
772 let text = match v { Value::String(s) => s.clone(), other => other.to_string() };
773 format!("{k}={text}")
774 }).collect();
775 let row = [
776 part.number.clone(),
777 part.name.clone(),
778 part.part_type.clone(),
779 part.document_class.as_str().to_string(),
780 crate::catalog::path_name(&state.categories, &part.category),
781 part.tags.join("; "),
782 part.description.clone(),
783 latest.map(|r| r.label.clone()).unwrap_or_default(),
784 latest.map(|r| r.lifecycle.as_str().to_string()).unwrap_or_default(),
785 part.current_release().map(|r| r.label.clone()).unwrap_or_default(),
786 part.revisions.len().to_string(),
787 preferred.map(|m| m.mpn.clone()).unwrap_or_default(),
788 maker,
789 attributes.join("; "),
790 ];
791 out.push_str(&row.iter().map(|c| crate::bom::csv_cell(c)).collect::<Vec<_>>().join(","));
792 out.push('\n');
793 }
794 out
795}
796
797pub fn structure_csv(state: &State) -> String {
799 let mut out = String::from(
800 "Parent number,Parent rev,Parent state,Child number,Child rev,Floating,Quantity,Unit,Find,Reference,Notes\n",
801 );
802 for part in state.parts.iter() {
803 for revision in &part.revisions {
804 for line in &revision.uses {
805 let child = state.part(&line.part);
806 let child_revision = child.and_then(|c| crate::bom::resolve(c, line));
807 let row = [
808 part.number.clone(),
809 revision.label.clone(),
810 revision.lifecycle.as_str().to_string(),
811 child.map(|c| c.number.clone()).unwrap_or_default(),
812 child_revision.map(|r| r.label.clone()).unwrap_or_default(),
813 if line.revision.is_empty() { "yes".into() } else { String::new() },
814 crate::bom::qty(line.quantity),
815 line.unit.clone(),
816 line.find_number.clone(),
817 line.reference.clone(),
818 line.notes.clone(),
819 ];
820 out.push_str(&row.iter().map(|c| crate::bom::csv_cell(c)).collect::<Vec<_>>().join(","));
821 out.push('\n');
822 }
823 }
824 }
825 out
826}
827
828pub const DEFAULT_KEEP: usize = 7;
834pub const PREFIX: &str = "brep-plm-";
836pub const SUFFIX: &str = ".tar.gz";
837
838#[derive(Debug, Clone, Serialize, Default)]
840pub struct LastBackup {
841 pub at: u64,
842 pub file: String,
844 pub size: u64,
845 pub files: usize,
846 pub attempts: usize,
847 pub seq: u64,
848 pub ok: bool,
849 pub error: String,
850 pub trigger: String,
852}
853
854#[derive(Debug, Default)]
855pub struct Status {
856 last: std::sync::Mutex<Option<LastBackup>>,
857 running: std::sync::atomic::AtomicBool,
858}
859
860impl Status {
861 pub fn last(&self) -> Option<LastBackup> {
862 self.last.lock().unwrap_or_else(|e| e.into_inner()).clone()
863 }
864
865 pub fn running(&self) -> bool {
866 self.running.load(std::sync::atomic::Ordering::SeqCst)
867 }
868
869 fn begin(&self) -> Option<Running<'_>> {
871 use std::sync::atomic::Ordering;
872 self.running.compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst).ok()?;
873 Some(Running(self))
874 }
875
876 fn record(&self, last: LastBackup) {
877 *self.last.lock().unwrap_or_else(|e| e.into_inner()) = Some(last);
878 }
879}
880
881struct Running<'a>(&'a Status);
882
883impl Drop for Running<'_> {
884 fn drop(&mut self) {
885 self.0.running.store(false, std::sync::atomic::Ordering::SeqCst);
886 }
887}
888
889pub fn stamp(seconds: u64) -> String {
891 let days = (seconds / 86_400) as i64;
892 let rest = seconds % 86_400;
893 let z = days + 719_468;
895 let era = z.div_euclid(146_097);
896 let doe = z - era * 146_097;
897 let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
898 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
899 let mp = (5 * doy + 2) / 153;
900 let day = doy - (153 * mp + 2) / 5 + 1;
901 let month = if mp < 10 { mp + 3 } else { mp - 9 };
902 let year = yoe + era * 400 + if month <= 2 { 1 } else { 0 };
903 format!("{year:04}{month:02}{day:02}-{:02}{:02}{:02}", rest / 3600, rest % 3600 / 60, rest % 60)
904}
905
906pub fn is_backup_name(name: &str) -> bool {
909 name.starts_with(PREFIX)
910 && name.ends_with(SUFFIX)
911 && name.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'.' || b == b'_')
912}
913
914#[derive(Debug, Clone, Serialize)]
915pub struct SavedBackup {
916 pub name: String,
917 pub size: u64,
918 pub modified: u64,
919}
920
921pub fn saved(dir: &Path) -> Vec<SavedBackup> {
923 let mut out = Vec::new();
924 if let Ok(entries) = fs::read_dir(dir) {
925 for entry in entries.flatten() {
926 let name = entry.file_name().to_string_lossy().to_string();
927 if !is_backup_name(&name) {
928 continue;
929 }
930 let Ok(meta) = entry.metadata() else { continue };
931 let modified = meta
932 .modified()
933 .ok()
934 .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
935 .map(|d| d.as_secs())
936 .unwrap_or(0);
937 out.push(SavedBackup { name, size: meta.len(), modified });
938 }
939 }
940 let key = |n: &str| n.trim_end_matches(SUFFIX).to_string();
943 out.sort_by(|a, b| key(&b.name).cmp(&key(&a.name)));
944 out
945}
946
947impl crate::db::Db {
948 pub fn backup_now(&self, trigger: &str) -> Result<LastBackup, crate::Error> {
951 let config = self.security().config.clone();
952 let dir = config
953 .backup_dir
954 .clone()
955 .ok_or_else(|| crate::Error::conflict("no backup directory is set (--backup-dir) — download a backup instead"))?;
956 let _running = self
957 .backups()
958 .begin()
959 .ok_or_else(|| crate::Error::conflict("a backup is already running"))?;
960 let at = now();
961 let mut name = format!("{PREFIX}{}{SUFFIX}", stamp(at));
962 let mut n = 1;
963 while dir.join(&name).exists() {
964 n += 1;
965 name = format!("{PREFIX}{}-{n:02}{SUFFIX}", stamp(at));
966 }
967 let result = self.backup_into(&dir.join(&name));
968 let last = match &result {
969 Ok(manifest) => LastBackup {
970 at,
971 file: name.clone(),
972 size: fs::metadata(dir.join(&name)).map(|m| m.len()).unwrap_or(0),
973 files: manifest.files.len(),
974 attempts: manifest.attempts,
975 seq: manifest.seq,
976 ok: true,
977 error: String::new(),
978 trigger: trigger.into(),
979 },
980 Err(error) => LastBackup { at, ok: false, error: error.to_string(), trigger: trigger.into(), ..Default::default() },
981 };
982 self.backups().record(last.clone());
983 self.record(
984 "backup",
985 crate::model::EntityRef { kind: "backup".into(), id: name.clone(), label: name.clone(), part_id: String::new() },
986 if last.ok { format!("{trigger}: {} files, {} bytes", last.files, last.size) } else { format!("{trigger}: FAILED {}", last.error) },
987 );
988 if let Err(error) = result {
989 return Err(crate::Error::internal(error));
990 }
991 let keep = if config.backup_keep == 0 { DEFAULT_KEEP } else { config.backup_keep };
992 for old in saved(&dir).into_iter().skip(keep) {
993 let _ = fs::remove_file(dir.join(&old.name));
994 }
995 Ok(last)
996 }
997
998 pub fn backup_into(&self, out: &Path) -> io::Result<Manifest> {
1002 let hold = |f: &mut dyn FnMut() -> io::Result<Attempt>| self.read(|_| f());
1003 let blobs = crate::attach::BlobsHeld::new(self.root());
1006 let manifest = backup_held(self.root(), Some(self.scripts().dir()), out, &hold);
1007 blobs.release(self).map_err(other)?;
1008 manifest
1009 }
1010
1011 pub fn backup_to_temp(&self) -> Result<(PathBuf, Manifest), crate::Error> {
1014 let _running = self
1015 .backups()
1016 .begin()
1017 .ok_or_else(|| crate::Error::conflict("a backup is already running"))?;
1018 let at = now();
1019 let path = std::env::temp_dir().join(format!("{PREFIX}{}-{}{SUFFIX}", stamp(at), crate::auth::new_id()));
1020 let result = self.backup_into(&path);
1021 let last = match &result {
1022 Ok(manifest) => LastBackup {
1023 at,
1024 size: fs::metadata(&path).map(|m| m.len()).unwrap_or(0),
1025 files: manifest.files.len(),
1026 attempts: manifest.attempts,
1027 seq: manifest.seq,
1028 ok: true,
1029 trigger: "download".into(),
1030 ..Default::default()
1031 },
1032 Err(error) => LastBackup { at, ok: false, error: error.to_string(), trigger: "download".into(), ..Default::default() },
1033 };
1034 self.backups().record(last.clone());
1035 self.record(
1036 "backup",
1037 crate::model::EntityRef { kind: "backup".into(), id: "download".into(), label: "download".into(), part_id: String::new() },
1038 if last.ok { format!("download: {} files, {} bytes", last.files, last.size) } else { format!("download: FAILED {}", last.error) },
1039 );
1040 let manifest = result.map_err(crate::Error::internal)?;
1041 Ok((path, manifest))
1042 }
1043}
1044
1045pub fn load_snapshot(data: &Path) -> io::Result<State> {
1048 let dir = std::env::temp_dir().join(format!(".brep-export-{}", crate::auth::new_id()));
1049 let stage = Stage { dir };
1050 fs::create_dir_all(&stage.dir)?;
1051 let snapshot = stage.dir.join(crate::db::SQLITE_FILE);
1052 {
1053 use rusqlite::{Connection, OpenFlags};
1054 let source = data.join(crate::db::SQLITE_FILE);
1055 if !source.exists() {
1056 return Err(other(format!("{} has no {}", data.display(), crate::db::SQLITE_FILE)));
1057 }
1058 let conn = Connection::open_with_flags(&source, OpenFlags::SQLITE_OPEN_READ_ONLY).map_err(other_sql)?;
1059 conn.busy_timeout(std::time::Duration::from_secs(30)).map_err(other_sql)?;
1060 conn.execute("VACUUM INTO ?1", [snapshot.to_string_lossy().as_ref()]).map_err(other_sql)?;
1061 }
1062 let sql = crate::sql::Sql::open(&snapshot).map_err(other_sql)?;
1063 let state = sql.load().map_err(other_sql)?.unwrap_or_default();
1064 drop(sql);
1065 Ok(state)
1066}