mirror of
https://github.com/clash-verge-rev/clash-verge-rev.git
synced 2026-12-04 21:30:06 +08:00
fix(profile): commit missing companions with the refreshed subscription
This commit is contained in:
@@ -28,6 +28,7 @@
|
||||
<details>
|
||||
<summary><strong> 🐞 修复问题 </strong></summary>
|
||||
|
||||
- 修复订阅更新覆盖下载期间修改的设置,以及更新失败后遗留增强配置
|
||||
- 修复手动更新订阅时错误提示缺失或重复,显示订阅名称和失败原因
|
||||
- 优化订阅恢复失败提示,显示受影响的订阅名称
|
||||
- 修复「外部控制器」复制成功的提示一闪而过
|
||||
|
||||
@@ -28,6 +28,7 @@ const INDEX_NEXT: &str = "index.next";
|
||||
const DECISION_NEXT: &str = "decision.next";
|
||||
const DECISION_BUILDING: &str = "decision.building";
|
||||
const APPLY: &str = "body.apply";
|
||||
const MAX_COMPANIONS: usize = 5;
|
||||
|
||||
type Result<T> = std::result::Result<T, StoreError>;
|
||||
|
||||
@@ -62,6 +63,46 @@ struct Decision {
|
||||
old_index_digest: [u8; 32],
|
||||
body_digest: [u8; 32],
|
||||
index_digest: [u8; 32],
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
companions: Vec<Companion>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Companion {
|
||||
uid: String,
|
||||
digest: [u8; 32],
|
||||
}
|
||||
|
||||
fn companion_file<'a>(profiles: &'a IProfiles, parent: &str, uid: &str) -> Result<&'a str> {
|
||||
let item = profiles.get_item(uid)?;
|
||||
let options = profiles
|
||||
.get_item(parent)?
|
||||
.option
|
||||
.as_ref()
|
||||
.ok_or(StoreError::DecisionTargetMismatch)?;
|
||||
let reference = match item.itype.as_deref() {
|
||||
Some("merge") => &options.merge,
|
||||
Some("script") => &options.script,
|
||||
Some("rules") => &options.rules,
|
||||
Some("proxies") => &options.proxies,
|
||||
Some("groups") => &options.groups,
|
||||
_ => return Err(StoreError::DecisionTargetMismatch),
|
||||
};
|
||||
let file = item.file.as_deref().ok_or(StoreError::MissingFilename)?;
|
||||
validate_filename(file)?;
|
||||
if reference.as_deref() != Some(uid)
|
||||
|| profiles
|
||||
.items
|
||||
.iter()
|
||||
.flatten()
|
||||
.filter(|other| other.uid.as_deref() == Some(uid) || other.file.as_deref() == Some(file))
|
||||
.count()
|
||||
!= 1
|
||||
{
|
||||
return Err(StoreError::DecisionTargetMismatch);
|
||||
}
|
||||
Ok(file)
|
||||
}
|
||||
|
||||
impl Session {
|
||||
@@ -239,8 +280,8 @@ impl Session {
|
||||
return Err(StoreError::SharedFilename);
|
||||
}
|
||||
let profiles_dir = self.root.join(PROFILES);
|
||||
let metadata = unshared_body(&profiles_dir, ¤t, file)?;
|
||||
unshared_body(&profiles_dir, candidate, file)?;
|
||||
let metadata = unshared_body(&profiles_dir, ¤t, file, 1)?;
|
||||
unshared_body(&profiles_dir, candidate, file, 1)?;
|
||||
let index_permissions = regular(&index_path)?.permissions();
|
||||
let old_body_digest = optional_file_digest(&profiles_dir.join(file))?;
|
||||
if old_item.file.is_none() && old_body_digest.is_some() {
|
||||
@@ -248,8 +289,34 @@ impl Session {
|
||||
}
|
||||
let mut index = b"# Profiles Config for Clash Verge\n\n".to_vec();
|
||||
serde_yaml_ng::to_writer(&mut index, candidate)?;
|
||||
let mut companions = Vec::new();
|
||||
let mut templates = Vec::new();
|
||||
for item in candidate.items.iter().flatten() {
|
||||
let Some(data) = &item.file_data else { continue };
|
||||
let id = item.uid.as_deref().ok_or(StoreError::DecisionTargetMismatch)?;
|
||||
let file = companion_file(candidate, uid, id)?;
|
||||
if current
|
||||
.items
|
||||
.iter()
|
||||
.flatten()
|
||||
.any(|old| old.uid.as_deref() == Some(id) || old.file.as_deref() == Some(file))
|
||||
|| optional_regular(&profiles_dir.join(file))?.is_some()
|
||||
{
|
||||
return Err(StoreError::ExistingBodyPath);
|
||||
}
|
||||
let bytes = data.as_bytes();
|
||||
companions.push(Companion {
|
||||
uid: id.to_owned(),
|
||||
digest: Sha256::digest(bytes).into(),
|
||||
});
|
||||
templates.push(bytes);
|
||||
}
|
||||
if companions.len() > MAX_COMPANIONS {
|
||||
return Err(StoreError::DecisionTargetMismatch);
|
||||
}
|
||||
let decision = Decision {
|
||||
version: 1,
|
||||
version: if companions.is_empty() { 1 } else { 2 },
|
||||
companions,
|
||||
uid: uid.into(),
|
||||
file: file.into(),
|
||||
old_body_digest,
|
||||
@@ -268,6 +335,9 @@ impl Session {
|
||||
checkpoint("journal-created")?;
|
||||
write_new(&journal.join(BODY_NEXT), body, metadata.map(|meta| meta.permissions()))?;
|
||||
checkpoint("body-staged")?;
|
||||
for (slot, bytes) in templates.into_iter().enumerate() {
|
||||
write_new(&journal.join(format!("companion.{slot}")), bytes, None)?;
|
||||
}
|
||||
write_new(&journal.join(INDEX_NEXT), &index, Some(index_permissions))?;
|
||||
checkpoint("index-staged")?;
|
||||
write_new(&journal.join(DECISION_BUILDING), &decision, None)?;
|
||||
@@ -296,7 +366,7 @@ impl Session {
|
||||
let can_revert_new_body = decision.old_body_digest.is_none()
|
||||
&& (!index_installed || decision.old_index_digest == decision.index_digest);
|
||||
if !can_revert_new_body {
|
||||
unshared_body(&profiles_dir, &candidate, &decision.file)?;
|
||||
unshared_body(&profiles_dir, &candidate, &decision.file, 1)?;
|
||||
}
|
||||
|
||||
let body_next = journal.join(BODY_NEXT);
|
||||
@@ -319,11 +389,11 @@ impl Session {
|
||||
if can_revert_new_body {
|
||||
// Native aliases of a missing file only resolve once the file exists.
|
||||
let check = (|| {
|
||||
unshared_body(&profiles_dir, &candidate, &decision.file)?;
|
||||
unshared_body(&profiles_dir, &candidate, &decision.file, 1)?;
|
||||
if !index_installed {
|
||||
let (index, _) = verified(&index_path, decision.old_index_digest)?;
|
||||
let current = serde_yaml_ng::from_slice(&index)?;
|
||||
unshared_body(&profiles_dir, ¤t, &decision.file)?;
|
||||
unshared_body(&profiles_dir, ¤t, &decision.file, 1)?;
|
||||
}
|
||||
Ok(())
|
||||
})();
|
||||
@@ -339,6 +409,36 @@ impl Session {
|
||||
return Ok(InstallOutcome::Reverted(error));
|
||||
}
|
||||
}
|
||||
let old_companion_index: Option<IProfiles> = if !index_installed && !decision.companions.is_empty() {
|
||||
let (index, _) = verified(&index_path, decision.old_index_digest)?;
|
||||
Some(serde_yaml_ng::from_slice(&index)?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
for (slot, companion) in decision.companions.iter().enumerate() {
|
||||
let file = companion_file(&candidate, &decision.uid, &companion.uid)?;
|
||||
let staged = journal.join(format!("companion.{slot}"));
|
||||
if file_digest(&staged)? != companion.digest {
|
||||
return Err(StoreError::StagedChecksumMismatch);
|
||||
}
|
||||
let target = profiles_dir.join(file);
|
||||
match fs::hard_link(&staged, &target) {
|
||||
Ok(()) => {}
|
||||
Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {
|
||||
if platform::file_identity(&target, ®ular(&target)?)?
|
||||
!= platform::file_identity(&staged, ®ular(&staged)?)?
|
||||
{
|
||||
return Err(StoreError::LiveContentChanged(target));
|
||||
}
|
||||
}
|
||||
Err(error) => return Err(error.into()),
|
||||
}
|
||||
unshared_body(&profiles_dir, &candidate, file, 2)?;
|
||||
if let Some(old) = &old_companion_index {
|
||||
unshared_body(&profiles_dir, old, file, 2)?;
|
||||
}
|
||||
checkpoint("companion-installed")?;
|
||||
}
|
||||
if index_installed {
|
||||
platform::sync_file(&index_path)?;
|
||||
} else {
|
||||
@@ -381,7 +481,15 @@ impl Session {
|
||||
] {
|
||||
remove_file_if_exists(&journal.join(name))?;
|
||||
}
|
||||
fs::remove_dir(&journal)?;
|
||||
match fs::remove_dir(&journal) {
|
||||
Err(error) if error.kind() == io::ErrorKind::DirectoryNotEmpty => {
|
||||
for slot in 0..MAX_COMPANIONS {
|
||||
remove_file_if_exists(&journal.join(format!("companion.{slot}")))?;
|
||||
}
|
||||
fs::remove_dir(&journal)?;
|
||||
}
|
||||
result => result?,
|
||||
}
|
||||
Ok(platform::sync_dir(&self.root)?)
|
||||
}
|
||||
|
||||
@@ -393,6 +501,17 @@ impl Session {
|
||||
if !old_pair && !new_pair {
|
||||
return Err(StoreError::InconsistentUnmarkedPair);
|
||||
}
|
||||
if new_pair && !intent.companions.is_empty() {
|
||||
let (bytes, _) = verified(&self.root.join(INDEX), intent.index_digest)?;
|
||||
let candidate = serde_yaml_ng::from_slice(&bytes)?;
|
||||
for companion in &intent.companions {
|
||||
let file = companion_file(&candidate, &intent.uid, &companion.uid)?;
|
||||
let path = self.root.join(PROFILES).join(file);
|
||||
if optional_file_digest(&path)? != Some(companion.digest) {
|
||||
return Err(StoreError::LiveContentChanged(path));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -438,7 +557,10 @@ fn read_decision(path: &Path) -> Result<Decision> {
|
||||
return Err(StoreError::OversizedDecision);
|
||||
}
|
||||
let decision: Decision = serde_json::from_slice(&fs::read(path)?).map_err(StoreError::InvalidDecision)?;
|
||||
if decision.version != 1 {
|
||||
if !matches!(
|
||||
(decision.version, decision.companions.len()),
|
||||
(1, 0) | (2, 1..=MAX_COMPANIONS)
|
||||
) {
|
||||
return Err(StoreError::UnknownDecisionVersion);
|
||||
}
|
||||
validate_filename(&decision.file)?;
|
||||
@@ -500,14 +622,17 @@ fn body_filename<'a>(profiles: &'a IProfiles, uid: &str) -> Result<&'a str> {
|
||||
Ok(file)
|
||||
}
|
||||
|
||||
fn unshared_body(dir: &Path, profiles: &IProfiles, file: &str) -> Result<Option<fs::Metadata>> {
|
||||
fn unshared_body(dir: &Path, profiles: &IProfiles, file: &str, expected_links: u64) -> Result<Option<fs::Metadata>> {
|
||||
let mut path = dir.join(file);
|
||||
let target = optional_regular(&path)?;
|
||||
let identity = target
|
||||
.as_ref()
|
||||
.map(|metadata| platform::file_identity(&path, metadata))
|
||||
.transpose()?;
|
||||
if identity.as_ref().is_some_and(|identity| identity.links != 1) {
|
||||
if identity
|
||||
.as_ref()
|
||||
.is_some_and(|identity| identity.links != expected_links)
|
||||
{
|
||||
return Err(StoreError::HardLinkedBody);
|
||||
}
|
||||
for other in profiles.items.iter().flatten().filter_map(|item| item.file.as_deref()) {
|
||||
|
||||
@@ -126,3 +126,50 @@ fn recovery_identifies_the_interrupted_subscription_from_its_verified_index()
|
||||
assert!(matches!(recover_pending(root), Err(StoreError::StagedChecksumMismatch)));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(feature = "test-support")]
|
||||
#[test]
|
||||
fn legacy_companions_follow_the_refresh_decision() -> Result<(), clash_verge_profile_store::StoreError> {
|
||||
for phase in ["prepared", "companion-installed", "decision-removed"] {
|
||||
let home = tempfile::tempdir()?;
|
||||
let root = home.path();
|
||||
let profiles = root.join("profiles");
|
||||
fs::create_dir(&profiles)?;
|
||||
let old = "items: [{uid: r, type: remote, file: r.yaml}]";
|
||||
fs::write(root.join("profiles.yaml"), old)?;
|
||||
fs::write(profiles.join("r.yaml"), b"old")?;
|
||||
let mut candidate: IProfiles = serde_yaml_ng::from_str(
|
||||
"items: [{uid: r, type: remote, file: r.yaml, option: {script: s}}, {uid: s, type: script, file: s.js}]",
|
||||
)?;
|
||||
candidate.get_item_mut("s")?.file_data = Some("template".into());
|
||||
let result = Session::open(root)?.commit_observed("r", &candidate, b"new", &mut |checkpoint| {
|
||||
if checkpoint == phase {
|
||||
return Err(std::io::Error::other("interrupted").into());
|
||||
}
|
||||
Ok(())
|
||||
});
|
||||
if phase == "decision-removed" {
|
||||
assert!(matches!(result, CommitOutcome::CommittedCleanupPending(_)));
|
||||
fs::write(profiles.join("s.js"), b"edited")?;
|
||||
assert!(clash_verge_profile_store::recover_pending(root).is_err());
|
||||
assert_eq!(fs::read(profiles.join("s.js"))?, b"edited");
|
||||
assert!(root.join(clash_verge_profile_store::RECOVERY_JOURNAL_NAME).exists());
|
||||
continue;
|
||||
}
|
||||
assert_eq!(fs::read_to_string(root.join("profiles.yaml"))?, old);
|
||||
if phase == "prepared" {
|
||||
assert!(matches!(result, CommitOutcome::Retryable(_)));
|
||||
clash_verge_profile_store::recover_pending(root)?;
|
||||
assert!(!profiles.join("s.js").exists());
|
||||
assert_eq!(fs::read(profiles.join("r.yaml"))?, b"old");
|
||||
} else {
|
||||
assert!(matches!(result, CommitOutcome::NeedsRecovery(_)));
|
||||
clash_verge_profile_store::recover_pending(root)?;
|
||||
let stored: IProfiles = serde_yaml_ng::from_slice(&fs::read(root.join("profiles.yaml"))?)?;
|
||||
assert_eq!(stored.get_item("s")?.file.as_deref(), Some("s.js"));
|
||||
assert_eq!(fs::read(profiles.join("r.yaml"))?, b"new");
|
||||
assert_eq!(fs::read(profiles.join("s.js"))?, b"template");
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -44,15 +44,26 @@ pub(super) async fn build_profile(item: &PrfItem, file_data: Option<String>) ->
|
||||
}
|
||||
}
|
||||
|
||||
async fn append_companion_item(item: &mut PrfItem) -> Result<String> {
|
||||
profiles::append_profile(item).await?;
|
||||
item.uid
|
||||
.clone()
|
||||
.ok_or_else(|| anyhow::anyhow!("appended companion item has no uid"))
|
||||
fn missing_companions(options: &mut PrfOption) -> Vec<PrfItem> {
|
||||
let mut companions = Vec::new();
|
||||
for (reference, build) in [
|
||||
(&mut options.merge, (|| build_merge_profile(None)) as fn() -> PrfItem),
|
||||
(&mut options.script, || build_script_profile(None)),
|
||||
(&mut options.rules, from_rules),
|
||||
(&mut options.proxies, from_proxies),
|
||||
(&mut options.groups, from_groups),
|
||||
] {
|
||||
if reference.is_none() {
|
||||
let item = build();
|
||||
*reference = item.uid.clone();
|
||||
companions.push(item);
|
||||
}
|
||||
}
|
||||
companions
|
||||
}
|
||||
|
||||
async fn prepare_profile_options(source: Option<&PrfOption>) -> Result<PrfOption> {
|
||||
let mut options = PrfOption {
|
||||
fn creation_options(source: Option<&PrfOption>) -> PrfOption {
|
||||
PrfOption {
|
||||
update_interval: source.and_then(|options| options.update_interval),
|
||||
merge: source.and_then(|options| options.merge.clone()),
|
||||
script: source.and_then(|options| options.script.clone()),
|
||||
@@ -60,23 +71,14 @@ async fn prepare_profile_options(source: Option<&PrfOption>) -> Result<PrfOption
|
||||
proxies: source.and_then(|options| options.proxies.clone()),
|
||||
groups: source.and_then(|options| options.groups.clone()),
|
||||
..PrfOption::default()
|
||||
};
|
||||
if options.merge.is_none() {
|
||||
options.merge = Some(append_companion_item(&mut build_merge_profile(None)).await?);
|
||||
}
|
||||
if options.script.is_none() {
|
||||
options.script = Some(append_companion_item(&mut build_script_profile(None)).await?);
|
||||
}
|
||||
|
||||
async fn append_companions(companions: Vec<PrfItem>) -> Result<()> {
|
||||
for mut item in companions {
|
||||
profiles::append_profile(&mut item).await?;
|
||||
}
|
||||
if options.rules.is_none() {
|
||||
options.rules = Some(append_companion_item(&mut from_rules()).await?);
|
||||
}
|
||||
if options.proxies.is_none() {
|
||||
options.proxies = Some(append_companion_item(&mut from_proxies()).await?);
|
||||
}
|
||||
if options.groups.is_none() {
|
||||
options.groups = Some(append_companion_item(&mut from_groups()).await?);
|
||||
}
|
||||
Ok(options)
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn from_local(
|
||||
@@ -87,7 +89,8 @@ async fn from_local(
|
||||
) -> Result<PrfItem> {
|
||||
let uid = help::get_uid("L").into();
|
||||
let file = format!("{uid}.yaml").into();
|
||||
let options = prepare_profile_options(option).await?;
|
||||
let mut options = creation_options(option);
|
||||
append_companions(missing_companions(&mut options)).await?;
|
||||
Ok(PrfItem {
|
||||
uid: Some(uid),
|
||||
itype: Some("local".into()),
|
||||
@@ -113,12 +116,16 @@ pub(crate) struct DownloadedSubscription {
|
||||
body: String,
|
||||
}
|
||||
|
||||
pub(crate) struct RemoteProfileRefresh {
|
||||
pub(super) extra: Option<PrfExtra>,
|
||||
pub(super) home: Option<String>,
|
||||
pub(super) updated: usize,
|
||||
pub(super) option: PrfOption,
|
||||
pub(super) body: String,
|
||||
impl DownloadedSubscription {
|
||||
pub(super) fn apply(self, item: &mut PrfItem) -> (String, Vec<PrfItem>) {
|
||||
let option = item.option.get_or_insert_with(PrfOption::default);
|
||||
option.update_interval = option.update_interval.or(self.update_interval_minutes);
|
||||
option.allow_auto_update.get_or_insert(true);
|
||||
item.home = self.home;
|
||||
item.extra = self.extra;
|
||||
item.updated = Some(chrono::Local::now().timestamp() as usize);
|
||||
(self.body, missing_companions(option))
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn build_remote_profile(
|
||||
@@ -135,28 +142,22 @@ pub(crate) async fn build_remote_profile(
|
||||
.or_else(|| downloaded.suggested_name.take().map(Into::into))
|
||||
.unwrap_or_else(|| "Remote File".into());
|
||||
let url = downloaded.url.as_str().into();
|
||||
let RemoteProfileRefresh {
|
||||
extra,
|
||||
home,
|
||||
updated,
|
||||
option,
|
||||
body,
|
||||
} = prepare_remote_refresh(downloaded, option).await?;
|
||||
|
||||
Ok(PrfItem {
|
||||
let mut options = creation_options(option);
|
||||
options.allow_auto_update = option.and_then(|value| value.allow_auto_update);
|
||||
let mut item = PrfItem {
|
||||
uid: Some(uid),
|
||||
itype: Some("remote".into()),
|
||||
name: Some(name),
|
||||
desc: desc.cloned(),
|
||||
file: Some(file),
|
||||
url: Some(url),
|
||||
selected: None,
|
||||
extra,
|
||||
option: Some(option),
|
||||
home,
|
||||
updated: Some(updated),
|
||||
file_data: Some(body),
|
||||
})
|
||||
option: Some(options),
|
||||
..Default::default()
|
||||
};
|
||||
let (body, companions) = downloaded.apply(&mut item);
|
||||
append_companions(companions).await?;
|
||||
item.file_data = Some(body);
|
||||
Ok(item)
|
||||
}
|
||||
|
||||
pub(crate) fn subscription_proxy(options: Option<&PrfOption>) -> ProxyType {
|
||||
@@ -212,22 +213,6 @@ pub(crate) async fn download_subscription(
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) async fn prepare_remote_refresh(
|
||||
downloaded: DownloadedSubscription,
|
||||
option: Option<&PrfOption>,
|
||||
) -> Result<RemoteProfileRefresh> {
|
||||
let mut options = prepare_profile_options(option).await?;
|
||||
options.update_interval = options.update_interval.or(downloaded.update_interval_minutes);
|
||||
options.allow_auto_update = Some(option.and_then(|options| options.allow_auto_update).unwrap_or(true));
|
||||
Ok(RemoteProfileRefresh {
|
||||
extra: downloaded.extra,
|
||||
home: downloaded.home,
|
||||
updated: chrono::Local::now().timestamp() as usize,
|
||||
option: options,
|
||||
body: downloaded.body,
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn build_merge_profile(uid: Option<String>) -> PrfItem {
|
||||
let (id, template) = if let Some(uid) = uid {
|
||||
(uid, tmpl::ITEM_MERGE.into())
|
||||
@@ -380,7 +365,14 @@ mod tests {
|
||||
..option
|
||||
};
|
||||
let downloaded = download_subscription(&url, Some(&refresh_option), ProxyType::None).await?;
|
||||
let refresh = prepare_remote_refresh(downloaded, Some(&refresh_option)).await?;
|
||||
let mut refresh = PrfItem {
|
||||
option: Some(PrfOption {
|
||||
groups: None,
|
||||
..refresh_option.clone()
|
||||
}),
|
||||
..Default::default()
|
||||
};
|
||||
let (body, companions) = downloaded.apply(&mut refresh);
|
||||
server.await??;
|
||||
assert_eq!(item.itype.as_deref(), Some("remote"));
|
||||
assert_eq!(item.name.as_deref(), Some("remote.yaml"));
|
||||
@@ -393,16 +385,19 @@ mod tests {
|
||||
assert_eq!(fetched_option.update_interval, Some(0));
|
||||
assert_eq!(fetched_option.allow_auto_update, Some(false));
|
||||
|
||||
assert_eq!(refresh.body.as_str(), BODY);
|
||||
assert_eq!(body.as_str(), BODY);
|
||||
assert_eq!(refresh.home, item.home);
|
||||
let usage = refresh.extra.context("expected refresh usage")?;
|
||||
assert_eq!((usage.upload, usage.download, usage.total, usage.expire), (1, 2, 3, 4));
|
||||
assert_eq!(companions.len(), 1);
|
||||
assert_eq!(companions[0].itype.as_deref(), Some("groups"));
|
||||
assert_eq!(
|
||||
refresh.option,
|
||||
PrfOption {
|
||||
Some(PrfOption {
|
||||
update_interval: Some(120),
|
||||
..fetched_option
|
||||
}
|
||||
groups: companions[0].uid.clone(),
|
||||
..refresh_option
|
||||
})
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -127,12 +127,16 @@ pub(super) async fn commit_refresh(
|
||||
body: tristr::alias::String,
|
||||
) -> Result<super::IProfiles> {
|
||||
#[cfg(any(unix, all(windows, feature = "profile-store-windows")))]
|
||||
return commit_recoverable_refresh(uid, candidate, body).await;
|
||||
let mut candidate = commit_recoverable_refresh(uid, candidate, body).await?;
|
||||
#[cfg(not(any(unix, all(windows, feature = "profile-store-windows"))))]
|
||||
{
|
||||
let mut candidate = {
|
||||
write_legacy_refresh(&crate::utils::dirs::app_home_dir()?, &uid, &candidate, body.as_bytes()).await?;
|
||||
Ok(candidate)
|
||||
candidate
|
||||
};
|
||||
for item in candidate.items.iter_mut().flatten() {
|
||||
item.file_data = None;
|
||||
}
|
||||
Ok(candidate)
|
||||
}
|
||||
|
||||
#[cfg(any(not(unix), test))]
|
||||
@@ -161,9 +165,72 @@ async fn write_legacy_refresh(
|
||||
.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"))
|
||||
let mut created = Vec::new();
|
||||
let result: Result<()> = async {
|
||||
for item in candidate.items.iter().flatten() {
|
||||
let Some(data) = &item.file_data else { continue };
|
||||
let name = item.file.as_deref().context("missing companion filename")?;
|
||||
super::profiles::validate_profile_file(name)?;
|
||||
let path = root.join(crate::utils::dirs::PROFILES_DIR).join(name);
|
||||
let mut options = tokio::fs::OpenOptions::new();
|
||||
options.create_new(true).write(true);
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use windows_sys::Win32::Storage::FileSystem::{DELETE, FILE_GENERIC_WRITE, FILE_SHARE_READ};
|
||||
options
|
||||
.access_mode(FILE_GENERIC_WRITE | DELETE)
|
||||
.share_mode(FILE_SHARE_READ);
|
||||
}
|
||||
let mut file = options.open(&path).await?;
|
||||
let written = async {
|
||||
file.write_all(data.as_bytes()).await?;
|
||||
file.flush().await
|
||||
}
|
||||
.await;
|
||||
created.push((path, file));
|
||||
written?;
|
||||
}
|
||||
super::profiles::save_profile_index(&root.join(crate::utils::dirs::PROFILE_YAML), candidate).await
|
||||
}
|
||||
.await;
|
||||
if let Err(error) = result {
|
||||
let mut error = error;
|
||||
for (path, file) in created {
|
||||
#[cfg(windows)]
|
||||
let cleanup = {
|
||||
use std::os::windows::io::AsRawHandle as _;
|
||||
use windows_sys::Win32::Storage::FileSystem::{
|
||||
FILE_DISPOSITION_INFO, FileDispositionInfo, SetFileInformationByHandle,
|
||||
};
|
||||
let disposition = FILE_DISPOSITION_INFO { DeleteFile: 1 };
|
||||
// Remove only the file this refresh created, even if its parent has been renamed.
|
||||
let deleted = unsafe {
|
||||
SetFileInformationByHandle(
|
||||
file.as_raw_handle(),
|
||||
FileDispositionInfo,
|
||||
(&raw const disposition).cast(),
|
||||
std::mem::size_of::<FILE_DISPOSITION_INFO>() as u32,
|
||||
)
|
||||
};
|
||||
if deleted == 0 {
|
||||
Err(std::io::Error::last_os_error())
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
};
|
||||
#[cfg(not(windows))]
|
||||
let cleanup = {
|
||||
drop(file);
|
||||
tokio::fs::remove_file(&path).await
|
||||
};
|
||||
if let Err(cleanup) = cleanup {
|
||||
error = error.context(format!("failed to clean up {}: {cleanup}", path.display()));
|
||||
}
|
||||
}
|
||||
return Err(error)
|
||||
.with_context(|| format!("profile body was written to {file}, but the index was not updated"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(any(unix, all(windows, feature = "profile-store-windows")))]
|
||||
@@ -263,10 +330,13 @@ mod tests {
|
||||
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 mut profiles: super::super::IProfiles =
|
||||
serde_yaml_ng::from_str("items: [{uid: r, file: old.yaml}, {uid: s, type: script, file: s.js}]")?;
|
||||
profiles.get_item_mut("s")?.file_data = Some("template".into());
|
||||
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"));
|
||||
assert!(!root.join("profiles/s.js").exists());
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use super::{
|
||||
PrfItem, PrfOption, PrfSelected, patch_opt_field,
|
||||
prfitem::{DownloadedSubscription, build_profile, prepare_remote_refresh},
|
||||
prfitem::{DownloadedSubscription, build_profile},
|
||||
profile_storage,
|
||||
};
|
||||
use crate::core::notify::{Refresh, announce};
|
||||
@@ -310,7 +310,6 @@ pub(crate) async fn save_remote_refresh(
|
||||
url: String,
|
||||
file: Option<String>,
|
||||
downloaded: DownloadedSubscription,
|
||||
options: Option<PrfOption>,
|
||||
) -> Result<()> {
|
||||
let uid = uid.to_owned();
|
||||
// Dropping the caller must not separate an issued disk write from its Draft publication.
|
||||
@@ -318,30 +317,25 @@ pub(crate) async fn save_remote_refresh(
|
||||
let _profile_write = PROFILE_WRITE_LOCK.lock().await;
|
||||
anyhow::ensure!(!handle::Handle::global().is_exiting(), "application is exiting");
|
||||
let draft = Config::profiles().await;
|
||||
let snapshot = draft.data_arc();
|
||||
let source = snapshot.get_item(&uid)?;
|
||||
check_refresh_source(source, &url, file.as_ref())?;
|
||||
let name = source.name.clone();
|
||||
drop(snapshot);
|
||||
let refresh = prepare_remote_refresh(downloaded, options.as_ref()).await?;
|
||||
let mut name = None;
|
||||
let mut storage_guard = None;
|
||||
let mut persisted = false;
|
||||
let result = {
|
||||
let storage_guard = &mut storage_guard;
|
||||
let persisted = &mut persisted;
|
||||
let name = &mut name;
|
||||
draft
|
||||
.with_data_modify(|mut candidate| async move {
|
||||
*storage_guard = Some(profile_storage::write().await?);
|
||||
let profile = candidate.get_item_mut(&uid)?;
|
||||
check_refresh_source(profile, &url, file.as_ref())?;
|
||||
profile.extra = refresh.extra;
|
||||
profile.updated = Some(refresh.updated);
|
||||
profile.home = refresh.home;
|
||||
profile.option = PrfOption::merge(profile.option.as_ref(), Some(&refresh.option));
|
||||
*name = profile.name.clone();
|
||||
let (body, companions) = downloaded.apply(profile);
|
||||
profile
|
||||
.file
|
||||
.get_or_insert_with(|| format!("{}.yaml", help::get_uid("R")).into());
|
||||
let candidate = profile_storage::commit_refresh(uid, candidate, refresh.body).await?;
|
||||
candidate.items.get_or_insert_with(Vec::new).extend(companions);
|
||||
let candidate = profile_storage::commit_refresh(uid, candidate, body).await?;
|
||||
*persisted = true;
|
||||
Ok((candidate, ()))
|
||||
})
|
||||
|
||||
@@ -110,7 +110,7 @@ async fn perform_profile_update(uid: &str, source: RefreshSource, overrides: Opt
|
||||
.await;
|
||||
let (strategy, downloaded) = result.map_err(|err| anyhow::anyhow!(mask_err(&format!("{err:#}"))))?;
|
||||
// A persistence error must not replay a successful download with another transport.
|
||||
save_remote_refresh(uid, source.url, source.file, downloaded, options).await?;
|
||||
save_remote_refresh(uid, source.url, source.file, downloaded).await?;
|
||||
if !matches!(strategy, Strategy::Configured) {
|
||||
handle::Handle::notice(NoticeStatus::UpdateWithClashProxy, profile_name);
|
||||
}
|
||||
|
||||
@@ -278,7 +278,7 @@ export const HomeProfileCard = ({
|
||||
|
||||
setUpdating(true)
|
||||
try {
|
||||
if (!(await updateProfile(current, current.option ?? undefined))) return
|
||||
if (!(await updateProfile(current))) return
|
||||
onProfileUpdated?.()
|
||||
|
||||
// 刷新首页数据
|
||||
|
||||
Reference in New Issue
Block a user