Skip to content

Conversation

aayushchouhan09
Copy link
Member

@aayushchouhan09 aayushchouhan09 commented Sep 4, 2025

Describe the Problem

The issue is with the NooBaa core code handling of the POSTGRES_CONNECTION_STRING_PATH parameter. When the NooBaa operator sets this environment variable but the connection string file doesn't exist or is not readable, the code uses fs.readFileSync() directly which throws an unhandled exception. This causes the NooBaa core pod to crash during operator installation, leading to CI job failures with CrashLoopBackOff errors.

Explain the Changes

  1. Added proper error handling for POSTGRES_CONNECTION_STRING_PATH by wrapping fs.readFileSync() in a try-catch block.

Issues: Fixed #xxx / Gap #xxx

  1. gap: Add missing envs for external pg db noobaa-operator#1689

Testing Instructions:

  • Doc added/updated
  • Tests added

Summary by CodeRabbit

  • New Features

    • Support configuring the database via a single Postgres connection string from an environment variable or a file, with automatic fallback to host/user/password/port/database settings. No breaking changes.
  • Bug Fixes

    • Improved error reporting when reading the connection string from a file, providing clearer failure messages to aid troubleshooting.

Copy link

coderabbitai bot commented Sep 4, 2025

Walkthrough

Constructor now wraps reading POSTGRES_CONNECTION_STRING_PATH in a try-catch and throws a descriptive Error on read failure. Retrieval precedence (ENV → file → discrete params) and public/exported signatures remain unchanged.

Changes

Cohort / File(s) Summary
Postgres connection string handling
src/util/postgres_client.js
Reading POSTGRES_CONNECTION_STRING_PATH is now wrapped in a try-catch; on read failure the constructor throws Error("Failed to read connection string file '${process.env.POSTGRES_CONNECTION_STRING_PATH}': ${err.message}"). Retains existing precedence (ENV > file > host/user/password/database/port) and no exported API signature changes.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant Env as Environment
  participant PC as PostgresClient
  participant FS as File System
  participant PG as PG Pool

  Env->>PC: POSTGRES_CONNECTION_STRING?
  alt Env var present
    PC->>PC: use env connection_string
  else Env var absent
    Env->>PC: POSTGRES_CONNECTION_STRING_PATH?
    alt Path present
      PC->>FS: read(path) wrapped in try-catch
      alt read success
        FS-->>PC: contents (connection_string)
      else read error
        FS-->>PC: error
        PC->>PC: throw Error("Failed to read connection string file 'PATH': ...")
        Note right of PC: constructor throws — initialization aborts
      end
    else Path absent or empty
      PC->>PC: No connection_string available
    end
  end

  alt connection_string available
    PC->>PG: new Pool({ connectionString, ...params })
  else
    PC->>PG: new Pool({ host,user,password,database,port,...params })
  end
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Pre-merge checks and finishing touches

✅ 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 "Added a fix for POSTGRES_CONNECTION_STRING_PATH handling" is concise and directly reflects the main change in the diff—adding error handling around reading the POSTGRES_CONNECTION_STRING_PATH file—so it clearly communicates the primary intent to reviewers.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.
✨ Finishing touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

📜 Recent review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3d4375b and b9183ac.

📒 Files selected for processing (1)
  • src/util/postgres_client.js (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/util/postgres_client.js
⏰ 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). (3)
  • GitHub Check: run-jest-unit-tests
  • GitHub Check: run-package-lock-validation
  • GitHub Check: Build Noobaa Image

Tip

👮 Agentic pre-merge checks are now available in preview!

Pro plan users can now enable pre-merge checks in their settings to enforce checklists before merging PRs.

  • Built-in checks – Quickly apply ready-made checks to enforce title conventions, require pull request descriptions that follow templates, validate linked issues for compliance, and more.
  • Custom agentic checks – Define your own rules using CodeRabbit’s advanced agentic capabilities to enforce organization-specific policies and workflows. For example, you can instruct CodeRabbit’s agent to verify that API documentation is updated whenever API schema files are modified in a PR. Note: Upto 5 custom checks are currently allowed during the preview period. Pricing for this feature will be announced in a few weeks.

Please see the documentation for more information.

Example:

reviews:
  pre_merge_checks:
    custom_checks:
      - name: "Undocumented Breaking Changes"
        mode: "warning"
        instructions: |
          Pass/fail criteria: All breaking changes to public APIs, CLI flags, environment variables, configuration keys, database schemas, or HTTP/GraphQL endpoints must be documented in the "Breaking Change" section of the PR description and in CHANGELOG.md. Exclude purely internal or private changes (e.g., code not exported from package entry points or explicitly marked as internal).

Please share your feedback with us on this Discord post.


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

@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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/util/postgres_client.js (1)

1426-1439: Override the database in admin ops when using connectionString
pg prioritizes the URL over any database field (so database: undefined won’t unset it). Extract and parse connectionString to point at a known admin DB (e.g. postgres) for createDatabase/dropDatabase. For example:

// in src/util/postgres_client.js
getAdminClientConfig() {
  const base = { ...this.new_pool_params };
  if (base.connectionString) {
    try {
      const u = new URL(base.connectionString);
      u.pathname = '/postgres';
      return { ...base, connectionString: u.toString(), database: undefined };
    } catch {
      return { ...base, database: undefined };
    }
  }
  return { ...base, database: undefined };
}

// then use:
pg_client = new Client(this.getAdminClientConfig());
🧹 Nitpick comments (1)
src/util/postgres_client.js (1)

1501-1508: Normalize the connection string (trim, handle Buffer) and prefer nullish coalescing.

Prevents subtle failures from trailing newlines and treats empty string as “set but unusable” only if you want that.

-const connection_string = process.env.POSTGRES_CONNECTION_STRING ||
-    fs_utils.try_read_file_sync(process.env.POSTGRES_CONNECTION_STRING_PATH);
+const raw_cs = process.env.POSTGRES_CONNECTION_STRING ?? fs_utils.try_read_file_sync(process.env.POSTGRES_CONNECTION_STRING_PATH);
+const connection_string = raw_cs && raw_cs.toString ? raw_cs.toString().trim() : raw_cs;
📜 Review details

Configuration used: Path: .coderabbit.yaml

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 0bf3bf6 and 2794be1.

📒 Files selected for processing (1)
  • src/util/postgres_client.js (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
src/util/postgres_client.js (2)
src/hosted_agents/hosted_agents.js (1)
  • fs_utils (13-13)
src/server/system_services/cluster_server.js (1)
  • fs_utils (17-17)
⏰ 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). (3)
  • GitHub Check: run-package-lock-validation
  • GitHub Check: Build Noobaa Image
  • GitHub Check: run-jest-unit-tests
🔇 Additional comments (1)
src/util/postgres_client.js (1)

1501-1503: Good hardening: stop crashing when POSTGRES_CONNECTION_STRING_PATH is unset.

Using fs_utils.try_read_file_sync avoids the throw from fs.readFileSync and meets the PR goal.

Copy link
Member

@dannyzaken dannyzaken left a comment

Choose a reason for hiding this comment

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

I commented here on the necessary changes in the mentioned operator PR. If there is an environment variable for POSTGRES_CONNECTION_STRING_PATH but the path does not exist, the code should fail instead of silently falling back to the else code.
We might want to catch the error from fs.readFileSync and throw a more descriptive error, so it is clear why the process crashes.

@aayushchouhan09
Copy link
Member Author

I commented here on the necessary changes in the mentioned operator PR. If there is an environment variable for POSTGRES_CONNECTION_STRING_PATH but the path does not exist, the code should fail instead of silently falling back to the else code. We might want to catch the error from fs.readFileSync and throw a more descriptive error, so it is clear why the process crashes.

This makes sense to me. I will remove the unnecessary code and update it to catch the error and throw a more descriptive one. Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants