|
| 1 | +""" |
| 2 | +MATLAB HTTP Client |
| 3 | +
|
| 4 | +This module provides a client to communicate with the MATLAB HTTP API server |
| 5 | +running in a separate Docker container. |
| 6 | +""" |
| 7 | + |
| 8 | +import os |
| 9 | +import requests |
| 10 | +import logging |
| 11 | +from typing import Dict, Any, List, Optional |
| 12 | + |
| 13 | +logger = logging.getLogger(__name__) |
| 14 | + |
| 15 | + |
| 16 | +class MatlabHTTPClient: |
| 17 | + """ |
| 18 | + Client to communicate with MATLAB HTTP API server. |
| 19 | + Replaces direct MATLAB Engine API usage with HTTP requests. |
| 20 | + """ |
| 21 | + _instance: Optional['MatlabHTTPClient'] = None |
| 22 | + |
| 23 | + def __new__(cls): |
| 24 | + if cls._instance is None: |
| 25 | + cls._instance = super(MatlabHTTPClient, cls).__new__(cls) |
| 26 | + cls._instance._initialized = False |
| 27 | + return cls._instance |
| 28 | + |
| 29 | + def __init__(self): |
| 30 | + """Initialize the HTTP client.""" |
| 31 | + if self._initialized: |
| 32 | + return |
| 33 | + |
| 34 | + # Get MATLAB server configuration from environment |
| 35 | + self.matlab_host = os.getenv('MATLAB_HOST', 'matlab') |
| 36 | + self.matlab_port = int(os.getenv('MATLAB_HTTP_PORT', '9090')) |
| 37 | + self.base_url = f"http://{self.matlab_host}:{self.matlab_port}" |
| 38 | + self.timeout = 300 # 5 minutes timeout for MATLAB operations |
| 39 | + |
| 40 | + logger.info(f"MATLAB HTTP Client initialized: {self.base_url}") |
| 41 | + self._initialized = True |
| 42 | + |
| 43 | + def health_check(self) -> bool: |
| 44 | + """ |
| 45 | + Check if the MATLAB server is healthy and responsive. |
| 46 | + |
| 47 | + Returns: |
| 48 | + bool: True if server is healthy, False otherwise |
| 49 | + """ |
| 50 | + try: |
| 51 | + response = requests.get( |
| 52 | + f"{self.base_url}/health", |
| 53 | + timeout=5 |
| 54 | + ) |
| 55 | + return response.status_code == 200 |
| 56 | + except Exception as e: |
| 57 | + logger.error(f"MATLAB health check failed: {e}") |
| 58 | + return False |
| 59 | + |
| 60 | + def execute( |
| 61 | + self, |
| 62 | + function: str, |
| 63 | + *args, |
| 64 | + nargout: int = 1, |
| 65 | + **kwargs |
| 66 | + ) -> Dict[str, Any]: |
| 67 | + """ |
| 68 | + Execute a MATLAB function. |
| 69 | + |
| 70 | + Args: |
| 71 | + function: Name of the MATLAB function to execute |
| 72 | + *args: Positional arguments to pass to the function |
| 73 | + nargout: Number of output arguments (default 1) |
| 74 | + **kwargs: Keyword arguments to pass to the function |
| 75 | + |
| 76 | + Returns: |
| 77 | + Dictionary with 'status' and either 'result' or 'message': |
| 78 | + - {'status': 'success', 'result': <return_value>} |
| 79 | + - {'status': 'error', 'message': <error_message>} |
| 80 | + """ |
| 81 | + try: |
| 82 | + payload = { |
| 83 | + 'function': function, |
| 84 | + 'args': list(args), |
| 85 | + 'kwargs': kwargs, |
| 86 | + 'nargout': nargout |
| 87 | + } |
| 88 | + |
| 89 | + logger.debug(f"Executing MATLAB function: {function}") |
| 90 | + |
| 91 | + response = requests.post( |
| 92 | + f"{self.base_url}/execute", |
| 93 | + json=payload, |
| 94 | + timeout=self.timeout |
| 95 | + ) |
| 96 | + |
| 97 | + result = response.json() |
| 98 | + |
| 99 | + if response.status_code == 200: |
| 100 | + logger.debug(f"Function executed successfully: {function}") |
| 101 | + return result |
| 102 | + else: |
| 103 | + logger.error(f"Function execution failed: {result.get('message', 'Unknown error')}") |
| 104 | + return result |
| 105 | + |
| 106 | + except requests.exceptions.Timeout: |
| 107 | + error_msg = f"MATLAB function {function} timed out after {self.timeout} seconds" |
| 108 | + logger.error(error_msg) |
| 109 | + return {'status': 'error', 'message': error_msg} |
| 110 | + except requests.exceptions.ConnectionError as e: |
| 111 | + error_msg = f"Cannot connect to MATLAB server at {self.base_url}: {str(e)}" |
| 112 | + logger.error(error_msg) |
| 113 | + return {'status': 'error', 'message': error_msg} |
| 114 | + except Exception as e: |
| 115 | + error_msg = f"Unexpected error executing {function}: {str(e)}" |
| 116 | + logger.error(error_msg) |
| 117 | + return {'status': 'error', 'message': error_msg} |
| 118 | + |
| 119 | + def eval(self, code: str, nargout: int = 0) -> Dict[str, Any]: |
| 120 | + """ |
| 121 | + Evaluate MATLAB code. |
| 122 | + |
| 123 | + Args: |
| 124 | + code: MATLAB code string to evaluate |
| 125 | + nargout: Number of output arguments (default 0) |
| 126 | + |
| 127 | + Returns: |
| 128 | + Dictionary with 'status' and either 'result' or 'message': |
| 129 | + - {'status': 'success', 'result': <return_value>} (if nargout > 0) |
| 130 | + - {'status': 'success'} (if nargout == 0) |
| 131 | + - {'status': 'error', 'message': <error_message>} |
| 132 | + """ |
| 133 | + try: |
| 134 | + payload = { |
| 135 | + 'code': code, |
| 136 | + 'nargout': nargout |
| 137 | + } |
| 138 | + |
| 139 | + logger.debug(f"Evaluating MATLAB code: {code[:100]}...") |
| 140 | + |
| 141 | + response = requests.post( |
| 142 | + f"{self.base_url}/eval", |
| 143 | + json=payload, |
| 144 | + timeout=self.timeout |
| 145 | + ) |
| 146 | + |
| 147 | + result = response.json() |
| 148 | + |
| 149 | + if response.status_code == 200: |
| 150 | + logger.debug("Code evaluated successfully") |
| 151 | + return result |
| 152 | + else: |
| 153 | + logger.error(f"Code evaluation failed: {result.get('message', 'Unknown error')}") |
| 154 | + return result |
| 155 | + |
| 156 | + except requests.exceptions.Timeout: |
| 157 | + error_msg = f"MATLAB code evaluation timed out after {self.timeout} seconds" |
| 158 | + logger.error(error_msg) |
| 159 | + return {'status': 'error', 'message': error_msg} |
| 160 | + except requests.exceptions.ConnectionError as e: |
| 161 | + error_msg = f"Cannot connect to MATLAB server at {self.base_url}: {str(e)}" |
| 162 | + logger.error(error_msg) |
| 163 | + return {'status': 'error', 'message': error_msg} |
| 164 | + except Exception as e: |
| 165 | + error_msg = f"Unexpected error evaluating code: {str(e)}" |
| 166 | + logger.error(error_msg) |
| 167 | + return {'status': 'error', 'message': error_msg} |
| 168 | + |
| 169 | + @property |
| 170 | + def is_connected(self) -> bool: |
| 171 | + """Check if the MATLAB server is connected and responsive.""" |
| 172 | + return self.health_check() |
| 173 | + |
| 174 | + |
| 175 | +# Alias for backwards compatibility |
| 176 | +MatlabSessionManager = MatlabHTTPClient |
0 commit comments