1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
use super::error::{Error, Result};
use crate::shard::ResumeSession;
use crate::{
    queue::{LocalQueue, Queue},
    shard::config::{ShardConfig, ShardConfigBuilder},
};
use std::collections::HashMap;
use std::{
    convert::TryFrom,
    ops::{Bound, RangeBounds},
    sync::Arc,
};
use twilight_http::Client;
use twilight_model::gateway::{payload::update_status::UpdateStatusInfo, GatewayIntents};

/// The method of sharding to use.
///
/// By default this is [`Auto`].
///
/// [`Auto`]: #variant.Auto
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
pub enum ShardScheme {
    /// Specifies to retrieve the amount of shards recommended by Discord and
    /// then start all of them.
    ///
    /// For example, if Discord recommends 10 shards, then all 10 shards will be
    /// started.
    Auto,
    /// Specifies to start a range of shards.
    ///
    /// # Examples
    ///
    /// For example, if your bot uses 50 shards, then you might specify to start
    /// shards 0 through 24:
    ///
    /// ```
    /// use twilight_gateway::cluster::config::ShardScheme;
    /// use std::convert::TryFrom;
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let _range = ShardScheme::try_from((0..24, 50));
    /// # Ok(()) }
    /// ```
    Range {
        /// The first shard ID to spawn.
        from: u64,
        /// The last shard ID to spawn.
        ///
        /// This doesn't necessarily have to be up to the `total`.
        to: u64,
        /// The total number of shards used by the bot.
        total: u64,
    },
}

impl Default for ShardScheme {
    fn default() -> Self {
        Self::Auto
    }
}

impl<T: RangeBounds<u64>> TryFrom<(T, u64)> for ShardScheme {
    type Error = Error;

    fn try_from((range, total): (T, u64)) -> Result<Self, Self::Error> {
        let start = match range.start_bound() {
            Bound::Excluded(num) => *num - 1,
            Bound::Included(num) => *num,
            Bound::Unbounded => 0,
        };
        let end = match range.end_bound() {
            Bound::Excluded(num) => *num - 1,
            Bound::Included(num) => *num,
            Bound::Unbounded => total - 1,
        };

        if start > end {
            return Err(Error::IdTooLarge { end, start, total });
        }

        Ok(Self::Range {
            from: start,
            to: end,
            total,
        })
    }
}

/// Built configuration to be used for creating a [`Cluster`].
///
/// [`Cluster`]: ../struct.Cluster.html
#[derive(Debug)]
pub struct ClusterConfig {
    http_client: Client,
    shard_config: ShardConfig,
    shard_scheme: ShardScheme,
    queue: Arc<Box<dyn Queue>>,
    resume_sessions: HashMap<u64, ResumeSession>,
}

impl ClusterConfig {
    /// Creates a new builder to create a config.
    ///
    /// This is equivalent to calling [`ClusterConfigBuilder::new`] directly.
    ///
    /// [`ClusterConfigBuilder::new`]: struct.ClusterConfigBuilder.html#method.new
    pub fn builder(token: impl Into<String>) -> ClusterConfigBuilder {
        ClusterConfigBuilder::new(token)
    }

    /// Returns the `twilight_http` client used by the cluster and shards to get the
    /// gateway information.
    ///
    /// Refer to [`ClusterConfigBuilder::http_client`] for the default value.
    ///
    /// [`ClusterConfigBuilder::http_client`]: struct.ClusterConfigBuilder.html#method.http_client
    pub fn http_client(&self) -> &Client {
        &self.http_client
    }

    /// Returns the configuration used to create shards.
    ///
    /// Refer to [`shard::config::ClusterConfigBuilder`]'s methods for the default values.
    ///
    /// [`shard::config::ClusterConfigBuilder`]: ../../shard/config/struct.ClusterConfigBuilder.html#methods
    pub fn shard_config(&self) -> &ShardConfig {
        &self.shard_config
    }

    /// Returns the shard scheme used to start shards.
    ///
    /// Refer to [`ClusterConfigBuilder::shard_scheme`] for the default value.
    ///
    /// [`ClusterConfigBuilder::shard_scheme`]: struct.ClusterConfigBuilder.html#method.shard_scheme
    pub fn shard_scheme(&self) -> ShardScheme {
        self.shard_scheme
    }

    pub fn queue(&self) -> &Arc<Box<dyn Queue>> {
        &self.queue
    }

    /// Returns the resume data to resume shards for this cluster
    ///
    /// Refer to [`ClusterConfigBuilder::resume_sessions`] for the default value.
    ///
    /// [`ClusterConfigBuilder::resume_sessions`]: struct.ClusterConfigBuilder.html#method.resume_sessions
    pub fn resume_sessions(&self) -> &HashMap<u64, ResumeSession> {
        &self.resume_sessions
    }
}

impl From<ClusterConfigBuilder> for ClusterConfig {
    fn from(builder: ClusterConfigBuilder) -> Self {
        builder.build()
    }
}

impl<T: Into<String>> From<T> for ClusterConfig {
    fn from(token: T) -> Self {
        Self::builder(token).build()
    }
}

/// Builder to create a [`ClusterConfig`].
///
/// [`ClusterConfig`]: struct.ClusterConfig.html
// Yeah, I mean, we *could* deref to the `ShardConfigBuilder`, but it's not
// clear.
#[derive(Debug)]
pub struct ClusterConfigBuilder(ClusterConfig, ShardConfigBuilder);

impl ClusterConfigBuilder {
    /// Creates a new builder with default configuration values.
    ///
    /// Refer to each method to learn their default values.
    pub fn new(token: impl Into<String>) -> Self {
        Self::_new(token.into())
    }

    fn _new(mut token: String) -> Self {
        if !token.starts_with("Bot ") {
            token.insert_str(0, "Bot ");
        }

        Self(
            ClusterConfig {
                http_client: Client::new(token.clone()),
                shard_config: ShardConfig::from(token.clone()),
                shard_scheme: ShardScheme::Auto,
                queue: Arc::new(Box::new(LocalQueue::new())),
                resume_sessions: HashMap::new(),
            },
            ShardConfigBuilder::new(token),
        )
    }

    /// Consumes the builder and returns the final configuration.
    pub fn build(mut self) -> ClusterConfig {
        self.0.shard_config = self.1.build();

        self.0
    }

    /// Sets the `twilight_http` Client used by the cluster and the shards it
    /// manages.
    ///
    /// This is needed so that the cluster and shards can retrieve gateway
    /// information.
    ///
    /// By default, the default client is used.
    pub fn http_client(mut self, http_client: Client) -> Self {
        self.0.http_client = http_client.clone();
        self.1 = self.1.http_client(http_client);

        self
    }

    /// Sets the "large threshold" of shards.
    ///
    /// Refer to the shard's [`ShardConfigBuilder::large_threshold`] for more
    /// information.
    ///
    /// # Errors
    ///
    /// Returns [`ShardError::LargeThresholdInvalid`] if the value was not in
    /// the accepted range.
    ///
    /// [`ShardConfigBuilder::large_threshold`]: ../../shard/config/struct.ShardConfigBuilder.html#method.large_threshold
    /// [`ShardError::LargeThresholdInvalid`]: ../../shard/error/enum.Error.html#variant.LargeThresholdInvalid
    pub fn large_threshold(mut self, large_threshold: u64) -> Result<Self> {
        self.1 = self
            .1
            .large_threshold(large_threshold)
            .map_err(|source| Error::LargeThresholdInvalid { source })?;

        Ok(self)
    }

    /// Sets the presence to use when identifying with the gateway.
    ///
    /// Refer to the shard's [`ShardConfigBuilder::presence`] for more information.
    ///
    /// [`ShardConfigBuilder::presence`]: ../../shard/config/struct.ShardConfigBuilder.html#method.presence
    pub fn presence(mut self, presence: UpdateStatusInfo) -> Self {
        self.1 = self.1.presence(presence);

        self
    }

    /// Sets the intents to use when identifying with the gateway.
    ///
    /// Refer to the shard's [`ShardConfigBuilder::intents`] for more information.
    ///
    /// [`ShardConfigBuilder::intents`]: ../../shard/config/struct.ShardConfigBuilder.html#method.intents
    pub fn intents(mut self, intents: Option<GatewayIntents>) -> Self {
        self.1.intents(intents);

        self
    }

    /// Sets the scheme to use for shard managing.
    ///
    /// For example, [`ShardScheme::Auto`] means that the cluster will
    /// automatically manage all of the shards that Discord recommends you use.
    /// [`ShardScheme::Range`] means that it will manage a range of shards, but
    /// not necessarily all of the shards that your bot uses.
    ///
    /// The default value is [`ShardScheme::Auto`]. For most setups this is an
    /// acceptable default.
    ///
    /// # Examples
    ///
    /// Configure a cluster to manage shards 0-9 out of 20 shards total:
    ///
    /// ```no_run
    /// use twilight_gateway::cluster::config::{ClusterConfig, ShardScheme};
    /// use std::{
    ///     convert::TryFrom,
    ///     env,
    /// };
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let mut config = ClusterConfig::builder(env::var("DISCORD_TOKEN")?);
    ///
    /// let scheme = ShardScheme::try_from((0..=9, 20))?;
    /// config.shard_scheme(scheme);
    /// # Ok(()) }
    /// ```
    ///
    /// [`ShardScheme::Auto`]: enum.ShardScheme.html#variant.Auto
    /// [`ShardScheme::Range`]: enum.ShardScheme.html#variant.Range
    pub fn shard_scheme(mut self, scheme: ShardScheme) -> Self {
        self.0.shard_scheme = scheme;

        self
    }

    /// Sets the queue to use for queueing shard connections.
    ///
    /// This can be used when having advanced setups with multiple
    /// binaries connecting at the same time.
    pub fn queue(mut self, queue: Arc<Box<dyn Queue>>) -> Self {
        self.1 = self.1.queue(Arc::clone(&queue));
        self.0.queue = queue;

        self
    }

    /// Sets the session information to resume shards with
    ///
    /// This requires having recovered the resume data when shutting down the cluster
    /// NOTE: this does not guarantee these shards will be able to resume. If their sessions are invalid they will have to re-identify as normal
    pub fn resume_sessions(mut self, resume_sessions: HashMap<u64, ResumeSession>) -> Self {
        self.0.resume_sessions = resume_sessions;
        self
    }
}

impl<T: Into<String>> From<T> for ClusterConfigBuilder {
    fn from(token: T) -> Self {
        Self::new(token)
    }
}

#[cfg(test)]
mod tests {
    use super::ShardScheme;
    use std::{convert::TryFrom, error::Error};

    #[test]
    fn test_shard_scheme() -> Result<(), Box<dyn Error>> {
        assert_eq!(
            ShardScheme::Range {
                from: 0,
                to: 9,
                total: 10,
            },
            ShardScheme::try_from((0..=9, 10))?
        );

        Ok(())
    }
}