|
| 1 | +# Copyright OpenSearch Contributors |
| 2 | +# SPDX-License-Identifier: Apache-2.0 |
| 3 | +# |
| 4 | +# The OpenSearch Contributors require contributions made to |
| 5 | +# this file be licensed under the Apache-2.0 license or a |
| 6 | +# compatible open source license. |
| 7 | + |
| 8 | +import logging |
| 9 | +import time |
| 10 | +from typing import Dict, Any |
| 11 | +import requests |
| 12 | +from requests.exceptions import HTTPError, ConnectionError, Timeout |
| 13 | + |
| 14 | +from app.models.job import JobStatus |
| 15 | + |
| 16 | +class RemoteVectorAPIClient: |
| 17 | + def __init__(self, base_url: str = "http://localhost:1025", timeout: int = 30): |
| 18 | + self.base_url = base_url |
| 19 | + self.timeout = timeout |
| 20 | + |
| 21 | + |
| 22 | + def wait_for_job_completion( |
| 23 | + self, |
| 24 | + job_id: str, |
| 25 | + timeout: int = 1200, |
| 26 | + interval: int = 10 |
| 27 | + ) -> Dict[str, Any]: |
| 28 | + """Wait for job to complete with timeout""" |
| 29 | + start_time = time.time() |
| 30 | + attempts = 0 |
| 31 | + |
| 32 | + logger = logging.getLogger(__name__) |
| 33 | + |
| 34 | + while True: |
| 35 | + if time.time() - start_time > timeout: |
| 36 | + raise TimeoutError( |
| 37 | + f"Job {job_id} did not complete within {timeout} seconds" |
| 38 | + ) |
| 39 | + |
| 40 | + try: |
| 41 | + attempts += 1 |
| 42 | + status_response = self.get_job_status(job_id) |
| 43 | + |
| 44 | + task_status = status_response.get("task_status") |
| 45 | + |
| 46 | + if task_status == JobStatus.COMPLETED: |
| 47 | + logger.info(f"Job {job_id} completed successfully") |
| 48 | + return status_response |
| 49 | + elif task_status == JobStatus.FAILED: |
| 50 | + raise RuntimeError( |
| 51 | + f"Job {job_id} failed: {status_response.get('error_message')}" |
| 52 | + ) |
| 53 | + elif task_status == JobStatus.RUNNING: |
| 54 | + logger.debug( |
| 55 | + f"Job {job_id} still running (attempt {attempts}), " |
| 56 | + f"waiting {interval} seconds..." |
| 57 | + ) |
| 58 | + time.sleep(interval) |
| 59 | + else: |
| 60 | + raise RuntimeError(f"Unknown job status: {task_status}") |
| 61 | + |
| 62 | + except APIError as e: |
| 63 | + if time.time() - start_time > timeout: |
| 64 | + raise |
| 65 | + logger.warning( |
| 66 | + f"Error checking job status (attempt {attempts}): {str(e)}, " |
| 67 | + f"retrying in {interval} seconds..." |
| 68 | + ) |
| 69 | + time.sleep(interval) |
| 70 | + |
| 71 | + def get_job_status(self, job_id: str) -> Dict[str, Any]: |
| 72 | + """Get status of a job""" |
| 73 | + logger = logging.getLogger(__name__) |
| 74 | + try: |
| 75 | + response = self._make_request( |
| 76 | + method="GET", |
| 77 | + endpoint=f"/_status/{job_id}" |
| 78 | + ) |
| 79 | + return response.json() |
| 80 | + except APIError: |
| 81 | + logger.error(f"Failed to get status for job {job_id}") |
| 82 | + raise |
| 83 | + |
| 84 | + def build_index(self, index_build_parameters: Dict[str, Any]) -> str: |
| 85 | + """Create a new index build job""" |
| 86 | + logger = logging.getLogger(__name__) |
| 87 | + try: |
| 88 | + response = self._make_request( |
| 89 | + method="POST", |
| 90 | + endpoint="/_build", |
| 91 | + json=index_build_parameters |
| 92 | + ) |
| 93 | + return response.json()["job_id"] |
| 94 | + except APIError: |
| 95 | + logger.error("Failed to create index build job") |
| 96 | + raise |
| 97 | + |
| 98 | + def _make_request(self, method: str, endpoint: str, **kwargs) -> requests.Response: |
| 99 | + """Make HTTP request with error handling""" |
| 100 | + |
| 101 | + logger = logging.getLogger(__name__) |
| 102 | + url = f"{self.base_url}/{endpoint.lstrip('/')}" |
| 103 | + try: |
| 104 | + response = requests.request( |
| 105 | + method=method, |
| 106 | + url=url, |
| 107 | + timeout=self.timeout, |
| 108 | + **kwargs |
| 109 | + ) |
| 110 | + response.raise_for_status() |
| 111 | + return response |
| 112 | + except HTTPError as e: |
| 113 | + error_detail = None |
| 114 | + try: |
| 115 | + error_detail = e.response.json() |
| 116 | + except: |
| 117 | + error_detail = e.response.text |
| 118 | + |
| 119 | + logger.error( |
| 120 | + f"HTTP {e.response.status_code} Error: " |
| 121 | + f"URL: {url}, " |
| 122 | + f"Method: {method}, " |
| 123 | + f"Detail: {error_detail}" |
| 124 | + ) |
| 125 | + raise APIError(f"API request failed: {str(e)}") from e |
| 126 | + except ConnectionError as e: |
| 127 | + logger.error(f"Connection failed to {url}: {str(e)}") |
| 128 | + raise APIError("Could not connect to API server") from e |
| 129 | + except Timeout as e: |
| 130 | + logger.error(f"Request timed out to {url}: {str(e)}") |
| 131 | + raise APIError("API request timed out") from e |
| 132 | + except Exception as e: |
| 133 | + logger.error(f"Unexpected error making request to {url}: {str(e)}") |
| 134 | + raise APIError("Unexpected error during API request") from e |
| 135 | + |
| 136 | +class APIError(Exception): |
| 137 | + """Base exception for API errors""" |
| 138 | + pass |
0 commit comments