forked from ServiceStack/ServiceStack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathServerEventsClient.cs
More file actions
523 lines (421 loc) · 16.6 KB
/
Copy pathServerEventsClient.cs
File metadata and controls
523 lines (421 loc) · 16.6 KB
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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.IO;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using ServiceStack.Logging;
using ServiceStack.Text;
namespace ServiceStack
{
public class ServerEventConnect : ServerEventJoin
{
public string Id { get; set; }
public string UnRegisterUrl { get; set; }
public string HeartbeatUrl { get; set; }
public long HeartbeatIntervalMs { get; set; }
}
public class ServerEventJoin : ServerEventCommand
{
public string UserId { get; set; }
public string DisplayName { get; set; }
public string ProfileUrl { get; set; }
}
public class ServerEventLeave : ServerEventCommand {}
public class ServerEventCommand : ServerEventMessage { }
public class ServerEventMessage : IMeta
{
public long EventId { get; set; }
public string Data { get; set; }
public string Selector { get; set; }
public string Json { get; set; }
public string Op { get; set; }
public string Target { get; set; }
public string CssSelector { get; set; }
public Dictionary<string, string> Meta { get; set; }
}
public partial class ServerEventsClient : IDisposable
{
private static ILog log = LogManager.GetLogger(typeof(ServerEventsClient));
public static int BufferSize = 1024 * 64;
static int DefaultHeartbeatMs = 10 * 1000;
byte[] buffer;
Encoding encoding = new UTF8Encoding();
HttpWebRequest httpReq;
CancellationTokenSource cancel;
private ITimer heartbeatTimer;
public ServerEventConnect ConnectionInfo { get; private set; }
public string SubscriptionId
{
get { return ConnectionInfo != null ? ConnectionInfo.Id : null; }
}
public string EventStreamUri { get; set; }
public IServiceClient ServiceClient { get; set; }
public Action<ServerEventConnect> OnConnect;
public Action<ServerEventMessage> OnCommand;
public Action<ServerEventMessage> OnMessage;
public Action OnHeartbeat;
public Action<Exception> OnException;
public static readonly Task<object> EmptyTask;
static ServerEventsClient()
{
var tcs = new TaskCompletionSource<object>();
tcs.SetResult(null);
EmptyTask = tcs.Task;
}
public ServerEventsClient(string baseUri, string channel=null)
{
this.EventStreamUri = baseUri.CombineWith("event-stream");
if (channel != null)
this.EventStreamUri = this.EventStreamUri.AddQueryParam("channel", channel);
this.ServiceClient = new JsonServiceClient(baseUri);
this.Resolver = new NewInstanceResolver();
this.ReceiverTypes = new List<Type>();
this.Handlers = new Dictionary<string, ServerEventCallback>();
this.NamedReceivers = new Dictionary<string, ServerEventCallback>();
}
public ServerEventsClient Start()
{
if (log.IsDebugEnabled)
log.DebugFormat("Start()");
httpReq = (HttpWebRequest)WebRequest.Create(EventStreamUri);
//httpReq.AllowReadStreamBuffering = false; //.NET v4.5
var response = PclExport.Instance.GetResponse(httpReq);
var stream = response.GetResponseStream();
buffer = new byte[BufferSize];
cancel = new CancellationTokenSource();
//maintain existing tcs so reconnecting is transparent
if (connectTcs == null || connectTcs.Task.IsCompleted)
connectTcs = new TaskCompletionSource<ServerEventConnect>();
if (commandTcs == null || commandTcs.Task.IsCompleted)
commandTcs = new TaskCompletionSource<ServerEventCommand>();
if (messageTcs == null || messageTcs.Task.IsCompleted)
messageTcs = new TaskCompletionSource<ServerEventMessage>();
ProcessResponse(stream);
return this;
}
private TaskCompletionSource<ServerEventConnect> connectTcs;
public Task<ServerEventConnect> Connect()
{
if (httpReq == null)
Start();
Contract.Assert(!connectTcs.Task.IsCompleted);
return connectTcs.Task;
}
private TaskCompletionSource<ServerEventCommand> commandTcs;
public Task<ServerEventCommand> WaitForNextCommand()
{
Contract.Assert(!commandTcs.Task.IsCompleted);
return commandTcs.Task;
}
private TaskCompletionSource<ServerEventMessage> messageTcs;
public Task<ServerEventMessage> WaitForNextMessage()
{
Contract.Assert(!messageTcs.Task.IsCompleted);
return messageTcs.Task;
}
protected void OnConnectReceived()
{
if (log.IsDebugEnabled)
log.DebugFormat("OnConnectReceived: {0} on #{1} / {2}",
ConnectionInfo.EventId, ConnectionInfo.DisplayName, ConnectionInfo.Id);
var hold = connectTcs;
connectTcs = new TaskCompletionSource<ServerEventConnect>();
if (OnConnect != null)
OnConnect(ConnectionInfo);
hold.SetResult(ConnectionInfo);
StartNewHeartbeat();
}
private void StartNewHeartbeat()
{
if (string.IsNullOrEmpty(ConnectionInfo.HeartbeatUrl))
return;
if (heartbeatTimer != null)
heartbeatTimer.Cancel();
heartbeatTimer = PclExportClient.Instance.CreateTimer(Heartbeat,
TimeSpan.FromMilliseconds(ConnectionInfo.HeartbeatIntervalMs), this);
}
protected void Heartbeat(object state)
{
if (cancel.IsCancellationRequested)
return;
EnsureSynchronizationContext();
ConnectionInfo.HeartbeatUrl.GetStringFromUrlAsync()
.Success(t => {
if (cancel.IsCancellationRequested)
return;
if (OnHeartbeat != null)
OnHeartbeat(); //mainly for testing
if (log.IsDebugEnabled)
log.DebugFormat("Heartbeat sent to: " + ConnectionInfo.HeartbeatUrl);
StartNewHeartbeat();
})
.Error(ex => {
if (cancel.IsCancellationRequested)
return;
if (log.IsDebugEnabled)
log.DebugFormat("Error from Heartbeat: {0}", ex.UnwrapIfSingleException().Message);
OnExceptionReceived(ex);
});
}
private static void EnsureSynchronizationContext()
{
if (SynchronizationContext.Current != null) return;
//Unit test runner
if (log.IsDebugEnabled)
log.DebugFormat("SynchronizationContext.Current == null");
SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());
}
protected void OnCommandReceived(ServerEventCommand e)
{
if (log.IsDebugEnabled)
log.DebugFormat("OnCommandReceived: {0} on #{1}", e.EventId, ConnectionInfo.DisplayName);
var hold = commandTcs;
commandTcs = new TaskCompletionSource<ServerEventCommand>();
if (OnCommand != null)
OnCommand(e);
hold.SetResult(e);
}
protected void OnMessageReceived(ServerEventMessage e)
{
if (log.IsDebugEnabled)
log.DebugFormat("OnMessageReceived: {0} on #{1}", e.EventId, ConnectionInfo.DisplayName);
var hold = messageTcs;
messageTcs = new TaskCompletionSource<ServerEventMessage>();
if (OnMessage != null)
OnMessage(e);
hold.SetResult(e);
}
private int errorsCount;
protected void OnExceptionReceived(Exception ex)
{
errorsCount++;
ex = ex.UnwrapIfSingleException();
log.Error("OnExceptionReceived: {0} on #{1}".Fmt(ex.Message, ConnectionInfo.DisplayName), ex);
if (OnException != null)
OnException(ex);
Restart();
}
private void Restart()
{
try
{
Stop();
SleepBackOffMultiplier(errorsCount)
.ContinueWith(t =>
Start());
}
catch (Exception ex)
{
log.Error("Error whilst restarting: {0}".Fmt(ex.Message), ex);
}
}
readonly Random rand = new Random(Environment.TickCount);
private Task SleepBackOffMultiplier(int continuousErrorsCount)
{
if (continuousErrorsCount <= 1)
return EmptyTask;
const int MaxSleepMs = 60 * 1000;
//exponential/random retry back-off.
var nextTry = Math.Min(
rand.Next((int)Math.Pow(continuousErrorsCount, 3), (int)Math.Pow(continuousErrorsCount + 1, 3) + 1),
MaxSleepMs);
if (log.IsDebugEnabled)
log.Debug("Sleeping for {0}ms after {1} continuous errors".Fmt(nextTry, continuousErrorsCount));
return PclExportClient.Instance.WaitAsync(nextTry);
}
private string overflowText = "";
public void ProcessResponse(Stream stream)
{
if (!stream.CanRead) return;
var task = stream.ReadAsync(buffer, 0, 2048, cancel.Token);
task.ContinueWith(t =>
{
if (cancel.IsCancellationRequested || t.IsCanceled)
{
httpReq = null;
return;
}
if (t.IsFaulted)
{
OnExceptionReceived(t.Exception);
httpReq = null;
return;
}
errorsCount = 0;
int len = task.Result;
if (len > 0)
{
var text = overflowText + encoding.GetString(buffer, 0, len);
int pos;
while ((pos = text.IndexOf('\n')) >= 0)
{
if (text == "\n")
{
ProcessEventMessage(currentMsg);
currentMsg = null;
text = "";
break;
}
var line = text.Substring(0, pos);
ProcessLine(line);
if (text.Length > pos + 1)
text = text.Substring(pos + 1);
}
overflowText = text;
ProcessResponse(stream);
}
else
{
if (log.IsDebugEnabled)
log.DebugFormat("Connection ended on {0}",
ConnectionInfo != null ? ConnectionInfo.DisplayName : null);
}
});
}
private ServerEventMessage currentMsg;
void ProcessLine(string line)
{
if (line == null) return;
if (currentMsg == null)
currentMsg = new ServerEventMessage();
var parts = line.SplitOnFirst(':');
var label = parts[0];
var data = parts[1];
if (data.Length > 0 && data[0] == ' ')
data = data.Substring(1);
switch (label)
{
case "id":
currentMsg.EventId = long.Parse(data);
break;
case "data":
currentMsg.Data = data;
break;
}
}
void ProcessEventMessage(ServerEventMessage e)
{
var parts = e.Data.SplitOnFirst(' ');
e.Selector = parts[0];
e.Json = parts[1];
if (!string.IsNullOrEmpty(e.Selector))
{
parts = e.Selector.SplitOnFirst('.');
e.Op = parts[0];
var target = parts[1].Replace("%20", " ");
var tokens = target.SplitOnFirst('$');
e.Target = tokens[0];
if (tokens.Length > 1)
e.CssSelector = tokens[1];
if (e.Op == "cmd")
{
switch (e.Target)
{
case "onConnect":
ProcessOnConnectMessage(e);
return;
case "onJoin":
ProcessOnJoinMessage(e);
return;
case "onLeave":
ProcessOnLeaveMessage(e);
return;
default:
ServerEventCallback cb;
if (Handlers.TryGetValue(e.Target, out cb))
{
cb(this, e);
}
break;
}
}
ServerEventCallback receiver;
NamedReceivers.TryGetValue(e.Op, out receiver);
if (receiver != null)
{
receiver(this, e);
}
}
OnMessageReceived(e);
}
private void ProcessOnConnectMessage(ServerEventMessage e)
{
var msg = JsonObject.Parse(e.Json);
ConnectionInfo = new ServerEventConnect {
HeartbeatIntervalMs = DefaultHeartbeatMs,
}.Populate(e, msg);
ConnectionInfo.Id = msg.Get("id");
ConnectionInfo.HeartbeatUrl = msg.Get("heartbeatUrl");
ConnectionInfo.HeartbeatIntervalMs = msg.Get<long>("heartbeatIntervalMs");
ConnectionInfo.UnRegisterUrl = msg.Get("unRegisterUrl");
ConnectionInfo.UserId = msg.Get("userId");
ConnectionInfo.DisplayName = msg.Get("displayName");
ConnectionInfo.ProfileUrl = msg.Get("profileUrl");
OnConnectReceived();
}
private void ProcessOnJoinMessage(ServerEventMessage e)
{
var msg = JsonObject.Parse(e.Json);
var joinMsg = new ServerEventJoin().Populate(e, msg);
joinMsg.UserId = msg.Get("userId");
joinMsg.DisplayName = msg.Get("displayName");
joinMsg.ProfileUrl = msg.Get("profileUrl");
OnCommandReceived(joinMsg);
}
private void ProcessOnLeaveMessage(ServerEventMessage e)
{
var msg = JsonObject.Parse(e.Json);
var leaveMsg = new ServerEventLeave().Populate(e, msg);
OnCommandReceived(leaveMsg);
}
public virtual void Stop()
{
if (log.IsDebugEnabled)
log.DebugFormat("Stop()");
cancel.Cancel();
if (ConnectionInfo != null && ConnectionInfo.UnRegisterUrl != null)
{
EnsureSynchronizationContext();
ConnectionInfo.UnRegisterUrl.GetStringFromUrlAsync()
.Error(ex => { /*ignore*/});
}
ConnectionInfo = null;
httpReq = null;
}
public void Dispose()
{
if (log.IsDebugEnabled)
log.DebugFormat("Dispose()");
Stop();
}
}
public static class ServerEventClientExtensions
{
public static T Populate<T>(this T dst, ServerEventMessage src, JsonObject msg) where T : ServerEventMessage
{
dst.EventId = src.EventId;
dst.Data = src.Data;
dst.Selector = src.Selector;
dst.Json = src.Json;
dst.Op = src.Op;
if (dst.Meta == null)
dst.Meta = new Dictionary<string, string>();
foreach (var entry in msg)
{
dst.Meta[entry.Key] = entry.Value;
}
return dst;
}
public static ServerEventsClient RegisterHandlers(this ServerEventsClient client, Dictionary<string, ServerEventCallback> handlers)
{
foreach (var entry in handlers)
{
client.Handlers[entry.Key] = entry.Value;
}
return client;
}
}
}