-
Notifications
You must be signed in to change notification settings - Fork 9.8k
/
RedisHubLifetimeManager.cs
891 lines (765 loc) · 33.7 KB
/
RedisHubLifetimeManager.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
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
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Buffers;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.SignalR.Internal;
using Microsoft.AspNetCore.SignalR.Protocol;
using Microsoft.AspNetCore.SignalR.StackExchangeRedis.Internal;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using StackExchange.Redis;
namespace Microsoft.AspNetCore.SignalR.StackExchangeRedis;
/// <summary>
/// The Redis scaleout provider for multi-server support.
/// </summary>
/// <typeparam name="THub">The type of <see cref="Hub"/> to manage connections for.</typeparam>
public class RedisHubLifetimeManager<THub> : HubLifetimeManager<THub>, IDisposable where THub : Hub
{
private readonly HubConnectionStore _connections = new HubConnectionStore();
private readonly RedisSubscriptionManager _groups = new RedisSubscriptionManager();
private readonly RedisSubscriptionManager _users = new RedisSubscriptionManager();
private IConnectionMultiplexer? _redisServerConnection;
private ISubscriber? _bus;
private readonly ILogger _logger;
private readonly RedisOptions _options;
private readonly RedisChannels _channels;
private readonly string _serverName = GenerateServerName();
private readonly RedisProtocol _protocol;
private readonly SemaphoreSlim _connectionLock = new SemaphoreSlim(1);
private readonly IHubProtocolResolver _hubProtocolResolver;
private readonly ClientResultsManager _clientResultsManager = new();
private bool _redisConnectErrorLogged;
private readonly AckHandler _ackHandler;
private int _internalAckId;
/// <summary>
/// Constructs the <see cref="RedisHubLifetimeManager{THub}"/> with types from Dependency Injection.
/// </summary>
/// <param name="logger">The logger to write information about what the class is doing.</param>
/// <param name="options">The <see cref="RedisOptions"/> that influence behavior of the Redis connection.</param>
/// <param name="hubProtocolResolver">The <see cref="IHubProtocolResolver"/> to get an <see cref="IHubProtocol"/> instance when writing to connections.</param>
public RedisHubLifetimeManager(ILogger<RedisHubLifetimeManager<THub>> logger,
IOptions<RedisOptions> options,
IHubProtocolResolver hubProtocolResolver)
: this(logger, options, hubProtocolResolver, globalHubOptions: null, hubOptions: null)
{
}
/// <summary>
/// Constructs the <see cref="RedisHubLifetimeManager{THub}"/> with types from Dependency Injection.
/// </summary>
/// <param name="logger">The logger to write information about what the class is doing.</param>
/// <param name="options">The <see cref="RedisOptions"/> that influence behavior of the Redis connection.</param>
/// <param name="hubProtocolResolver">The <see cref="IHubProtocolResolver"/> to get an <see cref="IHubProtocol"/> instance when writing to connections.</param>
/// <param name="globalHubOptions">The global <see cref="HubOptions"/>.</param>
/// <param name="hubOptions">The <typeparamref name="THub"/> specific options.</param>
public RedisHubLifetimeManager(ILogger<RedisHubLifetimeManager<THub>> logger,
IOptions<RedisOptions> options,
IHubProtocolResolver hubProtocolResolver,
IOptions<HubOptions>? globalHubOptions,
IOptions<HubOptions<THub>>? hubOptions)
{
_hubProtocolResolver = hubProtocolResolver;
_logger = logger;
_options = options.Value;
_ackHandler = new AckHandler();
_channels = new RedisChannels(typeof(THub).FullName!, _serverName);
if (globalHubOptions != null && hubOptions != null)
{
_protocol = new RedisProtocol(new DefaultHubMessageSerializer(hubProtocolResolver, globalHubOptions.Value.SupportedProtocols, hubOptions.Value.SupportedProtocols));
}
else
{
var supportedProtocols = hubProtocolResolver.AllProtocols.Select(p => p.Name).ToList();
_protocol = new RedisProtocol(new DefaultHubMessageSerializer(hubProtocolResolver, supportedProtocols, null));
}
RedisLog.ConnectingToEndpoints(_logger, options.Value.Configuration.EndPoints, _serverName);
_ = EnsureRedisServerConnection();
}
/// <inheritdoc />
public override async Task OnConnectedAsync(HubConnectionContext connection)
{
await EnsureRedisServerConnection();
var feature = new RedisFeature();
connection.Features.Set<IRedisFeature>(feature);
var userTask = Task.CompletedTask;
_connections.Add(connection);
var connectionTask = SubscribeToConnection(connection);
if (!string.IsNullOrEmpty(connection.UserIdentifier))
{
userTask = SubscribeToUser(connection);
}
await Task.WhenAll(connectionTask, userTask);
}
/// <inheritdoc />
public override Task OnDisconnectedAsync(HubConnectionContext connection)
{
_connections.Remove(connection);
// If the bus is null then the Redis connection failed to be established and none of the other connection setup ran
if (_bus is null)
{
return Task.CompletedTask;
}
var connectionChannel = _channels.Connection(connection.ConnectionId);
var tasks = new List<Task>();
RedisLog.Unsubscribe(_logger, connectionChannel);
tasks.Add(_bus.UnsubscribeAsync(connectionChannel));
var feature = connection.Features.GetRequiredFeature<IRedisFeature>();
var groupNames = feature.Groups;
if (groupNames != null)
{
// Copy the groups to an array here because they get removed from this collection
// in RemoveFromGroupAsync
foreach (var group in groupNames.ToArray())
{
// Use RemoveGroupAsyncCore because the connection is local and we don't want to
// accidentally go to other servers with our remove request.
tasks.Add(RemoveGroupAsyncCore(connection, group));
}
}
if (!string.IsNullOrEmpty(connection.UserIdentifier))
{
tasks.Add(RemoveUserAsync(connection));
}
return Task.WhenAll(tasks);
}
/// <inheritdoc />
public override Task SendAllAsync(string methodName, object?[] args, CancellationToken cancellationToken = default)
{
var message = _protocol.WriteInvocation(methodName, args);
return PublishAsync(_channels.All, message);
}
/// <inheritdoc />
public override Task SendAllExceptAsync(string methodName, object?[] args, IReadOnlyList<string> excludedConnectionIds, CancellationToken cancellationToken = default)
{
var message = _protocol.WriteInvocation(methodName, args, excludedConnectionIds: excludedConnectionIds);
return PublishAsync(_channels.All, message);
}
/// <inheritdoc />
public override Task SendConnectionAsync(string connectionId, string methodName, object?[] args, CancellationToken cancellationToken = default)
{
if (connectionId == null)
{
throw new ArgumentNullException(nameof(connectionId));
}
// If the connection is local we can skip sending the message through the bus since we require sticky connections.
// This also saves serializing and deserializing the message!
var connection = _connections[connectionId];
if (connection != null)
{
return connection.WriteAsync(new InvocationMessage(methodName, args), cancellationToken).AsTask();
}
var message = _protocol.WriteInvocation(methodName, args);
return PublishAsync(_channels.Connection(connectionId), message);
}
/// <inheritdoc />
public override Task SendGroupAsync(string groupName, string methodName, object?[] args, CancellationToken cancellationToken = default)
{
if (groupName == null)
{
throw new ArgumentNullException(nameof(groupName));
}
var message = _protocol.WriteInvocation(methodName, args);
return PublishAsync(_channels.Group(groupName), message);
}
/// <inheritdoc />
public override Task SendGroupExceptAsync(string groupName, string methodName, object?[] args, IReadOnlyList<string> excludedConnectionIds, CancellationToken cancellationToken = default)
{
if (groupName == null)
{
throw new ArgumentNullException(nameof(groupName));
}
var message = _protocol.WriteInvocation(methodName, args, excludedConnectionIds: excludedConnectionIds);
return PublishAsync(_channels.Group(groupName), message);
}
/// <inheritdoc />
public override Task SendUserAsync(string userId, string methodName, object?[] args, CancellationToken cancellationToken = default)
{
var message = _protocol.WriteInvocation(methodName, args);
return PublishAsync(_channels.User(userId), message);
}
/// <inheritdoc />
public override Task AddToGroupAsync(string connectionId, string groupName, CancellationToken cancellationToken = default)
{
if (connectionId == null)
{
throw new ArgumentNullException(nameof(connectionId));
}
if (groupName == null)
{
throw new ArgumentNullException(nameof(groupName));
}
var connection = _connections[connectionId];
if (connection != null)
{
// short circuit if connection is on this server
return AddGroupAsyncCore(connection, groupName);
}
return SendGroupActionAndWaitForAck(connectionId, groupName, GroupAction.Add);
}
/// <inheritdoc />
public override Task RemoveFromGroupAsync(string connectionId, string groupName, CancellationToken cancellationToken = default)
{
if (connectionId == null)
{
throw new ArgumentNullException(nameof(connectionId));
}
if (groupName == null)
{
throw new ArgumentNullException(nameof(groupName));
}
var connection = _connections[connectionId];
if (connection != null)
{
// short circuit if connection is on this server
return RemoveGroupAsyncCore(connection, groupName);
}
return SendGroupActionAndWaitForAck(connectionId, groupName, GroupAction.Remove);
}
/// <inheritdoc />
public override Task SendConnectionsAsync(IReadOnlyList<string> connectionIds, string methodName, object?[] args, CancellationToken cancellationToken = default)
{
if (connectionIds == null)
{
throw new ArgumentNullException(nameof(connectionIds));
}
var publishTasks = new List<Task>(connectionIds.Count);
var payload = _protocol.WriteInvocation(methodName, args);
foreach (var connectionId in connectionIds)
{
publishTasks.Add(PublishAsync(_channels.Connection(connectionId), payload));
}
return Task.WhenAll(publishTasks);
}
/// <inheritdoc />
public override Task SendGroupsAsync(IReadOnlyList<string> groupNames, string methodName, object?[] args, CancellationToken cancellationToken = default)
{
if (groupNames == null)
{
throw new ArgumentNullException(nameof(groupNames));
}
var publishTasks = new List<Task>(groupNames.Count);
var payload = _protocol.WriteInvocation(methodName, args);
foreach (var groupName in groupNames)
{
if (!string.IsNullOrEmpty(groupName))
{
publishTasks.Add(PublishAsync(_channels.Group(groupName), payload));
}
}
return Task.WhenAll(publishTasks);
}
/// <inheritdoc />
public override Task SendUsersAsync(IReadOnlyList<string> userIds, string methodName, object?[] args, CancellationToken cancellationToken = default)
{
if (userIds.Count > 0)
{
var payload = _protocol.WriteInvocation(methodName, args);
var publishTasks = new List<Task>(userIds.Count);
foreach (var userId in userIds)
{
if (!string.IsNullOrEmpty(userId))
{
publishTasks.Add(PublishAsync(_channels.User(userId), payload));
}
}
return Task.WhenAll(publishTasks);
}
return Task.CompletedTask;
}
private async Task<long> PublishAsync(string channel, byte[] payload)
{
await EnsureRedisServerConnection();
RedisLog.PublishToChannel(_logger, channel);
return await _bus!.PublishAsync(channel, payload);
}
private Task AddGroupAsyncCore(HubConnectionContext connection, string groupName)
{
var feature = connection.Features.GetRequiredFeature<IRedisFeature>();
var groupNames = feature.Groups;
lock (groupNames)
{
// Connection already in group
if (!groupNames.Add(groupName))
{
return Task.CompletedTask;
}
}
var groupChannel = _channels.Group(groupName);
return _groups.AddSubscriptionAsync(groupChannel, connection, SubscribeToGroupAsync);
}
/// <summary>
/// This takes <see cref="HubConnectionContext"/> because we want to remove the connection from the
/// _connections list in OnDisconnectedAsync and still be able to remove groups with this method.
/// </summary>
private async Task RemoveGroupAsyncCore(HubConnectionContext connection, string groupName)
{
var groupChannel = _channels.Group(groupName);
await _groups.RemoveSubscriptionAsync(groupChannel, connection, this, static (state, channelName) =>
{
var lifetimeManager = (RedisHubLifetimeManager<THub>)state;
RedisLog.Unsubscribe(lifetimeManager._logger, channelName);
return lifetimeManager._bus!.UnsubscribeAsync(channelName);
});
var feature = connection.Features.GetRequiredFeature<IRedisFeature>();
var groupNames = feature.Groups;
if (groupNames != null)
{
lock (groupNames)
{
groupNames.Remove(groupName);
}
}
}
private async Task SendGroupActionAndWaitForAck(string connectionId, string groupName, GroupAction action)
{
var id = Interlocked.Increment(ref _internalAckId);
var ack = _ackHandler.CreateAck(id);
// Send Add/Remove Group to other servers and wait for an ack or timeout
var message = RedisProtocol.WriteGroupCommand(new RedisGroupCommand(id, _serverName, action, groupName, connectionId));
await PublishAsync(_channels.GroupManagement, message);
await ack;
}
private Task RemoveUserAsync(HubConnectionContext connection)
{
var userChannel = _channels.User(connection.UserIdentifier!);
return _users.RemoveSubscriptionAsync(userChannel, connection, this, static (state, channelName) =>
{
var lifetimeManager = (RedisHubLifetimeManager<THub>)state;
RedisLog.Unsubscribe(lifetimeManager._logger, channelName);
return lifetimeManager._bus!.UnsubscribeAsync(channelName);
});
}
/// <summary>
/// Cleans up the Redis connection.
/// </summary>
public void Dispose()
{
_bus?.UnsubscribeAll();
_redisServerConnection?.Dispose();
_ackHandler.Dispose();
}
/// <inheritdoc/>
public override async Task<T> InvokeConnectionAsync<T>(string connectionId, string methodName, object?[] args, CancellationToken cancellationToken)
{
// send thing
if (connectionId == null)
{
throw new ArgumentNullException(nameof(connectionId));
}
var connection = _connections[connectionId];
// ID needs to be unique for each invocation and across servers, we generate a GUID every time, that should provide enough uniqueness guarantees.
var invocationId = GenerateInvocationId();
using var _ = CancellationTokenUtils.CreateLinkedToken(cancellationToken,
connection?.ConnectionAborted ?? default, out var linkedToken);
var task = _clientResultsManager.AddInvocation<T>(connectionId, invocationId, linkedToken);
try
{
if (connection == null)
{
// TODO: Need to handle other server going away while waiting for connection result
var messageBytes = _protocol.WriteInvocation(methodName, args, invocationId, returnChannel: _channels.ReturnResults);
var received = await PublishAsync(_channels.Connection(connectionId), messageBytes);
if (received < 1)
{
throw new IOException($"Connection '{connectionId}' does not exist.");
}
}
else
{
// We're sending to a single connection
// Write message directly to connection without caching it in memory
var message = new InvocationMessage(invocationId, methodName, args);
await connection.WriteAsync(message, cancellationToken);
}
}
catch
{
_clientResultsManager.RemoveInvocation(invocationId);
throw;
}
try
{
return await task;
}
catch
{
// ConnectionAborted will trigger a generic "Canceled" exception from the task, let's convert it into a more specific message.
if (connection?.ConnectionAborted.IsCancellationRequested == true)
{
throw new IOException($"Connection '{connectionId}' disconnected.");
}
throw;
}
}
/// <inheritdoc/>
public override Task SetConnectionResultAsync(string connectionId, CompletionMessage result)
{
_clientResultsManager.TryCompleteResult(connectionId, result);
return Task.CompletedTask;
}
/// <inheritdoc/>
public override bool TryGetReturnType(string invocationId, [NotNullWhen(true)] out Type? type)
{
return _clientResultsManager.TryGetType(invocationId, out type);
}
private async Task SubscribeToAll()
{
RedisLog.Subscribing(_logger, _channels.All);
var channel = await _bus!.SubscribeAsync(_channels.All);
channel.OnMessage(async channelMessage =>
{
try
{
RedisLog.ReceivedFromChannel(_logger, _channels.All);
var invocation = RedisProtocol.ReadInvocation((byte[])channelMessage.Message);
var tasks = new List<Task>(_connections.Count);
foreach (var connection in _connections)
{
if (invocation.ExcludedConnectionIds == null || !invocation.ExcludedConnectionIds.Contains(connection.ConnectionId))
{
tasks.Add(connection.WriteAsync(invocation.Message).AsTask());
}
}
await Task.WhenAll(tasks);
}
catch (Exception ex)
{
RedisLog.FailedWritingMessage(_logger, ex);
}
});
}
private async Task SubscribeToGroupManagementChannel()
{
var channel = await _bus!.SubscribeAsync(_channels.GroupManagement);
channel.OnMessage(async channelMessage =>
{
try
{
var groupMessage = RedisProtocol.ReadGroupCommand((byte[])channelMessage.Message);
var connection = _connections[groupMessage.ConnectionId];
if (connection == null)
{
// user not on this server
return;
}
if (groupMessage.Action == GroupAction.Remove)
{
await RemoveGroupAsyncCore(connection, groupMessage.GroupName);
}
if (groupMessage.Action == GroupAction.Add)
{
await AddGroupAsyncCore(connection, groupMessage.GroupName);
}
// Send an ack to the server that sent the original command.
await PublishAsync(_channels.Ack(groupMessage.ServerName), RedisProtocol.WriteAck(groupMessage.Id));
}
catch (Exception ex)
{
RedisLog.InternalMessageFailed(_logger, ex);
}
});
}
private async Task SubscribeToAckChannel()
{
// Create server specific channel in order to send an ack to a single server
var channel = await _bus!.SubscribeAsync(_channels.Ack(_serverName));
channel.OnMessage(channelMessage =>
{
var ackId = RedisProtocol.ReadAck((byte[])channelMessage.Message);
_ackHandler.TriggerAck(ackId);
});
}
private async Task SubscribeToConnection(HubConnectionContext connection)
{
var connectionChannel = _channels.Connection(connection.ConnectionId);
RedisLog.Subscribing(_logger, connectionChannel);
var channel = await _bus!.SubscribeAsync(connectionChannel);
channel.OnMessage(channelMessage =>
{
var invocation = RedisProtocol.ReadInvocation((byte[])channelMessage.Message);
// This is a Client result we need to setup state for the completion and forward the message to the client
if (!string.IsNullOrEmpty(invocation.InvocationId))
{
CancellationTokenRegistration? tokenRegistration = null;
_clientResultsManager.AddInvocation(invocation.InvocationId,
(typeof(RawResult), connection.ConnectionId, null!, async (_, completionMessage) =>
{
var protocolName = connection.Protocol.Name;
tokenRegistration?.Dispose();
var memoryBufferWriter = AspNetCore.Internal.MemoryBufferWriter.Get();
byte[] message;
try
{
try
{
connection.Protocol.WriteMessage(completionMessage, memoryBufferWriter);
message = RedisProtocol.WriteCompletionMessage(memoryBufferWriter, protocolName);
}
finally
{
memoryBufferWriter.Dispose();
}
await PublishAsync(invocation.ReturnChannel!, message);
}
catch (Exception ex)
{
RedisLog.ErrorForwardingResult(_logger, completionMessage.InvocationId, ex);
}
}));
// TODO: this isn't great
tokenRegistration = connection.ConnectionAborted.UnsafeRegister(_ =>
{
var invocationInfo = _clientResultsManager.RemoveInvocation(invocation.InvocationId);
invocationInfo?.Completion(null!, CompletionMessage.WithError(invocation.InvocationId, "Connection disconnected."));
}, null);
}
// Forward message from other server to client
// Normal client method invokes and client result invokes use the same message
return connection.WriteAsync(invocation.Message).AsTask();
});
}
private Task SubscribeToUser(HubConnectionContext connection)
{
var userChannel = _channels.User(connection.UserIdentifier!);
return _users.AddSubscriptionAsync(userChannel, connection, async (channelName, subscriptions) =>
{
RedisLog.Subscribing(_logger, channelName);
var channel = await _bus!.SubscribeAsync(channelName);
channel.OnMessage(async channelMessage =>
{
try
{
var invocation = RedisProtocol.ReadInvocation((byte[])channelMessage.Message);
var tasks = new List<Task>(subscriptions.Count);
foreach (var userConnection in subscriptions)
{
tasks.Add(userConnection.WriteAsync(invocation.Message).AsTask());
}
await Task.WhenAll(tasks);
}
catch (Exception ex)
{
RedisLog.FailedWritingMessage(_logger, ex);
}
});
});
}
private async Task SubscribeToGroupAsync(string groupChannel, HubConnectionStore groupConnections)
{
RedisLog.Subscribing(_logger, groupChannel);
var channel = await _bus!.SubscribeAsync(groupChannel);
channel.OnMessage(async (channelMessage) =>
{
try
{
var invocation = RedisProtocol.ReadInvocation((byte[])channelMessage.Message);
var tasks = new List<Task>(groupConnections.Count);
foreach (var groupConnection in groupConnections)
{
if (invocation.ExcludedConnectionIds?.Contains(groupConnection.ConnectionId) == true)
{
continue;
}
tasks.Add(groupConnection.WriteAsync(invocation.Message).AsTask());
}
await Task.WhenAll(tasks);
}
catch (Exception ex)
{
RedisLog.FailedWritingMessage(_logger, ex);
}
});
}
private async Task SubscribeToReturnResultsAsync()
{
var channel = await _bus!.SubscribeAsync(_channels.ReturnResults);
channel.OnMessage((channelMessage) =>
{
var completion = RedisProtocol.ReadCompletion(channelMessage.Message);
IHubProtocol? protocol = null;
foreach (var hubProtocol in _hubProtocolResolver.AllProtocols)
{
if (hubProtocol.Name.Equals(completion.ProtocolName))
{
protocol = hubProtocol;
break;
}
}
// Should only happen if you have different versions of servers and don't have the same protocols registered on both
if (protocol is null)
{
RedisLog.MismatchedServers(_logger, completion.ProtocolName);
return;
}
var ros = completion.CompletionMessage;
HubMessage? hubMessage = null;
bool retryForError = false;
try
{
var parseSuccess = protocol.TryParseMessage(ref ros, _clientResultsManager, out hubMessage);
retryForError = !parseSuccess;
}
catch
{
// Client returned wrong type? Or just an error from the HubProtocol, let's try with RawResult as the type and see if that works
retryForError = true;
}
if (retryForError)
{
try
{
ros = completion.CompletionMessage;
// if this works then we know there was an error with the type the client returned, we'll replace the CompletionMessage below and provide an error to the application code
if (!protocol.TryParseMessage(ref ros, FakeInvocationBinder.Instance, out hubMessage))
{
RedisLog.ErrorParsingResult(_logger, completion.ProtocolName, null);
return;
}
}
// Exceptions here would mean the HubProtocol implementation very likely has a bug, the other server has already deserialized the message (with RawResult) so it should be deserializable
// We don't know the InvocationId, we should let the application developer know and potentially surface the issue to the HubProtocol implementor
catch (Exception ex)
{
RedisLog.ErrorParsingResult(_logger, completion.ProtocolName, ex);
return;
}
}
var invocationInfo = _clientResultsManager.RemoveInvocation(((CompletionMessage)hubMessage!).InvocationId!);
if (retryForError && invocationInfo is not null)
{
hubMessage = CompletionMessage.WithError(((CompletionMessage)hubMessage!).InvocationId!, $"Client result wasn't deserializable to {invocationInfo?.Type.Name}.");
}
invocationInfo?.Completion(invocationInfo?.Tcs!, (CompletionMessage)hubMessage!);
});
}
private class FakeInvocationBinder : IInvocationBinder
{
public static readonly FakeInvocationBinder Instance = new FakeInvocationBinder();
private FakeInvocationBinder() { }
public IReadOnlyList<Type> GetParameterTypes(string methodName)
{
throw new NotImplementedException();
}
public Type GetReturnType(string invocationId)
{
return typeof(RawResult);
}
public Type GetStreamItemType(string streamId)
{
throw new NotImplementedException();
}
}
private async Task EnsureRedisServerConnection()
{
if (_redisServerConnection == null)
{
await _connectionLock.WaitAsync();
try
{
if (_redisServerConnection == null)
{
var writer = new LoggerTextWriter(_logger);
try
{
_redisServerConnection = await _options.ConnectAsync(writer);
}
catch (Exception ex)
{
// If the connection hasn't been established yet we shouldn't keep logging the same error over and over
// for every new client connection.
if (!_redisConnectErrorLogged)
{
RedisLog.ErrorConnecting(_logger, ex);
_redisConnectErrorLogged = true;
}
throw;
}
_bus = _redisServerConnection.GetSubscriber();
_redisServerConnection.ConnectionRestored += (_, e) =>
{
// We use the subscription connection type
// Ignore messages from the interactive connection (avoids duplicates)
if (e.ConnectionType == ConnectionType.Interactive)
{
return;
}
RedisLog.ConnectionRestored(_logger);
};
_redisServerConnection.ConnectionFailed += (_, e) =>
{
// We use the subscription connection type
// Ignore messages from the interactive connection (avoids duplicates)
if (e.ConnectionType == ConnectionType.Interactive)
{
return;
}
RedisLog.ConnectionFailed(_logger, e.Exception);
};
if (_redisServerConnection.IsConnected)
{
RedisLog.Connected(_logger);
}
else
{
RedisLog.NotConnected(_logger);
}
await SubscribeToAll();
await SubscribeToGroupManagementChannel();
await SubscribeToAckChannel();
await SubscribeToReturnResultsAsync();
}
}
finally
{
_connectionLock.Release();
}
}
}
private static string GenerateServerName()
{
// Use the machine name for convenient diagnostics, but add a guid to make it unique.
// Example: MyServerName_02db60e5fab243b890a847fa5c4dcb29
return $"{Environment.MachineName}_{Guid.NewGuid():N}";
}
private static string GenerateInvocationId()
{
Span<byte> buffer = stackalloc byte[16];
var success = Guid.NewGuid().TryWriteBytes(buffer);
Debug.Assert(success);
// 16 * 4/3 = 21.333 which means base64 encoding will use 22 characters of actual data and 2 characters of padding ('=')
Span<char> base64 = stackalloc char[24];
success = Convert.TryToBase64Chars(buffer, base64, out var written);
Debug.Assert(success);
Debug.Assert(written == 24);
// Trim the two '=='
Debug.Assert(base64.EndsWith("=="));
return new string(base64[..^2]);
}
private sealed class LoggerTextWriter : TextWriter
{
private readonly ILogger _logger;
public LoggerTextWriter(ILogger logger)
{
_logger = logger;
}
public override Encoding Encoding => Encoding.UTF8;
public override void Write(char value)
{
}
public override void WriteLine(string? value)
{
RedisLog.ConnectionMultiplexerMessage(_logger, value);
}
}
private interface IRedisFeature
{
HashSet<string> Groups { get; }
}
private sealed class RedisFeature : IRedisFeature
{
public HashSet<string> Groups { get; } = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
}
}