Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optimize receving payloads¹ #300

Merged
merged 2 commits into from
Apr 17, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
</ItemGroup>

<ItemGroup>
<PackageReference Include="CommunityToolkit.HighPerformance" />
<PackageReference Include="Remora.Extensions.Options.Immutable" />
<PackageReference Include="System.Threading.Channels" />
</ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using CommunityToolkit.HighPerformance;
using CommunityToolkit.HighPerformance.Buffers;
using JetBrains.Annotations;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
Expand Down Expand Up @@ -225,49 +227,40 @@ public async Task<Result<IPayload>> ReceivePayloadAsync(CancellationToken ct = d
return new InvalidOperationError("The socket was not open.");
}

await using var memoryStream = new MemoryStream();
using var bufferWriter = new ArrayPoolBufferWriter<byte>(); // Backed by the ArrayPool; the only allocation is the class itself

var buffer = ArrayPool<byte>.Shared.Rent(4096);
var buffer = bufferWriter.GetMemory(4096);

try
ValueWebSocketReceiveResult result;

do
{
WebSocketReceiveResult result;
result = await _clientWebSocket.ReceiveAsync(buffer, ct);

do
if (_clientWebSocket.CloseStatus.HasValue)
{
result = await _clientWebSocket.ReceiveAsync(buffer, ct);

if (result.CloseStatus.HasValue)
if (Enum.IsDefined(typeof(GatewayCloseStatus), (int)_clientWebSocket.CloseStatus))
{
if (Enum.IsDefined(typeof(GatewayCloseStatus), (int)result.CloseStatus))
{
return new GatewayDiscordError((GatewayCloseStatus)result.CloseStatus);
}

return new GatewayWebSocketError(result.CloseStatus.Value);
return new GatewayDiscordError((GatewayCloseStatus)_clientWebSocket.CloseStatus);
}

await memoryStream.WriteAsync(buffer.AsMemory(0, result.Count), ct);
}
while (!result.EndOfMessage);

memoryStream.Seek(0, SeekOrigin.Begin);

var payload = await JsonSerializer.DeserializeAsync<IPayload>(memoryStream, _jsonOptions, ct);
if (payload is null)
{
return new NotSupportedError
(
"The received payload deserialized as a null value."
);
return new GatewayWebSocketError(_clientWebSocket.CloseStatus.Value);
}

return Result<IPayload>.FromSuccess(payload);
bufferWriter.Advance(result.Count);
}
finally
while (!result.EndOfMessage);

var payload = JsonSerializer.Deserialize<IPayload>(bufferWriter.WrittenSpan, _jsonOptions);
if (payload is null)
{
ArrayPool<byte>.Shared.Return(buffer);
return new NotSupportedError
(
"The received payload deserialized as a null value."
);
}

return Result<IPayload>.FromSuccess(payload);
}

/// <inheritdoc/>
Expand Down
1 change: 1 addition & 0 deletions Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
</PropertyGroup>
<ItemGroup>
<PackageVersion Include="CommandLineParser" Version="2.9.1" />
<PackageVersion Include="CommunityToolkit.HighPerformance" Version="8.1.0" />
<PackageVersion Include="FuzzySharp" Version="2.0.2" />
<PackageVersion Include="Humanizer.Core" Version="2.14.1" />
<PackageVersion Include="Microsoft.Extensions.Caching.Abstractions" Version="7.0.0" />
Expand Down