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    pub workflows: Vec<crate::workflow::Definition>,
82    pub workflow_runs: Vec<crate::workflow::Run>,
83    pub bom_configuration: crate::bom_config::Configuration,
84    pub seq: u64,
85    pub users: Vec<User>,
86    /// Browser sessions, journaled ([`crate::journal`]): one is added per
87    /// sign-in, so this grows with use, and a list outside a journal costs
88    /// every write O(its length).
89    // Stored separately from the metadata snapshot and restored after decoding it.
90    #[serde(default)]
91    pub sessions: crate::journal::Journaled<Session>,
92    /// Bearer tokens for callers that are not a browser ([`ApiToken`]).
93    pub api_tokens: Vec<ApiToken>,
94    pub part_types: Vec<PartType>,
95    // Stored separately from the metadata snapshot and restored after decoding it.
96    #[serde(default)]
97    pub parts: Parts,
98    /// The catalog tree, flat: each category names its parent.
99    pub categories: Vec<Category>,
100    /// Who makes parts ([`Company`]); a manufacturer part names one.
101    pub manufacturers: Vec<Company>,
102    /// Who sells parts ([`Company`]); a supplier offer names one.
103    pub suppliers: Vec<Company>,
104    /// The administrator's policy choices ([`Settings`]).
105    pub settings: Settings,
106    pub changes: Vec<Change>,
107    /// The lowest sequence the change log can still answer for completely.
108    /// It moves only when [`CHANGE_LOG_LIMIT`] forces entries out, so a
109    /// client is told `stale` when the log has actually DROPPED something it
110    /// needed — not merely because nothing happened at the sequence it asked
111    /// from, which is the ordinary case for a client that has been idle.
112    pub changes_from: u64,
113    /// Every user's workspace entries ([`crate::model::WorkspaceEntry`]),
114    /// in creation order.
115    // Stored separately from the metadata snapshot and restored after decoding it.
116    #[serde(default)]
117    pub workspace: crate::workspace::Workspace,
118}
119
120impl State {
121    /// Record that every revision of `part_id` moved: a lock, a lifecycle or
122    /// a supersede changes the store index's rows for them (`locked_by`,
123    /// `lifecycle`, `editable`) without writing a document, and the change
124    /// feed has to name them so a client can re-read exactly those rows
125    /// (`GET /api/store/index?keys=`) instead of the whole index.
126    pub(crate) fn touch_part(&mut self, part_id: &str) {
127        let keys: Vec<String> = self
128            .part(part_id)
129            .map(|part| part.revisions.iter().map(|r| r.document_key(&part.id)).collect())
130            .unwrap_or_default();
131        for key in keys {
132            self.touch(key);
133        }
134    }
135
136    /// Record that `key`'s document moved at the current sequence. Called
137    /// inside a mutation, AFTER [`Db::mutate`] has bumped `seq`.
138    pub(crate) fn touch(&mut self, key: String) {
139        let seq = self.seq;
140        self.changes.retain(|change| change.key != key);
141        self.changes.push(Change { seq, key });
142        if self.changes.len() > CHANGE_LOG_LIMIT {
143            let excess = self.changes.len() - CHANGE_LOG_LIMIT;
144            let dropped: Vec<Change> = self.changes.drain(..excess).collect();
145            if let Some(last) = dropped.last() {
146                self.changes_from = self.changes_from.max(last.seq);
147            }
148        }
149    }
150
151    pub fn user(&self, id: &str) -> Option<&User> {
152        self.users.iter().find(|u| u.id == id)
153    }
154
155    pub fn user_by_name(&self, username: &str) -> Option<&User> {
156        let username = username.trim().to_ascii_lowercase();
157        self.users
158            .iter()
159            .find(|u| u.username.to_ascii_lowercase() == username)
160    }
161
162    pub fn part(&self, id: &str) -> Option<&Part> {
163        self.parts.get(id)
164    }
165
166    pub fn part_type(&self, id: &str) -> Option<&PartType> {
167        self.part_types.iter().find(|t| t.id == id)
168    }
169
170    /// A part by its id, or else by its number.
171    pub fn part_by_id_or_number(&self, key: &str) -> Option<&Part> {
172        let key = key.trim();
173        self.part(key).or_else(|| self.part_with_number(key))
174    }
175
176    /// The part that already carries `number`, compared without regard to
177    /// ASCII case. A part number is unique across ALL parts, whatever type
178    /// made it: it is what an ERP, a BOM and a person reading a drawing
179    /// use to mean exactly one part.
180    pub fn part_with_number(&self, number: &str) -> Option<&Part> {
181        let number = number.trim();
182        self.parts.iter().find(|p| p.number.eq_ignore_ascii_case(number))
183    }
184
185    /// The oldest sequence the change log can still answer for completely.
186    /// A client asking from before this is told `stale` and must re-index.
187    pub fn changes_floor(&self) -> u64 {
188        self.changes_from
189    }
190}
191
192/// The server's whole persistent state: the metadata under one lock (and in
193/// SQLite), the document tree beside it, and the administrator's scripts.
194///
195/// A `Db` is a HANDLE: cloning it is cheap and every clone is the same store.
196/// That is what lets a script's `plm.*` bindings hold the store for the length
197/// of one hook call.
198#[derive(Clone)]
199pub struct Db {
200    root: PathBuf,
201    state: Arc<RwLock<State>>,
202    scripts: Arc<Scripts>,
203    security: Arc<Security>,
204    /// The metadata on disk, and the audit log and search index with it.
205    sql: Arc<Sql>,
206    /// This process's hold on the data directory ([`crate::dirlock`]), for as
207    /// long as any handle to the store is alive.
208    _lock: Arc<crate::dirlock::DirLock>,
209    /// The last backup this process took, and whether one is running.
210    backups: Arc<crate::backup::Status>,
211    pub(crate) bake_worker: Arc<crate::bake_worker::Controller>,
212}
213
214/// Whole seconds since the epoch.
215pub fn now() -> Timestamp {
216    std::time::SystemTime::now()
217        .duration_since(std::time::UNIX_EPOCH)
218        .map(|d| d.as_secs())
219        .unwrap_or(0)
220}
221
222impl Db {
223    /// Open (or create) the store at `root`.
224    ///
225    /// Returns the generated administrator password when — and only when —
226    /// this call seeded the first account. It is printed once at boot and
227    /// never recoverable, which is the point: no build of this server ships a
228    /// known password.
229    pub fn open(root: impl Into<PathBuf>) -> io::Result<(Self, Option<String>)> {
230        Self::open_with_scripts(root, None)
231    }
232
233    /// [`Db::open`], with the scripts directory somewhere other than
234    /// `<root>/scripts` — typically a git checkout the administrator manages.
235    /// This is the path `serve` opens with, always at [`Durability::Full`].
236    pub fn open_with_scripts(
237        root: impl Into<PathBuf>,
238        scripts: Option<PathBuf>,
239    ) -> io::Result<(Self, Option<String>)> {
240        Self::open_with(root, scripts, Durability::Full)
241    }
242
243    /// [`Db::open_with_scripts`] at a chosen [`Durability`]. The test suites
244    /// open with [`Durability::Normal`]; the server never does.
245    pub fn open_with(
246        root: impl Into<PathBuf>,
247        scripts: Option<PathBuf>,
248        durability: Durability,
249    ) -> io::Result<(Self, Option<String>)> {
250        let root = root.into();
251        // First, before anything in the directory is read or moved: two
252        // servers on one directory would each hold their own copy of the
253        // metadata and overwrite each other's changes.
254        let lock = crate::dirlock::DirLock::acquire(&root)?;
255        fs::create_dir_all(root.join("models"))?;
256        let scripts = Scripts::new(scripts.unwrap_or_else(|| root.join("scripts")))?;
257        let sql = Sql::open_with(root.join(SQLITE_FILE), durability).map_err(io::Error::other)?;
258        let loaded = sql.load().map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
259        let fresh = loaded.is_none();
260        let mut state = loaded.unwrap_or_default();
261        if state.parts.iter().any(|p| p.id != p.number || p.revisions.iter().any(|r| r.id != r.label)) {
262            return Err(io::Error::new(io::ErrorKind::InvalidData,
263                "part and revision identities must match their current number and label"));
264        }
265        let before = sql::small_value(&mut state);
266
267        let mut seeded = None;
268        if state.part_types.is_empty() {
269            // The DEFAULT, not the rule: prefix and width are data from here
270            // on, and an operator adds more types through the API.
271            state.part_types.push(PartType {
272                id: "component".into(),
273                name: "Component".into(),
274                prefix: "CPART".into(),
275                digits: 9,
276                next: 1,
277                created_at: now(),
278                mode: Default::default(),
279            });
280        }
281        if state.users.is_empty() {
282            let password = auth::random_token(12);
283            state.users.push(User {
284                id: auth::new_id(),
285                username: "admin".into(),
286                display_name: "Administrator".into(),
287                email: String::new(),
288                password: auth::hash_password(&password),
289                groups: vec![groups::ADMIN.into()],
290                active: true,
291                created_at: now(),
292            });
293            seeded = Some(password);
294        }
295        let after = sql::small_value(&mut state);
296        if fresh || before != after {
297            let change = sql::Change {
298                before: &if fresh { Value::Object(Default::default()) } else { before },
299                after: &after,
300                parts: Vec::new(),
301                categories: &state.categories,
302                reindex: Vec::new(),
303                all_parts: &state.parts,
304                workspace: Vec::new(),
305                sessions: Vec::new(),
306            };
307            sql.write(&change, Vec::new()).map_err(io::Error::other)?;
308        }
309
310        let db = Db {
311            root,
312            state: Arc::new(RwLock::new(state)),
313            scripts: Arc::new(scripts),
314            security: Arc::new(Security::default()),
315            sql: Arc::new(sql),
316            _lock: Arc::new(lock),
317            backups: Arc::new(crate::backup::Status::default()),
318            bake_worker: Arc::new(crate::bake_worker::Controller::default()),
319        };
320        // What a crash between an upload's move and its commit can leave:
321        // nothing else is running yet, and the directory is ours alone.
322        match db.sweep_blobs() {
323            Ok(0) => {}
324            Ok(n) => eprintln!("brep-plm: removed {n} unreferenced attachment file(s)"),
325            Err(error) => eprintln!("brep-plm: could not sweep attachment files: {error}"),
326        }
327        db.recover_workflows().map_err(io::Error::other)?;
328        Ok((db, seeded))
329    }
330
331
332
333    /// The administrator's scripts directory.
334    /// The data directory.
335    pub fn root(&self) -> &Path {
336        &self.root
337    }
338
339    /// Stop only the child owned by this server, including on shutdown.
340    pub fn stop_bake_worker(&self) -> Result<crate::bake_worker::Status, Error> {
341        self.bake_worker.stop(self.security.config.bake_worker.as_ref())
342    }
343
344    pub fn scripts(&self) -> &Scripts {
345        &self.scripts
346    }
347
348    /// This store with the network-facing configuration `config`. Called once,
349    /// at start-up, before the store is shared; the throttle starts empty.
350    pub fn with_config(mut self, config: ServerConfig) -> Self {
351        self.security = Arc::new(Security { config, ..Security::default() });
352        self
353    }
354
355    /// The last backup this process took.
356    pub fn backups(&self) -> &crate::backup::Status {
357        &self.backups
358    }
359
360    /// The hardening layer: configuration and the sign-in throttle.
361    pub fn security(&self) -> &Security {
362        &self.security
363    }
364
365    /// Whether administrators may edit and test-run scripts in the browser:
366    /// the setting, unless `--lock-script-editor` forces it off.
367    pub fn script_editor_allowed(&self) -> bool {
368        !self.security.config.lock_script_editor && self.read(|state| state.settings.script_editor_enabled)
369    }
370
371    /// Read the metadata under the shared lock.
372    pub fn read<R>(&self, f: impl FnOnce(&State) -> R) -> R {
373        let state = self.state.read().unwrap_or_else(|e| e.into_inner());
374        f(&state)
375    }
376
377    /// Mutate the metadata under the exclusive lock, bump the sequence, and
378    /// PERSIST before returning.
379    ///
380    /// Persisting inside the guard is what makes number allocation safe: two
381    /// concurrent part creations serialize on this lock, and neither response
382    /// is sent until the number it handed out is committed. A closure that
383    /// returns `Err` leaves the state untouched: the parts it touched are put
384    /// back from the journal ([`Parts`]) and every other field from the copy
385    /// taken before it ran. The same happens when the write to disk fails —
386    /// a UNIQUE constraint the closure's own check missed, a full disk.
387    ///
388    /// The change's audit events ([`crate::audit`]) are computed from exactly
389    /// what it touched and committed in the SAME transaction as the change, so
390    /// a change is never on disk without its events, nor an event without its
391    /// change. Every write path goes through here, so every change is logged
392    /// without any of them asking.
393    pub fn mutate<R>(&self, f: impl FnOnce(&mut State) -> Result<R, Error>) -> Result<R, Error> {
394        let mut state = self.state.write().unwrap_or_else(|e| e.into_inner());
395        let before = sql::small_value(&mut state);
396        state.parts.begin();
397        state.workspace.begin();
398        state.sessions.begin();
399        state.seq += 1;
400        match f(&mut state) {
401            Ok(value) => {
402                let touched = state.parts.commit();
403                let entries = state.workspace.commit();
404                let sessions = state.sessions.commit();
405                match self.persist(&mut state, &before, &touched, &entries, &sessions) {
406                    Ok(()) => Ok(value),
407                    Err(error) => {
408                        state.parts.undo(touched);
409                        state.workspace.undo(entries);
410                        state.sessions.undo(sessions);
411                        restore_small(&mut state, &before)?;
412                        Err(error)
413                    }
414                }
415            }
416            Err(error) => {
417                state.parts.rollback();
418                state.workspace.rollback();
419                state.sessions.rollback();
420                restore_small(&mut state, &before)?;
421                Err(error)
422            }
423        }
424    }
425
426    /// Write one committed change and its audit events in one transaction.
427    fn persist(
428        &self,
429        state: &mut State,
430        before: &Value,
431        touched: &[crate::table::Touched],
432        entries: &[crate::journal::Touched<crate::model::WorkspaceEntry>],
433        sessions: &[crate::journal::Touched<Session>],
434    ) -> Result<(), Error> {
435        let after = sql::small_value(state);
436        // A part a change borrowed mutably but did not actually change is
437        // neither written nor audited.
438        let mut old_parts = Vec::new();
439        let mut new_parts = Vec::new();
440        let mut changed = Vec::new();
441        for t in touched {
442            let now_part = &state.parts[t.position];
443            let now_value = serde_json::to_value(now_part).map_err(Error::internal)?;
444            let was_value = match &t.before {
445                Some(part) => Some(serde_json::to_value(part).map_err(Error::internal)?),
446                None => None,
447            };
448            if was_value.as_ref() == Some(&now_value) {
449                continue;
450            }
451            old_parts.extend(was_value);
452            new_parts.push(now_value);
453            changed.push((t.position, now_part));
454        }
455        // The journaled lists the same way: only what was touched, and only
456        // what actually changed, is written and audited.
457        let (old_entries, new_entries, workspace) = journal_rows(&state.workspace, entries)?;
458        let (old_sessions, new_sessions, session_rows) = journal_rows(&state.sessions, sessions)?;
459        let mut old = before.clone();
460        let mut new = after.clone();
461        if let (Some(o), Some(n)) = (old.as_object_mut(), new.as_object_mut()) {
462            o.insert("parts".into(), Value::Array(old_parts));
463            n.insert("parts".into(), Value::Array(new_parts));
464            o.insert("workspace".into(), Value::Array(old_entries));
465            n.insert("workspace".into(), Value::Array(new_entries));
466            o.insert("sessions".into(), Value::Array(old_sessions));
467            n.insert("sessions".into(), Value::Array(new_sessions));
468        }
469        let events = audit::refine(audit::diff(&old, &new, &audit::current_actor(), now(), state.seq));
470        // A part's search row holds its category's PATH ("Fasteners /
471        // Screws"): re-index the parts whose category's path the change moved
472        // — a rename, a move, a category created for text a part already had.
473        let mut reindex = Vec::new();
474        if before.get("categories") != after.get("categories") {
475            let old_categories: Vec<Category> =
476                serde_json::from_value(before.get("categories").cloned().unwrap_or_default()).unwrap_or_default();
477            let moved: BTreeSet<String> = old_categories
478                .iter()
479                .chain(state.categories.iter())
480                .map(|c| c.id.to_ascii_lowercase())
481                .filter(|id| catalog::path_name(&old_categories, id) != catalog::path_name(&state.categories, id))
482                .collect();
483            reindex = state
484                .parts
485                .iter()
486                .enumerate()
487                .filter(|(_, p)| moved.contains(&p.category.to_ascii_lowercase()))
488                .map(|(i, _)| i)
489                .collect();
490        }
491        let change = sql::Change {
492            before,
493            after: &after,
494            parts: changed,
495            categories: &state.categories,
496            reindex,
497            all_parts: &state.parts,
498            workspace,
499            sessions: session_rows,
500        };
501        self.sql.write(&change, events).map(|_| ()).map_err(|error| {
502            if sql::is_constraint(&error) {
503                Error::conflict(format!("the store refused the change: {error}"))
504            } else {
505                Error::internal(error)
506            }
507        })
508    }
509
510    /// Record an event that is not a change to the store: a failed sign-in, a
511    /// script file edited or run in the browser.
512    pub fn record(&self, action: &str, entity: EntityRef, detail: impl Into<String>) {
513        let event = AuditEvent {
514            id: 0,
515            at: now(),
516            actor: audit::current_actor(),
517            action: action.to_string(),
518            entity,
519            changes: BTreeMap::new(),
520            detail: detail.into(),
521            seq: 0,
522        };
523        if let Err(error) = self.sql.append(vec![event]) {
524            eprintln!("brep-plm: audit: could not append to the log: {error}");
525        }
526    }
527
528    /// Audit events matching `filter`, newest first.
529    pub fn audit_query(&self, filter: &AuditFilter) -> Result<Vec<AuditEvent>, Error> {
530        self.sql.query(filter).map_err(Error::internal)
531    }
532
533    /// The SQLite store, for the search index and diagnostics.
534    pub fn sql(&self) -> &Sql {
535        &self.sql
536    }
537
538    // -- documents ---------------------------------------------------------
539
540    pub(crate) fn document_path(&self, key: &str) -> Result<PathBuf, Error> {
541        let (part, revision) = crate::identity::split_key(key)
542            .ok_or_else(|| Error::bad_request(format!("'{key}' is not a usable document key")))?;
543        Ok(self.root.join(crate::identity::model_path(&part, &revision)))
544    }
545
546    /// One document's text, or `None` when it has never been written.
547    pub fn read_document(&self, key: &str) -> Result<Option<String>, Error> {
548        let path = self.document_path(key)?;
549        match fs::read_to_string(path) {
550            Ok(text) => Ok(Some(text)),
551            Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None),
552            Err(error) => Err(Error::internal(error)),
553        }
554    }
555
556    /// Write a document and record its hash on the revision.
557    ///
558    /// The editable check is HERE, not only in the API layer: this is the one
559    /// function that can change a revision's bytes, so it is the one that has
560    /// to refuse a released revision. A guard that lives only in the handler
561    /// is a guard that the next caller forgets.
562    ///
563    /// Everything happens inside one [`Db::mutate`], which is what makes the
564    /// check race-free — a release landing between a separate check and the
565    /// write would otherwise rewrite released bytes. Within the guard the file
566    /// still lands BEFORE the metadata that describes it, so a crash between
567    /// the two leaves a document whose hash is not yet recorded, rather than a
568    /// recorded hash for bytes that do not exist.
569    pub fn write_document(&self, part_id: &str, revision_id: &str, body: &str) -> Result<u64, Error> {
570        self.write_document_inner(part_id, revision_id, body, None)
571    }
572
573    /// Import a reviewed document and its structure together. The expected
574    /// hash and checkout are checked under the write lock, so another save or
575    /// a broken checkout cannot silently replace the document reviewed by the user.
576    pub fn write_import_document(&self, user: &User, part_id: &str, revision_id: &str, expected_hash: &str, body: &str, uses: &Value) -> Result<u64, Error> {
577        self.write_document_inner(part_id, revision_id, body, Some((user, expected_hash, uses)))
578    }
579
580    fn write_document_inner(&self, part_id: &str, revision_id: &str, body: &str, import: Option<(&User, &str, &Value)>) -> Result<u64, Error> {
581        let key = crate::identity::document_key(part_id, revision_id);
582        let path = self.document_path(&key)?;
583        let hash = auth::content_hash(body);
584        let embedded = crate::thumbnail::embedded(self.root(), body)?;
585        let has_geometry = crate::geometry::contains_geometry(body);
586        self.mutate(move |state| {
587            let imported_uses = if let Some((user, expected, uses)) = import {
588                check_writable(state, user, part_id, revision_id)?;
589                let revision = state.part(part_id).and_then(|p| p.revision(revision_id))
590                    .ok_or_else(|| Error::not_found("revision"))?;
591                if revision.content_hash != expected {
592                    return Err(Error::conflict("the document changed since the import was reviewed; review it again"));
593                }
594                Some(bom::check_uses(state, part_id, uses)?)
595            } else { None };
596            let current = state.part(part_id).ok_or_else(|| Error::not_found("part"))?;
597            let defs = state.bom_configuration.part_fields.get(&current.part_type).cloned().unwrap_or_default();
598            let mut canonical = current.revision(revision_id).ok_or_else(|| Error::not_found("revision"))?.clone();
599            if let Ok(document) = serde_json::from_str::<Value>(body) {
600                if let Some(occurrences) = crate::bom_config::document_occurrences(&document) {
601                    if let Some(occurrences) = crate::bom_config::capture_occurrences(state, part_id, revision_id, &json!({"occurrences":occurrences}))? {
602                        canonical.occurrences = occurrences;
603                    }
604                }
605            }
606            let normalized = if !defs.is_empty() || !canonical.occurrences.is_empty() {
607                let mut document: Value = serde_json::from_str(body).map_err(|_| Error::bad_request("A CAD document must be JSON"))?;
608                let original = document.clone();
609                if !canonical.attributes_initialized && !defs.is_empty() {
610                    for def in &defs {
611                        if let Some(value) = document["partAttributes"].as_object().and_then(|attrs|attrs.iter().find(|(key,_)|key.to_ascii_lowercase()==def.key).map(|(_,value)|value)) {
612                            if let Some(value) = catalog::check_value(def, value).map_err(Error::bad_request)? {
613                                canonical.attributes.insert(def.key.clone(), value);
614                            }
615                        }
616                    }
617                    canonical.attributes_initialized = true;
618                }
619                crate::bom_config::overlay(&canonical, &defs, &mut document);
620                if document != original {Some(serde_json::to_string(&document).map_err(Error::internal)?)} else {None}
621            } else { None };
622            let body = normalized.as_deref().unwrap_or(body);
623            let hash = if normalized.is_some() { auth::content_hash(body) } else { hash };
624            let size = body.len() as u64;
625            let part = state.parts.get_mut(&part_id)
626                .ok_or_else(|| Error::not_found("part"))?;
627            let number = part.number.clone();
628            let revision = part
629                .revision_mut(revision_id)
630                .ok_or_else(|| Error::not_found("revision"))?;
631            if !revision.lifecycle.is_editable() {
632                return Err(Error::conflict(format!(
633                    "{number} revision {} is {} and cannot be written — start a new revision",
634                    revision.label,
635                    revision.lifecycle.as_str()
636                )));
637            }
638            if let Some(parent) = path.parent() {
639                fs::create_dir_all(parent).map_err(Error::internal)?;
640            }
641            let old_thumbnail = revision.thumbnail.as_ref().map(|t| t.sha256.clone());
642            let thumbnail = embedded.as_ref().map(|image| {
643                let user = import.map(|(user, _, _)| user.id.as_str())
644                    .or_else(|| revision.lock.as_ref().map(|lock| lock.user_id.as_str()))
645                    .unwrap_or(&revision.created_by);
646                image.place(self.root(), &hash, user)
647            }).transpose()?;
648            revision.attributes = canonical.attributes;
649            revision.attributes_initialized = canonical.attributes_initialized;
650            revision.occurrences = canonical.occurrences;
651            write_atomic(&path, body).map_err(Error::internal)?;
652            if let Some(thumbnail) = thumbnail { revision.thumbnail = Some(thumbnail); }
653            if let Some(uses) = imported_uses {
654                revision.uses = uses;
655            }
656            revision.has_geometry = has_geometry;
657            revision.geometry_content_hash = hash.clone();
658            revision.content_hash = hash;
659            revision.size = size;
660            revision.modified_at = now();
661            // A document someone SAVED supersedes a bake still waiting: the
662            // CAD app evaluated what it saved. A worker that had the job is
663            // refused when it reports back (see `Db::finish_bake`).
664            if revision.needs_bake() {
665                if let Some(bake) = revision.bake.as_mut() {
666                    bake.status = crate::model::BakeStatus::Done;
667                    bake.error = "superseded by a saved document".into();
668                    bake.finished_by = None;
669                    bake.finished_at = Some(now());
670                }
671            }
672            // Approvals given on the document before this save go stale (D8).
673            crate::review::document_changed(state, part_id, revision_id);
674            state.touch(key);
675            if embedded.is_some() {
676                if let Some(old) = old_thumbnail { crate::attach::remove_if_unreferenced(state, self.root(), &old)?; }
677            }
678            Ok(state.seq)
679        })
680    }
681
682    /// Remove a document's bytes. The revision record stays — a revision with
683    /// no document is a legitimate state (a part imported with no 3D model).
684    pub fn remove_document(&self, key: &str) -> Result<(), Error> {
685        let path = self.document_path(key)?;
686        match fs::remove_file(path) {
687            Ok(()) => Ok(()),
688            Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()),
689            Err(error) => Err(Error::internal(error)),
690        }
691    }
692}
693
694/// The metadata file in a data directory.
695pub const SQLITE_FILE: &str = "plm.sqlite";
696
697/// Put every field but the parts back as `before` had it.
698/// Whether `session` has ended by the settings' limits at `now`: idle for
699/// longer than `session_idle_minutes`, or signed in longer ago than
700/// `session_max_hours` (0: no such limit).
701pub fn session_expired(settings: &Settings, session: &Session, now: Timestamp) -> bool {
702    let idle = now.saturating_sub(session.last_seen) > settings.session_idle_minutes.saturating_mul(60);
703    let old = settings.session_max_hours > 0
704        && now.saturating_sub(session.created_at) > settings.session_max_hours.saturating_mul(3600);
705    idle || old
706}
707
708impl Db {
709    /// Remove every expired session ([`session_expired`]), as the system;
710    /// how many went.
711    ///
712    /// A session used to be removed only by signing out, or when its cookie
713    /// came back after it expired. A browser that simply stops sending the
714    /// cookie — it expired there, the user cleared it, a private window
715    /// closed — left its session in the store for good, and every sign-in
716    /// adds one: the list grew with use and nothing bounded it. This runs at
717    /// every sign-in — the only way the list grows — so it holds the sessions
718    /// that could still be used, plus whatever expired since the last
719    /// sign-in. Not at start-up: opening a store changes nothing in it (an
720    /// import or a restore opens exactly what it was given). Nothing is
721    /// written when nothing has expired.
722    pub fn prune_sessions(&self) -> Result<usize, Error> {
723        let at = now();
724        let expired = self.read(|state| state.sessions.iter().filter(|s| session_expired(&state.settings, s, at)).count());
725        if expired == 0 {
726            return Ok(0);
727        }
728        audit::as_actor(crate::model::Actor::system(), || {
729            self.mutate(move |state| {
730                let settings = state.settings.clone();
731                let before = state.sessions.len();
732                state.sessions.retain(|s| !session_expired(&settings, s, at));
733                Ok(before - state.sessions.len())
734            })
735        })
736    }
737}
738
739/// A journaled list's change as the audit and the store want it: the touched
740/// records before and after (only those that changed), and each changed key
741/// with what it is now (`None`: removed).
742#[allow(clippy::type_complexity)]
743fn journal_rows<'a, T>(
744    list: &'a crate::journal::Journaled<T>,
745    touched: &'a [crate::journal::Touched<T>],
746) -> Result<(Vec<Value>, Vec<Value>, Vec<(String, Option<&'a T>)>), Error>
747where
748    T: crate::journal::Keyed + Clone + PartialEq + Serialize,
749{
750    let mut old = Vec::new();
751    let mut new = Vec::new();
752    let mut rows = Vec::new();
753    for (t, now) in list.changed(touched) {
754        old.extend(t.before.as_ref().map(serde_json::to_value).transpose().map_err(Error::internal)?);
755        new.extend(now.map(serde_json::to_value).transpose().map_err(Error::internal)?);
756        rows.push((t.key.clone(), now));
757    }
758    Ok((old, new, rows))
759}
760
761fn restore_small(state: &mut State, before: &Value) -> Result<(), Error> {
762    let parts = std::mem::take(&mut state.parts);
763    let workspace = std::mem::take(&mut state.workspace);
764    let sessions = std::mem::take(&mut state.sessions);
765    *state = serde_json::from_value(before.clone()).map_err(Error::internal)?;
766    state.parts = parts;
767    state.workspace = workspace;
768    state.sessions = sessions;
769    Ok(())
770}
771
772/// Write `body` to `path` through a temporary file and a rename, so a reader
773/// never sees a partial file.
774pub(crate) fn write_atomic(path: &Path, body: &str) -> io::Result<()> {
775    let temp = path.with_extension("tmp");
776    fs::write(&temp, body)?;
777    fs::rename(&temp, path)
778}
779
780// ===========================================================================
781// Operations — the rules that are about MORE than one record
782// ===========================================================================
783
784impl Db {
785    /// Create a part of the default shape: the type decides the number, the
786    /// document is normal, the first revision takes the suggested label.
787    pub fn create_part(
788        &self,
789        author: &User,
790        part_type_id: &str,
791        name: &str,
792        description: &str,
793        category: &str,
794    ) -> Result<Part, Error> {
795        self.create_part_with(
796            author,
797            &PartSpec {
798                part_type: part_type_id.to_string(),
799                name: name.to_string(),
800                description: description.to_string(),
801                category: category.to_string(),
802                ..PartSpec::default()
803            },
804        )
805    }
806
807    /// Create a part with its first draft revision.
808    ///
809    /// The number comes from the type's [`NumberMode`]. A Script-mode type and
810    /// the revision-label hook are asked OUTSIDE the store lock, on a snapshot;
811    /// then one [`Db::mutate`] re-checks everything their answers depend on —
812    /// that the type's mode did not change meanwhile, and that the number and
813    /// label are still free. Two concurrent creates that a script gave the
814    /// same number therefore end as one part and one refusal, never two parts.
815    pub fn create_part_with(&self, author: &User, spec: &PartSpec) -> Result<Part, Error> {
816        check_origin(spec.origin)?;
817        let external_ref = spec.external_ref.trim().to_string();
818        let origin = spec.origin;
819        let name = spec.name.trim().to_string();
820        if name.is_empty() {
821            return Err(Error::bad_request("a part needs a name"));
822        }
823        let kind = self
824            .read(|state| state.part_type(&spec.part_type).cloned())
825            .ok_or_else(|| Error::bad_request(format!("no part type '{}'", spec.part_type)))?;
826        let typed = spec.number.trim().to_string();
827        let tags = catalog::tidy_tags(spec.tags.iter().cloned());
828        let part_view = json!({
829            "name": name,
830            "description": spec.description.trim(),
831            "category": spec.category.trim(),
832            "tags": tags,
833            "attributes": spec.attributes,
834            "document_class": spec.document_class,
835        });
836
837        let given: Option<String> = match &kind.mode {
838            NumberMode::Counter => {
839                if !typed.is_empty() {
840                    return Err(Error::bad_request(format!(
841                        "part type '{}' numbers by its counter — leave the number empty",
842                        kind.id
843                    )));
844                }
845                None
846            }
847            NumberMode::Free => {
848                if typed.is_empty() {
849                    return Err(Error::bad_request(format!(
850                        "part type '{}' takes the number you type — enter one",
851                        kind.id
852                    )));
853                }
854                Some(typed)
855            }
856            NumberMode::Pattern { regex } => {
857                let pattern = full_match(regex)?;
858                if typed.is_empty() {
859                    return Err(Error::bad_request(format!(
860                        "part type '{}' takes a typed number matching {regex} — enter one",
861                        kind.id
862                    )));
863                }
864                if !pattern.is_match(&typed) {
865                    return Err(Error::bad_request(format!(
866                        "'{typed}' does not match part type '{}' ({regex})",
867                        kind.id
868                    )));
869                }
870                Some(typed)
871            }
872            NumberMode::Script { script } => {
873                let input = json!({
874                    "requested": typed,
875                    "partType": kind,
876                    "part": part_view,
877                    "user": scripting::user_json(author),
878                });
879                let answer = match scripting::run(self, author, script, "partNumber", &input)? {
880                    HookResult::Absent => {
881                        return Err(Error::conflict(format!(
882                            "part type '{}' numbers by the script '{script}', which is not in the scripts directory",
883                            kind.id
884                        )))
885                    }
886                    HookResult::Refused(failure) => {
887                        return Err(Error::conflict(format!("{script}: {}", failure.message)))
888                    }
889                    HookResult::Returned(success) => success.value,
890                };
891                let number = scripting::string_answer(&answer, "number").ok_or_else(|| {
892                    Error::conflict(format!(
893                        "{script}: partNumber() must return the number, or {{ number }} — it returned {answer}"
894                    ))
895                })?;
896                if spec.exact && !number.eq_ignore_ascii_case(&typed) {
897                    return Err(Error::conflict(format!(
898                        "{script} would number it {number}, not {typed} — a family row names its own number"
899                    )));
900                }
901                Some(number)
902            }
903        };
904        if let Some(number) = &given {
905            check_number(number)?;
906        }
907
908        let requested_label = spec.label.trim().to_string();
909        let label = self.decide_label(author, None, &part_view, &requested_label, "A")?;
910        if spec.exact {
911            exact_label(&requested_label, &label)?;
912        }
913
914        let author_id = author.id.clone();
915        let document_class = spec.document_class;
916        let description = spec.description.trim().to_string();
917        let requested_category = spec.category.trim().to_string();
918        if spec.attributes.keys().any(|key| key.trim().eq_ignore_ascii_case("has_geometry")) {
919            return Err(Error::bad_request("has_geometry is derived from the saved model and cannot be edited"));
920        }
921        if spec.attributes.keys().any(|key| key.trim().eq_ignore_ascii_case("has_thumbnail")) {
922            return Err(Error::bad_request("has_thumbnail is derived from current thumbnails and cannot be edited"));
923        }
924        let requested_values = spec.attributes.clone();
925        let workspace = spec.workspace.clone();
926        self.mutate(move |state| {
927            // The category and the values are checked HERE, against the tree
928            // as it is at the write — an admin may be editing it meanwhile.
929            let category = known_category(&state.categories, &requested_category)?;
930            let mut attributes = BTreeMap::new();
931            catalog::apply_values(&state.categories, &category, &mut attributes, &requested_values)?;
932            let current = state
933                .part_types
934                .iter_mut()
935                .find(|t| t.id == kind.id)
936                .ok_or_else(|| Error::bad_request(format!("no part type '{}'", kind.id)))?;
937            if current.mode != kind.mode {
938                return Err(Error::conflict(format!(
939                    "part type '{}' changed its numbering while this part was being created — try again",
940                    kind.id
941                )));
942            }
943            let (number, sequence) = match given {
944                Some(number) => (number, 0),
945                None => {
946                    // The counter skips numbers another type already gave out:
947                    // a free-text or scripted number may land in its range.
948                    let mut sequence = current.next;
949                    let mut number = current.format_number(sequence);
950                    while sequence <= current.capacity()
951                        && state_has_number(&state.parts, &number)
952                    {
953                        sequence += 1;
954                        number = current.format_number(sequence);
955                    }
956                    if sequence > current.capacity() {
957                        return Err(Error::conflict(format!(
958                            "part type '{}' is exhausted: {} digits cannot spell {}",
959                            current.id, current.digits, sequence
960                        )));
961                    }
962                    current.next = sequence + 1;
963                    (number, sequence)
964                }
965            };
966            if let Some(owner) = state.part_with_number(&number) {
967                return Err(Error::conflict(format!(
968                    "part number {number} already exists ({})",
969                    owner.name
970                )));
971            }
972
973            external_ref_clash(state, &kind.id, &external_ref, "")?;
974            let stamp = now();
975            let mut revision = Revision::draft(label.clone(), label, author_id.clone(), stamp);
976            revision.origin = origin;
977            let part = Part {
978                id: number.clone(),
979                number,
980                part_type: kind.id.clone(),
981                sequence,
982                document_class,
983                name,
984                description,
985                category,
986                tags,
987                external_ref,
988                attributes,
989                sourcing: Vec::new(),
990                member_part_type: String::new(),
991                attachments: Vec::new(),
992                created_by: author_id,
993                created_at: stamp,
994                revisions: vec![revision],
995            };
996            state.parts.push(part.clone());
997            state.touch(part.revisions[0].document_key(&part.id));
998            if let Some(folder) = &workspace {
999                crate::workspace::link_new_part(state, &part.created_by, folder, &part)?;
1000            }
1001            Ok(part)
1002        })
1003    }
1004
1005    /// The label a new revision gets: the revision-label hook's answer when
1006    /// that script exists, else what the user typed, else `suggested`.
1007    fn decide_label(
1008        &self,
1009        user: &User,
1010        part: Option<&Part>,
1011        part_view: &Value,
1012        requested: &str,
1013        suggested: &str,
1014    ) -> Result<String, Error> {
1015        let existing: Vec<&str> = part
1016            .map(|p| p.revisions.iter().map(|r| r.label.as_str()).collect())
1017            .unwrap_or_default();
1018        let input = json!({
1019            "requested": requested,
1020            "suggested": suggested,
1021            "existing": existing,
1022            "part": part.map(|p| serde_json::to_value(p).unwrap_or(Value::Null)).unwrap_or_else(|| part_view.clone()),
1023            "user": scripting::user_json(user),
1024        });
1025        let label = match scripting::run(self, user, scripting::REVISION_LABEL, "revisionLabel", &input)? {
1026            HookResult::Absent => {
1027                if requested.is_empty() { suggested.to_string() } else { requested.to_string() }
1028            }
1029            HookResult::Refused(failure) => {
1030                return Err(Error::conflict(format!("{}: {}", scripting::REVISION_LABEL, failure.message)))
1031            }
1032            HookResult::Returned(success) => match &success.value {
1033                // Returning nothing means "no opinion".
1034                Value::Null => {
1035                    if requested.is_empty() { suggested.to_string() } else { requested.to_string() }
1036                }
1037                other => scripting::string_answer(other, "label").ok_or_else(|| {
1038                    Error::conflict(format!(
1039                        "{}: revisionLabel() must return the label, or {{ label }} — it returned {other}",
1040                        scripting::REVISION_LABEL
1041                    ))
1042                })?,
1043            },
1044        };
1045        check_label(&label)?;
1046        Ok(label)
1047    }
1048
1049    /// Start a new revision of a part, labelled with the suggestion.
1050    pub fn create_revision(&self, author: &User, part_id: &str) -> Result<Revision, Error> {
1051        self.create_revision_labelled(author, part_id, "")
1052    }
1053
1054    /// Start a new revision of a part.
1055    ///
1056    /// While another revision is in work this is refused only when the
1057    /// administrator has turned [`Settings::allow_multiple_open_drafts`] off;
1058    /// by default several revisions may be in work at once. The new draft
1059    /// inherits the document of the revision currently RELEASED — or, when
1060    /// none is, the newest revision — so revising a part starts from what the
1061    /// part currently is, never from somebody else's unfinished draft. That
1062    /// includes an imported part, which is revised rather than forked.
1063    ///
1064    /// `label` is free text; empty takes the suggestion. It must not repeat a
1065    /// label the part already has.
1066    pub fn create_revision_labelled(
1067        &self,
1068        author: &User,
1069        part_id: &str,
1070        label: &str,
1071    ) -> Result<Revision, Error> {
1072        self.create_revision_as(author, part_id, label, false, crate::model::Origin::Authored)
1073    }
1074
1075    /// [`Db::create_revision_labelled`] with the new revision's origin: a
1076    /// library re-import makes an `imported` one, so the next re-import
1077    /// still knows the latest revision is its own.
1078    pub fn create_revision_from(
1079        &self,
1080        author: &User,
1081        part_id: &str,
1082        label: &str,
1083        origin: crate::model::Origin,
1084    ) -> Result<Revision, Error> {
1085        check_origin(origin)?;
1086        self.create_revision_as(author, part_id, label, false, origin)
1087    }
1088
1089    /// [`Db::create_revision_labelled`]. With `exact`, the revision-label hook
1090    /// may refuse `label` but not rename it — what a family row needs, since
1091    /// the row names the revision it writes.
1092    pub(crate) fn create_revision_as(
1093        &self,
1094        author: &User,
1095        part_id: &str,
1096        label: &str,
1097        exact: bool,
1098        origin: crate::model::Origin,
1099    ) -> Result<Revision, Error> {
1100        let part = self
1101            .read(|state| state.part(part_id).cloned())
1102            .ok_or_else(|| Error::not_found("part"))?;
1103        let single = !self.read(|state| state.settings.allow_multiple_open_drafts);
1104        if let Some(open) = part.open_draft().filter(|_| single) {
1105            return Err(one_draft_refusal(open, &part));
1106        }
1107        let suggested = suggest_label(&part);
1108        let requested = label.trim();
1109        let label = self.decide_label(author, Some(&part), &Value::Null, requested, &suggested)?;
1110        if exact {
1111            exact_label(requested, &label)?;
1112        }
1113
1114        let carried_revision = part.current_release().or(part.latest()).map(|r| r.id.clone());
1115        let carried = part.current_release().or(part.latest()).map(|r| r.document_key(part_id));
1116        let carried_body = match carried {
1117            Some(key) => self.read_document(&key)?,
1118            None => None,
1119        };
1120        let carried_hash = carried_body.as_deref().map(auth::content_hash);
1121
1122        let author_id = author.id.clone();
1123        let revision = self.mutate(move |state| {
1124            // Again inside the lock: the setting, or the part, may have
1125            // changed since the look above.
1126            if !state.settings.allow_multiple_open_drafts {
1127                let part = state.part(part_id).ok_or_else(|| Error::not_found("part"))?;
1128                if let Some(open) = part.open_draft() {
1129                    return Err(one_draft_refusal(open, part));
1130                }
1131            }
1132            let part = state.parts.get_mut(&part_id)
1133                .ok_or_else(|| Error::not_found("part"))?;
1134            if let Some(clash) = part.revision_by_label(&label) {
1135                return Err(Error::conflict(format!(
1136                    "{} already has a revision labelled {}",
1137                    part.number, clash.label
1138                )));
1139            }
1140            let stamp = now();
1141            let mut revision = Revision::draft(label.clone(), label, author_id, stamp);
1142            revision.origin = origin;
1143            if let Some(previous) = carried_revision.as_deref().and_then(|id| part.revision(id)) {
1144                revision.has_geometry = previous.has_geometry;
1145                revision.attributes = previous.attributes.clone();
1146                revision.attributes_initialized = previous.attributes_initialized;
1147                revision.occurrences = previous.occurrences.clone();
1148            }
1149            // The uses list travels with the document it describes.
1150            revision.uses = carried_revision
1151                .as_deref()
1152                .and_then(|id| part.revision(id))
1153                .map(|r| r.uses.clone())
1154                .unwrap_or_default();
1155            // So do its files: new references to the same blobs, so removing
1156            // one from the new revision never touches the old one.
1157            revision.attachments = carried_revision
1158                .as_deref()
1159                .and_then(|id| part.revision(id))
1160                .map(|r| {
1161                    r.attachments
1162                        .iter()
1163                        .map(|a| crate::model::Attachment { id: auth::new_id(), ..a.clone() })
1164                        .collect()
1165                })
1166                .unwrap_or_default();
1167            // And its picture, while it still pictures the carried document
1168            // (the same bytes are written below, so the hash still matches).
1169            revision.thumbnail = carried_revision
1170                .as_deref()
1171                .and_then(|id| part.revision(id))
1172                .and_then(|r| r.thumbnail.clone())
1173                .filter(|t| carried_hash.as_deref() == Some(t.content_hash.as_str()));
1174            part.revisions.push(revision.clone());
1175            state.touch(revision.document_key(part_id));
1176            Ok(revision)
1177        })?;
1178
1179        if let Some(body) = carried_body {
1180            self.write_document(part_id, &revision.id, &body)?;
1181        }
1182        Ok(revision)
1183    }
1184
1185    /// Change a part's descriptive fields — `name`, `description`,
1186    /// `category`, `tags`, `external_ref` and `attributes`. The number, the
1187    /// type and the document class are identity and never change here.
1188    ///
1189    /// `attributes` MERGES: each key given is set (type-checked against the
1190    /// part's category, the new one if `category` changes in the same call),
1191    /// and a `null` clears it. Keys not mentioned are untouched — so moving a
1192    /// part to another category keeps the values the new schema lacks.
1193    ///
1194    /// This is the write behind `PATCH /api/parts/:id` and a script's
1195    /// `plm.updatePart`.
1196    pub fn update_part(&self, key: &str, fields: &Value) -> Result<Part, Error> {
1197        let Some(fields) = fields.as_object() else {
1198            return Err(Error::bad_request("the fields to change must be an object"));
1199        };
1200        for name in fields.keys() {
1201            if !matches!(
1202                name.as_str(),
1203                "name" | "description" | "category" | "tags" | "external_ref" | "attributes" | "member_part_type"
1204            ) {
1205                return Err(Error::bad_request(format!(
1206                    "'{name}' cannot be changed — only name, description, category, tags, attributes, external_ref and member_part_type"
1207                )));
1208            }
1209        }
1210        let fields = fields.clone();
1211        let key = key.to_string();
1212        self.mutate(move |state| {
1213            let id = state
1214                .part_by_id_or_number(&key)
1215                .map(|p| p.id.clone())
1216                .ok_or_else(|| Error::not_found("part"))?;
1217            if let Some(value) = fields.get("external_ref") {
1218                let reference = value.as_str().map(str::trim).unwrap_or_default();
1219                let kind = state.part(&id).map(|p| p.part_type.clone()).unwrap_or_default();
1220                external_ref_clash(state, &kind, reference, &id)?;
1221            }
1222            // Borrow the parts and the tree separately: the part is written,
1223            // the tree is only read.
1224            let State { parts, categories, settings, part_types, .. } = &mut *state;
1225            let part = parts.get_mut(&id).expect("found above");
1226            if let Some(value) = fields.get("member_part_type") {
1227                let requested = value.as_str().map(str::trim).unwrap_or_default();
1228                if part.document_class == DocumentClass::Normal && !requested.is_empty() {
1229                    return Err(Error::bad_request(
1230                        "only a family or a template has a member part type",
1231                    ));
1232                }
1233                if !requested.is_empty() && !part_types.iter().any(|t| t.id == requested) {
1234                    return Err(Error::bad_request(format!("no part type '{requested}'")));
1235                }
1236                part.member_part_type = requested.to_string();
1237            }
1238            let before = (part.category.clone(), part.attributes.clone());
1239            let updated = apply_part_fields(categories, part, &fields)?;
1240
1241            // Judged on what CHANGED, not on which fields were sent: the edit
1242            // dialog re-sends every field, and renaming a released part must
1243            // not trip a lock on values it left alone.
1244            if settings.lock_released_attributes
1245                && part.catalog_frozen()
1246                && before != (updated.category.clone(), updated.attributes.clone())
1247            {
1248                return Err(Error::conflict(format!(
1249                    "{} is released and its category and attributes are locked — start a new revision to change them",
1250                    part.number
1251                )));
1252            }
1253            Ok(updated)
1254        })
1255    }
1256}
1257
1258/// A family row and a template spin-out name their number and revision
1259/// themselves: the revision-label hook may refuse the label, but a hook that
1260/// RENAMES it would leave the table naming a revision that does not exist.
1261fn exact_label(requested: &str, decided: &str) -> Result<(), Error> {
1262    if !requested.is_empty() && !decided.eq_ignore_ascii_case(requested) {
1263        return Err(Error::conflict(format!(
1264            "{} would label it {decided}, not {requested} — a family row names its own revision",
1265            scripting::REVISION_LABEL
1266        )));
1267    }
1268    Ok(())
1269}
1270
1271/// A document still waiting for its bake cannot release: once released its
1272/// bytes are frozen, and the bake could never be written.
1273fn bake_gate(revision: &Revision) -> Result<(), Error> {
1274    match &revision.bake {
1275        Some(bake) if revision.needs_bake() => Err(Error::conflict(format!(
1276            "revision {} is waiting for a bake ({}{}) — it releases once a CAD worker has baked it, or once someone saves it from the CAD app",
1277            revision.label,
1278            bake.status.as_str(),
1279            if bake.error.is_empty() { String::new() } else { format!(": {}", bake.error) }
1280        ))),
1281        _ => Ok(()),
1282    }
1283}
1284
1285/// The refusal [`Settings::allow_multiple_open_drafts`] = off gives.
1286fn one_draft_refusal(open: &Revision, part: &Part) -> Error {
1287    Error::conflict(format!(
1288        "revision {} of {} is still open — release or delete it first (this server allows one revision in work at a time)",
1289        open.label, part.number
1290    ))
1291}
1292
1293impl Db {
1294    /// The administrator's settings as they stand.
1295    pub fn settings(&self) -> Settings {
1296        self.read(|state| state.settings.clone())
1297    }
1298
1299    /// Change settings. `fields` MERGES: each key given is set, the rest are
1300    /// untouched. An unknown key or a value of the wrong type is refused
1301    /// rather than ignored, so a typo in an admin's request cannot silently
1302    /// leave a policy where it was.
1303    pub fn update_settings(&self, fields: &Value) -> Result<Settings, Error> {
1304        let Some(fields) = fields.as_object() else {
1305            return Err(Error::bad_request("the settings to change must be an object"));
1306        };
1307        let mut merged = serde_json::to_value(self.settings()).map_err(Error::internal)?;
1308        for (key, value) in fields {
1309            let slot = merged
1310                .get_mut(key)
1311                .ok_or_else(|| Error::bad_request(format!("there is no setting '{key}'")))?;
1312            if slot.is_boolean() && !value.is_boolean() {
1313                return Err(Error::bad_request(format!("'{key}' must be true or false")));
1314            }
1315            if slot.is_u64() {
1316                let minimum = if key == "session_idle_minutes" { 5 } else { 0 };
1317                match value.as_u64() {
1318                    Some(n) if n >= minimum => {}
1319                    _ => {
1320                        return Err(Error::bad_request(format!(
1321                            "'{key}' must be a whole number of at least {minimum}"
1322                        )))
1323                    }
1324                }
1325            }
1326            *slot = value.clone();
1327        }
1328        self.read(|state| crate::review::normalize_settings_json(state, &mut merged))?;
1329        let settings: Settings = serde_json::from_value(merged)
1330            .map_err(|e| Error::bad_request(format!("those settings do not read: {e}")))?;
1331        self.mutate(move |state| {
1332            // The review rules name users, groups, part types and categories:
1333            // checked against the store as it is at the write.
1334            let mut settings = settings;
1335            crate::review::check_settings(state, &mut settings)?;
1336            crate::lifecycle::check_options(&settings.status_options)?;
1337            state.settings = settings.clone();
1338            Ok(settings)
1339        })
1340    }
1341}
1342
1343/// The body of [`Db::update_part`], inside its lock. `categories` is the tree
1344/// as it is at the write.
1345fn apply_part_fields(
1346    categories: &[Category],
1347    part: &mut Part,
1348    fields: &serde_json::Map<String, Value>,
1349) -> Result<Part, Error> {
1350    let text = |value: &Value| value.as_str().map(|s| s.trim().to_string());
1351    if let Some(value) = fields.get("name") {
1352        let name = text(value)
1353            .filter(|n| !n.is_empty())
1354            .ok_or_else(|| Error::bad_request("a part needs a name"))?;
1355        part.name = name;
1356    }
1357    if let Some(value) = fields.get("description") {
1358        part.description = text(value).unwrap_or_default();
1359    }
1360    if let Some(value) = fields.get("category") {
1361        let requested = text(value).unwrap_or_default();
1362        part.category = known_category(categories, &requested)?;
1363    }
1364    if let Some(value) = fields.get("external_ref") {
1365        part.external_ref = text(value).unwrap_or_default();
1366    }
1367    if let Some(value) = fields.get("tags") {
1368        part.tags = catalog::tidy_tags(
1369            value
1370                .as_array()
1371                .ok_or_else(|| Error::bad_request("tags must be a list of strings"))?
1372                .iter()
1373                .filter_map(|t| t.as_str().map(str::to_string)),
1374        );
1375    }
1376    // After the category, so a move and the new category's values can land in
1377    // one call.
1378    if let Some(value) = fields.get("attributes") {
1379        let changes = value
1380            .as_object()
1381            .ok_or_else(|| Error::bad_request("attributes must be an object of key: value"))?;
1382        if changes.keys().any(|key| key.trim().eq_ignore_ascii_case("has_geometry")) {
1383            return Err(Error::bad_request("has_geometry is derived from the saved model and cannot be edited"));
1384        }
1385        if changes.keys().any(|key| key.trim().eq_ignore_ascii_case("has_thumbnail")) {
1386            return Err(Error::bad_request("has_thumbnail is derived from current thumbnails and cannot be edited"));
1387        }
1388        catalog::apply_values(categories, &part.category, &mut part.attributes, changes)?;
1389    }
1390    Ok(part.clone())
1391}
1392
1393/// The category id to store for `requested`: empty for none, else the id of
1394/// an existing category (the text may differ in case). A category that does
1395/// not exist is refused rather than stored as free text, so a typo cannot
1396/// quietly file a part nowhere.
1397fn known_category(categories: &[Category], requested: &str) -> Result<String, Error> {
1398    let requested = requested.trim();
1399    if requested.is_empty() {
1400        return Ok(String::new());
1401    }
1402    catalog::find(categories, requested)
1403        .map(|c| c.id.clone())
1404        .ok_or_else(|| Error::bad_request(format!("there is no category '{requested}'")))
1405}
1406
1407/// What a parts listing is narrowed to. Every field is optional; empty means
1408/// "no constraint".
1409#[derive(Debug, Clone, Default)]
1410pub struct PartFilter {
1411    /// Text matched against the number, name, description, category name,
1412    /// tags, attribute values, and every MPN and SPN.
1413    pub q: String,
1414    /// A category id: the parts in it AND in every category beneath it.
1415    /// [`UNCATEGORIZED`] selects the parts without a category.
1416    pub category: String,
1417    /// A tag, matched whole and without regard to case.
1418    pub tag: String,
1419    /// A manufacturer, by id or name: the parts with a manufacturer part
1420    /// from it.
1421    pub manufacturer: String,
1422    /// A supplier, by id or name: the parts with an offer from it.
1423    pub supplier: String,
1424    /// Catalog attribute conditions, all of which a part must meet
1425    /// ([`AttributeFilter`]).
1426    pub attributes: Vec<AttributeFilter>,
1427    /// An external reference, matched exactly (a library import's lookup).
1428    pub external_ref: String,
1429    /// A part type id, matched exactly.
1430    pub part_type: String,
1431}
1432
1433/// One attribute condition of a parts listing (`attr.<key>=…`,
1434/// `attr.<key>.min=…`, `attr.<key>.max=…`), as the caller typed it. It is
1435/// read against the attribute's type in the catalog ([`attribute_matchers`]).
1436#[derive(Debug, Clone, Default, PartialEq)]
1437pub struct AttributeFilter {
1438    pub key: String,
1439    /// The part's value must equal one of these (any of); empty: any value.
1440    pub values: Vec<String>,
1441    /// Inclusive bounds, for a number attribute.
1442    pub min: Option<String>,
1443    pub max: Option<String>,
1444}
1445
1446impl AttributeFilter {
1447    /// The conditions in a query string's `attr.*` pairs, merged per key in
1448    /// the order they first appear. Anything after `attr.<key>` other than
1449    /// `.min` or `.max` is refused. Other pairs are ignored.
1450    pub fn from_query(pairs: &[(String, String)]) -> Result<Vec<AttributeFilter>, Error> {
1451        let mut out: Vec<AttributeFilter> = Vec::new();
1452        for (name, value) in pairs {
1453            let Some(rest) = name.strip_prefix("attr.") else { continue };
1454            let (key, bound) = match rest.rsplit_once('.') {
1455                Some((key, "min")) => (key, Some(true)),
1456                Some((key, "max")) => (key, Some(false)),
1457                Some((_, other)) if !rest.is_empty() => {
1458                    // An attribute key has no dots (catalog::usable_key), so
1459                    // anything after one is a suffix, and only two exist.
1460                    return Err(Error::bad_request(format!(
1461                        "'{name}': an attribute filter is attr.<key>, attr.<key>.min or attr.<key>.max, not .{other}"
1462                    )));
1463                }
1464                _ => (rest, None),
1465            };
1466            let key = key.trim();
1467            if key.is_empty() {
1468                return Err(Error::bad_request(format!("'{name}' names no attribute")));
1469            }
1470            let at = match out.iter().position(|f| f.key == key) {
1471                Some(i) => i,
1472                None => {
1473                    out.push(AttributeFilter { key: key.to_string(), ..AttributeFilter::default() });
1474                    out.len() - 1
1475                }
1476            };
1477            let filter = &mut out[at];
1478            match bound {
1479                None => filter.values.push(value.clone()),
1480                Some(true) => filter.min = Some(value.clone()),
1481                Some(false) => filter.max = Some(value.clone()),
1482            }
1483        }
1484        Ok(out)
1485    }
1486}
1487
1488/// An [`AttributeFilter`] read against the catalog: its type, its values in
1489/// the canonical form they are stored in, its bounds as numbers.
1490#[derive(Debug, Clone)]
1491pub struct AttributeMatcher {
1492    key: String,
1493    any_of: Vec<Value>,
1494    min: Option<f64>,
1495    max: Option<f64>,
1496}
1497
1498impl AttributeMatcher {
1499    fn matches(&self, part: &Part) -> bool {
1500        let geometry = Value::Bool(part.latest().is_some_and(|r| r.has_geometry));
1501        let thumbnail = Value::Bool(crate::thumbnail::of_part(part).is_some());
1502        let have = if self.key == "has_geometry" { &geometry } else if self.key == "has_thumbnail" { &thumbnail } else {
1503            let Some(value) = part.attributes.get(&self.key).filter(|v| !v.is_null()) else { return false };
1504            value
1505        };
1506        let number = have.as_f64();
1507        let equal = |want: &Value| match (want, have) {
1508            (Value::Number(w), Value::Number(h)) => w.as_f64() == h.as_f64(),
1509            (Value::String(w), Value::String(h)) => w.eq_ignore_ascii_case(h.trim()),
1510            (w, h) => w == h,
1511        };
1512        (self.any_of.is_empty() || self.any_of.iter().any(equal))
1513            && self.min.is_none_or(|min| number.is_some_and(|n| n >= min))
1514            && self.max.is_none_or(|max| number.is_some_and(|n| n <= max))
1515    }
1516}
1517
1518/// Read `filter`'s attribute conditions against the catalog, or say why they
1519/// cannot be read (a `400`).
1520///
1521/// With a `category` the key must be in that category's effective schema.
1522/// Without one it must be defined by some category, and every category that
1523/// defines it must agree on its type — else the caller is told to narrow by
1524/// category. A value is read as the catalog reads form text
1525/// ([`catalog::check_value`]), so `12.5`, `yes` and an enum value in any case
1526/// all work; `min` and `max` are for numbers only.
1527pub fn attribute_matchers(state: &State, filter: &PartFilter) -> Result<Vec<AttributeMatcher>, Error> {
1528    use crate::model::{AttributeDef, AttributeKind};
1529    let category = catalog::find(&state.categories, filter.category.trim()).map(|c| c.id.clone());
1530    let mut out = Vec::new();
1531    for condition in &filter.attributes {
1532        let key = condition.key.as_str();
1533        if matches!(key, "has_geometry" | "has_thumbnail") {
1534            if condition.min.is_some() || condition.max.is_some() {
1535                return Err(Error::bad_request(format!("{key} is a boolean and has no range")));
1536            }
1537            let any_of = condition.values.iter().map(|v| match v.as_str() {
1538                "true" => Ok(Value::Bool(true)), "false" => Ok(Value::Bool(false)),
1539                _ => Err(Error::bad_request(format!("attr.{key} must be true or false"))),
1540            }).collect::<Result<Vec<_>, _>>()?;
1541            out.push(AttributeMatcher { key: key.into(), any_of, min: None, max: None });
1542            continue;
1543        }
1544        let defs: Vec<(String, AttributeDef)> = match &category {
1545            Some(id) => catalog::schema(&state.categories, id)?
1546                .into_iter()
1547                .filter(|e| e.def.key == key)
1548                .map(|e| (id.clone(), e.def))
1549                .collect(),
1550            None => state
1551                .categories
1552                .iter()
1553                .flat_map(|c| c.attributes.iter().filter(|d| d.key == key).map(move |d| (c.id.clone(), d.clone())))
1554                .collect(),
1555        };
1556        let Some((first_category, def)) = defs.first().cloned() else {
1557            return Err(Error::bad_request(match &category {
1558                Some(id) => format!("the category '{id}' has no attribute '{key}'"),
1559                None => format!("no category has an attribute '{key}'"),
1560            }));
1561        };
1562        if let Some((other, clash)) = defs.iter().find(|(_, d)| d.kind.as_str() != def.kind.as_str()) {
1563            return Err(Error::bad_request(format!(
1564                "'{key}' is a {} in '{first_category}' but a {} in '{other}' — give a category to filter by it",
1565                def.kind.as_str(),
1566                clash.kind.as_str()
1567            )));
1568        }
1569        let mut any_of = Vec::new();
1570        for raw in &condition.values {
1571            // An enum's values may differ between the categories that define
1572            // the key: a value any of them lists is accepted.
1573            let read = defs.iter().map(|(_, d)| catalog::check_value(d, &Value::String(raw.clone())));
1574            let mut first_error = None;
1575            let mut value = None;
1576            for result in read {
1577                match result {
1578                    Ok(v) => {
1579                        value = v;
1580                        first_error = None;
1581                        break;
1582                    }
1583                    Err(e) => {
1584                        first_error.get_or_insert(e);
1585                    }
1586                }
1587            }
1588            if let Some(error) = first_error {
1589                return Err(Error::bad_request(format!("attr.{key}: {error}")));
1590            }
1591            let Some(value) = value else {
1592                return Err(Error::bad_request(format!("attr.{key} is empty — leave it out to filter on nothing")));
1593            };
1594            any_of.push(value);
1595        }
1596        let bound = |raw: &Option<String>, which: &str| -> Result<Option<f64>, Error> {
1597            let Some(raw) = raw else { return Ok(None) };
1598            if !matches!(def.kind, AttributeKind::Number { .. }) {
1599                return Err(Error::bad_request(format!(
1600                    "attr.{key}.{which}: '{key}' is a {}, and only a number has a range",
1601                    def.kind.as_str()
1602                )));
1603            }
1604            raw.trim()
1605                .parse::<f64>()
1606                .ok()
1607                .filter(|n| n.is_finite())
1608                .map(Some)
1609                .ok_or_else(|| Error::bad_request(format!("attr.{key}.{which} must be a number, not '{raw}'")))
1610        };
1611        out.push(AttributeMatcher {
1612            key: key.to_string(),
1613            any_of,
1614            min: bound(&condition.min, "min")?,
1615            max: bound(&condition.max, "max")?,
1616        });
1617    }
1618    Ok(out)
1619}
1620
1621/// One page of a parts listing ([`Db::find_parts_page`]).
1622#[derive(Debug, Default)]
1623pub struct PartPage {
1624    pub parts: Vec<Part>,
1625    /// The cursor for the next page, or `None` when this is the last.
1626    pub next: Option<String>,
1627    cursors: Vec<i64>,
1628}
1629
1630impl PartPage {
1631    /// Trim a page collected one past `limit`, and set its cursor.
1632    fn finish(&mut self, limit: Option<usize>) {
1633        if let Some(limit) = limit {
1634            if self.parts.len() > limit {
1635                self.parts.truncate(limit);
1636                self.next = self.cursors.get(limit - 1).map(|c| c.to_string());
1637            }
1638        }
1639        self.cursors.clear();
1640    }
1641}
1642
1643/// A [`PartFilter`] resolved against the store: the exact rules a part must
1644/// pass, whichever way the candidates were found.
1645struct Matcher {
1646    needle: String,
1647    tag: String,
1648    /// The category ids (lower-case) a part must be in; `Some(empty)` with
1649    /// `uncategorized` for "without a category".
1650    within: Option<BTreeSet<String>>,
1651    uncategorized: bool,
1652    /// `Some(None)`: the filter names a company that does not exist, which
1653    /// matches nothing rather than silently widening to everything.
1654    manufacturer: Option<Option<String>>,
1655    supplier: Option<Option<String>>,
1656    external_ref: String,
1657    part_type: String,
1658    /// The attribute conditions, read; `None` when they could not be read,
1659    /// which matches nothing (the route refuses such a filter with a 400
1660    /// before it gets here).
1661    attributes: Option<Vec<AttributeMatcher>>,
1662}
1663
1664impl Matcher {
1665    fn new(state: &State, filter: &PartFilter) -> Self {
1666        let within = match filter.category.trim() {
1667            "" => None,
1668            UNCATEGORIZED => Some(BTreeSet::new()),
1669            id => Some(catalog::descendants(&state.categories, id)),
1670        };
1671        let company = |which: sourcing::Companies, key: &str| -> Option<Option<String>> {
1672            let key = key.trim();
1673            if key.is_empty() {
1674                return None;
1675            }
1676            Some(sourcing::find_company(which.list(state), key).map(|c| c.id.clone()))
1677        };
1678        Matcher {
1679            needle: filter.q.trim().to_ascii_lowercase(),
1680            tag: filter.tag.trim().to_string(),
1681            within,
1682            uncategorized: filter.category.trim() == UNCATEGORIZED,
1683            manufacturer: company(sourcing::Companies::Manufacturers, &filter.manufacturer),
1684            supplier: company(sourcing::Companies::Suppliers, &filter.supplier),
1685            attributes: attribute_matchers(state, filter).ok(),
1686            external_ref: filter.external_ref.trim().to_string(),
1687            part_type: filter.part_type.trim().to_string(),
1688        }
1689    }
1690
1691    /// A filter no part can pass: it names a company that does not exist,
1692    /// or attribute conditions that do not read.
1693    fn impossible(&self) -> bool {
1694        matches!(self.manufacturer, Some(None)) || matches!(self.supplier, Some(None)) || self.attributes.is_none()
1695    }
1696
1697    fn matches(&self, categories: &[Category], part: &Part) -> bool {
1698        (match &self.within {
1699            None => true,
1700            Some(_) if self.uncategorized => part.category.is_empty(),
1701            Some(ids) => ids.contains(&part.category.to_ascii_lowercase()),
1702        }) && (self.tag.is_empty() || part.tags.iter().any(|t| t.eq_ignore_ascii_case(&self.tag)))
1703            && (match &self.manufacturer {
1704                None => true,
1705                Some(None) => false,
1706                Some(Some(id)) => part.sourcing.iter().any(|mp| &mp.manufacturer == id),
1707            })
1708            && (match &self.supplier {
1709                None => true,
1710                Some(None) => false,
1711                Some(Some(id)) => part.sourcing.iter().flat_map(|mp| &mp.offers).any(|o| &o.supplier == id),
1712            })
1713            && (self.external_ref.is_empty() || part.external_ref == self.external_ref)
1714            && (self.part_type.is_empty() || part.part_type == self.part_type)
1715            && self.attributes.as_ref().is_some_and(|all| all.iter().all(|a| a.matches(part)))
1716            && (self.needle.is_empty() || part_matches(categories, part, &self.needle))
1717    }
1718}
1719
1720/// The `category` filter value that selects parts without a category —
1721/// an empty category.
1722pub const UNCATEGORIZED: &str = "_none";
1723
1724impl Db {
1725    /// Search parts by number, name, category or tag — what a script's
1726    /// `plm.findParts` asks.
1727    pub fn search_parts(&self, query: &str) -> Vec<Part> {
1728        self.find_parts(&PartFilter { q: query.to_string(), ..PartFilter::default() })
1729    }
1730
1731    /// The parts that pass `filter`, in creation order.
1732    pub fn find_parts(&self, filter: &PartFilter) -> Vec<Part> {
1733        self.find_parts_page(filter, None, None).parts
1734    }
1735
1736    /// One page of the parts that pass `filter`, in creation order: at most
1737    /// `limit`, continuing after the cursor `after` (a [`PartPage::next`]).
1738    ///
1739    /// The SQLite side narrows ([`crate::sql::Sql::candidates`]): the trigram
1740    /// index finds the parts whose searchable text contains the search text,
1741    /// and indexed columns apply the category, tag and company filters. Every
1742    /// candidate is then checked against the in-memory part with the exact
1743    /// rules below, so the answer is the one the rules give — the index only
1744    /// decides how few parts are looked at. Search text shorter than three
1745    /// characters (the trigram minimum) narrows nothing and is checked on
1746    /// every part the other filters leave. Should the index fail, the answer
1747    /// comes from a scan of memory rather than an error.
1748    pub fn find_parts_page(&self, filter: &PartFilter, after: Option<&str>, limit: Option<usize>) -> PartPage {
1749        let matcher = self.read(|state| Matcher::new(state, filter));
1750        let after: Option<i64> = after.and_then(|a| a.trim().parse().ok());
1751        let limit = limit.map(|l| l.max(1));
1752        if matcher.impossible() {
1753            return PartPage::default();
1754        }
1755        // An exact external reference picks one part, or a handful: a walk of
1756        // memory finds it without paging through the index 256 rows at a time.
1757        if !matcher.external_ref.is_empty() {
1758            return self.scanned_page(&matcher, after, limit);
1759        }
1760        match self.indexed_page(&matcher, after, limit) {
1761            Ok(page) => page,
1762            Err(error) => {
1763                eprintln!("brep-plm: search index: {error}; answering from a scan");
1764                self.scanned_page(&matcher, after, limit)
1765            }
1766        }
1767    }
1768
1769    fn indexed_page(&self, matcher: &Matcher, mut after: Option<i64>, limit: Option<usize>) -> rusqlite::Result<PartPage> {
1770        let categories: Option<Vec<String>> = match (&matcher.within, matcher.uncategorized) {
1771            (Some(ids), false) => Some(ids.iter().cloned().collect()),
1772            _ => None,
1773        };
1774        let needle = (matcher.needle.chars().count() >= 3).then_some(matcher.needle.as_str());
1775        let mut page = PartPage::default();
1776        // One more than the page, to know whether there IS a next page.
1777        let wanted = limit.map(|l| l + 1);
1778        let batch = wanted.map(|w| w.max(256));
1779        loop {
1780            let rows = self.sql.candidates(&sql::Candidates {
1781                needle,
1782                categories: categories.as_deref(),
1783                uncategorized: matcher.uncategorized,
1784                tag: (!matcher.tag.is_empty()).then_some(matcher.tag.as_str()),
1785                manufacturer: matcher.manufacturer.as_ref().and_then(|m| m.as_deref()),
1786                supplier: matcher.supplier.as_ref().and_then(|s| s.as_deref()),
1787                after,
1788                limit: batch,
1789            })?;
1790            let exhausted = batch.is_none_or(|b| rows.len() < b);
1791            let full = self.read(|state| {
1792                for (ord, id) in &rows {
1793                    after = Some(*ord);
1794                    let Some(part) = state.parts.get(id) else { continue };
1795                    if matcher.matches(&state.categories, part) {
1796                        page.parts.push(part.clone());
1797                        page.cursors.push(*ord);
1798                        if wanted.is_some_and(|w| page.parts.len() >= w) {
1799                            return true;
1800                        }
1801                    }
1802                }
1803                false
1804            });
1805            if full || exhausted {
1806                break;
1807            }
1808        }
1809        page.finish(limit);
1810        Ok(page)
1811    }
1812
1813    fn scanned_page(&self, matcher: &Matcher, after: Option<i64>, limit: Option<usize>) -> PartPage {
1814        let mut page = PartPage::default();
1815        self.read(|state| {
1816            for (ord, part) in state.parts.iter().enumerate() {
1817                let ord = ord as i64;
1818                if after.is_some_and(|a| ord <= a) || !matcher.matches(&state.categories, part) {
1819                    continue;
1820                }
1821                page.parts.push(part.clone());
1822                page.cursors.push(ord);
1823                if limit.is_some_and(|l| page.parts.len() > l) {
1824                    break;
1825                }
1826            }
1827        });
1828        page.finish(limit);
1829        page
1830    }
1831
1832    /// [`Db::find_parts`] by a scan of memory alone, with no index — what the
1833    /// index's answers are checked against.
1834    pub fn find_parts_scanning(&self, filter: &PartFilter) -> Vec<Part> {
1835        let matcher = self.read(|state| Matcher::new(state, filter));
1836        if matcher.impossible() {
1837            return Vec::new();
1838        }
1839        self.scanned_page(&matcher, None, None).parts
1840    }
1841
1842    /// Take the lock on a draft revision.
1843    pub fn checkout(
1844        &self,
1845        user: &User,
1846        part_id: &str,
1847        revision_id: &str,
1848        client_id: &str,
1849    ) -> Result<(), Error> {
1850        let user_id = user.id.clone();
1851        let client_id = client_id.to_string();
1852        self.mutate(move |state| {
1853            let (_, revision) = find_revision_mut(state, part_id, revision_id)?;
1854            if !revision.lifecycle.is_editable() {
1855                return Err(Error::conflict(format!(
1856                    "revision {} is {} — only a draft can be checked out",
1857                    revision.label,
1858                    revision.lifecycle.as_str()
1859                )));
1860            }
1861            if let Some(lock) = &revision.lock {
1862                if lock.user_id != user_id {
1863                    return Err(Error::conflict(
1864                        "already checked out by another user".to_string(),
1865                    ));
1866                }
1867                // The same user re-taking their own lock from another client
1868                // is a no-op that re-stamps which client holds it.
1869            }
1870            revision.lock = Some(Lock {
1871                user_id,
1872                client_id,
1873                acquired_at: now(),
1874            });
1875            state.touch_part(part_id);
1876            Ok(())
1877        })
1878    }
1879
1880    /// Release the lock. `force` is the BREAK path and requires the check-in
1881    /// group; without it only the holder may check in.
1882    pub fn checkin(
1883        &self,
1884        user: &User,
1885        part_id: &str,
1886        revision_id: &str,
1887        force: bool,
1888    ) -> Result<(), Error> {
1889        let user_id = user.id.clone();
1890        let may_break = user.can_checkin();
1891        self.mutate(move |state| {
1892            let (_, revision) = find_revision_mut(state, part_id, revision_id)?;
1893            let Some(lock) = revision.lock.clone() else {
1894                return Err(Error::conflict("nothing is checked out".to_string()));
1895            };
1896            if lock.user_id != user_id {
1897                if !force {
1898                    return Err(Error::forbidden(
1899                        "another user holds this lock — breaking it needs the check-in group",
1900                    ));
1901                }
1902                if !may_break {
1903                    return Err(Error::forbidden(
1904                        "breaking another user's lock needs the check-in group",
1905                    ));
1906                }
1907            }
1908            revision.lock = None;
1909            state.touch_part(part_id);
1910            Ok(())
1911        })
1912    }
1913
1914    /// Move a revision's lifecycle state, applying the rules in
1915    /// [`crate::lifecycle`] and the automatic supersede.
1916    ///
1917    /// A release runs two hooks when their files exist. `beforeRelease` runs
1918    /// first, outside the store lock, and a throw refuses the release; the
1919    /// locked write then re-checks that the revision's bytes are the ones the
1920    /// hook saw. `afterRelease` runs once the release is committed: it cannot
1921    /// undo it, so its failure comes back as a WARNING, the release standing.
1922    pub fn transition(
1923        &self,
1924        user: &User,
1925        part_id: &str,
1926        revision_id: &str,
1927        to: Lifecycle,
1928    ) -> Result<Vec<String>, Error> {
1929        self.transition_checked(user, part_id, revision_id, to, None, None)
1930    }
1931
1932    pub fn transition_reviewed(&self, user: &User, part_id: &str, revision_id: &str, to: Lifecycle, expected_hash: &str) -> Result<Vec<String>, Error> {
1933        self.transition_checked(user, part_id, revision_id, to, Some(expected_hash), None)
1934    }
1935
1936    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> {
1937        self.transition_checked(user, part_id, revision_id, to, Some(expected_hash), Some(run_id))
1938    }
1939
1940    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> {
1941        if let Some(expected) = expected_hash {
1942            let (_, revision) = self.snapshot(part_id, revision_id)?;
1943            if revision.content_hash != expected { return Err(Error::conflict("workflow model changed after review")); }
1944        }
1945        lifecycle::check_enabled(&self.settings(), to)?;
1946        if to == Lifecycle::Released { self.read(|s|crate::workflow::release_gate(s,part_id,revision_id,workflow_run))?; }
1947        if to == Lifecycle::Superseded {
1948            return Err(Error::bad_request(
1949                "superseded is applied automatically when a newer revision releases",
1950            ));
1951        }
1952        if to == Lifecycle::Released && !user.can_checkin() {
1953            return Err(Error::forbidden("releasing needs the check-in group"));
1954        }
1955        // Submitting for review and pulling back from it are an author's work.
1956        if matches!(to, Lifecycle::InReview | Lifecycle::Draft) && !user.can_author() {
1957            return Err(Error::forbidden("submitting for review, or withdrawing, needs the author group"));
1958        }
1959        // Submitting opens a review round ([`crate::review`]).
1960        if to == Lifecycle::InReview {
1961            return self.submit_for_review(user, part_id, revision_id, &crate::review::Submission::default());
1962        }
1963
1964        // The before-release gate, on a snapshot. Refusals the locked write
1965        // would make anyway are made first, so a script is never asked about
1966        // a release that cannot happen.
1967        let mut seen_hash = None;
1968        if to == Lifecycle::Released {
1969            let (part, revision) = self.snapshot(part_id, revision_id)?;
1970            lifecycle::check_transition(revision.lifecycle, to).map_err(Error::conflict)?;
1971            self.read(|state| catalog_gate(&state.categories, &part))?;
1972            self.read(|state| children_gate(state, &part, &revision))?;
1973            self.read(|state| review_gate(state, &part, &revision))?;
1974            if revision.lock.is_some() {
1975                return Err(Error::conflict(format!(
1976                    "revision {} is checked out — check it in before releasing",
1977                    revision.label
1978                )));
1979            }
1980            bake_gate(&revision)?;
1981            let input = self.read(|state| release_input(state, &part, &revision, user));
1982            match scripting::run(self, user, scripting::BEFORE_RELEASE, "beforeRelease", &input)? {
1983                HookResult::Absent | HookResult::Returned(_) => {}
1984                HookResult::Refused(failure) => {
1985                    return Err(Error::conflict(format!(
1986                        "{} refused the release: {}",
1987                        scripting::BEFORE_RELEASE,
1988                        failure.message
1989                    )))
1990                }
1991            }
1992            seen_hash = Some(revision.content_hash.clone());
1993        }
1994
1995        let user_id = user.id.clone();
1996        self.mutate(move |state| {
1997            lifecycle::check_enabled(&state.settings, to)?;
1998            if to == Lifecycle::Released { crate::workflow::release_gate(state,part_id,revision_id,workflow_run)?; }
1999            if let Some(expected) = expected_hash {
2000                let revision = state.part(part_id).and_then(|p|p.revision(revision_id)).ok_or_else(||Error::not_found("revision"))?;
2001                if revision.content_hash != expected { return Err(Error::conflict("workflow model changed after review")); }
2002            }
2003            if to == Lifecycle::Released {
2004                // Again INSIDE the lock: the part's values or its category's
2005                // schema may have changed while the hook ran.
2006                let part = state.part(part_id).ok_or_else(|| Error::not_found("part"))?;
2007                catalog_gate(&state.categories, part)?;
2008                let revision = part.revision(revision_id).ok_or_else(|| Error::not_found("revision"))?;
2009                let field_problems = crate::bom_config::release_problems(state, part, revision);
2010                if !field_problems.is_empty() { return Err(Error::conflict(field_problems.join("; "))); }
2011                children_gate(state, part, revision)?;
2012                review_gate(state, part, revision)?;
2013            }
2014            let (_, revision) = find_revision_mut(state, part_id, revision_id)?;
2015            lifecycle::check_transition(revision.lifecycle, to).map_err(Error::conflict)?;
2016            // Pulling a revision out of review ends its round.
2017            if revision.lifecycle == Lifecycle::InReview && to == Lifecycle::Draft {
2018                if let Some(review) = revision.live_review_mut() {
2019                    crate::review::withdraw(review, &user_id, now());
2020                }
2021            }
2022            if let Some(hash) = &seen_hash {
2023                if *hash != revision.content_hash {
2024                    return Err(Error::conflict(format!(
2025                        "revision {} changed while {} was checking it — release it again",
2026                        revision.label,
2027                        scripting::BEFORE_RELEASE
2028                    )));
2029                }
2030            }
2031            if to == Lifecycle::Released {
2032                bake_gate(revision)?;
2033                if let Some(lock) = &revision.lock {
2034                    return Err(Error::conflict(format!(
2035                        "revision {} is checked out (held since {}) — check it in before releasing",
2036                        revision.label, lock.acquired_at
2037                    )));
2038                }
2039                crate::review::close_on_release(revision, &user_id, now());
2040                revision.released_by = Some(user_id);
2041                revision.released_at = Some(now());
2042                revision.lock = None;
2043            }
2044            revision.lifecycle = to;
2045            let released_id = revision.id.clone();
2046
2047            // The automatic supersede: every OTHER released revision of this
2048            // part steps down. Applied here so no caller can release without
2049            // it.
2050            if to == Lifecycle::Released {
2051                let part = state.parts.get_mut(&part_id)
2052                    .ok_or_else(|| Error::not_found("part"))?;
2053                for other in part.revisions.iter_mut() {
2054                    if other.id != released_id && other.lifecycle == Lifecycle::Released {
2055                        other.lifecycle = Lifecycle::Superseded;
2056                    }
2057                }
2058            }
2059            state.touch_part(&part_id);
2060            Ok(())
2061        })?;
2062
2063        let mut warnings = Vec::new();
2064        if to == Lifecycle::Draft {
2065            warnings.extend(self.review_withdrawn(user, part_id, revision_id));
2066        }
2067        if to == Lifecycle::Released {
2068            let (part, revision) = self.snapshot(part_id, revision_id)?;
2069            // With the gate off the release stands, and says what it did not
2070            // wait for.
2071            let unreleased = self.read(|state| bom::unreleased_children(state, &revision));
2072            if !unreleased.is_empty() {
2073                warnings.push(format!("released, but it uses unreleased parts: {}", unreleased.join("; ")));
2074            }
2075            let input = self.read(|state| release_input(state, &part, &revision, user));
2076            match scripting::run(self, user, scripting::AFTER_RELEASE, "afterRelease", &input) {
2077                Ok(HookResult::Absent) | Ok(HookResult::Returned(_)) => {}
2078                Ok(HookResult::Refused(failure)) => warnings.push(format!(
2079                    "released, but {} failed: {}",
2080                    scripting::AFTER_RELEASE,
2081                    failure.message
2082                )),
2083                Err(error) => warnings.push(format!(
2084                    "released, but {} could not run: {}",
2085                    scripting::AFTER_RELEASE,
2086                    error.message
2087                )),
2088            }
2089        }
2090        Ok(warnings)
2091    }
2092
2093    /// A copy of one part and one of its revisions, for a hook to read.
2094    pub(crate) fn snapshot(&self, part_id: &str, revision_id: &str) -> Result<(Part, Revision), Error> {
2095        self.read(|state| {
2096            let part = state.part(part_id).ok_or_else(|| Error::not_found("part"))?;
2097            let revision = part
2098                .revision(revision_id)
2099                .ok_or_else(|| Error::not_found("revision"))?;
2100            Ok((part.clone(), revision.clone()))
2101        })
2102    }
2103
2104    /// Delete a draft revision outright — the only removal this server allows.
2105    /// A released revision is never deleted; it is obsoleted.
2106    pub fn delete_draft(&self, user: &User, part_id: &str, revision_id: &str) -> Result<(), Error> {
2107        let user_id = user.id.clone();
2108        let may_break = user.can_checkin();
2109        let key = crate::identity::document_key(part_id, revision_id);
2110        let root = self.root().to_path_buf();
2111        self.mutate(|state| {
2112            let (_, revision) = find_revision_mut(state, part_id, revision_id)?;
2113            if !revision.lifecycle.is_editable() {
2114                return Err(Error::conflict(
2115                    "only a draft can be deleted — release history is permanent".to_string(),
2116                ));
2117            }
2118            if let Some(lock) = &revision.lock {
2119                if lock.user_id != user_id && !may_break {
2120                    return Err(Error::forbidden(
2121                        "another user has this draft checked out",
2122                    ));
2123                }
2124            }
2125            let part = state.parts.get_mut(&part_id)
2126                .ok_or_else(|| Error::not_found("part"))?;
2127            if part.revisions.len() == 1 {
2128                return Err(Error::conflict(
2129                    "a part keeps at least one revision".to_string(),
2130                ));
2131            }
2132            // A revision another list pins cannot go: that list would name
2133            // nothing.
2134            if let Some((parent, rev)) = pinned_by(state, part_id, revision_id) {
2135                return Err(Error::conflict(format!(
2136                    "this revision is used by {parent} rev {rev} — remove it from that list first"
2137                )));
2138            }
2139            let part = state.parts.get_mut(&part_id)
2140                .ok_or_else(|| Error::not_found("part"))?;
2141            let thumbnail = part.revision(revision_id).and_then(|r| r.thumbnail.as_ref()).map(|t| t.sha256.clone());
2142            part.revisions.retain(|r| r.id != revision_id);
2143            if let Some(sha) = thumbnail {
2144                crate::attach::remove_if_unreferenced(state, &root, &sha)?;
2145            }
2146            state.touch(key.clone());
2147            Ok(())
2148        })?;
2149        self.remove_document(&key)
2150    }
2151
2152    /// The keys that changed since `since`, and whether the log still reaches
2153    /// that far back.
2154    pub fn changes_since(&self, since: u64) -> (u64, bool, Vec<String>) {
2155        self.read(|state| {
2156            let stale = since < state.changes_floor();
2157            let keys: Vec<String> = state
2158                .changes
2159                .iter()
2160                .filter(|c| c.seq > since)
2161                .map(|c| c.key.clone())
2162                .collect::<BTreeSet<_>>()
2163                .into_iter()
2164                .collect();
2165            (state.seq, stale, keys)
2166        })
2167    }
2168}
2169
2170// ===========================================================================
2171// The catalog tree
2172// ===========================================================================
2173
2174/// What a category is made from, or changed to. On a change, `None` leaves a
2175/// field as it is.
2176#[derive(Debug, Clone, Default)]
2177pub struct CategoryChange {
2178    pub name: Option<String>,
2179    /// `Some("")` moves the category to the top level.
2180    pub parent: Option<String>,
2181    /// Replaces the category's OWN attribute list.
2182    pub attributes: Option<Vec<AttributeDef>>,
2183}
2184
2185impl Db {
2186    /// Add a category. The whole tree is re-checked inside the write
2187    /// ([`catalog::check_tree`]), so a parent that vanished meanwhile or a
2188    /// key an ancestor gained meanwhile is caught there.
2189    pub fn create_category(&self, id: &str, change: CategoryChange) -> Result<Category, Error> {
2190        let id = catalog::normalize_id(id)?;
2191        let name = change.name.unwrap_or_default().trim().to_string();
2192        if name.is_empty() {
2193            return Err(Error::bad_request("a category needs a name"));
2194        }
2195        let attributes = catalog::check_definitions(change.attributes.unwrap_or_default())?;
2196        let parent = change.parent.unwrap_or_default().trim().to_string();
2197        self.mutate(move |state| {
2198            if catalog::find(&state.categories, &id).is_some() {
2199                return Err(Error::conflict(format!("category '{id}' exists")));
2200            }
2201            let parent = if parent.is_empty() {
2202                String::new()
2203            } else {
2204                catalog::find(&state.categories, &parent)
2205                    .map(|c| c.id.clone())
2206                    .ok_or_else(|| Error::bad_request(format!("there is no category '{parent}'")))?
2207            };
2208            let category = Category { id, name, parent, attributes, created_at: now() };
2209            state.categories.push(category.clone());
2210            catalog::check_tree(&state.categories)?;
2211            Ok(category)
2212        })
2213    }
2214
2215    /// Rename a category, move it, or replace its own attributes.
2216    ///
2217    /// Changing an attribute's type, or dropping one, leaves the values parts
2218    /// already hold where they are: a value that no longer fits is reported
2219    /// at the next release of that part, and a value whose key is gone is
2220    /// inert. Nothing is rewritten behind anyone's back.
2221    pub fn update_category(&self, id: &str, change: CategoryChange) -> Result<Category, Error> {
2222        let attributes = change.attributes.map(catalog::check_definitions).transpose()?;
2223        let id = id.trim().to_string();
2224        self.mutate(move |state| {
2225            let index = state
2226                .categories
2227                .iter()
2228                .position(|c| c.id.eq_ignore_ascii_case(&id))
2229                .ok_or_else(|| Error::not_found(format!("category '{id}'")))?;
2230            if let Some(name) = change.name {
2231                let name = name.trim().to_string();
2232                if name.is_empty() {
2233                    return Err(Error::bad_request("a category needs a name"));
2234                }
2235                state.categories[index].name = name;
2236            }
2237            if let Some(parent) = change.parent {
2238                let parent = parent.trim();
2239                state.categories[index].parent = if parent.is_empty() {
2240                    String::new()
2241                } else {
2242                    catalog::find(&state.categories, parent)
2243                        .map(|c| c.id.clone())
2244                        .ok_or_else(|| Error::bad_request(format!("there is no category '{parent}'")))?
2245                };
2246            }
2247            if let Some(attributes) = attributes {
2248                state.categories[index].attributes = attributes;
2249            }
2250            // A cycle, a too-deep chain, or a key now defined twice along a
2251            // chain — in EITHER direction — is refused here, and the mutation
2252            // rolls back.
2253            catalog::check_tree(&state.categories)?;
2254            Ok(state.categories[index].clone())
2255        })
2256    }
2257
2258    /// Remove a category that nothing uses. A category with children, or with
2259    /// any part filed in it, is refused: deleting it would silently re-file
2260    /// those parts as uncategorized.
2261    pub fn delete_category(&self, id: &str) -> Result<(), Error> {
2262        let id = id.trim().to_string();
2263        self.mutate(move |state| {
2264            let category = catalog::find(&state.categories, &id)
2265                .ok_or_else(|| Error::not_found(format!("category '{id}'")))?
2266                .id
2267                .clone();
2268            if let Some(child) = state.categories.iter().find(|c| c.parent.eq_ignore_ascii_case(&category)) {
2269                return Err(Error::conflict(format!(
2270                    "category '{category}' has a sub-category '{}' — move or delete it first",
2271                    child.id
2272                )));
2273            }
2274            let used = state
2275                .parts
2276                .iter()
2277                .filter(|p| p.category.eq_ignore_ascii_case(&category))
2278                .count();
2279            if used > 0 {
2280                return Err(Error::conflict(format!(
2281                    "category '{category}' holds {used} part{} — move them to another category first",
2282                    if used == 1 { "" } else { "s" }
2283                )));
2284            }
2285            state.categories.retain(|c| c.id != category);
2286            Ok(())
2287        })
2288    }
2289}
2290
2291/// Whether `needle` (lower-case) appears in anything a person would search a
2292/// part by.
2293fn part_matches(categories: &[Category], part: &Part, needle: &str) -> bool {
2294    let hit = |text: &str| text.to_ascii_lowercase().contains(needle);
2295    hit(&part.number)
2296        || hit(&part.name)
2297        || hit(&part.description)
2298        || hit(&part.category)
2299        || hit(&catalog::path_name(categories, &part.category))
2300        || part.tags.iter().any(|t| hit(t))
2301        || part.attributes.values().any(|value| match value {
2302            Value::String(text) => hit(text),
2303            Value::Number(n) => hit(&n.to_string()),
2304            _ => false,
2305        })
2306        || part.sourcing.iter().any(|mp| hit(&mp.mpn) || mp.offers.iter().any(|o| hit(&o.spn)))
2307}
2308
2309/// Refuse a release whose part is missing a required attribute, or holds a
2310/// value its category's schema no longer accepts. Every problem is named at
2311/// once, so a user fixes them in one pass.
2312fn catalog_gate(categories: &[Category], part: &Part) -> Result<(), Error> {
2313    let problems = catalog::release_problems(categories, part);
2314    if problems.is_empty() {
2315        return Ok(());
2316    }
2317    Err(Error::conflict(format!(
2318        "{} cannot release until its catalog values are complete: {}",
2319        part.number,
2320        problems.join("; ")
2321    )))
2322}
2323
2324/// A revision whose review rule is not met cannot release ([`crate::review`]).
2325fn review_gate(state: &State, part: &Part, revision: &Revision) -> Result<(), Error> {
2326    let (rule, _) = crate::review::rule_for(&state.settings, &state.categories, part);
2327    crate::review::release_gate(revision, &rule, &part.number)
2328}
2329
2330fn children_gate(state: &State, part: &Part, revision: &Revision) -> Result<(), Error> {
2331    if !state.settings.require_released_children {
2332        return Ok(());
2333    }
2334    let problems = bom::unreleased_children(state, revision);
2335    if problems.is_empty() {
2336        return Ok(());
2337    }
2338    Err(Error::conflict(format!(
2339        "{} rev {} cannot release until everything it uses is released: {}",
2340        part.number,
2341        revision.label,
2342        problems.join("; ")
2343    )))
2344}
2345
2346/// The first revision whose uses list pins `revision_id` of `part_id`, as
2347/// "number" and "label".
2348fn pinned_by(state: &State, part_id: &str, revision_id: &str) -> Option<(String, String)> {
2349    state.parts.iter().find_map(|parent| {
2350        parent.revisions.iter().find_map(|rev| {
2351            rev.uses
2352                .iter()
2353                .any(|u| u.part == part_id && u.revision == revision_id)
2354                .then(|| (parent.number.clone(), rev.label.clone()))
2355        })
2356    })
2357}
2358
2359/// The two conditions a revision's document and uses list are written under,
2360/// checked together so the refusal says which one failed: the revision is in
2361/// work, and `user` holds its lock.
2362pub fn check_writable(state: &State, user: &User, part_id: &str, revision_id: &str) -> Result<(), Error> {
2363    let part = state.part(part_id).ok_or_else(|| Error::not_found("part"))?;
2364    let revision = part
2365        .revision(revision_id)
2366        .ok_or_else(|| Error::not_found("revision"))?;
2367    if !revision.lifecycle.is_editable() {
2368        return Err(Error::conflict(format!(
2369            "{} revision {} is {} and cannot be written — start a new revision",
2370            part.number,
2371            revision.label,
2372            revision.lifecycle.as_str()
2373        )));
2374    }
2375    match &revision.lock {
2376        None => Err(Error::conflict(format!(
2377            "{} revision {} is not checked out — check it out before saving",
2378            part.number, revision.label
2379        ))),
2380        Some(lock) if lock.user_id != user.id => {
2381            let holder = state
2382                .user(&lock.user_id)
2383                .map(|u| u.username.clone())
2384                .unwrap_or_else(|| "another user".to_string());
2385            Err(Error::conflict(format!(
2386                "{} revision {} is checked out by {holder}",
2387                part.number, revision.label
2388            )))
2389        }
2390        Some(_) => Ok(()),
2391    }
2392}
2393
2394impl Db {
2395    /// Replace a revision's uses list — the call the CAD app makes on save,
2396    /// and the web page's stand-in until it does. Written under the same two
2397    /// conditions as the document ([`check_writable`]), so a released
2398    /// revision's list never changes; checked by [`bom::check_uses`] inside
2399    /// the same lock, so no two concurrent writes can close a cycle between
2400    /// them.
2401    pub fn set_uses(&self, user: &User, part_id: &str, revision_id: &str, body: &Value) -> Result<Vec<Use>, Error> {
2402        let user = user.clone();
2403        let body = body.clone();
2404        self.mutate(move |state| {
2405            check_writable(state, &user, part_id, revision_id)?;
2406            let uses = bom::check_uses(state, part_id, &body)?;
2407            let occurrences = crate::bom_config::capture_occurrences(state, part_id, revision_id, &body)?;
2408            let (_, revision) = find_revision_mut(state, part_id, revision_id)?;
2409            revision.uses = uses.clone();
2410            if let Some(occurrences) = occurrences { revision.occurrences = occurrences; }
2411            crate::bom_config::synchronize_uses(revision);
2412            revision.modified_at = now();
2413            state.touch(crate::identity::document_key(part_id, revision_id));
2414            Ok(uses)
2415        })
2416    }
2417}
2418
2419/// What the release hooks receive.
2420pub(crate) fn release_input(state: &State, part: &Part, revision: &Revision, user: &User) -> Value {
2421    json!({
2422        "part": part,
2423        "sourcing": sourcing::resolved(state, part),
2424        "revision": revision,
2425        "uses": bom::resolved_uses(state, revision),
2426        "unreleased_children": bom::unreleased_children(state, revision),
2427        "document_key": revision.document_key(&part.id),
2428        "user": scripting::user_json(user),
2429    })
2430}
2431
2432/// Whether any part already carries `number` (ASCII case ignored).
2433fn state_has_number(parts: &[Part], number: &str) -> bool {
2434    parts.iter().any(|p| p.number.eq_ignore_ascii_case(number))
2435}
2436
2437/// An admin's pattern, anchored so it must match the WHOLE number: a pattern
2438/// of `\d{5}` should not accept `ABC12345XYZ`.
2439pub fn full_match(pattern: &str) -> Result<regex::Regex, Error> {
2440    regex::Regex::new(&format!("^(?:{pattern})$"))
2441        .map_err(|e| Error::bad_request(format!("'{pattern}' is not a usable pattern: {e}")))
2442}
2443
2444/// The longest part number or revision label the store accepts.
2445pub const MAX_IDENTIFIER: usize = 64;
2446
2447/// A number is text a person can read aloud and type back: not empty, not
2448/// padded, no control characters, and short enough to print on a label.
2449pub fn check_number(number: &str) -> Result<(), Error> {
2450    check_identifier(number, "a part number")
2451}
2452
2453/// A label follows the same rule as a number.
2454pub fn check_label(label: &str) -> Result<(), Error> {
2455    check_identifier(label, "a revision label")
2456}
2457
2458fn check_identifier(text: &str, what: &str) -> Result<(), Error> {
2459    if text.trim().is_empty() {
2460        return Err(Error::bad_request(format!("{what} cannot be empty")));
2461    }
2462    if text.trim() != text {
2463        return Err(Error::bad_request(format!("{what} cannot start or end with a space")));
2464    }
2465    if text.chars().any(char::is_control) {
2466        return Err(Error::bad_request(format!("{what} cannot hold control characters")));
2467    }
2468    if text.chars().count() > MAX_IDENTIFIER {
2469        return Err(Error::bad_request(format!("{what} is at most {MAX_IDENTIFIER} characters")));
2470    }
2471    Ok(())
2472}
2473
2474/// The label offered for a part's next revision: the one after the newest
2475/// revision's, skipping any the part already has. Free-text labels can be
2476/// anything, so the walk may restart at `A`; skipping taken labels is what
2477/// keeps the suggestion usable.
2478pub fn suggest_label(part: &Part) -> String {
2479    let mut candidate = lifecycle::next_revision_label(part.latest().map(|r| r.label.as_str()));
2480    while part.revision_by_label(&candidate).is_some() {
2481        candidate = lifecycle::next_revision_label(Some(&candidate));
2482    }
2483    candidate
2484}
2485
2486/// What a new part is made from. Empty `number` lets the type decide (a
2487/// counter) or leaves it to the script; empty `label` takes the suggestion.
2488#[derive(Debug, Clone, Default)]
2489pub struct PartSpec {
2490    pub part_type: String,
2491    pub number: String,
2492    pub name: String,
2493    pub description: String,
2494    pub category: String,
2495    pub document_class: DocumentClass,
2496    pub label: String,
2497    pub tags: Vec<String>,
2498    /// Attribute values, checked against the category's schema. A draft may
2499    /// leave required ones out; the release gate asks for them.
2500    pub attributes: serde_json::Map<String, Value>,
2501    /// Use `number` and `label` as typed: a script may refuse them but not
2502    /// change them. A family row names its member's number and revision.
2503    pub exact: bool,
2504    /// Where the part comes from in another system (a KiCad `library_id`).
2505    /// Unique among parts of the same type ([`external_ref_clash`]).
2506    pub external_ref: String,
2507    /// The first revision's origin: authored, or imported by a library
2508    /// import. Generated is Generate's alone.
2509    pub origin: crate::model::Origin,
2510    /// Link the new part into its creator's workspace, in this folder (empty:
2511    /// the top), in the same transaction as the part. `None` links nothing.
2512    /// Only [`crate::workspace::link_on_create`] decides it.
2513    pub workspace: Option<String>,
2514}
2515
2516/// The refusal for giving a part of type `part_type` the external reference
2517/// `external_ref` when another part of that type already has it — checked
2518/// inside the store's write lock, so two imports of one library entry at
2519/// once cannot both make a part. `except` is the part being edited. An empty
2520/// reference never clashes.
2521pub fn external_ref_clash(state: &State, part_type: &str, external_ref: &str, except: &str) -> Result<(), Error> {
2522    if external_ref.is_empty() {
2523        return Ok(());
2524    }
2525    match state.parts.iter().find(|p| p.id != except && p.part_type == part_type && p.external_ref == external_ref) {
2526        Some(owner) => Err(Error::conflict(format!(
2527            "external_ref '{external_ref}' is already {} ({}) — look it up with ?external_ref= and use that part",
2528            owner.number, part_type
2529        ))),
2530        None => Ok(()),
2531    }
2532}
2533
2534/// Refuse `origin: generated` from a caller: only Generate makes those.
2535pub fn check_origin(origin: crate::model::Origin) -> Result<(), Error> {
2536    if origin == crate::model::Origin::Generated {
2537        return Err(Error::bad_request("origin 'generated' is set by Generate alone — use authored or imported"));
2538    }
2539    Ok(())
2540}
2541
2542/// Find a revision for mutation, reporting which half was missing.
2543pub(crate) fn find_revision_mut<'a>(
2544    state: &'a mut State,
2545    part_id: &str,
2546    revision_id: &str,
2547) -> Result<(String, &'a mut Revision), Error> {
2548    let part = state.parts.get_mut(&part_id)
2549        .ok_or_else(|| Error::not_found("part"))?;
2550    let number = part.number.clone();
2551    let revision = part
2552        .revision_mut(revision_id)
2553        .ok_or_else(|| Error::not_found("revision"))?;
2554    Ok((number, revision))
2555}