ascii-chat
Binary v0.16.114-28-gf5913657f
Library lib/v0.3.2-3302-gf5913657f
Video chat in your terminal
Loading...
Searching...
No Matches
memory.c
Go to the documentation of this file.
1
7
8/* Storage capacities in elements; text buffers include the terminating NUL. */
9#define NETWORK_RATE_LIMIT_MEMORY_KEY_BUFFER_SIZE 256
10
11/* Existing buffer budgets in bytes, including NUL for text storage. */
12#define RATE_LIMIT_INITIAL_EVENT_CAPACITY 100
13
15#include <ascii-chat/common.h>
16#include <recast/defer.h>
17#include <ascii-chat/log/log.h>
19#include <libplatform/compiler.h>
20#include <libplatform/mutex.h>
21#include <libplatform/system.h>
22#include <libplatform/terminal.h>
23#include <ascii-chat/uthash.h>
24#include <stdlib.h>
25#include <string.h>
26
45
49typedef struct {
51 mutex_t lock;
53
57static void make_key(const char *ip_address, rate_event_type_t event_type, char *key, size_t key_size) {
58 safe_snprintf(key, key_size, "%s:%d", ip_address, event_type);
59}
60
64static void add_timestamp(rate_event_t *event, uint64_t timestamp) {
65 if (event->count < event->capacity) {
66 // Buffer not full yet
67 event->timestamps[event->count++] = timestamp;
68 } else {
69 // Buffer full, overwrite oldest
70 event->timestamps[event->head] = timestamp;
71 event->head = (event->head + 1) % event->capacity;
72 }
73}
74
78static uint32_t count_events_in_window(rate_event_t *event, uint64_t window_start_ms) {
79 uint32_t count = 0;
80
81 for (size_t i = 0; i < event->count; i++) {
82 if (event->timestamps[i] >= window_start_ms) {
83 count++;
84 }
85 }
86
87 return count;
88}
89
93static void cleanup_old_events(rate_event_t *event, uint64_t cutoff_ns) {
94 // Compact array by removing old timestamps
95 size_t write_idx = 0;
96
97 for (size_t read_idx = 0; read_idx < event->count; read_idx++) {
98 if (event->timestamps[read_idx] >= cutoff_ns) {
99 event->timestamps[write_idx++] = event->timestamps[read_idx];
100 }
101 }
102
103 event->count = write_idx;
104 event->head = 0; // Reset circular buffer head
105}
106
107static asciichat_error_t memory_check(void *backend_data, const char *ip_address, rate_event_type_t event_type, const rate_limit_config_t *config, bool *allowed) {
108 memory_backend_t *backend = (memory_backend_t *)backend_data;
109
110 // Use provided config or default
111 const rate_limit_config_t *limit = config ? config : &DEFAULT_RATE_LIMITS[event_type];
112
113 // Get current time in nanoseconds
114 uint64_t now_ns = time_get_realtime_ns();
115 uint64_t window_start_ns = now_ns - ((uint64_t)limit->window_secs * NS_PER_SEC_INT);
116
117 // Create hash key
119 make_key(ip_address, event_type, key, sizeof(key));
120
121 mutex_lock(&backend->lock);
122
123 // Find event record
124 rate_event_t *event = NULL;
125 HASH_FIND_STR(backend->events, key, event);
126
127 uint32_t event_count = 0;
128
129 if (event) {
130 // Count events in window
131 event_count = count_events_in_window(event, window_start_ns);
132 }
133
134 mutex_unlock(&backend->lock);
135
136 // Check if limit exceeded
137 *allowed = (event_count < limit->max_events);
138
139 if (!*allowed) {
140 log_warn("Rate limit exceeded for %s (event: %s, count: %u/%u)", ip_address, rate_limiter_event_type_string(event_type), event_count, limit->max_events);
141 }
142
143 return ASCIICHAT_OK;
144}
145
146static asciichat_error_t memory_record(void *backend_data, const char *ip_address, rate_event_type_t event_type) {
147 memory_backend_t *backend = (memory_backend_t *)backend_data;
148
149 // Get current time in nanoseconds
150 uint64_t now_ns = time_get_realtime_ns();
151
152 // Create hash key
154 make_key(ip_address, event_type, key, sizeof(key));
155
156 mutex_lock(&backend->lock);
157
158 // Find or create event record
159 rate_event_t *event = NULL;
160 HASH_FIND_STR(backend->events, key, event);
161
162 if (!event) {
163 // Create new event record
164 event = SAFE_MALLOC(sizeof(rate_event_t), rate_event_t *);
165 if (!event) {
166 mutex_unlock(&backend->lock);
167 return SET_ERRNO(ERROR_MEMORY, "Failed to allocate rate event");
168 }
169
170 memset(event, 0, sizeof(*event));
171 SAFE_STRNCPY(event->key, key, sizeof(event->key));
172
173 // Allocate timestamp buffer (default: 100 events)
174 event->capacity = RATE_LIMIT_INITIAL_EVENT_CAPACITY;
175 event->timestamps = SAFE_MALLOC(sizeof(uint64_t) * event->capacity, uint64_t *);
176 if (!event->timestamps) {
177 SAFE_FREE(event);
178 mutex_unlock(&backend->lock);
179 return SET_ERRNO(ERROR_MEMORY, "Failed to allocate timestamp buffer");
180 }
181
182 HASH_ADD_STR(backend->events, key, event);
183 }
184
185 // Add timestamp (in nanoseconds)
186 add_timestamp(event, now_ns);
187
188 mutex_unlock(&backend->lock);
189
190 log_debug("Rate event recorded: %s - %s", ip_address, rate_limiter_event_type_string(event_type));
191 return ASCIICHAT_OK;
192}
193
194static asciichat_error_t memory_cleanup(void *backend_data, uint32_t max_age_secs) {
195 memory_backend_t *backend = (memory_backend_t *)backend_data;
196
197 // Default to 1 hour cleanup window
198 if (max_age_secs == 0) {
199 max_age_secs = SEC_PER_HOUR;
200 }
201
202 // Calculate cutoff time in nanoseconds
203 uint64_t now_ns = time_get_realtime_ns();
204 uint64_t cutoff_ns = now_ns - ((uint64_t)max_age_secs * NS_PER_SEC_INT);
205
206 mutex_lock(&backend->lock);
207
208 size_t total_removed = 0;
209 rate_event_t *event = NULL, *tmp = NULL;
210
211 HASH_ITER(hh, backend->events, event, tmp) {
212 size_t before_count = event->count;
213
214 // Remove old timestamps
215 cleanup_old_events(event, cutoff_ns);
216
217 total_removed += (before_count - event->count);
218
219 // Remove event record if empty
220 if (event->count == 0) {
221 HASH_DEL(backend->events, event);
222 SAFE_FREE(event->timestamps);
223 SAFE_FREE(event);
224 }
225 }
226
227 mutex_unlock(&backend->lock);
228
229 if (total_removed > 0) {
230 log_debug("Cleaned up %zu old rate events", total_removed);
231 }
232
233 return ASCIICHAT_OK;
234}
235
236static void memory_destroy(void *backend_data) {
237 memory_backend_t *backend = (memory_backend_t *)backend_data;
238 if (!backend) {
239 return;
240 }
241
242 // Free all event records
243 rate_event_t *event, *tmp;
244 HASH_ITER(hh, backend->events, event, tmp) {
245 HASH_DEL(backend->events, event);
246 SAFE_FREE(event->timestamps);
247 SAFE_FREE(event);
248 }
249
250 mutex_destroy(&backend->lock);
251 SAFE_FREE(backend);
252}
253
256 if (!backend) {
257 log_error("Failed to allocate memory backend");
258 return NULL;
259 }
260
261 defer_named(release_backend, SAFE_FREE(backend));
262 memset(backend, 0, sizeof(*backend));
263
264 if (mutex_init(&backend->lock, "rate_limiter") != 0) {
265 log_error("Failed to initialize mutex");
266 return NULL;
267 }
268
269 log_debug("Memory rate limiter backend initialized");
270 defer_cancel(release_backend);
271 return backend;
272}
273
275 .check = memory_check,
276 .record = memory_record,
277 .cleanup = memory_cleanup,
278 .destroy = memory_destroy,
279};
#define SET_ERRNO(code,...)
unsigned int uint32_t
#define SAFE_STRNCPY(dst, src, size)
#define SAFE_FREE(ptr)
#define SAFE_MALLOC(size, cast)
unsigned long long uint64_t
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
@ ERROR_MEMORY
Definition error_codes.h:55
@ ASCIICHAT_OK
Definition error_codes.h:50
#define log_warn(...)
Log a WARN message.
Definition log/log.h:591
#define log_error(...)
Log an ERROR message.
Definition log/log.h:604
#define log_debug(...)
Log a DEBUG message.
Definition log/log.h:565
#define SEC_PER_HOUR
Definition time.h:184
#define NS_PER_SEC_INT
Definition time.h:173
⚙️ Common definitions, error codes, macros, and types shared throughout the application
📝 Logging API with multiple log levels and terminal output control
void * memory_backend_create(void)
Create memory backend instance.
Definition memory.c:254
const rate_limiter_backend_ops_t memory_backend_ops
Memory backend operations vtable.
Definition memory.c:274
#define RATE_LIMIT_INITIAL_EVENT_CAPACITY
Definition memory.c:12
#define NETWORK_RATE_LIMIT_MEMORY_KEY_BUFFER_SIZE
Definition memory.c:9
struct rate_event_s rate_event_t
The useful part of memory backend is in events, lock: together they describe what is pending,...
🧠 In-memory rate limiting backend interface
const char * rate_limiter_event_type_string(rate_event_type_t event_type)
Get event type string for logging.
Definition rate_limit.c:193
const rate_limit_config_t DEFAULT_RATE_LIMITS[RATE_EVENT_MAX]
Default rate limits for each event type.
Definition rate_limit.c:33
rate_event_type_t
One sliding-window rate-limit policy.
Definition rate_limit.h:52
🔤 String Manipulation and Shell Escaping Utilities
Memory backend data.
Definition memory.c:49
mutex_t lock
Mutex for thread safety.
Definition memory.c:51
rate_event_t * events
Hash table of rate events.
Definition memory.c:50
The useful part of memory backend is in events, lock: together they describe what is pending,...
Definition memory.c:37
char key[256]
Hash key: "ip_address:event_type".
Definition memory.c:38
size_t count
Number of events in buffer.
Definition memory.c:40
UT_hash_handle hh
uthash handle
Definition memory.c:43
size_t capacity
Buffer capacity.
Definition memory.c:41
size_t head
Head index (oldest event).
Definition memory.c:42
uint64_t * timestamps
Array of timestamps (circular buffer).
Definition memory.c:39
One sliding-window rate-limit policy.
Definition rate_limit.h:77
uint32_t max_events
Maximum events allowed.
Definition rate_limit.h:78
uint32_t window_secs
Time window in seconds.
Definition rate_limit.h:79
Backend callbacks implementing rate-limit checks, recording, cleanup, and destruction.
Definition rate_limit.h:96
⏱️ High-precision timing utilities using sokol_time.h and uthash