ascii-chat
Binary v0.16.114-28-gf5913657f
Library lib/v0.3.2-3302-gf5913657f
Video chat in your terminal
Loading...
Searching...
No Matches
otel.c
Go to the documentation of this file.
1
2#define ASCIICHAT_OTEL_IMPLEMENTATION
3
4/* Storage capacities in elements; text buffers include the terminating NUL. */
5#define OTEL_NAME_BUFFER_SIZE 256
6#define OTEL_VERSION_BUFFER_SIZE 32
7#define OTEL_BODY_BUFFER_SIZE 4096
8#define OTEL_URL_BUFFER_SIZE 2048
9#define OTEL_NAME_EXTENDED_BUFFER_SIZE 1200
10
11/* Existing buffer budgets in bytes, including NUL for text storage. */
12#define OTEL_WAIT_SNAPSHOT_CAPACITY 256
13
14#include <ascii-chat/common.h>
17#include <ascii-chat/log/log.h>
20#include <ascii-chat/otel.h>
23#include <ascii-chat/util/url.h>
24#include <ascii-chat/version.h>
25#include <libplatform/process.h>
26#include <libplatform/system.h>
27#include <libplatform/thread.h>
28#include <math.h>
29#include <options/options.h>
30#include <stdatomic.h>
31#include <stdio.h>
32#include <stdlib.h>
33#include <string.h>
34
35static _Thread_local bool in_log;
36
37// Keep library status codes inside this boundary and retain their diagnostic
38// text.
39static asciichat_error_t otel_status(otlp_status_t status,
40 const char *operation) {
41 if (status == OTLP_OK)
42 return ASCIICHAT_OK;
44 switch (status) {
45 case OTLP_ERR_NOMEM:
46 error = ERROR_MEMORY;
47 break;
48 case OTLP_ERR_INVALID_ARGUMENT:
49 case OTLP_ERR_NULL:
50 error = ERROR_INVALID_PARAM;
51 break;
52 case OTLP_ERR_OVERFLOW:
54 break;
55 case OTLP_ERR_UTF8:
56 error = ERROR_STRING;
57 break;
58 case OTLP_ERR_NETWORK:
59 case OTLP_ERR_DNS:
60 case OTLP_ERR_WRITE:
61 case OTLP_ERR_READ:
62 error = ERROR_NETWORK;
63 break;
64 case OTLP_ERR_CONNECT:
66 break;
67 case OTLP_ERR_TIMEOUT:
69 break;
70 case OTLP_ERR_PROTOCOL:
71 case OTLP_ERR_INVALID_RESPONSE:
72 case OTLP_ERR_HTTP_STATUS:
73 case OTLP_ERR_SERVER:
75 break;
76 case OTLP_ERR_THROTTLED:
78 break;
79 case OTLP_ERR_BUFFER_FULL:
80 error = ERROR_BUFFER_FULL;
81 break;
82 case OTLP_ERR_SHUTDOWN:
83 error = ERROR_INVALID_STATE;
84 break;
85 case OTLP_ERR_WOULDBLOCK:
87 break;
88 case OTLP_ERR_NOT_IMPLEMENTED:
89 error = ERROR_NOT_SUPPORTED;
90 break;
91 default:
92 error = ERROR_INTERNAL;
93 break;
94 }
95 // Error recording logs locally; do not export that diagnostic back into a
96 // failing exporter.
97 bool previous = in_log;
98 in_log = true;
99 asciichat_error_t result =
100 SET_ERRNO(error, "%s failed: %s (OTLP status %d)", operation,
101 otlp_strerror(status), (int)status);
102 in_log = previous;
103 return result;
104}
105
106static const gotel_operation_t operations[] = {
107#define ASCII_OTEL_OPERATION(id, name, realtime) {name, realtime},
108#include <ascii-chat/otel_operations.def>
109#undef ASCII_OTEL_OPERATION
110};
111static const double metric_bounds[] = {
112 .0001, .001, .005, .01, .025, .05, .1, .25, .5, 1, 2,
113 5, 10, 50, 100, 500, 1000, 5000, 10000, 50000, 100000, 1000000};
114static const gotel_metric_t metrics[] = {
115#define ASCII_OTEL_METRIC(id, name, type, unit) \
116 {name, unit, OTLP_METRIC_##type, metric_bounds, \
117 sizeof(metric_bounds) / sizeof(metric_bounds[0])},
118#include <ascii-chat/otel_metrics.def>
119#undef ASCII_OTEL_METRIC
120};
121static atomic_ptr_t host;
122static atomic_uint readers;
123static atomic_bool stopping;
124static atomic_bool worker_done;
125static platform_thread_t worker;
126static bool worker_started;
127static asciichat_error_t drain_result;
128static int minimum_log_level;
129static gotel_scope_t command_scope;
130static _Thread_local ascii_otel_scope_t *current_scope;
131static uint64_t shutdown_timeout_ns;
132static atomic_uint_fast64_t exporter_retries, exporter_batches;
133static atomic_size_t exporter_queue_capacity;
134void ascii_otel_test_set_host(gotel_host_t *value) {
135 atomic_ptr_store(&host, value);
136}
137unsigned ascii_otel_test_reader_count(void) { return atomic_load(&readers); }
138gotel_scope_t *ascii_otel_test_command_scope(void) { return &command_scope; }
139
140static void exporter_event(void *context, const otlp_event_t *event) {
141 (void)context;
142 if (event->code == OTLP_EVT_RETRY_ARMED)
143 atomic_fetch_add(&exporter_retries, 1);
144 if (event->code == OTLP_EVT_BATCH_SENT)
145 atomic_fetch_add(&exporter_batches, 1);
146}
147
148static uint64_t telemetry_realtime_ns(void) {
149 // time_get_realtime_ns() is normalized to Unix epoch nanoseconds by
150 // libplatform on every supported platform, including Windows.
151 return time_get_realtime_ns();
152}
153static gotel_host_t *retain(void) {
154 if (!atomic_ptr_load(&host))
155 return NULL;
156 atomic_fetch_add_explicit(&readers, 1, memory_order_seq_cst);
157 gotel_host_t *h = atomic_ptr_load(&host);
158 if (!h)
159 atomic_fetch_sub_explicit(&readers, 1, memory_order_seq_cst);
160 return h;
161}
162static void release(void) {
163 atomic_fetch_sub_explicit(&readers, 1, memory_order_seq_cst);
164}
166 return current_scope &&
167 current_scope->scope.operation < ASCII_OTEL_OPERATION_COUNT
168 ? operations[current_scope->scope.operation].name
169 : "";
170}
171bool ascii_otel_enabled(void) { return atomic_ptr_load(&host) != NULL; }
173 atomic_store_explicit(&stopping, true, memory_order_release);
174}
175void ascii_otel_metric(ascii_otel_metric_t metric, double value) {
176 gotel_host_t *h = retain();
177 if (h) {
178 (void)otel_status(gotel_metric_record(h, metric, value),
179 "gotel_metric_record");
180 release();
181 }
182}
183enum {
185#define ASCII_STATS_COUNTER(id, metric_id, name, unit) +1
186#define ASCII_STATS_GAUGE(id, metric_id, name, unit) +1
187#define ASCII_STATS_DURATION(id, metric_id, name, unit) +1
188#include <ascii-chat/stats/telemetry.def>
189#undef ASCII_STATS_COUNTER
190#undef ASCII_STATS_GAUGE
191#undef ASCII_STATS_DURATION
192};
195 "Every typed stat needs a telemetry metric");
196
198 unsigned id) {
199 if (!((kind == STATS_RECORD_COUNTER && id < STATS_COUNTER_COUNT) ||
200 (kind == STATS_RECORD_GAUGE && id < STATS_GAUGE_COUNT) ||
203 ascii_otel_metric_t metric;
204 switch (((unsigned)kind << 16) | id) {
205#define ASCII_STATS_COUNTER(id, metric_id, name, unit) \
206 case (STATS_RECORD_COUNTER << 16) | STATS_COUNTER_##id: \
207 metric = ASCII_OTEL_METRIC_##metric_id; \
208 break;
209#define ASCII_STATS_GAUGE(id, metric_id, name, unit) \
210 case (STATS_RECORD_GAUGE << 16) | STATS_GAUGE_##id: \
211 metric = ASCII_OTEL_METRIC_##metric_id; \
212 break;
213#define ASCII_STATS_DURATION(id, metric_id, name, unit) \
214 case (STATS_RECORD_DURATION << 16) | STATS_DURATION_##id: \
215 metric = ASCII_OTEL_METRIC_##metric_id; \
216 break;
217#include <ascii-chat/stats/telemetry.def>
218#undef ASCII_STATS_COUNTER
219#undef ASCII_STATS_GAUGE
220#undef ASCII_STATS_DURATION
221 default:
223 }
224 return metric;
225}
226
227static void stats_metric_record(stats_record_kind_t kind, unsigned id,
228 uint64_t value, void *context) {
229 (void)context;
231 if (metric == ASCII_OTEL_METRIC_COUNT)
232 return;
233 ascii_otel_metric(metric, kind == STATS_RECORD_DURATION ? (double)value / 1e9
234 : (double)value);
235}
236
238 stats_scope_set_observer(scope, stats_metric_record, NULL);
239}
240static void exporter_diagnostic(void *context, otlp_log_level_t level,
241 const char *message) {
242 (void)context;
243 (void)level;
244 bool previous = in_log;
245 in_log = true;
246 log_debug("OTLP exporter: %s", message);
247 in_log = previous;
248}
249#ifndef NDEBUG
250static mutex_wait_snapshot_t watchdog_detail;
251static bool watchdog_snapshot(void *context, gotel_watchdog_snapshot_t *out) {
252 (void)context;
254 size_t count = 0;
255 if (!mutex_stack_try_snapshot(waits, 256, &count, &out->limited))
256 return false;
257 uint64_t now = time_get_ns();
258 for (size_t i = 0; i < count; ++i) {
259 if (waits[i].cycle) {
260 if (!out->blocked_threads) {
261 watchdog_detail = waits[i];
262 memcpy(out->parent.trace_id, waits[i].trace_id,
263 sizeof(out->parent.trace_id));
264 memcpy(out->parent.span_id, waits[i].span_id,
265 sizeof(out->parent.span_id));
266 out->parent.valid = waits[i].context_valid;
267 out->parent.sampled = waits[i].context_sampled;
268 out->parent.realtime = true;
269 out->parent_snapshot.context = out->parent;
270 memcpy(out->parent_snapshot.parent_span_id, waits[i].parent_span_id,
271 sizeof(waits[i].parent_span_id));
272 out->parent_snapshot.start_unix_ns = waits[i].span_start_unix_ns;
273 SAFE_STRNCPY(out->parent_snapshot.name, waits[i].span_name,
274 sizeof(out->parent_snapshot.name));
275 }
276 ++out->blocked_threads;
277 uint64_t age = now >= waits[i].since_ns ? now - waits[i].since_ns : 0;
278 if (!out->wait_ns || age < out->wait_ns)
279 out->wait_ns = age;
280 }
281 }
282 return true;
283}
284static void watchdog_decorate(void *context, gotel_scope_t *scope) {
285 (void)context;
286 gotel_attr_string(scope, "thread.blocked.span.name",
287 watchdog_detail.span_name);
288 gotel_attr_int(scope, "asciichat_errno.code", watchdog_detail.error_code);
289 gotel_attr_string(scope, "asciichat_errno.code_message",
290 asciichat_error_string(watchdog_detail.error_code));
291 gotel_attr_string(scope, "asciichat_errno.message",
292 watchdog_detail.error_message);
293}
294#endif
295static atomic_uint_fast64_t pipeline_capture_ns, pipeline_display_ns,
296 pipeline_encode_ns;
297static atomic_uint pipeline_expected;
298void ascii_otel_pipeline_progress(unsigned stage, unsigned expected) {
299 if (!ascii_otel_enabled())
300 return;
301 uint64_t now = time_get_ns();
302 if (stage == 0) {
303 if (!atomic_load(&pipeline_capture_ns)) {
304 atomic_store(&pipeline_display_ns, now);
305 atomic_store(&pipeline_encode_ns, now);
306 }
307 if (!(expected & 1))
308 atomic_store(&pipeline_display_ns, now);
309 if (!(expected & 2))
310 atomic_store(&pipeline_encode_ns, now);
311 atomic_store(&pipeline_expected, expected);
312 atomic_store(&pipeline_capture_ns, now);
313 } else if (stage == 1)
314 atomic_store(&pipeline_display_ns, now);
315 else if (stage == 2)
316 atomic_store(&pipeline_encode_ns, now);
317 else {
318 atomic_store(&pipeline_expected, 0);
319 atomic_store(&pipeline_capture_ns, 0);
320 ascii_otel_metric(ASCII_OTEL_METRIC_PIPELINE_DISPLAY_STALL, 0);
321 ascii_otel_metric(ASCII_OTEL_METRIC_PIPELINE_ENCODE_STALL, 0);
322 }
323}
325 uint64_t progress, bool expected) {
326 return expected && capture && progress && now >= capture && now >= progress &&
327 now - capture < 2 * NS_PER_SEC_INT
328 ? (double)(now - progress) / 1e9
329 : 0;
330}
331static void pipeline_health(gotel_host_t *h, uint64_t now) {
332 uint64_t capture = atomic_load(&pipeline_capture_ns);
333 unsigned expected = atomic_load(&pipeline_expected);
334 uint64_t display = atomic_load(&pipeline_display_ns),
335 encode = atomic_load(&pipeline_encode_ns);
336 (void)gotel_metric_record(
337 h, ASCII_OTEL_METRIC_PIPELINE_DISPLAY_STALL,
338 ascii_otel_pipeline_age(now, capture, display, (expected & 1) != 0));
339 (void)gotel_metric_record(
340 h, ASCII_OTEL_METRIC_PIPELINE_ENCODE_STALL,
341 ascii_otel_pipeline_age(now, capture, encode, (expected & 2) != 0));
342}
343static void *export_worker(void *arg) {
344 gotel_host_t *h = arg;
345 /* Telemetry export is best-effort. DNS/collector failures must not become
346 * user-facing modal errors, especially while the application is otherwise
347 * connected and rendering normally. */
348 bool notifications = errno_notifications_suppress(true);
349 uint64_t last_health = 0;
350 uint64_t last_failure_warning = 0, observed_failures = 0, observed_sent = 0;
351 bool collector_failed = false;
352 while (!atomic_load_explicit(&stopping, memory_order_acquire)) {
353 uint64_t start = time_get_ns();
354 (void)otel_status(gotel_tick(h), "gotel_tick");
355 (void)otel_status(
356 gotel_metric_record(h, ASCII_OTEL_METRIC_EXPORT_LATENCY,
357 (double)(time_get_ns() - start) / 1e9),
358 "gotel_metric_record");
359 if (!last_health || start - last_health >= NS_PER_SEC_INT) {
360 last_health = start;
361 pipeline_health(h, time_get_ns());
362 platform_process_stats_t process;
363 if (platform_process_stats(&process) == ASCIICHAT_OK) {
364 (void)otel_status(
365 gotel_metric_record(h, ASCII_OTEL_METRIC_CPU, process.cpu_seconds),
366 "gotel_metric_record");
367 (void)otel_status(gotel_metric_record(h, ASCII_OTEL_METRIC_RSS,
368 (double)process.resident_bytes),
369 "gotel_metric_record");
370 (void)otel_status(gotel_metric_record(h, ASCII_OTEL_METRIC_THREADS,
371 (double)process.threads),
372 "gotel_metric_record");
373 }
374 otlp_exporter_stats_t stats = {0};
375 (void)otel_status(gotel_stats(h, &stats), "gotel_stats");
376 uint64_t accepted =
377 stats.emitted + stats.emitted_logs + stats.emitted_metrics;
378 uint64_t sent = stats.sent + stats.sent_logs + stats.sent_metrics;
379 uint64_t failures = stats.network_err + stats.http_4xx + stats.http_5xx;
380 // Exporter health logs stay local to avoid feeding failures back into its
381 // queue.
382 bool previous = in_log;
383 in_log = true;
384 if (failures > observed_failures) {
385 collector_failed = true;
386 if (!last_failure_warning ||
387 start - last_failure_warning >= 30 * NS_PER_SEC_INT) {
388 log_warn("Telemetry collector export failed (%llu failures); export "
389 "continues in background",
390 (unsigned long long)failures);
391 last_failure_warning = start;
392 }
393 } else if (collector_failed && sent > observed_sent) {
394 log_info("Telemetry collector export recovered");
395 collector_failed = false;
396 last_failure_warning = 0;
397 }
398 in_log = previous;
399 observed_failures = failures;
400 observed_sent = sent;
401 uint64_t failed = stats.dropped_err + stats.dropped_logs_err +
402 stats.dropped_metrics_err;
403 uint64_t pending =
404 accepted > sent + failed ? accepted - sent - failed : 0;
405 (void)otel_status(
406 gotel_metric_record(
407 h, ASCII_OTEL_METRIC_EXPORT_QUEUE,
408 (double)pending / (3.0 * atomic_load(&exporter_queue_capacity))),
409 "gotel_metric_record");
410 (void)otel_status(
411 gotel_metric_record(h, ASCII_OTEL_METRIC_EXPORT_SENT, (double)sent),
412 "gotel_metric_record");
413 (void)otel_status(
414 gotel_metric_record(h, ASCII_OTEL_METRIC_EXPORT_DROP,
415 (double)(failed + stats.dropped_full +
416 stats.dropped_logs_full +
417 stats.dropped_metrics_full)),
418 "gotel_metric_record");
419 (void)otel_status(gotel_metric_record(h, ASCII_OTEL_METRIC_EXPORT_RETRY,
420 (double)stats.network_err),
421 "gotel_metric_record");
422 (void)otel_status(gotel_metric_record(h, ASCII_OTEL_METRIC_EXPORT_REJECT,
423 (double)stats.rejected_spans),
424 "gotel_metric_record");
425 (void)otel_status(
426 gotel_metric_record(h, ASCII_OTEL_METRIC_EXPORT_RETRIES,
427 (double)atomic_load(&exporter_retries)),
428 "gotel_metric_record");
429 (void)otel_status(
430 gotel_metric_record(h, ASCII_OTEL_METRIC_EXPORT_BATCHES,
431 (double)atomic_load(&exporter_batches)),
432 "gotel_metric_record");
433 }
434 platform_sleep_ms(10);
435 }
436 // Drain on the exporter worker, never on the exit thread. The shutdown
437 // caller waits only for its hard budget below; if the collector is blocked
438 // in DNS/TLS/HTTP, the worker remains retained until process exit rather
439 // than delaying application shutdown.
440 drain_result = otel_status(gotel_drain(h), "Drain telemetry exporter");
441 errno_notifications_suppress(notifications);
442 atomic_store_explicit(&worker_done, true, memory_order_release);
443 return NULL;
444}
449 const gotel_context_t *parent) {
450 gotel_host_t *h = retain();
451 s->retained = h != NULL;
452 if (h) {
453 gotel_context_t context = gotel_current_context();
454 bool lifetime_parent =
455 current_scope &&
456 (current_scope->scope.operation == ASCII_OTEL_SESSION_CLIENT_LIKE_RUN ||
457 current_scope->scope.operation == ASCII_OTEL_SESSION_ATTEMPT);
458 // Lifetime spans finish only at shutdown. Completed operations must remain
459 // inspectable while a server is running, including after abrupt
460 // termination.
461 if (!parent && context.valid) {
462 gotel_parent_mode_t mode =
463 lifetime_parent ||
464 memcmp(context.span_id, command_scope.context.span_id,
465 sizeof(context.span_id)) == 0
466 ? GOTEL_PARENT_INDEPENDENT
467 : GOTEL_PARENT_BOUNDED;
468 context = gotel_operation_parent(context, mode);
469 parent = &context;
470 }
471 gotel_begin(h, &s->scope, (size_t)op, parent);
472 s->previous = current_scope;
473 current_scope = s;
474 }
475}
476/* Keep the stack-scope lifetime boundary visible to the cleanup caller. If
477 * GCC inlines this helper, its dangling-pointer analysis treats the deliberate
478 * thread-local scope stack as an escaped local even though cleanup restores it
479 * before return. */
480#if defined(__GNUC__) || defined(__clang__)
481__attribute__((noinline))
482#endif
483static bool scope_retained(ascii_otel_scope_t *s, ascii_otel_operation_t op,
484 const gotel_context_t *parent) {
485 gotel_host_t *h = retain();
486 if (!h)
487 return false;
488 if (!gotel_begin_retained(h, &s->scope, op, parent)) {
489 release();
490 return false;
491 }
492 s->retained = true;
493 s->previous = current_scope;
494 current_scope = s;
495 return true;
496}
498 if (!s || !s->retained)
499 return;
500 gotel_end(&s->scope);
501 if (current_scope == s)
502 current_scope = s->previous;
503 s->retained = false;
504 release();
505}
506void ascii_otel_ui_usage(const char *screen, const char *event,
507 uint64_t duration_ns) {
508 // UI transitions must not inherit realtime media sampling decisions.
509 gotel_context_t root = {0};
510 ASCII_OTEL_SCOPE_PARENT(UI_USAGE, &root);
511 ASCII_OTEL_ATTR_STRING("ascii_chat.ui.screen", screen);
512 ASCII_OTEL_ATTR_STRING("ascii_chat.ui.event", event);
513 ASCII_OTEL_ATTR_INT("ascii_chat.ui.duration_ns", (int64_t)duration_ns);
514}
515
516void ascii_otel_call_session_used(const char *session_string) {
517 if (!session_string || !session_string[0])
518 return;
519 // Call usage must not inherit a realtime packet's sampling decision.
520 gotel_context_t root = {0};
521 ASCII_OTEL_SCOPE_PARENT(CALL_SESSION_USED, &root);
522 ASCII_OTEL_ATTR_STRING("ascii-chat.session.string", session_string);
523}
525 size_t payload_size, const char *action, int transport) {
526 if (!scope->retained || !scope->scope.span)
527 return;
528 const char *packet = acip_packet_type_name(type);
530 safe_snprintf(name, sizeof(name), "%s.%s",
531 operations[scope->scope.operation].name, packet);
532 safe_snprintf(version, sizeof(version), "%d.%d.%d", PROTOCOL_VERSION_MAJOR,
534 (void)otel_status(otlp_span_set_name(scope->scope.span, name),
535 "otlp_span_set_name");
536 gotel_attr_string(&scope->scope, "network.protocol.name", "acip");
537 gotel_attr_string(&scope->scope, "network.protocol.version", version);
538 gotel_attr_string(&scope->scope, "network.packet.name", packet);
539 gotel_attr_int(&scope->scope, "network.packet.type", type);
540 gotel_attr_int(&scope->scope, "network.packet.size", (int64_t)payload_size);
541 gotel_attr_string(&scope->scope, "network.packet.operation", action);
542 const char *carrier = transport == ACIP_TRANSPORT_TCP ? "tcp"
543 : transport == ACIP_TRANSPORT_WEBSOCKET ? "websocket"
544 : transport == ACIP_TRANSPORT_WEBRTC ? "webrtc"
545 : "unknown";
546 gotel_attr_string(&scope->scope, "acip.transport", carrier);
547}
549 atomic_store_explicit(&stopping, true, memory_order_release);
550 gotel_host_t *h = atomic_ptr_exchange(&host, NULL);
551 if (!h)
552 return;
553 // The command span may still reference exporter-owned state while a
554 // shutdown signal is being handled on another thread. Do not close it on
555 // the exit thread; the exporter owns the remaining queued data and process
556 // teardown reclaims the span memory.
557 uint64_t started = time_get_ns();
558 // Leave time for the rest of process teardown, even if the collector stalls.
559 // Keep the application-side budget below one second while allowing the
560 // exporter its bounded 500 ms interruptible network drain.
561 uint64_t budget_ns = shutdown_timeout_ns < 900 * NS_PER_MS_INT
562 ? shutdown_timeout_ns
563 : 900 * NS_PER_MS_INT;
564 bool producers_active =
565 atomic_load_explicit(&readers, memory_order_seq_cst) != 0;
566 if (worker_started) {
567 // Interrupt any exporter request before waiting for the worker. Waiting
568 // first makes cancellation unreachable when the worker is blocked in
569 // DNS/TLS/HTTP, which turns a bounded shutdown into a process hang.
570 (void)otel_status(gotel_drain(h), "Drain telemetry exporter");
571 while (!atomic_load_explicit(&worker_done, memory_order_acquire) &&
572 time_get_ns() - started < budget_ns)
573 platform_sleep_ms(1);
574 bool done = atomic_load_explicit(&worker_done, memory_order_acquire);
575 uint64_t elapsed_ns = time_get_ns() - started;
576 int joined = -1;
577 if (done && elapsed_ns < budget_ns) {
578#if !defined(__linux__) && !defined(_WIN32)
579 // The POSIX timed join implementation blocks on these platforms. The
580 // worker has finished using the exporter, so detach its remaining wrapper
581 // cleanup.
582 joined = thread_detach(&worker);
583#else
584 joined = thread_join_timeout(&worker, NULL, budget_ns - elapsed_ns);
585#endif
586 }
587 if (joined != 0) {
588 log_warn("Telemetry worker did not stop within its deadline; exporter "
589 "retained until process exit");
590 return;
591 }
592 worker_started = false;
593 }
594 asciichat_error_t result = drain_result;
595 otlp_exporter_stats_t stats = {0};
596 (void)otel_status(gotel_stats(h, &stats), "gotel_stats");
597 // exit() can bypass scope cleanup in a producer. Do not free its host while
598 // it remains borrowed; the process will reclaim it after atexit handlers.
599 if (!producers_active)
600 gotel_destroy(h);
601 else
602 log_warn("Telemetry producer still active during process shutdown; "
603 "exporter retained");
604 if (result != ASCIICHAT_OK)
605 log_warn("Telemetry flush deadline reached; pending records discarded");
606 log_debug("Telemetry exporter stopped: spans=%llu/%llu logs=%llu/%llu "
607 "metrics=%llu/%llu network_errors=%llu "
608 "http_4xx=%llu dropped=%llu rejected=%llu",
609 (unsigned long long)stats.sent, (unsigned long long)stats.emitted,
610 (unsigned long long)stats.sent_logs,
611 (unsigned long long)stats.emitted_logs,
612 (unsigned long long)stats.sent_metrics,
613 (unsigned long long)stats.emitted_metrics,
614 (unsigned long long)stats.network_err,
615 (unsigned long long)stats.http_4xx,
616 (unsigned long long)(stats.dropped_full + stats.dropped_err),
617 (unsigned long long)stats.rejected_spans);
618}
619static const gotel_command_rule_t command_argument_rules[] = {
620 {"--password", GOTEL_COMMAND_VALUE_REQUIRED, GOTEL_COMMAND_REDACT},
621 {"--key", GOTEL_COMMAND_VALUE_REQUIRED, GOTEL_COMMAND_REDACT},
622 {"-K", GOTEL_COMMAND_VALUE_REQUIRED, GOTEL_COMMAND_REDACT},
623 {"--server-key", GOTEL_COMMAND_VALUE_REQUIRED, GOTEL_COMMAND_REDACT},
624 {"--client-keys", GOTEL_COMMAND_VALUE_REQUIRED, GOTEL_COMMAND_REDACT},
625 {"--discovery-service-key", GOTEL_COMMAND_VALUE_REQUIRED,
626 GOTEL_COMMAND_REDACT},
627 {"--address", GOTEL_COMMAND_VALUE_REQUIRED, GOTEL_COMMAND_REDACT},
628 {"--address6", GOTEL_COMMAND_VALUE_REQUIRED, GOTEL_COMMAND_REDACT},
629 {"--port", GOTEL_COMMAND_VALUE_REQUIRED, GOTEL_COMMAND_REDACT},
630 {"-p", GOTEL_COMMAND_VALUE_REQUIRED, GOTEL_COMMAND_REDACT},
631 {"--websocket-port", GOTEL_COMMAND_VALUE_REQUIRED, GOTEL_COMMAND_REDACT},
632 {"--tls-cert", GOTEL_COMMAND_VALUE_REQUIRED, GOTEL_COMMAND_REDACT},
633 {"--tls-key", GOTEL_COMMAND_VALUE_REQUIRED, GOTEL_COMMAND_REDACT},
634 {"--tls-key-password", GOTEL_COMMAND_VALUE_REQUIRED, GOTEL_COMMAND_REDACT},
635 {"--discovery-service", GOTEL_COMMAND_VALUE_REQUIRED, GOTEL_COMMAND_REDACT},
636 {"--stun-servers", GOTEL_COMMAND_VALUE_REQUIRED, GOTEL_COMMAND_REDACT},
637 {"--turn-servers", GOTEL_COMMAND_VALUE_REQUIRED, GOTEL_COMMAND_REDACT},
638 {"--turn-username", GOTEL_COMMAND_VALUE_REQUIRED, GOTEL_COMMAND_REDACT},
639 {"--turn-credential", GOTEL_COMMAND_VALUE_REQUIRED, GOTEL_COMMAND_REDACT},
640 {"--turn-secret", GOTEL_COMMAND_VALUE_REQUIRED, GOTEL_COMMAND_REDACT},
641 {"--url", GOTEL_COMMAND_VALUE_REQUIRED, GOTEL_COMMAND_REDACT},
642 {"-u", GOTEL_COMMAND_VALUE_REQUIRED, GOTEL_COMMAND_REDACT},
643 {"--yt-dlp-options", GOTEL_COMMAND_VALUE_REQUIRED, GOTEL_COMMAND_REDACT},
644 {"--otel-endpoint", GOTEL_COMMAND_VALUE_REQUIRED, GOTEL_COMMAND_REDACT},
645 {"--otel-ca-file", GOTEL_COMMAND_VALUE_REQUIRED, GOTEL_COMMAND_REDACT},
646};
647
648asciichat_error_t ascii_otel_init(const char *mode, int argc, char **argv) {
649 // Test mode is a hard export prohibition, including explicit endpoints and
650 // CLI overrides.
651 if (is_test_environment())
652 return ASCIICHAT_OK;
653 const options_t *o = options_get();
654 if (!o)
655 return ASCIICHAT_OK;
656 const char *endpoint = o->otel_endpoint;
657 if (!endpoint || endpoint[0] == '\0')
658 return ASCIICHAT_OK;
659 bool endpoint_cli = false, timeout_cli = false;
660 for (int i = 1; i < argc; ++i) {
661 endpoint_cli |= !strcmp(argv[i], "--otel-endpoint") ||
662 !strncmp(argv[i], "--otel-endpoint=", 16);
663 timeout_cli |= !strcmp(argv[i], "--otel-timeout") ||
664 !strncmp(argv[i], "--otel-timeout=", 15);
665 }
666 unsigned signals;
667 asciichat_error_t parsed =
668 otel_status(gotel_parse_signals(o->otel_enabled_telemetry, &signals),
669 "Parse otel-enabled-telemetry (traces,logs,metrics or none)");
670 if (parsed != ASCIICHAT_OK)
671 return parsed;
672 if (!isfinite(o->otel_realtime_sample_rate) ||
674 o->otel_queue_capacity < 2 ||
676 o->otel_timeout < 1 || o->otel_metrics_interval < 1 ||
678 return SET_ERRNO(ERROR_CONFIG,
679 "Invalid telemetry sampling, queue capacity, or interval");
680 const char *log_names[] = {"dev", "debug", "info", "warn", "error", "fatal"};
681 const int log_levels[] = {LOG_DEV, LOG_DEBUG, LOG_INFO,
683 minimum_log_level = -1;
684 for (size_t i = 0; i < sizeof(log_levels) / sizeof(log_levels[0]); ++i)
685 if (strcmp(o->otel_log_level, log_names[i]) == 0)
686 minimum_log_level = log_levels[i];
687 if (minimum_log_level < 0)
688 return SET_ERRNO(ERROR_CONFIG, "Invalid otel-log-level");
689 if (!signals)
690 return ASCIICHAT_OK;
691 gotel_options_t config = {0};
692 config.application_name = "ascii-chat";
693 config.disable_span_name_prefix = true;
694 char service_name[OPTIONS_BUFF_SIZE];
695 int n =
696 safe_snprintf(service_name, sizeof(service_name), "ascii-chat-%s", mode);
697 if (n < 0 || (size_t)n >= sizeof(service_name))
698 return SET_ERRNO(ERROR_CONFIG, "Telemetry service name too long");
699 config.exporter.service_name = service_name;
700 // The exporter observes its batch interval during final flush as well.
701 // Keep it short enough to deliver all signals within the shutdown budget.
702 config.exporter.batch_ms = 25;
703 config.exporter.queue_capacity = (size_t)o->otel_queue_capacity;
704 config.exporter.connect_timeout_ms = (uint32_t)o->otel_timeout;
705 config.exporter.read_timeout_ms = (uint32_t)o->otel_timeout;
706 config.exporter.flush_timeout_ms = (uint32_t)o->otel_timeout;
707 otlp_resource_attr_t resources[] = {
708 {.key = "ascii_chat.mode",
709 .value = {.type = OTLP_VALUE_STRING, .v = {.string_val = mode}}},
710 {.key = "service.version",
711 .value = {.type = OTLP_VALUE_STRING,
712 .v = {.string_val = ASCII_CHAT_VERSION_FULL}}},
713 };
714 config.exporter.resource_attributes = resources;
715 config.exporter.n_resource_attributes =
716 sizeof(resources) / sizeof(resources[0]);
717 config.signals = signals;
718 config.realtime_sample_rate = o->otel_realtime_sample_rate;
719 config.realtime_max_per_second = (uint32_t)o->otel_realtime_max_per_second;
720 config.metrics_interval_ms = (uint32_t)o->otel_metrics_interval;
721 config.monotonic_ns = time_get_ns;
722 config.realtime_ns = telemetry_realtime_ns;
723 config.operations = operations;
724 config.operation_count = ASCII_OTEL_OPERATION_COUNT;
725 config.exporter_event = exporter_event;
726 config.metrics = metrics;
727 config.metric_count = ASCII_OTEL_METRIC_COUNT;
728#ifndef NDEBUG
729 config.watchdog.snapshot = watchdog_snapshot;
730 config.watchdog.decorate = watchdog_decorate;
731 config.watchdog.operation = ASCII_OTEL_THREAD_DEADLOCK;
732 config.watchdog.metric = ASCII_OTEL_METRIC_DEADLOCK_THREADS;
733#endif
734 gotel_command_args_t command_args = {0};
735 // Addresses are positional in native client/server modes, with optional
736 // ports.
737 char address_port[OPTIONS_BUFF_SIZE + 32],
738 address6_port[OPTIONS_BUFF_SIZE + 32];
739 char address_brackets[OPTIONS_BUFF_SIZE + 32],
740 address6_brackets[OPTIONS_BUFF_SIZE + 32];
741 char address_brackets_port[OPTIONS_BUFF_SIZE + 32],
742 address6_brackets_port[OPTIONS_BUFF_SIZE + 32];
743 SAFE_SNPRINTF(address_port, sizeof(address_port), "%s:%d", o->address,
744 o->port);
745 SAFE_SNPRINTF(address6_port, sizeof(address6_port), "%s:%d", o->address6,
746 o->port);
747 SAFE_SNPRINTF(address_brackets, sizeof(address_brackets), "[%s]", o->address);
748 SAFE_SNPRINTF(address6_brackets, sizeof(address6_brackets), "[%s]",
749 o->address6);
750 SAFE_SNPRINTF(address_brackets_port, sizeof(address_brackets_port), "[%s]:%d",
751 o->address, o->port);
752 SAFE_SNPRINTF(address6_brackets_port, sizeof(address6_brackets_port),
753 "[%s]:%d", o->address6, o->port);
754 const char *sensitive_values[] = {o->address,
755 o->address6,
756 address_port,
757 address6_port,
758 address_brackets,
759 address6_brackets,
760 address_brackets_port,
761 address6_brackets_port};
762 gotel_command_policy_t argument_policy = {
763#ifdef NDEBUG
764 .mode = GOTEL_COMMAND_REDACT_SELECTED,
765#else
766 .mode = GOTEL_COMMAND_REDACT_NONE,
767#endif
768 .rules = command_argument_rules,
769 .sensitive_values = sensitive_values,
770 .sensitive_value_count =
771 sizeof(sensitive_values) / sizeof(sensitive_values[0]),
772 .rule_count =
773 sizeof(command_argument_rules) / sizeof(command_argument_rules[0]),
774 };
775 asciichat_error_t arguments_status =
776 otel_status(gotel_command_args_init_policy(
777 &command_args, "ascii-chat", mode, argc,
778 (const char *const *)argv, &argument_policy),
779 "Sanitize telemetry command arguments");
780 if (arguments_status != ASCIICHAT_OK)
781 return arguments_status;
782 config.argc = command_args.argc;
783 config.argv = command_args.argv;
784 gotel_env_storage_t env;
785 asciichat_error_t env_status = otel_status(
786 gotel_options_apply_env(&config, &env, OPT_OTEL_ENDPOINT_DEFAULT),
787 "Configure OTEL environment");
788 if (env_status == ASCIICHAT_OK &&
789 (endpoint_cli || SAFE_GETENV("ASCII_CHAT_OTEL_ENDPOINT") ||
790 strcmp(endpoint, OPT_OTEL_ENDPOINT_DEFAULT)))
791 env_status =
792 otel_status(gotel_options_set_endpoint(&config, &env, endpoint),
793 "Configure telemetry endpoint");
794 if (timeout_cli || SAFE_GETENV("ASCII_CHAT_OTEL_TIMEOUT")) {
795 config.exporter.connect_timeout_ms = (uint32_t)o->otel_timeout;
796 config.exporter.read_timeout_ms = (uint32_t)o->otel_timeout;
797 config.exporter.flush_timeout_ms = (uint32_t)o->otel_timeout;
798 }
799 // The final drain runs on the exporter worker. Keep its network waits
800 // interruptible by the shutdown deadline even when the collector is down.
801 const uint32_t shutdown_safe_timeout_ms = 500;
802 if (config.exporter.connect_timeout_ms > shutdown_safe_timeout_ms)
803 config.exporter.connect_timeout_ms = shutdown_safe_timeout_ms;
804 if (config.exporter.read_timeout_ms > shutdown_safe_timeout_ms)
805 config.exporter.read_timeout_ms = shutdown_safe_timeout_ms;
806 if (config.exporter.flush_timeout_ms > shutdown_safe_timeout_ms)
807 config.exporter.flush_timeout_ms = shutdown_safe_timeout_ms;
808 if (*o->otel_ca_file)
809 config.tls_ca_file = o->otel_ca_file;
810 if (env_status != ASCIICHAT_OK || !config.signals ||
811 !config.exporter.endpoint) {
812 gotel_command_args_destroy(&command_args);
813 return env_status;
814 }
815 gotel_host_t *h = NULL;
816 asciichat_error_t created =
817 otel_status(gotel_create(&config, &h), "Initialize telemetry exporter");
818 if (created != ASCIICHAT_OK) {
819 gotel_command_args_destroy(&command_args);
820 return created;
821 }
822 gotel_set_logger(h, exporter_diagnostic, NULL);
823 shutdown_timeout_ns = (uint64_t)o->otel_timeout * NS_PER_MS_INT;
824 atomic_store(&stopping, false);
825 atomic_store(&exporter_queue_capacity, config.exporter.queue_capacity);
826 atomic_store(&worker_done, false);
827 if (platform_thread_create(&worker, "otel_export", export_worker, h) != 0) {
828 gotel_destroy(h);
829 gotel_command_args_destroy(&command_args);
830 return SET_ERRNO(ERROR_THREAD, "Cannot start telemetry exporter");
831 }
832 worker_started = true;
833 (void)atexit(ascii_otel_shutdown);
834 atomic_ptr_store(&host, h);
835 gotel_begin(h, &command_scope, ASCII_OTEL_CLI, NULL);
836 (void)otel_status(gotel_command_args_set_span(&command_scope, &command_args),
837 "Attach telemetry command arguments");
838 gotel_command_args_destroy(&command_args);
839
840 log_info("Telemetry enabled: %s (%s)", config.exporter.endpoint,
842 return ASCIICHAT_OK;
843}
844void ascii_otel_log(int level, const char *file, int line, const char *function,
845 const char *format, va_list args) {
846 (void)file;
847 (void)line;
848 (void)function;
849 if (in_log || level < minimum_log_level || !atomic_ptr_load(&host))
850 return;
851 in_log = true;
852 gotel_host_t *h = retain();
853 if (h) {
854 char body[OTEL_BODY_BUFFER_SIZE];
855 int n = safe_vsnprintf(body, sizeof(body), format, args);
856 if (n >= 0) {
857 url_redact_diagnostic(body, (size_t)n >= sizeof(body));
858 otlp_severity_t severity = level >= LOG_FATAL ? OTLP_SEVERITY_FATAL
859 : level >= LOG_ERROR ? OTLP_SEVERITY_ERROR
860 : level >= LOG_WARN ? OTLP_SEVERITY_WARN
861 : level >= LOG_INFO ? OTLP_SEVERITY_INFO
862 : level >= LOG_DEBUG ? OTLP_SEVERITY_DEBUG
863 : OTLP_SEVERITY_TRACE;
864 gotel_log(h, severity, body, file, line, function);
865 }
866 release();
867 }
868 in_log = false;
869}
870gotel_context_t ascii_otel_context(void) { return gotel_current_context(); }
872 int64_t value) {
873 if (s->retained)
874 gotel_attr_int(&s->scope, key, value);
875}
877 const char *value) {
878 if (s->retained)
879 gotel_attr_string(&s->scope, key, value);
880}
881void ascii_otel_exit(int code) {
882 gotel_attr_int(&command_scope, "process.exit.code", code);
883 if (code)
884 gotel_error(&command_scope, "ascii_chat.exit", "Command failed");
885 else {
886 command_scope.failed = false;
887 if (command_scope.span)
888 (void)otel_status(
889 otlp_span_set_status(command_scope.span, OTLP_STATUS_CODE_UNSET, ""),
890 "otlp_span_set_status");
891 }
892}
893void ascii_otel_frame_rejected(const char *validator, const char *reason,
894 size_t bytes, uint32_t width, uint32_t height,
895 asciichat_error_t code) {
896 ascii_otel_metric(ASCII_OTEL_METRIC_FRAME_VALIDATION_REJECTED, 1);
897 gotel_context_t parent = ascii_otel_context();
898 ascii_otel_scope_t otel_scope
899 __attribute__((cleanup(ascii_otel_scope_end))) = {0};
900 if (!scope_retained(&otel_scope, ASCII_OTEL_FRAME_VALIDATION_REJECTED,
901 &parent))
902 return;
903 ASCII_OTEL_ATTR_STRING("frame.validation.validator", validator);
904 ASCII_OTEL_ATTR_STRING("frame.validation.reason", reason);
905 ASCII_OTEL_ATTR_INT("frame.size_bytes", (int64_t)bytes);
906 ASCII_OTEL_ATTR_INT("frame.width", width);
907 ASCII_OTEL_ATTR_INT("frame.height", height);
908 ASCII_OTEL_ATTR_INT("asciichat_errno.code", code);
909 ASCII_OTEL_ATTR_STRING("asciichat_errno.code_message",
910 asciichat_error_string(code));
911 if (otel_scope.retained)
912 gotel_error(&otel_scope.scope, "ascii_chat.invalid_frame", reason);
913}
915 const char *origin) {
916 if (code == ASCIICHAT_OK || code == ERROR_SIGNAL_INTERRUPT ||
919 if ((code >= ERROR_CRYPTO && code <= ERROR_CRYPTO_VERIFICATION) ||
920 code == ERROR_CRYPTO_INIT || code == ERROR_INVALID_PASSWORD ||
922 return ASCII_OTEL_FAILURE_CRYPTO;
923 if (code == ERROR_NETWORK_PROTOCOL || code == ERROR_NETWORK_SIZE ||
924 code == ERROR_UNKNOWN_PACKET)
925 return ASCII_OTEL_FAILURE_PROTOCOL;
926 if ((code >= ERROR_SESSION_NOT_FOUND && code <= ERROR_SESSION_FULL) ||
928 (origin && !strncmp(origin, "ascii-chat.discovery.", 21)))
929 return ASCII_OTEL_FAILURE_DISCOVERY;
931}
932void ascii_otel_error_code(asciichat_error_t code, const char *message) {
933 if (code == ASCIICHAT_OK || code == ERROR_SIGNAL_INTERRUPT ||
935 return;
936 char redacted[OTEL_BODY_BUFFER_SIZE];
937 int written =
938 safe_snprintf(redacted, sizeof(redacted), "%s", message ? message : "");
939 if (written < 0)
940 return;
941 url_redact_diagnostic(redacted, (size_t)written >= sizeof(redacted));
942 gotel_current_error("ascii_chat.error", redacted);
943 if (!ascii_otel_enabled())
944 return;
945 const char *origin = ascii_otel_current_operation();
947 if (operation == ASCII_OTEL_OPERATION_COUNT)
948 return;
949 const char *category = operation == ASCII_OTEL_FAILURE_CRYPTO ? "crypto"
950 : operation == ASCII_OTEL_FAILURE_PROTOCOL
951 ? "protocol"
952 : "discovery";
953 gotel_context_t parent = ascii_otel_context();
954 ascii_otel_scope_t report
955 __attribute__((cleanup(ascii_otel_scope_end))) = {0};
956 if (!scope_retained(&report, operation, &parent))
957 return;
958 gotel_attr_string(&report.scope, "ascii_chat.failure.category", category);
959 gotel_attr_string(&report.scope, "ascii_chat.failure.operation", origin);
960 gotel_attr_int(&report.scope, "asciichat_errno.code", code);
961 gotel_attr_string(&report.scope, "asciichat_errno.code_message",
962 asciichat_error_string(code));
963 gotel_error(&report.scope, category, redacted);
964}
965void ascii_otel_error(const char *message) {
966 char redacted[OTEL_BODY_BUFFER_SIZE];
967 int written =
968 safe_snprintf(redacted, sizeof(redacted), "%s", message ? message : "");
969 if (written < 0)
970 return;
971 url_redact_diagnostic(redacted, (size_t)written >= sizeof(redacted));
972 gotel_current_error("ascii_chat.error", redacted);
973}
974void ascii_otel_http(ascii_otel_scope_t *s, const char *hostname,
975 const char *path) {
976 if (!s->retained || !hostname || !path)
977 return;
978 gotel_error(&s->scope, "http.transport", "HTTP operation did not complete");
980 int n = safe_snprintf(url, sizeof(url), "https://%s%s", hostname, path);
981 if (n >= 0 && (size_t)n < sizeof(url) &&
982 otel_status(
983 gotel_http_name(name, sizeof(name), "ascii-chat", false, "GET", url),
984 "Name HTTP telemetry span") == ASCIICHAT_OK) {
985 if (s->scope.span)
986 (void)otel_status(otlp_span_set_name(s->scope.span, name),
987 "otlp_span_set_name");
988 gotel_http_attributes(&s->scope, "GET", 0);
989 gotel_attr_string(&s->scope, "server.address", hostname);
990 gotel_attr_string(&s->scope, "url.scheme", "https");
991 }
992}
994 if (s->retained) {
995 if (status > 0 && status < 400) {
996 s->scope.failed = false;
997 if (s->scope.span) {
998 (void)otel_status(
999 otlp_span_set_status(s->scope.span, OTLP_STATUS_CODE_UNSET, ""),
1000 "otlp_span_set_status");
1001 gotel_attr_string(&s->scope, "error.type", "");
1002 }
1003 }
1004 gotel_http_attributes(&s->scope, "GET", status);
1005 }
1006}
1007int ascii_otel_sqlite_prepare(sqlite3 *db, const char *sql,
1008 sqlite3_stmt **statement) {
1009 return gotel_sqlite_prepare_db(db, sql, statement);
1010}
1011
1012void ascii_otel_sqlite(sqlite3 *db, const gotel_query_t *queries,
1013 size_t count) {
1014 gotel_host_t *h = retain();
1015 if (!h)
1016 return;
1017 gotel_sqlite_t *a = NULL;
1018 sequel_analysis_options_t analysis = {.format = true};
1019 gotel_sqlite_options_t options = {.analysis = &analysis};
1020 if (otel_status(gotel_sqlite_attach_with_options(h, db, "ascii-chat.storage",
1021 queries, count, &options,
1022 &a),
1023 "Attach SQLite telemetry") != ASCIICHAT_OK)
1024 log_warn("Could not attach SQLite telemetry");
1025 release();
1026}
1027
1029 const gotel_query_catalog_t *catalog) {
1030 gotel_host_t *h = retain();
1031 if (!h)
1032 return;
1033 gotel_sqlite_t *a = NULL;
1034 sequel_analysis_options_t analysis = {.format = true};
1035 gotel_sqlite_options_t options = {.analysis = &analysis};
1036 if (otel_status(gotel_sqlite_attach_catalog_with_options(
1037 h, db, "ascii-chat.storage", catalog, &options, &a),
1038 "Attach SQLite telemetry") != ASCIICHAT_OK)
1039 log_warn("Could not attach SQLite telemetry");
1040 release();
1041}
bool errno_notifications_suppress(bool suppress)
#define SET_ERRNO(code,...)
void * atomic_ptr_exchange(atomic_ptr_t *a, void *new_value)
Atomically exchange a pointer and return the old value.
void atomic_ptr_store(atomic_ptr_t *a, void *value)
Atomically store a pointer.
void * atomic_ptr_load(atomic_ptr_t *a)
Atomically load a pointer.
unsigned int height
Definition fft.c:24
unsigned int width
Definition fft.c:24
unsigned short uint16_t
unsigned int uint32_t
#define SAFE_STRNCPY(dst, src, size)
#define SAFE_GETENV(name)
#define SAFE_SNPRINTF(buffer, buffer_size,...)
unsigned long long uint64_t
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
@ ERROR_INVALID_STATE
@ ERROR_NETWORK_CONNECT
Definition error_codes.h:79
@ ERROR_NETWORK_INCOMPLETE
Definition error_codes.h:97
@ ERROR_SIGNAL_INTERRUPT
@ ERROR_UNKNOWN_PACKET
Definition error_codes.h:95
@ ERROR_INVALID_PASSWORD
Definition error_codes.h:89
@ ERROR_ACDS_STRING_INVALID
Definition error_codes.h:93
@ ERROR_ACDS_STRING_TAKEN
Definition error_codes.h:91
@ ERROR_NETWORK
Definition error_codes.h:77
@ ERROR_CRYPTO_VERIFICATION
@ ERROR_RESOURCE_EXHAUSTED
@ ERROR_BUFFER_FULL
@ ERROR_NETWORK_PROTOCOL
Definition error_codes.h:81
@ ERROR_MEMORY
Definition error_codes.h:55
@ ASCIICHAT_OK
Definition error_codes.h:50
@ ERROR_STRING
@ ERROR_INVALID_SIGNATURE
Definition error_codes.h:90
@ ERROR_NETWORK_SIZE
Definition error_codes.h:83
@ ERROR_SESSION_FULL
Definition error_codes.h:88
@ ERROR_CRYPTO_INIT
Definition error_codes.h:57
@ ERROR_CONFIG
Definition error_codes.h:56
@ ERROR_CRYPTO
@ ERROR_INVALID_PARAM
@ ERROR_BUFFER_OVERFLOW
@ ERROR_INTERNAL
Definition error_codes.h:94
@ ERROR_SESSION_NOT_FOUND
Definition error_codes.h:87
@ ERROR_NETWORK_TIMEOUT
Definition error_codes.h:80
@ ERROR_THREAD
@ ERROR_NOT_SUPPORTED
Definition error_codes.h:74
#define log_warn(...)
Log a WARN message.
Definition log/log.h:591
#define log_info(...)
Log an INFO message.
Definition log/log.h:578
#define log_debug(...)
Log a DEBUG message.
Definition log/log.h:565
int32_t vec_t __attribute__((vector_size(4 *4)))
SESSION_CREATED (PACKET_TYPE_ACIP_SESSION_CREATED) - Session created response.
Definition vector.h:42
#define NS_PER_SEC_INT
Definition time.h:173
#define NS_PER_MS_INT
Definition time.h:172
struct options_state options_t
Immutable, RCU-published snapshot of the application's runtime configuration.
#define OPT_OTEL_ENDPOINT_DEFAULT
Debug and Dev builds export to the local Spaniel Compose collector.
Definition options.h:349
const options_t * options_get(void)
Get pointer to current options struct (lock-free, thread-safe).
Definition rcu.c:513
#define OPTIONS_BUFF_SIZE
Buffer size for option string values.
Definition options.h:305
#define PROTOCOL_VERSION_MAJOR
Major protocol version number.
#define PROTOCOL_VERSION_MINOR
Minor protocol version number.
#define PROTOCOL_VERSION_PATCH
Patch protocol version number.
void url_redact_diagnostic(char *text, bool truncated)
Definition url.c:32
const char * acip_packet_type_name(uint16_t type)
Get human-readable name for packet type.
Definition handlers.c:579
⚙️ Common definitions, error codes, macros, and types shared throughout the application
Transport abstraction layer for ACIP protocol.
@ ACIP_TRANSPORT_TCP
Raw TCP socket.
@ ACIP_TRANSPORT_WEBSOCKET
WebSocket over TCP.
@ ACIP_TRANSPORT_WEBRTC
WebRTC DataChannel (P2P).
struct stats_scope stats_scope_t
void stats_scope_set_observer(stats_scope_t *scope, stats_observer_fn observer, void *context)
📝 Logging API with multiple log levels and terminal output control
#define LOG_DEV
Definition log/types.h:42
#define LOG_DEBUG
Definition log/types.h:43
#define LOG_FATAL
Definition log/types.h:47
#define LOG_ERROR
Definition log/types.h:46
#define LOG_WARN
Definition log/types.h:45
#define LOG_INFO
Definition log/types.h:44
🔢 Mathematical Utility Functions
ACIP protocol message structures and helpers.
bool mutex_stack_try_snapshot(mutex_wait_snapshot_t *waits, size_t capacity, size_t *count, bool *limited)
Definition mutex.c:529
Per-thread mutex lock stack for deadlock detection.
action_args_t args
deferred_action_t action
⚙️ Unified options parsing system for ascii-chat with builder pattern and lock-free access
void ascii_otel_error_code(asciichat_error_t code, const char *message)
Definition otel.c:932
#define OTEL_VERSION_BUFFER_SIZE
Definition otel.c:6
void ascii_otel_scope_parent(ascii_otel_scope_t *s, ascii_otel_operation_t op, const gotel_context_t *parent)
Definition otel.c:448
#define OTEL_NAME_EXTENDED_BUFFER_SIZE
Definition otel.c:9
bool ascii_otel_enabled(void)
Definition otel.c:171
#define OTEL_WAIT_SNAPSHOT_CAPACITY
Definition otel.c:12
void ascii_otel_test_set_host(gotel_host_t *value)
Definition otel.c:134
void ascii_otel_http(ascii_otel_scope_t *s, const char *hostname, const char *path)
Definition otel.c:974
void ascii_otel_shutdown(void)
Definition otel.c:548
int ascii_otel_sqlite_prepare(sqlite3 *db, const char *sql, sqlite3_stmt **statement)
Definition otel.c:1007
void ascii_otel_log(int level, const char *file, int line, const char *function, const char *format, va_list args)
Definition otel.c:844
gotel_context_t ascii_otel_context(void)
Definition otel.c:870
void ascii_otel_ui_usage(const char *screen, const char *event, uint64_t duration_ns)
Definition otel.c:506
void ascii_otel_exit(int code)
Definition otel.c:881
void ascii_otel_pipeline_progress(unsigned stage, unsigned expected)
Definition otel.c:298
void ascii_otel_stats_attach(stats_scope_t *scope)
Definition otel.c:237
ascii_otel_operation_t ascii_otel_failure_operation(asciichat_error_t code, const char *origin)
Definition otel.c:914
unsigned ascii_otel_test_reader_count(void)
Definition otel.c:137
void ascii_otel_scope_begin(ascii_otel_scope_t *s, ascii_otel_operation_t op)
Definition otel.c:445
void ascii_otel_scope_string(ascii_otel_scope_t *s, const char *key, const char *value)
Definition otel.c:876
@ stats_metric_count
Definition otel.c:184
const char * ascii_otel_current_operation(void)
Definition otel.c:165
double ascii_otel_pipeline_age(uint64_t now, uint64_t capture, uint64_t progress, bool expected)
Definition otel.c:324
gotel_scope_t * ascii_otel_test_command_scope(void)
Definition otel.c:138
void ascii_otel_sqlite_catalog(sqlite3 *db, const gotel_query_catalog_t *catalog)
Definition otel.c:1028
ascii_otel_metric_t ascii_otel_stats_metric(stats_record_kind_t kind, unsigned id)
Definition otel.c:197
void ascii_otel_request_shutdown(void)
Definition otel.c:172
void ascii_otel_scope_int(ascii_otel_scope_t *s, const char *key, int64_t value)
Definition otel.c:871
void ascii_otel_sqlite(sqlite3 *db, const gotel_query_t *queries, size_t count)
Definition otel.c:1012
#define OTEL_URL_BUFFER_SIZE
Definition otel.c:8
void ascii_otel_error(const char *message)
Definition otel.c:965
#define OTEL_BODY_BUFFER_SIZE
Definition otel.c:7
#define OTEL_NAME_BUFFER_SIZE
Definition otel.c:5
void ascii_otel_packet(ascii_otel_scope_t *scope, uint16_t type, size_t payload_size, const char *action, int transport)
Definition otel.c:524
void ascii_otel_scope_end(ascii_otel_scope_t *s)
Definition otel.c:497
void ascii_otel_metric(ascii_otel_metric_t metric, double value)
Definition otel.c:175
void ascii_otel_call_session_used(const char *session_string)
Definition otel.c:516
void ascii_otel_http_status(ascii_otel_scope_t *s, int status)
Definition otel.c:993
void ascii_otel_frame_rejected(const char *validator, const char *reason, size_t bytes, uint32_t width, uint32_t height, asciichat_error_t code)
Definition otel.c:893
asciichat_error_t ascii_otel_init(const char *mode, int argc, char **argv)
Definition otel.c:648
ascii_otel_operation_t
Definition otel.h:6
@ ASCII_OTEL_OPERATION_COUNT
Definition otel.h:10
#define ASCII_OTEL_SCOPE_PARENT(id, parent)
Definition otel.h:98
struct ascii_otel_scope ascii_otel_scope_t
ascii otel scope is intentionally a small, concrete record. Fields such as scope, retained,...
ascii_otel_metric_t
Definition otel.h:12
@ ASCII_OTEL_METRIC_COUNT
Definition otel.h:16
#define ASCII_OTEL_ATTR_INT(key, value)
Definition otel.h:94
#define ASCII_OTEL_ATTR_STRING(key, value)
Definition otel.h:92
Protocol version, features, compression, and frame flag constants.
static bool size_t gotel_query_t * out
Definition queries.h:10
🔤 String Manipulation and Shell Escaping Utilities
gotel_scope_t scope
Definition otel.h:32
bool retained
Definition otel.h:33
struct ascii_otel_scope * previous
Definition otel.h:34
Atomic value wrapper for integral/boolean types.
Definition atomic.h:114
For mutex wait snapshot, this is the live record that ties mutex_key, thread_key, since_ns,...
Definition mutex.h:122
uint64_t since_ns
Definition mutex.h:125
uint64_t span_start_unix_ns
Definition mutex.h:133
char otel_ca_file[256]
Definition options.h:1152
int otel_realtime_max_per_second
Definition options.h:1155
double otel_realtime_sample_rate
Definition options.h:1154
int otel_metrics_interval
Definition options.h:1156
int otel_queue_capacity
Definition options.h:1158
char otel_endpoint[256]
Definition options.h:1151
char otel_log_level[256]
Definition options.h:1150
char address6[256]
IPv6 bind address (server only).
Definition options.h:1003
int port
Server port number.
Definition options.h:1004
char otel_enabled_telemetry[256]
Definition options.h:1153
char address[256]
Server address (client) or bind address (server).
Definition options.h:1002
Test environment detection utilities.
⏱️ High-precision timing utilities using sokol_time.h and uthash
🌐 Production-Grade URL Validation and Parsing