make the analytics advanced include all type of data anlytics like graph table pir and everyttpe to cover all data analytic need and indepth filter for everything like make it super awsome and good include everything make it best and perfect and extensive
""""
const { z } = require('zod');
const mongoose = require('mongoose');
const User = require('../models/User');
const Log = require('../models/Log');
const monitorService = require('../services/monitorService');
const logger = require('../utils/logger');
// Schema for analytics
const analyticsSchema = z.object({
startDate: z
.string()
.optional()
.refine((date) => !date || !isNaN(Date.parse(date)), {
message: 'startDate must be a valid ISO date string',
}),
endDate: z
.string()
.optional()
.refine((date) => !date || !isNaN(Date.parse(date)), {
message: 'endDate must be a valid ISO date string',
}),
urls: z
.string()
.optional()
.refine(
(urls) => {
if (!urls) return true;
const urlsArray = urls.split(',');
return urlsArray.every((url) => {
try {
new URL(url.trim());
return true;
} catch {
return false;
}
});
},
{ message: 'urls must be a comma-separated list of valid URLs' }
),
statusCodes: z
.string()
.optional()
.refine(
(codes) => {
if (!codes) return true;
const codesArray = codes.split(',');
return codesArray.every((code) => /^\d+/.test(code.trim()));
},
{ message: 'statusCodes must be a comma-separated list of numbers' }
),
groupBy: z
.enum(['day', 'week', 'month'])
.optional()
.default('day'),
page: z
.string()
.optional()
.refine((val) => !val || /^\d+/.test(val), {
message: 'page must be a positive integer',
})
.default('1'),
limit: z
.string()
.optional()
.refine((val) => !val || (/^\d+$/.test(val) && parseInt(val) <= 1000), {
message: 'limit must be an integer between 1 and 1000',
})
.default('100'),
});
POST /api/user/monitor/start
*/
exports.startMonitoring = async (req, res) => {
try {
const user = await User.findById(req.user.id);
code
if (!user) {
return res.status(404).json({ message: 'User not found' });
}
if (!user.verified) {
return res.status(403).json({ message: 'Email not verified. Please verify your email to start monitoring.' });
}
if (!user.listOfUrls || user.listOfUrls.length === 0) {
return res.status(400).json({ message: 'No URLs configured for monitoring. Please add URLs to your settings.' });
}
// Check if monitoring is already active
const isMonitoringActive = monitorService.isMonitoringActive(user._id.toString());
if (isMonitoringActive) {
return res.status(400).json({ message: 'Monitoring is already active for your account.' });
}
// Start monitoring
monitorService.startMonitoring(user);
res.status(200).json({ message: 'Monitoring started successfully.' });
POST /api/user/monitor/stop
*/
exports.stopMonitoring = async (req, res) => {
try {
const user = await User.findById(req.user.id);
code
if (!user) {
return res.status(404).json({ message: 'User not found' });
}
// Check if monitoring is active
const isMonitoringActive = monitorService.isMonitoringActive(user._id.toString());
if (!isMonitoringActive) {
return res.status(400).json({ message: 'Monitoring is not active for your account.' });
}
// Stop monitoring
monitorService.stopMonitoring(user);
res.status(200).json({ message: 'Monitoring stopped successfully.' });
// Helper: Convert time period to cron expression
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 cron jobs and intervals
const userJobs = new Map();
const userIntervals = new Map();
// In-memory storage for notification timers
// Structure: { userId: { url: timeoutObject } }
const notificationTimers = new Map();
/**
Function to perform checks on user's URLs.
Logs all status codes, handles notifications for non-2xx responses,
and captures screenshots for error notifications.
@param {Object} user - The user object containing monitoring details.
*/
const performChecks = async (user) => {
for (const url of user.listOfUrls) {
try {
const response = await axios.get(url, { timeout: 10000 });
const statusCode = response.status;
code
// Log successful check with no screenshot
await logStatus(user._id, url, statusCode, "None");
if (statusCode < 200 || statusCode >= 300) {
logger.warn(`URL check failed for ${url} with status code ${statusCode}`);
if (isNotificationPending(user._id.toString(), url)) {
logger.info(`Notification already pending for ${url}. Skipping email.`);
continue;
}
const screenshotUrl = await screenshotService.takeScreenshot(url);
await emailService.sendErrorNotification(user.email, url, statusCode, screenshotUrl);
await logStatus(user._id, url, statusCode, screenshotUrl); // Log with screenshot URL
setNotificationTimer(user._id.toString(), url, 10 * 60 * 1000); // 10 minutes
} else {
logger.info(`URL check successful for ${url} with status code ${statusCode}`);
clearNotificationTimer(user._id.toString(), url);
}
} catch (error) {
let statusCode = error.response ? error.response.status : 0;
let screenshotUrl = 'None';
if (statusCode !== 0) {
try {
screenshotUrl = await screenshotService.takeScreenshot(url);
logger.info(`Screenshot captured for ${url}`);
} catch (screenshotError) {
logger.error(`Failed to take screenshot for ${url}: ${screenshotError.message}`);
}
}
await logStatus(user._id, url, statusCode, screenshotUrl); // Log with or without screenshot
if (!isNotificationPending(user._id.toString(), url)) {
await emailService.sendErrorNotification(user.email, url, statusCode, screenshotUrl);
setNotificationTimer(user._id.toString(), url, 10 * 60 * 1000);
}
}
}
};
/**
Logs the status of the URL check to the database.
@param {ObjectId} userId - The ID of the user.
@param {string} url - The URL that was checked.
@param {number} statusCode - The HTTP status code returned.
*/
const logStatus = async (userId, url, statusCode, screenshotUrl) => {
try {
const log = new Log({
user: userId,
url,
statusCode,
screenshotUrl,
timestamp: new Date(),
});
await log.save();
logger.info(Logged status for ${url} with status code ${statusCode} and screenshot URL: ${screenshotUrl});
} catch (logError) {
logger.error(Failed to log status for ${url}: ${logError.message});
}
};
// Function to start monitoring for a user
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.');
}
code
if (!user.listOfUrls || user.listOfUrls.length === 0) return;
// Clear existing jobs or intervals to prevent duplicates
stopMonitoring(user);
if (user.timePeriod === '30s') {
// node-cron doesn't support seconds intervals, use setInterval
const interval = setInterval(() => {
performChecks(user);
}, 30000); // 30 seconds
userIntervals.set(user._id.toString(), interval);
logger.info(`Started 30s interval monitoring for user ${user.username}`);
} else {
const cronExpression = timePeriodToCron(user.timePeriod);
if (!cronExpression) return;
const job = cron.schedule(cronExpression, () => {
performChecks(user);
}, {
scheduled: true,
timezone: "UTC",
});
userJobs.set(user._id.toString(), job);
logger.info(`Started cron job (${cronExpression}) monitoring for user ${user.username}`);
}
};
// Function to stop monitoring for a user
const stopMonitoring = (user) => {
const userId = user._id.toString();
code
if (userJobs.has(userId)) {
const job = userJobs.get(userId);
job.stop();
userJobs.delete(userId);
logger.info(`Stopped cron job monitoring for user ${user.username}`);
}
if (userIntervals.has(userId)) {
clearInterval(userIntervals.get(userId));
userIntervals.delete(userId);
logger.info(`Stopped interval monitoring for user ${user.username}`);
}
// Also clear any pending notification timers
if (notificationTimers.has(userId)) {
Object.values(notificationTimers.get(userId)).forEach(timeout => clearTimeout(timeout));
notificationTimers.delete(userId);
logger.info(`Cleared notification timers for user ${user.username}`);
}
};
// Function to restart monitoring (used when settings are updated)
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.');
}
startMonitoring(user);
};
// Function to check if monitoring is active for a user
const isMonitoringActive = (userId) => {
return userJobs.has(userId) || userIntervals.has(userId);
};
// Function to check if a notification is pending for a URL
const isNotificationPending = (userId, url) => {
if (!notificationTimers.has(userId)) return false;
const userTimers = notificationTimers.get(userId);
return userTimers.hasOwnProperty(url);
};
// Function to set a notification timer for a URL
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 notificationTimers.get(userId)[url];
logger.info(Notification timer expired for ${url});
// Optionally, notify the user that monitoring is active again
// Example:
// emailService.sendRecoveryNotification(user.email, url);
}
}, timeout);
};
// Function to clear notification timer (called when URL recovers)
const clearNotificationTimer = (userId, url) => {
if (!notificationTimers.has(userId)) return;
const userTimers = notificationTimers.get(userId);
if (userTimers.hasOwnProperty(url)) {
clearTimeout(userTimers[url]);
delete userTimers[url];
logger.info(Cleared notification timer for ${url});
}
};
// Initialize monitoring for existing users on server start
const initializeMonitoring = async () => {
const User = require('../models/User'); // Avoid circular dependency
try {
const users = await User.find({ verified: true }); // Only initialize for verified users
users.forEach(user => {
startMonitoring(user);
});
logger.info('Initialized monitoring for existing verified users');
} catch (error) {
logger.error('Error initializing monitoring:', error);
}
};
// Function to take a screenshot, compress, upload to Cloudinary, and return the URL
const takeScreenshot = async (url) => {
try {
const browser = await initBrowser();
const page = await browser.newPage();
code
// 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}`);
// Compress the image using Sharp
const compressedBuffer = await sharp(screenshotBuffer)
.jpeg({ quality: 20 }) // Adjust quality as needed (30 for high compression)
.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}`; // Removed extension
// Upload the compressed image to Cloudinary using a single upload_stream
const uploadPromise = 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', // Specify the format to ensure consistent extension
},
(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);
});
const cloudinaryUrl = await uploadPromise;
return cloudinaryUrl; // Return the Cloudinary URL
Enhancing your analytics to be comprehensive, advanced, and feature-rich involves expanding the current functionality to include a variety of metrics, visualizations, and in-depth filters. Below, I will guide you through the necessary enhancements to your existing codebase to achieve a super awesome, extensive, and perfect analytics system that covers all your data analytics needs.
Table of Contents
Overview of Current Analytics
Proposed Enhancements
Implementing the Enhancements
1. Extending the Log Model
2. Updating the Analytics Schema
3. Enhancing the getAnalytics Controller
4. Optimizing Database Indexes
5. Frontend Considerations
Final Code Snippets
Conclusion
1. Overview of Current Analytics
Your current getAnalytics function provides a solid foundation with the following features:
Total Checks: Total number of uptime checks performed.
Successful Checks: Number of checks with 2xx status codes.
Failed Checks: Number of checks with 4xx and 5xx status codes.
Status Code Distribution: Breakdown of different status codes received.
Uptime Percentage per URL: Success rate for each monitored URL.
Checks Over Time: Aggregated checks grouped by day, week, or month.
Recent Issues: Latest failed checks with details.
While comprehensive, there's room to make this analytics module even more robust and insightful.
2. Proposed Enhancements
To elevate your analytics to an advanced level, consider incorporating the following features:
Additional Metrics:
Average Response Time: Measure the average time taken for responses per URL.
Response Time Distribution: Categorize response times into buckets for analysis.
Peak Traffic Times: Identify when the most checks occur.
Top Slowest URLs: Highlight URLs with the highest average response times.
Trend Analysis: Analyze trends over extended periods.
Advanced Filtering:
Filter analytics based on response time ranges.
Combine multiple filters (e.g., specific URLs with high response times).
Comprehensive Visualizations:
Data structures that support various graph types like line charts, bar charts, pie charts, and tables.
Export Functionality:
Allow users to export analytics data in formats like CSV or integrate with BI tools.
Real-time Analytics:
Implement real-time data streaming for instant insights using WebSockets or similar technologies.
Performance Optimizations:
Enhance database indexing for faster query execution.
Implement caching strategies for frequently accessed analytics data.
3. Implementing the Enhancements
Below, I outline the steps to implement the proposed enhancements.
1. Extending the Log Model
To support additional metrics like response time, you'll need to extend your Log model.
Response Time Capture: Measures the time before and after the HTTP request to calculate responseTime.
Storing Response Time: Passes the responseTime to the logStatus function for storage.
2. Updating the Analytics Schema
Enhance the analyticsSchema to include new filters for comprehensive analytics.
Updated Analytics Schema in Controller:
javascript
// Schema for analytics
const analyticsSchema = z.object({
startDate: z
.string()
.optional()
.refine((date) => !date || !isNaN(Date.parse(date)), {
message: 'startDate must be a valid ISO date string',
}),
endDate: z
.string()
.optional()
.refine((date) => !date || !isNaN(Date.parse(date)), {
message: 'endDate must be a valid ISO date string',
}),
urls: z
.string()
.optional()
.refine(
(urls) => {
if (!urls) return true;
const urlsArray = urls.split(',');
return urlsArray.every((url) => {
try {
new URL(url.trim());
return true;
} catch {
return false;
}
});
},
{ message: 'urls must be a comma-separated list of valid URLs' }
),
statusCodes: z
.string()
.optional()
.refine(
(codes) => {
if (!codes) return true;
const codesArray = codes.split(',');
return codesArray.every((code) => /^\d+$/.test(code.trim()));
},
{ message: 'statusCodes must be a comma-separated list of numbers' }
),
minResponseTime: z
.string()
.optional()
.refine(
(rt) => !rt || /^\d+$/.test(rt),
{ message: 'minResponseTime must be a number representing milliseconds' }
),
maxResponseTime: z
.string()
.optional()
.refine(
(rt) => !rt || /^\d+$/.test(rt),
{ message: 'maxResponseTime must be a number representing milliseconds' }
),
groupBy: z
.enum(['hour', 'day', 'week', 'month'])
.optional()
.default('day'),
page: z
.string()
.optional()
.refine((val) => !val || /^\d+$/.test(val), {
message: 'page must be a positive integer',
})
.default('1'),
limit: z
.string()
.optional()
.refine((val) => !val || (/^\d+$/.test(val) && parseInt(val) <= 1000), {
message: 'limit must be an integer between 1 and 1000',
})
.default('100'),
});
Explanation:
minResponseTime & maxResponseTime: Allow filtering logs based on response time thresholds.
groupBy Options: Added 'hour' for more granular time-based grouping.
3. Enhancing the getAnalytics Controller
Implement enhanced aggregation pipelines to support the new metrics and filters.
Enhanced getAnalytics Function:
javascript
Explanation of Enhancements:
Additional Metrics:
Average Response Time: Calculated in checksOverTime aggregation and included in the response.
Response Time Distribution: Categorized into buckets (e.g., 0-100ms, 100-300ms, etc.) with counts and average response times.
Top Slowest URLs: Identifies top 10 URLs with the highest average response times.
Advanced Filtering:
Response Time Filters: minResponseTime and maxResponseTime allow users to filter logs based on response times.
Users can combine multiple filters (e.g., specific URLs with high response times within a date range).
Comprehensive Visualizations:
The structured response includes data suitable for various graph types on the frontend.
Helper Functions:
formatPeriod: Formats the time period based on the groupBy parameter.
formatResponseTimeRange: Converts numerical ranges into readable string formats.
4. Optimizing Database Indexes
To ensure that the enhanced analytics queries perform efficiently, optimize your MongoDB indexes.
Compound Indexes: Adding compound indexes involving responseTime improves the performance of queries filtering by response times along with other parameters.
5. Frontend Considerations
While the focus here is on backend enhancements, it's essential to ensure that the frontend can effectively visualize the enriched analytics data. Here are suggestions for frontend implementations:
Charts and Graphs:
Line Charts: Display checksOverTime and averageResponseTime trends.
Bar Charts: Visualize statusCodeDistribution and responseTimeDistribution.
Pie Charts: Show uptimePerUrl percentages.
Tables: Present recentIssues and topSlowestUrls with sortable columns.
Interactive Filters:
Allow users to dynamically apply filters like date ranges, specific URLs, status codes, and response time thresholds.
Utilize dropdowns, sliders, and multi-select inputs for an enhanced user experience.
Export Options:
Provide buttons to export analytics data as CSV or PDF.
Integrate with third-party BI tools like Tableau or Power BI using APIs or data connectors.
Real-time Updates:
Implement WebSockets to push real-time analytics updates to the dashboard.
Use libraries like Socket.IO for seamless real-time data broadcasting.
4. Final Code Snippets
Below are the complete updated code snippets incorporating all the enhancements discussed.
b. Controller Enhancements (controllers/userController.js)
javascript
c. Enhancing performChecks in services/monitorService.js
Ensure responseTime is captured during checks.
javascript
const performChecks = async (user) => {
for (const url of user.listOfUrls) {
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(user._id, 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(user._id.toString(), 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(user._id, url, statusCode, screenshotUrl, responseTime);
if (!isNotificationPending(user._id.toString(), url)) {
await emailService.sendErrorNotification(user.email, url, statusCode, screenshotUrl);
setNotificationTimer(user._id.toString(), url, 10 * 60 * 1000); // 10 minutes
}
}
}
};
/**
* Handles failed checks by sending notifications and logging.
*/
const handleFailure = async (user, url, statusCode) => {
logger.warn(`URL check failed for ${url} with status code ${statusCode}`);
if (isNotificationPending(user._id.toString(), 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);
await logStatus(user._id, url, statusCode, screenshotUrl);
} catch (error) {
logger.error(`Failed to handle failure for ${url}: ${error.message}`);
}
setNotificationTimer(user._id.toString(), url, 10 * 60 * 1000); // 10 minutes
};
Explanation:
Modular Handling: Extracted failure handling into a separate handleFailure function for cleaner code.
Response Time Tracking: Ensures that responseTime is captured regardless of success or failure.
5. Conclusion
By implementing the enhancements outlined above, your analytics system will:
Provide Comprehensive Metrics: Including response time analytics and top slowest URLs.
Support Advanced Filtering: Allowing users to drill down into the data based on multiple criteria.
Facilitate Diverse Visualizations: Enabling the frontend to present data in various insightful formats.
Ensure Optimal Performance: Through strategic database indexing and efficient aggregation pipelines.
These improvements will make your analytics module not only advanced but also indispensable for users seeking in-depth insights into their monitored URLs. Additionally, by following best practices in code organization and optimization, the system will remain scalable and maintainable as your user base grows.
Feel free to integrate these snippets into your codebase, test thoroughly, and adjust configurations like boundaries in response time distributions to best fit your specific use case.