Skip to content

Commit

Permalink
Reduce PubSub message parsing times by leveraging STJ sourcegen
Browse files Browse the repository at this point in the history
  • Loading branch information
ErisApps committed Oct 15, 2021
1 parent 583b9eb commit 0312051
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
12 changes: 12 additions & 0 deletions CatCore/Helpers/JSON/TwitchPubSubSerializerContext.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
using System.Text.Json.Serialization;
using CatCore.Models.Twitch.PubSub.Requests;
using CatCore.Models.Twitch.PubSub.Responses;

namespace CatCore.Helpers.JSON
{
[JsonSerializable(typeof(TopicNegotiationMessage))]
[JsonSerializable(typeof(Follow))]
internal partial class TwitchPubSubSerializerContext : JsonSerializerContext
{
}
}
10 changes: 8 additions & 2 deletions CatCore/Services/Twitch/TwitchPubSubServiceExperimentalAgent.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using System.Threading.Tasks;
using System.Timers;
using CatCore.Helpers;
using CatCore.Helpers.JSON;
using CatCore.Models.Shared;
using CatCore.Models.Twitch.PubSub;
using CatCore.Models.Twitch.PubSub.Requests;
Expand Down Expand Up @@ -360,7 +361,9 @@ async Task HandleQueue()
var fullTopic = ConvertTopic(msg.topic);
var nonce = GenerateNonce();

var jsonMessage = JsonSerializer.Serialize(new TopicNegotiationMessage(mode, new TopicNegotiationMessageData(new[] { fullTopic }), nonce));
var jsonMessage = JsonSerializer.Serialize(
new TopicNegotiationMessage(mode, new TopicNegotiationMessageData(new[] { fullTopic }), nonce),
TwitchPubSubSerializerContext.Default.TopicNegotiationMessage);

_inProgressTopicNegotiations.TryAdd(nonce, msg.topic);

Expand Down Expand Up @@ -450,15 +453,18 @@ private void HandleMessageTypeInternal(JsonElement rootElement)
{
case PubSubTopics.FOLLOWING:
{
/* TODO: Remove commented code if source-generated deserializing proves to be faster
var followingDocument = JsonDocument.Parse(message).RootElement;
var displayName = followingDocument.GetProperty("display_name").GetString()!;
var username = followingDocument.GetProperty("username").GetString()!;
var userId = followingDocument.GetProperty("user_id").GetString()!;
_logger.Debug("Main event type: {MainType} - {DisplayName} now follows channel {TargetChannelId}", topic, displayName, _channelId);
new Follow(userId, username, displayName)*/

OnFollow?.Invoke(_channelId, new Follow(userId, username, displayName));
var follow = JsonSerializer.Deserialize(message, TwitchPubSubSerializerContext.Default.Follow);
OnFollow?.Invoke(_channelId, follow);

break;
}
Expand Down

0 comments on commit 0312051

Please sign in to comment.