68 releases

0.16.0-rc.1 Feb 21, 2024
0.15.4 Sep 10, 2023
0.15.2 Apr 27, 2023
0.15.1 Feb 26, 2023
0.2.5 Nov 29, 2020

#329 in Web programming

Download history 908/week @ 2024-07-21 1451/week @ 2024-07-28 851/week @ 2024-08-04 1276/week @ 2024-08-11 812/week @ 2024-08-18 948/week @ 2024-08-25 932/week @ 2024-09-01 669/week @ 2024-09-08 744/week @ 2024-09-15 1218/week @ 2024-09-22 837/week @ 2024-09-29 457/week @ 2024-10-06 700/week @ 2024-10-13 965/week @ 2024-10-20 841/week @ 2024-10-27 756/week @ 2024-11-03

3,328 downloads per month
Used in 10 crates (9 directly)

ISC license

2.5MB
55K SLoC

twilight-gateway

codecov badge discord badge github badge license badge rust badge

twilight-gateway is an implementation of Discord's sharding gateway sessions. This is responsible for receiving stateful events in real-time from Discord and sending some stateful information.

The primary type is the Shard, a stateful interface to maintain a Websocket connection to Discord's gateway. Much of its functionality can be configured, and it's used to receive gateway events or raw Websocket messages, useful for load balancing and microservices.

Multiple shards may easily be created at once, with a per shard config created from a Fn(ShardId, ConfigBuilder) -> Config closure, with the help of the create_ set of functions. These functions will reuse shards' TLS context and [session queue][queue], something otherwise achieved by cloning an existing Config.

Features

  • simd-json: use simd-json instead of serde_json for deserializing events
  • TLS (mutually exclusive)
    • native-tls: platform's native TLS implementation via native-tls
    • rustls-native-roots (default): rustls using native root certificates
    • rustls-webpki-roots: rustls using webpki-roots for root certificates, useful for scratch containers
  • twilight-http (default): enable the stream::create_recommended function
  • Zlib (mutually exclusive)
    • zlib-stock (default): flate2's stock zlib implementation
    • zlib-simd: use zlib-ng for zlib, may have better performance

Example

Create the recommended number of shards and loop over their guild events in parallel

use std::{
    env,
    sync::atomic::{AtomicBool, Ordering},
};
use tokio::signal;
use twilight_gateway::{
    error::ReceiveMessageErrorType, CloseFrame, Config, Event, EventTypeFlags, Intents, Shard,
    StreamExt as _,
};
use twilight_http::Client;

static SHUTDOWN: AtomicBool = AtomicBool::new(false);

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    tracing_subscriber::fmt::init();

    let token = env::var("DISCORD_TOKEN")?;
    let client = Client::new(token.clone());
    let config = Config::new(token, Intents::GUILDS);

    let shards =
        twilight_gateway::create_recommended(&client, config, |_, builder| builder.build()).await?;
    let mut senders = Vec::with_capacity(shards.len());
    let mut tasks = Vec::with_capacity(shards.len());

    for shard in shards {
        senders.push(shard.sender());
        tasks.push(tokio::spawn(runner(shard)));
    }

    signal::ctrl_c().await?;
    SHUTDOWN.store(true, Ordering::Relaxed);
    for sender in senders {
        // Ignore error if shard's already shutdown.
        _ = sender.close(CloseFrame::NORMAL);
    }

    for jh in tasks {
        _ = jh.await;
    }

    Ok(())
}

async fn runner(mut shard: Shard) {
    while let Some(item) = shard.next_event(EventTypeFlags::all()).await {
        let event = match item {
            Ok(Event::GatewayClose(_)) if SHUTDOWN.load(Ordering::Relaxed) => break,
            Ok(event) => event,
            Err(source)
                if SHUTDOWN.load(Ordering::Relaxed)
                    && matches!(source.kind(), ReceiveMessageErrorType::WebSocket) =>
            {
                break
            }
            Err(source) => {
                tracing::warn!(?source, "error receiving event");

                continue;
            }
        };

        // You'd normally want to spawn a new tokio task for each event and
        // handle the event there to not block the shard.
        tracing::debug!(?event, shard = ?shard.id(), "received event");
    }
}

There are a few additional examples located in the repository.

Dependencies

~9–24MB
~361K SLoC