|
| 1 | +import crypto from 'crypto'; |
| 2 | +import { getDb } from './database'; |
| 3 | +import { monitorConfigStore, MonitorTarget } from './monitorConfigStore'; |
| 4 | +import { HealthStatus } from './monitorStore'; |
| 5 | + |
| 6 | +type AlertType = 'down' | 'reminder' | 'recovery'; |
| 7 | + |
| 8 | +interface AlertMetrics { |
| 9 | + latencyMs: number; |
| 10 | + ttftMs: number; |
| 11 | + outputTokens: number; |
| 12 | + errorMessage?: string; |
| 13 | +} |
| 14 | + |
| 15 | +/** Get the previous health status for a target (skip the just-inserted ping) */ |
| 16 | +function getPreviousStatus(providerId: string, modelName: string): HealthStatus | null { |
| 17 | + const db = getDb(); |
| 18 | + const row = db |
| 19 | + .prepare( |
| 20 | + `SELECT health_status FROM monitor_pings |
| 21 | + WHERE provider_id = ? AND model_name = ? |
| 22 | + ORDER BY checked_at DESC LIMIT 1 OFFSET 1`, |
| 23 | + ) |
| 24 | + .get(providerId, modelName) as { health_status: HealthStatus } | undefined; |
| 25 | + return row?.health_status ?? null; |
| 26 | +} |
| 27 | + |
| 28 | +/** Determine if an alert should be sent */ |
| 29 | +function shouldSendAlert( |
| 30 | + target: MonitorTarget, |
| 31 | + currentStatus: HealthStatus, |
| 32 | + reminderMinutes: number, |
| 33 | +): { send: boolean; type: AlertType } | null { |
| 34 | + const previousStatus = getPreviousStatus(target.providerId, target.modelName); |
| 35 | + |
| 36 | + if (!previousStatus) return null; |
| 37 | + |
| 38 | + const wasDown = previousStatus === 'down'; |
| 39 | + const isDown = currentStatus === 'down' || currentStatus === 'very_slow'; |
| 40 | + |
| 41 | + if (wasDown && !isDown) { |
| 42 | + return { send: true, type: 'recovery' }; |
| 43 | + } |
| 44 | + |
| 45 | + if (!wasDown && isDown) { |
| 46 | + return { send: true, type: 'down' }; |
| 47 | + } |
| 48 | + |
| 49 | + if (isDown) { |
| 50 | + const lastAlertAt = target.lastAlertAt; |
| 51 | + if (!lastAlertAt) { |
| 52 | + return { send: true, type: 'reminder' }; |
| 53 | + } |
| 54 | + const elapsed = Date.now() - new Date(lastAlertAt).getTime(); |
| 55 | + if (elapsed >= reminderMinutes * 60 * 1000) { |
| 56 | + return { send: true, type: 'reminder' }; |
| 57 | + } |
| 58 | + } |
| 59 | + |
| 60 | + return null; |
| 61 | +} |
| 62 | + |
| 63 | +/** Generate Feishu webhook signature — appends timestamp & sign as URL params */ |
| 64 | +function buildSignedUrl(webhookUrl: string, secret: string): string { |
| 65 | + const timestamp = Math.floor(Date.now() / 1000).toString(); |
| 66 | + const stringToSign = `${timestamp}\n${secret}`; |
| 67 | + const hmac = crypto.createHmac('sha256', stringToSign); |
| 68 | + hmac.update(''); |
| 69 | + const sign = hmac.digest('base64'); |
| 70 | + const sep = webhookUrl.includes('?') ? '&' : '?'; |
| 71 | + return `${webhookUrl}${sep}timestamp=${timestamp}&sign=${encodeURIComponent(sign)}`; |
| 72 | +} |
| 73 | + |
| 74 | +/** Localized alert content */ |
| 75 | +function getAlertContent(lang: 'en' | 'zh', type: AlertType, target: MonitorTarget, metrics: AlertMetrics) { |
| 76 | + const isZh = lang === 'zh'; |
| 77 | + const tps = metrics.latencyMs > 0 ? ((metrics.outputTokens / metrics.latencyMs) * 1000).toFixed(1) : '0'; |
| 78 | + |
| 79 | + const colors: Record<AlertType, string> = { down: 'red', reminder: 'orange', recovery: 'green' }; |
| 80 | + |
| 81 | + const titles: Record<AlertType, string> = isZh |
| 82 | + ? { down: '🚨 监控告警:服务异常', reminder: '⚠️ 监控提醒:服务仍异常', recovery: '✅ 监控恢复:服务已恢复' } |
| 83 | + : { |
| 84 | + down: '🚨 Monitor Alert: Service Down', |
| 85 | + reminder: '⚠️ Monitor Reminder: Still Down', |
| 86 | + recovery: '✅ Monitor Recovery: Service Restored', |
| 87 | + }; |
| 88 | + |
| 89 | + const providerLabel = isZh ? '服务商' : 'Provider'; |
| 90 | + const modelLabel = isZh ? '模型' : 'Model'; |
| 91 | + const latencyLabel = isZh ? '延迟' : 'Latency'; |
| 92 | + const errorLabel = isZh ? '错误' : 'Error'; |
| 93 | + const timeLabel = isZh ? '时间' : 'Time'; |
| 94 | + |
| 95 | + const elements = [ |
| 96 | + { |
| 97 | + tag: 'div', |
| 98 | + text: { |
| 99 | + tag: 'lark_md', |
| 100 | + content: `**${providerLabel}:** ${target.providerName}\n**${modelLabel}:** ${target.modelName}`, |
| 101 | + }, |
| 102 | + }, |
| 103 | + ]; |
| 104 | + |
| 105 | + if (type === 'recovery') { |
| 106 | + elements.push({ |
| 107 | + tag: 'div', |
| 108 | + text: { |
| 109 | + tag: 'lark_md', |
| 110 | + content: `**${latencyLabel}:** ${metrics.latencyMs}ms | **TPS:** ${tps} | **TTFT:** ${metrics.ttftMs}ms`, |
| 111 | + }, |
| 112 | + }); |
| 113 | + } else { |
| 114 | + const details = [ |
| 115 | + `**${latencyLabel}:** ${metrics.latencyMs}ms`, |
| 116 | + `**TTFT:** ${metrics.ttftMs}ms`, |
| 117 | + `**Tokens:** ${metrics.outputTokens}`, |
| 118 | + ]; |
| 119 | + if (metrics.errorMessage) details.push(`**${errorLabel}:** ${metrics.errorMessage}`); |
| 120 | + elements.push({ tag: 'div', text: { tag: 'lark_md', content: details.join('\n') } }); |
| 121 | + } |
| 122 | + |
| 123 | + elements.push({ |
| 124 | + tag: 'div', |
| 125 | + text: { tag: 'plain_text', content: `${timeLabel}: ${new Date().toISOString()}` }, |
| 126 | + }); |
| 127 | + |
| 128 | + return { color: colors[type], title: titles[type], elements }; |
| 129 | +} |
| 130 | + |
| 131 | +/** Send alert to Feishu webhook */ |
| 132 | +async function sendFeishuAlert( |
| 133 | + webhookUrl: string, |
| 134 | + secret: string | undefined, |
| 135 | + lang: 'en' | 'zh', |
| 136 | + type: AlertType, |
| 137 | + target: MonitorTarget, |
| 138 | + metrics: AlertMetrics, |
| 139 | +): Promise<void> { |
| 140 | + const { color, title, elements } = getAlertContent(lang, type, target, metrics); |
| 141 | + |
| 142 | + const bodyStr = JSON.stringify({ |
| 143 | + msg_type: 'interactive', |
| 144 | + card: { |
| 145 | + header: { title: { tag: 'plain_text', content: title }, template: color }, |
| 146 | + elements, |
| 147 | + }, |
| 148 | + }); |
| 149 | + |
| 150 | + const targetUrl = secret ? buildSignedUrl(webhookUrl, secret) : webhookUrl; |
| 151 | + const res = await fetch(targetUrl, { |
| 152 | + method: 'POST', |
| 153 | + headers: { 'Content-Type': 'application/json' }, |
| 154 | + body: bodyStr, |
| 155 | + }); |
| 156 | + |
| 157 | + if (!res.ok) { |
| 158 | + const text = await res.text().catch(() => ''); |
| 159 | + console.error(`[Alert] Feishu webhook failed (${res.status}): ${text}`); |
| 160 | + } |
| 161 | +} |
| 162 | + |
| 163 | +/** Main entry: check and send alert if needed */ |
| 164 | +export async function processAlert( |
| 165 | + target: MonitorTarget, |
| 166 | + currentStatus: HealthStatus, |
| 167 | + metrics: AlertMetrics, |
| 168 | +): Promise<void> { |
| 169 | + if (target.alertEnabled === false) return; |
| 170 | + |
| 171 | + const config = monitorConfigStore.getConfig(); |
| 172 | + const webhookUrl = config.alertWebhookUrl; |
| 173 | + if (!webhookUrl) return; |
| 174 | + |
| 175 | + const reminderMinutes = config.alertReminderMinutes ?? 360; |
| 176 | + const decision = shouldSendAlert(target, currentStatus, reminderMinutes); |
| 177 | + if (!decision) return; |
| 178 | + |
| 179 | + try { |
| 180 | + await sendFeishuAlert( |
| 181 | + webhookUrl, |
| 182 | + config.alertWebhookSecret || undefined, |
| 183 | + config.alertLanguage || 'en', |
| 184 | + decision.type, |
| 185 | + target, |
| 186 | + metrics, |
| 187 | + ); |
| 188 | + monitorConfigStore.updateLastAlertAt(target.providerId, target.modelName); |
| 189 | + } catch (err) { |
| 190 | + console.error('[Alert] Failed to send notification:', err); |
| 191 | + } |
| 192 | +} |
0 commit comments