PluralKit/Myriad/Gateway/ShardConnection.cs

122 lines
3.9 KiB
C#
Raw Normal View History

2020-12-22 12:15:26 +00:00
using System;
using System.Net.WebSockets;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Serilog;
namespace Myriad.Gateway
{
public class ShardConnection: IAsyncDisposable
{
2021-04-29 09:10:19 +00:00
private ClientWebSocket? _client;
2020-12-22 12:15:26 +00:00
private readonly ILogger _logger;
2021-04-29 09:10:19 +00:00
private readonly ShardPacketSerializer _serializer;
2021-01-30 00:07:43 +00:00
2021-04-29 09:10:19 +00:00
public WebSocketState State => _client?.State ?? WebSocketState.Closed;
public WebSocketCloseStatus? CloseStatus => _client?.CloseStatus;
public string? CloseStatusDescription => _client?.CloseStatusDescription;
public ShardConnection(JsonSerializerOptions jsonSerializerOptions, ILogger logger)
2020-12-22 12:15:26 +00:00
{
2021-04-29 09:10:19 +00:00
_logger = logger.ForContext<ShardConnection>();
_serializer = new(jsonSerializerOptions);
2020-12-22 12:15:26 +00:00
}
2021-04-29 09:10:19 +00:00
public async Task Connect(string url, CancellationToken ct)
2020-12-22 12:15:26 +00:00
{
2021-04-29 09:10:19 +00:00
_client?.Dispose();
_client = new ClientWebSocket();
2021-01-30 00:07:43 +00:00
2021-04-29 09:10:19 +00:00
await _client.ConnectAsync(GetConnectionUri(url), ct);
2020-12-22 12:15:26 +00:00
}
2021-04-29 09:10:19 +00:00
public async Task Disconnect(WebSocketCloseStatus closeStatus, string? reason)
2020-12-22 12:15:26 +00:00
{
2021-04-29 09:10:19 +00:00
await CloseInner(closeStatus, reason);
2020-12-22 12:15:26 +00:00
}
2021-04-29 09:10:19 +00:00
public async Task Send(GatewayPacket packet)
2020-12-22 12:15:26 +00:00
{
// from `ManagedWebSocket.s_validSendStates`
if (_client is not {State: WebSocketState.Open or WebSocketState.CloseReceived})
2021-04-29 09:10:19 +00:00
return;
2020-12-22 12:15:26 +00:00
try
{
2021-04-29 09:10:19 +00:00
await _serializer.WritePacket(_client, packet);
2020-12-22 12:15:26 +00:00
}
catch (Exception e)
{
2021-04-29 09:10:19 +00:00
_logger.Error(e, "Error sending WebSocket message");
2020-12-22 12:15:26 +00:00
}
}
2021-04-29 09:10:19 +00:00
public async ValueTask DisposeAsync()
2020-12-22 12:15:26 +00:00
{
2021-04-29 09:10:19 +00:00
await CloseInner(WebSocketCloseStatus.NormalClosure, null);
_client?.Dispose();
2020-12-22 12:15:26 +00:00
}
2021-04-29 09:10:19 +00:00
public async Task<GatewayPacket?> Read()
2020-12-22 12:15:26 +00:00
{
// from `ManagedWebSocket.s_validReceiveStates`
if (_client is not {State: WebSocketState.Open or WebSocketState.CloseSent})
2021-04-29 09:10:19 +00:00
return null;
2021-04-29 09:10:19 +00:00
try
{
var (_, packet) = await _serializer.ReadPacket(_client);
return packet;
}
catch (Exception e)
{
_logger.Error(e, "Error reading from WebSocket");
// force close so we can "reset"
await CloseInner(WebSocketCloseStatus.NormalClosure, null);
2021-04-29 09:10:19 +00:00
}
return null;
2020-12-22 12:15:26 +00:00
}
2021-04-29 09:10:19 +00:00
private Uri GetConnectionUri(string baseUri) => new UriBuilder(baseUri)
{
Query = "v=9&encoding=json"
2021-04-29 09:10:19 +00:00
}.Uri;
2020-12-22 12:15:26 +00:00
2021-04-29 09:10:19 +00:00
private async Task CloseInner(WebSocketCloseStatus closeStatus, string? description)
2020-12-22 12:15:26 +00:00
{
2021-04-29 09:10:19 +00:00
if (_client == null)
return;
var client = _client;
_client = null;
// from `ManagedWebSocket.s_validCloseStates`
if (client.State is WebSocketState.Open or WebSocketState.CloseReceived or WebSocketState.CloseSent)
{
// Close with timeout, mostly to work around https://github.com/dotnet/runtime/issues/51590
var cts = new CancellationTokenSource(TimeSpan.FromSeconds(2));
try
{
await client.CloseAsync(closeStatus, description, cts.Token);
}
catch (Exception e)
{
_logger.Error(e, "Error closing WebSocket connection");
}
}
2021-04-29 09:10:19 +00:00
// This shouldn't need to be wrapped in a try/catch but doing it anyway :/
2021-04-29 09:10:19 +00:00
try
{
client.Dispose();
2021-04-29 09:10:19 +00:00
}
catch (Exception e)
{
_logger.Error(e, "Error disposing WebSocket connection");
2021-04-29 09:10:19 +00:00
}
2020-12-22 12:15:26 +00:00
}
}
}