Skip to content

C# — Protocol Types

Core protocol types in Nnrp.Core implement packet serialization, handshake state machines, and cache management.

Import

csharp
using Nnrp.Core;

NnrpHeader

Fixed 40-byte packet header (readonly struct, IEquatable<NnrpHeader>).

Static Properties

PropertyTypeDescription
NnrpHeader.MagicReadOnlyMemory<byte>Fixed magic prefix b"NNRP"
NnrpHeader.HeaderLengthintFixed header byte length (40)
NnrpHeader.TotalLengthintAlias for HeaderLength

Properties

PropertyTypeDescription
WireFormatWireFormatWire format version
MsgTypeMessageTypeMessage type
FlagsHeaderFlagsHeader flags
MetaLenintMetadata byte count
BodyLenintBody byte count
SessionIduintSession ID
FrameIduintFrame ID
ViewIduintView ID
RouteIdushortRoute ID
TraceIdushortTrace ID

Methods

csharp
public static bool TryParse(ReadOnlySpan<byte> buffer, out NnrpHeader header);
public void WriteTo(Span<byte> destination);

NnrpFramedMessage

Complete framed message (header + metadata bytes + body bytes) (readonly struct).

PropertyTypeDescription
HeaderNnrpHeaderPacket header
MetadataBytesReadOnlyMemory<byte>Raw metadata bytes
BodyBytesReadOnlyMemory<byte>Raw body bytes
csharp
public static NnrpFramedMessage Create(NnrpHeader header, ReadOnlyMemory<byte> metadata, ReadOnlyMemory<byte> body);
public byte[] ToByteArray();

NnrpProtocolFailure

Represents a protocol-level failure (readonly struct).

PropertyTypeDescription
ErrorCodeErrorCodeError code
ErrorScopeErrorScopeError scope
SessionIduintRelated session ID
FrameIduintRelated frame ID
csharp
public static NnrpProtocolFailure AuthFailed(uint sessionId = 0);
public static NnrpProtocolFailure InvalidState(uint sessionId, uint frameId = 0);
public static NnrpProtocolFailure MalformedMessage(uint sessionId = 0);
public static NnrpProtocolFailure UnsupportedVersion(uint sessionId = 0);
public static NnrpProtocolFailure LimitExceeded(uint sessionId, uint frameId = 0);

NnrpCapabilitySelection

Negotiated session capability set (readonly struct).

PropertyTypeDescription
TransportIdTransportIdNegotiated transport type
LossToleranceLossToleranceNegotiated loss tolerance
EnableCacheboolCache enabled flag
MaxCacheEntriesintNegotiated max cache entries
MaxCacheByteslongNegotiated max cache bytes
PayloadKindMaskPayloadKindNegotiated payload type mask
csharp
public static NnrpCapabilitySelection Negotiate(
    ClientHelloMessage hello, ServerHelloAckMessage ack);

NnrpSessionStateMachine

Tracks the lifecycle state of a session.

SessionState Enum

MemberDescription
InitialNot yet connected
ConnectingHandshake in progress
ActiveActive session
ClosingGraceful close in progress
ClosedSession closed
ErrorSession in error state
csharp
public class NnrpSessionStateMachine
{
    public SessionState CurrentState { get; }
    public bool TryTransition(SessionState from, SessionState to);
    public void ForceState(SessionState state);
}

NnrpCacheKey

Cache object key (readonly struct, IEquatable<NnrpCacheKey>).

PropertyTypeDescription
KindCacheObjectKindObject type
IdulongObject ID
csharp
public static NnrpCacheKey For(CacheObjectKind kind, ulong id);

NnrpCacheStore

Thread-safe LRU cache store (sealed class).

csharp
public NnrpCacheStore(int maxEntries, long maxBytes);

public bool TryGet(NnrpCacheKey key, out ReadOnlyMemory<byte> data);
public bool Put(NnrpCacheKey key, ReadOnlyMemory<byte> data, CachePutFlags flags = CachePutFlags.None);
public int Invalidate(NnrpCacheKey key);
public int InvalidateByKind(CacheObjectKind kind);
public int InvalidateAll();

public int Count { get; }
public long BytesUsed { get; }

Typical Use Cases

Cache Pre-warming and Reuse

csharp
// Upload a static background tile to the server cache
var key = new NnrpCacheKey { KindId = CacheObjectKind.BackgroundTile, ObjectId = bgHash };
await session.PutCacheAsync(key, bgTensorData, CachePutFlags.Persistent);

// Subsequent frames reference the cache to reduce bandwidth
var req = new NnrpSubmitRequest
{
    FrameId      = frameId,
    InputProfile = InputProfile.ChangedTilesLuma,
    SubmitMode   = SubmitMode.Reference,   // reference server cache, skip re-transmission
    BudgetPolicy = BudgetPolicy.AllowPartial,
    CacheRefs    = new[] { key },
    Sections     = new[] { deltaSection }, // only transmit the delta
};

Low-Level Header Construction (debugging / adapters)

csharp
var header = new NnrpPacketHeader
{
    MessageType = MessageType.FrameSubmit,
    SessionId   = sessionId,
    PayloadSize = payload.Length,
    Flags       = HeaderFlags.None,
};
buffer.Write(header.Serialize());
buffer.Write(payload);

Common Pitfalls

WARNING

  1. NnrpCacheStore is client-local, not server-side cache. You must call PutCacheAsync() first to push data to the server before using SubmitMode.Reference.

  2. SubmitMode.Reference requires a server cache hit. If the server evicts the entry, the submit returns ErrorCode.CacheMiss — fall back to SubmitMode.Inline.

  3. NnrpPacketHeader.PayloadSize is in bytes, not section count or tile count.

  4. NnrpCacheStore evicts on whichever limit is hit firstmaxEntries or maxBytes. Increase maxBytes for large tensors.

NNRP Documentation