|
| 1 | +import { describe, expect, test, jest, beforeEach, afterEach } from "@jest/globals"; |
| 2 | +import { MonitoringWebSocketServer } from "../src/services/monitoringWebSocketServer"; |
| 3 | +import { DBType } from "../src/types"; |
| 4 | + |
| 5 | +const mockWebSocketServerInstances: any[] = []; |
| 6 | + |
| 7 | +jest.mock("ws", () => ({ |
| 8 | + WebSocketServer: jest.fn().mockImplementation((options) => { |
| 9 | + const listeners: Record<string, (...args: any[]) => void> = {}; |
| 10 | + |
| 11 | + const instance = { |
| 12 | + options, |
| 13 | + on: jest.fn((event: string, handler: (...args: any[]) => void) => { |
| 14 | + listeners[event] = handler; |
| 15 | + }), |
| 16 | + close: jest.fn(), |
| 17 | + address: jest.fn(() => ({ port: 4567 })), |
| 18 | + emit: async (event: string, ...args: any[]) => { |
| 19 | + const handler = listeners[event]; |
| 20 | + if (!handler) return undefined; |
| 21 | + return handler(...args); |
| 22 | + }, |
| 23 | + _listeners: listeners, |
| 24 | + }; |
| 25 | + |
| 26 | + mockWebSocketServerInstances.push(instance); |
| 27 | + return instance; |
| 28 | + }), |
| 29 | +})); |
| 30 | + |
| 31 | +function createMockLogger(): any { |
| 32 | + return { |
| 33 | + info: jest.fn(), |
| 34 | + warn: jest.fn(), |
| 35 | + error: jest.fn(), |
| 36 | + debug: jest.fn(), |
| 37 | + child: jest.fn().mockReturnThis(), |
| 38 | + }; |
| 39 | +} |
| 40 | + |
| 41 | +function createMockDbService() { |
| 42 | + return { |
| 43 | + getDatabaseConnection: jest.fn(), |
| 44 | + }; |
| 45 | +} |
| 46 | + |
| 47 | +function createMockMonitoringService() { |
| 48 | + return { |
| 49 | + getSnapshot: jest.fn(), |
| 50 | + }; |
| 51 | +} |
| 52 | + |
| 53 | +function createMockSocket() { |
| 54 | + const listeners: Record<string, (...args: any[]) => void> = {}; |
| 55 | + return { |
| 56 | + readyState: 1, |
| 57 | + send: jest.fn(), |
| 58 | + close: jest.fn(), |
| 59 | + on: jest.fn((event: string, handler: (...args: any[]) => void) => { |
| 60 | + listeners[event] = handler; |
| 61 | + }), |
| 62 | + emit: async (event: string, ...args: any[]) => { |
| 63 | + const handler = listeners[event]; |
| 64 | + if (!handler) return undefined; |
| 65 | + return handler(...args); |
| 66 | + }, |
| 67 | + _listeners: listeners, |
| 68 | + }; |
| 69 | +} |
| 70 | + |
| 71 | +describe("MonitoringWebSocketServer", () => { |
| 72 | + let logger: any; |
| 73 | + let dbService: ReturnType<typeof createMockDbService>; |
| 74 | + let monitoringService: ReturnType<typeof createMockMonitoringService>; |
| 75 | + let server: MonitoringWebSocketServer; |
| 76 | + let setIntervalSpy: jest.SpiedFunction<typeof setInterval>; |
| 77 | + let clearIntervalSpy: jest.SpiedFunction<typeof clearInterval>; |
| 78 | + |
| 79 | + beforeEach(() => { |
| 80 | + mockWebSocketServerInstances.length = 0; |
| 81 | + logger = createMockLogger(); |
| 82 | + dbService = createMockDbService(); |
| 83 | + monitoringService = createMockMonitoringService(); |
| 84 | + server = new MonitoringWebSocketServer(dbService as any, monitoringService as any, logger); |
| 85 | + setIntervalSpy = jest.spyOn(global, "setInterval").mockReturnValue(123 as any); |
| 86 | + clearIntervalSpy = jest.spyOn(global, "clearInterval").mockImplementation(() => undefined); |
| 87 | + }); |
| 88 | + |
| 89 | + afterEach(() => { |
| 90 | + jest.restoreAllMocks(); |
| 91 | + server.close(); |
| 92 | + }); |
| 93 | + |
| 94 | + test("starts once and exposes websocket info after listening", () => { |
| 95 | + expect(() => server.getInfo()).toThrow("Monitoring WebSocket server is not ready"); |
| 96 | + |
| 97 | + server.start(); |
| 98 | + server.start(); |
| 99 | + |
| 100 | + expect(mockWebSocketServerInstances).toHaveLength(1); |
| 101 | + expect(mockWebSocketServerInstances[0].options).toEqual({ |
| 102 | + host: "127.0.0.1", |
| 103 | + port: 0, |
| 104 | + path: "/monitoring", |
| 105 | + }); |
| 106 | + |
| 107 | + mockWebSocketServerInstances[0].emit("listening"); |
| 108 | + |
| 109 | + expect(logger.info).toHaveBeenCalledWith({ port: 4567 }, "Monitoring WebSocket server started"); |
| 110 | + expect(server.getInfo()).toEqual({ |
| 111 | + url: "ws://127.0.0.1:4567/monitoring", |
| 112 | + intervalMs: 5000, |
| 113 | + }); |
| 114 | + }); |
| 115 | + |
| 116 | + test("closes unsupported websocket connections immediately", async () => { |
| 117 | + server.start(); |
| 118 | + const wsServer = mockWebSocketServerInstances[0]; |
| 119 | + const socket = createMockSocket(); |
| 120 | + |
| 121 | + (dbService.getDatabaseConnection as any).mockResolvedValue({ conn: { id: "conn" }, dbType: DBType.SQLITE }); |
| 122 | + |
| 123 | + await wsServer.emit("connection", socket, { url: "/monitoring?dbId=db-1" } as any); |
| 124 | + |
| 125 | + expect(dbService.getDatabaseConnection).toHaveBeenCalledWith("db-1"); |
| 126 | + expect(socket.send).toHaveBeenCalledWith( |
| 127 | + JSON.stringify({ |
| 128 | + type: "unsupported", |
| 129 | + message: "Monitoring is not supported for sqlite", |
| 130 | + }) |
| 131 | + ); |
| 132 | + expect(socket.close).toHaveBeenCalledWith(1008, "Unsupported database type"); |
| 133 | + }); |
| 134 | + |
| 135 | + test("sends snapshots over websocket and enforces minimum interval", async () => { |
| 136 | + server.start(); |
| 137 | + const wsServer = mockWebSocketServerInstances[0]; |
| 138 | + const socket = createMockSocket(); |
| 139 | + |
| 140 | + (dbService.getDatabaseConnection as any).mockResolvedValue({ conn: { id: "conn" }, dbType: DBType.POSTGRES }); |
| 141 | + (monitoringService.getSnapshot as any).mockResolvedValue({ |
| 142 | + databaseType: DBType.POSTGRES, |
| 143 | + sampledAt: "2026-05-16T00:00:00.000Z", |
| 144 | + health: { ok: true, latencyMs: 11 }, |
| 145 | + connections: { active: 1, max: 50, usagePct: 2 }, |
| 146 | + throughput: { qps: 5, totalQueries: 100 }, |
| 147 | + cacheHitRatio: 98.5, |
| 148 | + activeQueries: [], |
| 149 | + }); |
| 150 | + |
| 151 | + await wsServer.emit("connection", socket, { url: "/monitoring?dbId=db-1&intervalMs=1000" } as any); |
| 152 | + |
| 153 | + expect(dbService.getDatabaseConnection).toHaveBeenCalledWith("db-1"); |
| 154 | + expect(monitoringService.getSnapshot).toHaveBeenCalledWith("db-1", { id: "conn" }, DBType.POSTGRES); |
| 155 | + expect(JSON.parse(socket.send.mock.calls[0][0] as string)).toMatchObject({ |
| 156 | + type: "snapshot", |
| 157 | + data: expect.objectContaining({ databaseType: DBType.POSTGRES }), |
| 158 | + }); |
| 159 | + expect(setIntervalSpy).toHaveBeenCalledWith(expect.any(Function), 2000); |
| 160 | + expect(clearIntervalSpy).not.toHaveBeenCalled(); |
| 161 | + }); |
| 162 | +}); |
0 commit comments