This commit is contained in:
Slipstream 2025-05-06 17:58:59 -06:00
parent 5ca9881df8
commit 9577dce9f5
Signed by: slipstream
GPG Key ID: 13E498CE010AC6FD

View File

@ -1464,8 +1464,8 @@ def _get_log_toggle_cache_key(guild_id: int) -> str:
async def get_all_log_event_toggles(guild_id: int) -> Dict[str, bool]:
"""Gets all logging event toggle settings for a guild, checking cache first."""
if not pg_pool or not redis_pool:
log.warning(f"Pools not initialized, cannot get log toggles for guild {guild_id}.")
if not _active_pg_pool or not _active_redis_pool:
log.warning(f"Pools not initialized in settings_manager, cannot get log toggles for guild {guild_id}.")
return {}
cache_key = _get_log_toggle_cache_key(guild_id)
@ -1473,7 +1473,7 @@ async def get_all_log_event_toggles(guild_id: int) -> Dict[str, bool]:
# Try cache first
try:
cached_toggles = await asyncio.wait_for(redis_pool.hgetall(cache_key), timeout=2.0)
cached_toggles = await asyncio.wait_for(_active_redis_pool.hgetall(cache_key), timeout=2.0)
if cached_toggles:
log.debug(f"Cache hit for log toggles (Guild: {guild_id})")
# Convert string bools back to boolean
@ -1486,7 +1486,7 @@ async def get_all_log_event_toggles(guild_id: int) -> Dict[str, bool]:
# Cache miss or error, get from DB
log.debug(f"Cache miss for log toggles (Guild: {guild_id})")
try:
async with pg_pool.acquire() as conn:
async with _active_pg_pool.acquire() as conn:
records = await conn.fetch(
"SELECT event_key, enabled FROM logging_event_toggles WHERE guild_id = $1",
guild_id
@ -1498,14 +1498,14 @@ async def get_all_log_event_toggles(guild_id: int) -> Dict[str, bool]:
# Convert boolean values to strings for Redis Hash
toggles_to_cache = {key: str(value) for key, value in toggles.items()}
if toggles_to_cache: # Only set if there are toggles, otherwise cache remains empty
async with redis_pool.pipeline(transaction=True) as pipe:
async with _active_redis_pool.pipeline(transaction=True) as pipe:
pipe.delete(cache_key) # Clear potentially stale data
pipe.hset(cache_key, mapping=toggles_to_cache)
pipe.expire(cache_key, 3600) # Cache for 1 hour
await pipe.execute()
else:
# If DB is empty, ensure cache is also empty (or set a placeholder if needed)
await redis_pool.delete(cache_key)
await _active_redis_pool.delete(cache_key)
except Exception as e:
log.exception(f"Redis error setting cache for log toggles (Guild: {guild_id}): {e}")
@ -1517,15 +1517,15 @@ async def get_all_log_event_toggles(guild_id: int) -> Dict[str, bool]:
async def is_log_event_enabled(guild_id: int, event_key: str, default_enabled: bool = True) -> bool:
"""Checks if a specific logging event is enabled for a guild."""
if not pg_pool or not redis_pool:
log.warning(f"Pools not initialized, returning default for log event '{event_key}'.")
if not _active_pg_pool or not _active_redis_pool:
log.warning(f"Pools not initialized in settings_manager, returning default for log event '{event_key}'.")
return default_enabled
cache_key = _get_log_toggle_cache_key(guild_id)
# Try cache first
try:
cached_value = await asyncio.wait_for(redis_pool.hget(cache_key, event_key), timeout=2.0)
cached_value = await asyncio.wait_for(_active_redis_pool.hget(cache_key, event_key), timeout=2.0)
if cached_value is not None:
# log.debug(f"Cache hit for log event '{event_key}' status (Guild: {guild_id})")
return cached_value == 'True'
@ -1541,7 +1541,7 @@ async def is_log_event_enabled(guild_id: int, event_key: str, default_enabled: b
# log.debug(f"Cache miss for log event '{event_key}' (Guild: {guild_id})")
db_enabled_status = None
try:
async with pg_pool.acquire() as conn:
async with _active_pg_pool.acquire() as conn:
db_enabled_status = await conn.fetchval(
"SELECT enabled FROM logging_event_toggles WHERE guild_id = $1 AND event_key = $2",
guild_id, event_key
@ -1553,11 +1553,11 @@ async def is_log_event_enabled(guild_id: int, event_key: str, default_enabled: b
if db_enabled_status is not None: # Only cache if it was explicitly set in DB
try:
await asyncio.wait_for(
redis_pool.hset(cache_key, event_key, str(final_status)),
_active_redis_pool.hset(cache_key, event_key, str(final_status)),
timeout=2.0
)
# Ensure the hash key itself has an expiry
await redis_pool.expire(cache_key, 3600, nx=True) # Set expiry only if it doesn't exist
await _active_redis_pool.expire(cache_key, 3600, nx=True) # Set expiry only if it doesn't exist
except asyncio.TimeoutError:
log.warning(f"Redis timeout setting cache for log event '{event_key}' (Guild: {guild_id})")
except Exception as e:
@ -1570,13 +1570,13 @@ async def is_log_event_enabled(guild_id: int, event_key: str, default_enabled: b
async def set_log_event_enabled(guild_id: int, event_key: str, enabled: bool) -> bool:
"""Sets the enabled status for a specific logging event type."""
if not pg_pool or not redis_pool:
log.error(f"Pools not initialized, cannot set log event '{event_key}'.")
if not _active_pg_pool or not _active_redis_pool:
log.error(f"Pools not initialized in settings_manager, cannot set log event '{event_key}'.")
return False
cache_key = _get_log_toggle_cache_key(guild_id)
try:
async with pg_pool.acquire() as conn:
async with _active_pg_pool.acquire() as conn:
# Ensure guild exists
await conn.execute("INSERT INTO guilds (guild_id) VALUES ($1) ON CONFLICT (guild_id) DO NOTHING;", guild_id)
# Upsert the toggle status
@ -1590,16 +1590,16 @@ async def set_log_event_enabled(guild_id: int, event_key: str, enabled: bool) ->
)
# Update cache
await redis_pool.hset(cache_key, event_key, str(enabled))
await _active_redis_pool.hset(cache_key, event_key, str(enabled))
# Ensure the hash key itself has an expiry
await redis_pool.expire(cache_key, 3600, nx=True) # Set expiry only if it doesn't exist
await _active_redis_pool.expire(cache_key, 3600, nx=True) # Set expiry only if it doesn't exist
log.info(f"Set log event '{event_key}' enabled status to {enabled} for guild {guild_id}")
return True
except Exception as e:
log.exception(f"Database or Redis error setting log event '{event_key}' in guild {guild_id}: {e}")
# Attempt to invalidate cache field on error
try:
await redis_pool.hdel(cache_key, event_key)
await _active_redis_pool.hdel(cache_key, event_key)
except Exception as redis_err:
log.exception(f"Failed to invalidate Redis cache field for log event '{event_key}' (Guild: {guild_id}): {redis_err}")
return False