|
34 | 34 | from google.cloud.sql.connector.enums import DriverMapping |
35 | 35 | from google.cloud.sql.connector.enums import IPTypes |
36 | 36 | from google.cloud.sql.connector.enums import RefreshStrategy |
| 37 | +from google.cloud.sql.connector.exceptions import ClosedConnectorError |
37 | 38 | from google.cloud.sql.connector.exceptions import ConnectorLoopError |
38 | 39 | from google.cloud.sql.connector.instance import RefreshAheadCache |
39 | 40 | from google.cloud.sql.connector.lazy import LazyRefreshCache |
@@ -155,6 +156,7 @@ def __init__( |
155 | 156 | # connection name string and enable_iam_auth boolean flag |
156 | 157 | self._cache: dict[tuple[str, bool], MonitoredCache] = {} |
157 | 158 | self._client: Optional[CloudSQLClient] = None |
| 159 | + self._closed: bool = False |
158 | 160 |
|
159 | 161 | # initialize credentials |
160 | 162 | scopes = ["https://www.googleapis.com/auth/sqlservice.admin"] |
@@ -244,6 +246,12 @@ def connect( |
244 | 246 | # connect runs sync database connections on background thread. |
245 | 247 | # Async database connections should call 'connect_async' directly to |
246 | 248 | # avoid hanging indefinitely. |
| 249 | + |
| 250 | + # Check if the connector is closed before attempting to connect. |
| 251 | + if self._closed: |
| 252 | + raise ClosedConnectorError( |
| 253 | + "Connection attempt failed because the connector has already been closed." |
| 254 | + ) |
247 | 255 | connect_future = asyncio.run_coroutine_threadsafe( |
248 | 256 | self.connect_async(instance_connection_string, driver, **kwargs), |
249 | 257 | self._loop, |
@@ -281,7 +289,13 @@ async def connect_async( |
281 | 289 | and then subsequent attempt with IAM database authentication. |
282 | 290 | KeyError: Unsupported database driver Must be one of pymysql, asyncpg, |
283 | 291 | pg8000, and pytds. |
| 292 | + RuntimeError: Connector has been closed. Cannot connect using a closed |
| 293 | + Connector. |
284 | 294 | """ |
| 295 | + if self._closed: |
| 296 | + raise ClosedConnectorError( |
| 297 | + "Connection attempt failed because the connector has already been closed." |
| 298 | + ) |
285 | 299 | # check if event loop is running in current thread |
286 | 300 | if self._loop != asyncio.get_running_loop(): |
287 | 301 | raise ConnectorLoopError( |
@@ -477,9 +491,10 @@ def close(self) -> None: |
477 | 491 | async def close_async(self) -> None: |
478 | 492 | """Helper function to cancel the cache's tasks |
479 | 493 | and close aiohttp.ClientSession.""" |
480 | | - await asyncio.gather(*[cache.close() for cache in self._cache.values()]) |
| 494 | + self._closed = True |
481 | 495 | if self._client: |
482 | 496 | await self._client.close() |
| 497 | + await asyncio.gather(*[cache.close() for cache in self._cache.values()]) |
483 | 498 |
|
484 | 499 |
|
485 | 500 | async def create_async_connector( |
|
0 commit comments