2021-02-08 22:52:35 +00:00
|
|
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
|
|
|
|
// See the LICENCE file in the repository root for full licence text.
|
|
|
|
|
|
|
|
#nullable enable
|
|
|
|
|
|
|
|
using System;
|
2021-11-11 05:04:17 +00:00
|
|
|
using System.Collections.Generic;
|
2021-02-08 22:52:35 +00:00
|
|
|
using System.Threading;
|
|
|
|
using System.Threading.Tasks;
|
|
|
|
using Microsoft.AspNetCore.SignalR.Client;
|
|
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
|
|
using Newtonsoft.Json;
|
|
|
|
using osu.Framework;
|
|
|
|
using osu.Framework.Bindables;
|
|
|
|
using osu.Framework.Logging;
|
|
|
|
using osu.Game.Online.API;
|
|
|
|
|
|
|
|
namespace osu.Game.Online
|
|
|
|
{
|
2021-02-15 07:31:00 +00:00
|
|
|
public class HubClientConnector : IHubClientConnector
|
2021-02-08 22:52:35 +00:00
|
|
|
{
|
|
|
|
/// <summary>
|
2021-02-11 09:39:06 +00:00
|
|
|
/// Invoked whenever a new hub connection is built, to configure it before it's started.
|
2021-02-08 22:52:35 +00:00
|
|
|
/// </summary>
|
2021-02-15 07:31:00 +00:00
|
|
|
public Action<HubConnection>? ConfigureConnection { get; set; }
|
2021-02-08 22:52:35 +00:00
|
|
|
|
|
|
|
private readonly string clientName;
|
|
|
|
private readonly string endpoint;
|
2021-02-14 14:31:57 +00:00
|
|
|
private readonly string versionHash;
|
2021-08-02 05:44:51 +00:00
|
|
|
private readonly bool preferMessagePack;
|
2021-02-11 09:32:54 +00:00
|
|
|
private readonly IAPIProvider api;
|
2021-02-08 22:52:35 +00:00
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
/// The current connection opened by this connector.
|
|
|
|
/// </summary>
|
|
|
|
public HubConnection? CurrentConnection { get; private set; }
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
/// Whether this is connected to the hub, use <see cref="CurrentConnection"/> to access the connection, if this is <c>true</c>.
|
|
|
|
/// </summary>
|
|
|
|
public IBindable<bool> IsConnected => isConnected;
|
|
|
|
|
|
|
|
private readonly Bindable<bool> isConnected = new Bindable<bool>();
|
|
|
|
private readonly SemaphoreSlim connectionLock = new SemaphoreSlim(1);
|
|
|
|
private CancellationTokenSource connectCancelSource = new CancellationTokenSource();
|
|
|
|
|
|
|
|
private readonly IBindable<APIState> apiState = new Bindable<APIState>();
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
/// Constructs a new <see cref="HubClientConnector"/>.
|
|
|
|
/// </summary>
|
|
|
|
/// <param name="clientName">The name of the client this connector connects for, used for logging.</param>
|
|
|
|
/// <param name="endpoint">The endpoint to the hub.</param>
|
2021-02-11 09:32:54 +00:00
|
|
|
/// <param name="api"> An API provider used to react to connection state changes.</param>
|
2021-02-14 14:31:57 +00:00
|
|
|
/// <param name="versionHash">The hash representing the current game version, used for verification purposes.</param>
|
2021-08-02 05:44:51 +00:00
|
|
|
/// <param name="preferMessagePack">Whether to use MessagePack for serialisation if available on this platform.</param>
|
|
|
|
public HubClientConnector(string clientName, string endpoint, IAPIProvider api, string versionHash, bool preferMessagePack = true)
|
2021-02-08 22:52:35 +00:00
|
|
|
{
|
|
|
|
this.clientName = clientName;
|
|
|
|
this.endpoint = endpoint;
|
2021-02-09 04:53:22 +00:00
|
|
|
this.api = api;
|
2021-02-14 14:31:57 +00:00
|
|
|
this.versionHash = versionHash;
|
2021-08-02 05:44:51 +00:00
|
|
|
this.preferMessagePack = preferMessagePack;
|
2021-02-09 04:53:22 +00:00
|
|
|
|
2021-02-11 09:32:54 +00:00
|
|
|
apiState.BindTo(api.State);
|
|
|
|
apiState.BindValueChanged(state =>
|
2021-02-08 22:52:35 +00:00
|
|
|
{
|
2021-02-11 09:32:54 +00:00
|
|
|
switch (state.NewValue)
|
2021-02-08 22:52:35 +00:00
|
|
|
{
|
2021-02-11 09:32:54 +00:00
|
|
|
case APIState.Failing:
|
|
|
|
case APIState.Offline:
|
|
|
|
Task.Run(() => disconnect(true));
|
|
|
|
break;
|
|
|
|
|
|
|
|
case APIState.Online:
|
|
|
|
Task.Run(connect);
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
}, true);
|
2021-02-08 22:52:35 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
private async Task connect()
|
|
|
|
{
|
|
|
|
cancelExistingConnect();
|
|
|
|
|
2021-03-08 03:57:16 +00:00
|
|
|
if (!await connectionLock.WaitAsync(10000).ConfigureAwait(false))
|
2021-02-08 22:52:35 +00:00
|
|
|
throw new TimeoutException("Could not obtain a lock to connect. A previous attempt is likely stuck.");
|
|
|
|
|
|
|
|
try
|
|
|
|
{
|
|
|
|
while (apiState.Value == APIState.Online)
|
|
|
|
{
|
|
|
|
// ensure any previous connection was disposed.
|
|
|
|
// this will also create a new cancellation token source.
|
2021-03-08 03:57:16 +00:00
|
|
|
await disconnect(false).ConfigureAwait(false);
|
2021-02-08 22:52:35 +00:00
|
|
|
|
|
|
|
// this token will be valid for the scope of this connection.
|
|
|
|
// if cancelled, we can be sure that a disconnect or reconnect is handled elsewhere.
|
|
|
|
var cancellationToken = connectCancelSource.Token;
|
|
|
|
|
|
|
|
cancellationToken.ThrowIfCancellationRequested();
|
|
|
|
|
|
|
|
Logger.Log($"{clientName} connecting...", LoggingTarget.Network);
|
|
|
|
|
|
|
|
try
|
|
|
|
{
|
|
|
|
// importantly, rebuild the connection each attempt to get an updated access token.
|
2021-02-11 07:49:16 +00:00
|
|
|
CurrentConnection = buildConnection(cancellationToken);
|
2021-02-08 22:52:35 +00:00
|
|
|
|
2021-03-08 03:57:16 +00:00
|
|
|
await CurrentConnection.StartAsync(cancellationToken).ConfigureAwait(false);
|
2021-02-08 22:52:35 +00:00
|
|
|
|
|
|
|
Logger.Log($"{clientName} connected!", LoggingTarget.Network);
|
|
|
|
isConnected.Value = true;
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
catch (OperationCanceledException)
|
|
|
|
{
|
|
|
|
//connection process was cancelled.
|
|
|
|
throw;
|
|
|
|
}
|
|
|
|
catch (Exception e)
|
|
|
|
{
|
2021-07-28 11:46:02 +00:00
|
|
|
await handleErrorAndDelay(e, cancellationToken).ConfigureAwait(false);
|
2021-02-08 22:52:35 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
finally
|
|
|
|
{
|
|
|
|
connectionLock.Release();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-07-28 11:46:02 +00:00
|
|
|
/// <summary>
|
|
|
|
/// Handles an exception and delays an async flow.
|
|
|
|
/// </summary>
|
|
|
|
private async Task handleErrorAndDelay(Exception exception, CancellationToken cancellationToken)
|
|
|
|
{
|
|
|
|
Logger.Log($"{clientName} connection error: {exception}", LoggingTarget.Network);
|
|
|
|
await Task.Delay(5000, cancellationToken).ConfigureAwait(false);
|
|
|
|
}
|
|
|
|
|
2021-02-11 07:49:16 +00:00
|
|
|
private HubConnection buildConnection(CancellationToken cancellationToken)
|
2021-02-08 22:52:35 +00:00
|
|
|
{
|
|
|
|
var builder = new HubConnectionBuilder()
|
2021-02-14 14:31:57 +00:00
|
|
|
.WithUrl(endpoint, options =>
|
|
|
|
{
|
|
|
|
options.Headers.Add("Authorization", $"Bearer {api.AccessToken}");
|
|
|
|
options.Headers.Add("OsuVersionHash", versionHash);
|
|
|
|
});
|
2021-02-08 22:52:35 +00:00
|
|
|
|
2021-08-02 05:44:51 +00:00
|
|
|
if (RuntimeInfo.SupportsJIT && preferMessagePack)
|
2021-08-19 08:41:50 +00:00
|
|
|
{
|
|
|
|
builder.AddMessagePackProtocol(options =>
|
|
|
|
{
|
|
|
|
options.SerializerOptions = SignalRUnionWorkaroundResolver.OPTIONS;
|
|
|
|
});
|
|
|
|
}
|
2021-02-08 22:52:35 +00:00
|
|
|
else
|
|
|
|
{
|
|
|
|
// eventually we will precompile resolvers for messagepack, but this isn't working currently
|
|
|
|
// see https://github.com/neuecc/MessagePack-CSharp/issues/780#issuecomment-768794308.
|
2021-08-02 05:37:47 +00:00
|
|
|
builder.AddNewtonsoftJsonProtocol(options =>
|
|
|
|
{
|
|
|
|
options.PayloadSerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
|
2021-11-11 05:04:17 +00:00
|
|
|
options.PayloadSerializerSettings.Converters = new List<JsonConverter>
|
|
|
|
{
|
|
|
|
new SignalRDerivedTypeWorkaroundJsonConverter(),
|
|
|
|
};
|
2021-08-02 05:37:47 +00:00
|
|
|
});
|
2021-02-08 22:52:35 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
var newConnection = builder.Build();
|
|
|
|
|
2021-02-11 07:49:16 +00:00
|
|
|
ConfigureConnection?.Invoke(newConnection);
|
2021-02-08 22:52:35 +00:00
|
|
|
|
2021-02-11 07:49:16 +00:00
|
|
|
newConnection.Closed += ex => onConnectionClosed(ex, cancellationToken);
|
|
|
|
return newConnection;
|
|
|
|
}
|
2021-02-08 22:52:35 +00:00
|
|
|
|
2021-07-28 11:46:02 +00:00
|
|
|
private async Task onConnectionClosed(Exception? ex, CancellationToken cancellationToken)
|
2021-02-11 07:49:16 +00:00
|
|
|
{
|
|
|
|
isConnected.Value = false;
|
2021-02-08 22:52:35 +00:00
|
|
|
|
2021-07-28 11:46:02 +00:00
|
|
|
if (ex != null)
|
|
|
|
await handleErrorAndDelay(ex, cancellationToken).ConfigureAwait(false);
|
|
|
|
else
|
|
|
|
Logger.Log($"{clientName} disconnected", LoggingTarget.Network);
|
2021-02-08 22:52:35 +00:00
|
|
|
|
2021-02-11 07:49:16 +00:00
|
|
|
// make sure a disconnect wasn't triggered (and this is still the active connection).
|
|
|
|
if (!cancellationToken.IsCancellationRequested)
|
2021-07-28 11:46:02 +00:00
|
|
|
await Task.Run(connect, default).ConfigureAwait(false);
|
2021-02-08 22:52:35 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
private async Task disconnect(bool takeLock)
|
|
|
|
{
|
|
|
|
cancelExistingConnect();
|
|
|
|
|
|
|
|
if (takeLock)
|
|
|
|
{
|
2021-03-08 03:57:16 +00:00
|
|
|
if (!await connectionLock.WaitAsync(10000).ConfigureAwait(false))
|
2021-02-08 22:52:35 +00:00
|
|
|
throw new TimeoutException("Could not obtain a lock to disconnect. A previous attempt is likely stuck.");
|
|
|
|
}
|
|
|
|
|
|
|
|
try
|
|
|
|
{
|
|
|
|
if (CurrentConnection != null)
|
2021-03-08 03:57:16 +00:00
|
|
|
await CurrentConnection.DisposeAsync().ConfigureAwait(false);
|
2021-02-08 22:52:35 +00:00
|
|
|
}
|
|
|
|
finally
|
|
|
|
{
|
|
|
|
CurrentConnection = null;
|
|
|
|
if (takeLock)
|
|
|
|
connectionLock.Release();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
private void cancelExistingConnect()
|
|
|
|
{
|
|
|
|
connectCancelSource.Cancel();
|
|
|
|
connectCancelSource = new CancellationTokenSource();
|
|
|
|
}
|
|
|
|
|
|
|
|
public override string ToString() => $"Connector for {clientName} ({(IsConnected.Value ? "connected" : "not connected")}";
|
|
|
|
|
2021-02-09 04:53:22 +00:00
|
|
|
public void Dispose()
|
2021-02-08 22:52:35 +00:00
|
|
|
{
|
2021-02-09 04:53:22 +00:00
|
|
|
apiState.UnbindAll();
|
2021-02-08 22:52:35 +00:00
|
|
|
cancelExistingConnect();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|