/** * Queue Monitor for tracking queue levels and sending alerts * Handles low queue and empty queue notifications to authorized users */ const config = require('../config'); const fs = require('fs').promises; const path = require('path'); class QueueMonitor { constructor(telegramBot) { this.telegramBot = telegramBot; this.queueManager = null; // Will be set after initialization // Alert state tracking this.lastQueueLength = 0; this.lowQueueAlertSent = false; this.emptyQueueAlertSent = false; this.lastLowQueueAlertTime = 0; this.lastEmptyQueueAlertTime = 0; // Persistence file path this.stateFilePath = path.join(__dirname, '..', 'queue', 'alert-state.json'); // Configuration this.lowThreshold = config.queueLowThreshold; this.emptyThreshold = config.queueEmptyThreshold; this.alertsEnabled = config.queueAlertsEnabled; this.alertCooldownHours = config.queueAlertCooldownHours || 24; // 24 hour cooldown between alerts // Monitoring interval (check every 30 seconds) this.monitoringInterval = null; this.intervalMs = 30 * 1000; // Periodic save interval (save state every 5 minutes) this.periodicSaveInterval = null; this.saveIntervalMs = 5 * 60 * 1000; // 5 minutes in milliseconds console.log(`[QueueMonitor] Initialized - Low threshold: ${this.lowThreshold}, Empty threshold: ${this.emptyThreshold}, Alerts enabled: ${this.alertsEnabled}`); } /** * Initialize the queue monitor with queue manager reference * @param {Object} queueManager - The queue manager instance */ async init(queueManager) { this.queueManager = queueManager; // Load persisted alert state await this.loadAlertState(); if (this.alertsEnabled) { this.startMonitoring(); } // Start periodic saving regardless of whether alerts are enabled this.startPeriodicSave(); } /** * Start monitoring the queue for changes */ startMonitoring() { if (this.monitoringInterval) { clearInterval(this.monitoringInterval); } this.monitoringInterval = setInterval(() => { this.checkQueueStatus(); }, this.intervalMs); console.log('[QueueMonitor] Queue monitoring started'); } /** * Start periodic saving of alert state (every 5 minutes) */ startPeriodicSave() { if (this.periodicSaveInterval) { clearInterval(this.periodicSaveInterval); } this.periodicSaveInterval = setInterval(async () => { await this.saveAlertState(); console.log('Queue alert state saved (periodic backup)'); }, this.saveIntervalMs); console.log('[QueueMonitor] Periodic alert state saving started (every 5 minutes)'); } /** * Stop monitoring the queue */ stopMonitoring() { if (this.monitoringInterval) { clearInterval(this.monitoringInterval); this.monitoringInterval = null; } console.log('Queue monitoring stopped'); } /** * Stop periodic saving of alert state */ stopPeriodicSave() { if (this.periodicSaveInterval) { clearInterval(this.periodicSaveInterval); this.periodicSaveInterval = null; } console.log('Periodic alert state saving stopped'); } /** * Check current queue status and send alerts if necessary */ async checkQueueStatus() { if (!this.queueManager || !this.alertsEnabled) { return; } try { const currentLength = await this.queueManager.getQueueLength(); const currentTime = Date.now(); const cooldownMs = this.alertCooldownHours * 60 * 60 * 1000; // Convert hours to milliseconds let stateChanged = false; // Only reset alert flags when queue has grown above thresholds // This prevents continuous resetting when queue is at/below thresholds if (currentLength > this.lowThreshold) { if (this.lowQueueAlertSent || this.emptyQueueAlertSent) { this.lowQueueAlertSent = false; this.emptyQueueAlertSent = false; stateChanged = true; } } else if (currentLength > this.emptyThreshold && currentLength <= this.lowThreshold) { // Only reset empty alert flag if we're between empty and low thresholds if (this.emptyQueueAlertSent) { this.emptyQueueAlertSent = false; stateChanged = true; } } // Check for low queue alert (with 24-hour cooldown) const canSendLowAlert = !this.lowQueueAlertSent && (currentTime - this.lastLowQueueAlertTime) >= cooldownMs; if (currentLength <= this.lowThreshold && currentLength > this.emptyThreshold && canSendLowAlert) { await this.sendLowQueueAlert(currentLength); this.lowQueueAlertSent = true; this.lastLowQueueAlertTime = currentTime; stateChanged = true; } // Check for empty queue alert (with 24-hour cooldown) const canSendEmptyAlert = !this.emptyQueueAlertSent && (currentTime - this.lastEmptyQueueAlertTime) >= cooldownMs; if (currentLength <= this.emptyThreshold && canSendEmptyAlert) { await this.sendEmptyQueueAlert(currentLength); this.emptyQueueAlertSent = true; this.lastEmptyQueueAlertTime = currentTime; stateChanged = true; } // Save state if any alert flags or timestamps changed if (stateChanged) { await this.saveAlertState(); } this.lastQueueLength = currentLength; } catch (error) { console.error('Error checking queue status:', error); } } /** * Send low queue alert to all authorized users * @param {number} queueLength - Current queue length */ async sendLowQueueAlert(queueLength) { const message = `⚠️ *Queue Running Low*\n\nThe queue currently has only *${queueLength}* item${queueLength !== 1 ? 's' : ''} remaining.\n\nConsider adding more content to maintain posting schedule.`; await this.sendAlertToAuthorizedUsers(message); console.log(`Low queue alert sent (${queueLength} items remaining)`); } /** * Send empty queue alert to all authorized users * @param {number} queueLength - Current queue length (should be 0 or empty threshold) */ async sendEmptyQueueAlert(queueLength) { const message = queueLength === 0 ? `🚨 *Queue is Empty*\n\nThe queue is completely empty! No content will be posted until new items are added.\n\nUse the bot to add new content immediately.` : `🚨 *Queue Critically Low*\n\nThe queue has only *${queueLength}* item${queueLength !== 1 ? 's' : ''} left and has reached the critical threshold.\n\nImmediate attention required!`; await this.sendAlertToAuthorizedUsers(message); console.log(`Empty queue alert sent (${queueLength} items remaining)`); } /** * Send alert message to all authorized users * @param {string} message - The alert message to send */ async sendAlertToAuthorizedUsers(message) { if (!this.telegramBot || !config.authorizedUsers) { return; } const authorizedUsers = config.authorizedUsers; for (const userId of authorizedUsers) { try { await this.telegramBot.bot.sendMessage(userId, message, { parse_mode: 'Markdown', disable_notification: false }); } catch (error) { console.error(`Failed to send alert to user ${userId}:`, error.message); } } } /** * Get current queue status information * @returns {Object} - Queue status object */ async getQueueStatus() { if (!this.queueManager) { return null; } try { const currentLength = await this.queueManager.getQueueLength(); const queue = await this.queueManager.getQueue(); // Calculate how many items are ready to post for each service const readyItems = { telegram: 0, discord: 0 }; queue.forEach(item => { if (item.postedTo) { if (!item.postedTo.telegram) readyItems.telegram++; if (this.queueManager.postServices.includes('discord') && !item.postedTo.discord) { readyItems.discord++; } } else { // If no postedTo field, assume all services need to post readyItems.telegram++; if (this.queueManager.postServices.includes('discord')) { readyItems.discord++; } } }); return { totalItems: currentLength, readyForTelegram: readyItems.telegram, readyForDiscord: readyItems.discord, shuffleMode: this.queueManager.isShuffleModeEnabled(), alertsEnabled: this.alertsEnabled, lowThreshold: this.lowThreshold, emptyThreshold: this.emptyThreshold, lowQueueAlertSent: this.lowQueueAlertSent, emptyQueueAlertSent: this.emptyQueueAlertSent, lastLowQueueAlertTime: this.lastLowQueueAlertTime, lastEmptyQueueAlertTime: this.lastEmptyQueueAlertTime, alertCooldownHours: this.alertCooldownHours }; } catch (error) { console.error('Error getting queue status:', error); return null; } } /** * Manually trigger a queue status check (for testing or forced updates) */ async forceCheck() { await this.checkQueueStatus(); } /** * Reset alert flags (useful for testing or manual reset) */ async resetAlerts() { this.lowQueueAlertSent = false; this.emptyQueueAlertSent = false; this.lastLowQueueAlertTime = 0; this.lastEmptyQueueAlertTime = 0; await this.saveAlertState(); console.log('Queue alert flags and timestamps reset'); } /** * Update configuration settings * @param {Object} newConfig - New configuration object */ updateConfig(newConfig) { if (newConfig.lowThreshold !== undefined) { this.lowThreshold = newConfig.lowThreshold; } if (newConfig.emptyThreshold !== undefined) { this.emptyThreshold = newConfig.emptyThreshold; } if (newConfig.alertCooldownHours !== undefined) { this.alertCooldownHours = newConfig.alertCooldownHours; } if (newConfig.alertsEnabled !== undefined) { this.alertsEnabled = newConfig.alertsEnabled; if (this.alertsEnabled && !this.monitoringInterval) { this.startMonitoring(); } else if (!this.alertsEnabled && this.monitoringInterval) { this.stopMonitoring(); } // Note: Periodic saving continues regardless of alert settings // to ensure state persistence for cooldown timers } console.log(`Queue monitor config updated - Low: ${this.lowThreshold}, Empty: ${this.emptyThreshold}, Cooldown: ${this.alertCooldownHours}h, Enabled: ${this.alertsEnabled}`); } /** * Load alert state from persistent storage */ async loadAlertState() { try { const data = await fs.readFile(this.stateFilePath, 'utf8'); const state = JSON.parse(data); // Restore alert flags and timestamps this.lowQueueAlertSent = state.lowQueueAlertSent || false; this.emptyQueueAlertSent = state.emptyQueueAlertSent || false; this.lastLowQueueAlertTime = state.lastLowQueueAlertTime || 0; this.lastEmptyQueueAlertTime = state.lastEmptyQueueAlertTime || 0; console.log('[QueueMonitor] Queue alert state loaded from persistent storage'); // Log current cooldown status if alerts were previously sent const currentTime = Date.now(); const cooldownMs = this.alertCooldownHours * 60 * 60 * 1000; if (this.lastLowQueueAlertTime > 0) { const timeSinceLastLow = currentTime - this.lastLowQueueAlertTime; const lowCooldownRemaining = Math.max(0, cooldownMs - timeSinceLastLow); if (lowCooldownRemaining > 0) { const hoursRemaining = Math.ceil(lowCooldownRemaining / (60 * 60 * 1000)); console.log(`[QueueMonitor] Low queue alert cooldown: ${hoursRemaining} hours remaining`); } } if (this.lastEmptyQueueAlertTime > 0) { const timeSinceLastEmpty = currentTime - this.lastEmptyQueueAlertTime; const emptyCooldownRemaining = Math.max(0, cooldownMs - timeSinceLastEmpty); if (emptyCooldownRemaining > 0) { const hoursRemaining = Math.ceil(emptyCooldownRemaining / (60 * 60 * 1000)); console.log(`[QueueMonitor] Empty queue alert cooldown: ${hoursRemaining} hours remaining`); } } } catch (error) { if (error.code === 'ENOENT') { console.log('[QueueMonitor] No existing alert state file found, starting with fresh state'); } else { console.error('[QueueMonitor] Error loading alert state:', error); } // Continue with default values if file doesn't exist or is corrupted } } /** * Save alert state to persistent storage */ async saveAlertState() { try { const state = { lowQueueAlertSent: this.lowQueueAlertSent, emptyQueueAlertSent: this.emptyQueueAlertSent, lastLowQueueAlertTime: this.lastLowQueueAlertTime, lastEmptyQueueAlertTime: this.lastEmptyQueueAlertTime, lastSaved: Date.now() }; await fs.writeFile(this.stateFilePath, JSON.stringify(state, null, 2)); } catch (error) { console.error('Error saving alert state:', error); } } /** * Shutdown the queue monitor */ async shutdown() { this.stopMonitoring(); this.stopPeriodicSave(); await this.saveAlertState(); console.log('Queue monitor shutdown complete'); } } module.exports = QueueMonitor;