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

Use namespace in DB #295

Merged
merged 1 commit into from
Dec 2, 2024
Merged

Use namespace in DB #295

merged 1 commit into from
Dec 2, 2024

Conversation

neekolas
Copy link
Contributor

@neekolas neekolas commented Nov 26, 2024

TL;DR

Added database namespace support based on private key and contract address

What changed?

  • Introduced a new BuildNamespace function that generates a unique namespace using the node's private key and contract address
  • Modified the replication service to use namespaced database connections
  • The namespace is a 12-character hex string derived from the Keccak256 hash of the private key and contract address

How to test?

  1. Start multiple nodes with different private keys
  2. Verify each node creates its database tables under a unique namespace
  3. Confirm that data remains isolated between different node instances

Summary by CodeRabbit

  • New Features

    • Introduced a new method for database initialization that supports namespacing.
    • Added a function to compute a namespace based on server options.
    • Added a --broadcast option for contract deployment commands, enabling transaction broadcasting.
  • Bug Fixes

    • Enhanced error handling during database and component initialization to ensure graceful application exits.
    • Improved reliability of deployment scripts with better error handling and control flow.
    • Updated deployment scripts to reflect changes in contract deployment processes.

Copy link

coderabbitai bot commented Nov 26, 2024

Warning

Rate limit exceeded

@neekolas has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 22 minutes and 45 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 6383a48 and a7a562d.

Walkthrough

The pull request modifies the database initialization process in the cmd/replication/main.go file by replacing the db.NewDB method with db.NewNamespacedDB, which now requires a namespace argument derived from a newly introduced utility function. The BuildNamespace function, added to the pkg/utils/namespace.go file, computes this namespace based on specific properties of the server options. Additionally, scripts in the dev/contracts directory have been updated to include the --broadcast option in the forge create command, enhancing deployment functionality and error handling.

Changes

File Path Change Summary
cmd/replication/main.go Replaced db.NewDB with db.NewNamespacedDB, adding a namespace argument from utils.BuildNamespace(options). Error handling remains unchanged.
pkg/utils/namespace.go Added BuildNamespace(options config.ServerOptions) string function to compute a namespace using Keccak256 hashing.
dev/contracts/deploy-ephemeral Added --broadcast option to the forge create command.
dev/contracts/deploy-local Added set -euo pipefail for improved error handling; included --broadcast option in the forge create command.
dev/contracts/deploy-testnet Added --broadcast option to the forge create command; commented out deployment of GroupMessages and IdentityUpdates contracts.

Sequence Diagram(s)

sequenceDiagram
    participant Main
    participant DB
    participant Utils

    Main->>Utils: BuildNamespace(options)
    Utils-->>Main: namespace
    Main->>DB: NewNamespacedDB(ctx, writerConnectionString, namespace, waitForDB, readTimeout)
Loading

Possibly related PRs

Suggested reviewers

  • mkysel

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.

Copy link
Contributor Author

neekolas commented Nov 26, 2024

This stack of pull requests is managed by Graphite. Learn more about stacking.

@neekolas neekolas marked this pull request as ready for review November 26, 2024 20:56
@neekolas neekolas requested a review from a team as a code owner November 26, 2024 20:56
Copy link

@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: 2

🧹 Outside diff range and nitpick comments (3)
pkg/utils/namespace.go (2)

14-14: Risk of namespace collisions due to hash truncation

Truncating the hash to 12 characters (6 bytes) significantly increases the probability of collisions. With 6 bytes, you have 2^48 possible values, which might not be sufficient for a large-scale distributed system.

Consider:

  1. Using a longer prefix (e.g., 16 or 20 characters) to reduce collision probability
  2. Implementing collision detection in the database layer
  3. Adding a validation mechanism to ensure namespace uniqueness

8-15: Add unit tests for namespace generation

This is a critical function that affects database isolation. It needs comprehensive testing to ensure consistent behavior.

Would you like me to help create unit tests that cover:

  1. Normal operation with valid inputs
  2. Collision probability assessment
  3. Error cases with invalid inputs
  4. Consistency of namespace generation
cmd/replication/main.go (1)

60-65: Consider adding integration tests for namespaced DB

The database namespace change could affect data isolation. Consider adding integration tests to verify:

  1. Data isolation between different namespaces
  2. Proper cleanup/teardown in tests
  3. Namespace collision scenarios
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 3671479 and c4ab5f0.

📒 Files selected for processing (2)
  • cmd/replication/main.go (1 hunks)
  • pkg/utils/namespace.go (1 hunks)
🔇 Additional comments (3)
pkg/utils/namespace.go (1)

14-14: Verify HexEncode function implementation

The code uses HexEncode which isn't imported but presumably exists in the same package.

Let's verify the implementation:

✅ Verification successful

HexEncode implementation is correct and properly located

The HexEncode function is correctly implemented in the same package (pkg/utils/hex.go) and uses the standard encoding/hex package's EncodeToString function to convert byte data to a hexadecimal string. Since it's in the same package, no import is needed in namespace.go.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for HexEncode function definition
ast-grep --pattern 'func HexEncode($_) $_'

# Backup: use ripgrep if ast-grep doesn't find it
rg -p "func HexEncode"

Length of output: 362

cmd/replication/main.go (2)

63-63: Verify namespace generation consistency

The namespace is derived from server options, which could affect database isolation between different server instances.

✅ Verification successful

Namespace generation is correctly isolated and consistent

The BuildNamespace function in pkg/utils/namespace.go generates a unique namespace by hashing the signer's private key and nodes contract address, which ensures proper database isolation between different server instances. The implementation is deterministic and depends only on server-specific configuration, making it safe for use.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check the implementation of BuildNamespace
ast-grep --pattern 'func BuildNamespace($$$) {
  $$$
}'

# Look for other potential namespace usages
rg -A 5 'BuildNamespace'

Length of output: 656


60-65: Verify namespace initialization and database compatibility

The switch to NewNamespacedDB suggests a multi-tenant or isolation approach. This is a significant architectural change that requires careful consideration.

Let's verify the implementation details:

Consider the following architectural aspects:

  1. Ensure all database operations respect the namespace
  2. Verify that existing data migration scripts handle namespaced tables
  3. Document the namespace strategy for operational visibility
✅ Verification successful

Let me gather more information about the namespace implementation and migration handling.


Let me check one more aspect - the actual SQL migrations and database schema to understand how namespacing is implemented.


Based on the gathered information, I can now provide the final response:

Database namespacing implementation is properly handled

The switch to NewNamespacedDB is well-implemented with the following key aspects:

  • Creates a new database using the namespace as the database name
  • Namespace is deterministically generated using server options (private key and contract address)
  • Database creation is handled safely with proper connection management
  • Existing migrations will run in the namespaced database context
  • All tables (node_info, gateway_envelopes, etc.) are automatically isolated by being created in the namespaced database

No architectural issues found as the isolation is handled at the database level rather than schema/table level, providing complete separation of data between different instances.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check the database package for namespace handling
ast-grep --pattern 'func NewNamespacedDB($$$) {
  $$$
}'

# Check for any database migration files that might need updates
fd -e sql -e go migration

Length of output: 115


Script:

#!/bin/bash
# Check the implementation of NewNamespacedDB
rg -A 10 "NewNamespacedDB" 

# Check BuildNamespace implementation
rg -A 5 "BuildNamespace"

# Check migration code for namespace handling
cat pkg/migrations/migrations.go

# Look for any database operations that might need namespace awareness
ast-grep --pattern 'db.$_($$$)'

Length of output: 2984


Script:

#!/bin/bash
# Check SQL migration files
fd -e sql . pkg/migrations -x cat {}

# Check if namespace is used in table names or schemas
rg -A 5 "CREATE TABLE|CREATE SCHEMA" 

# Look for any database configuration or schema setup
rg -A 10 "pgxpool.ParseConfig" 

Length of output: 6506

pkg/utils/namespace.go Show resolved Hide resolved
@neekolas neekolas force-pushed the 11-26-add_support_for_creating_namespaced_databases branch from 3671479 to c60671d Compare November 27, 2024 00:26
@neekolas neekolas force-pushed the 11-26-use_namespace_in_db branch from c4ab5f0 to 769a3f9 Compare November 27, 2024 00:26
@neekolas neekolas force-pushed the 11-26-add_support_for_creating_namespaced_databases branch from c60671d to 21e80d5 Compare November 27, 2024 00:32
@neekolas neekolas force-pushed the 11-26-use_namespace_in_db branch from 769a3f9 to 3d8ea11 Compare November 27, 2024 00:32
@neekolas neekolas force-pushed the 11-26-add_support_for_creating_namespaced_databases branch from 21e80d5 to 6e15894 Compare November 27, 2024 00:36
@neekolas neekolas force-pushed the 11-26-use_namespace_in_db branch from 3d8ea11 to f5bb7ba Compare November 27, 2024 00:36
@neekolas neekolas force-pushed the 11-26-add_support_for_creating_namespaced_databases branch from 6e15894 to 4e6c14c Compare November 27, 2024 01:29
@neekolas neekolas force-pushed the 11-26-use_namespace_in_db branch from f5bb7ba to 258b3a7 Compare November 27, 2024 01:29
@neekolas neekolas force-pushed the 11-26-add_support_for_creating_namespaced_databases branch from 4e6c14c to ac71c6b Compare November 27, 2024 01:39
@neekolas neekolas force-pushed the 11-26-use_namespace_in_db branch from 258b3a7 to a1f3f7e Compare November 27, 2024 01:39
@neekolas neekolas force-pushed the 11-26-add_support_for_creating_namespaced_databases branch from ac71c6b to de7bd67 Compare November 27, 2024 01:44
@neekolas neekolas force-pushed the 11-26-use_namespace_in_db branch from a1f3f7e to d0f0f50 Compare November 27, 2024 01:44
@neekolas neekolas force-pushed the 11-26-add_support_for_creating_namespaced_databases branch from de7bd67 to b97c1ee Compare November 27, 2024 01:50
@neekolas neekolas force-pushed the 11-26-use_namespace_in_db branch from d0f0f50 to d0c365c Compare November 27, 2024 01:50
@neekolas neekolas force-pushed the 11-26-add_support_for_creating_namespaced_databases branch from b97c1ee to f1897ed Compare November 27, 2024 01:52
@neekolas neekolas force-pushed the 11-26-use_namespace_in_db branch from d0c365c to 0a2d620 Compare November 27, 2024 01:52
Copy link
Contributor Author

neekolas commented Dec 2, 2024

Merge activity

  • Dec 2, 2:07 PM PST: A user started a stack merge that includes this pull request via Graphite.
  • Dec 2, 2:09 PM PST: Graphite rebased this pull request as part of a merge.
  • Dec 2, 2:10 PM PST: Graphite couldn't merge this PR because it was not satisfying all requirements (Failed CI: 'Push Docker Image to GitHub Packages').

@neekolas neekolas changed the base branch from 11-26-add_support_for_creating_namespaced_databases to graphite-base/295 December 2, 2024 22:07
@neekolas neekolas changed the base branch from graphite-base/295 to main December 2, 2024 22:07
@neekolas neekolas force-pushed the 11-26-use_namespace_in_db branch 3 times, most recently from bb8f74c to 6383a48 Compare December 2, 2024 22:41
Copy link

@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.

Caution

Inline review comments failed to post. This is likely due to GitHub's limits when posting large numbers of comments.

Actionable comments posted: 1

🧹 Outside diff range and nitpick comments (1)
dev/contracts/deploy-testnet (1)

21-23: Document the rationale for commented-out contracts

The selective deployment of only the Nodes contract needs explanation, especially since it differs from local deployment.

Add a comment explaining the deployment strategy, for example:

-# deploy_contract src/GroupMessages.sol GroupMessages
+# GroupMessages contract deployment temporarily disabled for namespace migration
 deploy_contract src/Nodes.sol Nodes
-# deploy_contract src/IdentityUpdates.sol IdentityUpdates
+# IdentityUpdates contract deployment temporarily disabled for namespace migration
🛑 Comments failed to post (1)
dev/contracts/deploy-ephemeral (1)

8-8: 🛠️ Refactor suggestion

Add error handling directives for script robustness

While the addition of --broadcast is good, this script should include error handling directives for consistency with other deployment scripts.

Add these lines at the beginning of the script:

 #!/bin/bash
+set -euo pipefail
 
 source dev/contracts/.env

Committable suggestion skipped: line range outside the PR's diff.

@neekolas neekolas force-pushed the 11-26-use_namespace_in_db branch from 6383a48 to a7a562d Compare December 2, 2024 22:46
@neekolas neekolas merged commit a50c51e into main Dec 2, 2024
9 checks passed
@neekolas neekolas deleted the 11-26-use_namespace_in_db branch December 2, 2024 22:53
@coderabbitai coderabbitai bot mentioned this pull request Dec 4, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants