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
use super::{Event, EventConversionError};
use serde::{Deserialize, Serialize};
use std::convert::TryFrom;

/// Indicator that a shard is now fully connected.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct Connected {
    /// The interval that heartbeats are being sent to the gateway.
    pub heartbeat_interval: u64,
    /// The ID of the shard that's now connected.
    pub shard_id: u64,
}

/// Indicator that a shard is now connecting.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct Connecting {
    /// The URL used to connect to the gateway.
    pub gateway: String,
    /// The ID of the shard that's now connecting.
    pub shard_id: u64,
}

/// Indicator that a shard is now disconnected and may soon be reconnecting if
/// not explicitly shutdown.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct Disconnected {
    /// The code for the disconnect if not initiated by the host, if any.
    pub code: Option<u16>,
    /// The reason for the disconnect if not initiated by the host, if any.
    pub reason: Option<String>,
    /// The ID of the shard that's now disconnected.
    pub shard_id: u64,
}

/// Indicator that a shard is now identifying with the gateway to create a new
/// session.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct Identifying {
    /// The ID of the shard that identified with the gateway.
    pub shard_id: u64,
    /// The total shards used by the bot.
    pub shard_total: u64,
}

/// A payload of bytes came in through the gateway.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct Payload {
    /// The bytes that came in.
    pub bytes: Vec<u8>,
}

/// Indicator that a shard is now reconnecting.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct Reconnecting {
    /// The ID of the shard that began reconnecting.
    pub shard_id: u64,
}

/// Indicator that a shard is now resuming a session after a disconnect.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct Resuming {
    /// The event sequence sent when resuming was initiated.
    pub seq: u64,
    /// The ID of the shard that began resuming.
    pub shard_id: u64,
}

/// "Meta" events about a shard's status, not from the gateway.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(untagged)]
pub enum ShardEvent {
    /// A shard is now in a Connected stage after being fully connected to the
    /// gateway.
    Connected(Connected),
    /// A shard is now in a Connecting stage after starting to connect to the
    /// gateway.
    Connecting(Connecting),
    /// A shard is now in a Disconnected stage after the connection was closed.
    Disconnected(Disconnected),
    /// A shard is now in a Identifying stage after starting a new session.
    Identifying(Identifying),
    /// A payload of bytes came in through the shard's connection.
    Payload(Payload),
    /// A shard is now in a Reconnecting stage after a disconnect or session was
    /// ended.
    Reconnecting(Reconnecting),
    /// A shard is now in a Resuming stage after a disconnect.
    Resuming(Resuming),
}

impl TryFrom<Event> for ShardEvent {
    type Error = EventConversionError;

    fn try_from(event: Event) -> Result<Self, Self::Error> {
        Ok(match event {
            Event::ShardConnected(v) => Self::Connected(v),
            Event::ShardConnecting(v) => Self::Connecting(v),
            Event::ShardDisconnected(v) => Self::Disconnected(v),
            Event::ShardIdentifying(v) => Self::Identifying(v),
            Event::ShardPayload(v) => Self::Payload(v),
            Event::ShardReconnecting(v) => Self::Reconnecting(v),
            Event::ShardResuming(v) => Self::Resuming(v),

            _ => return Err(EventConversionError::new(event)),
        })
    }
}

#[cfg(test)]
mod tests {
    use super::{
        Connected, Connecting, Disconnected, Event, Identifying, Payload, Reconnecting, Resuming,
        ShardEvent,
    };
    use serde_test::Token;
    use std::convert::TryInto;

    #[test]
    fn test_connected() {
        let value = Connected {
            heartbeat_interval: 41_250,
            shard_id: 4,
        };

        serde_test::assert_tokens(
            &value,
            &[
                Token::Struct {
                    name: "Connected",
                    len: 2,
                },
                Token::Str("heartbeat_interval"),
                Token::U64(41_250),
                Token::Str("shard_id"),
                Token::U64(4),
                Token::StructEnd,
            ],
        );
    }

    #[test]
    fn test_connecting() {
        let value = Connecting {
            gateway: "https://example.com".to_owned(),
            shard_id: 4,
        };

        serde_test::assert_tokens(
            &value,
            &[
                Token::Struct {
                    name: "Connecting",
                    len: 2,
                },
                Token::Str("gateway"),
                Token::Str("https://example.com"),
                Token::Str("shard_id"),
                Token::U64(4),
                Token::StructEnd,
            ],
        );
    }

    #[test]
    fn test_disconnected() {
        let value = Disconnected {
            code: Some(4_000),
            reason: Some("the reason".to_owned()),
            shard_id: 4,
        };

        serde_test::assert_tokens(
            &value,
            &[
                Token::Struct {
                    name: "Disconnected",
                    len: 3,
                },
                Token::Str("code"),
                Token::Some,
                Token::U16(4_000),
                Token::Str("reason"),
                Token::Some,
                Token::Str("the reason"),
                Token::Str("shard_id"),
                Token::U64(4),
                Token::StructEnd,
            ],
        );
    }

    #[test]
    fn test_identifying() {
        let value = Identifying {
            shard_id: 4,
            shard_total: 7,
        };

        serde_test::assert_tokens(
            &value,
            &[
                Token::Struct {
                    name: "Identifying",
                    len: 2,
                },
                Token::Str("shard_id"),
                Token::U64(4),
                Token::Str("shard_total"),
                Token::U64(7),
                Token::StructEnd,
            ],
        );
    }

    #[test]
    fn test_payload() {
        let value = Payload { bytes: vec![1, 2] };

        serde_test::assert_tokens(
            &value,
            &[
                Token::Struct {
                    name: "Payload",
                    len: 1,
                },
                Token::Str("bytes"),
                Token::Seq { len: Some(2) },
                Token::U8(1),
                Token::U8(2),
                Token::SeqEnd,
                Token::StructEnd,
            ],
        );
    }

    #[test]
    fn test_reconnecting() {
        let value = Reconnecting { shard_id: 4 };

        serde_test::assert_tokens(
            &value,
            &[
                Token::Struct {
                    name: "Reconnecting",
                    len: 1,
                },
                Token::Str("shard_id"),
                Token::U64(4),
                Token::StructEnd,
            ],
        );
    }

    #[test]
    fn test_resuming() {
        let value = Resuming {
            seq: 100,
            shard_id: 4,
        };

        serde_test::assert_tokens(
            &value,
            &[
                Token::Struct {
                    name: "Resuming",
                    len: 2,
                },
                Token::Str("seq"),
                Token::U64(100),
                Token::Str("shard_id"),
                Token::U64(4),
                Token::StructEnd,
            ],
        );
    }

    #[test]
    fn test_shard_event_try_from_event() {
        let connected = Event::ShardConnected(Connected {
            heartbeat_interval: 41_250,
            shard_id: 4,
        });
        assert!(matches!(
            connected.try_into().unwrap(),
            ShardEvent::Connected(_)
        ));

        let connecting = Event::ShardConnecting(Connecting {
            gateway: "https://example.com".to_owned(),
            shard_id: 4,
        });
        assert!(matches!(
            connecting.try_into().unwrap(),
            ShardEvent::Connecting(_)
        ));

        let disconnected = Event::ShardDisconnected(Disconnected {
            code: Some(4_000),
            reason: None,
            shard_id: 4,
        });
        assert!(matches!(
            disconnected.try_into().unwrap(),
            ShardEvent::Disconnected(_)
        ));

        let identifying = Event::ShardIdentifying(Identifying {
            shard_id: 4,
            shard_total: 7,
        });
        assert!(matches!(
            identifying.try_into().unwrap(),
            ShardEvent::Identifying(_)
        ));

        let payload = Event::ShardPayload(Payload { bytes: vec![1, 2] });
        assert!(matches!(
            payload.try_into().unwrap(),
            ShardEvent::Payload(_)
        ));

        let reconnecting = Event::ShardReconnecting(Reconnecting { shard_id: 4 });
        assert!(matches!(
            reconnecting.try_into().unwrap(),
            ShardEvent::Reconnecting(_)
        ));

        let resuming = Event::ShardResuming(Resuming {
            seq: 100,
            shard_id: 4,
        });
        assert!(matches!(
            resuming.try_into().unwrap(),
            ShardEvent::Resuming(_)
        ));
    }
}