kumo_api_types/
egress_path.rs

1use cidr_map::CidrSet;
2use data_loader::KeySource;
3use dns_resolver::IpLookupStrategy;
4use mailexchanger::MailExchanger;
5#[cfg(feature = "lua")]
6use mlua::prelude::*;
7use openssl::ssl::SslOptions;
8use ordermap::OrderMap;
9use rfc5321::SmtpClientTimeouts;
10use rustls::crypto::aws_lc_rs::ALL_CIPHER_SUITES;
11use rustls::SupportedCipherSuite;
12use serde::{Deserialize, Deserializer, Serialize};
13use std::collections::BTreeMap;
14use std::fmt::Write;
15use std::time::Duration;
16use throttle::{LimitSpec, ThrottleSpec};
17use utoipa::ToSchema;
18
19#[derive(Deserialize, Serialize, Debug, Clone, PartialEq, Eq, Copy)]
20pub enum Tls {
21    /// Use it if available. If the peer has invalid or self-signed certificates, then
22    /// delivery will fail. Will NOT fallback to not using TLS if the peer advertises
23    /// STARTTLS.
24    Opportunistic,
25    /// Use it if available, and allow self-signed or otherwise invalid server certs.
26    /// Not recommended for sending to the public internet; this is for local/lab
27    /// testing scenarios only.
28    OpportunisticInsecure,
29    /// TLS with valid certs is required.
30    Required,
31    /// Required, and allow self-signed or otherwise invalid server certs.
32    /// Not recommended for sending to the public internet; this is for local/lab
33    /// testing scenarios only.
34    RequiredInsecure,
35    /// Do not try to use TLS
36    Disabled,
37}
38
39/// How insistent a [`Tls`] policy is about negotiating STARTTLS, ordered
40/// from least to most demanding.
41#[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Copy)]
42enum Starttls {
43    Never,
44    IfOffered,
45    Mandatory,
46}
47
48impl Tls {
49    /// Merges `self` with `floor`, taking the stronger of the two on each
50    /// of STARTTLS-mandatory and peer-certificate-verified independently.
51    /// Used to raise a configured policy to a destination-published floor
52    /// (MTA-STS, DANE) without ever lowering it.
53    pub fn at_least(self, floor: Tls) -> Tls {
54        let (starttls, verify) = self.axes();
55        let (floor_starttls, floor_verify) = floor.axes();
56        Self::from_axes(starttls.max(floor_starttls), verify || floor_verify)
57    }
58
59    fn axes(self) -> (Starttls, bool) {
60        match self {
61            Self::Disabled => (Starttls::Never, false),
62            Self::OpportunisticInsecure => (Starttls::IfOffered, false),
63            Self::Opportunistic => (Starttls::IfOffered, true),
64            Self::RequiredInsecure => (Starttls::Mandatory, false),
65            Self::Required => (Starttls::Mandatory, true),
66        }
67    }
68
69    fn from_axes(starttls: Starttls, verify: bool) -> Tls {
70        match (starttls, verify) {
71            (Starttls::Never, _) => Self::Disabled,
72            (Starttls::IfOffered, false) => Self::OpportunisticInsecure,
73            (Starttls::IfOffered, true) => Self::Opportunistic,
74            (Starttls::Mandatory, false) => Self::RequiredInsecure,
75            (Starttls::Mandatory, true) => Self::Required,
76        }
77    }
78
79    pub fn allow_insecure(&self) -> bool {
80        match self {
81            Self::OpportunisticInsecure | Self::RequiredInsecure => true,
82            _ => false,
83        }
84    }
85
86    pub fn is_opportunistic(&self) -> bool {
87        match self {
88            Self::OpportunisticInsecure | Self::Opportunistic => true,
89            _ => false,
90        }
91    }
92}
93
94impl Default for Tls {
95    fn default() -> Self {
96        Self::Opportunistic
97    }
98}
99
100/// Selects how TLS is established on an SMTP connection, independently of the
101/// security posture expressed by [Tls].
102#[derive(Deserialize, Serialize, Debug, Clone, PartialEq, Eq, Copy, Default)]
103pub enum TlsMode {
104    /// Begin in cleartext and upgrade via the STARTTLS verb, as governed by
105    /// `enable_tls`.
106    #[default]
107    StartTls,
108    /// The connection is TLS from the first byte (SMTPS). There is no STARTTLS
109    /// negotiation. `enable_tls` is consulted only for certificate validation:
110    /// an `*Insecure` variant skips validation, any other variant (including
111    /// `Disabled`) requires a valid certificate. DANE and MTA-STS do not apply.
112    ImplicitTls,
113}
114
115pub fn parse_openssl_options(option_list: &str) -> anyhow::Result<SslOptions> {
116    let mut result = SslOptions::empty();
117
118    for option in option_list.split('|') {
119        match SslOptions::from_name(option) {
120            Some(opt) => {
121                result.insert(opt);
122            }
123            None => {
124                let mut allowed: Vec<_> = SslOptions::all()
125                    .iter_names()
126                    .map(|(name, _)| format!("`{name}`"))
127                    .collect();
128                allowed.sort();
129                let allowed = allowed.join(", ");
130                anyhow::bail!(
131                    "`{option}` is not a valid SslOption name. \
132                    Possible values are {allowed} joined together by the pipe `|` character."
133                );
134            }
135        }
136    }
137
138    Ok(result)
139}
140
141/// Deserializes a usize field, rejecting a value of zero. Used for fields
142/// that cap how many items of a list are kept, where zero would keep nothing.
143fn deserialize_nonzero_usize<'de, D>(deserializer: D) -> Result<usize, D::Error>
144where
145    D: Deserializer<'de>,
146{
147    use serde::de::Error;
148    let value = usize::deserialize(deserializer)?;
149    if value == 0 {
150        return Err(D::Error::custom("value must be at least 1"));
151    }
152    Ok(value)
153}
154
155fn deserialize_ssl_options<'de, D>(deserializer: D) -> Result<Option<SslOptions>, D::Error>
156where
157    D: Deserializer<'de>,
158{
159    use serde::de::Error;
160    let maybe_options = Option::<String>::deserialize(deserializer)?;
161
162    match maybe_options {
163        None => Ok(None),
164        Some(option_list) => match parse_openssl_options(&option_list) {
165            Ok(options) => Ok(Some(options)),
166            Err(err) => Err(D::Error::custom(format!("{err:#}"))),
167        },
168    }
169}
170
171fn deserialize_supported_ciphersuite<'de, D>(
172    deserializer: D,
173) -> Result<Vec<SupportedCipherSuite>, D::Error>
174where
175    D: Deserializer<'de>,
176{
177    use serde::de::Error;
178    let suites = Vec::<String>::deserialize(deserializer)?;
179    let mut result = vec![];
180
181    for s in suites {
182        match find_rustls_cipher_suite(&s) {
183            Some(s) => {
184                result.push(s);
185            }
186            None => {
187                return Err(D::Error::custom(format!(
188                    "`{s}` is not a valid rustls cipher suite"
189                )));
190            }
191        }
192    }
193
194    Ok(result)
195}
196
197pub fn find_rustls_cipher_suite(name: &str) -> Option<SupportedCipherSuite> {
198    for suite in ALL_CIPHER_SUITES {
199        let sname = format!("{:?}", suite.suite());
200        if sname.eq_ignore_ascii_case(name) {
201            return Some(*suite);
202        }
203    }
204    None
205}
206
207#[derive(Deserialize, Serialize, Debug, Clone, Default, Copy, PartialEq, Eq)]
208#[cfg_attr(feature = "lua", derive(FromLua))]
209pub enum WakeupStrategy {
210    #[default]
211    Aggressive,
212    Relaxed,
213}
214
215#[derive(Deserialize, Serialize, Debug, Clone, Default, Copy, PartialEq, Eq)]
216#[cfg_attr(feature = "lua", derive(FromLua))]
217pub enum MemoryReductionPolicy {
218    #[default]
219    ShrinkDataAndMeta,
220    ShrinkData,
221    NoShrink,
222}
223
224#[derive(Deserialize, Serialize, Debug, Clone, Default, Copy, PartialEq, Eq)]
225#[cfg_attr(feature = "lua", derive(FromLua))]
226pub enum ConfigRefreshStrategy {
227    #[default]
228    Ttl,
229    Epoch,
230}
231
232#[derive(Deserialize, Serialize, Debug, Clone, Default, Copy, PartialEq, Eq)]
233#[cfg_attr(feature = "lua", derive(FromLua))]
234pub enum ReconnectStrategy {
235    /// Close out the current connection session, allowing the maintainer
236    /// to decide about opening a new session and starting with a fresh
237    /// connection plan
238    TerminateSession,
239    /// Try to reconnect to the same host that we were using and where
240    /// we experienced the error
241    ReconnectSameHost,
242    /// Advance to the next host in the connection, if any. If none remain,
243    /// this is equivalent to TerminateSession
244    #[default]
245    ConnectNextHost,
246}
247
248#[derive(Deserialize, Serialize, Debug, Clone, PartialEq)]
249#[cfg_attr(feature = "lua", derive(FromLua))]
250#[serde(deny_unknown_fields)]
251pub struct EgressPathConfig {
252    #[serde(default = "EgressPathConfig::default_connection_limit")]
253    pub connection_limit: LimitSpec,
254
255    #[serde(default)]
256    pub additional_connection_limits: OrderMap<String, LimitSpec>,
257
258    #[serde(default)]
259    pub enable_tls: Tls,
260
261    #[serde(default)]
262    pub tls_mode: TlsMode,
263
264    #[serde(default = "EgressPathConfig::default_enable_mta_sts")]
265    pub enable_mta_sts: bool,
266
267    #[serde(default = "EgressPathConfig::default_enable_dane")]
268    pub enable_dane: bool,
269
270    #[serde(default = "EgressPathConfig::default_enable_pipelining")]
271    pub enable_pipelining: bool,
272
273    #[serde(default = "EgressPathConfig::default_enable_rset")]
274    pub enable_rset: bool,
275
276    #[serde(default)]
277    pub tls_prefer_openssl: bool,
278
279    #[serde(default)]
280    pub tls_certificate: Option<KeySource>,
281
282    #[serde(default)]
283    pub tls_private_key: Option<KeySource>,
284
285    #[serde(default)]
286    pub openssl_cipher_list: Option<String>,
287    #[serde(default)]
288    pub openssl_cipher_suites: Option<String>,
289    #[serde(
290        default,
291        deserialize_with = "deserialize_ssl_options",
292        skip_serializing // FIXME
293    )]
294    pub openssl_options: Option<SslOptions>,
295
296    #[serde(
297        default,
298        deserialize_with = "deserialize_supported_ciphersuite",
299        skip_serializing // FIXME
300    )]
301    pub rustls_cipher_suites: Vec<SupportedCipherSuite>,
302
303    #[serde(flatten)]
304    pub client_timeouts: SmtpClientTimeouts,
305
306    /// How long to wait for an established session to gracefully
307    /// close when the system is shutting down. After this period
308    /// has elapsed, sessions will be aborted.
309    #[serde(default, with = "duration_serde")]
310    pub system_shutdown_timeout: Option<Duration>,
311
312    #[serde(default = "EgressPathConfig::default_max_ready")]
313    pub max_ready: usize,
314
315    #[serde(default = "EgressPathConfig::default_consecutive_connection_failures_before_delay")]
316    pub consecutive_connection_failures_before_delay: usize,
317
318    #[serde(default = "EgressPathConfig::default_smtp_port")]
319    pub smtp_port: u16,
320
321    #[serde(default)]
322    pub smtp_auth_plain_username: Option<String>,
323
324    #[serde(default)]
325    pub smtp_auth_plain_password: Option<KeySource>,
326
327    #[serde(default)]
328    pub allow_smtp_auth_plain_without_tls: bool,
329
330    /// {{since('2026.09.22-a276d4a8')}}
331    /// When false (the default), SMTP AUTH PLAIN will not be attempted over a
332    /// TLS session whose peer certificate was not validated (for example, an
333    /// `OpportunisticInsecure`/`RequiredInsecure` session, or a DANE host whose
334    /// TLSA records are unusable). Set to true to restore the previous behavior
335    /// of sending credentials over any encrypted session.
336    #[serde(default)]
337    pub allow_smtp_auth_plain_without_valid_certificate: bool,
338
339    #[serde(default)]
340    pub max_message_rate: Option<ThrottleSpec>,
341
342    #[serde(default)]
343    pub additional_message_rate_throttles: OrderMap<String, ThrottleSpec>,
344
345    #[serde(default)]
346    pub source_selection_rate: Option<ThrottleSpec>,
347
348    #[serde(default)]
349    pub additional_source_selection_rates: OrderMap<String, ThrottleSpec>,
350
351    #[serde(default)]
352    pub max_connection_rate: Option<ThrottleSpec>,
353
354    #[serde(default = "EgressPathConfig::default_max_deliveries_per_connection")]
355    pub max_deliveries_per_connection: usize,
356
357    #[serde(default = "EgressPathConfig::default_max_recipients_per_batch")]
358    pub max_recipients_per_batch: usize,
359
360    #[serde(default = "CidrSet::default_prohibited_hosts")]
361    pub prohibited_hosts: CidrSet,
362
363    #[serde(default)]
364    pub skip_hosts: CidrSet,
365
366    #[serde(default)]
367    pub ip_lookup_strategy: IpLookupStrategy,
368
369    /// {{since('dev')}}
370    /// The largest number of candidate addresses to retain in the connection
371    /// plan that is built for a delivery attempt. MX resolution expands each
372    /// MX host to every one of its `A`/`AAAA` addresses. Neither DNS nor SMTP
373    /// limits how many MX hosts or addresses the nameservers of a destination
374    /// may answer with, and without this cap the destination's answers would
375    /// dictate the size of the plan directly. Addresses are retained in preference
376    /// order, keeping the most-preferred hosts when the limit truncates. RFC
377    /// 5321 section 5.1 permits a configurable limit on the number of
378    /// alternate addresses that are tried. Must be at least 1.
379    #[serde(
380        default = "EgressPathConfig::default_max_mx_plan_size",
381        deserialize_with = "deserialize_nonzero_usize"
382    )]
383    pub max_mx_plan_size: usize,
384
385    /// {{since('dev')}}
386    /// The largest number of addresses to retain from one MX host, applied
387    /// before `max_mx_plan_size`. Caps the `A`/`AAAA` RRset of one host so that
388    /// a host publishing a very large address set cannot crowd the plan with
389    /// its own addresses at the expense of other hosts. The cap keeps the first
390    /// N addresses of the answer in answer order. Under the default
391    /// `Ipv4AndIpv6` strategy the answer orders `A` records before `AAAA`
392    /// records, and a small value keeps only `A` records. Must be at least 1.
393    #[serde(
394        default = "EgressPathConfig::default_max_mx_addresses_per_host",
395        deserialize_with = "deserialize_nonzero_usize"
396    )]
397    pub max_mx_addresses_per_host: usize,
398
399    #[serde(default)]
400    pub ehlo_domain: Option<String>,
401
402    // TODO: decide if we want to keep this and then document
403    #[serde(default)]
404    pub aggressive_connection_opening: bool,
405
406    /// How long to wait between calls to get_egress_path_config for
407    /// any given ready queue. Making this longer uses fewer
408    /// resources (in aggregate) but means that it will take longer
409    /// to detect and adjust to changes in the queue configuration.
410    #[serde(
411        default = "EgressPathConfig::default_refresh_interval",
412        with = "duration_serde"
413    )]
414    pub refresh_interval: Duration,
415    #[serde(default)]
416    pub refresh_strategy: ConfigRefreshStrategy,
417
418    #[serde(default)]
419    pub dispatcher_wakeup_strategy: WakeupStrategy,
420    #[serde(default)]
421    pub maintainer_wakeup_strategy: WakeupStrategy,
422
423    /// Specify an explicit provider name that should apply to this
424    /// path. The provider name will be used when computing metrics
425    /// rollups by provider. If omitted, then
426    #[serde(default)]
427    pub provider_name: Option<String>,
428
429    /// If set, a process-local cache will be used to remember if
430    /// a site has broken TLS for the duration specified.  Once
431    /// encountered, we will pretend that EHLO didn't advertise STARTTLS
432    /// on subsequent connection attempts.
433    #[serde(default, with = "duration_serde")]
434    pub remember_broken_tls: Option<Duration>,
435
436    /// If true, when a TLS handshake fails and TLS is set to
437    /// opportunistic, we will re-connect to that host with
438    /// TLS disabled.
439    #[serde(default)]
440    pub opportunistic_tls_reconnect_on_failed_handshake: bool,
441
442    /// If true, rather than ESMTP, use the LMTP protocol
443    #[serde(default)]
444    pub use_lmtp: bool,
445
446    /// How to behave if we experience either a 421 response, an IO Error,
447    /// or a timeout while talking to the peer.
448    #[serde(default)]
449    pub reconnect_strategy: ReconnectStrategy,
450
451    /// Which thread pool to use for processing the ready queue
452    #[serde(default)]
453    pub readyq_pool_name: Option<String>,
454
455    /// What to do to newly inserted messages when memory is low
456    #[serde(default)]
457    pub low_memory_reduction_policy: MemoryReductionPolicy,
458
459    /// What to do to newly inserted messages when memory is over the soft limit
460    #[serde(default)]
461    pub no_memory_reduction_policy: MemoryReductionPolicy,
462
463    /// If we experience a transport error during SMTP, should we retry the
464    /// current message on the next host in the connection plan, or
465    /// immediately consider it a transient failure for that message?
466    #[serde(default)]
467    pub try_next_host_on_transport_error: bool,
468
469    /// If true, don't check for 8bit compatibility issues during
470    /// sending, instead, leave it to the remote host to raise
471    /// an error.
472    #[serde(default)]
473    pub ignore_8bit_checks: bool,
474
475    /// When set, dispatcher tasks for this egress path that fail to
476    /// make any forward progress for this duration are aborted by the
477    /// maintainer. When omitted the effective value is derived at
478    /// runtime from the protocol:
479    ///   * SMTP / Xfer: max(2 * longest of mail_from, rcpt_to, data,
480    ///     data_dot timeouts, 60s)
481    ///   * Lua / HttpInjectionGenerator / DeferredSmtpInjection: 600s
482    ///
483    /// Users with a large `max_batch_latency` should set this
484    /// explicitly so the watchdog does not flag batch accumulation.
485    #[serde(default, with = "duration_serde")]
486    pub dispatcher_progress_watchdog_timeout: Option<Duration>,
487}
488
489#[cfg(feature = "lua")]
490impl LuaUserData for EgressPathConfig {
491    fn add_methods<M: mlua::UserDataMethods<Self>>(methods: &mut M) {
492        config::impl_pairs_and_index(methods);
493    }
494}
495
496impl Default for EgressPathConfig {
497    fn default() -> Self {
498        Self {
499            connection_limit: Self::default_connection_limit(),
500            tls_prefer_openssl: false,
501            enable_tls: Tls::default(),
502            tls_mode: TlsMode::default(),
503            enable_mta_sts: Self::default_enable_mta_sts(),
504            enable_dane: Self::default_enable_dane(),
505            enable_rset: Self::default_enable_rset(),
506            enable_pipelining: Self::default_enable_pipelining(),
507            max_ready: Self::default_max_ready(),
508            consecutive_connection_failures_before_delay:
509                Self::default_consecutive_connection_failures_before_delay(),
510            smtp_port: Self::default_smtp_port(),
511            max_message_rate: None,
512            max_connection_rate: None,
513            max_deliveries_per_connection: Self::default_max_deliveries_per_connection(),
514            max_recipients_per_batch: Self::default_max_recipients_per_batch(),
515            client_timeouts: SmtpClientTimeouts::default(),
516            system_shutdown_timeout: None,
517            prohibited_hosts: CidrSet::default_prohibited_hosts(),
518            skip_hosts: CidrSet::default(),
519            ehlo_domain: None,
520            allow_smtp_auth_plain_without_tls: false,
521            allow_smtp_auth_plain_without_valid_certificate: false,
522            smtp_auth_plain_username: None,
523            smtp_auth_plain_password: None,
524            aggressive_connection_opening: false,
525            rustls_cipher_suites: vec![],
526            tls_certificate: None,
527            tls_private_key: None,
528            openssl_cipher_list: None,
529            openssl_cipher_suites: None,
530            openssl_options: None,
531            refresh_interval: Self::default_refresh_interval(),
532            refresh_strategy: ConfigRefreshStrategy::default(),
533            additional_message_rate_throttles: OrderMap::default(),
534            additional_connection_limits: OrderMap::default(),
535            source_selection_rate: None,
536            additional_source_selection_rates: OrderMap::default(),
537            provider_name: None,
538            remember_broken_tls: None,
539            opportunistic_tls_reconnect_on_failed_handshake: false,
540            use_lmtp: false,
541            reconnect_strategy: ReconnectStrategy::default(),
542            readyq_pool_name: None,
543            low_memory_reduction_policy: MemoryReductionPolicy::default(),
544            no_memory_reduction_policy: MemoryReductionPolicy::default(),
545            maintainer_wakeup_strategy: WakeupStrategy::default(),
546            dispatcher_wakeup_strategy: WakeupStrategy::default(),
547            try_next_host_on_transport_error: false,
548            ignore_8bit_checks: false,
549            ip_lookup_strategy: IpLookupStrategy::default(),
550            max_mx_plan_size: Self::default_max_mx_plan_size(),
551            max_mx_addresses_per_host: Self::default_max_mx_addresses_per_host(),
552            dispatcher_progress_watchdog_timeout: None,
553        }
554    }
555}
556
557impl EgressPathConfig {
558    fn default_connection_limit() -> LimitSpec {
559        LimitSpec::new(32)
560    }
561
562    fn default_enable_mta_sts() -> bool {
563        true
564    }
565
566    fn default_enable_pipelining() -> bool {
567        true
568    }
569
570    fn default_enable_rset() -> bool {
571        true
572    }
573
574    fn default_enable_dane() -> bool {
575        false
576    }
577
578    fn default_max_ready() -> usize {
579        1024
580    }
581
582    fn default_consecutive_connection_failures_before_delay() -> usize {
583        100
584    }
585
586    fn default_smtp_port() -> u16 {
587        25
588    }
589
590    fn default_max_deliveries_per_connection() -> usize {
591        1024
592    }
593
594    fn default_max_recipients_per_batch() -> usize {
595        100
596    }
597
598    fn default_max_mx_plan_size() -> usize {
599        50
600    }
601
602    fn default_max_mx_addresses_per_host() -> usize {
603        10
604    }
605
606    fn default_refresh_interval() -> Duration {
607        Duration::from_secs(60)
608    }
609
610    /// Compute the steady-state ceilings implied by this
611    /// configuration. Per-axis, each ceiling carries a tag for which
612    /// configuration term produced it, so operators can see which
613    /// knob to turn.
614    ///
615    /// If `additional` is supplied, its ceilings are merged in via
616    /// `EffectiveConstraints::merge`. This is the entry point for
617    /// folding in constraints from other configuration layers, such
618    /// as the scheduled-queue rate from `QueueConfig`.
619    pub fn compute_constraints(
620        &self,
621        additional: Option<&EffectiveConstraints>,
622    ) -> EffectiveConstraints {
623        let mut constraints = self.compute_path_constraints();
624        if let Some(extra) = additional {
625            constraints.merge(extra);
626        }
627        constraints
628    }
629
630    fn compute_path_constraints(&self) -> EffectiveConstraints {
631        let max_concurrent_dispatchers = {
632            let mut best = EffectiveCeiling {
633                value: self.connection_limit.limit as f64,
634                source: CeilingSource::Primary,
635                display: self.connection_limit.limit.to_string(),
636            };
637            for (name, spec) in &self.additional_connection_limits {
638                let value = spec.limit as f64;
639                if value < best.value {
640                    best = EffectiveCeiling {
641                        value,
642                        source: CeilingSource::Additional { name: name.clone() },
643                        display: spec.limit.to_string(),
644                    };
645                }
646            }
647            best
648        };
649
650        // Compute the message-rate ceiling across the primary,
651        // additional throttles, and the synthetic K × C ceiling.
652        let mut msg_candidates: Vec<EffectiveCeiling> = vec![];
653        if let Some(spec) = &self.max_message_rate {
654            msg_candidates.push(throttle_ceiling(spec, CeilingSource::Primary));
655        }
656        for (name, spec) in &self.additional_message_rate_throttles {
657            msg_candidates.push(throttle_ceiling(
658                spec,
659                CeilingSource::Additional { name: name.clone() },
660            ));
661        }
662        if let Some(spec) = &self.max_connection_rate {
663            // K × C ceiling: every connection delivers at most
664            // max_deliveries_per_connection messages, so total msg
665            // rate cannot exceed (max_deliveries_per_connection) times
666            // the connection-establishment rate. The display shows
667            // both the factors and the computed total so operators
668            // don't have to do the arithmetic mentally for cases
669            // like 32 × 50/s.
670            let k = self.max_deliveries_per_connection as u64;
671            let total = ThrottleSpec {
672                limit: k.saturating_mul(spec.limit),
673                period: spec.period,
674                max_burst: None,
675                force_local: false,
676            };
677            msg_candidates.push(EffectiveCeiling {
678                value: throttle_rate_per_sec(spec) * k as f64,
679                source: CeilingSource::ReconnectCycling,
680                display: format!("{k} × {spec} = {total}"),
681            });
682        }
683        // total_cmp gives a total ordering even for NaN, so a malformed
684        // candidate cannot cause a panic here. NaN sorts greater than
685        // any finite value, so it naturally loses the min_by.
686        let max_message_rate = msg_candidates
687            .iter()
688            .min_by(|a, b| a.value.total_cmp(&b.value))
689            .cloned();
690
691        // If max_message_rate is explicitly configured but a
692        // different term (typically the synthetic reconnect-cycling
693        // ceiling) wins the minimum, record the declared rate so
694        // renderers can show an "effectively unreachable" annotation.
695        // Preserve the operator's original units via ThrottleSpec's
696        // Display impl.
697        let max_message_rate_declared = match (&max_message_rate, &self.max_message_rate) {
698            (Some(ceiling), Some(declared))
699                if !matches!(ceiling.source, CeilingSource::Primary) =>
700            {
701                Some(declared.to_string())
702            }
703            _ => None,
704        };
705
706        let max_connection_rate = self
707            .max_connection_rate
708            .as_ref()
709            .map(|spec| throttle_ceiling(spec, CeilingSource::Primary));
710
711        let max_source_selection_rate = {
712            let mut candidates: Vec<EffectiveCeiling> = vec![];
713            if let Some(spec) = &self.source_selection_rate {
714                candidates.push(throttle_ceiling(spec, CeilingSource::Primary));
715            }
716            for (name, spec) in &self.additional_source_selection_rates {
717                candidates.push(throttle_ceiling(
718                    spec,
719                    CeilingSource::Additional { name: name.clone() },
720                ));
721            }
722            candidates
723                .into_iter()
724                .min_by(|a, b| a.value.total_cmp(&b.value))
725        };
726
727        EffectiveConstraints {
728            max_concurrent_dispatchers,
729            max_message_rate,
730            max_message_rate_declared,
731            max_connection_rate,
732            max_source_selection_rate,
733        }
734    }
735}
736
737fn throttle_rate_per_sec(spec: &ThrottleSpec) -> f64 {
738    spec.limit as f64 / spec.period as f64
739}
740
741fn throttle_ceiling(spec: &ThrottleSpec, source: CeilingSource) -> EffectiveCeiling {
742    EffectiveCeiling {
743        value: throttle_rate_per_sec(spec),
744        source,
745        display: spec.to_string(),
746    }
747}
748
749/// Steady-state ceiling for a single throughput axis, with a tag
750/// for which configuration term produced it.
751///
752/// {{since('2026.09.22-a276d4a8')}}
753#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, ToSchema)]
754pub struct EffectiveCeiling {
755    /// Canonical value. For rate axes: events per second; useful
756    /// for numeric comparison. For concurrency: a count.
757    pub value: f64,
758    pub source: CeilingSource,
759    /// Pre-formatted human display preserving the operator's
760    /// original configuration units. A rate configured as
761    /// `10000/hr` renders here as `10000/h` rather than `2.78/s`.
762    /// For concurrency, the integer count. For the synthetic
763    /// reconnect-cycling ceiling, the formula
764    /// `max_deliveries_per_connection × <connection_rate>`.
765    pub display: String,
766}
767
768/// Which configuration term produced an `EffectiveCeiling`.
769///
770/// {{since('2026.09.22-a276d4a8')}}
771#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, ToSchema)]
772#[serde(tag = "kind", rename_all = "snake_case")]
773pub enum CeilingSource {
774    /// The primary configured term for this axis:
775    /// `connection_limit`, `max_message_rate`,
776    /// `max_connection_rate`, or `source_selection_rate`.
777    Primary,
778    /// A named entry from the corresponding `additional_*` map.
779    Additional { name: String },
780    /// Synthetic ceiling formed from
781    /// `max_deliveries_per_connection × max_connection_rate`.
782    /// Applies only to the message-rate axis: each connection
783    /// delivers at most `max_deliveries_per_connection` messages
784    /// before reconnecting, and new connections are throttled by
785    /// `max_connection_rate`, so the product is a hard ceiling on
786    /// system-wide message rate independent of `max_message_rate`.
787    ReconnectCycling,
788    /// A constraint contributed from a configuration layer outside
789    /// the egress path config. `name` is a free-form, human-readable
790    /// description of where the constraint came from (for example,
791    /// `"scheduled queue max_message_rate"`).
792    Other { name: String },
793}
794
795/// Summary of an MX resolution attempt for a destination.
796///
797/// {{since('2026.09.22-a276d4a8')}}
798#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, ToSchema)]
799pub struct MxResolution {
800    /// Canonical site name; the value used as the queue grouping
801    /// key for this destination.
802    pub site_name: String,
803
804    /// MX hostnames grouped by preference. Lower preference is
805    /// preferred. Empty when DNS returned no MX records and the
806    /// resolver synthesised A/AAAA against `domain` directly.
807    pub by_preference: BTreeMap<u16, Vec<String>>,
808
809    /// True if real MX records were found in DNS. False when the
810    /// resolver synthesised an A/AAAA lookup against the domain.
811    pub is_mx: bool,
812
813    /// True if the destination was a domain literal like `[1.2.3.4]`.
814    pub is_domain_literal: bool,
815
816    /// True if the DNS result was DNSSEC validated.
817    pub is_secure: bool,
818}
819
820impl From<&MailExchanger> for MxResolution {
821    fn from(mx: &MailExchanger) -> Self {
822        Self {
823            site_name: mx.site_name.clone(),
824            by_preference: mx.by_pref.clone(),
825            is_mx: mx.is_mx,
826            is_domain_literal: mx.is_domain_literal,
827            is_secure: mx.is_secure,
828        }
829    }
830}
831
832impl MxResolution {
833    /// Render a one-line header summarising the MX result, plus an
834    /// indented preference→host listing beneath. Shared by
835    /// `kcli inspect-ready-q` and `kcli resolve-egress-path` so the
836    /// two surfaces produce identical output for the same input.
837    pub fn render(&self, out: &mut dyn Write) -> std::fmt::Result {
838        let mut flags: Vec<&str> = vec![];
839        if !self.is_mx {
840            flags.push("synthesised");
841        }
842        if self.is_domain_literal {
843            flags.push("domain literal");
844        }
845        if self.is_secure {
846            flags.push("dnssec verified");
847        }
848        write!(out, "mx (site: {}", self.site_name)?;
849        if !flags.is_empty() {
850            write!(out, ", {}", flags.join(", "))?;
851        }
852        writeln!(out, "):")?;
853        for (pref, hosts) in &self.by_preference {
854            for host in hosts {
855                writeln!(out, "  {pref:>4}  {host}")?;
856            }
857        }
858        Ok(())
859    }
860
861    pub fn to_human_string(&self) -> String {
862        let mut s = String::new();
863        let _ = self.render(&mut s);
864        s
865    }
866}
867
868/// Steady-state ceilings implied by an `EgressPathConfig`. Each
869/// ceiling carries a tag for which configuration term produced it.
870///
871/// {{since('2026.09.22-a276d4a8')}}
872///
873/// These are per-queue ceilings; shared limits in `additional_*`
874/// maps are reported at their full value and may be tighter in
875/// practice when the bucket is contended.
876#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, ToSchema)]
877pub struct EffectiveConstraints {
878    pub max_concurrent_dispatchers: EffectiveCeiling,
879    /// None when neither `max_message_rate` nor any
880    /// `additional_message_rate_throttles` entry nor
881    /// `max_connection_rate` is configured.
882    pub max_message_rate: Option<EffectiveCeiling>,
883    /// Pre-formatted display of the declared `max_message_rate` when
884    /// a different term (typically `ReconnectCycling`) wins the
885    /// minimum. Lets renderers show a "declared but unreachable"
886    /// annotation. Uses the operator's original units.
887    pub max_message_rate_declared: Option<String>,
888    pub max_connection_rate: Option<EffectiveCeiling>,
889    pub max_source_selection_rate: Option<EffectiveCeiling>,
890}
891
892impl EffectiveConstraints {
893    /// Render a human-readable multi-line block. The same formatting
894    /// is used by `kcli inspect-ready-q` and by the
895    /// `resolve-shaping-domain` script, so operators see the same
896    /// output regardless of where they retrieved the config.
897    pub fn render(&self, out: &mut dyn Write) -> std::fmt::Result {
898        let label_axis = |w: &mut dyn Write, label: &str, value: &str| -> std::fmt::Result {
899            writeln!(w, "  {label:<24}{value}")
900        };
901        let label_source =
902            |w: &mut dyn Write, src: &CeilingSource, primary: &str| -> std::fmt::Result {
903                let s = match src {
904                    CeilingSource::Primary => primary,
905                    CeilingSource::Additional { name } => name.as_str(),
906                    CeilingSource::ReconnectCycling => {
907                        "max_deliveries_per_connection × max_connection_rate"
908                    }
909                    CeilingSource::Other { name } => name.as_str(),
910                };
911                writeln!(w, "    source: {s}")
912            };
913
914        writeln!(out, "ceilings:")?;
915
916        label_axis(
917            out,
918            "concurrent dispatchers:",
919            &self.max_concurrent_dispatchers.display,
920        )?;
921        label_source(
922            out,
923            &self.max_concurrent_dispatchers.source,
924            "connection_limit",
925        )?;
926
927        if let Some(c) = &self.max_message_rate {
928            label_axis(out, "message rate:", &c.display)?;
929            label_source(out, &c.source, "max_message_rate")?;
930            if let Some(declared) = &self.max_message_rate_declared {
931                writeln!(
932                    out,
933                    "    declared: max_message_rate = {declared} ← effectively unreachable"
934                )?;
935            }
936        }
937
938        if let Some(c) = &self.max_connection_rate {
939            label_axis(out, "connection rate:", &c.display)?;
940            label_source(out, &c.source, "max_connection_rate")?;
941        }
942
943        if let Some(c) = &self.max_source_selection_rate {
944            label_axis(out, "source selection rate:", &c.display)?;
945            label_source(out, &c.source, "source_selection_rate")?;
946        }
947
948        Ok(())
949    }
950
951    pub fn to_human_string(&self) -> String {
952        let mut s = String::new();
953        // std::fmt::Write into a String cannot fail in practice;
954        // swallow the error to avoid a panic site here.
955        let _ = self.render(&mut s);
956        s
957    }
958
959    /// Fold another `EffectiveConstraints` into this one by taking
960    /// the per-axis minimum. The losing ceiling is shadowed; the
961    /// winner's `source` tag is preserved. The
962    /// `max_message_rate_declared` annotation is re-evaluated so a
963    /// rate that is now shadowed by an external source gets the
964    /// "declared but unreachable" treatment.
965    pub fn merge(&mut self, other: &EffectiveConstraints) {
966        // Remember the path's declared rate before merging; if a
967        // tighter external source wins, we need to surface the
968        // declared value as the unreachable annotation.
969        let path_declared = self
970            .max_message_rate
971            .as_ref()
972            .filter(|c| matches!(c.source, CeilingSource::Primary))
973            .map(|c| c.display.clone())
974            .or_else(|| self.max_message_rate_declared.clone());
975
976        merge_axis(
977            &mut self.max_concurrent_dispatchers,
978            &other.max_concurrent_dispatchers,
979        );
980        merge_optional(&mut self.max_message_rate, &other.max_message_rate);
981        merge_optional(&mut self.max_connection_rate, &other.max_connection_rate);
982        merge_optional(
983            &mut self.max_source_selection_rate,
984            &other.max_source_selection_rate,
985        );
986
987        if let Some(merged) = &self.max_message_rate {
988            if !matches!(merged.source, CeilingSource::Primary) {
989                if let Some(declared) = path_declared {
990                    self.max_message_rate_declared = Some(declared);
991                }
992            }
993        }
994    }
995}
996
997fn merge_axis(a: &mut EffectiveCeiling, b: &EffectiveCeiling) {
998    if b.value.total_cmp(&a.value).is_lt() {
999        *a = b.clone();
1000    }
1001}
1002
1003fn merge_optional(a: &mut Option<EffectiveCeiling>, b: &Option<EffectiveCeiling>) {
1004    match (a.as_mut(), b) {
1005        (Some(av), Some(bv)) if bv.value.total_cmp(&av.value).is_lt() => *av = bv.clone(),
1006        (None, Some(bv)) => *a = Some(bv.clone()),
1007        _ => {}
1008    }
1009}
1010
1011#[cfg(test)]
1012mod tls_tests {
1013    use super::*;
1014
1015    const ALL: [Tls; 5] = [
1016        Tls::Disabled,
1017        Tls::OpportunisticInsecure,
1018        Tls::Opportunistic,
1019        Tls::RequiredInsecure,
1020        Tls::Required,
1021    ];
1022
1023    #[test]
1024    fn at_least_never_weakens_either_axis() {
1025        for a in ALL {
1026            for b in ALL {
1027                let result = a.at_least(b);
1028                k9::assert_equal!(result, b.at_least(a));
1029                let (starttls, verify) = result.axes();
1030                for input in [a, b] {
1031                    let (in_starttls, in_verify) = input.axes();
1032                    assert!(
1033                        starttls >= in_starttls,
1034                        "{a:?}.at_least({b:?}) = {result:?}"
1035                    );
1036                    assert!(verify || !in_verify, "{a:?}.at_least({b:?}) = {result:?}");
1037                }
1038            }
1039            k9::assert_equal!(a.at_least(a), a);
1040        }
1041    }
1042
1043    #[test]
1044    fn published_policy_floors() {
1045        // `RequiredInsecure` as the floor models an unusable DANE TLSA record.
1046        k9::assert_equal!(
1047            Tls::Opportunistic.at_least(Tls::RequiredInsecure),
1048            Tls::Required
1049        );
1050        k9::assert_equal!(Tls::Required.at_least(Tls::RequiredInsecure), Tls::Required);
1051        k9::assert_equal!(
1052            Tls::OpportunisticInsecure.at_least(Tls::RequiredInsecure),
1053            Tls::RequiredInsecure
1054        );
1055        k9::assert_equal!(
1056            Tls::Disabled.at_least(Tls::RequiredInsecure),
1057            Tls::RequiredInsecure
1058        );
1059        // A floor of `Required` models MTA-STS enforce or a usable DANE
1060        // TLSA record, both of which mandate verified STARTTLS. Since
1061        // `Required` is already the strongest value on both axes, every
1062        // local policy raised to it ends up `Required`, regardless of how
1063        // weak the local policy started out.
1064        for local in ALL {
1065            k9::assert_equal!(local.at_least(Tls::Required), Tls::Required);
1066        }
1067    }
1068}
1069
1070#[cfg(test)]
1071mod constraints_tests {
1072    use super::*;
1073
1074    fn cfg() -> EgressPathConfig {
1075        EgressPathConfig::default()
1076    }
1077
1078    /// Derive the canonical numeric value from the same display
1079    /// string the production code emits. A bare integer is a
1080    /// concurrency count; a `<limit>/<period>` form is a rate (in
1081    /// events per second after normalization); a `K × <rate> = <rate>`
1082    /// form is the reconnect-cycling formula and uses the total on
1083    /// the right side. Keeps tests as declarative `display`
1084    /// strings.
1085    fn value_from_display(display: &str) -> f64 {
1086        if let Some((_, total)) = display.split_once(" = ") {
1087            let spec = ThrottleSpec::try_from(total).unwrap();
1088            return spec.limit as f64 / spec.period as f64;
1089        }
1090        if let Ok(spec) = ThrottleSpec::try_from(display) {
1091            return spec.limit as f64 / spec.period as f64;
1092        }
1093        display.parse::<u64>().unwrap() as f64
1094    }
1095
1096    fn primary(display: &str) -> EffectiveCeiling {
1097        EffectiveCeiling {
1098            value: value_from_display(display),
1099            source: CeilingSource::Primary,
1100            display: display.to_string(),
1101        }
1102    }
1103
1104    fn additional(name: &str, display: &str) -> EffectiveCeiling {
1105        EffectiveCeiling {
1106            value: value_from_display(display),
1107            source: CeilingSource::Additional {
1108                name: name.to_string(),
1109            },
1110            display: display.to_string(),
1111        }
1112    }
1113
1114    fn other(name: &str, display: &str) -> EffectiveCeiling {
1115        EffectiveCeiling {
1116            value: value_from_display(display),
1117            source: CeilingSource::Other {
1118                name: name.to_string(),
1119            },
1120            display: display.to_string(),
1121        }
1122    }
1123
1124    fn reconnect_cycling(display: &str) -> EffectiveCeiling {
1125        EffectiveCeiling {
1126            value: value_from_display(display),
1127            source: CeilingSource::ReconnectCycling,
1128            display: display.to_string(),
1129        }
1130    }
1131
1132    fn throttle(s: &str) -> ThrottleSpec {
1133        ThrottleSpec::try_from(s).unwrap()
1134    }
1135
1136    #[test]
1137    fn rust_compact_round_trips() {
1138        // Calling the compact TOML renderer directly on a typed
1139        // EgressPathConfig preserves the array vs. map shape of
1140        // each field, so the rendered text deserializes back into
1141        // an equivalent EgressPathConfig.
1142        let original = EgressPathConfig::default();
1143        let s = mod_serde::toml_encode_pretty_compact(&original).unwrap();
1144        let parsed: EgressPathConfig = toml::from_str(&s).unwrap();
1145        assert_eq!(parsed, original);
1146    }
1147
1148    #[test]
1149    fn zero_mx_plan_limits_are_rejected() {
1150        // A zero limit would silently empty the connection plan and fail
1151        // every delivery; it must be a configuration error instead.
1152        let err = toml::from_str::<EgressPathConfig>("max_mx_plan_size = 0").unwrap_err();
1153        k9::snapshot!(
1154            err.to_string(),
1155            "
1156TOML parse error at line 1, column 20
1157  |
11581 | max_mx_plan_size = 0
1159  |                    ^
1160value must be at least 1
1161
1162"
1163        );
1164        let err = toml::from_str::<EgressPathConfig>("max_mx_addresses_per_host = 0").unwrap_err();
1165        k9::snapshot!(
1166            err.to_string(),
1167            "
1168TOML parse error at line 1, column 29
1169  |
11701 | max_mx_addresses_per_host = 0
1171  |                             ^
1172value must be at least 1
1173
1174"
1175        );
1176    }
1177
1178    #[test]
1179    fn defaults_only_concurrency() {
1180        assert_eq!(
1181            cfg().compute_constraints(None),
1182            EffectiveConstraints {
1183                max_concurrent_dispatchers: primary("32"),
1184                max_message_rate: None,
1185                max_message_rate_declared: None,
1186                max_connection_rate: None,
1187                max_source_selection_rate: None,
1188            }
1189        );
1190    }
1191
1192    #[test]
1193    fn additional_connection_limit_wins() {
1194        let mut p = cfg();
1195        p.additional_connection_limits
1196            .insert("provider_shared".to_string(), LimitSpec::new(10));
1197        assert_eq!(
1198            p.compute_constraints(None),
1199            EffectiveConstraints {
1200                max_concurrent_dispatchers: additional("provider_shared", "10"),
1201                max_message_rate: None,
1202                max_message_rate_declared: None,
1203                max_connection_rate: None,
1204                max_source_selection_rate: None,
1205            }
1206        );
1207    }
1208
1209    #[test]
1210    fn primary_connection_limit_wins_when_smaller() {
1211        let mut p = cfg();
1212        p.connection_limit = LimitSpec::new(4);
1213        p.additional_connection_limits
1214            .insert("large_pool".to_string(), LimitSpec::new(100));
1215        assert_eq!(
1216            p.compute_constraints(None),
1217            EffectiveConstraints {
1218                max_concurrent_dispatchers: primary("4"),
1219                max_message_rate: None,
1220                max_message_rate_declared: None,
1221                max_connection_rate: None,
1222                max_source_selection_rate: None,
1223            }
1224        );
1225    }
1226
1227    #[test]
1228    fn primary_message_rate_only() {
1229        let mut p = cfg();
1230        p.max_message_rate = Some(throttle("1000/s"));
1231        assert_eq!(
1232            p.compute_constraints(None),
1233            EffectiveConstraints {
1234                max_concurrent_dispatchers: primary("32"),
1235                max_message_rate: Some(primary("1000/s")),
1236                max_message_rate_declared: None,
1237                max_connection_rate: None,
1238                max_source_selection_rate: None,
1239            }
1240        );
1241    }
1242
1243    #[test]
1244    fn additional_message_rate_wins() {
1245        let mut p = cfg();
1246        p.max_message_rate = Some(throttle("1000/s"));
1247        p.additional_message_rate_throttles
1248            .insert("provider_cap".to_string(), throttle("250/s"));
1249        assert_eq!(
1250            p.compute_constraints(None),
1251            EffectiveConstraints {
1252                max_concurrent_dispatchers: primary("32"),
1253                max_message_rate: Some(additional("provider_cap", "250/s")),
1254                max_message_rate_declared: Some("1000/s".to_string()),
1255                max_connection_rate: None,
1256                max_source_selection_rate: None,
1257            }
1258        );
1259    }
1260
1261    #[test]
1262    fn additional_message_rate_throttles_mixed_periods() {
1263        // Three additional throttles with mixed periods: the smallest
1264        // canonical rate (10/hr ≈ 0.0028 msg/s) must win the min,
1265        // even though numerically 5/s has the smallest *literal*
1266        // limit. This exercises the period-normalized comparison.
1267        let mut p = cfg();
1268        p.additional_message_rate_throttles
1269            .insert("per_hour".to_string(), throttle("10/hr"));
1270        p.additional_message_rate_throttles
1271            .insert("per_minute".to_string(), throttle("8/min"));
1272        p.additional_message_rate_throttles
1273            .insert("per_second".to_string(), throttle("5/s"));
1274        assert_eq!(
1275            p.compute_constraints(None),
1276            EffectiveConstraints {
1277                max_concurrent_dispatchers: primary("32"),
1278                max_message_rate: Some(additional("per_hour", "10/h")),
1279                max_message_rate_declared: None,
1280                max_connection_rate: None,
1281                max_source_selection_rate: None,
1282            }
1283        );
1284    }
1285
1286    #[test]
1287    fn hourly_rate_preserves_units() {
1288        // Operator-configured "10000/hr" should round-trip as
1289        // "10000/h" via ThrottleSpec::Display, not collapse to a
1290        // per-second decimal like "2.78/s". Canonical value is
1291        // still events per second for numeric comparison.
1292        let mut p = cfg();
1293        p.max_message_rate = Some(throttle("10000/hr"));
1294        assert_eq!(
1295            p.compute_constraints(None),
1296            EffectiveConstraints {
1297                max_concurrent_dispatchers: primary("32"),
1298                max_message_rate: Some(primary("10000/h")),
1299                max_message_rate_declared: None,
1300                max_connection_rate: None,
1301                max_source_selection_rate: None,
1302            }
1303        );
1304    }
1305
1306    #[test]
1307    fn reconnect_cycling_wins() {
1308        // K = 10, C = 10/s => 100 msg/s ceiling, smaller than the
1309        // 1000/s max_message_rate.
1310        let mut p = cfg();
1311        p.max_message_rate = Some(throttle("1000/s"));
1312        p.max_deliveries_per_connection = 10;
1313        p.max_connection_rate = Some(throttle("10/s"));
1314        assert_eq!(
1315            p.compute_constraints(None),
1316            EffectiveConstraints {
1317                max_concurrent_dispatchers: primary("32"),
1318                max_message_rate: Some(reconnect_cycling("10 × 10/s = 100/s")),
1319                max_message_rate_declared: Some("1000/s".to_string()),
1320                max_connection_rate: Some(primary("10/s")),
1321                max_source_selection_rate: None,
1322            }
1323        );
1324    }
1325
1326    #[test]
1327    fn reconnect_cycling_does_not_bind_with_large_k() {
1328        // K = 1024 (default), C = 10/s => 10240 msg/s synthetic,
1329        // not binding when max_message_rate is 1000/s. Primary wins
1330        // and no declared-but-unreachable annotation is needed.
1331        let mut p = cfg();
1332        p.max_message_rate = Some(throttle("1000/s"));
1333        p.max_connection_rate = Some(throttle("10/s"));
1334        assert_eq!(
1335            p.compute_constraints(None),
1336            EffectiveConstraints {
1337                max_concurrent_dispatchers: primary("32"),
1338                max_message_rate: Some(primary("1000/s")),
1339                max_message_rate_declared: None,
1340                max_connection_rate: Some(primary("10/s")),
1341                max_source_selection_rate: None,
1342            }
1343        );
1344    }
1345
1346    #[test]
1347    fn reconnect_cycling_alone_sets_message_rate() {
1348        // No explicit max_message_rate, but K × C is still a
1349        // computable ceiling and should be reported. Nothing was
1350        // declared, so no annotation.
1351        let mut p = cfg();
1352        p.max_deliveries_per_connection = 5;
1353        p.max_connection_rate = Some(throttle("2/s"));
1354        assert_eq!(
1355            p.compute_constraints(None),
1356            EffectiveConstraints {
1357                max_concurrent_dispatchers: primary("32"),
1358                max_message_rate: Some(reconnect_cycling("5 × 2/s = 10/s")),
1359                max_message_rate_declared: None,
1360                max_connection_rate: Some(primary("2/s")),
1361                max_source_selection_rate: None,
1362            }
1363        );
1364    }
1365
1366    #[test]
1367    fn merge_external_message_rate_wins() {
1368        // Path config declares max_message_rate = 1000/s, but an
1369        // external source (e.g. a scheduled queue) declares 100/s.
1370        // The merged result picks the external term and surfaces the
1371        // path's declared rate as "effectively unreachable".
1372        let mut p = cfg();
1373        p.max_message_rate = Some(throttle("1000/s"));
1374        let external = EffectiveConstraints {
1375            max_concurrent_dispatchers: EffectiveCeiling {
1376                value: f64::INFINITY,
1377                source: CeilingSource::Other {
1378                    name: "queue config".to_string(),
1379                },
1380                display: "∞".to_string(),
1381            },
1382            max_message_rate: Some(other("scheduled queue max_message_rate", "100/s")),
1383            max_message_rate_declared: None,
1384            max_connection_rate: None,
1385            max_source_selection_rate: None,
1386        };
1387        assert_eq!(
1388            p.compute_constraints(Some(&external)),
1389            EffectiveConstraints {
1390                max_concurrent_dispatchers: primary("32"),
1391                max_message_rate: Some(other("scheduled queue max_message_rate", "100/s")),
1392                max_message_rate_declared: Some("1000/s".to_string()),
1393                max_connection_rate: None,
1394                max_source_selection_rate: None,
1395            }
1396        );
1397    }
1398
1399    #[test]
1400    fn merge_external_does_not_bind() {
1401        // Path config declares max_message_rate = 100/s; external
1402        // declares 1000/s. Path's primary wins; no annotation.
1403        let mut p = cfg();
1404        p.max_message_rate = Some(throttle("100/s"));
1405        let external = EffectiveConstraints {
1406            max_concurrent_dispatchers: EffectiveCeiling {
1407                value: f64::INFINITY,
1408                source: CeilingSource::Other {
1409                    name: "queue config".to_string(),
1410                },
1411                display: "∞".to_string(),
1412            },
1413            max_message_rate: Some(other("scheduled queue max_message_rate", "1000/s")),
1414            max_message_rate_declared: None,
1415            max_connection_rate: None,
1416            max_source_selection_rate: None,
1417        };
1418        assert_eq!(
1419            p.compute_constraints(Some(&external)),
1420            EffectiveConstraints {
1421                max_concurrent_dispatchers: primary("32"),
1422                max_message_rate: Some(primary("100/s")),
1423                max_message_rate_declared: None,
1424                max_connection_rate: None,
1425                max_source_selection_rate: None,
1426            }
1427        );
1428    }
1429
1430    #[test]
1431    fn render_external_wins_with_annotation() {
1432        let mut p = cfg();
1433        p.max_message_rate = Some(throttle("1000/s"));
1434        let external = EffectiveConstraints {
1435            max_concurrent_dispatchers: EffectiveCeiling {
1436                value: f64::INFINITY,
1437                source: CeilingSource::Other {
1438                    name: "queue config".to_string(),
1439                },
1440                display: "∞".to_string(),
1441            },
1442            max_message_rate: Some(other("scheduled queue max_message_rate", "100/s")),
1443            max_message_rate_declared: None,
1444            max_connection_rate: None,
1445            max_source_selection_rate: None,
1446        };
1447        let c = p.compute_constraints(Some(&external));
1448        k9::snapshot!(
1449            c.to_human_string(),
1450            "
1451ceilings:
1452  concurrent dispatchers: 32
1453    source: connection_limit
1454  message rate:           100/s
1455    source: scheduled queue max_message_rate
1456    declared: max_message_rate = 1000/s ← effectively unreachable
1457
1458"
1459        );
1460    }
1461
1462    #[test]
1463    fn source_selection_rate() {
1464        let mut p = cfg();
1465        p.source_selection_rate = Some(throttle("5/s"));
1466        assert_eq!(
1467            p.compute_constraints(None),
1468            EffectiveConstraints {
1469                max_concurrent_dispatchers: primary("32"),
1470                max_message_rate: None,
1471                max_message_rate_declared: None,
1472                max_connection_rate: None,
1473                max_source_selection_rate: Some(primary("5/s")),
1474            }
1475        );
1476    }
1477
1478    #[test]
1479    fn render_defaults() {
1480        let c = cfg().compute_constraints(None);
1481        k9::snapshot!(
1482            c.to_human_string(),
1483            "
1484ceilings:
1485  concurrent dispatchers: 32
1486    source: connection_limit
1487
1488"
1489        );
1490    }
1491
1492    #[test]
1493    fn render_primary_message_rate_no_annotation() {
1494        // max_message_rate is the binding term; no declared-but-
1495        // unreachable annotation should appear.
1496        let mut p = cfg();
1497        p.max_message_rate = Some(throttle("1000/s"));
1498        let c = p.compute_constraints(None);
1499        k9::snapshot!(
1500            c.to_human_string(),
1501            "
1502ceilings:
1503  concurrent dispatchers: 32
1504    source: connection_limit
1505  message rate:           1000/s
1506    source: max_message_rate
1507
1508"
1509        );
1510    }
1511
1512    #[test]
1513    fn render_reconnect_cycling_with_annotation() {
1514        let mut p = cfg();
1515        p.max_message_rate = Some(throttle("1000/s"));
1516        p.max_deliveries_per_connection = 10;
1517        p.max_connection_rate = Some(throttle("10/s"));
1518        let c = p.compute_constraints(None);
1519        k9::snapshot!(
1520            c.to_human_string(),
1521            "
1522ceilings:
1523  concurrent dispatchers: 32
1524    source: connection_limit
1525  message rate:           10 × 10/s = 100/s
1526    source: max_deliveries_per_connection × max_connection_rate
1527    declared: max_message_rate = 1000/s ← effectively unreachable
1528  connection rate:        10/s
1529    source: max_connection_rate
1530
1531"
1532        );
1533    }
1534
1535    #[test]
1536    fn render_additional_throttle_winning() {
1537        let mut p = cfg();
1538        p.max_message_rate = Some(throttle("1000/s"));
1539        p.additional_message_rate_throttles
1540            .insert("provider_cap".to_string(), throttle("250/s"));
1541        let c = p.compute_constraints(None);
1542        k9::snapshot!(
1543            c.to_human_string(),
1544            "
1545ceilings:
1546  concurrent dispatchers: 32
1547    source: connection_limit
1548  message rate:           250/s
1549    source: provider_cap
1550    declared: max_message_rate = 1000/s ← effectively unreachable
1551
1552"
1553        );
1554    }
1555}