Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Calculate network/device uptime statistics over any specified period #3586

Draft
wants to merge 5 commits into
base: staging
Choose a base branch
from

Conversation

Baalmart
Copy link
Contributor

@Baalmart Baalmart commented Oct 6, 2024

Description

calculate network/device uptime statistics over the specified period

Changes Made

  • startDate and endDate. These are used to filter the devices and their status history within the specified date range. The function calculates the uptime based on the status changes within this period.
  • timeFrame:This parameter allows for aggregating results by daily, weekly, or monthly periods. If specified, the results are grouped according to the chosen time frame.
  • Uptime Calculation: The function now calculates the actual uptime for each device based on its status history. It considers the time periods when the device was online within the specified date range.
  • Online/Offline Classification: Devices are now classified as online or offline based on their uptime percentage (>= 50% is considered online).
  • Aggregation: The results are still grouped by network, but now include more detailed uptime statistics. If a time frame is specified, an additional grouping is applied to show trends over time.
  • Added new appropriate unit tests for associated models, utils, controllers and route files.

Testing

  • Tested locally
  • Tested against staging environment
  • Relevant tests passed: [List test names]

Affected Services

  • Which services were modified:
    • Device Registry

Endpoints Ready for Testing

  • New endpoints ready for testing:
    • Endpoint 1
    • Endpoint 2
    • Other...

API Documentation Updated?

  • Yes, API documentation was updated
  • No, API documentation does not need updating

Additional Notes

This functionality or feature provides more comprehensive and flexible uptime statistics. It allows for analysing device performance over specific time periods and can show trends when using the timeFrame parameter.

Summary by CodeRabbit

  • New Features
    • Introduced a new method to calculate detailed uptime statistics for devices, allowing users to analyze device performance based on various parameters such as device IDs, date ranges, and network filters.
  • Documentation
    • Added usage examples for the new uptime statistics method to enhance user understanding.

Copy link
Contributor

coderabbitai bot commented Oct 6, 2024

Important

Review skipped

Draft detected.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

📝 Walkthrough
📝 Walkthrough

Walkthrough

The pull request introduces a new static method getUptimeStatistics to the deviceSchema in Device.js. This method calculates uptime statistics for devices, utilizing parameters such as device IDs, date ranges, time frames, and network filters. It constructs an aggregation pipeline with multiple stages to filter, unwind, group, and project device data, ultimately providing detailed uptime analysis.

Changes

File Path Change Summary
src/device-registry/models/Device.js Added a new static method async getUptimeStatistics for calculating device uptime statistics based on various parameters.

Possibly related PRs

Suggested labels

ready for review

Suggested reviewers

  • BenjaminSsempala
  • Codebmk

🎉 In the realm of devices, a method shines bright,
getUptimeStatistics, a beacon of light.
With filters and stages, it weaves through the data,
To count and to measure, it’s truly a beta!
So here’s to the uptime, may it always be high,
With devices in sync, let our stats touch the sky! 🌟


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@Baalmart Baalmart marked this pull request as draft October 6, 2024 07:24
@Baalmart Baalmart changed the title calculate network/device uptime statistics over the specified period [Device Registry] calculate network/device uptime statistics over the specified period Oct 6, 2024
Copy link

codecov bot commented Oct 6, 2024

Codecov Report

Attention: Patch coverage is 3.50877% with 55 lines in your changes missing coverage. Please review.

Project coverage is 26.98%. Comparing base (ede7c21) to head (faa5eab).
Report is 7 commits behind head on staging.

Files with missing lines Patch % Lines
src/device-registry/controllers/create-device.js 0.00% 21 Missing ⚠️
src/device-registry/models/Device.js 4.54% 21 Missing ⚠️
src/device-registry/utils/create-device.js 0.00% 9 Missing ⚠️
src/device-registry/routes/v2/devices.js 20.00% 4 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@             Coverage Diff             @@
##           staging    #3586      +/-   ##
===========================================
- Coverage    27.04%   26.98%   -0.07%     
===========================================
  Files          146      146              
  Lines        21340    21397      +57     
  Branches       274      274              
===========================================
+ Hits          5772     5774       +2     
- Misses       15568    15623      +55     
Files with missing lines Coverage Δ
src/device-registry/routes/v2/devices.js 27.13% <20.00%> (-0.29%) ⬇️
src/device-registry/utils/create-device.js 32.40% <0.00%> (-0.93%) ⬇️
src/device-registry/controllers/create-device.js 3.20% <0.00%> (-0.18%) ⬇️
src/device-registry/models/Device.js 14.48% <4.54%> (-1.14%) ⬇️

Copy link
Contributor

github-actions bot commented Oct 6, 2024

Device registry changes in this PR available for preview here

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 6

🧹 Outside diff range and nitpick comments (1)
src/device-registry/models/Device.js (1)

729-983: Consider adding unit tests for the new method

The getUptimeStatistics method adds significant functionality to the codebase. Adding unit tests will ensure the method works as intended and will help catch any future regressions.

Would you like assistance in creating unit tests for this method?

🧰 Tools
🪛 Biome

[error] 917-917: Do not add then to an object.

(lint/suspicious/noThenProperty)


[error] 922-922: Do not add then to an object.

(lint/suspicious/noThenProperty)


[error] 926-926: Do not add then to an object.

(lint/suspicious/noThenProperty)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 8bf375d and bc55da1.

📒 Files selected for processing (1)
  • src/device-registry/models/Device.js (1 hunks)
🧰 Additional context used
🪛 Biome
src/device-registry/models/Device.js

[error] 917-917: Do not add then to an object.

(lint/suspicious/noThenProperty)


[error] 922-922: Do not add then to an object.

(lint/suspicious/noThenProperty)


[error] 926-926: Do not add then to an object.

(lint/suspicious/noThenProperty)

🔇 Additional comments (1)
src/device-registry/models/Device.js (1)

914-926: Address static analysis errors related to 'then' property

The static analysis tool reports errors on lines 917, 922, and 926 regarding the use of the then property. In the context of MongoDB aggregation pipelines, using case and then within the $switch operator is correct.

🧰 Tools
🪛 Biome

[error] 917-917: Do not add then to an object.

(lint/suspicious/noThenProperty)


[error] 922-922: Do not add then to an object.

(lint/suspicious/noThenProperty)


[error] 926-926: Do not add then to an object.

(lint/suspicious/noThenProperty)

Comment on lines 729 to 735
deviceSchema.statics.getUptimeStatistics = async function({
devices = [],
startDate,
endDate,
timeFrame,
networkFilter,
} = {}) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Add input validation for function parameters

The getUptimeStatistics method accepts parameters like devices, startDate, endDate, timeFrame, and networkFilter without validating them. To enhance robustness, consider adding validation to ensure:

  • startDate and endDate are valid dates and startDate is not after endDate.
  • timeFrame is one of the expected values: "daily", "weekly", or "monthly".

This will prevent potential runtime errors due to invalid inputs.

Comment on lines +749 to +753
matchStage.createdAt = {
$gte: new Date(startDate),
$lte: new Date(endDate),
};
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Handle cases where date ranges are partially provided

Currently, the code checks if both startDate and endDate are provided before adding date range filters. However, users might provide only one of these dates. Consider supporting scenarios where:

  • Only startDate is provided: Filter records from startDate onwards.
  • Only endDate is provided: Filter records up to endDate.

Updating the conditions will make the method more flexible.

Apply this diff to adjust the date range handling:

 // Add date range to match stage if provided
-if (startDate && endDate) {
+if (startDate || endDate) {
   matchStage.createdAt = {
-    $gte: new Date(startDate),
-    $lte: new Date(endDate),
+    ...(startDate && { $gte: new Date(startDate) }),
+    ...(endDate && { $lte: new Date(endDate) }),
   };
 }

Similarly, adjust the status history date range filtering:

 // Match status history within the date range
-if (startDate && endDate) {
+if (startDate || endDate) {
   pipeline.push({
     $match: {
       "statusHistory.timestamp": {
-        $gte: new Date(startDate),
-        $lte: new Date(endDate),
+        ...(startDate && { $gte: new Date(startDate) }),
+        ...(endDate && { $lte: new Date(endDate) }),
       },
     },
   });
 }

Also applies to: 760-770

Comment on lines +739 to +745
const matchStage = {};
if (devices.length > 0) {
matchStage._id = { $in: devices };
}
if (networkFilter) {
matchStage.network = networkFilter;
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Optimize the match stage in the aggregation pipeline

To improve performance, consider moving the initial $match stage after the $unwind of statusHistory if the filters are primarily on statusHistory fields. Additionally, ensure indexes are in place for the fields used in the $match stage to speed up query execution.

Comment on lines +980 to +983
const result = await this.aggregate(pipeline);

return result;
};
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Add error handling for the aggregation pipeline execution

Currently, the aggregation execution does not handle potential errors that may occur during database operations. Wrapping the aggregation call in a try-catch block will allow the method to handle exceptions gracefully and provide meaningful error messages.

Apply this diff to add error handling:

 // Execute the aggregation pipeline
-const result = await this.aggregate(pipeline);
+let result;
+try {
+  result = await this.aggregate(pipeline);
+} catch (error) {
+  logger.error(`Aggregation error: ${error.message}`);
+  throw new Error('Error fetching uptime statistics');
+}

 return result;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const result = await this.aggregate(pipeline);
return result;
};
// Execute the aggregation pipeline
let result;
try {
result = await this.aggregate(pipeline);
} catch (error) {
logger.error(`Aggregation error: ${error.message}`);
throw new Error('Error fetching uptime statistics');
}
return result;
};

Comment on lines +819 to +820
$multiply: [{ $divide: ["$uptime", "$totalTime"] }, 100],
},
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Prevent division by zero in uptime percentage calculation

The calculation of uptimePercentage could result in a division by zero if totalTime is zero. To avoid runtime errors, add a check to ensure totalTime is not zero before performing the division.

Apply this diff to handle cases where totalTime is zero:

 uptimePercentage: {
-  $multiply: [{ $divide: ["$uptime", "$totalTime"] }, 100],
+  $cond: {
+    if: { $eq: ["$totalTime", 0] },
+    then: 0,
+    else: {
+      $multiply: [{ $divide: ["$uptime", "$totalTime"] }, 100],
+    },
+  },
 },
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
$multiply: [{ $divide: ["$uptime", "$totalTime"] }, 100],
},
uptimePercentage: {
$cond: {
if: { $eq: ["$totalTime", 0] },
then: 0,
else: {
$multiply: [{ $divide: ["$uptime", "$totalTime"] }, 100],
},
},
},

Comment on lines 907 to 972
pipeline.push({
$group: {
_id: {
network: "$network",
timeFrame: {
$switch: {
branches: [
{
case: { $eq: [timeFrame, "daily"] },
then: {
$dateToString: { format: "%Y-%m-%d", date: "$$NOW" },
},
},
{
case: { $eq: [timeFrame, "weekly"] },
then: { $dateToString: { format: "%Y-W%V", date: "$$NOW" } },
},
{
case: { $eq: [timeFrame, "monthly"] },
then: { $dateToString: { format: "%Y-%m", date: "$$NOW" } },
},
],
default: "all",
},
},
},
network: { $first: "$network" },
totalDevices: { $sum: "$totalDevices" },
avgUptimePercentage: { $avg: "$avgUptimePercentage" },
onlineDevices: { $sum: "$onlineDevices" },
offlineDevices: { $sum: "$offlineDevices" },
onlinePercentage: { $avg: "$onlinePercentage" },
offlinePercentage: { $avg: "$offlinePercentage" },
onlineDeviceNames: { $addToSet: "$onlineDeviceNames" },
offlineDeviceNames: { $addToSet: "$offlineDeviceNames" },
},
});

// Flatten device names arrays
pipeline.push({
$project: {
network: 1,
timeFrame: "$_id.timeFrame",
totalDevices: 1,
avgUptimePercentage: 1,
onlineDevices: 1,
offlineDevices: 1,
onlinePercentage: 1,
offlinePercentage: 1,
onlineDeviceNames: {
$reduce: {
input: "$onlineDeviceNames",
initialValue: [],
in: { $setUnion: ["$$value", "$$this"] },
},
},
offlineDeviceNames: {
$reduce: {
input: "$offlineDeviceNames",
initialValue: [],
in: { $setUnion: ["$$value", "$$this"] },
},
},
},
});
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Refine the time frame grouping logic

The use of $$NOW in the $dateToString expressions will result in all documents being grouped under the current date, week, or month rather than the dates from the data. To accurately group data based on the statusHistory.timestamp, consider using the timestamp from the records.

Apply this diff to correct the time frame grouping:

 timeFrame: {
   $switch: {
     branches: [
       {
         case: { $eq: [timeFrame, "daily"] },
         then: {
-          $dateToString: { format: "%Y-%m-%d", date: "$$NOW" },
+          $dateToString: { format: "%Y-%m-%d", date: "$statusHistory.timestamp" },
         },
       },
       {
         case: { $eq: [timeFrame, "weekly"] },
         then: {
-          $dateToString: { format: "%Y-W%V", date: "$$NOW" },
+          $dateToString: { format: "%Y-W%V", date: "$statusHistory.timestamp" },
         },
       },
       {
         case: { $eq: [timeFrame, "monthly"] },
         then: {
-          $dateToString: { format: "%Y-%m", date: "$$NOW" },
+          $dateToString: { format: "%Y-%m", date: "$statusHistory.timestamp" },
         },
       },
     ],
     default: "all",
   },
 },

This change ensures that the grouping is based on the actual timestamps of the status history.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
pipeline.push({
$group: {
_id: {
network: "$network",
timeFrame: {
$switch: {
branches: [
{
case: { $eq: [timeFrame, "daily"] },
then: {
$dateToString: { format: "%Y-%m-%d", date: "$$NOW" },
},
},
{
case: { $eq: [timeFrame, "weekly"] },
then: { $dateToString: { format: "%Y-W%V", date: "$$NOW" } },
},
{
case: { $eq: [timeFrame, "monthly"] },
then: { $dateToString: { format: "%Y-%m", date: "$$NOW" } },
},
],
default: "all",
},
},
},
network: { $first: "$network" },
totalDevices: { $sum: "$totalDevices" },
avgUptimePercentage: { $avg: "$avgUptimePercentage" },
onlineDevices: { $sum: "$onlineDevices" },
offlineDevices: { $sum: "$offlineDevices" },
onlinePercentage: { $avg: "$onlinePercentage" },
offlinePercentage: { $avg: "$offlinePercentage" },
onlineDeviceNames: { $addToSet: "$onlineDeviceNames" },
offlineDeviceNames: { $addToSet: "$offlineDeviceNames" },
},
});
// Flatten device names arrays
pipeline.push({
$project: {
network: 1,
timeFrame: "$_id.timeFrame",
totalDevices: 1,
avgUptimePercentage: 1,
onlineDevices: 1,
offlineDevices: 1,
onlinePercentage: 1,
offlinePercentage: 1,
onlineDeviceNames: {
$reduce: {
input: "$onlineDeviceNames",
initialValue: [],
in: { $setUnion: ["$$value", "$$this"] },
},
},
offlineDeviceNames: {
$reduce: {
input: "$offlineDeviceNames",
initialValue: [],
in: { $setUnion: ["$$value", "$$this"] },
},
},
},
});
}
pipeline.push({
$group: {
_id: {
network: "$network",
timeFrame: {
$switch: {
branches: [
{
case: { $eq: [timeFrame, "daily"] },
then: {
$dateToString: { format: "%Y-%m-%d", date: "$statusHistory.timestamp" },
},
},
{
case: { $eq: [timeFrame, "weekly"] },
then: { $dateToString: { format: "%Y-W%V", date: "$statusHistory.timestamp" } },
},
{
case: { $eq: [timeFrame, "monthly"] },
then: { $dateToString: { format: "%Y-%m", date: "$statusHistory.timestamp" } },
},
],
default: "all",
},
},
},
network: { $first: "$network" },
totalDevices: { $sum: "$totalDevices" },
avgUptimePercentage: { $avg: "$avgUptimePercentage" },
onlineDevices: { $sum: "$onlineDevices" },
offlineDevices: { $sum: "$offlineDevices" },
onlinePercentage: { $avg: "$onlinePercentage" },
offlinePercentage: { $avg: "$offlinePercentage" },
onlineDeviceNames: { $addToSet: "$onlineDeviceNames" },
offlineDeviceNames: { $addToSet: "$offlineDeviceNames" },
},
});
// Flatten device names arrays
pipeline.push({
$project: {
network: 1,
timeFrame: "$_id.timeFrame",
totalDevices: 1,
avgUptimePercentage: 1,
onlineDevices: 1,
offlineDevices: 1,
onlinePercentage: 1,
offlinePercentage: 1,
onlineDeviceNames: {
$reduce: {
input: "$onlineDeviceNames",
initialValue: [],
in: { $setUnion: ["$$value", "$$this"] },
},
},
offlineDeviceNames: {
$reduce: {
input: "$offlineDeviceNames",
initialValue: [],
in: { $setUnion: ["$$value", "$$this"] },
},
},
},
});
}
🧰 Tools
🪛 Biome

[error] 917-917: Do not add then to an object.

(lint/suspicious/noThenProperty)


[error] 922-922: Do not add then to an object.

(lint/suspicious/noThenProperty)


[error] 926-926: Do not add then to an object.

(lint/suspicious/noThenProperty)

Copy link
Contributor

github-actions bot commented Oct 6, 2024

Device registry changes in this PR available for preview here

Copy link
Contributor

Device registry changes in this PR available for preview here

Copy link
Contributor

Device registry changes in this PR available for preview here

@Baalmart Baalmart changed the title [Device Registry] calculate network/device uptime statistics over the specified period Calculate network/device uptime statistics over the specified period Oct 15, 2024
@Baalmart Baalmart changed the title Calculate network/device uptime statistics over the specified period Calculate network/device uptime statistics over any specified period Oct 15, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant