Discord's Gateway, one shard over a websocket (in Effect, dfx's
DiscordGateway): it identifies or resumes, heartbeats, keeps the session
in a ShardStateStore and hands each dispatch to the DispatchHook
before storing its sequence, then to every subscriber of dispatch.
- The websocket is
DiscordWs;layer_wsbuilds it on aWebSocketConstructor(pyfect.socket.ws, extrawebsockets). It reconnects by itself, and aRECONNECTwritten to it drops the connection with close code 4000, which keeps the session for a RESUME. - A host built again with the same
ShardStateStoresends RESUME, not IDENTIFY, and Discord sends what it missed. - A hook that fails or dies drops the connection without storing the
dispatch's sequence, so the RESUME brings it back: after 1 second,
doubling with every failure in a row up to 2 minutes. Whatever was already
read from a dropped connection is skipped, unstored, until the next HELLO,
and comes back with the RESUME too. A refused
READYstores no session. - Op 7 (reconnect) resumes; op 9 (invalid session) that can't be resumed clears the stored session and identifies again. A heartbeat Discord did not acknowledge before the next one drops the connection.
- Inbound frames are untrusted: one that is not a JSON object, or nests deeper than 64, is dropped.
Values#
| Attribute | Type | Description |
|---|---|---|
DEFAULT_URL | Literal['wss://gateway.discord.gg'] = 'wss://gateway.discord.gg' | Discord's gateway; |
GUILDS | Literal[1] | |
GUILD_MESSAGES | Literal[512] | |
GUILD_MESSAGE_REACTIONS | Literal[1024] | |
DIRECT_MESSAGES | Literal[4096] | |
DIRECT_MESSAGE_REACTIONS | Literal[8192] | |
MESSAGE_CONTENT | Literal[32768] | A privileged intent: switch it on for the application in the developer portal. |
DEFAULT_INTENTS | Literal[46593] | The intents the chat adapter reads. |
RECONNECT | Reconnect | |
layer_ws | Layer[DiscordWs, Never, WebSocketConstructor] |
|
Types#
| Type | Definition | Description |
|---|---|---|
Hook | type Hook = Callable[[GatewayDispatch], Effect[None, object]] | |
GatewaySend | type GatewaySend = Mapping[str, object] |
Classes#
Functions#
with_query#
with_query(url) -> strA gateway URL with the version and encoding the shard speaks.
| Parameter | Type | Description |
|---|---|---|
url | str |
Returns str
def with_query(url: str) -> str:
"""A gateway URL with the version and encoding the shard speaks."""
base = url.split("?", 1)[0].rstrip("/")
return f"{base}/?v=10&encoding=json"layer#
layer(*, token, intents=DEFAULT_INTENTS, shard=(0, 1), url=DEFAULT_URL) -> Layer[DiscordGateway, Never, DiscordWs]One shard of the gateway, running until the layer's scope closes. It
keeps its session in the ShardStateStore in context, or in memory,
and runs the DispatchHook in context on each dispatch.
| Parameter | Type | Description |
|---|---|---|
token | Redacted[str] | |
intents | int = DEFAULT_INTENTS | |
shard | tuple[int, int] = (0, 1) | |
url | str = DEFAULT_URL |
Returns Layer[DiscordGateway, Never, DiscordWs]
def layer(
*,
token: Redacted[str],
intents: int = DEFAULT_INTENTS,
shard: tuple[int, int] = (0, 1),
url: str = DEFAULT_URL,
) -> Layer[DiscordGateway, Never, DiscordWs]:
"""One shard of the gateway, running until the layer's scope closes. It
keeps its session in the ``ShardStateStore`` in context, or in memory,
and runs the ``DispatchHook`` in context on each dispatch."""
if not (0 <= shard[0] < shard[1]):
raise ValueError(f"shard must be (id, count) with 0 <= id < count, got {shard!r}")
@fx.gen
def build() -> Generator[Effect[Any, Never, Any], Any, DiscordGatewayService]:
ws = yield from DiscordWs()
found = yield from fx.service_option(ShardStateStore)
stores: ShardStateStoreService = MemoryStateStore() if found is None else found.value
hook = yield from DispatchHook()
store = yield from fx.sync(lambda: stores.for_shard(shard))
pubsub: PubSub[GatewayDispatch] = yield from PubSub[GatewayDispatch].unbounded()
state = _Shard(
token=token,
intents=intents,
shard=shard,
url=url,
store=store,
hook=hook,
pubsub=pubsub,
)
stored = yield from state._get() # pyright: ignore[reportPrivateUsage]
start = with_query(url if stored is None else stored.resume_url)
state.conn = yield from ws.connect(start, fx.sync(state.on_connecting))
conn = state.conn
yield from conn.take.flat_map(state.on_payload).forever().fork_scoped()
def stop(_: object) -> Effect[None]:
beating = state.heartbeat
return fx.void if beating is None else beating.interrupt()
yield from fx.add_finalizer(stop)
return DiscordGatewayService(pubsub)
return _layer_effect(DiscordGateway, build)