zcbot/windows-node/Zcbot.WindowsNode/Protocol/NodeProtocolCodec.cs

35 lines
1.0 KiB
C#

using System.Text.Json;
namespace Zcbot.WindowsNode;
internal sealed record NodeProtocolMessage(string Type, JsonElement Payload);
internal static class NodeProtocolCodec
{
internal static byte[] Encode(string type, object payload) =>
JsonSerializer.SerializeToUtf8Bytes(new
{
protocol_version = 1,
message_id = Guid.NewGuid(),
type,
sent_at = DateTimeOffset.UtcNow,
payload,
});
internal static NodeProtocolMessage? Decode(byte[] message)
{
using var document = JsonDocument.Parse(message);
if (!document.RootElement.TryGetProperty("type", out var typeValue)
|| typeValue.ValueKind != JsonValueKind.String
|| typeValue.GetString() is not string type)
{
return null;
}
var payload = document.RootElement.TryGetProperty("payload", out var payloadValue)
? payloadValue.Clone()
: default;
return new NodeProtocolMessage(type, payload);
}
}