-
Notifications
You must be signed in to change notification settings - Fork 9.8k
/
HubConnection.cs
2027 lines (1743 loc) · 86.2 KB
/
HubConnection.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
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Connections;
using Microsoft.AspNetCore.Connections.Features;
using Microsoft.AspNetCore.Internal;
using Microsoft.AspNetCore.SignalR.Client.Internal;
using Microsoft.AspNetCore.SignalR.Internal;
using Microsoft.AspNetCore.SignalR.Protocol;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
namespace Microsoft.AspNetCore.SignalR.Client
{
/// <summary>
/// A connection used to invoke hub methods on a SignalR Server.
/// </summary>
/// <remarks>
/// A <see cref="HubConnection"/> should be created using <see cref="HubConnectionBuilder"/>.
/// Before hub methods can be invoked the connection must be started using <see cref="StartAsync"/>.
/// Clean up a connection using <see cref="StopAsync"/> or <see cref="DisposeAsync"/>.
/// </remarks>
public partial class HubConnection : IAsyncDisposable
{
/// <summary>
/// The default timeout which specifies how long to wait for a message before closing the connection. Default is 30 seconds.
/// </summary>
public static readonly TimeSpan DefaultServerTimeout = TimeSpan.FromSeconds(30); // Server ping rate is 15 sec, this is 2 times that.
/// <summary>
/// The default timeout which specifies how long to wait for the handshake to respond before closing the connection. Default is 15 seconds.
/// </summary>
public static readonly TimeSpan DefaultHandshakeTimeout = TimeSpan.FromSeconds(15);
/// <summary>
/// The default interval that the client will send keep alive messages to let the server know to not close the connection. Default is 15 second interval.
/// </summary>
public static readonly TimeSpan DefaultKeepAliveInterval = TimeSpan.FromSeconds(15);
// The receive loop has a single reader and single writer at a time so optimize the channel for that
private static readonly UnboundedChannelOptions _receiveLoopOptions = new UnboundedChannelOptions
{
SingleReader = true,
SingleWriter = true
};
private static readonly MethodInfo _sendStreamItemsMethod = typeof(HubConnection).GetMethods(BindingFlags.NonPublic | BindingFlags.Instance).Single(m => m.Name.Equals(nameof(SendStreamItems)));
private static readonly MethodInfo _sendIAsyncStreamItemsMethod = typeof(HubConnection).GetMethods(BindingFlags.NonPublic | BindingFlags.Instance).Single(m => m.Name.Equals(nameof(SendIAsyncEnumerableStreamItems)));
// Persistent across all connections
private readonly ILoggerFactory _loggerFactory;
private readonly ILogger _logger;
private readonly ConnectionLogScope _logScope;
private readonly IHubProtocol _protocol;
private readonly IServiceProvider _serviceProvider;
private readonly IConnectionFactory _connectionFactory;
private readonly IRetryPolicy? _reconnectPolicy;
private readonly EndPoint _endPoint;
private readonly ConcurrentDictionary<string, InvocationHandlerList> _handlers = new ConcurrentDictionary<string, InvocationHandlerList>(StringComparer.Ordinal);
// Holds all mutable state other than user-defined handlers and settable properties.
private readonly ReconnectingConnectionState _state;
private bool _disposed;
/// <summary>
/// Occurs when the connection is closed. The connection could be closed due to an error or due to either the server or client intentionally
/// closing the connection without error.
/// </summary>
/// <remarks>
/// If this event was triggered from a connection error, the <see cref="Exception"/> that occurred will be passed in as the
/// sole argument to this handler. If this event was triggered intentionally by either the client or server, then
/// the argument will be <see langword="null"/>.
/// </remarks>
/// <example>
/// The following example attaches a handler to the <see cref="Closed"/> event, and checks the provided argument to determine
/// if there was an error:
///
/// <code>
/// connection.Closed += (exception) =>
/// {
/// if (exception == null)
/// {
/// Console.WriteLine("Connection closed without error.");
/// }
/// else
/// {
/// Console.WriteLine($"Connection closed due to an error: {exception}");
/// }
/// };
/// </code>
/// </example>
public event Func<Exception?, Task>? Closed;
/// <summary>
/// Occurs when the <see cref="HubConnection"/> starts reconnecting after losing its underlying connection.
/// </summary>
/// <remarks>
/// The <see cref="Exception"/> that occurred will be passed in as the sole argument to this handler.
/// </remarks>
/// <example>
/// The following example attaches a handler to the <see cref="Reconnecting"/> event, and checks the provided argument to log the error.
///
/// <code>
/// connection.Reconnecting += (exception) =>
/// {
/// Console.WriteLine($"Connection started reconnecting due to an error: {exception}");
/// };
/// </code>
/// </example>
public event Func<Exception?, Task>? Reconnecting;
/// <summary>
/// Occurs when the <see cref="HubConnection"/> successfully reconnects after losing its underlying connection.
/// </summary>
/// <remarks>
/// The <see cref="string"/> parameter will be the <see cref="HubConnection"/>'s new ConnectionId or null if negotiation was skipped.
/// </remarks>
/// <example>
/// The following example attaches a handler to the <see cref="Reconnected"/> event, and checks the provided argument to log the ConnectionId.
///
/// <code>
/// connection.Reconnected += (connectionId) =>
/// {
/// Console.WriteLine($"Connection successfully reconnected. The ConnectionId is now: {connectionId}");
/// };
/// </code>
/// </example>
public event Func<string?, Task>? Reconnected;
// internal for testing purposes
internal TimeSpan TickRate { get; set; } = TimeSpan.FromSeconds(1);
/// <summary>
/// Gets or sets the server timeout interval for the connection.
/// </summary>
/// <remarks>
/// The client times out if it hasn't heard from the server for `this` long.
/// </remarks>
public TimeSpan ServerTimeout { get; set; } = DefaultServerTimeout;
/// <summary>
/// Gets or sets the interval at which the client sends ping messages.
/// </summary>
/// <remarks>
/// Sending any message resets the timer to the start of the interval.
/// </remarks>
public TimeSpan KeepAliveInterval { get; set; } = DefaultKeepAliveInterval;
/// <summary>
/// Gets or sets the timeout for the initial handshake.
/// </summary>
public TimeSpan HandshakeTimeout { get; set; } = DefaultHandshakeTimeout;
/// <summary>
/// Gets the connection's current Id. This value will be cleared when the connection is stopped and will have a new value every time the connection is (re)established.
/// This value will be null if the negotiation step is skipped via HttpConnectionOptions or if the WebSockets transport is explicitly specified because the
/// client skips negotiation in that case as well.
/// </summary>
public string? ConnectionId => _state.CurrentConnectionStateUnsynchronized?.Connection.ConnectionId;
/// <summary>
/// Indicates the state of the <see cref="HubConnection"/> to the server.
/// </summary>
public HubConnectionState State => _state.OverallState;
/// <summary>
/// Initializes a new instance of the <see cref="HubConnection"/> class.
/// </summary>
/// <param name="connectionFactory">The <see cref="IConnectionFactory" /> used to create a connection each time <see cref="StartAsync" /> is called.</param>
/// <param name="protocol">The <see cref="IHubProtocol" /> used by the connection.</param>
/// <param name="endPoint">The <see cref="EndPoint"/> to connect to.</param>
/// <param name="serviceProvider">An <see cref="IServiceProvider"/> containing the services provided to this <see cref="HubConnection"/> instance.</param>
/// <param name="loggerFactory">The logger factory.</param>
/// <param name="reconnectPolicy">
/// The <see cref="IRetryPolicy"/> that controls the timing and number of reconnect attempts.
/// The <see cref="HubConnection"/> will not reconnect if the <paramref name="reconnectPolicy"/> is null.
/// </param>
/// <remarks>
/// The <see cref="IServiceProvider"/> used to initialize the connection will be disposed when the connection is disposed.
/// </remarks>
public HubConnection(IConnectionFactory connectionFactory, IHubProtocol protocol, EndPoint endPoint, IServiceProvider serviceProvider, ILoggerFactory loggerFactory, IRetryPolicy reconnectPolicy)
: this(connectionFactory, protocol, endPoint, serviceProvider, loggerFactory)
{
_reconnectPolicy = reconnectPolicy;
}
/// <summary>
/// Initializes a new instance of the <see cref="HubConnection"/> class.
/// </summary>
/// <param name="connectionFactory">The <see cref="IConnectionFactory" /> used to create a connection each time <see cref="StartAsync" /> is called.</param>
/// <param name="protocol">The <see cref="IHubProtocol" /> used by the connection.</param>
/// <param name="endPoint">The <see cref="EndPoint"/> to connect to.</param>
/// <param name="serviceProvider">An <see cref="IServiceProvider"/> containing the services provided to this <see cref="HubConnection"/> instance.</param>
/// <param name="loggerFactory">The logger factory.</param>
/// <remarks>
/// The <see cref="IServiceProvider"/> used to initialize the connection will be disposed when the connection is disposed.
/// </remarks>
public HubConnection(IConnectionFactory connectionFactory,
IHubProtocol protocol,
EndPoint endPoint,
IServiceProvider serviceProvider,
ILoggerFactory loggerFactory)
{
_connectionFactory = connectionFactory ?? throw new ArgumentNullException(nameof(connectionFactory));
_protocol = protocol ?? throw new ArgumentNullException(nameof(protocol));
_endPoint = endPoint ?? throw new ArgumentNullException(nameof(endPoint));
_serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));
_loggerFactory = loggerFactory ?? NullLoggerFactory.Instance;
_logger = _loggerFactory.CreateLogger<HubConnection>();
_state = new ReconnectingConnectionState(_logger);
_logScope = new ConnectionLogScope();
}
/// <summary>
/// Starts a connection to the server.
/// </summary>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None" />.</param>
/// <returns>A <see cref="Task"/> that represents the asynchronous start.</returns>
public virtual async Task StartAsync(CancellationToken cancellationToken = default)
{
CheckDisposed();
using (_logger.BeginScope(_logScope))
{
await StartAsyncInner(cancellationToken).ForceAsync();
}
}
private async Task StartAsyncInner(CancellationToken cancellationToken = default)
{
await _state.WaitConnectionLockAsync(token: cancellationToken);
try
{
if (!_state.TryChangeState(HubConnectionState.Disconnected, HubConnectionState.Connecting))
{
throw new InvalidOperationException($"The {nameof(HubConnection)} cannot be started if it is not in the {nameof(HubConnectionState.Disconnected)} state.");
}
// The StopCts is canceled at the start of StopAsync should be reset every time the connection finishes stopping.
// If this token is currently canceled, it means that StartAsync was called while StopAsync was still running.
if (_state.StopCts.Token.IsCancellationRequested)
{
throw new InvalidOperationException($"The {nameof(HubConnection)} cannot be started while {nameof(StopAsync)} is running.");
}
using (CreateLinkedToken(cancellationToken, _state.StopCts.Token, out var linkedToken))
{
await StartAsyncCore(linkedToken);
}
_state.ChangeState(HubConnectionState.Connecting, HubConnectionState.Connected);
}
catch
{
if (_state.TryChangeState(HubConnectionState.Connecting, HubConnectionState.Disconnected))
{
_state.StopCts = new CancellationTokenSource();
}
throw;
}
finally
{
_state.ReleaseConnectionLock();
}
}
/// <summary>
/// Stops a connection to the server.
/// </summary>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None" />.</param>
/// <returns>A <see cref="Task"/> that represents the asynchronous stop.</returns>
public virtual async Task StopAsync(CancellationToken cancellationToken = default)
{
CheckDisposed();
using (_logger.BeginScope(_logScope))
{
await StopAsyncCore(disposing: false).ForceAsync();
}
}
// Current plan for IAsyncDisposable is that DisposeAsync will NOT take a CancellationToken
// https://github.com/dotnet/csharplang/blob/195efa07806284d7b57550e7447dc8bd39c156bf/proposals/async-streams.md#iasyncdisposable
/// <summary>
/// Disposes the <see cref="HubConnection"/>.
/// </summary>
/// <returns>A <see cref="ValueTask"/> that represents the asynchronous dispose.</returns>
public virtual async ValueTask DisposeAsync()
{
if (!_disposed)
{
using (_logger.BeginScope(_logScope))
{
await StopAsyncCore(disposing: true).ForceAsync();
}
}
}
// If the registered callback blocks it can cause the client to stop receiving messages. If you need to block, get off the current thread first.
/// <summary>
/// Registers a handler that will be invoked when the hub method with the specified method name is invoked.
/// </summary>
/// <param name="methodName">The name of the hub method to define.</param>
/// <param name="parameterTypes">The parameters types expected by the hub method.</param>
/// <param name="handler">The handler that will be raised when the hub method is invoked.</param>
/// <param name="state">A state object that will be passed to the handler.</param>
/// <returns>A subscription that can be disposed to unsubscribe from the hub method.</returns>
/// <remarks>
/// This is a low level method for registering a handler. Using an <see cref="HubConnectionExtensions"/> <c>On</c> extension method is recommended.
/// </remarks>
public virtual IDisposable On(string methodName, Type[] parameterTypes, Func<object?[], object, Task> handler, object state)
{
Log.RegisteringHandler(_logger, methodName);
CheckDisposed();
// It's OK to be disposed while registering a callback, we'll just never call the callback anyway (as with all the callbacks registered before disposal).
var invocationHandler = new InvocationHandler(parameterTypes, handler, state);
var invocationList = _handlers.AddOrUpdate(methodName, _ => new InvocationHandlerList(invocationHandler),
(_, invocations) =>
{
lock (invocations)
{
invocations.Add(invocationHandler);
}
return invocations;
});
return new Subscription(invocationHandler, invocationList);
}
/// <summary>
/// Removes all handlers associated with the method with the specified method name.
/// </summary>
/// <param name="methodName">The name of the hub method from which handlers are being removed</param>
public virtual void Remove(string methodName)
{
CheckDisposed();
Log.RemovingHandlers(_logger, methodName);
_handlers.TryRemove(methodName, out _);
}
/// <summary>
/// Invokes a streaming hub method on the server using the specified method name, return type and arguments.
/// </summary>
/// <param name="methodName">The name of the server method to invoke.</param>
/// <param name="returnType">The return type of the server method.</param>
/// <param name="args">The arguments used to invoke the server method.</param>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None" />.</param>
/// <returns>
/// A <see cref="Task{TResult}"/> that represents the asynchronous invoke.
/// The <see cref="Task{TResult}.Result"/> property returns a <see cref="ChannelReader{T}"/> for the streamed hub method values.
/// </returns>
/// <remarks>
/// This is a low level method for invoking a streaming hub method on the server. Using an <see cref="HubConnectionExtensions"/> <c>StreamAsChannelAsync</c> extension method is recommended.
/// </remarks>
public virtual async Task<ChannelReader<object?>> StreamAsChannelCoreAsync(string methodName, Type returnType, object?[] args, CancellationToken cancellationToken = default)
{
using (_logger.BeginScope(_logScope))
{
return await StreamAsChannelCoreAsyncCore(methodName, returnType, args, cancellationToken).ForceAsync();
}
}
/// <summary>
/// Invokes a hub method on the server using the specified method name, return type and arguments.
/// </summary>
/// <param name="methodName">The name of the server method to invoke.</param>
/// <param name="returnType">The return type of the server method.</param>
/// <param name="args">The arguments used to invoke the server method.</param>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None" />.</param>
/// <returns>
/// A <see cref="Task{TResult}"/> that represents the asynchronous invoke.
/// The <see cref="Task{TResult}.Result"/> property returns an <see cref="object"/> for the hub method return value.
/// </returns>
/// <remarks>
/// This is a low level method for invoking a hub method on the server. Using an <see cref="HubConnectionExtensions"/> <c>InvokeAsync</c> extension method is recommended.
/// </remarks>
public virtual async Task<object?> InvokeCoreAsync(string methodName, Type returnType, object?[] args, CancellationToken cancellationToken = default)
{
using (_logger.BeginScope(_logScope))
{
return await InvokeCoreAsyncCore(methodName, returnType, args, cancellationToken).ForceAsync();
}
}
/// <summary>
/// Invokes a hub method on the server using the specified method name and arguments.
/// Does not wait for a response from the receiver.
/// </summary>
/// <param name="methodName">The name of the server method to invoke.</param>
/// <param name="args">The arguments used to invoke the server method.</param>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None" />.</param>
/// <returns>A <see cref="Task"/> that represents the asynchronous invoke.</returns>
/// <remarks>
/// This is a low level method for invoking a hub method on the server. Using an <see cref="HubConnectionExtensions"/> <c>SendAsync</c> extension method is recommended.
/// </remarks>
public virtual async Task SendCoreAsync(string methodName, object?[] args, CancellationToken cancellationToken = default)
{
using (_logger.BeginScope(_logScope))
{
await SendCoreAsyncCore(methodName, args, cancellationToken).ForceAsync();
}
}
private async Task StartAsyncCore(CancellationToken cancellationToken)
{
_state.AssertInConnectionLock();
SafeAssert(_state.CurrentConnectionStateUnsynchronized == null, "We already have a connection!");
cancellationToken.ThrowIfCancellationRequested();
CheckDisposed();
Log.Starting(_logger);
// Start the connection
var connection = await _connectionFactory.ConnectAsync(_endPoint, cancellationToken);
var startingConnectionState = new ConnectionState(connection, this);
// From here on, if an error occurs we need to shut down the connection because
// we still own it.
try
{
Log.HubProtocol(_logger, _protocol.Name, _protocol.Version);
await HandshakeAsync(startingConnectionState, cancellationToken);
}
catch (Exception ex)
{
Log.ErrorStartingConnection(_logger, ex);
// Can't have any invocations to cancel, we're in the lock.
await CloseAsync(startingConnectionState.Connection);
throw;
}
// Set this at the end to avoid setting internal state until the connection is real
_state.CurrentConnectionStateUnsynchronized = startingConnectionState;
// Tell the server we intend to ping.
// Old clients never ping, and shouldn't be timed out, so ping to tell the server that we should be timed out if we stop.
// StartAsyncCore is invoked and awaited by StartAsyncInner and ReconnectAsync with the connection lock still acquired.
if (!(connection.Features.Get<IConnectionInherentKeepAliveFeature>()?.HasInherentKeepAlive ?? false))
{
await SendHubMessage(startingConnectionState, PingMessage.Instance, cancellationToken);
}
startingConnectionState.ReceiveTask = ReceiveLoop(startingConnectionState);
Log.Started(_logger);
}
private static ValueTask CloseAsync(ConnectionContext connection)
{
return connection.DisposeAsync();
}
// This method does both Dispose and Start, the 'disposing' flag indicates which.
// The behaviors are nearly identical, except that the _disposed flag is set in the lock
// if we're disposing.
private async Task StopAsyncCore(bool disposing)
{
// StartAsync acquires the connection lock for the duration of the handshake.
// ReconnectAsync also acquires the connection lock for reconnect attempts and handshakes.
// Cancel the StopCts without acquiring the lock so we can short-circuit it.
_state.StopCts.Cancel();
// Potentially wait for StartAsync to finish, and block a new StartAsync from
// starting until we've finished stopping.
await _state.WaitConnectionLockAsync(token: default);
// Ensure that ReconnectingState.ReconnectTask is not accessed outside of the lock.
var reconnectTask = _state.ReconnectTask;
if (reconnectTask.Status != TaskStatus.RanToCompletion)
{
// Let the current reconnect attempts finish if necessary without the lock.
// Otherwise, ReconnectAsync will stall forever acquiring the lock.
// It should never throw, even if the reconnect attempts fail.
// The StopCts should prevent the HubConnection from restarting until it is reset.
_state.ReleaseConnectionLock();
await reconnectTask;
await _state.WaitConnectionLockAsync(token: default);
}
ConnectionState? connectionState;
try
{
if (disposing && _disposed)
{
// DisposeAsync should be idempotent.
return;
}
CheckDisposed();
connectionState = _state.CurrentConnectionStateUnsynchronized;
// Set the stopping flag so that any invocations after this get a useful error message instead of
// silently failing or throwing an error about the pipe being completed.
if (connectionState != null)
{
connectionState.Stopping = true;
}
else
{
// Reset StopCts if there isn't an active connection so that the next StartAsync wont immediately fail due to the token being canceled
_state.StopCts = new CancellationTokenSource();
}
if (disposing)
{
// Must set this before calling DisposeAsync because the service provider has a reference to the HubConnection and will try to dispose it again
_disposed = true;
if (_serviceProvider is IAsyncDisposable asyncDispose)
{
await asyncDispose.DisposeAsync();
}
else
{
(_serviceProvider as IDisposable)?.Dispose();
}
}
}
finally
{
_state.ReleaseConnectionLock();
}
// Now stop the connection we captured
if (connectionState != null)
{
await connectionState.StopAsync();
}
}
/// <summary>
/// Invokes a streaming hub method on the server using the specified method name, return type and arguments.
/// </summary>
/// <typeparam name="TResult">The return type of the streaming server method.</typeparam>
/// <param name="methodName">The name of the server method to invoke.</param>
/// <param name="args">The arguments used to invoke the server method.</param>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None" />.</param>
/// <returns>
/// A <see cref="IAsyncEnumerable{TResult}"/> that represents the stream.
/// </returns>
public virtual IAsyncEnumerable<TResult> StreamAsyncCore<TResult>(string methodName, object?[] args, CancellationToken cancellationToken = default)
{
var cts = cancellationToken.CanBeCanceled ? CancellationTokenSource.CreateLinkedTokenSource(cancellationToken) : new CancellationTokenSource();
var stream = CastIAsyncEnumerable<TResult>(methodName, args, cts);
var cancelableStream = AsyncEnumerableAdapters.MakeCancelableTypedAsyncEnumerable(stream, cts);
return cancelableStream;
}
private async IAsyncEnumerable<T> CastIAsyncEnumerable<T>(string methodName, object?[] args, CancellationTokenSource cts)
{
var reader = await StreamAsChannelCoreAsync(methodName, typeof(T), args, cts.Token);
while (await reader.WaitToReadAsync(cts.Token))
{
while (reader.TryRead(out var item))
{
yield return (T)item!;
}
}
}
private async Task<ChannelReader<object?>> StreamAsChannelCoreAsyncCore(string methodName, Type returnType, object?[] args, CancellationToken cancellationToken)
{
async Task OnStreamCanceled(InvocationRequest irq)
{
// We need to take the connection lock in order to ensure we a) have a connection and b) are the only one accessing the write end of the pipe.
await _state.WaitConnectionLockAsync(token: default);
try
{
if (_state.CurrentConnectionStateUnsynchronized != null)
{
Log.SendingCancellation(_logger, irq.InvocationId);
// Fire and forget, if it fails that means we aren't connected anymore.
_ = SendHubMessage(_state.CurrentConnectionStateUnsynchronized, new CancelInvocationMessage(irq.InvocationId), irq.CancellationToken);
}
else
{
Log.UnableToSendCancellation(_logger, irq.InvocationId);
}
}
finally
{
_state.ReleaseConnectionLock();
}
// Cancel the invocation
irq.Dispose();
}
var readers = default(Dictionary<string, object>);
CheckDisposed();
var connectionState = await _state.WaitForActiveConnectionAsync(nameof(StreamAsChannelCoreAsync), token: cancellationToken);
ChannelReader<object?> channel;
try
{
CheckDisposed();
cancellationToken.ThrowIfCancellationRequested();
readers = PackageStreamingParams(connectionState, ref args, out var streamIds);
// I just want an excuse to use 'irq' as a variable name...
var irq = InvocationRequest.Stream(cancellationToken, returnType, connectionState.GetNextId(), _loggerFactory, this, out channel);
await InvokeStreamCore(connectionState, methodName, irq, args, streamIds?.ToArray(), cancellationToken);
if (cancellationToken.CanBeCanceled)
{
cancellationToken.Register(state => _ = OnStreamCanceled((InvocationRequest)state!), irq);
}
LaunchStreams(connectionState, readers, cancellationToken);
}
finally
{
_state.ReleaseConnectionLock();
}
return channel;
}
private Dictionary<string, object>? PackageStreamingParams(ConnectionState connectionState, ref object?[] args, out List<string>? streamIds)
{
Dictionary<string, object>? readers = null;
streamIds = null;
var newArgsCount = args.Length;
const int MaxStackSize = 256;
Span<bool> isStreaming = args.Length <= MaxStackSize
? stackalloc bool[MaxStackSize].Slice(0, args.Length)
: new bool[args.Length];
for (var i = 0; i < args.Length; i++)
{
var arg = args[i];
if (arg is not null && ReflectionHelper.IsStreamingType(arg.GetType()))
{
isStreaming[i] = true;
newArgsCount--;
if (readers is null)
{
readers = new Dictionary<string, object>();
}
if (streamIds is null)
{
streamIds = new List<string>();
}
var id = connectionState.GetNextId();
readers[id] = arg;
streamIds.Add(id);
Log.StartingStream(_logger, id);
}
}
if (newArgsCount == args.Length)
{
return null;
}
var newArgs = newArgsCount > 0
? new object?[newArgsCount]
: Array.Empty<object?>();
int newArgsIndex = 0;
for (var i = 0; i < args.Length; i++)
{
if (!isStreaming[i])
{
newArgs[newArgsIndex] = args[i];
newArgsIndex++;
}
}
args = newArgs;
return readers;
}
private void LaunchStreams(ConnectionState connectionState, Dictionary<string, object>? readers, CancellationToken cancellationToken)
{
if (readers == null)
{
// if there were no streaming parameters then readers is never initialized
return;
}
_state.AssertInConnectionLock();
// It's safe to access connectionState.UploadStreamToken as we still have the connection lock
var cts = CancellationTokenSource.CreateLinkedTokenSource(connectionState.UploadStreamToken, cancellationToken);
foreach (var kvp in readers)
{
var reader = kvp.Value;
// For each stream that needs to be sent, run a "send items" task in the background.
// This reads from the channel, attaches streamId, and sends to server.
// A single background thread here quickly gets messy.
if (ReflectionHelper.IsIAsyncEnumerable(reader.GetType()))
{
_ = _sendIAsyncStreamItemsMethod
.MakeGenericMethod(reader.GetType().GetInterface("IAsyncEnumerable`1")!.GetGenericArguments())
.Invoke(this, new object[] { connectionState, kvp.Key.ToString(), reader, cts });
continue;
}
_ = _sendStreamItemsMethod
.MakeGenericMethod(reader.GetType().GetGenericArguments())
.Invoke(this, new object[] { connectionState, kvp.Key.ToString(), reader, cts });
}
}
// this is called via reflection using the `_sendStreamItems` field
private Task SendStreamItems<T>(ConnectionState connectionState, string streamId, ChannelReader<T> reader, CancellationTokenSource tokenSource)
{
async Task ReadChannelStream()
{
while (await reader.WaitToReadAsync(tokenSource.Token))
{
while (!tokenSource.Token.IsCancellationRequested && reader.TryRead(out var item))
{
await SendWithLock(connectionState, new StreamItemMessage(streamId, item), tokenSource.Token);
Log.SendingStreamItem(_logger, streamId);
}
}
}
return CommonStreaming(connectionState, streamId, ReadChannelStream);
}
// this is called via reflection using the `_sendIAsyncStreamItemsMethod` field
private Task SendIAsyncEnumerableStreamItems<T>(ConnectionState connectionState, string streamId, IAsyncEnumerable<T> stream, CancellationTokenSource tokenSource)
{
async Task ReadAsyncEnumerableStream()
{
var streamValues = AsyncEnumerableAdapters.MakeCancelableTypedAsyncEnumerable(stream, tokenSource);
await foreach (var streamValue in streamValues)
{
await SendWithLock(connectionState, new StreamItemMessage(streamId, streamValue), tokenSource.Token);
Log.SendingStreamItem(_logger, streamId);
}
}
return CommonStreaming(connectionState, streamId, ReadAsyncEnumerableStream);
}
private async Task CommonStreaming(ConnectionState connectionState, string streamId, Func<Task> createAndConsumeStream)
{
Log.StartingStream(_logger, streamId);
string? responseError = null;
try
{
await createAndConsumeStream();
}
catch (OperationCanceledException)
{
Log.CancelingStream(_logger, streamId);
responseError = "Stream canceled by client.";
}
catch (Exception ex)
{
Log.ErroredStream(_logger, streamId, ex);
responseError = $"Stream errored by client: '{ex}'";
}
Log.CompletingStream(_logger, streamId);
// Don't use cancellation token here
// this is triggered by a cancellation token to tell the server that the client is done streaming
await SendWithLock(connectionState, CompletionMessage.WithError(streamId, responseError), cancellationToken: default);
}
private async Task<object?> InvokeCoreAsyncCore(string methodName, Type returnType, object?[] args, CancellationToken cancellationToken)
{
var readers = default(Dictionary<string, object>);
CheckDisposed();
var connectionState = await _state.WaitForActiveConnectionAsync(nameof(InvokeCoreAsync), token: cancellationToken);
Task<object?> invocationTask;
try
{
CheckDisposed();
readers = PackageStreamingParams(connectionState, ref args, out var streamIds);
var irq = InvocationRequest.Invoke(cancellationToken, returnType, connectionState.GetNextId(), _loggerFactory, this, out invocationTask);
await InvokeCore(connectionState, methodName, irq, args, streamIds?.ToArray(), cancellationToken);
LaunchStreams(connectionState, readers, cancellationToken);
}
finally
{
_state.ReleaseConnectionLock();
}
// Wait for this outside the lock, because it won't complete until the server responds
return await invocationTask;
}
private async Task InvokeCore(ConnectionState connectionState, string methodName, InvocationRequest irq, object?[] args, string[]? streams, CancellationToken cancellationToken)
{
Log.PreparingBlockingInvocation(_logger, irq.InvocationId, methodName, irq.ResultType.FullName!, args.Length);
// Client invocations are always blocking
var invocationMessage = new InvocationMessage(irq.InvocationId, methodName, args, streams);
Log.RegisteringInvocation(_logger, irq.InvocationId);
connectionState.AddInvocation(irq);
// Trace the full invocation
Log.IssuingInvocation(_logger, irq.InvocationId, irq.ResultType.FullName!, methodName, args);
try
{
await SendHubMessage(connectionState, invocationMessage, cancellationToken);
}
catch (Exception ex)
{
Log.FailedToSendInvocation(_logger, irq.InvocationId, ex);
connectionState.TryRemoveInvocation(irq.InvocationId, out _);
irq.Fail(ex);
}
}
private async Task InvokeStreamCore(ConnectionState connectionState, string methodName, InvocationRequest irq, object?[] args, string[]? streams, CancellationToken cancellationToken)
{
_state.AssertConnectionValid();
Log.PreparingStreamingInvocation(_logger, irq.InvocationId, methodName, irq.ResultType.FullName!, args.Length);
var invocationMessage = new StreamInvocationMessage(irq.InvocationId, methodName, args, streams);
Log.RegisteringInvocation(_logger, irq.InvocationId);
connectionState.AddInvocation(irq);
// Trace the full invocation
Log.IssuingInvocation(_logger, irq.InvocationId, irq.ResultType.FullName!, methodName, args);
try
{
await SendHubMessage(connectionState, invocationMessage, cancellationToken);
}
catch (Exception ex)
{
Log.FailedToSendInvocation(_logger, irq.InvocationId, ex);
connectionState.TryRemoveInvocation(irq.InvocationId, out _);
irq.Fail(ex);
}
}
private async Task SendHubMessage(ConnectionState connectionState, HubMessage hubMessage, CancellationToken cancellationToken = default)
{
_state.AssertConnectionValid();
_protocol.WriteMessage(hubMessage, connectionState.Connection.Transport.Output);
Log.SendingMessage(_logger, hubMessage);
#pragma warning disable CA2016 // Forward the 'CancellationToken' parameter to methods
// REVIEW: If a token is passed in and is canceled during FlushAsync it seems to break .Complete()...
await connectionState.Connection.Transport.Output.FlushAsync();
#pragma warning restore CA2016 // Forward the 'CancellationToken' parameter to methods
Log.MessageSent(_logger, hubMessage);
// We've sent a message, so don't ping for a while
connectionState.ResetSendPing();
}
private async Task SendCoreAsyncCore(string methodName, object?[] args, CancellationToken cancellationToken)
{
var readers = default(Dictionary<string, object>);
CheckDisposed();
var connectionState = await _state.WaitForActiveConnectionAsync(nameof(SendCoreAsync), token: cancellationToken);
try
{
CheckDisposed();
readers = PackageStreamingParams(connectionState, ref args, out var streamIds);
Log.PreparingNonBlockingInvocation(_logger, methodName, args.Length);
var invocationMessage = new InvocationMessage(null, methodName, args, streamIds?.ToArray());
await SendHubMessage(connectionState, invocationMessage, cancellationToken);
LaunchStreams(connectionState, readers, cancellationToken);
}
finally
{
_state.ReleaseConnectionLock();
}
}
private async Task SendWithLock(ConnectionState expectedConnectionState, HubMessage message, CancellationToken cancellationToken, [CallerMemberName] string callerName = "")
{
CheckDisposed();
var connectionState = await _state.WaitForActiveConnectionAsync(callerName, token: cancellationToken);
try
{
CheckDisposed();
SafeAssert(ReferenceEquals(expectedConnectionState, connectionState), "The connection state changed unexpectedly!");
await SendHubMessage(connectionState, message, cancellationToken);
}
finally
{
_state.ReleaseConnectionLock();
}
}
private async Task<CloseMessage?> ProcessMessagesAsync(HubMessage message, ConnectionState connectionState, ChannelWriter<InvocationMessage> invocationMessageWriter)
{
Log.ResettingKeepAliveTimer(_logger);
connectionState.ResetTimeout();
InvocationRequest? irq;
switch (message)
{
case InvocationBindingFailureMessage bindingFailure:
// The server can't receive a response, so we just drop the message and log
// REVIEW: Is this the right approach?
Log.ArgumentBindingFailure(_logger, bindingFailure.InvocationId, bindingFailure.Target, bindingFailure.BindingFailure.SourceException);
break;
case InvocationMessage invocation:
Log.ReceivedInvocation(_logger, invocation.InvocationId, invocation.Target, invocation.Arguments);
await invocationMessageWriter.WriteAsync(invocation);
break;
case CompletionMessage completion:
if (!connectionState.TryRemoveInvocation(completion.InvocationId!, out irq))
{
Log.DroppedCompletionMessage(_logger, completion.InvocationId!);
break;
}
DispatchInvocationCompletion(completion, irq);
irq.Dispose();
break;
case StreamItemMessage streamItem:
// if there's no open StreamInvocation with the given id, then complete with an error
if (!connectionState.TryGetInvocation(streamItem.InvocationId!, out irq))
{
Log.DroppedStreamMessage(_logger, streamItem.InvocationId!);
break;
}
await DispatchInvocationStreamItemAsync(streamItem, irq);
break;
case CloseMessage close:
if (string.IsNullOrEmpty(close.Error))
{
Log.ReceivedClose(_logger);
}
else
{
Log.ReceivedCloseWithError(_logger, close.Error);
}
return close;
case PingMessage _:
Log.ReceivedPing(_logger);
// timeout is reset above, on receiving any message
break;
default:
throw new InvalidOperationException($"Unexpected message type: {message.GetType().FullName}");
}
return null;
}
private async Task DispatchInvocationAsync(InvocationMessage invocation)
{
// Find the handler
if (!_handlers.TryGetValue(invocation.Target, out var invocationHandlerList))
{
Log.MissingHandler(_logger, invocation.Target);
return;
}
// Grabbing the current handlers
var copiedHandlers = invocationHandlerList.GetHandlers();
foreach (var handler in copiedHandlers)