Skip to content

chore: add check for closed connector #1269

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 9 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions google/cloud/sql/connector/connector.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
from google.cloud.sql.connector.enums import DriverMapping
from google.cloud.sql.connector.enums import IPTypes
from google.cloud.sql.connector.enums import RefreshStrategy
from google.cloud.sql.connector.exceptions import ClosedConnectorError
from google.cloud.sql.connector.instance import RefreshAheadCache
from google.cloud.sql.connector.lazy import LazyRefreshCache
from google.cloud.sql.connector.monitored_cache import MonitoredCache
Expand Down Expand Up @@ -153,6 +154,7 @@ def __init__(
# connection name string and enable_iam_auth boolean flag
self._cache: dict[tuple[str, bool], MonitoredCache] = {}
self._client: Optional[CloudSQLClient] = None
self._closed: bool = False

# initialize credentials
scopes = ["https://www.googleapis.com/auth/sqlservice.admin"]
Expand Down Expand Up @@ -242,6 +244,12 @@ def connect(
# connect runs sync database connections on background thread.
# Async database connections should call 'connect_async' directly to
# avoid hanging indefinitely.

# Check if the connector is closed before attempting to connect.
if self._closed:
raise ClosedConnectorError(
"Connection attempt failed because the connector has already been closed."
)
connect_future = asyncio.run_coroutine_threadsafe(
self.connect_async(instance_connection_string, driver, **kwargs),
self._loop,
Expand Down Expand Up @@ -279,7 +287,13 @@ async def connect_async(
and then subsequent attempt with IAM database authentication.
KeyError: Unsupported database driver Must be one of pymysql, asyncpg,
pg8000, and pytds.
RuntimeError: Connector has been closed. Cannot connect using a closed
Connector.
"""
if self._closed:
raise ClosedConnectorError(
"Connection attempt failed because the connector has already been closed."
)
if self._keys is None:
self._keys = asyncio.create_task(generate_keys())
if self._client is None:
Expand Down Expand Up @@ -462,13 +476,15 @@ def close(self) -> None:
self._loop.call_soon_threadsafe(self._loop.stop)
# wait for thread to finish closing (i.e. loop to stop)
self._thread.join()
self._closed = True
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is not necessary as synchronous close calls close_async so should get closed by close_async


async def close_async(self) -> None:
"""Helper function to cancel the cache's tasks
and close aiohttp.ClientSession."""
await asyncio.gather(*[cache.close() for cache in self._cache.values()])
if self._client:
await self._client.close()
self._closed = True


async def create_async_connector(
Expand Down
7 changes: 7 additions & 0 deletions google/cloud/sql/connector/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,3 +84,10 @@ class CacheClosedError(Exception):
Exception to be raised when a ConnectionInfoCache can not be accessed after
it is closed.
"""


class ClosedConnectorError(Exception):
"""
Exception to be raised when a Connector is closed and connect method is
called on it.
"""
46 changes: 46 additions & 0 deletions tests/unit/test_connector.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
from google.cloud.sql.connector import IPTypes
from google.cloud.sql.connector.client import CloudSQLClient
from google.cloud.sql.connector.connection_name import ConnectionName
from google.cloud.sql.connector.exceptions import ClosedConnectorError
from google.cloud.sql.connector.exceptions import CloudSQLIPTypeError
from google.cloud.sql.connector.exceptions import IncompatibleDriverError
from google.cloud.sql.connector.instance import RefreshAheadCache
Expand Down Expand Up @@ -468,3 +469,48 @@ def test_configured_quota_project_env_var(
assert connector._quota_project == quota_project
# unset env var
del os.environ["GOOGLE_CLOUD_QUOTA_PROJECT"]


@pytest.mark.asyncio
async def test_connect_async_closed_connector(
fake_credentials: Credentials, fake_client: CloudSQLClient
) -> None:
"""Test that calling connect_async() on a closed connector raises an error."""
async with Connector(
credentials=fake_credentials, loop=asyncio.get_running_loop()
) as connector:
connector._client = fake_client
await connector.close_async()
with pytest.raises(ClosedConnectorError) as exc_info:
await connector.connect_async(
"test-project:test-region:test-instance",
"asyncpg",
user="my-user",
password="my-pass",
db="my-db",
)
assert (
exc_info.value.args[0]
== "Connection attempt failed because the connector has already been closed."
)


def test_connect_closed_connector(
fake_credentials: Credentials, fake_client: CloudSQLClient
) -> None:
"""Test that calling connect() on a closed connector raises an error."""
with Connector(credentials=fake_credentials) as connector:
connector._client = fake_client
connector.close()
with pytest.raises(ClosedConnectorError) as exc_info:
connector.connect(
"test-project:test-region:test-instance",
"pg8000",
user="my-user",
password="my-pass",
db="my-db",
)
assert (
exc_info.value.args[0]
== "Connection attempt failed because the connector has already been closed."
)