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: removed pool config from knex and better closing in cli #3155

Merged
merged 1 commit into from
Feb 27, 2025

Conversation

akhilmhdh
Copy link
Member

@akhilmhdh akhilmhdh commented Feb 26, 2025

Description 📣

Improved gateway closing and removed pool from knexjs for dynamic secret sql

Type ✨

  • Bug fix
  • New feature
  • Improvement
  • Breaking change
  • Documentation

Tests 🛠️

# Here's some code block to paste some code snippets

Summary by CodeRabbit

  • Bug Fixes

    • Improved database transaction management to ensure all connections are reliably closed, reducing the risk of resource leaks.
    • Refined gateway shutdown behavior with better error handling and retry logic, enhancing overall operational stability.
  • Refactor

    • Enhanced signal monitoring and connection management, ensuring a smoother and more resilient shutdown process.

@akhilmhdh akhilmhdh requested a review from maidul98 February 26, 2025 20:03
Copy link

coderabbitai bot commented Feb 26, 2025

Walkthrough

This pull request implements a series of changes focused on enhancing connection and error management across both the backend and CLI components. In the SQL database provider, the connection pool configuration has been removed and transaction handling has been refactored to use a try...finally block, ensuring that database connections are always destroyed. In the gateway CLI code, signal handling has been strengthened by introducing a mechanism to detect a second signal to trigger a forced exit, while the connection establishment logic is now restructured to retry upon errors using a ticker. Additionally, adjustments in the Listen method of the gateway include the renaming of a shutdown signal variable and the implementation of deadlines to manage connection timeouts and facilitate graceful shutdowns. No changes were made to exported or public entity declarations.

Warning

There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

backend/src/ee/services/dynamic-secret/providers/sql-database.ts

Oops! Something went wrong! :(

ESLint: 8.57.1

ESLint couldn't find the plugin "@typescript-eslint/eslint-plugin".

(The package "@typescript-eslint/eslint-plugin" was not found when loaded as a Node module from the directory "/backend".)

It's likely that the plugin isn't installed correctly. Try reinstalling by running the following:

npm install @typescript-eslint/eslint-plugin@latest --save-dev

The plugin "@typescript-eslint/eslint-plugin" was referenced from the config file in "backend/.eslintrc.js".

If you still can't figure out the problem, please stop by https://eslint.org/chat/help to chat with the team.

✨ Finishing Touches
  • 📝 Generate Docstrings

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

@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)
backend/src/ee/services/dynamic-secret/providers/sql-database.ts (1)

121-141: Ensure the removal of pool config meets performance needs.

You are using a try/finally block for transaction execution and destroying the db client immediately after creation, which cleanly prevents resource leaks. However, removing the pool configuration means each call will create and destroy a fresh connection. For high-traffic scenarios, this can negatively affect performance. Consider whether a small pool of reusable connections is acceptable and, if so, provide a more controlled approach to connection lifecycle.

cli/packages/cmd/gateway.go (1)

63-108: Consider configurable or exponential backoff for retries.

You introduce a retry mechanism with a fixed 5-second interval when connecting or listening fails. While it works, use of a simple ticker may lead to repeated retries in resource-heavy environments. Consider adding:
• A configurable initial delay.
• Exponential backoff to increase wait times under recurring failures.

- retryTicker := time.NewTicker(5 * time.Second)
+ backoffDuration := 5 * time.Second // or configurable
+ // Potential exponential backoff approach if desired
cli/packages/gateway/gateway.go (1)

265-277: Graceful shutdown with a 5-second wait.

Signaling the accept loop and then waiting up to 5 seconds is a good compromise. For heavily loaded gateways or longer-running connections, consider making this timeout configurable or logging additional details if the wait is insufficient.

- case <-time.After(5 * time.Second):
+ // Consider making 5s a configurable setting
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e6af7a6 and 3e7110f.

📒 Files selected for processing (3)
  • backend/src/ee/services/dynamic-secret/providers/sql-database.ts (3 hunks)
  • cli/packages/cmd/gateway.go (1 hunks)
  • cli/packages/gateway/gateway.go (6 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Run integration test
  • GitHub Check: Check TS and Lint
🔇 Additional comments (9)
backend/src/ee/services/dynamic-secret/providers/sql-database.ts (2)

157-168: Transaction scope and graceful resource cleanup look solid.

Similar to the create operation, you properly encapsulate the revoke logic inside a transaction and ensure the database connection is destroyed in the finally block. This helps maintain code consistency and reliability. Keep an eye on potential performance impacts as noted previously.


192-203: Renew logic replicates the same pattern—good consistency.

This try/finally technique for reliable cleanup is applied consistently in the renew method and is a good approach. As with the other operations, just be aware of any overhead from repeatedly initializing and destroying connections in high-volume use cases, especially since pools have been removed.

cli/packages/cmd/gateway.go (1)

56-61: Second-signal handling is a great fallback.

Having a fallback for forceful termination upon receiving a second signal is helpful for edge cases where the first signal might fail to gracefully stop the process. Ensure developers clearly understand that any unflushed resources will be discarded if the second signal arrives too quickly.

cli/packages/gateway/gateway.go (6)

115-115: No functional changes identified.

There doesn't appear to be a substantive difference here beyond a new annotation or whitespace. Proceeding without further comment.


143-144: Channel-based shutdown strategy is clear.

Defining shutdownCh to control the lifecycle of permission registration and other loops is an elegant approach. This channel signaling pattern simplifies concurrency management and clarifies shutdown flow.

Also applies to: 155-155


173-176: Heartbeat and relay checks align well with channel-based design.

Registering your heartbeat and relay-active checks with the same shutdownCh ensures that these periodic tasks end promptly. This prevents zombie goroutines after shutdown.


182-185: Non-blocking accept loop with adjustable deadlines is robust.

Using a short deadline on the listener in combination with checking ctx.Done() and shutdownCh helps keep the accept loop from permanently blocking. This approach works well for a more graceful shutdown.

Also applies to: 187-191


213-218: TLS handshake and certificate checks are properly enforced.

You properly set a handshake deadline and validate certificate fields (gateway-client, cloud). This ensures secure, validated connections. Good job promptly closing the connection on mismatch.

Also applies to: 231-232


238-253: Goroutine closure strategy is well-considered.

A dedicated goroutine waits on ctx.Done() or shutdownCh and then closes the connection. This ensures each accepted connection can be forcibly terminated if needed without complicating the main accept loop.

@fumeoss
Copy link

fumeoss commented Feb 26, 2025

Summary

  • Removed the connection pooling configuration from Knex for SQL database connections to enhance dynamic secret management.
  • Improved the closure of database connections during gateway shutdown to prevent resource leaks.
  • Enhanced error handling and retry logic during gateway operations to increase reliability and stability.
  • Refactored the shutdown process to ensure a smoother operation and more graceful handling of connection and shutdown signals.
🧪 2 passed

🟢 Test Gateway Connection Retry Under Load

🟢 Test Gateway Graceful Shutdown with Active Connections

Want to make Fume a regular reviewer at Infisical? 👉 let's talk

@maidul98 maidul98 merged commit 30f0f17 into Infisical:main Feb 27, 2025
5 of 6 checks passed
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