mirror of
https://github.com/PluralKit/PluralKit.git
synced 2026-02-12 16:50:10 +00:00
feat: upgrade to .NET 6, refactor everything
This commit is contained in:
parent
d28e99ba43
commit
1918c56937
314 changed files with 27954 additions and 27966 deletions
|
|
@ -1,90 +1,84 @@
|
|||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
using Myriad.Gateway.Limit;
|
||||
using Myriad.Types;
|
||||
|
||||
using Serilog;
|
||||
|
||||
namespace Myriad.Gateway
|
||||
namespace Myriad.Gateway;
|
||||
|
||||
public class Cluster
|
||||
{
|
||||
public class Cluster
|
||||
private readonly GatewaySettings _gatewaySettings;
|
||||
private readonly ILogger _logger;
|
||||
private readonly ConcurrentDictionary<int, Shard> _shards = new();
|
||||
private IGatewayRatelimiter? _ratelimiter;
|
||||
|
||||
public Cluster(GatewaySettings gatewaySettings, ILogger logger)
|
||||
{
|
||||
private readonly GatewaySettings _gatewaySettings;
|
||||
private readonly ILogger _logger;
|
||||
private readonly ConcurrentDictionary<int, Shard> _shards = new();
|
||||
private IGatewayRatelimiter? _ratelimiter;
|
||||
_gatewaySettings = gatewaySettings;
|
||||
_logger = logger.ForContext<Cluster>();
|
||||
}
|
||||
|
||||
public Cluster(GatewaySettings gatewaySettings, ILogger logger)
|
||||
{
|
||||
_gatewaySettings = gatewaySettings;
|
||||
_logger = logger.ForContext<Cluster>();
|
||||
}
|
||||
public Func<Shard, IGatewayEvent, Task>? EventReceived { get; set; }
|
||||
|
||||
public Func<Shard, IGatewayEvent, Task>? EventReceived { get; set; }
|
||||
public event Action<Shard>? ShardCreated;
|
||||
public IReadOnlyDictionary<int, Shard> Shards => _shards;
|
||||
public event Action<Shard>? ShardCreated;
|
||||
|
||||
public IReadOnlyDictionary<int, Shard> Shards => _shards;
|
||||
public async Task Start(GatewayInfo.Bot info)
|
||||
{
|
||||
await Start(info.Url, 0, info.Shards - 1, info.Shards, info.SessionStartLimit.MaxConcurrency);
|
||||
}
|
||||
|
||||
public async Task Start(GatewayInfo.Bot info)
|
||||
{
|
||||
await Start(info.Url, 0, info.Shards - 1, info.Shards, info.SessionStartLimit.MaxConcurrency);
|
||||
}
|
||||
public async Task Start(string url, int shardMin, int shardMax, int shardTotal, int recommendedConcurrency)
|
||||
{
|
||||
_ratelimiter = GetRateLimiter(recommendedConcurrency);
|
||||
|
||||
public async Task Start(string url, int shardMin, int shardMax, int shardTotal, int recommendedConcurrency)
|
||||
{
|
||||
_ratelimiter = GetRateLimiter(recommendedConcurrency);
|
||||
var shardCount = shardMax - shardMin + 1;
|
||||
_logger.Information("Starting {ShardCount} of {ShardTotal} shards (#{ShardMin}-#{ShardMax}) at {Url}",
|
||||
shardCount, shardTotal, shardMin, shardMax, url);
|
||||
for (var i = shardMin; i <= shardMax; i++)
|
||||
CreateAndAddShard(url, new ShardInfo(i, shardTotal));
|
||||
|
||||
var shardCount = shardMax - shardMin + 1;
|
||||
_logger.Information("Starting {ShardCount} of {ShardTotal} shards (#{ShardMin}-#{ShardMax}) at {Url}",
|
||||
shardCount, shardTotal, shardMin, shardMax, url);
|
||||
for (var i = shardMin; i <= shardMax; i++)
|
||||
CreateAndAddShard(url, new ShardInfo(i, shardTotal));
|
||||
await StartShards();
|
||||
}
|
||||
|
||||
await StartShards();
|
||||
}
|
||||
private async Task StartShards()
|
||||
{
|
||||
_logger.Information("Connecting shards...");
|
||||
foreach (var shard in _shards.Values)
|
||||
await shard.Start();
|
||||
}
|
||||
private async Task StartShards()
|
||||
{
|
||||
_logger.Information("Connecting shards...");
|
||||
foreach (var shard in _shards.Values)
|
||||
await shard.Start();
|
||||
}
|
||||
|
||||
private void CreateAndAddShard(string url, ShardInfo shardInfo)
|
||||
{
|
||||
var shard = new Shard(_gatewaySettings, shardInfo, _ratelimiter!, url, _logger);
|
||||
shard.OnEventReceived += evt => OnShardEventReceived(shard, evt);
|
||||
_shards[shardInfo.ShardId] = shard;
|
||||
private void CreateAndAddShard(string url, ShardInfo shardInfo)
|
||||
{
|
||||
var shard = new Shard(_gatewaySettings, shardInfo, _ratelimiter!, url, _logger);
|
||||
shard.OnEventReceived += evt => OnShardEventReceived(shard, evt);
|
||||
_shards[shardInfo.ShardId] = shard;
|
||||
|
||||
ShardCreated?.Invoke(shard);
|
||||
}
|
||||
ShardCreated?.Invoke(shard);
|
||||
}
|
||||
|
||||
private async Task OnShardEventReceived(Shard shard, IGatewayEvent evt)
|
||||
{
|
||||
if (EventReceived != null)
|
||||
await EventReceived(shard, evt);
|
||||
}
|
||||
private async Task OnShardEventReceived(Shard shard, IGatewayEvent evt)
|
||||
{
|
||||
if (EventReceived != null)
|
||||
await EventReceived(shard, evt);
|
||||
}
|
||||
|
||||
private int GetActualShardConcurrency(int recommendedConcurrency)
|
||||
{
|
||||
if (_gatewaySettings.MaxShardConcurrency == null)
|
||||
return recommendedConcurrency;
|
||||
private int GetActualShardConcurrency(int recommendedConcurrency)
|
||||
{
|
||||
if (_gatewaySettings.MaxShardConcurrency == null)
|
||||
return recommendedConcurrency;
|
||||
|
||||
return Math.Min(_gatewaySettings.MaxShardConcurrency.Value, recommendedConcurrency);
|
||||
}
|
||||
return Math.Min(_gatewaySettings.MaxShardConcurrency.Value, recommendedConcurrency);
|
||||
}
|
||||
|
||||
private IGatewayRatelimiter GetRateLimiter(int recommendedConcurrency)
|
||||
{
|
||||
if (_gatewaySettings.GatewayQueueUrl != null)
|
||||
{
|
||||
return new TwilightGatewayRatelimiter(_logger, _gatewaySettings.GatewayQueueUrl);
|
||||
}
|
||||
private IGatewayRatelimiter GetRateLimiter(int recommendedConcurrency)
|
||||
{
|
||||
if (_gatewaySettings.GatewayQueueUrl != null)
|
||||
return new TwilightGatewayRatelimiter(_logger, _gatewaySettings.GatewayQueueUrl);
|
||||
|
||||
var concurrency = GetActualShardConcurrency(recommendedConcurrency);
|
||||
return new LocalGatewayRatelimiter(_logger, concurrency);
|
||||
}
|
||||
var concurrency = GetActualShardConcurrency(recommendedConcurrency);
|
||||
return new LocalGatewayRatelimiter(_logger, concurrency);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,6 +1,5 @@
|
|||
using Myriad.Types;
|
||||
|
||||
namespace Myriad.Gateway
|
||||
{
|
||||
public record ChannelCreateEvent: Channel, IGatewayEvent;
|
||||
}
|
||||
namespace Myriad.Gateway;
|
||||
|
||||
public record ChannelCreateEvent: Channel, IGatewayEvent;
|
||||
|
|
@ -1,6 +1,5 @@
|
|||
using Myriad.Types;
|
||||
|
||||
namespace Myriad.Gateway
|
||||
{
|
||||
public record ChannelDeleteEvent: Channel, IGatewayEvent;
|
||||
}
|
||||
namespace Myriad.Gateway;
|
||||
|
||||
public record ChannelDeleteEvent: Channel, IGatewayEvent;
|
||||
|
|
@ -1,6 +1,5 @@
|
|||
using Myriad.Types;
|
||||
|
||||
namespace Myriad.Gateway
|
||||
{
|
||||
public record ChannelUpdateEvent: Channel, IGatewayEvent;
|
||||
}
|
||||
namespace Myriad.Gateway;
|
||||
|
||||
public record ChannelUpdateEvent: Channel, IGatewayEvent;
|
||||
|
|
@ -1,11 +1,10 @@
|
|||
using Myriad.Types;
|
||||
|
||||
namespace Myriad.Gateway
|
||||
namespace Myriad.Gateway;
|
||||
|
||||
public record GuildCreateEvent: Guild, IGatewayEvent
|
||||
{
|
||||
public record GuildCreateEvent: Guild, IGatewayEvent
|
||||
{
|
||||
public Channel[] Channels { get; init; }
|
||||
public GuildMember[] Members { get; init; }
|
||||
public Channel[] Threads { get; init; }
|
||||
}
|
||||
public Channel[] Channels { get; init; }
|
||||
public GuildMember[] Members { get; init; }
|
||||
public Channel[] Threads { get; init; }
|
||||
}
|
||||
|
|
@ -1,4 +1,3 @@
|
|||
namespace Myriad.Gateway
|
||||
{
|
||||
public record GuildDeleteEvent(ulong Id, bool Unavailable): IGatewayEvent;
|
||||
}
|
||||
namespace Myriad.Gateway;
|
||||
|
||||
public record GuildDeleteEvent(ulong Id, bool Unavailable): IGatewayEvent;
|
||||
|
|
@ -1,9 +1,8 @@
|
|||
using Myriad.Types;
|
||||
|
||||
namespace Myriad.Gateway
|
||||
namespace Myriad.Gateway;
|
||||
|
||||
public record GuildMemberAddEvent: GuildMember, IGatewayEvent
|
||||
{
|
||||
public record GuildMemberAddEvent: GuildMember, IGatewayEvent
|
||||
{
|
||||
public ulong GuildId { get; init; }
|
||||
}
|
||||
public ulong GuildId { get; init; }
|
||||
}
|
||||
|
|
@ -1,10 +1,9 @@
|
|||
using Myriad.Types;
|
||||
|
||||
namespace Myriad.Gateway
|
||||
namespace Myriad.Gateway;
|
||||
|
||||
public class GuildMemberRemoveEvent: IGatewayEvent
|
||||
{
|
||||
public class GuildMemberRemoveEvent: IGatewayEvent
|
||||
{
|
||||
public ulong GuildId { get; init; }
|
||||
public User User { get; init; }
|
||||
}
|
||||
public ulong GuildId { get; init; }
|
||||
public User User { get; init; }
|
||||
}
|
||||
|
|
@ -1,9 +1,8 @@
|
|||
using Myriad.Types;
|
||||
|
||||
namespace Myriad.Gateway
|
||||
namespace Myriad.Gateway;
|
||||
|
||||
public record GuildMemberUpdateEvent: GuildMember, IGatewayEvent
|
||||
{
|
||||
public record GuildMemberUpdateEvent: GuildMember, IGatewayEvent
|
||||
{
|
||||
public ulong GuildId { get; init; }
|
||||
}
|
||||
public ulong GuildId { get; init; }
|
||||
}
|
||||
|
|
@ -1,6 +1,5 @@
|
|||
using Myriad.Types;
|
||||
|
||||
namespace Myriad.Gateway
|
||||
{
|
||||
public record GuildRoleCreateEvent(ulong GuildId, Role Role): IGatewayEvent;
|
||||
}
|
||||
namespace Myriad.Gateway;
|
||||
|
||||
public record GuildRoleCreateEvent(ulong GuildId, Role Role): IGatewayEvent;
|
||||
|
|
@ -1,4 +1,3 @@
|
|||
namespace Myriad.Gateway
|
||||
{
|
||||
public record GuildRoleDeleteEvent(ulong GuildId, ulong RoleId): IGatewayEvent;
|
||||
}
|
||||
namespace Myriad.Gateway;
|
||||
|
||||
public record GuildRoleDeleteEvent(ulong GuildId, ulong RoleId): IGatewayEvent;
|
||||
|
|
@ -1,6 +1,5 @@
|
|||
using Myriad.Types;
|
||||
|
||||
namespace Myriad.Gateway
|
||||
{
|
||||
public record GuildRoleUpdateEvent(ulong GuildId, Role Role): IGatewayEvent;
|
||||
}
|
||||
namespace Myriad.Gateway;
|
||||
|
||||
public record GuildRoleUpdateEvent(ulong GuildId, Role Role): IGatewayEvent;
|
||||
|
|
@ -1,6 +1,5 @@
|
|||
using Myriad.Types;
|
||||
|
||||
namespace Myriad.Gateway
|
||||
{
|
||||
public record GuildUpdateEvent: Guild, IGatewayEvent;
|
||||
}
|
||||
namespace Myriad.Gateway;
|
||||
|
||||
public record GuildUpdateEvent: Guild, IGatewayEvent;
|
||||
|
|
@ -1,39 +1,35 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
namespace Myriad.Gateway;
|
||||
|
||||
namespace Myriad.Gateway
|
||||
public interface IGatewayEvent
|
||||
{
|
||||
public interface IGatewayEvent
|
||||
public static readonly Dictionary<string, Type> EventTypes = new()
|
||||
{
|
||||
public static readonly Dictionary<string, Type> EventTypes = new()
|
||||
{
|
||||
{ "READY", typeof(ReadyEvent) },
|
||||
{ "RESUMED", typeof(ResumedEvent) },
|
||||
{ "GUILD_CREATE", typeof(GuildCreateEvent) },
|
||||
{ "GUILD_UPDATE", typeof(GuildUpdateEvent) },
|
||||
{ "GUILD_DELETE", typeof(GuildDeleteEvent) },
|
||||
{ "GUILD_MEMBER_ADD", typeof(GuildMemberAddEvent) },
|
||||
{ "GUILD_MEMBER_REMOVE", typeof(GuildMemberRemoveEvent) },
|
||||
{ "GUILD_MEMBER_UPDATE", typeof(GuildMemberUpdateEvent) },
|
||||
{ "GUILD_ROLE_CREATE", typeof(GuildRoleCreateEvent) },
|
||||
{ "GUILD_ROLE_UPDATE", typeof(GuildRoleUpdateEvent) },
|
||||
{ "GUILD_ROLE_DELETE", typeof(GuildRoleDeleteEvent) },
|
||||
{ "CHANNEL_CREATE", typeof(ChannelCreateEvent) },
|
||||
{ "CHANNEL_UPDATE", typeof(ChannelUpdateEvent) },
|
||||
{ "CHANNEL_DELETE", typeof(ChannelDeleteEvent) },
|
||||
{ "THREAD_CREATE", typeof(ThreadCreateEvent) },
|
||||
{ "THREAD_UPDATE", typeof(ThreadUpdateEvent) },
|
||||
{ "THREAD_DELETE", typeof(ThreadDeleteEvent) },
|
||||
{ "THREAD_LIST_SYNC", typeof(ThreadListSyncEvent) },
|
||||
{ "MESSAGE_CREATE", typeof(MessageCreateEvent) },
|
||||
{ "MESSAGE_UPDATE", typeof(MessageUpdateEvent) },
|
||||
{ "MESSAGE_DELETE", typeof(MessageDeleteEvent) },
|
||||
{ "MESSAGE_DELETE_BULK", typeof(MessageDeleteBulkEvent) },
|
||||
{ "MESSAGE_REACTION_ADD", typeof(MessageReactionAddEvent) },
|
||||
{ "MESSAGE_REACTION_REMOVE", typeof(MessageReactionRemoveEvent) },
|
||||
{ "MESSAGE_REACTION_REMOVE_ALL", typeof(MessageReactionRemoveAllEvent) },
|
||||
{ "MESSAGE_REACTION_REMOVE_EMOJI", typeof(MessageReactionRemoveEmojiEvent) },
|
||||
{ "INTERACTION_CREATE", typeof(InteractionCreateEvent) }
|
||||
};
|
||||
}
|
||||
{ "READY", typeof(ReadyEvent) },
|
||||
{ "RESUMED", typeof(ResumedEvent) },
|
||||
{ "GUILD_CREATE", typeof(GuildCreateEvent) },
|
||||
{ "GUILD_UPDATE", typeof(GuildUpdateEvent) },
|
||||
{ "GUILD_DELETE", typeof(GuildDeleteEvent) },
|
||||
{ "GUILD_MEMBER_ADD", typeof(GuildMemberAddEvent) },
|
||||
{ "GUILD_MEMBER_REMOVE", typeof(GuildMemberRemoveEvent) },
|
||||
{ "GUILD_MEMBER_UPDATE", typeof(GuildMemberUpdateEvent) },
|
||||
{ "GUILD_ROLE_CREATE", typeof(GuildRoleCreateEvent) },
|
||||
{ "GUILD_ROLE_UPDATE", typeof(GuildRoleUpdateEvent) },
|
||||
{ "GUILD_ROLE_DELETE", typeof(GuildRoleDeleteEvent) },
|
||||
{ "CHANNEL_CREATE", typeof(ChannelCreateEvent) },
|
||||
{ "CHANNEL_UPDATE", typeof(ChannelUpdateEvent) },
|
||||
{ "CHANNEL_DELETE", typeof(ChannelDeleteEvent) },
|
||||
{ "THREAD_CREATE", typeof(ThreadCreateEvent) },
|
||||
{ "THREAD_UPDATE", typeof(ThreadUpdateEvent) },
|
||||
{ "THREAD_DELETE", typeof(ThreadDeleteEvent) },
|
||||
{ "THREAD_LIST_SYNC", typeof(ThreadListSyncEvent) },
|
||||
{ "MESSAGE_CREATE", typeof(MessageCreateEvent) },
|
||||
{ "MESSAGE_UPDATE", typeof(MessageUpdateEvent) },
|
||||
{ "MESSAGE_DELETE", typeof(MessageDeleteEvent) },
|
||||
{ "MESSAGE_DELETE_BULK", typeof(MessageDeleteBulkEvent) },
|
||||
{ "MESSAGE_REACTION_ADD", typeof(MessageReactionAddEvent) },
|
||||
{ "MESSAGE_REACTION_REMOVE", typeof(MessageReactionRemoveEvent) },
|
||||
{ "MESSAGE_REACTION_REMOVE_ALL", typeof(MessageReactionRemoveAllEvent) },
|
||||
{ "MESSAGE_REACTION_REMOVE_EMOJI", typeof(MessageReactionRemoveEmojiEvent) },
|
||||
{ "INTERACTION_CREATE", typeof(InteractionCreateEvent) }
|
||||
};
|
||||
}
|
||||
|
|
@ -1,6 +1,5 @@
|
|||
using Myriad.Types;
|
||||
|
||||
namespace Myriad.Gateway
|
||||
{
|
||||
public record InteractionCreateEvent: Interaction, IGatewayEvent;
|
||||
}
|
||||
namespace Myriad.Gateway;
|
||||
|
||||
public record InteractionCreateEvent: Interaction, IGatewayEvent;
|
||||
|
|
@ -1,9 +1,8 @@
|
|||
using Myriad.Types;
|
||||
|
||||
namespace Myriad.Gateway
|
||||
namespace Myriad.Gateway;
|
||||
|
||||
public record MessageCreateEvent: Message, IGatewayEvent
|
||||
{
|
||||
public record MessageCreateEvent: Message, IGatewayEvent
|
||||
{
|
||||
public GuildMemberPartial? Member { get; init; }
|
||||
}
|
||||
public GuildMemberPartial? Member { get; init; }
|
||||
}
|
||||
|
|
@ -1,4 +1,3 @@
|
|||
namespace Myriad.Gateway
|
||||
{
|
||||
public record MessageDeleteBulkEvent(ulong[] Ids, ulong ChannelId, ulong? GuildId): IGatewayEvent;
|
||||
}
|
||||
namespace Myriad.Gateway;
|
||||
|
||||
public record MessageDeleteBulkEvent(ulong[] Ids, ulong ChannelId, ulong? GuildId): IGatewayEvent;
|
||||
|
|
@ -1,4 +1,3 @@
|
|||
namespace Myriad.Gateway
|
||||
{
|
||||
public record MessageDeleteEvent(ulong Id, ulong ChannelId, ulong? GuildId): IGatewayEvent;
|
||||
}
|
||||
namespace Myriad.Gateway;
|
||||
|
||||
public record MessageDeleteEvent(ulong Id, ulong ChannelId, ulong? GuildId): IGatewayEvent;
|
||||
|
|
@ -1,8 +1,7 @@
|
|||
using Myriad.Types;
|
||||
|
||||
namespace Myriad.Gateway
|
||||
{
|
||||
public record MessageReactionAddEvent(ulong UserId, ulong ChannelId, ulong MessageId, ulong? GuildId,
|
||||
GuildMember? Member,
|
||||
Emoji Emoji): IGatewayEvent;
|
||||
}
|
||||
namespace Myriad.Gateway;
|
||||
|
||||
public record MessageReactionAddEvent(ulong UserId, ulong ChannelId, ulong MessageId, ulong? GuildId,
|
||||
GuildMember? Member,
|
||||
Emoji Emoji): IGatewayEvent;
|
||||
|
|
@ -1,4 +1,3 @@
|
|||
namespace Myriad.Gateway
|
||||
{
|
||||
public record MessageReactionRemoveAllEvent(ulong ChannelId, ulong MessageId, ulong? GuildId): IGatewayEvent;
|
||||
}
|
||||
namespace Myriad.Gateway;
|
||||
|
||||
public record MessageReactionRemoveAllEvent(ulong ChannelId, ulong MessageId, ulong? GuildId): IGatewayEvent;
|
||||
|
|
@ -1,7 +1,6 @@
|
|||
using Myriad.Types;
|
||||
|
||||
namespace Myriad.Gateway
|
||||
{
|
||||
public record MessageReactionRemoveEmojiEvent
|
||||
(ulong ChannelId, ulong MessageId, ulong? GuildId, Emoji Emoji): IGatewayEvent;
|
||||
}
|
||||
namespace Myriad.Gateway;
|
||||
|
||||
public record MessageReactionRemoveEmojiEvent
|
||||
(ulong ChannelId, ulong MessageId, ulong? GuildId, Emoji Emoji): IGatewayEvent;
|
||||
|
|
@ -1,7 +1,6 @@
|
|||
using Myriad.Types;
|
||||
|
||||
namespace Myriad.Gateway
|
||||
{
|
||||
public record MessageReactionRemoveEvent
|
||||
(ulong UserId, ulong ChannelId, ulong MessageId, ulong? GuildId, Emoji Emoji): IGatewayEvent;
|
||||
}
|
||||
namespace Myriad.Gateway;
|
||||
|
||||
public record MessageReactionRemoveEvent
|
||||
(ulong UserId, ulong ChannelId, ulong MessageId, ulong? GuildId, Emoji Emoji): IGatewayEvent;
|
||||
|
|
@ -1,15 +1,15 @@
|
|||
using Myriad.Types;
|
||||
using Myriad.Utils;
|
||||
|
||||
namespace Myriad.Gateway
|
||||
namespace Myriad.Gateway;
|
||||
|
||||
public record MessageUpdateEvent(ulong Id, ulong ChannelId): IGatewayEvent
|
||||
{
|
||||
public record MessageUpdateEvent(ulong Id, ulong ChannelId): IGatewayEvent
|
||||
{
|
||||
public Optional<string?> Content { get; init; }
|
||||
public Optional<User> Author { get; init; }
|
||||
public Optional<GuildMemberPartial> Member { get; init; }
|
||||
public Optional<Message.Attachment[]> Attachments { get; init; }
|
||||
public Optional<ulong?> GuildId { get; init; }
|
||||
// TODO: lots of partials
|
||||
}
|
||||
public Optional<string?> Content { get; init; }
|
||||
public Optional<User> Author { get; init; }
|
||||
public Optional<GuildMemberPartial> Member { get; init; }
|
||||
public Optional<Message.Attachment[]> Attachments { get; init; }
|
||||
|
||||
public Optional<ulong?> GuildId { get; init; }
|
||||
// TODO: lots of partials
|
||||
}
|
||||
|
|
@ -2,14 +2,13 @@ using System.Text.Json.Serialization;
|
|||
|
||||
using Myriad.Types;
|
||||
|
||||
namespace Myriad.Gateway
|
||||
namespace Myriad.Gateway;
|
||||
|
||||
public record ReadyEvent: IGatewayEvent
|
||||
{
|
||||
public record ReadyEvent: IGatewayEvent
|
||||
{
|
||||
[JsonPropertyName("v")] public int Version { get; init; }
|
||||
public User User { get; init; }
|
||||
public string SessionId { get; init; }
|
||||
public ShardInfo? Shard { get; init; }
|
||||
public ApplicationPartial Application { get; init; }
|
||||
}
|
||||
[JsonPropertyName("v")] public int Version { get; init; }
|
||||
public User User { get; init; }
|
||||
public string SessionId { get; init; }
|
||||
public ShardInfo? Shard { get; init; }
|
||||
public ApplicationPartial Application { get; init; }
|
||||
}
|
||||
|
|
@ -1,4 +1,3 @@
|
|||
namespace Myriad.Gateway
|
||||
{
|
||||
public record ResumedEvent: IGatewayEvent;
|
||||
}
|
||||
namespace Myriad.Gateway;
|
||||
|
||||
public record ResumedEvent: IGatewayEvent;
|
||||
|
|
@ -1,6 +1,5 @@
|
|||
using Myriad.Types;
|
||||
|
||||
namespace Myriad.Gateway
|
||||
{
|
||||
public record ThreadCreateEvent: Channel, IGatewayEvent;
|
||||
}
|
||||
namespace Myriad.Gateway;
|
||||
|
||||
public record ThreadCreateEvent: Channel, IGatewayEvent;
|
||||
|
|
@ -1,12 +1,11 @@
|
|||
using Myriad.Types;
|
||||
|
||||
namespace Myriad.Gateway
|
||||
namespace Myriad.Gateway;
|
||||
|
||||
public record ThreadDeleteEvent: IGatewayEvent
|
||||
{
|
||||
public record ThreadDeleteEvent: IGatewayEvent
|
||||
{
|
||||
public ulong Id { get; init; }
|
||||
public ulong? GuildId { get; init; }
|
||||
public ulong? ParentId { get; init; }
|
||||
public Channel.ChannelType Type { get; init; }
|
||||
}
|
||||
public ulong Id { get; init; }
|
||||
public ulong? GuildId { get; init; }
|
||||
public ulong? ParentId { get; init; }
|
||||
public Channel.ChannelType Type { get; init; }
|
||||
}
|
||||
|
|
@ -1,11 +1,10 @@
|
|||
using Myriad.Types;
|
||||
|
||||
namespace Myriad.Gateway
|
||||
namespace Myriad.Gateway;
|
||||
|
||||
public record ThreadListSyncEvent: IGatewayEvent
|
||||
{
|
||||
public record ThreadListSyncEvent: IGatewayEvent
|
||||
{
|
||||
public ulong GuildId { get; init; }
|
||||
public ulong[]? ChannelIds { get; init; }
|
||||
public Channel[] Threads { get; init; }
|
||||
}
|
||||
public ulong GuildId { get; init; }
|
||||
public ulong[]? ChannelIds { get; init; }
|
||||
public Channel[] Threads { get; init; }
|
||||
}
|
||||
|
|
@ -1,6 +1,5 @@
|
|||
using Myriad.Types;
|
||||
|
||||
namespace Myriad.Gateway
|
||||
{
|
||||
public record ThreadUpdateEvent: Channel, IGatewayEvent;
|
||||
}
|
||||
namespace Myriad.Gateway;
|
||||
|
||||
public record ThreadUpdateEvent: Channel, IGatewayEvent;
|
||||
|
|
@ -1,35 +1,32 @@
|
|||
using System;
|
||||
namespace Myriad.Gateway;
|
||||
|
||||
namespace Myriad.Gateway
|
||||
// TODO: unused?
|
||||
public class GatewayCloseException: Exception
|
||||
{
|
||||
// TODO: unused?
|
||||
public class GatewayCloseException: Exception
|
||||
public GatewayCloseException(int closeCode, string closeReason) : base($"{closeCode}: {closeReason}")
|
||||
{
|
||||
public GatewayCloseException(int closeCode, string closeReason) : base($"{closeCode}: {closeReason}")
|
||||
{
|
||||
CloseCode = closeCode;
|
||||
CloseReason = closeReason;
|
||||
}
|
||||
|
||||
public int CloseCode { get; }
|
||||
public string CloseReason { get; }
|
||||
CloseCode = closeCode;
|
||||
CloseReason = closeReason;
|
||||
}
|
||||
|
||||
public class GatewayCloseCode
|
||||
{
|
||||
public const int UnknownError = 4000;
|
||||
public const int UnknownOpcode = 4001;
|
||||
public const int DecodeError = 4002;
|
||||
public const int NotAuthenticated = 4003;
|
||||
public const int AuthenticationFailed = 4004;
|
||||
public const int AlreadyAuthenticated = 4005;
|
||||
public const int InvalidSeq = 4007;
|
||||
public const int RateLimited = 4008;
|
||||
public const int SessionTimedOut = 4009;
|
||||
public const int InvalidShard = 4010;
|
||||
public const int ShardingRequired = 4011;
|
||||
public const int InvalidApiVersion = 4012;
|
||||
public const int InvalidIntent = 4013;
|
||||
public const int DisallowedIntent = 4014;
|
||||
}
|
||||
public int CloseCode { get; }
|
||||
public string CloseReason { get; }
|
||||
}
|
||||
|
||||
public class GatewayCloseCode
|
||||
{
|
||||
public const int UnknownError = 4000;
|
||||
public const int UnknownOpcode = 4001;
|
||||
public const int DecodeError = 4002;
|
||||
public const int NotAuthenticated = 4003;
|
||||
public const int AuthenticationFailed = 4004;
|
||||
public const int AlreadyAuthenticated = 4005;
|
||||
public const int InvalidSeq = 4007;
|
||||
public const int RateLimited = 4008;
|
||||
public const int SessionTimedOut = 4009;
|
||||
public const int InvalidShard = 4010;
|
||||
public const int ShardingRequired = 4011;
|
||||
public const int InvalidApiVersion = 4012;
|
||||
public const int InvalidIntent = 4013;
|
||||
public const int DisallowedIntent = 4014;
|
||||
}
|
||||
|
|
@ -1,24 +1,21 @@
|
|||
using System;
|
||||
namespace Myriad.Gateway;
|
||||
|
||||
namespace Myriad.Gateway
|
||||
[Flags]
|
||||
public enum GatewayIntent
|
||||
{
|
||||
[Flags]
|
||||
public enum GatewayIntent
|
||||
{
|
||||
Guilds = 1 << 0,
|
||||
GuildMembers = 1 << 1,
|
||||
GuildBans = 1 << 2,
|
||||
GuildEmojis = 1 << 3,
|
||||
GuildIntegrations = 1 << 4,
|
||||
GuildWebhooks = 1 << 5,
|
||||
GuildInvites = 1 << 6,
|
||||
GuildVoiceStates = 1 << 7,
|
||||
GuildPresences = 1 << 8,
|
||||
GuildMessages = 1 << 9,
|
||||
GuildMessageReactions = 1 << 10,
|
||||
GuildMessageTyping = 1 << 11,
|
||||
DirectMessages = 1 << 12,
|
||||
DirectMessageReactions = 1 << 13,
|
||||
DirectMessageTyping = 1 << 14
|
||||
}
|
||||
Guilds = 1 << 0,
|
||||
GuildMembers = 1 << 1,
|
||||
GuildBans = 1 << 2,
|
||||
GuildEmojis = 1 << 3,
|
||||
GuildIntegrations = 1 << 4,
|
||||
GuildWebhooks = 1 << 5,
|
||||
GuildInvites = 1 << 6,
|
||||
GuildVoiceStates = 1 << 7,
|
||||
GuildPresences = 1 << 8,
|
||||
GuildMessages = 1 << 9,
|
||||
GuildMessageReactions = 1 << 10,
|
||||
GuildMessageTyping = 1 << 11,
|
||||
DirectMessages = 1 << 12,
|
||||
DirectMessageReactions = 1 << 13,
|
||||
DirectMessageTyping = 1 << 14
|
||||
}
|
||||
|
|
@ -1,33 +1,32 @@
|
|||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace Myriad.Gateway
|
||||
namespace Myriad.Gateway;
|
||||
|
||||
public record GatewayPacket
|
||||
{
|
||||
public record GatewayPacket
|
||||
{
|
||||
[JsonPropertyName("op")] public GatewayOpcode Opcode { get; init; }
|
||||
[JsonPropertyName("d")] public object? Payload { get; init; }
|
||||
[JsonPropertyName("op")] public GatewayOpcode Opcode { get; init; }
|
||||
[JsonPropertyName("d")] public object? Payload { get; init; }
|
||||
|
||||
[JsonPropertyName("s")]
|
||||
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
|
||||
public int? Sequence { get; init; }
|
||||
[JsonPropertyName("s")]
|
||||
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
|
||||
public int? Sequence { get; init; }
|
||||
|
||||
[JsonPropertyName("t")]
|
||||
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
|
||||
public string? EventType { get; init; }
|
||||
}
|
||||
[JsonPropertyName("t")]
|
||||
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
|
||||
public string? EventType { get; init; }
|
||||
}
|
||||
|
||||
public enum GatewayOpcode
|
||||
{
|
||||
Dispatch = 0,
|
||||
Heartbeat = 1,
|
||||
Identify = 2,
|
||||
PresenceUpdate = 3,
|
||||
VoiceStateUpdate = 4,
|
||||
Resume = 6,
|
||||
Reconnect = 7,
|
||||
RequestGuildMembers = 8,
|
||||
InvalidSession = 9,
|
||||
Hello = 10,
|
||||
HeartbeatAck = 11
|
||||
}
|
||||
public enum GatewayOpcode
|
||||
{
|
||||
Dispatch = 0,
|
||||
Heartbeat = 1,
|
||||
Identify = 2,
|
||||
PresenceUpdate = 3,
|
||||
VoiceStateUpdate = 4,
|
||||
Resume = 6,
|
||||
Reconnect = 7,
|
||||
RequestGuildMembers = 8,
|
||||
InvalidSession = 9,
|
||||
Hello = 10,
|
||||
HeartbeatAck = 11
|
||||
}
|
||||
|
|
@ -1,10 +1,9 @@
|
|||
namespace Myriad.Gateway
|
||||
namespace Myriad.Gateway;
|
||||
|
||||
public record GatewaySettings
|
||||
{
|
||||
public record GatewaySettings
|
||||
{
|
||||
public string Token { get; init; }
|
||||
public GatewayIntent Intents { get; init; }
|
||||
public int? MaxShardConcurrency { get; init; }
|
||||
public string? GatewayQueueUrl { get; init; }
|
||||
}
|
||||
public string Token { get; init; }
|
||||
public GatewayIntent Intents { get; init; }
|
||||
public int? MaxShardConcurrency { get; init; }
|
||||
public string? GatewayQueueUrl { get; init; }
|
||||
}
|
||||
|
|
@ -1,9 +1,6 @@
|
|||
using System.Threading.Tasks;
|
||||
namespace Myriad.Gateway.Limit;
|
||||
|
||||
namespace Myriad.Gateway.Limit
|
||||
public interface IGatewayRatelimiter
|
||||
{
|
||||
public interface IGatewayRatelimiter
|
||||
{
|
||||
public Task Identify(int shard);
|
||||
}
|
||||
public Task Identify(int shard);
|
||||
}
|
||||
|
|
@ -1,73 +1,70 @@
|
|||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
using Serilog;
|
||||
|
||||
namespace Myriad.Gateway.Limit
|
||||
namespace Myriad.Gateway.Limit;
|
||||
|
||||
public class LocalGatewayRatelimiter: IGatewayRatelimiter
|
||||
{
|
||||
public class LocalGatewayRatelimiter: IGatewayRatelimiter
|
||||
// docs specify 5 seconds, but we're actually throttling connections, not identify, so we need a bit of leeway
|
||||
private static readonly TimeSpan BucketLength = TimeSpan.FromSeconds(6);
|
||||
|
||||
private readonly ConcurrentDictionary<int, ConcurrentQueue<TaskCompletionSource>> _buckets = new();
|
||||
private readonly ILogger _logger;
|
||||
private readonly int _maxConcurrency;
|
||||
|
||||
private Task? _refillTask;
|
||||
|
||||
public LocalGatewayRatelimiter(ILogger logger, int maxConcurrency)
|
||||
{
|
||||
// docs specify 5 seconds, but we're actually throttling connections, not identify, so we need a bit of leeway
|
||||
private static readonly TimeSpan BucketLength = TimeSpan.FromSeconds(6);
|
||||
_logger = logger.ForContext<LocalGatewayRatelimiter>();
|
||||
_maxConcurrency = maxConcurrency;
|
||||
}
|
||||
|
||||
private readonly ConcurrentDictionary<int, ConcurrentQueue<TaskCompletionSource>> _buckets = new();
|
||||
private readonly int _maxConcurrency;
|
||||
public Task Identify(int shard)
|
||||
{
|
||||
var bucket = shard % _maxConcurrency;
|
||||
var queue = _buckets.GetOrAdd(bucket, _ => new ConcurrentQueue<TaskCompletionSource>());
|
||||
var tcs = new TaskCompletionSource();
|
||||
queue.Enqueue(tcs);
|
||||
|
||||
private Task? _refillTask;
|
||||
private readonly ILogger _logger;
|
||||
ScheduleRefill();
|
||||
|
||||
public LocalGatewayRatelimiter(ILogger logger, int maxConcurrency)
|
||||
return tcs.Task;
|
||||
}
|
||||
|
||||
private void ScheduleRefill()
|
||||
{
|
||||
if (_refillTask != null && !_refillTask.IsCompleted)
|
||||
return;
|
||||
|
||||
_refillTask?.Dispose();
|
||||
_refillTask = RefillTask();
|
||||
}
|
||||
|
||||
private async Task RefillTask()
|
||||
{
|
||||
await Task.Delay(TimeSpan.FromMilliseconds(250));
|
||||
|
||||
while (true)
|
||||
{
|
||||
_logger = logger.ForContext<LocalGatewayRatelimiter>();
|
||||
_maxConcurrency = maxConcurrency;
|
||||
}
|
||||
var isClear = true;
|
||||
foreach (var (bucket, queue) in _buckets)
|
||||
{
|
||||
if (!queue.TryDequeue(out var tcs))
|
||||
continue;
|
||||
|
||||
public Task Identify(int shard)
|
||||
{
|
||||
var bucket = shard % _maxConcurrency;
|
||||
var queue = _buckets.GetOrAdd(bucket, _ => new ConcurrentQueue<TaskCompletionSource>());
|
||||
var tcs = new TaskCompletionSource();
|
||||
queue.Enqueue(tcs);
|
||||
_logger.Debug(
|
||||
"Allowing identify for bucket {BucketId} through ({QueueLength} left in bucket queue)",
|
||||
bucket, queue.Count);
|
||||
tcs.SetResult();
|
||||
isClear = false;
|
||||
}
|
||||
|
||||
ScheduleRefill();
|
||||
|
||||
return tcs.Task;
|
||||
}
|
||||
|
||||
private void ScheduleRefill()
|
||||
{
|
||||
if (_refillTask != null && !_refillTask.IsCompleted)
|
||||
if (isClear)
|
||||
return;
|
||||
|
||||
_refillTask?.Dispose();
|
||||
_refillTask = RefillTask();
|
||||
}
|
||||
|
||||
private async Task RefillTask()
|
||||
{
|
||||
await Task.Delay(TimeSpan.FromMilliseconds(250));
|
||||
|
||||
while (true)
|
||||
{
|
||||
var isClear = true;
|
||||
foreach (var (bucket, queue) in _buckets)
|
||||
{
|
||||
if (!queue.TryDequeue(out var tcs))
|
||||
continue;
|
||||
|
||||
_logger.Debug(
|
||||
"Allowing identify for bucket {BucketId} through ({QueueLength} left in bucket queue)",
|
||||
bucket, queue.Count);
|
||||
tcs.SetResult();
|
||||
isClear = false;
|
||||
}
|
||||
|
||||
if (isClear)
|
||||
return;
|
||||
|
||||
await Task.Delay(BucketLength);
|
||||
}
|
||||
await Task.Delay(BucketLength);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,41 +1,30 @@
|
|||
using System;
|
||||
using System.Net.Http;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
using Serilog;
|
||||
|
||||
namespace Myriad.Gateway.Limit
|
||||
namespace Myriad.Gateway.Limit;
|
||||
|
||||
public class TwilightGatewayRatelimiter: IGatewayRatelimiter
|
||||
{
|
||||
public class TwilightGatewayRatelimiter: IGatewayRatelimiter
|
||||
private readonly HttpClient _httpClient = new() { Timeout = TimeSpan.FromSeconds(60) };
|
||||
|
||||
private readonly ILogger _logger;
|
||||
private readonly string _url;
|
||||
|
||||
public TwilightGatewayRatelimiter(ILogger logger, string url)
|
||||
{
|
||||
private readonly string _url;
|
||||
private readonly ILogger _logger;
|
||||
private readonly HttpClient _httpClient = new()
|
||||
{
|
||||
Timeout = TimeSpan.FromSeconds(60)
|
||||
};
|
||||
_url = url;
|
||||
_logger = logger.ForContext<TwilightGatewayRatelimiter>();
|
||||
}
|
||||
|
||||
public TwilightGatewayRatelimiter(ILogger logger, string url)
|
||||
{
|
||||
_url = url;
|
||||
_logger = logger.ForContext<TwilightGatewayRatelimiter>();
|
||||
}
|
||||
|
||||
public async Task Identify(int shard)
|
||||
{
|
||||
while (true)
|
||||
public async Task Identify(int shard)
|
||||
{
|
||||
while (true)
|
||||
try
|
||||
{
|
||||
try
|
||||
{
|
||||
_logger.Information("Shard {ShardId}: Requesting identify at gateway queue {GatewayQueueUrl}",
|
||||
shard, _url);
|
||||
await _httpClient.GetAsync(_url);
|
||||
return;
|
||||
}
|
||||
catch (TimeoutException)
|
||||
{
|
||||
}
|
||||
_logger.Information("Shard {ShardId}: Requesting identify at gateway queue {GatewayQueueUrl}",
|
||||
shard, _url);
|
||||
await _httpClient.GetAsync(_url);
|
||||
return;
|
||||
}
|
||||
}
|
||||
catch (TimeoutException) { }
|
||||
}
|
||||
}
|
||||
|
|
@ -1,4 +1,3 @@
|
|||
namespace Myriad.Gateway
|
||||
{
|
||||
public record GatewayHello(int HeartbeatInterval);
|
||||
}
|
||||
namespace Myriad.Gateway;
|
||||
|
||||
public record GatewayHello(int HeartbeatInterval);
|
||||
|
|
@ -1,28 +1,27 @@
|
|||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace Myriad.Gateway
|
||||
namespace Myriad.Gateway;
|
||||
|
||||
public record GatewayIdentify
|
||||
{
|
||||
public record GatewayIdentify
|
||||
public string Token { get; init; }
|
||||
public ConnectionProperties Properties { get; init; }
|
||||
|
||||
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
|
||||
public bool? Compress { get; init; }
|
||||
|
||||
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
|
||||
public int? LargeThreshold { get; init; }
|
||||
|
||||
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
|
||||
public ShardInfo? Shard { get; init; }
|
||||
|
||||
public GatewayIntent Intents { get; init; }
|
||||
|
||||
public record ConnectionProperties
|
||||
{
|
||||
public string Token { get; init; }
|
||||
public ConnectionProperties Properties { get; init; }
|
||||
|
||||
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
|
||||
public bool? Compress { get; init; }
|
||||
|
||||
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
|
||||
public int? LargeThreshold { get; init; }
|
||||
|
||||
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
|
||||
public ShardInfo? Shard { get; init; }
|
||||
|
||||
public GatewayIntent Intents { get; init; }
|
||||
|
||||
public record ConnectionProperties
|
||||
{
|
||||
[JsonPropertyName("$os")] public string Os { get; init; }
|
||||
[JsonPropertyName("$browser")] public string Browser { get; init; }
|
||||
[JsonPropertyName("$device")] public string Device { get; init; }
|
||||
}
|
||||
[JsonPropertyName("$os")] public string Os { get; init; }
|
||||
[JsonPropertyName("$browser")] public string Browser { get; init; }
|
||||
[JsonPropertyName("$device")] public string Device { get; init; }
|
||||
}
|
||||
}
|
||||
|
|
@ -1,4 +1,3 @@
|
|||
namespace Myriad.Gateway
|
||||
{
|
||||
public record GatewayResume(string Token, string SessionId, int Seq);
|
||||
}
|
||||
namespace Myriad.Gateway;
|
||||
|
||||
public record GatewayResume(string Token, string SessionId, int Seq);
|
||||
|
|
@ -3,23 +3,22 @@ using System.Text.Json.Serialization;
|
|||
using Myriad.Serialization;
|
||||
using Myriad.Types;
|
||||
|
||||
namespace Myriad.Gateway
|
||||
{
|
||||
public record GatewayStatusUpdate
|
||||
{
|
||||
[JsonConverter(typeof(JsonSnakeCaseStringEnumConverter))]
|
||||
public enum UserStatus
|
||||
{
|
||||
Online,
|
||||
Dnd,
|
||||
Idle,
|
||||
Invisible,
|
||||
Offline
|
||||
}
|
||||
namespace Myriad.Gateway;
|
||||
|
||||
public ulong? Since { get; init; }
|
||||
public ActivityPartial[]? Activities { get; init; }
|
||||
public UserStatus Status { get; init; }
|
||||
public bool Afk { get; init; }
|
||||
public record GatewayStatusUpdate
|
||||
{
|
||||
[JsonConverter(typeof(JsonSnakeCaseStringEnumConverter))]
|
||||
public enum UserStatus
|
||||
{
|
||||
Online,
|
||||
Dnd,
|
||||
Idle,
|
||||
Invisible,
|
||||
Offline
|
||||
}
|
||||
|
||||
public ulong? Since { get; init; }
|
||||
public ActivityPartial[]? Activities { get; init; }
|
||||
public UserStatus Status { get; init; }
|
||||
public bool Afk { get; init; }
|
||||
}
|
||||
|
|
@ -1,7 +1,5 @@
|
|||
using System;
|
||||
using System.Net.WebSockets;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
using Myriad.Gateway.Limit;
|
||||
using Myriad.Gateway.State;
|
||||
|
|
@ -11,214 +9,203 @@ using Myriad.Types;
|
|||
using Serilog;
|
||||
using Serilog.Context;
|
||||
|
||||
namespace Myriad.Gateway
|
||||
namespace Myriad.Gateway;
|
||||
|
||||
public class Shard
|
||||
{
|
||||
public class Shard
|
||||
private const string LibraryName = "Myriad (for PluralKit)";
|
||||
|
||||
private readonly GatewaySettings _settings;
|
||||
private readonly ShardInfo _info;
|
||||
private readonly IGatewayRatelimiter _ratelimiter;
|
||||
private readonly string _url;
|
||||
private readonly ILogger _logger;
|
||||
private readonly ShardStateManager _stateManager;
|
||||
private readonly JsonSerializerOptions _jsonSerializerOptions;
|
||||
private readonly ShardConnection _conn;
|
||||
|
||||
public int ShardId => _info.ShardId;
|
||||
public ShardState State => _stateManager.State;
|
||||
public TimeSpan? Latency => _stateManager.Latency;
|
||||
public User? User => _stateManager.User;
|
||||
public ApplicationPartial? Application => _stateManager.Application;
|
||||
|
||||
// TODO: I wanna get rid of these or move them at some point
|
||||
public event Func<IGatewayEvent, Task>? OnEventReceived;
|
||||
public event Action<TimeSpan>? HeartbeatReceived;
|
||||
public event Action? SocketOpened;
|
||||
public event Action? Resumed;
|
||||
public event Action? Ready;
|
||||
public event Action<WebSocketCloseStatus?, string?>? SocketClosed;
|
||||
|
||||
private TimeSpan _reconnectDelay = TimeSpan.Zero;
|
||||
private Task? _worker;
|
||||
|
||||
public Shard(GatewaySettings settings, ShardInfo info, IGatewayRatelimiter ratelimiter, string url, ILogger logger)
|
||||
{
|
||||
private const string LibraryName = "Myriad (for PluralKit)";
|
||||
_jsonSerializerOptions = new JsonSerializerOptions().ConfigureForMyriad();
|
||||
|
||||
private readonly GatewaySettings _settings;
|
||||
private readonly ShardInfo _info;
|
||||
private readonly IGatewayRatelimiter _ratelimiter;
|
||||
private readonly string _url;
|
||||
private readonly ILogger _logger;
|
||||
private readonly ShardStateManager _stateManager;
|
||||
private readonly JsonSerializerOptions _jsonSerializerOptions;
|
||||
private readonly ShardConnection _conn;
|
||||
|
||||
public int ShardId => _info.ShardId;
|
||||
public ShardState State => _stateManager.State;
|
||||
public TimeSpan? Latency => _stateManager.Latency;
|
||||
public User? User => _stateManager.User;
|
||||
public ApplicationPartial? Application => _stateManager.Application;
|
||||
|
||||
// TODO: I wanna get rid of these or move them at some point
|
||||
public event Func<IGatewayEvent, Task>? OnEventReceived;
|
||||
public event Action<TimeSpan>? HeartbeatReceived;
|
||||
public event Action? SocketOpened;
|
||||
public event Action? Resumed;
|
||||
public event Action? Ready;
|
||||
public event Action<WebSocketCloseStatus?, string?>? SocketClosed;
|
||||
|
||||
private TimeSpan _reconnectDelay = TimeSpan.Zero;
|
||||
private Task? _worker;
|
||||
|
||||
public Shard(GatewaySettings settings, ShardInfo info, IGatewayRatelimiter ratelimiter, string url, ILogger logger)
|
||||
_settings = settings;
|
||||
_info = info;
|
||||
_ratelimiter = ratelimiter;
|
||||
_url = url;
|
||||
_logger = logger.ForContext<Shard>().ForContext("ShardId", info.ShardId);
|
||||
_stateManager = new ShardStateManager(info, _jsonSerializerOptions, logger)
|
||||
{
|
||||
_jsonSerializerOptions = new JsonSerializerOptions().ConfigureForMyriad();
|
||||
|
||||
_settings = settings;
|
||||
_info = info;
|
||||
_ratelimiter = ratelimiter;
|
||||
_url = url;
|
||||
_logger = logger.ForContext<Shard>().ForContext("ShardId", info.ShardId);
|
||||
_stateManager = new ShardStateManager(info, _jsonSerializerOptions, logger)
|
||||
{
|
||||
HandleEvent = HandleEvent,
|
||||
SendHeartbeat = SendHeartbeat,
|
||||
SendIdentify = SendIdentify,
|
||||
SendResume = SendResume,
|
||||
Connect = ConnectInner,
|
||||
Reconnect = Reconnect,
|
||||
};
|
||||
_stateManager.OnHeartbeatReceived += latency =>
|
||||
{
|
||||
HeartbeatReceived?.Invoke(latency);
|
||||
};
|
||||
|
||||
_conn = new ShardConnection(_jsonSerializerOptions, _logger);
|
||||
}
|
||||
|
||||
private async Task ShardLoop()
|
||||
HandleEvent = HandleEvent,
|
||||
SendHeartbeat = SendHeartbeat,
|
||||
SendIdentify = SendIdentify,
|
||||
SendResume = SendResume,
|
||||
Connect = ConnectInner,
|
||||
Reconnect = Reconnect,
|
||||
};
|
||||
_stateManager.OnHeartbeatReceived += latency =>
|
||||
{
|
||||
// may be superfluous but this adds shard id to ambient context which is nice
|
||||
using var _ = LogContext.PushProperty("ShardId", _info.ShardId);
|
||||
HeartbeatReceived?.Invoke(latency);
|
||||
};
|
||||
|
||||
while (true)
|
||||
_conn = new ShardConnection(_jsonSerializerOptions, _logger);
|
||||
}
|
||||
|
||||
private async Task ShardLoop()
|
||||
{
|
||||
// may be superfluous but this adds shard id to ambient context which is nice
|
||||
using var _ = LogContext.PushProperty("ShardId", _info.ShardId);
|
||||
|
||||
while (true)
|
||||
{
|
||||
try
|
||||
{
|
||||
try
|
||||
await ConnectInner();
|
||||
|
||||
await HandleConnectionOpened();
|
||||
|
||||
while (_conn.State == WebSocketState.Open)
|
||||
{
|
||||
await ConnectInner();
|
||||
var packet = await _conn.Read();
|
||||
if (packet == null)
|
||||
break;
|
||||
|
||||
await HandleConnectionOpened();
|
||||
|
||||
while (_conn.State == WebSocketState.Open)
|
||||
{
|
||||
var packet = await _conn.Read();
|
||||
if (packet == null)
|
||||
break;
|
||||
|
||||
await _stateManager.HandlePacketReceived(packet);
|
||||
}
|
||||
|
||||
await HandleConnectionClosed(_conn.CloseStatus, _conn.CloseStatusDescription);
|
||||
|
||||
_logger.Information("Shard {ShardId}: Reconnecting after delay {ReconnectDelay}",
|
||||
_info.ShardId, _reconnectDelay);
|
||||
|
||||
if (_reconnectDelay > TimeSpan.Zero)
|
||||
await Task.Delay(_reconnectDelay);
|
||||
_reconnectDelay = TimeSpan.Zero;
|
||||
await _stateManager.HandlePacketReceived(packet);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
_logger.Error(e, "Shard {ShardId}: Error in main shard loop, reconnecting in 5 seconds...", _info.ShardId);
|
||||
|
||||
// todo: exponential backoff here? this should never happen, ideally...
|
||||
await Task.Delay(TimeSpan.FromSeconds(5));
|
||||
}
|
||||
await HandleConnectionClosed(_conn.CloseStatus, _conn.CloseStatusDescription);
|
||||
|
||||
_logger.Information("Shard {ShardId}: Reconnecting after delay {ReconnectDelay}",
|
||||
_info.ShardId, _reconnectDelay);
|
||||
|
||||
if (_reconnectDelay > TimeSpan.Zero)
|
||||
await Task.Delay(_reconnectDelay);
|
||||
_reconnectDelay = TimeSpan.Zero;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task Start()
|
||||
{
|
||||
if (_worker == null)
|
||||
_worker = ShardLoop();
|
||||
|
||||
// Ideally we'd stagger the startups so we don't smash the websocket but that's difficult with the
|
||||
// identify rate limiter so this is the best we can do rn, maybe?
|
||||
await Task.Delay(200);
|
||||
}
|
||||
|
||||
public async Task UpdateStatus(GatewayStatusUpdate payload)
|
||||
{
|
||||
await _conn.Send(new GatewayPacket
|
||||
catch (Exception e)
|
||||
{
|
||||
Opcode = GatewayOpcode.PresenceUpdate,
|
||||
Payload = payload
|
||||
});
|
||||
}
|
||||
_logger.Error(e, "Shard {ShardId}: Error in main shard loop, reconnecting in 5 seconds...", _info.ShardId);
|
||||
|
||||
private async Task ConnectInner()
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
await _ratelimiter.Identify(_info.ShardId);
|
||||
|
||||
_logger.Information("Shard {ShardId}: Connecting to WebSocket", _info.ShardId);
|
||||
try
|
||||
{
|
||||
await _conn.Connect(_url, default);
|
||||
break;
|
||||
}
|
||||
catch (WebSocketException e)
|
||||
{
|
||||
_logger.Error(e, "Shard {ShardId}: Error connecting to WebSocket, retrying in 5 seconds...", _info.ShardId);
|
||||
await Task.Delay(TimeSpan.FromSeconds(5));
|
||||
}
|
||||
// todo: exponential backoff here? this should never happen, ideally...
|
||||
await Task.Delay(TimeSpan.FromSeconds(5));
|
||||
}
|
||||
}
|
||||
|
||||
private async Task DisconnectInner(WebSocketCloseStatus closeStatus)
|
||||
{
|
||||
await _conn.Disconnect(closeStatus, null);
|
||||
}
|
||||
|
||||
private async Task SendIdentify()
|
||||
{
|
||||
await _conn.Send(new GatewayPacket
|
||||
{
|
||||
Opcode = GatewayOpcode.Identify,
|
||||
Payload = new GatewayIdentify
|
||||
{
|
||||
Compress = false,
|
||||
Intents = _settings.Intents,
|
||||
Properties = new GatewayIdentify.ConnectionProperties
|
||||
{
|
||||
Browser = LibraryName,
|
||||
Device = LibraryName,
|
||||
Os = Environment.OSVersion.ToString()
|
||||
},
|
||||
Shard = _info,
|
||||
Token = _settings.Token,
|
||||
LargeThreshold = 50
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private async Task SendResume((string SessionId, int? LastSeq) arg)
|
||||
{
|
||||
await _conn.Send(new GatewayPacket
|
||||
{
|
||||
Opcode = GatewayOpcode.Resume,
|
||||
Payload = new GatewayResume(_settings.Token, arg.SessionId, arg.LastSeq ?? 0)
|
||||
});
|
||||
}
|
||||
|
||||
private async Task SendHeartbeat(int? lastSeq)
|
||||
{
|
||||
await _conn.Send(new GatewayPacket { Opcode = GatewayOpcode.Heartbeat, Payload = lastSeq });
|
||||
}
|
||||
|
||||
private async Task Reconnect(WebSocketCloseStatus closeStatus, TimeSpan delay)
|
||||
{
|
||||
_reconnectDelay = delay;
|
||||
await DisconnectInner(closeStatus);
|
||||
}
|
||||
|
||||
private async Task HandleEvent(IGatewayEvent arg)
|
||||
{
|
||||
if (arg is ReadyEvent)
|
||||
Ready?.Invoke();
|
||||
if (arg is ResumedEvent)
|
||||
Resumed?.Invoke();
|
||||
|
||||
await (OnEventReceived?.Invoke(arg) ?? Task.CompletedTask);
|
||||
}
|
||||
|
||||
private async Task HandleConnectionOpened()
|
||||
{
|
||||
_logger.Information("Shard {ShardId}: Connection opened", _info.ShardId);
|
||||
await _stateManager.HandleConnectionOpened();
|
||||
SocketOpened?.Invoke();
|
||||
}
|
||||
|
||||
private async Task HandleConnectionClosed(WebSocketCloseStatus? closeStatus, string? description)
|
||||
{
|
||||
_logger.Information("Shard {ShardId}: Connection closed ({CloseStatus}/{Description})",
|
||||
_info.ShardId, closeStatus, description ?? "<null>");
|
||||
await _stateManager.HandleConnectionClosed();
|
||||
SocketClosed?.Invoke(closeStatus, description);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task Start()
|
||||
{
|
||||
if (_worker == null)
|
||||
_worker = ShardLoop();
|
||||
|
||||
// Ideally we'd stagger the startups so we don't smash the websocket but that's difficult with the
|
||||
// identify rate limiter so this is the best we can do rn, maybe?
|
||||
await Task.Delay(200);
|
||||
}
|
||||
|
||||
public async Task UpdateStatus(GatewayStatusUpdate payload)
|
||||
=> await _conn.Send(new GatewayPacket
|
||||
{
|
||||
Opcode = GatewayOpcode.PresenceUpdate,
|
||||
Payload = payload
|
||||
});
|
||||
|
||||
private async Task ConnectInner()
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
await _ratelimiter.Identify(_info.ShardId);
|
||||
|
||||
_logger.Information("Shard {ShardId}: Connecting to WebSocket", _info.ShardId);
|
||||
try
|
||||
{
|
||||
await _conn.Connect(_url, default);
|
||||
break;
|
||||
}
|
||||
catch (WebSocketException e)
|
||||
{
|
||||
_logger.Error(e, "Shard {ShardId}: Error connecting to WebSocket, retrying in 5 seconds...", _info.ShardId);
|
||||
await Task.Delay(TimeSpan.FromSeconds(5));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private Task DisconnectInner(WebSocketCloseStatus closeStatus)
|
||||
=> _conn.Disconnect(closeStatus, null);
|
||||
|
||||
private async Task SendIdentify()
|
||||
=> await _conn.Send(new GatewayPacket
|
||||
{
|
||||
Opcode = GatewayOpcode.Identify,
|
||||
Payload = new GatewayIdentify
|
||||
{
|
||||
Compress = false,
|
||||
Intents = _settings.Intents,
|
||||
Properties = new GatewayIdentify.ConnectionProperties
|
||||
{
|
||||
Browser = LibraryName,
|
||||
Device = LibraryName,
|
||||
Os = Environment.OSVersion.ToString()
|
||||
},
|
||||
Shard = _info,
|
||||
Token = _settings.Token,
|
||||
LargeThreshold = 50
|
||||
}
|
||||
});
|
||||
|
||||
private async Task SendResume((string SessionId, int? LastSeq) arg)
|
||||
=> await _conn.Send(new GatewayPacket
|
||||
{
|
||||
Opcode = GatewayOpcode.Resume,
|
||||
Payload = new GatewayResume(_settings.Token, arg.SessionId, arg.LastSeq ?? 0)
|
||||
});
|
||||
|
||||
private async Task SendHeartbeat(int? lastSeq)
|
||||
=> await _conn.Send(new GatewayPacket { Opcode = GatewayOpcode.Heartbeat, Payload = lastSeq });
|
||||
|
||||
private async Task Reconnect(WebSocketCloseStatus closeStatus, TimeSpan delay)
|
||||
{
|
||||
_reconnectDelay = delay;
|
||||
await DisconnectInner(closeStatus);
|
||||
}
|
||||
|
||||
private async Task HandleEvent(IGatewayEvent arg)
|
||||
{
|
||||
if (arg is ReadyEvent)
|
||||
Ready?.Invoke();
|
||||
if (arg is ResumedEvent)
|
||||
Resumed?.Invoke();
|
||||
|
||||
await (OnEventReceived?.Invoke(arg) ?? Task.CompletedTask);
|
||||
}
|
||||
|
||||
private async Task HandleConnectionOpened()
|
||||
{
|
||||
_logger.Information("Shard {ShardId}: Connection opened", _info.ShardId);
|
||||
await _stateManager.HandleConnectionOpened();
|
||||
SocketOpened?.Invoke();
|
||||
}
|
||||
|
||||
private async Task HandleConnectionClosed(WebSocketCloseStatus? closeStatus, string? description)
|
||||
{
|
||||
_logger.Information("Shard {ShardId}: Connection closed ({CloseStatus}/{Description})",
|
||||
_info.ShardId, closeStatus, description ?? "<null>");
|
||||
await _stateManager.HandleConnectionClosed();
|
||||
SocketClosed?.Invoke(closeStatus, description);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,122 +1,115 @@
|
|||
using System;
|
||||
using System.Net.WebSockets;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
using Serilog;
|
||||
|
||||
namespace Myriad.Gateway
|
||||
namespace Myriad.Gateway;
|
||||
|
||||
public class ShardConnection: IAsyncDisposable
|
||||
{
|
||||
public class ShardConnection: IAsyncDisposable
|
||||
private readonly ILogger _logger;
|
||||
private readonly ShardPacketSerializer _serializer;
|
||||
private ClientWebSocket? _client;
|
||||
|
||||
public ShardConnection(JsonSerializerOptions jsonSerializerOptions, ILogger logger)
|
||||
{
|
||||
private ClientWebSocket? _client;
|
||||
private readonly ILogger _logger;
|
||||
private readonly ShardPacketSerializer _serializer;
|
||||
_logger = logger.ForContext<ShardConnection>();
|
||||
_serializer = new ShardPacketSerializer(jsonSerializerOptions);
|
||||
}
|
||||
|
||||
public WebSocketState State => _client?.State ?? WebSocketState.Closed;
|
||||
public WebSocketCloseStatus? CloseStatus => _client?.CloseStatus;
|
||||
public string? CloseStatusDescription => _client?.CloseStatusDescription;
|
||||
public WebSocketState State => _client?.State ?? WebSocketState.Closed;
|
||||
public WebSocketCloseStatus? CloseStatus => _client?.CloseStatus;
|
||||
public string? CloseStatusDescription => _client?.CloseStatusDescription;
|
||||
|
||||
public ShardConnection(JsonSerializerOptions jsonSerializerOptions, ILogger logger)
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
await CloseInner(WebSocketCloseStatus.NormalClosure, null);
|
||||
_client?.Dispose();
|
||||
}
|
||||
|
||||
public async Task Connect(string url, CancellationToken ct)
|
||||
{
|
||||
_client?.Dispose();
|
||||
_client = new ClientWebSocket();
|
||||
|
||||
await _client.ConnectAsync(GetConnectionUri(url), ct);
|
||||
}
|
||||
|
||||
public async Task Disconnect(WebSocketCloseStatus closeStatus, string? reason)
|
||||
{
|
||||
await CloseInner(closeStatus, reason);
|
||||
}
|
||||
|
||||
public async Task Send(GatewayPacket packet)
|
||||
{
|
||||
// from `ManagedWebSocket.s_validSendStates`
|
||||
if (_client is not { State: WebSocketState.Open or WebSocketState.CloseReceived })
|
||||
return;
|
||||
|
||||
try
|
||||
{
|
||||
_logger = logger.ForContext<ShardConnection>();
|
||||
_serializer = new(jsonSerializerOptions);
|
||||
await _serializer.WritePacket(_client, packet);
|
||||
}
|
||||
|
||||
public async Task Connect(string url, CancellationToken ct)
|
||||
catch (Exception e)
|
||||
{
|
||||
_client?.Dispose();
|
||||
_client = new ClientWebSocket();
|
||||
|
||||
await _client.ConnectAsync(GetConnectionUri(url), ct);
|
||||
_logger.Error(e, "Error sending WebSocket message");
|
||||
}
|
||||
}
|
||||
|
||||
public async Task Disconnect(WebSocketCloseStatus closeStatus, string? reason)
|
||||
{
|
||||
await CloseInner(closeStatus, reason);
|
||||
}
|
||||
|
||||
public async Task Send(GatewayPacket packet)
|
||||
{
|
||||
// from `ManagedWebSocket.s_validSendStates`
|
||||
if (_client is not { State: WebSocketState.Open or WebSocketState.CloseReceived })
|
||||
return;
|
||||
|
||||
try
|
||||
{
|
||||
await _serializer.WritePacket(_client, packet);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
_logger.Error(e, "Error sending WebSocket message");
|
||||
}
|
||||
}
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
await CloseInner(WebSocketCloseStatus.NormalClosure, null);
|
||||
_client?.Dispose();
|
||||
}
|
||||
|
||||
public async Task<GatewayPacket?> Read()
|
||||
{
|
||||
// from `ManagedWebSocket.s_validReceiveStates`
|
||||
if (_client is not { State: WebSocketState.Open or WebSocketState.CloseSent })
|
||||
return null;
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
public async Task<GatewayPacket?> Read()
|
||||
{
|
||||
// from `ManagedWebSocket.s_validReceiveStates`
|
||||
if (_client is not { State: WebSocketState.Open or WebSocketState.CloseSent })
|
||||
return null;
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
private Uri GetConnectionUri(string baseUri) => new UriBuilder(baseUri)
|
||||
return null;
|
||||
}
|
||||
|
||||
private Uri GetConnectionUri(string baseUri) => new UriBuilder(baseUri) { Query = "v=9&encoding=json" }.Uri;
|
||||
|
||||
private async Task CloseInner(WebSocketCloseStatus closeStatus, string? description)
|
||||
{
|
||||
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)
|
||||
{
|
||||
Query = "v=9&encoding=json"
|
||||
}.Uri;
|
||||
|
||||
private async Task CloseInner(WebSocketCloseStatus closeStatus, string? description)
|
||||
{
|
||||
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");
|
||||
}
|
||||
}
|
||||
|
||||
// This shouldn't need to be wrapped in a try/catch but doing it anyway :/
|
||||
// Close with timeout, mostly to work around https://github.com/dotnet/runtime/issues/51590
|
||||
var cts = new CancellationTokenSource(TimeSpan.FromSeconds(2));
|
||||
try
|
||||
{
|
||||
client.Dispose();
|
||||
await client.CloseAsync(closeStatus, description, cts.Token);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
_logger.Error(e, "Error disposing WebSocket connection");
|
||||
_logger.Error(e, "Error closing WebSocket connection");
|
||||
}
|
||||
}
|
||||
|
||||
// This shouldn't need to be wrapped in a try/catch but doing it anyway :/
|
||||
try
|
||||
{
|
||||
client.Dispose();
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
_logger.Error(e, "Error disposing WebSocket connection");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,4 +1,3 @@
|
|||
namespace Myriad.Gateway
|
||||
{
|
||||
public record ShardInfo(int ShardId, int NumShards);
|
||||
}
|
||||
namespace Myriad.Gateway;
|
||||
|
||||
public record ShardInfo(int ShardId, int NumShards);
|
||||
|
|
@ -1,70 +1,68 @@
|
|||
using System;
|
||||
using System.Buffers;
|
||||
using System.IO;
|
||||
using System.Net.WebSockets;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Myriad.Gateway
|
||||
namespace Myriad.Gateway;
|
||||
|
||||
public class ShardPacketSerializer
|
||||
{
|
||||
public class ShardPacketSerializer
|
||||
private const int BufferSize = 64 * 1024;
|
||||
|
||||
private readonly JsonSerializerOptions _jsonSerializerOptions;
|
||||
|
||||
public ShardPacketSerializer(JsonSerializerOptions jsonSerializerOptions)
|
||||
{
|
||||
private const int BufferSize = 64 * 1024;
|
||||
_jsonSerializerOptions = jsonSerializerOptions;
|
||||
}
|
||||
|
||||
private readonly JsonSerializerOptions _jsonSerializerOptions;
|
||||
public async ValueTask<(WebSocketMessageType type, GatewayPacket? packet)> ReadPacket(ClientWebSocket socket)
|
||||
{
|
||||
using var buf = MemoryPool<byte>.Shared.Rent(BufferSize);
|
||||
|
||||
public ShardPacketSerializer(JsonSerializerOptions jsonSerializerOptions)
|
||||
var res = await socket.ReceiveAsync(buf.Memory, default);
|
||||
if (res.MessageType == WebSocketMessageType.Close)
|
||||
return (res.MessageType, null);
|
||||
|
||||
if (res.EndOfMessage)
|
||||
// Entire packet fits within one buffer, deserialize directly
|
||||
return DeserializeSingleBuffer(buf, res);
|
||||
|
||||
// Otherwise copy to stream buffer and deserialize from there
|
||||
return await DeserializeMultipleBuffer(socket, buf, res);
|
||||
}
|
||||
|
||||
public async Task WritePacket(ClientWebSocket socket, GatewayPacket packet)
|
||||
{
|
||||
var bytes = JsonSerializer.SerializeToUtf8Bytes(packet, _jsonSerializerOptions);
|
||||
await socket.SendAsync(bytes.AsMemory(), WebSocketMessageType.Text, true, default);
|
||||
}
|
||||
|
||||
private async Task<(WebSocketMessageType type, GatewayPacket packet)> DeserializeMultipleBuffer(
|
||||
ClientWebSocket socket, IMemoryOwner<byte> buf, ValueWebSocketReceiveResult res)
|
||||
{
|
||||
await using var stream = new MemoryStream(BufferSize * 4);
|
||||
stream.Write(buf.Memory.Span.Slice(0, res.Count));
|
||||
|
||||
while (!res.EndOfMessage)
|
||||
{
|
||||
_jsonSerializerOptions = jsonSerializerOptions;
|
||||
}
|
||||
|
||||
public async ValueTask<(WebSocketMessageType type, GatewayPacket? packet)> ReadPacket(ClientWebSocket socket)
|
||||
{
|
||||
using var buf = MemoryPool<byte>.Shared.Rent(BufferSize);
|
||||
|
||||
var res = await socket.ReceiveAsync(buf.Memory, default);
|
||||
if (res.MessageType == WebSocketMessageType.Close)
|
||||
return (res.MessageType, null);
|
||||
|
||||
if (res.EndOfMessage)
|
||||
// Entire packet fits within one buffer, deserialize directly
|
||||
return DeserializeSingleBuffer(buf, res);
|
||||
|
||||
// Otherwise copy to stream buffer and deserialize from there
|
||||
return await DeserializeMultipleBuffer(socket, buf, res);
|
||||
}
|
||||
|
||||
public async Task WritePacket(ClientWebSocket socket, GatewayPacket packet)
|
||||
{
|
||||
var bytes = JsonSerializer.SerializeToUtf8Bytes(packet, _jsonSerializerOptions);
|
||||
await socket.SendAsync(bytes.AsMemory(), WebSocketMessageType.Text, true, default);
|
||||
}
|
||||
|
||||
private async Task<(WebSocketMessageType type, GatewayPacket packet)> DeserializeMultipleBuffer(ClientWebSocket socket, IMemoryOwner<byte> buf, ValueWebSocketReceiveResult res)
|
||||
{
|
||||
await using var stream = new MemoryStream(BufferSize * 4);
|
||||
res = await socket.ReceiveAsync(buf.Memory, default);
|
||||
stream.Write(buf.Memory.Span.Slice(0, res.Count));
|
||||
|
||||
while (!res.EndOfMessage)
|
||||
{
|
||||
res = await socket.ReceiveAsync(buf.Memory, default);
|
||||
stream.Write(buf.Memory.Span.Slice(0, res.Count));
|
||||
}
|
||||
|
||||
return DeserializeObject(res, stream.GetBuffer().AsSpan(0, (int)stream.Length));
|
||||
}
|
||||
|
||||
private (WebSocketMessageType type, GatewayPacket packet) DeserializeSingleBuffer(
|
||||
IMemoryOwner<byte> buf, ValueWebSocketReceiveResult res)
|
||||
{
|
||||
var span = buf.Memory.Span.Slice(0, res.Count);
|
||||
return DeserializeObject(res, span);
|
||||
}
|
||||
return DeserializeObject(res, stream.GetBuffer().AsSpan(0, (int)stream.Length));
|
||||
}
|
||||
|
||||
private (WebSocketMessageType type, GatewayPacket packet) DeserializeObject(ValueWebSocketReceiveResult res, Span<byte> span)
|
||||
{
|
||||
var packet = JsonSerializer.Deserialize<GatewayPacket>(span, _jsonSerializerOptions)!;
|
||||
return (res.MessageType, packet);
|
||||
}
|
||||
private (WebSocketMessageType type, GatewayPacket packet) DeserializeSingleBuffer(
|
||||
IMemoryOwner<byte> buf, ValueWebSocketReceiveResult res)
|
||||
{
|
||||
var span = buf.Memory.Span.Slice(0, res.Count);
|
||||
return DeserializeObject(res, span);
|
||||
}
|
||||
|
||||
private (WebSocketMessageType type, GatewayPacket packet) DeserializeObject(
|
||||
ValueWebSocketReceiveResult res, Span<byte> span)
|
||||
{
|
||||
var packet = JsonSerializer.Deserialize<GatewayPacket>(span, _jsonSerializerOptions)!;
|
||||
return (res.MessageType, packet);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,63 +1,58 @@
|
|||
using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
namespace Myriad.Gateway.State;
|
||||
|
||||
namespace Myriad.Gateway.State
|
||||
public class HeartbeatWorker: IAsyncDisposable
|
||||
{
|
||||
public class HeartbeatWorker: IAsyncDisposable
|
||||
private Task? _worker;
|
||||
private CancellationTokenSource? _workerCts;
|
||||
|
||||
public TimeSpan? CurrentHeartbeatInterval { get; private set; }
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
private Task? _worker;
|
||||
private CancellationTokenSource? _workerCts;
|
||||
await Stop();
|
||||
}
|
||||
|
||||
public TimeSpan? CurrentHeartbeatInterval { get; private set; }
|
||||
|
||||
public async ValueTask Start(TimeSpan heartbeatInterval, Func<Task> callback)
|
||||
{
|
||||
if (_worker != null)
|
||||
await Stop();
|
||||
|
||||
CurrentHeartbeatInterval = heartbeatInterval;
|
||||
_workerCts = new CancellationTokenSource();
|
||||
_worker = Worker(heartbeatInterval, callback, _workerCts.Token);
|
||||
}
|
||||
|
||||
public async ValueTask Stop()
|
||||
{
|
||||
if (_worker == null)
|
||||
return;
|
||||
|
||||
_workerCts?.Cancel();
|
||||
try
|
||||
{
|
||||
await _worker;
|
||||
}
|
||||
catch (TaskCanceledException) { }
|
||||
|
||||
_worker?.Dispose();
|
||||
_workerCts?.Dispose();
|
||||
_worker = null;
|
||||
CurrentHeartbeatInterval = null;
|
||||
}
|
||||
|
||||
private async Task Worker(TimeSpan heartbeatInterval, Func<Task> callback, CancellationToken ct)
|
||||
{
|
||||
var initialDelay = GetInitialHeartbeatDelay(heartbeatInterval);
|
||||
await Task.Delay(initialDelay, ct);
|
||||
|
||||
while (!ct.IsCancellationRequested)
|
||||
{
|
||||
await callback();
|
||||
await Task.Delay(heartbeatInterval, ct);
|
||||
}
|
||||
}
|
||||
|
||||
private static TimeSpan GetInitialHeartbeatDelay(TimeSpan heartbeatInterval) =>
|
||||
// Docs specify `heartbeat_interval * random.random()` but we'll add a lil buffer :)
|
||||
heartbeatInterval * (new Random().NextDouble() * 0.9 + 0.05);
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
public async ValueTask Start(TimeSpan heartbeatInterval, Func<Task> callback)
|
||||
{
|
||||
if (_worker != null)
|
||||
await Stop();
|
||||
|
||||
CurrentHeartbeatInterval = heartbeatInterval;
|
||||
_workerCts = new CancellationTokenSource();
|
||||
_worker = Worker(heartbeatInterval, callback, _workerCts.Token);
|
||||
}
|
||||
|
||||
public async ValueTask Stop()
|
||||
{
|
||||
if (_worker == null)
|
||||
return;
|
||||
|
||||
_workerCts?.Cancel();
|
||||
try
|
||||
{
|
||||
await _worker;
|
||||
}
|
||||
catch (TaskCanceledException) { }
|
||||
|
||||
_worker?.Dispose();
|
||||
_workerCts?.Dispose();
|
||||
_worker = null;
|
||||
CurrentHeartbeatInterval = null;
|
||||
}
|
||||
|
||||
private async Task Worker(TimeSpan heartbeatInterval, Func<Task> callback, CancellationToken ct)
|
||||
{
|
||||
var initialDelay = GetInitialHeartbeatDelay(heartbeatInterval);
|
||||
await Task.Delay(initialDelay, ct);
|
||||
|
||||
while (!ct.IsCancellationRequested)
|
||||
{
|
||||
await callback();
|
||||
await Task.Delay(heartbeatInterval, ct);
|
||||
}
|
||||
}
|
||||
|
||||
private static TimeSpan GetInitialHeartbeatDelay(TimeSpan heartbeatInterval) =>
|
||||
// Docs specify `heartbeat_interval * random.random()` but we'll add a lil buffer :)
|
||||
heartbeatInterval * (new Random().NextDouble() * 0.9 + 0.05);
|
||||
}
|
||||
|
|
@ -1,11 +1,10 @@
|
|||
namespace Myriad.Gateway.State
|
||||
namespace Myriad.Gateway.State;
|
||||
|
||||
public enum ShardState
|
||||
{
|
||||
public enum ShardState
|
||||
{
|
||||
Disconnected,
|
||||
Handshaking,
|
||||
Identifying,
|
||||
Connected,
|
||||
Reconnecting
|
||||
}
|
||||
Disconnected,
|
||||
Handshaking,
|
||||
Identifying,
|
||||
Connected,
|
||||
Reconnecting
|
||||
}
|
||||
|
|
@ -1,246 +1,246 @@
|
|||
using System;
|
||||
using System.Net.WebSockets;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
using Myriad.Gateway.State;
|
||||
using Myriad.Types;
|
||||
|
||||
using Serilog;
|
||||
|
||||
namespace Myriad.Gateway
|
||||
namespace Myriad.Gateway;
|
||||
|
||||
public class ShardStateManager
|
||||
{
|
||||
public class ShardStateManager
|
||||
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)
|
||||
{
|
||||
private readonly HeartbeatWorker _heartbeatWorker = new();
|
||||
private readonly ILogger _logger;
|
||||
_info = info;
|
||||
_jsonSerializerOptions = jsonSerializerOptions;
|
||||
_logger = logger.ForContext<ShardStateManager>();
|
||||
}
|
||||
|
||||
private readonly ShardInfo _info;
|
||||
private readonly JsonSerializerOptions _jsonSerializerOptions;
|
||||
private ShardState _state = ShardState.Disconnected;
|
||||
public ShardState State { get; private set; } = ShardState.Disconnected;
|
||||
|
||||
private DateTimeOffset? _lastHeartbeatSent;
|
||||
private TimeSpan? _latency;
|
||||
private bool _hasReceivedHeartbeatAck;
|
||||
public TimeSpan? Latency => _latency;
|
||||
public User? User { get; private set; }
|
||||
public ApplicationPartial? Application { get; private set; }
|
||||
|
||||
private string? _sessionId;
|
||||
private int? _lastSeq;
|
||||
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; }
|
||||
|
||||
public ShardState State => _state;
|
||||
public TimeSpan? Latency => _latency;
|
||||
public User? User { get; private set; }
|
||||
public ApplicationPartial? Application { get; private set; }
|
||||
public event Action<TimeSpan> OnHeartbeatReceived;
|
||||
|
||||
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; }
|
||||
public Task HandleConnectionOpened()
|
||||
{
|
||||
State = ShardState.Handshaking;
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public event Action<TimeSpan> OnHeartbeatReceived;
|
||||
public async Task HandleConnectionClosed()
|
||||
{
|
||||
_latency = null;
|
||||
await _heartbeatWorker.Stop();
|
||||
}
|
||||
|
||||
public ShardStateManager(ShardInfo info, JsonSerializerOptions jsonSerializerOptions, ILogger logger)
|
||||
public async Task HandlePacketReceived(GatewayPacket packet)
|
||||
{
|
||||
switch (packet.Opcode)
|
||||
{
|
||||
_info = info;
|
||||
_jsonSerializerOptions = jsonSerializerOptions;
|
||||
_logger = logger.ForContext<ShardStateManager>();
|
||||
}
|
||||
case GatewayOpcode.Hello:
|
||||
var hello = DeserializePayload<GatewayHello>(packet);
|
||||
await HandleHello(hello);
|
||||
break;
|
||||
|
||||
public Task HandleConnectionOpened()
|
||||
{
|
||||
_state = ShardState.Handshaking;
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
case GatewayOpcode.Heartbeat:
|
||||
await HandleHeartbeatRequest();
|
||||
break;
|
||||
|
||||
public async Task HandleConnectionClosed()
|
||||
{
|
||||
_latency = null;
|
||||
await _heartbeatWorker.Stop();
|
||||
}
|
||||
case GatewayOpcode.HeartbeatAck:
|
||||
await HandleHeartbeatAck();
|
||||
break;
|
||||
|
||||
public async Task HandlePacketReceived(GatewayPacket packet)
|
||||
{
|
||||
switch (packet.Opcode)
|
||||
{
|
||||
case GatewayOpcode.Hello:
|
||||
var hello = DeserializePayload<GatewayHello>(packet);
|
||||
await HandleHello(hello);
|
||||
case GatewayOpcode.Reconnect:
|
||||
{
|
||||
await HandleReconnect();
|
||||
break;
|
||||
}
|
||||
|
||||
case GatewayOpcode.Heartbeat:
|
||||
await HandleHeartbeatRequest();
|
||||
case GatewayOpcode.InvalidSession:
|
||||
{
|
||||
var canResume = DeserializePayload<bool>(packet);
|
||||
await HandleInvalidSession(canResume);
|
||||
break;
|
||||
}
|
||||
|
||||
case GatewayOpcode.HeartbeatAck:
|
||||
await HandleHeartbeatAck();
|
||||
break;
|
||||
case GatewayOpcode.Dispatch:
|
||||
_lastSeq = packet.Sequence;
|
||||
|
||||
case GatewayOpcode.Reconnect:
|
||||
{
|
||||
await HandleReconnect();
|
||||
break;
|
||||
}
|
||||
var evt = DeserializeEvent(packet.EventType!, (JsonElement)packet.Payload!);
|
||||
if (evt != null)
|
||||
{
|
||||
if (evt is ReadyEvent ready)
|
||||
await HandleReady(ready);
|
||||
|
||||
case GatewayOpcode.InvalidSession:
|
||||
{
|
||||
var canResume = DeserializePayload<bool>(packet);
|
||||
await HandleInvalidSession(canResume);
|
||||
break;
|
||||
}
|
||||
if (evt is ResumedEvent)
|
||||
await HandleResumed();
|
||||
|
||||
case GatewayOpcode.Dispatch:
|
||||
_lastSeq = packet.Sequence;
|
||||
await HandleEvent(evt);
|
||||
}
|
||||
|
||||
var evt = DeserializeEvent(packet.EventType!, (JsonElement)packet.Payload!);
|
||||
if (evt != null)
|
||||
{
|
||||
if (evt is ReadyEvent ready)
|
||||
await HandleReady(ready);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (evt is ResumedEvent)
|
||||
await HandleResumed();
|
||||
private async Task HandleHello(GatewayHello hello)
|
||||
{
|
||||
var interval = TimeSpan.FromMilliseconds(hello.HeartbeatInterval);
|
||||
|
||||
await HandleEvent(evt);
|
||||
}
|
||||
break;
|
||||
}
|
||||
_hasReceivedHeartbeatAck = true;
|
||||
await _heartbeatWorker.Start(interval, HandleHeartbeatTimer);
|
||||
await IdentifyOrResume();
|
||||
}
|
||||
|
||||
private async Task IdentifyOrResume()
|
||||
{
|
||||
State = ShardState.Identifying;
|
||||
|
||||
if (_sessionId != null)
|
||||
{
|
||||
_logger.Information("Shard {ShardId}: Received Hello, attempting to resume (seq {LastSeq})",
|
||||
_info.ShardId, _lastSeq);
|
||||
await SendResume((_sessionId!, _lastSeq));
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.Information("Shard {ShardId}: Received Hello, identifying",
|
||||
_info.ShardId);
|
||||
|
||||
await SendIdentify();
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
private async Task HandleInvalidSession(bool canResume)
|
||||
{
|
||||
if (!canResume)
|
||||
{
|
||||
_sessionId = null;
|
||||
_lastSeq = null;
|
||||
}
|
||||
|
||||
private async Task HandleHello(GatewayHello hello)
|
||||
{
|
||||
var interval = TimeSpan.FromMilliseconds(hello.HeartbeatInterval);
|
||||
_logger.Information("Shard {ShardId}: Received Invalid Session (can resume? {CanResume})",
|
||||
_info.ShardId, canResume);
|
||||
|
||||
_hasReceivedHeartbeatAck = true;
|
||||
await _heartbeatWorker.Start(interval, HandleHeartbeatTimer);
|
||||
await IdentifyOrResume();
|
||||
var delay = TimeSpan.FromMilliseconds(new Random().Next(1000, 5000));
|
||||
await DoReconnect(WebSocketCloseStatus.NormalClosure, delay);
|
||||
}
|
||||
|
||||
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));
|
||||
}
|
||||
|
||||
private Task HandleReady(ReadyEvent ready)
|
||||
{
|
||||
_logger.Information("Shard {ShardId}: Received Ready", _info.ShardId);
|
||||
|
||||
_sessionId = ready.SessionId;
|
||||
State = ShardState.Connected;
|
||||
User = ready.User;
|
||||
Application = ready.Application;
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
private Task HandleResumed()
|
||||
{
|
||||
_logger.Information("Shard {ShardId}: Received Resume", _info.ShardId);
|
||||
|
||||
State = ShardState.Connected;
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
private async Task HandleHeartbeatRequest()
|
||||
{
|
||||
await SendHeartbeatInternal();
|
||||
}
|
||||
|
||||
private async Task SendHeartbeatInternal()
|
||||
{
|
||||
await SendHeartbeat(_lastSeq);
|
||||
_lastHeartbeatSent = DateTimeOffset.UtcNow;
|
||||
}
|
||||
|
||||
private async Task HandleHeartbeatTimer()
|
||||
{
|
||||
if (!_hasReceivedHeartbeatAck)
|
||||
{
|
||||
_logger.Warning("Shard {ShardId}: Heartbeat worker timed out", _info.ShardId);
|
||||
await DoReconnect(WebSocketCloseStatus.ProtocolError, TimeSpan.Zero);
|
||||
return;
|
||||
}
|
||||
|
||||
private async Task IdentifyOrResume()
|
||||
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))
|
||||
{
|
||||
_state = ShardState.Identifying;
|
||||
|
||||
if (_sessionId != null)
|
||||
{
|
||||
_logger.Information("Shard {ShardId}: Received Hello, attempting to resume (seq {LastSeq})",
|
||||
_info.ShardId, _lastSeq);
|
||||
await SendResume((_sessionId!, _lastSeq));
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.Information("Shard {ShardId}: Received Hello, identifying",
|
||||
_info.ShardId);
|
||||
|
||||
await SendIdentify();
|
||||
}
|
||||
_logger.Debug("Shard {ShardId}: Received unknown event type {EventType}", _info.ShardId, eventType);
|
||||
return null;
|
||||
}
|
||||
|
||||
private Task HandleHeartbeatAck()
|
||||
try
|
||||
{
|
||||
_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;
|
||||
_logger.Verbose("Shard {ShardId}: Deserializing {EventType} to {ClrType}", _info.ShardId, eventType,
|
||||
clrType);
|
||||
return JsonSerializer.Deserialize(payload.GetRawText(), clrType, _jsonSerializerOptions)
|
||||
as IGatewayEvent;
|
||||
}
|
||||
|
||||
private async Task HandleInvalidSession(bool canResume)
|
||||
catch (JsonException e)
|
||||
{
|
||||
if (!canResume)
|
||||
{
|
||||
_sessionId = null;
|
||||
_lastSeq = null;
|
||||
}
|
||||
|
||||
_logger.Information("Shard {ShardId}: Received Invalid Session (can resume? {CanResume})",
|
||||
_info.ShardId, canResume);
|
||||
|
||||
var delay = TimeSpan.FromMilliseconds(new Random().Next(1000, 5000));
|
||||
await DoReconnect(WebSocketCloseStatus.NormalClosure, delay);
|
||||
}
|
||||
|
||||
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));
|
||||
}
|
||||
|
||||
private Task HandleReady(ReadyEvent ready)
|
||||
{
|
||||
_logger.Information("Shard {ShardId}: Received Ready", _info.ShardId);
|
||||
|
||||
_sessionId = ready.SessionId;
|
||||
_state = ShardState.Connected;
|
||||
User = ready.User;
|
||||
Application = ready.Application;
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
private Task HandleResumed()
|
||||
{
|
||||
_logger.Information("Shard {ShardId}: Received Resume", _info.ShardId);
|
||||
|
||||
_state = ShardState.Connected;
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
private async Task HandleHeartbeatRequest()
|
||||
{
|
||||
await SendHeartbeatInternal();
|
||||
}
|
||||
|
||||
private async Task SendHeartbeatInternal()
|
||||
{
|
||||
await SendHeartbeat(_lastSeq);
|
||||
_lastHeartbeatSent = DateTimeOffset.UtcNow;
|
||||
}
|
||||
|
||||
private async Task HandleHeartbeatTimer()
|
||||
{
|
||||
if (!_hasReceivedHeartbeatAck)
|
||||
{
|
||||
_logger.Warning("Shard {ShardId}: Heartbeat worker timed out", _info.ShardId);
|
||||
await DoReconnect(WebSocketCloseStatus.ProtocolError, TimeSpan.Zero);
|
||||
return;
|
||||
}
|
||||
|
||||
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))
|
||||
{
|
||||
_logger.Debug("Shard {ShardId}: Received unknown event type {EventType}", _info.ShardId, eventType);
|
||||
return null;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
_logger.Verbose("Shard {ShardId}: Deserializing {EventType} to {ClrType}", _info.ShardId, eventType, clrType);
|
||||
return JsonSerializer.Deserialize(payload.GetRawText(), clrType, _jsonSerializerOptions)
|
||||
as IGatewayEvent;
|
||||
}
|
||||
catch (JsonException e)
|
||||
{
|
||||
_logger.Error(e, "Shard {ShardId}: Error deserializing event {EventType} to {ClrType}", _info.ShardId, eventType, clrType);
|
||||
return null;
|
||||
}
|
||||
_logger.Error(e, "Shard {ShardId}: Error deserializing event {EventType} to {ClrType}", _info.ShardId,
|
||||
eventType, clrType);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue