eggress-embed 1.0.4

Stable Rust embed API for eggress proxy
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
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
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
//! # eggress-embed
//!
//! Stable Rust embed API for starting and controlling an eggress proxy in-process.
//!
//! This crate wraps the internal runtime, config, and server infrastructure behind
//! a minimal, binding-friendly surface. Python bindings (PyO3) in later phases will
//! wrap this API.
//!
//! ## Quick start (blocking)
//!
//! ```no_run
//! use eggress_embed::{EggressService, EggressConfig};
//!
//! let config = EggressConfig::from_toml_str(r#"
//!     version = 1
//!     [[listeners]]
//!     name = "socks"
//!     bind = "127.0.0.1:0"
//!     protocols = ["socks5"]
//! "#).unwrap();
//!
//! let handle = EggressService::new(config).start_blocking().unwrap();
//! let addrs = handle.bound_addresses();
//! println!("listening on {:?}", addrs);
//! handle.shutdown_blocking().unwrap();
//! ```
//!
//! ## Quick start (async)
//!
//! ```no_run
//! # tokio_test::block_on(async {
//! use eggress_embed::{EggressService, EggressConfig};
//!
//! let config = EggressConfig::from_toml_str(r#"
//!     version = 1
//!     [[listeners]]
//!     name = "http"
//!     bind = "127.0.0.1:0"
//!     protocols = ["http"]
//! "#).unwrap();
//!
//! let handle = EggressService::new(config).start().await.unwrap();
//! let status = handle.status();
//! println!("generation: {}", status.generation);
//! handle.shutdown().await.unwrap();
//! # });
//! ```

mod error;
pub mod outbound;

use std::net::{IpAddr, Ipv4Addr, SocketAddr};
use std::path::Path;
use std::sync::atomic::Ordering;
use std::sync::Arc;
use std::time::Duration;

pub use error::EggressError;

/// Parsed and validated eggress configuration.
///
/// Construct via [`EggressConfig::from_toml_str`] or [`EggressConfig::from_toml_file`].
#[derive(Clone)]
pub struct EggressConfig {
    source_toml: String,
}

impl EggressConfig {
    /// Parse a TOML configuration string.
    pub fn from_toml_str(input: &str) -> Result<Self, EggressError> {
        let config: eggress_config::model::ConfigFile =
            toml::from_str(input).map_err(|e| EggressError::Config(e.to_string()))?;

        if let Some(version) = config.version {
            if version != 1 {
                return Err(EggressError::Config(format!(
                    "unsupported config version: {version}"
                )));
            }
        }

        eggress_config::validate::validate_config(&config).map_err(|errors| {
            let messages: Vec<String> = errors.iter().map(|e| e.to_string()).collect();
            EggressError::Config(messages.join("; "))
        })?;

        let _inner = eggress_config::compile::compile_config(&config)
            .map_err(|e| EggressError::Config(e.to_string()))?;

        Ok(Self {
            source_toml: input.to_string(),
        })
    }

    /// Load and validate a TOML configuration file.
    pub fn from_toml_file(path: impl AsRef<Path>) -> Result<Self, EggressError> {
        let path = path.as_ref();
        let contents = std::fs::read_to_string(path)
            .map_err(|e| EggressError::Config(format!("failed to read {path:?}: {e}")))?;
        Self::from_toml_str(&contents)
    }

    /// Return the original TOML source text.
    pub fn source_toml(&self) -> &str {
        &self.source_toml
    }

    /// Return the TOML source with credentials redacted.
    ///
    /// Listener auth passwords and upstream URI credentials are replaced with
    /// `****` / `****:****@` placeholders. The result is suitable for logging
    /// or display without leaking secrets.
    pub fn to_redacted_toml(&self) -> Result<String, EggressError> {
        let mut value: toml::Value =
            toml::from_str(&self.source_toml).map_err(|e| EggressError::Config(e.to_string()))?;

        redact_toml_value(&mut value);

        toml::to_string_pretty(&value).map_err(|e| EggressError::Internal(e.to_string()))
    }
}

/// Pre-start service builder.
///
/// Created from a validated config. Call [`.start()`](EggressService::start) (async) or
/// [`.start_blocking()`](EggressService::start_blocking) to launch the proxy and obtain a handle.
pub struct EggressService {
    config: EggressConfig,
}

impl EggressService {
    /// Create a new service from a validated config.
    pub fn new(config: EggressConfig) -> Self {
        Self { config }
    }

    /// Convenience: parse TOML and create a service.
    pub fn from_toml_str(input: &str) -> Result<Self, EggressError> {
        EggressConfig::from_toml_str(input).map(Self::new)
    }

    /// Convenience: load file and create a service.
    pub fn from_toml_file(path: impl AsRef<Path>) -> Result<Self, EggressError> {
        EggressConfig::from_toml_file(path).map(Self::new)
    }

    /// Start the service using a caller-provided Tokio runtime context.
    ///
    /// The caller must be inside a Tokio runtime. The service binds listeners,
    /// starts health probes, and enters the event loop on a background task.
    /// Returns once readiness is achieved or startup fails.
    pub async fn start(self) -> Result<EggressHandle, EggressError> {
        let (ready_tx, ready_rx) = tokio::sync::oneshot::channel();
        let config_path = write_temp_config(&self.config)?;
        let config_path_clone = config_path.clone();

        let join = tokio::task::spawn_blocking(move || -> Result<
            (
                Arc<eggress_runtime::RuntimeState>,
                tokio_util::sync::CancellationToken,
            ),
            EggressError,
        > {
            let mut sup = match eggress_runtime::ServiceSupervisor::start(&config_path_clone) {
                Ok(sup) => sup,
                Err(error) => {
                    let _ = std::fs::remove_file(&config_path_clone);
                    return Err(EggressError::Startup(error.to_string()));
                }
            };

            let state = sup.state().clone();
            let token = sup.shutdown_token();

            let run_result = std::thread::Builder::new()
                .name("eggress-embed-rt".into())
                .spawn(move || sup.run())
                .map_err(|error| {
                    let _ = std::fs::remove_file(&config_path_clone);
                    EggressError::Startup(error.to_string())
                })?;

            // Wait for readiness or failure
            let started = std::time::Instant::now();
            let timeout = Duration::from_secs(30);
            loop {
                if state.readiness.load(Ordering::Acquire) {
                    let _ = ready_tx.send(Ok((state.clone(), token.clone())));
                    break;
                }
                if started.elapsed() > timeout {
                    token.cancel();
                    let _ = std::fs::remove_file(&config_path_clone);
                    let _ = ready_tx.send(Err(EggressError::Startup(
                        "readiness timeout".to_string(),
                    )));
                    break;
                }
                std::thread::sleep(Duration::from_millis(5));
            }

            // Wait for the run thread to finish (shutdown)
            match run_result.join() {
                Ok(Ok(())) => {}
                Ok(Err(e)) => tracing::debug!(%e, "runtime exited with error"),
                Err(_) => tracing::debug!("runtime thread panicked"),
            }

            // Clean up temp config file
            let _ = std::fs::remove_file(&config_path_clone);

            Ok((state, token))
        });

        let (state, token) = ready_rx
            .await
            .map_err(|_| EggressError::Startup("startup channel dropped".into()))??;

        let join = tokio::task::spawn(async move {
            match join.await {
                Ok(Ok(_)) => Ok(()),
                Ok(Err(e)) => Err(EggressError::Startup(format!("startup failed: {e}"))),
                Err(e) => Err(EggressError::Startup(format!("startup task panicked: {e}"))),
            }
        });

        Ok(EggressHandle {
            state,
            token: Some(token),
            _run_handle: None,
            _config_path: Some(config_path),
            _runtime_task: Some(join),
            reload_mutex: std::sync::Mutex::new(()),
        })
    }

    /// Start the service with a dedicated runtime thread (blocking).
    ///
    /// This spawns a background thread that creates a Tokio runtime and runs
    /// the proxy. Blocks until readiness is achieved or startup fails.
    /// Returns a handle that owns the runtime thread.
    pub fn start_blocking(self) -> Result<EggressHandle, EggressError> {
        let (ready_tx, ready_rx) = std::sync::mpsc::sync_channel(1);
        let config_path = write_temp_config(&self.config)?;
        let config_path_clone = config_path.clone();

        let _thread_handle = std::thread::Builder::new()
            .name("eggress-embed-rt".into())
            .spawn(move || {
                let mut sup = match eggress_runtime::ServiceSupervisor::start(&config_path_clone) {
                    Ok(s) => s,
                    Err(e) => {
                        let _ = std::fs::remove_file(&config_path_clone);
                        let _ = ready_tx.send(Err(EggressError::Startup(e.to_string())));
                        return;
                    }
                };

                let state = sup.state().clone();
                let token = sup.shutdown_token();

                let run_handle = std::thread::Builder::new()
                    .name("eggress-embed-run".into())
                    .spawn(move || {
                        if let Err(e) = sup.run() {
                            tracing::error!("supervisor exited with error: {e}");
                        }
                    });

                let run_handle = match run_handle {
                    Ok(h) => h,
                    Err(e) => {
                        let _ = std::fs::remove_file(&config_path_clone);
                        let _ = ready_tx.send(Err(EggressError::Startup(e.to_string())));
                        return;
                    }
                };

                // Wait for readiness
                let started = std::time::Instant::now();
                let timeout = Duration::from_secs(30);
                loop {
                    if state.readiness.load(Ordering::Acquire) {
                        let _ = ready_tx.send(Ok((state, token, run_handle, config_path_clone)));
                        break;
                    }
                    if started.elapsed() > timeout {
                        // On timeout, cancel and clean up immediately
                        token.cancel();
                        let _ = std::fs::remove_file(&config_path_clone);
                        match run_handle.join() {
                            Ok(()) => {}
                            Err(_) => tracing::debug!("runtime thread panicked"),
                        }
                        let _ =
                            ready_tx.send(Err(EggressError::Startup("readiness timeout".into())));
                        break;
                    }
                    std::thread::sleep(Duration::from_millis(5));
                }
            })
            .map_err(|e| {
                let _ = std::fs::remove_file(&config_path);
                EggressError::Startup(e.to_string())
            })?;

        let (state, token, run_handle, config_path) = ready_rx
            .recv()
            .map_err(|_| EggressError::Startup("startup channel dropped".into()))??;

        Ok(EggressHandle {
            state,
            token: Some(token),
            _run_handle: Some(run_handle),
            _config_path: Some(config_path),
            _runtime_task: None,
            reload_mutex: std::sync::Mutex::new(()),
        })
    }

    /// Start a compatibility service from the validated in-memory config.
    ///
    /// This variant is used by the Python `pproxy` entry point so compatibility
    /// options such as `--auth`, `--sys`, `-d`, and `-v` reach the runtime
    /// without going through a temporary config file or the native defaults.
    #[cfg(feature = "pproxy-compat")]
    pub fn start_blocking_with_compatibility_options(
        self,
        compatibility_options: eggress_runtime::CompatibilityOptions,
    ) -> Result<EggressHandle, EggressError> {
        let (ready_tx, ready_rx) = std::sync::mpsc::sync_channel(1);
        let source_toml = self.config.source_toml.clone();
        let rt_config = eggress_config::validate_and_compile_toml_with_warnings(&source_toml)
            .map(|(config, _)| config)
            .map_err(|e| EggressError::Config(e.to_string()))?;

        std::thread::Builder::new()
            .name("eggress-embed-rt".into())
            .spawn(move || {
                let mut supervisor =
                    match eggress_runtime::ServiceSupervisor::start_from_config_with_options(
                        rt_config,
                        None,
                        compatibility_options,
                    ) {
                        Ok(supervisor) => supervisor,
                        Err(error) => {
                            let _ = ready_tx.send(Err(EggressError::Startup(error.to_string())));
                            return;
                        }
                    };

                let state = supervisor.state().clone();
                let token = supervisor.shutdown_token();
                let run_handle = std::thread::Builder::new()
                    .name("eggress-embed-run".into())
                    .spawn(move || {
                        if let Err(error) = supervisor.run() {
                            tracing::error!("supervisor exited with error: {error}");
                        }
                    });

                let run_handle = match run_handle {
                    Ok(handle) => handle,
                    Err(error) => {
                        let _ = ready_tx.send(Err(EggressError::Startup(error.to_string())));
                        return;
                    }
                };

                let started = std::time::Instant::now();
                let timeout = Duration::from_secs(30);
                loop {
                    if state.readiness.load(Ordering::Acquire) {
                        let _ = ready_tx.send(Ok((state, token, run_handle)));
                        break;
                    }
                    if started.elapsed() > timeout {
                        token.cancel();
                        let _ = run_handle.join();
                        let _ =
                            ready_tx.send(Err(EggressError::Startup("readiness timeout".into())));
                        break;
                    }
                    std::thread::sleep(Duration::from_millis(5));
                }
            })
            .map_err(|e| EggressError::Startup(e.to_string()))?;

        let (state, token, run_handle) = ready_rx
            .recv()
            .map_err(|_| EggressError::Startup("startup channel dropped".into()))??;

        Ok(EggressHandle {
            state,
            token: Some(token),
            _run_handle: Some(run_handle),
            _config_path: None,
            _runtime_task: None,
            reload_mutex: std::sync::Mutex::new(()),
        })
    }
}

/// Handle to a running eggress service.
///
/// Provides access to bound addresses, status, metrics, reload, and shutdown.
/// Dropping the handle cancels the shutdown token, initiating graceful shutdown.
///
/// # Thread ownership
///
/// The handle owns exactly one of two mutually exclusive thread models:
///
/// **Async path** (`start()`):
/// - A Tokio blocking-pool thread runs the startup sequence and then blocks on
///   `run_result.join()` for the lifetime of the service.
/// - A dedicated OS thread (`"eggress-embed-rt"`) owns `ServiceSupervisor::run()`.
/// - `_runtime_task` wraps the blocking task's JoinHandle as a Tokio task.
///
/// **Blocking path** (`start_blocking()`):
/// - An outer OS thread (`"eggress-embed-rt"`) handles startup, sends results
///   through a channel, and terminates.
/// - An inner OS thread (`"eggress-embed-run"`) owns `ServiceSupervisor::run()`.
/// - `_run_handle` holds the inner thread's JoinHandle directly.
///
/// # Drop behavior
///
/// Dropping the handle cancels the shutdown token and performs a best-effort
/// join: the blocking path joins the run thread directly; the async path
/// creates a throwaway Tokio runtime and awaits the task with a 5-second
/// timeout. Explicit `shutdown()` or `shutdown_blocking()` is preferred to
/// guarantee orderly teardown.
pub struct EggressHandle {
    state: Arc<eggress_runtime::RuntimeState>,
    token: Option<tokio_util::sync::CancellationToken>,
    _run_handle: Option<std::thread::JoinHandle<()>>,
    _config_path: Option<String>,
    _runtime_task: Option<tokio::task::JoinHandle<Result<(), EggressError>>>,
    reload_mutex: std::sync::Mutex<()>,
}

impl EggressHandle {
    /// Get the addresses the service is listening on.
    pub fn bound_addresses(&self) -> BoundAddresses {
        let addrs = self
            .state
            .listener_addrs
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let admin = self
            .state
            .admin_local_addr
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let snap = self.state.snapshot.load();
        let listeners: Vec<ListenerAddress> = snap
            .listeners
            .iter()
            .enumerate()
            .map(|(idx, lcfg)| ListenerAddress {
                name: lcfg.name.clone(),
                addr: listener_addr_or_configured(&addrs, idx, &lcfg.bind),
            })
            .collect();
        BoundAddresses {
            listeners,
            admin: *admin,
        }
    }

    /// Get the current service status.
    pub fn status(&self) -> ServiceStatus {
        let snap = self.state.snapshot.load();
        let addrs = self
            .state
            .listener_addrs
            .lock()
            .unwrap_or_else(|e| e.into_inner());

        let listeners: Vec<ListenerStatus> = snap
            .listeners
            .iter()
            .enumerate()
            .map(|(idx, lcfg)| ListenerStatus {
                name: lcfg.name.clone(),
                bind: lcfg.bind.clone(),
                local_addr: listener_addr_or_configured(&addrs, idx, &lcfg.bind),
                protocols: lcfg.protocols.iter().map(|p| format!("{p}")).collect(),
                udp_enabled: lcfg.udp.as_ref().is_some_and(|u| u.enabled),
            })
            .collect();

        let udp_active = self
            .state
            .udp_metrics
            .associations_active
            .load(Ordering::Relaxed);

        ServiceStatus {
            generation: snap.generation,
            readiness: self.state.readiness.load(Ordering::Relaxed),
            active_connections: self.state.active_connections.load(Ordering::Relaxed),
            uptime_secs: self.state.start_time.elapsed().as_secs(),
            listener_count: snap.listeners.len(),
            listeners,
            udp_associations_active: udp_active,
            upstream_count: snap.upstreams.len(),
        }
    }

    /// Render Prometheus metrics text.
    pub fn metrics_text(&self) -> Result<String, EggressError> {
        Ok(self.state.metrics.render_prometheus())
    }

    /// Reload configuration from a TOML string.
    ///
    /// Returns the outcome of the reload attempt. On success, the generation
    /// is incremented. On rejection, the old configuration remains active.
    pub fn reload_toml_str(&self, input: &str) -> Result<ReloadOutcome, EggressError> {
        let _guard = self
            .reload_mutex
            .lock()
            .map_err(|_| EggressError::Reload("concurrent reload in progress".to_string()))?;

        // Parse and validate the new config
        let config: eggress_config::model::ConfigFile =
            toml::from_str(input).map_err(|e| EggressError::Reload(e.to_string()))?;

        if let Some(version) = config.version {
            if version != 1 {
                return Err(EggressError::Reload(format!(
                    "unsupported config version: {version}"
                )));
            }
        }

        eggress_config::validate::validate_config(&config).map_err(|errors| {
            let messages: Vec<String> = errors.iter().map(|e| e.to_string()).collect();
            EggressError::Reload(messages.join("; "))
        })?;

        let new_rt_config = eggress_config::compile::compile_config(&config)
            .map_err(|e| EggressError::Reload(e.to_string()))?;

        // Classify reload using the same topology and endpoint rules as the
        // file-backed runtime reload path.
        let prev_snapshot = self.state.snapshot.load();
        eggress_runtime::classify_reload_config(
            &prev_snapshot.listeners,
            &prev_snapshot.timeouts,
            prev_snapshot.admin.as_ref(),
            &new_rt_config,
        )
        .map_err(EggressError::Reload)?;

        let prev_ref: Option<&eggress_runtime::CompiledRuntimeSnapshot> = Some(&prev_snapshot);
        let new_snapshot =
            eggress_runtime::snapshot::compile_runtime_snapshot(&new_rt_config, prev_ref)
                .map_err(|e| EggressError::Reload(format!("snapshot build: {e}")))?;

        let gen = new_snapshot.generation;
        let upstreams = new_snapshot.upstreams.len();

        // Snapshot must be published before the router swap. Readers that observe
        // the new generation via `snapshot.load()` pull the router from that
        // same snapshot Arc, so any reader seeing the new generation also sees
        // the router that belongs to it.
        let new_snapshot = Arc::new(new_snapshot);
        self.state.snapshot.store(new_snapshot.clone());
        self.state.routing.swap_arc(new_snapshot.router.clone());
        self.state.restart_health_probes();

        self.state.metrics.set_config_generation(gen);
        self.state.metrics.record_reload(true);

        Ok(ReloadOutcome::Applied {
            generation: gen,
            upstreams,
        })
    }

    /// Reload configuration from a file.
    pub fn reload_toml_file(&self, path: impl AsRef<Path>) -> Result<ReloadOutcome, EggressError> {
        let path = path.as_ref();
        let contents = std::fs::read_to_string(path)
            .map_err(|e| EggressError::Reload(format!("failed to read {path:?}: {e}")))?;
        self.reload_toml_str(&contents)
    }

    /// Cancel the runtime's shutdown token without joining the supervisor.
    ///
    /// Best-effort teardown for finalizers that must not synchronously join
    /// the service thread: listeners and background tasks stop in the
    /// background while the handle itself may be abandoned.
    pub fn cancel(&self) {
        if let Some(token) = self.token.as_ref() {
            token.cancel();
        }
    }

    /// Cancel the runtime and remove the temporary config without joining it.
    ///
    /// This is intended for finalizers that must abandon the handle after
    /// cancellation without retaining credentials in a temporary file.
    pub fn cancel_and_cleanup(&mut self) {
        self.cancel();
        if let Some(path) = self._config_path.take() {
            let _ = std::fs::remove_file(&path);
        }
    }

    /// Initiate graceful shutdown.
    pub async fn shutdown(mut self) -> Result<(), EggressError> {
        if let Some(token) = self.token.take() {
            token.cancel();
        }
        if let Some(task) = self._runtime_task.take() {
            let _ = task.await;
        }
        if let Some(jh) = self._run_handle.take() {
            let _ = tokio::task::spawn_blocking(move || {
                let _ = jh.join();
            })
            .await;
        }
        if let Some(path) = self._config_path.take() {
            let _ = std::fs::remove_file(&path);
        }
        Ok(())
    }

    /// Initiate graceful shutdown (blocking).
    pub fn shutdown_blocking(mut self) -> Result<(), EggressError> {
        if let Some(token) = self.token.take() {
            token.cancel();
        }
        if let Some(jh) = self._run_handle.take() {
            let _ = jh.join();
        }
        if let Some(task) = self._runtime_task.take() {
            let rt = tokio::runtime::Runtime::new()
                .map_err(|e| EggressError::Shutdown(e.to_string()))?;
            rt.block_on(async {
                let _ = task.await;
            });
        }
        if let Some(path) = self._config_path.take() {
            let _ = std::fs::remove_file(&path);
        }
        Ok(())
    }
}

impl Drop for EggressHandle {
    /// Cancel the shutdown token and best-effort join the supervisor.
    ///
    /// This is a fallback for callers who do not call `shutdown()` explicitly.
    /// The async path creates a throwaway Tokio runtime to await the task with
    /// a 5-second timeout; if the timeout expires, the task is abandoned.
    /// Prefer explicit `shutdown()` or `shutdown_blocking()` for guaranteed
    /// orderly teardown.
    fn drop(&mut self) {
        if let Some(token) = self.token.take() {
            token.cancel();
        }
        if let Some(jh) = self._run_handle.take() {
            let _ = jh.join();
        }
        if let Some(task) = self._runtime_task.take() {
            let rt = tokio::runtime::Runtime::new().ok();
            if let Some(rt) = rt {
                rt.block_on(async {
                    let _ = tokio::time::timeout(Duration::from_secs(5), task).await;
                });
            }
        }
        if let Some(path) = self._config_path.take() {
            let _ = std::fs::remove_file(&path);
        }
    }
}

fn listener_addr_or_configured(
    bound_addrs: &[Option<SocketAddr>],
    idx: usize,
    configured_bind: &str,
) -> SocketAddr {
    bound_addrs
        .get(idx)
        .and_then(|a| *a)
        .or_else(|| configured_bind.parse().ok())
        .unwrap_or_else(default_listener_addr)
}

fn default_listener_addr() -> SocketAddr {
    SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), 0)
}

/// Addresses the service is listening on.
#[derive(Debug, Clone)]
pub struct BoundAddresses {
    /// TCP listener addresses.
    pub listeners: Vec<ListenerAddress>,
    /// Admin server address (if enabled).
    pub admin: Option<std::net::SocketAddr>,
}

impl BoundAddresses {
    /// Look up a listener by name.
    pub fn listener(&self, name: &str) -> Option<std::net::SocketAddr> {
        self.listeners
            .iter()
            .find(|l| l.name == name)
            .map(|l| l.addr)
    }
}

/// A single listener's bound address.
#[derive(Debug, Clone)]
pub struct ListenerAddress {
    /// Listener name from config.
    pub name: String,
    /// Bound socket address.
    pub addr: std::net::SocketAddr,
}

/// Detailed status of a single listener.
#[derive(Debug, Clone)]
pub struct ListenerStatus {
    /// Listener name from config.
    pub name: String,
    /// Configured bind address.
    pub bind: String,
    /// Actual bound socket address (reflects port-0 resolution).
    pub local_addr: std::net::SocketAddr,
    /// Protocols served by this listener.
    pub protocols: Vec<String>,
    /// Whether UDP relay is enabled on this listener.
    pub udp_enabled: bool,
}

/// Current service status.
#[derive(Debug, Clone)]
pub struct ServiceStatus {
    /// Current configuration generation (increments on reload).
    pub generation: u64,
    /// Whether the service is ready to accept connections.
    pub readiness: bool,
    /// Number of active connections.
    pub active_connections: u64,
    /// Uptime in seconds since the service started.
    pub uptime_secs: u64,
    /// Number of configured listeners.
    pub listener_count: usize,
    /// Detailed status for each listener.
    pub listeners: Vec<ListenerStatus>,
    /// Number of active UDP associations.
    pub udp_associations_active: u64,
    /// Number of configured upstreams.
    pub upstream_count: usize,
}

/// Outcome of a configuration reload attempt.
#[derive(Debug)]
pub enum ReloadOutcome {
    /// Reload was applied successfully.
    Applied {
        /// New generation number.
        generation: u64,
        /// Number of upstreams in the new config.
        upstreams: usize,
    },
}

/// Well-known keys that hold raw secrets and must always be redacted.
const REDACTED_SECRET_KEYS: &[&str] = &[
    "password",
    "password_env",
    "secret",
    "secret_ref",
    "token",
    "api_key",
    "apikey",
    "credentials",
];

/// Redact credential fields in a dynamic TOML value tree.
///
/// Walks the tree generically rather than only enumerating known paths:
/// - Any string whose key matches a known credential-bearing name is
///   replaced with `****`.
/// - Any string that looks like a proxy URI (`scheme://...`) is passed
///   through [`redact_uri`] so `user:pass@` and `user@` authorities are
///   stripped. This covers `upstreams[].uri`, per-hop credentials, PAC
///   fields, and any future field that embeds a proxy URI.
fn redact_toml_value(value: &mut toml::Value) {
    redact_toml_value_inner(value);
}

fn redact_toml_value_inner(value: &mut toml::Value) {
    match value {
        toml::Value::Table(table) => {
            for (key, val) in table.iter_mut() {
                let lkey = key.to_ascii_lowercase();
                if REDACTED_SECRET_KEYS.iter().any(|k| lkey == *k) {
                    if let toml::Value::String(_) = val {
                        *val = toml::Value::String("****".to_string());
                        continue;
                    }
                }
                redact_toml_value_inner(val);
            }
        }
        toml::Value::Array(items) => {
            for item in items.iter_mut() {
                redact_toml_value_inner(item);
            }
        }
        toml::Value::String(s) if looks_like_proxy_uri(s) => {
            *s = redact_uri(s);
        }
        _ => {}
    }
}

/// Heuristic: a string is treated as a proxy URI if it starts with
/// `scheme://` where `scheme` is one of the eggress-supported schemes.
fn looks_like_proxy_uri(s: &str) -> bool {
    let Some(colon) = s.find("://") else {
        return false;
    };
    let scheme = &s[..colon];
    matches!(
        scheme,
        "socks5"
            | "socks4"
            | "http"
            | "https"
            | "ss"
            | "trojan"
            | "h2"
            | "ws"
            | "wss"
            | "raw"
            | "tunnel"
            | "redir"
            | "unix"
    )
}

/// Redact credentials embedded in a proxy URI.
///
/// Transforms `proto://user:pass@host:port` into `proto://****:****@host:port`.
/// Also redacts username-only authorities (`proto://user@host:port`) so that
/// bare usernames never leak into diagnostic or `redacted_*` output.
/// If no `userinfo` is present, the URI is returned unchanged.
///
/// The userinfo separator is the LAST unbracketed `@` after the scheme;
/// a raw password containing `@` must not be treated as a separator.
fn redact_uri(uri: &str) -> String {
    if let Some(scheme_end) = uri.find("://") {
        let rest = &uri[scheme_end + 3..];
        // Find LAST unbracketed '@' so a raw '@' in the password is preserved.
        let mut last_at: Option<usize> = None;
        let mut bracket_depth = 0u32;
        for (i, c) in rest.char_indices() {
            match c {
                '[' => bracket_depth += 1,
                ']' => bracket_depth = bracket_depth.saturating_sub(1),
                '@' if bracket_depth == 0 => last_at = Some(i),
                _ => {}
            }
        }
        if let Some(at_pos) = last_at {
            let authority_after = &rest[at_pos + 1..];
            return format!("{}://****:****@{}", &uri[..scheme_end], authority_after);
        }
    }
    uri.to_string()
}

/// Write config to a temporary file for the supervisor.
///
/// The TOML may carry plaintext upstream credentials, so the file is created
/// without following a pre-existing path. On Unix it is also owner-only
/// (0600) instead of world-readable.
fn write_temp_config(config: &EggressConfig) -> Result<String, EggressError> {
    let dir = std::env::temp_dir();
    use std::io::Write;
    let mut file = tempfile::Builder::new()
        .prefix("eggress-embed-")
        .suffix(".toml")
        .tempfile_in(dir)
        .map_err(|e| EggressError::Config(format!("failed to create temp config: {e}")))?;
    file.write_all(config.source_toml.as_bytes())
        .and_then(|_| file.flush())
        .map_err(|e| EggressError::Config(format!("failed to write temp config: {e}")))?;
    file.into_temp_path()
        .keep()
        .map(|path| path.to_string_lossy().into_owned())
        .map_err(|e| EggressError::Config(format!("failed to retain temp config: {e}")))
}

#[cfg(test)]
mod tests {
    use std::net::SocketAddr;

    use super::{default_listener_addr, listener_addr_or_configured};

    #[test]
    fn listener_addr_prefers_bound_address() {
        let bound: SocketAddr = "127.0.0.1:1234".parse().unwrap();

        assert_eq!(
            listener_addr_or_configured(&[Some(bound)], 0, "127.0.0.1:5678"),
            bound
        );
    }

    #[test]
    fn listener_addr_falls_back_to_configured_bind() {
        let configured: SocketAddr = "127.0.0.1:5678".parse().unwrap();

        assert_eq!(
            listener_addr_or_configured(&[], 0, "127.0.0.1:5678"),
            configured
        );
    }

    #[test]
    fn listener_addr_uses_default_for_invalid_configured_bind() {
        assert_eq!(
            listener_addr_or_configured(&[], 0, "not an address"),
            default_listener_addr()
        );
    }

    #[cfg(unix)]
    #[test]
    fn temp_config_file_is_owner_only() {
        use std::os::unix::fs::PermissionsExt;

        let config = super::EggressConfig::from_toml_str("version = 1").unwrap();
        let path = super::write_temp_config(&config).unwrap();
        let metadata = std::fs::metadata(&path).unwrap();
        assert_eq!(
            metadata.permissions().mode() & 0o777,
            0o600,
            "temp config carries plaintext credentials and must not be group/world readable"
        );
        let _ = std::fs::remove_file(&path);
    }

    #[test]
    fn temp_config_files_use_distinct_random_names() {
        let config = super::EggressConfig::from_toml_str("version = 1").unwrap();
        let first = super::write_temp_config(&config).unwrap();
        let second = super::write_temp_config(&config).unwrap();
        assert_ne!(first, second);
        let _ = std::fs::remove_file(first);
        let _ = std::fs::remove_file(second);
    }

    #[test]
    fn cancel_removes_temp_config_file() {
        let config = super::EggressConfig::from_toml_str("version = 1").unwrap();
        let mut handle = super::EggressService::new(config).start_blocking().unwrap();
        let path = handle._config_path.clone().unwrap();

        assert!(std::path::Path::new(&path).exists());
        handle.cancel_and_cleanup();
        assert!(!std::path::Path::new(&path).exists());
    }
}