Skip to main content

brep_app/plm/
adoption.rs

1//! Adoption: turning a folder of documents into PLM parts (S13, the pure half).
2//!
3//! Without this there is no way from a tree of `.nbrep` files to a populated
4//! PLM (D10). The importer mints one part per document, uploads each document
5//! to its part's first revision, and publishes every assembly's uses list. An
6//! imported assembly only resolves if its occurrences' `sourceKey`s have been
7//! rewritten from file names to `part/<part>/rev/<revision>`.
8//!
9//! This module decides WHAT to do and in what order; the importer (wired once
10//! the PLM client lands) does it. It never writes: the source tree is read
11//! into [`SourceDocument`]s and every rewrite is made on a copy, so the same
12//! folder still opens file-based afterwards.
13//!
14//! * [`plan_adoption`]: one [`PlannedPart`] per document, with its class
15//!   (from the extension, as the file stores read it) and every `sourceKey` it
16//!   names that the tree does not hold.
17//! * [`Ledger`]: `identity → (part, revision)` and how far each document has
18//!   got. It is what makes the import restartable. [`next_step`] reads the
19//!   plan against the ledger and answers the first thing not yet done, so a
20//!   run killed at any point resumes where it stopped. An import of a tree the
21//!   ledger has already finished answers `None`: it writes nothing.
22//! * [`rewrite_source_keys`]: every `sourceKey`, at EVERY depth. A
23//!   sub-assembly's library entry carries that sub-assembly's whole document,
24//!   whose own entries have `sourceKey`s too; a stale nested key is what Update
25//!   Components would later "fix" by fetching a file that is not there.
26//!
27//! The order is three phases over the whole tree: mint every part, then
28//! upload every document, then publish every assembly's uses list. A document
29//! can only be uploaded rewritten once every part it names has been minted,
30//! and a uses list can only name parts that exist. Part NUMBERS are the
31//! server's to give (counter, pattern or script numbering cannot run here),
32//! so a plan holds intents, and the ledger holds what the server answered.
33
34use crate::document_class::DocumentClass;
35use crate::plm::uses;
36use crate::store::DocumentIdentity;
37use serde_json::Value;
38use std::collections::{BTreeMap, BTreeSet};
39
40/// One document of the tree being adopted, as read — never written back.
41#[derive(Clone, Debug, PartialEq, Eq)]
42pub struct SourceDocument {
43    /// Its canonical identity (`ModelStore::canonical_identity`), the key
44    /// every `sourceKey` is matched against.
45    pub identity: String,
46    pub contents: String,
47}
48
49/// A part the import will mint for one document.
50#[derive(Clone, Debug, PartialEq, Eq)]
51pub struct PlannedPart {
52    pub identity: String,
53    /// From the file's extension: a `.fbrep` is a family, a `.tbrep` a
54    /// template, anything else a normal part.
55    pub class: DocumentClass,
56    /// The name a person knew it by: its file name without the class
57    /// extension.
58    pub name: String,
59    /// The document's content signature, so a later import can tell a
60    /// changed file from an adopted one.
61    pub signature: String,
62    /// Whether it places components, which is what earns it a uses list.
63    pub assembly: bool,
64}
65
66/// What an import of a tree will do.
67#[derive(Clone, Debug, Default, PartialEq, Eq)]
68pub struct AdoptionPlan {
69    /// One per document, in identity order.
70    pub parts: Vec<PlannedPart>,
71    /// Documents that will not be imported, and why.
72    pub refused: Vec<(String, String)>,
73    /// `(document, sourceKey)` for every key a document names that the tree
74    /// does not hold. The key is left as it is; an assembly with one cannot
75    /// publish a whole uses list, so the importer reports it before it starts.
76    pub external: Vec<(String, String)>,
77}
78
79/// Plan the adoption of `documents`. `canonical` spells a `sourceKey` the way
80/// the walker spelled the documents (`ModelStore::canonical_identity`).
81pub fn plan_adoption(
82    documents: &[SourceDocument],
83    canonical: &dyn Fn(&str) -> String,
84) -> AdoptionPlan {
85    let mut plan = AdoptionPlan::default();
86    let held: BTreeSet<&str> = documents.iter().map(|d| d.identity.as_str()).collect();
87    let mut sorted: Vec<&SourceDocument> = documents.iter().collect();
88    sorted.sort_by(|a, b| a.identity.cmp(&b.identity));
89    for document in sorted {
90        let parsed: Value = match serde_json::from_str(&document.contents) {
91            Ok(parsed @ Value::Object(_)) => parsed,
92            Ok(_) => {
93                plan.refused
94                    .push((document.identity.clone(), "not a model document (not a JSON object)".into()));
95                continue;
96            }
97            Err(error) => {
98                plan.refused
99                    .push((document.identity.clone(), format!("does not parse: {error}")));
100                continue;
101            }
102        };
103        let mut keys = Vec::new();
104        source_keys(&parsed, &mut keys);
105        for key in keys {
106            if DocumentIdentity::parse_revision_key(&key).is_some() {
107                continue; // already a PLM part
108            }
109            if !held.contains(canonical(&key).as_str()) {
110                plan.external.push((document.identity.clone(), key));
111            }
112        }
113        let file = crate::store::file_name_of(&document.identity);
114        plan.parts.push(PlannedPart {
115            class: DocumentClass::of_name(&file).unwrap_or_default(),
116            name: crate::document_class::strip_class_extension(&file).to_string(),
117            signature: crate::panels::parts_library::document_signature(&document.contents),
118            assembly: !uses::occurrences(&parsed).is_empty(),
119            identity: document.identity.clone(),
120        });
121    }
122    plan.external.dedup();
123    plan
124}
125
126/// Every non-empty `sourceKey` in `document`'s parts library, at every depth,
127/// in document order.
128fn source_keys(document: &Value, out: &mut Vec<String>) {
129    let Some(library) = document.get("partsLibrary").and_then(Value::as_object) else {
130        return;
131    };
132    for entry in library.values() {
133        if let Some(key) = entry.get("sourceKey").and_then(Value::as_str) {
134            if !key.is_empty() {
135                out.push(key.to_string());
136            }
137        }
138        if let Some(nested) = entry.get("document") {
139            source_keys(nested, out);
140        }
141    }
142}
143
144/// Rewrite every `sourceKey` in `document`, at every depth, through `to_key`
145/// (a raw key → its `part/…/rev/…` key, or `None` when the import did not
146/// mint it). Returns the keys `to_key` did not know, which are left exactly
147/// as they were: an unknown key is reported, never blanked, because an empty
148/// `sourceKey` means "embedded, never a part", which is a different claim.
149/// An empty key or a key that is already a revision key is left alone.
150pub fn rewrite_source_keys(
151    document: &mut Value,
152    to_key: &dyn Fn(&str) -> Option<String>,
153) -> Vec<String> {
154    let mut unknown = Vec::new();
155    rewrite(document, to_key, &mut unknown);
156    unknown
157}
158
159fn rewrite(document: &mut Value, to_key: &dyn Fn(&str) -> Option<String>, unknown: &mut Vec<String>) {
160    let Some(library) = document.get_mut("partsLibrary").and_then(Value::as_object_mut) else {
161        return;
162    };
163    for entry in library.values_mut() {
164        let key = entry
165            .get("sourceKey")
166            .and_then(Value::as_str)
167            .unwrap_or_default()
168            .to_string();
169        if !key.is_empty() && DocumentIdentity::parse_revision_key(&key).is_none() {
170            match to_key(&key) {
171                Some(revision_key) => entry["sourceKey"] = Value::String(revision_key),
172                None => unknown.push(key),
173            }
174        }
175        if let Some(nested) = entry.get_mut("document") {
176            rewrite(nested, to_key, unknown);
177        }
178    }
179}
180
181/// How far one document has got. Persisted between runs; this is what makes
182/// the import restartable.
183#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
184pub struct LedgerEntry {
185    /// What the server minted for it.
186    pub part: String,
187    pub revision: String,
188    /// The content signature it was minted from.
189    pub signature: String,
190    #[serde(default)]
191    pub uploaded: bool,
192    #[serde(default)]
193    pub published: bool,
194}
195
196/// The import's memory, by canonical identity.
197#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
198pub struct Ledger {
199    pub entries: BTreeMap<String, LedgerEntry>,
200}
201
202impl Ledger {
203    /// The revision key the import minted for a document.
204    pub fn revision_key(&self, identity: &str) -> Option<String> {
205        self.entries.get(identity).map(|entry| {
206            DocumentIdentity::Revision {
207                part: entry.part.clone(),
208                revision: entry.revision.clone(),
209            }
210            .key()
211        })
212    }
213
214    pub fn record_minted(&mut self, part: &PlannedPart, part_id: &str, revision_id: &str) {
215        self.entries.insert(
216            part.identity.clone(),
217            LedgerEntry {
218                part: part_id.into(),
219                revision: revision_id.into(),
220                signature: part.signature.clone(),
221                uploaded: false,
222                published: false,
223            },
224        );
225    }
226
227    pub fn record_uploaded(&mut self, identity: &str) {
228        if let Some(entry) = self.entries.get_mut(identity) {
229            entry.uploaded = true;
230        }
231    }
232
233    pub fn record_published(&mut self, identity: &str) {
234        if let Some(entry) = self.entries.get_mut(identity) {
235            entry.published = true;
236        }
237    }
238}
239
240/// Every import's ledger on this machine, under the reserved Local key
241/// `@plm_import`: by PLM server, then by the folder imported. A ledger names
242/// part and revision ids that exist on ONE server, so an import of the same
243/// folder against another server starts from nothing rather than "resuming"
244/// with ids that server never minted.
245#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
246pub struct ImportLedgers {
247    /// Server (normalised by [`server_key`]) → folder → ledger.
248    pub servers: BTreeMap<String, BTreeMap<String, Ledger>>,
249}
250
251/// A server URL as a ledger key: scheme and host lowercased, no trailing
252/// slash, so `HTTPS://PLM.example.com/` and `https://plm.example.com` are one
253/// server. The path is kept: two PLMs may be served under one host.
254pub fn server_key(url: &str) -> String {
255    let url = url.trim().trim_end_matches('/');
256    match url.split_once("://") {
257        Some((scheme, rest)) => {
258            let (host, path) = rest.split_once('/').map_or((rest, ""), |(h, p)| (h, p));
259            let mut key = format!("{}://{}", scheme.to_ascii_lowercase(), host.to_ascii_lowercase());
260            if !path.is_empty() {
261                key.push('/');
262                key.push_str(path);
263            }
264            key
265        }
266        None => url.to_ascii_lowercase(),
267    }
268}
269
270impl ImportLedgers {
271    /// What the store holds; empty when nothing (or something unreadable) is.
272    pub fn load(store: &dyn crate::store::ModelStore) -> Self {
273        store
274            .read(crate::store::PLM_IMPORT_KEY)
275            .and_then(|text| serde_json::from_str(&text).ok())
276            .unwrap_or_default()
277    }
278
279    /// The ledger for importing `folder` into `server`; empty if never run.
280    pub fn ledger(&self, server: &str, folder: &str) -> Ledger {
281        self.servers
282            .get(&server_key(server))
283            .and_then(|folders| folders.get(folder))
284            .cloned()
285            .unwrap_or_default()
286    }
287
288    /// Record `ledger` for `folder` on `server` and write the whole record.
289    pub fn save(
290        &mut self,
291        store: &dyn crate::store::ModelStore,
292        server: &str,
293        folder: &str,
294        ledger: &Ledger,
295    ) -> Result<(), String> {
296        self.servers
297            .entry(server_key(server))
298            .or_default()
299            .insert(folder.to_string(), ledger.clone());
300        let text = serde_json::to_string(self).map_err(|error| error.to_string())?;
301        store.write(crate::store::PLM_IMPORT_KEY, &text)
302    }
303}
304
305/// The next thing an import has to do.
306#[derive(Clone, Debug, PartialEq)]
307pub enum Step {
308    /// Create a part (and its first revision) for this document.
309    Mint(PlannedPart),
310    /// Upload the document, rewritten, to the revision the ledger names.
311    Upload {
312        identity: String,
313        key: String,
314        document: String,
315        /// `sourceKey`s the rewrite could not map (all of them in
316        /// [`AdoptionPlan::external`]).
317        unknown: Vec<String>,
318    },
319    /// Publish an assembly's uses list: the `PUT …/uses` body, or why there
320    /// is none (an occurrence naming no minted part).
321    PublishUses {
322        identity: String,
323        key: String,
324        body: Result<Value, String>,
325    },
326}
327
328/// The first step `plan` still needs, given `ledger`; `None` when the import
329/// is complete. `documents` are the same ones the plan was made from.
330///
331/// A document whose signature has changed since it was minted is NOT
332/// re-uploaded: that would be a new revision of a part that may already be
333/// released, which is the ordinary revision workflow and not adoption. It is
334/// reported by [`changed_since`].
335pub fn next_step(
336    plan: &AdoptionPlan,
337    documents: &[SourceDocument],
338    ledger: &Ledger,
339    canonical: &dyn Fn(&str) -> String,
340) -> Option<Step> {
341    if let Some(part) = plan.parts.iter().find(|p| !ledger.entries.contains_key(&p.identity)) {
342        return Some(Step::Mint(part.clone()));
343    }
344    let contents = |identity: &str| {
345        documents
346            .iter()
347            .find(|d| d.identity == identity)
348            .map(|d| d.contents.as_str())
349    };
350    let to_key = |key: &str| ledger.revision_key(&canonical(key));
351    for part in &plan.parts {
352        let entry = &ledger.entries[&part.identity];
353        if entry.uploaded {
354            continue;
355        }
356        let mut document: Value = serde_json::from_str(contents(&part.identity)?).ok()?;
357        let unknown = rewrite_source_keys(&mut document, &to_key);
358        return Some(Step::Upload {
359            identity: part.identity.clone(),
360            key: ledger.revision_key(&part.identity)?,
361            document: document.to_string(),
362            unknown,
363        });
364    }
365    for part in plan.parts.iter().filter(|p| p.assembly) {
366        if ledger.entries[&part.identity].published {
367            continue;
368        }
369        let mut document: Value = serde_json::from_str(contents(&part.identity)?).ok()?;
370        rewrite_source_keys(&mut document, &to_key);
371        let resolve = |key: &str| {
372            DocumentIdentity::parse_revision_key(key)
373                .unwrap_or_else(|| DocumentIdentity::Path(key.to_string()))
374        };
375        return Some(Step::PublishUses {
376            identity: part.identity.clone(),
377            key: ledger.revision_key(&part.identity)?,
378            body: uses::uses_lines(&uses::occurrences(&document), &resolve).body(),
379        });
380    }
381    None
382}
383
384/// Documents whose content changed after the import minted them.
385pub fn changed_since(plan: &AdoptionPlan, ledger: &Ledger) -> Vec<String> {
386    plan.parts
387        .iter()
388        .filter(|part| {
389            ledger
390                .entries
391                .get(&part.identity)
392                .is_some_and(|entry| entry.signature != part.signature)
393        })
394        .map(|part| part.identity.clone())
395        .collect()
396}
397
398// --- reading the tree -------------------------------------------------------------
399
400/// Every model document under the explorer location `root`, folders
401/// included, read through the store the user browses — the same identities
402/// the explorer shows, so a `sourceKey` picked there matches. The explorer's
403/// location is restored afterwards. Nothing is written.
404pub fn walk_tree(store: &dyn crate::store::ModelStore, root: &str) -> Result<Vec<SourceDocument>, String> {
405    let before = store.browser_location();
406    let walked = walk(store, root);
407    let _ = store.browser_navigate(&before);
408    walked
409}
410
411fn walk(store: &dyn crate::store::ModelStore, root: &str) -> Result<Vec<SourceDocument>, String> {
412    let mut out = Vec::new();
413    let mut folders = vec![root.to_string()];
414    let mut seen = BTreeSet::new();
415    while let Some(folder) = folders.pop() {
416        if !seen.insert(folder.clone()) {
417            continue;
418        }
419        store.browser_navigate(&folder)?;
420        for entry in store.browser_entries(crate::store::MODEL_EXTENSIONS) {
421            if entry.is_dir {
422                folders.push(entry.identity);
423            } else {
424                let contents = store
425                    .read(&entry.identity)
426                    .ok_or_else(|| format!("'{}' could not be read", entry.identity))?;
427                out.push(SourceDocument { identity: entry.identity, contents });
428            }
429        }
430    }
431    out.sort_by(|a, b| a.identity.cmp(&b.identity));
432    Ok(out)
433}
434
435// --- the importer, over the PLM client ----------------------------------------------
436
437/// How an imported part is numbered.
438#[derive(Clone, Debug, PartialEq, Eq)]
439pub struct ImportNumbering {
440    /// The part type every document is minted as.
441    pub part_type: String,
442    /// Send the file's name as the number: for a free or pattern type, whose
443    /// numbers must be typed. A counter type refuses one, so this is `false`
444    /// for it and the counter numbers each part.
445    pub number_from_name: bool,
446}
447
448/// What an import run did.
449#[derive(Clone, Debug, Default, PartialEq, Eq)]
450pub struct ImportReport {
451    pub minted: usize,
452    pub uploaded: usize,
453    pub published: usize,
454    /// `(document, sentence)` for every step the server refused. The run stops
455    /// at the first; the ledger holds everything before it, so fixing the
456    /// cause and running again resumes there.
457    pub refused: Vec<(String, String)>,
458}
459
460/// The name this import checks revisions out under, so a lock left by a run
461/// killed mid-step says what holds it.
462const CLIENT_ID: &str = "brep-app import";
463
464async fn with_checkout(
465    client: &crate::plm::client::PlmClient,
466    key: &str,
467    write: impl std::future::Future<Output = Result<(), String>>,
468) -> Result<(), String> {
469    let Some(DocumentIdentity::Revision { part, revision }) = DocumentIdentity::parse_revision_key(key) else {
470        return Err(format!("'{key}' is not a PLM revision"));
471    };
472    let base = crate::plm::identity::revision_path(&part, &revision);
473    let body = |value: Value| Some(serde_json::to_vec(&value).unwrap_or_default());
474    // Checking out a revision this user already holds succeeds, so a run
475    // killed between checkout and check-in resumes cleanly.
476    client
477        .call("POST", &format!("{base}/checkout"), body(serde_json::json!({ "client_id": CLIENT_ID })))
478        .await
479        .map_err(|error| error.to_string())?;
480    let written = write.await;
481    // Check in whatever happened: a refused write must not leave the draft
482    // locked against the person who will fix it.
483    let checked_in = client
484        .call("POST", &format!("{base}/checkin"), body(serde_json::json!({})))
485        .await
486        .map_err(|error| error.to_string());
487    written.and(checked_in.map(|_| ()))
488}
489
490/// Load `contents` — a file family (`.fbrep`), template (`.tbrep`) or any
491/// model document — into the existing revision `key` (`part/…/rev/…`): check
492/// it out, write it, check it in. This is what the web page's "load a file
493/// into this revision" did; the CAD app does it from the file it has open.
494/// The server's refusal (a released revision, someone else's lock, a document
495/// that is not JSON) comes back as its sentence.
496pub async fn load_into_revision(
497    client: &crate::plm::client::PlmClient,
498    key: &str,
499    contents: &str,
500) -> Result<(), String> {
501    if serde_json::from_str::<Value>(contents).is_err() {
502        return Err("the file is not a model document (it does not parse as JSON)".into());
503    }
504    let path = crate::plm::identity::doc_path(key);
505    let bytes = contents.as_bytes().to_vec();
506    with_checkout(client, key, async {
507        client.call("PUT", &path, Some(bytes)).await.map(|_| ()).map_err(|e| e.to_string())
508    })
509    .await
510}
511
512/// Run an adoption against the PLM `client` is signed in to, from wherever
513/// `ledger` says it got to. `persist` is called after every step that moved
514/// the ledger, so a run killed at any point loses at most the step in flight
515/// (and that step is safe to repeat, except a mint whose answer never arrived,
516/// which leaves one unused part — the one thing a restart cannot know). It
517/// answers whether to go on: `false` is the user's Stop, and the next run
518/// resumes from the ledger it was just handed.
519pub async fn run_import(
520    client: &crate::plm::client::PlmClient,
521    plan: &AdoptionPlan,
522    documents: &[SourceDocument],
523    ledger: &mut Ledger,
524    canonical: &dyn Fn(&str) -> String,
525    numbering: &ImportNumbering,
526    persist: &mut dyn FnMut(&Ledger) -> bool,
527) -> ImportReport {
528    let mut report = ImportReport::default();
529    while let Some(step) = next_step(plan, documents, ledger, canonical) {
530        let outcome: Result<(), String> = match &step {
531            Step::Mint(part) => {
532                let request = serde_json::json!({
533                    "part_type": numbering.part_type,
534                    "name": part.name,
535                    "number": if numbering.number_from_name { part.name.clone() } else { String::new() },
536                    "document_class": part.class.slug(),
537                    // A bulk import: the server links none of these parts into
538                    // the workspace (`brep_plm::workspace::link_on_create`).
539                    "bulk": true,
540                });
541                match client
542                    .call("POST", "/api/parts", Some(serde_json::to_vec(&request).unwrap_or_default()))
543                    .await
544                {
545                    Ok(response) => {
546                        let created: Value = serde_json::from_slice(&response.body).unwrap_or_default();
547                        let id = created["id"].as_str().unwrap_or_default();
548                        let revision = created["revisions"][0]["id"].as_str().unwrap_or_default();
549                        if id.is_empty() || revision.is_empty() {
550                            Err("the PLM created the part but did not say its revision".to_string())
551                        } else {
552                            ledger.record_minted(part, id, revision);
553                            report.minted += 1;
554                            Ok(())
555                        }
556                    }
557                    Err(error) => Err(error.to_string()),
558                }
559            }
560            Step::Upload { identity, key, document, .. } => {
561                let bytes = document.clone().into_bytes();
562                let path = crate::plm::identity::doc_path(key);
563                let written = with_checkout(client, key, async {
564                    client.call("PUT", &path, Some(bytes)).await.map(|_| ()).map_err(|e| e.to_string())
565                })
566                .await;
567                written.map(|()| {
568                    ledger.record_uploaded(identity);
569                    report.uploaded += 1;
570                })
571            }
572            Step::PublishUses { identity, key, body } => match body {
573                Err(refusal) => Err(refusal.clone()),
574                Ok(body) => {
575                    let Some(DocumentIdentity::Revision { part, revision }) = DocumentIdentity::parse_revision_key(key)
576                    else {
577                        return report;
578                    };
579                    let path = format!("{}/uses", crate::plm::identity::revision_path(&part, &revision));
580                    let bytes = serde_json::to_vec(body).unwrap_or_default();
581                    let written = with_checkout(client, key, async {
582                        client.call("PUT", &path, Some(bytes)).await.map(|_| ()).map_err(|e| e.to_string())
583                    })
584                    .await;
585                    written.map(|()| {
586                        ledger.record_published(identity);
587                        report.published += 1;
588                    })
589                }
590            },
591        };
592        match outcome {
593            Ok(()) => {
594                if !persist(ledger) {
595                    return report;
596                }
597            }
598            Err(sentence) => {
599                let identity = match &step {
600                    Step::Mint(part) => part.identity.clone(),
601                    Step::Upload { identity, .. } | Step::PublishUses { identity, .. } => identity.clone(),
602                };
603                report.refused.push((identity, sentence));
604                return report;
605            }
606        }
607    }
608    report
609}
610