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
659 lines (529 loc) · 21.6 KB
/
ServerEventsClient.cs
File metadata and controls
659 lines (529 loc) · 21.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
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
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 long IdleTimeoutMs { 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 ServerEventHeartbeat : ServerEventCommand { }
public class ServerEventMessage : IMeta
{
public long EventId { get; set; }
public string Channel { 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;
static int DefaultIdleTimeoutMs = 30 * 1000;
private bool stopped = true;
byte[] buffer;
Encoding encoding = new UTF8Encoding();
HttpWebRequest httpReq;
HttpWebResponse response;
CancellationTokenSource cancel;
private ITimer heartbeatTimer;
public ServerEventConnect ConnectionInfo { get; private set; }
public string SubscriptionId
{
get { return ConnectionInfo != null ? ConnectionInfo.Id : null; }
}
public string ConnectionDisplayName
{
get { return ConnectionInfo != null ? ConnectionInfo.DisplayName : "(not connected)"; }
}
public string EventStreamUri { get; set; }
public string[] Channels { get; set; }
public IServiceClient ServiceClient { get; set; }
public DateTime LastPulseAt { get; set; }
public Action<ServerEventConnect> OnConnect;
public Action<ServerEventMessage> OnCommand;
public Action<ServerEventMessage> OnMessage;
public Action OnHeartbeat;
public Action<Exception> OnException;
public Action<WebRequest> EventStreamRequestFilter { get; set; }
public Action<WebRequest> HeartbeatRequestFilter { get; set; }
public static readonly Task<object> EmptyTask;
static ServerEventsClient()
{
var tcs = new TaskCompletionSource<object>();
tcs.SetResult(null);
EmptyTask = tcs.Task;
}
public ServerEventsClient(string baseUri, params string[] channels)
{
this.EventStreamUri = baseUri.CombineWith("event-stream");
this.Channels = channels;
if (Channels != null && Channels.Length > 0)
this.EventStreamUri = this.EventStreamUri
.AddQueryParam("channel", string.Join(",", Channels));
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()");
stopped = false;
httpReq = (HttpWebRequest)WebRequest.Create(EventStreamUri);
httpReq.CookieContainer = ((ServiceClientBase)ServiceClient).CookieContainer; //share auth cookies
//httpReq.AllowReadStreamBuffering = false; //.NET v4.5
if (EventStreamRequestFilter != null)
EventStreamRequestFilter(httpReq);
response = (HttpWebResponse)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 (heartbeatTcs == null || heartbeatTcs.Task.IsCompleted)
heartbeatTcs = new TaskCompletionSource<ServerEventHeartbeat>();
if (messageTcs == null || messageTcs.Task.IsCompleted)
messageTcs = new TaskCompletionSource<ServerEventMessage>();
LastPulseAt = DateTime.UtcNow;
if (log.IsDebugEnabled)
log.Debug("[SSE-CLIENT] LastPulseAt: " + DateTime.UtcNow.TimeOfDay);
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<ServerEventHeartbeat> heartbeatTcs;
public Task<ServerEventHeartbeat> WaitForNextHeartbeat()
{
Contract.Assert(!heartbeatTcs.Task.IsCompleted);
return heartbeatTcs.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("[SSE-CLIENT] OnConnectReceived: {0} on #{1} / {2} on ({3})",
ConnectionInfo.EventId, ConnectionDisplayName, ConnectionInfo.Id, string.Join(", ", Channels));
StartNewHeartbeat();
var hold = connectTcs;
connectTcs = new TaskCompletionSource<ServerEventConnect>();
if (OnConnect != null)
OnConnect(ConnectionInfo);
hold.SetResult(ConnectionInfo); //needs to be at end or control yielded before Heartbeat can start
}
protected void StartNewHeartbeat()
{
if (ConnectionInfo == null || 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 (log.IsDebugEnabled)
log.DebugFormat("[SSE-CLIENT] Prep for Heartbeat...");
if (cancel.IsCancellationRequested)
return;
var elapsedMs = (DateTime.UtcNow - LastPulseAt).TotalMilliseconds;
if (elapsedMs > ConnectionInfo.IdleTimeoutMs)
{
OnExceptionReceived(new TimeoutException("Last Heartbeat Pulse was {0}ms ago".Fmt(elapsedMs)));
return;
}
EnsureSynchronizationContext();
if (ConnectionInfo == null)
return;
ConnectionInfo.HeartbeatUrl.GetStringFromUrlAsync(requestFilter:HeartbeatRequestFilter)
.Success(t => {
if (cancel.IsCancellationRequested)
return;
if (log.IsDebugEnabled)
log.DebugFormat("[SSE-CLIENT] Heartbeat sent to: " + ConnectionInfo.HeartbeatUrl);
StartNewHeartbeat();
})
.Error(ex => {
if (cancel.IsCancellationRequested)
return;
if (log.IsDebugEnabled)
log.DebugFormat("[SSE-CLIENT] 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("[SSE-CLIENT] SynchronizationContext.Current == null");
SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());
}
protected void OnCommandReceived(ServerEventCommand e)
{
if (log.IsDebugEnabled)
log.DebugFormat("[SSE-CLIENT] OnCommandReceived: ({0}) #{1} on #{2} ({3})", e.GetType().Name, e.EventId, ConnectionDisplayName, string.Join(", ", Channels));
var hold = commandTcs;
commandTcs = new TaskCompletionSource<ServerEventCommand>();
if (OnCommand != null)
OnCommand(e);
hold.SetResult(e);
}
protected void OnHeartbeatReceived(ServerEventHeartbeat e)
{
if (log.IsDebugEnabled)
log.DebugFormat("[SSE-CLIENT] OnHeartbeatReceived: ({0}) #{1} on #{2} ({3})", e.GetType().Name, e.EventId, ConnectionDisplayName, string.Join(", ", Channels));
var hold = heartbeatTcs;
heartbeatTcs = new TaskCompletionSource<ServerEventHeartbeat>();
if (OnHeartbeat != null)
OnHeartbeat();
hold.SetResult(e);
}
protected void OnMessageReceived(ServerEventMessage e)
{
if (log.IsDebugEnabled)
log.DebugFormat("[SSE-CLIENT] OnMessageReceived: {0} on #{1} ({2})", e.EventId, ConnectionDisplayName, string.Join(", ", Channels));
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("[SSE-CLIENT] OnExceptionReceived: {0} on #{1}".Fmt(ex.Message, ConnectionDisplayName), ex);
if (OnException != null)
OnException(ex);
Restart();
}
public void Restart()
{
try
{
InternalStop();
if (stopped)
return;
SleepBackOffMultiplier(errorsCount)
.ContinueWith(t =>
{
try
{
Start();
}
catch (Exception ex)
{
OnExceptionReceived(ex);
}
});
}
catch (Exception ex)
{
log.Error("[SSE-CLIENT] 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 (pos == 0)
{
if (currentMsg != null)
ProcessEventMessage(currentMsg);
currentMsg = null;
text = text.Substring(pos + 1);
if (text.Length > 0)
continue;
break;
}
var line = text.Substring(0, pos);
if (!string.IsNullOrWhiteSpace(line))
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}", ConnectionDisplayName);
Restart();
}
});
}
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];
var selParts = e.Selector.SplitOnFirst('@');
if (selParts.Length > 1)
{
e.Channel = selParts[0];
e.Selector = selParts[1];
}
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;
case "onHeartbeat":
ProcessOnHeartbeatMessage(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 = JsonServiceClient.ParseObject(e.Json);
ConnectionInfo = new ServerEventConnect {
HeartbeatIntervalMs = DefaultHeartbeatMs,
IdleTimeoutMs = DefaultIdleTimeoutMs,
}.Populate(e, msg);
ConnectionInfo.Id = msg.Get("id");
ConnectionInfo.HeartbeatUrl = msg.Get("heartbeatUrl");
ConnectionInfo.HeartbeatIntervalMs = msg.Get<long>("heartbeatIntervalMs");
ConnectionInfo.IdleTimeoutMs = msg.Get<long>("idleTimeoutMs");
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 = JsonServiceClient.ParseObject(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 = JsonServiceClient.ParseObject(e.Json);
var leaveMsg = new ServerEventLeave().Populate(e, msg);
leaveMsg.Channel = msg.Get("channel");
OnCommandReceived(leaveMsg);
}
private void ProcessOnHeartbeatMessage(ServerEventMessage e)
{
LastPulseAt = DateTime.UtcNow;
if (log.IsDebugEnabled)
log.Debug("[SSE-CLIENT] LastPulseAt: " + DateTime.UtcNow.TimeOfDay);
var msg = JsonServiceClient.ParseObject(e.Json);
var heartbeatMsg = new ServerEventHeartbeat().Populate(e, msg);
OnHeartbeatReceived(heartbeatMsg);
}
public virtual Task Stop()
{
stopped = true;
return InternalStop();
}
public virtual Task InternalStop()
{
if (log.IsDebugEnabled)
log.DebugFormat("Stop()");
if (cancel != null)
cancel.Cancel();
Task task = EmptyTask;
if (ConnectionInfo != null && ConnectionInfo.UnRegisterUrl != null)
{
EnsureSynchronizationContext();
task = ConnectionInfo.UnRegisterUrl.GetStringFromUrlAsync();
task.Error(ex => { /*ignore*/});
}
using (response)
{
response = null;
}
ConnectionInfo = null;
httpReq = null;
return task;
}
public void Dispose()
{
if (log.IsDebugEnabled)
log.DebugFormat("Dispose()");
Stop();
}
}
public static class ServerEventClientExtensions
{
#if !SL5
public static AuthenticateResponse Authenticate(this ServerEventsClient client, Authenticate request)
{
return client.ServiceClient.Post(request);
}
#endif
public static Task<AuthenticateResponse> AuthenticateAsync(this ServerEventsClient client, Authenticate request)
{
return client.ServiceClient.PostAsync(request);
}
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.Channel = src.Channel;
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;
}
}
}