Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1036x 1036x 1036x 1036x 1036x 5x 5x 1036x 1x 1x 1x 1x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 1x 1x 1x 1x 11x 11x 11x 11x 1021x 1021x 1021x 1021x 1021x 1011x 1011x 1021x 10x 10x 1021x 11x 11x 11x 10x 10x 11x 11x 11x 11x 1x 1x 1x 1x 1021x 1021x 1021x 1021x 1021x 1021x 1021x 1021x 1021x 1021x 1021x 1021x 1021x 1021x 1017x 1017x 1017x 1021x 1017x 1017x 1017x 1x 1x 1x 1x 16x 16x 16x 1x 1x 1x 1x 4x 4x 4x 4x 4x 4x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 4x 4x 4x 4x | /**
* Database Query Metrics Collection
*
* Tracks slow queries and provides statistics for monitoring database performance.
* Used by Prisma query logging in src/lib/prisma.ts
*/
export interface QueryMetric {
query: string;
duration: number;
timestamp: Date;
endpoint?: string;
}
// In-memory store for query metrics (server-side only)
const queryMetrics: QueryMetric[] = [];
const MAX_METRICS = 1000;
// Performance thresholds in milliseconds
export const QUERY_THRESHOLDS = {
SLOW: 100, // Queries taking longer than 100ms
WARNING: 500, // Queries taking longer than 500ms
CRITICAL: 1000, // Queries taking longer than 1 second
} as const;
/**
* Track a slow query for monitoring
*/
export function trackSlowQuery(metric: QueryMetric): void {
queryMetrics.push(metric);
// Keep only recent metrics to prevent memory bloat
if (queryMetrics.length > MAX_METRICS) {
queryMetrics.shift();
}
}
/**
* Get query metrics statistics
*/
export function getQueryMetrics(): {
total: number;
slowQueries: number;
warningQueries: number;
criticalQueries: number;
averageDuration: number;
topSlowest: QueryMetric[];
recentQueries: QueryMetric[];
queryPatterns: { pattern: string; count: number; avgDuration: number }[];
} {
const slowQueries = queryMetrics.filter(q => q.duration > QUERY_THRESHOLDS.SLOW);
const warningQueries = queryMetrics.filter(q => q.duration > QUERY_THRESHOLDS.WARNING);
const criticalQueries = queryMetrics.filter(q => q.duration > QUERY_THRESHOLDS.CRITICAL);
const totalDuration = queryMetrics.reduce((sum, q) => sum + q.duration, 0);
const averageDuration = queryMetrics.length > 0 ? totalDuration / queryMetrics.length : 0;
// Top 10 slowest queries
const topSlowest = [...queryMetrics]
.sort((a, b) => b.duration - a.duration)
.slice(0, 10);
// Most recent 20 queries
const recentQueries = [...queryMetrics]
.sort((a, b) => b.timestamp.getTime() - a.timestamp.getTime())
.slice(0, 20);
// Analyze query patterns
const patterns = analyzeQueryPatterns(queryMetrics);
return {
total: queryMetrics.length,
slowQueries: slowQueries.length,
warningQueries: warningQueries.length,
criticalQueries: criticalQueries.length,
averageDuration: Number(averageDuration.toFixed(2)),
topSlowest,
recentQueries,
queryPatterns: patterns};
}
/**
* Analyze query patterns to identify common slow queries
*/
function analyzeQueryPatterns(metrics: QueryMetric[]): { pattern: string; count: number; avgDuration: number }[] {
const patternMap = new Map<string, { count: number; totalDuration: number }>();
for (const metric of metrics) {
// Extract table name from query as a simple pattern
const pattern = extractQueryPattern(metric.query);
const existing = patternMap.get(pattern);
if (existing) {
existing.count++;
existing.totalDuration += metric.duration;
} else {
patternMap.set(pattern, { count: 1, totalDuration: metric.duration });
}
}
return Array.from(patternMap.entries())
.map(([pattern, data]) => ({
pattern,
count: data.count,
avgDuration: Number((data.totalDuration / data.count).toFixed(2))}))
.sort((a, b) => b.avgDuration - a.avgDuration)
.slice(0, 10);
}
/**
* Extract a simplified pattern from a SQL query
*/
function extractQueryPattern(query: string): string {
// Normalize whitespace
const normalized = query.replace(/\s+/g, ' ').trim();
// Extract the main operation and table
const selectMatch = normalized.match(/SELECT.*?FROM\s+`?(\w+)`?/i);
const insertMatch = normalized.match(/INSERT\s+INTO\s+`?(\w+)`?/i);
const updateMatch = normalized.match(/UPDATE\s+`?(\w+)`?/i);
const deleteMatch = normalized.match(/DELETE\s+FROM\s+`?(\w+)`?/i);
if (selectMatch) return `SELECT ${selectMatch[1]}`;
if (insertMatch) return `INSERT ${insertMatch[1]}`;
if (updateMatch) return `UPDATE ${updateMatch[1]}`;
if (deleteMatch) return `DELETE ${deleteMatch[1]}`;
// For Prisma-style queries, extract model name
const prismaMatch = normalized.match(/prisma\.(\w+)\./);
if (prismaMatch) return `PRISMA ${prismaMatch[1]}`;
return 'UNKNOWN';
}
/**
* Clear all collected metrics (useful for testing)
*/
export function clearMetrics(): void {
queryMetrics.length = 0;
}
/**
* Get metrics summary for health checks
*/
export function getMetricsSummary(): {
healthy: boolean;
avgQueryTime: number;
slowQueryPercentage: number;
} {
if (queryMetrics.length === 0) {
return {
healthy: true,
avgQueryTime: 0,
slowQueryPercentage: 0};
}
const totalDuration = queryMetrics.reduce((sum, q) => sum + q.duration, 0);
const avgQueryTime = totalDuration / queryMetrics.length;
const slowCount = queryMetrics.filter(q => q.duration > QUERY_THRESHOLDS.SLOW).length;
const slowQueryPercentage = (slowCount / queryMetrics.length) * 100;
return {
healthy: avgQueryTime < QUERY_THRESHOLDS.SLOW && slowQueryPercentage < 10,
avgQueryTime: Number(avgQueryTime.toFixed(2)),
slowQueryPercentage: Number(slowQueryPercentage.toFixed(2))};
}
|