dsp-vre 0.1.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.
- dsp_vre/__init__.py +6 -0
- dsp_vre/clients/CLAUDE.md +491 -0
- dsp_vre/clients/__init__.py +65 -0
- dsp_vre/clients/authentication_client.py +14 -0
- dsp_vre/clients/authentication_client_live.py +71 -0
- dsp_vre/clients/bulk_ingest_client.py +214 -0
- dsp_vre/clients/client_warnings.py +2 -0
- dsp_vre/clients/connection.py +35 -0
- dsp_vre/clients/connection_live.py +238 -0
- dsp_vre/clients/data_import_client.py +46 -0
- dsp_vre/clients/data_import_client_live.py +176 -0
- dsp_vre/clients/exceptions.py +182 -0
- dsp_vre/clients/group_user_clients.py +35 -0
- dsp_vre/clients/group_user_clients_live.py +178 -0
- dsp_vre/clients/ingest.py +117 -0
- dsp_vre/clients/legal_info_client.py +23 -0
- dsp_vre/clients/legal_info_client_live.py +132 -0
- dsp_vre/clients/list_client.py +39 -0
- dsp_vre/clients/list_client_live.py +151 -0
- dsp_vre/clients/mapping_client.py +21 -0
- dsp_vre/clients/mapping_client_live.py +104 -0
- dsp_vre/clients/metadata_client.py +24 -0
- dsp_vre/clients/metadata_client_live.py +49 -0
- dsp_vre/clients/migration_clients.py +58 -0
- dsp_vre/clients/migration_clients_live.py +198 -0
- dsp_vre/clients/ontology_clients.py +49 -0
- dsp_vre/clients/ontology_create_client_live.py +165 -0
- dsp_vre/clients/ontology_get_client_live.py +81 -0
- dsp_vre/clients/permissions_client.py +27 -0
- dsp_vre/clients/permissions_client_live.py +102 -0
- dsp_vre/clients/project_client.py +19 -0
- dsp_vre/clients/project_client_live.py +83 -0
- dsp_vre/clients/request_utils.py +279 -0
- dsp_vre/clients/resource_client.py +20 -0
- dsp_vre/clients/resource_client_live.py +96 -0
- dsp_vre/clients/value_client.py +22 -0
- dsp_vre/clients/value_client_live.py +87 -0
- dsp_vre/py.typed +0 -0
- dsp_vre-0.1.0.dist-info/METADATA +28 -0
- dsp_vre-0.1.0.dist-info/RECORD +41 -0
- dsp_vre-0.1.0.dist-info/WHEEL +4 -0
dsp_vre/__init__.py
ADDED
|
@@ -0,0 +1,491 @@
|
|
|
1
|
+
# Client Pattern Documentation
|
|
2
|
+
|
|
3
|
+
This document describes the architectural pattern used for client classes in dsp-vre.
|
|
4
|
+
These clients provide interfaces to interact with the DSP-API endpoints.
|
|
5
|
+
|
|
6
|
+
## Overview
|
|
7
|
+
|
|
8
|
+
The client architecture follows a **Protocol-based dependency injection pattern** that separates interface definitions
|
|
9
|
+
from concrete implementations. This design enables testability, modularity, and clear contracts between components.
|
|
10
|
+
The clients should be as simple to initiate as possible and be stateless, if possible.
|
|
11
|
+
|
|
12
|
+
## Core Components
|
|
13
|
+
|
|
14
|
+
### 1. Protocol Classes (Abstract Interfaces)
|
|
15
|
+
|
|
16
|
+
Protocol classes define the contract that implementations must follow:
|
|
17
|
+
|
|
18
|
+
- **Location**: `src/dsp_vre/clients/`
|
|
19
|
+
- **Naming**: `<Domain>Client` (e.g., `AuthenticationClient`, `LegalInfoClient`)
|
|
20
|
+
- **Implementation**: Use `typing.Protocol` for structural subtyping
|
|
21
|
+
- **Purpose**: Define required attributes and method signatures without implementation
|
|
22
|
+
|
|
23
|
+
Example:
|
|
24
|
+
|
|
25
|
+
```python
|
|
26
|
+
from typing import Protocol
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class AuthenticationClient(Protocol):
|
|
30
|
+
server: str
|
|
31
|
+
email: str
|
|
32
|
+
password: str
|
|
33
|
+
|
|
34
|
+
def get_token(self) -> str:
|
|
35
|
+
pass
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
### 2. Live Implementations
|
|
39
|
+
|
|
40
|
+
Live implementations are concrete classes that interact with real DSP API endpoints:
|
|
41
|
+
|
|
42
|
+
- **Location**: `src/dsp_vre/clients/`
|
|
43
|
+
- **Naming**: `<Domain>ClientLive` (e.g., `AuthenticationClientLive`, `LegalInfoClientLive`)
|
|
44
|
+
- **Decorator**: Always use `@dataclass` decorator
|
|
45
|
+
- **Inheritance**: Inherit from corresponding Protocol class
|
|
46
|
+
- **Purpose**: Implement actual HTTP communication with the DSP-API
|
|
47
|
+
|
|
48
|
+
Example:
|
|
49
|
+
|
|
50
|
+
```python
|
|
51
|
+
from dataclasses import dataclass
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@dataclass
|
|
55
|
+
class AuthenticationClientLive(AuthenticationClient):
|
|
56
|
+
server: str
|
|
57
|
+
email: str
|
|
58
|
+
password: str
|
|
59
|
+
_token: str | None = None
|
|
60
|
+
|
|
61
|
+
def get_token(self) -> str:
|
|
62
|
+
# Implementation here
|
|
63
|
+
pass
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
## Implementation Pattern
|
|
67
|
+
|
|
68
|
+
### Required Attributes
|
|
69
|
+
|
|
70
|
+
Live clients typically include:
|
|
71
|
+
|
|
72
|
+
- **Server identification**: `api_url`
|
|
73
|
+
- **Project identification**: `shortcode`, `project_shortcode`, `project_iri`
|
|
74
|
+
- **Authentication**: `auth: AuthenticationClient` (for endpoints requiring auth)
|
|
75
|
+
- **Private state**: Optional private attributes (e.g., `_token`)
|
|
76
|
+
|
|
77
|
+
### Request Workflow
|
|
78
|
+
|
|
79
|
+
There are three main patterns for handling non-ok API responses.
|
|
80
|
+
|
|
81
|
+
In most cases `HTTPStatus.FORBIDDEN` will mean that a `BadCredentialsError` will be raised
|
|
82
|
+
|
|
83
|
+
Pattern 1: If the request is not successfully, then an error is raised.
|
|
84
|
+
|
|
85
|
+
```python
|
|
86
|
+
def _make_request(self, url: str, data: dict[str, Any] | None = None) -> Response:
|
|
87
|
+
# 1. Prepare request parameters
|
|
88
|
+
headers = {
|
|
89
|
+
"Content-Type": "application/json",
|
|
90
|
+
"Authorization": f"Bearer {self.auth.get_token()}",
|
|
91
|
+
}
|
|
92
|
+
params = RequestParameters("POST", url, TIMEOUT, data, headers)
|
|
93
|
+
|
|
94
|
+
# 2. Log the request
|
|
95
|
+
log_request(params)
|
|
96
|
+
|
|
97
|
+
# 3. Execute request with exception handling
|
|
98
|
+
try:
|
|
99
|
+
response = requests.post(
|
|
100
|
+
url=params.url,
|
|
101
|
+
headers=params.headers,
|
|
102
|
+
data=params.data_serialized,
|
|
103
|
+
timeout=params.timeout,
|
|
104
|
+
)
|
|
105
|
+
except RequestException as err:
|
|
106
|
+
log_and_raise_request_exception(err)
|
|
107
|
+
|
|
108
|
+
# 4. Log the response
|
|
109
|
+
log_response(response)
|
|
110
|
+
|
|
111
|
+
# 5. Handle response status
|
|
112
|
+
if response.ok:
|
|
113
|
+
return response
|
|
114
|
+
|
|
115
|
+
if response.status_code == HTTPStatus.FORBIDDEN:
|
|
116
|
+
raise BadCredentialsError(
|
|
117
|
+
"Only a SystemAdmin or ProjectAdmin can do ... Your permissions are insufficient for this action.."
|
|
118
|
+
)
|
|
119
|
+
|
|
120
|
+
raise FatalNonOkApiResponseCodeError(url, response.status_code, response.text)
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
Pattern 2: If the request is not successful, then the user is warned and `None` is returned (non-fatal failure)
|
|
124
|
+
|
|
125
|
+
```python
|
|
126
|
+
def create_resource(self, resource_data: dict[str, Any]) -> str | None:
|
|
127
|
+
# 1. Prepare request parameters
|
|
128
|
+
url = f"{self.api_url}/v2/resources"
|
|
129
|
+
headers = {
|
|
130
|
+
"Content-Type": "application/json",
|
|
131
|
+
"Authorization": f"Bearer {self.auth.get_token()}",
|
|
132
|
+
}
|
|
133
|
+
params = RequestParameters("POST", url, TIMEOUT, resource_data, headers)
|
|
134
|
+
|
|
135
|
+
# 2. Log the request
|
|
136
|
+
log_request(params)
|
|
137
|
+
|
|
138
|
+
# 3. Execute request with exception handling
|
|
139
|
+
try:
|
|
140
|
+
response = requests.post(
|
|
141
|
+
url=params.url,
|
|
142
|
+
headers=params.headers,
|
|
143
|
+
data=params.data_serialized,
|
|
144
|
+
timeout=params.timeout,
|
|
145
|
+
)
|
|
146
|
+
except RequestException as err:
|
|
147
|
+
log_and_raise_request_exception(err)
|
|
148
|
+
|
|
149
|
+
# 4. Log the response
|
|
150
|
+
log_response(response)
|
|
151
|
+
|
|
152
|
+
# 5. Handle response status
|
|
153
|
+
if response.ok:
|
|
154
|
+
result = response.json()
|
|
155
|
+
resource_iri = cast(str, result["@id"])
|
|
156
|
+
return resource_iri
|
|
157
|
+
|
|
158
|
+
# 6. Handle specific known error cases
|
|
159
|
+
if response.status_code == HTTPStatus.FORBIDDEN:
|
|
160
|
+
raise BadCredentialsError("You don't have permission to create resources in this project.")
|
|
161
|
+
|
|
162
|
+
# 7. Handle unexpected errors non-fatally
|
|
163
|
+
log_and_warn_unexpected_non_ok_response(response.status_code, response.text)
|
|
164
|
+
return None
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
Pattern 3: If the request is not successful, return a `ResponseCodeAndText` so the caller can decide how to handle it.
|
|
168
|
+
Use this when the caller needs to inspect the status code and response text to apply retry logic or other strategies.
|
|
169
|
+
|
|
170
|
+
```python
|
|
171
|
+
def post_resource(self, resource_json: dict[str, Any], resource_has_bitstream: bool) -> str | ResponseCodeAndText:
|
|
172
|
+
url = f"{self.server}/v2/resources"
|
|
173
|
+
headers = {
|
|
174
|
+
"Content-Type": "application/json",
|
|
175
|
+
"Authorization": f"Bearer {self.auth.get_token()}",
|
|
176
|
+
}
|
|
177
|
+
params = RequestParameters("POST", url, TIMEOUT_1800, resource_json, headers)
|
|
178
|
+
log_request(params)
|
|
179
|
+
try:
|
|
180
|
+
response = requests.post(
|
|
181
|
+
url=params.url,
|
|
182
|
+
headers=params.headers,
|
|
183
|
+
data=params.data_serialized,
|
|
184
|
+
timeout=params.timeout,
|
|
185
|
+
)
|
|
186
|
+
except RequestException as err:
|
|
187
|
+
log_and_raise_request_exception(err)
|
|
188
|
+
log_response(response)
|
|
189
|
+
match response.status_code:
|
|
190
|
+
case HTTPStatus.OK:
|
|
191
|
+
return cast(str, response.json()["@id"])
|
|
192
|
+
case HTTPStatus.FORBIDDEN:
|
|
193
|
+
raise BadCredentialsError("You don't have permission to create resources in this project.")
|
|
194
|
+
case _:
|
|
195
|
+
return ResponseCodeAndText(response.status_code, response.text)
|
|
196
|
+
```
|
|
197
|
+
|
|
198
|
+
### Key Steps
|
|
199
|
+
|
|
200
|
+
1. **Prepare Request Parameters**: Create `RequestParameters` object with method, URL, timeout, data, and headers
|
|
201
|
+
2. **Log Request**: Call `log_request(params)` before making the request
|
|
202
|
+
3. **Execute Request**: Use `requests.<method>()` wrapped in try/except.
|
|
203
|
+
Take every argument from the logged `params` (`url=params.url`, `timeout=params.timeout`, ...),
|
|
204
|
+
so that the log shows the request that was actually sent.
|
|
205
|
+
Exception: pass a streamed file body directly as `data=<file object>`.
|
|
206
|
+
`RequestParameters` cannot carry a file, and `log_request` must not log the body
|
|
207
|
+
(example: `DataImportClientLive.post_import`)
|
|
208
|
+
4. **Log Response**: Call `log_response(response)` after receiving response
|
|
209
|
+
5. **Handle Status**: Check response status and raise appropriate exceptions
|
|
210
|
+
|
|
211
|
+
### Error Handling Strategy
|
|
212
|
+
|
|
213
|
+
- **Network errors**: Catch `RequestException` and call `log_and_raise_request_exception(err)`
|
|
214
|
+
- **Authentication/Authorization (401/403)**: Raise `BadCredentialsError` with context-specific message
|
|
215
|
+
- **Other API errors**: Raise `FatalNonOkApiResponseCodeError` with URL, status code, and response text
|
|
216
|
+
- **Expected failures**: Use `log_and_warn_unexpected_non_ok_response()` when failure is non-fatal
|
|
217
|
+
- **Exception classes**: All exceptions are in `exceptions.py` and subclass `DspVreUserError`
|
|
218
|
+
(the user can solve the problem) or `DspVreInternalError` (the user cannot).
|
|
219
|
+
Both subclass `DspVreBaseError`, which has a `message` attribute.
|
|
220
|
+
Do not import the exceptions of dsp-tools. dsp-tools catches these base classes in `cli/entry_point.py`.
|
|
221
|
+
|
|
222
|
+
### 401 vs 403: Authentication vs Authorization
|
|
223
|
+
|
|
224
|
+
It's crucial to distinguish between authentication failures (401) and authorization failures (403):
|
|
225
|
+
|
|
226
|
+
#### 401 Unauthorized - Authentication Failure
|
|
227
|
+
|
|
228
|
+
- **Meaning**: "Who are you?" - The request lacks credentials, or the credentials are invalid/expired
|
|
229
|
+
- **Example error message**: "Please ensure that an account for this email exists and that the password is correct."
|
|
230
|
+
- **Where to handle this**: Only in the authentication client. All other clients depend on the authentication client,
|
|
231
|
+
so it's pointless to handle 401 there.
|
|
232
|
+
- **Exception: the DSP-INGEST service.** As of 2026-10, it answers 401, not 403, when the user lacks write access
|
|
233
|
+
to the project (`ensureProjectWritable` in
|
|
234
|
+
[AuthorizationHandler.scala](https://github.com/dasch-swiss/dsp-api/blob/main/modules/ingest/src/main/scala/swiss/dasch/api/AuthorizationHandler.scala)).
|
|
235
|
+
It also answers 401 when it rejects the token.
|
|
236
|
+
`DspIngestClientLive.ingest` and the `BulkIngestClient` methods `upload_file`, `trigger_ingest_process`
|
|
237
|
+
and `retrieve_mapping_generator` therefore map 401 and 403 to `BadCredentialsError`,
|
|
238
|
+
and their messages name both causes.
|
|
239
|
+
`BulkIngestClient` raises on the first refusal and does not return an `UploadFailure`,
|
|
240
|
+
because every later request gets the same answer.
|
|
241
|
+
|
|
242
|
+
#### 403 Forbidden - Authorization Failure
|
|
243
|
+
|
|
244
|
+
- **Meaning**: "I know who you are, but you can't do that" - The user is authenticated but lacks sufficient permissions
|
|
245
|
+
- **When to use**: Insufficient role/permissions, project membership required, admin-only actions
|
|
246
|
+
- **Example error message**: "Only a SystemAdmin or ProjectAdmin can create new copyright holders."
|
|
247
|
+
- **Naming roles**: Name a role in the message only after you read the check that DSP-API enforces for that route
|
|
248
|
+
(for example `auth.ensureSystemAdmin` or `ensureSystemAdminOrProjectAdmin`).
|
|
249
|
+
If you are not sure, write "Your permissions are insufficient for this action." and name no role.
|
|
250
|
+
- **Where to handle this**: In all clients except the authentication client,
|
|
251
|
+
and except the clients that only access public endpoints.
|
|
252
|
+
|
|
253
|
+
#### Code Examples
|
|
254
|
+
|
|
255
|
+
Correct 401 handling (authentication):
|
|
256
|
+
|
|
257
|
+
```python
|
|
258
|
+
if response.status_code == HTTPStatus.UNAUTHORIZED:
|
|
259
|
+
raise BadCredentialsError("Authentication failed. Please check your credentials.")
|
|
260
|
+
```
|
|
261
|
+
|
|
262
|
+
Correct 403 handling (authorization):
|
|
263
|
+
|
|
264
|
+
```python
|
|
265
|
+
if response.status_code == HTTPStatus.FORBIDDEN:
|
|
266
|
+
raise BadCredentialsError(
|
|
267
|
+
"Only a SystemAdmin or ProjectAdmin can create new copyright holders. "
|
|
268
|
+
"Your permissions are insufficient for this action."
|
|
269
|
+
)
|
|
270
|
+
```
|
|
271
|
+
|
|
272
|
+
## Common Imports
|
|
273
|
+
|
|
274
|
+
All live clients typically import:
|
|
275
|
+
|
|
276
|
+
```python
|
|
277
|
+
import logging
|
|
278
|
+
from dataclasses import dataclass
|
|
279
|
+
from http import HTTPStatus
|
|
280
|
+
from typing import Any, cast
|
|
281
|
+
|
|
282
|
+
import requests
|
|
283
|
+
from requests import RequestException, Response
|
|
284
|
+
|
|
285
|
+
from dsp_vre.clients.<protocol_file> import <ProtocolClass>
|
|
286
|
+
from dsp_vre.clients.authentication_client import AuthenticationClient
|
|
287
|
+
from dsp_vre.clients.exceptions import BadCredentialsError
|
|
288
|
+
from dsp_vre.clients.exceptions import FatalNonOkApiResponseCodeError
|
|
289
|
+
from dsp_vre.clients.request_utils import (
|
|
290
|
+
RequestParameters,
|
|
291
|
+
log_and_raise_request_exception,
|
|
292
|
+
log_request,
|
|
293
|
+
log_response,
|
|
294
|
+
)
|
|
295
|
+
|
|
296
|
+
logger = logging.getLogger(__name__)
|
|
297
|
+
```
|
|
298
|
+
|
|
299
|
+
Log only with the standard `logging` module, never with loguru or `print`.
|
|
300
|
+
The module loggers are children of the logger `dsp_vre`. The caller configures handlers, formats and files.
|
|
301
|
+
A message for the user of a long operation (for example a retry or a timeout) goes to the logger
|
|
302
|
+
`dsp_vre.notices` at level INFO (`notices` in `request_utils.py`). dsp-tools prints this logger on the terminal.
|
|
303
|
+
Write a notice only with `notify(logger, msg)` from `request_utils.py`.
|
|
304
|
+
It writes the notice and one record on the module logger.
|
|
305
|
+
Notices do not propagate: the caller attaches a handler to `dsp_vre.notices`.
|
|
306
|
+
Messages and exceptions do not name dsp-tools commands. dsp-tools adds such hints where it catches the exception.
|
|
307
|
+
|
|
308
|
+
## Constants
|
|
309
|
+
|
|
310
|
+
- **Timeout values**: Define module-level constants for timeouts called `TIMEOUT_[number in seconds]`
|
|
311
|
+
(for example `TIMEOUT_10 = 10`)
|
|
312
|
+
- **Default values**: Use module-level constants for commonly used values
|
|
313
|
+
|
|
314
|
+
```python
|
|
315
|
+
TIMEOUT = 60
|
|
316
|
+
```
|
|
317
|
+
|
|
318
|
+
## Type Safety
|
|
319
|
+
|
|
320
|
+
- **Type hints**: All parameters, return types, and attributes must have type hints
|
|
321
|
+
- **JSON responses**: Use `cast()` when extracting values from JSON responses
|
|
322
|
+
- **Optional returns**: Use `| None` for methods that may return None
|
|
323
|
+
|
|
324
|
+
Example:
|
|
325
|
+
|
|
326
|
+
```python
|
|
327
|
+
def get_token(self) -> str:
|
|
328
|
+
res_json: dict[str, Any] = response.json()
|
|
329
|
+
tkn = cast(str, res_json["token"])
|
|
330
|
+
return tkn
|
|
331
|
+
```
|
|
332
|
+
|
|
333
|
+
## Testing Strategy
|
|
334
|
+
|
|
335
|
+
- **Mock implementations**: Create mock/fake clients implementing the Protocol for testing
|
|
336
|
+
- **Dependency injection**: Pass Protocol types to consumers, not concrete implementations
|
|
337
|
+
- **Unittesting**: Test live clients with mocked `requests` library.
|
|
338
|
+
The tests are in `test/unittests/clients/` of this package. Run them with `just vre-unittests`.
|
|
339
|
+
- **String patch targets**: Patch a name in the module that uses it (`dsp_vre.clients.<module>.<name>`),
|
|
340
|
+
not in the module that defines it. A patch on the defining module has no effect on a module that imported the name.
|
|
341
|
+
- **End-to-end testing**: Test against DSP-API in a test container
|
|
342
|
+
|
|
343
|
+
## Client Dependencies
|
|
344
|
+
|
|
345
|
+
Clients can depend on other clients (via their Protocol):
|
|
346
|
+
|
|
347
|
+
```python
|
|
348
|
+
@dataclass
|
|
349
|
+
class LegalInfoClientLive(LegalInfoClient):
|
|
350
|
+
server: str
|
|
351
|
+
project_shortcode: str
|
|
352
|
+
auth: AuthenticationClient # Protocol type, not concrete
|
|
353
|
+
```
|
|
354
|
+
|
|
355
|
+
This enables:
|
|
356
|
+
|
|
357
|
+
- Testing with mock authentication clients
|
|
358
|
+
- Flexibility in authentication strategy
|
|
359
|
+
- Clear dependency contracts
|
|
360
|
+
|
|
361
|
+
## Authentication Pattern
|
|
362
|
+
|
|
363
|
+
Clients requiring authentication:
|
|
364
|
+
|
|
365
|
+
1. Accept `auth: AuthenticationClient` as an attribute
|
|
366
|
+
2. Call `self.auth.get_token()` to get bearer token
|
|
367
|
+
3. Include token in `Authorization` header: `f"Bearer {self.auth.get_token()}"`
|
|
368
|
+
|
|
369
|
+
Example:
|
|
370
|
+
|
|
371
|
+
```python
|
|
372
|
+
headers = {
|
|
373
|
+
"Content-Type": "application/json",
|
|
374
|
+
"Authorization": f"Bearer {self.auth.get_token()}",
|
|
375
|
+
}
|
|
376
|
+
```
|
|
377
|
+
|
|
378
|
+
## Best Practices
|
|
379
|
+
|
|
380
|
+
### DO
|
|
381
|
+
|
|
382
|
+
- Use `@dataclass` decorator for all live implementations
|
|
383
|
+
- Log all requests and responses using provided utilities
|
|
384
|
+
- Provide descriptive, actionable error messages
|
|
385
|
+
- Create custom Error Classes if it makes sense
|
|
386
|
+
- Use module-level constants for timeouts
|
|
387
|
+
- Handle specific HTTP status codes with appropriate exceptions
|
|
388
|
+
- Type hint all parameters and return values
|
|
389
|
+
- Use private methods (prefix with `_`) for internal helpers
|
|
390
|
+
- Follow the standardized request workflow
|
|
391
|
+
|
|
392
|
+
### DON'T
|
|
393
|
+
|
|
394
|
+
- Skip request/response logging
|
|
395
|
+
- Use generic error messages
|
|
396
|
+
- Hardcode timeout values in method calls
|
|
397
|
+
- Pass `url`, `timeout`, or other local variables to `requests.<method>()` directly instead of the `params` values
|
|
398
|
+
- Catch exceptions without re-raising or logging
|
|
399
|
+
- Return raw response objects from public methods
|
|
400
|
+
- Mix business logic with HTTP communication
|
|
401
|
+
|
|
402
|
+
## Naming Conventions
|
|
403
|
+
|
|
404
|
+
- **Protocol files**: `<domain>_client.py`
|
|
405
|
+
- **Protocol classes**: `<Domain>Client`
|
|
406
|
+
- **Implementation files**: `<domain>_client_live.py`
|
|
407
|
+
- **Implementation classes**: `<Domain>ClientLive`
|
|
408
|
+
- **Private methods**: `_<method_name>`
|
|
409
|
+
- **Helper methods**: `_<verb>_and_log_request` for HTTP helpers
|
|
410
|
+
|
|
411
|
+
## Example: Creating a New Client
|
|
412
|
+
|
|
413
|
+
A client method that only dsp-tools calls is unused within this package.
|
|
414
|
+
Add its name to `packages/dsp-vre/.vulture_whitelist.py`, or `just vulture-vre` fails.
|
|
415
|
+
|
|
416
|
+
First: Define the Protocol in `src/dsp_vre/clients/<domain>_client.py`:
|
|
417
|
+
|
|
418
|
+
```python
|
|
419
|
+
from typing import Protocol
|
|
420
|
+
|
|
421
|
+
|
|
422
|
+
class UserClient(Protocol):
|
|
423
|
+
server: str
|
|
424
|
+
auth: AuthenticationClient
|
|
425
|
+
|
|
426
|
+
def get_user(self, user_iri: str) -> dict[str, Any]:
|
|
427
|
+
"""Get user information by IRI"""
|
|
428
|
+
```
|
|
429
|
+
|
|
430
|
+
Second: Implement the live client in `src/dsp_vre/clients/<domain>_client_live.py`:
|
|
431
|
+
|
|
432
|
+
```python
|
|
433
|
+
from dataclasses import dataclass
|
|
434
|
+
from http import HTTPStatus
|
|
435
|
+
from typing import Any
|
|
436
|
+
|
|
437
|
+
import requests
|
|
438
|
+
from requests import RequestException
|
|
439
|
+
|
|
440
|
+
from dsp_vre.clients.authentication_client import AuthenticationClient
|
|
441
|
+
from dsp_vre.clients.exceptions import BadCredentialsError
|
|
442
|
+
from dsp_vre.clients.exceptions import FatalNonOkApiResponseCodeError
|
|
443
|
+
from dsp_vre.clients.group_user_clients import UserClient
|
|
444
|
+
from dsp_vre.clients.request_utils import (
|
|
445
|
+
RequestParameters,
|
|
446
|
+
log_and_raise_request_exception,
|
|
447
|
+
log_request,
|
|
448
|
+
log_response,
|
|
449
|
+
)
|
|
450
|
+
|
|
451
|
+
TIMEOUT = 60
|
|
452
|
+
|
|
453
|
+
|
|
454
|
+
@dataclass
|
|
455
|
+
class UserClientLive(UserClient):
|
|
456
|
+
server: str
|
|
457
|
+
auth: AuthenticationClient
|
|
458
|
+
|
|
459
|
+
def get_user(self, user_iri: str) -> dict[str, Any]:
|
|
460
|
+
url = f"{self.server}/admin/users/{user_iri}"
|
|
461
|
+
headers = {
|
|
462
|
+
"Authorization": f"Bearer {self.auth.get_token()}",
|
|
463
|
+
}
|
|
464
|
+
params = RequestParameters("GET", url, TIMEOUT, headers=headers)
|
|
465
|
+
log_request(params)
|
|
466
|
+
|
|
467
|
+
try:
|
|
468
|
+
response = requests.get(
|
|
469
|
+
url=params.url,
|
|
470
|
+
headers=params.headers,
|
|
471
|
+
timeout=params.timeout,
|
|
472
|
+
)
|
|
473
|
+
except RequestException as err:
|
|
474
|
+
log_and_raise_request_exception(err)
|
|
475
|
+
|
|
476
|
+
log_response(response)
|
|
477
|
+
|
|
478
|
+
if response.ok:
|
|
479
|
+
return response.json()
|
|
480
|
+
|
|
481
|
+
if response.status_code == HTTPStatus.FORBIDDEN:
|
|
482
|
+
raise BadCredentialsError("You don't have permission to access user information.")
|
|
483
|
+
raise FatalNonOkApiResponseCodeError(url, response.status_code, response.text)
|
|
484
|
+
```
|
|
485
|
+
|
|
486
|
+
## Related Documentation
|
|
487
|
+
|
|
488
|
+
- Request utilities: `src/dsp_vre/clients/request_utils.py`
|
|
489
|
+
- Exception definitions: `src/dsp_vre/clients/exceptions.py`
|
|
490
|
+
- Package documentation: `../../../CLAUDE.md` (dsp-vre)
|
|
491
|
+
- Repository documentation: `/CLAUDE.md`
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
from dsp_vre.clients.authentication_client import AuthenticationClient
|
|
2
|
+
from dsp_vre.clients.bulk_ingest_client import BulkIngestClient
|
|
3
|
+
from dsp_vre.clients.connection import Connection
|
|
4
|
+
from dsp_vre.clients.connection_live import ConnectionLive
|
|
5
|
+
from dsp_vre.clients.data_import_client import DataImportClient
|
|
6
|
+
from dsp_vre.clients.data_import_client import DataImportId
|
|
7
|
+
from dsp_vre.clients.data_import_client import DataImportStatus
|
|
8
|
+
from dsp_vre.clients.data_import_client import DataImportStatusValue
|
|
9
|
+
from dsp_vre.clients.group_user_clients import GroupClient
|
|
10
|
+
from dsp_vre.clients.group_user_clients import UserClient
|
|
11
|
+
from dsp_vre.clients.group_user_clients_live import GroupClientLive
|
|
12
|
+
from dsp_vre.clients.group_user_clients_live import UserClientLive
|
|
13
|
+
from dsp_vre.clients.ingest import DspIngestClientLive
|
|
14
|
+
from dsp_vre.clients.legal_info_client import LegalInfoClient
|
|
15
|
+
from dsp_vre.clients.legal_info_client_live import LegalInfoClientLive
|
|
16
|
+
from dsp_vre.clients.mapping_client import MappingClient
|
|
17
|
+
from dsp_vre.clients.mapping_client_live import MappingClientLive
|
|
18
|
+
from dsp_vre.clients.metadata_client import ExistingResourcesRetrieved
|
|
19
|
+
from dsp_vre.clients.metadata_client_live import MetadataClientLive
|
|
20
|
+
from dsp_vre.clients.migration_clients import ExportId
|
|
21
|
+
from dsp_vre.clients.migration_clients import ExportImportStatus
|
|
22
|
+
from dsp_vre.clients.migration_clients import ImportId
|
|
23
|
+
from dsp_vre.clients.migration_clients import MigrationExportClient
|
|
24
|
+
from dsp_vre.clients.migration_clients import MigrationImportClient
|
|
25
|
+
from dsp_vre.clients.ontology_clients import OntologyCreateClient
|
|
26
|
+
from dsp_vre.clients.ontology_clients import OntologyGetClient
|
|
27
|
+
from dsp_vre.clients.ontology_get_client_live import OntologyGetClientLive
|
|
28
|
+
from dsp_vre.clients.permissions_client import PermissionsClient
|
|
29
|
+
from dsp_vre.clients.permissions_client_live import PermissionsClientLive
|
|
30
|
+
from dsp_vre.clients.project_client import ProjectClient
|
|
31
|
+
from dsp_vre.clients.resource_client import ResourceClient
|
|
32
|
+
|
|
33
|
+
__all__ = [
|
|
34
|
+
"AuthenticationClient",
|
|
35
|
+
"BulkIngestClient",
|
|
36
|
+
"Connection",
|
|
37
|
+
"ConnectionLive",
|
|
38
|
+
"DataImportClient",
|
|
39
|
+
"DataImportId",
|
|
40
|
+
"DataImportStatus",
|
|
41
|
+
"DataImportStatusValue",
|
|
42
|
+
"DspIngestClientLive",
|
|
43
|
+
"ExistingResourcesRetrieved",
|
|
44
|
+
"ExportId",
|
|
45
|
+
"ExportImportStatus",
|
|
46
|
+
"GroupClient",
|
|
47
|
+
"GroupClientLive",
|
|
48
|
+
"ImportId",
|
|
49
|
+
"LegalInfoClient",
|
|
50
|
+
"LegalInfoClientLive",
|
|
51
|
+
"MappingClient",
|
|
52
|
+
"MappingClientLive",
|
|
53
|
+
"MetadataClientLive",
|
|
54
|
+
"MigrationExportClient",
|
|
55
|
+
"MigrationImportClient",
|
|
56
|
+
"OntologyCreateClient",
|
|
57
|
+
"OntologyGetClient",
|
|
58
|
+
"OntologyGetClientLive",
|
|
59
|
+
"PermissionsClient",
|
|
60
|
+
"PermissionsClientLive",
|
|
61
|
+
"ProjectClient",
|
|
62
|
+
"ResourceClient",
|
|
63
|
+
"UserClient",
|
|
64
|
+
"UserClientLive",
|
|
65
|
+
]
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
from typing import Protocol
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class AuthenticationClient(Protocol):
|
|
5
|
+
"""
|
|
6
|
+
Protocol for a client that can authenticate with a DSP server and returns a token.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
server: str
|
|
10
|
+
email: str
|
|
11
|
+
password: str
|
|
12
|
+
|
|
13
|
+
def get_token(self) -> str:
|
|
14
|
+
pass
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
from dataclasses import dataclass
|
|
2
|
+
from http import HTTPStatus
|
|
3
|
+
from typing import Any
|
|
4
|
+
from typing import cast
|
|
5
|
+
|
|
6
|
+
import requests
|
|
7
|
+
from requests import RequestException
|
|
8
|
+
|
|
9
|
+
from dsp_vre.clients.authentication_client import AuthenticationClient
|
|
10
|
+
from dsp_vre.clients.exceptions import BadCredentialsError
|
|
11
|
+
from dsp_vre.clients.exceptions import FatalNonOkApiResponseCodeError
|
|
12
|
+
from dsp_vre.clients.request_utils import USER_AGENT
|
|
13
|
+
from dsp_vre.clients.request_utils import RequestParameters
|
|
14
|
+
from dsp_vre.clients.request_utils import log_and_raise_request_exception
|
|
15
|
+
from dsp_vre.clients.request_utils import log_request
|
|
16
|
+
from dsp_vre.clients.request_utils import log_response
|
|
17
|
+
|
|
18
|
+
TIMEOUT_10 = 10
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@dataclass
|
|
22
|
+
class AuthenticationClientLive(AuthenticationClient):
|
|
23
|
+
"""
|
|
24
|
+
Client that can authenticate with a DSP server and return a token.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
server: str
|
|
28
|
+
email: str
|
|
29
|
+
password: str
|
|
30
|
+
_token: str | None = None
|
|
31
|
+
|
|
32
|
+
def get_token(self) -> str:
|
|
33
|
+
"""
|
|
34
|
+
Returns a token. If no token is available, it will get one from the server.
|
|
35
|
+
"""
|
|
36
|
+
if self._token:
|
|
37
|
+
return self._token
|
|
38
|
+
return self._get_token()
|
|
39
|
+
|
|
40
|
+
def _get_token(self) -> str:
|
|
41
|
+
url = f"{self.server}/v2/authentication"
|
|
42
|
+
payload = {"email": self.email, "password": self.password}
|
|
43
|
+
headers = {"User-Agent": USER_AGENT}
|
|
44
|
+
request_params = RequestParameters("POST", url, data=payload, timeout=TIMEOUT_10, headers=headers)
|
|
45
|
+
log_request(request_params)
|
|
46
|
+
try:
|
|
47
|
+
response = requests.post(
|
|
48
|
+
request_params.url,
|
|
49
|
+
json=request_params.data,
|
|
50
|
+
headers=request_params.headers,
|
|
51
|
+
timeout=request_params.timeout,
|
|
52
|
+
)
|
|
53
|
+
except RequestException as err:
|
|
54
|
+
log_and_raise_request_exception(err)
|
|
55
|
+
|
|
56
|
+
match response.status_code:
|
|
57
|
+
case HTTPStatus.OK:
|
|
58
|
+
log_response(response, include_response_content=False, status_code=response.status_code)
|
|
59
|
+
res_json: dict[str, Any] = response.json()
|
|
60
|
+
tkn = cast(str, res_json["token"])
|
|
61
|
+
self._token = tkn
|
|
62
|
+
return tkn
|
|
63
|
+
case HTTPStatus.UNAUTHORIZED | HTTPStatus.BAD_REQUEST:
|
|
64
|
+
log_response(response, status_code=response.status_code)
|
|
65
|
+
raise BadCredentialsError(
|
|
66
|
+
f"Login to the API with the email '{self.email}' was not successful. "
|
|
67
|
+
f"Please ensure that an account for this email exists and that the password is correct."
|
|
68
|
+
)
|
|
69
|
+
case _:
|
|
70
|
+
log_response(response, status_code=response.status_code)
|
|
71
|
+
raise FatalNonOkApiResponseCodeError(url, response.status_code, response.text)
|