ascii-chat
Binary v0.16.50-198-g78f51665f
Library lib/v0.3.2-2240-g78f51665f
Video chat in your terminal
Loading...
Searching...
No Matches
keepalive.c
Go to the documentation of this file.
64
65#include "keepalive.h"
66#include "main.h"
67#include "../main.h" // Global exit API
68#include "server.h"
69#include "crypto.h"
70#include <ascii-chat/util/fps.h>
72
73#include <ascii-chat/common.h>
75#include <libplatform/compiler.h>
76#include <libplatform/system.h>
77#include <libplatform/terminal.h>
79
80#include <libplatform/atomic.h>
82
83/* ============================================================================
84 * Keepalive Thread Management
85 * ============================================================================ */
86
87/* ============================================================================
88 * Keepalive Configuration
89 * ============================================================================ */
90
92#define PING_INTERVAL_NS (1LL * NS_PER_SEC_INT)
93
95#define PING_SLEEP_INTERVAL_NS (1LL * NS_PER_SEC_INT)
96
97/* ============================================================================
98 * Ping Thread Implementation
99 * ============================================================================ */
100
126static void *ping_thread_func(void *arg) {
127 client_connection_t *connection = arg;
128
129#ifdef DEBUG_THREADS
130 log_debug("Ping thread started");
131#endif
132
133 // FPS tracking for keepalive thread (ping sent every 1 second)
134 fps_t fps_tracker = {0};
135 bool fps_tracker_initialized = false;
136 if (!fps_tracker_initialized) {
137 fps_init_with_interval(&fps_tracker, 1, "KEEPALIVE",
138 100 * NS_PER_MS_INT); // Report keepalive metrics every 100ms
139 fps_tracker_initialized = true;
140 }
141
142 // Startup grace period: Allow connection initialization to complete before checking state
143 // Prevents race condition where thread spawns before transport is fully configured
144 APP_CALLBACK_VOID(platform_pump_events);
145 platform_sleep_ms(100);
146
147 while (!should_exit() && !server_connection_is_lost(connection)) {
148 // Check if connection is still active before sending
149 if (!server_connection_is_active(connection)) {
150 log_debug("Connection inactive, exiting ping thread");
151 break;
152 }
153
154 // Send ping packet every PING_INTERVAL_SECONDS to keep connection alive
155 // Server timeout is 5 seconds, so 3-second pings provide safety margin
156 if (threaded_send_ping_packet(connection) != ASCIICHAT_OK) {
157 log_debug("Failed to send ping packet");
158 // Set connection lost flag so main loop knows to reconnect
159 server_connection_lost(connection);
160 break;
161 }
162
163 // Track ping for FPS reporting
164 uint64_t ping_start_ns = time_get_ns();
165 fps_frame_ns(&fps_tracker, ping_start_ns, "ping sent");
166
167 // Sleep with early wake capability for responsive shutdown
168 // Break sleep into intervals to check shutdown flags and rekey triggers
169 while (!should_exit() && !server_connection_is_lost(connection) && server_connection_is_active(connection)) {
170 uint64_t now_ns = time_get_ns();
171 uint64_t elapsed_ns = time_elapsed_ns(ping_start_ns, now_ns);
172
173 if (elapsed_ns >= PING_INTERVAL_NS) {
174 break; // Time for next ping
175 }
176
177 // Sleep for one interval or until next ping, whichever is sooner
178 uint64_t remaining_ns = PING_INTERVAL_NS - elapsed_ns;
179 uint64_t sleep_ns = (remaining_ns > PING_SLEEP_INTERVAL_NS) ? PING_SLEEP_INTERVAL_NS : remaining_ns;
180 platform_sleep_ns(sleep_ns);
181 }
182 }
183
184#ifdef DEBUG_THREADS
185 log_debug("Ping thread stopped");
186#endif
187
188 atomic_store_bool(&connection->ping_thread_exited, true);
189
190 // Clean up thread-local error context before exit
191
192 return NULL;
193}
194
195/* ============================================================================
196 * Public Interface Functions
197 * ============================================================================ */
198
210 if (connection->ping_thread_created) {
211 log_warn("Ping thread already created");
212 return 0;
213 }
214
215 // Start ping thread for keepalive
216 atomic_store_bool(&connection->ping_thread_exited, false);
217 if (thread_pool_spawn(connection->client_worker_pool, ping_thread_func, connection, 3, "keepalive_ping") != ASCIICHAT_OK) {
218 log_error("Failed to spawn ping thread in worker pool");
219 LOG_ERRNO_IF_SET("Ping thread creation failed");
220 return -1;
221 }
222
223 connection->ping_thread_created = true;
224 return 0;
225}
226
236 if (!connection)
237 return;
238 if (!connection->ping_thread_created) {
239 return;
240 }
241
242 // Don't call signal_exit() here - that's for global shutdown only!
243 // The ping thread monitors connection state and will exit when connection is lost
244
245 // Wait for thread to exit gracefully
246 int wait_count = 0;
247 while (wait_count < 20 && !atomic_load_bool(&connection->ping_thread_exited)) {
248 platform_sleep_ns(100 * NS_PER_MS_INT); // 100ms
249 wait_count++;
250 }
251
252 if (!atomic_load_bool(&connection->ping_thread_exited)) {
253 log_warn("Ping thread not responding - will be joined by thread pool");
254 }
255
256 // Thread will be joined by thread_pool_stop_all() in client_connection_stop()
257 connection->ping_thread_created = false;
258
259 log_debug("Ping thread stopped and joined");
260}
261
270 return atomic_load_bool(&connection->ping_thread_exited);
271}
Application-level callbacks for library code.
#define APP_CALLBACK_VOID(callback_name)
#define LOG_ERRNO_IF_SET(message)
void atomic_store_bool(atomic_t *a, bool value)
Atomically store a boolean value.
bool atomic_load_bool(atomic_t *a)
Atomic pointer wrapper.
ascii-chat Client Mode Entry Point Header
Named object registry for debugging — log identifiable resource names.
⏱️ FPS tracking utility for monitoring frame throughput across all threads
void fps_init_with_interval(fps_t *tracker, int expected_fps, const char *name, uint64_t report_interval_ns)
Initialize FPS tracker with custom report interval.
Definition fps.c:34
void fps_frame_ns(fps_t *tracker, uint64_t current_time_ns, const char *context)
Track a frame and detect lag conditions (nanosecond version - PRIMARY).
Definition fps.c:49
unsigned long long uint64_t
@ ASCIICHAT_OK
Definition error_codes.h:50
#define log_warn(...)
Log a WARN message.
Definition log/log.h:615
#define log_error(...)
Log an ERROR message.
Definition log/log.h:628
#define log_debug(...)
Log a DEBUG message.
Definition log/log.h:589
#define NS_PER_MS_INT
Definition time.h:172
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
void keepalive_stop_thread(client_connection_t *connection)
Stop keepalive/ping thread.
Definition keepalive.c:235
#define PING_INTERVAL_NS
Definition keepalive.c:92
bool keepalive_thread_exited(client_connection_t *connection)
Check if keepalive thread has exited.
Definition keepalive.c:269
#define PING_SLEEP_INTERVAL_NS
Definition keepalive.c:95
int keepalive_start_thread(client_connection_t *connection)
Start keepalive/ping thread.
Definition keepalive.c:209
ascii-chat Client Connection Keepalive Management Interface
bool should_exit(void)
Definition main.c:248
Global application exit and signal handling API.
struct client_connection client_connection_t
bool server_connection_is_active(client_connection_t *connection)
Establish connection to ascii-chat server.
void server_connection_lost(client_connection_t *connection)
Signal that connection has been lost.
bool server_connection_is_lost(client_connection_t *connection)
Check if connection loss has been detected.
asciichat_error_t threaded_send_ping_packet(client_connection_t *connection)
Thread-safe ping packet transmission.
ascii-chat Client Server Connection Management Interface
thread_pool_t * client_worker_pool
Counters and timestamps used to calculate and report frame rate.
Definition fps.h:57
asciichat_error_t thread_pool_spawn(thread_pool_t *pool, void *(*thread_func)(void *), void *thread_arg, int stop_id, const char *thread_name)
Spawn a worker thread in the pool.
🧵 Generic thread pool abstraction for managing worker threads
⏱️ High-precision timing utilities using sokol_time.h and uthash