mirror of
https://github.com/clash-verge-rev/clash-verge-rev.git
synced 2026-12-01 02:20:07 +08:00
refactor(runtime-bundle): extract runtime bundle planning
Plan provider destinations and assets in the crate. Adapt the plan to the Service wire format at the call site.
This commit is contained in:
Generated
+14
@@ -1097,6 +1097,7 @@ dependencies = [
|
||||
"clash-verge-limiter",
|
||||
"clash-verge-logging",
|
||||
"clash-verge-media-unlock",
|
||||
"clash-verge-runtime-bundle",
|
||||
"clash-verge-signal",
|
||||
"clash-verge-subscription",
|
||||
"clash-verge-task",
|
||||
@@ -1215,6 +1216,19 @@ dependencies = [
|
||||
"tokio",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "clash-verge-runtime-bundle"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"clash-verge-logging",
|
||||
"hex",
|
||||
"log",
|
||||
"serde_yaml_ng",
|
||||
"sha2 0.11.2",
|
||||
"thiserror 2.0.20",
|
||||
"tokio",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "clash-verge-signal"
|
||||
version = "0.1.0"
|
||||
|
||||
@@ -10,6 +10,7 @@ members = [
|
||||
"crates/clash-verge-i18n",
|
||||
"crates/clash-verge-limiter",
|
||||
"crates/clash-verge-subscription",
|
||||
"crates/clash-verge-runtime-bundle",
|
||||
]
|
||||
resolver = "2"
|
||||
|
||||
@@ -61,6 +62,8 @@ clash-verge-signal = { path = "crates/clash-verge-signal" }
|
||||
clash-verge-i18n = { path = "crates/clash-verge-i18n" }
|
||||
clash-verge-limiter = { path = "crates/clash-verge-limiter" }
|
||||
clash-verge-subscription = { path = "crates/clash-verge-subscription" }
|
||||
clash-verge-runtime-bundle = { path = "crates/clash-verge-runtime-bundle" }
|
||||
clash_verge_service_ipc = { git = "https://github.com/clash-verge-rev/clash-verge-service-ipc.git", branch = "main", version = "2.8.2", default-features = false }
|
||||
tracing-estuary = { git = "https://github.com/Tunglies/tracing-estuary.git", branch = "main" }
|
||||
tauri-plugin-clash-verge-sysinfo = { path = "crates/tauri-plugin-clash-verge-sysinfo" }
|
||||
tracing = "0.1.44"
|
||||
@@ -94,6 +97,7 @@ serde = { version = "1.0.229" }
|
||||
tristr = { git = "https://github.com/Tunglies/tristr", rev = "d849e5cff47a570849c2e1bada0a2b6481cf3378", default-features = false, features = ["serde", "specta"] }
|
||||
serde_json = { version = "1.0.154" }
|
||||
serde_yaml_ng = { version = "0.10.0" }
|
||||
sha2 = "0.11.2"
|
||||
socket2 = "0.6.5"
|
||||
|
||||
# *** For Windows platform only ***
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
[package]
|
||||
name = "clash-verge-runtime-bundle"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
thiserror = { workspace = true }
|
||||
clash-verge-logging = { workspace = true }
|
||||
hex = "0.4.3"
|
||||
log = { workspace = true }
|
||||
serde_yaml_ng = { workspace = true }
|
||||
sha2 = { workspace = true }
|
||||
tokio = { workspace = true, features = ["fs"] }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,45 @@
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum RuntimeBundleError {
|
||||
#[error(transparent)]
|
||||
Io(#[from] std::io::Error),
|
||||
#[error("failed to read runtime config {path:?}")]
|
||||
ReadConfig {
|
||||
path: PathBuf,
|
||||
#[source]
|
||||
source: std::io::Error,
|
||||
},
|
||||
#[error("failed to parse runtime config {path:?}")]
|
||||
ParseConfig {
|
||||
path: PathBuf,
|
||||
#[source]
|
||||
source: serde_yaml_ng::Error,
|
||||
},
|
||||
#[error("runtime config has no parent directory")]
|
||||
MissingConfigDirectory,
|
||||
#[error("failed to serialize service runtime config")]
|
||||
SerializeConfig(#[source] serde_yaml_ng::Error),
|
||||
#[error("runtime provider destination {0:?} is declared for two different sources")]
|
||||
DifferentSources(String),
|
||||
#[error("runtime provider destination {0:?} is claimed more than once")]
|
||||
DuplicateDestination(String),
|
||||
#[error("local runtime provider is unavailable: {path:?}")]
|
||||
LocalProviderUnavailable {
|
||||
path: PathBuf,
|
||||
#[source]
|
||||
source: std::io::Error,
|
||||
},
|
||||
#[error("local runtime provider is outside the config root: {0:?}")]
|
||||
LocalProviderOutsideRoot(PathBuf),
|
||||
#[error("runtime provider destination traverses outside the runtime")]
|
||||
DestinationOutsideRuntime,
|
||||
#[error("runtime provider path has no existing ancestor: {0:?}")]
|
||||
MissingAncestor(PathBuf),
|
||||
#[error("runtime provider path is outside the config root: {0:?}")]
|
||||
ProviderOutsideRoot(PathBuf),
|
||||
#[error("local runtime provider destination traverses outside the runtime")]
|
||||
LocalDestinationOutsideRuntime,
|
||||
#[error("local runtime provider destination is empty")]
|
||||
EmptyDestination,
|
||||
}
|
||||
+88
-83
@@ -1,12 +1,14 @@
|
||||
use anyhow::{Context as _, Result, bail};
|
||||
mod error;
|
||||
|
||||
pub use error::RuntimeBundleError;
|
||||
|
||||
use clash_verge_logging::{Type, logging};
|
||||
use clash_verge_service_ipc::{RemoteProvider, RuntimeAsset, RuntimeBundle};
|
||||
use serde_yaml_ng::{Mapping, Value};
|
||||
use sha2::{Digest as _, Sha256};
|
||||
use std::collections::{BTreeMap, HashSet};
|
||||
use std::path::{Component, Path, PathBuf, Prefix};
|
||||
|
||||
pub(crate) const GEO_ASSETS: &[&str] = &[
|
||||
pub const GEO_ASSETS: &[&str] = &[
|
||||
"Country.mmdb",
|
||||
"ASN.mmdb",
|
||||
"geoip.dat",
|
||||
@@ -17,10 +19,22 @@ pub(crate) const GEO_ASSETS: &[&str] = &[
|
||||
|
||||
/// Provider identity used by the runtime config and core API.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub(crate) struct RemoteProviderRef {
|
||||
pub struct RemoteProviderRef {
|
||||
pub section: &'static str,
|
||||
pub name: String,
|
||||
pub provider: RemoteProvider,
|
||||
pub destination: String,
|
||||
pub url: String,
|
||||
}
|
||||
|
||||
pub struct RuntimeAsset {
|
||||
pub source: String,
|
||||
pub destination: String,
|
||||
}
|
||||
|
||||
pub struct RuntimeBundlePlan {
|
||||
pub yaml: String,
|
||||
pub assets: Vec<RuntimeAsset>,
|
||||
pub remote_providers: Vec<RemoteProviderRef>,
|
||||
}
|
||||
|
||||
struct RuntimeParts {
|
||||
@@ -29,29 +43,29 @@ struct RuntimeParts {
|
||||
remote_providers: Vec<RemoteProviderRef>,
|
||||
}
|
||||
|
||||
pub(crate) async fn collect_runtime_bundle(config_file: &Path, core_path: &Path) -> Result<RuntimeBundle> {
|
||||
type Result<T> = std::result::Result<T, RuntimeBundleError>;
|
||||
|
||||
pub async fn collect_runtime_bundle(config_file: &Path) -> Result<RuntimeBundlePlan> {
|
||||
let yaml = tokio::fs::read_to_string(config_file)
|
||||
.await
|
||||
.with_context(|| format!("failed to read runtime config {config_file:?}"))?;
|
||||
let config: Value =
|
||||
serde_yaml_ng::from_str(&yaml).with_context(|| format!("failed to parse runtime config {config_file:?}"))?;
|
||||
let config_root = config_file
|
||||
.parent()
|
||||
.ok_or_else(|| anyhow::anyhow!("runtime config has no parent directory"))?;
|
||||
.map_err(|source| RuntimeBundleError::ReadConfig {
|
||||
path: config_file.to_owned(),
|
||||
source,
|
||||
})?;
|
||||
let config: Value = serde_yaml_ng::from_str(&yaml).map_err(|source| RuntimeBundleError::ParseConfig {
|
||||
path: config_file.to_owned(),
|
||||
source,
|
||||
})?;
|
||||
let config_root = config_file.parent().ok_or(RuntimeBundleError::MissingConfigDirectory)?;
|
||||
let parts = collect_runtime_parts(config, config_root)?;
|
||||
Ok(RuntimeBundle {
|
||||
yaml: serde_yaml_ng::to_string(&parts.config).context("failed to serialize service runtime config")?,
|
||||
Ok(RuntimeBundlePlan {
|
||||
yaml: serde_yaml_ng::to_string(&parts.config).map_err(RuntimeBundleError::SerializeConfig)?,
|
||||
assets: parts.assets,
|
||||
remote_providers: parts
|
||||
.remote_providers
|
||||
.into_iter()
|
||||
.map(|declared| declared.provider)
|
||||
.collect(),
|
||||
core_path: core_path.to_string_lossy().into_owned(),
|
||||
remote_providers: parts.remote_providers,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn remote_providers_of(config: &Mapping, config_root: &Path) -> Result<Vec<RemoteProviderRef>> {
|
||||
pub fn remote_providers_of(config: &Mapping, config_root: &Path) -> Result<Vec<RemoteProviderRef>> {
|
||||
Ok(collect_runtime_parts(Value::Mapping(config.clone()), config_root)?.remote_providers)
|
||||
}
|
||||
|
||||
@@ -61,7 +75,7 @@ struct ProviderPathOwners {
|
||||
local: bool,
|
||||
}
|
||||
|
||||
pub(crate) fn resolve_provider_path_conflicts(config: &mut Mapping, config_root: &Path) -> Result<()> {
|
||||
pub fn resolve_provider_path_conflicts(config: &mut Mapping, config_root: &Path) -> Result<()> {
|
||||
let config_root = std::fs::canonicalize(config_root)?;
|
||||
let mut paths = BTreeMap::<String, ProviderPathOwners>::new();
|
||||
let mut reserved: HashSet<String> = GEO_ASSETS.iter().map(|name| (*name).to_owned()).collect();
|
||||
@@ -122,7 +136,7 @@ fn allocate_provider_destination(destination: &str, url: &str, reserved: &mut Ha
|
||||
digest.update(destination.as_bytes());
|
||||
digest.update([0]);
|
||||
digest.update(url.as_bytes());
|
||||
let digest: String = crate::utils::help::hex_encode(&digest.finalize());
|
||||
let digest = hex::encode(digest.finalize());
|
||||
let path = Path::new(destination);
|
||||
let extension = path
|
||||
.extension()
|
||||
@@ -214,26 +228,21 @@ fn collect_provider_assets(
|
||||
(true, Some(url)) => {
|
||||
let destination = provider_destination(config_root, raw_path)?;
|
||||
// Reserve remote destinations too; copied and downloaded files must not collide.
|
||||
match remote_providers
|
||||
.iter()
|
||||
.find(|declared| declared.provider.destination == destination)
|
||||
{
|
||||
Some(declared) if declared.provider.url == url => {}
|
||||
Some(_) => {
|
||||
bail!("runtime provider destination {destination:?} is declared for two different sources")
|
||||
}
|
||||
None => {
|
||||
if !destinations.insert(destination.clone()) {
|
||||
bail!("runtime provider destination {destination:?} is claimed more than once");
|
||||
}
|
||||
remote_providers.push(RemoteProviderRef {
|
||||
section,
|
||||
name: name.as_str().unwrap_or_default().to_owned(),
|
||||
provider: RemoteProvider {
|
||||
destination: destination.clone(),
|
||||
url,
|
||||
},
|
||||
});
|
||||
if destinations.insert(destination.clone()) {
|
||||
remote_providers.push(RemoteProviderRef {
|
||||
section,
|
||||
name: name.as_str().unwrap_or_default().to_owned(),
|
||||
destination: destination.clone(),
|
||||
url,
|
||||
});
|
||||
} else {
|
||||
match remote_providers
|
||||
.iter()
|
||||
.find(|declared| declared.destination == destination)
|
||||
{
|
||||
Some(declared) if declared.url == url => {}
|
||||
Some(_) => return Err(RuntimeBundleError::DifferentSources(destination)),
|
||||
None => return Err(RuntimeBundleError::DuplicateDestination(destination)),
|
||||
}
|
||||
}
|
||||
destination
|
||||
@@ -347,10 +356,13 @@ fn local_provider_source(config_root: &Path, raw_path: &str) -> Result<PathBuf>
|
||||
config_root.join(path)
|
||||
};
|
||||
let canonical_source =
|
||||
std::fs::canonicalize(&source).with_context(|| format!("local runtime provider is unavailable: {source:?}"))?;
|
||||
std::fs::canonicalize(&source).map_err(|error| RuntimeBundleError::LocalProviderUnavailable {
|
||||
path: source,
|
||||
source: error,
|
||||
})?;
|
||||
canonical_source
|
||||
.strip_prefix(config_root)
|
||||
.map_err(|_| anyhow::anyhow!("local runtime provider is outside the config root: {canonical_source:?}"))?;
|
||||
.map_err(|_| RuntimeBundleError::LocalProviderOutsideRoot(canonical_source.clone()))?;
|
||||
Ok(canonical_source)
|
||||
}
|
||||
|
||||
@@ -360,7 +372,7 @@ fn provider_destination(config_root: &Path, raw_path: &str) -> Result<String> {
|
||||
.components()
|
||||
.any(|component| matches!(component, Component::ParentDir))
|
||||
{
|
||||
bail!("runtime provider destination traverses outside the runtime");
|
||||
return Err(RuntimeBundleError::DestinationOutsideRuntime);
|
||||
}
|
||||
if path.is_absolute() {
|
||||
let normalized = canonicalize_with_missing_tail(path)?;
|
||||
@@ -376,11 +388,11 @@ fn canonicalize_with_missing_tail(path: &Path) -> Result<PathBuf> {
|
||||
while !ancestor.exists() {
|
||||
let name = ancestor
|
||||
.file_name()
|
||||
.ok_or_else(|| anyhow::anyhow!("runtime provider path has no existing ancestor: {path:?}"))?;
|
||||
.ok_or_else(|| RuntimeBundleError::MissingAncestor(path.to_owned()))?;
|
||||
tail.push(name.to_owned());
|
||||
ancestor = ancestor
|
||||
.parent()
|
||||
.ok_or_else(|| anyhow::anyhow!("runtime provider path has no existing ancestor: {path:?}"))?;
|
||||
.ok_or_else(|| RuntimeBundleError::MissingAncestor(path.to_owned()))?;
|
||||
}
|
||||
let mut normalized = std::fs::canonicalize(ancestor)?;
|
||||
for component in tail.iter().rev() {
|
||||
@@ -392,7 +404,7 @@ fn canonicalize_with_missing_tail(path: &Path) -> Result<PathBuf> {
|
||||
fn destination_below_root(config_root: &Path, path: &Path) -> Result<String> {
|
||||
let relative = path
|
||||
.strip_prefix(config_root)
|
||||
.map_err(|_| anyhow::anyhow!("runtime provider path is outside the config root: {path:?}"))?;
|
||||
.map_err(|_| RuntimeBundleError::ProviderOutsideRoot(path.to_owned()))?;
|
||||
normalized_destination(relative)
|
||||
}
|
||||
|
||||
@@ -402,11 +414,11 @@ fn normalized_destination(relative: &Path) -> Result<String> {
|
||||
match component {
|
||||
Component::Normal(component) => destination.push(component),
|
||||
Component::CurDir => {}
|
||||
_ => bail!("local runtime provider destination traverses outside the runtime"),
|
||||
_ => return Err(RuntimeBundleError::LocalDestinationOutsideRuntime),
|
||||
}
|
||||
}
|
||||
if destination.as_os_str().is_empty() {
|
||||
bail!("local runtime provider destination is empty");
|
||||
return Err(RuntimeBundleError::EmptyDestination);
|
||||
}
|
||||
Ok(destination.to_string_lossy().replace('\\', "/"))
|
||||
}
|
||||
@@ -416,7 +428,8 @@ mod tests {
|
||||
use super::{collect_runtime_bundle, remote_providers_of, resolve_provider_path_conflicts};
|
||||
|
||||
#[tokio::test]
|
||||
async fn conflicting_sources_get_separate_paths_in_config_bundle_and_readback() -> anyhow::Result<()> {
|
||||
async fn conflicting_sources_get_separate_paths_in_config_bundle_and_readback()
|
||||
-> std::result::Result<(), Box<dyn std::error::Error>> {
|
||||
let root = std::env::temp_dir().join(format!("clash-verge-provider-paths-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&root)?;
|
||||
let mut config: serde_yaml_ng::Mapping = serde_yaml_ng::from_str(
|
||||
@@ -433,7 +446,7 @@ mod tests {
|
||||
resolve_provider_path_conflicts(&mut config, &root)?;
|
||||
let config_file = root.join("config.yaml");
|
||||
std::fs::write(&config_file, serde_yaml_ng::to_string(&config)?)?;
|
||||
let bundle = collect_runtime_bundle(&config_file, &root.join("mihomo")).await?;
|
||||
let bundle = collect_runtime_bundle(&config_file).await?;
|
||||
let paths = &config["rule-providers"];
|
||||
assert_ne!(paths["AppleDev"]["path"], paths["mirror"]["path"]);
|
||||
resolve_provider_path_conflicts(&mut reordered, &root)?;
|
||||
@@ -452,11 +465,8 @@ mod tests {
|
||||
let readback = remote_providers_of(&config, &root)?;
|
||||
assert_eq!(bundle.remote_providers.len(), 2);
|
||||
for declared in readback {
|
||||
assert!(bundle.remote_providers.contains(&declared.provider));
|
||||
assert_eq!(
|
||||
config[declared.section][&declared.name]["path"],
|
||||
declared.provider.destination
|
||||
);
|
||||
assert!(bundle.remote_providers.contains(&declared));
|
||||
assert_eq!(config[declared.section][&declared.name]["path"], declared.destination);
|
||||
assert_eq!(
|
||||
config[declared.section][&declared.name]["url"],
|
||||
original[declared.section][&declared.name]["url"]
|
||||
@@ -467,7 +477,8 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn allocated_provider_paths_do_not_claim_another_declared_path() -> anyhow::Result<()> {
|
||||
fn allocated_provider_paths_do_not_claim_another_declared_path()
|
||||
-> std::result::Result<(), Box<dyn std::error::Error>> {
|
||||
let root = std::env::temp_dir();
|
||||
let original: serde_yaml_ng::Mapping = serde_yaml_ng::from_str(
|
||||
"proxy-providers:\n a:\n type: http\n url: https://one.example/p.yaml\n path: ./providers/shared.yaml\nrule-providers:\n b:\n type: http\n url: https://two.example/r.yaml\n path: ./providers/shared.yaml\n",
|
||||
@@ -489,7 +500,8 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn provider_path_resolution_leaves_shared_sources_and_local_files_unchanged() -> anyhow::Result<()> {
|
||||
fn provider_path_resolution_leaves_shared_sources_and_local_files_unchanged()
|
||||
-> std::result::Result<(), Box<dyn std::error::Error>> {
|
||||
let mut config: serde_yaml_ng::Mapping = serde_yaml_ng::from_str(
|
||||
"rule-providers:\n a:\n type: http\n url: https://one.example/r.yaml\n path: ./rules/shared.yaml\n b:\n type: http\n url: https://one.example/r.yaml\n path: ./rules/shared.yaml\n local:\n type: file\n path: ./rules/local.yaml\n remote:\n type: http\n url: https://two.example/r.yaml\n path: ./rules/local.yaml\n mirror:\n type: http\n url: https://three.example/r.yaml\n path: ./rules/local.yaml\n",
|
||||
)?;
|
||||
@@ -500,7 +512,8 @@ mod tests {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn collects_only_local_providers_and_existing_geo_assets() -> anyhow::Result<()> {
|
||||
async fn collects_only_local_providers_and_existing_geo_assets()
|
||||
-> std::result::Result<(), Box<dyn std::error::Error>> {
|
||||
let root = std::env::temp_dir().join(format!("clash-verge-runtime-bundle-{}", std::process::id()));
|
||||
std::fs::create_dir_all(root.join("providers"))?;
|
||||
std::fs::write(root.join("providers/local.yaml"), b"proxies: []\n")?;
|
||||
@@ -516,10 +529,8 @@ mod tests {
|
||||
absolute_remote.display()
|
||||
),
|
||||
)?;
|
||||
let core = root.join("mihomo");
|
||||
std::fs::write(&core, b"core")?;
|
||||
|
||||
let bundle = collect_runtime_bundle(&config, &core).await?;
|
||||
let bundle = collect_runtime_bundle(&config).await?;
|
||||
|
||||
let bundled_config: serde_yaml_ng::Value = serde_yaml_ng::from_str(&bundle.yaml)?;
|
||||
assert_eq!(
|
||||
@@ -560,7 +571,8 @@ mod tests {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn two_names_for_one_remote_file_are_folded_rather_than_refused() -> anyhow::Result<()> {
|
||||
async fn two_names_for_one_remote_file_are_folded_rather_than_refused()
|
||||
-> std::result::Result<(), Box<dyn std::error::Error>> {
|
||||
// Identical repeats are one service-side file and are safe to fold.
|
||||
let root = std::env::temp_dir().join(format!("clash-verge-bundle-dup-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
@@ -570,10 +582,8 @@ mod tests {
|
||||
&config,
|
||||
"rule-providers:\n a:\n type: http\n url: https://one.example/x.yaml\n path: ./rules/x.yaml\n b:\n type: http\n url: https://one.example/x.yaml\n path: ./rules/x.yaml\n",
|
||||
)?;
|
||||
let core = root.join("mihomo");
|
||||
std::fs::write(&core, b"core")?;
|
||||
|
||||
let bundle = collect_runtime_bundle(&config, &core).await?;
|
||||
let bundle = collect_runtime_bundle(&config).await?;
|
||||
|
||||
assert_eq!(bundle.remote_providers.len(), 1, "one file, declared twice");
|
||||
assert_eq!(bundle.remote_providers[0].destination, "rules/x.yaml");
|
||||
@@ -582,7 +592,7 @@ mod tests {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn two_sources_for_one_remote_file_are_refused() -> anyhow::Result<()> {
|
||||
async fn two_sources_for_one_remote_file_are_refused() -> std::result::Result<(), Box<dyn std::error::Error>> {
|
||||
let root = std::env::temp_dir().join(format!("clash-verge-bundle-conflict-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
std::fs::create_dir_all(&root)?;
|
||||
@@ -591,11 +601,9 @@ mod tests {
|
||||
&config,
|
||||
"rule-providers:\n a:\n type: http\n url: https://one.example/x.yaml\n path: ./rules/x.yaml\n b:\n type: http\n url: https://two.example/x.yaml\n path: ./rules/x.yaml\n",
|
||||
)?;
|
||||
let core = root.join("mihomo");
|
||||
std::fs::write(&core, b"core")?;
|
||||
|
||||
let Err(error) = collect_runtime_bundle(&config, &core).await else {
|
||||
anyhow::bail!("two sources cannot own one file");
|
||||
let Err(error) = collect_runtime_bundle(&config).await else {
|
||||
return Err("two sources cannot own one file".into());
|
||||
};
|
||||
|
||||
assert!(error.to_string().contains("two different sources"), "{error}");
|
||||
@@ -604,7 +612,8 @@ mod tests {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_odd_provider_is_left_alone_instead_of_failing_the_whole_bundle() -> anyhow::Result<()> {
|
||||
async fn an_odd_provider_is_left_alone_instead_of_failing_the_whole_bundle()
|
||||
-> std::result::Result<(), Box<dyn std::error::Error>> {
|
||||
// Odd providers accepted by mihomo must not block the rest of the bundle.
|
||||
let root = std::env::temp_dir().join(format!("clash-verge-bundle-odd-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
@@ -614,10 +623,8 @@ mod tests {
|
||||
&config,
|
||||
"rule-providers:\n nourl:\n type: http\n path: ./rules/nourl.yaml\n missing:\n type: inline\n url: https://one.example/i.yaml\n path: ./rules/missing.yaml\n good:\n type: http\n url: https://one.example/g.yaml\n path: ./rules/g.yaml\n",
|
||||
)?;
|
||||
let core = root.join("mihomo");
|
||||
std::fs::write(&core, b"core")?;
|
||||
|
||||
let bundle = collect_runtime_bundle(&config, &core).await?;
|
||||
let bundle = collect_runtime_bundle(&config).await?;
|
||||
|
||||
assert_eq!(
|
||||
bundle.remote_providers.len(),
|
||||
@@ -636,13 +643,13 @@ mod tests {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rejects_provider_paths_outside_the_config_root() -> anyhow::Result<()> {
|
||||
async fn rejects_provider_paths_outside_the_config_root() -> std::result::Result<(), Box<dyn std::error::Error>> {
|
||||
let root = std::env::temp_dir().join(format!("clash-verge-runtime-bundle-outside-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&root)?;
|
||||
let config = root.join("config.yaml");
|
||||
let outside = root
|
||||
.parent()
|
||||
.ok_or_else(|| anyhow::anyhow!("test root has no parent"))?
|
||||
.ok_or("test root has no parent")?
|
||||
.join(format!("outside-{}.yaml", std::process::id()));
|
||||
std::fs::write(
|
||||
&config,
|
||||
@@ -651,11 +658,9 @@ mod tests {
|
||||
outside.display()
|
||||
),
|
||||
)?;
|
||||
let core = root.join("mihomo");
|
||||
std::fs::write(&core, b"core")?;
|
||||
|
||||
let Err(error) = collect_runtime_bundle(&config, &core).await else {
|
||||
anyhow::bail!("outside provider path must be rejected");
|
||||
let Err(error) = collect_runtime_bundle(&config).await else {
|
||||
return Err("outside provider path must be rejected".into());
|
||||
};
|
||||
|
||||
assert!(error.to_string().contains("outside the config root"));
|
||||
@@ -37,6 +37,7 @@ clash-verge-logging = { workspace = true }
|
||||
clash-verge-i18n = { workspace = true }
|
||||
clash-verge-limiter = { workspace = true }
|
||||
clash-verge-subscription = { workspace = true }
|
||||
clash-verge-runtime-bundle = { workspace = true }
|
||||
tauri-plugin-clash-verge-sysinfo = { workspace = true }
|
||||
tauri-plugin-clipboard-manager = { workspace = true }
|
||||
tauri = { workspace = true, features = [
|
||||
@@ -82,7 +83,7 @@ flate2 = "1.1.11"
|
||||
reqwest_dav = "0.4.0"
|
||||
aes-gcm = { version = "0.11.1" }
|
||||
base64 = "0.23.1"
|
||||
sha2 = "0.11.2"
|
||||
sha2 = { workspace = true }
|
||||
getrandom = "0.4.3"
|
||||
futures = { workspace = true }
|
||||
gethostname = "1.1.0"
|
||||
@@ -93,9 +94,7 @@ tracing = { workspace = true }
|
||||
tauri-plugin-devtools = { version = "2.2.3", optional = true }
|
||||
tauri-plugin-mihomo = { git = "https://github.com/clash-verge-rev/tauri-plugin-mihomo", rev = "7e4fa8642cf6c394ed88b5a969420d8eab60087f" }
|
||||
async-trait = "0.1.92"
|
||||
clash_verge_service_ipc = { git = "https://github.com/clash-verge-rev/clash-verge-service-ipc.git", branch = "main", version = "2.8.2", features = [
|
||||
"client",
|
||||
] }
|
||||
clash_verge_service_ipc = { workspace = true, features = ["client"] }
|
||||
arc-swap = "1.9.5"
|
||||
tokio-rustls = "0.26.6"
|
||||
rustls = { version = "0.23.46", features = ["ring"] }
|
||||
|
||||
@@ -7,7 +7,6 @@ use crate::{
|
||||
CoreManager,
|
||||
handle::{self, Handle},
|
||||
listener::MIXED_PORT_KEY,
|
||||
runtime_bundle::resolve_provider_path_conflicts,
|
||||
tray,
|
||||
validate::CoreConfigValidator,
|
||||
},
|
||||
@@ -19,6 +18,7 @@ use anyhow::{Result, anyhow};
|
||||
use backon::{ExponentialBuilder, Retryable as _};
|
||||
use clash_verge_draft::Draft;
|
||||
use clash_verge_logging::{Type, logging, logging_error};
|
||||
use clash_verge_runtime_bundle::resolve_provider_path_conflicts;
|
||||
use serde_yaml_ng::{Mapping, Value};
|
||||
use std::{collections::HashSet, path::PathBuf};
|
||||
use tokio::sync::{Mutex, MutexGuard, OnceCell};
|
||||
|
||||
@@ -13,7 +13,6 @@ pub(crate) mod owner_identity;
|
||||
pub mod proxy_control;
|
||||
pub mod proxy_view;
|
||||
pub mod runstate;
|
||||
pub(crate) mod runtime_bundle;
|
||||
pub mod service;
|
||||
pub mod sysopt;
|
||||
pub mod timer;
|
||||
|
||||
@@ -13,7 +13,6 @@ use crate::{
|
||||
CORE_REJECTED_PREFIX, OwnerRecoveryReason, OwnerSample, OwnerStep, OwnerWatch, PendingAction, RUN_STATE,
|
||||
ReadyWaitError, RunState, RunStateEnv, RunStateStore, ServiceHealth,
|
||||
},
|
||||
runtime_bundle::{GEO_ASSETS, RemoteProviderRef, collect_runtime_bundle, remote_providers_of},
|
||||
tray::Tray,
|
||||
},
|
||||
process::AsyncHandler,
|
||||
@@ -21,10 +20,11 @@ use crate::{
|
||||
use anyhow::{Context as _, Result, anyhow, bail};
|
||||
use clash_verge_draft::Draft;
|
||||
use clash_verge_logging::{Type, logging};
|
||||
use clash_verge_runtime_bundle::{GEO_ASSETS, RemoteProviderRef, collect_runtime_bundle, remote_providers_of};
|
||||
use clash_verge_service_ipc::{
|
||||
MacosProxyConfig, OwnerCredentials, OwnerIdentity, OwnerSessionProof, ProtocolInfo, ProxyApplyOutcome,
|
||||
RuntimeBundle, RuntimeFileOutcome, RuntimeFileRequest, ServiceErrorCode, ServiceStatusSnapshot,
|
||||
StageRuntimeOutcome, StartClashRequest, WriterConfig,
|
||||
RemoteProvider, RuntimeAsset, RuntimeBundle, RuntimeFileOutcome, RuntimeFileRequest, ServiceErrorCode,
|
||||
ServiceStatusSnapshot, StageRuntimeOutcome, StartClashRequest, WriterConfig,
|
||||
};
|
||||
use clash_verge_task::scheduled_task::{self, Mailbox, Next, ScheduledTask};
|
||||
use clash_verge_task::watch_task;
|
||||
@@ -611,7 +611,27 @@ async fn collect_service_runtime_bundle(config_file: &Path) -> Result<RuntimeBun
|
||||
|
||||
let bin_ext = if cfg!(windows) { ".exe" } else { "" };
|
||||
let bin_path = service_core_path(&clash_core, bin_ext)?;
|
||||
collect_runtime_bundle(config_file, &bin_path).await
|
||||
let plan = collect_runtime_bundle(config_file).await?;
|
||||
Ok(RuntimeBundle {
|
||||
yaml: plan.yaml,
|
||||
assets: plan
|
||||
.assets
|
||||
.into_iter()
|
||||
.map(|asset| RuntimeAsset {
|
||||
source: asset.source,
|
||||
destination: asset.destination,
|
||||
})
|
||||
.collect(),
|
||||
remote_providers: plan
|
||||
.remote_providers
|
||||
.into_iter()
|
||||
.map(|provider| RemoteProvider {
|
||||
destination: provider.destination,
|
||||
url: provider.url,
|
||||
})
|
||||
.collect(),
|
||||
core_path: bin_path.to_string_lossy().into_owned(),
|
||||
})
|
||||
}
|
||||
|
||||
/// A staging response whose refusal code tells callers whether a fresh start can help.
|
||||
@@ -948,7 +968,7 @@ async fn sync_runtime_providers_by_service() -> Result<ProviderSync> {
|
||||
let loaded_before = provider_load_times().await;
|
||||
let mut fetched = Vec::new();
|
||||
for declared in applied_remote_providers(&runtime, &app_dir)? {
|
||||
let (temp, file) = match create_sync_temp(&app_dir.join(&declared.provider.destination)).await {
|
||||
let (temp, file) = match create_sync_temp(&app_dir.join(&declared.destination)).await {
|
||||
Ok(created) => created,
|
||||
Err(error) => {
|
||||
logging!(warn, Type::Service, "{error:#}");
|
||||
@@ -956,7 +976,7 @@ async fn sync_runtime_providers_by_service() -> Result<ProviderSync> {
|
||||
continue;
|
||||
}
|
||||
};
|
||||
match fetch_runtime_file(&credentials, &session, &declared.provider.destination, file).await {
|
||||
match fetch_runtime_file(&credentials, &session, &declared.destination, file).await {
|
||||
Ok(Fetch::Complete { len, mtime_ns }) => fetched.push(FetchedCache {
|
||||
declared,
|
||||
temp,
|
||||
@@ -977,7 +997,7 @@ async fn sync_runtime_providers_by_service() -> Result<ProviderSync> {
|
||||
warn,
|
||||
Type::Service,
|
||||
"failed to read provider cache {} into {}: {error:#}",
|
||||
declared.provider.destination,
|
||||
declared.destination,
|
||||
temp.display()
|
||||
);
|
||||
outcome.pending += 1;
|
||||
@@ -1088,7 +1108,7 @@ async fn sync_runtime_geo(
|
||||
fn applied_remote_providers(runtime: &Draft<IRuntime>, app_dir: &Path) -> Result<Vec<RemoteProviderRef>> {
|
||||
let applied = runtime.data_arc();
|
||||
match applied.config.as_ref() {
|
||||
Some(config) => remote_providers_of(config, app_dir),
|
||||
Some(config) => remote_providers_of(config, app_dir).map_err(Into::into),
|
||||
None => Ok(Vec::new()),
|
||||
}
|
||||
}
|
||||
@@ -1117,7 +1137,7 @@ async fn publish_fetched(
|
||||
};
|
||||
let mut synced = 0;
|
||||
for cache in fetched {
|
||||
let target = app_dir.join(&cache.declared.provider.destination);
|
||||
let target = app_dir.join(&cache.declared.destination);
|
||||
if !declared.contains(&cache.declared) || same_contents(&cache.temp, &target).await {
|
||||
remove_temp(&cache.temp).await;
|
||||
continue;
|
||||
@@ -1194,7 +1214,7 @@ async fn recheck_identity(
|
||||
cache: &FetchedCache,
|
||||
) -> Result<Fetch> {
|
||||
let request = RuntimeFileRequest {
|
||||
destination: cache.declared.provider.destination.to_owned(),
|
||||
destination: cache.declared.destination.to_owned(),
|
||||
offset: cache.len,
|
||||
};
|
||||
Ok(match read_chunk(credentials, session, &request).await? {
|
||||
|
||||
@@ -31,7 +31,7 @@ async fn validation_fingerprint(yaml: &str) -> u64 {
|
||||
.map(|exe| exe.with_file_name(format!("{}{}", core.as_str(), std::env::consts::EXE_SUFFIX)));
|
||||
// The test run reads geo databases from the app dir; a geo update must revalidate.
|
||||
let geo = dirs::app_home_dir().into_iter().flat_map(|dir| {
|
||||
super::runtime_bundle::GEO_ASSETS
|
||||
clash_verge_runtime_bundle::GEO_ASSETS
|
||||
.iter()
|
||||
.map(move |asset| dir.join(asset))
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user