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