diff --git a/google/cloud/sql/connector/connector.py b/google/cloud/sql/connector/connector.py index 7a9964ca3..efbecc1e8 100644 --- a/google/cloud/sql/connector/connector.py +++ b/google/cloud/sql/connector/connector.py @@ -502,8 +502,12 @@ async def _remove_cached( logger.debug( f"['{instance_connection_string}']: Removing connection info from cache" ) - # remove cache from stored caches and close it - cache = self._cache.pop((instance_connection_string, enable_iam_auth)) + # remove cache from stored caches and close it. The entry can already be + # gone when multiple connection attempts for the same instance fail at + # the same time, in which case the first one has done the cleanup. + cache = self._cache.pop((instance_connection_string, enable_iam_auth), None) + if cache is None: + return await cache.close() def __enter__(self) -> Any: diff --git a/tests/unit/test_connector.py b/tests/unit/test_connector.py index 9b621a691..57f74846e 100644 --- a/tests/unit/test_connector.py +++ b/tests/unit/test_connector.py @@ -414,6 +414,45 @@ async def test_Connector_remove_cached_no_ip_type( assert (str(conn_name), False) not in connector._cache +async def test_Connector_remove_cached_shared_cache_concurrent_failure( + fake_credentials: Credentials, fake_client: CloudSQLClient +) -> None: + """When two connection attempts share a cache entry and both fail, each + caller should see the real error. The first caller removes the entry from + the cache, so the second must not trip over the missing key. + """ + # set instance to only have public IP + fake_client.instance.ip_addrs = {"PRIMARY": "127.0.0.1"} + async with Connector( + credentials=fake_credentials, loop=asyncio.get_running_loop() + ) as connector: + conn_name = ConnectionName("test-project", "test-region", "test-instance") + # populate cache + cache = RefreshAheadCache(conn_name, fake_client, connector._keys) + connector._cache[(str(conn_name), False)] = cache + # both attempts wait on the same cache entry, then fail the same way + results = await asyncio.gather( + connector.connect_async( + str(conn_name), + "pg8000", + user="my-user", + password="my-pass", + ip_type="private", + ), + connector.connect_async( + str(conn_name), + "pg8000", + user="my-user", + password="my-pass", + ip_type="private", + ), + return_exceptions=True, + ) + assert all(isinstance(r, CloudSQLIPTypeError) for r in results) + # check that cache has been removed from dict + assert (str(conn_name), False) not in connector._cache + + def test_default_universe_domain(fake_credentials: Credentials) -> None: """Test that default universe domain and constructed service endpoint are formatted correctly.