|
| 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 Exception("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 Exception(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 Exception("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 Exception("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 Exception(f"Graph creation failed: {error}") |
| 212 | + |
| 213 | + raise Exception(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 | + from ..client import AuthenticatedClient |
| 226 | + from ..api.graphs.get_graph import sync_detailed as get_graph |
| 227 | + |
| 228 | + if not self.token: |
| 229 | + raise Exception("No API key provided. Set X-API-Key in headers.") |
| 230 | + |
| 231 | + client = AuthenticatedClient( |
| 232 | + base_url=self.base_url, |
| 233 | + token=self.token, |
| 234 | + prefix="", |
| 235 | + auth_header_name="X-API-Key", |
| 236 | + headers=self.headers, |
| 237 | + ) |
| 238 | + |
| 239 | + response = get_graph(graph_id=graph_id, client=client) |
| 240 | + |
| 241 | + if not response.parsed: |
| 242 | + raise Exception(f"Failed to get graph info: {response.status_code}") |
| 243 | + |
| 244 | + data = response.parsed |
| 245 | + if isinstance(data, dict): |
| 246 | + return GraphInfo( |
| 247 | + graph_id=data.get("graph_id", graph_id), |
| 248 | + graph_name=data.get("graph_name", ""), |
| 249 | + description=data.get("description"), |
| 250 | + schema_extensions=data.get("schema_extensions"), |
| 251 | + tags=data.get("tags"), |
| 252 | + created_at=data.get("created_at"), |
| 253 | + status=data.get("status"), |
| 254 | + ) |
| 255 | + else: |
| 256 | + return GraphInfo( |
| 257 | + graph_id=getattr(data, "graph_id", graph_id), |
| 258 | + graph_name=getattr(data, "graph_name", ""), |
| 259 | + description=getattr(data, "description", None), |
| 260 | + schema_extensions=getattr(data, "schema_extensions", None), |
| 261 | + tags=getattr(data, "tags", None), |
| 262 | + created_at=getattr(data, "created_at", None), |
| 263 | + status=getattr(data, "status", None), |
| 264 | + ) |
| 265 | + |
| 266 | + def delete_graph(self, graph_id: str) -> None: |
| 267 | + """ |
| 268 | + Delete a graph. |
| 269 | +
|
| 270 | + Args: |
| 271 | + graph_id: The graph ID to delete |
| 272 | + """ |
| 273 | + from ..client import AuthenticatedClient |
| 274 | + from ..api.graphs.delete_graph import sync_detailed as delete_graph |
| 275 | + |
| 276 | + if not self.token: |
| 277 | + raise Exception("No API key provided. Set X-API-Key in headers.") |
| 278 | + |
| 279 | + client = AuthenticatedClient( |
| 280 | + base_url=self.base_url, |
| 281 | + token=self.token, |
| 282 | + prefix="", |
| 283 | + auth_header_name="X-API-Key", |
| 284 | + headers=self.headers, |
| 285 | + ) |
| 286 | + |
| 287 | + response = delete_graph(graph_id=graph_id, client=client) |
| 288 | + |
| 289 | + if response.status_code not in [200, 204]: |
| 290 | + raise Exception(f"Failed to delete graph: {response.status_code}") |
| 291 | + |
| 292 | + def close(self): |
| 293 | + """Clean up resources (placeholder for consistency)""" |
| 294 | + pass |
0 commit comments