| Crates.io | adaptive-pipeline-bootstrap |
| lib.rs | adaptive-pipeline-bootstrap |
| version | 2.0.0 |
| created_at | 2025-10-12 10:49:16.423804+00 |
| updated_at | 2025-10-12 10:49:16.423804+00 |
| description | Bootstrap module for optimized, adaptive pipeline crate - handles entry point, DI, signals, and platform abstraction |
| homepage | |
| repository | https://github.com/abitofhelp/adaptive_pipeline.git |
| max_upload_size | |
| id | 1879173 |
| size | 147,774 |
Bootstrap and platform abstraction layer for the Adaptive Pipeline - Handles application entry points, dependency injection, signal handling, and cross-platform operations.
This crate sits outside the enterprise application layers and provides the foundational infrastructure needed to bootstrap and run Rust applications with:
Add this to your Cargo.toml:
[dependencies]
adaptive-pipeline-bootstrap = "1.0"
Bootstrap is the outermost layer that initializes the application:
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ BOOTSTRAP (This Crate) โ
โ - Entry Point โ
โ - DI Container (Composition Root) โ
โ - Platform Abstraction โ
โ - Signal Handling โ
โ - Secure Arg Parsing โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ APPLICATION LAYER โ
โ - Use Cases โ
โ - Application Services โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ DOMAIN LAYER โ
โ - Business Logic โ
โ - Domain Services โ
โ - Entities & Value Objects โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โฒ
โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ INFRASTRUCTURE LAYER โ
โ - Adapters โ
โ - Repositories โ
โ - External Services โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
use bootstrap::{bootstrap_cli, result_to_exit_code};
#[tokio::main]
async fn main() -> std::process::ExitCode {
// Parse and validate CLI arguments
let cli = match bootstrap::bootstrap_cli() {
Ok(cli) => cli,
Err(e) => {
eprintln!("CLI Error: {}", e);
return std::process::ExitCode::from(65); // EX_DATAERR
}
};
// Run application with validated config
let result = run_application(cli).await;
// Map result to Unix exit code
result_to_exit_code(result)
}
async fn run_application(cli: bootstrap::ValidatedCli) -> Result<(), String> {
println!("Running with config: {:?}", cli);
Ok(())
}
use bootstrap::platform::create_platform;
// Get platform-specific implementation
let platform = create_platform();
// Cross-platform API
println!("Platform: {}", platform.platform_name());
println!("CPU cores: {}", platform.cpu_count());
println!("Page size: {} bytes", platform.page_size());
// Memory information
let total = platform.total_memory()?;
let available = platform.available_memory()?;
println!("Memory: {}/{} GB", available / 1_000_000_000, total / 1_000_000_000);
// Platform-specific constants
println!("Line separator: {:?}", platform.line_separator());
println!("Path separator: {:?}", platform.path_separator());
use bootstrap::signals::create_signal_handler;
use bootstrap::shutdown::ShutdownCoordinator;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// Set up graceful shutdown
let coordinator = ShutdownCoordinator::new();
let signal_handler = create_signal_handler(coordinator.token());
// Start signal monitoring
tokio::spawn(async move {
signal_handler.wait_for_signal().await;
println!("Received shutdown signal - cleaning up...");
});
// Run application with cancellation
run_with_cancellation(coordinator.token()).await?;
// Wait for graceful shutdown (with timeout)
coordinator.wait_for_completion(30).await?;
Ok(())
}
use bootstrap::cli::{parse_and_validate, ValidatedCli};
// Parse with automatic validation
let cli = parse_and_validate()?;
// All inputs are validated:
// - No SQL injection patterns
// - No path traversal (../)
// - No dangerous shell characters
// - Numbers within allowed ranges
// - Paths are sanitized
match &cli.command {
ValidatedCommand::Process { input, output, .. } => {
// Paths are already validated and safe
println!("Processing {} -> {}", input.display(), output.display());
}
_ => {}
}
use bootstrap::exit_code::{map_error_to_exit_code, ExitCode};
fn main() -> std::process::ExitCode {
let result = dangerous_operation();
match result {
Ok(_) => ExitCode::Success.into(),
Err(e) => {
// Automatic mapping to Unix exit codes
let exit_code = map_error_to_exit_code(&e);
eprintln!("Error: {}", e);
exit_code.into()
}
}
}
// Maps error messages to sysexits.h codes:
// - "file not found" -> EX_NOINPUT (66)
// - "invalid data" -> EX_DATAERR (65)
// - "I/O error" -> EX_IOERR (74)
platform)Provides unified cross-platform API:
pub trait Platform: Send + Sync {
// System Information
fn page_size(&self) -> usize;
fn cpu_count(&self) -> usize;
fn total_memory(&self) -> Result<u64, PlatformError>;
fn available_memory(&self) -> Result<u64, PlatformError>;
// Platform Constants
fn line_separator(&self) -> &'static str;
fn path_separator(&self) -> char;
fn platform_name(&self) -> &'static str;
fn temp_dir(&self) -> PathBuf;
// Security & Permissions
fn is_elevated(&self) -> bool;
fn set_permissions(&self, path: &Path, mode: u32) -> Result<(), PlatformError>;
fn is_executable(&self, path: &Path) -> bool;
// File Operations
async fn sync_file(&self, file: &tokio::fs::File) -> Result<(), PlatformError>;
}
Implementations:
UnixPlatform - Uses libc, /proc, /sysWindowsPlatform - Uses winapi, with stubs for non-Windowssignals)Cross-platform graceful shutdown:
pub trait SignalHandler: Send + Sync {
async fn wait_for_signal(&self);
fn shutdown_requested(&self) -> bool;
}
// Unix: SIGTERM, SIGINT, SIGHUP
// Windows: Ctrl+C, Ctrl+Break
let handler = create_signal_handler(cancellation_token);
cli)Secure argument validation with clap:
pub struct ValidatedCli {
pub command: ValidatedCommand,
pub verbose: bool,
pub config: Option<PathBuf>,
pub cpu_threads: Option<usize>,
pub io_threads: Option<usize>,
pub storage_type: Option<String>,
pub channel_depth: usize,
}
// Security validations:
// - SQL injection prevention
// - Path traversal checks
// - Shell command injection blocking
// - Numeric range validation
shutdown)CancellationToken-based coordination:
pub struct ShutdownCoordinator {
token: CancellationToken,
completed: Arc<AtomicBool>,
}
impl ShutdownCoordinator {
pub fn new() -> Self;
pub fn token(&self) -> CancellationToken;
pub fn initiate(&self);
pub async fn wait_for_completion(&self, timeout_secs: u64) -> Result<()>;
pub fn mark_complete(&self);
}
exit_code)Unix sysexits.h standard codes:
pub enum ExitCode {
Success = 0,
Error = 1,
DataErr = 65, // Invalid data
NoInput = 66, // File not found
Software = 70, // Internal error
IoErr = 74, // I/O error
}
// Automatic error message mapping
let code = map_error_to_exit_code("file not found");
assert_eq!(code, ExitCode::NoInput);
Compile-time platform selection:
#[cfg(unix)]
pub use unix::UnixPlatform;
#[cfg(windows)]
pub use windows::WindowsPlatform;
Runtime platform detection:
let platform = create_platform();
if platform.platform_name() == "macos" {
// macOS-specific logic
}
All CLI inputs are validated for security:
// โ Rejected patterns:
// - "../../../etc/passwd" (path traversal)
// - "'; DROP TABLE users; --" (SQL injection)
// - "$(rm -rf /)" (shell injection)
// - "\x00\x01\x02" (binary data)
// โ
Accepted inputs:
// - "/valid/path/to/file.txt"
// - "my-pipeline-name"
// - "8" (numeric validation)
Multi-stage shutdown:
1. Signal received (SIGTERM/SIGINT)
2. CancellationToken triggered
3. Tasks check token and cleanup
4. Coordinator waits for completion
5. Timeout enforcement (default: 30s)
6. Process exits cleanly
Bootstrap includes testable abstractions:
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_platform_detection() {
let platform = create_platform();
assert!(platform.cpu_count() >= 1);
assert!(platform.page_size() >= 512);
}
#[tokio::test]
async fn test_graceful_shutdown() {
let coordinator = ShutdownCoordinator::new();
let token = coordinator.token();
coordinator.initiate();
assert!(token.is_cancelled());
}
}
Minimal dependencies for cross-platform support:
Platform-specific:
libcwinapiBSD 3-Clause License - see LICENSE file for details.
Contributions should focus on:
Cross-Platform Foundation | Secure by Default | Production-Ready