Python functions as REST objects, with clustering, load balancing and state replication; no containers or orchestration.

0 downloads

Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-object-primitive.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-object-primitive.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-object-primitive.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

Dan Q Consolidate duplicate QUICKSTARTs on the top-level file 503f830 7 months ago History
[id].py · 37.3 KB · 1099 lines
1"""
2API handler for individual objects
3
4GET /objects/{id} - Execute object's GET method
5GET /objects/{id}?source=true - View object's source code
6GET /objects/{id}?metadata=true - View object metadata
7GET /objects/{id}?logs=true - View object logs
8GET /objects/{id}?versions=true - View version history
9GET /objects/{id}?version=N - Get specific version
10
11POST /objects/{id} - Execute object's POST method
12POST /objects/{id} (action=rollback) - Rollback to specific version
13PUT /objects/{id} - Execute object's PUT method or update code
14DELETE /objects/{id} - Execute object's DELETE method
15
16Cross-station routing (Phase 7.2):
17GET /objects/{id}@{station_id} - Execute object on remote station
18"""
19import json
20import os
21import time
22import requests
23from pathlib import Path
24from dbbasic_web.responses import json as json_response, json_error
25
26from dbbasic_object_core.runtime.object_runtime import ObjectRuntime
27
28
29# Initialize runtime (shared across requests)
30_runtime = None
31
32
33def 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
41def 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
76def 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
93def 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
156def 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
221def 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
239def 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
293def 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
349def 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/test)
410 is_execution = not any(param in request.GET for param in ['source', 'metadata', 'logs', 'versions', 'test', 'state', 'status'])
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), object_id=object_id)
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 state
474 if query.get('state') == 'true':
475 try:
476 state = obj.get_state()
477 return json_response(json.dumps({
478 'status': 'ok',
479 'object_id': object_id,
480 'state': state,
481 }))
482 except Exception as e:
483 return json_error(f'Failed to get state: {e}', status=500)
484
485 # Get schedule status
486 if query.get('status') == 'true':
487 try:
488 schedules = runtime.get_schedules(object_id)
489 return json_response(json.dumps({
490 'status': 'ok',
491 'object_id': object_id,
492 'running': len(schedules) > 0,
493 'schedules': schedules
494 }))
495 except Exception as e:
496 return json_error(f'Failed to get status: {e}', status=500)
497
498 # Download file
499 if query.get('file'):
500 filename = query.get('file')
501 try:
502 content = obj.file_manager.get(filename)
503
504 # Detect content type from file extension
505 import mimetypes
506 content_type, _ = mimetypes.guess_type(filename)
507 if content_type is None:
508 content_type = 'application/octet-stream'
509
510 # Build headers
511 headers = [
512 ('content-type', content_type),
513 ]
514
515 # For images, use inline; for others, use attachment
516 if content_type.startswith('image/'):
517 headers.append(('content-disposition', f'inline; filename="{filename}"'))
518 else:
519 headers.append(('content-disposition', f'attachment; filename="{filename}"'))
520
521 # Return binary response (status, headers, body)
522 return 200, headers, [content]
523
524 except FileNotFoundError:
525 return json_error(f'File not found: {filename}', status=404)
526 except Exception as e:
527 return json_error(f'Failed to get file: {e}', status=500)
528
529 # List files
530 if query.get('files') == 'true':
531 try:
532 files = obj.file_manager.list()
533 return json_response(json.dumps({
534 'status': 'ok',
535 'object_id': object_id,
536 'files': files,
537 'count': len(files)
538 }))
539 except Exception as e:
540 return json_error(f'Failed to list files: {e}', status=500)
541
542 # Run tests (dogfooding - objects test themselves!)
543 if query.get('test') == 'true':
544 try:
545 # Get the underlying module (obj.endpoint contains the actual loaded module)
546 module = obj.endpoint
547
548 # Find all test methods (functions starting with test_)
549 test_methods = []
550 for name in dir(module):
551 if name.startswith('test_') and callable(getattr(module, name)):
552 test_methods.append(name)
553
554 if not test_methods:
555 return json_response(json.dumps({
556 'status': 'ok',
557 'object_id': object_id,
558 'message': 'No tests found (no test_* methods)',
559 'test_count': 0,
560 'results': []
561 }))
562
563 # Run each test
564 results = []
565 passed = 0
566 failed = 0
567 skipped = 0
568
569 for test_name in test_methods:
570 test_func = getattr(module, test_name)
571
572 start_time = time.time()
573 try:
574 result = test_func()
575 exec_time_ms = (time.time() - start_time) * 1000
576
577 # Normalize result
578 if isinstance(result, dict):
579 status = result.get('status', 'pass')
580 else:
581 status = 'pass'
582
583 if status == 'pass':
584 passed += 1
585 elif status == 'skip':
586 skipped += 1
587 else:
588 failed += 1
589
590 results.append({
591 'test': test_name,
592 'status': status,
593 'exec_time_ms': round(exec_time_ms, 2),
594 'result': result if isinstance(result, dict) else {'status': status}
595 })
596
597 except AssertionError as e:
598 exec_time_ms = (time.time() - start_time) * 1000
599 failed += 1
600 results.append({
601 'test': test_name,
602 'status': 'fail',
603 'exec_time_ms': round(exec_time_ms, 2),
604 'error': str(e),
605 'error_type': 'AssertionError'
606 })
607
608 except Exception as e:
609 exec_time_ms = (time.time() - start_time) * 1000
610 failed += 1
611 results.append({
612 'test': test_name,
613 'status': 'error',
614 'exec_time_ms': round(exec_time_ms, 2),
615 'error': str(e),
616 'error_type': type(e).__name__
617 })
618
619 # Determine overall status
620 overall_status = 'pass' if failed == 0 else 'fail'
621
622 return json_response(json.dumps({
623 'status': overall_status,
624 'object_id': object_id,
625 'test_count': len(test_methods),
626 'passed': passed,
627 'failed': failed,
628 'skipped': skipped,
629 'results': results
630 }))
631 except Exception as e:
632 return json_error(f'Failed to run tests: {e}', status=500)
633
634 # View logs
635 if query.get('logs') == 'true':
636 try:
637 level = query.get('level') # Optional log level filter
638 limit_str = query.get('limit', '100')
639 limit = int(limit_str) if limit_str else 100
640
641 logs = obj.get_logs(level=level, limit=limit)
642 return json_response(json.dumps({
643 'status': 'ok',
644 'object_id': object_id,
645 'logs': logs,
646 'count': len(logs),
647 }))
648 except Exception as e:
649 return json_error(f'Failed to get logs: {e}', status=500)
650
651 # View version history
652 if query.get('versions') == 'true':
653 try:
654 limit_str = query.get('limit', '10')
655 limit = int(limit_str) if limit_str else 10
656
657 history = obj.get_version_history(limit=limit)
658 return json_response(json.dumps({
659 'status': 'ok',
660 'object_id': object_id,
661 'versions': history,
662 'count': len(history),
663 }))
664 except Exception as e:
665 return json_error(f'Failed to get version history: {e}', status=500)
666
667 # Get specific version
668 if query.get('version'):
669 try:
670 version_id = int(query.get('version'))
671 version_data = obj.get_version(version_id)
672
673 if not version_data:
674 return json_error(f'Version not found: {version_id}', status=404)
675
676 return json_response(json.dumps({
677 'status': 'ok',
678 'object_id': object_id,
679 'version': version_data,
680 }))
681 except ValueError:
682 return json_error('Invalid version number', status=400)
683 except Exception as e:
684 return json_error(f'Failed to get version: {e}', status=500)
685
686 # Execute GET method (default)
687 try:
688 # Build request data from query parameters
689 req_data = dict(query)
690
691 result = obj.execute('GET', req_data)
692
693 # Check if result specifies a content type (for HTML, images, etc.)
694 if isinstance(result, dict) and result.get('content_type'):
695 content_type = result.get('content_type')
696 body = result.get('body', b'')
697
698 # Build headers
699 headers = [('content-type', content_type)]
700
701 # Return binary/text response
702 if isinstance(body, bytes):
703 return 200, headers, [body]
704 else:
705 from dbbasic_web.responses import html as html_response
706 return html_response(body)
707
708 return json_response(json.dumps(result))
709 except Exception as e:
710 import traceback
711 tb = traceback.format_exc()
712
713 # Log error to object's own logs (self-contained debugging)
714 try:
715 obj.logger.error(f'GET execution failed: {e}',
716 error=str(e),
717 traceback=tb)
718 except:
719 pass # Don't fail if logging fails
720
721 return json_error(f'Execution failed: {e}\n\n{tb}', status=500)
722
723
724def POST(request, id: str):
725 """Execute object's POST method (supports cross-station routing)"""
726 # Parse routing syntax (Phase 7.2)
727 object_id, target_station = parse_object_routing(id)
728
729 # Check if this should be routed to another station
730 if target_station:
731 local_station = os.environ.get('STATION_ID', 'unknown')
732
733 # If target is not local station, route to remote
734 if target_station != local_station:
735 station_info = get_station_info(target_station)
736
737 if not station_info:
738 return json_error(
739 f'Station not found or offline: {target_station}',
740 status=503
741 )
742
743 # Parse request body
744 try:
745 if request.body:
746 body_data = json.loads(request.body.decode('utf-8'))
747 else:
748 body_data = dict(request.POST) if request.POST else dict(request.GET)
749 except json.JSONDecodeError as e:
750 return json_error(f'Invalid JSON: {e}', status=400)
751
752 # Forward request
753 try:
754 result = forward_request(
755 station_info=station_info,
756 object_id=object_id,
757 method='POST',
758 query_params=dict(request.GET),
759 body_data=body_data,
760 timeout=30
761 )
762 return json_response(json.dumps(result))
763 except requests.Timeout:
764 return json_error(f'Timeout calling station {target_station}', status=504)
765 except requests.RequestException as e:
766 return json_error(f'Failed to call station {target_station}: {e}', status=502)
767
768 # Local execution
769 # Find object file
770 obj_file = find_object_file(object_id)
771 if not obj_file:
772 return json_error(f'Object not found: {object_id}', status=404)
773
774 # Load object
775 try:
776 runtime = get_runtime()
777 obj = runtime.load_object(str(obj_file), object_id=object_id)
778 except Exception as e:
779 return json_error(f'Failed to load object: {e}', status=500)
780
781 # Check for file upload (multipart/form-data)
782 files = request.get('files', {})
783 if files and len(files) > 0:
784 try:
785 uploaded_files = []
786
787 for field_name, file_data in files.items():
788 # file_data is a dict with 'filename', 'content', 'content_type'
789 filename = file_data.get('filename', field_name)
790 content = file_data.get('content', b'')
791
792 # Store using FileManager
793 obj.file_manager.put(filename, content)
794
795 uploaded_files.append({
796 'filename': filename,
797 'size': len(content),
798 'field': field_name
799 })
800
801 return json_response(json.dumps({
802 'status': 'ok',
803 'message': f'Uploaded {len(uploaded_files)} file(s)',
804 'object_id': object_id,
805 'files': uploaded_files
806 }))
807 except Exception as e:
808 return json_error(f'File upload failed: {e}', status=500)
809
810 # Parse request body as JSON
811 try:
812 if request.body:
813 req_data = json.loads(request.body.decode('utf-8'))
814 else:
815 # Fall back to form data or query params
816 req_data = dict(request.POST) if request.POST else dict(request.GET)
817 except UnicodeDecodeError as e:
818 # Binary data (file upload) that wasn't caught above
819 return json_error(f'Binary data in request body. Use ?file= parameter for file upload or ensure request.files is properly set. Debug: {e}', status=400)
820 except json.JSONDecodeError as e:
821 return json_error(f'Invalid JSON: {e}', status=400)
822
823 # Check for special actions
824 action = req_data.get('action')
825
826 # Rollback to specific version
827 if action == 'rollback':
828 try:
829 version_id = req_data.get('version_id')
830 if not version_id:
831 return json_error('version_id required for rollback', status=400)
832
833 version_id = int(version_id)
834 author = req_data.get('author', 'api_user')
835 message = req_data.get('message', f'Rollback to version {version_id}')
836
837 obj.rollback_to_version(version_id, author=author, message=message)
838
839 return json_response(json.dumps({
840 'status': 'ok',
841 'message': f'Rolled back to version {version_id}',
842 'version_id': version_id,
843 'object_id': object_id,
844 }))
845
846 except Exception as e:
847 return json_error(f'Rollback failed: {e}', status=500)
848
849 # Start scheduled execution
850 if action == 'start':
851 try:
852 # Call the object's start() method if it exists
853 if hasattr(obj.endpoint, 'start'):
854 result = obj.endpoint.start(req_data)
855 return json_response(json.dumps({
856 'status': 'ok',
857 'message': 'Object started',
858 'object_id': object_id,
859 'result': result
860 }))
861 else:
862 return json_error('Object has no start() method', status=400)
863 except Exception as e:
864 return json_error(f'Start failed: {e}', status=500)
865
866 # Stop scheduled execution
867 if action == 'stop':
868 try:
869 # Call the object's stop() method if it exists
870 if hasattr(obj.endpoint, 'stop'):
871 result = obj.endpoint.stop(req_data)
872 return json_response(json.dumps({
873 'status': 'ok',
874 'message': 'Object stopped',
875 'object_id': object_id,
876 'result': result
877 }))
878 else:
879 return json_error('Object has no stop() method', status=400)
880 except Exception as e:
881 return json_error(f'Stop failed: {e}', status=500)
882
883 # Execute POST method (default - no special action)
884 try:
885 result = obj.execute('POST', req_data)
886 return json_response(json.dumps(result))
887 except Exception as e:
888 import traceback
889 tb = traceback.format_exc()
890
891 # Log error to object's own logs (self-contained debugging)
892 try:
893 obj.logger.error(f'POST execution failed: {e}',
894 error=str(e),
895 traceback=tb)
896 except:
897 pass # Don't fail if logging fails
898
899 return json_error(f'Execution failed: {e}\n\n{tb}', status=500)
900
901
902def PUT(request, id: str):
903 """Execute object's PUT method or update code (supports cross-station routing)"""
904 # Parse routing syntax (Phase 7.2)
905 object_id, target_station = parse_object_routing(id)
906
907 # Check if this should be routed to another station
908 if target_station:
909 local_station = os.environ.get('STATION_ID', 'unknown')
910
911 # If target is not local station, route to remote
912 if target_station != local_station:
913 station_info = get_station_info(target_station)
914
915 if not station_info:
916 return json_error(
917 f'Station not found or offline: {target_station}',
918 status=503
919 )
920
921 # Parse request body
922 try:
923 if request.body:
924 body_data = json.loads(request.body.decode('utf-8'))
925 else:
926 body_data = dict(request.POST) if request.POST else dict(request.GET)
927 except json.JSONDecodeError as e:
928 return json_error(f'Invalid JSON: {e}', status=400)
929
930 # Forward request
931 try:
932 result = forward_request(
933 station_info=station_info,
934 object_id=object_id,
935 method='PUT',
936 query_params=dict(request.GET),
937 body_data=body_data,
938 timeout=30
939 )
940 return json_response(json.dumps(result))
941 except requests.Timeout:
942 return json_error(f'Timeout calling station {target_station}', status=504)
943 except requests.RequestException as e:
944 return json_error(f'Failed to call station {target_station}: {e}', status=502)
945
946 # Local execution
947 # Find object file
948 obj_file = find_object_file(object_id)
949 if not obj_file:
950 return json_error(f'Object not found: {object_id}', status=404)
951
952 # Load object
953 try:
954 runtime = get_runtime()
955 obj = runtime.load_object(str(obj_file), object_id=object_id)
956 except Exception as e:
957 return json_error(f'Failed to load object: {e}', status=500)
958
959 # Check if this is a code update
960 query = request.GET
961 if query.get('source') == 'true':
962 # Update source code
963 try:
964 if not request.body:
965 return json_error('Missing request body', status=400)
966
967 data = json.loads(request.body.decode('utf-8'))
968
969 new_code = data.get('code')
970 author = data.get('author', 'api')
971 message = data.get('message', 'Updated via API')
972
973 if not new_code:
974 return json_error('Missing field: code', status=400)
975
976 version_id = obj.update_code(
977 new_code=new_code,
978 author=author,
979 message=message,
980 )
981
982 return json_response(json.dumps({
983 'status': 'ok',
984 'message': f'Code updated to version {version_id}',
985 'version_id': version_id,
986 'object_id': object_id,
987 }))
988 except Exception as e:
989 import traceback
990 tb = traceback.format_exc()
991 return json_error(f'Update failed: {e}\n\n{tb}', status=500)
992
993 # Execute PUT method (default)
994 try:
995 if request.body:
996 req_data = json.loads(request.body.decode('utf-8'))
997 else:
998 req_data = dict(request.POST) if request.POST else dict(request.GET)
999
1000 result = obj.execute('PUT', req_data)
1001 return json_response(json.dumps(result))
1002 except Exception as e:
1003 import traceback
1004 tb = traceback.format_exc()
1005
1006 # Log error to object's own logs (self-contained debugging)
1007 try:
1008 obj.logger.error(f'PUT execution failed: {e}',
1009 error=str(e),
1010 traceback=tb)
1011 except:
1012 pass # Don't fail if logging fails
1013
1014 return json_error(f'Execution failed: {e}\n\n{tb}', status=500)
1015
1016
1017def DELETE(request, id: str):
1018 """Execute object's DELETE method (supports cross-station routing)"""
1019 # Parse routing syntax (Phase 7.2)
1020 object_id, target_station = parse_object_routing(id)
1021
1022 # Check if this should be routed to another station
1023 if target_station:
1024 local_station = os.environ.get('STATION_ID', 'unknown')
1025
1026 # If target is not local station, route to remote
1027 if target_station != local_station:
1028 station_info = get_station_info(target_station)
1029
1030 if not station_info:
1031 return json_error(
1032 f'Station not found or offline: {target_station}',
1033 status=503
1034 )
1035
1036 # Parse request body
1037 try:
1038 if request.body:
1039 body_data = json.loads(request.body.decode('utf-8'))
1040 else:
1041 body_data = dict(request.POST) if request.POST else dict(request.GET)
1042 except json.JSONDecodeError as e:
1043 return json_error(f'Invalid JSON: {e}', status=400)
1044
1045 # Forward request
1046 try:
1047 result = forward_request(
1048 station_info=station_info,
1049 object_id=object_id,
1050 method='DELETE',
1051 query_params=dict(request.GET),
1052 body_data=body_data,
1053 timeout=30
1054 )
1055 return json_response(json.dumps(result))
1056 except requests.Timeout:
1057 return json_error(f'Timeout calling station {target_station}', status=504)
1058 except requests.RequestException as e:
1059 return json_error(f'Failed to call station {target_station}: {e}', status=502)
1060
1061 # Local execution
1062 # Find object file
1063 obj_file = find_object_file(object_id)
1064 if not obj_file:
1065 return json_error(f'Object not found: {object_id}', status=404)
1066
1067 # Load object
1068 try:
1069 runtime = get_runtime()
1070 obj = runtime.load_object(str(obj_file), object_id=object_id)
1071 except Exception as e:
1072 return json_error(f'Failed to load object: {e}', status=500)
1073
1074 # Parse request data
1075 try:
1076 if request.body:
1077 req_data = json.loads(request.body.decode('utf-8'))
1078 else:
1079 req_data = dict(request.POST) if request.POST else dict(request.GET)
1080 except json.JSONDecodeError as e:
1081 return json_error(f'Invalid JSON: {e}', status=400)
1082
1083 # Execute DELETE method
1084 try:
1085 result = obj.execute('DELETE', req_data)
1086 return json_response(json.dumps(result))
1087 except Exception as e:
1088 import traceback
1089 tb = traceback.format_exc()
1090
1091 # Log error to object's own logs (self-contained debugging)
1092 try:
1093 obj.logger.error(f'DELETE execution failed: {e}',
1094 error=str(e),
1095 traceback=tb)
1096 except:
1097 pass # Don't fail if logging fails
1098
1099 return json_error(f'Execution failed: {e}\n\n{tb}', status=500)