Skip to main content

rtflow_mount/
upstream.rs

1//! Upstream proxy configuration and supervision state.
2//!
3//! These are plain value types shared with the mount registry (which owns the
4//! proxy state of a mount); the runtime that drives them lives in
5//! `rtflow_rtsp_server::proxy_runtime`.
6pub use super::continuity::{
7    ContinuityPolicy, KeyframeCache, StartupCacheConfig, TimelineNormalizer, TimelineSnapshot,
8    TrackCompatibility,
9};
10use rtflow_media::MediaDescription;
11use rtflow_rtp::JitterBufferConfig;
12use rtflow_rtsp::auth::Credentials;
13pub use rtflow_rtsp::transport::UpstreamTransport;
14#[cfg(feature = "tls")]
15use rtflow_security::TlsClientConfig;
16use std::{
17    sync::{Arc, Mutex},
18    time::{Duration, Instant},
19};
20
21#[derive(Clone, Debug)]
22pub struct UpstreamEndpoint {
23    pub url: url::Url,
24    pub transport: UpstreamTransport,
25    pub credentials: Option<Credentials>,
26    pub request_timeout: Duration,
27    pub media_idle_timeout: Duration,
28    pub follow_redirects: bool,
29    pub allow_cross_origin_redirect: bool,
30    /// Resolved peer address used to pin DNS (the URL host is kept for SNI).
31    pub resolved: Option<std::net::SocketAddr>,
32    pub jitter: JitterBufferConfig,
33    #[cfg(feature = "tls")]
34    pub tls: Option<TlsClientConfig>,
35}
36
37impl UpstreamEndpoint {
38    pub fn new(url: url::Url, transport: UpstreamTransport) -> Self {
39        Self {
40            url,
41            transport,
42            credentials: None,
43            request_timeout: Duration::from_secs(5),
44            media_idle_timeout: Duration::from_secs(15),
45            follow_redirects: true,
46            allow_cross_origin_redirect: false,
47            resolved: None,
48            jitter: JitterBufferConfig::default(),
49            #[cfg(feature = "tls")]
50            tls: None,
51        }
52    }
53}
54
55#[derive(Clone, Copy, Debug, Eq, PartialEq)]
56pub enum FailoverStrategy {
57    Ordered,
58    RoundRobin,
59}
60
61#[derive(Clone, Debug)]
62pub struct FailoverPolicy {
63    pub strategy: FailoverStrategy,
64    pub failure_threshold: u32,
65    pub circuit_open_duration: Duration,
66}
67
68impl Default for FailoverPolicy {
69    fn default() -> Self {
70        Self {
71            strategy: FailoverStrategy::Ordered,
72            failure_threshold: 1,
73            circuit_open_duration: Duration::from_secs(10),
74        }
75    }
76}
77
78#[derive(Clone, Debug, Default)]
79pub struct UpstreamHealth {
80    pub consecutive_failures: u32,
81    pub circuit_open_until: Option<Instant>,
82    pub last_error: Option<rtflow_core::error::ErrorCode>,
83}
84
85impl UpstreamHealth {
86    pub fn is_available(&self, now: Instant) -> bool {
87        self.circuit_open_until.is_none_or(|until| now >= until)
88    }
89
90    pub fn record_success(&mut self) {
91        self.consecutive_failures = 0;
92        self.circuit_open_until = None;
93        self.last_error = None;
94    }
95
96    pub fn record_failure(
97        &mut self,
98        code: rtflow_core::error::ErrorCode,
99        policy: &FailoverPolicy,
100        now: Instant,
101    ) {
102        self.consecutive_failures = self.consecutive_failures.saturating_add(1);
103        self.last_error = Some(code);
104        if self.consecutive_failures >= policy.failure_threshold.max(1) {
105            self.circuit_open_until = Some(now + policy.circuit_open_duration);
106        }
107    }
108}
109
110pub trait UpstreamSelector: Send + Sync {
111    fn select(
112        &self,
113        endpoints: &[UpstreamEndpoint],
114        health: &[UpstreamHealth],
115        attempt: u32,
116        now: Instant,
117    ) -> Option<usize>;
118}
119
120#[derive(Clone, Debug)]
121pub struct PolicySelector {
122    pub strategy: FailoverStrategy,
123}
124
125impl UpstreamSelector for PolicySelector {
126    fn select(
127        &self,
128        endpoints: &[UpstreamEndpoint],
129        health: &[UpstreamHealth],
130        attempt: u32,
131        now: Instant,
132    ) -> Option<usize> {
133        if endpoints.is_empty() || endpoints.len() != health.len() {
134            return None;
135        }
136        let start = match self.strategy {
137            FailoverStrategy::Ordered => 0,
138            FailoverStrategy::RoundRobin => attempt as usize % endpoints.len(),
139        };
140        (0..endpoints.len())
141            .map(|offset| (start + offset) % endpoints.len())
142            .find(|index| health[*index].is_available(now))
143    }
144}
145
146#[derive(Clone, Debug)]
147pub struct ProxyRoute {
148    pub upstreams: Vec<UpstreamEndpoint>,
149    pub reconnect: ReconnectPolicy,
150    pub failover: FailoverPolicy,
151    pub continuity: ContinuityPolicy,
152    pub startup_cache: StartupCacheConfig,
153    pub cached_description: Option<Arc<MediaDescription>>,
154}
155
156impl ProxyRoute {
157    pub fn new(primary: UpstreamEndpoint) -> Self {
158        Self {
159            upstreams: vec![primary],
160            reconnect: ReconnectPolicy::default(),
161            failover: FailoverPolicy::default(),
162            continuity: ContinuityPolicy::default(),
163            startup_cache: StartupCacheConfig::default(),
164            cached_description: None,
165        }
166    }
167
168    pub fn add_fallback(mut self, endpoint: UpstreamEndpoint) -> Self {
169        self.upstreams.push(endpoint);
170        self
171    }
172
173    pub fn validate(&self) -> rtflow_core::error::Result<()> {
174        if self.upstreams.is_empty() {
175            return Err(rtflow_core::error::Error::Limit("proxy upstreams"));
176        }
177        if self.failover.failure_threshold == 0
178            || self.failover.circuit_open_duration == Duration::ZERO
179        {
180            return Err(rtflow_core::error::Error::Limit("proxy circuit breaker"));
181        }
182        Ok(())
183    }
184}
185#[derive(Clone, Debug)]
186pub struct ReconnectPolicy {
187    pub initial_delay: Duration,
188    pub max_delay: Duration,
189    pub multiplier: f32,
190    pub jitter_ratio: f32,
191}
192impl Default for ReconnectPolicy {
193    fn default() -> Self {
194        Self {
195            initial_delay: Duration::from_millis(250),
196            max_delay: Duration::from_secs(30),
197            multiplier: 2.0,
198            jitter_ratio: 0.2,
199        }
200    }
201}
202#[derive(Clone, Debug)]
203pub enum ProxyState {
204    Idle,
205    Connecting,
206    Streaming,
207    BackingOff { retry_at: Instant, attempts: u32 },
208    Stopped,
209}
210fn random_jitter_sample() -> u16 {
211    let mut bytes = [0u8; 2];
212    if getrandom::fill(&mut bytes).is_ok() {
213        u16::from_le_bytes(bytes) % 2_001
214    } else {
215        (std::time::SystemTime::now()
216            .duration_since(std::time::UNIX_EPOCH)
217            .unwrap_or_default()
218            .subsec_millis() as u16
219            * 2)
220            % 2_001
221    }
222}
223
224#[derive(Clone)]
225pub struct UpstreamConfig {
226    pub url: url::Url,
227    pub transport: UpstreamTransport,
228    pub credentials: Option<Credentials>,
229    pub reconnect: ReconnectPolicy,
230    pub request_timeout: Duration,
231    pub media_idle_timeout: Duration,
232    pub follow_redirects: bool,
233    pub allow_cross_origin_redirect: bool,
234    pub resolved: Option<std::net::SocketAddr>,
235    pub jitter: JitterBufferConfig,
236    #[cfg(feature = "tls")]
237    pub tls: Option<TlsClientConfig>,
238    pub cached_description: Option<Arc<MediaDescription>>,
239    pub continuity: ContinuityPolicy,
240    pub startup_cache: StartupCacheConfig,
241    pub fallbacks: Vec<UpstreamEndpoint>,
242    pub failover: FailoverPolicy,
243    state: Arc<Mutex<ProxyState>>,
244}
245impl UpstreamConfig {
246    pub fn new(url: url::Url, transport: UpstreamTransport) -> Self {
247        Self {
248            url,
249            transport,
250            credentials: None,
251            reconnect: ReconnectPolicy::default(),
252            request_timeout: Duration::from_secs(5),
253            media_idle_timeout: Duration::from_secs(15),
254            follow_redirects: true,
255            allow_cross_origin_redirect: false,
256            resolved: None,
257            jitter: JitterBufferConfig::default(),
258            #[cfg(feature = "tls")]
259            tls: None,
260            cached_description: None,
261            continuity: ContinuityPolicy::default(),
262            startup_cache: StartupCacheConfig::default(),
263            fallbacks: Vec::new(),
264            failover: FailoverPolicy::default(),
265            state: Arc::new(Mutex::new(ProxyState::Idle)),
266        }
267    }
268    pub fn add_fallback(&mut self, endpoint: UpstreamEndpoint) {
269        self.fallbacks.push(endpoint);
270    }
271    pub fn endpoints(&self) -> Vec<UpstreamEndpoint> {
272        let mut endpoints = Vec::with_capacity(self.fallbacks.len() + 1);
273        endpoints.push(UpstreamEndpoint {
274            url: self.url.clone(),
275            transport: self.transport,
276            credentials: self.credentials.clone(),
277            request_timeout: self.request_timeout,
278            media_idle_timeout: self.media_idle_timeout,
279            follow_redirects: self.follow_redirects,
280            allow_cross_origin_redirect: self.allow_cross_origin_redirect,
281            resolved: self.resolved,
282            jitter: self.jitter.clone(),
283            #[cfg(feature = "tls")]
284            tls: self.tls.clone(),
285        });
286        endpoints.extend(self.fallbacks.iter().cloned());
287        endpoints
288    }
289    pub fn state(&self) -> ProxyState {
290        self.state
291            .lock()
292            .unwrap_or_else(std::sync::PoisonError::into_inner)
293            .clone()
294    }
295    pub fn set_state(&self, state: ProxyState) {
296        *self
297            .state
298            .lock()
299            .unwrap_or_else(std::sync::PoisonError::into_inner) = state;
300    }
301
302    /// Detach the shared proxy state from other clones (for example when a
303    /// restart re-registers the same upstream while the old worker is still
304    /// shutting down, so a late `Stopped` cannot overwrite the new state).
305    pub fn reset_state(&mut self) {
306        self.state = Arc::new(Mutex::new(ProxyState::Idle));
307    }
308    pub fn next_retry(&self, attempts: u32) -> Duration {
309        let ms = (self.reconnect.initial_delay.as_millis() as f32
310            * self
311                .reconnect
312                .multiplier
313                .powi(attempts.saturating_sub(1).min(30) as i32)) as u128;
314        let capped = ms.min(self.reconnect.max_delay.as_millis()) as f32;
315        let ratio = self.reconnect.jitter_ratio.clamp(0.0, 1.0);
316        let sample = random_jitter_sample();
317        let centered = f32::from(sample) / 1_000.0 - 1.0;
318        Duration::from_millis(
319            (capped * (1.0 + centered * ratio))
320                .max(0.0)
321                .min(self.reconnect.max_delay.as_millis() as f32) as u64,
322        )
323    }
324}
325
326impl TryFrom<ProxyRoute> for UpstreamConfig {
327    type Error = rtflow_core::error::Error;
328
329    fn try_from(mut route: ProxyRoute) -> Result<Self, Self::Error> {
330        route.validate()?;
331        let primary = route.upstreams.remove(0);
332        let mut config = Self::new(primary.url, primary.transport);
333        config.credentials = primary.credentials;
334        config.request_timeout = primary.request_timeout;
335        config.media_idle_timeout = primary.media_idle_timeout;
336        config.follow_redirects = primary.follow_redirects;
337        config.allow_cross_origin_redirect = primary.allow_cross_origin_redirect;
338        config.resolved = primary.resolved;
339        config.jitter = primary.jitter;
340        #[cfg(feature = "tls")]
341        {
342            config.tls = primary.tls;
343        }
344        config.fallbacks = route.upstreams;
345        config.reconnect = route.reconnect;
346        config.failover = route.failover;
347        config.continuity = route.continuity;
348        config.startup_cache = route.startup_cache;
349        config.cached_description = route.cached_description;
350        Ok(config)
351    }
352}
353
354#[cfg(test)]
355mod tests {
356    use super::*;
357
358    #[test]
359    fn retry_is_jittered_and_capped() {
360        let mut upstream = UpstreamConfig::new(
361            url::Url::parse("rtsp://127.0.0.1/source").unwrap(),
362            UpstreamTransport::Udp,
363        );
364        upstream.reconnect.initial_delay = Duration::from_millis(100);
365        upstream.reconnect.max_delay = Duration::from_millis(500);
366        upstream.reconnect.jitter_ratio = 0.2;
367        let first = upstream.next_retry(1);
368        assert!((80..=120).contains(&first.as_millis()));
369        assert!(upstream.next_retry(20) <= Duration::from_millis(500));
370    }
371}