streamkit_core/
moq_gateway.rs

1// SPDX-FileCopyrightText: © 2025 StreamKit Contributors
2//
3// SPDX-License-Identifier: MPL-2.0
4
5//! Gateway trait for MoQ WebTransport routing
6//!
7//! This module defines the gateway interface that nodes can use to register routes.
8//! The actual implementation lives in the server crate, but the interface is defined
9//! here in core to avoid circular dependencies.
10
11use async_trait::async_trait;
12use std::sync::Arc;
13use tokio::sync::mpsc;
14
15/// Opaque type for WebTransport session - actual type defined in moq-native
16pub type WebTransportSession = Box<dyn std::any::Any + Send>;
17
18/// Result of attempting to handle a MoQ connection
19#[derive(Debug)]
20pub enum MoqConnectionResult {
21    /// Connection was successfully handled by a node
22    Accepted,
23    /// Connection was rejected by the node
24    Rejected(String),
25}
26
27/// A WebTransport connection that needs to be routed to a moq_peer node
28pub struct MoqConnection {
29    /// The path requested (e.g., "/moq/anon/input")
30    pub path: String,
31
32    /// The WebTransport session handle (type-erased)
33    pub session: WebTransportSession,
34
35    /// Channel to send response back to gateway
36    pub response_tx: tokio::sync::oneshot::Sender<MoqConnectionResult>,
37}
38
39/// Gateway interface that nodes can use to register routes
40#[async_trait]
41pub trait MoqGatewayTrait: Send + Sync {
42    /// Register a path pattern for a session's moq_peer node
43    ///
44    /// Returns a receiver that will receive accepted connections matching this path.
45    async fn register_route(
46        &self,
47        path_pattern: String,
48        session_id: String,
49    ) -> Result<mpsc::UnboundedReceiver<MoqConnection>, String>;
50
51    /// Unregister a path pattern
52    async fn unregister_route(&self, path_pattern: &str);
53}
54
55/// Global gateway registry - nodes call this to get the gateway
56static GATEWAY: std::sync::OnceLock<Arc<dyn MoqGatewayTrait>> = std::sync::OnceLock::new();
57
58/// Initialize the global MoQ gateway (called by server)
59pub fn init_moq_gateway(gateway: Arc<dyn MoqGatewayTrait>) {
60    if GATEWAY.set(gateway).is_err() {
61        tracing::warn!("MoQ gateway already initialized");
62    }
63}
64
65/// Get the global MoQ gateway (called by nodes)
66pub fn get_moq_gateway() -> Option<Arc<dyn MoqGatewayTrait>> {
67    GATEWAY.get().cloned()
68}