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 File Reference

💓 Client keepalive: periodic ping/pong exchange for reliable connection failure detection More...

Go to the source code of this file.

Macros

#define PING_INTERVAL_NS   (1LL * NS_PER_SEC_INT)
#define PING_SLEEP_INTERVAL_NS   (1LL * NS_PER_SEC_INT)

Functions

int keepalive_start_thread (client_connection_t *connection)
 Start keepalive/ping thread.
void keepalive_stop_thread (client_connection_t *connection)
 Stop keepalive/ping thread.
bool keepalive_thread_exited (client_connection_t *connection)
 Check if keepalive thread has exited.

Detailed Description

💓 Client keepalive: periodic ping/pong exchange for reliable connection failure detection

The keepalive system uses a dedicated ping thread:

  • Ping Thread: Sends periodic ping packets to server
  • Response Monitoring: Server responds with pong packets
  • Timeout Detection: Connection loss detected via failed pings
  • Coordinated Shutdown: Thread integrates with global shutdown logic

Timing Strategy

Keepalive timing optimized for connection reliability:

  • Ping Interval: 1 second between ping packets
  • Server Timeout: Server times out clients after 5 seconds of silence
  • Safety Margin: 4-second buffer prevents false disconnections
  • Network Tolerance: Accounts for network jitter and processing delays

Thread Management

Ping thread follows robust lifecycle management:

  • Creation: Thread started after successful connection
  • Monitoring: Continuous health checks and connection validation
  • Coordination: Respects global shutdown flags and connection state
  • Termination: Graceful shutdown with resource cleanup
  • Recovery: Thread recreated for each new connection

Connection Health Monitoring

Multiple layers of connection health detection:

  1. Socket Validity: Check socket file descriptor before sending
  2. Connection Flags: Monitor atomic connection state variables
  3. Send Failures: Detect network errors during ping transmission
  4. Global Shutdown: Respect application-wide shutdown requests

Integration Points

  • main.c: Keepalive thread lifecycle management
  • server.c: Ping packet transmission and connection monitoring
  • protocol.c: Pong packet reception and response handling
  • network.c: Low-level ping/pong packet formatting

Error Handling

Keepalive errors handled with appropriate escalation:

  • Ping Send Failures: Signal connection loss for reconnection
  • Socket Errors: Clean thread exit and connection cleanup
  • Network Timeouts: Graceful handling without false alarms
  • Thread Failures: Log errors and continue with degraded monitoring

Resource Management

Minimal resource usage for efficient keepalive:

  • Thread Resources: Single lightweight thread with minimal stack
  • Network Overhead: Small ping/pong packets with minimal bandwidth
  • Timing Precision: Efficient sleep implementation with early wake
  • Memory Usage: No dynamic allocations in steady-state operation
Author
Zachary Fogg me@zf.nosp@m.o.gg
Date
2025

Definition in file keepalive.c.

Macro Definition Documentation

◆ PING_INTERVAL_NS

#define PING_INTERVAL_NS   (1LL * NS_PER_SEC_INT)

Ping interval in nanoseconds (must be less than server timeout)

Definition at line 92 of file keepalive.c.

◆ PING_SLEEP_INTERVAL_NS

#define PING_SLEEP_INTERVAL_NS   (1LL * NS_PER_SEC_INT)

Sleep interval for ping timing loop (1 second in nanoseconds)

Definition at line 95 of file keepalive.c.

Function Documentation

◆ keepalive_start_thread()

int keepalive_start_thread ( client_connection_t * connection)

Start keepalive/ping thread.

Start keepalive/ping thread

Creates and starts the ping thread for connection keepalive. Must be called after successful server connection establishment.

Returns
0 on success, negative on error

Definition at line 209 of file keepalive.c.

209 {
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}
#define LOG_ERRNO_IF_SET(message)
void atomic_store_bool(atomic_t *a, bool value)
Atomically store a boolean value.
@ 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
thread_pool_t * client_worker_pool
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.

References ASCIICHAT_OK, atomic_store_bool(), client_connection::client_worker_pool, LOG_ERRNO_IF_SET, log_error, log_warn, client_connection::ping_thread_created, client_connection::ping_thread_exited, and thread_pool_spawn().

Referenced by client_protocol_start().

◆ keepalive_stop_thread()

void keepalive_stop_thread ( client_connection_t * connection)

Stop keepalive/ping thread.

Stop keepalive/ping thread

Gracefully stops the ping thread and cleans up resources. Safe to call multiple times.

Definition at line 235 of file keepalive.c.

235 {
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}
bool atomic_load_bool(atomic_t *a)
Atomic pointer wrapper.
#define log_debug(...)
Log a DEBUG message.
Definition log/log.h:589
#define NS_PER_MS_INT
Definition time.h:172

References atomic_load_bool(), log_debug, log_warn, NS_PER_MS_INT, client_connection::ping_thread_created, and client_connection::ping_thread_exited.

◆ keepalive_thread_exited()

bool keepalive_thread_exited ( client_connection_t * connection)

Check if keepalive thread has exited.

Check if keepalive thread has exited

Returns
true if thread has exited, false otherwise

Definition at line 269 of file keepalive.c.

269 {
270 return atomic_load_bool(&connection->ping_thread_exited);
271}

References atomic_load_bool(), and client_connection::ping_thread_exited.