visionai-sdk-python 2.1.0__py3-none-any.whl → 2.2.0__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/__init__.py +6 -0
- visionai_sdk_python/_base.py +91 -50
- visionai_sdk_python/async_client.py +91 -38
- visionai_sdk_python/auth/__init__.py +9 -1
- visionai_sdk_python/auth/_mixin.py +1 -1
- visionai_sdk_python/auth/async_resource.py +35 -17
- visionai_sdk_python/auth/credentials.py +347 -0
- visionai_sdk_python/auth/models.py +1 -1
- visionai_sdk_python/auth/resource.py +37 -17
- visionai_sdk_python/client.py +89 -38
- visionai_sdk_python/constants.py +20 -33
- visionai_sdk_python/exceptions.py +57 -0
- visionai_sdk_python/instrumentation.py +12 -4
- visionai_sdk_python/relay/__init__.py +72 -0
- visionai_sdk_python/relay/examples/__init__.py +28 -0
- visionai_sdk_python/relay/examples/error_connection.json +3 -0
- visionai_sdk_python/relay/examples/error_request.json +4 -0
- visionai_sdk_python/relay/examples/heartbeat.json +1 -0
- visionai_sdk_python/relay/examples/register.json +8 -0
- visionai_sdk_python/relay/examples/registered.json +4 -0
- visionai_sdk_python/relay/examples/request.json +17 -0
- visionai_sdk_python/relay/examples/response.json +9 -0
- visionai_sdk_python/relay/examples/response_text.json +5 -0
- visionai_sdk_python/relay/protocol.py +210 -0
- visionai_sdk_python/vlm/async_resource.py +12 -18
- visionai_sdk_python/vlm/resource.py +12 -18
- {visionai_sdk_python-2.1.0.dist-info → visionai_sdk_python-2.2.0.dist-info}/METADATA +76 -9
- visionai_sdk_python-2.2.0.dist-info/RECORD +39 -0
- {visionai_sdk_python-2.1.0.dist-info → visionai_sdk_python-2.2.0.dist-info}/WHEEL +1 -1
- visionai_sdk_python-2.1.0.dist-info/RECORD +0 -27
- {visionai_sdk_python-2.1.0.dist-info → visionai_sdk_python-2.2.0.dist-info}/top_level.txt +0 -0
visionai_sdk_python/__init__.py
CHANGED
|
@@ -4,6 +4,7 @@ A client library for interacting with VisionAI authentication and VLM services.
|
|
|
4
4
|
"""
|
|
5
5
|
|
|
6
6
|
from .async_client import AsyncClient
|
|
7
|
+
from .auth.credentials import AccessToken, AsyncClientCredentials, ClientCredentials
|
|
7
8
|
from .client import Client
|
|
8
9
|
from .exceptions import (
|
|
9
10
|
AuthenticationError,
|
|
@@ -11,16 +12,21 @@ from .exceptions import (
|
|
|
11
12
|
JwksDiscoveryError,
|
|
12
13
|
NetworkError,
|
|
13
14
|
PermissionDeniedError,
|
|
15
|
+
RateLimitedError,
|
|
14
16
|
ServerError,
|
|
15
17
|
VisionaiSDKError,
|
|
16
18
|
)
|
|
17
19
|
|
|
18
20
|
__all__ = [
|
|
21
|
+
"AccessToken",
|
|
19
22
|
"AsyncClient",
|
|
23
|
+
"AsyncClientCredentials",
|
|
20
24
|
"Client",
|
|
25
|
+
"ClientCredentials",
|
|
21
26
|
"VisionaiSDKError",
|
|
22
27
|
"AuthenticationError",
|
|
23
28
|
"PermissionDeniedError",
|
|
29
|
+
"RateLimitedError",
|
|
24
30
|
"ClientError",
|
|
25
31
|
"ServerError",
|
|
26
32
|
"NetworkError",
|
visionai_sdk_python/_base.py
CHANGED
|
@@ -1,17 +1,37 @@
|
|
|
1
1
|
import time
|
|
2
|
-
from typing import Literal
|
|
2
|
+
from typing import TYPE_CHECKING, Literal
|
|
3
3
|
|
|
4
4
|
import httpx
|
|
5
5
|
|
|
6
6
|
from ._jwt_verifier import JwtVerifier
|
|
7
7
|
from .constants import resolve_allowed_issuers
|
|
8
|
-
from .exceptions import
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
8
|
+
from .exceptions import raise_for_status
|
|
9
|
+
|
|
10
|
+
if TYPE_CHECKING:
|
|
11
|
+
from .auth.credentials import AsyncClientCredentials, ClientCredentials
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
_TRANSPORT_DEFAULTS = {
|
|
15
|
+
"verify_ssl": True,
|
|
16
|
+
"timeout": 10.0,
|
|
17
|
+
"max_connections": 100,
|
|
18
|
+
"max_keepalive_connections": 20,
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _transport_settings(injected: object | None, **given: object) -> dict:
|
|
23
|
+
"""The settings for the httpx client the SDK builds, or an error with an injected one.
|
|
24
|
+
|
|
25
|
+
An injected client brings its own TLS, timeout and limits, so none of these
|
|
26
|
+
may be given with it: silently ignoring ``verify_ssl=False`` would surprise.
|
|
27
|
+
"""
|
|
28
|
+
passed = {name: value for name, value in given.items() if value is not None}
|
|
29
|
+
if injected is not None and passed:
|
|
30
|
+
raise ValueError(
|
|
31
|
+
"the injected http client has its own verify, timeout and limits; "
|
|
32
|
+
f"do not pass {', '.join(passed)} with it"
|
|
33
|
+
)
|
|
34
|
+
return {**_TRANSPORT_DEFAULTS, **passed}
|
|
15
35
|
|
|
16
36
|
|
|
17
37
|
class _BaseClient:
|
|
@@ -24,32 +44,40 @@ class _BaseClient:
|
|
|
24
44
|
def __init__(
|
|
25
45
|
self,
|
|
26
46
|
auth_url: str,
|
|
27
|
-
vlm_url: str,
|
|
47
|
+
vlm_url: str | None = None,
|
|
28
48
|
allowed_issuers: list[str] | None = None,
|
|
29
49
|
verify_ssl: bool = True,
|
|
30
50
|
timeout: float = 10.0,
|
|
31
51
|
max_connections: int = 100,
|
|
32
52
|
max_keepalive_connections: int = 20,
|
|
53
|
+
credential: "ClientCredentials | AsyncClientCredentials | None" = None,
|
|
33
54
|
) -> None:
|
|
34
55
|
"""Initialize the client with connection settings.
|
|
35
56
|
|
|
36
57
|
Args:
|
|
37
58
|
auth_url: Base URL for the authentication service.
|
|
38
|
-
vlm_url: Base URL for the VLM inference service.
|
|
59
|
+
vlm_url: Base URL for the VLM inference service. Optional for clients
|
|
60
|
+
that only authenticate; VLM calls then raise ``ValueError``.
|
|
39
61
|
allowed_issuers: Optional list of allowed JWT issuers. If provided, tokens
|
|
40
62
|
whose ``iss`` claim is not in this list will be rejected. If omitted,
|
|
41
|
-
|
|
63
|
+
the issuers are derived from ``auth_url``.
|
|
42
64
|
verify_ssl: Whether to verify TLS certificates.
|
|
43
65
|
timeout: Default request timeout in seconds.
|
|
44
66
|
max_connections: Maximum number of concurrent connections in the pool.
|
|
45
67
|
max_keepalive_connections: Maximum number of idle keep-alive connections.
|
|
68
|
+
credential: A ``ClientCredentials`` / ``AsyncClientCredentials`` whose
|
|
69
|
+
token every call uses; shareable between clients. Without it the
|
|
70
|
+
client keeps the token from ``auth.login()`` or ``set_token()``;
|
|
71
|
+
``auth.get_access_token()`` installs a credential. The last explicit
|
|
72
|
+
authentication wins.
|
|
46
73
|
"""
|
|
47
74
|
if not auth_url.strip():
|
|
48
75
|
raise ValueError("auth_url must not be empty")
|
|
49
|
-
if not vlm_url.strip():
|
|
76
|
+
if vlm_url is not None and not vlm_url.strip():
|
|
50
77
|
raise ValueError("vlm_url must not be empty")
|
|
51
78
|
self.auth_url = auth_url.strip()
|
|
52
|
-
self.vlm_url = vlm_url.strip()
|
|
79
|
+
self.vlm_url = vlm_url.strip() if vlm_url is not None else None
|
|
80
|
+
self._credential = credential
|
|
53
81
|
self.verify_ssl = verify_ssl
|
|
54
82
|
self.timeout = timeout
|
|
55
83
|
self.max_connections = max_connections
|
|
@@ -70,13 +98,53 @@ class _BaseClient:
|
|
|
70
98
|
self._access_token: str | None = None
|
|
71
99
|
self._token_expires_at: float | None = None # monotonic time
|
|
72
100
|
self._credentials: dict | None = None
|
|
73
|
-
self._credentials_type: Literal["login"
|
|
101
|
+
self._credentials_type: Literal["login"] | None = None
|
|
102
|
+
|
|
103
|
+
@property
|
|
104
|
+
def credential(self) -> "ClientCredentials | AsyncClientCredentials | None":
|
|
105
|
+
"""The credential currently in use, or None.
|
|
106
|
+
|
|
107
|
+
Set by ``credential=`` or by ``auth.get_access_token()``; dropped by
|
|
108
|
+
``login()`` / ``set_token()``, whose token then takes over. For callers
|
|
109
|
+
that need the raw token themselves (a WebSocket upgrade, another HTTP
|
|
110
|
+
library): ``credential.get_token()`` / ``credential.invalidate(token)``."""
|
|
111
|
+
return self._credential
|
|
74
112
|
|
|
75
113
|
@staticmethod
|
|
76
114
|
def _build_url(base_url: str, path: str) -> str:
|
|
77
115
|
"""Join a base URL and a path, normalizing slashes."""
|
|
78
116
|
return f"{base_url.rstrip('/')}/{path.lstrip('/')}"
|
|
79
117
|
|
|
118
|
+
@staticmethod
|
|
119
|
+
def _full_url(url: str) -> str:
|
|
120
|
+
"""``request()`` takes a full URL: the client has two bases (``auth_url``,
|
|
121
|
+
``vlm_url``), so a bare path would not say which one is meant."""
|
|
122
|
+
if "://" not in url:
|
|
123
|
+
raise ValueError(f"request() needs a full URL, got {url!r}")
|
|
124
|
+
return url
|
|
125
|
+
|
|
126
|
+
def _with_auth(self, kwargs: dict, token: str) -> dict:
|
|
127
|
+
"""``kwargs`` for httpx with the bearer header; the client's token wins."""
|
|
128
|
+
headers = httpx.Headers(kwargs.get("headers"))
|
|
129
|
+
headers["Authorization"] = f"Bearer {token}" # case-insensitive: one header
|
|
130
|
+
return {**kwargs, "headers": headers}
|
|
131
|
+
|
|
132
|
+
@staticmethod
|
|
133
|
+
def _resendable(kwargs: dict) -> bool:
|
|
134
|
+
"""Whether the body can be sent a second time (streams and files cannot)."""
|
|
135
|
+
content = kwargs.get("content")
|
|
136
|
+
if content is not None and not isinstance(content, (bytes, str)):
|
|
137
|
+
return False
|
|
138
|
+
if kwargs.get("files") is not None:
|
|
139
|
+
return False
|
|
140
|
+
data = kwargs.get("data")
|
|
141
|
+
return data is None or isinstance(data, dict)
|
|
142
|
+
|
|
143
|
+
def _require_vlm_url(self) -> str:
|
|
144
|
+
if self.vlm_url is None:
|
|
145
|
+
raise ValueError("vlm_url is required for VLM calls; pass it to the client")
|
|
146
|
+
return self.vlm_url
|
|
147
|
+
|
|
80
148
|
@staticmethod
|
|
81
149
|
def _build_auth_header(access_token: str) -> dict[str, str]:
|
|
82
150
|
"""Build authorization header."""
|
|
@@ -89,16 +157,20 @@ class _BaseClient:
|
|
|
89
157
|
access_token: str,
|
|
90
158
|
expires_in: int,
|
|
91
159
|
credentials: dict | None = None,
|
|
92
|
-
credentials_type: Literal["login"
|
|
160
|
+
credentials_type: Literal["login"] | None = None,
|
|
93
161
|
) -> None:
|
|
94
|
-
"""
|
|
162
|
+
"""Use this token from now on; a credential set earlier is dropped.
|
|
163
|
+
|
|
164
|
+
The last explicit authentication wins, in both directions.
|
|
95
165
|
|
|
96
166
|
Args:
|
|
97
167
|
access_token: JWT access token.
|
|
98
168
|
expires_in: Token expiration time in seconds.
|
|
99
169
|
credentials: Optional credentials for auto-refresh.
|
|
100
|
-
credentials_type:
|
|
170
|
+
credentials_type: "login" for email / password credentials; client
|
|
171
|
+
credentials live in a ``ClientCredentials`` on the client instead.
|
|
101
172
|
"""
|
|
173
|
+
self._credential = None
|
|
102
174
|
self._access_token = access_token
|
|
103
175
|
self._token_expires_at = time.monotonic() + expires_in
|
|
104
176
|
self._credentials = credentials
|
|
@@ -174,36 +246,5 @@ class _BaseClient:
|
|
|
174
246
|
|
|
175
247
|
@staticmethod
|
|
176
248
|
def _handle_response(response: httpx.Response) -> httpx.Response:
|
|
177
|
-
"""Raise SDK
|
|
178
|
-
|
|
179
|
-
Raises:
|
|
180
|
-
AuthenticationError: If the server returns 401
|
|
181
|
-
PermissionDeniedError: If the server returns 403
|
|
182
|
-
ClientError: If the server returns any other 4xx
|
|
183
|
-
ServerError: If the server returns 5xx
|
|
184
|
-
APIError: If the server returns any other non-2xx status
|
|
185
|
-
"""
|
|
186
|
-
try:
|
|
187
|
-
response.raise_for_status()
|
|
188
|
-
except httpx.HTTPStatusError as e:
|
|
189
|
-
body = None
|
|
190
|
-
if e.response.content:
|
|
191
|
-
try:
|
|
192
|
-
body = e.response.json()
|
|
193
|
-
except Exception:
|
|
194
|
-
pass
|
|
195
|
-
if isinstance(body, dict):
|
|
196
|
-
detail: str = body.get("detail") or body.get("message") or str(e)
|
|
197
|
-
else:
|
|
198
|
-
detail = str(e)
|
|
199
|
-
status = e.response.status_code
|
|
200
|
-
if status == 401:
|
|
201
|
-
raise AuthenticationError(detail) from e
|
|
202
|
-
if status == 403:
|
|
203
|
-
raise PermissionDeniedError(detail) from e
|
|
204
|
-
if 400 <= status < 500:
|
|
205
|
-
raise ClientError(status, detail) from e
|
|
206
|
-
if 500 <= status < 600:
|
|
207
|
-
raise ServerError(status, detail) from e
|
|
208
|
-
raise APIError(status, detail) from e
|
|
209
|
-
return response
|
|
249
|
+
"""Raise the SDK exception for a non-2xx response (``exceptions.raise_for_status``)."""
|
|
250
|
+
return raise_for_status(response)
|
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
import httpx
|
|
2
2
|
|
|
3
|
-
from ._base import _BaseClient
|
|
3
|
+
from ._base import _BaseClient, _transport_settings
|
|
4
4
|
from ._request_attribution import merge_request_attribution
|
|
5
5
|
from .auth.async_resource import AsyncAuthResource
|
|
6
|
-
from .
|
|
6
|
+
from .auth.credentials import AsyncClientCredentials
|
|
7
|
+
from .exceptions import AuthenticationError, from_transport_error
|
|
7
8
|
from .vlm.async_resource import AsyncVLMResource
|
|
8
9
|
|
|
9
10
|
|
|
@@ -11,30 +12,53 @@ class AsyncClient(_BaseClient):
|
|
|
11
12
|
def __init__(
|
|
12
13
|
self,
|
|
13
14
|
auth_url: str,
|
|
14
|
-
vlm_url: str,
|
|
15
|
+
vlm_url: str | None = None,
|
|
15
16
|
allowed_issuers: list[str] | None = None,
|
|
16
|
-
verify_ssl: bool =
|
|
17
|
-
timeout: float =
|
|
18
|
-
max_connections: int =
|
|
19
|
-
max_keepalive_connections: int =
|
|
17
|
+
verify_ssl: bool | None = None,
|
|
18
|
+
timeout: float | None = None,
|
|
19
|
+
max_connections: int | None = None,
|
|
20
|
+
max_keepalive_connections: int | None = None,
|
|
21
|
+
credential: AsyncClientCredentials | None = None,
|
|
22
|
+
http_client: httpx.AsyncClient | None = None,
|
|
20
23
|
) -> None:
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
24
|
+
"""See ``_BaseClient``. ``http_client`` is an httpx.AsyncClient to send through
|
|
25
|
+
(tests, shared pools): its own TLS, timeout and limits apply, so
|
|
26
|
+
``verify_ssl`` / ``timeout`` / ``max_connections`` /
|
|
27
|
+
``max_keepalive_connections`` cannot be given with it (``ValueError``);
|
|
28
|
+
the client closes only the one it created."""
|
|
29
|
+
if credential is not None and not isinstance(
|
|
30
|
+
credential, AsyncClientCredentials
|
|
31
|
+
):
|
|
32
|
+
raise TypeError(
|
|
33
|
+
"AsyncClient takes an AsyncClientCredentials; Client takes a ClientCredentials"
|
|
34
|
+
)
|
|
35
|
+
settings = _transport_settings(
|
|
36
|
+
http_client,
|
|
25
37
|
verify_ssl=verify_ssl,
|
|
26
38
|
timeout=timeout,
|
|
27
39
|
max_connections=max_connections,
|
|
28
40
|
max_keepalive_connections=max_keepalive_connections,
|
|
29
41
|
)
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
42
|
+
super().__init__(
|
|
43
|
+
auth_url=auth_url,
|
|
44
|
+
vlm_url=vlm_url,
|
|
45
|
+
allowed_issuers=allowed_issuers,
|
|
46
|
+
credential=credential,
|
|
47
|
+
**settings,
|
|
48
|
+
)
|
|
49
|
+
self._client = (
|
|
50
|
+
http_client
|
|
51
|
+
if http_client is not None
|
|
52
|
+
else httpx.AsyncClient(
|
|
53
|
+
verify=self.verify_ssl,
|
|
54
|
+
timeout=self.timeout,
|
|
55
|
+
limits=httpx.Limits(
|
|
56
|
+
max_connections=self.max_connections,
|
|
57
|
+
max_keepalive_connections=self.max_keepalive_connections,
|
|
58
|
+
),
|
|
59
|
+
)
|
|
37
60
|
)
|
|
61
|
+
self._http_owner = http_client is None # a client we built is ours to close
|
|
38
62
|
# Register the different function resource
|
|
39
63
|
self.auth = AsyncAuthResource(self)
|
|
40
64
|
self.vlm = AsyncVLMResource(self)
|
|
@@ -44,17 +68,47 @@ class AsyncClient(_BaseClient):
|
|
|
44
68
|
merge_request_attribution(kwargs)
|
|
45
69
|
try:
|
|
46
70
|
response = await self._client.request(method, url, **kwargs)
|
|
47
|
-
except httpx.TimeoutException as e:
|
|
48
|
-
raise NetworkError("Request timed out") from e
|
|
49
|
-
except httpx.NetworkError as e:
|
|
50
|
-
raise NetworkError(f"Network error: {e}") from e
|
|
51
71
|
except httpx.RequestError as e:
|
|
52
|
-
raise
|
|
72
|
+
raise from_transport_error(e) from e
|
|
53
73
|
return self._handle_response(response)
|
|
54
74
|
|
|
75
|
+
async def request(self, method: str, url: str, **kwargs) -> httpx.Response:
|
|
76
|
+
"""Send any request with this client's bearer token.
|
|
77
|
+
|
|
78
|
+
``url`` is a full URL (the client has two bases); ``kwargs`` go to httpx. The
|
|
79
|
+
bearer token goes to whatever host ``url`` names, so ``url`` must come from
|
|
80
|
+
configuration or code, never from a caller's input; redirects are not
|
|
81
|
+
followed unless asked, and httpx drops the header on a cross-origin redirect.
|
|
82
|
+
|
|
83
|
+
With a ``credential``, a 401 buys one retry with the credential's current
|
|
84
|
+
token, which it replaces when the rejected one is old enough to have been
|
|
85
|
+
revoked (``REPLACE_COOLDOWN_S``); a 401 on the retry raises. Without a
|
|
86
|
+
credential, or with a body that cannot be sent twice (a stream or a
|
|
87
|
+
file), a 401 raises.
|
|
88
|
+
|
|
89
|
+
Raises:
|
|
90
|
+
ValueError: ``url`` is not a full URL.
|
|
91
|
+
AuthenticationError: No token, or the fresh one was refused too.
|
|
92
|
+
RateLimitedError, NetworkError, ServerError, ClientError: As the
|
|
93
|
+
resource methods.
|
|
94
|
+
"""
|
|
95
|
+
url = self._full_url(url)
|
|
96
|
+
token = await self._ensure_token()
|
|
97
|
+
try:
|
|
98
|
+
return await self._request(method, url, **self._with_auth(kwargs, token))
|
|
99
|
+
except AuthenticationError:
|
|
100
|
+
if self._credential is None or not self._resendable(kwargs):
|
|
101
|
+
raise
|
|
102
|
+
self._credential.invalidate(token)
|
|
103
|
+
replacement = (await self._credential.get_token()).token
|
|
104
|
+
if replacement == token:
|
|
105
|
+
raise
|
|
106
|
+
return await self._request(method, url, **self._with_auth(kwargs, replacement))
|
|
107
|
+
|
|
55
108
|
async def close(self) -> None:
|
|
56
|
-
"""Close the HTTP client and release connections."""
|
|
57
|
-
|
|
109
|
+
"""Close the HTTP client this client created and release its connections."""
|
|
110
|
+
if self._http_owner:
|
|
111
|
+
await self._client.aclose()
|
|
58
112
|
|
|
59
113
|
async def __aenter__(self) -> "AsyncClient":
|
|
60
114
|
"""Async context manager entry."""
|
|
@@ -65,7 +119,9 @@ class AsyncClient(_BaseClient):
|
|
|
65
119
|
await self.close()
|
|
66
120
|
|
|
67
121
|
async def _refresh_token(self) -> None:
|
|
68
|
-
"""Refresh token
|
|
122
|
+
"""Refresh the token with the stored login credentials.
|
|
123
|
+
|
|
124
|
+
Client credentials refresh through the credential object instead.
|
|
69
125
|
|
|
70
126
|
Raises:
|
|
71
127
|
AuthenticationError: If no credentials are stored or refresh fails.
|
|
@@ -73,23 +129,19 @@ class AsyncClient(_BaseClient):
|
|
|
73
129
|
if self._credentials is None or self._credentials_type is None:
|
|
74
130
|
raise AuthenticationError("No credentials available for token refresh")
|
|
75
131
|
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
)
|
|
81
|
-
elif self._credentials_type == "client":
|
|
82
|
-
await self.auth.get_access_token(
|
|
83
|
-
client_id=self._credentials["client_id"],
|
|
84
|
-
client_secret=self._credentials["client_secret"],
|
|
85
|
-
)
|
|
132
|
+
await self.auth.login(
|
|
133
|
+
email=self._credentials["email"],
|
|
134
|
+
password=self._credentials["password"],
|
|
135
|
+
)
|
|
86
136
|
|
|
87
|
-
async def _ensure_token(self) ->
|
|
88
|
-
"""
|
|
137
|
+
async def _ensure_token(self) -> str:
|
|
138
|
+
"""The token to send: the credential's, else the stored one, refreshed if expiring.
|
|
89
139
|
|
|
90
140
|
Raises:
|
|
91
141
|
AuthenticationError: If no token is available or token expired without credentials.
|
|
92
142
|
"""
|
|
143
|
+
if self._credential is not None:
|
|
144
|
+
return (await self._credential.get_token()).token
|
|
93
145
|
if self._access_token is None:
|
|
94
146
|
raise AuthenticationError(
|
|
95
147
|
"Not authenticated. Call login() or get_access_token() first."
|
|
@@ -101,3 +153,4 @@ class AsyncClient(_BaseClient):
|
|
|
101
153
|
"Token expired and no credentials available for refresh"
|
|
102
154
|
)
|
|
103
155
|
await self._refresh_token()
|
|
156
|
+
return self._access_token
|
|
@@ -1,7 +1,15 @@
|
|
|
1
1
|
"""Authentication resources for VisionAI SDK."""
|
|
2
2
|
|
|
3
3
|
from .async_resource import AsyncAuthResource
|
|
4
|
+
from .credentials import AccessToken, AsyncClientCredentials, ClientCredentials
|
|
4
5
|
from .models import TokenResponse
|
|
5
6
|
from .resource import AuthResource
|
|
6
7
|
|
|
7
|
-
__all__ = [
|
|
8
|
+
__all__ = [
|
|
9
|
+
"AccessToken",
|
|
10
|
+
"AsyncAuthResource",
|
|
11
|
+
"AsyncClientCredentials",
|
|
12
|
+
"AuthResource",
|
|
13
|
+
"ClientCredentials",
|
|
14
|
+
"TokenResponse",
|
|
15
|
+
]
|
|
@@ -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
|
|
@@ -7,6 +7,7 @@ import jwt
|
|
|
7
7
|
from ..endpoints import AuthEndpoint
|
|
8
8
|
from ..exceptions import JwksDiscoveryError
|
|
9
9
|
from ._mixin import AuthMixin
|
|
10
|
+
from .credentials import AsyncClientCredentials
|
|
10
11
|
from .models import TokenResponse
|
|
11
12
|
|
|
12
13
|
if TYPE_CHECKING:
|
|
@@ -27,16 +28,25 @@ class AsyncAuthResource(AuthMixin):
|
|
|
27
28
|
self._sdk_client = client
|
|
28
29
|
|
|
29
30
|
async def get_access_token(
|
|
30
|
-
self, client_id: str, client_secret: str
|
|
31
|
+
self, client_id: str, client_secret: str, *, force_refresh: bool = False
|
|
31
32
|
) -> TokenResponse:
|
|
32
33
|
"""Get access token using client credentials flow.
|
|
33
34
|
|
|
34
|
-
The
|
|
35
|
-
|
|
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.
|
|
41
|
+
|
|
42
|
+
New code should build a ``ClientCredentials`` / ``AsyncClientCredentials``
|
|
43
|
+
and pass it as ``credential=`` to the client instead; this method stays for
|
|
44
|
+
existing callers.
|
|
36
45
|
|
|
37
46
|
Args:
|
|
38
47
|
client_id: OAuth client ID
|
|
39
48
|
client_secret: OAuth client secret
|
|
49
|
+
force_refresh: Mint a new token even if a fresh one is cached.
|
|
40
50
|
|
|
41
51
|
Returns:
|
|
42
52
|
TokenResponse with access_token, expires_in, and token_type
|
|
@@ -49,20 +59,28 @@ class AsyncAuthResource(AuthMixin):
|
|
|
49
59
|
# Validate (from Mixin)
|
|
50
60
|
self._validate_client_credentials(client_id, client_secret)
|
|
51
61
|
|
|
52
|
-
#
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
)
|
|
58
|
-
|
|
59
|
-
)
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
62
|
+
# One credential per client: cached, one mint at a time, one replacement
|
|
63
|
+
# per 401, no mint for an hour after a 429. Calling this again with the
|
|
64
|
+
# same client credentials reuses it, so it does not mint again.
|
|
65
|
+
credential = self._sdk_client._credential
|
|
66
|
+
if not (
|
|
67
|
+
isinstance(credential, AsyncClientCredentials)
|
|
68
|
+
and credential.is_for(client_id, client_secret)
|
|
69
|
+
):
|
|
70
|
+
credential = AsyncClientCredentials(
|
|
71
|
+
self._sdk_client.auth_url,
|
|
72
|
+
client_id,
|
|
73
|
+
client_secret,
|
|
74
|
+
http=self._sdk_client._client,
|
|
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(
|
|
81
|
+
access_token=token.token,
|
|
82
|
+
expires_in=token.expires_in(),
|
|
83
|
+
token_type=token.token_type,
|
|
66
84
|
)
|
|
67
85
|
|
|
68
86
|
async def login(self, email: str, password: str) -> TokenResponse:
|