1#![allow(unused_assignments)]
8
9use miette::{Diagnostic, NamedSource, SourceSpan};
10use std::io;
11use std::path::PathBuf;
12use thiserror::Error;
13
14#[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#[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#[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 involved: Vec<String>,
151 },
152}
153
154#[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#[derive(Debug, Error, Diagnostic)]
184pub enum ConfigParseError {
185 #[error("failed to parse configuration")]
186 #[diagnostic(code(pitchfork::config::parse_error))]
187 TomlError {
188 #[source_code]
190 src: NamedSource<String>,
191
192 #[label("{message}")]
194 span: SourceSpan,
195
196 message: String,
198
199 #[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 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 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#[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#[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 #[error("IPC request timed out after {seconds}s")]
436 #[diagnostic(
437 code(pitchfork::ipc::timeout),
438 url("https://pitchfork.jdx.dev/supervisor"),
439 help(
440 "the supervisor may be unresponsive or overloaded.\nCheck supervisor status: pitchfork supervisor status\nView logs: pitchfork logs"
441 )
442 )]
443 Timeout { seconds: u64 },
444
445 #[error("IPC connection closed unexpectedly")]
446 #[diagnostic(
447 code(pitchfork::ipc::connection_closed),
448 url("https://pitchfork.jdx.dev/supervisor"),
449 help(
450 "the supervisor may have crashed or been stopped.\nRestart with: pitchfork supervisor start"
451 )
452 )]
453 ConnectionClosed,
454
455 #[error("failed to read IPC response")]
456 #[diagnostic(code(pitchfork::ipc::read_failed))]
457 ReadFailed {
458 #[source]
459 source: io::Error,
460 },
461
462 #[error("failed to send IPC request")]
463 #[diagnostic(code(pitchfork::ipc::send_failed))]
464 SendFailed {
465 #[source]
466 source: io::Error,
467 },
468
469 #[error("unexpected response from supervisor: expected {expected}, got {actual}")]
470 #[diagnostic(
471 code(pitchfork::ipc::unexpected_response),
472 help("this may indicate a version mismatch between the CLI and supervisor")
473 )]
474 UnexpectedResponse { expected: String, actual: String },
475
476 #[error("IPC message is invalid: {reason}")]
477 #[diagnostic(code(pitchfork::ipc::invalid_message))]
478 InvalidMessage { reason: String },
479}
480
481#[derive(Debug, Error, Diagnostic)]
486#[error("multiple errors occurred ({} total)", errors.len())]
487#[diagnostic(code(pitchfork::multiple_errors))]
488#[allow(dead_code)]
489pub struct MultipleErrors {
490 #[related]
491 pub errors: Vec<Box<dyn Diagnostic + Send + Sync + 'static>>,
492}
493
494#[allow(dead_code)]
495impl MultipleErrors {
496 pub fn new(errors: Vec<Box<dyn Diagnostic + Send + Sync + 'static>>) -> Self {
498 Self { errors }
499 }
500
501 pub fn is_empty(&self) -> bool {
503 self.errors.is_empty()
504 }
505
506 pub fn len(&self) -> usize {
508 self.errors.len()
509 }
510}
511
512pub fn find_similar_daemon<'a>(
514 name: &str,
515 available: impl Iterator<Item = &'a str>,
516) -> Option<String> {
517 use fuzzy_matcher::FuzzyMatcher;
518 use fuzzy_matcher::skim::SkimMatcherV2;
519
520 let matcher = SkimMatcherV2::default();
521 available
522 .filter_map(|candidate| {
523 matcher
524 .fuzzy_match(candidate, name)
525 .map(|score| (candidate, score))
526 })
527 .max_by_key(|(_, score)| *score)
528 .filter(|(_, score)| *score > 0)
529 .map(|(candidate, _)| format!("did you mean '{candidate}'?"))
530}
531
532#[cfg(test)]
533mod tests {
534 use super::*;
535
536 #[test]
537 fn test_daemon_id_error_display() {
538 let err = DaemonIdError::Empty;
539 assert_eq!(err.to_string(), "daemon ID cannot be empty");
540
541 let err = DaemonIdError::PathSeparator {
542 id: "foo/bar".to_string(),
543 sep: '/',
544 };
545 assert_eq!(
546 err.to_string(),
547 "daemon ID 'foo/bar' contains path separator '/'"
548 );
549
550 let err = DaemonIdError::ContainsSpace {
551 id: "my app".to_string(),
552 };
553 assert_eq!(err.to_string(), "daemon ID 'my app' contains spaces");
554 }
555
556 #[test]
557 fn test_dependency_error_display() {
558 let err = DependencyError::DaemonNotFound {
559 name: "postgres".to_string(),
560 suggestion: None,
561 };
562 assert_eq!(
563 err.to_string(),
564 "daemon 'postgres' not found in configuration"
565 );
566
567 let err = DependencyError::MissingDependency {
568 daemon: "api".to_string(),
569 dependency: "db".to_string(),
570 };
571 assert_eq!(
572 err.to_string(),
573 "daemon 'api' depends on 'db' which is not defined"
574 );
575
576 let err = DependencyError::CircularDependency {
577 involved: vec!["a".to_string(), "b".to_string(), "c".to_string()],
578 };
579 assert!(err.to_string().contains("circular dependency"));
580 assert!(err.to_string().contains("a, b, c"));
581 }
582
583 #[test]
584 fn test_find_similar_daemon() {
585 let daemons = ["postgres", "redis", "api", "worker"];
586
587 let suggestion = find_similar_daemon("postgre", daemons.iter().copied());
589 assert_eq!(suggestion, Some("did you mean 'postgres'?".to_string()));
590
591 let suggestion = find_similar_daemon("xyz123", daemons.iter().copied());
593 assert!(suggestion.is_none());
594 }
595
596 #[test]
597 fn test_file_error_display() {
598 let err = FileError::ReadError {
599 path: PathBuf::from("/path/to/config.toml"),
600 source: io::Error::new(io::ErrorKind::NotFound, "file not found"),
601 };
602 assert!(err.to_string().contains("failed to read file"));
603 assert!(err.to_string().contains("config.toml"));
604
605 let err = FileError::NoPath;
606 assert!(err.to_string().contains("no file path"));
607 }
608
609 #[test]
610 fn test_ipc_error_display() {
611 let err = IpcError::ConnectionFailed {
612 attempts: 5,
613 source: None,
614 help: "ensure the supervisor is running".to_string(),
615 };
616 assert!(err.to_string().contains("failed to connect"));
617 assert!(err.to_string().contains("5 attempts"));
618
619 let err = IpcError::Timeout { seconds: 30 };
620 assert!(err.to_string().contains("timed out"));
621 assert!(err.to_string().contains("30s"));
622
623 let err = IpcError::UnexpectedResponse {
624 expected: "Ok".to_string(),
625 actual: "Error".to_string(),
626 };
627 assert!(err.to_string().contains("unexpected response"));
628 assert!(err.to_string().contains("Ok"));
629 assert!(err.to_string().contains("Error"));
630 }
631
632 #[test]
633 fn test_config_parse_error() {
634 let contents = "[daemons.test]\nrun = ".to_string();
635 let err = toml::from_str::<toml::Value>(&contents).unwrap_err();
636 let parse_err =
637 ConfigParseError::from_toml_error(std::path::Path::new("test.toml"), contents, err);
638
639 assert!(parse_err.to_string().contains("failed to parse"));
640 }
641
642 #[test]
643 fn test_multiple_errors() {
644 let errors: Vec<Box<dyn Diagnostic + Send + Sync>> = vec![
645 Box::new(DaemonIdError::Empty),
646 Box::new(DaemonIdError::CurrentDir),
647 ];
648 let multi = MultipleErrors::new(errors);
649
650 assert_eq!(multi.len(), 2);
651 assert!(!multi.is_empty());
652 assert!(multi.to_string().contains("2 total"));
653 }
654}