use serde::{Deserialize, Serialize};
use crate::checksum::Checksum;
use crate::enums::{
ArtifactType, CleEventType, CollectionOwner, CollectionUpdateReasonType,
ComplianceDocumentType, IdentifierType, TeaErrorCode,
};
use crate::error::ModelError;
use crate::ids::{
ArtifactId, CollectionId, ComponentId, ComponentReleaseId, DistributionId, ProductId,
ProductReleaseId, TeaTimestamp,
};
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct Identifier {
pub id_type: IdentifierType,
pub id_value: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct Product {
pub uuid: ProductId,
pub name: String,
pub identifiers: Vec<Identifier>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct ComponentRef {
pub uuid: ComponentId,
#[serde(default)]
pub release: Option<ComponentReleaseId>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct ProductRelease {
pub uuid: ProductReleaseId,
pub product: ProductId,
#[serde(default)]
pub product_name: Option<String>,
pub version: String,
pub created_date: TeaTimestamp,
#[serde(default)]
pub release_date: Option<TeaTimestamp>,
#[serde(default)]
pub pre_release: Option<bool>,
#[serde(default)]
pub identifiers: Option<Vec<Identifier>>,
pub components: Vec<ComponentRef>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct ProductReleaseWithCollection {
#[serde(flatten)]
pub release: ProductRelease,
pub latest_collection: Collection,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct Component {
pub uuid: ComponentId,
pub name: String,
pub identifiers: Vec<Identifier>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct ReleaseDistribution {
pub distribution_id: DistributionId,
#[serde(default)]
pub description: Option<String>,
#[serde(default)]
pub identifiers: Option<Vec<Identifier>>,
#[serde(default)]
pub url: Option<String>,
#[serde(default)]
pub signature_url: Option<String>,
#[serde(default)]
pub checksums: Option<Vec<Checksum>>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct ComponentRelease {
pub uuid: ComponentReleaseId,
pub component: ComponentId,
#[serde(default)]
pub component_name: Option<String>,
pub version: String,
pub created_date: TeaTimestamp,
#[serde(default)]
pub release_date: Option<TeaTimestamp>,
#[serde(default)]
pub pre_release: Option<bool>,
#[serde(default)]
pub identifiers: Option<Vec<Identifier>>,
#[serde(default)]
pub distributions: Option<Vec<ReleaseDistribution>>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct ComponentReleaseWithCollection {
#[serde(flatten)]
pub release: ComponentRelease,
pub latest_collection: Collection,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct CollectionUpdateReason {
#[serde(rename = "type")]
pub reason_type: CollectionUpdateReasonType,
#[serde(default)]
pub comment: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct ArtifactFormat {
pub media_type: String,
#[serde(default)]
pub description: Option<String>,
#[serde(default)]
pub url: Option<String>,
#[serde(default)]
pub signature_url: Option<String>,
#[serde(default)]
pub checksums: Option<Vec<Checksum>>,
}
impl ArtifactFormat {
pub fn validate(&self) -> Result<(), ModelError> {
if let Some(checksums) = &self.checksums {
if checksums.is_empty() {
return Err(ModelError::Invalid(
"checksums, when present, must contain at least one entry".into(),
));
}
}
if self.url.is_some() && self.checksums.as_ref().map(Vec::is_empty).unwrap_or(true) {
return Err(ModelError::Invalid(
"an artifact format with url must publish at least one checksum".into(),
));
}
if self.media_type.is_empty() {
return Err(ModelError::Invalid("mediaType must not be empty".into()));
}
Ok(())
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct Artifact {
pub uuid: ArtifactId,
pub version: u64,
#[serde(default)]
pub name: Option<String>,
#[serde(rename = "type")]
pub artifact_type: ArtifactType,
pub created_date: TeaTimestamp,
#[serde(default)]
pub distribution_ids: Option<Vec<DistributionId>>,
pub formats: Vec<ArtifactFormat>,
}
impl Artifact {
pub fn validate(&self) -> Result<(), ModelError> {
if self.version < 1 {
return Err(ModelError::Invalid("artifact version starts at 1".into()));
}
if self.formats.is_empty() {
return Err(ModelError::Invalid(
"artifact formats must not be empty".into(),
));
}
let mut seen = Vec::new();
for format in &self.formats {
format.validate()?;
if seen
.iter()
.any(|existing: &String| existing == &format.media_type)
{
return Err(ModelError::Invalid(format!(
"mediaType `{}` is repeated in one artifact revision",
format.media_type
)));
}
seen.push(format.media_type.clone());
}
Ok(())
}
#[must_use]
pub fn format(&self, media_type: &str) -> Option<&ArtifactFormat> {
self.formats
.iter()
.find(|format| format.media_type == media_type)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct Collection {
pub uuid: CollectionId,
pub version: u64,
pub created_date: TeaTimestamp,
pub belongs_to: CollectionOwner,
pub update_reason: CollectionUpdateReason,
pub artifacts: Vec<Artifact>,
}
impl Collection {
pub fn validate(&self) -> Result<(), ModelError> {
if self.version < 1 {
return Err(ModelError::Invalid("collection version starts at 1".into()));
}
for artifact in &self.artifacts {
artifact.validate()?;
}
Ok(())
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct Page<T> {
pub has_next: bool,
#[serde(default)]
pub next_page_token: Option<String>,
pub results: Vec<T>,
}
impl<T> Page<T> {
#[must_use]
pub fn new(results: Vec<T>, has_next: bool, next_page_token: Option<String>) -> Self {
Self {
has_next,
next_page_token,
results,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct TeaErrorBody {
pub error: TeaErrorCode,
#[serde(default)]
pub message: Option<String>,
}
impl TeaErrorBody {
pub fn parse(bytes: &[u8]) -> Result<Self, ModelError> {
Ok(serde_json::from_slice(bytes)?)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct TokenErrorBody {
pub error: String,
#[serde(default)]
pub error_description: Option<String>,
#[serde(default)]
pub error_uri: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[non_exhaustive]
pub struct TokenResponse {
pub access_token: String,
pub token_type: String,
#[serde(default)]
pub expires_in: Option<u64>,
#[serde(default)]
pub scope: Option<String>,
}
impl TokenResponse {
pub fn bearer(self) -> Result<Self, ModelError> {
if !self.token_type.eq_ignore_ascii_case("bearer") {
return Err(ModelError::Invalid(format!(
"token_type must be Bearer, got `{}`",
self.token_type
)));
}
if self.access_token.is_empty() {
return Err(ModelError::Invalid("access_token is empty".into()));
}
Ok(self)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct CleSupportDefinition {
pub id: String,
pub description: String,
#[serde(default)]
pub url: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct CleDefinitions {
#[serde(default)]
pub support: Option<Vec<CleSupportDefinition>>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct CleEvent {
pub id: i64,
#[serde(rename = "type")]
pub event_type: CleEventType,
pub effective: TeaTimestamp,
pub published: TeaTimestamp,
#[serde(default)]
pub version: Option<String>,
#[serde(default)]
pub versions: Option<Vec<CleVersionSpecifier>>,
#[serde(default)]
pub support_id: Option<String>,
#[serde(default)]
pub license: Option<String>,
#[serde(default)]
pub superseded_by_version: Option<String>,
#[serde(default)]
pub identifiers: Option<Vec<Identifier>>,
#[serde(default)]
pub event_id: Option<i64>,
#[serde(default)]
pub reason: Option<String>,
#[serde(default)]
pub description: Option<String>,
#[serde(default)]
pub references: Option<Vec<String>>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct CleVersionSpecifier {
#[serde(default)]
pub version: Option<String>,
#[serde(default)]
pub range: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Cle {
pub events: Vec<CleEvent>,
#[serde(default)]
pub definitions: Option<CleDefinitions>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ComplianceDocument(pub ComplianceDocumentType);
pub fn parse_json<T>(bytes: &[u8]) -> Result<T, ModelError>
where
T: for<'de> Deserialize<'de>,
{
Ok(serde_json::from_slice(bytes)?)
}
pub fn parse_artifact(bytes: &[u8]) -> Result<Artifact, ModelError> {
let artifact: Artifact = parse_json(bytes)?;
artifact.validate()?;
Ok(artifact)
}
pub fn parse_collection(bytes: &[u8]) -> Result<Collection, ModelError> {
let collection: Collection = parse_json(bytes)?;
collection.validate()?;
Ok(collection)
}
pub fn parse_product_release(bytes: &[u8]) -> Result<ProductReleaseWithCollection, ModelError> {
let value: ProductReleaseWithCollection = parse_json(bytes)?;
value.latest_collection.validate()?;
Ok(value)
}
pub fn parse_component_release(bytes: &[u8]) -> Result<ComponentReleaseWithCollection, ModelError> {
let value: ComponentReleaseWithCollection = parse_json(bytes)?;
value.latest_collection.validate()?;
Ok(value)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn artifact_with_url_requires_checksum() {
let json = br#"{
"uuid": "2ff3ae7c-8eab-4e0b-9b8b-1a0c4c4c1c2d",
"version": 1,
"type": "BOM",
"createdDate": "2026-01-02T03:04:05Z",
"formats": [{"mediaType": "application/vnd.cyclonedx+json", "url": "https://cdn.example/sbom.json"}]
}"#;
assert!(parse_artifact(json).is_err());
}
#[test]
fn preserves_unknown_artifact_type() {
let json = br#"{
"uuid": "2ff3ae7c-8eab-4e0b-9b8b-1a0c4c4c1c2d",
"version": 1,
"type": "FUTURE_DOC",
"createdDate": "2026-01-02T03:04:05.5Z",
"formats": [{"mediaType": "application/json", "checksums": [{"algType": "SHA-256", "algValue": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}]}]
}"#;
let artifact = parse_artifact(json).unwrap();
assert_eq!(artifact.artifact_type.as_str(), "FUTURE_DOC");
}
}