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 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 10x 10x 9x 9x 10x 10x 1x 10x 10x 10x 1x 10x 10x 10x 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 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 11x 11x 11x 11x 11x 1x 1x 1x 1x 1x 1x 1x 1x 1x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 11x 9x 9x 9x 9x 9x 9x 9x 8x 8x 8x 8x 8x 8x 2x 8x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 8x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 10x 10x 11x 1x 1x 1x 10x 10x 10x 1x 1x 1x 1x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 6x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 6x 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 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 9x 9x 9x 10x 1x 1x 1x 10x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 21x 21x 21x 1x 1x 1x 1x 20x 20x 20x | /**
* SLO Alert Service
*
* Monitors SLOs and triggers alerts when targets are breached.
* Integrates with the email alerting system for notifications.
*/
import { Resend } from 'resend';
import { prisma } from '@/lib/prisma';
import { logger } from './logger';
import { checkSLOsForAlerts, type SLOResult, getSLOStatusText, formatWindow } from './slo';
// Lazy initialization of Resend client
let resend: Resend | null = null;
function getResendClient(): Resend | null {
if (resend === null && process.env.RESEND_API_KEY) {
resend = new Resend(process.env.RESEND_API_KEY);
}
return resend;
}
function getAlertEmail(): string {
return process.env.ALERT_EMAIL || 'admin@example.com';
}
function getAlertFrom(): string {
return process.env.ALERT_FROM_EMAIL || 'alerts@elite-events.com';
}
// Rate limiting for SLO alerts
const sloAlertCooldowns = new Map<string, number>();
const COOLDOWN_MS = 15 * 60 * 1000; // 15 minutes between same SLO alerts
/**
* SLO Alert configuration
*/
export interface SLOAlertConfig {
/** Whether alerting is enabled */
enabled: boolean;
/** Check interval in milliseconds */
checkIntervalMs: number;
/** Whether to alert on warning status */
alertOnWarning: boolean;
/** Whether to alert on critical status */
alertOnCritical: boolean;
}
/**
* Default configuration
*/
export const defaultSLOAlertConfig: SLOAlertConfig = {
enabled: true,
checkIntervalMs: 5 * 60 * 1000, // 5 minutes
alertOnWarning: false, // Only alert on critical by default
alertOnCritical: true,
};
/**
* Result from checking and alerting on SLOs
*/
export interface CheckAndAlertResult {
/** Number of SLOs checked */
slosChecked: number;
/** Number of alerts triggered */
alertsTriggered: number;
/** Number of alerts that were rate-limited */
alertsSkipped: number;
/** Number of alerts resolved */
alertsResolved: number;
/** Details of breaching SLOs */
breachingSLOs: Array<{
name: string;
status: string;
current: number;
target: number;
budgetConsumed: number;
alertSent: boolean;
}>;
}
/**
* Check all SLOs and send alerts for breaches
*/
export async function checkAndAlertSLOs(
config: Partial<SLOAlertConfig> = {}
): Promise<CheckAndAlertResult> {
const mergedConfig = { ...defaultSLOAlertConfig, ...config };
if (!mergedConfig.enabled) {
logger.debug('SLO alerting disabled');
return {
slosChecked: 0,
alertsTriggered: 0,
alertsSkipped: 0,
alertsResolved: 0,
breachingSLOs: [],
};
}
const breachingSLOs = await checkSLOsForAlerts();
const result: CheckAndAlertResult = {
slosChecked: breachingSLOs.length,
alertsTriggered: 0,
alertsSkipped: 0,
alertsResolved: 0,
breachingSLOs: [],
};
// Get currently active alerts from database
const activeAlerts = await prisma.sloAlert.findMany({
where: { resolvedAt: null },
});
const activeAlertNames = new Set(activeAlerts.map((a) => a.sloName));
// Process each breaching SLO
for (const slo of breachingSLOs) {
const shouldAlert =
(slo.status === 'warning' && mergedConfig.alertOnWarning) ||
(slo.status === 'critical' && mergedConfig.alertOnCritical);
let alertSent = false;
if (shouldAlert) {
// Check rate limiting
const alertKey = `slo:${slo.name}`;
const lastAlert = sloAlertCooldowns.get(alertKey);
const now = Date.now();
if (lastAlert && now - lastAlert < COOLDOWN_MS) {
result.alertsSkipped++;
} else {
// Create or update alert in database
await createOrUpdateSLOAlert(slo);
// Send email alert
const emailSent = await sendSLOAlertEmail(slo);
if (emailSent) {
sloAlertCooldowns.set(alertKey, now);
result.alertsTriggered++;
alertSent = true;
}
}
}
result.breachingSLOs.push({
name: slo.name,
status: slo.status,
current: slo.current,
target: slo.target,
budgetConsumed: slo.budgetConsumed,
alertSent,
});
// Remove from active set since it's still breaching
activeAlertNames.delete(slo.name);
}
// Resolve any active alerts that are now healthy
if (activeAlertNames.size > 0) {
const resolvedCount = await resolveHealthySLOAlerts(Array.from(activeAlertNames));
result.alertsResolved = resolvedCount;
}
return result;
}
/**
* Create or update an SLO alert in the database
*/
async function createOrUpdateSLOAlert(slo: SLOResult): Promise<void> {
// Check if there's already an unresolved alert for this SLO
const existingAlert = await prisma.sloAlert.findFirst({
where: {
sloName: slo.name,
resolvedAt: null,
},
});
if (existingAlert) {
// Update existing alert with new values
await prisma.sloAlert.update({
where: { id: existingAlert.id },
data: {
status: slo.status,
current: slo.current,
budgetConsumed: slo.budgetConsumed,
},
});
logger.debug('Updated existing SLO alert', { sloName: slo.name });
} else {
// Create new alert
await prisma.sloAlert.create({
data: {
sloName: slo.name,
status: slo.status,
current: slo.current,
target: slo.target,
budgetConsumed: slo.budgetConsumed,
},
});
logger.info('Created new SLO alert', { sloName: slo.name, status: slo.status });
}
}
/**
* Resolve alerts for SLOs that are now healthy
*/
async function resolveHealthySLOAlerts(sloNames: string[]): Promise<number> {
const result = await prisma.sloAlert.updateMany({
where: {
sloName: { in: sloNames },
resolvedAt: null,
},
data: {
resolvedAt: new Date(),
},
});
if (result.count > 0) {
logger.info('Resolved SLO alerts', { count: result.count, sloNames });
}
return result.count;
}
/**
* Send an SLO alert email
*/
export async function sendSLOAlertEmail(slo: SLOResult): Promise<boolean> {
const client = getResendClient();
if (!client) {
logger.warn('SLO alert email skipped: RESEND_API_KEY not configured');
return false;
}
const statusColor = slo.status === 'critical' ? '#dc2626' : '#f59e0b'; // red or amber
const statusText = getSLOStatusText(slo.status);
const windowText = formatWindow(slo.window);
const dashboardUrl = process.env.NEXT_PUBLIC_APP_URL
? `${process.env.NEXT_PUBLIC_APP_URL}/admin/monitoring/observability`
: '#';
try {
await client.emails.send({
from: getAlertFrom(),
to: getAlertEmail(),
subject: `[SLO ${slo.status.toUpperCase()}] ${slo.name} - ${slo.current.toFixed(2)}% (target: ${slo.target}%)`,
html: `
<div style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; max-width: 600px; margin: 0 auto;">
<div style="background: ${statusColor}; color: white; padding: 20px; border-radius: 8px 8px 0 0;">
<h1 style="margin: 0; font-size: 24px;">SLO Alert: ${statusText}</h1>
<p style="margin: 8px 0 0; opacity: 0.9;">${slo.name}</p>
</div>
<div style="padding: 24px; background: #f9fafb; border: 1px solid #e5e7eb; border-top: none;">
<table style="width: 100%; border-collapse: collapse;">
<tr>
<td style="padding: 12px; border-bottom: 1px solid #e5e7eb;">
<strong>Current Value</strong>
</td>
<td style="padding: 12px; border-bottom: 1px solid #e5e7eb; text-align: right;">
<span style="font-size: 20px; font-weight: bold; color: ${statusColor};">
${slo.current.toFixed(2)}%
</span>
</td>
</tr>
<tr>
<td style="padding: 12px; border-bottom: 1px solid #e5e7eb;">
<strong>Target</strong>
</td>
<td style="padding: 12px; border-bottom: 1px solid #e5e7eb; text-align: right;">
${slo.target}%
</td>
</tr>
<tr>
<td style="padding: 12px; border-bottom: 1px solid #e5e7eb;">
<strong>Error Budget Consumed</strong>
</td>
<td style="padding: 12px; border-bottom: 1px solid #e5e7eb; text-align: right;">
<span style="color: ${slo.budgetConsumed > 80 ? '#dc2626' : '#374151'};">
${slo.budgetConsumed.toFixed(1)}%
</span>
</td>
</tr>
<tr>
<td style="padding: 12px; border-bottom: 1px solid #e5e7eb;">
<strong>Error Budget Remaining</strong>
</td>
<td style="padding: 12px; border-bottom: 1px solid #e5e7eb; text-align: right;">
${slo.budgetRemaining.toFixed(3)}%
</td>
</tr>
<tr>
<td style="padding: 12px; border-bottom: 1px solid #e5e7eb;">
<strong>Time Window</strong>
</td>
<td style="padding: 12px; border-bottom: 1px solid #e5e7eb; text-align: right;">
${windowText}
</td>
</tr>
<tr>
<td style="padding: 12px;">
<strong>Category</strong>
</td>
<td style="padding: 12px; text-align: right;">
${slo.category}
</td>
</tr>
</table>
<div style="margin-top: 24px; padding: 16px; background: white; border-radius: 8px; border: 1px solid #e5e7eb;">
<h3 style="margin: 0 0 8px; color: #374151;">What this means</h3>
<p style="margin: 0; color: #6b7280; font-size: 14px;">
${slo.status === 'critical'
? `The ${slo.name} SLO has breached its target. Error budget is nearly exhausted. Immediate attention recommended.`
: `The ${slo.name} SLO is at risk of breaching. Error budget is being consumed faster than expected.`
}
</p>
</div>
<a href="${dashboardUrl}"
style="display: inline-block; margin-top: 24px; padding: 12px 24px; background: #3b82f6; color: white; text-decoration: none; border-radius: 6px; font-weight: 500;">
View Observability Dashboard
</a>
<p style="margin-top: 24px; color: #9ca3af; font-size: 12px;">
Alert generated at ${slo.calculatedAt.toISOString()}
</p>
</div>
</div>
`,
});
logger.info('Sent SLO alert email', { sloName: slo.name, status: slo.status });
return true;
} catch (error) {
logger.error('Failed to send SLO alert email', error as Error, { sloName: slo.name });
return false;
}
}
/**
* Get active (unresolved) SLO alerts
*/
export async function getActiveSLOAlerts() {
return prisma.sloAlert.findMany({
where: { resolvedAt: null },
orderBy: { createdAt: 'desc' },
});
}
/**
* Get recent SLO alerts (both active and resolved)
*/
export async function getRecentSLOAlerts(hours: number = 24) {
const since = new Date(Date.now() - hours * 60 * 60 * 1000);
return prisma.sloAlert.findMany({
where: {
createdAt: { gte: since },
},
orderBy: { createdAt: 'desc' },
});
}
/**
* Resolve an SLO alert manually
*/
export async function resolveSLOAlert(alertId: string, resolvedBy?: number) {
return prisma.sloAlert.update({
where: { id: alertId },
data: {
resolvedAt: new Date(),
resolvedBy,
},
});
}
/**
* Get SLO alert statistics
*/
export async function getSLOAlertStats(days: number = 7) {
const since = new Date(Date.now() - days * 24 * 60 * 60 * 1000);
const [total, active, byStatus, bySLO] = await Promise.all([
// Total alerts in period
prisma.sloAlert.count({
where: { createdAt: { gte: since } },
}),
// Currently active
prisma.sloAlert.count({
where: { resolvedAt: null },
}),
// By status
prisma.sloAlert.groupBy({
by: ['status'],
where: { createdAt: { gte: since } },
_count: { id: true },
}),
// By SLO name
prisma.sloAlert.groupBy({
by: ['sloName'],
where: { createdAt: { gte: since } },
_count: { id: true },
orderBy: { _count: { id: 'desc' } },
take: 10,
}),
]);
return {
total,
active,
byStatus: byStatus.reduce(
(acc, item) => ({ ...acc, [item.status]: item._count.id }),
{} as Record<string, number>
),
bySLO: bySLO.map((item) => ({
sloName: item.sloName,
count: item._count.id,
})),
};
}
/**
* Clear rate limit cache (for testing)
*/
export function clearSLOAlertCooldowns(): void {
sloAlertCooldowns.clear();
}
/**
* Reset Resend client (for testing)
*/
export function resetResendClient(): void {
resend = null;
}
|