-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
InProcessMessageStore.cs
103 lines (82 loc) · 3.23 KB
/
InProcessMessageStore.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
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using SignalR.Infrastructure;
namespace SignalR {
public class InProcessMessageStore : IMessageStore {
private readonly ConcurrentDictionary<string, SafeSet<Message>> _items = new ConcurrentDictionary<string, SafeSet<Message>>(StringComparer.OrdinalIgnoreCase);
// Interval to wait before cleaning up expired items
private readonly TimeSpan _cleanupInterval = TimeSpan.FromSeconds(10);
private long _lastMessageId = 0;
private readonly object _idLocker = new object();
private bool _gcRunning;
private readonly Timer _timer;
public InProcessMessageStore()
: this(garbageCollectMessages: true) {
}
internal InProcessMessageStore(bool garbageCollectMessages) {
if (garbageCollectMessages) {
_timer = new Timer(RemoveExpiredEntries, null, _cleanupInterval, _cleanupInterval);
}
}
public Task Save(string key, object value) {
var message = new Message(key, Interlocked.Increment(ref _lastMessageId), value);
return Save(message);
}
protected internal Task Save(Message message) {
var key = message.SignalKey;
var list = _items.GetOrAdd(key, _ => new SafeSet<Message>());
list.Add(message);
if (message.Id > _lastMessageId) {
lock (_idLocker) {
if (message.Id > _lastMessageId) {
_lastMessageId = message.Id;
}
}
}
return TaskAsyncHelper.Empty;
}
public Task<IEnumerable<Message>> GetAllSince(string key, long id) {
if (id > _lastMessageId) {
id = 0;
}
var items = GetAllCore(key).Where(item => item.Id > id)
.OrderBy(item => item.Id);
return TaskAsyncHelper.FromResult<IEnumerable<Message>>(items);
}
public Task<long?> GetLastId() {
if (_lastMessageId > 0) {
return TaskAsyncHelper.FromResult<long?>(_lastMessageId);
}
return TaskAsyncHelper.FromResult<long?>(null);
}
private IEnumerable<Message> GetAllCore(string key) {
SafeSet<Message> list;
if (_items.TryGetValue(key, out list)) {
// Return a copy of the list
return list.GetSnapshot();
}
return Enumerable.Empty<Message>();
}
private void RemoveExpiredEntries(object state) {
if (_gcRunning) {
return;
}
_gcRunning = true;
// Take a snapshot of the entries
var entries = _items.ToList();
// Remove all the expired ones
foreach (var entry in entries) {
foreach (var item in entry.Value.GetSnapshot()) {
if (item.Expired) {
entry.Value.Remove(item);
}
}
}
_gcRunning = false;
}
}
}