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        "daemon '{daemon}' in {} sets proxy_tls = \"passthrough\" but has no port",
218        path.display()
219    )]
220    #[diagnostic(
221        code(pitchfork::config::passthrough_without_port),
222        url("https://pitchfork.jdx.dev/guides/port-management#tls-passthrough"),
223        help(
224            "TLS passthrough splices the raw stream to a port on 127.0.0.1, so the daemon's port must be known up front; add `port = <number>` to the daemon, or remove proxy_tls"
225        )
226    )]
227    PassthroughWithoutPort { daemon: String, path: PathBuf },
228
229    #[error(
230        "daemon '{daemon}' in {} sets proxy_tls_port = {port}, which is not one of its ports {declared:?}",
231        path.display()
232    )]
233    #[diagnostic(
234        code(pitchfork::config::proxy_port_not_declared),
235        url(
236            "https://pitchfork.jdx.dev/guides/port-management#choosing-a-port-on-a-multi-port-daemon"
237        ),
238        help(
239            "the proxy hostname maps to one of the daemon's own ports, so name a port from `port`, or add this one to it"
240        )
241    )]
242    ProxyPortNotDeclared {
243        daemon: String,
244        port: u16,
245        declared: Vec<u16>,
246        path: PathBuf,
247    },
248
249    #[error(
250        "daemon '{daemon}' in {} sets {key} = 0, which is not a port a hostname can be routed to",
251        path.display()
252    )]
253    #[diagnostic(
254        code(pitchfork::config::proxy_port_zero),
255        url(
256            "https://pitchfork.jdx.dev/guides/port-management#choosing-a-port-on-a-multi-port-daemon"
257        ),
258        help(
259            "port 0 asks the operating system to pick a port, so there is no fixed port for the proxy to send a hostname to; name the port the daemon actually listens on"
260        )
261    )]
262    ProxyPortZero {
263        daemon: String,
264        key: &'static str,
265        path: PathBuf,
266    },
267
268    #[error(
269        "invalid dependency '{dependency}' in daemon '{daemon}' ({}): {reason}",
270        path.display()
271    )]
272    #[diagnostic(
273        code(pitchfork::config::invalid_dependency),
274        url("https://pitchfork.jdx.dev/configuration#depends"),
275        help(
276            "dependency IDs must be valid daemon IDs; use 'name' for same namespace or 'namespace/name' for cross-namespace"
277        )
278    )]
279    InvalidDependency {
280        daemon: String,
281        dependency: String,
282        path: PathBuf,
283        reason: String,
284    },
285
286    #[error(
287        "daemon '{daemon}' in {} sets oneshot = true together with {}",
288        path.display(),
289        conflicts.join(", ")
290    )]
291    #[diagnostic(
292        code(pitchfork::config::oneshot_conflict),
293        url("https://pitchfork.jdx.dev/guides/ready-checks#oneshot-tasks"),
294        help(
295            "a oneshot daemon is ready when its process exits 0, so readiness and health checks do not apply; remove them or drop oneshot = true"
296        )
297    )]
298    OneshotConflict {
299        daemon: String,
300        path: PathBuf,
301        conflicts: Vec<String>,
302    },
303
304    #[error(
305        "namespace collision: '{}' and '{}' both resolve to namespace '{ns}'",
306        path_a.display(),
307        path_b.display()
308    )]
309    #[diagnostic(
310        code(pitchfork::config::namespace_collision),
311        url("https://pitchfork.jdx.dev/concepts/namespaces"),
312        help(
313            "rename one of the directories so that no two project configs share the same namespace"
314        )
315    )]
316    NamespaceCollision {
317        path_a: PathBuf,
318        path_b: PathBuf,
319        ns: String,
320    },
321
322    #[error(
323        "invalid namespace '{namespace}' in {}: {reason}",
324        path.display()
325    )]
326    #[diagnostic(
327        code(pitchfork::config::invalid_namespace),
328        url("https://pitchfork.jdx.dev/concepts/namespaces"),
329        help(
330            "set a valid top-level namespace in your pitchfork.toml, e.g. namespace = \"my-project\""
331        )
332    )]
333    InvalidNamespace {
334        path: PathBuf,
335        namespace: String,
336        reason: String,
337    },
338}
339
340impl ConfigParseError {
341    /// Create a new ConfigParseError from a toml parse error
342    pub fn from_toml_error(path: &std::path::Path, contents: String, err: toml::de::Error) -> Self {
343        let message = err.message().to_string();
344
345        // Try to get span information from the TOML error
346        let span = err
347            .span()
348            .map(|r| SourceSpan::from(r.start..r.end))
349            .unwrap_or_else(|| SourceSpan::from(0..0));
350
351        Self::TomlError {
352            src: NamedSource::new(path.display().to_string(), contents),
353            span,
354            message,
355            help: Some("check TOML syntax at https://toml.io".to_string()),
356        }
357    }
358}
359
360/// Errors related to file operations (config and state files).
361#[derive(Debug, Error, Diagnostic)]
362pub enum FileError {
363    #[error("failed to read file: {}", path.display())]
364    #[diagnostic(code(pitchfork::file::read_error))]
365    ReadError {
366        path: PathBuf,
367        #[source]
368        source: io::Error,
369    },
370
371    #[error("failed to write file: {}", path.display())]
372    #[diagnostic(code(pitchfork::file::write_error))]
373    WriteError {
374        path: PathBuf,
375        #[help]
376        details: Option<String>,
377    },
378
379    #[error("failed to serialize data for file: {}", path.display())]
380    #[diagnostic(
381        code(pitchfork::file::serialize_error),
382        help("this is likely an internal error; please report it")
383    )]
384    SerializeError {
385        path: PathBuf,
386        #[source]
387        source: toml::ser::Error,
388    },
389
390    #[error("no file path specified")]
391    #[diagnostic(
392        code(pitchfork::file::no_path),
393        help("ensure a pitchfork.toml file exists in your project or specify a path")
394    )]
395    NoPath,
396}
397
398/// Errors related to IPC communication with the supervisor.
399#[derive(Debug, Error, Diagnostic)]
400pub enum IpcError {
401    #[error("failed to connect to supervisor after {attempts} attempts")]
402    #[diagnostic(
403        code(pitchfork::ipc::connection_failed),
404        url("https://pitchfork.jdx.dev/supervisor")
405    )]
406    ConnectionFailed {
407        attempts: u32,
408        #[source]
409        source: Option<io::Error>,
410        #[help]
411        help: String,
412    },
413
414    #[error("IPC request timed out after {seconds}s")]
415    #[diagnostic(
416        code(pitchfork::ipc::timeout),
417        url("https://pitchfork.jdx.dev/supervisor"),
418        help(
419            "the supervisor may be unresponsive or overloaded.\nCheck supervisor status: pitchfork supervisor status\nView logs: pitchfork logs"
420        )
421    )]
422    Timeout { seconds: u64 },
423
424    #[error("IPC connection closed unexpectedly")]
425    #[diagnostic(
426        code(pitchfork::ipc::connection_closed),
427        url("https://pitchfork.jdx.dev/supervisor"),
428        help(
429            "the supervisor may have crashed or been stopped.\nRestart with: pitchfork supervisor start"
430        )
431    )]
432    ConnectionClosed,
433
434    #[error("failed to read IPC response")]
435    #[diagnostic(code(pitchfork::ipc::read_failed))]
436    ReadFailed {
437        #[source]
438        source: io::Error,
439    },
440
441    #[error("failed to send IPC request")]
442    #[diagnostic(code(pitchfork::ipc::send_failed))]
443    SendFailed {
444        #[source]
445        source: io::Error,
446    },
447
448    #[error("unexpected response from supervisor: expected {expected}, got {actual}")]
449    #[diagnostic(
450        code(pitchfork::ipc::unexpected_response),
451        help("this may indicate a version mismatch between the CLI and supervisor")
452    )]
453    UnexpectedResponse { expected: String, actual: String },
454
455    #[error("IPC message is invalid: {reason}")]
456    #[diagnostic(code(pitchfork::ipc::invalid_message))]
457    InvalidMessage { reason: String },
458}
459
460/// A collection of multiple errors that occurred during validation or processing.
461///
462/// This is useful when you want to collect and report all validation errors at once
463/// instead of failing on the first error.
464#[derive(Debug, Error, Diagnostic)]
465#[error("multiple errors occurred ({} total)", errors.len())]
466#[diagnostic(code(pitchfork::multiple_errors))]
467#[allow(dead_code)]
468pub struct MultipleErrors {
469    #[related]
470    pub errors: Vec<Box<dyn Diagnostic + Send + Sync + 'static>>,
471}
472
473#[allow(dead_code)]
474impl MultipleErrors {
475    /// Create a new MultipleErrors from a vector of diagnostics
476    pub fn new(errors: Vec<Box<dyn Diagnostic + Send + Sync + 'static>>) -> Self {
477        Self { errors }
478    }
479
480    /// Returns true if there are no errors
481    pub fn is_empty(&self) -> bool {
482        self.errors.is_empty()
483    }
484
485    /// Returns the number of errors
486    pub fn len(&self) -> usize {
487        self.errors.len()
488    }
489}
490
491/// Find the most similar daemon name for suggestions.
492pub fn find_similar_daemon<'a>(
493    name: &str,
494    available: impl Iterator<Item = &'a str>,
495) -> Option<String> {
496    use fuzzy_matcher::FuzzyMatcher;
497    use fuzzy_matcher::skim::SkimMatcherV2;
498
499    let matcher = SkimMatcherV2::default();
500    available
501        .filter_map(|candidate| {
502            matcher
503                .fuzzy_match(candidate, name)
504                .map(|score| (candidate, score))
505        })
506        .max_by_key(|(_, score)| *score)
507        .filter(|(_, score)| *score > 0)
508        .map(|(candidate, _)| format!("did you mean '{candidate}'?"))
509}
510
511#[cfg(test)]
512mod tests {
513    use super::*;
514
515    #[test]
516    fn test_daemon_id_error_display() {
517        let err = DaemonIdError::Empty;
518        assert_eq!(err.to_string(), "daemon ID cannot be empty");
519
520        let err = DaemonIdError::PathSeparator {
521            id: "foo/bar".to_string(),
522            sep: '/',
523        };
524        assert_eq!(
525            err.to_string(),
526            "daemon ID 'foo/bar' contains path separator '/'"
527        );
528
529        let err = DaemonIdError::ContainsSpace {
530            id: "my app".to_string(),
531        };
532        assert_eq!(err.to_string(), "daemon ID 'my app' contains spaces");
533    }
534
535    #[test]
536    fn test_dependency_error_display() {
537        let err = DependencyError::DaemonNotFound {
538            name: "postgres".to_string(),
539            suggestion: None,
540        };
541        assert_eq!(
542            err.to_string(),
543            "daemon 'postgres' not found in configuration"
544        );
545
546        let err = DependencyError::MissingDependency {
547            daemon: "api".to_string(),
548            dependency: "db".to_string(),
549        };
550        assert_eq!(
551            err.to_string(),
552            "daemon 'api' depends on 'db' which is not defined"
553        );
554
555        let err = DependencyError::CircularDependency {
556            involved: vec!["a".to_string(), "b".to_string(), "c".to_string()],
557        };
558        assert!(err.to_string().contains("circular dependency"));
559        assert!(err.to_string().contains("a, b, c"));
560    }
561
562    #[test]
563    fn test_find_similar_daemon() {
564        let daemons = ["postgres", "redis", "api", "worker"];
565
566        // Close match
567        let suggestion = find_similar_daemon("postgre", daemons.iter().copied());
568        assert_eq!(suggestion, Some("did you mean 'postgres'?".to_string()));
569
570        // No reasonable match
571        let suggestion = find_similar_daemon("xyz123", daemons.iter().copied());
572        assert!(suggestion.is_none());
573    }
574
575    #[test]
576    fn test_file_error_display() {
577        let err = FileError::ReadError {
578            path: PathBuf::from("/path/to/config.toml"),
579            source: io::Error::new(io::ErrorKind::NotFound, "file not found"),
580        };
581        assert!(err.to_string().contains("failed to read file"));
582        assert!(err.to_string().contains("config.toml"));
583
584        let err = FileError::NoPath;
585        assert!(err.to_string().contains("no file path"));
586    }
587
588    #[test]
589    fn test_ipc_error_display() {
590        let err = IpcError::ConnectionFailed {
591            attempts: 5,
592            source: None,
593            help: "ensure the supervisor is running".to_string(),
594        };
595        assert!(err.to_string().contains("failed to connect"));
596        assert!(err.to_string().contains("5 attempts"));
597
598        let err = IpcError::Timeout { seconds: 30 };
599        assert!(err.to_string().contains("timed out"));
600        assert!(err.to_string().contains("30s"));
601
602        let err = IpcError::UnexpectedResponse {
603            expected: "Ok".to_string(),
604            actual: "Error".to_string(),
605        };
606        assert!(err.to_string().contains("unexpected response"));
607        assert!(err.to_string().contains("Ok"));
608        assert!(err.to_string().contains("Error"));
609    }
610
611    #[test]
612    fn test_config_parse_error() {
613        let contents = "[daemons.test]\nrun = ".to_string();
614        let err = toml::from_str::<toml::Value>(&contents).unwrap_err();
615        let parse_err =
616            ConfigParseError::from_toml_error(std::path::Path::new("test.toml"), contents, err);
617
618        assert!(parse_err.to_string().contains("failed to parse"));
619    }
620
621    #[test]
622    fn test_multiple_errors() {
623        let errors: Vec<Box<dyn Diagnostic + Send + Sync>> = vec![
624            Box::new(DaemonIdError::Empty),
625            Box::new(DaemonIdError::CurrentDir),
626        ];
627        let multi = MultipleErrors::new(errors);
628
629        assert_eq!(multi.len(), 2);
630        assert!(!multi.is_empty());
631        assert!(multi.to_string().contains("2 total"));
632    }
633}