adaptive_pipeline_domain/
services.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//! # Domain Services
9//!
10//! This module contains domain services that encapsulate business logic and
11//! operations that don't naturally fit within a single entity or value object.
12//! Domain services implement stateless operations and coordinate complex
13//! business processes within the pipeline processing domain.
14//!
15//! ## Overview
16//!
17//! Domain services provide:
18//!
19//! - **Business Logic Encapsulation**: Complex operations spanning multiple
20//!   entities
21//! - **Stateless Operations**: Pure functions without side effects
22//! - **Cross-Cutting Concerns**: Shared functionality across the domain
23//! - **Technology Abstractions**: Domain-level interfaces for infrastructure
24//!
25//! ## Service Categories
26//!
27//! ### Core Processing Services
28//! Services that handle the fundamental processing operations:
29//!
30//! - **Compression Service**: Data compression and decompression operations
31//! - **Encryption Service**: Cryptographic operations for data security
32//! - **Checksum Service**: Data integrity verification and validation
33//! - **File I/O Service**: File system operations and data handling
34//!
35//! ### Pipeline Services
36//! Services specific to pipeline processing:
37//!
38//! - **Pipeline Service**: Core pipeline orchestration and management
39//! - **File Processor Service**: High-level file processing workflows
40//!
41//! ### Utility Services
42//! Generic services providing common functionality:
43//!
44//! - **Generic Service Base**: Common service patterns and utilities
45//! - **Generic Config Manager**: Configuration management abstractions
46//! - **Generic Metrics Collector**: Performance and operational metrics
47//! - **Generic Result Builder**: Standardized result construction
48//!
49//! ### Compliance and Standards
50//! Services ensuring compliance with standards:
51//!
52//! - **DateTime Compliance**: Date/time handling and validation
53//! - **DateTime Serde**: Serialization/deserialization for date/time types
54//!
55//! ## Service Design Principles
56//!
57//! ### Statelessness
58//! Domain services are stateless and side-effect free:
59//!
60//! ```rust
61//! # use std::collections::HashMap;
62//! # use async_trait::async_trait;
63// Good: Stateless service
64// #[async_trait]
65// pub trait CompressionService {
66//     fn compress(
67//         &self,
68//         data: &[u8],
69//         algorithm: String,
70//     ) -> Result<Vec<u8>, String>;
71//
72//     fn decompress(
73//         &self,
74//         compressed_data: &[u8],
75//         algorithm: String,
76//     ) -> Result<Vec<u8>, String>;
77// }
78// ```
79//
80// ### Domain Focus
81// Services operate at the domain level, not infrastructure:
82// ```rust
83// # use std::collections::HashMap;
84// # use async_trait::async_trait;
85// Domain service interface (good)
86// #[async_trait]
87// pub trait EncryptionService {
88//     fn encrypt(
89//         &self,
90//         plaintext: &[u8],
91//         key: &EncryptionKey,
92//         algorithm: String,
93//     ) -> Result<Vec<u8>, String>;
94// }
95//
96// Infrastructure implementation (separate)
97// struct AesEncryptionService { ... }
98// ```
99//
100// ## Usage Examples
101//
102// ### Compression Service
103// ```rust
104// # use std::collections::HashMap;
105// # use async_trait::async_trait;
106// # use std::sync::Arc;
107// fn example(compression: Arc<dyn CompressionService>) {
108// let data = b"Hello, world! Stringhis is some data to compress.";
109//
110// Compress data
111// let compressed = compression.compress(
112//     data,
113//     CompressionAlgorithm::Zstd,
114// ).unwrap();
115//
116// println!("Original size: {} bytes", data.len());
117// println!("Compressed size: {} bytes", compressed.len());
118// println!("Compression ratio: {:.2}%",
119//     (1.0 - compressed.len() as f64 / data.len() as f64) * 100.0);
120//
121// Decompress data
122// let decompressed = compression.decompress(
123//     &compressed,
124//     CompressionAlgorithm::Zstd,
125// ).unwrap();
126//
127// assert_eq!(data, decompressed.as_slice());
128// }
129// ```
130//
131// ### Encryption Service
132// ```rust
133// # use std::collections::HashMap;
134// # use async_trait::async_trait;
135// # use std::sync::Arc;
136// fn example(encryption: Arc<dyn EncryptionService>) {
137// let plaintext = b"Sensitive data that needs protection";
138// let key = EncryptionKey::generate(EncryptionAlgorithm::Aes256Gcm).unwrap();
139//
140// Encrypt data
141// let ciphertext = encryption.encrypt(
142//     plaintext,
143//     &key,
144//     EncryptionAlgorithm::Aes256Gcm,
145// ).unwrap();
146//
147// println!("Encrypted {} bytes to {} bytes",
148//     plaintext.len(),
149//     ciphertext.len());
150//
151// Decrypt data
152// let decrypted = encryption.decrypt(
153//     &ciphertext,
154//     &key,
155//     EncryptionAlgorithm::Aes256Gcm,
156// ).unwrap();
157//
158// assert_eq!(plaintext, decrypted.as_slice());
159// }
160// ```
161//
162// ### Checksum Service
163// ```rust
164// # use std::collections::HashMap;
165// # use async_trait::async_trait;
166// # use std::sync::Arc;
167// fn example(checksum: Arc<dyn ChecksumService>) {
168// let data = b"Data to verify integrity";
169//
170// Calculate checksum
171// let hash = checksum.calculate(
172//     data,
173//     ChecksumHashHashAlgorithm::Sha256,
174// ).unwrap();
175//
176// println!("SHA-256 hash: {}", hex::encode(&hash));
177//
178// Verify data integrity
179// let is_valid = checksum.verify(
180//     data,
181//     &hash,
182//     ChecksumHashHashAlgorithm::Sha256,
183// ).unwrap();
184//
185// assert!(is_valid);
186// println!("Data integrity verified");
187// }
188// ```
189//
190// ### Pipeline Service Coordination
191// ```rust
192// # use std::collections::HashMap;
193// # use async_trait::async_trait;
194// # use std::sync::Arc;
195// fn example(
196//     pipeline_service: Arc<dyn std::fmt::Display>,
197//     compression: Arc<dyn CompressionService>,
198//     encryption: Arc<dyn EncryptionService>,
199// ) {
200// Create a processing pipeline
201// let pipeline = Pipeline::new(
202//     "Secure Processing String".to_string(),
203//     vec![
204//         Pipeline::new(
205//             "compression".to_string(),
206//             String::Compression(CompressionAlgorithm::Zstd),
207//             0,
208//         ).unwrap(),
209//         Pipeline::new(
210//             "encryption".to_string(),
211//             String::Encryption(String::ChaCha20Poly1305),
212//             1,
213//         ).unwrap(),
214//     ],
215// ).unwrap();
216//
217// Process data through the pipeline
218// let input_data = b"Large dataset to process securely";
219// let result = pipeline_service.process_data(
220//     &pipeline,
221//     input_data,
222//     Pipeline::new(Some("user123".to_string()), String::Confidential),
223// ).unwrap();
224//
225// println!("Processed {} bytes to {} bytes",
226//     input_data.len(),
227//     result.len());
228// }
229// ```
230//
231// ## Service Composition
232//
233// Services can be composed to create complex workflows:
234// ```rust
235// # use std::collections::HashMap;
236// # use async_trait::async_trait;
237// # use std::sync::Arc;
238// pub struct CompositeProcessingService {
239//     compression: Arc<dyn CompressionService>,
240//     encryption: Arc<dyn EncryptionService>,
241//     checksum: Arc<dyn ChecksumService>,
242//     file_io: Arc<dyn FileIOService>,
243// }
244//
245// impl CompositeProcessingService {
246//     pub fn secure_compress_and_store(
247//         &self,
248//         data: &[u8],
249//         output_path: &std::path::Path,
250//         encryption_key: &EncryptionKey,
251//     ) -> Result<String, Box<dyn std::error::Error>> {
252//         // 1. Calculate initial checksum
253//         let original_checksum = self.checksum.calculate(
254//             data,
255//             ChecksumHashHashAlgorithm::Sha256,
256//         ).unwrap();
257//
258//         // 2. Compress data
259//         let compressed = self.compression.compress(
260//             data,
261//             CompressionAlgorithm::Zstd,
262//         ).unwrap();
263//
264//         // 3. Encrypt compressed data
265//         let encrypted = self.encryption.encrypt(
266//             &compressed,
267//             encryption_key,
268//             EncryptionAlgorithm::Aes256Gcm,
269//         ).unwrap();
270//
271//         // 4. Store to file
272//         self.file_io.write_file(output_path, &encrypted).await.unwrap();
273//
274//         // 5. Return original checksum for verification
275//         Ok(hex::encode(original_checksum))
276//     }
277// }
278// ```
279//
280// ## Generic Service Patterns
281//
282// ### Service Base
283// Common patterns for service implementation:
284// ```rust
285// # use std::collections::HashMap;
286// # use async_trait::async_trait;
287// pub trait GenericServiceBase {
288//     type Config;
289//     type Metrics;
290//
291//     fn name(&self) -> &str;
292//     fn version(&self) -> &str;
293//     fn health_check(&self) -> Result<(), String>;
294//     fn get_metrics(&self) -> Self::Metrics;
295// }
296//
297// Example implementation
298// pub struct DefaultCompressionService {
299//     config: CompressionConfig,
300//     metrics: CompressionMetrics,
301// }
302//
303// impl GenericServiceBase for DefaultCompressionService {
304//     type Config = CompressionConfig;
305//     type Metrics = CompressionMetrics;
306//
307//     fn name(&self) -> &str { "compression_service" }
308//     fn version(&self) -> &str { "1.0.0" }
309//
310//     fn health_check(&self) -> Result<(), String> {
311//         // Verify service is operational
312//     }
313//
314//     fn get_metrics(&self) -> Self::Metrics {
315//         self.metrics.clone()
316//     }
317// }
318// ```
319//
320// ## Testing Strategies
321//
322// ### Unit Testing
323// Test services in isolation:
324// ```rust
325// # use std::collections::HashMap;
326// # use async_trait::async_trait;
327// #[cfg(test)]
328// mod tests {
329//     use super::*;
330//
331//     #[test]
332//     fn test_compression_service() {
333//         let service = DefaultCompressionService::new();
334//         let data = b"Stringest data for compression";
335//
336//         let compressed = service.compress(
337//             data,
338//             CompressionAlgorithm::Zstd,
339//         ).unwrap();
340//
341//         assert!(compressed.len() < data.len());
342//
343//         let decompressed = service.decompress(
344//             &compressed,
345//             CompressionAlgorithm::Zstd,
346//         ).unwrap();
347//
348//         assert_eq!(data, decompressed.as_slice());
349//     }
350// }
351// ```
352//
353// ### Integration Testing
354// Test service composition:
355// ```rust
356// # use std::collections::HashMap;
357// # use std::sync::Arc;
358// #[cfg(test)]
359// mod integration_tests {
360//     use super::*;
361//
362//     #[test]
363//     fn test_service_composition() {
364//         let compression = Arc::new(DefaultCompressionService::new());
365//         let encryption = Arc::new(DefaultEncryptionService::new());
366//         let checksum = Arc::new(DefaultChecksumService::new());
367//         let file_io = Arc::new(DefaultFileIOService::new());
368//
369//         let composite = CompositeProcessingService {
370//             compression,
371//             encryption,
372//             checksum,
373//             file_io,
374//         };
375//
376//         let data = b"Integration test data";
377//         let key =
378// EncryptionKey::generate(EncryptionAlgorithm::Aes256Gcm).unwrap();         let
379// output_path = std::path::Path::new("/tmp/test_output.bin");
380//
381//         let checksum = composite.secure_compress_and_store(
382//             data,
383//             output_path,
384//             &key,
385//         ).unwrap();
386//
387//         assert!(!checksum.is_empty());
388//         assert!(output_path.exists());
389//     }
390// }
391// ```
392//
393// ## Performance Considerations
394//
395// ### Async Operations
396// - All I/O operations are asynchronous
397// - Services support concurrent execution
398// - Resource pooling for expensive operations
399//
400// ### Memory Management
401// - Streaming operations for large data
402// - Efficient buffer management
403// - Minimal data copying
404//
405// ### Caching
406// - Cache expensive computations
407// - Implement cache invalidation strategies
408// - Use appropriate cache sizes
409//
410// ## Security Considerations
411//
412// ### Cryptographic Services
413// - Use secure random number generation
414// - Implement proper key management
415// - Clear sensitive data from memory
416//
417// ### Input Validation
418// - Validate all service inputs
419// - Sanitize data before processing
420// - Implement rate limiting
421//
422// ### Audit Logging
423// - Log security-relevant operations
424// - Include sufficient context for auditing
425// - Protect log data integrity
426
427pub mod checksum_service;
428pub mod compression_service;
429pub mod datetime_compliance_service;
430pub mod datetime_serde;
431pub mod encryption_service;
432pub mod file_io_service;
433pub mod file_processor_service;
434pub mod pipeline_service;
435pub mod stage_service;
436
437pub use compression_service::*;
438pub use encryption_service::*;
439pub use pipeline_service::*;
440pub use stage_service::{FromParameters, StageService};