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

feat(launcher): db connect options #1182

Merged
merged 3 commits into from
Jan 14, 2025
Merged

Conversation

k1rill-fedoseev
Copy link
Member

@k1rill-fedoseev k1rill-fedoseev commented Jan 13, 2025

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced new optional dependency for improved serialization.
    • Added new environment variables for enhanced database connection options.
  • Chores

    • Updated package version for blockscout-service-launcher.
    • Updated dependency management for database configurations.
  • Refactor

    • Simplified database initialization process by consolidating parameters.
    • Centralized database settings configuration for improved clarity and maintainability.

@k1rill-fedoseev k1rill-fedoseev self-assigned this Jan 13, 2025
Copy link
Contributor

coderabbitai bot commented Jan 13, 2025

Warning

Rate limit exceeded

@k1rill-fedoseev 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 3980f5f and 8920cd9.

📒 Files selected for processing (1)
  • libs/blockscout-service-launcher/src/database.rs (6 hunks)

Walkthrough

The pull request introduces updates to the Blockscout service launcher library and related components. The primary changes involve updating the blockscout-service-launcher package version to 0.16.0 and adding a new optional serde_with dependency. In the database.rs file, significant refactoring occurred to centralize database configuration, introducing new structs like DatabaseConnectOptionsSettings and LevelFilter. The env-collector library was updated to support new database connection environment variables, expanding the configuration options for database connections. The service template's server initialization was simplified to use a more consolidated approach for database connection settings.

Poem

🐰 Hop, hop, through code so bright,
Database settings now take flight!
Serde and connections align,
With rabbit's magic design divine 🔧
Configuration's new frontier gleams! 🌟


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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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

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

🧹 Nitpick comments (2)
libs/blockscout-service-launcher/src/database.rs (1)

148-173: Add documentation for connection pool settings.

While the struct fields have basic comments, consider adding more detailed documentation about:

  • Recommended values for connection pool settings
  • Impact of each timeout setting
  • Trade-offs between different configurations

Example documentation for max_connections:

 /// Maximum number of connections for a pool
+/// 
+/// This setting controls the maximum size of the connection pool.
+/// Choose a value based on:
+/// - Your application's concurrency needs
+/// - Database server's max_connections limit
+/// - Available system resources
+/// 
+/// Recommended range: 10-100 for most applications
 pub max_connections: Option<u32>,
libs/blockscout-service-launcher/Cargo.toml (1)

29-29: Consider adding version constraints for serde_with.

The current specification version = "3" could potentially accept breaking changes in future releases. Consider using a more specific version constraint:

-serde_with = {version = "3", optional = true }
+serde_with = {version = "~3.0", optional = true }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5481500 and 5a7b6a4.

📒 Files selected for processing (5)
  • libs/blockscout-service-launcher/Cargo.toml (3 hunks)
  • libs/blockscout-service-launcher/src/database.rs (6 hunks)
  • libs/env-collector/Cargo.toml (1 hunks)
  • libs/env-collector/src/lib.rs (3 hunks)
  • service-template/{{project-name}}-server/src/server.rs (1 hunks)
🔇 Additional comments (8)
service-template/{{project-name}}-server/src/server.rs (1)

47-47: LGTM! Clean refactor of database initialization.

The change simplifies the database initialization by passing the entire settings object, which aligns with the new function signature and reduces complexity.

libs/blockscout-service-launcher/src/database.rs (3)

3-3: LGTM! Required import for duration serialization.

The serde_with import is necessary for serializing Duration fields in the new database connection options.


21-21: LGTM! Updated error message to include new database version.

The compile error message now correctly includes the new database-1_0 feature option.


30-34: LGTM! Clean refactor of database initialization.

The changes improve the function's interface by:

  • Consolidating parameters into a single settings structure
  • Making the code more maintainable
  • Preserving existing functionality

Also applies to: 37-37

libs/env-collector/src/lib.rs (1)

654-713: LGTM! Comprehensive environment variables for database connection options.

The changes:

  • Add all necessary environment variables for the new connection options
  • Use consistent naming and structure
  • Include appropriate default values
libs/env-collector/Cargo.toml (1)

16-16: LGTM! Updated dependency to use new database version.

The change correctly updates the blockscout-service-launcher dependency to use the new database-1_0 feature.

libs/blockscout-service-launcher/Cargo.toml (2)

3-3: LGTM: Version bump follows semantic versioning.

The version increment from 0.15.0 to 0.16.0 appropriately reflects the addition of new database configuration features.


94-94: LGTM: Database feature dependencies updated correctly.

The addition of serde_with to the database feature is consistent with the enhanced database configuration capabilities.

@k1rill-fedoseev k1rill-fedoseev force-pushed the kf/feat/db-connect-options branch from 8d302ff to 3980f5f Compare January 13, 2025 13:54
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.

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

🧹 Nitpick comments (2)
libs/blockscout-service-launcher/src/database.rs (2)

Line range hint 38-77: Enhance error handling in database creation.

The database creation error handling could be improved by using a custom error type instead of string matching.

Consider creating a custom error type:

#[derive(Debug, thiserror::Error)]
pub enum DatabaseError {
    #[error("Database '{0}' already exists")]
    AlreadyExists(String),
    #[error(transparent)]
    Other(#[from] DbErr),
}

Then refactor the error handling:

-            Err(e) => {
-                if e.to_string().contains("already exists") {
-                    tracing::info!("database '{db_name}' already exists");
-                } else {
-                    return Err(anyhow::anyhow!(e));
-                }
-            }
+            Err(e) => match DatabaseError::from(e) {
+                DatabaseError::AlreadyExists(_) => {
+                    tracing::info!("database '{db_name}' already exists");
+                }
+                DatabaseError::Other(e) => return Err(e.into()),
+            }

234-247: Consider simplifying LevelFilter serialization.

The custom serialization could be simplified by using derive macros or the existing Display and FromStr implementations.

Consider using serde's built-in string serialization:

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum LevelFilter {
    Off,
    Error,
    Warn,
    Info,
    Debug,
    Trace,
}
🛑 Comments failed to post (1)
libs/blockscout-service-launcher/src/database.rs (1)

224-224: ⚠️ Potential issue

Remove unnecessary type conversions.

The .into() conversions are unnecessary as we're already using tracing::log::LevelFilter.

Apply this diff to fix the pipeline errors:

-        options.sqlx_logging_level(self.sqlx_logging_level.into());
+        options.sqlx_logging_level(self.sqlx_logging_level);
         #[cfg(feature = "database-1_0")]
         options.sqlx_slow_statements_logging_settings(
-            self.sqlx_slow_statements_logging_level.into(),
+            self.sqlx_slow_statements_logging_level,
             self.sqlx_slow_statements_logging_threshold,
         );

Also applies to: 227-227

🧰 Tools
🪛 GitHub Actions: Test, lint (libs)

[error] 224-224: Useless conversion to the same type: tracing::log::LevelFilter. Remove .into() from self.sqlx_logging_level.into()

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: 0

🧹 Nitpick comments (3)
libs/blockscout-service-launcher/src/database.rs (3)

Line range hint 38-77: Consider improving error handling in database creation.

The database creation error handling could be more robust. Currently, it only checks if the error message contains "already exists", which might be fragile across different PostgreSQL versions or locales.

Consider using the PostgreSQL error codes instead:

-            if e.to_string().contains("already exists") {
+            if let DbErr::Custom(ref e) = e {
+                // 42P04 is the PostgreSQL error code for "duplicate_database"
+                if e.contains("42P04") {
                    tracing::info!("database '{db_name}' already exists");
                } else {
                    return Err(anyhow::anyhow!(e));
                }
+            } else {
+                return Err(anyhow::anyhow!(e));
+            }

149-182: Add validation for timeout settings.

The struct accepts any Duration values for timeouts without validation. This could lead to operational issues if unreasonable values are provided (e.g., extremely short timeouts or very long lifetimes).

Consider adding validation during deserialization:

impl DatabaseConnectOptionsSettings {
    fn validate_timeout(name: &str, value: Duration) -> Result<(), String> {
        const MIN_TIMEOUT: Duration = Duration::from_millis(100);
        const MAX_TIMEOUT: Duration = Duration::from_secs(3600);
        if value < MIN_TIMEOUT || value > MAX_TIMEOUT {
            return Err(format!(
                "{} must be between {:?} and {:?}",
                name, MIN_TIMEOUT, MAX_TIMEOUT
            ));
        }
        Ok(())
    }
}

203-232: Consider adding connection pool metrics.

The connection pool configuration is comprehensive, but there's no built-in way to monitor pool health (active connections, wait times, etc.).

Consider adding metrics collection capabilities:

  1. Add pool statistics collection
  2. Expose metrics for monitoring systems (e.g., Prometheus)
  3. Add health check endpoints

This would help with operational monitoring and troubleshooting. Would you like me to provide a detailed implementation proposal?

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8d302ff and 3980f5f.

📒 Files selected for processing (1)
  • libs/blockscout-service-launcher/src/database.rs (6 hunks)
🔇 Additional comments (1)
libs/blockscout-service-launcher/src/database.rs (1)

193-194: Review default SQLx logging configuration.

The default configuration enables SQLx logging (sqlx_logging: true) at Debug level. This might be too verbose for production environments and could impact performance.

Consider if these defaults are appropriate for your use case. You may want to:

  1. Disable logging by default
  2. Set a less verbose default level like Info

Run this script to check current logging usage across the codebase:

@k1rill-fedoseev k1rill-fedoseev force-pushed the kf/feat/db-connect-options branch from 3980f5f to 081a63a Compare January 13, 2025 13:59
Copy link
Member

@rimrakhimov rimrakhimov left a comment

Choose a reason for hiding this comment

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

Looks great for me

Copy link
Contributor

@bragov4ik bragov4ik left a comment

Choose a reason for hiding this comment

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

lgtm

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.

3 participants