Skip to main content

brep_plm/
db.rs

1//! The store: the metadata in SQLite (`plm.sqlite`, see [`crate::sql`]), one
2//! file per CAD document, and the monotonic change sequence the CAD app's
3//! mirror will key its cache on.
4//!
5//! # Memory, then disk, in one critical section
6//!
7//! The whole metadata is held in memory under one lock and every read is
8//! answered from there. Every change goes through [`Db::mutate`]: under the
9//! write lock, the change's closure checks its rules against the in-memory
10//! state and edits it, and then — still under the lock — exactly what it
11//! touched is written to SQLite in ONE transaction, together with the
12//! change's audit events. If the closure refuses, or the transaction fails,
13//! the in-memory edits are undone and nothing is on disk. So every rule that
14//! "runs inside the lock" runs in the same critical section as the write that
15//! depends on it, and the schema's own constraints (one number per part, one
16//! label per revision within a part) refuse anything a rule missed.
17//!
18//! A change costs what it touched, not what the store holds: the part list
19//! journals the parts a change touches ([`crate::table::Parts`]), and the
20//! other state fields — users, sessions, the catalog, settings — are small.
21//!
22//! # Documents
23//!
24//! Write to `<path>.tmp`, then rename. A rename over an existing file is
25//! atomic on every platform this runs on, so a process killed mid-write leaves
26//! either the old file or the new one and never a truncated one.
27//!
28//! # The sequence
29//!
30//! `seq` increments on every mutation, whoever made it, and every mutating
31//! response carries it. That is the `mutation_generation()` the CAD app's
32//! `ModelStore` requires — a REQUIRED trait method precisely so a backend
33//! cannot compile while silently never invalidating anything. `changes(since)`
34//! then answers "which keys moved", which is what drives a client's per-key
35//! refresh instead of a re-hydrate.
36//!
37//! The change log is bounded ([`CHANGE_LOG_LIMIT`]). A client that asks from
38//! further back than the log reaches is told `stale`, and its correct response
39//! is to re-read the index rather than to trust a short answer.
40//!
41use 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
66/// How many recent key changes the log keeps. Past this a client is told to
67/// re-index rather than given a partial answer.
68pub const CHANGE_LOG_LIMIT: usize = 4096;
69
70/// One key that changed, and the sequence it changed at.
71#[derive(Debug, Clone, Serialize, Deserialize)]
72pub struct Change {
73    pub seq: u64,
74    pub key: String,
75}
76
77/// Everything the server holds in memory, and exactly what the metadata file
78/// contains.
79#[derive(Debug, Default, Serialize, Deserialize)]
80pub struct State {
81    /// The tools library ([`crate::tools`]), and the last tool number handed out.
82    #[serde(default)]
83    pub tools: Vec<crate::tools::Tool>,
84    #[serde(default)]
85    pub next_tool: u64,
86    /// The jobs floor queue ([`crate::jobs`]), journaled like sessions: a
87    /// floor signs a step a minute, and a list kept in the state's other
88    /// fields cost every write on the server O(every job) — 0.56 s at 1,000
89    /// jobs of 30 steps. One `meta` row per job (`job:<id>`).
90    // Stored separately from the metadata snapshot and restored after decoding it.
91    #[serde(default)]
92    pub jobs: crate::journal::Journaled<crate::jobs::Job>,
93    /// The last job number handed out.
94    #[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    /// Browser sessions, journaled ([`crate::journal`]): one is added per
102    /// sign-in, so this grows with use, and a list outside a journal costs
103    /// every write O(its length).
104    // Stored separately from the metadata snapshot and restored after decoding it.
105    #[serde(default)]
106    pub sessions: crate::journal::Journaled<Session>,
107    /// Bearer tokens for callers that are not a browser ([`ApiToken`]).
108    pub api_tokens: Vec<ApiToken>,
109    pub part_types: Vec<PartType>,
110    // Stored separately from the metadata snapshot and restored after decoding it.
111    #[serde(default)]
112    pub parts: Parts,
113    /// The catalog tree, flat: each category names its parent.
114    pub categories: Vec<Category>,
115    /// Who makes parts ([`Company`]); a manufacturer part names one.
116    pub manufacturers: Vec<Company>,
117    /// Who sells parts ([`Company`]); a supplier offer names one.
118    pub suppliers: Vec<Company>,
119    /// The administrator's policy choices ([`Settings`]).
120    pub settings: Settings,
121    /// The workspace model the store is at ([`crate::workspace::MODEL`]);
122    /// an older one is brought up to date when the store opens.
123    #[serde(default)]
124    pub workspace_model: u32,
125    pub changes: Vec<Change>,
126    /// The lowest sequence the change log can still answer for completely.
127    /// It moves only when [`CHANGE_LOG_LIMIT`] forces entries out, so a
128    /// client is told `stale` when the log has actually DROPPED something it
129    /// needed — not merely because nothing happened at the sequence it asked
130    /// from, which is the ordinary case for a client that has been idle.
131    pub changes_from: u64,
132    /// Every user's workspace entries ([`crate::model::WorkspaceEntry`]),
133    /// in creation order.
134    // Stored separately from the metadata snapshot and restored after decoding it.
135    #[serde(default)]
136    pub workspace: crate::workspace::Workspace,
137}
138
139impl State {
140    /// Record that every revision of `part_id` moved: a lock, a lifecycle or
141    /// a supersede changes the store index's rows for them (`locked_by`,
142    /// `lifecycle`, `editable`) without writing a document, and the change
143    /// feed has to name them so a client can re-read exactly those rows
144    /// (`GET /api/store/index?keys=`) instead of the whole index.
145    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    /// Record that `key`'s document moved at the current sequence. Called
156    /// inside a mutation, AFTER [`Db::mutate`] has bumped `seq`.
157    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    /// A part by its id, or else by its number.
190    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    /// The part that already carries `number`, compared without regard to
196    /// ASCII case. A part number is unique across ALL parts, whatever type
197    /// made it: it is what an ERP, a BOM and a person
198    /// reading a drawing use to mean exactly one part.
199    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    /// The oldest sequence the change log can still answer for completely.
205    /// A client asking from before this is told `stale` and must re-index.
206    pub fn changes_floor(&self) -> u64 {
207        self.changes_from
208    }
209}
210
211/// The server's whole persistent state: the metadata under one lock (and in
212/// SQLite), the document tree beside it, and the administrator's scripts.
213///
214/// A `Db` is a HANDLE: cloning it is cheap and every clone is the same store.
215/// That is what lets a script's `plm.*` bindings hold the store for the length
216/// of one hook call.
217#[derive(Clone)]
218pub struct Db {
219    root: PathBuf,
220    state: Arc<RwLock<State>>,
221    scripts: Arc<Scripts>,
222    security: Arc<Security>,
223    /// The metadata on disk, and the audit log and search index with it.
224    sql: Arc<Sql>,
225    /// This process's hold on the data directory ([`crate::dirlock`]), for as
226    /// long as any handle to the store is alive.
227    _lock: Arc<crate::dirlock::DirLock>,
228    /// The last backup this process took, and whether one is running.
229    backups: Arc<crate::backup::Status>,
230    pub(crate) bake_worker: Arc<crate::bake_worker::Controller>,
231}
232
233/// Whole seconds since the epoch.
234pub 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    /// Open (or create) the store at `root`.
243    ///
244    /// Returns the generated administrator password when — and only when —
245    /// this call seeded the first account. It is printed once at boot and
246    /// never recoverable, which is the point: no build of this server ships a
247    /// known password.
248    pub fn open(root: impl Into<PathBuf>) -> io::Result<(Self, Option<String>)> {
249        Self::open_with_scripts(root, None)
250    }
251
252    /// [`Db::open`], with the scripts directory somewhere other than
253    /// `<root>/scripts` — typically a git checkout the administrator manages.
254    /// This is the path `serve` opens with, always at [`Durability::Full`].
255    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    /// [`Db::open_with_scripts`] at a chosen [`Durability`]. The test suites
263    /// open with [`Durability::Normal`]; the server never does.
264    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        // First, before anything in the directory is read or moved: two
271        // servers on one directory would each hold their own copy of the
272        // metadata and overwrite each other's changes.
273        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        // A store with no workspace entries has nothing to convert: it is at
286        // the current model from the start, with no audited change.
287        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            // The DEFAULT, not the rule: prefix and width are data from here
294            // on, and an operator adds more types through the API.
295            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        // What a crash between an upload's move and its commit can leave:
346        // nothing else is running yet, and the directory is ours alone.
347        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    /// The administrator's scripts directory.
362    /// The data directory.
363    pub fn root(&self) -> &Path {
364        &self.root
365    }
366
367    /// Stop only the child owned by this server, including on shutdown.
368    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    /// This store with the network-facing configuration `config`. Called once,
377    /// at start-up, before the store is shared; the throttle starts empty.
378    pub fn with_config(mut self, config: ServerConfig) -> Self {
379        self.security = Arc::new(Security { config, ..Security::default() });
380        self
381    }
382
383    /// The last backup this process took.
384    pub fn backups(&self) -> &crate::backup::Status {
385        &self.backups
386    }
387
388    /// The hardening layer: configuration and the sign-in throttle.
389    pub fn security(&self) -> &Security {
390        &self.security
391    }
392
393    /// Whether administrators may edit and test-run scripts in the browser:
394    /// the setting, unless `--lock-script-editor` forces it off.
395    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    /// Read the metadata under the shared lock.
400    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    /// Mutate the metadata under the exclusive lock, bump the sequence, and
406    /// PERSIST before returning.
407    ///
408    /// Persisting inside the guard is what makes number allocation safe: two
409    /// concurrent part creations serialize on this lock, and neither response
410    /// is sent until the number it handed out is committed. A closure that
411    /// returns `Err` leaves the state untouched: the parts it touched are put
412    /// back from the journal ([`Parts`]) and every other field from the copy
413    /// taken before it ran. The same happens when the write to disk fails —
414    /// a UNIQUE constraint the closure's own check missed, a full disk.
415    ///
416    /// The change's audit events ([`crate::audit`]) are computed from exactly
417    /// what it touched and committed in the SAME transaction as the change, so
418    /// a change is never on disk without its events, nor an event without its
419    /// change. Every write path goes through here, so every change is logged
420    /// without any of them asking.
421    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    /// Write one committed change and its audit events in one transaction.
459    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        // A part a change borrowed mutably but did not actually change is
470        // neither written nor audited.
471        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        // The journaled lists the same way: only what was touched, and only
489        // what actually changed, is written and audited.
490        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        // A part's search row holds its category's PATH ("Fasteners /
507        // Screws"): re-index the parts whose category's path the change moved
508        // — a rename, a move, a category created for text a part already had.
509        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    /// Record an event that is not a change to the store: a failed sign-in, a
548    /// script file edited or run in the browser.
549    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    /// Audit events matching `filter`, newest first.
566    pub fn audit_query(&self, filter: &AuditFilter) -> Result<Vec<AuditEvent>, Error> {
567        self.sql.query(filter).map_err(Error::internal)
568    }
569
570    /// The SQLite store, for the search index and diagnostics.
571    pub fn sql(&self) -> &Sql {
572        &self.sql
573    }
574
575    // -- documents ---------------------------------------------------------
576
577    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    /// One document's text, or `None` when it has never been written.
584    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    /// Write a document and record its hash on the revision.
594    ///
595    /// The editable check is HERE, not only in the API layer: this is the one
596    /// function that can change a revision's bytes, so it is the one that has
597    /// to refuse a released revision. A guard that lives only in the handler
598    /// is a guard that the next caller forgets.
599    ///
600    /// Everything happens inside one [`Db::mutate`], which is what makes the
601    /// check race-free — a release landing between a separate check and the
602    /// write would otherwise rewrite released bytes. Within the guard the file
603    /// still lands BEFORE the metadata that describes it, so a crash between
604    /// the two leaves a document whose hash is not yet recorded, rather than a
605    /// recorded hash for bytes that do not exist.
606    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    /// [`Self::write_document`] (or [`Self::write_document_if`] with
611    /// `if_match`), answering also why the document's uses list was NOT
612    /// derived from it, when it was not (S5 derived, `derived-uses`): an
613    /// occurrence that places no PLM revision, or a list the uses rules
614    /// refuse. The document is written either way, as it was when the CAD app
615    /// published the list in a request of its own.
616    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    /// [`Self::write_document`] only if the revision still holds the document
621    /// whose content hash is `expected` (an `If-Match` write): checked under
622    /// the write lock, so a save made meanwhile (another client of the same
623    /// user, another session) is never overwritten by a write based on the
624    /// older document. A mismatch is `409`, naming when it changed and who
625    /// holds it now.
626    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    /// Import a reviewed document and its structure together. The expected
631    /// hash and checkout are checked under the write lock, so another save or
632    /// a broken checkout cannot silently replace the document reviewed by the user.
633    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            // S5 derived: the uses list follows the document, in this same
672            // write (an import brings its reviewed list instead). A list the
673            // rules refuse leaves the old one and says why; the document is
674            // written all the same.
675            let mut uses_refused = None;
676            // Instructions place their assembly as one wrapper component: that
677            // is what they instruct, not something they are built from, so
678            // they publish no uses list (and no occurrences) from it.
679            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(&current.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            // A document someone SAVED supersedes a bake still waiting: the
769            // CAD app evaluated what it saved. A worker that had the job is
770            // refused when it reports back (see `Db::finish_bake`).
771            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            // Approvals given on the document before this save go stale (D8).
780            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    /// Remove a document's bytes. The revision record stays — a revision with
790    /// no document is a legitimate state (a part imported with no 3D model).
791    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
801/// The metadata file in a data directory.
802pub const SQLITE_FILE: &str = "plm.sqlite";
803
804/// Put every field but the parts back as `before` had it.
805/// Whether `session` has ended by the settings' limits at `now`: idle for
806/// longer than `session_idle_minutes`, or signed in longer ago than
807/// `session_max_hours` (0: no such limit).
808pub 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    /// Remove every expired session ([`session_expired`]), as the system;
817    /// how many went.
818    ///
819    /// A session used to be removed only by signing out, or when its cookie
820    /// came back after it expired. A browser that simply stops sending the
821    /// cookie — it expired there, the user cleared it, a private window
822    /// closed — left its session in the store for good, and every sign-in
823    /// adds one: the list grew with use and nothing bounded it. This runs at
824    /// every sign-in — the only way the list grows — so it holds the sessions
825    /// that could still be used, plus whatever expired since the last
826    /// sign-in. Not at start-up: opening a store changes nothing in it (an
827    /// import or a restore opens exactly what it was given). Nothing is
828    /// written when nothing has expired.
829    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/// A journaled list's change as the audit and the store want it: the touched
847/// records before and after (only those that changed), and each changed key
848/// with what it is now (`None`: removed).
849#[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
881/// Write `body` to `path` through a temporary file and a rename, so a reader
882/// never sees a partial file and a crash never leaves a short one: the
883/// temporary sits beside `path` (same file system, so the rename is atomic),
884/// is named for this process and write (`<name>.<pid>-<n>.tmp`, so two
885/// writers never share one and it never replaces `path`'s extension), is
886/// flushed to disk before the rename, and is removed when any step fails.
887pub(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
908// ===========================================================================
909// Operations — the rules that are about MORE than one record
910// ===========================================================================
911
912impl Db {
913    /// Create a part of the default shape: the type decides the number, the
914    /// document is normal, the first revision takes the suggested label.
915    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    /// Create a part with its first draft revision.
936    ///
937    /// The number comes from the type's [`NumberMode`]. A Script-mode type and
938    /// the revision-label hook are asked OUTSIDE the store lock, on a snapshot;
939    /// then one [`Db::mutate`] re-checks everything their answers depend on —
940    /// that the type's mode did not change meanwhile, and that the number and
941    /// label are still free. Two concurrent creates that a script gave the
942    /// same number therefore end as one part and one refusal, never two parts.
943    /// The part type instructions are numbered in when a request names none:
944    /// `instructions` (`MI` and 9 digits), made the first time it is needed.
945    /// An admin may rename it or change its numbering like any other type.
946    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            // The category and the values are checked HERE, against the tree
1086            // as it is at the write — an admin may be editing it meanwhile.
1087            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                    // The counter skips numbers another type already gave out:
1105                    // a free-text or scripted number may land in its range.
1106                    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    /// The label a new revision gets: the revision-label hook's answer when
1164    /// that script exists, else what the user typed, else `suggested`.
1165    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                // Returning nothing means "no opinion".
1192                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    /// Start a new revision of a part, labelled with the suggestion.
1208    pub fn create_revision(&self, author: &User, part_id: &str) -> Result<Revision, Error> {
1209        self.create_revision_labelled(author, part_id, "")
1210    }
1211
1212    /// Start a new revision of a part.
1213    ///
1214    /// While another revision is in work this is refused only when the
1215    /// administrator has turned [`Settings::allow_multiple_open_drafts`] off;
1216    /// by default several revisions may be in work at once. The new draft
1217    /// inherits the document of the revision currently RELEASED — or, when
1218    /// none is, the newest revision — so revising a part starts from what the
1219    /// part currently is, never from somebody else's unfinished draft. That
1220    /// includes an imported part, which is revised rather than forked.
1221    ///
1222    /// `label` is free text; empty takes the suggestion.
1223    /// It must not repeat a label the part already has.
1224    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    /// [`Db::create_revision_labelled`] with the new revision's origin: a
1234    /// library re-import makes an `imported` one, so the next re-import
1235    /// still knows the latest revision is its own.
1236    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    /// [`Db::create_revision_labelled`]. With `exact`, the revision-label hook
1248    /// may refuse `label` but not rename it — what a family row needs, since
1249    /// the row names the revision it writes.
1250    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            // Again inside the lock: the setting, or the part, may have
1283            // changed since the look above.
1284            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            // The uses list travels with the document it describes.
1308            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            // As does what instructions instruct.
1314            revision.instructs = carried_revision.as_deref().and_then(|id| part.revision(id)).and_then(|r| r.instructs.clone());
1315            // So do its files: new references to the same blobs, so removing
1316            // one from the new revision never touches the old one.
1317            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            // And its picture, while it still pictures the carried document
1328            // (the same bytes are written below, so the hash still matches).
1329            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    /// Change a part's descriptive fields — `name`, `description`,
1346    /// `category`, `tags`, `external_ref` and `attributes`. The number, the
1347    /// type and the document class are identity and never change here.
1348    ///
1349    /// `attributes` MERGES: each key given is set (type-checked against the
1350    /// part's category, the new one if `category` changes in the same call),
1351    /// and a `null` clears it. Keys not mentioned are untouched — so moving a
1352    /// part to another category keeps the values the new schema lacks.
1353    ///
1354    /// This is the write behind `PATCH /api/parts/:id` and a script's
1355    /// `plm.updatePart`.
1356    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            // Borrow the parts and the tree separately: the part is written,
1383            // the tree is only read.
1384            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            // Judged on what CHANGED, not on which fields were sent: the edit
1402            // dialog re-sends every field, and renaming a released part must
1403            // not trip a lock on values it left alone.
1404            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
1418/// A family row and a template spin-out name their number and revision
1419/// themselves: the revision-label hook may refuse the label, but a hook that
1420/// RENAMES it would leave the table naming a revision that does not exist.
1421fn 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
1431/// A document still waiting for its bake cannot release: once released its
1432/// bytes are frozen, and the bake could never be written.
1433fn 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
1445/// The refusal [`Settings::allow_multiple_open_drafts`] = off gives.
1446fn 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    /// The administrator's settings as they stand.
1455    pub fn settings(&self) -> Settings {
1456        self.read(|state| state.settings.clone())
1457    }
1458
1459    /// Change settings. `fields` MERGES: each key given is set, the rest are
1460    /// untouched. An unknown key or a value of the wrong type is refused
1461    /// rather than ignored, so a typo in an admin's request cannot silently
1462    /// leave a policy where it was.
1463    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            // The review rules name users, groups, part types and categories:
1493            // checked against the store as it is at the write.
1494            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
1503/// The body of [`Db::update_part`], inside its lock. `categories` is the tree
1504/// as it is at the write.
1505fn 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    // After the category, so a move and the new category's values can land in
1537    // one call.
1538    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
1553/// The category id to store for `requested`: empty for none, else the id of
1554/// an existing category (the text may differ in case). A category that does
1555/// not exist is refused rather than stored as free text, so a typo cannot
1556/// quietly file a part nowhere.
1557fn 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/// What a parts listing is narrowed to. Every field is optional; empty means
1568/// "no constraint".
1569#[derive(Debug, Clone, Default)]
1570pub struct PartFilter {
1571    /// Text matched against the number, name, description, category name,
1572    /// tags, attribute values, and every MPN and SPN.
1573    pub q: String,
1574    /// A category id: the parts in it AND in every category beneath it.
1575    /// [`UNCATEGORIZED`] selects the parts without a category.
1576    pub category: String,
1577    /// A tag, matched whole and without regard to case.
1578    pub tag: String,
1579    /// A manufacturer, by id or name: the parts with a manufacturer part
1580    /// from it.
1581    pub manufacturer: String,
1582    /// A supplier, by id or name: the parts with an offer from it.
1583    pub supplier: String,
1584    /// Catalog attribute conditions, all of which a part must meet
1585    /// ([`AttributeFilter`]).
1586    pub attributes: Vec<AttributeFilter>,
1587    /// An external reference, matched exactly (a library import's lookup).
1588    pub external_ref: String,
1589    /// A part type id, matched exactly.
1590    pub part_type: String,
1591}
1592
1593/// One attribute condition of a parts listing (`attr.<key>=…`,
1594/// `attr.<key>.min=…`, `attr.<key>.max=…`), as the caller typed it. It is
1595/// read against the attribute's type in the catalog ([`attribute_matchers`]).
1596#[derive(Debug, Clone, Default, PartialEq)]
1597pub struct AttributeFilter {
1598    pub key: String,
1599    /// The part's value must equal one of these (any of); empty: any value.
1600    pub values: Vec<String>,
1601    /// Inclusive bounds, for a number attribute.
1602    pub min: Option<String>,
1603    pub max: Option<String>,
1604}
1605
1606impl AttributeFilter {
1607    /// The conditions in a query string's `attr.*` pairs, merged per key in
1608    /// the order they first appear. Anything after `attr.<key>` other than
1609    /// `.min` or `.max` is refused. Other pairs are ignored.
1610    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                    // An attribute key has no dots (catalog::usable_key), so
1619                    // anything after one is a suffix, and only two exist.
1620                    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/// An [`AttributeFilter`] read against the catalog: its type, its values in
1649/// the canonical form they are stored in, its bounds as numbers.
1650#[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
1678/// Read `filter`'s attribute conditions against the catalog, or say why they
1679/// cannot be read (a `400`).
1680///
1681/// With a `category` the key must be in that category's effective schema.
1682/// Without one it must be defined by some category, and every category that
1683/// defines it must agree on its type — else the caller is told to narrow by
1684/// category. A value is read as the catalog reads form text
1685/// ([`catalog::check_value`]), so `12.5`, `yes` and an enum value in any case
1686/// all work; `min` and `max` are for numbers only.
1687pub 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            // An enum's values may differ between the categories that define
1732            // the key: a value any of them lists is accepted.
1733            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/// One page of a parts listing ([`Db::find_parts_page`]).
1782#[derive(Debug, Default)]
1783pub struct PartPage {
1784    pub parts: Vec<Part>,
1785    /// The cursor for the next page, or `None` when this is the last.
1786    pub next: Option<String>,
1787    cursors: Vec<i64>,
1788}
1789
1790impl PartPage {
1791    /// Trim a page collected one past `limit`, and set its cursor.
1792    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
1803/// A [`PartFilter`] resolved against the store: the exact rules a part must
1804/// pass, whichever way the candidates were found.
1805struct Matcher {
1806    needle: String,
1807    tag: String,
1808    /// The category ids (lower-case) a part must be in; `Some(empty)` with
1809    /// `uncategorized` for "without a category".
1810    within: Option<BTreeSet<String>>,
1811    uncategorized: bool,
1812    /// `Some(None)`: the filter names a company that does not exist, which
1813    /// matches nothing rather than silently widening to everything.
1814    manufacturer: Option<Option<String>>,
1815    supplier: Option<Option<String>>,
1816    external_ref: String,
1817    part_type: String,
1818    /// The attribute conditions, read; `None` when they could not be read,
1819    /// which matches nothing (the route refuses such a filter with a 400
1820    /// before it gets here).
1821    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    /// A filter no part can pass: it names a company that does not exist,
1852    /// or attribute conditions that do not read.
1853    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
1880/// The `category` filter value that selects parts without a category —
1881/// an empty category.
1882pub const UNCATEGORIZED: &str = "_none";
1883
1884impl Db {
1885    /// Search parts by number, name, category or tag — what a script's
1886    /// `plm.findParts` asks.
1887    pub fn search_parts(&self, query: &str) -> Vec<Part> {
1888        self.find_parts(&PartFilter { q: query.to_string(), ..PartFilter::default() })
1889    }
1890
1891    /// The parts that pass `filter`, in creation order.
1892    pub fn find_parts(&self, filter: &PartFilter) -> Vec<Part> {
1893        self.find_parts_page(filter, None, None).parts
1894    }
1895
1896    /// One page of the parts that pass `filter`, in creation order: at most
1897    /// `limit`, continuing after the cursor `after` (a [`PartPage::next`]).
1898    ///
1899    /// The SQLite side narrows ([`crate::sql::Sql::candidates`]): the trigram
1900    /// index finds the parts whose searchable text contains the search text,
1901    /// and indexed columns apply the category, tag and company filters. Every
1902    /// candidate is then checked against the in-memory part with the exact
1903    /// rules below, so the answer is the one the rules give — the index only
1904    /// decides how few parts are looked at. Search text shorter than three
1905    /// characters (the trigram minimum) narrows nothing and is checked on
1906    /// every part the other filters leave. Should the index fail, the answer
1907    /// comes from a scan of memory rather than an error.
1908    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        // An exact external reference picks one part, or a handful: a walk of
1916        // memory finds it without paging through the index 256 rows at a time.
1917        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        // One more than the page, to know whether there IS a next page.
1937        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    /// [`Db::find_parts`] by a scan of memory alone, with no index — what the
1993    /// index's answers are checked against.
1994    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    /// Take the lock on a draft revision.
2003    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                // The same user re-taking their own lock from another client
2028                // is a no-op that re-stamps which client holds it.
2029            }
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    /// Release the lock. `force` is the BREAK path and requires the check-in
2041    /// group; without it only the holder may check in.
2042    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    /// Move a revision's lifecycle state, applying the rules in
2075    /// [`crate::lifecycle`] and the automatic supersede.
2076    ///
2077    /// A release runs two hooks when their files exist. `beforeRelease` runs
2078    /// first, outside the store lock, and a throw refuses the release; the
2079    /// locked write then re-checks that the revision's bytes are the ones the
2080    /// hook saw. `afterRelease` runs once the release is committed: it cannot
2081    /// undo it, so its failure comes back as a WARNING, the release standing.
2082    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        // Retiring a released revision from every new use is the release
2116        // authority's decision too.
2117        if to == Lifecycle::Obsolete && !user.can_checkin() {
2118            return Err(Error::forbidden("making a revision obsolete needs the check-in group"));
2119        }
2120        // Submitting for review and pulling back from it are an author's work.
2121        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        // Submitting opens a review round ([`crate::review`]).
2125        if to == Lifecycle::InReview {
2126            return self.submit_for_review(user, part_id, revision_id, &crate::review::Submission::default());
2127        }
2128
2129        // The before-release gate, on a snapshot. Refusals the locked write
2130        // would make anyway are made first, so a script is never asked about
2131        // a release that cannot happen.
2132        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        // Who uses the revision as it stands, for the warning an obsolete
2161        // revision answers with (it is still used; nothing refuses).
2162        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                // Again INSIDE the lock: the part's values or its category's
2178                // schema may have changed while the hook ran.
2179                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            // Pulling a revision out of review ends its round.
2191            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            // The automatic supersede: every OTHER released revision of this
2222            // part steps down. Applied here so no caller can release without
2223            // it.
2224            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            // With the gate off the release stands, and says what it did not
2250            // wait for.
2251            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    /// A copy of one part and one of its revisions, for a hook to read.
2274    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    /// Delete a draft revision outright — the only removal this server allows.
2285    /// A released revision is never deleted; it is obsoleted.
2286    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            // A revision another list pins cannot go: that list would name
2313            // nothing.
2314            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    /// The keys that changed since `since`, and whether the log still reaches
2336    /// that far back.
2337    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// ===========================================================================
2354// The catalog tree
2355// ===========================================================================
2356
2357/// What a category is made from, or changed to. On a change, `None` leaves a
2358/// field as it is.
2359#[derive(Debug, Clone, Default)]
2360pub struct CategoryChange {
2361    pub name: Option<String>,
2362    /// `Some("")` moves the category to the top level.
2363    pub parent: Option<String>,
2364    /// Replaces the category's OWN attribute list.
2365    pub attributes: Option<Vec<AttributeDef>>,
2366}
2367
2368impl Db {
2369    /// Add a category. The whole tree is re-checked inside the write
2370    /// ([`catalog::check_tree`]), so a parent that vanished meanwhile or a
2371    /// key an ancestor gained meanwhile is caught there.
2372    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    /// Rename a category, move it, or replace its own attributes.
2399    ///
2400    /// Changing an attribute's type, or dropping one, leaves the values parts
2401    /// already hold where they are: a value that no longer fits is reported
2402    /// at the next release of that part, and a value whose key is gone is
2403    /// inert. Nothing is rewritten behind anyone's back.
2404    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            // A cycle, a too-deep chain, or a key now defined twice along a
2434            // chain — in EITHER direction — is refused here, and the mutation
2435            // rolls back.
2436            catalog::check_tree(&state.categories)?;
2437            Ok(state.categories[index].clone())
2438        })
2439    }
2440
2441    /// Remove a category that nothing uses. A category with children, or with
2442    /// any part filed in it, is refused: deleting it would silently re-file
2443    /// those parts as uncategorized.
2444    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
2474/// Whether `needle` (lower-case) appears in anything a person would search a
2475/// part by.
2476fn 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
2492/// Refuse a release whose part is missing a required attribute, or holds a
2493/// value its category's schema no longer accepts. Every problem is named at
2494/// once, so a user fixes them in one pass.
2495fn 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
2507/// A revision whose review rule is not met cannot release ([`crate::review`]).
2508fn 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
2513/// The assembly revision an instructions document instructs: its
2514/// `instructions.target.sourceKey`, when that names a PLM revision that exists
2515/// and is not itself instructions. A local file's key is no reference.
2516pub 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
2524/// Instructions release for a released assembly revision, only once the
2525/// author approved a re-target (the document's `instructions.retarget` is
2526/// clear), and only with current player data: made by the CAD app from the
2527/// document the revision holds ([`crate::player`]), so the released player
2528/// shows what was released.
2529fn 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
2571/// The first revision whose uses list pins `revision_id` of `part_id`, as
2572/// "number" and "label".
2573fn 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
2588/// The direct users of `revision_id` of `part_id` (pinned, or floating to it
2589/// now), each as `<number> rev <label> (<state>)`, in store order, each once.
2590fn 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
2603/// `names` for a sentence: at most [`NAMED_AT_MOST`], then how many more.
2604pub(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
2612/// How many users a refusal or warning names before "and N more".
2613const NAMED_AT_MOST: usize = 10;
2614
2615/// The two conditions a revision's document and uses list are written under,
2616/// checked together so the refusal says which one failed: the revision is in
2617/// work, and `user` holds its lock.
2618pub 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    /// Replace a revision's uses list — the call the CAD app makes on save,
2652    /// and the web page's stand-in until it does. Written under the same two
2653    /// conditions as the document ([`check_writable`]), so a released
2654    /// revision's list never changes; checked by [`bom::check_uses`] inside
2655    /// the same lock, so no two concurrent writes can close a cycle between
2656    /// them.
2657    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
2675/// What the release hooks receive.
2676pub(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
2688/// Whether any part already carries `number` (ASCII case ignored).
2689fn state_has_number(parts: &[Part], number: &str) -> bool {
2690    parts.iter().any(|p| p.number.eq_ignore_ascii_case(number))
2691}
2692
2693/// An admin's pattern, anchored so it must match the WHOLE number: a pattern
2694/// of `\d{5}` should not accept `ABC12345XYZ`.
2695pub 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
2700/// The longest part number or revision label the store accepts.
2701pub const MAX_IDENTIFIER: usize = 64;
2702
2703/// A number is text a person can read aloud and type back: not empty, not
2704/// padded, no control characters, and short enough to print on a label.
2705pub fn check_number(number: &str) -> Result<(), Error> {
2706    check_identifier(number, "a part number")
2707}
2708
2709/// A label follows the same rule as a number.
2710pub 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
2730/// The label offered for a part's next revision: the one after the newest
2731/// revision's, skipping any the part already has. Free-text labels can be
2732/// anything, so the walk may restart at `A`; skipping taken labels is what
2733/// keeps the suggestion usable.
2734pub 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/// What a new part is made from. Empty `number` lets the type decide (a
2743/// counter) or leaves it to the script; empty `label` takes the suggestion.
2744#[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    /// Attribute values, checked against the category's schema. A draft may
2755    /// leave required ones out; the release gate asks for them.
2756    pub attributes: serde_json::Map<String, Value>,
2757    /// Use `number` and `label` as typed: a script may refuse them but not
2758    /// change them. A family row names its member's number and revision.
2759    pub exact: bool,
2760    /// Where the part comes from in another system (a KiCad `library_id`).
2761    /// Unique among parts of the same type ([`external_ref_clash`]).
2762    pub external_ref: String,
2763    /// The first revision's origin: authored, or imported by a library
2764    /// import. Generated is Generate's alone.
2765    pub origin: crate::model::Origin,
2766    /// Link the new part into its creator's workspace, in this folder (empty:
2767    /// the top), in the same transaction as the part. `None` links nothing.
2768    /// Only [`crate::workspace::link_on_create`] decides it.
2769    pub workspace: Option<String>,
2770}
2771
2772/// The refusal for giving a part of type `part_type` the external reference
2773/// `external_ref` when another part of that type already has it — checked
2774/// inside the store's write lock, so two imports of one library entry at
2775/// once cannot both make a part. `except` is the part being edited. An empty
2776/// reference never clashes.
2777pub 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
2790/// Refuse `origin: generated` from a caller: only Generate makes those.
2791pub 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
2798/// Find a revision for mutation, reporting which half was missing.
2799pub(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