feat(modpacks): refresh managed instances safely

This commit is contained in:
objz committed 2026-08-05 00:16:24 +02:00
1 parent bbf0317775
commit e09e5a0168
15 files changed
+840 -29

No files matched your search

+35
View File
@@ -193,6 +193,41 @@ async fn download_files(
Ok(())
}
pub(super) async fn owned_files(path: &Path) -> Result<Vec<std::path::PathBuf>, String> {
let manifest = parse(path)?;
let api_key = crate::net::curseforge::api_key()
.ok_or_else(|| "CurseForge API key is not configured".to_owned())?;
let ids = manifest
.files
.iter()
.filter(|file| file.required)
.map(|file| file.file_id)
.collect::<Vec<_>>();
let versions =
crate::net::curseforge::fetch_file_versions(&crate::net::HttpClient::new(), api_key, &ids)
.await
.map_err(|error| error.to_string())?;
if versions.len() != ids.len() {
return Err(format!(
"CurseForge returned {} of {} required pack files",
versions.len(),
ids.len()
));
}
versions
.into_iter()
.map(|version| {
version
.files
.iter()
.find(|file| file.primary)
.or_else(|| version.files.first())
.map(|file| std::path::PathBuf::from("mods").join(&file.filename))
.ok_or_else(|| format!("CurseForge file '{}' has no artifact", version.id))
})
.collect()
}
fn count_overrides(path: &Path, root: &str) -> Result<usize, String> {
let root = root.trim_matches('/');
if root.is_empty() {
+75
View File
@@ -4,6 +4,7 @@
pub mod curseforge;
pub mod mmc;
pub mod mrpack;
pub mod refresh;
use std::path::{Path, PathBuf};
@@ -184,10 +185,84 @@ pub async fn execute_import(
if summary.source.is_some() {
config.modpack_source = summary.source.clone();
manager.save(&config)?;
let state = match owned_files(summary).await {
Ok(files) => refresh::PackState {
source: summary.source.clone().expect("source checked above"),
files,
},
Err(error) => {
cleanup_failed_import(manager, &config.name);
return Err(error.into());
}
};
if let Err(error) = state.save(&crate::storage::InstancePaths::new(
manager.instances_dir.join(&config.name),
)) {
cleanup_failed_import(manager, &config.name);
return Err(error.into());
}
}
Ok(config)
}
pub async fn provider_versions(
source: &crate::instance::ProviderProject,
) -> Result<Vec<crate::net::modrinth::VersionInfo>, crate::net::NetError> {
let client = crate::net::HttpClient::new();
match source.provider.as_str() {
"curseforge" => {
let api_key = crate::net::curseforge::api_key().ok_or_else(|| {
crate::net::NetError::Parse("CurseForge API key is not configured".to_owned())
})?;
crate::net::curseforge::fetch_versions(&client, api_key, &source.project_id, "", None)
.await
}
"modrinth" => crate::net::modrinth::fetch_versions(&client, &source.project_id).await,
provider => Err(crate::net::NetError::Parse(format!(
"Unsupported modpack provider '{provider}'"
))),
}
}
pub async fn download_provider_summary(
source: &crate::instance::ProviderProject,
version: &crate::net::modrinth::VersionInfo,
temporary_dir: &Path,
) -> Result<ImportSummary, crate::net::NetError> {
tokio::fs::create_dir_all(temporary_dir).await?;
let registry = crate::instance::content::provider::ProviderRegistry::configured(
crate::net::HttpClient::new(),
);
let provider = registry.get(&source.provider).ok_or_else(|| {
crate::net::NetError::Parse(format!(
"{} content provider is unavailable",
source.provider
))
})?;
let archive = match provider
.download_version(version, temporary_dir, None)
.await?
{
crate::net::modrinth::DownloadOutcome::Downloaded(path)
| crate::net::modrinth::DownloadOutcome::SkippedExisting(path) => path,
};
let mut summary = build_summary(&archive).map_err(crate::net::NetError::Parse)?;
summary.source = Some(crate::instance::ProviderProject {
provider: source.provider.clone(),
project_id: source.project_id.clone(),
version_id: version.id.clone(),
});
Ok(summary)
}
async fn owned_files(summary: &ImportSummary) -> Result<Vec<PathBuf>, String> {
match summary.format {
PackFormat::Mrpack => mrpack::owned_files(&summary.archive_path),
PackFormat::CurseForge => curseforge::owned_files(&summary.archive_path).await,
PackFormat::Mmc => Err("Managed updates are unavailable for MultiMC packs".to_owned()),
}
}
fn cleanup_failed_import(manager: &InstanceManager, name: &str) {
crate::feedback::progress::clear();
let instance_dir = manager.instances_dir.join(name);
+8
View File
@@ -331,6 +331,14 @@ fn safe_mrpack_path(path: &str) -> Result<PathBuf, crate::net::NetError> {
Ok(path.to_owned())
}
pub(super) fn owned_files(path: &Path) -> Result<Vec<PathBuf>, String> {
parse_mrpack(path)?
.files
.into_iter()
.map(|file| safe_mrpack_path(&file.path).map_err(|error| error.to_string()))
.collect()
}
fn verify_mrpack_file(
path: &Path,
expected_size: u64,
+345
View File
@@ -0,0 +1,345 @@
use std::collections::HashSet;
use std::path::{Path, PathBuf};
use serde::{Deserialize, Serialize};
use crate::instance::{InstanceConfig, InstanceManager, ProviderProject};
use crate::net::modrinth::VersionInfo;
use crate::storage::InstancePaths;
use super::ImportSummary;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PackState {
pub source: ProviderProject,
pub files: Vec<PathBuf>,
}
impl PackState {
pub fn load(paths: &InstancePaths) -> Option<Self> {
std::fs::read(paths.modpack_state())
.ok()
.and_then(|bytes| serde_json::from_slice(&bytes).ok())
}
pub fn save(&self, paths: &InstancePaths) -> Result<(), String> {
let bytes = serde_json::to_vec_pretty(self).map_err(|error| error.to_string())?;
crate::storage::write_atomic(&paths.modpack_state(), &bytes)
.map_err(|error| error.to_string())
}
}
pub struct RefreshPlan {
pub instance: InstanceConfig,
pub summary: ImportSummary,
pub current_version: String,
pub target_version: String,
pub conflicts: Vec<PathBuf>,
stage_root: PathBuf,
staged_instance: PathBuf,
old_owned: HashSet<PathBuf>,
new_owned: HashSet<PathBuf>,
}
impl Drop for RefreshPlan {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.stage_root);
}
}
pub async fn prepare(
manager: &InstanceManager,
instance: &InstanceConfig,
target: VersionInfo,
) -> Result<RefreshPlan, String> {
if crate::instance::runtime::get(&instance.name)
.is_some_and(|state| !matches!(state, crate::instance::runtime::RunState::Crashed(_)))
{
return Err("Stop the instance before updating its modpack".to_owned());
}
let source = instance
.modpack_source
.clone()
.ok_or_else(|| "This instance is not linked to a modpack provider".to_owned())?;
let live = manager.instances_dir.join(&instance.name);
let needed = directory_size(&live)
.saturating_add(target.files.iter().map(|file| file.size).sum::<u64>())
.saturating_add(64 * 1024 * 1024);
let available = fs2::available_space(&manager.instances_dir).map_err(|e| e.to_string())?;
if available < needed {
return Err(format!(
"Not enough free space to stage this update (need about {}, available {})",
format_bytes(needed),
format_bytes(available)
));
}
let nonce = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_err(|error| error.to_string())?
.as_nanos();
let stage_root = manager.instances_dir.join(format!(".rmcl-refresh-{nonce}"));
let archives = stage_root.join("archives");
let result = async {
let summary = super::download_provider_summary(&source, &target, &archives.join("target"))
.await
.map_err(|error| error.to_string())?;
let old_owned = match PackState::load(&InstancePaths::new(&live))
.filter(|state| state.source == source)
{
Some(state) => state.files.into_iter().collect(),
None => reconstruct_owned_files(&source, &archives.join("current")).await?,
};
let staging_manager = InstanceManager::new(&stage_root, &manager.meta_dir);
let staged_config = super::execute_import(&summary, &staging_manager)
.await
.map_err(|error| error.to_string())?;
let imported = stage_root.join(&staged_config.name);
let new_owned = PackState::load(&InstancePaths::new(&imported))
.ok_or_else(|| "The staged pack did not record its owned files".to_owned())?
.files
.into_iter()
.collect::<HashSet<_>>();
let staged_instance = stage_root.join(&instance.name);
if imported != staged_instance {
std::fs::rename(&imported, &staged_instance).map_err(|error| error.to_string())?;
}
let mut config = instance.clone();
config.game_version = summary.game_version.clone();
config.loader = summary.loader;
config.loader_version = summary.loader_version.clone();
config.modpack_source = summary.source.clone();
let staged_manager = InstanceManager::new(&stage_root, &manager.meta_dir);
staged_manager
.save(&config)
.map_err(|error| error.to_string())?;
let conflicts = user_file_collisions(
&InstancePaths::new(&live).minecraft(),
&old_owned,
&new_owned,
)?;
Ok::<_, String>(RefreshPlan {
instance: config,
current_version: source.version_id.clone(),
target_version: target.version_number.clone(),
summary,
conflicts,
stage_root: stage_root.clone(),
staged_instance,
old_owned,
new_owned,
})
}
.await;
if result.is_err() {
let _ = std::fs::remove_dir_all(&stage_root);
}
result
}
pub fn apply(
plan: RefreshPlan,
replace_conflicts: &HashSet<PathBuf>,
) -> Result<InstanceConfig, String> {
let live = plan
.stage_root
.parent()
.ok_or_else(|| "Invalid refresh staging path".to_owned())?
.join(&plan.instance.name);
let old_minecraft = InstancePaths::new(&live).minecraft();
let staged_minecraft = InstancePaths::new(&plan.staged_instance).minecraft();
preserve_user_files(
&old_minecraft,
&staged_minecraft,
&old_minecraft,
&plan.old_owned,
&plan.new_owned,
replace_conflicts,
)?;
let backup = live.with_file_name(format!(".{}.rmcl-backup", plan.instance.name));
if backup.exists() {
return Err(format!(
"A previous update backup still exists at '{}'",
backup.display()
));
}
std::fs::rename(&live, &backup).map_err(|error| error.to_string())?;
if let Err(error) = std::fs::rename(&plan.staged_instance, &live) {
let _ = std::fs::rename(&backup, &live);
return Err(format!("Could not activate the staged update: {error}"));
}
if let Err(error) = std::fs::remove_dir_all(&backup) {
tracing::warn!("Could not remove successful modpack update backup: {error}");
}
Ok(plan.instance.clone())
}
async fn reconstruct_owned_files(
source: &ProviderProject,
temporary_dir: &Path,
) -> Result<HashSet<PathBuf>, String> {
let registry = crate::instance::content::provider::ProviderRegistry::configured(
crate::net::HttpClient::new(),
);
let provider = registry
.get(&source.provider)
.ok_or_else(|| format!("{} content provider is unavailable", source.provider))?;
let version = provider
.version(&source.version_id)
.await
.map_err(|error| error.to_string())?;
let summary = super::download_provider_summary(source, &version, temporary_dir)
.await
.map_err(|error| error.to_string())?;
Ok(super::owned_files(&summary).await?.into_iter().collect())
}
fn user_file_collisions(
minecraft: &Path,
old_owned: &HashSet<PathBuf>,
new_owned: &HashSet<PathBuf>,
) -> Result<Vec<PathBuf>, String> {
let mut collisions = Vec::new();
collect_files(minecraft, minecraft, &mut |relative, _| {
if !old_owned.contains(relative) && new_owned.contains(relative) {
collisions.push(relative.to_owned());
}
Ok(())
})?;
collisions.sort();
Ok(collisions)
}
fn preserve_user_files(
source: &Path,
destination: &Path,
root: &Path,
old_owned: &HashSet<PathBuf>,
new_owned: &HashSet<PathBuf>,
replace_conflicts: &HashSet<PathBuf>,
) -> Result<(), String> {
for entry in std::fs::read_dir(source).map_err(|error| error.to_string())? {
let entry = entry.map_err(|error| error.to_string())?;
let path = entry.path();
let relative = path.strip_prefix(root).map_err(|error| error.to_string())?;
let metadata = std::fs::symlink_metadata(&path).map_err(|error| error.to_string())?;
if metadata.file_type().is_symlink() {
return Err(format!(
"Cannot safely preserve symbolic link '{}'",
path.display()
));
}
if metadata.is_dir() {
let target = destination.join(entry.file_name());
std::fs::create_dir_all(&target).map_err(|error| error.to_string())?;
preserve_user_files(
&path,
&target,
root,
old_owned,
new_owned,
replace_conflicts,
)?;
} else if !(old_owned.contains(relative)
|| new_owned.contains(relative) && replace_conflicts.contains(relative))
{
let target = destination.join(entry.file_name());
std::fs::copy(&path, target).map_err(|error| error.to_string())?;
}
}
Ok(())
}
fn collect_files(
directory: &Path,
root: &Path,
visit: &mut impl FnMut(&Path, &Path) -> Result<(), String>,
) -> Result<(), String> {
if !directory.exists() {
return Ok(());
}
for entry in std::fs::read_dir(directory).map_err(|error| error.to_string())? {
let entry = entry.map_err(|error| error.to_string())?;
let path = entry.path();
let metadata = std::fs::symlink_metadata(&path).map_err(|error| error.to_string())?;
if metadata.is_dir() {
collect_files(&path, root, visit)?;
} else if metadata.is_file() {
visit(
path.strip_prefix(root).map_err(|error| error.to_string())?,
&path,
)?;
}
}
Ok(())
}
fn directory_size(path: &Path) -> u64 {
let mut size = 0;
let _ = collect_files(path, path, &mut |_, file| {
size += file.metadata().map(|metadata| metadata.len()).unwrap_or(0);
Ok(())
});
size
}
fn format_bytes(bytes: u64) -> String {
if bytes >= 1024 * 1024 * 1024 {
format!("{:.1} GB", bytes as f64 / (1024 * 1024 * 1024) as f64)
} else {
format!("{:.1} MB", bytes as f64 / (1024 * 1024) as f64)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn preservation_replaces_pack_files_and_keeps_user_files() {
let temp = tempfile::tempdir().unwrap();
let old = temp.path().join("old");
let new = temp.path().join("new");
std::fs::create_dir_all(old.join("mods")).unwrap();
std::fs::create_dir_all(new.join("mods")).unwrap();
std::fs::write(old.join("mods/pack.jar"), "old").unwrap();
std::fs::write(old.join("mods/user.jar"), "user").unwrap();
std::fs::write(new.join("mods/pack.jar"), "new").unwrap();
std::fs::write(new.join("mods/user.jar"), "pack collision").unwrap();
let owned = HashSet::from([PathBuf::from("mods/pack.jar")]);
let target_owned = HashSet::from([
PathBuf::from("mods/pack.jar"),
PathBuf::from("mods/user.jar"),
]);
preserve_user_files(&old, &new, &old, &owned, &target_owned, &HashSet::new()).unwrap();
assert_eq!(
std::fs::read_to_string(new.join("mods/pack.jar")).unwrap(),
"new"
);
assert_eq!(
std::fs::read_to_string(new.join("mods/user.jar")).unwrap(),
"user"
);
std::fs::write(new.join("mods/user.jar"), "pack collision").unwrap();
preserve_user_files(
&old,
&new,
&old,
&owned,
&target_owned,
&HashSet::from([PathBuf::from("mods/user.jar")]),
)
.unwrap();
assert_eq!(
std::fs::read_to_string(new.join("mods/user.jar")).unwrap(),
"pack collision"
);
}
}