Skip to main content

pb_mapper_core/
config.rs

1use std::net::SocketAddr;
2use std::num::NonZeroUsize;
3use std::sync::Arc;
4use std::time::Duration;
5
6use snafu::ResultExt;
7
8use crate::error::{CfgPbServerEnvNotExistSnafu, CfgResolveSockAddrSnafu, Result};
9
10#[derive(Debug, Clone, Copy)]
11pub enum StatusOp {
12    /// Get active remote connection IDs.
13    RemoteId,
14    /// Get registered service keys.
15    Keys,
16    /// Get direct-session observations reported by endpoints in this namespace.
17    Sessions,
18}
19
20/// Every address a name resolved to, in the order the resolver returned them.
21///
22/// Resolution used to end in `.next()`, which threw away everything after the
23/// first candidate. That is enough for an `ip:port` literal, but a hostname with
24/// several A/AAAA records — a relay behind round-robin DNS, or a dual-stack host
25/// whose first record is an unreachable IPv6 address — resolved to one address
26/// and then failed against it, with the working candidates never tried.
27///
28/// The dial loops below this were always able to try every address: both
29/// `each_addr` and the `uni-stream` providers iterate a `ToSocketAddrs` and only
30/// report the last error once every candidate has failed. They just never
31/// received more than one. So this type is the whole of the fix: carry the list
32/// to them, and they do the rest.
33///
34/// Guaranteed non-empty, so a caller never has to handle a resolution that
35/// succeeded with nothing in it. Cheap to clone — the addresses are shared, not
36/// copied — because every tunnel worker and every retry needs its own handle.
37#[derive(Clone, Debug, Eq, PartialEq)]
38pub struct ResolvedAddrs {
39    /// Non-empty by construction; see [`ResolvedAddrs::new`].
40    addrs: Arc<[SocketAddr]>,
41}
42
43impl ResolvedAddrs {
44    /// Build from the outcome of looking `name` up, rejecting an empty result.
45    /// A failure keeps the resolver's reason.
46    fn looked_up(name: &str, lookup: std::io::Result<Vec<SocketAddr>>) -> Result<Self> {
47        let addrs = lookup.context(CfgResolveSockAddrSnafu { string: name })?;
48        Self::from_candidates(addrs).ok_or_else(|| crate::error::Error::CfgResolveSockAddr {
49            string: name.to_string(),
50            source: std::io::Error::new(
51                std::io::ErrorKind::NotFound,
52                "the resolver answered with no address",
53            ),
54        })
55    }
56
57    /// Build from candidates already resolved elsewhere, rejecting an empty list.
58    ///
59    /// For callers that resolve through another address trait — the tunnel
60    /// internals take a generic `ToSocketAddrs` at their public boundary — and
61    /// need the result in this non-empty form.
62    #[must_use]
63    pub fn from_candidates(addrs: Vec<SocketAddr>) -> Option<Self> {
64        if addrs.is_empty() {
65            return None;
66        }
67        Some(Self {
68            addrs: Arc::from(addrs),
69        })
70    }
71
72    /// The candidates, for handing to `each_addr` or a `ToSocketAddrs` bound.
73    ///
74    /// `&[SocketAddr]` is what both address traits in play accept, and it is
75    /// `Copy`, which the `A: ToSocketAddrs + Copy` bounds on the tunnel internals
76    /// require. A `Vec` is neither.
77    #[inline]
78    #[must_use]
79    pub fn as_slice(&self) -> &[SocketAddr] {
80        &self.addrs
81    }
82
83    /// The first candidate.
84    ///
85    /// For the places that genuinely need one address rather than a list: a
86    /// `SocketAddr` field on a status record, a preflight probe, a log line. Not
87    /// for dialling — that is what [`Self::as_slice`] is for.
88    #[inline]
89    #[must_use]
90    pub fn primary(&self) -> SocketAddr {
91        // Non-empty by construction, so indexing cannot panic. `[0]` rather than
92        // `first().unwrap()`: the invariant is the reason, and `unwrap` is denied.
93        self.addrs[0]
94    }
95}
96
97impl std::fmt::Display for ResolvedAddrs {
98    /// Renders the primary address, with a count when candidates were dropped.
99    ///
100    /// Log lines pass these through `%`, and a bare Debug dump of a one-element
101    /// list reads worse than the address itself.
102    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
103        write!(formatter, "{}", self.primary())?;
104        match self.addrs.len() {
105            1 => Ok(()),
106            more => write!(formatter, " (+{} more)", more - 1),
107        }
108    }
109}
110
111impl From<SocketAddr> for ResolvedAddrs {
112    fn from(addr: SocketAddr) -> Self {
113        Self {
114            addrs: Arc::from(vec![addr]),
115        }
116    }
117}
118
119/// What an address to resolve names.
120enum Target<'a> {
121    /// A literal `ip:port`, which needs no resolver.
122    Literal(SocketAddr),
123    /// A host and port to look up.
124    Name(&'a str, u16),
125}
126
127impl<'a> Target<'a> {
128    /// Splits `addr` as the system resolver does, so that whatever it would
129    /// look up is looked up. Anything else is a malformed address, which fails
130    /// with its parse error: so does a host with a colon in it, which no name
131    /// has, and which is what the split leaves of an IPv6 address written
132    /// without its brackets and port.
133    fn of(addr: &'a str) -> Result<Self> {
134        let parse_error = match addr.parse::<SocketAddr>() {
135            Ok(socket_addr) => return Ok(Self::Literal(socket_addr)),
136            Err(error) => error,
137        };
138        match addr
139            .rsplit_once(':')
140            .filter(|(host, _)| !host.contains(':'))
141            .and_then(|(host, port)| Some((host, port.parse().ok()?)))
142        {
143            Some((host, port)) => Ok(Self::Name(host, port)),
144            None => Err(crate::error::Error::CfgParseSockAddr {
145                string: addr.to_string(),
146                source: parse_error,
147            }),
148        }
149    }
150}
151
152/// Resolve `addr` to every candidate it names.
153///
154/// A literal `ip:port` short-circuits; anything else goes to the system
155/// resolver, once. Only [`resolve_addrs_async`] asks the configured DNS
156/// servers first.
157#[inline]
158pub fn resolve_addrs(addr: &str) -> Result<ResolvedAddrs> {
159    let (host, port) = match Target::of(addr)? {
160        Target::Literal(literal) => return Ok(ResolvedAddrs::from(literal)),
161        Target::Name(host, port) => (host, port),
162    };
163    let lookup = std::net::ToSocketAddrs::to_socket_addrs(&(host, port));
164    ResolvedAddrs::looked_up(addr, lookup.map(Iterator::collect))
165}
166
167/// Async counterpart of [`resolve_addrs`], for Tokio contexts.
168///
169/// It asks the built-in public DNS servers before the system resolver, and
170/// that order is decided, not an oversight: a device whose own resolver
171/// answers wrongly, but answers, still finds its relay. The price is that a
172/// name which resolves differently inside a private network gets its public
173/// answer, and that a network which drops DNS to all but its own resolver
174/// makes each lookup wait out the public servers first.
175pub async fn resolve_addrs_async(addr: &str) -> Result<ResolvedAddrs> {
176    let (host, port) = match Target::of(addr)? {
177        Target::Literal(literal) => return Ok(ResolvedAddrs::from(literal)),
178        Target::Name(host, port) => (host, port),
179    };
180    if host != "localhost"
181        && let Ok(ips) = crate::addr::get_ip_addrs_async(host).await
182        && let Some(addrs) = ResolvedAddrs::from_candidates(
183            ips.into_iter()
184                .map(|ip| SocketAddr::new(ip, port))
185                .collect(),
186        )
187    {
188        return Ok(addrs);
189    }
190    let lookup = tokio::net::lookup_host((host, port)).await;
191    ResolvedAddrs::looked_up(addr, lookup.map(Iterator::collect))
192}
193
194const PB_MAPPER_SERVER: &str = "PB_MAPPER_SERVER";
195
196/// Env to control whether the keep-alive option of TCP is enabled
197pub const PB_MAPPER_KEEP_ALIVE: &str = "PB_MAPPER_KEEP_ALIVE";
198pub const PB_MAPPER_CONTROL_IO_TIMEOUT: &str = "PB_MAPPER_CONTROL_IO_TIMEOUT";
199pub const PB_MAPPER_STREAM_ACK_TIMEOUT: &str = "PB_MAPPER_STREAM_ACK_TIMEOUT";
200pub const PB_MAPPER_STREAM_READY_TIMEOUT: &str = "PB_MAPPER_STREAM_READY_TIMEOUT";
201pub const PB_MAPPER_STREAM_RECOVERY_TIMEOUT: &str = "PB_MAPPER_STREAM_RECOVERY_TIMEOUT";
202pub const PB_MAPPER_CONTROL_CONN_POOL_SIZE: &str = "PB_MAPPER_CONTROL_CONN_POOL_SIZE";
203pub const PB_MAPPER_CONTROL_HEARTBEAT_INTERVAL: &str = "PB_MAPPER_CONTROL_HEARTBEAT_INTERVAL";
204pub const PB_MAPPER_CONTROL_HEARTBEAT_TOLERANCE: &str = "PB_MAPPER_CONTROL_HEARTBEAT_TOLERANCE";
205pub const PB_MAPPER_CONTROL_SUSPECT_GRACE: &str = "PB_MAPPER_CONTROL_SUSPECT_GRACE";
206pub const PB_MAPPER_REGISTRATION_PROBE_TIMEOUT: &str = "PB_MAPPER_REGISTRATION_PROBE_TIMEOUT";
207pub const PB_MAPPER_REGISTRATION_REJECT_BACKOFF_MIN: &str =
208    "PB_MAPPER_REGISTRATION_REJECT_BACKOFF_MIN";
209pub const PB_MAPPER_REGISTRATION_REJECT_BACKOFF_MAX: &str =
210    "PB_MAPPER_REGISTRATION_REJECT_BACKOFF_MAX";
211pub const PB_MAPPER_SERVER_LEASE_TIMEOUT: &str = "PB_MAPPER_SERVER_LEASE_TIMEOUT";
212pub const PB_MAPPER_SERVER_LEASE_SWEEP_INTERVAL: &str = "PB_MAPPER_SERVER_LEASE_SWEEP_INTERVAL";
213pub const PB_MAPPER_CLIENT_HEALTH_CHECK_INTERVAL: &str = "PB_MAPPER_CLIENT_HEALTH_CHECK_INTERVAL";
214pub const PB_MAPPER_CLIENT_HEALTH_CHECK_TIMEOUT: &str = "PB_MAPPER_CLIENT_HEALTH_CHECK_TIMEOUT";
215pub const PB_MAPPER_CLIENT_HEALTH_FAILURE_THRESHOLD: &str =
216    "PB_MAPPER_CLIENT_HEALTH_FAILURE_THRESHOLD";
217pub const PB_MAPPER_LOG_FORMAT: &str = "PB_MAPPER_LOG_FORMAT";
218pub const PB_MAPPER_TUNNEL_IDLE_TIMEOUT: &str = "PB_MAPPER_TUNNEL_IDLE_TIMEOUT";
219pub const PB_MAPPER_HALF_CLOSE_IDLE_TIMEOUT: &str = "PB_MAPPER_HALF_CLOSE_IDLE_TIMEOUT";
220pub const PB_MAPPER_NEW_STREAMS_PER_SECOND: &str = "PB_MAPPER_NEW_STREAMS_PER_SECOND";
221/// What [`new_streams_per_second`] is when the variable is unset or not a
222/// positive integer.
223pub const DEFAULT_NEW_STREAMS_PER_SECOND: u32 = 100;
224const DEFAULT_CONTROL_IO_TIMEOUT: Duration = Duration::from_secs(30);
225const DEFAULT_STREAM_ACK_TIMEOUT: Duration = Duration::from_millis(300);
226const DEFAULT_STREAM_READY_TIMEOUT: Duration = Duration::from_secs(1);
227const DEFAULT_STREAM_RECOVERY_TIMEOUT: Duration = Duration::from_secs(2);
228const DEFAULT_CONTROL_CONN_POOL_SIZE: usize = 2;
229const DEFAULT_CONTROL_HEARTBEAT_INTERVAL: Duration = Duration::from_secs(2);
230const DEFAULT_CONTROL_HEARTBEAT_TOLERANCE: Duration = Duration::from_secs(6);
231const DEFAULT_CONTROL_SUSPECT_GRACE: Duration = Duration::from_secs(2);
232const DEFAULT_REGISTRATION_PROBE_TIMEOUT: Duration = Duration::from_secs(1);
233const DEFAULT_REGISTRATION_REJECT_BACKOFF_MIN: Duration = Duration::from_secs(5);
234const DEFAULT_REGISTRATION_REJECT_BACKOFF_MAX: Duration = Duration::from_secs(80);
235const DEFAULT_SERVER_LEASE_TIMEOUT: Duration = Duration::from_secs(15);
236const DEFAULT_SERVER_LEASE_SWEEP_INTERVAL: Duration = Duration::from_secs(5);
237const DEFAULT_CLIENT_HEALTH_CHECK_INTERVAL: Duration = Duration::from_secs(15);
238const DEFAULT_CLIENT_HEALTH_CHECK_TIMEOUT: Duration = Duration::from_secs(5);
239const DEFAULT_CLIENT_HEALTH_FAILURE_THRESHOLD: usize = 3;
240const DEFAULT_TUNNEL_IDLE_TIMEOUT: Duration = Duration::from_secs(60 * 60);
241const DEFAULT_HALF_CLOSE_IDLE_TIMEOUT: Duration = Duration::from_secs(60);
242const MAX_CONTROL_CONN_POOL_SIZE: usize = 16;
243const MAX_CLIENT_HEALTH_FAILURE_THRESHOLD: usize = 100;
244
245const _: () = assert!(
246    !DEFAULT_REGISTRATION_REJECT_BACKOFF_MIN.is_zero()
247        && !DEFAULT_REGISTRATION_REJECT_BACKOFF_MAX.is_zero()
248        && !DEFAULT_SERVER_LEASE_SWEEP_INTERVAL.is_zero(),
249    "positive_duration_from_env falls back to these defaults, so they must be positive"
250);
251const _: () = assert!(
252    DEFAULT_REGISTRATION_REJECT_BACKOFF_MIN.as_nanos()
253        <= DEFAULT_REGISTRATION_REJECT_BACKOFF_MAX.as_nanos(),
254    "the default registration reject backoff must be a valid RetryBackoff range"
255);
256const _: () = assert!(
257    DEFAULT_CONTROL_HEARTBEAT_INTERVAL.as_nanos() < DEFAULT_CONTROL_HEARTBEAT_TOLERANCE.as_nanos(),
258    "a control connection becomes suspect only after missing heartbeats"
259);
260const _: () = assert!(
261    DEFAULT_CONTROL_HEARTBEAT_INTERVAL.as_nanos() < DEFAULT_SERVER_LEASE_TIMEOUT.as_nanos(),
262    "a lease must outlast the heartbeat that renews it"
263);
264const _: () = assert!(
265    DEFAULT_SERVER_LEASE_SWEEP_INTERVAL.as_nanos() * 3 == DEFAULT_SERVER_LEASE_TIMEOUT.as_nanos(),
266    "server_lease_sweep_interval documents its default as a third of the lease"
267);
268const _: () = assert!(
269    0 < DEFAULT_CONTROL_CONN_POOL_SIZE
270        && DEFAULT_CONTROL_CONN_POOL_SIZE <= MAX_CONTROL_CONN_POOL_SIZE
271        && 0 < DEFAULT_CLIENT_HEALTH_FAILURE_THRESHOLD
272        && DEFAULT_CLIENT_HEALTH_FAILURE_THRESHOLD <= MAX_CLIENT_HEALTH_FAILURE_THRESHOLD,
273    "a default count must be one bounded_count_from_env could return"
274);
275
276#[derive(Debug, Clone, Copy, PartialEq, Eq)]
277pub enum LogFormat {
278    Pretty,
279    Compact,
280    Json,
281}
282
283pub fn parse_log_format(value: &str) -> LogFormat {
284    match value.trim().to_ascii_lowercase().as_str() {
285        "compact" => LogFormat::Compact,
286        "json" => LogFormat::Json,
287        _ => LogFormat::Pretty,
288    }
289}
290
291pub fn parse_duration(value: &str) -> Option<Duration> {
292    let value = value.trim();
293    if value.is_empty() {
294        return None;
295    }
296    if let Some(raw) = value.strip_suffix("ms") {
297        return raw.trim().parse::<u64>().ok().map(Duration::from_millis);
298    }
299    if let Some(raw) = value.strip_suffix('s') {
300        return raw.trim().parse::<u64>().ok().map(Duration::from_secs);
301    }
302    if let Some(raw) = value.strip_suffix('m') {
303        return raw
304            .trim()
305            .parse::<u64>()
306            .ok()
307            .and_then(|minutes| minutes.checked_mul(60))
308            .map(Duration::from_secs);
309    }
310    if let Some(raw) = value.strip_suffix('h') {
311        return raw
312            .trim()
313            .parse::<u64>()
314            .ok()
315            .and_then(|hours| hours.checked_mul(60 * 60))
316            .map(Duration::from_secs);
317    }
318    value.parse::<u64>().ok().map(Duration::from_secs)
319}
320
321pub fn duration_from_env(name: &str, default: Duration) -> Duration {
322    std::env::var(name)
323        .ok()
324        .and_then(|value| parse_duration(&value))
325        .unwrap_or(default)
326}
327
328/// Read a duration that has to be positive, falling back to `default` on a zero.
329///
330/// Zero is never a usable value for these settings: a period of zero panics
331/// `tokio::time::interval`, and a zero minimum trips [`RetryBackoff::new`]'s
332/// assertion. Clamping a zero up to a millisecond avoids the panic, but trades it
333/// for a hot loop — a rejected registration retried a thousand times a second, or
334/// a full registration scan queued into the routing loop every millisecond. The
335/// default is the only value that is both safe and useful, so a zero selects it
336/// and says so once.
337///
338/// [`RetryBackoff::new`]: crate::timeout::RetryBackoff::new
339fn positive_duration_from_env(name: &str, default: Duration) -> Duration {
340    let value = duration_from_env(name, default);
341    if value.is_zero() {
342        tracing::warn!(
343            event = "config_zero_duration_ignored",
344            variable = name,
345            default = ?default,
346            "ignoring a zero duration and using the default instead"
347        );
348        return default;
349    }
350    value
351}
352
353pub fn control_io_timeout() -> Duration {
354    duration_from_env(PB_MAPPER_CONTROL_IO_TIMEOUT, DEFAULT_CONTROL_IO_TIMEOUT)
355}
356
357pub fn stream_ack_timeout() -> Duration {
358    duration_from_env(PB_MAPPER_STREAM_ACK_TIMEOUT, DEFAULT_STREAM_ACK_TIMEOUT)
359}
360
361pub fn stream_ready_timeout() -> Duration {
362    duration_from_env(PB_MAPPER_STREAM_READY_TIMEOUT, DEFAULT_STREAM_READY_TIMEOUT)
363}
364
365pub fn stream_recovery_timeout() -> Duration {
366    duration_from_env(
367        PB_MAPPER_STREAM_RECOVERY_TIMEOUT,
368        DEFAULT_STREAM_RECOVERY_TIMEOUT,
369    )
370}
371
372/// A positive count from `name`, capped at `max`, or `default` when it is
373/// unset, unparsable or zero.
374fn bounded_count_from_env(name: &str, max: usize, default: usize) -> usize {
375    std::env::var(name)
376        .ok()
377        .and_then(|value| value.trim().parse::<usize>().ok())
378        .filter(|count| *count > 0)
379        .map(|count| count.min(max))
380        .unwrap_or(default)
381}
382
383pub fn control_conn_pool_size() -> usize {
384    bounded_count_from_env(
385        PB_MAPPER_CONTROL_CONN_POOL_SIZE,
386        MAX_CONTROL_CONN_POOL_SIZE,
387        DEFAULT_CONTROL_CONN_POOL_SIZE,
388    )
389}
390
391pub fn control_heartbeat_interval() -> Duration {
392    duration_from_env(
393        PB_MAPPER_CONTROL_HEARTBEAT_INTERVAL,
394        DEFAULT_CONTROL_HEARTBEAT_INTERVAL,
395    )
396}
397
398pub fn control_heartbeat_tolerance() -> Duration {
399    duration_from_env(
400        PB_MAPPER_CONTROL_HEARTBEAT_TOLERANCE,
401        DEFAULT_CONTROL_HEARTBEAT_TOLERANCE,
402    )
403}
404
405pub fn control_suspect_grace() -> Duration {
406    duration_from_env(
407        PB_MAPPER_CONTROL_SUSPECT_GRACE,
408        DEFAULT_CONTROL_SUSPECT_GRACE,
409    )
410}
411
412pub fn registration_probe_timeout() -> Duration {
413    duration_from_env(
414        PB_MAPPER_REGISTRATION_PROBE_TIMEOUT,
415        DEFAULT_REGISTRATION_PROBE_TIMEOUT,
416    )
417}
418
419/// The retry ladder for a registration the relay rejected but marked retryable.
420///
421/// Separate from the transport ladder, and far slower. A transport failure means
422/// the relay could not be reached, so retrying quickly is how the tunnel comes
423/// back. A retryable rejection is the opposite: the relay answered, and refused —
424/// a per-service connection quota that is full, a namespace at its service limit.
425/// Reconnecting a few times a second adds load to the very condition that has to
426/// clear, and it produced thousands of identical reject lines a minute in
427/// production. So the ladder starts at 5s and settles at 80s, each wait cut
428/// short by up to a quarter so that publishers refused together do not come
429/// back together.
430///
431/// Both ends come back together because they are only valid as a pair: a zero
432/// falls back to its default, and the maximum is then raised to the minimum,
433/// rather than letting an environment typo reach [`RetryBackoff::new`]'s
434/// assertions, which would abort the process at start-up.
435///
436/// Raising the maximum, but defaulting a zero minimum, because the two failures
437/// are different. An inverted range is a legible request — wait exactly this long
438/// — and collapsing it to a fixed delay honours it. A zero minimum is not: it
439/// asks for no wait at all, and since [`RetryBackoff`] caps its multiplier at
440/// 1024 ([`RetryBackoff::MAX_DOUBLINGS`]), a millisecond minimum would never
441/// climb past about a second no matter how high the maximum, hammering the very
442/// quota the ladder exists to let clear.
443///
444/// [`RetryBackoff`]: crate::timeout::RetryBackoff
445/// [`RetryBackoff::new`]: crate::timeout::RetryBackoff::new
446/// [`RetryBackoff::MAX_DOUBLINGS`]: crate::timeout::RetryBackoff::MAX_DOUBLINGS
447pub fn registration_reject_backoff() -> (Duration, Duration) {
448    let min = positive_duration_from_env(
449        PB_MAPPER_REGISTRATION_REJECT_BACKOFF_MIN,
450        DEFAULT_REGISTRATION_REJECT_BACKOFF_MIN,
451    );
452    let max = positive_duration_from_env(
453        PB_MAPPER_REGISTRATION_REJECT_BACKOFF_MAX,
454        DEFAULT_REGISTRATION_REJECT_BACKOFF_MAX,
455    )
456    .max(min);
457    (min, max)
458}
459
460pub fn server_lease_timeout() -> Duration {
461    duration_from_env(PB_MAPPER_SERVER_LEASE_TIMEOUT, DEFAULT_SERVER_LEASE_TIMEOUT)
462}
463
464/// How often the relay looks for registrations that stopped renewing their lease.
465///
466/// A third of [`server_lease_timeout`] by default, which bounds two things at
467/// once: how long an expired registration can keep attracting subscribers, and —
468/// because the sweep needs two passes to retire one — how much grace a live
469/// connection gets to notice its own idle timeout first.
470///
471/// A zero falls back to the default: `tokio::time::interval` panics on a zero
472/// period, and each tick queues a scan over every registration through the single
473/// routing loop, so sweeping as fast as the timer allows would starve the traffic
474/// the sweep exists to protect.
475pub fn server_lease_sweep_interval() -> Duration {
476    positive_duration_from_env(
477        PB_MAPPER_SERVER_LEASE_SWEEP_INTERVAL,
478        DEFAULT_SERVER_LEASE_SWEEP_INTERVAL,
479    )
480}
481
482pub fn client_health_check_interval() -> Duration {
483    duration_from_env(
484        PB_MAPPER_CLIENT_HEALTH_CHECK_INTERVAL,
485        DEFAULT_CLIENT_HEALTH_CHECK_INTERVAL,
486    )
487}
488
489pub fn client_health_check_timeout() -> Duration {
490    duration_from_env(
491        PB_MAPPER_CLIENT_HEALTH_CHECK_TIMEOUT,
492        DEFAULT_CLIENT_HEALTH_CHECK_TIMEOUT,
493    )
494}
495
496pub fn client_health_failure_threshold() -> usize {
497    bounded_count_from_env(
498        PB_MAPPER_CLIENT_HEALTH_FAILURE_THRESHOLD,
499        MAX_CLIENT_HEALTH_FAILURE_THRESHOLD,
500        DEFAULT_CLIENT_HEALTH_FAILURE_THRESHOLD,
501    )
502}
503
504/// How long a TCP tunnel may carry nothing in either direction before it is
505/// closed. Zero never closes it for idling.
506pub fn tunnel_idle_timeout() -> Duration {
507    duration_from_env(PB_MAPPER_TUNNEL_IDLE_TIMEOUT, DEFAULT_TUNNEL_IDLE_TIMEOUT)
508}
509
510/// How long a TCP tunnel one side has finished sending on may carry nothing
511/// more before it is closed. Zero never closes it for idling.
512pub fn half_close_idle_timeout() -> Duration {
513    duration_from_env(
514        PB_MAPPER_HALF_CLOSE_IDLE_TIMEOUT,
515        DEFAULT_HALF_CLOSE_IDLE_TIMEOUT,
516    )
517}
518
519/// New streams a namespace may open per second, sustained: the relay's
520/// stream rate limit, and the basis of the first-flight replay budget. The
521/// variable as a positive integer, untrimmed, or
522/// [`DEFAULT_NEW_STREAMS_PER_SECOND`].
523pub fn new_streams_per_second() -> NonZeroUsize {
524    const DEFAULT: NonZeroUsize = match NonZeroUsize::new(DEFAULT_NEW_STREAMS_PER_SECOND as usize) {
525        Some(rate) => rate,
526        None => panic!("the default stream rate is positive"),
527    };
528    std::env::var(PB_MAPPER_NEW_STREAMS_PER_SECOND)
529        .ok()
530        .and_then(|value| value.parse().ok())
531        .unwrap_or(DEFAULT)
532}
533
534/// Whether the environment asks for TCP keep-alive, from `PB_MAPPER_KEEP_ALIVE`.
535///
536/// A default for a process to read once at startup — not something the tunnels
537/// consult. Keep-alive is a per-tunnel parameter because one process can run
538/// many tunnels that disagree about it, which is why this is a function and not
539/// the `LazyLock<bool>` it used to be: that froze on the first tunnel to touch
540/// a socket and left every later one, including the UI's own toggle, unable to
541/// change it.
542pub fn keep_alive_from_env() -> bool {
543    match std::env::var(PB_MAPPER_KEEP_ALIVE) {
544        // The documented spelling is `ON`; the previous check was `is_ok()`,
545        // which turned keep-alive on for any value at all — `OFF` included.
546        Ok(value) => matches!(
547            value.trim().to_ascii_lowercase().as_str(),
548            "on" | "1" | "true" | "yes"
549        ),
550        Err(_) => false,
551    }
552}
553
554/// The relay address as configured: `addr` if given, else `PB_MAPPER_SERVER`.
555///
556/// Unresolved on purpose. A caller that hands the address to something which
557/// resolves it itself — the SDK client, for one — should pass the name along
558/// rather than resolve it here and stringify the result, which both duplicates
559/// the lookup and narrows a multi-address name down to one entry on the way.
560pub fn pb_mapper_server_addr(addr: Option<&str>) -> Result<String> {
561    match addr {
562        Some(addr) => Ok(addr.to_string()),
563        None => std::env::var(PB_MAPPER_SERVER).context(CfgPbServerEnvNotExistSnafu),
564    }
565}
566
567/// Every address the relay resolves to: `addr` if given, else `PB_MAPPER_SERVER`.
568#[inline]
569pub fn resolve_pb_mapper_server(addr: Option<&str>) -> Result<ResolvedAddrs> {
570    match addr {
571        Some(addr) => resolve_addrs(addr),
572        None => {
573            let addr = std::env::var(PB_MAPPER_SERVER).context(CfgPbServerEnvNotExistSnafu)?;
574            resolve_addrs(&addr)
575        }
576    }
577}
578
579/// Async counterpart of [`resolve_pb_mapper_server`], for Tokio contexts.
580pub async fn resolve_pb_mapper_server_async(addr: Option<&str>) -> Result<ResolvedAddrs> {
581    match addr {
582        Some(addr) => resolve_addrs_async(addr).await,
583        None => {
584            let addr = std::env::var(PB_MAPPER_SERVER).context(CfgPbServerEnvNotExistSnafu)?;
585            resolve_addrs_async(&addr).await
586        }
587    }
588}
589
590#[cfg(test)]
591mod tests {
592    use super::*;
593
594    #[test]
595    fn parse_log_format_accepts_supported_values() {
596        assert_eq!(parse_log_format("pretty"), LogFormat::Pretty);
597        assert_eq!(parse_log_format("compact"), LogFormat::Compact);
598        assert_eq!(parse_log_format("json"), LogFormat::Json);
599        assert_eq!(parse_log_format(" JSON "), LogFormat::Json);
600        assert_eq!(parse_log_format("unknown"), LogFormat::Pretty);
601    }
602
603    #[test]
604    fn parse_duration_accepts_suffixes_and_plain_seconds() {
605        assert_eq!(parse_duration("42"), Some(Duration::from_secs(42)));
606        assert_eq!(parse_duration("500ms"), Some(Duration::from_millis(500)));
607        assert_eq!(parse_duration("2s"), Some(Duration::from_secs(2)));
608        assert_eq!(parse_duration("3m"), Some(Duration::from_secs(180)));
609        assert_eq!(parse_duration("1h"), Some(Duration::from_secs(3600)));
610        assert_eq!(parse_duration(""), None);
611        assert_eq!(parse_duration("bad"), None);
612        assert_eq!(parse_duration("18446744073709551615h"), None);
613    }
614
615    /// The point of [`ResolvedAddrs`]: a name with several records keeps them
616    /// all, so the dial loops can try each one. Collapsing to the first is what
617    /// made a multi-record relay unreachable whenever its first address was.
618    #[test]
619    fn resolved_addrs_keeps_every_candidate() {
620        let first: SocketAddr = "127.0.0.1:7666".parse().expect("literal");
621        let second: SocketAddr = "[::1]:7666".parse().expect("literal");
622        let addrs = ResolvedAddrs::from_candidates(vec![first, second]).expect("non-empty");
623
624        assert_eq!(addrs.as_slice(), [first, second]);
625        assert_eq!(addrs.primary(), first, "order is the resolver's order");
626    }
627
628    /// An empty candidate list is not a resolution: nothing could be dialled, so
629    /// it has to be rejected here rather than surface as a connect failure
630    /// against an address the caller never gave.
631    #[test]
632    fn resolved_addrs_rejects_an_empty_candidate_list() {
633        assert!(ResolvedAddrs::from_candidates(Vec::new()).is_none());
634    }
635
636    /// The rendering has to name one address — it goes into connect errors and
637    /// log fields — while still admitting that others were available.
638    #[test]
639    fn resolved_addrs_renders_the_primary_and_the_rest_as_a_count() {
640        let single: SocketAddr = "127.0.0.1:7666".parse().expect("literal");
641        assert_eq!(ResolvedAddrs::from(single).to_string(), "127.0.0.1:7666");
642
643        let second: SocketAddr = "[::1]:7666".parse().expect("literal");
644        let both = ResolvedAddrs::from_candidates(vec![single, second]).expect("non-empty");
645        assert_eq!(both.to_string(), "127.0.0.1:7666 (+1 more)");
646    }
647
648    /// A literal address needs no resolver, and must survive verbatim.
649    #[test]
650    fn resolve_addrs_passes_a_literal_through() {
651        let addrs = resolve_addrs("127.0.0.1:7666").expect("a literal always resolves");
652        assert_eq!(
653            addrs.as_slice(),
654            ["127.0.0.1:7666".parse().expect("literal")]
655        );
656    }
657
658    /// `localhost` is the everyday multi-record name: it resolves to a v4 and a
659    /// v6 loopback on most hosts, and both must reach the dial loop.
660    #[test]
661    fn resolve_addrs_keeps_every_localhost_record() {
662        let addrs = resolve_addrs("localhost:7666").expect("localhost always resolves");
663        assert!(
664            addrs.as_slice().iter().all(|addr| addr.ip().is_loopback()),
665            "localhost must resolve to loopback only, got {:?}",
666            addrs.as_slice()
667        );
668    }
669
670    /// A name that resolves to nothing is an error, not an empty success.
671    ///
672    /// Tested with a missing port rather than an unresolvable host: a resolver
673    /// that answers every query with a wildcard address — WSL's NAT DNS, among
674    /// others — makes "this host does not exist" untestable, while no resolver
675    /// invents a port.
676    #[test]
677    fn resolve_addrs_fails_when_nothing_can_be_resolved() {
678        assert!(resolve_addrs("127.0.0.1").is_err(), "no port");
679        assert!(resolve_addrs("localhost").is_err(), "no port");
680    }
681
682    /// A name that does not resolve reports the resolver's reason, not the
683    /// parse error a malformed address gets, which would send whoever has to
684    /// fix it to the address's syntax. A NUL byte fails every resolver before
685    /// a query is sent.
686    #[tokio::test]
687    async fn a_name_that_does_not_resolve_reports_the_resolvers_reason() {
688        let blocking = resolve_addrs("bad\0name:7666").expect_err("a NUL never resolves");
689        let asynchronous = resolve_addrs_async("bad\0name:7666")
690            .await
691            .expect_err("a NUL never resolves");
692        for error in [blocking, asynchronous] {
693            assert!(
694                matches!(error, crate::error::Error::CfgResolveSockAddr { .. }),
695                "{error:?}"
696            );
697        }
698        // No port, and an IPv6 address without one, are malformed, not names.
699        for malformed in ["localhost", "fe80::1", "::1"] {
700            assert!(
701                matches!(
702                    resolve_addrs_async(malformed).await,
703                    Err(crate::error::Error::CfgParseSockAddr { .. })
704                ),
705                "{malformed}"
706            );
707        }
708    }
709
710    /// The async path is the one the tunnels use, and has to agree with the
711    /// blocking one on a literal.
712    #[tokio::test]
713    async fn resolve_addrs_async_matches_the_blocking_path_on_a_literal() {
714        let expected = resolve_addrs("127.0.0.1:7666").expect("literal");
715        let actual = resolve_addrs_async("127.0.0.1:7666")
716            .await
717            .expect("literal");
718        assert_eq!(actual, expected);
719    }
720}