|
| 1 | +"""Graph Management Client |
| 2 | +
|
| 3 | +Provides high-level graph management operations with automatic operation monitoring. |
| 4 | +""" |
| 5 | + |
| 6 | +from dataclasses import dataclass |
| 7 | +from typing import Dict, Any, Optional, Callable |
| 8 | +import time |
| 9 | +import logging |
| 10 | + |
| 11 | +logger = logging.getLogger(__name__) |
| 12 | + |
| 13 | + |
| 14 | +@dataclass |
| 15 | +class GraphMetadata: |
| 16 | + """Graph metadata for creation""" |
| 17 | + |
| 18 | + graph_name: str |
| 19 | + description: Optional[str] = None |
| 20 | + schema_extensions: Optional[list] = None |
| 21 | + tags: Optional[list] = None |
| 22 | + |
| 23 | + |
| 24 | +@dataclass |
| 25 | +class InitialEntityData: |
| 26 | + """Initial entity data for graph creation""" |
| 27 | + |
| 28 | + name: str |
| 29 | + uri: str |
| 30 | + category: Optional[str] = None |
| 31 | + sic: Optional[str] = None |
| 32 | + sic_description: Optional[str] = None |
| 33 | + |
| 34 | + |
| 35 | +@dataclass |
| 36 | +class GraphInfo: |
| 37 | + """Information about a graph""" |
| 38 | + |
| 39 | + graph_id: str |
| 40 | + graph_name: str |
| 41 | + description: Optional[str] = None |
| 42 | + schema_extensions: Optional[list] = None |
| 43 | + tags: Optional[list] = None |
| 44 | + created_at: Optional[str] = None |
| 45 | + status: Optional[str] = None |
| 46 | + |
| 47 | + |
| 48 | +class GraphClient: |
| 49 | + """Client for graph management operations""" |
| 50 | + |
| 51 | + def __init__(self, config: Dict[str, Any]): |
| 52 | + self.config = config |
| 53 | + self.base_url = config["base_url"] |
| 54 | + self.headers = config.get("headers", {}) |
| 55 | + self.token = config.get("token") |
| 56 | + |
| 57 | + def create_graph_and_wait( |
| 58 | + self, |
| 59 | + metadata: GraphMetadata, |
| 60 | + initial_entity: Optional[InitialEntityData] = None, |
| 61 | + timeout: int = 60, |
| 62 | + poll_interval: int = 2, |
| 63 | + on_progress: Optional[Callable[[str], None]] = None, |
| 64 | + ) -> str: |
| 65 | + """ |
| 66 | + Create a graph and wait for completion. |
| 67 | +
|
| 68 | + Args: |
| 69 | + metadata: Graph metadata |
| 70 | + initial_entity: Optional initial entity data |
| 71 | + timeout: Maximum time to wait in seconds |
| 72 | + poll_interval: Time between status checks in seconds |
| 73 | + on_progress: Callback for progress updates |
| 74 | +
|
| 75 | + Returns: |
| 76 | + graph_id when creation completes |
| 77 | +
|
| 78 | + Raises: |
| 79 | + Exception: If creation fails or times out |
| 80 | + """ |
| 81 | + from ..client import AuthenticatedClient |
| 82 | + from ..api.graphs.create_graph import sync_detailed as create_graph |
| 83 | + from ..api.operations.get_operation_status import sync_detailed as get_status |
| 84 | + from ..models.create_graph_request import CreateGraphRequest |
| 85 | + from ..models.graph_metadata import GraphMetadata as APIGraphMetadata |
| 86 | + |
| 87 | + if not self.token: |
| 88 | + raise ValueError("No API key provided. Set X-API-Key in headers.") |
| 89 | + |
| 90 | + client = AuthenticatedClient( |
| 91 | + base_url=self.base_url, |
| 92 | + token=self.token, |
| 93 | + prefix="", |
| 94 | + auth_header_name="X-API-Key", |
| 95 | + headers=self.headers, |
| 96 | + ) |
| 97 | + |
| 98 | + # Build API metadata |
| 99 | + api_metadata = APIGraphMetadata( |
| 100 | + graph_name=metadata.graph_name, |
| 101 | + description=metadata.description, |
| 102 | + schema_extensions=metadata.schema_extensions or [], |
| 103 | + tags=metadata.tags or [], |
| 104 | + ) |
| 105 | + |
| 106 | + # Build initial entity if provided |
| 107 | + initial_entity_dict = None |
| 108 | + if initial_entity: |
| 109 | + initial_entity_dict = { |
| 110 | + "name": initial_entity.name, |
| 111 | + "uri": initial_entity.uri, |
| 112 | + } |
| 113 | + if initial_entity.category: |
| 114 | + initial_entity_dict["category"] = initial_entity.category |
| 115 | + if initial_entity.sic: |
| 116 | + initial_entity_dict["sic"] = initial_entity.sic |
| 117 | + if initial_entity.sic_description: |
| 118 | + initial_entity_dict["sic_description"] = initial_entity.sic_description |
| 119 | + |
| 120 | + # Create graph request |
| 121 | + graph_create = CreateGraphRequest( |
| 122 | + metadata=api_metadata, |
| 123 | + initial_entity=initial_entity_dict, |
| 124 | + ) |
| 125 | + |
| 126 | + if on_progress: |
| 127 | + on_progress(f"Creating graph: {metadata.graph_name}") |
| 128 | + |
| 129 | + # Execute create request |
| 130 | + response = create_graph(client=client, body=graph_create) |
| 131 | + |
| 132 | + if not response.parsed: |
| 133 | + raise RuntimeError(f"Failed to create graph: {response.status_code}") |
| 134 | + |
| 135 | + # Extract graph_id or operation_id |
| 136 | + if isinstance(response.parsed, dict): |
| 137 | + graph_id = response.parsed.get("graph_id") |
| 138 | + operation_id = response.parsed.get("operation_id") |
| 139 | + else: |
| 140 | + graph_id = getattr(response.parsed, "graph_id", None) |
| 141 | + operation_id = getattr(response.parsed, "operation_id", None) |
| 142 | + |
| 143 | + # If graph_id returned immediately, we're done |
| 144 | + if graph_id: |
| 145 | + if on_progress: |
| 146 | + on_progress(f"Graph created: {graph_id}") |
| 147 | + return graph_id |
| 148 | + |
| 149 | + # Otherwise, poll operation until complete |
| 150 | + if not operation_id: |
| 151 | + raise RuntimeError("No graph_id or operation_id in response") |
| 152 | + |
| 153 | + if on_progress: |
| 154 | + on_progress(f"Graph creation queued (operation: {operation_id})") |
| 155 | + |
| 156 | + max_attempts = timeout // poll_interval |
| 157 | + for attempt in range(max_attempts): |
| 158 | + time.sleep(poll_interval) |
| 159 | + |
| 160 | + status_response = get_status(operation_id=operation_id, client=client) |
| 161 | + |
| 162 | + if not status_response.parsed: |
| 163 | + continue |
| 164 | + |
| 165 | + # Handle both dict and object responses |
| 166 | + status_data = status_response.parsed |
| 167 | + if isinstance(status_data, dict): |
| 168 | + status = status_data.get("status") |
| 169 | + else: |
| 170 | + # Check for additional_properties first (common in generated clients) |
| 171 | + if hasattr(status_data, "additional_properties"): |
| 172 | + status = status_data.additional_properties.get("status") |
| 173 | + else: |
| 174 | + status = getattr(status_data, "status", None) |
| 175 | + |
| 176 | + if on_progress: |
| 177 | + on_progress(f"Status: {status} (attempt {attempt + 1}/{max_attempts})") |
| 178 | + |
| 179 | + if status == "completed": |
| 180 | + # Extract graph_id from result |
| 181 | + if isinstance(status_data, dict): |
| 182 | + result = status_data.get("result", {}) |
| 183 | + elif hasattr(status_data, "additional_properties"): |
| 184 | + result = status_data.additional_properties.get("result", {}) |
| 185 | + else: |
| 186 | + result = getattr(status_data, "result", {}) |
| 187 | + |
| 188 | + if isinstance(result, dict): |
| 189 | + graph_id = result.get("graph_id") |
| 190 | + else: |
| 191 | + graph_id = getattr(result, "graph_id", None) |
| 192 | + |
| 193 | + if graph_id: |
| 194 | + if on_progress: |
| 195 | + on_progress(f"Graph created: {graph_id}") |
| 196 | + return graph_id |
| 197 | + else: |
| 198 | + raise RuntimeError("Operation completed but no graph_id in result") |
| 199 | + |
| 200 | + elif status == "failed": |
| 201 | + # Extract error message |
| 202 | + if isinstance(status_data, dict): |
| 203 | + error = ( |
| 204 | + status_data.get("error") or status_data.get("message") or "Unknown error" |
| 205 | + ) |
| 206 | + elif hasattr(status_data, "additional_properties"): |
| 207 | + props = status_data.additional_properties |
| 208 | + error = props.get("error") or props.get("message") or "Unknown error" |
| 209 | + else: |
| 210 | + error = getattr(status_data, "message", "Unknown error") |
| 211 | + raise RuntimeError(f"Graph creation failed: {error}") |
| 212 | + |
| 213 | + raise TimeoutError(f"Graph creation timed out after {timeout}s") |
| 214 | + |
| 215 | + def get_graph_info(self, graph_id: str) -> GraphInfo: |
| 216 | + """ |
| 217 | + Get information about a graph. |
| 218 | +
|
| 219 | + Args: |
| 220 | + graph_id: The graph ID |
| 221 | +
|
| 222 | + Returns: |
| 223 | + GraphInfo with graph details |
| 224 | +
|
| 225 | + Raises: |
| 226 | + ValueError: If graph not found |
| 227 | + """ |
| 228 | + from ..client import AuthenticatedClient |
| 229 | + from ..api.graphs.get_graphs import sync_detailed as get_graphs |
| 230 | + |
| 231 | + if not self.token: |
| 232 | + raise ValueError("No API key provided. Set X-API-Key in headers.") |
| 233 | + |
| 234 | + client = AuthenticatedClient( |
| 235 | + base_url=self.base_url, |
| 236 | + token=self.token, |
| 237 | + prefix="", |
| 238 | + auth_header_name="X-API-Key", |
| 239 | + headers=self.headers, |
| 240 | + ) |
| 241 | + |
| 242 | + # Use get_graphs and filter for the specific graph |
| 243 | + response = get_graphs(client=client) |
| 244 | + |
| 245 | + if not response.parsed: |
| 246 | + raise RuntimeError(f"Failed to get graphs: {response.status_code}") |
| 247 | + |
| 248 | + data = response.parsed |
| 249 | + graphs = None |
| 250 | + |
| 251 | + # Extract graphs list from response |
| 252 | + if isinstance(data, dict): |
| 253 | + graphs = data.get("graphs", []) |
| 254 | + elif hasattr(data, "additional_properties"): |
| 255 | + graphs = data.additional_properties.get("graphs", []) |
| 256 | + elif hasattr(data, "graphs"): |
| 257 | + graphs = data.graphs |
| 258 | + else: |
| 259 | + raise RuntimeError("Unexpected response format from get_graphs") |
| 260 | + |
| 261 | + # Find the specific graph by ID |
| 262 | + graph_data = None |
| 263 | + for graph in graphs: |
| 264 | + if isinstance(graph, dict): |
| 265 | + if graph.get("graph_id") == graph_id or graph.get("id") == graph_id: |
| 266 | + graph_data = graph |
| 267 | + break |
| 268 | + elif hasattr(graph, "graph_id"): |
| 269 | + if graph.graph_id == graph_id or getattr(graph, "id", None) == graph_id: |
| 270 | + graph_data = graph |
| 271 | + break |
| 272 | + |
| 273 | + if not graph_data: |
| 274 | + raise ValueError(f"Graph not found: {graph_id}") |
| 275 | + |
| 276 | + # Build GraphInfo from the found graph |
| 277 | + if isinstance(graph_data, dict): |
| 278 | + return GraphInfo( |
| 279 | + graph_id=graph_data.get("graph_id") or graph_data.get("id", graph_id), |
| 280 | + graph_name=graph_data.get("graph_name") or graph_data.get("name", ""), |
| 281 | + description=graph_data.get("description"), |
| 282 | + schema_extensions=graph_data.get("schema_extensions"), |
| 283 | + tags=graph_data.get("tags"), |
| 284 | + created_at=graph_data.get("created_at"), |
| 285 | + status=graph_data.get("status"), |
| 286 | + ) |
| 287 | + else: |
| 288 | + return GraphInfo( |
| 289 | + graph_id=getattr(graph_data, "graph_id", None) |
| 290 | + or getattr(graph_data, "id", graph_id), |
| 291 | + graph_name=getattr(graph_data, "graph_name", None) |
| 292 | + or getattr(graph_data, "name", ""), |
| 293 | + description=getattr(graph_data, "description", None), |
| 294 | + schema_extensions=getattr(graph_data, "schema_extensions", None), |
| 295 | + tags=getattr(graph_data, "tags", None), |
| 296 | + created_at=getattr(graph_data, "created_at", None), |
| 297 | + status=getattr(graph_data, "status", None), |
| 298 | + ) |
| 299 | + |
| 300 | + def delete_graph(self, graph_id: str) -> None: |
| 301 | + """ |
| 302 | + Delete a graph. |
| 303 | +
|
| 304 | + Note: This method is not yet available as the delete_graph endpoint |
| 305 | + is not included in the generated SDK. This will be implemented when |
| 306 | + the endpoint is added to the API specification. |
| 307 | +
|
| 308 | + Args: |
| 309 | + graph_id: The graph ID to delete |
| 310 | +
|
| 311 | + Raises: |
| 312 | + NotImplementedError: This feature is not yet available |
| 313 | + """ |
| 314 | + raise NotImplementedError( |
| 315 | + "Graph deletion is not yet available. " |
| 316 | + "The delete_graph endpoint needs to be added to the API specification." |
| 317 | + ) |
| 318 | + |
| 319 | + def close(self): |
| 320 | + """Clean up resources (placeholder for consistency)""" |
| 321 | + pass |
0 commit comments