askrobots / dbbasic-object-primitive
Public
Python functions as REST objects, with clustering, load balancing and state replication; no containers or orchestration.
heartbeat.py · 2.7 KB · 93 lines
| 1 | """ |
| 2 | Cluster Heartbeat |
| 3 | |
| 4 | POST /cluster/heartbeat - Send heartbeat to master |
| 5 | |
| 6 | Workers send periodic heartbeats to master to stay in registry. |
| 7 | Master updates last_heartbeat timestamp for the station. |
| 8 | """ |
| 9 | import json |
| 10 | import os |
| 11 | import time |
| 12 | from pathlib import Path |
| 13 | from dbbasic_web.responses import json as json_response |
| 14 | |
| 15 | |
| 16 | def POST(request): |
| 17 | """Send heartbeat to master""" |
| 18 | # Parse JSON from request body |
| 19 | try: |
| 20 | if request.body: |
| 21 | data = json.loads(request.body.decode('utf-8')) |
| 22 | else: |
| 23 | data = {} |
| 24 | except json.JSONDecodeError: |
| 25 | data = {} |
| 26 | |
| 27 | station_id = data.get('station_id') |
| 28 | host = data.get('host') |
| 29 | port = data.get('port', 8001) |
| 30 | metrics = data.get('metrics', {}) |
| 31 | version = data.get('version', 'unknown') |
| 32 | |
| 33 | if not station_id or not host: |
| 34 | return json_response(json.dumps({ |
| 35 | 'status': 'error', |
| 36 | 'message': 'station_id and host are required' |
| 37 | })) |
| 38 | |
| 39 | # Update registry with heartbeat |
| 40 | data_dir = Path('data/cluster') |
| 41 | data_dir.mkdir(parents=True, exist_ok=True) |
| 42 | registry_file = data_dir / 'stations.tsv' |
| 43 | |
| 44 | current_time = time.time() |
| 45 | |
| 46 | # Read existing registry |
| 47 | existing = {} |
| 48 | header = None |
| 49 | if registry_file.exists(): |
| 50 | with open(registry_file, 'r') as f: |
| 51 | for line_num, line in enumerate(f): |
| 52 | # Skip and preserve header row |
| 53 | if line_num == 0 and line.strip().startswith('station_id'): |
| 54 | header = line.strip() |
| 55 | continue |
| 56 | |
| 57 | if line.strip(): |
| 58 | parts = line.strip().split('\t') |
| 59 | if len(parts) >= 4: |
| 60 | sid = parts[0] |
| 61 | existing[sid] = parts |
| 62 | |
| 63 | # Update this station's heartbeat (with metrics as JSON in 5th column, version in 6th) |
| 64 | metrics_json = json.dumps(metrics) if metrics else '{}' |
| 65 | existing[station_id] = [station_id, host, str(port), str(current_time), metrics_json, version] |
| 66 | |
| 67 | # Write back |
| 68 | with open(registry_file, 'w') as f: |
| 69 | # Write header if we had one |
| 70 | if header: |
| 71 | f.write(header + '\n') |
| 72 | |
| 73 | for sid, parts in sorted(existing.items()): |
| 74 | f.write('\t'.join(parts) + '\n') |
| 75 | |
| 76 | return json_response(json.dumps({ |
| 77 | 'status': 'ok', |
| 78 | 'message': 'Heartbeat received', |
| 79 | 'station_id': station_id, |
| 80 | 'timestamp': current_time |
| 81 | })) |
| 82 | |
| 83 | |
| 84 | def GET(request): |
| 85 | """Get heartbeat status (for monitoring)""" |
| 86 | my_station_id = os.environ.get('STATION_ID', 'unknown') |
| 87 | |
| 88 | return json_response(json.dumps({ |
| 89 | 'status': 'ok', |
| 90 | 'station_id': my_station_id, |
| 91 | 'timestamp': time.time(), |
| 92 | 'message': 'Heartbeat endpoint active' |
| 93 | })) |