Skip to main content

rtflow_mount/
registry.rs

1use super::*;
2
3// ---------------------------------------------------------------------------
4// MountRegistry
5// ---------------------------------------------------------------------------
6
7/// Shared mount registry accessible by all protocol servers.
8pub struct MountRegistry {
9    mounts: RwLock<HashMap<MountId, Arc<Mount>>>,
10    max_mounts: usize,
11    /// Global metrics registry mirrored by every mount created through
12    /// this registry (R12: frame counters were previously only wired for
13    /// mounts registered via RtspServer, leaving RTMP/SRT/gateway mounts
14    /// invisible in /metrics).
15    global: Option<Arc<rtflow_core::metrics::MetricsRegistry>>,
16}
17
18/// Default per-consumer buffering limit (bytes) applied to every mount
19/// unless overridden via [`MountOptions`] or the server/gateway config.
20pub const DEFAULT_MAX_QUEUED_BYTES_PER_SESSION: usize = 4 * 1024 * 1024;
21/// Hard upper bound for the per-mount broadcast ring. A configuration typo
22/// must not allocate an unbounded queue.
23pub const MAX_CONSUMER_QUEUE_CAPACITY: usize = 4096;
24
25/// Per-mount tuning knobs for [`MountRegistry::register_with`].
26///
27/// All fields are optional; `None` falls back to the defaults that
28/// [`MountRegistry::register`] historically used, so existing callers keep
29/// identical behavior.
30#[derive(Default, Clone)]
31#[non_exhaustive]
32pub struct MountOptions {
33    /// Capacity (frames) of the per-mount broadcast ring. Slow consumers
34    /// lag and recover; the broadcaster never blocks the encoder.
35    pub consumer_queue_capacity: Option<usize>,
36    /// Frame-size budget used by senders and startup snapshots. This is not
37    /// a full broadcast-ring byte budget yet; size the ring together with
38    /// the expected frame size.
39    pub max_queued_bytes_per_session: Option<usize>,
40    /// Sink for mount lifecycle/stream events; `None` → no-op sink.
41    pub event_sink: Option<Arc<dyn EventSink>>,
42    /// Startup (keyframe) cache policy for every mount type; `None` uses
43    /// the server default.
44    pub startup_cache_config: Option<crate::continuity::StartupCacheConfig>,
45    /// Per-mount override of the server's live NPT timeline mode.
46    pub timeline: Option<rtflow_rtsp::range::TimelineMode>,
47    /// Parent cancellation token. Server-owned mounts pass a child token so
48    /// `RtspServer::shutdown` also stops file demuxers/proxies; standalone
49    /// registries may leave this `None`.
50    pub cancel: Option<CancellationToken>,
51}
52
53impl std::fmt::Debug for MountOptions {
54    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
55        let mut debug = formatter.debug_struct("MountOptions");
56        debug
57            .field("consumer_queue_capacity", &self.consumer_queue_capacity)
58            .field(
59                "max_queued_bytes_per_session",
60                &self.max_queued_bytes_per_session,
61            )
62            .field("event_sink", &self.event_sink.as_ref().map(|_| "<sink>"))
63            .field("timeline", &self.timeline)
64            .field("cancel", &self.cancel.is_some());
65        debug.field("startup_cache_config", &self.startup_cache_config);
66        debug.finish()
67    }
68}
69
70pub struct MountOptionsBuilder {
71    options: MountOptions,
72}
73
74impl MountOptions {
75    pub fn builder() -> MountOptionsBuilder {
76        MountOptionsBuilder {
77            options: MountOptions::default(),
78        }
79    }
80}
81
82impl MountOptionsBuilder {
83    pub fn consumer_queue_capacity(mut self, value: usize) -> Self {
84        self.options.consumer_queue_capacity = Some(value);
85        self
86    }
87
88    pub fn max_queued_bytes_per_session(mut self, value: usize) -> Self {
89        self.options.max_queued_bytes_per_session = Some(value);
90        self
91    }
92
93    pub fn event_sink(mut self, value: Arc<dyn EventSink>) -> Self {
94        self.options.event_sink = Some(value);
95        self
96    }
97
98    pub fn startup_cache_config(mut self, value: crate::continuity::StartupCacheConfig) -> Self {
99        self.options.startup_cache_config = Some(value);
100        self
101    }
102
103    pub fn timeline(mut self, value: rtflow_rtsp::range::TimelineMode) -> Self {
104        self.options.timeline = Some(value);
105        self
106    }
107
108    pub fn cancel(mut self, value: CancellationToken) -> Self {
109        self.options.cancel = Some(value);
110        self
111    }
112
113    pub fn build(self) -> MountOptions {
114        self.options
115    }
116}
117
118impl MountRegistry {
119    pub fn new(max_mounts: usize) -> Self {
120        Self {
121            mounts: RwLock::new(HashMap::new()),
122            max_mounts,
123            global: None,
124        }
125    }
126
127    /// Mirror per-mount frame counters into a global metrics registry.
128    /// Must be called before mounts are registered.
129    pub fn attach_global(&mut self, registry: Arc<rtflow_core::metrics::MetricsRegistry>) {
130        self.global = Some(registry);
131    }
132
133    /// Insert a pre-built mount. Returns error on conflict or limit.
134    #[doc(hidden)]
135    pub fn insert(&self, path: Arc<str>, mount: Arc<Mount>) -> Result<()> {
136        let id = MountId::from(path);
137        let mut mounts = self
138            .mounts
139            .write()
140            .unwrap_or_else(std::sync::PoisonError::into_inner);
141        if mounts.contains_key(&id) {
142            return Err(Error::Conflict(id.to_string()));
143        }
144        if mounts.len() >= self.max_mounts {
145            return Err(Error::Limit("mounts"));
146        }
147        mounts.insert(id, mount);
148        Ok(())
149    }
150
151    #[doc(hidden)]
152    pub fn remove(&self, path: &str) -> Option<Arc<Mount>> {
153        self.mounts
154            .write()
155            .unwrap_or_else(std::sync::PoisonError::into_inner)
156            .remove(path)
157    }
158
159    /// Shared mount state for `path` (control-plane access).
160    #[doc(hidden)]
161    pub fn get(&self, path: &str) -> Option<Arc<Mount>> {
162        self.mounts
163            .read()
164            .unwrap_or_else(std::sync::PoisonError::into_inner)
165            .get(path)
166            .cloned()
167    }
168
169    /// Number of currently registered mounts.
170    pub fn len(&self) -> usize {
171        self.mounts
172            .read()
173            .unwrap_or_else(std::sync::PoisonError::into_inner)
174            .len()
175    }
176
177    pub fn is_empty(&self) -> bool {
178        self.len() == 0
179    }
180
181    /// Cancel every mount's data plane and drop the registry entries.
182    /// Protocol servers call this on shutdown; the mount handles held by
183    /// callers become detached but their broadcast receivers close when
184    /// those handles are dropped.
185    pub fn cancel_all(&self) {
186        let mut mounts = self
187            .mounts
188            .write()
189            .unwrap_or_else(std::sync::PoisonError::into_inner);
190        for mount in mounts.values() {
191            mount.cancel.cancel();
192        }
193        mounts.clear();
194    }
195
196    /// List all registered mounts in stable path order.
197    pub fn paths(&self) -> Vec<MountId> {
198        let mut paths = self
199            .mounts
200            .read()
201            .unwrap_or_else(std::sync::PoisonError::into_inner)
202            .keys()
203            .cloned()
204            .collect::<Vec<_>>();
205        paths.sort_by(|left, right| left.as_str().cmp(right.as_str()));
206        paths
207    }
208
209    /// Find the mount whose path is the longest prefix of `requested`.
210    #[allow(dead_code)] // used by the RTSP server
211    /// Longest registered path that prefixes `requested`.
212    #[doc(hidden)]
213    pub fn find_longest_prefix(&self, requested: &str) -> Option<(MountId, Arc<Mount>)> {
214        let mounts = self
215            .mounts
216            .read()
217            .unwrap_or_else(std::sync::PoisonError::into_inner);
218        // Exact match is the overwhelmingly common case: O(1) hash lookup
219        // instead of a linear prefix scan over every registered mount.
220        if let Some((path, mount)) = mounts.get_key_value(&MountId::new(requested)) {
221            return Some((path.clone(), mount.clone()));
222        }
223        mounts
224            .iter()
225            .filter(|(path, _)| {
226                requested
227                    .strip_prefix(path.as_str())
228                    .is_some_and(|suffix| suffix.starts_with('/'))
229            })
230            .max_by_key(|(path, _)| path.as_str().len())
231            .map(|(path, mount)| (path.clone(), mount.clone()))
232    }
233
234    /// Register a new mount from a config with default options. Returns a
235    /// handle on success.
236    pub fn register(&self, path: Arc<str>, config: MountConfig) -> Result<MountHandle> {
237        self.register_with(path, config, MountOptions::default())
238    }
239
240    /// Register a new mount from a config plus per-mount tuning options
241    /// (queue capacity, event sink, startup cache policy). Returns a
242    /// handle on success.
243    ///
244    /// This is the single construction path for `Mount`: protocol servers
245    /// (RTSP via `register_mount`, RTMP, SRT) and the multi-protocol
246    /// gateway all funnel through it, so every mount gets identical
247    /// wiring for stats, startup cache and lifecycle.
248    pub fn register_with(
249        &self,
250        path: Arc<str>,
251        config: MountConfig,
252        options: MountOptions,
253    ) -> Result<MountHandle> {
254        if !path.starts_with('/') {
255            return Err(Error::InvalidConfig(
256                "mount path must start with '/'".into(),
257            ));
258        }
259        let description = description_for(&config)?;
260        let queue_capacity = options
261            .consumer_queue_capacity
262            .unwrap_or(256)
263            .clamp(1, MAX_CONSUMER_QUEUE_CAPACITY);
264        let max_bytes = options
265            .max_queued_bytes_per_session
266            .unwrap_or(DEFAULT_MAX_QUEUED_BYTES_PER_SESSION);
267        let frames = FrameBus::new(queue_capacity, max_bytes);
268        let (keyframe_requests, _) = broadcast::channel(16);
269        let (nack_requests, _) = broadcast::channel(64);
270        let startup_cache = KeyframeCache::new(
271            &description,
272            options.startup_cache_config.unwrap_or_default(),
273        )?;
274        let mount = Arc::new(Mount {
275            id: MountId::from(path.clone()),
276            config,
277            frames,
278            consumer_queue_capacity: queue_capacity,
279            keyframe_requests,
280            nack_requests,
281            timeline: options.timeline,
282            stats: {
283                #[cfg_attr(not(feature = "metrics"), allow(unused_mut))]
284                let mut counters = StreamCounters::default();
285                if let Some(global) = &self.global {
286                    counters.attach_global(global.clone());
287                } else if let Some(sink) = &options.event_sink {
288                    // Gateway-style registries carry metrics through the
289                    // event sink instead of a registry-global handle.
290                    if let Some(registry) = rtflow_core::metrics::registry_from_sink(sink) {
291                        counters.attach_global(registry);
292                    }
293                }
294                counters
295            },
296            description: std::sync::RwLock::new(Arc::new(description.clone())),
297            startup_cache: Mutex::new(startup_cache),
298            startup_cache_config: options.startup_cache_config.unwrap_or_default(),
299            bootstrap: Mutex::new(std::array::from_fn(|_| None)),
300            codec_by_track: std::sync::RwLock::new(codec_lookup_table(&description)),
301            event_sink: options
302                .event_sink
303                .unwrap_or_else(|| Arc::new(rtflow_core::observe::NoopEventSink)),
304            cancel: options.cancel.unwrap_or_default(),
305            proxy_running: AtomicBool::new(false),
306            publishers: AtomicUsize::new(0),
307            publisher_claimed: AtomicBool::new(false),
308            active_sessions: AtomicUsize::new(0),
309            max_queued_bytes_per_session: max_bytes,
310            announce_fmtp: Mutex::new(HashMap::new()),
311            rtmp_seq_headers: Mutex::new(HashMap::new()),
312            // Two frames: enough for the frame currently being fanned out
313            // plus one in flight, without pinning a visible amount of memory.
314            derived_payloads: crate::derived::DerivedPayloadCache::new(2),
315        });
316        self.insert(path.clone(), mount.clone())?;
317        Ok(MountHandle {
318            path: MountId::from(path),
319            description: Arc::new(description),
320            inner: mount,
321        })
322    }
323
324    /// Get a mount handle by path.
325    pub fn get_handle(&self, path: &str) -> Option<MountHandle> {
326        self.get(path).map(|mount| {
327            let description = mount.description_snapshot();
328            MountHandle {
329                path: mount.id.clone(),
330                description,
331                inner: mount,
332            }
333        })
334    }
335
336    /// Remove a mount from the registry and cancel its data plane.
337    ///
338    /// Protocol servers (RTMP/SRT) must call this when the publishing
339    /// session that created the mount ends, otherwise every distinct
340    /// stream path permanently consumes one of the `max_mounts` slots.
341    pub fn unregister(&self, path: &str) -> Option<MountHandle> {
342        let removed = self.remove(path)?;
343        removed.cancel.cancel();
344        tracing::info!(path, "mount unregistered");
345        Some(MountHandle {
346            path: removed.id.clone(),
347            description: Arc::new(description_for(&removed.config).unwrap_or_else(|_| {
348                MediaDescription {
349                    session_name: path.into(),
350                    tracks: Vec::new(),
351                    connection: None,
352                }
353            })),
354            inner: removed,
355        })
356    }
357
358    /// Snapshot all registered mounts (identity + stats).
359    pub fn snapshots(&self) -> Vec<(MountId, MountSnapshot)> {
360        let mut snapshots = self
361            .mounts
362            .read()
363            .unwrap_or_else(std::sync::PoisonError::into_inner)
364            .iter()
365            .map(|(path, mount)| {
366                let handle = MountHandle {
367                    path: path.clone(),
368                    description: Arc::new(MediaDescription {
369                        session_name: path.as_str().into(),
370                        tracks: Vec::new(),
371                        connection: None,
372                    }),
373                    inner: mount.clone(),
374                };
375                (path.clone(), handle.snapshot())
376            })
377            .collect::<Vec<_>>();
378        snapshots.sort_by(|(left, _), (right, _)| left.as_str().cmp(right.as_str()));
379        snapshots
380    }
381}
382
383#[cfg(test)]
384mod tests {
385    use super::*;
386
387    fn local(path: &str) -> rtflow_media::MediaDescription {
388        rtflow_media::MediaDescription::new(
389            path,
390            vec![rtflow_media::TrackDescription::h264_video(
391                0,
392                &[],
393                &[],
394                640,
395                360,
396                30,
397            )],
398        )
399    }
400
401    #[test]
402    fn longest_prefix_respects_path_boundaries() {
403        let registry = MountRegistry::new(4);
404        registry
405            .register(
406                Arc::from("/cam"),
407                MountConfig::Local {
408                    description: local("cam"),
409                },
410            )
411            .unwrap();
412        registry
413            .register(
414                Arc::from("/cam/main"),
415                MountConfig::Local {
416                    description: local("main"),
417                },
418            )
419            .unwrap();
420        let (path, _) = registry
421            .find_longest_prefix("/cam/main/track0")
422            .expect("prefix");
423        assert_eq!(path.as_str(), "/cam/main");
424        assert!(registry.find_longest_prefix("/camera").is_none());
425    }
426
427    #[test]
428    fn paths_are_sorted_and_cancel_all_clears() {
429        let registry = MountRegistry::new(4);
430        for path in ["/b", "/a"] {
431            registry
432                .register(
433                    Arc::from(path),
434                    MountConfig::Local {
435                        description: local(path),
436                    },
437                )
438                .unwrap();
439        }
440        assert_eq!(
441            registry
442                .paths()
443                .iter()
444                .map(|id| id.as_str())
445                .collect::<Vec<_>>(),
446            vec!["/a", "/b"]
447        );
448        let handle = registry.get_handle("/a").unwrap();
449        registry.cancel_all();
450        assert!(handle.cancellation_token().is_cancelled());
451        assert!(registry.is_empty());
452    }
453
454    #[tokio::test]
455    async fn dropping_mount_closes_frame_subscribers() {
456        let registry = MountRegistry::new(1);
457        let handle = registry
458            .register(
459                Arc::from("/close"),
460                MountConfig::Local {
461                    description: local("close"),
462                },
463            )
464            .unwrap();
465        let mut receiver = handle.subscribe();
466        drop(handle);
467        drop(registry);
468        assert!(matches!(
469            receiver.recv().await,
470            Err(crate::FrameRecvError::Closed)
471        ));
472    }
473
474    #[test]
475    fn queue_capacity_is_clamped() {
476        let registry = MountRegistry::new(1);
477        let handle = registry
478            .register_with(
479                Arc::from("/capacity"),
480                MountConfig::Local {
481                    description: local("capacity"),
482                },
483                MountOptions::builder()
484                    .consumer_queue_capacity(usize::MAX)
485                    .build(),
486            )
487            .unwrap();
488        assert_eq!(
489            handle.snapshot().consumer_queue_capacity,
490            MAX_CONSUMER_QUEUE_CAPACITY
491        );
492    }
493
494    #[test]
495    fn oversized_frame_is_dropped_before_broadcast() {
496        let registry = MountRegistry::new(1);
497        let handle = registry
498            .register_with(
499                Arc::from("/oversized"),
500                MountConfig::Local {
501                    description: local("oversized"),
502                },
503                MountOptions::builder()
504                    .max_queued_bytes_per_session(4)
505                    .build(),
506            )
507            .unwrap();
508        let publisher = handle.publisher().unwrap();
509        let frame = rtflow_media::AccessUnit {
510            nal_offsets: None,
511            track_id: 0,
512            codec: rtflow_media::Codec::H264,
513            pts: std::time::Duration::ZERO,
514            dts: None,
515            rtp_timestamp: 0,
516            is_keyframe: true,
517            data: bytes::Bytes::from_static(b"12345"),
518        };
519        assert_eq!(publisher.try_push(frame).unwrap(), PushResult::Dropped);
520        assert_eq!(handle.snapshot().stats.dropped_frames, 1);
521    }
522
523    #[test]
524    fn mount_options_builder_sets_values() {
525        let options = MountOptions::builder()
526            .consumer_queue_capacity(32)
527            .max_queued_bytes_per_session(1024)
528            .timeline(rtflow_rtsp::range::TimelineMode::Absolute {
529                offset: std::time::Duration::from_secs(10),
530            })
531            .build();
532        assert_eq!(options.consumer_queue_capacity, Some(32));
533        assert_eq!(options.max_queued_bytes_per_session, Some(1024));
534        assert!(matches!(
535            options.timeline,
536            Some(rtflow_rtsp::range::TimelineMode::Absolute { .. })
537        ));
538    }
539}