askrobots / dbbasic-object-primitive
Public
Python functions as REST objects, with clustering, load balancing and state replication; no containers or orchestration.
[id].py · 28.6 KB · 859 lines
| 1 | """ |
| 2 | API handler for individual objects |
| 3 | |
| 4 | GET /objects/{id} - Execute object's GET method |
| 5 | GET /objects/{id}?source=true - View object's source code |
| 6 | GET /objects/{id}?metadata=true - View object metadata |
| 7 | GET /objects/{id}?logs=true - View object logs |
| 8 | GET /objects/{id}?versions=true - View version history |
| 9 | GET /objects/{id}?version=N - Get specific version |
| 10 | |
| 11 | POST /objects/{id} - Execute object's POST method |
| 12 | POST /objects/{id} (action=rollback) - Rollback to specific version |
| 13 | PUT /objects/{id} - Execute object's PUT method or update code |
| 14 | DELETE /objects/{id} - Execute object's DELETE method |
| 15 | |
| 16 | Cross-station routing (Phase 7.2): |
| 17 | GET /objects/{id}@{station_id} - Execute object on remote station |
| 18 | """ |
| 19 | import json |
| 20 | import os |
| 21 | import time |
| 22 | import requests |
| 23 | from pathlib import Path |
| 24 | from dbbasic_web.responses import json as json_response, json_error |
| 25 | |
| 26 | from dbbasic_object_core.runtime.object_runtime import ObjectRuntime |
| 27 | |
| 28 | |
| 29 | # Initialize runtime (shared across requests) |
| 30 | _runtime = None |
| 31 | |
| 32 | |
| 33 | def get_runtime(): |
| 34 | """Get or create the ObjectRuntime instance""" |
| 35 | global _runtime |
| 36 | if _runtime is None: |
| 37 | _runtime = ObjectRuntime(base_dir='./data') |
| 38 | return _runtime |
| 39 | |
| 40 | |
| 41 | def find_object_file(object_id: str) -> Path | None: |
| 42 | """Find object file by ID""" |
| 43 | # Convert object_id back to path |
| 44 | # basics_counter -> basics/counter.py |
| 45 | # tutorial_03_counter -> tutorial/03_counter.py |
| 46 | |
| 47 | examples_dir = Path('examples') |
| 48 | |
| 49 | # Try direct path first |
| 50 | parts = object_id.split('_', 1) |
| 51 | if len(parts) == 2: |
| 52 | subdir, filename = parts |
| 53 | py_file = examples_dir / subdir / f'{filename}.py' |
| 54 | if py_file.exists(): |
| 55 | return py_file |
| 56 | |
| 57 | # Try as single file |
| 58 | py_file = examples_dir / f'{object_id}.py' |
| 59 | if py_file.exists(): |
| 60 | return py_file |
| 61 | |
| 62 | # Scan for match |
| 63 | for py_file in examples_dir.rglob('*.py'): |
| 64 | if py_file.name == '__init__.py' or '__pycache__' in str(py_file): |
| 65 | continue |
| 66 | |
| 67 | rel_path = py_file.relative_to(examples_dir) |
| 68 | found_id = str(rel_path).replace('.py', '').replace('/', '_') |
| 69 | |
| 70 | if found_id == object_id: |
| 71 | return py_file |
| 72 | |
| 73 | return None |
| 74 | |
| 75 | |
| 76 | def parse_object_routing(id_param: str) -> tuple[str, str | None]: |
| 77 | """ |
| 78 | Parse object_id@station_id syntax |
| 79 | |
| 80 | Returns: |
| 81 | (object_id, station_id) - station_id is None if no @ in id_param |
| 82 | |
| 83 | Examples: |
| 84 | 'calculator' -> ('calculator', None) |
| 85 | 'calculator@station2' -> ('calculator', 'station2') |
| 86 | """ |
| 87 | if '@' in id_param: |
| 88 | object_id, station_id = id_param.split('@', 1) |
| 89 | return object_id, station_id |
| 90 | return id_param, None |
| 91 | |
| 92 | |
| 93 | def get_station_info(station_id: str) -> dict | None: |
| 94 | """ |
| 95 | Look up station in cluster registry |
| 96 | |
| 97 | Returns: |
| 98 | Station info dict or None if not found/inactive |
| 99 | { |
| 100 | 'station_id': 'station2', |
| 101 | 'host': '192.0.2.2', |
| 102 | 'port': 8001, |
| 103 | 'last_heartbeat': 1234567890.123, |
| 104 | 'is_active': True, |
| 105 | 'url': 'http://192.0.2.2:8001', |
| 106 | 'metrics': {...} # Optional |
| 107 | } |
| 108 | """ |
| 109 | registry_file = Path('data/cluster/stations.tsv') |
| 110 | |
| 111 | if not registry_file.exists(): |
| 112 | return None |
| 113 | |
| 114 | current_time = time.time() |
| 115 | timeout = 30 # seconds |
| 116 | |
| 117 | with open(registry_file, 'r') as f: |
| 118 | for line in f: |
| 119 | if line.strip(): |
| 120 | parts = line.strip().split('\t') |
| 121 | if len(parts) >= 4: |
| 122 | sid, host, port, last_heartbeat = parts[:4] |
| 123 | metrics_json = parts[4] if len(parts) > 4 else '{}' |
| 124 | |
| 125 | if sid == station_id: |
| 126 | # Check if active |
| 127 | age = current_time - float(last_heartbeat) |
| 128 | is_active = age < timeout |
| 129 | |
| 130 | if not is_active: |
| 131 | return None # Station offline |
| 132 | |
| 133 | # Parse metrics |
| 134 | try: |
| 135 | metrics = json.loads(metrics_json) |
| 136 | except: |
| 137 | metrics = {} |
| 138 | |
| 139 | station_info = { |
| 140 | 'station_id': sid, |
| 141 | 'host': host, |
| 142 | 'port': int(port), |
| 143 | 'last_heartbeat': float(last_heartbeat), |
| 144 | 'is_active': is_active, |
| 145 | 'url': f'http://{host}:{port}' |
| 146 | } |
| 147 | |
| 148 | if metrics: |
| 149 | station_info['metrics'] = metrics |
| 150 | |
| 151 | return station_info |
| 152 | |
| 153 | return None |
| 154 | |
| 155 | |
| 156 | def get_all_active_stations() -> list[dict]: |
| 157 | """ |
| 158 | Get list of all active stations in cluster |
| 159 | |
| 160 | Returns: |
| 161 | List of station info dicts (same format as get_station_info) |
| 162 | """ |
| 163 | registry_file = Path('data/cluster/stations.tsv') |
| 164 | |
| 165 | if not registry_file.exists(): |
| 166 | return [] |
| 167 | |
| 168 | current_time = time.time() |
| 169 | timeout = 30 # seconds |
| 170 | stations = [] |
| 171 | |
| 172 | with open(registry_file, 'r') as f: |
| 173 | for line in f: |
| 174 | if line.strip(): |
| 175 | parts = line.strip().split('\t') |
| 176 | if len(parts) >= 4: |
| 177 | sid, host, port, last_heartbeat = parts[:4] |
| 178 | metrics_json = parts[4] if len(parts) > 4 else '{}' |
| 179 | |
| 180 | # Check if active |
| 181 | age = current_time - float(last_heartbeat) |
| 182 | is_active = age < timeout |
| 183 | |
| 184 | if is_active: |
| 185 | # Parse metrics |
| 186 | try: |
| 187 | metrics = json.loads(metrics_json) |
| 188 | except: |
| 189 | metrics = {} |
| 190 | |
| 191 | station_info = { |
| 192 | 'station_id': sid, |
| 193 | 'host': host, |
| 194 | 'port': int(port), |
| 195 | 'last_heartbeat': float(last_heartbeat), |
| 196 | 'is_active': True, |
| 197 | 'url': f'http://{host}:{port}' |
| 198 | } |
| 199 | |
| 200 | if metrics: |
| 201 | station_info['metrics'] = metrics |
| 202 | |
| 203 | stations.append(station_info) |
| 204 | |
| 205 | # Always include ourselves if we're station1 |
| 206 | local_station = os.environ.get('STATION_ID', 'unknown') |
| 207 | if local_station == 'station1': |
| 208 | if not any(s['station_id'] == local_station for s in stations): |
| 209 | stations.insert(0, { |
| 210 | 'station_id': local_station, |
| 211 | 'host': 'localhost', |
| 212 | 'port': 8001, |
| 213 | 'last_heartbeat': current_time, |
| 214 | 'is_active': True, |
| 215 | 'url': 'http://localhost:8001' |
| 216 | }) |
| 217 | |
| 218 | return stations |
| 219 | |
| 220 | |
| 221 | def calculate_load_score(metrics: dict) -> float: |
| 222 | """ |
| 223 | Calculate load score from metrics (lower is better) |
| 224 | |
| 225 | Score = (cpu_percent * 0.6) + (memory_percent * 0.4) |
| 226 | |
| 227 | Range: 0-100 (0 = idle, 100 = fully loaded) |
| 228 | """ |
| 229 | if not metrics: |
| 230 | return 50.0 # Default middle score if no metrics |
| 231 | |
| 232 | cpu = metrics.get('cpu_percent', 50.0) |
| 233 | mem = metrics.get('memory_percent', 50.0) |
| 234 | |
| 235 | # Weighted average (CPU weighted higher than memory) |
| 236 | return (cpu * 0.6) + (mem * 0.4) |
| 237 | |
| 238 | |
| 239 | def find_best_station(object_id: str) -> dict | None: |
| 240 | """ |
| 241 | Find the best station to execute an object based on load |
| 242 | |
| 243 | Strategy: |
| 244 | 1. Get all active stations |
| 245 | 2. Check which ones have the object |
| 246 | 3. Select the one with lowest load score |
| 247 | 4. If no remote stations have it, return None (execute locally) |
| 248 | |
| 249 | Returns: |
| 250 | Station info dict or None if should execute locally |
| 251 | """ |
| 252 | local_station = os.environ.get('STATION_ID', 'unknown') |
| 253 | stations = get_all_active_stations() |
| 254 | |
| 255 | if len(stations) <= 1: |
| 256 | return None # No remote stations, execute locally |
| 257 | |
| 258 | # For now, assume all stations have all objects (deployed via rsync) |
| 259 | # Future: Check which stations actually have the object |
| 260 | |
| 261 | # Find station with lowest load (excluding ourselves) |
| 262 | best_station = None |
| 263 | best_score = float('inf') |
| 264 | |
| 265 | for station in stations: |
| 266 | # Skip ourselves - we want to offload if possible |
| 267 | if station['station_id'] == local_station: |
| 268 | continue |
| 269 | |
| 270 | metrics = station.get('metrics', {}) |
| 271 | score = calculate_load_score(metrics) |
| 272 | |
| 273 | if score < best_score: |
| 274 | best_score = score |
| 275 | best_station = station |
| 276 | |
| 277 | # Only route if remote station is significantly less loaded (> 20% better) |
| 278 | local_metrics = {} |
| 279 | for station in stations: |
| 280 | if station['station_id'] == local_station: |
| 281 | local_metrics = station.get('metrics', {}) |
| 282 | break |
| 283 | |
| 284 | local_score = calculate_load_score(local_metrics) |
| 285 | |
| 286 | # Route if remote is at least 20 points better, or if local is > 70% loaded |
| 287 | if best_station and (local_score - best_score > 20 or local_score > 70): |
| 288 | return best_station |
| 289 | |
| 290 | return None # Execute locally |
| 291 | |
| 292 | |
| 293 | def forward_request(station_info: dict, object_id: str, method: str, |
| 294 | query_params: dict = None, body_data: dict = None, |
| 295 | timeout: int = 30) -> dict: |
| 296 | """ |
| 297 | Forward HTTP request to remote station |
| 298 | |
| 299 | Args: |
| 300 | station_info: Station info from get_station_info() |
| 301 | object_id: Object ID (without @station_id) |
| 302 | method: HTTP method (GET, POST, PUT, DELETE) |
| 303 | query_params: Query parameters dict |
| 304 | body_data: Request body data (for POST/PUT/DELETE) |
| 305 | timeout: Request timeout in seconds |
| 306 | |
| 307 | Returns: |
| 308 | Response JSON dict |
| 309 | |
| 310 | Raises: |
| 311 | requests.RequestException: If request fails |
| 312 | """ |
| 313 | url = f"{station_info['url']}/objects/{object_id}" |
| 314 | |
| 315 | # Prepare request |
| 316 | headers = {'Content-Type': 'application/json'} |
| 317 | params = query_params or {} |
| 318 | |
| 319 | # Make request |
| 320 | if method == 'GET': |
| 321 | response = requests.get(url, params=params, timeout=timeout) |
| 322 | elif method == 'POST': |
| 323 | response = requests.post(url, params=params, json=body_data, headers=headers, timeout=timeout) |
| 324 | elif method == 'PUT': |
| 325 | response = requests.put(url, params=params, json=body_data, headers=headers, timeout=timeout) |
| 326 | elif method == 'DELETE': |
| 327 | response = requests.delete(url, params=params, json=body_data, headers=headers, timeout=timeout) |
| 328 | else: |
| 329 | raise ValueError(f'Unsupported method: {method}') |
| 330 | |
| 331 | # Parse response |
| 332 | try: |
| 333 | result = response.json() |
| 334 | # Add routing metadata |
| 335 | result['_routed_to'] = station_info['station_id'] |
| 336 | result['_routed_from'] = os.environ.get('STATION_ID', 'unknown') |
| 337 | return result |
| 338 | except json.JSONDecodeError: |
| 339 | # Return raw response if not JSON |
| 340 | return { |
| 341 | 'status': 'error', |
| 342 | 'error': 'Invalid JSON response from remote station', |
| 343 | 'raw_response': response.text, |
| 344 | '_routed_to': station_info['station_id'], |
| 345 | '_routed_from': os.environ.get('STATION_ID', 'unknown') |
| 346 | } |
| 347 | |
| 348 | |
| 349 | def GET(request, id: str): |
| 350 | """ |
| 351 | Get object information or execute GET method |
| 352 | |
| 353 | Query parameters: |
| 354 | - source: Return source code |
| 355 | - metadata: Return metadata |
| 356 | - logs: Return logs |
| 357 | - versions: Return version history |
| 358 | - (default): Execute GET method |
| 359 | |
| 360 | Cross-station routing: |
| 361 | - id can be 'object_id' or 'object_id@station_id' |
| 362 | - If @station_id is present, route to that station |
| 363 | """ |
| 364 | # Parse routing syntax (Phase 7.2) |
| 365 | object_id, target_station = parse_object_routing(id) |
| 366 | |
| 367 | # Check if this should be routed to another station |
| 368 | if target_station: |
| 369 | local_station = os.environ.get('STATION_ID', 'unknown') |
| 370 | |
| 371 | # If target is local station, execute locally |
| 372 | if target_station == local_station: |
| 373 | # Continue to local execution below |
| 374 | pass |
| 375 | else: |
| 376 | # Route to remote station |
| 377 | station_info = get_station_info(target_station) |
| 378 | |
| 379 | if not station_info: |
| 380 | return json_error( |
| 381 | f'Station not found or offline: {target_station}', |
| 382 | status=503 # Service Unavailable |
| 383 | ) |
| 384 | |
| 385 | # Forward request to remote station |
| 386 | try: |
| 387 | result = forward_request( |
| 388 | station_info=station_info, |
| 389 | object_id=object_id, |
| 390 | method='GET', |
| 391 | query_params=dict(request.GET), |
| 392 | timeout=30 |
| 393 | ) |
| 394 | return json_response(json.dumps(result)) |
| 395 | except requests.Timeout: |
| 396 | return json_error( |
| 397 | f'Timeout calling station {target_station}', |
| 398 | status=504 # Gateway Timeout |
| 399 | ) |
| 400 | except requests.RequestException as e: |
| 401 | return json_error( |
| 402 | f'Failed to call station {target_station}: {e}', |
| 403 | status=502 # Bad Gateway |
| 404 | ) |
| 405 | |
| 406 | # Smart load balancing (Phase 7.4) |
| 407 | # If no explicit station was specified, consider load-based routing |
| 408 | if not target_station: |
| 409 | # Check if this is an execution request (not metadata/source/logs) |
| 410 | is_execution = not any(param in request.GET for param in ['source', 'metadata', 'logs', 'versions']) |
| 411 | |
| 412 | if is_execution: |
| 413 | # Try to find a better station based on load |
| 414 | best_station = find_best_station(object_id) |
| 415 | |
| 416 | if best_station: |
| 417 | # Route to best station |
| 418 | try: |
| 419 | result = forward_request( |
| 420 | station_info=best_station, |
| 421 | object_id=object_id, |
| 422 | method='GET', |
| 423 | query_params=dict(request.GET), |
| 424 | timeout=30 |
| 425 | ) |
| 426 | result['_load_balanced'] = True |
| 427 | result['_original_station'] = os.environ.get('STATION_ID', 'unknown') |
| 428 | return json_response(json.dumps(result)) |
| 429 | except (requests.Timeout, requests.RequestException): |
| 430 | # If routing fails, fall through to local execution |
| 431 | pass |
| 432 | |
| 433 | # Local execution (either no @station_id or @local_station) |
| 434 | # Find object file |
| 435 | obj_file = find_object_file(object_id) |
| 436 | if not obj_file: |
| 437 | return json_error(f'Object not found: {object_id}', status=404) |
| 438 | |
| 439 | # Load object |
| 440 | try: |
| 441 | runtime = get_runtime() |
| 442 | obj = runtime.load_object(str(obj_file)) |
| 443 | except Exception as e: |
| 444 | return json_error(f'Failed to load object: {e}', status=500) |
| 445 | |
| 446 | # Check query parameters |
| 447 | query = request.GET |
| 448 | |
| 449 | # View source code |
| 450 | if query.get('source') == 'true': |
| 451 | try: |
| 452 | source = obj.get_source_code() |
| 453 | return json_response(json.dumps({ |
| 454 | 'status': 'ok', |
| 455 | 'object_id': object_id, |
| 456 | 'source': source, |
| 457 | })) |
| 458 | except Exception as e: |
| 459 | return json_error(f'Failed to get source: {e}', status=500) |
| 460 | |
| 461 | # View metadata |
| 462 | if query.get('metadata') == 'true': |
| 463 | try: |
| 464 | metadata = obj.get_metadata() |
| 465 | return json_response(json.dumps({ |
| 466 | 'status': 'ok', |
| 467 | 'object_id': object_id, |
| 468 | 'metadata': metadata, |
| 469 | })) |
| 470 | except Exception as e: |
| 471 | return json_error(f'Failed to get metadata: {e}', status=500) |
| 472 | |
| 473 | # View logs |
| 474 | if query.get('logs') == 'true': |
| 475 | try: |
| 476 | level = query.get('level') # Optional log level filter |
| 477 | limit_str = query.get('limit', '100') |
| 478 | limit = int(limit_str) if limit_str else 100 |
| 479 | |
| 480 | logs = obj.get_logs(level=level, limit=limit) |
| 481 | return json_response(json.dumps({ |
| 482 | 'status': 'ok', |
| 483 | 'object_id': object_id, |
| 484 | 'logs': logs, |
| 485 | 'count': len(logs), |
| 486 | })) |
| 487 | except Exception as e: |
| 488 | return json_error(f'Failed to get logs: {e}', status=500) |
| 489 | |
| 490 | # View version history |
| 491 | if query.get('versions') == 'true': |
| 492 | try: |
| 493 | limit_str = query.get('limit', '10') |
| 494 | limit = int(limit_str) if limit_str else 10 |
| 495 | |
| 496 | history = obj.get_version_history(limit=limit) |
| 497 | return json_response(json.dumps({ |
| 498 | 'status': 'ok', |
| 499 | 'object_id': object_id, |
| 500 | 'versions': history, |
| 501 | 'count': len(history), |
| 502 | })) |
| 503 | except Exception as e: |
| 504 | return json_error(f'Failed to get version history: {e}', status=500) |
| 505 | |
| 506 | # Get specific version |
| 507 | if query.get('version'): |
| 508 | try: |
| 509 | version_id = int(query.get('version')) |
| 510 | version_data = obj.get_version(version_id) |
| 511 | |
| 512 | if not version_data: |
| 513 | return json_error(f'Version not found: {version_id}', status=404) |
| 514 | |
| 515 | return json_response(json.dumps({ |
| 516 | 'status': 'ok', |
| 517 | 'object_id': object_id, |
| 518 | 'version': version_data, |
| 519 | })) |
| 520 | except ValueError: |
| 521 | return json_error('Invalid version number', status=400) |
| 522 | except Exception as e: |
| 523 | return json_error(f'Failed to get version: {e}', status=500) |
| 524 | |
| 525 | # Execute GET method (default) |
| 526 | try: |
| 527 | # Build request data from query parameters |
| 528 | req_data = dict(query) |
| 529 | |
| 530 | result = obj.execute('GET', req_data) |
| 531 | return json_response(json.dumps(result)) |
| 532 | except Exception as e: |
| 533 | import traceback |
| 534 | tb = traceback.format_exc() |
| 535 | |
| 536 | # Log error to object's own logs (self-contained debugging) |
| 537 | try: |
| 538 | obj.logger.error(f'GET execution failed: {e}', |
| 539 | error=str(e), |
| 540 | traceback=tb) |
| 541 | except: |
| 542 | pass # Don't fail if logging fails |
| 543 | |
| 544 | return json_error(f'Execution failed: {e}\n\n{tb}', status=500) |
| 545 | |
| 546 | |
| 547 | def POST(request, id: str): |
| 548 | """Execute object's POST method (supports cross-station routing)""" |
| 549 | # Parse routing syntax (Phase 7.2) |
| 550 | object_id, target_station = parse_object_routing(id) |
| 551 | |
| 552 | # Check if this should be routed to another station |
| 553 | if target_station: |
| 554 | local_station = os.environ.get('STATION_ID', 'unknown') |
| 555 | |
| 556 | # If target is not local station, route to remote |
| 557 | if target_station != local_station: |
| 558 | station_info = get_station_info(target_station) |
| 559 | |
| 560 | if not station_info: |
| 561 | return json_error( |
| 562 | f'Station not found or offline: {target_station}', |
| 563 | status=503 |
| 564 | ) |
| 565 | |
| 566 | # Parse request body |
| 567 | try: |
| 568 | if request.body: |
| 569 | body_data = json.loads(request.body.decode('utf-8')) |
| 570 | else: |
| 571 | body_data = dict(request.POST) if request.POST else dict(request.GET) |
| 572 | except json.JSONDecodeError as e: |
| 573 | return json_error(f'Invalid JSON: {e}', status=400) |
| 574 | |
| 575 | # Forward request |
| 576 | try: |
| 577 | result = forward_request( |
| 578 | station_info=station_info, |
| 579 | object_id=object_id, |
| 580 | method='POST', |
| 581 | query_params=dict(request.GET), |
| 582 | body_data=body_data, |
| 583 | timeout=30 |
| 584 | ) |
| 585 | return json_response(json.dumps(result)) |
| 586 | except requests.Timeout: |
| 587 | return json_error(f'Timeout calling station {target_station}', status=504) |
| 588 | except requests.RequestException as e: |
| 589 | return json_error(f'Failed to call station {target_station}: {e}', status=502) |
| 590 | |
| 591 | # Local execution |
| 592 | # Find object file |
| 593 | obj_file = find_object_file(object_id) |
| 594 | if not obj_file: |
| 595 | return json_error(f'Object not found: {object_id}', status=404) |
| 596 | |
| 597 | # Load object |
| 598 | try: |
| 599 | runtime = get_runtime() |
| 600 | obj = runtime.load_object(str(obj_file)) |
| 601 | except Exception as e: |
| 602 | return json_error(f'Failed to load object: {e}', status=500) |
| 603 | |
| 604 | # Parse request body as JSON |
| 605 | try: |
| 606 | if request.body: |
| 607 | req_data = json.loads(request.body.decode('utf-8')) |
| 608 | else: |
| 609 | # Fall back to form data or query params |
| 610 | req_data = dict(request.POST) if request.POST else dict(request.GET) |
| 611 | except json.JSONDecodeError as e: |
| 612 | return json_error(f'Invalid JSON: {e}', status=400) |
| 613 | |
| 614 | # Check for special actions |
| 615 | action = req_data.get('action') |
| 616 | |
| 617 | # Rollback to specific version |
| 618 | if action == 'rollback': |
| 619 | try: |
| 620 | version_id = req_data.get('version_id') |
| 621 | if not version_id: |
| 622 | return json_error('version_id required for rollback', status=400) |
| 623 | |
| 624 | version_id = int(version_id) |
| 625 | author = req_data.get('author', 'api_user') |
| 626 | message = req_data.get('message', f'Rollback to version {version_id}') |
| 627 | |
| 628 | obj.rollback_to_version(version_id, author=author, message=message) |
| 629 | |
| 630 | return json_response(json.dumps({ |
| 631 | 'status': 'ok', |
| 632 | 'message': f'Rolled back to version {version_id}', |
| 633 | 'version_id': version_id, |
| 634 | 'object_id': object_id, |
| 635 | })) |
| 636 | except ValueError as e: |
| 637 | return json_error(f'Invalid version_id: {e}', status=400) |
| 638 | except Exception as e: |
| 639 | import traceback |
| 640 | tb = traceback.format_exc() |
| 641 | return json_error(f'Rollback failed: {e}\n\n{tb}', status=500) |
| 642 | |
| 643 | # Execute POST method (default) |
| 644 | try: |
| 645 | result = obj.execute('POST', req_data) |
| 646 | return json_response(json.dumps(result)) |
| 647 | except Exception as e: |
| 648 | import traceback |
| 649 | tb = traceback.format_exc() |
| 650 | |
| 651 | # Log error to object's own logs (self-contained debugging) |
| 652 | try: |
| 653 | obj.logger.error(f'POST execution failed: {e}', |
| 654 | error=str(e), |
| 655 | traceback=tb) |
| 656 | except: |
| 657 | pass # Don't fail if logging fails |
| 658 | |
| 659 | return json_error(f'Execution failed: {e}\n\n{tb}', status=500) |
| 660 | |
| 661 | |
| 662 | def PUT(request, id: str): |
| 663 | """Execute object's PUT method or update code (supports cross-station routing)""" |
| 664 | # Parse routing syntax (Phase 7.2) |
| 665 | object_id, target_station = parse_object_routing(id) |
| 666 | |
| 667 | # Check if this should be routed to another station |
| 668 | if target_station: |
| 669 | local_station = os.environ.get('STATION_ID', 'unknown') |
| 670 | |
| 671 | # If target is not local station, route to remote |
| 672 | if target_station != local_station: |
| 673 | station_info = get_station_info(target_station) |
| 674 | |
| 675 | if not station_info: |
| 676 | return json_error( |
| 677 | f'Station not found or offline: {target_station}', |
| 678 | status=503 |
| 679 | ) |
| 680 | |
| 681 | # Parse request body |
| 682 | try: |
| 683 | if request.body: |
| 684 | body_data = json.loads(request.body.decode('utf-8')) |
| 685 | else: |
| 686 | body_data = dict(request.POST) if request.POST else dict(request.GET) |
| 687 | except json.JSONDecodeError as e: |
| 688 | return json_error(f'Invalid JSON: {e}', status=400) |
| 689 | |
| 690 | # Forward request |
| 691 | try: |
| 692 | result = forward_request( |
| 693 | station_info=station_info, |
| 694 | object_id=object_id, |
| 695 | method='PUT', |
| 696 | query_params=dict(request.GET), |
| 697 | body_data=body_data, |
| 698 | timeout=30 |
| 699 | ) |
| 700 | return json_response(json.dumps(result)) |
| 701 | except requests.Timeout: |
| 702 | return json_error(f'Timeout calling station {target_station}', status=504) |
| 703 | except requests.RequestException as e: |
| 704 | return json_error(f'Failed to call station {target_station}: {e}', status=502) |
| 705 | |
| 706 | # Local execution |
| 707 | # Find object file |
| 708 | obj_file = find_object_file(object_id) |
| 709 | if not obj_file: |
| 710 | return json_error(f'Object not found: {object_id}', status=404) |
| 711 | |
| 712 | # Load object |
| 713 | try: |
| 714 | runtime = get_runtime() |
| 715 | obj = runtime.load_object(str(obj_file)) |
| 716 | except Exception as e: |
| 717 | return json_error(f'Failed to load object: {e}', status=500) |
| 718 | |
| 719 | # Check if this is a code update |
| 720 | query = request.GET |
| 721 | if query.get('source') == 'true': |
| 722 | # Update source code |
| 723 | try: |
| 724 | if not request.body: |
| 725 | return json_error('Missing request body', status=400) |
| 726 | |
| 727 | data = json.loads(request.body.decode('utf-8')) |
| 728 | |
| 729 | new_code = data.get('code') |
| 730 | author = data.get('author', 'api') |
| 731 | message = data.get('message', 'Updated via API') |
| 732 | |
| 733 | if not new_code: |
| 734 | return json_error('Missing field: code', status=400) |
| 735 | |
| 736 | version_id = obj.update_code( |
| 737 | new_code=new_code, |
| 738 | author=author, |
| 739 | message=message, |
| 740 | ) |
| 741 | |
| 742 | return json_response(json.dumps({ |
| 743 | 'status': 'ok', |
| 744 | 'message': f'Code updated to version {version_id}', |
| 745 | 'version_id': version_id, |
| 746 | 'object_id': object_id, |
| 747 | })) |
| 748 | except Exception as e: |
| 749 | import traceback |
| 750 | tb = traceback.format_exc() |
| 751 | return json_error(f'Update failed: {e}\n\n{tb}', status=500) |
| 752 | |
| 753 | # Execute PUT method (default) |
| 754 | try: |
| 755 | if request.body: |
| 756 | req_data = json.loads(request.body.decode('utf-8')) |
| 757 | else: |
| 758 | req_data = dict(request.POST) if request.POST else dict(request.GET) |
| 759 | |
| 760 | result = obj.execute('PUT', req_data) |
| 761 | return json_response(json.dumps(result)) |
| 762 | except Exception as e: |
| 763 | import traceback |
| 764 | tb = traceback.format_exc() |
| 765 | |
| 766 | # Log error to object's own logs (self-contained debugging) |
| 767 | try: |
| 768 | obj.logger.error(f'PUT execution failed: {e}', |
| 769 | error=str(e), |
| 770 | traceback=tb) |
| 771 | except: |
| 772 | pass # Don't fail if logging fails |
| 773 | |
| 774 | return json_error(f'Execution failed: {e}\n\n{tb}', status=500) |
| 775 | |
| 776 | |
| 777 | def DELETE(request, id: str): |
| 778 | """Execute object's DELETE method (supports cross-station routing)""" |
| 779 | # Parse routing syntax (Phase 7.2) |
| 780 | object_id, target_station = parse_object_routing(id) |
| 781 | |
| 782 | # Check if this should be routed to another station |
| 783 | if target_station: |
| 784 | local_station = os.environ.get('STATION_ID', 'unknown') |
| 785 | |
| 786 | # If target is not local station, route to remote |
| 787 | if target_station != local_station: |
| 788 | station_info = get_station_info(target_station) |
| 789 | |
| 790 | if not station_info: |
| 791 | return json_error( |
| 792 | f'Station not found or offline: {target_station}', |
| 793 | status=503 |
| 794 | ) |
| 795 | |
| 796 | # Parse request body |
| 797 | try: |
| 798 | if request.body: |
| 799 | body_data = json.loads(request.body.decode('utf-8')) |
| 800 | else: |
| 801 | body_data = dict(request.POST) if request.POST else dict(request.GET) |
| 802 | except json.JSONDecodeError as e: |
| 803 | return json_error(f'Invalid JSON: {e}', status=400) |
| 804 | |
| 805 | # Forward request |
| 806 | try: |
| 807 | result = forward_request( |
| 808 | station_info=station_info, |
| 809 | object_id=object_id, |
| 810 | method='DELETE', |
| 811 | query_params=dict(request.GET), |
| 812 | body_data=body_data, |
| 813 | timeout=30 |
| 814 | ) |
| 815 | return json_response(json.dumps(result)) |
| 816 | except requests.Timeout: |
| 817 | return json_error(f'Timeout calling station {target_station}', status=504) |
| 818 | except requests.RequestException as e: |
| 819 | return json_error(f'Failed to call station {target_station}: {e}', status=502) |
| 820 | |
| 821 | # Local execution |
| 822 | # Find object file |
| 823 | obj_file = find_object_file(object_id) |
| 824 | if not obj_file: |
| 825 | return json_error(f'Object not found: {object_id}', status=404) |
| 826 | |
| 827 | # Load object |
| 828 | try: |
| 829 | runtime = get_runtime() |
| 830 | obj = runtime.load_object(str(obj_file)) |
| 831 | except Exception as e: |
| 832 | return json_error(f'Failed to load object: {e}', status=500) |
| 833 | |
| 834 | # Parse request data |
| 835 | try: |
| 836 | if request.body: |
| 837 | req_data = json.loads(request.body.decode('utf-8')) |
| 838 | else: |
| 839 | req_data = dict(request.POST) if request.POST else dict(request.GET) |
| 840 | except json.JSONDecodeError as e: |
| 841 | return json_error(f'Invalid JSON: {e}', status=400) |
| 842 | |
| 843 | # Execute DELETE method |
| 844 | try: |
| 845 | result = obj.execute('DELETE', req_data) |
| 846 | return json_response(json.dumps(result)) |
| 847 | except Exception as e: |
| 848 | import traceback |
| 849 | tb = traceback.format_exc() |
| 850 | |
| 851 | # Log error to object's own logs (self-contained debugging) |
| 852 | try: |
| 853 | obj.logger.error(f'DELETE execution failed: {e}', |
| 854 | error=str(e), |
| 855 | traceback=tb) |
| 856 | except: |
| 857 | pass # Don't fail if logging fails |
| 858 | |
| 859 | return json_error(f'Execution failed: {e}\n\n{tb}', status=500) |