fix(content): make provider metadata durable
This commit is contained in:
1 parent
c59228e1fd
commit
0a930a4f86
6 files changed
+267
-98
No files matched your search
+24
-18
@@ -101,29 +101,35 @@ impl ContentProvider for ModrinthProvider {
|
|||||||
&self,
|
&self,
|
||||||
files: &[FingerprintQuery],
|
files: &[FingerprintQuery],
|
||||||
) -> Result<Vec<ResolvedFile>, crate::net::NetError> {
|
) -> Result<Vec<ResolvedFile>, crate::net::NetError> {
|
||||||
let by_hash = files
|
let mut by_hash = HashMap::<String, Vec<String>>::new();
|
||||||
.iter()
|
for file in files {
|
||||||
.filter_map(|file| {
|
if let Some(hash) = file.fingerprint.hash("sha512") {
|
||||||
file.fingerprint
|
by_hash
|
||||||
.hash("sha512")
|
.entry(hash.to_owned())
|
||||||
.map(|hash| (hash.to_owned(), file.key.clone()))
|
.or_default()
|
||||||
})
|
.push(file.key.clone());
|
||||||
.collect::<HashMap<_, _>>();
|
}
|
||||||
|
}
|
||||||
let hashes = by_hash.keys().cloned().collect::<Vec<_>>();
|
let hashes = by_hash.keys().cloned().collect::<Vec<_>>();
|
||||||
let versions =
|
let versions =
|
||||||
crate::net::modrinth::resolve_version_files(&self.client, &hashes, "sha512").await?;
|
crate::net::modrinth::resolve_version_files(&self.client, &hashes, "sha512").await?;
|
||||||
Ok(versions
|
Ok(versions
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.filter_map(|(hash, version)| {
|
.flat_map(|(hash, version)| {
|
||||||
let key = by_hash.get(&hash)?.clone();
|
let keys = by_hash.get(&hash).cloned().unwrap_or_default();
|
||||||
(!version.project_id.is_empty()).then_some(ResolvedFile {
|
if version.project_id.is_empty() {
|
||||||
key,
|
return Vec::new();
|
||||||
project: ProviderProject {
|
}
|
||||||
provider: self.id().to_owned(),
|
keys.into_iter()
|
||||||
project_id: version.project_id,
|
.map(|key| ResolvedFile {
|
||||||
version_id: version.id,
|
key,
|
||||||
},
|
project: ProviderProject {
|
||||||
})
|
provider: self.id().to_owned(),
|
||||||
|
project_id: version.project_id.clone(),
|
||||||
|
version_id: version.id.clone(),
|
||||||
|
},
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
})
|
})
|
||||||
.collect())
|
.collect())
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,12 +1,15 @@
|
|||||||
use std::collections::BTreeMap;
|
use std::collections::{BTreeMap, HashMap};
|
||||||
use std::io::Read;
|
use std::io::Read;
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
|
use std::sync::{Arc, LazyLock, Mutex};
|
||||||
use std::time::{SystemTime, UNIX_EPOCH};
|
use std::time::{SystemTime, UNIX_EPOCH};
|
||||||
|
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use sha1::Digest as _;
|
use sha1::Digest as _;
|
||||||
|
|
||||||
const MANIFEST_VERSION: u32 = 1;
|
const MANIFEST_VERSION: u32 = 1;
|
||||||
|
static MANIFEST_LOCKS: LazyLock<Mutex<HashMap<PathBuf, Arc<Mutex<()>>>>> =
|
||||||
|
LazyLock::new(|| Mutex::new(HashMap::new()));
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
#[serde(rename_all = "snake_case")]
|
#[serde(rename_all = "snake_case")]
|
||||||
@@ -112,18 +115,31 @@ impl ContentManifest {
|
|||||||
ManifestError::InvalidPath(format!("{} has no parent", path.display()))
|
ManifestError::InvalidPath(format!("{} has no parent", path.display()))
|
||||||
})?;
|
})?;
|
||||||
std::fs::create_dir_all(parent)?;
|
std::fs::create_dir_all(parent)?;
|
||||||
let temporary = parent.join(format!(
|
|
||||||
".{}.tmp",
|
|
||||||
path.file_name()
|
|
||||||
.and_then(|name| name.to_str())
|
|
||||||
.unwrap_or("manifest")
|
|
||||||
));
|
|
||||||
let bytes = serde_json::to_vec_pretty(self)?;
|
let bytes = serde_json::to_vec_pretty(self)?;
|
||||||
std::fs::write(&temporary, bytes)?;
|
crate::storage::write_atomic(path, &bytes)?;
|
||||||
std::fs::rename(temporary, path)?;
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn update<T>(
|
||||||
|
path: &Path,
|
||||||
|
update: impl FnOnce(&mut Self) -> Result<T, ManifestError>,
|
||||||
|
) -> Result<T, ManifestError> {
|
||||||
|
let lock = {
|
||||||
|
let mut locks = MANIFEST_LOCKS
|
||||||
|
.lock()
|
||||||
|
.map_err(|_| ManifestError::LockPoisoned)?;
|
||||||
|
locks
|
||||||
|
.entry(path.to_owned())
|
||||||
|
.or_insert_with(|| Arc::new(Mutex::new(())))
|
||||||
|
.clone()
|
||||||
|
};
|
||||||
|
let _guard = lock.lock().map_err(|_| ManifestError::LockPoisoned)?;
|
||||||
|
let mut manifest = Self::load(path)?;
|
||||||
|
let result = update(&mut manifest)?;
|
||||||
|
manifest.save(path)?;
|
||||||
|
Ok(result)
|
||||||
|
}
|
||||||
|
|
||||||
pub fn record(&self, relative_path: &Path) -> Option<&ContentFileRecord> {
|
pub fn record(&self, relative_path: &Path) -> Option<&ContentFileRecord> {
|
||||||
self.files
|
self.files
|
||||||
.iter()
|
.iter()
|
||||||
@@ -175,6 +191,8 @@ pub enum ManifestError {
|
|||||||
UnsupportedVersion(u32),
|
UnsupportedVersion(u32),
|
||||||
#[error("Invalid manifest path: {0}")]
|
#[error("Invalid manifest path: {0}")]
|
||||||
InvalidPath(String),
|
InvalidPath(String),
|
||||||
|
#[error("Content manifest lock was poisoned")]
|
||||||
|
LockPoisoned,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn fingerprint(path: &Path) -> Result<FileFingerprint, std::io::Error> {
|
pub fn fingerprint(path: &Path) -> Result<FileFingerprint, std::io::Error> {
|
||||||
|
|||||||
@@ -157,10 +157,11 @@ async fn reconcile(job: ReconcileJob, task: &ProgressTask) -> ReconcileResult {
|
|||||||
let retry_hours = crate::config::SETTINGS.content.unmatched_retry_hours;
|
let retry_hours = crate::config::SETTINGS.content.unmatched_retry_hours;
|
||||||
let max_fingerprint_size_mib = crate::config::SETTINGS.content.max_fingerprint_size_mib;
|
let max_fingerprint_size_mib = crate::config::SETTINGS.content.max_fingerprint_size_mib;
|
||||||
let inventory_progress = task.handle();
|
let inventory_progress = task.handle();
|
||||||
|
let inventory_minecraft_dir = minecraft_dir.clone();
|
||||||
let inventory = tokio::task::spawn_blocking(move || {
|
let inventory = tokio::task::spawn_blocking(move || {
|
||||||
reconcile_inventory(
|
reconcile_inventory(
|
||||||
&manifest_path,
|
&manifest_path,
|
||||||
&minecraft_dir,
|
&inventory_minecraft_dir,
|
||||||
retry_hours,
|
retry_hours,
|
||||||
max_fingerprint_size_mib,
|
max_fingerprint_size_mib,
|
||||||
&inventory_progress,
|
&inventory_progress,
|
||||||
@@ -195,27 +196,38 @@ async fn reconcile(job: ReconcileJob, task: &ProgressTask) -> ReconcileResult {
|
|||||||
&task,
|
&task,
|
||||||
)
|
)
|
||||||
.await;
|
.await;
|
||||||
match inventory.manifest.save(&manifest_path) {
|
match save_reconciled_manifest(
|
||||||
Ok(()) => ReconcileResult {
|
&manifest_path,
|
||||||
|
&minecraft_dir,
|
||||||
|
inventory.manifest,
|
||||||
|
) {
|
||||||
|
Ok(manifest) => ReconcileResult {
|
||||||
instance_name,
|
instance_name,
|
||||||
manifest: inventory.manifest,
|
manifest,
|
||||||
icons: icon_result.unwrap_or_default(),
|
icons: icon_result.unwrap_or_default(),
|
||||||
error: None,
|
error: None,
|
||||||
},
|
},
|
||||||
Err(error) => ReconcileResult {
|
Err(error) => ReconcileResult {
|
||||||
instance_name,
|
instance_name,
|
||||||
manifest: inventory.manifest,
|
manifest: ContentManifest::default(),
|
||||||
icons: HashMap::new(),
|
icons: HashMap::new(),
|
||||||
error: Some(error.to_string()),
|
error: Some(error.to_string()),
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Err(error) => ReconcileResult {
|
Err(error) => {
|
||||||
instance_name,
|
let saved = save_reconciled_manifest(
|
||||||
manifest: inventory.manifest,
|
&manifest_path,
|
||||||
icons: HashMap::new(),
|
&minecraft_dir,
|
||||||
error: Some(error.to_string()),
|
inventory.manifest,
|
||||||
},
|
);
|
||||||
|
ReconcileResult {
|
||||||
|
instance_name,
|
||||||
|
manifest: saved.unwrap_or_default(),
|
||||||
|
icons: HashMap::new(),
|
||||||
|
error: Some(error.to_string()),
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Ok(Err(error)) => ReconcileResult {
|
Ok(Err(error)) => ReconcileResult {
|
||||||
@@ -234,6 +246,36 @@ async fn reconcile(job: ReconcileJob, task: &ProgressTask) -> ReconcileResult {
|
|||||||
result
|
result
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn save_reconciled_manifest(
|
||||||
|
manifest_path: &Path,
|
||||||
|
minecraft_dir: &Path,
|
||||||
|
reconciled: ContentManifest,
|
||||||
|
) -> Result<ContentManifest, crate::instance::content::manifest::ManifestError> {
|
||||||
|
let reconciled_paths = reconciled
|
||||||
|
.files
|
||||||
|
.iter()
|
||||||
|
.map(|record| record.relative_path.clone())
|
||||||
|
.collect::<HashSet<_>>();
|
||||||
|
ContentManifest::update(manifest_path, |current| {
|
||||||
|
current.files.retain(|record| {
|
||||||
|
reconciled_paths.contains(&record.relative_path)
|
||||||
|
|| minecraft_dir.join(&record.relative_path).exists()
|
||||||
|
});
|
||||||
|
for record in reconciled.files {
|
||||||
|
let keep_resolved = current
|
||||||
|
.record(&record.relative_path)
|
||||||
|
.is_some_and(|existing| {
|
||||||
|
existing.fingerprint == record.fingerprint
|
||||||
|
&& matches!(existing.resolution, Resolution::Resolved { .. })
|
||||||
|
});
|
||||||
|
if !keep_resolved {
|
||||||
|
current.upsert(record);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(current.clone())
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
struct Inventory {
|
struct Inventory {
|
||||||
manifest: ContentManifest,
|
manifest: ContentManifest,
|
||||||
queries: Vec<FingerprintQuery>,
|
queries: Vec<FingerprintQuery>,
|
||||||
@@ -369,6 +411,7 @@ async fn resolve_queries(
|
|||||||
}
|
}
|
||||||
let mut matches: HashMap<String, Vec<ProviderProject>> = HashMap::new();
|
let mut matches: HashMap<String, Vec<ProviderProject>> = HashMap::new();
|
||||||
let mut checked = Vec::new();
|
let mut checked = Vec::new();
|
||||||
|
let mut last_error = None;
|
||||||
for provider in registry.providers() {
|
for provider in registry.providers() {
|
||||||
let provider_id = provider.id();
|
let provider_id = provider.id();
|
||||||
match tokio::time::timeout(
|
match tokio::time::timeout(
|
||||||
@@ -390,14 +433,21 @@ async fn resolve_queries(
|
|||||||
tracing::warn!(
|
tracing::warn!(
|
||||||
"Skipping {provider_id} content matching after provider error: {error}"
|
"Skipping {provider_id} content matching after provider error: {error}"
|
||||||
);
|
);
|
||||||
|
last_error = Some(error.to_string());
|
||||||
}
|
}
|
||||||
Err(_) => {
|
Err(_) => {
|
||||||
tracing::warn!(
|
tracing::warn!(
|
||||||
"Skipping {provider_id} content matching after the 10 second timeout"
|
"Skipping {provider_id} content matching after the 10 second timeout"
|
||||||
);
|
);
|
||||||
|
last_error = Some(format!("{provider_id} content matching timed out"));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if checked.is_empty() {
|
||||||
|
return Err(crate::net::NetError::TaskFailed(last_error.unwrap_or_else(
|
||||||
|
|| "No content providers are available".to_owned(),
|
||||||
|
)));
|
||||||
|
}
|
||||||
let query_keys = queries
|
let query_keys = queries
|
||||||
.iter()
|
.iter()
|
||||||
.map(|query| query.key.as_str())
|
.map(|query| query.key.as_str())
|
||||||
@@ -483,13 +533,30 @@ async fn load_project_icons(
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
task.set_sub_action(&project_id);
|
task.set_sub_action(&project_id);
|
||||||
match tokio::time::timeout(
|
let cached_project = metadata
|
||||||
remaining.min(std::time::Duration::from_secs(3)),
|
.provider_projects(&provider_id)
|
||||||
provider.project(&project_id),
|
.join(format!("{project_id}.json"));
|
||||||
)
|
let project_result = match tokio::fs::read(&cached_project).await {
|
||||||
.await
|
Ok(bytes) => serde_json::from_slice(&bytes)
|
||||||
{
|
.map_err(|error| crate::net::NetError::Parse(error.to_string())),
|
||||||
Ok(Ok(project)) => {
|
Err(_) => match tokio::time::timeout(
|
||||||
|
remaining.min(std::time::Duration::from_secs(3)),
|
||||||
|
provider.project(&project_id),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Ok(result) => result,
|
||||||
|
Err(_) => {
|
||||||
|
tracing::debug!(
|
||||||
|
"Timed out loading {provider_id} project {project_id}; using fallback"
|
||||||
|
);
|
||||||
|
task.set_progress(index as u64 + 1, project_count);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
};
|
||||||
|
match project_result {
|
||||||
|
Ok(project) => {
|
||||||
if let Err(error) = cache_project(metadata, &provider_id, &project) {
|
if let Err(error) = cache_project(metadata, &provider_id, &project) {
|
||||||
tracing::warn!("Failed to cache {provider_id} project {project_id}: {error}");
|
tracing::warn!("Failed to cache {provider_id} project {project_id}: {error}");
|
||||||
}
|
}
|
||||||
@@ -527,12 +594,9 @@ async fn load_project_icons(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Ok(Err(error)) => {
|
Err(error) => {
|
||||||
tracing::warn!("Failed to load {provider_id} project {project_id}: {error}")
|
tracing::warn!("Failed to load {provider_id} project {project_id}: {error}")
|
||||||
}
|
}
|
||||||
Err(_) => tracing::debug!(
|
|
||||||
"Timed out loading {provider_id} project {project_id}; using fallback"
|
|
||||||
),
|
|
||||||
}
|
}
|
||||||
task.set_progress(index as u64 + 1, project_count);
|
task.set_progress(index as u64 + 1, project_count);
|
||||||
}
|
}
|
||||||
@@ -550,9 +614,9 @@ fn cache_project(
|
|||||||
if let Some(parent) = path.parent() {
|
if let Some(parent) = path.parent() {
|
||||||
std::fs::create_dir_all(parent)?;
|
std::fs::create_dir_all(parent)?;
|
||||||
}
|
}
|
||||||
std::fs::write(
|
crate::storage::write_atomic(
|
||||||
path,
|
&path,
|
||||||
serde_json::to_vec_pretty(project)
|
&serde_json::to_vec_pretty(project)
|
||||||
.map_err(|error| crate::net::NetError::Parse(error.to_string()))?,
|
.map_err(|error| crate::net::NetError::Parse(error.to_string()))?,
|
||||||
)?;
|
)?;
|
||||||
Ok(())
|
Ok(())
|
||||||
|
|||||||
+18
-13
@@ -205,23 +205,28 @@ pub async fn download_file(
|
|||||||
) -> Result<(), NetError> {
|
) -> Result<(), NetError> {
|
||||||
tracing::debug!("Downloading {} to {}", url, dest.display());
|
tracing::debug!("Downloading {} to {}", url, dest.display());
|
||||||
|
|
||||||
for attempt in 0..=MAX_RETRIES {
|
let result = 'download: {
|
||||||
match download_file_once(client, url, dest, &progress_cb).await {
|
for attempt in 0..=MAX_RETRIES {
|
||||||
Ok(()) => {
|
match download_file_once(client, url, dest, &progress_cb).await {
|
||||||
tracing::debug!("Downloaded {} to {}", url, dest.display());
|
Ok(()) => {
|
||||||
return Ok(());
|
tracing::debug!("Downloaded {} to {}", url, dest.display());
|
||||||
}
|
break 'download Ok(());
|
||||||
Err(e) if is_retryable(&e) => {
|
|
||||||
if attempt == MAX_RETRIES {
|
|
||||||
return Err(e);
|
|
||||||
}
|
}
|
||||||
sleep_before_retry("download", url, attempt, &e).await;
|
Err(e) if is_retryable(&e) => {
|
||||||
|
if attempt == MAX_RETRIES {
|
||||||
|
break 'download Err(e);
|
||||||
|
}
|
||||||
|
sleep_before_retry("download", url, attempt, &e).await;
|
||||||
|
}
|
||||||
|
Err(e) => break 'download Err(e),
|
||||||
}
|
}
|
||||||
Err(e) => return Err(e),
|
|
||||||
}
|
}
|
||||||
|
unreachable!("retry loop returns on success or final error")
|
||||||
|
};
|
||||||
|
if result.is_err() {
|
||||||
|
let _ = tokio::fs::remove_file(dest).await;
|
||||||
}
|
}
|
||||||
|
result
|
||||||
unreachable!("retry loop returns on success or final error")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// single attempt at downloading a file to disk
|
// single attempt at downloading a file to disk
|
||||||
|
|||||||
+58
-11
@@ -15,7 +15,7 @@ pub struct ProjectInfo {
|
|||||||
pub icon_url: Option<String>,
|
pub icon_url: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Deserialize)]
|
#[derive(Debug, Clone, Deserialize, serde::Serialize)]
|
||||||
pub struct VersionInfo {
|
pub struct VersionInfo {
|
||||||
pub id: String,
|
pub id: String,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
@@ -27,7 +27,7 @@ pub struct VersionInfo {
|
|||||||
pub files: Vec<VersionFile>,
|
pub files: Vec<VersionFile>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Deserialize)]
|
#[derive(Debug, Clone, Deserialize, serde::Serialize)]
|
||||||
pub struct VersionFile {
|
pub struct VersionFile {
|
||||||
pub url: String,
|
pub url: String,
|
||||||
pub filename: String,
|
pub filename: String,
|
||||||
@@ -359,14 +359,32 @@ pub async fn download_version_file(
|
|||||||
let file = select_primary_file(version)?;
|
let file = select_primary_file(version)?;
|
||||||
let path = destination.join(&file.filename);
|
let path = destination.join(&file.filename);
|
||||||
if path.exists() {
|
if path.exists() {
|
||||||
return Ok(DownloadOutcome::SkippedExisting(path));
|
if verify_version_file(&path, file)? {
|
||||||
|
return Ok(DownloadOutcome::SkippedExisting(path));
|
||||||
|
}
|
||||||
|
return Err(crate::net::NetError::Parse(format!(
|
||||||
|
"Existing file '{}' does not match the selected Modrinth version",
|
||||||
|
path.display()
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
let temporary = destination.join(format!(".{}.{}.rmcl-download", file.filename, version.id));
|
||||||
|
if temporary.exists() {
|
||||||
|
tokio::fs::remove_file(&temporary).await?;
|
||||||
}
|
}
|
||||||
let progress =
|
let progress =
|
||||||
crate::tui::progress::ProgressTask::start(format!("Downloading {}", file.filename));
|
crate::tui::progress::ProgressTask::start(format!("Downloading {}", file.filename));
|
||||||
crate::net::download_file(client, &file.url, &path, |current, total| {
|
crate::net::download_file(client, &file.url, &temporary, |current, total| {
|
||||||
progress.set_progress(current, total);
|
progress.set_progress(current, total);
|
||||||
})
|
})
|
||||||
.await?;
|
.await?;
|
||||||
|
if !verify_version_file(&temporary, file)? {
|
||||||
|
let _ = tokio::fs::remove_file(&temporary).await;
|
||||||
|
return Err(crate::net::NetError::Parse(format!(
|
||||||
|
"Downloaded file '{}' failed its size or hash verification",
|
||||||
|
file.filename
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
tokio::fs::rename(&temporary, &path).await?;
|
||||||
progress.finish();
|
progress.finish();
|
||||||
Ok(DownloadOutcome::Downloaded(path))
|
Ok(DownloadOutcome::Downloaded(path))
|
||||||
}
|
}
|
||||||
@@ -385,11 +403,15 @@ pub async fn download_version_file_for_update(
|
|||||||
|
|
||||||
let temporary = destination.join(format!(".{}.{}.rmcl-download", file.filename, version.id));
|
let temporary = destination.join(format!(".{}.{}.rmcl-download", file.filename, version.id));
|
||||||
let backup = destination.join(format!(".{}.{}.rmcl-backup", file.filename, version.id));
|
let backup = destination.join(format!(".{}.{}.rmcl-backup", file.filename, version.id));
|
||||||
if temporary.exists() || backup.exists() {
|
if backup.exists() {
|
||||||
return Err(crate::net::NetError::Parse(format!(
|
if !installed_path.exists() {
|
||||||
"A previous update of '{}' did not finish cleanly",
|
tokio::fs::rename(&backup, installed_path).await?;
|
||||||
file.filename
|
} else {
|
||||||
)));
|
tokio::fs::remove_file(&backup).await?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if temporary.exists() {
|
||||||
|
tokio::fs::remove_file(&temporary).await?;
|
||||||
}
|
}
|
||||||
|
|
||||||
let progress =
|
let progress =
|
||||||
@@ -398,11 +420,36 @@ pub async fn download_version_file_for_update(
|
|||||||
progress.set_progress(current, total);
|
progress.set_progress(current, total);
|
||||||
})
|
})
|
||||||
.await?;
|
.await?;
|
||||||
progress.finish();
|
if !verify_version_file(&temporary, file)? {
|
||||||
|
let _ = tokio::fs::remove_file(&temporary).await;
|
||||||
|
return Err(crate::net::NetError::Parse(format!(
|
||||||
|
"Downloaded file '{}' failed its size or hash verification",
|
||||||
|
file.filename
|
||||||
|
)));
|
||||||
|
}
|
||||||
replace_installed_file(&temporary, &target, installed_path, &backup).await?;
|
replace_installed_file(&temporary, &target, installed_path, &backup).await?;
|
||||||
|
progress.finish();
|
||||||
Ok(DownloadOutcome::Downloaded(target))
|
Ok(DownloadOutcome::Downloaded(target))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn verify_version_file(
|
||||||
|
path: &std::path::Path,
|
||||||
|
expected: &VersionFile,
|
||||||
|
) -> Result<bool, crate::net::NetError> {
|
||||||
|
let fingerprint = crate::instance::content::manifest::fingerprint(path)?;
|
||||||
|
if expected.size > 0 && fingerprint.size != expected.size {
|
||||||
|
return Ok(false);
|
||||||
|
}
|
||||||
|
for algorithm in ["sha512", "sha1"] {
|
||||||
|
if let Some(expected_hash) = expected.hashes.get(algorithm)
|
||||||
|
&& fingerprint.hash(algorithm) != Some(expected_hash.as_str())
|
||||||
|
{
|
||||||
|
return Ok(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(true)
|
||||||
|
}
|
||||||
|
|
||||||
async fn replace_installed_file(
|
async fn replace_installed_file(
|
||||||
temporary: &std::path::Path,
|
temporary: &std::path::Path,
|
||||||
target: &std::path::Path,
|
target: &std::path::Path,
|
||||||
@@ -611,7 +658,7 @@ mod tests {
|
|||||||
let version = version_with_files(vec![VersionFile {
|
let version = version_with_files(vec![VersionFile {
|
||||||
url: "https://example.test/example.jar".to_owned(),
|
url: "https://example.test/example.jar".to_owned(),
|
||||||
filename: "example.jar".to_owned(),
|
filename: "example.jar".to_owned(),
|
||||||
size: 1,
|
size: b"existing".len() as u64,
|
||||||
primary: true,
|
primary: true,
|
||||||
hashes: HashMap::new(),
|
hashes: HashMap::new(),
|
||||||
}]);
|
}]);
|
||||||
|
|||||||
+51
-22
@@ -26,18 +26,25 @@ impl App {
|
|||||||
let relative_path = conflict.relative_path.clone();
|
let relative_path = conflict.relative_path.clone();
|
||||||
let project = conflict.candidates.get(conflict.selected).cloned();
|
let project = conflict.candidates.get(conflict.selected).cloned();
|
||||||
if let Some(project) = project
|
if let Some(project) = project
|
||||||
&& let Some((instance_name, manifest)) = &mut self.content_manifest
|
&& let Some((instance_name, _)) = &self.content_manifest
|
||||||
&& let Some(record) = manifest
|
|
||||||
.files
|
|
||||||
.iter_mut()
|
|
||||||
.find(|record| record.relative_path == relative_path)
|
|
||||||
{
|
{
|
||||||
record.resolution = crate::instance::Resolution::Resolved { project };
|
|
||||||
let manifest_path = crate::storage::InstancePaths::new(
|
let manifest_path = crate::storage::InstancePaths::new(
|
||||||
self.instance_manager.instances_dir.join(instance_name),
|
self.instance_manager.instances_dir.join(instance_name),
|
||||||
)
|
)
|
||||||
.content_manifest();
|
.content_manifest();
|
||||||
manifest.save(&manifest_path)?;
|
let updated =
|
||||||
|
crate::instance::ContentManifest::update(&manifest_path, |manifest| {
|
||||||
|
if let Some(record) = manifest
|
||||||
|
.files
|
||||||
|
.iter_mut()
|
||||||
|
.find(|record| record.relative_path == relative_path)
|
||||||
|
{
|
||||||
|
record.resolution =
|
||||||
|
crate::instance::Resolution::Resolved { project };
|
||||||
|
}
|
||||||
|
Ok(manifest.clone())
|
||||||
|
})?;
|
||||||
|
self.content_manifest = Some((instance_name.clone(), updated));
|
||||||
self.provider_conflict = None;
|
self.provider_conflict = None;
|
||||||
self.reconciliation_for = None;
|
self.reconciliation_for = None;
|
||||||
}
|
}
|
||||||
@@ -641,11 +648,19 @@ impl App {
|
|||||||
let Some(request) = state.begin_versions() else {
|
let Some(request) = state.begin_versions() else {
|
||||||
return;
|
return;
|
||||||
};
|
};
|
||||||
|
let version_cache = crate::storage::MetadataPaths::new(&self.instance_manager.meta_dir)
|
||||||
|
.provider_versions("modrinth")
|
||||||
|
.join(&request.project_id)
|
||||||
|
.join(format!(
|
||||||
|
"{}-{}.json",
|
||||||
|
instance.game_version,
|
||||||
|
instance.loader.to_string().to_lowercase()
|
||||||
|
));
|
||||||
tokio::spawn(async move {
|
tokio::spawn(async move {
|
||||||
let registry =
|
let registry =
|
||||||
crate::content_provider::ProviderRegistry::modrinth(crate::net::HttpClient::new());
|
crate::content_provider::ProviderRegistry::modrinth(crate::net::HttpClient::new());
|
||||||
let result = match registry.preferred("modrinth") {
|
let result = match registry.preferred("modrinth") {
|
||||||
Some(provider) => provider
|
Some(provider) => match provider
|
||||||
.compatible_versions(
|
.compatible_versions(
|
||||||
&request.project_id,
|
&request.project_id,
|
||||||
discovery_content_kind(kind),
|
discovery_content_kind(kind),
|
||||||
@@ -653,7 +668,21 @@ impl App {
|
|||||||
instance.loader,
|
instance.loader,
|
||||||
)
|
)
|
||||||
.await
|
.await
|
||||||
.map_err(|error| error.to_string()),
|
{
|
||||||
|
Ok(versions) => {
|
||||||
|
if let Ok(bytes) = serde_json::to_vec_pretty(&versions) {
|
||||||
|
let _ = crate::storage::write_atomic(&version_cache, &bytes);
|
||||||
|
}
|
||||||
|
Ok(versions)
|
||||||
|
}
|
||||||
|
Err(error) => match std::fs::read(&version_cache)
|
||||||
|
.ok()
|
||||||
|
.and_then(|bytes| serde_json::from_slice(&bytes).ok())
|
||||||
|
{
|
||||||
|
Some(versions) => Ok(versions),
|
||||||
|
None => Err(error.to_string()),
|
||||||
|
},
|
||||||
|
},
|
||||||
None => Err("Modrinth content provider is unavailable".to_owned()),
|
None => Err("Modrinth content provider is unavailable".to_owned()),
|
||||||
};
|
};
|
||||||
widgets::content::DiscoveryState::push_action_result(
|
widgets::content::DiscoveryState::push_action_result(
|
||||||
@@ -731,20 +760,12 @@ impl App {
|
|||||||
crate::net::modrinth::DownloadOutcome::SkippedExisting(path) => (path, true),
|
crate::net::modrinth::DownloadOutcome::SkippedExisting(path) => (path, true),
|
||||||
};
|
};
|
||||||
let replaced = request.installed_path.is_some() && !skipped;
|
let replaced = request.installed_path.is_some() && !skipped;
|
||||||
let mut manifest = crate::instance::ContentManifest::load(&manifest_path)
|
|
||||||
.map_err(|error| crate::net::NetError::Parse(error.to_string()))?;
|
|
||||||
if let Some(old_path) = request.installed_path.as_ref()
|
|
||||||
&& let Ok(relative) = old_path.strip_prefix(&minecraft_dir)
|
|
||||||
&& old_path != &path
|
|
||||||
{
|
|
||||||
manifest.remove(relative);
|
|
||||||
}
|
|
||||||
let relative_path = path
|
let relative_path = path
|
||||||
.strip_prefix(&minecraft_dir)
|
.strip_prefix(&minecraft_dir)
|
||||||
.map_err(|error| crate::net::NetError::Parse(error.to_string()))?
|
.map_err(|error| crate::net::NetError::Parse(error.to_string()))?
|
||||||
.to_path_buf();
|
.to_path_buf();
|
||||||
let fingerprint = crate::instance::content::manifest::fingerprint(&path)?;
|
let fingerprint = crate::instance::content::manifest::fingerprint(&path)?;
|
||||||
manifest.upsert(crate::instance::ContentFileRecord {
|
let record = crate::instance::ContentFileRecord {
|
||||||
relative_path,
|
relative_path,
|
||||||
kind: content_kind,
|
kind: content_kind,
|
||||||
enabled: !path
|
enabled: !path
|
||||||
@@ -759,10 +780,18 @@ impl App {
|
|||||||
version_id: request.version.id.clone(),
|
version_id: request.version.id.clone(),
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
});
|
};
|
||||||
manifest
|
crate::instance::ContentManifest::update(&manifest_path, |manifest| {
|
||||||
.save(&manifest_path)
|
if let Some(old_path) = request.installed_path.as_ref()
|
||||||
.map_err(|error| crate::net::NetError::Parse(error.to_string()))?;
|
&& let Ok(relative) = old_path.strip_prefix(&minecraft_dir)
|
||||||
|
&& old_path != &path
|
||||||
|
{
|
||||||
|
manifest.remove(relative);
|
||||||
|
}
|
||||||
|
manifest.upsert(record);
|
||||||
|
Ok(())
|
||||||
|
})
|
||||||
|
.map_err(|error| crate::net::NetError::Parse(error.to_string()))?;
|
||||||
if !skipped
|
if !skipped
|
||||||
&& let Some(old_path) = request
|
&& let Some(old_path) = request
|
||||||
.installed_path
|
.installed_path
|
||||||
|
|||||||
Reference in new issue
Block a user