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