Skip to content

Commit 46aa248

Browse files
JadHADDAD92Kludex
andauthored
Bugfix: avoid race condition when refreshing google token (#2100)
Co-authored-by: Marcelo Trylesinski <[email protected]>
1 parent 41640aa commit 46aa248

File tree

1 file changed

+9
-4
lines changed

1 file changed

+9
-4
lines changed

pydantic_ai_slim/pydantic_ai/providers/google_vertex.py

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,8 @@ def __init__(
116116
class _VertexAIAuth(httpx.Auth):
117117
"""Auth class for Vertex AI API."""
118118

119+
_refresh_lock: anyio.Lock = anyio.Lock()
120+
119121
credentials: BaseCredentials | ServiceAccountCredentials | None
120122

121123
def __init__(
@@ -169,10 +171,13 @@ async def _get_credentials(self) -> BaseCredentials | ServiceAccountCredentials:
169171
return creds
170172

171173
async def _refresh_token(self) -> str: # pragma: no cover
172-
assert self.credentials is not None
173-
await anyio.to_thread.run_sync(self.credentials.refresh, Request()) # type: ignore[reportUnknownMemberType]
174-
assert isinstance(self.credentials.token, str), f'Expected token to be a string, got {self.credentials.token}' # type: ignore[reportUnknownMemberType]
175-
return self.credentials.token
174+
async with self._refresh_lock:
175+
assert self.credentials is not None
176+
await anyio.to_thread.run_sync(self.credentials.refresh, Request()) # type: ignore[reportUnknownMemberType]
177+
assert isinstance(self.credentials.token, str), ( # type: ignore[reportUnknownMemberType]
178+
f'Expected token to be a string, got {self.credentials.token}' # type: ignore[reportUnknownMemberType]
179+
)
180+
return self.credentials.token
176181

177182

178183
async def _async_google_auth() -> tuple[BaseCredentials, str | None]:

0 commit comments

Comments
 (0)