use std::fmt;
use std::str::FromStr;
use aecr_pig::{ActorId, ContentHash, RevisionId};
use serde::{Deserialize, Serialize};
use crate::error::SyncError;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub enum CdeState {
WorkInProgress,
Shared,
Published,
Archived,
}
impl fmt::Display for CdeState {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::WorkInProgress => f.write_str("WorkInProgress"),
Self::Shared => f.write_str("Shared"),
Self::Published => f.write_str("Published"),
Self::Archived => f.write_str("Archived"),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub enum SuitabilityCode {
S0,
S1,
S2,
S3,
S4,
A1,
A2,
A3,
A4,
Cr,
}
impl fmt::Display for SuitabilityCode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let code = match self {
Self::S0 => "S0",
Self::S1 => "S1",
Self::S2 => "S2",
Self::S3 => "S3",
Self::S4 => "S4",
Self::A1 => "A1",
Self::A2 => "A2",
Self::A3 => "A3",
Self::A4 => "A4",
Self::Cr => "Cr",
};
f.write_str(code)
}
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct ContainerId {
pub project: String,
pub originator: String,
pub volume_system: String,
pub level_location: String,
pub doc_type: String,
pub discipline: String,
pub number: String,
}
impl ContainerId {
pub fn new(
project: impl Into<String>,
originator: impl Into<String>,
volume_system: impl Into<String>,
level_location: impl Into<String>,
doc_type: impl Into<String>,
discipline: impl Into<String>,
number: impl Into<String>,
) -> Result<Self, SyncError> {
let id = Self {
project: project.into(),
originator: originator.into(),
volume_system: volume_system.into(),
level_location: level_location.into(),
doc_type: doc_type.into(),
discipline: discipline.into(),
number: number.into(),
};
id.validate()?;
Ok(id)
}
pub fn parse(raw: &str) -> Result<Self, SyncError> {
let mut iter = raw.split('-');
let (
Some(project),
Some(originator),
Some(volume_system),
Some(level_location),
Some(doc_type),
Some(discipline),
Some(number),
) = (
iter.next(),
iter.next(),
iter.next(),
iter.next(),
iter.next(),
iter.next(),
iter.next(),
)
else {
let count = raw.split('-').count();
return Err(SyncError::InvalidContainerId(format!(
"expected 7 hyphen-delimited tokens in '{raw}', got {count}"
)));
};
let extra = iter.count();
if extra > 0 {
return Err(SyncError::InvalidContainerId(format!(
"expected 7 hyphen-delimited tokens in '{raw}', got {}",
7 + extra
)));
}
Self::new(
project,
originator,
volume_system,
level_location,
doc_type,
discipline,
number,
)
}
pub fn validate(&self) -> Result<(), SyncError> {
validate_token("project", &self.project)?;
validate_token("originator", &self.originator)?;
validate_token("volume_system", &self.volume_system)?;
validate_token("level_location", &self.level_location)?;
validate_token("doc_type", &self.doc_type)?;
validate_token("discipline", &self.discipline)?;
validate_token("number", &self.number)
}
pub fn canonical_code(&self) -> String {
self.to_string()
}
}
impl fmt::Display for ContainerId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{}-{}-{}-{}-{}-{}-{}",
self.project,
self.originator,
self.volume_system,
self.level_location,
self.doc_type,
self.discipline,
self.number
)
}
}
impl FromStr for ContainerId {
type Err = SyncError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Self::parse(s)
}
}
impl TryFrom<&str> for ContainerId {
type Error = SyncError;
fn try_from(value: &str) -> Result<Self, Self::Error> {
Self::parse(value)
}
}
fn validate_token(field: &str, value: &str) -> Result<(), SyncError> {
if value.is_empty() {
return Err(SyncError::InvalidContainerId(format!(
"{field} token must not be empty"
)));
}
if !value
.bytes()
.all(|b| b.is_ascii_uppercase() || b.is_ascii_digit())
{
return Err(SyncError::InvalidContainerId(format!(
"{field} token '{value}' must contain only ASCII uppercase alphanumeric characters"
)));
}
Ok(())
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TransitionRecord {
pub from_state: CdeState,
pub to_state: CdeState,
pub suitability: SuitabilityCode,
pub revision: String,
pub actor: ActorId,
pub timestamp_utc_ns: u64,
pub root_hash: ContentHash,
pub note: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ContainerMetadata {
pub id: ContainerId,
pub state: CdeState,
pub suitability: SuitabilityCode,
pub revision: String,
pub graph_revision: RevisionId,
pub root_hash: ContentHash,
pub audit_trail: Vec<TransitionRecord>,
}
impl ContainerMetadata {
pub fn new_wip(
id: ContainerId,
revision: impl Into<String>,
graph_revision: RevisionId,
root_hash: ContentHash,
) -> Self {
Self {
id,
state: CdeState::WorkInProgress,
suitability: SuitabilityCode::S0,
revision: revision.into(),
graph_revision,
root_hash,
audit_trail: Vec::new(),
}
}
#[inline]
pub const fn is_immutable(&self) -> bool {
matches!(self.state, CdeState::Published | CdeState::Archived)
}
#[inline]
pub const fn is_valid_state_suitability(state: CdeState, suitability: SuitabilityCode) -> bool {
matches!(
(state, suitability),
(CdeState::WorkInProgress, SuitabilityCode::S0)
| (
CdeState::Shared,
SuitabilityCode::S1
| SuitabilityCode::S2
| SuitabilityCode::S3
| SuitabilityCode::S4
)
| (
CdeState::Published,
SuitabilityCode::A1
| SuitabilityCode::A2
| SuitabilityCode::A3
| SuitabilityCode::A4
)
| (CdeState::Archived, SuitabilityCode::Cr)
)
}
pub fn validate_state_suitability(&self) -> Result<(), SyncError> {
if Self::is_valid_state_suitability(self.state, self.suitability) {
Ok(())
} else {
Err(SyncError::InvalidTransition {
from: self.state,
to: self.state,
suitability: self.suitability,
})
}
}
pub fn validate_transition(
&self,
to: CdeState,
suitability: SuitabilityCode,
) -> Result<(), SyncError> {
if self.state == CdeState::Archived {
return Err(SyncError::ContainerLocked(CdeState::Archived));
}
if self.state == CdeState::Published && to != CdeState::Archived {
return Err(SyncError::ContainerLocked(CdeState::Published));
}
if !Self::is_valid_state_suitability(to, suitability) {
return Err(SyncError::InvalidTransition {
from: self.state,
to,
suitability,
});
}
let legal_edge = matches!(
(self.state, to),
(CdeState::WorkInProgress, CdeState::Shared)
| (
CdeState::Shared,
CdeState::WorkInProgress | CdeState::Published
)
| (CdeState::Published, CdeState::Archived)
);
if !legal_edge {
return Err(SyncError::InvalidTransition {
from: self.state,
to,
suitability,
});
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use aecr_pig::{ContentHash, RevisionId};
use super::{CdeState, ContainerId, ContainerMetadata, SuitabilityCode};
use crate::error::SyncError;
#[test]
fn container_id_validates_iso19650_naming_rules() -> Result<(), SyncError> {
let id = ContainerId::parse("PRJ1-ARC-ZZ-01-M3-A-0001")?;
assert_eq!(id.project, "PRJ1");
assert_eq!(id.originator, "ARC");
assert_eq!(id.volume_system, "ZZ");
assert_eq!(id.level_location, "01");
assert_eq!(id.doc_type, "M3");
assert_eq!(id.discipline, "A");
assert_eq!(id.number, "0001");
assert_eq!(id.canonical_code(), "PRJ1-ARC-ZZ-01-M3-A-0001");
assert_eq!(id.to_string(), "PRJ1-ARC-ZZ-01-M3-A-0001");
assert!(matches!(
ContainerId::parse("prj1-ARC-ZZ-01-M3-A-0001"),
Err(SyncError::InvalidContainerId(_))
));
assert!(matches!(
ContainerId::parse("PRJ1-ARC--01-M3-A-0001"),
Err(SyncError::InvalidContainerId(_))
));
assert!(matches!(
ContainerId::parse("PRJ1-ARC-ZZ-01-M3-A"),
Err(SyncError::InvalidContainerId(_))
));
assert!(matches!(
ContainerId::new("PRJ1", "ARC", "ZZ", "01", "M3", "A_1", "0001"),
Err(SyncError::InvalidContainerId(_))
));
Ok(())
}
#[test]
fn state_suitability_matrix_and_transition_locks() -> Result<(), SyncError> {
assert!(ContainerMetadata::is_valid_state_suitability(
CdeState::WorkInProgress,
SuitabilityCode::S0
));
assert!(!ContainerMetadata::is_valid_state_suitability(
CdeState::WorkInProgress,
SuitabilityCode::S1
));
assert!(ContainerMetadata::is_valid_state_suitability(
CdeState::Shared,
SuitabilityCode::S3
));
assert!(!ContainerMetadata::is_valid_state_suitability(
CdeState::Shared,
SuitabilityCode::A1
));
assert!(ContainerMetadata::is_valid_state_suitability(
CdeState::Published,
SuitabilityCode::A2
));
assert!(!ContainerMetadata::is_valid_state_suitability(
CdeState::Published,
SuitabilityCode::Cr
));
assert!(ContainerMetadata::is_valid_state_suitability(
CdeState::Archived,
SuitabilityCode::Cr
));
let id = ContainerId::parse("PRJ1-ARC-ZZ-01-M3-A-0001")?;
let mut meta =
ContainerMetadata::new_wip(id, "P01.01", RevisionId::ZERO, ContentHash::ZERO);
assert!(!meta.is_immutable());
meta.validate_state_suitability()?;
assert!(matches!(
meta.validate_transition(CdeState::Published, SuitabilityCode::A1),
Err(SyncError::InvalidTransition { .. })
));
assert!(matches!(
meta.validate_transition(CdeState::Shared, SuitabilityCode::S0),
Err(SyncError::InvalidTransition { .. })
));
meta.validate_transition(CdeState::Shared, SuitabilityCode::S1)?;
meta.state = CdeState::Published;
meta.suitability = SuitabilityCode::A1;
assert!(meta.is_immutable());
assert!(matches!(
meta.validate_transition(CdeState::WorkInProgress, SuitabilityCode::S0),
Err(SyncError::ContainerLocked(CdeState::Published))
));
assert!(matches!(
meta.validate_transition(CdeState::Shared, SuitabilityCode::S1),
Err(SyncError::ContainerLocked(CdeState::Published))
));
meta.validate_transition(CdeState::Archived, SuitabilityCode::Cr)?;
meta.state = CdeState::Archived;
meta.suitability = SuitabilityCode::Cr;
assert!(meta.is_immutable());
assert!(matches!(
meta.validate_transition(CdeState::Archived, SuitabilityCode::Cr),
Err(SyncError::ContainerLocked(CdeState::Archived))
));
Ok(())
}
}