1use std::collections::{BTreeMap, BTreeSet};
42use std::fs;
43use std::io;
44use std::path::{Path, PathBuf};
45use std::sync::{Arc, RwLock};
46
47use serde::{Deserialize, Serialize};
48use serde_json::{json, Value};
49
50use crate::audit::{self, AuditFilter, AuditSink};
51use crate::auth;
52use crate::bom;
53use crate::catalog;
54use crate::lifecycle;
55use crate::model::{
56 groups, ApiToken, AttributeDef, AuditEvent, EntityRef, Category, Company, DocumentClass, Lifecycle, Lock, NumberMode, Part, PartType, Revision, Session, Settings,
57 Timestamp, Use, User,
58};
59use crate::scripting::{self, HookResult, Scripts};
60use crate::security::{Security, ServerConfig};
61use crate::sourcing;
62use crate::sql::{self, Durability, Sql};
63use crate::table::Parts;
64use crate::Error;
65
66pub const CHANGE_LOG_LIMIT: usize = 4096;
69
70#[derive(Debug, Clone, Serialize, Deserialize)]
72pub struct Change {
73 pub seq: u64,
74 pub key: String,
75}
76
77#[derive(Debug, Default, Serialize, Deserialize)]
80pub struct State {
81 #[serde(default)]
83 pub tools: Vec<crate::tools::Tool>,
84 #[serde(default)]
85 pub next_tool: u64,
86 #[serde(default)]
92 pub jobs: crate::journal::Journaled<crate::jobs::Job>,
93 #[serde(default)]
95 pub next_job: u64,
96 pub workflows: Vec<crate::workflow::Definition>,
97 pub workflow_runs: Vec<crate::workflow::Run>,
98 pub bom_configuration: crate::bom_config::Configuration,
99 pub seq: u64,
100 pub users: Vec<User>,
101 #[serde(default)]
106 pub sessions: crate::journal::Journaled<Session>,
107 pub api_tokens: Vec<ApiToken>,
109 pub part_types: Vec<PartType>,
110 #[serde(default)]
112 pub parts: Parts,
113 pub categories: Vec<Category>,
115 pub manufacturers: Vec<Company>,
117 pub suppliers: Vec<Company>,
119 pub settings: Settings,
121 #[serde(default)]
124 pub workspace_model: u32,
125 pub changes: Vec<Change>,
126 pub changes_from: u64,
132 #[serde(default)]
136 pub workspace: crate::workspace::Workspace,
137}
138
139impl State {
140 pub(crate) fn touch_part(&mut self, part_id: &str) {
146 let keys: Vec<String> = self
147 .part(part_id)
148 .map(|part| part.revisions.iter().map(|r| r.document_key(&part.id)).collect())
149 .unwrap_or_default();
150 for key in keys {
151 self.touch(key);
152 }
153 }
154
155 pub(crate) fn touch(&mut self, key: String) {
158 let seq = self.seq;
159 self.changes.retain(|change| change.key != key);
160 self.changes.push(Change { seq, key });
161 if self.changes.len() > CHANGE_LOG_LIMIT {
162 let excess = self.changes.len() - CHANGE_LOG_LIMIT;
163 let dropped: Vec<Change> = self.changes.drain(..excess).collect();
164 if let Some(last) = dropped.last() {
165 self.changes_from = self.changes_from.max(last.seq);
166 }
167 }
168 }
169
170 pub fn user(&self, id: &str) -> Option<&User> {
171 self.users.iter().find(|u| u.id == id)
172 }
173
174 pub fn user_by_name(&self, username: &str) -> Option<&User> {
175 let username = username.trim().to_ascii_lowercase();
176 self.users
177 .iter()
178 .find(|u| u.username.to_ascii_lowercase() == username)
179 }
180
181 pub fn part(&self, id: &str) -> Option<&Part> {
182 self.parts.get(id)
183 }
184
185 pub fn part_type(&self, id: &str) -> Option<&PartType> {
186 self.part_types.iter().find(|t| t.id == id)
187 }
188
189 pub fn part_by_id_or_number(&self, key: &str) -> Option<&Part> {
191 let key = key.trim();
192 self.part(key).or_else(|| self.part_with_number(key))
193 }
194
195 pub fn part_with_number(&self, number: &str) -> Option<&Part> {
200 let number = number.trim();
201 self.parts.iter().find(|p| p.number.eq_ignore_ascii_case(number))
202 }
203
204 pub fn changes_floor(&self) -> u64 {
207 self.changes_from
208 }
209}
210
211#[derive(Clone)]
218pub struct Db {
219 root: PathBuf,
220 state: Arc<RwLock<State>>,
221 scripts: Arc<Scripts>,
222 security: Arc<Security>,
223 sql: Arc<Sql>,
225 _lock: Arc<crate::dirlock::DirLock>,
228 backups: Arc<crate::backup::Status>,
230 pub(crate) bake_worker: Arc<crate::bake_worker::Controller>,
231}
232
233pub fn now() -> Timestamp {
235 std::time::SystemTime::now()
236 .duration_since(std::time::UNIX_EPOCH)
237 .map(|d| d.as_secs())
238 .unwrap_or(0)
239}
240
241impl Db {
242 pub fn open(root: impl Into<PathBuf>) -> io::Result<(Self, Option<String>)> {
249 Self::open_with_scripts(root, None)
250 }
251
252 pub fn open_with_scripts(
256 root: impl Into<PathBuf>,
257 scripts: Option<PathBuf>,
258 ) -> io::Result<(Self, Option<String>)> {
259 Self::open_with(root, scripts, Durability::Full)
260 }
261
262 pub fn open_with(
265 root: impl Into<PathBuf>,
266 scripts: Option<PathBuf>,
267 durability: Durability,
268 ) -> io::Result<(Self, Option<String>)> {
269 let root = root.into();
270 let lock = crate::dirlock::DirLock::acquire(&root)?;
274 fs::create_dir_all(root.join("models"))?;
275 let scripts = Scripts::new(scripts.unwrap_or_else(|| root.join("scripts")))?;
276 let sql = Sql::open_with(root.join(SQLITE_FILE), durability).map_err(io::Error::other)?;
277 let loaded = sql.load().map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
278 let fresh = loaded.is_none();
279 let mut state = loaded.unwrap_or_default();
280 if state.parts.iter().any(|p| p.id != p.number || p.revisions.iter().any(|r| r.id != r.label)) {
281 return Err(io::Error::new(io::ErrorKind::InvalidData,
282 "part and revision identities must match their current number and label"));
283 }
284 let before = sql::small_value(&mut state);
285 if state.workspace.iter().next().is_none() {
288 state.workspace_model = crate::workspace::MODEL;
289 }
290
291 let mut seeded = None;
292 if state.part_types.is_empty() {
293 state.part_types.push(PartType {
296 id: "component".into(),
297 name: "Component".into(),
298 prefix: "CPART".into(),
299 digits: 9,
300 next: 1,
301 created_at: now(),
302 mode: Default::default(),
303 });
304 }
305 if state.users.is_empty() {
306 let password = auth::random_token(12);
307 state.users.push(User {
308 id: auth::new_id(),
309 username: "admin".into(),
310 display_name: "Administrator".into(),
311 email: String::new(),
312 password: auth::hash_password(&password),
313 groups: vec![groups::ADMIN.into()],
314 active: true,
315 created_at: now(),
316 });
317 seeded = Some(password);
318 }
319 let after = sql::small_value(&mut state);
320 if fresh || before != after {
321 let change = sql::Change {
322 before: &if fresh { Value::Object(Default::default()) } else { before },
323 after: &after,
324 parts: Vec::new(),
325 categories: &state.categories,
326 reindex: Vec::new(),
327 all_parts: &state.parts,
328 workspace: Vec::new(),
329 sessions: Vec::new(),
330 jobs: Vec::new(),
331 };
332 sql.write(&change, Vec::new()).map_err(io::Error::other)?;
333 }
334
335 let db = Db {
336 root,
337 state: Arc::new(RwLock::new(state)),
338 scripts: Arc::new(scripts),
339 security: Arc::new(Security::default()),
340 sql: Arc::new(sql),
341 _lock: Arc::new(lock),
342 backups: Arc::new(crate::backup::Status::default()),
343 bake_worker: Arc::new(crate::bake_worker::Controller::default()),
344 };
345 match db.sweep_blobs() {
348 Ok(0) => {}
349 Ok(n) => eprintln!("brep-plm: removed {n} unreferenced attachment file(s)"),
350 Err(error) => eprintln!("brep-plm: could not sweep attachment files: {error}"),
351 }
352 db.recover_workflows().map_err(io::Error::other)?;
353 if db.read(|state| state.workspace_model < crate::workspace::MODEL) {
354 db.mutate(crate::workspace::migrate).map_err(io::Error::other)?;
355 }
356 Ok((db, seeded))
357 }
358
359
360
361 pub fn root(&self) -> &Path {
364 &self.root
365 }
366
367 pub fn stop_bake_worker(&self) -> Result<crate::bake_worker::Status, Error> {
369 self.bake_worker.stop(self.security.config.bake_worker.as_ref())
370 }
371
372 pub fn scripts(&self) -> &Scripts {
373 &self.scripts
374 }
375
376 pub fn with_config(mut self, config: ServerConfig) -> Self {
379 self.security = Arc::new(Security { config, ..Security::default() });
380 self
381 }
382
383 pub fn backups(&self) -> &crate::backup::Status {
385 &self.backups
386 }
387
388 pub fn security(&self) -> &Security {
390 &self.security
391 }
392
393 pub fn script_editor_allowed(&self) -> bool {
396 !self.security.config.lock_script_editor && self.read(|state| state.settings.script_editor_enabled)
397 }
398
399 pub fn read<R>(&self, f: impl FnOnce(&State) -> R) -> R {
401 let state = self.state.read().unwrap_or_else(|e| e.into_inner());
402 f(&state)
403 }
404
405 pub fn mutate<R>(&self, f: impl FnOnce(&mut State) -> Result<R, Error>) -> Result<R, Error> {
422 let mut state = self.state.write().unwrap_or_else(|e| e.into_inner());
423 let before = sql::small_value(&mut state);
424 state.parts.begin();
425 state.workspace.begin();
426 state.sessions.begin();
427 state.jobs.begin();
428 state.seq += 1;
429 match f(&mut state) {
430 Ok(value) => {
431 let touched = state.parts.commit();
432 let entries = state.workspace.commit();
433 let sessions = state.sessions.commit();
434 let jobs = state.jobs.commit();
435 match self.persist(&mut state, &before, &touched, &entries, &sessions, &jobs) {
436 Ok(()) => Ok(value),
437 Err(error) => {
438 state.parts.undo(touched);
439 state.workspace.undo(entries);
440 state.sessions.undo(sessions);
441 state.jobs.undo(jobs);
442 restore_small(&mut state, &before)?;
443 Err(error)
444 }
445 }
446 }
447 Err(error) => {
448 state.parts.rollback();
449 state.workspace.rollback();
450 state.sessions.rollback();
451 state.jobs.rollback();
452 restore_small(&mut state, &before)?;
453 Err(error)
454 }
455 }
456 }
457
458 fn persist(
460 &self,
461 state: &mut State,
462 before: &Value,
463 touched: &[crate::table::Touched],
464 entries: &[crate::journal::Touched<crate::model::WorkspaceEntry>],
465 sessions: &[crate::journal::Touched<Session>],
466 jobs: &[crate::journal::Touched<crate::jobs::Job>],
467 ) -> Result<(), Error> {
468 let after = sql::small_value(state);
469 let mut old_parts = Vec::new();
472 let mut new_parts = Vec::new();
473 let mut changed = Vec::new();
474 for t in touched {
475 let now_part = &state.parts[t.position];
476 let now_value = serde_json::to_value(now_part).map_err(Error::internal)?;
477 let was_value = match &t.before {
478 Some(part) => Some(serde_json::to_value(part).map_err(Error::internal)?),
479 None => None,
480 };
481 if was_value.as_ref() == Some(&now_value) {
482 continue;
483 }
484 old_parts.extend(was_value);
485 new_parts.push(now_value);
486 changed.push((t.position, now_part));
487 }
488 let (old_entries, new_entries, workspace) = journal_rows(&state.workspace, entries)?;
491 let (old_sessions, new_sessions, session_rows) = journal_rows(&state.sessions, sessions)?;
492 let (old_jobs, new_jobs, job_rows) = journal_rows(&state.jobs, jobs)?;
493 let mut old = before.clone();
494 let mut new = after.clone();
495 if let (Some(o), Some(n)) = (old.as_object_mut(), new.as_object_mut()) {
496 o.insert("parts".into(), Value::Array(old_parts));
497 n.insert("parts".into(), Value::Array(new_parts));
498 o.insert("workspace".into(), Value::Array(old_entries));
499 n.insert("workspace".into(), Value::Array(new_entries));
500 o.insert("sessions".into(), Value::Array(old_sessions));
501 n.insert("sessions".into(), Value::Array(new_sessions));
502 o.insert("jobs".into(), Value::Array(old_jobs));
503 n.insert("jobs".into(), Value::Array(new_jobs));
504 }
505 let events = audit::refine(audit::diff(&old, &new, &audit::current_actor(), now(), state.seq));
506 let mut reindex = Vec::new();
510 if before.get("categories") != after.get("categories") {
511 let old_categories: Vec<Category> =
512 serde_json::from_value(before.get("categories").cloned().unwrap_or_default()).unwrap_or_default();
513 let moved: BTreeSet<String> = old_categories
514 .iter()
515 .chain(state.categories.iter())
516 .map(|c| c.id.to_ascii_lowercase())
517 .filter(|id| catalog::path_name(&old_categories, id) != catalog::path_name(&state.categories, id))
518 .collect();
519 reindex = state
520 .parts
521 .iter()
522 .enumerate()
523 .filter(|(_, p)| moved.contains(&p.category.to_ascii_lowercase()))
524 .map(|(i, _)| i)
525 .collect();
526 }
527 let change = sql::Change {
528 before,
529 after: &after,
530 parts: changed,
531 categories: &state.categories,
532 reindex,
533 all_parts: &state.parts,
534 workspace,
535 sessions: session_rows,
536 jobs: job_rows,
537 };
538 self.sql.write(&change, events).map(|_| ()).map_err(|error| {
539 if sql::is_constraint(&error) {
540 Error::conflict(format!("the store refused the change: {error}"))
541 } else {
542 Error::internal(error)
543 }
544 })
545 }
546
547 pub fn record(&self, action: &str, entity: EntityRef, detail: impl Into<String>) {
550 let event = AuditEvent {
551 id: 0,
552 at: now(),
553 actor: audit::current_actor(),
554 action: action.to_string(),
555 entity,
556 changes: BTreeMap::new(),
557 detail: detail.into(),
558 seq: 0,
559 };
560 if let Err(error) = self.sql.append(vec![event]) {
561 eprintln!("brep-plm: audit: could not append to the log: {error}");
562 }
563 }
564
565 pub fn audit_query(&self, filter: &AuditFilter) -> Result<Vec<AuditEvent>, Error> {
567 self.sql.query(filter).map_err(Error::internal)
568 }
569
570 pub fn sql(&self) -> &Sql {
572 &self.sql
573 }
574
575 pub(crate) fn document_path(&self, key: &str) -> Result<PathBuf, Error> {
578 let (part, revision) = crate::identity::split_key(key)
579 .ok_or_else(|| Error::bad_request(format!("'{key}' is not a usable document key")))?;
580 Ok(self.root.join(crate::identity::model_path(&part, &revision)))
581 }
582
583 pub fn read_document(&self, key: &str) -> Result<Option<String>, Error> {
585 let path = self.document_path(key)?;
586 match fs::read_to_string(path) {
587 Ok(text) => Ok(Some(text)),
588 Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None),
589 Err(error) => Err(Error::internal(error)),
590 }
591 }
592
593 pub fn write_document(&self, part_id: &str, revision_id: &str, body: &str) -> Result<u64, Error> {
607 self.write_document_inner(part_id, revision_id, body, None, None).map(|(seq, _)| seq)
608 }
609
610 pub fn write_document_deriving(&self, part_id: &str, revision_id: &str, body: &str, if_match: Option<&str>) -> Result<(u64, Option<String>), Error> {
617 self.write_document_inner(part_id, revision_id, body, None, if_match)
618 }
619
620 pub fn write_document_if(&self, part_id: &str, revision_id: &str, body: &str, expected: &str) -> Result<u64, Error> {
627 self.write_document_inner(part_id, revision_id, body, None, Some(expected)).map(|(seq, _)| seq)
628 }
629
630 pub fn write_import_document(&self, user: &User, part_id: &str, revision_id: &str, expected_hash: &str, body: &str, uses: &Value) -> Result<u64, Error> {
634 self.write_document_inner(part_id, revision_id, body, Some((user, expected_hash, uses)), None).map(|(seq, _)| seq)
635 }
636
637 fn write_document_inner(&self, part_id: &str, revision_id: &str, body: &str, import: Option<(&User, &str, &Value)>, if_match: Option<&str>) -> Result<(u64, Option<String>), Error> {
638 let key = crate::identity::document_key(part_id, revision_id);
639 let path = self.document_path(&key)?;
640 let hash = auth::content_hash(body);
641 let embedded = crate::thumbnail::embedded(self.root(), body)?;
642 let has_geometry = crate::geometry::contains_geometry(body);
643 self.mutate(move |state| {
644 let imported_uses = if let Some((user, expected, uses)) = import {
645 check_writable(state, user, part_id, revision_id)?;
646 let revision = state.part(part_id).and_then(|p| p.revision(revision_id))
647 .ok_or_else(|| Error::not_found("revision"))?;
648 if revision.content_hash != expected {
649 return Err(Error::conflict("the document changed since the import was reviewed; review it again"));
650 }
651 Some(bom::check_uses(state, part_id, uses)?)
652 } else { None };
653 if let Some(expected) = if_match {
654 let part = state.part(part_id).ok_or_else(|| Error::not_found("part"))?;
655 let revision = part.revision(revision_id).ok_or_else(|| Error::not_found("revision"))?;
656 if revision.content_hash != expected {
657 let holder = revision
658 .lock
659 .as_ref()
660 .and_then(|lock| state.user(&lock.user_id))
661 .map_or_else(String::new, |user| format!(", checked out by {}", user.username));
662 return Err(Error::conflict(format!(
663 "{} rev {} was saved again on the PLM (at {:02}:{:02} UTC{holder}) after the document this save was based on: not overwritten",
664 part.number,
665 revision.label,
666 revision.modified_at % 86_400 / 3_600,
667 revision.modified_at % 3_600 / 60,
668 )));
669 }
670 }
671 let mut uses_refused = None;
676 let instructions = state.part(part_id).is_some_and(|p| p.document_class == DocumentClass::Instructions);
680 let instructs = if instructions { serde_json::from_str::<Value>(body).ok().and_then(|d| instructs_of(state, &d)) } else { None };
681 let derived_uses = if imported_uses.is_some() || instructions {
682 None
683 } else {
684 match serde_json::from_str::<Value>(body).ok().as_ref().and_then(crate::bom_config::document_uses) {
685 None => None,
686 Some(Err(why)) => {
687 uses_refused = Some(why);
688 None
689 }
690 Some(Ok(list)) => match bom::check_uses(state, part_id, &list) {
691 Ok(uses) => Some(uses),
692 Err(error) => {
693 uses_refused = Some(format!("the uses list was not published: {}", error.message));
694 None
695 }
696 },
697 }
698 };
699 let current = state.part(part_id).ok_or_else(|| Error::not_found("part"))?;
700 let defs = state.bom_configuration.part_fields.get(¤t.part_type).cloned().unwrap_or_default();
701 let mut canonical = current.revision(revision_id).ok_or_else(|| Error::not_found("revision"))?.clone();
702 if let Some(document) = serde_json::from_str::<Value>(body).ok().filter(|_| !instructions) {
703 if let Some(occurrences) = crate::bom_config::document_occurrences(&document) {
704 if let Some(occurrences) = crate::bom_config::capture_occurrences(state, part_id, revision_id, &json!({"occurrences":occurrences}))? {
705 canonical.occurrences = occurrences;
706 }
707 }
708 }
709 let normalized = if !defs.is_empty() || !canonical.occurrences.is_empty() {
710 let mut document: Value = serde_json::from_str(body).map_err(|_| Error::bad_request("A CAD document must be JSON"))?;
711 let original = document.clone();
712 if !canonical.attributes_initialized && !defs.is_empty() {
713 for def in &defs {
714 if let Some(value) = document["partAttributes"].as_object().and_then(|attrs|attrs.iter().find(|(key,_)|key.to_ascii_lowercase()==def.key).map(|(_,value)|value)) {
715 if let Some(value) = catalog::check_value(def, value).map_err(Error::bad_request)? {
716 canonical.attributes.insert(def.key.clone(), value);
717 }
718 }
719 }
720 canonical.attributes_initialized = true;
721 }
722 crate::bom_config::overlay(&canonical, &defs, &mut document);
723 if document != original {Some(serde_json::to_string(&document).map_err(Error::internal)?)} else {None}
724 } else { None };
725 let body = normalized.as_deref().unwrap_or(body);
726 let hash = if normalized.is_some() { auth::content_hash(body) } else { hash };
727 let size = body.len() as u64;
728 let part = state.parts.get_mut(&part_id)
729 .ok_or_else(|| Error::not_found("part"))?;
730 let number = part.number.clone();
731 let revision = part
732 .revision_mut(revision_id)
733 .ok_or_else(|| Error::not_found("revision"))?;
734 if !revision.lifecycle.is_editable() {
735 return Err(Error::conflict(format!(
736 "{number} revision {} is {} and cannot be written — start a new revision",
737 revision.label,
738 revision.lifecycle.as_str()
739 )));
740 }
741 if let Some(parent) = path.parent() {
742 fs::create_dir_all(parent).map_err(Error::internal)?;
743 }
744 let old_thumbnail = revision.thumbnail.as_ref().map(|t| t.sha256.clone());
745 let thumbnail = embedded.as_ref().map(|image| {
746 let user = import.map(|(user, _, _)| user.id.as_str())
747 .or_else(|| revision.lock.as_ref().map(|lock| lock.user_id.as_str()))
748 .unwrap_or(&revision.created_by);
749 image.place(self.root(), &hash, user)
750 }).transpose()?;
751 revision.attributes = canonical.attributes;
752 revision.attributes_initialized = canonical.attributes_initialized;
753 revision.occurrences = canonical.occurrences;
754 write_atomic(&path, body).map_err(Error::internal)?;
755 if let Some(thumbnail) = thumbnail { revision.thumbnail = Some(thumbnail); }
756 if let Some(uses) = imported_uses.or(derived_uses) {
757 revision.uses = uses;
758 crate::bom_config::synchronize_uses(revision);
759 }
760 if instructions {
761 revision.instructs = instructs;
762 }
763 revision.has_geometry = has_geometry;
764 revision.geometry_content_hash = hash.clone();
765 revision.content_hash = hash;
766 revision.size = size;
767 revision.modified_at = now();
768 if revision.needs_bake() {
772 if let Some(bake) = revision.bake.as_mut() {
773 bake.status = crate::model::BakeStatus::Done;
774 bake.error = "superseded by a saved document".into();
775 bake.finished_by = None;
776 bake.finished_at = Some(now());
777 }
778 }
779 crate::review::document_changed(state, part_id, revision_id);
781 state.touch(key);
782 if embedded.is_some() {
783 if let Some(old) = old_thumbnail { crate::attach::remove_if_unreferenced(state, self.root(), &old)?; }
784 }
785 Ok((state.seq, uses_refused))
786 })
787 }
788
789 pub fn remove_document(&self, key: &str) -> Result<(), Error> {
792 let path = self.document_path(key)?;
793 match fs::remove_file(path) {
794 Ok(()) => Ok(()),
795 Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()),
796 Err(error) => Err(Error::internal(error)),
797 }
798 }
799}
800
801pub const SQLITE_FILE: &str = "plm.sqlite";
803
804pub fn session_expired(settings: &Settings, session: &Session, now: Timestamp) -> bool {
809 let idle = now.saturating_sub(session.last_seen) > settings.session_idle_minutes.saturating_mul(60);
810 let old = settings.session_max_hours > 0
811 && now.saturating_sub(session.created_at) > settings.session_max_hours.saturating_mul(3600);
812 idle || old
813}
814
815impl Db {
816 pub fn prune_sessions(&self) -> Result<usize, Error> {
830 let at = now();
831 let expired = self.read(|state| state.sessions.iter().filter(|s| session_expired(&state.settings, s, at)).count());
832 if expired == 0 {
833 return Ok(0);
834 }
835 audit::as_actor(crate::model::Actor::system(), || {
836 self.mutate(move |state| {
837 let settings = state.settings.clone();
838 let before = state.sessions.len();
839 state.sessions.retain(|s| !session_expired(&settings, s, at));
840 Ok(before - state.sessions.len())
841 })
842 })
843 }
844}
845
846#[allow(clippy::type_complexity)]
850fn journal_rows<'a, T>(
851 list: &'a crate::journal::Journaled<T>,
852 touched: &'a [crate::journal::Touched<T>],
853) -> Result<(Vec<Value>, Vec<Value>, Vec<(String, Option<&'a T>)>), Error>
854where
855 T: crate::journal::Keyed + Clone + PartialEq + Serialize,
856{
857 let mut old = Vec::new();
858 let mut new = Vec::new();
859 let mut rows = Vec::new();
860 for (t, now) in list.changed(touched) {
861 old.extend(t.before.as_ref().map(serde_json::to_value).transpose().map_err(Error::internal)?);
862 new.extend(now.map(serde_json::to_value).transpose().map_err(Error::internal)?);
863 rows.push((t.key.clone(), now));
864 }
865 Ok((old, new, rows))
866}
867
868fn restore_small(state: &mut State, before: &Value) -> Result<(), Error> {
869 let parts = std::mem::take(&mut state.parts);
870 let workspace = std::mem::take(&mut state.workspace);
871 let sessions = std::mem::take(&mut state.sessions);
872 let jobs = std::mem::take(&mut state.jobs);
873 *state = serde_json::from_value(before.clone()).map_err(Error::internal)?;
874 state.parts = parts;
875 state.workspace = workspace;
876 state.sessions = sessions;
877 state.jobs = jobs;
878 Ok(())
879}
880
881pub(crate) fn write_atomic(path: &Path, body: impl AsRef<[u8]>) -> io::Result<()> {
888 use std::io::Write;
889 use std::sync::atomic::{AtomicU64, Ordering};
890 static NEXT: AtomicU64 = AtomicU64::new(0);
891 let name = path.file_name().ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "no file name"))?;
892 let mut temp_name = name.to_os_string();
893 temp_name.push(format!(".{}-{}.tmp", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
894 let temp = path.with_file_name(temp_name);
895 let written = (|| {
896 let mut file = fs::OpenOptions::new().write(true).create_new(true).open(&temp)?;
897 file.write_all(body.as_ref())?;
898 file.sync_all()?;
899 drop(file);
900 fs::rename(&temp, path)
901 })();
902 if written.is_err() {
903 let _ = fs::remove_file(&temp);
904 }
905 written
906}
907
908impl Db {
913 pub fn create_part(
916 &self,
917 author: &User,
918 part_type_id: &str,
919 name: &str,
920 description: &str,
921 category: &str,
922 ) -> Result<Part, Error> {
923 self.create_part_with(
924 author,
925 &PartSpec {
926 part_type: part_type_id.to_string(),
927 name: name.to_string(),
928 description: description.to_string(),
929 category: category.to_string(),
930 ..PartSpec::default()
931 },
932 )
933 }
934
935 pub fn instructions_part_type(&self) -> Result<String, Error> {
947 const ID: &str = "instructions";
948 if self.read(|state| state.part_type(ID).is_some()) {
949 return Ok(ID.into());
950 }
951 self.mutate(|state| {
952 if state.part_type(ID).is_none() {
953 if let Some(clash) = state.part_types.iter().find(|t| t.mode == NumberMode::Counter && t.prefix.eq_ignore_ascii_case("MI")) {
954 return Err(Error::conflict(format!(
955 "part type '{}' already numbers with MI: create a part type for instructions and name it",
956 clash.id
957 )));
958 }
959 state.part_types.push(PartType {
960 id: ID.into(),
961 name: "Instructions".into(),
962 prefix: "MI".into(),
963 digits: 9,
964 next: 1,
965 created_at: now(),
966 mode: NumberMode::Counter,
967 });
968 }
969 Ok(ID.into())
970 })
971 }
972
973 pub fn create_part_with(&self, author: &User, spec: &PartSpec) -> Result<Part, Error> {
974 check_origin(spec.origin)?;
975 let external_ref = spec.external_ref.trim().to_string();
976 let origin = spec.origin;
977 let name = spec.name.trim().to_string();
978 if name.is_empty() {
979 return Err(Error::bad_request("a part needs a name"));
980 }
981 let kind = self
982 .read(|state| state.part_type(&spec.part_type).cloned())
983 .ok_or_else(|| Error::bad_request(format!("no part type '{}'", spec.part_type)))?;
984 let typed = spec.number.trim().to_string();
985 let tags = catalog::tidy_tags(spec.tags.iter().cloned());
986 let part_view = json!({
987 "name": name,
988 "description": spec.description.trim(),
989 "category": spec.category.trim(),
990 "tags": tags,
991 "attributes": spec.attributes,
992 "document_class": spec.document_class,
993 });
994
995 let given: Option<String> = match &kind.mode {
996 NumberMode::Counter => {
997 if !typed.is_empty() {
998 return Err(Error::bad_request(format!(
999 "part type '{}' numbers by its counter — leave the number empty",
1000 kind.id
1001 )));
1002 }
1003 None
1004 }
1005 NumberMode::Free => {
1006 if typed.is_empty() {
1007 return Err(Error::bad_request(format!(
1008 "part type '{}' takes the number you type — enter one",
1009 kind.id
1010 )));
1011 }
1012 Some(typed)
1013 }
1014 NumberMode::Pattern { regex } => {
1015 let pattern = full_match(regex)?;
1016 if typed.is_empty() {
1017 return Err(Error::bad_request(format!(
1018 "part type '{}' takes a typed number matching {regex} — enter one",
1019 kind.id
1020 )));
1021 }
1022 if !pattern.is_match(&typed) {
1023 return Err(Error::bad_request(format!(
1024 "'{typed}' does not match part type '{}' ({regex})",
1025 kind.id
1026 )));
1027 }
1028 Some(typed)
1029 }
1030 NumberMode::Script { script } => {
1031 let input = json!({
1032 "requested": typed,
1033 "partType": kind,
1034 "part": part_view,
1035 "user": scripting::user_json(author),
1036 });
1037 let answer = match scripting::run(self, author, script, "partNumber", &input)? {
1038 HookResult::Absent => {
1039 return Err(Error::conflict(format!(
1040 "part type '{}' numbers by the script '{script}', which is not in the scripts directory",
1041 kind.id
1042 )))
1043 }
1044 HookResult::Refused(failure) => {
1045 return Err(Error::conflict(format!("{script}: {}", failure.message)))
1046 }
1047 HookResult::Returned(success) => success.value,
1048 };
1049 let number = scripting::string_answer(&answer, "number").ok_or_else(|| {
1050 Error::conflict(format!(
1051 "{script}: partNumber() must return the number, or {{ number }} — it returned {answer}"
1052 ))
1053 })?;
1054 if spec.exact && !number.eq_ignore_ascii_case(&typed) {
1055 return Err(Error::conflict(format!(
1056 "{script} would number it {number}, not {typed} — a family row names its own number"
1057 )));
1058 }
1059 Some(number)
1060 }
1061 };
1062 if let Some(number) = &given {
1063 check_number(number)?;
1064 }
1065
1066 let requested_label = spec.label.trim().to_string();
1067 let label = self.decide_label(author, None, &part_view, &requested_label, "A")?;
1068 if spec.exact {
1069 exact_label(&requested_label, &label)?;
1070 }
1071
1072 let author_id = author.id.clone();
1073 let document_class = spec.document_class;
1074 let description = spec.description.trim().to_string();
1075 let requested_category = spec.category.trim().to_string();
1076 if spec.attributes.keys().any(|key| key.trim().eq_ignore_ascii_case("has_geometry")) {
1077 return Err(Error::bad_request("has_geometry is derived from the saved model and cannot be edited"));
1078 }
1079 if spec.attributes.keys().any(|key| key.trim().eq_ignore_ascii_case("has_thumbnail")) {
1080 return Err(Error::bad_request("has_thumbnail is derived from current thumbnails and cannot be edited"));
1081 }
1082 let requested_values = spec.attributes.clone();
1083 let workspace = spec.workspace.clone();
1084 self.mutate(move |state| {
1085 let category = known_category(&state.categories, &requested_category)?;
1088 let mut attributes = BTreeMap::new();
1089 catalog::apply_values(&state.categories, &category, &mut attributes, &requested_values)?;
1090 let current = state
1091 .part_types
1092 .iter_mut()
1093 .find(|t| t.id == kind.id)
1094 .ok_or_else(|| Error::bad_request(format!("no part type '{}'", kind.id)))?;
1095 if current.mode != kind.mode {
1096 return Err(Error::conflict(format!(
1097 "part type '{}' changed its numbering while this part was being created — try again",
1098 kind.id
1099 )));
1100 }
1101 let (number, sequence) = match given {
1102 Some(number) => (number, 0),
1103 None => {
1104 let mut sequence = current.next;
1107 let mut number = current.format_number(sequence);
1108 while sequence <= current.capacity()
1109 && state_has_number(&state.parts, &number)
1110 {
1111 sequence += 1;
1112 number = current.format_number(sequence);
1113 }
1114 if sequence > current.capacity() {
1115 return Err(Error::conflict(format!(
1116 "part type '{}' is exhausted: {} digits cannot spell {}",
1117 current.id, current.digits, sequence
1118 )));
1119 }
1120 current.next = sequence + 1;
1121 (number, sequence)
1122 }
1123 };
1124 if let Some(owner) = state.part_with_number(&number) {
1125 return Err(Error::conflict(format!(
1126 "part number {number} already exists ({})",
1127 owner.name
1128 )));
1129 }
1130
1131 external_ref_clash(state, &kind.id, &external_ref, "")?;
1132 let stamp = now();
1133 let mut revision = Revision::draft(label.clone(), label, author_id.clone(), stamp);
1134 revision.origin = origin;
1135 let part = Part {
1136 id: number.clone(),
1137 number,
1138 part_type: kind.id.clone(),
1139 sequence,
1140 document_class,
1141 name,
1142 description,
1143 category,
1144 tags,
1145 external_ref,
1146 attributes,
1147 sourcing: Vec::new(),
1148 member_part_type: String::new(),
1149 attachments: Vec::new(),
1150 created_by: author_id,
1151 created_at: stamp,
1152 revisions: vec![revision],
1153 };
1154 state.parts.push(part.clone());
1155 state.touch(part.revisions[0].document_key(&part.id));
1156 if let Some(folder) = &workspace {
1157 crate::workspace::link_new_part(state, &part.created_by, folder, &part)?;
1158 }
1159 Ok(part)
1160 })
1161 }
1162
1163 fn decide_label(
1166 &self,
1167 user: &User,
1168 part: Option<&Part>,
1169 part_view: &Value,
1170 requested: &str,
1171 suggested: &str,
1172 ) -> Result<String, Error> {
1173 let existing: Vec<&str> = part
1174 .map(|p| p.revisions.iter().map(|r| r.label.as_str()).collect())
1175 .unwrap_or_default();
1176 let input = json!({
1177 "requested": requested,
1178 "suggested": suggested,
1179 "existing": existing,
1180 "part": part.map(|p| serde_json::to_value(p).unwrap_or(Value::Null)).unwrap_or_else(|| part_view.clone()),
1181 "user": scripting::user_json(user),
1182 });
1183 let label = match scripting::run(self, user, scripting::REVISION_LABEL, "revisionLabel", &input)? {
1184 HookResult::Absent => {
1185 if requested.is_empty() { suggested.to_string() } else { requested.to_string() }
1186 }
1187 HookResult::Refused(failure) => {
1188 return Err(Error::conflict(format!("{}: {}", scripting::REVISION_LABEL, failure.message)))
1189 }
1190 HookResult::Returned(success) => match &success.value {
1191 Value::Null => {
1193 if requested.is_empty() { suggested.to_string() } else { requested.to_string() }
1194 }
1195 other => scripting::string_answer(other, "label").ok_or_else(|| {
1196 Error::conflict(format!(
1197 "{}: revisionLabel() must return the label, or {{ label }} — it returned {other}",
1198 scripting::REVISION_LABEL
1199 ))
1200 })?,
1201 },
1202 };
1203 check_label(&label)?;
1204 Ok(label)
1205 }
1206
1207 pub fn create_revision(&self, author: &User, part_id: &str) -> Result<Revision, Error> {
1209 self.create_revision_labelled(author, part_id, "")
1210 }
1211
1212 pub fn create_revision_labelled(
1225 &self,
1226 author: &User,
1227 part_id: &str,
1228 label: &str,
1229 ) -> Result<Revision, Error> {
1230 self.create_revision_as(author, part_id, label, false, crate::model::Origin::Authored)
1231 }
1232
1233 pub fn create_revision_from(
1237 &self,
1238 author: &User,
1239 part_id: &str,
1240 label: &str,
1241 origin: crate::model::Origin,
1242 ) -> Result<Revision, Error> {
1243 check_origin(origin)?;
1244 self.create_revision_as(author, part_id, label, false, origin)
1245 }
1246
1247 pub(crate) fn create_revision_as(
1251 &self,
1252 author: &User,
1253 part_id: &str,
1254 label: &str,
1255 exact: bool,
1256 origin: crate::model::Origin,
1257 ) -> Result<Revision, Error> {
1258 let part = self
1259 .read(|state| state.part(part_id).cloned())
1260 .ok_or_else(|| Error::not_found("part"))?;
1261 let single = !self.read(|state| state.settings.allow_multiple_open_drafts);
1262 if let Some(open) = part.open_draft().filter(|_| single) {
1263 return Err(one_draft_refusal(open, &part));
1264 }
1265 let suggested = suggest_label(&part);
1266 let requested = label.trim();
1267 let label = self.decide_label(author, Some(&part), &Value::Null, requested, &suggested)?;
1268 if exact {
1269 exact_label(requested, &label)?;
1270 }
1271
1272 let carried_revision = part.current_release().or(part.latest()).map(|r| r.id.clone());
1273 let carried = part.current_release().or(part.latest()).map(|r| r.document_key(part_id));
1274 let carried_body = match carried {
1275 Some(key) => self.read_document(&key)?,
1276 None => None,
1277 };
1278 let carried_hash = carried_body.as_deref().map(auth::content_hash);
1279
1280 let author_id = author.id.clone();
1281 let revision = self.mutate(move |state| {
1282 if !state.settings.allow_multiple_open_drafts {
1285 let part = state.part(part_id).ok_or_else(|| Error::not_found("part"))?;
1286 if let Some(open) = part.open_draft() {
1287 return Err(one_draft_refusal(open, part));
1288 }
1289 }
1290 let part = state.parts.get_mut(&part_id)
1291 .ok_or_else(|| Error::not_found("part"))?;
1292 if let Some(clash) = part.revision_by_label(&label) {
1293 return Err(Error::conflict(format!(
1294 "{} already has a revision labelled {}",
1295 part.number, clash.label
1296 )));
1297 }
1298 let stamp = now();
1299 let mut revision = Revision::draft(label.clone(), label, author_id, stamp);
1300 revision.origin = origin;
1301 if let Some(previous) = carried_revision.as_deref().and_then(|id| part.revision(id)) {
1302 revision.has_geometry = previous.has_geometry;
1303 revision.attributes = previous.attributes.clone();
1304 revision.attributes_initialized = previous.attributes_initialized;
1305 revision.occurrences = previous.occurrences.clone();
1306 }
1307 revision.uses = carried_revision
1309 .as_deref()
1310 .and_then(|id| part.revision(id))
1311 .map(|r| r.uses.clone())
1312 .unwrap_or_default();
1313 revision.instructs = carried_revision.as_deref().and_then(|id| part.revision(id)).and_then(|r| r.instructs.clone());
1315 revision.attachments = carried_revision
1318 .as_deref()
1319 .and_then(|id| part.revision(id))
1320 .map(|r| {
1321 r.attachments
1322 .iter()
1323 .map(|a| crate::model::Attachment { id: auth::new_id(), ..a.clone() })
1324 .collect()
1325 })
1326 .unwrap_or_default();
1327 revision.thumbnail = carried_revision
1330 .as_deref()
1331 .and_then(|id| part.revision(id))
1332 .and_then(|r| r.thumbnail.clone())
1333 .filter(|t| carried_hash.as_deref() == Some(t.content_hash.as_str()));
1334 part.revisions.push(revision.clone());
1335 state.touch(revision.document_key(part_id));
1336 Ok(revision)
1337 })?;
1338
1339 if let Some(body) = carried_body {
1340 self.write_document(part_id, &revision.id, &body)?;
1341 }
1342 Ok(revision)
1343 }
1344
1345 pub fn update_part(&self, key: &str, fields: &Value) -> Result<Part, Error> {
1357 let Some(fields) = fields.as_object() else {
1358 return Err(Error::bad_request("the fields to change must be an object"));
1359 };
1360 for name in fields.keys() {
1361 if !matches!(
1362 name.as_str(),
1363 "name" | "description" | "category" | "tags" | "external_ref" | "attributes" | "member_part_type"
1364 ) {
1365 return Err(Error::bad_request(format!(
1366 "'{name}' cannot be changed — only name, description, category, tags, attributes, external_ref and member_part_type"
1367 )));
1368 }
1369 }
1370 let fields = fields.clone();
1371 let key = key.to_string();
1372 self.mutate(move |state| {
1373 let id = state
1374 .part_by_id_or_number(&key)
1375 .map(|p| p.id.clone())
1376 .ok_or_else(|| Error::not_found("part"))?;
1377 if let Some(value) = fields.get("external_ref") {
1378 let reference = value.as_str().map(str::trim).unwrap_or_default();
1379 let kind = state.part(&id).map(|p| p.part_type.clone()).unwrap_or_default();
1380 external_ref_clash(state, &kind, reference, &id)?;
1381 }
1382 let State { parts, categories, settings, part_types, .. } = &mut *state;
1385 let part = parts.get_mut(&id).expect("found above");
1386 if let Some(value) = fields.get("member_part_type") {
1387 let requested = value.as_str().map(str::trim).unwrap_or_default();
1388 if part.document_class == DocumentClass::Normal && !requested.is_empty() {
1389 return Err(Error::bad_request(
1390 "only a family or a template has a member part type",
1391 ));
1392 }
1393 if !requested.is_empty() && !part_types.iter().any(|t| t.id == requested) {
1394 return Err(Error::bad_request(format!("no part type '{requested}'")));
1395 }
1396 part.member_part_type = requested.to_string();
1397 }
1398 let before = (part.category.clone(), part.attributes.clone());
1399 let updated = apply_part_fields(categories, part, &fields)?;
1400
1401 if settings.lock_released_attributes
1405 && part.catalog_frozen()
1406 && before != (updated.category.clone(), updated.attributes.clone())
1407 {
1408 return Err(Error::conflict(format!(
1409 "{} is released and its category and attributes are locked — start a new revision to change them",
1410 part.number
1411 )));
1412 }
1413 Ok(updated)
1414 })
1415 }
1416}
1417
1418fn exact_label(requested: &str, decided: &str) -> Result<(), Error> {
1422 if !requested.is_empty() && !decided.eq_ignore_ascii_case(requested) {
1423 return Err(Error::conflict(format!(
1424 "{} would label it {decided}, not {requested} — a family row names its own revision",
1425 scripting::REVISION_LABEL
1426 )));
1427 }
1428 Ok(())
1429}
1430
1431fn bake_gate(revision: &Revision) -> Result<(), Error> {
1434 match &revision.bake {
1435 Some(bake) if revision.needs_bake() => Err(Error::conflict(format!(
1436 "revision {} is waiting for a bake ({}{}) — it releases once a CAD worker has baked it, or once someone saves it from the CAD app",
1437 revision.label,
1438 bake.status.as_str(),
1439 if bake.error.is_empty() { String::new() } else { format!(": {}", bake.error) }
1440 ))),
1441 _ => Ok(()),
1442 }
1443}
1444
1445fn one_draft_refusal(open: &Revision, part: &Part) -> Error {
1447 Error::conflict(format!(
1448 "revision {} of {} is still open — release or delete it first (this server allows one revision in work at a time)",
1449 open.label, part.number
1450 ))
1451}
1452
1453impl Db {
1454 pub fn settings(&self) -> Settings {
1456 self.read(|state| state.settings.clone())
1457 }
1458
1459 pub fn update_settings(&self, fields: &Value) -> Result<Settings, Error> {
1464 let Some(fields) = fields.as_object() else {
1465 return Err(Error::bad_request("the settings to change must be an object"));
1466 };
1467 let mut merged = serde_json::to_value(self.settings()).map_err(Error::internal)?;
1468 for (key, value) in fields {
1469 let slot = merged
1470 .get_mut(key)
1471 .ok_or_else(|| Error::bad_request(format!("there is no setting '{key}'")))?;
1472 if slot.is_boolean() && !value.is_boolean() {
1473 return Err(Error::bad_request(format!("'{key}' must be true or false")));
1474 }
1475 if slot.is_u64() {
1476 let minimum = if key == "session_idle_minutes" { 5 } else { 0 };
1477 match value.as_u64() {
1478 Some(n) if n >= minimum => {}
1479 _ => {
1480 return Err(Error::bad_request(format!(
1481 "'{key}' must be a whole number of at least {minimum}"
1482 )))
1483 }
1484 }
1485 }
1486 *slot = value.clone();
1487 }
1488 self.read(|state| crate::review::normalize_settings_json(state, &mut merged))?;
1489 let settings: Settings = serde_json::from_value(merged)
1490 .map_err(|e| Error::bad_request(format!("those settings do not read: {e}")))?;
1491 self.mutate(move |state| {
1492 let mut settings = settings;
1495 crate::review::check_settings(state, &mut settings)?;
1496 crate::lifecycle::check_options(&settings.status_options)?;
1497 state.settings = settings.clone();
1498 Ok(settings)
1499 })
1500 }
1501}
1502
1503fn apply_part_fields(
1506 categories: &[Category],
1507 part: &mut Part,
1508 fields: &serde_json::Map<String, Value>,
1509) -> Result<Part, Error> {
1510 let text = |value: &Value| value.as_str().map(|s| s.trim().to_string());
1511 if let Some(value) = fields.get("name") {
1512 let name = text(value)
1513 .filter(|n| !n.is_empty())
1514 .ok_or_else(|| Error::bad_request("a part needs a name"))?;
1515 part.name = name;
1516 }
1517 if let Some(value) = fields.get("description") {
1518 part.description = text(value).unwrap_or_default();
1519 }
1520 if let Some(value) = fields.get("category") {
1521 let requested = text(value).unwrap_or_default();
1522 part.category = known_category(categories, &requested)?;
1523 }
1524 if let Some(value) = fields.get("external_ref") {
1525 part.external_ref = text(value).unwrap_or_default();
1526 }
1527 if let Some(value) = fields.get("tags") {
1528 part.tags = catalog::tidy_tags(
1529 value
1530 .as_array()
1531 .ok_or_else(|| Error::bad_request("tags must be a list of strings"))?
1532 .iter()
1533 .filter_map(|t| t.as_str().map(str::to_string)),
1534 );
1535 }
1536 if let Some(value) = fields.get("attributes") {
1539 let changes = value
1540 .as_object()
1541 .ok_or_else(|| Error::bad_request("attributes must be an object of key: value"))?;
1542 if changes.keys().any(|key| key.trim().eq_ignore_ascii_case("has_geometry")) {
1543 return Err(Error::bad_request("has_geometry is derived from the saved model and cannot be edited"));
1544 }
1545 if changes.keys().any(|key| key.trim().eq_ignore_ascii_case("has_thumbnail")) {
1546 return Err(Error::bad_request("has_thumbnail is derived from current thumbnails and cannot be edited"));
1547 }
1548 catalog::apply_values(categories, &part.category, &mut part.attributes, changes)?;
1549 }
1550 Ok(part.clone())
1551}
1552
1553fn known_category(categories: &[Category], requested: &str) -> Result<String, Error> {
1558 let requested = requested.trim();
1559 if requested.is_empty() {
1560 return Ok(String::new());
1561 }
1562 catalog::find(categories, requested)
1563 .map(|c| c.id.clone())
1564 .ok_or_else(|| Error::bad_request(format!("there is no category '{requested}'")))
1565}
1566
1567#[derive(Debug, Clone, Default)]
1570pub struct PartFilter {
1571 pub q: String,
1574 pub category: String,
1577 pub tag: String,
1579 pub manufacturer: String,
1582 pub supplier: String,
1584 pub attributes: Vec<AttributeFilter>,
1587 pub external_ref: String,
1589 pub part_type: String,
1591}
1592
1593#[derive(Debug, Clone, Default, PartialEq)]
1597pub struct AttributeFilter {
1598 pub key: String,
1599 pub values: Vec<String>,
1601 pub min: Option<String>,
1603 pub max: Option<String>,
1604}
1605
1606impl AttributeFilter {
1607 pub fn from_query(pairs: &[(String, String)]) -> Result<Vec<AttributeFilter>, Error> {
1611 let mut out: Vec<AttributeFilter> = Vec::new();
1612 for (name, value) in pairs {
1613 let Some(rest) = name.strip_prefix("attr.") else { continue };
1614 let (key, bound) = match rest.rsplit_once('.') {
1615 Some((key, "min")) => (key, Some(true)),
1616 Some((key, "max")) => (key, Some(false)),
1617 Some((_, other)) if !rest.is_empty() => {
1618 return Err(Error::bad_request(format!(
1621 "'{name}': an attribute filter is attr.<key>, attr.<key>.min or attr.<key>.max, not .{other}"
1622 )));
1623 }
1624 _ => (rest, None),
1625 };
1626 let key = key.trim();
1627 if key.is_empty() {
1628 return Err(Error::bad_request(format!("'{name}' names no attribute")));
1629 }
1630 let at = match out.iter().position(|f| f.key == key) {
1631 Some(i) => i,
1632 None => {
1633 out.push(AttributeFilter { key: key.to_string(), ..AttributeFilter::default() });
1634 out.len() - 1
1635 }
1636 };
1637 let filter = &mut out[at];
1638 match bound {
1639 None => filter.values.push(value.clone()),
1640 Some(true) => filter.min = Some(value.clone()),
1641 Some(false) => filter.max = Some(value.clone()),
1642 }
1643 }
1644 Ok(out)
1645 }
1646}
1647
1648#[derive(Debug, Clone)]
1651pub struct AttributeMatcher {
1652 key: String,
1653 any_of: Vec<Value>,
1654 min: Option<f64>,
1655 max: Option<f64>,
1656}
1657
1658impl AttributeMatcher {
1659 fn matches(&self, part: &Part) -> bool {
1660 let geometry = Value::Bool(part.latest().is_some_and(|r| r.has_geometry));
1661 let thumbnail = Value::Bool(crate::thumbnail::of_part(part).is_some());
1662 let have = if self.key == "has_geometry" { &geometry } else if self.key == "has_thumbnail" { &thumbnail } else {
1663 let Some(value) = part.attributes.get(&self.key).filter(|v| !v.is_null()) else { return false };
1664 value
1665 };
1666 let number = have.as_f64();
1667 let equal = |want: &Value| match (want, have) {
1668 (Value::Number(w), Value::Number(h)) => w.as_f64() == h.as_f64(),
1669 (Value::String(w), Value::String(h)) => w.eq_ignore_ascii_case(h.trim()),
1670 (w, h) => w == h,
1671 };
1672 (self.any_of.is_empty() || self.any_of.iter().any(equal))
1673 && self.min.is_none_or(|min| number.is_some_and(|n| n >= min))
1674 && self.max.is_none_or(|max| number.is_some_and(|n| n <= max))
1675 }
1676}
1677
1678pub fn attribute_matchers(state: &State, filter: &PartFilter) -> Result<Vec<AttributeMatcher>, Error> {
1688 use crate::model::{AttributeDef, AttributeKind};
1689 let category = catalog::find(&state.categories, filter.category.trim()).map(|c| c.id.clone());
1690 let mut out = Vec::new();
1691 for condition in &filter.attributes {
1692 let key = condition.key.as_str();
1693 if matches!(key, "has_geometry" | "has_thumbnail") {
1694 if condition.min.is_some() || condition.max.is_some() {
1695 return Err(Error::bad_request(format!("{key} is a boolean and has no range")));
1696 }
1697 let any_of = condition.values.iter().map(|v| match v.as_str() {
1698 "true" => Ok(Value::Bool(true)), "false" => Ok(Value::Bool(false)),
1699 _ => Err(Error::bad_request(format!("attr.{key} must be true or false"))),
1700 }).collect::<Result<Vec<_>, _>>()?;
1701 out.push(AttributeMatcher { key: key.into(), any_of, min: None, max: None });
1702 continue;
1703 }
1704 let defs: Vec<(String, AttributeDef)> = match &category {
1705 Some(id) => catalog::schema(&state.categories, id)?
1706 .into_iter()
1707 .filter(|e| e.def.key == key)
1708 .map(|e| (id.clone(), e.def))
1709 .collect(),
1710 None => state
1711 .categories
1712 .iter()
1713 .flat_map(|c| c.attributes.iter().filter(|d| d.key == key).map(move |d| (c.id.clone(), d.clone())))
1714 .collect(),
1715 };
1716 let Some((first_category, def)) = defs.first().cloned() else {
1717 return Err(Error::bad_request(match &category {
1718 Some(id) => format!("the category '{id}' has no attribute '{key}'"),
1719 None => format!("no category has an attribute '{key}'"),
1720 }));
1721 };
1722 if let Some((other, clash)) = defs.iter().find(|(_, d)| d.kind.as_str() != def.kind.as_str()) {
1723 return Err(Error::bad_request(format!(
1724 "'{key}' is a {} in '{first_category}' but a {} in '{other}' — give a category to filter by it",
1725 def.kind.as_str(),
1726 clash.kind.as_str()
1727 )));
1728 }
1729 let mut any_of = Vec::new();
1730 for raw in &condition.values {
1731 let read = defs.iter().map(|(_, d)| catalog::check_value(d, &Value::String(raw.clone())));
1734 let mut first_error = None;
1735 let mut value = None;
1736 for result in read {
1737 match result {
1738 Ok(v) => {
1739 value = v;
1740 first_error = None;
1741 break;
1742 }
1743 Err(e) => {
1744 first_error.get_or_insert(e);
1745 }
1746 }
1747 }
1748 if let Some(error) = first_error {
1749 return Err(Error::bad_request(format!("attr.{key}: {error}")));
1750 }
1751 let Some(value) = value else {
1752 return Err(Error::bad_request(format!("attr.{key} is empty — leave it out to filter on nothing")));
1753 };
1754 any_of.push(value);
1755 }
1756 let bound = |raw: &Option<String>, which: &str| -> Result<Option<f64>, Error> {
1757 let Some(raw) = raw else { return Ok(None) };
1758 if !matches!(def.kind, AttributeKind::Number { .. }) {
1759 return Err(Error::bad_request(format!(
1760 "attr.{key}.{which}: '{key}' is a {}, and only a number has a range",
1761 def.kind.as_str()
1762 )));
1763 }
1764 raw.trim()
1765 .parse::<f64>()
1766 .ok()
1767 .filter(|n| n.is_finite())
1768 .map(Some)
1769 .ok_or_else(|| Error::bad_request(format!("attr.{key}.{which} must be a number, not '{raw}'")))
1770 };
1771 out.push(AttributeMatcher {
1772 key: key.to_string(),
1773 any_of,
1774 min: bound(&condition.min, "min")?,
1775 max: bound(&condition.max, "max")?,
1776 });
1777 }
1778 Ok(out)
1779}
1780
1781#[derive(Debug, Default)]
1783pub struct PartPage {
1784 pub parts: Vec<Part>,
1785 pub next: Option<String>,
1787 cursors: Vec<i64>,
1788}
1789
1790impl PartPage {
1791 fn finish(&mut self, limit: Option<usize>) {
1793 if let Some(limit) = limit {
1794 if self.parts.len() > limit {
1795 self.parts.truncate(limit);
1796 self.next = self.cursors.get(limit - 1).map(|c| c.to_string());
1797 }
1798 }
1799 self.cursors.clear();
1800 }
1801}
1802
1803struct Matcher {
1806 needle: String,
1807 tag: String,
1808 within: Option<BTreeSet<String>>,
1811 uncategorized: bool,
1812 manufacturer: Option<Option<String>>,
1815 supplier: Option<Option<String>>,
1816 external_ref: String,
1817 part_type: String,
1818 attributes: Option<Vec<AttributeMatcher>>,
1822}
1823
1824impl Matcher {
1825 fn new(state: &State, filter: &PartFilter) -> Self {
1826 let within = match filter.category.trim() {
1827 "" => None,
1828 UNCATEGORIZED => Some(BTreeSet::new()),
1829 id => Some(catalog::descendants(&state.categories, id)),
1830 };
1831 let company = |which: sourcing::Companies, key: &str| -> Option<Option<String>> {
1832 let key = key.trim();
1833 if key.is_empty() {
1834 return None;
1835 }
1836 Some(sourcing::find_company(which.list(state), key).map(|c| c.id.clone()))
1837 };
1838 Matcher {
1839 needle: filter.q.trim().to_ascii_lowercase(),
1840 tag: filter.tag.trim().to_string(),
1841 within,
1842 uncategorized: filter.category.trim() == UNCATEGORIZED,
1843 manufacturer: company(sourcing::Companies::Manufacturers, &filter.manufacturer),
1844 supplier: company(sourcing::Companies::Suppliers, &filter.supplier),
1845 attributes: attribute_matchers(state, filter).ok(),
1846 external_ref: filter.external_ref.trim().to_string(),
1847 part_type: filter.part_type.trim().to_string(),
1848 }
1849 }
1850
1851 fn impossible(&self) -> bool {
1854 matches!(self.manufacturer, Some(None)) || matches!(self.supplier, Some(None)) || self.attributes.is_none()
1855 }
1856
1857 fn matches(&self, categories: &[Category], part: &Part) -> bool {
1858 (match &self.within {
1859 None => true,
1860 Some(_) if self.uncategorized => part.category.is_empty(),
1861 Some(ids) => ids.contains(&part.category.to_ascii_lowercase()),
1862 }) && (self.tag.is_empty() || part.tags.iter().any(|t| t.eq_ignore_ascii_case(&self.tag)))
1863 && (match &self.manufacturer {
1864 None => true,
1865 Some(None) => false,
1866 Some(Some(id)) => part.sourcing.iter().any(|mp| &mp.manufacturer == id),
1867 })
1868 && (match &self.supplier {
1869 None => true,
1870 Some(None) => false,
1871 Some(Some(id)) => part.sourcing.iter().flat_map(|mp| &mp.offers).any(|o| &o.supplier == id),
1872 })
1873 && (self.external_ref.is_empty() || part.external_ref == self.external_ref)
1874 && (self.part_type.is_empty() || part.part_type == self.part_type)
1875 && self.attributes.as_ref().is_some_and(|all| all.iter().all(|a| a.matches(part)))
1876 && (self.needle.is_empty() || part_matches(categories, part, &self.needle))
1877 }
1878}
1879
1880pub const UNCATEGORIZED: &str = "_none";
1883
1884impl Db {
1885 pub fn search_parts(&self, query: &str) -> Vec<Part> {
1888 self.find_parts(&PartFilter { q: query.to_string(), ..PartFilter::default() })
1889 }
1890
1891 pub fn find_parts(&self, filter: &PartFilter) -> Vec<Part> {
1893 self.find_parts_page(filter, None, None).parts
1894 }
1895
1896 pub fn find_parts_page(&self, filter: &PartFilter, after: Option<&str>, limit: Option<usize>) -> PartPage {
1909 let matcher = self.read(|state| Matcher::new(state, filter));
1910 let after: Option<i64> = after.and_then(|a| a.trim().parse().ok());
1911 let limit = limit.map(|l| l.max(1));
1912 if matcher.impossible() {
1913 return PartPage::default();
1914 }
1915 if !matcher.external_ref.is_empty() {
1918 return self.scanned_page(&matcher, after, limit);
1919 }
1920 match self.indexed_page(&matcher, after, limit) {
1921 Ok(page) => page,
1922 Err(error) => {
1923 eprintln!("brep-plm: search index: {error}; answering from a scan");
1924 self.scanned_page(&matcher, after, limit)
1925 }
1926 }
1927 }
1928
1929 fn indexed_page(&self, matcher: &Matcher, mut after: Option<i64>, limit: Option<usize>) -> rusqlite::Result<PartPage> {
1930 let categories: Option<Vec<String>> = match (&matcher.within, matcher.uncategorized) {
1931 (Some(ids), false) => Some(ids.iter().cloned().collect()),
1932 _ => None,
1933 };
1934 let needle = (matcher.needle.chars().count() >= 3).then_some(matcher.needle.as_str());
1935 let mut page = PartPage::default();
1936 let wanted = limit.map(|l| l + 1);
1938 let batch = wanted.map(|w| w.max(256));
1939 loop {
1940 let rows = self.sql.candidates(&sql::Candidates {
1941 needle,
1942 categories: categories.as_deref(),
1943 uncategorized: matcher.uncategorized,
1944 tag: (!matcher.tag.is_empty()).then_some(matcher.tag.as_str()),
1945 manufacturer: matcher.manufacturer.as_ref().and_then(|m| m.as_deref()),
1946 supplier: matcher.supplier.as_ref().and_then(|s| s.as_deref()),
1947 after,
1948 limit: batch,
1949 })?;
1950 let exhausted = batch.is_none_or(|b| rows.len() < b);
1951 let full = self.read(|state| {
1952 for (ord, id) in &rows {
1953 after = Some(*ord);
1954 let Some(part) = state.parts.get(id) else { continue };
1955 if matcher.matches(&state.categories, part) {
1956 page.parts.push(part.clone());
1957 page.cursors.push(*ord);
1958 if wanted.is_some_and(|w| page.parts.len() >= w) {
1959 return true;
1960 }
1961 }
1962 }
1963 false
1964 });
1965 if full || exhausted {
1966 break;
1967 }
1968 }
1969 page.finish(limit);
1970 Ok(page)
1971 }
1972
1973 fn scanned_page(&self, matcher: &Matcher, after: Option<i64>, limit: Option<usize>) -> PartPage {
1974 let mut page = PartPage::default();
1975 self.read(|state| {
1976 for (ord, part) in state.parts.iter().enumerate() {
1977 let ord = ord as i64;
1978 if after.is_some_and(|a| ord <= a) || !matcher.matches(&state.categories, part) {
1979 continue;
1980 }
1981 page.parts.push(part.clone());
1982 page.cursors.push(ord);
1983 if limit.is_some_and(|l| page.parts.len() > l) {
1984 break;
1985 }
1986 }
1987 });
1988 page.finish(limit);
1989 page
1990 }
1991
1992 pub fn find_parts_scanning(&self, filter: &PartFilter) -> Vec<Part> {
1995 let matcher = self.read(|state| Matcher::new(state, filter));
1996 if matcher.impossible() {
1997 return Vec::new();
1998 }
1999 self.scanned_page(&matcher, None, None).parts
2000 }
2001
2002 pub fn checkout(
2004 &self,
2005 user: &User,
2006 part_id: &str,
2007 revision_id: &str,
2008 client_id: &str,
2009 ) -> Result<(), Error> {
2010 let user_id = user.id.clone();
2011 let client_id = client_id.to_string();
2012 self.mutate(move |state| {
2013 let (_, revision) = find_revision_mut(state, part_id, revision_id)?;
2014 if !revision.lifecycle.is_editable() {
2015 return Err(Error::conflict(format!(
2016 "revision {} is {} — only a draft can be checked out",
2017 revision.label,
2018 revision.lifecycle.as_str()
2019 )));
2020 }
2021 if let Some(lock) = &revision.lock {
2022 if lock.user_id != user_id {
2023 return Err(Error::conflict(
2024 "already checked out by another user".to_string(),
2025 ));
2026 }
2027 }
2030 revision.lock = Some(Lock {
2031 user_id,
2032 client_id,
2033 acquired_at: now(),
2034 });
2035 state.touch_part(part_id);
2036 Ok(())
2037 })
2038 }
2039
2040 pub fn checkin(
2043 &self,
2044 user: &User,
2045 part_id: &str,
2046 revision_id: &str,
2047 force: bool,
2048 ) -> Result<(), Error> {
2049 let user_id = user.id.clone();
2050 let may_break = user.can_checkin();
2051 self.mutate(move |state| {
2052 let (_, revision) = find_revision_mut(state, part_id, revision_id)?;
2053 let Some(lock) = revision.lock.clone() else {
2054 return Err(Error::conflict("nothing is checked out".to_string()));
2055 };
2056 if lock.user_id != user_id {
2057 if !force {
2058 return Err(Error::forbidden(
2059 "another user holds this lock — breaking it needs the check-in group",
2060 ));
2061 }
2062 if !may_break {
2063 return Err(Error::forbidden(
2064 "breaking another user's lock needs the check-in group",
2065 ));
2066 }
2067 }
2068 revision.lock = None;
2069 state.touch_part(part_id);
2070 Ok(())
2071 })
2072 }
2073
2074 pub fn transition(
2083 &self,
2084 user: &User,
2085 part_id: &str,
2086 revision_id: &str,
2087 to: Lifecycle,
2088 ) -> Result<Vec<String>, Error> {
2089 self.transition_checked(user, part_id, revision_id, to, None, None)
2090 }
2091
2092 pub fn transition_reviewed(&self, user: &User, part_id: &str, revision_id: &str, to: Lifecycle, expected_hash: &str) -> Result<Vec<String>, Error> {
2093 self.transition_checked(user, part_id, revision_id, to, Some(expected_hash), None)
2094 }
2095
2096 pub(crate) fn transition_workflow(&self, user: &User, part_id: &str, revision_id: &str, to: Lifecycle, expected_hash: &str, run_id: &str) -> Result<Vec<String>, Error> {
2097 self.transition_checked(user, part_id, revision_id, to, Some(expected_hash), Some(run_id))
2098 }
2099
2100 fn transition_checked(&self, user: &User, part_id: &str, revision_id: &str, to: Lifecycle, expected_hash: Option<&str>, workflow_run: Option<&str>) -> Result<Vec<String>, Error> {
2101 if let Some(expected) = expected_hash {
2102 let (_, revision) = self.snapshot(part_id, revision_id)?;
2103 if revision.content_hash != expected { return Err(Error::conflict("workflow model changed after review")); }
2104 }
2105 lifecycle::check_enabled(&self.settings(), to)?;
2106 if to == Lifecycle::Released { self.read(|s|crate::workflow::release_gate(s,part_id,revision_id,workflow_run))?; }
2107 if to == Lifecycle::Superseded {
2108 return Err(Error::bad_request(
2109 "superseded is applied automatically when a newer revision releases",
2110 ));
2111 }
2112 if to == Lifecycle::Released && !user.can_checkin() {
2113 return Err(Error::forbidden("releasing needs the check-in group"));
2114 }
2115 if to == Lifecycle::Obsolete && !user.can_checkin() {
2118 return Err(Error::forbidden("making a revision obsolete needs the check-in group"));
2119 }
2120 if matches!(to, Lifecycle::InReview | Lifecycle::Draft) && !user.can_author() {
2122 return Err(Error::forbidden("submitting for review, or withdrawing, needs the author group"));
2123 }
2124 if to == Lifecycle::InReview {
2126 return self.submit_for_review(user, part_id, revision_id, &crate::review::Submission::default());
2127 }
2128
2129 let mut seen_hash = None;
2133 if to == Lifecycle::Released {
2134 let (part, revision) = self.snapshot(part_id, revision_id)?;
2135 lifecycle::check_transition(revision.lifecycle, to).map_err(Error::conflict)?;
2136 self.read(|state| catalog_gate(&state.categories, &part))?;
2137 self.read(|state| children_gate(state, &part, &revision))?;
2138 self.read(|state| review_gate(state, &part, &revision))?;
2139 if revision.lock.is_some() {
2140 return Err(Error::conflict(format!(
2141 "revision {} is checked out — check it in before releasing",
2142 revision.label
2143 )));
2144 }
2145 bake_gate(&revision)?;
2146 let input = self.read(|state| release_input(state, &part, &revision, user));
2147 match scripting::run(self, user, scripting::BEFORE_RELEASE, "beforeRelease", &input)? {
2148 HookResult::Absent | HookResult::Returned(_) => {}
2149 HookResult::Refused(failure) => {
2150 return Err(Error::conflict(format!(
2151 "{} refused the release: {}",
2152 scripting::BEFORE_RELEASE,
2153 failure.message
2154 )))
2155 }
2156 }
2157 seen_hash = Some(revision.content_hash.clone());
2158 }
2159
2160 let users = if to == Lifecycle::Obsolete {
2163 self.read(|state| used_by_now(state, part_id, revision_id))
2164 } else {
2165 Vec::new()
2166 };
2167 let user_id = user.id.clone();
2168 let root = self.root().to_path_buf();
2169 self.mutate(move |state| {
2170 lifecycle::check_enabled(&state.settings, to)?;
2171 if to == Lifecycle::Released { crate::workflow::release_gate(state,part_id,revision_id,workflow_run)?; }
2172 if let Some(expected) = expected_hash {
2173 let revision = state.part(part_id).and_then(|p|p.revision(revision_id)).ok_or_else(||Error::not_found("revision"))?;
2174 if revision.content_hash != expected { return Err(Error::conflict("workflow model changed after review")); }
2175 }
2176 if to == Lifecycle::Released {
2177 let part = state.part(part_id).ok_or_else(|| Error::not_found("part"))?;
2180 catalog_gate(&state.categories, part)?;
2181 let revision = part.revision(revision_id).ok_or_else(|| Error::not_found("revision"))?;
2182 let field_problems = crate::bom_config::release_problems(state, part, revision);
2183 if !field_problems.is_empty() { return Err(Error::conflict(field_problems.join("; "))); }
2184 children_gate(state, part, revision)?;
2185 instructions_gate(state, &root, part, revision)?;
2186 review_gate(state, part, revision)?;
2187 }
2188 let (_, revision) = find_revision_mut(state, part_id, revision_id)?;
2189 lifecycle::check_transition(revision.lifecycle, to).map_err(Error::conflict)?;
2190 if revision.lifecycle == Lifecycle::InReview && to == Lifecycle::Draft {
2192 if let Some(review) = revision.live_review_mut() {
2193 crate::review::withdraw(review, &user_id, now());
2194 }
2195 }
2196 if let Some(hash) = &seen_hash {
2197 if *hash != revision.content_hash {
2198 return Err(Error::conflict(format!(
2199 "revision {} changed while {} was checking it — release it again",
2200 revision.label,
2201 scripting::BEFORE_RELEASE
2202 )));
2203 }
2204 }
2205 if to == Lifecycle::Released {
2206 bake_gate(revision)?;
2207 if let Some(lock) = &revision.lock {
2208 return Err(Error::conflict(format!(
2209 "revision {} is checked out (held since {}) — check it in before releasing",
2210 revision.label, lock.acquired_at
2211 )));
2212 }
2213 crate::review::close_on_release(revision, &user_id, now());
2214 revision.released_by = Some(user_id);
2215 revision.released_at = Some(now());
2216 revision.lock = None;
2217 }
2218 revision.lifecycle = to;
2219 let released_id = revision.id.clone();
2220
2221 if to == Lifecycle::Released {
2225 let part = state.parts.get_mut(&part_id)
2226 .ok_or_else(|| Error::not_found("part"))?;
2227 for other in part.revisions.iter_mut() {
2228 if other.id != released_id && other.lifecycle == Lifecycle::Released {
2229 other.lifecycle = Lifecycle::Superseded;
2230 }
2231 }
2232 }
2233 state.touch_part(&part_id);
2234 Ok(())
2235 })?;
2236
2237 let mut warnings = Vec::new();
2238 if to == Lifecycle::Draft {
2239 warnings.extend(self.review_withdrawn(user, part_id, revision_id));
2240 }
2241 if !users.is_empty() {
2242 warnings.push(format!(
2243 "obsolete, but still used by {}: their BOMs flag it until they are revised to use another revision",
2244 named_list(&users)
2245 ));
2246 }
2247 if to == Lifecycle::Released {
2248 let (part, revision) = self.snapshot(part_id, revision_id)?;
2249 let unreleased = self.read(|state| bom::unreleased_children(state, &revision));
2252 if !unreleased.is_empty() {
2253 warnings.push(format!("released, but it uses unreleased parts: {}", unreleased.join("; ")));
2254 }
2255 let input = self.read(|state| release_input(state, &part, &revision, user));
2256 match scripting::run(self, user, scripting::AFTER_RELEASE, "afterRelease", &input) {
2257 Ok(HookResult::Absent) | Ok(HookResult::Returned(_)) => {}
2258 Ok(HookResult::Refused(failure)) => warnings.push(format!(
2259 "released, but {} failed: {}",
2260 scripting::AFTER_RELEASE,
2261 failure.message
2262 )),
2263 Err(error) => warnings.push(format!(
2264 "released, but {} could not run: {}",
2265 scripting::AFTER_RELEASE,
2266 error.message
2267 )),
2268 }
2269 }
2270 Ok(warnings)
2271 }
2272
2273 pub(crate) fn snapshot(&self, part_id: &str, revision_id: &str) -> Result<(Part, Revision), Error> {
2275 self.read(|state| {
2276 let part = state.part(part_id).ok_or_else(|| Error::not_found("part"))?;
2277 let revision = part
2278 .revision(revision_id)
2279 .ok_or_else(|| Error::not_found("revision"))?;
2280 Ok((part.clone(), revision.clone()))
2281 })
2282 }
2283
2284 pub fn delete_draft(&self, user: &User, part_id: &str, revision_id: &str) -> Result<(), Error> {
2287 let user_id = user.id.clone();
2288 let may_break = user.can_checkin();
2289 let key = crate::identity::document_key(part_id, revision_id);
2290 let root = self.root().to_path_buf();
2291 self.mutate(|state| {
2292 let (_, revision) = find_revision_mut(state, part_id, revision_id)?;
2293 if !revision.lifecycle.is_editable() {
2294 return Err(Error::conflict(
2295 "only a draft can be deleted — release history is permanent".to_string(),
2296 ));
2297 }
2298 if let Some(lock) = &revision.lock {
2299 if lock.user_id != user_id && !may_break {
2300 return Err(Error::forbidden(
2301 "another user has this draft checked out",
2302 ));
2303 }
2304 }
2305 let part = state.parts.get_mut(&part_id)
2306 .ok_or_else(|| Error::not_found("part"))?;
2307 if part.revisions.len() == 1 {
2308 return Err(Error::conflict(
2309 "a part keeps at least one revision".to_string(),
2310 ));
2311 }
2312 let pinners = pinned_by(state, part_id, revision_id);
2315 if !pinners.is_empty() {
2316 let lists = if pinners.len() == 1 { "that list" } else { "those lists" };
2317 return Err(Error::conflict(format!(
2318 "this revision is used by {} — remove it from {lists} first",
2319 named_list(&pinners)
2320 )));
2321 }
2322 let part = state.parts.get_mut(&part_id)
2323 .ok_or_else(|| Error::not_found("part"))?;
2324 let thumbnail = part.revision(revision_id).and_then(|r| r.thumbnail.as_ref()).map(|t| t.sha256.clone());
2325 part.revisions.retain(|r| r.id != revision_id);
2326 if let Some(sha) = thumbnail {
2327 crate::attach::remove_if_unreferenced(state, &root, &sha)?;
2328 }
2329 state.touch(key.clone());
2330 Ok(())
2331 })?;
2332 self.remove_document(&key)
2333 }
2334
2335 pub fn changes_since(&self, since: u64) -> (u64, bool, Vec<String>) {
2338 self.read(|state| {
2339 let stale = since < state.changes_floor();
2340 let keys: Vec<String> = state
2341 .changes
2342 .iter()
2343 .filter(|c| c.seq > since)
2344 .map(|c| c.key.clone())
2345 .collect::<BTreeSet<_>>()
2346 .into_iter()
2347 .collect();
2348 (state.seq, stale, keys)
2349 })
2350 }
2351}
2352
2353#[derive(Debug, Clone, Default)]
2360pub struct CategoryChange {
2361 pub name: Option<String>,
2362 pub parent: Option<String>,
2364 pub attributes: Option<Vec<AttributeDef>>,
2366}
2367
2368impl Db {
2369 pub fn create_category(&self, id: &str, change: CategoryChange) -> Result<Category, Error> {
2373 let id = catalog::normalize_id(id)?;
2374 let name = change.name.unwrap_or_default().trim().to_string();
2375 if name.is_empty() {
2376 return Err(Error::bad_request("a category needs a name"));
2377 }
2378 let attributes = catalog::check_definitions(change.attributes.unwrap_or_default())?;
2379 let parent = change.parent.unwrap_or_default().trim().to_string();
2380 self.mutate(move |state| {
2381 if catalog::find(&state.categories, &id).is_some() {
2382 return Err(Error::conflict(format!("category '{id}' exists")));
2383 }
2384 let parent = if parent.is_empty() {
2385 String::new()
2386 } else {
2387 catalog::find(&state.categories, &parent)
2388 .map(|c| c.id.clone())
2389 .ok_or_else(|| Error::bad_request(format!("there is no category '{parent}'")))?
2390 };
2391 let category = Category { id, name, parent, attributes, created_at: now() };
2392 state.categories.push(category.clone());
2393 catalog::check_tree(&state.categories)?;
2394 Ok(category)
2395 })
2396 }
2397
2398 pub fn update_category(&self, id: &str, change: CategoryChange) -> Result<Category, Error> {
2405 let attributes = change.attributes.map(catalog::check_definitions).transpose()?;
2406 let id = id.trim().to_string();
2407 self.mutate(move |state| {
2408 let index = state
2409 .categories
2410 .iter()
2411 .position(|c| c.id.eq_ignore_ascii_case(&id))
2412 .ok_or_else(|| Error::not_found(format!("category '{id}'")))?;
2413 if let Some(name) = change.name {
2414 let name = name.trim().to_string();
2415 if name.is_empty() {
2416 return Err(Error::bad_request("a category needs a name"));
2417 }
2418 state.categories[index].name = name;
2419 }
2420 if let Some(parent) = change.parent {
2421 let parent = parent.trim();
2422 state.categories[index].parent = if parent.is_empty() {
2423 String::new()
2424 } else {
2425 catalog::find(&state.categories, parent)
2426 .map(|c| c.id.clone())
2427 .ok_or_else(|| Error::bad_request(format!("there is no category '{parent}'")))?
2428 };
2429 }
2430 if let Some(attributes) = attributes {
2431 state.categories[index].attributes = attributes;
2432 }
2433 catalog::check_tree(&state.categories)?;
2437 Ok(state.categories[index].clone())
2438 })
2439 }
2440
2441 pub fn delete_category(&self, id: &str) -> Result<(), Error> {
2445 let id = id.trim().to_string();
2446 self.mutate(move |state| {
2447 let category = catalog::find(&state.categories, &id)
2448 .ok_or_else(|| Error::not_found(format!("category '{id}'")))?
2449 .id
2450 .clone();
2451 if let Some(child) = state.categories.iter().find(|c| c.parent.eq_ignore_ascii_case(&category)) {
2452 return Err(Error::conflict(format!(
2453 "category '{category}' has a sub-category '{}' — move or delete it first",
2454 child.id
2455 )));
2456 }
2457 let used = state
2458 .parts
2459 .iter()
2460 .filter(|p| p.category.eq_ignore_ascii_case(&category))
2461 .count();
2462 if used > 0 {
2463 return Err(Error::conflict(format!(
2464 "category '{category}' holds {used} part{} — move them to another category first",
2465 if used == 1 { "" } else { "s" }
2466 )));
2467 }
2468 state.categories.retain(|c| c.id != category);
2469 Ok(())
2470 })
2471 }
2472}
2473
2474fn part_matches(categories: &[Category], part: &Part, needle: &str) -> bool {
2477 let hit = |text: &str| text.to_ascii_lowercase().contains(needle);
2478 hit(&part.number)
2479 || hit(&part.name)
2480 || hit(&part.description)
2481 || hit(&part.category)
2482 || hit(&catalog::path_name(categories, &part.category))
2483 || part.tags.iter().any(|t| hit(t))
2484 || part.attributes.values().any(|value| match value {
2485 Value::String(text) => hit(text),
2486 Value::Number(n) => hit(&n.to_string()),
2487 _ => false,
2488 })
2489 || part.sourcing.iter().any(|mp| hit(&mp.mpn) || mp.offers.iter().any(|o| hit(&o.spn)))
2490}
2491
2492fn catalog_gate(categories: &[Category], part: &Part) -> Result<(), Error> {
2496 let problems = catalog::release_problems(categories, part);
2497 if problems.is_empty() {
2498 return Ok(());
2499 }
2500 Err(Error::conflict(format!(
2501 "{} cannot release until its catalog values are complete: {}",
2502 part.number,
2503 problems.join("; ")
2504 )))
2505}
2506
2507fn review_gate(state: &State, part: &Part, revision: &Revision) -> Result<(), Error> {
2509 let (rule, _) = crate::review::rule_for(&state.settings, &state.categories, part);
2510 crate::review::release_gate(revision, &rule, &part.number)
2511}
2512
2513pub fn instructs_of(state: &State, document: &Value) -> Option<crate::model::Instructs> {
2517 let key = document.pointer("/instructions/target/sourceKey")?.as_str()?;
2518 let (number, label) = crate::identity::split_key(key)?;
2519 let part = state.part(&number).filter(|p| p.document_class != DocumentClass::Instructions)?;
2520 let revision = part.revision(&label)?;
2521 Some(crate::model::Instructs { part: part.id.clone(), revision: revision.id.clone() })
2522}
2523
2524fn instructions_gate(state: &State, root: &Path, part: &Part, revision: &Revision) -> Result<(), Error> {
2530 if part.document_class != DocumentClass::Instructions {
2531 return Ok(());
2532 }
2533 let refuse = |why: String| Err(Error::conflict(format!("{} rev {} cannot release: {why}", part.number, revision.label)));
2534 let Some(target) = &revision.instructs else {
2535 return refuse("its document instructs no PLM assembly revision".into());
2536 };
2537 let Some((assembly, assembly_revision)) = state.part(&target.part).and_then(|p| Some((p, p.revision(&target.revision)?))) else {
2538 return refuse("the assembly revision it instructs is gone".into());
2539 };
2540 if assembly_revision.lifecycle != Lifecycle::Released {
2541 return refuse(format!("{} rev {} is {}, not released", assembly.number, assembly_revision.label, assembly_revision.lifecycle.as_str()));
2542 }
2543 let document = fs::read_to_string(root.join(crate::identity::model_path(&part.id, &revision.id)))
2544 .ok()
2545 .and_then(|text| serde_json::from_str::<Value>(&text).ok());
2546 if document.as_ref().and_then(|d| d.pointer("/instructions/retarget")).is_some_and(|r| !r.is_null()) {
2547 return refuse(format!("its re-target to {} rev {} is not approved yet", assembly.number, assembly_revision.label));
2548 }
2549 if revision.player.as_ref().is_none_or(|player| player.content_hash != revision.content_hash) {
2550 return refuse("it has no current player data: open it in the CAD app and save it there".into());
2551 }
2552 Ok(())
2553}
2554
2555fn children_gate(state: &State, part: &Part, revision: &Revision) -> Result<(), Error> {
2556 if !state.settings.require_released_children {
2557 return Ok(());
2558 }
2559 let problems = bom::unreleased_children(state, revision);
2560 if problems.is_empty() {
2561 return Ok(());
2562 }
2563 Err(Error::conflict(format!(
2564 "{} rev {} cannot release until everything it uses is released: {}",
2565 part.number,
2566 revision.label,
2567 problems.join("; ")
2568 )))
2569}
2570
2571fn pinned_by(state: &State, part_id: &str, revision_id: &str) -> Vec<String> {
2574 state
2575 .parts
2576 .iter()
2577 .flat_map(|parent| {
2578 parent.revisions.iter().filter_map(move |rev| {
2579 rev.uses
2580 .iter()
2581 .any(|u| u.part == part_id && u.revision == revision_id)
2582 .then(|| format!("{} rev {}", parent.number, rev.label))
2583 })
2584 })
2585 .collect()
2586}
2587
2588fn used_by_now(state: &State, part_id: &str, revision_id: &str) -> Vec<String> {
2591 let Some(part) = state.part(part_id) else { return Vec::new() };
2592 let Some(revision) = part.revision(revision_id) else { return Vec::new() };
2593 let mut out: Vec<String> = Vec::new();
2594 for line in bom::where_used(state, part, Some(revision), 1).lines {
2595 let name = format!("{} rev {} ({})", line.number, line.revision_label, line.state);
2596 if !out.contains(&name) {
2597 out.push(name);
2598 }
2599 }
2600 out
2601}
2602
2603pub(crate) fn named_list(names: &[String]) -> String {
2605 let shown = names.iter().take(NAMED_AT_MOST).cloned().collect::<Vec<_>>().join(", ");
2606 match names.len().saturating_sub(NAMED_AT_MOST) {
2607 0 => shown,
2608 more => format!("{shown} and {more} more"),
2609 }
2610}
2611
2612const NAMED_AT_MOST: usize = 10;
2614
2615pub fn check_writable(state: &State, user: &User, part_id: &str, revision_id: &str) -> Result<(), Error> {
2619 let part = state.part(part_id).ok_or_else(|| Error::not_found("part"))?;
2620 let revision = part
2621 .revision(revision_id)
2622 .ok_or_else(|| Error::not_found("revision"))?;
2623 if !revision.lifecycle.is_editable() {
2624 return Err(Error::conflict(format!(
2625 "{} revision {} is {} and cannot be written — start a new revision",
2626 part.number,
2627 revision.label,
2628 revision.lifecycle.as_str()
2629 )));
2630 }
2631 match &revision.lock {
2632 None => Err(Error::conflict(format!(
2633 "{} revision {} is not checked out — check it out before saving",
2634 part.number, revision.label
2635 ))),
2636 Some(lock) if lock.user_id != user.id => {
2637 let holder = state
2638 .user(&lock.user_id)
2639 .map(|u| u.username.clone())
2640 .unwrap_or_else(|| "another user".to_string());
2641 Err(Error::conflict(format!(
2642 "{} revision {} is checked out by {holder}",
2643 part.number, revision.label
2644 )))
2645 }
2646 Some(_) => Ok(()),
2647 }
2648}
2649
2650impl Db {
2651 pub fn set_uses(&self, user: &User, part_id: &str, revision_id: &str, body: &Value) -> Result<Vec<Use>, Error> {
2658 let user = user.clone();
2659 let body = body.clone();
2660 self.mutate(move |state| {
2661 check_writable(state, &user, part_id, revision_id)?;
2662 let uses = bom::check_uses(state, part_id, &body)?;
2663 let occurrences = crate::bom_config::capture_occurrences(state, part_id, revision_id, &body)?;
2664 let (_, revision) = find_revision_mut(state, part_id, revision_id)?;
2665 revision.uses = uses.clone();
2666 if let Some(occurrences) = occurrences { revision.occurrences = occurrences; }
2667 crate::bom_config::synchronize_uses(revision);
2668 revision.modified_at = now();
2669 state.touch(crate::identity::document_key(part_id, revision_id));
2670 Ok(uses)
2671 })
2672 }
2673}
2674
2675pub(crate) fn release_input(state: &State, part: &Part, revision: &Revision, user: &User) -> Value {
2677 json!({
2678 "part": part,
2679 "sourcing": sourcing::resolved(state, part),
2680 "revision": revision,
2681 "uses": bom::resolved_uses(state, revision),
2682 "unreleased_children": bom::unreleased_children(state, revision),
2683 "document_key": revision.document_key(&part.id),
2684 "user": scripting::user_json(user),
2685 })
2686}
2687
2688fn state_has_number(parts: &[Part], number: &str) -> bool {
2690 parts.iter().any(|p| p.number.eq_ignore_ascii_case(number))
2691}
2692
2693pub fn full_match(pattern: &str) -> Result<regex::Regex, Error> {
2696 regex::Regex::new(&format!("^(?:{pattern})$"))
2697 .map_err(|e| Error::bad_request(format!("'{pattern}' is not a usable pattern: {e}")))
2698}
2699
2700pub const MAX_IDENTIFIER: usize = 64;
2702
2703pub fn check_number(number: &str) -> Result<(), Error> {
2706 check_identifier(number, "a part number")
2707}
2708
2709pub fn check_label(label: &str) -> Result<(), Error> {
2711 check_identifier(label, "a revision label")
2712}
2713
2714fn check_identifier(text: &str, what: &str) -> Result<(), Error> {
2715 if text.trim().is_empty() {
2716 return Err(Error::bad_request(format!("{what} cannot be empty")));
2717 }
2718 if text.trim() != text {
2719 return Err(Error::bad_request(format!("{what} cannot start or end with a space")));
2720 }
2721 if text.chars().any(char::is_control) {
2722 return Err(Error::bad_request(format!("{what} cannot hold control characters")));
2723 }
2724 if text.chars().count() > MAX_IDENTIFIER {
2725 return Err(Error::bad_request(format!("{what} is at most {MAX_IDENTIFIER} characters")));
2726 }
2727 Ok(())
2728}
2729
2730pub fn suggest_label(part: &Part) -> String {
2735 let mut candidate = lifecycle::next_revision_label(part.latest().map(|r| r.label.as_str()));
2736 while part.revision_by_label(&candidate).is_some() {
2737 candidate = lifecycle::next_revision_label(Some(&candidate));
2738 }
2739 candidate
2740}
2741
2742#[derive(Debug, Clone, Default)]
2745pub struct PartSpec {
2746 pub part_type: String,
2747 pub number: String,
2748 pub name: String,
2749 pub description: String,
2750 pub category: String,
2751 pub document_class: DocumentClass,
2752 pub label: String,
2753 pub tags: Vec<String>,
2754 pub attributes: serde_json::Map<String, Value>,
2757 pub exact: bool,
2760 pub external_ref: String,
2763 pub origin: crate::model::Origin,
2766 pub workspace: Option<String>,
2770}
2771
2772pub fn external_ref_clash(state: &State, part_type: &str, external_ref: &str, except: &str) -> Result<(), Error> {
2778 if external_ref.is_empty() {
2779 return Ok(());
2780 }
2781 match state.parts.iter().find(|p| p.id != except && p.part_type == part_type && p.external_ref == external_ref) {
2782 Some(owner) => Err(Error::conflict(format!(
2783 "external_ref '{external_ref}' is already {} ({}) — look it up with ?external_ref= and use that part",
2784 owner.number, part_type
2785 ))),
2786 None => Ok(()),
2787 }
2788}
2789
2790pub fn check_origin(origin: crate::model::Origin) -> Result<(), Error> {
2792 if origin == crate::model::Origin::Generated {
2793 return Err(Error::bad_request("origin 'generated' is set by Generate alone — use authored or imported"));
2794 }
2795 Ok(())
2796}
2797
2798pub(crate) fn find_revision_mut<'a>(
2800 state: &'a mut State,
2801 part_id: &str,
2802 revision_id: &str,
2803) -> Result<(String, &'a mut Revision), Error> {
2804 let part = state.parts.get_mut(&part_id)
2805 .ok_or_else(|| Error::not_found("part"))?;
2806 let number = part.number.clone();
2807 let revision = part
2808 .revision_mut(revision_id)
2809 .ok_or_else(|| Error::not_found("revision"))?;
2810 Ok((number, revision))
2811}
2812