rtflow-http 0.7.0

Minimal bounded HTTP/1.1 server and router used by rtflow protocol adapters
Documentation
use rtflow_core::error::{Error, Result};
use std::time::Duration;
use tokio::io::{AsyncWrite, AsyncWriteExt};

pub struct ResponseWriter<W: AsyncWrite + Unpin> {
    inner: W,
    headers_written: bool,
    connection_close: bool,
    /// Per-write deadline; `None` disables the guard (R22: a frozen peer
    /// must not pin a connection slot forever).
    write_timeout: Option<Duration>,
    /// Bytes written since the last egress flush. The admission guard's
    /// counter is process-wide, so reporting one atomic per write makes every
    /// streaming connection contend on the same cache line.
    egress: u64,
}

/// Flush accumulated egress bytes at this size.
const EGRESS_FLUSH_BYTES: u64 = 64 * 1024;

/// 每个响应都带的浏览器安全头(handler 自己写了同名头就以它为准)。
///
/// * nosniff:禁止浏览器把 JSON/文本当脚本或样式执行;
/// * DENY:设备网页不允许被别的站点用 iframe 嵌入(防点击劫持);
/// * no-referrer:跳转到外部链接时不泄露设备地址与查询串里的 token。
const SECURITY_HEADERS: &[(&str, &str)] = &[
    ("X-Content-Type-Options", "nosniff"),
    ("X-Frame-Options", "DENY"),
    ("Referrer-Policy", "no-referrer"),
];

impl<W: AsyncWrite + Unpin> ResponseWriter<W> {
    pub fn new(writer: W) -> Self {
        Self {
            inner: writer,
            headers_written: false,
            connection_close: false,
            write_timeout: None,
            egress: 0,
        }
    }

    /// Enforce a per-write deadline (see `crate::HttpConfig::response_timeout`).
    pub fn with_write_timeout(mut self, timeout: Option<Duration>) -> Self {
        self.write_timeout = timeout;
        self
    }

    /// Reset per-response state so the same writer can serve the next
    /// request on a keep-alive connection.
    pub fn reset(&mut self) {
        self.headers_written = false;
        self.connection_close = false;
    }

    /// Write with the configured deadline (R22).
    async fn write_all_with_timeout(&mut self, buf: &[u8]) -> Result<()> {
        match self.write_timeout {
            Some(timeout) => tokio::time::timeout(timeout, self.inner.write_all(buf))
                .await
                .map_err(|_| Error::Http("response write timed out".into()))??,
            None => self.inner.write_all(buf).await?,
        }
        // 出口码率统计:HLS 分片、HTTP-FLV、网页/API 响应都从这里出去,
        // 统一在这里记账(与 C 版的 guard_note_egress 对齐)。
        self.record_egress(buf.len());
        Ok(())
    }

    fn record_egress(&mut self, bytes: usize) {
        self.egress = self
            .egress
            .saturating_add(u64::try_from(bytes).unwrap_or(u64::MAX));
        if self.egress >= EGRESS_FLUSH_BYTES {
            self.flush_egress();
        }
    }

    fn flush_egress(&mut self) {
        if self.egress > 0 {
            rtflow_security::guard::global().note_egress(self.egress);
            self.egress = 0;
        }
    }

    /// Whether the response indicated the connection should be closed.
    pub fn should_close(&self) -> bool {
        self.connection_close
    }

    pub async fn write_headers(&mut self, status: u16, headers: &[(&str, &str)]) -> Result<()> {
        if self.headers_written {
            return Err(Error::Http("HTTP response headers already written".into()));
        }
        let reason = status_reason(status);
        let mut buf = format!("HTTP/1.1 {} {}\r\n", status, reason);
        for (key, value) in headers {
            if key.eq_ignore_ascii_case("connection") && value.eq_ignore_ascii_case("close") {
                self.connection_close = true;
            }
            buf.push_str(key);
            buf.push_str(": ");
            buf.push_str(value);
            buf.push_str("\r\n");
        }
        for (key, value) in SECURITY_HEADERS {
            if headers
                .iter()
                .any(|(existing, _)| existing.eq_ignore_ascii_case(key))
            {
                continue;
            }
            buf.push_str(key);
            buf.push_str(": ");
            buf.push_str(value);
            buf.push_str("\r\n");
        }
        buf.push_str("\r\n");
        self.write_all_with_timeout(buf.as_bytes()).await?;
        self.headers_written = true;
        Ok(())
    }

    pub async fn write_chunked_headers(
        &mut self,
        content_type: &str,
        extra_headers: &[(&str, &str)],
    ) -> Result<()> {
        let mut headers = vec![
            ("Transfer-Encoding", "chunked"),
            ("Content-Type", content_type),
            ("Cache-Control", "no-cache, no-store"),
            ("Connection", "keep-alive"),
        ];
        for (k, v) in extra_headers {
            headers.push((k, v));
        }
        self.write_headers(200, &headers).await
    }

    pub async fn write_chunk(&mut self, data: &[u8]) -> Result<()> {
        if !self.headers_written {
            return Err(Error::Http("HTTP chunk written before headers".into()));
        }
        if data.is_empty() {
            return Ok(());
        }
        let header = format!("{:x}\r\n", data.len());
        self.write_all_with_timeout(header.as_bytes()).await?;
        self.write_all_with_timeout(data).await?;
        self.write_all_with_timeout(b"\r\n").await?;
        Ok(())
    }

    /// Write raw bytes directly to the stream (no chunked framing).
    /// Use with `Transfer-Encoding: none` / `Connection: close` for streaming.
    pub async fn write_raw(&mut self, data: &[u8]) -> Result<()> {
        if data.is_empty() {
            return Ok(());
        }
        self.write_all_with_timeout(data).await?;
        Ok(())
    }

    pub async fn write_body(&mut self, status: u16, content_type: &str, body: &[u8]) -> Result<()> {
        let content_length = body.len().to_string();
        let headers = vec![
            ("Content-Type", content_type),
            ("Content-Length", content_length.as_str()),
            ("Cache-Control", "no-cache"),
            ("Connection", "close"),
            // HLS playlists and other bodies are consumed cross-origin by
            // browser players (hls.js etc).
            ("Access-Control-Allow-Origin", "*"),
        ];
        self.write_headers(status, &headers).await?;
        self.write_all_with_timeout(body).await?;
        Ok(())
    }

    pub async fn write_json(&mut self, status: u16, json: &str) -> Result<()> {
        self.write_body(status, "application/json", json.as_bytes())
            .await
    }

    pub async fn flush(&mut self) -> Result<()> {
        self.flush_egress();
        self.inner.flush().await.map_err(Error::from)
    }

    pub fn into_inner(mut self) -> W {
        self.flush_egress();
        self.inner
    }
}

fn status_reason(status: u16) -> &'static str {
    match status {
        200 => "OK",
        201 => "Created",
        204 => "No Content",
        206 => "Partial Content",
        301 => "Moved Permanently",
        302 => "Found",
        304 => "Not Modified",
        400 => "Bad Request",
        401 => "Unauthorized",
        403 => "Forbidden",
        404 => "Not Found",
        405 => "Method Not Allowed",
        408 => "Request Timeout",
        409 => "Conflict",
        416 => "Range Not Satisfiable",
        429 => "Too Many Requests",
        500 => "Internal Server Error",
        502 => "Bad Gateway",
        503 => "Service Unavailable",
        _ => "Unknown",
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    async fn render(headers: &[(&str, &str)]) -> String {
        let mut writer = ResponseWriter::new(Vec::new());
        writer.write_headers(200, headers).await.expect("headers");
        String::from_utf8_lossy(&writer.into_inner()).into_owned()
    }

    #[tokio::test]
    async fn every_response_carries_security_headers() {
        let text = render(&[]).await;
        assert!(
            text.contains("X-Content-Type-Options: nosniff\r\n"),
            "{text}"
        );
        assert!(text.contains("X-Frame-Options: DENY\r\n"), "{text}");
        assert!(text.contains("Referrer-Policy: no-referrer\r\n"), "{text}");
    }

    #[tokio::test]
    async fn handler_supplied_header_wins_and_is_not_duplicated() {
        let text = render(&[("X-Frame-Options", "SAMEORIGIN")]).await;
        assert_eq!(text.matches("X-Frame-Options").count(), 1, "{text}");
        assert!(text.contains("X-Frame-Options: SAMEORIGIN\r\n"), "{text}");
        assert!(
            text.contains("X-Content-Type-Options: nosniff\r\n"),
            "{text}"
        );
    }
}