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