动态根据发送方和接收方内存调整分块大小

This commit is contained in:
captain committed 2026-03-03 15:31:42 +08:00
1 parent 7612bd3776
commit f4364a07af
5 files changed
+112 -58

No files matched your search

+1 -1
View File
@@ -22,7 +22,7 @@ required-features = ["web"]
[features]
default = ["desktop"]
desktop = ["tauri", "tauri-plugin-shell", "tauri-plugin-fs", "tauri-plugin-dialog", "tauri-plugin-sql", "tauri-plugin-log", "tauri-plugin-single-instance", "tauri-build", "sysinfo"]
web = []
web = ["sysinfo"]
[build-dependencies]
tauri-build = { version = "2.0", features = [], optional = true }
+51 -26
View File
@@ -2,7 +2,7 @@
use crate::db::DbState;
use crate::peers::{Peer, PeerManager};
use std::sync::Arc;
use tauri::State;
use tauri::{State, Manager};
// 用于管理 PeerManager 的状态
@@ -12,7 +12,7 @@ pub struct PeerState {
/// 根据设备内存和文件大小计算最优分块大小
#[cfg(feature = "desktop")]
fn calculate_optimal_chunk_size(file_size: usize) -> usize {
fn calculate_optimal_chunk_size(_file_size: usize) -> usize {
use sysinfo::System;
let mut sys = System::new_all();
@@ -24,20 +24,14 @@ fn calculate_optimal_chunk_size(file_size: usize) -> usize {
// 使用可用内存的 80%(大胆使用内存以获得更快的速度)
let max_chunk_memory = available_memory * 80 / 100;
// 根据文件大小选择基础分块大小
let base_chunk_size = if file_size < 100 * 1024 * 1024 {
50 * 1024 * 1024 // < 100MB: 50MB
} else if file_size < 500 * 1024 * 1024 {
100 * 1024 * 1024 // 100-500MB: 100MB
} else if file_size < 1024 * 1024 * 1024 {
200 * 1024 * 1024 // 500MB-1GB: 200MB
} else if file_size < 5 * 1024 * 1024 * 1024 {
300 * 1024 * 1024 // 1-5GB: 300MB
} else {
500 * 1024 * 1024 // > 5GB: 500MB
};
let chunk_size = std::cmp::min(base_chunk_size, max_chunk_memory);
// 动态计算分块大小:使用可用内存的 80%,但最小 50MB,最大 500MB
let chunk_size = std::cmp::max(
50 * 1024 * 1024, // 最小 50MB
std::cmp::min(
max_chunk_memory, // 使用可用内存的 80%
500 * 1024 * 1024 // 最大 500MB
)
);
println!("[Command] 系统可用内存: {} MB", available_memory / (1024 * 1024));
println!("[Command] 内存预算: {} MB", max_chunk_memory / (1024 * 1024));
@@ -134,7 +128,7 @@ pub async fn get_chat_history(
#[tauri::command]
pub async fn send_file(
_app: tauri::AppHandle,
app: tauri::AppHandle,
state: State<'_, DbState>,
peer_id: String,
peer_addr: String,
@@ -219,12 +213,32 @@ pub async fn send_file(
// 获取自己的 ID(发送者 ID)
let my_id = crate::db::get_user_id(&state.pool).await?;
// 获取接收方的可用内存
let receiver_memory_mb = if let Some(peer_state) = app.try_state::<PeerState>() {
let peers = peer_state.manager.get_all_peers();
peers.iter()
.find(|p| p.addr.starts_with(&peer_addr.split(':').next().unwrap_or("")))
.map(|p| p.available_memory_mb)
.unwrap_or(1024) // 默认 1GB
} else {
1024 // 默认 1GB
};
println!("[Command] 接收方可用内存: {} MB", receiver_memory_mb);
// 分块上传
let chunk_size = calculate_optimal_chunk_size(file_size);
let total_chunks = (file_size + chunk_size - 1) / chunk_size;
// 根据接收方内存调整分块大小(取发送方和接收方的最小值)
let max_chunk_for_receiver = std::cmp::max(50 * 1024 * 1024, receiver_memory_mb as usize * 1024 * 1024 / 4); // 接收方内存的 1/4
let adjusted_chunk_size = std::cmp::min(chunk_size, max_chunk_for_receiver);
println!("[Command] 原始分块大小: {} MB, 调整后: {} MB", chunk_size / (1024 * 1024), adjusted_chunk_size / (1024 * 1024));
let total_chunks = (file_size + adjusted_chunk_size - 1) / adjusted_chunk_size;
println!("[Command] 开始分块上传: 文件大小={}, 分块大小={}, 总分块数={}",
file_size, chunk_size, total_chunks);
file_size, adjusted_chunk_size, total_chunks);
let client = reqwest::Client::builder()
.timeout(std::time::Duration::from_secs(300))
@@ -243,17 +257,28 @@ pub async fn send_file(
let start_time = std::time::Instant::now();
loop {
// 读取分块
let mut buf = vec![0u8; chunk_size];
let n = tokio::io::AsyncReadExt::read(&mut file, &mut buf)
.await
.map_err(|e| format!("读取文件失败: {}", e))?;
// 读取分块(循环读取直到填满缓冲区或文件结束)
let mut buf = vec![0u8; adjusted_chunk_size];
let mut bytes_read = 0;
if n == 0 {
while bytes_read < adjusted_chunk_size {
let n = tokio::io::AsyncReadExt::read(&mut file, &mut buf[bytes_read..])
.await
.map_err(|e| format!("读取文件失败: {}", e))?;
if n == 0 {
break; // 文件读取完毕
}
bytes_read += n;
}
if bytes_read == 0 {
break; // 文件读取完毕
}
buf.truncate(n);
buf.truncate(bytes_read);
let n = bytes_read;
// 构造 multipart 请求
let form = reqwest::multipart::Form::new()
+20 -11
View File
@@ -36,7 +36,7 @@ fn create_broadcast_socket(bind_addr: &str) -> Result<UdpSocket, std::io::Error>
Ok(socket.into())
}
// 统一端口广播 - 动态获取用户名
// 统一端口广播 - 动态获取用户名和可用内存
pub async fn start_announcing(port: u16, user_id: String, pool: sqlx::Pool<sqlx::Sqlite>) {
let socket = match create_broadcast_socket("0.0.0.0:0") {
Ok(s) => s,
@@ -59,7 +59,13 @@ pub async fn start_announcing(port: u16, user_id: String, pool: sqlx::Pool<sqlx:
}
};
let msg = format!("LANChat|ONLINE|{}|{}|{}", user_id, username, port);
// 获取可用内存(MB)
use sysinfo::System;
let mut sys = System::new_all();
sys.refresh_all();
let available_memory_mb = sys.available_memory() / 1024; // 转换为 MB
let msg = format!("LANChat|ONLINE|{}|{}|{}|{}", user_id, username, port, available_memory_mb);
match socket.send_to(msg.as_bytes(), &broadcast_addr) {
Ok(size) => println!("[UDP] 广播成功: {} 字节 -> {}", size, broadcast_addr),
Err(e) => eprintln!("[UDP] 广播失败: {}", e),
@@ -88,11 +94,12 @@ pub async fn start_listening(port: u16, my_id: String, _my_name: String, app: Op
let msg = String::from_utf8_lossy(&buf[..size]);
let parts: Vec<&str> = msg.split('|').collect();
// 新协议: LANChat|ONLINE|UUID|用户名|端口
if parts.len() >= 5 && parts[0] == "LANChat" {
// 新协议: LANChat|ONLINE|UUID|用户名|端口|可用内存(MB)
if parts.len() >= 6 && parts[0] == "LANChat" {
let peer_id = parts[2].to_string();
let name = parts[3].to_string();
let peer_port = parts[4];
let available_memory_mb: u64 = parts[5].parse().unwrap_or(0);
// 忽略自己
if peer_id == my_id {
@@ -100,10 +107,10 @@ pub async fn start_listening(port: u16, my_id: String, _my_name: String, app: Op
}
let peer_addr = format!("{}:{}", addr.ip(), peer_port);
println!("[UDP] 发现用户: {} ({}) at {}", name, peer_id, peer_addr);
println!("[UDP] 发现用户: {} ({}) at {} (可用内存: {} MB)", name, peer_id, peer_addr, available_memory_mb);
// 添加到全局用户列表
peer_manager.add_or_update(peer_id.clone(), name.clone(), peer_addr.clone());
peer_manager.add_or_update_with_memory(peer_id.clone(), name.clone(), peer_addr.clone(), available_memory_mb);
// 只有当 app 存在时(桌面端)才发送事件
if let Some(app_handle) = &app {
@@ -112,7 +119,8 @@ pub async fn start_listening(port: u16, my_id: String, _my_name: String, app: Op
serde_json::json!({
"id": peer_id,
"name": name,
"addr": peer_addr
"addr": peer_addr,
"available_memory_mb": available_memory_mb
}),
);
}
@@ -141,11 +149,12 @@ pub async fn start_listening(port: u16, my_id: String, _my_name: String, peer_ma
let msg = String::from_utf8_lossy(&buf[..size]);
let parts: Vec<&str> = msg.split('|').collect();
// 新协议: LANChat|ONLINE|UUID|用户名|端口
if parts.len() >= 5 && parts[0] == "LANChat" {
// 新协议: LANChat|ONLINE|UUID|用户名|端口|可用内存(MB)
if parts.len() >= 6 && parts[0] == "LANChat" {
let peer_id = parts[2].to_string();
let name = parts[3].to_string();
let peer_port = parts[4];
let available_memory_mb: u64 = parts[5].parse().unwrap_or(0);
// 忽略自己
if peer_id == my_id {
@@ -153,10 +162,10 @@ pub async fn start_listening(port: u16, my_id: String, _my_name: String, peer_ma
}
let peer_addr = format!("{}:{}", addr.ip(), peer_port);
println!("[UDP] 发现用户: {} ({}) at {}", name, peer_id, peer_addr);
println!("[UDP] 发现用户: {} ({}) at {} (可用内存: {} MB)", name, peer_id, peer_addr, available_memory_mb);
// 添加到全局用户列表
peer_manager.add_or_update(peer_id, name, peer_addr);
peer_manager.add_or_update_with_memory(peer_id, name, peer_addr, available_memory_mb);
}
}
}
+11 -3
View File
@@ -11,6 +11,7 @@ pub struct Peer {
pub addr: String,
pub last_seen: u64, // Unix 时间戳
pub is_offline: bool, // 是否离线
pub available_memory_mb: u64, // 可用内存(MB)
}
// 全局在线用户列表
@@ -27,6 +28,11 @@ impl PeerManager {
// 添加或更新用户
pub fn add_or_update(&self, id: String, name: String, addr: String) {
self.add_or_update_with_memory(id, name, addr, 0);
}
// 添加或更新用户(包含内存信息)
pub fn add_or_update_with_memory(&self, id: String, name: String, addr: String, available_memory_mb: u64) {
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
@@ -41,11 +47,12 @@ impl PeerManager {
peer.addr = addr;
peer.last_seen = now;
peer.is_offline = false;
peer.available_memory_mb = available_memory_mb;
if was_offline {
println!("[PeerManager] 用户重新上线: {} ({})", peer.name, peer.id);
println!("[PeerManager] 用户重新上线: {} ({}) - 可用内存: {} MB", peer.name, peer.id, available_memory_mb);
} else {
println!("[PeerManager] 更新用户: {} ({})", peer.name, peer.id);
println!("[PeerManager] 更新用户: {} ({}) - 可用内存: {} MB", peer.name, peer.id, available_memory_mb);
}
} else {
// 新用户
@@ -55,8 +62,9 @@ impl PeerManager {
addr,
last_seen: now,
is_offline: false,
available_memory_mb,
};
println!("[PeerManager] 添加新用户: {} ({})", name, id);
println!("[PeerManager] 添加新用户: {} ({}) - 可用内存: {} MB", name, id, available_memory_mb);
peers.insert(id, peer);
}
}
+29 -17
View File
@@ -321,20 +321,20 @@ function calculateOptimalChunkSize(fileSize) {
// 使用可用内存的 80%(大胆使用内存以获得更快的速度)
const maxChunkMemory = availableMemory * 0.8;
// 根据文件大小选择分块策略
// 根据文件大小选择分块策略,基础大小调大
let baseChunkSize;
if (fileSize < 100 * 1024 * 1024) {
// < 100MB:50MB 分块
baseChunkSize = 50 * 1024 * 1024;
} else if (fileSize < 500 * 1024 * 1024) {
// 100-500MB:100MB 分块
// < 100MB:100MB 分块
baseChunkSize = 100 * 1024 * 1024;
} else if (fileSize < 1024 * 1024 * 1024) {
// 500MB-1GB:200MB 分块
} else if (fileSize < 500 * 1024 * 1024) {
// 100-500MB:200MB 分块
baseChunkSize = 200 * 1024 * 1024;
} else if (fileSize < 5 * 1024 * 1024 * 1024) {
// 1-5GB:300MB 分块
} else if (fileSize < 1024 * 1024 * 1024) {
// 500MB-1GB:300MB 分块
baseChunkSize = 300 * 1024 * 1024;
} else if (fileSize < 5 * 1024 * 1024 * 1024) {
// 1-5GB:400MB 分块
baseChunkSize = 400 * 1024 * 1024;
} else {
// > 5GB:500MB 分块
baseChunkSize = 500 * 1024 * 1024;
@@ -418,6 +418,12 @@ async function apiSendFile(peerId, peerAddr, file) {
console.log("[JS-API] 文件名:", fileName, "大小:", fileSize, "字节");
// 检查 fileSize 是否有效
if (fileSize <= 0) {
console.error("[JS-API] ✗ 文件大小无效:", fileSize);
throw new Error("无法获取文件大小");
}
// 立即保存"上传中"消息到数据库,让UI显示
console.log("[JS-API] 立即保存上传中消息到数据库");
let messageId = null;
@@ -454,23 +460,31 @@ async function apiSendFile(peerId, peerAddr, file) {
try {
const file = await tauri.fs.open(filePath, { read: true });
const bufferSize = 2 * 1024 * 1024; // 2MB 缓冲区用于读取
while (offset < fileSize) {
const size = Math.min(chunkSize, fileSize - offset);
const buf = new Uint8Array(size);
await file.read(buf, { at: offset });
let bytesRead = 0;
// 分多次读取以填满 chunkSize 的缓冲区
while (bytesRead < size) {
const toRead = Math.min(bufferSize, size - bytesRead);
const tempBuf = new Uint8Array(toRead);
const n = await file.read(tempBuf, { at: offset + bytesRead });
if (n === null || n === 0) break;
buf.set(tempBuf.slice(0, n), bytesRead);
bytesRead += n;
}
// 构造 FormData 上传这一块
const formData = new FormData();
// 重要:文本字段必须在文件字段之前
formData.append('peer_id', myId);
formData.append('file_name', fileName);
formData.append('file_size', fileSize.toString());
formData.append('chunk_index', chunkCount.toString());
formData.append('chunk_total', Math.ceil(fileSize / chunkSize).toString());
formData.append('chunk', new Blob([buf], { type: 'application/octet-stream' }), 'chunk');
console.log("[JS-API] 上传分块", chunkCount + 1, "大小:", size, "字节");
formData.append('chunk', new Blob([buf.slice(0, bytesRead)], { type: 'application/octet-stream' }), 'chunk');
const resp = await fetch(uploadUrl, {
method: 'POST',
@@ -481,12 +495,10 @@ async function apiSendFile(peerId, peerAddr, file) {
if (!resp.ok) {
const errorText = await resp.text();
console.error("[JS-API] ✗ 上传分块失败,状态码:", resp.status);
console.error("[JS-API] ✗ 错误响应体:", errorText);
console.error("[JS-API] ✗ 响应头:", resp.headers);
throw new Error(`HTTP ${resp.status}: ${errorText}`);
}
offset += size;
offset += bytesRead;
chunkCount++;
// 每秒打印一次进度并更新 UI