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