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.4 KB · 83 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 if registry_file.exists():
49 with open(registry_file, 'r') as f:
50 for line in f:
51 if line.strip():
52 parts = line.strip().split('\t')
53 if len(parts) >= 4:
54 sid = parts[0]
55 existing[sid] = parts
56
57 # Update this station's heartbeat (with metrics as JSON in 5th column, version in 6th)
58 metrics_json = json.dumps(metrics) if metrics else '{}'
59 existing[station_id] = [station_id, host, str(port), str(current_time), metrics_json, version]
60
61 # Write back
62 with open(registry_file, 'w') as f:
63 for sid, parts in sorted(existing.items()):
64 f.write('\t'.join(parts) + '\n')
65
66 return json_response(json.dumps({
67 'status': 'ok',
68 'message': 'Heartbeat received',
69 'station_id': station_id,
70 'timestamp': current_time
71 }))
72
73
74def GET(request):
75 """Get heartbeat status (for monitoring)"""
76 my_station_id = os.environ.get('STATION_ID', 'unknown')
77
78 return json_response(json.dumps({
79 'status': 'ok',
80 'station_id': my_station_id,
81 'timestamp': time.time(),
82 'message': 'Heartbeat endpoint active'
83 }))