visionai-sdk-python 2.2.0.dev1__py3-none-any.whl → 2.2.0.dev3__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- visionai_sdk_python/_base.py +46 -61
- visionai_sdk_python/async_client.py +50 -20
- visionai_sdk_python/auth/_mixin.py +1 -1
- visionai_sdk_python/auth/async_resource.py +15 -13
- visionai_sdk_python/auth/credentials.py +126 -68
- visionai_sdk_python/auth/resource.py +17 -13
- visionai_sdk_python/client.py +50 -20
- visionai_sdk_python/exceptions.py +51 -1
- visionai_sdk_python/relay/__init__.py +67 -0
- visionai_sdk_python/relay/protocol.py +178 -0
- visionai_sdk_python/vlm/async_resource.py +12 -18
- visionai_sdk_python/vlm/resource.py +12 -18
- {visionai_sdk_python-2.2.0.dev1.dist-info → visionai_sdk_python-2.2.0.dev3.dist-info}/METADATA +25 -10
- visionai_sdk_python-2.2.0.dev3.dist-info/RECORD +30 -0
- visionai_sdk_python-2.2.0.dev1.dist-info/RECORD +0 -28
- {visionai_sdk_python-2.2.0.dev1.dist-info → visionai_sdk_python-2.2.0.dev3.dist-info}/WHEEL +0 -0
- {visionai_sdk_python-2.2.0.dev1.dist-info → visionai_sdk_python-2.2.0.dev3.dist-info}/top_level.txt +0 -0
visionai_sdk_python/_base.py
CHANGED
|
@@ -5,16 +5,7 @@ import httpx
|
|
|
5
5
|
|
|
6
6
|
from ._jwt_verifier import JwtVerifier
|
|
7
7
|
from .constants import resolve_allowed_issuers
|
|
8
|
-
from .exceptions import
|
|
9
|
-
APIError,
|
|
10
|
-
AuthenticationError,
|
|
11
|
-
ClientError,
|
|
12
|
-
NetworkError,
|
|
13
|
-
PermissionDeniedError,
|
|
14
|
-
RateLimitedError,
|
|
15
|
-
ServerError,
|
|
16
|
-
VisionaiSDKError,
|
|
17
|
-
)
|
|
8
|
+
from .exceptions import raise_for_status
|
|
18
9
|
|
|
19
10
|
if TYPE_CHECKING:
|
|
20
11
|
from .auth.credentials import AsyncClientCredentials, ClientCredentials
|
|
@@ -53,8 +44,9 @@ class _BaseClient:
|
|
|
53
44
|
max_keepalive_connections: Maximum number of idle keep-alive connections.
|
|
54
45
|
credential: A ``ClientCredentials`` / ``AsyncClientCredentials`` whose
|
|
55
46
|
token every call uses; shareable between clients. Without it the
|
|
56
|
-
client keeps the token from ``auth.login()``
|
|
57
|
-
|
|
47
|
+
client keeps the token from ``auth.login()`` or ``set_token()``;
|
|
48
|
+
``auth.get_access_token()`` installs a credential. The last explicit
|
|
49
|
+
authentication wins.
|
|
58
50
|
"""
|
|
59
51
|
if not auth_url.strip():
|
|
60
52
|
raise ValueError("auth_url must not be empty")
|
|
@@ -83,27 +75,49 @@ class _BaseClient:
|
|
|
83
75
|
self._access_token: str | None = None
|
|
84
76
|
self._token_expires_at: float | None = None # monotonic time
|
|
85
77
|
self._credentials: dict | None = None
|
|
86
|
-
self._credentials_type: Literal["login"
|
|
78
|
+
self._credentials_type: Literal["login"] | None = None
|
|
79
|
+
|
|
80
|
+
@property
|
|
81
|
+
def credential(self) -> "ClientCredentials | AsyncClientCredentials | None":
|
|
82
|
+
"""The credential this client was built with, for callers that need the
|
|
83
|
+
raw token themselves (a WebSocket upgrade, another HTTP library)."""
|
|
84
|
+
return self._credential
|
|
87
85
|
|
|
88
86
|
@staticmethod
|
|
89
87
|
def _build_url(base_url: str, path: str) -> str:
|
|
90
88
|
"""Join a base URL and a path, normalizing slashes."""
|
|
91
89
|
return f"{base_url.rstrip('/')}/{path.lstrip('/')}"
|
|
92
90
|
|
|
93
|
-
|
|
91
|
+
@staticmethod
|
|
92
|
+
def _full_url(url: str) -> str:
|
|
93
|
+
"""``request()`` takes a full URL: the client has two bases (``auth_url``,
|
|
94
|
+
``vlm_url``), so a bare path would not say which one is meant."""
|
|
95
|
+
if "://" not in url:
|
|
96
|
+
raise ValueError(f"request() needs a full URL, got {url!r}")
|
|
97
|
+
return url
|
|
98
|
+
|
|
99
|
+
def _with_auth(self, kwargs: dict, token: str) -> dict:
|
|
100
|
+
"""``kwargs`` for httpx with the bearer header; the client's token wins."""
|
|
101
|
+
headers = httpx.Headers(kwargs.get("headers"))
|
|
102
|
+
headers["Authorization"] = f"Bearer {token}" # case-insensitive: one header
|
|
103
|
+
return {**kwargs, "headers": headers}
|
|
104
|
+
|
|
105
|
+
@staticmethod
|
|
106
|
+
def _resendable(kwargs: dict) -> bool:
|
|
107
|
+
"""Whether the body can be sent a second time (streams and files cannot)."""
|
|
108
|
+
content = kwargs.get("content")
|
|
109
|
+
if content is not None and not isinstance(content, (bytes, str)):
|
|
110
|
+
return False
|
|
111
|
+
if kwargs.get("files") is not None:
|
|
112
|
+
return False
|
|
113
|
+
data = kwargs.get("data")
|
|
114
|
+
return data is None or isinstance(data, dict)
|
|
115
|
+
|
|
116
|
+
def _require_vlm_url(self) -> str:
|
|
94
117
|
if self.vlm_url is None:
|
|
95
118
|
raise ValueError("vlm_url is required for VLM calls; pass it to the client")
|
|
96
119
|
return self.vlm_url
|
|
97
120
|
|
|
98
|
-
@staticmethod
|
|
99
|
-
def _map_transport_error(error: httpx.RequestError) -> VisionaiSDKError:
|
|
100
|
-
"""The SDK exception for an httpx request that never got a response."""
|
|
101
|
-
if isinstance(error, httpx.TimeoutException):
|
|
102
|
-
return NetworkError("Request timed out")
|
|
103
|
-
if isinstance(error, httpx.NetworkError):
|
|
104
|
-
return NetworkError(f"Network error: {error}")
|
|
105
|
-
return VisionaiSDKError(f"Request failed: {error}")
|
|
106
|
-
|
|
107
121
|
@staticmethod
|
|
108
122
|
def _build_auth_header(access_token: str) -> dict[str, str]:
|
|
109
123
|
"""Build authorization header."""
|
|
@@ -116,16 +130,20 @@ class _BaseClient:
|
|
|
116
130
|
access_token: str,
|
|
117
131
|
expires_in: int,
|
|
118
132
|
credentials: dict | None = None,
|
|
119
|
-
credentials_type: Literal["login"
|
|
133
|
+
credentials_type: Literal["login"] | None = None,
|
|
120
134
|
) -> None:
|
|
121
|
-
"""
|
|
135
|
+
"""Use this token from now on; a credential set earlier is dropped.
|
|
136
|
+
|
|
137
|
+
The last explicit authentication wins, in both directions.
|
|
122
138
|
|
|
123
139
|
Args:
|
|
124
140
|
access_token: JWT access token.
|
|
125
141
|
expires_in: Token expiration time in seconds.
|
|
126
142
|
credentials: Optional credentials for auto-refresh.
|
|
127
|
-
credentials_type:
|
|
143
|
+
credentials_type: "login" for email / password credentials; client
|
|
144
|
+
credentials live in a ``ClientCredentials`` on the client instead.
|
|
128
145
|
"""
|
|
146
|
+
self._credential = None
|
|
129
147
|
self._access_token = access_token
|
|
130
148
|
self._token_expires_at = time.monotonic() + expires_in
|
|
131
149
|
self._credentials = credentials
|
|
@@ -201,38 +219,5 @@ class _BaseClient:
|
|
|
201
219
|
|
|
202
220
|
@staticmethod
|
|
203
221
|
def _handle_response(response: httpx.Response) -> httpx.Response:
|
|
204
|
-
"""Raise SDK
|
|
205
|
-
|
|
206
|
-
Raises:
|
|
207
|
-
AuthenticationError: If the server returns 401
|
|
208
|
-
PermissionDeniedError: If the server returns 403
|
|
209
|
-
ClientError: If the server returns any other 4xx
|
|
210
|
-
ServerError: If the server returns 5xx
|
|
211
|
-
APIError: If the server returns any other non-2xx status
|
|
212
|
-
"""
|
|
213
|
-
try:
|
|
214
|
-
response.raise_for_status()
|
|
215
|
-
except httpx.HTTPStatusError as e:
|
|
216
|
-
body = None
|
|
217
|
-
if e.response.content:
|
|
218
|
-
try:
|
|
219
|
-
body = e.response.json()
|
|
220
|
-
except Exception:
|
|
221
|
-
pass
|
|
222
|
-
if isinstance(body, dict):
|
|
223
|
-
detail: str = body.get("detail") or body.get("message") or str(e)
|
|
224
|
-
else:
|
|
225
|
-
detail = str(e)
|
|
226
|
-
status = e.response.status_code
|
|
227
|
-
if status == 401:
|
|
228
|
-
raise AuthenticationError(detail) from e
|
|
229
|
-
if status == 403:
|
|
230
|
-
raise PermissionDeniedError(detail) from e
|
|
231
|
-
if status == 429:
|
|
232
|
-
raise RateLimitedError(detail) from e
|
|
233
|
-
if 400 <= status < 500:
|
|
234
|
-
raise ClientError(status, detail) from e
|
|
235
|
-
if 500 <= status < 600:
|
|
236
|
-
raise ServerError(status, detail) from e
|
|
237
|
-
raise APIError(status, detail) from e
|
|
238
|
-
return response
|
|
222
|
+
"""Raise the SDK exception for a non-2xx response (``exceptions.raise_for_status``)."""
|
|
223
|
+
return raise_for_status(response)
|
|
@@ -4,7 +4,7 @@ from ._base import _BaseClient
|
|
|
4
4
|
from ._request_attribution import merge_request_attribution
|
|
5
5
|
from .auth.async_resource import AsyncAuthResource
|
|
6
6
|
from .auth.credentials import AsyncClientCredentials
|
|
7
|
-
from .exceptions import AuthenticationError
|
|
7
|
+
from .exceptions import AuthenticationError, from_transport_error
|
|
8
8
|
from .vlm.async_resource import AsyncVLMResource
|
|
9
9
|
|
|
10
10
|
|
|
@@ -19,7 +19,10 @@ class AsyncClient(_BaseClient):
|
|
|
19
19
|
max_connections: int = 100,
|
|
20
20
|
max_keepalive_connections: int = 20,
|
|
21
21
|
credential: AsyncClientCredentials | None = None,
|
|
22
|
+
http_client: httpx.AsyncClient | None = None,
|
|
22
23
|
) -> None:
|
|
24
|
+
"""See ``_BaseClient``; ``http_client`` is an httpx.AsyncClient to send through
|
|
25
|
+
(tests, shared pools); the client closes only the one it created."""
|
|
23
26
|
super().__init__(
|
|
24
27
|
auth_url=auth_url,
|
|
25
28
|
vlm_url=vlm_url,
|
|
@@ -30,7 +33,7 @@ class AsyncClient(_BaseClient):
|
|
|
30
33
|
max_keepalive_connections=max_keepalive_connections,
|
|
31
34
|
credential=credential,
|
|
32
35
|
)
|
|
33
|
-
self._client = httpx.AsyncClient(
|
|
36
|
+
self._client = http_client or httpx.AsyncClient(
|
|
34
37
|
verify=self.verify_ssl,
|
|
35
38
|
timeout=self.timeout,
|
|
36
39
|
limits=httpx.Limits(
|
|
@@ -38,6 +41,7 @@ class AsyncClient(_BaseClient):
|
|
|
38
41
|
max_keepalive_connections=self.max_keepalive_connections,
|
|
39
42
|
),
|
|
40
43
|
)
|
|
44
|
+
self._http_owner = http_client is None # a client we built is ours to close
|
|
41
45
|
# Register the different function resource
|
|
42
46
|
self.auth = AsyncAuthResource(self)
|
|
43
47
|
self.vlm = AsyncVLMResource(self)
|
|
@@ -48,12 +52,42 @@ class AsyncClient(_BaseClient):
|
|
|
48
52
|
try:
|
|
49
53
|
response = await self._client.request(method, url, **kwargs)
|
|
50
54
|
except httpx.RequestError as e:
|
|
51
|
-
raise
|
|
55
|
+
raise from_transport_error(e) from e
|
|
52
56
|
return self._handle_response(response)
|
|
53
57
|
|
|
58
|
+
async def request(self, method: str, url: str, **kwargs) -> httpx.Response:
|
|
59
|
+
"""Send any request with this client's bearer token.
|
|
60
|
+
|
|
61
|
+
``url`` is a full URL (the client has two bases); ``kwargs`` go to httpx.
|
|
62
|
+
With a ``credential``, a 401 buys one retry with the credential's current
|
|
63
|
+
token, which it replaces when the rejected one is old enough to have been
|
|
64
|
+
revoked (``REPLACE_COOLDOWN_S``); a 401 on the retry raises. Without a
|
|
65
|
+
credential, or with a body that cannot be sent twice (a stream or a
|
|
66
|
+
file), a 401 raises.
|
|
67
|
+
|
|
68
|
+
Raises:
|
|
69
|
+
ValueError: ``url`` is not a full URL.
|
|
70
|
+
AuthenticationError: No token, or the fresh one was refused too.
|
|
71
|
+
RateLimitedError, NetworkError, ServerError, ClientError: As the
|
|
72
|
+
resource methods.
|
|
73
|
+
"""
|
|
74
|
+
url = self._full_url(url)
|
|
75
|
+
token = await self._ensure_token()
|
|
76
|
+
try:
|
|
77
|
+
return await self._request(method, url, **self._with_auth(kwargs, token))
|
|
78
|
+
except AuthenticationError:
|
|
79
|
+
if self._credential is None or not self._resendable(kwargs):
|
|
80
|
+
raise
|
|
81
|
+
self._credential.invalidate(token)
|
|
82
|
+
replacement = (await self._credential.get_token()).token
|
|
83
|
+
if replacement == token:
|
|
84
|
+
raise
|
|
85
|
+
return await self._request(method, url, **self._with_auth(kwargs, replacement))
|
|
86
|
+
|
|
54
87
|
async def close(self) -> None:
|
|
55
|
-
"""Close the HTTP client and release connections."""
|
|
56
|
-
|
|
88
|
+
"""Close the HTTP client this client created and release its connections."""
|
|
89
|
+
if self._http_owner:
|
|
90
|
+
await self._client.aclose()
|
|
57
91
|
|
|
58
92
|
async def __aenter__(self) -> "AsyncClient":
|
|
59
93
|
"""Async context manager entry."""
|
|
@@ -64,7 +98,9 @@ class AsyncClient(_BaseClient):
|
|
|
64
98
|
await self.close()
|
|
65
99
|
|
|
66
100
|
async def _refresh_token(self) -> None:
|
|
67
|
-
"""Refresh token
|
|
101
|
+
"""Refresh the token with the stored login credentials.
|
|
102
|
+
|
|
103
|
+
Client credentials refresh through the credential object instead.
|
|
68
104
|
|
|
69
105
|
Raises:
|
|
70
106
|
AuthenticationError: If no credentials are stored or refresh fails.
|
|
@@ -72,26 +108,19 @@ class AsyncClient(_BaseClient):
|
|
|
72
108
|
if self._credentials is None or self._credentials_type is None:
|
|
73
109
|
raise AuthenticationError("No credentials available for token refresh")
|
|
74
110
|
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
)
|
|
80
|
-
elif self._credentials_type == "client":
|
|
81
|
-
await self.auth.get_access_token(
|
|
82
|
-
client_id=self._credentials["client_id"],
|
|
83
|
-
client_secret=self._credentials["client_secret"],
|
|
84
|
-
)
|
|
111
|
+
await self.auth.login(
|
|
112
|
+
email=self._credentials["email"],
|
|
113
|
+
password=self._credentials["password"],
|
|
114
|
+
)
|
|
85
115
|
|
|
86
|
-
async def _ensure_token(self) ->
|
|
87
|
-
"""
|
|
116
|
+
async def _ensure_token(self) -> str:
|
|
117
|
+
"""The token to send: the credential's, else the stored one, refreshed if expiring.
|
|
88
118
|
|
|
89
119
|
Raises:
|
|
90
120
|
AuthenticationError: If no token is available or token expired without credentials.
|
|
91
121
|
"""
|
|
92
122
|
if self._credential is not None:
|
|
93
|
-
|
|
94
|
-
return
|
|
123
|
+
return (await self._credential.get_token()).token
|
|
95
124
|
if self._access_token is None:
|
|
96
125
|
raise AuthenticationError(
|
|
97
126
|
"Not authenticated. Call login() or get_access_token() first."
|
|
@@ -103,3 +132,4 @@ class AsyncClient(_BaseClient):
|
|
|
103
132
|
"Token expired and no credentials available for refresh"
|
|
104
133
|
)
|
|
105
134
|
await self._refresh_token()
|
|
135
|
+
return self._access_token
|
|
@@ -97,7 +97,7 @@ class AuthMixin:
|
|
|
97
97
|
Args:
|
|
98
98
|
response_data: Response JSON data
|
|
99
99
|
credentials: Credentials dict for auto-refresh
|
|
100
|
-
credentials_type: Type of credentials ("login"
|
|
100
|
+
credentials_type: Type of credentials ("login")
|
|
101
101
|
|
|
102
102
|
Returns:
|
|
103
103
|
Parsed TokenResponse
|
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
"""Authentication resource for async operations."""
|
|
2
2
|
|
|
3
|
-
import time
|
|
4
3
|
from typing import TYPE_CHECKING
|
|
5
4
|
|
|
6
5
|
import jwt
|
|
@@ -29,13 +28,16 @@ class AsyncAuthResource(AuthMixin):
|
|
|
29
28
|
self._sdk_client = client
|
|
30
29
|
|
|
31
30
|
async def get_access_token(
|
|
32
|
-
self, client_id: str, client_secret: str
|
|
31
|
+
self, client_id: str, client_secret: str, *, force_refresh: bool = False
|
|
33
32
|
) -> TokenResponse:
|
|
34
33
|
"""Get access token using client credentials flow.
|
|
35
34
|
|
|
36
|
-
The
|
|
37
|
-
|
|
38
|
-
|
|
35
|
+
The client keeps the resulting credential and uses it for subsequent API
|
|
36
|
+
calls, minting a new token when the current one expires. Calling this
|
|
37
|
+
again with the same client credentials returns the cached token;
|
|
38
|
+
``force_refresh=True`` mints a new one. A later ``login()`` or
|
|
39
|
+
``set_token()`` replaces the credential: the last explicit
|
|
40
|
+
authentication wins.
|
|
39
41
|
|
|
40
42
|
New code should build a ``ClientCredentials`` / ``AsyncClientCredentials``
|
|
41
43
|
and pass it as ``credential=`` to the client instead; this method stays for
|
|
@@ -44,6 +46,7 @@ class AsyncAuthResource(AuthMixin):
|
|
|
44
46
|
Args:
|
|
45
47
|
client_id: OAuth client ID
|
|
46
48
|
client_secret: OAuth client secret
|
|
49
|
+
force_refresh: Mint a new token even if a fresh one is cached.
|
|
47
50
|
|
|
48
51
|
Returns:
|
|
49
52
|
TokenResponse with access_token, expires_in, and token_type
|
|
@@ -70,16 +73,15 @@ class AsyncAuthResource(AuthMixin):
|
|
|
70
73
|
client_secret,
|
|
71
74
|
http=self._sdk_client._client,
|
|
72
75
|
)
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
+
token = await credential.get_token(force_refresh=force_refresh)
|
|
77
|
+
# Installed only once it works, and over a login() / set_token() token:
|
|
78
|
+
# the last explicit authentication wins.
|
|
79
|
+
self._sdk_client._credential = credential
|
|
80
|
+
return TokenResponse(
|
|
76
81
|
access_token=token.token,
|
|
77
|
-
expires_in=
|
|
78
|
-
|
|
79
|
-
credentials_type="client",
|
|
82
|
+
expires_in=token.expires_in(),
|
|
83
|
+
token_type=token.token_type,
|
|
80
84
|
)
|
|
81
|
-
assert credential.last_response is not None
|
|
82
|
-
return credential.last_response
|
|
83
85
|
|
|
84
86
|
async def login(self, email: str, password: str) -> TokenResponse:
|
|
85
87
|
"""Login with email and password to get JWT token.
|
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
"""One client-credentials token for every client and caller in a process.
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
3
|
+
A mint is a round trip to Platform and, on sites that cap client tokens, a
|
|
4
|
+
scarce one, so the token is cached until shortly before it expires, one mint
|
|
5
|
+
runs at a time, a refresh that fails keeps the current token while Platform
|
|
6
|
+
still accepts it, a 401 replaces a token that is old enough to have been
|
|
7
|
+
revoked, and a 429 stops minting for an hour.
|
|
6
8
|
"""
|
|
7
9
|
|
|
8
10
|
from __future__ import annotations
|
|
@@ -20,31 +22,43 @@ import httpx
|
|
|
20
22
|
from .._base import _BaseClient
|
|
21
23
|
from .._request_attribution import merge_request_attribution
|
|
22
24
|
from ..endpoints import AuthEndpoint
|
|
23
|
-
from ..exceptions import
|
|
25
|
+
from ..exceptions import (
|
|
26
|
+
RateLimitedError,
|
|
27
|
+
VisionaiSDKError,
|
|
28
|
+
from_transport_error,
|
|
29
|
+
raise_for_status,
|
|
30
|
+
)
|
|
24
31
|
from .models import TokenResponse
|
|
25
32
|
|
|
26
33
|
logger = logging.getLogger(__name__)
|
|
27
34
|
|
|
28
|
-
# A token
|
|
35
|
+
# A token is refreshed this long before it expires, or at half its lifetime when
|
|
36
|
+
# that is sooner, so a token is never served after Platform stops accepting it.
|
|
29
37
|
REFRESH_BUFFER_S = 300
|
|
30
|
-
#
|
|
31
|
-
|
|
32
|
-
#
|
|
33
|
-
|
|
38
|
+
# After a 429 no mint is tried for this long.
|
|
39
|
+
RATE_LIMIT_COOLDOWN_S = 3600
|
|
40
|
+
# A 401 on a token minted less than this long ago does not replace it.
|
|
41
|
+
REPLACE_COOLDOWN_S = 30 * 60
|
|
34
42
|
|
|
35
43
|
_now = time.monotonic
|
|
36
44
|
|
|
37
45
|
|
|
38
46
|
@dataclass(frozen=True)
|
|
39
47
|
class AccessToken:
|
|
40
|
-
"""A bearer token
|
|
48
|
+
"""A bearer token with the ``time.monotonic()`` seconds it expires at and was issued."""
|
|
41
49
|
|
|
42
50
|
token: str
|
|
43
51
|
expires_on: float
|
|
52
|
+
token_type: str
|
|
53
|
+
issued_at: float
|
|
54
|
+
|
|
55
|
+
def expires_in(self) -> int:
|
|
56
|
+
"""Seconds left before ``expires_on``, never negative."""
|
|
57
|
+
return max(int(self.expires_on - _now()), 0)
|
|
44
58
|
|
|
45
59
|
|
|
46
60
|
class _Credentials:
|
|
47
|
-
"""What the sync and async variants share: the cache, the 401 and 429 rules."""
|
|
61
|
+
"""What the sync and async variants share: the cache, the refresh, 401 and 429 rules."""
|
|
48
62
|
|
|
49
63
|
def __init__(self, auth_url: str, client_id: str, client_secret: str) -> None:
|
|
50
64
|
if not auth_url.strip():
|
|
@@ -57,12 +71,9 @@ class _Credentials:
|
|
|
57
71
|
self.client_id = client_id.strip()
|
|
58
72
|
self._client_secret = client_secret
|
|
59
73
|
self._url = _BaseClient._build_url(self.auth_url, AuthEndpoint.CLIENT_TOKEN)
|
|
60
|
-
self.
|
|
61
|
-
#: The last token endpoint response, for callers that want ``token_type`` too.
|
|
62
|
-
self.last_response: TokenResponse | None = None
|
|
63
|
-
# True while the cached token is the replacement a 401 bought.
|
|
64
|
-
self._replaced = False
|
|
74
|
+
self._current: AccessToken | None = None # the token this credential holds
|
|
65
75
|
self._blocked_until = 0.0
|
|
76
|
+
self._minting = False # a mint is in flight (set under the lock)
|
|
66
77
|
|
|
67
78
|
def is_for(self, client_id: str, client_secret: str) -> bool:
|
|
68
79
|
"""True when this credential was built for exactly these client credentials."""
|
|
@@ -70,63 +81,89 @@ class _Credentials:
|
|
|
70
81
|
self._client_secret, client_secret
|
|
71
82
|
)
|
|
72
83
|
|
|
73
|
-
def
|
|
74
|
-
|
|
75
|
-
|
|
84
|
+
def _fresh(self) -> AccessToken | None:
|
|
85
|
+
"""The current token while it is not yet due for a refresh."""
|
|
86
|
+
token = self._current
|
|
87
|
+
if token is None:
|
|
88
|
+
return None
|
|
89
|
+
buffer = min(REFRESH_BUFFER_S, (token.expires_on - token.issued_at) / 2)
|
|
90
|
+
return token if _now() < token.expires_on - buffer else None
|
|
91
|
+
|
|
92
|
+
def _valid(self) -> AccessToken | None:
|
|
93
|
+
"""The current token while Platform still accepts it, due for a refresh or not."""
|
|
94
|
+
if self._current and _now() < self._current.expires_on:
|
|
95
|
+
return self._current
|
|
76
96
|
return None
|
|
77
97
|
|
|
78
|
-
def
|
|
79
|
-
"""kwargs for the client-token POST
|
|
98
|
+
def _begin_mint(self) -> dict[str, Any]:
|
|
99
|
+
"""First half of a mint: the 429 gate, then the kwargs for the client-token POST."""
|
|
80
100
|
if _now() < self._blocked_until:
|
|
81
101
|
raise RateLimitedError(
|
|
82
|
-
"client-token
|
|
102
|
+
"client-token requests are rate limited; not minting until the cooldown ends"
|
|
83
103
|
)
|
|
84
|
-
if self._token is not None:
|
|
85
|
-
# Natural refresh: the next 401 may buy one replacement again.
|
|
86
|
-
self._replaced = False
|
|
87
104
|
kwargs: dict[str, Any] = {
|
|
88
105
|
"json": {"client_id": self.client_id, "client_secret": self._client_secret}
|
|
89
106
|
}
|
|
90
107
|
merge_request_attribution(kwargs)
|
|
91
108
|
return kwargs
|
|
92
109
|
|
|
93
|
-
def
|
|
110
|
+
def _finish_mint(self, response: httpx.Response) -> AccessToken:
|
|
111
|
+
"""Second half of a mint: the response becomes the current token, or raises."""
|
|
94
112
|
try:
|
|
95
|
-
|
|
113
|
+
raise_for_status(response)
|
|
96
114
|
except RateLimitedError:
|
|
97
|
-
self._blocked_until = _now() +
|
|
115
|
+
self._blocked_until = _now() + RATE_LIMIT_COOLDOWN_S
|
|
98
116
|
raise
|
|
99
117
|
try:
|
|
100
118
|
parsed = TokenResponse(**response.json())
|
|
101
119
|
except (ValueError, TypeError) as e:
|
|
102
120
|
raise VisionaiSDKError(f"client-token response is not a token: {e}") from e
|
|
103
|
-
|
|
104
|
-
self.
|
|
105
|
-
parsed.access_token,
|
|
121
|
+
now = _now()
|
|
122
|
+
self._current = AccessToken(
|
|
123
|
+
parsed.access_token, now + parsed.expires_in, parsed.token_type, now
|
|
106
124
|
)
|
|
107
125
|
logger.info(
|
|
108
126
|
"platform token minted",
|
|
109
127
|
extra={"client_id": self.client_id, "expires_in": parsed.expires_in},
|
|
110
128
|
)
|
|
111
|
-
return self.
|
|
129
|
+
return self._current
|
|
130
|
+
|
|
131
|
+
def _after_failed_refresh(self, error: VisionaiSDKError) -> AccessToken:
|
|
132
|
+
"""A refresh failed: keep serving the current token while it is valid, else raise."""
|
|
133
|
+
valid = self._valid()
|
|
134
|
+
if valid is None:
|
|
135
|
+
raise error
|
|
136
|
+
logger.warning(
|
|
137
|
+
"token refresh failed; using the current token until it expires",
|
|
138
|
+
extra={
|
|
139
|
+
"client_id": self.client_id,
|
|
140
|
+
"error": str(error),
|
|
141
|
+
"expires_in": valid.expires_in(),
|
|
142
|
+
},
|
|
143
|
+
)
|
|
144
|
+
return valid
|
|
112
145
|
|
|
113
146
|
def invalidate(self, token: str) -> bool:
|
|
114
147
|
"""Report a 401 for ``token``. True: dropped, so the next ``get_token()`` mints.
|
|
115
148
|
|
|
116
|
-
A
|
|
117
|
-
|
|
118
|
-
another mint would not fix,
|
|
149
|
+
A late report for a token no longer held changes nothing. A token minted
|
|
150
|
+
less than ``REPLACE_COOLDOWN_S`` ago is kept: a 401 that soon is a client or
|
|
151
|
+
allowlist problem another mint would not fix, and the cooldown bounds how
|
|
152
|
+
often a persistent 401 can mint. While a mint is in flight the report is
|
|
153
|
+
already being acted on.
|
|
119
154
|
"""
|
|
120
|
-
if self.
|
|
155
|
+
if self._current is None or token != self._current.token:
|
|
121
156
|
return False
|
|
122
|
-
if self.
|
|
123
|
-
|
|
124
|
-
|
|
157
|
+
if self._minting:
|
|
158
|
+
return True
|
|
159
|
+
if _now() - self._current.issued_at < REPLACE_COOLDOWN_S:
|
|
160
|
+
logger.warning(
|
|
161
|
+
"401 on a token minted %d s ago; keeping it until the cooldown ends",
|
|
162
|
+
int(_now() - self._current.issued_at),
|
|
125
163
|
extra={"client_id": self.client_id},
|
|
126
164
|
)
|
|
127
165
|
return False
|
|
128
|
-
self.
|
|
129
|
-
self._replaced = True
|
|
166
|
+
self._current = None
|
|
130
167
|
return True
|
|
131
168
|
|
|
132
169
|
|
|
@@ -149,32 +186,43 @@ class ClientCredentials(_Credentials):
|
|
|
149
186
|
) -> None:
|
|
150
187
|
super().__init__(auth_url, client_id, client_secret)
|
|
151
188
|
self._http = http or httpx.Client(verify=verify_ssl, timeout=timeout)
|
|
152
|
-
self.
|
|
189
|
+
self._http_owner = http is None # a client we built is ours to close
|
|
153
190
|
self._lock = threading.Lock()
|
|
154
191
|
|
|
155
|
-
def get_token(self) -> AccessToken:
|
|
156
|
-
"""The cached token,
|
|
192
|
+
def get_token(self, *, force_refresh: bool = False) -> AccessToken:
|
|
193
|
+
"""The cached token, refreshed shortly before it expires.
|
|
194
|
+
|
|
195
|
+
``force_refresh=True`` mints even while the cached token is fresh. A refresh
|
|
196
|
+
that fails keeps serving the current token while Platform still accepts it.
|
|
157
197
|
|
|
158
198
|
Raises:
|
|
159
199
|
AuthenticationError: Platform refused the client credentials (401).
|
|
160
|
-
RateLimitedError:
|
|
161
|
-
seen less than an hour ago.
|
|
200
|
+
RateLimitedError: Platform answered 429, or did so less than an hour ago.
|
|
162
201
|
NetworkError: Platform could not be reached.
|
|
163
202
|
VisionaiSDKError: Any other failure.
|
|
164
203
|
"""
|
|
165
204
|
with self._lock:
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
205
|
+
if not force_refresh:
|
|
206
|
+
fresh = self._fresh()
|
|
207
|
+
if fresh is not None:
|
|
208
|
+
return fresh
|
|
209
|
+
self._minting = True
|
|
170
210
|
try:
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
211
|
+
kwargs = self._begin_mint()
|
|
212
|
+
try:
|
|
213
|
+
response = self._http.post(self._url, **kwargs)
|
|
214
|
+
except httpx.RequestError as e:
|
|
215
|
+
raise from_transport_error(e) from e
|
|
216
|
+
return self._finish_mint(response)
|
|
217
|
+
except VisionaiSDKError as e:
|
|
218
|
+
if force_refresh:
|
|
219
|
+
raise
|
|
220
|
+
return self._after_failed_refresh(e)
|
|
221
|
+
finally:
|
|
222
|
+
self._minting = False
|
|
175
223
|
|
|
176
224
|
def close(self) -> None:
|
|
177
|
-
if self.
|
|
225
|
+
if self._http_owner:
|
|
178
226
|
self._http.close()
|
|
179
227
|
|
|
180
228
|
def __enter__(self) -> ClientCredentials:
|
|
@@ -204,27 +252,37 @@ class AsyncClientCredentials(_Credentials):
|
|
|
204
252
|
) -> None:
|
|
205
253
|
super().__init__(auth_url, client_id, client_secret)
|
|
206
254
|
self._http = http or httpx.AsyncClient(verify=verify_ssl, timeout=timeout)
|
|
207
|
-
self.
|
|
255
|
+
self._http_owner = http is None # a client we built is ours to close
|
|
208
256
|
self._lock = asyncio.Lock()
|
|
209
257
|
|
|
210
|
-
async def get_token(self) -> AccessToken:
|
|
211
|
-
"""The cached token,
|
|
258
|
+
async def get_token(self, *, force_refresh: bool = False) -> AccessToken:
|
|
259
|
+
"""The cached token, refreshed shortly before it expires.
|
|
212
260
|
|
|
213
|
-
Concurrent callers wait for one mint.
|
|
261
|
+
Concurrent callers wait for one mint. Behaves and raises as
|
|
262
|
+
``ClientCredentials.get_token``.
|
|
214
263
|
"""
|
|
215
264
|
async with self._lock:
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
265
|
+
if not force_refresh:
|
|
266
|
+
fresh = self._fresh()
|
|
267
|
+
if fresh is not None:
|
|
268
|
+
return fresh
|
|
269
|
+
self._minting = True
|
|
220
270
|
try:
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
271
|
+
kwargs = self._begin_mint()
|
|
272
|
+
try:
|
|
273
|
+
response = await self._http.post(self._url, **kwargs)
|
|
274
|
+
except httpx.RequestError as e:
|
|
275
|
+
raise from_transport_error(e) from e
|
|
276
|
+
return self._finish_mint(response)
|
|
277
|
+
except VisionaiSDKError as e:
|
|
278
|
+
if force_refresh:
|
|
279
|
+
raise
|
|
280
|
+
return self._after_failed_refresh(e)
|
|
281
|
+
finally:
|
|
282
|
+
self._minting = False
|
|
225
283
|
|
|
226
284
|
async def aclose(self) -> None:
|
|
227
|
-
if self.
|
|
285
|
+
if self._http_owner:
|
|
228
286
|
await self._http.aclose()
|
|
229
287
|
|
|
230
288
|
async def __aenter__(self) -> AsyncClientCredentials:
|