Repository navigation
feat(db): add MongoDB client options - #675
Conversation
MongoClient was built with PyMongo's defaults, so with MongoDB down, each request and the startup blocked for 30 seconds, and options could only be set via MONGO_URI. Add db.client_options, passed to MongoClient, with timeouts of 5 seconds and the service info's identifier as appname by default. Options in MONGO_URI win, with a warning on conflicts; FOCA has to enforce this, as keyword arguments win in PyMongo. Closes #618 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Parse options as PyMongo does (`;` as separator, `#` not special), so that options of the URI win in each form. Refuse username and password in client_options, which would override the URI. Skip app names that PyMongo would refuse. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Parse URI options with PyMongo's own function, which also splits on whitespace. Cut URIs for logs as PyMongo does, so that a # in a password no longer leaks its start. Closes #674 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Reviewer's GuideThe PR adds validated, configurable MongoDB client options across configuration and client creation, with shorter FOCA defaults, service-derived application names, and explicit deployment URI precedence. It also documents the behavior, updates mocks and comprehensive tests, and fixes credential redaction for passwords containing Sequence diagram for MongoDB client option resolutionsequenceDiagram
participant Config
participant Factory as create_mongo_client
participant PyMongo as MongoClient
participant URI as MONGO_URI
Config->>Config: _check_client_options()
Config->>Factory: get_mongo_client()
Factory->>Factory: _get_client_options()
Factory->>URI: split_options()
alt URI option overrides configured option
Factory-->>Factory: logger.warning()
Factory-->>PyMongo: omit option from keyword arguments
else option is not set in URI
Factory-->>PyMongo: pass defaults, appname, and client options
end
Factory->>PyMongo: MongoClient(uri, connect, options)
File-Level Changes
Possibly linked issues
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## dev #675 +/- ##
=========================================
Coverage 100.00% 100.00%
=========================================
Files 58 58
Lines 7499 7538 +39
=========================================
+ Hits 7499 7538 +39
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
Hey - I've found 5 issues
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="foca/database/register_mongodb.py" line_range="153" />
<code_context>
+ client: MongoClient[dict[str, Any]] = MongoClient(
+ uri,
+ connect=connect,
+ **_get_client_options(uri=uri, options=options or {}, appname=appname),
+ )
logger.info("Created MongoDB client for '%s'.", _redact_uri(uri))
</code_context>
<issue_to_address>
**URI credentials get overridden**
When a direct caller supplies `username` or `password` in `options` and the URI also contains credentials, `_get_client_options` forwards those options to PyMongo, which gives them precedence over the URI credentials; the client authenticates as a different user and bypasses the documented credential configuration path.
Reject `username` and `password` options when the URI supplies credentials.
Also at `foca/database/register_mongodb.py:205-206`.
</issue_to_address>
### Comment 2
<location path="foca/database/register_mongodb.py" line_range="108" />
<code_context>
port=conf.port,
db=next(iter(conf.dbs or {}), None),
connect=connect,
+ options=conf.client_options,
+ appname=conf._default_appname,
)
</code_context>
<issue_to_address>
**Invalid options pass startup unchecked**
When `db.client_options` contains an option PyMongo rejects and no configured database or other startup path creates a client, `register_mongodb()` creates a client only while iterating configured databases, so PyMongo never validates those options during startup; the app starts with the invalid setting and the error surfaces when a client is later created.
Validate `client_options` during startup even when no database causes a client to be created.
Also at `foca/models/config.py:2323`.
</issue_to_address>
### Comment 3
<location path="foca/database/register_mongodb.py" line_range="120" />
<code_context>
db: str | None = None,
connect: bool = True,
+ options: Mapping[str, Any] | None = None,
+ appname: str | None = None,
) -> MongoClient[dict[str, Any]]:
"""Create MongoDB client.
</code_context>
<issue_to_address>
**Standalone clients lack an app name**
When `create_mongo_client()` is called without an explicit `appname`, an `appname` option, or one in the URI, `create_mongo_client()` passes `appname=None` to `_get_client_options()`, which omits the option; MongoDB logs therefore lack the FOCA application name for these clients.
Give standalone clients a default FOCA application name when no app name is supplied.
Also at `foca/database/register_mongodb.py:203-205`, `docs/configuration/db.md:87`.
</issue_to_address>
### Comment 4
<location path="foca/models/config.py" line_range="2750" />
<code_context>
+ and name
+ and len(name.encode()) <= MAX_MONGO_APPNAME_BYTES
+ ):
+ self.db._default_appname = name
+ return self
</code_context>
<issue_to_address>
**Shared configs use the wrong app name**
When the same `MongoConfig` instance is reused by `Config` instances with different service names before a client is created, `Config._set_mongo_appname()` writes `_default_appname` to the shared `MongoConfig`, so the later validation overwrites the earlier app's name and its client is attributed to the wrong app in MongoDB logs.
Store the derived app name per `Config` instead of mutating the shared `MongoConfig`.
</issue_to_address>
### Comment 5
<location path="foca/database/register_mongodb.py" line_range="206" />
<code_context>
+ if appname is not None:
+ merged["appname"] = appname
+ merged.update({name.lower(): value for name, value in options.items()})
+ return {name: value for name, value in merged.items() if name not in in_uri}
+
+
</code_context>
<issue_to_address>
**Duplicate option values are discarded**
When `client_options` contains the same option under two names differing only by case, `_get_client_options` lowercases option names into a dict, so differently cased keys for the same option overwrite one another in mapping order without an error. The caller silently loses one configured value.
Reject duplicate option names after case normalization instead of silently selecting one value.
</issue_to_address>Linked issues
#618 feat(db): add MongoDB client options · 8 of 9 met · 1 to check by hand
| # | Requirement | Status | Notes |
|---|---|---|---|
| 1 | Add db.client_options as a mapping of PyMongo option names to scalar values; refuse options managed by FOCA or intended for environment variables. | ✅ Met | MongoConfig defines and validates client_options, and get_mongo_client passes it to MongoClient. |
| 2 | Default serverSelectionTimeoutMS and connectTimeoutMS to 5000. | ✅ Met | Both defaults are applied unless overridden by client_options or MONGO_URI. |
| 3 | Default appname to the service info id, or the package name. | ✅ Met | Config sets the default from the service id or package; names PyMongo would reject are skipped. |
| 4 | Let MONGO_URI options win and log a warning on conflict. | ✅ Met | URI option names are parsed with PyMongo's split_options(); matching configured options are omitted and their names are logged. |
| 5 | Fail at MongoClient creation for unknown options. | ✅ Met | Options are passed to PyMongo, which rejects unknown options; the tests cover this behavior. |
| 6 | Cover the model field, defaults, and pass-through in tests, with 100% coverage. | ✅ Met | Tests cover the field validation, defaults, pass-through, and invalid or unknown options; the PR reports 100% test coverage. |
| 7 | Document the field, defaults, and URI precedence on the database configuration page. | ✅ Met | The database configuration documentation describes these options and their precedence. |
| 8 | Mention the changed default timeout in release notes or the migration guide. | ✅ Met | docs/migration-0.21.md describes the timeout change. |
| 9 | Land the changed default by 1.0.0-rc1. | 👀 Check by hand (external system) | Check whether this change lands by the 1.0.0-rc1 release. |
#674 fix: redact passwords with # in MongoDB URIs · 2 of 2 met
| # | Requirement | Status | Notes |
|---|---|---|---|
| 1 | Redact credentials and options by cutting at the first ? and removing everything through the last @. | ✅ Met | _redact_uri applies that parsing and preserves the scheme, host, and path. |
| 2 | Add a regression test for a password containing #, preserving hosts and paths in the redacted form. | ✅ Met | The regression test checks a # in the password and verifies the redacted host and path. |
Sourcery assessment
Needs a human reviewer. 5 findings to address first, and the new client_options can change MongoDB security behavior, including TLS certificate verification, while the 5-second defaults can make requests or startup fail during slow connections or failovers. Reverting restores the prior client settings, but any data exposure or service outage that already occurred cannot be undone.
Blocking findings: foca/database/register_mongodb.py:153, foca/database/register_mongodb.py:108, foca/database/register_mongodb.py:120, foca/models/config.py:2750, foca/database/register_mongodb.py:206
Co-Authored-By: Claude Opus 5.5 <[email protected]>
There was a problem hiding this comment.
Linked issues
#618 feat(db): add MongoDB client options · 6 of 9 met · 2 to check by hand
| # | Requirement | Status | Notes |
|---|---|---|---|
| 1 | Add db.client_options as a mapping of scalar values using PyMongo option names. |
✅ Met | The MongoConfig field is passed to MongoClient by get_mongo_client. |
| 2 | Default serverSelectionTimeoutMS and connectTimeoutMS to 5000 unless configured otherwise. | ✅ Met | Both defaults are applied to clients, and configured options override them. |
| 3 | Default appname to the service-info identifier or package name. | 🟡 Partly met | This is done when Config has a db section, but clients created from the fallback MongoConfig used when it does not retain the generic foca name. |
| 4 | Let MONGO_URI options take precedence and warn on conflicts. | ✅ Met | URI option names are parsed with PyMongo's parser; warnings list conflicting configured names without values. |
| 5 | Fail at MongoClient creation for unknown options. | ✅ Met | Options are passed to MongoClient, which validates them; tests cover an unknown option. |
| 6 | Cover the model field, defaults and pass-through with tests at 100% coverage. | 👀 Check by hand (runtime) | The diff adds tests for the field, defaults and pass-through; confirm the reported 100% coverage in the test run. |
| 7 | Document the field, defaults and URI precedence on the database configuration page. | ✅ Met | The configuration page describes the field, defaults, and URI precedence. |
| 8 | Mention the changed default timeout in the release notes or migration guide. | ✅ Met | The 0.21 migration guide documents both shorter timeouts. |
| 9 | Land the changed default by 1.0.0-rc1. | 👀 Check by hand (manual process) | Confirm that this change is included by the 1.0.0-rc1 release. |
#674 fix: redact passwords with # in MongoDB URIs · 2 of 2 met
| # | Requirement | Status | Notes |
|---|---|---|---|
| 1 | Redact credentials and options by cutting the URI at the first ? and removing everything before the last @. |
✅ Met | The updated redaction logic follows those delimiters without treating # as a fragment. |
| 2 | Add a regression test for a # in the password and verify hosts and path remain in the redacted URI. |
✅ Met | The test includes a # in the password and checks the host and path in the expected redacted URI. |
There was a problem hiding this comment.
Linked issues
#618 feat(db): add MongoDB client options · 7 of 9 met · 1 to check by hand
| # | Requirement | Status | Notes |
|---|---|---|---|
| 1 | Add a scalar-valued db.client_options mapping using PyMongo option names, and reject reserved or duplicate names. |
✅ Met | MongoConfig defines and validates the field; its options are passed through get_mongo_client(). |
| 2 | Default serverSelectionTimeoutMS and connectTimeoutMS to 5000 unless overridden. |
✅ Met | The defaults are applied in _get_client_options() and are covered by tests. |
| 3 | Default appname to the service-info ID or package name. |
🟡 Partly met | The service-info ID or package name is used when Config.db exists, but the access-control fallback MongoConfig() retains foca even when that app has service info. |
| 4 | Let MONGO_URI options win and warn on conflicts. |
✅ Met | URI option names are parsed with PyMongo's parser; conflicts with configured options are warned about without logging their values. |
| 5 | Fail at client creation for unknown or invalid options. | ✅ Met | Options are passed to MongoClient, with tests covering unknown options and invalid types or values. |
| 6 | Cover the model field, defaults, and pass-through with tests (100% coverage). | ✅ Met | The new tests cover model validation, defaults, configured values, and real PyMongo client behavior. |
| 7 | Document the field, defaults, and URI precedence on the database configuration page. | ✅ Met | docs/configuration/db.md documents the options, defaults, restrictions, and precedence. |
| 8 | Mention the changed timeout default in the release notes or migration guide. | ✅ Met | docs/migration-0.21.md describes the five-second timeouts and how to override them. |
| 9 | Land the changed default by 1.0.0-rc1. | 👀 Check by hand (manual process) | Check that this change is included no later than the 1.0.0-rc1 release. |
#674 fix: redact passwords with # in MongoDB URIs · 2 of 2 met
| # | Requirement | Status | Notes |
|---|---|---|---|
| 1 | Redact credentials by cutting at the first ? and retaining everything after the last @. |
✅ Met | _redact_uri() uses that parsing, so # in a password is not treated as a fragment. |
| 2 | Add a regression test for a password containing #, preserving hosts and path in the redacted URI. |
✅ Met | The test covers a # in the password and checks that the hosts and path remain. |
Apps with access control but no `db` section got the default name in MongoDB's logs, not the one from their service info. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…nto feat/618-mongo-client-options
There was a problem hiding this comment.
Linked issues
#618 feat(db): add MongoDB client options · 5 of 7 met · 1 to check by hand
| # | Requirement | Status | Notes |
|---|---|---|---|
| 1 | Add db.client_options using PyMongo option names, pass options to MongoClient, and fail fast on unknown options. |
✅ Met | The config field is passed through the MongoDB client creation path, and tests cover invalid and unknown options. |
| 2 | Default the timeouts to 5000 ms and appname to the service ID or package name. |
✅ Met | The defaults and service-info naming are implemented, with tests for the timeout defaults and service ID/package cases. |
| 3 | Let options in MONGO_URI win and warn on conflicts. |
🟡 Partly met | Same-name options in the URI take precedence and conflicts are warned about, but aliases such as URI ssl and configured tls are not treated as the same option and can raise a conflict instead. |
| 4 | Cover the model field, defaults, and pass-through with tests at 100% coverage. | ✅ Met | The diff adds tests for the field, defaults, validation, pass-through, and real PyMongo behavior; the PR description reports 100% coverage. |
| 5 | Document the field, defaults, and URI precedence on the database configuration page. | ✅ Met | The database configuration page documents these, including the precedence behavior and its alias limitation. |
| 6 | Mention the changed timeout default in the release notes or migration guide. | ✅ Met | The migration guide describes the shorter MongoDB timeouts. |
| 7 | Land the changed default by 1.0.0-rc1. | 👀 Check by hand (external system) | Check the release schedule or target branch to confirm this change lands by 1.0.0-rc1. |
#674 fix: redact passwords with # in MongoDB URIs · 2 of 2 met
| # | Requirement | Status | Notes |
|---|---|---|---|
| 1 | Redact the URI by cutting at the first ? and keeping everything after the last @. |
✅ Met | The redaction helper uses that parsing approach, avoiding urlsplit() treating # in a password as a fragment. |
| 2 | Add a regression test for # in a password and verify the hosts and path remain in the redacted URI. |
✅ Met | The regression test includes # in the password and asserts the redacted hosts and path. |
…options # Conflicts: # docs/migration-0.21.md
Summary
db.client_options, passed toMongoClient, with PyMongo's names; unknown or invalid ones stop the app on startup.host,port,connect,usernameandpasswordare refused: they're set by FOCA or belong inMONGO_URI,MONGO_USERNAMEandMONGO_PASSWORD.serverSelectionTimeoutMSandconnectTimeoutMSof 5 seconds, instead of PyMongo's 30 and 20, andappnamefrom the service info. Changed defaults are indocs/migration-0.21.md.MONGO_URIwin, with a warning naming only the options. The issue says "as in PyMongo", which is wrong: in PyMongo, keyword arguments win (checked with a real client). FOCA enforces what the issue asks for, by leaving out what the connection string sets; names are parsed with PyMongo's ownsplit_options().docs/configuration/db.md, migration guide,templates/config.yaml._redact_uri()logged the start of a password containing#, asurlsplit()takes that for a fragment. Fixed here, as it's the same parsing in the same file.Closes #618
Closes #674
Verification
ruff check,ruff format --check,mypy,ast-grep scan,mkdocs build --strict: pass.pytestwith coverage: 100 %. Locally,tests/factories/test_celery_worker_fork.py::test_no_client_opened_before_forkdepends on which checkout the shared virtual environment has installed; see CI for the run on this branch.test_real_client,test_real_client_uri_wins).Declined review findings
Config:MongoConfigdoesn't know the service info, and the client is created in places without the config. Noted in a comment.dbsection, whose fallbackMongoConfigfor access control getsfoca: documented indocs/configuration/db.md.sslandtls: documented; PyMongo refuses them with different values (test_aliases_not_resolved).🤖 Generated with Claude Code
Summary by Sourcery
Support configurable MongoDB client behavior with safer defaults, deployment-level URI overrides, and clearer application identification.
New Features:
Bug Fixes:
Enhancements:
Documentation:
Tests: