-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
ScaleoutMessageBus.cs
258 lines (214 loc) · 9.53 KB
/
ScaleoutMessageBus.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
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
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.SignalR.Configuration;
using Microsoft.AspNet.SignalR.Infrastructure;
using Microsoft.AspNet.SignalR.Tracing;
namespace Microsoft.AspNet.SignalR.Messaging
{
/// <summary>
/// Common base class for scaleout message bus implementations.
/// </summary>
public abstract class ScaleoutMessageBus : MessageBus
{
private readonly SipHashBasedStringEqualityComparer _sipHashBasedComparer = new SipHashBasedStringEqualityComparer(0, 0);
private readonly ITraceManager _traceManager;
private readonly TraceSource _trace;
private readonly Lazy<ScaleoutStreamManager> _streamManager;
private readonly IPerformanceCounterManager _perfCounters;
protected ScaleoutMessageBus(IDependencyResolver resolver, ScaleoutConfiguration configuration)
: base(resolver)
{
if (configuration == null)
{
throw new ArgumentNullException("configuration");
}
_traceManager = resolver.Resolve<ITraceManager>();
_trace = _traceManager["SignalR." + typeof(ScaleoutMessageBus).Name];
_perfCounters = resolver.Resolve<IPerformanceCounterManager>();
var maxScaloutMappings = resolver.Resolve<IConfigurationManager>().MaxScaleoutMappingsPerStream;
_streamManager = new Lazy<ScaleoutStreamManager>(
() => new ScaleoutStreamManager(Send, OnReceivedCore, StreamCount, _trace, _perfCounters, configuration, maxScaloutMappings));
}
/// <summary>
/// The number of streams can't change for the lifetime of this instance.
/// </summary>
protected virtual int StreamCount
{
get
{
return 1;
}
}
private ScaleoutStreamManager StreamManager
{
get
{
return _streamManager.Value;
}
}
/// <summary>
/// Opens the specified queue for sending messages.
/// <param name="streamIndex">The index of the stream to open.</param>
/// </summary>
protected void Open(int streamIndex)
{
StreamManager.Open(streamIndex);
}
/// <summary>
/// Closes the specified queue.
/// <param name="streamIndex">The index of the stream to close.</param>
/// </summary>
protected void Close(int streamIndex)
{
StreamManager.Close(streamIndex);
}
/// <summary>
/// Closes the specified queue for sending messages making all sends fail asynchronously.
/// </summary>
/// <param name="streamIndex">The index of the stream to close.</param>
/// <param name="exception">The error that occurred.</param>
protected void OnError(int streamIndex, Exception exception)
{
StreamManager.OnError(streamIndex, exception);
}
/// <summary>
/// Sends messages to the backplane
/// </summary>
/// <param name="messages">The list of messages to send</param>
/// <returns></returns>
protected virtual Task Send(IList<Message> messages)
{
// If we're only using a single stream then just send
if (StreamCount == 1)
{
return StreamManager.Send(0, messages);
}
var taskCompletionSource = new DispatchingTaskCompletionSource<object>();
// Group messages by source (connection id)
var messagesBySource = messages.GroupBy(m => m.Source);
SendImpl(messagesBySource.GetEnumerator(), taskCompletionSource);
return taskCompletionSource.Task;
}
protected virtual Task Send(int streamIndex, IList<Message> messages)
{
throw new NotImplementedException();
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "We return a faulted tcs")]
private void SendImpl(IEnumerator<IGrouping<string, Message>> enumerator, DispatchingTaskCompletionSource<object> taskCompletionSource)
{
send:
if (!enumerator.MoveNext())
{
taskCompletionSource.TrySetResult(null);
}
else
{
IGrouping<string, Message> group = enumerator.Current;
// Get the channel index we're going to use for this message
int index = (int)((uint)_sipHashBasedComparer.GetHashCode(group.Key) % StreamCount);
Debug.Assert(index >= 0, "Hash function resulted in an index < 0.");
Task sendTask = StreamManager.Send(index, group.ToArray()).Catch(_trace);
if (sendTask.IsCompleted)
{
try
{
sendTask.Wait();
goto send;
}
catch (Exception ex)
{
taskCompletionSource.SetUnwrappedException(ex);
}
}
else
{
sendTask.Then((enumer, tcs) => SendImpl(enumer, tcs), enumerator, taskCompletionSource)
.ContinueWithNotComplete(taskCompletionSource);
}
}
}
/// <summary>
/// Invoked when a payload is received from the backplane. There should only be one active call at any time.
/// </summary>
/// <param name="streamIndex">id of the stream.</param>
/// <param name="id">id of the payload within that stream.</param>
/// <param name="message">The scaleout message.</param>
/// <returns></returns>
protected virtual void OnReceived(int streamIndex, ulong id, ScaleoutMessage message)
{
StreamManager.OnReceived(streamIndex, id, message);
}
private void OnReceivedCore(int streamIndex, ulong id, ScaleoutMessage scaleoutMessage)
{
Counters.ScaleoutMessageBusMessagesReceivedPerSec.IncrementBy(scaleoutMessage.Messages.Count);
_trace.TraceInformation("OnReceived({0}, {1}, {2})", streamIndex, id, scaleoutMessage.Messages.Count);
TraceScaleoutMessages(id, scaleoutMessage);
var localMapping = new LocalEventKeyInfo[scaleoutMessage.Messages.Count];
var keys = new HashSet<string>();
for (var i = 0; i < scaleoutMessage.Messages.Count; ++i)
{
Message message = scaleoutMessage.Messages[i];
// Remember where this message came from
message.MappingId = id;
message.StreamIndex = streamIndex;
keys.Add(message.Key);
ulong localId = Save(message);
_trace.TraceVerbose("Message id: {0}, stream : {1}, eventKey: '{2}' saved with local id: {3}",
id, streamIndex, message.Key, localId);
MessageStore<Message> messageStore = Topics[message.Key].Store;
localMapping[i] = new LocalEventKeyInfo(message.Key, localId, messageStore);
}
// Get the stream for this payload
ScaleoutMappingStore store = StreamManager.Streams[streamIndex];
// Publish only after we've setup the mapping fully
store.Add(id, scaleoutMessage, localMapping);
if (_trace.Switch.ShouldTrace(TraceEventType.Verbose))
{
_trace.TraceVerbose("Scheduling eventkeys: {0}", string.Join(",", keys));
}
// Schedule after we're done
foreach (var eventKey in keys)
{
ScheduleEvent(eventKey);
}
}
private void TraceScaleoutMessages(ulong id, ScaleoutMessage scaleoutMessage)
{
if (!_trace.Switch.ShouldTrace(TraceEventType.Verbose))
{
return;
}
foreach (var message in scaleoutMessage.Messages)
{
_trace.TraceVerbose("Received message {0}: '{1}' over ScaleoutMessageBus", id, message.GetString());
}
}
public override Task Publish(Message message)
{
Counters.MessageBusMessagesPublishedTotal.Increment();
Counters.MessageBusMessagesPublishedPerSec.Increment();
// TODO: Implement message batching here
return Send(new[] { message });
}
protected override void Dispose(bool disposing)
{
// Close all streams
for (int i = 0; i < StreamCount; i++)
{
Close(i);
}
base.Dispose(disposing);
}
[SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0", Justification = "Called from derived class")]
protected override Subscription CreateSubscription(ISubscriber subscriber, string cursor, Func<MessageResult, object, Task<bool>> callback, int messageBufferSize, object state)
{
return new ScaleoutSubscription(subscriber.Identity, subscriber.EventKeys, cursor, StreamManager.Streams, callback, messageBufferSize, _traceManager, Counters, state);
}
}
}