Skip to content

feat: add Close() to mongoClient for graceful shutdown#109

Open
Prabhjot-Sethi wants to merge 1 commit intomainfrom
feat/store-client-close
Open

feat: add Close() to mongoClient for graceful shutdown#109
Prabhjot-Sethi wants to merge 1 commit intomainfrom
feat/store-client-close

Conversation

@Prabhjot-Sethi
Copy link
Collaborator

@Prabhjot-Sethi Prabhjot-Sethi commented Mar 5, 2026

Summary

  • Adds Close() method to mongoClient that calls Disconnect() on the underlying *mongo.Client
  • Implements io.Closer so callers can type-assert StoreClient to io.Closer for graceful shutdown
  • Without this, the MongoDB driver connection pool leaks until process exit

Motivation

Downstream services (e.g., slack-adapter) wrap StoreClient with a closeable adapter that needs to disconnect on shutdown. Currently StoreClient has no close path, forcing services to maintain a parallel raw *mongo.Client just for disconnect. This one-line method eliminates that workaround.

Test plan

  • go build ./db/... passes
  • go vet ./db/... passes
  • Existing db tests pass (require MongoDB connection)

Summary by CodeRabbit

  • Chores
    • Enhanced application shutdown robustness through improved resource management and graceful disconnection handling.

Add io.Closer implementation to mongoClient so callers can type-assert
StoreClient to io.Closer and disconnect the connection pool during
graceful shutdown. Without this, the MongoDB driver pool leaks until
process exit.
@coderabbitai
Copy link

coderabbitai bot commented Mar 5, 2026

Walkthrough

Added a Close() error method to the mongoClient type that disconnects the underlying MongoDB client using a background context and returns the resulting error. This enables io.Closer compatibility for graceful shutdown support.

Changes

Cohort / File(s) Summary
MongoDB Client Closer Implementation
db/mongo.go
Added Close() error method to mongoClient type to implement io.Closer interface for graceful shutdown of MongoDB connections.

Estimated code review effort

🎯 1 (Trivial) | ⏱️ ~3 minutes

Poem

🐰 A little Close() for MongoDB's grace,
Disconnect with context in place,
io.Closer now fits like a glove,
Graceful shutdowns that rabbits love! 🌙

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately and specifically describes the main change: adding a Close() method to mongoClient to enable graceful shutdown of MongoDB connections.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
  • 📝 Generate docstrings (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/store-client-close

Tip

Try Coding Plans. Let us write the prompt for your AI agent so you can ship faster (with fewer bugs).
Share your feedback on Discord.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link

@chatgpt-codex-connector chatgpt-codex-connector bot left a comment

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: db136b8f80

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

// connection pool. Implements io.Closer so callers can type-assert
// StoreClient to io.Closer for graceful shutdown.
func (c *mongoClient) Close() error {
return c.client.Disconnect(context.Background())

Choose a reason for hiding this comment

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

P1 Badge Add a deadline when disconnecting Mongo client

Close() calls Disconnect(context.Background()), but Mongo driver's Disconnect waits for in-use connections to be returned and only stops waiting when the context is canceled/deadlined. In shutdown paths with a stuck/leaked DB operation, this can block indefinitely and prevent graceful process termination; using a bounded timeout context inside Close() avoids hanging services while still releasing the pool in normal cases.

Useful? React with 👍 / 👎.

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.

🧹 Nitpick comments (1)
db/mongo.go (1)

558-564: Add a timeout to Disconnect() for more robust graceful shutdown.

Using context.Background() without a timeout means Disconnect() could hang indefinitely if the MongoDB server is unresponsive. According to MongoDB's Go driver v2 documentation, a bounded timeout is the recommended pattern for shutdown—when the deadline expires, the driver force-closes any remaining in-use connections rather than waiting indefinitely.

While the current implementation works, adding a timeout improves reliability during application shutdown. The pattern elsewhere in this file (lines 251, 406) uses context.Background() for stream cleanup within operation contexts, which is different from a public Close() method called during application termination.

Recommended: Add a shutdown timeout
 func (c *mongoClient) Close() error {
-	return c.client.Disconnect(context.Background())
+	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+	defer cancel()
+	return c.client.Disconnect(ctx)
 }

This requires adding "time" to imports if not already present.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@db/mongo.go` around lines 558 - 564, The Close method currently calls
c.client.Disconnect(context.Background()) which can hang; change Close (in
mongoClient.Close) to use a context with a bounded timeout (e.g.,
context.WithTimeout) and pass that to Disconnect, cancelling the context after
Disconnect returns; also add the "time" import if missing and ensure proper ctx
cancellation (defer cancel()) so the driver force-closes when the deadline
expires.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@db/mongo.go`:
- Around line 558-564: The Close method currently calls
c.client.Disconnect(context.Background()) which can hang; change Close (in
mongoClient.Close) to use a context with a bounded timeout (e.g.,
context.WithTimeout) and pass that to Disconnect, cancelling the context after
Disconnect returns; also add the "time" import if missing and ensure proper ctx
cancellation (defer cancel()) so the driver force-closes when the deadline
expires.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 73149625-46de-4a4c-8202-4f3bebc8f79a

📥 Commits

Reviewing files that changed from the base of the PR and between 351a926 and db136b8.

📒 Files selected for processing (1)
  • db/mongo.go

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.

1 participant