ascii-chat
Binary v0.16.114-28-gf5913657f
Library lib/v0.3.2-3302-gf5913657f
Video chat in your terminal
Loading...
Searching...
No Matches
handoff.c
Go to the documentation of this file.
3#include <ascii-chat/otel.h>
5#include <string.h>
6
7static uint32_t read32(const uint8_t *p) {
8 return ((uint32_t)p[0] << 24) | ((uint32_t)p[1] << 16) | ((uint32_t)p[2] << 8) | p[3];
9}
10static void write32(uint8_t *p, uint32_t n) {
11 p[0] = (uint8_t)(n >> 24);
12 p[1] = (uint8_t)(n >> 16);
13 p[2] = (uint8_t)(n >> 8);
14 p[3] = (uint8_t)n;
15}
17 if (!data || !m || length < CONSENSUS_HANDOFF_HEADER)
18 return SET_ERRNO(ERROR_INVALID_PARAM, "Truncated handoff frame");
19 const uint8_t *p = data;
22 return SET_ERRNO(ERROR_NETWORK_PROTOCOL, "Invalid handoff version, kind or length");
23 memset(m, 0, sizeof(*m));
24 m->kind = p[1];
25 memcpy(m->session, p + 4, SESSION_ID_SIZE);
26 memcpy(m->participant, p + 20, SESSION_ID_SIZE);
27 m->generation = read32(p + 36);
28 m->sequence = read32(p + 40);
29 m->upload_kbps = read32(p + 44);
30 m->rtt_ms = read32(p + 48);
31 m->capabilities = p[52];
32 m->nat_tier = p[53];
33 m->port = (uint16_t)((p[54] << 8) | p[55]);
34 return ASCIICHAT_OK;
35}
37 memset(out, 0, CONSENSUS_HANDOFF_HEADER);
39 out[1] = m->kind;
40 memcpy(out + 4, m->session, SESSION_ID_SIZE);
41 memcpy(out + 20, m->participant, SESSION_ID_SIZE);
42 write32(out + 36, m->generation);
43 write32(out + 40, m->sequence);
44 write32(out + 44, m->upload_kbps);
45 write32(out + 48, m->rtt_ms);
46 out[52] = m->capabilities;
47 out[53] = m->nat_tier;
48 out[54] = (uint8_t)(m->port >> 8);
49 out[55] = (uint8_t)m->port;
50}
52 memset(s, 0, sizeof(*s));
53 memcpy(s->session, session, SESSION_ID_SIZE);
54 memcpy(s->host, host, SESSION_ID_SIZE);
55 s->generation = 1;
56}
58 for (size_t i = 0; i < s->count; ++i)
59 if (memcmp(s->peers[i].id, id, SESSION_ID_SIZE) == 0)
60 return &s->peers[i];
61 return NULL;
62}
64 if (find_peer(s, id))
65 return ASCIICHAT_OK;
67 return SET_ERRNO(ERROR_INVALID_STATE, "Handoff membership full");
69 memset(p, 0, sizeof(*p));
70 memcpy(p->id, id, SESSION_ID_SIZE);
71 p->nat_tier = 255;
72 ++s->generation;
73 s->ready = false;
74 memset(s->successor, 0, SESSION_ID_SIZE);
75 return ASCIICHAT_OK;
76}
78 // The incumbent can leave before its first measurement creates a peer entry.
79 if (memcmp(s->host, id, SESSION_ID_SIZE) == 0)
80 s->host_lost = true;
81 for (size_t i = 0; i < s->count; ++i) {
82 if (memcmp(s->peers[i].id, id, SESSION_ID_SIZE) != 0)
83 continue;
84 memmove(&s->peers[i], &s->peers[i + 1], (s->count - i - 1) * sizeof(s->peers[0]));
85 --s->count;
86 ++s->generation;
87 if (memcmp(s->host, id, SESSION_ID_SIZE) == 0)
88 s->host_lost = true;
89 // Pending acknowledgements carry the old membership generation. Reissue
90 // their preparation instead of rejecting the late reply and exhausting
91 // recovery without trying the still-eligible successor again.
92 if (!s->ready || memcmp(s->successor, id, SESSION_ID_SIZE) == 0) {
93 memset(s->successor, 0, SESSION_ID_SIZE);
94 s->ready = false;
95 }
96 return;
97 }
98}
99
104 if (!memcmp(s->host, host, sizeof(s->host)))
105 s->host_lost = true;
106}
107
115 if (memcmp(s->session, m->session, SESSION_ID_SIZE) != 0)
116 return SET_ERRNO(ERROR_NETWORK_PROTOCOL, "Wrong handoff session");
117 consensus_handoff_peer_t *p = find_peer(s, m->participant);
118 if (!p)
119 return SET_ERRNO(ERROR_NETWORK_PROTOCOL, "Handoff sender is not a member");
120 if (m->kind == HANDOFF_SAMPLE_START) {
121 if (m->sequence <= p->sequence || (p->measured_ms && now - p->measured_ms < 1000))
122 return SET_ERRNO(ERROR_NETWORK_PROTOCOL, "Repeated or excessive handoff probe");
123 p->sequence = m->sequence;
124 p->probe_started_ms = now;
125 p->measuring = true;
127 p->pending_nat_tier = m->nat_tier <= 4 ? m->nat_tier : 255;
128 p->pending_port = m->port;
129 } else if (m->kind == HANDOFF_SAMPLE_DATA) {
131 return SET_ERRNO(ERROR_NETWORK_PROTOCOL, "Unmatched handoff probe");
132 p->measuring = false;
133 uint64_t elapsed = now - p->probe_started_ms;
134 if (elapsed == 0)
135 elapsed = 1;
136 p->valid = elapsed <= 5000;
137 if (p->valid) {
140 p->port = p->pending_port;
141 // A quality refresh cannot extend a failed recovery by retrying the same host.
142 if (!s->host_lost)
143 p->rejected = false;
144 }
146 p->measured_ms = now;
147 } else if (m->kind == HANDOFF_READY || m->kind == HANDOFF_REJECT) {
148 if (m->generation != s->generation || m->sequence != s->round || memcmp(m->participant, s->successor, SESSION_ID_SIZE))
149 return SET_ERRNO(ERROR_NETWORK_PROTOCOL, "Obsolete handoff preparation");
150 if (m->kind == HANDOFF_READY && now <= s->prepare_deadline_ms)
151 s->ready = true;
152 else {
153 p->rejected = true;
154 s->ready = false;
155 memset(s->successor, 0, SESSION_ID_SIZE);
156 }
157 } else
158 return SET_ERRNO(ERROR_NETWORK_PROTOCOL, "Client cannot announce a handoff decision");
159 return ASCIICHAT_OK;
160}
161// Record decisions, not periodic ticks or per-peer measurements.
162static void handoff_record_action(consensus_handoff_t *state, const consensus_handoff_message_t *action, uint64_t now, size_t candidates) {
163 ASCII_OTEL_SCOPE(DISCOVERY_HOST_SELECTION);
164 const char *outcome = action->kind == HANDOFF_PREPARE ? "selected" : action->kind == HANDOFF_COMMIT ? "committed" : "failed";
165 ASCII_OTEL_ATTR_STRING("host.selection.phase", "successor");
166 ASCII_OTEL_ATTR_STRING("host.selection.outcome", outcome);
167 ASCII_OTEL_ATTR_STRING("host.selection.reason", action->kind == HANDOFF_PREPARE ? "best_eligible_quality" : action->kind == HANDOFF_COMMIT ? "prepared_successor" : "no_eligible_successor");
168 ASCII_OTEL_ATTR_INT("host.generation", state->generation);
169 ASCII_OTEL_ATTR_INT("host.selection.round", state->round);
170 if (action->kind != HANDOFF_COMMIT)
171 ASCII_OTEL_ATTR_INT("host.selection.eligible_candidates", (int64_t)candidates);
172 ASCII_OTEL_ATTR_INT("host.selection.host_lost", state->host_lost);
173 consensus_handoff_peer_t *peer = find_peer(state, action->participant);
174 if (peer) {
175 ASCII_OTEL_ATTR_INT("host.selection.upload_kbps", peer->upload_kbps);
176 ASCII_OTEL_ATTR_INT("host.selection.nat_tier", peer->nat_tier);
177 }
178 ascii_otel_metric(action->kind == HANDOFF_PREPARE ? ASCII_OTEL_METRIC_HOST_SELECTIONS : action->kind == HANDOFF_COMMIT ? ASCII_OTEL_METRIC_HOST_COMMITS : ASCII_OTEL_METRIC_HOST_FAILURES, 1);
181 if (now >= started)
182 ascii_otel_metric(ASCII_OTEL_METRIC_HOST_RECOVERY_DURATION, (double)(now - started) / 1000.0);
183 }
184}
185
195 memset(a, 0, sizeof(*a));
196 memcpy(a->session, s->session, SESSION_ID_SIZE);
197 a->generation = s->generation;
198 if (s->failure_announced)
199 return false; // Terminal until the session is recreated.
200 if (!s->monitoring) {
201 s->monitoring = true;
202 s->monitoring_started_ms = now;
203 }
204 consensus_handoff_peer_t *incumbent = find_peer(s, s->host);
205 uint64_t last_host_sample = incumbent && incumbent->valid ? incumbent->measured_ms : s->monitoring_started_ms;
206 if (now - last_host_sample > CONSENSUS_HANDOFF_FRESH_MS)
207 s->host_lost = true;
208 if (s->host_lost && !s->failure_deadline_ms)
210 // The recovery budget is shared by all candidates, including silent/rejecting
211 // candidates that continue sending fresh probes. A late READY cannot revive it.
212 if (s->host_lost && now >= s->failure_deadline_ms) {
213 s->failure_announced = true;
214 s->ready = false;
215 memset(s->successor, 0, sizeof(s->successor));
216 a->kind = HANDOFF_FAILED;
217 a->sequence = s->round;
218 handoff_record_action(s, a, now, 0);
219 return true;
220 }
221 if (s->ready && s->host_lost) {
222 consensus_handoff_peer_t *p = find_peer(s, s->successor);
223 if (p && p->valid && p->capabilities && now - p->measured_ms <= CONSENSUS_HANDOFF_FRESH_MS) {
224 a->kind = HANDOFF_COMMIT;
225 memcpy(a->participant, s->successor, SESSION_ID_SIZE);
226 a->sequence = s->round;
227 a->port = p->port;
229 handoff_record_action(s, a, now, 1);
230 s->host_sequence = a->sequence;
231 memcpy(s->host, s->successor, SESSION_ID_SIZE);
232 s->host_lost = false;
233 s->monitoring_started_ms = now;
234 s->ready = false;
235 s->failure_deadline_ms = 0;
236 s->failure_announced = false;
237 for (size_t i = 0; i < s->count; ++i)
238 s->peers[i].rejected = false;
239 memset(s->successor, 0, SESSION_ID_SIZE);
240 return true;
241 }
242 s->ready = false;
243 memset(s->successor, 0, SESSION_ID_SIZE);
244 }
245 uint8_t zero[SESSION_ID_SIZE] = {0};
246 if (memcmp(s->successor, zero, sizeof(s->successor))) {
247 consensus_handoff_peer_t *p = find_peer(s, s->successor);
248 if (p && p->valid && p->capabilities && now - p->measured_ms <= CONSENSUS_HANDOFF_FRESH_MS && (s->ready || now < s->prepare_deadline_ms))
249 return false;
250 if (p && !s->ready)
251 p->rejected = true;
252 memset(s->successor, 0, SESSION_ID_SIZE);
253 s->ready = false;
254 }
255 participant_metrics_t metrics[MAX_SESSION_PARTICIPANTS];
256 size_t count = 0;
257 for (size_t i = 0; i < s->count; ++i) {
259 if (!p->valid || p->rejected || !p->capabilities || now - p->measured_ms > CONSENSUS_HANDOFF_FRESH_MS || memcmp(p->id, s->host, SESSION_ID_SIZE) == 0)
260 continue;
261 participant_metrics_t *m = &metrics[count++];
262 memset(m, 0, sizeof(*m));
263 memcpy(m->participant_id, p->id, SESSION_ID_SIZE);
264 m->nat_tier = p->nat_tier <= 4 ? p->nat_tier : 4;
265 m->upload_kbps = p->upload_kbps;
266 m->rtt_ns = 500000000; /* Unknown RTT earns no latency bonus. */
267 }
268 if (!count)
269
270 return false;
271 int best = -1, backup = -1;
272 if (consensus_election_choose_hosts(metrics, (int)count, &best, &backup) != ASCIICHAT_OK)
273 return false;
274 memcpy(s->successor, metrics[best].participant_id, SESSION_ID_SIZE);
275 ++s->round;
278 memcpy(a->participant, s->successor, SESSION_ID_SIZE);
279 a->sequence = s->round;
280 handoff_record_action(s, a, now, count);
281 return true;
282}
#define SET_ERRNO(code,...)
Application limits and constraints.
asciichat_error_t consensus_election_choose_hosts(const participant_metrics_t *metrics, int num_metrics, int *out_best_index, int *out_backup_index)
Elect best and backup host from metrics.
Definition election.c:78
unsigned short uint16_t
unsigned int uint32_t
unsigned long long uint64_t
unsigned char uint8_t
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
@ ERROR_INVALID_STATE
@ ERROR_NETWORK_PROTOCOL
Definition error_codes.h:81
@ ASCIICHAT_OK
Definition error_codes.h:50
@ ERROR_INVALID_PARAM
#define MAX_SESSION_PARTICIPANTS
#define SESSION_ID_SIZE
void consensus_handoff_leave(consensus_handoff_t *s, const uint8_t id[SESSION_ID_SIZE])
Definition handoff.c:77
void consensus_handoff_host_lost(consensus_handoff_t *s, const uint8_t host[SESSION_ID_SIZE])
Record loss of the incumbent, ignoring delayed reports about old hosts. The caller authenticates the ...
Definition handoff.c:103
void consensus_handoff_init(consensus_handoff_t *s, const uint8_t session[SESSION_ID_SIZE], const uint8_t host[SESSION_ID_SIZE])
Definition handoff.c:51
bool consensus_handoff_tick(consensus_handoff_t *s, uint64_t now, consensus_handoff_message_t *a)
Advance measured successor selection and bounded host-loss recovery. Fresh eligible peers prepare wit...
Definition handoff.c:194
void consensus_handoff_encode(const consensus_handoff_message_t *m, uint8_t out[CONSENSUS_HANDOFF_HEADER])
Definition handoff.c:36
asciichat_error_t consensus_handoff_join(consensus_handoff_t *s, const uint8_t id[SESSION_ID_SIZE])
Definition handoff.c:63
asciichat_error_t consensus_handoff_decode(const void *data, size_t length, consensus_handoff_message_t *m)
Definition handoff.c:16
asciichat_error_t consensus_handoff_receive(consensus_handoff_t *s, const consensus_handoff_message_t *m, size_t length, uint64_t now)
Accept a member's probe or preparation reply using receiver-clock time. Probe metadata becomes eligib...
Definition handoff.c:114
#define CONSENSUS_HANDOFF_HEADER
Definition handoff.h:15
#define CONSENSUS_HANDOFF_PROBE_BYTES
Definition handoff.h:16
#define CONSENSUS_HANDOFF_PREPARE_MS
Definition handoff.h:18
#define CONSENSUS_HANDOFF_FRESH_MS
Definition handoff.h:17
#define CONSENSUS_HANDOFF_VERSION
Definition handoff.h:14
#define CONSENSUS_HANDOFF_RECOVERY_MS
Definition handoff.h:19
@ HANDOFF_REJECT
Definition handoff.h:28
@ HANDOFF_SAMPLE_DATA
Definition handoff.h:23
@ HANDOFF_COMMIT
Definition handoff.h:27
@ HANDOFF_FAILED
Definition handoff.h:29
@ HANDOFF_SAMPLE_ACK
Definition handoff.h:30
@ HANDOFF_READY
Definition handoff.h:25
@ HANDOFF_PREPARE
Definition handoff.h:24
@ HANDOFF_SAMPLE_START
Definition handoff.h:22
deferred_action_t action
void ascii_otel_metric(ascii_otel_metric_t metric, double value)
Definition otel.c:175
#define ASCII_OTEL_SCOPE(id)
Definition otel.h:102
#define ASCII_OTEL_ATTR_INT(key, value)
Definition otel.h:94
#define ASCII_OTEL_ATTR_STRING(key, value)
Definition otel.h:92
static bool size_t gotel_query_t * out
Definition queries.h:10
🔤 String Manipulation and Shell Escaping Utilities
uint8_t session[SESSION_ID_SIZE]
Definition handoff.h:35
uint8_t participant[SESSION_ID_SIZE]
Definition handoff.h:36
consensus handoff message is intentionally a small, concrete record. Fields such as kind,...
Definition handoff.h:53
uint64_t probe_started_ms
Definition handoff.h:63
uint8_t pending_capabilities
Definition handoff.h:58
uint8_t id[SESSION_ID_SIZE]
Definition handoff.h:54
uint32_t host_sequence
Last committed round; preparation does not change host authority.
Definition handoff.h:78
uint8_t session[SESSION_ID_SIZE]
Definition handoff.h:73
uint8_t successor[SESSION_ID_SIZE]
Definition handoff.h:75
uint64_t monitoring_started_ms
Definition handoff.h:84
uint64_t prepare_deadline_ms
Definition handoff.h:79
uint32_t generation
Definition handoff.h:76
consensus_handoff_peer_t peers[MAX_SESSION_PARTICIPANTS]
Definition handoff.h:86
uint64_t failure_deadline_ms
Definition handoff.h:83
uint8_t host[SESSION_ID_SIZE]
Definition handoff.h:74