ascii-chat
Binary v0.16.50-198-g78f51665f
Library lib/v0.3.2-2240-g78f51665f
Video chat in your terminal
Loading...
Searching...
No Matches
sqlite.c
Go to the documentation of this file.
1
7
9#include <ascii-chat/otel.h>
10#include <ascii-chat/log/log.h>
12#include <sqlite3.h>
13#include <string.h>
14
16
22typedef struct {
23 sqlite3 *db;
25
26static asciichat_error_t sqlite_check(void *backend_data, const char *ip_address, rate_event_type_t event_type, const rate_limit_config_t *config, bool *allowed) {
27 sqlite_backend_t *backend = (sqlite_backend_t *)backend_data;
28
29 // Use provided config or default
30 const rate_limit_config_t *limit = config ? config : &DEFAULT_RATE_LIMITS[event_type];
31
32 // Get current time in nanoseconds
33 uint64_t now_ns = time_get_realtime_ns();
34 uint64_t window_start_ns = now_ns - ((uint64_t)limit->window_secs * NS_PER_SEC_INT);
35
36 // Count events in the time window
37 const char *sql = database_queries[DATABASE_QUERY_CountRateEvents].sql;
38
39 sqlite3_stmt *stmt = NULL;
40 int rc = ascii_otel_sqlite_prepare(backend->db, sql, &stmt);
41 if (rc != SQLITE_OK) {
42 return SET_ERRNO(ERROR_CONFIG, "Failed to prepare rate limit query: %s", sqlite3_errmsg(backend->db));
43 }
44
45 if ((sqlite3_bind_text(stmt, sqlite3_bind_parameter_index(stmt, ":ip_address"), ip_address, -1, SQLITE_STATIC) != SQLITE_OK) ||
46 (sqlite3_bind_text(stmt, sqlite3_bind_parameter_index(stmt, ":event_type"), rate_limiter_event_type_string(event_type), -1, SQLITE_STATIC) != SQLITE_OK) ||
47 (sqlite3_bind_int64(stmt, sqlite3_bind_parameter_index(stmt, ":window_start"), (sqlite3_int64)window_start_ns) != SQLITE_OK)) {
48 sqlite3_finalize(stmt);
49 return SET_ERRNO(ERROR_CONFIG, "Failed to bind SQLite query parameters");
50 }
51
52 rc = sqlite3_step(stmt);
53 if (rc != SQLITE_ROW) {
54 sqlite3_finalize(stmt);
55 return SET_ERRNO(ERROR_CONFIG, "Failed to execute rate limit query: %s", sqlite3_errmsg(backend->db));
56 }
57
58 uint32_t event_count = (uint32_t)sqlite3_column_int(stmt, 0);
59 sqlite3_finalize(stmt);
60
61 // Check if limit exceeded
62 *allowed = (event_count < limit->max_events);
63
64 if (!*allowed) {
65 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);
66 }
67
68 return ASCIICHAT_OK;
69}
70
71static asciichat_error_t sqlite_record(void *backend_data, const char *ip_address, rate_event_type_t event_type) {
72 sqlite_backend_t *backend = (sqlite_backend_t *)backend_data;
73
74 // Get current time in nanoseconds
75 uint64_t now_ns = time_get_realtime_ns();
76
77 // Insert event
78 const char *sql = database_queries[DATABASE_QUERY_InsertRateEvent].sql;
79
80 sqlite3_stmt *stmt = NULL;
81 int rc = ascii_otel_sqlite_prepare(backend->db, sql, &stmt);
82 if (rc != SQLITE_OK) {
83 return SET_ERRNO(ERROR_CONFIG, "Failed to prepare rate limit insert: %s", sqlite3_errmsg(backend->db));
84 }
85
86 if ((sqlite3_bind_text(stmt, sqlite3_bind_parameter_index(stmt, ":ip_address"), ip_address, -1, SQLITE_STATIC) != SQLITE_OK) ||
87 (sqlite3_bind_text(stmt, sqlite3_bind_parameter_index(stmt, ":event_type"), rate_limiter_event_type_string(event_type), -1, SQLITE_STATIC) != SQLITE_OK) ||
88 (sqlite3_bind_int64(stmt, sqlite3_bind_parameter_index(stmt, ":timestamp"), (sqlite3_int64)now_ns) != SQLITE_OK)) {
89 sqlite3_finalize(stmt);
90 return SET_ERRNO(ERROR_CONFIG, "Failed to bind SQLite query parameters");
91 }
92
93 rc = sqlite3_step(stmt);
94 sqlite3_finalize(stmt);
95
96 if (rc != SQLITE_DONE) {
97 return SET_ERRNO(ERROR_CONFIG, "Failed to record rate event: %s", sqlite3_errmsg(backend->db));
98 }
99
100 log_debug("Rate event recorded: %s - %s", ip_address, rate_limiter_event_type_string(event_type));
101 return ASCIICHAT_OK;
102}
103
104static asciichat_error_t sqlite_cleanup(void *backend_data, uint32_t max_age_secs) {
105 sqlite_backend_t *backend = (sqlite_backend_t *)backend_data;
106
107 // Default to 1 hour cleanup window
108 if (max_age_secs == 0) {
109 max_age_secs = SEC_PER_HOUR;
110 }
111
112 // Calculate cutoff time in nanoseconds
113 uint64_t now_ns = time_get_realtime_ns();
114 uint64_t cutoff_ns = now_ns - ((uint64_t)max_age_secs * NS_PER_SEC_INT);
115
116 // Delete old events
117 const char *sql = database_queries[DATABASE_QUERY_DeleteRateEvents].sql;
118
119 sqlite3_stmt *stmt = NULL;
120 int rc = ascii_otel_sqlite_prepare(backend->db, sql, &stmt);
121 if (rc != SQLITE_OK) {
122 return SET_ERRNO(ERROR_CONFIG, "Failed to prepare rate limit cleanup: %s", sqlite3_errmsg(backend->db));
123 }
124
125 if ((sqlite3_bind_int64(stmt, sqlite3_bind_parameter_index(stmt, ":cutoff_time"), (sqlite3_int64)cutoff_ns) != SQLITE_OK)) {
126 sqlite3_finalize(stmt);
127 return SET_ERRNO(ERROR_CONFIG, "Failed to bind SQLite query parameters");
128 }
129
130 rc = sqlite3_step(stmt);
131 int changes = sqlite3_changes(backend->db);
132 sqlite3_finalize(stmt);
133
134 if (rc != SQLITE_DONE) {
135 return SET_ERRNO(ERROR_CONFIG, "Failed to cleanup rate events: %s", sqlite3_errmsg(backend->db));
136 }
137
138 if (changes > 0) {
139 log_debug("Cleaned up %d old rate events", changes);
140 }
141
142 return ASCIICHAT_OK;
143}
144
145static void sqlite_destroy(void *backend_data) {
146 sqlite_backend_t *backend = (sqlite_backend_t *)backend_data;
147 if (!backend) {
148 return;
149 }
150
151 // Note: We don't close the database here because it's owned by the caller
152 // (ACDS server manages the database lifecycle)
153 free(backend);
154}
155
156void *sqlite_backend_create(const char *db_path) {
157 (void)db_path; // Database is provided externally, not created here
158
159 sqlite_backend_t *backend = malloc(sizeof(sqlite_backend_t));
160 if (!backend) {
161 log_error("Failed to allocate SQLite backend");
162 return NULL;
163 }
164
165 memset(backend, 0, sizeof(*backend));
166
167 // Database handle will be set after creation by ACDS
168 // This is a placeholder backend that will be initialized later
169 log_debug("SQLite rate limiter backend allocated (database will be set externally)");
170 return backend;
171}
172
178void sqlite_backend_set_db(void *backend_data, sqlite3 *db) {
179 sqlite_backend_t *backend = (sqlite_backend_t *)backend_data;
180 if (backend) {
181 backend->db = db;
182 }
183}
184
186 .check = sqlite_check,
187 .record = sqlite_record,
188 .cleanup = sqlite_cleanup,
189 .destroy = sqlite_destroy,
190};
#define SET_ERRNO(code,...)
unsigned int uint32_t
unsigned long long uint64_t
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
@ ASCIICHAT_OK
Definition error_codes.h:50
@ ERROR_CONFIG
Definition error_codes.h:56
#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 SEC_PER_HOUR
Definition time.h:184
#define NS_PER_SEC_INT
Definition time.h:173
📝 Logging API with multiple log levels and terminal output control
int ascii_otel_sqlite_prepare(sqlite3 *db, const char *sql, sqlite3_stmt **statement)
Definition otel.c:813
@ DATABASE_QUERY_DeleteRateEvents
@ DATABASE_QUERY_InsertRateEvent
@ DATABASE_QUERY_CountRateEvents
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
void sqlite_backend_set_db(void *backend_data, sqlite3 *db)
Set SQLite database handle for backend.
Definition sqlite.c:178
void * sqlite_backend_create(const char *db_path)
Create SQLite backend instance.
Definition sqlite.c:156
const rate_limiter_backend_ops_t sqlite_backend_ops
SQLite backend operations vtable.
Definition sqlite.c:185
💾 SQLite rate limiting backend interface
🔤 String Manipulation and Shell Escaping Utilities
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
This is the handoff point for sqlite backend. Callers fill db before passing it on; consumers read th...
Definition sqlite.c:22
sqlite3 * db
SQLite database handle.
Definition sqlite.c:23
⏱️ High-precision timing utilities using sokol_time.h and uthash