-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathMongoMessageBus.cs
More file actions
317 lines (246 loc) · 9.85 KB
/
Copy pathMongoMessageBus.cs
File metadata and controls
317 lines (246 loc) · 9.85 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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Messaging;
using Microsoft.AspNet.SignalR.Tracing;
using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.Builders;
namespace Signalr.MongoDb
{
public class MongoMessageBus : ScaleoutMessageBus
{
private readonly MongoScaleoutConfiguration _config;
private MongoCollection<MongoMessage> _collection;
private readonly MongoUrl _url;
private MongoServer _server;
private Task _connectingTask;
private readonly TraceSource _trace;
private bool _connectionReady;
private string _collectionName;
private int _state;
private readonly object _callbackLock = new object();
public MongoMessageBus(IDependencyResolver resolver, MongoScaleoutConfiguration configuration)
: base(resolver, configuration)
{
if (configuration == null)
{
throw new ArgumentNullException("configuration");
}
_config = configuration;
_url = new MongoUrl(_config.ConnectionString);
_trace = resolver.Resolve<ITraceManager>()["Signalr." + typeof(MongoMessageBus).Name];
ConnectWithRetry();
}
private bool IsReady
{
get { return _connectionReady && _server != null && _server.State == MongoServerState.Connected; }
}
private void ConnectWithRetry()
{
Connect().ContinueWith(task =>
{
if (task.IsFaulted)
{
_trace.TraceError("Error connecting to Mongo - " + task.Exception.GetBaseException());
if (_state == State.Disposing)
{
Shutdown();
return;
}
Task.Delay(_config.RetryDelay).Then(bus => bus.ConnectWithRetry(), this);
}
else
{
var _oldState = Interlocked.CompareExchange(ref _state, State.Connected, State.Closed);
if (_oldState == State.Closed)
{
Open(0);
}
else if (_oldState == State.Disposing)
{
Shutdown();
}
}
},
TaskContinuationOptions.ExecuteSynchronously);
}
private Task Connect()
{
var _tcs = new TaskCompletionSource<object>();
if (IsReady || Interlocked.CompareExchange(ref _connectingTask, _tcs.Task, null) != null)
{
return TaskAsyncHelper.Empty;
}
try
{
if (_server == null)
{
Task.Factory.StartNew(Init).ContinueWith((task) =>
{
if (task.IsFaulted)
{
_tcs.SetException(task.Exception);
return;
}
if (task.IsCanceled)
{
_tcs.SetCanceled();
return;
}
//ready to send notifications
_tcs.SetResult(null);
_connectionReady = true;
//setup the receiving loop
//this is a blocking call while running
Receiving();
});
}
return _connectingTask.Catch();
}
catch (Exception ex)
{
return TaskAsyncHelper.FromError(ex);
}
}
private void Init()
{
_server = new MongoClient(_url).GetServer();
var _db = _server.GetDatabase(_url.DatabaseName);
_trace.TraceInformation("Opened Mongo database {0}", _url.DatabaseName);
_collectionName = GetCollectionName<MongoMessage>();
//create the collection if it doesn't exist
if (!_db.CollectionExists(_collectionName))
{
_db.CreateCollection(_collectionName, CollectionOptions.SetAutoIndexId(true).SetCapped(true).SetMaxSize(_config.CollectionMaxSize).SetMaxDocuments(_config.MaxDocuments));
////Insert an empty document as without this 'cursor.IsDead' is always true
_db.GetCollection<MongoMessage>(_collectionName).Insert(new MongoMessage(new byte[] { }) { Status = 1 });
}
_collection = _db.GetCollection<MongoMessage>(_collectionName);
_trace.TraceInformation("Opened Mongo collection {0}", _collectionName);
if (!_collection.IsCapped())
{
_trace.TraceInformation("Existing Mongo collection is not capped collection {0}", _collectionName);
throw new MongoConnectionException(string.Format("MongoCollection {0} must be capped", _collectionName));
}
}
protected override Task Send(int streamIndex, IList<Message> messages)
{
_trace.TraceVerbose("Send called with stream index {0}.", streamIndex);
var _msg = new MongoMessage(streamIndex, messages);
if (IsReady)
{
return Task.Factory.StartNew(() => _collection.Insert(_msg)).Catch();
}
return Connect().Then(() => Task.Factory.StartNew(() => _collection.Insert(_msg)));
}
//http://stackoverflow.com/questions/20700161/mongodb-2-4-8-capped-collection-and-tailable-cursor-consuming-all-memory
private void Receiving()
{
try
{
BsonValue _lastId = BsonMinKey.Value;
_trace.TraceInformation("Found collection {0} start point {1}", _collectionName, _lastId);
while (true)
{
IMongoQuery _query = Query.And(
Query<MongoMessage>.GT(x => x.Id, _lastId),
Query<MongoMessage>.EQ(x => x.Status, 0)
);
var _data = _collection.Find(_query)
.SetFlags(QueryFlags.TailableCursor | QueryFlags.NoCursorTimeout | QueryFlags.AwaitData);
var _cursor = new MongoCursorEnumerator<MongoMessage>(_data);
while (true)
{
if (_cursor.MoveNext())
{
var _msg = _cursor.Current;
Process(_msg);
_lastId = _msg.Id;
var _update = Update<MongoMessage>.Set(x => x.Status, 1);
_collection.Update(Query<MongoMessage>.EQ(x => x.Id, _msg.Id), _update);
}
else
{
if (_cursor.IsDead) break;
if (!_cursor.IsServerAwaitCapable) Thread.Sleep(TimeSpan.FromMilliseconds(150));
}
}
}
}
catch (IOException ex)
{
//reset the connection to force a reconnect
_connectionReady = false;
_connectingTask = null;
}
}
private void Process(MongoMessage _msg)
{
try
{
lock (_callbackLock)
{
var _scaleoutMessage = ScaleoutMessage.FromBytes(_msg.Value);
OnReceived(_msg.StreamIndex, (ulong)_msg.Id.CreationTime.Ticks, _scaleoutMessage);
}
}
catch (Exception ex)
{
_trace.TraceInformation("Error adding message to InProcessBus. EventKey={0}, Value={1}. Error={2}, Stack={3}",
_msg.Id, _msg.Value, ex.Message, ex.StackTrace);
Debug.WriteLine(ex.Message);
OnError(0, ex);
}
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
var oldState = Interlocked.Exchange(ref _state, State.Disposing);
switch (oldState)
{
case State.Connected:
case State.Closed:
Shutdown();
break;
case State.Disposed:
Interlocked.Exchange(ref _state, State.Disposed);
break;
}
}
base.Dispose(disposing);
}
private void Shutdown()
{
_trace.TraceInformation("Shutdown...");
if (_server != null)
{
_server.Disconnect();
}
Interlocked.Exchange(ref _state, State.Disposed);
_trace.TraceInformation("Goodbye...");
}
private string GetCollectionName<T>()
{
var _att = Attribute.GetCustomAttribute(typeof(T), typeof(CollectionName));
string _collectionName = _att != null ? ((CollectionName)_att).Name : typeof(T).Name;
if (string.IsNullOrEmpty(_collectionName))
{
throw new ArgumentException("Collection name cannot be empty for this entity");
}
return _collectionName;
}
private static class State
{
public const int Closed = 0;
public const int Connected = 1;
public const int Disposing = 2;
public const int Disposed = 3;
}
}
}