Skip to main content

brep_plm/
family.rs

1//! Families, templates and the bake queue on the server (§3.2, round
2//! 8).
3//!
4//! A family's TABLE lives inside the family's CAD document (`familyTable`),
5//! so it is revisioned with the family; the server reads it from a family
6//! revision's document ([`crate::seed`]). Generate writes each row to the
7//! part and the revision the row names, by the §3.2 rules:
8//!
9//! * the part is created when no part carries the row's number, in the
10//!   family's MEMBER PART TYPE (and by that type's numbering mode);
11//! * the revision is created when the part has none with the row's label;
12//! * an existing revision is overwritten when it is writeable — in work, and
13//!   not checked out by someone else — including one made outside the family;
14//! * a row FAILS when its revision exists and is not writeable (and, as in the
15//!   CAD app, when its number or document cannot be used at all). Every other
16//!   row is still generated, and the report names each row's outcome;
17//! * a row whose member already carries this family's stamp with the same
18//!   row fingerprint, the same model fingerprint, and a document nobody has
19//!   edited since, is SKIPPED;
20//! * nothing is released, and nothing is deleted: a member whose row is gone
21//!   is an orphan and stays;
22//! * a member's CATALOG VALUES come from its family: the family part's own
23//!   values, overlaid by the row's values whose column is an attribute of the
24//!   member's category (a family's parameters are a subset of its category's
25//!   attributes). They are type-checked like any write, and a value that does
26//!   not fit fails its row. Re-generating refreshes those keys, even for a row
27//!   whose document is unchanged; values set by hand under other keys are left
28//!   alone.
29//!
30//! A row arrives one of two ways. The CAD app sends it WITH the member
31//! document it baked. The web page (or a bulk setup) sends none, and the
32//! server assembles the member itself — the same document the CAD app would
33//! write — and queues it for a BAKE: the server never links the kernel, so a
34//! headless CAD worker takes the job, checks and rebuilds the document, and
35//! writes it back. A template spin-out is assembled and queued the same way.
36//!
37//! Each row is its own writes. Hooks (a Script-mode number, the revision
38//! label) run outside the store lock through the ordinary create paths; the
39//! final write re-checks writeability inside the lock.
40
41use std::collections::BTreeMap;
42
43use serde::{Deserialize, Serialize};
44use serde_json::Value;
45
46use crate::auth;
47use crate::catalog;
48use crate::db::{check_number, now, write_atomic, Db, PartSpec, State};
49use crate::model::{
50    Bake, BakeStatus, DocumentClass, FamilyStamp, Origin, Part, Revision, TemplateStamp, User,
51};
52use crate::seed::{self, FamilyColumn, FamilyRow};
53use crate::Error;
54
55/// How long a worker's claim on a bake job holds before another worker may
56/// take the job over. A crashed worker must not strand a job forever; a
57/// person can also hand a job back at any time ([`Db::retry_bake`]).
58pub const BAKE_LEASE: u64 = 15 * 60;
59
60// ===========================================================================
61// Shapes
62// ===========================================================================
63
64/// One row to generate. From the CAD app it carries the member `document`;
65/// without one the server assembles it and queues a bake.
66#[derive(Debug, Clone, Default, Deserialize)]
67pub struct GenerateRow {
68    pub number: String,
69    #[serde(default)]
70    pub revision: String,
71    #[serde(default)]
72    pub description: String,
73    #[serde(default)]
74    pub values: BTreeMap<String, String>,
75    #[serde(default)]
76    pub document: Option<Value>,
77}
78
79/// What to generate.
80#[derive(Debug, Clone, Default, Deserialize)]
81pub struct GenerateRequest {
82    /// The family revision (id or label) whose document is the seed. Empty is
83    /// the newest revision.
84    #[serde(default)]
85    pub family_revision: String,
86    /// The rows. Absent: every row of the family revision's own table.
87    #[serde(default)]
88    pub rows: Option<Vec<GenerateRow>>,
89    /// Generate only these part numbers (from `rows` or the table). Empty is
90    /// all of them.
91    #[serde(default)]
92    pub only: Vec<String>,
93}
94
95/// What Generate did with one row.
96#[derive(Debug, Clone, Serialize)]
97pub struct RowResult {
98    pub number: String,
99    /// The revision label written (or that would have been).
100    pub revision: String,
101    /// `written`, `skipped` or `failed`.
102    pub status: &'static str,
103    pub reason: String,
104    pub part_id: Option<String>,
105    pub revision_id: Option<String>,
106    pub created_part: bool,
107    pub created_revision: bool,
108    /// The member was assembled by the server and waits for a bake.
109    pub bake: bool,
110}
111
112/// What Generate did, one entry per row in order.
113#[derive(Debug, Clone, Serialize)]
114pub struct GenerateReport {
115    pub family: String,
116    pub family_revision: String,
117    pub rows: Vec<RowResult>,
118    pub written: usize,
119    pub skipped: usize,
120    pub failed: usize,
121}
122
123/// The family page: the table of one family revision and what each row's
124/// member looks like now.
125#[derive(Debug, Clone, Serialize)]
126pub struct FamilyView {
127    pub family_id: String,
128    pub number: String,
129    pub name: String,
130    pub revision_id: String,
131    pub revision_label: String,
132    pub revision_state: &'static str,
133    /// Whether this family revision can take a table import.
134    pub revision_writeable: bool,
135    pub revisions: Vec<RevisionChoice>,
136    pub has_document: bool,
137    /// The part type new members are created in, and its numbering mode.
138    pub member_part_type: String,
139    pub member_part_type_mode: String,
140    pub columns: Vec<FamilyColumn>,
141    pub rows: Vec<RowView>,
142    /// Members this family generated whose row is gone from this table.
143    pub orphans: Vec<MemberView>,
144}
145
146#[derive(Debug, Clone, Serialize)]
147pub struct RevisionChoice {
148    pub id: String,
149    pub label: String,
150    pub lifecycle: &'static str,
151}
152
153/// One table row and its member.
154#[derive(Debug, Clone, Serialize)]
155pub struct RowView {
156    pub part_number: String,
157    pub revision: String,
158    pub description: String,
159    pub values: BTreeMap<String, String>,
160    /// `new` (Generate would create the part or the revision), `current`
161    /// (generated from this row and this model, untouched), `stale` (the row
162    /// or the model changed since), `unstamped` (the revision exists but this
163    /// family did not write it; Generate would overwrite it), or `blocked`
164    /// (Generate would write it, and cannot).
165    pub status: &'static str,
166    pub note: String,
167    pub member: Option<MemberView>,
168}
169
170/// A member part, as the family page shows it.
171#[derive(Debug, Clone, Serialize)]
172pub struct MemberView {
173    pub part_id: String,
174    pub number: String,
175    pub name: String,
176    /// The revision the row targets (or, for an orphan, the newest one this
177    /// family wrote). Empty when the row names a revision not yet created.
178    pub revision_id: String,
179    pub revision_label: String,
180    pub lifecycle: String,
181    pub writeable: bool,
182    pub locked_by: Option<String>,
183    /// The label of the family revision it was generated from, when this
184    /// family generated it.
185    pub generated_from: Option<String>,
186    pub stale_values: bool,
187    pub stale_model: bool,
188    /// Its document changed since Generate (or its bake) wrote it.
189    pub hand_edited: bool,
190    pub bake: Option<&'static str>,
191    pub bake_error: String,
192}
193
194/// The result of a CSV import into a family table.
195#[derive(Debug, Clone, Serialize)]
196pub struct ImportReport {
197    pub revision_id: String,
198    pub revision_label: String,
199    pub added: usize,
200    pub updated: usize,
201    pub columns_added: Vec<String>,
202    pub rows: usize,
203}
204
205/// A template spin-out.
206#[derive(Debug, Clone, Default, Deserialize)]
207pub struct SpinOutRequest {
208    pub name: String,
209    #[serde(default)]
210    pub number: String,
211    /// The part type the copy is created in. Empty: the template's member
212    /// part type, else the template's own.
213    #[serde(default)]
214    pub part_type: String,
215    #[serde(default)]
216    pub description: String,
217    /// Input name -> expression source. An input left out takes the
218    /// template's own value.
219    #[serde(default)]
220    pub values: BTreeMap<String, String>,
221    /// The template revision (id or label). Empty: the released one, else the
222    /// newest.
223    #[serde(default)]
224    pub template_revision: String,
225    /// The creator's workspace folder the new part is linked into; empty is
226    /// the top ([`crate::workspace::link_on_create`]).
227    #[serde(default)]
228    pub workspace_folder: String,
229}
230
231/// The template page's form: the inputs a template marks, with defaults.
232#[derive(Debug, Clone, Serialize)]
233pub struct TemplateView {
234    pub template_id: String,
235    pub number: String,
236    pub revision_id: String,
237    pub revision_label: String,
238    pub has_document: bool,
239    pub member_part_type: String,
240    pub member_part_type_mode: String,
241    pub inputs: Vec<TemplateInputView>,
242    /// Parts spun out of this template, newest first.
243    pub copies: Vec<CopyView>,
244}
245
246#[derive(Debug, Clone, Serialize)]
247pub struct TemplateInputView {
248    #[serde(flatten)]
249    pub input: seed::TemplateInput,
250    pub default: String,
251}
252
253#[derive(Debug, Clone, Serialize)]
254pub struct CopyView {
255    pub part_id: String,
256    pub number: String,
257    pub name: String,
258    pub values: BTreeMap<String, String>,
259    pub created_at: u64,
260    pub bake: Option<&'static str>,
261}
262
263/// One job in the bake queue. Its id is the readable part/revision document key.
264#[derive(Debug, Clone, Serialize)]
265pub struct BakeJob {
266    pub expected_hash: Option<String>,
267    pub id: String,
268    pub part_id: String,
269    pub number: String,
270    pub name: String,
271    pub revision_label: String,
272    pub lifecycle: &'static str,
273    pub status: &'static str,
274    pub reason: String,
275    pub requested_by: String,
276    pub requested_at: u64,
277    pub claimed_by: Option<String>,
278    pub claimed_at: Option<u64>,
279    /// When another worker may take a claimed job over.
280    pub lease_expires_at: Option<u64>,
281    pub attempts: u32,
282    pub error: String,
283    pub finished_at: Option<u64>,
284    pub document_key: String,
285    /// `family`, `template`, `resave`, or empty.
286    pub source: &'static str,
287    /// Who has the revision checked out. A resave may refresh the requester's
288    /// own checkout; another user's checkout waits for check-in.
289    pub locked_by: Option<String>,
290    pub waiting_on_checkout: bool,
291}
292
293#[derive(Debug, Default, Serialize)]
294pub struct BakeCounts {
295    pub pending: usize,
296    pub claimed: usize,
297    pub done: usize,
298    pub failed: usize,
299    pub waiting: usize,
300}
301
302#[derive(Debug, Serialize)]
303pub struct BakePage {
304    pub jobs: Vec<BakeJob>,
305    pub total: usize,
306    pub offset: usize,
307    pub next: Option<usize>,
308    pub counts: BakeCounts,
309}
310
311// ===========================================================================
312// Reading a seed
313// ===========================================================================
314
315/// A family's or template's part, the chosen revision, and its document.
316struct Seed {
317    part: Part,
318    revision: Revision,
319    document: Option<Value>,
320}
321
322impl Db {
323    /// The seed `key` (id or number) of class `class`, at `revision` (id or
324    /// label; empty picks `default`).
325    fn seed(
326        &self,
327        key: &str,
328        class: DocumentClass,
329        revision: &str,
330        default: impl Fn(&Part) -> Option<&Revision>,
331    ) -> Result<Seed, Error> {
332        let (part, revision) = self.read(|state| {
333            let part = state.part_by_id_or_number(key).ok_or_else(|| Error::not_found("part"))?;
334            if part.document_class != class {
335                return Err(Error::bad_request(format!(
336                    "{} is a {} part, not a {}",
337                    part.number,
338                    part.document_class.as_str(),
339                    class.as_str()
340                )));
341            }
342            let revision = revision.trim();
343            let chosen = if revision.is_empty() {
344                default(part)
345            } else {
346                part.revision(revision).or_else(|| part.revision_by_label(revision))
347            }
348            .ok_or_else(|| Error::not_found("revision"))?;
349            Ok((part.clone(), chosen.clone()))
350        })?;
351        let document = match self.read_document(&revision.document_key(&part.id))? {
352            Some(text) => Some(
353                serde_json::from_str::<Value>(&text)
354                    .ok()
355                    .filter(Value::is_object)
356                    .ok_or_else(|| {
357                        Error::conflict(format!(
358                            "{} revision {} holds a document that is not a JSON object",
359                            part.number, revision.label
360                        ))
361                    })?,
362            ),
363            None => None,
364        };
365        Ok(Seed { part, revision, document })
366    }
367
368    fn seed_document(seed: &Seed) -> Result<&Value, Error> {
369        seed.document.as_ref().ok_or_else(|| {
370            Error::conflict(format!(
371                "{} revision {} has no document yet — save the {}'s model from the CAD app, or paste it into the revision's document",
372                seed.part.number,
373                seed.revision.label,
374                seed.part.document_class.as_str()
375            ))
376        })
377    }
378}
379
380/// The part type a seed's generated parts go into.
381fn member_type(part: &Part) -> String {
382    if part.member_part_type.is_empty() {
383        part.part_type.clone()
384    } else {
385        part.member_part_type.clone()
386    }
387}
388
389fn mode_of(state: &State, part_type: &str) -> String {
390    state.part_type(part_type).map(|t| t.mode.kind().to_string()).unwrap_or_default()
391}
392
393fn user_name(state: &State, id: &str) -> String {
394    state
395        .user(id)
396        .map(|u| if u.display_name.is_empty() { u.username.clone() } else { u.display_name.clone() })
397        .unwrap_or_else(|| "another user".into())
398}
399
400/// Whether `user` may write `revision` without a checkout of their own:
401/// it is in work, and nobody ELSE holds it.
402fn writeable_by(revision: &Revision, user_id: &str) -> bool {
403    revision.lifecycle.is_editable() && revision.lock.as_ref().is_none_or(|l| l.user_id == user_id)
404}
405
406/// Why `user` may not write `revision`, in words, if they may not.
407fn not_writeable(state: &State, part: &Part, revision: &Revision, user_id: &str) -> Option<String> {
408    if !revision.lifecycle.is_editable() {
409        return Some(format!(
410            "{} revision {} is {} and cannot be written — name a new revision in the row",
411            part.number,
412            revision.label,
413            revision.lifecycle.as_str()
414        ));
415    }
416    match &revision.lock {
417        Some(lock) if lock.user_id != user_id => Some(format!(
418            "{} revision {} is checked out by {}",
419            part.number,
420            revision.label,
421            user_name(state, &lock.user_id)
422        )),
423        _ => None,
424    }
425}
426
427fn bake_name(revision: &Revision) -> Option<&'static str> {
428    revision.bake.as_ref().map(|b| b.status.as_str())
429}
430
431fn new_bake(user: &User, reason: String) -> Bake {
432    Bake {
433        resave_hash: None,
434        status: BakeStatus::Pending,
435        reason,
436        requested_by: user.id.clone(),
437        requested_at: now(),
438        claimed_by: None,
439        claimed_at: None,
440        attempts: 0,
441        error: String::new(),
442        finished_by: None,
443        finished_at: None,
444    }
445}
446
447// ===========================================================================
448// The family page
449// ===========================================================================
450
451impl Db {
452    /// The family page for `key` at `revision` (empty: the newest).
453    pub fn family_view(&self, viewer: &User, key: &str, revision: &str) -> Result<FamilyView, Error> {
454        let seed = self.seed(key, DocumentClass::Family, revision, Part::latest)?;
455        let table = seed.document.as_ref().map(seed::read_table).unwrap_or_default();
456        let history = seed.document.as_ref().map(seed::history_hash);
457        let family = &seed.part;
458        self.read(|state| {
459            let member_view = |part: &Part, revision: Option<&Revision>| -> MemberView {
460                let stamp = revision.and_then(|r| r.family.as_ref()).filter(|s| s.family_part == family.id);
461                MemberView {
462                    part_id: part.id.clone(),
463                    number: part.number.clone(),
464                    name: part.name.clone(),
465                    revision_id: revision.map(|r| r.id.clone()).unwrap_or_default(),
466                    revision_label: revision.map(|r| r.label.clone()).unwrap_or_default(),
467                    lifecycle: revision.map(|r| r.lifecycle.as_str().to_string()).unwrap_or_default(),
468                    writeable: revision.is_some_and(|r| writeable_by(r, &viewer.id)),
469                    locked_by: revision
470                        .and_then(|r| r.lock.as_ref())
471                        .map(|l| user_name(state, &l.user_id)),
472                    generated_from: stamp.map(|s| {
473                        family
474                            .revision(&s.family_revision)
475                            .map(|r| r.label.clone())
476                            .unwrap_or_else(|| "a deleted revision".into())
477                    }),
478                    stale_values: false,
479                    stale_model: stamp.is_some_and(|s| history.as_ref().is_some_and(|h| &s.history_hash != h)),
480                    hand_edited: stamp
481                        .zip(revision)
482                        .is_some_and(|(s, r)| r.content_hash != s.generated_hash),
483                    bake: revision.and_then(bake_name),
484                    bake_error: revision
485                        .and_then(|r| r.bake.as_ref())
486                        .map(|b| b.error.clone())
487                        .unwrap_or_default(),
488                }
489            };
490
491            let mut rows = Vec::new();
492            for raw in &table.rows {
493                let row = seed::effective_row(&table, raw);
494                let number = row.part_number.trim();
495                let label = row.revision.trim();
496                let part = state.part_with_number(number);
497                let (status, note, member) = match part {
498                    None => ("new", "Generate creates this part".to_string(), None),
499                    Some(part) if part.document_class != DocumentClass::Normal => (
500                        "blocked",
501                        format!("{number} is a {} part — a member is a normal part", part.document_class.as_str()),
502                        Some(member_view(part, part.latest())),
503                    ),
504                    Some(part) => {
505                        let target = if label.is_empty() { part.latest() } else { part.revision_by_label(label) };
506                        match target {
507                            None => (
508                                "new",
509                                format!("Generate creates revision {label}"),
510                                Some(member_view(part, None)),
511                            ),
512                            Some(revision) => {
513                                let mut view = member_view(part, Some(revision));
514                                let stamp = revision.family.as_ref().filter(|s| s.family_part == family.id);
515                                view.stale_values = stamp.is_some_and(|s| s.values_hash != seed::row_hash(&row));
516                                let (status, note) = match stamp {
517                                    Some(_) if !view.stale_values && !view.stale_model && !view.hand_edited => {
518                                        ("current", String::new())
519                                    }
520                                    Some(_) => {
521                                        let mut why = Vec::new();
522                                        if view.stale_values {
523                                            why.push("the row changed");
524                                        }
525                                        if view.stale_model {
526                                            why.push("the family's model changed");
527                                        }
528                                        if view.hand_edited {
529                                            why.push("the member was edited by hand");
530                                        }
531                                        ("stale", format!("{} since it was generated", why.join(", ")))
532                                    }
533                                    None => (
534                                        "unstamped",
535                                        "this family did not write this revision — Generate overwrites it".into(),
536                                    ),
537                                };
538                                match not_writeable(state, part, revision, &viewer.id).filter(|_| status != "current") {
539                                    Some(why) => ("blocked", why, Some(view)),
540                                    None => (status, note, Some(view)),
541                                }
542                            }
543                        }
544                    }
545                };
546                rows.push(RowView {
547                    part_number: raw.part_number.clone(),
548                    revision: raw.revision.clone(),
549                    description: raw.description.clone(),
550                    values: raw.values.clone(),
551                    status,
552                    note,
553                    member,
554                });
555            }
556
557            let in_table = |number: &str| {
558                table.rows.iter().any(|r| r.part_number.trim().eq_ignore_ascii_case(number))
559            };
560            let orphans = state
561                .parts
562                .iter()
563                .filter(|p| !in_table(&p.number))
564                .filter_map(|p| {
565                    let newest = p
566                        .revisions
567                        .iter()
568                        .rev()
569                        .find(|r| r.family.as_ref().is_some_and(|s| s.family_part == family.id))?;
570                    Some(member_view(p, Some(newest)))
571                })
572                .collect();
573
574            let current = family.revision(&seed.revision.id).unwrap_or(&seed.revision);
575            let kind = member_type(family);
576            Ok(FamilyView {
577                family_id: family.id.clone(),
578                number: family.number.clone(),
579                name: family.name.clone(),
580                revision_id: current.id.clone(),
581                revision_label: current.label.clone(),
582                revision_state: current.lifecycle.as_str(),
583                revision_writeable: writeable_by(current, &viewer.id),
584                revisions: family
585                    .revisions
586                    .iter()
587                    .map(|r| RevisionChoice { id: r.id.clone(), label: r.label.clone(), lifecycle: r.lifecycle.as_str() })
588                    .collect(),
589                has_document: seed.document.is_some(),
590                member_part_type_mode: mode_of(state, &kind),
591                member_part_type: kind,
592                columns: table.columns.clone(),
593                rows,
594                orphans,
595            })
596        })
597    }
598}
599
600// ===========================================================================
601// Generate
602// ===========================================================================
603
604/// What every row of one Generate shares.
605struct Context<'a> {
606    family: &'a Part,
607    family_revision: &'a Revision,
608    document: &'a Value,
609    family_file: String,
610    history: String,
611    member_type: String,
612}
613
614impl Db {
615    /// Generate a family's members (see the module header for the rules).
616    pub fn generate(&self, user: &User, key: &str, request: GenerateRequest) -> Result<GenerateReport, Error> {
617        let seed = self.seed(key, DocumentClass::Family, &request.family_revision, Part::latest)?;
618        let document = Self::seed_document(&seed)?;
619        let table = seed::read_table(document);
620        let context = Context {
621            family: &seed.part,
622            family_revision: &seed.revision,
623            document,
624            family_file: format!("{}.fbrep", seed.part.number),
625            history: seed::history_hash(document),
626            member_type: member_type(&seed.part),
627        };
628        let rows: Vec<GenerateRow> = match request.rows {
629            Some(rows) => rows,
630            None => table
631                .rows
632                .iter()
633                .map(|raw| {
634                    let row = seed::effective_row(&table, raw);
635                    GenerateRow {
636                        number: row.part_number,
637                        revision: row.revision,
638                        description: row.description,
639                        values: row.values,
640                        document: None,
641                    }
642                })
643                .collect(),
644        };
645        let only: Vec<String> = request.only.iter().map(|n| n.trim().to_lowercase()).collect();
646
647        let mut report = GenerateReport {
648            family: seed.part.number.clone(),
649            family_revision: seed.revision.label.clone(),
650            rows: Vec::new(),
651            written: 0,
652            skipped: 0,
653            failed: 0,
654        };
655        let mut seen: BTreeMap<String, usize> = BTreeMap::new();
656        for (index, row) in rows.into_iter().enumerate() {
657            let key = row.number.trim().to_lowercase();
658            if !only.is_empty() && !only.contains(&key) {
659                continue;
660            }
661            let result = match seen.get(&key) {
662                Some(first) => failed(&row, format!("the same part number as row {}", first + 1)),
663                None => {
664                    seen.insert(key, index);
665                    self.generate_row(user, &context, row)
666                }
667            };
668            match result.status {
669                "written" => report.written += 1,
670                "skipped" => report.skipped += 1,
671                _ => report.failed += 1,
672            }
673            report.rows.push(result);
674        }
675        Ok(report)
676    }
677
678    fn generate_row(&self, user: &User, context: &Context, row: GenerateRow) -> RowResult {
679        let number = row.number.trim().to_string();
680        if let Err(error) = check_number(&number) {
681            return failed(&row, error.message);
682        }
683        let member_row = FamilyRow {
684            part_number: number.clone(),
685            revision: row.revision.trim().to_string(),
686            description: row.description.trim().to_string(),
687            values: row
688                .values
689                .iter()
690                .filter(|(_, v)| !v.trim().is_empty())
691                .map(|(k, v)| (k.trim().to_string(), v.trim().to_string()))
692                .collect(),
693        };
694        let values_hash = seed::row_hash(&member_row);
695
696        // The document: the CAD app's, or assembled here and queued to bake.
697        let assembled = row.document.is_none();
698        let document = match &row.document {
699            Some(document) => {
700                if !document.is_object() {
701                    return failed(&row, "the member document must be a JSON object".into());
702                }
703                if let Some(class) = seed::document_class(document) {
704                    return failed(&row, format!("the document sent is a {class} — a member is a normal part"));
705                }
706                document.clone()
707            }
708            None => seed::member_document(context.document, &context.family_file, &member_row),
709        };
710        let body = document.to_string();
711
712        // The part the row names, created if missing.
713        let existing = self.read(|state| state.part_with_number(&number).cloned());
714        let family_category = self.read(|state| {
715            catalog::find(&state.categories, &context.family.category).map(|c| c.id.clone())
716        });
717        // The member's catalog values, checked BEFORE anything is created, so
718        // a row whose value does not fit leaves nothing half-made.
719        let member_category = match &existing {
720            Some(part) => part.category.clone(),
721            None => family_category.clone().unwrap_or_default(),
722        };
723        let values = match self.read(|state| member_values(state, context.family, &member_category, &member_row.values)) {
724            Ok(values) => values,
725            Err(reason) => return failed(&row, reason),
726        };
727        let mut result = RowResult {
728            number: number.clone(),
729            revision: member_row.revision.clone(),
730            status: "failed",
731            reason: String::new(),
732            part_id: None,
733            revision_id: None,
734            created_part: false,
735            created_revision: false,
736            bake: false,
737        };
738        let part = match existing {
739            Some(part) if part.document_class != DocumentClass::Normal => {
740                result.reason = format!("{number} is a {} part — a member is a normal part", part.document_class.as_str());
741                result.part_id = Some(part.id);
742                return result;
743            }
744            Some(part) => part,
745            None => {
746                let category = family_category;
747                let name = if member_row.description.is_empty() {
748                    format!("{} {number}", context.family.name)
749                } else {
750                    member_row.description.clone()
751                };
752                let spec = PartSpec {
753                    part_type: context.member_type.clone(),
754                    number: number.clone(),
755                    name,
756                    description: member_row.description.clone(),
757                    category: category.unwrap_or_default(),
758                    document_class: DocumentClass::Normal,
759                    label: member_row.revision.clone(),
760                    tags: context.family.tags.clone(),
761                    exact: true,
762                    ..PartSpec::default()
763                };
764                match self.create_part_with(user, &spec) {
765                    Ok(part) => {
766                        result.created_part = true;
767                        result.created_revision = true;
768                        part
769                    }
770                    Err(error) => {
771                        result.reason = error.message;
772                        return result;
773                    }
774                }
775            }
776        };
777        result.part_id = Some(part.id.clone());
778
779        // The revision the row names, created if missing.
780        let target = if result.created_part {
781            part.revisions.first().cloned()
782        } else if member_row.revision.is_empty() {
783            part.latest().cloned()
784        } else {
785            part.revision_by_label(&member_row.revision).cloned()
786        };
787        let revision = match target {
788            Some(revision) => revision,
789            None => match self.create_revision_as(user, &part.id, &member_row.revision, true, Origin::Authored) {
790                Ok(revision) => {
791                    result.created_revision = true;
792                    revision
793                }
794                Err(error) => {
795                    result.reason = error.message;
796                    return result;
797                }
798            },
799        };
800        result.revision = revision.label.clone();
801        result.revision_id = Some(revision.id.clone());
802
803        // Unchanged: this family's stamp, the same row, the same model, and a
804        // document nobody has touched since. A baked document from the CAD
805        // app still lands on a member waiting for its bake.
806        if !result.created_revision {
807            let unchanged = revision.family.as_ref().is_some_and(|stamp| {
808                stamp.family_part == context.family.id
809                    && stamp.values_hash == values_hash
810                    && stamp.history_hash == context.history
811                    && stamp.generated_hash == revision.content_hash
812            });
813            if unchanged && !(revision.needs_bake() && !assembled) {
814                result.status = "skipped";
815                result.reason = "unchanged since it was last generated".into();
816                // The document is current; the catalog values may not be — the
817                // family's own values can change without the row or the model.
818                let stale = self.read(|state| {
819                    state.part(&part.id).is_some_and(|p| {
820                        let mut refreshed = p.attributes.clone();
821                        catalog::apply_values(&state.categories, &p.category, &mut refreshed, &values).is_ok()
822                            && refreshed != p.attributes
823                    })
824                });
825                if stale {
826                    match self.update_part(&part.id, &Value::Object(serde_json::Map::from_iter([(
827                        "attributes".to_string(),
828                        Value::Object(values),
829                    )]))) {
830                        Ok(_) => result.reason.push_str("; its catalog values were refreshed from the family"),
831                        Err(error) => {
832                            result.reason.push_str(&format!("; its catalog values were not refreshed: {}", error.message))
833                        }
834                    }
835                }
836                return result;
837            }
838        }
839
840        let stamp = FamilyStamp {
841            family_part: context.family.id.clone(),
842            family_revision: context.family_revision.id.clone(),
843            values: member_row.values.clone(),
844            description: member_row.description.clone(),
845            values_hash,
846            history_hash: context.history.clone(),
847            generated_hash: String::new(),
848            generated_by: user.id.clone(),
849            generated_at: now(),
850        };
851        let bake = assembled.then(|| {
852            new_bake(
853                user,
854                format!("generated from family {} revision {}", context.family.number, context.family_revision.label),
855            )
856        });
857        match self.write_generated(user, &part.id, &revision.id, &body, Written::Family(stamp), bake, &values) {
858            Ok(()) => {
859                result.status = "written";
860                result.bake = assembled;
861            }
862            Err(error) => result.reason = error.message,
863        }
864        result
865    }
866
867    /// Write a generated document into a revision, with its stamp and its
868    /// bake, in ONE locked write that re-checks the revision is writeable by
869    /// `user` — someone may have released it or checked it out since the row
870    /// was looked at.
871    fn write_generated(
872        &self,
873        user: &User,
874        part_id: &str,
875        revision_id: &str,
876        body: &str,
877        written: Written,
878        bake: Option<Bake>,
879        values: &serde_json::Map<String, Value>,
880    ) -> Result<(), Error> {
881        let values = values.clone();
882        let key = crate::identity::document_key(part_id, revision_id);
883        let path = self.document_path(&key)?;
884        let hash = auth::content_hash(body);
885        let size = body.len() as u64;
886        let user_id = user.id.clone();
887        self.mutate(move |state| {
888            let part = state.part(part_id).ok_or_else(|| Error::not_found("part"))?;
889            let revision = part.revision(revision_id).ok_or_else(|| Error::not_found("revision"))?;
890            if let Some(why) = not_writeable(state, part, revision, &user_id) {
891                return Err(Error::conflict(why));
892            }
893            // The catalog values first: they can still refuse (the tree may
894            // have changed since the row was checked), and nothing may be on
895            // disk when they do.
896            if !values.is_empty() {
897                let State { parts, categories, .. } = &mut *state;
898                let part = parts.get_mut(&part_id).ok_or_else(|| Error::not_found("part"))?;
899                let category = part.category.clone();
900                catalog::apply_values(categories, &category, &mut part.attributes, &values)
901                    .map_err(|e| Error::bad_request(format!("catalog value: {}", e.message)))?;
902            }
903            let revision = crate::db::find_revision_mut(state, part_id, revision_id)?.1;
904            if let Some(parent) = path.parent() {
905                std::fs::create_dir_all(parent).map_err(Error::internal)?;
906            }
907            revision.has_geometry = crate::geometry::contains_geometry(body);
908            revision.geometry_content_hash = hash.clone();
909            write_atomic(&path, body).map_err(Error::internal)?;
910            revision.content_hash = hash.clone();
911            revision.size = size;
912            revision.modified_at = now();
913            revision.origin = Origin::Generated;
914            match written {
915                Written::Family(mut stamp) => {
916                    stamp.generated_hash = hash;
917                    revision.family = Some(stamp);
918                }
919                Written::Template(stamp) => revision.template = Some(stamp),
920            }
921            match bake {
922                Some(bake) => revision.bake = Some(bake),
923                None => {
924                    // The CAD app's own document: whatever bake was waiting
925                    // is answered by it.
926                    if revision.needs_bake() {
927                        if let Some(old) = revision.bake.as_mut() {
928                            old.status = BakeStatus::Done;
929                            old.error = "superseded by a document from the CAD app".into();
930                            old.finished_by = Some(user_id.clone());
931                            old.finished_at = Some(now());
932                        }
933                    }
934                }
935            }
936            crate::review::document_changed(state, part_id, revision_id);
937            state.touch(key);
938            Ok(())
939        })
940    }
941}
942
943/// The catalog values a member takes from its family (see the module header):
944/// the family part's own values for keys the member's `category` defines,
945/// overlaid by the row's values whose column names such a key. Checked here
946/// on a scratch copy, so a value that does not fit is the row's failure.
947fn member_values(
948    state: &State,
949    family: &Part,
950    category: &str,
951    row: &BTreeMap<String, String>,
952) -> Result<serde_json::Map<String, Value>, String> {
953    let mut out = serde_json::Map::new();
954    let Some(found) = catalog::find(&state.categories, category) else {
955        return Ok(out);
956    };
957    let schema = catalog::schema(&state.categories, &found.id).map_err(|e| e.message)?;
958    for effective in &schema {
959        if let Some(value) = family.attributes.get(&effective.def.key) {
960            out.insert(effective.def.key.clone(), value.clone());
961        }
962    }
963    for (column, value) in row {
964        if let Some(effective) = schema.iter().find(|e| e.def.key.eq_ignore_ascii_case(column.trim())) {
965            out.insert(effective.def.key.clone(), Value::String(value.trim().to_string()));
966        }
967    }
968    let mut scratch = BTreeMap::new();
969    catalog::apply_values(&state.categories, &found.id, &mut scratch, &out)
970        .map_err(|e| format!("catalog value: {}", e.message))?;
971    Ok(out)
972}
973
974/// Which stamp a generated write records.
975enum Written {
976    Family(FamilyStamp),
977    Template(TemplateStamp),
978}
979
980fn failed(row: &GenerateRow, reason: String) -> RowResult {
981    RowResult {
982        number: row.number.trim().to_string(),
983        revision: row.revision.trim().to_string(),
984        status: "failed",
985        reason,
986        part_id: None,
987        revision_id: None,
988        created_part: false,
989        created_revision: false,
990        bake: false,
991    }
992}
993
994// ===========================================================================
995// CSV import into a family table
996// ===========================================================================
997
998impl Db {
999    /// Merge CSV rows into the table of a family revision in work (`revision`,
1000    /// or else the newest one in work), writing the family's DOCUMENT — the
1001    /// table lives there. A row whose part number the table already has is
1002    /// updated (its revision and description when the CSV has those columns,
1003    /// and its value in every column the CSV has; an empty cell clears the
1004    /// value back to the family's own); a new number is appended. Expression
1005    /// columns the table lacks are added. Nothing is generated here.
1006    pub fn import_table(&self, user: &User, key: &str, revision: &str, csv: &str) -> Result<ImportReport, Error> {
1007        let parsed = seed::parse_csv(csv).map_err(Error::bad_request)?;
1008        let seed = self.seed(key, DocumentClass::Family, revision, |part| {
1009            part.revisions.iter().rev().find(|r| r.lifecycle.is_editable())
1010        })?;
1011        let mut document = Self::seed_document(&seed)?.clone();
1012        let mut table = seed::read_table(&document);
1013        let mut report = ImportReport {
1014            revision_id: seed.revision.id.clone(),
1015            revision_label: seed.revision.label.clone(),
1016            added: 0,
1017            updated: 0,
1018            columns_added: Vec::new(),
1019            rows: 0,
1020        };
1021        for column in &parsed.columns {
1022            if !table.columns.iter().any(|c| &c.name == column) {
1023                table.columns.push(FamilyColumn { name: column.clone(), label: String::new() });
1024                report.columns_added.push(column.clone());
1025            }
1026        }
1027        for incoming in parsed.rows {
1028            match table
1029                .rows
1030                .iter_mut()
1031                .find(|r| r.part_number.trim().eq_ignore_ascii_case(&incoming.part_number))
1032            {
1033                Some(existing) => {
1034                    if parsed.has_revision {
1035                        existing.revision = incoming.revision;
1036                    }
1037                    if parsed.has_description {
1038                        existing.description = incoming.description;
1039                    }
1040                    for column in &parsed.columns {
1041                        match incoming.values.get(column) {
1042                            Some(value) => existing.values.insert(column.clone(), value.clone()),
1043                            None => existing.values.remove(column),
1044                        };
1045                    }
1046                    report.updated += 1;
1047                }
1048                None => {
1049                    table.rows.push(incoming);
1050                    report.added += 1;
1051                }
1052            }
1053        }
1054        report.rows = table.rows.len();
1055        seed::write_table(&mut document, &table).map_err(Error::bad_request)?;
1056        self.write_seed(user, &seed.part.id, &seed.revision.id, &document.to_string())?;
1057        Ok(report)
1058    }
1059
1060    /// Write a seed's own document (its table changed), re-checking inside
1061    /// the lock that `user` may write the revision.
1062    fn write_seed(&self, user: &User, part_id: &str, revision_id: &str, body: &str) -> Result<(), Error> {
1063        let key = crate::identity::document_key(part_id, revision_id);
1064        let path = self.document_path(&key)?;
1065        let hash = auth::content_hash(body);
1066        let size = body.len() as u64;
1067        let user_id = user.id.clone();
1068        self.mutate(move |state| {
1069            let part = state.part(part_id).ok_or_else(|| Error::not_found("part"))?;
1070            let revision = part.revision(revision_id).ok_or_else(|| Error::not_found("revision"))?;
1071            if let Some(why) = not_writeable(state, part, revision, &user_id) {
1072                return Err(Error::conflict(why.replace("name a new revision in the row", "start a new revision of the family")));
1073            }
1074            let revision = crate::db::find_revision_mut(state, part_id, revision_id)?.1;
1075            if let Some(parent) = path.parent() {
1076                std::fs::create_dir_all(parent).map_err(Error::internal)?;
1077            }
1078            revision.has_geometry = crate::geometry::contains_geometry(body);
1079            revision.geometry_content_hash = hash.clone();
1080            write_atomic(&path, body).map_err(Error::internal)?;
1081            revision.content_hash = hash;
1082            revision.size = size;
1083            revision.modified_at = now();
1084            crate::review::document_changed(state, part_id, revision_id);
1085            state.touch(key);
1086            Ok(())
1087        })
1088    }
1089}
1090
1091// ===========================================================================
1092// Templates
1093// ===========================================================================
1094
1095impl Db {
1096    /// The template page for `key` at `revision` (empty: the released one,
1097    /// else the newest).
1098    pub fn template_view(&self, key: &str, revision: &str) -> Result<TemplateView, Error> {
1099        let seed = self.seed(key, DocumentClass::Template, revision, |p| p.current_release().or(p.latest()))?;
1100        let inputs = seed
1101            .document
1102            .as_ref()
1103            .map(|document| {
1104                seed::inputs_of(document)
1105                    .into_iter()
1106                    .map(|input| TemplateInputView { default: seed::default_value(document, &input), input })
1107                    .collect()
1108            })
1109            .unwrap_or_default();
1110        self.read(|state| {
1111            let mut copies: Vec<CopyView> = state
1112                .parts
1113                .iter()
1114                .filter_map(|p| {
1115                    let first = p.revisions.iter().find(|r| {
1116                        r.template.as_ref().is_some_and(|t| t.template_part == seed.part.id)
1117                    })?;
1118                    let stamp = first.template.as_ref()?;
1119                    Some(CopyView {
1120                        part_id: p.id.clone(),
1121                        number: p.number.clone(),
1122                        name: p.name.clone(),
1123                        values: stamp.values.clone(),
1124                        created_at: stamp.created_at,
1125                        bake: bake_name(first),
1126                    })
1127                })
1128                .collect();
1129            copies.sort_by(|a, b| b.created_at.cmp(&a.created_at));
1130            let kind = member_type(&seed.part);
1131            Ok(TemplateView {
1132                template_id: seed.part.id.clone(),
1133                number: seed.part.number.clone(),
1134                revision_id: seed.revision.id.clone(),
1135                revision_label: seed.revision.label.clone(),
1136                has_document: seed.document.is_some(),
1137                member_part_type_mode: mode_of(state, &kind),
1138                member_part_type: kind,
1139                inputs,
1140                copies,
1141            })
1142        })
1143    }
1144
1145    /// Spin a new normal part out of a template: its first revision is the
1146    /// template's document with `values` in its expressions (the CAD app's
1147    /// `spin_out`), stamped with the template, and queued for a bake.
1148    pub fn spin_out(&self, user: &User, key: &str, request: SpinOutRequest) -> Result<Part, Error> {
1149        let seed = self.seed(key, DocumentClass::Template, &request.template_revision, |p| {
1150            p.current_release().or(p.latest())
1151        })?;
1152        let document = Self::seed_document(&seed)?;
1153        let template_file = format!("{}.tbrep", seed.part.number);
1154        let (copy, used) = seed::spin_out(document, &template_file, &request.values).map_err(Error::bad_request)?;
1155        let part_type = if request.part_type.trim().is_empty() {
1156            member_type(&seed.part)
1157        } else {
1158            request.part_type.trim().to_string()
1159        };
1160        let category = self.read(|state| catalog::find(&state.categories, &seed.part.category).map(|c| c.id.clone()));
1161        let part = self.create_part_with(
1162            user,
1163            &PartSpec {
1164                part_type,
1165                number: request.number.trim().to_string(),
1166                name: request.name,
1167                description: request.description,
1168                category: category.unwrap_or_default(),
1169                document_class: DocumentClass::Normal,
1170                tags: seed.part.tags.clone(),
1171                workspace: crate::workspace::link_on_create(
1172                    crate::model::Origin::Authored,
1173                    false,
1174                    &request.workspace_folder,
1175                ),
1176                ..PartSpec::default()
1177            },
1178        )?;
1179        let revision = part.revisions.first().ok_or_else(|| Error::internal("a new part has no revision"))?;
1180        let stamp = TemplateStamp {
1181            template_part: seed.part.id.clone(),
1182            template_revision: seed.revision.id.clone(),
1183            values: used,
1184            content_hash: seed::template_hash(document),
1185            created_at: now(),
1186        };
1187        let bake = new_bake(
1188            user,
1189            format!("spun out of template {} revision {}", seed.part.number, seed.revision.label),
1190        );
1191        self.write_generated(
1192            user,
1193            &part.id,
1194            &revision.id,
1195            &copy.to_string(),
1196            Written::Template(stamp),
1197            Some(bake),
1198            &serde_json::Map::new(),
1199        )?;
1200        self.read(|state| state.part(&part.id).cloned()).ok_or_else(|| Error::not_found("part"))
1201    }
1202}
1203
1204// ===========================================================================
1205// The bake queue
1206// ===========================================================================
1207
1208#[derive(Debug, Serialize)]
1209pub struct ResaveReport {
1210    pub jobs: Vec<BakeJob>,
1211    pub failures: Vec<ResaveFailure>,
1212}
1213
1214#[derive(Debug, Serialize)]
1215pub struct ResaveFailure {
1216    pub part_id: String,
1217    pub error: String,
1218}
1219
1220impl Db {
1221    /// Queue the latest revision of each selected part in the existing bake
1222    /// queue. The snapshot and all accepted jobs persist in one transaction.
1223    pub fn queue_resaves(&self, user: &User, parts: &[String]) -> Result<ResaveReport, Error> {
1224        if !user.can_author() { return Err(Error::forbidden("Force resave requires author permission")); }
1225        self.mutate(|state| {
1226            let mut report = ResaveReport { jobs: Vec::new(), failures: Vec::new() };
1227            let mut seen = std::collections::BTreeSet::new();
1228            for part_key in parts {
1229                if !seen.insert(part_key) { continue; }
1230                let queued = (|| {
1231                    let part = state.part_by_id_or_number(part_key).ok_or_else(|| Error::not_found("part"))?;
1232                    let revision = part.revisions.last().ok_or_else(|| Error::not_found("revision"))?;
1233                    if !revision.lifecycle.is_editable() {
1234                        return Err(Error::conflict(format!("Revision {} is {}", revision.label, revision.lifecycle.as_str())));
1235                    }
1236                    if revision.content_hash.is_empty() { return Err(Error::conflict("No saved model")); }
1237                    if let Some(bake) = revision.bake.as_ref().filter(|b| b.status != BakeStatus::Done) {
1238                        if bake.resave_hash.is_none() { return Err(Error::conflict("a generated bake is already queued; complete or retry it first")); }
1239                        if matches!(bake.status, BakeStatus::Pending | BakeStatus::Claimed) {
1240                            return Ok(job_view(state, part, revision, bake));
1241                        }
1242                    }
1243                    let (part_id, revision_id, hash) = (part.id.clone(), revision.id.clone(), revision.content_hash.clone());
1244                    let revision = crate::db::find_revision_mut(state, &part_id, &revision_id)?.1;
1245                    let attempts = revision.bake.as_ref().map(|b| b.attempts).unwrap_or_default();
1246                    let mut bake = new_bake(user, "Force resave model and thumbnail".into());
1247                    bake.resave_hash = Some(hash);
1248                    bake.attempts = attempts;
1249                    revision.bake = Some(bake);
1250                    state.touch(format!("part/{part_id}/rev/{revision_id}"));
1251                    let part = state.part(&part_id).expect("found above");
1252                    let revision = part.revision(&revision_id).expect("found above");
1253                    Ok(job_view(state, part, revision, revision.bake.as_ref().expect("just queued")))
1254                })();
1255                match queued {
1256                    Ok(job) => report.jobs.push(job),
1257                    Err(error) => report.failures.push(ResaveFailure {part_id:part_key.clone(),error:error.message}),
1258                }
1259            }
1260            Ok(report)
1261        })
1262    }
1263
1264    /// The bake jobs, oldest first. `status` narrows to one status; `all`
1265    /// includes finished jobs, which are otherwise left out.
1266    pub fn bake_jobs(&self, status: &str) -> Vec<BakeJob> {
1267        self.bake_jobs_page(status, 0, None, None).jobs
1268    }
1269
1270    /// Count matching jobs, but build detailed views only for the requested page.
1271    /// `ids` restricts progress to one user's batch, including jobs on other pages.
1272    pub fn bake_jobs_page(&self, status: &str, offset: usize, limit: Option<usize>, ids: Option<&[String]>) -> BakePage {
1273        let status = status.trim().to_ascii_lowercase();
1274        let limit = limit.map(|size| size.max(1));
1275        let ids = ids.map(|ids| ids.iter().map(String::as_str).collect::<std::collections::HashSet<_>>());
1276        self.read(|state| {
1277            let mut entries: Vec<_> = state
1278                .parts
1279                .iter()
1280                .flat_map(|part| part.revisions.iter().map(move |r| (part, r)))
1281                .filter_map(|(part, revision)| {
1282                    let bake = revision.bake.as_ref()?;
1283                    if ids.as_ref().is_some_and(|ids| !ids.contains(revision.document_key(&part.id).as_str())) {
1284                        return None;
1285                    }
1286                    let keep = match status.as_str() {
1287                        "" => bake.status != BakeStatus::Done,
1288                        "all" => true,
1289                        wanted => bake.status.as_str() == wanted,
1290                    };
1291                    keep.then_some((part, revision, bake))
1292                })
1293                .collect();
1294            entries.sort_by(|(a, ar, ab), (b, br, bb)| {
1295                ab.requested_at.cmp(&bb.requested_at).then_with(|| a.number.cmp(&b.number)).then_with(|| ar.id.cmp(&br.id))
1296            });
1297            let total = entries.len();
1298            let mut counts = BakeCounts::default();
1299            for (_, revision, bake) in &entries {
1300                match bake.status {
1301                    BakeStatus::Pending => {
1302                        counts.pending += 1;
1303                        if !bake_can_write_checkout(revision, bake.claimed_by.as_deref().unwrap_or("")) { counts.waiting += 1; }
1304                    }
1305                    BakeStatus::Claimed => counts.claimed += 1,
1306                    BakeStatus::Done => counts.done += 1,
1307                    BakeStatus::Failed => counts.failed += 1,
1308                }
1309            }
1310            // If a status filter shrank during polling, return its last page.
1311            let offset = match limit {
1312                Some(size) if offset >= total => total.saturating_sub(1) / size * size,
1313                _ => offset,
1314            };
1315            let jobs: Vec<_> = entries.iter().skip(offset).take(limit.unwrap_or(total))
1316                .map(|(part, revision, bake)| job_view(state, part, revision, bake)).collect();
1317            let next = (offset.saturating_add(jobs.len()) < total).then_some(offset.saturating_add(jobs.len()));
1318            BakePage { jobs, total, offset, next, counts }
1319        })
1320    }
1321
1322    /// Take a bake job: `id`, or else the oldest one free. A job is free when
1323    /// it is pending, or claimed longer than [`BAKE_LEASE`] ago. `None` when
1324    /// asked for the next and nothing is free.
1325    pub fn claim_bake(&self, worker: &User, id: Option<&str>) -> Result<Option<BakeJob>, Error> {
1326        let worker_id = worker.id.clone();
1327        let id = id.map(str::to_string);
1328        self.mutate(move |state| {
1329            let stamp = now();
1330            // Generated bakes wait for checkout. A resave can refresh the
1331            // requester's checkout while preserving checkout ownership.
1332            let unlocked = |revision: &Revision| bake_can_write_checkout(revision, &worker_id);
1333            let free = |revision: &Revision| {
1334                unlocked(revision)
1335                    && revision.bake.as_ref().is_some_and(|b| match b.status {
1336                        BakeStatus::Pending => true,
1337                        BakeStatus::Claimed => b.claimed_at.is_none_or(|at| at + BAKE_LEASE <= stamp),
1338                        _ => false,
1339                    })
1340            };
1341            let chosen = match &id {
1342                Some(id) => {
1343                    let (part, revision) = locate(state, id)?;
1344                    if !free(revision) {
1345                        let bake = revision.bake.as_ref().ok_or_else(|| Error::not_found("bake job"))?;
1346                        if let Some(lock) = revision.lock.as_ref().filter(|_| !unlocked(revision)) {
1347                            return Err(Error::conflict(format!(
1348                                "{} revision {} is checked out by {} — its bake waits until it is checked in",
1349                                part.number,
1350                                revision.label,
1351                                user_name(state, &lock.user_id)
1352                            )));
1353                        }
1354                        return Err(Error::conflict(match bake.status {
1355                            BakeStatus::Claimed => format!(
1356                                "{} revision {} is being baked by {} — the claim lapses {} seconds after it was taken",
1357                                part.number,
1358                                revision.label,
1359                                bake.claimed_by.as_deref().map(|u| user_name(state, u)).unwrap_or_default(),
1360                                BAKE_LEASE
1361                            ),
1362                            BakeStatus::Failed => format!(
1363                                "{} revision {} failed its bake — retry it first",
1364                                part.number, revision.label
1365                            ),
1366                            _ => format!("{} revision {} has nothing to bake", part.number, revision.label),
1367                        }));
1368                    }
1369                    Some((part.id.clone(), revision.id.clone()))
1370                }
1371                None => state
1372                    .parts
1373                    .iter()
1374                    .flat_map(|p| p.revisions.iter().map(move |r| (p, r)))
1375                    .filter(|(_, r)| free(r))
1376                    .min_by_key(|(p, r)| (r.bake.as_ref().map(|b| b.requested_at), p.number.clone()))
1377                    .map(|(p, r)| (p.id.clone(), r.id.clone())),
1378            };
1379            let Some((part_id, revision_id)) = chosen else {
1380                return Ok(None);
1381            };
1382            let revision = crate::db::find_revision_mut(state, &part_id, &revision_id)?.1;
1383            let bake = revision.bake.as_mut().expect("chosen as free");
1384            bake.status = BakeStatus::Claimed;
1385            bake.claimed_by = Some(worker_id.clone());
1386            bake.claimed_at = Some(stamp);
1387            bake.attempts += 1;
1388            let part = state.part(&part_id).expect("found above");
1389            let revision = part.revision(&revision_id).expect("found above");
1390            Ok(Some(job_view(state, part, revision, revision.bake.as_ref().expect("just set"))))
1391        })
1392    }
1393
1394    /// Extend a claimed job's lease: the claim holder says "still baking", and
1395    /// the claim runs [`BAKE_LEASE`] from now. A long bake renews every so
1396    /// often instead of being handed to another worker at 15 minutes. Only the
1397    /// holder may renew (`held_by`): a job another worker took over after
1398    /// the lease lapsed, or one nobody has claimed, is refused by name.
1399    pub fn renew_bake(&self, worker: &User, id: &str) -> Result<BakeJob, Error> {
1400        let worker_id = worker.id.clone();
1401        let id = id.to_string();
1402        self.mutate(move |state| {
1403            let (part, revision) = locate(state, &id)?;
1404            held_by(state, part, revision, &worker_id)?;
1405            let (part_id, revision_id) = (part.id.clone(), revision.id.clone());
1406            let revision = crate::db::find_revision_mut(state, &part_id, &revision_id)?.1;
1407            let bake = revision.bake.as_mut().expect("held above");
1408            bake.claimed_at = Some(now());
1409            let part = state.part(&part_id).expect("found above");
1410            let revision = part.revision(&revision_id).expect("found above");
1411            Ok(job_view(state, part, revision, revision.bake.as_ref().expect("held above")))
1412        })
1413    }
1414
1415    /// A worker's result: the baked document replaces the assembled one, the
1416    /// job is done, and a family member's stamp takes the new hash (a baked
1417    /// member is not "edited by hand").
1418    pub fn finish_bake(&self, worker: &User, id: &str, body: &str) -> Result<(), Error> {
1419        let parsed: Value = serde_json::from_str(body).map_err(|_| Error::bad_request("a document must be JSON"))?;
1420        if !parsed.is_object() {
1421            return Err(Error::bad_request("a document must be a JSON object"));
1422        }
1423        let hash = auth::content_hash(body);
1424        let size = body.len() as u64;
1425        let embedded = crate::thumbnail::embedded(self.root(), body)?;
1426        let worker_id = worker.id.clone();
1427        let id = id.to_string();
1428        let (part_id, revision_id) = self.read(|state| locate(state, &id).map(|(p, r)| (p.id.clone(), r.id.clone())))?;
1429        let path = self.document_path(&id)?;
1430        self.mutate(move |state| {
1431            let (part, revision) = locate(state, &id)?;
1432            held_by(state, part, revision, &worker_id)?;
1433            if let Some(lock) = revision.lock.as_ref().filter(|_| !bake_can_write_checkout(revision, &worker_id)) {
1434                return Err(Error::conflict(format!(
1435                    "{} revision {} was checked out by {} after the bake was claimed — report the bake failed, or wait and retry",
1436                    part.number,
1437                    revision.label,
1438                    user_name(state, &lock.user_id)
1439                )));
1440            }
1441            if !revision.lifecycle.is_editable() {
1442                return Err(Error::conflict(format!(
1443                    "{} revision {} is {} — its document can no longer change",
1444                    part.number,
1445                    revision.label,
1446                    revision.lifecycle.as_str()
1447                )));
1448            }
1449            let resave_hash = revision.bake.as_ref().and_then(|b| b.resave_hash.clone());
1450            if let Some(expected) = &resave_hash {
1451                if revision.content_hash != *expected {
1452                    return Err(Error::conflict("the model changed after Force resave was queued; retry it"));
1453                }
1454            }
1455            let key = revision.document_key(&part.id);
1456            let revision = crate::db::find_revision_mut(state, &part_id, &revision_id)?.1;
1457            if let Some(parent) = path.parent() {
1458                std::fs::create_dir_all(parent).map_err(Error::internal)?;
1459            }
1460            let old_thumbnail = revision.thumbnail.as_ref().map(|t| t.sha256.clone());
1461            let thumbnail = embedded.as_ref().map(|image| image.place(self.root(), &hash, &worker_id)).transpose()?;
1462            revision.has_geometry = crate::geometry::contains_geometry(body);
1463            revision.geometry_content_hash = hash.clone();
1464            write_atomic(&path, body).map_err(Error::internal)?;
1465            if let Some(thumbnail) = thumbnail { revision.thumbnail = Some(thumbnail); }
1466            revision.content_hash = hash.clone();
1467            revision.size = size;
1468            revision.modified_at = now();
1469            if let Some(stamp) = revision.family.as_mut() {
1470                if resave_hash.as_ref().is_none_or(|expected| stamp.generated_hash == *expected) {
1471                    stamp.generated_hash = hash;
1472                }
1473            }
1474            let bake = revision.bake.as_mut().expect("held_by checked it");
1475            bake.status = BakeStatus::Done;
1476            bake.error.clear();
1477            bake.finished_by = Some(worker_id);
1478            bake.finished_at = Some(now());
1479            crate::review::document_changed(state, &part_id, &revision_id);
1480            state.touch(key);
1481            if embedded.is_some() {
1482                if let Some(old) = old_thumbnail { crate::attach::remove_if_unreferenced(state, self.root(), &old)?; }
1483            }
1484            Ok(())
1485        })
1486    }
1487
1488    /// A worker reports that a bake failed (an expression that does not
1489    /// evaluate, a feature that does not build). The job waits for a person.
1490    pub fn fail_bake(&self, worker: &User, id: &str, error: &str) -> Result<(), Error> {
1491        let error = error.trim();
1492        if error.is_empty() {
1493            return Err(Error::bad_request("say why the bake failed"));
1494        }
1495        let worker_id = worker.id.clone();
1496        let error = error.to_string();
1497        let id = id.to_string();
1498        self.mutate(move |state| {
1499            let (part, revision) = locate(state, &id)?;
1500            held_by(state, part, revision, &worker_id)?;
1501            let (part_id, revision_id) = (part.id.clone(), revision.id.clone());
1502            let revision = crate::db::find_revision_mut(state, &part_id, &revision_id)?.1;
1503            let bake = revision.bake.as_mut().expect("held_by checked it");
1504            bake.status = BakeStatus::Failed;
1505            bake.error = error;
1506            bake.finished_by = Some(worker_id);
1507            bake.finished_at = Some(now());
1508            Ok(())
1509        })
1510    }
1511
1512    /// Put a failed or claimed job back in the queue — after fixing the row
1513    /// that failed, or to take a job off a worker that went away.
1514    pub fn retry_bake(&self, id: &str) -> Result<(), Error> {
1515        let id = id.to_string();
1516        self.mutate(move |state| {
1517            let (part, revision) = locate(state, &id)?;
1518            let (number, label) = (part.number.clone(), revision.label.clone());
1519            let (part_id, revision_id) = (part.id.clone(), revision.id.clone());
1520            let revision = crate::db::find_revision_mut(state, &part_id, &revision_id)?.1;
1521            if !revision.lifecycle.is_editable() {
1522                return Err(Error::conflict(format!("{number} revision {label} is no longer in work")));
1523            }
1524            let bake = revision.bake.as_mut().ok_or_else(|| Error::not_found("bake job"))?;
1525            if !matches!(bake.status, BakeStatus::Failed | BakeStatus::Claimed) {
1526                return Err(Error::conflict(format!(
1527                    "{number} revision {label}'s bake is {} — only a failed or claimed one goes back in the queue",
1528                    bake.status.as_str()
1529                )));
1530            }
1531            bake.status = BakeStatus::Pending;
1532            if bake.resave_hash.is_some() { bake.resave_hash = Some(revision.content_hash.clone()); }
1533            bake.claimed_by = None;
1534            bake.claimed_at = None;
1535            Ok(())
1536        })
1537    }
1538}
1539
1540/// Resolve the readable part/revision pair carried by a bake job.
1541fn locate<'a>(state: &'a State, id: &str) -> Result<(&'a Part, &'a Revision), Error> {
1542    let (part_id, revision_id) = crate::identity::split_key(id)
1543        .ok_or_else(|| Error::bad_request("a bake job needs its part/revision document key"))?;
1544    let part = state.part(&part_id).ok_or_else(|| Error::not_found("bake job"))?;
1545    let revision = part.revision(&revision_id).filter(|r| r.bake.is_some())
1546        .ok_or_else(|| Error::not_found("bake job"))?;
1547    Ok((part, revision))
1548}
1549
1550/// Refuse unless `worker` holds the job's claim.
1551fn held_by(state: &State, part: &Part, revision: &Revision, worker_id: &str) -> Result<(), Error> {
1552    let bake = revision.bake.as_ref().ok_or_else(|| Error::not_found("bake job"))?;
1553    if bake.status != BakeStatus::Claimed {
1554        return Err(Error::conflict(format!(
1555            "{} revision {}'s bake is {}{} — claim it first",
1556            part.number,
1557            revision.label,
1558            bake.status.as_str(),
1559            if bake.error.is_empty() { String::new() } else { format!(" ({})", bake.error) }
1560        )));
1561    }
1562    if bake.claimed_by.as_deref() != Some(worker_id) {
1563        return Err(Error::conflict(format!(
1564            "{} revision {} is being baked by {}",
1565            part.number,
1566            revision.label,
1567            bake.claimed_by.as_deref().map(|u| user_name(state, u)).unwrap_or_default()
1568        )));
1569    }
1570    Ok(())
1571}
1572
1573fn job_view(state: &State, part: &Part, revision: &Revision, bake: &Bake) -> BakeJob {
1574    BakeJob {
1575        expected_hash: bake.resave_hash.clone(),
1576        id: revision.document_key(&part.id),
1577        part_id: part.id.clone(),
1578        number: part.number.clone(),
1579        name: part.name.clone(),
1580        revision_label: revision.label.clone(),
1581        lifecycle: revision.lifecycle.as_str(),
1582        status: bake.status.as_str(),
1583        reason: bake.reason.clone(),
1584        requested_by: user_name(state, &bake.requested_by),
1585        requested_at: bake.requested_at,
1586        claimed_by: bake.claimed_by.as_deref().map(|u| user_name(state, u)),
1587        claimed_at: bake.claimed_at,
1588        lease_expires_at: (bake.status == BakeStatus::Claimed)
1589            .then(|| bake.claimed_at.map(|at| at + BAKE_LEASE))
1590            .flatten(),
1591        attempts: bake.attempts,
1592        error: bake.error.clone(),
1593        finished_at: bake.finished_at,
1594        document_key: revision.document_key(&part.id),
1595        source: if bake.resave_hash.is_some() {
1596            "resave"
1597        } else if revision.family.is_some() {
1598            "family"
1599        } else if revision.template.is_some() {
1600            "template"
1601        } else {
1602            ""
1603        },
1604        locked_by: revision.lock.as_ref().map(|l| user_name(state, &l.user_id)),
1605        waiting_on_checkout: !bake_can_write_checkout(revision, bake.claimed_by.as_deref().unwrap_or("")),
1606    }
1607}
1608
1609fn bake_can_write_checkout(revision: &Revision, worker_id: &str) -> bool {
1610    revision.lock.as_ref().is_none_or(|lock| {
1611        lock.user_id == worker_id || revision.bake.as_ref()
1612            .is_some_and(|bake| bake.resave_hash.is_some() && lock.user_id == bake.requested_by)
1613    })
1614}