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
heartbeat.py · 2.7 KB · 93 lines
1"""
2Cluster Heartbeat
3
4POST /cluster/heartbeat - Send heartbeat to master
5
6Workers send periodic heartbeats to master to stay in registry.
7Master updates last_heartbeat timestamp for the station.
8"""
9import json
10import os
11import time
12from pathlib import Path
13from dbbasic_web.responses import json as json_response
14
15
16def 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
84def 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 }))