src/rdflib/contrib/graphdb/client.py
1"""GraphDB client module."""
2
3from __future__ import annotations
4
5import json
6import os
7import pathlib
8import typing as t
9
10import httpx
11
12import rdflib.contrib.rdf4j
13from rdflib import Graph, Literal, URIRef
14from rdflib.contrib.graphdb.exceptions import (
15 BadRequestError,
16 ConflictError,
17 ForbiddenError,
18 InternalServerError,
19 NotFoundError,
20 PreconditionFailedError,
21 RepositoryNotFoundError,
22 RepositoryNotHealthyError,
23 ResponseFormatError,
24 ServiceUnavailableError,
25 UnauthorisedError,
26)
27from rdflib.contrib.graphdb.models import (
28 AccessControlEntry,
29 AuthenticatedUser,
30 BackupOperationBean,
31 ClearGraphAccessControlEntry,
32 ClusterRequest,
33 FreeAccessSettings,
34 GraphDBRepository,
35 ImportSettings,
36 InfrastructureStatistics,
37 NodeStatus,
38 ParserSettings,
39 PluginAccessControlEntry,
40 RepositoryConfigBean,
41 RepositoryConfigBeanCreate,
42 RepositorySizeInfo,
43 RepositoryStatistics,
44 ServerImportBody,
45 StatementAccessControlEntry,
46 StructuresStatistics,
47 SystemAccessControlEntry,
48 User,
49 UserCreate,
50 UserUpdate,
51 _parse_operation,
52 _parse_plugin,
53 _parse_policy,
54 _parse_role,
55)
56from rdflib.contrib.graphdb.util import (
57 extract_filename_from_content_disposition,
58 infer_filename_from_fileobj,
59)
60from rdflib.contrib.rdf4j import RDF4JClient
61
62FileContent = t.Union[
63 bytes,
64 str,
65 t.IO[bytes],
66 t.Tuple[t.Optional[str], t.Union[bytes, str, t.IO[bytes]]],
67 t.Tuple[t.Optional[str], t.Union[bytes, str, t.IO[bytes]], t.Optional[str]],
68]
69
70FilesType = t.Union[
71 t.Mapping[str, FileContent],
72 t.Iterable[t.Tuple[str, FileContent]],
73]
74
75_ALLOWED_FGAC_SCOPES = {"statement", "clear_graph", "plugin", "system"}
76
77
78class AccessControlListManagement:
79 """Manage fine-grained access control lists for GraphDB repositories."""
80
81 def __init__(self, identifier: str, http_client: httpx.Client):
82 self._identifier = identifier
83 self._http_client = http_client
84
85 @property
86 def http_client(self):
87 return self._http_client
88
89 @property
90 def identifier(self):
91 """Repository identifier."""
92 return self._identifier
93
94 def list(
95 self,
96 scope: t.Literal["statement", "clear_graph", "plugin", "system"] | None = None,
97 operation: t.Literal["read", "write", "*"] | None = None,
98 subject: str | URIRef | None = None,
99 predicate: str | URIRef | None = None,
100 obj: str | URIRef | Literal | None = None,
101 graph: t.Literal["*", "named", "default"] | URIRef | Graph | None = None,
102 plugin: str | None = None,
103 role: str | None = None,
104 policy: t.Literal["allow", "deny", "abstain"] | None = None,
105 ) -> t.List[
106 SystemAccessControlEntry
107 | StatementAccessControlEntry
108 | PluginAccessControlEntry
109 | ClearGraphAccessControlEntry
110 ]:
111 """
112 List ACL rules for the repository.
113
114 Parameters:
115 scope: The scope of the FGAC rule (`statement`, `clear_graph`, `plugin`, `system`).
116 operation: The operation of the FGAC rule (`read`, `write`, `*`).
117 subject: The subject of the FGAC rule in Turtle format (for example, `<http://example.com/Mary>`).
118 predicate: The predicate of the FGAC rule in Turtle format (for example, `<http://www.w3.org/2000/01/rdf-schema#label>`).
119 obj: The object of the FGAC rule in Turtle format (for example, `"Mary"@en`).
120 graph: The graph of the FGAC rule in Turtle format (for example, `<http://example.org/graphs/graph1>`).
121 plugin: The plugin name for the FGAC rule with plugin scope (for example, `elasticsearch-connector`).
122 role: The role associated with the FGAC rule.
123 policy: The policy for the FGAC rule (`allow`, `deny`, `abstain`).
124
125 Returns:
126 A list of FGAC rules.
127
128 Raises:
129 ValueError: If the parameters are invalid.
130 UnauthorisedError: If the request is unauthorised.
131 ForbiddenError: If the request is forbidden.
132 InternalServerError: If the server returns an internal error.
133 ResponseFormatError: If the response cannot be parsed.
134 """
135 params: dict[str, str] = {}
136 if scope is not None:
137 if scope not in _ALLOWED_FGAC_SCOPES:
138 raise ValueError(f"Invalid FGAC scope filter: {scope!r}")
139 params["scope"] = scope
140 if operation is not None:
141 params["operation"] = _parse_operation(operation)
142 if subject is not None:
143 if isinstance(subject, URIRef):
144 params["subject"] = subject.n3()
145 elif isinstance(subject, str):
146 params["subject"] = subject
147 else:
148 raise ValueError(f"Invalid FGAC subject filter: {subject!r}")
149 if predicate is not None:
150 if isinstance(predicate, URIRef):
151 params["predicate"] = predicate.n3()
152 elif isinstance(predicate, str):
153 params["predicate"] = predicate
154 else:
155 raise ValueError(f"Invalid FGAC predicate filter: {predicate!r}")
156 if obj is not None:
157 if isinstance(obj, (URIRef, Literal)):
158 params["object"] = obj.n3()
159 elif isinstance(obj, str):
160 params["object"] = obj
161 else:
162 raise ValueError(f"Invalid FGAC object filter: {obj!r}")
163 if graph is not None:
164 if isinstance(graph, URIRef):
165 params["context"] = graph.n3()
166 elif isinstance(graph, Graph):
167 params["context"] = graph.identifier.n3()
168 elif isinstance(graph, str):
169 params["context"] = graph
170 else:
171 raise ValueError(f"Invalid FGAC graph filter: {graph!r}")
172 if plugin is not None:
173 params["plugin"] = _parse_plugin(plugin)
174 if role is not None:
175 params["role"] = _parse_role(role)
176 if policy is not None:
177 params["policy"] = _parse_policy(policy)
178
179 try:
180 response = self._http_client.get(
181 f"/rest/repositories/{self.identifier}/acl", params=params
182 )
183 response.raise_for_status()
184 try:
185 payload = response.json()
186 except (ValueError, TypeError) as err:
187 raise ResponseFormatError(
188 f"Failed to parse GraphDB response: {err}"
189 ) from err
190
191 if not isinstance(payload, list):
192 raise ResponseFormatError(
193 "Failed to parse GraphDB response: expected a list of ACL entries."
194 )
195
196 try:
197 return [AccessControlEntry.from_dict(acl) for acl in payload]
198 except (ValueError, TypeError) as err:
199 raise ResponseFormatError(
200 f"Failed to parse GraphDB response: {err}"
201 ) from err
202 except httpx.HTTPStatusError as err:
203 status = err.response.status_code
204 if status == 401:
205 raise UnauthorisedError(
206 f"Request is unauthorised: {err.response.text}"
207 ) from err
208 elif status == 403:
209 raise ForbiddenError(
210 f"Request is forbidden: {err.response.text}"
211 ) from err
212 elif status == 500:
213 raise InternalServerError(
214 f"Internal server error: {err.response.text}"
215 ) from err
216 raise
217
218 def set(self, acl_rules: t.Sequence[AccessControlEntry]):
219 """
220 Set ACL rules for the repository.
221
222 !!! Note
223 This method overwrites existing ACL rules in the repository.
224 If you want to add new rules without overwriting existing ones,
225 use the [`add`][rdflib.contrib.graphdb.client.AccessControlListManagement.add] method.
226
227 Parameters:
228 acl_rules: The list of ACL rules to set.
229
230 Raises:
231 BadRequestError: If the request is invalid.
232 UnauthorisedError: If the request is unauthorised.
233 ForbiddenError: If the request is forbidden.
234 InternalServerError: If the server returns an internal error.
235 ValueError: If the ACL rules are not provided as a sequence or are not AccessControlEntry instances.
236 """
237 acl_rules_list = list(acl_rules)
238 if any(not isinstance(rule, AccessControlEntry) for rule in acl_rules_list):
239 raise ValueError("All ACL rules must be AccessControlEntry instances.")
240
241 payload = [rule.as_dict() for rule in acl_rules_list]
242 headers = {"Content-Type": "application/json"}
243 try:
244 response = self._http_client.put(
245 f"/rest/repositories/{self.identifier}/acl",
246 headers=headers,
247 json=payload,
248 )
249 response.raise_for_status()
250 except httpx.HTTPStatusError as err:
251 status = err.response.status_code
252 if status == 400:
253 raise BadRequestError(f"Invalid request: {err.response.text}") from err
254 elif status == 401:
255 raise UnauthorisedError(
256 f"Request is unauthorised: {err.response.text}"
257 ) from err
258 elif status == 403:
259 raise ForbiddenError(
260 f"Request is forbidden: {err.response.text}"
261 ) from err
262 elif status == 500:
263 raise InternalServerError(
264 f"Internal server error: {err.response.text}"
265 ) from err
266 raise
267
268 def add(
269 self, acl_rules: t.Sequence[AccessControlEntry], position: int | None = None
270 ):
271 """
272 Add ACL rules to the repository.
273
274 You can also provide an optional URL request parameter position that specifies the position of the rules to be added.
275 The position is zero-based (0 is the first position). If the position parameter is not provided, the rules are added at
276 the end of the list.
277
278 Parameters:
279 acl_rules: The list of ACL rules to add.
280 position: The zero-based position to add the rules at.
281
282 Raises:
283 BadRequestError: If the request is invalid.
284 UnauthorisedError: If the request is unauthorised.
285 ForbiddenError: If the request is forbidden.
286 InternalServerError: If the server returns an internal error.
287 ValueError: If the position is not an integer or is a negative integer.
288 ValueError: If the ACL rules are not provided as a sequence or are not AccessControlEntry instances.
289 """
290 acl_rules_list = list(acl_rules)
291 if any(not isinstance(rule, AccessControlEntry) for rule in acl_rules_list):
292 raise ValueError("All ACL rules must be AccessControlEntry instances.")
293
294 payload = [rule.as_dict() for rule in acl_rules_list]
295 headers = {"Content-Type": "application/json"}
296 params = {}
297 if position is not None:
298 if not isinstance(position, int):
299 raise ValueError("Position must be an integer.")
300 if position < 0:
301 raise ValueError("Position must be a positive integer.")
302 params["position"] = str(position)
303 try:
304 response = self._http_client.post(
305 f"/rest/repositories/{self.identifier}/acl",
306 headers=headers,
307 json=payload,
308 params=params,
309 )
310 response.raise_for_status()
311 except httpx.HTTPStatusError as err:
312 status = err.response.status_code
313 if status == 400:
314 raise BadRequestError(f"Invalid request: {err.response.text}") from err
315 elif status == 401:
316 raise UnauthorisedError(
317 f"Request is unauthorised: {err.response.text}"
318 ) from err
319 elif status == 403:
320 raise ForbiddenError(
321 f"Request is forbidden: {err.response.text}"
322 ) from err
323 elif status == 500:
324 raise InternalServerError(
325 f"Internal server error: {err.response.text}"
326 ) from err
327 raise
328
329 def delete(self, acl_rules: t.Sequence[AccessControlEntry]):
330 """
331 Delete ACL rules from the repository.
332
333 The provided FGAC rules are removed from the list regardless of their position.
334
335 Parameters:
336 acl_rules: The list of ACL rules to delete.
337
338 Raises:
339 BadRequestError: If the request is invalid.
340 UnauthorisedError: If the request is unauthorised.
341 ForbiddenError: If the request is forbidden.
342 InternalServerError: If the server returns an internal error.
343 ValueError: If the ACL rules are not provided as a sequence or are not AccessControlEntry instances.
344 """
345 acl_rules_list = list(acl_rules)
346 if any(not isinstance(rule, AccessControlEntry) for rule in acl_rules_list):
347 raise ValueError("All ACL rules must be AccessControlEntry instances.")
348
349 payload = [rule.as_dict() for rule in acl_rules_list]
350 headers = {"Content-Type": "application/json"}
351 try:
352 response = self._http_client.request(
353 method="DELETE",
354 url=f"/rest/repositories/{self.identifier}/acl",
355 headers=headers,
356 json=payload,
357 )
358 response.raise_for_status()
359 except httpx.HTTPStatusError as err:
360 status = err.response.status_code
361 if status == 400:
362 raise BadRequestError(f"Invalid request: {err.response.text}") from err
363 elif status == 401:
364 raise UnauthorisedError(
365 f"Request is unauthorised: {err.response.text}"
366 ) from err
367 elif status == 403:
368 raise ForbiddenError(
369 f"Request is forbidden: {err.response.text}"
370 ) from err
371 elif status == 500:
372 raise InternalServerError(
373 f"Internal server error: {err.response.text}"
374 ) from err
375 raise
376
377
378class ClusterGroupManagement:
379 """Manage and monitor GraphDB cluster configurations."""
380
381 def __init__(self, http_client: httpx.Client):
382 self._http_client = http_client
383
384 @property
385 def http_client(self):
386 return self._http_client
387
388 def truncate_log(self) -> None:
389 """Truncate the GraphDB cluster log.
390
391 The truncate log operation is used to free up storage space on all cluster nodes by clearing the
392 current transaction log and removing cached recovery snapshots.
393
394 Raises:
395 ResponseFormatError: If the response is not in the expected format.
396 BadRequestError: If the request is invalid.
397 UnauthorisedError: If the request is unauthorised.
398 ForbiddenError: If the request is forbidden.
399 """
400 try:
401 response = self.http_client.post("/rest/cluster/truncate-log")
402 response.raise_for_status()
403 except httpx.HTTPStatusError as err:
404 status = err.response.status_code
405 if status == 400:
406 raise BadRequestError(f"Invalid request: {err.response.text}") from err
407 elif status == 401:
408 raise UnauthorisedError(
409 f"Request is unauthorised: {err.response.text}"
410 ) from err
411 elif status == 403:
412 raise ForbiddenError(
413 f"Request is forbidden: {err.response.text}"
414 ) from err
415 raise
416
417 def get_config(self) -> ClusterRequest:
418 """Get the GraphDB cluster configuration.
419
420 Returns:
421 Cluster configuration.
422
423 Raises:
424 ResponseFormatError: If the response is not in the expected format.
425 UnauthorisedError: If the request is unauthorised.
426 NotFoundError: If the cluster configuration is not found.
427 InternalServerError: If the server returns an internal error.
428 """
429 try:
430 headers = {"Accept": "application/json"}
431 response = self.http_client.get("/rest/cluster/config", headers=headers)
432 response.raise_for_status()
433 try:
434 return ClusterRequest.from_dict(response.json())
435 except (KeyError, TypeError, ValueError) as err:
436 raise ResponseFormatError(
437 f"Failed to parse cluster configuration: {err}"
438 ) from err
439 except httpx.HTTPStatusError as err:
440 status = err.response.status_code
441 if status == 401:
442 raise UnauthorisedError(
443 f"Request is unauthorised: {err.response.text}"
444 ) from err
445 elif status == 404:
446 raise NotFoundError(
447 f"Cluster configuration not found: {err.response.text}"
448 ) from err
449 elif status == 500:
450 raise InternalServerError(
451 f"Internal server error: {err.response.text}"
452 ) from err
453 raise
454
455 def create_config(
456 self,
457 nodes: list[str],
458 election_min_timeout: int | None = None,
459 election_range_timeout: int | None = None,
460 heartbeat_interval: int | None = None,
461 message_size_kb: int | None = None,
462 verification_timeout: int | None = None,
463 transaction_log_maximum_size_gb: int | None = None,
464 batch_update_interval: int | None = None,
465 ) -> None:
466 """Create a GraphDB cluster.
467
468 Parameters:
469 nodes: List of node addresses.
470 election_min_timeout: The minimum wait time in milliseconds for a heartbeat from a leader.
471 election_range_timeout: The variable portion of each waiting period in milliseconds for a heartbeat.
472 heartbeat_interval: The interval in milliseconds between each heartbeat that is sent to follower nodes by the leader.
473 message_size_kb: The size of the data blocks, in kilobytes, transferred during data replication streaming through the RPC protocol.
474 verification_timeout: The amount of time in milliseconds that a follower node would wait before attempting to verify the last committed
475 entry when the first verification is unsuccessful.
476 transaction_log_maximum_size_gb: Maximum size of the transaction log in GBs. The transaction log will be automatically truncated if it
477 becomes bigger than this value. The minimum transaction log size is 1 GB. Setting it to a negative value will disable automatic transaction
478 log truncation.
479 batch_update_interval: The interval in milliseconds between requesting updates from the primary cluster. Used only when the cluster is in
480 secondary mode.
481
482 Raises:
483 BadRequestError: If the request is invalid.
484 UnauthorisedError: If the request is unauthorised.
485 ForbiddenError: If the request is forbidden.
486 ConflictError: If the cluster configuration already exists.
487 PreconditionFailedError: If the cluster is not in a state to create a configuration.
488 """
489 try:
490 if not isinstance(nodes, list) or any(
491 not isinstance(node, str) for node in nodes
492 ):
493 raise TypeError("nodes must be a list[str].")
494
495 _int_fields: list[tuple[str, int | None]] = [
496 ("election_min_timeout", election_min_timeout),
497 ("election_range_timeout", election_range_timeout),
498 ("heartbeat_interval", heartbeat_interval),
499 ("message_size_kb", message_size_kb),
500 ("verification_timeout", verification_timeout),
501 ("transaction_log_maximum_size_gb", transaction_log_maximum_size_gb),
502 ("batch_update_interval", batch_update_interval),
503 ]
504 for field_name, value in _int_fields:
505 if value is not None and type(value) is not int:
506 raise TypeError(f"{field_name} must be an int if provided.")
507
508 payload: dict[str, t.Any] = {"nodes": nodes}
509 if election_min_timeout is not None:
510 payload["electionMinTimeout"] = election_min_timeout
511 if election_range_timeout is not None:
512 payload["electionRangeTimeout"] = election_range_timeout
513 if heartbeat_interval is not None:
514 payload["heartbeatInterval"] = heartbeat_interval
515 if message_size_kb is not None:
516 payload["messageSizeKB"] = message_size_kb
517 if verification_timeout is not None:
518 payload["verificationTimeout"] = verification_timeout
519 if transaction_log_maximum_size_gb is not None:
520 payload["transactionLogMaximumSizeGB"] = transaction_log_maximum_size_gb
521 if batch_update_interval is not None:
522 payload["batchUpdateInterval"] = batch_update_interval
523
524 headers = {"Content-Type": "application/json"}
525 response = self.http_client.post(
526 "/rest/cluster/config", headers=headers, json=payload
527 )
528 response.raise_for_status()
529 except httpx.HTTPStatusError as err:
530 status = err.response.status_code
531 if status == 400:
532 raise BadRequestError(f"Invalid request: {err.response.text}") from err
533 elif status == 401:
534 raise UnauthorisedError(
535 f"Request is unauthorised: {err.response.text}"
536 ) from err
537 elif status == 403:
538 raise ForbiddenError(
539 f"Request is forbidden: {err.response.text}"
540 ) from err
541 elif status == 409:
542 raise ConflictError(
543 f"Cluster configuration already exists: {err.response.text}"
544 ) from err
545 elif status == 412:
546 raise PreconditionFailedError(
547 f"Precondition failed: {err.response.text}"
548 ) from err
549 raise
550
551 def delete_config(self, force: bool | None = None) -> dict[str, str]:
552 """Delete the GraphDB cluster.
553
554 By default, the cluster group cannot be deleted if one or more nodes are unreachable.
555 Reachable here means that the nodes are not in status `NO_CONNECTION`, therefore there is an
556 RPC connection to them.
557
558 Parameter:
559 force: When set to `True`, the cluster configuration will be deleted only on the reachable nodes and
560 the response will always succeed.
561
562 Returns:
563 A dictionary where the node address is the key and the deletion status message is the value.
564
565 Raises:
566 ResponseFormatError: If the response is not in the expected format.
567 UnauthorisedError: If the request is unauthorised.
568 ForbiddenError: If the request is forbidden.
569 PreconditionFailedError: If one or more nodes in the group are not reachable and force is not set to `True`.
570 """
571 params: dict[str, str] | None = None
572 if force is not None:
573 params = {"force": str(force).lower()}
574 try:
575 headers = {"Accept": "application/json"}
576 if params is None:
577 response = self.http_client.delete(
578 "/rest/cluster/config", headers=headers
579 )
580 else:
581 response = self.http_client.delete(
582 "/rest/cluster/config", headers=headers, params=params
583 )
584 response.raise_for_status()
585 try:
586 payload = response.json()
587 except (ValueError, TypeError) as err:
588 raise ResponseFormatError(
589 f"Failed to parse cluster deletion response: {err}"
590 ) from err
591 if not isinstance(payload, dict):
592 raise ResponseFormatError(
593 "Failed to parse cluster deletion response: expected a JSON object."
594 )
595 if not all(
596 isinstance(key, str) and isinstance(value, str)
597 for key, value in payload.items()
598 ):
599 raise ResponseFormatError(
600 "Failed to parse cluster deletion response: expected string keys and values."
601 )
602 return t.cast(dict[str, str], payload)
603 except httpx.HTTPStatusError as err:
604 status = err.response.status_code
605 if status == 401:
606 raise UnauthorisedError(
607 f"Request is unauthorised: {err.response.text}"
608 ) from err
609 elif status == 403:
610 raise ForbiddenError(
611 f"Request is forbidden: {err.response.text}"
612 ) from err
613 elif status == 412:
614 raise PreconditionFailedError(
615 f"Precondition failed: {err.response.text}"
616 ) from err
617 raise
618
619 def update_config(
620 self,
621 election_min_timeout: int | None = None,
622 election_range_timeout: int | None = None,
623 heartbeat_interval: int | None = None,
624 message_size_kb: int | None = None,
625 verification_timeout: int | None = None,
626 transaction_log_maximum_size_gb: int | None = None,
627 batch_update_interval: int | None = None,
628 ) -> ClusterRequest:
629 """Update the GraphDB cluster configuration.
630
631 If one of the cluster nodes is down or was not able to accept the new configuration,
632 the operation will not be successful. A total consensus between the nodes is required.
633 In case one or more of them cannot append the new configuration, it will be rejected
634 by all of the nodes.
635
636 Parameters:
637 election_min_timeout: The minimum wait time in milliseconds for a heartbeat from a leader.
638 election_range_timeout: The variable portion of each waiting period in milliseconds for a heartbeat.
639 heartbeat_interval: The interval in milliseconds between each heartbeat that is sent to follower nodes by the leader.
640 message_size_kb: The size of the data blocks, in kilobytes, transferred during data replication streaming through the RPC protocol.
641 verification_timeout: The amount of time in milliseconds that a follower node would wait before attempting to verify the last committed
642 entry when the first verification is unsuccessful.
643 transaction_log_maximum_size_gb: Maximum size of the transaction log in GBs. The transaction log will be automatically truncated if it
644 becomes bigger than this value. The minimum transaction log size is 1 GB. Setting it to a negative value will disable automatic transaction
645 log truncation.
646 batch_update_interval: The interval in milliseconds between requesting updates from the primary cluster. Used only when the cluster is in
647 secondary mode.
648
649 Returns:
650 The updated cluster configuration.
651
652 Raises:
653 BadRequestError: If the request is invalid.
654 UnauthorisedError: If the request is unauthorised.
655 ForbiddenError: If the request is forbidden.
656 PreconditionFailedError: If one or more nodes in the group are not reachable.
657 """
658 _int_fields: list[tuple[str, int | None]] = [
659 ("election_min_timeout", election_min_timeout),
660 ("election_range_timeout", election_range_timeout),
661 ("heartbeat_interval", heartbeat_interval),
662 ("message_size_kb", message_size_kb),
663 ("verification_timeout", verification_timeout),
664 ("transaction_log_maximum_size_gb", transaction_log_maximum_size_gb),
665 ("batch_update_interval", batch_update_interval),
666 ]
667 for field_name, value in _int_fields:
668 if value is not None and type(value) is not int:
669 raise TypeError(f"{field_name} must be an int if provided.")
670
671 payload: dict[str, t.Any] = {}
672 if election_min_timeout is not None:
673 payload["electionMinTimeout"] = election_min_timeout
674 if election_range_timeout is not None:
675 payload["electionRangeTimeout"] = election_range_timeout
676 if heartbeat_interval is not None:
677 payload["heartbeatInterval"] = heartbeat_interval
678 if message_size_kb is not None:
679 payload["messageSizeKB"] = message_size_kb
680 if verification_timeout is not None:
681 payload["verificationTimeout"] = verification_timeout
682 if transaction_log_maximum_size_gb is not None:
683 payload["transactionLogMaximumSizeGB"] = transaction_log_maximum_size_gb
684 if batch_update_interval is not None:
685 payload["batchUpdateInterval"] = batch_update_interval
686
687 headers = {"Accept": "application/json"}
688 try:
689 response = self.http_client.patch(
690 "/rest/cluster/config", headers=headers, json=payload
691 )
692 response.raise_for_status()
693 try:
694 return ClusterRequest.from_dict(response.json())
695 except (KeyError, TypeError, ValueError) as err:
696 raise ResponseFormatError(
697 f"Failed to parse updated cluster configuration: {err}"
698 ) from err
699 except httpx.HTTPStatusError as err:
700 status = err.response.status_code
701 if status == 400:
702 raise BadRequestError(f"Invalid request: {err.response.text}") from err
703 elif status == 401:
704 raise UnauthorisedError(
705 f"Request is unauthorised: {err.response.text}"
706 ) from err
707 elif status == 403:
708 raise ForbiddenError(
709 f"Request is forbidden: {err.response.text}"
710 ) from err
711 elif status == 412:
712 raise PreconditionFailedError(
713 f"Precondition failed: {err.response.text}"
714 ) from err
715 raise
716
717 def add_tag(self, tag: str) -> None:
718 """Add primary cluster tag.
719
720 Parameters:
721 tag: The identifier tag to add to the primary cluster.
722
723 Raises:
724 TypeError: If tag is not a string.
725 ValueError: If tag is an empty string.
726 BadRequestError: If the request is invalid.
727 UnauthorisedError: If the request is unauthorised.
728 ForbiddenError: If the request is forbidden.
729 PreconditionFailedError: If the cluster is not in a state to add a tag.
730 """
731 if not isinstance(tag, str):
732 raise TypeError("tag must be a string")
733 if not tag:
734 raise ValueError("tag must be a non-empty string")
735
736 try:
737 response = self.http_client.post(
738 "/rest/cluster/config/tag", json={"tag": tag}
739 )
740 response.raise_for_status()
741 except httpx.HTTPStatusError as err:
742 status = err.response.status_code
743 if status == 400:
744 raise BadRequestError(f"Invalid request: {err.response.text}") from err
745 elif status == 401:
746 raise UnauthorisedError(
747 f"Request is unauthorised: {err.response.text}"
748 ) from err
749 elif status == 403:
750 raise ForbiddenError(
751 f"Request is forbidden: {err.response.text}"
752 ) from err
753 elif status == 412:
754 raise PreconditionFailedError(
755 f"Precondition failed: {err.response.text}"
756 ) from err
757 raise
758
759 def delete_tag(self, tag: str) -> None:
760 """Remove primary cluster tag.
761
762 Parameters:
763 tag: The identifier tag to remove from the primary cluster.
764
765 Raises:
766 TypeError: If tag is not a string.
767 ValueError: If tag is an empty string.
768 BadRequestError: If the request is invalid.
769 UnauthorisedError: If the request is unauthorised.
770 ForbiddenError: If the request is forbidden.
771 PreconditionFailedError: If the cluster is not in a state to delete a tag.
772 """
773 if not isinstance(tag, str):
774 raise TypeError("tag must be a string")
775 if not tag:
776 raise ValueError("tag must be a non-empty string")
777
778 headers = {"Content-Type": "application/json"}
779 try:
780 response = self.http_client.request(
781 method="DELETE",
782 url="/rest/cluster/config/tag",
783 headers=headers,
784 json={"tag": tag},
785 )
786 response.raise_for_status()
787 except httpx.HTTPStatusError as err:
788 status = err.response.status_code
789 if status == 400:
790 raise BadRequestError(f"Invalid request: {err.response.text}") from err
791 elif status == 401:
792 raise UnauthorisedError(
793 f"Request is unauthorised: {err.response.text}"
794 ) from err
795 elif status == 403:
796 raise ForbiddenError(
797 f"Request is forbidden: {err.response.text}"
798 ) from err
799 elif status == 412:
800 raise PreconditionFailedError(
801 f"Precondition failed: {err.response.text}"
802 ) from err
803 raise
804
805 def enable_secondary_mode(self, primary_node: str, tag: str) -> None:
806 """Enable cluster secondary mode.
807
808 You can switch any healthy primary cluster to secondary mode by providing the RPC address
809 of the primary cluster node that it will replicate and then declaring the tag used to identify
810 it. Once you have switched a cluster to secondary mode, all of its current repositories and
811 data will be removed and replaced with the data and state of the primary cluster.
812
813 !!! Note
814 You can enable the secondary cluster mode from any of the nodes of a cluster, not just the
815 leader node. You can also use any of the healthy nodes of the primary cluster to connect to
816 that cluster.
817
818 !!! Warning
819 Enabling the secondary mode will delete all data on the secondary cluster and replicate
820 the state of the primary cluster.
821
822 Parameters:
823 primary_node: The RPC address of one of the healthy nodes of the primary cluster.
824 tag: The identifier tag of the primary cluster.
825
826 Raises:
827 TypeError: If primary_node or tag is not a string.
828 ValueError: If primary_node or tag is an empty string.
829 BadRequestError: If the request is invalid.
830 UnauthorisedError: If the request is unauthorised.
831 ForbiddenError: If the request is forbidden.
832 PreconditionFailedError: If the cluster is not in a state to enable secondary mode.
833 """
834 if not isinstance(primary_node, str):
835 raise TypeError("primary_node must be a string")
836 if not primary_node:
837 raise ValueError("primary_node must be a non-empty string")
838 if not isinstance(tag, str):
839 raise TypeError("tag must be a string")
840 if not tag:
841 raise ValueError("tag must be a non-empty string")
842
843 payload = {"primaryNode": primary_node, "tag": tag}
844 try:
845 response = self.http_client.post(
846 "/rest/cluster/config/secondary-mode", json=payload
847 )
848 response.raise_for_status()
849 except httpx.HTTPStatusError as err:
850 status = err.response.status_code
851 if status == 400:
852 raise BadRequestError(f"Invalid request: {err.response.text}") from err
853 elif status == 401:
854 raise UnauthorisedError(
855 f"Request is unauthorised: {err.response.text}"
856 ) from err
857 elif status == 403:
858 raise ForbiddenError(
859 f"Request is forbidden: {err.response.text}"
860 ) from err
861 elif status == 412:
862 raise PreconditionFailedError(
863 f"Precondition failed: {err.response.text}"
864 ) from err
865 raise
866
867 def disable_secondary_mode(self) -> None:
868 """Disable cluster secondary mode.
869
870 Once in secondary mode, you can disable secondary mode and then you will no longer be in
871 that mode. Doing this will stop the pulling of updates from the primary cluster.
872
873 Raises:
874 BadRequestError: If the request is invalid.
875 UnauthorisedError: If the request is unauthorised.
876 ForbiddenError: If the request is forbidden.
877 PreconditionFailedError: If the cluster is not in a state to disable secondary mode.
878 """
879 try:
880 response = self.http_client.delete("/rest/cluster/config/secondary-mode")
881 response.raise_for_status()
882 except httpx.HTTPStatusError as err:
883 status = err.response.status_code
884 if status == 400:
885 raise BadRequestError(f"Invalid request: {err.response.text}") from err
886 elif status == 401:
887 raise UnauthorisedError(
888 f"Request is unauthorised: {err.response.text}"
889 ) from err
890 elif status == 403:
891 raise ForbiddenError(
892 f"Request is forbidden: {err.response.text}"
893 ) from err
894 elif status == 412:
895 raise PreconditionFailedError(
896 f"Precondition failed: {err.response.text}"
897 ) from err
898 raise
899
900 def add_nodes(self, nodes: list[str]) -> None:
901 """Add nodes to the GraphDB cluster.
902
903 Parameters:
904 nodes: List of node addresses to add to the cluster.
905
906 Raises:
907 TypeError: If nodes is not a list of strings.
908 BadRequestError: If the request is invalid.
909 UnauthorisedError: If the request is unauthorised.
910 ForbiddenError: If the request is forbidden.
911 PreconditionFailedError: If one or more nodes in the group are not reachable.
912 """
913 if not isinstance(nodes, list) or any(
914 not isinstance(node, str) for node in nodes
915 ):
916 raise TypeError("nodes must be a list[str].")
917
918 payload = {"nodes": nodes}
919 headers = {"Content-Type": "application/json"}
920 try:
921 response = self.http_client.post(
922 "/rest/cluster/config/node", headers=headers, json=payload
923 )
924 response.raise_for_status()
925 except httpx.HTTPStatusError as err:
926 status = err.response.status_code
927 if status == 400:
928 raise BadRequestError(f"Invalid request: {err.response.text}") from err
929 elif status == 401:
930 raise UnauthorisedError(
931 f"Request is unauthorised: {err.response.text}"
932 ) from err
933 elif status == 403:
934 raise ForbiddenError(
935 f"Request is forbidden: {err.response.text}"
936 ) from err
937 elif status == 412:
938 raise PreconditionFailedError(
939 f"Precondition failed: {err.response.text}"
940 ) from err
941 raise
942
943 def remove_nodes(self, nodes: list[str]) -> None:
944 """Remove nodes from the GraphDB cluster.
945
946 Parameters:
947 nodes: List of node addresses to remove from the cluster.
948
949 Raises:
950 TypeError: If nodes is not a list of strings.
951 BadRequestError: If the request is invalid.
952 UnauthorisedError: If the request is unauthorised.
953 ForbiddenError: If the request is forbidden.
954 PreconditionFailedError: If one or more nodes in the group are not reachable.
955 """
956 if not isinstance(nodes, list) or any(
957 not isinstance(node, str) for node in nodes
958 ):
959 raise TypeError("nodes must be a list[str].")
960
961 payload = {"nodes": nodes}
962 try:
963 response = self.http_client.request(
964 method="DELETE",
965 url="/rest/cluster/config/node",
966 json=payload,
967 )
968 response.raise_for_status()
969 except httpx.HTTPStatusError as err:
970 status = err.response.status_code
971 if status == 400:
972 raise BadRequestError(f"Invalid request: {err.response.text}") from err
973 elif status == 401:
974 raise UnauthorisedError(
975 f"Request is unauthorised: {err.response.text}"
976 ) from err
977 elif status == 403:
978 raise ForbiddenError(
979 f"Request is forbidden: {err.response.text}"
980 ) from err
981 elif status == 412:
982 raise PreconditionFailedError(
983 f"Precondition failed: {err.response.text}"
984 ) from err
985 raise
986
987 def replace_nodes(self, add_nodes: list[str], remove_nodes: list[str]) -> None:
988 """Replace nodes in the GraphDB cluster.
989
990 Parameters:
991 add_nodes: List of node addresses to add to the cluster.
992 remove_nodes: List of node addresses to remove from the cluster.
993
994 Raises:
995 TypeError: If add_nodes or remove_nodes is not a list of strings.
996 BadRequestError: If the request is invalid.
997 UnauthorisedError: If the request is unauthorised.
998 ForbiddenError: If the request is forbidden.
999 PreconditionFailedError: If one or more nodes in the group are not reachable.
1000 """
1001 if not isinstance(add_nodes, list) or any(
1002 not isinstance(node, str) for node in add_nodes
1003 ):
1004 raise TypeError("add_nodes must be a list[str].")
1005 if not isinstance(remove_nodes, list) or any(
1006 not isinstance(node, str) for node in remove_nodes
1007 ):
1008 raise TypeError("remove_nodes must be a list[str].")
1009
1010 payload = {"removeNodes": remove_nodes, "addNodes": add_nodes}
1011 try:
1012 response = self.http_client.patch("/rest/cluster/config/node", json=payload)
1013 response.raise_for_status()
1014 except httpx.HTTPStatusError as err:
1015 status = err.response.status_code
1016 if status == 400:
1017 raise BadRequestError(f"Invalid request: {err.response.text}") from err
1018 elif status == 401:
1019 raise UnauthorisedError(
1020 f"Request is unauthorised: {err.response.text}"
1021 ) from err
1022 elif status == 403:
1023 raise ForbiddenError(
1024 f"Request is forbidden: {err.response.text}"
1025 ) from err
1026 elif status == 412:
1027 raise PreconditionFailedError(
1028 f"Precondition failed: {err.response.text}"
1029 ) from err
1030 raise
1031
1032 def node_status(self) -> NodeStatus:
1033 """Get the status of this GraphDB cluster node.
1034
1035 Returns:
1036 NodeStatus: The status of this GraphDB cluster node.
1037
1038 Raises:
1039 ResponseFormatError: If the response cannot be parsed.
1040 BadRequestError: If the request is invalid.
1041 NotFoundError: If the node status is not found.
1042 InternalServerError: If the internal server error.
1043 """
1044 try:
1045 headers = {"Accept": "application/json"}
1046 response = self.http_client.get(
1047 "/rest/cluster/node/status", headers=headers
1048 )
1049 response.raise_for_status()
1050 try:
1051 return NodeStatus.from_dict(response.json())
1052 except (KeyError, TypeError, ValueError) as err:
1053 raise ResponseFormatError(
1054 f"Failed to parse node status: {err}"
1055 ) from err
1056 except httpx.HTTPStatusError as err:
1057 status = err.response.status_code
1058 if status == 400:
1059 raise BadRequestError(f"Invalid request: {err.response.text}") from err
1060 elif status == 404:
1061 raise NotFoundError(
1062 f"Node status not found: {err.response.text}"
1063 ) from err
1064 elif status == 500:
1065 raise InternalServerError(
1066 f"Internal server error: {err.response.text}"
1067 ) from err
1068 raise
1069
1070 def group_status(self) -> list[NodeStatus]:
1071 """Get the status of the GraphDB cluster.
1072
1073 Returns:
1074 A list of node statuses for the cluster group.
1075
1076 Raises:
1077 ResponseFormatError: If the response cannot be parsed.
1078 BadRequestError: If the request is invalid.
1079 NotFoundError: If the group status is not found.
1080 InternalServerError: If the internal server error.
1081 """
1082 try:
1083 headers = {"Accept": "application/json"}
1084 response = self.http_client.get(
1085 "/rest/cluster/group/status", headers=headers
1086 )
1087 response.raise_for_status()
1088 try:
1089 data = response.json()
1090 return [NodeStatus.from_dict(item) for item in data]
1091 except (KeyError, TypeError, ValueError) as err:
1092 raise ResponseFormatError(
1093 f"Failed to parse group status: {err}"
1094 ) from err
1095 except httpx.HTTPStatusError as err:
1096 status = err.response.status_code
1097 if status == 400:
1098 raise BadRequestError(f"Invalid request: {err.response.text}") from err
1099 elif status == 404:
1100 raise NotFoundError(
1101 f"Group status not found: {err.response.text}"
1102 ) from err
1103 elif status == 500:
1104 raise InternalServerError(
1105 f"Internal server error: {err.response.text}"
1106 ) from err
1107 raise
1108
1109
1110class Repository(rdflib.contrib.rdf4j.client.Repository):
1111 """GraphDB Repository client.
1112
1113 Overrides specific methods of the RDF4J Repository class and also provides GraphDB-only functionality
1114 (such as FGAC ACL management) made available through the GraphDB REST API.
1115
1116 Parameters:
1117 identifier: The identifier of the repository.
1118 http_client: The httpx.Client instance.
1119 """
1120
1121 def __init__(self, identifier: str, http_client: httpx.Client):
1122 super().__init__(identifier, http_client)
1123 self._access_control_list_management = AccessControlListManagement(
1124 self.identifier, self.http_client
1125 )
1126
1127 @property
1128 def acl(self) -> AccessControlListManagement:
1129 return self._access_control_list_management
1130
1131 def health(self, timeout: int = 5) -> bool:
1132 """Repository health check.
1133
1134 Parameters:
1135 timeout: A timeout parameter in seconds. If provided, the endpoint attempts
1136 to retrieve the repository within this timeout. If not, the passive
1137 check is performed.
1138
1139 Returns:
1140 bool: True if the repository is healthy, otherwise an error is raised.
1141
1142 Raises:
1143 RepositoryNotFoundError: If the repository is not found.
1144 RepositoryNotHealthyError: If the repository is not healthy.
1145 """
1146 try:
1147 params = {"passive": str(timeout)}
1148 response = self.http_client.get(
1149 f"/repositories/{self.identifier}/health", params=params
1150 )
1151 response.raise_for_status()
1152 return True
1153 except httpx.HTTPStatusError as err:
1154 if err.response.status_code == 404:
1155 raise RepositoryNotFoundError(
1156 f"Repository {self._identifier} not found."
1157 )
1158 raise RepositoryNotHealthyError(
1159 f"Repository {self._identifier} is not healthy. {err.response.status_code} - {err.response.text}"
1160 )
1161
1162 def get_server_import_files(self) -> list[ImportSettings]:
1163 """Get server files available for import.
1164
1165 Returns:
1166 A list of files available for import.
1167
1168 Raises:
1169 ResponseFormatError: If the response format is invalid.
1170 UnauthorisedError: If the request is unauthorised.
1171 ForbiddenError: If the request is forbidden.
1172 InternalServerError: If the server returns an internal error.
1173 """
1174 try:
1175 headers = {"Accept": "application/json"}
1176 response = self.http_client.get(
1177 f"/rest/repositories/{self.identifier}/import/server",
1178 headers=headers,
1179 )
1180 response.raise_for_status()
1181 try:
1182 result = []
1183 for item in response.json():
1184 # Convert nested parserSettings dict to ParserSettings instance
1185 if "parserSettings" in item and isinstance(
1186 item["parserSettings"], dict
1187 ):
1188 item["parserSettings"] = ParserSettings(
1189 **item["parserSettings"]
1190 )
1191 result.append(ImportSettings(**item))
1192 return result
1193 except (ValueError, TypeError) as err:
1194 raise ResponseFormatError(f"Failed to parse response: {err}") from err
1195 except httpx.HTTPStatusError as err:
1196 if err.response.status_code == 401:
1197 raise UnauthorisedError(
1198 f"Request is unauthorised: {err.response.text}"
1199 ) from err
1200 elif err.response.status_code == 403:
1201 raise ForbiddenError(
1202 f"Request is forbidden: {err.response.text}"
1203 ) from err
1204 elif err.response.status_code == 500:
1205 raise InternalServerError(
1206 f"Internal server error: {err.response.text}"
1207 ) from err
1208 raise
1209
1210 def import_server_import_file(self, server_import_body: ServerImportBody) -> None:
1211 """Import a server file into the repository.
1212
1213 Parameters:
1214 server_import_body: The server import body.
1215
1216 Raises:
1217 BadRequestError: If the request is bad.
1218 UnauthorisedError: If the request is unauthorised.
1219 ForbiddenError: If the request is forbidden.
1220 NotFoundError: If the request is not found.
1221 """
1222 try:
1223 headers = {"Content-Type": "application/json"}
1224 response = self.http_client.post(
1225 f"/rest/repositories/{self.identifier}/import/server",
1226 headers=headers,
1227 json=server_import_body.as_dict(),
1228 )
1229 response.raise_for_status()
1230 except httpx.HTTPStatusError as err:
1231 status = err.response.status_code
1232 if status == 400:
1233 raise BadRequestError(f"Bad request: {err.response.text}") from err
1234 elif status == 401:
1235 raise UnauthorisedError(
1236 f"Request is unauthorised: {err.response.text}"
1237 ) from err
1238 elif status == 403:
1239 raise ForbiddenError(
1240 f"Request is forbidden: {err.response.text}"
1241 ) from err
1242 elif status == 404:
1243 raise NotFoundError(
1244 f"Request is not found: {err.response.text}"
1245 ) from err
1246 raise
1247
1248 def cancel_server_import_file(self, name: str) -> None:
1249 """Cancel server file import operation.
1250
1251 Parameters:
1252 name: The name of the file import to interrupt.
1253
1254 Raises:
1255 BadRequestError: If the request is bad.
1256 UnauthorisedError: If the request is unauthorised.
1257 ForbiddenError: If the request is forbidden.
1258 """
1259 try:
1260 params = {"name": name}
1261 response = self.http_client.delete(
1262 f"/rest/repositories/{self.identifier}/import/server",
1263 params=params,
1264 )
1265 response.raise_for_status()
1266 except httpx.HTTPStatusError as err:
1267 status = err.response.status_code
1268 if status == 400:
1269 raise BadRequestError(f"Bad request: {err.response.text}") from err
1270 elif status == 401:
1271 raise UnauthorisedError(
1272 f"Request is unauthorised: {err.response.text}"
1273 ) from err
1274 elif status == 403:
1275 raise ForbiddenError(
1276 f"Request is forbidden: {err.response.text}"
1277 ) from err
1278 raise
1279
1280
1281class RepositoryManager(rdflib.contrib.rdf4j.client.RepositoryManager):
1282 """GraphDB Repository Manager.
1283
1284 This manager client overrides specific RDF4J RepositoryManager class methods to provide GraphDB-specific implementations.
1285 """
1286
1287 def get(self, repository_id: str) -> Repository:
1288 """Get a repository by ID.
1289
1290 !!! Note
1291 This performs a health check before returning the repository object.
1292
1293 Parameters:
1294 repository_id: The identifier of the repository.
1295
1296 Returns:
1297 Repository: The repository instance.
1298
1299 Raises:
1300 RepositoryNotFoundError: If the repository is not found.
1301 RepositoryNotHealthyError: If the repository is not healthy.
1302 """
1303 _repo = super().get(repository_id)
1304 return Repository(_repo.identifier, _repo.http_client)
1305
1306
1307class MonitoringManagement:
1308 """
1309 Monitor different GraphDB processes.
1310 """
1311
1312 def __init__(self, http_client: httpx.Client):
1313 self._http_client = http_client
1314
1315 @property
1316 def http_client(self):
1317 return self._http_client
1318
1319 @property
1320 def structures(self) -> StructuresStatistics:
1321 """Get structures statistics.
1322
1323 Returns:
1324 The structures statistics.
1325
1326 Raises:
1327 ResponseFormatError: If the response format is invalid.
1328 UnauthorisedError: If the request is unauthorised.
1329 ForbiddenError: If the request is forbidden.
1330 InternalServerError: If the server returns an internal error.
1331 ServiceUnavailableError: If the server is unavailable.
1332 """
1333 try:
1334 headers = {"Accept": "application/json"}
1335 response = self.http_client.get("/rest/monitor/structures", headers=headers)
1336 response.raise_for_status()
1337 try:
1338 return StructuresStatistics(**response.json())
1339 except (ValueError, TypeError) as err:
1340 raise ResponseFormatError(f"Failed to parse response: {err}") from err
1341 except httpx.HTTPStatusError as err:
1342 status = err.response.status_code
1343 if status == 401:
1344 raise UnauthorisedError(
1345 f"Request is unauthorised: {err.response.text}"
1346 ) from err
1347 elif status == 403:
1348 raise ForbiddenError(
1349 f"Request is forbidden: {err.response.text}"
1350 ) from err
1351 elif status == 500:
1352 raise InternalServerError(
1353 f"Internal server error: {err.response.text}"
1354 ) from err
1355 elif status == 503:
1356 raise ServiceUnavailableError(
1357 f"Service is unavailable: {err.response.text}"
1358 ) from err
1359 raise
1360
1361 def get_repo_stats(self, repository_id: str):
1362 """Get repository statistics.
1363
1364 Parameters:
1365 repository_id: The identifier of the repository.
1366
1367 Returns:
1368 RepositoryStatistics: The repository statistics.
1369
1370 Raises:
1371 ResponseFormatError: If the response cannot be parsed.
1372 UnauthorisedError: If the request is unauthorised.
1373 ForbiddenError: If the request is forbidden.
1374 InternalServerError: If the server returns an internal error.
1375 """
1376 try:
1377 headers = {"Accept": "application/json"}
1378 response = self.http_client.get(
1379 f"/rest/monitor/repository/{repository_id}", headers=headers
1380 )
1381 response.raise_for_status()
1382 try:
1383 return RepositoryStatistics.from_dict(response.json())
1384 except (ValueError, TypeError, KeyError) as err:
1385 raise ResponseFormatError(f"Failed to parse response: {err}") from err
1386 except httpx.HTTPStatusError as err:
1387 status = err.response.status_code
1388 if status == 401:
1389 raise UnauthorisedError(
1390 f"Request is unauthorised: {err.response.text}"
1391 ) from err
1392 elif status == 403:
1393 raise ForbiddenError(
1394 f"Request is forbidden: {err.response.text}"
1395 ) from err
1396 elif status == 500:
1397 raise InternalServerError(
1398 f"Internal server error: {err.response.text}"
1399 ) from err
1400 raise
1401
1402 @property
1403 def infrastructure(self) -> InfrastructureStatistics:
1404 """Get all infrastructure statistics.
1405
1406 Returns:
1407 InfrastructureStatistics: The infrastructure statistics.
1408
1409 Raises:
1410 ResponseFormatError: If the response cannot be parsed.
1411 UnauthorisedError: If the request is unauthorised.
1412 ForbiddenError: If the request is forbidden.
1413 InternalServerError: If the server returns an internal error.
1414 """
1415 try:
1416 headers = {"Accept": "application/json"}
1417 response = self.http_client.get(
1418 "/rest/monitor/infrastructure", headers=headers
1419 )
1420 response.raise_for_status()
1421 try:
1422 return InfrastructureStatistics.from_dict(response.json())
1423 except (ValueError, TypeError, KeyError) as err:
1424 raise ResponseFormatError(f"Failed to parse response: {err}") from err
1425 except httpx.HTTPStatusError as err:
1426 status = err.response.status_code
1427 if status == 401:
1428 raise UnauthorisedError(
1429 f"Request is unauthorised: {err.response.text}"
1430 ) from err
1431 elif status == 403:
1432 raise ForbiddenError(
1433 f"Request is forbidden: {err.response.text}"
1434 ) from err
1435 elif status == 500:
1436 raise InternalServerError(
1437 f"Internal server error: {err.response.text}"
1438 ) from err
1439 raise
1440
1441 def cluster(self) -> str:
1442 """Get cluster statistics.
1443
1444 !!! Note
1445 This endpoint is only available in GraphDB EE.
1446
1447 Returns:
1448 Prometheus-style metrics.
1449
1450 Raises:
1451 UnauthorisedError: If the request is unauthorised.
1452 ForbiddenError: If the request is forbidden.
1453 InternalServerError: If the server returns an internal error.
1454 ServiceUnavailableError: If the server is unavailable.
1455 """
1456 try:
1457 headers = {"Accept": "text/plain"}
1458 response = self.http_client.get("/rest/monitor/cluster", headers=headers)
1459 response.raise_for_status()
1460 return response.text
1461 except httpx.HTTPStatusError as err:
1462 status = err.response.status_code
1463 if status == 401:
1464 raise UnauthorisedError(
1465 f"Request is unauthorised: {err.response.text}"
1466 ) from err
1467 elif status == 403:
1468 raise ForbiddenError(
1469 f"Request is forbidden: {err.response.text}"
1470 ) from err
1471 elif status == 500:
1472 raise InternalServerError(
1473 f"Internal server error: {err.response.text}"
1474 ) from err
1475 elif status == 503:
1476 raise ServiceUnavailableError(
1477 f"Service is unavailable: {err.response.text}"
1478 ) from err
1479 raise
1480
1481 def backup(self) -> BackupOperationBean | None:
1482 """Track backup operations.
1483
1484 Returns:
1485 On-going backup operations or `None` if no backup is in progress.
1486
1487 Raises:
1488 ResponseFormatError: If the response cannot be parsed.
1489 UnauthorisedError: If the request is unauthorised.
1490 ForbiddenError: If the request is forbidden.
1491 InternalServerError: If the server returns an internal error.
1492 ServiceUnavailableError: If the server is unavailable.
1493 """
1494 try:
1495 headers = {"Accept": "application/json"}
1496 response = self.http_client.get("/rest/monitor/backup", headers=headers)
1497 response.raise_for_status()
1498 try:
1499 data = response.json()
1500 if not data:
1501 return None
1502 return BackupOperationBean.from_dict(data)
1503 except (ValueError, TypeError, KeyError) as err:
1504 raise ResponseFormatError(f"Failed to parse response: {err}") from err
1505 except httpx.HTTPStatusError as err:
1506 status = err.response.status_code
1507 if status == 401:
1508 raise UnauthorisedError(
1509 f"Request is unauthorised: {err.response.text}"
1510 ) from err
1511 elif status == 403:
1512 raise ForbiddenError(
1513 f"Request is forbidden: {err.response.text}"
1514 ) from err
1515 elif status == 500:
1516 raise InternalServerError(
1517 f"Internal server error: {err.response.text}"
1518 ) from err
1519 elif status == 503:
1520 raise ServiceUnavailableError(
1521 f"Service is unavailable: {err.response.text}"
1522 ) from err
1523 raise
1524
1525
1526class RecoveryManagement:
1527 """
1528 GraphDB Recovery Management client.
1529 """
1530
1531 def __init__(self, http_client: httpx.Client):
1532 self._http_client = http_client
1533
1534 @property
1535 def http_client(self):
1536 return self._http_client
1537
1538 def restore(
1539 self,
1540 backup: bytes | bytearray | memoryview | t.IO[bytes] | str | os.PathLike[str],
1541 repositories: list[str] | None = None,
1542 restore_system_data: bool | None = None,
1543 remove_stale_repositories: bool | None = None,
1544 ) -> None:
1545 """Restore GraphDB instance from a backup archive.
1546
1547 Parameters:
1548 backup: Backup archive content as bytes/bytes-like, a binary file-like
1549 object, or a filesystem path to a `.tar` produced by
1550 [`backup`][rdflib.contrib.graphdb.client.RecoveryManagement.backup].
1551 repositories: List of repositories to restore. If `None` (default), the
1552 parameter is omitted and all repositories found in the backup are
1553 restored. If an empty list (`[]`) is provided, no repositories from
1554 the backup are restored.
1555 restore_system_data: Whether to restore system data (users, saved queries,
1556 visual graphs, etc.). If omitted, GraphDB defaults to `false`. If
1557 `true` and no system data exists in the backup, GraphDB returns an
1558 error.
1559 remove_stale_repositories: Whether to remove repositories on the target
1560 instance that are not restored from the backup. If omitted, GraphDB
1561 defaults to `false`.
1562
1563 Raises:
1564 ValueError: If parameters are invalid, or if backup is not a supported type.
1565 BadRequestError: If the request is bad.
1566 UnauthorisedError: If the request is unauthorised.
1567 ForbiddenError: If the request is forbidden.
1568 """
1569 if repositories is not None:
1570 if not isinstance(repositories, list):
1571 raise ValueError("repositories must be a list or None")
1572 if not all(isinstance(r, str) for r in repositories):
1573 raise ValueError("repositories must be a list of strings")
1574 if (
1575 not isinstance(restore_system_data, bool)
1576 and restore_system_data is not None
1577 ):
1578 raise ValueError("restore_system_data must be a bool or None")
1579 if (
1580 not isinstance(remove_stale_repositories, bool)
1581 and remove_stale_repositories is not None
1582 ):
1583 raise ValueError("remove_stale_repositories must be a bool or None")
1584
1585 payload: dict[str, t.Any] = {}
1586 if repositories is not None:
1587 payload["repositories"] = repositories
1588 if restore_system_data is not None:
1589 payload["restoreSystemData"] = restore_system_data
1590 if remove_stale_repositories is not None:
1591 payload["removeStaleRepositories"] = remove_stale_repositories
1592
1593 params_part: FileContent = (None, json.dumps(payload), "application/json")
1594
1595 def _post(file_part: FileContent) -> None:
1596 try:
1597 response = self.http_client.post(
1598 "/rest/recovery/restore",
1599 files=[("params", params_part), ("file", file_part)],
1600 )
1601 response.raise_for_status()
1602 except httpx.HTTPStatusError as err:
1603 status = err.response.status_code
1604 if status == 400:
1605 raise BadRequestError(f"Bad request: {err.response.text}") from err
1606 elif status == 401:
1607 raise UnauthorisedError(
1608 f"Request is unauthorised: {err.response.text}"
1609 ) from err
1610 elif status == 403:
1611 raise ForbiddenError(
1612 f"Request is forbidden: {err.response.text}"
1613 ) from err
1614 raise err
1615
1616 if isinstance(backup, (bytes, bytearray, memoryview)):
1617 content = bytes(backup)
1618 _post(("graphdb-backup.tar", content, "application/x-tar"))
1619 return
1620
1621 if hasattr(backup, "read") and not isinstance(backup, (str, os.PathLike)):
1622 file_obj = t.cast(t.IO[bytes], backup)
1623 filename = infer_filename_from_fileobj(file_obj, "graphdb-backup.tar")
1624 _post((filename, file_obj, "application/x-tar"))
1625 return
1626
1627 if isinstance(backup, (str, os.PathLike)):
1628 backup_path = pathlib.Path(backup).expanduser()
1629 with open(backup_path, "rb") as f:
1630 filename = backup_path.name or infer_filename_from_fileobj(
1631 f, "graphdb-backup.tar"
1632 )
1633 _post((filename, f, "application/x-tar"))
1634 return
1635
1636 raise ValueError(
1637 "backup must be bytes/bytes-like, a binary file-like object, or a filesystem path"
1638 )
1639
1640 def cloud_restore(
1641 self,
1642 bucket_uri: str,
1643 repositories: list[str] | None = None,
1644 restore_system_data: bool | None = None,
1645 remove_stale_repositories: bool | None = None,
1646 authentication_file: (
1647 bytes | bytearray | memoryview | t.IO[bytes] | str | os.PathLike[str] | None
1648 ) = None,
1649 ) -> None:
1650 """Restore GraphDB instance from a cloud backup archive.
1651
1652 Parameters:
1653 bucket_uri: Cloud bucket URI including provider-specific parameters (required).
1654 repositories: List of repositories to restore. If `None` (default), the
1655 parameter is omitted and all repositories found in the backup are
1656 restored. If an empty list (`[]`) is provided, no repositories from
1657 the backup are restored.
1658 restore_system_data: Whether to restore system data (users, saved queries,
1659 visual graphs, etc.). If omitted, GraphDB defaults to `false`. If
1660 `true` and no system data exists in the backup, GraphDB returns an
1661 error.
1662 remove_stale_repositories: Whether to remove repositories on the target
1663 instance that are not restored from the backup. If omitted, GraphDB
1664 defaults to `false`.
1665 authentication_file: Optional credential file content as bytes/bytes-like, a
1666 binary file-like object, or a filesystem path.
1667
1668 Raises:
1669 ValueError: If parameters are invalid, or authentication_file is not a supported type.
1670 BadRequestError: If the request is bad.
1671 UnauthorisedError: If the request is unauthorised.
1672 ForbiddenError: If the request is forbidden.
1673 """
1674 if not isinstance(bucket_uri, str) or not bucket_uri:
1675 raise ValueError("bucket_uri must be a non-empty string")
1676
1677 if repositories is not None:
1678 if not isinstance(repositories, list):
1679 raise ValueError("repositories must be a list or None")
1680 if not all(isinstance(r, str) for r in repositories):
1681 raise ValueError("repositories must be a list of strings")
1682 if (
1683 not isinstance(restore_system_data, bool)
1684 and restore_system_data is not None
1685 ):
1686 raise ValueError("restore_system_data must be a bool or None")
1687 if (
1688 not isinstance(remove_stale_repositories, bool)
1689 and remove_stale_repositories is not None
1690 ):
1691 raise ValueError("remove_stale_repositories must be a bool or None")
1692
1693 payload: dict[str, t.Any] = {}
1694 if repositories is not None:
1695 payload["repositories"] = repositories
1696 if restore_system_data is not None:
1697 payload["restoreSystemData"] = restore_system_data
1698 if remove_stale_repositories is not None:
1699 payload["removeStaleRepositories"] = remove_stale_repositories
1700 payload["bucketUri"] = bucket_uri
1701
1702 params_part: FileContent = (None, json.dumps(payload), "application/json")
1703
1704 def _post(authentication_part: FileContent | None) -> None:
1705 files: list[tuple[str, FileContent]] = [("params", params_part)]
1706 if authentication_part is not None:
1707 files.append(("authenticationFile", authentication_part))
1708 try:
1709 response = self.http_client.post(
1710 "/rest/recovery/cloud-restore",
1711 headers={"Accept": "application/json"},
1712 files=files,
1713 )
1714 response.raise_for_status()
1715 except httpx.HTTPStatusError as err:
1716 status = err.response.status_code
1717 if status == 400:
1718 raise BadRequestError(f"Bad request: {err.response.text}") from err
1719 elif status == 401:
1720 raise UnauthorisedError(
1721 f"Request is unauthorised: {err.response.text}"
1722 ) from err
1723 elif status == 403:
1724 raise ForbiddenError(
1725 f"Request is forbidden: {err.response.text}"
1726 ) from err
1727 raise err
1728
1729 if authentication_file is None:
1730 _post(None)
1731 return
1732
1733 if isinstance(authentication_file, (bytes, bytearray, memoryview)):
1734 content = bytes(authentication_file)
1735 _post(("authentication-file", content, "application/octet-stream"))
1736 return
1737
1738 if hasattr(authentication_file, "read") and not isinstance(
1739 authentication_file, (str, os.PathLike)
1740 ):
1741 file_obj = t.cast(t.IO[bytes], authentication_file)
1742 filename = infer_filename_from_fileobj(file_obj, "authentication-file")
1743 _post((filename, file_obj, "application/octet-stream"))
1744 return
1745
1746 if isinstance(authentication_file, (str, os.PathLike)):
1747 auth_path = pathlib.Path(authentication_file).expanduser()
1748 with open(auth_path, "rb") as f:
1749 filename = auth_path.name or infer_filename_from_fileobj(
1750 f, "authentication-file"
1751 )
1752 _post((filename, f, "application/octet-stream"))
1753 return
1754
1755 raise ValueError(
1756 "authentication_file must be bytes/bytes-like, a binary file-like object, or a filesystem path"
1757 )
1758
1759 @t.overload
1760 def backup(
1761 self,
1762 repositories: list[str] | None = None,
1763 backup_system_data: bool | None = None,
1764 *,
1765 dest: None = None,
1766 ) -> bytes: ...
1767
1768 @t.overload
1769 def backup(
1770 self,
1771 repositories: list[str] | None = None,
1772 backup_system_data: bool | None = None,
1773 *,
1774 dest: str | os.PathLike[str],
1775 ) -> pathlib.Path: ...
1776
1777 def backup(
1778 self,
1779 repositories: list[str] | None = None,
1780 backup_system_data: bool | None = None,
1781 *,
1782 dest: str | os.PathLike[str] | None = None,
1783 ) -> bytes | pathlib.Path:
1784 """Create a new backup of GraphDB instance.
1785
1786 The backup is returned as a tar archive containing repository data and
1787 optionally system data (user accounts, saved queries, visual graphs, etc.).
1788
1789 Parameters:
1790 repositories: List of repositories to be backed up, specified by their repository identifiers.
1791 If `None`, all repositories will be included in the backup.
1792 backup_system_data: Determines whether user account data such as user accounts, saved queries,
1793 or visual graphs, among others, should be included in the backup.
1794 dest: Destination path to save the backup archive. If `None`, the backup
1795 content is returned as bytes (suitable for small backups). If a directory
1796 path is provided, the filename from the response Content-Disposition header
1797 is used (e.g., backup-2026-01-16-10-30-00.tar). If a file path is provided,
1798 that exact path is used. The response is streamed directly to disk
1799 (recommended for large backups).
1800
1801 Returns:
1802 bytes: If `dest` is `None`, returns the backup archive as bytes.
1803 Path: If `dest` is provided, returns the resolved `pathlib.Path` where the backup was saved.
1804
1805 Raises:
1806 ValueError: If repositories is not a list or None, or if backup_system_data is not a bool or None.
1807 BadRequestError: If the request is bad.
1808 UnauthorisedError: If the request is unauthorised.
1809 ForbiddenError: If the request is forbidden.
1810 OSError: If the destination path cannot be written to.
1811 """
1812 if repositories is not None:
1813 if not isinstance(repositories, list):
1814 raise ValueError("repositories must be a list or None")
1815 if not all(isinstance(r, str) for r in repositories):
1816 raise ValueError("repositories must be a list of strings")
1817 if not isinstance(backup_system_data, bool) and backup_system_data is not None:
1818 raise ValueError("backup_system_data must be a bool")
1819
1820 payload: dict[str, t.Any] = {}
1821 if repositories is not None:
1822 payload["repositories"] = repositories
1823 if backup_system_data is not None:
1824 payload["backupSystemData"] = backup_system_data
1825
1826 def _handle_http_error(err: httpx.HTTPStatusError) -> t.NoReturn:
1827 status = err.response.status_code
1828 if status == 400:
1829 raise BadRequestError(f"Bad request: {err.response.text}") from err
1830 elif status == 401:
1831 raise UnauthorisedError(
1832 f"Request is unauthorised: {err.response.text}"
1833 ) from err
1834 elif status == 403:
1835 raise ForbiddenError(
1836 f"Request is forbidden: {err.response.text}"
1837 ) from err
1838 raise err
1839
1840 if dest is None:
1841 # Return bytes directly (suitable for small backups)
1842 try:
1843 response = self.http_client.post("/rest/recovery/backup", json=payload)
1844 response.raise_for_status()
1845 return response.content
1846 except httpx.HTTPStatusError as err:
1847 _handle_http_error(err)
1848 else:
1849 # Stream to disk (recommended for large backups)
1850 dest_path = pathlib.Path(dest).expanduser().resolve()
1851
1852 try:
1853 with self.http_client.stream(
1854 "POST", "/rest/recovery/backup", json=payload
1855 ) as response:
1856 response.raise_for_status()
1857
1858 # If dest is a directory, extract filename from Content-Disposition
1859 if dest_path.is_dir():
1860 content_disposition = response.headers.get(
1861 "Content-Disposition", ""
1862 )
1863 filename = extract_filename_from_content_disposition(
1864 content_disposition
1865 )
1866 if filename:
1867 dest_path = dest_path / filename
1868 else:
1869 # Fallback to a default name if header parsing fails
1870 dest_path = dest_path / "graphdb-backup.tar"
1871
1872 # Use a temporary file during download, then rename atomically
1873 tmp_path = dest_path.with_suffix(dest_path.suffix + ".partial")
1874
1875 with open(tmp_path, "wb") as f:
1876 for chunk in response.iter_bytes():
1877 f.write(chunk)
1878 tmp_path.replace(dest_path)
1879 return dest_path
1880 except httpx.HTTPStatusError as err:
1881 _handle_http_error(err)
1882
1883 def cloud_backup(
1884 self,
1885 bucket_uri: str,
1886 repositories: list[str] | None = None,
1887 backup_system_data: bool | None = None,
1888 authentication_file: (
1889 bytes | bytearray | memoryview | t.IO[bytes] | str | os.PathLike[str] | None
1890 ) = None,
1891 ) -> None:
1892 """Create a new backup of GraphDB instance uploaded to a cloud bucket.
1893
1894 GraphDB uploads the resulting `.tar` archive directly to the configured
1895 cloud bucket. This uses the GraphDB endpoint `/rest/recovery/cloud-backup`.
1896
1897 Parameters:
1898 bucket_uri: Cloud bucket URI including provider-specific parameters (required).
1899 repositories: Optional list of repositories to be backed up.
1900 backup_system_data: Optional flag to include system data (users, saved queries, etc.).
1901 authentication_file: Optional credential file content as bytes/bytes-like, a
1902 binary file-like object, or a filesystem path.
1903
1904 Raises:
1905 ValueError: If parameters are invalid, or authentication_file is not a supported type.
1906 BadRequestError: If the request is bad.
1907 UnauthorisedError: If the request is unauthorised.
1908 ForbiddenError: If the request is forbidden.
1909 """
1910 if not isinstance(bucket_uri, str) or not bucket_uri:
1911 raise ValueError("bucket_uri must be a non-empty string")
1912
1913 if repositories is not None:
1914 if not isinstance(repositories, list):
1915 raise ValueError("repositories must be a list or None")
1916 if not all(isinstance(r, str) for r in repositories):
1917 raise ValueError("repositories must be a list of strings")
1918
1919 if not isinstance(backup_system_data, bool) and backup_system_data is not None:
1920 raise ValueError("backup_system_data must be a bool")
1921
1922 payload: dict[str, t.Any] = {}
1923 if repositories is not None:
1924 payload["repositories"] = repositories
1925 if backup_system_data is not None:
1926 payload["backupSystemData"] = backup_system_data
1927 payload["bucketUri"] = bucket_uri
1928
1929 params_part: FileContent = (None, json.dumps(payload), "application/json")
1930
1931 def _post(authentication_part: FileContent | None) -> None:
1932 files: list[tuple[str, FileContent]] = [("params", params_part)]
1933 if authentication_part is not None:
1934 files.append(("authenticationFile", authentication_part))
1935 try:
1936 response = self.http_client.post(
1937 "/rest/recovery/cloud-backup",
1938 headers={"Accept": "application/json"},
1939 files=files,
1940 )
1941 response.raise_for_status()
1942 except httpx.HTTPStatusError as err:
1943 status = err.response.status_code
1944 if status == 400:
1945 raise BadRequestError(f"Bad request: {err.response.text}") from err
1946 elif status == 401:
1947 raise UnauthorisedError(
1948 f"Request is unauthorised: {err.response.text}"
1949 ) from err
1950 elif status == 403:
1951 raise ForbiddenError(
1952 f"Request is forbidden: {err.response.text}"
1953 ) from err
1954 raise err
1955
1956 if authentication_file is None:
1957 _post(None)
1958 return
1959
1960 if isinstance(authentication_file, (bytes, bytearray, memoryview)):
1961 content = bytes(authentication_file)
1962 _post(("authentication-file", content, "application/octet-stream"))
1963 return
1964
1965 if hasattr(authentication_file, "read") and not isinstance(
1966 authentication_file, (str, os.PathLike)
1967 ):
1968 file_obj = t.cast(t.IO[bytes], authentication_file)
1969 filename = infer_filename_from_fileobj(file_obj, "authentication-file")
1970 _post((filename, file_obj, "application/octet-stream"))
1971 return
1972
1973 if isinstance(authentication_file, (str, os.PathLike)):
1974 auth_path = pathlib.Path(authentication_file).expanduser()
1975 with open(auth_path, "rb") as f:
1976 filename = auth_path.name or infer_filename_from_fileobj(
1977 f, "authentication-file"
1978 )
1979 _post((filename, f, "application/octet-stream"))
1980 return
1981
1982 raise ValueError(
1983 "authentication_file must be bytes/bytes-like, a binary file-like object, or a filesystem path"
1984 )
1985
1986
1987class RepositoryManagement:
1988 """GraphDB Repository Management client.
1989
1990 The functionality provided by this management client accepts an optional location parameter to operate on external
1991 GraphDB locations.
1992 """
1993
1994 def __init__(self, http_client: httpx.Client):
1995 self._http_client = http_client
1996
1997 def list(self, location: str | None = None) -> list[GraphDBRepository]:
1998 """List all repositories.
1999
2000 Parameters:
2001 location: The location of the repositories.
2002
2003 Returns:
2004 list[GraphDBRepository]: List of GraphDB repositories.
2005
2006 Raises:
2007 InternalServerError: If the server returns an internal error.
2008 ResponseFormatError: If the response cannot be parsed.
2009 """
2010 params = {}
2011 if location is not None:
2012 params["location"] = location
2013 try:
2014 response = self.http_client.get("/rest/repositories", params=params)
2015 response.raise_for_status()
2016 try:
2017 return [GraphDBRepository.from_dict(repo) for repo in response.json()]
2018 except (ValueError, TypeError) as err:
2019 raise ResponseFormatError(
2020 f"Failed to parse GraphDB response: {err}"
2021 ) from err
2022 except httpx.HTTPStatusError as err:
2023 if err.response.status_code == 500:
2024 raise InternalServerError(
2025 f"Internal server error: {err.response.text}"
2026 ) from err
2027 raise
2028
2029 def create(
2030 self,
2031 config: RepositoryConfigBeanCreate | str,
2032 location: str | None = None,
2033 files: FilesType | None = None,
2034 ):
2035 """Create a new repository.
2036
2037 Parameters:
2038 config: Repository configuration. When a `RepositoryConfigBeanCreate` is
2039 provided, the request is sent as JSON. When a string is provided, it
2040 is treated as Turtle content and sent as multipart/form-data part
2041 `config` (required by GraphDB) with the content type `text/turtle`.
2042 location: Optional repository location (query param `location`).
2043 files: Optional extra multipart parts for GraphDB-specific files (e.g.
2044 `obdaFile`, `owlFile`, `propertiesFile`, `constraintFile`,
2045 `dbMetadataFile`, `lensesFile`). Keys must be the form part names;
2046 values may be file content or httpx-style file tuples. Ignored when
2047 `config` is a dataclass (JSON payload).
2048
2049 Raises:
2050 BadRequestError: If the request is invalid.
2051 UnauthorisedError: If the request is unauthorised.
2052 ForbiddenError: If the request is forbidden.
2053 InternalServerError: If the server returns an internal error.
2054 """
2055 params = {}
2056 if location is not None:
2057 params["location"] = location
2058
2059 def _normalize_file_content(field: str, value: FileContent) -> FileContent:
2060 if isinstance(value, tuple):
2061 # fill in the missing filename with the field name
2062 if len(value) == 2:
2063 filename, content = value
2064 return (filename or field, content)
2065 filename, content, content_type = value
2066 return (filename or field, content, content_type)
2067 return (field, value)
2068
2069 try:
2070 if isinstance(config, str):
2071 extra_parts: list[tuple[str, FileContent]] = []
2072 if files is not None:
2073 if isinstance(files, t.Mapping):
2074 extra_parts = list(files.items())
2075 else:
2076 extra_parts = list(files)
2077
2078 if any(field == "config" for field, _ in extra_parts):
2079 raise ValueError(
2080 "Do not pass a 'config' multipart part via files; use the config argument instead."
2081 )
2082
2083 multipart_files: list[tuple[str, FileContent]] = [
2084 ("config", ("config.ttl", config, "text/turtle"))
2085 ]
2086 for field, content in extra_parts:
2087 multipart_files.append(
2088 (field, _normalize_file_content(field, content))
2089 )
2090
2091 response = self.http_client.post(
2092 "/rest/repositories",
2093 params=params,
2094 files=multipart_files,
2095 )
2096 else:
2097 if files is not None:
2098 raise ValueError(
2099 "Additional files can only be provided when config is a Turtle string."
2100 )
2101 response = self.http_client.post(
2102 "/rest/repositories",
2103 headers={"Content-Type": "application/json"},
2104 json=config.as_dict(),
2105 params=params,
2106 )
2107 response.raise_for_status()
2108 except httpx.HTTPStatusError as err:
2109 status = err.response.status_code
2110 if status == 400:
2111 raise BadRequestError(f"Invalid request: {err.response.text}") from err
2112 elif status == 401:
2113 raise UnauthorisedError(
2114 f"Request is unauthorised: {err.response.text}"
2115 ) from err
2116 elif status == 403:
2117 raise ForbiddenError(
2118 f"Request is forbidden: {err.response.text}"
2119 ) from err
2120 elif status == 500:
2121 raise InternalServerError(
2122 f"Internal server error: {err.response.text}"
2123 ) from err
2124 raise
2125
2126 @property
2127 def http_client(self):
2128 return self._http_client
2129
2130 @t.overload
2131 def get(
2132 self,
2133 repository_id: str,
2134 content_type: t.Literal["application/json"],
2135 location: str | None = None,
2136 ) -> RepositoryConfigBean: ...
2137
2138 @t.overload
2139 def get(
2140 self,
2141 repository_id: str,
2142 content_type: None = None,
2143 location: str | None = None,
2144 ) -> RepositoryConfigBean: ...
2145
2146 @t.overload
2147 def get(
2148 self,
2149 repository_id: str,
2150 content_type: t.Literal["text/turtle"],
2151 location: str | None = None,
2152 ) -> Graph: ...
2153
2154 @t.overload
2155 def get(
2156 self,
2157 repository_id: str,
2158 content_type: str,
2159 location: str | None = None,
2160 ) -> RepositoryConfigBean | Graph: ...
2161
2162 def get(
2163 self,
2164 repository_id: str,
2165 content_type: str | None = None,
2166 location: str | None = None,
2167 ) -> RepositoryConfigBean | Graph:
2168 """Get a repository's configuration.
2169
2170 Parameters:
2171 repository_id: The identifier of the repository.
2172 content_type: The content type of the response. Can be `application/json` or
2173 `text/turtle`. Defaults to `application/json`.
2174 location: The location of the repository.
2175
2176 Returns:
2177 RepositoryConfigBean: The repository configuration.
2178 Graph: The repository configuration in RDF.
2179
2180 Raises:
2181 BadRequestError: If the content type is not supported.
2182 ResponseFormatError: If the response cannot be parsed.
2183 RepositoryNotFoundError: If the repository is not found.
2184 InternalServerError: If the server returns an internal error.
2185 """
2186 if content_type is None:
2187 content_type = "application/json"
2188 if content_type not in ("application/json", "text/turtle"):
2189 raise ValueError(f"Unsupported content type: {content_type}.")
2190 headers = {"Accept": content_type}
2191 params = {}
2192 if location is not None:
2193 params["location"] = location
2194 try:
2195 response = self.http_client.get(
2196 f"/rest/repositories/{repository_id}", headers=headers, params=params
2197 )
2198 response.raise_for_status()
2199
2200 if content_type == "application/json":
2201 try:
2202 return RepositoryConfigBean(**response.json())
2203 except (ValueError, TypeError) as err:
2204 raise ResponseFormatError(
2205 "Failed to parse GraphDB response."
2206 ) from err
2207 elif content_type == "text/turtle":
2208 try:
2209 return Graph().parse(data=response.text, format="turtle")
2210 except Exception as err:
2211 raise ResponseFormatError(f"Error parsing RDF: {err}") from err
2212 else:
2213 raise ValueError(f"Unhandled content type: {content_type}.")
2214 except httpx.HTTPStatusError as err:
2215 if err.response.status_code == 404:
2216 raise RepositoryNotFoundError(
2217 f"Repository {repository_id} not found."
2218 ) from err
2219 elif err.response.status_code == 500:
2220 raise InternalServerError("Internal server error.") from err
2221 raise
2222
2223 def edit(self, repository_id: str, config: RepositoryConfigBeanCreate) -> None:
2224 """Edit a repository's configuration.
2225
2226 Parameters:
2227 repository_id: The identifier of the repository.
2228 config: The repository configuration.
2229
2230 Raises:
2231 BadRequestError: If the request is invalid.
2232 UnauthorisedError: If the request is unauthorised.
2233 ForbiddenError: If the request is forbidden.
2234 InternalServerError: If the server returns an internal error.
2235 """
2236 headers = {
2237 "Content-Type": "application/json",
2238 }
2239 try:
2240 response = self.http_client.put(
2241 f"/rest/repositories/{repository_id}",
2242 headers=headers,
2243 json=config.as_dict(),
2244 )
2245 response.raise_for_status()
2246 except httpx.HTTPStatusError as err:
2247 if err.response.status_code == 400:
2248 raise BadRequestError(f"Invalid request: {err.response.text}") from err
2249 elif err.response.status_code == 401:
2250 raise UnauthorisedError(
2251 f"Request is unauthorised: {err.response.text}"
2252 ) from err
2253 elif err.response.status_code == 403:
2254 raise ForbiddenError(
2255 f"Request is forbidden: {err.response.text}"
2256 ) from err
2257 elif err.response.status_code == 500:
2258 raise InternalServerError(
2259 f"Internal server error: {err.response.text}"
2260 ) from err
2261 raise
2262
2263 def delete(self, repository_id: str, location: str | None = None) -> None:
2264 """Delete a repository.
2265
2266 Parameters:
2267 repository_id: The identifier of the repository.
2268 location: The location of the repository.
2269
2270 Raises:
2271 BadRequestError: If the request is invalid.
2272 UnauthorisedError: If the request is unauthorised.
2273 ForbiddenError: If the request is forbidden.
2274 InternalServerError: If the server returns an internal error.
2275 """
2276 params = {}
2277 if location is not None:
2278 params["location"] = location
2279 try:
2280 response = self.http_client.delete(
2281 f"/rest/repositories/{repository_id}", params=params
2282 )
2283 response.raise_for_status()
2284 except httpx.HTTPStatusError as err:
2285 if err.response.status_code == 400:
2286 raise BadRequestError(f"Invalid request: {err.response.text}") from err
2287 elif err.response.status_code == 401:
2288 raise UnauthorisedError(
2289 f"Request is unauthorised: {err.response.text}"
2290 ) from err
2291 elif err.response.status_code == 403:
2292 raise ForbiddenError(
2293 f"Request is forbidden: {err.response.text}"
2294 ) from err
2295 elif err.response.status_code == 500:
2296 raise InternalServerError(
2297 f"Internal server error: {err.response.text}"
2298 ) from err
2299 raise
2300
2301 def restart(
2302 self, repository_id: str, sync: bool | None = None, location: str | None = None
2303 ) -> str:
2304 """Restart a repository.
2305
2306 Parameters:
2307 repository_id: The identifier of the repository.
2308 sync: Whether to sync the repository.
2309 location: The location of the repository.
2310
2311 Returns:
2312 str: The response text.
2313
2314 Raises:
2315 UnauthorisedError: If the request is unauthorised.
2316 ForbiddenError: If the request is forbidden.
2317 RepositoryNotFoundError: If the repository is not found.
2318 """
2319 params = {}
2320 if sync is not None:
2321 params["sync"] = str(sync).lower()
2322 if location is not None:
2323 params["location"] = location
2324 try:
2325 response = self.http_client.post(
2326 f"/rest/repositories/{repository_id}/restart", params=params
2327 )
2328 response.raise_for_status()
2329 return response.text
2330 except httpx.HTTPStatusError as err:
2331 if err.response.status_code == 401:
2332 raise UnauthorisedError("Request is unauthorised.") from err
2333 elif err.response.status_code == 403:
2334 raise ForbiddenError("Request is forbidden.") from err
2335 elif err.response.status_code == 404:
2336 raise RepositoryNotFoundError(
2337 f"Repository {repository_id} not found."
2338 ) from err
2339 raise
2340
2341 def size(
2342 self, repository_id: str, location: str | None = None
2343 ) -> RepositorySizeInfo:
2344 """Get repository size.
2345
2346 Parameters:
2347 repository_id: The identifier of the repository.
2348 location: The location of the repository.
2349
2350 Raises:
2351 ResponseFormatError: If the response cannot be parsed.
2352 InternalServerError: If the server returns an internal error.
2353 """
2354 params = {}
2355 if location:
2356 params["location"] = location
2357 try:
2358 response = self.http_client.get(
2359 f"/rest/repositories/{repository_id}/size", params=params
2360 )
2361 response.raise_for_status()
2362 try:
2363 return RepositorySizeInfo(**response.json())
2364 except (ValueError, TypeError) as err:
2365 raise ResponseFormatError("Failed to parse GraphDB response.") from err
2366 except httpx.HTTPStatusError as err:
2367 if err.response.status_code == 500:
2368 raise InternalServerError(
2369 f"Internal server error: {err.response.text}"
2370 ) from err
2371 raise
2372
2373 @t.overload
2374 def validate(
2375 self,
2376 repository_id: str,
2377 *,
2378 content_type: str,
2379 content: str,
2380 location: str | None = None,
2381 shapes_repository_id: None = None,
2382 ) -> str: ...
2383
2384 @t.overload
2385 def validate(
2386 self,
2387 repository_id: str,
2388 *,
2389 content: t.IO[bytes],
2390 content_type: str | None = None,
2391 location: str | None = None,
2392 shapes_repository_id: None = None,
2393 ) -> str: ...
2394
2395 @t.overload
2396 def validate(
2397 self,
2398 repository_id: str,
2399 *,
2400 shapes_repository_id: str,
2401 location: str | None = None,
2402 ) -> str: ...
2403
2404 def validate(
2405 self,
2406 repository_id: str,
2407 *,
2408 content_type: str | None = None,
2409 content: str | t.IO[bytes] | None = None,
2410 location: str | None = None,
2411 shapes_repository_id: str | None = None,
2412 ) -> str:
2413 """Validate repository data using SHACL shapes.
2414
2415 Parameters:
2416 repository_id: The identifier of the repository.
2417 content_type: Content type of the request body (required for text payloads).
2418 content: SHACL shapes payload; string for text-based validation or file-like
2419 (binary) object for multipart validation.
2420 location: Optional repository location.
2421 shapes_repository_id: ID of repository containing SHACL shapes; when
2422 provided, no content is sent and shapes are fetched from that
2423 repository.
2424
2425 Returns:
2426 str: Validation report as RDF Turtle.
2427
2428 Raises:
2429 UnauthorisedError: If the request is unauthorised.
2430 ForbiddenError: If the request is forbidden.
2431 InternalServerError: If the server returns an internal error.
2432 """
2433 params = {}
2434 if location is not None:
2435 params["location"] = location
2436
2437 if shapes_repository_id is not None:
2438 if content is not None:
2439 raise ValueError(
2440 "content must not be provided when shapes_repository_id is set."
2441 )
2442 if content_type is not None:
2443 raise ValueError(
2444 "content_type must not be provided when shapes_repository_id is set."
2445 )
2446 headers = {"Accept": "text/turtle"}
2447 try:
2448 response = self.http_client.post(
2449 url=f"/rest/repositories/{repository_id}/validate/repository/{shapes_repository_id}",
2450 params=params,
2451 headers=headers,
2452 )
2453 response.raise_for_status()
2454 return response.text
2455 except httpx.HTTPStatusError as err:
2456 status = err.response.status_code
2457 if status == 401:
2458 raise UnauthorisedError("Request is unauthorised.") from err
2459 elif status == 403:
2460 raise ForbiddenError("Request is forbidden.") from err
2461 elif status == 500:
2462 raise InternalServerError(
2463 f"Internal server error: {err.response.text}"
2464 ) from err
2465 raise
2466
2467 if content is None:
2468 raise ValueError("content must be provided.")
2469
2470 is_file_like = hasattr(content, "read") and not isinstance(content, str)
2471
2472 if is_file_like:
2473 headers = {"Accept": "text/turtle"}
2474 file_part = (
2475 "shapes.ttl",
2476 t.cast(t.IO[bytes], content),
2477 content_type or "text/turtle",
2478 )
2479 files: FilesType = {"file": file_part}
2480 try:
2481 response = self.http_client.post(
2482 url=f"/rest/repositories/{repository_id}/validate/file",
2483 params=params,
2484 headers=headers,
2485 files=files,
2486 )
2487 response.raise_for_status()
2488 return response.text
2489 except httpx.HTTPStatusError as err:
2490 status = err.response.status_code
2491 if status == 401:
2492 raise UnauthorisedError("Request is unauthorised.") from err
2493 elif status == 403:
2494 raise ForbiddenError("Request is forbidden.") from err
2495 elif status == 500:
2496 raise InternalServerError(
2497 f"Internal server error: {err.response.text}"
2498 ) from err
2499 raise
2500 else:
2501 if not content_type:
2502 raise ValueError("content_type must be provided for text validation.")
2503
2504 headers = {"Content-Type": content_type, "Accept": "text/turtle"}
2505 try:
2506 response = self.http_client.post(
2507 url=f"/rest/repositories/{repository_id}/validate/text",
2508 params=params,
2509 headers=headers,
2510 content=content,
2511 )
2512 response.raise_for_status()
2513 return response.text
2514 except httpx.HTTPStatusError as err:
2515 status = err.response.status_code
2516 if status == 401:
2517 raise UnauthorisedError("Request is unauthorised.") from err
2518 elif status == 403:
2519 raise ForbiddenError("Request is forbidden.") from err
2520 elif status == 500:
2521 raise InternalServerError(
2522 f"Internal server error: {err.response.text}"
2523 ) from err
2524 raise
2525
2526
2527class SecurityManagement:
2528 """GraphDB Security Management client."""
2529
2530 def __init__(self, http_client: httpx.Client):
2531 self._http_client = http_client
2532
2533 @property
2534 def http_client(self):
2535 return self._http_client
2536
2537 @property
2538 def enabled(self) -> bool:
2539 """Check if security is enabled.
2540
2541 Returns:
2542 bool: True if security is enabled, False otherwise.
2543
2544 Raises:
2545 ResponseFormatError: If the response format is invalid.
2546 InternalServerError: If the server returns an internal error.
2547 """
2548 try:
2549 headers = {"Accept": "application/json"}
2550 response = self.http_client.get("/rest/security", headers=headers)
2551 response.raise_for_status()
2552 try:
2553 value = response.json()
2554 if not isinstance(value, bool):
2555 raise ResponseFormatError("Response is not a boolean.")
2556 return value
2557 except (ValueError, TypeError) as err:
2558 raise ResponseFormatError(
2559 f"Failed to parse GraphDB response: {err}"
2560 ) from err
2561 except httpx.HTTPStatusError as err:
2562 if err.response.status_code == 500:
2563 raise InternalServerError(
2564 f"Internal server error: {err.response.text}"
2565 ) from err
2566 raise
2567
2568 @enabled.setter
2569 def enabled(self, value: bool):
2570 """Enable or disable security.
2571
2572 Parameters:
2573 value: The value to set.
2574
2575 Raises:
2576 TypeError: If the value is not a boolean.
2577 UnauthorisedError: If the request is unauthorised.
2578 ForbiddenError: If the request is forbidden.
2579 PreconditionFailedError: If the precondition is failed.
2580 """
2581 if not isinstance(value, bool):
2582 raise TypeError("Value must be a boolean.")
2583 try:
2584 headers = {"Content-Type": "application/json", "Accept": "application/json"}
2585 response = self.http_client.post(
2586 "/rest/security", headers=headers, json=value
2587 )
2588 response.raise_for_status()
2589 except httpx.HTTPStatusError as err:
2590 if err.response.status_code == 401:
2591 raise UnauthorisedError("Request is unauthorised.") from err
2592 elif err.response.status_code == 403:
2593 raise ForbiddenError("Request is forbidden.") from err
2594 elif err.response.status_code == 412:
2595 raise PreconditionFailedError("Precondition failed.") from err
2596 raise
2597
2598 def get_free_access_details(self):
2599 """
2600 Check if free access is enabled.
2601
2602 Returns:
2603 FreeAccessSettings: The free access settings.
2604
2605 Raises:
2606 ResponseFormatError: If the response format is invalid.
2607 InternalServerError: If the server returns an internal error.
2608 """
2609 try:
2610 headers = {"Accept": "application/json"}
2611 response = self.http_client.get(
2612 "/rest/security/free-access", headers=headers
2613 )
2614 response.raise_for_status()
2615 try:
2616 return FreeAccessSettings(**response.json())
2617 except (ValueError, TypeError) as err:
2618 raise ResponseFormatError(
2619 f"Failed to parse GraphDB response: {err}"
2620 ) from err
2621 except httpx.HTTPStatusError as err:
2622 if err.response.status_code == 500:
2623 raise InternalServerError(
2624 f"Internal server error: {err.response.text}"
2625 ) from err
2626 raise
2627
2628 def set_free_access_details(self, free_access_settings: FreeAccessSettings):
2629 """
2630 Enable or disable free access.
2631
2632 Parameters:
2633 free_access_settings: The free access settings.
2634
2635 Raises:
2636 UnauthorisedError: If the request is unauthorised.
2637 ForbiddenError: If the request is forbidden.
2638 PreconditionFailedError: If the precondition is failed.
2639 """
2640 try:
2641 headers = {"Content-Type": "application/json", "Accept": "application/json"}
2642 response = self.http_client.post(
2643 "/rest/security/free-access",
2644 headers=headers,
2645 json=free_access_settings.as_dict(),
2646 )
2647 response.raise_for_status()
2648 except httpx.HTTPStatusError as err:
2649 if err.response.status_code == 401:
2650 raise UnauthorisedError("Request is unauthorised.") from err
2651 elif err.response.status_code == 403:
2652 raise ForbiddenError("Request is forbidden.") from err
2653 elif err.response.status_code == 412:
2654 raise PreconditionFailedError("Precondition failed.") from err
2655 raise
2656
2657
2658class UserManagement:
2659 """GraphDB User Management client."""
2660
2661 def __init__(self, http_client: httpx.Client):
2662 self._http_client = http_client
2663
2664 @property
2665 def http_client(self):
2666 return self._http_client
2667
2668 def list(self) -> list[User]:
2669 """
2670 Get all users.
2671
2672 Returns:
2673 A list of users.
2674
2675 Raises:
2676 ResponseFormatError: If the response format is invalid.
2677 UnauthorisedError: If the request is unauthorised.
2678 ForbiddenError: If the request is forbidden.
2679 PreconditionFailedError: If the precondition is failed.
2680 InternalServerError: If the server returns an internal error.
2681 """
2682 headers = {"Accept": "application/json"}
2683 try:
2684 response = self.http_client.get("/rest/security/users", headers=headers)
2685 response.raise_for_status()
2686 try:
2687 return [User(**user) for user in response.json()]
2688 except (ValueError, TypeError) as err:
2689 raise ResponseFormatError(
2690 f"Failed to parse GraphDB response: {err}"
2691 ) from err
2692 except httpx.HTTPStatusError as err:
2693 if err.response.status_code == 401:
2694 raise UnauthorisedError("Request is unauthorised.") from err
2695 elif err.response.status_code == 403:
2696 raise ForbiddenError("Request is forbidden.") from err
2697 elif err.response.status_code == 412:
2698 raise PreconditionFailedError("Precondition failed.") from err
2699 elif err.response.status_code == 500:
2700 raise InternalServerError(
2701 f"Internal server error: {err.response.text}"
2702 ) from err
2703 raise
2704
2705 def get(self, username: str) -> User:
2706 """
2707 Get a user.
2708
2709 Parameters:
2710 username: The username of the user.
2711
2712 Returns:
2713 User: The user.
2714
2715 Raises:
2716 ResponseFormatError: If the response format is invalid.
2717 ForbiddenError: If the request is forbidden.
2718 NotFoundError: If the user is not found.
2719 InternalServerError: If the server returns an internal error.
2720 """
2721 try:
2722 headers = {"Accept": "application/json"}
2723 response = self.http_client.get(
2724 f"/rest/security/users/{username}", headers=headers
2725 )
2726 response.raise_for_status()
2727 try:
2728 return User(**response.json())
2729 except (ValueError, TypeError) as err:
2730 raise ResponseFormatError(
2731 f"Failed to parse GraphDB response: {err}"
2732 ) from err
2733 except httpx.HTTPStatusError as err:
2734 if err.response.status_code == 403:
2735 raise ForbiddenError("Request is forbidden.") from err
2736 elif err.response.status_code == 404:
2737 raise NotFoundError("User not found.") from err
2738 elif err.response.status_code == 500:
2739 raise InternalServerError(
2740 f"Internal server error: {err.response.text}"
2741 ) from err
2742 raise
2743
2744 def overwrite(self, username: str, user: User) -> None:
2745 """
2746 Overwrite a user.
2747
2748 Parameters:
2749 username: The username of the user.
2750 user: The user to overwrite.
2751
2752 Raises:
2753 TypeError: if username is not a string or user is not an instance of User.
2754 UnauthorisedError: If the request is unauthorised.
2755 ForbiddenError: If the request is forbidden.
2756 NotFoundError: If the user is not found.
2757 """
2758 if not isinstance(username, str):
2759 raise TypeError("Username must be a string.")
2760 if not isinstance(user, User):
2761 raise TypeError("User must be an instance of User.")
2762
2763 try:
2764 headers = {"Content-Type": "application/json"}
2765 response = self.http_client.put(
2766 f"/rest/security/users/{username}", headers=headers, json=user.as_dict()
2767 )
2768 response.raise_for_status()
2769 except httpx.HTTPStatusError as err:
2770 if err.response.status_code == 401:
2771 raise UnauthorisedError("Request is unauthorised.") from err
2772 elif err.response.status_code == 403:
2773 raise ForbiddenError("Request is forbidden.") from err
2774 elif err.response.status_code == 404:
2775 raise NotFoundError("User not found.") from err
2776 raise
2777
2778 def create(self, username: str, user: UserCreate) -> None:
2779 """
2780 Create a user.
2781
2782 Parameters:
2783 username: The username of the user.
2784 user: The user to create.
2785
2786 Raises:
2787 TypeError: if username is not a string or user is not an instance of UserCreate.
2788 BadRequestError: If the request is bad.
2789 UnauthorisedError: If the request is unauthorised.
2790 ForbiddenError: If the request is forbidden.
2791 """
2792 if not isinstance(username, str):
2793 raise TypeError("Username must be a string.")
2794 if not isinstance(user, UserCreate):
2795 raise TypeError("User must be an instance of UserCreate.")
2796
2797 try:
2798 headers = {"Content-Type": "application/json"}
2799 response = self.http_client.post(
2800 f"/rest/security/users/{username}", headers=headers, json=user.as_dict()
2801 )
2802 response.raise_for_status()
2803 except httpx.HTTPStatusError as err:
2804 if err.response.status_code == 400:
2805 raise BadRequestError(f"Bad request. {err.response.text}") from err
2806 elif err.response.status_code == 401:
2807 raise UnauthorisedError("Request is unauthorised.") from err
2808 elif err.response.status_code == 403:
2809 raise ForbiddenError("Request is forbidden.") from err
2810 raise
2811
2812 def delete(self, username: str) -> None:
2813 """
2814 Delete a user.
2815
2816 Parameters:
2817 username: The username of the user.
2818
2819 Raises:
2820 TypeError: if username is not a string.
2821 BadRequestError: If the request is bad.
2822 UnauthorisedError: If the request is unauthorised.
2823 ForbiddenError: If the request is forbidden.
2824 NotFoundError: If the user is not found.
2825 """
2826 if not isinstance(username, str):
2827 raise TypeError("Username must be a string.")
2828
2829 try:
2830 response = self.http_client.delete(f"/rest/security/users/{username}")
2831 response.raise_for_status()
2832 except httpx.HTTPStatusError as err:
2833 if err.response.status_code == 400:
2834 raise BadRequestError(f"Bad request. {err.response.text}") from err
2835 elif err.response.status_code == 401:
2836 raise UnauthorisedError("Request is unauthorised.") from err
2837 elif err.response.status_code == 403:
2838 raise ForbiddenError("Request is forbidden.") from err
2839 elif err.response.status_code == 404:
2840 raise NotFoundError("User not found.") from err
2841 raise
2842
2843 def update(self, username: str, user: UserUpdate | dict[str, t.Any]) -> None:
2844 """
2845 Update a user.
2846
2847 !!! Note
2848 Certain user fields are not updatable using PATCH. For example, at the
2849 time of writing, `grantedAuthorities` are not updatable, but `appSettings` are.
2850
2851 Parameters:
2852 username: The username of the user.
2853 user: The user data to update, either as a UserUpdate instance or a dict.
2854
2855 Raises:
2856 TypeError: if username is not a string or user is not an instance of UserUpdate or dict.
2857 ForbiddenError: If the request is forbidden.
2858 PreconditionFailedError: If the precondition is failed.
2859 """
2860 if not isinstance(username, str):
2861 raise TypeError("Username must be a string.")
2862 if not isinstance(user, (UserUpdate, dict)):
2863 raise TypeError("User must be an instance of UserUpdate or dict.")
2864
2865 if isinstance(user, UserUpdate):
2866 user_data = user.as_dict()
2867 else:
2868 user_data = user
2869
2870 try:
2871 headers = {"Content-Type": "application/json"}
2872 response = self.http_client.patch(
2873 f"/rest/security/users/{username}", headers=headers, json=user_data
2874 )
2875 response.raise_for_status()
2876 except httpx.HTTPStatusError as err:
2877 if err.response.status_code == 403:
2878 raise ForbiddenError("Request is forbidden.") from err
2879 elif err.response.status_code == 412:
2880 raise PreconditionFailedError("Precondition failed.") from err
2881 raise
2882
2883 def custom_roles(self, username: str) -> t.List[str]:
2884 """
2885 Retrieve custom roles associated with the user.
2886
2887 Parameters:
2888 username: The username of the user.
2889
2890 Returns:
2891 list[str]: The custom roles for the user.
2892
2893 Raises:
2894 TypeError: if username is not a string.
2895 ForbiddenError: If the request is forbidden.
2896 NotFoundError: If the user is not found.
2897 InternalServerError: If the request fails.
2898 """
2899 if not isinstance(username, str):
2900 raise TypeError("Username must be a string.")
2901
2902 try:
2903 response = self.http_client.get(
2904 f"/rest/security/users/{username}/custom-roles"
2905 )
2906 response.raise_for_status()
2907 return response.json()
2908 except httpx.HTTPStatusError as err:
2909 if err.response.status_code == 403:
2910 raise ForbiddenError("Request is forbidden.") from err
2911 elif err.response.status_code == 404:
2912 raise NotFoundError("User not found.") from err
2913 elif err.response.status_code == 500:
2914 raise InternalServerError("Internal server error.") from err
2915 raise
2916
2917
2918class GraphDBClient(RDF4JClient):
2919 """GraphDB Client
2920
2921 This client and its inner management objects perform HTTP requests via
2922 httpx and may raise httpx-specific exceptions. Errors documented by GraphDB
2923 in its OpenAPI specification are mapped to specific exceptions in this
2924 library where applicable. Error mappings are documented on each management
2925 method. The underlying httpx client is reused across
2926 requests, and connection pooling is handled automatically by httpx.
2927
2928 Parameters:
2929 base_url: The base URL of the GraphDB server.
2930 auth: Authentication credentials. Can be a tuple (username, password) for
2931 basic auth, or a string for token-based auth (e.g., "GDB <token>")
2932 which is added as the Authorization header.
2933 timeout: Request timeout in seconds or an httpx.Timeout for fine-grained control (default: 30.0).
2934 kwargs: Additional keyword arguments to pass to the httpx.Client.
2935 """
2936
2937 def __init__(
2938 self,
2939 base_url: str,
2940 auth: tuple[str, str] | str | None = None,
2941 timeout: float | httpx.Timeout = 30.0,
2942 **kwargs: t.Any,
2943 ):
2944 super().__init__(base_url, auth, timeout, **kwargs)
2945 self._cluster_group = ClusterGroupManagement(self.http_client)
2946 self._monitoring = MonitoringManagement(self.http_client)
2947 self._recovery = RecoveryManagement(self.http_client)
2948 self._graphdb_repository_manager = RepositoryManager(self.http_client)
2949 self._graphdb_repositories = RepositoryManagement(self.http_client)
2950 self._security = SecurityManagement(self.http_client)
2951 self._users = UserManagement(self.http_client)
2952
2953 @property
2954 def cluster(self) -> ClusterGroupManagement:
2955 return self._cluster_group
2956
2957 @property
2958 def monitoring(self) -> MonitoringManagement:
2959 return self._monitoring
2960
2961 @property
2962 def recovery(self) -> RecoveryManagement:
2963 return self._recovery
2964
2965 @property
2966 def repositories(self) -> RepositoryManager:
2967 """Server-level repository management operations (GraphDB-specific)."""
2968 return self._graphdb_repository_manager
2969
2970 @property
2971 def graphdb_repositories(self) -> RepositoryManagement:
2972 return self._graphdb_repositories
2973
2974 @property
2975 def security(self) -> SecurityManagement:
2976 return self._security
2977
2978 @property
2979 def users(self) -> UserManagement:
2980 return self._users
2981
2982 def login(self, username: str, password: str) -> AuthenticatedUser:
2983 """Authenticate with GraphDB and obtain a GDB token.
2984
2985 Parameters:
2986 username: The username to authenticate with.
2987 password: The password to authenticate with.
2988
2989 Returns:
2990 An AuthenticatedUser instance containing user details and the GDB token.
2991
2992 Raises:
2993 UnauthorisedError: If the credentials are invalid.
2994 BadRequestError: If the request body is invalid.
2995 ResponseFormatError: If the response cannot be parsed.
2996 """
2997 try:
2998 response = self.http_client.post(
2999 "/rest/login",
3000 json={"username": username, "password": password},
3001 )
3002 response.raise_for_status()
3003
3004 auth_header = response.headers.get("Authorization", "")
3005 if not auth_header.startswith("GDB "):
3006 raise ResponseFormatError(
3007 "Authorization header missing or invalid format"
3008 )
3009
3010 try:
3011 data = response.json()
3012 except (ValueError, TypeError) as err:
3013 raise ResponseFormatError(
3014 f"Failed to parse login response: {err}"
3015 ) from err
3016
3017 try:
3018 return AuthenticatedUser.from_response(data, auth_header)
3019 except (ValueError, TypeError) as err:
3020 raise ResponseFormatError(
3021 f"Failed to parse authenticated user: {err}"
3022 ) from err
3023
3024 except httpx.HTTPStatusError as err:
3025 status = err.response.status_code
3026 if status == 400:
3027 raise BadRequestError(f"Invalid request: {err.response.text}") from err
3028 elif status == 401:
3029 raise UnauthorisedError(
3030 f"Invalid credentials: {err.response.text}"
3031 ) from err
3032 raise