:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(mongodb): replace raw pymongo connection error with a clear message (#63530)
Tom Owerscec758648e67
diff --git a/posthog/temporal/data_imports/sources/mongodb/source.py b/posthog/temporal/data_imports/sources/mongodb/source.pyindex 6af80349dbf3..3ecc167e3578 100644--- a/posthog/temporal/data_imports/sources/mongodb/source.py+++ b/posthog/temporal/data_imports/sources/mongodb/source.py@@ -47,6 +47,19 @@ _MONGO_ATLAS_SQL_MESSAGE = ("driver. Use your regular cluster connection string (e.g. mongodb+srv://...mongodb.net) instead.")+_MONGO_HOST_UNRESOLVED_MESSAGE = (+ "The MongoDB host could not be resolved. Check that the cluster address in your connection "+ "string is spelled correctly."+)++# Substrings pymongo embeds in ServerSelectionTimeoutError when the OS can't resolve the host.+_DNS_RESOLUTION_FAILURE_MARKERS = (+ "No address associated with hostname",+ "nodename nor servname provided",+ "Name or service not known",+ "Temporary failure in name resolution",+)+@SourceRegistry.registerclass MongoDBSource(SimpleSource[MongoDBSourceConfig], ValidateDatabaseHostMixin):@@ -150,7 +163,7 @@ class MongoDBSource(SimpleSource[MongoDBSourceConfig], ValidateDatabaseHostMixindef validate_credentials(self, config: MongoDBSourceConfig, team_id: int, schema_name: Optional[str] = None) -> tuple[bool, str | None]:- from pymongo.errors import OperationFailure+ from pymongo.errors import OperationFailure, ServerSelectionTimeoutErrortry:connection_params = _parse_connection_string(config.connection_string, config.database_name)@@ -177,6 +190,15 @@ class MongoDBSource(SimpleSource[MongoDBSourceConfig], ValidateDatabaseHostMixinexcept OperationFailure as e:capture_exception(e)return False, f"MongoDB authentication failed: {str(e)}"+ except ServerSelectionTimeoutError as e:+ # pymongo dumps a verbose topology description into str(e); surface a concise,+ # actionable message instead. A DNS failure means the host doesn't resolve at all,+ # which is distinct from an allowlist/reachability problem.+ capture_exception(e)+ message = str(e)+ if any(marker in message for marker in _DNS_RESOLUTION_FAILURE_MARKERS):+ return False, _MONGO_HOST_UNRESOLVED_MESSAGE+ return False, _MONGO_UNREACHABLE_MESSAGEexcept Exception as e:capture_exception(e)return False, f"Failed to connect to MongoDB database: {str(e)}"diff --git a/posthog/temporal/data_imports/sources/mongodb/test_database_name.py b/posthog/temporal/data_imports/sources/mongodb/test_database_name.pyindex a38f8e221fe2..9e703d724df4 100644--- a/posthog/temporal/data_imports/sources/mongodb/test_database_name.py+++ b/posthog/temporal/data_imports/sources/mongodb/test_database_name.py@@ -3,7 +3,12 @@ from unittest.mock import patchfrom posthog.temporal.data_imports.sources.generated_configs import MongoDBSourceConfigfrom posthog.temporal.data_imports.sources.mongodb.mongo import DATABASE_NAME_REQUIRED_ERROR, _parse_connection_string-from posthog.temporal.data_imports.sources.mongodb.source import MongoDBSource+from posthog.temporal.data_imports.sources.mongodb.source import (+ _DNS_RESOLUTION_FAILURE_MARKERS,+ _MONGO_HOST_UNRESOLVED_MESSAGE,+ _MONGO_UNREACHABLE_MESSAGE,+ MongoDBSource,+)_SRV_NO_DB = "mongodb+srv://user:[email protected]/?retryWrites=true&w=majority"_SRV_WITH_DB = "mongodb+srv://user:[email protected]/realdb?retryWrites=true"@@ -45,3 +50,37 @@ class TestMongoValidateCredentialsDatabaseName:assert ok is Trueassert err is None+++class TestMongoValidateCredentialsServerSelection:+ @pytest.mark.parametrize("marker", _DNS_RESOLUTION_FAILURE_MARKERS)+ @patch("posthog.temporal.data_imports.sources.mongodb.source.get_collection_names")+ def test_dns_resolution_failure_returns_unresolved_message(self, mock_get_collections, marker):+ from pymongo.errors import ServerSelectionTimeoutError++ # The verbose topology-description message pymongo raises when the host doesn't resolve.+ mock_get_collections.side_effect = ServerSelectionTimeoutError(+ f"cluster0.qwi73.mongodb.net:27017: [Errno -5] {marker} "+ "(configured timeouts: socketTimeoutMS: 20000.0ms), Topology Description: <TopologyDescription ...>"+ )+ config = MongoDBSourceConfig.from_dict({"connection_string": _SRV_WITH_DB})++ ok, err = MongoDBSource().validate_credentials(config, team_id=1)++ assert ok is False+ assert err == _MONGO_HOST_UNRESOLVED_MESSAGE+ assert "Topology Description" not in (err or "")++ @patch("posthog.temporal.data_imports.sources.mongodb.source.get_collection_names")+ def test_unreachable_cluster_returns_allowlist_message(self, mock_get_collections):+ from pymongo.errors import ServerSelectionTimeoutError++ mock_get_collections.side_effect = ServerSelectionTimeoutError(+ "No servers found yet, Topology Description: ..."+ )+ config = MongoDBSourceConfig.from_dict({"connection_string": _SRV_WITH_DB})++ ok, err = MongoDBSource().validate_credentials(config, team_id=1)++ assert ok is False+ assert err == _MONGO_UNREACHABLE_MESSAGE