Files
Checkmate/server/src/domain/diagnostics/diagnostic.service.ts
T

145 lines
4.2 KiB
TypeScript
Raw Normal View History

2025-07-23 14:28:16 -07:00
import v8 from "v8";
import os from "os";
2026-06-09 12:34:15 -07:00
import { IDb } from "@/db/db.interface.js";
2026-05-26 13:31:13 -07:00
import { Mongoose } from "mongoose";
import { AppError } from "@/utils/AppError.js";
2025-07-23 14:28:16 -07:00
const SERVICE_NAME = "diagnosticService";
2026-05-26 14:53:33 -07:00
export interface CollectionDiagnostics {
name: string;
documentCount: number;
storageSize: number;
totalIndexSize: number;
totalSize: number;
bucketCount?: number;
}
export interface MongoDiagnostics {
readyState: number;
host: string;
port: number;
dbName: string;
totalSize: number;
collections: CollectionDiagnostics[];
}
export interface Diagnostics {
osStats: { totalMemoryBytes: number };
cpuUsage: { usagePercentage: number };
v8HeapStats: {
totalHeapSizeBytes: number;
usedHeapSizeBytes: number;
heapSizeLimitBytes: number;
};
eventLoopDelayMs: number;
uptimeMs: number;
mongoStats: MongoDiagnostics;
}
2026-03-05 14:46:28 -08:00
export interface IDiagnosticService {
2026-05-26 14:53:33 -07:00
getSystemStats(): Promise<Diagnostics>;
2026-01-20 21:53:19 +00:00
}
2026-03-05 14:46:28 -08:00
export class DiagnosticService implements IDiagnosticService {
2025-07-23 14:28:16 -07:00
static SERVICE_NAME = SERVICE_NAME;
2025-07-25 15:15:14 -07:00
2026-05-26 13:31:13 -07:00
constructor(private db: IDb<Mongoose>) {
2025-07-23 14:31:40 -07:00
/**
* Performance Observer for monitoring system performance metrics.
* Clears performance marks after each measurement to prevent memory leaks.
*/
const obs = new PerformanceObserver((items) => {
2026-03-20 10:51:06 -07:00
items.getEntries();
2025-07-23 14:31:40 -07:00
performance.clearMarks();
});
obs.observe({ entryTypes: ["measure"] });
}
2025-07-23 14:28:16 -07:00
2025-07-25 15:15:14 -07:00
get serviceName() {
return DiagnosticService.SERVICE_NAME;
}
2026-05-26 14:53:33 -07:00
private getCPUUsagePercentage = async (): Promise<number> => {
2025-07-23 14:28:16 -07:00
const startUsage = process.cpuUsage();
const timingPeriod = 1000; // measured in ms
await new Promise((resolve) => setTimeout(resolve, timingPeriod));
const endUsage = process.cpuUsage(startUsage);
2026-05-26 14:53:33 -07:00
return ((endUsage.user + endUsage.system) / 1000 / timingPeriod) * 100;
2025-07-23 14:28:16 -07:00
};
2026-05-26 14:53:33 -07:00
private getMongoDBStats = async (): Promise<MongoDiagnostics> => {
2026-05-26 13:31:13 -07:00
const mongo = await this.db.getConnection();
const db = mongo.connection.db;
if (!db) {
throw new AppError({ message: "Database connection is not available", service: SERVICE_NAME, method: "getMongoDBStats" });
}
2026-05-26 14:53:33 -07:00
const dbStats = await db.stats();
const rawCollections = await db.collections();
const collections: CollectionDiagnostics[] = await Promise.all(
rawCollections
.filter((collection) => !collection.collectionName.startsWith("system"))
.map(async (collection) => {
const stats = await db.command({ collStats: collection.collectionName });
const documentCount = await db.collection(collection.collectionName).countDocuments({});
const entry: CollectionDiagnostics = {
name: collection.collectionName,
documentCount,
storageSize: stats.storageSize ?? 0,
totalIndexSize: stats.totalIndexSize ?? 0,
totalSize: stats.totalSize ?? (stats.storageSize ?? 0) + (stats.totalIndexSize ?? 0),
2026-05-26 14:53:33 -07:00
};
if (stats.timeseries?.bucketCount !== undefined) {
entry.bucketCount = stats.timeseries.bucketCount;
}
return entry;
})
2026-05-26 13:31:13 -07:00
);
return {
2026-05-26 14:53:33 -07:00
readyState: mongo.connection.readyState,
host: mongo.connection.host,
port: mongo.connection.port,
dbName: mongo.connection.name,
totalSize: dbStats.totalSize ?? (dbStats.storageSize ?? 0) + (dbStats.indexSize ?? 0),
2026-05-26 14:53:33 -07:00
collections,
2026-05-26 13:31:13 -07:00
};
};
2026-05-26 14:53:33 -07:00
getSystemStats = async (): Promise<Diagnostics> => {
const osStats = { totalMemoryBytes: os.totalmem() };
2025-07-23 14:28:16 -07:00
2026-05-26 14:53:33 -07:00
const cpuUsage = { usagePercentage: await this.getCPUUsagePercentage() };
2025-07-23 14:28:16 -07:00
const heapStats = v8.getHeapStatistics();
2026-05-26 14:53:33 -07:00
const v8HeapStats = {
totalHeapSizeBytes: heapStats.total_heap_size,
usedHeapSizeBytes: heapStats.used_heap_size,
heapSizeLimitBytes: heapStats.heap_size_limit,
2025-07-23 14:28:16 -07:00
};
2026-05-26 14:53:33 -07:00
let eventLoopDelayMs = 0;
2025-07-23 14:28:16 -07:00
performance.mark("start");
await new Promise((resolve) => setTimeout(resolve, 0));
performance.mark("end");
performance.measure("eventLoopDelay", "start", "end");
const entries = performance.getEntriesByName("eventLoopDelay");
2026-01-20 21:53:19 +00:00
if (entries.length > 0 && entries[0] !== undefined) {
2026-05-26 14:53:33 -07:00
eventLoopDelayMs = entries[0].duration;
2025-07-23 14:28:16 -07:00
}
2026-05-26 14:53:33 -07:00
const uptimeMs = process.uptime() * 1000;
2026-05-26 13:31:13 -07:00
const mongoStats = await this.getMongoDBStats();
2026-05-26 14:53:33 -07:00
return {
2025-07-23 14:28:16 -07:00
osStats,
2026-05-26 14:53:33 -07:00
cpuUsage,
v8HeapStats,
eventLoopDelayMs,
2025-07-23 14:28:16 -07:00
uptimeMs,
2026-05-26 13:31:13 -07:00
mongoStats,
2025-07-23 14:28:16 -07:00
};
};
}