Files
MoShiro/backend/fleet/src/Fleet.Rpc/OutboxFrame.cs
T
2026-10-04 21:46:39 +08:00

36 lines
1.1 KiB
C#

namespace Fleet.Rpc;
/// <summary>
/// 发件箱二进制帧:<c>u8 channel | 16 字节 msg_id (UUIDv7) | 正文</c>。
/// 服务端按 msg_id 去重,持久化之后才回复 <c>fleet.outbox.ack</c>。
/// </summary>
public static class OutboxFrame
{
public const int HeaderBytes = 1 + 16;
public static bool TryParse(ReadOnlyMemory<byte> frame, out byte channel, out Guid msgId, out ReadOnlyMemory<byte> payload)
{
if (frame.Length < HeaderBytes)
{
channel = 0;
msgId = Guid.Empty;
payload = default;
return false;
}
channel = frame.Span[0];
msgId = new Guid(frame.Span.Slice(1, 16), bigEndian: true);
payload = frame[HeaderBytes..];
return true;
}
public static byte[] Build(byte channel, Guid msgId, ReadOnlySpan<byte> payload)
{
byte[] frame = new byte[HeaderBytes + payload.Length];
frame[0] = channel;
msgId.TryWriteBytes(frame.AsSpan(1, 16), bigEndian: true, out _);
payload.CopyTo(frame.AsSpan(HeaderBytes));
return frame;
}
}