adaptive_pipeline_domain/services/datetime_compliance_service.rs
1// /////////////////////////////////////////////////////////////////////////////
2// Adaptive Pipeline
3// Copyright (c) 2025 Michael Gardner, A Bit of Help, Inc.
4// SPDX-License-Identifier: BSD-3-Clause
5// See LICENSE file in the project root.
6// /////////////////////////////////////////////////////////////////////////////
7
8//! # DateTime Compliance Service
9//!
10//! This module provides RFC3339 datetime compliance utilities and validation
11//! for the adaptive pipeline system. It ensures all datetime values in the
12//! system are RFC3339 compliant as required by the SRS documentation.
13//!
14//! ## Overview
15//!
16//! The datetime compliance service provides:
17//!
18//! - **RFC3339 Compliance**: Ensure all datetime values follow RFC3339 standard
19//! - **Validation**: Comprehensive datetime validation and verification
20//! - **Serialization**: Consistent datetime serialization across the system
21//! - **Testing**: Testing utilities for datetime compliance verification
22//! - **Standards Compliance**: Adherence to international datetime standards
23//!
24//! ## Architecture
25//!
26//! The service follows standards compliance principles:
27//!
28//! - **RFC3339 Standard**: Full compliance with RFC3339 datetime format
29//! - **UTC Normalization**: All timestamps normalized to UTC
30//! - **Serialization Consistency**: Consistent serialization format
31//! - **Validation Framework**: Comprehensive validation and testing
32//!
33//! ## Key Features
34//!
35//! ### RFC3339 Compliance
36//!
37//! - **Standard Format**: YYYY-MM-DDTHH:MM:SS.sssZ format
38//! - **Timezone Support**: Proper timezone handling and UTC normalization
39//! - **Precision**: Millisecond precision for accurate timestamps
40//! - **Validation**: Automatic validation of datetime formats
41//!
42//! ### Serialization
43//!
44//! - **JSON Serialization**: Consistent JSON serialization format
45//! - **Deserialization**: Robust deserialization with error handling
46//! - **Optional Values**: Support for optional datetime fields
47//! - **Null Handling**: Proper handling of null datetime values
48//!
49//! ### Testing and Validation
50//!
51//! - **Compliance Testing**: Automated compliance testing utilities
52//! - **Format Validation**: Validation of datetime format compliance
53//! - **Round-trip Testing**: Serialization/deserialization round-trip testing
54//! - **Error Detection**: Detection and reporting of compliance violations
55//!
56//! ## Usage Examples
57//!
58//! ### Basic DateTime Compliance
59
60//!
61//! ### Custom DateTime Validation
62
63//!
64//! ### Batch DateTime Validation
65
66//!
67//! ### Integration with Domain Entities
68
69//!
70//! ## RFC3339 Standard Compliance
71//!
72//! ### Format Specification
73//!
74//! The RFC3339 format specification:
75//!
76//! - **Basic Format**: `YYYY-MM-DDTHH:MM:SSZ`
77//! - **With Milliseconds**: `YYYY-MM-DDTHH:MM:SS.sssZ`
78//! - **With Timezone**: `YYYY-MM-DDTHH:MM:SS.sss+/-HH:MM`
79//! - **UTC Indicator**: `Z` suffix for UTC timestamps
80//!
81//! ### Validation Rules
82//!
83//! - **Year**: 4-digit year (0000-9999)
84//! - **Month**: 2-digit month (01-12)
85//! - **Day**: 2-digit day (01-31, depending on month)
86//! - **Hour**: 2-digit hour (00-23)
87//! - **Minute**: 2-digit minute (00-59)
88//! - **Second**: 2-digit second (00-59)
89//! - **Milliseconds**: Optional 3-digit milliseconds (000-999)
90//! - **Timezone**: UTC (Z) or offset (+/-HH:MM)
91//!
92//! ### Compliance Testing
93//!
94//! - **Format Validation**: Validate datetime string format
95//! - **Value Validation**: Validate datetime component values
96//! - **Timezone Validation**: Validate timezone specifications
97//! - **Round-trip Testing**: Serialize/deserialize consistency
98//!
99//! ## Serialization Support
100//!
101//! ### JSON Serialization
102//!
103//! - **Consistent Format**: All datetimes serialized in RFC3339 format
104//! - **UTC Normalization**: All timestamps normalized to UTC
105//! - **Precision Preservation**: Millisecond precision preserved
106//! - **Null Handling**: Proper handling of optional datetime fields
107//!
108//! ### Custom Serialization
109//!
110//! - **Serde Integration**: Full integration with Serde serialization
111//! - **Custom Formats**: Support for custom datetime formats when needed
112//! - **Backward Compatibility**: Maintain compatibility with existing data
113//!
114//! ## Error Handling
115//!
116//! ### Validation Errors
117//!
118//! - **Format Errors**: Invalid datetime format strings
119//! - **Value Errors**: Invalid datetime component values
120//! - **Timezone Errors**: Invalid timezone specifications
121//! - **Precision Errors**: Precision loss during serialization
122//!
123//! ### Error Recovery
124//!
125//! - **Graceful Degradation**: Handle invalid datetimes gracefully
126//! - **Error Reporting**: Detailed error messages with context
127//! - **Fallback Values**: Use fallback values for invalid datetimes
128//!
129//! ## Performance Considerations
130//!
131//! ### Validation Efficiency
132//!
133//! - **Cached Validators**: Cache validation logic for better performance
134//! - **Batch Processing**: Efficient batch validation of multiple datetimes
135//! - **Lazy Validation**: Validate only when necessary
136//!
137//! ### Serialization Performance
138//!
139//! - **Efficient Serialization**: Optimized serialization routines
140//! - **Memory Usage**: Minimal memory usage during serialization
141//! - **String Pooling**: Reuse common datetime strings
142//!
143//! ## Integration
144//!
145//! The datetime compliance service integrates with:
146//!
147//! - **Domain Entities**: Validate datetime fields in domain entities
148//! - **Serialization**: Ensure consistent datetime serialization
149//! - **Database**: Store datetimes in RFC3339 format
150//! - **API**: Consistent datetime format in API responses
151//!
152//! ## Standards Compliance
153//!
154//! ### RFC3339 Compliance
155//!
156//! - **Full Compliance**: Complete adherence to RFC3339 standard
157//! - **Interoperability**: Ensure interoperability with other systems
158//! - **Future Compatibility**: Maintain compatibility with future standards
159//!
160//! ### ISO 8601 Compatibility
161//!
162//! - **Subset Compliance**: RFC3339 is a subset of ISO 8601
163//! - **Extended Support**: Support for extended ISO 8601 features
164//! - **Migration Support**: Support for migrating from other formats
165//!
166//! ## Future Enhancements
167//!
168//! Planned enhancements include:
169//!
170//! - **Timezone Database**: Integration with timezone database
171//! - **Localization**: Support for localized datetime formats
172//! - **Performance Optimization**: Further performance optimizations
173//! - **Extended Validation**: More comprehensive validation rules
174
175/// RFC3339 datetime compliance utilities and tests
176///
177/// This module ensures all datetime values in the system are RFC3339 compliant
178/// as required by the SRS documentation.
179use chrono::{DateTime, Utc};
180use serde::{Deserialize, Serialize};
181
182/// Test structure to verify RFC3339 compliance
183///
184/// This structure provides a comprehensive test framework for validating
185/// RFC3339 datetime compliance across the system. It includes both required
186/// and optional datetime fields to test various scenarios.
187///
188/// # Key Features
189///
190/// - **Required DateTime**: Tests mandatory datetime field compliance
191/// - **Optional DateTime**: Tests optional datetime field compliance
192/// - **Serialization Testing**: Validates serialization format compliance
193/// - **Round-trip Testing**: Ensures serialization/deserialization consistency
194///
195/// # Examples
196#[derive(Debug, Clone, Serialize, Deserialize)]
197pub struct DateTimeTest {
198 pub timestamp: DateTime<Utc>,
199 pub optional_timestamp: Option<DateTime<Utc>>,
200}
201
202impl Default for DateTimeTest {
203 fn default() -> Self {
204 Self::new()
205 }
206}
207
208impl DateTimeTest {
209 /// Creates a new test instance with current timestamp
210 pub fn new() -> Self {
211 Self {
212 timestamp: Utc::now(),
213 optional_timestamp: Some(Utc::now()),
214 }
215 }
216
217 /// Verifies that serialization produces RFC3339 format
218 pub fn verify_rfc3339_compliance(&self) -> Result<(), String> {
219 // Serialize to JSON
220 let json = serde_json::to_string(self).map_err(|e| format!("Serialization failed: {}", e))?;
221
222 // Check that the timestamp is in RFC3339 format
223 // RFC3339 format: YYYY-MM-DDTHH:MM:SS.sssZ or YYYY-MM-DDTHH:MM:SS.sss+/-HH:MM
224 let rfc3339_regex = regex::Regex::new(r#"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})"#)
225 .map_err(|e| format!("Regex compilation failed: {}", e))?;
226
227 if !rfc3339_regex.is_match(&json) {
228 return Err(format!("Serialized JSON does not contain RFC3339 timestamps: {}", json));
229 }
230
231 // Deserialize back to verify round-trip compatibility
232 let _deserialized: DateTimeTest =
233 serde_json::from_str(&json).map_err(|e| format!("Deserialization failed: {}", e))?;
234
235 Ok(())
236 }
237
238 /// Returns the RFC3339 string representation of the timestamp
239 pub fn to_rfc3339_string(&self) -> String {
240 self.timestamp.to_rfc3339()
241 }
242}
243
244/// Utility function to ensure all datetime values in the system are RFC3339
245/// compliant
246pub fn ensure_rfc3339_compliance() {
247 // This function serves as documentation that all DateTime<Utc> fields
248 // in our domain automatically serialize to RFC3339 format when using serde
249
250 // Key points:
251 // 1. All datetime fields use chrono::DateTime<chrono::Utc>
252 // 2. All structs with datetime fields have Serialize/Deserialize derives
253 // 3. chrono automatically uses RFC3339 format for serialization
254 // 4. UTC timezone ensures consistent handling across systems
255}
256
257#[cfg(test)]
258mod tests {
259 use super::*;
260
261 /// Tests RFC3339 datetime compliance validation and formatting.
262 ///
263 /// This test validates that datetime instances comply with RFC3339
264 /// standards and that RFC3339 string formatting produces correctly
265 /// formatted timestamps for interoperability.
266 ///
267 /// # Test Coverage
268 ///
269 /// - RFC3339 compliance verification
270 /// - RFC3339 string formatting
271 /// - Timezone indicator validation
272 /// - Timestamp format structure
273 /// - Standards compliance checking
274 ///
275 /// # Test Scenario
276 ///
277 /// Creates a datetime test instance and verifies RFC3339 compliance
278 /// and proper string formatting with timezone indicators.
279 ///
280 /// # Domain Concerns
281 ///
282 /// - Datetime standards compliance
283 /// - Interoperability and data exchange
284 /// - Timestamp formatting consistency
285 /// - Cross-system compatibility
286 ///
287 /// # Assertions
288 ///
289 /// - RFC3339 compliance verification succeeds
290 /// - RFC3339 string contains 'T' separator
291 /// - RFC3339 string has proper timezone indicator
292 /// - Timestamp format meets standards
293 #[test]
294 fn test_rfc3339_compliance() {
295 let test_instance = DateTimeTest::new();
296
297 // Verify RFC3339 compliance
298 assert!(test_instance.verify_rfc3339_compliance().is_ok());
299
300 // Verify manual RFC3339 conversion
301 let rfc3339_string = test_instance.to_rfc3339_string();
302 assert!(rfc3339_string.contains('T'));
303 assert!(rfc3339_string.ends_with('Z') || rfc3339_string.contains('+') || rfc3339_string.contains('-'));
304 }
305
306 /// Tests datetime serialization format compliance and JSON output.
307 ///
308 /// This test validates that datetime instances serialize to JSON
309 /// with proper RFC3339 formatting and that serialized timestamps
310 /// maintain standards compliance.
311 ///
312 /// # Test Coverage
313 ///
314 /// - JSON serialization of datetime instances
315 /// - RFC3339 format preservation in JSON
316 /// - Serialized timestamp structure validation
317 /// - JSON output format verification
318 /// - Standards compliance in serialization
319 ///
320 /// # Test Scenario
321 ///
322 /// Serializes a datetime test instance to JSON and verifies
323 /// that the output contains properly formatted RFC3339 timestamps.
324 ///
325 /// # Domain Concerns
326 ///
327 /// - Data serialization and persistence
328 /// - API data exchange formats
329 /// - Timestamp serialization consistency
330 /// - Standards compliance in data output
331 ///
332 /// # Assertions
333 ///
334 /// - JSON serialization succeeds
335 /// - Serialized JSON contains 'T' separator
336 /// - Serialized JSON has timezone indicators
337 /// - Timestamp format is preserved in JSON
338 #[test]
339 fn test_serialization_format() {
340 let test_instance = DateTimeTest::new();
341 let json = serde_json::to_string(&test_instance).unwrap();
342
343 // Verify that the JSON contains RFC3339 formatted timestamps
344 println!("Serialized JSON: {}", json);
345 assert!(json.contains("T"));
346 assert!(json.contains("Z") || json.contains("+") || json.contains("-"));
347 }
348}