Skip to content

Conversation

@mtrezza
Copy link
Member

@mtrezza mtrezza commented Jan 24, 2026

Pull Request

Issue

If MongoDB driver timeout parameters are set, and a timeout occurs, the error crashes with an uncaught exception, like this:

Uncaught internal server error. Timed out while checking out a connection from connection pool.

Original code:

throw new Parse.Error(Parse.Error.UNKNOWN_ERROR, error);

Crashing on database connection errors could be intentional, but wrapping it in Parse.Error suggests the intent was to send an error response to the client, not to crash.

Summary by CodeRabbit

  • Bug Fixes

    • Convert certain database connectivity errors into a generic "Database error" message for clients.
    • Better classify and handle transient database connectivity failures.
    • Sanitize client-facing error responses while preserving internal logging for diagnostics.
  • Tests

    • Added tests covering transient database error translation, non-transient cases, and null/undefined error handling.

✏️ Tip: You can customize this high-level summary in your review settings.

@parse-github-assistant
Copy link

parse-github-assistant bot commented Jan 24, 2026

🚀 Thanks for opening this pull request!

@parseplatformorg
Copy link
Contributor

parseplatformorg commented Jan 24, 2026

Snyk checks have passed. No issues have been found so far.

Status Scanner Critical High Medium Low Total (0)
Open Source Security 0 0 0 0 0 issues

💻 Catch issues earlier using the plugins for VS Code, JetBrains IDEs, Visual Studio, and Eclipse.

@coderabbitai
Copy link

coderabbitai bot commented Jan 24, 2026

📝 Walkthrough

Walkthrough

Classifies certain MongoDB errors as transient in MongoStorageAdapter and maps them to a generic Parse.Error("Database error"). Changes middleware error handling in handleParseSession to log the original error and call next() with a sanitized Parse.Error. Adds/updates tests asserting these behaviors.

Changes

Cohort / File(s) Summary
Mongo storage error handling
src/Adapters/Storage/Mongo/MongoStorageAdapter.js
Added isTransientError(error) and updated handleError() to map transient Mongo errors (MongoWaitQueueTimeoutError, MongoServerSelectionError, MongoNetworkTimeoutError, MongoNetworkError, TransientTransactionError) to Parse.Error(INTERNAL_SERVER_ERROR, "Database error").
Middleware error propagation
src/middlewares.js
In handleParseSession catch block: log the original error and propagate a sanitized Parse.Error(Parse.Error.UNKNOWN_ERROR, 'Unknown error') via next() instead of throwing.
Tests
spec/MongoStorageAdapter.spec.js, spec/ParseServer.spec.js, spec/index.spec.js
Added tests for transient error classification and transformation; updated expectations from Mongo-specific error messages to the generic "Database error" in existing tests.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Middleware
    participant StorageAdapter
    participant MongoDB

    Client->>Middleware: request
    Middleware->>StorageAdapter: perform DB operation
    StorageAdapter->>MongoDB: execute query/command

    rect rgba(255, 100, 100, 0.5)
    MongoDB-->>StorageAdapter: transient error (e.g., MongoServerSelectionError)
    end

    StorageAdapter->>StorageAdapter: isTransientError(error)?
    alt transient
        StorageAdapter->>StorageAdapter: create Parse.Error(INTERNAL_SERVER_ERROR,"Database error")
        StorageAdapter-->>Middleware: Parse.Error("Database error")
        Middleware->>Middleware: log original error
        Middleware-->>Client: sanitized error response
    else non-transient
        StorageAdapter-->>Middleware: original error
        Middleware-->>Client: original error response
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

🚥 Pre-merge checks | ✅ 2 | ❌ 1
❌ Failed checks (1 inconclusive)
Check name Status Explanation Resolution
Description check ❓ Inconclusive The description provides context about the issue (MongoDB timeout crashes) but does not fill out the 'Closes:' field linking to an issue or clearly document all changes and approach. Link this PR to a GitHub issue by filling in the 'Closes: ' field in the description template.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main change: fixing MongoDB timeout errors that were unhandled and potentially revealing internal data through Parse.Error.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

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

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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.

@mtrezza mtrezza changed the title fix: fix: MongoDB timeout errors unhandled and potentially revealing internal data Jan 24, 2026
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/middlewares.js (1)

376-384: Use INTERNAL_SERVER_ERROR to avoid returning 400 for internal failures.
handleParseErrors maps non-INTERNAL_SERVER_ERROR Parse errors to 400; this catch represents an internal auth resolution failure and should stay 500.

🛠️ Proposed fix
-    next(new Parse.Error(Parse.Error.UNKNOWN_ERROR, 'Unknown error'));
+    next(new Parse.Error(Parse.Error.INTERNAL_SERVER_ERROR, 'Unknown error'));

coderabbitai[bot]
coderabbitai bot previously approved these changes Jan 24, 2026
Signed-off-by: Manuel <5673677+mtrezza@users.noreply.github.com>
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: 1

🤖 Fix all issues with AI agents
In `@src/Adapters/Storage/Mongo/MongoStorageAdapter.js`:
- Around line 34-52: The if statements inside function isTransientError are
missing curly braces; update the function so each conditional block (the initial
null check "if (!error)", the transientErrorNames.include check "if
(transientErrorNames.includes(error.name))", and the nested label check "if
(error.hasErrorLabel('TransientTransactionError'))") uses braces around their
bodies to satisfy ESLint—i.e., wrap each single-line consequent in { ... } while
preserving current logic and return values.
🧹 Nitpick comments (1)
spec/MongoStorageAdapter.spec.js (1)

1067-1188: Add cleanup calls to prevent connection leaks.

These tests call adapter.connect() but don't call adapter.handleShutdown() afterwards. Other tests in this file (e.g., lines 863, 895, 998) follow the pattern of shutting down after testing. This could cause connection leaks during test runs.

♻️ Proposed fix for one test (apply similarly to others)
     it('should transform MongoWaitQueueTimeoutError to Parse.Error.INTERNAL_SERVER_ERROR', async () => {
       const adapter = new MongoStorageAdapter({ uri: databaseURI });
       await adapter.connect();

       // Create a mock error with the MongoWaitQueueTimeoutError name
       const mockError = new Error('Timed out while checking out a connection from connection pool');
       mockError.name = 'MongoWaitQueueTimeoutError';

       try {
         adapter.handleError(mockError);
         fail('Expected handleError to throw');
       } catch (error) {
         expect(error instanceof Parse.Error).toBe(true);
         expect(error.code).toBe(Parse.Error.INTERNAL_SERVER_ERROR);
         expect(error.message).toBe('Database error');
+      } finally {
+        await adapter.handleShutdown();
       }
     });

Alternatively, consider using a beforeEach/afterEach pattern for the adapter lifecycle within this describe block.

@codecov
Copy link

codecov bot commented Jan 24, 2026

Codecov Report

❌ Patch coverage is 92.30769% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 92.54%. Comparing base (756c204) to head (8064c6b).
⚠️ Report is 3 commits behind head on alpha.

Files with missing lines Patch % Lines
src/middlewares.js 0.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##            alpha   #10020      +/-   ##
==========================================
+ Coverage   92.12%   92.54%   +0.42%     
==========================================
  Files         190      190              
  Lines       15477    15489      +12     
  Branches      176      176              
==========================================
+ Hits        14258    14335      +77     
+ Misses       1203     1142      -61     
+ Partials       16       12       -4     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@mtrezza mtrezza merged commit 1d3336d into parse-community:alpha Jan 24, 2026
22 of 23 checks passed
parseplatformorg pushed a commit that referenced this pull request Jan 24, 2026
# [9.2.0-alpha.2](9.2.0-alpha.1...9.2.0-alpha.2) (2026-01-24)

### Bug Fixes

* MongoDB timeout errors unhandled and potentially revealing internal data ([#10020](#10020)) ([1d3336d](1d3336d))
@parseplatformorg
Copy link
Contributor

🎉 This change has been released in version 9.2.0-alpha.2

@parseplatformorg parseplatformorg added the state:released-alpha Released as alpha version label Jan 24, 2026
@mtrezza mtrezza deleted the fix/mongodb-errors branch January 24, 2026 23:16
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

state:released-alpha Released as alpha version

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants