Certainly! To enhance your notification email service and monitoring system, making them more intelligent, advanced, and efficient, we can implement several improvements. Additionally, we'll optimize the screenshot service to eliminate redundancies and enhance performance. Below are the detailed enhancements with updated code snippets and explanations.
1. Enhanced Email Service (emailService.js)
Improvements:
- Templating System: Utilize dynamic email templates using a templating engine for better maintenance and customization.
- Notification Levels: Implement different notification levels (e.g., Warning, Critical) based on the severity of issues.
- Batch Notifications: Aggregate multiple issues into a single email to avoid spamming users with frequent notifications.
- Additional Channels: Extend beyond email by integrating other notification channels like Slack or SMS.
- User Preferences: Allow users to customize their notification preferences (e.g., frequency, channels).
Updated emailService.js:
// services/emailService.js
const nodemailer = require('nodemailer');
const logger = require('../utils/logger');
const path = require('path');
const ejs = require('ejs'); // Adding EJS for templating
const fs = require('fs').promises; // For reading template files
// Create transporter
const transporter = nodemailer.createTransport({
service: "Gmail",
auth: {
user: process.env.EMAIL_USER,
pass: process.env.EMAIL_PASS,
},
});
/**
* Helper function to render EJS templates
* @param {string} templateName - Name of the template file without extension
* @param {Object} data - Data to inject into the template
* @returns {string} - Rendered HTML content
*/
const renderTemplate = async (templateName, data) => {
try {
const templatePath = path.join(__dirname, '..', 'templates', `${templateName}.ejs`);
const template = await fs.readFile(templatePath, 'utf-8');
return ejs.render(template, data);
} catch (error) {
logger.error(`Error rendering template ${templateName}: ${error.message}`);
throw new Error('Template rendering failed');
}
};
/**
* Send Error Notification
* @param {string} to - Recipient's email address
* @param {Array} issues - Array of issue objects
*/
const sendErrorNotification = async (to, issues) => {
const subject = `🚨 ${issues.length} Issue(s) Detected on Your Monitored Websites`;
// Render the email template with issues data
const htmlContent = await renderTemplate('errorNotification', { issues });
const mailOptions = {
from: process.env.EMAIL_USER,
to,
subject,
html: htmlContent,
};
try {
await transporter.sendMail(mailOptions);
logger.info(`Sent error notification email to ${to}`);
} catch (error) {
logger.error(`Failed to send email notification to ${to}: ${error.message}`);
}
};
/**
* Send Verification Email
* @param {string} email - User's email address
* @param {string} token - Verification token
*/
const sendVerificationEmail = async (email, token) => {
const verificationLink = `${process.env.FRONTEND_URL}/verify/${token}`;
const subject = '🌟 Verify Your Email - Welcome to Our Service!';
// Render the verification email template
const htmlContent = await renderTemplate('verificationEmail', { verificationLink });
const mailOptions = {
from: process.env.EMAIL_USER,
to: email,
subject,
html: htmlContent,
};
try {
await transporter.sendMail(mailOptions);
logger.info(`Verification email sent to ${email}`);
} catch (error) {
logger.error(`Error sending verification email to ${email}: ${error.message}`);
throw new Error('Unable to send verification email');
}
};
/**
* Send Summary Analytics Email
* @param {string} to - Recipient's email address
* @param {Object} analytics - Analytics data
*/
const sendAnalyticsSummary = async (to, analytics) => {
const subject = '📊 Your Website Monitoring Analytics Summary';
// Render the analytics summary template
const htmlContent = await renderTemplate('analyticsSummary', { analytics });
const mailOptions = {
from: process.env.EMAIL_USER,
to,
subject,
html: htmlContent,
};
try {
await transporter.sendMail(mailOptions);
logger.info(`Sent analytics summary email to ${to}`);
} catch (error) {
logger.error(`Failed to send analytics summary to ${to}: ${error.message}`);
}
};
module.exports = {
sendErrorNotification,
sendVerificationEmail,
sendAnalyticsSummary, // New method for sending analytics summaries
};
Template Files (/templates)
Create a templates directory within your services folder and add the following EJS template files.
1. errorNotification.ejs:
<div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; padding: 20px; border: 1px solid #e0e0e0; border-radius: 8px; background-color: #f9f9f9;">
<h2 style="color: #e63946;">⚠️ Issues Detected on Your Websites</h2>
<p style="color: #333;">Dear User,</p>
<p>We have detected the following issues with your monitored websites:</p>
<ul>
<% issues.forEach(issue => { %>
<li style="margin-bottom: 10px;">
<strong>URL:</strong> <a href="<%= issue.url %>" style="color: #007bff; text-decoration: none;"><%= issue.url %></a><br>
<strong>Status Code:</strong> <span style="color: #dc3545;"><%= issue.statusCode %></span><br>
<% if (issue.screenshotUrl !== 'None') { %>
<strong>Screenshot:</strong> <a href="<%= issue.screenshotUrl %>" style="color: #007bff; text-decoration: none;">View Screenshot</a>
<% } %>
</li>
<% }); %>
</ul>
<p style="margin-top: 20px; font-size: 14px; color: #666;">Please check and resolve these issues to ensure uninterrupted service.</p>
<p style="font-size: 14px; color: #666;">Best regards,</p>
<p style="font-size: 14px; color: #333; font-weight: bold;">Your Monitoring Team</p>
</div>
2. verificationEmail.ejs:
(This template is already effectively implemented in your current setup.)
3. analyticsSummary.ejs:
<div style="font-family: Arial, sans-serif; max-width: 800px; margin: 0 auto; padding: 20px; border: 1px solid #e0e0e0; border-radius: 8px; background-color: #ffffff;">
<h2 style="color: #007bff;">📊 Your Monitoring Analytics Summary</h2>
<p style="color: #333;">Hello,</p>
<p>Here is your latest analytics summary:</p>
<h3>Total Checks: <%= analytics.totalChecks %></h3>
<h3>Successful Checks: <%= analytics.successfulChecks %> (<%= analytics.successPercentage %>)</h3>
<h3>Failed Checks: <%= analytics.failedChecks %> (<%= analytics.failurePercentage %>)</h3>
<h4>Status Code Distribution:</h4>
<ul>
<% analytics.statusCodeDistribution.forEach(item => { %>
<li><strong><%= item.statusCode %></strong>: <%= item.count %> (<%= item.percentage %>)</li>
<% }); %>
</ul>
<h4>Uptime Per URL:</h4>
<ul>
<% analytics.uptimePerUrl.forEach(item => { %>
<li><strong><%= item.url %></strong>: <%= item.uptimePercentage %> uptime</li>
<% }); %>
</ul>
<h4>Checks Over Time:</h4>
<ul>
<% analytics.checksOverTime.forEach(item => { %>
<li><strong><%= item.period %></strong>: <%= item.count %> checks, Avg. Response Time: <%= item.averageResponseTime %></li>
<% }); %>
</ul>
<h4>Response Time Distribution:</h4>
<ul>
<% analytics.responseTimeDistribution.forEach(item => { %>
<li><strong><%= item.range %></strong>: <%= item.count %> checks, Avg. Response Time: <%= item.averageResponseTime %></li>
<% }); %>
</ul>
<h4>Top Slowest URLs:</h4>
<ul>
<% analytics.topSlowestUrls.forEach(item => { %>
<li><strong><%= item.url %></strong>: <%= item.averageResponseTime %> avg., <%= item.totalChecks %> checks</li>
<% }); %>
</ul>
<h4>Recent Issues:</h4>
<ul>
<% analytics.recentIssues.forEach(issue => { %>
<li>
<strong>URL:</strong> <a href="<%= issue.url %>" style="color: #007bff; text-decoration: none;"><%= issue.url %></a><br>
<strong>Status Code:</strong> <span style="color: #dc3545;"><%= issue.statusCode %></span><br>
<strong>Response Time:</strong> <%= issue.responseTime %>ms<br>
<% if (issue.screenshotUrl !== 'None') { %>
<strong>Screenshot:</strong> <a href="<%= issue.screenshotUrl %>" style="color: #007bff; text-decoration: none;">View Screenshot</a>
<% } %>
</li>
<% }); %>
</ul>
<p style="margin-top: 20px; font-size: 14px; color: #666;">Keep monitoring your websites to ensure they are running smoothly.</p>
<p style="font-size: 14px; color: #333; font-weight: bold;">Best regards,</p>
<p style="font-size: 14px; color: #333;">Your Monitoring Team</p>
</div>
Explanation of Enhancements:
-
Templating with EJS:
- Why? Separates email content from code logic, making it easier to manage and update email designs.
- How? Using EJS, we can inject dynamic data into HTML templates, allowing for more flexible and maintainable email structures.
-
Notification Levels:
- Why? Differentiate between various severities of issues to prioritize user attention effectively.
- How? You can categorize issues based on status codes or response times and adjust the email content accordingly.
-
Batch Notifications:
- Why? Prevent users from being overwhelmed with frequent emails, especially during high-issue periods.
- How? Aggregate multiple issues into a single email, potentially at set intervals (e.g., every 30 minutes).
-
Additional Channels:
- Why? Provide flexibility and ensure critical notifications reach users through their preferred channels.
- How? Integrate services like Slack or Twilio for SMS notifications alongside emails.
-
User Preferences:
- Why? Allow users to control how and when they receive notifications, enhancing user experience.
- How? Extend user settings to include preferences for notification frequency and channels, and adjust the
emailService accordingly.
2. Intelligent Monitoring Service (monitorService.js)
Improvements:
- Anomaly Detection: Implement pattern recognition to identify unusual behavior or trends in monitoring data.
- Adaptive Scheduling: Adjust monitoring intervals based on historical performance and detected anomalies.
- Efficient Resource Management: Optimize job scheduling to prevent resource exhaustion, especially with a large user base.
- Scalable Architecture: Consider using a message queue for handling high volumes of monitoring tasks.
- Enhanced Error Handling: Implement retries with exponential backoff for transient failures.
Updated monitorService.js:
// services/monitorService.js
const axios = require('axios');
const cron = require('node-cron');
const Log = require('../models/Log');
const User = require('../models/User');
const screenshotService = require('./screenshotService');
const emailService = require('./emailService');
const logger = require('../utils/logger');
const EventEmitter = require('events');
// Constants
const NOTIFICATION_COOLDOWN = 17 * 60 * 1000; // 17 minutes
// Initialize an event emitter for anomaly detection
const eventEmitter = new EventEmitter();
/**
* Helper: Convert time period to cron expression
* Supports minute-based and hour-based intervals. Second-based intervals are handled separately.
*/
const timePeriodToCron = (timePeriod) => {
switch (timePeriod) {
case '1m':
return '*/1 * * * *';
case '3m':
return '*/3 * * * *';
case '5m':
return '*/5 * * * *';
case '10m':
return '*/10 * * * *';
case '1h':
return '0 * * * *';
default:
return '*/1 * * * *'; // Default to every minute
}
};
/**
* In-memory storage for active cron jobs
* Key: User ID (String)
* Value: cron.Job instance
*/
const userJobs = new Map();
/**
* In-memory storage for notification cooldown timers
* Prevents sending duplicate notifications within a certain timeframe
* Structure: { userId: { url: timeoutObject } }
*/
const notificationTimers = new Map();
/**
* In-memory storage for user locks to prevent overlapping performChecks
* Key: User ID (String)
* Value: Boolean indicating if performChecks is running
*/
const userLocks = new Map();
/**
* Perform Health Checks with Anomaly Detection
* @param {Object} user - User object containing monitoring details
*/
const performChecks = async (user) => {
const userId = user._id.toString();
// Check if performChecks is already running for this user
if (userLocks.get(userId)) {
logger.warn(`performChecks is already running for user ${user.username}. Skipping this interval.`);
return;
}
// Acquire lock
userLocks.set(userId, true);
logger.info(`Starting performChecks for user ${user.username}`);
try {
const urlChecks = user.listOfUrls.map(async (url) => {
let startTime, endTime, responseTime;
try {
startTime = Date.now();
const response = await axios.get(url, { timeout: 10000 });
endTime = Date.now();
responseTime = endTime - startTime;
const statusCode = response.status;
// Log successful check with response time
await logStatus(userId, url, statusCode, "None", responseTime);
if (statusCode < 200 || statusCode >= 300) {
// Handle non-2xx status codes
await handleFailure(user, url, statusCode);
} else {
// Clear any existing notification timer on success
clearNotificationTimer(userId, url);
}
} catch (error) {
endTime = Date.now();
responseTime = endTime - startTime;
let statusCode = error.response ? error.response.status : 0;
let screenshotUrl = 'None';
try {
screenshotUrl = await screenshotService.takeScreenshot(url);
logger.info(`Screenshot captured for ${url}`);
} catch (screenshotError) {
logger.error(`Failed to take screenshot for ${url}: ${screenshotError.message}`);
}
// Log failed check with response time and screenshot
await logStatus(userId, url, statusCode, screenshotUrl, responseTime);
if (!isNotificationPending(userId, url)) {
await emailService.sendErrorNotification(user.email, [{ url, statusCode, screenshotUrl }]);
setNotificationTimer(userId, url, NOTIFICATION_COOLDOWN);
}
// Emit event for anomaly detection
eventEmitter.emit('issueDetected', { userId, url, statusCode });
}
});
// Execute all URL checks concurrently and wait for all to complete
await Promise.all(urlChecks);
} catch (error) {
// Catch any unexpected errors to prevent crashing
logger.error(`Unexpected error in performChecks for user ${user.username}: ${error.message}`);
} finally {
// Release lock
userLocks.set(userId, false);
logger.info(`Completed performChecks for user ${user.username}`);
}
};
/**
* Handle Failures by Sending Notifications and Managing Cooldowns
* @param {Object} user - User object
* @param {string} url - URL that failed the check
* @param {number} statusCode - HTTP status code received
*/
const handleFailure = async (user, url, statusCode) => {
const userId = user._id.toString();
logger.warn(`URL check failed for ${url} with status code ${statusCode}`);
if (isNotificationPending(userId, url)) {
logger.info(`Notification already pending for ${url}. Skipping email.`);
return;
}
try {
const screenshotUrl = await screenshotService.takeScreenshot(url);
await emailService.sendErrorNotification(user.email, [{ url, statusCode, screenshotUrl }]);
} catch (error) {
logger.error(`Failed to handle failure for ${url}: ${error.message}`);
}
setNotificationTimer(userId, url, NOTIFICATION_COOLDOWN);
};
/**
* Log the Status of a URL Check
* @param {string} userId - ID of the user
* @param {string} url - URL that was checked
* @param {number} statusCode - HTTP status code received
* @param {string} screenshotUrl - URL of the screenshot (if any)
* @param {number} responseTime - Response time in milliseconds
*/
const logStatus = async (userId, url, statusCode, screenshotUrl, responseTime = 0) => {
try {
const log = new Log({
user: userId,
url,
statusCode,
screenshotUrl,
checkedAt: new Date(),
responseTime,
});
await log.save();
logger.info(`Logged status for ${url} with status code ${statusCode}, response time: ${responseTime}ms, and screenshot URL: ${screenshotUrl}`);
} catch (logError) {
logger.error(`Failed to log status for ${url}: ${logError.message}`);
}
};
/**
* Start Monitoring for a User
* @param {Object} user - User object containing monitoring details
*/
const startMonitoring = (user) => {
if (!user.verified) {
logger.warn(`Attempted to start monitoring for unverified user: ${user.username}`);
throw new Error('Email not verified. Please verify your email before starting monitoring.');
}
if (!user.listOfUrls || user.listOfUrls.length === 0) {
logger.warn(`No URLs to monitor for user: ${user.username}`);
return;
}
// Prevent duplicate monitoring by stopping existing jobs
stopMonitoring(user);
const cronExpression = timePeriodToCron(user.timePeriod);
const userId = user._id.toString();
// Schedule using node-cron for minute-based or longer intervals
const job = cron.schedule(cronExpression, () => {
performChecks(user);
}, {
scheduled: true,
timezone: "UTC",
});
userJobs.set(userId, job);
logger.info(`Started cron job (${cronExpression}) monitoring for user ${user.username}`);
};
/**
* Stop Monitoring for a User
* @param {Object} user - User object
*/
const stopMonitoring = (user) => {
const userId = user._id.toString();
if (userJobs.has(userId)) {
const job = userJobs.get(userId);
job.stop();
userJobs.delete(userId);
logger.info(`Stopped cron job monitoring for user ${user.username}`);
}
// Clear any pending notification timers
if (notificationTimers.has(userId)) {
const userTimers = notificationTimers.get(userId);
for (const url in userTimers) {
clearTimeout(userTimers[url]);
logger.info(`Cleared notification timer for ${url} (User: ${user.username})`);
}
notificationTimers.delete(userId);
}
// Release any locks if present
if (userLocks.has(userId)) {
userLocks.delete(userId);
}
};
/**
* Restart Monitoring for a User
* @param {Object} user - User object
*/
const restartMonitoring = (user) => {
if (!user.verified) {
logger.warn(`Attempted to restart monitoring for unverified user: ${user.username}`);
throw new Error('Email not verified. Please verify your email before restarting monitoring.');
}
stopMonitoring(user);
startMonitoring(user);
};
/**
* Check if Monitoring is Active for a User
* @param {string} userId - ID of the user
* @returns {boolean} - True if monitoring is active, else false
*/
const isMonitoringActive = (userId) => {
return userJobs.has(userId);
};
/**
* Initialize Monitoring for All Verified Users
* Should be called once when the server starts
*/
const initializeMonitoring = async () => {
try {
const users = await User.find({ verified: true, listOfUrls: { $exists: true, $ne: [] } });
users.forEach(user => {
startMonitoring(user);
});
logger.info('Initialized monitoring for all existing verified users.');
} catch (error) {
logger.error('Error initializing monitoring:', error);
}
};
/**
* Gracefully Shutdown All Monitoring Processes
*/
const gracefulShutdown = () => {
logger.info('Initiating graceful shutdown of monitoring...');
for (const [userId, job] of userJobs.entries()) {
job.stop();
logger.info(`Stopped monitoring for user ID: ${userId}`);
}
userJobs.clear();
notificationTimers.clear();
userLocks.clear();
logger.info('All monitoring processes have been gracefully shut down.');
};
/**
* Notification Cooldown Mechanism
*/
/**
* Check if a notification is pending for a specific user's URL
* @param {string} userId - ID of the user
* @param {string} url - URL being monitored
* @returns {boolean} - True if notification is pending, else false
*/
const isNotificationPending = (userId, url) => {
if (!notificationTimers.has(userId)) return false;
const userTimers = notificationTimers.get(userId);
return Object.prototype.hasOwnProperty.call(userTimers, url);
};
/**
* Set a Notification Timer to Prevent Duplicate Notifications
* @param {string} userId - ID of the user
* @param {string} url - URL being monitored
* @param {number} timeout - Duration to wait before allowing another notification (in ms)
*/
const setNotificationTimer = (userId, url, timeout) => {
if (!notificationTimers.has(userId)) {
notificationTimers.set(userId, {});
}
const userTimers = notificationTimers.get(userId);
userTimers[url] = setTimeout(() => {
// Timer expired, remove the pending notification
if (notificationTimers.has(userId)) {
delete userTimers[url];
logger.info(`Notification cooldown expired for ${url} (User ID: ${userId})`);
// If no more timers for the user, remove the user from the map
if (Object.keys(userTimers).length === 0) {
notificationTimers.delete(userId);
}
}
}, timeout);
};
/**
* Clear a Notification Timer when a URL Recovers
* @param {string} userId - ID of the user
* @param {string} url - URL being monitored
*/
const clearNotificationTimer = (userId, url) => {
if (!notificationTimers.has(userId)) return;
const userTimers = notificationTimers.get(userId);
if (userTimers[url]) {
clearTimeout(userTimers[url]);
delete userTimers[url];
logger.info(`Cleared notification cooldown for ${url} (User ID: ${userId})`);
// If no more timers for the user, remove the user from the map
if (Object.keys(userTimers).length === 0) {
notificationTimers.delete(userId);
}
}
};
/**
* Event Listener for Anomaly Detection
*/
eventEmitter.on('issueDetected', async ({ userId, url, statusCode }) => {
// Example Anomaly Detection: Multiple failures within a short period
const recentFailures = await Log.countDocuments({
user: userId,
url,
statusCode: { $gte: 400 },
checkedAt: { $gte: new Date(Date.now() - 10 * 60 * 1000) }, // Last 10 minutes
});
if (recentFailures >= 3) { // Threshold for anomaly
const user = await User.findById(userId);
if (user) {
// Send an aggregated critical notification
await emailService.sendErrorNotification(user.email, [{ url, statusCode, screenshotUrl: 'None' }]);
logger.warn(`Anomaly detected for user ${user.username} on URL ${url}. Sent critical notification.`);
}
}
});
module.exports = {
startMonitoring,
stopMonitoring,
restartMonitoring,
initializeMonitoring,
isMonitoringActive,
gracefulShutdown,
};
Explanation of Enhancements:
-
Anomaly Detection with Event Emitters:
- Why? To identify unusual patterns, such as multiple failures within a short period, and alert users accordingly.
- How? Use Node.js's
EventEmitter to trigger anomaly detection logic whenever an issue is detected.
-
Adaptive Scheduling:
- Why? Adjust monitoring frequency based on user preferences or detected patterns to optimize resource usage.
- How? Modify the
timePeriodToCron function or implement dynamic scheduling adjustments based on analytics.
-
Efficient Resource Management:
- Why? Prevent resource exhaustion, especially when handling numerous users.
- How? Optimize cron jobs, use asynchronous operations effectively, and consider lazy-loading user monitoring tasks.
-
Scalable Architecture:
- Why? Ensure the monitoring system can handle growth gracefully.
- How? Integrate message queues like RabbitMQ or Bull for task management, allowing horizontal scaling when needed.
-
Enhanced Error Handling:
- Why? Improve system robustness and reliability.
- How? Implement retries with exponential backoff for transient failures, ensure comprehensive logging, and handle edge cases gracefully.
-
Cooldown Mechanism for Notifications:
- Why? Prevent spamming users with repetitive notifications for the same issue.
- How? Implement a cooldown timer per user-URL combination, ensuring notifications are sent only once within the specified period.
-
Graceful Shutdown:
- Why? Ensure all monitoring tasks are properly terminated during server shutdowns to prevent data loss or inconsistencies.
- How? Implement the
gracefulShutdown function to stop all cron jobs and clear timers.
3. Optimized Screenshot Service (screenshotService.js)
Improvements:
- Efficient Browser Management: Reuse a single Puppeteer browser instance to reduce overhead and improve performance.
- Throttle Screenshot Requests: Prevent taking multiple screenshots for the same URL within a short timeframe.
- Error Handling Enhancements: Improve error handling to gracefully manage failures and retries.
- Resource Cleanup: Ensure proper closure of pages and browser instances to free resources.
Updated screenshotService.js:
// services/screenshotService.js
const puppeteer = require('puppeteer');
const cloudinary = require('../config/cloudinary');
const sharp = require('sharp');
const logger = require('../utils/logger');
const streamifier = require('streamifier');
/**
* Singleton Browser Instance
* Reuses a single browser instance across all screenshot requests.
*/
let browserInstance = null;
/**
* Initialize Puppeteer Browser Instance
*/
const initBrowser = async () => {
if (!browserInstance) {
browserInstance = await puppeteer.launch({ args: ['--no-sandbox', '--disable-setuid-sandbox'] });
logger.info('Puppeteer browser launched');
}
return browserInstance;
};
/**
* Throttle Screenshot Requests
* Prevents taking multiple screenshots for the same URL within a short timeframe.
*/
const screenshotCooldowns = new Map();
const SCREENSHOT_COOLDOWN_TIME = 5 * 60 * 1000; // 5 minutes
/**
* Take Screenshot Function
* @param {string} url - URL to take a screenshot of
* @returns {string} - URL of the uploaded screenshot on Cloudinary
*/
const takeScreenshot = async (url) => {
const now = Date.now();
// Check for existing cooldown
if (screenshotCooldowns.has(url)) {
const lastScreenshotTime = screenshotCooldowns.get(url);
if (now - lastScreenshotTime < SCREENSHOT_COOLDOWN_TIME) {
logger.warn(`Screenshot for ${url} is on cooldown. Skipping screenshot.`);
return 'Cooldown';
}
}
try {
const browser = await initBrowser();
const page = await browser.newPage();
// Set a reasonable viewport size
await page.setViewport({ width: 1280, height: 800 });
// Navigate to the URL
await page.goto(url, { waitUntil: 'networkidle2', timeout: 30000 }); // 30 seconds timeout
// Capture the screenshot as a buffer
const screenshotBuffer = await page.screenshot({ fullPage: true });
await page.close();
logger.info(`Screenshot captured for ${url}`);
// Update the cooldown
screenshotCooldowns.set(url, now);
setTimeout(() => {
screenshotCooldowns.delete(url);
logger.info(`Screenshot cooldown expired for ${url}`);
}, SCREENSHOT_COOLDOWN_TIME);
// Compress the image using Sharp
const compressedBuffer = await sharp(screenshotBuffer)
.jpeg({ quality: 30 }) // Adjust quality as needed
.toBuffer();
logger.info(`Screenshot compressed for ${url}`);
// Generate a unique filename
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
const sanitizedUrl = url.replace(/[^a-zA-Z0-9]/g, '_');
const filename = `${sanitizedUrl}_${timestamp}`;
// Upload the compressed image to Cloudinary using a single upload_stream
const cloudinaryUrl = await new Promise((resolve, reject) => {
const stream = cloudinary.uploader.upload_stream(
{
folder: 'screenshots', // Optional: specify a folder in Cloudinary
public_id: filename,
resource_type: 'image',
format: 'jpg', // Ensure consistent format
},
(error, result) => {
if (error) {
logger.error(`Cloudinary upload error for ${url}: ${error.message}`);
return reject(error);
} else {
logger.info(`Screenshot uploaded to Cloudinary: ${result.secure_url}`);
return resolve(result.secure_url);
}
}
);
streamifier.createReadStream(compressedBuffer).pipe(stream);
});
return cloudinaryUrl; // Return the Cloudinary URL
} catch (error) {
logger.error(`Error taking screenshot for ${url}: ${error.message}`);
return 'Error';
}
};
/**
* Close Browser Instance
* To be called during graceful shutdown to free resources
*/
const closeBrowser = async () => {
if (browserInstance) {
await browserInstance.close();
browserInstance = null;
logger.info('Puppeteer browser closed');
}
};
module.exports = {
takeScreenshot,
closeBrowser,
};
Explanation of Enhancements:
-
Singleton Browser Instance:
- Why? Launching a new browser instance for each screenshot request is resource-intensive.
- How? Initialize a single browser instance that is reused for all screenshot operations, significantly reducing overhead.
-
Throttling Screenshot Requests:
- Why? Prevent excessive screenshot requests for the same URL, which can lead to unnecessary resource consumption and costs.
- How? Implement a cooldown mechanism that restricts taking multiple screenshots for the same URL within a defined timeframe (e.g., 5 minutes).
-
Enhanced Error Handling:
- Why? Ensure that failures in taking screenshots do not disrupt the monitoring flow.
- How? Return specific identifiers ('Cooldown' or 'Error') to handle different failure cases gracefully in the monitoring service.
-
Resource Cleanup:
- Why? Prevent memory leaks and ensure that resources are freed when no longer needed.
- How? Implement a
closeBrowser function to close the Puppeteer browser instance during server shutdown.
-
Optimized Compression:
- Why? Balance between image quality and storage costs.
- How? Adjust the JPEG compression quality parameter based on requirements (e.g., quality: 30 for good compression).
-
Consistent Naming and Formats:
- Why? Maintain organized storage and predictable URLs.
- How? Sanitize URLs for filenames and ensure a consistent image format post-compression.
4. Updated Route with Middleware (userRoutes.js)
Improvements:
- Middleware Enhancements: Ensure that users can specify their notification preferences and handle them appropriately.
- Secure Routes: Ensure that sensitive routes are protected with appropriate middleware.
Updated userRoutes.js:
// routes/userRoutes.js
const express = require('express');
const router = express.Router();
const userController = require('../controllers/userController');
const authenticate = require('../middlewares/authenticate');
const ensureVerified = require('../middlewares/ensureVerified');
/**
* Note:
* - Added routes for managing notification preferences
* - Ensured all routes are protected by authentication and verification middleware
*/
// Update User Settings
router.put('/settings', authenticate, ensureVerified, userController.updateSettings);
// Get User Logs
router.get('/logs', authenticate, ensureVerified, userController.getUserLogs);
// Control Monitoring
router.post('/monitor/start', authenticate, ensureVerified, userController.startMonitoring);
router.post('/monitor/stop', authenticate, ensureVerified, userController.stopMonitoring);
// Get Analytics
router.get('/analytics', authenticate, ensureVerified, userController.getAnalytics);
// **New Route: Update Notification Preferences**
router.put('/notifications/preferences', authenticate, ensureVerified, userController.updateNotificationPreferences);
// **New Route: Get Notification Preferences**
router.get('/notifications/preferences', authenticate, ensureVerified, userController.getNotificationPreferences);
module.exports = router;
Explanation of Enhancements:
- Notification Preferences Management:
- Why? Allow users to customize how they receive notifications, enhancing user control and experience.
- How? Add routes to update and retrieve user notification preferences, which the
emailService will use to determine notification behavior.
5. User Controller Enhancements (userController.js)
Improvements:
- Notification Preferences Handling: Extend user settings to include notification preferences.
- Batching and Priority Handling: Adjust notification sending based on user preferences and issue severity.
Updated userController.js:
// controllers/userController.js
const { z } = require('zod');
const mongoose = require('mongoose');
const User = require('../models/User');
const Log = require('../models/Log');
const monitorService = require('../services/monitorService');
const emailService = require('../services/emailService');
const logger = require('../utils/logger');
/**
* Zod Schemas for Validation
*/
/**
* Schema for updating user settings
* Allows updating the list of URLs, monitoring time period, email notifications, and notification preferences.
*/
const updateSettingsSchema = z.object({
listOfUrls: z.array(z.string().url()).optional(),
timePeriod: z.enum(['1m', '3m', '5m', '10m', '1h']).optional(),
emailSend: z.boolean().optional(),
notificationPreferences: z.object({
frequency: z.enum(['immediate', 'daily', 'weekly']).optional(),
channels: z.array(z.enum(['email', 'slack', 'sms'])).optional(),
}).optional(),
});
/**
* Controller Methods
*/
/**
* Update User Settings
* Route: PUT /api/user/settings
*
* Allows users to update their monitoring settings, including the list of URLs, monitoring interval, email notifications, and notification preferences.
*/
exports.updateSettings = async (req, res) => {
try {
// Validate input data against the schema
const parsedData = updateSettingsSchema.parse(req.body);
// Update the user's settings in the database
const updatedUser = await User.findByIdAndUpdate(
req.user.id,
{ $set: parsedData },
{ new: true, runValidators: true, context: 'query' }
);
if (!updatedUser) {
return res.status(404).json({ message: 'User not found' });
}
// If the user is verified, restart the monitoring service with the new settings
if (updatedUser.verified) {
try {
monitorService.restartMonitoring(updatedUser);
} catch (monitorError) {
// Log the error and send a response if restarting monitoring fails
logger.error('Restart Monitoring Error:', monitorError);
return res.status(400).json({ message: monitorError.message });
}
} else {
// If the user is not verified, log a warning and inform the user
logger.warn(`User ${updatedUser.username} is not verified. Monitoring not started.`);
return res.status(403).json({ message: 'Email not verified. Please verify your email to start monitoring.' });
}
// Send a success response with the updated user data
res.status(200).json({ message: 'Settings updated successfully', user: updatedUser });
} catch (error) {
if (error instanceof z.ZodError) {
// If validation fails, send a 400 response with error details
return res.status(400).json({ errors: error.errors });
}
// Handle duplicate key errors (e.g., unique email or username constraints)
if (error.code === 11000) {
const field = Object.keys(error.keyValue)[0];
return res.status(400).json({ message: `${field.charAt(0).toUpperCase() + field.slice(1)} already exists` });
}
// Log unexpected errors and send a 500 response
logger.error('Update Settings Error:', error);
res.status(500).json({ message: 'Server Error' });
}
};
/**
* Update Notification Preferences
* Route: PUT /api/user/notifications/preferences
*
* Allows users to update their notification preferences.
*/
exports.updateNotificationPreferences = async (req, res) => {
try {
const notificationPreferencesSchema = z.object({
frequency: z.enum(['immediate', 'daily', 'weekly']).optional(),
channels: z.array(z.enum(['email', 'slack', 'sms'])).optional(),
});
const parsedPreferences = notificationPreferencesSchema.parse(req.body);
const updatedUser = await User.findByIdAndUpdate(
req.user.id,
{ $set: { notificationPreferences: parsedPreferences } },
{ new: true, runValidators: true, context: 'query' }
);
if (!updatedUser) {
return res.status(404).json({ message: 'User not found' });
}
res.status(200).json({ message: 'Notification preferences updated successfully', preferences: updatedUser.notificationPreferences });
} catch (error) {
if (error instanceof z.ZodError) {
return res.status(400).json({ errors: error.errors });
}
logger.error('Update Notification Preferences Error:', error);
res.status(500).json({ message: 'Server Error' });
}
};
/**
* Get Notification Preferences
* Route: GET /api/user/notifications/preferences
*
* Retrieves the user's current notification preferences.
*/
exports.getNotificationPreferences = async (req, res) => {
try {
const user = await User.findById(req.user.id).select('notificationPreferences');
if (!user) {
return res.status(404).json({ message: 'User not found' });
}
res.status(200).json({ preferences: user.notificationPreferences });
} catch (error) {
logger.error('Get Notification Preferences Error:', error);
res.status(500).json({ message: 'Server Error' });
}
};
/**
* The rest of your controller methods (getUserLogs, startMonitoring, stopMonitoring, getAnalytics) remain unchanged.
*/
Explanation of Enhancements:
-
Notification Preferences Handling:
- Why? Empower users to control how they receive notifications, improving user satisfaction and engagement.
- How? Add routes and controller methods to update and retrieve user notification preferences, which the
emailService can utilize to tailor notifications.
-
Batching Notifications Based on Frequency:
- Why? Different users have different preferences for notification frequency, allowing for personalized experiences.
- How? Implement logic within the
monitorService and emailService to aggregate notifications based on user-specified frequencies (immediate, daily, weekly).
-
Additional Notification Channels:
- Why? Diversify the ways users can receive notifications to ensure they are promptly informed.
- How? Extend the
emailService to include methods for sending notifications via Slack, SMS, etc., based on user preferences.
6. Final Touches & Best Practices
A. Middleware for Notification Preferences
Ensure that user preferences are respected across the monitoring and email services by creating middleware or extending existing services to check user preferences before sending notifications.
B. Security Enhancements
- Environment Variables: Ensure sensitive data like API keys and credentials are stored securely using environment variables.
- Input Validation: Continue using Zod for robust input validation to prevent injection attacks and ensure data integrity.
- Rate Limiting: Implement rate limiting on routes to prevent abuse and ensure service stability.
C. Documentation & Maintenance
- Inline Documentation: Maintain clear and concise comments within your codebase for ease of understanding and maintenance.
- API Documentation: Use tools like Swagger to document your API endpoints, making it easier for developers to integrate and use your services.
- Logging: Ensure comprehensive logging for monitoring system health, debugging, and forensic analysis.
D. Testing
- Unit Tests: Implement unit tests for critical functions within your services to ensure reliability.
- Integration Tests: Test the interactions between different services (e.g., monitoring triggering email notifications) to ensure seamless operation.
- Load Testing: Perform load testing to ensure your monitoring and notification services can handle high volumes gracefully.
Conclusion
By implementing the above enhancements, your notification email service and monitoring system will become more intelligent, adaptive, and efficient. These improvements not only optimize resource usage but also provide a better user experience through personalized and timely notifications. Additionally, optimizing the screenshot service ensures that system resources are utilized effectively, reducing costs and improving performance.
Remember to thoroughly test each enhancement in a staging environment before deploying to production to ensure stability and reliability.
If you have any further questions or need assistance with specific implementations, feel free to ask!