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
use super::{
super::stage::Stage,
error::{Error, Result},
heartbeat::{Heartbeater, Heartbeats},
};
use futures_channel::mpsc::UnboundedSender;
use futures_util::{
future::{self, AbortHandle},
lock::Mutex,
};
use serde::ser::Serialize;
use std::{
convert::TryFrom,
sync::{
atomic::{AtomicU64, AtomicU8, Ordering},
Arc,
},
};
use twilight_model::gateway::payload::Heartbeat;
use async_tungstenite::tungstenite::{protocol::CloseFrame, Message as TungsteniteMessage};
use std::time::Duration;
use tokio::time::{interval, Interval};
#[derive(Debug)]
pub struct Session {
pub heartbeater_handle: Arc<Mutex<Option<AbortHandle>>>,
pub heartbeats: Arc<Heartbeats>,
pub heartbeat_interval: AtomicU64,
pub id: Mutex<Option<String>>,
pub seq: Arc<AtomicU64>,
pub stage: AtomicU8,
pub tx: UnboundedSender<TungsteniteMessage>,
pub ratelimit: Mutex<Interval>,
}
impl Session {
pub fn new(tx: UnboundedSender<TungsteniteMessage>) -> Self {
Self {
heartbeater_handle: Arc::new(Mutex::new(None)),
heartbeats: Arc::new(Heartbeats::default()),
heartbeat_interval: AtomicU64::new(0),
id: Mutex::new(None),
seq: Arc::new(AtomicU64::new(0)),
stage: AtomicU8::new(Stage::default() as u8),
tx,
ratelimit: Mutex::new(interval(Duration::from_millis(520))),
}
}
pub fn send(&self, payload: impl Serialize) -> Result<()> {
let bytes = crate::json_to_vec(&payload)
.map_err(|source| Error::PayloadSerialization { source })?;
self.tx
.unbounded_send(TungsteniteMessage::Binary(bytes))
.map_err(|source| Error::SendingMessage { source })?;
Ok(())
}
pub fn close(&self, close_frame: Option<CloseFrame<'static>>) -> Result<()> {
self.tx
.unbounded_send(TungsteniteMessage::Close(close_frame))
.map_err(|source| Error::SendingMessage { source })?;
Ok(())
}
pub fn heartbeat_interval(&self) -> u64 {
self.heartbeat_interval.load(Ordering::Relaxed)
}
pub fn set_heartbeat_interval(&self, new_heartbeat_interval: u64) {
self.heartbeat_interval
.store(new_heartbeat_interval, Ordering::Release);
}
pub fn seq(&self) -> u64 {
self.seq.load(Ordering::Relaxed)
}
pub fn set_seq(&self, seq: u64) {
self.seq.store(seq, Ordering::Release);
}
pub fn stage(&self) -> Stage {
Stage::try_from(self.stage.load(Ordering::Relaxed)).unwrap_or_default()
}
pub fn set_stage(&self, stage: Stage) {
self.stage.store(stage as u8, Ordering::Release);
}
pub fn heartbeat(&self) -> Result<()> {
self.send(Heartbeat::new(self.seq()))
}
pub async fn id(&self) -> Option<String> {
self.id.lock().await.clone()
}
pub async fn set_id(&self, new_id: impl Into<String>) {
self.id.lock().await.replace(new_id.into());
}
pub async fn stop_heartbeater(&self) {
if let Some(handle) = self.heartbeater_handle.lock().await.take() {
handle.abort();
}
}
pub async fn start_heartbeater(&self) {
let interval = self.heartbeat_interval();
let seq = Arc::clone(&self.seq);
let heartbeats = Arc::clone(&self.heartbeats);
let heartbeater = Heartbeater::new(heartbeats, interval, seq, self.tx.clone()).run();
let (fut, handle) = future::abortable(heartbeater);
tokio::spawn(async {
let _ = fut.await;
});
if let Some(old) = self.heartbeater_handle.lock().await.replace(handle) {
old.abort();
}
}
}
impl Drop for Session {
fn drop(&mut self) {
let handle = Arc::clone(&self.heartbeater_handle);
let _ = tokio::spawn(async move {
if let Some(handle) = handle.lock().await.take() {
handle.abort();
}
});
}
}