src/rdflib/contrib/graphdb/models.py
1from __future__ import annotations
2
3import typing as t
4from dataclasses import asdict, dataclass, field
5from enum import Enum
6
7from rdflib import Literal, URIRef
8from rdflib.util import from_n3
9
10
11@dataclass(frozen=True)
12class TopologyStatus:
13 state: str
14 primaryTags: dict[str, t.Any] # noqa: N815
15
16 def __post_init__(self) -> None:
17 invalid: list[tuple[str, t.Any, type]] = []
18 state = t.cast(t.Any, self.state)
19 primary_tags = t.cast(t.Any, self.primaryTags)
20
21 if not isinstance(state, str):
22 invalid.append(("state", state, type(state)))
23 if not isinstance(primary_tags, dict):
24 invalid.append(("primaryTags", primary_tags, type(primary_tags)))
25 else:
26 for key, value in primary_tags.items():
27 if not isinstance(key, str):
28 invalid.append((f"primaryTags key '{key}'", key, type(key)))
29
30 if invalid:
31 raise ValueError("Invalid TopologyStatus values: ", invalid)
32
33
34@dataclass(frozen=True)
35class RecoveryOperation:
36 name: str
37 message: str
38
39 def __post_init__(self) -> None:
40 invalid: list[tuple[str, t.Any, type]] = []
41 name = t.cast(t.Any, self.name)
42 message = t.cast(t.Any, self.message)
43
44 if not isinstance(name, str):
45 invalid.append(("name", name, type(name)))
46 if not isinstance(message, str):
47 invalid.append(("message", message, type(message)))
48
49 if invalid:
50 raise ValueError("Invalid RecoveryOperation values: ", invalid)
51
52
53@dataclass(frozen=True)
54class RecoveryStatus:
55 state: RecoveryOperation | None = None
56 message: str | None = None
57 affectedNodes: list[str] = field(default_factory=list) # noqa: N815
58
59 def __post_init__(self) -> None:
60 invalid: list[tuple[str, t.Any, type]] = []
61 state = t.cast(t.Any, self.state)
62 message = t.cast(t.Any, self.message)
63 affected_nodes = t.cast(t.Any, self.affectedNodes)
64
65 if state is not None and not isinstance(state, RecoveryOperation):
66 invalid.append(("state", state, type(state)))
67 if message is not None and not isinstance(message, str):
68 invalid.append(("message", message, type(message)))
69 if not isinstance(affected_nodes, list):
70 invalid.append(("affectedNodes", affected_nodes, type(affected_nodes)))
71 else:
72 for index, value in enumerate(affected_nodes):
73 if not isinstance(value, str):
74 invalid.append((f"affectedNodes[{index}]", value, type(value)))
75
76 if invalid:
77 raise ValueError("Invalid RecoveryStatus values: ", invalid)
78
79 @classmethod
80 def from_dict(cls, data: dict) -> RecoveryStatus:
81 """Create a RecoveryStatus instance from a dict.
82
83 This is useful for converting JSON response data into the dataclass structure.
84 Handles empty dict {} by returning a RecoveryStatus with all None/default values.
85 The nested 'state' dict (if present) is automatically converted to
86 a RecoveryOperation instance.
87
88 Parameters:
89 data: A dict containing the recovery status data, typically
90 parsed from a JSON response. Can be an empty dict.
91
92 Returns:
93 A RecoveryStatus instance with nested dataclass objects.
94
95 Raises:
96 KeyError: If required keys are missing from the input dict.
97 TypeError: If nested 'state' cannot be unpacked into RecoveryOperation.
98 ValueError: If field validation fails in RecoveryOperation or
99 RecoveryStatus (e.g., invalid types).
100 """
101 # Handle empty dict case
102 if not data:
103 return cls()
104
105 state = None
106 if "state" in data and data["state"] is not None:
107 state = RecoveryOperation(**data["state"])
108
109 return cls(
110 state=state,
111 message=data.get("message"),
112 affectedNodes=data.get("affectedNodes", []),
113 )
114
115
116@dataclass(frozen=True)
117class NodeStatus:
118 address: str
119 nodeState: str # noqa: N815
120 term: int
121 syncStatus: dict[str, str] # noqa: N815
122 lastLogTerm: int # noqa: N815
123 lastLogIndex: int # noqa: N815
124 endpoint: str
125 recoveryStatus: RecoveryStatus | None # noqa: N815
126 topologyStatus: TopologyStatus | None # noqa: N815
127 clusterEnabled: bool | None # noqa: N815
128
129 def __post_init__(self) -> None:
130 invalid: list[tuple[str, t.Any, type]] = []
131 address = t.cast(t.Any, self.address)
132 node_state = t.cast(t.Any, self.nodeState)
133 term = t.cast(t.Any, self.term)
134 sync_status = t.cast(t.Any, self.syncStatus)
135 last_log_term = t.cast(t.Any, self.lastLogTerm)
136 last_log_index = t.cast(t.Any, self.lastLogIndex)
137 endpoint = t.cast(t.Any, self.endpoint)
138 recovery_status = t.cast(t.Any, self.recoveryStatus)
139 topology_status = t.cast(t.Any, self.topologyStatus)
140 cluster_enabled = t.cast(t.Any, self.clusterEnabled)
141
142 if not isinstance(address, str):
143 invalid.append(("address", address, type(address)))
144 if not isinstance(node_state, str):
145 invalid.append(("nodeState", node_state, type(node_state)))
146 if type(term) is not int:
147 invalid.append(("term", term, type(term)))
148 if not isinstance(sync_status, dict):
149 invalid.append(("syncStatus", sync_status, type(sync_status)))
150 else:
151 for key, value in sync_status.items():
152 if not isinstance(key, str):
153 invalid.append((f"syncStatus key '{key}'", key, type(key)))
154 if not isinstance(value, str):
155 invalid.append((f"syncStatus['{key}']", value, type(value)))
156 if type(last_log_term) is not int:
157 invalid.append(("lastLogTerm", last_log_term, type(last_log_term)))
158 if type(last_log_index) is not int:
159 invalid.append(("lastLogIndex", last_log_index, type(last_log_index)))
160 if not isinstance(endpoint, str):
161 invalid.append(("endpoint", endpoint, type(endpoint)))
162 if recovery_status is not None and not isinstance(
163 recovery_status, RecoveryStatus
164 ):
165 invalid.append(("recoveryStatus", recovery_status, type(recovery_status)))
166 if topology_status is not None and not isinstance(
167 topology_status, TopologyStatus
168 ):
169 invalid.append(("topologyStatus", topology_status, type(topology_status)))
170 if cluster_enabled is not None and type(cluster_enabled) is not bool:
171 invalid.append(("clusterEnabled", cluster_enabled, type(cluster_enabled)))
172
173 if invalid:
174 raise ValueError("Invalid NodeStatus values: ", invalid)
175
176 @classmethod
177 def from_dict(cls, data: dict) -> NodeStatus:
178 """Create a NodeStatus instance from a dict.
179
180 This is useful for converting JSON response data into the dataclass structure.
181 The nested 'recoveryStatus' and 'topologyStatus' dicts are automatically
182 converted to their respective dataclass instances.
183
184 Parameters:
185 data: A dict containing the node status data, typically
186 parsed from a JSON response.
187
188 Returns:
189 A NodeStatus instance with nested dataclass objects.
190
191 Raises:
192 KeyError: If required keys are missing from the input dict.
193 TypeError: If nested dicts cannot be unpacked into their respective
194 dataclass instances.
195 ValueError: If field validation fails in TopologyStatus, RecoveryOperation,
196 RecoveryStatus, or NodeStatus (e.g., invalid types).
197 """
198 # Handle recoveryStatus - can be empty dict or actual data
199 recovery_status = None
200 if "recoveryStatus" in data and data["recoveryStatus"]:
201 recovery_status = RecoveryStatus.from_dict(data["recoveryStatus"])
202 elif "recoveryStatus" in data:
203 # Empty dict case
204 recovery_status = RecoveryStatus.from_dict({})
205
206 # Handle topologyStatus - optional field
207 topology_status = None
208 if "topologyStatus" in data and data["topologyStatus"]:
209 topology_status = TopologyStatus(**data["topologyStatus"])
210
211 return cls(
212 address=data["address"],
213 nodeState=data["nodeState"],
214 term=data["term"],
215 syncStatus=data["syncStatus"],
216 lastLogTerm=data["lastLogTerm"],
217 lastLogIndex=data["lastLogIndex"],
218 endpoint=data["endpoint"],
219 recoveryStatus=recovery_status,
220 topologyStatus=topology_status,
221 clusterEnabled=data.get("clusterEnabled"),
222 )
223
224
225@dataclass(frozen=True)
226class ClusterRequest:
227 electionMinTimeout: int # noqa: N815
228 electionRangeTimeout: int # noqa: N815
229 heartbeatInterval: int # noqa: N815
230 messageSizeKB: int # noqa: N815
231 verificationTimeout: int # noqa: N815
232 transactionLogMaximumSizeGB: int # noqa: N815
233 batchUpdateInterval: int # noqa: N815
234 nodes: list[str]
235
236 def __post_init__(self) -> None:
237 invalid: list[tuple[str, t.Any, type]] = []
238 election_min_timeout = t.cast(t.Any, self.electionMinTimeout)
239 election_range_timeout = t.cast(t.Any, self.electionRangeTimeout)
240 heartbeat_interval = t.cast(t.Any, self.heartbeatInterval)
241 message_size_kb = t.cast(t.Any, self.messageSizeKB)
242 verification_timeout = t.cast(t.Any, self.verificationTimeout)
243 transaction_log_maximum_size_gb = t.cast(
244 t.Any, self.transactionLogMaximumSizeGB
245 )
246 batch_update_interval = t.cast(t.Any, self.batchUpdateInterval)
247 nodes = t.cast(t.Any, self.nodes)
248
249 if type(election_min_timeout) is not int:
250 invalid.append(
251 ("electionMinTimeout", election_min_timeout, type(election_min_timeout))
252 )
253 if type(election_range_timeout) is not int:
254 invalid.append(
255 (
256 "electionRangeTimeout",
257 election_range_timeout,
258 type(election_range_timeout),
259 )
260 )
261 if type(heartbeat_interval) is not int:
262 invalid.append(
263 ("heartbeatInterval", heartbeat_interval, type(heartbeat_interval))
264 )
265 if type(message_size_kb) is not int:
266 invalid.append(("messageSizeKB", message_size_kb, type(message_size_kb)))
267 if type(verification_timeout) is not int:
268 invalid.append(
269 (
270 "verificationTimeout",
271 verification_timeout,
272 type(verification_timeout),
273 )
274 )
275 if type(transaction_log_maximum_size_gb) is not int:
276 invalid.append(
277 (
278 "transactionLogMaximumSizeGB",
279 transaction_log_maximum_size_gb,
280 type(transaction_log_maximum_size_gb),
281 )
282 )
283 if type(batch_update_interval) is not int:
284 invalid.append(
285 (
286 "batchUpdateInterval",
287 batch_update_interval,
288 type(batch_update_interval),
289 )
290 )
291
292 if not isinstance(nodes, list):
293 invalid.append(("nodes", nodes, type(nodes)))
294 else:
295 for index, value in enumerate(nodes):
296 if not isinstance(value, str):
297 invalid.append((f"nodes[{index}]", value, type(value)))
298
299 if invalid:
300 raise ValueError("Invalid ClusterRequest values: ", invalid)
301
302 @classmethod
303 def from_dict(cls, data: dict) -> ClusterRequest:
304 """Create a ClusterRequest instance from a dict.
305
306 This is useful for converting JSON response data into the dataclass structure.
307
308 Parameters:
309 data: A dict containing the cluster request data, typically
310 parsed from a JSON response.
311
312 Returns:
313 A ClusterRequest instance.
314
315 Raises:
316 KeyError: If required keys are missing from the input dict.
317 TypeError: If the dict cannot be unpacked into ClusterRequest.
318 ValueError: If field validation fails in ClusterRequest
319 (e.g., invalid types for integer fields or nodes).
320 """
321 return cls(
322 electionMinTimeout=data["electionMinTimeout"],
323 electionRangeTimeout=data["electionRangeTimeout"],
324 heartbeatInterval=data["heartbeatInterval"],
325 messageSizeKB=data["messageSizeKB"],
326 verificationTimeout=data["verificationTimeout"],
327 transactionLogMaximumSizeGB=data["transactionLogMaximumSizeGB"],
328 batchUpdateInterval=data["batchUpdateInterval"],
329 nodes=data["nodes"],
330 )
331
332
333@dataclass(frozen=True)
334class SnapshotOptionsBean:
335 withRepositoryData: bool # noqa: N815
336 withSystemData: bool # noqa: N815
337 cleanDataDir: bool # noqa: N815
338 repositories: list[str] | None = None
339
340 def __post_init__(self) -> None:
341 invalid: list[tuple[str, t.Any, type]] = []
342 with_repository_data = t.cast(t.Any, self.withRepositoryData)
343 with_system_data = t.cast(t.Any, self.withSystemData)
344 clean_data_dir = t.cast(t.Any, self.cleanDataDir)
345 repositories = t.cast(t.Any, self.repositories)
346
347 if type(with_repository_data) is not bool:
348 invalid.append(
349 ("withRepositoryData", with_repository_data, type(with_repository_data))
350 )
351 if type(with_system_data) is not bool:
352 invalid.append(("withSystemData", with_system_data, type(with_system_data)))
353 if type(clean_data_dir) is not bool:
354 invalid.append(("cleanDataDir", clean_data_dir, type(clean_data_dir)))
355
356 if repositories is not None:
357 if not isinstance(repositories, list):
358 invalid.append(("repositories", repositories, type(repositories)))
359 else:
360 for index, value in enumerate(repositories):
361 if not isinstance(value, str):
362 invalid.append((f"repositories[{index}]", value, type(value)))
363
364 if invalid:
365 raise ValueError("Invalid SnapshotOptionsBean values: ", invalid)
366
367
368@dataclass(frozen=True)
369class BackupOperationBean:
370 id: str
371 username: str
372 operation: t.Literal[
373 "CREATE_BACKUP_IN_PROGRESS",
374 "RESTORE_BACKUP_IN_PROGRESS",
375 "CREATE_CLOUD_BACKUP_IN_PROGRESS",
376 "RESTORE_CLOUD_BACKUP_IN_PROGRESS",
377 ]
378 affectedRepositories: list[str] # noqa: N815
379 msSinceCreated: int # noqa: N815
380 snapshotOptions: SnapshotOptionsBean # noqa: N815
381 nodePerformingClusterBackup: str | None = None # noqa: N815
382
383 def __post_init__(self) -> None:
384 _allowed_operations = {
385 "CREATE_BACKUP_IN_PROGRESS",
386 "RESTORE_BACKUP_IN_PROGRESS",
387 "CREATE_CLOUD_BACKUP_IN_PROGRESS",
388 "RESTORE_CLOUD_BACKUP_IN_PROGRESS",
389 }
390 invalid: list[tuple[str, t.Any, type]] = []
391 id_ = t.cast(t.Any, self.id)
392 username = t.cast(t.Any, self.username)
393 operation = t.cast(t.Any, self.operation)
394 affected_repositories = t.cast(t.Any, self.affectedRepositories)
395 ms_since_created = t.cast(t.Any, self.msSinceCreated)
396 snapshot_options = t.cast(t.Any, self.snapshotOptions)
397 node_performing_cluster_backup = t.cast(t.Any, self.nodePerformingClusterBackup)
398
399 if not isinstance(id_, str):
400 invalid.append(("id", id_, type(id_)))
401 if not isinstance(username, str):
402 invalid.append(("username", username, type(username)))
403 if not isinstance(operation, str) or operation not in _allowed_operations:
404 invalid.append(("operation", operation, type(operation)))
405 if not isinstance(affected_repositories, list):
406 invalid.append(
407 (
408 "affectedRepositories",
409 affected_repositories,
410 type(affected_repositories),
411 )
412 )
413 else:
414 for index, value in enumerate(affected_repositories):
415 if not isinstance(value, str):
416 invalid.append(
417 (f"affectedRepositories[{index}]", value, type(value))
418 )
419 if type(ms_since_created) is not int:
420 invalid.append(("msSinceCreated", ms_since_created, type(ms_since_created)))
421 if not isinstance(snapshot_options, SnapshotOptionsBean):
422 invalid.append(
423 ("snapshotOptions", snapshot_options, type(snapshot_options))
424 )
425 if node_performing_cluster_backup is not None and not isinstance(
426 node_performing_cluster_backup, str
427 ):
428 invalid.append(
429 (
430 "nodePerformingClusterBackup",
431 node_performing_cluster_backup,
432 type(node_performing_cluster_backup),
433 )
434 )
435
436 if invalid:
437 raise ValueError("Invalid BackupOperationBean values: ", invalid)
438
439 @classmethod
440 def from_dict(cls, data: dict) -> BackupOperationBean:
441 """Create a BackupOperationBean instance from a dict.
442
443 This is useful for converting JSON response data into the dataclass structure.
444 The nested 'snapshotOptions' dict is automatically converted to
445 a SnapshotOptionsBean instance.
446
447 Parameters:
448 data: A dict containing the backup operation data, typically
449 parsed from a JSON response.
450
451 Returns:
452 A BackupOperationBean instance with nested dataclass objects.
453
454 Raises:
455 KeyError: If required keys are missing from the input dict.
456 TypeError: If nested 'snapshotOptions' cannot be unpacked into
457 SnapshotOptionsBean.
458 ValueError: If field validation fails in SnapshotOptionsBean or
459 BackupOperationBean (e.g., invalid types or operation values).
460 """
461 snapshot_options = SnapshotOptionsBean(**data["snapshotOptions"])
462 return cls(
463 id=data["id"],
464 username=data["username"],
465 operation=data["operation"],
466 affectedRepositories=data["affectedRepositories"],
467 msSinceCreated=data["msSinceCreated"],
468 snapshotOptions=snapshot_options,
469 nodePerformingClusterBackup=data.get("nodePerformingClusterBackup"),
470 )
471
472
473@dataclass(frozen=True)
474class StructuresStatistics:
475 cacheHit: int # noqa: N815
476 cacheMiss: int # noqa: N815
477
478 def __post_init__(self) -> None:
479 invalid: list[tuple[str, t.Any, type]] = []
480 cache_hit = t.cast(t.Any, self.cacheHit)
481 cache_miss = t.cast(t.Any, self.cacheMiss)
482
483 if type(cache_hit) is not int:
484 invalid.append(("cacheHit", cache_hit, type(cache_hit)))
485 if type(cache_miss) is not int:
486 invalid.append(("cacheMiss", cache_miss, type(cache_miss)))
487
488 if invalid:
489 raise ValueError("Invalid StructuresStatistics values: ", invalid)
490
491
492@dataclass(frozen=True)
493class RepositoryStatisticsQueries:
494 slow: int
495 suboptimal: int
496
497 def __post_init__(self) -> None:
498 invalid: list[tuple[str, t.Any, type]] = []
499 slow = t.cast(t.Any, self.slow)
500 suboptimal = t.cast(t.Any, self.suboptimal)
501
502 if type(slow) is not int:
503 invalid.append(("slow", slow, type(slow)))
504 if type(suboptimal) is not int:
505 invalid.append(("suboptimal", suboptimal, type(suboptimal)))
506
507 if invalid:
508 raise ValueError("Invalid RepositoryStatisticsQueries values: ", invalid)
509
510
511@dataclass(frozen=True)
512class RepositoryStatisticsEntityPool:
513 epoolReads: int # noqa: N815
514 epoolWrites: int # noqa: N815
515 epoolSize: int # noqa: N815
516
517 def __post_init__(self) -> None:
518 invalid: list[tuple[str, t.Any, type]] = []
519 epool_reads = t.cast(t.Any, self.epoolReads)
520 epool_writes = t.cast(t.Any, self.epoolWrites)
521 epool_size = t.cast(t.Any, self.epoolSize)
522
523 if type(epool_reads) is not int:
524 invalid.append(("epoolReads", epool_reads, type(epool_reads)))
525 if type(epool_writes) is not int:
526 invalid.append(("epoolWrites", epool_writes, type(epool_writes)))
527 if type(epool_size) is not int:
528 invalid.append(("epoolSize", epool_size, type(epool_size)))
529
530 if invalid:
531 raise ValueError("Invalid RepositoryStatisticsEntityPool values: ", invalid)
532
533
534@dataclass(frozen=True)
535class RepositoryStatistics:
536 queries: RepositoryStatisticsQueries
537 entityPool: RepositoryStatisticsEntityPool # noqa: N815
538 activeTransactions: int # noqa: N815
539 openConnections: int # noqa: N815
540
541 def __post_init__(self) -> None:
542 invalid: list[tuple[str, t.Any, type]] = []
543 queries = t.cast(t.Any, self.queries)
544 entity_pool = t.cast(t.Any, self.entityPool)
545 active_transactions = t.cast(t.Any, self.activeTransactions)
546 open_connections = t.cast(t.Any, self.openConnections)
547
548 if not isinstance(queries, RepositoryStatisticsQueries):
549 invalid.append(("queries", queries, type(queries)))
550 if not isinstance(entity_pool, RepositoryStatisticsEntityPool):
551 invalid.append(("entityPool", entity_pool, type(entity_pool)))
552 if type(active_transactions) is not int:
553 invalid.append(
554 ("activeTransactions", active_transactions, type(active_transactions))
555 )
556 if type(open_connections) is not int:
557 invalid.append(
558 ("openConnections", open_connections, type(open_connections))
559 )
560
561 if invalid:
562 raise ValueError("Invalid RepositoryStatistics values: ", invalid)
563
564 @classmethod
565 def from_dict(cls, data: dict) -> RepositoryStatistics:
566 """Create a RepositoryStatistics instance from a dict.
567
568 This is useful for converting JSON response data into the dataclass structure.
569 The nested 'queries' and 'entityPool' dicts are automatically converted to
570 their respective dataclass instances.
571
572 Parameters:
573 data: A dict containing the repository statistics data, typically
574 parsed from a JSON response.
575
576 Returns:
577 A RepositoryStatistics instance with nested dataclass objects.
578
579 Raises:
580 KeyError: If required keys are missing from the input dict.
581 TypeError: If nested dicts cannot be unpacked into their respective
582 dataclass instances.
583 ValueError: If field validation fails in RepositoryStatisticsQueries,
584 RepositoryStatisticsEntityPool, or RepositoryStatistics
585 (e.g., invalid types).
586 """
587 queries = RepositoryStatisticsQueries(**data["queries"])
588 entity_pool = RepositoryStatisticsEntityPool(**data["entityPool"])
589 return cls(
590 queries=queries,
591 entityPool=entity_pool,
592 activeTransactions=data["activeTransactions"],
593 openConnections=data["openConnections"],
594 )
595
596
597@dataclass(frozen=True)
598class InfrastructureMemoryUsage:
599 max: int
600 committed: int
601 init: int
602 used: int
603
604 def __post_init__(self) -> None:
605 invalid: list[tuple[str, t.Any, type]] = []
606 max_val = t.cast(t.Any, self.max)
607 committed = t.cast(t.Any, self.committed)
608 init = t.cast(t.Any, self.init)
609 used = t.cast(t.Any, self.used)
610
611 if type(max_val) is not int:
612 invalid.append(("max", max_val, type(max_val)))
613 if type(committed) is not int:
614 invalid.append(("committed", committed, type(committed)))
615 if type(init) is not int:
616 invalid.append(("init", init, type(init)))
617 if type(used) is not int:
618 invalid.append(("used", used, type(used)))
619
620 if invalid:
621 raise ValueError("Invalid InfrastructureMemoryUsage values: ", invalid)
622
623
624@dataclass(frozen=True)
625class InfrastructureStorageMemory:
626 dataDirUsed: int # noqa: N815
627 workDirUsed: int # noqa: N815
628 logsDirUsed: int # noqa: N815
629 dataDirFree: int # noqa: N815
630 workDirFree: int # noqa: N815
631 logsDirFree: int # noqa: N815
632
633 def __post_init__(self) -> None:
634 invalid: list[tuple[str, t.Any, type]] = []
635 data_dir_used = t.cast(t.Any, self.dataDirUsed)
636 work_dir_used = t.cast(t.Any, self.workDirUsed)
637 logs_dir_used = t.cast(t.Any, self.logsDirUsed)
638 data_dir_free = t.cast(t.Any, self.dataDirFree)
639 work_dir_free = t.cast(t.Any, self.workDirFree)
640 logs_dir_free = t.cast(t.Any, self.logsDirFree)
641
642 if type(data_dir_used) is not int:
643 invalid.append(("dataDirUsed", data_dir_used, type(data_dir_used)))
644 if type(work_dir_used) is not int:
645 invalid.append(("workDirUsed", work_dir_used, type(work_dir_used)))
646 if type(logs_dir_used) is not int:
647 invalid.append(("logsDirUsed", logs_dir_used, type(logs_dir_used)))
648 if type(data_dir_free) is not int:
649 invalid.append(("dataDirFree", data_dir_free, type(data_dir_free)))
650 if type(work_dir_free) is not int:
651 invalid.append(("workDirFree", work_dir_free, type(work_dir_free)))
652 if type(logs_dir_free) is not int:
653 invalid.append(("logsDirFree", logs_dir_free, type(logs_dir_free)))
654
655 if invalid:
656 raise ValueError("Invalid InfrastructureStorageMemory values: ", invalid)
657
658
659@dataclass(frozen=True)
660class InfrastructureStatistics:
661 heapMemoryUsage: InfrastructureMemoryUsage # noqa: N815
662 nonHeapMemoryUsage: InfrastructureMemoryUsage # noqa: N815
663 storageMemory: InfrastructureStorageMemory # noqa: N815
664 threadCount: int # noqa: N815
665 cpuLoad: float # noqa: N815
666 classCount: int # noqa: N815
667 gcCount: int # noqa: N815
668 openFileDescriptors: int # noqa: N815
669 maxFileDescriptors: int # noqa: N815
670
671 def __post_init__(self) -> None:
672 invalid: list[tuple[str, t.Any, type]] = []
673 heap_memory_usage = t.cast(t.Any, self.heapMemoryUsage)
674 non_heap_memory_usage = t.cast(t.Any, self.nonHeapMemoryUsage)
675 storage_memory = t.cast(t.Any, self.storageMemory)
676 thread_count = t.cast(t.Any, self.threadCount)
677 cpu_load = t.cast(t.Any, self.cpuLoad)
678 class_count = t.cast(t.Any, self.classCount)
679 gc_count = t.cast(t.Any, self.gcCount)
680 open_file_descriptors = t.cast(t.Any, self.openFileDescriptors)
681 max_file_descriptors = t.cast(t.Any, self.maxFileDescriptors)
682
683 if not isinstance(heap_memory_usage, InfrastructureMemoryUsage):
684 invalid.append(
685 ("heapMemoryUsage", heap_memory_usage, type(heap_memory_usage))
686 )
687 if not isinstance(non_heap_memory_usage, InfrastructureMemoryUsage):
688 invalid.append(
689 (
690 "nonHeapMemoryUsage",
691 non_heap_memory_usage,
692 type(non_heap_memory_usage),
693 )
694 )
695 if not isinstance(storage_memory, InfrastructureStorageMemory):
696 invalid.append(("storageMemory", storage_memory, type(storage_memory)))
697 if type(thread_count) is not int:
698 invalid.append(("threadCount", thread_count, type(thread_count)))
699 if type(cpu_load) is not float and type(cpu_load) is not int:
700 invalid.append(("cpuLoad", cpu_load, type(cpu_load)))
701 if type(class_count) is not int:
702 invalid.append(("classCount", class_count, type(class_count)))
703 if type(gc_count) is not int:
704 invalid.append(("gcCount", gc_count, type(gc_count)))
705 if type(open_file_descriptors) is not int:
706 invalid.append(
707 (
708 "openFileDescriptors",
709 open_file_descriptors,
710 type(open_file_descriptors),
711 )
712 )
713 if type(max_file_descriptors) is not int:
714 invalid.append(
715 ("maxFileDescriptors", max_file_descriptors, type(max_file_descriptors))
716 )
717
718 if invalid:
719 raise ValueError("Invalid InfrastructureStatistics values: ", invalid)
720
721 @classmethod
722 def from_dict(cls, data: dict) -> InfrastructureStatistics:
723 """Create an InfrastructureStatistics instance from a dict.
724
725 This is useful for converting JSON response data into the dataclass structure.
726 The nested memory and storage dicts are automatically converted to their
727 respective dataclass instances.
728
729 Parameters:
730 data: A dict containing the infrastructure statistics data, typically
731 parsed from a JSON response.
732
733 Returns:
734 An InfrastructureStatistics instance with nested dataclass objects.
735
736 Raises:
737 KeyError: If required keys are missing from the input dict.
738 TypeError: If nested dicts cannot be unpacked into their respective
739 dataclass instances.
740 ValueError: If field validation fails in InfrastructureMemoryUsage,
741 InfrastructureStorageMemory, or InfrastructureStatistics
742 (e.g., invalid types).
743 """
744 heap_memory_usage = InfrastructureMemoryUsage(**data["heapMemoryUsage"])
745 non_heap_memory_usage = InfrastructureMemoryUsage(**data["nonHeapMemoryUsage"])
746 storage_memory = InfrastructureStorageMemory(**data["storageMemory"])
747 return cls(
748 heapMemoryUsage=heap_memory_usage,
749 nonHeapMemoryUsage=non_heap_memory_usage,
750 storageMemory=storage_memory,
751 threadCount=data["threadCount"],
752 cpuLoad=float(data["cpuLoad"]),
753 classCount=data["classCount"],
754 gcCount=data["gcCount"],
755 openFileDescriptors=data["openFileDescriptors"],
756 maxFileDescriptors=data["maxFileDescriptors"],
757 )
758
759
760@dataclass(frozen=True)
761class ParserSettings:
762 preserveBNodeIds: bool = False # noqa: N815
763 failOnUnknownDataTypes: bool = False # noqa: N815
764 verifyDataTypeValues: bool = False # noqa: N815
765 normalizeDataTypeValues: bool = False # noqa: N815
766 failOnUnknownLanguageTags: bool = False # noqa: N815
767 verifyLanguageTags: bool = True # noqa: N815
768 normalizeLanguageTags: bool = False # noqa: N815
769 stopOnError: bool = True # noqa: N815
770 contextLink: t.Any | None = None # noqa: N815
771
772 def __post_init__(self) -> None:
773 invalid: list[tuple[str, t.Any, type]] = []
774 preserve_bnode_ids = t.cast(t.Any, self.preserveBNodeIds)
775 fail_on_unknown_data_types = t.cast(t.Any, self.failOnUnknownDataTypes)
776 verify_data_type_values = t.cast(t.Any, self.verifyDataTypeValues)
777 normalize_data_type_values = t.cast(t.Any, self.normalizeDataTypeValues)
778 fail_on_unknown_language_tags = t.cast(t.Any, self.failOnUnknownLanguageTags)
779 verify_language_tags = t.cast(t.Any, self.verifyLanguageTags)
780 normalize_language_tags = t.cast(t.Any, self.normalizeLanguageTags)
781 stop_on_error = t.cast(t.Any, self.stopOnError)
782
783 if type(preserve_bnode_ids) is not bool:
784 invalid.append(
785 ("preserveBNodeIds", preserve_bnode_ids, type(preserve_bnode_ids))
786 )
787 if type(fail_on_unknown_data_types) is not bool:
788 invalid.append(
789 (
790 "failOnUnknownDataTypes",
791 fail_on_unknown_data_types,
792 type(fail_on_unknown_data_types),
793 )
794 )
795 if type(verify_data_type_values) is not bool:
796 invalid.append(
797 (
798 "verifyDataTypeValues",
799 verify_data_type_values,
800 type(verify_data_type_values),
801 )
802 )
803 if type(normalize_data_type_values) is not bool:
804 invalid.append(
805 (
806 "normalizeDataTypeValues",
807 normalize_data_type_values,
808 type(normalize_data_type_values),
809 )
810 )
811 if type(fail_on_unknown_language_tags) is not bool:
812 invalid.append(
813 (
814 "failOnUnknownLanguageTags",
815 fail_on_unknown_language_tags,
816 type(fail_on_unknown_language_tags),
817 )
818 )
819 if type(verify_language_tags) is not bool:
820 invalid.append(
821 ("verifyLanguageTags", verify_language_tags, type(verify_language_tags))
822 )
823 if type(normalize_language_tags) is not bool:
824 invalid.append(
825 (
826 "normalizeLanguageTags",
827 normalize_language_tags,
828 type(normalize_language_tags),
829 )
830 )
831 if type(stop_on_error) is not bool:
832 invalid.append(("stopOnError", stop_on_error, type(stop_on_error)))
833
834 # Note: don't check contextLink here since it's of type t.Any.
835
836 if invalid:
837 raise ValueError("Invalid ParserSettings values: ", invalid)
838
839 def as_dict(self) -> dict[str, t.Any]:
840 return asdict(self)
841
842
843@dataclass(frozen=True)
844class ImportSettings:
845 name: str
846 status: t.Literal["PENDING", "IMPORTING", "DONE", "ERROR", "NONE", "INTERRUPTING"]
847 size: str
848 lastModified: int # noqa: N815
849 imported: int
850 addedStatements: int # noqa: N815
851 removedStatements: int # noqa: N815
852 numReplacedGraphs: int # noqa: N815
853 message: str = ""
854 context: t.Any | None = None
855 replaceGraphs: t.List = field(default_factory=list) # noqa: N815
856 baseURI: t.Any | None = None # noqa: N815
857 forceSerial: bool = False # noqa: N815
858 type: str = "file"
859 format: t.Any | None = None
860 data: t.Any | None = None
861 parserSettings: ParserSettings = field(default_factory=ParserSettings) # noqa: N815
862
863 def __post_init__(self) -> None:
864 _allowed_status = {
865 "PENDING",
866 "IMPORTING",
867 "DONE",
868 "ERROR",
869 "NONE",
870 "INTERRUPTING",
871 }
872 invalid: list[tuple[str, t.Any, type]] = []
873
874 name = t.cast(t.Any, self.name)
875 status = t.cast(t.Any, self.status)
876 message = t.cast(t.Any, self.message)
877 replace_graphs = t.cast(t.Any, self.replaceGraphs)
878 force_serial = t.cast(t.Any, self.forceSerial)
879 type_ = t.cast(t.Any, self.type)
880 parser_settings = t.cast(t.Any, self.parserSettings)
881 size = t.cast(t.Any, self.size)
882 last_modified = t.cast(t.Any, self.lastModified)
883 imported = t.cast(t.Any, self.imported)
884 added_statements = t.cast(t.Any, self.addedStatements)
885 removed_statements = t.cast(t.Any, self.removedStatements)
886 num_replaced_graphs = t.cast(t.Any, self.numReplacedGraphs)
887
888 if not isinstance(name, str):
889 invalid.append(("name", name, type(name)))
890 if status not in _allowed_status:
891 invalid.append(("status", status, type(status)))
892 if not isinstance(message, str):
893 invalid.append(("message", message, type(message)))
894 if not isinstance(replace_graphs, list):
895 invalid.append(("replaceGraphs", replace_graphs, type(replace_graphs)))
896 if type(force_serial) is not bool:
897 invalid.append(("forceSerial", force_serial, type(force_serial)))
898 if not isinstance(type_, str):
899 invalid.append(("type", type_, type(type_)))
900 if not isinstance(parser_settings, ParserSettings):
901 invalid.append(("parserSettings", parser_settings, type(parser_settings)))
902 if not isinstance(size, str):
903 invalid.append(("size", size, type(size)))
904 if type(last_modified) is not int:
905 invalid.append(("lastModified", last_modified, type(last_modified)))
906 if type(imported) is not int:
907 invalid.append(("imported", imported, type(imported)))
908 if type(added_statements) is not int:
909 invalid.append(
910 ("addedStatements", added_statements, type(added_statements))
911 )
912 if type(removed_statements) is not int:
913 invalid.append(
914 ("removedStatements", removed_statements, type(removed_statements))
915 )
916 if type(num_replaced_graphs) is not int:
917 invalid.append(
918 ("numReplacedGraphs", num_replaced_graphs, type(num_replaced_graphs))
919 )
920
921 # Note: don't check context, baseURI, format, or data here since they are of type t.Any.
922
923 if invalid:
924 raise ValueError("Invalid ImportSettings values: ", invalid)
925
926 def as_dict(self) -> dict[str, t.Any]:
927 return asdict(self)
928
929
930@dataclass(frozen=True)
931class ServerImportBody:
932 fileNames: list[str] # noqa: N815
933 importSettings: ImportSettings | None = None # noqa: N815
934
935 def __post_init__(self) -> None:
936 invalid: list[tuple[str, t.Any, type]] = []
937 import_settings = t.cast(t.Any, self.importSettings)
938 file_names = t.cast(t.Any, self.fileNames)
939
940 if import_settings is not None and not isinstance(
941 import_settings, ImportSettings
942 ):
943 invalid.append(("importSettings", import_settings, type(import_settings)))
944 if not isinstance(file_names, list):
945 invalid.append(("fileNames", file_names, type(file_names)))
946 else:
947 for index, value in enumerate(file_names):
948 if not isinstance(value, str):
949 invalid.append((f"fileNames[{index}]", value, type(value)))
950
951 if invalid:
952 raise ValueError("Invalid ServerImportBody values: ", invalid)
953
954 def as_dict(self) -> dict[str, t.Any]:
955 result = asdict(self)
956 if self.importSettings is None:
957 result.pop("importSettings", None)
958 return result
959
960
961@dataclass(frozen=True)
962class UserUpdate:
963 password: str = field(default="")
964 appSettings: dict[str, t.Any] = field(default_factory=dict) # noqa: N815
965 gptThreads: list[t.Any] = field(default_factory=list) # noqa: N815
966
967 def as_dict(self) -> dict[str, t.Any]:
968 return asdict(self)
969
970
971@dataclass(frozen=True)
972class UserCreate:
973 """Dataclass for creating a new user in GraphDB.
974
975 Unlike `User`, this class does not include `dateCreated` since
976 GraphDB automatically assigns this value when the user is created.
977 """
978
979 username: str
980 password: str
981 grantedAuthorities: list[str] = field(default_factory=list) # noqa: N815
982 appSettings: dict[str, t.Any] = field(default_factory=dict) # noqa: N815
983 gptThreads: list[t.Any] = field(default_factory=list) # noqa: N815
984
985 def __post_init__(self) -> None:
986 invalid: list[tuple[str, t.Any, type]] = []
987 username = t.cast(t.Any, self.username)
988 password = t.cast(t.Any, self.password)
989 granted_authorities = t.cast(t.Any, self.grantedAuthorities)
990 app_settings = t.cast(t.Any, self.appSettings)
991 gpt_threads = t.cast(t.Any, self.gptThreads)
992
993 if not isinstance(username, str):
994 invalid.append(("username", username, type(username)))
995 if not isinstance(password, str):
996 invalid.append(("password", password, type(password)))
997
998 if not isinstance(granted_authorities, list):
999 invalid.append(
1000 ("grantedAuthorities", granted_authorities, type(granted_authorities))
1001 )
1002 else:
1003 for index, value in enumerate(granted_authorities):
1004 if not isinstance(value, str):
1005 invalid.append((f"grantedAuthorities[{index}]", value, type(value)))
1006
1007 if not isinstance(app_settings, dict):
1008 invalid.append(("appSettings", app_settings, type(app_settings)))
1009 else:
1010 for key in app_settings.keys():
1011 if not isinstance(key, str):
1012 invalid.append(("appSettings key", key, type(key)))
1013 break
1014
1015 if not isinstance(gpt_threads, list):
1016 invalid.append(("gptThreads", gpt_threads, type(gpt_threads)))
1017
1018 if invalid:
1019 raise ValueError("Invalid UserCreate values: ", invalid)
1020
1021 def as_dict(self) -> dict[str, t.Any]:
1022 return asdict(self)
1023
1024
1025@dataclass(frozen=True)
1026class User:
1027 username: str
1028 password: str
1029 dateCreated: int # noqa: N815
1030 grantedAuthorities: list[str] = field(default_factory=list) # noqa: N815
1031 appSettings: dict[str, t.Any] = field(default_factory=dict) # noqa: N815
1032 gptThreads: list[t.Any] = field(default_factory=list) # noqa: N815
1033
1034 def __post_init__(self) -> None:
1035 # Normalize None values from API responses to empty collections
1036 if self.grantedAuthorities is None:
1037 object.__setattr__(self, "grantedAuthorities", []) # type: ignore[unreachable]
1038 if self.appSettings is None:
1039 object.__setattr__(self, "appSettings", {}) # type: ignore[unreachable]
1040 if self.gptThreads is None:
1041 object.__setattr__(self, "gptThreads", []) # type: ignore[unreachable]
1042
1043 invalid: list[tuple[str, t.Any, type]] = []
1044 username = t.cast(t.Any, self.username)
1045 password = t.cast(t.Any, self.password)
1046 date_created = t.cast(t.Any, self.dateCreated)
1047 granted_authorities = t.cast(t.Any, self.grantedAuthorities)
1048 app_settings = t.cast(t.Any, self.appSettings)
1049 gpt_threads = t.cast(t.Any, self.gptThreads)
1050
1051 if not isinstance(username, str):
1052 invalid.append(("username", username, type(username)))
1053 if not isinstance(password, str):
1054 invalid.append(("password", password, type(password)))
1055 if not isinstance(date_created, int):
1056 invalid.append(("dateCreated", date_created, type(date_created)))
1057
1058 if not isinstance(granted_authorities, list):
1059 invalid.append(
1060 ("grantedAuthorities", granted_authorities, type(granted_authorities))
1061 )
1062 else:
1063 for index, value in enumerate(granted_authorities):
1064 if not isinstance(value, str):
1065 invalid.append((f"grantedAuthorities[{index}]", value, type(value)))
1066
1067 if not isinstance(app_settings, dict):
1068 invalid.append(("appSettings", app_settings, type(app_settings)))
1069 else:
1070 for key in app_settings.keys():
1071 if not isinstance(key, str):
1072 invalid.append(("appSettings key", key, type(key)))
1073 break
1074
1075 if not isinstance(gpt_threads, list):
1076 invalid.append(("gptThreads", gpt_threads, type(gpt_threads)))
1077
1078 if invalid:
1079 raise ValueError("Invalid User values: ", invalid)
1080
1081 def as_dict(self):
1082 return asdict(self)
1083
1084
1085@dataclass(frozen=True)
1086class AuthenticatedUser:
1087 """Represents an authenticated user returned from POST /rest/login.
1088
1089 Attributes:
1090 username: The username of the authenticated user.
1091 authorities: List of granted authorities/roles (e.g., ["ROLE_USER", "ROLE_ADMIN"]).
1092 appSettings: Application settings for the user.
1093 external: Whether the user is external (e.g., from LDAP/OAuth).
1094 token: The full Authorization header value (e.g., "GDB <token>").
1095 Can be passed directly to GraphDBClient's auth parameter.
1096 """
1097
1098 username: str
1099 authorities: list[str] = field(default_factory=list)
1100 appSettings: dict[str, t.Any] = field(default_factory=dict) # noqa: N815
1101 external: bool = False
1102 token: str = ""
1103
1104 def __post_init__(self) -> None:
1105 # Normalize None values from API responses to empty collections
1106 if self.authorities is None:
1107 object.__setattr__(self, "authorities", []) # type: ignore[unreachable]
1108 if self.appSettings is None:
1109 object.__setattr__(self, "appSettings", {}) # type: ignore[unreachable]
1110
1111 invalid: list[tuple[str, t.Any, type]] = []
1112 username = t.cast(t.Any, self.username)
1113 authorities = t.cast(t.Any, self.authorities)
1114 app_settings = t.cast(t.Any, self.appSettings)
1115 external = t.cast(t.Any, self.external)
1116 token = t.cast(t.Any, self.token)
1117
1118 if not isinstance(username, str):
1119 invalid.append(("username", username, type(username)))
1120 if not isinstance(authorities, list):
1121 invalid.append(("authorities", authorities, type(authorities)))
1122 else:
1123 for index, value in enumerate(authorities):
1124 if not isinstance(value, str):
1125 invalid.append((f"authorities[{index}]", value, type(value)))
1126 if not isinstance(app_settings, dict):
1127 invalid.append(("appSettings", app_settings, type(app_settings)))
1128 else:
1129 for key in app_settings.keys():
1130 if not isinstance(key, str):
1131 invalid.append(("appSettings key", key, type(key)))
1132 break
1133 if type(external) is not bool:
1134 invalid.append(("external", external, type(external)))
1135 if not isinstance(token, str):
1136 invalid.append(("token", token, type(token)))
1137
1138 if invalid:
1139 raise ValueError("Invalid AuthenticatedUser values: ", invalid)
1140
1141 @classmethod
1142 def from_response(cls, data: dict[str, t.Any], token: str) -> AuthenticatedUser:
1143 """Create an AuthenticatedUser from API response data and token.
1144
1145 Parameters:
1146 data: The JSON response body from POST /rest/login.
1147 token: The GDB token extracted from the Authorization header.
1148
1149 Returns:
1150 An AuthenticatedUser instance.
1151
1152 Raises:
1153 ValueError: If required fields are missing or invalid.
1154 TypeError: If data is not a dict.
1155 """
1156 if not isinstance(data, dict):
1157 raise TypeError("Response data must be a dict")
1158 if "username" not in data:
1159 raise ValueError("Response data must contain 'username'")
1160
1161 return cls(
1162 username=data["username"],
1163 authorities=data.get("authorities", []),
1164 appSettings=data.get("appSettings", {}),
1165 external=data.get("external", False),
1166 token=token,
1167 )
1168
1169
1170@dataclass(frozen=True)
1171class FreeAccessSettings:
1172 enabled: bool
1173 authorities: list[str] = field(default_factory=list)
1174 appSettings: dict[str, t.Any] = field(default_factory=dict) # noqa: N815
1175
1176 def __post_init__(self) -> None:
1177 invalid: list[tuple[str, t.Any, type]] = []
1178 enabled = t.cast(t.Any, self.enabled)
1179 authorities = t.cast(t.Any, self.authorities)
1180 app_settings = t.cast(t.Any, self.appSettings)
1181 if type(enabled) is not bool:
1182 invalid.append(("enabled", enabled, type(enabled)))
1183 if not isinstance(authorities, list):
1184 invalid.append(("authorities", authorities, type(authorities)))
1185 else:
1186 for index, value in enumerate(authorities):
1187 if not isinstance(value, str):
1188 invalid.append((f"authorities[{index}]", value, type(value)))
1189 if not isinstance(app_settings, dict):
1190 invalid.append(("appSettings", app_settings, type(app_settings)))
1191 else:
1192 for key in app_settings.keys():
1193 if not isinstance(key, str):
1194 invalid.append(("appSettings key", key, type(key)))
1195 break
1196
1197 if invalid:
1198 raise ValueError("Invalid FreeAccessSettings values: ", invalid)
1199
1200 def as_dict(self):
1201 return asdict(self)
1202
1203
1204@dataclass(frozen=True)
1205class RepositorySizeInfo:
1206 inferred: int
1207 total: int
1208 explicit: int
1209
1210 def __post_init__(self):
1211 invalid = []
1212 if type(self.inferred) is not int:
1213 invalid.append("inferred")
1214 if type(self.total) is not int:
1215 invalid.append("total")
1216 if type(self.explicit) is not int:
1217 invalid.append("explicit")
1218
1219 if invalid:
1220 raise ValueError(
1221 "Invalid RepositorySizeInfo values: ",
1222 [(x, self.__dict__[x], type(self.__dict__[x])) for x in invalid],
1223 )
1224
1225
1226@dataclass(frozen=True)
1227class OWLimParameter:
1228 name: str
1229 label: str
1230 value: str
1231
1232
1233@dataclass(frozen=True)
1234class RepositoryConfigBean:
1235 id: str
1236 title: str
1237 type: str
1238 sesameType: str # noqa: N815
1239 location: str
1240 params: dict[str, OWLimParameter] = field(default_factory=dict)
1241
1242
1243@dataclass(frozen=True)
1244class RepositoryConfigBeanCreate:
1245 id: str
1246 title: str
1247 type: str
1248 sesameType: str # noqa: N815
1249 location: str
1250 params: dict[str, OWLimParameter] = field(default_factory=dict)
1251 missingDefaults: dict[str, OWLimParameter] = field( # noqa: N815
1252 default_factory=dict
1253 )
1254
1255 def as_dict(self) -> dict:
1256 """Serialize the dataclass to a Python dict.
1257
1258 Returns:
1259 dict: A dictionary representation of the dataclass suitable for use
1260 with httpx POST requests (e.g., via the `json` parameter).
1261
1262 Examples:
1263 >>> config = RepositoryConfigBeanCreate(
1264 ... id="test-repo",
1265 ... title="Test Repository",
1266 ... type="graphdb:FreeSailRepository",
1267 ... sesameType="graphdb:FreeSailRepository",
1268 ... location="",
1269 ... )
1270 >>> config_dict = config.as_dict()
1271 >>> isinstance(config_dict, dict)
1272 True
1273 """
1274 return asdict(self)
1275
1276
1277class RepositoryState(str, Enum):
1278 """Enumeration for repository state values."""
1279
1280 INACTIVE = "INACTIVE"
1281 STARTING = "STARTING"
1282 RUNNING = "RUNNING"
1283 RESTARTING = "RESTARTING"
1284 STOPPING = "STOPPING"
1285
1286
1287@dataclass
1288class GraphDBRepository:
1289 id: t.Optional[str] = None
1290 title: t.Optional[str] = None
1291 uri: t.Optional[str] = None
1292 externalUrl: t.Optional[str] = None # noqa: N815
1293 local: t.Optional[bool] = None
1294 type: t.Optional[str] = None
1295 sesameType: t.Optional[str] = None # noqa: N815
1296 location: t.Optional[str] = None
1297 readable: t.Optional[bool] = None
1298 writable: t.Optional[bool] = None
1299 unsupported: t.Optional[bool] = None
1300 state: t.Optional[RepositoryState] = None
1301
1302 @classmethod
1303 def from_dict(cls, data: dict) -> GraphDBRepository:
1304 """Create a GraphDBRepository instance from a dict.
1305
1306 Parameters:
1307 data: A dict containing the repository data, typically
1308 parsed from a JSON response.
1309
1310 Returns:
1311 A GraphDBRepository instance.
1312
1313 Raises:
1314 TypeError: If the dict contains keys that do not match
1315 GraphDBRepository fields.
1316 ValueError: If the 'state' value is not a valid RepositoryState.
1317 """
1318 data_copy = dict(data)
1319 if "state" in data_copy and data_copy["state"] is not None:
1320 data_copy["state"] = RepositoryState(data_copy["state"])
1321 return cls(**data_copy)
1322
1323
1324@dataclass
1325class AccessControlEntry:
1326 scope: t.Literal["statement", "clear_graph", "plugin", "system"]
1327 policy: t.Literal["allow", "deny", "abstain"]
1328 role: str
1329
1330 def as_dict(self) -> dict[str, t.Any]:
1331 raise NotImplementedError("Use a concrete AccessControlEntry subclass.")
1332
1333 @classmethod
1334 def from_dict(
1335 cls, data: dict
1336 ) -> (
1337 SystemAccessControlEntry
1338 | StatementAccessControlEntry
1339 | PluginAccessControlEntry
1340 | ClearGraphAccessControlEntry
1341 ):
1342 """Create an AccessControlEntry subclass instance from raw GraphDB data.
1343
1344 Note: we perform parse validation essentially twice (here and in the
1345 subclass's __post_init__) to ensure mypy is satisfied with the value's type.
1346
1347 Parameters:
1348 data: A dict containing the access control entry data, typically
1349 parsed from a JSON response.
1350
1351 Returns:
1352 An AccessControlEntry subclass instance (SystemAccessControlEntry,
1353 StatementAccessControlEntry, PluginAccessControlEntry, or
1354 ClearGraphAccessControlEntry) depending on the 'scope' field.
1355
1356 Raises:
1357 TypeError: If data is not a dict.
1358 ValueError: If 'scope' is not a supported value ('system', 'statement',
1359 'plugin', 'clear_graph'), or if any field fails validation
1360 (e.g., invalid policy, operation, role, plugin, subject,
1361 predicate, object, or graph values).
1362 """
1363 if not isinstance(data, dict):
1364 raise TypeError("ACL entry must be a mapping.")
1365
1366 scope = data.get("scope")
1367 if scope == "system":
1368 policy = _parse_policy(data.get("policy"))
1369 role = _parse_role(data.get("role"))
1370 operation = _parse_operation(data.get("operation"))
1371 return SystemAccessControlEntry(
1372 scope="system",
1373 policy=policy,
1374 role=role,
1375 operation=operation,
1376 )
1377 if scope == "statement":
1378 policy = _parse_policy(data.get("policy"))
1379 role = _parse_role(data.get("role"))
1380 operation = _parse_operation(data.get("operation"))
1381 subject = _parse_subject(data.get("subject"))
1382 predicate = _parse_predicate(data.get("predicate"))
1383 obj = _parse_object(data.get("object"))
1384 graph = _parse_graph(data.get("context"))
1385 return StatementAccessControlEntry(
1386 scope="statement",
1387 policy=policy,
1388 role=role,
1389 operation=operation,
1390 subject=subject,
1391 predicate=predicate,
1392 object=obj,
1393 graph=graph,
1394 )
1395 if scope == "plugin":
1396 policy = _parse_policy(data.get("policy"))
1397 role = _parse_role(data.get("role"))
1398 operation = _parse_operation(data.get("operation"))
1399 plugin = _parse_plugin(data.get("plugin"))
1400 return PluginAccessControlEntry(
1401 scope="plugin",
1402 policy=policy,
1403 role=role,
1404 operation=operation,
1405 plugin=plugin,
1406 )
1407 if scope == "clear_graph":
1408 policy = _parse_policy(data.get("policy"))
1409 role = _parse_role(data.get("role"))
1410 graph = _parse_graph(data.get("context"))
1411 return ClearGraphAccessControlEntry(
1412 scope="clear_graph",
1413 policy=policy,
1414 role=role,
1415 graph=graph,
1416 )
1417
1418 raise ValueError(f"Unsupported FGAC scope: {scope!r}")
1419
1420
1421@dataclass
1422class SystemAccessControlEntry(AccessControlEntry):
1423 scope: t.Literal["system"]
1424 policy: t.Literal["allow", "deny", "abstain"]
1425 role: str
1426 operation: t.Literal["read", "write", "*"]
1427
1428 def __post_init__(self) -> None:
1429 self.policy = _parse_policy(self.policy)
1430 self.role = _parse_role(self.role)
1431 self.operation = _parse_operation(self.operation)
1432
1433 def as_dict(self) -> dict[str, t.Any]:
1434 return {
1435 "scope": self.scope,
1436 "policy": self.policy,
1437 "role": self.role,
1438 "operation": self.operation,
1439 }
1440
1441
1442@dataclass
1443class StatementAccessControlEntry(AccessControlEntry):
1444 scope: t.Literal["statement"]
1445 policy: t.Literal["allow", "deny", "abstain"]
1446 role: str
1447 operation: t.Literal["read", "write", "*"]
1448 subject: t.Literal["*"] | URIRef
1449 predicate: t.Literal["*"] | URIRef
1450 object: t.Literal["*"] | URIRef | Literal
1451 graph: t.Literal["*", "named", "default"] | URIRef
1452
1453 def __post_init__(self) -> None:
1454 self.policy = _parse_policy(self.policy)
1455 self.role = _parse_role(self.role)
1456 self.operation = _parse_operation(self.operation)
1457 self.subject = _parse_subject(self.subject)
1458 self.predicate = _parse_predicate(self.predicate)
1459 self.object = _parse_object(self.object)
1460 self.graph = _parse_graph(self.graph)
1461
1462 def as_dict(self) -> dict[str, t.Any]:
1463 return {
1464 "scope": self.scope,
1465 "policy": self.policy,
1466 "role": self.role,
1467 "operation": self.operation,
1468 "subject": _format_term(self.subject),
1469 "predicate": _format_term(self.predicate),
1470 "object": _format_term(self.object),
1471 "context": _format_term(self.graph),
1472 }
1473
1474
1475@dataclass
1476class PluginAccessControlEntry(AccessControlEntry):
1477 scope: t.Literal["plugin"]
1478 policy: t.Literal["allow", "deny", "abstain"]
1479 role: str
1480 operation: t.Literal["read", "write", "*"]
1481 plugin: str
1482
1483 def __post_init__(self) -> None:
1484 self.policy = _parse_policy(self.policy)
1485 self.role = _parse_role(self.role)
1486 self.operation = _parse_operation(self.operation)
1487 self.plugin = _parse_plugin(self.plugin)
1488
1489 def as_dict(self) -> dict[str, t.Any]:
1490 return {
1491 "scope": self.scope,
1492 "policy": self.policy,
1493 "role": self.role,
1494 "operation": self.operation,
1495 "plugin": self.plugin,
1496 }
1497
1498
1499@dataclass
1500class ClearGraphAccessControlEntry(AccessControlEntry):
1501 scope: t.Literal["clear_graph"]
1502 policy: t.Literal["allow", "deny", "abstain"]
1503 role: str
1504 graph: t.Literal["*", "named", "default"] | URIRef
1505
1506 def __post_init__(self) -> None:
1507 self.policy = _parse_policy(self.policy)
1508 self.role = _parse_role(self.role)
1509 self.graph = _parse_graph(self.graph)
1510
1511 def as_dict(self) -> dict[str, t.Any]:
1512 return {
1513 "scope": self.scope,
1514 "policy": self.policy,
1515 "role": self.role,
1516 "context": _format_term(self.graph),
1517 }
1518
1519
1520_ALLOWED_POLICIES = {"allow", "deny", "abstain"}
1521_ALLOWED_OPERATIONS = {"read", "write", "*"}
1522_ALLOWED_GRAPHS = {"*", "named", "default"}
1523
1524
1525def _parse_policy(policy: t.Any) -> t.Literal["allow", "deny", "abstain"]:
1526 if policy not in _ALLOWED_POLICIES:
1527 raise ValueError(f"Invalid FGAC policy: {policy!r}")
1528 return t.cast(t.Literal["allow", "deny", "abstain"], policy)
1529
1530
1531def _parse_operation(operation: t.Any) -> t.Literal["read", "write", "*"]:
1532 if operation not in _ALLOWED_OPERATIONS:
1533 raise ValueError(f"Invalid FGAC operation: {operation!r}")
1534 return t.cast(t.Literal["read", "write", "*"], operation)
1535
1536
1537def _parse_role(role: t.Any) -> str:
1538 if not isinstance(role, str):
1539 raise ValueError(f"Invalid FGAC role: {role!r}")
1540 return role
1541
1542
1543def _parse_plugin(plugin: t.Any) -> str:
1544 if not isinstance(plugin, str):
1545 raise ValueError(f"Invalid FGAC plugin: {plugin!r}")
1546 return plugin
1547
1548
1549def _parse_subject(subject: t.Any) -> t.Literal["*"] | URIRef:
1550 if subject == "*":
1551 return "*"
1552 if isinstance(subject, URIRef):
1553 return subject
1554 if isinstance(subject, str):
1555 parsed = _parse_with_n3(subject)
1556 if isinstance(parsed, URIRef):
1557 return parsed
1558 raise ValueError(f"Invalid FGAC subject: {subject!r}")
1559
1560
1561def _parse_predicate(predicate: t.Any) -> t.Literal["*"] | URIRef:
1562 if predicate == "*":
1563 return "*"
1564 if isinstance(predicate, URIRef):
1565 return predicate
1566 if isinstance(predicate, str):
1567 parsed = _parse_with_n3(predicate)
1568 if isinstance(parsed, URIRef):
1569 return parsed
1570 raise ValueError(f"Invalid FGAC predicate: {predicate!r}")
1571
1572
1573def _parse_object(obj: t.Any) -> t.Literal["*"] | URIRef | Literal:
1574 if obj == "*":
1575 return "*"
1576 if isinstance(obj, (URIRef, Literal)):
1577 return obj
1578 if isinstance(obj, str):
1579 parsed = _parse_with_n3(obj)
1580 if isinstance(parsed, (URIRef, Literal)):
1581 return parsed
1582 raise ValueError(f"Invalid FGAC object: {obj!r}")
1583
1584
1585def _parse_graph(graph: t.Any) -> t.Literal["*", "named", "default"] | URIRef:
1586 if graph in _ALLOWED_GRAPHS:
1587 return t.cast(t.Literal["*", "named", "default"], graph)
1588 if isinstance(graph, URIRef):
1589 return graph
1590 if isinstance(graph, str):
1591 parsed = _parse_with_n3(graph)
1592 if isinstance(parsed, URIRef):
1593 return parsed
1594 raise ValueError(f"Invalid FGAC graph: {graph!r}")
1595
1596
1597def _parse_with_n3(value: str) -> URIRef | Literal:
1598 try:
1599 parsed = from_n3(value)
1600 except Exception:
1601 parsed = None
1602 if isinstance(parsed, (URIRef, Literal)):
1603 return parsed
1604 try:
1605 return URIRef(value)
1606 except Exception as err: # pragma: no cover - defensive
1607 raise ValueError(f"Unable to parse value {value!r} into an RDF term.") from err
1608
1609
1610def _format_term(value: t.Any) -> str:
1611 if isinstance(value, (URIRef, Literal)):
1612 return value.n3()
1613 return t.cast(str, value)