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
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
use crate::{
Config, Proc, ProcStatus, Prox, ProxEvent, ProxSignal, debug, error, info,
logging::{self, DEFAULT_PROX_PREFIX, Level},
warn,
};
use anyhow::{Context, Result};
use dashmap::DashMap;
use notify::{RecursiveMode, Watcher, recommended_watcher};
use std::{
collections::HashMap,
path::{Path, PathBuf},
process::{Child, Command},
sync::{
Arc,
atomic::{AtomicBool, Ordering},
mpsc,
},
thread::{sleep, spawn},
time::{Duration, Instant},
};
impl Prox {
/// Get a reference to the configuration
pub fn config(&self) -> &Config {
&self.config
}
/// Get a reference to the processes
pub fn procs(&self) -> &[Proc] {
&self.procs
}
/// Set up a [`ProxEvent`] receiver channel and return the receiver.
/// Can be run only once. Returns error if run again.
pub fn setup_event_rx(&mut self) -> Result<mpsc::Receiver<ProxEvent>> {
if self.event_tx.is_some() {
return Err(anyhow::anyhow!("event channel is already set up"));
}
let (tx, rx) = mpsc::channel();
self.event_tx = Some(tx);
Ok(rx)
}
/// Start all processes
pub fn start(&mut self) -> Result<()> {
// Initialize logging
logging::init_logging(logging::LogConfig {
prox_prefix: DEFAULT_PROX_PREFIX.to_string(),
prefix_width: self.config.prefix_width,
timestamp: self.config.show_timestamps,
level: Level::from_env(),
});
// TODO: debounce these to public ProxEvent::Idle
// use self.config.output_idle_debounce_ms
let (proc_output_tx, proc_output_rx) = mpsc::channel::<()>();
let (restart_tx, restart_rx) = mpsc::channel::<String>();
// Set up idle detection if enabled
if self.config.output_idle_debounce_ms > 0 {
let idle_debounce_duration = Duration::from_millis(self.config.output_idle_debounce_ms);
let event_tx = self.event_tx.clone();
let running = self.running.clone();
spawn(move || {
let mut idle_sent = false;
loop {
if !running.load(Ordering::SeqCst) {
break;
}
match proc_output_rx.recv_timeout(idle_debounce_duration) {
Ok(()) => {
// Received output, reset idle state
idle_sent = false;
}
Err(mpsc::RecvTimeoutError::Timeout) => {
// Timeout reached, send idle event if not already sent
if !idle_sent {
if let Some(ref event_tx) = event_tx {
event_tx.send(ProxEvent::Idle).ok();
}
idle_sent = true;
}
}
Err(mpsc::RecvTimeoutError::Disconnected) => {
// Channel disconnected, exit
break;
}
}
}
});
}
self.running.store(true, Ordering::SeqCst);
let keep_going = self.config.keep_going;
self.assign_missing_colors();
if let Some(rx) = self.signal_rx.take() {
let running = self.running.clone();
let child_refs = self.child_refs.clone();
let restart_tx = restart_tx.clone();
let procs = self.procs.clone();
spawn(move || {
for signal in rx {
match signal {
ProxSignal::Start => {
// restart any processes that are not currently running
let mut start_count = 0;
for proc in &procs {
if let Some(mut child) = child_refs.get_mut(&proc.name) {
if child.try_wait().is_ok_and(|s| s.is_none()) {
continue;
}
}
start_count += 1;
restart_tx.send(proc.name.clone()).ok();
}
if start_count == 0 {
info!("All processes are already running");
}
}
ProxSignal::Restart => {
error!("RECEIVED RESTART SIGNAL");
// restart all processes
for proc in &procs {
restart_tx.send(proc.name.clone()).ok();
}
}
ProxSignal::Shutdown => {
running.store(false, Ordering::SeqCst);
return;
}
}
}
});
}
// Set up Control-C handler
if self.config.handle_control_c {
let running = self.running.clone();
let event_tx = self.event_tx.clone();
if let Err(err) = ctrlc::try_set_handler(move || {
running.store(false, Ordering::SeqCst);
if let Some(event_tx) = &event_tx {
event_tx.send(ProxEvent::SigIntReceived).ok();
}
}) {
warn!("Failed to set Control-C handler (is one already set?): {err}");
}
}
// Start all processes
let (failure_tx, failure_rx) = mpsc::channel();
for proc in &self.procs {
if let Err(err) =
self.start_process(proc.clone(), failure_tx.clone(), proc_output_tx.clone())
{
if !keep_going {
eprintln!("Failed to start process {}: {err}", proc.name);
self.shutdown();
return Err(err);
}
}
}
// Set up file watchers
if let Err(err) = self.setup_file_watchers(failure_tx.clone(), proc_output_tx.clone()) {
eprintln!("Failed to set up file watchers: {err}");
self.shutdown();
return Err(err);
}
// Main loop
while self.running.load(Ordering::SeqCst) {
// Check for restart requests
if let Ok(proc_name) = restart_rx.try_recv()
&& let Some(proc) = self.procs.iter().find(|p| p.name == proc_name)
&& let Err(err) =
self.start_process(proc.clone(), failure_tx.clone(), proc_output_tx.clone())
{
eprintln!("Failed to restart process {}: {err}", proc.name);
if !keep_going {
self.running.store(false, Ordering::SeqCst);
}
break;
}
// Check for failures
if let Ok(failure_msg) = failure_rx.try_recv() {
if !keep_going {
eprintln!("Process failure: {failure_msg}");
self.running.store(false, Ordering::SeqCst);
break;
}
}
// Check if any processes have exited
let mut any_exited = false;
let mut dead_processes = Vec::new();
for mut entry in self.child_refs.iter_mut() {
let name = entry.key().clone();
let child = entry.value_mut();
match child.try_wait() {
Ok(Some(status)) => {
println!("{name} exited with status: {status:?}");
if let Some(event_tx) = &self.event_tx {
event_tx
.send(ProxEvent::Exited {
proc_name: name.clone(),
status,
})
.ok();
}
if !keep_going {
self.running.store(false, Ordering::SeqCst);
any_exited = true;
break;
} else {
println!("{name} will restart when watched files change");
dead_processes.push(name);
}
}
Ok(None) => {}
Err(e) => {
println!("Failed to wait on process {name}: {e}");
if !keep_going {
self.running.store(false, Ordering::SeqCst);
any_exited = true;
break;
} else {
println!("{name} will restart when watched files change");
dead_processes.push(name);
}
}
}
}
// Remove dead processes from child_refs when keep_going is true
// Do this carefully to avoid interfering with restart logic
for dead_process in dead_processes {
// Only remove if not currently starting (to avoid race with restart)
if !self.starting.contains_key(&dead_process) {
self.child_refs.remove(&dead_process);
}
}
if any_exited {
break;
}
// Sleep briefly
sleep(Duration::from_millis(100));
}
error!("SHUTDOWN NOW");
// Shutdown
self.shutdown();
Ok(())
}
fn assign_missing_colors(&mut self) {
// Assign colors to processes that don't have one
let colors = &self.config.colors;
for (i, proc) in self.procs.iter_mut().enumerate() {
proc.color.get_or_insert_with(|| colors[i % colors.len()]);
}
}
fn start_process(
&self,
proc: Proc,
failure_tx: mpsc::Sender<String>,
proc_output_tx: mpsc::Sender<()>,
) -> Result<()> {
let child_refs = self.child_refs.clone();
let starting = self.starting.clone();
let running = self.running.clone();
let fallback_timeout = self.config.readiness_fallback_timeout;
let process_group_id = self.process_group_id.clone();
let config = self.config.clone();
let procs = self.procs.clone();
let event_tx = self.event_tx.clone();
let status_refs = self.status_refs.clone();
spawn(move || {
starting.insert(proc.name.clone(), Instant::now());
// Remove any existing process
if let Some((_, mut old_child)) = child_refs.remove(&proc.name) {
old_child.kill().ok();
old_child.wait().ok();
}
status_refs.insert(proc.name.clone(), ProcStatus::Starting);
match proc.start_service(&process_group_id, &config, Some(proc_output_tx.clone())) {
Ok((new_child, readiness_rx)) => {
child_refs.insert(proc.name.clone(), new_child);
info!("{} Service started, waiting for readiness...", proc.name);
if proc.readiness_pattern.is_some() {
// Wait for readiness pattern (forever, until process crashes)
loop {
match readiness_rx.try_recv() {
Ok(()) => {
status_refs.insert(proc.name.clone(), ProcStatus::Running);
info!(
"{} detected readiness pattern, start complete",
proc.name
);
if let Some(event_tx) = &event_tx {
event_tx
.send(ProxEvent::Started {
proc_name: proc.name.clone(),
})
.ok();
}
break;
}
Err(mpsc::TryRecvError::Empty) => {
if !running.load(Ordering::SeqCst) {
break;
}
sleep(Duration::from_millis(100));
continue;
}
Err(mpsc::TryRecvError::Disconnected) => {
// Process died, will be detected by crash detection
break;
}
}
}
} else {
// No readiness pattern - wait fallback timeout then assume ready
let start_time = Instant::now();
while start_time.elapsed() < fallback_timeout
&& running.load(Ordering::SeqCst)
{
// Check if process is still alive
if let Some(mut child_entry) = child_refs.get_mut(&proc.name) {
match child_entry.try_wait() {
Ok(Some(status)) => {
// Process exited, will be detected by crash detection
status_refs
.insert(proc.name.clone(), ProcStatus::Exited(status));
break;
}
Ok(None) => {
// Still running, continue waiting
}
Err(err) => {
// Error checking status, assume dead
status_refs.insert(
proc.name.clone(),
ProcStatus::Error(err.to_string()),
);
break;
}
}
}
sleep(Duration::from_millis(100));
}
info!("{} assumed running after fallback timeout", proc.name);
status_refs.insert(proc.name.clone(), ProcStatus::Running);
if let Some(event_tx) = &event_tx {
event_tx
.send(ProxEvent::Started {
proc_name: proc.name.clone(),
})
.ok();
}
}
starting.remove(&proc.name);
if starting.is_empty() {
let exited_procs = exited_procs(&procs, &child_refs);
if exited_procs.is_empty() {
info!("All processes started successfully!");
if let Some(event_tx) = &event_tx {
event_tx.send(ProxEvent::AllStarted).ok();
}
} else {
info!("Procs exited! {exited_procs:?}");
if let Some(event_tx) = &event_tx {
event_tx.send(ProxEvent::SomeFailed { exited_procs }).ok();
}
}
} else {
debug!(
"starting.is_empty(): {}, child_refs.len(): {}, total_procs: {}",
starting.is_empty(),
child_refs.len(),
procs.len()
);
}
}
Err(e) => {
let error_msg = format!("Failed to start {}: {e}", proc.name);
status_refs.insert(proc.name.clone(), ProcStatus::Error(error_msg.clone()));
if let Some(event_tx) = &event_tx {
event_tx
.send(ProxEvent::StartFailed {
proc_name: proc.name.clone(),
message: error_msg.clone(),
})
.ok();
}
error!("{error_msg}");
failure_tx.send(error_msg).ok();
starting.remove(&proc.name);
running.store(false, Ordering::SeqCst);
}
}
});
Ok(())
}
fn setup_file_watchers(
&self,
failure_tx: mpsc::Sender<String>,
proc_output_tx: mpsc::Sender<()>,
) -> Result<()> {
let mut watch_path_procs: HashMap<PathBuf, Vec<Proc>> = HashMap::new();
// Build path -> process mapping
for proc in &self.procs {
for path in proc.watch_abs(&self.config)? {
watch_path_procs.entry(path).or_default().push(proc.clone());
}
}
if watch_path_procs.is_empty() {
return Ok(());
}
// Start file watcher
let running = self.running.clone();
let child_refs = self.child_refs.clone();
let starting = self.starting.clone();
let fallback_timeout = self.config.readiness_fallback_timeout;
let process_group_id = self.process_group_id.clone();
let config = self.config.clone();
let procs = self.procs.clone();
let event_tx = self.event_tx.clone();
let proc_output_tx_clone = proc_output_tx.clone();
spawn(move || {
let (tx, rx) = mpsc::channel();
let mut watcher = match recommended_watcher(tx) {
Ok(w) => w,
Err(e) => {
eprintln!("Failed to create file watcher: {e}");
return;
}
};
for path in watch_path_procs.keys() {
println!("[GLOBAL] Watching: {}", path.display());
if let Err(e) = watcher.watch(path, RecursiveMode::Recursive) {
eprintln!("Failed to watch path {}: {e}", path.display());
}
}
while running.load(Ordering::SeqCst) {
match rx.recv() {
Ok(Ok(event)) => {
let mut procs_to_restart = HashMap::new();
for event_path in &event.paths {
for (watched_path, procs) in &watch_path_procs {
if !event_path.starts_with(watched_path) {
// println!("SKIP WATCH PATH: {}", event_path.display());
continue;
}
println!("RESTART FOR WATCH PATH: {}", event_path.display());
for proc in procs {
println!(
"restart? {}, starting? {}",
proc.name,
starting.contains_key(&proc.name)
);
if !starting.contains_key(&proc.name) {
println!("RESTART PROC: {}", proc.name);
procs_to_restart.insert(proc.name.clone(), proc.clone());
}
}
}
}
for (_, proc) in procs_to_restart {
let child_refs = child_refs.clone();
let starting = starting.clone();
starting.insert(proc.name.clone(), Instant::now());
let running = running.clone();
let failure_tx = failure_tx.clone();
let process_group_id = process_group_id.clone();
let config = config.clone();
let procs = procs.clone();
let event_tx = event_tx.clone();
let proc_output_tx = proc_output_tx_clone.clone();
spawn(move || {
// Small delay to avoid race conditions with process cleanup
sleep(Duration::from_millis(100));
// Remove existing process
if let Some((_, mut old_child)) = child_refs.remove(&proc.name) {
old_child.kill().ok();
old_child.wait().ok();
}
match proc.start_service(
&process_group_id,
&config,
Some(proc_output_tx.clone()),
) {
Ok((new_child, readiness_rx)) => {
child_refs.insert(proc.name.clone(), new_child);
if proc.readiness_pattern.is_some() {
// Wait for readiness pattern (forever, until process crashes)
loop {
match readiness_rx.try_recv() {
Ok(()) => {
println!(
"[GLOBAL] {} restart complete",
proc.name
);
if let Some(event_tx) = &event_tx {
event_tx
.send(ProxEvent::Restarted {
proc_name: proc.name.clone(),
})
.ok();
}
break;
}
Err(mpsc::TryRecvError::Empty) => {
if !running.load(Ordering::SeqCst) {
break;
}
sleep(Duration::from_millis(10));
continue;
}
Err(mpsc::TryRecvError::Disconnected) => {
// Process died, will be detected by crash detection
break;
}
}
}
} else {
// No readiness pattern - wait fallback timeout then assume ready
let start_time = Instant::now();
while start_time.elapsed() < fallback_timeout
&& running.load(Ordering::SeqCst)
{
// Check if process is still alive
if let Some(mut child_entry) =
child_refs.get_mut(&proc.name)
{
match child_entry.try_wait() {
Ok(Some(_)) => {
// Process exited, will be detected by crash detection
break;
}
Ok(None) => {
// Still running, continue waiting
}
Err(_) => {
// Error checking status, assume dead
break;
}
}
}
sleep(Duration::from_millis(100));
}
// If we get here and process is still alive, assume ready
println!(
"[GLOBAL] {} restart assumed ready after fallback timeout",
proc.name
);
}
starting.remove(&proc.name);
if starting.is_empty() {
let exited_procs = exited_procs(&procs, &child_refs);
if exited_procs.is_empty() {
println!(
"[GLOBAL] All processes restarted successfully!"
);
} else {
println!("[GLOBAL] Procs exited! {exited_procs:?}");
}
}
}
Err(e) => {
let error_msg =
format!("Failed to restart {}: {e}", proc.name);
eprintln!("{error_msg}");
failure_tx.send(error_msg).ok();
starting.remove(&proc.name);
}
}
});
}
}
Ok(Err(e)) => {
eprintln!("[GLOBAL] Watch error: {e}");
}
Err(_) => {
eprintln!("[GLOBAL] File watcher channel disconnected");
break;
}
}
}
});
Ok(())
}
fn shutdown(&self) {
static SHUTDOWN_CALLED: AtomicBool = AtomicBool::new(false);
if SHUTDOWN_CALLED.swap(true, Ordering::SeqCst) {
println!("Shutdown already called!");
return;
}
self.running.store(false, Ordering::SeqCst);
// Stop individual processes
for proc in self.procs.iter().rev() {
if let Some((_, mut child)) = self.child_refs.remove(&proc.name) {
println!("Shutting down process: {}", proc.name);
child.kill().ok();
child.wait().ok();
}
proc.cleanup();
self.starting.remove(&proc.name);
println!("{} stopped and cleaned up.", proc.name);
}
// Kill process group as fallback
let gid = self
.process_group_id
.lock()
.expect("failed to lock process group ID");
if *gid > 0 {
println!("Killing process group {}", *gid);
Command::new("kill")
.args(["-KILL", &format!("-{}", *gid)])
.output()
.ok();
}
println!("Prox shutting down.");
}
/// Load configuration from TOML file
pub fn load_toml<P: AsRef<Path>>(path: P) -> anyhow::Result<Prox> {
let content = std::fs::read_to_string(path.as_ref())
.with_context(|| format!("Failed to read TOML file: {}", path.as_ref().display()))?;
let prox: Prox = toml::from_str(&content)
.with_context(|| format!("Failed to parse TOML config: {}", path.as_ref().display()))?;
Ok(prox)
}
/// Load configuration from YAML file
pub fn load_yaml<P: AsRef<Path>>(path: P) -> anyhow::Result<Prox> {
let content = std::fs::read_to_string(path.as_ref())
.with_context(|| format!("Failed to read YAML file: {}", path.as_ref().display()))?;
let prox: Prox = serde_yml::from_str(&content)
.with_context(|| format!("Failed to parse YAML config: {}", path.as_ref().display()))?;
Ok(prox)
}
/// Load configuration from JSON file
pub fn load_json<P: AsRef<Path>>(path: P) -> anyhow::Result<Prox> {
let content = std::fs::read_to_string(path.as_ref())
.with_context(|| format!("Failed to read JSON file: {}", path.as_ref().display()))?;
let prox: Prox = serde_json::from_str(&content)
.with_context(|| format!("Failed to parse JSON config: {}", path.as_ref().display()))?;
Ok(prox)
}
}
fn exited_procs(procs: &[Proc], child_refs: &Arc<DashMap<String, Child>>) -> Vec<String> {
let mut exited = vec![];
for proc in procs {
let Some(mut child_entry) = child_refs.get_mut(&proc.name) else {
exited.push(proc.name.clone());
continue;
};
match child_entry.try_wait() {
Ok(Some(_)) => {
exited.push(child_entry.key().clone());
}
Ok(None) => {
// Still running
}
Err(_) => {
exited.push(child_entry.key().clone());
}
}
}
exited
}