修復 too many connection 問題
This commit is contained in:
371
app/admin/connection-monitor/page.tsx
Normal file
371
app/admin/connection-monitor/page.tsx
Normal file
@@ -0,0 +1,371 @@
|
||||
'use client';
|
||||
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Loader2, Database, Trash2, Settings, Activity, Clock, Users } from 'lucide-react';
|
||||
|
||||
interface ConnectionStats {
|
||||
totalConnections: number;
|
||||
idleConnections: number;
|
||||
oldConnections: number;
|
||||
maxIdleTime: number;
|
||||
maxConnectionAge: number;
|
||||
connections: Array<{
|
||||
createdAt: string;
|
||||
lastUsed: string;
|
||||
idleTime: number;
|
||||
age: number;
|
||||
userId?: string;
|
||||
sessionId?: string;
|
||||
}>;
|
||||
}
|
||||
|
||||
export default function ConnectionMonitorPage() {
|
||||
const [stats, setStats] = useState<ConnectionStats | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [message, setMessage] = useState<string>('');
|
||||
const [error, setError] = useState<string>('');
|
||||
const [maxIdleTime, setMaxIdleTime] = useState<number>(300000); // 5分鐘
|
||||
const [maxConnectionAge, setMaxConnectionAge] = useState<number>(1800000); // 30分鐘
|
||||
|
||||
// 獲取連線統計
|
||||
const fetchStats = async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
const response = await fetch('/api/connection-monitor?action=stats');
|
||||
const data = await response.json();
|
||||
|
||||
if (data.success) {
|
||||
setStats(data.data);
|
||||
setMessage('統計更新成功');
|
||||
setError('');
|
||||
} else {
|
||||
setError(data.error || '獲取統計失敗');
|
||||
}
|
||||
} catch (err) {
|
||||
setError('網路錯誤: ' + (err instanceof Error ? err.message : '未知錯誤'));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// 強制清理連線
|
||||
const forceCleanup = async () => {
|
||||
if (!confirm('確定要強制清理所有連線嗎?這可能會影響正在進行的操作!')) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
setLoading(true);
|
||||
const response = await fetch('/api/connection-monitor?action=cleanup');
|
||||
const data = await response.json();
|
||||
|
||||
if (data.success) {
|
||||
setMessage('連線清理完成');
|
||||
setError('');
|
||||
await fetchStats(); // 重新獲取統計
|
||||
} else {
|
||||
setError(data.error || '清理失敗');
|
||||
}
|
||||
} catch (err) {
|
||||
setError('清理錯誤: ' + (err instanceof Error ? err.message : '未知錯誤'));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// 測試智能連線
|
||||
const testConnection = async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
const response = await fetch('/api/connection-monitor?action=test');
|
||||
const data = await response.json();
|
||||
|
||||
if (data.success) {
|
||||
setMessage('智能連線測試成功');
|
||||
setError('');
|
||||
await fetchStats(); // 重新獲取統計
|
||||
} else {
|
||||
setError(data.error || '測試失敗');
|
||||
}
|
||||
} catch (err) {
|
||||
setError('測試錯誤: ' + (err instanceof Error ? err.message : '未知錯誤'));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// 更新清理配置
|
||||
const updateConfig = async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
const response = await fetch('/api/connection-monitor', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
action: 'config',
|
||||
maxIdleTime,
|
||||
maxConnectionAge
|
||||
}),
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (data.success) {
|
||||
setMessage('清理配置更新成功');
|
||||
setError('');
|
||||
await fetchStats(); // 重新獲取統計
|
||||
} else {
|
||||
setError(data.error || '配置更新失敗');
|
||||
}
|
||||
} catch (err) {
|
||||
setError('配置更新錯誤: ' + (err instanceof Error ? err.message : '未知錯誤'));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// 格式化時間
|
||||
const formatTime = (ms: number) => {
|
||||
const seconds = Math.floor(ms / 1000);
|
||||
const minutes = Math.floor(seconds / 60);
|
||||
const hours = Math.floor(minutes / 60);
|
||||
|
||||
if (hours > 0) return `${hours}h ${minutes % 60}m`;
|
||||
if (minutes > 0) return `${minutes}m ${seconds % 60}s`;
|
||||
return `${seconds}s`;
|
||||
};
|
||||
|
||||
// 組件載入時獲取統計
|
||||
useEffect(() => {
|
||||
fetchStats();
|
||||
|
||||
// 每30秒自動更新統計
|
||||
const interval = setInterval(fetchStats, 30000);
|
||||
return () => clearInterval(interval);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className="container mx-auto p-6 space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold">連線監控管理</h1>
|
||||
<p className="text-muted-foreground">
|
||||
監控和管理資料庫連線的生命週期
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
onClick={fetchStats}
|
||||
disabled={loading}
|
||||
variant="outline"
|
||||
>
|
||||
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <Activity className="h-4 w-4" />}
|
||||
重新整理
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* 統計概覽 */}
|
||||
{stats && (
|
||||
<div className="grid grid-cols-1 md:grid-cols-4 gap-4">
|
||||
<Card>
|
||||
<CardContent className="p-6">
|
||||
<div className="flex items-center gap-2">
|
||||
<Database className="h-5 w-5 text-blue-500" />
|
||||
<div>
|
||||
<p className="text-sm font-medium text-muted-foreground">總連線數</p>
|
||||
<p className="text-2xl font-bold">{stats.totalConnections}</p>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardContent className="p-6">
|
||||
<div className="flex items-center gap-2">
|
||||
<Clock className="h-5 w-5 text-yellow-500" />
|
||||
<div>
|
||||
<p className="text-sm font-medium text-muted-foreground">空閒連線</p>
|
||||
<p className="text-2xl font-bold">{stats.idleConnections}</p>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardContent className="p-6">
|
||||
<div className="flex items-center gap-2">
|
||||
<Users className="h-5 w-5 text-red-500" />
|
||||
<div>
|
||||
<p className="text-sm font-medium text-muted-foreground">舊連線</p>
|
||||
<p className="text-2xl font-bold">{stats.oldConnections}</p>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardContent className="p-6">
|
||||
<div className="flex items-center gap-2">
|
||||
<Activity className="h-5 w-5 text-green-500" />
|
||||
<div>
|
||||
<p className="text-sm font-medium text-muted-foreground">健康狀態</p>
|
||||
<p className="text-2xl font-bold">
|
||||
{stats.idleConnections + stats.oldConnections === 0 ? '良好' : '需清理'}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 操作按鈕 */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Settings className="h-5 w-5" />
|
||||
連線管理
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
管理和清理資料庫連線
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
|
||||
<Button
|
||||
onClick={testConnection}
|
||||
disabled={loading}
|
||||
variant="outline"
|
||||
className="w-full"
|
||||
>
|
||||
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <Database className="h-4 w-4" />}
|
||||
測試智能連線
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
onClick={forceCleanup}
|
||||
disabled={loading}
|
||||
variant="destructive"
|
||||
className="w-full"
|
||||
>
|
||||
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <Trash2 className="h-4 w-4" />}
|
||||
強制清理連線
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
onClick={updateConfig}
|
||||
disabled={loading}
|
||||
variant="secondary"
|
||||
className="w-full"
|
||||
>
|
||||
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <Settings className="h-4 w-4" />}
|
||||
更新配置
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* 配置設定 */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4 pt-4 border-t">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="maxIdleTime">最大空閒時間 (毫秒)</Label>
|
||||
<Input
|
||||
id="maxIdleTime"
|
||||
type="number"
|
||||
value={maxIdleTime}
|
||||
onChange={(e) => setMaxIdleTime(Number(e.target.value))}
|
||||
placeholder="300000 (5分鐘)"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="maxConnectionAge">最大連線年齡 (毫秒)</Label>
|
||||
<Input
|
||||
id="maxConnectionAge"
|
||||
type="number"
|
||||
value={maxConnectionAge}
|
||||
onChange={(e) => setMaxConnectionAge(Number(e.target.value))}
|
||||
placeholder="1800000 (30分鐘)"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* 連線詳情 */}
|
||||
{stats && stats.connections.length > 0 && (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>連線詳情</CardTitle>
|
||||
<CardDescription>
|
||||
當前活躍的資料庫連線列表
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-2">
|
||||
{stats.connections.map((conn, index) => (
|
||||
<div key={index} className="flex items-center justify-between p-3 border rounded-lg">
|
||||
<div className="flex items-center gap-4">
|
||||
<Badge variant="outline">#{index + 1}</Badge>
|
||||
<div>
|
||||
<p className="text-sm font-medium">
|
||||
創建時間: {new Date(conn.createdAt).toLocaleString()}
|
||||
</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
最後使用: {new Date(conn.lastUsed).toLocaleString()}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Badge variant={conn.idleTime > stats.maxIdleTime ? "destructive" : "default"}>
|
||||
空閒: {formatTime(conn.idleTime)}
|
||||
</Badge>
|
||||
<Badge variant={conn.age > stats.maxConnectionAge ? "destructive" : "default"}>
|
||||
年齡: {formatTime(conn.age)}
|
||||
</Badge>
|
||||
{conn.userId && (
|
||||
<Badge variant="secondary">用戶: {conn.userId}</Badge>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* 訊息顯示 */}
|
||||
{message && (
|
||||
<Alert>
|
||||
<Activity className="h-4 w-4" />
|
||||
<AlertDescription>{message}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{error && (
|
||||
<Alert variant="destructive">
|
||||
<Database className="h-4 w-4" />
|
||||
<AlertDescription>{error}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{/* 說明資訊 */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>智能連線管理說明</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-2 text-sm text-muted-foreground">
|
||||
<p>• <strong>自動清理:</strong> 系統每30秒自動檢查並清理空閒或過期的連線</p>
|
||||
<p>• <strong>智能追蹤:</strong> 追蹤每個連線的創建時間、最後使用時間和用戶信息</p>
|
||||
<p>• <strong>即時監控:</strong> 實時顯示連線狀態,幫助識別連線洩漏問題</p>
|
||||
<p>• <strong>自動釋放:</strong> 查詢完成後自動釋放連線,避免連線累積</p>
|
||||
<p>• <strong>用戶關閉網頁:</strong> 空閒連線會在設定的時間後自動清理</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
267
app/admin/database-shutdown/page.tsx
Normal file
267
app/admin/database-shutdown/page.tsx
Normal file
@@ -0,0 +1,267 @@
|
||||
'use client';
|
||||
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||
import { Loader2, Database, Power, AlertTriangle, CheckCircle } from 'lucide-react';
|
||||
|
||||
interface ShutdownStatus {
|
||||
isShuttingDown: boolean;
|
||||
handlerCount: number;
|
||||
registeredHandlers: string[];
|
||||
}
|
||||
|
||||
export default function DatabaseShutdownPage() {
|
||||
const [status, setStatus] = useState<ShutdownStatus | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [message, setMessage] = useState<string>('');
|
||||
const [error, setError] = useState<string>('');
|
||||
|
||||
// 獲取關閉狀態
|
||||
const fetchStatus = async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
const response = await fetch('/api/test-shutdown?action=status');
|
||||
const data = await response.json();
|
||||
|
||||
if (data.success) {
|
||||
setStatus(data.data);
|
||||
setMessage('狀態更新成功');
|
||||
setError('');
|
||||
} else {
|
||||
setError(data.error || '獲取狀態失敗');
|
||||
}
|
||||
} catch (err) {
|
||||
setError('網路錯誤: ' + (err instanceof Error ? err.message : '未知錯誤'));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// 測試關閉機制
|
||||
const testShutdown = async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
const response = await fetch('/api/test-shutdown?action=test');
|
||||
const data = await response.json();
|
||||
|
||||
if (data.success) {
|
||||
setMessage('關閉機制測試成功');
|
||||
setError('');
|
||||
await fetchStatus(); // 重新獲取狀態
|
||||
} else {
|
||||
setError(data.error || '測試失敗');
|
||||
}
|
||||
} catch (err) {
|
||||
setError('測試錯誤: ' + (err instanceof Error ? err.message : '未知錯誤'));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// 強制關閉測試
|
||||
const forceShutdown = async () => {
|
||||
if (!confirm('確定要執行強制關閉測試嗎?這可能會影響應用程式運行!')) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
setLoading(true);
|
||||
const response = await fetch('/api/test-shutdown?action=force');
|
||||
const data = await response.json();
|
||||
|
||||
if (data.success) {
|
||||
setMessage('強制關閉測試完成');
|
||||
setError('');
|
||||
await fetchStatus(); // 重新獲取狀態
|
||||
} else {
|
||||
setError(data.error || '強制關閉測試失敗');
|
||||
}
|
||||
} catch (err) {
|
||||
setError('強制關閉錯誤: ' + (err instanceof Error ? err.message : '未知錯誤'));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// 優雅關閉測試
|
||||
const gracefulShutdown = async () => {
|
||||
if (!confirm('確定要執行優雅關閉測試嗎?這會關閉所有資料庫連線!')) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
setLoading(true);
|
||||
const response = await fetch('/api/test-shutdown', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({ action: 'graceful' }),
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (data.success) {
|
||||
setMessage('優雅關閉測試完成');
|
||||
setError('');
|
||||
await fetchStatus(); // 重新獲取狀態
|
||||
} else {
|
||||
setError(data.error || '優雅關閉測試失敗');
|
||||
}
|
||||
} catch (err) {
|
||||
setError('優雅關閉錯誤: ' + (err instanceof Error ? err.message : '未知錯誤'));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// 組件載入時獲取狀態
|
||||
useEffect(() => {
|
||||
fetchStatus();
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className="container mx-auto p-6 space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold">資料庫關閉管理</h1>
|
||||
<p className="text-muted-foreground">
|
||||
監控和管理資料庫連線的關閉機制
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
onClick={fetchStatus}
|
||||
disabled={loading}
|
||||
variant="outline"
|
||||
>
|
||||
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <Database className="h-4 w-4" />}
|
||||
重新整理狀態
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* 狀態顯示 */}
|
||||
{status && (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Database className="h-5 w-5" />
|
||||
關閉狀態
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
當前資料庫關閉管理器的運行狀態
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-sm font-medium">關閉狀態:</span>
|
||||
<Badge variant={status.isShuttingDown ? "destructive" : "default"}>
|
||||
{status.isShuttingDown ? "關閉中" : "正常"}
|
||||
</Badge>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-sm font-medium">處理器數量:</span>
|
||||
<Badge variant="outline">{status.handlerCount}</Badge>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-sm font-medium">狀態:</span>
|
||||
<Badge variant={status.isShuttingDown ? "destructive" : "default"}>
|
||||
{status.isShuttingDown ? "異常" : "正常"}
|
||||
</Badge>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<span className="text-sm font-medium">已註冊的處理器:</span>
|
||||
<div className="mt-2 flex flex-wrap gap-2">
|
||||
{status.registeredHandlers.map((handler, index) => (
|
||||
<Badge key={index} variant="secondary">
|
||||
{handler}
|
||||
</Badge>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* 操作按鈕 */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Power className="h-5 w-5" />
|
||||
關閉操作
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
測試和管理資料庫關閉機制
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
|
||||
<Button
|
||||
onClick={testShutdown}
|
||||
disabled={loading}
|
||||
variant="outline"
|
||||
className="w-full"
|
||||
>
|
||||
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <CheckCircle className="h-4 w-4" />}
|
||||
測試關閉機制
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
onClick={forceShutdown}
|
||||
disabled={loading}
|
||||
variant="destructive"
|
||||
className="w-full"
|
||||
>
|
||||
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <AlertTriangle className="h-4 w-4" />}
|
||||
強制關閉測試
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
onClick={gracefulShutdown}
|
||||
disabled={loading}
|
||||
variant="destructive"
|
||||
className="w-full"
|
||||
>
|
||||
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <Power className="h-4 w-4" />}
|
||||
優雅關閉測試
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* 訊息顯示 */}
|
||||
{message && (
|
||||
<Alert>
|
||||
<CheckCircle className="h-4 w-4" />
|
||||
<AlertDescription>{message}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{error && (
|
||||
<Alert variant="destructive">
|
||||
<AlertTriangle className="h-4 w-4" />
|
||||
<AlertDescription>{error}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{/* 說明資訊 */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>使用說明</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-2 text-sm text-muted-foreground">
|
||||
<p>• <strong>測試關閉機制:</strong> 檢查關閉處理器是否正常註冊,不會實際關閉連線</p>
|
||||
<p>• <strong>強制關閉測試:</strong> 模擬強制關閉所有資料庫連線(用於測試)</p>
|
||||
<p>• <strong>優雅關閉測試:</strong> 執行完整的優雅關閉流程(會實際關閉連線)</p>
|
||||
<p>• 當應用程式收到 SIGINT 或 SIGTERM 信號時,會自動執行優雅關閉</p>
|
||||
<p>• 關閉管理器會確保所有資料庫連線池都被正確關閉</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
281
app/admin/emergency-cleanup/page.tsx
Normal file
281
app/admin/emergency-cleanup/page.tsx
Normal file
@@ -0,0 +1,281 @@
|
||||
'use client';
|
||||
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||
import { Loader2, Database, AlertTriangle, Trash2, Eye, Zap } from 'lucide-react';
|
||||
|
||||
interface ConnectionDetail {
|
||||
ID: number;
|
||||
USER: string;
|
||||
HOST: string;
|
||||
DB: string;
|
||||
COMMAND: string;
|
||||
TIME: number;
|
||||
STATE: string;
|
||||
INFO?: string;
|
||||
}
|
||||
|
||||
interface ConnectionData {
|
||||
connectionCount: number;
|
||||
connections: ConnectionDetail[];
|
||||
}
|
||||
|
||||
export default function EmergencyCleanupPage() {
|
||||
const [connectionData, setConnectionData] = useState<ConnectionData | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [message, setMessage] = useState<string>('');
|
||||
const [error, setError] = useState<string>('');
|
||||
|
||||
// 獲取連線詳情
|
||||
const fetchConnectionDetails = async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
const response = await fetch('/api/emergency-cleanup?action=details');
|
||||
const data = await response.json();
|
||||
|
||||
if (data.success) {
|
||||
setConnectionData(data.data);
|
||||
setMessage('連線詳情更新成功');
|
||||
setError('');
|
||||
} else {
|
||||
setError(data.error || '獲取連線詳情失敗');
|
||||
}
|
||||
} catch (err) {
|
||||
setError('網路錯誤: ' + (err instanceof Error ? err.message : '未知錯誤'));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// 執行緊急清理
|
||||
const executeEmergencyCleanup = async () => {
|
||||
if (!confirm('確定要執行緊急清理嗎?這會關閉所有資料庫連線!')) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
setLoading(true);
|
||||
const response = await fetch('/api/emergency-cleanup', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({ action: 'cleanup' }),
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (data.success) {
|
||||
setMessage('緊急清理完成');
|
||||
setError('');
|
||||
await fetchConnectionDetails(); // 重新獲取詳情
|
||||
} else {
|
||||
setError(data.error || '緊急清理失敗');
|
||||
}
|
||||
} catch (err) {
|
||||
setError('緊急清理錯誤: ' + (err instanceof Error ? err.message : '未知錯誤'));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// 強制殺死所有連線
|
||||
const forceKillAllConnections = async () => {
|
||||
if (!confirm('確定要強制殺死所有連線嗎?這會立即終止所有資料庫連線!')) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
setLoading(true);
|
||||
const response = await fetch('/api/emergency-cleanup', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({ action: 'kill-all' }),
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (data.success) {
|
||||
setMessage('強制殺死連線完成');
|
||||
setError('');
|
||||
await fetchConnectionDetails(); // 重新獲取詳情
|
||||
} else {
|
||||
setError(data.error || '強制殺死連線失敗');
|
||||
}
|
||||
} catch (err) {
|
||||
setError('強制殺死連線錯誤: ' + (err instanceof Error ? err.message : '未知錯誤'));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// 組件載入時獲取連線詳情
|
||||
useEffect(() => {
|
||||
fetchConnectionDetails();
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className="container mx-auto p-6 space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold text-red-600">緊急連線清理</h1>
|
||||
<p className="text-muted-foreground">
|
||||
緊急清理和強制關閉資料庫連線
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
onClick={fetchConnectionDetails}
|
||||
disabled={loading}
|
||||
variant="outline"
|
||||
>
|
||||
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <Eye className="h-4 w-4" />}
|
||||
重新整理
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* 警告提示 */}
|
||||
<Alert variant="destructive">
|
||||
<AlertTriangle className="h-4 w-4" />
|
||||
<AlertDescription>
|
||||
<strong>警告:</strong> 這些操作會立即關閉所有資料庫連線,可能影響正在運行的應用程式。請謹慎使用!
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
|
||||
{/* 連線統計 */}
|
||||
{connectionData && (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Database className="h-5 w-5" />
|
||||
當前連線狀態
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
資料庫連線的詳細信息
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="flex items-center gap-4">
|
||||
<Badge variant="outline" className="text-lg px-3 py-1">
|
||||
總連線數: {connectionData.connectionCount}
|
||||
</Badge>
|
||||
<Badge
|
||||
variant={connectionData.connectionCount > 10 ? "destructive" : "default"}
|
||||
className="text-lg px-3 py-1"
|
||||
>
|
||||
狀態: {connectionData.connectionCount > 10 ? "異常" : "正常"}
|
||||
</Badge>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* 緊急操作 */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2 text-red-600">
|
||||
<Zap className="h-5 w-5" />
|
||||
緊急操作
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
立即清理和關閉資料庫連線
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<Button
|
||||
onClick={executeEmergencyCleanup}
|
||||
disabled={loading}
|
||||
variant="destructive"
|
||||
className="w-full"
|
||||
>
|
||||
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <Trash2 className="h-4 w-4" />}
|
||||
緊急清理連線
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
onClick={forceKillAllConnections}
|
||||
disabled={loading}
|
||||
variant="destructive"
|
||||
className="w-full"
|
||||
>
|
||||
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <AlertTriangle className="h-4 w-4" />}
|
||||
強制殺死所有連線
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* 連線詳情列表 */}
|
||||
{connectionData && connectionData.connections.length > 0 && (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>連線詳情列表</CardTitle>
|
||||
<CardDescription>
|
||||
當前所有資料庫連線的詳細信息
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-2 max-h-96 overflow-y-auto">
|
||||
{connectionData.connections.map((conn, index) => (
|
||||
<div key={conn.ID} className="flex items-center justify-between p-3 border rounded-lg">
|
||||
<div className="flex items-center gap-4">
|
||||
<Badge variant="outline">#{conn.ID}</Badge>
|
||||
<div>
|
||||
<p className="text-sm font-medium">
|
||||
用戶: {conn.USER} | 主機: {conn.HOST}
|
||||
</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
資料庫: {conn.DB} | 命令: {conn.COMMAND}
|
||||
</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
時間: {conn.TIME}s | 狀態: {conn.STATE}
|
||||
</p>
|
||||
{conn.INFO && (
|
||||
<p className="text-xs text-muted-foreground mt-1">
|
||||
查詢: {conn.INFO.length > 100 ? conn.INFO.substring(0, 100) + '...' : conn.INFO}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* 訊息顯示 */}
|
||||
{message && (
|
||||
<Alert>
|
||||
<Database className="h-4 w-4" />
|
||||
<AlertDescription>{message}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{error && (
|
||||
<Alert variant="destructive">
|
||||
<AlertTriangle className="h-4 w-4" />
|
||||
<AlertDescription>{error}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{/* 使用說明 */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>使用說明</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-2 text-sm text-muted-foreground">
|
||||
<p>• <strong>緊急清理連線:</strong> 停止監控並關閉所有連線池,這是較溫和的方式</p>
|
||||
<p>• <strong>強制殺死所有連線:</strong> 直接殺死資料庫中的所有連線,這是更激進的方式</p>
|
||||
<p>• <strong>重新整理:</strong> 獲取最新的連線狀態和詳情</p>
|
||||
<p>• 建議先嘗試「緊急清理連線」,如果無效再使用「強制殺死所有連線」</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
442
app/admin/ip-cleanup/page.tsx
Normal file
442
app/admin/ip-cleanup/page.tsx
Normal file
@@ -0,0 +1,442 @@
|
||||
'use client';
|
||||
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Loader2, Database, AlertTriangle, Trash2, Eye, Zap, Globe } from 'lucide-react';
|
||||
|
||||
interface ConnectionDetail {
|
||||
ID: number;
|
||||
USER: string;
|
||||
HOST: string;
|
||||
DB: string;
|
||||
COMMAND: string;
|
||||
TIME: number;
|
||||
STATE: string;
|
||||
INFO?: string;
|
||||
}
|
||||
|
||||
interface ConnectionStatus {
|
||||
ip: string;
|
||||
connectionCount: number;
|
||||
connections: ConnectionDetail[];
|
||||
}
|
||||
|
||||
interface LocalStats {
|
||||
clientIP: string;
|
||||
trackedConnections: number;
|
||||
connections: Array<{
|
||||
connectionId: string;
|
||||
createdAt: string;
|
||||
lastUsed: string;
|
||||
userAgent?: string;
|
||||
}>;
|
||||
}
|
||||
|
||||
export default function IPCleanupPage() {
|
||||
const [connectionStatus, setConnectionStatus] = useState<ConnectionStatus | null>(null);
|
||||
const [localStats, setLocalStats] = useState<LocalStats | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [message, setMessage] = useState<string>('');
|
||||
const [error, setError] = useState<string>('');
|
||||
const [targetIP, setTargetIP] = useState<string>('');
|
||||
|
||||
// 獲取當前 IP 的連線狀態
|
||||
const fetchCurrentIPStatus = async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
const response = await fetch('/api/ip-cleanup?action=status');
|
||||
const data = await response.json();
|
||||
|
||||
if (data.success) {
|
||||
setConnectionStatus(data.data);
|
||||
setMessage('當前 IP 連線狀態更新成功');
|
||||
setError('');
|
||||
} else {
|
||||
setError(data.error || '獲取當前 IP 連線狀態失敗');
|
||||
}
|
||||
} catch (err) {
|
||||
setError('網路錯誤: ' + (err instanceof Error ? err.message : '未知錯誤'));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// 獲取指定 IP 的連線狀態
|
||||
const fetchSpecificIPStatus = async () => {
|
||||
if (!targetIP.trim()) {
|
||||
setError('請輸入目標 IP 地址');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
setLoading(true);
|
||||
const response = await fetch(`/api/ip-cleanup?action=status-specific&ip=${encodeURIComponent(targetIP)}`);
|
||||
const data = await response.json();
|
||||
|
||||
if (data.success) {
|
||||
setConnectionStatus(data.data);
|
||||
setMessage(`指定 IP ${targetIP} 的連線狀態更新成功`);
|
||||
setError('');
|
||||
} else {
|
||||
setError(data.error || '獲取指定 IP 連線狀態失敗');
|
||||
}
|
||||
} catch (err) {
|
||||
setError('網路錯誤: ' + (err instanceof Error ? err.message : '未知錯誤'));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// 獲取本地連線統計
|
||||
const fetchLocalStats = async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
const response = await fetch('/api/ip-cleanup?action=local-stats');
|
||||
const data = await response.json();
|
||||
|
||||
if (data.success) {
|
||||
setLocalStats(data.data);
|
||||
setMessage('本地連線統計更新成功');
|
||||
setError('');
|
||||
} else {
|
||||
setError(data.error || '獲取本地連線統計失敗');
|
||||
}
|
||||
} catch (err) {
|
||||
setError('網路錯誤: ' + (err instanceof Error ? err.message : '未知錯誤'));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// 清理當前 IP 的連線
|
||||
const cleanupCurrentIP = async () => {
|
||||
if (!confirm('確定要清理當前 IP 的所有連線嗎?')) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
setLoading(true);
|
||||
const response = await fetch('/api/ip-cleanup', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({ action: 'cleanup-current' }),
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (data.success) {
|
||||
setMessage(data.message || '當前 IP 連線清理完成');
|
||||
setError('');
|
||||
await fetchCurrentIPStatus(); // 重新獲取狀態
|
||||
} else {
|
||||
setError(data.error || '當前 IP 連線清理失敗');
|
||||
}
|
||||
} catch (err) {
|
||||
setError('當前 IP 連線清理錯誤: ' + (err instanceof Error ? err.message : '未知錯誤'));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// 清理指定 IP 的連線
|
||||
const cleanupSpecificIP = async () => {
|
||||
if (!targetIP.trim()) {
|
||||
setError('請輸入目標 IP 地址');
|
||||
return;
|
||||
}
|
||||
|
||||
if (!confirm(`確定要清理 IP ${targetIP} 的所有連線嗎?`)) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
setLoading(true);
|
||||
const response = await fetch('/api/ip-cleanup', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
action: 'cleanup-specific',
|
||||
targetIP: targetIP.trim()
|
||||
}),
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (data.success) {
|
||||
setMessage(data.message || `IP ${targetIP} 連線清理完成`);
|
||||
setError('');
|
||||
await fetchSpecificIPStatus(); // 重新獲取狀態
|
||||
} else {
|
||||
setError(data.error || `IP ${targetIP} 連線清理失敗`);
|
||||
}
|
||||
} catch (err) {
|
||||
setError(`IP ${targetIP} 連線清理錯誤: ` + (err instanceof Error ? err.message : '未知錯誤'));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// 清理本地追蹤的連線
|
||||
const cleanupLocalConnections = async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
const response = await fetch('/api/ip-cleanup', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({ action: 'cleanup-local' }),
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (data.success) {
|
||||
setMessage(data.message || '本地連線清理完成');
|
||||
setError('');
|
||||
await fetchLocalStats(); // 重新獲取統計
|
||||
} else {
|
||||
setError(data.error || '本地連線清理失敗');
|
||||
}
|
||||
} catch (err) {
|
||||
setError('本地連線清理錯誤: ' + (err instanceof Error ? err.message : '未知錯誤'));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// 組件載入時獲取狀態
|
||||
useEffect(() => {
|
||||
fetchCurrentIPStatus();
|
||||
fetchLocalStats();
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className="container mx-auto p-6 space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold">IP 連線管理</h1>
|
||||
<p className="text-muted-foreground">
|
||||
基於 IP 地址的智能連線清理和管理
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
onClick={fetchCurrentIPStatus}
|
||||
disabled={loading}
|
||||
variant="outline"
|
||||
>
|
||||
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <Eye className="h-4 w-4" />}
|
||||
當前 IP
|
||||
</Button>
|
||||
<Button
|
||||
onClick={fetchLocalStats}
|
||||
disabled={loading}
|
||||
variant="outline"
|
||||
>
|
||||
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <Database className="h-4 w-4" />}
|
||||
本地統計
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 當前 IP 連線狀態 */}
|
||||
{connectionStatus && (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Globe className="h-5 w-5" />
|
||||
IP 連線狀態
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
IP: {connectionStatus.ip} | 連線數: {connectionStatus.connectionCount}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="flex items-center gap-4">
|
||||
<Badge variant="outline" className="text-lg px-3 py-1">
|
||||
連線數: {connectionStatus.connectionCount}
|
||||
</Badge>
|
||||
<Badge
|
||||
variant={connectionStatus.connectionCount > 5 ? "destructive" : "default"}
|
||||
className="text-lg px-3 py-1"
|
||||
>
|
||||
狀態: {connectionStatus.connectionCount > 5 ? "異常" : "正常"}
|
||||
</Badge>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* 本地連線統計 */}
|
||||
{localStats && (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Database className="h-5 w-5" />
|
||||
本地連線統計
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
客戶端 IP: {localStats.clientIP} | 追蹤連線數: {localStats.trackedConnections}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-2">
|
||||
{localStats.connections.map((conn, index) => (
|
||||
<div key={index} className="flex items-center justify-between p-2 border rounded">
|
||||
<div>
|
||||
<p className="text-sm font-medium">連線 ID: {conn.connectionId}</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
創建: {new Date(conn.createdAt).toLocaleString()} |
|
||||
最後使用: {new Date(conn.lastUsed).toLocaleString()}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* 操作按鈕 */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Trash2 className="h-5 w-5" />
|
||||
IP 連線清理
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
清理指定 IP 地址的資料庫連線
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<Button
|
||||
onClick={cleanupCurrentIP}
|
||||
disabled={loading}
|
||||
variant="destructive"
|
||||
className="w-full"
|
||||
>
|
||||
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <Trash2 className="h-4 w-4" />}
|
||||
清理當前 IP 連線
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
onClick={cleanupLocalConnections}
|
||||
disabled={loading}
|
||||
variant="outline"
|
||||
className="w-full"
|
||||
>
|
||||
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <Database className="h-4 w-4" />}
|
||||
清理本地追蹤連線
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* 指定 IP 清理 */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="targetIP">指定 IP 地址</Label>
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
id="targetIP"
|
||||
value={targetIP}
|
||||
onChange={(e) => setTargetIP(e.target.value)}
|
||||
placeholder="例如: 192.168.1.100"
|
||||
className="flex-1"
|
||||
/>
|
||||
<Button
|
||||
onClick={fetchSpecificIPStatus}
|
||||
disabled={loading || !targetIP.trim()}
|
||||
variant="outline"
|
||||
>
|
||||
<Eye className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
onClick={cleanupSpecificIP}
|
||||
disabled={loading || !targetIP.trim()}
|
||||
variant="destructive"
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* 連線詳情列表 */}
|
||||
{connectionStatus && connectionStatus.connections.length > 0 && (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>連線詳情列表</CardTitle>
|
||||
<CardDescription>
|
||||
IP {connectionStatus.ip} 的所有資料庫連線
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-2 max-h-96 overflow-y-auto">
|
||||
{connectionStatus.connections.map((conn, index) => (
|
||||
<div key={conn.ID} className="flex items-center justify-between p-3 border rounded-lg">
|
||||
<div className="flex items-center gap-4">
|
||||
<Badge variant="outline">#{conn.ID}</Badge>
|
||||
<div>
|
||||
<p className="text-sm font-medium">
|
||||
用戶: {conn.USER} | 主機: {conn.HOST}
|
||||
</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
資料庫: {conn.DB} | 命令: {conn.COMMAND}
|
||||
</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
時間: {conn.TIME}s | 狀態: {conn.STATE}
|
||||
</p>
|
||||
{conn.INFO && (
|
||||
<p className="text-xs text-muted-foreground mt-1">
|
||||
查詢: {conn.INFO.length > 100 ? conn.INFO.substring(0, 100) + '...' : conn.INFO}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* 訊息顯示 */}
|
||||
{message && (
|
||||
<Alert>
|
||||
<Database className="h-4 w-4" />
|
||||
<AlertDescription>{message}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{error && (
|
||||
<Alert variant="destructive">
|
||||
<AlertTriangle className="h-4 w-4" />
|
||||
<AlertDescription>{error}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{/* 使用說明 */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>IP 連線管理說明</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-2 text-sm text-muted-foreground">
|
||||
<p>• <strong>當前 IP 連線:</strong> 顯示和清理當前訪問者的所有資料庫連線</p>
|
||||
<p>• <strong>指定 IP 連線:</strong> 輸入特定 IP 地址來查看和清理該 IP 的連線</p>
|
||||
<p>• <strong>本地追蹤連線:</strong> 清理應用程式內部追蹤的連線記錄</p>
|
||||
<p>• <strong>智能清理:</strong> 只清理指定 IP 的連線,不影響其他用戶</p>
|
||||
<p>• <strong>關閉網站時:</strong> 系統會自動清理當前 IP 的所有連線</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
314
app/admin/ultimate-kill/page.tsx
Normal file
314
app/admin/ultimate-kill/page.tsx
Normal file
@@ -0,0 +1,314 @@
|
||||
'use client';
|
||||
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||
import { Loader2, Database, AlertTriangle, Trash2, Eye, Zap, Skull } from 'lucide-react';
|
||||
|
||||
interface ConnectionStatus {
|
||||
currentConnections: number;
|
||||
maxConnections: number;
|
||||
usagePercentage: number;
|
||||
connectionDetails: Array<{
|
||||
ID: number;
|
||||
USER: string;
|
||||
HOST: string;
|
||||
DB: string;
|
||||
COMMAND: string;
|
||||
TIME: number;
|
||||
STATE: string;
|
||||
INFO?: string;
|
||||
}>;
|
||||
connectionCount: number;
|
||||
}
|
||||
|
||||
export default function UltimateKillPage() {
|
||||
const [status, setStatus] = useState<ConnectionStatus | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [message, setMessage] = useState<string>('');
|
||||
const [error, setError] = useState<string>('');
|
||||
|
||||
// 獲取連線狀態
|
||||
const fetchStatus = async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
const response = await fetch('/api/ultimate-kill?action=status');
|
||||
const data = await response.json();
|
||||
|
||||
if (data.success) {
|
||||
setStatus(data.data);
|
||||
setMessage('狀態更新成功');
|
||||
setError('');
|
||||
} else {
|
||||
setError(data.error || '獲取狀態失敗');
|
||||
}
|
||||
} catch (err) {
|
||||
setError('網路錯誤: ' + (err instanceof Error ? err.message : '未知錯誤'));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// 終極清理 - 殺死所有連線
|
||||
const ultimateKill = async () => {
|
||||
if (!confirm('確定要執行終極清理嗎?這會強制殺死所有資料庫連線!')) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
setLoading(true);
|
||||
const response = await fetch('/api/ultimate-kill', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({ action: 'kill-all' }),
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (data.success) {
|
||||
setMessage(data.message || '終極清理完成');
|
||||
setError('');
|
||||
await fetchStatus(); // 重新獲取狀態
|
||||
} else {
|
||||
setError(data.error || '終極清理失敗');
|
||||
}
|
||||
} catch (err) {
|
||||
setError('終極清理錯誤: ' + (err instanceof Error ? err.message : '未知錯誤'));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// 強制重啟資料庫連線
|
||||
const forceRestart = async () => {
|
||||
if (!confirm('確定要強制重啟資料庫連線嗎?這會先殺死所有連線然後重新建立!')) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
setLoading(true);
|
||||
const response = await fetch('/api/ultimate-kill', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({ action: 'restart' }),
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (data.success) {
|
||||
setMessage(data.message || '強制重啟完成');
|
||||
setError('');
|
||||
await fetchStatus(); // 重新獲取狀態
|
||||
} else {
|
||||
setError(data.error || '強制重啟失敗');
|
||||
}
|
||||
} catch (err) {
|
||||
setError('強制重啟錯誤: ' + (err instanceof Error ? err.message : '未知錯誤'));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// 組件載入時獲取狀態
|
||||
useEffect(() => {
|
||||
fetchStatus();
|
||||
|
||||
// 每10秒自動更新狀態
|
||||
const interval = setInterval(fetchStatus, 10000);
|
||||
return () => clearInterval(interval);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className="container mx-auto p-6 space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold text-red-600">終極連線清理</h1>
|
||||
<p className="text-muted-foreground">
|
||||
強制殺死所有資料庫連線 - 最後手段
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
onClick={fetchStatus}
|
||||
disabled={loading}
|
||||
variant="outline"
|
||||
>
|
||||
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <Eye className="h-4 w-4" />}
|
||||
重新整理
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* 嚴重警告 */}
|
||||
<Alert variant="destructive">
|
||||
<Skull className="h-4 w-4" />
|
||||
<AlertDescription>
|
||||
<strong>嚴重警告:</strong> 這些操作會立即強制殺死所有資料庫連線,可能導致正在運行的應用程式崩潰。請確保沒有重要操作正在進行!
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
|
||||
{/* 連線狀態概覽 */}
|
||||
{status && (
|
||||
<div className="grid grid-cols-1 md:grid-cols-4 gap-4">
|
||||
<Card>
|
||||
<CardContent className="p-6">
|
||||
<div className="flex items-center gap-2">
|
||||
<Database className="h-5 w-5 text-blue-500" />
|
||||
<div>
|
||||
<p className="text-sm font-medium text-muted-foreground">總連線數</p>
|
||||
<p className="text-2xl font-bold">{status.currentConnections}</p>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardContent className="p-6">
|
||||
<div className="flex items-center gap-2">
|
||||
<AlertTriangle className="h-5 w-5 text-yellow-500" />
|
||||
<div>
|
||||
<p className="text-sm font-medium text-muted-foreground">最大連線數</p>
|
||||
<p className="text-2xl font-bold">{status.maxConnections}</p>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardContent className="p-6">
|
||||
<div className="flex items-center gap-2">
|
||||
<Zap className="h-5 w-5 text-red-500" />
|
||||
<div>
|
||||
<p className="text-sm font-medium text-muted-foreground">使用率</p>
|
||||
<p className="text-2xl font-bold">{status.usagePercentage.toFixed(1)}%</p>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardContent className="p-6">
|
||||
<div className="flex items-center gap-2">
|
||||
<Trash2 className="h-5 w-5 text-green-500" />
|
||||
<div>
|
||||
<p className="text-sm font-medium text-muted-foreground">狀態</p>
|
||||
<p className="text-2xl font-bold">
|
||||
{status.connectionCount <= 1 ? '正常' : '異常'}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 終極操作 */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2 text-red-600">
|
||||
<Skull className="h-5 w-5" />
|
||||
終極操作
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
強制殺死所有資料庫連線 - 最後手段
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<Button
|
||||
onClick={ultimateKill}
|
||||
disabled={loading}
|
||||
variant="destructive"
|
||||
className="w-full"
|
||||
>
|
||||
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <Skull className="h-4 w-4" />}
|
||||
終極清理 - 殺死所有連線
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
onClick={forceRestart}
|
||||
disabled={loading}
|
||||
variant="destructive"
|
||||
className="w-full"
|
||||
>
|
||||
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <Zap className="h-4 w-4" />}
|
||||
強制重啟資料庫連線
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* 連線詳情列表 */}
|
||||
{status && status.connectionDetails.length > 0 && (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>連線詳情列表</CardTitle>
|
||||
<CardDescription>
|
||||
當前所有資料庫連線的詳細信息
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-2 max-h-96 overflow-y-auto">
|
||||
{status.connectionDetails.map((conn, index) => (
|
||||
<div key={conn.ID} className="flex items-center justify-between p-3 border rounded-lg">
|
||||
<div className="flex items-center gap-4">
|
||||
<Badge variant="outline">#{conn.ID}</Badge>
|
||||
<div>
|
||||
<p className="text-sm font-medium">
|
||||
用戶: {conn.USER} | 主機: {conn.HOST}
|
||||
</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
資料庫: {conn.DB} | 命令: {conn.COMMAND}
|
||||
</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
時間: {conn.TIME}s | 狀態: {conn.STATE}
|
||||
</p>
|
||||
{conn.INFO && (
|
||||
<p className="text-xs text-muted-foreground mt-1">
|
||||
查詢: {conn.INFO.length > 100 ? conn.INFO.substring(0, 100) + '...' : conn.INFO}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* 訊息顯示 */}
|
||||
{message && (
|
||||
<Alert>
|
||||
<Database className="h-4 w-4" />
|
||||
<AlertDescription>{message}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{error && (
|
||||
<Alert variant="destructive">
|
||||
<AlertTriangle className="h-4 w-4" />
|
||||
<AlertDescription>{error}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{/* 使用說明 */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>終極清理說明</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-2 text-sm text-muted-foreground">
|
||||
<p>• <strong>終極清理:</strong> 直接殺死資料庫中的所有連線,立即生效</p>
|
||||
<p>• <strong>強制重啟:</strong> 先殺死所有連線,等待系統穩定,然後重新建立連線</p>
|
||||
<p>• <strong>自動更新:</strong> 頁面每10秒自動更新連線狀態</p>
|
||||
<p>• <strong>最後手段:</strong> 這些操作是最後的手段,會立即終止所有連線</p>
|
||||
<p>• 建議先嘗試「終極清理」,如果問題持續再使用「強制重啟」</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
37
app/api/competitions/[id]/route.ts
Normal file
37
app/api/competitions/[id]/route.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
// =====================================================
|
||||
// 獲取競賽詳情 API
|
||||
// =====================================================
|
||||
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { CompetitionService } from '@/lib/services/database-service';
|
||||
|
||||
export async function GET(request: NextRequest, { params }: { params: { id: string } }) {
|
||||
try {
|
||||
const { id } = await params;
|
||||
|
||||
// 獲取競賽詳情
|
||||
const competition = await CompetitionService.getCompetitionById(id);
|
||||
|
||||
if (!competition) {
|
||||
return NextResponse.json({
|
||||
success: false,
|
||||
message: '競賽不存在',
|
||||
error: '找不到指定的競賽'
|
||||
}, { status: 404 });
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
message: '競賽詳情獲取成功',
|
||||
data: competition
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('獲取競賽詳情失敗:', error);
|
||||
return NextResponse.json({
|
||||
success: false,
|
||||
message: '獲取競賽詳情失敗',
|
||||
error: error instanceof Error ? error.message : '未知錯誤'
|
||||
}, { status: 500 });
|
||||
}
|
||||
}
|
122
app/api/connection-monitor/route.ts
Normal file
122
app/api/connection-monitor/route.ts
Normal file
@@ -0,0 +1,122 @@
|
||||
// =====================================================
|
||||
// 連線監控 API
|
||||
// =====================================================
|
||||
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { smartPool } from '@/lib/smart-connection-pool';
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
const { searchParams } = new URL(request.url);
|
||||
const action = searchParams.get('action') || 'stats';
|
||||
|
||||
switch (action) {
|
||||
case 'stats':
|
||||
// 獲取連線統計
|
||||
const stats = smartPool.getConnectionStats();
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
message: '連線統計獲取成功',
|
||||
data: stats
|
||||
});
|
||||
|
||||
case 'cleanup':
|
||||
// 強制清理連線
|
||||
console.log('🧹 執行強制連線清理...');
|
||||
smartPool.forceCleanup();
|
||||
const newStats = smartPool.getConnectionStats();
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
message: '連線清理完成',
|
||||
data: newStats
|
||||
});
|
||||
|
||||
case 'test':
|
||||
// 測試智能連線
|
||||
try {
|
||||
const testResult = await smartPool.executeQueryOne(
|
||||
'SELECT 1 as test_value',
|
||||
[],
|
||||
{ userId: 'test', sessionId: 'test-session', requestId: 'test-request' }
|
||||
);
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
message: '智能連線測試成功',
|
||||
data: {
|
||||
testResult,
|
||||
stats: smartPool.getConnectionStats()
|
||||
}
|
||||
});
|
||||
} catch (error) {
|
||||
return NextResponse.json({
|
||||
success: false,
|
||||
error: '智能連線測試失敗',
|
||||
details: error instanceof Error ? error.message : '未知錯誤'
|
||||
}, { status: 500 });
|
||||
}
|
||||
|
||||
default:
|
||||
return NextResponse.json({
|
||||
success: false,
|
||||
error: '無效的操作參數',
|
||||
availableActions: ['stats', 'cleanup', 'test']
|
||||
}, { status: 400 });
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ 連線監控 API 錯誤:', error);
|
||||
return NextResponse.json({
|
||||
success: false,
|
||||
error: 'API 請求失敗',
|
||||
details: error instanceof Error ? error.message : '未知錯誤'
|
||||
}, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const body = await request.json();
|
||||
const { action, maxIdleTime, maxConnectionAge } = body;
|
||||
|
||||
switch (action) {
|
||||
case 'config':
|
||||
// 更新清理配置
|
||||
smartPool.setCleanupParams(maxIdleTime, maxConnectionAge);
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
message: '清理配置更新成功',
|
||||
data: {
|
||||
maxIdleTime: maxIdleTime || '未變更',
|
||||
maxConnectionAge: maxConnectionAge || '未變更'
|
||||
}
|
||||
});
|
||||
|
||||
case 'cleanup':
|
||||
// 強制清理連線
|
||||
console.log('🧹 執行強制連線清理...');
|
||||
smartPool.forceCleanup();
|
||||
const stats = smartPool.getConnectionStats();
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
message: '連線清理完成',
|
||||
data: stats
|
||||
});
|
||||
|
||||
default:
|
||||
return NextResponse.json({
|
||||
success: false,
|
||||
error: '無效的操作參數',
|
||||
availableActions: ['config', 'cleanup']
|
||||
}, { status: 400 });
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ 連線監控 POST API 錯誤:', error);
|
||||
return NextResponse.json({
|
||||
success: false,
|
||||
error: 'API 請求失敗',
|
||||
details: error instanceof Error ? error.message : '未知錯誤'
|
||||
}, { status: 500 });
|
||||
}
|
||||
}
|
59
app/api/debug-ip/route.ts
Normal file
59
app/api/debug-ip/route.ts
Normal file
@@ -0,0 +1,59 @@
|
||||
// =====================================================
|
||||
// IP 調試 API
|
||||
// =====================================================
|
||||
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { smartIPDetector } from '@/lib/smart-ip-detector';
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
// 使用智能 IP 偵測器
|
||||
const ipDetection = smartIPDetector.detectClientIP(request);
|
||||
|
||||
// 收集所有可能的 IP 信息
|
||||
const ipInfo = {
|
||||
// 智能偵測結果
|
||||
smartDetection: ipDetection,
|
||||
// 請求標頭
|
||||
headers: {
|
||||
'x-forwarded-for': request.headers.get('x-forwarded-for'),
|
||||
'x-real-ip': request.headers.get('x-real-ip'),
|
||||
'cf-connecting-ip': request.headers.get('cf-connecting-ip'),
|
||||
'x-client-ip': request.headers.get('x-client-ip'),
|
||||
'x-forwarded': request.headers.get('x-forwarded'),
|
||||
'x-cluster-client-ip': request.headers.get('x-cluster-client-ip'),
|
||||
'x-original-forwarded-for': request.headers.get('x-original-forwarded-for'),
|
||||
'x-remote-addr': request.headers.get('x-remote-addr'),
|
||||
'remote-addr': request.headers.get('remote-addr'),
|
||||
'client-ip': request.headers.get('client-ip'),
|
||||
'user-agent': request.headers.get('user-agent'),
|
||||
'host': request.headers.get('host'),
|
||||
},
|
||||
// NextRequest 的 IP
|
||||
nextRequestIP: request.ip,
|
||||
// 環境變數
|
||||
env: {
|
||||
NODE_ENV: process.env.NODE_ENV,
|
||||
VERCEL: process.env.VERCEL,
|
||||
VERCEL_REGION: process.env.VERCEL_REGION,
|
||||
},
|
||||
// 所有標頭(用於調試)
|
||||
allHeaders: Object.fromEntries(request.headers.entries()),
|
||||
};
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
message: 'IP 調試信息獲取成功',
|
||||
data: ipInfo,
|
||||
timestamp: new Date().toISOString()
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ IP 調試 API 錯誤:', error);
|
||||
return NextResponse.json({
|
||||
success: false,
|
||||
error: 'IP 調試失敗',
|
||||
details: error instanceof Error ? error.message : '未知錯誤'
|
||||
}, { status: 500 });
|
||||
}
|
||||
}
|
104
app/api/emergency-cleanup/route.ts
Normal file
104
app/api/emergency-cleanup/route.ts
Normal file
@@ -0,0 +1,104 @@
|
||||
// =====================================================
|
||||
// 緊急連線清理 API
|
||||
// =====================================================
|
||||
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { emergencyCleanup } from '@/lib/emergency-connection-cleanup';
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const body = await request.json();
|
||||
const { action } = body;
|
||||
|
||||
switch (action) {
|
||||
case 'cleanup':
|
||||
// 執行緊急清理
|
||||
console.log('🚨 收到緊急清理請求');
|
||||
await emergencyCleanup.emergencyCleanup();
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
message: '緊急清理完成',
|
||||
timestamp: new Date().toISOString()
|
||||
});
|
||||
|
||||
case 'kill-all':
|
||||
// 強制殺死所有連線
|
||||
console.log('💀 收到強制殺死連線請求');
|
||||
await emergencyCleanup.forceKillAllConnections();
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
message: '強制殺死連線完成',
|
||||
timestamp: new Date().toISOString()
|
||||
});
|
||||
|
||||
case 'details':
|
||||
// 獲取連線詳情
|
||||
const connections = await emergencyCleanup.getConnectionDetails();
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
message: '連線詳情獲取成功',
|
||||
data: {
|
||||
connectionCount: connections.length,
|
||||
connections: connections
|
||||
},
|
||||
timestamp: new Date().toISOString()
|
||||
});
|
||||
|
||||
default:
|
||||
return NextResponse.json({
|
||||
success: false,
|
||||
error: '無效的操作參數',
|
||||
availableActions: ['cleanup', 'kill-all', 'details']
|
||||
}, { status: 400 });
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ 緊急清理 API 錯誤:', error);
|
||||
return NextResponse.json({
|
||||
success: false,
|
||||
error: '緊急清理失敗',
|
||||
details: error instanceof Error ? error.message : '未知錯誤'
|
||||
}, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
const { searchParams } = new URL(request.url);
|
||||
const action = searchParams.get('action') || 'details';
|
||||
|
||||
switch (action) {
|
||||
case 'details':
|
||||
// 獲取連線詳情
|
||||
const connections = await emergencyCleanup.getConnectionDetails();
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
message: '連線詳情獲取成功',
|
||||
data: {
|
||||
connectionCount: connections.length,
|
||||
connections: connections
|
||||
},
|
||||
timestamp: new Date().toISOString()
|
||||
});
|
||||
|
||||
default:
|
||||
return NextResponse.json({
|
||||
success: false,
|
||||
error: '無效的操作參數',
|
||||
availableActions: ['details']
|
||||
}, { status: 400 });
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ 緊急清理 GET API 錯誤:', error);
|
||||
return NextResponse.json({
|
||||
success: false,
|
||||
error: '獲取連線詳情失敗',
|
||||
details: error instanceof Error ? error.message : '未知錯誤'
|
||||
}, { status: 500 });
|
||||
}
|
||||
}
|
177
app/api/ip-cleanup/route.ts
Normal file
177
app/api/ip-cleanup/route.ts
Normal file
@@ -0,0 +1,177 @@
|
||||
// =====================================================
|
||||
// 基於 IP 的連線清理 API
|
||||
// =====================================================
|
||||
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { smartIPPool } from '@/lib/smart-ip-connection-pool';
|
||||
import { smartIPDetector } from '@/lib/smart-ip-detector';
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const body = await request.json();
|
||||
const { action, targetIP } = body;
|
||||
// 使用智能 IP 偵測器
|
||||
const ipDetection = smartIPDetector.detectClientIP(request);
|
||||
const clientIP = ipDetection.detectedIP;
|
||||
|
||||
console.log('🎯 智能 IP 偵測結果:', {
|
||||
detectedIP: clientIP,
|
||||
confidence: ipDetection.confidence,
|
||||
source: ipDetection.source,
|
||||
isPublicIP: ipDetection.isPublicIP,
|
||||
allCandidates: ipDetection.allCandidates
|
||||
});
|
||||
|
||||
// 設置客戶端 IP
|
||||
smartIPPool.setClientIP(clientIP);
|
||||
|
||||
switch (action) {
|
||||
case 'cleanup-current':
|
||||
// 清理當前 IP 的連線
|
||||
console.log(`🧹 收到清理當前 IP 連線請求: ${clientIP}`);
|
||||
const cleanupResult = await smartIPPool.cleanupCurrentIPConnections();
|
||||
|
||||
return NextResponse.json({
|
||||
success: cleanupResult.success,
|
||||
message: cleanupResult.message,
|
||||
data: {
|
||||
clientIP,
|
||||
killedCount: cleanupResult.killedCount
|
||||
},
|
||||
timestamp: new Date().toISOString()
|
||||
});
|
||||
|
||||
case 'cleanup-specific':
|
||||
// 清理指定 IP 的連線
|
||||
if (!targetIP) {
|
||||
return NextResponse.json({
|
||||
success: false,
|
||||
error: '缺少目標 IP 參數'
|
||||
}, { status: 400 });
|
||||
}
|
||||
|
||||
console.log(`🧹 收到清理指定 IP 連線請求: ${targetIP}`);
|
||||
const specificCleanupResult = await smartIPPool.cleanupIPConnections(targetIP);
|
||||
|
||||
return NextResponse.json({
|
||||
success: specificCleanupResult.success,
|
||||
message: specificCleanupResult.message,
|
||||
data: {
|
||||
targetIP,
|
||||
killedCount: specificCleanupResult.killedCount
|
||||
},
|
||||
timestamp: new Date().toISOString()
|
||||
});
|
||||
|
||||
case 'cleanup-local':
|
||||
// 清理本地追蹤的連線
|
||||
console.log('🧹 收到清理本地連線請求');
|
||||
const localCleanupCount = smartIPPool.cleanupLocalConnections();
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
message: `已清理 ${localCleanupCount} 個本地追蹤的連線`,
|
||||
data: {
|
||||
clientIP,
|
||||
cleanedCount: localCleanupCount
|
||||
},
|
||||
timestamp: new Date().toISOString()
|
||||
});
|
||||
|
||||
default:
|
||||
return NextResponse.json({
|
||||
success: false,
|
||||
error: '無效的操作參數',
|
||||
availableActions: ['cleanup-current', 'cleanup-specific', 'cleanup-local']
|
||||
}, { status: 400 });
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ IP 清理 API 錯誤:', error);
|
||||
return NextResponse.json({
|
||||
success: false,
|
||||
error: 'IP 清理失敗',
|
||||
details: error instanceof Error ? error.message : '未知錯誤'
|
||||
}, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
const { searchParams } = new URL(request.url);
|
||||
const action = searchParams.get('action') || 'status';
|
||||
const targetIP = searchParams.get('ip');
|
||||
// 使用智能 IP 偵測器
|
||||
const ipDetection = smartIPDetector.detectClientIP(request);
|
||||
const clientIP = ipDetection.detectedIP;
|
||||
|
||||
// 設置客戶端 IP
|
||||
smartIPPool.setClientIP(clientIP);
|
||||
|
||||
switch (action) {
|
||||
case 'status':
|
||||
// 獲取當前 IP 的連線狀態
|
||||
const currentIPStatus = await smartIPPool.getCurrentIPConnections();
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
message: '連線狀態獲取成功',
|
||||
data: {
|
||||
detectedIP: clientIP,
|
||||
...currentIPStatus
|
||||
},
|
||||
timestamp: new Date().toISOString()
|
||||
});
|
||||
|
||||
case 'status-specific':
|
||||
// 獲取指定 IP 的連線狀態
|
||||
if (!targetIP) {
|
||||
return NextResponse.json({
|
||||
success: false,
|
||||
error: '缺少目標 IP 參數'
|
||||
}, { status: 400 });
|
||||
}
|
||||
|
||||
const specificIPStatus = await smartIPPool.getIPConnections(targetIP);
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
message: '指定 IP 連線狀態獲取成功',
|
||||
data: {
|
||||
targetIP,
|
||||
...specificIPStatus
|
||||
},
|
||||
timestamp: new Date().toISOString()
|
||||
});
|
||||
|
||||
case 'local-stats':
|
||||
// 獲取本地連線統計
|
||||
const localStats = smartIPPool.getLocalConnectionStats();
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
message: '本地連線統計獲取成功',
|
||||
data: {
|
||||
detectedIP: clientIP,
|
||||
...localStats
|
||||
},
|
||||
timestamp: new Date().toISOString()
|
||||
});
|
||||
|
||||
default:
|
||||
return NextResponse.json({
|
||||
success: false,
|
||||
error: '無效的操作參數',
|
||||
availableActions: ['status', 'status-specific', 'local-stats']
|
||||
}, { status: 400 });
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ IP 清理 GET API 錯誤:', error);
|
||||
return NextResponse.json({
|
||||
success: false,
|
||||
error: '獲取連線狀態失敗',
|
||||
details: error instanceof Error ? error.message : '未知錯誤'
|
||||
}, { status: 500 });
|
||||
}
|
||||
}
|
78
app/api/set-client-ip/route.ts
Normal file
78
app/api/set-client-ip/route.ts
Normal file
@@ -0,0 +1,78 @@
|
||||
// =====================================================
|
||||
// 手動設置客戶端 IP API
|
||||
// =====================================================
|
||||
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { smartIPPool } from '@/lib/smart-ip-connection-pool';
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const body = await request.json();
|
||||
const { clientIP } = body;
|
||||
|
||||
if (!clientIP) {
|
||||
return NextResponse.json({
|
||||
success: false,
|
||||
error: '缺少客戶端 IP 參數'
|
||||
}, { status: 400 });
|
||||
}
|
||||
|
||||
console.log('🔧 手動設置客戶端 IP:', clientIP);
|
||||
|
||||
// 設置客戶端 IP
|
||||
smartIPPool.setClientIP(clientIP);
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
message: `客戶端 IP 已設置為: ${clientIP}`,
|
||||
data: {
|
||||
clientIP,
|
||||
timestamp: new Date().toISOString()
|
||||
}
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ 設置客戶端 IP 失敗:', error);
|
||||
return NextResponse.json({
|
||||
success: false,
|
||||
error: '設置客戶端 IP 失敗',
|
||||
details: error instanceof Error ? error.message : '未知錯誤'
|
||||
}, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
const { searchParams } = new URL(request.url);
|
||||
const clientIP = searchParams.get('ip');
|
||||
|
||||
if (!clientIP) {
|
||||
return NextResponse.json({
|
||||
success: false,
|
||||
error: '缺少 IP 參數'
|
||||
}, { status: 400 });
|
||||
}
|
||||
|
||||
console.log('🔧 通過 GET 設置客戶端 IP:', clientIP);
|
||||
|
||||
// 設置客戶端 IP
|
||||
smartIPPool.setClientIP(clientIP);
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
message: `客戶端 IP 已設置為: ${clientIP}`,
|
||||
data: {
|
||||
clientIP,
|
||||
timestamp: new Date().toISOString()
|
||||
}
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ 設置客戶端 IP 失敗:', error);
|
||||
return NextResponse.json({
|
||||
success: false,
|
||||
error: '設置客戶端 IP 失敗',
|
||||
details: error instanceof Error ? error.message : '未知錯誤'
|
||||
}, { status: 500 });
|
||||
}
|
||||
}
|
100
app/api/test-shutdown/route.ts
Normal file
100
app/api/test-shutdown/route.ts
Normal file
@@ -0,0 +1,100 @@
|
||||
// =====================================================
|
||||
// 測試資料庫關閉機制 API
|
||||
// =====================================================
|
||||
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { dbShutdownManager } from '@/lib/database-shutdown-manager';
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
const { searchParams } = new URL(request.url);
|
||||
const action = searchParams.get('action') || 'status';
|
||||
|
||||
switch (action) {
|
||||
case 'status':
|
||||
// 獲取關閉狀態
|
||||
const status = dbShutdownManager.getShutdownStatus();
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
message: '關閉狀態查詢成功',
|
||||
data: status
|
||||
});
|
||||
|
||||
case 'test':
|
||||
// 測試關閉機制(不會真的關閉)
|
||||
console.log('🧪 測試關閉機制...');
|
||||
const testStatus = dbShutdownManager.getShutdownStatus();
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
message: '關閉機制測試成功',
|
||||
data: {
|
||||
...testStatus,
|
||||
testTime: new Date().toISOString()
|
||||
}
|
||||
});
|
||||
|
||||
case 'force':
|
||||
// 強制關閉(僅用於測試)
|
||||
console.log('🚨 執行強制關閉測試...');
|
||||
dbShutdownManager.forceShutdown();
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
message: '強制關閉測試完成',
|
||||
data: {
|
||||
timestamp: new Date().toISOString()
|
||||
}
|
||||
});
|
||||
|
||||
default:
|
||||
return NextResponse.json({
|
||||
success: false,
|
||||
error: '無效的操作參數',
|
||||
availableActions: ['status', 'test', 'force']
|
||||
}, { status: 400 });
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ 測試關閉機制時發生錯誤:', error);
|
||||
return NextResponse.json({
|
||||
success: false,
|
||||
error: '測試失敗',
|
||||
details: error instanceof Error ? error.message : '未知錯誤'
|
||||
}, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const body = await request.json();
|
||||
const { action } = body;
|
||||
|
||||
switch (action) {
|
||||
case 'graceful':
|
||||
// 優雅關閉(僅用於測試)
|
||||
console.log('🔄 執行優雅關閉測試...');
|
||||
await dbShutdownManager.gracefulShutdown();
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
message: '優雅關閉測試完成',
|
||||
data: {
|
||||
timestamp: new Date().toISOString()
|
||||
}
|
||||
});
|
||||
|
||||
default:
|
||||
return NextResponse.json({
|
||||
success: false,
|
||||
error: '無效的操作參數',
|
||||
availableActions: ['graceful']
|
||||
}, { status: 400 });
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ 執行關閉測試時發生錯誤:', error);
|
||||
return NextResponse.json({
|
||||
success: false,
|
||||
error: '關閉測試失敗',
|
||||
details: error instanceof Error ? error.message : '未知錯誤'
|
||||
}, { status: 500 });
|
||||
}
|
||||
}
|
96
app/api/ultimate-kill/route.ts
Normal file
96
app/api/ultimate-kill/route.ts
Normal file
@@ -0,0 +1,96 @@
|
||||
// =====================================================
|
||||
// 終極連線清理 API
|
||||
// =====================================================
|
||||
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { ultimateKiller } from '@/lib/ultimate-connection-killer';
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const body = await request.json();
|
||||
const { action } = body;
|
||||
|
||||
switch (action) {
|
||||
case 'kill-all':
|
||||
// 終極清理 - 殺死所有連線
|
||||
console.log('💀 收到終極清理請求');
|
||||
const killResult = await ultimateKiller.ultimateKill();
|
||||
|
||||
return NextResponse.json({
|
||||
success: killResult.success,
|
||||
message: killResult.message || '終極清理完成',
|
||||
data: killResult,
|
||||
timestamp: new Date().toISOString()
|
||||
});
|
||||
|
||||
case 'restart':
|
||||
// 強制重啟資料庫連線
|
||||
console.log('🔄 收到強制重啟請求');
|
||||
const restartResult = await ultimateKiller.forceRestart();
|
||||
|
||||
return NextResponse.json({
|
||||
success: restartResult.success,
|
||||
message: restartResult.message || '強制重啟完成',
|
||||
data: restartResult,
|
||||
timestamp: new Date().toISOString()
|
||||
});
|
||||
|
||||
default:
|
||||
return NextResponse.json({
|
||||
success: false,
|
||||
error: '無效的操作參數',
|
||||
availableActions: ['kill-all', 'restart']
|
||||
}, { status: 400 });
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ 終極清理 API 錯誤:', error);
|
||||
return NextResponse.json({
|
||||
success: false,
|
||||
error: '終極清理失敗',
|
||||
details: error instanceof Error ? error.message : '未知錯誤'
|
||||
}, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
const { searchParams } = new URL(request.url);
|
||||
const action = searchParams.get('action') || 'status';
|
||||
|
||||
switch (action) {
|
||||
case 'status':
|
||||
// 檢查連線狀態
|
||||
const status = await ultimateKiller.checkStatus();
|
||||
|
||||
if (status) {
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
message: '連線狀態獲取成功',
|
||||
data: status,
|
||||
timestamp: new Date().toISOString()
|
||||
});
|
||||
} else {
|
||||
return NextResponse.json({
|
||||
success: false,
|
||||
error: '無法獲取連線狀態'
|
||||
}, { status: 500 });
|
||||
}
|
||||
|
||||
default:
|
||||
return NextResponse.json({
|
||||
success: false,
|
||||
error: '無效的操作參數',
|
||||
availableActions: ['status']
|
||||
}, { status: 400 });
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ 終極清理 GET API 錯誤:', error);
|
||||
return NextResponse.json({
|
||||
success: false,
|
||||
error: '獲取連線狀態失敗',
|
||||
details: error instanceof Error ? error.message : '未知錯誤'
|
||||
}, { status: 500 });
|
||||
}
|
||||
}
|
297
app/auto-ip-test/page.tsx
Normal file
297
app/auto-ip-test/page.tsx
Normal file
@@ -0,0 +1,297 @@
|
||||
'use client';
|
||||
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||
import { Loader2, Database, CheckCircle, AlertTriangle, RefreshCw, Trash2 } from 'lucide-react';
|
||||
|
||||
interface IPDetectionResult {
|
||||
detectedIP: string;
|
||||
confidence: 'high' | 'medium' | 'low';
|
||||
source: string;
|
||||
isPublicIP: boolean;
|
||||
allCandidates: string[];
|
||||
}
|
||||
|
||||
interface ConnectionStatus {
|
||||
ip: string;
|
||||
connectionCount: number;
|
||||
connections: any[];
|
||||
}
|
||||
|
||||
export default function AutoIPTestPage() {
|
||||
const [ipDetection, setIpDetection] = useState<IPDetectionResult | null>(null);
|
||||
const [connectionStatus, setConnectionStatus] = useState<ConnectionStatus | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [message, setMessage] = useState<string>('');
|
||||
const [error, setError] = useState<string>('');
|
||||
|
||||
// 自動偵測 IP
|
||||
const detectIP = async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
const response = await fetch('/api/debug-ip');
|
||||
const data = await response.json();
|
||||
|
||||
if (data.success && data.data.smartDetection) {
|
||||
setIpDetection(data.data.smartDetection);
|
||||
setMessage(`IP 偵測成功: ${data.data.smartDetection.detectedIP}`);
|
||||
setError('');
|
||||
} else {
|
||||
setError('IP 偵測失敗');
|
||||
}
|
||||
} catch (err) {
|
||||
setError('IP 偵測錯誤: ' + (err instanceof Error ? err.message : '未知錯誤'));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// 獲取連線狀態
|
||||
const getConnectionStatus = async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
const response = await fetch('/api/ip-cleanup?action=status');
|
||||
const data = await response.json();
|
||||
|
||||
if (data.success) {
|
||||
setConnectionStatus(data.data);
|
||||
setMessage(`連線狀態獲取成功: ${data.data.connectionCount} 個連線`);
|
||||
setError('');
|
||||
} else {
|
||||
setError('獲取連線狀態失敗');
|
||||
}
|
||||
} catch (err) {
|
||||
setError('獲取連線狀態錯誤: ' + (err instanceof Error ? err.message : '未知錯誤'));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// 清理當前 IP 連線
|
||||
const cleanupConnections = async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
const response = await fetch('/api/ip-cleanup', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({ action: 'cleanup-current' }),
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (data.success) {
|
||||
setMessage(`清理成功: ${data.message}`);
|
||||
setError('');
|
||||
// 重新獲取連線狀態
|
||||
await getConnectionStatus();
|
||||
} else {
|
||||
setError(data.error || '清理失敗');
|
||||
}
|
||||
} catch (err) {
|
||||
setError('清理錯誤: ' + (err instanceof Error ? err.message : '未知錯誤'));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// 組件載入時自動偵測
|
||||
useEffect(() => {
|
||||
detectIP();
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className="container mx-auto p-6 space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold">自動 IP 偵測測試</h1>
|
||||
<p className="text-muted-foreground">
|
||||
測試智能 IP 偵測和自動連線清理功能
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
onClick={detectIP}
|
||||
disabled={loading}
|
||||
variant="outline"
|
||||
>
|
||||
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <RefreshCw className="h-4 w-4" />}
|
||||
偵測 IP
|
||||
</Button>
|
||||
<Button
|
||||
onClick={getConnectionStatus}
|
||||
disabled={loading}
|
||||
variant="outline"
|
||||
>
|
||||
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <Database className="h-4 w-4" />}
|
||||
檢查連線
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* IP 偵測結果 */}
|
||||
{ipDetection && (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<CheckCircle className="h-5 w-5" />
|
||||
智能 IP 偵測結果
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
系統自動偵測到的客戶端 IP 地址
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="flex items-center gap-4">
|
||||
<Badge
|
||||
variant={ipDetection.isPublicIP ? "default" : "secondary"}
|
||||
className="text-lg px-3 py-1"
|
||||
>
|
||||
{ipDetection.detectedIP}
|
||||
</Badge>
|
||||
<Badge
|
||||
variant={
|
||||
ipDetection.confidence === 'high' ? "default" :
|
||||
ipDetection.confidence === 'medium' ? "secondary" : "destructive"
|
||||
}
|
||||
className="text-lg px-3 py-1"
|
||||
>
|
||||
可信度: {ipDetection.confidence}
|
||||
</Badge>
|
||||
<Badge variant="outline" className="text-lg px-3 py-1">
|
||||
來源: {ipDetection.source}
|
||||
</Badge>
|
||||
</div>
|
||||
|
||||
{ipDetection.allCandidates.length > 1 && (
|
||||
<div>
|
||||
<p className="text-sm font-medium mb-2">所有候選 IP:</p>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{ipDetection.allCandidates.map((ip, index) => (
|
||||
<Badge
|
||||
key={index}
|
||||
variant={ip === ipDetection.detectedIP ? "default" : "outline"}
|
||||
className="text-sm"
|
||||
>
|
||||
{ip}
|
||||
</Badge>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* 連線狀態 */}
|
||||
{connectionStatus && (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Database className="h-5 w-5" />
|
||||
連線狀態
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
當前 IP 的資料庫連線狀態
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="flex items-center gap-4">
|
||||
<Badge variant="default" className="text-lg px-3 py-1">
|
||||
IP: {connectionStatus.ip}
|
||||
</Badge>
|
||||
<Badge
|
||||
variant={connectionStatus.connectionCount > 0 ? "destructive" : "default"}
|
||||
className="text-lg px-3 py-1"
|
||||
>
|
||||
連線數: {connectionStatus.connectionCount}
|
||||
</Badge>
|
||||
</div>
|
||||
|
||||
{connectionStatus.connections.length > 0 && (
|
||||
<div>
|
||||
<p className="text-sm font-medium mb-2">連線詳情:</p>
|
||||
<div className="space-y-2 max-h-48 overflow-y-auto">
|
||||
{connectionStatus.connections.map((conn, index) => (
|
||||
<div key={index} className="flex items-center justify-between p-2 border rounded text-sm">
|
||||
<span>ID: {conn.ID}</span>
|
||||
<span>HOST: {conn.HOST}</span>
|
||||
<span>時間: {conn.TIME}s</span>
|
||||
<span>狀態: {conn.STATE || 'Sleep'}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* 操作按鈕 */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>操作</CardTitle>
|
||||
<CardDescription>
|
||||
測試自動 IP 偵測和連線清理功能
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="flex gap-4">
|
||||
<Button
|
||||
onClick={cleanupConnections}
|
||||
disabled={loading || !ipDetection}
|
||||
variant="destructive"
|
||||
className="flex-1"
|
||||
>
|
||||
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <Trash2 className="h-4 w-4" />}
|
||||
清理我的連線
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
onClick={getConnectionStatus}
|
||||
disabled={loading}
|
||||
variant="outline"
|
||||
className="flex-1"
|
||||
>
|
||||
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <RefreshCw className="h-4 w-4" />}
|
||||
重新檢查
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* 使用說明 */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>使用說明</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-2 text-sm text-muted-foreground">
|
||||
<p>• <strong>自動偵測:</strong> 頁面載入時會自動偵測你的 IP 地址</p>
|
||||
<p>• <strong>智能算法:</strong> 使用多種方法偵測最準確的 IP 地址</p>
|
||||
<p>• <strong>連線檢查:</strong> 檢查你的 IP 在資料庫中的連線狀態</p>
|
||||
<p>• <strong>自動清理:</strong> 點擊「清理我的連線」來清理你的 IP 連線</p>
|
||||
<p>• <strong>關閉頁面:</strong> 關閉此頁面時會自動觸發連線清理</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* 訊息顯示 */}
|
||||
{message && (
|
||||
<Alert>
|
||||
<CheckCircle className="h-4 w-4" />
|
||||
<AlertDescription>{message}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{error && (
|
||||
<Alert variant="destructive">
|
||||
<AlertTriangle className="h-4 w-4" />
|
||||
<AlertDescription>{error}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
325
app/debug-ip/page.tsx
Normal file
325
app/debug-ip/page.tsx
Normal file
@@ -0,0 +1,325 @@
|
||||
'use client';
|
||||
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||
import { Loader2, Database, Eye, RefreshCw } from 'lucide-react';
|
||||
|
||||
interface IPInfo {
|
||||
smartDetection?: {
|
||||
detectedIP: string;
|
||||
confidence: 'high' | 'medium' | 'low';
|
||||
source: string;
|
||||
allCandidates: string[];
|
||||
isPublicIP: boolean;
|
||||
};
|
||||
headers: Record<string, string | null>;
|
||||
nextRequestIP: string | undefined;
|
||||
env: Record<string, string | undefined>;
|
||||
allHeaders: Record<string, string>;
|
||||
}
|
||||
|
||||
export default function DebugIPPage() {
|
||||
const [ipInfo, setIpInfo] = useState<IPInfo | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [message, setMessage] = useState<string>('');
|
||||
const [error, setError] = useState<string>('');
|
||||
const [recommendedIP, setRecommendedIP] = useState<string>('');
|
||||
|
||||
// 獲取 IP 調試信息
|
||||
const fetchIPInfo = async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
const response = await fetch('/api/debug-ip');
|
||||
const data = await response.json();
|
||||
|
||||
if (data.success) {
|
||||
setIpInfo(data.data);
|
||||
|
||||
// 提取智能偵測結果
|
||||
if (data.data.smartDetection) {
|
||||
const smartDetection = data.data.smartDetection;
|
||||
setRecommendedIP(smartDetection.detectedIP);
|
||||
setMessage(`智能偵測結果: ${smartDetection.detectedIP} (可信度: ${smartDetection.confidence}, 來源: ${smartDetection.source})`);
|
||||
} else {
|
||||
setMessage('IP 調試信息更新成功');
|
||||
}
|
||||
setError('');
|
||||
} else {
|
||||
setError(data.error || '獲取 IP 調試信息失敗');
|
||||
}
|
||||
} catch (err) {
|
||||
setError('網路錯誤: ' + (err instanceof Error ? err.message : '未知錯誤'));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// 組件載入時獲取 IP 信息
|
||||
useEffect(() => {
|
||||
fetchIPInfo();
|
||||
}, []);
|
||||
|
||||
// 獲取推薦的 IP
|
||||
const getRecommendedIP = () => {
|
||||
if (!ipInfo) return 'unknown';
|
||||
|
||||
// 優先使用智能偵測結果
|
||||
if (ipInfo.smartDetection) {
|
||||
return ipInfo.smartDetection.detectedIP;
|
||||
}
|
||||
|
||||
// 回退到舊的邏輯
|
||||
const { headers, nextRequestIP } = ipInfo;
|
||||
|
||||
// 優先順序檢查
|
||||
if (headers['cf-connecting-ip']) return headers['cf-connecting-ip'];
|
||||
if (headers['x-real-ip']) return headers['x-real-ip'];
|
||||
if (headers['x-client-ip']) return headers['x-client-ip'];
|
||||
if (headers['x-cluster-client-ip']) return headers['x-cluster-client-ip'];
|
||||
if (headers['x-forwarded']) return headers['x-forwarded'];
|
||||
if (headers['x-forwarded-for']) {
|
||||
const ips = headers['x-forwarded-for']!.split(',').map(ip => ip.trim());
|
||||
const publicIPs = ips.filter(ip =>
|
||||
ip &&
|
||||
ip !== '127.0.0.1' &&
|
||||
ip !== '::1' &&
|
||||
!ip.startsWith('192.168.') &&
|
||||
!ip.startsWith('10.') &&
|
||||
!ip.startsWith('172.')
|
||||
);
|
||||
if (publicIPs.length > 0) return publicIPs[0];
|
||||
return ips[0];
|
||||
}
|
||||
if (nextRequestIP && nextRequestIP !== '::1' && nextRequestIP !== '127.0.0.1') {
|
||||
return nextRequestIP;
|
||||
}
|
||||
|
||||
return 'unknown';
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="container mx-auto p-6 space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold">IP 調試工具</h1>
|
||||
<p className="text-muted-foreground">
|
||||
調試和檢查客戶端 IP 地址獲取
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
onClick={fetchIPInfo}
|
||||
disabled={loading}
|
||||
variant="outline"
|
||||
>
|
||||
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <RefreshCw className="h-4 w-4" />}
|
||||
重新整理
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* 智能偵測結果 */}
|
||||
{ipInfo?.smartDetection && (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Eye className="h-5 w-5" />
|
||||
智能 IP 偵測結果
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
使用智能算法偵測的客戶端 IP 地址
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="flex items-center gap-4">
|
||||
<Badge
|
||||
variant={ipInfo.smartDetection.isPublicIP ? "default" : "secondary"}
|
||||
className="text-lg px-3 py-1"
|
||||
>
|
||||
{ipInfo.smartDetection.detectedIP}
|
||||
</Badge>
|
||||
<Badge
|
||||
variant={
|
||||
ipInfo.smartDetection.confidence === 'high' ? "default" :
|
||||
ipInfo.smartDetection.confidence === 'medium' ? "secondary" : "destructive"
|
||||
}
|
||||
className="text-lg px-3 py-1"
|
||||
>
|
||||
可信度: {ipInfo.smartDetection.confidence}
|
||||
</Badge>
|
||||
<Badge variant="outline" className="text-lg px-3 py-1">
|
||||
來源: {ipInfo.smartDetection.source}
|
||||
</Badge>
|
||||
</div>
|
||||
|
||||
{ipInfo.smartDetection.allCandidates.length > 1 && (
|
||||
<div>
|
||||
<p className="text-sm font-medium mb-2">所有候選 IP:</p>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{ipInfo.smartDetection.allCandidates.map((ip, index) => (
|
||||
<Badge
|
||||
key={index}
|
||||
variant={ip === ipInfo.smartDetection.detectedIP ? "default" : "outline"}
|
||||
className="text-sm"
|
||||
>
|
||||
{ip}
|
||||
</Badge>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* 推薦的 IP (回退顯示) */}
|
||||
{ipInfo && !ipInfo.smartDetection && (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Eye className="h-5 w-5" />
|
||||
推薦的 IP 地址
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
系統推薦使用的客戶端 IP 地址
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="flex items-center gap-4">
|
||||
<Badge variant="default" className="text-lg px-3 py-1">
|
||||
{getRecommendedIP()}
|
||||
</Badge>
|
||||
<Badge
|
||||
variant={getRecommendedIP() === 'unknown' ? "destructive" : "default"}
|
||||
className="text-lg px-3 py-1"
|
||||
>
|
||||
狀態: {getRecommendedIP() === 'unknown' ? "無法識別" : "已識別"}
|
||||
</Badge>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* 請求標頭 */}
|
||||
{ipInfo && (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>請求標頭</CardTitle>
|
||||
<CardDescription>
|
||||
從 HTTP 請求標頭中獲取的 IP 相關信息
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-2">
|
||||
{Object.entries(ipInfo.headers).map(([key, value]) => (
|
||||
<div key={key} className="flex items-center justify-between p-2 border rounded">
|
||||
<span className="font-medium text-sm">{key}:</span>
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{value || 'null'}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* NextRequest IP */}
|
||||
{ipInfo && (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>NextRequest IP</CardTitle>
|
||||
<CardDescription>
|
||||
Next.js 框架提供的 IP 地址
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="flex items-center gap-4">
|
||||
<Badge variant="outline" className="text-lg px-3 py-1">
|
||||
{ipInfo.nextRequestIP || 'undefined'}
|
||||
</Badge>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* 環境信息 */}
|
||||
{ipInfo && (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>環境信息</CardTitle>
|
||||
<CardDescription>
|
||||
部署環境相關信息
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-2">
|
||||
{Object.entries(ipInfo.env).map(([key, value]) => (
|
||||
<div key={key} className="flex items-center justify-between p-2 border rounded">
|
||||
<span className="font-medium text-sm">{key}:</span>
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{value || 'undefined'}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* 所有標頭(用於調試) */}
|
||||
{ipInfo && (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>所有請求標頭</CardTitle>
|
||||
<CardDescription>
|
||||
完整的 HTTP 請求標頭信息
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-2 max-h-96 overflow-y-auto">
|
||||
{Object.entries(ipInfo.allHeaders).map(([key, value]) => (
|
||||
<div key={key} className="flex items-center justify-between p-2 border rounded text-xs">
|
||||
<span className="font-medium">{key}:</span>
|
||||
<span className="text-muted-foreground break-all">
|
||||
{value}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* 訊息顯示 */}
|
||||
{message && (
|
||||
<Alert>
|
||||
<Database className="h-4 w-4" />
|
||||
<AlertDescription>{message}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{error && (
|
||||
<Alert variant="destructive">
|
||||
<Eye className="h-4 w-4" />
|
||||
<AlertDescription>{error}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{/* 使用說明 */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>使用說明</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-2 text-sm text-muted-foreground">
|
||||
<p>• <strong>推薦的 IP:</strong> 系統根據優先順序推薦使用的 IP 地址</p>
|
||||
<p>• <strong>請求標頭:</strong> 檢查各種代理和負載均衡器設置的 IP 標頭</p>
|
||||
<p>• <strong>NextRequest IP:</strong> Next.js 框架直接提供的 IP 地址</p>
|
||||
<p>• <strong>環境信息:</strong> 部署環境相關的配置信息</p>
|
||||
<p>• 如果推薦的 IP 是 "unknown",請檢查代理設置或網路配置</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
@@ -5,6 +5,8 @@ import { AuthProvider } from "@/contexts/auth-context"
|
||||
import { CompetitionProvider } from "@/contexts/competition-context"
|
||||
import { Toaster } from "@/components/ui/toaster"
|
||||
import { ChatBot } from "@/components/chat-bot"
|
||||
import { ClientConnectionCleanup } from "@/components/client-connection-cleanup"
|
||||
import "@/lib/app-initializer" // 自動初始化應用程式
|
||||
|
||||
const inter = Inter({ subsets: ["latin"] })
|
||||
|
||||
@@ -28,6 +30,7 @@ export default function RootLayout({
|
||||
{children}
|
||||
<Toaster />
|
||||
<ChatBot />
|
||||
<ClientConnectionCleanup />
|
||||
</CompetitionProvider>
|
||||
</AuthProvider>
|
||||
</body>
|
||||
|
174
app/set-ip/page.tsx
Normal file
174
app/set-ip/page.tsx
Normal file
@@ -0,0 +1,174 @@
|
||||
'use client';
|
||||
|
||||
import React, { useState } from 'react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||
import { Loader2, Database, CheckCircle, AlertTriangle } from 'lucide-react';
|
||||
|
||||
export default function SetIPPage() {
|
||||
const [clientIP, setClientIP] = useState('61-227-253-171');
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [message, setMessage] = useState<string>('');
|
||||
const [error, setError] = useState<string>('');
|
||||
|
||||
// 設置客戶端 IP
|
||||
const setClientIP = async () => {
|
||||
if (!clientIP.trim()) {
|
||||
setError('請輸入客戶端 IP 地址');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
setLoading(true);
|
||||
const response = await fetch('/api/set-client-ip', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({ clientIP: clientIP.trim() }),
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (data.success) {
|
||||
setMessage(data.message || '客戶端 IP 設置成功');
|
||||
setError('');
|
||||
} else {
|
||||
setError(data.error || '設置客戶端 IP 失敗');
|
||||
}
|
||||
} catch (err) {
|
||||
setError('設置錯誤: ' + (err instanceof Error ? err.message : '未知錯誤'));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// 快速設置你的 IP
|
||||
const setYourIP = () => {
|
||||
setClientIP('61-227-253-171');
|
||||
};
|
||||
|
||||
// 測試清理功能
|
||||
const testCleanup = async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
const response = await fetch('/api/ip-cleanup', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({ action: 'cleanup-current' }),
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (data.success) {
|
||||
setMessage(`清理完成: ${data.message}`);
|
||||
setError('');
|
||||
} else {
|
||||
setError(data.error || '清理失敗');
|
||||
}
|
||||
} catch (err) {
|
||||
setError('清理錯誤: ' + (err instanceof Error ? err.message : '未知錯誤'));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="container mx-auto p-6 space-y-6">
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold">設置客戶端 IP</h1>
|
||||
<p className="text-muted-foreground">
|
||||
手動設置你的真實 IP 地址,用於連線清理
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* IP 設置 */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Database className="h-5 w-5" />
|
||||
設置客戶端 IP
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
輸入你的真實 IP 地址,系統將使用此 IP 來清理連線
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="clientIP">客戶端 IP 地址</Label>
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
id="clientIP"
|
||||
value={clientIP}
|
||||
onChange={(e) => setClientIP(e.target.value)}
|
||||
placeholder="例如: 61-227-253-171"
|
||||
className="flex-1"
|
||||
/>
|
||||
<Button
|
||||
onClick={setYourIP}
|
||||
disabled={loading}
|
||||
variant="outline"
|
||||
>
|
||||
使用你的 IP
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
onClick={setClientIP}
|
||||
disabled={loading || !clientIP.trim()}
|
||||
className="flex-1"
|
||||
>
|
||||
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <CheckCircle className="h-4 w-4" />}
|
||||
設置 IP
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
onClick={testCleanup}
|
||||
disabled={loading}
|
||||
variant="destructive"
|
||||
className="flex-1"
|
||||
>
|
||||
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <AlertTriangle className="h-4 w-4" />}
|
||||
測試清理
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* 使用說明 */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>使用說明</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-2 text-sm text-muted-foreground">
|
||||
<p>• <strong>你的 IP:</strong> 61-227-253-171(從資料庫連線列表中獲取)</p>
|
||||
<p>• <strong>設置 IP:</strong> 點擊「設置 IP」按鈕來設置你的客戶端 IP</p>
|
||||
<p>• <strong>測試清理:</strong> 點擊「測試清理」按鈕來清理你的 IP 連線</p>
|
||||
<p>• <strong>自動清理:</strong> 設置後,關閉頁面時會自動清理你的 IP 連線</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* 訊息顯示 */}
|
||||
{message && (
|
||||
<Alert>
|
||||
<CheckCircle className="h-4 w-4" />
|
||||
<AlertDescription>{message}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{error && (
|
||||
<Alert variant="destructive">
|
||||
<AlertTriangle className="h-4 w-4" />
|
||||
<AlertDescription>{error}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
226
app/test-ip-cleanup/page.tsx
Normal file
226
app/test-ip-cleanup/page.tsx
Normal file
@@ -0,0 +1,226 @@
|
||||
'use client';
|
||||
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||
import { Loader2, Database, Trash2, Eye, Zap } from 'lucide-react';
|
||||
import { clientCleanup } from '@/lib/client-connection-cleanup';
|
||||
|
||||
export default function TestIPCleanupPage() {
|
||||
const [status, setStatus] = useState<any>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [message, setMessage] = useState<string>('');
|
||||
const [error, setError] = useState<string>('');
|
||||
|
||||
// 獲取連線狀態
|
||||
const fetchStatus = async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
const status = await clientCleanup.getConnectionStatus();
|
||||
setStatus(status);
|
||||
setMessage('連線狀態更新成功');
|
||||
setError('');
|
||||
} catch (err) {
|
||||
setError('獲取狀態失敗: ' + (err instanceof Error ? err.message : '未知錯誤'));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// 手動清理
|
||||
const manualCleanup = async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
const success = await clientCleanup.manualCleanup();
|
||||
|
||||
if (success) {
|
||||
setMessage('手動清理完成');
|
||||
setError('');
|
||||
await fetchStatus(); // 重新獲取狀態
|
||||
} else {
|
||||
setError('手動清理失敗');
|
||||
}
|
||||
} catch (err) {
|
||||
setError('手動清理錯誤: ' + (err instanceof Error ? err.message : '未知錯誤'));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// 模擬關閉頁面
|
||||
const simulatePageClose = () => {
|
||||
if (confirm('確定要模擬關閉頁面嗎?這會觸發自動清理機制。')) {
|
||||
// 觸發 beforeunload 事件
|
||||
window.dispatchEvent(new Event('beforeunload'));
|
||||
|
||||
// 等待一下再觸發 unload 事件
|
||||
setTimeout(() => {
|
||||
window.dispatchEvent(new Event('unload'));
|
||||
}, 100);
|
||||
}
|
||||
};
|
||||
|
||||
// 組件載入時獲取狀態
|
||||
useEffect(() => {
|
||||
fetchStatus();
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className="container mx-auto p-6 space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold">IP 連線清理測試</h1>
|
||||
<p className="text-muted-foreground">
|
||||
測試基於 IP 的智能連線清理功能
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
onClick={fetchStatus}
|
||||
disabled={loading}
|
||||
variant="outline"
|
||||
>
|
||||
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <Eye className="h-4 w-4" />}
|
||||
重新整理
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* 客戶端信息 */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Database className="h-5 w-5" />
|
||||
客戶端信息
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-2">
|
||||
<p><strong>客戶端 ID:</strong> {clientCleanup.getClientId()}</p>
|
||||
<p><strong>用戶代理:</strong> {navigator.userAgent}</p>
|
||||
<p><strong>當前時間:</strong> {new Date().toLocaleString()}</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* 連線狀態 */}
|
||||
{status && (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Eye className="h-5 w-5" />
|
||||
連線狀態
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
IP: {status.ip} | 連線數: {status.connectionCount}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="flex items-center gap-4">
|
||||
<Badge variant="outline" className="text-lg px-3 py-1">
|
||||
連線數: {status.connectionCount}
|
||||
</Badge>
|
||||
<Badge
|
||||
variant={status.connectionCount > 5 ? "destructive" : "default"}
|
||||
className="text-lg px-3 py-1"
|
||||
>
|
||||
狀態: {status.connectionCount > 5 ? "異常" : "正常"}
|
||||
</Badge>
|
||||
</div>
|
||||
|
||||
{status.connections && status.connections.length > 0 && (
|
||||
<div className="space-y-2">
|
||||
<h4 className="font-medium">連線詳情:</h4>
|
||||
{status.connections.slice(0, 5).map((conn: any, index: number) => (
|
||||
<div key={index} className="p-2 border rounded text-sm">
|
||||
<p>ID: {conn.ID} | HOST: {conn.HOST} | 時間: {conn.TIME}s</p>
|
||||
</div>
|
||||
))}
|
||||
{status.connections.length > 5 && (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
... 還有 {status.connections.length - 5} 個連線
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* 測試操作 */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Zap className="h-5 w-5" />
|
||||
測試操作
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
測試各種連線清理功能
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
|
||||
<Button
|
||||
onClick={manualCleanup}
|
||||
disabled={loading}
|
||||
variant="outline"
|
||||
className="w-full"
|
||||
>
|
||||
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <Trash2 className="h-4 w-4" />}
|
||||
手動清理
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
onClick={simulatePageClose}
|
||||
disabled={loading}
|
||||
variant="destructive"
|
||||
className="w-full"
|
||||
>
|
||||
<Zap className="h-4 w-4" />
|
||||
模擬關閉頁面
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
onClick={() => window.location.reload()}
|
||||
disabled={loading}
|
||||
variant="secondary"
|
||||
className="w-full"
|
||||
>
|
||||
<Database className="h-4 w-4" />
|
||||
重新載入頁面
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* 自動清理說明 */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>自動清理機制</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-2 text-sm text-muted-foreground">
|
||||
<p>• <strong>頁面關閉前:</strong> 自動清理當前 IP 的所有連線</p>
|
||||
<p>• <strong>頁面隱藏時:</strong> 當切換到其他標籤頁時清理連線</p>
|
||||
<p>• <strong>定期清理:</strong> 每5分鐘檢查並清理多餘連線</p>
|
||||
<p>• <strong>手動清理:</strong> 可以隨時手動觸發清理</p>
|
||||
<p>• <strong>智能識別:</strong> 只清理當前 IP 的連線,不影響其他用戶</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* 訊息顯示 */}
|
||||
{message && (
|
||||
<Alert>
|
||||
<Database className="h-4 w-4" />
|
||||
<AlertDescription>{message}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{error && (
|
||||
<Alert variant="destructive">
|
||||
<Trash2 className="h-4 w-4" />
|
||||
<AlertDescription>{error}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
Reference in New Issue
Block a user