-
Notifications
You must be signed in to change notification settings - Fork 2.1k
Expand file tree
/
Copy pathClientMessageCenter.cs
More file actions
455 lines (401 loc) · 19.5 KB
/
Copy pathClientMessageCenter.cs
File metadata and controls
455 lines (401 loc) · 19.5 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
using System;
using System.Collections.Generic;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Orleans.Configuration;
using Orleans.Internal;
using Orleans.Runtime;
using Orleans.Runtime.Messaging;
#nullable disable
namespace Orleans.Messaging
{
// <summary>
// This class is used on the client only.
// It provides the client counterpart to the Gateway and GatewayAcceptor classes on the silo side.
//
// There is one ClientMessageCenter instance per OutsideRuntimeClient. There can be multiple ClientMessageCenter instances
// in a single process, but because RuntimeClient keeps a static pointer to a single OutsideRuntimeClient instance, this is not
// generally done in practice.
//
// Each ClientMessageCenter keeps a collection of GatewayConnection instances. Each of these represents a bidirectional connection
// to a single gateway endpoint. Requests are assigned to a specific connection based on the target grain ID, so that requests to
// the same grain will go to the same gateway, in sending order. To do this efficiently and scalably, we bucket grains together
// based on their hash code mod a reasonably large number (currently 8192).
//
// When the first message is sent to a bucket, we assign a gateway to that bucket, selecting in round-robin fashion from the known
// gateways. If this is the first message to be sent to the gateway, we will create a new connection for it and assign the bucket to
// the new connection. Either way, all messages to grains in that bucket will be sent to the assigned connection as long as the
// connection is live.
//
// Connections stay live as long as possible. If a socket error or other communications error occurs, then the client will try to
// reconnect twice before giving up on the gateway. If the connection cannot be re-established, then the gateway is deemed (temporarily)
// dead, and any buckets assigned to the connection are unassigned (so that the next message sent will cause a new gateway to be selected).
// There is no assumption that this death is permanent; the system will try to reuse the gateway every 5 minutes.
//
// The list of known gateways is managed by the GatewayManager class. See comments there for details.
// </summary>
internal partial class ClientMessageCenter : IMessageCenter, IDisposable
{
#if NET9_0_OR_GREATER
private readonly Lock grainBucketUpdateLock = new();
#else
private readonly object grainBucketUpdateLock = new();
#endif
internal static readonly TimeSpan MINIMUM_INTERCONNECT_DELAY = TimeSpan.FromMilliseconds(100); // wait one tenth of a second between connect attempts
internal const int CONNECT_RETRY_COUNT = 2; // Retry twice before giving up on a gateway server
internal ClientGrainId ClientId => _localClientDetails.ClientId;
public IRuntimeClient RuntimeClient { get; }
internal bool Running { get; private set; }
private readonly GatewayManager gatewayManager;
private Action<Message> messageHandler;
private int numMessages;
// The grainBuckets array is used to select the connection to use when sending an ordered message to a grain.
// Requests are bucketed by GrainID, so that all requests to a grain get routed through the same bucket.
// Each bucket holds a (possibly null) weak reference to a GatewayConnection object. That connection instance is used
// if the WeakReference is non-null, is alive, and points to a live gateway connection. If any of these conditions is
// false, then a new gateway is selected using the gateway manager, and a new connection established if necessary.
private readonly WeakReference<ClientOutboundConnection>[] grainBuckets;
private readonly ILogger logger;
public SiloAddress MyAddress => _localClientDetails.ClientAddress;
private int numberOfConnectedGateways = 0;
private readonly MessageFactory messageFactory;
private readonly IClusterConnectionStatusListener connectionStatusListener;
private readonly ConnectionManager connectionManager;
private readonly LocalClientDetails _localClientDetails;
public ClientMessageCenter(
IOptions<ClientMessagingOptions> clientMessagingOptions,
LocalClientDetails localClientDetails,
IRuntimeClient runtimeClient,
MessageFactory messageFactory,
IClusterConnectionStatusListener connectionStatusListener,
ILoggerFactory loggerFactory,
ConnectionManager connectionManager,
GatewayManager gatewayManager)
{
this.connectionManager = connectionManager;
_localClientDetails = localClientDetails;
this.RuntimeClient = runtimeClient;
this.messageFactory = messageFactory;
this.connectionStatusListener = connectionStatusListener;
Running = false;
this.gatewayManager = gatewayManager;
numMessages = 0;
this.grainBuckets = new WeakReference<ClientOutboundConnection>[clientMessagingOptions.Value.ClientSenderBuckets];
logger = loggerFactory.CreateLogger<ClientMessageCenter>();
ClientInstruments.RegisterConnectedGatewayCountObserve(() => connectionManager.ConnectionCount);
}
public async Task StartAsync(CancellationToken cancellationToken)
{
await EstablishInitialConnection(cancellationToken);
Running = true;
LogClientMessageCenterStarted();
}
private async Task EstablishInitialConnection(CancellationToken cancellationToken)
{
var liveGateways = gatewayManager.GetLiveGateways();
if (liveGateways.Count == 0)
{
throw new ConnectionFailedException("There are no available gateways.");
}
var pendingTasks = new List<Task>(liveGateways.Count);
foreach (var gateway in liveGateways)
{
pendingTasks.Add(connectionManager.GetConnection(gateway).AsTask());
}
try
{
while (pendingTasks.Count > 0)
{
var completedTask = await Task.WhenAny(pendingTasks).WaitAsync(cancellationToken);
pendingTasks.Remove(completedTask);
// If at least one gateway connection has been established, break out of the loop and continue startup.
if (completedTask.IsCompletedSuccessfully)
{
break;
}
// If there are no more gateways, observe the most recent exception and bail out.
if (pendingTasks.Count == 0)
{
await completedTask;
}
else
{
completedTask.Ignore();
}
}
}
catch (Exception exception)
{
throw new ConnectionFailedException(
$"Unable to connect to any of the {liveGateways.Count} available gateways.",
exception);
}
}
public async Task StopAsync(CancellationToken cancellationToken)
{
Running = false;
await gatewayManager.StopAsync(cancellationToken);
}
public void DispatchLocalMessage(Message message)
{
var handler = this.messageHandler;
if (handler is null)
{
ThrowNullMessageHandler();
}
else
{
handler(message);
}
static void ThrowNullMessageHandler() => throw new InvalidOperationException("MessageCenter does not have a message handler set");
}
public void SendMessage(Message msg)
{
if (!Running)
{
LogNotRunning(msg);
return;
}
var connectionTask = this.GetGatewayConnection(msg);
if (connectionTask.IsCompletedSuccessfully)
{
var connection = connectionTask.Result;
if (connection is null) return;
connection.Send(msg);
LogSendingMessage(msg, connection.RemoteEndPoint);
}
else
{
_ = SendAsync(connectionTask, msg);
async Task SendAsync(ValueTask<Connection> task, Message message)
{
try
{
var connection = await task;
// If the connection returned is null then the message was already rejected due to a failure.
if (connection is null) return;
connection.Send(message);
LogSendingMessage(message, connection.RemoteEndPoint);
}
catch (Exception exception)
{
if (message.RetryCount < MessagingOptions.DEFAULT_MAX_MESSAGE_SEND_RETRIES)
{
++message.RetryCount;
_ = Task.Factory.StartNew(
state => this.SendMessage((Message)state),
message,
CancellationToken.None,
TaskCreationOptions.DenyChildAttach,
TaskScheduler.Default);
}
else
{
this.RejectMessage(message, $"Unable to send message due to exception {exception}", exception);
}
}
}
}
}
private ValueTask<Connection> GetGatewayConnection(Message msg)
{
// If there's a specific gateway specified, use it
if (msg.TargetSilo != null && gatewayManager.IsGatewayAvailable(msg.TargetSilo))
{
var siloAddress = SiloAddress.New(msg.TargetSilo.Endpoint, 0);
var connectionTask = this.connectionManager.GetConnection(siloAddress);
if (connectionTask.IsCompletedSuccessfully) return connectionTask;
return ConnectAsync(msg.TargetSilo, connectionTask, msg, directGatewayMessage: true);
}
// For untargeted messages to system targets, and for unordered messages, pick a next connection in round robin fashion.
if (msg.TargetGrain.IsSystemTarget() || msg.IsUnordered)
{
// Get the cached list of live gateways.
// Pick a next gateway name in a round robin fashion.
// See if we have a live connection to it.
// If Yes, use it.
// If not, create a new GatewayConnection and start it.
// If start fails, we will mark this connection as dead and remove it from the GetCachedLiveGatewayNames.
int msgNumber = Interlocked.Increment(ref numMessages);
var gatewayAddresses = gatewayManager.GetLiveGateways();
int numGateways = gatewayAddresses.Count;
if (numGateways == 0)
{
RejectMessage(msg, "No gateways available");
LogSendFailed(msg, gatewayManager);
return new ValueTask<Connection>(default(Connection));
}
var gatewayAddress = gatewayAddresses[msgNumber % numGateways];
var connectionTask = this.connectionManager.GetConnection(gatewayAddress);
if (connectionTask.IsCompletedSuccessfully) return connectionTask;
return ConnectAsync(gatewayAddress, connectionTask, msg, directGatewayMessage: false);
}
// Otherwise, use the buckets to ensure ordering.
var index = GetHashCodeModulo(msg.TargetGrain.GetHashCode(), (uint)grainBuckets.Length);
// Repeated from above, at the declaration of the grainBuckets array:
// Requests are bucketed by GrainID, so that all requests to a grain get routed through the same bucket.
// Each bucket holds a (possibly null) weak reference to a GatewayConnection object. That connection instance is used
// if the WeakReference is non-null, is alive, and points to a live gateway connection. If any of these conditions is
// false, then a new gateway is selected using the gateway manager, and a new connection established if necessary.
WeakReference<ClientOutboundConnection> weakRef = grainBuckets[index];
if (weakRef != null
&& weakRef.TryGetTarget(out var existingConnection)
&& existingConnection.IsValid
&& gatewayManager.IsGatewayAvailable(existingConnection.RemoteSiloAddress))
{
return new ValueTask<Connection>(existingConnection);
}
var addr = gatewayManager.GetLiveGateway();
if (addr == null)
{
RejectMessage(msg, "No gateways available");
LogNoGatewayAvailableForMessage(msg, gatewayManager);
return new ValueTask<Connection>(default(Connection));
}
var gatewayConnection = this.connectionManager.GetConnection(addr);
if (gatewayConnection.IsCompletedSuccessfully)
{
this.UpdateBucket(index, (ClientOutboundConnection)gatewayConnection.Result);
return gatewayConnection;
}
return AddToBucketAsync(index, gatewayConnection, addr);
async ValueTask<Connection> AddToBucketAsync(
uint bucketIndex,
ValueTask<Connection> connectionTask,
SiloAddress gatewayAddress)
{
try
{
var connection = (ClientOutboundConnection)await connectionTask.ConfigureAwait(false);
this.UpdateBucket(bucketIndex, connection);
return connection;
}
catch
{
this.gatewayManager.MarkAsDead(gatewayAddress);
this.UpdateBucket(bucketIndex, null);
throw;
}
}
async ValueTask<Connection> ConnectAsync(
SiloAddress gateway,
ValueTask<Connection> connectionTask,
Message message,
bool directGatewayMessage)
{
Connection result = default;
try
{
return result = await connectionTask;
}
catch (Exception exception) when (directGatewayMessage)
{
RejectMessage(message, $"Target silo {message.TargetSilo} is unavailable", exception);
return null;
}
finally
{
if (result is null) this.gatewayManager.MarkAsDead(gateway);
}
}
static uint GetHashCodeModulo(int key, uint umod)
{
int mod = (int)umod;
key = ((key % mod) + mod) % mod; // key should be positive now. So assert with checked.
return checked((uint)key);
}
}
private void UpdateBucket(uint index, ClientOutboundConnection connection)
{
lock (this.grainBucketUpdateLock)
{
var value = this.grainBuckets[index] ?? new WeakReference<ClientOutboundConnection>(connection);
value.SetTarget(connection);
this.grainBuckets[index] = value;
}
}
public void RegisterLocalMessageHandler(Action<Message> handler)
{
this.messageHandler = handler;
}
public void RejectMessage(Message msg, string reason, Exception exc = null)
{
if (!Running) return;
if (msg.Direction != Message.Directions.Request)
{
LogDroppingMessage(msg, reason);
msg.ReleaseDropped("DroppedNonRequest");
}
else
{
LogRejectingMessage(msg, reason);
MessagingInstruments.OnRejectedMessage(msg);
var error = this.messageFactory.CreateRejectionResponse(msg, Message.RejectionTypes.Unrecoverable, reason, exc);
DispatchLocalMessage(error);
msg.ReleaseDropped("RejectedRequest");
}
}
internal void OnGatewayConnectionOpen()
{
int newCount = Interlocked.Increment(ref numberOfConnectedGateways);
this.connectionStatusListener.NotifyGatewayCountChanged(newCount, newCount - 1);
}
internal void OnGatewayConnectionClosed()
{
var gatewayCount = Interlocked.Decrement(ref numberOfConnectedGateways);
if (gatewayCount == 0)
{
this.connectionStatusListener.NotifyClusterConnectionLost();
}
this.connectionStatusListener.NotifyGatewayCountChanged(gatewayCount, gatewayCount + 1);
}
public void Dispose()
{
gatewayManager.Dispose();
}
[LoggerMessage(
EventId = (int)ErrorCode.ProxyClient_MsgCtrNotRunning,
Level = LogLevel.Error,
Message = "Ignoring {Message} because the client message center is not running."
)]
private partial void LogNotRunning(Message message);
[LoggerMessage(
EventId = (int)ErrorCode.ProxyClient_QueueRequest,
Level = LogLevel.Trace,
Message = "Sending message {Message} via gateway '{Gateway}'."
)]
private partial void LogSendingMessage(Message message, EndPoint gateway);
[LoggerMessage(
Level = LogLevel.Trace,
Message = "Client message center started."
)]
private partial void LogClientMessageCenterStarted();
[LoggerMessage(
EventId = (int)ErrorCode.ProxyClient_CannotSend,
Level = LogLevel.Warning,
Message = "Unable to send message {Message}; Gateway manager state is {GatewayManager}."
)]
private partial void LogSendFailed(Message message, GatewayManager gatewayManager);
[LoggerMessage(
EventId = (int)ErrorCode.ProxyClient_CannotSend_NoGateway,
Level = LogLevel.Warning,
Message = "No gateway available to receive message {Message}; Gateway manager state is {GatewayManager}."
)]
private partial void LogNoGatewayAvailableForMessage(Message message, GatewayManager gatewayManager);
[LoggerMessage(
EventId = (int)ErrorCode.ProxyClient_DroppingMsg,
Level = LogLevel.Debug,
Message = "Dropping message: {Message}. Reason = {Reason}"
)]
private partial void LogDroppingMessage(Message message, string reason);
[LoggerMessage(
EventId = (int)ErrorCode.ProxyClient_RejectingMsg,
Level = LogLevel.Debug,
Message = "Rejecting message: {Message}. Reason = {Reason}"
)]
private partial void LogRejectingMessage(Message message, string reason);
}
}