2020-12-22 12:15:26 +00:00
|
|
|
|
using System;
|
|
|
|
|
using System.Net.WebSockets;
|
|
|
|
|
using System.Text.Json;
|
|
|
|
|
using System.Threading.Tasks;
|
|
|
|
|
|
|
|
|
|
using Myriad.Serialization;
|
|
|
|
|
using Myriad.Types;
|
|
|
|
|
|
|
|
|
|
using Serilog;
|
|
|
|
|
|
|
|
|
|
namespace Myriad.Gateway
|
|
|
|
|
{
|
|
|
|
|
public class Shard: IAsyncDisposable
|
|
|
|
|
{
|
2021-01-30 00:07:43 +00:00
|
|
|
|
private const string LibraryName = "Myriad (for PluralKit)";
|
2020-12-22 12:15:26 +00:00
|
|
|
|
|
|
|
|
|
private readonly JsonSerializerOptions _jsonSerializerOptions =
|
2021-01-30 00:07:43 +00:00
|
|
|
|
new JsonSerializerOptions().ConfigureForMyriad();
|
2020-12-22 12:15:26 +00:00
|
|
|
|
|
|
|
|
|
private readonly ILogger _logger;
|
|
|
|
|
private readonly Uri _uri;
|
|
|
|
|
|
|
|
|
|
private ShardConnection? _conn;
|
|
|
|
|
private TimeSpan? _currentHeartbeatInterval;
|
|
|
|
|
private bool _hasReceivedAck;
|
|
|
|
|
private DateTimeOffset? _lastHeartbeatSent;
|
|
|
|
|
private Task _worker;
|
|
|
|
|
|
2021-01-30 00:07:43 +00:00
|
|
|
|
public ShardInfo ShardInfo { get; private set; }
|
|
|
|
|
public int ShardId => ShardInfo.ShardId;
|
2020-12-22 12:15:26 +00:00
|
|
|
|
public GatewaySettings Settings { get; }
|
|
|
|
|
public ShardSessionInfo SessionInfo { get; private set; }
|
|
|
|
|
public ShardState State { get; private set; }
|
|
|
|
|
public TimeSpan? Latency { get; private set; }
|
|
|
|
|
public User? User { get; private set; }
|
2020-12-24 13:52:44 +00:00
|
|
|
|
public ApplicationPartial? Application { get; private set; }
|
2020-12-22 12:15:26 +00:00
|
|
|
|
|
|
|
|
|
public Func<IGatewayEvent, Task>? OnEventReceived { get; set; }
|
2021-01-30 00:07:43 +00:00
|
|
|
|
public event Action<TimeSpan>? HeartbeatReceived;
|
|
|
|
|
public event Action? SocketOpened;
|
|
|
|
|
public event Action? Resumed;
|
|
|
|
|
public event Action? Ready;
|
|
|
|
|
public event Action<WebSocketCloseStatus, string?>? SocketClosed;
|
2020-12-22 12:15:26 +00:00
|
|
|
|
|
2021-01-30 00:07:43 +00:00
|
|
|
|
public Shard(ILogger logger, Uri uri, GatewaySettings settings, ShardInfo info,
|
2020-12-22 12:15:26 +00:00
|
|
|
|
ShardSessionInfo? sessionInfo = null)
|
|
|
|
|
{
|
2021-01-30 00:07:43 +00:00
|
|
|
|
_logger = logger.ForContext<Shard>();
|
2020-12-22 12:15:26 +00:00
|
|
|
|
_uri = uri;
|
|
|
|
|
|
|
|
|
|
Settings = settings;
|
|
|
|
|
ShardInfo = info;
|
|
|
|
|
SessionInfo = sessionInfo ?? new ShardSessionInfo();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public async ValueTask DisposeAsync()
|
|
|
|
|
{
|
|
|
|
|
if (_conn != null)
|
|
|
|
|
await _conn.DisposeAsync();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public Task Start()
|
|
|
|
|
{
|
|
|
|
|
_worker = MainLoop();
|
|
|
|
|
return Task.CompletedTask;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public async Task UpdateStatus(GatewayStatusUpdate payload)
|
|
|
|
|
{
|
|
|
|
|
if (_conn != null && _conn.State == WebSocketState.Open)
|
|
|
|
|
await _conn!.Send(new GatewayPacket {Opcode = GatewayOpcode.PresenceUpdate, Payload = payload});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private async Task MainLoop()
|
|
|
|
|
{
|
|
|
|
|
while (true)
|
|
|
|
|
try
|
|
|
|
|
{
|
2021-01-30 00:07:43 +00:00
|
|
|
|
_logger.Information("Shard {ShardId}: Connecting...", ShardId);
|
2020-12-22 12:15:26 +00:00
|
|
|
|
|
|
|
|
|
State = ShardState.Connecting;
|
|
|
|
|
await Connect();
|
|
|
|
|
|
2021-01-30 00:07:43 +00:00
|
|
|
|
_logger.Information("Shard {ShardId}: Connected. Entering main loop...", ShardId);
|
2020-12-22 12:15:26 +00:00
|
|
|
|
|
|
|
|
|
// Tick returns false if we need to stop and reconnect
|
|
|
|
|
while (await Tick(_conn!))
|
|
|
|
|
await Task.Delay(TimeSpan.FromMilliseconds(1000));
|
|
|
|
|
|
2021-01-30 00:07:43 +00:00
|
|
|
|
_logger.Information("Shard {ShardId}: Connection closed, reconnecting...", ShardId);
|
2020-12-22 12:15:26 +00:00
|
|
|
|
State = ShardState.Closed;
|
|
|
|
|
}
|
|
|
|
|
catch (Exception e)
|
|
|
|
|
{
|
2021-01-30 00:07:43 +00:00
|
|
|
|
_logger.Error(e, "Shard {ShardId}: Error in shard state handler", ShardId);
|
2020-12-22 12:15:26 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private async Task<bool> Tick(ShardConnection conn)
|
|
|
|
|
{
|
|
|
|
|
if (conn.State != WebSocketState.Connecting && conn.State != WebSocketState.Open)
|
|
|
|
|
return false;
|
|
|
|
|
|
|
|
|
|
if (!await TickHeartbeat(conn))
|
|
|
|
|
// TickHeartbeat returns false if we're disconnecting
|
|
|
|
|
return false;
|
|
|
|
|
|
|
|
|
|
return true;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private async Task<bool> TickHeartbeat(ShardConnection conn)
|
|
|
|
|
{
|
|
|
|
|
// If we don't need to heartbeat, do nothing
|
|
|
|
|
if (_lastHeartbeatSent == null || _currentHeartbeatInterval == null)
|
|
|
|
|
return true;
|
|
|
|
|
|
|
|
|
|
if (DateTimeOffset.UtcNow - _lastHeartbeatSent < _currentHeartbeatInterval)
|
|
|
|
|
return true;
|
|
|
|
|
|
|
|
|
|
// If we haven't received the ack in time, close w/ error
|
|
|
|
|
if (!_hasReceivedAck)
|
|
|
|
|
{
|
|
|
|
|
_logger.Warning(
|
2021-01-30 00:07:43 +00:00
|
|
|
|
"Shard {ShardId}: Did not receive heartbeat Ack from gateway within interval ({HeartbeatInterval})",
|
|
|
|
|
ShardId, _currentHeartbeatInterval);
|
2020-12-22 12:15:26 +00:00
|
|
|
|
State = ShardState.Closing;
|
|
|
|
|
await conn.Disconnect(WebSocketCloseStatus.ProtocolError, "Did not receive ACK in time");
|
|
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Otherwise just send it :)
|
|
|
|
|
await SendHeartbeat(conn);
|
|
|
|
|
_hasReceivedAck = false;
|
|
|
|
|
return true;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private async Task SendHeartbeat(ShardConnection conn)
|
|
|
|
|
{
|
2021-01-30 00:07:43 +00:00
|
|
|
|
_logger.Debug("Shard {ShardId}: Sending heartbeat with seq.no. {LastSequence}",
|
|
|
|
|
ShardId, SessionInfo.LastSequence);
|
2020-12-22 12:15:26 +00:00
|
|
|
|
|
|
|
|
|
await conn.Send(new GatewayPacket {Opcode = GatewayOpcode.Heartbeat, Payload = SessionInfo.LastSequence});
|
|
|
|
|
_lastHeartbeatSent = DateTimeOffset.UtcNow;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private async Task Connect()
|
|
|
|
|
{
|
|
|
|
|
if (_conn != null)
|
|
|
|
|
await _conn.DisposeAsync();
|
|
|
|
|
|
|
|
|
|
_currentHeartbeatInterval = null;
|
|
|
|
|
|
2021-01-30 00:07:43 +00:00
|
|
|
|
_conn = new ShardConnection(_uri, _logger, _jsonSerializerOptions)
|
|
|
|
|
{
|
|
|
|
|
OnReceive = OnReceive,
|
|
|
|
|
OnOpen = () => SocketOpened?.Invoke(),
|
|
|
|
|
OnClose = (closeStatus, message) => SocketClosed?.Invoke(closeStatus, message)
|
|
|
|
|
};
|
2020-12-22 12:15:26 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private async Task OnReceive(GatewayPacket packet)
|
|
|
|
|
{
|
|
|
|
|
switch (packet.Opcode)
|
|
|
|
|
{
|
|
|
|
|
case GatewayOpcode.Hello:
|
|
|
|
|
{
|
|
|
|
|
await HandleHello((JsonElement) packet.Payload!);
|
|
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
case GatewayOpcode.Heartbeat:
|
|
|
|
|
{
|
2021-01-30 00:07:43 +00:00
|
|
|
|
_logger.Debug("Shard {ShardId}: Received heartbeat request from shard, sending Ack", ShardId);
|
2020-12-22 12:15:26 +00:00
|
|
|
|
await _conn!.Send(new GatewayPacket {Opcode = GatewayOpcode.HeartbeatAck});
|
|
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
case GatewayOpcode.HeartbeatAck:
|
|
|
|
|
{
|
|
|
|
|
Latency = DateTimeOffset.UtcNow - _lastHeartbeatSent;
|
2021-01-30 00:07:43 +00:00
|
|
|
|
_logger.Debug("Shard {ShardId}: Received heartbeat Ack with latency {Latency}", ShardId, Latency);
|
|
|
|
|
if (Latency != null)
|
|
|
|
|
HeartbeatReceived?.Invoke(Latency!.Value);
|
2020-12-22 12:15:26 +00:00
|
|
|
|
|
|
|
|
|
_hasReceivedAck = true;
|
|
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
case GatewayOpcode.Reconnect:
|
|
|
|
|
{
|
2021-01-30 00:07:43 +00:00
|
|
|
|
_logger.Information("Shard {ShardId}: Received Reconnect, closing and reconnecting", ShardId);
|
2020-12-22 12:15:26 +00:00
|
|
|
|
await _conn!.Disconnect(WebSocketCloseStatus.Empty, null);
|
|
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
case GatewayOpcode.InvalidSession:
|
|
|
|
|
{
|
|
|
|
|
var canResume = ((JsonElement) packet.Payload!).GetBoolean();
|
|
|
|
|
|
|
|
|
|
// Clear session info before DCing
|
|
|
|
|
if (!canResume)
|
|
|
|
|
SessionInfo = SessionInfo with { Session = null };
|
|
|
|
|
|
|
|
|
|
var delay = TimeSpan.FromMilliseconds(new Random().Next(1000, 5000));
|
|
|
|
|
|
|
|
|
|
_logger.Information(
|
2021-01-30 00:07:43 +00:00
|
|
|
|
"Shard {ShardId}: Received Invalid Session (can resume? {CanResume}), reconnecting after {ReconnectDelay}",
|
|
|
|
|
ShardId, canResume, delay);
|
2020-12-22 12:15:26 +00:00
|
|
|
|
await _conn!.Disconnect(WebSocketCloseStatus.Empty, null);
|
|
|
|
|
|
|
|
|
|
// Will reconnect after exiting this "loop"
|
|
|
|
|
await Task.Delay(delay);
|
|
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
case GatewayOpcode.Dispatch:
|
|
|
|
|
{
|
|
|
|
|
SessionInfo = SessionInfo with { LastSequence = packet.Sequence };
|
|
|
|
|
var evt = DeserializeEvent(packet.EventType!, (JsonElement) packet.Payload!)!;
|
|
|
|
|
|
|
|
|
|
if (evt is ReadyEvent rdy)
|
|
|
|
|
{
|
|
|
|
|
if (State == ShardState.Connecting)
|
|
|
|
|
await HandleReady(rdy);
|
|
|
|
|
else
|
2021-01-30 00:07:43 +00:00
|
|
|
|
_logger.Warning("Shard {ShardId}: Received Ready event in unexpected state {ShardState}, ignoring?",
|
|
|
|
|
ShardId, State);
|
2020-12-22 12:15:26 +00:00
|
|
|
|
}
|
|
|
|
|
else if (evt is ResumedEvent)
|
|
|
|
|
{
|
|
|
|
|
if (State == ShardState.Connecting)
|
|
|
|
|
await HandleResumed();
|
|
|
|
|
else
|
2021-01-30 00:07:43 +00:00
|
|
|
|
_logger.Warning("Shard {ShardId}: Received Resumed event in unexpected state {ShardState}, ignoring?",
|
|
|
|
|
ShardId, State);
|
2020-12-22 12:15:26 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
await HandleEvent(evt);
|
|
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
default:
|
|
|
|
|
{
|
2021-01-30 00:07:43 +00:00
|
|
|
|
_logger.Debug("Shard {ShardId}: Received unknown gateway opcode {Opcode}", ShardId, packet.Opcode);
|
2020-12-22 12:15:26 +00:00
|
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private async Task HandleEvent(IGatewayEvent evt)
|
|
|
|
|
{
|
|
|
|
|
if (OnEventReceived != null)
|
|
|
|
|
await OnEventReceived.Invoke(evt);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
private IGatewayEvent? DeserializeEvent(string eventType, JsonElement data)
|
|
|
|
|
{
|
|
|
|
|
if (!IGatewayEvent.EventTypes.TryGetValue(eventType, out var clrType))
|
|
|
|
|
{
|
2021-01-30 00:07:43 +00:00
|
|
|
|
_logger.Information("Shard {ShardId}: Received unknown event type {EventType}", ShardId, eventType);
|
2020-12-22 12:15:26 +00:00
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
try
|
|
|
|
|
{
|
2021-01-30 00:07:43 +00:00
|
|
|
|
_logger.Verbose("Shard {ShardId}: Deserializing {EventType} to {ClrType}", ShardId, eventType, clrType);
|
2020-12-22 12:15:26 +00:00
|
|
|
|
return JsonSerializer.Deserialize(data.GetRawText(), clrType, _jsonSerializerOptions)
|
|
|
|
|
as IGatewayEvent;
|
|
|
|
|
}
|
|
|
|
|
catch (JsonException e)
|
|
|
|
|
{
|
2021-01-30 00:07:43 +00:00
|
|
|
|
_logger.Error(e, "Shard {ShardId}: Error deserializing event {EventType} to {ClrType}", ShardId, eventType, clrType);
|
2020-12-22 12:15:26 +00:00
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private Task HandleReady(ReadyEvent ready)
|
|
|
|
|
{
|
2021-01-30 00:07:43 +00:00
|
|
|
|
// TODO: when is ready.Shard ever null?
|
|
|
|
|
ShardInfo = ready.Shard ?? new ShardInfo(0, 0);
|
2020-12-22 12:15:26 +00:00
|
|
|
|
SessionInfo = SessionInfo with { Session = ready.SessionId };
|
|
|
|
|
User = ready.User;
|
2020-12-24 13:52:44 +00:00
|
|
|
|
Application = ready.Application;
|
2020-12-22 12:15:26 +00:00
|
|
|
|
State = ShardState.Open;
|
2021-01-30 00:07:43 +00:00
|
|
|
|
|
|
|
|
|
Ready?.Invoke();
|
2020-12-22 12:15:26 +00:00
|
|
|
|
return Task.CompletedTask;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private Task HandleResumed()
|
|
|
|
|
{
|
|
|
|
|
State = ShardState.Open;
|
2021-01-30 00:07:43 +00:00
|
|
|
|
Resumed?.Invoke();
|
2020-12-22 12:15:26 +00:00
|
|
|
|
return Task.CompletedTask;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private async Task HandleHello(JsonElement json)
|
|
|
|
|
{
|
|
|
|
|
var hello = JsonSerializer.Deserialize<GatewayHello>(json.GetRawText(), _jsonSerializerOptions)!;
|
2021-01-30 00:07:43 +00:00
|
|
|
|
_logger.Debug("Shard {ShardId}: Received Hello with interval {Interval} ms", ShardId, hello.HeartbeatInterval);
|
2020-12-22 12:15:26 +00:00
|
|
|
|
_currentHeartbeatInterval = TimeSpan.FromMilliseconds(hello.HeartbeatInterval);
|
|
|
|
|
|
|
|
|
|
await SendHeartbeat(_conn!);
|
|
|
|
|
|
|
|
|
|
await SendIdentifyOrResume();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private async Task SendIdentifyOrResume()
|
|
|
|
|
{
|
|
|
|
|
if (SessionInfo.Session != null && SessionInfo.LastSequence != null)
|
|
|
|
|
await SendResume(SessionInfo.Session, SessionInfo.LastSequence!.Value);
|
|
|
|
|
else
|
|
|
|
|
await SendIdentify();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private async Task SendIdentify()
|
|
|
|
|
{
|
2021-01-30 00:07:43 +00:00
|
|
|
|
_logger.Information("Shard {ShardId}: Sending gateway Identify for shard {@ShardInfo}", ShardId, ShardInfo);
|
2020-12-22 12:15:26 +00:00
|
|
|
|
await _conn!.Send(new GatewayPacket
|
|
|
|
|
{
|
|
|
|
|
Opcode = GatewayOpcode.Identify,
|
|
|
|
|
Payload = new GatewayIdentify
|
|
|
|
|
{
|
|
|
|
|
Token = Settings.Token,
|
|
|
|
|
Properties = new GatewayIdentify.ConnectionProperties
|
|
|
|
|
{
|
|
|
|
|
Browser = LibraryName, Device = LibraryName, Os = Environment.OSVersion.ToString()
|
|
|
|
|
},
|
|
|
|
|
Intents = Settings.Intents,
|
|
|
|
|
Shard = ShardInfo
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private async Task SendResume(string session, int lastSequence)
|
|
|
|
|
{
|
2021-01-30 00:07:43 +00:00
|
|
|
|
_logger.Information("Shard {ShardId}: Sending gateway Resume for session {@SessionInfo}",
|
|
|
|
|
ShardId, SessionInfo);
|
2020-12-22 12:15:26 +00:00
|
|
|
|
await _conn!.Send(new GatewayPacket
|
|
|
|
|
{
|
2021-01-30 00:07:43 +00:00
|
|
|
|
Opcode = GatewayOpcode.Resume,
|
|
|
|
|
Payload = new GatewayResume(Settings.Token, session, lastSequence)
|
2020-12-22 12:15:26 +00:00
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public enum ShardState
|
|
|
|
|
{
|
|
|
|
|
Closed,
|
|
|
|
|
Connecting,
|
|
|
|
|
Open,
|
|
|
|
|
Closing
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|