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