Dough Git

clove/allInOne

src/http.rs

back to src

// src/http.rs

use std::{
    collections::HashMap,
    path::{Component, Path, PathBuf},
    sync::Arc,
};

use futures_util::{SinkExt, StreamExt};
use http_body_util::{BodyExt, Full, Limited};
use hyper::{
    Method, Request, Response, StatusCode,
    body::{Bytes, Incoming},
    header,
    server::conn::http1,
    service::service_fn,
};
use hyper_util::rt::TokioIo;
use serde_json::{Value, json};
use tokio::{net::TcpListener, sync::broadcast};
use tokio_tungstenite::{
    WebSocketStream,
    tungstenite::{Message, handshake::derive_accept_key, protocol::Role},
};

use crate::{
    storage_event,
    store::{self, Store},
    web_api,
};

pub type Reply = Response<Full<Bytes>>;
pub type Query = HashMap<String, String>;
pub const JPCL: &str = "application/jpcl";

#[derive(Debug)]
pub struct Error(pub StatusCode, pub String);

impl Error {
    pub fn invalid(message: impl Into<String>) -> Self {
        Self(StatusCode::UNPROCESSABLE_ENTITY, message.into())
    }

    pub fn missing(message: impl Into<String>) -> Self {
        Self(StatusCode::NOT_FOUND, message.into())
    }
}

impl From<anyhow::Error> for Error {
    fn from(error: anyhow::Error) -> Self {
        eprintln!("System request failed: {error:#}");
        Self(
            StatusCode::INTERNAL_SERVER_ERROR,
            "Internal server error".into(),
        )
    }
}

pub fn reply(status: StatusCode, mime: &str, content: impl Into<Bytes>) -> Reply {
    Response::builder()
        .status(status)
        .header(header::CONTENT_TYPE, mime)
        .header(header::X_CONTENT_TYPE_OPTIONS, "nosniff")
        .body(Full::new(content.into()))
        .expect("valid response")
}

pub fn document(
    status: StatusCode,
    value: &Value,
    format: &str,
    wrapper: &str,
) -> Result<Reply, Error> {
    match format {
        "json" => Ok(reply(status, "application/json", value.to_string())),
        // JSON flow syntax is also valid YAML 1.2.
        "yml" => Ok(reply(status, "application/yaml", value.to_string())),
        "jpcl" | "plain" => {
            let value = if value.is_array() {
                json!({ wrapper: value })
            } else {
                value.clone()
            };
            let mime = if format == "jpcl" {
                JPCL
            } else {
                "text/plain; charset=utf-8"
            };
            Ok(reply(status, mime, store::encode(&value)?))
        }
        _ => Err(Error::invalid("Unknown response format")),
    }
}

pub fn bearer(request: &Request<Incoming>) -> Option<&str> {
    let (scheme, token) = request
        .headers()
        .get(header::AUTHORIZATION)?
        .to_str()
        .ok()?
        .split_once(' ')?;
    scheme.eq_ignore_ascii_case("bearer").then_some(token)
}

pub async fn body(request: &mut Request<Incoming>) -> Result<Value, Error> {
    let jpcl = request
        .headers()
        .get(header::CONTENT_TYPE)
        .and_then(|value| value.to_str().ok())
        .is_some_and(|value| value.split(';').next() == Some(JPCL));
    let bytes = bytes(request, 1024 * 1024).await?;
    let value = if jpcl {
        std::str::from_utf8(&bytes)
            .ok()
            .and_then(|text| store::decode(text).ok())
    } else {
        serde_json::from_slice(&bytes).ok()
    };
    value.filter(Value::is_object).ok_or_else(|| {
        Error(
            StatusCode::BAD_REQUEST,
            "Expected a JPCL or JSON object".into(),
        )
    })
}

pub async fn bytes(request: &mut Request<Incoming>, limit: usize) -> Result<Bytes, Error> {
    Limited::new(request.body_mut(), limit)
        .collect()
        .await
        .map(|body| body.to_bytes())
        .map_err(|_| {
            Error(
                StatusCode::PAYLOAD_TOO_LARGE,
                "Could not read request body".into(),
            )
        })
}

pub async fn serve(listener: TcpListener, state: Arc<web_api::Web>) -> anyhow::Result<()> {
    loop {
        let (stream, _) = listener.accept().await?;
        let state = state.clone();
        tokio::spawn(connection(stream, state));
    }
}

pub(crate) async fn connection(
    stream: impl tokio::io::AsyncRead + tokio::io::AsyncWrite + Send + Unpin + 'static,
    state: Arc<web_api::Web>,
) {
    let service = service_fn(move |request| {
        let state = state.clone();
        async move { Ok::<_, std::convert::Infallible>(handle(request, state).await) }
    });
    let _ = http1::Builder::new()
        .serve_connection(TokioIo::new(stream), service)
        .with_upgrades()
        .await;
}

async fn handle(mut request: Request<Incoming>, state: Arc<web_api::Web>) -> Reply {
    let query: Query = reqwest::Url::parse("http://localhost/")
        .map(|mut url| {
            url.set_query(request.uri().query());
            url.query_pairs().into_owned().collect()
        })
        .unwrap_or_default();
    let request_path = request.uri().path().to_owned();
    let path: Vec<_> = request_path
        .trim_start_matches('/')
        .split('/')
        .map(|part| percent_encoding::percent_decode_str(part).decode_utf8())
        .collect::<Result<_, _>>()
        .unwrap_or_default();
    let path: Vec<_> = path.iter().map(|part| part.as_ref()).collect();
    let wants_jpcl = request
        .headers()
        .get(header::ACCEPT)
        .and_then(|value| value.to_str().ok())
        .is_some_and(|value| {
            value
                .split(',')
                .any(|entry| entry.trim().eq_ignore_ascii_case(JPCL))
        });
    let error_format = if wants_jpcl { "jpcl" } else { "json" };

    let result = match path.as_slice() {
        ["api", "plural", "ws"] if request.method() == Method::GET => {
            websocket(&mut request, &state.store)
        }
        ["api", "plural", rest @ ..] => {
            web_api::route(&state, &mut request, rest, &query, wants_jpcl).await
        }
        ["api", "openapi.json" | "openapi.jp"] => web_api::openapi(&state, &request, path[1]).await,
        ["api", ..] => Err(Error::missing("Unknown route")),
        _ if *request.method() == Method::GET || *request.method() == Method::HEAD => {
            static_file(&state.web_root, &path).await
        }
        _ => Err(Error::missing("Unknown route")),
    };

    let mut response = match result {
        Ok(response) => response,
        Err(Error(status, message)) => {
            let mut response = document(status, &json!({ "detail": message }), error_format, "")
                .unwrap_or_else(|_| {
                    reply(
                        StatusCode::INTERNAL_SERVER_ERROR,
                        "text/plain",
                        "Internal server error",
                    )
                });
            if status == StatusCode::UNAUTHORIZED {
                response.headers_mut().insert(
                    header::WWW_AUTHENTICATE,
                    header::HeaderValue::from_static("Bearer"),
                );
            }
            response
        }
    };
    if path.first() == Some(&"api") && response.status() != StatusCode::SWITCHING_PROTOCOLS {
        response
            .headers_mut()
            .insert(header::VARY, header::HeaderValue::from_static("Accept"));
        response.headers_mut().insert(
            header::CACHE_CONTROL,
            header::HeaderValue::from_static("no-store"),
        );
    }
    if request.method() == Method::HEAD {
        *response.body_mut() = Full::default();
    }
    response
}

async fn static_file(root: &Path, segments: &[&str]) -> Result<Reply, Error> {
    let mut path = PathBuf::from(root);
    for segment in segments.iter().filter(|segment| !segment.is_empty()) {
        let mut components = Path::new(segment).components();
        if !matches!(components.next(), Some(Component::Normal(_)))
            || components.next().is_some()
            || segment.starts_with('.')
            || segment.contains(['/', '\\'])
        {
            return Err(Error::missing("File not found"));
        }
        path.push(segment);
    }

    if let Ok(content) = tokio::fs::read(&path).await {
        return Ok(reply(
            StatusCode::OK,
            mime_guess::from_path(path)
                .first_or_octet_stream()
                .essence_str(),
            content,
        ));
    }
    if segments.first() == Some(&"_app")
        || segments.last().is_some_and(|segment| segment.contains('.'))
    {
        return Err(Error::missing("File not found"));
    }
    let content = tokio::fs::read(root.join("index.html"))
        .await
        .map_err(|_| {
            Error(
                StatusCode::SERVICE_UNAVAILABLE,
                "Build the website in web/ first".into(),
            )
        })?;
    Ok(reply(StatusCode::OK, "text/html; charset=utf-8", content))
}

fn websocket(request: &mut Request<Incoming>, store: &Arc<Store>) -> Result<Reply, Error> {
    let has_token = |name, token: &str| {
        request
            .headers()
            .get(name)
            .and_then(|value| value.to_str().ok())
            .is_some_and(|value| {
                value
                    .split(',')
                    .any(|entry| entry.trim().eq_ignore_ascii_case(token))
            })
    };
    let key = request
        .headers()
        .get(header::SEC_WEBSOCKET_KEY)
        .filter(|_| {
            has_token(header::UPGRADE, "websocket")
                && has_token(header::CONNECTION, "upgrade")
                && has_token(header::SEC_WEBSOCKET_VERSION, "13")
        })
        .ok_or_else(|| Error(StatusCode::BAD_REQUEST, "WebSocket upgrade required".into()))?;
    let accept = derive_accept_key(key.as_bytes());
    let jpcl = has_token(header::SEC_WEBSOCKET_PROTOCOL, "jpcl");
    let mut events = store.events.subscribe();
    let upgrade = hyper::upgrade::on(request);

    tokio::spawn(async move {
        let Ok(stream) = upgrade.await else { return };
        let mut socket =
            WebSocketStream::from_raw_socket(TokioIo::new(stream), Role::Server, None).await;
        loop {
            let outgoing = tokio::select! {
                frame = socket.next() => match frame {
                    Some(Ok(Message::Text(text))) if text == "ping" => Message::Text("pong".into()),
                    Some(Ok(Message::Ping(payload))) => Message::Pong(payload),
                    Some(Ok(Message::Close(_)) | Err(_)) | None => break,
                    _ => continue,
                },
                event = events.recv() => {
                    let event = match event {
                        Ok(event) => event,
                        Err(broadcast::error::RecvError::Lagged(_)) => storage_event("force_refresh", Value::Null),
                        Err(broadcast::error::RecvError::Closed) => break,
                    };
                    let text = if jpcl { store::encode(&event) } else { Ok(event.to_string()) };
                    let Ok(text) = text else { continue };
                    Message::Text(text)
                }
            };
            if socket.send(outgoing).await.is_err() {
                break;
            }
        }
    });

    let mut response = Response::builder()
        .status(StatusCode::SWITCHING_PROTOCOLS)
        .header(header::UPGRADE, "websocket")
        .header(header::CONNECTION, "upgrade")
        .header(header::SEC_WEBSOCKET_ACCEPT, accept);
    if jpcl {
        response = response.header(header::SEC_WEBSOCKET_PROTOCOL, "jpcl");
    }
    Ok(response.body(Full::default()).expect("valid handshake"))
}