rust-web-utils 0.1.0

Lightweight web utilities: client IP & trusted proxies, bot/browser detection, unified JSON response, business timezone, auth cookies + CSRF, cron guards, Next.js static export hosting
Documentation
//! 导出目录快照: 文件索引 + 按需填充的 HTML 缓存

use std::collections::{HashMap, HashSet};
use std::fs;
use std::io;
use std::path::Path;
use std::sync::{PoisonError, RwLock};

use bytes::Bytes;

use super::Error;

/// HTML 内存缓存的默认总量上限
const DEFAULT_HTML_CACHE_MAX_BYTES: i64 = 64 << 20;

/// 导出目录在某一时刻的快照。路径解析的存在性判断全部走索引, 未命中请求 (扫描器打随机路径)
/// 不产生 stat 系统调用; 快照整体替换 (reload), `files` 构建后只读
pub(super) struct Snapshot {
    /// 普通文件集合, key 为相对导出根、以 `/` 开头的斜杠路径 (区分大小写)
    files: HashSet<String>,
    html_max: i64,
    html: RwLock<HtmlCache>,
}

#[derive(Default)]
struct HtmlCache {
    entries: HashMap<String, Bytes>,
    bytes: i64,
}

impl Snapshot {
    /// 遍历导出目录建立文件索引; 指向普通文件的符号链接收录, 符号链接目录不展开
    pub(super) fn build(root: &Path, html_max: i64) -> Result<Self, Error> {
        // 遍历不跟随符号链接, Root 本身是链接时先解析
        let resolved = fs::canonicalize(root).map_err(|e| Error::Index(root.to_path_buf(), e))?;
        let mut files = HashSet::new();
        walk(&resolved, "", &mut files).map_err(|e| Error::Index(root.to_path_buf(), e))?;
        let html_max = if html_max == 0 {
            DEFAULT_HTML_CACHE_MAX_BYTES
        } else {
            html_max
        };
        Ok(Self {
            files,
            html_max,
            html: RwLock::default(),
        })
    }

    pub(super) fn contains(&self, key: &str) -> bool {
        self.files.contains(key)
    }

    /// 返回缓存的 HTML
    pub(super) fn cached_html(&self, key: &str) -> Option<Bytes> {
        self.html
            .read()
            .unwrap_or_else(PoisonError::into_inner)
            .entries
            .get(key)
            .cloned()
    }

    /// 写入 HTML 缓存; 总量达到上限后新文件不再入缓存 (退化为每次读盘), 不做淘汰。
    /// 并发首读时以先入缓存者为准
    pub(super) fn store_html(&self, key: &str, body: Bytes) -> Bytes {
        let mut cache = self.html.write().unwrap_or_else(PoisonError::into_inner);
        if let Some(existing) = cache.entries.get(key) {
            return existing.clone();
        }
        let len = i64::try_from(body.len()).unwrap_or(i64::MAX);
        if cache.bytes.saturating_add(len) <= self.html_max {
            cache.bytes += len;
            cache.entries.insert(key.to_owned(), body.clone());
        }
        body
    }
}

fn walk(dir: &Path, prefix: &str, files: &mut HashSet<String>) -> io::Result<()> {
    for entry in fs::read_dir(dir)? {
        let entry = entry?;
        // 非 UTF-8 文件名无法被 UTF-8 请求路径命中, 跳过
        let Some(name) = entry.file_name().to_str().map(str::to_owned) else {
            continue;
        };
        let key = format!("{prefix}/{name}");
        let ft = entry.file_type()?;
        if ft.is_dir() {
            walk(&entry.path(), &key, files)?;
        } else if ft.is_symlink() {
            // 只收录指向普通文件的链接; 链接目录与断链跳过
            if fs::metadata(entry.path()).is_ok_and(|m| m.is_file()) {
                files.insert(key);
            }
        } else if ft.is_file() {
            files.insert(key);
        }
    }
    Ok(())
}