mirror of
https://github.com/fawney19/Aether.git
synced 2026-10-08 02:17:46 +08:00
@@ -1,6 +1,19 @@
|
||||
<template>
|
||||
<div class="w-full space-y-1">
|
||||
<!-- 时间线 -->
|
||||
<HealthStatusTimeline
|
||||
v-if="hasStatusTimeline"
|
||||
:timeline="monitor?.timeline"
|
||||
:timeline-details="monitor?.timeline_details"
|
||||
:time-range-start="monitor?.time_range_start"
|
||||
:time-range-end="monitor?.time_range_end"
|
||||
:lookback-hours="lookbackHours"
|
||||
:fallback-segments="segmentCount ?? GRID_COUNT"
|
||||
entity-label="端点"
|
||||
:entity-name="monitor?.api_format"
|
||||
/>
|
||||
<div
|
||||
v-else
|
||||
class="w-full space-y-1"
|
||||
>
|
||||
<div class="flex items-center gap-px h-6 w-full">
|
||||
<TooltipProvider
|
||||
v-for="(segment, index) in segments"
|
||||
@@ -9,8 +22,10 @@
|
||||
>
|
||||
<Tooltip>
|
||||
<TooltipTrigger as-child>
|
||||
<div
|
||||
class="flex-1 h-full rounded-sm transition-all duration-150 cursor-pointer hover:scale-y-110 hover:brightness-110"
|
||||
<button
|
||||
type="button"
|
||||
:title="segment.tooltip"
|
||||
class="h-full flex-1 cursor-pointer rounded-sm border-0 p-0 transition-all duration-150 hover:scale-y-110 hover:brightness-110 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary"
|
||||
:class="segment.color"
|
||||
/>
|
||||
</TooltipTrigger>
|
||||
@@ -26,7 +41,6 @@
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
</div>
|
||||
<!-- 时间标签 -->
|
||||
<div class="flex items-center justify-between text-[10px] text-muted-foreground">
|
||||
<span>{{ earliestTime }}</span>
|
||||
<span>{{ latestTime }}</span>
|
||||
@@ -38,6 +52,8 @@
|
||||
import { computed } from 'vue'
|
||||
import type { EndpointStatusMonitor, EndpointHealthEvent, PublicEndpointStatusMonitor, PublicHealthEvent } from '@/api/endpoints'
|
||||
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'
|
||||
import HealthStatusTimeline from './HealthStatusTimeline.vue'
|
||||
import { formatTimestamp, formatTimelineTooltip } from './health-monitor-utils'
|
||||
|
||||
// 组件同时支持管理员端和用户端的监控数据类型
|
||||
// - EndpointStatusMonitor: 管理员端,包含 provider_count, key_count 等敏感信息
|
||||
@@ -49,40 +65,34 @@ const props = defineProps<{
|
||||
}>()
|
||||
|
||||
// 固定格子数量,将实际事件按时间均匀分布到格子中
|
||||
const GRID_COUNT = 100
|
||||
const GRID_COUNT = 60
|
||||
|
||||
const hasStatusTimeline = computed(() =>
|
||||
Array.isArray(props.monitor?.timeline) && (props.monitor?.timeline?.length ?? 0) > 0
|
||||
)
|
||||
|
||||
const segments = computed(() => {
|
||||
const gridCount = props.segmentCount ?? GRID_COUNT
|
||||
const lookbackHours = props.lookbackHours ?? 6
|
||||
const usageTimeline = Array.isArray(props.monitor?.timeline)
|
||||
? props.monitor?.timeline ?? []
|
||||
: []
|
||||
|
||||
if (usageTimeline.length > 0) {
|
||||
return buildUsageTimelineSegments(
|
||||
usageTimeline,
|
||||
props.monitor?.time_range_start ?? null,
|
||||
props.monitor?.time_range_end ?? null,
|
||||
lookbackHours
|
||||
)
|
||||
}
|
||||
|
||||
const events = props.monitor?.events ?? []
|
||||
|
||||
// 无数据时显示空白格子
|
||||
if (events.length === 0) {
|
||||
return Array.from({ length: gridCount }, () => ({
|
||||
color: 'bg-gray-300 dark:bg-gray-600',
|
||||
tooltip: '暂无请求记录'
|
||||
}))
|
||||
}
|
||||
|
||||
// 计算时间范围:使用 UTC 时间戳避免时区问题
|
||||
const nowUtc = Date.now()
|
||||
const startTimeUtc = nowUtc - lookbackHours * 60 * 60 * 1000
|
||||
const timeRange = lookbackHours * 60 * 60 * 1000
|
||||
const timePerGrid = timeRange / gridCount
|
||||
|
||||
// 无数据时显示空白格子
|
||||
if (events.length === 0) {
|
||||
return Array.from({ length: gridCount }, (_, index) => {
|
||||
const cellStartTime = new Date(startTimeUtc + index * timePerGrid)
|
||||
const cellEndTime = new Date(startTimeUtc + (index + 1) * timePerGrid)
|
||||
return {
|
||||
color: 'bg-gray-300 dark:bg-gray-600',
|
||||
tooltip: buildSegmentTooltip('unknown', cellStartTime, cellEndTime, [])
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// 计算时间范围:使用 UTC 时间戳避免时区问题
|
||||
const gridEvents: Array<Array<EndpointHealthEvent | PublicHealthEvent>> = Array.from({ length: gridCount }, () => [])
|
||||
|
||||
for (const event of events) {
|
||||
@@ -103,7 +113,7 @@ const segments = computed(() => {
|
||||
if (cellEvents.length === 0) {
|
||||
result.push({
|
||||
color: 'bg-gray-300 dark:bg-gray-600',
|
||||
tooltip: `${formatTimestamp(cellStartTime.toISOString())} - ${formatTimestamp(cellEndTime.toISOString())}\n暂无请求记录`
|
||||
tooltip: buildSegmentTooltip('unknown', cellStartTime, cellEndTime, [])
|
||||
})
|
||||
continue
|
||||
}
|
||||
@@ -111,7 +121,12 @@ const segments = computed(() => {
|
||||
if (cellEvents.length === 1) {
|
||||
result.push({
|
||||
color: getStatusColor(cellEvents[0].status),
|
||||
tooltip: buildTooltip(cellEvents[0])
|
||||
tooltip: buildSegmentTooltip(
|
||||
getTimelineStatusFromEvents(cellEvents),
|
||||
cellStartTime,
|
||||
cellEndTime,
|
||||
cellEvents
|
||||
)
|
||||
})
|
||||
continue
|
||||
}
|
||||
@@ -134,11 +149,15 @@ const segments = computed(() => {
|
||||
color = 'bg-gray-300 dark:bg-gray-600'
|
||||
}
|
||||
|
||||
const firstTime = formatTimestamp(cellEvents[0]?.timestamp)
|
||||
const lastTime = formatTimestamp(cellEvents[cellEvents.length - 1]?.timestamp)
|
||||
const tooltip = `${firstTime} - ${lastTime}\n共 ${total} 次请求\n成功: ${successCount}, 失败: ${failedCount}, 跳过: ${skippedCount}`
|
||||
|
||||
result.push({ color, tooltip })
|
||||
result.push({
|
||||
color,
|
||||
tooltip: buildSegmentTooltip(
|
||||
getTimelineStatusFromEvents(cellEvents),
|
||||
cellStartTime,
|
||||
cellEndTime,
|
||||
cellEvents
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
return result
|
||||
@@ -159,42 +178,6 @@ function getStatusColor(status: string) {
|
||||
}
|
||||
}
|
||||
|
||||
function buildTooltip(event: EndpointHealthEvent | PublicHealthEvent) {
|
||||
const time = formatTimestamp(event.timestamp)
|
||||
const statusText = getStatusText(event.status)
|
||||
const latency = event.latency_ms ? ` • ${event.latency_ms}ms` : ''
|
||||
const code = event.status_code ? ` • ${event.status_code}` : ''
|
||||
const error = event.error_type ? ` • ${event.error_type}` : ''
|
||||
return `${time} ${statusText}${latency}${code}${error}`
|
||||
}
|
||||
|
||||
function getStatusText(status: string) {
|
||||
switch (status) {
|
||||
case 'success':
|
||||
return '成功'
|
||||
case 'failed':
|
||||
return '失败'
|
||||
case 'skipped':
|
||||
return '跳过'
|
||||
case 'started':
|
||||
return '执行中'
|
||||
default:
|
||||
return '未知'
|
||||
}
|
||||
}
|
||||
|
||||
function formatTimestamp(timestamp?: string | null) {
|
||||
if (!timestamp) return '未知时间'
|
||||
const date = new Date(timestamp)
|
||||
return date.toLocaleString('zh-CN', {
|
||||
month: '2-digit',
|
||||
day: '2-digit',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
second: '2-digit'
|
||||
})
|
||||
}
|
||||
|
||||
// 计算时间范围显示
|
||||
const earliestTime = computed(() => {
|
||||
const explicitStart =
|
||||
@@ -212,55 +195,51 @@ const latestTime = computed(() => {
|
||||
return formatTimestamp(new Date().toISOString())
|
||||
})
|
||||
|
||||
function buildUsageTimelineSegments(
|
||||
statuses: string[],
|
||||
timeRangeStart: string | null,
|
||||
timeRangeEnd: string | null,
|
||||
lookbackHours: number
|
||||
function buildSegmentTooltip(
|
||||
status: string,
|
||||
cellStartTime: Date,
|
||||
cellEndTime: Date,
|
||||
cellEvents: Array<EndpointHealthEvent | PublicHealthEvent>
|
||||
) {
|
||||
const gridCount = statuses.length
|
||||
const endTime = timeRangeEnd ? new Date(timeRangeEnd).getTime() : Date.now()
|
||||
const startTime = timeRangeStart
|
||||
? new Date(timeRangeStart).getTime()
|
||||
: endTime - lookbackHours * 60 * 60 * 1000
|
||||
const safeRange = Math.max(endTime - startTime, 1)
|
||||
const interval = safeRange / gridCount
|
||||
const successCount = cellEvents.filter(event => event.status === 'success').length
|
||||
const failedCount = cellEvents.filter(event => event.status === 'failed').length
|
||||
const completedCount = successCount + failedCount
|
||||
const latencyValues = cellEvents
|
||||
.map(event => event.latency_ms)
|
||||
.filter((value): value is number => typeof value === 'number' && !Number.isNaN(value))
|
||||
const avgLatencyMs = latencyValues.length > 0
|
||||
? latencyValues.reduce((sum, value) => sum + value, 0) / latencyValues.length
|
||||
: null
|
||||
|
||||
return statuses.map((status, index) => {
|
||||
const cellStart = new Date(startTime + index * interval)
|
||||
const cellEnd = new Date(startTime + (index + 1) * interval)
|
||||
return {
|
||||
color: getHealthTimelineColor(status),
|
||||
tooltip: `${formatTimestamp(cellStart.toISOString())} - ${formatTimestamp(
|
||||
cellEnd.toISOString()
|
||||
)}\n状态:${getHealthTimelineLabel(status)}`
|
||||
}
|
||||
return formatTimelineTooltip({
|
||||
status,
|
||||
timeRangeStart: cellStartTime.toISOString(),
|
||||
timeRangeEnd: cellEndTime.toISOString(),
|
||||
metrics: {
|
||||
total_attempts: cellEvents.length,
|
||||
success_count: successCount,
|
||||
failed_count: failedCount,
|
||||
success_rate: completedCount > 0 ? successCount / completedCount : null,
|
||||
avg_latency_ms: avgLatencyMs,
|
||||
avg_first_byte_ms: null,
|
||||
avg_tps: null
|
||||
},
|
||||
entityLabel: '端点',
|
||||
entityName: props.monitor?.api_format
|
||||
})
|
||||
}
|
||||
|
||||
function getHealthTimelineColor(status: string) {
|
||||
switch (status) {
|
||||
case 'healthy':
|
||||
return 'bg-green-500/80 dark:bg-green-400/90'
|
||||
case 'warning':
|
||||
return 'bg-amber-400/80 dark:bg-amber-300/80'
|
||||
case 'unhealthy':
|
||||
return 'bg-red-500/80 dark:bg-red-400/90'
|
||||
default:
|
||||
return 'bg-gray-300 dark:bg-gray-600'
|
||||
}
|
||||
function getTimelineStatusFromEvents(
|
||||
cellEvents: Array<EndpointHealthEvent | PublicHealthEvent>
|
||||
) {
|
||||
const successCount = cellEvents.filter(event => event.status === 'success').length
|
||||
const failedCount = cellEvents.filter(event => event.status === 'failed').length
|
||||
const completedCount = successCount + failedCount
|
||||
if (completedCount === 0) return 'unknown'
|
||||
const successRate = successCount / completedCount
|
||||
if (successRate >= 0.95) return 'healthy'
|
||||
if (successRate >= 0.7) return 'warning'
|
||||
return 'unhealthy'
|
||||
}
|
||||
|
||||
function getHealthTimelineLabel(status: string) {
|
||||
switch (status) {
|
||||
case 'healthy':
|
||||
return '健康'
|
||||
case 'warning':
|
||||
return '警告'
|
||||
case 'unhealthy':
|
||||
return '异常'
|
||||
default:
|
||||
return '未知'
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
<template>
|
||||
<div class="grid w-full grid-cols-2 gap-2 sm:grid-cols-4">
|
||||
<div
|
||||
v-for="metric in metrics"
|
||||
:key="metric.label"
|
||||
class="rounded-lg border border-border/40 bg-muted/20 px-3 py-2"
|
||||
>
|
||||
<div class="text-[11px] leading-tight text-muted-foreground">
|
||||
{{ metric.label }}
|
||||
</div>
|
||||
<div
|
||||
class="mt-1 text-sm font-semibold tabular-nums"
|
||||
:class="metric.valueClass"
|
||||
>
|
||||
{{ metric.value }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import {
|
||||
formatAvailability,
|
||||
formatMs,
|
||||
formatTps,
|
||||
getAvailabilityClass
|
||||
} from './health-monitor-utils'
|
||||
|
||||
const props = defineProps<{
|
||||
avgLatencyMs?: number | null
|
||||
avgFirstByteMs?: number | null
|
||||
avgTps?: number | null
|
||||
totalAttempts: number
|
||||
successRate: number
|
||||
}>()
|
||||
|
||||
const availabilityItem = computed(() => ({
|
||||
total_attempts: props.totalAttempts,
|
||||
success_rate: props.successRate
|
||||
}))
|
||||
|
||||
const metrics = computed(() => [
|
||||
{
|
||||
label: '平均耗时',
|
||||
value: formatMs(props.avgLatencyMs),
|
||||
valueClass: ''
|
||||
},
|
||||
{
|
||||
label: '平均TTFB',
|
||||
value: formatMs(props.avgFirstByteMs),
|
||||
valueClass: ''
|
||||
},
|
||||
{
|
||||
label: '平均速度',
|
||||
value: formatTps(props.avgTps),
|
||||
valueClass: ''
|
||||
},
|
||||
{
|
||||
label: '可用率',
|
||||
value: formatAvailability(availabilityItem.value),
|
||||
valueClass: getAvailabilityClass(availabilityItem.value)
|
||||
}
|
||||
])
|
||||
</script>
|
||||
@@ -3,52 +3,14 @@
|
||||
variant="default"
|
||||
class="overflow-hidden"
|
||||
>
|
||||
<!-- 标题和筛选器 -->
|
||||
<div class="px-6 py-3.5 border-b border-border/60">
|
||||
<div class="flex items-center justify-between gap-4">
|
||||
<div>
|
||||
<h3 class="text-base font-semibold">
|
||||
{{ title }}
|
||||
</h3>
|
||||
<p class="mt-1 text-xs text-muted-foreground">
|
||||
基于真实请求统计端点可用率、请求成功率与健康历史
|
||||
</p>
|
||||
</div>
|
||||
<div class="flex items-center gap-3">
|
||||
<Label class="text-xs text-muted-foreground">回溯时间:</Label>
|
||||
<Select
|
||||
v-model="lookbackHours"
|
||||
>
|
||||
<SelectTrigger class="w-28 h-8 text-xs border-border/60">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="1">
|
||||
1 小时
|
||||
</SelectItem>
|
||||
<SelectItem value="6">
|
||||
6 小时
|
||||
</SelectItem>
|
||||
<SelectItem value="12">
|
||||
12 小时
|
||||
</SelectItem>
|
||||
<SelectItem value="24">
|
||||
24 小时
|
||||
</SelectItem>
|
||||
<SelectItem value="48">
|
||||
48 小时
|
||||
</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<RefreshButton
|
||||
:loading="loading"
|
||||
@click="refreshData"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<HealthMonitorHeader
|
||||
v-model:lookback-hours="lookbackHours"
|
||||
:title="title"
|
||||
description="基于真实请求统计端点可用率、平均耗时、平均TTFB 与平均速度"
|
||||
:loading="loading"
|
||||
@refresh="refreshData"
|
||||
/>
|
||||
|
||||
<!-- 内容区域 -->
|
||||
<div class="p-6">
|
||||
<div
|
||||
v-if="loadingMonitors"
|
||||
@@ -59,7 +21,7 @@
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-else-if="monitors.length === 0"
|
||||
v-else-if="visibleMonitors.length === 0"
|
||||
class="flex flex-col items-center justify-center py-12 text-muted-foreground"
|
||||
>
|
||||
<Activity class="w-12 h-12 mb-3 opacity-30" />
|
||||
@@ -71,59 +33,70 @@
|
||||
|
||||
<div
|
||||
v-else
|
||||
class="space-y-3"
|
||||
class="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4"
|
||||
>
|
||||
<div
|
||||
v-for="monitor in monitors"
|
||||
:key="monitor.api_format"
|
||||
class="border border-border/60 rounded-lg p-4 hover:border-primary/50 transition-colors"
|
||||
v-for="(monitor, index) in visibleMonitors"
|
||||
:key="`${monitor.api_format}-${index}`"
|
||||
class="relative overflow-hidden rounded-xl border border-border/60 bg-card/60 p-4 transition-colors hover:border-primary/50"
|
||||
>
|
||||
<!-- 响应式布局:窄屏上下两行,宽屏左右结构 -->
|
||||
<div class="flex flex-col sm:flex-row sm:gap-6 sm:items-center">
|
||||
<!-- 第一行/左侧:信息区域 -->
|
||||
<div class="sm:w-52 flex-shrink-0 space-y-1.5 mb-3 sm:mb-0">
|
||||
<!-- API 格式标签和成功率 -->
|
||||
<div class="flex items-center gap-2 flex-wrap">
|
||||
<Badge
|
||||
variant="outline"
|
||||
class="font-mono text-xs whitespace-nowrap"
|
||||
>
|
||||
{{ formatApiFormat(monitor.api_format) }}
|
||||
</Badge>
|
||||
<Badge
|
||||
v-if="monitor.total_attempts > 0"
|
||||
:variant="getSuccessRateVariant(monitor.success_rate)"
|
||||
class="text-xs whitespace-nowrap"
|
||||
>
|
||||
{{ (monitor.success_rate * 100).toFixed(0) }}%
|
||||
</Badge>
|
||||
<!-- 提供商信息(仅管理员可见)- 窄屏时显示在同一行 -->
|
||||
<span
|
||||
v-if="showProviderInfo && 'provider_count' in monitor"
|
||||
class="text-xs text-muted-foreground sm:hidden"
|
||||
>
|
||||
{{ monitor.provider_count }} 个提供商 / {{ monitor.key_count }} 个密钥
|
||||
</span>
|
||||
</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
|
||||
v-if="showProviderInfo && 'provider_count' in monitor"
|
||||
class="text-xs text-muted-foreground hidden sm:block"
|
||||
class="flex h-11 w-11 flex-shrink-0 items-center justify-center rounded-xl border border-border/60 bg-muted/50"
|
||||
>
|
||||
{{ monitor.provider_count }} 个提供商 / {{ monitor.key_count }} 个密钥
|
||||
<Activity class="h-5 w-5 text-muted-foreground" />
|
||||
</div>
|
||||
<div class="min-w-0">
|
||||
<h4 class="truncate text-sm font-semibold">
|
||||
{{ formatApiFormat(monitor.api_format) }}
|
||||
</h4>
|
||||
</div>
|
||||
</div>
|
||||
<Badge
|
||||
:variant="getHealthBadgeVariant(monitor)"
|
||||
class="shrink-0"
|
||||
>
|
||||
{{ getHealthLabel(monitor) }}
|
||||
</Badge>
|
||||
</div>
|
||||
|
||||
<!-- 第二行/右侧:时间线区域 -->
|
||||
<div class="flex-1 min-w-0 sm:flex sm:justify-end">
|
||||
<div class="w-full sm:max-w-5xl">
|
||||
<EndpointHealthTimeline
|
||||
:monitor="monitor"
|
||||
:lookback-hours="parseInt(lookbackHours)"
|
||||
/>
|
||||
</div>
|
||||
</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">
|
||||
{{ getEndpointMetaText(monitor) }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div class="mt-2">
|
||||
<EndpointHealthTimeline
|
||||
:monitor="monitor"
|
||||
:lookback-hours="parseInt(lookbackHours)"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="mt-4 flex justify-end">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
@click="openDetails(monitor)"
|
||||
>
|
||||
查看详情
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -132,23 +105,28 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, onMounted, watch } from 'vue'
|
||||
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 Label from '@/components/ui/label.vue'
|
||||
import Select from '@/components/ui/select.vue'
|
||||
import SelectTrigger from '@/components/ui/select-trigger.vue'
|
||||
import SelectValue from '@/components/ui/select-value.vue'
|
||||
import SelectContent from '@/components/ui/select-content.vue'
|
||||
import SelectItem from '@/components/ui/select-item.vue'
|
||||
import RefreshButton from '@/components/ui/refresh-button.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,
|
||||
summarizeHealthMonitorItems
|
||||
} from './health-monitor-utils'
|
||||
|
||||
type EndpointMonitor = EndpointStatusMonitor | PublicEndpointStatusMonitor
|
||||
|
||||
const props = withDefaults(defineProps<{
|
||||
title?: string
|
||||
@@ -160,12 +138,18 @@ const props = withDefaults(defineProps<{
|
||||
showProviderInfo: false
|
||||
})
|
||||
|
||||
const emit = defineEmits<{
|
||||
viewDetails: [target: HealthMonitorDetailTarget]
|
||||
summaryUpdated: [summary: HealthMonitorSectionSummary]
|
||||
}>()
|
||||
|
||||
const { error: showError } = useToast()
|
||||
|
||||
const loading = ref(false)
|
||||
const loadingMonitors = ref(false)
|
||||
const monitors = ref<(EndpointStatusMonitor | PublicEndpointStatusMonitor)[]>([])
|
||||
const monitors = ref<EndpointMonitor[]>([])
|
||||
const lookbackHours = ref('6')
|
||||
const visibleMonitors = computed(() => monitors.value.filter(monitor => monitor.total_attempts > 0))
|
||||
|
||||
async function loadMonitors() {
|
||||
loadingMonitors.value = true
|
||||
@@ -182,6 +166,7 @@ async function loadMonitors() {
|
||||
const data = await getPublicEndpointStatusMonitor(params)
|
||||
monitors.value = data.formats || []
|
||||
}
|
||||
emitSummary()
|
||||
} catch (err: unknown) {
|
||||
showError(parseApiError(err, '加载健康监控数据失败'), '错误')
|
||||
} finally {
|
||||
@@ -198,10 +183,60 @@ async function refreshData() {
|
||||
}
|
||||
}
|
||||
|
||||
function getSuccessRateVariant(rate: number): 'default' | 'secondary' | 'destructive' | 'outline' {
|
||||
if (rate >= 0.95) return 'default'
|
||||
if (rate >= 0.8) return 'secondary'
|
||||
return 'destructive'
|
||||
function getEndpointMetaText(monitor: EndpointMonitor) {
|
||||
const attempts = `${formatCompactNumber(monitor.total_attempts)} 次请求`
|
||||
if (props.showProviderInfo && hasProviderInfo(monitor)) {
|
||||
return `${monitor.provider_count} 个提供商 / ${monitor.key_count} 个密钥 / ${attempts}`
|
||||
}
|
||||
if (hasApiPath(monitor)) {
|
||||
return `${monitor.api_path} / ${attempts}`
|
||||
}
|
||||
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,
|
||||
timelineDetails: monitor.timeline_details || 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'
|
||||
}
|
||||
|
||||
function hasApiPath(monitor: EndpointMonitor): monitor is PublicEndpointStatusMonitor {
|
||||
return 'api_path' in monitor && typeof monitor.api_path === 'string' && monitor.api_path.length > 0
|
||||
}
|
||||
|
||||
watch(lookbackHours, () => {
|
||||
|
||||
@@ -0,0 +1,306 @@
|
||||
<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,
|
||||
timeline_details: source.timelineDetails || 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,
|
||||
timelineDetails: monitor.timeline_details || 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,71 @@
|
||||
<template>
|
||||
<div class="px-6 py-3.5 border-b border-border/60">
|
||||
<div class="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div>
|
||||
<h3 class="text-base font-semibold">
|
||||
{{ title }}
|
||||
</h3>
|
||||
<p class="mt-1 text-xs text-muted-foreground">
|
||||
{{ description }}
|
||||
</p>
|
||||
</div>
|
||||
<div class="flex items-center gap-3">
|
||||
<Label class="text-xs text-muted-foreground">回溯时间:</Label>
|
||||
<Select v-model="selectedLookbackHours">
|
||||
<SelectTrigger class="w-28 h-8 text-xs border-border/60">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="1">
|
||||
1 小时
|
||||
</SelectItem>
|
||||
<SelectItem value="6">
|
||||
6 小时
|
||||
</SelectItem>
|
||||
<SelectItem value="12">
|
||||
12 小时
|
||||
</SelectItem>
|
||||
<SelectItem value="24">
|
||||
24 小时
|
||||
</SelectItem>
|
||||
<SelectItem value="48">
|
||||
48 小时
|
||||
</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<RefreshButton
|
||||
:loading="loading"
|
||||
@click="$emit('refresh')"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import Label from '@/components/ui/label.vue'
|
||||
import Select from '@/components/ui/select.vue'
|
||||
import SelectTrigger from '@/components/ui/select-trigger.vue'
|
||||
import SelectValue from '@/components/ui/select-value.vue'
|
||||
import SelectContent from '@/components/ui/select-content.vue'
|
||||
import SelectItem from '@/components/ui/select-item.vue'
|
||||
import RefreshButton from '@/components/ui/refresh-button.vue'
|
||||
|
||||
const props = defineProps<{
|
||||
title: string
|
||||
description: string
|
||||
lookbackHours: string
|
||||
loading: boolean
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
'update:lookbackHours': [value: string]
|
||||
refresh: []
|
||||
}>()
|
||||
|
||||
const selectedLookbackHours = computed({
|
||||
get: () => props.lookbackHours,
|
||||
set: value => emit('update:lookbackHours', value)
|
||||
})
|
||||
</script>
|
||||
@@ -0,0 +1,133 @@
|
||||
<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"
|
||||
:timeline-details="monitor.timeline_details"
|
||||
: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>
|
||||
@@ -0,0 +1,128 @@
|
||||
<template>
|
||||
<div class="w-full space-y-1">
|
||||
<div class="flex h-6 w-full items-center gap-px">
|
||||
<TooltipProvider
|
||||
v-for="(segment, index) in segments"
|
||||
:key="index"
|
||||
:delay-duration="100"
|
||||
>
|
||||
<Tooltip>
|
||||
<TooltipTrigger as-child>
|
||||
<button
|
||||
type="button"
|
||||
:title="segment.tooltip"
|
||||
class="h-full flex-1 cursor-pointer rounded-sm border-0 p-0 transition-all duration-150 hover:scale-y-110 hover:brightness-110 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary"
|
||||
:class="getTimelineColor(segment.status)"
|
||||
/>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent
|
||||
side="top"
|
||||
:side-offset="8"
|
||||
class="max-w-xs"
|
||||
>
|
||||
<div class="text-xs whitespace-pre-line">
|
||||
{{ segment.tooltip }}
|
||||
</div>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
</div>
|
||||
|
||||
<div class="flex items-center justify-between text-[10px] text-muted-foreground">
|
||||
<span>{{ startLabel }}</span>
|
||||
<span>{{ endLabel }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'
|
||||
import {
|
||||
formatTimestamp,
|
||||
formatTimelineTooltip,
|
||||
getTimelineColor,
|
||||
type HealthTimelineTooltipMetrics
|
||||
} from './health-monitor-utils'
|
||||
|
||||
const props = withDefaults(defineProps<{
|
||||
timeline?: string[] | null
|
||||
timelineDetails?: HealthTimelineTooltipMetrics[] | null
|
||||
timeRangeStart?: string | null
|
||||
timeRangeEnd?: string | null
|
||||
generatedAt?: string | null
|
||||
lookbackHours?: number
|
||||
fallbackSegments?: number
|
||||
entityLabel?: string
|
||||
entityName?: string | null
|
||||
}>(), {
|
||||
lookbackHours: 6,
|
||||
fallbackSegments: 60,
|
||||
entityLabel: '',
|
||||
entityName: null
|
||||
})
|
||||
|
||||
const statuses = computed(() => {
|
||||
if (Array.isArray(props.timeline) && props.timeline.length > 0) {
|
||||
return props.timeline
|
||||
}
|
||||
return Array.from({ length: props.fallbackSegments }, () => 'unknown')
|
||||
})
|
||||
|
||||
const startMs = computed(() => {
|
||||
const explicitStart = props.timeRangeStart
|
||||
? new Date(props.timeRangeStart).getTime()
|
||||
: NaN
|
||||
if (!Number.isNaN(explicitStart)) return explicitStart
|
||||
return endMs.value - props.lookbackHours * 60 * 60 * 1000
|
||||
})
|
||||
|
||||
const endMs = computed(() => {
|
||||
const explicitEnd = props.timeRangeEnd
|
||||
? new Date(props.timeRangeEnd).getTime()
|
||||
: NaN
|
||||
if (!Number.isNaN(explicitEnd)) return explicitEnd
|
||||
const generatedAt = props.generatedAt
|
||||
? new Date(props.generatedAt).getTime()
|
||||
: NaN
|
||||
if (!Number.isNaN(generatedAt)) return generatedAt
|
||||
return Date.now()
|
||||
})
|
||||
|
||||
const startLabel = computed(() => formatTimestamp(new Date(startMs.value).toISOString()))
|
||||
const endLabel = computed(() => formatTimestamp(new Date(endMs.value).toISOString()))
|
||||
|
||||
const segments = computed(() => {
|
||||
const segmentStatuses = statuses.value
|
||||
const safeRange = Math.max(endMs.value - startMs.value, 1)
|
||||
const interval = safeRange / segmentStatuses.length
|
||||
|
||||
return segmentStatuses.map((status, index) => {
|
||||
const cellStart = new Date(startMs.value + index * interval).toISOString()
|
||||
const cellEnd = new Date(startMs.value + (index + 1) * interval).toISOString()
|
||||
const detail = props.timelineDetails?.[index] ?? null
|
||||
const timeRangeStart = detail?.time_range_start || cellStart
|
||||
const timeRangeEnd = detail?.time_range_end || cellEnd
|
||||
return {
|
||||
status,
|
||||
tooltip: buildTooltip(status, timeRangeStart, timeRangeEnd, detail)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
function buildTooltip(
|
||||
status: string,
|
||||
cellStart: string,
|
||||
cellEnd: string,
|
||||
detail: HealthTimelineTooltipMetrics | null
|
||||
) {
|
||||
return formatTimelineTooltip({
|
||||
status,
|
||||
timeRangeStart: cellStart,
|
||||
timeRangeEnd: cellEnd,
|
||||
metrics: detail,
|
||||
entityLabel: props.entityLabel,
|
||||
entityName: props.entityName
|
||||
})
|
||||
}
|
||||
</script>
|
||||
@@ -1,49 +1,12 @@
|
||||
<template>
|
||||
<Card
|
||||
variant="default"
|
||||
class="overflow-hidden"
|
||||
>
|
||||
<div class="px-6 py-3.5 border-b border-border/60">
|
||||
<div class="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div>
|
||||
<h3 class="text-base font-semibold">
|
||||
{{ title }}
|
||||
</h3>
|
||||
<p class="mt-1 text-xs text-muted-foreground">
|
||||
基于真实请求统计模型可用率、响应延迟与首包延迟
|
||||
</p>
|
||||
</div>
|
||||
<div class="flex items-center gap-3">
|
||||
<Label class="text-xs text-muted-foreground">回溯时间:</Label>
|
||||
<Select v-model="lookbackHours">
|
||||
<SelectTrigger class="w-28 h-8 text-xs border-border/60">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="1">
|
||||
1 小时
|
||||
</SelectItem>
|
||||
<SelectItem value="6">
|
||||
6 小时
|
||||
</SelectItem>
|
||||
<SelectItem value="12">
|
||||
12 小时
|
||||
</SelectItem>
|
||||
<SelectItem value="24">
|
||||
24 小时
|
||||
</SelectItem>
|
||||
<SelectItem value="48">
|
||||
48 小时
|
||||
</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<RefreshButton
|
||||
:loading="loading"
|
||||
@click="refreshData"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<Card variant="default" class="overflow-hidden">
|
||||
<HealthMonitorHeader
|
||||
v-model:lookback-hours="lookbackHours"
|
||||
:title="title"
|
||||
description="基于真实请求统计模型可用率、平均耗时、平均TTFB 与平均速度"
|
||||
:loading="loading"
|
||||
@refresh="refreshData"
|
||||
/>
|
||||
|
||||
<div class="p-6">
|
||||
<div
|
||||
@@ -60,106 +23,72 @@
|
||||
>
|
||||
<Bot class="w-12 h-12 mb-3 opacity-30" />
|
||||
<p>暂无模型健康监控数据</p>
|
||||
<p class="text-xs mt-1">
|
||||
模型尚未产生请求记录
|
||||
</p>
|
||||
<p class="text-xs mt-1">模型尚未产生请求记录</p>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-else
|
||||
class="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4"
|
||||
>
|
||||
<div v-else class="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4">
|
||||
<div
|
||||
v-for="monitor in monitors"
|
||||
:key="monitor.model"
|
||||
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="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">
|
||||
<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">
|
||||
{{ monitor.display_name || monitor.model }}
|
||||
</h4>
|
||||
</div>
|
||||
<Badge
|
||||
:variant="getHealthBadgeVariant(monitor)"
|
||||
class="shrink-0"
|
||||
>
|
||||
<Badge :variant="getHealthBadgeVariant(monitor)" class="shrink-0">
|
||||
{{ getHealthLabel(monitor) }}
|
||||
</Badge>
|
||||
</div>
|
||||
|
||||
<div class="mt-4 grid grid-cols-3 gap-2">
|
||||
<div class="rounded-lg border border-border/40 bg-muted/20 px-3 py-2">
|
||||
<div class="flex items-center gap-1.5 text-[11px] text-muted-foreground">
|
||||
<Gauge class="h-3.5 w-3.5" />
|
||||
延迟
|
||||
</div>
|
||||
<div class="mt-1 text-sm font-semibold tabular-nums">
|
||||
{{ formatMs(monitor.avg_latency_ms) }}
|
||||
</div>
|
||||
</div>
|
||||
<div class="rounded-lg border border-border/40 bg-muted/20 px-3 py-2">
|
||||
<div class="flex items-center gap-1.5 text-[11px] text-muted-foreground">
|
||||
<Radio class="h-3.5 w-3.5" />
|
||||
Ping
|
||||
</div>
|
||||
<div class="mt-1 text-sm font-semibold tabular-nums">
|
||||
{{ formatMs(monitor.avg_first_byte_ms) }}
|
||||
</div>
|
||||
</div>
|
||||
<div class="rounded-lg border border-border/40 bg-muted/20 px-3 py-2">
|
||||
<div class="flex items-center gap-1.5 text-[11px] text-muted-foreground">
|
||||
<Activity class="h-3.5 w-3.5" />
|
||||
可用率
|
||||
</div>
|
||||
<div
|
||||
class="mt-1 text-sm font-semibold tabular-nums"
|
||||
:class="getSuccessRateClass(monitor.success_rate)"
|
||||
>
|
||||
{{ formatPercent(monitor.success_rate) }}
|
||||
</div>
|
||||
</div>
|
||||
</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">
|
||||
<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">
|
||||
{{ getModelMetaText(monitor) }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<TooltipProvider :delay-duration="100">
|
||||
<div class="mt-2 flex h-7 w-full items-center gap-px">
|
||||
<Tooltip
|
||||
v-for="(segment, index) in timelineSegments(monitor)"
|
||||
:key="`${monitor.model}-${index}`"
|
||||
>
|
||||
<TooltipTrigger as-child>
|
||||
<div
|
||||
class="h-full flex-1 rounded-[2px] transition-all duration-150 hover:scale-y-110 hover:brightness-110"
|
||||
:class="getTimelineColor(segment)"
|
||||
/>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent
|
||||
side="top"
|
||||
:side-offset="8"
|
||||
class="max-w-xs"
|
||||
>
|
||||
<div class="text-xs whitespace-pre-line">
|
||||
{{ buildTimelineTooltip(monitor, segment, index) }}
|
||||
</div>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</div>
|
||||
</TooltipProvider>
|
||||
<HealthStatusTimeline
|
||||
class="mt-2"
|
||||
:timeline="monitor.timeline"
|
||||
:timeline-details="monitor.timeline_details"
|
||||
:time-range-start="monitor.time_range_start"
|
||||
:time-range-end="monitor.time_range_end"
|
||||
:generated-at="generatedAt"
|
||||
:lookback-hours="parseInt(lookbackHours)"
|
||||
entity-label="模型"
|
||||
:entity-name="monitor.model"
|
||||
/>
|
||||
|
||||
<div class="mt-2 flex items-center justify-between text-[10px] text-muted-foreground">
|
||||
<span>{{ formatTimestamp(monitor.time_range_start) }}</span>
|
||||
<span>{{ formatTimestamp(monitor.time_range_end || generatedAt) }}</span>
|
||||
<div class="mt-4 flex justify-end">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
@click="openDetails(monitor)"
|
||||
>
|
||||
查看详情
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -168,182 +97,136 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, onMounted, watch } from 'vue'
|
||||
import { Activity, Bot, Gauge, Loader2, Radio } from 'lucide-vue-next'
|
||||
import Card from '@/components/ui/card.vue'
|
||||
import Badge from '@/components/ui/badge.vue'
|
||||
import Label from '@/components/ui/label.vue'
|
||||
import Select from '@/components/ui/select.vue'
|
||||
import SelectTrigger from '@/components/ui/select-trigger.vue'
|
||||
import SelectValue from '@/components/ui/select-value.vue'
|
||||
import SelectContent from '@/components/ui/select-content.vue'
|
||||
import SelectItem from '@/components/ui/select-item.vue'
|
||||
import RefreshButton from '@/components/ui/refresh-button.vue'
|
||||
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'
|
||||
import { getModelStatusMonitor, getPublicModelStatusMonitor } from '@/api/endpoints/health'
|
||||
import type { ModelStatusMonitor } from '@/api/endpoints/types'
|
||||
import { useToast } from '@/composables/useToast'
|
||||
import { parseApiError } from '@/utils/errorParser'
|
||||
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";
|
||||
import {
|
||||
getModelStatusMonitor,
|
||||
getPublicModelStatusMonitor,
|
||||
} from "@/api/endpoints/health";
|
||||
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(defineProps<{
|
||||
title?: string
|
||||
isAdmin?: boolean
|
||||
showProviderInfo?: boolean
|
||||
}>(), {
|
||||
title: '模型健康监控',
|
||||
isAdmin: false,
|
||||
showProviderInfo: false
|
||||
})
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
title?: string;
|
||||
isAdmin?: boolean;
|
||||
showProviderInfo?: boolean;
|
||||
}>(),
|
||||
{
|
||||
title: "模型健康监控",
|
||||
isAdmin: false,
|
||||
showProviderInfo: false,
|
||||
},
|
||||
);
|
||||
|
||||
const { error: showError } = useToast()
|
||||
const emit = defineEmits<{
|
||||
viewDetails: [target: HealthMonitorDetailTarget];
|
||||
summaryUpdated: [summary: HealthMonitorSectionSummary];
|
||||
}>();
|
||||
|
||||
const loading = ref(false)
|
||||
const loadingMonitors = ref(false)
|
||||
const monitors = ref<ModelStatusMonitor[]>([])
|
||||
const generatedAt = ref<string | null>(null)
|
||||
const lookbackHours = ref('6')
|
||||
const { error: showError } = useToast();
|
||||
|
||||
const loading = ref(false);
|
||||
const loadingMonitors = ref(false);
|
||||
const monitors = ref<ModelStatusMonitor[]>([]);
|
||||
const generatedAt = ref<string | null>(null);
|
||||
const lookbackHours = ref("6");
|
||||
|
||||
async function loadMonitors() {
|
||||
loadingMonitors.value = true
|
||||
loadingMonitors.value = true;
|
||||
try {
|
||||
const params = {
|
||||
lookback_hours: parseInt(lookbackHours.value),
|
||||
model_limit: 12,
|
||||
per_model_limit: 100
|
||||
}
|
||||
per_model_limit: 100,
|
||||
};
|
||||
|
||||
const data = props.isAdmin
|
||||
? await getModelStatusMonitor(params)
|
||||
: await getPublicModelStatusMonitor(params)
|
||||
monitors.value = data.models || []
|
||||
generatedAt.value = data.generated_at || null
|
||||
: await getPublicModelStatusMonitor(params);
|
||||
monitors.value = data.models || [];
|
||||
generatedAt.value = data.generated_at || null;
|
||||
emitSummary();
|
||||
} catch (err: unknown) {
|
||||
showError(parseApiError(err, '加载模型健康监控数据失败'), '错误')
|
||||
showError(parseApiError(err, "加载模型健康监控数据失败"), "错误");
|
||||
} finally {
|
||||
loadingMonitors.value = false
|
||||
loadingMonitors.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function refreshData() {
|
||||
loading.value = true
|
||||
loading.value = true;
|
||||
try {
|
||||
await loadMonitors()
|
||||
await loadMonitors();
|
||||
} finally {
|
||||
loading.value = false
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function getHealthLabel(monitor: ModelStatusMonitor) {
|
||||
if (monitor.total_attempts <= 0) return '未知'
|
||||
if (monitor.success_rate >= 0.95) return '正常'
|
||||
if (monitor.success_rate >= 0.8) return '波动'
|
||||
return '异常'
|
||||
}
|
||||
|
||||
function getHealthBadgeVariant(monitor: ModelStatusMonitor): 'default' | 'secondary' | 'destructive' | 'outline' | 'success' | 'warning' | 'dark' {
|
||||
if (monitor.total_attempts <= 0) return 'outline'
|
||||
if (monitor.success_rate >= 0.95) return 'success'
|
||||
if (monitor.success_rate >= 0.8) return 'warning'
|
||||
return 'destructive'
|
||||
}
|
||||
|
||||
function getSuccessRateClass(rate: number) {
|
||||
if (rate >= 0.95) return 'text-green-600 dark:text-green-400'
|
||||
if (rate >= 0.8) return 'text-amber-600 dark:text-amber-400'
|
||||
return 'text-red-600 dark:text-red-400'
|
||||
}
|
||||
|
||||
function getModelMetaText(monitor: ModelStatusMonitor) {
|
||||
const attempts = `${formatCompactNumber(monitor.total_attempts)} 次请求`
|
||||
if (props.showProviderInfo && typeof monitor.provider_count === 'number') {
|
||||
return `${monitor.provider_count} 个提供商 / ${attempts}`
|
||||
const attempts = `${formatCompactNumber(monitor.total_attempts)} 次请求`;
|
||||
if (props.showProviderInfo && typeof monitor.provider_count === "number") {
|
||||
return `${monitor.provider_count} 个提供商 / ${attempts}`;
|
||||
}
|
||||
return attempts
|
||||
return attempts;
|
||||
}
|
||||
|
||||
function formatMs(value?: number | null) {
|
||||
if (typeof value !== 'number' || Number.isNaN(value)) return '-'
|
||||
const absValue = Math.abs(value)
|
||||
if (absValue < 1000) return `${Math.round(value)} ms`
|
||||
if (absValue < 60_000) return `${formatDurationNumber(value / 1000)} s`
|
||||
return `${formatDurationNumber(value / 60_000)} min`
|
||||
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,
|
||||
timelineDetails: monitor.timeline_details || null,
|
||||
timeRangeStart: monitor.time_range_start || null,
|
||||
timeRangeEnd: monitor.time_range_end || null,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function formatDurationNumber(value: number) {
|
||||
return new Intl.NumberFormat('zh-CN', {
|
||||
maximumFractionDigits: Math.abs(value) < 10 ? 2 : 1
|
||||
}).format(value)
|
||||
}
|
||||
|
||||
function formatPercent(value: number) {
|
||||
if (typeof value !== 'number' || Number.isNaN(value)) return '-'
|
||||
return `${(value * 100).toFixed(2)}%`
|
||||
}
|
||||
|
||||
function formatCompactNumber(value: number) {
|
||||
return new Intl.NumberFormat('zh-CN', { notation: 'compact', maximumFractionDigits: 1 }).format(value)
|
||||
}
|
||||
|
||||
function timelineSegments(monitor: ModelStatusMonitor) {
|
||||
const timeline = Array.isArray(monitor.timeline) ? monitor.timeline : []
|
||||
if (timeline.length > 0) return timeline
|
||||
return Array.from({ length: 60 }, () => 'unknown')
|
||||
}
|
||||
|
||||
function getTimelineColor(status: string) {
|
||||
switch (status) {
|
||||
case 'healthy':
|
||||
return 'bg-green-500/85 dark:bg-green-400/90'
|
||||
case 'warning':
|
||||
return 'bg-amber-400/85 dark:bg-amber-300/85'
|
||||
case 'unhealthy':
|
||||
return 'bg-red-500/85 dark:bg-red-400/90'
|
||||
default:
|
||||
return 'bg-gray-300 dark:bg-gray-600'
|
||||
function getModelDetailMetaText(monitor: ModelStatusMonitor) {
|
||||
if (props.showProviderInfo && typeof monitor.provider_count === "number") {
|
||||
return `${monitor.provider_count} 个提供商`;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function getTimelineLabel(status: string) {
|
||||
switch (status) {
|
||||
case 'healthy':
|
||||
return '健康'
|
||||
case 'warning':
|
||||
return '波动'
|
||||
case 'unhealthy':
|
||||
return '异常'
|
||||
default:
|
||||
return '无请求'
|
||||
}
|
||||
}
|
||||
|
||||
function buildTimelineTooltip(monitor: ModelStatusMonitor, status: string, index: number) {
|
||||
const segmentCount = timelineSegments(monitor).length
|
||||
const startMs = monitor.time_range_start ? new Date(monitor.time_range_start).getTime() : Date.now() - parseInt(lookbackHours.value) * 60 * 60 * 1000
|
||||
const endMs = monitor.time_range_end ? new Date(monitor.time_range_end).getTime() : Date.now()
|
||||
const interval = Math.max(endMs - startMs, 1) / segmentCount
|
||||
const cellStart = new Date(startMs + index * interval).toISOString()
|
||||
const cellEnd = new Date(startMs + (index + 1) * interval).toISOString()
|
||||
return `${formatTimestamp(cellStart)} - ${formatTimestamp(cellEnd)}\n模型:${monitor.model}\n状态:${getTimelineLabel(status)}`
|
||||
}
|
||||
|
||||
function formatTimestamp(timestamp?: string | null) {
|
||||
if (!timestamp) return '未知时间'
|
||||
const date = new Date(timestamp)
|
||||
if (Number.isNaN(date.getTime())) return '未知时间'
|
||||
return date.toLocaleString('zh-CN', {
|
||||
month: '2-digit',
|
||||
day: '2-digit',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
second: '2-digit'
|
||||
})
|
||||
function emitSummary() {
|
||||
emit("summaryUpdated", summarizeHealthMonitorItems(monitors.value));
|
||||
}
|
||||
|
||||
watch(lookbackHours, () => {
|
||||
loadMonitors()
|
||||
})
|
||||
loadMonitors();
|
||||
});
|
||||
|
||||
onMounted(() => {
|
||||
refreshData()
|
||||
})
|
||||
refreshData();
|
||||
});
|
||||
</script>
|
||||
|
||||
@@ -681,10 +681,10 @@
|
||||
<span>成功 {{ importTask.success }} · 失败 {{ importTask.failed }}</span>
|
||||
</div>
|
||||
<p
|
||||
v-if="importTask.message"
|
||||
v-if="importTaskMessageText"
|
||||
class="text-[11px] text-muted-foreground"
|
||||
>
|
||||
{{ importTask.message }}
|
||||
{{ importTaskMessageText }}
|
||||
</p>
|
||||
<div
|
||||
v-if="importTask.error_samples.length > 0"
|
||||
@@ -926,6 +926,7 @@ const importInputResetKey = ref(0)
|
||||
const importTask = ref<OAuthBatchImportTaskStatusResponse | null>(null)
|
||||
let importPollTimer: ReturnType<typeof setTimeout> | null = null
|
||||
const importPolling = ref(false)
|
||||
const redundantImportTaskMessagePattern = /^处理中(?:\s+\d+\s*\/\s*\d+)?$/
|
||||
const windsurfImportMethod = ref<WindsurfImportMethod>('email_password')
|
||||
const windsurfEmail = ref('')
|
||||
const windsurfPassword = ref('')
|
||||
@@ -1036,6 +1037,13 @@ const importButtonText = computed(() => {
|
||||
return isWindsurfEmailPasswordImport.value ? '登录并导入' : importButtonLabel.value
|
||||
})
|
||||
|
||||
const importTaskMessageText = computed(() => {
|
||||
const message = importTask.value?.message?.trim()
|
||||
if (!message) return ''
|
||||
// 后端进度 message 已由“进度 x/y”展示,避免在导入中重复显示“处理中 x/y”。
|
||||
return redundantImportTaskMessagePattern.test(message) ? '' : message
|
||||
})
|
||||
|
||||
function stopImportPolling() {
|
||||
if (importPollTimer) {
|
||||
clearTimeout(importPollTimer)
|
||||
|
||||
@@ -3,47 +3,13 @@
|
||||
variant="default"
|
||||
class="overflow-hidden"
|
||||
>
|
||||
<div class="px-6 py-3.5 border-b border-border/60">
|
||||
<div class="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div>
|
||||
<h3 class="text-base font-semibold">
|
||||
{{ title }}
|
||||
</h3>
|
||||
<p class="mt-1 text-xs text-muted-foreground">
|
||||
仅展示活跃提供商,展开后查看该提供商下的模型健康明细
|
||||
</p>
|
||||
</div>
|
||||
<div class="flex items-center gap-3">
|
||||
<Label class="text-xs text-muted-foreground">回溯时间:</Label>
|
||||
<Select v-model="lookbackHours">
|
||||
<SelectTrigger class="w-28 h-8 text-xs border-border/60">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="1">
|
||||
1 小时
|
||||
</SelectItem>
|
||||
<SelectItem value="6">
|
||||
6 小时
|
||||
</SelectItem>
|
||||
<SelectItem value="12">
|
||||
12 小时
|
||||
</SelectItem>
|
||||
<SelectItem value="24">
|
||||
24 小时
|
||||
</SelectItem>
|
||||
<SelectItem value="48">
|
||||
48 小时
|
||||
</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<RefreshButton
|
||||
:loading="loading"
|
||||
@click="refreshData"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<HealthMonitorHeader
|
||||
v-model:lookback-hours="lookbackHours"
|
||||
:title="title"
|
||||
description="仅展示活跃提供商,点击详情查看该提供商关联的端点与模型健康"
|
||||
:loading="loading"
|
||||
@refresh="refreshData"
|
||||
/>
|
||||
|
||||
<div class="p-6">
|
||||
<div
|
||||
@@ -55,209 +21,108 @@
|
||||
</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>
|
||||
|
||||
<div class="grid w-full grid-cols-3 gap-2 lg:max-w-xl">
|
||||
<MetricBox
|
||||
label="延迟"
|
||||
:value="formatMs(provider.avg_latency_ms)"
|
||||
/>
|
||||
<MetricBox
|
||||
label="Ping"
|
||||
:value="formatMs(provider.avg_first_byte_ms)"
|
||||
/>
|
||||
<MetricBox
|
||||
label="可用率"
|
||||
:value="formatPercent(provider.success_rate)"
|
||||
:value-class="getSuccessRateClass(provider.success_rate)"
|
||||
/>
|
||||
</div>
|
||||
</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>
|
||||
|
||||
<div class="mt-4 grid grid-cols-3 gap-2">
|
||||
<MetricBox
|
||||
label="延迟"
|
||||
:value="formatMs(model.avg_latency_ms)"
|
||||
/>
|
||||
<MetricBox
|
||||
label="Ping"
|
||||
:value="formatMs(model.avg_first_byte_ms)"
|
||||
/>
|
||||
<MetricBox
|
||||
label="可用率"
|
||||
:value="formatPercent(model.success_rate)"
|
||||
:value-class="getSuccessRateClass(model.success_rate)"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<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>
|
||||
|
||||
<TooltipProvider :delay-duration="100">
|
||||
<div class="mt-2 flex h-7 w-full items-center gap-px">
|
||||
<Tooltip
|
||||
v-for="(segment, index) in timelineSegments(model)"
|
||||
:key="`${provider.provider_id}-${model.model}-${index}`"
|
||||
>
|
||||
<TooltipTrigger as-child>
|
||||
<div
|
||||
class="h-full flex-1 rounded-[2px] transition-all duration-150 hover:scale-y-110 hover:brightness-110"
|
||||
:class="getTimelineColor(segment)"
|
||||
/>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent
|
||||
side="top"
|
||||
:side-offset="8"
|
||||
class="max-w-xs"
|
||||
>
|
||||
<div class="text-xs whitespace-pre-line">
|
||||
{{ buildTimelineTooltip(model, segment, index) }}
|
||||
</div>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</div>
|
||||
</TooltipProvider>
|
||||
|
||||
<div class="mt-2 flex items-center justify-between text-[10px] text-muted-foreground">
|
||||
<span>{{ formatTimestamp(model.time_range_start) }}</span>
|
||||
<span>{{ formatTimestamp(model.time_range_end || generatedAt) }}</span>
|
||||
</div>
|
||||
<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"
|
||||
:timeline-details="provider.timeline_details"
|
||||
: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 { defineComponent, h, 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 Label from '@/components/ui/label.vue'
|
||||
import Select from '@/components/ui/select.vue'
|
||||
import SelectTrigger from '@/components/ui/select-trigger.vue'
|
||||
import SelectValue from '@/components/ui/select-value.vue'
|
||||
import SelectContent from '@/components/ui/select-content.vue'
|
||||
import SelectItem from '@/components/ui/select-item.vue'
|
||||
import RefreshButton from '@/components/ui/refresh-button.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 { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'
|
||||
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 { ModelStatusMonitor, ProviderStatusMonitor } from '@/api/endpoints/types'
|
||||
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'
|
||||
|
||||
type HealthMonitorItem = Pick<ProviderStatusMonitor | ModelStatusMonitor, 'total_attempts' | 'success_rate'>
|
||||
|
||||
const MetricBox = defineComponent({
|
||||
props: {
|
||||
label: { type: String, required: true },
|
||||
value: { type: String, required: true },
|
||||
valueClass: { type: String, default: '' }
|
||||
},
|
||||
setup(props) {
|
||||
return () => h('div', { class: 'rounded-lg border border-border/40 bg-muted/20 px-3 py-2' }, [
|
||||
h('div', { class: 'text-[11px] text-muted-foreground' }, props.label),
|
||||
h('div', { class: ['mt-1 text-sm font-semibold tabular-nums', props.valueClass] }, props.value)
|
||||
])
|
||||
}
|
||||
})
|
||||
import {
|
||||
formatCompactNumber,
|
||||
getHealthBadgeVariant,
|
||||
getHealthLabel,
|
||||
summarizeHealthMonitorItems
|
||||
} from './health-monitor-utils'
|
||||
|
||||
const props = withDefaults(defineProps<{
|
||||
title?: string
|
||||
@@ -265,6 +130,11 @@ const props = withDefaults(defineProps<{
|
||||
title: '提供商健康监控'
|
||||
})
|
||||
|
||||
const emit = defineEmits<{
|
||||
viewDetails: [target: HealthMonitorDetailTarget]
|
||||
summaryUpdated: [summary: HealthMonitorSectionSummary]
|
||||
}>()
|
||||
|
||||
const { error: showError } = useToast()
|
||||
|
||||
const loading = ref(false)
|
||||
@@ -272,7 +142,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
|
||||
@@ -285,7 +155,7 @@ async function loadMonitors() {
|
||||
})
|
||||
providers.value = data.providers || []
|
||||
generatedAt.value = data.generated_at || null
|
||||
ensureExpandedProviderState()
|
||||
emitSummary()
|
||||
} catch (err: unknown) {
|
||||
showError(parseApiError(err, '加载提供商健康监控数据失败'), '错误')
|
||||
} finally {
|
||||
@@ -302,119 +172,38 @@ 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 getHealthLabel(item: HealthMonitorItem) {
|
||||
if (item.total_attempts <= 0) return '暂无请求'
|
||||
if (item.success_rate >= 0.95) return '正常'
|
||||
if (item.success_rate >= 0.8) return '波动'
|
||||
return '异常'
|
||||
}
|
||||
|
||||
function getHealthBadgeVariant(item: HealthMonitorItem): 'default' | 'secondary' | 'destructive' | 'outline' | 'success' | 'warning' | 'dark' {
|
||||
if (item.total_attempts <= 0) return 'outline'
|
||||
if (item.success_rate >= 0.95) return 'success'
|
||||
if (item.success_rate >= 0.8) return 'warning'
|
||||
return 'destructive'
|
||||
}
|
||||
|
||||
function getSuccessRateClass(rate: number) {
|
||||
if (rate >= 0.95) return 'text-green-600 dark:text-green-400'
|
||||
if (rate >= 0.8) return 'text-amber-600 dark:text-amber-400'
|
||||
return 'text-red-600 dark:text-red-400'
|
||||
}
|
||||
|
||||
function getProviderMetaText(provider: ProviderStatusMonitor) {
|
||||
const attempts = `${formatCompactNumber(provider.total_attempts)} 次请求`
|
||||
return `${provider.model_count} 个模型 / ${attempts}`
|
||||
}
|
||||
|
||||
function formatMs(value?: number | null) {
|
||||
if (typeof value !== 'number' || Number.isNaN(value)) return '-'
|
||||
const absValue = Math.abs(value)
|
||||
if (absValue < 1000) return `${Math.round(value)} ms`
|
||||
if (absValue < 60_000) return `${formatDurationNumber(value / 1000)} s`
|
||||
return `${formatDurationNumber(value / 60_000)} min`
|
||||
}
|
||||
|
||||
function formatDurationNumber(value: number) {
|
||||
return new Intl.NumberFormat('zh-CN', {
|
||||
maximumFractionDigits: Math.abs(value) < 10 ? 2 : 1
|
||||
}).format(value)
|
||||
}
|
||||
|
||||
function formatPercent(value: number) {
|
||||
if (typeof value !== 'number' || Number.isNaN(value)) return '-'
|
||||
return `${(value * 100).toFixed(2)}%`
|
||||
}
|
||||
|
||||
function formatCompactNumber(value: number) {
|
||||
return new Intl.NumberFormat('zh-CN', { notation: 'compact', maximumFractionDigits: 1 }).format(value)
|
||||
}
|
||||
|
||||
function timelineSegments(item: ModelStatusMonitor | ProviderStatusMonitor) {
|
||||
const timeline = Array.isArray(item.timeline) ? item.timeline : []
|
||||
if (timeline.length > 0) return timeline
|
||||
return Array.from({ length: 60 }, () => 'unknown')
|
||||
}
|
||||
|
||||
function getTimelineColor(status: string) {
|
||||
switch (status) {
|
||||
case 'healthy':
|
||||
return 'bg-green-500/85 dark:bg-green-400/90'
|
||||
case 'warning':
|
||||
return 'bg-amber-400/85 dark:bg-amber-300/85'
|
||||
case 'unhealthy':
|
||||
return 'bg-red-500/85 dark:bg-red-400/90'
|
||||
default:
|
||||
return 'bg-gray-300 dark:bg-gray-600'
|
||||
}
|
||||
}
|
||||
|
||||
function getTimelineLabel(status: string) {
|
||||
switch (status) {
|
||||
case 'healthy':
|
||||
return '健康'
|
||||
case 'warning':
|
||||
return '波动'
|
||||
case 'unhealthy':
|
||||
return '异常'
|
||||
default:
|
||||
return '无请求'
|
||||
}
|
||||
}
|
||||
|
||||
function buildTimelineTooltip(model: ModelStatusMonitor, status: string, index: number) {
|
||||
const segmentCount = timelineSegments(model).length
|
||||
const startMs = model.time_range_start ? new Date(model.time_range_start).getTime() : Date.now() - parseInt(lookbackHours.value) * 60 * 60 * 1000
|
||||
const endMs = model.time_range_end ? new Date(model.time_range_end).getTime() : Date.now()
|
||||
const interval = Math.max(endMs - startMs, 1) / segmentCount
|
||||
const cellStart = new Date(startMs + index * interval).toISOString()
|
||||
const cellEnd = new Date(startMs + (index + 1) * interval).toISOString()
|
||||
return `${formatTimestamp(cellStart)} - ${formatTimestamp(cellEnd)}\n模型:${model.model}\n状态:${getTimelineLabel(status)}`
|
||||
}
|
||||
|
||||
function formatTimestamp(timestamp?: string | null) {
|
||||
if (!timestamp) return '未知时间'
|
||||
const date = new Date(timestamp)
|
||||
if (Number.isNaN(date.getTime())) return '未知时间'
|
||||
return date.toLocaleString('zh-CN', {
|
||||
month: '2-digit',
|
||||
day: '2-digit',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
second: '2-digit'
|
||||
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,
|
||||
timelineDetails: provider.timeline_details || null,
|
||||
timeRangeStart: provider.time_range_start || null,
|
||||
timeRangeEnd: provider.time_range_end || null
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
function emitSummary() {
|
||||
emit('summaryUpdated', summarizeHealthMonitorItems(visibleProviders.value))
|
||||
}
|
||||
|
||||
watch(lookbackHours, () => {
|
||||
loadMonitors()
|
||||
})
|
||||
|
||||
@@ -0,0 +1,259 @@
|
||||
export type HealthBadgeVariant =
|
||||
| 'default'
|
||||
| 'secondary'
|
||||
| 'destructive'
|
||||
| 'outline'
|
||||
| 'success'
|
||||
| '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
|
||||
timelineDetails?: HealthTimelineTooltipMetrics[] | 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 HealthTimelineTooltipMetrics {
|
||||
time_range_start?: string | null
|
||||
time_range_end?: string | null
|
||||
total_attempts?: number | null
|
||||
success_count?: number | null
|
||||
failed_count?: number | null
|
||||
success_rate?: number | null
|
||||
avg_latency_ms?: number | null
|
||||
avg_first_byte_ms?: number | null
|
||||
avg_tps?: number | null
|
||||
}
|
||||
|
||||
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 = '暂无请求'
|
||||
) {
|
||||
if (item.total_attempts <= 0) return emptyLabel
|
||||
if (item.success_rate >= 0.95) return '正常'
|
||||
if (item.success_rate >= 0.8) return '波动'
|
||||
return '异常'
|
||||
}
|
||||
|
||||
export function getHealthBadgeVariant(
|
||||
item: HealthMonitorAvailability
|
||||
): HealthBadgeVariant {
|
||||
if (item.total_attempts <= 0) return 'outline'
|
||||
if (item.success_rate >= 0.95) return 'success'
|
||||
if (item.success_rate >= 0.8) return 'warning'
|
||||
return 'destructive'
|
||||
}
|
||||
|
||||
export function getSuccessRateClass(rate: number) {
|
||||
if (rate >= 0.95) return 'text-green-600 dark:text-green-400'
|
||||
if (rate >= 0.8) return 'text-amber-600 dark:text-amber-400'
|
||||
return 'text-red-600 dark:text-red-400'
|
||||
}
|
||||
|
||||
export function getAvailabilityClass(item: HealthMonitorAvailability) {
|
||||
if (item.total_attempts <= 0) return ''
|
||||
return getSuccessRateClass(item.success_rate)
|
||||
}
|
||||
|
||||
export function formatMs(value?: number | null) {
|
||||
if (typeof value !== 'number' || Number.isNaN(value)) return '-'
|
||||
const absValue = Math.abs(value)
|
||||
if (absValue < 1000) return `${Math.round(value)} ms`
|
||||
if (absValue < 60_000) return `${formatDurationNumber(value / 1000)} s`
|
||||
return `${formatDurationNumber(value / 60_000)} min`
|
||||
}
|
||||
|
||||
function formatDurationNumber(value: number) {
|
||||
return new Intl.NumberFormat('zh-CN', {
|
||||
maximumFractionDigits: Math.abs(value) < 10 ? 2 : 1
|
||||
}).format(value)
|
||||
}
|
||||
|
||||
export function formatPercent(value: number) {
|
||||
if (typeof value !== 'number' || Number.isNaN(value)) return '-'
|
||||
return `${(value * 100).toFixed(2)}%`
|
||||
}
|
||||
|
||||
export function formatAvailability(item: HealthMonitorAvailability) {
|
||||
if (item.total_attempts <= 0) return '-'
|
||||
return formatPercent(item.success_rate)
|
||||
}
|
||||
|
||||
export function formatTps(value?: number | null) {
|
||||
if (typeof value !== 'number' || Number.isNaN(value)) return '-'
|
||||
return `${new Intl.NumberFormat('zh-CN', {
|
||||
maximumFractionDigits: value < 10 ? 2 : value < 100 ? 1 : 0
|
||||
}).format(value)} tps`
|
||||
}
|
||||
|
||||
export function formatFullTimestamp(timestamp?: string | null) {
|
||||
if (!timestamp) return '未知时间'
|
||||
const date = new Date(timestamp)
|
||||
if (Number.isNaN(date.getTime())) return '未知时间'
|
||||
const pad = (value: number) => value.toString().padStart(2, '0')
|
||||
return [
|
||||
`${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`,
|
||||
`${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`
|
||||
].join(' ')
|
||||
}
|
||||
|
||||
export function formatTimelineTooltip(input: {
|
||||
status: string
|
||||
timeRangeStart: string
|
||||
timeRangeEnd: string
|
||||
metrics?: HealthTimelineTooltipMetrics | null
|
||||
entityLabel?: string
|
||||
entityName?: string | null
|
||||
}) {
|
||||
const metrics = input.metrics
|
||||
const lines = [
|
||||
`总请求/成功/失败/可用率/状态:${formatTimelineRequestBreakdown(metrics, input.status)}`,
|
||||
`平均耗时/TTFB/速度:${formatTimelineAverageMetrics(metrics)}`,
|
||||
`时间范围:${formatFullTimestamp(input.timeRangeStart)} - ${formatFullTimestamp(input.timeRangeEnd)}`
|
||||
]
|
||||
if (input.entityLabel && input.entityName) {
|
||||
lines.push(`${input.entityLabel}:${input.entityName}`)
|
||||
}
|
||||
return lines.join('\n')
|
||||
}
|
||||
|
||||
function formatTimelineAverageMetrics(metrics?: HealthTimelineTooltipMetrics | null) {
|
||||
return [
|
||||
formatMs(metrics?.avg_latency_ms),
|
||||
formatMs(metrics?.avg_first_byte_ms),
|
||||
formatTps(metrics?.avg_tps)
|
||||
].join('/')
|
||||
}
|
||||
|
||||
function formatTimelineRequestBreakdown(
|
||||
metrics: HealthTimelineTooltipMetrics | null | undefined,
|
||||
status: string
|
||||
) {
|
||||
if (!metrics) return '-'
|
||||
const total = formatTimelineCount(metrics.total_attempts)
|
||||
const success = formatTimelineCount(metrics.success_count)
|
||||
const failed = formatTimelineCount(metrics.failed_count)
|
||||
const availability = formatTimelineMetricAvailability(metrics)
|
||||
return `${total}/${success}/${failed}/${availability}/${getTimelineLabel(status)}`
|
||||
}
|
||||
|
||||
function formatTimelineCount(value?: number | null) {
|
||||
if (typeof value !== 'number' || Number.isNaN(value)) return '-'
|
||||
return `${new Intl.NumberFormat('zh-CN').format(value)} 次`
|
||||
}
|
||||
|
||||
function formatTimelineMetricAvailability(metrics?: HealthTimelineTooltipMetrics | null) {
|
||||
if (!metrics) return '-'
|
||||
if (typeof metrics.total_attempts === 'number' && metrics.total_attempts <= 0) return '-'
|
||||
if (typeof metrics.success_rate !== 'number' || Number.isNaN(metrics.success_rate)) return '-'
|
||||
return formatPercent(metrics.success_rate)
|
||||
}
|
||||
|
||||
export function formatCompactNumber(value: number) {
|
||||
return new Intl.NumberFormat('zh-CN', {
|
||||
notation: 'compact',
|
||||
maximumFractionDigits: 1
|
||||
}).format(value)
|
||||
}
|
||||
|
||||
export function formatTimestamp(timestamp?: string | null) {
|
||||
if (!timestamp) return '未知时间'
|
||||
const date = new Date(timestamp)
|
||||
if (Number.isNaN(date.getTime())) return '未知时间'
|
||||
return date.toLocaleString('zh-CN', {
|
||||
month: '2-digit',
|
||||
day: '2-digit',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
second: '2-digit'
|
||||
})
|
||||
}
|
||||
|
||||
export function getTimelineColor(status: string) {
|
||||
switch (status) {
|
||||
case 'healthy':
|
||||
return 'bg-green-500/80 dark:bg-green-400/90'
|
||||
case 'warning':
|
||||
return 'bg-amber-400/80 dark:bg-amber-300/80'
|
||||
case 'unhealthy':
|
||||
return 'bg-red-500/80 dark:bg-red-400/90'
|
||||
default:
|
||||
return 'bg-gray-300 dark:bg-gray-600'
|
||||
}
|
||||
}
|
||||
|
||||
export function getTimelineLabel(status: string) {
|
||||
switch (status) {
|
||||
case 'healthy':
|
||||
return '健康'
|
||||
case 'warning':
|
||||
return '波动'
|
||||
case 'unhealthy':
|
||||
return '异常'
|
||||
default:
|
||||
return '无请求'
|
||||
}
|
||||
}
|
||||
@@ -338,7 +338,22 @@
|
||||
</template>
|
||||
</div>
|
||||
|
||||
<!-- 第三行:性能指标 -->
|
||||
<!-- 第三行:用户 + 提供商 -->
|
||||
<div
|
||||
v-if="isAdmin"
|
||||
class="mt-1 flex min-w-0 items-center gap-1.5 text-[10px] leading-3.5 text-muted-foreground"
|
||||
>
|
||||
<span
|
||||
class="min-w-0 truncate"
|
||||
:title="formatRecordUserProviderLine(record)"
|
||||
>
|
||||
{{ formatRecordUserSegment(record) }}
|
||||
</span>
|
||||
<span class="shrink-0 text-muted-foreground/40">·</span>
|
||||
<span class="min-w-0 truncate">{{ formatRecordProviderSegment(record) }}</span>
|
||||
</div>
|
||||
|
||||
<!-- 第四行:性能指标 -->
|
||||
<div class="mt-1.5 flex min-w-0 flex-wrap items-center gap-x-1.5 gap-y-1 text-[10px] leading-3.5 text-muted-foreground">
|
||||
<span
|
||||
class="min-w-0 truncate whitespace-nowrap tabular-nums text-foreground"
|
||||
@@ -1389,6 +1404,22 @@ function formatRecordTime(dateStr: string): string {
|
||||
return `${hours}:${minutes}:${seconds}`
|
||||
}
|
||||
|
||||
function getRecordUserName(record: UsageRecord): string {
|
||||
return record.username || record.user_email || (record.user_id ? `User ${record.user_id}` : '已删除用户')
|
||||
}
|
||||
|
||||
function formatRecordUserProviderLine(record: UsageRecord): string {
|
||||
return `${formatRecordUserSegment(record)} · ${formatRecordProviderSegment(record)}`
|
||||
}
|
||||
|
||||
function formatRecordUserSegment(record: UsageRecord): string {
|
||||
return `${getRecordUserName(record)} / ${record.api_key?.name || '-'}`
|
||||
}
|
||||
|
||||
function formatRecordProviderSegment(record: UsageRecord): string {
|
||||
return `${record.provider || '-'} / ${record.provider_key_name || '-'}`
|
||||
}
|
||||
|
||||
watch(() => props.filterSearch, (value) => {
|
||||
if (value !== localSearch.value) {
|
||||
localSearch.value = value
|
||||
|
||||
Reference in New Issue
Block a user