Skip to content

Commit

Permalink
chore: improve connector.close (#239)
Browse files Browse the repository at this point in the history
  • Loading branch information
jackwotherspoon committed Jan 29, 2024
1 parent 3f14bb2 commit e9cbc0a
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 8 deletions.
22 changes: 14 additions & 8 deletions google/cloud/alloydb/connector/connector.py
Original file line number Diff line number Diff line change
Expand Up @@ -305,15 +305,17 @@ def __exit__(

def close(self) -> None:
"""Close Connector by stopping tasks and releasing resources."""
close_future = asyncio.run_coroutine_threadsafe(
self.close_async(), loop=self._loop
)
# Will attempt to gracefully shut down tasks for 3s
close_future.result(timeout=3)
if self._loop.is_running():
close_future = asyncio.run_coroutine_threadsafe(
self.close_async(), loop=self._loop
)
# Will attempt to gracefully shut down tasks for 3s
close_future.result(timeout=3)
# if background thread exists for Connector, clean it up
if self._thread:
# stop event loop running in background thread
self._loop.call_soon_threadsafe(self._loop.stop)
if self._thread.is_alive():
if self._loop.is_running():
# stop event loop running in background thread
self._loop.call_soon_threadsafe(self._loop.stop)
# wait for thread to finish closing (i.e. loop to stop)
self._thread.join()

Expand All @@ -325,3 +327,7 @@ async def close_async(self) -> None:
)
if self._client:
await self._client.close()

def __del__(self) -> None:
"""Close Connector as part of garbage collection"""
self.close()
13 changes: 13 additions & 0 deletions tests/unit/test_connector.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,3 +102,16 @@ def test_connect_unsupported_driver(credentials: FakeCredentials) -> None:
exc_info.value.args[0]
== "Driver 'bad_driver' is not a supported database driver."
)


def test_Connector_close_called_multiple_times(credentials: FakeCredentials) -> None:
"""Test that Connector.close can be called multiple times."""
# open and close Connector object
connector = Connector(credentials=credentials)
# verify background thread exists
assert connector._thread
connector.close()
# check that connector thread is no longer running
assert connector._thread.is_alive() is False
# call connector.close a second time
connector.close()

0 comments on commit e9cbc0a

Please sign in to comment.