proc-daemon 1.0.0

A foundational framework for building high-performance, resilient daemon services in Rust. Handles all the boilerplate for signal handling, graceful shutdown, logging, and configuration.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
//! Configuration management for the proc-daemon framework.
//!
//! This module provides a flexible configuration system that can load settings
//! from multiple sources with clear precedence rules. Built on top of figment
//! for maximum flexibility and performance.

#[cfg(any(feature = "toml", feature = "serde_json"))]
use figment::providers::Format;
use figment::providers::{Env, Serialized};
use figment::{Figment, Provider};
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
use std::time::Duration;

use crate::error::{Error, Result};

#[cfg(feature = "toml")]
use std::fs;

#[cfg(feature = "config-watch")]
use {
    notify::{Event, RecommendedWatcher, RecursiveMode, Result as NotifyResult, Watcher},
    std::sync::Arc,
};

/// Log level configuration.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum LogLevel {
    /// Trace level logging (most verbose)
    Trace,
    /// Debug level logging
    Debug,
    /// Info level logging (default)
    #[default]
    Info,
    /// Warning level logging
    Warn,
    /// Error level logging
    Error,
}

impl From<LogLevel> for tracing::Level {
    fn from(level: LogLevel) -> Self {
        match level {
            LogLevel::Trace => Self::TRACE,
            LogLevel::Debug => Self::DEBUG,
            LogLevel::Info => Self::INFO,
            LogLevel::Warn => Self::WARN,
            LogLevel::Error => Self::ERROR,
        }
    }
}

/// Logging configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LogConfig {
    /// Logging level
    pub level: LogLevel,
    /// Enable JSON formatted logs
    pub json: bool,
    /// Enable colored output (ignored for JSON logs)
    pub color: bool,
    /// Log file path (optional)
    pub file: Option<PathBuf>,
    /// Maximum log file size in bytes before rotation
    pub max_file_size: Option<u64>,
    /// Number of rotated log files to keep
    pub max_files: Option<u32>,
}

impl Default for LogConfig {
    fn default() -> Self {
        Self {
            level: LogLevel::Info,
            json: false,
            color: true,
            file: None,
            max_file_size: Some(100 * 1024 * 1024), // 100MB
            max_files: Some(5),
        }
    }
}

/// Shutdown configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ShutdownConfig {
    /// Graceful shutdown timeout in milliseconds
    pub graceful: u64,
    /// Force shutdown timeout in milliseconds
    pub force: u64,
    /// Kill processes timeout in milliseconds
    pub kill: u64,
}

impl Default for ShutdownConfig {
    fn default() -> Self {
        Self {
            graceful: crate::DEFAULT_SHUTDOWN_TIMEOUT_MS,
            force: 10_000, // 10 seconds
            kill: 15_000,  // 15 seconds
        }
    }
}

/// Performance tuning configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PerformanceConfig {
    /// Number of worker threads (0 = auto-detect)
    pub worker_threads: usize,
    /// Enable thread pinning to CPU cores
    pub thread_pinning: bool,
    /// Memory pool initial size in bytes
    pub memory_pool_size: usize,
    /// Enable NUMA awareness
    pub numa_aware: bool,
    /// Enable lock-free optimizations
    pub lock_free: bool,
}

impl Default for PerformanceConfig {
    fn default() -> Self {
        Self {
            worker_threads: 0, // Auto-detect
            thread_pinning: false,
            memory_pool_size: 1024 * 1024, // 1MB
            numa_aware: false,
            lock_free: true,
        }
    }
}

/// Monitoring configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MonitoringConfig {
    /// Enable metrics collection
    pub enable_metrics: bool,
    /// Metrics collection interval in milliseconds
    pub metrics_interval_ms: u64,
    /// Enable resource usage tracking
    pub track_resources: bool,
    /// Enable health checks
    pub health_checks: bool,
    /// Health check interval in milliseconds
    pub health_check_interval_ms: u64,
}

impl Default for MonitoringConfig {
    fn default() -> Self {
        Self {
            enable_metrics: true,
            metrics_interval_ms: 1000, // 1 second
            track_resources: true,
            health_checks: true,
            health_check_interval_ms: 5000, // 5 seconds
        }
    }
}

/// Main daemon configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Config {
    /// Daemon name/identifier
    pub name: String,
    /// Logging configuration
    pub logging: LogConfig,
    /// Shutdown configuration
    pub shutdown: ShutdownConfig,
    /// Performance configuration
    pub performance: PerformanceConfig,
    /// Monitoring configuration
    pub monitoring: MonitoringConfig,
    /// Working directory
    pub work_dir: Option<PathBuf>,
    /// PID file location
    pub pid_file: Option<PathBuf>,
    /// Enable configuration hot-reloading
    pub hot_reload: bool,
}

impl Default for Config {
    fn default() -> Self {
        Self {
            // Use a static string to avoid allocation
            name: String::from("proc-daemon"),
            logging: LogConfig::default(),
            shutdown: ShutdownConfig::default(),
            performance: PerformanceConfig::default(),
            monitoring: MonitoringConfig::default(),
            work_dir: None,
            pid_file: None,
            hot_reload: false,
        }
    }
}

impl Config {
    /// Create a new config with defaults.
    ///
    /// # Errors
    ///
    /// Will return an error if the default configuration validation fails.
    pub fn new() -> Result<Self> {
        let config = Self::default();
        config.validate()?;
        Ok(config)
    }

    /// Load configuration from multiple sources with precedence:
    /// 1. Default values
    /// 2. Configuration file (if exists)
    /// 3. Environment variables
    /// 4. Provided overrides
    ///
    /// # Errors
    ///
    /// Will return an error if the configuration file cannot be read or contains invalid configuration data.
    pub fn load() -> Result<Self> {
        Self::load_from_file(crate::DEFAULT_CONFIG_FILE)
    }

    /// Load config from a file.
    ///
    /// # Errors
    ///
    /// Will return an error if the file cannot be read or contains invalid configuration data.
    pub fn load_from_file<P: AsRef<Path>>(path: P) -> Result<Self> {
        let path = path.as_ref();

        // Base figment configuration
        let base = Figment::from(Serialized::defaults(Self::default()));
        let figment = base.merge(Env::prefixed("DAEMON_").split("_"));

        // Add config file if it exists
        let figment = if path.exists() {
            // Try fast-path buffered TOML parsing while minimizing allocations when enabled
            #[cfg(feature = "toml")]
            {
                if path.extension().and_then(|s| s.to_str()) == Some("toml") {
                    // Attempt a single buffered read, avoid intermediate String by parsing from &str
                    if let Ok(bytes) = fs::read(path) {
                        if let Ok(s) = std::str::from_utf8(&bytes) {
                            if let Ok(file_cfg) = toml::from_str::<Self>(s) {
                                return Figment::from(Serialized::defaults(Self::default()))
                                    .merge(Serialized::from(file_cfg, "file"))
                                    .merge(Env::prefixed("DAEMON_").split("_"))
                                    .extract()
                                    .map_err(Error::from);
                            }
                        }
                    }
                }
            }

            // Provider-based path (original behavior)
            let result = figment;
            #[cfg(feature = "toml")]
            let result = result.merge(figment::providers::Toml::file(path));

            #[cfg(feature = "serde_json")]
            let result = if path.extension().and_then(|s| s.to_str()) == Some("json") {
                result.merge(figment::providers::Json::file(path))
            } else {
                result
            };

            result
        } else {
            figment
        };

        figment.extract().map_err(Error::from)
    }

    /// Load config using a configuration provider.
    ///
    /// # Errors
    ///
    /// Will return an error if the provider fails to load a valid configuration.
    pub fn load_with_provider<P: Provider>(provider: P) -> Result<Self> {
        Figment::from(Serialized::defaults(Self::default()))
            .merge(Env::prefixed("DAEMON_").split("_"))
            .merge(provider)
            .extract()
            .map_err(Error::from)
    }

    /// Get the shutdown timeout as a Duration.
    #[must_use]
    pub const fn shutdown_timeout(&self) -> Duration {
        Duration::from_millis(self.shutdown.graceful)
    }

    /// Get the force shutdown timeout as a Duration.
    #[must_use]
    pub const fn force_shutdown_timeout(&self) -> Duration {
        Duration::from_millis(self.shutdown.force)
    }

    /// Get the kill timeout as a Duration.
    #[must_use]
    pub const fn kill_timeout(&self) -> Duration {
        Duration::from_millis(self.shutdown.kill)
    }

    /// Get the metrics interval as a Duration.
    #[must_use]
    pub const fn metrics_interval(&self) -> Duration {
        Duration::from_millis(self.monitoring.metrics_interval_ms)
    }

    /// Get the health check interval as a Duration.
    #[must_use]
    pub const fn health_check_interval(&self) -> Duration {
        Duration::from_millis(self.monitoring.health_check_interval_ms)
    }

    /// Validate the configuration.
    ///
    /// # Errors
    ///
    /// Will return an error if any configuration values are invalid or missing required fields.
    pub fn validate(&self) -> Result<()> {
        // Validate timeouts
        if self.shutdown.graceful == 0 {
            return Err(Error::config("Shutdown timeout must be greater than 0"));
        }

        if self.shutdown.force <= self.shutdown.graceful {
            return Err(Error::config(
                "Force timeout must be greater than graceful timeout",
            ));
        }

        if self.shutdown.kill <= self.shutdown.force {
            return Err(Error::config(
                "Kill timeout must be greater than force timeout",
            ));
        }

        // Validate performance settings
        if self.performance.memory_pool_size == 0 {
            return Err(Error::config("Memory pool size must be greater than 0"));
        }

        // Validate monitoring settings
        if self.monitoring.enable_metrics && self.monitoring.metrics_interval_ms == 0 {
            return Err(Error::config(
                "Metrics interval must be greater than 0 when metrics are enabled",
            ));
        }

        if self.monitoring.health_checks && self.monitoring.health_check_interval_ms == 0 {
            return Err(Error::config(
                "Health check interval must be greater than 0 when health checks are enabled",
            ));
        }

        // Validate name
        if self.name.is_empty() {
            return Err(Error::config("Daemon name cannot be empty"));
        }

        // Validate file paths
        if let Some(ref pid_file) = self.pid_file {
            if let Some(parent) = pid_file.parent() {
                if !parent.exists() {
                    return Err(Error::config(format!(
                        "PID file directory does not exist: {}",
                        parent.display()
                    )));
                }
            }
        }

        if let Some(ref work_dir) = self.work_dir {
            if !work_dir.exists() {
                return Err(Error::config(format!(
                    "Working directory does not exist: {}",
                    work_dir.display()
                )));
            }
            if !work_dir.is_dir() {
                return Err(Error::config(format!(
                    "Working directory is not a directory: {}",
                    work_dir.display()
                )));
            }
        }

        if let Some(ref log_file) = self.logging.file {
            if let Some(parent) = log_file.parent() {
                if !parent.exists() {
                    return Err(Error::config(format!(
                        "Log file directory does not exist: {}",
                        parent.display()
                    )));
                }
            }
        }

        if let Some(max_size) = self.logging.max_file_size {
            if max_size == 0 {
                return Err(Error::config("Log max_file_size must be greater than 0"));
            }
        }

        Ok(())
    }

    /// Get the number of worker threads to use.
    pub fn worker_threads(&self) -> usize {
        if self.performance.worker_threads == 0 {
            std::thread::available_parallelism()
                .map(std::num::NonZeroUsize::get)
                .unwrap_or(4)
        } else {
            self.performance.worker_threads
        }
    }

    /// Check if JSON logging is enabled.
    #[must_use]
    pub const fn is_json_logging(&self) -> bool {
        self.logging.json
    }

    /// Check if colored logging is enabled.
    #[must_use]
    pub const fn is_colored_logging(&self) -> bool {
        self.logging.color && !self.logging.json
    }

    /// Create a builder for this configuration.
    #[must_use]
    pub fn builder() -> ConfigBuilder {
        ConfigBuilder::new()
    }
}

/// Builder for creating configurations programmatically.
#[derive(Debug, Clone)]
pub struct ConfigBuilder {
    config: Config,
}

impl ConfigBuilder {
    /// Create a new configuration builder.
    pub fn new() -> Self {
        Self {
            config: Config::default(),
        }
    }

    /// Set the daemon name.
    pub fn name<S: Into<String>>(mut self, name: S) -> Self {
        self.config.name = name.into();
        self
    }

    /// Set the log level.
    pub const fn log_level(mut self, level: LogLevel) -> Self {
        self.config.logging.level = level;
        self
    }

    /// Enable JSON logging.
    pub const fn json_logging(mut self, enabled: bool) -> Self {
        self.config.logging.json = enabled;
        self
    }

    /// Set the shutdown timeout
    ///
    /// # Errors
    ///
    /// Will return an error if the duration exceeds `u64::MAX` milliseconds
    pub fn shutdown_timeout(mut self, timeout: Duration) -> Result<Self> {
        self.config.shutdown.graceful = u64::try_from(timeout.as_millis())
            .map_err(|_| Error::config("Shutdown timeout too large"))?;
        Ok(self)
    }

    /// Set the force shutdown timeout
    ///
    /// # Errors
    ///
    /// Will return an error if the duration exceeds `u64::MAX` milliseconds
    pub fn force_shutdown_timeout(mut self, timeout: Duration) -> Result<Self> {
        self.config.shutdown.force = u64::try_from(timeout.as_millis())
            .map_err(|_| Error::config("Force shutdown timeout too large"))?;
        Ok(self)
    }

    /// Set the kill timeout
    ///
    /// # Errors
    ///
    /// Will return an error if the duration exceeds `u64::MAX` milliseconds
    pub fn kill_timeout(mut self, timeout: Duration) -> Result<Self> {
        self.config.shutdown.kill = u64::try_from(timeout.as_millis())
            .map_err(|_| Error::config("Kill timeout too large"))?;
        Ok(self)
    }

    /// Set the working directory.
    pub fn work_dir<P: Into<PathBuf>>(mut self, dir: P) -> Self {
        self.config.work_dir = Some(dir.into());
        self
    }

    /// Set the PID file location.
    pub fn pid_file<P: Into<PathBuf>>(mut self, path: P) -> Self {
        self.config.pid_file = Some(path.into());
        self
    }

    /// Enable hot-reloading of configuration.
    pub const fn hot_reload(mut self, enabled: bool) -> Self {
        self.config.hot_reload = enabled;
        self
    }

    /// Set the number of worker threads.
    pub const fn worker_threads(mut self, threads: usize) -> Self {
        self.config.performance.worker_threads = threads;
        self
    }

    /// Enable metrics collection.
    pub const fn enable_metrics(mut self, enabled: bool) -> Self {
        self.config.monitoring.enable_metrics = enabled;
        self
    }

    /// Set the memory pool size.
    pub const fn memory_pool_size(mut self, size: usize) -> Self {
        self.config.performance.memory_pool_size = size;
        self
    }

    /// Enable lock-free optimizations.
    pub const fn lock_free(mut self, enabled: bool) -> Self {
        self.config.performance.lock_free = enabled;
        self
    }

    /// Build the configuration.
    pub fn build(self) -> Result<Config> {
        self.config.validate()?;
        Ok(self.config)
    }
}

impl Default for ConfigBuilder {
    fn default() -> Self {
        Self::new()
    }
}

// Optional config file watcher using notify
#[cfg(feature = "config-watch")]
impl Config {
    /// Start watching a configuration file and invoke a callback on changes.
    /// This uses the same loading path as `load_from_file`, so it will pick up
    /// any enabled fast-paths (e.g., `mmap-config`).
    ///
    /// The returned watcher must be kept alive for notifications to continue.
    ///
    /// # Errors
    /// Returns an error if the watcher cannot be created or the path cannot be watched.
    pub fn watch_file<F, P>(path: P, on_change: F) -> Result<RecommendedWatcher>
    where
        F: Fn(Result<Self>) + Send + Sync + 'static,
        P: AsRef<Path>,
    {
        let path_buf: Arc<PathBuf> = Arc::new(path.as_ref().to_path_buf());
        let cb: Arc<dyn Fn(Result<Self>) + Send + Sync> = Arc::new(on_change);

        let mut watcher = notify::recommended_watcher({
            let cb = Arc::clone(&cb);
            let arc_path = Arc::clone(&path_buf);
            move |res: NotifyResult<Event>| {
                // On any filesystem event, attempt reload and notify
                match res {
                    Ok(_event) => {
                        let result = Self::load_from_file(arc_path.as_ref());
                        cb(result);
                    }
                    Err(e) => {
                        // Surface error to callback as a runtime error
                        cb(Err(Error::runtime_with_source("Config watcher error", e)));
                    }
                }
            }
        })
        .map_err(|e| Error::runtime_with_source("Failed to create config watcher", e))?;

        watcher
            .watch(path_buf.as_ref(), RecursiveMode::NonRecursive)
            .map_err(|e| Error::runtime_with_source("Failed to watch config path", e))?;

        Ok(watcher)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::time::Duration;

    #[test]
    fn test_default_config() {
        let config = Config::default();
        assert_eq!(config.name, "proc-daemon");
        assert_eq!(config.logging.level, LogLevel::Info);
        assert!(!config.logging.json);
        assert!(config.logging.color);
    }

    #[test]
    fn test_config_builder() {
        let config = Config::builder()
            .name("test-daemon")
            .log_level(LogLevel::Debug)
            .json_logging(true)
            .shutdown_timeout(Duration::from_secs(10))
            .unwrap()
            .force_shutdown_timeout(Duration::from_secs(20))
            .unwrap() // Force timeout > shutdown timeout
            .kill_timeout(Duration::from_secs(30))
            .unwrap() // Kill timeout > force timeout
            .worker_threads(4)
            .build()
            .unwrap();

        assert_eq!(config.name, "test-daemon");
        assert_eq!(config.logging.level, LogLevel::Debug);
        assert!(config.logging.json);
        assert_eq!(config.shutdown.graceful, 10_000);
        assert_eq!(config.shutdown.force, 20_000);
        assert_eq!(config.shutdown.kill, 30_000);
        assert_eq!(config.performance.worker_threads, 4);
    }

    #[test]
    fn test_config_validation() {
        let mut config = Config::default();
        config.shutdown.graceful = 0;
        assert!(config.validate().is_err());

        config.shutdown.graceful = 5000;
        config.shutdown.force = 3000;
        assert!(config.validate().is_err());

        config.shutdown.force = 10_000;
        config.shutdown.kill = 8_000;
        assert!(config.validate().is_err());

        config.shutdown.kill = 15_000;
        assert!(config.validate().is_ok());
    }

    #[test]
    fn test_log_level_conversion() {
        assert_eq!(tracing::Level::from(LogLevel::Info), tracing::Level::INFO);
        assert_eq!(tracing::Level::from(LogLevel::Error), tracing::Level::ERROR);
    }

    #[test]
    fn test_duration_helpers() {
        let config = Config::default();
        assert_eq!(config.shutdown_timeout(), Duration::from_millis(5000));
        assert_eq!(
            config.force_shutdown_timeout(),
            Duration::from_millis(10_000)
        );
        assert_eq!(config.kill_timeout(), Duration::from_millis(15_000));
    }
}