forked from ServiceStack/ServiceStack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRedisServerEvents.cs
More file actions
434 lines (362 loc) · 14.7 KB
/
RedisServerEvents.cs
File metadata and controls
434 lines (362 loc) · 14.7 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
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using ServiceStack.Logging;
using ServiceStack.Redis;
namespace ServiceStack
{
public class RedisServerEvents : IServerEvents
{
private static ILog Log = LogManager.GetLogger(typeof(RedisServerEvents));
private MemoryServerEvents local;
public TimeSpan Timeout
{
get { return local.IdleTimeout; }
set { local.IdleTimeout = value; }
}
public Action<IEventSubscription> OnSubscribe
{
get { return local.OnSubscribe; }
set { local.OnSubscribe = value; }
}
public Action<IEventSubscription> OnUnsubscribe
{
get { return local.OnUnsubscribe; }
set { local.OnUnsubscribe = value; }
}
public bool NotifyChannelOfSubscriptions
{
get { return local.NotifyChannelOfSubscriptions; }
set { local.NotifyChannelOfSubscriptions = value; }
}
public int? KeepAliveRetryAfterMs
{
get { return RedisPubSub.KeepAliveRetryAfterMs; }
set { RedisPubSub.KeepAliveRetryAfterMs = value; }
}
public static string Topic = "sse:topic";
public class RedisIndex
{
public const string Subscription = "sse:id:{0}";
public const string ActiveSubscriptionsSet = "sse:ids";
public const string ChannelSet = "sse:channel:{0}";
public const string UserIdSet = "sse:userid:{0}";
public const string UserNameSet = "sse:username:{0}";
public const string SessionSet = "sse:session:{0}";
}
public IRedisClientsManager clientsManager;
public IRedisPubSubServer RedisPubSub { get; set; }
public RedisServerEvents(IRedisPubSubServer redisPubSub)
{
this.RedisPubSub = redisPubSub;
this.clientsManager = redisPubSub.ClientsManager;
redisPubSub.OnInit = OnInit;
redisPubSub.OnError = ex => Log.Error("Exception in RedisServerEvents: " + ex.Message, ex);
redisPubSub.OnMessage = HandleMessage;
KeepAliveRetryAfterMs = 2000;
local = new MemoryServerEvents
{
NotifyJoin = HandleOnJoin,
NotifyLeave = HandleOnLeave,
NotifyHeartbeat = HandleOnHeartbeat,
Serialize = HandleSerialize,
};
var appHost = HostContext.AppHost;
var feature = appHost != null ? appHost.GetPlugin<ServerEventsFeature>() : null;
if (feature != null)
{
Timeout = feature.IdleTimeout;
OnSubscribe = feature.OnSubscribe;
OnUnsubscribe = feature.OnUnsubscribe;
NotifyChannelOfSubscriptions = feature.NotifyChannelOfSubscriptions;
}
}
private void OnInit()
{
UnRegisterExpiredSubscriptions();
}
private void UnRegisterExpiredSubscriptions()
{
using (var redis = clientsManager.GetClient())
{
var lastPulseBefore = (RedisPubSub.CurrentServerTime - Timeout).Ticks;
var expiredSubIds = redis.GetRangeFromSortedSetByLowestScore(
RedisIndex.ActiveSubscriptionsSet, 0, lastPulseBefore);
foreach (var id in expiredSubIds)
{
NotifyRedis("unregister.id." + id, null, null);
}
//Force remove zombie subscriptions which have no listeners
var infos = GetSubscriptionInfos(redis, expiredSubIds);
foreach (var info in infos)
{
RemoveSubscriptionFromRedis(info);
}
}
}
private static List<SubscriptionInfo> GetSubscriptionInfos(IRedisClient redis, IEnumerable<string> subIds)
{
var keys = subIds.Map(x => RedisIndex.Subscription.Fmt(x));
var infos = redis.GetValues<SubscriptionInfo>(keys);
return infos;
}
public RedisServerEvents(IRedisClientsManager clientsManager)
: this(new RedisPubSubServer(clientsManager, Topic)) {}
void HandleOnJoin(IEventSubscription sub)
{
NotifyChannel(sub.Channel, "cmd.onJoin", sub.Meta);
}
void HandleOnLeave(IEventSubscription sub)
{
var info = sub.GetInfo();
RemoveSubscriptionFromRedis(info);
NotifyChannel(sub.Channel, "cmd.onLeave", sub.Meta);
}
void HandleOnHeartbeat(IEventSubscription sub)
{
NotifyChannel(sub.Channel, "cmd.onHeartbeat", sub.Meta);
}
private void RemoveSubscriptionFromRedis(SubscriptionInfo info)
{
var id = info.SubscriptionId;
using (var redis = clientsManager.GetClient())
using (var trans = redis.CreateTransaction())
{
trans.QueueCommand(r => r.Remove(RedisIndex.Subscription.Fmt(id)));
trans.QueueCommand(r => r.RemoveItemFromSortedSet(RedisIndex.ActiveSubscriptionsSet, id));
trans.QueueCommand(r => r.RemoveItemFromSet(RedisIndex.ChannelSet.Fmt(info.Channel), id));
trans.QueueCommand(r => r.RemoveItemFromSet(RedisIndex.UserIdSet.Fmt(info.UserId), id));
if (info.UserName != null)
trans.QueueCommand(r => r.RemoveItemFromSet(RedisIndex.UserNameSet.Fmt(info.UserName), id));
if (info.SessionId != null)
trans.QueueCommand(r => r.RemoveItemFromSet(RedisIndex.SessionSet.Fmt(info.SessionId), id));
trans.Commit();
}
}
string HandleSerialize(object o)
{
return (string)o; //Already a seiralized JSON string
}
public void NotifyAll(string selector, object message)
{
NotifyRedis("notify.all", selector, message);
}
public void NotifyChannel(string channel, string selector, object message)
{
NotifyRedis("notify.channel." + channel, selector, message);
}
public void NotifySubscription(string subscriptionId, string selector, object message, string channel = null)
{
NotifyRedis("notify.subscription." + subscriptionId, selector, message, channel);
}
public void NotifyUserId(string userId, string selector, object message, string channel = null)
{
NotifyRedis("notify.userid." + userId, selector, message, channel);
}
public void NotifyUserName(string userName, string selector, object message, string channel = null)
{
NotifyRedis("notify.username." + userName, selector, message, channel);
}
public void NotifySession(string sspid, string selector, object message, string channel = null)
{
NotifyRedis("notify.session." + sspid, selector, message, channel);
}
public SubscriptionInfo GetSubscriptionInfo(string id)
{
using (var redis = clientsManager.GetClient())
{
var info = redis.Get<SubscriptionInfo>(RedisIndex.Subscription.Fmt(id));
return info;
}
}
public List<SubscriptionInfo> GetSubscriptionInfosByUserId(string userId)
{
using (var redis = clientsManager.GetClient())
{
var ids = redis.GetAllItemsFromSet(RedisIndex.UserIdSet.Fmt(userId));
var keys = ids.Map(x => RedisIndex.Subscription.Fmt(x));
var infos = redis.GetValues<SubscriptionInfo>(keys);
return infos;
}
}
public void Register(IEventSubscription sub, Dictionary<string, string> connectArgs = null)
{
if (sub == null)
throw new ArgumentNullException("subscription");
var info = sub.GetInfo();
using (var redis = clientsManager.GetClient())
{
StoreSubscriptionInfo(redis, info);
}
if (connectArgs != null)
sub.Publish("cmd.onConnect", connectArgs.ToJson());
local.Register(sub);
}
private void StoreSubscriptionInfo(IRedisClient redis, SubscriptionInfo info)
{
var id = info.SubscriptionId;
using (var trans = redis.CreateTransaction())
{
trans.QueueCommand(r => r.AddItemToSortedSet(RedisIndex.ActiveSubscriptionsSet, id, RedisPubSub.CurrentServerTime.Ticks));
trans.QueueCommand(r => r.Set(RedisIndex.Subscription.Fmt(id), info));
trans.QueueCommand(r => r.AddItemToSet(RedisIndex.ChannelSet.Fmt(info.Channel), id));
trans.QueueCommand(r => r.AddItemToSet(RedisIndex.UserIdSet.Fmt(info.UserId), id));
if (info.UserName != null)
trans.QueueCommand(r => r.AddItemToSet(RedisIndex.UserNameSet.Fmt(info.UserName), id));
if (info.SessionId != null)
trans.QueueCommand(r => r.AddItemToSet(RedisIndex.SessionSet.Fmt(info.SessionId), id));
trans.Commit();
}
}
public void UnRegister(string subscriptionId)
{
var info = GetSubscriptionInfo(subscriptionId);
if (info == null)
return;
NotifyRedis("unregister.id." + subscriptionId, null, null);
}
public long GetNextSequence(string sequenceId)
{
using (var redis = clientsManager.GetClient())
{
return redis.Increment("sse:seq:" + sequenceId, 1);
}
}
public List<Dictionary<string, string>> GetSubscriptionsDetails(string channel = null)
{
using (var redis = clientsManager.GetClient())
{
var ids = redis.GetAllItemsFromSet(RedisIndex.ChannelSet.Fmt(channel));
var keys = ids.Map(x => RedisIndex.Subscription.Fmt(x));
var infos = redis.GetValues<SubscriptionInfo>(keys);
var metas = infos.Map(x => x.Meta);
return metas;
}
}
public bool Pulse(string subscriptionId)
{
using (var redis = clientsManager.GetClient())
{
var info = redis.Get<SubscriptionInfo>(RedisIndex.Subscription.Fmt(subscriptionId));
if (info == null)
return false;
redis.AddItemToSortedSet(RedisIndex.ActiveSubscriptionsSet,
info.SubscriptionId, RedisPubSub.CurrentServerTime.Ticks);
NotifyRedis("pulse.id." + subscriptionId, null, null);
return true;
}
}
public void Reset()
{
local.Reset();
using (var redis = clientsManager.GetClient())
{
redis.FlushDb();
}
}
public void Start()
{
RedisPubSub.Start();
local.Start();
}
public void Stop()
{
RedisPubSub.Stop();
local.Stop();
}
protected void NotifyRedis(string key, string selector, object message, string channel = null)
{
using (var redis = clientsManager.GetClient())
{
var json = message != null ? message.ToJson() : null;
var sb = new StringBuilder(key);
if (selector != null)
{
sb.Append(' ').Append(selector);
if (channel != null)
{
sb.Append('@');
sb.Append(channel);
}
}
if (json != null)
{
sb.Append(' ');
sb.Append(json);
}
var msg = sb.ToString();
redis.PublishMessage(Topic, msg);
}
}
public void HandleMessage(string channel, string message)
{
OnMessage(message);
}
protected void OnMessage(string message)
{
var parts = message.SplitOnFirst(' ');
var tokens = parts[0].Split('.');
var cmd = tokens[0];
switch (cmd)
{
case "notify":
var notify = tokens[1];
var who = tokens.Length > 2 ? tokens[2] : null;
var body = parts[1].SplitOnFirst(' ');
var selUri = body[0];
var selParts = selUri.SplitOnFirst('@');
var selector = selParts[0];
var channel = selParts.Length > 1 ? selParts[1] : null;
var msg = body.Length > 1 ? body[1] : null;
switch (notify)
{
case "all":
local.NotifyAll(selector, msg);
break;
case "channel":
local.NotifyChannel(who, selector, msg);
break;
case "subscription":
local.NotifySubscription(who, selector, msg, channel);
break;
case "userid":
local.NotifyUserId(who, selector, msg, channel);
break;
case "username":
local.NotifyUserName(who, selector, msg, channel);
break;
case "session":
local.NotifySession(who, selector, msg, channel);
break;
}
break;
case "unregister":
var unregister = tokens[1];
if (unregister == "id")
{
var id = tokens.Length > 2 ? tokens[2] : null;
local.UnRegister(id);
}
break;
case "pulse":
var pulse = tokens[1];
if (pulse == "id")
{
var id = tokens.Length > 2 ? tokens[2] : null;
local.Pulse(id);
}
break;
}
}
public void Dispose()
{
if (RedisPubSub != null)
RedisPubSub.Dispose();
if (local != null)
local.Dispose();
RedisPubSub = null;
local = null;
}
}
}