mirror of
https://github.com/fawney19/Aether.git
synced 2026-09-10 13:10:21 +08:00
refactor(health): add dashboard overview and related drill-down
- Replace health monitor tabs with a dashboard layout - Add related health drill-down for endpoint, model, and provider cards - Render provider health as cards and hide empty monitors
This commit is contained in:
@@ -21,6 +21,7 @@ pub(crate) fn mount_public_support_routes(router: Router<AppState>) -> Router<Ap
|
||||
.route("/api/public/global-models", get(proxy_request))
|
||||
.route("/api/public/health/api-formats", get(proxy_request))
|
||||
.route("/api/public/health/models", get(proxy_request))
|
||||
.route("/api/public/health/related", get(proxy_request))
|
||||
.route("/api/modules/auth-status", get(proxy_request))
|
||||
.route("/api/capabilities", get(proxy_request))
|
||||
.route("/api/capabilities/user-configurable", get(proxy_request))
|
||||
|
||||
@@ -94,6 +94,7 @@ pub(crate) const RUST_FRONTDOOR_OWNED_ROUTE_PATTERNS: &[&str] = &[
|
||||
"/api/public/global-models",
|
||||
"/api/public/health/api-formats",
|
||||
"/api/public/health/models",
|
||||
"/api/public/health/related",
|
||||
"/api/oauth/providers",
|
||||
"/api/oauth/{provider_type}/authorize",
|
||||
"/api/oauth/{provider_type}/callback",
|
||||
|
||||
@@ -81,6 +81,16 @@ pub(super) fn classify_admin_endpoints_family_route(
|
||||
"admin:endpoints_health",
|
||||
false,
|
||||
))
|
||||
} else if method == http::Method::GET
|
||||
&& normalized_path == "/api/admin/endpoints/health/related"
|
||||
{
|
||||
Some(classified(
|
||||
"admin_proxy",
|
||||
"endpoints_health",
|
||||
"health_related",
|
||||
"admin:endpoints_health",
|
||||
false,
|
||||
))
|
||||
} else if method == http::Method::GET
|
||||
&& normalized_path.starts_with("/api/admin/endpoints/rpm/key/")
|
||||
{
|
||||
|
||||
@@ -157,6 +157,7 @@ pub(super) fn classify_public_support_route(
|
||||
| "/api/public/global-models"
|
||||
| "/api/public/health/api-formats"
|
||||
| "/api/public/health/models"
|
||||
| "/api/public/health/related"
|
||||
)
|
||||
{
|
||||
let route_kind = match normalized_path {
|
||||
@@ -168,6 +169,7 @@ pub(super) fn classify_public_support_route(
|
||||
"/api/public/global-models" => "global_models",
|
||||
"/api/public/health/api-formats" => "health_api_formats",
|
||||
"/api/public/health/models" => "health_models",
|
||||
"/api/public/health/related" => "health_related",
|
||||
_ => "site_info",
|
||||
};
|
||||
Some(classified(
|
||||
|
||||
@@ -140,6 +140,25 @@ fn classifies_admin_endpoint_health_providers_as_admin_proxy_route() {
|
||||
assert!(!decision.is_execution_runtime_candidate());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn classifies_admin_endpoint_health_related_as_admin_proxy_route() {
|
||||
let headers = headers(&[]);
|
||||
let uri: Uri = "/api/admin/endpoints/health/related?dimension=model&value=gpt-5"
|
||||
.parse()
|
||||
.expect("uri should parse");
|
||||
let decision =
|
||||
classify_control_route(&http::Method::GET, &uri, &headers).expect("route should classify");
|
||||
|
||||
assert_eq!(decision.route_class.as_deref(), Some("admin_proxy"));
|
||||
assert_eq!(decision.route_family.as_deref(), Some("endpoints_health"));
|
||||
assert_eq!(decision.route_kind.as_deref(), Some("health_related"));
|
||||
assert_eq!(
|
||||
decision.auth_endpoint_signature.as_deref(),
|
||||
Some("admin:endpoints_health")
|
||||
);
|
||||
assert!(!decision.is_execution_runtime_candidate());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn classifies_admin_endpoint_key_rpm_as_admin_proxy_route() {
|
||||
let headers = headers(&[]);
|
||||
|
||||
@@ -757,6 +757,25 @@ fn classifies_public_catalog_health_models_as_public_support_route() {
|
||||
assert!(!decision.is_execution_runtime_candidate());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn classifies_public_catalog_health_related_as_public_support_route() {
|
||||
let headers = headers(&[]);
|
||||
let uri: Uri = "/api/public/health/related?dimension=endpoint&value=openai%3Achat"
|
||||
.parse()
|
||||
.expect("uri should parse");
|
||||
let decision =
|
||||
classify_control_route(&http::Method::GET, &uri, &headers).expect("route should classify");
|
||||
|
||||
assert_eq!(decision.route_class.as_deref(), Some("public_support"));
|
||||
assert_eq!(decision.route_family.as_deref(), Some("public_catalog"));
|
||||
assert_eq!(decision.route_kind.as_deref(), Some("health_related"));
|
||||
assert_eq!(
|
||||
decision.auth_endpoint_signature.as_deref(),
|
||||
Some("public:catalog")
|
||||
);
|
||||
assert!(!decision.is_execution_runtime_candidate());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn classifies_auth_registration_settings_as_public_support_route() {
|
||||
let headers = headers(&[]);
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
use super::extractors::{admin_health_key_id, admin_recover_key_id};
|
||||
use crate::handlers::admin::request::{AdminAppState, AdminRequestContext};
|
||||
use crate::handlers::admin::shared::query_param_value;
|
||||
use crate::handlers::public::{ApiFormatHealthMonitorOptions, ModelHealthMonitorOptions};
|
||||
use crate::handlers::public::{
|
||||
ApiFormatHealthMonitorOptions, HealthMonitorRelationDimension, ModelHealthMonitorOptions,
|
||||
};
|
||||
use crate::GatewayError;
|
||||
use axum::{
|
||||
body::Body,
|
||||
@@ -22,6 +24,14 @@ fn build_admin_endpoint_health_data_unavailable_response() -> Response<Body> {
|
||||
.into_response()
|
||||
}
|
||||
|
||||
fn build_admin_endpoint_health_bad_request_response(detail: &str) -> Response<Body> {
|
||||
(
|
||||
http::StatusCode::BAD_REQUEST,
|
||||
Json(json!({ "detail": detail })),
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
|
||||
pub(super) async fn maybe_build_local_admin_endpoints_health_response(
|
||||
state: &AdminAppState<'_>,
|
||||
request_context: &AdminRequestContext<'_>,
|
||||
@@ -231,6 +241,55 @@ pub(super) async fn maybe_build_local_admin_endpoints_health_response(
|
||||
return Ok(Some(Json(payload).into_response()));
|
||||
}
|
||||
|
||||
if decision.route_family.as_deref() == Some("endpoints_health")
|
||||
&& decision.route_kind.as_deref() == Some("health_related")
|
||||
&& request_context.path() == "/api/admin/endpoints/health/related"
|
||||
{
|
||||
if !state.has_usage_data_reader() {
|
||||
return Ok(Some(build_admin_endpoint_health_data_unavailable_response()));
|
||||
}
|
||||
let Some(dimension) = query_param_value(request_context.query_string(), "dimension")
|
||||
.and_then(|value| HealthMonitorRelationDimension::parse(&value))
|
||||
else {
|
||||
return Ok(Some(build_admin_endpoint_health_bad_request_response(
|
||||
"dimension 必须是 endpoint、model 或 provider",
|
||||
)));
|
||||
};
|
||||
let Some(value) = query_param_value(request_context.query_string(), "value")
|
||||
.map(|value| value.trim().to_string())
|
||||
.filter(|value| !value.is_empty())
|
||||
else {
|
||||
return Ok(Some(build_admin_endpoint_health_bad_request_response(
|
||||
"value 不能为空",
|
||||
)));
|
||||
};
|
||||
let lookback_hours = query_param_value(request_context.query_string(), "lookback_hours")
|
||||
.and_then(|value| value.parse::<u64>().ok())
|
||||
.filter(|value| (1..=72).contains(value))
|
||||
.unwrap_or(6);
|
||||
let related_limit = query_param_value(request_context.query_string(), "related_limit")
|
||||
.and_then(|value| value.parse::<usize>().ok())
|
||||
.filter(|value| (1..=50).contains(value))
|
||||
.unwrap_or(8);
|
||||
let per_item_limit = query_param_value(request_context.query_string(), "per_item_limit")
|
||||
.and_then(|value| value.parse::<usize>().ok())
|
||||
.filter(|value| (10..=200).contains(value))
|
||||
.unwrap_or(100);
|
||||
let Some(payload) = state
|
||||
.build_related_health_monitor_payload(
|
||||
lookback_hours,
|
||||
dimension,
|
||||
&value,
|
||||
related_limit,
|
||||
per_item_limit,
|
||||
)
|
||||
.await
|
||||
else {
|
||||
return Ok(Some(build_admin_endpoint_health_data_unavailable_response()));
|
||||
};
|
||||
return Ok(Some(Json(payload).into_response()));
|
||||
}
|
||||
|
||||
if decision.route_family.as_deref() == Some("endpoints_health")
|
||||
&& decision.route_kind.as_deref() == Some("health_status")
|
||||
&& request_context.path() == "/api/admin/endpoints/health/status"
|
||||
|
||||
@@ -276,6 +276,26 @@ impl<'a> AdminAppState<'a> {
|
||||
.await
|
||||
}
|
||||
|
||||
pub(crate) async fn build_related_health_monitor_payload(
|
||||
&self,
|
||||
lookback_hours: u64,
|
||||
dimension: crate::handlers::public::HealthMonitorRelationDimension,
|
||||
value: &str,
|
||||
related_limit: usize,
|
||||
per_item_limit: usize,
|
||||
) -> Option<serde_json::Value> {
|
||||
crate::handlers::public::build_related_health_monitor_payload(
|
||||
self.app,
|
||||
lookback_hours,
|
||||
dimension,
|
||||
value,
|
||||
related_limit,
|
||||
per_item_limit,
|
||||
true,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
pub(crate) async fn execute_execution_runtime_sync_plan(
|
||||
&self,
|
||||
trace_id: Option<&str>,
|
||||
|
||||
@@ -337,6 +337,8 @@ pub(crate) async fn build_api_format_health_monitor_payload(
|
||||
created_until_unix_secs: now_unix_secs,
|
||||
user_id: None,
|
||||
provider_name: None,
|
||||
model: None,
|
||||
api_format: None,
|
||||
exclude_status_codes: vec![USER_CANCELLED_STATUS_CODE],
|
||||
group_by: UsageBreakdownGroupBy::ApiFormat,
|
||||
})
|
||||
@@ -628,6 +630,8 @@ pub(crate) async fn build_model_health_monitor_payload(
|
||||
created_until_unix_secs: now_unix_secs,
|
||||
user_id: None,
|
||||
provider_name: None,
|
||||
model: None,
|
||||
api_format: None,
|
||||
exclude_status_codes: vec![USER_CANCELLED_STATUS_CODE],
|
||||
group_by: UsageBreakdownGroupBy::Model,
|
||||
})
|
||||
@@ -746,6 +750,8 @@ pub(crate) async fn build_provider_health_monitor_payload(
|
||||
created_until_unix_secs: now_unix_secs,
|
||||
user_id: None,
|
||||
provider_name: None,
|
||||
model: None,
|
||||
api_format: None,
|
||||
exclude_status_codes: vec![USER_CANCELLED_STATUS_CODE],
|
||||
group_by: UsageBreakdownGroupBy::Provider,
|
||||
})
|
||||
@@ -795,6 +801,465 @@ pub(crate) async fn build_provider_health_monitor_payload(
|
||||
}))
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum HealthMonitorRelationDimension {
|
||||
Endpoint,
|
||||
Model,
|
||||
Provider,
|
||||
}
|
||||
|
||||
impl HealthMonitorRelationDimension {
|
||||
pub(crate) fn parse(value: &str) -> Option<Self> {
|
||||
match value.trim().to_ascii_lowercase().as_str() {
|
||||
"endpoint" | "api_format" | "api-format" => Some(Self::Endpoint),
|
||||
"model" => Some(Self::Model),
|
||||
"provider" => Some(Self::Provider),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::Endpoint => "endpoint",
|
||||
Self::Model => "model",
|
||||
Self::Provider => "provider",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn build_related_health_monitor_payload(
|
||||
state: &AppState,
|
||||
lookback_hours: u64,
|
||||
dimension: HealthMonitorRelationDimension,
|
||||
value: &str,
|
||||
related_limit: usize,
|
||||
per_item_limit: usize,
|
||||
include_provider_info: bool,
|
||||
) -> Option<serde_json::Value> {
|
||||
if !state.has_usage_data_reader() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let value = value.trim();
|
||||
if value.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let now_unix_secs = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map(|duration| duration.as_secs())
|
||||
.unwrap_or_default();
|
||||
let since_unix_secs = now_unix_secs.saturating_sub(lookback_hours * 3600);
|
||||
let related_limit = related_limit.max(1);
|
||||
let per_item_limit = per_item_limit.max(1);
|
||||
|
||||
let mut related_endpoints = Vec::new();
|
||||
let mut related_models = Vec::new();
|
||||
let mut related_providers = Vec::new();
|
||||
|
||||
match dimension {
|
||||
HealthMonitorRelationDimension::Endpoint => {
|
||||
let api_format = value.to_string();
|
||||
related_models = build_related_health_items(
|
||||
state,
|
||||
breakdown_summary_query(
|
||||
since_unix_secs,
|
||||
now_unix_secs,
|
||||
None,
|
||||
None,
|
||||
Some(api_format.clone()),
|
||||
UsageBreakdownGroupBy::Model,
|
||||
),
|
||||
since_unix_secs,
|
||||
now_unix_secs,
|
||||
related_limit,
|
||||
per_item_limit,
|
||||
"model",
|
||||
{
|
||||
let api_format = api_format.clone();
|
||||
move |row| {
|
||||
usage_audit_query(
|
||||
since_unix_secs,
|
||||
now_unix_secs,
|
||||
None,
|
||||
Some(row.group_key.clone()),
|
||||
Some(api_format.clone()),
|
||||
per_item_limit,
|
||||
)
|
||||
}
|
||||
},
|
||||
|row, events| related_model_display_meta(row, events),
|
||||
)
|
||||
.await;
|
||||
|
||||
if include_provider_info {
|
||||
let api_format = value.to_string();
|
||||
related_providers = build_related_health_items(
|
||||
state,
|
||||
breakdown_summary_query(
|
||||
since_unix_secs,
|
||||
now_unix_secs,
|
||||
None,
|
||||
None,
|
||||
Some(api_format.clone()),
|
||||
UsageBreakdownGroupBy::Provider,
|
||||
),
|
||||
since_unix_secs,
|
||||
now_unix_secs,
|
||||
related_limit,
|
||||
per_item_limit,
|
||||
"provider",
|
||||
{
|
||||
let api_format = api_format.clone();
|
||||
move |row| {
|
||||
usage_audit_query(
|
||||
since_unix_secs,
|
||||
now_unix_secs,
|
||||
Some(row.group_key.clone()),
|
||||
None,
|
||||
Some(api_format.clone()),
|
||||
per_item_limit,
|
||||
)
|
||||
}
|
||||
},
|
||||
related_provider_display_meta,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
HealthMonitorRelationDimension::Model => {
|
||||
let model = value.to_string();
|
||||
related_endpoints = build_related_health_items(
|
||||
state,
|
||||
breakdown_summary_query(
|
||||
since_unix_secs,
|
||||
now_unix_secs,
|
||||
None,
|
||||
Some(model.clone()),
|
||||
None,
|
||||
UsageBreakdownGroupBy::ApiFormat,
|
||||
),
|
||||
since_unix_secs,
|
||||
now_unix_secs,
|
||||
related_limit,
|
||||
per_item_limit,
|
||||
"endpoint",
|
||||
{
|
||||
let model = model.clone();
|
||||
move |row| {
|
||||
usage_audit_query(
|
||||
since_unix_secs,
|
||||
now_unix_secs,
|
||||
None,
|
||||
Some(model.clone()),
|
||||
Some(row.group_key.clone()),
|
||||
per_item_limit,
|
||||
)
|
||||
}
|
||||
},
|
||||
related_endpoint_display_meta,
|
||||
)
|
||||
.await;
|
||||
|
||||
if include_provider_info {
|
||||
let model = value.to_string();
|
||||
related_providers = build_related_health_items(
|
||||
state,
|
||||
breakdown_summary_query(
|
||||
since_unix_secs,
|
||||
now_unix_secs,
|
||||
None,
|
||||
Some(model.clone()),
|
||||
None,
|
||||
UsageBreakdownGroupBy::Provider,
|
||||
),
|
||||
since_unix_secs,
|
||||
now_unix_secs,
|
||||
related_limit,
|
||||
per_item_limit,
|
||||
"provider",
|
||||
{
|
||||
let model = model.clone();
|
||||
move |row| {
|
||||
usage_audit_query(
|
||||
since_unix_secs,
|
||||
now_unix_secs,
|
||||
Some(row.group_key.clone()),
|
||||
Some(model.clone()),
|
||||
None,
|
||||
per_item_limit,
|
||||
)
|
||||
}
|
||||
},
|
||||
related_provider_display_meta,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
HealthMonitorRelationDimension::Provider => {
|
||||
let provider_name = value.to_string();
|
||||
related_endpoints = build_related_health_items(
|
||||
state,
|
||||
breakdown_summary_query(
|
||||
since_unix_secs,
|
||||
now_unix_secs,
|
||||
Some(provider_name.clone()),
|
||||
None,
|
||||
None,
|
||||
UsageBreakdownGroupBy::ApiFormat,
|
||||
),
|
||||
since_unix_secs,
|
||||
now_unix_secs,
|
||||
related_limit,
|
||||
per_item_limit,
|
||||
"endpoint",
|
||||
{
|
||||
let provider_name = provider_name.clone();
|
||||
move |row| {
|
||||
usage_audit_query(
|
||||
since_unix_secs,
|
||||
now_unix_secs,
|
||||
Some(provider_name.clone()),
|
||||
None,
|
||||
Some(row.group_key.clone()),
|
||||
per_item_limit,
|
||||
)
|
||||
}
|
||||
},
|
||||
related_endpoint_display_meta,
|
||||
)
|
||||
.await;
|
||||
|
||||
let provider_name = value.to_string();
|
||||
related_models = build_related_health_items(
|
||||
state,
|
||||
breakdown_summary_query(
|
||||
since_unix_secs,
|
||||
now_unix_secs,
|
||||
Some(provider_name.clone()),
|
||||
None,
|
||||
None,
|
||||
UsageBreakdownGroupBy::Model,
|
||||
),
|
||||
since_unix_secs,
|
||||
now_unix_secs,
|
||||
related_limit,
|
||||
per_item_limit,
|
||||
"model",
|
||||
{
|
||||
let provider_name = provider_name.clone();
|
||||
move |row| {
|
||||
usage_audit_query(
|
||||
since_unix_secs,
|
||||
now_unix_secs,
|
||||
Some(provider_name.clone()),
|
||||
Some(row.group_key.clone()),
|
||||
None,
|
||||
per_item_limit,
|
||||
)
|
||||
}
|
||||
},
|
||||
|row, events| related_model_display_meta(row, events),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
Some(json!({
|
||||
"generated_at": unix_secs_to_rfc3339(now_unix_secs),
|
||||
"dimension": dimension.as_str(),
|
||||
"value": value,
|
||||
"related_endpoints": related_endpoints,
|
||||
"related_models": related_models,
|
||||
"related_providers": related_providers,
|
||||
}))
|
||||
}
|
||||
|
||||
fn breakdown_summary_query(
|
||||
created_from_unix_secs: u64,
|
||||
created_until_unix_secs: u64,
|
||||
provider_name: Option<String>,
|
||||
model: Option<String>,
|
||||
api_format: Option<String>,
|
||||
group_by: UsageBreakdownGroupBy,
|
||||
) -> UsageBreakdownSummaryQuery {
|
||||
UsageBreakdownSummaryQuery {
|
||||
created_from_unix_secs,
|
||||
created_until_unix_secs,
|
||||
user_id: None,
|
||||
provider_name,
|
||||
model,
|
||||
api_format,
|
||||
exclude_status_codes: vec![USER_CANCELLED_STATUS_CODE],
|
||||
group_by,
|
||||
}
|
||||
}
|
||||
|
||||
fn usage_audit_query(
|
||||
created_from_unix_secs: u64,
|
||||
created_until_unix_secs: u64,
|
||||
provider_name: Option<String>,
|
||||
model: Option<String>,
|
||||
api_format: Option<String>,
|
||||
limit: usize,
|
||||
) -> UsageAuditListQuery {
|
||||
UsageAuditListQuery {
|
||||
created_from_unix_secs: Some(created_from_unix_secs),
|
||||
created_until_unix_secs: Some(created_until_unix_secs),
|
||||
provider_name,
|
||||
model,
|
||||
api_format,
|
||||
exclude_status_codes: vec![USER_CANCELLED_STATUS_CODE],
|
||||
limit: Some(limit),
|
||||
newest_first: true,
|
||||
..UsageAuditListQuery::default()
|
||||
}
|
||||
}
|
||||
|
||||
async fn build_related_health_items<F, G>(
|
||||
state: &AppState,
|
||||
query: UsageBreakdownSummaryQuery,
|
||||
since_unix_secs: u64,
|
||||
now_unix_secs: u64,
|
||||
related_limit: usize,
|
||||
per_item_limit: usize,
|
||||
kind: &'static str,
|
||||
build_events_query: F,
|
||||
build_display_meta: G,
|
||||
) -> Vec<serde_json::Value>
|
||||
where
|
||||
F: Fn(&StoredUsageBreakdownSummaryRow) -> UsageAuditListQuery,
|
||||
G: Fn(&StoredUsageBreakdownSummaryRow, &[StoredRequestUsageAudit]) -> (String, Option<String>),
|
||||
{
|
||||
let mut rows = state
|
||||
.summarize_usage_breakdown(&query)
|
||||
.await
|
||||
.ok()
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.filter(|row| !row.group_key.trim().is_empty())
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
rows.sort_by(|left, right| {
|
||||
related_health_sort_rank(left)
|
||||
.cmp(&related_health_sort_rank(right))
|
||||
.then_with(|| right.request_count.cmp(&left.request_count))
|
||||
.then_with(|| left.group_key.cmp(&right.group_key))
|
||||
});
|
||||
|
||||
let mut items = Vec::new();
|
||||
for row in rows.into_iter().take(related_limit) {
|
||||
let events = state
|
||||
.list_usage_audits(&build_events_query(&row))
|
||||
.await
|
||||
.ok()
|
||||
.unwrap_or_default();
|
||||
let (display_name, meta_text) = build_display_meta(&row, &events);
|
||||
items.push(related_health_item_payload(
|
||||
kind,
|
||||
&row,
|
||||
&events,
|
||||
display_name,
|
||||
meta_text,
|
||||
since_unix_secs,
|
||||
now_unix_secs,
|
||||
));
|
||||
}
|
||||
|
||||
items
|
||||
}
|
||||
|
||||
fn related_health_item_payload(
|
||||
kind: &'static str,
|
||||
row: &StoredUsageBreakdownSummaryRow,
|
||||
events: &[StoredRequestUsageAudit],
|
||||
display_name: String,
|
||||
meta_text: Option<String>,
|
||||
since_unix_secs: u64,
|
||||
now_unix_secs: u64,
|
||||
) -> serde_json::Value {
|
||||
let (timeline, time_range_start, time_range_end) = build_model_health_timeline(
|
||||
events,
|
||||
since_unix_secs,
|
||||
now_unix_secs,
|
||||
MODEL_HEALTH_TIMELINE_SEGMENTS,
|
||||
);
|
||||
let total_attempts = row.request_count;
|
||||
let success_count = row.success_count.min(total_attempts);
|
||||
let failed_count = total_attempts.saturating_sub(success_count);
|
||||
let success_rate = if total_attempts > 0 {
|
||||
success_count as f64 / total_attempts as f64
|
||||
} else {
|
||||
1.0
|
||||
};
|
||||
let last_event_at = events
|
||||
.first()
|
||||
.and_then(|item| unix_secs_to_rfc3339(item.created_at_unix_ms));
|
||||
|
||||
json!({
|
||||
"kind": kind,
|
||||
"key": row.group_key.clone(),
|
||||
"display_name": display_name,
|
||||
"meta_text": meta_text,
|
||||
"total_attempts": total_attempts,
|
||||
"success_count": success_count,
|
||||
"failed_count": failed_count,
|
||||
"success_rate": success_rate,
|
||||
"avg_latency_ms": model_health_average_latency_ms(row),
|
||||
"avg_first_byte_ms": model_health_average_first_byte_ms(events),
|
||||
"avg_tps": model_health_average_tps(row),
|
||||
"last_event_at": last_event_at,
|
||||
"timeline": timeline,
|
||||
"time_range_start": unix_secs_to_rfc3339(time_range_start),
|
||||
"time_range_end": unix_secs_to_rfc3339(time_range_end),
|
||||
})
|
||||
}
|
||||
|
||||
fn related_model_display_meta(
|
||||
row: &StoredUsageBreakdownSummaryRow,
|
||||
events: &[StoredRequestUsageAudit],
|
||||
) -> (String, Option<String>) {
|
||||
let provider_count = model_health_provider_count(events);
|
||||
let meta_text = if provider_count > 0 {
|
||||
Some(format!("{provider_count} 个提供商"))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
(model_health_display_name(&row.group_key), meta_text)
|
||||
}
|
||||
|
||||
fn related_provider_display_meta(
|
||||
row: &StoredUsageBreakdownSummaryRow,
|
||||
_events: &[StoredRequestUsageAudit],
|
||||
) -> (String, Option<String>) {
|
||||
(row.group_key.clone(), None)
|
||||
}
|
||||
|
||||
fn related_endpoint_display_meta(
|
||||
row: &StoredUsageBreakdownSummaryRow,
|
||||
_events: &[StoredRequestUsageAudit],
|
||||
) -> (String, Option<String>) {
|
||||
(
|
||||
api_format_display_name(&row.group_key),
|
||||
Some(public_api_format_local_path(&row.group_key).to_string()),
|
||||
)
|
||||
}
|
||||
|
||||
fn related_health_sort_rank(row: &StoredUsageBreakdownSummaryRow) -> u8 {
|
||||
if row.request_count == 0 {
|
||||
return 3;
|
||||
}
|
||||
let success_count = row.success_count.min(row.request_count);
|
||||
let success_rate = success_count as f64 / row.request_count as f64;
|
||||
if success_rate < 0.8 {
|
||||
0
|
||||
} else if success_rate < 0.95 {
|
||||
1
|
||||
} else {
|
||||
2
|
||||
}
|
||||
}
|
||||
|
||||
async fn build_provider_health_payload(
|
||||
state: &AppState,
|
||||
provider: StoredProviderCatalogProvider,
|
||||
@@ -810,6 +1275,8 @@ async fn build_provider_health_payload(
|
||||
created_until_unix_secs: now_unix_secs,
|
||||
user_id: None,
|
||||
provider_name: Some(provider.name.clone()),
|
||||
model: None,
|
||||
api_format: None,
|
||||
exclude_status_codes: vec![USER_CANCELLED_STATUS_CODE],
|
||||
group_by: UsageBreakdownGroupBy::Model,
|
||||
})
|
||||
|
||||
@@ -10,10 +10,11 @@ pub(crate) use self::catalog_helpers::{
|
||||
admin_requested_force_stream, api_format_display_name, build_api_format_health_monitor_payload,
|
||||
build_model_health_monitor_payload, build_provider_health_monitor_payload,
|
||||
build_public_catalog_models_payload, build_public_catalog_search_models_payload,
|
||||
build_public_health_timeline, build_public_providers_payload, normalize_admin_base_url,
|
||||
provider_key_api_formats, request_candidate_event_unix_ms, request_candidate_status_label,
|
||||
build_public_health_timeline, build_public_providers_payload,
|
||||
build_related_health_monitor_payload, normalize_admin_base_url, provider_key_api_formats,
|
||||
request_candidate_event_unix_ms, request_candidate_status_label,
|
||||
sanitize_public_model_config_for_user, ApiFormatHealthMonitorOptions,
|
||||
ModelHealthMonitorOptions,
|
||||
HealthMonitorRelationDimension, ModelHealthMonitorOptions,
|
||||
};
|
||||
pub(crate) use self::system_modules_helpers::{
|
||||
build_admin_keys_grouped_by_format_payload, build_public_auth_modules_status_payload,
|
||||
|
||||
@@ -2,9 +2,10 @@ use super::{
|
||||
build_api_format_health_monitor_payload, build_model_health_monitor_payload,
|
||||
build_public_auth_modules_status_payload, build_public_catalog_models_payload,
|
||||
build_public_catalog_search_models_payload, build_public_providers_payload,
|
||||
capability_detail_by_name, ldap_module_config_is_valid, sanitize_public_model_config_for_user,
|
||||
serialize_public_capability, supported_capability_names, ApiFormatHealthMonitorOptions,
|
||||
ModelHealthMonitorOptions, PUBLIC_CAPABILITY_DEFINITIONS,
|
||||
build_related_health_monitor_payload, capability_detail_by_name, ldap_module_config_is_valid,
|
||||
sanitize_public_model_config_for_user, serialize_public_capability, supported_capability_names,
|
||||
ApiFormatHealthMonitorOptions, HealthMonitorRelationDimension, ModelHealthMonitorOptions,
|
||||
PUBLIC_CAPABILITY_DEFINITIONS,
|
||||
};
|
||||
use crate::control::GatewayPublicRequestContext;
|
||||
use crate::handlers::shared::{
|
||||
@@ -477,6 +478,77 @@ pub(crate) async fn maybe_build_local_public_support_response(
|
||||
.await?;
|
||||
return Some(Json(payload).into_response());
|
||||
}
|
||||
|
||||
if decision.route_kind.as_deref() == Some("health_related")
|
||||
&& request_context.request_path == "/api/public/health/related"
|
||||
{
|
||||
let Some(dimension) =
|
||||
query_param_value(request_context.request_query_string.as_deref(), "dimension")
|
||||
.and_then(|value| HealthMonitorRelationDimension::parse(&value))
|
||||
else {
|
||||
return Some(
|
||||
(
|
||||
http::StatusCode::BAD_REQUEST,
|
||||
Json(json!({ "detail": "dimension 必须是 endpoint 或 model" })),
|
||||
)
|
||||
.into_response(),
|
||||
);
|
||||
};
|
||||
if matches!(dimension, HealthMonitorRelationDimension::Provider) {
|
||||
return Some(
|
||||
(
|
||||
http::StatusCode::BAD_REQUEST,
|
||||
Json(json!({ "detail": "公开健康监控不支持 provider 维度" })),
|
||||
)
|
||||
.into_response(),
|
||||
);
|
||||
}
|
||||
let Some(value) =
|
||||
query_param_value(request_context.request_query_string.as_deref(), "value")
|
||||
.map(|value| value.trim().to_string())
|
||||
.filter(|value| !value.is_empty())
|
||||
else {
|
||||
return Some(
|
||||
(
|
||||
http::StatusCode::BAD_REQUEST,
|
||||
Json(json!({ "detail": "value 不能为空" })),
|
||||
)
|
||||
.into_response(),
|
||||
);
|
||||
};
|
||||
let lookback_hours = query_param_value(
|
||||
request_context.request_query_string.as_deref(),
|
||||
"lookback_hours",
|
||||
)
|
||||
.and_then(|value| value.parse::<u64>().ok())
|
||||
.filter(|value| (1..=168).contains(value))
|
||||
.unwrap_or(6);
|
||||
let related_limit = query_param_value(
|
||||
request_context.request_query_string.as_deref(),
|
||||
"related_limit",
|
||||
)
|
||||
.and_then(|value| value.parse::<usize>().ok())
|
||||
.filter(|value| (1..=50).contains(value))
|
||||
.unwrap_or(8);
|
||||
let per_item_limit = query_param_value(
|
||||
request_context.request_query_string.as_deref(),
|
||||
"per_item_limit",
|
||||
)
|
||||
.and_then(|value| value.parse::<usize>().ok())
|
||||
.filter(|value| (10..=500).contains(value))
|
||||
.unwrap_or(100);
|
||||
let payload = build_related_health_monitor_payload(
|
||||
state,
|
||||
lookback_hours,
|
||||
dimension,
|
||||
&value,
|
||||
related_limit,
|
||||
per_item_limit,
|
||||
false,
|
||||
)
|
||||
.await?;
|
||||
return Some(Json(payload).into_response());
|
||||
}
|
||||
}
|
||||
|
||||
if decision.route_family.as_deref() == Some("capabilities") {
|
||||
|
||||
@@ -848,6 +848,8 @@ pub(super) async fn handle_users_me_usage_get(
|
||||
created_until_unix_secs,
|
||||
user_id: Some(auth.user.id.clone()),
|
||||
provider_name: None,
|
||||
model: None,
|
||||
api_format: None,
|
||||
exclude_status_codes: Vec::new(),
|
||||
group_by: UsageBreakdownGroupBy::Model,
|
||||
})
|
||||
@@ -869,6 +871,8 @@ pub(super) async fn handle_users_me_usage_get(
|
||||
created_until_unix_secs,
|
||||
user_id: Some(auth.user.id.clone()),
|
||||
provider_name: None,
|
||||
model: None,
|
||||
api_format: None,
|
||||
exclude_status_codes: Vec::new(),
|
||||
group_by: UsageBreakdownGroupBy::Provider,
|
||||
})
|
||||
@@ -890,6 +894,8 @@ pub(super) async fn handle_users_me_usage_get(
|
||||
created_until_unix_secs,
|
||||
user_id: Some(auth.user.id.clone()),
|
||||
provider_name: None,
|
||||
model: None,
|
||||
api_format: None,
|
||||
exclude_status_codes: Vec::new(),
|
||||
group_by: UsageBreakdownGroupBy::ApiFormat,
|
||||
})
|
||||
|
||||
@@ -988,6 +988,8 @@ pub struct UsageBreakdownSummaryQuery {
|
||||
pub created_until_unix_secs: u64,
|
||||
pub user_id: Option<String>,
|
||||
pub provider_name: Option<String>,
|
||||
pub model: Option<String>,
|
||||
pub api_format: Option<String>,
|
||||
pub exclude_status_codes: Vec<u16>,
|
||||
pub group_by: UsageBreakdownGroupBy,
|
||||
}
|
||||
|
||||
@@ -552,6 +552,16 @@ fn usage_matches_breakdown_summary_query(
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if let Some(model) = query.model.as_deref() {
|
||||
if item.model != model {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if let Some(api_format) = query.api_format.as_deref() {
|
||||
if item.api_format.as_deref() != Some(api_format) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if item
|
||||
.status_code
|
||||
.is_some_and(|status_code| query.exclude_status_codes.contains(&status_code))
|
||||
|
||||
@@ -4841,6 +4841,18 @@ WITH filtered_usage AS (
|
||||
.push("\"usage\".provider_name = ")
|
||||
.push_bind(provider_name.to_string());
|
||||
}
|
||||
if let Some(model) = query.model.as_deref() {
|
||||
builder.push(if has_where { " AND " } else { " WHERE " });
|
||||
builder
|
||||
.push("\"usage\".model = ")
|
||||
.push_bind(model.to_string());
|
||||
}
|
||||
if let Some(api_format) = query.api_format.as_deref() {
|
||||
builder.push(if has_where { " AND " } else { " WHERE " });
|
||||
builder
|
||||
.push("\"usage\".api_format = ")
|
||||
.push_bind(api_format.to_string());
|
||||
}
|
||||
push_postgres_usage_excluded_status_codes(
|
||||
&mut builder,
|
||||
&mut has_where,
|
||||
@@ -4944,6 +4956,12 @@ ORDER BY request_count DESC, group_key ASC
|
||||
if query.provider_name.is_some() {
|
||||
return self.summarize_usage_breakdown_raw(query).await;
|
||||
}
|
||||
if query.model.is_some() {
|
||||
return self.summarize_usage_breakdown_raw(query).await;
|
||||
}
|
||||
if query.api_format.is_some() {
|
||||
return self.summarize_usage_breakdown_raw(query).await;
|
||||
}
|
||||
let Some(user_id) = query.user_id.as_deref() else {
|
||||
return self.summarize_usage_breakdown_raw(query).await;
|
||||
};
|
||||
@@ -4966,6 +4984,8 @@ ORDER BY request_count DESC, group_key ASC
|
||||
created_until_unix_secs: dashboard_utc_to_unix_secs(raw_end),
|
||||
user_id: Some(user_id.to_string()),
|
||||
provider_name: None,
|
||||
model: None,
|
||||
api_format: None,
|
||||
exclude_status_codes: query.exclude_status_codes.clone(),
|
||||
group_by: query.group_by,
|
||||
})
|
||||
@@ -4990,6 +5010,8 @@ ORDER BY request_count DESC, group_key ASC
|
||||
created_until_unix_secs: dashboard_utc_to_unix_secs(raw_end),
|
||||
user_id: Some(user_id.to_string()),
|
||||
provider_name: None,
|
||||
model: None,
|
||||
api_format: None,
|
||||
exclude_status_codes: query.exclude_status_codes.clone(),
|
||||
group_by: query.group_by,
|
||||
})
|
||||
|
||||
@@ -2490,6 +2490,18 @@ FROM "usage"
|
||||
"provider_name",
|
||||
query.provider_name.as_deref(),
|
||||
);
|
||||
push_sqlite_usage_optional_text_filter(
|
||||
&mut builder,
|
||||
&mut has_where,
|
||||
"model",
|
||||
query.model.as_deref(),
|
||||
);
|
||||
push_sqlite_usage_optional_text_filter(
|
||||
&mut builder,
|
||||
&mut has_where,
|
||||
"api_format",
|
||||
query.api_format.as_deref(),
|
||||
);
|
||||
push_sqlite_usage_excluded_status_codes(
|
||||
&mut builder,
|
||||
&mut has_where,
|
||||
|
||||
@@ -5,7 +5,9 @@ import type {
|
||||
EndpointStatusMonitorResponse,
|
||||
PublicEndpointStatusMonitorResponse,
|
||||
ModelStatusMonitorResponse,
|
||||
ProviderStatusMonitorResponse
|
||||
ProviderStatusMonitorResponse,
|
||||
HealthRelatedMonitorResponse,
|
||||
HealthMonitorRelatedDimension
|
||||
} from './types'
|
||||
|
||||
/**
|
||||
@@ -136,3 +138,29 @@ export async function getProviderStatusMonitor(params?: {
|
||||
})
|
||||
return response.data
|
||||
}
|
||||
|
||||
export async function getHealthRelatedMonitor(params: {
|
||||
dimension: HealthMonitorRelatedDimension
|
||||
value: string
|
||||
lookback_hours?: number
|
||||
related_limit?: number
|
||||
per_item_limit?: number
|
||||
}): Promise<HealthRelatedMonitorResponse> {
|
||||
const response = await client.get('/api/admin/endpoints/health/related', {
|
||||
params
|
||||
})
|
||||
return response.data
|
||||
}
|
||||
|
||||
export async function getPublicHealthRelatedMonitor(params: {
|
||||
dimension: Exclude<HealthMonitorRelatedDimension, 'provider'>
|
||||
value: string
|
||||
lookback_hours?: number
|
||||
related_limit?: number
|
||||
per_item_limit?: number
|
||||
}): Promise<HealthRelatedMonitorResponse> {
|
||||
const response = await client.get('/api/public/health/related', {
|
||||
params
|
||||
})
|
||||
return response.data
|
||||
}
|
||||
|
||||
@@ -676,6 +676,35 @@ export interface ProviderStatusMonitorResponse {
|
||||
providers: ProviderStatusMonitor[]
|
||||
}
|
||||
|
||||
export type HealthMonitorRelatedDimension = 'endpoint' | 'model' | 'provider'
|
||||
|
||||
export interface HealthRelatedMonitor {
|
||||
kind: HealthMonitorRelatedDimension
|
||||
key: string
|
||||
display_name: string
|
||||
meta_text?: string | null
|
||||
total_attempts: number
|
||||
success_count: number
|
||||
failed_count: number
|
||||
success_rate: number
|
||||
avg_latency_ms?: number | null
|
||||
avg_first_byte_ms?: number | null
|
||||
avg_tps?: number | null
|
||||
last_event_at?: string | null
|
||||
timeline?: string[]
|
||||
time_range_start?: string | null
|
||||
time_range_end?: string | null
|
||||
}
|
||||
|
||||
export interface HealthRelatedMonitorResponse {
|
||||
generated_at: string
|
||||
dimension: HealthMonitorRelatedDimension
|
||||
value: string
|
||||
related_endpoints: HealthRelatedMonitor[]
|
||||
related_models: HealthRelatedMonitor[]
|
||||
related_providers: HealthRelatedMonitor[]
|
||||
}
|
||||
|
||||
export type ProviderType = 'custom' | 'claude_code' | 'codex' | 'chatgpt_web' | 'gemini_cli' | 'antigravity' | 'kiro' | 'grok' | 'windsurf' | 'vertex_ai'
|
||||
|
||||
export interface ClaudeCodeAdvancedConfig {
|
||||
|
||||
@@ -88,6 +88,16 @@
|
||||
:lookback-hours="parseInt(lookbackHours)"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="mt-4 flex justify-end">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
@click="openDetails(monitor)"
|
||||
>
|
||||
查看详情
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -99,18 +109,21 @@ import { computed, ref, onMounted, watch } from 'vue'
|
||||
import { Activity, Loader2 } from 'lucide-vue-next'
|
||||
import Card from '@/components/ui/card.vue'
|
||||
import Badge from '@/components/ui/badge.vue'
|
||||
import Button from '@/components/ui/button.vue'
|
||||
import HealthMetricGrid from './HealthMetricGrid.vue'
|
||||
import HealthMonitorHeader from './HealthMonitorHeader.vue'
|
||||
import EndpointHealthTimeline from './EndpointHealthTimeline.vue'
|
||||
import { getEndpointStatusMonitor, getPublicEndpointStatusMonitor } from '@/api/endpoints/health'
|
||||
import type { EndpointStatusMonitor, PublicEndpointStatusMonitor } from '@/api/endpoints/types'
|
||||
import type { HealthMonitorDetailTarget, HealthMonitorSectionSummary } from './health-monitor-utils'
|
||||
import { useToast } from '@/composables/useToast'
|
||||
import { parseApiError } from '@/utils/errorParser'
|
||||
import { formatApiFormat } from '@/api/endpoints/types/api-format'
|
||||
import {
|
||||
formatCompactNumber,
|
||||
getHealthBadgeVariant,
|
||||
getHealthLabel
|
||||
getHealthLabel,
|
||||
summarizeHealthMonitorItems
|
||||
} from './health-monitor-utils'
|
||||
|
||||
type EndpointMonitor = EndpointStatusMonitor | PublicEndpointStatusMonitor
|
||||
@@ -125,6 +138,11 @@ const props = withDefaults(defineProps<{
|
||||
showProviderInfo: false
|
||||
})
|
||||
|
||||
const emit = defineEmits<{
|
||||
viewDetails: [target: HealthMonitorDetailTarget]
|
||||
summaryUpdated: [summary: HealthMonitorSectionSummary]
|
||||
}>()
|
||||
|
||||
const { error: showError } = useToast()
|
||||
|
||||
const loading = ref(false)
|
||||
@@ -148,6 +166,7 @@ async function loadMonitors() {
|
||||
const data = await getPublicEndpointStatusMonitor(params)
|
||||
monitors.value = data.formats || []
|
||||
}
|
||||
emitSummary()
|
||||
} catch (err: unknown) {
|
||||
showError(parseApiError(err, '加载健康监控数据失败'), '错误')
|
||||
} finally {
|
||||
@@ -175,6 +194,42 @@ function getEndpointMetaText(monitor: EndpointMonitor) {
|
||||
return attempts
|
||||
}
|
||||
|
||||
function openDetails(monitor: EndpointMonitor) {
|
||||
emit('viewDetails', {
|
||||
lookbackHours: parseInt(lookbackHours.value),
|
||||
source: {
|
||||
kind: 'endpoint',
|
||||
value: monitor.api_format,
|
||||
title: formatApiFormat(monitor.api_format),
|
||||
metaText: getEndpointDetailMetaText(monitor),
|
||||
totalAttempts: monitor.total_attempts,
|
||||
successCount: monitor.success_count,
|
||||
failedCount: monitor.failed_count,
|
||||
successRate: monitor.success_rate,
|
||||
avgLatencyMs: monitor.avg_latency_ms,
|
||||
avgFirstByteMs: monitor.avg_first_byte_ms,
|
||||
avgTps: monitor.avg_tps,
|
||||
timeline: monitor.timeline || null,
|
||||
timeRangeStart: monitor.time_range_start || null,
|
||||
timeRangeEnd: monitor.time_range_end || null
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
function getEndpointDetailMetaText(monitor: EndpointMonitor) {
|
||||
if (props.showProviderInfo && hasProviderInfo(monitor)) {
|
||||
return `${monitor.provider_count} 个提供商 / ${monitor.key_count} 个密钥`
|
||||
}
|
||||
if (hasApiPath(monitor)) {
|
||||
return monitor.api_path
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
function emitSummary() {
|
||||
emit('summaryUpdated', summarizeHealthMonitorItems(visibleMonitors.value))
|
||||
}
|
||||
|
||||
function hasProviderInfo(monitor: EndpointMonitor): monitor is EndpointStatusMonitor {
|
||||
return 'provider_count' in monitor && typeof monitor.provider_count === 'number'
|
||||
}
|
||||
|
||||
@@ -0,0 +1,304 @@
|
||||
<template>
|
||||
<Dialog
|
||||
v-model:open="isOpen"
|
||||
:title="dialogTitle"
|
||||
:description="dialogDescription"
|
||||
max-width="6xl"
|
||||
no-padding
|
||||
>
|
||||
<template #header-actions>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
@click="isOpen = false"
|
||||
>
|
||||
关闭
|
||||
</Button>
|
||||
</template>
|
||||
|
||||
<div class="max-h-[78vh] overflow-y-auto px-4 py-4 sm:px-6">
|
||||
<div
|
||||
v-if="sourceMonitor"
|
||||
class="space-y-6"
|
||||
>
|
||||
<section>
|
||||
<div class="mb-3 flex items-center justify-between gap-3">
|
||||
<div>
|
||||
<h4 class="text-sm font-semibold">
|
||||
当前健康
|
||||
</h4>
|
||||
<p class="text-xs text-muted-foreground">
|
||||
当前卡片在相同回溯窗口内的健康概况
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<HealthRelatedMonitorCard
|
||||
:monitor="sourceMonitor"
|
||||
:lookback-hours="target?.lookbackHours || 6"
|
||||
:show-detail-button="false"
|
||||
/>
|
||||
</section>
|
||||
|
||||
<div
|
||||
v-if="loading"
|
||||
class="flex items-center justify-center rounded-xl border border-dashed border-border/60 py-12 text-muted-foreground"
|
||||
>
|
||||
<Loader2 class="h-5 w-5 animate-spin" />
|
||||
<span class="ml-2 text-sm">加载关联健康...</span>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-else-if="errorMessage"
|
||||
class="rounded-xl border border-destructive/30 bg-destructive/5 p-4 text-sm text-destructive"
|
||||
>
|
||||
<div class="flex items-start gap-2">
|
||||
<AlertTriangle class="mt-0.5 h-4 w-4 flex-shrink-0" />
|
||||
<div class="min-w-0">
|
||||
<p class="font-medium">关联健康加载失败</p>
|
||||
<p class="mt-1 text-xs">{{ errorMessage }}</p>
|
||||
</div>
|
||||
</div>
|
||||
<Button
|
||||
class="mt-3"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
@click="loadRelated"
|
||||
>
|
||||
重试
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<template v-else>
|
||||
<section
|
||||
v-for="section in relatedSections"
|
||||
:key="section.key"
|
||||
class="space-y-3"
|
||||
>
|
||||
<div>
|
||||
<h4 class="text-sm font-semibold">
|
||||
{{ section.title }}
|
||||
</h4>
|
||||
<p class="text-xs text-muted-foreground">
|
||||
{{ section.description }}
|
||||
</p>
|
||||
</div>
|
||||
<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
|
||||
<HealthRelatedMonitorCard
|
||||
v-for="monitor in section.items"
|
||||
:key="`${monitor.kind}-${monitor.key}`"
|
||||
:monitor="monitor"
|
||||
:lookback-hours="target?.lookbackHours || 6"
|
||||
:generated-at="related?.generated_at || null"
|
||||
@view-details="openRelatedDetails"
|
||||
/>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<div
|
||||
v-if="relatedSections.length === 0"
|
||||
class="rounded-xl border border-dashed border-border/60 py-10 text-center text-sm text-muted-foreground"
|
||||
>
|
||||
当前时间范围内暂无关联健康数据
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
</Dialog>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, ref, watch } from 'vue'
|
||||
import { AlertTriangle, Loader2 } from 'lucide-vue-next'
|
||||
import Dialog from '@/components/ui/dialog/Dialog.vue'
|
||||
import Button from '@/components/ui/button.vue'
|
||||
import {
|
||||
getHealthRelatedMonitor,
|
||||
getPublicHealthRelatedMonitor
|
||||
} from '@/api/endpoints/health'
|
||||
import type {
|
||||
HealthRelatedMonitor,
|
||||
HealthRelatedMonitorResponse
|
||||
} from '@/api/endpoints/types'
|
||||
import { useToast } from '@/composables/useToast'
|
||||
import { parseApiError } from '@/utils/errorParser'
|
||||
import HealthRelatedMonitorCard from './HealthRelatedMonitorCard.vue'
|
||||
import type {
|
||||
HealthMonitorDetailSource,
|
||||
HealthMonitorDetailTarget
|
||||
} from './health-monitor-utils'
|
||||
|
||||
const props = defineProps<{
|
||||
open: boolean
|
||||
target: HealthMonitorDetailTarget | null
|
||||
isAdmin: boolean
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
'update:open': [value: boolean]
|
||||
viewDetails: [target: HealthMonitorDetailTarget]
|
||||
}>()
|
||||
|
||||
const { error: showError } = useToast()
|
||||
|
||||
const related = ref<HealthRelatedMonitorResponse | null>(null)
|
||||
const loading = ref(false)
|
||||
const errorMessage = ref<string | null>(null)
|
||||
let requestSeq = 0
|
||||
|
||||
const isOpen = computed({
|
||||
get: () => props.open,
|
||||
set: value => emit('update:open', value)
|
||||
})
|
||||
|
||||
const dialogTitle = computed(() => {
|
||||
if (!props.target) return '健康详情'
|
||||
return `${props.target.source.title} 详情`
|
||||
})
|
||||
|
||||
const dialogDescription = computed(() => {
|
||||
if (!props.target) return '查看关联健康维度'
|
||||
const dimensions = props.isAdmin ? '关联端点、模型与提供商健康' : '关联端点与模型健康'
|
||||
return `${props.target.lookbackHours} 小时内的${dimensions}`
|
||||
})
|
||||
|
||||
const sourceMonitor = computed<HealthRelatedMonitor | null>(() => {
|
||||
const source = props.target?.source
|
||||
if (!source) return null
|
||||
return {
|
||||
kind: source.kind,
|
||||
key: source.value,
|
||||
display_name: source.title,
|
||||
meta_text: source.metaText || null,
|
||||
total_attempts: source.totalAttempts,
|
||||
success_count: source.successCount,
|
||||
failed_count: source.failedCount,
|
||||
success_rate: source.successRate,
|
||||
avg_latency_ms: source.avgLatencyMs,
|
||||
avg_first_byte_ms: source.avgFirstByteMs,
|
||||
avg_tps: source.avgTps,
|
||||
timeline: source.timeline || undefined,
|
||||
time_range_start: source.timeRangeStart || null,
|
||||
time_range_end: source.timeRangeEnd || null
|
||||
}
|
||||
})
|
||||
|
||||
const relatedSections = computed(() => {
|
||||
const data = related.value
|
||||
const targetKind = props.target?.source.kind
|
||||
if (!data || !targetKind) return []
|
||||
|
||||
const sectionMap = {
|
||||
endpoints: {
|
||||
key: 'endpoints',
|
||||
title: '关联端点健康',
|
||||
description: '当前维度下实际请求涉及的端点健康',
|
||||
items: data.related_endpoints || []
|
||||
},
|
||||
models: {
|
||||
key: 'models',
|
||||
title: '关联模型健康',
|
||||
description: '当前维度下实际请求涉及的模型健康',
|
||||
items: data.related_models || []
|
||||
},
|
||||
providers: {
|
||||
key: 'providers',
|
||||
title: '关联提供商健康',
|
||||
description: '当前维度下实际请求涉及的提供商健康',
|
||||
items: props.isAdmin ? (data.related_providers || []) : []
|
||||
}
|
||||
}
|
||||
|
||||
const orderByKind = {
|
||||
endpoint: ['providers', 'models'],
|
||||
provider: ['endpoints', 'models'],
|
||||
model: ['providers', 'endpoints']
|
||||
} as const
|
||||
|
||||
return orderByKind[targetKind]
|
||||
.map(key => sectionMap[key])
|
||||
.filter(section => section.items.length > 0)
|
||||
})
|
||||
|
||||
async function loadRelated() {
|
||||
const target = props.target
|
||||
if (!props.open || !target) return
|
||||
|
||||
const seq = ++requestSeq
|
||||
loading.value = true
|
||||
errorMessage.value = null
|
||||
try {
|
||||
const params = {
|
||||
dimension: target.source.kind,
|
||||
value: target.source.value,
|
||||
lookback_hours: target.lookbackHours,
|
||||
related_limit: 8,
|
||||
per_item_limit: 100
|
||||
}
|
||||
if (!props.isAdmin && target.source.kind === 'provider') {
|
||||
throw new Error('公开健康监控不支持 provider 详情')
|
||||
}
|
||||
const data = props.isAdmin
|
||||
? await getHealthRelatedMonitor(params)
|
||||
: await getPublicHealthRelatedMonitor({
|
||||
...params,
|
||||
dimension: target.source.kind
|
||||
})
|
||||
if (seq === requestSeq) {
|
||||
related.value = data
|
||||
}
|
||||
} catch (err: unknown) {
|
||||
if (seq === requestSeq) {
|
||||
const message = parseApiError(err, '加载关联健康失败')
|
||||
errorMessage.value = message
|
||||
showError(message, '错误')
|
||||
}
|
||||
} finally {
|
||||
if (seq === requestSeq) {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function openRelatedDetails(monitor: HealthRelatedMonitor) {
|
||||
if (!props.isAdmin && monitor.kind === 'provider') return
|
||||
emit('viewDetails', {
|
||||
lookbackHours: props.target?.lookbackHours || 6,
|
||||
source: buildSourceFromRelatedMonitor(monitor)
|
||||
})
|
||||
}
|
||||
|
||||
function buildSourceFromRelatedMonitor(monitor: HealthRelatedMonitor): HealthMonitorDetailSource {
|
||||
return {
|
||||
kind: monitor.kind,
|
||||
value: monitor.key,
|
||||
title: monitor.display_name || monitor.key,
|
||||
metaText: buildRelatedMetaText(monitor),
|
||||
totalAttempts: monitor.total_attempts,
|
||||
successCount: monitor.success_count,
|
||||
failedCount: monitor.failed_count,
|
||||
successRate: monitor.success_rate,
|
||||
avgLatencyMs: monitor.avg_latency_ms,
|
||||
avgFirstByteMs: monitor.avg_first_byte_ms,
|
||||
avgTps: monitor.avg_tps,
|
||||
timeline: monitor.timeline || null,
|
||||
timeRangeStart: monitor.time_range_start || null,
|
||||
timeRangeEnd: monitor.time_range_end || null
|
||||
}
|
||||
}
|
||||
|
||||
function buildRelatedMetaText(monitor: HealthRelatedMonitor) {
|
||||
return monitor.meta_text || null
|
||||
}
|
||||
|
||||
watch([
|
||||
() => props.open,
|
||||
() => props.target?.source.kind,
|
||||
() => props.target?.source.value,
|
||||
() => props.target?.lookbackHours,
|
||||
() => props.isAdmin
|
||||
], ([open]) => {
|
||||
if (open) {
|
||||
loadRelated()
|
||||
}
|
||||
}, { immediate: true })
|
||||
</script>
|
||||
@@ -0,0 +1,132 @@
|
||||
<template>
|
||||
<div class="relative overflow-hidden rounded-xl border border-border/60 bg-card/60 p-4 transition-colors hover:border-primary/50">
|
||||
<div class="absolute inset-x-0 top-0 h-px bg-gradient-to-r from-transparent via-primary/40 to-transparent" />
|
||||
|
||||
<div class="flex items-start justify-between gap-3">
|
||||
<div class="flex min-w-0 items-center gap-3">
|
||||
<div class="flex h-11 w-11 flex-shrink-0 items-center justify-center rounded-xl border border-border/60 bg-muted/50">
|
||||
<component
|
||||
:is="iconComponent"
|
||||
class="h-5 w-5 text-muted-foreground"
|
||||
/>
|
||||
</div>
|
||||
<div class="min-w-0">
|
||||
<h4 class="truncate text-sm font-semibold">
|
||||
{{ monitor.display_name || monitor.key }}
|
||||
</h4>
|
||||
<p
|
||||
v-if="monitor.meta_text"
|
||||
class="mt-1 truncate text-xs text-muted-foreground"
|
||||
>
|
||||
{{ monitor.meta_text }}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<Badge
|
||||
:variant="getHealthBadgeVariant(monitor)"
|
||||
class="shrink-0"
|
||||
>
|
||||
{{ getHealthLabel(monitor) }}
|
||||
</Badge>
|
||||
</div>
|
||||
|
||||
<HealthMetricGrid
|
||||
class="mt-4"
|
||||
:avg-latency-ms="monitor.avg_latency_ms"
|
||||
:avg-first-byte-ms="monitor.avg_first_byte_ms"
|
||||
:avg-tps="monitor.avg_tps"
|
||||
:total-attempts="monitor.total_attempts"
|
||||
:success-rate="monitor.success_rate"
|
||||
/>
|
||||
|
||||
<div class="mt-4 flex items-center justify-between gap-3 text-[11px] uppercase tracking-wide text-muted-foreground">
|
||||
<span>History (60pts)</span>
|
||||
<span class="truncate normal-case tracking-normal">
|
||||
{{ metaText }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<HealthStatusTimeline
|
||||
class="mt-2"
|
||||
:timeline="monitor.timeline"
|
||||
:time-range-start="monitor.time_range_start"
|
||||
:time-range-end="monitor.time_range_end"
|
||||
:generated-at="generatedAt"
|
||||
:lookback-hours="lookbackHours"
|
||||
:entity-label="entityLabel"
|
||||
:entity-name="monitor.key"
|
||||
/>
|
||||
|
||||
<div
|
||||
v-if="showDetailButton"
|
||||
class="mt-4 flex justify-end"
|
||||
>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
@click="$emit('viewDetails', monitor)"
|
||||
>
|
||||
查看详情
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import { Activity, Bot, Server } from 'lucide-vue-next'
|
||||
import Badge from '@/components/ui/badge.vue'
|
||||
import Button from '@/components/ui/button.vue'
|
||||
import type { HealthRelatedMonitor } from '@/api/endpoints/types'
|
||||
import HealthMetricGrid from './HealthMetricGrid.vue'
|
||||
import HealthStatusTimeline from './HealthStatusTimeline.vue'
|
||||
import {
|
||||
formatCompactNumber,
|
||||
getHealthBadgeVariant,
|
||||
getHealthLabel
|
||||
} from './health-monitor-utils'
|
||||
|
||||
const props = withDefaults(defineProps<{
|
||||
monitor: HealthRelatedMonitor
|
||||
lookbackHours: number
|
||||
generatedAt?: string | null
|
||||
showDetailButton?: boolean
|
||||
}>(), {
|
||||
generatedAt: null,
|
||||
showDetailButton: true
|
||||
})
|
||||
|
||||
defineEmits<{
|
||||
viewDetails: [monitor: HealthRelatedMonitor]
|
||||
}>()
|
||||
|
||||
const iconComponent = computed(() => {
|
||||
switch (props.monitor.kind) {
|
||||
case 'model':
|
||||
return Bot
|
||||
case 'provider':
|
||||
return Server
|
||||
default:
|
||||
return Activity
|
||||
}
|
||||
})
|
||||
|
||||
const entityLabel = computed(() => {
|
||||
switch (props.monitor.kind) {
|
||||
case 'model':
|
||||
return '模型'
|
||||
case 'provider':
|
||||
return '提供商'
|
||||
default:
|
||||
return '端点'
|
||||
}
|
||||
})
|
||||
|
||||
const metaText = computed(() => {
|
||||
const attempts = `${formatCompactNumber(props.monitor.total_attempts)} 次请求`
|
||||
if (props.monitor.meta_text?.includes('次请求')) return props.monitor.meta_text
|
||||
return props.monitor.meta_text
|
||||
? `${props.monitor.meta_text} / ${attempts}`
|
||||
: attempts
|
||||
})
|
||||
</script>
|
||||
@@ -79,6 +79,16 @@
|
||||
entity-label="模型"
|
||||
:entity-name="monitor.model"
|
||||
/>
|
||||
|
||||
<div class="mt-4 flex justify-end">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
@click="openDetails(monitor)"
|
||||
>
|
||||
查看详情
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -90,6 +100,7 @@ import { ref, onMounted, watch } from "vue";
|
||||
import { Bot, Loader2 } from "lucide-vue-next";
|
||||
import Card from "@/components/ui/card.vue";
|
||||
import Badge from "@/components/ui/badge.vue";
|
||||
import Button from "@/components/ui/button.vue";
|
||||
import HealthMetricGrid from "./HealthMetricGrid.vue";
|
||||
import HealthMonitorHeader from "./HealthMonitorHeader.vue";
|
||||
import HealthStatusTimeline from "./HealthStatusTimeline.vue";
|
||||
@@ -100,10 +111,15 @@ import {
|
||||
import type { ModelStatusMonitor } from "@/api/endpoints/types";
|
||||
import { useToast } from "@/composables/useToast";
|
||||
import { parseApiError } from "@/utils/errorParser";
|
||||
import type {
|
||||
HealthMonitorDetailTarget,
|
||||
HealthMonitorSectionSummary,
|
||||
} from "./health-monitor-utils";
|
||||
import {
|
||||
formatCompactNumber,
|
||||
getHealthBadgeVariant,
|
||||
getHealthLabel,
|
||||
summarizeHealthMonitorItems,
|
||||
} from "./health-monitor-utils";
|
||||
|
||||
const props = withDefaults(
|
||||
@@ -119,6 +135,11 @@ const props = withDefaults(
|
||||
},
|
||||
);
|
||||
|
||||
const emit = defineEmits<{
|
||||
viewDetails: [target: HealthMonitorDetailTarget];
|
||||
summaryUpdated: [summary: HealthMonitorSectionSummary];
|
||||
}>();
|
||||
|
||||
const { error: showError } = useToast();
|
||||
|
||||
const loading = ref(false);
|
||||
@@ -141,6 +162,7 @@ async function loadMonitors() {
|
||||
: await getPublicModelStatusMonitor(params);
|
||||
monitors.value = data.models || [];
|
||||
generatedAt.value = data.generated_at || null;
|
||||
emitSummary();
|
||||
} catch (err: unknown) {
|
||||
showError(parseApiError(err, "加载模型健康监控数据失败"), "错误");
|
||||
} finally {
|
||||
@@ -165,6 +187,39 @@ function getModelMetaText(monitor: ModelStatusMonitor) {
|
||||
return attempts;
|
||||
}
|
||||
|
||||
function openDetails(monitor: ModelStatusMonitor) {
|
||||
emit("viewDetails", {
|
||||
lookbackHours: parseInt(lookbackHours.value),
|
||||
source: {
|
||||
kind: "model",
|
||||
value: monitor.model,
|
||||
title: monitor.display_name || monitor.model,
|
||||
metaText: getModelDetailMetaText(monitor),
|
||||
totalAttempts: monitor.total_attempts,
|
||||
successCount: monitor.success_count,
|
||||
failedCount: monitor.failed_count,
|
||||
successRate: monitor.success_rate,
|
||||
avgLatencyMs: monitor.avg_latency_ms,
|
||||
avgFirstByteMs: monitor.avg_first_byte_ms,
|
||||
avgTps: monitor.avg_tps,
|
||||
timeline: monitor.timeline || null,
|
||||
timeRangeStart: monitor.time_range_start || null,
|
||||
timeRangeEnd: monitor.time_range_end || null,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function getModelDetailMetaText(monitor: ModelStatusMonitor) {
|
||||
if (props.showProviderInfo && typeof monitor.provider_count === "number") {
|
||||
return `${monitor.provider_count} 个提供商`;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function emitSummary() {
|
||||
emit("summaryUpdated", summarizeHealthMonitorItems(monitors.value));
|
||||
}
|
||||
|
||||
watch(lookbackHours, () => {
|
||||
loadMonitors();
|
||||
});
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
<HealthMonitorHeader
|
||||
v-model:lookback-hours="lookbackHours"
|
||||
:title="title"
|
||||
description="仅展示活跃提供商,展开后查看该提供商下的模型健康明细"
|
||||
description="仅展示活跃提供商,点击详情查看该提供商关联的端点与模型健康"
|
||||
:loading="loading"
|
||||
@refresh="refreshData"
|
||||
/>
|
||||
@@ -21,159 +21,106 @@
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-else-if="providers.length === 0"
|
||||
v-else-if="visibleProviders.length === 0"
|
||||
class="flex flex-col items-center justify-center py-12 text-muted-foreground"
|
||||
>
|
||||
<Server class="w-12 h-12 mb-3 opacity-30" />
|
||||
<p>暂无活跃提供商健康数据</p>
|
||||
<p>暂无提供商健康数据</p>
|
||||
<p class="text-xs mt-1">
|
||||
当前没有活跃提供商或尚未产生请求记录
|
||||
当前没有提供商产生请求记录
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-else
|
||||
class="space-y-3"
|
||||
class="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4"
|
||||
>
|
||||
<Collapsible
|
||||
v-for="provider in providers"
|
||||
<div
|
||||
v-for="provider in visibleProviders"
|
||||
:key="provider.provider_id"
|
||||
v-model:open="expandedProviders[provider.provider_id]"
|
||||
class="overflow-hidden rounded-xl border border-border/60 bg-card/60"
|
||||
class="relative overflow-hidden rounded-xl border border-border/60 bg-card/60 p-4 transition-colors hover:border-primary/50"
|
||||
>
|
||||
<CollapsibleTrigger as-child>
|
||||
<button
|
||||
type="button"
|
||||
class="flex w-full flex-col gap-4 p-4 text-left transition-colors hover:bg-muted/30 lg:flex-row lg:items-center lg:justify-between"
|
||||
>
|
||||
<div class="flex min-w-0 items-start gap-3">
|
||||
<div class="flex h-11 w-11 flex-shrink-0 items-center justify-center rounded-xl border border-border/60 bg-muted/50">
|
||||
<Server class="h-5 w-5 text-muted-foreground" />
|
||||
</div>
|
||||
<div class="min-w-0">
|
||||
<div class="flex min-w-0 flex-wrap items-center gap-2">
|
||||
<ChevronRight
|
||||
class="h-4 w-4 text-muted-foreground transition-transform"
|
||||
:class="{ 'rotate-90': expandedProviders[provider.provider_id] }"
|
||||
/>
|
||||
<h4 class="truncate text-sm font-semibold">
|
||||
{{ provider.provider_name }}
|
||||
</h4>
|
||||
<Badge
|
||||
variant="outline"
|
||||
class="font-mono text-[11px]"
|
||||
>
|
||||
{{ provider.provider_type || 'custom' }}
|
||||
</Badge>
|
||||
<Badge :variant="getHealthBadgeVariant(provider)">
|
||||
{{ getHealthLabel(provider) }}
|
||||
</Badge>
|
||||
</div>
|
||||
<p class="mt-1 text-xs text-muted-foreground">
|
||||
{{ getProviderMetaText(provider) }}
|
||||
</p>
|
||||
</div>
|
||||
<div class="absolute inset-x-0 top-0 h-px bg-gradient-to-r from-transparent via-primary/40 to-transparent" />
|
||||
<div class="flex items-start justify-between gap-3">
|
||||
<div class="flex min-w-0 items-center gap-3">
|
||||
<div class="flex h-11 w-11 flex-shrink-0 items-center justify-center rounded-xl border border-border/60 bg-muted/50">
|
||||
<Server class="h-5 w-5 text-muted-foreground" />
|
||||
</div>
|
||||
|
||||
<HealthMetricGrid
|
||||
class="lg:max-w-2xl"
|
||||
:avg-latency-ms="provider.avg_latency_ms"
|
||||
:avg-first-byte-ms="provider.avg_first_byte_ms"
|
||||
:avg-tps="provider.avg_tps"
|
||||
:total-attempts="provider.total_attempts"
|
||||
:success-rate="provider.success_rate"
|
||||
/>
|
||||
</button>
|
||||
</CollapsibleTrigger>
|
||||
|
||||
<CollapsibleContent class="border-t border-border/50 px-4 pb-4 pt-4">
|
||||
<div
|
||||
v-if="provider.models.length === 0"
|
||||
class="rounded-lg border border-dashed border-border/60 py-8 text-center text-sm text-muted-foreground"
|
||||
>
|
||||
该提供商在当前时间范围内暂无模型请求
|
||||
</div>
|
||||
<div
|
||||
v-else
|
||||
class="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4"
|
||||
>
|
||||
<div
|
||||
v-for="model in provider.models"
|
||||
:key="`${provider.provider_id}-${model.model}`"
|
||||
class="relative overflow-hidden rounded-xl border border-border/60 bg-card/80 p-4 transition-colors hover:border-primary/50"
|
||||
>
|
||||
<div class="absolute inset-x-0 top-0 h-px bg-gradient-to-r from-transparent via-primary/40 to-transparent" />
|
||||
<div class="flex items-start justify-between gap-3">
|
||||
<div class="flex min-w-0 items-center gap-3">
|
||||
<div class="flex h-11 w-11 flex-shrink-0 items-center justify-center rounded-xl border border-border/60 bg-muted/50">
|
||||
<Bot class="h-5 w-5 text-muted-foreground" />
|
||||
</div>
|
||||
<h4 class="min-w-0 truncate text-sm font-semibold">
|
||||
{{ model.display_name || model.model }}
|
||||
</h4>
|
||||
</div>
|
||||
<Badge
|
||||
:variant="getHealthBadgeVariant(model)"
|
||||
class="shrink-0"
|
||||
>
|
||||
{{ getHealthLabel(model) }}
|
||||
</Badge>
|
||||
</div>
|
||||
|
||||
<HealthMetricGrid
|
||||
class="mt-4"
|
||||
:avg-latency-ms="model.avg_latency_ms"
|
||||
:avg-first-byte-ms="model.avg_first_byte_ms"
|
||||
:avg-tps="model.avg_tps"
|
||||
:total-attempts="model.total_attempts"
|
||||
:success-rate="model.success_rate"
|
||||
/>
|
||||
|
||||
<div class="mt-4 flex items-center justify-between gap-3 text-[11px] uppercase tracking-wide text-muted-foreground">
|
||||
<span>History (60pts)</span>
|
||||
<span class="truncate normal-case tracking-normal">
|
||||
{{ formatCompactNumber(model.total_attempts) }} 次请求
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<HealthStatusTimeline
|
||||
class="mt-2"
|
||||
:timeline="model.timeline"
|
||||
:time-range-start="model.time_range_start"
|
||||
:time-range-end="model.time_range_end"
|
||||
:generated-at="generatedAt"
|
||||
:lookback-hours="parseInt(lookbackHours)"
|
||||
entity-label="模型"
|
||||
:entity-name="model.model"
|
||||
/>
|
||||
<div class="min-w-0">
|
||||
<h4 class="truncate text-sm font-semibold">
|
||||
{{ provider.provider_name }}
|
||||
</h4>
|
||||
</div>
|
||||
</div>
|
||||
</CollapsibleContent>
|
||||
</Collapsible>
|
||||
<Badge
|
||||
:variant="getHealthBadgeVariant(provider)"
|
||||
class="shrink-0"
|
||||
>
|
||||
{{ getHealthLabel(provider) }}
|
||||
</Badge>
|
||||
</div>
|
||||
|
||||
<HealthMetricGrid
|
||||
class="mt-4"
|
||||
:avg-latency-ms="provider.avg_latency_ms"
|
||||
:avg-first-byte-ms="provider.avg_first_byte_ms"
|
||||
:avg-tps="provider.avg_tps"
|
||||
:total-attempts="provider.total_attempts"
|
||||
:success-rate="provider.success_rate"
|
||||
/>
|
||||
|
||||
<div class="mt-4 flex items-center justify-between gap-3 text-[11px] uppercase tracking-wide text-muted-foreground">
|
||||
<span>History (60pts)</span>
|
||||
<span class="truncate normal-case tracking-normal">
|
||||
{{ getProviderMetaText(provider) }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<HealthStatusTimeline
|
||||
class="mt-2"
|
||||
:timeline="provider.timeline"
|
||||
:time-range-start="provider.time_range_start"
|
||||
:time-range-end="provider.time_range_end"
|
||||
:generated-at="generatedAt"
|
||||
:lookback-hours="parseInt(lookbackHours)"
|
||||
entity-label="提供商"
|
||||
:entity-name="provider.provider_name"
|
||||
/>
|
||||
|
||||
<div class="mt-4 flex justify-end">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
@click="openDetails(provider)"
|
||||
>
|
||||
查看详情
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, onMounted, watch } from 'vue'
|
||||
import { Bot, ChevronRight, Loader2, Server } from 'lucide-vue-next'
|
||||
import { computed, ref, onMounted, watch } from 'vue'
|
||||
import { Loader2, Server } from 'lucide-vue-next'
|
||||
import Card from '@/components/ui/card.vue'
|
||||
import Badge from '@/components/ui/badge.vue'
|
||||
import Collapsible from '@/components/ui/collapsible.vue'
|
||||
import CollapsibleTrigger from '@/components/ui/collapsible-trigger.vue'
|
||||
import CollapsibleContent from '@/components/ui/collapsible-content.vue'
|
||||
import Button from '@/components/ui/button.vue'
|
||||
import HealthMetricGrid from './HealthMetricGrid.vue'
|
||||
import HealthMonitorHeader from './HealthMonitorHeader.vue'
|
||||
import HealthStatusTimeline from './HealthStatusTimeline.vue'
|
||||
import { getProviderStatusMonitor } from '@/api/endpoints/health'
|
||||
import type { ProviderStatusMonitor } from '@/api/endpoints/types'
|
||||
import type { HealthMonitorDetailTarget, HealthMonitorSectionSummary } from './health-monitor-utils'
|
||||
import { useToast } from '@/composables/useToast'
|
||||
import { parseApiError } from '@/utils/errorParser'
|
||||
import {
|
||||
formatCompactNumber,
|
||||
getHealthBadgeVariant,
|
||||
getHealthLabel
|
||||
getHealthLabel,
|
||||
summarizeHealthMonitorItems
|
||||
} from './health-monitor-utils'
|
||||
|
||||
const props = withDefaults(defineProps<{
|
||||
@@ -182,6 +129,11 @@ const props = withDefaults(defineProps<{
|
||||
title: '提供商健康监控'
|
||||
})
|
||||
|
||||
const emit = defineEmits<{
|
||||
viewDetails: [target: HealthMonitorDetailTarget]
|
||||
summaryUpdated: [summary: HealthMonitorSectionSummary]
|
||||
}>()
|
||||
|
||||
const { error: showError } = useToast()
|
||||
|
||||
const loading = ref(false)
|
||||
@@ -189,7 +141,7 @@ const loadingMonitors = ref(false)
|
||||
const providers = ref<ProviderStatusMonitor[]>([])
|
||||
const generatedAt = ref<string | null>(null)
|
||||
const lookbackHours = ref('6')
|
||||
const expandedProviders = ref<Record<string, boolean>>({})
|
||||
const visibleProviders = computed(() => providers.value.filter(provider => provider.total_attempts > 0))
|
||||
|
||||
async function loadMonitors() {
|
||||
loadingMonitors.value = true
|
||||
@@ -202,7 +154,7 @@ async function loadMonitors() {
|
||||
})
|
||||
providers.value = data.providers || []
|
||||
generatedAt.value = data.generated_at || null
|
||||
ensureExpandedProviderState()
|
||||
emitSummary()
|
||||
} catch (err: unknown) {
|
||||
showError(parseApiError(err, '加载提供商健康监控数据失败'), '错误')
|
||||
} finally {
|
||||
@@ -219,21 +171,37 @@ async function refreshData() {
|
||||
}
|
||||
}
|
||||
|
||||
function ensureExpandedProviderState() {
|
||||
const next = { ...expandedProviders.value }
|
||||
for (const provider of providers.value) {
|
||||
if (!(provider.provider_id in next)) {
|
||||
next[provider.provider_id] = false
|
||||
}
|
||||
}
|
||||
expandedProviders.value = next
|
||||
}
|
||||
|
||||
function getProviderMetaText(provider: ProviderStatusMonitor) {
|
||||
const attempts = `${formatCompactNumber(provider.total_attempts)} 次请求`
|
||||
return `${provider.model_count} 个模型 / ${attempts}`
|
||||
}
|
||||
|
||||
function openDetails(provider: ProviderStatusMonitor) {
|
||||
emit('viewDetails', {
|
||||
lookbackHours: parseInt(lookbackHours.value),
|
||||
source: {
|
||||
kind: 'provider',
|
||||
value: provider.provider_name,
|
||||
title: provider.provider_name,
|
||||
metaText: null,
|
||||
totalAttempts: provider.total_attempts,
|
||||
successCount: provider.success_count,
|
||||
failedCount: provider.failed_count,
|
||||
successRate: provider.success_rate,
|
||||
avgLatencyMs: provider.avg_latency_ms,
|
||||
avgFirstByteMs: provider.avg_first_byte_ms,
|
||||
avgTps: provider.avg_tps,
|
||||
timeline: provider.timeline || null,
|
||||
timeRangeStart: provider.time_range_start || null,
|
||||
timeRangeEnd: provider.time_range_end || null
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
function emitSummary() {
|
||||
emit('summaryUpdated', summarizeHealthMonitorItems(visibleProviders.value))
|
||||
}
|
||||
|
||||
watch(lookbackHours, () => {
|
||||
loadMonitors()
|
||||
})
|
||||
|
||||
@@ -7,11 +7,74 @@ export type HealthBadgeVariant =
|
||||
| 'warning'
|
||||
| 'dark'
|
||||
|
||||
export type HealthMonitorSourceKind = 'endpoint' | 'model' | 'provider'
|
||||
|
||||
export interface HealthMonitorDetailSource {
|
||||
kind: HealthMonitorSourceKind
|
||||
value: string
|
||||
title: string
|
||||
metaText?: string | null
|
||||
totalAttempts: number
|
||||
successCount: number
|
||||
failedCount: number
|
||||
successRate: number
|
||||
avgLatencyMs?: number | null
|
||||
avgFirstByteMs?: number | null
|
||||
avgTps?: number | null
|
||||
timeline?: string[] | null
|
||||
timeRangeStart?: string | null
|
||||
timeRangeEnd?: string | null
|
||||
}
|
||||
|
||||
export interface HealthMonitorDetailTarget {
|
||||
source: HealthMonitorDetailSource
|
||||
lookbackHours: number
|
||||
}
|
||||
|
||||
export interface HealthMonitorAvailability {
|
||||
total_attempts: number
|
||||
success_rate: number
|
||||
}
|
||||
|
||||
export interface HealthMonitorSectionSummary {
|
||||
total: number
|
||||
healthy: number
|
||||
warning: number
|
||||
unhealthy: number
|
||||
empty: number
|
||||
attempts: number
|
||||
}
|
||||
|
||||
export function summarizeHealthMonitorItems(
|
||||
items: HealthMonitorAvailability[]
|
||||
): HealthMonitorSectionSummary {
|
||||
return items.reduce<HealthMonitorSectionSummary>((summary, item) => {
|
||||
summary.total += 1
|
||||
summary.attempts += item.total_attempts
|
||||
if (item.total_attempts <= 0) {
|
||||
summary.empty += 1
|
||||
} else if (item.success_rate >= 0.95) {
|
||||
summary.healthy += 1
|
||||
} else if (item.success_rate >= 0.8) {
|
||||
summary.warning += 1
|
||||
} else {
|
||||
summary.unhealthy += 1
|
||||
}
|
||||
return summary
|
||||
}, createEmptyHealthMonitorSectionSummary())
|
||||
}
|
||||
|
||||
export function createEmptyHealthMonitorSectionSummary(): HealthMonitorSectionSummary {
|
||||
return {
|
||||
total: 0,
|
||||
healthy: 0,
|
||||
warning: 0,
|
||||
unhealthy: 0,
|
||||
empty: 0,
|
||||
attempts: 0
|
||||
}
|
||||
}
|
||||
|
||||
export function getHealthLabel(
|
||||
item: HealthMonitorAvailability,
|
||||
emptyLabel = '暂无请求'
|
||||
|
||||
@@ -458,6 +458,104 @@ const MOCK_PROVIDER_HEALTH_STATUS = {
|
||||
]
|
||||
}
|
||||
|
||||
function mockApiFormatDisplayName(apiFormat: string) {
|
||||
const labels: Record<string, string> = {
|
||||
'claude:messages': 'Claude Messages',
|
||||
'gemini:generate_content': 'Gemini Generate Content',
|
||||
'openai:chat': 'OpenAI Chat',
|
||||
'openai:embedding': 'OpenAI Embedding'
|
||||
}
|
||||
return labels[apiFormat] || apiFormat
|
||||
}
|
||||
|
||||
function relatedEndpointMonitor(format: typeof MOCK_ENDPOINT_STATUS.formats[number]) {
|
||||
return {
|
||||
kind: 'endpoint',
|
||||
key: format.api_format,
|
||||
display_name: mockApiFormatDisplayName(format.api_format),
|
||||
meta_text: format.api_path,
|
||||
total_attempts: format.total_attempts,
|
||||
success_count: format.success_count,
|
||||
failed_count: format.failed_count,
|
||||
success_rate: format.success_rate,
|
||||
avg_latency_ms: format.avg_latency_ms,
|
||||
avg_first_byte_ms: format.avg_first_byte_ms,
|
||||
avg_tps: format.avg_tps,
|
||||
last_event_at: format.last_event_at,
|
||||
timeline: format.timeline,
|
||||
time_range_start: format.time_range_start,
|
||||
time_range_end: format.time_range_end
|
||||
}
|
||||
}
|
||||
|
||||
function relatedModelMonitor(model: typeof MOCK_MODEL_STATUS.models[number]) {
|
||||
return {
|
||||
kind: 'model',
|
||||
key: model.model,
|
||||
display_name: model.display_name || model.model,
|
||||
meta_text: model.provider_count ? `${model.provider_count} 个提供商` : null,
|
||||
total_attempts: model.total_attempts,
|
||||
success_count: model.success_count,
|
||||
failed_count: model.failed_count,
|
||||
success_rate: model.success_rate,
|
||||
avg_latency_ms: model.avg_latency_ms,
|
||||
avg_first_byte_ms: model.avg_first_byte_ms,
|
||||
avg_tps: model.avg_tps,
|
||||
last_event_at: model.last_event_at,
|
||||
timeline: model.timeline,
|
||||
time_range_start: model.time_range_start,
|
||||
time_range_end: model.time_range_end
|
||||
}
|
||||
}
|
||||
|
||||
function relatedProviderMonitor(provider: typeof MOCK_PROVIDER_HEALTH_STATUS.providers[number]) {
|
||||
return {
|
||||
kind: 'provider',
|
||||
key: provider.provider_name,
|
||||
display_name: provider.provider_name,
|
||||
meta_text: provider.provider_type || 'custom',
|
||||
total_attempts: provider.total_attempts,
|
||||
success_count: provider.success_count,
|
||||
failed_count: provider.failed_count,
|
||||
success_rate: provider.success_rate,
|
||||
avg_latency_ms: provider.avg_latency_ms,
|
||||
avg_first_byte_ms: provider.avg_first_byte_ms,
|
||||
avg_tps: provider.avg_tps,
|
||||
last_event_at: provider.last_event_at,
|
||||
timeline: provider.timeline,
|
||||
time_range_start: provider.time_range_start,
|
||||
time_range_end: provider.time_range_end
|
||||
}
|
||||
}
|
||||
|
||||
function uniqueMockEndpointFormats() {
|
||||
const seen = new Set<string>()
|
||||
return MOCK_ENDPOINT_STATUS.formats.filter(format => {
|
||||
if (seen.has(format.api_format)) return false
|
||||
seen.add(format.api_format)
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
||||
function buildMockRelatedHealthResponse(config: AxiosRequestConfig, includeProviders: boolean) {
|
||||
const dimension = String(config.params?.dimension || 'endpoint')
|
||||
const value = String(config.params?.value || '')
|
||||
const endpoints = uniqueMockEndpointFormats().slice(0, 3).map(relatedEndpointMonitor)
|
||||
const models = MOCK_MODEL_STATUS.models.slice(0, 3).map(relatedModelMonitor)
|
||||
const providers = includeProviders
|
||||
? MOCK_PROVIDER_HEALTH_STATUS.providers.slice(0, 3).map(relatedProviderMonitor)
|
||||
: []
|
||||
|
||||
return {
|
||||
generated_at: new Date().toISOString(),
|
||||
dimension,
|
||||
value,
|
||||
related_endpoints: dimension === 'endpoint' ? [] : endpoints,
|
||||
related_models: dimension === 'model' ? [] : models,
|
||||
related_providers: dimension === 'provider' ? [] : providers
|
||||
}
|
||||
}
|
||||
|
||||
// 生成活跃热力图数据(最近365天)
|
||||
function generateActivityHeatmap() {
|
||||
const days: Array<{
|
||||
@@ -1258,6 +1356,12 @@ const mockHandlers: Record<string, (config: AxiosRequestConfig) => Promise<Axios
|
||||
return createMockResponse(MOCK_PROVIDER_HEALTH_STATUS)
|
||||
},
|
||||
|
||||
'GET /api/admin/endpoints/health/related': async (config) => {
|
||||
await delay()
|
||||
requireAdmin()
|
||||
return createMockResponse(buildMockRelatedHealthResponse(config, true))
|
||||
},
|
||||
|
||||
'GET /api/admin/endpoints/keys': async () => {
|
||||
await delay()
|
||||
requireAdmin()
|
||||
@@ -1648,6 +1752,11 @@ const mockHandlers: Record<string, (config: AxiosRequestConfig) => Promise<Axios
|
||||
time_range_end: model.time_range_end
|
||||
}))
|
||||
})
|
||||
},
|
||||
|
||||
'GET /api/public/health/related': async (config) => {
|
||||
await delay()
|
||||
return createMockResponse(buildMockRelatedHealthResponse(config, false))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,82 +1,355 @@
|
||||
<template>
|
||||
<div class="space-y-6 pb-8">
|
||||
<Tabs v-model="activeTab">
|
||||
<TabsList
|
||||
class="tabs-button-list grid w-full"
|
||||
:class="isAdminPage ? 'max-w-2xl grid-cols-3' : 'max-w-md grid-cols-2'"
|
||||
>
|
||||
<TabsTrigger value="endpoint">
|
||||
端点健康监控
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="model">
|
||||
模型健康监控
|
||||
</TabsTrigger>
|
||||
<TabsTrigger
|
||||
v-if="isAdminPage"
|
||||
value="provider"
|
||||
>
|
||||
提供商健康监控
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
<Card
|
||||
variant="default"
|
||||
class="overflow-hidden"
|
||||
>
|
||||
<div class="relative overflow-hidden border-b border-border/60 px-6 py-5">
|
||||
<div class="absolute inset-0 bg-gradient-to-br from-primary/10 via-transparent to-muted/30" />
|
||||
<div class="relative flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
|
||||
<div class="max-w-3xl">
|
||||
<p class="text-xs font-medium uppercase tracking-[0.22em] text-primary/80">
|
||||
Health Dashboard
|
||||
</p>
|
||||
<h2 class="mt-2 text-2xl font-semibold tracking-tight">
|
||||
健康监控
|
||||
</h2>
|
||||
<p class="mt-2 text-sm leading-6 text-muted-foreground">
|
||||
统一查看端点、模型{{ isAdminPage ? '、提供商' : '' }}健康状态,先从概览判断风险,再进入具体视角排查关联健康。
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<TabsContent
|
||||
value="endpoint"
|
||||
class="mt-4"
|
||||
>
|
||||
<HealthMonitorCard
|
||||
v-if="visitedTabs.endpoint"
|
||||
title="端点健康监控"
|
||||
:is-admin="isAdminPage"
|
||||
:show-provider-info="isAdminPage"
|
||||
/>
|
||||
</TabsContent>
|
||||
<div class="space-y-5 p-6">
|
||||
<div class="grid grid-cols-1 gap-3 sm:grid-cols-2 xl:grid-cols-4">
|
||||
<div
|
||||
v-for="card in overviewCards"
|
||||
:key="card.label"
|
||||
class="rounded-xl border border-border/60 bg-card/70 p-4"
|
||||
>
|
||||
<div class="flex items-start justify-between gap-3">
|
||||
<div>
|
||||
<p class="text-xs text-muted-foreground">
|
||||
{{ card.label }}
|
||||
</p>
|
||||
<div
|
||||
class="mt-2 text-2xl font-semibold tabular-nums"
|
||||
:class="card.valueClass"
|
||||
>
|
||||
{{ card.value }}
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-xl border border-border/60 bg-muted/40">
|
||||
<component
|
||||
:is="card.icon"
|
||||
class="h-5 w-5 text-muted-foreground"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<p class="mt-3 text-xs text-muted-foreground">
|
||||
{{ card.description }}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<TabsContent
|
||||
value="model"
|
||||
class="mt-4"
|
||||
>
|
||||
<ModelHealthMonitorCard
|
||||
v-if="visitedTabs.model"
|
||||
title="模型健康监控"
|
||||
:is-admin="isAdminPage"
|
||||
:show-provider-info="isAdminPage"
|
||||
/>
|
||||
</TabsContent>
|
||||
<div>
|
||||
<div class="mb-3 flex flex-col gap-1 sm:flex-row sm:items-end sm:justify-between">
|
||||
<div>
|
||||
<h3 class="text-sm font-semibold">
|
||||
综合概览
|
||||
</h3>
|
||||
<p class="text-xs text-muted-foreground">
|
||||
点击视角卡片快速跳转到对应健康列表
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<TabsContent
|
||||
v-if="isAdminPage"
|
||||
value="provider"
|
||||
class="mt-4"
|
||||
>
|
||||
<ProviderHealthMonitorCard
|
||||
v-if="visitedTabs.provider"
|
||||
title="提供商健康监控"
|
||||
/>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
<div
|
||||
class="grid grid-cols-1 gap-3"
|
||||
:class="isAdminPage ? 'lg:grid-cols-3' : 'lg:grid-cols-2'"
|
||||
>
|
||||
<button
|
||||
v-for="section in sectionCards"
|
||||
:key="section.key"
|
||||
type="button"
|
||||
class="group rounded-xl border border-border/60 bg-muted/20 p-4 text-left transition-colors hover:border-primary/50 hover:bg-primary/5"
|
||||
@click="scrollToSection(section.id)"
|
||||
>
|
||||
<div class="flex items-start justify-between gap-3">
|
||||
<div class="flex min-w-0 items-center gap-3">
|
||||
<div class="flex h-11 w-11 flex-shrink-0 items-center justify-center rounded-xl border border-border/60 bg-card/70 transition-colors group-hover:border-primary/40">
|
||||
<component
|
||||
:is="section.icon"
|
||||
class="h-5 w-5 text-muted-foreground"
|
||||
/>
|
||||
</div>
|
||||
<div class="min-w-0">
|
||||
<h4 class="truncate text-sm font-semibold">
|
||||
{{ section.title }}
|
||||
</h4>
|
||||
<p class="mt-1 text-xs text-muted-foreground">
|
||||
{{ section.description }}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<Badge
|
||||
:variant="section.badgeVariant"
|
||||
class="shrink-0"
|
||||
>
|
||||
{{ section.badgeLabel }}
|
||||
</Badge>
|
||||
</div>
|
||||
<div class="mt-4 grid grid-cols-3 gap-2 text-xs">
|
||||
<div class="rounded-lg border border-border/40 bg-card/50 px-3 py-2">
|
||||
<p class="text-muted-foreground">总数</p>
|
||||
<p class="mt-1 font-semibold tabular-nums">{{ section.summary.total }}</p>
|
||||
</div>
|
||||
<div class="rounded-lg border border-border/40 bg-card/50 px-3 py-2">
|
||||
<p class="text-muted-foreground">异常</p>
|
||||
<p class="mt-1 font-semibold tabular-nums text-red-600 dark:text-red-400">{{ section.summary.unhealthy }}</p>
|
||||
</div>
|
||||
<div class="rounded-lg border border-border/40 bg-card/50 px-3 py-2">
|
||||
<p class="text-muted-foreground">波动</p>
|
||||
<p class="mt-1 font-semibold tabular-nums text-amber-600 dark:text-amber-400">{{ section.summary.warning }}</p>
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
<section
|
||||
id="health-endpoints"
|
||||
class="scroll-mt-6"
|
||||
>
|
||||
<HealthMonitorCard
|
||||
title="端点健康监控"
|
||||
:is-admin="isAdminPage"
|
||||
:show-provider-info="isAdminPage"
|
||||
@view-details="openHealthDetails"
|
||||
@summary-updated="updateSummary('endpoint', $event)"
|
||||
/>
|
||||
</section>
|
||||
|
||||
<section
|
||||
id="health-models"
|
||||
class="scroll-mt-6"
|
||||
>
|
||||
<ModelHealthMonitorCard
|
||||
title="模型健康监控"
|
||||
:is-admin="isAdminPage"
|
||||
:show-provider-info="isAdminPage"
|
||||
@view-details="openHealthDetails"
|
||||
@summary-updated="updateSummary('model', $event)"
|
||||
/>
|
||||
</section>
|
||||
|
||||
<section
|
||||
v-if="isAdminPage"
|
||||
id="health-providers"
|
||||
class="scroll-mt-6"
|
||||
>
|
||||
<ProviderHealthMonitorCard
|
||||
title="提供商健康监控"
|
||||
@view-details="openHealthDetails"
|
||||
@summary-updated="updateSummary('provider', $event)"
|
||||
/>
|
||||
</section>
|
||||
|
||||
<HealthMonitorDetailDrawer
|
||||
v-model:open="detailOpen"
|
||||
:target="detailTarget"
|
||||
:is-admin="isAdminPage"
|
||||
@view-details="openHealthDetails"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, ref, watch } from 'vue'
|
||||
import { computed, ref, type Component } from 'vue'
|
||||
import { useRoute } from 'vue-router'
|
||||
import Tabs from '@/components/ui/tabs.vue'
|
||||
import TabsContent from '@/components/ui/tabs-content.vue'
|
||||
import TabsList from '@/components/ui/tabs-list.vue'
|
||||
import TabsTrigger from '@/components/ui/tabs-trigger.vue'
|
||||
import { Activity, Bot, Gauge, Server, Zap } from 'lucide-vue-next'
|
||||
import Card from '@/components/ui/card.vue'
|
||||
import Badge from '@/components/ui/badge.vue'
|
||||
import HealthMonitorCard from '@/features/providers/components/HealthMonitorCard.vue'
|
||||
import ModelHealthMonitorCard from '@/features/providers/components/ModelHealthMonitorCard.vue'
|
||||
import ProviderHealthMonitorCard from '@/features/providers/components/ProviderHealthMonitorCard.vue'
|
||||
import HealthMonitorDetailDrawer from '@/features/providers/components/HealthMonitorDetailDrawer.vue'
|
||||
import {
|
||||
createEmptyHealthMonitorSectionSummary,
|
||||
formatCompactNumber,
|
||||
type HealthBadgeVariant,
|
||||
type HealthMonitorDetailTarget,
|
||||
type HealthMonitorSectionSummary,
|
||||
type HealthMonitorSourceKind
|
||||
} from '@/features/providers/components/health-monitor-utils'
|
||||
|
||||
const route = useRoute()
|
||||
const isAdminPage = computed(() => route.path.startsWith('/admin'))
|
||||
const activeTab = ref('endpoint')
|
||||
const visitedTabs = ref<Record<string, boolean>>({ endpoint: true })
|
||||
const detailOpen = ref(false)
|
||||
const detailTarget = ref<HealthMonitorDetailTarget | null>(null)
|
||||
const sectionSummaries = ref<Partial<Record<HealthMonitorSourceKind, HealthMonitorSectionSummary>>>({})
|
||||
|
||||
watch(activeTab, value => {
|
||||
visitedTabs.value = {
|
||||
...visitedTabs.value,
|
||||
[value]: true
|
||||
const expectedSectionKeys = computed<HealthMonitorSourceKind[]>(() => (
|
||||
isAdminPage.value ? ['endpoint', 'model', 'provider'] : ['endpoint', 'model']
|
||||
))
|
||||
|
||||
const loadedSectionCount = computed(() => (
|
||||
expectedSectionKeys.value.filter(key => sectionSummaries.value[key]).length
|
||||
))
|
||||
|
||||
const allSectionsLoaded = computed(() => loadedSectionCount.value >= expectedSectionKeys.value.length)
|
||||
|
||||
const combinedSummary = computed(() => {
|
||||
const summary = createEmptyHealthMonitorSectionSummary()
|
||||
for (const key of expectedSectionKeys.value) {
|
||||
const section = getSummary(key)
|
||||
summary.total += section.total
|
||||
summary.healthy += section.healthy
|
||||
summary.warning += section.warning
|
||||
summary.unhealthy += section.unhealthy
|
||||
summary.empty += section.empty
|
||||
summary.attempts += section.attempts
|
||||
}
|
||||
return summary
|
||||
})
|
||||
|
||||
const overallLabel = computed(() => getStatusLabel(combinedSummary.value, allSectionsLoaded.value))
|
||||
const overallBadgeVariant = computed(() => getStatusBadgeVariant(combinedSummary.value, allSectionsLoaded.value))
|
||||
|
||||
const overviewCards = computed(() => {
|
||||
const endpointSummary = getSummary('endpoint')
|
||||
const modelSummary = getSummary('model')
|
||||
const providerSummary = getSummary('provider')
|
||||
const cards = [
|
||||
{
|
||||
label: '总体状态',
|
||||
value: overallLabel.value,
|
||||
description: allSectionsLoaded.value
|
||||
? `${combinedSummary.value.total} 项健康对象 / ${formatCompactNumber(combinedSummary.value.attempts)} 次请求`
|
||||
: `${loadedSectionCount.value}/${expectedSectionKeys.value.length} 个视角已加载`,
|
||||
icon: Gauge,
|
||||
valueClass: getStatusValueClass(combinedSummary.value, allSectionsLoaded.value)
|
||||
},
|
||||
{
|
||||
label: '异常端点',
|
||||
value: endpointSummary.unhealthy,
|
||||
description: `${endpointSummary.warning} 个波动 / ${formatCompactNumber(endpointSummary.attempts)} 次请求`,
|
||||
icon: Activity,
|
||||
valueClass: endpointSummary.unhealthy > 0 ? 'text-red-600 dark:text-red-400' : ''
|
||||
},
|
||||
{
|
||||
label: '异常模型',
|
||||
value: modelSummary.unhealthy,
|
||||
description: `${modelSummary.warning} 个波动 / ${formatCompactNumber(modelSummary.attempts)} 次请求`,
|
||||
icon: Bot,
|
||||
valueClass: modelSummary.unhealthy > 0 ? 'text-red-600 dark:text-red-400' : ''
|
||||
}
|
||||
]
|
||||
|
||||
if (isAdminPage.value) {
|
||||
cards.push({
|
||||
label: '异常提供商',
|
||||
value: providerSummary.unhealthy,
|
||||
description: `${providerSummary.warning} 个波动 / ${providerSummary.empty} 个暂无请求`,
|
||||
icon: Server,
|
||||
valueClass: providerSummary.unhealthy > 0 ? 'text-red-600 dark:text-red-400' : ''
|
||||
})
|
||||
} else {
|
||||
cards.push({
|
||||
label: '请求总量',
|
||||
value: formatCompactNumber(combinedSummary.value.attempts),
|
||||
description: '当前回溯窗口内参与健康统计的请求',
|
||||
icon: Zap,
|
||||
valueClass: ''
|
||||
})
|
||||
}
|
||||
|
||||
return cards
|
||||
})
|
||||
|
||||
const sectionCards = computed(() => {
|
||||
const sections = [
|
||||
buildSectionCard('endpoint', 'health-endpoints', '端点视角', '按 API 入口定位入口层健康', Activity),
|
||||
buildSectionCard('model', 'health-models', '模型视角', '按模型聚合查看跨提供商健康', Bot)
|
||||
]
|
||||
|
||||
if (isAdminPage.value) {
|
||||
sections.push(buildSectionCard('provider', 'health-providers', '提供商视角', '按提供商定位供应商侧波动', Server))
|
||||
}
|
||||
|
||||
return sections
|
||||
})
|
||||
|
||||
function openHealthDetails(target: HealthMonitorDetailTarget) {
|
||||
detailTarget.value = target
|
||||
detailOpen.value = true
|
||||
}
|
||||
|
||||
function updateSummary(kind: HealthMonitorSourceKind, summary: HealthMonitorSectionSummary) {
|
||||
sectionSummaries.value = {
|
||||
...sectionSummaries.value,
|
||||
[kind]: summary
|
||||
}
|
||||
}
|
||||
|
||||
function getSummary(kind: HealthMonitorSourceKind) {
|
||||
return sectionSummaries.value[kind] || createEmptyHealthMonitorSectionSummary()
|
||||
}
|
||||
|
||||
function buildSectionCard(
|
||||
key: HealthMonitorSourceKind,
|
||||
id: string,
|
||||
title: string,
|
||||
description: string,
|
||||
icon: Component
|
||||
) {
|
||||
const summary = getSummary(key)
|
||||
const loaded = Boolean(sectionSummaries.value[key])
|
||||
return {
|
||||
key,
|
||||
id,
|
||||
title,
|
||||
description,
|
||||
icon,
|
||||
summary,
|
||||
badgeLabel: getStatusLabel(summary, loaded),
|
||||
badgeVariant: getStatusBadgeVariant(summary, loaded)
|
||||
}
|
||||
}
|
||||
|
||||
function getStatusLabel(summary: HealthMonitorSectionSummary, loaded: boolean) {
|
||||
if (!loaded) return '加载中'
|
||||
if (summary.total === 0) return '暂无数据'
|
||||
if (summary.unhealthy > 0) return '异常'
|
||||
if (summary.warning > 0) return '波动'
|
||||
if (summary.empty > 0) return '部分暂无请求'
|
||||
return '正常'
|
||||
}
|
||||
|
||||
function getStatusBadgeVariant(
|
||||
summary: HealthMonitorSectionSummary,
|
||||
loaded: boolean
|
||||
): HealthBadgeVariant {
|
||||
if (!loaded || summary.total === 0) return 'outline'
|
||||
if (summary.unhealthy > 0) return 'destructive'
|
||||
if (summary.warning > 0 || summary.empty > 0) return 'warning'
|
||||
return 'success'
|
||||
}
|
||||
|
||||
function getStatusValueClass(summary: HealthMonitorSectionSummary, loaded: boolean) {
|
||||
if (!loaded || summary.total === 0) return ''
|
||||
if (summary.unhealthy > 0) return 'text-red-600 dark:text-red-400'
|
||||
if (summary.warning > 0 || summary.empty > 0) return 'text-amber-600 dark:text-amber-400'
|
||||
return 'text-green-600 dark:text-green-400'
|
||||
}
|
||||
|
||||
function scrollToSection(id: string) {
|
||||
document.getElementById(id)?.scrollIntoView({
|
||||
behavior: 'smooth',
|
||||
block: 'start'
|
||||
})
|
||||
}
|
||||
</script>
|
||||
|
||||
Reference in New Issue
Block a user