清理不必要的測試檔案
This commit is contained in:
@@ -1,371 +0,0 @@
|
||||
'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>
|
||||
);
|
||||
}
|
@@ -1,267 +0,0 @@
|
||||
'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>
|
||||
);
|
||||
}
|
@@ -1,281 +0,0 @@
|
||||
'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>
|
||||
);
|
||||
}
|
@@ -1,442 +0,0 @@
|
||||
'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>
|
||||
);
|
||||
}
|
@@ -1,195 +0,0 @@
|
||||
"use client"
|
||||
|
||||
import { useState } from "react"
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Label } from "@/components/ui/label"
|
||||
import { Textarea } from "@/components/ui/textarea"
|
||||
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog"
|
||||
import { CheckCircle, Edit, Loader2 } from "lucide-react"
|
||||
|
||||
export default function ScoringFormTestPage() {
|
||||
const [showScoringForm, setShowScoringForm] = useState(false)
|
||||
const [manualScoring, setManualScoring] = useState({
|
||||
judgeId: "judge1",
|
||||
participantId: "app1",
|
||||
scores: {
|
||||
"創新性": 0,
|
||||
"技術性": 0,
|
||||
"實用性": 0,
|
||||
"展示效果": 0,
|
||||
"影響力": 0
|
||||
},
|
||||
comments: ""
|
||||
})
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
|
||||
const scoringRules = [
|
||||
{ name: "創新性", description: "技術創新程度和獨特性", weight: 25 },
|
||||
{ name: "技術性", description: "技術實現的複雜度和穩定性", weight: 20 },
|
||||
{ name: "實用性", description: "實際應用價值和用戶體驗", weight: 25 },
|
||||
{ name: "展示效果", description: "演示效果和表達能力", weight: 15 },
|
||||
{ name: "影響力", description: "對行業和社會的潛在影響", weight: 15 }
|
||||
]
|
||||
|
||||
const calculateTotalScore = (scores: Record<string, number>): number => {
|
||||
let totalScore = 0
|
||||
let totalWeight = 0
|
||||
|
||||
scoringRules.forEach(rule => {
|
||||
const score = scores[rule.name] || 0
|
||||
const weight = rule.weight || 1
|
||||
totalScore += score * weight
|
||||
totalWeight += weight
|
||||
})
|
||||
|
||||
return totalWeight > 0 ? Math.round(totalScore / totalWeight) : 0
|
||||
}
|
||||
|
||||
const handleSubmitScore = async () => {
|
||||
setIsLoading(true)
|
||||
// 模擬提交
|
||||
setTimeout(() => {
|
||||
setIsLoading(false)
|
||||
setShowScoringForm(false)
|
||||
}, 2000)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="container mx-auto py-6">
|
||||
<div className="mb-6">
|
||||
<h1 className="text-3xl font-bold">評分表單測試</h1>
|
||||
<p className="text-gray-600">測試完整的評分表單功能</p>
|
||||
</div>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>評分表單演示</CardTitle>
|
||||
<CardDescription>點擊按鈕查看完整的評分表單</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<Button onClick={() => setShowScoringForm(true)} size="lg">
|
||||
<Edit className="w-5 h-5 mr-2" />
|
||||
開啟評分表單
|
||||
</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Dialog open={showScoringForm} onOpenChange={setShowScoringForm}>
|
||||
<DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center space-x-2">
|
||||
<Edit className="w-5 h-5" />
|
||||
<span>評分表單</span>
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
為參賽者進行評分,請根據各項指標進行評分
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-6">
|
||||
{/* 評分項目 */}
|
||||
<div className="space-y-4">
|
||||
<h3 className="text-lg font-semibold">評分項目</h3>
|
||||
{scoringRules.map((rule, index) => (
|
||||
<div key={index} className="space-y-4 p-6 border rounded-lg bg-white shadow-sm">
|
||||
<div className="flex justify-between items-start">
|
||||
<div className="flex-1">
|
||||
<Label className="text-lg font-semibold text-gray-900">{rule.name}</Label>
|
||||
<p className="text-sm text-gray-600 mt-2 leading-relaxed">{rule.description}</p>
|
||||
<p className="text-xs text-purple-600 mt-2 font-medium">權重:{rule.weight}%</p>
|
||||
</div>
|
||||
<div className="text-right ml-4">
|
||||
<span className="text-2xl font-bold text-blue-600">
|
||||
{manualScoring.scores[rule.name] || 0} / 10
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 評分按鈕 */}
|
||||
<div className="flex flex-wrap gap-3">
|
||||
{Array.from({ length: 10 }, (_, i) => i + 1).map((score) => (
|
||||
<button
|
||||
key={score}
|
||||
type="button"
|
||||
onClick={() => setManualScoring({
|
||||
...manualScoring,
|
||||
scores: { ...manualScoring.scores, [rule.name]: score }
|
||||
})}
|
||||
className={`w-12 h-12 rounded-lg border-2 font-semibold text-lg transition-all duration-200 ${
|
||||
(manualScoring.scores[rule.name] || 0) === score
|
||||
? 'bg-blue-600 text-white border-blue-600 shadow-lg scale-105'
|
||||
: 'bg-white text-gray-700 border-gray-300 hover:border-blue-400 hover:bg-blue-50 hover:scale-105'
|
||||
}`}
|
||||
>
|
||||
{score}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* 總分顯示 */}
|
||||
<div className="p-6 bg-gradient-to-r from-blue-50 to-purple-50 rounded-lg border-2 border-blue-200">
|
||||
<div className="flex justify-between items-center">
|
||||
<div>
|
||||
<span className="text-xl font-bold text-gray-900">總分</span>
|
||||
<p className="text-sm text-gray-600 mt-1">根據權重計算的綜合評分</p>
|
||||
</div>
|
||||
<div className="flex items-center space-x-3">
|
||||
<span className="text-4xl font-bold text-blue-600">
|
||||
{calculateTotalScore(manualScoring.scores)}
|
||||
</span>
|
||||
<span className="text-xl text-gray-500 font-medium">/ 10</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 評審意見 */}
|
||||
<div className="space-y-3">
|
||||
<Label className="text-lg font-semibold">評審意見 *</Label>
|
||||
<Textarea
|
||||
placeholder="請詳細填寫評審意見、優點分析、改進建議等..."
|
||||
value={manualScoring.comments}
|
||||
onChange={(e) => setManualScoring({ ...manualScoring, comments: e.target.value })}
|
||||
rows={6}
|
||||
className="min-h-[120px] resize-none"
|
||||
/>
|
||||
<p className="text-xs text-gray-500">請提供具體的評審意見,包括項目的優點、不足之處和改進建議</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end space-x-4 pt-6 border-t border-gray-200">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="lg"
|
||||
onClick={() => setShowScoringForm(false)}
|
||||
className="px-8"
|
||||
>
|
||||
取消
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleSubmitScore}
|
||||
disabled={isLoading}
|
||||
size="lg"
|
||||
className="px-8 bg-blue-600 hover:bg-blue-700"
|
||||
>
|
||||
{isLoading ? (
|
||||
<>
|
||||
<Loader2 className="w-5 h-5 mr-2 animate-spin" />
|
||||
提交中...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<CheckCircle className="w-5 h-5 mr-2" />
|
||||
提交評分
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
)
|
||||
}
|
@@ -1,13 +0,0 @@
|
||||
import { ScoringManagement } from "@/components/admin/scoring-management"
|
||||
|
||||
export default function ScoringTestPage() {
|
||||
return (
|
||||
<div className="container mx-auto py-6">
|
||||
<div className="mb-6">
|
||||
<h1 className="text-3xl font-bold">評分管理測試</h1>
|
||||
<p className="text-gray-600">測試動態評分項目功能</p>
|
||||
</div>
|
||||
<ScoringManagement />
|
||||
</div>
|
||||
)
|
||||
}
|
@@ -1,13 +0,0 @@
|
||||
import { ScoringManagement } from "@/components/admin/scoring-management"
|
||||
|
||||
export default function ScoringPage() {
|
||||
return (
|
||||
<div className="container mx-auto py-6">
|
||||
<div className="mb-6">
|
||||
<h1 className="text-3xl font-bold">評分管理</h1>
|
||||
<p className="text-gray-600">管理競賽評分,查看已完成和未完成的評分內容</p>
|
||||
</div>
|
||||
<ScoringManagement />
|
||||
</div>
|
||||
)
|
||||
}
|
@@ -1,314 +0,0 @@
|
||||
'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>
|
||||
);
|
||||
}
|
@@ -1,122 +0,0 @@
|
||||
// =====================================================
|
||||
// 連線監控 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 });
|
||||
}
|
||||
}
|
@@ -1,59 +0,0 @@
|
||||
// =====================================================
|
||||
// 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 });
|
||||
}
|
||||
}
|
@@ -1,45 +0,0 @@
|
||||
// =====================================================
|
||||
// 調試競賽 API
|
||||
// =====================================================
|
||||
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { CompetitionService } from '@/lib/services/database-service';
|
||||
|
||||
// 獲取所有競賽和當前競賽狀態
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
// 獲取所有競賽
|
||||
const allCompetitions = await CompetitionService.getAllCompetitions();
|
||||
|
||||
// 獲取當前競賽
|
||||
const currentCompetition = await CompetitionService.getCurrentCompetition();
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
data: {
|
||||
allCompetitions: allCompetitions.map(c => ({
|
||||
id: c.id,
|
||||
name: c.name,
|
||||
status: c.status,
|
||||
is_current: c.is_current,
|
||||
is_active: c.is_active
|
||||
})),
|
||||
currentCompetition: currentCompetition ? {
|
||||
id: currentCompetition.id,
|
||||
name: currentCompetition.name,
|
||||
status: currentCompetition.status,
|
||||
is_current: currentCompetition.is_current,
|
||||
is_active: currentCompetition.is_active
|
||||
} : null
|
||||
}
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('調試競賽失敗:', error);
|
||||
return NextResponse.json({
|
||||
success: false,
|
||||
message: '調試競賽失敗',
|
||||
error: error instanceof Error ? error.message : '未知錯誤'
|
||||
}, { status: 500 });
|
||||
}
|
||||
}
|
54
app/api/debug/env/route.ts
vendored
54
app/api/debug/env/route.ts
vendored
@@ -1,54 +0,0 @@
|
||||
// =====================================================
|
||||
// 環境變數調試 API
|
||||
// =====================================================
|
||||
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
console.log('🔍 檢查 Next.js 中的環境變數...');
|
||||
|
||||
// 檢查所有相關的環境變數
|
||||
const envVars = {
|
||||
DB_HOST: process.env.DB_HOST,
|
||||
DB_PORT: process.env.DB_PORT,
|
||||
DB_NAME: process.env.DB_NAME,
|
||||
DB_USER: process.env.DB_USER,
|
||||
DB_PASSWORD: process.env.DB_PASSWORD ? '***' : undefined,
|
||||
SLAVE_DB_HOST: process.env.SLAVE_DB_HOST,
|
||||
SLAVE_DB_PORT: process.env.SLAVE_DB_PORT,
|
||||
SLAVE_DB_NAME: process.env.SLAVE_DB_NAME,
|
||||
SLAVE_DB_USER: process.env.SLAVE_DB_USER,
|
||||
SLAVE_DB_PASSWORD: process.env.SLAVE_DB_PASSWORD ? '***' : undefined,
|
||||
DB_DUAL_WRITE_ENABLED: process.env.DB_DUAL_WRITE_ENABLED,
|
||||
DB_MASTER_PRIORITY: process.env.DB_MASTER_PRIORITY,
|
||||
NODE_ENV: process.env.NODE_ENV,
|
||||
};
|
||||
|
||||
console.log('📋 Next.js 環境變數檢查結果:');
|
||||
Object.entries(envVars).forEach(([key, value]) => {
|
||||
if (value) {
|
||||
console.log(`✅ ${key}: ${value}`);
|
||||
} else {
|
||||
console.log(`❌ ${key}: undefined`);
|
||||
}
|
||||
});
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
message: '環境變數檢查完成',
|
||||
data: {
|
||||
envVars,
|
||||
timestamp: new Date().toISOString(),
|
||||
nodeEnv: process.env.NODE_ENV,
|
||||
}
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('❌ 環境變數檢查失敗:', error);
|
||||
return NextResponse.json({
|
||||
success: false,
|
||||
message: '環境變數檢查失敗',
|
||||
error: error instanceof Error ? error.message : '未知錯誤'
|
||||
}, { status: 500 });
|
||||
}
|
||||
}
|
@@ -1,44 +0,0 @@
|
||||
// =====================================================
|
||||
// 簡單環境變數測試
|
||||
// =====================================================
|
||||
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
// 直接檢查環境變數
|
||||
const envCheck = {
|
||||
NODE_ENV: process.env.NODE_ENV,
|
||||
DB_HOST: process.env.DB_HOST,
|
||||
DB_PORT: process.env.DB_PORT,
|
||||
DB_NAME: process.env.DB_NAME,
|
||||
DB_USER: process.env.DB_USER,
|
||||
DB_PASSWORD: process.env.DB_PASSWORD ? '***' : undefined,
|
||||
// 檢查所有可能的環境變數
|
||||
ALL_ENV_KEYS: Object.keys(process.env).filter(key => key.startsWith('DB_')),
|
||||
};
|
||||
|
||||
console.log('🔍 環境變數檢查:');
|
||||
console.log('NODE_ENV:', process.env.NODE_ENV);
|
||||
console.log('DB_HOST:', process.env.DB_HOST);
|
||||
console.log('DB_PORT:', process.env.DB_PORT);
|
||||
console.log('DB_NAME:', process.env.DB_NAME);
|
||||
console.log('DB_USER:', process.env.DB_USER);
|
||||
console.log('DB_PASSWORD:', process.env.DB_PASSWORD ? '***' : 'undefined');
|
||||
console.log('所有 DB_ 開頭的環境變數:', Object.keys(process.env).filter(key => key.startsWith('DB_')));
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
message: '環境變數檢查完成',
|
||||
data: envCheck,
|
||||
timestamp: new Date().toISOString(),
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('❌ 環境變數檢查失敗:', error);
|
||||
return NextResponse.json({
|
||||
success: false,
|
||||
message: '環境變數檢查失敗',
|
||||
error: error instanceof Error ? error.message : '未知錯誤'
|
||||
}, { status: 500 });
|
||||
}
|
||||
}
|
@@ -1,104 +0,0 @@
|
||||
// =====================================================
|
||||
// 緊急連線清理 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 });
|
||||
}
|
||||
}
|
@@ -1,177 +0,0 @@
|
||||
// =====================================================
|
||||
// 基於 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 });
|
||||
}
|
||||
}
|
@@ -1,78 +0,0 @@
|
||||
// =====================================================
|
||||
// 手動設置客戶端 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 });
|
||||
}
|
||||
}
|
@@ -1,59 +0,0 @@
|
||||
// =====================================================
|
||||
// 智能連線清理 API
|
||||
// =====================================================
|
||||
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { smartConnectionCleaner } from '@/lib/smart-connection-cleaner';
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
console.log('🧠 收到智能清理請求');
|
||||
|
||||
// 執行智能清理
|
||||
const result = await smartConnectionCleaner.smartCleanup(request);
|
||||
|
||||
return NextResponse.json({
|
||||
success: result.success,
|
||||
message: result.message,
|
||||
data: {
|
||||
killedCount: result.killedCount,
|
||||
details: result.details,
|
||||
timestamp: new Date().toISOString()
|
||||
}
|
||||
});
|
||||
|
||||
} 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 {
|
||||
console.log('📊 收到連線統計請求');
|
||||
|
||||
// 獲取連線統計
|
||||
const stats = await smartConnectionCleaner.getConnectionStats();
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
message: '連線統計獲取成功',
|
||||
data: {
|
||||
stats,
|
||||
timestamp: new Date().toISOString()
|
||||
}
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ 連線統計 API 錯誤:', error);
|
||||
return NextResponse.json({
|
||||
success: false,
|
||||
error: '獲取連線統計失敗',
|
||||
details: error instanceof Error ? error.message : '未知錯誤'
|
||||
}, { status: 500 });
|
||||
}
|
||||
}
|
@@ -1,38 +0,0 @@
|
||||
// =====================================================
|
||||
// 資料庫連接測試 API
|
||||
// =====================================================
|
||||
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { db } from '@/lib/database';
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
// 測試基本查詢
|
||||
const result = await db.query('SELECT 1 as test');
|
||||
|
||||
// 測試競賽表
|
||||
const competitions = await db.query('SELECT id, name, type FROM competitions WHERE is_active = TRUE LIMIT 3');
|
||||
|
||||
// 測試評審表
|
||||
const judges = await db.query('SELECT id, name, title FROM judges WHERE is_active = TRUE LIMIT 3');
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
message: '資料庫連接測試成功',
|
||||
data: {
|
||||
basicQuery: result,
|
||||
competitions: competitions,
|
||||
judges: judges
|
||||
}
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ 資料庫連接測試失敗:', error);
|
||||
return NextResponse.json({
|
||||
success: false,
|
||||
message: '資料庫連接測試失敗',
|
||||
error: error instanceof Error ? error.message : '未知錯誤',
|
||||
stack: error instanceof Error ? error.stack : undefined
|
||||
}, { status: 500 });
|
||||
}
|
||||
}
|
@@ -1,100 +0,0 @@
|
||||
// =====================================================
|
||||
// 測試資料庫關閉機制 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 });
|
||||
}
|
||||
}
|
@@ -1,96 +0,0 @@
|
||||
// =====================================================
|
||||
// 終極連線清理 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 });
|
||||
}
|
||||
}
|
@@ -1,297 +0,0 @@
|
||||
'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>
|
||||
);
|
||||
}
|
@@ -1,325 +0,0 @@
|
||||
'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>
|
||||
);
|
||||
}
|
@@ -1,180 +0,0 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useState } from 'react'
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Button } from '@/components/ui/button'
|
||||
|
||||
export default function DebugScoringPage() {
|
||||
const [competitions, setCompetitions] = useState<any[]>([])
|
||||
const [selectedCompetition, setSelectedCompetition] = useState<any>(null)
|
||||
const [competitionJudges, setCompetitionJudges] = useState<any[]>([])
|
||||
const [competitionParticipants, setCompetitionParticipants] = useState<any[]>([])
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [logs, setLogs] = useState<string[]>([])
|
||||
|
||||
const addLog = (message: string) => {
|
||||
setLogs(prev => [...prev, `${new Date().toLocaleTimeString()}: ${message}`])
|
||||
}
|
||||
|
||||
// 載入競賽列表
|
||||
const loadCompetitions = async () => {
|
||||
try {
|
||||
addLog('🔄 開始載入競賽列表...')
|
||||
const response = await fetch('/api/competitions')
|
||||
const data = await response.json()
|
||||
addLog(`📋 競賽API回應: ${JSON.stringify(data)}`)
|
||||
|
||||
if (data.success && data.data) {
|
||||
setCompetitions(data.data)
|
||||
addLog(`✅ 載入 ${data.data.length} 個競賽`)
|
||||
} else {
|
||||
addLog(`❌ 競賽載入失敗: ${data.message}`)
|
||||
}
|
||||
} catch (error) {
|
||||
addLog(`❌ 競賽載入錯誤: ${error.message}`)
|
||||
}
|
||||
}
|
||||
|
||||
// 載入競賽數據
|
||||
const loadCompetitionData = async (competitionId: string) => {
|
||||
if (!competitionId) return
|
||||
|
||||
setLoading(true)
|
||||
addLog(`🔍 開始載入競賽數據,ID: ${competitionId}`)
|
||||
|
||||
try {
|
||||
// 載入評審
|
||||
addLog('📋 載入評審...')
|
||||
const judgesResponse = await fetch(`/api/competitions/${competitionId}/judges`)
|
||||
const judgesData = await judgesResponse.json()
|
||||
addLog(`評審API回應: ${JSON.stringify(judgesData)}`)
|
||||
|
||||
if (judgesData.success && judgesData.data && judgesData.data.judges) {
|
||||
setCompetitionJudges(judgesData.data.judges)
|
||||
addLog(`✅ 載入 ${judgesData.data.judges.length} 個評審`)
|
||||
} else {
|
||||
addLog(`❌ 評審載入失敗: ${judgesData.message}`)
|
||||
setCompetitionJudges([])
|
||||
}
|
||||
|
||||
// 載入參賽者
|
||||
addLog('📱 載入參賽者...')
|
||||
const [appsResponse, teamsResponse] = await Promise.all([
|
||||
fetch(`/api/competitions/${competitionId}/apps`),
|
||||
fetch(`/api/competitions/${competitionId}/teams`)
|
||||
])
|
||||
|
||||
const appsData = await appsResponse.json()
|
||||
const teamsData = await teamsResponse.json()
|
||||
|
||||
addLog(`應用API回應: ${JSON.stringify(appsData)}`)
|
||||
addLog(`團隊API回應: ${JSON.stringify(teamsData)}`)
|
||||
|
||||
const participants = []
|
||||
|
||||
if (appsData.success && appsData.data && appsData.data.apps) {
|
||||
participants.push(...appsData.data.apps.map((app: any) => ({
|
||||
id: app.id,
|
||||
name: app.name,
|
||||
type: 'individual',
|
||||
creator: app.creator
|
||||
})))
|
||||
addLog(`✅ 載入 ${appsData.data.apps.length} 個應用`)
|
||||
} else {
|
||||
addLog(`❌ 應用載入失敗: ${appsData.message}`)
|
||||
}
|
||||
|
||||
if (teamsData.success && teamsData.data && teamsData.data.teams) {
|
||||
participants.push(...teamsData.data.teams.map((team: any) => ({
|
||||
id: team.id,
|
||||
name: team.name,
|
||||
type: 'team',
|
||||
creator: team.members && team.members.find((m: any) => m.role === '隊長')?.name || '未知隊長'
|
||||
})))
|
||||
addLog(`✅ 載入 ${teamsData.data.teams.length} 個團隊`)
|
||||
} else {
|
||||
addLog(`❌ 團隊載入失敗: ${teamsData.message}`)
|
||||
}
|
||||
|
||||
setCompetitionParticipants(participants)
|
||||
addLog(`✅ 參賽者載入完成: ${participants.length} 個`)
|
||||
|
||||
} catch (error) {
|
||||
addLog(`❌ 載入失敗: ${error.message}`)
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
loadCompetitions()
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<div className="container mx-auto p-6 space-y-6">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>評分表單調試頁面</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-2">選擇競賽:</label>
|
||||
<select
|
||||
value={selectedCompetition?.id || ""}
|
||||
onChange={(e) => {
|
||||
const competition = competitions.find(c => c.id === e.target.value)
|
||||
setSelectedCompetition(competition)
|
||||
if (competition) {
|
||||
loadCompetitionData(competition.id)
|
||||
}
|
||||
}}
|
||||
className="w-full p-2 border rounded"
|
||||
>
|
||||
<option value="">選擇競賽</option>
|
||||
{competitions.map(comp => (
|
||||
<option key={comp.id} value={comp.id}>
|
||||
{comp.name} ({comp.type})
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
{selectedCompetition && (
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div>
|
||||
<h3 className="font-semibold mb-2">評審 ({competitionJudges.length})</h3>
|
||||
<div className="space-y-2">
|
||||
{competitionJudges.map(judge => (
|
||||
<div key={judge.id} className="p-2 bg-gray-100 rounded">
|
||||
{judge.name} - {judge.title} - {judge.department}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<h3 className="font-semibold mb-2">參賽者 ({competitionParticipants.length})</h3>
|
||||
<div className="space-y-2">
|
||||
{competitionParticipants.map(participant => (
|
||||
<div key={participant.id} className="p-2 bg-gray-100 rounded">
|
||||
{participant.name} ({participant.type}) - {participant.creator}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div>
|
||||
<h3 className="font-semibold mb-2">調試日誌</h3>
|
||||
<div className="bg-gray-100 p-4 rounded max-h-96 overflow-y-auto">
|
||||
{logs.map((log, index) => (
|
||||
<div key={index} className="text-sm font-mono">{log}</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
)
|
||||
}
|
100
app/globals.css
100
app/globals.css
@@ -1,100 +0,0 @@
|
||||
@tailwind base;
|
||||
@tailwind components;
|
||||
@tailwind utilities;
|
||||
|
||||
/* 隱藏滾動條 */
|
||||
.scrollbar-hide {
|
||||
-ms-overflow-style: none; /* Internet Explorer 10+ */
|
||||
scrollbar-width: none; /* Firefox */
|
||||
}
|
||||
|
||||
.scrollbar-hide::-webkit-scrollbar {
|
||||
display: none; /* Safari and Chrome */
|
||||
}
|
||||
|
||||
@layer utilities {
|
||||
.text-balance {
|
||||
text-wrap: balance;
|
||||
}
|
||||
}
|
||||
|
||||
@layer base {
|
||||
:root {
|
||||
--background: 0 0% 100%;
|
||||
--foreground: 0 0% 3.9%;
|
||||
--card: 0 0% 100%;
|
||||
--card-foreground: 0 0% 3.9%;
|
||||
--popover: 0 0% 100%;
|
||||
--popover-foreground: 0 0% 3.9%;
|
||||
--primary: 0 0% 9%;
|
||||
--primary-foreground: 0 0% 98%;
|
||||
--secondary: 0 0% 96.1%;
|
||||
--secondary-foreground: 0 0% 9%;
|
||||
--muted: 0 0% 96.1%;
|
||||
--muted-foreground: 0 0% 45.1%;
|
||||
--accent: 0 0% 96.1%;
|
||||
--accent-foreground: 0 0% 9%;
|
||||
--destructive: 0 84.2% 60.2%;
|
||||
--destructive-foreground: 0 0% 98%;
|
||||
--border: 0 0% 89.8%;
|
||||
--input: 0 0% 89.8%;
|
||||
--ring: 0 0% 3.9%;
|
||||
--chart-1: 12 76% 61%;
|
||||
--chart-2: 173 58% 39%;
|
||||
--chart-3: 197 37% 24%;
|
||||
--chart-4: 43 74% 66%;
|
||||
--chart-5: 27 87% 67%;
|
||||
--radius: 0.5rem;
|
||||
--sidebar-background: 0 0% 98%;
|
||||
--sidebar-foreground: 240 5.3% 26.1%;
|
||||
--sidebar-primary: 240 5.9% 10%;
|
||||
--sidebar-primary-foreground: 0 0% 98%;
|
||||
--sidebar-accent: 240 4.8% 95.9%;
|
||||
--sidebar-accent-foreground: 240 5.9% 10%;
|
||||
--sidebar-border: 220 13% 91%;
|
||||
--sidebar-ring: 217.2 91.2% 59.8%;
|
||||
}
|
||||
.dark {
|
||||
--background: 0 0% 3.9%;
|
||||
--foreground: 0 0% 98%;
|
||||
--card: 0 0% 3.9%;
|
||||
--card-foreground: 0 0% 98%;
|
||||
--popover: 0 0% 3.9%;
|
||||
--popover-foreground: 0 0% 98%;
|
||||
--primary: 0 0% 98%;
|
||||
--primary-foreground: 0 0% 9%;
|
||||
--secondary: 0 0% 14.9%;
|
||||
--secondary-foreground: 0 0% 98%;
|
||||
--muted: 0 0% 14.9%;
|
||||
--muted-foreground: 0 0% 63.9%;
|
||||
--accent: 0 0% 14.9%;
|
||||
--accent-foreground: 0 0% 98%;
|
||||
--destructive: 0 62.8% 30.6%;
|
||||
--destructive-foreground: 0 0% 98%;
|
||||
--border: 0 0% 14.9%;
|
||||
--input: 0 0% 14.9%;
|
||||
--ring: 0 0% 83.1%;
|
||||
--chart-1: 220 70% 50%;
|
||||
--chart-2: 160 60% 45%;
|
||||
--chart-3: 30 80% 55%;
|
||||
--chart-4: 280 65% 60%;
|
||||
--chart-5: 340 75% 55%;
|
||||
--sidebar-background: 240 5.9% 10%;
|
||||
--sidebar-foreground: 240 4.8% 95.9%;
|
||||
--sidebar-primary: 224.3 76.3% 48%;
|
||||
--sidebar-primary-foreground: 0 0% 100%;
|
||||
--sidebar-accent: 240 3.7% 15.9%;
|
||||
--sidebar-accent-foreground: 240 4.8% 95.9%;
|
||||
--sidebar-border: 240 3.7% 15.9%;
|
||||
--sidebar-ring: 217.2 91.2% 59.8%;
|
||||
}
|
||||
}
|
||||
|
||||
@layer base {
|
||||
* {
|
||||
@apply border-border;
|
||||
}
|
||||
body {
|
||||
@apply bg-background text-foreground;
|
||||
}
|
||||
}
|
@@ -1,11 +1,10 @@
|
||||
import type React from "react"
|
||||
import { Inter } from "next/font/google"
|
||||
import "./globals.css"
|
||||
import "../styles/globals.css"
|
||||
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"] })
|
||||
@@ -30,7 +29,6 @@ export default function RootLayout({
|
||||
{children}
|
||||
<Toaster />
|
||||
<ChatBot />
|
||||
<ClientConnectionCleanup />
|
||||
</CompetitionProvider>
|
||||
</AuthProvider>
|
||||
</body>
|
||||
|
@@ -1,174 +0,0 @@
|
||||
'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 handleSetClientIP = 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 handleSetYourIP = () => {
|
||||
setClientIP('61-227-253-171');
|
||||
};
|
||||
|
||||
// 測試清理功能
|
||||
const handleTestCleanup = 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={handleSetYourIP}
|
||||
disabled={loading}
|
||||
variant="outline"
|
||||
>
|
||||
使用你的 IP
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
onClick={handleSetClientIP}
|
||||
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={handleTestCleanup}
|
||||
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>
|
||||
);
|
||||
}
|
@@ -1,280 +0,0 @@
|
||||
'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, BarChart3 } from 'lucide-react';
|
||||
|
||||
interface ConnectionStats {
|
||||
total: number;
|
||||
user: number;
|
||||
infrastructure: number;
|
||||
other: number;
|
||||
details: Array<{
|
||||
id: number;
|
||||
host: string;
|
||||
time: number;
|
||||
state: string;
|
||||
type: 'user' | 'infrastructure' | 'other';
|
||||
}>;
|
||||
}
|
||||
|
||||
interface CleanupResult {
|
||||
success: boolean;
|
||||
message: string;
|
||||
data: {
|
||||
killedCount: number;
|
||||
details: {
|
||||
userRealIP?: string;
|
||||
infrastructureIPs?: string[];
|
||||
cleanedConnections: Array<{
|
||||
id: number;
|
||||
host: string;
|
||||
time: number;
|
||||
state: string;
|
||||
}>;
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
export default function SmartCleanupTestPage() {
|
||||
const [stats, setStats] = useState<ConnectionStats | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [message, setMessage] = useState<string>('');
|
||||
const [error, setError] = useState<string>('');
|
||||
|
||||
// 獲取連線統計
|
||||
const fetchStats = async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
const response = await fetch('/api/smart-cleanup');
|
||||
const data = await response.json();
|
||||
|
||||
if (data.success) {
|
||||
setStats(data.data.stats);
|
||||
setMessage('連線統計更新成功');
|
||||
setError('');
|
||||
} else {
|
||||
setError(data.error || '獲取連線統計失敗');
|
||||
}
|
||||
} catch (err) {
|
||||
setError('網路錯誤: ' + (err instanceof Error ? err.message : '未知錯誤'));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// 執行智能清理
|
||||
const performSmartCleanup = async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
const response = await fetch('/api/smart-cleanup', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
});
|
||||
|
||||
const data: CleanupResult = await response.json();
|
||||
|
||||
if (data.success) {
|
||||
setMessage(`智能清理完成: ${data.message}`);
|
||||
setError('');
|
||||
// 重新獲取統計
|
||||
await fetchStats();
|
||||
} else {
|
||||
setError(data.error || '智能清理失敗');
|
||||
}
|
||||
} catch (err) {
|
||||
setError('清理錯誤: ' + (err instanceof Error ? err.message : '未知錯誤'));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// 組件載入時獲取統計
|
||||
useEffect(() => {
|
||||
fetchStats();
|
||||
}, []);
|
||||
|
||||
// 獲取類型顏色
|
||||
const getTypeColor = (type: 'user' | 'infrastructure' | 'other') => {
|
||||
switch (type) {
|
||||
case 'user': return 'default';
|
||||
case 'infrastructure': return 'destructive';
|
||||
case 'other': return 'secondary';
|
||||
default: return 'outline';
|
||||
}
|
||||
};
|
||||
|
||||
// 獲取類型標籤
|
||||
const getTypeLabel = (type: 'user' | 'infrastructure' | 'other') => {
|
||||
switch (type) {
|
||||
case 'user': return '用戶連線';
|
||||
case 'infrastructure': return '基礎設施';
|
||||
case 'other': return '其他';
|
||||
default: return '未知';
|
||||
}
|
||||
};
|
||||
|
||||
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">
|
||||
智能識別和清理用戶真實 IP 及基礎設施連線
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
onClick={fetchStats}
|
||||
disabled={loading}
|
||||
variant="outline"
|
||||
>
|
||||
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <RefreshCw className="h-4 w-4" />}
|
||||
刷新統計
|
||||
</Button>
|
||||
<Button
|
||||
onClick={performSmartCleanup}
|
||||
disabled={loading}
|
||||
variant="destructive"
|
||||
>
|
||||
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <Trash2 className="h-4 w-4" />}
|
||||
智能清理
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 連線統計概覽 */}
|
||||
{stats && (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<BarChart3 className="h-5 w-5" />
|
||||
連線統計概覽
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
當前資料庫連線的分類統計
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="grid grid-cols-2 md:grid-cols-4 gap-4">
|
||||
<div className="text-center">
|
||||
<div className="text-2xl font-bold">{stats.total}</div>
|
||||
<div className="text-sm text-muted-foreground">總連線數</div>
|
||||
</div>
|
||||
<div className="text-center">
|
||||
<div className="text-2xl font-bold text-blue-600">{stats.user}</div>
|
||||
<div className="text-sm text-muted-foreground">用戶連線</div>
|
||||
</div>
|
||||
<div className="text-center">
|
||||
<div className="text-2xl font-bold text-red-600">{stats.infrastructure}</div>
|
||||
<div className="text-sm text-muted-foreground">基礎設施</div>
|
||||
</div>
|
||||
<div className="text-center">
|
||||
<div className="text-2xl font-bold text-gray-600">{stats.other}</div>
|
||||
<div className="text-sm text-muted-foreground">其他</div>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* 連線詳情 */}
|
||||
{stats && stats.details.length > 0 && (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>連線詳情</CardTitle>
|
||||
<CardDescription>
|
||||
所有連線的詳細信息
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-2 max-h-96 overflow-y-auto">
|
||||
{stats.details.map((conn, index) => (
|
||||
<div key={index} className="flex items-center justify-between p-3 border rounded">
|
||||
<div className="flex items-center gap-3">
|
||||
<Badge variant={getTypeColor(conn.type)}>
|
||||
{getTypeLabel(conn.type)}
|
||||
</Badge>
|
||||
<span className="font-mono text-sm">ID: {conn.id}</span>
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{conn.host}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
<span className="text-sm">時間: {conn.time}s</span>
|
||||
<span className="text-sm text-muted-foreground">
|
||||
狀態: {conn.state}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* 功能說明 */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>智能清理功能</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div>
|
||||
<h4 className="font-semibold text-blue-600 mb-2">用戶連線清理</h4>
|
||||
<ul className="text-sm text-muted-foreground space-y-1">
|
||||
<li>• 自動識別你的真實 IP (61-227-253-171)</li>
|
||||
<li>• 清理所有來自你 IP 的連線</li>
|
||||
<li>• 不影響其他用戶的連線</li>
|
||||
<li>• 關閉網站時自動觸發</li>
|
||||
</ul>
|
||||
</div>
|
||||
<div>
|
||||
<h4 className="font-semibold text-red-600 mb-2">基礎設施連線清理</h4>
|
||||
<ul className="text-sm text-muted-foreground space-y-1">
|
||||
<li>• 識別 AWS EC2 實例連線</li>
|
||||
<li>• 識別 Vercel 服務器連線</li>
|
||||
<li>• 可選清理基礎設施連線</li>
|
||||
<li>• 保護網站正常運行</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* 使用說明 */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>使用說明</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-2 text-sm text-muted-foreground">
|
||||
<p>• <strong>刷新統計:</strong> 查看當前所有連線的分類統計</p>
|
||||
<p>• <strong>智能清理:</strong> 自動識別並清理你的真實 IP 連線</p>
|
||||
<p>• <strong>用戶連線:</strong> 來自你真實 IP 的連線,會被優先清理</p>
|
||||
<p>• <strong>基礎設施連線:</strong> Vercel/AWS 服務器連線,通常不清理</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>
|
||||
);
|
||||
}
|
@@ -1,72 +0,0 @@
|
||||
'use client'
|
||||
|
||||
import { useState } from 'react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
|
||||
export default function TestAPIPage() {
|
||||
const [competitionId, setCompetitionId] = useState('be47d842-91f1-11f0-8595-bd825523ae01')
|
||||
const [results, setResults] = useState<any>({})
|
||||
|
||||
const testAPI = async (endpoint: string, name: string) => {
|
||||
try {
|
||||
const response = await fetch(`/api/competitions/${competitionId}/${endpoint}`)
|
||||
const data = await response.json()
|
||||
setResults(prev => ({ ...prev, [name]: data }))
|
||||
console.log(`${name} API回應:`, data)
|
||||
} catch (error) {
|
||||
console.error(`${name} API錯誤:`, error)
|
||||
setResults(prev => ({ ...prev, [name]: { error: error.message } }))
|
||||
}
|
||||
}
|
||||
|
||||
const testAllAPIs = async () => {
|
||||
setResults({})
|
||||
await Promise.all([
|
||||
testAPI('judges', '評審'),
|
||||
testAPI('apps', '應用'),
|
||||
testAPI('teams', '團隊')
|
||||
])
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="container mx-auto p-6 space-y-6">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>API 測試頁面</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-2">競賽ID:</label>
|
||||
<input
|
||||
type="text"
|
||||
value={competitionId}
|
||||
onChange={(e) => setCompetitionId(e.target.value)}
|
||||
className="w-full p-2 border rounded"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex space-x-2">
|
||||
<Button onClick={testAllAPIs}>測試所有API</Button>
|
||||
<Button onClick={() => testAPI('judges', '評審')}>測試評審API</Button>
|
||||
<Button onClick={() => testAPI('apps', '應用')}>測試應用API</Button>
|
||||
<Button onClick={() => testAPI('teams', '團隊')}>測試團隊API</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{Object.entries(results).map(([name, data]) => (
|
||||
<Card key={name}>
|
||||
<CardHeader>
|
||||
<CardTitle>{name} API 結果</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<pre className="bg-gray-100 p-4 rounded overflow-auto text-sm">
|
||||
{JSON.stringify(data, null, 2)}
|
||||
</pre>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
@@ -1,226 +0,0 @@
|
||||
'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>
|
||||
);
|
||||
}
|
@@ -1,101 +0,0 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useEffect } from 'react'
|
||||
import { CompetitionProvider } from '@/contexts/competition-context'
|
||||
|
||||
export default function TestManualScoringPage() {
|
||||
const [competition, setCompetition] = useState<any>(null)
|
||||
const [teams, setTeams] = useState<any[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
|
||||
useEffect(() => {
|
||||
loadCompetitionData()
|
||||
}, [])
|
||||
|
||||
const loadCompetitionData = async () => {
|
||||
try {
|
||||
|
||||
// 載入競賽信息
|
||||
const competitionResponse = await fetch('/api/competitions/be4b0a71-91f1-11f0-bb38-4adff2d0e33e')
|
||||
const competitionData = await competitionResponse.json()
|
||||
|
||||
if (competitionData.success) {
|
||||
setCompetition(competitionData.data.competition)
|
||||
}
|
||||
|
||||
// 載入團隊數據
|
||||
const teamsResponse = await fetch('/api/competitions/be4b0a71-91f1-11f0-bb38-4adff2d0e33e/teams')
|
||||
const teamsData = await teamsResponse.json()
|
||||
|
||||
if (teamsData.success) {
|
||||
setTeams(teamsData.data.teams)
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ 載入數據失敗:', error)
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
if (loading) {
|
||||
return <div className="p-8">載入中...</div>
|
||||
}
|
||||
|
||||
return (
|
||||
<CompetitionProvider>
|
||||
<div className="p-8">
|
||||
<h1 className="text-2xl font-bold mb-4">測試手動評分數據載入</h1>
|
||||
|
||||
<div className="mb-6">
|
||||
<h2 className="text-lg font-semibold mb-2">競賽信息</h2>
|
||||
{competition ? (
|
||||
<div className="bg-gray-100 p-4 rounded">
|
||||
<p><strong>名稱:</strong> {competition.name}</p>
|
||||
<p><strong>類型:</strong> {competition.type}</p>
|
||||
<p><strong>狀態:</strong> {competition.status}</p>
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-red-500">競賽數據載入失敗</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="mb-6">
|
||||
<h2 className="text-lg font-semibold mb-2">團隊數據</h2>
|
||||
{teams.length > 0 ? (
|
||||
<div className="space-y-4">
|
||||
{teams.map((team) => (
|
||||
<div key={team.id} className="bg-gray-100 p-4 rounded">
|
||||
<h3 className="font-semibold">{team.name}</h3>
|
||||
<p><strong>ID:</strong> {team.id}</p>
|
||||
<p><strong>APP數量:</strong> {team.apps?.length || 0}</p>
|
||||
{team.apps && team.apps.length > 0 && (
|
||||
<div className="mt-2">
|
||||
<h4 className="font-medium">APP列表:</h4>
|
||||
<ul className="ml-4">
|
||||
{team.apps.map((app: any) => (
|
||||
<li key={app.id} className="text-sm">
|
||||
• {app.name} ({app.id})
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-red-500">團隊數據載入失敗</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="mb-6">
|
||||
<h2 className="text-lg font-semibold mb-2">手動評分測試</h2>
|
||||
<p className="text-gray-600">
|
||||
請檢查瀏覽器控制台的日誌,查看數據載入情況。
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</CompetitionProvider>
|
||||
)
|
||||
}
|
@@ -1,313 +0,0 @@
|
||||
'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, AlertTriangle, CheckCircle } from 'lucide-react';
|
||||
|
||||
interface VercelIPInfo {
|
||||
smartDetection: {
|
||||
detectedIP: string;
|
||||
confidence: 'high' | 'medium' | 'low';
|
||||
source: string;
|
||||
isPublicIP: boolean;
|
||||
allCandidates: string[];
|
||||
isInfrastructureIP?: boolean;
|
||||
isUserRealIP?: boolean;
|
||||
infrastructureIPs?: string[];
|
||||
userRealIPs?: string[];
|
||||
};
|
||||
headers: Record<string, string | null>;
|
||||
nextRequestIP: string | undefined;
|
||||
env: Record<string, string | undefined>;
|
||||
allHeaders: Record<string, string>;
|
||||
}
|
||||
|
||||
export default function VercelIPDebugPage() {
|
||||
const [ipInfo, setIpInfo] = useState<VercelIPInfo | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [message, setMessage] = useState<string>('');
|
||||
const [error, setError] = 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;
|
||||
setMessage(`Vercel IP 偵測結果: ${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 isInfrastructureIP = (ip: string): boolean => {
|
||||
if (!ip) return false;
|
||||
return ip.includes('ec2-') && ip.includes('.amazonaws.com');
|
||||
};
|
||||
|
||||
// 檢查是否為用戶真實 IP
|
||||
const isUserRealIP = (ip: string): boolean => {
|
||||
if (!ip || ip === 'unknown') return false;
|
||||
return !isInfrastructureIP(ip) && ip !== '::1' && ip !== '127.0.0.1';
|
||||
};
|
||||
|
||||
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">Vercel IP 調試工具</h1>
|
||||
<p className="text-muted-foreground">
|
||||
專門用於調試 Vercel 部署環境中的 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 地址(已過濾基礎設施 IP)
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="flex items-center gap-4">
|
||||
<Badge
|
||||
variant={
|
||||
isUserRealIP(ipInfo.smartDetection.detectedIP) ? "default" :
|
||||
isInfrastructureIP(ipInfo.smartDetection.detectedIP) ? "destructive" : "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>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div>
|
||||
<p className="text-sm font-medium mb-2">用戶真實 IP:</p>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{ipInfo.smartDetection.userRealIPs?.map((ip, index) => (
|
||||
<Badge
|
||||
key={index}
|
||||
variant="default"
|
||||
className="text-sm"
|
||||
>
|
||||
{ip}
|
||||
</Badge>
|
||||
)) || <span className="text-muted-foreground text-sm">無</span>}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<p className="text-sm font-medium mb-2">基礎設施 IP (已過濾):</p>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{ipInfo.smartDetection.infrastructureIPs?.map((ip, index) => (
|
||||
<Badge
|
||||
key={index}
|
||||
variant="destructive"
|
||||
className="text-sm"
|
||||
>
|
||||
{ip}
|
||||
</Badge>
|
||||
)) || <span className="text-muted-foreground text-sm">無</span>}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* 請求標頭分析 */}
|
||||
{ipInfo && (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>請求標頭分析</CardTitle>
|
||||
<CardDescription>
|
||||
分析各種 HTTP 標頭中的 IP 信息
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-4">
|
||||
{Object.entries(ipInfo.headers).map(([key, value]) => {
|
||||
if (!value) return null;
|
||||
|
||||
const isInfra = isInfrastructureIP(value);
|
||||
const isUser = isUserRealIP(value);
|
||||
|
||||
return (
|
||||
<div key={key} className="flex items-center justify-between p-3 border rounded">
|
||||
<div className="flex-1">
|
||||
<span className="font-medium text-sm">{key}:</span>
|
||||
<div className="mt-1">
|
||||
<Badge
|
||||
variant={
|
||||
isUser ? "default" :
|
||||
isInfra ? "destructive" : "outline"
|
||||
}
|
||||
className="text-sm"
|
||||
>
|
||||
{value}
|
||||
</Badge>
|
||||
<div className="flex gap-2 mt-1">
|
||||
{isUser && <Badge variant="default" className="text-xs">用戶真實 IP</Badge>}
|
||||
{isInfra && <Badge variant="destructive" className="text-xs">基礎設施 IP</Badge>}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* 環境信息 */}
|
||||
{ipInfo && (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>部署環境信息</CardTitle>
|
||||
<CardDescription>
|
||||
Vercel 部署環境相關信息
|
||||
</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>
|
||||
)}
|
||||
|
||||
{/* 問題診斷 */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<AlertTriangle className="h-5 w-5" />
|
||||
問題診斷
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{ipInfo?.smartDetection && (
|
||||
<>
|
||||
{isInfrastructureIP(ipInfo.smartDetection.detectedIP) && (
|
||||
<Alert variant="destructive">
|
||||
<AlertTriangle className="h-4 w-4" />
|
||||
<AlertDescription>
|
||||
<strong>問題:</strong> 偵測到的是 Vercel/AWS 基礎設施 IP,不是用戶真實 IP。
|
||||
<br />
|
||||
<strong>解決方案:</strong> 檢查 x-forwarded-for 標頭中是否包含用戶真實 IP。
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{isUserRealIP(ipInfo.smartDetection.detectedIP) && (
|
||||
<Alert>
|
||||
<CheckCircle className="h-4 w-4" />
|
||||
<AlertDescription>
|
||||
<strong>正常:</strong> 成功偵測到用戶真實 IP。
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{!isUserRealIP(ipInfo.smartDetection.detectedIP) && !isInfrastructureIP(ipInfo.smartDetection.detectedIP) && (
|
||||
<Alert variant="destructive">
|
||||
<AlertTriangle className="h-4 w-4" />
|
||||
<AlertDescription>
|
||||
<strong>問題:</strong> 無法偵測到有效的用戶 IP。
|
||||
<br />
|
||||
<strong>可能原因:</strong> 代理配置問題或網路環境限制。
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* 使用說明 */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>使用說明</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-2 text-sm text-muted-foreground">
|
||||
<p>• <strong>基礎設施 IP:</strong> Vercel/AWS 的服務器 IP,不是用戶真實 IP</p>
|
||||
<p>• <strong>用戶真實 IP:</strong> 實際訪問網站的用戶 IP 地址</p>
|
||||
<p>• <strong>x-forwarded-for:</strong> 通常包含用戶真實 IP,格式為 "用戶IP,代理IP"</p>
|
||||
<p>• <strong>問題排查:</strong> 如果偵測到基礎設施 IP,檢查代理配置</p>
|
||||
</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>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
@@ -1,28 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect } from 'react';
|
||||
import { clientCleanup } from '@/lib/client-connection-cleanup';
|
||||
|
||||
// 客戶端連線清理組件
|
||||
export function ClientConnectionCleanup() {
|
||||
useEffect(() => {
|
||||
// 確保在瀏覽器環境中執行
|
||||
if (typeof window === 'undefined') return;
|
||||
|
||||
// 初始化客戶端清理
|
||||
console.log('🖥️ 客戶端連線清理組件已載入');
|
||||
|
||||
// 可以在這裡添加額外的初始化邏輯
|
||||
const clientId = clientCleanup.getClientId();
|
||||
console.log('🆔 客戶端 ID:', clientId);
|
||||
|
||||
// 清理函數(組件卸載時)
|
||||
return () => {
|
||||
console.log('🔄 客戶端連線清理組件卸載');
|
||||
// 可以在這裡添加清理邏輯
|
||||
};
|
||||
}, []);
|
||||
|
||||
// 這個組件不渲染任何內容
|
||||
return null;
|
||||
}
|
@@ -4,7 +4,6 @@
|
||||
|
||||
import { dbShutdownManager } from './database-shutdown-manager';
|
||||
import { startConnectionMonitoring } from './database-middleware';
|
||||
import { smartPool } from './smart-connection-pool';
|
||||
|
||||
// 應用程式初始化
|
||||
export function initializeApp() {
|
||||
@@ -20,11 +19,6 @@ export function initializeApp() {
|
||||
console.log('📊 啟動資料庫連線監控...');
|
||||
startConnectionMonitoring();
|
||||
|
||||
// 初始化智能連線池
|
||||
console.log('🧠 初始化智能連線池...');
|
||||
const poolStats = smartPool.getConnectionStats();
|
||||
console.log('✅ 智能連線池已初始化:', poolStats);
|
||||
|
||||
console.log('✅ 應用程式初始化完成');
|
||||
|
||||
} catch (error) {
|
||||
|
@@ -1,231 +0,0 @@
|
||||
// =====================================================
|
||||
// 客戶端連線清理腳本
|
||||
// =====================================================
|
||||
|
||||
export class ClientConnectionCleanup {
|
||||
private static instance: ClientConnectionCleanup;
|
||||
private isCleaning = false;
|
||||
private clientId: string;
|
||||
|
||||
private constructor() {
|
||||
this.clientId = this.generateClientId();
|
||||
this.setupEventListeners();
|
||||
}
|
||||
|
||||
public static getInstance(): ClientConnectionCleanup {
|
||||
if (!ClientConnectionCleanup.instance) {
|
||||
ClientConnectionCleanup.instance = new ClientConnectionCleanup();
|
||||
}
|
||||
return ClientConnectionCleanup.instance;
|
||||
}
|
||||
|
||||
// 生成客戶端唯一標識符
|
||||
private generateClientId(): string {
|
||||
const timestamp = Date.now();
|
||||
const random = Math.random().toString(36).substring(2);
|
||||
return `client_${timestamp}_${random}`;
|
||||
}
|
||||
|
||||
// 設置事件監聽器
|
||||
private setupEventListeners() {
|
||||
// 確保在瀏覽器環境中執行
|
||||
if (typeof window === 'undefined') {
|
||||
console.log('🖥️ 客戶端連線清理跳過(服務端環境)');
|
||||
return;
|
||||
}
|
||||
|
||||
// 頁面關閉前清理
|
||||
window.addEventListener('beforeunload', () => {
|
||||
this.cleanupOnUnload();
|
||||
});
|
||||
|
||||
// 頁面隱藏時清理
|
||||
document.addEventListener('visibilitychange', () => {
|
||||
if (document.hidden) {
|
||||
this.cleanupOnHidden();
|
||||
}
|
||||
});
|
||||
|
||||
// 頁面卸載時清理
|
||||
window.addEventListener('unload', () => {
|
||||
this.cleanupOnUnload();
|
||||
});
|
||||
|
||||
// 定期清理(每5分鐘)
|
||||
setInterval(() => {
|
||||
this.periodicCleanup();
|
||||
}, 5 * 60 * 1000);
|
||||
|
||||
console.log('🖥️ 客戶端連線清理已啟動');
|
||||
}
|
||||
|
||||
// 頁面關閉前清理
|
||||
private async cleanupOnUnload() {
|
||||
if (this.isCleaning) return;
|
||||
|
||||
// 確保在瀏覽器環境中執行
|
||||
if (typeof window === 'undefined') return;
|
||||
|
||||
this.isCleaning = true;
|
||||
console.log('🔄 頁面關閉前清理連線...');
|
||||
|
||||
try {
|
||||
// 使用 sendBeacon 確保請求能夠發送
|
||||
const data = JSON.stringify({
|
||||
action: 'cleanup-current',
|
||||
clientId: this.clientId,
|
||||
timestamp: Date.now()
|
||||
});
|
||||
|
||||
// 嘗試使用 sendBeacon
|
||||
if (navigator.sendBeacon) {
|
||||
navigator.sendBeacon('/api/ip-cleanup', data);
|
||||
console.log('✅ 使用 sendBeacon 發送清理請求');
|
||||
} else {
|
||||
// 備用方案:使用 fetch
|
||||
await fetch('/api/ip-cleanup', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: data,
|
||||
keepalive: true
|
||||
});
|
||||
console.log('✅ 使用 fetch 發送清理請求');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('❌ 清理請求發送失敗:', error);
|
||||
}
|
||||
}
|
||||
|
||||
// 頁面隱藏時清理
|
||||
private async cleanupOnHidden() {
|
||||
// 確保在瀏覽器環境中執行
|
||||
if (typeof window === 'undefined') return;
|
||||
|
||||
console.log('🔄 頁面隱藏時清理連線...');
|
||||
|
||||
try {
|
||||
await fetch('/api/ip-cleanup', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
action: 'cleanup-current',
|
||||
clientId: this.clientId,
|
||||
reason: 'page-hidden'
|
||||
})
|
||||
});
|
||||
console.log('✅ 頁面隱藏清理完成');
|
||||
} catch (error) {
|
||||
console.error('❌ 頁面隱藏清理失敗:', error);
|
||||
}
|
||||
}
|
||||
|
||||
// 定期清理
|
||||
private async periodicCleanup() {
|
||||
// 確保在瀏覽器環境中執行
|
||||
if (typeof window === 'undefined') return;
|
||||
|
||||
console.log('🔄 定期清理連線...');
|
||||
|
||||
try {
|
||||
const response = await fetch('/api/ip-cleanup?action=local-stats');
|
||||
const data = await response.json();
|
||||
|
||||
if (data.success && data.data.trackedConnections > 10) {
|
||||
// 如果追蹤的連線數超過10個,執行清理
|
||||
await fetch('/api/ip-cleanup', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
action: 'cleanup-local',
|
||||
clientId: this.clientId,
|
||||
reason: 'periodic-cleanup'
|
||||
})
|
||||
});
|
||||
console.log('✅ 定期清理完成');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('❌ 定期清理失敗:', error);
|
||||
}
|
||||
}
|
||||
|
||||
// 手動清理
|
||||
public async manualCleanup(): Promise<boolean> {
|
||||
// 確保在瀏覽器環境中執行
|
||||
if (typeof window === 'undefined') return false;
|
||||
|
||||
try {
|
||||
const response = await fetch('/api/ip-cleanup', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
action: 'cleanup-current',
|
||||
clientId: this.clientId,
|
||||
reason: 'manual-cleanup'
|
||||
})
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (data.success) {
|
||||
console.log('✅ 手動清理完成:', data.message);
|
||||
return true;
|
||||
} else {
|
||||
console.error('❌ 手動清理失敗:', data.error);
|
||||
return false;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('❌ 手動清理錯誤:', error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// 獲取連線狀態
|
||||
public async getConnectionStatus() {
|
||||
// 確保在瀏覽器環境中執行
|
||||
if (typeof window === 'undefined') return null;
|
||||
|
||||
try {
|
||||
const response = await fetch('/api/ip-cleanup?action=status');
|
||||
const data = await response.json();
|
||||
|
||||
if (data.success) {
|
||||
console.log('📊 連線狀態:', data.data);
|
||||
return data.data;
|
||||
} else {
|
||||
console.error('❌ 獲取連線狀態失敗:', data.error);
|
||||
return null;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('❌ 獲取連線狀態錯誤:', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// 獲取客戶端 ID
|
||||
public getClientId(): string {
|
||||
return this.clientId;
|
||||
}
|
||||
}
|
||||
|
||||
// 導出單例實例
|
||||
export const clientCleanup = ClientConnectionCleanup.getInstance();
|
||||
|
||||
// 在模組載入時自動初始化(只在瀏覽器環境中)
|
||||
if (typeof window !== 'undefined') {
|
||||
// 延遲初始化,確保 DOM 已載入
|
||||
if (document.readyState === 'loading') {
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
clientCleanup;
|
||||
});
|
||||
} else {
|
||||
clientCleanup;
|
||||
}
|
||||
}
|
@@ -1,178 +0,0 @@
|
||||
// =====================================================
|
||||
// 連線生命週期管理器
|
||||
// =====================================================
|
||||
|
||||
import { db } from './database';
|
||||
import { dbFailover } from './database-failover';
|
||||
|
||||
export class ConnectionLifecycleManager {
|
||||
private static instance: ConnectionLifecycleManager;
|
||||
private activeConnections = new Map<string, {
|
||||
connection: any;
|
||||
createdAt: number;
|
||||
lastUsed: number;
|
||||
userId?: string;
|
||||
sessionId?: string;
|
||||
}>();
|
||||
private cleanupInterval: NodeJS.Timeout | null = null;
|
||||
private maxIdleTime = 5 * 60 * 1000; // 5分鐘空閒超時
|
||||
private maxConnectionAge = 30 * 60 * 1000; // 30分鐘最大連線時間
|
||||
|
||||
private constructor() {
|
||||
this.startCleanupProcess();
|
||||
}
|
||||
|
||||
public static getInstance(): ConnectionLifecycleManager {
|
||||
if (!ConnectionLifecycleManager.instance) {
|
||||
ConnectionLifecycleManager.instance = new ConnectionLifecycleManager();
|
||||
}
|
||||
return ConnectionLifecycleManager.instance;
|
||||
}
|
||||
|
||||
// 註冊連線
|
||||
public registerConnection(connectionId: string, connection: any, metadata?: {
|
||||
userId?: string;
|
||||
sessionId?: string;
|
||||
}) {
|
||||
this.activeConnections.set(connectionId, {
|
||||
connection,
|
||||
createdAt: Date.now(),
|
||||
lastUsed: Date.now(),
|
||||
userId: metadata?.userId,
|
||||
sessionId: metadata?.sessionId
|
||||
});
|
||||
|
||||
console.log(`📝 註冊連線: ${connectionId} (總數: ${this.activeConnections.size})`);
|
||||
}
|
||||
|
||||
// 更新連線使用時間
|
||||
public updateConnectionUsage(connectionId: string) {
|
||||
const conn = this.activeConnections.get(connectionId);
|
||||
if (conn) {
|
||||
conn.lastUsed = Date.now();
|
||||
}
|
||||
}
|
||||
|
||||
// 釋放連線
|
||||
public releaseConnection(connectionId: string) {
|
||||
const conn = this.activeConnections.get(connectionId);
|
||||
if (conn) {
|
||||
try {
|
||||
if (conn.connection && typeof conn.connection.release === 'function') {
|
||||
conn.connection.release();
|
||||
}
|
||||
this.activeConnections.delete(connectionId);
|
||||
console.log(`🗑️ 釋放連線: ${connectionId} (剩餘: ${this.activeConnections.size})`);
|
||||
} catch (error) {
|
||||
console.error(`❌ 釋放連線失敗: ${connectionId}`, error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 開始清理程序
|
||||
private startCleanupProcess() {
|
||||
// 每30秒檢查一次空閒連線
|
||||
this.cleanupInterval = setInterval(() => {
|
||||
this.cleanupIdleConnections();
|
||||
}, 30 * 1000);
|
||||
|
||||
console.log('🧹 連線生命週期管理器已啟動');
|
||||
}
|
||||
|
||||
// 清理空閒連線
|
||||
private cleanupIdleConnections() {
|
||||
const now = Date.now();
|
||||
const toRemove: string[] = [];
|
||||
|
||||
for (const [connectionId, conn] of this.activeConnections) {
|
||||
const idleTime = now - conn.lastUsed;
|
||||
const connectionAge = now - conn.createdAt;
|
||||
|
||||
// 檢查空閒時間
|
||||
if (idleTime > this.maxIdleTime) {
|
||||
console.log(`⏰ 連線 ${connectionId} 空閒時間過長 (${Math.round(idleTime / 1000)}s),準備釋放`);
|
||||
toRemove.push(connectionId);
|
||||
}
|
||||
// 檢查連線年齡
|
||||
else if (connectionAge > this.maxConnectionAge) {
|
||||
console.log(`⏰ 連線 ${connectionId} 存在時間過長 (${Math.round(connectionAge / 1000)}s),準備釋放`);
|
||||
toRemove.push(connectionId);
|
||||
}
|
||||
}
|
||||
|
||||
// 釋放需要清理的連線
|
||||
toRemove.forEach(connectionId => {
|
||||
this.releaseConnection(connectionId);
|
||||
});
|
||||
|
||||
if (toRemove.length > 0) {
|
||||
console.log(`🧹 清理了 ${toRemove.length} 個空閒連線`);
|
||||
}
|
||||
}
|
||||
|
||||
// 強制清理所有連線
|
||||
public forceCleanupAll() {
|
||||
console.log('🚨 強制清理所有連線...');
|
||||
|
||||
const connectionIds = Array.from(this.activeConnections.keys());
|
||||
connectionIds.forEach(connectionId => {
|
||||
this.releaseConnection(connectionId);
|
||||
});
|
||||
|
||||
console.log(`✅ 已清理 ${connectionIds.length} 個連線`);
|
||||
}
|
||||
|
||||
// 獲取連線統計
|
||||
public getConnectionStats() {
|
||||
const now = Date.now();
|
||||
const connections = Array.from(this.activeConnections.values());
|
||||
|
||||
const idleConnections = connections.filter(conn =>
|
||||
now - conn.lastUsed > this.maxIdleTime
|
||||
).length;
|
||||
|
||||
const oldConnections = connections.filter(conn =>
|
||||
now - conn.createdAt > this.maxConnectionAge
|
||||
).length;
|
||||
|
||||
return {
|
||||
totalConnections: this.activeConnections.size,
|
||||
idleConnections,
|
||||
oldConnections,
|
||||
maxIdleTime: this.maxIdleTime,
|
||||
maxConnectionAge: this.maxConnectionAge,
|
||||
connections: connections.map(conn => ({
|
||||
createdAt: new Date(conn.createdAt).toISOString(),
|
||||
lastUsed: new Date(conn.lastUsed).toISOString(),
|
||||
idleTime: now - conn.lastUsed,
|
||||
age: now - conn.createdAt,
|
||||
userId: conn.userId,
|
||||
sessionId: conn.sessionId
|
||||
}))
|
||||
};
|
||||
}
|
||||
|
||||
// 停止清理程序
|
||||
public stop() {
|
||||
if (this.cleanupInterval) {
|
||||
clearInterval(this.cleanupInterval);
|
||||
this.cleanupInterval = null;
|
||||
}
|
||||
|
||||
// 清理所有連線
|
||||
this.forceCleanupAll();
|
||||
|
||||
console.log('⏹️ 連線生命週期管理器已停止');
|
||||
}
|
||||
|
||||
// 設置清理參數
|
||||
public setCleanupParams(maxIdleTime?: number, maxConnectionAge?: number) {
|
||||
if (maxIdleTime) this.maxIdleTime = maxIdleTime;
|
||||
if (maxConnectionAge) this.maxConnectionAge = maxConnectionAge;
|
||||
|
||||
console.log(`⚙️ 更新清理參數: 空閒時間=${this.maxIdleTime}ms, 最大年齡=${this.maxConnectionAge}ms`);
|
||||
}
|
||||
}
|
||||
|
||||
// 導出單例實例
|
||||
export const connectionLifecycleManager = ConnectionLifecycleManager.getInstance();
|
@@ -5,7 +5,6 @@
|
||||
import { db } from './database';
|
||||
import { dbFailover } from './database-failover';
|
||||
import { dbMonitor } from './database-monitor';
|
||||
import { smartPool } from './smart-connection-pool';
|
||||
|
||||
export class DatabaseShutdownManager {
|
||||
private static instance: DatabaseShutdownManager;
|
||||
@@ -58,16 +57,6 @@ export class DatabaseShutdownManager {
|
||||
}
|
||||
});
|
||||
|
||||
// 添加智能連線池關閉處理器
|
||||
this.addShutdownHandler('smart-pool', async () => {
|
||||
console.log('🔄 正在清理智能連線池...');
|
||||
try {
|
||||
smartPool.forceCleanup();
|
||||
console.log('✅ 智能連線池已清理');
|
||||
} catch (error) {
|
||||
console.error('❌ 清理智能連線池時發生錯誤:', error);
|
||||
}
|
||||
});
|
||||
|
||||
// 註冊系統信號處理器
|
||||
this.registerSystemHandlers();
|
||||
|
@@ -1,175 +0,0 @@
|
||||
// =====================================================
|
||||
// 緊急連線清理工具
|
||||
// =====================================================
|
||||
|
||||
import { db } from './database';
|
||||
import { dbFailover } from './database-failover';
|
||||
import { dbMonitor } from './database-monitor';
|
||||
|
||||
export class EmergencyConnectionCleanup {
|
||||
private static instance: EmergencyConnectionCleanup;
|
||||
|
||||
private constructor() {}
|
||||
|
||||
public static getInstance(): EmergencyConnectionCleanup {
|
||||
if (!EmergencyConnectionCleanup.instance) {
|
||||
EmergencyConnectionCleanup.instance = new EmergencyConnectionCleanup();
|
||||
}
|
||||
return EmergencyConnectionCleanup.instance;
|
||||
}
|
||||
|
||||
// 立即停止所有監控和清理所有連線
|
||||
public async emergencyCleanup() {
|
||||
console.log('🚨 執行緊急連線清理...');
|
||||
|
||||
try {
|
||||
// 1. 立即停止所有監控
|
||||
console.log('⏹️ 停止資料庫監控...');
|
||||
dbMonitor.stopMonitoring();
|
||||
|
||||
// 2. 強制關閉所有連線池
|
||||
console.log('🔌 關閉主要資料庫連線池...');
|
||||
await db.close();
|
||||
|
||||
console.log('🔌 關閉備援資料庫連線池...');
|
||||
await dbFailover.close();
|
||||
|
||||
// 3. 等待一段時間讓連線完全關閉
|
||||
console.log('⏳ 等待連線關閉...');
|
||||
await new Promise(resolve => setTimeout(resolve, 2000));
|
||||
|
||||
// 4. 檢查連線狀態
|
||||
await this.checkConnectionStatus();
|
||||
|
||||
console.log('✅ 緊急清理完成');
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ 緊急清理失敗:', error);
|
||||
}
|
||||
}
|
||||
|
||||
// 檢查連線狀態(不建立新連線)
|
||||
private async checkConnectionStatus() {
|
||||
try {
|
||||
// 使用一個臨時連線來檢查狀態
|
||||
const tempConnection = await db.getConnection();
|
||||
|
||||
try {
|
||||
const [statusResult] = await tempConnection.execute(`
|
||||
SHOW STATUS LIKE 'Threads_connected'
|
||||
`);
|
||||
|
||||
const [maxConnResult] = await tempConnection.execute(`
|
||||
SHOW VARIABLES LIKE 'max_connections'
|
||||
`);
|
||||
|
||||
const currentConnections = statusResult[0]?.Value || 0;
|
||||
const maxConnections = maxConnResult[0]?.Value || 100;
|
||||
const usagePercentage = (currentConnections / maxConnections) * 100;
|
||||
|
||||
console.log(`📊 清理後連線狀態: ${currentConnections}/${maxConnections} (${usagePercentage.toFixed(1)}%)`);
|
||||
|
||||
if (currentConnections > 5) {
|
||||
console.warn(`⚠️ 仍有 ${currentConnections} 個連線未關閉`);
|
||||
} else {
|
||||
console.log('✅ 連線已成功清理');
|
||||
}
|
||||
|
||||
} finally {
|
||||
tempConnection.release();
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ 檢查連線狀態失敗:', error);
|
||||
}
|
||||
}
|
||||
|
||||
// 強制殺死所有資料庫連線
|
||||
public async forceKillAllConnections() {
|
||||
console.log('💀 強制殺死所有資料庫連線...');
|
||||
|
||||
try {
|
||||
const tempConnection = await db.getConnection();
|
||||
|
||||
try {
|
||||
// 獲取所有連線ID
|
||||
const [connections] = await tempConnection.execute(`
|
||||
SELECT ID FROM information_schema.PROCESSLIST
|
||||
WHERE USER = ? AND COMMAND != 'Sleep'
|
||||
`, [process.env.DB_USER || 'A999']);
|
||||
|
||||
console.log(`🔍 找到 ${connections.length} 個活躍連線`);
|
||||
|
||||
// 殺死所有連線(除了當前連線)
|
||||
for (const conn of connections) {
|
||||
if (conn.ID !== tempConnection.threadId) {
|
||||
try {
|
||||
await tempConnection.execute(`KILL ${conn.ID}`);
|
||||
console.log(`💀 已殺死連線 ${conn.ID}`);
|
||||
} catch (error) {
|
||||
console.log(`⚠️ 無法殺死連線 ${conn.ID}:`, error.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 等待連線關閉
|
||||
await new Promise(resolve => setTimeout(resolve, 1000));
|
||||
|
||||
// 再次檢查狀態
|
||||
await this.checkConnectionStatus();
|
||||
|
||||
} finally {
|
||||
tempConnection.release();
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ 強制殺死連線失敗:', error);
|
||||
}
|
||||
}
|
||||
|
||||
// 獲取連線詳情
|
||||
public async getConnectionDetails() {
|
||||
try {
|
||||
const tempConnection = await db.getConnection();
|
||||
|
||||
try {
|
||||
const [connections] = await tempConnection.execute(`
|
||||
SELECT
|
||||
ID,
|
||||
USER,
|
||||
HOST,
|
||||
DB,
|
||||
COMMAND,
|
||||
TIME,
|
||||
STATE,
|
||||
INFO
|
||||
FROM information_schema.PROCESSLIST
|
||||
WHERE USER = ?
|
||||
ORDER BY TIME DESC
|
||||
`, [process.env.DB_USER || 'A999']);
|
||||
|
||||
console.log('📋 當前資料庫連線詳情:');
|
||||
connections.forEach((conn, index) => {
|
||||
console.log(`${index + 1}. ID: ${conn.ID}, 用戶: ${conn.USER}, 時間: ${conn.TIME}s, 狀態: ${conn.STATE}`);
|
||||
if (conn.INFO && conn.INFO.length > 50) {
|
||||
console.log(` 查詢: ${conn.INFO.substring(0, 50)}...`);
|
||||
} else if (conn.INFO) {
|
||||
console.log(` 查詢: ${conn.INFO}`);
|
||||
}
|
||||
});
|
||||
|
||||
return connections;
|
||||
|
||||
} finally {
|
||||
tempConnection.release();
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ 獲取連線詳情失敗:', error);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 導出單例實例
|
||||
export const emergencyCleanup = EmergencyConnectionCleanup.getInstance();
|
@@ -1,251 +0,0 @@
|
||||
// =====================================================
|
||||
// 基於 IP 的連線管理器
|
||||
// =====================================================
|
||||
|
||||
import mysql from 'mysql2/promise';
|
||||
import { db } from './database';
|
||||
|
||||
export class IPBasedConnectionManager {
|
||||
private static instance: IPBasedConnectionManager;
|
||||
private clientIP: string | null = null;
|
||||
private connectionTracker = new Map<string, {
|
||||
connectionId: string;
|
||||
createdAt: number;
|
||||
lastUsed: number;
|
||||
userAgent?: string;
|
||||
}>();
|
||||
|
||||
private constructor() {
|
||||
this.detectClientIP();
|
||||
}
|
||||
|
||||
public static getInstance(): IPBasedConnectionManager {
|
||||
if (!IPBasedConnectionManager.instance) {
|
||||
IPBasedConnectionManager.instance = new IPBasedConnectionManager();
|
||||
}
|
||||
return IPBasedConnectionManager.instance;
|
||||
}
|
||||
|
||||
// 檢測客戶端 IP
|
||||
private detectClientIP() {
|
||||
// 在瀏覽器環境中,我們無法直接獲取真實 IP
|
||||
// 但我們可以通過其他方式來識別連線
|
||||
if (typeof window !== 'undefined') {
|
||||
// 客戶端:生成一個唯一標識符
|
||||
this.clientIP = this.generateClientId();
|
||||
console.log('🖥️ 客戶端標識符:', this.clientIP);
|
||||
} else {
|
||||
// 服務端:嘗試從環境變數或請求中獲取
|
||||
this.clientIP = process.env.CLIENT_IP || 'server-side';
|
||||
console.log('🖥️ 服務端標識符:', this.clientIP);
|
||||
}
|
||||
}
|
||||
|
||||
// 生成客戶端唯一標識符
|
||||
private generateClientId(): string {
|
||||
const timestamp = Date.now();
|
||||
const random = Math.random().toString(36).substring(2);
|
||||
return `client_${timestamp}_${random}`;
|
||||
}
|
||||
|
||||
// 設置客戶端 IP(從請求中獲取)
|
||||
public setClientIP(ip: string) {
|
||||
this.clientIP = ip;
|
||||
console.log('🖥️ 設置客戶端 IP:', ip);
|
||||
}
|
||||
|
||||
// 獲取客戶端 IP
|
||||
public getClientIP(): string | null {
|
||||
return this.clientIP;
|
||||
}
|
||||
|
||||
// 註冊連線(帶 IP 標識)
|
||||
public registerConnection(connectionId: string, metadata?: {
|
||||
userAgent?: string;
|
||||
requestId?: string;
|
||||
}) {
|
||||
if (!this.clientIP) return;
|
||||
|
||||
this.connectionTracker.set(connectionId, {
|
||||
connectionId,
|
||||
createdAt: Date.now(),
|
||||
lastUsed: Date.now(),
|
||||
userAgent: metadata?.userAgent,
|
||||
});
|
||||
|
||||
console.log(`📝 註冊連線: ${connectionId} (IP: ${this.clientIP})`);
|
||||
}
|
||||
|
||||
// 更新連線使用時間
|
||||
public updateConnectionUsage(connectionId: string) {
|
||||
const conn = this.connectionTracker.get(connectionId);
|
||||
if (conn) {
|
||||
conn.lastUsed = Date.now();
|
||||
}
|
||||
}
|
||||
|
||||
// 釋放連線
|
||||
public releaseConnection(connectionId: string) {
|
||||
const conn = this.connectionTracker.get(connectionId);
|
||||
if (conn) {
|
||||
this.connectionTracker.delete(connectionId);
|
||||
console.log(`🗑️ 釋放連線: ${connectionId} (IP: ${this.clientIP})`);
|
||||
}
|
||||
}
|
||||
|
||||
// 根據 IP 清理連線
|
||||
public async cleanupConnectionsByIP(targetIP?: string): Promise<{
|
||||
success: boolean;
|
||||
killedCount: number;
|
||||
message: string;
|
||||
}> {
|
||||
const ipToClean = targetIP || this.clientIP;
|
||||
|
||||
if (!ipToClean) {
|
||||
return {
|
||||
success: false,
|
||||
killedCount: 0,
|
||||
message: '無法識別客戶端 IP'
|
||||
};
|
||||
}
|
||||
|
||||
console.log(`🧹 開始清理 IP ${ipToClean} 的連線...`);
|
||||
|
||||
let connection = null;
|
||||
let killedCount = 0;
|
||||
|
||||
try {
|
||||
// 建立臨時連線
|
||||
connection = await db.getConnection();
|
||||
|
||||
// 獲取指定 IP 的所有連線(使用更寬鬆的匹配)
|
||||
const [connections] = await connection.execute(`
|
||||
SELECT ID, USER, HOST, DB, COMMAND, TIME, STATE, INFO
|
||||
FROM information_schema.PROCESSLIST
|
||||
WHERE USER = ? AND (HOST LIKE ? OR HOST LIKE ? OR HOST LIKE ?)
|
||||
ORDER BY TIME DESC
|
||||
`, [
|
||||
process.env.DB_USER || 'A999',
|
||||
`%${ipToClean}%`, // 包含 IP 的 HOST
|
||||
`%${ipToClean}.%`, // IP 開頭的 HOST
|
||||
`%${ipToClean}-%` // IP 帶連字符的 HOST
|
||||
]);
|
||||
|
||||
console.log(`🔍 找到 ${connections.length} 個來自 ${ipToClean} 的連線`);
|
||||
|
||||
// 顯示連線詳情
|
||||
connections.forEach((conn: any, index: number) => {
|
||||
console.log(`${index + 1}. ID: ${conn.ID}, HOST: ${conn.HOST}, 時間: ${conn.TIME}s, 狀態: ${conn.STATE}`);
|
||||
});
|
||||
|
||||
// 殺死指定 IP 的連線(除了當前連線)
|
||||
for (const conn of connections) {
|
||||
if (conn.ID !== connection.threadId) {
|
||||
try {
|
||||
await connection.execute(`KILL ${conn.ID}`);
|
||||
console.log(`💀 已殺死連線 ${conn.ID} (HOST: ${conn.HOST})`);
|
||||
killedCount++;
|
||||
} catch (error: any) {
|
||||
console.log(`⚠️ 無法殺死連線 ${conn.ID}: ${error.message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 清理本地追蹤的連線
|
||||
this.connectionTracker.clear();
|
||||
|
||||
console.log(`✅ 已清理 ${killedCount} 個來自 ${ipToClean} 的連線`);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
killedCount,
|
||||
message: `已清理 ${killedCount} 個來自 ${ipToClean} 的連線`
|
||||
};
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ 清理連線失敗:', error);
|
||||
return {
|
||||
success: false,
|
||||
killedCount: 0,
|
||||
message: `清理失敗: ${error instanceof Error ? error.message : '未知錯誤'}`
|
||||
};
|
||||
} finally {
|
||||
if (connection) {
|
||||
connection.release();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 獲取指定 IP 的連線狀態
|
||||
public async getConnectionsByIP(targetIP?: string): Promise<{
|
||||
ip: string;
|
||||
connectionCount: number;
|
||||
connections: any[];
|
||||
}> {
|
||||
const ipToCheck = targetIP || this.clientIP;
|
||||
|
||||
if (!ipToCheck) {
|
||||
return {
|
||||
ip: 'unknown',
|
||||
connectionCount: 0,
|
||||
connections: []
|
||||
};
|
||||
}
|
||||
|
||||
let connection = null;
|
||||
|
||||
try {
|
||||
connection = await db.getConnection();
|
||||
|
||||
const [connections] = await connection.execute(`
|
||||
SELECT ID, USER, HOST, DB, COMMAND, TIME, STATE, INFO
|
||||
FROM information_schema.PROCESSLIST
|
||||
WHERE USER = ? AND HOST LIKE ?
|
||||
ORDER BY TIME DESC
|
||||
`, [process.env.DB_USER || 'A999', `%${ipToCheck}%`]);
|
||||
|
||||
return {
|
||||
ip: ipToCheck,
|
||||
connectionCount: connections.length,
|
||||
connections: connections
|
||||
};
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ 獲取連線狀態失敗:', error);
|
||||
return {
|
||||
ip: ipToCheck,
|
||||
connectionCount: 0,
|
||||
connections: []
|
||||
};
|
||||
} finally {
|
||||
if (connection) {
|
||||
connection.release();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 清理所有本地追蹤的連線
|
||||
public cleanupLocalConnections() {
|
||||
const count = this.connectionTracker.size;
|
||||
this.connectionTracker.clear();
|
||||
console.log(`🧹 已清理 ${count} 個本地追蹤的連線`);
|
||||
return count;
|
||||
}
|
||||
|
||||
// 獲取本地連線統計
|
||||
public getLocalConnectionStats() {
|
||||
return {
|
||||
clientIP: this.clientIP,
|
||||
trackedConnections: this.connectionTracker.size,
|
||||
connections: Array.from(this.connectionTracker.values()).map(conn => ({
|
||||
connectionId: conn.connectionId,
|
||||
createdAt: new Date(conn.createdAt).toISOString(),
|
||||
lastUsed: new Date(conn.lastUsed).toISOString(),
|
||||
userAgent: conn.userAgent
|
||||
}))
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// 導出單例實例
|
||||
export const ipConnectionManager = IPBasedConnectionManager.getInstance();
|
@@ -1,280 +0,0 @@
|
||||
// =====================================================
|
||||
// 智能連線清理器
|
||||
// =====================================================
|
||||
|
||||
import mysql from 'mysql2/promise';
|
||||
import { db } from './database';
|
||||
import { smartIPDetector } from './smart-ip-detector';
|
||||
import { NextRequest } from 'next/server';
|
||||
|
||||
export interface CleanupResult {
|
||||
success: boolean;
|
||||
killedCount: number;
|
||||
message: string;
|
||||
details: {
|
||||
userRealIP?: string;
|
||||
infrastructureIPs?: string[];
|
||||
cleanedConnections: Array<{
|
||||
id: number;
|
||||
host: string;
|
||||
time: number;
|
||||
state: string;
|
||||
}>;
|
||||
};
|
||||
}
|
||||
|
||||
export class SmartConnectionCleaner {
|
||||
private static instance: SmartConnectionCleaner;
|
||||
|
||||
public static getInstance(): SmartConnectionCleaner {
|
||||
if (!SmartConnectionCleaner.instance) {
|
||||
SmartConnectionCleaner.instance = new SmartConnectionCleaner();
|
||||
}
|
||||
return SmartConnectionCleaner.instance;
|
||||
}
|
||||
|
||||
// 智能清理連線
|
||||
public async smartCleanup(request: NextRequest): Promise<CleanupResult> {
|
||||
try {
|
||||
// 1. 使用智能 IP 偵測器獲取真實 IP
|
||||
const ipDetection = smartIPDetector.detectClientIP(request);
|
||||
const userRealIP = ipDetection.detectedIP;
|
||||
|
||||
console.log('🧠 智能清理開始:', {
|
||||
detectedIP: userRealIP,
|
||||
confidence: ipDetection.confidence,
|
||||
source: ipDetection.source,
|
||||
isUserRealIP: ipDetection.isUserRealIP,
|
||||
infrastructureIPs: ipDetection.infrastructureIPs
|
||||
});
|
||||
|
||||
// 2. 建立資料庫連線
|
||||
const connection = await db.getConnection();
|
||||
let killedCount = 0;
|
||||
const cleanedConnections: Array<{
|
||||
id: number;
|
||||
host: string;
|
||||
time: number;
|
||||
state: string;
|
||||
}> = [];
|
||||
|
||||
try {
|
||||
// 3. 獲取所有相關連線
|
||||
const [allConnections] = await connection.execute(`
|
||||
SELECT ID, USER, HOST, DB, COMMAND, TIME, STATE, INFO
|
||||
FROM information_schema.PROCESSLIST
|
||||
WHERE USER = ?
|
||||
ORDER BY TIME DESC
|
||||
`, [process.env.DB_USER || 'A999']);
|
||||
|
||||
console.log(`🔍 找到 ${allConnections.length} 個總連線`);
|
||||
|
||||
// 4. 分類連線
|
||||
const userConnections = allConnections.filter((conn: any) =>
|
||||
this.isUserConnection(conn.HOST, userRealIP)
|
||||
);
|
||||
|
||||
const infrastructureConnections = allConnections.filter((conn: any) =>
|
||||
this.isInfrastructureConnection(conn.HOST)
|
||||
);
|
||||
|
||||
console.log(`👤 用戶連線: ${userConnections.length} 個`);
|
||||
console.log(`🏗️ 基礎設施連線: ${infrastructureConnections.length} 個`);
|
||||
|
||||
// 5. 清理用戶連線(優先)
|
||||
if (userConnections.length > 0) {
|
||||
console.log(`🧹 開始清理用戶連線 (IP: ${userRealIP})`);
|
||||
|
||||
for (const conn of userConnections) {
|
||||
if (conn.ID !== connection.threadId) {
|
||||
try {
|
||||
await connection.execute(`KILL ${conn.ID}`);
|
||||
console.log(`💀 已殺死用戶連線 ${conn.ID} (HOST: ${conn.HOST})`);
|
||||
killedCount++;
|
||||
cleanedConnections.push({
|
||||
id: conn.ID,
|
||||
host: conn.HOST,
|
||||
time: conn.TIME,
|
||||
state: conn.STATE || 'Sleep'
|
||||
});
|
||||
} catch (error: any) {
|
||||
console.log(`⚠️ 無法殺死用戶連線 ${conn.ID}: ${error.message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 6. 清理基礎設施連線(可選,根據配置)
|
||||
const shouldCleanInfrastructure = process.env.CLEAN_INFRASTRUCTURE_CONNECTIONS === 'true';
|
||||
|
||||
if (shouldCleanInfrastructure && infrastructureConnections.length > 0) {
|
||||
console.log(`🧹 開始清理基礎設施連線`);
|
||||
|
||||
for (const conn of infrastructureConnections) {
|
||||
if (conn.ID !== connection.threadId) {
|
||||
try {
|
||||
await connection.execute(`KILL ${conn.ID}`);
|
||||
console.log(`💀 已殺死基礎設施連線 ${conn.ID} (HOST: ${conn.HOST})`);
|
||||
killedCount++;
|
||||
cleanedConnections.push({
|
||||
id: conn.ID,
|
||||
host: conn.HOST,
|
||||
time: conn.TIME,
|
||||
state: conn.STATE || 'Sleep'
|
||||
});
|
||||
} catch (error: any) {
|
||||
console.log(`⚠️ 無法殺死基礎設施連線 ${conn.ID}: ${error.message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`✅ 智能清理完成: 共清理 ${killedCount} 個連線`);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
killedCount,
|
||||
message: `智能清理完成: 共清理 ${killedCount} 個連線`,
|
||||
details: {
|
||||
userRealIP: userRealIP !== 'unknown' ? userRealIP : undefined,
|
||||
infrastructureIPs: ipDetection.infrastructureIPs,
|
||||
cleanedConnections
|
||||
}
|
||||
};
|
||||
|
||||
} finally {
|
||||
connection.release();
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ 智能清理失敗:', error);
|
||||
return {
|
||||
success: false,
|
||||
killedCount: 0,
|
||||
message: `智能清理失敗: ${error instanceof Error ? error.message : '未知錯誤'}`,
|
||||
details: {
|
||||
cleanedConnections: []
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// 檢查是否為用戶連線
|
||||
private isUserConnection(host: string, userIP: string): boolean {
|
||||
if (!host || !userIP || userIP === 'unknown') return false;
|
||||
|
||||
// 直接匹配用戶 IP
|
||||
if (host.includes(userIP)) return true;
|
||||
|
||||
// 匹配用戶 IP 的變體格式
|
||||
const ipVariants = [
|
||||
userIP,
|
||||
userIP.replace(/\./g, '-'), // 61.227.253.171 -> 61-227-253-171
|
||||
userIP.replace(/\./g, '_'), // 61.227.253.171 -> 61_227_253_171
|
||||
];
|
||||
|
||||
return ipVariants.some(variant => host.includes(variant));
|
||||
}
|
||||
|
||||
// 檢查是否為基礎設施連線
|
||||
private isInfrastructureConnection(host: string): boolean {
|
||||
if (!host) return false;
|
||||
|
||||
// AWS EC2 實例
|
||||
if (host.includes('ec2-') && host.includes('.amazonaws.com')) return true;
|
||||
|
||||
// 其他基礎設施模式
|
||||
const infrastructurePatterns = [
|
||||
'.amazonaws.com',
|
||||
'.vercel.app',
|
||||
'vercel',
|
||||
'cloudflare',
|
||||
'fastly.com',
|
||||
'cloudfront.net'
|
||||
];
|
||||
|
||||
return infrastructurePatterns.some(pattern => host.includes(pattern));
|
||||
}
|
||||
|
||||
// 獲取連線統計
|
||||
public async getConnectionStats(): Promise<{
|
||||
total: number;
|
||||
user: number;
|
||||
infrastructure: number;
|
||||
other: number;
|
||||
details: Array<{
|
||||
id: number;
|
||||
host: string;
|
||||
time: number;
|
||||
state: string;
|
||||
type: 'user' | 'infrastructure' | 'other';
|
||||
}>;
|
||||
}> {
|
||||
try {
|
||||
const connection = await db.getConnection();
|
||||
|
||||
try {
|
||||
const [connections] = await connection.execute(`
|
||||
SELECT ID, USER, HOST, DB, COMMAND, TIME, STATE, INFO
|
||||
FROM information_schema.PROCESSLIST
|
||||
WHERE USER = ?
|
||||
ORDER BY TIME DESC
|
||||
`, [process.env.DB_USER || 'A999']);
|
||||
|
||||
const stats = {
|
||||
total: connections.length,
|
||||
user: 0,
|
||||
infrastructure: 0,
|
||||
other: 0,
|
||||
details: [] as Array<{
|
||||
id: number;
|
||||
host: string;
|
||||
time: number;
|
||||
state: string;
|
||||
type: 'user' | 'infrastructure' | 'other';
|
||||
}>
|
||||
};
|
||||
|
||||
for (const conn of connections) {
|
||||
let type: 'user' | 'infrastructure' | 'other' = 'other';
|
||||
|
||||
if (this.isInfrastructureConnection(conn.HOST)) {
|
||||
type = 'infrastructure';
|
||||
stats.infrastructure++;
|
||||
} else if (this.isUserConnection(conn.HOST, 'unknown')) {
|
||||
type = 'user';
|
||||
stats.user++;
|
||||
} else {
|
||||
stats.other++;
|
||||
}
|
||||
|
||||
stats.details.push({
|
||||
id: conn.ID,
|
||||
host: conn.HOST,
|
||||
time: conn.TIME,
|
||||
state: conn.STATE || 'Sleep',
|
||||
type
|
||||
});
|
||||
}
|
||||
|
||||
return stats;
|
||||
|
||||
} finally {
|
||||
connection.release();
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ 獲取連線統計失敗:', error);
|
||||
return {
|
||||
total: 0,
|
||||
user: 0,
|
||||
infrastructure: 0,
|
||||
other: 0,
|
||||
details: []
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 導出單例實例
|
||||
export const smartConnectionCleaner = SmartConnectionCleaner.getInstance();
|
@@ -1,202 +0,0 @@
|
||||
// =====================================================
|
||||
// 智能連線池包裝器
|
||||
// =====================================================
|
||||
|
||||
import { db } from './database';
|
||||
import { dbFailover } from './database-failover';
|
||||
import { connectionLifecycleManager } from './connection-lifecycle-manager';
|
||||
|
||||
export class SmartConnectionPool {
|
||||
private static instance: SmartConnectionPool;
|
||||
private connectionCounter = 0;
|
||||
|
||||
private constructor() {}
|
||||
|
||||
public static getInstance(): SmartConnectionPool {
|
||||
if (!SmartConnectionPool.instance) {
|
||||
SmartConnectionPool.instance = new SmartConnectionPool();
|
||||
}
|
||||
return SmartConnectionPool.instance;
|
||||
}
|
||||
|
||||
// 獲取智能連線
|
||||
public async getSmartConnection(metadata?: {
|
||||
userId?: string;
|
||||
sessionId?: string;
|
||||
requestId?: string;
|
||||
}): Promise<{
|
||||
connection: any;
|
||||
connectionId: string;
|
||||
release: () => void;
|
||||
}> {
|
||||
const connectionId = `conn_${++this.connectionCounter}_${Date.now()}`;
|
||||
|
||||
try {
|
||||
// 獲取實際連線
|
||||
const connection = await db.getConnection();
|
||||
|
||||
// 註冊到生命週期管理器
|
||||
connectionLifecycleManager.registerConnection(connectionId, connection, metadata);
|
||||
|
||||
// 創建包裝的釋放函數
|
||||
const release = () => {
|
||||
connectionLifecycleManager.releaseConnection(connectionId);
|
||||
};
|
||||
|
||||
console.log(`🔗 獲取智能連線: ${connectionId}`);
|
||||
|
||||
return {
|
||||
connection,
|
||||
connectionId,
|
||||
release
|
||||
};
|
||||
} catch (error) {
|
||||
console.error(`❌ 獲取智能連線失敗: ${connectionId}`, error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// 執行智能查詢
|
||||
public async executeQuery<T = any>(
|
||||
sql: string,
|
||||
params?: any[],
|
||||
metadata?: {
|
||||
userId?: string;
|
||||
sessionId?: string;
|
||||
requestId?: string;
|
||||
}
|
||||
): Promise<T[]> {
|
||||
const { connection, connectionId, release } = await this.getSmartConnection(metadata);
|
||||
|
||||
try {
|
||||
// 更新連線使用時間
|
||||
connectionLifecycleManager.updateConnectionUsage(connectionId);
|
||||
|
||||
// 執行查詢
|
||||
const [rows] = await connection.execute(sql, params);
|
||||
return rows as T[];
|
||||
} catch (error) {
|
||||
console.error(`❌ 智能查詢失敗: ${connectionId}`, error);
|
||||
throw error;
|
||||
} finally {
|
||||
// 確保釋放連線
|
||||
release();
|
||||
}
|
||||
}
|
||||
|
||||
// 執行智能單一查詢
|
||||
public async executeQueryOne<T = any>(
|
||||
sql: string,
|
||||
params?: any[],
|
||||
metadata?: {
|
||||
userId?: string;
|
||||
sessionId?: string;
|
||||
requestId?: string;
|
||||
}
|
||||
): Promise<T | null> {
|
||||
const results = await this.executeQuery<T>(sql, params, metadata);
|
||||
return results.length > 0 ? results[0] : null;
|
||||
}
|
||||
|
||||
// 執行智能插入
|
||||
public async executeInsert(
|
||||
sql: string,
|
||||
params?: any[],
|
||||
metadata?: {
|
||||
userId?: string;
|
||||
sessionId?: string;
|
||||
requestId?: string;
|
||||
}
|
||||
): Promise<any> {
|
||||
const { connection, connectionId, release } = await this.getSmartConnection(metadata);
|
||||
|
||||
try {
|
||||
// 更新連線使用時間
|
||||
connectionLifecycleManager.updateConnectionUsage(connectionId);
|
||||
|
||||
// 執行插入
|
||||
const [result] = await connection.execute(sql, params);
|
||||
return result;
|
||||
} catch (error) {
|
||||
console.error(`❌ 智能插入失敗: ${connectionId}`, error);
|
||||
throw error;
|
||||
} finally {
|
||||
// 確保釋放連線
|
||||
release();
|
||||
}
|
||||
}
|
||||
|
||||
// 執行智能更新
|
||||
public async executeUpdate(
|
||||
sql: string,
|
||||
params?: any[],
|
||||
metadata?: {
|
||||
userId?: string;
|
||||
sessionId?: string;
|
||||
requestId?: string;
|
||||
}
|
||||
): Promise<any> {
|
||||
const { connection, connectionId, release } = await this.getSmartConnection(metadata);
|
||||
|
||||
try {
|
||||
// 更新連線使用時間
|
||||
connectionLifecycleManager.updateConnectionUsage(connectionId);
|
||||
|
||||
// 執行更新
|
||||
const [result] = await connection.execute(sql, params);
|
||||
return result;
|
||||
} catch (error) {
|
||||
console.error(`❌ 智能更新失敗: ${connectionId}`, error);
|
||||
throw error;
|
||||
} finally {
|
||||
// 確保釋放連線
|
||||
release();
|
||||
}
|
||||
}
|
||||
|
||||
// 執行智能刪除
|
||||
public async executeDelete(
|
||||
sql: string,
|
||||
params?: any[],
|
||||
metadata?: {
|
||||
userId?: string;
|
||||
sessionId?: string;
|
||||
requestId?: string;
|
||||
}
|
||||
): Promise<any> {
|
||||
const { connection, connectionId, release } = await this.getSmartConnection(metadata);
|
||||
|
||||
try {
|
||||
// 更新連線使用時間
|
||||
connectionLifecycleManager.updateConnectionUsage(connectionId);
|
||||
|
||||
// 執行刪除
|
||||
const [result] = await connection.execute(sql, params);
|
||||
return result;
|
||||
} catch (error) {
|
||||
console.error(`❌ 智能刪除失敗: ${connectionId}`, error);
|
||||
throw error;
|
||||
} finally {
|
||||
// 確保釋放連線
|
||||
release();
|
||||
}
|
||||
}
|
||||
|
||||
// 獲取連線統計
|
||||
public getConnectionStats() {
|
||||
return connectionLifecycleManager.getConnectionStats();
|
||||
}
|
||||
|
||||
// 強制清理所有連線
|
||||
public forceCleanup() {
|
||||
connectionLifecycleManager.forceCleanupAll();
|
||||
}
|
||||
|
||||
// 設置清理參數
|
||||
public setCleanupParams(maxIdleTime?: number, maxConnectionAge?: number) {
|
||||
connectionLifecycleManager.setCleanupParams(maxIdleTime, maxConnectionAge);
|
||||
}
|
||||
}
|
||||
|
||||
// 導出單例實例
|
||||
export const smartPool = SmartConnectionPool.getInstance();
|
@@ -1,153 +0,0 @@
|
||||
// =====================================================
|
||||
// 智能 IP 連線池
|
||||
// =====================================================
|
||||
|
||||
import { db } from './database';
|
||||
import { ipConnectionManager } from './ip-based-connection-manager';
|
||||
|
||||
export class SmartIPConnectionPool {
|
||||
private static instance: SmartIPConnectionPool;
|
||||
private connectionCounter = 0;
|
||||
|
||||
private constructor() {}
|
||||
|
||||
public static getInstance(): SmartIPConnectionPool {
|
||||
if (!SmartIPConnectionPool.instance) {
|
||||
SmartIPConnectionPool.instance = new SmartIPConnectionPool();
|
||||
}
|
||||
return SmartIPConnectionPool.instance;
|
||||
}
|
||||
|
||||
// 設置客戶端 IP
|
||||
public setClientIP(ip: string) {
|
||||
ipConnectionManager.setClientIP(ip);
|
||||
}
|
||||
|
||||
// 獲取智能連線(帶 IP 追蹤)
|
||||
public async getSmartConnection(metadata?: {
|
||||
userAgent?: string;
|
||||
requestId?: string;
|
||||
clientIP?: string;
|
||||
}): Promise<{
|
||||
connection: any;
|
||||
connectionId: string;
|
||||
release: () => void;
|
||||
}> {
|
||||
const connectionId = `conn_${++this.connectionCounter}_${Date.now()}`;
|
||||
|
||||
// 設置客戶端 IP
|
||||
if (metadata?.clientIP) {
|
||||
ipConnectionManager.setClientIP(metadata.clientIP);
|
||||
}
|
||||
|
||||
try {
|
||||
// 獲取實際連線
|
||||
const connection = await db.getConnection();
|
||||
|
||||
// 註冊到 IP 連線管理器
|
||||
ipConnectionManager.registerConnection(connectionId, {
|
||||
userAgent: metadata?.userAgent,
|
||||
requestId: metadata?.requestId
|
||||
});
|
||||
|
||||
// 創建包裝的釋放函數
|
||||
const release = () => {
|
||||
ipConnectionManager.releaseConnection(connectionId);
|
||||
};
|
||||
|
||||
console.log(`🔗 獲取智能 IP 連線: ${connectionId}`);
|
||||
|
||||
return {
|
||||
connection,
|
||||
connectionId,
|
||||
release
|
||||
};
|
||||
} catch (error) {
|
||||
console.error(`❌ 獲取智能 IP 連線失敗: ${connectionId}`, error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// 執行智能查詢(帶 IP 追蹤)
|
||||
public async executeQuery<T = any>(
|
||||
sql: string,
|
||||
params?: any[],
|
||||
metadata?: {
|
||||
userAgent?: string;
|
||||
requestId?: string;
|
||||
clientIP?: string;
|
||||
}
|
||||
): Promise<T[]> {
|
||||
const { connection, connectionId, release } = await this.getSmartConnection(metadata);
|
||||
|
||||
try {
|
||||
// 更新連線使用時間
|
||||
ipConnectionManager.updateConnectionUsage(connectionId);
|
||||
|
||||
// 執行查詢
|
||||
const [rows] = await connection.execute(sql, params);
|
||||
return rows as T[];
|
||||
} catch (error) {
|
||||
console.error(`❌ 智能 IP 查詢失敗: ${connectionId}`, error);
|
||||
throw error;
|
||||
} finally {
|
||||
// 確保釋放連線
|
||||
release();
|
||||
}
|
||||
}
|
||||
|
||||
// 執行智能單一查詢
|
||||
public async executeQueryOne<T = any>(
|
||||
sql: string,
|
||||
params?: any[],
|
||||
metadata?: {
|
||||
userAgent?: string;
|
||||
requestId?: string;
|
||||
clientIP?: string;
|
||||
}
|
||||
): Promise<T | null> {
|
||||
const results = await this.executeQuery<T>(sql, params, metadata);
|
||||
return results.length > 0 ? results[0] : null;
|
||||
}
|
||||
|
||||
// 清理當前 IP 的所有連線
|
||||
public async cleanupCurrentIPConnections(): Promise<{
|
||||
success: boolean;
|
||||
killedCount: number;
|
||||
message: string;
|
||||
}> {
|
||||
return await ipConnectionManager.cleanupConnectionsByIP();
|
||||
}
|
||||
|
||||
// 清理指定 IP 的所有連線
|
||||
public async cleanupIPConnections(targetIP: string): Promise<{
|
||||
success: boolean;
|
||||
killedCount: number;
|
||||
message: string;
|
||||
}> {
|
||||
return await ipConnectionManager.cleanupConnectionsByIP(targetIP);
|
||||
}
|
||||
|
||||
// 獲取當前 IP 的連線狀態
|
||||
public async getCurrentIPConnections() {
|
||||
return await ipConnectionManager.getConnectionsByIP();
|
||||
}
|
||||
|
||||
// 獲取指定 IP 的連線狀態
|
||||
public async getIPConnections(targetIP: string) {
|
||||
return await ipConnectionManager.getConnectionsByIP(targetIP);
|
||||
}
|
||||
|
||||
// 獲取本地連線統計
|
||||
public getLocalConnectionStats() {
|
||||
return ipConnectionManager.getLocalConnectionStats();
|
||||
}
|
||||
|
||||
// 清理本地追蹤的連線
|
||||
public cleanupLocalConnections() {
|
||||
return ipConnectionManager.cleanupLocalConnections();
|
||||
}
|
||||
}
|
||||
|
||||
// 導出單例實例
|
||||
export const smartIPPool = SmartIPConnectionPool.getInstance();
|
@@ -1,272 +0,0 @@
|
||||
// =====================================================
|
||||
// 智能 IP 偵測器
|
||||
// =====================================================
|
||||
|
||||
import { NextRequest } from 'next/server';
|
||||
|
||||
export interface IPDetectionResult {
|
||||
detectedIP: string;
|
||||
confidence: 'high' | 'medium' | 'low';
|
||||
source: string;
|
||||
allCandidates: string[];
|
||||
isPublicIP: boolean;
|
||||
}
|
||||
|
||||
export class SmartIPDetector {
|
||||
private static instance: SmartIPDetector;
|
||||
|
||||
public static getInstance(): SmartIPDetector {
|
||||
if (!SmartIPDetector.instance) {
|
||||
SmartIPDetector.instance = new SmartIPDetector();
|
||||
}
|
||||
return SmartIPDetector.instance;
|
||||
}
|
||||
|
||||
// 檢查是否為公網 IP
|
||||
private isPublicIP(ip: string): boolean {
|
||||
if (!ip || ip === 'unknown') return false;
|
||||
|
||||
// 本地地址
|
||||
if (ip === '127.0.0.1' || ip === '::1' || ip === 'localhost') return false;
|
||||
|
||||
// 私有地址範圍
|
||||
if (ip.startsWith('192.168.') ||
|
||||
ip.startsWith('10.') ||
|
||||
ip.startsWith('172.') ||
|
||||
ip.startsWith('169.254.')) return false;
|
||||
|
||||
// IPv6 本地地址
|
||||
if (ip.startsWith('fe80:') ||
|
||||
ip.startsWith('::1') ||
|
||||
ip.startsWith('::ffff:127.0.0.1')) return false;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
// 檢查是否為基礎設施 IP(Vercel、AWS、Cloudflare 等)
|
||||
private isInfrastructureIP(ip: string): boolean {
|
||||
if (!ip) return false;
|
||||
|
||||
// Vercel/AWS EC2 實例
|
||||
if (ip.includes('ec2-') && ip.includes('.compute-1.amazonaws.com')) return true;
|
||||
if (ip.includes('ec2-') && ip.includes('.amazonaws.com')) return true;
|
||||
|
||||
// AWS 其他服務
|
||||
if (ip.includes('.amazonaws.com')) return true;
|
||||
|
||||
// Vercel 相關
|
||||
if (ip.includes('vercel')) return true;
|
||||
|
||||
// Cloudflare 相關(但 cf-connecting-ip 是我們想要的)
|
||||
if (ip.includes('cloudflare') && !ip.includes('cf-connecting-ip')) return true;
|
||||
|
||||
// 其他常見的 CDN/代理服務
|
||||
const infrastructurePatterns = [
|
||||
'fastly.com',
|
||||
'cloudfront.net',
|
||||
'akamai.net',
|
||||
'maxcdn.com',
|
||||
'keycdn.com'
|
||||
];
|
||||
|
||||
return infrastructurePatterns.some(pattern => ip.includes(pattern));
|
||||
}
|
||||
|
||||
// 檢查是否為用戶真實 IP
|
||||
private isUserRealIP(ip: string): boolean {
|
||||
if (!ip || ip === 'unknown') return false;
|
||||
|
||||
// 不是基礎設施 IP
|
||||
if (this.isInfrastructureIP(ip)) return false;
|
||||
|
||||
// 是公網 IP
|
||||
if (!this.isPublicIP(ip)) return false;
|
||||
|
||||
// 是有效的 IP 格式
|
||||
if (!this.isValidIP(ip)) return false;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
// 從 x-forwarded-for 解析 IP
|
||||
private parseForwardedFor(forwarded: string): string[] {
|
||||
if (!forwarded) return [];
|
||||
|
||||
return forwarded
|
||||
.split(',')
|
||||
.map(ip => ip.trim())
|
||||
.filter(ip => ip && ip !== 'unknown');
|
||||
}
|
||||
|
||||
// 智能偵測客戶端 IP
|
||||
public detectClientIP(request: NextRequest): IPDetectionResult {
|
||||
const candidates: string[] = [];
|
||||
const sources: { [key: string]: string } = {};
|
||||
|
||||
// 1. 收集所有可能的 IP 來源
|
||||
const 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'),
|
||||
};
|
||||
|
||||
// 2. 從各個標頭提取 IP
|
||||
Object.entries(headers).forEach(([header, value]) => {
|
||||
if (value) {
|
||||
if (header === 'x-forwarded-for') {
|
||||
const ips = this.parseForwardedFor(value);
|
||||
ips.forEach(ip => {
|
||||
candidates.push(ip);
|
||||
sources[ip] = header;
|
||||
});
|
||||
} else {
|
||||
candidates.push(value);
|
||||
sources[value] = header;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// 3. 添加 NextRequest 的 IP (如果可用)
|
||||
const nextIP = (request as any).ip;
|
||||
if (nextIP) {
|
||||
candidates.push(nextIP);
|
||||
sources[nextIP] = 'next-request';
|
||||
}
|
||||
|
||||
// 4. 去重並過濾
|
||||
const uniqueCandidates = [...new Set(candidates)].filter(ip =>
|
||||
ip && ip !== 'unknown' && ip !== '::1' && ip !== '127.0.0.1'
|
||||
);
|
||||
|
||||
console.log('🔍 IP 偵測候選:', {
|
||||
candidates: uniqueCandidates,
|
||||
sources: sources,
|
||||
allHeaders: Object.fromEntries(request.headers.entries())
|
||||
});
|
||||
|
||||
// 5. 智能選擇最佳 IP
|
||||
let selectedIP = 'unknown';
|
||||
let confidence: 'high' | 'medium' | 'low' = 'low';
|
||||
let source = 'unknown';
|
||||
|
||||
// 優先級 1: Cloudflare IP (最高可信度) - 但要是用戶真實 IP
|
||||
const cfIP = uniqueCandidates.find(ip => sources[ip] === 'cf-connecting-ip');
|
||||
if (cfIP && this.isUserRealIP(cfIP)) {
|
||||
selectedIP = cfIP;
|
||||
confidence = 'high';
|
||||
source = 'cf-connecting-ip';
|
||||
}
|
||||
|
||||
// 優先級 2: 其他代理標頭中的用戶真實 IP
|
||||
if (selectedIP === 'unknown') {
|
||||
const proxyHeaders = ['x-real-ip', 'x-client-ip', 'x-cluster-client-ip'];
|
||||
for (const header of proxyHeaders) {
|
||||
const ip = uniqueCandidates.find(candidate => sources[candidate] === header);
|
||||
if (ip && this.isUserRealIP(ip)) {
|
||||
selectedIP = ip;
|
||||
confidence = 'high';
|
||||
source = header;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 優先級 3: x-forwarded-for 中的第一個用戶真實 IP
|
||||
if (selectedIP === 'unknown') {
|
||||
const forwardedIPs = uniqueCandidates.filter(ip => sources[ip] === 'x-forwarded-for');
|
||||
const userRealIP = forwardedIPs.find(ip => this.isUserRealIP(ip));
|
||||
if (userRealIP) {
|
||||
selectedIP = userRealIP;
|
||||
confidence = 'medium';
|
||||
source = 'x-forwarded-for';
|
||||
}
|
||||
}
|
||||
|
||||
// 優先級 4: 任何用戶真實 IP
|
||||
if (selectedIP === 'unknown') {
|
||||
const userRealIP = uniqueCandidates.find(ip => this.isUserRealIP(ip));
|
||||
if (userRealIP) {
|
||||
selectedIP = userRealIP;
|
||||
confidence = 'medium';
|
||||
source = sources[userRealIP] || 'unknown';
|
||||
}
|
||||
}
|
||||
|
||||
// 優先級 5: 任何公網 IP(非基礎設施)
|
||||
if (selectedIP === 'unknown') {
|
||||
const publicIP = uniqueCandidates.find(ip =>
|
||||
this.isPublicIP(ip) && !this.isInfrastructureIP(ip)
|
||||
);
|
||||
if (publicIP) {
|
||||
selectedIP = publicIP;
|
||||
confidence = 'low';
|
||||
source = sources[publicIP] || 'unknown';
|
||||
}
|
||||
}
|
||||
|
||||
// 優先級 6: 任何非本地 IP(非基礎設施)
|
||||
if (selectedIP === 'unknown') {
|
||||
const nonLocalIP = uniqueCandidates.find(ip =>
|
||||
ip !== '::1' && ip !== '127.0.0.1' &&
|
||||
!ip.startsWith('192.168.') && !ip.startsWith('10.') && !ip.startsWith('172.') &&
|
||||
!this.isInfrastructureIP(ip)
|
||||
);
|
||||
if (nonLocalIP) {
|
||||
selectedIP = nonLocalIP;
|
||||
confidence = 'low';
|
||||
source = sources[nonLocalIP] || 'unknown';
|
||||
}
|
||||
}
|
||||
|
||||
// 優先級 7: 第一個候選 IP(最後選擇)
|
||||
if (selectedIP === 'unknown' && uniqueCandidates.length > 0) {
|
||||
selectedIP = uniqueCandidates[0];
|
||||
confidence = 'low';
|
||||
source = sources[selectedIP] || 'unknown';
|
||||
}
|
||||
|
||||
const result: IPDetectionResult = {
|
||||
detectedIP: selectedIP,
|
||||
confidence,
|
||||
source,
|
||||
allCandidates: uniqueCandidates,
|
||||
isPublicIP: this.isPublicIP(selectedIP)
|
||||
};
|
||||
|
||||
console.log('🎯 IP 偵測結果:', {
|
||||
...result,
|
||||
isInfrastructureIP: this.isInfrastructureIP(selectedIP),
|
||||
isUserRealIP: this.isUserRealIP(selectedIP),
|
||||
infrastructureIPs: uniqueCandidates.filter(ip => this.isInfrastructureIP(ip)),
|
||||
userRealIPs: uniqueCandidates.filter(ip => this.isUserRealIP(ip))
|
||||
});
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
// 驗證 IP 格式
|
||||
public isValidIP(ip: string): boolean {
|
||||
if (!ip || ip === 'unknown') return false;
|
||||
|
||||
// IPv4 格式檢查
|
||||
const ipv4Regex = /^(\d{1,3}\.){3}\d{1,3}$/;
|
||||
if (ipv4Regex.test(ip)) {
|
||||
const parts = ip.split('.').map(Number);
|
||||
return parts.every(part => part >= 0 && part <= 255);
|
||||
}
|
||||
|
||||
// IPv6 格式檢查(簡化)
|
||||
const ipv6Regex = /^([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$/;
|
||||
return ipv6Regex.test(ip);
|
||||
}
|
||||
}
|
||||
|
||||
// 導出單例實例
|
||||
export const smartIPDetector = SmartIPDetector.getInstance();
|
@@ -1,186 +0,0 @@
|
||||
// =====================================================
|
||||
// 終極連線殺手 - 強制清理所有連線
|
||||
// =====================================================
|
||||
|
||||
import mysql from 'mysql2/promise';
|
||||
|
||||
export class UltimateConnectionKiller {
|
||||
private static instance: UltimateConnectionKiller;
|
||||
|
||||
private constructor() {}
|
||||
|
||||
public static getInstance(): UltimateConnectionKiller {
|
||||
if (!UltimateConnectionKiller.instance) {
|
||||
UltimateConnectionKiller.instance = new UltimateConnectionKiller();
|
||||
}
|
||||
return UltimateConnectionKiller.instance;
|
||||
}
|
||||
|
||||
// 終極清理 - 殺死所有連線
|
||||
public async ultimateKill() {
|
||||
console.log('💀 執行終極連線清理...');
|
||||
|
||||
try {
|
||||
// 1. 建立一個臨時連線來執行清理
|
||||
const tempConnection = await mysql.createConnection({
|
||||
host: process.env.DB_HOST || '122.100.99.161',
|
||||
port: parseInt(process.env.DB_PORT || '43306'),
|
||||
user: process.env.DB_USER || 'A999',
|
||||
password: process.env.DB_PASSWORD || '1023',
|
||||
database: process.env.DB_NAME || 'db_AI_Platform',
|
||||
charset: 'utf8mb4',
|
||||
timezone: '+08:00',
|
||||
});
|
||||
|
||||
try {
|
||||
// 2. 獲取所有連線
|
||||
const [connections] = await tempConnection.execute(`
|
||||
SELECT ID, USER, HOST, DB, COMMAND, TIME, STATE, INFO
|
||||
FROM information_schema.PROCESSLIST
|
||||
WHERE USER = ?
|
||||
ORDER BY TIME DESC
|
||||
`, [process.env.DB_USER || 'A999']);
|
||||
|
||||
console.log(`🔍 找到 ${connections.length} 個連線需要清理`);
|
||||
|
||||
// 3. 殺死所有連線(除了當前連線)
|
||||
let killedCount = 0;
|
||||
for (const conn of connections) {
|
||||
if (conn.ID !== tempConnection.threadId) {
|
||||
try {
|
||||
await tempConnection.execute(`KILL ${conn.ID}`);
|
||||
console.log(`💀 已殺死連線 ${conn.ID} (用戶: ${conn.USER}, 時間: ${conn.TIME}s)`);
|
||||
killedCount++;
|
||||
} catch (error: any) {
|
||||
console.log(`⚠️ 無法殺死連線 ${conn.ID}: ${error.message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`✅ 已殺死 ${killedCount} 個連線`);
|
||||
|
||||
// 4. 等待連線完全關閉
|
||||
console.log('⏳ 等待連線完全關閉...');
|
||||
await new Promise(resolve => setTimeout(resolve, 3000));
|
||||
|
||||
// 5. 再次檢查狀態
|
||||
const [finalConnections] = await tempConnection.execute(`
|
||||
SELECT COUNT(*) as count FROM information_schema.PROCESSLIST
|
||||
WHERE USER = ?
|
||||
`, [process.env.DB_USER || 'A999']);
|
||||
|
||||
const remainingConnections = finalConnections[0].count;
|
||||
console.log(`📊 清理後剩餘連線: ${remainingConnections}`);
|
||||
|
||||
if (remainingConnections <= 1) {
|
||||
console.log('🎉 連線清理成功!');
|
||||
} else {
|
||||
console.warn(`⚠️ 仍有 ${remainingConnections - 1} 個連線未清理`);
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
killedCount,
|
||||
remainingConnections: remainingConnections - 1, // 減去當前連線
|
||||
message: `已殺死 ${killedCount} 個連線,剩餘 ${remainingConnections - 1} 個`
|
||||
};
|
||||
|
||||
} finally {
|
||||
// 6. 關閉臨時連線
|
||||
await tempConnection.end();
|
||||
console.log('🔌 臨時連線已關閉');
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ 終極清理失敗:', error);
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : '未知錯誤'
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// 檢查連線狀態
|
||||
public async checkStatus() {
|
||||
try {
|
||||
const tempConnection = await mysql.createConnection({
|
||||
host: process.env.DB_HOST || '122.100.99.161',
|
||||
port: parseInt(process.env.DB_PORT || '43306'),
|
||||
user: process.env.DB_USER || 'A999',
|
||||
password: process.env.DB_PASSWORD || '1023',
|
||||
database: process.env.DB_NAME || 'db_AI_Platform',
|
||||
charset: 'utf8mb4',
|
||||
timezone: '+08:00',
|
||||
});
|
||||
|
||||
try {
|
||||
// 獲取連線統計
|
||||
const [statusResult] = await tempConnection.execute(`
|
||||
SHOW STATUS LIKE 'Threads_connected'
|
||||
`);
|
||||
|
||||
const [maxConnResult] = await tempConnection.execute(`
|
||||
SHOW VARIABLES LIKE 'max_connections'
|
||||
`);
|
||||
|
||||
const [connections] = await tempConnection.execute(`
|
||||
SELECT ID, USER, HOST, DB, COMMAND, TIME, STATE, INFO
|
||||
FROM information_schema.PROCESSLIST
|
||||
WHERE USER = ?
|
||||
ORDER BY TIME DESC
|
||||
`, [process.env.DB_USER || 'A999']);
|
||||
|
||||
const currentConnections = statusResult[0]?.Value || 0;
|
||||
const maxConnections = maxConnResult[0]?.Value || 100;
|
||||
const usagePercentage = (currentConnections / maxConnections) * 100;
|
||||
|
||||
return {
|
||||
currentConnections: parseInt(currentConnections),
|
||||
maxConnections: parseInt(maxConnections),
|
||||
usagePercentage,
|
||||
connectionDetails: connections,
|
||||
connectionCount: connections.length
|
||||
};
|
||||
|
||||
} finally {
|
||||
await tempConnection.end();
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ 檢查狀態失敗:', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// 強制重啟資料庫連線
|
||||
public async forceRestart() {
|
||||
console.log('🔄 強制重啟資料庫連線...');
|
||||
|
||||
try {
|
||||
// 1. 先殺死所有連線
|
||||
await this.ultimateKill();
|
||||
|
||||
// 2. 等待一段時間
|
||||
console.log('⏳ 等待系統穩定...');
|
||||
await new Promise(resolve => setTimeout(resolve, 5000));
|
||||
|
||||
// 3. 檢查狀態
|
||||
const status = await this.checkStatus();
|
||||
|
||||
if (status && status.connectionCount <= 1) {
|
||||
console.log('✅ 資料庫連線重啟成功');
|
||||
return { success: true, message: '資料庫連線重啟成功' };
|
||||
} else {
|
||||
console.warn('⚠️ 資料庫連線重啟後仍有連線存在');
|
||||
return { success: false, message: '重啟後仍有連線存在' };
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ 強制重啟失敗:', error);
|
||||
return { success: false, error: error instanceof Error ? error.message : '未知錯誤' };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 導出單例實例
|
||||
export const ultimateKiller = UltimateConnectionKiller.getInstance();
|
@@ -1,107 +0,0 @@
|
||||
-- =====================================================
|
||||
-- 完整的虛擬應用設置腳本
|
||||
-- =====================================================
|
||||
|
||||
-- 1. 查看現有團隊
|
||||
SELECT '=== 現有團隊 ===' as info;
|
||||
SELECT id, name, department FROM teams WHERE is_active = TRUE;
|
||||
|
||||
-- 2. 查看現有應用
|
||||
SELECT '=== 現有應用 ===' as info;
|
||||
SELECT id, name, type FROM apps WHERE is_active = TRUE LIMIT 5;
|
||||
|
||||
-- 3. 創建虛擬應用記錄
|
||||
SELECT '=== 創建虛擬應用 ===' as info;
|
||||
|
||||
-- 為團隊 aaa 創建虛擬應用
|
||||
INSERT IGNORE INTO apps (
|
||||
id,
|
||||
name,
|
||||
description,
|
||||
creator_id,
|
||||
category,
|
||||
type,
|
||||
app_url,
|
||||
icon,
|
||||
icon_color,
|
||||
likes_count,
|
||||
views_count,
|
||||
rating,
|
||||
is_active,
|
||||
created_at,
|
||||
updated_at
|
||||
) VALUES (
|
||||
'team_t1757702332911zcl6iafq1',
|
||||
'[團隊評分] aaa',
|
||||
'團隊 aaa 的評分記錄 - 用於存儲團隊評分數據',
|
||||
'00000000-0000-0000-0000-000000000000',
|
||||
'team_scoring',
|
||||
'team',
|
||||
NULL,
|
||||
'Users',
|
||||
'from-gray-500 to-gray-600',
|
||||
0,
|
||||
0,
|
||||
0.00,
|
||||
TRUE,
|
||||
NOW(),
|
||||
NOW()
|
||||
);
|
||||
|
||||
-- 4. 驗證虛擬應用創建
|
||||
SELECT '=== 虛擬應用創建結果 ===' as info;
|
||||
SELECT id, name, type, category, is_active FROM apps WHERE id LIKE 'team_%';
|
||||
|
||||
-- 5. 測試插入團隊評分記錄
|
||||
SELECT '=== 測試團隊評分插入 ===' as info;
|
||||
|
||||
-- 插入測試評分記錄
|
||||
INSERT INTO app_judge_scores (
|
||||
id,
|
||||
judge_id,
|
||||
app_id,
|
||||
innovation_score,
|
||||
technical_score,
|
||||
usability_score,
|
||||
presentation_score,
|
||||
impact_score,
|
||||
total_score,
|
||||
comments,
|
||||
submitted_at
|
||||
) VALUES (
|
||||
UUID(),
|
||||
'fed0a353-8ffe-11f0-bb38-4adff2d0e33e', -- 評審ID
|
||||
'team_t1757702332911zcl6iafq1', -- 虛擬應用ID
|
||||
8, -- innovation_score
|
||||
7, -- technical_score
|
||||
9, -- usability_score
|
||||
8, -- presentation_score
|
||||
7, -- impact_score
|
||||
7.8, -- total_score (平均分)
|
||||
'測試團隊評分記錄',
|
||||
NOW()
|
||||
);
|
||||
|
||||
-- 6. 驗證評分記錄插入
|
||||
SELECT '=== 評分記錄插入結果 ===' as info;
|
||||
SELECT
|
||||
ajs.id,
|
||||
ajs.judge_id,
|
||||
ajs.app_id,
|
||||
ajs.innovation_score,
|
||||
ajs.technical_score,
|
||||
ajs.usability_score,
|
||||
ajs.presentation_score,
|
||||
ajs.impact_score,
|
||||
ajs.total_score,
|
||||
ajs.comments,
|
||||
ajs.submitted_at,
|
||||
a.name as app_name
|
||||
FROM app_judge_scores ajs
|
||||
LEFT JOIN apps a ON ajs.app_id = a.id
|
||||
WHERE ajs.app_id LIKE 'team_%'
|
||||
ORDER BY ajs.submitted_at DESC;
|
||||
|
||||
-- 7. 清理測試數據(可選)
|
||||
-- DELETE FROM app_judge_scores WHERE app_id LIKE 'team_%';
|
||||
-- DELETE FROM apps WHERE id LIKE 'team_%';
|
@@ -1,54 +0,0 @@
|
||||
-- =====================================================
|
||||
-- 手動新增虛擬應用記錄用於團隊評分
|
||||
-- =====================================================
|
||||
|
||||
-- 首先查看現有的團隊數據
|
||||
SELECT id, name FROM teams WHERE is_active = 1;
|
||||
|
||||
-- 為每個團隊創建對應的虛擬應用記錄
|
||||
-- 格式:team_{teamId} 以便識別這是團隊評分
|
||||
|
||||
-- 團隊 1: aaa (ID: t1757702332911zcl6iafq1)
|
||||
INSERT INTO apps (
|
||||
id,
|
||||
name,
|
||||
description,
|
||||
creator_id,
|
||||
category,
|
||||
type,
|
||||
app_url,
|
||||
icon,
|
||||
icon_color,
|
||||
likes_count,
|
||||
views_count,
|
||||
rating,
|
||||
is_active,
|
||||
created_at,
|
||||
updated_at
|
||||
) VALUES (
|
||||
'team_t1757702332911zcl6iafq1',
|
||||
'[團隊評分] aaa',
|
||||
'團隊 aaa 的評分記錄',
|
||||
'00000000-0000-0000-0000-000000000000',
|
||||
'team_scoring',
|
||||
'team',
|
||||
NULL,
|
||||
'Users',
|
||||
'from-gray-500 to-gray-600',
|
||||
0,
|
||||
0,
|
||||
0.00,
|
||||
1,
|
||||
NOW(),
|
||||
NOW()
|
||||
);
|
||||
|
||||
-- 如果有其他團隊,請按照相同格式添加
|
||||
-- 團隊 2: (如果有的話)
|
||||
-- INSERT INTO apps (...) VALUES (...);
|
||||
|
||||
-- 驗證插入結果
|
||||
SELECT id, name, type, category FROM apps WHERE id LIKE 'team_%';
|
||||
|
||||
-- 檢查外鍵約束是否解決
|
||||
-- 現在可以嘗試插入團隊評分記錄
|
@@ -1,106 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
// =====================================================
|
||||
// 初始數據遷移腳本
|
||||
// =====================================================
|
||||
|
||||
const mysql = require('mysql2/promise');
|
||||
|
||||
// 資料庫配置
|
||||
const dbConfig = {
|
||||
host: process.env.DB_HOST || 'mysql.theaken.com',
|
||||
port: parseInt(process.env.DB_PORT || '33306'),
|
||||
user: process.env.DB_USER || 'AI_Platform',
|
||||
password: process.env.DB_PASSWORD || 'Aa123456',
|
||||
database: process.env.DB_NAME || 'db_AI_Platform',
|
||||
charset: 'utf8mb4',
|
||||
timezone: '+08:00',
|
||||
acquireTimeout: 60000,
|
||||
timeout: 60000,
|
||||
reconnect: true,
|
||||
connectionLimit: 10,
|
||||
queueLimit: 0,
|
||||
};
|
||||
|
||||
async function migrateData() {
|
||||
let connection;
|
||||
|
||||
try {
|
||||
console.log('🚀 開始初始數據遷移...');
|
||||
|
||||
// 創建連接
|
||||
connection = await mysql.createConnection({
|
||||
...dbConfig,
|
||||
multipleStatements: true
|
||||
});
|
||||
|
||||
console.log('✅ 資料庫連接成功');
|
||||
|
||||
// 系統設定數據
|
||||
const systemSettingsSQL = `
|
||||
INSERT INTO system_settings (id, \`key\`, value, description, category, is_public) VALUES
|
||||
(UUID(), 'site_name', '強茂集團 AI 展示平台', '網站名稱', 'general', TRUE),
|
||||
(UUID(), 'site_description', '企業內部 AI 應用展示與競賽管理系統', '網站描述', 'general', TRUE),
|
||||
(UUID(), 'max_team_size', '5', '最大團隊人數', 'competition', FALSE),
|
||||
(UUID(), 'max_file_size', '10485760', '最大文件上傳大小(字節)', 'upload', FALSE),
|
||||
(UUID(), 'allowed_file_types', 'jpg,jpeg,png,gif,pdf,doc,docx,ppt,pptx', '允許上傳的文件類型', 'upload', FALSE)
|
||||
ON DUPLICATE KEY UPDATE
|
||||
value = VALUES(value),
|
||||
description = VALUES(description),
|
||||
category = VALUES(category),
|
||||
is_public = VALUES(is_public),
|
||||
updated_at = CURRENT_TIMESTAMP;
|
||||
`;
|
||||
|
||||
console.log('⚡ 插入系統設定...');
|
||||
await connection.execute(systemSettingsSQL);
|
||||
console.log('✅ 系統設定插入成功');
|
||||
|
||||
// AI 助手配置數據
|
||||
const aiConfigSQL = `
|
||||
INSERT INTO ai_assistant_configs (id, api_key, api_url, model, max_tokens, temperature, system_prompt, is_active) VALUES
|
||||
(UUID(), 'sk-3640dcff23fe4a069a64f536ac538d75', 'https://api.deepseek.com/v1/chat/completions', 'deepseek-chat', 200, 0.70, '你是一個競賽管理系統的AI助手,專門幫助用戶了解如何使用這個系統。請用友善、專業的語氣回答用戶問題,並提供具體的操作步驟。回答要簡潔明瞭,避免過長的文字。重要:請不要使用任何Markdown格式,只使用純文字回答。回答時請使用繁體中文。', TRUE)
|
||||
ON DUPLICATE KEY UPDATE
|
||||
api_key = VALUES(api_key),
|
||||
api_url = VALUES(api_url),
|
||||
model = VALUES(model),
|
||||
max_tokens = VALUES(max_tokens),
|
||||
temperature = VALUES(temperature),
|
||||
system_prompt = VALUES(system_prompt),
|
||||
is_active = VALUES(is_active),
|
||||
updated_at = CURRENT_TIMESTAMP;
|
||||
`;
|
||||
|
||||
console.log('⚡ 插入 AI 助手配置...');
|
||||
await connection.execute(aiConfigSQL);
|
||||
console.log('✅ AI 助手配置插入成功');
|
||||
|
||||
// 檢查插入的數據
|
||||
console.log('🔍 檢查插入的數據...');
|
||||
|
||||
const [settings] = await connection.execute('SELECT COUNT(*) as count FROM system_settings');
|
||||
console.log(`⚙️ 系統設定數量: ${settings[0].count}`);
|
||||
|
||||
const [aiConfigs] = await connection.execute('SELECT COUNT(*) as count FROM ai_assistant_configs');
|
||||
console.log(`🤖 AI 助手配置數量: ${aiConfigs[0].count}`);
|
||||
|
||||
console.log('🎉 初始數據遷移完成!');
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ 數據遷移失敗:', error.message);
|
||||
console.error('詳細錯誤:', error);
|
||||
process.exit(1);
|
||||
} finally {
|
||||
if (connection) {
|
||||
await connection.end();
|
||||
console.log('🔌 資料庫連接已關閉');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 執行遷移
|
||||
if (require.main === module) {
|
||||
migrateData().catch(console.error);
|
||||
}
|
||||
|
||||
module.exports = { migrateData };
|
@@ -1,141 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
// =====================================================
|
||||
// 資料庫遷移腳本 (修復版)
|
||||
// =====================================================
|
||||
|
||||
const mysql = require('mysql2/promise');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
// 資料庫配置
|
||||
const dbConfig = {
|
||||
host: process.env.DB_HOST || 'mysql.theaken.com',
|
||||
port: parseInt(process.env.DB_PORT || '33306'),
|
||||
user: process.env.DB_USER || 'AI_Platform',
|
||||
password: process.env.DB_PASSWORD || 'Aa123456',
|
||||
database: process.env.DB_NAME || 'db_AI_Platform',
|
||||
charset: 'utf8mb4',
|
||||
timezone: '+08:00',
|
||||
};
|
||||
|
||||
async function runMigration() {
|
||||
let connection;
|
||||
|
||||
try {
|
||||
console.log('🚀 開始資料庫遷移...');
|
||||
|
||||
// 創建連接
|
||||
connection = await mysql.createConnection({
|
||||
...dbConfig,
|
||||
multipleStatements: true
|
||||
});
|
||||
|
||||
console.log('✅ 資料庫連接成功');
|
||||
|
||||
// 讀取 SQL 文件
|
||||
const sqlFile = path.join(__dirname, '..', 'database-schema-simple.sql');
|
||||
const sqlContent = fs.readFileSync(sqlFile, 'utf8');
|
||||
|
||||
console.log('📖 讀取 SQL 文件成功');
|
||||
|
||||
// 處理 SQL 內容,正確分割語句
|
||||
console.log('⚡ 處理 SQL 語句...');
|
||||
|
||||
// 先處理觸發器,因為它們包含分號
|
||||
const triggerRegex = /CREATE TRIGGER[\s\S]*?END;/g;
|
||||
const triggers = sqlContent.match(triggerRegex) || [];
|
||||
|
||||
// 移除觸發器部分,處理其他語句
|
||||
let remainingSql = sqlContent.replace(triggerRegex, '');
|
||||
|
||||
// 分割其他語句
|
||||
const otherStatements = remainingSql
|
||||
.split(';')
|
||||
.map(stmt => stmt.trim())
|
||||
.filter(stmt => stmt.length > 0 && !stmt.startsWith('--'));
|
||||
|
||||
// 合併所有語句
|
||||
const allStatements = [...otherStatements, ...triggers];
|
||||
|
||||
console.log(`📊 共找到 ${allStatements.length} 個語句`);
|
||||
|
||||
// 執行語句
|
||||
for (let i = 0; i < allStatements.length; i++) {
|
||||
const statement = allStatements[i];
|
||||
if (statement.trim()) {
|
||||
try {
|
||||
// 特殊處理 USE 語句和觸發器
|
||||
if (statement.toUpperCase().startsWith('USE') ||
|
||||
statement.toUpperCase().startsWith('CREATE TRIGGER')) {
|
||||
await connection.query(statement + ';');
|
||||
} else {
|
||||
await connection.execute(statement + ';');
|
||||
}
|
||||
console.log(`✅ 執行語句 ${i + 1}/${allStatements.length}`);
|
||||
} catch (error) {
|
||||
console.error(`❌ 語句 ${i + 1} 執行失敗:`, error.message);
|
||||
console.error(`語句內容: ${statement.substring(0, 100)}...`);
|
||||
// 對於某些錯誤,我們可以繼續執行
|
||||
if (error.message.includes('already exists') ||
|
||||
error.message.includes('Duplicate entry') ||
|
||||
error.message.includes('Table') && error.message.includes('already exists')) {
|
||||
console.log('⚠️ 跳過已存在的項目');
|
||||
continue;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
console.log('✅ 資料庫結構創建成功!');
|
||||
|
||||
// 驗證表是否創建成功
|
||||
console.log('🔍 驗證表結構...');
|
||||
const [tables] = await connection.execute('SHOW TABLES');
|
||||
console.log(`📊 共創建了 ${tables.length} 個表:`);
|
||||
|
||||
tables.forEach((table, index) => {
|
||||
const tableName = Object.values(table)[0];
|
||||
console.log(` ${index + 1}. ${tableName}`);
|
||||
});
|
||||
|
||||
// 檢查視圖
|
||||
console.log('🔍 驗證視圖...');
|
||||
const [views] = await connection.execute('SHOW FULL TABLES WHERE Table_type = "VIEW"');
|
||||
console.log(`📈 共創建了 ${views.length} 個視圖:`);
|
||||
|
||||
views.forEach((view, index) => {
|
||||
const viewName = Object.values(view)[0];
|
||||
console.log(` ${index + 1}. ${viewName}`);
|
||||
});
|
||||
|
||||
// 檢查觸發器
|
||||
console.log('🔍 驗證觸發器...');
|
||||
const [triggerList] = await connection.execute('SHOW TRIGGERS');
|
||||
console.log(`⚙️ 共創建了 ${triggerList.length} 個觸發器:`);
|
||||
|
||||
triggerList.forEach((trigger, index) => {
|
||||
console.log(` ${index + 1}. ${trigger.Trigger}`);
|
||||
});
|
||||
|
||||
console.log('🎉 資料庫遷移完成!');
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ 遷移失敗:', error.message);
|
||||
console.error('詳細錯誤:', error);
|
||||
process.exit(1);
|
||||
} finally {
|
||||
if (connection) {
|
||||
await connection.end();
|
||||
console.log('🔌 資料庫連接已關閉');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 執行遷移
|
||||
if (require.main === module) {
|
||||
runMigration().catch(console.error);
|
||||
}
|
||||
|
||||
module.exports = { runMigration };
|
@@ -1,124 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
// =====================================================
|
||||
// 資料庫遷移腳本 (無觸發器版)
|
||||
// =====================================================
|
||||
|
||||
const mysql = require('mysql2/promise');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
// 資料庫配置
|
||||
const dbConfig = {
|
||||
host: process.env.DB_HOST || 'mysql.theaken.com',
|
||||
port: parseInt(process.env.DB_PORT || '33306'),
|
||||
user: process.env.DB_USER || 'AI_Platform',
|
||||
password: process.env.DB_PASSWORD || 'Aa123456',
|
||||
database: process.env.DB_NAME || 'db_AI_Platform',
|
||||
charset: 'utf8mb4',
|
||||
timezone: '+08:00',
|
||||
};
|
||||
|
||||
async function runMigration() {
|
||||
let connection;
|
||||
|
||||
try {
|
||||
console.log('🚀 開始資料庫遷移...');
|
||||
|
||||
// 創建連接
|
||||
connection = await mysql.createConnection({
|
||||
...dbConfig,
|
||||
multipleStatements: true
|
||||
});
|
||||
|
||||
console.log('✅ 資料庫連接成功');
|
||||
|
||||
// 讀取 SQL 文件
|
||||
const sqlFile = path.join(__dirname, '..', 'database-schema-simple.sql');
|
||||
const sqlContent = fs.readFileSync(sqlFile, 'utf8');
|
||||
|
||||
console.log('📖 讀取 SQL 文件成功');
|
||||
|
||||
// 移除觸發器部分
|
||||
console.log('⚡ 處理 SQL 語句...');
|
||||
const triggerRegex = /CREATE TRIGGER[\s\S]*?END;/g;
|
||||
let sqlWithoutTriggers = sqlContent.replace(triggerRegex, '');
|
||||
|
||||
// 分割語句
|
||||
const statements = sqlWithoutTriggers
|
||||
.split(';')
|
||||
.map(stmt => stmt.trim())
|
||||
.filter(stmt => stmt.length > 0 && !stmt.startsWith('--'));
|
||||
|
||||
console.log(`📊 共找到 ${statements.length} 個語句`);
|
||||
|
||||
// 執行語句
|
||||
for (let i = 0; i < statements.length; i++) {
|
||||
const statement = statements[i];
|
||||
if (statement.trim()) {
|
||||
try {
|
||||
// 特殊處理 USE 語句
|
||||
if (statement.toUpperCase().startsWith('USE')) {
|
||||
await connection.query(statement + ';');
|
||||
} else {
|
||||
await connection.execute(statement + ';');
|
||||
}
|
||||
console.log(`✅ 執行語句 ${i + 1}/${statements.length}`);
|
||||
} catch (error) {
|
||||
console.error(`❌ 語句 ${i + 1} 執行失敗:`, error.message);
|
||||
console.error(`語句內容: ${statement.substring(0, 100)}...`);
|
||||
// 對於某些錯誤,我們可以繼續執行
|
||||
if (error.message.includes('already exists') ||
|
||||
error.message.includes('Duplicate entry') ||
|
||||
error.message.includes('Table') && error.message.includes('already exists')) {
|
||||
console.log('⚠️ 跳過已存在的項目');
|
||||
continue;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
console.log('✅ 資料庫結構創建成功!');
|
||||
|
||||
// 驗證表是否創建成功
|
||||
console.log('🔍 驗證表結構...');
|
||||
const [tables] = await connection.execute('SHOW TABLES');
|
||||
console.log(`📊 共創建了 ${tables.length} 個表:`);
|
||||
|
||||
tables.forEach((table, index) => {
|
||||
const tableName = Object.values(table)[0];
|
||||
console.log(` ${index + 1}. ${tableName}`);
|
||||
});
|
||||
|
||||
// 檢查視圖
|
||||
console.log('🔍 驗證視圖...');
|
||||
const [views] = await connection.execute('SHOW FULL TABLES WHERE Table_type = "VIEW"');
|
||||
console.log(`📈 共創建了 ${views.length} 個視圖:`);
|
||||
|
||||
views.forEach((view, index) => {
|
||||
const viewName = Object.values(view)[0];
|
||||
console.log(` ${index + 1}. ${viewName}`);
|
||||
});
|
||||
|
||||
console.log('🎉 資料庫遷移完成!');
|
||||
console.log('⚠️ 注意:觸發器由於權限限制未創建,但基本表結構已就緒');
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ 遷移失敗:', error.message);
|
||||
console.error('詳細錯誤:', error);
|
||||
process.exit(1);
|
||||
} finally {
|
||||
if (connection) {
|
||||
await connection.end();
|
||||
console.log('🔌 資料庫連接已關閉');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 執行遷移
|
||||
if (require.main === module) {
|
||||
runMigration().catch(console.error);
|
||||
}
|
||||
|
||||
module.exports = { runMigration };
|
@@ -1,101 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
// =====================================================
|
||||
// 簡單遷移腳本
|
||||
// =====================================================
|
||||
|
||||
const mysql = require('mysql2/promise');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
// 資料庫配置
|
||||
const dbConfig = {
|
||||
host: process.env.DB_HOST || 'mysql.theaken.com',
|
||||
port: parseInt(process.env.DB_PORT || '33306'),
|
||||
user: process.env.DB_USER || 'AI_Platform',
|
||||
password: process.env.DB_PASSWORD || 'Aa123456',
|
||||
database: process.env.DB_NAME || 'db_AI_Platform',
|
||||
charset: 'utf8mb4',
|
||||
timezone: '+08:00',
|
||||
acquireTimeout: 60000,
|
||||
timeout: 60000,
|
||||
reconnect: true,
|
||||
connectionLimit: 10,
|
||||
queueLimit: 0,
|
||||
};
|
||||
|
||||
async function migrateSimple() {
|
||||
let connection;
|
||||
|
||||
try {
|
||||
console.log('🚀 開始簡單遷移...');
|
||||
|
||||
// 創建連接
|
||||
connection = await mysql.createConnection({
|
||||
...dbConfig,
|
||||
multipleStatements: true
|
||||
});
|
||||
|
||||
console.log('✅ 資料庫連接成功');
|
||||
|
||||
// 讀取 SQL 文件
|
||||
const sqlFile = path.join(__dirname, '..', 'database-tables-only.sql');
|
||||
const sqlContent = fs.readFileSync(sqlFile, 'utf8');
|
||||
|
||||
console.log('📖 讀取 SQL 文件成功');
|
||||
|
||||
// 直接執行整個 SQL 文件
|
||||
console.log('⚡ 執行 SQL 語句...');
|
||||
await connection.query(sqlContent);
|
||||
|
||||
console.log('✅ 資料庫結構創建成功!');
|
||||
|
||||
// 驗證表是否創建成功
|
||||
console.log('🔍 驗證表結構...');
|
||||
const [tables] = await connection.execute('SHOW TABLES');
|
||||
console.log(`📊 共創建了 ${tables.length} 個表:`);
|
||||
|
||||
tables.forEach((table, index) => {
|
||||
const tableName = Object.values(table)[0];
|
||||
console.log(` ${index + 1}. ${tableName}`);
|
||||
});
|
||||
|
||||
// 檢查視圖
|
||||
console.log('🔍 檢查視圖...');
|
||||
const [views] = await connection.execute('SHOW FULL TABLES WHERE Table_type = "VIEW"');
|
||||
console.log(`📈 共創建了 ${views.length} 個視圖:`);
|
||||
|
||||
views.forEach((view, index) => {
|
||||
const viewName = Object.values(view)[0];
|
||||
console.log(` ${index + 1}. ${viewName}`);
|
||||
});
|
||||
|
||||
// 檢查觸發器
|
||||
console.log('🔍 檢查觸發器...');
|
||||
const [triggers] = await connection.execute('SHOW TRIGGERS');
|
||||
console.log(`⚙️ 共創建了 ${triggers.length} 個觸發器:`);
|
||||
|
||||
triggers.forEach((trigger, index) => {
|
||||
console.log(` ${index + 1}. ${trigger.Trigger}`);
|
||||
});
|
||||
|
||||
console.log('🎉 遷移完成!');
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ 遷移失敗:', error.message);
|
||||
console.error('詳細錯誤:', error);
|
||||
process.exit(1);
|
||||
} finally {
|
||||
if (connection) {
|
||||
await connection.end();
|
||||
console.log('🔌 資料庫連接已關閉');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 執行遷移
|
||||
if (require.main === module) {
|
||||
migrateSimple().catch(console.error);
|
||||
}
|
||||
|
||||
module.exports = { migrateSimple };
|
@@ -1,115 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
// =====================================================
|
||||
// 資料表遷移腳本
|
||||
// =====================================================
|
||||
|
||||
const mysql = require('mysql2/promise');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
// 資料庫配置
|
||||
const dbConfig = {
|
||||
host: process.env.DB_HOST || 'mysql.theaken.com',
|
||||
port: parseInt(process.env.DB_PORT || '33306'),
|
||||
user: process.env.DB_USER || 'AI_Platform',
|
||||
password: process.env.DB_PASSWORD || 'Aa123456',
|
||||
database: process.env.DB_NAME || 'db_AI_Platform',
|
||||
charset: 'utf8mb4',
|
||||
timezone: '+08:00',
|
||||
acquireTimeout: 60000,
|
||||
timeout: 60000,
|
||||
reconnect: true,
|
||||
connectionLimit: 10,
|
||||
queueLimit: 0,
|
||||
};
|
||||
|
||||
async function migrateTables() {
|
||||
let connection;
|
||||
|
||||
try {
|
||||
console.log('🚀 開始資料表遷移...');
|
||||
|
||||
// 創建連接
|
||||
connection = await mysql.createConnection({
|
||||
...dbConfig,
|
||||
multipleStatements: true
|
||||
});
|
||||
|
||||
console.log('✅ 資料庫連接成功');
|
||||
|
||||
// 讀取 SQL 文件
|
||||
const sqlFile = path.join(__dirname, '..', 'database-schema-simple.sql');
|
||||
const sqlContent = fs.readFileSync(sqlFile, 'utf8');
|
||||
|
||||
console.log('📖 讀取 SQL 文件成功');
|
||||
|
||||
// 分割 SQL 語句,只保留 CREATE TABLE 語句
|
||||
const statements = sqlContent
|
||||
.split(';')
|
||||
.map(stmt => stmt.trim())
|
||||
.filter(stmt => {
|
||||
return stmt.length > 0 &&
|
||||
!stmt.startsWith('--') &&
|
||||
!stmt.toUpperCase().includes('DELIMITER') &&
|
||||
!stmt.toUpperCase().includes('TRIGGER') &&
|
||||
!stmt.toUpperCase().includes('CREATE VIEW') &&
|
||||
!stmt.toUpperCase().includes('INSERT INTO') &&
|
||||
!stmt.toUpperCase().includes('SELECT') &&
|
||||
(stmt.toUpperCase().includes('CREATE TABLE') || stmt.toUpperCase().includes('CREATE DATABASE') || stmt.toUpperCase().includes('USE'));
|
||||
});
|
||||
|
||||
console.log(`📊 找到 ${statements.length} 個表創建語句`);
|
||||
|
||||
// 逐個執行語句
|
||||
for (let i = 0; i < statements.length; i++) {
|
||||
const statement = statements[i];
|
||||
if (statement.trim()) {
|
||||
try {
|
||||
// 特殊處理 USE 語句
|
||||
if (statement.toUpperCase().startsWith('USE')) {
|
||||
await connection.query(statement + ';');
|
||||
} else {
|
||||
await connection.execute(statement + ';');
|
||||
}
|
||||
console.log(`✅ 執行語句 ${i + 1}/${statements.length}`);
|
||||
} catch (error) {
|
||||
console.error(`❌ 語句 ${i + 1} 執行失敗:`, error.message);
|
||||
console.error(`語句內容: ${statement.substring(0, 100)}...`);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
console.log('✅ 資料表創建成功!');
|
||||
|
||||
// 驗證表是否創建成功
|
||||
console.log('🔍 驗證表結構...');
|
||||
const [tables] = await connection.execute('SHOW TABLES');
|
||||
console.log(`📊 共創建了 ${tables.length} 個表:`);
|
||||
|
||||
tables.forEach((table, index) => {
|
||||
const tableName = Object.values(table)[0];
|
||||
console.log(` ${index + 1}. ${tableName}`);
|
||||
});
|
||||
|
||||
console.log('🎉 資料表遷移完成!');
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ 遷移失敗:', error.message);
|
||||
console.error('詳細錯誤:', error);
|
||||
process.exit(1);
|
||||
} finally {
|
||||
if (connection) {
|
||||
await connection.end();
|
||||
console.log('🔌 資料庫連接已關閉');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 執行遷移
|
||||
if (require.main === module) {
|
||||
migrateTables().catch(console.error);
|
||||
}
|
||||
|
||||
module.exports = { migrateTables };
|
@@ -1,68 +0,0 @@
|
||||
// =====================================================
|
||||
// 遷移到動態評分系統的腳本
|
||||
// =====================================================
|
||||
|
||||
const mysql = require('mysql2/promise');
|
||||
const fs = require('fs');
|
||||
|
||||
async function migrateToDynamicScoring() {
|
||||
console.log('🚀 開始遷移到動態評分系統...\n');
|
||||
|
||||
let connection;
|
||||
|
||||
try {
|
||||
// 連接數據庫
|
||||
connection = await mysql.createConnection({
|
||||
host: 'mysql.theaken.com',
|
||||
port: 33306,
|
||||
user: 'AI_Platform',
|
||||
password: 'Aa123456',
|
||||
database: 'db_AI_Platform'
|
||||
});
|
||||
|
||||
console.log('✅ 數據庫連接成功');
|
||||
|
||||
// 讀取 SQL 腳本
|
||||
const sqlScript = fs.readFileSync('scripts/redesign-scoring-database.sql', 'utf8');
|
||||
|
||||
// 分割 SQL 語句
|
||||
const statements = sqlScript
|
||||
.split(';')
|
||||
.map(stmt => stmt.trim())
|
||||
.filter(stmt => stmt.length > 0 && !stmt.startsWith('--'));
|
||||
|
||||
console.log(`📝 準備執行 ${statements.length} 個 SQL 語句...`);
|
||||
|
||||
// 逐個執行 SQL 語句
|
||||
for (let i = 0; i < statements.length; i++) {
|
||||
const statement = statements[i];
|
||||
console.log(`\n🔄 執行語句 ${i + 1}/${statements.length}:`);
|
||||
console.log(statement.substring(0, 100) + (statement.length > 100 ? '...' : ''));
|
||||
|
||||
try {
|
||||
await connection.execute(statement);
|
||||
console.log('✅ 執行成功');
|
||||
} catch (error) {
|
||||
console.log('⚠️ 執行警告:', error.message);
|
||||
// 繼續執行其他語句
|
||||
}
|
||||
}
|
||||
|
||||
console.log('\n🎉 數據庫遷移完成!');
|
||||
console.log('\n📊 新表結構:');
|
||||
console.log('- judge_scores: 主評分記錄表');
|
||||
console.log('- judge_score_details: 評分項目詳情表');
|
||||
console.log('- app_judge_scores: 向後兼容視圖');
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ 遷移失敗:', error.message);
|
||||
} finally {
|
||||
if (connection) {
|
||||
await connection.end();
|
||||
console.log('\n✅ 數據庫連接已關閉');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 執行遷移
|
||||
migrateToDynamicScoring();
|
@@ -1,150 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
// =====================================================
|
||||
// 觸發器遷移腳本
|
||||
// =====================================================
|
||||
|
||||
const mysql = require('mysql2/promise');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
// 資料庫配置
|
||||
const dbConfig = {
|
||||
host: process.env.DB_HOST || 'mysql.theaken.com',
|
||||
port: parseInt(process.env.DB_PORT || '33306'),
|
||||
user: process.env.DB_USER || 'AI_Platform',
|
||||
password: process.env.DB_PASSWORD || 'Aa123456',
|
||||
database: process.env.DB_NAME || 'db_AI_Platform',
|
||||
charset: 'utf8mb4',
|
||||
timezone: '+08:00',
|
||||
acquireTimeout: 60000,
|
||||
timeout: 60000,
|
||||
reconnect: true,
|
||||
connectionLimit: 10,
|
||||
queueLimit: 0,
|
||||
};
|
||||
|
||||
async function migrateTriggers() {
|
||||
let connection;
|
||||
|
||||
try {
|
||||
console.log('🚀 開始觸發器遷移...');
|
||||
|
||||
// 創建連接
|
||||
connection = await mysql.createConnection({
|
||||
...dbConfig,
|
||||
multipleStatements: true
|
||||
});
|
||||
|
||||
console.log('✅ 資料庫連接成功');
|
||||
|
||||
// 觸發器 SQL
|
||||
const triggers = [
|
||||
{
|
||||
name: 'calculate_app_total_score',
|
||||
sql: `CREATE TRIGGER calculate_app_total_score
|
||||
BEFORE INSERT ON app_judge_scores
|
||||
FOR EACH ROW
|
||||
BEGIN
|
||||
SET NEW.total_score = (
|
||||
NEW.innovation_score +
|
||||
NEW.technical_score +
|
||||
NEW.usability_score +
|
||||
NEW.presentation_score +
|
||||
NEW.impact_score
|
||||
) / 5.0;
|
||||
END`
|
||||
},
|
||||
{
|
||||
name: 'calculate_app_total_score_update',
|
||||
sql: `CREATE TRIGGER calculate_app_total_score_update
|
||||
BEFORE UPDATE ON app_judge_scores
|
||||
FOR EACH ROW
|
||||
BEGIN
|
||||
SET NEW.total_score = (
|
||||
NEW.innovation_score +
|
||||
NEW.technical_score +
|
||||
NEW.usability_score +
|
||||
NEW.presentation_score +
|
||||
NEW.impact_score
|
||||
) / 5.0;
|
||||
END`
|
||||
},
|
||||
{
|
||||
name: 'calculate_proposal_total_score',
|
||||
sql: `CREATE TRIGGER calculate_proposal_total_score
|
||||
BEFORE INSERT ON proposal_judge_scores
|
||||
FOR EACH ROW
|
||||
BEGIN
|
||||
SET NEW.total_score = (
|
||||
NEW.problem_identification_score +
|
||||
NEW.solution_feasibility_score +
|
||||
NEW.innovation_score +
|
||||
NEW.impact_score +
|
||||
NEW.presentation_score
|
||||
) / 5.0;
|
||||
END`
|
||||
},
|
||||
{
|
||||
name: 'calculate_proposal_total_score_update',
|
||||
sql: `CREATE TRIGGER calculate_proposal_total_score_update
|
||||
BEFORE UPDATE ON proposal_judge_scores
|
||||
FOR EACH ROW
|
||||
BEGIN
|
||||
SET NEW.total_score = (
|
||||
NEW.problem_identification_score +
|
||||
NEW.solution_feasibility_score +
|
||||
NEW.innovation_score +
|
||||
NEW.impact_score +
|
||||
NEW.presentation_score
|
||||
) / 5.0;
|
||||
END`
|
||||
}
|
||||
];
|
||||
|
||||
console.log('⚡ 執行觸發器 SQL...');
|
||||
|
||||
for (const trigger of triggers) {
|
||||
try {
|
||||
await connection.query(trigger.sql);
|
||||
console.log(`✅ 創建觸發器: ${trigger.name}`);
|
||||
} catch (error) {
|
||||
if (error.code === 'ER_TRG_ALREADY_EXISTS') {
|
||||
console.log(`⚠️ 觸發器已存在: ${trigger.name}`);
|
||||
} else {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
console.log('✅ 觸發器創建成功!');
|
||||
|
||||
// 檢查觸發器
|
||||
console.log('🔍 檢查觸發器...');
|
||||
const [triggerList] = await connection.execute('SHOW TRIGGERS');
|
||||
console.log(`⚙️ 共創建了 ${triggerList.length} 個觸發器:`);
|
||||
|
||||
triggerList.forEach((trigger, index) => {
|
||||
console.log(` ${index + 1}. ${trigger.Trigger}`);
|
||||
});
|
||||
|
||||
console.log('🎉 觸發器遷移完成!');
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ 觸發器遷移失敗:', error.message);
|
||||
console.error('詳細錯誤:', error);
|
||||
process.exit(1);
|
||||
} finally {
|
||||
if (connection) {
|
||||
await connection.end();
|
||||
console.log('🔌 資料庫連接已關閉');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 執行遷移
|
||||
if (require.main === module) {
|
||||
migrateTriggers().catch(console.error);
|
||||
}
|
||||
|
||||
module.exports = { migrateTriggers };
|
@@ -1,253 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
// =====================================================
|
||||
// 視圖遷移腳本
|
||||
// =====================================================
|
||||
|
||||
const mysql = require('mysql2/promise');
|
||||
|
||||
// 資料庫配置
|
||||
const dbConfig = {
|
||||
host: process.env.DB_HOST || 'mysql.theaken.com',
|
||||
port: parseInt(process.env.DB_PORT || '33306'),
|
||||
user: process.env.DB_USER || 'AI_Platform',
|
||||
password: process.env.DB_PASSWORD || 'Aa123456',
|
||||
database: process.env.DB_NAME || 'db_AI_Platform',
|
||||
charset: 'utf8mb4',
|
||||
timezone: '+08:00',
|
||||
acquireTimeout: 60000,
|
||||
timeout: 60000,
|
||||
reconnect: true,
|
||||
connectionLimit: 10,
|
||||
queueLimit: 0,
|
||||
};
|
||||
|
||||
async function migrateViews() {
|
||||
let connection;
|
||||
|
||||
try {
|
||||
console.log('🚀 開始視圖遷移...');
|
||||
|
||||
// 創建連接
|
||||
connection = await mysql.createConnection({
|
||||
...dbConfig,
|
||||
multipleStatements: true
|
||||
});
|
||||
|
||||
console.log('✅ 資料庫連接成功');
|
||||
|
||||
// 視圖 SQL
|
||||
const viewSQL = `
|
||||
-- 用戶統計視圖
|
||||
CREATE VIEW user_statistics AS
|
||||
SELECT
|
||||
u.id,
|
||||
u.name,
|
||||
u.email,
|
||||
u.department,
|
||||
u.role,
|
||||
u.join_date,
|
||||
u.total_likes,
|
||||
u.total_views,
|
||||
COUNT(DISTINCT f.app_id) as favorite_count,
|
||||
COUNT(DISTINCT l.app_id) as liked_apps_count,
|
||||
COUNT(DISTINCT v.app_id) as viewed_apps_count,
|
||||
AVG(r.rating) as average_rating_given,
|
||||
COUNT(DISTINCT t.id) as teams_joined,
|
||||
COUNT(DISTINCT CASE WHEN t.leader_id = u.id THEN t.id END) as teams_led
|
||||
FROM users u
|
||||
LEFT JOIN user_favorites f ON u.id = f.user_id
|
||||
LEFT JOIN user_likes l ON u.id = l.user_id
|
||||
LEFT JOIN user_views v ON u.id = v.user_id
|
||||
LEFT JOIN user_ratings r ON u.id = r.user_id
|
||||
LEFT JOIN team_members tm ON u.id = tm.user_id
|
||||
LEFT JOIN teams t ON tm.team_id = t.id
|
||||
WHERE u.is_active = TRUE
|
||||
GROUP BY u.id;
|
||||
|
||||
-- 應用統計視圖
|
||||
CREATE VIEW app_statistics AS
|
||||
SELECT
|
||||
a.id,
|
||||
a.name,
|
||||
a.description,
|
||||
a.category,
|
||||
a.type,
|
||||
a.likes_count,
|
||||
a.views_count,
|
||||
a.rating,
|
||||
u.name as creator_name,
|
||||
u.department as creator_department,
|
||||
t.name as team_name,
|
||||
COUNT(DISTINCT f.user_id) as favorite_users_count,
|
||||
COUNT(DISTINCT l.user_id) as liked_users_count,
|
||||
COUNT(DISTINCT v.user_id) as viewed_users_count,
|
||||
AVG(ajs.total_score) as average_judge_score,
|
||||
COUNT(DISTINCT ajs.judge_id) as judge_count
|
||||
FROM apps a
|
||||
LEFT JOIN users u ON a.creator_id = u.id
|
||||
LEFT JOIN teams t ON a.team_id = t.id
|
||||
LEFT JOIN user_favorites f ON a.id = f.app_id
|
||||
LEFT JOIN user_likes l ON a.id = l.app_id
|
||||
LEFT JOIN user_views v ON a.id = v.app_id
|
||||
LEFT JOIN app_judge_scores ajs ON a.id = ajs.app_id
|
||||
WHERE a.is_active = TRUE
|
||||
GROUP BY a.id;
|
||||
|
||||
-- 競賽統計視圖
|
||||
CREATE VIEW competition_statistics AS
|
||||
SELECT
|
||||
c.id,
|
||||
c.name,
|
||||
c.year,
|
||||
c.month,
|
||||
c.type,
|
||||
c.status,
|
||||
COUNT(DISTINCT cj.judge_id) as judge_count,
|
||||
COUNT(DISTINCT ca.app_id) as app_count,
|
||||
COUNT(DISTINCT ct.team_id) as team_count,
|
||||
COUNT(DISTINCT cp.proposal_id) as proposal_count,
|
||||
COUNT(DISTINCT aw.id) as award_count
|
||||
FROM competitions c
|
||||
LEFT JOIN competition_judges cj ON c.id = cj.competition_id
|
||||
LEFT JOIN competition_apps ca ON c.id = ca.competition_id
|
||||
LEFT JOIN competition_teams ct ON c.id = ct.competition_id
|
||||
LEFT JOIN competition_proposals cp ON c.id = cp.competition_id
|
||||
LEFT JOIN awards aw ON c.id = aw.competition_id
|
||||
WHERE c.is_active = TRUE
|
||||
GROUP BY c.id;
|
||||
`;
|
||||
|
||||
console.log('⚡ 執行視圖 SQL...');
|
||||
|
||||
// 分別執行每個視圖
|
||||
const views = [
|
||||
{
|
||||
name: 'user_statistics',
|
||||
sql: `CREATE VIEW user_statistics AS
|
||||
SELECT
|
||||
u.id,
|
||||
u.name,
|
||||
u.email,
|
||||
u.department,
|
||||
u.role,
|
||||
u.join_date,
|
||||
u.total_likes,
|
||||
u.total_views,
|
||||
COUNT(DISTINCT f.app_id) as favorite_count,
|
||||
COUNT(DISTINCT l.app_id) as liked_apps_count,
|
||||
COUNT(DISTINCT v.app_id) as viewed_apps_count,
|
||||
AVG(r.rating) as average_rating_given,
|
||||
COUNT(DISTINCT t.id) as teams_joined,
|
||||
COUNT(DISTINCT CASE WHEN t.leader_id = u.id THEN t.id END) as teams_led
|
||||
FROM users u
|
||||
LEFT JOIN user_favorites f ON u.id = f.user_id
|
||||
LEFT JOIN user_likes l ON u.id = l.user_id
|
||||
LEFT JOIN user_views v ON u.id = v.user_id
|
||||
LEFT JOIN user_ratings r ON u.id = r.user_id
|
||||
LEFT JOIN team_members tm ON u.id = tm.user_id
|
||||
LEFT JOIN teams t ON tm.team_id = t.id
|
||||
WHERE u.is_active = TRUE
|
||||
GROUP BY u.id`
|
||||
},
|
||||
{
|
||||
name: 'app_statistics',
|
||||
sql: `CREATE VIEW app_statistics AS
|
||||
SELECT
|
||||
a.id,
|
||||
a.name,
|
||||
a.description,
|
||||
a.category,
|
||||
a.type,
|
||||
a.likes_count,
|
||||
a.views_count,
|
||||
a.rating,
|
||||
u.name as creator_name,
|
||||
u.department as creator_department,
|
||||
t.name as team_name,
|
||||
COUNT(DISTINCT f.user_id) as favorite_users_count,
|
||||
COUNT(DISTINCT l.user_id) as liked_users_count,
|
||||
COUNT(DISTINCT v.user_id) as viewed_users_count,
|
||||
AVG(ajs.total_score) as average_judge_score,
|
||||
COUNT(DISTINCT ajs.judge_id) as judge_count
|
||||
FROM apps a
|
||||
LEFT JOIN users u ON a.creator_id = u.id
|
||||
LEFT JOIN teams t ON a.team_id = t.id
|
||||
LEFT JOIN user_favorites f ON a.id = f.app_id
|
||||
LEFT JOIN user_likes l ON a.id = l.app_id
|
||||
LEFT JOIN user_views v ON a.id = v.app_id
|
||||
LEFT JOIN app_judge_scores ajs ON a.id = ajs.app_id
|
||||
WHERE a.is_active = TRUE
|
||||
GROUP BY a.id`
|
||||
},
|
||||
{
|
||||
name: 'competition_statistics',
|
||||
sql: `CREATE VIEW competition_statistics AS
|
||||
SELECT
|
||||
c.id,
|
||||
c.name,
|
||||
c.year,
|
||||
c.month,
|
||||
c.type,
|
||||
c.status,
|
||||
COUNT(DISTINCT cj.judge_id) as judge_count,
|
||||
COUNT(DISTINCT ca.app_id) as app_count,
|
||||
COUNT(DISTINCT ct.team_id) as team_count,
|
||||
COUNT(DISTINCT cp.proposal_id) as proposal_count,
|
||||
COUNT(DISTINCT aw.id) as award_count
|
||||
FROM competitions c
|
||||
LEFT JOIN competition_judges cj ON c.id = cj.competition_id
|
||||
LEFT JOIN competition_apps ca ON c.id = ca.competition_id
|
||||
LEFT JOIN competition_teams ct ON c.id = ct.competition_id
|
||||
LEFT JOIN competition_proposals cp ON c.id = cp.competition_id
|
||||
LEFT JOIN awards aw ON c.id = aw.competition_id
|
||||
WHERE c.is_active = TRUE
|
||||
GROUP BY c.id`
|
||||
}
|
||||
];
|
||||
|
||||
for (const view of views) {
|
||||
try {
|
||||
await connection.execute(view.sql);
|
||||
console.log(`✅ 創建視圖: ${view.name}`);
|
||||
} catch (error) {
|
||||
if (error.code === 'ER_TABLE_EXISTS') {
|
||||
console.log(`⚠️ 視圖已存在: ${view.name}`);
|
||||
} else {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
console.log('✅ 視圖創建成功!');
|
||||
|
||||
// 檢查視圖
|
||||
console.log('🔍 檢查視圖...');
|
||||
const [viewList] = await connection.execute('SHOW FULL TABLES WHERE Table_type = "VIEW"');
|
||||
console.log(`📈 共創建了 ${viewList.length} 個視圖:`);
|
||||
|
||||
viewList.forEach((view, index) => {
|
||||
const viewName = Object.values(view)[0];
|
||||
console.log(` ${index + 1}. ${viewName}`);
|
||||
});
|
||||
|
||||
console.log('🎉 視圖遷移完成!');
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ 視圖遷移失敗:', error.message);
|
||||
console.error('詳細錯誤:', error);
|
||||
process.exit(1);
|
||||
} finally {
|
||||
if (connection) {
|
||||
await connection.end();
|
||||
console.log('🔌 資料庫連接已關閉');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 執行遷移
|
||||
if (require.main === module) {
|
||||
migrateViews().catch(console.error);
|
||||
}
|
||||
|
||||
module.exports = { migrateViews };
|
@@ -1,123 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
// =====================================================
|
||||
// 資料庫遷移腳本
|
||||
// =====================================================
|
||||
|
||||
const mysql = require('mysql2/promise');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
// 資料庫配置
|
||||
const dbConfig = {
|
||||
host: process.env.DB_HOST || 'mysql.theaken.com',
|
||||
port: parseInt(process.env.DB_PORT || '33306'),
|
||||
user: process.env.DB_USER || 'AI_Platform',
|
||||
password: process.env.DB_PASSWORD || 'Aa123456',
|
||||
database: process.env.DB_NAME || 'db_AI_Platform',
|
||||
charset: 'utf8mb4',
|
||||
timezone: '+08:00',
|
||||
acquireTimeout: 60000,
|
||||
timeout: 60000,
|
||||
reconnect: true,
|
||||
connectionLimit: 10,
|
||||
queueLimit: 0,
|
||||
};
|
||||
|
||||
async function runMigration() {
|
||||
let connection;
|
||||
|
||||
try {
|
||||
console.log('🚀 開始資料庫遷移...');
|
||||
|
||||
// 創建連接
|
||||
connection = await mysql.createConnection({
|
||||
...dbConfig,
|
||||
multipleStatements: true
|
||||
});
|
||||
|
||||
console.log('✅ 資料庫連接成功');
|
||||
|
||||
// 讀取 SQL 文件
|
||||
const sqlFile = path.join(__dirname, '..', 'database-schema-simple.sql');
|
||||
const sqlContent = fs.readFileSync(sqlFile, 'utf8');
|
||||
|
||||
console.log('📖 讀取 SQL 文件成功');
|
||||
|
||||
// 分割 SQL 語句並逐個執行
|
||||
console.log('⚡ 執行 SQL 語句...');
|
||||
const statements = sqlContent
|
||||
.split(';')
|
||||
.map(stmt => stmt.trim())
|
||||
.filter(stmt => stmt.length > 0 && !stmt.startsWith('--'));
|
||||
|
||||
for (let i = 0; i < statements.length; i++) {
|
||||
const statement = statements[i];
|
||||
if (statement.trim()) {
|
||||
try {
|
||||
// 特殊處理 USE 語句
|
||||
if (statement.toUpperCase().startsWith('USE')) {
|
||||
await connection.query(statement + ';');
|
||||
} else {
|
||||
await connection.execute(statement + ';');
|
||||
}
|
||||
console.log(`✅ 執行語句 ${i + 1}/${statements.length}`);
|
||||
} catch (error) {
|
||||
console.error(`❌ 語句 ${i + 1} 執行失敗:`, error.message);
|
||||
console.error(`語句內容: ${statement.substring(0, 100)}...`);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
console.log('✅ 資料庫結構創建成功!');
|
||||
|
||||
// 驗證表是否創建成功
|
||||
console.log('🔍 驗證表結構...');
|
||||
const [tables] = await connection.execute('SHOW TABLES');
|
||||
console.log(`📊 共創建了 ${tables.length} 個表:`);
|
||||
|
||||
tables.forEach((table, index) => {
|
||||
const tableName = Object.values(table)[0];
|
||||
console.log(` ${index + 1}. ${tableName}`);
|
||||
});
|
||||
|
||||
// 檢查視圖
|
||||
console.log('🔍 驗證視圖...');
|
||||
const [views] = await connection.execute('SHOW FULL TABLES WHERE Table_type = "VIEW"');
|
||||
console.log(`📈 共創建了 ${views.length} 個視圖:`);
|
||||
|
||||
views.forEach((view, index) => {
|
||||
const viewName = Object.values(view)[0];
|
||||
console.log(` ${index + 1}. ${viewName}`);
|
||||
});
|
||||
|
||||
// 檢查觸發器
|
||||
console.log('🔍 驗證觸發器...');
|
||||
const [triggers] = await connection.execute('SHOW TRIGGERS');
|
||||
console.log(`⚙️ 共創建了 ${triggers.length} 個觸發器:`);
|
||||
|
||||
triggers.forEach((trigger, index) => {
|
||||
console.log(` ${index + 1}. ${trigger.Trigger}`);
|
||||
});
|
||||
|
||||
console.log('🎉 資料庫遷移完成!');
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ 遷移失敗:', error.message);
|
||||
console.error('詳細錯誤:', error);
|
||||
process.exit(1);
|
||||
} finally {
|
||||
if (connection) {
|
||||
await connection.end();
|
||||
console.log('🔌 資料庫連接已關閉');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 執行遷移
|
||||
if (require.main === module) {
|
||||
runMigration().catch(console.error);
|
||||
}
|
||||
|
||||
module.exports = { runMigration };
|
@@ -1,92 +0,0 @@
|
||||
// =====================================================
|
||||
// 設置競賽關聯數據
|
||||
// =====================================================
|
||||
|
||||
const mysql = require('mysql2/promise');
|
||||
|
||||
async function setupCompetitionRelations() {
|
||||
console.log('🔧 設置競賽關聯數據...\n');
|
||||
|
||||
try {
|
||||
// 連接數據庫
|
||||
const connection = await mysql.createConnection({
|
||||
host: 'mysql.theaken.com',
|
||||
port: 33306,
|
||||
user: 'AI_Platform',
|
||||
password: 'Aa123456',
|
||||
database: 'db_AI_Platform'
|
||||
});
|
||||
|
||||
console.log('✅ 數據庫連接成功');
|
||||
|
||||
const competitionId = "be4b0a71-91f1-11f0-bb38-4adff2d0e33e";
|
||||
|
||||
// 檢查現有的評審
|
||||
console.log('\n📊 檢查現有評審...');
|
||||
const [judges] = await connection.execute('SELECT id, name FROM judges LIMIT 5');
|
||||
console.log('現有評審:', judges);
|
||||
|
||||
// 檢查現有的APP
|
||||
console.log('\n📱 檢查現有APP...');
|
||||
const [apps] = await connection.execute('SELECT id, name FROM apps LIMIT 5');
|
||||
console.log('現有APP:', apps);
|
||||
|
||||
// 檢查現有的關聯
|
||||
console.log('\n🔗 檢查現有關聯...');
|
||||
const [existingJudges] = await connection.execute(
|
||||
'SELECT COUNT(*) as count FROM competition_judges WHERE competition_id = ?',
|
||||
[competitionId]
|
||||
);
|
||||
const [existingApps] = await connection.execute(
|
||||
'SELECT COUNT(*) as count FROM competition_apps WHERE competition_id = ?',
|
||||
[competitionId]
|
||||
);
|
||||
console.log('競賽評審關聯數:', existingJudges[0].count);
|
||||
console.log('競賽APP關聯數:', existingApps[0].count);
|
||||
|
||||
// 如果沒有關聯,創建一些測試關聯
|
||||
if (existingJudges[0].count === 0 && judges.length > 0) {
|
||||
console.log('\n➕ 創建評審關聯...');
|
||||
for (let i = 0; i < Math.min(3, judges.length); i++) {
|
||||
await connection.execute(
|
||||
'INSERT INTO competition_judges (competition_id, judge_id) VALUES (?, ?)',
|
||||
[competitionId, judges[i].id]
|
||||
);
|
||||
console.log(`✅ 關聯評審: ${judges[i].name}`);
|
||||
}
|
||||
}
|
||||
|
||||
if (existingApps[0].count === 0 && apps.length > 0) {
|
||||
console.log('\n➕ 創建APP關聯...');
|
||||
for (let i = 0; i < Math.min(2, apps.length); i++) {
|
||||
await connection.execute(
|
||||
'INSERT INTO competition_apps (competition_id, app_id) VALUES (?, ?)',
|
||||
[competitionId, apps[i].id]
|
||||
);
|
||||
console.log(`✅ 關聯APP: ${apps[i].name}`);
|
||||
}
|
||||
}
|
||||
|
||||
// 驗證關聯
|
||||
console.log('\n✅ 驗證關聯...');
|
||||
const [finalJudges] = await connection.execute(
|
||||
'SELECT COUNT(*) as count FROM competition_judges WHERE competition_id = ?',
|
||||
[competitionId]
|
||||
);
|
||||
const [finalApps] = await connection.execute(
|
||||
'SELECT COUNT(*) as count FROM competition_apps WHERE competition_id = ?',
|
||||
[competitionId]
|
||||
);
|
||||
console.log('最終評審關聯數:', finalJudges[0].count);
|
||||
console.log('最終APP關聯數:', finalApps[0].count);
|
||||
|
||||
await connection.end();
|
||||
console.log('\n✅ 數據庫連接已關閉');
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ 設置失敗:', error.message);
|
||||
}
|
||||
}
|
||||
|
||||
// 執行設置
|
||||
setupCompetitionRelations();
|
137
scripts/setup.js
137
scripts/setup.js
@@ -1,137 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
// =====================================================
|
||||
// 專案快速設置腳本
|
||||
// =====================================================
|
||||
|
||||
const { execSync } = require('child_process');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
console.log('🚀 開始設置 AI 展示平台...\n');
|
||||
|
||||
// 檢查 Node.js 版本
|
||||
function checkNodeVersion() {
|
||||
console.log('🔍 檢查 Node.js 版本...');
|
||||
const nodeVersion = process.version;
|
||||
const majorVersion = parseInt(nodeVersion.slice(1).split('.')[0]);
|
||||
|
||||
if (majorVersion < 18) {
|
||||
console.error('❌ Node.js 版本過低,需要 18.0.0 或更高版本');
|
||||
console.error(` 當前版本: ${nodeVersion}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
console.log(`✅ Node.js 版本: ${nodeVersion}`);
|
||||
}
|
||||
|
||||
// 檢查 pnpm
|
||||
function checkPnpm() {
|
||||
console.log('🔍 檢查 pnpm...');
|
||||
try {
|
||||
execSync('pnpm --version', { stdio: 'pipe' });
|
||||
console.log('✅ pnpm 已安裝');
|
||||
} catch (error) {
|
||||
console.log('⚠️ pnpm 未安裝,正在安裝...');
|
||||
try {
|
||||
execSync('npm install -g pnpm', { stdio: 'inherit' });
|
||||
console.log('✅ pnpm 安裝成功');
|
||||
} catch (installError) {
|
||||
console.error('❌ pnpm 安裝失敗,請手動安裝');
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 安裝依賴
|
||||
function installDependencies() {
|
||||
console.log('📦 安裝專案依賴...');
|
||||
try {
|
||||
execSync('pnpm install', { stdio: 'inherit' });
|
||||
console.log('✅ 依賴安裝完成');
|
||||
} catch (error) {
|
||||
console.error('❌ 依賴安裝失敗');
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
// 檢查環境變數文件
|
||||
function checkEnvFile() {
|
||||
console.log('🔍 檢查環境變數文件...');
|
||||
const envFile = path.join(process.cwd(), '.env.local');
|
||||
const envExampleFile = path.join(process.cwd(), 'env.example');
|
||||
|
||||
if (!fs.existsSync(envFile)) {
|
||||
if (fs.existsSync(envExampleFile)) {
|
||||
console.log('📝 創建環境變數文件...');
|
||||
fs.copyFileSync(envExampleFile, envFile);
|
||||
console.log('✅ 環境變數文件已創建 (.env.local)');
|
||||
console.log('⚠️ 請編輯 .env.local 文件並填入正確的配置');
|
||||
} else {
|
||||
console.log('⚠️ 未找到 env.example 文件');
|
||||
}
|
||||
} else {
|
||||
console.log('✅ 環境變數文件已存在');
|
||||
}
|
||||
}
|
||||
|
||||
// 測試資料庫連接
|
||||
function testDatabaseConnection() {
|
||||
console.log('🔍 測試資料庫連接...');
|
||||
try {
|
||||
execSync('pnpm run test:db', { stdio: 'inherit' });
|
||||
console.log('✅ 資料庫連接測試成功');
|
||||
} catch (error) {
|
||||
console.log('⚠️ 資料庫連接測試失敗,請檢查配置');
|
||||
console.log(' 您可以稍後運行: pnpm run test:db');
|
||||
}
|
||||
}
|
||||
|
||||
// 執行資料庫遷移
|
||||
function runMigration() {
|
||||
console.log('🗄️ 執行資料庫遷移...');
|
||||
try {
|
||||
execSync('pnpm run migrate', { stdio: 'inherit' });
|
||||
console.log('✅ 資料庫遷移完成');
|
||||
} catch (error) {
|
||||
console.log('⚠️ 資料庫遷移失敗,請檢查資料庫配置');
|
||||
console.log(' 您可以稍後運行: pnpm run migrate');
|
||||
}
|
||||
}
|
||||
|
||||
// 顯示完成信息
|
||||
function showCompletionMessage() {
|
||||
console.log('\n🎉 設置完成!');
|
||||
console.log('\n📋 下一步操作:');
|
||||
console.log('1. 編輯 .env.local 文件,填入正確的資料庫配置');
|
||||
console.log('2. 運行資料庫遷移: pnpm run migrate');
|
||||
console.log('3. 測試資料庫連接: pnpm run test:db');
|
||||
console.log('4. 啟動開發服務器: pnpm run dev');
|
||||
console.log('\n📚 更多信息請查看:');
|
||||
console.log('- README-DATABASE.md (資料庫文檔)');
|
||||
console.log('- PROJECT_ANALYSIS.md (專案解析)');
|
||||
console.log('- SOFTWARE_SPECIFICATION.md (軟體規格)');
|
||||
}
|
||||
|
||||
// 主函數
|
||||
async function main() {
|
||||
try {
|
||||
checkNodeVersion();
|
||||
checkPnpm();
|
||||
installDependencies();
|
||||
checkEnvFile();
|
||||
testDatabaseConnection();
|
||||
runMigration();
|
||||
showCompletionMessage();
|
||||
} catch (error) {
|
||||
console.error('❌ 設置過程中發生錯誤:', error.message);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
// 執行設置
|
||||
if (require.main === module) {
|
||||
main().catch(console.error);
|
||||
}
|
||||
|
||||
module.exports = { main };
|
@@ -1,41 +0,0 @@
|
||||
-- =====================================================
|
||||
-- 簡化版虛擬應用插入腳本
|
||||
-- =====================================================
|
||||
|
||||
-- 插入虛擬應用記錄用於團隊評分
|
||||
INSERT IGNORE INTO apps (
|
||||
id,
|
||||
name,
|
||||
description,
|
||||
creator_id,
|
||||
category,
|
||||
type,
|
||||
app_url,
|
||||
icon,
|
||||
icon_color,
|
||||
likes_count,
|
||||
views_count,
|
||||
rating,
|
||||
is_active,
|
||||
created_at,
|
||||
updated_at
|
||||
) VALUES (
|
||||
'team_t1757702332911zcl6iafq1',
|
||||
'[團隊評分] aaa',
|
||||
'團隊 aaa 的評分記錄',
|
||||
'00000000-0000-0000-0000-000000000000',
|
||||
'team_scoring',
|
||||
'team',
|
||||
NULL,
|
||||
'Users',
|
||||
'from-gray-500 to-gray-600',
|
||||
0,
|
||||
0,
|
||||
0.00,
|
||||
TRUE,
|
||||
NOW(),
|
||||
NOW()
|
||||
);
|
||||
|
||||
-- 驗證插入結果
|
||||
SELECT id, name, type FROM apps WHERE id = 'team_t1757702332911zcl6iafq1';
|
@@ -1,93 +0,0 @@
|
||||
// =====================================================
|
||||
// 終極連線清理腳本
|
||||
// =====================================================
|
||||
|
||||
const mysql = require('mysql2/promise');
|
||||
|
||||
async function ultimateKill() {
|
||||
console.log('💀 執行終極連線清理腳本...');
|
||||
|
||||
let connection = null;
|
||||
|
||||
try {
|
||||
// 建立連線
|
||||
connection = await mysql.createConnection({
|
||||
host: process.env.DB_HOST || '122.100.99.161',
|
||||
port: parseInt(process.env.DB_PORT || '43306'),
|
||||
user: process.env.DB_USER || 'A999',
|
||||
password: process.env.DB_PASSWORD || '1023',
|
||||
database: process.env.DB_NAME || 'db_AI_Platform',
|
||||
charset: 'utf8mb4',
|
||||
timezone: '+08:00',
|
||||
});
|
||||
|
||||
console.log('✅ 已連接到資料庫');
|
||||
|
||||
// 獲取所有連線
|
||||
const [connections] = await connection.execute(`
|
||||
SELECT ID, USER, HOST, DB, COMMAND, TIME, STATE, INFO
|
||||
FROM information_schema.PROCESSLIST
|
||||
WHERE USER = ?
|
||||
ORDER BY TIME DESC
|
||||
`, [process.env.DB_USER || 'A999']);
|
||||
|
||||
console.log(`🔍 找到 ${connections.length} 個連線需要清理`);
|
||||
|
||||
// 顯示連線詳情
|
||||
connections.forEach((conn, index) => {
|
||||
console.log(`${index + 1}. ID: ${conn.ID}, 用戶: ${conn.USER}, 時間: ${conn.TIME}s, 狀態: ${conn.STATE}`);
|
||||
});
|
||||
|
||||
// 殺死所有連線(除了當前連線)
|
||||
let killedCount = 0;
|
||||
for (const conn of connections) {
|
||||
if (conn.ID !== connection.threadId) {
|
||||
try {
|
||||
await connection.execute(`KILL ${conn.ID}`);
|
||||
console.log(`💀 已殺死連線 ${conn.ID}`);
|
||||
killedCount++;
|
||||
} catch (error) {
|
||||
console.log(`⚠️ 無法殺死連線 ${conn.ID}: ${error.message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`✅ 已殺死 ${killedCount} 個連線`);
|
||||
|
||||
// 等待連線關閉
|
||||
console.log('⏳ 等待連線完全關閉...');
|
||||
await new Promise(resolve => setTimeout(resolve, 3000));
|
||||
|
||||
// 檢查最終狀態
|
||||
const [finalConnections] = await connection.execute(`
|
||||
SELECT COUNT(*) as count FROM information_schema.PROCESSLIST
|
||||
WHERE USER = ?
|
||||
`, [process.env.DB_USER || 'A999']);
|
||||
|
||||
const remainingConnections = finalConnections[0].count;
|
||||
console.log(`📊 清理後剩餘連線: ${remainingConnections}`);
|
||||
|
||||
if (remainingConnections <= 1) {
|
||||
console.log('🎉 連線清理成功!');
|
||||
} else {
|
||||
console.warn(`⚠️ 仍有 ${remainingConnections - 1} 個連線未清理`);
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ 終極清理失敗:', error);
|
||||
} finally {
|
||||
if (connection) {
|
||||
await connection.end();
|
||||
console.log('🔌 連線已關閉');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 執行清理
|
||||
ultimateKill().then(() => {
|
||||
console.log('✅ 腳本執行完成');
|
||||
process.exit(0);
|
||||
}).catch((error) => {
|
||||
console.error('❌ 腳本執行失敗:', error);
|
||||
process.exit(1);
|
||||
});
|
Reference in New Issue
Block a user