run dotnet format
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
using System;
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
@@ -30,7 +30,7 @@ namespace Myriad.Gateway
|
||||
public IReadOnlyDictionary<int, Shard> Shards => _shards;
|
||||
public User? User => _shards.Values.Select(s => s.User).FirstOrDefault(s => s != null);
|
||||
public ApplicationPartial? Application => _shards.Values.Select(s => s.Application).FirstOrDefault(s => s != null);
|
||||
|
||||
|
||||
public async Task Start(GatewayInfo.Bot info)
|
||||
{
|
||||
await Start(info.Url, 0, info.Shards - 1, info.Shards, info.SessionStartLimit.MaxConcurrency);
|
||||
@@ -39,7 +39,7 @@ namespace Myriad.Gateway
|
||||
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);
|
||||
@@ -51,7 +51,7 @@ namespace Myriad.Gateway
|
||||
private async Task StartShards()
|
||||
{
|
||||
_logger.Information("Connecting shards...");
|
||||
foreach (var shard in _shards.Values)
|
||||
foreach (var shard in _shards.Values)
|
||||
await shard.Start();
|
||||
}
|
||||
|
||||
@@ -60,7 +60,7 @@ namespace Myriad.Gateway
|
||||
var shard = new Shard(_gatewaySettings, shardInfo, _ratelimiter!, url, _logger);
|
||||
shard.OnEventReceived += evt => OnShardEventReceived(shard, evt);
|
||||
_shards[shardInfo.ShardId] = shard;
|
||||
|
||||
|
||||
ShardCreated?.Invoke(shard);
|
||||
}
|
||||
|
||||
@@ -69,12 +69,12 @@ namespace Myriad.Gateway
|
||||
if (EventReceived != null)
|
||||
await EventReceived(shard, evt);
|
||||
}
|
||||
|
||||
|
||||
private int GetActualShardConcurrency(int recommendedConcurrency)
|
||||
{
|
||||
if (_gatewaySettings.MaxShardConcurrency == null)
|
||||
return recommendedConcurrency;
|
||||
|
||||
|
||||
return Math.Min(_gatewaySettings.MaxShardConcurrency.Value, recommendedConcurrency);
|
||||
}
|
||||
|
||||
@@ -84,7 +84,7 @@ namespace Myriad.Gateway
|
||||
{
|
||||
return new TwilightGatewayRatelimiter(_logger, _gatewaySettings.GatewayQueueUrl);
|
||||
}
|
||||
|
||||
|
||||
var concurrency = GetActualShardConcurrency(recommendedConcurrency);
|
||||
return new LocalGatewayRatelimiter(_logger, concurrency);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
using Myriad.Types;
|
||||
using Myriad.Types;
|
||||
|
||||
namespace Myriad.Gateway
|
||||
{
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
using Myriad.Types;
|
||||
using Myriad.Types;
|
||||
|
||||
namespace Myriad.Gateway
|
||||
{
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
using Myriad.Types;
|
||||
using Myriad.Types;
|
||||
|
||||
namespace Myriad.Gateway
|
||||
{
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
using Myriad.Types;
|
||||
using Myriad.Types;
|
||||
|
||||
namespace Myriad.Gateway
|
||||
{
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
namespace Myriad.Gateway
|
||||
namespace Myriad.Gateway
|
||||
{
|
||||
public record GuildDeleteEvent(ulong Id, bool Unavailable): IGatewayEvent;
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
using Myriad.Types;
|
||||
using Myriad.Types;
|
||||
|
||||
namespace Myriad.Gateway
|
||||
{
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
using Myriad.Types;
|
||||
using Myriad.Types;
|
||||
|
||||
namespace Myriad.Gateway
|
||||
{
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
using Myriad.Types;
|
||||
using Myriad.Types;
|
||||
|
||||
namespace Myriad.Gateway
|
||||
{
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
using Myriad.Types;
|
||||
using Myriad.Types;
|
||||
|
||||
namespace Myriad.Gateway
|
||||
{
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
namespace Myriad.Gateway
|
||||
namespace Myriad.Gateway
|
||||
{
|
||||
public record GuildRoleDeleteEvent(ulong GuildId, ulong RoleId): IGatewayEvent;
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
using Myriad.Types;
|
||||
using Myriad.Types;
|
||||
|
||||
namespace Myriad.Gateway
|
||||
{
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
using Myriad.Types;
|
||||
using Myriad.Types;
|
||||
|
||||
namespace Myriad.Gateway
|
||||
{
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
using System;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace Myriad.Gateway
|
||||
@@ -7,33 +7,33 @@ namespace Myriad.Gateway
|
||||
{
|
||||
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,4 +1,4 @@
|
||||
using Myriad.Types;
|
||||
using Myriad.Types;
|
||||
|
||||
namespace Myriad.Gateway
|
||||
{
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
using Myriad.Types;
|
||||
using Myriad.Types;
|
||||
|
||||
namespace Myriad.Gateway
|
||||
{
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
namespace Myriad.Gateway
|
||||
namespace Myriad.Gateway
|
||||
{
|
||||
public record MessageDeleteBulkEvent(ulong[] Ids, ulong ChannelId, ulong? GuildId): IGatewayEvent;
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
namespace Myriad.Gateway
|
||||
namespace Myriad.Gateway
|
||||
{
|
||||
public record MessageDeleteEvent(ulong Id, ulong ChannelId, ulong? GuildId): IGatewayEvent;
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
using Myriad.Types;
|
||||
using Myriad.Types;
|
||||
|
||||
namespace Myriad.Gateway
|
||||
{
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
namespace Myriad.Gateway
|
||||
namespace Myriad.Gateway
|
||||
{
|
||||
public record MessageReactionRemoveAllEvent(ulong ChannelId, ulong MessageId, ulong? GuildId): IGatewayEvent;
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
using Myriad.Types;
|
||||
using Myriad.Types;
|
||||
|
||||
namespace Myriad.Gateway
|
||||
{
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
using Myriad.Types;
|
||||
using Myriad.Types;
|
||||
|
||||
namespace Myriad.Gateway
|
||||
{
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
using Myriad.Types;
|
||||
using Myriad.Types;
|
||||
using Myriad.Utils;
|
||||
|
||||
namespace Myriad.Gateway
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
using Myriad.Types;
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
namespace Myriad.Gateway
|
||||
namespace Myriad.Gateway
|
||||
{
|
||||
public record ResumedEvent: IGatewayEvent;
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
using Myriad.Types;
|
||||
using Myriad.Types;
|
||||
|
||||
namespace Myriad.Gateway
|
||||
{
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
using Myriad.Types;
|
||||
using Myriad.Types;
|
||||
|
||||
namespace Myriad.Gateway
|
||||
{
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
using Myriad.Types;
|
||||
using Myriad.Types;
|
||||
|
||||
namespace Myriad.Gateway
|
||||
{
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
using Myriad.Types;
|
||||
using Myriad.Types;
|
||||
|
||||
namespace Myriad.Gateway
|
||||
{
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
using System;
|
||||
using System;
|
||||
|
||||
namespace Myriad.Gateway
|
||||
{
|
||||
// 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;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
using System;
|
||||
using System;
|
||||
|
||||
namespace Myriad.Gateway
|
||||
{
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace Myriad.Gateway
|
||||
{
|
||||
@@ -7,10 +7,12 @@ namespace Myriad.Gateway
|
||||
[JsonPropertyName("op")] public GatewayOpcode Opcode { get; init; }
|
||||
[JsonPropertyName("d")] public object? Payload { get; init; }
|
||||
|
||||
[JsonPropertyName("s")] [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
|
||||
[JsonPropertyName("s")]
|
||||
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
|
||||
public int? Sequence { get; init; }
|
||||
|
||||
[JsonPropertyName("t")] [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
|
||||
[JsonPropertyName("t")]
|
||||
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
|
||||
public string? EventType { get; init; }
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
namespace Myriad.Gateway
|
||||
namespace Myriad.Gateway
|
||||
{
|
||||
public record GatewaySettings
|
||||
{
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
using System.Threading.Tasks;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Myriad.Gateway.Limit
|
||||
{
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
using System;
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
using System;
|
||||
using System;
|
||||
using System.Net.Http;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
@@ -14,7 +14,7 @@ namespace Myriad.Gateway.Limit
|
||||
{
|
||||
Timeout = TimeSpan.FromSeconds(60)
|
||||
};
|
||||
|
||||
|
||||
public TwilightGatewayRatelimiter(ILogger logger, string url)
|
||||
{
|
||||
_url = url;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
namespace Myriad.Gateway
|
||||
namespace Myriad.Gateway
|
||||
{
|
||||
public record GatewayHello(int HeartbeatInterval);
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace Myriad.Gateway
|
||||
{
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
namespace Myriad.Gateway
|
||||
namespace Myriad.Gateway
|
||||
{
|
||||
public record GatewayResume(string Token, string SessionId, int Seq);
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
using Myriad.Serialization;
|
||||
using Myriad.Types;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
using System;
|
||||
using System;
|
||||
using System.Net.WebSockets;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
@@ -68,18 +68,18 @@ namespace Myriad.Gateway
|
||||
|
||||
_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
|
||||
{
|
||||
await ConnectInner();
|
||||
|
||||
|
||||
await HandleConnectionOpened();
|
||||
|
||||
while (_conn.State == WebSocketState.Open)
|
||||
@@ -90,7 +90,7 @@ namespace Myriad.Gateway
|
||||
|
||||
await _stateManager.HandlePacketReceived(packet);
|
||||
}
|
||||
|
||||
|
||||
await HandleConnectionClosed(_conn.CloseStatus, _conn.CloseStatusDescription);
|
||||
|
||||
_logger.Information("Shard {ShardId}: Reconnecting after delay {ReconnectDelay}",
|
||||
@@ -103,20 +103,20 @@ namespace Myriad.Gateway
|
||||
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));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public async Task Start()
|
||||
{
|
||||
if (_worker == null)
|
||||
_worker = ShardLoop();
|
||||
|
||||
// we can probably TCS this instead of spin loop but w/e
|
||||
while (State != ShardState.Identifying)
|
||||
while (State != ShardState.Identifying)
|
||||
await Task.Delay(100);
|
||||
}
|
||||
|
||||
@@ -128,7 +128,7 @@ namespace Myriad.Gateway
|
||||
Payload = payload
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
private async Task ConnectInner()
|
||||
{
|
||||
while (true)
|
||||
@@ -148,12 +148,12 @@ namespace Myriad.Gateway
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private async Task DisconnectInner(WebSocketCloseStatus closeStatus)
|
||||
{
|
||||
await _conn.Disconnect(closeStatus, null);
|
||||
}
|
||||
|
||||
|
||||
private async Task SendIdentify()
|
||||
{
|
||||
await _conn.Send(new GatewayPacket
|
||||
@@ -165,8 +165,8 @@ namespace Myriad.Gateway
|
||||
Intents = _settings.Intents,
|
||||
Properties = new GatewayIdentify.ConnectionProperties
|
||||
{
|
||||
Browser = LibraryName,
|
||||
Device = LibraryName,
|
||||
Browser = LibraryName,
|
||||
Device = LibraryName,
|
||||
Os = Environment.OSVersion.ToString()
|
||||
},
|
||||
Shard = _info,
|
||||
@@ -175,7 +175,7 @@ namespace Myriad.Gateway
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
private async Task SendResume((string SessionId, int? LastSeq) arg)
|
||||
{
|
||||
await _conn.Send(new GatewayPacket
|
||||
@@ -184,12 +184,12 @@ namespace Myriad.Gateway
|
||||
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});
|
||||
await _conn.Send(new GatewayPacket { Opcode = GatewayOpcode.Heartbeat, Payload = lastSeq });
|
||||
}
|
||||
|
||||
|
||||
private async Task Reconnect(WebSocketCloseStatus closeStatus, TimeSpan delay)
|
||||
{
|
||||
_reconnectDelay = delay;
|
||||
@@ -202,7 +202,7 @@ namespace Myriad.Gateway
|
||||
Ready?.Invoke();
|
||||
if (arg is ResumedEvent)
|
||||
Resumed?.Invoke();
|
||||
|
||||
|
||||
await (OnEventReceived?.Invoke(arg) ?? Task.CompletedTask);
|
||||
}
|
||||
|
||||
@@ -215,7 +215,7 @@ namespace Myriad.Gateway
|
||||
|
||||
private async Task HandleConnectionClosed(WebSocketCloseStatus? closeStatus, string? description)
|
||||
{
|
||||
_logger.Information("Shard {ShardId}: Connection closed ({CloseStatus}/{Description})",
|
||||
_logger.Information("Shard {ShardId}: Connection closed ({CloseStatus}/{Description})",
|
||||
_info.ShardId, closeStatus, description ?? "<null>");
|
||||
await _stateManager.HandleConnectionClosed();
|
||||
SocketClosed?.Invoke(closeStatus, description);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
using System;
|
||||
using System;
|
||||
using System.Net.WebSockets;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
@@ -13,11 +13,11 @@ namespace Myriad.Gateway
|
||||
private ClientWebSocket? _client;
|
||||
private readonly ILogger _logger;
|
||||
private readonly ShardPacketSerializer _serializer;
|
||||
|
||||
|
||||
public WebSocketState State => _client?.State ?? WebSocketState.Closed;
|
||||
public WebSocketCloseStatus? CloseStatus => _client?.CloseStatus;
|
||||
public string? CloseStatusDescription => _client?.CloseStatusDescription;
|
||||
|
||||
|
||||
public ShardConnection(JsonSerializerOptions jsonSerializerOptions, ILogger logger)
|
||||
{
|
||||
_logger = logger.ForContext<ShardConnection>();
|
||||
@@ -28,7 +28,7 @@ namespace Myriad.Gateway
|
||||
{
|
||||
_client?.Dispose();
|
||||
_client = new ClientWebSocket();
|
||||
|
||||
|
||||
await _client.ConnectAsync(GetConnectionUri(url), ct);
|
||||
}
|
||||
|
||||
@@ -40,7 +40,7 @@ namespace Myriad.Gateway
|
||||
public async Task Send(GatewayPacket packet)
|
||||
{
|
||||
// from `ManagedWebSocket.s_validSendStates`
|
||||
if (_client is not {State: WebSocketState.Open or WebSocketState.CloseReceived})
|
||||
if (_client is not { State: WebSocketState.Open or WebSocketState.CloseReceived })
|
||||
return;
|
||||
|
||||
try
|
||||
@@ -62,7 +62,7 @@ namespace Myriad.Gateway
|
||||
public async Task<GatewayPacket?> Read()
|
||||
{
|
||||
// from `ManagedWebSocket.s_validReceiveStates`
|
||||
if (_client is not {State: WebSocketState.Open or WebSocketState.CloseSent})
|
||||
if (_client is not { State: WebSocketState.Open or WebSocketState.CloseSent })
|
||||
return null;
|
||||
|
||||
try
|
||||
@@ -79,7 +79,7 @@ namespace Myriad.Gateway
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
private Uri GetConnectionUri(string baseUri) => new UriBuilder(baseUri)
|
||||
{
|
||||
Query = "v=9&encoding=json"
|
||||
@@ -89,10 +89,10 @@ namespace Myriad.Gateway
|
||||
{
|
||||
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)
|
||||
{
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
namespace Myriad.Gateway
|
||||
namespace Myriad.Gateway
|
||||
{
|
||||
public record ShardInfo(int ShardId, int NumShards);
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
using System;
|
||||
using System;
|
||||
using System.Buffers;
|
||||
using System.IO;
|
||||
using System.Net.WebSockets;
|
||||
@@ -10,7 +10,7 @@ namespace Myriad.Gateway
|
||||
public class ShardPacketSerializer
|
||||
{
|
||||
private const int BufferSize = 64 * 1024;
|
||||
|
||||
|
||||
private readonly JsonSerializerOptions _jsonSerializerOptions;
|
||||
|
||||
public ShardPacketSerializer(JsonSerializerOptions jsonSerializerOptions)
|
||||
@@ -21,15 +21,15 @@ namespace Myriad.Gateway
|
||||
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);
|
||||
}
|
||||
@@ -51,7 +51,7 @@ namespace Myriad.Gateway
|
||||
stream.Write(buf.Memory.Span.Slice(0, res.Count));
|
||||
}
|
||||
|
||||
return DeserializeObject(res, stream.GetBuffer().AsSpan(0, (int) stream.Length));
|
||||
return DeserializeObject(res, stream.GetBuffer().AsSpan(0, (int)stream.Length));
|
||||
}
|
||||
|
||||
private (WebSocketMessageType type, GatewayPacket packet) DeserializeSingleBuffer(
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
using System;
|
||||
using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
@@ -8,7 +8,7 @@ namespace Myriad.Gateway.State
|
||||
{
|
||||
private Task? _worker;
|
||||
private CancellationTokenSource? _workerCts;
|
||||
|
||||
|
||||
public TimeSpan? CurrentHeartbeatInterval { get; private set; }
|
||||
|
||||
public async ValueTask Start(TimeSpan heartbeatInterval, Func<Task> callback)
|
||||
@@ -23,9 +23,9 @@ namespace Myriad.Gateway.State
|
||||
|
||||
public async ValueTask Stop()
|
||||
{
|
||||
if (_worker == null)
|
||||
if (_worker == null)
|
||||
return;
|
||||
|
||||
|
||||
_workerCts?.Cancel();
|
||||
try
|
||||
{
|
||||
@@ -38,12 +38,12 @@ namespace Myriad.Gateway.State
|
||||
_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();
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
namespace Myriad.Gateway.State
|
||||
namespace Myriad.Gateway.State
|
||||
{
|
||||
public enum ShardState
|
||||
{
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
using System;
|
||||
using System;
|
||||
using System.Net.WebSockets;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
@@ -18,7 +18,7 @@ namespace Myriad.Gateway
|
||||
private readonly ShardInfo _info;
|
||||
private readonly JsonSerializerOptions _jsonSerializerOptions;
|
||||
private ShardState _state = ShardState.Disconnected;
|
||||
|
||||
|
||||
private DateTimeOffset? _lastHeartbeatSent;
|
||||
private TimeSpan? _latency;
|
||||
private bool _hasReceivedHeartbeatAck;
|
||||
@@ -30,7 +30,7 @@ namespace Myriad.Gateway
|
||||
public TimeSpan? Latency => _latency;
|
||||
public User? User { get; private set; }
|
||||
public ApplicationPartial? Application { get; private set; }
|
||||
|
||||
|
||||
public Func<Task> SendIdentify { get; init; }
|
||||
public Func<(string SessionId, int? LastSeq), Task> SendResume { get; init; }
|
||||
public Func<int?, Task> SendHeartbeat { get; init; }
|
||||
@@ -52,7 +52,7 @@ namespace Myriad.Gateway
|
||||
_state = ShardState.Handshaking;
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
|
||||
public async Task HandleConnectionClosed()
|
||||
{
|
||||
_latency = null;
|
||||
@@ -71,36 +71,36 @@ namespace Myriad.Gateway
|
||||
case GatewayOpcode.Heartbeat:
|
||||
await HandleHeartbeatRequest();
|
||||
break;
|
||||
|
||||
|
||||
case GatewayOpcode.HeartbeatAck:
|
||||
await HandleHeartbeatAck();
|
||||
break;
|
||||
|
||||
|
||||
case GatewayOpcode.Reconnect:
|
||||
{
|
||||
await HandleReconnect();
|
||||
break;
|
||||
}
|
||||
{
|
||||
await HandleReconnect();
|
||||
break;
|
||||
}
|
||||
|
||||
case GatewayOpcode.InvalidSession:
|
||||
{
|
||||
var canResume = DeserializePayload<bool>(packet);
|
||||
await HandleInvalidSession(canResume);
|
||||
break;
|
||||
}
|
||||
{
|
||||
var canResume = DeserializePayload<bool>(packet);
|
||||
await HandleInvalidSession(canResume);
|
||||
break;
|
||||
}
|
||||
|
||||
case GatewayOpcode.Dispatch:
|
||||
case GatewayOpcode.Dispatch:
|
||||
_lastSeq = packet.Sequence;
|
||||
|
||||
var evt = DeserializeEvent(packet.EventType!, (JsonElement) packet.Payload!);
|
||||
var evt = DeserializeEvent(packet.EventType!, (JsonElement)packet.Payload!);
|
||||
if (evt != null)
|
||||
{
|
||||
if (evt is ReadyEvent ready)
|
||||
if (evt is ReadyEvent ready)
|
||||
await HandleReady(ready);
|
||||
|
||||
if (evt is ResumedEvent)
|
||||
|
||||
if (evt is ResumedEvent)
|
||||
await HandleResumed();
|
||||
|
||||
|
||||
await HandleEvent(evt);
|
||||
}
|
||||
break;
|
||||
@@ -110,7 +110,7 @@ namespace Myriad.Gateway
|
||||
private async Task HandleHello(GatewayHello hello)
|
||||
{
|
||||
var interval = TimeSpan.FromMilliseconds(hello.HeartbeatInterval);
|
||||
|
||||
|
||||
_hasReceivedHeartbeatAck = true;
|
||||
await _heartbeatWorker.Start(interval, HandleHeartbeatTimer);
|
||||
await IdentifyOrResume();
|
||||
@@ -152,14 +152,14 @@ namespace Myriad.Gateway
|
||||
_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);
|
||||
@@ -167,7 +167,7 @@ namespace Myriad.Gateway
|
||||
// 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);
|
||||
@@ -218,10 +218,10 @@ namespace Myriad.Gateway
|
||||
|
||||
private T DeserializePayload<T>(GatewayPacket packet)
|
||||
{
|
||||
var packetPayload = (JsonElement) packet.Payload!;
|
||||
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))
|
||||
|
||||
Reference in New Issue
Block a user