diff --git a/backend/Cargo.lock b/backend/Cargo.lock index 03b02b19f..98e70c292 100644 --- a/backend/Cargo.lock +++ b/backend/Cargo.lock @@ -1762,6 +1762,7 @@ dependencies = [ "thiserror", "tokio", "tracing", + "url", "uuid", ] diff --git a/backend/crates/gateway-admin/Cargo.toml b/backend/crates/gateway-admin/Cargo.toml index e2be586aa..64173dd2d 100644 --- a/backend/crates/gateway-admin/Cargo.toml +++ b/backend/crates/gateway-admin/Cargo.toml @@ -32,6 +32,7 @@ sha2 = "0.11" subtle = "2.6.1" thiserror = "2.0.18" tracing = "0.1.44" +url = "2.5.8" uuid = { version = "1.23.3", features = ["v4", "v7"] } cron = "0.17" chrono-tz = "0.10" diff --git a/backend/crates/gateway-admin/src/model/audit.rs b/backend/crates/gateway-admin/src/model/audit.rs index ea47372c4..9e7e8a290 100644 --- a/backend/crates/gateway-admin/src/model/audit.rs +++ b/backend/crates/gateway-admin/src/model/audit.rs @@ -47,6 +47,7 @@ pub enum MutationAuditOperation { OutboundProxyUpdate, OutboundProxyDelete, OutboundProxyTest, + ProxyTestTargetsUpdate, AccountGroupPluginReconcile, ClientApiKeyPluginReconcile, ProviderAccountImportDocument, @@ -110,6 +111,7 @@ impl MutationAuditOperation { Self::OutboundProxyCreate => ("create", "outbound_proxy"), Self::OutboundProxyUpdate => ("update", "outbound_proxy"), Self::OutboundProxyDelete => ("delete", "outbound_proxy"), + Self::ProxyTestTargetsUpdate => ("update", "proxy_test_targets"), Self::OutboundProxyTest => ("test", "outbound_proxy"), Self::AccountGroupPluginReconcile => ("plugin_reconcile", "account_group"), Self::ClientApiKeyPluginReconcile => ("plugin_reconcile", "client_api_key"), diff --git a/backend/crates/gateway-admin/src/model/proxies.rs b/backend/crates/gateway-admin/src/model/proxies.rs index a0bf14165..525fdff27 100644 --- a/backend/crates/gateway-admin/src/model/proxies.rs +++ b/backend/crates/gateway-admin/src/model/proxies.rs @@ -56,6 +56,41 @@ pub struct ProxyAccountPage { pub page_size: u16, } +#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub struct ProxyTestTarget { + pub name: String, + pub url: String, +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub struct ProxyTestTargets { + pub revision: Revision, + pub targets: Vec, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct TargetProbeResult { + pub latency_ms: u64, + #[serde(flatten)] + pub outcome: TargetProbeOutcome, +} + +#[derive(Debug, Serialize)] +#[serde(tag = "kind", rename_all = "camelCase")] +pub enum TargetProbeOutcome { + Http { + status: u16, + #[serde(rename = "exitIp")] + exit_ip: Option, + }, + Failed { + message: String, + }, +} + #[derive(Debug, Clone, PartialEq, Eq)] pub struct ProxyTestResult { pub location: ProxyLocationDetection, diff --git a/backend/crates/gateway-admin/src/ports/proxy.rs b/backend/crates/gateway-admin/src/ports/proxy.rs index 2304c6d46..e1a458eef 100644 --- a/backend/crates/gateway-admin/src/ports/proxy.rs +++ b/backend/crates/gateway-admin/src/ports/proxy.rs @@ -8,7 +8,8 @@ use crate::model::{ AdminError, MutationContext, Revision, proxies::{ ImportProxyBinding, NewProxy, ProxyAccountListQuery, ProxyAccountPage, ProxyListQuery, - ProxyMutation, ProxyPage, ProxyRecord, ProxyTestResult, UpdateProxy, + ProxyMutation, ProxyPage, ProxyRecord, ProxyTestResult, ProxyTestTargets, + TargetProbeResult, UpdateProxy, }, }; @@ -21,6 +22,12 @@ pub trait PluginProxyAccess: Send + Sync { #[async_trait] pub trait ProxyStore: Send + Sync { + async fn test_targets(&self) -> AdminStoreResult; + async fn replace_test_targets( + &self, + settings: &ProxyTestTargets, + context: &MutationContext, + ) -> AdminStoreResult; /// 在凭据交换到提交期间保护选定代理的连接配置和测试结果 async fn reserve_import(&self, id: &str) -> AdminStoreResult; async fn list(&self, query: ProxyListQuery) -> AdminStoreResult; @@ -78,5 +85,6 @@ pub enum ProbeRoute<'a> { #[async_trait] pub trait ProxyProbe: Send + Sync { + async fn test_target(&self, proxy: &OutboundProxy, endpoint: &str) -> TargetProbeResult; async fn test(&self, proxy: ProbeRoute<'_>, detect_location: bool) -> ProxyTestResult; } diff --git a/backend/crates/gateway-admin/src/use_case/proxies.rs b/backend/crates/gateway-admin/src/use_case/proxies.rs index a40cb9ac8..b9f9be8db 100644 --- a/backend/crates/gateway-admin/src/use_case/proxies.rs +++ b/backend/crates/gateway-admin/src/use_case/proxies.rs @@ -69,6 +69,18 @@ async fn list_proxies( #[async_trait] pub trait ProxiesService: Send + Sync { + async fn test_targets(&self) -> Result; + async fn replace_test_targets( + &self, + settings: ProxyTestTargets, + context: &MutationContext, + ) -> Result; + async fn test_target( + &self, + proxy_id: &str, + name: &str, + revision: Revision, + ) -> Result<(String, TargetProbeResult), AdminError>; async fn create_batch( &self, commands: Vec>, @@ -131,6 +143,12 @@ pub(crate) struct DefaultProxiesService { } impl DefaultProxiesService { + fn test_slot(&self) -> Result, AdminError> { + self.test_slots + .try_acquire() + .map_err(|_| AdminError::new(AdminErrorKind::RateLimited, "代理测试已达并发上限")) + } + pub(crate) fn new( store: Arc, probe: Arc, @@ -151,6 +169,84 @@ impl DefaultProxiesService { #[async_trait] impl ProxiesService for DefaultProxiesService { + async fn test_targets(&self) -> Result { + self.store + .test_targets() + .await + .map_err(|error| map_store_error(error, "proxy test targets")) + } + + async fn replace_test_targets( + &self, + mut settings: ProxyTestTargets, + context: &MutationContext, + ) -> Result { + if settings.targets.len() > 32 { + return Err(AdminError::invalid("最多可配置 32 个测试目标")); + } + let mut names = std::collections::HashSet::new(); + for target in &mut settings.targets { + target.name = target.name.trim().to_owned(); + if target.name.is_empty() + || target.name.chars().count() > 100 + || target.name.chars().any(char::is_control) + { + return Err(AdminError::invalid("目标名称需要 1 至 100 个字符")); + } + if !names.insert(target.name.as_str()) { + return Err(AdminError::invalid("测试目标名称重复")); + } + let raw = target.url.trim(); + let url = url::Url::parse(raw) + .ok() + .filter(|url| { + !raw.chars().any(char::is_control) + && url.scheme() == "https" + && url.has_host() + && url.username().is_empty() + && url.password().is_none() + && url.fragment().is_none() + }) + .ok_or_else(|| AdminError::invalid("请输入不含凭据和片段的 HTTPS 目标地址"))?; + if raw.len() > 2048 || url.as_str().len() > 2048 { + return Err(AdminError::invalid("目标地址不能超过 2048 字节")); + } + target.url = url.into(); + } + settings.revision = self + .store + .replace_test_targets(&settings, context) + .await + .map_err(|error| map_store_error(error, "proxy test targets"))?; + publish_committed(self.snapshot.as_ref(), settings.revision).await?; + Ok(settings) + } + + async fn test_target( + &self, + proxy_id: &str, + name: &str, + revision: Revision, + ) -> Result<(String, TargetProbeResult), AdminError> { + let _permit = self.test_slot()?; + let settings = self.test_targets().await?; + if settings.revision != revision { + return Err(AdminError::conflict("测试目标已更新,请重新选择")); + } + let target = settings + .targets + .iter() + .find(|target| target.name == name) + .ok_or_else(|| AdminError::not_found("测试目标不存在"))?; + let record = self + .store + .get(proxy_id) + .await + .map_err(|error| map_store_error(error, "proxy"))?; + let result = self.probe.test_target(&record.proxy, &target.url).await; + Ok((record.name, result)) + } + async fn create_batch( &self, commands: Vec>, @@ -394,10 +490,7 @@ impl ProxiesService for DefaultProxiesService { proxy: ProbeRoute<'_>, detect_location: bool, ) -> Result { - let _permit = self - .test_slots - .try_acquire() - .map_err(|_| AdminError::new(AdminErrorKind::RateLimited, "代理测试已达并发上限"))?; + let _permit = self.test_slot()?; Ok(self.probe.test(proxy, detect_location).await) } @@ -408,10 +501,7 @@ impl ProxiesService for DefaultProxiesService { detect_location: bool, context: &MutationContext, ) -> Result { - let _permit = self - .test_slots - .try_acquire() - .map_err(|_| AdminError::new(AdminErrorKind::RateLimited, "代理测试已达并发上限"))?; + let _permit = self.test_slot()?; let record = self .store .get(id) diff --git a/backend/crates/gateway-admin/tests/use_case/plugins/distribution.rs b/backend/crates/gateway-admin/tests/use_case/plugins/distribution.rs index 28777fbd8..bf99d3d27 100644 --- a/backend/crates/gateway-admin/tests/use_case/plugins/distribution.rs +++ b/backend/crates/gateway-admin/tests/use_case/plugins/distribution.rs @@ -100,6 +100,20 @@ impl SnapshotControl for Fixture { #[async_trait] impl ProxyStore for Fixture { + async fn test_targets( + &self, + ) -> gateway_admin::ports::store::AdminStoreResult< + gateway_admin::model::proxies::ProxyTestTargets, + > { + unreachable!() + } + async fn replace_test_targets( + &self, + _: &gateway_admin::model::proxies::ProxyTestTargets, + _: &gateway_admin::model::MutationContext, + ) -> gateway_admin::ports::store::AdminStoreResult { + unreachable!() + } async fn reserve_import(&self, _: &str) -> AdminStoreResult { unreachable!() } diff --git a/backend/crates/gateway-admin/tests/use_case/plugins/mod.rs b/backend/crates/gateway-admin/tests/use_case/plugins/mod.rs index f50423e62..38bd9b910 100644 --- a/backend/crates/gateway-admin/tests/use_case/plugins/mod.rs +++ b/backend/crates/gateway-admin/tests/use_case/plugins/mod.rs @@ -39,6 +39,20 @@ pub(super) struct TestPluginPorts; #[async_trait] impl gateway_admin::ports::proxy::ProxyStore for TestPluginPorts { + async fn test_targets( + &self, + ) -> gateway_admin::ports::store::AdminStoreResult< + gateway_admin::model::proxies::ProxyTestTargets, + > { + unreachable!() + } + async fn replace_test_targets( + &self, + _: &gateway_admin::model::proxies::ProxyTestTargets, + _: &gateway_admin::model::MutationContext, + ) -> gateway_admin::ports::store::AdminStoreResult { + unreachable!() + } async fn reserve_import( &self, _: &str, diff --git a/backend/crates/gateway-admin/tests/use_case/proxies.rs b/backend/crates/gateway-admin/tests/use_case/proxies.rs index dc06b0206..a5065f542 100644 --- a/backend/crates/gateway-admin/tests/use_case/proxies.rs +++ b/backend/crates/gateway-admin/tests/use_case/proxies.rs @@ -39,6 +39,20 @@ impl ProxyStore for TestProxies { Err(super::unavailable("proxy")) } + async fn test_targets( + &self, + ) -> gateway_admin::ports::store::AdminStoreResult< + gateway_admin::model::proxies::ProxyTestTargets, + > { + unreachable!() + } + async fn replace_test_targets( + &self, + _: &gateway_admin::model::proxies::ProxyTestTargets, + _: &gateway_admin::model::MutationContext, + ) -> gateway_admin::ports::store::AdminStoreResult { + unreachable!() + } async fn reserve_import( &self, id: &str, @@ -194,6 +208,14 @@ async fn plugin_proxy_resolution_requires_enabled_configuration_without_account_ #[async_trait] impl ProxyProbe for TestProxies { + async fn test_target( + &self, + _: &gateway_core::account::OutboundProxy, + _: &str, + ) -> gateway_admin::model::proxies::TargetProbeResult { + unreachable!() + } + async fn test(&self, _: ProbeRoute<'_>, _: bool) -> ProxyTestResult { panic!("unexpected proxy probe") } @@ -487,6 +509,14 @@ impl Drop for ActiveProbe<'_> { #[async_trait] impl ProxyProbe for GatedProxyProbe { + async fn test_target( + &self, + _: &gateway_core::account::OutboundProxy, + _: &str, + ) -> gateway_admin::model::proxies::TargetProbeResult { + unreachable!() + } + async fn test(&self, _: ProbeRoute<'_>, _: bool) -> ProxyTestResult { self.active .fetch_add(1, std::sync::atomic::Ordering::Relaxed); diff --git a/backend/crates/gateway-api/src/admin/proxies.rs b/backend/crates/gateway-api/src/admin/proxies.rs index 1c1b1840a..111fce752 100644 --- a/backend/crates/gateway-api/src/admin/proxies.rs +++ b/backend/crates/gateway-api/src/admin/proxies.rs @@ -13,7 +13,7 @@ use gateway_admin::model::{ AdminError as ServiceError, PageSize, Revision, proxies::{ NewProxy, ProxyAccountListQuery, ProxyBatchResult, ProxyListQuery, ProxyMutation, - ProxyRecord, ProxyTestResult, TestProxy, UpdateProxy, + ProxyRecord, ProxyTestResult, ProxyTestTargets, TestProxy, UpdateProxy, }, }; use serde::{Deserialize, Serialize}; @@ -260,6 +260,11 @@ where .route("/api/admin/proxies/delete", post(delete::)) .route("/api/admin/proxies/test", post(test::)) .route("/api/admin/proxies/probe", post(probe::)) + .route( + "/api/admin/proxies/targets", + get(test_targets::).post(replace_test_targets::), + ) + .route("/api/admin/proxies/targets/test", post(test_target::)) } fn revision(value: u64) -> Result { @@ -546,6 +551,75 @@ where )) } +async fn test_targets( + _: AdminAuth, + State(state): State, +) -> Result +where + S: SessionState + Send + Sync, +{ + let targets = state + .admin_services() + .proxies() + .test_targets() + .await + .map_err(map_error)?; + Ok(AdminResponse::new( + StatusCode::OK, + AdminEnvelope::ok(targets), + )) +} + +async fn replace_test_targets( + auth: AdminAuth, + State(state): State, + AdminJson(settings): AdminJson, +) -> Result +where + S: SessionState + Send + Sync, +{ + let targets = state + .admin_services() + .proxies() + .replace_test_targets(settings, &auth.context().mutation_context()) + .await + .map_err(map_error)?; + Ok(AdminResponse::new( + StatusCode::OK, + AdminEnvelope::ok(targets), + )) +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct TargetTestRequest { + proxy_id: String, + target_name: String, + revision: Revision, +} + +async fn test_target( + _: AdminAuth, + State(state): State, + AdminJson(request): AdminJson, +) -> Result +where + S: SessionState + Send + Sync, +{ + let (proxy_name, result) = state + .admin_services() + .proxies() + .test_target(&request.proxy_id, &request.target_name, request.revision) + .await + .map_err(map_error)?; + Ok(AdminResponse::new( + StatusCode::OK, + AdminEnvelope::ok(serde_json::json!({ + "proxyName": proxy_name, "result": result, + })), + )) +} + async fn probe( _: AdminAuth, State(state): State, diff --git a/backend/crates/gateway-api/tests/admin/proxies.rs b/backend/crates/gateway-api/tests/admin/proxies.rs index b7cf0dbef..f00c885f9 100644 --- a/backend/crates/gateway-api/tests/admin/proxies.rs +++ b/backend/crates/gateway-api/tests/admin/proxies.rs @@ -91,8 +91,71 @@ async fn proxy_location_rejects_invalid_and_incomplete_input() { assert!(created["data"][0]["data"]["record"]["location"].is_null()); } +#[tokio::test] +async fn site_tests_use_saved_targets_and_preserve_the_exit_test() { + let fixture = AdminTestFixture::new().await; + fixture.auth.insert_session("valid-session"); + let path = "/api/admin/proxies/targets"; + assert_eq!( + request(&fixture, path, None, false).await.0, + StatusCode::UNAUTHORIZED + ); + let (_, initial) = request(&fixture, path, None, true).await; + let revision = &initial["data"]["revision"]; + let target = json!({"name":"ChatGPT","url":"https://chatgpt.com/cdn-cgi/trace"}); + for targets in [ + json!([{"name":"A","url":"http://example.org"}]), + json!([{"name":"A","url":"https://user:pass@example.org"}]), + json!([target, target]), + ] { + let (status, _) = request( + &fixture, + path, + Some(json!({"revision":revision,"targets":targets})), + true, + ) + .await; + assert_eq!(status, StatusCode::BAD_REQUEST); + } + let settings = json!({"revision":revision,"targets":[target]}); + let (status, saved) = request(&fixture, path, Some(settings.clone()), true).await; + assert_eq!(status, StatusCode::OK); + assert_eq!( + request(&fixture, path, Some(settings), true).await.0, + StatusCode::CONFLICT + ); + let (status, _) = request( + &fixture, + "/api/admin/proxies/create", + Some(json!([{"name":"Office","proxyUrl":"http://proxy.example:8080"}])), + true, + ) + .await; + assert_eq!(status, StatusCode::OK); + let run_path = "/api/admin/proxies/targets/test"; + let mut run = json!({"proxyId":"proxy_test","targetName":"ChatGPT","revision":revision}); + assert_eq!( + request(&fixture, run_path, Some(run.clone()), true).await.0, + StatusCode::CONFLICT + ); + run["revision"] = saved["data"]["revision"].clone(); + let (status, response) = request(&fixture, run_path, Some(run.clone()), true).await; + assert_eq!(status, StatusCode::OK); + assert_eq!( + response["data"], + json!({"proxyName":"Office","result":{"kind":"http","status":403,"exitIp":null,"latencyMs":18}}) + ); + let (_, page) = request(&fixture, "/api/admin/proxies", None, true).await; + assert!(page["data"]["items"][0]["lastTest"].is_null()); + run["targetName"] = json!("https://another.example"); + assert_eq!( + request(&fixture, run_path, Some(run), true).await.0, + StatusCode::NOT_FOUND + ); +} + #[derive(Default)] -pub(super) struct MemoryProxies(Mutex>); +pub(super) struct MemoryProxies(Mutex>, Mutex>); #[tokio::test] async fn proxy_enabled_updates_preserve_connection_and_omitted_state() { @@ -153,6 +216,38 @@ impl ProxyStore for MemoryProxies { Ok(Revision::new(4).unwrap()) } + async fn test_targets(&self) -> AdminStoreResult { + Ok(self + .1 + .lock() + .unwrap() + .clone() + .unwrap_or_else(|| ProxyTestTargets { + revision: Revision::new(1).unwrap(), + targets: vec![], + })) + } + async fn replace_test_targets( + &self, + settings: &ProxyTestTargets, + _: &MutationContext, + ) -> AdminStoreResult { + let mut saved = self.1.lock().unwrap(); + let current = saved.as_ref().map_or(1, |value| value.revision.get()); + if current != settings.revision.get() { + return Err(AdminStoreError::new( + AdminStoreErrorKind::StaleRevision, + "proxy test targets", + "stale revision", + )); + } + let revision = Revision::new(current + 1).unwrap(); + *saved = Some(ProxyTestTargets { + revision, + targets: settings.targets.clone(), + }); + Ok(revision) + } async fn reserve_import( &self, _: &str, @@ -348,6 +443,22 @@ pub(super) struct SuccessfulProbe; #[async_trait] impl ProxyProbe for SuccessfulProbe { + async fn test_target( + &self, + proxy: &gateway_core::account::OutboundProxy, + endpoint: &str, + ) -> gateway_admin::model::proxies::TargetProbeResult { + assert_eq!(proxy.expose_url(), "http://proxy.example:8080/"); + assert_eq!(endpoint, "https://chatgpt.com/cdn-cgi/trace"); + TargetProbeResult { + latency_ms: 18, + outcome: TargetProbeOutcome::Http { + status: 403, + exit_ip: None, + }, + } + } + async fn test(&self, proxy: ProbeRoute<'_>, detect_location: bool) -> ProxyTestResult { if let ProbeRoute::Proxy(proxy) = proxy { assert_eq!( diff --git a/backend/crates/gateway-host/src/proxy_probe.rs b/backend/crates/gateway-host/src/proxy_probe.rs index 17af377ed..82255e04a 100644 --- a/backend/crates/gateway-host/src/proxy_probe.rs +++ b/backend/crates/gateway-host/src/proxy_probe.rs @@ -8,7 +8,9 @@ use std::{ use async_trait::async_trait; use gateway_admin::{ - model::proxies::{ProxyLocationDetection, ProxyTestResult}, + model::proxies::{ + ProxyLocationDetection, ProxyTestResult, TargetProbeOutcome, TargetProbeResult, + }, ports::proxy::{ProbeRoute, ProxyProbe}, }; use gateway_core::account::RequestLocation; @@ -50,6 +52,17 @@ impl Default for HttpProxyProbe { } } +async fn read_probe_body(mut response: reqwest::Response) -> Result, &'static str> { + let mut body = Vec::new(); + while let Some(chunk) = response.chunk().await.map_err(|_| "出口检测响应读取失败")? { + if body.len() + chunk.len() > 1024 { + return Err("出口检测响应过大"); + } + body.extend_from_slice(&chunk); + } + Ok(body) +} + impl HttpProxyProbe { #[must_use] pub fn new(endpoint: impl Into) -> Self { @@ -82,23 +95,31 @@ impl HttpProxyProbe { self } - async fn exit_ip_at( + async fn request( &self, proxy: ProbeRoute<'_>, endpoint: &str, - ) -> Result { + ) -> Result { let builder = probe_client(proxy)? .connect_timeout(Duration::from_secs(5)) .timeout(Duration::from_secs(12)) .redirect(reqwest::redirect::Policy::none()); let client = (self.build_client)(builder)?; - let mut response = client.get(endpoint).send().await.map_err(|error| { + client.get(endpoint).send().await.map_err(|error| { if error.is_timeout() { "出口连接超时" } else { "出口连接失败" } - })?; + }) + } + + async fn exit_ip_at( + &self, + proxy: ProbeRoute<'_>, + endpoint: &str, + ) -> Result { + let response = self.request(proxy, endpoint).await?; if !response.status().is_success() { return Err( if response.status() == reqwest::StatusCode::PROXY_AUTHENTICATION_REQUIRED { @@ -108,14 +129,7 @@ impl HttpProxyProbe { }, ); } - let mut body = Vec::new(); - while let Some(chunk) = response.chunk().await.map_err(|_| "出口检测响应读取失败")? - { - if body.len() + chunk.len() > 1024 { - return Err("出口检测响应过大"); - } - body.extend_from_slice(&chunk); - } + let body = read_probe_body(response).await?; #[derive(Deserialize)] struct Response { ip: IpAddr, @@ -396,6 +410,45 @@ impl HttpProxyProbe { #[async_trait] impl ProxyProbe for HttpProxyProbe { + async fn test_target( + &self, + proxy: &gateway_core::account::OutboundProxy, + endpoint: &str, + ) -> TargetProbeResult { + let started = Instant::now(); + let response = self.request(ProbeRoute::Proxy(proxy), endpoint).await; + // 耗时截至收到响应头,可选的 trace 正文不影响站点状态与延迟 + let latency_ms = u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX); + let outcome = match response { + Ok(response) => { + let status = response.status(); + let exit_ip = if status.is_success() && response.url().path() == "/cdn-cgi/trace" { + read_probe_body(response).await.ok().and_then(|body| { + std::str::from_utf8(&body) + .ok()? + .lines() + .find_map(|line| line.strip_prefix("ip="))? + .parse() + .ok() + }) + } else { + None + }; + TargetProbeOutcome::Http { + status: status.as_u16(), + exit_ip, + } + } + Err(message) => TargetProbeOutcome::Failed { + message: message.to_owned(), + }, + }; + TargetProbeResult { + latency_ms, + outcome, + } + } + async fn test(&self, proxy: ProbeRoute<'_>, detect_location: bool) -> ProxyTestResult { let mut result = self.test_connection(proxy).await; if detect_location { diff --git a/backend/crates/gateway-host/tests/proxy_probe.rs b/backend/crates/gateway-host/tests/proxy_probe.rs index a5a036d92..b02ca8a06 100644 --- a/backend/crates/gateway-host/tests/proxy_probe.rs +++ b/backend/crates/gateway-host/tests/proxy_probe.rs @@ -9,6 +9,52 @@ use wiremock::{ matchers::{any, header, path}, }; +#[tokio::test] +async fn site_probe_reports_the_first_http_status_and_only_parses_bounded_trace_responses() { + use gateway_admin::model::proxies::TargetProbeOutcome; + for (endpoint, status, body, ip) in [ + ("/", 403, "ip=192.0.2.1".to_owned(), None), + ("/", 302, String::new(), None), + ( + "/cdn-cgi/trace", + 200, + "ip=2001:db8::1\nloc=US\n".to_owned(), + Some("2001:db8::1"), + ), + ( + "/cdn-cgi/trace", + 200, + format!("ip=192.0.2.1\n{}", "x".repeat(1024)), + None, + ), + ("/cdn-cgi/trace", 200, "ip=invalid".to_owned(), None), + ] { + let server = MockServer::start().await; + Mock::given(path(endpoint)) + .respond_with( + ResponseTemplate::new(status) + .insert_header("Location", "http://other.invalid/") + .set_body_string(body), + ) + .expect(1) + .mount(&server) + .await; + let proxy = OutboundProxy::parse(&server.uri()).unwrap(); + let result = HttpProxyProbe::default() + .test_target(&proxy, &format!("http://target.invalid{endpoint}")) + .await; + let TargetProbeOutcome::Http { + status: actual, + exit_ip, + } = result.outcome + else { + panic!("expected HTTP response") + }; + assert_eq!(actual, status); + assert_eq!(exit_ip, ip.map(|ip| ip.parse().unwrap())); + } +} + #[tokio::test] async fn proxy_probe_supports_ipv4_and_ipv6_proxies_and_exit_addresses() { for (listen_address, exit_ip) in [ diff --git a/backend/crates/gateway-plugin/runtime/tests/support/environment.rs b/backend/crates/gateway-plugin/runtime/tests/support/environment.rs index 6a0a9adf2..af876a150 100644 --- a/backend/crates/gateway-plugin/runtime/tests/support/environment.rs +++ b/backend/crates/gateway-plugin/runtime/tests/support/environment.rs @@ -951,6 +951,14 @@ impl PricingSource for UnusedAdminRuntime { #[async_trait] impl ProxyProbe for UnusedAdminRuntime { + async fn test_target( + &self, + _: &gateway_core::account::OutboundProxy, + _: &str, + ) -> gateway_admin::model::proxies::TargetProbeResult { + unreachable!() + } + async fn test( &self, _: gateway_admin::ports::proxy::ProbeRoute<'_>, diff --git a/backend/crates/gateway-store/src/postgres/proxies.rs b/backend/crates/gateway-store/src/postgres/proxies.rs index e32d8bd88..9ca3b1562 100644 --- a/backend/crates/gateway-store/src/postgres/proxies.rs +++ b/backend/crates/gateway-store/src/postgres/proxies.rs @@ -403,6 +403,59 @@ async fn audit( #[async_trait] impl ProxyStore for PgProxyRepository { + async fn test_targets(&self) -> AdminStoreResult { + let (revision, targets) = sqlx::query_as::<_, (i64, sqlx::types::Json>)>( + "select proxy_test_targets_revision, proxy_test_targets from runtime_settings where id = 1" + ).fetch_one(&self.pool).await.map_err(|source| store_error(unavailable(source)))?; + Ok(ProxyTestTargets { + revision: AdminRevision::new(revision.try_into().map_err(|_| store_error(invalid()))?) + .map_err(|_| store_error(invalid()))?, + targets: targets.0, + }) + } + + async fn replace_test_targets( + &self, + settings: &ProxyTestTargets, + context: &MutationContext, + ) -> AdminStoreResult { + let mut transaction = self + .pool + .begin() + .await + .map_err(|source| store_error(unavailable(source)))?; + let revision = bump_config_revision_in_transaction(&mut transaction) + .await + .map_err(store_error)?; + let updated = sqlx::query("update runtime_settings set proxy_test_targets = $1, proxy_test_targets_revision = $2 where id = 1 and proxy_test_targets_revision = $3") + .bind(sqlx::types::Json(&settings.targets)) + .bind(i64::try_from(revision.get()).map_err(|_| store_error(invalid()))?) + .bind(i64::try_from(settings.revision.get()).map_err(|_| store_error(invalid()))?) + .execute(&mut *transaction).await.map_err(|source| store_error(unavailable(source)))?; + if updated.rows_affected() == 0 { + return Err(AdminStoreError::new( + gateway_admin::ports::store::AdminStoreErrorKind::StaleRevision, + "proxy test targets", + "stale revision", + )); + } + audit( + &mut transaction, + context, + MutationAuditOperation::ProxyTestTargetsUpdate, + "1", + &["targets"], + revision, + ) + .await + .map_err(store_error)?; + transaction + .commit() + .await + .map_err(|source| store_error(unavailable(source)))?; + admin_revision(revision) + } + async fn remove_account( &self, proxy_id: &str, diff --git a/backend/crates/gateway-store/tests/postgres/proxies.rs b/backend/crates/gateway-store/tests/postgres/proxies.rs index da9f3b9ef..6c5597780 100644 --- a/backend/crates/gateway-store/tests/postgres/proxies.rs +++ b/backend/crates/gateway-store/tests/postgres/proxies.rs @@ -18,6 +18,36 @@ use gateway_store::postgres::{ use super::{TestDatabase, admin_account_store, provider_accounts::account}; +#[tokio::test] +async fn proxy_test_targets_survive_reload_and_reject_stale_replacements() { + let Some(database) = TestDatabase::create("proxy_targets").await else { + return; + }; + let repository = PgProxyRepository::new(database.pool.clone()); + let mut settings = repository.test_targets().await.unwrap(); + assert!(settings.targets.is_empty()); + settings.targets.push(ProxyTestTarget { + name: "ChatGPT".into(), + url: "https://chatgpt.com/cdn-cgi/trace".into(), + }); + let revision = repository + .replace_test_targets(&settings, &context()) + .await + .unwrap(); + let stale = repository + .replace_test_targets(&settings, &context()) + .await + .unwrap_err(); + assert_eq!(stale.kind(), AdminStoreErrorKind::StaleRevision); + let saved = PgProxyRepository::new(database.pool.clone()) + .test_targets() + .await + .unwrap(); + assert_eq!(saved.revision, revision); + assert_eq!(saved.targets, settings.targets); + database.close().await; +} + #[tokio::test] async fn proxy_location_is_shared_preserved_cleared_and_removed_with_binding() { use gateway_core::account::{ProviderAccountStore, RequestLocation}; diff --git a/backend/migrations/.frozen-sha256 b/backend/migrations/.frozen-sha256 index 9aa45e60c..82207f2b9 100644 --- a/backend/migrations/.frozen-sha256 +++ b/backend/migrations/.frozen-sha256 @@ -47,3 +47,4 @@ e115a71b80faa08be4cf4f8747eec01e7b855ad3d8aa9622ca70b57300847b54 0046_account_a 98070edbfc34e71e403810fbb8db3bd18e7e241caeda2e952af022cd98ecdb6b 0047_request_plan_display.sql 709df48f4dd067332177fb8bee15c5e75d4666a0dc9c7a8e48f8480a01a99908 0048_openai_runtime_settings.sql c7ade39b6c5026c1a728bf4e3e0d64c5d5b6aba1cf6fa13a64ca2b79172ab56c 0049_client_key_validity.sql +d715793026842c42a17c2846bec46bd9f01e256b10594b33765bea8ac374e380 0050_proxy_test_targets.sql diff --git a/backend/migrations/0050_proxy_test_targets.sql b/backend/migrations/0050_proxy_test_targets.sql new file mode 100644 index 000000000..7676763a4 --- /dev/null +++ b/backend/migrations/0050_proxy_test_targets.sql @@ -0,0 +1,3 @@ +alter table runtime_settings + add column proxy_test_targets jsonb not null default '[]'::jsonb, + add column proxy_test_targets_revision bigint not null default 1 check (proxy_test_targets_revision > 0); diff --git a/docs/api.md b/docs/api.md index 148f49940..ef66ea85b 100644 --- a/docs/api.md +++ b/docs/api.md @@ -1497,6 +1497,8 @@ Search 的选号限制不约束插件在选号后主动改写正文。 | `POST` | `/api/admin/proxies/update` | `{ id, revision, name, enabled?, proxyUrl?, location?, autoLocation?, maxWebsocketConnections? }` | `{ record, configRevision }` | | `POST` | `/api/admin/proxies/probe` | `{ proxyUrl, useDeploymentProxy?, detectLocation? }` | 测试未保存的地址、部署默认出口或服务器直连出口,返回连通性及可选位置结果,不创建代理 | | `POST` | `/api/admin/proxies/test` | `[{ id, revision, detectLocation? }]` | 逐项结果数组,成功项的 `data` 为最新代理记录 | +| `GET` / `POST` | `/api/admin/proxies/targets` | GET 读取;POST 用 `{ revision, targets: [{ name, url }] }` 替换 | 返回当前目标列表及其版本,版本冲突返回 409 | +| `POST` | `/api/admin/proxies/targets/test` | `{ proxyId, targetName, revision }`,版本取自目标列表 | `{ proxyName, result }`,仅返回本次站点诊断 | | `POST` | `/api/admin/proxies/delete` | `{ id, revision }` | `{ configRevision }` | `probe` 的 `proxyUrl` 必填,空字符串默认测试服务器直连,同时传 `useDeploymentProxy: true` 则测试部署默认出口。指定代理地址时不能同时传 `useDeploymentProxy: true`;非空值须为合法代理 URL,`null`、省略或非法地址均拒绝。 @@ -1572,6 +1574,10 @@ API 的 `autoLocation` 默认为 `false`;开启时使用已检测位置,测 客户端实际本机时区不受影响,工具读取本机时区后的输出仍可包含真实值;排查见 [时区与客户端环境信息](../deploy/README.md#时区与客户端环境信息) +站点测试目标在部署内共享,最多 32 项。名称去除首尾空白后唯一,长度为 1–100 个字符;地址为最多 2048 字节的 HTTPS URL,不含用户凭据或片段。测试只接受已保存的代理和目标名称,目标配置变化后重新读取列表。管理端可选择多条代理测试同一目标,同时发起最多两条请求,与出口探测共用后端并发额度 + +站点测试发起 GET 并保留首个 HTTP 状态。收到响应时 `result` 包含 `kind: "http"`、`status`、`latencyMs` 和可空的 `exitIp`;只有成功的 `/cdn-cgi/trace` 响应才尝试读取 `ip=`。连接失败时返回 `kind: "failed"`、`latencyMs` 和 `message`。结果只在当次请求返回,代理的 `lastTest` 和检测位置仍由出口探测维护 + 测试经代理并发访问 IPv4 专用端点 `https://api.ipify.org?format=json` 与 IPv6 专用端点 `https://api6.ipify.org?format=json`, 分别验证并记录双栈出口(IPv4 与 IPv6 地址),在任一地址族可用时即判定连接成功。超时 15 秒,每进程最多同时测试 4 条。 解析位置时还会向 `https://ipwho.is/<出口 IP>` 查询地理位置,出口 IP 会发送给该第三方服务; diff --git a/docs/architecture.md b/docs/architecture.md index 6ade74796..b512d0498 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -1180,6 +1180,7 @@ client,OIDC 的 JWKS 缓存与单飞归属对应出口状态。凭据变更后 出口测试结果属于诊断信息,不作为选择、授权或导入绑定的准入条件。 双栈出口并发检测,延迟对应首选可用出口的 HTTP 探测耗时(IPv4 优先),不包含另一地址族失败的等待; 检测仍等待两个地址族完成或超时,以保留双栈可用性结果。两者均失败时,延迟为整体检测耗时。 +管理员配置的站点测试目标由代理管理模块持有。站点探测复用出口和并发额度,结果仅用于当次诊断;持久化出口和位置仍由双栈探测更新。 代理启停由代理记录独立持有;关闭时保留绑定、连接配置和位置规则,账号执行使用部署默认出口, 不使用该代理的位置覆盖,重新启用后恢复原出口。 连接配置改变时在同一事务内同步关联账号并清除旧测试结果。 diff --git a/frontend/package.json b/frontend/package.json index 560127fdf..8d707ddb8 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -17,7 +17,7 @@ }, "dependencies": { "@boxicons/vue": "1.0.1", - "@codex-proxy/ui": "github:zyycn/codex-proxy-ui#v0.13.4", + "@codex-proxy/ui": "github:zyycn/codex-proxy-ui#v0.13.5", "@fontsource-variable/inter": "^5.3.0", "@fontsource-variable/jetbrains-mono": "^5.3.0", "@lucide/vue": "^1.77.0", diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yaml index b4cd4673a..ea0691d00 100644 --- a/frontend/pnpm-lock.yaml +++ b/frontend/pnpm-lock.yaml @@ -195,8 +195,8 @@ importers: specifier: 1.0.1 version: 1.0.1(vue@3.5.46(typescript@6.0.3)) '@codex-proxy/ui': - specifier: github:zyycn/codex-proxy-ui#v0.13.4 - version: https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/ac8114d16c0341c66e9c360f797c1ae77d2e0d5d(axios@1.21.1(debug@4.4.3))(change-case@5.4.4)(jiti@2.7.0)(postcss@8.5.30)(vite@8.3.8(@types/node@26.6.6)(jiti@2.7.0)(yaml@2.9.0))(vue@3.5.46(typescript@6.0.3))(yaml@2.9.0) + specifier: github:zyycn/codex-proxy-ui#v0.13.5 + version: https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/8228b10d8f4b02bda468a075f7f87358630c0581(axios@1.21.1(debug@4.4.3))(change-case@5.4.4)(jiti@2.7.0)(postcss@8.5.30)(vite@8.3.8(@types/node@26.6.6)(jiti@2.7.0)(yaml@2.9.0))(vue@3.5.46(typescript@6.0.3))(yaml@2.9.0) '@fontsource-variable/inter': specifier: ^5.3.0 version: 5.3.0 @@ -456,9 +456,9 @@ packages: resolution: {integrity: sha512-dlT1m5e/0yUL0kRNcQn7yGLVThkgbB0Ga/1AmfDDC/8ik6AIiSf2QLQO2zPYvefsHP0aFgxO93cVLCCfDp7kzQ==} engines: {node: '>= 20.12.0'} - '@codex-proxy/ui@https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/ac8114d16c0341c66e9c360f797c1ae77d2e0d5d': - resolution: {gitHosted: true, integrity: sha512-6VttYlRECaLbR39j3VXBAradAwxo4PACMiorKz8WyVTnRWqKnvMxt2zhxu1GTHmQ9jJFg8Y/spfCuFP3P/Ym/Q==, tarball: https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/ac8114d16c0341c66e9c360f797c1ae77d2e0d5d} - version: 0.13.4 + '@codex-proxy/ui@https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/8228b10d8f4b02bda468a075f7f87358630c0581': + resolution: {gitHosted: true, integrity: sha512-LtGKbhViL9fixVJSCtEUZHDx+/13VOOUK1PMJHl6tlrxyNm8OR7s0tcMpmb3se+/v/F2gfZ0He/3n4a6fanUUA==, tarball: https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/8228b10d8f4b02bda468a075f7f87358630c0581} + version: 0.13.5 engines: {node: '>=24'} peerDependencies: vite: ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0 @@ -3590,7 +3590,7 @@ snapshots: fast-wrap-ansi: 0.2.2 sisteransi: 1.0.5 - '@codex-proxy/ui@https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/ac8114d16c0341c66e9c360f797c1ae77d2e0d5d(axios@1.21.1(debug@4.4.3))(change-case@5.4.4)(jiti@2.7.0)(postcss@8.5.30)(vite@8.3.8(@types/node@26.6.6)(jiti@2.7.0)(yaml@2.9.0))(vue@3.5.46(typescript@6.0.3))(yaml@2.9.0)': + '@codex-proxy/ui@https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/8228b10d8f4b02bda468a075f7f87358630c0581(axios@1.21.1(debug@4.4.3))(change-case@5.4.4)(jiti@2.7.0)(postcss@8.5.30)(vite@8.3.8(@types/node@26.6.6)(jiti@2.7.0)(yaml@2.9.0))(vue@3.5.46(typescript@6.0.3))(yaml@2.9.0)': dependencies: '@ant-design/colors': 8.0.1 '@ant-design/fast-color': 3.0.1 diff --git a/frontend/src/api/modules/proxies.ts b/frontend/src/api/modules/proxies.ts index 059e9d62f..4bd02328e 100644 --- a/frontend/src/api/modules/proxies.ts +++ b/frontend/src/api/modules/proxies.ts @@ -197,3 +197,47 @@ export function probeProxy(data: ProxyProbeParam, options: RequestOptions = {}) ...options, }) } + +export interface ProxyTestTarget { + name: string + url: string +} + +export interface ProxyTestTargets { + revision: number + targets: ProxyTestTarget[] +} + +export type TargetProbeResult = { latencyMs: number } & ( + | { kind: 'http', status: number, exitIp: string | null } + | { kind: 'failed', message: string } +) + +export function getProxyTestTargets(options: RequestOptions = {}) { + return request({ + url: '/api/admin/proxies/targets', + method: 'GET', + ...options, + }) +} + +export function saveProxyTestTargets(data: ProxyTestTargets, options: RequestOptions = {}) { + return request({ + url: '/api/admin/proxies/targets', + method: 'POST', + data, + retry: false, + ...options, + }) +} + +export function testProxyTarget(data: { proxyId: string, targetName: string, revision: number }, options: RequestOptions = {}) { + return request<{ proxyName: string, result: TargetProbeResult }>({ + url: '/api/admin/proxies/targets/test', + method: 'POST', + data, + timeout: 20000, + retry: false, + ...options, + }) +} diff --git a/frontend/src/components/ClientImportModal.vue b/frontend/src/components/ClientImportModal.vue index 1d76ed642..a67d3e854 100644 --- a/frontend/src/components/ClientImportModal.vue +++ b/frontend/src/components/ClientImportModal.vue @@ -10,7 +10,7 @@ import ProviderSelect from '@/components/ProviderSelect.vue' const props = defineProps<{ provider?: BuiltinProvider }>() const emit = defineEmits<{ select: [provider: BuiltinProvider] - afterLeave: [] + closed: [] }>() const open = defineModel({ default: false }) const selectedProvider = shallowRef('openai') @@ -28,7 +28,7 @@ function select() { :title="t('keys.configuration.importTo')" :description="t('keys.configuration.selectImportTool')" width="24rem" - @closed="emit('afterLeave')" + @closed="emit('closed')" >
diff --git a/frontend/src/components/api-key-config-modal/index.vue b/frontend/src/components/api-key-config-modal/index.vue index d93396197..43f329866 100644 --- a/frontend/src/components/api-key-config-modal/index.vue +++ b/frontend/src/components/api-key-config-modal/index.vue @@ -10,7 +10,7 @@ import ProviderSelect from '@/components/ProviderSelect.vue' import { buildCcSwitchImportDeeplink, buildClientConfig, resolveServiceRootUrl } from './client' const props = defineProps<{ title?: string, apiKey: { name?: string, key?: string } | null }>() -const emit = defineEmits<{ copy: [text: string], afterLeave: [] }>() +const emit = defineEmits<{ copy: [text: string], closed: [] }>() const open = defineModel({ default: false }) const { t } = useI18n({ useScope: 'global' }) const showImport = shallowRef(false) @@ -44,7 +44,7 @@ function importToClient() { - + diff --git a/frontend/src/i18n/locales/en/proxies.json b/frontend/src/i18n/locales/en/proxies.json index 3e8098a2a..4736be906 100644 --- a/frontend/src/i18n/locales/en/proxies.json +++ b/frontend/src/i18n/locales/en/proxies.json @@ -174,6 +174,23 @@ "enableFirst": "Enable this proxy before assigning accounts", "assignAction": "Assign ({count})", "assigned": "Assigned {count} account to “{name}” | Assigned {count} accounts to “{name}”" + }, + "targets": { + "manage": "Manage sites", + "name": "Site name", + "address": "HTTPS URL", + "remove": "Remove site", + "add": "Add site", + "skipped": "Skipped", + "custom": "Custom test", + "site": "Test site", + "run": "Run test", + "empty": "No test sites yet", + "shared": "These sites are shared by all proxies", + "accessDenied": "Access denied", + "redirect": "Redirect", + "detectedRegion": "Detected region", + "includeSelected": "Test all {count} selected proxies" } } } diff --git a/frontend/src/i18n/locales/zh-Hans/proxies.json b/frontend/src/i18n/locales/zh-Hans/proxies.json index 99c52888b..123650685 100644 --- a/frontend/src/i18n/locales/zh-Hans/proxies.json +++ b/frontend/src/i18n/locales/zh-Hans/proxies.json @@ -174,6 +174,23 @@ "enableFirst": "启用此代理后可分配账号", "assignAction": "分配 ({count})", "assigned": "已将 {count} 个账号分配至“{name}”" + }, + "targets": { + "manage": "管理站点", + "name": "站点名称", + "address": "HTTPS 地址", + "remove": "移除站点", + "add": "添加站点", + "skipped": "已跳过", + "custom": "自定义测试", + "site": "测试站点", + "run": "开始测试", + "empty": "还没有测试站点", + "shared": "所有代理共用这份站点列表", + "accessDenied": "拒绝访问", + "redirect": "重定向", + "detectedRegion": "已识别地区", + "includeSelected": "测试勾选的 {count} 个代理" } } } diff --git a/frontend/src/i18n/locales/zh-Hant/proxies.json b/frontend/src/i18n/locales/zh-Hant/proxies.json index bfa7af680..adca78c8f 100644 --- a/frontend/src/i18n/locales/zh-Hant/proxies.json +++ b/frontend/src/i18n/locales/zh-Hant/proxies.json @@ -174,6 +174,23 @@ "enableFirst": "啟用此代理後可分配賬號", "assignAction": "分配 ({count})", "assigned": "已將 {count} 個賬號分配至“{name}”" + }, + "targets": { + "manage": "管理站點", + "name": "站點名稱", + "address": "HTTPS 位址", + "remove": "移除站點", + "add": "新增站點", + "skipped": "已略過", + "custom": "自訂測試", + "site": "測試站點", + "run": "開始測試", + "empty": "還沒有測試站點", + "shared": "所有代理共用這份站點列表", + "accessDenied": "拒絕存取", + "redirect": "重新導向", + "detectedRegion": "已識別地區", + "includeSelected": "測試勾選的 {count} 個代理" } } } diff --git a/frontend/src/views/accounts/components/AccountBatchEditModal.vue b/frontend/src/views/accounts/components/AccountBatchEditModal.vue index e768e1547..05571855e 100644 --- a/frontend/src/views/accounts/components/AccountBatchEditModal.vue +++ b/frontend/src/views/accounts/components/AccountBatchEditModal.vue @@ -3,7 +3,7 @@ import type { AccountGroupRef, AccountModelAccess } from '@/api' import { ZButton, ZDialog, ZForm, ZFormItem, ZSegmented } from '@codex-proxy/ui' -import { computed, useTemplateRef, watch } from 'vue' +import { computed, useTemplateRef } from 'vue' import { useI18n } from 'vue-i18n' import { useAccountSettingsFormRules } from '../composables/useAccountSettingsFormRules' import AccountSettingsFields from './AccountSettingsFields.vue' @@ -44,8 +44,6 @@ const rules = useAccountSettingsFormRules(() => form.value, { editedFields: () => props.editedFields, }) -watch(open, () => formRef.value?.clearValidate()) - async function requestSave() { if (props.saving || !props.selectedCount || props.groupsLoading || !await formRef.value?.validate().catch(() => false)) return @@ -81,10 +79,12 @@ const schedulingMode = computed({