本篇是 Rspack 源码解析系列第三十七篇。前面多次出现
[contenthash],但哈希计算有个经典难题:文件名里含有 contenthash,而 contenthash 又是根据文件内容算出来的,文件内容又可能引用了其他文件的 hash------形成依赖环。本文进入crates/rspack_plugin_real_content_hash,看它如何把占位 hash 换成真实 hash,并处理 hash 之间的依赖排序。
前言:contenthash 的两难
理想情况下 [contenthash] 应该等于「最终产物内容的哈希」。但产物内容里可能嵌着别的文件的 hash(例如 runtime 里引用了 chunk 文件名)。于是:
text
文件名 = 前缀 + contenthash(内容) + 后缀
内容 = 可能包含其他文件的文件名(含它们的 hash)
这导致 hash 之间互相依赖。webpack 的做法是先用一个「占位 hash」生成文件名和内容,再在内容里搜索所有 hash,替换成真实 hash。Rspack 的 RealContentHashPlugin 就是这个替换过程的 Rust 实现。
源码入口:插件与 Hook 存储
crates/rspack_plugin_real_content_hash/src/lib.rs 顶部:
rust
static COMPILATION_HOOKS_MAP: LazyLock<FxDashMap<CompilationId, ArcReadContentHashPluginHooks>> =
LazyLock::new(Default::default);
#[plugin]
#[derive(Debug, Default)]
pub struct RealContentHashPlugin;
impl RealContentHashPlugin {
pub fn get_compilation_hooks(id: CompilationId) -> ArcReadContentHashPluginHooks { ... }
pub fn get_compilation_hooks_mut(id: CompilationId) -> ArcReadContentHashPluginHooks { ... }
}
这里有一个贯穿 Rspack 的模式:插件通过 CompilationId -> Hooks 的全局 map 暴露自己的编译级 Hook ,供其他插件(如第 38 篇的 SRI)tap 进来。AtomicRefCell 保证同 Hook 实例上没有读-写、写-写冲突。
clear_cache 在编译结束时清理:
rust
fn clear_cache(&self, id: CompilationId) {
COMPILATION_HOOKS_MAP.remove(&id);
}
process_assets:入口
主 Hook 在 PROCESS_ASSETS_STAGE_OPTIMIZE_HASH 阶段:
rust
#[plugin_hook(CompilationProcessAssets for RealContentHashPlugin, stage = Compilation::PROCESS_ASSETS_STAGE_OPTIMIZE_HASH)]
async fn process_assets(&self, compilation: &mut Compilation) -> Result<()> {
inner_impl(compilation).await
}
建立 hash 到 asset 名的映射
inner_impl 先遍历所有 asset,收集每个 hash 对应哪些文件名:
rust
let mut hash_to_asset_names: HashMap<&str, Vec<&str>> = HashMap::default();
for (name, asset) in compilation.assets().iter()
.filter(|(_, asset)| asset.get_source().is_some()) {
for hash in &asset.info.content_hash {
hash_to_asset_names.entry(hash).and_modify(|names| names.push(name))
.or_insert_with(|| vec![name]);
}
}
if hash_to_asset_names.is_empty() { return Ok(()); }
例如 [contenthash:8]-[contenthash:6].js 里两个 hash 都会记录,且都指向这个文件名。
Aho-Corasick 多模式匹配
搜索 hash 用 aho_corasick 库,一次扫描匹配所有 hash 模式:
rust
let hash_ac = AhoCorasick::builder()
.match_kind(MatchKind::LeftmostLongest)
.build(hash_to_asset_names.keys().map(|s| s.as_bytes()))
.expect("Invalid patterns");
LeftmostLongest 保证在重叠时优先匹配最长的 hash。注释解释了原因:
text
4afc|4afcbe match xxx.4afcbe-4afc.js -> xxx.[4afc]be-[4afc].js
4afcbe|4afc match xxx.4afcbe-4afc.js -> xxx.[4afcbe]-[4afc].js
如果 hash 有前缀关系,最短优先会切错。Aho-Corasick 一次扫描就能找到所有 hash 位置,比逐个 Regex::find 高效得多。
AssetData:解析内容里的 hash
AssetData::new 解析每个 asset 的内容,区分「自己的 hash」和「引用的 hash」:
rust
pub fn new(source: BoxSource, info: &AssetInfo, hash_ac: &AhoCorasick) -> Self {
let mut own_hashes = HashSet::default();
let mut referenced_hashes = HashSet::default();
let content = if let SourceValue::String(content) = source.source() {
for hash in hash_ac.find_iter(content.as_ref()) {
let hash = &content[hash.range()];
if info.content_hash.contains(hash) {
own_hashes.insert(hash.to_string()); // 自己名字里的 hash
continue;
}
referenced_hashes.insert(hash.to_string()); // 引用了别人的 hash
}
AssetDataContent::String(content.into_owned())
} else {
AssetDataContent::Buffer
};
// ...
}
只有字符串内容才需要替换 hash;二进制内容(Buffer)跳过。
OrderedHashesBuilder:hash 依赖拓扑排序
关键在 OrderedHashesBuilder。它建立 hash 之间的依赖图并排序:
rust
fn get_hash_dependencies(&self, hash: &str) -> HashSet<&str> {
// 找到引用了这个 hash 的 asset,收集这些 asset 自己的 hash 作为依赖
}
fn add_to_ordered_hashes(&self, hash, ordered_hashes, stack, hash_dependencies) {
let deps = hash_dependencies.entry(hash).or_insert_with(|| self.get_hash_dependencies(hash)).clone();
stack.insert(hash);
for dep in deps {
if ordered_hashes.contains(dep) { continue; }
if stack.contains(dep) {
panic!("RealContentHashPlugin: circular hash dependency");
}
self.add_to_ordered_hashes(dep, ordered_hashes, stack, hash_dependencies);
}
ordered_hashes.insert(hash.to_string());
stack.remove(hash);
}
这是典型的 DFS 拓扑排序:stack 检测环,ordered_hashes 记录已访问。注释解释了为什么可以有 panic:
text
Safety: all chunk-level hash will be collected in runtime chunk
so there shouldn't have circular hash dependency between chunks
所有 chunk 级 hash 都被收集进 runtime chunk,所以理论上不会出现 hash 环,一旦出现说明是 bug。
分批计算:先算无依赖的 hash
inner_impl 主循环按拓扑序分批处理:
rust
loop {
let Some(top) = top_task else { break; };
let mut batch = vec![top];
top_task = None;
for hash in ordered_hashes_iter.by_ref() {
let Some(dependencies) = hash_dependencies.remove(hash.as_str()) else {
top_task = Some(hash);
break;
};
if dependencies.iter().all(|dep| computed_hashes.contains(dep)) {
batch.push(hash);
} else {
top_task = Some(hash);
break;
}
}
// ... 计算这一批 hash
}
batch 是「依赖都已计算」的一批 hash,可以并行算。这样既保证依赖顺序,又能批量并行。
并行计算新 hash
每一批用 rspack_futures::scope 并发算新 hash:
rust
let new_hashes = rspack_futures::scope::<_, Result<_>>(|token| {
batch.iter().cloned().filter_map(|old_hash| {
let asset_names = hash_to_asset_names.remove(old_hash.as_str())?;
Some((old_hash, asset_names))
})
.for_each(|(old_hash, asset_names)| {
let s = unsafe { token.used((&hooks, &compilation, &batch_sources, old_hash, asset_names)) };
s.spawn(|(hooks, compilation, batch_sources, old_hash, mut asset_names)| async move {
asset_names.sort_unstable();
let mut asset_contents = asset_names.iter()
.filter_map(|name| batch_sources.get(&(old_hash.as_str(), name)))
.cloned().collect::<Vec<_>>();
asset_contents.dedup();
let updated_hash = hooks.borrow().update_hash.call(compilation, &asset_contents, &old_hash).await?;
let new_hash = if let Some(new_hash) = updated_hash {
new_hash
} else {
let mut hasher = RspackHash::from(&compilation.options.output);
for asset_content in asset_contents {
hasher.write(&asset_content.buffer());
}
let new_hash = hasher.digest(&compilation.options.output.hash_digest);
new_hash.rendered(old_hash.len()).to_string()
};
Ok((old_hash.clone(), new_hash))
});
});
}).await.into_iter().map(|r| r.to_rspack_result()).collect::<Result<Vec<_>>>()?;
注意 update_hash 是插件 Hook:其他插件(如 SRI)可以 tap 它,自定义 hash 计算方式。没被覆盖时,默认用 RspackHash 对 asset 内容做 digest。
替换 hash:文件名 + 内容
最后一步,用 hash_to_new_hash 替换文件名和内容里的旧 hash:
rust
let updates: Vec<_> = assets_data.into_par_iter().filter_map(|(name, data)| {
let new_source = data.compute_new_source(false, &hash_to_new_hash, &hash_ac);
let mut new_name = String::with_capacity(name.len());
hash_ac.replace_all_with(name, &mut new_name, |_, hash, dst| {
let replace_to = hash_to_new_hash.get(hash).expect("should have new hash");
dst.push_str(replace_to);
true
});
let new_name = (name != new_name).then_some(new_name);
Some((name.to_owned(), new_source, new_name))
}).collect();
compute_new_source 用 Aho-Corasick 的 replace_all_with 替换内容里的 hash;文件名同理。最后 update_asset 更新内容,par_rename_assets 批量重命名文件。
AssetData 的缓存:OnceCell
AssetData 用 OnceCell 缓存计算结果,避免重复替换:
rust
struct AssetData {
own_hashes: HashSet<String>,
referenced_hashes: HashSet<String>,
#[debug(skip)] old_source: BoxSource,
#[debug(skip)] content: AssetDataContent,
#[debug(skip)] new_source: OnceCell<BoxSource>,
#[debug(skip)] new_source_without_own: OnceCell<BoxSource>,
}
compute_new_source 里 get_or_init 保证只算一次:
rust
(if without_own { &self.new_source_without_own } else { &self.new_source })
.get_or_init(|| { /* 替换逻辑 */ })
.clone()
without_own 用于处理「自己的 hash 在中间阶段需要临时清空」的场景,避免自引用。
Rust 角度:拓扑排序 + 多模式匹配
这个插件是 Rust 性能优势的集中体现:
- Aho-Corasick:一次扫描匹配所有 hash,复杂度与 hash 数量无关(只与内容长度有关);
- 拓扑排序:正确建模 hash 依赖,保证替换顺序;
- rayon 并行 :
par_iter并行处理 asset 和 hash 计算; - OnceCell 缓存:避免重复替换。
对比 webpack 的 JS 实现,这些算法在 Rust 里更紧凑、更快。
这一篇应该带走什么
- contenthash 先占位后替换,解决「内容依赖文件名」的循环;
- Aho-Corasick 一次扫描匹配所有 hash,
LeftmostLongest处理前缀重叠; AssetData区分 own_hashes 与 referenced_hashes;OrderedHashesBuilder用 DFS 拓扑排序 hash 依赖,panic 检测环;- 分批并行计算 hash,
update_hashHook 允许插件自定义。