Skip to main content

aecr_sync/
iso19650.rs

1//! ISO 19650 Common Data Environment container naming, states, suitability codes, and metadata.
2
3use std::fmt;
4use std::str::FromStr;
5
6use aecr_pig::{ActorId, ContentHash, RevisionId};
7use serde::{Deserialize, Serialize};
8
9use crate::error::SyncError;
10
11/// ISO 19650 information container lifecycle state.
12#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
13pub enum CdeState {
14    /// Work in Progress (discipline-private authoring with element borrowing).
15    WorkInProgress,
16    /// Shared across disciplines after passing automated verification checks.
17    Shared,
18    /// Authorized and published for submission, tender, or construction.
19    Published,
20    /// Immutable historical record after publication.
21    Archived,
22}
23
24impl fmt::Display for CdeState {
25    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
26        match self {
27            Self::WorkInProgress => f.write_str("WorkInProgress"),
28            Self::Shared => f.write_str("Shared"),
29            Self::Published => f.write_str("Published"),
30            Self::Archived => f.write_str("Archived"),
31        }
32    }
33}
34
35/// ISO 19650 suitability code governing allowed container usage within each CDE state.
36#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
37pub enum SuitabilityCode {
38    /// Initial Work in Progress status.
39    S0,
40    /// Suitable for multi-discipline coordination (`Shared`).
41    S1,
42    /// Suitable for information (`Shared`).
43    S2,
44    /// Suitable for review and comment (`Shared`).
45    S3,
46    /// Suitable for stage approval (`Shared`).
47    S4,
48    /// Authorized and accepted stage 1 (`Published`).
49    A1,
50    /// Authorized and accepted stage 2 (`Published`).
51    A2,
52    /// Authorized and accepted stage 3 (`Published`).
53    A3,
54    /// Authorized and accepted stage 4 (`Published`).
55    A4,
56    /// As-constructed / archived record (`Archived`).
57    Cr,
58}
59
60impl fmt::Display for SuitabilityCode {
61    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
62        let code = match self {
63            Self::S0 => "S0",
64            Self::S1 => "S1",
65            Self::S2 => "S2",
66            Self::S3 => "S3",
67            Self::S4 => "S4",
68            Self::A1 => "A1",
69            Self::A2 => "A2",
70            Self::A3 => "A3",
71            Self::A4 => "A4",
72            Self::Cr => "Cr",
73        };
74        f.write_str(code)
75    }
76}
77
78/// ISO 19650-2 / JKR BIM 7-field information container identifier (`PRJ1-ARC-ZZ-01-M3-A-0001`).
79#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
80pub struct ContainerId {
81    /// Project code token.
82    pub project: String,
83    /// Authoring organization or originator code token.
84    pub originator: String,
85    /// Spatial volume or system code token.
86    pub volume_system: String,
87    /// Storey level or location code token.
88    pub level_location: String,
89    /// Information container type code token (for example, `M3` or `DR`).
90    pub doc_type: String,
91    /// Authoring discipline or role code token (for example, `A`, `S`, `M`, `E`).
92    pub discipline: String,
93    /// Sequential document or model number token.
94    pub number: String,
95}
96
97impl ContainerId {
98    /// Constructs and validates a 7-token ISO 19650-2 container identifier.
99    pub fn new(
100        project: impl Into<String>,
101        originator: impl Into<String>,
102        volume_system: impl Into<String>,
103        level_location: impl Into<String>,
104        doc_type: impl Into<String>,
105        discipline: impl Into<String>,
106        number: impl Into<String>,
107    ) -> Result<Self, SyncError> {
108        let id = Self {
109            project: project.into(),
110            originator: originator.into(),
111            volume_system: volume_system.into(),
112            level_location: level_location.into(),
113            doc_type: doc_type.into(),
114            discipline: discipline.into(),
115            number: number.into(),
116        };
117        id.validate()?;
118        Ok(id)
119    }
120
121    /// Parses and validates a hyphen-separated ISO 19650-2 container code string.
122    pub fn parse(raw: &str) -> Result<Self, SyncError> {
123        let mut iter = raw.split('-');
124        let (
125            Some(project),
126            Some(originator),
127            Some(volume_system),
128            Some(level_location),
129            Some(doc_type),
130            Some(discipline),
131            Some(number),
132        ) = (
133            iter.next(),
134            iter.next(),
135            iter.next(),
136            iter.next(),
137            iter.next(),
138            iter.next(),
139            iter.next(),
140        )
141        else {
142            let count = raw.split('-').count();
143            return Err(SyncError::InvalidContainerId(format!(
144                "expected 7 hyphen-delimited tokens in '{raw}', got {count}"
145            )));
146        };
147        let extra = iter.count();
148        if extra > 0 {
149            return Err(SyncError::InvalidContainerId(format!(
150                "expected 7 hyphen-delimited tokens in '{raw}', got {}",
151                7 + extra
152            )));
153        }
154        Self::new(
155            project,
156            originator,
157            volume_system,
158            level_location,
159            doc_type,
160            discipline,
161            number,
162        )
163    }
164
165    /// Checks that all seven fields are non-empty ASCII uppercase alphanumeric tokens.
166    pub fn validate(&self) -> Result<(), SyncError> {
167        validate_token("project", &self.project)?;
168        validate_token("originator", &self.originator)?;
169        validate_token("volume_system", &self.volume_system)?;
170        validate_token("level_location", &self.level_location)?;
171        validate_token("doc_type", &self.doc_type)?;
172        validate_token("discipline", &self.discipline)?;
173        validate_token("number", &self.number)
174    }
175
176    /// Formats the canonical hyphen-delimited ISO 19650-2 container code.
177    pub fn canonical_code(&self) -> String {
178        self.to_string()
179    }
180}
181
182impl fmt::Display for ContainerId {
183    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
184        write!(
185            f,
186            "{}-{}-{}-{}-{}-{}-{}",
187            self.project,
188            self.originator,
189            self.volume_system,
190            self.level_location,
191            self.doc_type,
192            self.discipline,
193            self.number
194        )
195    }
196}
197
198impl FromStr for ContainerId {
199    type Err = SyncError;
200
201    fn from_str(s: &str) -> Result<Self, Self::Err> {
202        Self::parse(s)
203    }
204}
205
206impl TryFrom<&str> for ContainerId {
207    type Error = SyncError;
208
209    fn try_from(value: &str) -> Result<Self, Self::Error> {
210        Self::parse(value)
211    }
212}
213
214fn validate_token(field: &str, value: &str) -> Result<(), SyncError> {
215    if value.is_empty() {
216        return Err(SyncError::InvalidContainerId(format!(
217            "{field} token must not be empty"
218        )));
219    }
220    if !value
221        .bytes()
222        .all(|b| b.is_ascii_uppercase() || b.is_ascii_digit())
223    {
224        return Err(SyncError::InvalidContainerId(format!(
225            "{field} token '{value}' must contain only ASCII uppercase alphanumeric characters"
226        )));
227    }
228    Ok(())
229}
230
231/// Immutable audit record appended on every CDE lifecycle state transition.
232#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
233pub struct TransitionRecord {
234    /// Lifecycle state prior to this transition.
235    pub from_state: CdeState,
236    /// Lifecycle state entered by this transition.
237    pub to_state: CdeState,
238    /// Suitability code assigned on transition.
239    pub suitability: SuitabilityCode,
240    /// Container revision string recorded at transition time.
241    pub revision: String,
242    /// Actor authorizing or executing the transition.
243    pub actor: ActorId,
244    /// UTC transition timestamp in nanoseconds.
245    pub timestamp_utc_ns: u64,
246    /// PIG Merkle root hash bound to this transition.
247    pub root_hash: ContentHash,
248    /// Human-readable audit note or transmittal summary.
249    pub note: String,
250}
251
252/// ISO 19650 Common Data Environment metadata and transition history for one container.
253#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
254pub struct ContainerMetadata {
255    /// Validated ISO 19650-2 / JKR container identifier.
256    pub id: ContainerId,
257    /// Current CDE lifecycle state.
258    pub state: CdeState,
259    /// Current ISO 19650 suitability code.
260    pub suitability: SuitabilityCode,
261    /// Container revision string (for example, `P01.01` in WIP or `C01` when Published).
262    pub revision: String,
263    /// Monotonic PIG graph revision bound to the current container state.
264    pub graph_revision: RevisionId,
265    /// Deterministic PIG SHA-256 root hash bound to the current container state.
266    pub root_hash: ContentHash,
267    /// Chronological audit trail of lifecycle state transitions.
268    pub audit_trail: Vec<TransitionRecord>,
269}
270
271impl ContainerMetadata {
272    /// Creates a new container in [`CdeState::WorkInProgress`] with [`SuitabilityCode::S0`].
273    pub fn new_wip(
274        id: ContainerId,
275        revision: impl Into<String>,
276        graph_revision: RevisionId,
277        root_hash: ContentHash,
278    ) -> Self {
279        Self {
280            id,
281            state: CdeState::WorkInProgress,
282            suitability: SuitabilityCode::S0,
283            revision: revision.into(),
284            graph_revision,
285            root_hash,
286            audit_trail: Vec::new(),
287        }
288    }
289
290    /// Returns `true` once the container is [`CdeState::Published`] or [`CdeState::Archived`].
291    #[inline]
292    pub const fn is_immutable(&self) -> bool {
293        matches!(self.state, CdeState::Published | CdeState::Archived)
294    }
295
296    /// Returns `true` if `(state, suitability)` is legal under the ISO 19650 suitability matrix.
297    #[inline]
298    pub const fn is_valid_state_suitability(state: CdeState, suitability: SuitabilityCode) -> bool {
299        matches!(
300            (state, suitability),
301            (CdeState::WorkInProgress, SuitabilityCode::S0)
302                | (
303                    CdeState::Shared,
304                    SuitabilityCode::S1
305                        | SuitabilityCode::S2
306                        | SuitabilityCode::S3
307                        | SuitabilityCode::S4
308                )
309                | (
310                    CdeState::Published,
311                    SuitabilityCode::A1
312                        | SuitabilityCode::A2
313                        | SuitabilityCode::A3
314                        | SuitabilityCode::A4
315                )
316                | (CdeState::Archived, SuitabilityCode::Cr)
317        )
318    }
319
320    /// Validates that the container's current `(state, suitability)` pair satisfies the matrix.
321    pub fn validate_state_suitability(&self) -> Result<(), SyncError> {
322        if Self::is_valid_state_suitability(self.state, self.suitability) {
323            Ok(())
324        } else {
325            Err(SyncError::InvalidTransition {
326                from: self.state,
327                to: self.state,
328                suitability: self.suitability,
329            })
330        }
331    }
332
333    /// Validates whether transitioning from `self.state` to `to` with `suitability` is legal.
334    pub fn validate_transition(
335        &self,
336        to: CdeState,
337        suitability: SuitabilityCode,
338    ) -> Result<(), SyncError> {
339        if self.state == CdeState::Archived {
340            return Err(SyncError::ContainerLocked(CdeState::Archived));
341        }
342        if self.state == CdeState::Published && to != CdeState::Archived {
343            return Err(SyncError::ContainerLocked(CdeState::Published));
344        }
345        if !Self::is_valid_state_suitability(to, suitability) {
346            return Err(SyncError::InvalidTransition {
347                from: self.state,
348                to,
349                suitability,
350            });
351        }
352        let legal_edge = matches!(
353            (self.state, to),
354            (CdeState::WorkInProgress, CdeState::Shared)
355                | (
356                    CdeState::Shared,
357                    CdeState::WorkInProgress | CdeState::Published
358                )
359                | (CdeState::Published, CdeState::Archived)
360        );
361        if !legal_edge {
362            return Err(SyncError::InvalidTransition {
363                from: self.state,
364                to,
365                suitability,
366            });
367        }
368        Ok(())
369    }
370}
371
372#[cfg(test)]
373mod tests {
374    use aecr_pig::{ContentHash, RevisionId};
375
376    use super::{CdeState, ContainerId, ContainerMetadata, SuitabilityCode};
377    use crate::error::SyncError;
378
379    #[test]
380    fn container_id_validates_iso19650_naming_rules() -> Result<(), SyncError> {
381        let id = ContainerId::parse("PRJ1-ARC-ZZ-01-M3-A-0001")?;
382        assert_eq!(id.project, "PRJ1");
383        assert_eq!(id.originator, "ARC");
384        assert_eq!(id.volume_system, "ZZ");
385        assert_eq!(id.level_location, "01");
386        assert_eq!(id.doc_type, "M3");
387        assert_eq!(id.discipline, "A");
388        assert_eq!(id.number, "0001");
389        assert_eq!(id.canonical_code(), "PRJ1-ARC-ZZ-01-M3-A-0001");
390        assert_eq!(id.to_string(), "PRJ1-ARC-ZZ-01-M3-A-0001");
391
392        // Lowercase, empty token, wrong segment count, and punctuation are rejected.
393        assert!(matches!(
394            ContainerId::parse("prj1-ARC-ZZ-01-M3-A-0001"),
395            Err(SyncError::InvalidContainerId(_))
396        ));
397        assert!(matches!(
398            ContainerId::parse("PRJ1-ARC--01-M3-A-0001"),
399            Err(SyncError::InvalidContainerId(_))
400        ));
401        assert!(matches!(
402            ContainerId::parse("PRJ1-ARC-ZZ-01-M3-A"),
403            Err(SyncError::InvalidContainerId(_))
404        ));
405        assert!(matches!(
406            ContainerId::new("PRJ1", "ARC", "ZZ", "01", "M3", "A_1", "0001"),
407            Err(SyncError::InvalidContainerId(_))
408        ));
409        Ok(())
410    }
411
412    #[test]
413    fn state_suitability_matrix_and_transition_locks() -> Result<(), SyncError> {
414        assert!(ContainerMetadata::is_valid_state_suitability(
415            CdeState::WorkInProgress,
416            SuitabilityCode::S0
417        ));
418        assert!(!ContainerMetadata::is_valid_state_suitability(
419            CdeState::WorkInProgress,
420            SuitabilityCode::S1
421        ));
422        assert!(ContainerMetadata::is_valid_state_suitability(
423            CdeState::Shared,
424            SuitabilityCode::S3
425        ));
426        assert!(!ContainerMetadata::is_valid_state_suitability(
427            CdeState::Shared,
428            SuitabilityCode::A1
429        ));
430        assert!(ContainerMetadata::is_valid_state_suitability(
431            CdeState::Published,
432            SuitabilityCode::A2
433        ));
434        assert!(!ContainerMetadata::is_valid_state_suitability(
435            CdeState::Published,
436            SuitabilityCode::Cr
437        ));
438        assert!(ContainerMetadata::is_valid_state_suitability(
439            CdeState::Archived,
440            SuitabilityCode::Cr
441        ));
442
443        let id = ContainerId::parse("PRJ1-ARC-ZZ-01-M3-A-0001")?;
444        let mut meta =
445            ContainerMetadata::new_wip(id, "P01.01", RevisionId::ZERO, ContentHash::ZERO);
446        assert!(!meta.is_immutable());
447        meta.validate_state_suitability()?;
448
449        // Skipping Shared or mismatched suitability fails.
450        assert!(matches!(
451            meta.validate_transition(CdeState::Published, SuitabilityCode::A1),
452            Err(SyncError::InvalidTransition { .. })
453        ));
454        assert!(matches!(
455            meta.validate_transition(CdeState::Shared, SuitabilityCode::S0),
456            Err(SyncError::InvalidTransition { .. })
457        ));
458        meta.validate_transition(CdeState::Shared, SuitabilityCode::S1)?;
459
460        // Published allows only Archived(Cr) and blocks other transitions via ContainerLocked.
461        meta.state = CdeState::Published;
462        meta.suitability = SuitabilityCode::A1;
463        assert!(meta.is_immutable());
464        assert!(matches!(
465            meta.validate_transition(CdeState::WorkInProgress, SuitabilityCode::S0),
466            Err(SyncError::ContainerLocked(CdeState::Published))
467        ));
468        assert!(matches!(
469            meta.validate_transition(CdeState::Shared, SuitabilityCode::S1),
470            Err(SyncError::ContainerLocked(CdeState::Published))
471        ));
472        meta.validate_transition(CdeState::Archived, SuitabilityCode::Cr)?;
473
474        // Archived locks every transition permanently.
475        meta.state = CdeState::Archived;
476        meta.suitability = SuitabilityCode::Cr;
477        assert!(meta.is_immutable());
478        assert!(matches!(
479            meta.validate_transition(CdeState::Archived, SuitabilityCode::Cr),
480            Err(SyncError::ContainerLocked(CdeState::Archived))
481        ));
482        Ok(())
483    }
484}