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
replicate.py · 3.4 KB · 123 lines
1"""
2Cluster State Replication
3
4POST /cluster/replicate - Receive state replication from another station
5
6Used for high availability: when an object updates its state on station1,
7it automatically replicates to station2 and station3. If station1 fails,
8objects can read state from replicas.
9"""
10import json
11import os
12import time
13from pathlib import Path
14from dbbasic_web.responses import json as json_response, json_error
15
16
17def POST(request):
18 """
19 Receive state replication from another station
20
21 Request body:
22 {
23 "object_id": str,
24 "key": str,
25 "value": str,
26 "timestamp": float,
27 "source_station": str
28 }
29
30 Response:
31 {
32 "status": "ok",
33 "message": "State replicated",
34 "object_id": str,
35 "key": str
36 }
37 """
38 try:
39 if request.body:
40 data = json.loads(request.body.decode('utf-8'))
41 else:
42 return json_error('Request body required', status=400)
43 except json.JSONDecodeError:
44 return json_error('Invalid JSON', status=400)
45
46 object_id = data.get('object_id')
47 key = data.get('key')
48 value = data.get('value')
49 timestamp = data.get('timestamp')
50 source_station = data.get('source_station')
51
52 if not all([object_id, key, value is not None, timestamp, source_station]):
53 return json_error(
54 'Missing required fields: object_id, key, value, timestamp, source_station',
55 status=400
56 )
57
58 # Write to local state (replica)
59 state_dir = Path(f'data/state/{object_id}')
60 state_dir.mkdir(parents=True, exist_ok=True)
61 state_file = state_dir / 'state.tsv'
62
63 # Read existing state
64 existing = {}
65 if state_file.exists():
66 with open(state_file, 'r') as f:
67 for line in f:
68 if line.strip():
69 parts = line.strip().split('\t')
70 if len(parts) >= 3:
71 k, v, ts = parts[0], parts[1], float(parts[2])
72 existing[k] = (v, ts)
73
74 # Check if we should accept this update (last-write-wins)
75 if key in existing:
76 _, existing_ts = existing[key]
77 if timestamp <= existing_ts:
78 # Existing value is newer, reject this update
79 return json_response(json.dumps({
80 'status': 'ok',
81 'message': 'Replica already has newer value',
82 'object_id': object_id,
83 'key': key,
84 'rejected': True
85 }))
86
87 # Update with new value
88 existing[key] = (value, timestamp)
89
90 # Write back to file
91 with open(state_file, 'w') as f:
92 for k, (v, ts) in sorted(existing.items()):
93 f.write(f'{k}\t{v}\t{ts}\n')
94
95 return json_response(json.dumps({
96 'status': 'ok',
97 'message': 'State replicated',
98 'object_id': object_id,
99 'key': key,
100 'source_station': source_station,
101 'timestamp': timestamp
102 }))
103
104
105def GET(request):
106 """
107 Get replication status for monitoring
108
109 Response:
110 {
111 "status": "ok",
112 "station_id": str,
113 "message": "Replication endpoint active"
114 }
115 """
116 station_id = os.environ.get('STATION_ID', 'unknown')
117
118 return json_response(json.dumps({
119 'status': 'ok',
120 'station_id': station_id,
121 'message': 'Replication endpoint active',
122 'timestamp': time.time()
123 }))