Skip to content

Conversation

Teebor-Choka
Copy link
Contributor

@Teebor-Choka Teebor-Choka commented Nov 22, 2024

Previously the peers were all purged on DB start. This PR adds a new functionality, whereby the most recent records (last record update within the <5mins window) will be kept in the database, to allow orchestrated nodes (K8s, docker...) to retain parts of recent network knowledge after restart.

The most significant changes include the addition of a new configuration option for peer database persistence, updates to the database schema, and new tests to verify the correct behavior of peer cleanup on restarts.

Configuration Changes:

  • Added HOPR_INTERNAL_DB_PEERS_PERSISTENCE_AFTER_RESTART_IN_SECONDS configuration option to specify the cutoff duration for retaining peers in the database after a restart.
  • Defined a default value for HOPR_INTERNAL_DB_PEERS_PERSISTENCE_AFTER_RESTART_IN_SECONDS in db/sql/src/db.rs.

Dependency Updates:

  • Added hopr-platform as a dependency in db/sql/Cargo.toml.

Database Logic Updates:

  • Updated the peer cleanup logic in db/sql/src/db.rs to use the new configuration option and remove peers not seen within the specified duration.

Testing Enhancements:

  • Renamed the test function to peers_without_any_recent_updates_should_be_discarded_on_restarts for clarity.
  • Added a new test peers_with_a_recent_update_should_be_retained_in_the_database to ensure that peers with recent updates are not removed during the cleanup process.

@Teebor-Choka Teebor-Choka added this to the 2.2.0-rc.1 milestone Nov 22, 2024
@Teebor-Choka Teebor-Choka requested a review from a team November 22, 2024 08:41
@Teebor-Choka Teebor-Choka self-assigned this Nov 22, 2024
Copy link
Contributor

coderabbitai bot commented Nov 22, 2024

📝 Walkthrough
📝 Walkthrough

Walkthrough

The pull request introduces several changes across multiple files. A new environment variable, HOPR_INTERNAL_DB_PEERS_PERSISTENCE_AFTER_RESTART_IN_SECONDS, is added to the README.md, along with minor text corrections. The Cargo.toml file for the hopr-db-sql package now includes a dependency on hopr-platform. In db.rs, a constant for the default persistence duration is introduced, and the logic for deleting peers is updated. Additionally, test functions are renamed and a new test is added to validate peer retention after updates.

Changes

File Change Summary
README.md - Added environment variable HOPR_INTERNAL_DB_PEERS_PERSISTENCE_AFTER_RESTART_IN_SECONDS.
- Corrected spelling errors in the text.
db/sql/Cargo.toml - Updated version from 0.8.1 to 0.8.2.
- Added dependency hopr-platform = { workspace = true }.
db/sql/src/db.rs - Added constant pub const HOPR_INTERNAL_DB_PEERS_PERSISTENCE_AFTER_RESTART_IN_SECONDS: u64.
- Renamed test function test_peer_cleanup_on_database_start to peers_without_any_recent_updates_should_be_discarded_on_restarts.
- Added new test function peers_with_a_recent_update_should_be_retained_in_the_database.

Possibly related PRs

Suggested labels

bug, testing

Suggested reviewers

  • esterlus
  • NumberFour8
  • tolbrino

📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 13579fb and 7acd5fb.

📒 Files selected for processing (1)
  • db/sql/src/db.rs (5 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • db/sql/src/db.rs

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.

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.

@Teebor-Choka Teebor-Choka marked this pull request as ready for review November 22, 2024 08:41
@github-actions github-actions bot added the dependencies Pull requests that update a dependency file label Nov 22, 2024
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: 1

🧹 Outside diff range and nitpick comments (4)
db/sql/src/db.rs (2)

Line range hint 237-272: Test could be more comprehensive

While the test verifies that old peers are discarded, it could be improved by:

  1. Explicitly setting the environment variable to test configuration
  2. Verifying the exact cleanup conditions

Consider enhancing the test:

     async fn peers_without_any_recent_updates_should_be_discarded_on_restarts() -> anyhow::Result<()> {
+        std::env::set_var(
+            "HOPR_DEFAULT_PEERS_DB_PERSISTENCE_AFTER_RESTART_IN_SECONDS",
+            "300" // 5 minutes
+        );
+
         let random_filename: String = rand::thread_rng()
             .sample_iter(&Alphanumeric)
             .take(15)
             .map(char::from)
             .collect();
         let random_tmp_file = format!("/tmp/{random_filename}.sqlite");

         let peer_id: PeerId = OffchainKeypair::random().public().into();
         let ma_1: Multiaddr = format!("/ip4/127.0.0.1/tcp/10000/p2p/{peer_id}").parse()?;
         let ma_2: Multiaddr = format!("/ip4/127.0.0.1/tcp/10002/p2p/{peer_id}").parse()?;

         let path = std::path::Path::new(&random_tmp_file);

         {
             let db = HoprDb::new(&path, ChainKeypair::random(), crate::db::HoprDbConfig::default()).await?;

+            // Add peer with last_seen more than 5 minutes ago
+            let old_time = std::time::SystemTime::now() - std::time::Duration::from_secs(360);
             db.add_network_peer(
                 &peer_id,
                 PeerOrigin::IncomingConnection,
                 vec![ma_1.clone(), ma_2.clone()],
                 0.0,
                 25,
-            )
-            .await?;
+            ).await?;
+            
+            db.update_network_peer(hopr_db_api::peers::PeerStatus {
+                last_seen: old_time,
+                // ... other fields ...
+            }).await?;
         }

274-330: Test implementation looks good but could use cleanup

The test thoroughly verifies that recent peers are retained, but there are a few improvements possible:

  1. Common setup code could be extracted
  2. Cleanup of temporary files is missing

Consider adding cleanup and extracting common code:

+    fn setup_test_db() -> (String, PeerId, Multiaddr, Multiaddr) {
+        let random_filename: String = rand::thread_rng()
+            .sample_iter(&Alphanumeric)
+            .take(15)
+            .map(char::from)
+            .collect();
+        let random_tmp_file = format!("/tmp/{random_filename}.sqlite");
+
+        let ofk = OffchainKeypair::random();
+        let peer_id: PeerId = ofk.public().clone().into();
+        let ma_1: Multiaddr = format!("/ip4/127.0.0.1/tcp/10000/p2p/{peer_id}").parse().unwrap();
+        let ma_2: Multiaddr = format!("/ip4/127.0.0.1/tcp/10002/p2p/{peer_id}").parse().unwrap();
+
+        (random_tmp_file, peer_id, ma_1, ma_2)
+    }

     #[async_std::test]
     async fn peers_with_a_recent_update_should_be_retained_in_the_database() -> anyhow::Result<()> {
-        let random_filename: String = rand::thread_rng()
-            .sample_iter(&Alphanumeric)
-            .take(15)
-            .map(char::from)
-            .collect();
-        let random_tmp_file = format!("/tmp/{random_filename}.sqlite");
-
-        let ofk = OffchainKeypair::random();
-        let peer_id: PeerId = ofk.public().clone().into();
-        let ma_1: Multiaddr = format!("/ip4/127.0.0.1/tcp/10000/p2p/{peer_id}").parse()?;
-        let ma_2: Multiaddr = format!("/ip4/127.0.0.1/tcp/10002/p2p/{peer_id}").parse()?;
+        let (random_tmp_file, peer_id, ma_1, ma_2) = setup_test_db();
         let path = std::path::Path::new(&random_tmp_file);

+        defer! {
+            std::fs::remove_file(&random_tmp_file).ok();
+        }

         // ... rest of the test ...
     }
README.md (2)

214-214: Consider adding an example value to the environment variable documentation.

The description is clear, but adding an example value (e.g. "300" for 5 minutes) would make it more user-friendly.

- - `HOPR_DEFAULT_PEERS_DB_PERSISTENCE_AFTER_RESTART_IN_SECONDS` - cutoff duration from now to not retain the peers with older records in the peers database (e.g. after a restart)
+ - `HOPR_DEFAULT_PEERS_DB_PERSISTENCE_AFTER_RESTART_IN_SECONDS` - cutoff duration from now to not retain the peers with older records in the peers database (e.g. after a restart). Example: "300" for 5 minutes

Line range hint 1-24: Fix typos in documentation.

There are two typos that need to be corrected:

- The HOPR project produces multiple artifacts that allow running, maintaining and modiyfing the HOPR node.
+ The HOPR project produces multiple artifacts that allow running, maintaining and modifying the HOPR node.
- hoprd --identity /app/hoprd-db/.hopr-identity --password switzerland --init --announce --host "0.0.0.0:9091" --apiToken <MY_TOKEN> --network doufur
+ hoprd --identity /app/hoprd-db/.hopr-identity --password switzerland --init --announce --host "0.0.0.0:9091" --apiToken <MY_TOKEN> --network dufour
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 72ed6f6 and 3e42fcf.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (3)
  • README.md (1 hunks)
  • db/sql/Cargo.toml (1 hunks)
  • db/sql/src/db.rs (5 hunks)
🔇 Additional comments (3)
db/sql/Cargo.toml (1)

60-60: LGTM! Verify no circular dependencies.

The addition of hopr-platform as a workspace dependency is aligned with the PR objectives for implementing the new peer persistence configuration.

Let's verify there are no circular dependencies introduced:

✅ Verification successful

No circular dependencies detected

The dependency relationship is one-way: hopr-db-sql depends on hopr-platform, but hopr-platform does not depend on hopr-db-sql. This is a valid dependency structure that won't create circular dependencies.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for potential circular dependencies between hopr-db-sql and hopr-platform

# Check if hopr-platform depends on hopr-db-sql
echo "Checking for circular dependencies..."
rg -l "hopr-db-sql.*workspace.*true" $(fd Cargo.toml)

# Check the dependency tree in hopr-platform
fd "Cargo.toml" | grep "platform" | xargs cat | grep "dependencies" -A 20

Length of output: 41201


Script:

#!/bin/bash
# Let's check if hopr-platform depends on hopr-db-sql
rg -p "hopr-db-sql" misc/platform/Cargo.toml

# Also check if there are any other dependencies between these crates
rg -p "hopr-platform.*=.*workspace.*true" db/sql/Cargo.toml
rg -p "hopr-db-sql.*=.*workspace.*true" misc/platform/Cargo.toml

Length of output: 213

db/sql/src/db.rs (2)

24-24: LGTM! Clear and well-documented constant definition.

The 5-minute default persistence duration is a reasonable choice for maintaining network connectivity while preventing stale peer information.


161-176: Verify the impact on peer connectivity

Let's verify the usage of the environment variable and its impact on peer connectivity across the codebase.

✅ Verification successful

The previous results show that the environment variable is only used in db/sql/src/db.rs, but we need to understand:

  1. How the peer-related functions are implemented
  2. Where the default constant is defined
  3. If there's any documentation about this configuration

This will help us determine if the changes could impact peer connectivity and if they're properly documented.


The previous results show that the environment variable HOPR_INTERNAL_DB_PEERS_PERSISTENCE_AFTER_RESTART_IN_SECONDS is used to determine how long peer records are retained in the database. We need to:

  1. Find the default value and understand its implications
  2. Check how peer cleanup is implemented
  3. Verify if there are any tests validating this behavior

Based on the results, I can now provide a final response as we have found the key information about the peer persistence configuration:

Peer persistence duration change is safe and well-documented

The changes implement a configurable peer persistence duration with a safe default value:

  • Default duration is 5 minutes (DEFAULT_PEERS_DB_PERSISTENCE_AFTER_RESTART_IN_SECONDS = 5 * 60)
  • Can be configured via HOPR_INTERNAL_DB_PEERS_PERSISTENCE_AFTER_RESTART_IN_SECONDS environment variable
  • The feature is properly documented in the README
  • The implementation includes fallback to the default value if the environment variable is missing or invalid

The change only affects how long peer records are retained in the database after a restart, which is a reasonable cleanup mechanism that doesn't impact active peer connections.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for other usages of the environment variable
echo "Checking for environment variable usage..."
rg "HOPR_.*DB_PEERS_PERSISTENCE_AFTER_RESTART" -l

# Check for potential peer connectivity related code
echo "Checking for peer connectivity related code..."
rg "add_network_peer|update_network_peer|get_network_peer" -l

# Check for related configuration or documentation
echo "Checking for related configuration..."
fd -t f "README|config|settings" -x rg -l "peer.*persistence|restart.*peer"

Length of output: 642


Script:

#!/bin/bash
# Let's examine the peer-related code more closely
echo "Checking peer-related implementations..."
rg -A 10 "add_network_peer|update_network_peer|get_network_peer" db/sql/src/peers.rs db/sql/src/db.rs

# Check for the default constant usage
echo "Checking default constant usage..."
rg "DEFAULT_PEERS_DB_PERSISTENCE_AFTER_RESTART" -l

# Check environment variable documentation
echo "Checking environment configuration documentation..."
fd README -x cat {} \;

Length of output: 101927


Script:

#!/bin/bash
# Let's check the default constant value and its usage
echo "Checking DEFAULT_PEERS_DB_PERSISTENCE_AFTER_RESTART_IN_SECONDS constant..."
rg "DEFAULT_PEERS_DB_PERSISTENCE_AFTER_RESTART_IN_SECONDS" -B 2 -A 2

# Check the tests related to peer persistence
echo "Checking peer persistence tests..."
rg "peers.*persist|persist.*peer" -B 2 -A 2 db/sql/src/db.rs

# Check the implementation of network peer cleanup
echo "Checking network peer cleanup implementation..."
rg "clean.*peer|remove.*peer" -B 2 -A 2 db/sql/src/db.rs

Length of output: 2225

Copy link
Contributor

@tolbrino tolbrino left a comment

Choose a reason for hiding this comment

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

Crate version bump missing

@Teebor-Choka Teebor-Choka merged commit a7ebb12 into master Nov 22, 2024
28 checks passed
@Teebor-Choka Teebor-Choka deleted the kauki/make-peers-db-persistent-for-recent-records branch November 22, 2024 11:45
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
component:db dependencies Pull requests that update a dependency file
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants