capy-framework 0.10.0

An opinionated full-stack Rust web framework with strong conventions and sensible defaults.
Documentation
use crate::{AppError, Result};
use axum::{
    body::Body,
    extract::Request,
    http::{header, HeaderValue, Method, StatusCode},
    response::{IntoResponse, Response},
};
use std::path::{Path, PathBuf};
use tower::ServiceExt;
use tower_http::services::{ServeDir, ServeFile};

pub(crate) fn validate(directory: &Path) -> Result<()> {
    if !directory.join("index.html").is_file()
        || std::fs::File::open(directory.join("index.html")).is_err()
    {
        return Err(AppError::Configuration(format!(
            "Capy could not find the frontend build at {}.\n\nRun:\n\n    capy build\n\nDeploy frontend/dist alongside the binary and run from the application root.",
            directory.display()
        )));
    }
    Ok(())
}

pub(crate) async fn serve(directory: PathBuf, request: Request) -> Response {
    let path = request.uri().path();
    // This guard also reserves /api when no API routes are registered. A missing
    // endpoint must never turn into a successful HTML response.
    if path == "/api" || path.starts_with("/api/") {
        return AppError::NotFound.into_response();
    }
    if request.method() != Method::GET && request.method() != Method::HEAD {
        return AppError::MethodNotAllowed.into_response();
    }
    // Asset typos should return 404, rather than index.html with a wrong MIME type.
    let browser_route = !path.starts_with("/assets/")
        && !path.rsplit('/').next().unwrap_or("").contains('.')
        && !path.split('/').any(|segment| segment.starts_with('.'));
    let immutable = fingerprinted_asset(path);
    let (parts, _) = request.into_parts();
    let mut response = ServeDir::new(&directory)
        .append_index_html_on_directories(false)
        .oneshot(Request::from_parts(parts.clone(), Body::empty()))
        .await
        .unwrap_or_else(|never| match never {})
        .into_response();
    if response.status() != StatusCode::NOT_FOUND || !browser_route {
        cache(&mut response, immutable);
        return response;
    }
    let mut response = ServeFile::new(directory.join("index.html"))
        .oneshot(Request::from_parts(parts, Body::empty()))
        .await
        .unwrap_or_else(|never| match never {})
        .into_response();
    cache(&mut response, false);
    response
}

fn cache(response: &mut Response, immutable: bool) {
    if response.status().is_success() || response.status() == StatusCode::NOT_MODIFIED {
        let html = response
            .headers()
            .get(header::CONTENT_TYPE)
            .and_then(|value| value.to_str().ok())
            .is_some_and(|mime| mime.starts_with("text/html"));
        response.headers_mut().insert(
            header::CACHE_CONTROL,
            HeaderValue::from_static(if immutable && !html {
                "public, max-age=31536000, immutable"
            } else {
                "no-cache"
            }),
        );
    }
}

// Vite's default output is name-HASH.ext, with a URL-safe base64 hash. Only
// eligible /assets paths opt into immutable caching; HTML always revalidates.
fn fingerprinted_asset(path: &str) -> bool {
    path.starts_with("/assets/")
        && path
            .rsplit('/')
            .next()
            .and_then(|name| name.rsplit_once('.').map(|(stem, _)| stem))
            .is_some_and(|stem| {
                stem.match_indices('-').any(|(index, _)| {
                    let hash = &stem[index + 1..];
                    hash.len() == 8
                        && hash
                            .bytes()
                            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-'))
                })
            })
}