feat(rust): 批次 B 落盘批量化(write_files_atomic / rename_many)

This commit is contained in:
qiqi committed 2026-12-05 19:46:47 +08:00
1 parent e34d643c51
commit dd0d80513f
9 files changed
+210 -30

No files matched your search

+107
View File
@@ -447,6 +447,78 @@ async fn read_files_b64(base: String, rels: Vec<String>) -> Result<Vec<FileB64>,
}
#[derive(serde::Deserialize)]
struct WriteFileItem {
path: String,
text: String,
}
#[derive(serde::Serialize)]
struct WriteFileResult {
path: String,
ok: bool,
error: Option<String>,
}
#[tauri::command]
async fn write_files_atomic(base: String, files: Vec<WriteFileItem>) -> Result<Vec<WriteFileResult>, String> {
let base_path = std::path::PathBuf::from(&base);
let mut out = Vec::with_capacity(files.len());
for f in files {
let mut item = WriteFileResult { path: f.path.clone(), ok: false, error: None };
match resolve_under(&base_path, &f.path) {
Some(abs) => {
if let Some(parent) = abs.parent() {
let _ = tokio::fs::create_dir_all(parent).await;
}
let tmp = std::path::PathBuf::from(format!("{}.tmp", abs.display()));
match tokio::fs::write(&tmp, f.text.as_bytes()).await {
Ok(_) => match tokio::fs::rename(&tmp, &abs).await {
Ok(_) => item.ok = true,
Err(_) => {
let _ = tokio::fs::remove_file(&abs).await;
match tokio::fs::rename(&tmp, &abs).await {
Ok(_) => item.ok = true,
Err(e) => item.error = Some(e.to_string()),
}
}
},
Err(e) => item.error = Some(e.to_string()),
}
}
None => item.error = Some("bad-path".to_string()),
}
out.push(item);
}
Ok(out)
}
#[derive(serde::Deserialize)]
struct RenameItem {
from: String,
to: String,
}
#[tauri::command]
async fn rename_many(base: String, pairs: Vec<RenameItem>) -> Result<Vec<WriteFileResult>, String> {
let base_path = std::path::PathBuf::from(&base);
let mut out = Vec::with_capacity(pairs.len());
for p in pairs {
let mut item = WriteFileResult { path: p.from.clone(), ok: false, error: None };
match (resolve_under(&base_path, &p.from), resolve_under(&base_path, &p.to)) {
(Some(from), Some(to)) => match tokio::fs::rename(&from, &to).await {
Ok(_) => item.ok = true,
Err(e) => item.error = Some(e.to_string()),
},
_ => item.error = Some("bad-path".to_string()),
}
out.push(item);
}
Ok(out)
}
// 2026-12-04(文件版下载,默认关闭):流式写文件,避免整包 base64 过 IPC。
// 目标路径由 JS 提供(资料目录下的 cache/tmp/),这里只负责抓字节 + 落盘;失败会删半成品。
#[tauri::command]
@@ -2325,6 +2397,8 @@ pub fn run() {
read_text_many,
list_dir_entries,
read_files_b64,
write_files_atomic,
rename_many,
])
.setup(|app| {
if cfg!(debug_assertions) {
@@ -2594,3 +2668,36 @@ mod batch_io_tests {
}
}
#[cfg(test)]
mod batch_write_tests {
use super::*;
#[test]
fn write_and_rename_batch() {
let base = std::env::temp_dir().join(format!("iwb-batchw-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&base);
std::fs::create_dir_all(&base).unwrap();
let b = base.to_string_lossy().to_string();
tauri::async_runtime::block_on(async {
let files = vec![
WriteFileItem { path: "a/1.json".to_string(), text: "one".to_string() },
WriteFileItem { path: "a/2.json".to_string(), text: "two".to_string() },
WriteFileItem { path: "../evil.json".to_string(), text: "x".to_string() },
];
let r = write_files_atomic(b.clone(), files).await.unwrap();
assert!(r[0].ok && r[1].ok);
assert!(!r[2].ok);
assert_eq!(std::fs::read_to_string(base.join("a/1.json")).unwrap(), "one");
let pairs = vec![
RenameItem { from: "a/1.json".to_string(), to: "a/1b.json".to_string() },
RenameItem { from: "../evil.json".to_string(), to: "a/x.json".to_string() },
];
let rr = rename_many(b.clone(), pairs).await.unwrap();
assert!(rr[0].ok && !rr[1].ok);
assert!(base.join("a/1b.json").exists());
});
let _ = std::fs::remove_dir_all(&base);
}
}