perf: 并行化 admin 聚合路由并完善前端缓存预取

- gateway: usage detail / provider summary / pool overview / users list 改为 tokio join 并行拉取依赖数据
- usage: interval timeline 支持自动刷新并按查询区间动态展示,取消服务端 120 分钟过滤并在 ScatterChart 统一封顶
- frontend: 新增管理端导航预取工具及 SidebarNav/MainLayout 触发,admin 读接口统一走 cachedRequest 的短期缓存
- dashboard: request detail 支持短 TTL 缓存并在 UsageRecordsTable mousedown 时预取
- data: migrate 测试在 wait_for_postgres 失败时清理子进程,避免遗留
This commit is contained in:
fawney19
2026-04-19 15:17:25 +08:00
parent 97cd877ce5
commit 41b51f10a9
30 changed files with 619 additions and 243 deletions

View File

@@ -1,4 +1,5 @@
import apiClient from './client'
import { buildCacheKey, cachedRequest } from '@/utils/cache'
import type { RefundRequest, WalletSummary, WalletTransaction } from './wallet'
export interface AdminWallet extends WalletSummary {
@@ -100,41 +101,51 @@ export const adminWalletApi = {
async listAllWallets(params?: {
status?: string
owner_type?: 'user' | 'api_key'
}): Promise<AdminWallet[]> {
const items: AdminWallet[] = []
const limit = 200
const maxPages = 200
let offset = 0
let page = 0
}, options: { cacheTtlMs?: number } = {}): Promise<AdminWallet[]> {
const cacheKey = buildCacheKey(
'admin:wallets:list-all',
params as Record<string, unknown> | undefined,
)
return cachedRequest(
cacheKey,
async () => {
const items: AdminWallet[] = []
const limit = 200
const maxPages = 200
let offset = 0
let page = 0
while (page < maxPages) {
const response = await apiClient.get<AdminWalletListResponse>('/api/admin/wallets', {
params: {
...params,
limit,
offset,
},
})
const data = response.data
items.push(...data.items)
while (page < maxPages) {
const response = await apiClient.get<AdminWalletListResponse>('/api/admin/wallets', {
params: {
...params,
limit,
offset,
},
})
const data = response.data
items.push(...data.items)
if (items.length >= data.total || data.items.length < limit) {
break
}
if (items.length >= data.total || data.items.length < limit) {
break
}
const nextOffset = offset + data.items.length
if (nextOffset <= offset) {
throw new Error('分页游标未前进,终止全量钱包拉取以避免死循环')
}
offset = nextOffset
page += 1
}
const nextOffset = offset + data.items.length
if (nextOffset <= offset) {
throw new Error('分页游标未前进,终止全量钱包拉取以避免死循环')
}
offset = nextOffset
page += 1
}
if (page >= maxPages) {
throw new Error(`钱包列表分页超过最大页数 ${maxPages},已中止请求`)
}
if (page >= maxPages) {
throw new Error(`钱包列表分页超过最大页数 ${maxPages},已中止请求`)
}
return items
return items
},
options.cacheTtlMs ?? 0,
)
},
async getWalletDetail(walletId: string): Promise<AdminWalletDetailResponse> {

View File

@@ -583,11 +583,22 @@ export const adminApi = {
},
// 获取特定系统配置
async getSystemConfig(key: string): Promise<{ key: string; value: unknown }> {
const response = await apiClient.get<{ key: string; value: unknown }>(
`/api/admin/system/configs/${key}`
async getSystemConfig(
key: string,
options: { cacheTtlMs?: number } = {},
): Promise<{ key: string; value: unknown }> {
const cacheTtlMs = options.cacheTtlMs ?? 0
const cacheKey = buildCacheKey('admin:system:config', { key })
return cachedRequest(
cacheKey,
async () => {
const response = await apiClient.get<{ key: string; value: unknown }>(
`/api/admin/system/configs/${key}`
)
return response.data
},
cacheTtlMs,
)
return response.data
},
// 更新系统配置

View File

@@ -1,6 +1,8 @@
import apiClient from './client'
import { cachedRequest, buildCacheKey } from '@/utils/cache'
const REQUEST_DETAIL_PREFETCH_TTL_MS = 5_000
export interface DashboardStat {
name: string
value: string
@@ -360,11 +362,30 @@ export const dashboardApi = {
// 获取请求详情
// NOTE: This method now calls the new RESTful API at /api/admin/usage/{id}
async getRequestDetail(requestId: string, options: { includeBodies?: boolean } = {}): Promise<RequestDetail> {
const response = await apiClient.get<RequestDetail>(`/api/admin/usage/${requestId}`, {
params: { include_bodies: options.includeBodies ?? true },
async getRequestDetail(
requestId: string,
options: { includeBodies?: boolean, cacheTtlMs?: number } = {}
): Promise<RequestDetail> {
const includeBodies = options.includeBodies ?? true
const cacheTtlMs = options.cacheTtlMs ?? 0
const cacheKey = buildCacheKey('dashboard:request-detail', { requestId, includeBodies })
return cachedRequest(
cacheKey,
async () => {
const response = await apiClient.get<RequestDetail>(`/api/admin/usage/${requestId}`, {
params: { include_bodies: includeBodies },
})
return response.data
},
cacheTtlMs
)
},
async prefetchRequestDetail(requestId: string): Promise<void> {
await dashboardApi.getRequestDetail(requestId, {
includeBodies: false,
cacheTtlMs: REQUEST_DETAIL_PREFETCH_TTL_MS
})
return response.data
},
// 获取每日统计数据

View File

@@ -1,5 +1,5 @@
import client from '../client'
import { dedupedRequest, buildCacheKey } from '@/utils/cache'
import { buildCacheKey, cachedRequest, dedupedRequest } from '@/utils/cache'
import type {
GlobalModelCreate,
GlobalModelUpdate,
@@ -22,17 +22,26 @@ export type {
/**
* 获取 GlobalModel 列表
*/
interface GlobalModelListOptions {
cacheTtlMs?: number
}
export async function getGlobalModels(params?: {
skip?: number
limit?: number
is_active?: boolean
search?: string
}): Promise<GlobalModelListResponse> {
}, options: GlobalModelListOptions = {}): Promise<GlobalModelListResponse> {
const cacheTtlMs = options.cacheTtlMs ?? 0
const key = buildCacheKey('global-models:list', params as Record<string, unknown> | undefined)
return dedupedRequest(key, async () => {
const response = await client.get('/api/admin/models/global', { params })
return response.data
})
return cachedRequest(
key,
async () => {
const response = await client.get('/api/admin/models/global', { params })
return response.data
},
cacheTtlMs,
)
}
/**

View File

@@ -1,5 +1,5 @@
import client from '../client'
import { dedupedRequest } from '@/utils/cache'
import { buildCacheKey, cachedRequest } from '@/utils/cache'
import type {
AllowedModels,
OAuthOrganizationInfo,
@@ -230,33 +230,59 @@ export interface PoolBatchAction {
payload?: Record<string, unknown> | null
}
export async function getPoolOverview(): Promise<PoolOverviewResponse> {
return dedupedRequest('pool:overview', async () => {
const response = await client.get<PoolOverviewResponse>('/api/admin/pool/overview')
return response.data
})
interface PoolReadOptions {
cacheTtlMs?: number
}
export async function getPoolSchedulingPresets(): Promise<PoolPresetMeta[]> {
return dedupedRequest('pool:scheduling-presets', async () => {
const response = await client.get<PoolPresetMeta[]>('/api/admin/pool/scheduling-presets')
return response.data
})
export async function getPoolOverview(
options: PoolReadOptions = {},
): Promise<PoolOverviewResponse> {
const cacheTtlMs = options.cacheTtlMs ?? 0
return cachedRequest(
'pool:overview',
async () => {
const response = await client.get<PoolOverviewResponse>('/api/admin/pool/overview')
return response.data
},
cacheTtlMs,
)
}
export async function getPoolSchedulingPresets(
options: PoolReadOptions = {},
): Promise<PoolPresetMeta[]> {
const cacheTtlMs = options.cacheTtlMs ?? 0
return cachedRequest(
'pool:scheduling-presets',
async () => {
const response = await client.get<PoolPresetMeta[]>('/api/admin/pool/scheduling-presets')
return response.data
},
cacheTtlMs,
)
}
export async function listPoolKeys(
providerId: string,
params: PoolKeysQuery = {},
options: PoolReadOptions = {},
): Promise<PoolKeysPageResponse> {
const normalizedParams = {
...params,
quick_selectors: params.quick_selectors?.length ? params.quick_selectors.join(',') : undefined,
}
const key = `pool:keys:${providerId}|${normalizedParams.page ?? ''}|${normalizedParams.page_size ?? ''}|${normalizedParams.search ?? ''}|${normalizedParams.status ?? ''}|${normalizedParams.quick_selectors ?? ''}|${normalizedParams.search_scope ?? ''}`
return dedupedRequest(key, async () => {
const response = await client.get<PoolKeysPageResponse>(`/api/admin/pool/${providerId}/keys`, { params: normalizedParams })
return response.data
})
const cacheKey = buildCacheKey(
`pool:keys:${providerId}`,
normalizedParams as Record<string, unknown>,
)
return cachedRequest(
cacheKey,
async () => {
const response = await client.get<PoolKeysPageResponse>(`/api/admin/pool/${providerId}/keys`, { params: normalizedParams })
return response.data
},
options.cacheTtlMs ?? 0,
)
}
export async function resolvePoolKeySelection(

View File

@@ -1,5 +1,5 @@
import client from '../client'
import { dedupedRequest } from '@/utils/cache'
import { buildCacheKey, cachedRequest, dedupedRequest } from '@/utils/cache'
import type {
ClaudeCodeAdvancedConfig,
FailoverRulesConfig,
@@ -13,6 +13,11 @@ interface ProviderRequestOptions {
timeout?: number
}
interface ProviderReadOptions {
timeout?: number
cacheTtlMs?: number
}
/**
* 获取 Providers 摘要(分页)
*/
@@ -43,15 +48,27 @@ function normalizeProviderSummary(
export async function getProvidersSummary(
params: ProviderSummaryQuery = {},
options: ProviderReadOptions = {},
): Promise<ProviderSummaryPageResponse> {
const response = await client.get<ProviderSummaryPageResponse>(
'/api/admin/providers/summary',
{ params },
const cacheTtlMs = options.cacheTtlMs ?? 0
const cacheKey = buildCacheKey('providers:summary', params as Record<string, unknown>)
return cachedRequest(
cacheKey,
async () => {
const response = await client.get<ProviderSummaryPageResponse>(
'/api/admin/providers/summary',
{
params,
timeout: options.timeout,
},
)
return {
...response.data,
items: response.data.items.map(normalizeProviderSummary),
}
},
cacheTtlMs,
)
return {
...response.data,
items: response.data.items.map(normalizeProviderSummary),
}
}
/**

View File

@@ -5,6 +5,8 @@ import { cachedRequest, buildCacheKey } from '@/utils/cache'
import type { BillingSummary } from './auth'
import type { UserSession } from '@/types/session'
const ACTIVITY_HEATMAP_CACHE_TTL_MS = 30 * 60 * 1000
export type { UserSession }
export interface Profile {
@@ -414,7 +416,7 @@ export const meApi = {
/**
* 获取活跃度热力图数据(用户)
* 后端已缓存5分钟
* 历史热力图变化很慢,前端做长缓存,避免短时间重复请求。
*/
async getActivityHeatmap(): Promise<ActivityHeatmap> {
return cachedRequest(
@@ -423,7 +425,7 @@ export const meApi = {
const response = await apiClient.get<ActivityHeatmap>('/api/users/me/usage/heatmap')
return response.data
},
60000
ACTIVITY_HEATMAP_CACHE_TTL_MS
)
}
}

View File

@@ -2,6 +2,8 @@ import apiClient from './client'
import { cachedRequest, dedupedRequest, buildCacheKey } from '@/utils/cache'
import type { ActivityHeatmap } from '@/types/activity'
const ACTIVITY_HEATMAP_CACHE_TTL_MS = 30 * 60 * 1000
export interface UsageRecord {
id: string // UUID
user_id: string // UUID
@@ -340,7 +342,7 @@ export const usageApi = {
/**
* 获取活跃度热力图数据(管理员)
* 后端已缓存5分钟
* 历史热力图变化很慢,前端做长缓存,避免自动刷新链路重复请求。
*/
async getActivityHeatmap(): Promise<ActivityHeatmap> {
return cachedRequest(
@@ -349,7 +351,7 @@ export const usageApi = {
const response = await apiClient.get<ActivityHeatmap | unknown[]>('/api/admin/usage/heatmap')
return normalizeActivityHeatmapResponse(response.data)
},
60000
ACTIVITY_HEATMAP_CACHE_TTL_MS
)
}
}

View File

@@ -1,4 +1,5 @@
import apiClient from './client'
import { cachedRequest } from '@/utils/cache'
import type { UserSession as SessionRecord } from '@/types/session'
export interface User {
@@ -70,9 +71,16 @@ export interface UpsertUserApiKeyRequest {
export type UserSession = SessionRecord
export const usersApi = {
async getAllUsers(): Promise<User[]> {
const response = await apiClient.get<User[]>('/api/admin/users')
return response.data
async getAllUsers(options: { cacheTtlMs?: number } = {}): Promise<User[]> {
const cacheTtlMs = options.cacheTtlMs ?? 0
return cachedRequest(
'admin:users:list',
async () => {
const response = await apiClient.get<User[]>('/api/admin/users')
return response.data
},
cacheTtlMs,
)
},
async getUser(userId: string): Promise<User> {

View File

@@ -290,10 +290,10 @@ function transformData(data: ChartData<'scatter'>): ChartData<'scatter'> {
...data,
datasets: data.datasets.map(dataset => ({
...dataset,
data: (dataset.data as Array<{ x: string; y: number; _originalX?: string }>).map(point => ({
data: (dataset.data as Array<{ x: string; y: number; _originalX?: string; _originalY?: number }>).map(point => ({
...point,
y: toDisplayValue(point.y),
_originalY: point.y // 保存原始值用于 tooltip
y: toDisplayValue(Math.min(point.y, 120)),
_originalY: point._originalY ?? point.y // 保存原始值用于 tooltip
}))
}))
}

View File

@@ -29,6 +29,9 @@
? 'bg-primary/10 text-primary font-medium'
: 'text-muted-foreground hover:text-foreground hover:bg-muted/50'
]"
@mouseenter="emit('prefetch', item.href)"
@focus="emit('prefetch', item.href)"
@pointerdown="emit('prefetch', item.href)"
@click="handleNavigate(item.href)"
>
<div class="flex items-center gap-2.5">
@@ -76,6 +79,7 @@ const props = defineProps<{
const emit = defineEmits<{
(e: 'navigate', href: string): void
(e: 'prefetch', href: string): void
}>()
function isItemActive(href: string) {

View File

@@ -66,14 +66,18 @@ const props = withDefaults(defineProps<{
title: string
isAdmin: boolean
hours?: number
refreshIntervalMs?: number
}>(), {
hours: 24 // 默认当天
hours: 24, // 默认当天
refreshIntervalMs: 30000
})
const loading = ref(false)
const timelineData = ref<IntervalTimelineResponse | null>(null)
const primaryColor = ref('201, 100, 66') // 默认主题色
let loadRequestId = 0
let refreshTimer: ReturnType<typeof setTimeout> | null = null
const isPageVisible = ref(typeof document === 'undefined' ? true : !document.hidden)
const ADMIN_TIMELINE_LIMIT = 1500
const USER_TIMELINE_LIMIT = 1200
@@ -90,7 +94,11 @@ function getPrimaryColor(): string {
onMounted(() => {
primaryColor.value = getPrimaryColor()
if (typeof document !== 'undefined') {
document.addEventListener('visibilitychange', handleVisibilityChange)
}
void loadData()
scheduleNextRefresh()
})
// 预定义的颜色列表(用于区分不同用户/模型)
@@ -315,11 +323,45 @@ async function loadData() {
}
}
function stopRefreshTimer() {
if (refreshTimer) {
clearTimeout(refreshTimer)
refreshTimer = null
}
}
function scheduleNextRefresh() {
if (refreshTimer) return
if (!isPageVisible.value) return
if (!props.refreshIntervalMs || props.refreshIntervalMs <= 0) return
refreshTimer = setTimeout(async () => {
refreshTimer = null
await loadData()
scheduleNextRefresh()
}, props.refreshIntervalMs)
}
function handleVisibilityChange() {
isPageVisible.value = !document.hidden
if (!isPageVisible.value) {
stopRefreshTimer()
return
}
void loadData()
scheduleNextRefresh()
}
watch([() => props.hours, () => props.isAdmin], () => {
void loadData()
stopRefreshTimer()
scheduleNextRefresh()
})
onBeforeUnmount(() => {
loadRequestId++
if (typeof document !== 'undefined') {
document.removeEventListener('visibilitychange', handleVisibilityChange)
}
stopRefreshTimer()
})
</script>

View File

@@ -1664,7 +1664,10 @@ async function loadDetail(id: string, silent = false) {
}
error.value = null
try {
const response = await dashboardApi.getRequestDetail(id, { includeBodies: false })
const response = await dashboardApi.getRequestDetail(id, {
includeBodies: false,
cacheTtlMs: silent ? 0 : 5_000
})
if (requestId !== loadDetailRequestId) return
const previousDetail = detail.value

View File

@@ -341,7 +341,7 @@
v-else
:key="record.id"
:class="isAdmin ? 'cursor-pointer border-b border-border/40 hover:bg-muted/30 transition-colors h-[72px]' : 'border-b border-border/40 hover:bg-muted/30 transition-colors h-[72px]'"
@mousedown="handleMouseDown"
@mousedown="handleRowMouseDown($event, record.id)"
@click="handleRowClick($event, record.id)"
>
<TableCell class="text-xs py-4 w-[70px]">
@@ -730,6 +730,7 @@ const emit = defineEmits<{
'update:autoRefresh': [value: boolean]
'refresh': []
'showDetail': [id: string]
'prefetchDetail': [id: string]
}>()
// 静态常量(放在 defineProps/defineEmits 之后)
@@ -776,6 +777,13 @@ watch(localSearch, (value) => {
// 使用复用的行点击逻辑
const { handleMouseDown, shouldTriggerRowClick } = useRowClick()
function handleRowMouseDown(event: MouseEvent, id: string) {
handleMouseDown(event)
if (!props.isAdmin) return
if (event.button !== 0) return
emit('prefetchDetail', id)
}
// 处理行点击,排除文本选择操作
function handleRowClick(event: MouseEvent, id: string) {
if (!props.isAdmin) return

View File

@@ -53,6 +53,7 @@
<SidebarNav
:items="navigation"
:is-active="isNavActive"
@prefetch="prefetchNavigationItem"
/>
</div>
@@ -195,6 +196,9 @@
:class="isNavActive(item.href)
? 'bg-[#cc785c]/10 dark:bg-[#cc785c]/20 text-[#cc785c] dark:text-[#d4a27f]'
: 'text-[#666663] dark:text-muted-foreground hover:bg-black/5 dark:hover:bg-white/5 hover:text-[#191919] dark:hover:text-white'"
@mouseenter="prefetchNavigationItem(item.href)"
@focus="prefetchNavigationItem(item.href)"
@pointerdown="prefetchNavigationItem(item.href)"
@click="mobileMenuOpen = false"
>
<component
@@ -382,6 +386,7 @@ import {
import GithubIcon from '@/components/icons/GithubIcon.vue'
import { BUILTIN_TOOL_BREADCRUMBS } from '@/config/builtin-tools'
import { prefetchAdminNavigationTarget } from '@/utils/adminNavigationPrefetch'
const router = useRouter()
const route = useRoute()
@@ -508,6 +513,10 @@ function isNavActive(href: string) {
return route.path === href || route.path.startsWith(`${href}/`)
}
function prefetchNavigationItem(href: string) {
prefetchAdminNavigationTarget(href)
}
// Navigation Data
const navigation = computed(() => {
const baseNavigation = [

View File

@@ -16,12 +16,12 @@ export const useUsersStore = defineStore('users', () => {
const loading = ref(false)
const error = ref<string | null>(null)
async function fetchUsers() {
async function fetchUsers(options: { cacheTtlMs?: number } = {}) {
loading.value = true
error.value = null
try {
users.value = await usersApi.getAllUsers()
users.value = await usersApi.getAllUsers(options)
} catch (err: unknown) {
error.value = parseApiError(err, '获取用户列表失败')
} finally {

View File

@@ -0,0 +1,90 @@
import { adminWalletApi } from '@/api/admin-wallets'
import { adminApi } from '@/api/admin'
import { getProvidersSummary } from '@/api/endpoints/providers'
import { getPoolOverview, getPoolSchedulingPresets, listPoolKeys } from '@/api/endpoints/pool'
import { listGlobalModels } from '@/api/global-models'
import { usersApi } from '@/api/users'
import { log } from '@/utils/logger'
const NAV_DATA_CACHE_TTL_MS = 10 * 1000
const NAV_SYSTEM_CONFIG_CACHE_TTL_MS = 30 * 1000
const NAV_POOL_PRESETS_CACHE_TTL_MS = 5 * 60 * 1000
const PREFETCH_COOLDOWN_MS = 5 * 1000
const lastPrefetchAt = new Map<string, number>()
const adminRouteWarmers: Record<string, () => Promise<void>> = {
'/admin/users': async () => {
await Promise.allSettled([
import('@/views/admin/Users.vue'),
usersApi.getAllUsers({ cacheTtlMs: NAV_DATA_CACHE_TTL_MS }),
adminWalletApi.listAllWallets(
{ owner_type: 'user' },
{ cacheTtlMs: NAV_DATA_CACHE_TTL_MS },
),
])
},
'/admin/providers': async () => {
await Promise.allSettled([
import('@/views/admin/ProviderManagement.vue'),
getProvidersSummary(
{ page: 1, page_size: 20 },
{ cacheTtlMs: NAV_DATA_CACHE_TTL_MS },
),
adminApi.getSystemConfig('provider_priority_mode', {
cacheTtlMs: NAV_SYSTEM_CONFIG_CACHE_TTL_MS,
}),
listGlobalModels(
{ is_active: true, limit: 1000 },
{ cacheTtlMs: NAV_DATA_CACHE_TTL_MS },
),
])
},
'/admin/models': async () => {
await Promise.allSettled([
import('@/views/admin/ModelManagement.vue'),
listGlobalModels(
{ skip: 0, limit: 20 },
{ cacheTtlMs: NAV_DATA_CACHE_TTL_MS },
),
])
},
'/admin/pool': async () => {
const [overviewResult] = await Promise.allSettled([
getPoolOverview({ cacheTtlMs: NAV_DATA_CACHE_TTL_MS }),
getPoolSchedulingPresets({ cacheTtlMs: NAV_POOL_PRESETS_CACHE_TTL_MS }),
import('@/views/admin/PoolManagement.vue'),
])
if (overviewResult.status !== 'fulfilled') {
return
}
const firstProviderId = overviewResult.value.items.find(item => item.pool_enabled)?.provider_id
if (!firstProviderId) {
return
}
await listPoolKeys(
firstProviderId,
{ page: 1, page_size: 50, status: 'all' },
{ cacheTtlMs: NAV_DATA_CACHE_TTL_MS },
)
},
}
export function prefetchAdminNavigationTarget(href: string): void {
const warmer = adminRouteWarmers[href]
if (!warmer) return
const now = Date.now()
const lastRun = lastPrefetchAt.get(href) ?? 0
if (now - lastRun < PREFETCH_COOLDOWN_MS) {
return
}
lastPrefetchAt.set(href, now)
void warmer().catch((err) => {
log.debug('[adminNavigationPrefetch] ignore prefetch failure', err)
})
}

View File

@@ -717,6 +717,7 @@ let modelSelectionRequestId = 0
let modelProvidersRequestId = 0
let batchManageModelsRequestId = 0
let providerOptionsRequest: Promise<void> | null = null
const GLOBAL_MODELS_LIST_CACHE_TTL_MS = 10 * 1000
// 模型目录分页
const catalogCurrentPage = ref(1)
@@ -1036,11 +1037,13 @@ const globalModelsQueryParams = computed(() => ({
let modelSearchDebounceTimer: ReturnType<typeof setTimeout> | null = null
async function loadGlobalModels() {
async function loadGlobalModels(options: { cacheTtlMs?: number } = {}) {
const requestId = ++globalModelsRequestId
loading.value = true
try {
const response = await listGlobalModels(globalModelsQueryParams.value)
const response = await listGlobalModels(globalModelsQueryParams.value, {
cacheTtlMs: options.cacheTtlMs ?? 0,
})
if (requestId !== globalModelsRequestId) return
const pageModels = response.models || []
@@ -1533,9 +1536,11 @@ watch(globalModelsQueryParams, (newParams, oldParams) => {
&& newParams.skip === oldParams?.skip
&& newParams.limit === oldParams?.limit
if (isSearchOnly) {
modelSearchDebounceTimer = setTimeout(loadGlobalModels, 300)
modelSearchDebounceTimer = setTimeout(() => {
void loadGlobalModels({ cacheTtlMs: GLOBAL_MODELS_LIST_CACHE_TTL_MS })
}, 300)
} else {
loadGlobalModels()
void loadGlobalModels({ cacheTtlMs: GLOBAL_MODELS_LIST_CACHE_TTL_MS })
}
}, { immediate: true })

View File

@@ -1258,12 +1258,15 @@ let keysRequestId = 0
let keysSearchDebounceTimer: number | null = null
let suppressFiltersWatch = false
let hasHydratedInitialProviderSelection = false
const POOL_OVERVIEW_CACHE_TTL_MS = 10 * 1000
const POOL_KEYS_CACHE_TTL_MS = 10 * 1000
const POOL_SCHEDULING_PRESETS_CACHE_TTL_MS = 5 * 60 * 1000
async function loadOverview() {
async function loadOverview(options: { cacheTtlMs?: number } = {}) {
const requestId = ++overviewRequestId
overviewLoading.value = true
try {
const res = await getPoolOverview()
const res = await getPoolOverview({ cacheTtlMs: options.cacheTtlMs ?? 0 })
if (requestId !== overviewRequestId) return
const allProviders = Array.isArray(res.items) ? res.items : []
const enabledProviders = allProviders.filter(item => item.pool_enabled)
@@ -1283,6 +1286,7 @@ async function loadOverview() {
preserveSearch: true,
preserveStatus: true,
preservePagination: true,
cacheTtlMs: options.cacheTtlMs ? POOL_KEYS_CACHE_TTL_MS : 0,
})
}
return
@@ -1296,6 +1300,7 @@ async function loadOverview() {
preserveSearch: shouldPreserveViewState,
preserveStatus: shouldPreserveViewState,
preservePagination: shouldPreserveViewState,
cacheTtlMs: options.cacheTtlMs ? POOL_KEYS_CACHE_TTL_MS : 0,
})
} else {
selectedProviderId.value = null
@@ -1333,7 +1338,7 @@ const selectedProviderIdProxy = computed({
get: () => selectedProviderId.value ?? '',
set: (val: string) => {
if (val && val !== selectedProviderId.value) {
selectProvider(val)
void selectProvider(val, { cacheTtlMs: POOL_KEYS_CACHE_TTL_MS })
}
},
})
@@ -1363,9 +1368,9 @@ function normalizePresetName(value: unknown): string {
return String(value ?? '').trim().toLowerCase()
}
async function loadSchedulingPresetMetas(): Promise<void> {
async function loadSchedulingPresetMetas(options: { cacheTtlMs?: number } = {}): Promise<void> {
try {
const metas = await getPoolSchedulingPresets()
const metas = await getPoolSchedulingPresets({ cacheTtlMs: options.cacheTtlMs ?? 0 })
const next: Record<string, string> = {}
for (const meta of metas as PoolPresetMeta[]) {
const name = normalizePresetName(meta.name)
@@ -1492,6 +1497,7 @@ async function selectProvider(
preserveSearch?: boolean
preserveStatus?: boolean
preservePagination?: boolean
cacheTtlMs?: number
} = {},
) {
const requestId = ++selectProviderRequestId
@@ -1522,7 +1528,7 @@ async function selectProvider(
keysSearchDebounceTimer = null
}
resetKeyPage(currentPage.value, pageSize.value)
const keysTask = loadKeys()
const keysTask = loadKeys({ cacheTtlMs: options.cacheTtlMs ?? 0 })
// Provider summary is non-blocking for key list rendering.
void loadProviderData(id)
await keysTask
@@ -1620,6 +1626,7 @@ watch(
preserveSearch: true,
preserveStatus: true,
preservePagination: true,
cacheTtlMs: POOL_KEYS_CACHE_TTL_MS,
})
},
{ immediate: true },
@@ -1790,7 +1797,7 @@ async function refreshCurrentPage() {
}
}
async function loadKeys() {
async function loadKeys(options: { cacheTtlMs?: number } = {}) {
if (!selectedProviderId.value) return
const requestId = ++keysRequestId
const providerId = selectedProviderId.value
@@ -1805,6 +1812,8 @@ async function loadKeys() {
page_size: pageSizeValue,
search,
status,
}, {
cacheTtlMs: options.cacheTtlMs ?? 0,
})
if (requestId !== keysRequestId || selectedProviderId.value !== providerId) return
const resolvedPage = resolvePoolManagementPageAfterLoad({
@@ -1829,13 +1838,13 @@ async function loadKeys() {
}
watch([currentPage, pageSize], () => {
void loadKeys()
void loadKeys({ cacheTtlMs: POOL_KEYS_CACHE_TTL_MS })
})
watch(statusFilter, () => {
if (suppressFiltersWatch) return
currentPage.value = 1
void loadKeys()
void loadKeys({ cacheTtlMs: POOL_KEYS_CACHE_TTL_MS })
})
watch(searchQuery, () => {
@@ -1846,7 +1855,7 @@ watch(searchQuery, () => {
}
keysSearchDebounceTimer = window.setTimeout(() => {
keysSearchDebounceTimer = null
void loadKeys()
void loadKeys({ cacheTtlMs: POOL_KEYS_CACHE_TTL_MS })
}, 300)
})
@@ -3035,8 +3044,8 @@ function formatRelativeTime(isoStr: string): string {
// --- Init ---
onMounted(() => {
startCountdownTimer()
void loadSchedulingPresetMetas()
void loadOverview()
void loadSchedulingPresetMetas({ cacheTtlMs: POOL_SCHEDULING_PRESETS_CACHE_TTL_MS })
void loadOverview({ cacheTtlMs: POOL_OVERVIEW_CACHE_TTL_MS })
})
onBeforeUnmount(() => {

View File

@@ -324,6 +324,9 @@ let deletePollAbort: AbortController | null = null
const DELETE_POLL_INTERVAL_MS = 2000
const DELETE_POLL_MAX_MS = 30 * 60 * 1000
const DELETE_POLL_MAX_FAILURES = 3
const PROVIDER_SUMMARY_CACHE_TTL_MS = 10 * 1000
const PROVIDER_PRIORITY_MODE_CACHE_TTL_MS = 30 * 1000
const PROVIDER_MODEL_FILTER_CACHE_TTL_MS = 10 * 1000
async function pollProviderDeleteTask(providerId: string, taskId: string) {
deletePollAbort?.abort()
@@ -533,9 +536,11 @@ const maxProviderPriority = computed(() => {
})
// 加载优先级模式
async function loadPriorityMode() {
async function loadPriorityMode(options: { cacheTtlMs?: number } = {}) {
try {
const response = await adminApi.getSystemConfig('provider_priority_mode')
const response = await adminApi.getSystemConfig('provider_priority_mode', {
cacheTtlMs: options.cacheTtlMs ?? 0,
})
if (response.value) {
priorityMode.value = response.value as 'provider' | 'global_key'
}
@@ -545,9 +550,12 @@ async function loadPriorityMode() {
}
// 加载全局模型列表(用于模型筛选下拉)
async function loadGlobalModelList() {
async function loadGlobalModelList(options: { cacheTtlMs?: number } = {}) {
try {
const response = await getGlobalModels({ is_active: true, limit: 1000 })
const response = await getGlobalModels(
{ is_active: true, limit: 1000 },
{ cacheTtlMs: options.cacheTtlMs ?? 0 },
)
globalModels.value = response.models.map(m => ({ id: m.id, name: m.name }))
} catch {
globalModels.value = []
@@ -555,11 +563,13 @@ async function loadGlobalModelList() {
}
// 加载提供商列表(服务端分页)
async function loadProviders() {
async function loadProviders(options: { cacheTtlMs?: number } = {}) {
const requestId = ++providersRequestId
loading.value = true
try {
const response = await getProvidersSummary(queryParams.value)
const response = await getProvidersSummary(queryParams.value, {
cacheTtlMs: options.cacheTtlMs ?? 0,
})
if (requestId !== providersRequestId) return
providers.value = response.items
total.value = response.total
@@ -587,9 +597,11 @@ watch(queryParams, (newParams, oldParams) => {
newParams.api_format === oldParams?.api_format &&
newParams.model_id === oldParams?.model_id
if (isSearchOnly) {
debounceTimer = setTimeout(loadProviders, 300)
debounceTimer = setTimeout(() => {
void loadProviders({ cacheTtlMs: PROVIDER_SUMMARY_CACHE_TTL_MS })
}, 300)
} else {
loadProviders()
void loadProviders({ cacheTtlMs: PROVIDER_SUMMARY_CACHE_TTL_MS })
}
}, { deep: true })
@@ -658,7 +670,7 @@ function openOpsConfigDialog(provider: ProviderWithEndpointsSummary) {
// 扩展操作配置保存回调
function handleOpsConfigSaved() {
opsConfigDialogOpen.value = false
loadProviders()
void loadProviders()
}
// 处理提供商编辑完成
@@ -680,7 +692,7 @@ async function handlePrioritySaved() {
// 处理提供商添加
function handleProviderAdded() {
loadProviders()
void loadProviders()
}
// 删除提供商
@@ -716,7 +728,7 @@ async function handleDeleteProvider(provider: ProviderWithEndpointsSummary) {
showSuccess('提供商已删除')
providerDeleteProgress.value = null
loadProviders()
void loadProviders()
} catch (err: unknown) {
providerDeleteProgress.value = null
showError(parseApiError(err, '删除提供商失败'), '错误')
@@ -753,10 +765,10 @@ function handleGlobalClick(event: MouseEvent) {
}
onMounted(() => {
loadProviders()
loadPriorityMode()
loadGlobalModelList()
loadArchitectureSchemas()
void loadProviders({ cacheTtlMs: PROVIDER_SUMMARY_CACHE_TTL_MS })
void loadPriorityMode({ cacheTtlMs: PROVIDER_PRIORITY_MODE_CACHE_TTL_MS })
void loadGlobalModelList({ cacheTtlMs: PROVIDER_MODEL_FILTER_CACHE_TTL_MS })
void loadArchitectureSchemas()
document.addEventListener('click', handleGlobalClick, true)
// 每秒更新一次倒计时
startTick()

View File

@@ -1128,6 +1128,9 @@ const filterStatus = ref('all')
const currentPage = ref(1)
const pageSize = ref(20)
const USERS_PAGE_CACHE_TTL_MS = 10 * 1000
const USER_WALLETS_CACHE_TTL_MS = 10 * 1000
let userWalletsRequestId = 0
const filteredUsers = computed(() => {
let filtered = [...usersStore.users]
@@ -1173,31 +1176,38 @@ watch([searchQuery, filterRole, filterStatus], () => {
currentPage.value = 1
})
onMounted(async () => {
await refreshUsers()
onMounted(() => {
void refreshUsers({ preferCache: true })
})
async function refreshUsers() {
await Promise.all([
usersStore.fetchUsers(),
loadUserWallets()
])
async function refreshUsers(options: { preferCache?: boolean } = {}) {
const cacheTtlMs = options.preferCache ? USERS_PAGE_CACHE_TTL_MS : 0
await usersStore.fetchUsers({ cacheTtlMs })
void loadUserWallets({
cacheTtlMs: options.preferCache ? USER_WALLETS_CACHE_TTL_MS : 0,
})
}
function formatDate(dateString: string) {
return new Date(dateString).toLocaleDateString('zh-CN')
}
async function loadUserWallets() {
async function loadUserWallets(options: { cacheTtlMs?: number } = {}) {
const requestId = ++userWalletsRequestId
try {
const wallets = await adminWalletApi.listAllWallets()
const wallets = await adminWalletApi.listAllWallets(
{ owner_type: 'user' },
{ cacheTtlMs: options.cacheTtlMs ?? 0 },
)
if (requestId !== userWalletsRequestId) return
userWalletMap.value = wallets
.filter((wallet) => wallet.owner_type === 'user' && !!wallet.user_id)
.filter((wallet) => !!wallet.user_id)
.reduce<Record<string, AdminWallet>>((acc, wallet) => {
acc[wallet.user_id as string] = wallet
return acc
}, {})
} catch (err) {
if (requestId !== userWalletsRequestId) return
log.error('加载用户钱包失败:', err)
}
}

View File

@@ -35,9 +35,10 @@
:has-error="heatmapError"
/>
<IntervalTimelineCard
:title="isAdminPage ? '请求间隔时间线' : '我的请求间隔'"
:title="intervalTimelineTitle"
:is-admin="isAdminPage"
:hours="24"
:hours="intervalTimelineHours"
:refresh-interval-ms="30000"
/>
</div>
@@ -108,6 +109,7 @@
@update:page-size="handlePageSizeChange"
@update:auto-refresh="handleAutoRefreshChange"
@refresh="refreshData"
@prefetch-detail="prefetchRequestDetail"
@show-detail="showRequestDetail"
/>
@@ -129,6 +131,7 @@ import { useAuthStore } from '@/stores/auth'
import { usageApi } from '@/api/usage'
import { usersApi } from '@/api/users'
import { meApi } from '@/api/me'
import { dashboardApi } from '@/api/dashboard'
import { PanelTopClose, PanelTopOpen } from 'lucide-vue-next'
import {
UsageModelTable,
@@ -171,6 +174,44 @@ const currentPage = ref(1)
const pageSize = ref(20)
const pageSizeOptions = [10, 20, 50, 100]
function clampIntervalTimelineHours(hours: number): number {
return Math.min(720, Math.max(1, Math.ceil(hours)))
}
function getIntervalTimelineHours(dateRange: DateRangeParams): number {
switch (dateRange.preset) {
case 'yesterday':
return 48
case 'last7days':
return 24 * 7
case 'last30days':
return 24 * 30
case 'last90days':
return 24 * 30
case 'today':
return 24
default:
break
}
if (dateRange.start_date && dateRange.end_date) {
const start = new Date(`${dateRange.start_date}T00:00:00`)
const end = new Date(`${dateRange.end_date}T23:59:59`)
const diffMs = end.getTime() - start.getTime()
if (!Number.isNaN(diffMs) && diffMs >= 0) {
return clampIntervalTimelineHours(diffMs / (1000 * 60 * 60))
}
}
return 24
}
function formatIntervalTimelineWindow(hours: number): string {
if (hours === 24) return '最近24小时'
if (hours % 24 === 0) return `最近${hours / 24}`
return `最近${hours}小时`
}
// 筛选状态
const filterSearch = ref('')
const filterUser = ref('__all__')
@@ -200,6 +241,11 @@ const {
const activityHeatmapData = ref<ActivityHeatmap | null>(null)
const isLoadingHeatmap = ref(false)
const heatmapError = ref(false)
const intervalTimelineHours = computed(() => getIntervalTimelineHours(timeRange.value))
const intervalTimelineTitle = computed(() => {
const baseTitle = isAdminPage.value ? '请求间隔时间线' : '我的请求间隔'
return `${baseTitle}${formatIntervalTimelineWindow(intervalTimelineHours.value)}`
})
const ADMIN_ANALYTICS_REFRESH_INTERVAL = 60000
let adminAnalyticsRefreshInFlight: Promise<void> | null = null
let lastAdminAnalyticsRefreshAt = 0
@@ -254,13 +300,6 @@ async function refreshAdminAnalytics(options: { force?: boolean } = {}) {
warning('统计数据加载失败,请刷新重试')
}
try {
await loadHeatmapData()
hasSuccessfulRefresh = true
} catch (error) {
log.error('加载热力图数据失败:', error)
}
if (hasSuccessfulRefresh) {
lastAdminAnalyticsRefreshAt = Date.now()
}
@@ -632,6 +671,7 @@ onMounted(async () => {
)
void (async () => {
await refreshAdminAnalytics({ force: true })
await loadHeatmapData()
await loadAdminUsers()
})()
} else {
@@ -769,6 +809,7 @@ async function refreshData() {
getCurrentFilters(),
timeRange.value
)
// 热力图反映长期活跃分布,不跟随自动刷新链路一起重载。
void refreshAdminAnalytics()
return
}
@@ -791,6 +832,13 @@ function showRequestDetail(id: string) {
detailModalOpen.value = true
}
function prefetchRequestDetail(id: string) {
if (!isAdminPage.value) return
void dashboardApi.prefetchRequestDetail(id).catch(error => {
log.debug('预取请求详情失败', error)
})
}
</script>
<style scoped>