UNPKG

redis-smq-common

Version:

Provides essential components and utilities shared across RedisSMQ packages.

209 lines 7.92 kB
"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || (function () { var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.CPUMonitor = void 0; const crypto = __importStar(require("crypto")); const node_os_1 = __importDefault(require("node:os")); class CPUMonitor { constructor(options = {}) { var _a, _b; this.baselines = new Map(); this.maxBaselineAgeMs = (_a = options.maxBaselineAgeMs) !== null && _a !== void 0 ? _a : 300000; this.precision = Math.max(0, Math.min(3, (_b = options.precision) !== null && _b !== void 0 ? _b : 2)); } static getInstance(options = {}) { if (!CPUMonitor.instance) { CPUMonitor.instance = new CPUMonitor(options); } return CPUMonitor.instance; } cleanupOldBaselines() { const now = Date.now(); const cutoff = now - this.maxBaselineAgeMs; for (const [callerId, entry] of this.baselines) { if (entry.timestamp < cutoff) { this.baselines.delete(callerId); } } } takeSnapshot() { const cpus = node_os_1.default.cpus(); if (!cpus.length) { throw new Error('No CPU information available'); } let totalUser = 0; let totalSystem = 0; let totalIdle = 0; let totalAll = 0; cpus.forEach((cpu) => { totalUser += cpu.times.user; totalSystem += cpu.times.sys; totalIdle += cpu.times.idle; totalAll += cpu.times.user + cpu.times.nice + cpu.times.sys + cpu.times.idle + cpu.times.irq; }); return { user: totalUser, system: totalSystem, idle: totalIdle, total: totalAll, timestamp: Date.now(), }; } calculateUsage(start, end) { if (end.timestamp <= start.timestamp) { return { user: 0, system: 0, percentage: '0%' }; } const userDiff = Math.max(0, end.user - start.user); const systemDiff = Math.max(0, end.system - start.system); const totalDiff = Math.max(0, end.total - start.total); if (totalDiff === 0) { return { user: 0, system: 0, percentage: '0%' }; } const userPct = (userDiff / totalDiff) * 100; const systemPct = (systemDiff / totalDiff) * 100; const totalPct = Math.min(100, userPct + systemPct); const factor = Math.pow(10, this.precision); return { user: Math.round(userPct * factor) / factor, system: Math.round(systemPct * factor) / factor, percentage: Math.round(totalPct) + '%', }; } getStats(callerId = 'default') { this.cleanupOldBaselines(); const current = this.takeSnapshot(); const previous = this.baselines.get(callerId); if (!previous) { this.baselines.set(callerId, { snapshot: current, timestamp: Date.now(), }); return { user: 0, system: 0, percentage: '0%' }; } const usage = this.calculateUsage(previous.snapshot, current); this.baselines.set(callerId, { snapshot: current, timestamp: Date.now() }); return usage; } getStatsOverInterval() { return __awaiter(this, arguments, void 0, function* (callerId = 'default', intervalMs = 1000) { this.cleanupOldBaselines(); const start = this.takeSnapshot(); const tempId = `temp-${callerId}-${Date.now()}`; this.baselines.set(tempId, { snapshot: start, timestamp: Date.now() }); yield new Promise((resolve) => setTimeout(resolve, Math.max(0, intervalMs))); const end = this.takeSnapshot(); const usage = this.calculateUsage(start, end); this.baselines.delete(tempId); return usage; }); } generateCallerId() { return crypto.randomBytes(16).toString('hex'); } removeCaller(callerId) { return this.baselines.delete(callerId); } hasCaller(callerId) { return this.baselines.has(callerId); } getActiveCallerCount() { this.cleanupOldBaselines(); return this.baselines.size; } getActiveCallers() { this.cleanupOldBaselines(); return Array.from(this.baselines.keys()); } getBaselineAge(callerId) { const entry = this.baselines.get(callerId); return entry ? Date.now() - entry.timestamp : null; } reset() { this.baselines.clear(); } cleanup() { this.cleanupOldBaselines(); } getMonitorStats() { this.cleanupOldBaselines(); let oldest = Date.now(); let newest = 0; for (const entry of this.baselines.values()) { oldest = Math.min(oldest, entry.timestamp); newest = Math.max(newest, entry.timestamp); } return { activeCallers: this.baselines.size, oldestBaseline: oldest === Date.now() ? 0 : oldest, newestBaseline: newest, totalBaselines: this.baselines.size, }; } getOneTimeStats() { const id = this.generateCallerId(); const usage = this.getStats(id); this.removeCaller(id); return usage; } getStatsWithAutoId() { const callerId = this.generateCallerId(); const usage = this.getStats(callerId); return { callerId, usage, cleanup: () => this.removeCaller(callerId), }; } } exports.CPUMonitor = CPUMonitor; CPUMonitor.instance = null; //# sourceMappingURL=cpu-monitor.js.map