-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathapi.py
More file actions
3192 lines (2514 loc) · 115 KB
/
Copy pathapi.py
File metadata and controls
3192 lines (2514 loc) · 115 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import asyncio
import hashlib
import json
import logging
import time
import uuid
from collections.abc import AsyncIterator, Sequence
from contextlib import asynccontextmanager
from datetime import datetime
from typing import Any
from asyncmy import Pool # type: ignore[import-not-found]
from discord import Entitlement
from models import (
AISituationModel,
BlacklistEntryModel,
BlockedReporterModel,
ChannelOverwriteModel,
ClaimedBoosterChannelModel,
ClaimedBoosterRoleModel,
DetailedWarningModel,
DynamicSlowmodeMessageModel,
DynamicSlowmodeModel,
GiveawayBlacklistEntryModel,
GiveawayChannelRequirementModel,
GiveawayModel,
LeaveChannelModel,
LevelLeaderboardEntryModel,
LevelRoleModel,
LevelRolesGroupModel,
LogEnableModel,
ReportModel,
ScheduledMessageModel,
TicketMessageModel,
TicketModel,
TokenOverviewModel,
TriggerMessageChannelModel,
TriggerMessageModel,
TwitchOnlineNotificationModel,
UserLevelInfoModel,
WarnConfigModel,
WarningModel,
WelcomeChannelModel,
XpBoostModel,
)
# ── Log blacklist (delegated to LogBlacklistRepository) ─────────────────────────────
from repositories.log_blacklist_repository import LogBlacklistType, log_blacklist_repo
from utility import get_level_for_xp_async, get_xp_for_level_async
from utils.cache import StampedeProtectedCache, TTLCache
def _log_blacklist_cache_key(guild_id: str | int, blacklist_type: LogBlacklistType) -> tuple[str, str]:
return (str(guild_id), blacklist_type.name)
async def add_log_blacklist(guild_id: str, entity_id: str, blacklist_type: LogBlacklistType) -> None:
await log_blacklist_repo.add(guild_id, entity_id, blacklist_type)
_log_blacklist_cache.invalidate(_log_blacklist_cache_key(guild_id, blacklist_type))
async def remove_log_blacklist(guild_id: str, entity_id: str, blacklist_type: LogBlacklistType) -> None:
await log_blacklist_repo.remove(guild_id, entity_id, blacklist_type)
_log_blacklist_cache.invalidate(_log_blacklist_cache_key(guild_id, blacklist_type))
async def get_log_blacklist(guild_id: str, blacklist_type: LogBlacklistType) -> list[str]:
key = _log_blacklist_cache_key(guild_id, blacklist_type)
return await _log_blacklist_cache.get_or_fetch(
key,
lambda: log_blacklist_repo.get_all(guild_id, blacklist_type),
)
async def is_log_entity_blacklisted(guild_id: str, entity_id: str, blacklist_type: LogBlacklistType) -> str | None:
return await log_blacklist_repo.is_entity_blacklisted(guild_id, entity_id, blacklist_type)
logger = logging.getLogger(__name__)
class DatabaseManager:
"""Central database connection manager.
Owns the connection pool and provides lifecycle management.
All database operations in api.py resolve their pool through
this manager instead of relying on global ``_bot`` state.
"""
def __init__(self, pool: Any | None = None) -> None:
self._pool: Any | None = pool
@property
def is_ready(self) -> bool:
"""Check whether the pool has been initialized."""
return self._pool is not None
def set_pool(self, pool: Any) -> None:
"""Set or replace the connection pool."""
self._pool = pool
# ── High-level query methods ────────────────────────────────────────
async def execute_query(
self,
query: str,
params: Sequence[Any] | dict[str, Any] | None = None,
) -> list[tuple[Any, ...]] | None:
"""Execute a SELECT query and return all result rows."""
if not self.is_ready:
return None
async def _callback(cursor: Any, conn: Any) -> list[tuple[Any, ...]]:
return await cursor.fetchall()
return await _execute_with_retry("execute_query", _callback, query, params)
async def execute_action(
self,
query: str,
params: Sequence[Any] | dict[str, Any] | None = None,
) -> int | None:
"""Execute a write query (INSERT/UPDATE/DELETE) and return rowcount."""
if not self.is_ready:
return None
async def _callback(cursor: Any, conn: Any) -> int:
await conn.commit()
return cursor.rowcount
return await _execute_with_retry("execute_action", _callback, query, params, is_write=True)
async def execute_batch(
self,
query: str,
params_list: list[tuple],
) -> None:
"""Execute a batch INSERT using executemany for bulk operations."""
if not self.is_ready:
raise RuntimeError("Database pool is not initialized")
async def _callback(cursor: Any, conn: Any) -> None:
await cursor.executemany(query, params_list)
await conn.commit()
return None
await _execute_with_retry("execute_batch", _callback, query, is_write=True)
async def execute_insert_and_get_id(
self,
query: str,
params: Sequence[Any] | dict[str, Any] | None = None,
) -> int | None:
"""Execute an INSERT and return the last inserted row ID."""
if not self.is_ready:
return None
async def _callback(cursor: Any, conn: Any) -> int | None:
await conn.commit()
return cursor.lastrowid
return await _execute_with_retry("execute_insert_and_get_id", _callback, query, params, is_write=True)
async def check_health(self) -> bool:
"""Check if the database pool is healthy by running SELECT 1."""
if not self.is_ready:
return False
return await check_pool_health()
async def create_tables(self) -> None:
"""Create all database tables."""
if not self.is_ready:
return
await create_tables()
# Module-level singleton — all DB functions resolve pools through this instance.
db_manager = DatabaseManager()
# Backward-compatible aliases so existing code continues to work.
# New code should use ``from api import db_manager`` and access
# ``db_manager._pool`` / ``db_manager.is_ready`` directly.
_bot = None
def set_bot(bot) -> None:
"""Set the pool from a bot object (backward-compat).
Extracts ``bot._pool`` and stores it in the global
``DatabaseManager`` singleton. Also keeps the old
``_bot`` reference for code that checks ``_bot`` directly.
"""
global _bot
_bot = bot
if bot is not None and hasattr(bot, "_pool") and bot._pool is not None:
db_manager._pool = bot._pool
elif bot is None:
# Clear the manager's pool when clearing _bot so test resets work
db_manager._pool = None
def _get_pool() -> Pool | None:
"""Return the shared connection pool.
Delegates to ``db_manager._pool`` so that all functions
automatically use the DatabaseManager singleton.
Falls back to the old ``_bot._pool`` path for safety.
"""
if db_manager.is_ready:
return db_manager._pool
if _bot is not None and hasattr(_bot, "_pool") and _bot._pool is not None:
db_manager._pool = _bot._pool
return db_manager._pool
return None
# Max retries for transient DB failures
_MAX_DB_RETRIES = 5
# Pool acquire timeout in seconds
_POOL_ACQUIRE_TIMEOUT = 10
# Query execution timeout in seconds
_QUERY_TIMEOUT = 60
def _query_safe_id(query: str) -> str:
"""Return a deterministic opaque hash of a query for logging (no SQL/params leaked)."""
return hashlib.sha256(query.encode()).hexdigest()[:12]
def _sanitize_for_log(query: str, params: Any = None) -> str:
"""Log a safe query identifier without exposing raw SQL or parameters."""
return f"q={_query_safe_id(query)}"
def _release_pool_connection(pool, conn, *, broken: bool = False) -> None:
if broken:
conn.close()
pool.release(conn)
def _is_stale_pool_connection_error(exc: BaseException) -> bool:
msg = str(exc).lower()
return "at_eof" in msg or (isinstance(exc, AttributeError) and "_reader" in msg)
async def _purge_stale_pool_connections(pool) -> None:
clear = getattr(pool, "clear", None)
if clear is None:
return
try:
await clear()
except Exception:
pass
async def _execute_with_retry(
operation: str,
callback,
query: str,
params: Any = None,
bot=None,
*,
is_write: bool = False,
) -> Any:
"""Execute a DB operation with retry logic for transient failures.
For write operations (is_write=True), only retries on deadlock/server-abort
"""
pool = _get_pool()
if pool is None:
print(f"Tried to execute {operation} without pool. Pool is not yet initialized. {_sanitize_for_log(query)}")
return None
last_exception = None
safe_id = _sanitize_for_log(query)
_start = time.monotonic()
for attempt in range(_MAX_DB_RETRIES):
conn = None
broken_connection = False
try:
conn = await asyncio.wait_for(pool.acquire(), timeout=_POOL_ACQUIRE_TIMEOUT)
async with conn.cursor() as cursor:
await asyncio.wait_for(cursor.execute(query, params), timeout=_QUERY_TIMEOUT)
_result = await callback(cursor, conn)
if not is_write:
try:
await conn.rollback()
except Exception:
pass
_elapsed = time.monotonic() - _start
try:
from extensions.prometheus_metrics import record_db_query
record_db_query(operation, _elapsed, error=False)
except ImportError:
pass
return _result
except TimeoutError:
broken_connection = True
msg = f"Timeout on {operation} attempt {attempt + 1}/{_MAX_DB_RETRIES}: {safe_id}"
print(msg)
last_exception = TimeoutError(msg)
if attempt < _MAX_DB_RETRIES - 1:
await asyncio.sleep(0.5 * (attempt + 1))
continue
except Exception as e:
err_str = str(e).lower()
if is_write and ("duplicate column" in err_str or "duplicate key name" in err_str):
raise
stale_pool = _is_stale_pool_connection_error(e)
retryable = "deadlock" in err_str or "abort" in err_str or "restart transaction" in err_str or "record has changed" in err_str
if not is_write:
retryable = retryable or "connection" in err_str or "timeout" in err_str
if stale_pool:
retryable = True
if attempt < _MAX_DB_RETRIES - 1 and retryable:
if stale_pool:
await _purge_stale_pool_connections(pool)
if is_write and conn is not None:
try:
await conn.rollback()
except Exception:
pass
print(f"Transient error on {operation} attempt {attempt + 1}/{_MAX_DB_RETRIES}: {safe_id}")
await asyncio.sleep(0.5 * (attempt + 1))
last_exception = e
if stale_pool or "connection" in err_str or "timeout" in err_str:
broken_connection = True
continue
if is_write and conn is not None:
try:
await conn.rollback()
except Exception:
pass
_elapsed = time.monotonic() - _start
try:
from extensions.prometheus_metrics import record_db_query
record_db_query(operation, _elapsed, error=True)
except ImportError:
pass
print(f"Error during {operation}: {e} — {safe_id}")
raise
finally:
if conn is not None:
_release_pool_connection(pool, conn, broken=broken_connection)
if last_exception:
_elapsed = time.monotonic() - _start
try:
from extensions.prometheus_metrics import record_db_query
record_db_query(operation, _elapsed, error=True)
except ImportError:
pass
print(f"All retries exhausted for {operation}: {safe_id} — returning None to avoid crash")
return None
# ── Cache System ──────────────────────────────────────────────────────────────
# Centralised TTL caches. Each cache owns its TTL and (optionally) max size;
# LRU eviction happens automatically when ``maxsize`` is set.
_blacklist_cache: TTLCache[str, dict[str, list[BlacklistEntryModel]]] = TTLCache(ttl=30)
_guild_config_cache: TTLCache[str, dict[str, Any]] = TTLCache(ttl=300, maxsize=2000)
_log_enable_cache: StampedeProtectedCache[str, LogEnableModel] = StampedeProtectedCache(ttl=60, maxsize=5000)
_log_blacklist_cache: StampedeProtectedCache[tuple[str, str], list[str]] = StampedeProtectedCache(ttl=30, maxsize=5000)
_log_channel_cache: StampedeProtectedCache[str, str | None] = StampedeProtectedCache(ttl=60, maxsize=5000)
def clear_db_read_caches() -> None:
"""Reset hot-path read caches (for tests and maintenance)."""
_log_enable_cache.clear()
_log_blacklist_cache.clear()
_log_channel_cache.clear()
# In-memory cache for XP cooldowns: (guild_id, user_id) -> last_xp_gain_timestamp
# Eliminates DB queries entirely when user is on cooldown
_last_xp_gain_cache: dict[tuple[str, str], float] = {}
# In-memory cache for counting configs: channel_id -> (counting_config, challenge_config, modes_config)
# Reduces 3 DB queries per message to in-memory lookup
_counting_cache: TTLCache[str, tuple[dict | None, dict | None, dict | None]] = TTLCache(ttl=30)
def _invalidate_guild_cache(guild_id: str) -> None:
_blacklist_cache.delete(guild_id)
_guild_config_cache.delete(guild_id)
def invalidate_counting_cache(channel_id: str | int) -> None:
"""Remove the counting config cache entry for a specific channel."""
_counting_cache.delete(str(channel_id))
async def preload_guild_configs(bot=None) -> None:
"""Fetch all guild-level configs at startup to warm the cache.
Single bulk query replaces ~12+ individual queries per guild on first message.
"""
query = """
SELECT guild_id, active, difficulty, customFormula, level_up_messageActive,
level_up_message, level_up_channel_id, textCooldown, voiceCooldown
FROM levelConfig
"""
pool = _get_pool()
if pool is None:
return
_guild_config_cache.clear()
conn = None
broken_connection = False
try:
conn = await asyncio.wait_for(pool.acquire(), timeout=_POOL_ACQUIRE_TIMEOUT)
async with conn.cursor() as cursor:
await asyncio.wait_for(cursor.execute(query), timeout=_QUERY_TIMEOUT)
async for row in cursor:
guild_id = str(row[0])
_guild_config_cache.set(
guild_id,
{
"active": row[1],
"scaling": row[2],
"custom_formula": row[3],
"level_up_message_active": row[4],
"level_up_message": row[5],
"level_up_channel_id": row[6],
"text_cooldown": row[7],
"voice_cooldown": row[8],
},
)
except TimeoutError:
broken_connection = True
print("Error preloading guild configs: timed out while using database connection")
except Exception as e:
if "connection" in str(e).lower() or "timeout" in str(e).lower():
broken_connection = True
print(f"Error preloading guild configs: {e}")
finally:
if conn is not None:
_release_pool_connection(pool, conn, broken=broken_connection)
async def _get_cached_blacklist(guild_id: str) -> dict[str, list[BlacklistEntryModel]]:
"""Get blacklist with TTL cache (30s), reducing per-message DB queries by ~97%."""
cached = _blacklist_cache.get(guild_id)
if cached is not None:
return cached
data = await get_blacklist(guild_id)
_blacklist_cache.set(guild_id, data)
return data
async def _get_cached_config(guild_id: str, key: str, default: Any = None) -> Any:
"""Get a cached level config value with TTL check. Falls back to DB on miss."""
cache_entry = _guild_config_cache.get(guild_id)
if cache_entry is not None:
return cache_entry.get(key, default)
# Cache miss — reload from DB
query = """
SELECT guild_id, active, difficulty, customFormula, level_up_messageActive,
level_up_message, level_up_channel_id, textCooldown, voiceCooldown
FROM levelConfig WHERE guild_id = %s
"""
pool = _get_pool()
if pool is None:
return default
conn = None
broken_connection = False
try:
conn = await asyncio.wait_for(pool.acquire(), timeout=_POOL_ACQUIRE_TIMEOUT)
async with conn.cursor() as cursor:
await asyncio.wait_for(cursor.execute(query, (guild_id,)), timeout=_QUERY_TIMEOUT)
row = await cursor.fetchone()
if row:
data = {
"active": row[1],
"scaling": row[2],
"custom_formula": row[3],
"level_up_message_active": row[4],
"level_up_message": row[5],
"level_up_channel_id": row[6],
"text_cooldown": row[7],
"voice_cooldown": row[8],
}
_guild_config_cache.set(guild_id, data)
return data.get(key, default)
# Cache the miss (no levelConfig row for this guild)
_guild_config_cache.set(guild_id, {})
except TimeoutError:
broken_connection = True
print(f"Error caching guild config for {guild_id}: timed out while using database connection")
except Exception as e:
if "connection" in str(e).lower() or "timeout" in str(e).lower():
broken_connection = True
print(f"Error caching guild config for {guild_id}: {e}")
finally:
if conn is not None:
_release_pool_connection(pool, conn, broken=broken_connection)
return default
async def execute_query(
query: str, params: Sequence[Any] | dict[str, Any] | None = None, bot=None
) -> list[tuple[Any, ...]] | None:
async def _callback(cursor, connection):
result = await cursor.fetchall()
return result
return await _execute_with_retry("execute_query", _callback, query, params, bot)
async def execute_action(query: str, params: Sequence[Any] | dict[str, Any] | None = None, bot=None) -> int | None:
async def _callback(cursor, connection):
await connection.commit()
return cursor.rowcount
return await _execute_with_retry("execute_action", _callback, query, params, bot, is_write=True)
async def execute_batch(query: str, params_list: list[tuple], bot=None) -> None:
"""Execute a batch INSERT using executemany for bulk operations.
Reduces database round-trips by sending all rows in one query.
"""
pool = _get_pool()
if pool is None:
raise RuntimeError("Database pool is not initialized")
last_exception = None
safe_id = _query_safe_id(query)
_start = time.monotonic()
for attempt in range(_MAX_DB_RETRIES):
conn = None
broken_connection = False
try:
conn = await asyncio.wait_for(pool.acquire(), timeout=_POOL_ACQUIRE_TIMEOUT)
async with conn.cursor() as cursor:
await asyncio.wait_for(cursor.executemany(query, params_list), timeout=_QUERY_TIMEOUT)
await conn.commit()
return
except TimeoutError:
broken_connection = True
msg = f"Timeout on execute_batch attempt {attempt + 1}/{_MAX_DB_RETRIES}: {safe_id}"
print(msg)
last_exception = TimeoutError(msg)
if attempt < _MAX_DB_RETRIES - 1:
await asyncio.sleep(0.5 * (attempt + 1))
continue
except Exception as e:
err_str = str(e).lower()
if "connection" in err_str or "timeout" in err_str:
broken_connection = True
# Determine which errors are safe to retry (mirroring _execute_with_retry for write operations)
retryable = "deadlock" in err_str or "duplicate" in err_str or "abort" in err_str
if attempt < _MAX_DB_RETRIES - 1 and retryable:
print(f"Transient error on execute_batch attempt {attempt + 1}/{_MAX_DB_RETRIES}: {safe_id}")
await asyncio.sleep(0.5 * (attempt + 1))
last_exception = e
continue
# Non-retryable error or final attempt: raise instead of silently failing
_elapsed = time.monotonic() - _start
try:
from extensions.prometheus_metrics import record_db_query
record_db_query("execute_batch", _elapsed, error=True)
except ImportError:
pass
print(f"Error during execute_batch: {e} — {safe_id}")
raise
finally:
if conn is not None:
_release_pool_connection(pool, conn, broken=broken_connection)
if last_exception:
_elapsed = time.monotonic() - _start
try:
from extensions.prometheus_metrics import record_db_query
record_db_query("execute_batch", _elapsed, error=True)
except ImportError:
pass
print(f"All retries exhausted for execute_batch: {safe_id}")
raise last_exception
async def execute_insert_and_get_id(query: str, params: Sequence[Any] | dict[str, Any] | None = None, bot=None) -> int | None:
async def _callback(cursor, connection):
await connection.commit()
await cursor.execute("SELECT LAST_INSERT_ID()")
last_id = await cursor.fetchone()
return last_id[0] if last_id else None
return await _execute_with_retry("execute_insert_and_get_id", _callback, query, params, bot, is_write=True)
async def execute_query_iter(
query: str, params: Sequence[Any] | dict[str, Any] | None = None, bot=None
) -> AsyncIterator[tuple[Any, ...]]:
"""Async generator that yields rows one at a time for large result sets."""
pool = _get_pool()
if pool is None:
print(f"Tried to execute_query_iter without pool. {_sanitize_for_log(query)}")
return
safe_id = _query_safe_id(query)
yielded_any = False
for attempt in range(_MAX_DB_RETRIES):
conn = None
broken_connection = False
try:
conn = await asyncio.wait_for(pool.acquire(), timeout=_POOL_ACQUIRE_TIMEOUT)
async with conn.cursor() as cursor:
await asyncio.wait_for(cursor.execute(query, params), timeout=_QUERY_TIMEOUT)
async for row in cursor:
yielded_any = True
yield row
try:
await conn.rollback()
except Exception:
pass
return
except TimeoutError:
broken_connection = True
if yielded_any:
logger.error(f"Timeout after yielding rows on execute_query_iter: {safe_id}")
raise
print(f"Timeout on execute_query_iter attempt {attempt + 1}/{_MAX_DB_RETRIES}: {safe_id}")
if attempt < _MAX_DB_RETRIES - 1:
await asyncio.sleep(0.5 * (attempt + 1))
continue
except Exception as e:
if yielded_any:
logger.error(f"Error after yielding rows during query iteration: {e} — {safe_id}")
raise
err_str = str(e).lower()
retryable = "deadlock" in err_str or "connection" in err_str or "timeout" in err_str
if attempt < _MAX_DB_RETRIES - 1 and retryable:
print(f"Transient error on execute_query_iter attempt {attempt + 1}/{_MAX_DB_RETRIES}: {safe_id}")
await asyncio.sleep(0.5 * (attempt + 1))
if "connection" in err_str or "timeout" in err_str:
broken_connection = True
continue
print(f"Error during query iteration: {e} — {safe_id}")
return
finally:
if conn is not None:
_release_pool_connection(pool, conn, broken=broken_connection)
print(f"All retries exhausted for execute_query_iter: {safe_id}")
async def safe_execute_query(
query: str, params: Sequence[Any] | dict[str, Any] | None = None, bot=None
) -> list[tuple[Any, ...]]:
"""Like execute_query but always returns a list (empty on error)."""
try:
result = await execute_query(query, params, bot)
if not result:
return []
return list(result)
except Exception:
return []
@asynccontextmanager
async def transaction(bot=None):
"""Async context manager for DB transactions with automatic rollback on error."""
pool = _get_pool()
if pool is None:
raise RuntimeError("Database pool is not initialized")
for attempt in range(_MAX_DB_RETRIES):
safe_id = str(uuid.uuid4())
conn = None
broken_connection = False
try:
conn = await asyncio.wait_for(pool.acquire(), timeout=_POOL_ACQUIRE_TIMEOUT)
try:
yield conn
await conn.commit()
except Exception:
await conn.rollback()
raise
return
except TimeoutError:
broken_connection = True
print(f"Timeout on transaction acquire attempt {attempt + 1}/{_MAX_DB_RETRIES}: {safe_id}")
if attempt < _MAX_DB_RETRIES - 1:
await asyncio.sleep(0.5 * (attempt + 1))
continue
except Exception as e:
err_str = str(e).lower()
if "connection" in err_str or "timeout" in err_str:
broken_connection = True
raise
finally:
if conn is not None:
_release_pool_connection(pool, conn, broken=broken_connection)
raise RuntimeError(f"Could not acquire database connection after {_MAX_DB_RETRIES} attempts [{safe_id}]")
async def check_pool_health(bot=None) -> bool:
"""Check if the database is responsive.
Uses a short-lived standalone connection instead of the shared pool
so that repeated health checks cannot exhaust the connection pool.
Previously, this function acquired from the pool with a timeout;
if the pool was full, the timeout leaked connections until the pool
was completely drained.
"""
try:
import asyncmy
import os
host = os.environ.get("MARIADB_HOST") or os.environ.get("MYSQL_HOST")
port = int(os.environ.get("MARIADB_PORT") or os.environ.get("MYSQL_PORT", "3306"))
user = os.environ.get("MARIADB_USER") or os.environ.get("MYSQL_USER")
password = os.environ.get("MARIADB_PASSWORD") or os.environ.get("MYSQL_PASSWORD")
db = os.environ.get("MARIADB_DATABASE") or os.environ.get("MYSQL_DATABASE")
if not all((host, user, password, db)):
# No DB config available — use pool-based health check as fallback
pool = _get_pool()
if pool is None:
return False
async with pool.acquire() as conn:
async with conn.cursor() as cursor:
await asyncio.wait_for(cursor.execute("SELECT 1"), timeout=5)
return True
conn = await asyncio.wait_for(
asyncmy.connect(
host=host, port=port, user=user, password=password, db=db,
connect_timeout=5,
),
timeout=8,
)
try:
async with conn.cursor() as cursor:
await asyncio.wait_for(cursor.execute("SELECT 1"), timeout=5)
return True
finally:
conn.close()
except Exception:
return False
async def bulk_update_user_xp(
guild_id: str,
updates: list[tuple[str, int]],
bot=None,
) -> None:
"""Update XP for multiple users in a single transaction."""
try:
async with transaction(bot) as conn, conn.cursor() as cursor:
for user_id, xp_to_add in updates:
await cursor.execute(
"INSERT INTO level (user_id, guild_id, xp) VALUES (%s, %s, %s) ON DUPLICATE KEY UPDATE xp = xp + %s",
(user_id, guild_id, xp_to_add, xp_to_add),
)
except Exception as e:
safe_id = _query_safe_id("bulk_update_user_xp")
print(f"Error during bulk XP update: {e} — {safe_id}")
def get_table_defs() -> dict[str, "TableDef"]:
"""Return table definitions as Pydantic TableDef models.
Use this for introspection, testing, and programmatic schema access.
Converted incrementally from get_table_definitions().
"""
from table_def_models.table_def import TableDef, col, idx
_t: dict[str, TableDef] = {}
# ── Simple tables (mostly 1-3 columns, no FKs) ────────────────────────
_t["channel_overwrites"] = TableDef(
name="channel_overwrites",
columns=[
col("id", "INT", pk=True, ai=True),
col("channel_id", "VARCHAR(20)", nullable=False),
col("role_id", "VARCHAR(20)", nullable=False),
col("overwrites", "JSON"),
col("created_at", "TIMESTAMP", default="CURRENT_TIMESTAMP"),
],
)
_t["message_tracking_opt_out"] = TableDef(
name="message_tracking_opt_out",
columns=[col("user_id", "VARCHAR(20)", pk=True)],
)
_t["counting"] = TableDef(
name="counting",
columns=[
col("channel_id", "VARCHAR(20)", pk=True),
col("progress", "INT UNSIGNED", default="0"),
col("last_counter_id", "VARCHAR(20)", default="NULL"),
col("guild_id", "VARCHAR(20)"),
],
)
_t["counting_challenge"] = TableDef(
name="counting_challenge",
columns=[
col("channel_id", "VARCHAR(20)", pk=True),
col("progress", "INT UNSIGNED", default="0"),
col("last_counter_id", "VARCHAR(20)", default="NULL"),
col("guild_id", "VARCHAR(20)"),
],
)
_t["counting_modes"] = TableDef(
name="counting_modes",
columns=[
col("channel_id", "VARCHAR(20)", pk=True),
col("progress", "INT", default="0"),
col("mode", "TINYINT UNSIGNED", default="0"),
col("goal", "INT"),
col("last_counter_id", "VARCHAR(20)", default="NULL"),
col("guild_id", "VARCHAR(20)"),
],
)
_t["wordchain"] = TableDef(
name="wordchain",
columns=[
col("channel_id", "VARCHAR(20)", pk=True),
col("word", "VARCHAR(1028)", default="NULL"),
col("last_user_id", "VARCHAR(20)", default="NULL"),
col("guild_id", "VARCHAR(20)"),
],
)
_t["blacklistedUser"] = TableDef(
name="blacklistedUser",
primary_key=["user_id", "guild_id"],
columns=[
col("user_id", "VARCHAR(20)", nullable=False),
col("guild_id", "VARCHAR(20)", nullable=False),
col("reason", "VARCHAR(255)", default="NULL"),
col("blacklisted_at", "TIMESTAMP", default="CURRENT_TIMESTAMP"),
],
)
_t["blacklisted_role"] = TableDef(
name="blacklisted_role",
primary_key=["role_id", "guild_id"],
columns=[
col("role_id", "VARCHAR(20)", nullable=False),
col("guild_id", "VARCHAR(20)", nullable=False),
col("reason", "VARCHAR(255)", default="NULL"),
col("blacklisted_at", "TIMESTAMP", default="CURRENT_TIMESTAMP"),
],
)
_t["blacklistedChannel"] = TableDef(
name="blacklistedChannel",
primary_key=["channel_id", "guild_id"],
columns=[
col("channel_id", "VARCHAR(20)", nullable=False),
col("guild_id", "VARCHAR(20)", nullable=False),
col("reason", "VARCHAR(255)", default="NULL"),
col("blacklisted_at", "TIMESTAMP", default="CURRENT_TIMESTAMP"),
],
)
_t["userXpBoost"] = TableDef(
name="userXpBoost",
primary_key=["user_id", "guild_id"],
columns=[
col("user_id", "VARCHAR(20)", nullable=False),
col("guild_id", "VARCHAR(20)", nullable=False),
col("boost", "DECIMAL(4, 2) UNSIGNED", default="1"),
col("additive", "TINYINT(1)", default="0"),
col("boosted_at", "TIMESTAMP", default="CURRENT_TIMESTAMP"),
],
)
_t["roleXpBoost"] = TableDef(
name="roleXpBoost",
primary_key=["role_id", "guild_id"],
columns=[
col("role_id", "VARCHAR(20)", nullable=False),
col("guild_id", "VARCHAR(20)", nullable=False),
col("boost", "DECIMAL(4, 2) UNSIGNED", default="1"),
col("additive", "TINYINT(1)", default="0"),
col("boosted_at", "TIMESTAMP", default="CURRENT_TIMESTAMP"),
],
)
_t["channelXpBoost"] = TableDef(
name="channelXpBoost",
primary_key=["channel_id", "guild_id"],
columns=[
col("channel_id", "VARCHAR(20)", nullable=False),
col("guild_id", "VARCHAR(20)", nullable=False),
col("boost", "DECIMAL(4, 2) UNSIGNED", default="1"),
col("additive", "TINYINT(1)", default="0"),
col("boosted_at", "TIMESTAMP", default="CURRENT_TIMESTAMP"),
],
)
_t["levelRole"] = TableDef(
name="levelRole",
primary_key=["role_id", "guild_id"],
columns=[
col("role_id", "VARCHAR(20)", nullable=False),
col("guild_id", "VARCHAR(20)", nullable=False),
col("level", "INT UNSIGNED", default="0"),
],
)
_t["autopublish"] = TableDef(
name="autopublish",
columns=[col("channel_id", "VARCHAR(20)", pk=True)],
)
_t["feedbackBlocked"] = TableDef(
name="feedbackBlocked",
columns=[col("user_id", "VARCHAR(20)", pk=True)],
)
_t["afk_users"] = TableDef(
name="afk_users",
columns=[
col("user_id", "VARCHAR(20)", pk=True),
col("reason", "VARCHAR(1024)"),
],
)
_t["mediaChannel"] = TableDef(
name="mediaChannel",
columns=[
col("channel_id", "VARCHAR(20)", pk=True),
col("guild_id", "VARCHAR(20)"),
],
)
_t["brawlstarsLinkedAccounts"] = TableDef(
name="brawlstarsLinkedAccounts",
columns=[
col("user_id", "VARCHAR(20)", pk=True),
col("brawlstarsTag", "VARCHAR(20)"),
],
)
# ── Medium tables (5-10 columns, PK, indices) ─────────────────────────
_t["warnings"] = TableDef(
name="warnings",
columns=[
col("id", "INT", pk=True, ai=True),
col("guild_id", "VARCHAR(20)", nullable=False),
col("user_id", "VARCHAR(20)", nullable=False),
col("reason", "VARCHAR(255)"),
col("created_at", "TIMESTAMP", default="CURRENT_TIMESTAMP"),
col("expires_at", "TIMESTAMP", default="NULL"),
col("created_by", "VARCHAR(20)", nullable=False),
col("escalation_level", "INT", default="0"),
],
indices=[idx("idx_warnings_user_guild", "user_id", "guild_id")],
)
_t["warn_config"] = TableDef(
name="warn_config",
columns=[
col("guild_id", "VARCHAR(20)", pk=True),
col("expiration_days", "INT", default="0"),
col("timeout_threshold", "INT", default="0"),
col("timeout_duration", "INT", default="0"),
col("kick_threshold", "INT", default="0"),
col("ban_threshold", "INT", default="0"),
],
)
_t["level"] = TableDef(
name="level",
primary_key=["user_id", "guild_id"],
columns=[
col("user_id", "VARCHAR(20)", nullable=False),
col("guild_id", "VARCHAR(20)", nullable=False),
col("xp", "INT UNSIGNED", default="0"),
col("customBackground", "VARCHAR(255)", default="NULL"),
col("last_xp_gain", "DATETIME", default="NOW()"),
col("last_voice_xp_gain", "DATETIME", default="NOW()"),
],
indices=[idx("idx_level_guild_xp", "guild_id", "xp DESC")],
)
_t["levelConfig"] = TableDef(
name="levelConfig",
engine="InnoDB",
charset="utf8mb4",
columns=[
col("guild_id", "VARCHAR(20)", pk=True),
col("difficulty", "ENUM('easy', 'medium', 'hard', 'extreme', 'custom')", default="'medium'"),
col("customFormula", "VARCHAR(255)", default="NULL"),
col("level_up_messageActive", "TINYINT(1)", default="1"),
col("level_up_message", "VARCHAR(1000)", default="NULL"),
col("level_up_channel_id", "VARCHAR(20)", default="NULL"),
col("active", "TINYINT(1)", default="1"),
col("textCooldown", "INT", default="60"),
col("voiceCooldown", "INT", default="60"),
],
)
_t["aiToken"] = TableDef(
name="aiToken",
columns=[
col("freeToken", "SMALLINT UNSIGNED", default="500"),
col("plusToken", "SMALLINT UNSIGNED", default="0"),
col("paidToken", "INT UNSIGNED", default="0"),
col("usedToken", "INT UNSIGNED", default="0"),
col("user_id", "VARCHAR(20)", pk=True),
],
)
_t["afkMessages"] = TableDef(
name="afkMessages",
columns=[
col("user_id", "VARCHAR(20)", nullable=False),
col("messageId", "VARCHAR(20)", nullable=False),
col("channel_id", "VARCHAR(20)"),
],