427 lines
18 KiB
TypeScript
427 lines
18 KiB
TypeScript
'use client'
|
||
|
||
import { useCallback, useEffect, useMemo, useState } from 'react'
|
||
|
||
type DatePreset = 'today' | 'last7' | 'last30' | 'custom'
|
||
|
||
interface PublicTrafficStats {
|
||
generatedAt: string
|
||
available: boolean
|
||
range: {
|
||
start: string
|
||
end: string
|
||
}
|
||
summary: {
|
||
responseBytes: number
|
||
requestBytes: number | null
|
||
requestBytesKnownCount: number
|
||
totalRequests: number
|
||
uniqueIpCount: number
|
||
statusCounts: Record<string, number>
|
||
firstSeen: string | null
|
||
lastSeen: string | null
|
||
}
|
||
byDay: Array<{
|
||
date: string
|
||
responseBytes: number
|
||
requestBytes: number | null
|
||
requestBytesKnownCount: number
|
||
totalRequests: number
|
||
}>
|
||
byDomain: Array<{
|
||
domain: string
|
||
responseBytes: number
|
||
requestBytes: number | null
|
||
requestBytesKnownCount: number
|
||
totalRequests: number
|
||
statusCounts: Record<string, number>
|
||
}>
|
||
byPurpose: Array<{
|
||
key: string
|
||
label: string
|
||
category: string
|
||
detail: string
|
||
responseBytes: number
|
||
requestBytes: number | null
|
||
requestBytesKnownCount: number
|
||
totalRequests: number
|
||
}>
|
||
topPaths: Array<{
|
||
path: string
|
||
method: string
|
||
purposeLabel: string
|
||
purposeCategory: string
|
||
purposeDetail: string
|
||
responseBytes: number
|
||
totalRequests: number
|
||
}>
|
||
source: {
|
||
logPaths: string[]
|
||
scannedFiles: number
|
||
scannedLines: number
|
||
matchedLines: number
|
||
skippedLines: number
|
||
truncated: boolean
|
||
issues: Array<{
|
||
path: string
|
||
reason: string
|
||
}>
|
||
requestBytesAvailable: boolean
|
||
}
|
||
}
|
||
|
||
interface PublicTrafficTabProps {
|
||
showToast: (message: string, type?: 'success' | 'error') => void
|
||
}
|
||
|
||
function toDateInputValue(date: Date) {
|
||
const year = date.getFullYear()
|
||
const month = String(date.getMonth() + 1).padStart(2, '0')
|
||
const day = String(date.getDate()).padStart(2, '0')
|
||
return `${year}-${month}-${day}`
|
||
}
|
||
|
||
function presetRange(preset: Exclude<DatePreset, 'custom'>) {
|
||
const now = new Date()
|
||
const end = toDateInputValue(now)
|
||
const startDate = new Date(now)
|
||
|
||
if (preset === 'today') {
|
||
return { start: end, end }
|
||
}
|
||
|
||
startDate.setDate(now.getDate() - (preset === 'last7' ? 6 : 29))
|
||
return { start: toDateInputValue(startDate), end }
|
||
}
|
||
|
||
function formatBytes(bytes: number | null | undefined) {
|
||
if (bytes === null || bytes === undefined) return '未统计'
|
||
if (bytes < 1024) return `${bytes.toFixed(0)} B`
|
||
if (bytes < 1024 ** 2) return `${(bytes / 1024).toFixed(2)} KB`
|
||
if (bytes < 1024 ** 3) return `${(bytes / 1024 ** 2).toFixed(2)} MB`
|
||
if (bytes < 1024 ** 4) return `${(bytes / 1024 ** 3).toFixed(2)} GB`
|
||
return `${(bytes / 1024 ** 4).toFixed(2)} TB`
|
||
}
|
||
|
||
function formatNumber(value: number) {
|
||
return new Intl.NumberFormat('zh-CN').format(value)
|
||
}
|
||
|
||
function formatTime(value: string | null) {
|
||
if (!value) return '无'
|
||
return new Date(value).toLocaleString('zh-CN', { hour12: false })
|
||
}
|
||
|
||
const PRESET_OPTIONS: Array<{ key: Exclude<DatePreset, 'custom'>; label: string }> = [
|
||
{ key: 'today', label: '今天' },
|
||
{ key: 'last7', label: '近7天' },
|
||
{ key: 'last30', label: '近30天' },
|
||
]
|
||
|
||
function StatCard({
|
||
label,
|
||
value,
|
||
subText,
|
||
}: {
|
||
label: string
|
||
value: string
|
||
subText?: string
|
||
}) {
|
||
return (
|
||
<div className="rounded-xl border border-gray-200 bg-white p-5 shadow-sm dark:border-gray-700 dark:bg-gray-800">
|
||
<div className="text-sm text-gray-500 dark:text-gray-400">{label}</div>
|
||
<div className="mt-2 text-2xl font-semibold text-gray-900 dark:text-white">{value}</div>
|
||
{subText && <div className="mt-2 text-xs text-gray-500 dark:text-gray-400">{subText}</div>}
|
||
</div>
|
||
)
|
||
}
|
||
|
||
export default function PublicTrafficTab({ showToast }: PublicTrafficTabProps) {
|
||
const [preset, setPreset] = useState<DatePreset>('last7')
|
||
const initialRange = useMemo(() => presetRange('last7'), [])
|
||
const [startDate, setStartDate] = useState(initialRange.start)
|
||
const [endDate, setEndDate] = useState(initialRange.end)
|
||
const [loading, setLoading] = useState(false)
|
||
const [stats, setStats] = useState<PublicTrafficStats | null>(null)
|
||
|
||
const loadStats = useCallback(async () => {
|
||
setLoading(true)
|
||
try {
|
||
const params = new URLSearchParams()
|
||
params.set('start', startDate)
|
||
params.set('end', endDate)
|
||
const response = await fetch(`/api/admin/public-traffic?${params.toString()}`, { cache: 'no-store' })
|
||
|
||
if (!response.ok) {
|
||
const data = await response.json().catch(() => null)
|
||
throw new Error(data?.error || '加载公网流量统计失败')
|
||
}
|
||
|
||
const data = await response.json()
|
||
setStats(data)
|
||
} catch (error) {
|
||
console.error('Load public traffic stats error:', error)
|
||
showToast(error instanceof Error ? error.message : '加载公网流量统计失败', 'error')
|
||
} finally {
|
||
setLoading(false)
|
||
}
|
||
}, [endDate, showToast, startDate])
|
||
|
||
useEffect(() => {
|
||
loadStats()
|
||
}, [loadStats])
|
||
|
||
const handlePresetChange = (nextPreset: Exclude<DatePreset, 'custom'>) => {
|
||
const range = presetRange(nextPreset)
|
||
setPreset(nextPreset)
|
||
setStartDate(range.start)
|
||
setEndDate(range.end)
|
||
}
|
||
|
||
const responseBytes = stats?.summary.responseBytes || 0
|
||
const requestBytes = stats?.summary.requestBytes ?? null
|
||
const totalBytes = requestBytes === null ? responseBytes : responseBytes + requestBytes
|
||
const dayPeak = stats?.byDay.reduce((max, item) => Math.max(max, item.responseBytes), 0) || 0
|
||
|
||
return (
|
||
<div className="space-y-6">
|
||
<div className="rounded-xl border border-gray-200 bg-white p-5 shadow-sm dark:border-gray-700 dark:bg-gray-800">
|
||
<div className="flex flex-col gap-4 lg:flex-row lg:items-end lg:justify-between">
|
||
<div>
|
||
<h2 className="text-xl font-semibold text-gray-900 dark:text-white">公网流量统计</h2>
|
||
<p className="mt-1 text-sm text-gray-500 dark:text-gray-400">
|
||
按 .38 公网入口日志统计,包含素材库、资源入口、产品设计平台经过入口服务器的流量;七牛 CDN 流量以七牛后台为准。
|
||
</p>
|
||
</div>
|
||
|
||
<div className="flex flex-wrap items-end gap-3">
|
||
<div className="flex rounded-lg border border-gray-200 bg-gray-50 p-1 dark:border-gray-700 dark:bg-gray-900">
|
||
{PRESET_OPTIONS.map((item) => (
|
||
<button
|
||
key={item.key}
|
||
type="button"
|
||
onClick={() => handlePresetChange(item.key)}
|
||
className={`rounded-md px-3 py-1.5 text-sm transition-colors ${
|
||
preset === item.key
|
||
? 'bg-white text-gray-900 shadow-sm dark:bg-gray-700 dark:text-white'
|
||
: 'text-gray-500 hover:text-gray-900 dark:text-gray-400 dark:hover:text-white'
|
||
}`}
|
||
>
|
||
{item.label}
|
||
</button>
|
||
))}
|
||
</div>
|
||
|
||
<label className="text-sm text-gray-600 dark:text-gray-300">
|
||
开始
|
||
<input
|
||
type="date"
|
||
value={startDate}
|
||
onChange={(event) => {
|
||
setPreset('custom')
|
||
setStartDate(event.target.value)
|
||
}}
|
||
className="ml-2 rounded-lg border border-gray-200 bg-white px-3 py-2 text-sm dark:border-gray-700 dark:bg-gray-900 dark:text-white"
|
||
/>
|
||
</label>
|
||
|
||
<label className="text-sm text-gray-600 dark:text-gray-300">
|
||
结束
|
||
<input
|
||
type="date"
|
||
value={endDate}
|
||
onChange={(event) => {
|
||
setPreset('custom')
|
||
setEndDate(event.target.value)
|
||
}}
|
||
className="ml-2 rounded-lg border border-gray-200 bg-white px-3 py-2 text-sm dark:border-gray-700 dark:bg-gray-900 dark:text-white"
|
||
/>
|
||
</label>
|
||
|
||
<button
|
||
type="button"
|
||
onClick={loadStats}
|
||
disabled={loading}
|
||
className="rounded-lg bg-gray-900 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-gray-800 disabled:cursor-not-allowed disabled:opacity-60 dark:bg-white dark:text-gray-900 dark:hover:bg-gray-100"
|
||
>
|
||
{loading ? '刷新中...' : '刷新'}
|
||
</button>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
{stats && !stats.available && (
|
||
<div className="rounded-xl border border-amber-200 bg-amber-50 p-4 text-sm text-amber-800 dark:border-amber-800 dark:bg-amber-900/30 dark:text-amber-200">
|
||
暂未读取到公网入口日志。请在服务器环境变量配置 `PUBLIC_TRAFFIC_LOG_PATHS`,或把穿透服务器
|
||
Nginx access log 同步到应用服务器后再查看。
|
||
</div>
|
||
)}
|
||
|
||
{stats && (
|
||
<>
|
||
<div className="grid grid-cols-1 gap-4 md:grid-cols-2 xl:grid-cols-4">
|
||
<StatCard
|
||
label="统计总流量"
|
||
value={formatBytes(totalBytes)}
|
||
subText={requestBytes === null ? '当前日志未包含入站请求字节,先按响应流量统计。' : '响应 + 请求入站'}
|
||
/>
|
||
<StatCard label="响应流量" value={formatBytes(responseBytes)} subText="服务器发送到公网客户端" />
|
||
<StatCard label="请求次数" value={formatNumber(stats.summary.totalRequests)} subText={`${formatNumber(stats.summary.uniqueIpCount)} 个客户端 IP`} />
|
||
<StatCard label="日志范围" value={`${formatTime(stats.summary.firstSeen)} 起`} subText={`最近:${formatTime(stats.summary.lastSeen)}`} />
|
||
</div>
|
||
|
||
<div className="grid grid-cols-1 gap-6 xl:grid-cols-2">
|
||
<div className="rounded-xl border border-gray-200 bg-white p-5 shadow-sm dark:border-gray-700 dark:bg-gray-800">
|
||
<h3 className="mb-4 text-lg font-semibold text-gray-900 dark:text-white">按域名</h3>
|
||
<div className="space-y-4">
|
||
{stats.byDomain.length === 0 && (
|
||
<div className="text-sm text-gray-500 dark:text-gray-400">当前范围没有流量记录。</div>
|
||
)}
|
||
{stats.byDomain.map((item) => {
|
||
const percentage = responseBytes > 0 ? Math.round((item.responseBytes / responseBytes) * 100) : 0
|
||
return (
|
||
<div key={item.domain}>
|
||
<div className="mb-2 flex items-center justify-between gap-3 text-sm">
|
||
<span className="font-medium text-gray-800 dark:text-gray-100">{item.domain}</span>
|
||
<span className="text-gray-500 dark:text-gray-400">
|
||
{formatBytes(item.responseBytes)} · {formatNumber(item.totalRequests)} 次
|
||
</span>
|
||
</div>
|
||
<div className="h-2 rounded-full bg-gray-100 dark:bg-gray-700">
|
||
<div className="h-2 rounded-full bg-sky-500" style={{ width: `${Math.max(percentage, 2)}%` }} />
|
||
</div>
|
||
</div>
|
||
)
|
||
})}
|
||
</div>
|
||
</div>
|
||
|
||
<div className="rounded-xl border border-gray-200 bg-white p-5 shadow-sm dark:border-gray-700 dark:bg-gray-800">
|
||
<h3 className="mb-4 text-lg font-semibold text-gray-900 dark:text-white">按日期</h3>
|
||
<div className="space-y-3">
|
||
{stats.byDay.length === 0 && (
|
||
<div className="text-sm text-gray-500 dark:text-gray-400">当前范围没有流量记录。</div>
|
||
)}
|
||
{stats.byDay.map((item) => {
|
||
const width = dayPeak > 0 ? Math.round((item.responseBytes / dayPeak) * 100) : 0
|
||
return (
|
||
<div key={item.date} className="grid grid-cols-[92px_1fr_120px] items-center gap-3 text-sm">
|
||
<span className="text-gray-500 dark:text-gray-400">{item.date}</span>
|
||
<div className="h-2 rounded-full bg-gray-100 dark:bg-gray-700">
|
||
<div className="h-2 rounded-full bg-teal-500" style={{ width: `${Math.max(width, 2)}%` }} />
|
||
</div>
|
||
<span className="text-right text-gray-700 dark:text-gray-200">{formatBytes(item.responseBytes)}</span>
|
||
</div>
|
||
)
|
||
})}
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
<div className="rounded-xl border border-gray-200 bg-white p-5 shadow-sm dark:border-gray-700 dark:bg-gray-800">
|
||
<h3 className="mb-4 text-lg font-semibold text-gray-900 dark:text-white">流量用途汇总</h3>
|
||
<div className="overflow-x-auto">
|
||
<table className="min-w-full divide-y divide-gray-200 text-sm dark:divide-gray-700">
|
||
<thead>
|
||
<tr className="text-left text-gray-500 dark:text-gray-400">
|
||
<th className="px-3 py-2 font-medium">用途</th>
|
||
<th className="px-3 py-2 font-medium">类别</th>
|
||
<th className="px-3 py-2 text-right font-medium">响应流量</th>
|
||
<th className="px-3 py-2 text-right font-medium">请求次数</th>
|
||
</tr>
|
||
</thead>
|
||
<tbody className="divide-y divide-gray-100 dark:divide-gray-700">
|
||
{stats.byPurpose.slice(0, 12).map((item) => (
|
||
<tr key={item.key} className="text-gray-700 dark:text-gray-200">
|
||
<td className="px-3 py-3">
|
||
<div className="font-medium text-gray-900 dark:text-white">{item.label}</div>
|
||
<div className="mt-1 max-w-[720px] text-xs text-gray-500 dark:text-gray-400">{item.detail}</div>
|
||
</td>
|
||
<td className="px-3 py-3 text-gray-500 dark:text-gray-400">{item.category}</td>
|
||
<td className="px-3 py-3 text-right font-medium">{formatBytes(item.responseBytes)}</td>
|
||
<td className="px-3 py-3 text-right">{formatNumber(item.totalRequests)}</td>
|
||
</tr>
|
||
))}
|
||
{stats.byPurpose.length === 0 && (
|
||
<tr>
|
||
<td colSpan={4} className="px-3 py-6 text-center text-gray-500 dark:text-gray-400">
|
||
当前范围没有用途数据。
|
||
</td>
|
||
</tr>
|
||
)}
|
||
</tbody>
|
||
</table>
|
||
</div>
|
||
</div>
|
||
|
||
<div className="rounded-xl border border-gray-200 bg-white p-5 shadow-sm dark:border-gray-700 dark:bg-gray-800">
|
||
<h3 className="mb-4 text-lg font-semibold text-gray-900 dark:text-white">流量最高路径明细</h3>
|
||
<div className="overflow-x-auto">
|
||
<table className="min-w-full divide-y divide-gray-200 text-sm dark:divide-gray-700">
|
||
<thead>
|
||
<tr className="text-left text-gray-500 dark:text-gray-400">
|
||
<th className="px-3 py-2 font-medium">用途和原始路径</th>
|
||
<th className="px-3 py-2 font-medium">类别</th>
|
||
<th className="px-3 py-2 font-medium">方法</th>
|
||
<th className="px-3 py-2 text-right font-medium">响应流量</th>
|
||
<th className="px-3 py-2 text-right font-medium">请求次数</th>
|
||
</tr>
|
||
</thead>
|
||
<tbody className="divide-y divide-gray-100 dark:divide-gray-700">
|
||
{stats.topPaths.map((item) => (
|
||
<tr key={`${item.method}-${item.path}`} className="text-gray-700 dark:text-gray-200">
|
||
<td className="px-3 py-3">
|
||
<div className="font-medium text-gray-900 dark:text-white">{item.purposeLabel}</div>
|
||
<div className="mt-1 text-xs text-gray-500 dark:text-gray-400">{item.purposeDetail}</div>
|
||
<div className="mt-1 max-w-[640px] truncate font-mono text-xs text-gray-400" title={item.path}>
|
||
{item.path}
|
||
</div>
|
||
</td>
|
||
<td className="px-3 py-3 text-gray-500 dark:text-gray-400">{item.purposeCategory}</td>
|
||
<td className="px-3 py-3">{item.method}</td>
|
||
<td className="px-3 py-3 text-right">{formatBytes(item.responseBytes)}</td>
|
||
<td className="px-3 py-3 text-right">{formatNumber(item.totalRequests)}</td>
|
||
</tr>
|
||
))}
|
||
{stats.topPaths.length === 0 && (
|
||
<tr>
|
||
<td colSpan={5} className="px-3 py-6 text-center text-gray-500 dark:text-gray-400">
|
||
当前范围没有路径数据。
|
||
</td>
|
||
</tr>
|
||
)}
|
||
</tbody>
|
||
</table>
|
||
</div>
|
||
</div>
|
||
|
||
<div className="rounded-xl border border-gray-200 bg-white p-4 text-xs text-gray-500 shadow-sm dark:border-gray-700 dark:bg-gray-800 dark:text-gray-400">
|
||
<div>
|
||
已扫描 {formatNumber(stats.source.scannedFiles)} 个日志文件,{formatNumber(stats.source.scannedLines)} 行;
|
||
命中 {formatNumber(stats.source.matchedLines)} 行。
|
||
{stats.source.truncated ? ' 本次读取达到上限,结果可能不完整。' : ''}
|
||
</div>
|
||
{!stats.source.requestBytesAvailable && (
|
||
<div className="mt-1">
|
||
当前日志没有 `request_length` 字段,上传入站流量无法精确拆分;如需统计上传流量,需要在公网入口日志里增加该字段。
|
||
</div>
|
||
)}
|
||
{stats.source.issues.length > 0 && (
|
||
<details className="mt-2">
|
||
<summary className="cursor-pointer">数据源提示</summary>
|
||
<ul className="mt-2 space-y-1">
|
||
{stats.source.issues.slice(0, 8).map((issue) => (
|
||
<li key={`${issue.path}-${issue.reason}`}>
|
||
{issue.path}:{issue.reason}
|
||
</li>
|
||
))}
|
||
</ul>
|
||
</details>
|
||
)}
|
||
</div>
|
||
</>
|
||
)}
|
||
</div>
|
||
)
|
||
}
|