Skip to main content

atmos/os_lib/web_engine/
cache_path.rs

1//! キャッシュのファイル名を組み立てる(純粋モジュール)。
2//!
3//! ファイルシステムにもネットワークにも触れないので、
4//! QEMU 抜きで検証できる。
5//!
6//! # 気をつける点
7//!
8//! - `FileMetadata::filename` は **128 バイト**まで(`kernel/fs/mod.rs`)。
9//!   超えると切り詰められ、**別の URL が同じ名前になって中身が入れ替わる**。
10//! - ホスト名の `:`(`example.com:8080`)は SylFS のパスに使えない。
11//! - 同じホストでもパスが違えば必ず違う名前になること。
12
13extern crate alloc;
14use alloc::string::String;
15use alloc::vec::Vec;
16
17/// 名前の最大長。`FileMetadata::filename`(128 バイト)に収まる必要がある。
18pub const MAX_CACHE_PATH_LEN: usize = 128;
19
20/// RAMDisk キャッシュ内で DEFLATE 圧縮済みエントリを表す 4 バイトマジック(TODO P6c)。
21pub const CACHE_GZIP_MAGIC: &[u8; 4] = b"AGZ1";
22
23/// これ未満の小さなデータは圧縮のオーバーヘッドの方が大きいため生で置く。
24pub const MIN_COMPRESS_SIZE: usize = 512;
25
26/// `host` と `path` からキャッシュ上の絶対パスを作る。
27///
28/// パスは FNV-1a で 16 桁の 16 進へ畳む。
29/// ホスト名はそのまま入れる(人が読んで分かるように)が、
30/// `:` だけは使えないので `-` へ置き換える。
31pub fn cache_path_for(host: &str, path: &str) -> String {
32    let mut h: u64 = 0xcbf2_9ce4_8422_2325;
33    for b in path.bytes() {
34        h ^= b as u64;
35        h = h.wrapping_mul(0x0000_0100_0000_01b3);
36    }
37    let safe_host: String = host
38        .chars()
39        .map(|c| if c == ':' { '-' } else { c })
40        .collect();
41    alloc::format!("/cache/browser/{}/{:016x}", safe_host, h)
42}
43
44/// 既に圧縮済みのバイナリ形式(WOFF2/PNG/JPEG/WebP/GIF/動画など)か判定する。
45pub fn is_already_compressed_resource(path: &str, data: &[u8]) -> bool {
46    if data.starts_with(CACHE_GZIP_MAGIC)
47        || data.starts_with(&[0x1f, 0x8b])
48        || data.starts_with(b"wOF2")
49        || data.starts_with(b"wOFF")
50        || data.starts_with(b"\x89PNG")
51        || data.starts_with(&[0xff, 0xd8, 0xff])
52        || data.starts_with(b"RIFF")
53        || data.starts_with(b"GIF8")
54    {
55        return true;
56    }
57    let clean = path.split('?').next().unwrap_or(path);
58    let lower = clean.to_ascii_lowercase();
59    lower.ends_with(".woff2")
60        || lower.ends_with(".woff")
61        || lower.ends_with(".png")
62        || lower.ends_with(".jpg")
63        || lower.ends_with(".jpeg")
64        || lower.ends_with(".webp")
65        || lower.ends_with(".gif")
66        || lower.ends_with(".mp4")
67        || lower.ends_with(".m4s")
68        || lower.ends_with(".webm")
69}
70
71/// キャッシュ保存用にペイロードを圧縮梱包する(TODO P6c)。
72///
73/// HTML・JS・CSS・JSON・SVG・TTF 等(512B 以上)を DEFLATE 圧縮し、縮んだ場合のみ
74/// `b"AGZ1" + 元の長さ(u32 LE) + 圧縮データ` として返す(66MB の RAMDisk に 3〜5 倍入る)。
75pub fn pack_cache_payload(path: &str, data: &[u8]) -> Vec<u8> {
76    if data.len() < MIN_COMPRESS_SIZE || is_already_compressed_resource(path, data) {
77        return data.to_vec();
78    }
79    let compressed = crate::os_lib::deflate_enc::deflate_raw(data);
80    if compressed.len().saturating_add(8) < data.len() {
81        let mut out = Vec::with_capacity(8 + compressed.len());
82        out.extend_from_slice(CACHE_GZIP_MAGIC);
83        out.extend_from_slice(&(data.len() as u32).to_le_bytes());
84        out.extend_from_slice(&compressed);
85        out
86    } else {
87        data.to_vec()
88    }
89}
90
91/// キャッシュから読み出したバイト列を復元する(`AGZ1` ヘッダ付きなら展開、それ以外はそのまま)。
92pub fn unpack_cache_payload(stored: Vec<u8>) -> Option<Vec<u8>> {
93    if stored.is_empty() {
94        return None;
95    }
96    if stored.starts_with(CACHE_GZIP_MAGIC) {
97        if stored.len() < 8 {
98            return None;
99        }
100        let orig_len = u32::from_le_bytes([stored[4], stored[5], stored[6], stored[7]]) as usize;
101        if orig_len == 0 || orig_len > crate::os_lib::deflate_enc::MAX_DECOMPRESSED_BYTES {
102            return None;
103        }
104        let options = zune_inflate::DeflateOptions::default()
105            .set_limit(orig_len.saturating_add(64))
106            // 【2026-11-19】TODO A7: 展開器は出力の末尾に約 300 バイトの余白を要り、ぴったりだと最後に倍へ伸ばす
107            // (2.9MB の JS で 5.9MB の一括確保)。余白を足して見積もる。
108            .set_size_hint(orig_len.saturating_add(1024));
109        let decoded = zune_inflate::DeflateDecoder::new_with_options(&stored[8..], options)
110            .decode_deflate()
111            .ok()?;
112        if decoded.len() != orig_len {
113            return None;
114        }
115        Some(decoded)
116    } else {
117        Some(stored)
118    }
119}