pitchfork-cli 2.36.0

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
use crate::Result;
use crate::cli::daemons::resolve_config_path;
use crate::daemon_id::DaemonId;
use crate::pitchfork_toml::{
    CronRetrigger, HealthCmd, HealthHttp, HealthPort, PitchforkToml, PitchforkTomlAuto,
    PitchforkTomlCron, PitchforkTomlDaemon, PitchforkTomlHooks, PortBump, PortConfig, ReadyCmd,
    ReadyHttp, ReadyOutput, ReadyPort, Retry, namespace_from_path,
};
use crate::settings::settings;
use indexmap::IndexMap;
use miette::{IntoDiagnostic, bail};
use std::path::PathBuf;

/// Add a new daemon to pitchfork.toml
#[derive(Debug, usage_rs::Args)]
#[usage(
    verbatim_doc_comment,
    long_about = "\
Add a new daemon to pitchfork.toml

Creates a new daemon configuration section in the pitchfork.toml file.
The daemon will be added to the nearest pitchfork.toml found in the
filesystem hierarchy starting from the current directory.

Examples:

    pitchfork daemons add api bun run server
                                     Add daemon using positional args
    pitchfork daemons add api --run 'npm start'
                                     Add daemon with explicit run command
    pitchfork daemons add api -- bun run server
                                     Add daemon with explicit args after --
    pitchfork daemons add api --run 'npm start' --retry 3
                                     Add with retry policy
    pitchfork daemons add api --run 'npm start' --watch 'src/**/*.ts'
                                     Add with file watching
    pitchfork daemons add api --run 'npm start' --autostart --autostop
                                     Add with auto start/stop hooks
    pitchfork daemons add worker --run './worker' --depends api
                                     Add with daemon dependency
    pitchfork daemons add api --run 'npm start' --local
                                   Add to pitchfork.local.toml instead
    pitchfork daemons add api --run 'npm start' --global
                                  Add to ~/.config/pitchfork/config.toml instead
    pitchfork daemons add worker --run './worker' --cron-schedule '0 */5 * * * *' --cron-immediate
                                  Schedule every five minutes, including a just-missed trigger
"
)]
pub struct Add {
    /// ID of the daemon to add (e.g., "api" or "namespace/api")
    pub id: String,
    /// Command to run (can also use positional args)
    #[usage(long)]
    run: Option<String>,
    /// Arguments to pass to the daemon (alternative to --run)
    #[usage(double_dash = "automatic")]
    args: Vec<String>,
    /// Number of retry attempts on failure (use \"true\" for infinite)
    #[usage(long)]
    retry: Option<String>,
    /// Glob patterns to watch for changes (can be specified multiple times)
    #[usage(long = "watch")]
    watch: Vec<String>,
    /// Working directory for the daemon
    #[usage(long)]
    dir: Option<String>,
    /// Environment variables in KEY=value format (can be specified multiple times)
    #[usage(long = "env")]
    env: Vec<String>,
    /// Delay in seconds before considering daemon ready
    #[usage(long)]
    ready_delay: Option<u64>,
    /// Regex pattern to match in output for readiness
    #[usage(long)]
    ready_output: Option<String>,
    /// HTTP endpoint URL to poll for readiness
    #[usage(long)]
    ready_http: Option<String>,
    /// TCP port to check for readiness (a number or Tera template)
    #[usage(long)]
    ready_port: Option<ReadyPort>,
    /// Shell command to poll for readiness
    #[usage(long)]
    ready_cmd: Option<String>,
    /// Shell command to poll for health (exit code 0 = healthy)
    #[usage(long)]
    health_cmd: Option<String>,
    /// HTTP endpoint URL to poll for health
    #[usage(long)]
    health_http: Option<String>,
    /// TCP port to probe for health (connection success = healthy)
    #[usage(long)]
    health_port: Option<u16>,
    /// Ports the daemon is expected to bind to (can be specified multiple times or comma-separated)
    #[usage(long = "expected-port", delimiter = ',')]
    expected_port: Vec<u16>,
    /// Automatically find an available port if the expected port is in use
    #[usage(long, value_name = "BUMP")]
    bump: Option<Option<u32>>,
    /// Daemon dependencies that must start first (can be specified multiple times)
    #[usage(long = "depends")]
    depends: Vec<String>,
    /// Start this daemon automatically on system boot
    #[usage(long)]
    boot_start: bool,
    /// Autostart the daemon when entering the directory
    #[usage(long)]
    autostart: bool,
    /// Autostop the daemon when leaving the directory
    #[usage(long)]
    autostop: bool,
    /// Command to run when daemon becomes ready
    #[usage(long)]
    on_ready: Option<String>,
    /// Command to run when daemon fails
    #[usage(long)]
    on_fail: Option<String>,
    /// Command to run before each retry attempt
    #[usage(long)]
    on_retry: Option<String>,
    /// Command to run when the daemon is explicitly stopped by pitchfork
    #[usage(long)]
    on_stop: Option<String>,
    /// Command to run on any daemon termination (clean exit, crash, or stop)
    #[usage(long)]
    on_exit: Option<String>,
    /// Cron schedule expression (6 fields: second minute hour day month weekday)
    #[usage(long)]
    cron_schedule: Option<String>,
    /// Cron retrigger behavior: finish, always, success, fail
    #[usage(long)]
    cron_retrigger: Option<String>,
    /// On the first cron check, include scheduled times from the previous 10 seconds
    #[usage(long)]
    cron_immediate: bool,
    /// Write to pitchfork.local.toml instead of pitchfork.toml
    #[usage(long)]
    local: bool,
    /// Write to pitchfork.toml explicitly (default if no flag specified)
    #[usage(long)]
    project: bool,
    /// Write to the user-level global config (~/.config/pitchfork/config.toml)
    #[usage(long)]
    global: bool,
}

impl Add {
    pub async fn run(&self) -> Result<()> {
        let config_path = resolve_config_path(self.global, self.local, self.project, false).await?;

        let mut pt = if tokio::fs::try_exists(&config_path).await.unwrap_or(false) {
            let config_path_clone = config_path.clone();
            let result =
                tokio::task::spawn_blocking(move || PitchforkToml::read(&config_path_clone))
                    .await
                    .into_diagnostic()?;
            result.map_err(|e| miette::miette!("{e}"))?
        } else {
            if let Some(parent) = config_path.parent() {
                tokio::fs::create_dir_all(parent).await.map_err(|e| {
                    miette::miette!(
                        "Failed to create config directory {}: {e}",
                        parent.display()
                    )
                })?;
            }
            PitchforkToml::new(config_path.clone())
        };
        pt.path = Some(config_path.clone());

        let run_cmd = if let Some(ref run) = self.run {
            run.clone()
        } else if !self.args.is_empty() {
            shell_words::join(&self.args)
        } else {
            bail!("Either --run or command arguments must be provided");
        };

        let retry = if let Some(ref retry_str) = self.retry {
            Self::parse_retry(retry_str)?
        } else {
            Retry::default()
        };

        let env = if self.env.is_empty() {
            None
        } else {
            let mut map = IndexMap::new();
            for env_str in &self.env {
                let parts: Vec<&str> = env_str.splitn(2, '=').collect();
                if parts.len() != 2 {
                    bail!(
                        "Invalid environment variable format: {}. Expected KEY=value",
                        env_str
                    );
                }
                map.insert(parts[0].to_string(), parts[1].to_string());
            }
            Some(map)
        };

        let mut auto = vec![];
        if self.autostart {
            auto.push(PitchforkTomlAuto::Start);
        }
        if self.autostop {
            auto.push(PitchforkTomlAuto::Stop);
        }

        let hooks = if self.on_ready.is_some()
            || self.on_fail.is_some()
            || self.on_retry.is_some()
            || self.on_stop.is_some()
            || self.on_exit.is_some()
        {
            Some(PitchforkTomlHooks {
                on_ready: self.on_ready.clone(),
                on_fail: self.on_fail.clone(),
                on_retry: self.on_retry.clone(),
                on_stop: self.on_stop.clone(),
                on_exit: self.on_exit.clone(),
                on_output: None,
            })
        } else {
            None
        };

        let cron = if let Some(ref schedule) = self.cron_schedule {
            let retrigger = self
                .cron_retrigger
                .as_ref()
                .map(|s| Self::parse_cron_retrigger(s))
                .transpose()?
                .unwrap_or(CronRetrigger::Finish);
            Some(PitchforkTomlCron {
                schedule: schedule.clone(),
                retrigger,
                immediate: self.cron_immediate,
            })
        } else {
            None
        };

        let boot_start = if self.boot_start { Some(true) } else { None };

        let canonical_path = tokio::fs::canonicalize(&config_path)
            .await
            .unwrap_or_else(|_| config_path.clone());
        let daemon_id = if self.id.contains('/') {
            DaemonId::parse(&self.id)?
        } else {
            let namespace = namespace_from_path(&canonical_path)?;
            DaemonId::try_new(&namespace, &self.id)?
        };
        pt.daemons.insert(
            daemon_id.clone(),
            PitchforkTomlDaemon {
                run: run_cmd.into(),
                auto,
                cron,
                retry,
                ready_delay: self.ready_delay,
                ready_output: self.ready_output.clone().map(ReadyOutput::new),
                ready_http: self.ready_http.clone().map(ReadyHttp::new),
                ready_port: self.ready_port.clone(),
                ready_cmd: self.ready_cmd.clone().map(ReadyCmd::new),
                health_cmd: self.health_cmd.clone().map(HealthCmd::new),
                health_http: self.health_http.clone().map(HealthHttp::new),
                health_port: self.health_port.map(HealthPort::new),
                port: {
                    let expect = self.expected_port.clone();
                    let bump = match self.bump {
                        None => PortBump(0),
                        Some(None) => PortBump(settings().default_port_bump_attempts()),
                        Some(Some(n)) => PortBump(n),
                    };
                    PortConfig::from_parts(expect, bump)
                },
                boot_start,
                depends: {
                    let namespace = daemon_id.namespace().to_string();
                    let mut deps = Vec::new();
                    for dep in &self.depends {
                        let dep_id = if dep.contains('/') {
                            DaemonId::parse(dep)?
                        } else {
                            DaemonId::try_new(&namespace, dep)?
                        };
                        deps.push(dep_id);
                    }
                    deps
                },
                watch: self.watch.clone(),
                dir: self.dir.clone(),
                env,
                hooks,
                ..PitchforkTomlDaemon::default()
            },
        );
        let project_dir = crate::pitchfork_toml::project_dir_for_config(&config_path)
            .unwrap_or_else(|| PathBuf::from("."));
        tokio::task::spawn_blocking(move || {
            PitchforkToml::validate_aliases_after_save(&project_dir, &pt)?;
            pt.write()
        })
        .await
        .into_diagnostic()?
        .map_err(|e| miette::miette!("{e}"))?;
        let path_display = config_path.display();
        println!("added {daemon_id} to {path_display}");
        Ok(())
    }

    fn parse_retry(s: &str) -> Result<Retry> {
        if s.eq_ignore_ascii_case("true") {
            Ok(Retry::INFINITE)
        } else if s.eq_ignore_ascii_case("false") {
            Ok(Retry(0))
        } else {
            match s.parse::<u32>() {
                Ok(n) => Ok(Retry(n)),
                Err(_) => {
                    bail!(
                        "Invalid retry value: {}. Expected a number or 'true'/'false'",
                        s
                    );
                }
            }
        }
    }

    fn parse_cron_retrigger(s: &str) -> Result<CronRetrigger> {
        match s.to_lowercase().as_str() {
            "finish" => Ok(CronRetrigger::Finish),
            "always" => Ok(CronRetrigger::Always),
            "success" => Ok(CronRetrigger::Success),
            "fail" => Ok(CronRetrigger::Fail),
            _ => {
                bail!(
                    "Invalid cron retrigger value: {}. Expected 'finish', 'always', 'success', or 'fail'",
                    s
                );
            }
        }
    }
}

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

    #[test]
    fn test_parse_retry_numeric() {
        assert_eq!(Add::parse_retry("0").unwrap().count(), 0);
        assert_eq!(Add::parse_retry("3").unwrap().count(), 3);
        assert_eq!(Add::parse_retry("10").unwrap().count(), 10);
    }

    #[test]
    fn test_parse_retry_boolean() {
        assert!(Add::parse_retry("true").unwrap().is_infinite());
        assert!(Add::parse_retry("TRUE").unwrap().is_infinite());
        assert!(Add::parse_retry("True").unwrap().is_infinite());
        assert_eq!(Add::parse_retry("false").unwrap().count(), 0);
        assert_eq!(Add::parse_retry("FALSE").unwrap().count(), 0);
    }

    #[test]
    fn test_parse_retry_invalid() {
        assert!(Add::parse_retry("invalid").is_err());
        assert!(Add::parse_retry("").is_err());
    }

    #[test]
    fn test_parse_cron_retrigger_valid() {
        assert_eq!(
            Add::parse_cron_retrigger("finish").unwrap(),
            CronRetrigger::Finish
        );
        assert_eq!(
            Add::parse_cron_retrigger("FINISH").unwrap(),
            CronRetrigger::Finish
        );
        assert_eq!(
            Add::parse_cron_retrigger("always").unwrap(),
            CronRetrigger::Always
        );
        assert_eq!(
            Add::parse_cron_retrigger("success").unwrap(),
            CronRetrigger::Success
        );
        assert_eq!(
            Add::parse_cron_retrigger("fail").unwrap(),
            CronRetrigger::Fail
        );
    }

    #[test]
    fn test_parse_cron_retrigger_invalid() {
        assert!(Add::parse_cron_retrigger("invalid").is_err());
        assert!(Add::parse_cron_retrigger("").is_err());
        assert!(Add::parse_cron_retrigger("never").is_err());
    }
}