Skip to content

Commit

Permalink
Merge branch 'dev' into bf
Browse files Browse the repository at this point in the history
  • Loading branch information
vicancy authored Feb 26, 2025
2 parents 2cf4168 + f674fd8 commit 71f2158
Show file tree
Hide file tree
Showing 172 changed files with 3,266 additions and 2,988 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,15 @@
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;

using Microsoft.Azure.SignalR.Protocol;
using Microsoft.Extensions.Primitives;

namespace Microsoft.Azure.SignalR.AspNet;

internal class ClientConnectionContext : IClientConnection
{
private readonly CancellationTokenSource _source = new CancellationTokenSource();
private readonly CancellationTokenSource _source = new();

public string ConnectionId { get; }

Expand Down
31 changes: 16 additions & 15 deletions src/Microsoft.Azure.SignalR.AspNet/ProductInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,22 +3,23 @@

using System.Reflection;

namespace Microsoft.Azure.SignalR.AspNet
namespace Microsoft.Azure.SignalR.AspNet;

#nullable enable

internal static class ProductInfo
{
internal static class ProductInfo
/// <summary>
/// For .NET framework below netframework462, there are assembly binding issues when referencing netstandard assemblies, https://github.com/Azure/azure-signalr/issues/452
/// For now, disable usage of System.Runtime.InteropServices.RuntimeInformation
/// </summary>
/// <returns></returns>
public static string GetProductInfo()
{
/// <summary>
/// For .NET framework below netframework462, there are assembly binding issues when referencing netstandard assemblies, https://github.com/Azure/azure-signalr/issues/452
/// For now, disable usage of System.Runtime.InteropServices.RuntimeInformation
/// </summary>
/// <returns></returns>
public static string GetProductInfo()
{
var assembly = Assembly.GetCallingAssembly();
var packageId = assembly.GetName().Name;
var version = assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>().InformationalVersion;

return $"{packageId}/{version}";
}
var assembly = Assembly.GetCallingAssembly();
var packageId = assembly.GetName().Name;
var version = assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>().InformationalVersion;

return $"{packageId}/{version}";
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
using System.Text;
using System.Threading;
using System.Threading.Tasks;

using Microsoft.AspNetCore.Connections;
using Microsoft.Azure.SignalR.Protocol;
using Microsoft.Extensions.Logging;
Expand All @@ -21,13 +22,11 @@ internal partial class ServiceConnection : ServiceConnectionBase
{
private const string ReconnectMessage = "asrs:reconnect";

private static readonly Dictionary<string, string> CustomHeader = new Dictionary<string, string>
{{Constants.AsrsUserAgent, ProductInfo.GetProductInfo()}};
private static readonly Dictionary<string, string> CustomHeader = new() { { Constants.AsrsUserAgent, ProductInfo.GetProductInfo() } };

private static readonly TimeSpan CloseApplicationTimeout = TimeSpan.FromSeconds(5);

private readonly ConcurrentDictionary<string, ClientConnectionContext> _clientConnections =
new ConcurrentDictionary<string, ClientConnectionContext>(StringComparer.Ordinal);
private readonly ConcurrentDictionary<string, ClientConnectionContext> _clientConnections = new(StringComparer.Ordinal);

private readonly IConnectionFactory _connectionFactory;

Expand Down Expand Up @@ -75,6 +74,11 @@ public override bool TryRemoveClientConnection(string connectionId, out IClientC
return r;
}

public override Task CloseClientConnections(CancellationToken token)
{
throw new NotSupportedException();
}

protected override Task<ConnectionContext> CreateConnection(string target = null)
{
return _connectionFactory.ConnectAsync(HubEndpoint, TransferFormat.Binary, ConnectionId, target,
Expand All @@ -97,11 +101,6 @@ protected override Task CleanupClientConnections(string fromInstanceId = null)
return Task.CompletedTask;
}

public override Task CloseClientConnections(CancellationToken token)
{
throw new NotSupportedException();
}

protected override Task OnClientConnectedAsync(OpenConnectionMessage openConnectionMessage)
{
// Create empty transport with only channel for async processing messages
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
using System;
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;

using Microsoft.Azure.SignalR.Protocol;
using Microsoft.Extensions.Logging;

Expand Down
16 changes: 9 additions & 7 deletions src/Microsoft.Azure.SignalR.Common/DefaultServerNameProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,16 @@

using System;

namespace Microsoft.Azure.SignalR
namespace Microsoft.Azure.SignalR;

#nullable enable

internal class DefaultServerNameProvider : IServerNameProvider
{
internal class DefaultServerNameProvider : IServerNameProvider
private readonly string _name = $"{Environment.MachineName}_{Guid.NewGuid():N}";

public string GetName()
{
private readonly string _name = $"{Environment.MachineName}_{Guid.NewGuid():N}";
public string GetName()
{
return _name;
}
return _name;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,16 @@

namespace Microsoft.Azure.SignalR;

#nullable enable

internal interface IConnectionFactory
{
Task<ConnectionContext> ConnectAsync(HubServiceEndpoint endpoint,
TransferFormat transferFormat,
string connectionId,
string target,
CancellationToken cancellationToken = default,
IDictionary<string, string> headers = null);
IDictionary<string, string>? headers = null);

// Current plan for IAsyncDisposable is that DisposeAsync will NOT take a CancellationToken
// https://github.com/dotnet/csharplang/blob/195efa07806284d7b57550e7447dc8bd39c156bf/proposals/async-streams.md#iasyncdisposable
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using System;
using System.Threading;
using System.Threading.Tasks;

using Microsoft.Azure.SignalR.Protocol;

namespace Microsoft.Azure.SignalR;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Copyright (c) Microsoft. All rights reserved.
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
Expand All @@ -11,6 +11,8 @@

namespace Microsoft.Azure.SignalR;

#nullable enable

internal class ConnectionFactory : IConnectionFactory
{
private readonly ILoggerFactory _loggerFactory;
Expand All @@ -20,15 +22,15 @@ internal class ConnectionFactory : IConnectionFactory
public ConnectionFactory(IServerNameProvider nameProvider, ILoggerFactory loggerFactory)
{
_loggerFactory = loggerFactory != null ? new GracefulLoggerFactory(loggerFactory) : throw new ArgumentNullException(nameof(loggerFactory));
_serverId = nameProvider?.GetName();
_serverId = nameProvider.GetName();
}

public async Task<ConnectionContext> ConnectAsync(HubServiceEndpoint hubServiceEndpoint,
TransferFormat transferFormat,
string connectionId,
string target,
CancellationToken cancellationToken = default,
IDictionary<string, string> headers = null)
IDictionary<string, string>? headers = null)
{
var provider = hubServiceEndpoint.Provider;
var hubName = hubServiceEndpoint.Hub;
Expand Down Expand Up @@ -140,7 +142,7 @@ public GracefulLogger(ILogger inner)
/// <param name="state"></param>
/// <param name="exception"></param>
/// <param name="formatter"></param>
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
{
if (logLevel >= LogLevel.Error)
{
Expand All @@ -154,10 +156,12 @@ public bool IsEnabled(LogLevel logLevel)
return _inner.IsEnabled(logLevel);
}

#nullable disable
public IDisposable BeginScope<TState>(TState state)
{
return _inner.BeginScope(state);
}
}
#nullable restore
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -38,11 +38,11 @@ internal abstract partial class ServiceConnectionBase : IServiceConnection

private readonly HandshakeRequestMessage _handshakeRequest;

private readonly SemaphoreSlim _writeLock = new SemaphoreSlim(1, 1);
private readonly SemaphoreSlim _writeLock = new(1, 1);

private readonly TaskCompletionSource<bool> _serviceConnectionStartTcs = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
private readonly TaskCompletionSource<bool> _serviceConnectionStartTcs = new(TaskCreationOptions.RunContinuationsAsynchronously);

private readonly TaskCompletionSource<object> _serviceConnectionOfflineTcs = new TaskCompletionSource<object>(TaskCreationOptions.RunContinuationsAsynchronously);
private readonly TaskCompletionSource<object> _serviceConnectionOfflineTcs = new(TaskCreationOptions.RunContinuationsAsynchronously);

private readonly ServiceConnectionType _connectionType;

Expand All @@ -52,7 +52,7 @@ internal abstract partial class ServiceConnectionBase : IServiceConnection

private readonly IClientConnectionManager _clientConnectionManager;

private readonly object _statusLock = new object();
private readonly object _statusLock = new();

private readonly string _endpointName;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,25 +31,25 @@ internal abstract class ServiceConnectionContainerBase : IServiceConnectionConta
private const int MessageWriteMaxRetry = 3;

// Give (interval * 3 + 1) delay when check value expire.
private static readonly long DefaultServersPingTimeoutTicks = Stopwatch.Frequency * ((long)Constants.Periods.DefaultServersPingInterval.TotalSeconds * 3 + 1);
private static readonly long DefaultServersPingTimeoutTicks = Stopwatch.Frequency * (((long)Constants.Periods.DefaultServersPingInterval.TotalSeconds * 3) + 1);

private static readonly Tuple<string, long> DefaultServersTagContext = new Tuple<string, long>(string.Empty, 0);
private static readonly Tuple<string, long> DefaultServersTagContext = new(string.Empty, 0);

private readonly IReadOnlyDictionary<byte, StrongBox<WeakReference<IServiceConnection>>> _partitionedCache;

private readonly BackOffPolicy _backOffPolicy = new BackOffPolicy();
private readonly BackOffPolicy _backOffPolicy = new();

private readonly object _lock = new object();
private readonly object _lock = new();

private readonly object _statusLock = new object();
private readonly object _statusLock = new();

private readonly AckHandler _ackHandler;

private readonly CustomizedPingTimer _statusPing;

private readonly CustomizedPingTimer _serversPing;

private readonly ServiceDiagnosticLogsContext _serviceDiagnosticLogsContext = new ServiceDiagnosticLogsContext { EnableMessageLog = false };
private readonly ServiceDiagnosticLogsContext _serviceDiagnosticLogsContext = new() { EnableMessageLog = false };

private (int count, DateTime? last) _inactiveInfo;

Expand Down Expand Up @@ -256,7 +256,7 @@ public async IAsyncEnumerable<GroupMember> ListConnectionsInGroupAsync(string gr
{
throw new ArgumentException($"'{nameof(groupName)}' cannot be null or whitespace.", nameof(groupName));
}
if (top != null && top <= 0)
if (top is not null and <= 0)
{
throw new ArgumentException($"'{nameof(top)}' must be greater than 0.", nameof(top));
}
Expand Down Expand Up @@ -487,7 +487,7 @@ protected async Task RemoveConnectionAsync(IServiceConnection c, GracefulShutdow

private async Task StartStatusPing()
{
await this.ConnectionInitializedTask.ConfigureAwait(false);
await ConnectionInitializedTask.ConfigureAwait(false);
_statusPing.Start();
}

Expand Down Expand Up @@ -607,7 +607,7 @@ private async Task RestartFixedServiceConnectionCoreAsync(int index)
return;
}

Func<Task<bool>> tryNewConnection = async () =>
async Task<bool> tryNewConnection()
{
var connection = CreateServiceConnectionCore(InitialConnectionType);
ReplaceFixedConnection(index, connection);
Expand All @@ -616,7 +616,7 @@ private async Task RestartFixedServiceConnectionCoreAsync(int index)
await connection.ConnectionInitializedTask;

return connection.Status == ServiceConnectionStatus.Connected;
};
}
await _backOffPolicy.CallProbeWithBackOffAsync(tryNewConnection, GetRetryDelay);
}

Expand Down Expand Up @@ -669,7 +669,7 @@ private void OnConnectionStatusChanged(StatusChange obj)

private IEnumerable<IServiceConnection> CreateFixedServiceConnection(int count)
{
for (int i = 0; i < count; i++)
for (var i = 0; i < count; i++)
{
yield return CreateServiceConnectionCore(InitialConnectionType);
}
Expand Down Expand Up @@ -704,7 +704,7 @@ private async Task SafeWriteAsync(ServiceMessage serviceMessage)

protected internal sealed class CustomizedPingTimer : IDisposable
{
private readonly object _lock = new object();
private readonly object _lock = new();

private readonly long _defaultPingTicks;

Expand Down
Loading

0 comments on commit 71f2158

Please sign in to comment.