From 80c1f298626f6f15a2ceec07067972bcbcb8b6e9 Mon Sep 17 00:00:00 2001 From: rnxm <63553775+rnxm@users.noreply.github.com> Date: Fri, 13 Nov 2026 16:49:35 +0100 Subject: [PATCH 1/3] feat: deploy behind a gateway proxy instead of reconnecting shards Production can now run Gelbpunkt's gateway-proxy, which holds the shard connections and replays READY/GUILD_CREATE from its cache when the bot connects. A deploy restarts only the bot and sends no IDENTIFY. - DISCORD_GATEWAY_URL points discord.py at the proxy and skips the 5-second IDENTIFY spacing; SHARD_COUNT is required and checked against the proxy's /shard-count at startup. - The proxy is a compose service behind the gateway-proxy profile, pinned by digest; `just deploy` never touches it, `just deploy-proxy` recreates it. - MIGRATE_ON_START=false skips the boot-time migration in production. - Remove the bot-side RESUME machinery (SessionPersister, launch_shard override, session save on close, IDENTIFY lock): a fresh process that RESUMEs gets no READY or GUILD_CREATE and starts with an empty cache. Co-Authored-By: Claude Opus 5.5 --- .env.example | 8 +- AGENTS.md | 2 +- GLOSSARY.md | 2 + README.md | 28 ++++- compose.yml | 19 +++- core/bot.py | 96 ++++++----------- core/clustering/__init__.py | 8 +- core/clustering/config.py | 15 ++- core/clustering/gateway_proxy.py | 57 +++++++++++ core/clustering/interfaces.py | 17 --- core/clustering/session_persister.py | 115 --------------------- gateway-proxy.json | 22 ++++ justfile | 11 +- tests/test_clustering.py | 10 +- tests/test_gateway_proxy.py | 148 +++++++++++++++++++++++++++ 15 files changed, 339 insertions(+), 219 deletions(-) create mode 100644 core/clustering/gateway_proxy.py delete mode 100644 core/clustering/session_persister.py create mode 100644 gateway-proxy.json create mode 100644 tests/test_gateway_proxy.py diff --git a/.env.example b/.env.example index 6ee6209..cadd405 100644 --- a/.env.example +++ b/.env.example @@ -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 diff --git a/AGENTS.md b/AGENTS.md index 3c342dd..0ec693b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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) diff --git a/GLOSSARY.md b/GLOSSARY.md index 77afe22..1b02c31 100644 --- a/GLOSSARY.md +++ b/GLOSSARY.md @@ -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. diff --git a/README.md b/README.md index 650e63a..95c2762 100644 --- a/README.md +++ b/README.md @@ -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: @@ -84,6 +84,32 @@ 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` rebuilds and restarts only the bot; the proxy keeps the shards connected. +- `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 diff --git a/compose.yml b/compose.yml index 532efb8..65adcd1 100644 --- a/compose.yml +++ b/compose.yml @@ -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: @@ -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: diff --git a/core/bot.py b/core/bot.py index f5bcdf2..83c5fc8 100644 --- a/core/bot.py +++ b/core/bot.py @@ -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 @@ -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 ( @@ -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 @@ -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, @@ -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.""" @@ -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) @@ -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: @@ -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...") diff --git a/core/clustering/__init__.py b/core/clustering/__init__.py index dd96e26..1e66ca1 100644 --- a/core/clustering/__init__.py +++ b/core/clustering/__init__.py @@ -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__ = ( @@ -23,14 +22,13 @@ "InMemoryStateStore", "LocalEventBus", "MessageBuffer", - "NullSessionPersister", "RedisMessageBuffer", "RedisPubSubBus", - "RedisSessionPersister", "RedisShardCoordinator", "RedisStateStore", - "SessionPersister", "ShardCoordinator", "StandaloneCoordinator", "StateStore", + "configure_gateway_proxy", + "fetch_proxy_shard_count", ) diff --git a/core/clustering/config.py b/core/clustering/config.py index 617a6f1..352e9bd 100644 --- a/core/clustering/config.py +++ b/core/clustering/config.py @@ -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: @@ -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, @@ -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, ) diff --git a/core/clustering/gateway_proxy.py b/core/clustering/gateway_proxy.py new file mode 100644 index 0000000..019a00b --- /dev/null +++ b/core/clustering/gateway_proxy.py @@ -0,0 +1,57 @@ +from __future__ import annotations + +import aiohttp +import yarl +from discord import utils +from discord.gateway import DiscordWebSocket + +__all__ = ("configure_gateway_proxy", "fetch_proxy_shard_count", "shard_count_url") + + +def configure_gateway_proxy(gateway_url: str) -> None: + """Point every gateway connection discord.py opens at the gateway proxy. + + discord.py connects to ``DiscordWebSocket.DEFAULT_GATEWAY`` on startup when a shard count is set, and falls back to it + whenever a session is invalidated, so replacing it keeps re-identifies behind the proxy as well. + + Args: + gateway_url: The proxy's WebSocket URL, e.g. ``ws://gateway-proxy:7878``. + + Raises: + RuntimeError: The installed discord.py negotiates a transport compression the proxy cannot produce. + """ + compression = getattr(utils._ActiveDecompressionContext, "COMPRESSION_TYPE", None) + if compression != "zlib-stream": + raise RuntimeError( + f"discord.py uses {compression} gateway compression, but the gateway proxy only speaks zlib-stream" + ) + DiscordWebSocket.DEFAULT_GATEWAY = yarl.URL(gateway_url) + + +def shard_count_url(gateway_url: str) -> str: + """Build the URL of the proxy's ``/shard-count`` endpoint from its WebSocket URL. + + Args: + gateway_url: The proxy's WebSocket URL (``ws://`` or ``wss://``). + + Returns: + str: The HTTP(S) URL that returns the proxy's shard count as plain text. + """ + url = yarl.URL(gateway_url) + scheme = {"ws": "http", "wss": "https"}.get(url.scheme, url.scheme) + return str(url.with_scheme(scheme).with_path("/shard-count").with_query(None)) + + +async def fetch_proxy_shard_count(session: aiohttp.ClientSession, gateway_url: str) -> int: + """Ask the gateway proxy how many shards it runs. + + Args: + session: The HTTP session to use. + gateway_url: The proxy's WebSocket URL. + + Returns: + int: The proxy's total shard count. + """ + async with session.get(shard_count_url(gateway_url), timeout=aiohttp.ClientTimeout(total=10)) as response: + response.raise_for_status() + return int(await response.text()) diff --git a/core/clustering/interfaces.py b/core/clustering/interfaces.py index 2bb3599..95b75e3 100644 --- a/core/clustering/interfaces.py +++ b/core/clustering/interfaces.py @@ -75,20 +75,3 @@ async def release_shards(self) -> None: ... async def update_health(self, shard_id: int, latency: float, guild_count: int, status: str) -> None: ... async def close(self) -> None: ... - - -@runtime_checkable -class SessionPersister(Protocol): - """Manages gateway session persistence for zero-blackout rolling restarts.""" - - async def save_sessions(self, sessions: dict[int, dict[str, Any]]) -> None: ... - - async def get_session(self, shard_id: int) -> dict[str, Any] | None: ... - - async def clear_session(self, shard_id: int) -> None: ... - - async def acquire_identify_lock(self, shard_id: int, max_concurrency: int = 1) -> bool: ... - - async def release_identify_lock(self, shard_id: int, max_concurrency: int = 1) -> None: ... - - async def close(self) -> None: ... diff --git a/core/clustering/session_persister.py b/core/clustering/session_persister.py deleted file mode 100644 index 6735c90..0000000 --- a/core/clustering/session_persister.py +++ /dev/null @@ -1,115 +0,0 @@ -from __future__ import annotations - -import asyncio -import contextlib -import time -import uuid -from logging import getLogger -from typing import Any - -import orjson -import redis.asyncio as aioredis - -from core.clustering.interfaces import SessionPersister - -logger = getLogger(__name__) - -RELEASE_LOCK_LUA = """ -if redis.call('get', KEYS[1]) == ARGV[1] then - return redis.call('del', KEYS[1]) -else - return 0 -end -""" - - -class NullSessionPersister(SessionPersister): - """No-op SessionPersister for BOT_MODE=standalone.""" - - async def save_sessions(self, sessions: dict[int, dict[str, Any]]) -> None: - pass - - async def get_session(self, shard_id: int) -> dict[str, Any] | None: - return None - - async def clear_session(self, shard_id: int) -> None: - pass - - async def acquire_identify_lock(self, shard_id: int, max_concurrency: int = 1) -> bool: - return True - - async def release_identify_lock(self, shard_id: int, max_concurrency: int = 1) -> None: - pass - - async def close(self) -> None: - pass - - -class RedisSessionPersister(SessionPersister): - """Persists shard session IDs and gateway URLs to Redis for zero-blackout rolling restarts.""" - - def __init__(self, redis_client: aioredis.Redis, session_ttl: int = 90) -> None: - self.redis = redis_client - self.session_ttl = session_ttl - self.worker_id = uuid.uuid4().hex - self.prefix = "fm01" - - @classmethod - def from_url(cls, url: str, session_ttl: int = 90) -> RedisSessionPersister: - client = aioredis.from_url(url, decode_responses=False) - return cls(client, session_ttl=session_ttl) - - async def save_sessions(self, sessions: dict[int, dict[str, Any]]) -> None: - if not sessions: - return - logger.info(f"Persisting {len(sessions)} shard session(s) to Redis with TTL {self.session_ttl}s...") - try: - async with self.redis.pipeline(transaction=True) as pipe: - for shard_id, data in sessions.items(): - payload = orjson.dumps(data) - pipe.set(f"{self.prefix}:shard:session:{shard_id}", payload, ex=self.session_ttl) - await pipe.execute() - logger.info("Successfully persisted shard sessions for zero-blackout resumption.") - except Exception: - logger.exception("Failed to persist shard sessions to Redis") - - async def get_session(self, shard_id: int) -> dict[str, Any] | None: - try: - raw = await self.redis.get(f"{self.prefix}:shard:session:{shard_id}") - if raw: - data = orjson.loads(raw) - logger.info(f"Loaded saved gateway session for shard {shard_id}: session_id={data.get('session_id')}") - return data - except Exception: - logger.exception(f"Failed to fetch saved session from Redis for shard {shard_id}") - return None - - async def clear_session(self, shard_id: int) -> None: - with contextlib.suppress(Exception): - await self.redis.delete(f"{self.prefix}:shard:session:{shard_id}") - - async def acquire_identify_lock(self, shard_id: int, max_concurrency: int = 1, timeout: float = 30.0) -> bool: - """Acquire distributed IDENTIFY lock to avoid colliding with other containers on cold IDENTIFY.""" - bucket = shard_id % max_concurrency - lock_key = f"{self.prefix}:identify_lock:{bucket}" - start_time = time.monotonic() - - while time.monotonic() - start_time < timeout: - acquired = await self.redis.set(lock_key, self.worker_id.encode("utf-8"), nx=True, ex=6) - if acquired: - logger.debug(f"Acquired IDENTIFY lock on bucket {bucket} for shard {shard_id}") - return True - await asyncio.sleep(0.5) - - logger.warning(f"Timed out waiting for IDENTIFY lock on bucket {bucket} for shard {shard_id}") - return False - - async def release_identify_lock(self, shard_id: int, max_concurrency: int = 1) -> None: - bucket = shard_id % max_concurrency - lock_key = f"{self.prefix}:identify_lock:{bucket}" - with contextlib.suppress(Exception): - await self.redis.eval(RELEASE_LOCK_LUA, 1, lock_key, self.worker_id.encode("utf-8")) - - async def close(self) -> None: - with contextlib.suppress(Exception): - await self.redis.aclose() diff --git a/gateway-proxy.json b/gateway-proxy.json new file mode 100644 index 0000000..1e271a9 --- /dev/null +++ b/gateway-proxy.json @@ -0,0 +1,22 @@ +{ + "backpressure": 100, + "cache": { + "channels": true, + "current_member": true, + "emojis": true, + "members": true, + "presences": false, + "roles": true, + "scheduled_events": true, + "stage_instances": true, + "stickers": true, + "users": true, + "voice_states": true + }, + "externally_accessible_url": "ws://gateway-proxy:7878", + "intents": 53608447, + "log_level": "info", + "port": 7878, + "status": "idle", + "validate_token": true +} diff --git a/justfile b/justfile index 877ff26..f30e44f 100644 --- a/justfile +++ b/justfile @@ -35,14 +35,21 @@ restart *ARGS: logs *ARGS: docker compose logs -f {{ARGS}} +# Restarts only the bot; the gateway proxy keeps the shards connected. Services are listed so the proxy is never touched. deploy: git fetch --all git reset --hard origin/main uv sync just up db just migrate - docker compose build - just up -d --remove-orphans + docker compose build bot + just up --remove-orphans db lavalink redis bot + +# Recreates the gateway proxy, which reconnects every shard to Discord. Only for proxy upgrades and SHARD_COUNT changes. +deploy-proxy: + docker compose --profile gateway-proxy pull gateway-proxy + docker compose --profile gateway-proxy up -d --force-recreate gateway-proxy + just up bot [windows] debug: diff --git a/tests/test_clustering.py b/tests/test_clustering.py index ea7adb4..97681c9 100644 --- a/tests/test_clustering.py +++ b/tests/test_clustering.py @@ -10,7 +10,6 @@ InMemoryMessageBuffer, InMemoryStateStore, LocalEventBus, - NullSessionPersister, StandaloneCoordinator, ) from core.clustering.message_buffer import serialize_message @@ -154,17 +153,10 @@ def test_cluster_config_hostname_fallback(monkeypatch): @pytest.mark.asyncio -async def test_standalone_coordinator_and_persister(): +async def test_standalone_coordinator(): coordinator = StandaloneCoordinator() assert await coordinator.acquire_shards(64, 16) is None await coordinator.start_heartbeat() await coordinator.update_health(0, 0.05, 100, "ready") await coordinator.release_shards() await coordinator.close() - - persister = NullSessionPersister() - await persister.save_sessions({0: {"session_id": "abc", "sequence": 1, "gateway": "wss://gateway"}}) - assert await persister.get_session(0) is None - assert await persister.acquire_identify_lock(0) is True - await persister.release_identify_lock(0) - await persister.close() diff --git a/tests/test_gateway_proxy.py b/tests/test_gateway_proxy.py new file mode 100644 index 0000000..d53c0f6 --- /dev/null +++ b/tests/test_gateway_proxy.py @@ -0,0 +1,148 @@ +from __future__ import annotations + +from unittest.mock import AsyncMock, patch + +import aiohttp +import pytest +import yarl +from aiohttp import web +from aiohttp.test_utils import TestServer +from core.bot import Bot +from core.clustering import ClusterConfig, configure_gateway_proxy, fetch_proxy_shard_count +from core.clustering.gateway_proxy import shard_count_url +from core.config import Config +from discord.gateway import DiscordWebSocket + +PROXY_URL = "ws://gateway-proxy:7878" + + +@pytest.fixture(autouse=True) +def restore_default_gateway(monkeypatch): + monkeypatch.setattr(DiscordWebSocket, "DEFAULT_GATEWAY", DiscordWebSocket.DEFAULT_GATEWAY) + + +@pytest.fixture +def config() -> Config: + return Config( + debug=False, + owner_ids=[123], + modules=["*"], + emojis={}, + log_channel_id=999, + allowed_contexts={"guild": True, "dm_channel": True, "private_channel": True}, + allowed_installs={"guild": True, "user": True}, + allowed_mentions={"everyone": False, "roles": False, "users": False}, + ) + + +def make_bot(config: Config) -> Bot: + with patch("core.bot.update_slash_localizations"): + return Bot(config=config) + + +@pytest.mark.parametrize( + ("gateway_url", "expected"), + [ + ("ws://gateway-proxy:7878", "http://gateway-proxy:7878/shard-count"), + ("wss://proxy.example.com/", "https://proxy.example.com/shard-count"), + ("ws://localhost:7878/?v=10&encoding=json", "http://localhost:7878/shard-count"), + ], +) +def test_shard_count_url(gateway_url, expected): + assert shard_count_url(gateway_url) == expected + + +def test_configure_gateway_proxy_replaces_default_gateway(): + configure_gateway_proxy(PROXY_URL) + assert DiscordWebSocket.DEFAULT_GATEWAY == yarl.URL(PROXY_URL) + + +def test_cluster_config_reads_gateway_url(monkeypatch): + monkeypatch.setenv("DISCORD_GATEWAY_URL", PROXY_URL) + monkeypatch.setenv("SHARD_COUNT", "32") + cfg = ClusterConfig.from_env() + assert cfg.uses_gateway_proxy is True + assert cfg.gateway_url == PROXY_URL + assert cfg.shard_count == 32 + assert cfg.shard_count_configured is True + + +def test_cluster_config_without_gateway_url(monkeypatch): + monkeypatch.setenv("DISCORD_GATEWAY_URL", "") + monkeypatch.delenv("SHARD_COUNT", raising=False) + cfg = ClusterConfig.from_env() + assert cfg.uses_gateway_proxy is False + assert cfg.shard_count == 64 + assert cfg.shard_count_configured is False + + +def test_bot_requires_shard_count_behind_proxy(monkeypatch, config): + monkeypatch.setenv("DISCORD_GATEWAY_URL", PROXY_URL) + monkeypatch.delenv("SHARD_COUNT", raising=False) + with pytest.raises(ValueError, match="SHARD_COUNT"): + make_bot(config) + + +def test_bot_connects_directly_without_proxy(monkeypatch, config): + monkeypatch.delenv("DISCORD_GATEWAY_URL", raising=False) + monkeypatch.setenv("BOT_MODE", "standalone") + original = DiscordWebSocket.DEFAULT_GATEWAY + bot = make_bot(config) + assert bot.shard_count is None + assert DiscordWebSocket.DEFAULT_GATEWAY == original + + +@pytest.mark.asyncio +async def test_bot_behind_proxy_skips_identify_spacing(monkeypatch, config): + monkeypatch.setenv("DISCORD_GATEWAY_URL", PROXY_URL) + monkeypatch.setenv("SHARD_COUNT", "32") + monkeypatch.setenv("BOT_MODE", "standalone") + bot = make_bot(config) + assert bot.shard_count == 32 + assert DiscordWebSocket.DEFAULT_GATEWAY == yarl.URL(PROXY_URL) + + with patch("discord.client.asyncio.sleep", new=AsyncMock()) as sleep: + await bot.before_identify_hook(5, initial=False) + sleep.assert_not_called() + + +@pytest.mark.asyncio +async def test_bot_without_proxy_keeps_identify_spacing(monkeypatch, config): + monkeypatch.delenv("DISCORD_GATEWAY_URL", raising=False) + bot = make_bot(config) + with patch("discord.client.asyncio.sleep", new=AsyncMock()) as sleep: + await bot.before_identify_hook(5, initial=False) + sleep.assert_awaited_once_with(5.0) + + +@pytest.mark.asyncio +async def test_verify_shard_count_rejects_mismatch(monkeypatch, config): + monkeypatch.setenv("DISCORD_GATEWAY_URL", PROXY_URL) + monkeypatch.setenv("SHARD_COUNT", "32") + bot = make_bot(config) + with ( + patch("core.bot.fetch_proxy_shard_count", new=AsyncMock(return_value=31)), + pytest.raises(RuntimeError, match="SHARD_COUNT=31"), + ): + await bot.verify_gateway_proxy_shard_count(PROXY_URL) + + +@pytest.mark.asyncio +async def test_verify_shard_count_accepts_match(monkeypatch, config): + monkeypatch.setenv("DISCORD_GATEWAY_URL", PROXY_URL) + monkeypatch.setenv("SHARD_COUNT", "32") + bot = make_bot(config) + with patch("core.bot.fetch_proxy_shard_count", new=AsyncMock(return_value=32)): + await bot.verify_gateway_proxy_shard_count(PROXY_URL) + + +@pytest.mark.asyncio +async def test_fetch_proxy_shard_count(): + async def shard_count(_request: web.Request) -> web.Response: + return web.Response(text="32") + + app = web.Application() + app.router.add_get("/shard-count", shard_count) + async with TestServer(app) as server, aiohttp.ClientSession() as session: + gateway_url = f"ws://{server.host}:{server.port}" + assert await fetch_proxy_shard_count(session, gateway_url) == 32 From e4cc1e581c7993d06ff65a17efed02e37c03c5f7 Mon Sep 17 00:00:00 2001 From: rnxm <63553775+rnxm@users.noreply.github.com> Date: Fri, 13 Nov 2026 17:52:50 +0100 Subject: [PATCH 2/3] refactor: keep strict SHARD_COUNT parsing and shorten deploy recipe docs Co-Authored-By: Claude Opus 5.5 --- .env.example | 2 +- compose.yml | 2 +- core/bot.py | 2 -- core/clustering/config.py | 5 +---- justfile | 4 ++-- tests/test_gateway_proxy.py | 9 --------- 6 files changed, 5 insertions(+), 19 deletions(-) diff --git a/.env.example b/.env.example index cadd405..cb62b52 100644 --- a/.env.example +++ b/.env.example @@ -23,7 +23,7 @@ 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; required with DISCORD_GATEWAY_URL +SHARD_COUNT=64 # A shard usually contains 1000 servers; must match the gateway proxy when one is used 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 diff --git a/compose.yml b/compose.yml index 65adcd1..55a85cf 100644 --- a/compose.yml +++ b/compose.yml @@ -94,7 +94,7 @@ services: LAVALINK_PASSWORD: ${LAVALINK_PASSWORD} SENTRY_DSN: ${SENTRY_DSN:-} BOT_MODE: ${BOT_MODE:-standalone} - SHARD_COUNT: ${SHARD_COUNT:-} + SHARD_COUNT: ${SHARD_COUNT:-64} SHARDS_PER_CLUSTER: ${SHARDS_PER_CLUSTER:-16} CLUSTER_ID: ${CLUSTER_ID:-} REDIS_URL: ${REDIS_URL:-redis://redis:6379/0} diff --git a/core/bot.py b/core/bot.py index 83c5fc8..1925d39 100644 --- a/core/bot.py +++ b/core/bot.py @@ -82,8 +82,6 @@ def __init__(self, config: Config): 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() diff --git a/core/clustering/config.py b/core/clustering/config.py index 352e9bd..e7c3f8b 100644 --- a/core/clustering/config.py +++ b/core/clustering/config.py @@ -18,7 +18,6 @@ class ClusterConfig: 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 @@ -33,8 +32,7 @@ def uses_gateway_proxy(self) -> bool: @classmethod def from_env(cls) -> ClusterConfig: mode = os.getenv("BOT_MODE", "standalone").strip().lower() - raw_shard_count = (os.getenv("SHARD_COUNT") or "").strip() - shard_count = int(raw_shard_count) if raw_shard_count else 64 + shard_count = int(os.getenv("SHARD_COUNT", "64")) shards_per_cluster = int(os.getenv("SHARDS_PER_CLUSTER", "16")) raw_cluster_id = (os.getenv("CLUSTER_ID") or "").strip() if raw_cluster_id: @@ -69,7 +67,6 @@ def from_env(cls) -> ClusterConfig: 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, ) diff --git a/justfile b/justfile index f30e44f..0cab1c7 100644 --- a/justfile +++ b/justfile @@ -35,7 +35,7 @@ restart *ARGS: logs *ARGS: docker compose logs -f {{ARGS}} -# Restarts only the bot; the gateway proxy keeps the shards connected. Services are listed so the proxy is never touched. +# Restarts the bot without disconnecting from Discord deploy: git fetch --all git reset --hard origin/main @@ -45,7 +45,7 @@ deploy: docker compose build bot just up --remove-orphans db lavalink redis bot -# Recreates the gateway proxy, which reconnects every shard to Discord. Only for proxy upgrades and SHARD_COUNT changes. +# Restarts the entire stack, disconnecting from Discord deploy-proxy: docker compose --profile gateway-proxy pull gateway-proxy docker compose --profile gateway-proxy up -d --force-recreate gateway-proxy diff --git a/tests/test_gateway_proxy.py b/tests/test_gateway_proxy.py index d53c0f6..b8362fb 100644 --- a/tests/test_gateway_proxy.py +++ b/tests/test_gateway_proxy.py @@ -64,7 +64,6 @@ def test_cluster_config_reads_gateway_url(monkeypatch): assert cfg.uses_gateway_proxy is True assert cfg.gateway_url == PROXY_URL assert cfg.shard_count == 32 - assert cfg.shard_count_configured is True def test_cluster_config_without_gateway_url(monkeypatch): @@ -73,14 +72,6 @@ def test_cluster_config_without_gateway_url(monkeypatch): cfg = ClusterConfig.from_env() assert cfg.uses_gateway_proxy is False assert cfg.shard_count == 64 - assert cfg.shard_count_configured is False - - -def test_bot_requires_shard_count_behind_proxy(monkeypatch, config): - monkeypatch.setenv("DISCORD_GATEWAY_URL", PROXY_URL) - monkeypatch.delenv("SHARD_COUNT", raising=False) - with pytest.raises(ValueError, match="SHARD_COUNT"): - make_bot(config) def test_bot_connects_directly_without_proxy(monkeypatch, config): From 304976180b6d94442441033e4f04e46f4594efe4 Mon Sep 17 00:00:00 2001 From: rnxm <63553775+rnxm@users.noreply.github.com> Date: Fri, 13 Nov 2026 17:58:49 +0100 Subject: [PATCH 3/3] feat: deploy releases instead of main, restore required SHARD_COUNT `just deploy` now checks out the latest v* release tag (prereleases excluded), or the tag or branch passed to it, instead of resetting to origin/main. Restores the explicit SHARD_COUNT requirement behind the gateway proxy. Co-Authored-By: Claude Opus 5.5 --- .env.example | 2 +- README.md | 3 ++- compose.yml | 2 +- core/bot.py | 2 ++ core/clustering/config.py | 5 ++++- justfile | 13 +++++++++---- tests/test_gateway_proxy.py | 9 +++++++++ 7 files changed, 28 insertions(+), 8 deletions(-) diff --git a/.env.example b/.env.example index cb62b52..cadd405 100644 --- a/.env.example +++ b/.env.example @@ -23,7 +23,7 @@ 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; must match the gateway proxy when one is used +# 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 diff --git a/README.md b/README.md index 95c2762..b1afdde 100644 --- a/README.md +++ b/README.md @@ -104,7 +104,8 @@ The proxy's shard count comes from Discord's recommendation; `curl localhost:787 in `gateway-proxy.json` must match the bot's (`discord.Intents.all()`), since the bot's own IDENTIFY never reaches Discord. -- `just deploy` rebuilds and restarts only the bot; the proxy keeps the shards connected. +- `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. diff --git a/compose.yml b/compose.yml index 55a85cf..65adcd1 100644 --- a/compose.yml +++ b/compose.yml @@ -94,7 +94,7 @@ 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} diff --git a/core/bot.py b/core/bot.py index 1925d39..83c5fc8 100644 --- a/core/bot.py +++ b/core/bot.py @@ -82,6 +82,8 @@ def __init__(self, config: Config): 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() diff --git a/core/clustering/config.py b/core/clustering/config.py index e7c3f8b..352e9bd 100644 --- a/core/clustering/config.py +++ b/core/clustering/config.py @@ -18,6 +18,7 @@ class ClusterConfig: 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 @@ -32,7 +33,8 @@ def uses_gateway_proxy(self) -> bool: @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: @@ -67,6 +69,7 @@ def from_env(cls) -> ClusterConfig: 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, ) diff --git a/justfile b/justfile index 0cab1c7..c226ae0 100644 --- a/justfile +++ b/justfile @@ -35,10 +35,15 @@ restart *ARGS: logs *ARGS: docker compose logs -f {{ARGS}} -# Restarts the bot without disconnecting from Discord -deploy: - git fetch --all - git reset --hard origin/main +# Restarts the bot without disconnecting from Discord, on the latest release or the given tag or branch +[unix] +deploy ref="": + git fetch --force --tags origin + ref="{{ref}}"; \ + if [ -z "$ref" ]; then ref="$(git tag --list 'v*' --sort=-v:refname | grep -v -- - | head -n 1)"; \ + elif git rev-parse --quiet --verify "origin/$ref" >/dev/null; then ref="origin/$ref"; fi; \ + echo "Deploying $ref"; \ + git checkout --force --detach "$ref" uv sync just up db just migrate diff --git a/tests/test_gateway_proxy.py b/tests/test_gateway_proxy.py index b8362fb..d53c0f6 100644 --- a/tests/test_gateway_proxy.py +++ b/tests/test_gateway_proxy.py @@ -64,6 +64,7 @@ def test_cluster_config_reads_gateway_url(monkeypatch): assert cfg.uses_gateway_proxy is True assert cfg.gateway_url == PROXY_URL assert cfg.shard_count == 32 + assert cfg.shard_count_configured is True def test_cluster_config_without_gateway_url(monkeypatch): @@ -72,6 +73,14 @@ def test_cluster_config_without_gateway_url(monkeypatch): cfg = ClusterConfig.from_env() assert cfg.uses_gateway_proxy is False assert cfg.shard_count == 64 + assert cfg.shard_count_configured is False + + +def test_bot_requires_shard_count_behind_proxy(monkeypatch, config): + monkeypatch.setenv("DISCORD_GATEWAY_URL", PROXY_URL) + monkeypatch.delenv("SHARD_COUNT", raising=False) + with pytest.raises(ValueError, match="SHARD_COUNT"): + make_bot(config) def test_bot_connects_directly_without_proxy(monkeypatch, config):