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

Open
wants to merge 1 commit into
base: 11-26-add_support_for_creating_namespaced_databases
Choose a base branch
from

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.
  • Bug Fixes

    • Enhanced error handling during database and component initialization to ensure graceful application exits.

Copy link

coderabbitai bot commented Nov 26, 2024

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. The overall structure and error handling of the main function remain unchanged.

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.

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

Warning

Rate limit exceeded

@neekolas has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 6 minutes and 42 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 d0c365c and 0a2d620.


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between d0c365c and 0a2d620.

📒 Files selected for processing (2)
  • cmd/replication/main.go (1 hunks)
  • pkg/utils/namespace.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • cmd/replication/main.go
  • pkg/utils/namespace.go

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

Warning

This pull request is not mergeable via GitHub because a downstack PR is open. Once all requirements are satisfied, merge this PR as a stack on Graphite.
Learn more

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-add_support_for_creating_namespaced_databases branch from c60671d to 21e80d5 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-add_support_for_creating_namespaced_databases branch from 6e15894 to 4e6c14c 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-add_support_for_creating_namespaced_databases branch from ac71c6b to de7bd67 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-add_support_for_creating_namespaced_databases branch from b97c1ee to f1897ed Compare November 27, 2024 01:52
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