ascii-chat
Binary v0.16.50-198-g78f51665f
Library lib/v0.3.2-2240-g78f51665f
Video chat in your terminal
Loading...
Searching...
No Matches
coordinator.c
Go to the documentation of this file.
1
5
6/* Storage capacities in elements; text buffers include the terminating NUL. */
7#define NETWORK_CONSENSUS_COORDINATOR_COORDINATOR_NAME_BUFFER_SIZE 64
8
15#include <ascii-chat/log/log.h>
16#include <ascii-chat/common.h>
17#include <recast/defer.h>
19#include <string.h>
20
21/* Round scheduling constants */
22#define CONSENSUS_ROUND_INTERVAL_NS (5ULL * 60 * NS_PER_SEC_INT) /* 5 minutes */
23#define CONSENSUS_COLLECTION_DEADLINE_NS (30ULL * NS_PER_SEC_INT) /* 30 seconds */
24
52
57 consensus_coordinator_t **out_coordinator) {
58 if (!my_id || !topology || !election_func || !out_coordinator) {
59 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameter: my_id=%p, topology=%p, election_func=%p, out_coordinator=%p", (const void *)my_id, (const void *)topology, (const void *)election_func,
60 (const void *)out_coordinator);
61 }
62
64 if (!coordinator) {
65 return SET_ERRNO(ERROR_MEMORY, "Failed to allocate coordinator");
66 }
67
68 defer_named(release_coordinator, SAFE_FREE(coordinator));
69 memset(coordinator, 0, sizeof(*coordinator));
70 memcpy(coordinator->my_id, my_id, SESSION_ID_SIZE);
71 coordinator->topology = topology;
72 coordinator->election_func = election_func;
73 coordinator->election_context = election_context;
74
75 /* Initialize state machine */
76 asciichat_error_t err = consensus_state_create(my_id, topology, &coordinator->state);
77 if (err != ASCIICHAT_OK) {
78 return err;
79 }
80
81 /* Initialize round scheduling */
82 coordinator->last_round_start_ns = time_get_ns();
83 coordinator->next_round_id = 1;
84 coordinator->has_stored_result = false;
85
86 /* Register coordinator with named registry */
88 snprintf(coordinator_name, sizeof(coordinator_name), "consensus_coordinator:node_%u", my_id[0]);
89 NAMED_REGISTER(coordinator, coordinator_name, "consensus_coordinator_t", "0x%tx", NULL);
90
91 /* Register child state with coordinator as parent */
92 NAMED_REGISTER(coordinator->state, "state", "consensus_state_t", "0x%tx", (uintptr_t)(const void *)(coordinator));
93
94 log_debug("Coordinator created for node %u, first round in 5 minutes", my_id[0]);
95
96 *out_coordinator = coordinator;
97 defer_cancel(release_coordinator);
98 return ASCIICHAT_OK;
99}
100
105 if (!coordinator) {
106 return;
107 }
108 consensus_state_destroy(coordinator->state);
109 SAFE_FREE(coordinator);
110}
111
115static bool should_start_new_round(consensus_coordinator_t *coordinator, uint64_t now_ns) {
116 if (!coordinator || !coordinator->state) {
117 return false;
118 }
119
121 if (current_state != CONSENSUS_STATE_IDLE) {
122 return false;
123 }
124
125 uint64_t time_since_last_round = time_elapsed_ns(coordinator->last_round_start_ns, now_ns);
126 return time_since_last_round >= CONSENSUS_ROUND_INTERVAL_NS;
127}
128
132static asciichat_error_t measure_and_add_metrics(consensus_coordinator_t *coordinator) {
133 participant_metrics_t metrics;
135 coordinator->metrics_provider ? coordinator->metrics_provider(coordinator->metrics_context, coordinator->my_id, &metrics) : consensus_metrics_measure(coordinator->my_id, &metrics);
136 if (err != ASCIICHAT_OK) {
137 return err;
138 }
139
140 err = consensus_state_add_metrics(coordinator->state, &metrics);
141 if (err != ASCIICHAT_OK) {
142 return err;
143 }
144
145 log_debug("Added own metrics to collection");
146 return ASCIICHAT_OK;
147}
148
152static asciichat_error_t start_collection_round(consensus_coordinator_t *coordinator, uint64_t now_ns) {
153 /* Transition state machine */
155 if (err != ASCIICHAT_OK) {
156 return err;
157 }
158
159 coordinator->last_round_start_ns = now_ns;
161 coordinator->next_round_id++;
162
163 log_info("Starting collection round %u, deadline in 30 seconds", coordinator->next_round_id - 1);
164
165 /* Measure our own metrics immediately */
166 err = measure_and_add_metrics(coordinator);
167 if (err != ASCIICHAT_OK) {
168 return err;
169 }
170
171 return ASCIICHAT_OK;
172}
173
177static bool has_collection_timed_out(consensus_coordinator_t *coordinator, uint64_t now_ns) {
179 if (current_state != CONSENSUS_STATE_COLLECTING) {
180 return false;
181 }
182
183 return now_ns >= coordinator->collection_deadline_ns;
184}
185
189static asciichat_error_t complete_collection(consensus_coordinator_t *coordinator) {
191 if (err != ASCIICHAT_OK) {
192 return err;
193 }
194
196
197 if (current_state == CONSENSUS_STATE_ELECTION_START) {
198 /* Leader: Run election */
199 log_info("Leader: Computing election from %d metrics", consensus_state_get_metrics_count(coordinator->state));
200
201 if (coordinator->election_func) {
202 err = coordinator->election_func(coordinator->election_context, coordinator->state);
203 if (err != ASCIICHAT_OK)
204 return err;
205 }
207 err = consensus_state_compute_election(coordinator->state);
208 if (err != ASCIICHAT_OK)
209 return err;
210 }
211
212 /* Store elected hosts */
213 uint8_t host_id[SESSION_ID_SIZE], backup_id[16];
214 err = consensus_state_get_elected_host(coordinator->state, host_id);
215 if (err == ASCIICHAT_OK) {
216 err = consensus_state_get_elected_backup(coordinator->state, backup_id);
217 }
218 if (err == ASCIICHAT_OK) {
219 memcpy(coordinator->stored_host_id, host_id, SESSION_ID_SIZE);
220 memcpy(coordinator->stored_backup_id, backup_id, SESSION_ID_SIZE);
221 coordinator->has_stored_result = true;
222 log_info("Election complete: host=%u, backup=%u", host_id[0], backup_id[0]);
223 }
224 }
225
226 return ASCIICHAT_OK;
227}
228
233 (void)timeout_ms; /* Currently unused, but kept for future use */
234
235 if (!coordinator) {
236 return SET_ERRNO(ERROR_INVALID_PARAM, "Coordinator is NULL");
237 }
238
239 uint64_t now_ns = time_get_ns();
240
241 /* Check if we should start a new round */
242 if (should_start_new_round(coordinator, now_ns)) {
243 /* Only leader starts rounds */
244 if (consensus_topology_am_leader(coordinator->topology)) {
245 asciichat_error_t err = start_collection_round(coordinator, now_ns);
246 if (err != ASCIICHAT_OK) {
247 log_warn("Failed to start collection round: %d", err);
248 return err;
249 }
250 }
251 }
252
254
255 /* Check for collection timeout */
256 if (current_state == CONSENSUS_STATE_COLLECTING && has_collection_timed_out(coordinator, now_ns)) {
257 log_warn("Collection round timed out, completing early");
258 asciichat_error_t err = complete_collection(coordinator);
259 if (err != ASCIICHAT_OK) {
260 log_error("Failed to complete collection on timeout: %d", err);
261 }
262 }
263
264 return ASCIICHAT_OK;
265}
266
271 if (!coordinator || !new_topology) {
272 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameter");
273 }
274
275 /* State also borrows the topology while idle. Build a complete replacement
276 * before publishing either pointer so a rejected update leaves both valid. */
277 consensus_state_t *replacement = NULL;
278 asciichat_error_t err = consensus_state_create(coordinator->my_id, new_topology, &replacement);
279 if (err != ASCIICHAT_OK)
280 return err;
282 if (current_state != CONSENSUS_STATE_IDLE)
283 log_warn("Ring topology changed during round, resetting state");
284 consensus_state_destroy(coordinator->state);
285 coordinator->state = replacement;
286 coordinator->topology = new_topology;
287
288 log_info("Ring topology updated");
289 return ASCIICHAT_OK;
290}
291
296 if (!coordinator) {
297 return SET_ERRNO(ERROR_INVALID_PARAM, "Coordinator is NULL");
298 }
299
301 if (current_state != CONSENSUS_STATE_IDLE) {
302 return SET_ERRNO(ERROR_INVALID_STATE, "Cannot start collection, state is %d", current_state);
303 }
304
305 /* Start collection */
307 if (err != ASCIICHAT_OK) {
308 return err;
309 }
310
311 coordinator->next_round_id = round_id;
312 coordinator->collection_deadline_ns = deadline_ns;
313
314 /* Measure and add our metrics */
315 err = measure_and_add_metrics(coordinator);
316 if (err != ASCIICHAT_OK) {
317 log_warn("Failed to measure metrics: %d", err);
318 }
319
320 uint64_t now_ns = time_get_ns();
321 log_dev("Collection started: round_id=%u, deadline in %u seconds", round_id, (unsigned int)((deadline_ns > now_ns ? deadline_ns - now_ns : 0) / NS_PER_SEC_INT));
322
323 return ASCIICHAT_OK;
324}
325
329asciichat_error_t consensus_coordinator_on_stats_update(consensus_coordinator_t *coordinator, const uint8_t sender_id[SESSION_ID_SIZE], const participant_metrics_t *metrics, uint8_t num_metrics) {
330 if (!coordinator || !sender_id || !metrics) {
331 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameter");
332 }
333
335 if (current_state != CONSENSUS_STATE_COLLECTING) {
336 return SET_ERRNO(ERROR_INVALID_STATE, "Cannot accept metrics, state is %d", current_state);
337 }
338
339 /* Add all metrics to state */
340 for (int i = 0; i < num_metrics; i++) {
341 asciichat_error_t err = consensus_state_add_metrics(coordinator->state, &metrics[i]);
342 if (err != ASCIICHAT_OK) {
343 log_warn("Failed to add metric %d: %d", i, err);
344 }
345 }
346
347 log_debug("Received %d metrics from sender %u", num_metrics, sender_id[0]);
348
349 return ASCIICHAT_OK;
350}
351
356 if (!coordinator || !host_id || !backup_id) {
357 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameter");
358 }
359
360 /* Store the elected host and backup */
361 memcpy(coordinator->stored_host_id, host_id, SESSION_ID_SIZE);
362 memcpy(coordinator->stored_backup_id, backup_id, SESSION_ID_SIZE);
363 coordinator->has_stored_result = true;
364
365 log_info("Election result received: host=%u, backup=%u", host_id[0], backup_id[0]);
366
367 /* Transition state back to IDLE */
369 if (current_state == CONSENSUS_STATE_ELECTION_COMPLETE) {
371 if (err != ASCIICHAT_OK) {
372 log_warn("Failed to reset state to IDLE: %d", err);
373 }
374 }
375
376 return ASCIICHAT_OK;
377}
378
383 if (!coordinator || !out_host_id || !out_backup_id) {
384 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameter");
385 }
386
387 /* Try to get from current state first */
389 if (current_state == CONSENSUS_STATE_ELECTION_COMPLETE) {
390 asciichat_error_t err = consensus_state_get_elected_host(coordinator->state, out_host_id);
391 if (err == ASCIICHAT_OK) {
392 err = consensus_state_get_elected_backup(coordinator->state, out_backup_id);
393 }
394 if (err == ASCIICHAT_OK) {
395 return ASCIICHAT_OK;
396 }
397 }
398
399 /* Fall back to stored result */
400 if (coordinator->has_stored_result) {
401 memcpy(out_host_id, coordinator->stored_host_id, SESSION_ID_SIZE);
402 memcpy(out_backup_id, coordinator->stored_backup_id, SESSION_ID_SIZE);
403 return ASCIICHAT_OK;
404 }
405
406 return SET_ERRNO(ERROR_INVALID_STATE, "No election result available");
407}
408
413 if (!coordinator || !coordinator->state) {
415 }
416 return consensus_state_get_current_state(coordinator->state);
417}
418
423 if (!coordinator) {
424 return 0;
425 }
426
427 uint64_t now_ns = time_get_ns();
428 uint64_t next_round_ns = coordinator->last_round_start_ns + CONSENSUS_ROUND_INTERVAL_NS;
429
430 if (now_ns >= next_round_ns) {
431 return 0;
432 }
433
434 return next_round_ns - now_ns;
435}
436
441 if (!coordinator || !coordinator->state) {
442 return -1;
443 }
444 return consensus_state_get_metrics_count(coordinator->state);
445}
446
448 if (!coordinator)
449 return;
450 coordinator->metrics_provider = provider;
451 coordinator->metrics_context = context;
452}
#define SET_ERRNO(code,...)
Application limits and constraints.
void consensus_coordinator_destroy(consensus_coordinator_t *coordinator)
Clean up coordinator resources.
asciichat_error_t consensus_coordinator_get_current_host(const consensus_coordinator_t *coordinator, uint8_t out_host_id[SESSION_ID_SIZE], uint8_t out_backup_id[SESSION_ID_SIZE])
Get currently elected host.
asciichat_error_t consensus_coordinator_create(const uint8_t my_id[SESSION_ID_SIZE], const consensus_topology_t *topology, consensus_election_func_t election_func, void *election_context, consensus_coordinator_t **out_coordinator)
Initialize coordinator with given parameters.
Definition coordinator.c:56
#define CONSENSUS_COLLECTION_DEADLINE_NS
Definition coordinator.c:23
int consensus_coordinator_get_metrics_count(const consensus_coordinator_t *coordinator)
Get count of metrics in current round.
asciichat_error_t consensus_coordinator_on_ring_members(consensus_coordinator_t *coordinator, const consensus_topology_t *new_topology)
Update ring topology when participants change.
struct consensus_coordinator consensus_coordinator_t
Coordinates consensus work for a session: it tracks the participant topology, election state,...
asciichat_error_t consensus_coordinator_process(consensus_coordinator_t *coordinator, uint32_t timeout_ms)
Main orchestration loop.
uint64_t consensus_coordinator_time_until_next_round(const consensus_coordinator_t *coordinator)
Get time until next round.
consensus_state_machine_t consensus_coordinator_get_state(const consensus_coordinator_t *coordinator)
Get current coordinator state.
asciichat_error_t consensus_coordinator_on_election_result(consensus_coordinator_t *coordinator, const uint8_t host_id[SESSION_ID_SIZE], const uint8_t backup_id[SESSION_ID_SIZE])
Handle ELECTION_RESULT packet.
asciichat_error_t consensus_coordinator_on_stats_update(consensus_coordinator_t *coordinator, const uint8_t sender_id[SESSION_ID_SIZE], const participant_metrics_t *metrics, uint8_t num_metrics)
Handle STATS_UPDATE packet.
#define NETWORK_CONSENSUS_COORDINATOR_COORDINATOR_NAME_BUFFER_SIZE
Definition coordinator.c:7
asciichat_error_t consensus_coordinator_on_collection_start(consensus_coordinator_t *coordinator, uint32_t round_id, uint64_t deadline_ns)
Handle STATS_COLLECTION_START packet.
void consensus_coordinator_set_metrics_provider(consensus_coordinator_t *coordinator, consensus_metrics_provider_fn provider, void *context)
#define CONSENSUS_ROUND_INTERVAL_NS
Definition coordinator.c:22
Ring consensus coordinator orchestration.
asciichat_error_t(* consensus_election_func_t)(void *context, consensus_state_t *state)
Election callback function type.
Definition coordinator.h:40
asciichat_error_t(* consensus_metrics_provider_fn)(void *, const uint8_t[16], participant_metrics_t *)
Named object registry for debugging — log identifiable resource names.
Deterministic host election algorithm.
unsigned int uint32_t
#define SAFE_FREE(ptr)
#define SAFE_MALLOC(size, cast)
unsigned long long uint64_t
unsigned char uint8_t
#define NAMED_REGISTER(ptr, name, type, fmt, parent_ptr)
Register any pointer with base name, type, format spec, and location (auto-suffix).
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
@ ERROR_INVALID_STATE
@ ERROR_MEMORY
Definition error_codes.h:55
@ ASCIICHAT_OK
Definition error_codes.h:50
@ ERROR_INVALID_PARAM
#define SESSION_ID_SIZE
#define log_warn(...)
Log a WARN message.
Definition log/log.h:615
#define log_dev(...)
Log a DEV message (most verbose, development only).
Definition log/log.h:575
#define log_error(...)
Log an ERROR message.
Definition log/log.h:628
#define log_info(...)
Log an INFO message.
Definition log/log.h:602
#define log_debug(...)
Log a DEBUG message.
Definition log/log.h:589
#define NS_PER_SEC_INT
Definition time.h:173
uint64_t time_elapsed_ns(uint64_t start_ns, uint64_t end_ns)
Calculate elapsed time with wraparound safety.
Definition time.c:117
⚙️ Common definitions, error codes, macros, and types shared throughout the application
📝 Logging API with multiple log levels and terminal output control
asciichat_error_t consensus_metrics_measure(const uint8_t my_id[SESSION_ID_SIZE], participant_metrics_t *out_metrics)
Measure participant network quality metrics.
Definition metrics.c:33
Ring consensus metrics collection and wire protocol.
asciichat_error_t consensus_state_start_collection(consensus_state_t *state)
Transition to COLLECTION_START state.
Definition state.c:75
asciichat_error_t consensus_state_compute_election(consensus_state_t *state)
Run election algorithm and transition to ELECTION_COMPLETE.
Definition state.c:135
asciichat_error_t consensus_state_create(const uint8_t my_id[SESSION_ID_SIZE], const consensus_topology_t *topology, consensus_state_t **out_state)
Initialize state machine with topology.
Definition state.c:43
void consensus_state_destroy(consensus_state_t *state)
Destroy state machine and free resources.
Definition state.c:66
asciichat_error_t consensus_state_get_elected_backup(const consensus_state_t *state, uint8_t out_backup_id[SESSION_ID_SIZE])
Get elected backup host ID from last election.
Definition state.c:197
asciichat_error_t consensus_state_get_elected_host(const consensus_state_t *state, uint8_t out_host_id[SESSION_ID_SIZE])
Get elected host ID from last election.
Definition state.c:184
asciichat_error_t consensus_state_reset_to_idle(consensus_state_t *state)
Transition back to IDLE from ELECTION_COMPLETE.
Definition state.c:164
asciichat_error_t consensus_state_collection_complete(consensus_state_t *state)
Transition to COLLECTION_COMPLETE state.
Definition state.c:116
struct consensus_state consensus_state_t
State machine instance.
int consensus_state_get_metrics_count(const consensus_state_t *state)
Get count of metrics collected in current round.
Definition state.c:217
consensus_state_machine_t consensus_state_get_current_state(const consensus_state_t *state)
Get current state machine state.
Definition state.c:177
asciichat_error_t consensus_state_add_metrics(consensus_state_t *state, const participant_metrics_t *metrics)
Add collected metrics from a participant.
Definition state.c:92
consensus_state_machine_t
State machine lifecycle states.
Definition state.h:23
@ CONSENSUS_STATE_ELECTION_COMPLETE
Definition state.h:30
@ CONSENSUS_STATE_FAILED
Definition state.h:31
@ CONSENSUS_STATE_ELECTION_START
Definition state.h:28
@ CONSENSUS_STATE_IDLE
Definition state.h:24
@ CONSENSUS_STATE_COLLECTING
Definition state.h:26
🔤 String Manipulation and Shell Escaping Utilities
Coordinates consensus work for a session: it tracks the participant topology, election state,...
Definition coordinator.c:33
uint8_t stored_backup_id[SESSION_ID_SIZE]
Definition coordinator.c:49
uint64_t collection_deadline_ns
Definition coordinator.c:45
uint64_t last_round_start_ns
Definition coordinator.c:43
const consensus_topology_t * topology
Definition coordinator.c:35
uint8_t my_id[SESSION_ID_SIZE]
Definition coordinator.c:34
consensus_metrics_provider_fn metrics_provider
Definition coordinator.c:39
uint8_t stored_host_id[SESSION_ID_SIZE]
Definition coordinator.c:48
consensus_election_func_t election_func
Definition coordinator.c:37
consensus_state_t * state
Definition coordinator.c:36
⏱️ High-precision timing utilities using sokol_time.h and uthash
bool consensus_topology_am_leader(const consensus_topology_t *topology)
Check if I am the ring leader (last position).
Definition topology.c:82
struct consensus_topology consensus_topology_t
Ring topology for consensus participants.