Skip to main content

pitchfork_cli/
error.rs

1//! Custom diagnostic error types for rich error reporting via miette.
2//!
3//! This module provides structured error types that leverage miette's diagnostic
4//! features including error codes, help text, source code highlighting, and suggestions.
5
6// False positive: fields are used in #[error] format strings and miette derive macros
7#![allow(unused_assignments)]
8
9use miette::{Diagnostic, NamedSource, SourceSpan};
10use std::io;
11use std::path::PathBuf;
12use thiserror::Error;
13
14/// Errors related to daemon ID validation.
15#[derive(Debug, Error, Diagnostic)]
16pub enum DaemonIdError {
17    #[error("daemon ID cannot be empty")]
18    #[diagnostic(
19        code(pitchfork::daemon::empty_id),
20        url("https://pitchfork.jdx.dev/configuration"),
21        help("provide a non-empty identifier for the daemon")
22    )]
23    Empty,
24
25    #[error("daemon ID {component} cannot be empty")]
26    #[diagnostic(
27        code(pitchfork::daemon::empty_component),
28        url("https://pitchfork.jdx.dev/configuration"),
29        help("both namespace and name must be non-empty")
30    )]
31    EmptyComponent { component: String },
32
33    #[error("daemon ID '{id}' contains path separator '{sep}'")]
34    #[diagnostic(
35        code(pitchfork::daemon::path_separator),
36        url("https://pitchfork.jdx.dev/configuration"),
37        help("daemon IDs cannot contain '/' or '\\' to prevent path traversal")
38    )]
39    PathSeparator { id: String, sep: char },
40
41    #[error("daemon ID '{id}' contains parent directory reference '..'")]
42    #[diagnostic(
43        code(pitchfork::daemon::parent_dir_ref),
44        url("https://pitchfork.jdx.dev/configuration"),
45        help("daemon IDs cannot contain '..' to prevent path traversal")
46    )]
47    ParentDirRef { id: String },
48
49    #[error("daemon ID '{id}' contains reserved sequence '--'")]
50    #[diagnostic(
51        code(pitchfork::daemon::reserved_sequence),
52        url("https://pitchfork.jdx.dev/configuration"),
53        help("'--' is reserved for internal path encoding; use single dashes instead")
54    )]
55    ReservedSequence { id: String },
56
57    #[error("daemon ID component '{id}' starts or ends with a dash '-'")]
58    #[diagnostic(
59        code(pitchfork::daemon::leading_trailing_dash),
60        url("https://pitchfork.jdx.dev/configuration"),
61        help(
62            "remove the leading or trailing dash (e.g. 'my-daemon' not '-my-daemon' or 'my-daemon-')"
63        )
64    )]
65    LeadingTrailingDash { id: String },
66
67    #[error("daemon ID '{id}' contains spaces")]
68    #[diagnostic(
69        code(pitchfork::daemon::contains_space),
70        url("https://pitchfork.jdx.dev/configuration"),
71        help("use hyphens or underscores instead of spaces (e.g., 'my-daemon' or 'my_daemon')")
72    )]
73    ContainsSpace { id: String },
74
75    #[error("daemon ID cannot be '.'")]
76    #[diagnostic(
77        code(pitchfork::daemon::current_dir),
78        url("https://pitchfork.jdx.dev/configuration"),
79        help("'.' refers to the current directory; use a descriptive name instead")
80    )]
81    CurrentDir,
82
83    #[error("daemon ID '{id}' contains non-printable or non-ASCII character")]
84    #[diagnostic(
85        code(pitchfork::daemon::invalid_chars),
86        url("https://pitchfork.jdx.dev/configuration"),
87        help(
88            "daemon IDs must contain only printable ASCII characters (letters, numbers, hyphens, underscores, dots)"
89        )
90    )]
91    InvalidChars { id: String },
92
93    #[error("daemon ID '{id}' is missing namespace (expected format: namespace/name)")]
94    #[diagnostic(
95        code(pitchfork::daemon::missing_namespace),
96        url("https://pitchfork.jdx.dev/configuration"),
97        help("use qualified format like 'global/myapp' or 'project-name/daemon'")
98    )]
99    MissingNamespace { id: String },
100
101    #[error("invalid safe path format '{path}' (expected namespace--name)")]
102    #[diagnostic(
103        code(pitchfork::daemon::invalid_safe_path),
104        help("safe paths use '--' to separate namespace and name")
105    )]
106    InvalidSafePath { path: String },
107}
108
109/// Errors related to daemon operations.
110#[derive(Debug, Error, Diagnostic)]
111pub enum DaemonError {
112    #[error("failed to stop daemon '{id}': {error}")]
113    #[diagnostic(
114        code(pitchfork::daemon::stop_failed),
115        help("the process may be stuck or require manual intervention. Try: kill -9 <pid>")
116    )]
117    StopFailed { id: String, error: String },
118}
119
120/// Errors related to dependency resolution.
121#[derive(Debug, Error, Diagnostic)]
122pub enum DependencyError {
123    #[error("daemon '{name}' not found in configuration")]
124    #[diagnostic(
125        code(pitchfork::deps::not_found),
126        url("https://pitchfork.jdx.dev/configuration#depends")
127    )]
128    DaemonNotFound {
129        name: String,
130        #[help]
131        suggestion: Option<String>,
132    },
133
134    #[error("daemon '{daemon}' depends on '{dependency}' which is not defined")]
135    #[diagnostic(
136        code(pitchfork::deps::missing_dependency),
137        url("https://pitchfork.jdx.dev/configuration#depends"),
138        help("add the missing daemon to your pitchfork.toml or remove it from the depends list")
139    )]
140    MissingDependency { daemon: String, dependency: String },
141
142    #[error("circular dependency detected involving: {}", involved.join(", "))]
143    #[diagnostic(
144        code(pitchfork::deps::circular),
145        url("https://pitchfork.jdx.dev/configuration#depends"),
146        help("break the cycle by removing one of the dependencies")
147    )]
148    CircularDependency {
149        /// The daemons involved in the cycle
150        involved: Vec<String>,
151    },
152}
153
154/// Errors related to port binding and availability.
155#[derive(Debug, Error, Diagnostic)]
156pub enum PortError {
157    #[error("port {port} is already in use by process '{process}' (PID: {pid})")]
158    #[diagnostic(
159        code(pitchfork::port::in_use),
160        url("https://pitchfork.jdx.dev/configuration#port"),
161        help(
162            "choose a different port, stop the existing process, or enable auto_bump_port to automatically find an available port"
163        )
164    )]
165    InUse {
166        port: u16,
167        process: String,
168        pid: u32,
169    },
170
171    #[error(
172        "could not find an available port after {attempts} attempts starting from {start_port}"
173    )]
174    #[diagnostic(
175        code(pitchfork::port::no_available_port),
176        url("https://pitchfork.jdx.dev/configuration#port"),
177        help("manually specify an available port or reduce the number of concurrent services")
178    )]
179    NoAvailablePort { start_port: u16, attempts: u32 },
180}
181
182/// Error for TOML configuration parse failures with source code highlighting.
183#[derive(Debug, Error, Diagnostic)]
184pub enum ConfigParseError {
185    #[error("failed to parse configuration")]
186    #[diagnostic(code(pitchfork::config::parse_error))]
187    TomlError {
188        /// The source file contents for display
189        #[source_code]
190        src: NamedSource<String>,
191
192        /// The location of the error in the source
193        #[label("{message}")]
194        span: SourceSpan,
195
196        /// The error message from the TOML parser
197        message: String,
198
199        /// Additional help text
200        #[help]
201        help: Option<String>,
202    },
203
204    #[error("invalid daemon name '{name}' in {}", path.display())]
205    #[diagnostic(
206        code(pitchfork::config::invalid_daemon_name),
207        url("https://pitchfork.jdx.dev/configuration"),
208        help("daemon names must be valid identifiers without spaces, '--', or special characters")
209    )]
210    InvalidDaemonName {
211        name: String,
212        path: PathBuf,
213        reason: String,
214    },
215
216    #[error(
217        "invalid dependency '{dependency}' in daemon '{daemon}' ({}): {reason}",
218        path.display()
219    )]
220    #[diagnostic(
221        code(pitchfork::config::invalid_dependency),
222        url("https://pitchfork.jdx.dev/configuration#depends"),
223        help(
224            "dependency IDs must be valid daemon IDs; use 'name' for same namespace or 'namespace/name' for cross-namespace"
225        )
226    )]
227    InvalidDependency {
228        daemon: String,
229        dependency: String,
230        path: PathBuf,
231        reason: String,
232    },
233
234    #[error(
235        "daemon '{daemon}' in {} sets oneshot = true together with {}",
236        path.display(),
237        conflicts.join(", ")
238    )]
239    #[diagnostic(
240        code(pitchfork::config::oneshot_conflict),
241        url("https://pitchfork.jdx.dev/guides/ready-checks#oneshot-tasks"),
242        help(
243            "a oneshot daemon is ready when its process exits 0, so readiness and health checks do not apply; remove them or drop oneshot = true"
244        )
245    )]
246    OneshotConflict {
247        daemon: String,
248        path: PathBuf,
249        conflicts: Vec<String>,
250    },
251
252    #[error(
253        "namespace collision: '{}' and '{}' both resolve to namespace '{ns}'",
254        path_a.display(),
255        path_b.display()
256    )]
257    #[diagnostic(
258        code(pitchfork::config::namespace_collision),
259        url("https://pitchfork.jdx.dev/concepts/namespaces"),
260        help(
261            "rename one of the directories so that no two project configs share the same namespace"
262        )
263    )]
264    NamespaceCollision {
265        path_a: PathBuf,
266        path_b: PathBuf,
267        ns: String,
268    },
269
270    #[error(
271        "invalid namespace '{namespace}' in {}: {reason}",
272        path.display()
273    )]
274    #[diagnostic(
275        code(pitchfork::config::invalid_namespace),
276        url("https://pitchfork.jdx.dev/concepts/namespaces"),
277        help(
278            "set a valid top-level namespace in your pitchfork.toml, e.g. namespace = \"my-project\""
279        )
280    )]
281    InvalidNamespace {
282        path: PathBuf,
283        namespace: String,
284        reason: String,
285    },
286}
287
288impl ConfigParseError {
289    /// Create a new ConfigParseError from a toml parse error
290    pub fn from_toml_error(path: &std::path::Path, contents: String, err: toml::de::Error) -> Self {
291        let message = err.message().to_string();
292
293        // Try to get span information from the TOML error
294        let span = err
295            .span()
296            .map(|r| SourceSpan::from(r.start..r.end))
297            .unwrap_or_else(|| SourceSpan::from(0..0));
298
299        Self::TomlError {
300            src: NamedSource::new(path.display().to_string(), contents),
301            span,
302            message,
303            help: Some("check TOML syntax at https://toml.io".to_string()),
304        }
305    }
306}
307
308/// Errors related to file operations (config and state files).
309#[derive(Debug, Error, Diagnostic)]
310pub enum FileError {
311    #[error("failed to read file: {}", path.display())]
312    #[diagnostic(code(pitchfork::file::read_error))]
313    ReadError {
314        path: PathBuf,
315        #[source]
316        source: io::Error,
317    },
318
319    #[error("failed to write file: {}", path.display())]
320    #[diagnostic(code(pitchfork::file::write_error))]
321    WriteError {
322        path: PathBuf,
323        #[help]
324        details: Option<String>,
325    },
326
327    #[error("failed to serialize data for file: {}", path.display())]
328    #[diagnostic(
329        code(pitchfork::file::serialize_error),
330        help("this is likely an internal error; please report it")
331    )]
332    SerializeError {
333        path: PathBuf,
334        #[source]
335        source: toml::ser::Error,
336    },
337
338    #[error("no file path specified")]
339    #[diagnostic(
340        code(pitchfork::file::no_path),
341        help("ensure a pitchfork.toml file exists in your project or specify a path")
342    )]
343    NoPath,
344}
345
346/// Errors related to IPC communication with the supervisor.
347#[derive(Debug, Error, Diagnostic)]
348pub enum IpcError {
349    #[error("failed to connect to supervisor after {attempts} attempts")]
350    #[diagnostic(
351        code(pitchfork::ipc::connection_failed),
352        url("https://pitchfork.jdx.dev/supervisor")
353    )]
354    ConnectionFailed {
355        attempts: u32,
356        #[source]
357        source: Option<io::Error>,
358        #[help]
359        help: String,
360    },
361
362    #[error("IPC request timed out after {seconds}s")]
363    #[diagnostic(
364        code(pitchfork::ipc::timeout),
365        url("https://pitchfork.jdx.dev/supervisor"),
366        help(
367            "the supervisor may be unresponsive or overloaded.\nCheck supervisor status: pitchfork supervisor status\nView logs: pitchfork logs"
368        )
369    )]
370    Timeout { seconds: u64 },
371
372    #[error("IPC connection closed unexpectedly")]
373    #[diagnostic(
374        code(pitchfork::ipc::connection_closed),
375        url("https://pitchfork.jdx.dev/supervisor"),
376        help(
377            "the supervisor may have crashed or been stopped.\nRestart with: pitchfork supervisor start"
378        )
379    )]
380    ConnectionClosed,
381
382    #[error("failed to read IPC response")]
383    #[diagnostic(code(pitchfork::ipc::read_failed))]
384    ReadFailed {
385        #[source]
386        source: io::Error,
387    },
388
389    #[error("failed to send IPC request")]
390    #[diagnostic(code(pitchfork::ipc::send_failed))]
391    SendFailed {
392        #[source]
393        source: io::Error,
394    },
395
396    #[error("unexpected response from supervisor: expected {expected}, got {actual}")]
397    #[diagnostic(
398        code(pitchfork::ipc::unexpected_response),
399        help("this may indicate a version mismatch between the CLI and supervisor")
400    )]
401    UnexpectedResponse { expected: String, actual: String },
402
403    #[error("IPC message is invalid: {reason}")]
404    #[diagnostic(code(pitchfork::ipc::invalid_message))]
405    InvalidMessage { reason: String },
406}
407
408/// A collection of multiple errors that occurred during validation or processing.
409///
410/// This is useful when you want to collect and report all validation errors at once
411/// instead of failing on the first error.
412#[derive(Debug, Error, Diagnostic)]
413#[error("multiple errors occurred ({} total)", errors.len())]
414#[diagnostic(code(pitchfork::multiple_errors))]
415#[allow(dead_code)]
416pub struct MultipleErrors {
417    #[related]
418    pub errors: Vec<Box<dyn Diagnostic + Send + Sync + 'static>>,
419}
420
421#[allow(dead_code)]
422impl MultipleErrors {
423    /// Create a new MultipleErrors from a vector of diagnostics
424    pub fn new(errors: Vec<Box<dyn Diagnostic + Send + Sync + 'static>>) -> Self {
425        Self { errors }
426    }
427
428    /// Returns true if there are no errors
429    pub fn is_empty(&self) -> bool {
430        self.errors.is_empty()
431    }
432
433    /// Returns the number of errors
434    pub fn len(&self) -> usize {
435        self.errors.len()
436    }
437}
438
439/// Find the most similar daemon name for suggestions.
440pub fn find_similar_daemon<'a>(
441    name: &str,
442    available: impl Iterator<Item = &'a str>,
443) -> Option<String> {
444    use fuzzy_matcher::FuzzyMatcher;
445    use fuzzy_matcher::skim::SkimMatcherV2;
446
447    let matcher = SkimMatcherV2::default();
448    available
449        .filter_map(|candidate| {
450            matcher
451                .fuzzy_match(candidate, name)
452                .map(|score| (candidate, score))
453        })
454        .max_by_key(|(_, score)| *score)
455        .filter(|(_, score)| *score > 0)
456        .map(|(candidate, _)| format!("did you mean '{candidate}'?"))
457}
458
459#[cfg(test)]
460mod tests {
461    use super::*;
462
463    #[test]
464    fn test_daemon_id_error_display() {
465        let err = DaemonIdError::Empty;
466        assert_eq!(err.to_string(), "daemon ID cannot be empty");
467
468        let err = DaemonIdError::PathSeparator {
469            id: "foo/bar".to_string(),
470            sep: '/',
471        };
472        assert_eq!(
473            err.to_string(),
474            "daemon ID 'foo/bar' contains path separator '/'"
475        );
476
477        let err = DaemonIdError::ContainsSpace {
478            id: "my app".to_string(),
479        };
480        assert_eq!(err.to_string(), "daemon ID 'my app' contains spaces");
481    }
482
483    #[test]
484    fn test_dependency_error_display() {
485        let err = DependencyError::DaemonNotFound {
486            name: "postgres".to_string(),
487            suggestion: None,
488        };
489        assert_eq!(
490            err.to_string(),
491            "daemon 'postgres' not found in configuration"
492        );
493
494        let err = DependencyError::MissingDependency {
495            daemon: "api".to_string(),
496            dependency: "db".to_string(),
497        };
498        assert_eq!(
499            err.to_string(),
500            "daemon 'api' depends on 'db' which is not defined"
501        );
502
503        let err = DependencyError::CircularDependency {
504            involved: vec!["a".to_string(), "b".to_string(), "c".to_string()],
505        };
506        assert!(err.to_string().contains("circular dependency"));
507        assert!(err.to_string().contains("a, b, c"));
508    }
509
510    #[test]
511    fn test_find_similar_daemon() {
512        let daemons = ["postgres", "redis", "api", "worker"];
513
514        // Close match
515        let suggestion = find_similar_daemon("postgre", daemons.iter().copied());
516        assert_eq!(suggestion, Some("did you mean 'postgres'?".to_string()));
517
518        // No reasonable match
519        let suggestion = find_similar_daemon("xyz123", daemons.iter().copied());
520        assert!(suggestion.is_none());
521    }
522
523    #[test]
524    fn test_file_error_display() {
525        let err = FileError::ReadError {
526            path: PathBuf::from("/path/to/config.toml"),
527            source: io::Error::new(io::ErrorKind::NotFound, "file not found"),
528        };
529        assert!(err.to_string().contains("failed to read file"));
530        assert!(err.to_string().contains("config.toml"));
531
532        let err = FileError::NoPath;
533        assert!(err.to_string().contains("no file path"));
534    }
535
536    #[test]
537    fn test_ipc_error_display() {
538        let err = IpcError::ConnectionFailed {
539            attempts: 5,
540            source: None,
541            help: "ensure the supervisor is running".to_string(),
542        };
543        assert!(err.to_string().contains("failed to connect"));
544        assert!(err.to_string().contains("5 attempts"));
545
546        let err = IpcError::Timeout { seconds: 30 };
547        assert!(err.to_string().contains("timed out"));
548        assert!(err.to_string().contains("30s"));
549
550        let err = IpcError::UnexpectedResponse {
551            expected: "Ok".to_string(),
552            actual: "Error".to_string(),
553        };
554        assert!(err.to_string().contains("unexpected response"));
555        assert!(err.to_string().contains("Ok"));
556        assert!(err.to_string().contains("Error"));
557    }
558
559    #[test]
560    fn test_config_parse_error() {
561        let contents = "[daemons.test]\nrun = ".to_string();
562        let err = toml::from_str::<toml::Value>(&contents).unwrap_err();
563        let parse_err =
564            ConfigParseError::from_toml_error(std::path::Path::new("test.toml"), contents, err);
565
566        assert!(parse_err.to_string().contains("failed to parse"));
567    }
568
569    #[test]
570    fn test_multiple_errors() {
571        let errors: Vec<Box<dyn Diagnostic + Send + Sync>> = vec![
572            Box::new(DaemonIdError::Empty),
573            Box::new(DaemonIdError::CurrentDir),
574        ];
575        let multi = MultipleErrors::new(errors);
576
577        assert_eq!(multi.len(), 2);
578        assert!(!multi.is_empty());
579        assert!(multi.to_string().contains("2 total"));
580    }
581}