1use std::fmt;
4use std::str::FromStr;
5
6use aecr_pig::{ActorId, ContentHash, RevisionId};
7use serde::{Deserialize, Serialize};
8
9use crate::error::SyncError;
10
11#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
13pub enum CdeState {
14 WorkInProgress,
16 Shared,
18 Published,
20 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#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
37pub enum SuitabilityCode {
38 S0,
40 S1,
42 S2,
44 S3,
46 S4,
48 A1,
50 A2,
52 A3,
54 A4,
56 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#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
80pub struct ContainerId {
81 pub project: String,
83 pub originator: String,
85 pub volume_system: String,
87 pub level_location: String,
89 pub doc_type: String,
91 pub discipline: String,
93 pub number: String,
95}
96
97impl ContainerId {
98 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 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 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 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
233pub struct TransitionRecord {
234 pub from_state: CdeState,
236 pub to_state: CdeState,
238 pub suitability: SuitabilityCode,
240 pub revision: String,
242 pub actor: ActorId,
244 pub timestamp_utc_ns: u64,
246 pub root_hash: ContentHash,
248 pub note: String,
250}
251
252#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
254pub struct ContainerMetadata {
255 pub id: ContainerId,
257 pub state: CdeState,
259 pub suitability: SuitabilityCode,
261 pub revision: String,
263 pub graph_revision: RevisionId,
265 pub root_hash: ContentHash,
267 pub audit_trail: Vec<TransitionRecord>,
269}
270
271impl ContainerMetadata {
272 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 #[inline]
292 pub const fn is_immutable(&self) -> bool {
293 matches!(self.state, CdeState::Published | CdeState::Archived)
294 }
295
296 #[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 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 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 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 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 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 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}