Skip to content

Conversation

@pablohashescobar
Copy link
Member

@pablohashescobar pablohashescobar commented Aug 26, 2025

Description

  • correct mongo connection class to initialize mongo db when is_configured is called.
  • add mongo url and mongo database environment to settings

Type of Change

  • Bug fix (non-breaking change which fixes an issue)

Test Scenarios

  • check if mongo db is connected

References

WEB-4720

Summary by CodeRabbit

  • New Features
    • Added support for configuring MongoDB via environment variables (MONGO_DB_URL, MONGO_DB_DATABASE), enabling easier setup and deployment across environments and simplifying ops workflows.
  • Bug Fixes
    • Improved MongoDB connection initialization to automatically create a client when missing, enhancing reliability during startup, reducing intermittent connection errors, and ensuring the database becomes available without manual intervention.

Copilot AI review requested due to automatic review settings August 26, 2025 10:33
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 26, 2025

Walkthrough

Adds MongoDB environment configuration variables in Django settings and updates the Mongo settings helper so is_configured ensures a singleton instance is created when missing before checking connectivity.

Changes

Cohort / File(s) Summary
Django settings: MongoDB vars
apps/api/plane/settings/common.py
Adds environment-driven variables MONGO_DB_URL and MONGO_DB_DATABASE (default False). Inserts a "MongoDB Settings" comment section.
Mongo config: singleton init on check
apps/api/plane/settings/mongo.py
Updates is_configured(cls) to instantiate the singleton (cls._instance = cls()) when _client is None before evaluating configuration; returns True only if both _client and _db are set.

Sequence Diagram(s)

sequenceDiagram
    autonumber
    participant Caller
    participant MongoSettings as MongoSettings (class)

    Caller->>MongoSettings: is_configured()
    alt _client is None
        MongoSettings->>MongoSettings: _instance = cls()<br/>(instantiate singleton)
    else _client exists
        Note over MongoSettings: Use existing client
    end
    MongoSettings->>MongoSettings: Check _client and _db
    MongoSettings-->>Caller: return (_client != None && _db != None)
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Poem

A rabbit taps code with a gentle thrum,
New env keys set, like a quiet hum.
The singleton wakes when pinged, not shy—
“Am I configured?” “Let’s instantiate and try.”
Carrots compiled, configs aligned,
Hoppity ready, with Mongo assigned. 🥕🐇

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix-mongo-connection

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
🪧 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.
    • 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.
  • 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 the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

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

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • 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.

@makeplane
Copy link

makeplane bot commented Aug 26, 2025

Pull Request Linked with Plane Work Items

Comment Automatically Generated by Plane

Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull Request Overview

This PR fixes a bug in the MongoDB connection class where the is_configured method would incorrectly return False even when MongoDB was properly configured, because it wasn't initializing the connection before checking the status. The fix ensures the MongoDB connection is established when checking configuration status.

  • Fix MongoDB connection initialization in the is_configured class method
  • Add MongoDB environment variables to Django settings

Reviewed Changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 1 comment.

File Description
apps/api/plane/settings/mongo.py Adds initialization logic to ensure MongoDB connection is established before status check
apps/api/plane/settings/common.py Adds MongoDB URL and database environment variable configurations

Tip: Customize your code reviews with copilot-instructions.md. Create the file or learn how to get started.

Comment on lines +122 to +123
if cls._client is None:
cls._instance = cls()
Copy link

Copilot AI Aug 26, 2025

Choose a reason for hiding this comment

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

The code sets cls._instance but doesn't assign the result to cls._client or cls._db. This means the initialization won't actually populate the client/database attributes that are checked in the return statement. You should either call a method that properly initializes these attributes or ensure the constructor properly sets cls._client and cls._db.

Suggested change
if cls._client is None:
cls._instance = cls()
if cls._client is None or cls._db is None:
cls._initialize_connection()

Copilot uses AI. Check for mistakes.
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 (4)
apps/api/plane/settings/common.py (2)

470-471: Prefer None defaults to avoid mixing bool and str types

Staying type-consistent helps downstream checks and tooling. Current truthiness checks still work, but None is a clearer “unset” sentinel.

Apply this minimal diff:

-MONGO_DB_URL = os.environ.get("MONGO_DB_URL", False)
-MONGO_DB_DATABASE = os.environ.get("MONGO_DB_DATABASE", False)
+MONGO_DB_URL = os.environ.get("MONGO_DB_URL")
+MONGO_DB_DATABASE = os.environ.get("MONGO_DB_DATABASE")

Optional alternative for broader compatibility (commonly used var names):

-MONGO_DB_URL = os.environ.get("MONGO_DB_URL", False)
+MONGO_DB_URL = os.environ.get("MONGO_DB_URL") or os.environ.get("MONGODB_URI")
-MONGO_DB_DATABASE = os.environ.get("MONGO_DB_DATABASE", False)
+MONGO_DB_DATABASE = os.environ.get("MONGO_DB_DATABASE") or os.environ.get("MONGODB_DATABASE")

469-471: Document new env vars and sample defaults

Add these to your env templates/docs (e.g., .env.example, Helm/Compose values) so operators know how to enable Mongo.

I can open a follow-up PR to add doc snippets and sample values if you’d like.

apps/api/plane/settings/mongo.py (2)

122-124: Also re-init when _db is None to avoid partial state

If initialization fails to set the db (e.g., missing database name) but _client ends up non-None, you won’t retry. Light tweak ensures a retry path.

Apply this diff:

-        if cls._client is None:
+        if cls._client is None or cls._db is None:
             cls._instance = cls()

122-124: Add timeout + ping and make init thread-safe (optional hardening)

  • Connectivity probe: prefer client.admin.command("ping") with a short serverSelectionTimeoutMS to avoid long blocking on first access.
  • Thread safety: guard singleton initialization with a lock to prevent duplicate inits under load.
  • Logging: consider sanitizing exception text to avoid leaking parts of the URI from driver errors.

Outside the changed lines, the following pattern keeps behavior but improves resilience:

# at top of module
import threading
# inside MongoConnection class
_lock = threading.Lock()

def __new__(cls: Type[T]) -> T:
    if cls._instance is None:
        with cls._lock:
            if cls._instance is None:  # double-checked
                cls._instance = super(MongoConnection, cls).__new__(cls)
                try:
                    mongo_url = getattr(settings, "MONGO_DB_URL", None)
                    mongo_db_database = getattr(settings, "MONGO_DB_DATABASE", None)
                    if not mongo_url or not mongo_db_database:
                        logger.warning("MongoDB not configured; functionality disabled.")
                        return cls._instance

                    cls._client = MongoClient(
                        mongo_url,
                        serverSelectionTimeoutMS=int(os.environ.get("MONGO_DB_TIMEOUT_MS", "2000")),
                        connectTimeoutMS=int(os.environ.get("MONGO_DB_CONNECT_TIMEOUT_MS", "2000")),
                    )
                    cls._db = cls._client[mongo_db_database]

                    # Fast, low-privilege health check
                    cls._client.admin.command("ping")
                    logger.info("MongoDB connection established successfully")
                except Exception as e:
                    # Avoid printing full URI; log class and reason
                    logger.warning(f"Failed to initialize MongoDB connection: {e.__class__.__name__}: {e}")
    return cls._instance
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between cf7b288 and 2c61389.

📒 Files selected for processing (2)
  • apps/api/plane/settings/common.py (1 hunks)
  • apps/api/plane/settings/mongo.py (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Analyze (javascript)
🔇 Additional comments (3)
apps/api/plane/settings/common.py (1)

469-471: MongoDB settings surfaced via env: LGTM

Adding explicit MONGO_DB_URL and MONGO_DB_DATABASE knobs keeps configuration centralized and discoverable.

apps/api/plane/settings/mongo.py (2)

122-124: Ensuring init on is_configured(): LGTM

Triggering singleton initialization from is_configured aligns with the PR intent and unblocks connectivity checks.


122-124: Add targeted unit tests for MongoConnection and confirm caller resilience

  • Call-site audit:
    apps/api/plane/bgtasks/cleanup_task.py (lines 35–43) already checks MongoConnection.is_configured() before calling get_collection().
    • No other references to MongoConnection.(is_configured|get_db|get_client|get_collection) found.
    • No direct MongoClient(...) instantiations outside of apps/api/plane/settings/mongo.py.

  • Testing requirements:
    • Mock MongoClient to assert is_configured() returns:
    False when MONGO_DB_URL or MONGO_DB_DATABASE env vars are unset.
    True when env vars are set and MongoClient().ping() succeeds.
    False when env vars are set but MongoClient().ping() throws an error.
    • Cover get_client(), get_db(), and get_collection() for both configured and error paths.
    • Verify consumers (e.g., the cleanup task) handle is_configured() == False without assuming a DB is available.

@sriramveeraghanta sriramveeraghanta merged commit ddeabee into preview Aug 28, 2025
5 of 8 checks passed
@sriramveeraghanta sriramveeraghanta deleted the fix-mongo-connection branch August 28, 2025 08:27
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants