Skip to main content

rtflow_http/
router.rs

1use super::request::{HttpRequest, Method};
2use super::response::ResponseWriter;
3use rtflow_core::error::Result;
4use std::future::Future;
5use std::pin::Pin;
6use std::sync::Arc;
7use tokio::net::tcp::OwnedWriteHalf;
8
9/// Shared write half of an accepted HTTP connection.
10///
11/// The TLS variant only exists with the `tls` feature; handlers stay generic
12/// over the writer so no media code needs to know which transport it serves.
13pub enum ConnWriter {
14    Tcp(OwnedWriteHalf),
15    #[cfg(feature = "tls")]
16    Tls(tokio::io::WriteHalf<tokio_rustls::server::TlsStream<tokio::net::TcpStream>>),
17}
18
19impl ConnWriter {
20    #[cfg(not(feature = "tls"))]
21    pub fn tcp(writer: OwnedWriteHalf) -> Self {
22        Self::Tcp(writer)
23    }
24
25    #[cfg(feature = "tls")]
26    pub fn tcp(writer: OwnedWriteHalf) -> Self {
27        Self::Tcp(writer)
28    }
29}
30
31impl tokio::io::AsyncWrite for ConnWriter {
32    fn poll_write(
33        self: std::pin::Pin<&mut Self>,
34        cx: &mut std::task::Context<'_>,
35        buf: &[u8],
36    ) -> std::task::Poll<std::io::Result<usize>> {
37        match self.get_mut() {
38            Self::Tcp(writer) => std::pin::Pin::new(writer).poll_write(cx, buf),
39            #[cfg(feature = "tls")]
40            Self::Tls(writer) => std::pin::Pin::new(writer).poll_write(cx, buf),
41        }
42    }
43
44    fn poll_flush(
45        self: std::pin::Pin<&mut Self>,
46        cx: &mut std::task::Context<'_>,
47    ) -> std::task::Poll<std::io::Result<()>> {
48        match self.get_mut() {
49            Self::Tcp(writer) => std::pin::Pin::new(writer).poll_flush(cx),
50            #[cfg(feature = "tls")]
51            Self::Tls(writer) => std::pin::Pin::new(writer).poll_flush(cx),
52        }
53    }
54
55    fn poll_shutdown(
56        self: std::pin::Pin<&mut Self>,
57        cx: &mut std::task::Context<'_>,
58    ) -> std::task::Poll<std::io::Result<()>> {
59        match self.get_mut() {
60            Self::Tcp(writer) => std::pin::Pin::new(writer).poll_shutdown(cx),
61            #[cfg(feature = "tls")]
62            Self::Tls(writer) => std::pin::Pin::new(writer).poll_shutdown(cx),
63        }
64    }
65}
66
67pub type Handler = Arc<
68    dyn Fn(
69            HttpRequest,
70            ResponseWriter<ConnWriter>,
71        ) -> Pin<Box<dyn Future<Output = Result<ResponseWriter<ConnWriter>>> + Send>>
72        + Send
73        + Sync,
74>;
75
76pub struct Route {
77    pub method: Method,
78    pub pattern: PathPattern,
79    pub handler: Handler,
80}
81
82pub struct Router {
83    routes: Vec<Route>,
84    not_found: Handler,
85    method_not_allowed: Handler,
86}
87
88impl Default for Router {
89    fn default() -> Self {
90        Self::new()
91    }
92}
93
94impl Router {
95    pub fn new() -> Self {
96        Self {
97            routes: Vec::new(),
98            not_found: Arc::new(|_req, mut writer| {
99                Box::pin(async move {
100                    writer.write_body(404, "text/plain", b"Not Found").await?;
101                    Ok(writer)
102                })
103            }),
104            method_not_allowed: Arc::new(|_req, mut writer| {
105                Box::pin(async move {
106                    // Content-Length + Connection: close are mandatory: an
107                    // HTTP/1.1 client would otherwise wait for the body to
108                    // end until its own timeout.
109                    writer
110                        .write_headers(
111                            405,
112                            &[
113                                ("Allow", "GET, HEAD, OPTIONS"),
114                                ("Content-Length", "18"),
115                                ("Connection", "close"),
116                            ],
117                        )
118                        .await?;
119                    writer.write_raw(b"Method Not Allowed").await?;
120                    Ok(writer)
121                })
122            }),
123        }
124    }
125
126    pub fn add(&mut self, method: Method, pattern: &str, handler: Handler) {
127        self.routes.push(Route {
128            method,
129            pattern: PathPattern::new(pattern),
130            handler,
131        });
132    }
133
134    pub(crate) fn route(&self, method: &Method, path: &str) -> (&Handler, Vec<String>) {
135        let mut path_match = false;
136        for route in &self.routes {
137            if route.pattern.matches(path).is_some() {
138                path_match = true;
139            }
140            if &route.method != method {
141                continue;
142            }
143            if let Some(params) = route.pattern.matches(path) {
144                return (&route.handler, params);
145            }
146        }
147        if path_match {
148            (&self.method_not_allowed, Vec::new())
149        } else {
150            (&self.not_found, Vec::new())
151        }
152    }
153}
154
155pub struct PathPattern {
156    segments: Vec<PatternSegment>,
157}
158
159enum PatternSegment {
160    Literal(String),
161    #[allow(dead_code)]
162    Param(String),
163    /// A segment with a prefix and suffix around a parameter, e.g. `segment_{seq}.m4s`.
164    ParamWithAffixes {
165        prefix: String,
166        suffix: String,
167    },
168    Wildcard,
169}
170
171impl PathPattern {
172    pub fn new(pattern: &str) -> Self {
173        let segments = pattern
174            .split('/')
175            .filter(|s| !s.is_empty())
176            .map(|s| {
177                if s == "*" {
178                    PatternSegment::Wildcard
179                } else if s.starts_with('{') && s.ends_with('}') {
180                    PatternSegment::Param(s[1..s.len() - 1].to_string())
181                } else if let Some(brace_start) = s.find('{') {
182                    if let Some(brace_end) = s[brace_start..].find('}') {
183                        let prefix = s[..brace_start].to_string();
184                        let suffix = s[brace_start + brace_end + 1..].to_string();
185                        PatternSegment::ParamWithAffixes { prefix, suffix }
186                    } else {
187                        PatternSegment::Literal(s.to_string())
188                    }
189                } else {
190                    PatternSegment::Literal(s.to_string())
191                }
192            })
193            .collect();
194        Self { segments }
195    }
196
197    fn matches(&self, path: &str) -> Option<Vec<String>> {
198        let parts: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();
199        if parts.len() != self.segments.len() {
200            if let Some(PatternSegment::Wildcard) = self.segments.last() {
201                if parts.len() < self.segments.len() - 1 {
202                    return None;
203                }
204            } else {
205                return None;
206            }
207        }
208
209        let mut params = Vec::new();
210        for (i, seg) in self.segments.iter().enumerate() {
211            match seg {
212                PatternSegment::Literal(lit) => {
213                    if i >= parts.len() || parts[i] != lit {
214                        return None;
215                    }
216                }
217                PatternSegment::Param(_) => {
218                    if i >= parts.len() {
219                        return None;
220                    }
221                    params.push(parts[i].to_string());
222                }
223                PatternSegment::ParamWithAffixes { prefix, suffix } => {
224                    if i >= parts.len() {
225                        return None;
226                    }
227                    let part = parts[i];
228                    if !part.starts_with(prefix.as_str()) || !part.ends_with(suffix.as_str()) {
229                        return None;
230                    }
231                    let value = &part[prefix.len()..part.len() - suffix.len()];
232                    params.push(value.to_string());
233                }
234                PatternSegment::Wildcard => {
235                    break;
236                }
237            }
238        }
239        Some(params)
240    }
241}