Repository navigation
Conversation
connect-mongo's `mongoUrl` option opens its own MongoClient once at construction and caches the connect promise. If MongoDB is down when the API boots, every session read/write replays that MongoServerSelectionError and every request with a session cookie returns 500 until a restart, even after connectDBWithRetry has connected mongoose (#2966). Back the session store with the mongoose connection instead: build a MongoStore on mongoose's client once it is connected, rebuild it when mongoose replaces the client, and fail session operations fast until then.
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
🦋 Changeset detectedLatest commit: 47ff983 The changes in this PR will be included in the next version bump. This PR includes changesets to release 3 packages
Not sure what this means? Click here to learn what changesets are. Click here if you're a maintainer who wants to add another changeset to this PR |
🔵 Tier 2 — Low RiskSmall, isolated change with no API route or data model modifications. Why this tier:
Review process: AI review + quick human skim (target: 5–15 min). Reviewer validates AI assessment and checks for domain-specific concerns. Stats
|
Duplicate code analysisNo new duplicate code introduced by this PR. jscpd compared this branch against |
PR Review
1 finding(s): 🔴 0 critical · 🟠 0 major · 🔵 1 minor None could be anchored to changed lines; they are listed below. Findings outside the changed lines1 minor
Severity is the reviewer's own estimate and is used for ordering, not filtering. No finding blocks merge automatically; a maintainer decides. |
|
Deep Review✅ No critical issues found. The change is well-scoped and defensively handles the close/rebuild race (with dedicated tests). Shutdown swallows rejections via 🟡 P2 -- recommended
🔵 P3 nitpicks (2)
Reviewers (8): correctness, reliability, adversarial, kieran-typescript, testing, maintainability, project-standards, previous-comments. Testing gaps: No coverage for the failure-counter reset-on-success semantics or the No finding blocks merge automatically. A maintainer will expect P0/P1 findings in code this PR changes to be fixed; P2/P3 are your call -- fix or reply. Never fix findings about surrounding code here; reply instead. Do not widen the PR. How to respond |
E2E Test Results✅ All tests passed • 408 passed • 1 skipped • 1329s
Tests ran across 4 shards in parallel. |
Use the shared isMongoConnected() readiness check so sessions and /ready agree on what "connected" means, drop a banner comment, and type the test helper's result instead of using any.
The mongoose (mongodb 4.x) to connect-mongo (mongodb 6.x types) client cast needs one eslint-disable; without it the warning pushes the api package over its --max-warnings ceiling. Raise the api eslint-disable ratchet baseline from 36 to 37 to match.
…t-disable" This reverts commit 6cc4d54.
Handing mongoose's client to connect-mongo needed a cast between mongoose's bundled mongodb 4.x types and the 6.x types connect-mongo is typed against. Instead, keep connect-mongo's own `mongoUrl` client, but only create the store once mongoose is connected and create a new one if its connect or setup fails. This drops the cast and its eslint-disable, and connect-mongo stays on the driver it already used.
A store whose client connected but whose setup (the TTL index) failed was dropped without closing its MongoClient, leaking a connection pool per failure. Close it, and wait with capped exponential backoff (1s to 30s, as connectDBWithRetry does) before building the next store so a persistent setup failure doesn't open a new client on every session operation.
The session store opens its own MongoClient, but Server.shutdown only closed mongoose's. Add MongoSessionStore.close(), which closes the current store and forgets it so a restarted server builds a new one, and call it from Server.shutdown. Also drop a guard in the failed-store handler that was always true.
| this.retryAt = | ||
| Date.now() + | ||
| Math.min( | ||
| REBUILD_BASE_DELAY_MS * 2 ** (this.failures - 1), |
There was a problem hiding this comment.
🔵 minor — Backoff schedule copied from connectDBWithRetry by hand
REBUILD_BASE_DELAY_MS, REBUILD_MAX_DELAY_MS and Math.min(base * 2 ** (n - 1), max) repeat the defaults and the formula in packages/api/src/models/index.ts:95-127. The comment 'Same schedule as connectDBWithRetry' only stays true while both are edited together. Move the defaults and a small backoffDelayMs(attempt, opts) helper into a shared module and use it in both places.
Advisory. Fix if it is a small defect in code this PR changes; otherwise reply in the thread. Do not widen the PR or touch files it did not already change. How to respond
| callback?: (err?: unknown) => void, | ||
| ) { | ||
| this.withStore(callback, store => | ||
| store.touch(sid, sess as Parameters<MongoStore['touch']>[1], callback), |
There was a problem hiding this comment.
🔵 minor — as cast in touch() goes against the 'Avoid as casts' convention
sess as Parameters<MongoStore['touch']>[1] bypasses type checking. Type touch's sess parameter as Parameters<MongoStore['touch']>[1] (it is compatible with express-session's Store signature) or use satisfies, instead of casting at the call site.
Advisory. Fix if it is a small defect in code this PR changes; otherwise reply in the thread. Do not widen the PR or touch files it did not already change. How to respond
The failed-store handler dropped the rejection reason, so a persistent setup failure (missing createIndex privilege, auth error on the store's client) only surfaced as the generic retry message during backoff. Log it with the failure count and retry delay, as connectDBWithRetry does, and count it in hyperdx.session_store.setup_failures.
close() replaces the current store, so a store whose setup rejects after close() could clear a newer store (leaking its client) and count the deliberate close as a setup failure, backing off the next start. Skip the handler when the store is no longer current, and reset the backoff in close() so a restarted server builds its store straight away.
Summary
If MongoDB is unreachable when the API starts, every request with a session cookie returns 500 for good, even after MongoDB is back.
/readygoes 200, but logged-in pages keep failing until the API restarts.The cause is the express-session store.
new MongoStore({ mongoUrl })opens its ownMongoClientonce, at construction, and every session read/write awaits that one connect promise. When it rejects, the store replays the originalMongoServerSelectionError: connect ECONNREFUSEDon every request. The mongoose connection recovers becauseconnectDBWithRetryretries it (#2966), but the session store never used that connection.This PR adds
MongoSessionStore(packages/api/src/utils/sessionStore.ts), a thinsession.Storearound the samenew MongoStore({ mongoUrl }):MongoStoreon first use once mongoose is connected (the sameisMongoConnected()check/readyuses), so the store's connect runs when MongoDB is reachable.connectDBWithRetry), instead of replaying the error forever.connect-mongokeeps its ownMongoClienton the API's mongodb 6.x driver, as before. Handing it mongoose's client instead would need a cast between mongoose's bundled mongodb 4.x types and the 6.x typesconnect-mongois typed against, and it breaks when mongoose reconnects with a new client (a closed client can't be reused).Server.shutdownnow also closes the session store's client, whichmainnever did.close()forgets the closed store, so a server started again in the same process (as the integration tests do) builds a new one.Tests:
utils/__tests__/sessionStore.test.ts.make dev-int FILE=dashboardspasses locally (10 suites, 544 tests). It includes a file that starts and stops the server twice and logs in each time./ready200, thenGET /methree times with the existing cookie. Result:mainreturned 500 500 500, and this branch returned 200 200 200.How to reproduce
Starting point: local full stack with
yarn dev(the bug needs the API and MongoDB).On
main:yarn dev, register, and stay logged in.docker stop <dev project>-db-1; the dev portal at http://localhost:9900 lists the project name).touch packages/api/src/index.tsso nodemon restarts it.Initial MongoDB connection failed, retrying, which takes about 30 s.GET /readyon the API to return 200./mereturns 500, and the API log showsMongoServerSelectionError: connect ECONNREFUSEDfromMongoClient.connect.On this branch:
How to test on Vercel preview
N/A, non-UI change.
References
/healthreturns 200 while MongoDB is unreachable — pod stays Ready, cannot serve, and crashloops collectors via OpAMP 500 #2966 / fix(api): retry initial MongoDB connect and add Mongo-aware /ready endpoints #2968 (initial MongoDB connect retry and/ready), [HDX-1874] Enable MongoStore Compatibility Mode to Reduce MongoDB Permission Requirements #928 (connect-mongoindex creation; touches the same store setup)🤖 Generated with Claude Code