修復 too many connection 問題

This commit is contained in:
2025-09-21 02:46:16 +08:00
parent a36ab3c98d
commit 808d5bb52c
36 changed files with 5582 additions and 249 deletions

177
app/api/ip-cleanup/route.ts Normal file
View File

@@ -0,0 +1,177 @@
// =====================================================
// 基於 IP 的連線清理 API
// =====================================================
import { NextRequest, NextResponse } from 'next/server';
import { smartIPPool } from '@/lib/smart-ip-connection-pool';
import { smartIPDetector } from '@/lib/smart-ip-detector';
export async function POST(request: NextRequest) {
try {
const body = await request.json();
const { action, targetIP } = body;
// 使用智能 IP 偵測器
const ipDetection = smartIPDetector.detectClientIP(request);
const clientIP = ipDetection.detectedIP;
console.log('🎯 智能 IP 偵測結果:', {
detectedIP: clientIP,
confidence: ipDetection.confidence,
source: ipDetection.source,
isPublicIP: ipDetection.isPublicIP,
allCandidates: ipDetection.allCandidates
});
// 設置客戶端 IP
smartIPPool.setClientIP(clientIP);
switch (action) {
case 'cleanup-current':
// 清理當前 IP 的連線
console.log(`🧹 收到清理當前 IP 連線請求: ${clientIP}`);
const cleanupResult = await smartIPPool.cleanupCurrentIPConnections();
return NextResponse.json({
success: cleanupResult.success,
message: cleanupResult.message,
data: {
clientIP,
killedCount: cleanupResult.killedCount
},
timestamp: new Date().toISOString()
});
case 'cleanup-specific':
// 清理指定 IP 的連線
if (!targetIP) {
return NextResponse.json({
success: false,
error: '缺少目標 IP 參數'
}, { status: 400 });
}
console.log(`🧹 收到清理指定 IP 連線請求: ${targetIP}`);
const specificCleanupResult = await smartIPPool.cleanupIPConnections(targetIP);
return NextResponse.json({
success: specificCleanupResult.success,
message: specificCleanupResult.message,
data: {
targetIP,
killedCount: specificCleanupResult.killedCount
},
timestamp: new Date().toISOString()
});
case 'cleanup-local':
// 清理本地追蹤的連線
console.log('🧹 收到清理本地連線請求');
const localCleanupCount = smartIPPool.cleanupLocalConnections();
return NextResponse.json({
success: true,
message: `已清理 ${localCleanupCount} 個本地追蹤的連線`,
data: {
clientIP,
cleanedCount: localCleanupCount
},
timestamp: new Date().toISOString()
});
default:
return NextResponse.json({
success: false,
error: '無效的操作參數',
availableActions: ['cleanup-current', 'cleanup-specific', 'cleanup-local']
}, { status: 400 });
}
} catch (error) {
console.error('❌ IP 清理 API 錯誤:', error);
return NextResponse.json({
success: false,
error: 'IP 清理失敗',
details: error instanceof Error ? error.message : '未知錯誤'
}, { status: 500 });
}
}
export async function GET(request: NextRequest) {
try {
const { searchParams } = new URL(request.url);
const action = searchParams.get('action') || 'status';
const targetIP = searchParams.get('ip');
// 使用智能 IP 偵測器
const ipDetection = smartIPDetector.detectClientIP(request);
const clientIP = ipDetection.detectedIP;
// 設置客戶端 IP
smartIPPool.setClientIP(clientIP);
switch (action) {
case 'status':
// 獲取當前 IP 的連線狀態
const currentIPStatus = await smartIPPool.getCurrentIPConnections();
return NextResponse.json({
success: true,
message: '連線狀態獲取成功',
data: {
detectedIP: clientIP,
...currentIPStatus
},
timestamp: new Date().toISOString()
});
case 'status-specific':
// 獲取指定 IP 的連線狀態
if (!targetIP) {
return NextResponse.json({
success: false,
error: '缺少目標 IP 參數'
}, { status: 400 });
}
const specificIPStatus = await smartIPPool.getIPConnections(targetIP);
return NextResponse.json({
success: true,
message: '指定 IP 連線狀態獲取成功',
data: {
targetIP,
...specificIPStatus
},
timestamp: new Date().toISOString()
});
case 'local-stats':
// 獲取本地連線統計
const localStats = smartIPPool.getLocalConnectionStats();
return NextResponse.json({
success: true,
message: '本地連線統計獲取成功',
data: {
detectedIP: clientIP,
...localStats
},
timestamp: new Date().toISOString()
});
default:
return NextResponse.json({
success: false,
error: '無效的操作參數',
availableActions: ['status', 'status-specific', 'local-stats']
}, { status: 400 });
}
} catch (error) {
console.error('❌ IP 清理 GET API 錯誤:', error);
return NextResponse.json({
success: false,
error: '獲取連線狀態失敗',
details: error instanceof Error ? error.message : '未知錯誤'
}, { status: 500 });
}
}