From 8c7610d82ca6a261dd922f69af18d775eaadb378 Mon Sep 17 00:00:00 2001 From: Khuong Nguyen Date: Wed, 2 Dec 2026 10:49:25 +0700 Subject: [PATCH] feat: add uptime monitor, HTTP/TCP probes, anti-flapping alerts, and /monitor commands --- .env.example | 3 + package.json | 1 + src/commands/monitor.command.ts | 239 +++++++++++++++++ src/commands/vps.command.ts | 4 + src/config/env.ts | 1 + src/demo-server.ts | 25 ++ src/deploy-commands.ts | 7 +- src/index.ts | 118 +++++++-- src/repositories/monitor.repository.ts | 297 ++++++++++++++++++++++ src/repositories/permission.repository.ts | 4 + src/seed.ts | 13 + src/services/monitor.service.ts | 233 +++++++++++++++++ src/types/monitor.ts | 46 ++++ src/utils/embeds.ts | 126 +++++++++ src/utils/permissions.ts | 10 +- src/utils/probe.ts | 153 +++++++++++ tests/monitor.service.test.ts | 164 ++++++++++++ 17 files changed, 1425 insertions(+), 19 deletions(-) create mode 100644 src/commands/monitor.command.ts create mode 100644 src/demo-server.ts create mode 100644 src/repositories/monitor.repository.ts create mode 100644 src/services/monitor.service.ts create mode 100644 src/types/monitor.ts create mode 100644 src/utils/probe.ts create mode 100644 tests/monitor.service.test.ts diff --git a/.env.example b/.env.example index 68dcfaf..db5a935 100644 --- a/.env.example +++ b/.env.example @@ -12,3 +12,6 @@ DEVOPS_ROLE_ID=your_devops_role_id_here # Path to SQLite database file (optional, defaults to data/vps.db) VPS_DB_PATH=data/vps.db + +# Discord Channel ID for #alerts (optional; auto-discovers #alerts channel by name if omitted) +ALERTS_CHANNEL_ID= diff --git a/package.json b/package.json index dcaea8a..f9d18af 100644 --- a/package.json +++ b/package.json @@ -8,6 +8,7 @@ "start": "tsx src/index.ts", "deploy:commands": "tsx src/deploy-commands.ts", "db:seed": "tsx src/seed.ts", + "demo:api": "tsx src/demo-server.ts", "typecheck": "tsc --noEmit", "test": "vitest run" }, diff --git a/src/commands/monitor.command.ts b/src/commands/monitor.command.ts new file mode 100644 index 0000000..464926b --- /dev/null +++ b/src/commands/monitor.command.ts @@ -0,0 +1,239 @@ +import { ChatInputCommandInteraction, EmbedBuilder, SlashCommandBuilder } from "discord.js"; +import { PermissionRepository } from "../repositories/permission.repository.js"; +import { MonitorService } from "../services/monitor.service.js"; +import { + createErrorEmbed, + createMonitorListEmbed, + createMonitorStatusEmbed, + EMBED_COLORS, +} from "../utils/embeds.js"; +import { + authorizeAction, + createDefaultPermissionConfig, + PermissionSource, + VPSPermission, +} from "../utils/permissions.js"; + +export const MONITOR_SUBCOMMAND_PERMISSIONS: Record = { + add: "monitor:add", + remove: "monitor:remove", + list: "monitor:list", + status: "monitor:status", +}; + +export const monitorCommandData = new SlashCommandBuilder() + .setName("monitor") + .setDescription("Service Uptime Monitor & Alert commands") + .addSubcommand((sub) => + sub + .setName("add") + .setDescription("Add a new HTTP URL or TCP host:port service to monitor") + .addStringOption((opt) => + opt.setName("name").setDescription("Unique service name (e.g. demo-api)").setRequired(true) + ) + .addStringOption((opt) => + opt + .setName("target") + .setDescription("HTTP(S) URL or TCP host:port (e.g. http://localhost:8080/health)") + .setRequired(true) + ) + .addIntegerOption((opt) => + opt + .setName("interval") + .setDescription("Check interval in seconds (5–3600, default 30)") + .setMinValue(5) + .setMaxValue(3600) + .setRequired(false) + ) + ) + .addSubcommand((sub) => + sub + .setName("remove") + .setDescription("Stop monitoring and remove a service") + .addStringOption((opt) => + opt.setName("name").setDescription("Service name to remove").setRequired(true) + ) + ) + .addSubcommand((sub) => + sub.setName("list").setDescription("Display all monitored services and their current status") + ) + .addSubcommand((sub) => + sub + .setName("status") + .setDescription("Display detailed uptime status for a monitored service") + .addStringOption((opt) => + opt.setName("name").setDescription("Service name").setRequired(true) + ) + ); + +export class MonitorCommandHandler { + private monitorService: MonitorService; + private permissionSource: PermissionSource; + + constructor(monitorService?: MonitorService, permissionSource?: PermissionSource) { + this.monitorService = monitorService || new MonitorService(); + this.permissionSource = + permissionSource || createDefaultPermissionConfig(process.env.DEVOPS_ROLE_ID); + } + + /** + * Main router for `/monitor` subcommands with action-based authorization. + */ + public async handle(interaction: ChatInputCommandInteraction): Promise { + const subcommand = interaction.options.getSubcommand(); + + try { + const requiredPermission = MONITOR_SUBCOMMAND_PERMISSIONS[subcommand]; + if (!requiredPermission) { + await interaction.reply({ + embeds: [createErrorEmbed("Unknown Subcommand", "The requested subcommand is not recognized.")], + ephemeral: true, + }); + return; + } + + const authResult = authorizeAction(interaction, requiredPermission, this.permissionSource); + if (!authResult.authorized) { + this.recordAudit(interaction, requiredPermission, subcommand, "DENIED", authResult.reason); + await interaction.reply({ + embeds: [ + createErrorEmbed( + "Unauthorized", + authResult.reason || "You do not have permission to execute this action." + ), + ], + ephemeral: true, + }); + return; + } + + switch (subcommand) { + case "add": + await this.handleAdd(interaction); + break; + case "remove": + await this.handleRemove(interaction); + break; + case "list": + await this.handleList(interaction); + break; + case "status": + await this.handleStatus(interaction); + break; + } + } catch (error) { + console.error(`[Error in /monitor ${subcommand}]:`, (error as Error).message); + const errorEmbed = createErrorEmbed( + "Monitor Error", + (error as Error).message || "An unexpected error occurred." + ); + + if (interaction.replied || interaction.deferred) { + await interaction.followUp({ embeds: [errorEmbed], ephemeral: true }); + } else { + await interaction.reply({ embeds: [errorEmbed], ephemeral: true }); + } + } + } + + private recordAudit( + interaction: ChatInputCommandInteraction, + action: string, + target: string | undefined, + status: "ALLOWED" | "DENIED" | "ERROR", + details?: string + ): void { + if (!(this.permissionSource instanceof PermissionRepository)) { + return; + } + try { + this.permissionSource.logAudit({ + actorId: interaction.user.id, + actorTag: interaction.user.tag, + action, + target, + status, + details, + }); + } catch { + // Never fail user interaction on audit write failure + } + } + + private async handleAdd(interaction: ChatInputCommandInteraction): Promise { + const name = interaction.options.getString("name", true); + const target = interaction.options.getString("target", true); + const intervalSeconds = interaction.options.getInteger("interval") ?? undefined; + + const created = this.monitorService.addService({ name, target, intervalSeconds }); + this.recordAudit(interaction, "monitor:add", created.name, "ALLOWED", `${created.type} ${created.target}`); + + const embed = new EmbedBuilder() + .setTitle("āœ… Service Monitor Added") + .setColor(EMBED_COLORS.SUCCESS) + .setDescription(`Started monitoring **${created.name}**.`) + .addFields( + { name: "Type", value: `\`${created.type}\``, inline: true }, + { name: "Interval", value: `${created.intervalSeconds}s`, inline: true }, + { name: "Target", value: `\`${created.target}\``, inline: false } + ) + .setTimestamp(); + + await interaction.reply({ embeds: [embed] }); + } + + private async handleRemove(interaction: ChatInputCommandInteraction): Promise { + const name = interaction.options.getString("name", true); + const removed = this.monitorService.removeService(name); + + if (!removed) { + await interaction.reply({ + embeds: [ + createErrorEmbed( + "Service Not Found", + `Could not find any monitored service named **"${name}"**.` + ), + ], + ephemeral: true, + }); + return; + } + + this.recordAudit(interaction, "monitor:remove", name, "ALLOWED"); + + const embed = new EmbedBuilder() + .setTitle("šŸ—‘ļø Service Monitor Removed") + .setColor(EMBED_COLORS.WARNING) + .setDescription(`Stopped monitoring and removed **${name}**.`) + .setTimestamp(); + + await interaction.reply({ embeds: [embed] }); + } + + private async handleList(interaction: ChatInputCommandInteraction): Promise { + const monitors = this.monitorService.listServices(); + const embed = createMonitorListEmbed(monitors); + await interaction.reply({ embeds: [embed] }); + } + + private async handleStatus(interaction: ChatInputCommandInteraction): Promise { + const name = interaction.options.getString("name", true); + const monitor = this.monitorService.getServiceStatus(name); + + if (!monitor) { + await interaction.reply({ + embeds: [ + createErrorEmbed( + "Service Not Found", + `Could not find any monitored service named **"${name}"**.` + ), + ], + ephemeral: true, + }); + return; + } + + const embed = createMonitorStatusEmbed(monitor); + await interaction.reply({ embeds: [embed] }); + } +} diff --git a/src/commands/vps.command.ts b/src/commands/vps.command.ts index 4fb399b..64f862f 100644 --- a/src/commands/vps.command.ts +++ b/src/commands/vps.command.ts @@ -57,6 +57,10 @@ const PERMISSION_CHOICES = [ { name: "vps:add (/vps add - future)", value: "vps:add" }, { name: "vps:update (/vps update - future)", value: "vps:update" }, { name: "vps:delete (/vps delete - future)", value: "vps:delete" }, + { name: "monitor:list (/monitor list)", value: "monitor:list" }, + { name: "monitor:status (/monitor status)", value: "monitor:status" }, + { name: "monitor:add (/monitor add)", value: "monitor:add" }, + { name: "monitor:remove (/monitor remove)", value: "monitor:remove" }, ] as const; export const vpsCommandData = new SlashCommandBuilder() diff --git a/src/config/env.ts b/src/config/env.ts index b7ae724..6beaa30 100644 --- a/src/config/env.ts +++ b/src/config/env.ts @@ -12,6 +12,7 @@ export const envSchema = dataConfigSchema.extend({ DISCORD_CLIENT_ID: z.string().min(1, "DISCORD_CLIENT_ID is required"), DISCORD_GUILD_ID: z.string().min(1, "DISCORD_GUILD_ID is required"), DEVOPS_ROLE_ID: z.string().optional(), + ALERTS_CHANNEL_ID: z.string().optional(), }); export type DataConfig = z.infer; diff --git a/src/demo-server.ts b/src/demo-server.ts new file mode 100644 index 0000000..36dc3cd --- /dev/null +++ b/src/demo-server.ts @@ -0,0 +1,25 @@ +import http from "node:http"; + +const PORT = Number(process.env.DEMO_API_PORT || 8080); + +const server = http.createServer((req, res) => { + if (req.url === "/health" && req.method === "GET") { + res.writeHead(200, { "Content-Type": "application/json" }); + res.end( + JSON.stringify({ + status: "ok", + service: "demo-api", + timestamp: new Date().toISOString(), + }) + ); + return; + } + + res.writeHead(404, { "Content-Type": "application/json" }); + res.end(JSON.stringify({ error: "Not Found" })); +}); + +server.listen(PORT, "127.0.0.1", () => { + console.log(`🟢 demo-api listening at http://localhost:${PORT}/health`); + console.log("Press Ctrl+C to simulate service DOWN during the workshop demo."); +}); diff --git a/src/deploy-commands.ts b/src/deploy-commands.ts index accdffc..fe57c1c 100644 --- a/src/deploy-commands.ts +++ b/src/deploy-commands.ts @@ -1,4 +1,5 @@ import { REST, Routes } from "discord.js"; +import { monitorCommandData } from "./commands/monitor.command.js"; import { vpsCommandData } from "./commands/vps.command.js"; import { getEnv } from "./config/env.js"; @@ -7,10 +8,12 @@ async function deployCommands() { const env = getEnv(); console.log("šŸš€ Starting deployment of Discord Slash Commands..."); - const commands = [vpsCommandData.toJSON()]; + const commands = [vpsCommandData.toJSON(), monitorCommandData.toJSON()]; const rest = new REST({ version: "10" }).setToken(env.DISCORD_TOKEN); - console.log(`šŸ“¦ Registering ${commands.length} application command(s) to Guild ID: ${env.DISCORD_GUILD_ID}`); + console.log( + `šŸ“¦ Registering ${commands.length} application command(s) (/vps, /monitor) to Guild ID: ${env.DISCORD_GUILD_ID}` + ); const data = (await rest.put( Routes.applicationGuildCommands(env.DISCORD_CLIENT_ID, env.DISCORD_GUILD_ID), diff --git a/src/index.ts b/src/index.ts index 74ba997..213f251 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,12 +1,47 @@ -import { Client, Events, GatewayIntentBits, Partials } from "discord.js"; +import { ChannelType, Client, Events, GatewayIntentBits, Partials, TextChannel } from "discord.js"; +import { MonitorCommandHandler } from "./commands/monitor.command.js"; import { VPSCommandHandler } from "./commands/vps.command.js"; import { getEnv } from "./config/env.js"; +import { MonitorRepository } from "./repositories/monitor.repository.js"; import { PermissionRepository } from "./repositories/permission.repository.js"; import { VPSRepository } from "./repositories/vps.repository.js"; +import { MonitorService } from "./services/monitor.service.js"; import { VPSService } from "./services/vps.service.js"; +import { createMonitorAlertEmbed } from "./utils/embeds.js"; + +async function resolveAlertsChannel( + client: Client, + guildId: string, + configuredChannelId?: string +): Promise { + if (configuredChannelId && configuredChannelId.trim() !== "") { + try { + const ch = await client.channels.fetch(configuredChannelId.trim()); + if (ch && ch.isTextBased() && "send" in ch) { + return ch as TextChannel; + } + } catch { + console.warn(`āš ļø Configured ALERTS_CHANNEL_ID (${configuredChannelId}) could not be fetched.`); + } + } + + try { + const guild = await client.guilds.fetch(guildId); + const channels = await guild.channels.fetch(); + const alertsChannel = channels.find( + (c) => + c !== null && + c.type === ChannelType.GuildText && + (c.name.toLowerCase() === "alerts" || c.name.toLowerCase() === "alert") + ); + return (alertsChannel as TextChannel) ?? null; + } catch { + return null; + } +} async function bootstrap() { - console.log("⚔ Starting VPS Inventory Assistant Discord Bot..."); + console.log("⚔ Starting VPS Inventory & Uptime Monitor Discord Bot..."); // 1. Validate environment configuration up front let env; @@ -17,9 +52,10 @@ async function bootstrap() { process.exit(1); } - // 2. Initialize SQLite data sources up front (VPS inventory & Permission tables) + // 2. Initialize SQLite data sources up front (VPS inventory, RBAC Permissions, & Monitors) let vpsRepository: VPSRepository; let permissionRepository: PermissionRepository; + let monitorRepository: MonitorRepository; try { vpsRepository = new VPSRepository(env.VPS_DB_PATH); vpsRepository.init(); @@ -31,11 +67,18 @@ async function bootstrap() { const seededPerms = permissionRepository.seedIfEmpty(env.DEVOPS_ROLE_ID); const rolePerms = permissionRepository.listRolePermissions(); - if (seededVps > 0 || seededPerms > 0) { - console.log(`🌱 Initialized SQLite seed data (${seededVps} VPS, ${seededPerms} permission rules).`); + monitorRepository = new MonitorRepository(env.VPS_DB_PATH); + monitorRepository.init(); + const seededMonitors = monitorRepository.seedIfEmpty(); + const monitorRecords = monitorRepository.getAll(); + + if (seededVps > 0 || seededPerms > 0 || seededMonitors > 0) { + console.log( + `🌱 Initialized SQLite seed data (${seededVps} VPS, ${seededPerms} permission rules, ${seededMonitors} monitors).` + ); } console.log( - `šŸ—„ļø Connected to SQLite (${env.VPS_DB_PATH}) — ${vpsRecords.length} VPS, ${rolePerms.length} role-permission rule(s).` + `šŸ—„ļø Connected to SQLite (${env.VPS_DB_PATH}) — ${vpsRecords.length} VPS, ${rolePerms.length} permission rule(s), ${monitorRecords.length} monitor(s).` ); } catch (err) { console.error("āŒ Failed to initialize SQLite database:", (err as Error).message); @@ -43,40 +86,81 @@ async function bootstrap() { } const vpsService = new VPSService(vpsRepository); - const commandHandler = new VPSCommandHandler(vpsService, permissionRepository); + const monitorService = new MonitorService(monitorRepository); - // 3. Initialize Discord Client with minimal required intents for slash commands & DM buttons + const vpsCommandHandler = new VPSCommandHandler(vpsService, permissionRepository); + const monitorCommandHandler = new MonitorCommandHandler(monitorService, permissionRepository); + + // 3. Initialize Discord Client with minimal required intents const client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.DirectMessages], partials: [Partials.Channel], }); - // Ready event - client.once(Events.ClientReady, (readyClient) => { + // Ready event: start background uptime scheduler + client.once(Events.ClientReady, async (readyClient) => { console.log(`šŸ¤– Logged in as ${readyClient.user.tag}`); console.log(`🌐 Active in ${readyClient.guilds.cache.size} guild(s)`); - console.log("✨ Bot is ready to receive /vps commands!"); + + const alertsChannel = await resolveAlertsChannel( + readyClient, + env.DISCORD_GUILD_ID, + env.ALERTS_CHANNEL_ID + ); + if (alertsChannel) { + console.log(`šŸ”” Uptime alerts will be sent to #${alertsChannel.name} (${alertsChannel.id})`); + } else { + console.warn( + "āš ļø Could not find #alerts channel (and ALERTS_CHANNEL_ID not set). Create a #alerts text channel to receive downtime alerts." + ); + } + + monitorService.startScheduler(async (outcome) => { + console.log( + `[Alert] ${outcome.monitor.name} transitioned to ${outcome.transition} (${outcome.monitor.target})` + ); + const targetChannel = + alertsChannel || + (await resolveAlertsChannel(readyClient, env.DISCORD_GUILD_ID, env.ALERTS_CHANNEL_ID)); + + if (targetChannel) { + await targetChannel.send({ embeds: [createMonitorAlertEmbed(outcome)] }); + console.log(`šŸ“Ø Sent ${outcome.transition} alert for ${outcome.monitor.name} to #${targetChannel.name}`); + } else { + console.warn(`āš ļø Alert for ${outcome.monitor.name} (${outcome.transition}) not sent: #alerts/#alert channel not found.`); + } + }); + + console.log("✨ Bot is ready to receive /vps and /monitor commands!"); }); // Interaction Create event client.on(Events.InteractionCreate, async (interaction) => { - if (interaction.isChatInputCommand() && interaction.commandName === "vps") { - await commandHandler.handle(interaction); - return; + if (interaction.isChatInputCommand()) { + if (interaction.commandName === "vps") { + await vpsCommandHandler.handle(interaction); + return; + } + if (interaction.commandName === "monitor") { + await monitorCommandHandler.handle(interaction); + return; + } } if (interaction.isButton() && interaction.customId.startsWith("vps_list_")) { - await commandHandler.handleListPaginationButton(interaction); + await vpsCommandHandler.handleListPaginationButton(interaction); } }); // Graceful shutdown handling const handleShutdown = (signal: string) => { console.log(`\nšŸ›‘ Received ${signal}. Shutting down gracefully...`); + monitorService.stopScheduler(); client.destroy(); vpsRepository.close(); permissionRepository.close(); - console.log("šŸ‘‹ Discord client & SQLite closed. Goodbye!"); + monitorRepository.close(); + console.log("šŸ‘‹ Discord client, monitor scheduler & SQLite closed. Goodbye!"); process.exit(0); }; @@ -88,8 +172,10 @@ async function bootstrap() { await client.login(env.DISCORD_TOKEN); } catch (err) { console.error("āŒ Failed to log in to Discord:", (err as Error).message); + monitorService.stopScheduler(); vpsRepository.close(); permissionRepository.close(); + monitorRepository.close(); process.exit(1); } } diff --git a/src/repositories/monitor.repository.ts b/src/repositories/monitor.repository.ts new file mode 100644 index 0000000..1425dbd --- /dev/null +++ b/src/repositories/monitor.repository.ts @@ -0,0 +1,297 @@ +import crypto from "node:crypto"; +import fs from "node:fs"; +import path from "node:path"; +import { DatabaseSync } from "node:sqlite"; +import { getDataConfig } from "../config/env.js"; +import { + monitorListSchema, + monitorSchema, + MonitorStatus, + MonitorType, + ServiceMonitor, +} from "../types/monitor.js"; + +export interface SeedMonitorRecord { + id: string; + name: string; + type: MonitorType; + target: string; + intervalSeconds: number; +} + +export const SEED_MONITOR_RECORDS: readonly SeedMonitorRecord[] = [ + { + id: "mon-001", + name: "shop-web", + type: "HTTP", + target: "https://shop.example.com/", + intervalSeconds: 30, + }, + { + id: "mon-002", + name: "shop-api", + type: "HTTP", + target: "https://api.shop.example.com/health", + intervalSeconds: 30, + }, + { + id: "mon-003", + name: "staging-web", + type: "HTTP", + target: "https://staging.example.com/", + intervalSeconds: 60, + }, + { + id: "mon-004", + name: "db-prod", + type: "TCP", + target: "203.0.113.11:5432", + intervalSeconds: 60, + }, + { + id: "mon-005", + name: "demo-api", + type: "HTTP", + target: "http://localhost:8080/health", + intervalSeconds: 10, + }, +]; + +interface MonitorRow { + id: string; + name: string; + type: string; + target: string; + intervalSeconds: number; + status: string; + consecutiveFailures: number; + lastLatencyMs: number | null; + lastCheckedAt: string | null; + lastDownAt: string | null; + lastError: string | null; + createdAt: string; +} + +const SELECT_COLUMNS = ` + id, + name, + type, + target, + interval_seconds AS intervalSeconds, + status, + consecutive_failures AS consecutiveFailures, + last_latency_ms AS lastLatencyMs, + last_checked_at AS lastCheckedAt, + last_down_at AS lastDownAt, + last_error AS lastError, + created_at AS createdAt +`; + +function mapRowToMonitor(row: MonitorRow): ServiceMonitor { + return monitorSchema.parse({ + id: row.id, + name: row.name, + type: row.type, + target: row.target, + intervalSeconds: row.intervalSeconds, + status: row.status, + consecutiveFailures: row.consecutiveFailures, + lastLatencyMs: row.lastLatencyMs ?? undefined, + lastCheckedAt: row.lastCheckedAt ?? undefined, + lastDownAt: row.lastDownAt ?? undefined, + lastError: row.lastError ?? undefined, + createdAt: row.createdAt, + }); +} + +export class MonitorRepository { + private dbPath: string; + private db: DatabaseSync | null = null; + + constructor(dbPath?: string) { + const configuredPath = dbPath || getDataConfig().VPS_DB_PATH; + this.dbPath = + configuredPath === ":memory:" + ? ":memory:" + : path.resolve(process.cwd(), configuredPath); + } + + /** + * Opens SQLite connection and ensures the `monitors` table exists. + */ + public init(): void { + if (this.db) { + return; + } + + try { + if (this.dbPath !== ":memory:") { + fs.mkdirSync(path.dirname(this.dbPath), { recursive: true }); + } + + this.db = new DatabaseSync(this.dbPath); + this.db.exec(` + PRAGMA foreign_keys = ON; + ${this.dbPath !== ":memory:" ? "PRAGMA journal_mode = WAL;" : ""} + + CREATE TABLE IF NOT EXISTS monitors ( + id TEXT PRIMARY KEY, + name TEXT NOT NULL UNIQUE COLLATE NOCASE, + type TEXT NOT NULL CHECK (type IN ('HTTP', 'TCP')), + target TEXT NOT NULL, + interval_seconds INTEGER NOT NULL CHECK (interval_seconds >= 5 AND interval_seconds <= 3600), + status TEXT NOT NULL DEFAULT 'PENDING' CHECK (status IN ('PENDING', 'UP', 'DOWN')), + consecutive_failures INTEGER NOT NULL DEFAULT 0, + last_latency_ms INTEGER, + last_checked_at TEXT, + last_down_at TEXT, + last_error TEXT, + created_at TEXT NOT NULL DEFAULT (datetime('now')) + ); + `); + } catch (err) { + throw new Error(`Failed to initialize SQLite monitors table: ${(err as Error).message}`); + } + } + + private getDb(): DatabaseSync { + if (!this.db) { + this.init(); + } + return this.db!; + } + + /** + * Seeds default workshop services if the `monitors` table is empty. + */ + public seedIfEmpty(records: readonly SeedMonitorRecord[] = SEED_MONITOR_RECORDS): number { + const db = this.getDb(); + const countRow = db + .prepare("SELECT COUNT(*) AS count FROM monitors") + .get() as { count: number }; + + if (countRow.count > 0) { + return 0; + } + + const insert = db.prepare(` + INSERT INTO monitors (id, name, type, target, interval_seconds) + VALUES (?, ?, ?, ?, ?) + `); + + for (const rec of records) { + insert.run(rec.id, rec.name, rec.type, rec.target, rec.intervalSeconds); + } + + return records.length; + } + + /** + * Returns all monitored services ordered by creation order. + */ + public getAll(): ServiceMonitor[] { + const db = this.getDb(); + const rows = db + .prepare(`SELECT ${SELECT_COLUMNS} FROM monitors ORDER BY rowid ASC`) + .all() as unknown as MonitorRow[]; + + return monitorListSchema.parse(rows.map(mapRowToMonitor)); + } + + /** + * Finds a monitored service by name (case-insensitive). + */ + public getByName(name: string): ServiceMonitor | undefined { + const trimmed = name.trim(); + if (!trimmed) { + return undefined; + } + + const db = this.getDb(); + const row = db + .prepare(`SELECT ${SELECT_COLUMNS} FROM monitors WHERE LOWER(name) = LOWER(?) LIMIT 1`) + .get(trimmed) as unknown as MonitorRow | undefined; + + return row ? mapRowToMonitor(row) : undefined; + } + + /** + * Creates a new monitored service. + */ + public add(params: { + name: string; + type: MonitorType; + target: string; + intervalSeconds: number; + }): ServiceMonitor { + const db = this.getDb(); + const id = `mon-${crypto.randomUUID().slice(0, 8)}`; + + db.prepare(` + INSERT INTO monitors (id, name, type, target, interval_seconds) + VALUES (?, ?, ?, ?, ?) + `).run(id, params.name.trim(), params.type, params.target.trim(), params.intervalSeconds); + + return this.getByName(params.name)!; + } + + /** + * Removes a monitored service by name (case-insensitive). Returns true if deleted. + */ + public removeByName(name: string): boolean { + const db = this.getDb(); + const result = db + .prepare(`DELETE FROM monitors WHERE LOWER(name) = LOWER(?)`) + .run(name.trim()); + + return result.changes > 0; + } + + /** + * Persists the latest probe state for a service. + */ + public updateCheckState( + id: string, + state: { + status: MonitorStatus; + consecutiveFailures: number; + lastLatencyMs?: number; + lastCheckedAt: string; + lastDownAt?: string; + lastError?: string; + } + ): ServiceMonitor { + const db = this.getDb(); + db.prepare(` + UPDATE monitors + SET status = ?, + consecutive_failures = ?, + last_latency_ms = ?, + last_checked_at = ?, + last_down_at = ?, + last_error = ? + WHERE id = ? + `).run( + state.status, + state.consecutiveFailures, + state.lastLatencyMs ?? null, + state.lastCheckedAt, + state.lastDownAt ?? null, + state.lastError ?? null, + id + ); + + const row = db + .prepare(`SELECT ${SELECT_COLUMNS} FROM monitors WHERE id = ? LIMIT 1`) + .get(id) as unknown as MonitorRow; + + return mapRowToMonitor(row); + } + + public close(): void { + if (this.db) { + this.db.close(); + this.db = null; + } + } +} diff --git a/src/repositories/permission.repository.ts b/src/repositories/permission.repository.ts index 9a5ce6f..b80a391 100644 --- a/src/repositories/permission.repository.ts +++ b/src/repositories/permission.repository.ts @@ -39,6 +39,10 @@ const PERMISSION_CATALOG: ReadonlyArray<{ name: VPSPermission; description: stri { name: "vps:add", description: "Add new VPS records (/vps add)" }, { name: "vps:update", description: "Update existing VPS records (/vps update)" }, { name: "vps:delete", description: "Delete VPS records (/vps delete)" }, + { name: "monitor:list", description: "List monitored services (/monitor list)" }, + { name: "monitor:status", description: "View detailed service uptime status (/monitor status)" }, + { name: "monitor:add", description: "Add a service to uptime monitor (/monitor add)" }, + { name: "monitor:remove", description: "Stop monitoring a service (/monitor remove)" }, ]; export const DEFAULT_GUILD_ROLE_SCOPE = "@everyone"; diff --git a/src/seed.ts b/src/seed.ts index 0c227a2..d9cba54 100644 --- a/src/seed.ts +++ b/src/seed.ts @@ -1,4 +1,5 @@ import { getDataConfig } from "./config/env.js"; +import { MonitorRepository } from "./repositories/monitor.repository.js"; import { PermissionRepository } from "./repositories/permission.repository.js"; import { VPSRepository } from "./repositories/vps.repository.js"; @@ -6,6 +7,7 @@ function seedDatabase() { const { VPS_DB_PATH } = getDataConfig(); const vpsRepo = new VPSRepository(VPS_DB_PATH); const permRepo = new PermissionRepository(VPS_DB_PATH); + const monitorRepo = new MonitorRepository(VPS_DB_PATH); try { vpsRepo.init(); @@ -16,6 +18,10 @@ function seedDatabase() { const seededPerms = permRepo.seedIfEmpty(process.env.DEVOPS_ROLE_ID); const totalRolePerms = permRepo.listRolePermissions().length; + monitorRepo.init(); + const seededMonitors = monitorRepo.seedIfEmpty(); + const totalMonitors = monitorRepo.getAll().length; + if (seededVps > 0) { console.log(`āœ… Seeded ${seededVps} VPS record(s) into SQLite (${VPS_DB_PATH}).`); } else { @@ -27,9 +33,16 @@ function seedDatabase() { } else { console.log(`ā„¹ļø Table 'role_permissions' already contains ${totalRolePerms} mapping(s).`); } + + if (seededMonitors > 0) { + console.log(`āœ… Seeded ${seededMonitors} monitor service(s) into SQLite (${VPS_DB_PATH}).`); + } else { + console.log(`ā„¹ļø Table 'monitors' already contains ${totalMonitors} service(s).`); + } } finally { vpsRepo.close(); permRepo.close(); + monitorRepo.close(); } } diff --git a/src/services/monitor.service.ts b/src/services/monitor.service.ts new file mode 100644 index 0000000..30c8f9c --- /dev/null +++ b/src/services/monitor.service.ts @@ -0,0 +1,233 @@ +import { MonitorRepository } from "../repositories/monitor.repository.js"; +import { + AlertTransition, + CheckOutcome, + CreateMonitorInput, + MonitorStatus, + MonitorType, + ProbeResult, + ServiceMonitor, +} from "../types/monitor.js"; +import { parseMonitorTarget, probeService } from "../utils/probe.js"; + +export type ServiceProber = (type: MonitorType, target: string) => Promise; +export type AlertCallback = (outcome: CheckOutcome) => Promise | void; + +export const DEFAULT_FAILURE_THRESHOLD = 2; +export const DEFAULT_INTERVAL_SECONDS = 30; + +export class MonitorService { + private repository: MonitorRepository; + private prober: ServiceProber; + private failureThreshold: number; + private timers = new Map(); + private inFlight = new Set(); + private onAlert?: AlertCallback; + + constructor( + repository?: MonitorRepository, + prober: ServiceProber = probeService, + failureThreshold: number = DEFAULT_FAILURE_THRESHOLD + ) { + this.repository = repository || new MonitorRepository(); + this.prober = prober; + this.failureThreshold = Math.max(1, failureThreshold); + } + + /** + * Adds a new service to monitor after validating name, target, and interval. + */ + public addService(input: CreateMonitorInput): ServiceMonitor { + const trimmedName = input.name.trim(); + if (!trimmedName || trimmedName.length > 64) { + throw new Error("Service name must be between 1 and 64 characters."); + } + + if (this.repository.getByName(trimmedName)) { + throw new Error(`A monitored service named "${trimmedName}" already exists.`); + } + + const parsed = parseMonitorTarget(input.target); + if (!parsed.valid) { + throw new Error(parsed.error); + } + + const intervalSeconds = input.intervalSeconds ?? DEFAULT_INTERVAL_SECONDS; + if (!Number.isInteger(intervalSeconds) || intervalSeconds < 5 || intervalSeconds > 3600) { + throw new Error("Check interval must be an integer between 5 and 3600 seconds."); + } + + const created = this.repository.add({ + name: trimmedName, + type: parsed.type, + target: parsed.normalizedTarget, + intervalSeconds, + }); + + if (this.onAlert) { + this.scheduleMonitor(created, true); + } + + return created; + } + + /** + * Stops monitoring and removes a service by name. + */ + public removeService(name: string): boolean { + const existing = this.repository.getByName(name); + if (!existing) { + return false; + } + + const timer = this.timers.get(existing.id); + if (timer) { + clearInterval(timer); + this.timers.delete(existing.id); + } + + return this.repository.removeByName(existing.name); + } + + /** + * Lists all monitored services. + */ + public listServices(): ServiceMonitor[] { + return this.repository.getAll(); + } + + /** + * Gets detailed status for a single monitored service (case-insensitive). + */ + public getServiceStatus(name: string): ServiceMonitor | undefined { + if (!name || name.trim() === "") { + return undefined; + } + return this.repository.getByName(name); + } + + /** + * Executes a single probe and applies anti-flapping + no-duplicate-alert state transitions. + */ + public async checkService(monitor: ServiceMonitor): Promise { + const probe = await this.prober(monitor.type, monitor.target); + const nowIso = new Date().toISOString(); + + let nextStatus: MonitorStatus = monitor.status; + let nextFailures = monitor.consecutiveFailures; + let nextLastDownAt = monitor.lastDownAt; + let nextLastError: string | undefined; + let transition: AlertTransition = null; + + if (probe.ok) { + if (monitor.status === "DOWN") { + transition = "RECOVERED"; + } + nextStatus = "UP"; + nextFailures = 0; + nextLastError = undefined; + } else { + nextFailures = monitor.consecutiveFailures + 1; + nextLastError = probe.error || "Probe failed"; + + if (nextFailures >= this.failureThreshold) { + if (monitor.status !== "DOWN") { + transition = "DOWN"; + nextLastDownAt = nowIso; + } else { + nextLastDownAt = monitor.lastDownAt ?? nowIso; + } + nextStatus = "DOWN"; + } else { + // Below failure threshold: keep prior status (UP/PENDING) to avoid false-positive alerts + nextStatus = monitor.status; + } + } + + const updated = this.repository.updateCheckState(monitor.id, { + status: nextStatus, + consecutiveFailures: nextFailures, + lastLatencyMs: probe.latencyMs, + lastCheckedAt: nowIso, + lastDownAt: nextLastDownAt, + lastError: nextLastError, + }); + + return { + monitor: updated, + probe, + transition, + }; + } + + /** + * Starts periodic background monitoring for all persisted services. + */ + public startScheduler(onAlert: AlertCallback): void { + this.stopScheduler(); + this.onAlert = onAlert; + + const services = this.repository.getAll(); + for (const service of services) { + this.scheduleMonitor(service, false); + } + } + + private scheduleMonitor(monitor: ServiceMonitor, runImmediately: boolean): void { + const existingTimer = this.timers.get(monitor.id); + if (existingTimer) { + clearInterval(existingTimer); + } + + const runTick = async () => { + if (this.inFlight.has(monitor.id)) { + return; + } + this.inFlight.add(monitor.id); + try { + const latest = this.repository.getByName(monitor.name); + if (!latest) { + this.stopMonitorTimer(monitor.id); + return; + } + const outcome = await this.checkService(latest); + if (outcome.transition && this.onAlert) { + await this.onAlert(outcome); + } + } catch (err) { + console.error(`[Monitor Error - ${monitor.name}]:`, (err as Error).message); + } finally { + this.inFlight.delete(monitor.id); + } + }; + + if (runImmediately) { + void runTick(); + } + + const timer = setInterval(() => { + void runTick(); + }, monitor.intervalSeconds * 1000); + + this.timers.set(monitor.id, timer); + } + + private stopMonitorTimer(id: string): void { + const timer = this.timers.get(id); + if (timer) { + clearInterval(timer); + this.timers.delete(id); + } + } + + /** + * Stops all active monitor timers. + */ + public stopScheduler(): void { + for (const timer of this.timers.values()) { + clearInterval(timer); + } + this.timers.clear(); + this.inFlight.clear(); + } +} diff --git a/src/types/monitor.ts b/src/types/monitor.ts new file mode 100644 index 0000000..d940d63 --- /dev/null +++ b/src/types/monitor.ts @@ -0,0 +1,46 @@ +import { z } from "zod"; + +export const MonitorTypeEnum = z.enum(["HTTP", "TCP"]); +export type MonitorType = z.infer; + +export const MonitorStatusEnum = z.enum(["PENDING", "UP", "DOWN"]); +export type MonitorStatus = z.infer; + +export const monitorSchema = z.object({ + id: z.string().min(1), + name: z.string().min(1).max(64), + type: MonitorTypeEnum, + target: z.string().min(1), + intervalSeconds: z.number().int().min(5).max(3600), + status: MonitorStatusEnum, + consecutiveFailures: z.number().int().min(0), + lastLatencyMs: z.number().int().nonnegative().optional(), + lastCheckedAt: z.string().optional(), + lastDownAt: z.string().optional(), + lastError: z.string().optional(), + createdAt: z.string(), +}); + +export const monitorListSchema = z.array(monitorSchema); + +export type ServiceMonitor = z.infer; + +export interface CreateMonitorInput { + name: string; + target: string; + intervalSeconds?: number; +} + +export interface ProbeResult { + ok: boolean; + latencyMs: number; + error?: string; +} + +export type AlertTransition = "DOWN" | "RECOVERED" | null; + +export interface CheckOutcome { + monitor: ServiceMonitor; + probe: ProbeResult; + transition: AlertTransition; +} diff --git a/src/utils/embeds.ts b/src/utils/embeds.ts index ec11551..94a5fbf 100644 --- a/src/utils/embeds.ts +++ b/src/utils/embeds.ts @@ -1,4 +1,5 @@ import { EmbedBuilder } from "discord.js"; +import { CheckOutcome, MonitorStatus, ServiceMonitor } from "../types/monitor.js"; import { VPS, VPSFilterOptions, VPSStats } from "../types/vps.js"; export const EMBED_COLORS = { @@ -342,3 +343,128 @@ export function createWarningEmbed(title: string, description: string): EmbedBui .setDescription(description) .setTimestamp(); } + +function formatMonitorStatusBadge(status: MonitorStatus): string { + if (status === "UP") return "🟢 UP"; + if (status === "DOWN") return "šŸ”“ DOWN"; + return "⚪ PENDING"; +} + +/** + * Creates an embed listing all monitored services and their current status. + */ +export function createMonitorListEmbed(monitors: ServiceMonitor[]): EmbedBuilder { + const embed = new EmbedBuilder() + .setTitle("šŸ“” Service Uptime Monitors") + .setColor(EMBED_COLORS.PRIMARY) + .setTimestamp() + .setFooter({ text: `Total Monitored Services: ${monitors.length}` }); + + if (monitors.length === 0) { + embed.setDescription( + "ā„¹ļø No services are currently being monitored. Use `/monitor add` to add one." + ); + return embed; + } + + const upCount = monitors.filter((m) => m.status === "UP").length; + const downCount = monitors.filter((m) => m.status === "DOWN").length; + embed.setDescription( + `Monitoring **${monitors.length}** service(s) — 🟢 **${upCount} UP** | šŸ”“ **${downCount} DOWN**` + ); + + const displayed = monitors.slice(0, DISCORD_EMBED_LIMITS.MAX_FIELDS); + for (const m of displayed) { + const latency = m.lastLatencyMs !== undefined ? `${m.lastLatencyMs}ms` : "—"; + embed.addFields({ + name: `${formatMonitorStatusBadge(m.status)} — ${m.name}`, + value: `• **Target:** \`${m.target}\` (${m.type})\n• **Interval:** ${m.intervalSeconds}s | **Latency:** ${latency}`, + inline: false, + }); + } + + return embed; +} + +/** + * Creates a detailed status embed for a single monitored service. + */ +export function createMonitorStatusEmbed(monitor: ServiceMonitor): EmbedBuilder { + const color = + monitor.status === "UP" + ? EMBED_COLORS.SUCCESS + : monitor.status === "DOWN" + ? EMBED_COLORS.ERROR + : EMBED_COLORS.WARNING; + + const latencyDisplay = + monitor.lastLatencyMs !== undefined ? `${monitor.lastLatencyMs} ms` : "Not checked yet"; + const lastCheckedDisplay = monitor.lastCheckedAt + ? `` + : "Never"; + const lastDownDisplay = monitor.lastDownAt + ? `` + : "Never"; + + const embed = new EmbedBuilder() + .setTitle(`šŸ“” SERVICE STATUS — ${monitor.name}`) + .setColor(color) + .addFields( + { name: "Status", value: formatMonitorStatusBadge(monitor.status), inline: true }, + { name: "Type", value: `\`${monitor.type}\``, inline: true }, + { name: "Interval", value: `${monitor.intervalSeconds}s`, inline: true }, + { name: "Target", value: `\`${monitor.target}\``, inline: false }, + { name: "Response Time", value: latencyDisplay, inline: true }, + { name: "Last Checked", value: lastCheckedDisplay, inline: true }, + { name: "Consecutive Failures", value: `${monitor.consecutiveFailures}`, inline: true }, + { name: "Last Down", value: lastDownDisplay, inline: false } + ) + .setFooter({ text: `Monitor ID: ${monitor.id}` }) + .setTimestamp(); + + if (monitor.lastError) { + embed.addFields({ + name: "Last Error", + value: `\`\`\`\n${monitor.lastError.slice(0, 500)}\n\`\`\``, + inline: false, + }); + } + + return embed; +} + +/** + * Creates an alert embed when a service transitions to DOWN or RECOVERED. + */ +export function createMonitorAlertEmbed(outcome: CheckOutcome): EmbedBuilder { + const { monitor, probe, transition } = outcome; + + if (transition === "DOWN") { + return new EmbedBuilder() + .setTitle(`🚨 SERVICE DOWN — ${monitor.name}`) + .setColor(EMBED_COLORS.ERROR) + .setDescription(`Service **${monitor.name}** failed **${monitor.consecutiveFailures}** consecutive health check(s) and is now **DOWN**.`) + .addFields( + { name: "Target", value: `\`${monitor.target}\` (${monitor.type})`, inline: true }, + { name: "Check Interval", value: `${monitor.intervalSeconds}s`, inline: true }, + { + name: "Failure Reason", + value: `\`${(probe.error || monitor.lastError || "Unknown error").slice(0, 300)}\``, + inline: false, + } + ) + .setFooter({ text: "Uptime Monitor Alert" }) + .setTimestamp(); + } + + return new EmbedBuilder() + .setTitle(`āœ… SERVICE RECOVERED — ${monitor.name}`) + .setColor(EMBED_COLORS.SUCCESS) + .setDescription(`Service **${monitor.name}** is back **UP** and responding normally.`) + .addFields( + { name: "Target", value: `\`${monitor.target}\` (${monitor.type})`, inline: true }, + { name: "Response Time", value: `${probe.latencyMs} ms`, inline: true } + ) + .setFooter({ text: "Uptime Monitor Alert" }) + .setTimestamp(); +} diff --git a/src/utils/permissions.ts b/src/utils/permissions.ts index 2983c66..ad77ca4 100644 --- a/src/utils/permissions.ts +++ b/src/utils/permissions.ts @@ -18,7 +18,11 @@ export type VPSPermission = | "vps:connect" | "vps:add" | "vps:update" - | "vps:delete"; + | "vps:delete" + | "monitor:list" + | "monitor:status" + | "monitor:add" + | "monitor:remove"; export const ALL_VPS_PERMISSIONS: readonly VPSPermission[] = [ "vps:list", @@ -31,6 +35,10 @@ export const ALL_VPS_PERMISSIONS: readonly VPSPermission[] = [ "vps:add", "vps:update", "vps:delete", + "monitor:list", + "monitor:status", + "monitor:add", + "monitor:remove", ] as const; export interface RolePermissionConfig { diff --git a/src/utils/probe.ts b/src/utils/probe.ts new file mode 100644 index 0000000..8a55941 --- /dev/null +++ b/src/utils/probe.ts @@ -0,0 +1,153 @@ +import net from "node:net"; +import { MonitorType, ProbeResult } from "../types/monitor.js"; +import { isValidHost, isValidPort } from "./ssh.js"; + +export type ParsedTarget = + | { valid: true; type: MonitorType; normalizedTarget: string } + | { valid: false; error: string }; + +/** + * Parses and validates either an HTTP(S) URL or a TCP `host:port` target. + */ +export function parseMonitorTarget(rawTarget: string): ParsedTarget { + const trimmed = rawTarget.trim(); + if (!trimmed) { + return { valid: false, error: "Target cannot be empty." }; + } + + if (/^https?:\/\//i.test(trimmed)) { + try { + const parsed = new URL(trimmed); + if (parsed.protocol !== "http:" && parsed.protocol !== "https:") { + return { valid: false, error: "Only HTTP and HTTPS protocols are supported." }; + } + return { + valid: true, + type: "HTTP", + normalizedTarget: parsed.toString(), + }; + } catch { + return { valid: false, error: "Invalid HTTP/HTTPS URL format." }; + } + } + + // TCP target: host:port (supports IPv4, hostname, or [IPv6]:port) + const lastColon = trimmed.lastIndexOf(":"); + if (lastColon <= 0 || lastColon === trimmed.length - 1) { + return { + valid: false, + error: "Target must be an `http(s)://...` URL or a `host:port` TCP address.", + }; + } + + let host = trimmed.slice(0, lastColon).trim(); + if (host.startsWith("[") && host.endsWith("]")) { + host = host.slice(1, -1); + } + + const portStr = trimmed.slice(lastColon + 1).trim(); + const port = Number(portStr); + + if (!isValidHost(host)) { + return { valid: false, error: `Invalid TCP host: "${host}".` }; + } + + if (!Number.isInteger(port) || !isValidPort(port)) { + return { valid: false, error: `Invalid TCP port: "${portStr}". Must be 1–65535.` }; + } + + return { + valid: true, + type: "TCP", + normalizedTarget: `${host}:${port}`, + }; +} + +/** + * Performs an HTTP(S) GET health check with timeout. + */ +export async function probeHTTP(url: string, timeoutMs = 5000): Promise { + const start = performance.now(); + try { + const response = await fetch(url, { + method: "GET", + signal: AbortSignal.timeout(timeoutMs), + }); + const latencyMs = Math.max(1, Math.round(performance.now() - start)); + + if (response.status >= 200 && response.status < 400) { + return { ok: true, latencyMs }; + } + + return { + ok: false, + latencyMs, + error: `HTTP ${response.status} ${response.statusText}`.trim(), + }; + } catch (err) { + const latencyMs = Math.max(1, Math.round(performance.now() - start)); + const message = err instanceof Error ? err.message : String(err); + return { + ok: false, + latencyMs, + error: message, + }; + } +} + +/** + * Performs a TCP socket connection check with timeout. + */ +export async function probeTCP(target: string, timeoutMs = 5000): Promise { + const lastColon = target.lastIndexOf(":"); + let host = target.slice(0, lastColon); + if (host.startsWith("[") && host.endsWith("]")) { + host = host.slice(1, -1); + } + const port = Number(target.slice(lastColon + 1)); + + const start = performance.now(); + + return new Promise((resolve) => { + let settled = false; + const socket = net.createConnection({ host, port }); + + const finish = (result: ProbeResult) => { + if (settled) return; + settled = true; + socket.destroy(); + resolve(result); + }; + + socket.setTimeout(timeoutMs); + + socket.once("connect", () => { + const latencyMs = Math.max(1, Math.round(performance.now() - start)); + finish({ ok: true, latencyMs }); + }); + + socket.once("timeout", () => { + const latencyMs = Math.max(1, Math.round(performance.now() - start)); + finish({ ok: false, latencyMs, error: `TCP connection timed out after ${timeoutMs}ms` }); + }); + + socket.once("error", (err) => { + const latencyMs = Math.max(1, Math.round(performance.now() - start)); + finish({ ok: false, latencyMs, error: err.message }); + }); + }); +} + +/** + * Probes a service according to its monitor type. + */ +export async function probeService( + type: MonitorType, + target: string, + timeoutMs = 5000 +): Promise { + if (type === "HTTP") { + return probeHTTP(target, timeoutMs); + } + return probeTCP(target, timeoutMs); +} diff --git a/tests/monitor.service.test.ts b/tests/monitor.service.test.ts new file mode 100644 index 0000000..cd021d7 --- /dev/null +++ b/tests/monitor.service.test.ts @@ -0,0 +1,164 @@ +import { describe, it, expect, beforeEach, afterEach } from "vitest"; +import { MonitorRepository, SEED_MONITOR_RECORDS } from "../src/repositories/monitor.repository.js"; +import { MonitorService } from "../src/services/monitor.service.js"; +import { ProbeResult } from "../src/types/monitor.js"; +import { parseMonitorTarget } from "../src/utils/probe.js"; + +describe("Target Parser & Uptime Monitor Service", () => { + describe("parseMonitorTarget", () => { + it("should parse valid HTTP and HTTPS URLs", () => { + const http = parseMonitorTarget("http://localhost:8080/health"); + expect(http).toEqual({ + valid: true, + type: "HTTP", + normalizedTarget: "http://localhost:8080/health", + }); + + const https = parseMonitorTarget("https://shop.example.com/"); + expect(https).toEqual({ + valid: true, + type: "HTTP", + normalizedTarget: "https://shop.example.com/", + }); + }); + + it("should parse valid TCP host:port targets", () => { + const tcp = parseMonitorTarget("203.0.113.11:5432"); + expect(tcp).toEqual({ + valid: true, + type: "TCP", + normalizedTarget: "203.0.113.11:5432", + }); + }); + + it("should reject invalid targets and out-of-range ports", () => { + expect(parseMonitorTarget("").valid).toBe(false); + expect(parseMonitorTarget("not-a-target").valid).toBe(false); + expect(parseMonitorTarget("203.0.113.11:70000").valid).toBe(false); + expect(parseMonitorTarget("256.300.1.1:80").valid).toBe(false); + }); + }); + + describe("MonitorRepository & MonitorService", () => { + let repository: MonitorRepository; + let mockProbeResult: ProbeResult; + let service: MonitorService; + + beforeEach(() => { + repository = new MonitorRepository(":memory:"); + repository.init(); + mockProbeResult = { ok: true, latencyMs: 15 }; + service = new MonitorService(repository, async () => mockProbeResult, 2); + }); + + afterEach(() => { + service.stopScheduler(); + repository.close(); + }); + + it("should seed all 5 workshop services", () => { + const inserted = repository.seedIfEmpty(); + expect(inserted).toBe(5); + expect(SEED_MONITOR_RECORDS).toHaveLength(5); + + const all = service.listServices(); + expect(all.map((m) => m.name)).toEqual([ + "shop-web", + "shop-api", + "staging-web", + "db-prod", + "demo-api", + ]); + expect(service.getServiceStatus("demo-api")?.intervalSeconds).toBe(10); + expect(service.getServiceStatus("db-prod")?.type).toBe("TCP"); + }); + + it("should add and remove monitored services", () => { + const added = service.addService({ + name: "custom-api", + target: "http://localhost:3000/health", + intervalSeconds: 15, + }); + + expect(added.name).toBe("custom-api"); + expect(added.type).toBe("HTTP"); + expect(added.status).toBe("PENDING"); + expect(service.listServices()).toHaveLength(1); + + expect(() => + service.addService({ name: "custom-api", target: "http://localhost:3000/health" }) + ).toThrow("already exists"); + + expect(service.removeService("custom-api")).toBe(true); + expect(service.removeService("custom-api")).toBe(false); + expect(service.listServices()).toHaveLength(0); + }); + + it("should NOT alert on a single transient failure (anti-flapping) and reset on recovery", async () => { + const mon = service.addService({ + name: "demo-api", + target: "http://localhost:8080/health", + intervalSeconds: 10, + }); + + // 1. Initial UP check + const upCheck = await service.checkService(mon); + expect(upCheck.monitor.status).toBe("UP"); + expect(upCheck.transition).toBeNull(); + + // 2. Single transient failure -> below threshold (2), should NOT alert DOWN + mockProbeResult = { ok: false, latencyMs: 5000, error: "ECONNREFUSED" }; + const blipCheck = await service.checkService(upCheck.monitor); + expect(blipCheck.monitor.status).toBe("UP"); + expect(blipCheck.monitor.consecutiveFailures).toBe(1); + expect(blipCheck.transition).toBeNull(); + + // 3. Recovers on next check -> resets consecutiveFailures without alert + mockProbeResult = { ok: true, latencyMs: 12 }; + const recoverFromBlip = await service.checkService(blipCheck.monitor); + expect(recoverFromBlip.monitor.status).toBe("UP"); + expect(recoverFromBlip.monitor.consecutiveFailures).toBe(0); + expect(recoverFromBlip.transition).toBeNull(); + }); + + it("should alert DOWN once at threshold, avoid duplicate DOWN alerts, and alert RECOVERED once", async () => { + const mon = service.addService({ + name: "demo-api", + target: "http://localhost:8080/health", + intervalSeconds: 10, + }); + + // 1. Failure #1 (below threshold) + mockProbeResult = { ok: false, latencyMs: 50, error: "Connection refused" }; + const fail1 = await service.checkService(mon); + expect(fail1.transition).toBeNull(); + expect(fail1.monitor.status).toBe("PENDING"); + + // 2. Failure #2 (reaches threshold = 2) -> emits DOWN alert once + const fail2 = await service.checkService(fail1.monitor); + expect(fail2.transition).toBe("DOWN"); + expect(fail2.monitor.status).toBe("DOWN"); + expect(fail2.monitor.lastDownAt).toBeDefined(); + expect(fail2.monitor.lastError).toBe("Connection refused"); + + // 3. Failure #3 while already DOWN -> NO duplicate alert + const fail3 = await service.checkService(fail2.monitor); + expect(fail3.transition).toBeNull(); + expect(fail3.monitor.status).toBe("DOWN"); + expect(fail3.monitor.consecutiveFailures).toBe(3); + + // 4. Service recovers -> emits RECOVERED alert once + mockProbeResult = { ok: true, latencyMs: 8 }; + const recovered = await service.checkService(fail3.monitor); + expect(recovered.transition).toBe("RECOVERED"); + expect(recovered.monitor.status).toBe("UP"); + expect(recovered.monitor.consecutiveFailures).toBe(0); + expect(recovered.monitor.lastError).toBeUndefined(); + + // 5. Subsequent UP check -> no duplicate recovery alert + const steady = await service.checkService(recovered.monitor); + expect(steady.transition).toBeNull(); + expect(steady.monitor.status).toBe("UP"); + }); + }); +});