Files
mdrs-client-rust/src/commands/config.rs
T
orrisroot a16f73543d fix: stream transfers and close gaps against the Python client
A review against the Python client, which shares this client's config
and login cache, found the transfers holding whole files in memory and
several commands answering differently from their Python counterparts.

- Stream uploads and downloads instead of buffering the whole file, so
  memory no longer scales with file size times concurrency. Uploads
  still declare a Content-Length rather than going out chunked.
- Write a download beside its destination and move it into place once
  complete, and refuse a destination that cannot be written, so a
  failed transfer leaves what was already there untouched.
- Report the server's own error detail instead of the bare status.
- List locked sub-folders in `ls --json --recursive` using the given
  password and skip only those that cannot be unlocked, instead of
  failing the whole listing.
- Name each folder's laboratory in JSON output and sort its entries,
  matching the Python client's schema and order.
- Ask the server who is logged in for `whoami`, rather than trusting
  the cached name.
- Collapse repeated separators and refuse `..` in remote paths.
- Fall back to the API when a laboratory is missing from the cache, so
  a newly added one no longer needs a fresh login.
- Verify the login cache digest on read, as the Python client does.
- Accept `-e` as the short form of `--exclude`.
- Satisfy clippy and rustfmt across the crate.
2026-09-04 16:31:14 +09:00

201 lines
6.0 KiB
Rust

use anyhow::bail;
use configparser::ini::Ini;
use std::fs;
use std::path::PathBuf;
fn config_path() -> PathBuf {
crate::settings::SETTINGS.config_dirname.join("config.ini")
}
fn sanitize_config_file(path: &PathBuf) -> Result<(), anyhow::Error> {
if !path.exists() {
return Ok(());
}
let text = fs::read_to_string(path)?;
let lines: Vec<&str> = text.lines().collect();
if let Some(first) = lines.first()
&& first.trim() == path.to_string_lossy()
{
// remove the first line and write atomically
let new_text = if lines.len() > 1 {
lines[1..].join("\n")
} else {
String::new()
};
let tmp = path.with_extension("tmp");
fs::write(&tmp, new_text.as_bytes())?;
fs::rename(&tmp, path)?;
}
Ok(())
}
fn write_ini_atomic(path: &PathBuf, ini: &Ini) -> Result<(), anyhow::Error> {
let tmp = path.with_extension("tmp");
// write to tmp path then rename for atomicity
ini.write(&tmp)?;
fs::rename(&tmp, path)?;
Ok(())
}
pub fn get_remote_url(remote: &str) -> Result<Option<String>, anyhow::Error> {
let path = config_path();
sanitize_config_file(&path)?;
let path_str = path.to_string_lossy().to_string();
let mut conf = Ini::new();
if path.exists() {
let _ = conf.load(&path_str).map_err(|e| anyhow::anyhow!("{}", e))?;
}
Ok(conf.get(remote, "url"))
}
pub fn config_create(remote: &str, url: &str) -> Result<(), anyhow::Error> {
let Some(url) = normalize_url(url) else {
bail!("Malformed URL");
};
let url = url.as_str();
let path = config_path();
sanitize_config_file(&path)?;
let path_str = path.to_string_lossy().to_string();
let mut conf = Ini::new();
if path.exists() {
let _ = conf.load(&path_str).map_err(|e| anyhow::anyhow!("{}", e))?;
}
// check if section exists
let section_exists = conf
.get_map()
.map(|m| m.contains_key(remote))
.unwrap_or(false);
if section_exists {
bail!("Remote host `{}` is already exists.", remote);
}
// set url
conf.set(remote, "url", Some(url.to_string()));
// ensure parent dir exists
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?;
}
write_ini_atomic(&path, &conf)?;
Ok(())
}
pub fn config_update(remote: &str, url: &str) -> Result<(), anyhow::Error> {
let Some(url) = normalize_url(url) else {
bail!("Malformed URL");
};
let url = url.as_str();
let path = config_path();
sanitize_config_file(&path)?;
let path_str = path.to_string_lossy().to_string();
let mut conf = Ini::new();
if path.exists() {
let _ = conf.load(&path_str).map_err(|e| anyhow::anyhow!("{}", e))?;
}
// ensure section exists
let section_exists = conf
.get_map()
.map(|m| m.contains_key(remote))
.unwrap_or(false);
if !section_exists {
bail!("Remote host `{}` is not exists.", remote);
}
conf.set(remote, "url", Some(url.to_string()));
write_ini_atomic(&path, &conf)?;
Ok(())
}
pub fn config_list() -> Result<(), anyhow::Error> {
let path = config_path();
if !path.exists() {
return Ok(());
}
sanitize_config_file(&path)?;
let path_str = path.to_string_lossy().to_string();
let mut conf = Ini::new();
let _ = conf.load(&path_str).map_err(|e| anyhow::anyhow!("{}", e))?;
let map = conf.get_map().unwrap_or_default();
for (sec, props) in map.iter() {
if sec == "default" {
continue;
}
let url = props.get("url").and_then(|v| v.clone()).unwrap_or_default();
println!("{}:\t{}", sec, url);
}
Ok(())
}
pub fn config_delete(remote: &str) -> Result<(), anyhow::Error> {
let path = config_path();
sanitize_config_file(&path)?;
let path_str = path.to_string_lossy().to_string();
let mut conf = Ini::new();
if path.exists() {
let _ = conf.load(&path_str).map_err(|e| anyhow::anyhow!("{}", e))?;
}
// fallback: reconstruct by removing the section in memory map and writing file
let mut map = conf.get_map().unwrap_or_default();
if map.remove(remote).is_none() {
bail!("Remote host `{}` is not exists.", remote);
}
// build new Ini from map
let mut new_ini = Ini::new();
for (sec, props) in map.iter() {
for (k, v) in props.iter() {
new_ini.set(sec, k, v.clone());
}
}
write_ini_atomic(&path, &new_ini)?;
Ok(())
}
/// Check a remote URL and put it in the one form every client agrees on.
///
/// A bare hostname is accepted, so a development server on `localhost` is as acceptable
/// as a deployment behind a domain name. The trailing slash goes because the URL is
/// joined with a path that brings its own.
fn normalize_url(url: &str) -> Option<String> {
let parsed = reqwest::Url::parse(url).ok()?;
if !matches!(parsed.scheme(), "http" | "https") {
return None;
}
parsed.host_str()?;
Some(url.trim_end_matches('/').to_string())
}
#[cfg(test)]
mod url_tests {
use super::normalize_url;
/// Both clients share config.ini, so they have to agree on what a remote URL is.
#[test]
fn trailing_slash_is_dropped() {
assert_eq!(
normalize_url("http://127.0.0.1:8000/api/").as_deref(),
Some("http://127.0.0.1:8000/api")
);
assert_eq!(
normalize_url("https://neurodata.riken.jp/api/").as_deref(),
Some("https://neurodata.riken.jp/api")
);
}
#[test]
fn bare_hostname_is_accepted() {
assert_eq!(
normalize_url("http://localhost:8000/api").as_deref(),
Some("http://localhost:8000/api")
);
}
#[test]
fn only_http_schemes_are_accepted() {
for url in [
"ftp://x.example.com/",
"file:///etc/passwd",
"not-a-url",
"http://",
] {
assert_eq!(normalize_url(url), None, "{url} should be rejected");
}
}
}