This repository has been archived by the owner on Dec 18, 2018. It is now read-only.
/
HubConnection.cs
1126 lines (973 loc) · 47.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
// 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.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
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.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
{
public static readonly TimeSpan DefaultServerTimeout = TimeSpan.FromSeconds(30); // Server ping rate is 15 sec, this is 2 times that.
public static readonly TimeSpan DefaultHandshakeTimeout = TimeSpan.FromSeconds(15);
// This lock protects the connection state.
private readonly SemaphoreSlim _connectionLock = new SemaphoreSlim(1, 1);
// Persistent across all connections
private readonly ILoggerFactory _loggerFactory;
private readonly ILogger _logger;
private readonly IHubProtocol _protocol;
private readonly IServiceProvider _serviceProvider;
private readonly IConnectionFactory _connectionFactory;
private readonly ConcurrentDictionary<string, InvocationHandlerList> _handlers = new ConcurrentDictionary<string, InvocationHandlerList>(StringComparer.Ordinal);
private bool _disposed;
// Transient state to a connection
private ConnectionState _connectionState;
public event Func<Exception, Task> Closed;
/// <summary>
/// Gets or sets the server timeout interval for the connection. Changes to this value
/// will not be applied until the Keep Alive timer is next reset.
/// </summary>
public TimeSpan ServerTimeout { get; set; } = DefaultServerTimeout;
public TimeSpan HandshakeTimeout { get; set; } = DefaultHandshakeTimeout;
/// <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="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, IServiceProvider serviceProvider, ILoggerFactory loggerFactory)
: this(connectionFactory, protocol, loggerFactory)
{
_serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));
}
/// <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="loggerFactory">The logger factory.</param>
public HubConnection(IConnectionFactory connectionFactory, IHubProtocol protocol, ILoggerFactory loggerFactory)
{
_connectionFactory = connectionFactory ?? throw new ArgumentNullException(nameof(connectionFactory));
_protocol = protocol ?? throw new ArgumentNullException(nameof(protocol));
_loggerFactory = loggerFactory ?? NullLoggerFactory.Instance;
_logger = _loggerFactory.CreateLogger<HubConnection>();
}
/// <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 async Task StartAsync(CancellationToken cancellationToken = default)
{
CheckDisposed();
await StartAsyncCore(cancellationToken).ForceAsync();
}
/// <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 async Task StopAsync(CancellationToken cancellationToken = default)
{
CheckDisposed();
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="Task"/> that represents the asynchronous dispose.</returns>
public async Task DisposeAsync()
{
if (!_disposed)
{
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 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>
/// 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 async Task<ChannelReader<object>> StreamAsChannelCoreAsync(string methodName, Type returnType, object[] args, CancellationToken cancellationToken = default) =>
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 async Task<object> InvokeCoreAsync(string methodName, Type returnType, object[] args, CancellationToken cancellationToken = default) =>
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 async Task SendCoreAsync(string methodName, object[] args, CancellationToken cancellationToken = default) =>
await SendCoreAsyncCore(methodName, args, cancellationToken).ForceAsync();
private async Task StartAsyncCore(CancellationToken cancellationToken)
{
await WaitConnectionLockAsync();
try
{
if (_connectionState != null)
{
// We're already connected
return;
}
cancellationToken.ThrowIfCancellationRequested();
CheckDisposed();
Log.Starting(_logger);
// Start the connection
var connection = await _connectionFactory.ConnectAsync(_protocol.TransferFormat);
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
_connectionState = startingConnectionState;
_connectionState.ReceiveTask = ReceiveLoop(_connectionState);
Log.Started(_logger);
}
finally
{
ReleaseConnectionLock();
}
}
private Task CloseAsync(ConnectionContext connection)
{
return _connectionFactory.DisposeAsync(connection);
}
// 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)
{
// Block a Start from happening until we've finished capturing the connection state.
ConnectionState connectionState;
await WaitConnectionLockAsync();
try
{
if (disposing && _disposed)
{
// DisposeAsync should be idempotent.
return;
}
CheckDisposed();
connectionState = _connectionState;
// 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;
}
if (disposing)
{
(_serviceProvider as IDisposable)?.Dispose();
_disposed = true;
}
}
finally
{
ReleaseConnectionLock();
}
// Now stop the connection we captured
if (connectionState != null)
{
await connectionState.StopAsync();
}
}
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 WaitConnectionLockAsync();
try
{
if (_connectionState != null)
{
Log.SendingCancellation(_logger, irq.InvocationId);
// Fire and forget, if it fails that means we aren't connected anymore.
_ = SendHubMessage(new CancelInvocationMessage(irq.InvocationId), irq.CancellationToken);
}
else
{
Log.UnableToSendCancellation(_logger, irq.InvocationId);
}
}
finally
{
ReleaseConnectionLock();
}
// Cancel the invocation
irq.Dispose();
}
CheckDisposed();
await WaitConnectionLockAsync();
ChannelReader<object> channel;
try
{
CheckDisposed();
CheckConnectionActive(nameof(StreamAsChannelCoreAsync));
var irq = InvocationRequest.Stream(cancellationToken, returnType, _connectionState.GetNextId(), _loggerFactory, this, out channel);
await InvokeStreamCore(methodName, irq, args, cancellationToken);
if (cancellationToken.CanBeCanceled)
{
cancellationToken.Register(state => _ = OnStreamCanceled((InvocationRequest)state), irq);
}
}
finally
{
ReleaseConnectionLock();
}
return channel;
}
private async Task<object> InvokeCoreAsyncCore(string methodName, Type returnType, object[] args, CancellationToken cancellationToken)
{
CheckDisposed();
await WaitConnectionLockAsync();
Task<object> invocationTask;
try
{
CheckDisposed();
CheckConnectionActive(nameof(InvokeCoreAsync));
var irq = InvocationRequest.Invoke(cancellationToken, returnType, _connectionState.GetNextId(), _loggerFactory, this, out invocationTask);
await InvokeCore(methodName, irq, args, cancellationToken);
}
finally
{
ReleaseConnectionLock();
}
// Wait for this outside the lock, because it won't complete until the server responds.
return await invocationTask;
}
private async Task InvokeCore(string methodName, InvocationRequest irq, object[] args, CancellationToken cancellationToken)
{
AssertConnectionValid();
Log.PreparingBlockingInvocation(_logger, irq.InvocationId, methodName, irq.ResultType.FullName, args.Length);
// Client invocations are always blocking
var invocationMessage = new InvocationMessage(irq.InvocationId, methodName, args);
Log.RegisteringInvocation(_logger, invocationMessage.InvocationId);
_connectionState.AddInvocation(irq);
// Trace the full invocation
Log.IssuingInvocation(_logger, invocationMessage.InvocationId, irq.ResultType.FullName, methodName, args);
try
{
await SendHubMessage(invocationMessage, cancellationToken);
}
catch (Exception ex)
{
Log.FailedToSendInvocation(_logger, invocationMessage.InvocationId, ex);
_connectionState.TryRemoveInvocation(invocationMessage.InvocationId, out _);
irq.Fail(ex);
}
}
private async Task InvokeStreamCore(string methodName, InvocationRequest irq, object[] args, CancellationToken cancellationToken)
{
AssertConnectionValid();
Log.PreparingStreamingInvocation(_logger, irq.InvocationId, methodName, irq.ResultType.FullName, args.Length);
var invocationMessage = new StreamInvocationMessage(irq.InvocationId, methodName, args);
// I just want an excuse to use 'irq' as a variable name...
Log.RegisteringInvocation(_logger, invocationMessage.InvocationId);
_connectionState.AddInvocation(irq);
// Trace the full invocation
Log.IssuingInvocation(_logger, invocationMessage.InvocationId, irq.ResultType.FullName, methodName, args);
try
{
await SendHubMessage(invocationMessage, cancellationToken);
}
catch (Exception ex)
{
Log.FailedToSendInvocation(_logger, invocationMessage.InvocationId, ex);
_connectionState.TryRemoveInvocation(invocationMessage.InvocationId, out _);
irq.Fail(ex);
}
}
private async Task SendHubMessage(HubInvocationMessage hubMessage, CancellationToken cancellationToken = default)
{
AssertConnectionValid();
_protocol.WriteMessage(hubMessage, _connectionState.Connection.Transport.Output);
Log.SendingMessage(_logger, hubMessage);
// REVIEW: If a token is passed in and is canceled during FlushAsync it seems to break .Complete()...
await _connectionState.Connection.Transport.Output.FlushAsync();
Log.MessageSent(_logger, hubMessage);
}
private async Task SendCoreAsyncCore(string methodName, object[] args, CancellationToken cancellationToken)
{
CheckDisposed();
await WaitConnectionLockAsync();
try
{
CheckDisposed();
CheckConnectionActive(nameof(SendCoreAsync));
Log.PreparingNonBlockingInvocation(_logger, methodName, args.Length);
var invocationMessage = new InvocationMessage(null, methodName, args);
await SendHubMessage(invocationMessage, cancellationToken);
}
finally
{
ReleaseConnectionLock();
}
}
private async Task<(bool close, Exception exception)> ProcessMessagesAsync(HubMessage message, ConnectionState connectionState)
{
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 DispatchInvocationAsync(invocation);
break;
case CompletionMessage completion:
if (!connectionState.TryRemoveInvocation(completion.InvocationId, out irq))
{
Log.DroppedCompletionMessage(_logger, completion.InvocationId);
}
else
{
DispatchInvocationCompletion(completion, irq);
irq.Dispose();
}
break;
case StreamItemMessage streamItem:
// Complete the invocation with an error, we don't support streaming (yet)
if (!connectionState.TryGetInvocation(streamItem.InvocationId, out irq))
{
Log.DroppedStreamMessage(_logger, streamItem.InvocationId);
return (close: false, exception: null);
}
await DispatchInvocationStreamItemAsync(streamItem, irq);
break;
case CloseMessage close:
if (string.IsNullOrEmpty(close.Error))
{
Log.ReceivedClose(_logger);
return (close: true, exception: null);
}
else
{
Log.ReceivedCloseWithError(_logger, close.Error);
return (close: true, exception: new HubException($"The server closed the connection with the following error: {close.Error}"));
}
case PingMessage _:
Log.ReceivedPing(_logger);
// Nothing to do on receipt of a ping.
break;
default:
throw new InvalidOperationException($"Unexpected message type: {message.GetType().FullName}");
}
return (close: false, exception: 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)
{
try
{
await handler.InvokeAsync(invocation.Arguments);
}
catch (Exception ex)
{
Log.ErrorInvokingClientSideMethod(_logger, invocation.Target, ex);
}
}
}
private async Task DispatchInvocationStreamItemAsync(StreamItemMessage streamItem, InvocationRequest irq)
{
Log.ReceivedStreamItem(_logger, streamItem.InvocationId);
if (irq.CancellationToken.IsCancellationRequested)
{
Log.CancelingStreamItem(_logger, irq.InvocationId);
}
else if (!await irq.StreamItem(streamItem.Item))
{
Log.ReceivedStreamItemAfterClose(_logger, irq.InvocationId);
}
}
private void DispatchInvocationCompletion(CompletionMessage completion, InvocationRequest irq)
{
Log.ReceivedInvocationCompletion(_logger, completion.InvocationId);
if (irq.CancellationToken.IsCancellationRequested)
{
Log.CancelingInvocationCompletion(_logger, irq.InvocationId);
}
else
{
irq.Complete(completion);
}
}
private void CheckDisposed()
{
if (_disposed)
{
throw new ObjectDisposedException(nameof(HubConnection));
}
}
private async Task HandshakeAsync(ConnectionState startingConnectionState, CancellationToken cancellationToken)
{
// Send the Handshake request
Log.SendingHubHandshake(_logger);
var handshakeRequest = new HandshakeRequestMessage(_protocol.Name, _protocol.Version);
HandshakeProtocol.WriteRequestMessage(handshakeRequest, startingConnectionState.Connection.Transport.Output);
var sendHandshakeResult = await startingConnectionState.Connection.Transport.Output.FlushAsync(CancellationToken.None);
if (sendHandshakeResult.IsCompleted)
{
// The other side disconnected
throw new InvalidOperationException("The server disconnected before the handshake was completed");
}
try
{
using (var handshakeCts = new CancellationTokenSource(HandshakeTimeout))
using (var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, handshakeCts.Token))
{
while (true)
{
var result = await startingConnectionState.Connection.Transport.Input.ReadAsync(cts.Token);
var buffer = result.Buffer;
var consumed = buffer.Start;
var examined = buffer.End;
try
{
// Read first message out of the incoming data
if (!buffer.IsEmpty)
{
if (HandshakeProtocol.TryParseResponseMessage(ref buffer, out var message))
{
// Adjust consumed and examined to point to the end of the handshake
// response, this handles the case where invocations are sent in the same payload
// as the the negotiate response.
consumed = buffer.Start;
examined = consumed;
if (message.Error != null)
{
Log.HandshakeServerError(_logger, message.Error);
throw new HubException(
$"Unable to complete handshake with the server due to an error: {message.Error}");
}
break;
}
}
if (result.IsCompleted)
{
// Not enough data, and we won't be getting any more data.
throw new InvalidOperationException(
"The server disconnected before sending a handshake response");
}
}
finally
{
startingConnectionState.Connection.Transport.Input.AdvanceTo(consumed, examined);
}
}
}
}
// Ignore HubException because we throw it when we receive a handshake response with an error
// And we don't need to log that the handshake failed
catch (Exception ex) when (!(ex is HubException))
{
// shutdown if we're unable to read handshake
Log.ErrorReceivingHandshakeResponse(_logger, ex);
throw;
}
Log.HandshakeComplete(_logger);
}
private async Task ReceiveLoop(ConnectionState connectionState)
{
// We hold a local capture of the connection state because StopAsync may dump out the current one.
// We'll be locking any time we want to check back in to the "active" connection state.
Log.ReceiveLoopStarting(_logger);
var timeoutTimer = StartTimeoutTimer(connectionState);
try
{
while (true)
{
var result = await connectionState.Connection.Transport.Input.ReadAsync();
var buffer = result.Buffer;
try
{
if (result.IsCanceled)
{
// We were canceled. Possibly because we were stopped gracefully
break;
}
else if (!buffer.IsEmpty)
{
ResetTimeoutTimer(timeoutTimer);
Log.ProcessingMessage(_logger, buffer.Length);
var close = false;
while (_protocol.TryParseMessage(ref buffer, connectionState, out var message))
{
Exception exception;
// We have data, process it
(close, exception) = await ProcessMessagesAsync(message, connectionState);
if (close)
{
// Closing because we got a close frame, possibly with an error in it.
connectionState.CloseException = exception;
break;
}
}
// If we're closing stop everything
if (close)
{
break;
}
}
if (result.IsCompleted)
{
if (!buffer.IsEmpty)
{
throw new InvalidDataException("Connection terminated while reading a message.");
}
break;
}
}
finally
{
// The buffer was sliced up to where it was consumed, so we can just advance to the start.
// We mark examined as buffer.End so that if we didn't receive a full frame, we'll wait for more data
// before yielding the read again.
connectionState.Connection.Transport.Input.AdvanceTo(buffer.Start, buffer.End);
}
}
}
catch (Exception ex)
{
Log.ServerDisconnectedWithError(_logger, ex);
connectionState.CloseException = ex;
}
// Clear the connectionState field
await WaitConnectionLockAsync();
try
{
SafeAssert(ReferenceEquals(_connectionState, connectionState),
"Someone other than ReceiveLoop cleared the connection state!");
_connectionState = null;
}
finally
{
ReleaseConnectionLock();
}
// Stop the timeout timer.
timeoutTimer?.Dispose();
// Dispose the connection
await CloseAsync(connectionState.Connection);
// Cancel any outstanding invocations within the connection lock
connectionState.CancelOutstandingInvocations(connectionState.CloseException);
if (connectionState.CloseException != null)
{
Log.ShutdownWithError(_logger, connectionState.CloseException);
}
else
{
Log.ShutdownConnection(_logger);
}
var closed = Closed;
// There is no need to start a new task if there is no Closed event registered
if (closed != null)
{
// Fire-and-forget the closed event
_ = RunClosedEvent(closed, connectionState.CloseException);
}
}
private async Task RunClosedEvent(Func<Exception, Task> closed, Exception closeException)
{
// Dispatch to the thread pool before we invoke the user callback
await AwaitableThreadPool.Yield();
try
{
Log.InvokingClosedEventHandler(_logger);
await closed.Invoke(closeException);
}
catch (Exception ex)
{
Log.ErrorDuringClosedEvent(_logger, ex);
}
}
private void ResetTimeoutTimer(Timer timeoutTimer)
{
if (timeoutTimer != null)
{
Log.ResettingKeepAliveTimer(_logger);
timeoutTimer.Change(ServerTimeout, Timeout.InfiniteTimeSpan);
}
}
private Timer StartTimeoutTimer(ConnectionState connectionState)
{
// Check if we need keep-alive
Timer timeoutTimer = null;
// We use '!== true' because it could be null, which we treat as false.
if (connectionState.Connection.Features.Get<IConnectionInherentKeepAliveFeature>()?.HasInherentKeepAlive != true)
{
Log.StartingServerTimeoutTimer(_logger, ServerTimeout);
timeoutTimer = new Timer(
state => OnTimeout((ConnectionState)state),
connectionState,
dueTime: ServerTimeout,
period: Timeout.InfiniteTimeSpan);
}
else
{
Log.NotUsingServerTimeout(_logger);
}
return timeoutTimer;
}
private void OnTimeout(ConnectionState connectionState)
{
if (!Debugger.IsAttached)
{
connectionState.CloseException = new TimeoutException(
$"Server timeout ({ServerTimeout.TotalMilliseconds:0.00}ms) elapsed without receiving a message from the server.");
connectionState.Connection.Transport.Input.CancelPendingRead();
}
}
private void CheckConnectionActive(string methodName)
{
if (_connectionState == null || _connectionState.Stopping)
{
throw new InvalidOperationException($"The '{methodName}' method cannot be called if the connection is not active");
}
}
// Debug.Assert plays havoc with Unit Tests. But I want something that I can "assert" only in Debug builds.
[Conditional("DEBUG")]
private static void SafeAssert(bool condition, string message, [CallerMemberName] string memberName = null, [CallerFilePath] string fileName = null, [CallerLineNumber] int lineNumber = 0)
{
if (!condition)
{
throw new Exception($"Assertion failed in {memberName}, at {fileName}:{lineNumber}: {message}");
}
}
[Conditional("DEBUG")]
private void AssertInConnectionLock([CallerMemberName] string memberName = null, [CallerFilePath] string fileName = null, [CallerLineNumber] int lineNumber = 0) => SafeAssert(_connectionLock.CurrentCount == 0, "We're not in the Connection Lock!", memberName, fileName, lineNumber);
[Conditional("DEBUG")]
private void AssertConnectionValid([CallerMemberName] string memberName = null, [CallerFilePath] string fileName = null, [CallerLineNumber] int lineNumber = 0)
{
AssertInConnectionLock(memberName, fileName, lineNumber);
SafeAssert(_connectionState != null, "We don't have a connection!", memberName, fileName, lineNumber);
}
private Task WaitConnectionLockAsync([CallerMemberName] string memberName = null, [CallerFilePath] string filePath = null, [CallerLineNumber] int lineNumber = 0)
{
Log.WaitingOnConnectionLock(_logger, memberName, filePath, lineNumber);
return _connectionLock.WaitAsync();
}
private void ReleaseConnectionLock([CallerMemberName] string memberName = null,
[CallerFilePath] string filePath = null, [CallerLineNumber] int lineNumber = 0)
{
Log.ReleasingConnectionLock(_logger, memberName, filePath, lineNumber);
_connectionLock.Release();
}
private class Subscription : IDisposable
{
private readonly InvocationHandler _handler;
private readonly InvocationHandlerList _handlerList;
public Subscription(InvocationHandler handler, InvocationHandlerList handlerList)
{
_handler = handler;
_handlerList = handlerList;
}
public void Dispose()
{
_handlerList.Remove(_handler);
}
}
private class InvocationHandlerList
{
private readonly List<InvocationHandler> _invocationHandlers;
// A lazy cached copy of the handlers that doesn't change for thread safety.
// Adding or removing a handler sets this to null.
private InvocationHandler[] _copiedHandlers;
internal InvocationHandlerList(InvocationHandler handler)
{
_invocationHandlers = new List<InvocationHandler>() { handler };
}
internal InvocationHandler[] GetHandlers()
{
var handlers = _copiedHandlers;
if (handlers == null)
{
lock (_invocationHandlers)
{
// Check if the handlers are set, if not we'll copy them over.
if (_copiedHandlers == null)
{
_copiedHandlers = _invocationHandlers.ToArray();
}
handlers = _copiedHandlers;
}
}
return handlers;
}
internal void Add(InvocationHandler handler)
{
lock (_invocationHandlers)
{
_invocationHandlers.Add(handler);
_copiedHandlers = null;
}
}
internal void Remove(InvocationHandler handler)
{
lock (_invocationHandlers)
{
if (_invocationHandlers.Remove(handler))
{
_copiedHandlers = null;
}
}
}
}
private readonly struct InvocationHandler
{
public Type[] ParameterTypes { get; }
private readonly Func<object[], object, Task> _callback;
private readonly object _state;
public InvocationHandler(Type[] parameterTypes, Func<object[], object, Task> callback, object state)
{
_callback = callback;
ParameterTypes = parameterTypes;
_state = state;
}
public Task InvokeAsync(object[] parameters)
{
return _callback(parameters, _state);
}
}
// Represents all the transient state about a connection
// This includes binding information because return type binding depends upon _pendingCalls
private class ConnectionState : IInvocationBinder
{
private volatile bool _stopping;
private readonly HubConnection _hubConnection;
private TaskCompletionSource<object> _stopTcs;
private readonly object _lock = new object();
private readonly Dictionary<string, InvocationRequest> _pendingCalls = new Dictionary<string, InvocationRequest>(StringComparer.Ordinal);
private int _nextId;
public ConnectionContext Connection { get; }
public Task ReceiveTask { get; set; }
public Exception CloseException { get; set; }
public bool Stopping
{
get => _stopping;
set => _stopping = value;
}
public ConnectionState(ConnectionContext connection, HubConnection hubConnection)
{
_hubConnection = hubConnection;
Connection = connection;