Crate proc_daemon

Crate proc_daemon 

Source
Expand description

§proc-daemon: High-Performance Daemon Framework

A foundational framework for building high-performance, resilient daemon services in Rust. Designed for enterprise applications requiring nanosecond-level performance, bulletproof reliability, and extreme concurrency.

§Key Features

  • Zero-Copy Architecture: Minimal allocations with memory pooling
  • Runtime Agnostic: Support for both Tokio and async-std via feature flags
  • Cross-Platform: First-class support for Linux, macOS, and Windows
  • Graceful Shutdown: Coordinated shutdown with configurable timeouts
  • Signal Handling: Robust cross-platform signal management
  • Configuration: Hot-reloadable configuration with multiple sources
  • Structured Logging: High-performance tracing with JSON support
  • Subsystem Management: Concurrent subsystem lifecycle management
  • Enterprise Ready: Built for 100,000+ concurrent operations

§Quick Start

// This example is marked as compile_fail to prevent freezing in doctests
use proc_daemon::{Daemon, Config, Result};
use std::time::Duration;

async fn my_service(mut shutdown: proc_daemon::ShutdownHandle) -> Result<()> {
    // Limited iterations to prevent infinite loops
    for _ in 0..3 {
        tokio::select! {
            _ = shutdown.cancelled() => {
                tracing::info!("Service shutting down gracefully");
                return Ok(());
            }
            _ = tokio::time::sleep(Duration::from_millis(10)) => {
                tracing::info!("Service working...");
            }
        }
    }
    Ok(())
}

#[tokio::main]
async fn main() -> Result<()> {
    let config = Config::new()?;
     
    // Set a timeout for the daemon to auto-shutdown
    let daemon_handle = Daemon::builder(config)
        .with_subsystem_fn("main", my_service)
        .run()
        .await?
     
    // Wait for a short time, then explicitly shut down
    tokio::time::sleep(Duration::from_millis(100)).await;
    daemon_handle.initiate_shutdown();
    Ok(())
}
// This example is marked as ignore to prevent freezing in doctests
use proc_daemon::{Daemon, Config, Result};
use std::time::Duration;

async fn my_service(mut shutdown: proc_daemon::ShutdownHandle) -> Result<()> {
    // Use a counter to avoid infinite loops
    let mut counter = 0;
    while counter < 3 {
        tokio::select! {
            _ = shutdown.cancelled() => {
                tracing::info!("Service shutting down gracefully");
                break;
            }
            _ = tokio::time::sleep(Duration::from_millis(10)) => {
                tracing::info!("Service working...");
                counter += 1;
            }
        }
    }
    Ok(())
}

#[tokio::main]
async fn main() -> Result<()> {
    let config = Config::new()?;
     
    // Auto-shutdown after a brief time
    tokio::spawn(async {
        tokio::time::sleep(Duration::from_millis(50)).await;
        std::process::exit(0); // Force exit to prevent hanging
    });
     
    Daemon::builder(config)
        .with_subsystem_fn("main", my_service)
        .run()
        .await
}

Re-exports§

pub use shutdown::ShutdownHandle;
pub use shutdown::ShutdownReason;
pub use subsystem::RestartPolicy;
pub use subsystem::Subsystem;
pub use subsystem::SubsystemId;

Modules§

coord
Lightweight coordination primitives with optional lock-free backend.
ipc
IPC primitives (feature-gated)
lock
File-based locking mechanism to prevent multiple daemon instances.
metrics
Metrics collection and monitoring for proc-daemon.
profiling
Optional profiling utilities (CPU and heap) behind the profiling feature.
resources
Resource Usage Tracking
scheduler
Scheduler hint hooks (opt-in)
shutdown
Shutdown coordination system for graceful daemon termination.
signal
Cross-platform signal handling for graceful daemon shutdown.
subsystem
Subsystem management for concurrent lifecycle coordination.
timing
High-resolution timing helpers (opt-in)

Macros§

daemon_error
Helper macro for creating errors with formatted messages.
subsystem
Convenience macro for creating subsystems from closures.
task
Convenience macro for creating simple task-based subsystems.
time_block
Macro for timing code blocks.

Structs§

Config
Main daemon configuration.
Daemon
Main daemon instance that coordinates all subsystems and handles lifecycle.
DaemonBuilder
Builder for creating daemon instances with fluent API.
ObjectPool
A thread-safe object pool that pre-allocates and reuses objects to avoid runtime allocations on hot paths.
PooledObject
A smart pointer for objects borrowed from an ObjectPool.
PooledString
A smart pointer for strings borrowed from a StringPool.
PooledVec
A smart pointer for vectors borrowed from a VecPool.
StringPool
A pool for reusing String objects to avoid allocations in hot paths.
VecPool
Pool of reusable Vec<T> objects to avoid allocations on hot paths.

Enums§

Error
Comprehensive error type for all daemon operations.
LogLevel
Log level configuration.

Constants§

DEFAULT_CONFIG_FILE
Default configuration file name
DEFAULT_SHUTDOWN_TIMEOUT_MS
Default shutdown timeout in milliseconds
VERSION
Version of the proc-daemon library

Type Aliases§

Result
Result type alias for proc-daemon operations.