mirror of
https://github.com/clash-verge-rev/clash-verge-rev.git
synced 2026-12-05 05:50:04 +08:00
fix(profile): commit missing companions with the refreshed subscription
This commit is contained in:
@@ -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(())
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user