-
Notifications
You must be signed in to change notification settings - Fork 1
/
ReliableSignalRClient.cs
281 lines (234 loc) · 7.12 KB
/
ReliableSignalRClient.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
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
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNet.SignalR.Client;
using ReliableSignalR.Client.Contracts;
using ReliableSignalR.Client.Models;
using ReliableSignalR.Client.Utils;
namespace ReliableSignalR.Client
{
public class ReliableSignalRClient : IReliableSignalRClient
{
public event Action<StateChange> OnConnectionStateChanged;
public ConnectionState ConnectionState { get; private set; } = ConnectionState.Disconnected;
private HubConnection _connection;
private IHubProxy _proxy;
private Func<Dictionary<string, string>> _headersProvider;
private int _secondsToReconnect = 5;
private readonly string _className;
private TextWriter _tracer;
private TraceLevels _traceLevel;
private string _endpointUri;
private string _hubName;
private TimeSpan? _transportConnectionTimeout;
private Queue<FailedInvoke> _queue;
private Action<IHubProxy> _proxySubscriber;
private SimpleTimer _timer;
#region Constructor and fluent settings
public ReliableSignalRClient()
{
_className = nameof(ReliableSignalRClient);
}
public IReliableSignalRClient SetTransportTimeout(TimeSpan transportConnectionTimeout)
{
_transportConnectionTimeout = transportConnectionTimeout;
return this;
}
public IReliableSignalRClient UseTracer(TextWriter textWritter, TraceLevels traceLevel = TraceLevels.All)
{
_tracer = textWritter;
_traceLevel = traceLevel;
return this;
}
public IReliableSignalRClient SetEndpoint(string endpointUri)
{
_endpointUri = endpointUri;
return this;
}
public IReliableSignalRClient SetHubName(string hubName)
{
_hubName = hubName;
return this;
}
public IReliableSignalRClient SetHeadersProvider(Func<Dictionary<string, string>> headersProvider)
{
_headersProvider = headersProvider;
return this;
}
public IReliableSignalRClient RetryFailedInvokesOnReconnection()
{
_queue = new Queue<FailedInvoke>();
return this;
}
public IReliableSignalRClient SetSecondsToReconnect(int seconds)
{
_secondsToReconnect = seconds;
return this;
}
public IReliableSignalRClient SetProxySubscriber(Action<IHubProxy> proxySubscriber)
{
_proxySubscriber = proxySubscriber;
return this;
}
#endregion
#region Connection life cycle
public virtual async Task<bool> Connect()
{
if (string.IsNullOrEmpty(_endpointUri))
throw new InvalidOperationException("WithEndpoint() must be called before you connect");
if (string.IsNullOrEmpty(_hubName))
throw new InvalidOperationException("WithHubName() must be called before you connect");
if (_connection != null)
return false;
_connection = new HubConnection(_endpointUri);
_connection.StateChanged += OnConnectionStateChangedHandler;
_connection.Reconnected += OnReconnectedHandler;
if (_transportConnectionTimeout != null)
_connection.TransportConnectTimeout = _transportConnectionTimeout.Value;
if (_tracer != null)
{
_connection.TraceWriter = _tracer;
_connection.TraceLevel = _traceLevel;
}
if (_headersProvider != null)
{
foreach (var header in _headersProvider())
{
_connection.Headers.Add(header.Key, header.Value);
}
}
_proxy = _connection.CreateHubProxy(_hubName);
_proxySubscriber?.Invoke(_proxy);
if (_connection.State != ConnectionState.Disconnected)
return false;
try
{
_tracer?.WriteLine($"[{_className}] CONNECTING...");
await _connection.Start();
if (_queue != null)
{
await ProcessInvokeQueue();
}
return true;
}
catch (Exception ex)
{
_tracer?.WriteLine($"[{_className}] CONNECTION START ERROR: {ex.Message}");
}
return false;
}
public virtual void Disconnect()
{
_timer?.Stop();
DismissCurrentConnection();
_proxy = null;
}
protected virtual void DismissCurrentConnection()
{
if (_connection == null) return;
OnConnectionStateChanged?.Invoke(new StateChange(_connection.State, ConnectionState.Disconnected));
_connection.StateChanged -= OnConnectionStateChangedHandler;
_connection.Reconnected -= OnReconnectedHandler;
var connectionToDispose = _connection;
_connection = null;
// connection disposing can block the UI thread for about 20 seconds
// this doesn´t always happen but just in case we run it on a new thread
Task.Run(() =>
{
try
{
connectionToDispose.Dispose();
}
catch (Exception ex)
{
_tracer?.WriteLine($"[{_className}] Connection could not be disposed: {ex.Message}");
}
});
}
protected virtual async void OnReconnectedHandler()
{
if (_queue != null)
{
await ProcessInvokeQueue();
}
}
protected virtual void OnConnectionStateChangedHandler(StateChange change)
{
ConnectionState = change.NewState;
OnConnectionStateChanged?.Invoke(change);
if (!change.NewState.Equals(ConnectionState.Disconnected)) return;
// SignalR doesn´t do anything after disconnected state, so we need to manually reconnect
if (_timer == null)
{
_timer = new SimpleTimer(TimeSpan.FromSeconds(_secondsToReconnect), async () =>
{
DismissCurrentConnection();
await Connect();
}, true);
}
_timer.Start();
}
#endregion
#region Invokes and Queue
public async Task Invoke(string method, params object[] args)
{
await Connect(); // In case there isn´t a current connection
try
{
await _proxy.Invoke(method, args); //.ConfigureAwait(false);
}
catch (InvalidOperationException ex)
{
_tracer?.WriteLine($"[{_className}] Could not invoke '{method}': {ex.Message}");
_queue?.Enqueue(new FailedInvoke(method, args));
}
catch (Exception ex)
{
_tracer?.WriteLine($"[{_className}] Could not invoke '{method}': {ex.Message}");
_queue?.Enqueue(new FailedInvoke(method, args));
}
}
// TODO returned value will be lost if the invoke fails => allow to pass an Action<T> as parameter
public async Task<T> Invoke<T>(string method, params object[] args)
{
await Connect(); // In case there isn´t a current connection
try
{
return await _proxy.Invoke<T>(method, args); //.ConfigureAwait(false);
}
catch (InvalidOperationException ex)
{
_tracer?.WriteLine($"[{_className}] Could not invoke '{method}': {ex.Message}");
_queue?.Enqueue(new FailedInvoke(method, args));
return default(T);
}
catch (Exception ex)
{
_tracer?.WriteLine($"[{_className}] Could not invoke '{method}': {ex.Message}");
_queue?.Enqueue(new FailedInvoke(method, args));
return default(T);
}
}
protected virtual async Task ProcessInvokeQueue()
{
// we don´t want to process the queue until we are connected
if (_queue.Count > 0 && ConnectionState == ConnectionState.Connected)
{
while (_queue.Count > 0)
{
var item = _queue.Dequeue();
try
{
await _proxy.Invoke(item.MethodName, item.Args); //.ConfigureAwait(false);
}
catch (Exception ex)
{
_tracer?.WriteLine($"[{_className}] Could not process pending item '{item.MethodName}': {ex.Message}");
}
}
}
}
#endregion
}
}