pitchfork-cli 2.13.1

Daemons with DX
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
//! Custom diagnostic error types for rich error reporting via miette.
//!
//! This module provides structured error types that leverage miette's diagnostic
//! features including error codes, help text, source code highlighting, and suggestions.

// False positive: fields are used in #[error] format strings and miette derive macros
#![allow(unused_assignments)]

use miette::{Diagnostic, NamedSource, SourceSpan};
use std::io;
use std::path::PathBuf;
use thiserror::Error;

/// Errors related to daemon ID validation.
#[derive(Debug, Error, Diagnostic)]
pub enum DaemonIdError {
    #[error("daemon ID cannot be empty")]
    #[diagnostic(
        code(pitchfork::daemon::empty_id),
        url("https://pitchfork.jdx.dev/configuration"),
        help("provide a non-empty identifier for the daemon")
    )]
    Empty,

    #[error("daemon ID {component} cannot be empty")]
    #[diagnostic(
        code(pitchfork::daemon::empty_component),
        url("https://pitchfork.jdx.dev/configuration"),
        help("both namespace and name must be non-empty")
    )]
    EmptyComponent { component: String },

    #[error("daemon ID '{id}' contains path separator '{sep}'")]
    #[diagnostic(
        code(pitchfork::daemon::path_separator),
        url("https://pitchfork.jdx.dev/configuration"),
        help("daemon IDs cannot contain '/' or '\\' to prevent path traversal")
    )]
    PathSeparator { id: String, sep: char },

    #[error("daemon ID '{id}' contains parent directory reference '..'")]
    #[diagnostic(
        code(pitchfork::daemon::parent_dir_ref),
        url("https://pitchfork.jdx.dev/configuration"),
        help("daemon IDs cannot contain '..' to prevent path traversal")
    )]
    ParentDirRef { id: String },

    #[error("daemon ID '{id}' contains reserved sequence '--'")]
    #[diagnostic(
        code(pitchfork::daemon::reserved_sequence),
        url("https://pitchfork.jdx.dev/configuration"),
        help("'--' is reserved for internal path encoding; use single dashes instead")
    )]
    ReservedSequence { id: String },

    #[error("daemon ID component '{id}' starts or ends with a dash '-'")]
    #[diagnostic(
        code(pitchfork::daemon::leading_trailing_dash),
        url("https://pitchfork.jdx.dev/configuration"),
        help(
            "remove the leading or trailing dash (e.g. 'my-daemon' not '-my-daemon' or 'my-daemon-')"
        )
    )]
    LeadingTrailingDash { id: String },

    #[error("daemon ID '{id}' contains spaces")]
    #[diagnostic(
        code(pitchfork::daemon::contains_space),
        url("https://pitchfork.jdx.dev/configuration"),
        help("use hyphens or underscores instead of spaces (e.g., 'my-daemon' or 'my_daemon')")
    )]
    ContainsSpace { id: String },

    #[error("daemon ID cannot be '.'")]
    #[diagnostic(
        code(pitchfork::daemon::current_dir),
        url("https://pitchfork.jdx.dev/configuration"),
        help("'.' refers to the current directory; use a descriptive name instead")
    )]
    CurrentDir,

    #[error("daemon ID '{id}' contains non-printable or non-ASCII character")]
    #[diagnostic(
        code(pitchfork::daemon::invalid_chars),
        url("https://pitchfork.jdx.dev/configuration"),
        help(
            "daemon IDs must contain only printable ASCII characters (letters, numbers, hyphens, underscores, dots)"
        )
    )]
    InvalidChars { id: String },

    #[error("daemon ID '{id}' is missing namespace (expected format: namespace/name)")]
    #[diagnostic(
        code(pitchfork::daemon::missing_namespace),
        url("https://pitchfork.jdx.dev/configuration"),
        help("use qualified format like 'global/myapp' or 'project-name/daemon'")
    )]
    MissingNamespace { id: String },

    #[error("invalid safe path format '{path}' (expected namespace--name)")]
    #[diagnostic(
        code(pitchfork::daemon::invalid_safe_path),
        help("safe paths use '--' to separate namespace and name")
    )]
    InvalidSafePath { path: String },
}

/// Errors related to daemon operations.
#[derive(Debug, Error, Diagnostic)]
pub enum DaemonError {
    #[error("failed to stop daemon '{id}': {error}")]
    #[diagnostic(
        code(pitchfork::daemon::stop_failed),
        help("the process may be stuck or require manual intervention. Try: kill -9 <pid>")
    )]
    StopFailed { id: String, error: String },
}

/// Errors related to dependency resolution.
#[derive(Debug, Error, Diagnostic)]
pub enum DependencyError {
    #[error("daemon '{name}' not found in configuration")]
    #[diagnostic(
        code(pitchfork::deps::not_found),
        url("https://pitchfork.jdx.dev/configuration#depends")
    )]
    DaemonNotFound {
        name: String,
        #[help]
        suggestion: Option<String>,
    },

    #[error("daemon '{daemon}' depends on '{dependency}' which is not defined")]
    #[diagnostic(
        code(pitchfork::deps::missing_dependency),
        url("https://pitchfork.jdx.dev/configuration#depends"),
        help("add the missing daemon to your pitchfork.toml or remove it from the depends list")
    )]
    MissingDependency { daemon: String, dependency: String },

    #[error("circular dependency detected involving: {}", involved.join(", "))]
    #[diagnostic(
        code(pitchfork::deps::circular),
        url("https://pitchfork.jdx.dev/configuration#depends"),
        help("break the cycle by removing one of the dependencies")
    )]
    CircularDependency {
        /// The daemons involved in the cycle
        involved: Vec<String>,
    },
}

/// Errors related to port binding and availability.
#[derive(Debug, Error, Diagnostic)]
pub enum PortError {
    #[error("port {port} is already in use by process '{process}' (PID: {pid})")]
    #[diagnostic(
        code(pitchfork::port::in_use),
        url("https://pitchfork.jdx.dev/configuration#port"),
        help(
            "choose a different port, stop the existing process, or enable auto_bump_port to automatically find an available port"
        )
    )]
    InUse {
        port: u16,
        process: String,
        pid: u32,
    },

    #[error(
        "could not find an available port after {attempts} attempts starting from {start_port}"
    )]
    #[diagnostic(
        code(pitchfork::port::no_available_port),
        url("https://pitchfork.jdx.dev/configuration#port"),
        help("manually specify an available port or reduce the number of concurrent services")
    )]
    NoAvailablePort { start_port: u16, attempts: u32 },
}

/// Error for TOML configuration parse failures with source code highlighting.
#[derive(Debug, Error, Diagnostic)]
pub enum ConfigParseError {
    #[error("failed to parse configuration")]
    #[diagnostic(code(pitchfork::config::parse_error))]
    TomlError {
        /// The source file contents for display
        #[source_code]
        src: NamedSource<String>,

        /// The location of the error in the source
        #[label("{message}")]
        span: SourceSpan,

        /// The error message from the TOML parser
        message: String,

        /// Additional help text
        #[help]
        help: Option<String>,
    },

    #[error("invalid daemon name '{name}' in {}", path.display())]
    #[diagnostic(
        code(pitchfork::config::invalid_daemon_name),
        url("https://pitchfork.jdx.dev/configuration"),
        help("daemon names must be valid identifiers without spaces, '--', or special characters")
    )]
    InvalidDaemonName {
        name: String,
        path: PathBuf,
        reason: String,
    },

    #[error(
        "invalid dependency '{dependency}' in daemon '{daemon}' ({}): {reason}",
        path.display()
    )]
    #[diagnostic(
        code(pitchfork::config::invalid_dependency),
        url("https://pitchfork.jdx.dev/configuration#depends"),
        help(
            "dependency IDs must be valid daemon IDs; use 'name' for same namespace or 'namespace/name' for cross-namespace"
        )
    )]
    InvalidDependency {
        daemon: String,
        dependency: String,
        path: PathBuf,
        reason: String,
    },

    #[error(
        "namespace collision: '{}' and '{}' both resolve to namespace '{ns}'",
        path_a.display(),
        path_b.display()
    )]
    #[diagnostic(
        code(pitchfork::config::namespace_collision),
        url("https://pitchfork.jdx.dev/concepts/namespaces"),
        help(
            "rename one of the directories so that no two project configs share the same namespace"
        )
    )]
    NamespaceCollision {
        path_a: PathBuf,
        path_b: PathBuf,
        ns: String,
    },

    #[error(
        "invalid namespace '{namespace}' in {}: {reason}",
        path.display()
    )]
    #[diagnostic(
        code(pitchfork::config::invalid_namespace),
        url("https://pitchfork.jdx.dev/concepts/namespaces"),
        help(
            "set a valid top-level namespace in your pitchfork.toml, e.g. namespace = \"my-project\""
        )
    )]
    InvalidNamespace {
        path: PathBuf,
        namespace: String,
        reason: String,
    },
}

impl ConfigParseError {
    /// Create a new ConfigParseError from a toml parse error
    pub fn from_toml_error(path: &std::path::Path, contents: String, err: toml::de::Error) -> Self {
        let message = err.message().to_string();

        // Try to get span information from the TOML error
        let span = err
            .span()
            .map(|r| SourceSpan::from(r.start..r.end))
            .unwrap_or_else(|| SourceSpan::from(0..0));

        Self::TomlError {
            src: NamedSource::new(path.display().to_string(), contents),
            span,
            message,
            help: Some("check TOML syntax at https://toml.io".to_string()),
        }
    }
}

/// Errors related to file operations (config and state files).
#[derive(Debug, Error, Diagnostic)]
pub enum FileError {
    #[error("failed to read file: {}", path.display())]
    #[diagnostic(code(pitchfork::file::read_error))]
    ReadError {
        path: PathBuf,
        #[source]
        source: io::Error,
    },

    #[error("failed to write file: {}", path.display())]
    #[diagnostic(code(pitchfork::file::write_error))]
    WriteError {
        path: PathBuf,
        #[help]
        details: Option<String>,
    },

    #[error("failed to serialize data for file: {}", path.display())]
    #[diagnostic(
        code(pitchfork::file::serialize_error),
        help("this is likely an internal error; please report it")
    )]
    SerializeError {
        path: PathBuf,
        #[source]
        source: toml::ser::Error,
    },

    #[error("no file path specified")]
    #[diagnostic(
        code(pitchfork::file::no_path),
        help("ensure a pitchfork.toml file exists in your project or specify a path")
    )]
    NoPath,
}

/// Errors related to IPC communication with the supervisor.
#[derive(Debug, Error, Diagnostic)]
pub enum IpcError {
    #[error("failed to connect to supervisor after {attempts} attempts")]
    #[diagnostic(
        code(pitchfork::ipc::connection_failed),
        url("https://pitchfork.jdx.dev/supervisor")
    )]
    ConnectionFailed {
        attempts: u32,
        #[source]
        source: Option<io::Error>,
        #[help]
        help: String,
    },

    #[error("IPC request timed out after {seconds}s")]
    #[diagnostic(
        code(pitchfork::ipc::timeout),
        url("https://pitchfork.jdx.dev/supervisor"),
        help(
            "the supervisor may be unresponsive or overloaded.\nCheck supervisor status: pitchfork supervisor status\nView logs: pitchfork logs"
        )
    )]
    Timeout { seconds: u64 },

    #[error("IPC connection closed unexpectedly")]
    #[diagnostic(
        code(pitchfork::ipc::connection_closed),
        url("https://pitchfork.jdx.dev/supervisor"),
        help(
            "the supervisor may have crashed or been stopped.\nRestart with: pitchfork supervisor start"
        )
    )]
    ConnectionClosed,

    #[error("failed to read IPC response")]
    #[diagnostic(code(pitchfork::ipc::read_failed))]
    ReadFailed {
        #[source]
        source: io::Error,
    },

    #[error("failed to send IPC request")]
    #[diagnostic(code(pitchfork::ipc::send_failed))]
    SendFailed {
        #[source]
        source: io::Error,
    },

    #[error("unexpected response from supervisor: expected {expected}, got {actual}")]
    #[diagnostic(
        code(pitchfork::ipc::unexpected_response),
        help("this may indicate a version mismatch between the CLI and supervisor")
    )]
    UnexpectedResponse { expected: String, actual: String },

    #[error("IPC message is invalid: {reason}")]
    #[diagnostic(code(pitchfork::ipc::invalid_message))]
    InvalidMessage { reason: String },
}

/// A collection of multiple errors that occurred during validation or processing.
///
/// This is useful when you want to collect and report all validation errors at once
/// instead of failing on the first error.
#[derive(Debug, Error, Diagnostic)]
#[error("multiple errors occurred ({} total)", errors.len())]
#[diagnostic(code(pitchfork::multiple_errors))]
#[allow(dead_code)]
pub struct MultipleErrors {
    #[related]
    pub errors: Vec<Box<dyn Diagnostic + Send + Sync + 'static>>,
}

#[allow(dead_code)]
impl MultipleErrors {
    /// Create a new MultipleErrors from a vector of diagnostics
    pub fn new(errors: Vec<Box<dyn Diagnostic + Send + Sync + 'static>>) -> Self {
        Self { errors }
    }

    /// Returns true if there are no errors
    pub fn is_empty(&self) -> bool {
        self.errors.is_empty()
    }

    /// Returns the number of errors
    pub fn len(&self) -> usize {
        self.errors.len()
    }
}

/// Find the most similar daemon name for suggestions.
pub fn find_similar_daemon<'a>(
    name: &str,
    available: impl Iterator<Item = &'a str>,
) -> Option<String> {
    use fuzzy_matcher::FuzzyMatcher;
    use fuzzy_matcher::skim::SkimMatcherV2;

    let matcher = SkimMatcherV2::default();
    available
        .filter_map(|candidate| {
            matcher
                .fuzzy_match(candidate, name)
                .map(|score| (candidate, score))
        })
        .max_by_key(|(_, score)| *score)
        .filter(|(_, score)| *score > 0)
        .map(|(candidate, _)| format!("did you mean '{candidate}'?"))
}

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

    #[test]
    fn test_daemon_id_error_display() {
        let err = DaemonIdError::Empty;
        assert_eq!(err.to_string(), "daemon ID cannot be empty");

        let err = DaemonIdError::PathSeparator {
            id: "foo/bar".to_string(),
            sep: '/',
        };
        assert_eq!(
            err.to_string(),
            "daemon ID 'foo/bar' contains path separator '/'"
        );

        let err = DaemonIdError::ContainsSpace {
            id: "my app".to_string(),
        };
        assert_eq!(err.to_string(), "daemon ID 'my app' contains spaces");
    }

    #[test]
    fn test_dependency_error_display() {
        let err = DependencyError::DaemonNotFound {
            name: "postgres".to_string(),
            suggestion: None,
        };
        assert_eq!(
            err.to_string(),
            "daemon 'postgres' not found in configuration"
        );

        let err = DependencyError::MissingDependency {
            daemon: "api".to_string(),
            dependency: "db".to_string(),
        };
        assert_eq!(
            err.to_string(),
            "daemon 'api' depends on 'db' which is not defined"
        );

        let err = DependencyError::CircularDependency {
            involved: vec!["a".to_string(), "b".to_string(), "c".to_string()],
        };
        assert!(err.to_string().contains("circular dependency"));
        assert!(err.to_string().contains("a, b, c"));
    }

    #[test]
    fn test_find_similar_daemon() {
        let daemons = ["postgres", "redis", "api", "worker"];

        // Close match
        let suggestion = find_similar_daemon("postgre", daemons.iter().copied());
        assert_eq!(suggestion, Some("did you mean 'postgres'?".to_string()));

        // No reasonable match
        let suggestion = find_similar_daemon("xyz123", daemons.iter().copied());
        assert!(suggestion.is_none());
    }

    #[test]
    fn test_file_error_display() {
        let err = FileError::ReadError {
            path: PathBuf::from("/path/to/config.toml"),
            source: io::Error::new(io::ErrorKind::NotFound, "file not found"),
        };
        assert!(err.to_string().contains("failed to read file"));
        assert!(err.to_string().contains("config.toml"));

        let err = FileError::NoPath;
        assert!(err.to_string().contains("no file path"));
    }

    #[test]
    fn test_ipc_error_display() {
        let err = IpcError::ConnectionFailed {
            attempts: 5,
            source: None,
            help: "ensure the supervisor is running".to_string(),
        };
        assert!(err.to_string().contains("failed to connect"));
        assert!(err.to_string().contains("5 attempts"));

        let err = IpcError::Timeout { seconds: 30 };
        assert!(err.to_string().contains("timed out"));
        assert!(err.to_string().contains("30s"));

        let err = IpcError::UnexpectedResponse {
            expected: "Ok".to_string(),
            actual: "Error".to_string(),
        };
        assert!(err.to_string().contains("unexpected response"));
        assert!(err.to_string().contains("Ok"));
        assert!(err.to_string().contains("Error"));
    }

    #[test]
    fn test_config_parse_error() {
        let contents = "[daemons.test]\nrun = ".to_string();
        let err = toml::from_str::<toml::Value>(&contents).unwrap_err();
        let parse_err =
            ConfigParseError::from_toml_error(std::path::Path::new("test.toml"), contents, err);

        assert!(parse_err.to_string().contains("failed to parse"));
    }

    #[test]
    fn test_multiple_errors() {
        let errors: Vec<Box<dyn Diagnostic + Send + Sync>> = vec![
            Box::new(DaemonIdError::Empty),
            Box::new(DaemonIdError::CurrentDir),
        ];
        let multi = MultipleErrors::new(errors);

        assert_eq!(multi.len(), 2);
        assert!(!multi.is_empty());
        assert!(multi.to_string().contains("2 total"));
    }
}