perf(transfer): parallelize folder traversal API calls

Use a shared API request limiter across recursive upload and
download traversal so folder detail fetches, file listings,
folder auth, and transfers can run concurrently under one
budget.

Refactor the traversal loops into task-driven pipelines while
preserving skip-if-exists, excludes, cleanup, and current
output behavior.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
2026-05-07 15:49:02 +09:00
co-authored by Copilot
parent 4e73766732
commit 3f2ca938bd
7 changed files with 771 additions and 153 deletions
+261 -75
View File
@@ -1,13 +1,14 @@
use crate::cache::{create_authenticated_conn, load_cache_with_token_refresh};
use crate::commands::shared::{
find_file_by_name, find_folder, find_lab_in_cache, nfc, parse_remote_path,
find_file_by_name, find_folder_limited, find_lab_in_cache, nfc, parse_remote_path,
};
use crate::connection::{ApiRequestLimiter, MDRSConnection};
use crate::models::folder::FolderSimple;
use anyhow::{anyhow, bail};
use futures::stream::{FuturesUnordered, StreamExt};
use std::path::PathBuf;
use std::sync::Arc;
use tokio::fs;
use tokio::task::JoinSet;
pub async fn upload(
local_path: &str,
@@ -18,8 +19,9 @@ pub async fn upload(
let (remote, labname, r_path) = parse_remote_path(remote_path)?;
let cache = load_cache_with_token_refresh(&remote).await?;
let conn = Arc::new(create_authenticated_conn(&remote, &cache)?);
let limiter = ApiRequestLimiter::new(crate::settings::SETTINGS.concurrent);
let lab = find_lab_in_cache(&cache, &labname)?;
let dest_folder = find_folder(&conn, lab.id, &r_path, None).await?;
let dest_folder = find_folder_limited(&conn, &limiter, lab.id, &r_path, None).await?;
// Normalize local_path: resolve to an absolute canonical path so that
// trailing slashes and "./" prefixes are handled consistently (matching
@@ -30,7 +32,9 @@ pub async fn upload(
if local.is_file() {
let filename = local.file_name().unwrap().to_string_lossy().to_string();
let remote_files = conn.list_all_files(&dest_folder.id).await?;
let remote_files = conn
.list_all_files_limited(&dest_folder.id, &limiter)
.await?;
if skip_if_exists {
if let Some(rf) = find_file_by_name(&remote_files, &filename) {
if rf.size == std::fs::metadata(local)?.len() {
@@ -39,7 +43,7 @@ pub async fn upload(
}
}
}
conn.upload_file(&dest_folder.id, &local.to_string_lossy())
conn.upload_file_limited(&dest_folder.id, &local.to_string_lossy(), &limiter)
.await?;
println!("{}{}", dest_folder.path, filename);
} else if local.is_dir() {
@@ -52,75 +56,43 @@ pub async fn upload(
let local_basename = local.file_name().unwrap().to_string_lossy().to_string();
let top_remote_id = find_or_create_folder(
&conn,
&limiter,
&dest_folder.id,
&dest_folder.sub_folders,
&local_basename,
)
.await?;
let top_folder = conn.retrieve_folder(&top_remote_id).await?;
println!("{}", top_folder.path.trim_end_matches('/'));
println!(
"{}",
format!("{}{}", dest_folder.path, local_basename).trim_end_matches('/')
);
// Iterative depth-first walk: each entry is (local_dir, remote_folder_id)
let mut stack: Vec<(PathBuf, String)> = vec![(local.to_path_buf(), top_remote_id)];
let mut folder_tasks: JoinSet<Result<UploadFolderTaskResult, anyhow::Error>> =
JoinSet::new();
let mut upload_tasks: JoinSet<Result<(), anyhow::Error>> = JoinSet::new();
let mut errors = Vec::new();
while let Some((local_dir, remote_id)) = stack.pop() {
let folder_detail = conn.retrieve_folder(&remote_id).await?;
let remote_files = conn.list_all_files(&remote_id).await?;
spawn_upload_folder_task(
&mut folder_tasks,
conn.clone(),
limiter.clone(),
local.to_path_buf(),
top_remote_id,
skip_if_exists,
);
let mut entries = fs::read_dir(&local_dir).await?;
let mut subdirs: Vec<PathBuf> = Vec::new();
let mut files: Vec<PathBuf> = Vec::new();
while let Some(entry) = entries.next_entry().await? {
let p = entry.path();
if p.is_dir() {
subdirs.push(p);
} else {
files.push(p);
}
}
drive_upload_tasks(
&mut folder_tasks,
&mut upload_tasks,
&mut errors,
conn.clone(),
limiter,
skip_if_exists,
)
.await;
// Ensure each local sub-directory exists on the remote side
for subdir in subdirs {
let dirname = subdir.file_name().unwrap().to_string_lossy().to_string();
let sub_remote_id =
find_or_create_folder(&conn, &remote_id, &folder_detail.sub_folders, &dirname)
.await?;
let sub_folder = conn.retrieve_folder(&sub_remote_id).await?;
println!("{}", sub_folder.path.trim_end_matches('/'));
stack.push((subdir, sub_remote_id));
}
// Upload files in this directory (up to 10 concurrent)
let mut futs: FuturesUnordered<tokio::task::JoinHandle<()>> = FuturesUnordered::new();
for file_path in files {
let filename = file_path.file_name().unwrap().to_string_lossy().to_string();
let file_path_str = file_path.to_string_lossy().to_string();
if skip_if_exists {
if let Some(rf) = find_file_by_name(&remote_files, &filename) {
if let Ok(meta) = std::fs::metadata(&file_path) {
if rf.size == meta.len() {
let remote_path_prefix = folder_detail.path.clone();
println!("{}{}", remote_path_prefix, filename);
continue;
}
}
}
}
let conn = conn.clone();
let folder_id = remote_id.clone();
let remote_path_prefix = folder_detail.path.clone();
let fname = filename.clone();
futs.push(tokio::spawn(async move {
match conn.upload_file(&folder_id, &file_path_str).await {
Ok(_) => println!("{}{}", remote_path_prefix, fname),
Err(e) => eprintln!("Error: {}", e),
}
}));
if futs.len() >= crate::settings::SETTINGS.concurrent {
let _ = futs.next().await;
}
}
while futs.next().await.is_some() {}
if !errors.is_empty() {
bail!(errors.join("\n"));
}
} else {
bail!("File or directory `{}` not found.", local_path);
@@ -131,7 +103,8 @@ pub async fn upload(
/// Find an existing sub-folder by name or create it, returning its ID.
async fn find_or_create_folder(
conn: &crate::connection::MDRSConnection,
conn: &MDRSConnection,
limiter: &ApiRequestLimiter,
parent_id: &str,
existing: &[FolderSimple],
name: &str,
@@ -142,13 +115,226 @@ async fn find_or_create_folder(
{
return Ok(sf.id.clone());
}
let resp = conn.create_folder(parent_id, &nfc(name)).await?;
if !resp.status().is_success() {
bail!("Failed to create remote folder: {}", name);
}
let json: serde_json::Value = resp.json().await?;
json["id"]
.as_str()
.ok_or_else(|| anyhow!("No id in create_folder response for {}", name))
.map(|s| s.to_string())
conn.create_folder_id_limited(parent_id, &nfc(name), limiter)
.await
}
struct UploadFolderTaskResult {
child_folders: Vec<(PathBuf, String)>,
upload_jobs: Vec<UploadJob>,
}
struct UploadJob {
folder_id: String,
file_path: String,
remote_path: String,
}
fn spawn_upload_folder_task(
folder_tasks: &mut JoinSet<Result<UploadFolderTaskResult, anyhow::Error>>,
conn: Arc<MDRSConnection>,
limiter: ApiRequestLimiter,
local_dir: PathBuf,
remote_id: String,
skip_if_exists: bool,
) {
folder_tasks.spawn(async move {
process_upload_folder(conn, limiter, local_dir, remote_id, skip_if_exists).await
});
}
fn spawn_upload_task(
upload_tasks: &mut JoinSet<Result<(), anyhow::Error>>,
conn: Arc<MDRSConnection>,
limiter: ApiRequestLimiter,
job: UploadJob,
) {
upload_tasks.spawn(async move {
conn.upload_file_limited(&job.folder_id, &job.file_path, &limiter)
.await?;
println!("{}", job.remote_path);
Ok(())
});
}
async fn process_upload_folder(
conn: Arc<MDRSConnection>,
limiter: ApiRequestLimiter,
local_dir: PathBuf,
remote_id: String,
skip_if_exists: bool,
) -> Result<UploadFolderTaskResult, anyhow::Error> {
let (folder_detail, remote_files) = tokio::try_join!(
conn.retrieve_folder_limited(&remote_id, &limiter),
conn.list_all_files_limited(&remote_id, &limiter),
)?;
let mut entries = fs::read_dir(&local_dir).await?;
let mut subdirs: Vec<PathBuf> = Vec::new();
let mut files: Vec<PathBuf> = Vec::new();
while let Some(entry) = entries.next_entry().await? {
let path = entry.path();
if path.is_dir() {
subdirs.push(path);
} else {
files.push(path);
}
}
let mut subdir_tasks: JoinSet<Result<(PathBuf, String, String), anyhow::Error>> =
JoinSet::new();
let existing_subfolders = Arc::new(folder_detail.sub_folders.clone());
let folder_path_prefix = folder_detail.path.clone();
for subdir in subdirs {
let conn = conn.clone();
let limiter = limiter.clone();
let remote_id = remote_id.clone();
let existing_subfolders = existing_subfolders.clone();
let folder_path_prefix = folder_path_prefix.clone();
subdir_tasks.spawn(async move {
let dirname = subdir.file_name().unwrap().to_string_lossy().to_string();
let sub_remote_id = find_or_create_folder(
&conn,
&limiter,
&remote_id,
existing_subfolders.as_slice(),
&dirname,
)
.await?;
Ok((
subdir,
sub_remote_id,
format!("{}{}", folder_path_prefix, dirname),
))
});
}
let mut child_folders = Vec::new();
while let Some(result) = subdir_tasks.join_next().await {
let (subdir, sub_remote_id, remote_path) = flatten_join_result(result)?;
println!("{}", remote_path.trim_end_matches('/'));
child_folders.push((subdir, sub_remote_id));
}
let mut upload_jobs = Vec::new();
for file_path in files {
let filename = file_path.file_name().unwrap().to_string_lossy().to_string();
if skip_if_exists {
if let Some(rf) = find_file_by_name(&remote_files, &filename) {
if let Ok(meta) = std::fs::metadata(&file_path) {
if rf.size == meta.len() {
println!("{}{}", folder_detail.path, filename);
continue;
}
}
}
}
upload_jobs.push(UploadJob {
folder_id: remote_id.clone(),
file_path: file_path.to_string_lossy().to_string(),
remote_path: format!("{}{}", folder_detail.path, filename),
});
}
Ok(UploadFolderTaskResult {
child_folders,
upload_jobs,
})
}
async fn drive_upload_tasks(
folder_tasks: &mut JoinSet<Result<UploadFolderTaskResult, anyhow::Error>>,
upload_tasks: &mut JoinSet<Result<(), anyhow::Error>>,
errors: &mut Vec<String>,
conn: Arc<MDRSConnection>,
limiter: ApiRequestLimiter,
skip_if_exists: bool,
) {
loop {
match (folder_tasks.is_empty(), upload_tasks.is_empty()) {
(true, true) => break,
(false, true) => {
if let Some(result) = folder_tasks.join_next().await {
handle_upload_folder_result(
result,
folder_tasks,
upload_tasks,
errors,
conn.clone(),
limiter.clone(),
skip_if_exists,
);
}
}
(true, false) => {
if let Some(result) = upload_tasks.join_next().await {
if let Err(err) = flatten_join_result(result) {
errors.push(err.to_string());
}
}
}
(false, false) => {
tokio::select! {
result = folder_tasks.join_next() => {
if let Some(result) = result {
handle_upload_folder_result(
result,
folder_tasks,
upload_tasks,
errors,
conn.clone(),
limiter.clone(),
skip_if_exists,
);
}
}
result = upload_tasks.join_next() => {
if let Some(result) = result {
if let Err(err) = flatten_join_result(result) {
errors.push(err.to_string());
}
}
}
}
}
}
}
}
fn handle_upload_folder_result(
result: Result<Result<UploadFolderTaskResult, anyhow::Error>, tokio::task::JoinError>,
folder_tasks: &mut JoinSet<Result<UploadFolderTaskResult, anyhow::Error>>,
upload_tasks: &mut JoinSet<Result<(), anyhow::Error>>,
errors: &mut Vec<String>,
conn: Arc<MDRSConnection>,
limiter: ApiRequestLimiter,
skip_if_exists: bool,
) {
match flatten_join_result(result) {
Ok(task_result) => {
for (local_dir, remote_id) in task_result.child_folders {
spawn_upload_folder_task(
folder_tasks,
conn.clone(),
limiter.clone(),
local_dir,
remote_id,
skip_if_exists,
);
}
for job in task_result.upload_jobs {
spawn_upload_task(upload_tasks, conn.clone(), limiter.clone(), job);
}
}
Err(err) => errors.push(err.to_string()),
}
}
fn flatten_join_result<T>(
result: Result<Result<T, anyhow::Error>, tokio::task::JoinError>,
) -> Result<T, anyhow::Error> {
match result {
Ok(inner) => inner,
Err(err) => Err(anyhow!("Task join failed: {}", err)),
}
}