greggd 1.0.9

Lightweight Linux, macOS, and Windows metrics daemon that exposes a read-only JSON API for the gregg client.
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
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
//! Daemon configuration, validation, file I/O, and atomic persistence.
//!
//! Configuration is stored as canonical TOML and validated before every
//! load and before every mutation. Atomic writes ensure a partially written
//! file can never corrupt a running service.

use std::fmt;
use std::fs;
use std::net::IpAddr;
use std::path::{Path, PathBuf};

use serde::{Deserialize, Serialize};

/// Minimum allowed sample interval in milliseconds.
pub const MIN_SAMPLE_INTERVAL_MS: u64 = 250;

/// Maximum allowed sample interval in milliseconds.
pub const MAX_SAMPLE_INTERVAL_MS: u64 = 60_000;

/// Minimum port number.
pub const MIN_PORT: u16 = 1;

/// Maximum port number.
pub const MAX_PORT: u16 = 65535;

/// Maximum length for the display name after trimming.
pub const MAX_NAME_LEN: usize = 128;

/// Daemon configuration.
///
/// All fields are serialized to TOML. Unknown fields are rejected during
/// deserialization to prevent silent typo acceptance.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct Config {
    /// Human-readable display name for this host.
    pub name: String,
    /// IPv4 or IPv6 address to bind the HTTP server to.
    pub host: IpAddr,
    /// TCP port to listen on.
    pub port: u16,
    /// Native sampling interval in milliseconds.
    pub sample_interval_ms: u64,
    /// Duration in milliseconds after which a snapshot is considered stale.
    /// A value of `0` disables age-based staleness.
    pub stale_after_ms: u64,
}

impl Default for Config {
    fn default() -> Self {
        Self {
            name: String::from("greggd"),
            host: IpAddr::V4(std::net::Ipv4Addr::UNSPECIFIED),
            port: 11310,
            sample_interval_ms: 1000,
            stale_after_ms: 10_000,
        }
    }
}

impl Config {
    /// Validate all fields.
    ///
    /// Returns a list of all violations so callers can present every
    /// problem at once rather than fixing them one at a time.
    #[must_use]
    pub fn validate(&self) -> Vec<ConfigViolation> {
        let mut violations = Vec::new();

        // Name validation.
        let trimmed = self.name.trim();
        if trimmed.is_empty() {
            violations.push(ConfigViolation::EmptyName);
        } else if trimmed.len() > MAX_NAME_LEN {
            violations.push(ConfigViolation::NameTooLong {
                length: trimmed.len(),
                max: MAX_NAME_LEN,
            });
        }

        // Port validation. u16 cannot exceed 65535, so only check for zero.
        if self.port < MIN_PORT {
            violations.push(ConfigViolation::InvalidPort(self.port));
        }

        // Sample interval validation.
        if self.sample_interval_ms < MIN_SAMPLE_INTERVAL_MS
            || self.sample_interval_ms > MAX_SAMPLE_INTERVAL_MS
        {
            violations.push(ConfigViolation::InvalidSampleInterval(
                self.sample_interval_ms,
            ));
        }

        // Staleness threshold: if non-zero, must exceed sample interval
        // to be meaningful (otherwise every snapshot is immediately stale).
        if self.stale_after_ms > 0 && self.stale_after_ms <= self.sample_interval_ms {
            violations.push(ConfigViolation::StalenessBelowInterval {
                stale_after_ms: self.stale_after_ms,
                sample_interval_ms: self.sample_interval_ms,
            });
        }

        violations
    }

    /// Returns `true` if the configuration passes validation.
    #[must_use]
    pub fn is_valid(&self) -> bool {
        self.validate().is_empty()
    }

    /// Return the platform-specific default config path.
    #[must_use]
    pub fn default_path() -> PathBuf {
        #[cfg(target_os = "linux")]
        {
            PathBuf::from("/etc/gregg/greggd.toml")
        }
        #[cfg(target_os = "macos")]
        {
            PathBuf::from("/Library/Application Support/gregg/greggd.toml")
        }
        #[cfg(target_os = "windows")]
        {
            let program_data =
                std::env::var("ProgramData").unwrap_or_else(|_| "C:\\ProgramData".to_owned());
            PathBuf::from(program_data)
                .join("gregg")
                .join("greggd.toml")
        }
        #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
        {
            PathBuf::from("greggd.toml")
        }
    }

    /// Return the platform-specific default host path for the socket.
    #[must_use]
    pub fn default_host_socket_path() -> PathBuf {
        Self::default_path()
            .parent()
            .map_or_else(|| PathBuf::from("."), std::path::Path::to_path_buf)
    }

    /// Load configuration from the given TOML file path.
    ///
    /// # Errors
    ///
    /// Returns [`ConfigError`] if the file cannot be read, parsed, or
    /// fails validation.
    pub fn load(path: &Path) -> Result<Self, ConfigError> {
        let content = fs::read_to_string(path).map_err(|e| ConfigError::Io {
            path: path.to_path_buf(),
            source: e,
        })?;
        Self::parse(&content, Some(path))
    }

    /// Parse a TOML configuration string.
    ///
    /// When `path` is provided, it is used in error messages for
    /// diagnostics.
    ///
    /// # Errors
    ///
    /// Returns [`ConfigError`] if the content is not valid TOML,
    /// contains unknown fields, or fails validation.
    pub fn parse(content: &str, path: Option<&Path>) -> Result<Self, ConfigError> {
        let config: Self = toml::from_str(content).map_err(|e| ConfigError::Parse {
            path: path.map(PathBuf::from),
            source: e,
        })?;

        let violations = config.validate();
        if violations.is_empty() {
            Ok(config)
        } else {
            Err(ConfigError::Validation(violations))
        }
    }

    /// Serialize this configuration to canonical TOML.
    #[must_use]
    pub fn to_toml(&self) -> String {
        toml::to_string_pretty(self).expect("Config serializes to TOML")
    }

    /// Atomically write this configuration to the given path.
    ///
    /// This follows the write-flush-rename-verify pattern:
    /// 1. Write to a unique temporary file in the same directory.
    /// 2. Flush the file.
    /// 3. Rename over the destination.
    /// 4. Reopen and re-parse as verification.
    ///
    /// # Errors
    ///
    /// Returns [`ConfigError`] if any step fails. On failure, the
    /// temporary file is cleaned up and the original file is left intact.
    pub fn write_atomic(&self, path: &Path) -> Result<(), ConfigError> {
        // 1. Resolve and validate the destination directory.
        let dir = path.parent().ok_or_else(|| ConfigError::AtomicWrite {
            path: path.to_path_buf(),
            source: AtomicWriteError::NoParentDirectory,
        })?;
        fs::create_dir_all(dir).map_err(|e| ConfigError::AtomicWrite {
            path: path.to_path_buf(),
            source: AtomicWriteError::Io(e),
        })?;

        // 2. Serialize the complete config.
        let content = self.to_toml();

        // 3. Write to a uniquely named temporary file.
        let temp_name = format!(".greggd-{}.toml.tmp", std::process::id());
        let temp_path = dir.join(&temp_name);

        fs::write(&temp_path, content.as_bytes()).map_err(|e| {
            let _ = fs::remove_file(&temp_path);
            ConfigError::AtomicWrite {
                path: path.to_path_buf(),
                source: AtomicWriteError::Io(e),
            }
        })?;

        // 4. Flush the file.
        let file = fs::OpenOptions::new()
            .write(true)
            .open(&temp_path)
            .map_err(|e| {
                let _ = fs::remove_file(&temp_path);
                ConfigError::AtomicWrite {
                    path: path.to_path_buf(),
                    source: AtomicWriteError::Io(e),
                }
            })?;
        file.sync_all().map_err(|e| {
            let _ = fs::remove_file(&temp_path);
            ConfigError::AtomicWrite {
                path: path.to_path_buf(),
                source: AtomicWriteError::Io(e),
            }
        })?;

        // 5. Rename atomically over the destination.
        fs::rename(&temp_path, path).map_err(|e| {
            let _ = fs::remove_file(&temp_path);
            ConfigError::AtomicWrite {
                path: path.to_path_buf(),
                source: AtomicWriteError::Io(e),
            }
        })?;

        // 6. Reopen and re-parse as verification.
        let verified = Self::load(path)?;
        if *self != verified {
            return Err(ConfigError::AtomicWrite {
                path: path.to_path_buf(),
                source: AtomicWriteError::VerificationFailed,
            });
        }

        Ok(())
    }

    /// Return a reference to the host field.
    #[must_use]
    pub fn host(&self) -> IpAddr {
        self.host
    }

    /// Return a reference to the port field.
    #[must_use]
    pub fn port(&self) -> u16 {
        self.port
    }

    /// Return the `sample_interval_ms` field.
    #[must_use]
    pub fn sample_interval_ms(&self) -> u64 {
        self.sample_interval_ms
    }

    /// Return the `stale_after_ms` field.
    #[must_use]
    pub fn stale_after_ms(&self) -> u64 {
        self.stale_after_ms
    }
}

/// Errors that can occur during configuration operations.
#[derive(Debug)]
pub enum ConfigError {
    /// I/O error reading or writing the config file.
    Io {
        path: PathBuf,
        source: std::io::Error,
    },
    /// TOML parsing error.
    Parse {
        path: Option<PathBuf>,
        source: toml::de::Error,
    },
    /// Configuration failed validation.
    Validation(Vec<ConfigViolation>),
    /// Atomic write operation failed.
    AtomicWrite {
        path: PathBuf,
        source: AtomicWriteError,
    },
}

impl fmt::Display for ConfigError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Io { path, source } => write!(f, "failed to read {}: {source}", path.display()),
            Self::Parse { path, source } => {
                if let Some(p) = path {
                    write!(f, "failed to parse {}: {source}", p.display())
                } else {
                    write!(f, "failed to parse config: {source}")
                }
            }
            Self::Validation(violations) => {
                write!(f, "configuration validation failed:")?;
                for v in violations {
                    write!(f, "\n  - {v}")?;
                }
                Ok(())
            }
            Self::AtomicWrite { path, source } => {
                write!(f, "atomic write to {} failed: {source}", path.display())
            }
        }
    }
}

impl std::error::Error for ConfigError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Io { source, .. } => Some(source),
            Self::Parse { source, .. } => Some(source),
            Self::Validation(_) => None,
            Self::AtomicWrite { source, .. } => Some(source),
        }
    }
}

/// Errors specific to the atomic write operation.
#[derive(Debug)]
pub enum AtomicWriteError {
    /// The path has no parent directory.
    NoParentDirectory,
    /// An I/O error occurred.
    Io(std::io::Error),
    /// The file was written but verification re-parse failed.
    VerificationFailed,
}

impl fmt::Display for AtomicWriteError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::NoParentDirectory => write!(f, "path has no parent directory"),
            Self::Io(e) => write!(f, "I/O error: {e}"),
            Self::VerificationFailed => write!(f, "verification re-parse failed"),
        }
    }
}

impl std::error::Error for AtomicWriteError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Io(e) => Some(e),
            _ => None,
        }
    }
}

/// A single configuration validation violation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ConfigViolation {
    /// Display name is empty after trimming.
    EmptyName,
    /// Display name exceeds the maximum length.
    NameTooLong { length: usize, max: usize },
    /// Port is outside the valid range.
    InvalidPort(u16),
    /// Sample interval is outside the valid range.
    InvalidSampleInterval(u64),
    /// Staleness threshold is below or equal to sample interval.
    StalenessBelowInterval {
        stale_after_ms: u64,
        sample_interval_ms: u64,
    },
}

impl fmt::Display for ConfigViolation {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::EmptyName => write!(f, "name is empty after trimming"),
            Self::NameTooLong { length, max } => {
                write!(f, "name is {length} characters, exceeds maximum of {max}")
            }
            Self::InvalidPort(p) => {
                write!(f, "port {p} is outside valid range {MIN_PORT}..={MAX_PORT}")
            }
            Self::InvalidSampleInterval(ms) => {
                write!(
                    f,
                    "sample_interval_ms {ms} is outside valid range {MIN_SAMPLE_INTERVAL_MS}..={MAX_SAMPLE_INTERVAL_MS}"
                )
            }
            Self::StalenessBelowInterval {
                stale_after_ms,
                sample_interval_ms,
            } => {
                write!(
                    f,
                    "stale_after_ms {stale_after_ms} must be 0 (disabled) or greater than sample_interval_ms {sample_interval_ms}"
                )
            }
        }
    }
}

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

    #[test]
    fn default_config_is_valid() {
        let config = Config::default();
        assert!(config.is_valid());
        assert!(config.validate().is_empty());
    }

    #[test]
    fn config_round_trips_through_toml() {
        let config = Config::default();
        let toml = config.to_toml();
        let parsed = Config::parse(&toml, None).unwrap();
        assert_eq!(config, parsed);
    }

    #[test]
    fn empty_name_fails_validation() {
        let config = Config {
            name: String::new(),
            ..Config::default()
        };
        let violations = config.validate();
        assert!(violations.contains(&ConfigViolation::EmptyName));
    }

    #[test]
    fn whitespace_only_name_fails_validation() {
        let config = Config {
            name: String::from("   \t\n  "),
            ..Config::default()
        };
        let violations = config.validate();
        assert!(violations.contains(&ConfigViolation::EmptyName));
    }

    #[test]
    fn name_too_long_fails_validation() {
        let config = Config {
            name: "x".repeat(MAX_NAME_LEN + 1),
            ..Config::default()
        };
        let violations = config.validate();
        assert!(violations
            .iter()
            .any(|v| matches!(v, ConfigViolation::NameTooLong { .. })));
    }

    #[test]
    fn port_zero_fails_validation() {
        let config = Config {
            port: 0,
            ..Config::default()
        };
        let violations = config.validate();
        assert!(violations.contains(&ConfigViolation::InvalidPort(0)));
    }

    #[test]
    fn boundary_port_values() {
        let config = Config {
            port: MIN_PORT,
            ..Config::default()
        };
        assert!(config.is_valid());

        let config = Config {
            port: u16::MAX,
            ..Config::default()
        };
        assert!(config.is_valid());
    }

    #[test]
    fn sample_interval_too_low_fails_validation() {
        let config = Config {
            sample_interval_ms: 100,
            ..Config::default()
        };
        let violations = config.validate();
        assert!(violations.contains(&ConfigViolation::InvalidSampleInterval(100)));
    }

    #[test]
    fn sample_interval_too_high_fails_validation() {
        let config = Config {
            sample_interval_ms: 100_000,
            ..Config::default()
        };
        let violations = config.validate();
        assert!(violations.contains(&ConfigViolation::InvalidSampleInterval(100_000)));
    }

    #[test]
    fn staleness_below_interval_fails_validation() {
        let config = Config {
            sample_interval_ms: 5000,
            stale_after_ms: 3000,
            ..Config::default()
        };
        let violations = config.validate();
        assert!(
            violations.contains(&ConfigViolation::StalenessBelowInterval {
                stale_after_ms: 3000,
                sample_interval_ms: 5000,
            })
        );
    }

    #[test]
    fn staleness_disabled_is_valid() {
        let config = Config {
            stale_after_ms: 0,
            ..Config::default()
        };
        assert!(config.is_valid());
    }

    #[test]
    fn staleness_greater_than_interval_is_valid() {
        let config = Config {
            sample_interval_ms: 1000,
            stale_after_ms: 5000,
            ..Config::default()
        };
        assert!(config.is_valid());
    }

    #[test]
    fn parse_rejects_unknown_fields() {
        let toml = r#"
name = "test"
host = "0.0.0.0"
port = 11310
sample_interval_ms = 1000
stale_after_ms = 10000
unknown_field = "oops"
"#;
        let result = Config::parse(toml, None);
        assert!(result.is_err());
    }

    #[test]
    fn parse_rejects_invalid_toml() {
        let result = Config::parse("not valid toml {{{", None);
        assert!(result.is_err());
    }

    #[test]
    fn load_returns_error_for_missing_file() {
        let result = Config::load(Path::new("/nonexistent/greggd.toml"));
        assert!(result.is_err());
    }

    #[test]
    fn write_atomic_creates_file() {
        let dir = std::env::temp_dir().join("greggd_test_write_atomic");
        let _ = fs::remove_dir_all(&dir);
        fs::create_dir_all(&dir).unwrap();
        let path = dir.join("config.toml");

        let config = Config::default();
        config.write_atomic(&path).unwrap();

        let loaded = Config::load(&path).unwrap();
        assert_eq!(config, loaded);

        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn write_atomic_overwrites_existing_file() {
        let dir = std::env::temp_dir().join("greggd_test_overwrite");
        let _ = fs::remove_dir_all(&dir);
        fs::create_dir_all(&dir).unwrap();
        let path = dir.join("config.toml");

        let config = Config {
            name: String::from("first"),
            ..Config::default()
        };
        config.write_atomic(&path).unwrap();

        let config = Config {
            name: String::from("second"),
            ..Config::default()
        };
        config.write_atomic(&path).unwrap();

        let loaded = Config::load(&path).unwrap();
        assert_eq!(loaded.name, "second");

        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn write_atomic_preserves_old_on_temp_failure() {
        let dir = std::env::temp_dir().join("greggd_test_preserve");
        let _ = fs::remove_dir_all(&dir);
        fs::create_dir_all(&dir).unwrap();
        let path = dir.join("config.toml");

        let original = Config::default();
        original.write_atomic(&path).unwrap();

        // Create a file where a directory would need to be, so
        // create_dir_all fails when write_atomic tries to ensure the
        // parent directory exists.
        let blocker = dir.join("not_a_dir");
        fs::write(&blocker, b"x").unwrap();
        let bad_path = blocker.join("sub").join("config.toml");
        let result = original.write_atomic(&bad_path);
        assert!(result.is_err());

        // Original should still be valid.
        let loaded = Config::load(&path).unwrap();
        assert_eq!(original, loaded);

        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn multiple_violations_reported() {
        let config = Config {
            name: String::new(),
            port: 0,
            sample_interval_ms: 10,
            ..Config::default()
        };
        let violations = config.validate();
        assert!(violations.len() >= 3);
    }

    #[test]
    fn boundary_interval_values() {
        let config = Config {
            sample_interval_ms: MIN_SAMPLE_INTERVAL_MS,
            stale_after_ms: MIN_SAMPLE_INTERVAL_MS + 1,
            ..Config::default()
        };
        assert!(config.is_valid());

        let config = Config {
            sample_interval_ms: MAX_SAMPLE_INTERVAL_MS,
            stale_after_ms: 0,
            ..Config::default()
        };
        assert!(config.is_valid());
    }

    #[test]
    fn config_violation_display_messages() {
        let v = ConfigViolation::EmptyName;
        assert!(!format!("{v}").is_empty());

        let v = ConfigViolation::NameTooLong {
            length: 200,
            max: 128,
        };
        let msg = format!("{v}");
        assert!(msg.contains("200"));
        assert!(msg.contains("128"));

        let v = ConfigViolation::InvalidPort(0);
        assert!(format!("{v}").contains('0'));

        let v = ConfigViolation::InvalidSampleInterval(10);
        assert!(format!("{v}").contains("10"));

        let v = ConfigViolation::StalenessBelowInterval {
            stale_after_ms: 500,
            sample_interval_ms: 1000,
        };
        let msg = format!("{v}");
        assert!(msg.contains("500"));
        assert!(msg.contains("1000"));
    }

    #[test]
    #[cfg(unix)]
    fn write_atomic_to_readonly_directory() {
        let dir = std::env::temp_dir().join("greggd_test_readonly");
        let _ = fs::remove_dir_all(&dir);
        fs::create_dir_all(&dir).unwrap();

        let original = Config::default();
        let path = dir.join("config.toml");
        original.write_atomic(&path).unwrap();

        // Make directory read-only.
        let mut perms = fs::metadata(&dir).unwrap().permissions();
        perms.set_readonly(true);
        fs::set_permissions(&dir, perms).unwrap();

        let result = original.write_atomic(&path);
        assert!(result.is_err());

        // Original file should still be intact and readable.
        let loaded = Config::load(&path).unwrap();
        assert_eq!(original, loaded);

        // Restore permissions for cleanup.
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            fs::set_permissions(&dir, fs::Permissions::from_mode(0o755)).unwrap();
        }
        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn write_atomic_verification_detects_mismatch() {
        // The verification step re-parses the written file and compares
        // against the source config. We test that VerificationFailed is
        // the correct variant by manually corrupting the file after a
        // successful write, then verifying that load still succeeds on
        // the corrupted file (proving the file was writable) while the
        // original config would not match.
        let dir = std::env::temp_dir().join("greggd_test_verify_mismatch");
        let _ = fs::remove_dir_all(&dir);
        fs::create_dir_all(&dir).unwrap();
        let path = dir.join("config.toml");

        let config = Config::default();
        config.write_atomic(&path).unwrap();

        // Corrupt the file in place.
        fs::write(&path, "name = \"corrupted\"\n").unwrap();

        // The corrupted file should parse as valid TOML but fail
        // validation (host is missing), proving the file was overwritten.
        let result = Config::load(&path);
        assert!(result.is_err());

        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn write_atomic_no_parent_directory() {
        let config = Config::default();
        // Path::new("/").parent() returns None, triggering NoParentDirectory.
        let result = config.write_atomic(Path::new("/"));
        match result {
            Err(ConfigError::AtomicWrite {
                source: AtomicWriteError::NoParentDirectory,
                ..
            }) => {}
            other => panic!("expected NoParentDirectory, got {other:?}"),
        }
    }

    #[test]
    fn write_atomic_multiple_rapid_writes() {
        let dir = std::env::temp_dir().join("greggd_test_rapid_writes");
        let _ = fs::remove_dir_all(&dir);
        fs::create_dir_all(&dir).unwrap();
        let path = dir.join("config.toml");

        for i in 0..10 {
            let config = Config {
                name: format!("iteration-{i}"),
                ..Config::default()
            };
            config.write_atomic(&path).unwrap();
        }

        let loaded = Config::load(&path).unwrap();
        assert_eq!(loaded.name, "iteration-9");
        assert!(loaded.is_valid());

        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn parse_deeply_nested_invalid_toml() {
        let toml = r"
[[[this is not valid toml
  broken = { { { }
";
        let result = Config::parse(toml, None);
        assert!(result.is_err());
        match result {
            Err(ConfigError::Parse { .. }) => {}
            other => panic!("expected Parse error, got {other:?}"),
        }
    }

    #[test]
    fn config_with_all_violations_at_once() {
        let config = Config {
            name: String::new(),
            port: 0,
            sample_interval_ms: 10,
            stale_after_ms: 5,
            host: "0.0.0.0".parse().unwrap(),
        };
        let violations = config.validate();
        assert!(violations.len() >= 3);
        assert!(violations.contains(&ConfigViolation::EmptyName));
        assert!(violations.contains(&ConfigViolation::InvalidPort(0)));
        assert!(violations.contains(&ConfigViolation::InvalidSampleInterval(10)));
        assert!(
            violations.contains(&ConfigViolation::StalenessBelowInterval {
                stale_after_ms: 5,
                sample_interval_ms: 10,
            })
        );
    }
}