Skip to content
This repository was archived by the owner on Nov 13, 2026. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
8 changes: 7 additions & 1 deletion .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,15 @@ SENTRY_DSN=sentry_sdk_dsn
# It's not recommended to mess with these values when self-hosting.
BOT_MODE=standalone # or "clustered"
# If you use BOT_MODE=standalone, settings below will be ignored.
SHARD_COUNT=64 # A shard usually contains 1000 servers
# SHARD_COUNT=64 # A shard usually contains 1000 servers; required with DISCORD_GATEWAY_URL
SHARDS_PER_CLUSTER=16 # One cluster (process) will manage up to 16 shards
# CLUSTER_ID=cluster-0 # Leave unset for automatic cluster ID assignment per replica
REDIS_URL=redis://redis:6379/0
REDIS_MSG_URL=redis://redis:6379/1
# DISCORD_PROXY_URL=http://twilight-proxy:3000/api/v10

# Gateway proxy - for production deployments that restart without reconnecting to Discord.
# Leave unset to connect to Discord directly (self-hosting, debug bot).
# COMPOSE_PROFILES=gateway-proxy
# DISCORD_GATEWAY_URL=ws://gateway-proxy:7878
# MIGRATE_ON_START=false # `just deploy` migrates before restarting the bot
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ This document defines architectural standards, technical conventions, and operat
- `config.py` (`Config`): Runtime configuration parser loading `config.yml`.
- `settings.py` (`GuildSettings`, `GuildSetting`): Cached per-guild settings with cross-instance invalidation. Register feature settings here instead of keeping a cog-level cache.
- `locale.py` (`resolve_locale`): The single rule for which locale a response uses.
- `clustering/`: Shard coordination (`ShardCoordinator`), session resumption (`SessionPersister`), distributed state (`StateStore`), event pub/sub (`EventBus`), and audit log buffers (`MessageBuffer`).
- `clustering/`: Shard coordination (`ShardCoordinator`), gateway proxy connection (`gateway_proxy.py`), distributed state (`StateStore`), event pub/sub (`EventBus`), and audit log buffers (`MessageBuffer`).

#### `args/` (Safe String Formatting Wrappers)

Expand Down
2 changes: 2 additions & 0 deletions GLOSSARY.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,4 +38,6 @@ The words this codebase uses for its own concepts, and the decisions that shape

**Cache invalidation uses Redis pub/sub.** Instances tell each other about changed guild settings over the existing Redis event bus (`core/clustering/`). Postgres `LISTEN/NOTIFY` triggers were considered, so outside writers such as the dashboard backend would invalidate caches automatically, and rejected until the monorepo move.

**Deploys restart the bot behind a gateway proxy.** Production runs [gateway-proxy](https://github.com/Gelbpunkt/gateway-proxy) (upstream image, pinned by digest, no fork for now), which keeps the shard connections open and replays a synthetic `READY` and `GUILD_CREATE`s from its cache when the bot connects, so a deploy sends no IDENTIFY. Resuming the old sessions from a fresh process was rejected: Discord sends no `READY` or `GUILD_CREATE` after a RESUME, so the new process starts with an empty cache. nirn-proxy was rejected because it only proxies REST. Voice sessions are not carried across restarts. Deploys stop the old bot before starting the new one; a blue-green handover would make both answer while they overlap, because the proxy sends every event to every client of a shard. Self-hosters connect to Discord directly.

**Message visibility is configured per message, not in code.** Whether a response is ephemeral (and whether it deletes itself) comes from its localization key, which the dashboard will make editable per message. Commands don't hard-code `ephemeral`, and the bot doesn't defer slash commands automatically (a deferred response's visibility can't be changed afterwards). Commands that can take longer than Discord's 3-second window (rank card, snapshots, `voice play`, `info ip`, `info template`) call `ctx.defer()` themselves, so their replies are public. Revisit deferring when the dashboard work starts.
29 changes: 28 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ Then edit it:
docker compose up -d --build
```

Database migrations are applied automatically on every bot start.
Database migrations are applied automatically on every bot start (unless `MIGRATE_ON_START=false`).

Check that it's running:

Expand All @@ -84,6 +84,33 @@ docker compose logs -f bot
> [!WARNING]
> `docker compose down -v` / `just destroy` permanently deletes the database volume. Only use it in debug environments!

### Gateway proxy (production)

Production runs a [gateway proxy](https://github.com/Gelbpunkt/gateway-proxy) that holds the shard connections to
Discord. The bot connects to the proxy instead, so restarting it replays the guild state from the proxy's cache instead
of identifying every shard again (Discord allows one IDENTIFY per 5 seconds). Self-hosters don't need it: leave
`DISCORD_GATEWAY_URL` unset and the bot connects to Discord directly.

To enable it, set in `.env`:

```bash
COMPOSE_PROFILES=gateway-proxy
DISCORD_GATEWAY_URL=ws://gateway-proxy:7878
SHARD_COUNT=32 # must match the proxy; the bot refuses to start otherwise
MIGRATE_ON_START=false # `just deploy` runs migrations itself
```

The proxy's shard count comes from Discord's recommendation; `curl localhost:7878/shard-count` prints it. Its intents
in `gateway-proxy.json` must match the bot's (`discord.Intents.all()`), since the bot's own IDENTIFY never reaches
Discord.

- `just deploy` checks out the latest release, then rebuilds and restarts only the bot; the proxy keeps the shards
connected. `just deploy v0.9.0` deploys (or rolls back to) a given release, and `just deploy main` the testing branch.
- `just deploy-proxy` recreates the proxy, which reconnects every shard. Use it for proxy upgrades and shard count
changes only, and update `SHARD_COUNT` first when the count changes.

Voice sessions don't survive a bot restart: players that were playing stop and have to be started again.

### Debug mode

Set `debug: true` in `config.yml` and provide `DEBUG_TOKEN` in `.env`. The bot will log in with the debug token and
Expand Down
19 changes: 17 additions & 2 deletions compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,20 @@ services:
profiles:
- clustered

# Holds the Discord gateway connections so the bot can restart without reconnecting its shards.
# Pinned by digest; `just deploy-proxy` is the only routine that recreates it.
gateway-proxy:
image: ghcr.io/gelbpunkt/gateway-proxy:znver3@sha256:f130920b108fbc3a27ad0c75eee4174acf627802920daf75bc4b6a3f1d77995c
restart: unless-stopped
environment:
TOKEN: ${TOKEN:?Please set a bot token in .env}
volumes:
- ./gateway-proxy.json:/config.json:ro
ports:
- "127.0.0.1:7878:7878"
profiles:
- gateway-proxy

bot:
build: .
depends_on:
Expand All @@ -80,15 +94,16 @@ services:
LAVALINK_PASSWORD: ${LAVALINK_PASSWORD}
SENTRY_DSN: ${SENTRY_DSN:-}
BOT_MODE: ${BOT_MODE:-standalone}
SHARD_COUNT: ${SHARD_COUNT:-64}
SHARD_COUNT: ${SHARD_COUNT:-}
SHARDS_PER_CLUSTER: ${SHARDS_PER_CLUSTER:-16}
CLUSTER_ID: ${CLUSTER_ID:-}
REDIS_URL: ${REDIS_URL:-redis://redis:6379/0}
REDIS_MSG_URL: ${REDIS_MSG_URL:-redis://redis:6379/1}
DISCORD_PROXY_URL: ${DISCORD_PROXY_URL:-}
DISCORD_GATEWAY_URL: ${DISCORD_GATEWAY_URL:-}
volumes:
- .:/bot
command: sh -c "uv run alembic upgrade head && uv run --no-dev main.py"
command: sh -c "if [ '${MIGRATE_ON_START:-true}' = true ]; then uv run alembic upgrade head; fi && uv run --no-dev main.py"

volumes:
postgres_data:
96 changes: 34 additions & 62 deletions core/bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,8 @@
import discord
import discord.http
import wavelink
import yarl
from discord import app_commands
from discord.ext import commands, localization
from discord.gateway import DiscordWebSocket
from discord.shard import Shard
from discord.utils import MISSING
from helpers import custom_response, seconds_to_text

Expand All @@ -33,16 +30,15 @@
InMemoryStateStore,
LocalEventBus,
MessageBuffer,
NullSessionPersister,
RedisMessageBuffer,
RedisPubSubBus,
RedisSessionPersister,
RedisShardCoordinator,
RedisStateStore,
SessionPersister,
ShardCoordinator,
StandaloneCoordinator,
StateStore,
configure_gateway_proxy,
fetch_proxy_shard_count,
)
from core.config import Config
from core.settings import (
Expand Down Expand Up @@ -85,6 +81,11 @@ def __init__(self, config: Config):
proxy_url = self.cluster_config.discord_proxy_url.rstrip("/")
discord.http.Route.BASE = proxy_url

if self.cluster_config.gateway_url:
if not self.cluster_config.shard_count_configured:
raise ValueError("SHARD_COUNT must be set when DISCORD_GATEWAY_URL is set")
configure_gateway_proxy(self.cluster_config.gateway_url)

update_slash_localizations()
self._sentry_enabled = False
self.debug: bool = config.debug
Expand All @@ -95,7 +96,8 @@ def __init__(self, config: Config):
self.db: asyncpg.Pool | MISSING = None
self.session: aiohttp.ClientSession | None = None

shard_count = self.cluster_config.shard_count if self.cluster_config.is_clustered else None
uses_fixed_shard_count = self.cluster_config.is_clustered or self.cluster_config.uses_gateway_proxy
shard_count = self.cluster_config.shard_count if uses_fixed_shard_count else None

super().__init__(
command_prefix=Bot.fetch_prefix,
Expand Down Expand Up @@ -125,15 +127,11 @@ def __init__(self, config: Config):
heartbeat_interval=self.cluster_config.heartbeat_interval,
explicit_shard_ids=self.cluster_config.shard_ids,
)
self.session_persister: SessionPersister = RedisSessionPersister.from_url(
self.cluster_config.redis_url, session_ttl=self.cluster_config.lease_ttl * 3
)
else:
self.state_store = InMemoryStateStore()
self.event_bus = LocalEventBus()
self.message_buffer = InMemoryMessageBuffer()
self.coordinator = StandaloneCoordinator()
self.session_persister = NullSessionPersister()

self.message_logging_guilds: set[int] = set()
"""Guilds whose messages are buffered for deletion/edit logging; maintained by the log setting."""
Expand Down Expand Up @@ -184,6 +182,9 @@ async def setup_hook(self):
self.logger.exception("Failed to connect to database")
sys.exit()

if self.cluster_config.gateway_url:
await self.verify_gateway_proxy_shard_count(self.cluster_config.gateway_url)

await self.message_buffer.start()
await self.event_bus.start()
await self.event_bus.subscribe("fm01:events", self._on_cluster_event)
Expand Down Expand Up @@ -247,40 +248,31 @@ async def on_message(self, message: discord.Message) -> None:

await self.process_commands(message)

async def launch_shard(self, gateway: yarl.URL, shard_id: int, *, initial: bool = False) -> None:
session = await self.session_persister.get_session(shard_id)
if session and session.get("session_id") and session.get("sequence") is not None:
resume_gateway = yarl.URL(session["gateway"]) if session.get("gateway") else gateway
try:
coro = DiscordWebSocket.from_client(
self,
initial=False,
gateway=resume_gateway,
shard_id=shard_id,
session=session["session_id"],
sequence=session["sequence"],
resume=True,
)
ws = await asyncio.wait_for(coro, timeout=self.shard_connect_timeout)
self._AutoShardedClient__shards[shard_id] = ret = Shard( # type: ignore
ws,
self,
self._AutoShardedClient__queue.put_nowait, # type: ignore
)
ret.launch()
self.logger.info(f"Shard {shard_id} successfully RESUMED gateway session {session.get('session_id')}")
return
except (discord.DiscordException, aiohttp.ClientError, TimeoutError, OSError) as e:
self.logger.warning(
f"Failed to resume session for shard {shard_id}: {e}. Falling back to cold identify..."
)
await self.session_persister.clear_session(shard_id)
async def verify_gateway_proxy_shard_count(self, gateway_url: str) -> None:
"""Refuse to start when ``SHARD_COUNT`` differs from the gateway proxy's shard count.

The proxy disconnects every client whose IDENTIFY carries a different shard count, so a mismatch would leave
the bot reconnecting forever instead of failing.

await super().launch_shard(gateway, shard_id, initial=initial)
Args:
gateway_url: The proxy's WebSocket URL.

Raises:
RuntimeError: The counts differ.
"""
async with aiohttp.ClientSession() as session:
proxy_shard_count = await fetch_proxy_shard_count(session, gateway_url)
if proxy_shard_count != self.cluster_config.shard_count:
raise RuntimeError(
f"SHARD_COUNT is {self.cluster_config.shard_count}, but the gateway proxy at {gateway_url} "
f"runs {proxy_shard_count} shards; set SHARD_COUNT={proxy_shard_count}"
)
self.logger.info(f"Connecting to the gateway proxy at {gateway_url} with {proxy_shard_count} shards")

async def before_identify_hook(self, shard_id: int | None, *, initial: bool = False) -> None:
if shard_id is not None and self.cluster_config.is_clustered:
await self.session_persister.acquire_identify_lock(shard_id, self.cluster_config.max_concurrency)
# The proxy answers IDENTIFY itself and holds the real sessions, so Discord's 5-second spacing doesn't apply.
if self.cluster_config.uses_gateway_proxy:
return
await super().before_identify_hook(shard_id, initial=initial)

async def _health_reporting_loop(self) -> None:
Expand All @@ -305,31 +297,11 @@ async def close(self) -> None:
with contextlib.suppress(asyncio.CancelledError):
await self._health_task

if self.cluster_config.is_clustered:
sessions: dict[int, dict[str, Any]] = {}
for shard_id, shard in self.shards.items():
ws = getattr(shard, "ws", None)
if ws and getattr(ws, "session_id", None) and getattr(ws, "sequence", None) is not None:
sessions[shard_id] = {
"session_id": ws.session_id,
"sequence": ws.sequence,
"gateway": str(getattr(ws, "gateway", "")),
}
if sessions:
await self.session_persister.save_sessions(sessions)

for shard in self.shards.values():
ws = getattr(shard, "ws", None)
if ws and hasattr(ws, "socket") and ws.socket and not ws.socket.closed:
with contextlib.suppress(Exception):
await ws.socket.close(code=4000)

await self.coordinator.release_shards()
await self.coordinator.close()
await self.message_buffer.close()
await self.event_bus.close()
await self.state_store.close()
await self.session_persister.close()

if self.session and not self.session.closed:
self.logger.debug("Closing aiohttp session...")
Expand Down
8 changes: 3 additions & 5 deletions core/clustering/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,15 @@
from core.clustering.config import ClusterConfig
from core.clustering.coordinator import RedisShardCoordinator, StandaloneCoordinator
from core.clustering.event_bus import LocalEventBus, RedisPubSubBus
from core.clustering.gateway_proxy import configure_gateway_proxy, fetch_proxy_shard_count
from core.clustering.interfaces import (
EventBus,
EventHandler,
MessageBuffer,
SessionPersister,
ShardCoordinator,
StateStore,
)
from core.clustering.message_buffer import InMemoryMessageBuffer, RedisMessageBuffer
from core.clustering.session_persister import NullSessionPersister, RedisSessionPersister
from core.clustering.stores import InMemoryStateStore, RedisStateStore

__all__ = (
Expand All @@ -23,14 +22,13 @@
"InMemoryStateStore",
"LocalEventBus",
"MessageBuffer",
"NullSessionPersister",
"RedisMessageBuffer",
"RedisPubSubBus",
"RedisSessionPersister",
"RedisShardCoordinator",
"RedisStateStore",
"SessionPersister",
"ShardCoordinator",
"StandaloneCoordinator",
"StateStore",
"configure_gateway_proxy",
"fetch_proxy_shard_count",
)
15 changes: 11 additions & 4 deletions core/clustering/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,18 +17,24 @@ class ClusterConfig:
redis_url: str = "redis://localhost:6379/0"
redis_msg_url: str = "redis://localhost:6379/1"
discord_proxy_url: str | None = None
gateway_url: str | None = None
shard_count_configured: bool = False
lease_ttl: int = 30
heartbeat_interval: int = 10
max_concurrency: int = 1

@property
def is_clustered(self) -> bool:
return self.mode.lower() == "clustered"

@property
def uses_gateway_proxy(self) -> bool:
return bool(self.gateway_url)

@classmethod
def from_env(cls) -> ClusterConfig:
mode = os.getenv("BOT_MODE", "standalone").strip().lower()
shard_count = int(os.getenv("SHARD_COUNT", "64"))
raw_shard_count = (os.getenv("SHARD_COUNT") or "").strip()
shard_count = int(raw_shard_count) if raw_shard_count else 64
shards_per_cluster = int(os.getenv("SHARDS_PER_CLUSTER", "16"))
raw_cluster_id = (os.getenv("CLUSTER_ID") or "").strip()
if raw_cluster_id:
Expand All @@ -48,10 +54,10 @@ def from_env(cls) -> ClusterConfig:
redis_url = os.getenv("REDIS_URL", "redis://localhost:6379/0")
redis_msg_url = os.getenv("REDIS_MSG_URL", "redis://localhost:6379/1")
discord_proxy_url = os.getenv("DISCORD_PROXY_URL") or os.getenv("DISCORD_API_PROXY_URL")
gateway_url = (os.getenv("DISCORD_GATEWAY_URL") or "").strip() or None

lease_ttl = int(os.getenv("LEASE_TTL", "30"))
heartbeat_interval = int(os.getenv("HEARTBEAT_INTERVAL", "10"))
max_concurrency = int(os.getenv("MAX_CONCURRENCY", "1"))

return cls(
mode=mode,
Expand All @@ -62,7 +68,8 @@ def from_env(cls) -> ClusterConfig:
redis_url=redis_url,
redis_msg_url=redis_msg_url,
discord_proxy_url=discord_proxy_url,
gateway_url=gateway_url,
shard_count_configured=bool(raw_shard_count),
lease_ttl=lease_ttl,
heartbeat_interval=heartbeat_interval,
max_concurrency=max_concurrency,
)
Loading
Loading