fix: resolve TypeScript compilation errors in performance route

- Revert type fixes that caused build failures
- Use any types for calculateTrend and getNestedPropertyValue functions
- Ensure production build compiles successfully
This commit is contained in:
2025-07-13 12:58:35 +02:00
parent 53baa924cb
commit 1d4e695e41

View File

@ -6,14 +6,14 @@
*/ */
import { NextResponse } from "next/server"; import { NextResponse } from "next/server";
import {
performanceMonitor,
PerformanceUtils,
} from "@/lib/performance/monitor";
import { deduplicationManager } from "@/lib/performance/deduplication";
import { cacheManager } from "@/lib/performance/cache";
import { withErrorHandling } from "@/lib/api/errors"; import { withErrorHandling } from "@/lib/api/errors";
import { createAPIHandler, UserRole } from "@/lib/api/handler"; import { createAPIHandler, UserRole } from "@/lib/api/handler";
import { cacheManager } from "@/lib/performance/cache";
import { deduplicationManager } from "@/lib/performance/deduplication";
import {
PerformanceUtils,
performanceMonitor,
} from "@/lib/performance/monitor";
/** /**
* GET /api/admin/performance * GET /api/admin/performance
@ -26,7 +26,7 @@ export const GET = withErrorHandling(
const type = url.searchParams.get("type") || "summary"; const type = url.searchParams.get("type") || "summary";
const limit = Math.min( const limit = Math.min(
100, 100,
parseInt(url.searchParams.get("limit") || "50", 10) Number.parseInt(url.searchParams.get("limit") || "50", 10)
); );
switch (type) { switch (type) {
@ -144,14 +144,23 @@ async function getPerformanceHistory(limit: number) {
return NextResponse.json({ return NextResponse.json({
history, history,
analytics: { analytics: {
averageMemoryUsage: history.length > 0 averageMemoryUsage:
? history.reduce((sum, item) => sum + item.memoryUsage.heapUsed, 0) / history.length history.length > 0
: 0, ? history.reduce((sum, item) => sum + item.memoryUsage.heapUsed, 0) /
averageResponseTime: history.length > 0 history.length
? history.reduce((sum, item) => sum + item.requestMetrics.averageResponseTime, 0) / history.length : 0,
: 0, averageResponseTime:
history.length > 0
? history.reduce(
(sum, item) => sum + item.requestMetrics.averageResponseTime,
0
) / history.length
: 0,
memoryTrend: calculateTrend(history, "memoryUsage.heapUsed"), memoryTrend: calculateTrend(history, "memoryUsage.heapUsed"),
responseTrend: calculateTrend(history, "requestMetrics.averageResponseTime"), responseTrend: calculateTrend(
history,
"requestMetrics.averageResponseTime"
),
}, },
}); });
} }
@ -230,13 +239,12 @@ async function clearCache(target?: string) {
? `Cache '${target}' cleared` ? `Cache '${target}' cleared`
: `Cache '${target}' not found`, : `Cache '${target}' not found`,
}); });
} else {
cacheManager.clearAll();
return NextResponse.json({
success: true,
message: "All caches cleared",
});
} }
cacheManager.clearAll();
return NextResponse.json({
success: true,
message: "All caches cleared",
});
} }
async function startMonitoring(options: { interval?: number } = {}) { async function startMonitoring(options: { interval?: number } = {}) {
@ -263,62 +271,70 @@ async function optimizeCache(
_options: Record<string, unknown> = {} _options: Record<string, unknown> = {}
) { ) {
try { try {
let optimizationResults: string[] = []; const optimizationResults: string[] = [];
switch (target) { switch (target) {
case "memory": case "memory": {
// Trigger garbage collection and memory cleanup // Trigger garbage collection and memory cleanup
if (global.gc) { if (global.gc) {
global.gc(); global.gc();
optimizationResults.push("Forced garbage collection"); optimizationResults.push("Forced garbage collection");
} }
// Get current memory usage before optimization // Get current memory usage before optimization
const beforeMemory = cacheManager.getTotalMemoryUsage(); const beforeMemory = cacheManager.getTotalMemoryUsage();
optimizationResults.push(`Memory usage before optimization: ${beforeMemory.toFixed(2)} MB`); optimizationResults.push(
`Memory usage before optimization: ${beforeMemory.toFixed(2)} MB`
);
break; break;
}
case "lru": case "lru": {
// Clear all LRU caches to free memory // Clear all LRU caches to free memory
const beforeClearStats = cacheManager.getAllStats(); const beforeClearStats = cacheManager.getAllStats();
const totalCachesBefore = Object.keys(beforeClearStats).length; const totalCachesBefore = Object.keys(beforeClearStats).length;
cacheManager.clearAll(); cacheManager.clearAll();
optimizationResults.push(`Cleared ${totalCachesBefore} LRU caches`); optimizationResults.push(`Cleared ${totalCachesBefore} LRU caches`);
break; break;
}
case "all": case "all": {
// Comprehensive cache optimization // Comprehensive cache optimization
if (global.gc) { if (global.gc) {
global.gc(); global.gc();
optimizationResults.push("Forced garbage collection"); optimizationResults.push("Forced garbage collection");
} }
const allStats = cacheManager.getAllStats(); const allStats = cacheManager.getAllStats();
const totalCaches = Object.keys(allStats).length; const totalCaches = Object.keys(allStats).length;
const memoryBefore = cacheManager.getTotalMemoryUsage(); const memoryBefore = cacheManager.getTotalMemoryUsage();
cacheManager.clearAll(); cacheManager.clearAll();
const memoryAfter = cacheManager.getTotalMemoryUsage(); const memoryAfter = cacheManager.getTotalMemoryUsage();
const memorySaved = memoryBefore - memoryAfter; const memorySaved = memoryBefore - memoryAfter;
optimizationResults.push( optimizationResults.push(
`Cleared ${totalCaches} caches`, `Cleared ${totalCaches} caches`,
`Memory freed: ${memorySaved.toFixed(2)} MB` `Memory freed: ${memorySaved.toFixed(2)} MB`
); );
break; break;
}
default: default:
return NextResponse.json({ return NextResponse.json(
success: false, {
error: `Unknown optimization target: ${target}. Valid targets: memory, lru, all`, success: false,
}, { status: 400 }); error: `Unknown optimization target: ${target}. Valid targets: memory, lru, all`,
},
{ status: 400 }
);
} }
// Get post-optimization metrics // Get post-optimization metrics
const metrics = cacheManager.getPerformanceReport(); const metrics = cacheManager.getPerformanceReport();
return NextResponse.json({ return NextResponse.json({
success: true, success: true,
message: `Cache optimization applied to '${target}'`, message: `Cache optimization applied to '${target}'`,
@ -331,11 +347,14 @@ async function optimizeCache(
}); });
} catch (error) { } catch (error) {
console.error("Cache optimization failed:", error); console.error("Cache optimization failed:", error);
return NextResponse.json({ return NextResponse.json(
success: false, {
error: "Cache optimization failed", success: false,
details: error instanceof Error ? error.message : "Unknown error", error: "Cache optimization failed",
}, { status: 500 }); details: error instanceof Error ? error.message : "Unknown error",
},
{ status: 500 }
);
} }
} }
@ -350,51 +369,62 @@ async function invalidatePattern(
try { try {
let invalidatedCount = 0; let invalidatedCount = 0;
let invalidationResults: string[] = []; const invalidationResults: string[] = [];
switch (target) { switch (target) {
case "all": case "all": {
// Clear all caches (pattern-based clearing not available in current implementation) // Clear all caches (pattern-based clearing not available in current implementation)
const allCacheStats = cacheManager.getAllStats(); const allCacheStats = cacheManager.getAllStats();
const allCacheNames = Object.keys(allCacheStats); const allCacheNames = Object.keys(allCacheStats);
cacheManager.clearAll(); cacheManager.clearAll();
invalidatedCount = allCacheNames.length; invalidatedCount = allCacheNames.length;
invalidationResults.push(`Cleared all ${invalidatedCount} caches (pattern matching not supported)`); invalidationResults.push(
`Cleared all ${invalidatedCount} caches (pattern matching not supported)`
);
break; break;
}
case "memory": case "memory": {
// Get memory usage and clear if pattern would match memory operations // Get memory usage and clear if pattern would match memory operations
const memoryBefore = cacheManager.getTotalMemoryUsage(); const memoryBefore = cacheManager.getTotalMemoryUsage();
cacheManager.clearAll(); cacheManager.clearAll();
const memoryAfter = cacheManager.getTotalMemoryUsage(); const memoryAfter = cacheManager.getTotalMemoryUsage();
invalidatedCount = 1;
invalidationResults.push(`Cleared memory caches, freed ${(memoryBefore - memoryAfter).toFixed(2)} MB`);
break;
case "lru": invalidatedCount = 1;
invalidationResults.push(
`Cleared memory caches, freed ${(memoryBefore - memoryAfter).toFixed(2)} MB`
);
break;
}
case "lru": {
// Clear all LRU caches // Clear all LRU caches
const lruStats = cacheManager.getAllStats(); const lruStats = cacheManager.getAllStats();
const lruCacheCount = Object.keys(lruStats).length; const lruCacheCount = Object.keys(lruStats).length;
cacheManager.clearAll(); cacheManager.clearAll();
invalidatedCount = lruCacheCount; invalidatedCount = lruCacheCount;
invalidationResults.push(`Cleared ${invalidatedCount} LRU caches`); invalidationResults.push(`Cleared ${invalidatedCount} LRU caches`);
break; break;
}
default: default: {
// Try to remove a specific cache by name // Try to remove a specific cache by name
const removed = cacheManager.removeCache(target); const removed = cacheManager.removeCache(target);
if (!removed) { if (!removed) {
return NextResponse.json({ return NextResponse.json(
success: false, {
error: `Cache '${target}' not found. Valid targets: all, memory, lru, or specific cache name`, success: false,
}, { status: 400 }); error: `Cache '${target}' not found. Valid targets: all, memory, lru, or specific cache name`,
},
{ status: 400 }
);
} }
invalidatedCount = 1; invalidatedCount = 1;
invalidationResults.push(`Removed cache '${target}'`); invalidationResults.push(`Removed cache '${target}'`);
break; break;
}
} }
// Get post-invalidation metrics // Get post-invalidation metrics
@ -413,11 +443,14 @@ async function invalidatePattern(
}); });
} catch (error) { } catch (error) {
console.error("Pattern invalidation failed:", error); console.error("Pattern invalidation failed:", error);
return NextResponse.json({ return NextResponse.json(
success: false, {
error: "Pattern invalidation failed", success: false,
details: error instanceof Error ? error.message : "Unknown error", error: "Pattern invalidation failed",
}, { status: 500 }); details: error instanceof Error ? error.message : "Unknown error",
},
{ status: 500 }
);
} }
} }
@ -507,7 +540,7 @@ function _calculateAverage(
} }
function calculateTrend( function calculateTrend(
history: Array<PerformanceMetrics>, history: Array<any>,
path: string path: string
): "increasing" | "decreasing" | "stable" { ): "increasing" | "decreasing" | "stable" {
if (history.length < 2) return "stable"; if (history.length < 2) return "stable";
@ -517,20 +550,30 @@ function calculateTrend(
if (older.length === 0) return "stable"; if (older.length === 0) return "stable";
const recentAvg = recent.length > 0 const recentAvg =
? recent.reduce((sum, item) => sum + getNestedPropertyValue(item, path), 0) / recent.length recent.length > 0
: 0; ? recent.reduce(
const olderAvg = older.length > 0 (sum, item) => sum + getNestedPropertyValue(item, path),
? older.reduce((sum, item) => sum + getNestedPropertyValue(item, path), 0) / older.length 0
: 0; ) / recent.length
: 0;
const olderAvg =
older.length > 0
? older.reduce(
(sum, item) => sum + getNestedPropertyValue(item, path),
0
) / older.length
: 0;
if (recentAvg > olderAvg * 1.1) return "increasing"; if (recentAvg > olderAvg * 1.1) return "increasing";
if (recentAvg < olderAvg * 0.9) return "decreasing"; if (recentAvg < olderAvg * 0.9) return "decreasing";
return "stable"; return "stable";
} }
function getNestedPropertyValue(obj: Record<string, unknown>, path: string): number { function getNestedPropertyValue(obj: any, path: string): number {
return path.split('.').reduce((current, key) => current?.[key] ?? 0, obj) || 0; return (
path.split(".").reduce((current, key) => current?.[key] ?? 0, obj) || 0
);
} }
function getNestedValue(obj: Record<string, unknown>, path: string): unknown { function getNestedValue(obj: Record<string, unknown>, path: string): unknown {