Skip to main content

oxirs_samm/
lib.rs

1//! # OxiRS SAMM - Semantic Aspect Meta Model Implementation
2//!
3//! [![Version](https://img.shields.io/badge/version-0.2.4-blue)](https://github.com/cool-japan/oxirs/releases)
4//!
5//! **Status**: Production Release (v0.2.4)
6//! ✅ All public APIs documented. Production-ready with API stability guarantees.
7//!
8//! This crate provides a Rust implementation of the Semantic Aspect Meta Model (SAMM),
9//! which enables the creation of models to describe the semantics of digital twins.
10//!
11//! ## Overview
12//!
13//! SAMM (formerly BAMM) is a meta model for defining domain-specific aspects of digital twins.
14//! It provides a set of predefined objects that allow domain experts to define Aspect Models
15//! and complement digital twins with a semantic foundation.
16//!
17//! ## Core Concepts
18//!
19//! - **Aspect**: The root element describing a digital twin's specific aspect
20//! - **Property**: A named feature of an Aspect with a defined Characteristic
21//! - **Characteristic**: Describes the semantics of a Property's value
22//! - **Entity**: A complex data structure with multiple properties
23//! - **Operation**: A function that can be performed on an Aspect
24//! - **Event**: An occurrence that can be emitted by an Aspect
25//!
26//! ## Features
27//!
28//! - ✅ **SAMM 2.3.0 Support**: Full support for latest SAMM specification
29//! - ✅ **RDF/Turtle Parsing**: Load SAMM models from Turtle files
30//! - ✅ **SHACL Validation**: Validate models against SAMM shapes
31//! - ✅ **Code Generation**: Generate code in 7+ languages (Rust, TypeScript, Python, Java, Scala, GraphQL, SQL)
32//! - ✅ **AAS Integration**: Full Asset Administration Shell V3.0 support (XML, JSON, AASX packages)
33//! - ✅ **Performance Optimization**: Parallel processing, caching, profiling utilities
34//! - ✅ **Production Monitoring**: Metrics collection, health checks, structured logging
35//!
36//! ## Quick Start
37//!
38//! ### Basic Usage - Parse and Validate
39//!
40//! ```rust,no_run
41//! use oxirs_samm::metamodel::{Aspect, ModelElement};
42//! use oxirs_samm::parser::parse_aspect_model;
43//! use oxirs_samm::validator::validate_aspect;
44//!
45//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
46//! // Parse a SAMM model from a Turtle file
47//! let aspect = parse_aspect_model("path/to/AspectModel.ttl").await?;
48//!
49//! // Validate the aspect model
50//! let validation_result = validate_aspect(&aspect).await?;
51//! if !validation_result.is_valid {
52//!     for error in &validation_result.errors {
53//!         eprintln!("Validation error: {}", error.message);
54//!     }
55//! }
56//!
57//! // Access aspect properties
58//! println!("Aspect: {}", aspect.name());
59//! for property in aspect.properties() {
60//!     println!("  Property: {} (type: {:?})",
61//!              property.name(),
62//!              property.characteristic.as_ref().map(|c| &c.data_type));
63//! }
64//! # Ok(())
65//! # }
66//! ```
67//!
68//! ### Advanced Usage - Code Generation
69//!
70//! ```rust,no_run
71//! use oxirs_samm::parser::parse_aspect_model;
72//! use oxirs_samm::generators::{
73//!     generate_typescript, TsOptions,
74//!     generate_graphql,
75//!     generate_sql, SqlDialect,
76//! };
77//!
78//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
79//! let aspect = parse_aspect_model("Movement.ttl").await?;
80//!
81//! // Generate TypeScript interfaces
82//! let ts_code = generate_typescript(&aspect, TsOptions::default())?;
83//! std::fs::write("movement.ts", ts_code)?;
84//!
85//! // Generate GraphQL schema
86//! let graphql_schema = generate_graphql(&aspect)?;
87//! std::fs::write("movement.graphql", graphql_schema)?;
88//!
89//! // Generate SQL DDL
90//! let sql_ddl = generate_sql(&aspect, SqlDialect::PostgreSql)?;
91//! std::fs::write("movement.sql", sql_ddl)?;
92//! # Ok(())
93//! # }
94//! ```
95//!
96//! ### Performance Tuning
97//!
98//! ```rust,no_run
99//! use oxirs_samm::{PerformanceConfig, BatchProcessor, ModelCache};
100//!
101//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
102//! // Configure performance settings
103//! let config = PerformanceConfig {
104//!     parallel_processing: true,
105//!     num_workers: 8,
106//!     cache_size: 100,
107//!     profiling_enabled: true,
108//!     ..Default::default()
109//! };
110//!
111//! // Use batch processor for multiple models
112//! let processor = BatchProcessor::new(config);
113//! let models = vec![
114//!     "model1_content".to_string(),
115//!     "model2_content".to_string(),
116//!     "model3_content".to_string(),
117//! ];
118//! let results = processor.process_batch(models, |model| {
119//!     // Process each model
120//!     Ok(model.len())
121//! }).await?;
122//!
123//! // Use model cache for frequent lookups
124//! let cache = ModelCache::new(100);
125//! if let Some(cached_model) = cache.get("urn:samm:org.example:1.0.0#Movement") {
126//!     println!("Found cached model: {}", cached_model.len());
127//! }
128//! # Ok(())
129//! # }
130//! ```
131//!
132//! ### Production Monitoring
133//!
134//! ```rust,no_run
135//! use oxirs_samm::{
136//!     init_production, ProductionConfig,
137//!     MetricsCollector, OperationType,
138//!     health_check,
139//! };
140//!
141//! # fn example() -> Result<(), Box<dyn std::error::Error>> {
142//! // Initialize production monitoring
143//! let config = ProductionConfig::default();
144//! init_production(&config)?;
145//!
146//! // Collect metrics
147//! let metrics = MetricsCollector::global();
148//! metrics.record_operation(OperationType::Parse);
149//! metrics.record_operation_with_duration(OperationType::Parse, 150.0); // ms
150//!
151//! // Perform health checks
152//! let health_result = health_check();
153//! println!("System health: {:?}", health_result);
154//!
155//! // Get metrics snapshot
156//! let snapshot = metrics.snapshot();
157//! println!("Total operations: {}", snapshot.operations_total);
158//! println!("Parse operations: {}", snapshot.parse_operations);
159//! println!("Errors: {}", snapshot.errors_total);
160//! # Ok(())
161//! # }
162//! ```
163//!
164//! ## References
165//!
166//! - [SAMM Specification](https://eclipse-esmf.github.io/samm-specification/snapshot/index.html)
167//! - [Eclipse ESMF](https://github.com/eclipse-esmf)
168//! - [SAMM Java SDK](https://github.com/eclipse-esmf/esmf-sdk)
169
170// Documentation and linting configuration for Beta.1 release
171// All public APIs are now documented - enforcing strict documentation requirements
172#![deny(missing_docs)]
173#![warn(clippy::all)]
174#![allow(dead_code)]
175#![allow(unused_imports)]
176#![allow(unused_variables)]
177
178pub mod aas_parser;
179pub mod analytics;
180/// Structural differ for SAMM Aspect Models.
181pub mod aspect_differ;
182pub mod cache;
183pub mod cloud_backends;
184pub mod cloud_client;
185pub mod cloud_storage;
186pub mod codegen;
187pub mod comparison;
188pub mod documentation;
189pub mod dtdl_parser;
190pub mod error;
191pub mod generators;
192pub mod graph_analytics;
193pub mod metamodel;
194pub mod migration;
195pub mod operation_mapper;
196pub mod package;
197pub mod parser;
198pub mod performance;
199pub mod production;
200pub mod query;
201pub mod query_cache;
202pub mod serializer;
203pub mod simd_ops;
204pub mod submodel_templates;
205pub mod templates;
206pub mod transformation;
207pub mod utils;
208pub mod validation;
209pub mod validator;
210pub mod versioning;
211// SAMM vocabulary mapper (v1.1.0 round 5)
212pub mod vocabulary_mapper;
213
214// SAMM/BAMM unit catalog with SI and derived units (v1.1.0 round 6)
215pub mod unit_catalog;
216
217/// Registry of SAMM constraint types with validation support (v1.1.0 round 7).
218pub mod constraint_registry;
219
220/// SAMM aspect hierarchical property chain traversal (v1.1.0 round 8).
221pub mod aspect_chain;
222
223/// SAMM operation registry for aspect operations (v1.1.0 round 9).
224pub mod operation_registry;
225
226/// SAMM physical unit conversion engine (v1.1.0 round 10).
227pub mod unit_converter;
228
229/// SAMM event model for IoT events (v1.1.0 round 11).
230pub mod event_model;
231
232/// Aspect model serialization to JSON/YAML/Text (v1.1.0 round 12).
233pub mod aspect_export;
234
235/// SAMM characteristic validation (v1.1.0 round 13).
236pub mod characteristic_validator;
237
238/// SAMM aspect model validation — required properties, cardinality, constraints, cycles (v1.1.0 round 13).
239pub mod aspect_validator;
240
241/// SAMM aspect model serialization to JSON/YAML/Turtle/Compact formats (v1.1.0 round 14).
242pub mod model_serializer;
243
244/// SAMM entity resolution: hierarchy traversal, property flattening, and comparison (v1.1.0 round 12).
245pub mod entity_resolver;
246
247/// SAMM payload generation from aspect model definitions (v1.1.0 round 11).
248pub mod payload_generator;
249
250/// SAMM property mapping between aspect models and target schemas (v1.1.0 round 15).
251pub mod property_mapper;
252
253/// SAMM characteristic constraint validators (RangeConstraint, LengthConstraint, EncodingConstraint, RegularExpressionConstraint) (v1.1.0 round 16).
254pub mod constraint_validator;
255
256// Re-exports for convenience
257pub use analytics::{
258    Anomaly, AnomalyType, BenchmarkComparison, BenchmarkLevel, BestPracticeCheck,
259    BestPracticeReport, CheckCategory, ComplexityAssessment, ComplexityLevel, ConfidenceLevel,
260    CorrelationDirection, CorrelationInsight, CorrelationStrength, DependencyMetrics,
261    DistributionAnalysis, DistributionFit, DistributionParameters, DistributionStats,
262    DistributionType, ModelAnalytics, PropertyCorrelationMatrix, QualityTest, Recommendation,
263    RecommendationType, Severity, StatisticalAnomaly, StatisticalMetrics,
264};
265pub use cache::{
266    AspectCache, CacheStatistics, CharacteristicCache, EntityCache, LruModelCache, OperationCache,
267    PropertyCache, TtlCache, TtlCacheStatistics,
268};
269pub use cloud_client::{
270    CloudStorageClient, CloudStorageError, MockCloudStorage, RetryableCloudClient,
271};
272pub use cloud_storage::{
273    BatchResult, CacheStats, CloudModelStorage, CloudStorageBackend, MemoryBackend, ModelInfo,
274    ObjectMetadata,
275};
276pub use codegen::{
277    HttpMethod, JsonSchemaGenerator, JsonSchemaOptions, JsonSchemaValidator, OpenApiGenerator,
278    OpenApiOptions, ValidationError as JsonSchemaValidationError,
279};
280pub use comparison::{MetadataChange, MetadataChangeType, ModelComparison, PropertyChange};
281pub use documentation::{DocumentationFormat, DocumentationGenerator, DocumentationStyle};
282pub use dtdl_parser::parse_dtdl_interface;
283pub use error::{ErrorCategory, Result, SammError, SourceLocation};
284pub use generators::{GeneratedFile, MultiFileGenerator, MultiFileOptions, OutputLayout};
285pub use graph_analytics::{
286    CentralityMetrics, ChangeMagnitude, ColorScheme, Community, Cycle, CycleBreakSuggestion,
287    GraphComparison, GraphMetrics, ImpactAnalysis, ModelGraph, RiskLevel, VisualizationStyle,
288};
289pub use metamodel::{Aspect, Characteristic, Entity, Operation, Property};
290pub use migration::{MigrationOptions, MigrationResult, ModelMigrator, SammVersion};
291pub use parser::{ErrorRecoveryStrategy, RecoveryAction, RecoveryContext, StreamingParser};
292pub use performance::{BatchProcessor, ModelCache, PerformanceConfig};
293pub use production::{
294    health_check, init_production, HealthCheck, HealthStatus, MetricsCollector, OperationType,
295    ProductionConfig,
296};
297pub use query::{ComplexityMetrics, Dependency, ModelQuery};
298pub use query_cache::{CacheStatistics as QueryCacheStatistics, CachedModelQuery};
299pub use serializer::{
300    serialize_aspect_to_file, serialize_aspect_to_jsonld_file, serialize_aspect_to_jsonld_string,
301    serialize_aspect_to_rdfxml_file, serialize_aspect_to_rdfxml_string, serialize_aspect_to_string,
302    JsonLdSerializer, RdfXmlSerializer, TurtleSerializer,
303};
304pub use templates::{
305    scaffolding::{ModelTemplate, TemplateBuilder, TemplateRegistry},
306    PostRenderHook, PreRenderHook, TemplateContext, TemplateEngine, ValidationHook,
307};
308pub use transformation::{ModelTransformation, TransformationRule};
309pub use validation::{
310    SammSchemaValidator, SchemaValidationError, SchemaValidationWarning, ValidationReport,
311    ValidationRule,
312};
313pub use versioning::{AspectMigrationRegistry, AspectVersion, MigrationStep, VersionedAspect};
314
315/// SAMM version supported by this implementation
316pub const SAMM_VERSION: &str = "2.3.0";
317
318/// SAMM namespace URN prefix
319pub const SAMM_NAMESPACE: &str = "urn:samm:org.eclipse.esmf.samm";
320
321/// SAMM characteristics namespace
322pub const SAMM_C_NAMESPACE: &str = "urn:samm:org.eclipse.esmf.samm:characteristic";
323
324/// SAMM entities namespace
325pub const SAMM_E_NAMESPACE: &str = "urn:samm:org.eclipse.esmf.samm:entity";
326
327/// SAMM units namespace
328pub const SAMM_U_NAMESPACE: &str = "urn:samm:org.eclipse.esmf.samm:unit";
329
330#[cfg(test)]
331mod tests {
332    use super::*;
333
334    #[test]
335    fn test_samm_version() {
336        assert_eq!(SAMM_VERSION, "2.3.0");
337    }
338
339    #[test]
340    fn test_namespaces() {
341        assert!(SAMM_NAMESPACE.starts_with("urn:samm:"));
342        assert!(SAMM_C_NAMESPACE.contains("characteristic"));
343        assert!(SAMM_E_NAMESPACE.contains("entity"));
344        assert!(SAMM_U_NAMESPACE.contains("unit"));
345    }
346}