Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
95 commits
Select commit Hold shift + click to select a range
d02fb5c
feat(cache): implement caching system with Valkey and in-memory backends
kzndotsh Jan 28, 2026
fbbbfb2
docs(caching): update caching best practices and environment variable…
kzndotsh Jan 28, 2026
69c6300
feat(env): add Valkey configuration options and update example files
kzndotsh Jan 28, 2026
dacb7fc
feat(health): add Valkey health check to database health command
kzndotsh Jan 28, 2026
6f48a1c
feat(cache): implement CacheSetupService for Valkey integration
kzndotsh Jan 28, 2026
ce2a1a0
feat(cache): integrate CacheService for Valkey connection management
kzndotsh Jan 28, 2026
31d9e99
refactor(permission_system): switch to cache backend for command perm…
kzndotsh Jan 28, 2026
ef889e8
feat(prefix_manager): integrate cache backend for prefix management
kzndotsh Jan 28, 2026
cb02d66
feat(database): integrate cache backend for database controllers
kzndotsh Jan 28, 2026
555d582
refactor(moderation): update JailStatusCache usage for async operations
kzndotsh Jan 28, 2026
61cbc6c
refactor(comm_service): update guild config cache methods for async s…
kzndotsh Jan 28, 2026
3ded370
feat(config): add Valkey configuration options to settings
kzndotsh Jan 28, 2026
cacda70
refactor(cache): remove TTLCache implementation and update shared module
kzndotsh Jan 28, 2026
da62e83
feat(tests): add comprehensive unit tests for cache functionality
kzndotsh Jan 28, 2026
7e67236
docs(agents): update documentation to include Valkey cache integration
kzndotsh Jan 28, 2026
216e0c5
chore(dependencies): add Valkey as a new dependency
kzndotsh Jan 28, 2026
7d38f7b
feat(docker): add Valkey service to Docker Compose configuration
kzndotsh Jan 28, 2026
6c630d6
docs(agents): update Valkey usage instructions in Docker Compose docu…
kzndotsh Jan 29, 2026
0008534
feat(docker): add profile configuration for Valkey service in Docker …
kzndotsh Jan 29, 2026
4552714
feat(security): enhance Valkey password validation and URL encoding
kzndotsh Jan 29, 2026
0c6b182
refactor(cache): update AsyncCacheBackend methods and enhance InMemor…
kzndotsh Jan 29, 2026
e1c08d8
refactor(cache): enhance concurrency handling in GuildConfigCacheManager
kzndotsh Jan 29, 2026
d99695d
refactor(cache): update Valkey client initialization logging
kzndotsh Jan 29, 2026
24663fd
feat(cache): add method to invalidate cache entries by key predicate
kzndotsh Jan 29, 2026
8c23b72
fix(health): improve Valkey health check logging
kzndotsh Jan 29, 2026
9ae1a0b
fix(bot): enhance error logging for cache disconnection
kzndotsh Jan 29, 2026
a5be0a7
refactor(permission): remove unused in-memory cache from PermissionSy…
kzndotsh Jan 29, 2026
a9abd3c
docs(prefix_manager): clarify cache invalidation behavior in document…
kzndotsh Jan 29, 2026
26b6764
refactor(tests): streamline test setup and improve clarity in assertions
kzndotsh Jan 29, 2026
d4cc00e
test(cache): add unit tests for CacheSetupService initialization and …
kzndotsh Jan 29, 2026
ec85cc9
refactor(cache): add placeholder implementation for exists method in …
kzndotsh Jan 29, 2026
3ecc80c
test(cache): add comprehensive unit tests for GuildConfigCacheManager…
kzndotsh Jan 29, 2026
6ccb6e1
test(cache): add unit tests for TTLCache functionality
kzndotsh Jan 29, 2026
e435d39
test(permission): add unit tests for PermissionSetupService setup logic
kzndotsh Jan 29, 2026
3b2ce42
test(prefix_manager): add unit tests for PrefixManager functionality
kzndotsh Jan 29, 2026
a362839
test(permissions): add unit tests for PermissionRankController with c…
kzndotsh Jan 29, 2026
e1397d9
test(config): add unit tests for valkey_url configuration logic
kzndotsh Jan 29, 2026
07bd082
fix(cache): add type ignore comment for exists method in AsyncCacheBa…
kzndotsh Jan 29, 2026
a8bf37c
docs(caching): update async_set description for JailStatusCache
kzndotsh Jan 29, 2026
f6a3704
fix(cache): update JSON serialization in ValkeyBackend
kzndotsh Jan 29, 2026
f0fa68e
feat(cache): enhance GuildConfigCacheManager with locking and null lo…
kzndotsh Jan 29, 2026
6ed1973
feat(cache): improve TTLCache eviction logic and handle None values
kzndotsh Jan 29, 2026
1e09113
refactor(permission_system): optimize cache retrieval and storage wit…
kzndotsh Jan 29, 2026
89ce8b3
refactor(prefix_manager): enhance cache invalidation logic for guild …
kzndotsh Jan 29, 2026
de48ccc
refactor(test): update async_set test to reflect overwriting behavior…
kzndotsh Jan 29, 2026
47f579b
test(cache): add test for get_or_fetch behavior with None values
kzndotsh Jan 29, 2026
3d3c537
refactor(test): update prefix_manager fixture to use generator for be…
kzndotsh Jan 29, 2026
519988b
refactor(test): enhance environment setup for deterministic configura…
kzndotsh Jan 29, 2026
cbc8e8a
docs(caching): update cache key naming and method calls for clarity
kzndotsh Jan 29, 2026
4175a00
fix(cache): handle _CACHED_NONE in TTLCache to prevent unnecessary re…
kzndotsh Jan 29, 2026
4f736a8
fix(permission_system): improve cache handling for command permissions
kzndotsh Jan 29, 2026
4feac23
refactor(prefix_manager): optimize prefix cache writing and deletion …
kzndotsh Jan 29, 2026
527b554
refactor(test): update cache fixtures to use generators for improved …
kzndotsh Jan 29, 2026
b97cbd2
test(prefix_manager): enhance test coverage for prefix retrieval and …
kzndotsh Jan 29, 2026
5c2aee1
fix(permission_system): streamline cache handling for command permiss…
kzndotsh Jan 29, 2026
1a8680e
docs(caching): clarify backend-specific cache behavior and operationa…
kzndotsh Jan 29, 2026
675443d
docs(configuration): add Valkey cache options and clarify bot owner s…
kzndotsh Jan 29, 2026
0bc4157
fix(logging): update logger messages in cache managers for improved c…
kzndotsh Jan 29, 2026
1c247c0
fix(logging): correct logger message formatting in cache setup
kzndotsh Jan 29, 2026
09b19bb
fix(compose): change Valkey server log level from warning to debug
kzndotsh Jan 29, 2026
e70655f
docs(environment): clarify Valkey host configuration for local and Do…
kzndotsh Jan 29, 2026
3d497e2
docs(caching): expand Cache TTL reference and clarify backend behavior
kzndotsh Jan 29, 2026
4882f5c
refactor(jail): optimize database queries for jail configuration
kzndotsh Jan 29, 2026
3f76704
refactor(moderation): improve case creation and DM handling in modera…
kzndotsh Jan 29, 2026
1335479
fix(cache): ensure proper service closure in CacheSetupService
kzndotsh Jan 29, 2026
638381f
refactor(cache): enhance cache setup documentation and logging
kzndotsh Jan 29, 2026
92dacf2
refactor(cache): enhance docstrings for cache managers
kzndotsh Jan 29, 2026
9c74b36
docs(environment): enhance Valkey configuration instructions for loca…
kzndotsh Jan 29, 2026
d1df808
fix(compose): change Valkey server log level from debug to warning
kzndotsh Jan 29, 2026
873ed68
docs(caching): clarify Valkey TTL handling in caching documentation
kzndotsh Jan 29, 2026
6a9c5d7
refactor(cache): remove unused _null_lock method from GuildConfigCach…
kzndotsh Jan 29, 2026
267c91c
refactor(prefix_manager): specify type for write_tasks in PrefixManager
kzndotsh Jan 29, 2026
5b40862
refactor(jail): update cache invalidation and add cooldown to jail co…
kzndotsh Jan 29, 2026
83270ef
refactor(moderation): improve type safety in moderation coordinator
kzndotsh Jan 29, 2026
9041ce5
chore(changelog): update CHANGELOG for recent enhancements and fixes
kzndotsh Jan 29, 2026
bd2c943
refactor(moderation): enhance exception handling in moderation coordi…
kzndotsh Jan 29, 2026
5de958b
fix(prefix_manager): improve error handling for prefix caching
kzndotsh Jan 29, 2026
ae2eebf
fix(cache): improve error handling in ValkeyBackend
kzndotsh Jan 29, 2026
d5d2675
fix(database_setup): improve current revision retrieval and logging
kzndotsh Jan 29, 2026
4cfcb0e
feat(permission_checks): implement dynamic permission checks for comm…
kzndotsh Jan 29, 2026
974cff1
feat(permission_checks): add command permission check function
kzndotsh Jan 29, 2026
78162bc
feat(permission_system): add cache invalidation method for command pe…
kzndotsh Jan 29, 2026
43c2606
feat(permission_system): implement command permission cache invalidation
kzndotsh Jan 29, 2026
257987b
refactor(moderation): simplify type handling in moderation coordinator
kzndotsh Jan 29, 2026
739b0c7
feat(exceptions): enhance permission error messaging for unconfigured…
kzndotsh Jan 29, 2026
339aced
feat(permission_system): enhance role and command permission handling
kzndotsh Jan 29, 2026
a630f23
refactor(permission_system): update role removal logic for cache inva…
kzndotsh Jan 29, 2026
f6b30ae
fix(cache_setup): ensure proper closure of cache service on connectio…
kzndotsh Jan 29, 2026
910fddc
fix(decorators): replace contextlib with try-except for interaction d…
kzndotsh Jan 29, 2026
dd720fe
refactor(permission_system): extract cache invalidation logic into a …
kzndotsh Jan 29, 2026
ac33c01
refactor(database): add cache backend support to CaseController initi…
kzndotsh Jan 29, 2026
47c50b7
refactor(database): implement caching for case retrieval in CaseContr…
kzndotsh Jan 29, 2026
d960f2d
feat(permissions): add role assignment removal method and enhance cac…
kzndotsh Jan 29, 2026
552e205
refactor(permission_system): optimize role removal logic for cache in…
kzndotsh Jan 29, 2026
6f49386
fix(snippets): improve snippet ban check logic
kzndotsh Jan 29, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion .env.example
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Postgres, ExternalServices, BOT_TOKEN, DATABASE_URL, DEBUG, LOG_LEVEL, MAINTENANCE_MODE.
# Postgres, Valkey, ExternalServices, BOT_TOKEN, DATABASE_URL, DEBUG, LOG_LEVEL, MAINTENANCE_MODE.
# Used by Tux and Docker Compose. Other settings → config/config.json (config.json.example).

DEBUG=false
Expand All @@ -11,6 +11,11 @@ POSTGRES_DB=tuxdb
POSTGRES_USER=tuxuser
POSTGRES_PASSWORD=YOUR_POSTGRES_PASSWORD_HERE
DATABASE_URL=
VALKEY_HOST=
VALKEY_PORT=6379
VALKEY_DB=0
VALKEY_PASSWORD=YOUR_VALKEY_PASSWORD_HERE
VALKEY_URL=
EXTERNAL_SERVICES__SENTRY_DSN=
EXTERNAL_SERVICES__SENTRY_ENVIRONMENT=
EXTERNAL_SERVICES__GITHUB_APP_ID=
Expand Down
16 changes: 13 additions & 3 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

**Core:** Python 3.13.2+ • discord.py • PostgreSQL 17+ • SQLModel • Docker
**Tools:** uv • ruff • basedpyright • pytest • loguru • sentry-sdk • httpx • Zensical
**Additional:** typer (CLI) • Alembic (migrations) • psycopg (async PostgreSQL) • pydantic-settings
**Additional:** typer (CLI) • Alembic (migrations) • psycopg (async PostgreSQL) • pydantic-settings • Valkey (optional cache)

## Cursor Rules & Commands

Expand Down Expand Up @@ -66,6 +66,7 @@ uv run tux start --debug
```text
tux/
├── src/tux/ # Main source code
│ ├── cache/ # Cache layer (Valkey/in-memory backend, CacheService)
│ ├── core/ # Bot core (bot.py, app.py, base_cog.py)
│ ├── database/ # Database layer
│ │ ├── models/ # SQLModel models
Expand Down Expand Up @@ -290,7 +291,16 @@ docker compose up -d tux-postgres
- `production` - Production mode with pre-built image and security hardening
- `adminer` - Optional database management UI (combine with dev or production)

**Note:** `tux-postgres` has no profile and always starts. Do not use `--profile dev` and `--profile production` together.
**Note:** `tux-postgres` has no profile and always starts. Use `--profile valkey` to start Valkey (optional cache). Do not use `--profile dev` and `--profile production` together.

**Optional: Valkey (cache):** For shared cache across processes or restarts, start Valkey and set env:

```bash
docker compose --profile valkey up -d tux-valkey
# In .env: VALKEY_URL=valkey://localhost:6379/0 (or leave unset to use in-memory cache)
```

When `VALKEY_URL` is set and reachable, guild config, jail status, prefix, and permission caches use Valkey; otherwise they use in-memory TTL caches.

## Conventional Commits

Expand Down Expand Up @@ -376,7 +386,7 @@ refactor(database): optimize query performance

- **Async for I/O** - All database and HTTP operations are async
- **Connection pooling** - psycopg connection pooling for PostgreSQL
- **TTL caching** - Thread-safe TTL cache system for frequently accessed data (guild config, jail status, permissions)
- **TTL caching** - Thread-safe TTL cache system for frequently accessed data (guild config, jail status, permissions). Optional Valkey backend for shared cache across restarts (set `VALKEY_URL` and run `tux-valkey` in compose).
- **Batch operations** - Batch retrieval for permission checks and database queries
- **Cache pre-warming** - Automatic cache pre-warming on bot startup
- **Optimize queries** - Use database controllers with proper indexing
Expand Down
10 changes: 7 additions & 3 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),

### Added

* **Cache system**: TTLCache for thread-safe caching with automatic expiration; GuildConfigCacheManager for managing guild configuration data
* **Database**: Performance indexes for cases table (composite indexes for case lookups and expired tempbans); `fix-sequences` command to synchronize PostgreSQL sequences; safety checks for database reset and nuke operations in test mode
* **Bot configuration**: BotIntents model for Discord bot gateway intents configuration; HTTP client configuration for high-latency environments; `first_ready` flag for bot readiness tracking
* **Commands**: Enhanced case viewing with user or case number arguments; FlexibleUserConverter for enhanced user identification; `get_user_safe` utility function for optimized user resolution; `convert_reason` function to clean moderation reasons by removing flag-like prefixes
Expand All @@ -22,10 +21,10 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
* **Development tools**: Performance profiling command (`profile`) for analyzing Python script performance with cProfile
* **Testing**: Performance benchmarks for cache operations, data structures, permission systems, and string substitutions
* **Documentation**: Help command documentation with usage, syntax, and interactive features; enhanced configuration, commands, and caching documentation
* **Valkey**: Optional Valkey cache backend with in-memory fallback; CacheService and CacheSetupService for connection and lifecycle; prefix manager, database controllers, and permission system use cache backend; Valkey health check in `db health`; configuration via settings, `.env`, and Docker Compose (service and profile); password validation and URL encoding for Valkey URLs; cache invalidation by key predicate; unit tests for cache backends, service, TTLCache, and managers

### Changed

* **Caching**: Guild configuration caching for audit log, mod log, jail role, and jail channel IDs; cache invalidation on config updates; cache pre-warming on bot startup; memory efficiency improvements with `__slots__` in cache classes (TTLCache, GuildConfigCacheManager, JailStatusCache)
* **Performance**: Batch processing for permission checks, member role checks, and subcommand filtering; optimized command category retrieval; parallel execution of Discord actions and case creation in moderation coordinator; memory efficiency with `__slots__` in dependency trackers
* **Optimizations**: Optimized placeholder substitution in activity handler and fact module using single-pass substitution; optimized TLDR cache directory resolution with `@lru_cache` decorator for command listings
* **Interaction handling**: Improved deferral logic across all moderation commands; enhanced response handling in Info, XKCD, and other modules; `send_after_defer` method for improved message handling
Expand All @@ -41,8 +40,9 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
* **Dashboard**: Enhanced ranks management with cache control and rebuild options; improved cache invalidation logic for fresh data retrieval
* **Task monitor**: Optimized task categorization and processing using generator expressions and defaultdict for better memory efficiency
* **Guild config**: Simplified logging in `get_log_channel_ids` method; streamlined cache invalidation logic
* **Docker Compose**: Removed `initial_sync` from sync actions
* **Docker Compose**: Removed `initial_sync` from sync actions; Valkey service runs with warning log level (reduces verbosity)
* **Python version**: Updated to 3.13.11 across configuration files, workflows, and pre-commit hooks
* **Cache**: TTLCache uses _CACHED_NONE sentinel for eviction and None handling; GuildConfigCacheManager has locking and null-lock support; guild config and jail status use async cache operations; permission system and moderation (jail, prefix manager) use cache backend with concurrent retrieval and storage; prefix cache write/delete uses asyncio; jail command has cooldown and invalidates cache on rejoin; moderation coordinator has improved type safety and parallel case creation and DM handling; documentation for caching, Valkey TTL, environment, and Docker setup

### Fixed

Expand All @@ -55,6 +55,10 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
* **Config**: Clarified cache invalidation handling in ConfigDashboard (automatically managed by GuildConfigController.update_config)
* **Container**: Simplified Python image reference in Containerfile
* **Pre-commit**: Updated Python version in pre-commit configuration for consistency
* **Cache**: TTLCache correctly handles _CACHED_NONE to avoid unnecessary refetching; ValkeyBackend serializes values with JSON (broad type support); CacheSetupService closes properly on init failure; AsyncCacheBackend exists method has type annotation
* **Logging**: Cache setup and cache managers use consistent logger message formatting
* **Bot and health**: Cache disconnection and Valkey health check have improved error logging
* **Permission system**: Command permission cache correctly handles malformed entries and cache hits

## [0.1.1] - 2026-01-21

Expand Down
24 changes: 24 additions & 0 deletions compose.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,28 @@ services:
retries: 5
start_period: 30s
stop_grace_period: 30s
tux-valkey:
profiles: [valkey]
container_name: tux-valkey
hostname: tux-valkey
image: valkey/valkey:8.0-alpine
restart: ${RESTART_POLICY:-no}
ports: [127.0.0.1:6379:6379]
volumes:
- tux_valkey_data:/data
command: valkey-server --save 60 1 --loglevel warning
logging:
driver: json-file
options:
max-size: 10m
max-file: '3'
compress: 'true'
healthcheck:
test: [CMD, valkey-cli, ping]
interval: 10s
timeout: 5s
retries: 5
start_period: 5s

# Production app: pre-built image, no build, security hardening.
# Use: docker compose --profile production up -d
Expand Down Expand Up @@ -188,3 +210,5 @@ services:
volumes:
tux_postgres_data:
driver: local
tux_valkey_data:
driver: local
5 changes: 5 additions & 0 deletions config/config.json.example
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,11 @@
"HIDE_BOT_OWNER": false,
"PREFIX": "$"
},
"BOT_INTENTS": {
"presences": true,
"members": true,
"message_content": true
},
"USER_IDS": {
"BOT_OWNER_ID": 0,
"SYSADMINS": [
Expand Down
Loading
Loading