This repository has been archived by the owner on Apr 20, 2022. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 41
/
Copy pathConnectionManager.cs
233 lines (210 loc) · 9 KB
/
ConnectionManager.cs
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
using Discord.Logging;
using System;
using System.Threading;
using System.Threading.Tasks;
using Discord.Net;
namespace Discord
{
internal class ConnectionManager : IDisposable
{
public event Func<Task> Connected { add { _connectedEvent.Add(value); } remove { _connectedEvent.Remove(value); } }
private readonly AsyncEvent<Func<Task>> _connectedEvent = new AsyncEvent<Func<Task>>();
public event Func<Exception, bool, Task> Disconnected { add { _disconnectedEvent.Add(value); } remove { _disconnectedEvent.Remove(value); } }
private readonly AsyncEvent<Func<Exception, bool, Task>> _disconnectedEvent = new AsyncEvent<Func<Exception, bool, Task>>();
private readonly SemaphoreSlim _stateLock;
private readonly Logger _logger;
private readonly int _connectionTimeout;
private readonly Func<Task> _onConnecting;
private readonly Func<Exception, Task> _onDisconnecting;
private TaskCompletionSource<bool> _connectionPromise, _readyPromise;
private CancellationTokenSource _combinedCancelToken, _reconnectCancelToken, _connectionCancelToken;
private Task _task;
private bool _isDisposed;
public ConnectionState State { get; private set; }
public CancellationToken CancelToken { get; private set; }
internal ConnectionManager(SemaphoreSlim stateLock, Logger logger, int connectionTimeout,
Func<Task> onConnecting, Func<Exception, Task> onDisconnecting, Action<Func<Exception, Task>> clientDisconnectHandler)
{
_stateLock = stateLock;
_logger = logger;
_connectionTimeout = connectionTimeout;
_onConnecting = onConnecting;
_onDisconnecting = onDisconnecting;
clientDisconnectHandler(ex =>
{
if (ex != null)
{
var ex2 = ex as WebSocketClosedException;
if (ex2?.CloseCode == 4006)
CriticalError(new Exception("WebSocket session expired", ex));
else if (ex2?.CloseCode == 4014)
CriticalError(new Exception("WebSocket connection was closed", ex));
else
Error(new Exception("WebSocket connection was closed", ex));
}
else
Error(new Exception("WebSocket connection was closed"));
return Task.Delay(0);
});
}
public virtual async Task StartAsync()
{
if (State != ConnectionState.Disconnected)
throw new InvalidOperationException("Cannot start an already running client.");
await AcquireConnectionLock().ConfigureAwait(false);
var reconnectCancelToken = new CancellationTokenSource();
_reconnectCancelToken?.Dispose();
_reconnectCancelToken = reconnectCancelToken;
_task = Task.Run(async () =>
{
try
{
Random jitter = new Random();
int nextReconnectDelay = 1000;
while (!reconnectCancelToken.IsCancellationRequested)
{
try
{
await ConnectAsync(reconnectCancelToken).ConfigureAwait(false);
nextReconnectDelay = 1000; //Reset delay
await _connectionPromise.Task.ConfigureAwait(false);
}
catch (Exception ex)
{
Error(ex); //In case this exception didn't come from another Error call
if (!reconnectCancelToken.IsCancellationRequested)
{
await _logger.WarningAsync(ex).ConfigureAwait(false);
await DisconnectAsync(ex, true).ConfigureAwait(false);
}
else
{
await _logger.ErrorAsync(ex).ConfigureAwait(false);
await DisconnectAsync(ex, false).ConfigureAwait(false);
}
}
if (!reconnectCancelToken.IsCancellationRequested)
{
//Wait before reconnecting
await Task.Delay(nextReconnectDelay, reconnectCancelToken.Token).ConfigureAwait(false);
nextReconnectDelay = (nextReconnectDelay * 2) + jitter.Next(-250, 250);
if (nextReconnectDelay > 60000)
nextReconnectDelay = 60000;
}
}
}
finally { _stateLock.Release(); }
});
}
public virtual Task StopAsync()
{
Cancel();
return Task.CompletedTask;
}
private async Task ConnectAsync(CancellationTokenSource reconnectCancelToken)
{
_connectionCancelToken?.Dispose();
_combinedCancelToken?.Dispose();
_connectionCancelToken = new CancellationTokenSource();
_combinedCancelToken = CancellationTokenSource.CreateLinkedTokenSource(_connectionCancelToken.Token, reconnectCancelToken.Token);
CancelToken = _combinedCancelToken.Token;
_connectionPromise = new TaskCompletionSource<bool>();
State = ConnectionState.Connecting;
await _logger.InfoAsync("Connecting").ConfigureAwait(false);
try
{
var readyPromise = new TaskCompletionSource<bool>();
_readyPromise = readyPromise;
//Abort connection on timeout
var cancelToken = CancelToken;
var _ = Task.Run(async () =>
{
try
{
await Task.Delay(_connectionTimeout, cancelToken).ConfigureAwait(false);
readyPromise.TrySetException(new TimeoutException());
}
catch (OperationCanceledException) { }
});
await _onConnecting().ConfigureAwait(false);
await _logger.InfoAsync("Connected").ConfigureAwait(false);
State = ConnectionState.Connected;
await _logger.DebugAsync("Raising Event").ConfigureAwait(false);
await _connectedEvent.InvokeAsync().ConfigureAwait(false);
}
catch (Exception ex)
{
Error(ex);
throw;
}
}
private async Task DisconnectAsync(Exception ex, bool isReconnecting)
{
if (State == ConnectionState.Disconnected) return;
State = ConnectionState.Disconnecting;
await _logger.InfoAsync("Disconnecting").ConfigureAwait(false);
await _onDisconnecting(ex).ConfigureAwait(false);
await _disconnectedEvent.InvokeAsync(ex, isReconnecting).ConfigureAwait(false);
State = ConnectionState.Disconnected;
await _logger.InfoAsync("Disconnected").ConfigureAwait(false);
}
public async Task CompleteAsync()
{
await _readyPromise.TrySetResultAsync(true).ConfigureAwait(false);
}
public async Task WaitAsync()
{
await _readyPromise.Task.ConfigureAwait(false);
}
public void Cancel()
{
_readyPromise?.TrySetCanceled();
_connectionPromise?.TrySetCanceled();
_reconnectCancelToken?.Cancel();
_connectionCancelToken?.Cancel();
}
public void Error(Exception ex)
{
_readyPromise.TrySetException(ex);
_connectionPromise.TrySetException(ex);
_connectionCancelToken?.Cancel();
}
public void CriticalError(Exception ex)
{
_reconnectCancelToken?.Cancel();
Error(ex);
}
public void Reconnect()
{
_readyPromise.TrySetCanceled();
_connectionPromise.TrySetCanceled();
_connectionCancelToken?.Cancel();
}
private async Task AcquireConnectionLock()
{
while (true)
{
await StopAsync().ConfigureAwait(false);
if (await _stateLock.WaitAsync(0).ConfigureAwait(false))
break;
}
}
protected virtual void Dispose(bool disposing)
{
if (!_isDisposed)
{
if (disposing)
{
_combinedCancelToken?.Dispose();
_reconnectCancelToken?.Dispose();
_connectionCancelToken?.Dispose();
}
_isDisposed = true;
}
}
public void Dispose()
{
Dispose(true);
}
}
}