Skip to content

Commit f98c1b6

Browse files
fix: re-use existing connections on force refresh (#828)
1 parent c13bcb1 commit f98c1b6

File tree

3 files changed

+6
-5
lines changed

3 files changed

+6
-5
lines changed

google/cloud/sql/connector/connector.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -280,7 +280,7 @@ async def connect_async(
280280

281281
except Exception:
282282
# with any exception, we attempt a force refresh, then throw the error
283-
instance.force_refresh()
283+
await instance.force_refresh()
284284
raise
285285

286286
def __enter__(self) -> Any:

google/cloud/sql/connector/instance.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -255,16 +255,17 @@ def __init__(
255255
self._current = self._schedule_refresh(0)
256256
self._next = self._current
257257

258-
def force_refresh(self) -> None:
258+
async def force_refresh(self) -> None:
259259
"""
260260
Forces a new refresh attempt immediately to be used for future connection attempts.
261261
"""
262262
# if next refresh is not already in progress, cancel it and schedule new one immediately
263263
if not self._refresh_in_progress.is_set():
264264
self._next.cancel()
265265
self._next = self._schedule_refresh(0)
266-
# block all sequential connection attempts on the next refresh result
267-
self._current = self._next
266+
# block all sequential connection attempts on the next refresh result if current is invalid
267+
if not await _is_valid(self._current):
268+
self._current = self._next
268269

269270
async def _perform_refresh(self) -> InstanceMetadata:
270271
"""Retrieves instance metadata and ephemeral certificate from the

tests/unit/test_instance.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -194,7 +194,7 @@ async def test_force_refresh_cancels_pending_refresh(
194194
pending_refresh = instance._next
195195
assert instance._refresh_in_progress.is_set() is False
196196

197-
instance.force_refresh()
197+
await instance.force_refresh()
198198

199199
# pending_refresh has to be awaited for it to raised as cancelled
200200
with pytest.raises(asyncio.CancelledError):

0 commit comments

Comments
 (0)