2022-10-27 13:34:24 +08: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.
|
|
|
|
|
|
|
|
using System;
|
|
|
|
using System.Threading;
|
|
|
|
using System.Threading.Tasks;
|
|
|
|
using osu.Framework.Bindables;
|
|
|
|
using osu.Framework.Extensions.TypeExtensions;
|
|
|
|
using osu.Framework.Logging;
|
|
|
|
using osu.Game.Online.API;
|
|
|
|
|
|
|
|
namespace osu.Game.Online
|
|
|
|
{
|
2022-11-02 10:49:04 +08:00
|
|
|
public abstract class PersistentEndpointClientConnector : IDisposable
|
2022-10-27 13:34:24 +08:00
|
|
|
{
|
|
|
|
/// <summary>
|
2022-11-02 12:15:34 +08:00
|
|
|
/// Whether the managed connection is currently connected. When <c>true</c> use <see cref="CurrentConnection"/> to access the connection.
|
2022-10-27 13:34:24 +08:00
|
|
|
/// </summary>
|
|
|
|
public IBindable<bool> IsConnected => isConnected;
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
/// The current connection opened by this connector.
|
|
|
|
/// </summary>
|
2022-11-02 10:43:22 +08:00
|
|
|
public PersistentEndpointClient? CurrentConnection { get; private set; }
|
2022-10-27 13:34:24 +08:00
|
|
|
|
2022-11-02 09:04:24 +08:00
|
|
|
protected readonly IAPIProvider API;
|
|
|
|
|
|
|
|
private readonly IBindable<APIState> apiState = new Bindable<APIState>();
|
2022-10-27 13:34:24 +08:00
|
|
|
private readonly Bindable<bool> isConnected = new Bindable<bool>();
|
|
|
|
private readonly SemaphoreSlim connectionLock = new SemaphoreSlim(1);
|
|
|
|
private CancellationTokenSource connectCancelSource = new CancellationTokenSource();
|
2022-11-04 18:36:24 +08:00
|
|
|
private bool started;
|
2022-10-27 13:34:24 +08:00
|
|
|
|
|
|
|
/// <summary>
|
2022-11-02 12:15:34 +08:00
|
|
|
/// Constructs a new <see cref="PersistentEndpointClientConnector"/>.
|
2022-10-27 13:34:24 +08:00
|
|
|
/// </summary>
|
|
|
|
/// <param name="api"> An API provider used to react to connection state changes.</param>
|
2022-11-02 10:43:22 +08:00
|
|
|
protected PersistentEndpointClientConnector(IAPIProvider api)
|
2022-10-27 13:34:24 +08:00
|
|
|
{
|
2022-11-02 09:04:24 +08:00
|
|
|
API = api;
|
2022-10-27 13:34:24 +08:00
|
|
|
apiState.BindTo(api.State);
|
2022-11-04 18:36:24 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
/// Attempts to connect and begins processing messages from the remote endpoint.
|
|
|
|
/// </summary>
|
|
|
|
public void Start()
|
|
|
|
{
|
|
|
|
if (started)
|
|
|
|
return;
|
|
|
|
|
2022-10-27 13:34:24 +08:00
|
|
|
apiState.BindValueChanged(_ => Task.Run(connectIfPossible), true);
|
2022-11-04 18:36:24 +08:00
|
|
|
started = true;
|
2022-10-27 13:34:24 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
public Task Reconnect()
|
|
|
|
{
|
|
|
|
Logger.Log($"{ClientName} reconnecting...", LoggingTarget.Network);
|
|
|
|
return Task.Run(connectIfPossible);
|
|
|
|
}
|
|
|
|
|
|
|
|
private async Task connectIfPossible()
|
|
|
|
{
|
|
|
|
switch (apiState.Value)
|
|
|
|
{
|
|
|
|
case APIState.Failing:
|
|
|
|
case APIState.Offline:
|
|
|
|
await disconnect(true);
|
|
|
|
break;
|
|
|
|
|
|
|
|
case APIState.Online:
|
|
|
|
await connect();
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
private async Task connect()
|
|
|
|
{
|
|
|
|
cancelExistingConnect();
|
|
|
|
|
|
|
|
if (!await connectionLock.WaitAsync(10000).ConfigureAwait(false))
|
|
|
|
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.
|
|
|
|
await disconnect(false).ConfigureAwait(false);
|
|
|
|
|
|
|
|
// 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.
|
|
|
|
CurrentConnection = await BuildConnectionAsync(cancellationToken).ConfigureAwait(false);
|
|
|
|
CurrentConnection.Closed += ex => onConnectionClosed(ex, cancellationToken);
|
|
|
|
|
|
|
|
cancellationToken.ThrowIfCancellationRequested();
|
|
|
|
|
2022-10-28 16:53:28 +08:00
|
|
|
await CurrentConnection.ConnectAsync(cancellationToken).ConfigureAwait(false);
|
2022-10-27 13:34:24 +08:00
|
|
|
|
|
|
|
Logger.Log($"{ClientName} connected!", LoggingTarget.Network);
|
|
|
|
isConnected.Value = true;
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
catch (OperationCanceledException)
|
|
|
|
{
|
|
|
|
//connection process was cancelled.
|
|
|
|
throw;
|
|
|
|
}
|
|
|
|
catch (Exception e)
|
|
|
|
{
|
|
|
|
await handleErrorAndDelay(e, cancellationToken).ConfigureAwait(false);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
finally
|
|
|
|
{
|
|
|
|
connectionLock.Release();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
/// Handles an exception and delays an async flow.
|
|
|
|
/// </summary>
|
|
|
|
private async Task handleErrorAndDelay(Exception exception, CancellationToken cancellationToken)
|
|
|
|
{
|
|
|
|
Logger.Log($"{ClientName} connect attempt failed: {exception.Message}", LoggingTarget.Network);
|
|
|
|
await Task.Delay(5000, cancellationToken).ConfigureAwait(false);
|
|
|
|
}
|
|
|
|
|
2022-11-02 12:15:34 +08:00
|
|
|
/// <summary>
|
|
|
|
/// Creates a new <see cref="PersistentEndpointClient"/>.
|
|
|
|
/// </summary>
|
|
|
|
/// <param name="cancellationToken">A cancellation token to stop the process.</param>
|
2022-11-02 10:43:22 +08:00
|
|
|
protected abstract Task<PersistentEndpointClient> BuildConnectionAsync(CancellationToken cancellationToken);
|
2022-10-27 13:34:24 +08:00
|
|
|
|
|
|
|
private async Task onConnectionClosed(Exception? ex, CancellationToken cancellationToken)
|
|
|
|
{
|
2022-11-18 12:45:46 +08:00
|
|
|
bool hasBeenCancelled = cancellationToken.IsCancellationRequested;
|
|
|
|
|
|
|
|
await disconnect(true);
|
2022-10-27 13:34:24 +08:00
|
|
|
|
|
|
|
if (ex != null)
|
|
|
|
await handleErrorAndDelay(ex, cancellationToken).ConfigureAwait(false);
|
|
|
|
else
|
|
|
|
Logger.Log($"{ClientName} disconnected", LoggingTarget.Network);
|
|
|
|
|
|
|
|
// make sure a disconnect wasn't triggered (and this is still the active connection).
|
2022-11-18 12:45:46 +08:00
|
|
|
if (!hasBeenCancelled)
|
2022-10-27 13:34:24 +08:00
|
|
|
await Task.Run(connect, default).ConfigureAwait(false);
|
|
|
|
}
|
|
|
|
|
|
|
|
private async Task disconnect(bool takeLock)
|
|
|
|
{
|
|
|
|
cancelExistingConnect();
|
|
|
|
|
|
|
|
if (takeLock)
|
|
|
|
{
|
|
|
|
if (!await connectionLock.WaitAsync(10000).ConfigureAwait(false))
|
|
|
|
throw new TimeoutException("Could not obtain a lock to disconnect. A previous attempt is likely stuck.");
|
|
|
|
}
|
|
|
|
|
|
|
|
try
|
|
|
|
{
|
|
|
|
if (CurrentConnection != null)
|
|
|
|
await CurrentConnection.DisposeAsync().ConfigureAwait(false);
|
|
|
|
}
|
|
|
|
finally
|
|
|
|
{
|
2022-11-18 12:45:46 +08:00
|
|
|
isConnected.Value = false;
|
2022-10-27 13:34:24 +08:00
|
|
|
CurrentConnection = null;
|
2022-11-18 12:45:46 +08:00
|
|
|
|
2022-10-27 13:34:24 +08:00
|
|
|
if (takeLock)
|
|
|
|
connectionLock.Release();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
private void cancelExistingConnect()
|
|
|
|
{
|
|
|
|
connectCancelSource.Cancel();
|
|
|
|
connectCancelSource = new CancellationTokenSource();
|
|
|
|
}
|
|
|
|
|
|
|
|
protected virtual string ClientName => GetType().ReadableName();
|
|
|
|
|
|
|
|
public override string ToString() => $"{ClientName} ({(IsConnected.Value ? "connected" : "not connected")})";
|
|
|
|
|
2022-10-28 17:08:08 +08:00
|
|
|
private bool isDisposed;
|
|
|
|
|
|
|
|
protected virtual void Dispose(bool isDisposing)
|
2022-10-27 13:34:24 +08:00
|
|
|
{
|
2022-10-28 17:08:08 +08:00
|
|
|
if (isDisposed)
|
|
|
|
return;
|
|
|
|
|
2022-10-27 13:34:24 +08:00
|
|
|
apiState.UnbindAll();
|
|
|
|
cancelExistingConnect();
|
2022-10-28 17:08:08 +08:00
|
|
|
|
|
|
|
isDisposed = true;
|
|
|
|
}
|
|
|
|
|
|
|
|
public void Dispose()
|
|
|
|
{
|
|
|
|
Dispose(true);
|
|
|
|
GC.SuppressFinalize(this);
|
2022-10-27 13:34:24 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|