ascii-chat
Binary v0.16.50-198-g78f51665f
Library lib/v0.3.2-2240-g78f51665f
Video chat in your terminal
Loading...
Searching...
No Matches
lib/network/acip/server.c
Go to the documentation of this file.
1
12
13#include <ascii-chat/otel.h>
18#include <ascii-chat/buffer.h>
19#include <ascii-chat/log/log.h>
20#include <ascii-chat/common.h>
27#include <string.h>
28
29// =============================================================================
30// Server Receive (from client)
31// =============================================================================
32
34 ASCII_OTEL_SCOPE(ACIP_SERVER_RECEIVE_AND_DISPATCH);
35 uint64_t dispatch_start_ns = time_get_ns();
36 log_dev_every(4500 * US_PER_MS_INT, "ACIP_SERVER_DISPATCH: Entry, transport=%p, client_ctx=%p, callbacks=%p, timestamp=%llu", (void *)transport, client_ctx, (const void *)callbacks,
37 (unsigned long long)dispatch_start_ns);
38
39 if (!transport) {
40 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid transport (NULL)");
41 }
42 if (!callbacks) {
43 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid callbacks (NULL)");
44 }
45
46 // Check if transport is connected
47 if (!transport->methods->is_connected(transport)) {
48 return SET_ERRNO(ERROR_NETWORK, "Transport not connected");
49 }
50
51 packet_envelope_t envelope = {0};
52 asciichat_error_t received = packet_receive_via_transport(transport, &envelope.type, &envelope.data, &envelope.len, &envelope.allocated_buffer);
53 if (received != ASCIICHAT_OK)
54 return received;
55
56 // Dispatch packet to appropriate ACIP handler
57 // Server receives packets FROM clients, so use server packet handler
58 log_info("ACIP_DISPATCH_PKT: type=%d, len=%zu, client_ctx=%p", envelope.type, envelope.len, client_ctx);
59 log_info("📤 [FRAME_DISPATCH] Starting handler dispatch for packet type=%d (0x%04x), payload=%zu bytes", envelope.type, envelope.type, envelope.len);
60 uint64_t dispatch_handler_start_ns = time_get_ns();
61 asciichat_error_t dispatch_result = acip_handle_server_packet(transport, envelope.type, envelope.data, envelope.len, client_ctx, callbacks);
62 uint64_t dispatch_handler_end_ns = time_get_ns();
63 char handler_duration_str[TIME_DURATION_BUFFER_SIZE];
64 time_pretty((uint64_t)(dispatch_handler_end_ns - dispatch_handler_start_ns), -1, handler_duration_str, sizeof(handler_duration_str));
65 log_info("[WS_TIMING] Handler for type=%d took %s (result=%d)", envelope.type, handler_duration_str, dispatch_result);
66
67 if (dispatch_result != ASCIICHAT_OK) {
68 log_error("❌ [FRAME_DISPATCH_FAILED] Handler returned error for type=%d: %s", envelope.type, asciichat_error_format(NULL, dispatch_result));
69 } else {
70 log_info("✅ [FRAME_DISPATCH_SUCCESS] Handler completed successfully for type=%d", envelope.type);
71 }
72
73 // Always free the allocated buffer (even if handler failed)
74 if (envelope.allocated_buffer) {
75 buffer_release(envelope.allocated_buffer);
76 }
77
78 // Return handler result
79 return dispatch_result;
80}
81
82// =============================================================================
83// Server Send (to client)
84// =============================================================================
85
87 const acip_render_settings_t *settings, uint32_t effects, const char *client_id) {
88 ASCII_OTEL_SCOPE(ACIP_SEND_ASCII_FRAME_CONTRACT);
89 if (!transport || !frame_data || !workspace) {
90 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid transport or frame_data");
91 }
92
93 if (frame_size == 0) {
94 return SET_ERRNO(ERROR_INVALID_PARAM, "Empty frame data");
95 }
96
97 if (frame_size > UINT32_MAX) {
98 return SET_ERRNO(ERROR_NETWORK_SIZE, "ASCII frame is too large: %zu bytes", frame_size);
99 }
100
101 log_dev("SEND_ASCII_FRAME: client_id=%s, width=%u, height=%u, frame_size=%zu bytes", client_id, width, height, frame_size);
102
103 // Calculate CRC32 checksum of frame data for integrity verification
104 uint32_t checksum_value = asciichat_crc32(frame_data, frame_size);
105 log_debug("★ SEND_ASCII_FRAME: CRC32 checksum calculated: 0x%08x for %zu bytes", checksum_value, frame_size);
106
107 // Compress ANSI text before sending it. Native and browser clients decode zstd frames.
108 const void *payload_data = frame_data;
109 size_t payload_size = frame_size;
110 bool is_compressed = false;
111 if (frame_size >= COMPRESSION_MIN_SIZE && compress_workspace(&workspace->compression, frame_data, frame_size, 1) == ASCIICHAT_OK &&
112 should_compress(frame_size, workspace->compression.output.length)) {
113 payload_data = workspace->compression.output.data;
114 payload_size = workspace->compression.output.length;
115 is_compressed = true;
116 }
117
118 // Create ASCII frame packet header
120 header.width = HOST_TO_NET_U32(width);
121 header.height = HOST_TO_NET_U32(height);
122 header.original_size = HOST_TO_NET_U32((uint32_t)frame_size);
123 header.compressed_size = HOST_TO_NET_U32(is_compressed ? (uint32_t)payload_size : 0);
124 header.checksum = HOST_TO_NET_U32(checksum_value);
126 size_t contract_length = 0;
127 if (settings) {
128 asciichat_error_t encoded = frame_render_contract_encode(settings, effects, contract, &contract_length);
129 if (encoded != ASCIICHAT_OK)
130 return encoded;
131 }
132 header.flags = HOST_TO_NET_U32((is_compressed ? FRAME_FLAG_IS_COMPRESSED : 0) | (settings ? FRAME_FLAG_RENDER_CONTRACT : 0));
133
134 socket_buffer_t slices[3] = {{&header, sizeof(header)}};
135 size_t count = 1;
136 if (contract_length)
137 slices[count++] = (socket_buffer_t){contract, contract_length};
138 slices[count++] = (socket_buffer_t){payload_data, payload_size};
139 asciichat_error_t result = packet_send_via_transportv(transport, PACKET_TYPE_ASCII_FRAME, slices, count, 0);
140 return result;
141}
142
143asciichat_error_t acip_send_ascii_frame(acip_transport_t *transport, acip_frame_workspace_t *workspace, const char *text, size_t length, uint32_t width, uint32_t height, const char *client_id) {
144 return acip_send_ascii_frame_contract(transport, workspace, text, length, width, height, NULL, 0, client_id);
145}
146
148 if (!workspace)
149 return;
151}
152
154 if (!transport) {
155 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid transport");
156 }
157
158 return packet_send_via_transport(transport, PACKET_TYPE_CLEAR_CONSOLE, NULL, 0, 0);
159}
160
162 ASCII_OTEL_SCOPE(ACIP_SEND_SERVER_STATE);
163 if (!transport || !state) {
164 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid transport or state");
165 }
166
167 return packet_send_via_transport(transport, PACKET_TYPE_SERVER_STATE, state, sizeof(*state), 0);
168}
const char * asciichat_error_format(const char *message, asciichat_error_t code)
#define SET_ERRNO(code,...)
#define buffer_release(data)
Definition buffer.h:99
void compression_workspace_destroy(compression_workspace_t *workspace)
asciichat_error_t compress_workspace(compression_workspace_t *workspace, const void *input, size_t size, int level)
📦 Network Packet Compression Utilities
Hardware-Accelerated CRC32 Checksum Computation.
🔄 Network byte order conversion helpers
#define HOST_TO_NET_U32(val)
Definition endian.h:70
unsigned int height
Definition fft.c:24
unsigned int width
Definition fft.c:24
asciichat_error_t frame_render_contract_encode(const acip_render_settings_t *settings, uint32_t effects, uint8_t *wire, size_t *length)
unsigned int uint32_t
unsigned long long uint64_t
unsigned char uint8_t
#define COMPRESSION_MIN_SIZE
Minimum packet size to attempt compression (1KB).
Definition compression.h:66
bool should_compress(size_t original_size, size_t compressed_size)
Determine if compression should be used for given data sizes.
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
@ ERROR_NETWORK
Definition error_codes.h:76
@ ASCIICHAT_OK
Definition error_codes.h:50
@ ERROR_NETWORK_SIZE
Definition error_codes.h:81
@ ERROR_INVALID_PARAM
#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
int time_pretty(uint64_t nanoseconds, int decimals, char *buffer, size_t buffer_size)
Format nanoseconds as a compact duration with configurable sub-minute precision.
Definition time.c:368
#define TIME_DURATION_BUFFER_SIZE
Definition time.h:40
#define US_PER_MS_INT
Definition time.h:176
@ PACKET_TYPE_SERVER_STATE
Server sends current state to clients.
Definition packet.h:435
@ PACKET_TYPE_CLEAR_CONSOLE
Server tells client to clear console.
Definition packet.h:433
@ PACKET_TYPE_ASCII_FRAME
Complete ASCII frame with all metadata.
Definition packet.h:397
#define FRAME_FLAG_RENDER_CONTRACT
Explicit versioned render contract precedes encoded ASCII text.
#define FRAME_FLAG_IS_COMPRESSED
Frame data is compressed.
struct acip_transport acip_transport_t
Forward declaration of ACIP transport.
Definition host.h:508
#define asciichat_crc32(data, len)
Main CRC32 dispatcher macro - use this in application code.
Definition crc32.h:151
asciichat_error_t acip_handle_server_packet(acip_transport_t *transport, packet_type_t type, const void *payload, size_t payload_len, void *client_ctx, const acip_server_callbacks_t *callbacks)
Handle incoming packet on server side.
Definition handlers.c:730
ACIP protocol packet handlers (transport-agnostic).
⚙️ Common definitions, error codes, macros, and types shared throughout the application
ACIP server-side protocol API.
asciichat_error_t acip_send_server_state(acip_transport_t *transport, const server_state_packet_t *state)
Send server state update to client (server → client).
asciichat_error_t acip_server_receive_and_dispatch(acip_transport_t *transport, void *client_ctx, const acip_server_callbacks_t *callbacks)
Receive packet from client and dispatch to callbacks.
asciichat_error_t acip_send_ascii_frame_contract(acip_transport_t *transport, acip_frame_workspace_t *workspace, const char *frame_data, size_t frame_size, uint32_t width, uint32_t height, const acip_render_settings_t *settings, uint32_t effects, const char *client_id)
asciichat_error_t acip_send_clear_console(acip_transport_t *transport)
Send clear console command to client (server → client).
asciichat_error_t acip_send_ascii_frame(acip_transport_t *transport, acip_frame_workspace_t *workspace, const char *text, size_t length, uint32_t width, uint32_t height, const char *client_id)
void acip_frame_workspace_destroy(acip_frame_workspace_t *workspace)
📝 Logging API with multiple log levels and terminal output control
#define log_dev_every(interval_us, fmt,...)
Rate-limited DEV logging.
Definition log/log.h:740
#define ASCII_OTEL_SCOPE(id)
Definition otel.h:77
✅ Safe Integer Arithmetic and Overflow Detection
#define FRAME_RENDER_CONTRACT_MAX
asciichat_error_t packet_receive_via_transport(acip_transport_t *transport, packet_type_t *type, void **payload, size_t *payload_len, void **alloc_buffer)
Receive a packet via transport with header parsing and validation.
Definition send.c:192
asciichat_error_t packet_send_via_transportv(acip_transport_t *transport, packet_type_t type, const socket_buffer_t *payload, size_t count, uint32_t client_id)
Send arbitrary packet via transport (generic packet sender).
Definition send.c:150
asciichat_error_t packet_send_via_transport(acip_transport_t *transport, packet_type_t type, const void *payload, size_t payload_len, uint32_t client_id)
Definition send.c:183
ACIP shared/bidirectional packet sending functions.
🔤 String Manipulation and Shell Escaping Utilities
Send ASCII frame to client (server → client).
acip render settings keeps the values that move through the subsystem: caps, width,...
Server-side packet handler callbacks.
Definition handlers.h:147
bool(* is_connected)(acip_transport_t *transport)
Check if transport is connected.
const acip_transport_methods_t * methods
Method table (virtual functions).
The wire metadata for one rendered ASCII frame. width and height describe the terminal grid,...
Definition packet.h:916
uint32_t width
Terminal width in characters.
Definition packet.h:918
buffer_workspace_t output
Packet envelope containing received packet data.
Definition packet.h:1204
Server state packet structure.
Definition packet.h:757
⏱️ High-precision timing utilities using sokol_time.h and uthash