mirror of
https://github.com/clash-verge-rev/clash-verge-rev.git
synced 2026-12-04 21:30:06 +08:00
refactor(service): use the negotiated protocol for active sessions
This commit is contained in:
@@ -88,8 +88,8 @@ fn plan_config_application(attempt: &StageAttempt) -> ConfigApplication {
|
||||
}
|
||||
}
|
||||
|
||||
async fn ask_to_stage(path: &std::path::Path) -> StageAttempt {
|
||||
match crate::core::service::stage_runtime_by_service(path).await {
|
||||
async fn ask_to_stage(path: &std::path::Path, session: &clash_verge_service_ipc::OwnerSessionProof) -> StageAttempt {
|
||||
match crate::core::service::stage_runtime_by_service(path, session).await {
|
||||
Ok(StageRequest::Answered(outcome)) => StageAttempt::Answered(outcome),
|
||||
Ok(StageRequest::Refused { code, message }) => {
|
||||
let message = message.into();
|
||||
@@ -433,10 +433,10 @@ impl CoreManager {
|
||||
}
|
||||
|
||||
async fn attempt_staging(&self, path: &std::path::Path) -> StageAttempt {
|
||||
if !crate::core::service::active_service_supports_runtime_staging() {
|
||||
let Ok(session) = crate::core::service::active_service_session() else {
|
||||
return StageAttempt::Unsupported;
|
||||
}
|
||||
stage_with_confirmation(timing::STAGE_CONFIRM_TIMEOUT, || ask_to_stage(path)).await
|
||||
};
|
||||
stage_with_confirmation(timing::STAGE_CONFIRM_TIMEOUT, || ask_to_stage(path, &session)).await
|
||||
}
|
||||
|
||||
/// Reload the Core from `path`, and replace the Core if it will not take it.
|
||||
|
||||
+18
-116
@@ -22,9 +22,9 @@ 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,
|
||||
RemoteProvider, RuntimeAsset, RuntimeBundle, RuntimeFileOutcome, RuntimeFileRequest, ServiceErrorCode,
|
||||
ServiceStatusSnapshot, StageRuntimeOutcome, StartClashRequest, WriterConfig,
|
||||
MacosProxyConfig, OwnerCredentials, OwnerIdentity, OwnerSessionProof, ProxyApplyOutcome, 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;
|
||||
@@ -45,7 +45,7 @@ use tokio::{sync::watch, time::Instant};
|
||||
|
||||
static OWNER_MONITOR_GENERATION: AtomicU64 = AtomicU64::new(0);
|
||||
static PENDING_SERVICE_START: Mutex<Option<PendingServiceStart>> = Mutex::new(None);
|
||||
static ACTIVE_SERVICE_SESSION: Mutex<Option<ActiveServiceSession>> = Mutex::new(None);
|
||||
static ACTIVE_SERVICE_SESSION: Mutex<Option<Arc<OwnerSessionProof>>> = Mutex::new(None);
|
||||
static PENDING_SERVICE_REPAIR_NOTICE: AtomicBool = AtomicBool::new(false);
|
||||
static PENDING_SERVICE_OWNER_NOTICE: Mutex<Option<String>> = Mutex::new(None);
|
||||
|
||||
@@ -99,16 +99,6 @@ impl PendingServiceStart {
|
||||
}
|
||||
}
|
||||
|
||||
/// Capabilities of the service session that owns the running Core.
|
||||
/// They are discarded with that session rather than cached across service upgrades.
|
||||
#[derive(Clone)]
|
||||
struct ActiveServiceSession {
|
||||
proof: Arc<OwnerSessionProof>,
|
||||
supports_runtime_staging: bool,
|
||||
supports_runtime_file_read: bool,
|
||||
supports_runtime_geo_read: bool,
|
||||
}
|
||||
|
||||
fn generate_service_session_token() -> Result<String> {
|
||||
use std::fmt::Write as _;
|
||||
|
||||
@@ -124,89 +114,14 @@ fn generate_service_session_token() -> Result<String> {
|
||||
pub(crate) fn active_service_session() -> Result<Arc<OwnerSessionProof>> {
|
||||
ACTIVE_SERVICE_SESSION
|
||||
.lock()
|
||||
.as_ref()
|
||||
.map(|session| Arc::clone(&session.proof))
|
||||
.clone()
|
||||
.context("service owner session is not active")
|
||||
}
|
||||
|
||||
/// Returns false unless the active service session explicitly supports in-place staging.
|
||||
pub(crate) fn active_service_supports_runtime_staging() -> bool {
|
||||
ACTIVE_SERVICE_SESSION
|
||||
.lock()
|
||||
.as_ref()
|
||||
.is_some_and(|session| session.supports_runtime_staging)
|
||||
}
|
||||
|
||||
pub(crate) fn active_service_supports_runtime_file_read() -> bool {
|
||||
ACTIVE_SERVICE_SESSION
|
||||
.lock()
|
||||
.as_ref()
|
||||
.is_some_and(|session| session.supports_runtime_file_read)
|
||||
}
|
||||
|
||||
fn active_service_supports_runtime_geo_read() -> bool {
|
||||
ACTIVE_SERVICE_SESSION
|
||||
.lock()
|
||||
.as_ref()
|
||||
.is_some_and(|session| session.supports_runtime_geo_read)
|
||||
}
|
||||
|
||||
pub(crate) fn clear_active_service_session() {
|
||||
ACTIVE_SERVICE_SESSION.lock().take();
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Default)]
|
||||
struct ServiceCapabilities {
|
||||
runtime_staging: bool,
|
||||
runtime_file_read: bool,
|
||||
runtime_geo_read: bool,
|
||||
}
|
||||
|
||||
impl ServiceCapabilities {
|
||||
const fn of(info: &ProtocolInfo) -> Self {
|
||||
Self {
|
||||
runtime_staging: info.supports_runtime_staging(),
|
||||
runtime_file_read: info.supports_runtime_file_read(),
|
||||
runtime_geo_read: info.supports_runtime_geo_read(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Failed capability probes must not block startup.
|
||||
#[tracing::instrument(skip_all, level = "info", fields(supported = tracing::field::Empty))]
|
||||
async fn probe_service_capabilities() -> ServiceCapabilities {
|
||||
match clash_verge_service_ipc::get_version().await {
|
||||
Ok(response) if response.code == 0 => {
|
||||
let capabilities = response
|
||||
.data
|
||||
.as_ref()
|
||||
.map_or_else(ServiceCapabilities::default, ServiceCapabilities::of);
|
||||
tracing::Span::current().record("supported", capabilities.runtime_staging);
|
||||
capabilities
|
||||
}
|
||||
Ok(response) => {
|
||||
tracing::Span::current().record("supported", false);
|
||||
logging!(
|
||||
warn,
|
||||
Type::Service,
|
||||
"服务协议查询返回 {}: {};配置变更将走重启路径",
|
||||
response.code,
|
||||
response.message
|
||||
);
|
||||
ServiceCapabilities::default()
|
||||
}
|
||||
Err(error) => {
|
||||
tracing::Span::current().record("supported", false);
|
||||
logging!(
|
||||
warn,
|
||||
Type::Service,
|
||||
"无法查询服务协议版本: {error:#};配置变更将走重启路径"
|
||||
);
|
||||
ServiceCapabilities::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn session_matches_status(proof: &OwnerSessionProof, is_active: bool, active_generation: Option<u64>) -> bool {
|
||||
is_active && active_generation == Some(proof.generation)
|
||||
}
|
||||
@@ -666,12 +581,11 @@ impl StageRequest {
|
||||
}
|
||||
|
||||
/// Requests in-place staging. `Err` means no answer; refusals are returned for caller policy.
|
||||
pub(super) async fn stage_runtime_by_service(config_file: &Path) -> Result<StageRequest> {
|
||||
let session = active_service_session()?;
|
||||
pub(super) async fn stage_runtime_by_service(config_file: &Path, session: &OwnerSessionProof) -> Result<StageRequest> {
|
||||
let credentials = current_owner_credentials()?;
|
||||
let runtime = collect_service_runtime_bundle(config_file).await?;
|
||||
|
||||
let response = clash_verge_service_ipc::stage_runtime(&credentials, &session, &runtime)
|
||||
let response = clash_verge_service_ipc::stage_runtime(&credentials, session, &runtime)
|
||||
.await
|
||||
.context("无法连接到Clash Verge Service")?;
|
||||
if response.code > 0 {
|
||||
@@ -780,7 +694,7 @@ pub(super) async fn release_service_core_for_sidecar() -> Result<()> {
|
||||
}
|
||||
|
||||
/// 尝试使用服务启动core
|
||||
#[tracing::instrument(skip_all, level = "info", fields(generation = tracing::field::Empty, staging = tracing::field::Empty, code = tracing::field::Empty, outcome = tracing::field::Empty))]
|
||||
#[tracing::instrument(skip_all, level = "info", fields(generation = tracing::field::Empty, code = tracing::field::Empty, outcome = tracing::field::Empty))]
|
||||
async fn start_with_existing_service(
|
||||
config_file: &Path,
|
||||
start: &tokio::sync::OnceCell<StartClashRequest>,
|
||||
@@ -850,17 +764,10 @@ async fn start_with_existing_service(
|
||||
|
||||
let result = response.data.context("Clash Verge Service 未返回会话信息")?;
|
||||
tracing::Span::current().record("generation", result.session.generation);
|
||||
let capabilities = probe_service_capabilities().await;
|
||||
tracing::Span::current().record("staging", capabilities.runtime_staging);
|
||||
*ACTIVE_SERVICE_SESSION.lock() = Some(ActiveServiceSession {
|
||||
proof: Arc::new(OwnerSessionProof {
|
||||
generation: result.session.generation,
|
||||
token: request.proposed_session_token.clone(),
|
||||
}),
|
||||
supports_runtime_staging: capabilities.runtime_staging,
|
||||
supports_runtime_file_read: capabilities.runtime_file_read,
|
||||
supports_runtime_geo_read: capabilities.runtime_geo_read,
|
||||
});
|
||||
*ACTIVE_SERVICE_SESSION.lock() = Some(Arc::new(OwnerSessionProof {
|
||||
generation: result.session.generation,
|
||||
token: request.proposed_session_token.clone(),
|
||||
}));
|
||||
|
||||
PENDING_SERVICE_START.lock().take();
|
||||
// PAC follows the Running Mode; the caller opens it via `core_started(Service)`.
|
||||
@@ -1047,11 +954,10 @@ type ProviderLoadTimes = HashMap<(&'static str, String), Option<u64>>;
|
||||
|
||||
#[tracing::instrument(level = "info", fields(synced = tracing::field::Empty, pending = tracing::field::Empty))]
|
||||
async fn sync_runtime_providers_by_service() -> Result<ProviderSync> {
|
||||
if !active_service_supports_runtime_file_read() {
|
||||
let Ok(session) = active_service_session() else {
|
||||
return Ok(ProviderSync::default());
|
||||
}
|
||||
};
|
||||
let credentials = current_owner_credentials()?;
|
||||
let session = active_service_session()?;
|
||||
let app_dir = dirs::app_home_dir()?;
|
||||
let runtime = Config::runtime().await;
|
||||
let mut outcome = ProviderSync::default();
|
||||
@@ -1137,14 +1043,10 @@ async fn sync_runtime_providers_by_service() -> Result<ProviderSync> {
|
||||
|
||||
/// Pulls geo databases the service core rewrote, because validation reads the app dir.
|
||||
pub(crate) async fn sync_runtime_geo_by_service() {
|
||||
if !active_service_supports_runtime_geo_read() {
|
||||
let Ok(session) = active_service_session() else {
|
||||
return;
|
||||
}
|
||||
let (Ok(credentials), Ok(session), Ok(app_dir)) = (
|
||||
current_owner_credentials(),
|
||||
active_service_session(),
|
||||
dirs::app_home_dir(),
|
||||
) else {
|
||||
};
|
||||
let (Ok(credentials), Ok(app_dir)) = (current_owner_credentials(), dirs::app_home_dir()) else {
|
||||
return;
|
||||
};
|
||||
for asset in GEO_ASSETS {
|
||||
@@ -1732,7 +1634,7 @@ fn session_matches_active_status(is_active: bool, active_generation: Option<u64>
|
||||
ACTIVE_SERVICE_SESSION
|
||||
.lock()
|
||||
.as_ref()
|
||||
.is_some_and(|session| session_matches_status(&session.proof, is_active, active_generation))
|
||||
.is_some_and(|session| session_matches_status(session, is_active, active_generation))
|
||||
}
|
||||
|
||||
fn cancel_owner_monitors() {
|
||||
|
||||
Reference in New Issue
Block a user