Files
clash-verge-rev/src-tauri/src/config/profile_storage.rs
T

240 lines
8.3 KiB
Rust

use anyhow::{Result, anyhow};
use clash_verge_profile_store::RECOVERY_JOURNAL_NAME;
use parking_lot::Mutex;
use tokio::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard};
static PROFILE_IO: RwLock<()> = RwLock::const_new(());
static BLOCKED: Mutex<Option<StorageBlock>> = Mutex::new(None);
enum StorageBlock {
Transaction(String),
Restore(String),
}
pub(crate) fn check() -> Result<()> {
match BLOCKED.lock().as_ref() {
Some(StorageBlock::Transaction(reason) | StorageBlock::Restore(reason)) => {
Err(anyhow!("Profile storage requires recovery before use: {reason}"))
}
None => Ok(()),
}
}
pub(crate) fn block(error: &anyhow::Error) {
let mut blocked = BLOCKED.lock();
if !matches!(*blocked, Some(StorageBlock::Transaction(_))) {
*blocked = Some(StorageBlock::Transaction(format!("{error:#}")));
}
}
pub(crate) fn block_restore(error: &anyhow::Error) {
let mut blocked = BLOCKED.lock();
if !matches!(*blocked, Some(StorageBlock::Transaction(_))) {
*blocked = Some(StorageBlock::Restore(format!("{error:#}")));
}
}
pub(crate) async fn write_for_restore() -> Result<(RwLockWriteGuard<'static, ()>, bool)> {
let guard = PROFILE_IO.write().await;
let retry = match BLOCKED.lock().as_ref() {
Some(StorageBlock::Transaction(reason)) => {
return Err(anyhow!("Profile storage requires recovery before use: {reason}"));
}
Some(StorageBlock::Restore(_)) => true,
None => false,
};
Ok((guard, retry))
}
pub(crate) fn finish_restore(_guard: &RwLockWriteGuard<'_, ()>) {
let mut blocked = BLOCKED.lock();
if matches!(*blocked, Some(StorageBlock::Restore(_))) {
*blocked = None;
}
}
pub(crate) async fn read() -> Result<RwLockReadGuard<'static, ()>> {
let guard = PROFILE_IO.read().await;
check()?;
Ok(guard)
}
pub(crate) async fn write() -> Result<RwLockWriteGuard<'static, ()>> {
let guard = PROFILE_IO.write().await;
check()?;
Ok(guard)
}
pub(crate) async fn recover_at_startup() -> Result<()> {
let _guard = write().await?;
let root = crate::utils::dirs::app_home_dir().inspect_err(block)?;
let result: Result<()> = async {
if !journal_exists(&root).await? {
return Ok(());
}
#[cfg(any(unix, all(windows, feature = "profile-store-windows")))]
return tokio::task::spawn_blocking(move || clash_verge_profile_store::recover_pending(&root))
.await?
.map_err(Into::into);
#[cfg(not(any(unix, all(windows, feature = "profile-store-windows"))))]
return Err(anyhow!(
"restore the pending profile transaction with redo support enabled"
));
}
.await;
if let Err(error) = &result {
block(error);
}
result
}
async fn journal_exists(root: &std::path::Path) -> Result<bool> {
match tokio::fs::symlink_metadata(root.join(RECOVERY_JOURNAL_NAME)).await {
Ok(_) => Ok(true),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(false),
Err(error) => Err(error.into()),
}
}
pub(super) async fn commit_refresh(
uid: String,
candidate: super::IProfiles,
body: tristr::alias::String,
) -> Result<super::IProfiles> {
#[cfg(any(unix, all(windows, feature = "profile-store-windows")))]
return commit_recoverable_refresh(uid, candidate, body).await;
#[cfg(not(any(unix, all(windows, feature = "profile-store-windows"))))]
{
write_legacy_refresh(&crate::utils::dirs::app_home_dir()?, &uid, &candidate, body.as_bytes()).await?;
Ok(candidate)
}
}
#[cfg(any(not(unix), test))]
async fn write_legacy_refresh(
root: &std::path::Path,
uid: &str,
candidate: &super::IProfiles,
body: &[u8],
) -> Result<()> {
use anyhow::Context as _;
let file = candidate
.get_item(uid)?
.file
.as_deref()
.context("missing profile filename")?;
let path = root.join(crate::utils::dirs::PROFILES_DIR).join(file);
let mut target = tokio::fs::File::create(path)
.await
.with_context(|| format!("failed to write to file \"{file}\""))?;
use tokio::io::AsyncWriteExt as _;
async {
target.write_all(body).await?;
target.flush().await
}
.await
.with_context(|| format!("profile body {file} may be incomplete; the index was not updated"))?;
drop(target);
super::profiles::save_profile_index(&root.join(crate::utils::dirs::PROFILE_YAML), candidate)
.await
.with_context(|| format!("profile body was written to {file}, but the index was not updated"))
}
#[cfg(any(unix, all(windows, feature = "profile-store-windows")))]
async fn commit_recoverable_refresh(
uid: String,
candidate: super::IProfiles,
body: tristr::alias::String,
) -> Result<super::IProfiles> {
use clash_verge_profile_store::{CommitOutcome, Session};
let root = crate::utils::dirs::app_home_dir()?;
#[cfg(windows)]
{
let probe_root = root.clone();
let supported =
tokio::task::spawn_blocking(move || clash_verge_profile_store::supports_redo(&probe_root)).await??;
if !supported {
if journal_exists(&root).await? {
let error = anyhow!("Profile refresh journal requires a supported NTFS volume");
block(&error);
return Err(error);
}
write_legacy_refresh(&root, &uid, &candidate, body.as_bytes()).await?;
return Ok(candidate);
}
}
let result = tokio::task::spawn_blocking(move || {
let session = Session::open(&root).map_err(anyhow::Error::from).inspect_err(|error| {
match std::fs::symlink_metadata(root.join(RECOVERY_JOURNAL_NAME)) {
Err(status) if status.kind() == std::io::ErrorKind::NotFound => {}
_ => block(error),
}
})?;
let item = candidate.get_item(&uid)?;
if let Some(file) = item.file.as_deref()
&& !file.contains(['/', '\\', '\0'])
&& (!cfg!(windows) || !file.contains(':'))
&& !matches!(file, "" | "." | "..")
{
let path = root.join("profiles").join(file);
match std::fs::symlink_metadata(&path) {
Ok(metadata) if metadata.is_file() => {
std::fs::OpenOptions::new().write(true).open(&path)?;
}
Ok(_) => {}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
Err(error) => return Err(error.into()),
}
}
match session.commit_refresh(&uid, &candidate, body.as_bytes()) {
CommitOutcome::Committed => Ok(candidate),
CommitOutcome::CommittedCleanupPending(error) => {
block(&error.into());
Ok(candidate)
}
CommitOutcome::Retryable(error) => {
Err(anyhow::Error::from(error).context("profile refresh stopped before commit"))
}
CommitOutcome::RetryCleanupFailed(error) => {
let error = anyhow::Error::from(error);
block(&error);
Err(error.context("failed to discard the incomplete profile refresh"))
}
CommitOutcome::NeedsRecovery(error) => {
let error = anyhow::Error::from(error);
block(&error);
Err(error.context("profile refresh requires recovery"))
}
}
})
.await;
match result {
Ok(result) => result,
Err(error) => {
let error = anyhow::Error::from(error).context("profile storage worker stopped unexpectedly");
block(&error);
Err(error)
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn legacy_refresh_reports_a_written_body_when_index_replace_fails() -> Result<()> {
let home = tempfile::tempdir()?;
let root = home.path();
std::fs::create_dir(root.join("profiles"))?;
std::fs::create_dir(root.join("profiles.yaml"))?;
let profiles = serde_yaml_ng::from_str("items: [{uid: r, file: old.yaml}]")?;
let result = write_legacy_refresh(root, "r", &profiles, b"new body").await;
assert_eq!(std::fs::read(root.join("profiles/old.yaml"))?, b"new body");
assert!(result.unwrap_err().to_string().contains("body was written"));
Ok(())
}
}