dsp-vre 0.1.0__tar.gz

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.
Files changed (42) hide show
  1. dsp_vre-0.1.0/PKG-INFO +28 -0
  2. dsp_vre-0.1.0/README.md +8 -0
  3. dsp_vre-0.1.0/pyproject.toml +80 -0
  4. dsp_vre-0.1.0/pyproject.toml.orig +79 -0
  5. dsp_vre-0.1.0/src/dsp_vre/__init__.py +6 -0
  6. dsp_vre-0.1.0/src/dsp_vre/clients/CLAUDE.md +491 -0
  7. dsp_vre-0.1.0/src/dsp_vre/clients/__init__.py +65 -0
  8. dsp_vre-0.1.0/src/dsp_vre/clients/authentication_client.py +14 -0
  9. dsp_vre-0.1.0/src/dsp_vre/clients/authentication_client_live.py +71 -0
  10. dsp_vre-0.1.0/src/dsp_vre/clients/bulk_ingest_client.py +214 -0
  11. dsp_vre-0.1.0/src/dsp_vre/clients/client_warnings.py +2 -0
  12. dsp_vre-0.1.0/src/dsp_vre/clients/connection.py +35 -0
  13. dsp_vre-0.1.0/src/dsp_vre/clients/connection_live.py +238 -0
  14. dsp_vre-0.1.0/src/dsp_vre/clients/data_import_client.py +46 -0
  15. dsp_vre-0.1.0/src/dsp_vre/clients/data_import_client_live.py +176 -0
  16. dsp_vre-0.1.0/src/dsp_vre/clients/exceptions.py +182 -0
  17. dsp_vre-0.1.0/src/dsp_vre/clients/group_user_clients.py +35 -0
  18. dsp_vre-0.1.0/src/dsp_vre/clients/group_user_clients_live.py +178 -0
  19. dsp_vre-0.1.0/src/dsp_vre/clients/ingest.py +117 -0
  20. dsp_vre-0.1.0/src/dsp_vre/clients/legal_info_client.py +23 -0
  21. dsp_vre-0.1.0/src/dsp_vre/clients/legal_info_client_live.py +132 -0
  22. dsp_vre-0.1.0/src/dsp_vre/clients/list_client.py +39 -0
  23. dsp_vre-0.1.0/src/dsp_vre/clients/list_client_live.py +151 -0
  24. dsp_vre-0.1.0/src/dsp_vre/clients/mapping_client.py +21 -0
  25. dsp_vre-0.1.0/src/dsp_vre/clients/mapping_client_live.py +104 -0
  26. dsp_vre-0.1.0/src/dsp_vre/clients/metadata_client.py +24 -0
  27. dsp_vre-0.1.0/src/dsp_vre/clients/metadata_client_live.py +49 -0
  28. dsp_vre-0.1.0/src/dsp_vre/clients/migration_clients.py +58 -0
  29. dsp_vre-0.1.0/src/dsp_vre/clients/migration_clients_live.py +198 -0
  30. dsp_vre-0.1.0/src/dsp_vre/clients/ontology_clients.py +49 -0
  31. dsp_vre-0.1.0/src/dsp_vre/clients/ontology_create_client_live.py +165 -0
  32. dsp_vre-0.1.0/src/dsp_vre/clients/ontology_get_client_live.py +81 -0
  33. dsp_vre-0.1.0/src/dsp_vre/clients/permissions_client.py +27 -0
  34. dsp_vre-0.1.0/src/dsp_vre/clients/permissions_client_live.py +102 -0
  35. dsp_vre-0.1.0/src/dsp_vre/clients/project_client.py +19 -0
  36. dsp_vre-0.1.0/src/dsp_vre/clients/project_client_live.py +83 -0
  37. dsp_vre-0.1.0/src/dsp_vre/clients/request_utils.py +279 -0
  38. dsp_vre-0.1.0/src/dsp_vre/clients/resource_client.py +20 -0
  39. dsp_vre-0.1.0/src/dsp_vre/clients/resource_client_live.py +96 -0
  40. dsp_vre-0.1.0/src/dsp_vre/clients/value_client.py +22 -0
  41. dsp_vre-0.1.0/src/dsp_vre/clients/value_client_live.py +87 -0
  42. dsp_vre-0.1.0/src/dsp_vre/py.typed +0 -0
dsp_vre-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,28 @@
1
+ Metadata-Version: 2.3
2
+ Name: dsp-vre
3
+ Version: 0.1.0
4
+ Summary: dsp-vre is a Python client library for the DSP-API of a DaSCH Service Platform (DSP) server.
5
+ Author: DaSCH - Swiss National Data and Service Center for the Humanities
6
+ Author-email: DaSCH - Swiss National Data and Service Center for the Humanities <info@dasch.swiss>
7
+ Classifier: Programming Language :: Python :: 3.12
8
+ Classifier: Programming Language :: Python :: 3.13
9
+ Classifier: Programming Language :: Python :: 3.14
10
+ Classifier: License :: OSI Approved :: GNU General Public License v3 (GPLv3)
11
+ Classifier: Operating System :: OS Independent
12
+ Classifier: Typing :: Typed
13
+ Requires-Dist: rdflib
14
+ Requires-Dist: regex
15
+ Requires-Dist: requests
16
+ Requires-Python: >=3.12
17
+ Project-URL: Homepage, https://www.dasch.swiss/
18
+ Project-URL: Repository, https://github.com/dasch-swiss/dsp-tools.git
19
+ Description-Content-Type: text/markdown
20
+
21
+ # dsp-vre
22
+
23
+ `dsp-vre` is a Python client library for the DSP-API of a DaSCH Service Platform (DSP) server.
24
+ DaSCH tools, DaSCH services and researchers use it in their code.
25
+
26
+ The package is in an early stage and has no public interface yet.
27
+ The decisions about the interface are in the
28
+ [ADR for `dsp-vre`](docs/adr/0001-public-interface.md).
@@ -0,0 +1,8 @@
1
+ # dsp-vre
2
+
3
+ `dsp-vre` is a Python client library for the DSP-API of a DaSCH Service Platform (DSP) server.
4
+ DaSCH tools, DaSCH services and researchers use it in their code.
5
+
6
+ The package is in an early stage and has no public interface yet.
7
+ The decisions about the interface are in the
8
+ [ADR for `dsp-vre`](docs/adr/0001-public-interface.md).
@@ -0,0 +1,80 @@
1
+ [project]
2
+ name = "dsp-vre"
3
+ version = "0.1.0"
4
+ description = "dsp-vre is a Python client library for the DSP-API of a DaSCH Service Platform (DSP) server."
5
+ readme = "README.md"
6
+ classifiers = [
7
+ "Programming Language :: Python :: 3.12",
8
+ "Programming Language :: Python :: 3.13",
9
+ "Programming Language :: Python :: 3.14",
10
+ "License :: OSI Approved :: GNU General Public License v3 (GPLv3)",
11
+ "Operating System :: OS Independent",
12
+ "Typing :: Typed",
13
+ ]
14
+ requires-python = ">=3.12"
15
+ dependencies = [
16
+ "rdflib",
17
+ "regex",
18
+ "requests",
19
+ ]
20
+
21
+ [[project.authors]]
22
+ name = "DaSCH - Swiss National Data and Service Center for the Humanities"
23
+ email = "info@dasch.swiss"
24
+
25
+ [project.urls]
26
+ Homepage = "https://www.dasch.swiss/"
27
+ Repository = "https://github.com/dasch-swiss/dsp-tools.git"
28
+
29
+ [build-system]
30
+ requires = ["uv_build>=0.8.13"]
31
+ build-backend = "uv_build"
32
+
33
+ [tool.pytest.ini_options]
34
+ addopts = ["--import-mode=importlib"]
35
+ pythonpath = [
36
+ ".",
37
+ "src",
38
+ "test",
39
+ ]
40
+ filterwarnings = [
41
+ "ignore:Code. _mock_name is not defined in namespace XSD:UserWarning",
42
+ "ignore:ConjunctiveGraph is deprecated:DeprecationWarning:rdflib.plugins.parsers.jsonld",
43
+ ]
44
+
45
+ [tool.mypy]
46
+ python_version = "3.12"
47
+ show_column_numbers = true
48
+ strict = true
49
+ enable_error_code = ["possibly-undefined"]
50
+
51
+ [[tool.mypy.overrides]]
52
+ module = ["test/*"]
53
+ disable_error_code = [
54
+ "no-untyped-def",
55
+ "method-assign",
56
+ ]
57
+
58
+ [tool.ruff]
59
+ extend = "../../pyproject.toml"
60
+
61
+ [tool.ruff.lint.extend-per-file-ignores]
62
+ "test/*" = [
63
+ "S101",
64
+ "PLC2701",
65
+ "D103",
66
+ ]
67
+
68
+ [tool.ruff.lint.flake8-tidy-imports.banned-api.dsp_tools]
69
+ msg = "dsp_vre must not import dsp_tools"
70
+
71
+ [tool.ruff.lint.flake8-tidy-imports.banned-api.loguru]
72
+ msg = "dsp_vre logs with the standard logging module (ADR 0001)"
73
+
74
+ [tool.vulture]
75
+ paths = [
76
+ "src/dsp_vre",
77
+ ".vulture_whitelist.py",
78
+ ]
79
+ exclude = ["test/"]
80
+ sort_by_size = true
@@ -0,0 +1,79 @@
1
+ [project]
2
+ name = "dsp-vre"
3
+ version = "0.1.0"
4
+ description = "dsp-vre is a Python client library for the DSP-API of a DaSCH Service Platform (DSP) server."
5
+ authors = [
6
+ { name = "DaSCH - Swiss National Data and Service Center for the Humanities", email = "info@dasch.swiss" },
7
+ ]
8
+ readme = "README.md"
9
+ classifiers = [
10
+ "Programming Language :: Python :: 3.12",
11
+ "Programming Language :: Python :: 3.13",
12
+ "Programming Language :: Python :: 3.14",
13
+ "License :: OSI Approved :: GNU General Public License v3 (GPLv3)",
14
+ "Operating System :: OS Independent",
15
+ "Typing :: Typed",
16
+ ]
17
+ requires-python = ">=3.12"
18
+ dependencies = [
19
+ "rdflib",
20
+ "regex",
21
+ "requests",
22
+ ]
23
+
24
+
25
+ [project.urls]
26
+ Homepage = "https://www.dasch.swiss/"
27
+ Repository = "https://github.com/dasch-swiss/dsp-tools.git"
28
+
29
+
30
+ [build-system]
31
+ requires = ["uv_build>=0.8.13"]
32
+ build-backend = "uv_build"
33
+
34
+
35
+ [tool.pytest.ini_options]
36
+ addopts = ["--import-mode=importlib"]
37
+ pythonpath = [".", "src", "test"]
38
+ filterwarnings = [
39
+ # pytest looks up "_mock_name" on each module attribute, and the rdflib namespace XSD warns about unknown names.
40
+ "ignore:Code. _mock_name is not defined in namespace XSD:UserWarning",
41
+ # The rdflib JSON-LD parser uses ConjunctiveGraph internally. This is not in our code.
42
+ "ignore:ConjunctiveGraph is deprecated:DeprecationWarning:rdflib.plugins.parsers.jsonld",
43
+ ]
44
+
45
+
46
+ [tool.mypy]
47
+ python_version = "3.12"
48
+ show_column_numbers = true
49
+ strict = true
50
+ enable_error_code = ["possibly-undefined"]
51
+
52
+
53
+ [[tool.mypy.overrides]]
54
+ module = ["test/*"]
55
+ disable_error_code = ["no-untyped-def", "method-assign"]
56
+
57
+
58
+ [tool.ruff]
59
+ extend = "../../pyproject.toml"
60
+
61
+
62
+ [tool.ruff.lint.extend-per-file-ignores]
63
+ "test/*" = [
64
+ "S101", # flake8-bandit: use of assert
65
+ "PLC2701", # import of private function
66
+ "D103", # pydocstyle: undocumented-public-function
67
+ ]
68
+
69
+
70
+ [tool.ruff.lint.flake8-tidy-imports.banned-api]
71
+ # The dependency goes in one direction only: dsp-tools uses dsp-vre, never the reverse.
72
+ "dsp_tools".msg = "dsp_vre must not import dsp_tools"
73
+ "loguru".msg = "dsp_vre logs with the standard logging module (ADR 0001)"
74
+
75
+
76
+ [tool.vulture]
77
+ paths = ["src/dsp_vre", ".vulture_whitelist.py"]
78
+ exclude = ["test/"]
79
+ sort_by_size = true # sort unused classes and functions by size
@@ -0,0 +1,6 @@
1
+ """Python client library for the DSP-API of a DSP server."""
2
+
3
+ import logging
4
+
5
+ # A library adds no output of its own: without a handler of the caller, Python prints warnings on stderr.
6
+ logging.getLogger("dsp_vre").addHandler(logging.NullHandler())
@@ -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`