Skip to content

Bugfix: avoid race condition when refreshing google token #2100

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

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
13 changes: 9 additions & 4 deletions pydantic_ai_slim/pydantic_ai/providers/google_vertex.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,8 @@ def __init__(
class _VertexAIAuth(httpx.Auth):
"""Auth class for Vertex AI API."""

_refresh_lock: anyio.Lock = anyio.Lock()

credentials: BaseCredentials | ServiceAccountCredentials | None

def __init__(
Expand Down Expand Up @@ -169,10 +171,13 @@ async def _get_credentials(self) -> BaseCredentials | ServiceAccountCredentials:
return creds

async def _refresh_token(self) -> str: # pragma: no cover
assert self.credentials is not None
await anyio.to_thread.run_sync(self.credentials.refresh, Request()) # type: ignore[reportUnknownMemberType]
assert isinstance(self.credentials.token, str), f'Expected token to be a string, got {self.credentials.token}' # type: ignore[reportUnknownMemberType]
return self.credentials.token
async with self._refresh_lock:
assert self.credentials is not None
await anyio.to_thread.run_sync(self.credentials.refresh, Request()) # type: ignore[reportUnknownMemberType]
assert isinstance(self.credentials.token, str), ( # type: ignore[reportUnknownMemberType]
f'Expected token to be a string, got {self.credentials.token}' # type: ignore[reportUnknownMemberType]
)
return self.credentials.token


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