PluralKit/Myriad/Gateway/State/ShardStateManager.cs

246 lines
7.4 KiB
C#
Raw Permalink Normal View History

2021-04-29 09:10:19 +00:00
using System.Net.WebSockets;
using System.Text.Json;
using Myriad.Gateway.State;
using Myriad.Types;
using Serilog;
namespace Myriad.Gateway;
public class ShardStateManager
2021-04-29 09:10:19 +00:00
{
private readonly HeartbeatWorker _heartbeatWorker = new();
private readonly ShardInfo _info;
private readonly JsonSerializerOptions _jsonSerializerOptions;
private readonly ILogger _logger;
private bool _hasReceivedHeartbeatAck;
private DateTimeOffset? _lastHeartbeatSent;
private int? _lastSeq;
private TimeSpan? _latency;
private string? _sessionId;
public ShardStateManager(ShardInfo info, JsonSerializerOptions jsonSerializerOptions, ILogger logger)
2021-04-29 09:10:19 +00:00
{
_info = info;
_jsonSerializerOptions = jsonSerializerOptions;
_logger = logger.ForContext<ShardStateManager>();
}
2021-04-29 09:10:19 +00:00
public ShardState State { get; private set; } = ShardState.Disconnected;
2021-08-27 15:03:47 +00:00
public TimeSpan? Latency => _latency;
public User? User { get; private set; }
public ApplicationPartial? Application { get; private set; }
2021-04-29 09:10:19 +00:00
public Func<Task> SendIdentify { get; init; }
public Func<(string SessionId, int? LastSeq), Task> SendResume { get; init; }
public Func<int?, Task> SendHeartbeat { get; init; }
public Func<WebSocketCloseStatus, TimeSpan, Task> Reconnect { get; init; }
public Func<Task> Connect { get; init; }
public Func<IGatewayEvent, Task> HandleEvent { get; init; }
2021-04-29 09:10:19 +00:00
public event Action<TimeSpan> OnHeartbeatReceived;
2021-08-27 15:03:47 +00:00
public Task HandleConnectionOpened()
{
State = ShardState.Handshaking;
return Task.CompletedTask;
}
2021-04-29 09:10:19 +00:00
public async Task HandleConnectionClosed()
{
_latency = null;
await _heartbeatWorker.Stop();
}
2021-04-29 09:10:19 +00:00
public async Task HandlePacketReceived(GatewayPacket packet)
{
switch (packet.Opcode)
2021-04-29 09:10:19 +00:00
{
case GatewayOpcode.Hello:
var hello = DeserializePayload<GatewayHello>(packet);
await HandleHello(hello);
break;
2021-04-29 09:10:19 +00:00
case GatewayOpcode.Heartbeat:
await HandleHeartbeatRequest();
break;
2021-08-27 15:03:47 +00:00
case GatewayOpcode.HeartbeatAck:
await HandleHeartbeatAck();
break;
2021-04-29 09:10:19 +00:00
case GatewayOpcode.Reconnect:
{
await HandleReconnect();
2021-04-29 09:10:19 +00:00
break;
}
2021-04-29 09:10:19 +00:00
case GatewayOpcode.InvalidSession:
{
var canResume = DeserializePayload<bool>(packet);
await HandleInvalidSession(canResume);
2021-04-29 09:10:19 +00:00
break;
}
2021-08-27 15:03:47 +00:00
case GatewayOpcode.Dispatch:
_lastSeq = packet.Sequence;
2021-08-27 15:03:47 +00:00
var evt = DeserializeEvent(packet.EventType!, (JsonElement)packet.Payload!);
if (evt != null)
{
if (evt is ReadyEvent ready)
await HandleReady(ready);
2021-04-29 09:10:19 +00:00
if (evt is ResumedEvent)
await HandleResumed();
2021-08-27 15:03:47 +00:00
await HandleEvent(evt);
}
2021-04-29 09:10:19 +00:00
break;
2021-04-29 09:10:19 +00:00
}
}
private async Task HandleHello(GatewayHello hello)
{
var interval = TimeSpan.FromMilliseconds(hello.HeartbeatInterval);
2021-04-29 09:10:19 +00:00
_hasReceivedHeartbeatAck = true;
await _heartbeatWorker.Start(interval, HandleHeartbeatTimer);
await IdentifyOrResume();
}
private async Task IdentifyOrResume()
{
State = ShardState.Identifying;
if (_sessionId != null)
2021-04-29 09:10:19 +00:00
{
_logger.Information("Shard {ShardId}: Received Hello, attempting to resume (seq {LastSeq})",
_info.ShardId, _lastSeq);
await SendResume((_sessionId!, _lastSeq));
2021-04-29 09:10:19 +00:00
}
else
2021-04-29 09:10:19 +00:00
{
_logger.Information("Shard {ShardId}: Received Hello, identifying",
_info.ShardId);
2021-08-27 15:03:47 +00:00
await SendIdentify();
2021-04-29 09:10:19 +00:00
}
}
private Task HandleHeartbeatAck()
{
_hasReceivedHeartbeatAck = true;
_latency = DateTimeOffset.UtcNow - _lastHeartbeatSent;
OnHeartbeatReceived?.Invoke(_latency!.Value);
_logger.Debug("Shard {ShardId}: Received Heartbeat (latency {Latency:N2} ms)",
_info.ShardId, _latency?.TotalMilliseconds);
return Task.CompletedTask;
}
2021-08-27 15:03:47 +00:00
private async Task HandleInvalidSession(bool canResume)
{
if (!canResume)
2021-04-29 09:10:19 +00:00
{
_sessionId = null;
_lastSeq = null;
2021-04-29 09:10:19 +00:00
}
2021-08-27 15:03:47 +00:00
_logger.Information("Shard {ShardId}: Received Invalid Session (can resume? {CanResume})",
_info.ShardId, canResume);
2021-04-29 09:10:19 +00:00
var delay = TimeSpan.FromMilliseconds(new Random().Next(1000, 5000));
await DoReconnect(WebSocketCloseStatus.NormalClosure, delay);
}
2021-04-29 09:10:19 +00:00
private async Task HandleReconnect()
{
_logger.Information("Shard {ShardId}: Received Reconnect", _info.ShardId);
// close code 1000 kills the session, so can't reconnect
// we use 1005 (no error specified) instead
await DoReconnect(WebSocketCloseStatus.Empty, TimeSpan.FromSeconds(1));
}
2021-04-29 09:10:19 +00:00
private Task HandleReady(ReadyEvent ready)
{
_logger.Information("Shard {ShardId}: Received Ready", _info.ShardId);
2021-04-29 09:10:19 +00:00
_sessionId = ready.SessionId;
State = ShardState.Connected;
User = ready.User;
Application = ready.Application;
return Task.CompletedTask;
}
2021-04-29 09:10:19 +00:00
private Task HandleResumed()
{
_logger.Information("Shard {ShardId}: Received Resume", _info.ShardId);
State = ShardState.Connected;
return Task.CompletedTask;
}
2021-04-29 09:10:19 +00:00
private async Task HandleHeartbeatRequest()
{
await SendHeartbeatInternal();
}
private async Task SendHeartbeatInternal()
{
await SendHeartbeat(_lastSeq);
_lastHeartbeatSent = DateTimeOffset.UtcNow;
}
private async Task HandleHeartbeatTimer()
{
if (!_hasReceivedHeartbeatAck)
2021-04-29 09:10:19 +00:00
{
_logger.Warning("Shard {ShardId}: Heartbeat worker timed out", _info.ShardId);
await DoReconnect(WebSocketCloseStatus.ProtocolError, TimeSpan.Zero);
return;
2021-04-29 09:10:19 +00:00
}
await SendHeartbeatInternal();
}
private async Task DoReconnect(WebSocketCloseStatus closeStatus, TimeSpan delay)
{
State = ShardState.Reconnecting;
await Reconnect(closeStatus, delay);
}
private T DeserializePayload<T>(GatewayPacket packet)
{
var packetPayload = (JsonElement)packet.Payload!;
return JsonSerializer.Deserialize<T>(packetPayload.GetRawText(), _jsonSerializerOptions)!;
}
private IGatewayEvent? DeserializeEvent(string eventType, JsonElement payload)
{
if (!IGatewayEvent.EventTypes.TryGetValue(eventType, out var clrType))
2021-04-29 09:10:19 +00:00
{
_logger.Debug("Shard {ShardId}: Received unknown event type {EventType}", _info.ShardId, eventType);
return null;
2021-04-29 09:10:19 +00:00
}
try
2021-04-29 09:10:19 +00:00
{
_logger.Verbose("Shard {ShardId}: Deserializing {EventType} to {ClrType}", _info.ShardId, eventType,
clrType);
return JsonSerializer.Deserialize(payload.GetRawText(), clrType, _jsonSerializerOptions)
as IGatewayEvent;
2021-04-29 09:10:19 +00:00
}
catch (JsonException e)
2021-04-29 09:10:19 +00:00
{
_logger.Error(e, "Shard {ShardId}: Error deserializing event {EventType} to {ClrType}", _info.ShardId,
eventType, clrType);
return null;
2021-04-29 09:10:19 +00:00
}
}
}