ascii-chat
Binary v0.16.50-198-g78f51665f
Library lib/v0.3.2-2240-g78f51665f
Video chat in your terminal
Loading...
Searching...
No Matches
server.h File Reference

Go to the source code of this file.

Data Structures

struct  acds_client_data_t
 Network statistics for both TCP and WebSocket connections. More...
struct  acds_stats_t
 For acds client data, this is the live record that ties joined_session, negotiation, create_transport_length, create_keys together. The owning code creates it, updates it while work is active, and releases its handles and pointed-to storage before freeing the record. More...
struct  acds_server_t
 Discovery server state. More...

Functions

asciichat_error_t acds_server_init (acds_server_t *server, const acds_config_t *config)
 acds server is intentionally a small, concrete record. Fields such as network_server, handoff_mutex, handoffs, db give callers the identity and current value they need. It is normally borrowed from, or owned by, the surrounding subsystem—not independently managed.
void acds_server_shutdown (acds_server_t *server)
 Shutdown discovery server.
void acds_on_host_announcement (const acip_host_announcement_t *, acip_transport_t *, const char *, void *)
void acds_send_current_host (acds_server_t *, acip_transport_t *, const uint8_t[16])
void acds_on_host_announcement_ex (const acip_host_announcement_t *announcement, const void *metadata, size_t metadata_length, acip_transport_t *transport, const char *client_ip, void *app_ctx)

Variables

const network_connection_callbacks_t acds_network_callbacks

Function Documentation

◆ acds_on_host_announcement()

void acds_on_host_announcement ( const acip_host_announcement_t * announcement,
acip_transport_t * transport,
const char * client_ip,
void * app_ctx )

Definition at line 647 of file src/discovery-service/server.c.

647 {
648 acds_on_host_announcement_ex(announcement, NULL, 0, transport, client_ip, app_ctx);
649}
void acds_on_host_announcement_ex(const acip_host_announcement_t *announcement, const void *metadata, size_t metadata_length, acip_transport_t *transport, const char *client_ip, void *app_ctx)

References acds_on_host_announcement_ex(), and acip_host_announcement_t.

◆ acds_on_host_announcement_ex()

void acds_on_host_announcement_ex ( const acip_host_announcement_t * announcement,
const void * metadata,
size_t metadata_length,
acip_transport_t * transport,
const char * client_ip,
void * app_ctx )

Definition at line 651 of file src/discovery-service/server.c.

651 {
652
653 ASCII_OTEL_SCOPE(DISCOVERY_HOST_ANNOUNCE);
654 acds_server_t *server = (acds_server_t *)app_ctx;
655 ASCII_OTEL_ATTR_INT("host.generation", NET_TO_HOST_U32(announcement->generation));
656 ASCII_OTEL_ATTR_INT("host.decision.sequence", NET_TO_HOST_U32(announcement->sequence));
657 ASCII_OTEL_ATTR_STRING("host.update.outcome", "rejected");
658
659 log_info("HOST_ANNOUNCEMENT from %s: host_id=%02x%02x..., address=%.64s:%u, conn_type=%d", client_ip, announcement->host_id[0], announcement->host_id[1], announcement->host_address,
660 announcement->host_port, announcement->connection_type);
661
662 acds_client_data_t *client = transport ? transport->user_data : NULL;
663 if (!client || !client->joined_session || memcmp(client->participant_id, announcement->host_id, SESSION_ID_SIZE) || memcmp(client->session_id, announcement->session_id, SESSION_ID_SIZE)) {
664 ASCII_OTEL_ATTR_STRING("host.update.reason", "identity_mismatch");
665 acip_send_error(transport, ERROR_NETWORK_PROTOCOL, "Host announcement identity mismatch");
666 return;
667 }
668 if (!memchr(announcement->host_address, 0, sizeof(announcement->host_address)) || !announcement->host_port || announcement->connection_type > ACIP_CONNECTION_TYPE_TURN) {
669 ASCII_OTEL_ATTR_STRING("host.update.reason", "invalid_endpoint");
670 acip_send_error(transport, ERROR_NETWORK_PROTOCOL, "Invalid host endpoint");
671 return;
672 }
673 uint16_t quic_port;
674 char webtransport_url[512];
675 if (acds_transport_metadata_decode(metadata, metadata_length, &quic_port, webtransport_url, sizeof(webtransport_url)) != ASCIICHAT_OK) {
676 acip_send_error(transport, ERROR_NETWORK_PROTOCOL, "Invalid host transport metadata");
677 return;
678 }
679 const char *host_address = announcement->host_address[0] ? announcement->host_address : client_ip;
680 // Serialize authority validation, persistence and delivery with handoff commits.
681 mutex_lock(&server->handoff_mutex);
682 asciichat_error_t result = acds_update_announced_host(server, announcement, host_address, metadata, metadata_length);
683 mutex_unlock(&server->handoff_mutex);
684 ASCII_OTEL_ATTR_STRING("host.update.outcome", result == ASCIICHAT_OK ? "accepted" : "failed");
685 ASCII_OTEL_ATTR_INT("host.update.error_code", result);
686 if (result != ASCIICHAT_OK) {
687 acip_send_error(transport, result, "Host designation failed");
688 log_warn("Host designation failed: %s", asciichat_error_format(NULL, result));
689 return;
690 }
691 log_info("Session host updated via HOST_ANNOUNCEMENT from %s", client_ip);
692}
asciichat_error_t acds_transport_metadata_decode(const void *data, size_t length, uint16_t *port, char *url, size_t capacity)
const char * asciichat_error_format(const char *message, asciichat_error_t code)
#define NET_TO_HOST_U32(val)
Definition endian.h:85
unsigned short uint16_t
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
@ ERROR_NETWORK_PROTOCOL
Definition error_codes.h:80
@ ASCIICHAT_OK
Definition error_codes.h:50
#define SESSION_ID_SIZE
#define log_warn(...)
Log a WARN message.
Definition log/log.h:615
#define log_info(...)
Log an INFO message.
Definition log/log.h:602
@ ACIP_CONNECTION_TYPE_TURN
TURN relay (fallback).
Definition acds.h:846
#define ASCII_OTEL_SCOPE(id)
Definition otel.h:77
#define ASCII_OTEL_ATTR_INT(key, value)
Definition otel.h:72
#define ASCII_OTEL_ATTR_STRING(key, value)
Definition otel.h:71
asciichat_error_t acip_send_error(acip_transport_t *transport, uint32_t error_code, const char *message)
Send error message packet.
Definition send.c:402
Network statistics for both TCP and WebSocket connections.
bool joined_session
Whether client has successfully joined a session.
uint8_t participant_id[SESSION_ID_SIZE]
Participant UUID (valid if joined_session).
uint8_t session_id[SESSION_ID_SIZE]
Session UUID (valid if joined_session).
Discovery server state.
void * user_data
Application-specific context (e.g., per-client data).

References acds_transport_metadata_decode(), ACIP_CONNECTION_TYPE_TURN, acip_host_announcement_t, acip_send_error(), ASCII_OTEL_ATTR_INT, ASCII_OTEL_ATTR_STRING, ASCII_OTEL_SCOPE, asciichat_error_format(), ASCIICHAT_OK, ERROR_NETWORK_PROTOCOL, acds_server_t::handoff_mutex, acds_client_data_t::joined_session, log_info, log_warn, NET_TO_HOST_U32, acds_client_data_t::participant_id, acds_client_data_t::session_id, SESSION_ID_SIZE, and acip_transport::user_data.

Referenced by acds_on_host_announcement().

◆ acds_send_current_host()

void acds_send_current_host ( acds_server_t * ,
acip_transport_t * ,
const uint8_t [16] )

◆ acds_server_init()

asciichat_error_t acds_server_init ( acds_server_t * server,
const acds_config_t * config )

acds server is intentionally a small, concrete record. Fields such as network_server, handoff_mutex, handoffs, db give callers the identity and current value they need. It is normally borrowed from, or owned by, the surrounding subsystem—not independently managed.

Initialize discovery server

Loads or generates identity keys, opens database, creates session registry, and binds TCP socket.

Parameters
serverServer structure to initialize
configConfiguration from command-line parsing
Returns
ASCIICHAT_OK on success, error code otherwise

Definition at line 102 of file src/discovery-service/server.c.

102 {
103 ASCII_OTEL_SCOPE(DISCOVERY_INIT);
104 if (!server || !config) {
105 return SET_ERRNO(ERROR_INVALID_PARAM, "server or config is NULL");
106 }
107
108 memset(server, 0, sizeof(*server));
109 asciichat_error_t lock_result = mutex_init(&server->handoff_mutex, "acds_handoff");
110 if (lock_result != ASCIICHAT_OK)
111 return lock_result;
112 server->handoff_mutex_initialized = true;
113 memcpy(&server->config, config, sizeof(acds_config_t));
114
115 // Initialize stats
116 atomic_store_u64(&server->stats.bytes_sent, 0);
120 server->stats.start_time = time(NULL);
121
122 // Open database (SQLite as single source of truth)
123 asciichat_error_t result = database_init(config->database_path, &server->db);
124 if (result != ASCIICHAT_OK) {
125 goto init_failed;
126 }
127
128 // Initialize rate limiter with SQLite backend
129 server->rate_limiter = rate_limiter_create_sqlite(NULL); // NULL = externally managed DB
130 if (!server->rate_limiter) {
131 result = SET_ERRNO(ERROR_MEMORY, "Failed to create rate limiter");
132 goto init_failed;
133 }
134
135 // Set the database handle for the rate limiter
137
138 // Get TCP server from server_like (it owns the lifecycle)
140 if (!server->network_server) {
141 result = SET_ERRNO(ERROR_INVALID_STATE, "TCP server not available from server_like");
142 goto init_failed;
143 }
144
145 // Initialize background worker thread pool
146 atomic_store_bool(&server->shutdown, false);
147 server->worker_pool = thread_pool_create("acds_workers");
148 if (!server->worker_pool) {
149 log_warn("Failed to create worker thread pool");
150 result = SET_ERRNO(ERROR_MEMORY, "Failed to create worker thread pool");
151 goto init_failed;
152 }
153
154 // Spawn cleanup thread in worker pool
155 if (thread_pool_spawn(server->worker_pool, cleanup_thread_func, server, 0, "cleanup") != ASCIICHAT_OK) {
156 log_warn("Failed to spawn cleanup thread (continuing without cleanup)");
157 }
158
159 log_info("Discovery server initialized successfully");
160 return ASCIICHAT_OK;
161
162init_failed:
163 acds_server_shutdown(server);
164 return result;
165}
#define SET_ERRNO(code,...)
void atomic_store_bool(atomic_t *a, bool value)
Atomically store a boolean value.
void atomic_store_u64(atomic_t *a, uint64_t value)
Atomically store a uint64_t value.
asciichat_error_t database_init(const char *db_path, sqlite3 **db)
Initialize database and create schema.
@ ERROR_INVALID_STATE
@ ERROR_MEMORY
Definition error_codes.h:55
@ ERROR_INVALID_PARAM
void rate_limiter_set_sqlite_db(rate_limiter_t *limiter, void *db)
Set SQLite database handle for rate limiter.
Definition rate_limit.c:117
rate_limiter_t * rate_limiter_create_sqlite(const char *db_path)
Create SQLite-backed rate limiter.
Definition rate_limit.c:100
network_server_t * session_server_like_get_network_server(void)
void acds_server_shutdown(acds_server_t *server)
Shutdown discovery server.
Discovery server configuration.
char database_path[512]
SQLite database path.
acds_config_t config
Runtime configuration.
atomic_t shutdown
Shutdown flag for worker threads.
bool handoff_mutex_initialized
Whether shutdown owns the handoff mutex.
sqlite3 * db
SQLite database handle.
network_server_t * network_server
Network runtime owned by server_like.
acds_stats_t stats
Network statistics for all connections.
struct rate_limiter_s * rate_limiter
SQLite-backed rate limiter.
thread_pool_t * worker_pool
Thread pool for background workers.
atomic_t packets_received
Total packets received (TCP + WebSocket).
atomic_t packets_sent
Total packets sent (TCP + WebSocket).
atomic_t bytes_sent
Total bytes sent (TCP + WebSocket).
atomic_t bytes_received
Total bytes received (TCP + WebSocket).
time_t start_time
Server start time.
thread_pool_t * thread_pool_create(const char *pool_name)
Create a new thread pool (long-lived threads mode).
Definition thread_pool.c:92
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 acds_server_shutdown(), ASCII_OTEL_SCOPE, ASCIICHAT_OK, atomic_store_bool(), atomic_store_u64(), acds_stats_t::bytes_received, acds_stats_t::bytes_sent, acds_server_t::config, database_init(), acds_config_t::database_path, acds_server_t::db, ERROR_INVALID_PARAM, ERROR_INVALID_STATE, ERROR_MEMORY, acds_server_t::handoff_mutex, acds_server_t::handoff_mutex_initialized, log_info, log_warn, acds_server_t::network_server, acds_stats_t::packets_received, acds_stats_t::packets_sent, acds_server_t::rate_limiter, rate_limiter_create_sqlite(), rate_limiter_set_sqlite_db(), session_server_like_get_network_server(), SET_ERRNO, acds_server_t::shutdown, acds_stats_t::start_time, acds_server_t::stats, thread_pool_create(), thread_pool_spawn(), and acds_server_t::worker_pool.

◆ acds_server_shutdown()

void acds_server_shutdown ( acds_server_t * server)

Shutdown discovery server.

Closes listen socket, stops accepting connections, waits for handler threads to exit, closes database, and frees resources.

Parameters
serverServer structure to clean up

Definition at line 167 of file src/discovery-service/server.c.

167 {
168 ASCII_OTEL_SCOPE(DISCOVERY_SHUTDOWN);
169 if (!server) {
170 return;
171 }
172
173 // Signal shutdown to worker threads
174 atomic_store_bool(&server->shutdown, true);
175
176 // Stop and destroy worker thread pool (cleanup thread, etc.)
177 if (server->worker_pool) {
179 server->worker_pool = NULL;
180 log_debug("Worker thread pool stopped");
181 }
182
183 if (server->handoff_mutex_initialized) {
184 mutex_lock(&server->handoff_mutex);
185 while (server->handoffs) {
186 acds_handoff_entry_t *entry = server->handoffs;
187 server->handoffs = entry->next;
188 SAFE_FREE(entry);
189 }
190 mutex_unlock(&server->handoff_mutex);
191 mutex_destroy(&server->handoff_mutex);
192 server->handoff_mutex_initialized = false;
193 }
194
195 // Destroy rate limiter
196 if (server->rate_limiter) {
198 server->rate_limiter = NULL;
199 }
200
201 // Close database
202 if (server->db) {
203 database_close(server->db);
204 server->db = NULL;
205 }
206
207 log_info("Server shutdown complete");
208}
void database_close(sqlite3 *db)
Close database.
#define SAFE_FREE(ptr)
#define log_debug(...)
Log a DEBUG message.
Definition log/log.h:589
void rate_limiter_destroy(rate_limiter_t *limiter)
Destroy rate limiter and free resources.
Definition rate_limit.c:126
struct acds_handoff_entry acds_handoff_entry_t
Background thread for periodic cleanup.
struct acds_handoff_entry * next
struct acds_handoff_entry * handoffs
void thread_pool_destroy(thread_pool_t *pool)
Destroy a thread pool.

References ASCII_OTEL_SCOPE, atomic_store_bool(), database_close(), acds_server_t::db, acds_server_t::handoff_mutex, acds_server_t::handoff_mutex_initialized, acds_server_t::handoffs, log_debug, log_info, acds_handoff_entry::next, acds_server_t::rate_limiter, rate_limiter_destroy(), SAFE_FREE, acds_server_t::shutdown, thread_pool_destroy(), and acds_server_t::worker_pool.

Referenced by acds_server_init().

Variable Documentation

◆ acds_network_callbacks

const network_connection_callbacks_t acds_network_callbacks
extern

Definition at line 891 of file src/discovery-service/server.c.

891{acds_connection_open, acds_connection_packet, acds_connection_closing, acds_connection_closed};

Referenced by acds_main().