StellaOps.Router.Common

Shared Router types: frames, endpoint descriptors, options and the transport and plugin contracts used by microservices, gateways and transports.

PackageStellaOps.Router.Common
ComponentRouter
LicenceApache-2.0
Package kindLibrary
Target frameworknet10.0

To add the package to a project, see Installing Stella Ops packages.

Namespaces

NamespaceTypes
StellaOps.Router.Common2
StellaOps.Router.Common.Abstractions9
StellaOps.Router.Common.Enums3
StellaOps.Router.Common.Frames18
StellaOps.Router.Common.Identity3
StellaOps.Router.Common.Models24
StellaOps.Router.Common.Plugins5

StellaOps.Router.Common namespace

TypeKindDescription
PathMatcherclassMatches request paths against route templates.
PathTemplateSpecificityclassRanks route templates that all match the same request path, from most to least specific.

PathMatcher class

public sealed class PathMatcher

Matches request paths against route templates.

PathMatcher(string, bool) constructor

public PathMatcher(string template, bool caseInsensitive = true)

Initializes a new instance of the PathMatcherclass.

Parameters

Template property

public string Template { get; }

Gets the route template.

IsMatch(string) method

public bool IsMatch(string path)

Checks if a path matches the template.

Parameters

Returns

True if the path matches.

TryMatch(string, out Dictionary<string, string>) method

public bool TryMatch(string path, out Dictionary<string, string> parameters)

Tries to match a path against the template.

Parameters

Returns

True if the path matches.

PathTemplateSpecificity class

public static class PathTemplateSpecificity

Ranks route templates that all match the same request path, from most to least specific.

Remarks

Raw template length is not a specificity signal: a parameter placeholder is usually longer than the literal it competes with, so ordering by length alone lets an unconstrained /prefix/{id} out-rank a sibling literal /prefix/export — and where the two are published by DIFFERENT services, the loser’s surface becomes unreachable through the gateway with nothing in the route table to show for it.

A route constraint (for example {artifactDigest:digest}) removes the ambiguity at the source instead of ranking it at the gateway. The ordering applies to every template pair without such a constraint, so it is applied unconditionally rather than behind a flag.

MostSpecificFirst property

public static IComparer<string> MostSpecificFirst { get; }

Orders templates most-specific-first, for use as an ascending sort comparer.

Compare(string, string) method

public static int Compare(string? left, string? right)

Compares two templates, returning a negative value when left is the more specific of the two.

LiteralSegmentCount(string) method

public static int LiteralSegmentCount(string? template)

Counts the segments of template that contain no parameter placeholder.

ParameterSegmentCount(string) method

public static int ParameterSegmentCount(string? template)

Counts the segments of template that contain a parameter placeholder.

StellaOps.Router.Common.Abstractions namespace

TypeKindDescription
IGatewayConnectionTransportServerinterfaceGateway-side contract for connection-oriented Router transport servers.
IGatewayMessagingTransportServerinterfaceGateway-side contract for queue-backed messaging transport servers.
IGlobalRoutingStateinterfaceProvides global routing state derived from all live connections.
IMicroserviceTransportinterfaceRepresents a transport connection from a microservice to the gateway.
IRegionProviderinterfaceProvides region information for routing decisions.
IRoutingPlugininterfaceProvides extensibility for routing decisions.
ITransportClientinterfaceRepresents a transport client for sending requests to microservices.
ITransportServerinterfaceRepresents a transport server that accepts connections from microservices.
TransportStreamingDispatchclassThe streaming dispatch of the transports whose microservice side answers each request with one response frame.

IGatewayConnectionTransportServer interface

public interface IGatewayConnectionTransportServer : ITransportServer

Gateway-side contract for connection-oriented Router transport servers.

TransportType property

TransportType TransportType { get; }

The transport this server provides.

OnDisconnection event

event Action<string>? OnDisconnection

Raised when a connection closes, with its identifier.

OnFrame event

event Action<string, Frame>? OnFrame

Raised for each frame a connection receives, with the connection identifier.

CloseConnection(string) method

bool CloseConnection(string connectionId)

Closes a connection.

Parameters

Returns

true when the connection existed and was closed.

SendFrameAsync(string, Frame, CancellationToken) method

Task SendFrameAsync(string connectionId, Frame frame, CancellationToken cancellationToken = default)

Sends a frame on a connection.

Parameters

Returns

A task that completes when the frame is sent.

IGatewayMessagingTransportServer interface

public interface IGatewayMessagingTransportServer : ITransportServer

Gateway-side contract for queue-backed messaging transport servers.

OnConnectionClosed event

event Func<string, Task>? OnConnectionClosed

Raised when a microservice connection closes, with its identifier.

OnEndpointsUpdated event

event Func<ConnectionState, EndpointsUpdatePayload, Task>? OnEndpointsUpdated

Raised when a microservice replays or updates its endpoints.

OnHeartbeatReceived event

event Func<ConnectionState, HeartbeatPayload, Task>? OnHeartbeatReceived

Raised for each heartbeat of a microservice.

OnHelloReceived event

event Func<ConnectionState, HelloPayload, Task>? OnHelloReceived

Raised when a microservice announces itself and its endpoints (a HELLO).

OnResponseReceived event

event Func<ConnectionState, Frame, Task>? OnResponseReceived

Raised for each response frame a microservice sends.

SendToMicroserviceAsync(string, Frame, CancellationToken) method

ValueTask SendToMicroserviceAsync(string connectionId, Frame frame, CancellationToken cancellationToken)

Sends a frame to the microservice of a connection.

Parameters

Returns

A task that completes when the frame is queued.

IGlobalRoutingState interface

public interface IGlobalRoutingState

Provides global routing state derived from all live connections.

AddConnection(ConnectionState) method

void AddConnection(ConnectionState connection)

Adds a connection to the routing state.

Parameters

GetAllConnections() method

IReadOnlyList<ConnectionState> GetAllConnections()

Gets all active connections.

Returns

All active connections.

GetConnection(string) method

ConnectionState? GetConnection(string connectionId)

Gets a connection by its ID.

Parameters

Returns

The connection state, or null if not found.

GetConnectionsFor(EndpointDescriptor) method

IReadOnlyList<ConnectionState> GetConnectionsFor(EndpointDescriptor endpoint)

Finds instances of an already-resolved canonical endpoint without matching paths again.

GetConnectionsFor(string, string, string, string) method

IReadOnlyList<ConnectionState> GetConnectionsFor(string serviceName, string version, string method, string path)

Gets all connections that can handle the specified endpoint.

Parameters

Returns

The available connection states.

MatchesEndpoint(EndpointDescriptor, string) method

bool MatchesEndpoint(EndpointDescriptor endpoint, string path)

Matches a registered endpoint using its retained route matcher.

RemoveConnection(string) method

void RemoveConnection(string connectionId)

Removes a connection from the routing state.

Parameters

ResolveEndpoint(string, string) method

EndpointDescriptor? ResolveEndpoint(string method, string path)

Resolves an HTTP request to an endpoint descriptor.

Parameters

Returns

The endpoint descriptor, or null if not found.

UpdateConnection(string, Action<ConnectionState>) method

void UpdateConnection(string connectionId, Action<ConnectionState> update)

Updates an existing connection’s state.

Parameters

IMicroserviceTransport interface

public interface IMicroserviceTransport

Represents a transport connection from a microservice to the gateway. This interface is used by the Microservice SDK to communicate with the router.

OnCancelReceived event

event Func<Guid, string?, Task>? OnCancelReceived

Event raised when a CANCEL frame is received from the gateway.

OnRequestReceived event

event Func<Frame, CancellationToken, Task<Frame>>? OnRequestReceived

Event raised when a REQUEST frame is received from the gateway.

OnResyncRequested event

event Func<RegistrationResyncRequestPayload, CancellationToken, Task>? OnResyncRequested

Event raised when the router explicitly requests a fresh endpoint metadata replay.

TransportDied event

event Action? TransportDied

Raised when the transport connection is permanently lost and cannot recover. Consumers should reconnect by calling IMicroserviceTransport.ConnectAsync(InstanceDescriptor, IReadOnlyList<EndpointDescriptor>, CancellationToken)again.

ConnectAsync(InstanceDescriptor, IReadOnlyList<EndpointDescriptor>, CancellationToken) method

Task ConnectAsync(InstanceDescriptor instance, IReadOnlyList<EndpointDescriptor> endpoints, CancellationToken cancellationToken)

Connects to the router and registers the microservice.

Parameters

ConnectAsync(InstanceDescriptor, IReadOnlyList<EndpointDescriptor>, IReadOnlyDictionary<string, SchemaDefinition>, ServiceOpenApiInfo, CancellationToken) method

Task ConnectAsync(InstanceDescriptor instance, IReadOnlyList<EndpointDescriptor> endpoints, IReadOnlyDictionary<string, SchemaDefinition>? schemas, ServiceOpenApiInfo? openApiInfo, CancellationToken cancellationToken)

Connects to the router and registers the microservice, including schemas and OpenAPI metadata.

Parameters

DisconnectAsync() method

Task DisconnectAsync()

Disconnects from the router.

SendEndpointsUpdateAsync(IReadOnlyList<EndpointDescriptor>, IReadOnlyDictionary<string, SchemaDefinition>, ServiceOpenApiInfo, CancellationToken) method

Task SendEndpointsUpdateAsync(IReadOnlyList<EndpointDescriptor> endpoints, IReadOnlyDictionary<string, SchemaDefinition>? schemas, ServiceOpenApiInfo? openApiInfo, CancellationToken cancellationToken)

Sends the current endpoint/schema/OpenAPI metadata after the router explicitly requests a replay.

SendGoodbyeAsync(CancellationToken) method

Task SendGoodbyeAsync(CancellationToken cancellationToken)

Sends a best-effort Goodbye control frame before shutdown. Transports that do not maintain a live microservice connection may no-op.

Parameters

SendHeartbeatAsync(HeartbeatPayload, CancellationToken) method

Task SendHeartbeatAsync(HeartbeatPayload heartbeat, CancellationToken cancellationToken)

Sends a heartbeat to the router.

Parameters

IRegionProvider interface

public interface IRegionProvider

Provides region information for routing decisions.

NeighborRegions property

IReadOnlyList<string> NeighborRegions { get; }

Gets the neighbor regions in order of preference.

Region property

string Region { get; }

Gets the current gateway region.

IRoutingPlugin interface

public interface IRoutingPlugin

Provides extensibility for routing decisions.

ChooseInstanceAsync(RoutingContext, CancellationToken) method

Task<RoutingDecision?> ChooseInstanceAsync(RoutingContext context, CancellationToken cancellationToken)

Chooses an instance for the routing context.

Parameters

Returns

The routing decision, or null if this plugin cannot decide.

ITransportClient interface

public interface ITransportClient

Represents a transport client for sending requests to microservices.

SendCancelAsync(ConnectionState, Guid, string) method

Task SendCancelAsync(ConnectionState connection, Guid correlationId, string? reason = null)

Sends a cancellation request.

Parameters

SendRequestAsync(ConnectionState, Frame, TimeSpan, CancellationToken) method

Task<Frame> SendRequestAsync(ConnectionState connection, Frame requestFrame, TimeSpan timeout, CancellationToken cancellationToken)

Sends a request and waits for a response.

Parameters

Returns

The response frame.

SendStreamingAsync(ConnectionState, Frame, Stream, Func<ResponseFrame, Stream, Task>, PayloadLimits, CancellationToken) method

Task SendStreamingAsync(ConnectionState connection, Frame requestHeader, Stream requestBody, Func<ResponseFrame, Stream, Task> readResponse, PayloadLimits limits, CancellationToken cancellationToken)

Sends a request whose body is read from a stream and hands the microservice’s response to readResponse. TransportStreamingDispatch.SendBufferedAsync(ITransportClient, ConnectionState, Frame, Stream, Func<ResponseFrame, Stream, Task>, PayloadLimits, CancellationToken)implements it for transports whose microservice side answers a request with one response frame.

Parameters

ITransportServer interface

public interface ITransportServer

Represents a transport server that accepts connections from microservices.

StartAsync(CancellationToken) method

Task StartAsync(CancellationToken cancellationToken)

Starts listening for incoming connections.

Parameters

StopAsync(CancellationToken) method

Task StopAsync(CancellationToken cancellationToken)

Stops accepting new connections.

Parameters

TransportStreamingDispatch class

public static class TransportStreamingDispatch

The streaming dispatch of the transports whose microservice side answers each request with one response frame. The Microservice SDK dispatches one REQUEST frame and returns one RESPONSE frame; it does not assemble REQUEST_STREAM_DATA frames into a request body. So the request body is read up to PayloadLimits.MaxRequestBytesPerCalland sent as the payload of one REQUEST frame through ITransportClient.SendRequestAsync(ConnectionState, Frame, TimeSpan, CancellationToken), and the RESPONSE frame is handed over as its head (status code and headers) and its body.

SendBufferedAsync(ITransportClient, ConnectionState, Frame, Stream, Func<ResponseFrame, Stream, Task>, PayloadLimits, CancellationToken) method

public static Task SendBufferedAsync(ITransportClient client, ConnectionState connection, Frame requestHeader, Stream requestBody, Func<ResponseFrame, Stream, Task> readResponse, PayloadLimits limits, CancellationToken cancellationToken)

Sends requestBody as the payload of one request frame and passes the microservice’s response head and body to readResponse.

Parameters

Exceptions

StellaOps.Router.Common.Enums namespace

TypeKindDescription
FrameTypeenumDefines the frame types used in the router protocol.
InstanceHealthStatusenumDefines the health status of a microservice instance.
TransportTypeenumDefines the transport types supported for microservice-to-router communication.

FrameType enum

public enum FrameType

Defines the frame types used in the router protocol.

ValueDescription
Hello = 0Initial registration frame sent by microservice.
Heartbeat = 1Periodic health check frame.
Request = 2Request frame containing method, path, headers, and body.
Response = 3Response frame containing status, headers, and body.
RequestStreamData = 4Streaming request data frame.
ResponseStreamData = 5Streaming response data frame.
Cancel = 6Cancellation frame for aborting in-flight requests.
ResyncRequest = 7Gateway-to-service control frame requesting a fresh endpoint metadata replay.
EndpointsUpdate = 8Optional frame for updating endpoint metadata at runtime.
Goodbye = 9Sent by microservice to gateway immediately before shutdown to request prompt deregistration without waiting for lease expiry.

InstanceHealthStatus enum

public enum InstanceHealthStatus

Defines the health status of a microservice instance.

ValueDescription
Unknown = 0Health status is not yet determined.
Healthy = 1Instance is healthy and can accept requests.
Degraded = 2Instance is degraded but can still accept requests.
Draining = 3Instance is draining and will not accept new requests.
Unhealthy = 4Instance is unhealthy and should not receive requests.

TransportType enum

public enum TransportType

Defines the transport types supported for microservice-to-router communication. Note: HTTP is explicitly excluded per specification.

ValueDescription
InMemory = 0In-memory transport for testing and local development.
Udp = 1UDP transport for small/bounded payloads.
Tcp = 2TCP transport with length-prefixed framing.
Certificate = 3Certificate-based TCP (TLS/mTLS) transport with certificate-based authentication.
RabbitMq = 4RabbitMQ transport for queue-based communication.
Messaging = 5Messaging transport using StellaOps.Messaging (Valkey/Postgres/InMemory).

StellaOps.Router.Common.Frames namespace

TypeKindDescription
ControlFrameCodecclassEncodes and decodes the HELLO and HEARTBEAT payloads of the connection transports (TCP, TLS, UDP, RabbitMQ).
FrameCanonicalBytesclassComputes the canonical byte representation of a router frame for the purpose of HMAC sealing/verification.
FrameCanonicalBytes.DecodedFramerecordDecoded canonical frame fields.
FrameConverterclassConverts between generic Frame and typed frame records.
FrameEnvelopeOptionsclassConfiguration for the frame-layer envelope HMAC pipeline (signer + verifier).
FrameEnvelopeRejectedExceptionclassThrown when an inbound frame fails envelope-HMAC verification.
FrameEnvelopeRejectionReasonenumWhy IFrameEnvelopeVerifierrejected a frame.
FrameEnvelopeSealrecordCarries the gateway-issued integrity stamp attached to every router frame when frame-layer envelope HMAC is enforced.
FrameEnvelopeServiceCollectionExtensionsclassRegisters frame-envelope HMAC services when the operator supplies the FrameEnvelopeOptions.SectionNameconfiguration section.
HmacFrameEnvelopeSignerclassDefault IFrameEnvelopeSignerbacked by IHmacAlgorithm (HMAC-SHA256).
HmacFrameEnvelopeVerifierclassDefault IFrameEnvelopeVerifierbacked by IHmacAlgorithm.
IFrameEnvelopeSignerinterfaceSigns a router frame with the gateway-issued envelope HMAC.
IFrameEnvelopeVerifierinterfaceVerifies that a router frame carries a valid gateway-issued envelope HMAC.
PayloadTooLargeExceptionclassA frame, a datagram or a request body is larger than its transport or the configured limit accepts.
RequestFramerecordRepresents a REQUEST frame sent from gateway to microservice.
ResponseFramerecordRepresents a RESPONSE frame sent from microservice to gateway.
TransportErrorResponsesclassResponse frames a transport client sends in place of a response it cannot send.
TransportFrameHeaderclassThe frame header shared by the TCP, TLS and UDP transports: [1-byte frame type][1-byte correlation length N][N bytes UTF-8 correlation id].

ControlFrameCodec class

public static class ControlFrameCodec

Encodes and decodes the HELLO and HEARTBEAT payloads of the connection transports (TCP, TLS, UDP, RabbitMQ). Both the microservice side and the gateway side use this type, so the two ends cannot disagree on the wire format. The JSON shape (camelCase property names) is the one the Messaging transport already uses for the same records.

CreateConnectionState(string, TransportType, HelloPayload, DateTime) method

public static ConnectionState CreateConnectionState(string connectionId, TransportType transportType, HelloPayload hello, DateTime connectedAtUtc)

Builds the connection state the gateway keeps for an instance that sent HELLO.

Parameters

Returns

The connection state with the published endpoints.

CreateHello(InstanceDescriptor, IReadOnlyList<EndpointDescriptor>, IReadOnlyDictionary<string, SchemaDefinition>, ServiceOpenApiInfo) method

public static HelloPayload CreateHello(InstanceDescriptor instance, IReadOnlyList<EndpointDescriptor> endpoints, IReadOnlyDictionary<string, SchemaDefinition>? schemas, ServiceOpenApiInfo? openApiInfo)

Builds the HELLO payload a microservice sends when it connects.

Parameters

Returns

The HELLO payload.

SerializeHeartbeat(HeartbeatPayload) method

public static byte[] SerializeHeartbeat(HeartbeatPayload heartbeat)

Serializes a HEARTBEAT payload.

Parameters

Returns

The UTF-8 JSON bytes.

SerializeHello(HelloPayload) method

public static byte[] SerializeHello(HelloPayload payload)

Serializes a HELLO payload. EndpointDescriptor.HandlerTypeis a process-local handler reference that cannot cross a process boundary; the model marks it [JsonIgnore], so it is never written.

Parameters

Returns

The UTF-8 JSON bytes.

TryDeserializeHeartbeat(ReadOnlySpan<byte>, out HeartbeatPayload) method

public static bool TryDeserializeHeartbeat(ReadOnlySpan<byte> payload, out HeartbeatPayload? heartbeat)

Decodes a HEARTBEAT payload.

Parameters

Returns

true when the payload is a well-formed heartbeat.

TryDeserializeHello(ReadOnlySpan<byte>, out HelloPayload, out string) method

public static bool TryDeserializeHello(ReadOnlySpan<byte> payload, out HelloPayload? hello, out string error)

Decodes a HELLO payload. An empty payload is an error: every connection transport must identify the instance and publish its endpoints in HELLO.

Parameters

Returns

true when the payload is a well-formed HELLO.

FrameCanonicalBytes class

public static class FrameCanonicalBytes

Computes the canonical byte representation of a router frame for the purpose of HMAC sealing/verification.

Remarks

Determinism is non-negotiable: the canonical form must be identical across processes, languages, and OS line endings, otherwise gateway and service will compute different MACs over the same frame. The encoding is therefore an explicit length-prefixed binary form with a stable header, version marker, and field order. JSON serialisation is not used here — JSON property ordering is implementation-defined and would break sealing.

Wire layout (all big-endian, explicit lengths):

  1. 4 bytes magic "FECB" (Frame Envelope Canonical Bytes).
  2. 1 byte canonical-form version (currently 1).
  3. 1 byte FrameTypeas the underlying enum value.
  4. 2-byte length + UTF-8 bytes of the correlation id (or 0 if null).
  5. 2-byte length + UTF-8 bytes of the key id.
  6. 8 bytes Unix-millisecond UTC issued-at timestamp.
  7. 4-byte length + payload bytes.

CanonicalVersion constant

public const byte CanonicalVersion = 1

Canonical-form version. Bump when the layout changes; verifiers reject frames with a future version they cannot decode.

Magic field

public static readonly byte[] Magic

Magic header used to namespace the canonical bytes so a stray HMAC computation cannot accidentally validate a different binary.

Compute(Frame, string, DateTimeOffset) method

public static byte[] Compute(Frame frame, string keyId, DateTimeOffset issuedAtUtc)

Compute canonical bytes for a frame at a specific issuance timestamp using a specific signing key id.

Decode(ReadOnlySpan<byte>) method

public static FrameCanonicalBytes.DecodedFrame Decode(ReadOnlySpan<byte> canonicalBytes)

Decodes bytes produced by FrameCanonicalBytes.Compute(Frame, string, DateTimeOffset)back into their frame and envelope inputs.

FrameCanonicalBytes.DecodedFrame record

public sealed record DecodedFrame

Decoded canonical frame fields.

Parameters

DecodedFrame(Frame, string, DateTimeOffset) constructor

public DecodedFrame(Frame Frame, string KeyId, DateTimeOffset IssuedAtUtc)

Decoded canonical frame fields.

Parameters

Frame property

public Frame Frame { get; init; }

The frame.

IssuedAtUtc property

public DateTimeOffset IssuedAtUtc { get; init; }

When the frame was issued, in UTC.

KeyId property

public string KeyId { get; init; }

The identifier of the key the frame was signed with.

FrameConverter class

public static class FrameConverter

Converts between generic Frame and typed frame records.

IsGoodbyeFrame(Frame) method

public static bool IsGoodbyeFrame(Frame frame)

Returns true when the frame is a valid Goodbye control frame.

ToFrame(RequestFrame) method

public static Frame ToFrame(RequestFrame request)

Converts a RequestFrame to a generic Frame for transport.

ToFrame(ResponseFrame) method

public static Frame ToFrame(ResponseFrame response)

Converts a ResponseFrame to a generic Frame for transport.

ToGoodbyeFrame(string) method

public static Frame ToGoodbyeFrame(string? correlationId = null)

Creates a Goodbye control frame. Goodbye carries no payload beyond the standard frame envelope.

ToRequestFrame(Frame) method

public static RequestFrame? ToRequestFrame(Frame frame)

Converts a generic Frame to a RequestFrame.

ToResponseFrame(Frame) method

public static ResponseFrame? ToResponseFrame(Frame frame)

Converts a generic Frame to a ResponseFrame.

FrameEnvelopeOptions class

public sealed class FrameEnvelopeOptions

Configuration for the frame-layer envelope HMAC pipeline (signer + verifier). All fields are deterministic; a missing / empty key map indicates the host has not been bootstrapped and the HmacFrameEnvelopeSigner/ HmacFrameEnvelopeVerifierconstructors will refuse to operate rather than fall back to “no integrity”.

FrameEnvelopeOptions() constructor

public FrameEnvelopeOptions()

Creates an instance of FrameEnvelopeOptions.

DefaultReplayWindow field

public static readonly TimeSpan DefaultReplayWindow

Default replay window. The gateway and microservices share clocks loosely (NTP), and the default accepts ±5 minutes of skew so a microservice behind a slow boot sequence still verifies new frames. Configurable to widen for offline / air-gap deployments where NTP is best-effort.

SectionName constant

public const string SectionName = "Router:Frame:Envelope"

Configuration section under which the host binds these options.

ActiveKeyId property

public string ActiveKeyId { get; set; }

Active signing key id used by the signer. Must be present in FrameEnvelopeOptions.Keys. Verifiers ignore this field — they trust the key id carried inside the seal — so rotation works by adding a new key to FrameEnvelopeOptions.Keyson every host first, then flipping FrameEnvelopeOptions.ActiveKeyIdon the gateway.

Keys property

public Dictionary<string, string> Keys { get; set; }

Map of key id to UTF-8 signing key material. Multiple entries support a rotation window where verifiers accept frames signed by either the previous or the new key. Empty == disabled, which means any constructor that wires this up will throw at startup.

ReplayWindow property

public TimeSpan ReplayWindow { get; set; }

How far the issued-at timestamp on a frame may drift from “now” before the verifier rejects it. Default: ±5 minutes. The window is applied symmetrically (past and future) to absorb gateway / service clock skew.

FrameEnvelopeRejectedException class

public sealed class FrameEnvelopeRejectedException : Exception

Thrown when an inbound frame fails envelope-HMAC verification. The metadata keys (frame.envelope.*) carry the rejection reason, the seal key id and the issue time, so log emitters can attach them to dead-letter records and traces without parsing the message.

FrameEnvelopeRejectedException(FrameEnvelopeRejectionReason, string, string, DateTimeOffset?) constructor

public FrameEnvelopeRejectedException(FrameEnvelopeRejectionReason reason, string message, string? keyId = null, DateTimeOffset? issuedAtUtc = null)

Initializes a new instance of the FrameEnvelopeRejectedException.

MetadataKeyIssuedAt constant

public const string MetadataKeyIssuedAt = "frame.envelope.issuedAt"

Audit-metadata key carrying the issued-at timestamp (ISO-8601 UTC, when present).

MetadataKeyKeyId constant

public const string MetadataKeyKeyId = "frame.envelope.keyId"

Audit-metadata key carrying the seal key id (when present).

MetadataKeyReason constant

public const string MetadataKeyReason = "frame.envelope.reason"

Audit-metadata key carrying the reason label.

IssuedAtUtc property

public DateTimeOffset? IssuedAtUtc { get; }

Issued-at timestamp from the seal, when one was attached.

KeyId property

public string? KeyId { get; }

Key id presented by the seal, when one was attached.

Reason property

public FrameEnvelopeRejectionReason Reason { get; }

Why the verifier rejected the frame.

FrameEnvelopeRejectionReason enum

public enum FrameEnvelopeRejectionReason

Why IFrameEnvelopeVerifierrejected a frame. Fields double as the reason label on the router_frame_envelope_verify_failed_total counter so SREs can alert on each failure mode separately.

ValueDescription
Missing = 0No FrameEnvelopeSealattached to the frame.
UnknownKeyId = 1Seal carries a key id the verifier does not recognise.
UnsupportedAlgorithm = 2Seal algorithm marker is not supported by this verifier.
Malformed = 3Seal MAC is not valid Base64Url or has the wrong length for the algorithm.
TimestampOutOfWindow = 4Issued-at timestamp is outside the configured replay window.
MacMismatch = 5MAC bytes did not authenticate the canonical frame bytes (tamper or wrong key).
UnsupportedCanonicalVersion = 6Canonical-form version on the wire is unknown to this verifier.

FrameEnvelopeSeal record

public sealed record FrameEnvelopeSeal

Carries the gateway-issued integrity stamp attached to every router frame when frame-layer envelope HMAC is enforced. The seal binds the canonical frame header bytes to the signing key held by the gateway so that any transport — TCP, UDP, TLS, Messaging, RabbitMq, InMemory — can detect tampering and replay before dispatching the frame.

Remarks

The seal holds a key identifier (so keys can rotate without a coordinated downtime), the issuance timestamp (used to enforce the configurable replay window), the algorithm marker and the MAC bytes. The algorithm is HMAC-SHA256, as for the gateway-issued identity envelope. The seal records the algorithm marker, so another algorithm needs no change of the wire format.

FrameEnvelopeSeal() constructor

public FrameEnvelopeSeal()

Creates an instance of FrameEnvelopeSeal.

AlgorithmHs256 constant

public const string AlgorithmHs256 = "HS256"

HMAC algorithm marker used when computing the seal. Matches the wire alias used by GatewayIdentityEnvelopeCodec.

Algorithm property

public string Algorithm { get; init; }

HMAC algorithm marker. Currently FrameEnvelopeSeal.AlgorithmHs256; widen only by adding new constants — do not repurpose existing ones, since older verifiers must continue to recognise the marker.

IssuedAtUtc property

public required DateTimeOffset IssuedAtUtc { get; init; }

UTC timestamp at which the gateway stamped the frame. Used by the verifier to enforce the replay window.

KeyId property

public required string KeyId { get; init; }

Identifier of the signing key used to compute the MAC. Must be stable across services so verifiers can route a frame to the correct key material when more than one key is loaded (rotation window).

Mac property

public required string Mac { get; init; }

Base64Url-encoded MAC bytes. The MAC is computed over the canonical frame header bytes produced by FrameCanonicalBytesusing the key identified by FrameEnvelopeSeal.KeyId.

FrameEnvelopeServiceCollectionExtensions class

public static class FrameEnvelopeServiceCollectionExtensions

Registers frame-envelope HMAC services when the operator supplies the FrameEnvelopeOptions.SectionNameconfiguration section.

AddConfiguredFrameEnvelopeProtection(IServiceCollection, IConfiguration) extension method

public static IServiceCollection AddConfiguredFrameEnvelopeProtection(this IServiceCollection services, IConfiguration configuration)

Binds and validates frame-envelope options, then registers the signer and verifier. Hosts without the configuration section retain the documented bootstrap posture; a present but invalid section fails registration instead of silently disabling integrity.

Parameters

Returns

The service collection for chaining.

HmacFrameEnvelopeSigner class

public sealed class HmacFrameEnvelopeSigner : IFrameEnvelopeSigner

Default IFrameEnvelopeSignerbacked by IHmacAlgorithm (HMAC-SHA256). Stamps a producer-issued envelope seal over canonical frame bytes.

Remarks

Every frame producer signs its outbound request, response, and control frames; every consumer uses HmacFrameEnvelopeVerifierto authenticate frames it receives. The HMAC primitive is taken from IHmacAlgorithm; the signer makes no direct BCL HMAC call.

HmacFrameEnvelopeSigner(IOptions<FrameEnvelopeOptions>, IHmacAlgorithm, TimeProvider) constructor

public HmacFrameEnvelopeSigner(IOptions<FrameEnvelopeOptions> options, IHmacAlgorithm? hmac = null, TimeProvider? timeProvider = null)

Initializes a new instance of the HmacFrameEnvelopeSignerclass.

Sign(Frame) method

public FrameEnvelopeSeal Sign(Frame frame)

Compute a seal for frame. Implementations are expected to read “now” via the TimeProvider wired into them, so determinism tests can substitute a fake clock.

HmacFrameEnvelopeVerifier class

public sealed class HmacFrameEnvelopeVerifier : IFrameEnvelopeVerifier

Default IFrameEnvelopeVerifierbacked by IHmacAlgorithm. Recomputes canonical frame bytes against the key id presented in the seal, enforces the configured replay window using TimeProvider, and rejects on any mismatch with a structured FrameEnvelopeRejectedException.

HmacFrameEnvelopeVerifier(IOptions<FrameEnvelopeOptions>, IHmacAlgorithm, TimeProvider) constructor

public HmacFrameEnvelopeVerifier(IOptions<FrameEnvelopeOptions> options, IHmacAlgorithm? hmac = null, TimeProvider? timeProvider = null)

Initializes a new instance of the HmacFrameEnvelopeVerifierclass.

TryVerify(Frame, FrameEnvelopeSeal, out FrameEnvelopeRejectionReason) method

public bool TryVerify(Frame frame, FrameEnvelopeSeal? seal, out FrameEnvelopeRejectionReason reason)

Try-style overload. Returns true on success, otherwise sets reason to the failure label and returns false. Useful where a transport wants to emit a counter increment without paying the cost of throwing.

Verify(Frame, FrameEnvelopeSeal) method

public void Verify(Frame frame, FrameEnvelopeSeal seal)

Verify the seal attached to frame. Throws FrameEnvelopeRejectedExceptionon failure with a structured reason; transports that rely on at-least-once delivery (Messaging, RabbitMq) catch and dead-letter on this exception.

Parameters

IFrameEnvelopeSigner interface

public interface IFrameEnvelopeSigner

Signs a router frame with the gateway-issued envelope HMAC.

Remarks

Every router frame leaving a host must carry a FrameEnvelopeSealstamped over canonical frame bytes. The signer computes the MAC through StellaOps.Cryptography.IHmacAlgorithm, so a host can substitute the MAC implementation.

Sign(Frame) method

FrameEnvelopeSeal Sign(Frame frame)

Compute a seal for frame. Implementations are expected to read “now” via the TimeProvider wired into them, so determinism tests can substitute a fake clock.

IFrameEnvelopeVerifier interface

public interface IFrameEnvelopeVerifier

Verifies that a router frame carries a valid gateway-issued envelope HMAC.

TryVerify(Frame, FrameEnvelopeSeal, out FrameEnvelopeRejectionReason) method

bool TryVerify(Frame frame, FrameEnvelopeSeal? seal, out FrameEnvelopeRejectionReason reason)

Try-style overload. Returns true on success, otherwise sets reason to the failure label and returns false. Useful where a transport wants to emit a counter increment without paying the cost of throwing.

Verify(Frame, FrameEnvelopeSeal) method

void Verify(Frame frame, FrameEnvelopeSeal seal)

Verify the seal attached to frame. Throws FrameEnvelopeRejectedExceptionon failure with a structured reason; transports that rely on at-least-once delivery (Messaging, RabbitMq) catch and dead-letter on this exception.

Parameters

PayloadTooLargeException class

public sealed class PayloadTooLargeException : Exception

A frame, a datagram or a request body is larger than its transport or the configured limit accepts. It is raised before anything is sent, so the connection stays usable; the gateway answers the caller 413 Payload Too Large.

PayloadTooLargeException(long, long) constructor

public PayloadTooLargeException(long actualSize, long maxSize)

Initializes a new instance of the PayloadTooLargeExceptionclass.

Parameters

ActualSize property

public long ActualSize { get; }

Gets the size, in bytes, that exceeded the limit.

MaxSize property

public long MaxSize { get; }

Gets the limit, in bytes.

RequestFrame record

public sealed record RequestFrame

Represents a REQUEST frame sent from gateway to microservice.

RequestFrame() constructor

public RequestFrame()

Creates an instance of RequestFrame.

CorrelationId property

public string? CorrelationId { get; init; }

Gets the correlation ID for distributed tracing.

Headers property

public IReadOnlyDictionary<string, string> Headers { get; init; }

Gets the request headers.

Method property

public required string Method { get; init; }

Gets the HTTP method (GET, POST, PUT, DELETE, etc.).

Path property

public required string Path { get; init; }

Gets the request path.

Payload property

public ReadOnlyMemory<byte> Payload { get; init; }

Gets the request payload (body).

RawTarget property

public string? RawTarget { get; init; }

Gets the request target exactly as the gateway received it on the ingress wire (path plus query string, percent-encoding intact), after the gateway translated the route prefix the same way it translated RequestFrame.Path. Null when the ingress exposed no raw target (a gateway built before this field existed, or a synthetic caller).

Remarks

RequestFrame.Pathis the once-decoded, re-escaped form ASP.NET hands the gateway, so a canonical %252F on the wire has already become %2F there. Endpoints that must decode a segment exactly once (product keys carrying canonical PURL escapes) read IHttpRequestFeature.RawTarget instead of the route value; the ASP.NET dispatcher populates that feature from this value and, when it is absent, from RequestFrame.Path.

RequestId property

public required string RequestId { get; init; }

Gets the unique request ID for this request.

SupportsStreaming property

public bool SupportsStreaming { get; init; }

Gets whether this request supports streaming response.

TimeoutSeconds property

public int TimeoutSeconds { get; init; }

Gets the timeout in seconds for this request.

ResponseFrame record

public sealed record ResponseFrame

Represents a RESPONSE frame sent from microservice to gateway.

ResponseFrame() constructor

public ResponseFrame()

Creates an instance of ResponseFrame.

HasMoreChunks property

public bool HasMoreChunks { get; init; }

Gets whether there are more streaming chunks to follow.

Headers property

public IReadOnlyDictionary<string, string> Headers { get; init; }

Gets the response headers.

Payload property

public ReadOnlyMemory<byte> Payload { get; init; }

Gets the response payload (body).

RequestId property

public required string RequestId { get; init; }

Gets the request ID this response is for.

StatusCode property

public int StatusCode { get; init; }

Gets the HTTP status code.

TransportErrorResponses class

public static class TransportErrorResponses

Response frames a transport client sends in place of a response it cannot send.

ResponseTooLargeType constant

public const string ResponseTooLargeType = "urn:stellaops:router:response-too-large"

The type of the problem a TransportErrorResponses.ResponseTooLarge(string, long, long)frame carries.

ResponseTooLarge(string, long, long) method

public static Frame ResponseTooLarge(string correlationId, long actualBytes, long maxBytes)

A 502 response frame for a response whose frame is larger than the transport carries (PayloadTooLargeExceptionon the write). The gateway passes it to the caller at once instead of waiting for the endpoint timeout.

Parameters

Returns

The response frame.

TransportFrameHeader class

public static class TransportFrameHeader

The frame header shared by the TCP, TLS and UDP transports: [1-byte frame type][1-byte correlation length N][N bytes UTF-8 correlation id]. The correlation id is carried exactly as the sender set it (the gateway issues ULIDs), so a response can be matched to its request. A zero length means no correlation id.

MaxCorrelationIdBytes constant

public const int MaxCorrelationIdBytes = 255

The largest correlation id, in UTF-8 bytes, that fits the one-byte length field.

MinimumSize constant

public const int MinimumSize = 2

The size of a header without a correlation id.

GetSize(string) method

public static int GetSize(string? correlationId)

Gets the header size for a correlation id.

Parameters

Returns

The number of header bytes.

Exceptions

TryRead(ReadOnlySpan<byte>, out FrameType, out string, out int, out string) method

public static bool TryRead(ReadOnlySpan<byte> source, out FrameType frameType, out string? correlationId, out int headerSize, out string error)

Reads the header.

Parameters

Returns

true when the header is well formed.

Write(Span<byte>, FrameType, string) method

public static int Write(Span<byte> destination, FrameType frameType, string? correlationId)

Writes the header.

Parameters

Returns

The number of bytes written.

Exceptions

StellaOps.Router.Common.Identity namespace

TypeKindDescription
GatewayIdentityEnveloperecordSigned gateway-issued identity envelope used for trusted user impersonation when requests are dispatched through the Router gateway.
GatewayIdentityEnvelopeCodecclassCodec for creating and verifying signed identity envelopes.
GatewayIdentityEnvelopeSignaturestructResult of envelope signing operation.

GatewayIdentityEnvelope record

public sealed record GatewayIdentityEnvelope

Signed gateway-issued identity envelope used for trusted user impersonation when requests are dispatched through the Router gateway.

GatewayIdentityEnvelope() constructor

public GatewayIdentityEnvelope()

Creates an instance of GatewayIdentityEnvelope.

Claims property

public Dictionary<string, string[]> Claims { get; init; }

Gateway-validated non-scope claims that downstream services need for resource-level authorization decisions.

CorrelationId property

public string CorrelationId { get; init; }

Correlation identifier for audit traceability.

ExpiresAtUtc property

public DateTimeOffset ExpiresAtUtc { get; init; }

Envelope expiry timestamp (UTC).

IssuedAtUtc property

public DateTimeOffset IssuedAtUtc { get; init; }

Envelope issuance timestamp (UTC).

Issuer property

public string Issuer { get; init; }

Gateway issuer identifier.

Project property

public string? Project { get; init; }

Project identifier, when available.

Roles property

public IReadOnlyList<string> Roles { get; init; }

Effective roles enforced by the gateway.

Scopes property

public IReadOnlyList<string> Scopes { get; init; }

Effective scopes enforced by the gateway.

SenderConfirmation property

public string? SenderConfirmation { get; init; }

Sender confirmation thumbprint (for example DPoP JKT) when available.

Subject property

public string Subject { get; init; }

Subject (authenticated actor).

Tenant property

public string? Tenant { get; init; }

Tenant identifier, when available.

Version property

public int Version { get; init; }

Envelope schema version.

GatewayIdentityEnvelopeCodec class

public static class GatewayIdentityEnvelopeCodec

Codec for creating and verifying signed identity envelopes.

Remarks

The gateway seals every request it dispatches with this envelope, and every downstream service verifies it.

The MAC is computed through the ICryptoHmac abstraction for the authentication purpose (HmacPurpose.Authentication), not for document signing. The gateway and the services resolve the same implementation, so both sides compute the same algorithm and verification needs no further configuration.

Callers that omit the ICryptoHmac argument (or pass a DI lookup that found none) get DefaultCryptoPrimitives.Hmac: HMAC-SHA256, through the dependency-free Sha2CryptoHmac unless the host deploys its own crypto provider.

AlgorithmHs256 constant

public const string AlgorithmHs256 = "HS256"

Algorithm marker used for generated signatures under the default world compliance profile. Retained for backwards compatibility with existing tests and downstream consumers; the GatewayIdentityEnvelopeSignature.Algorithmfield of new signatures is populated dynamically from ICryptoHmac.GetAlgorithmForPurpose(string).

Sign(GatewayIdentityEnvelope, string, ICryptoHmac) method

public static GatewayIdentityEnvelopeSignature Sign(GatewayIdentityEnvelope envelope, string signingKey, ICryptoHmac? hmac = null)

Creates a signed identity envelope. The HMAC algorithm is chosen by the active regional compliance profile via ICryptoHmac, for the purpose HmacPurpose.Authentication.

Parameters

TryVerify(string, string, string, ICryptoHmac, out GatewayIdentityEnvelope) method

public static bool TryVerify(string payload, string signature, string signingKey, ICryptoHmac? hmac, out GatewayIdentityEnvelope? envelope)

Tries to verify and decode a signed identity envelope using the supplied compliance-aware HMAC primitive.

TryVerify(string, string, string, out GatewayIdentityEnvelope) method

public static bool TryVerify(string payload, string signature, string signingKey, out GatewayIdentityEnvelope? envelope)

Tries to verify and decode a signed identity envelope. The HMAC algorithm matches the active regional compliance profile resolved through ICryptoHmac.

GatewayIdentityEnvelopeSignature struct

public readonly struct GatewayIdentityEnvelopeSignature : IEquatable<GatewayIdentityEnvelopeSignature>

Result of envelope signing operation.

Parameters

GatewayIdentityEnvelopeSignature(string, string, string) constructor

public GatewayIdentityEnvelopeSignature(string Payload, string Signature, string Algorithm)

Result of envelope signing operation.

Parameters

Algorithm property

public string Algorithm { get; init; }

The algorithm the signature was made with.

Payload property

public string Payload { get; init; }

The encoded envelope payload.

Signature property

public string Signature { get; init; }

The signature of the payload.

StellaOps.Router.Common.Models namespace

TypeKindDescription
CancelPayloadrecordPayload for the Cancel frame.
CancelReasonsclassStandard reasons for request cancellation.
ClaimRequirementrecordRepresents a claim requirement for endpoint authorization.
ConnectionStateclassRepresents the state of a connection between a microservice and the router.
EndpointAuthorizationSemanticsclassResolves effective authorization semantics for endpoint descriptors.
EndpointAuthorizationSourceenumSource of authorization metadata for an endpoint descriptor.
EndpointDescriptorrecordDescribes an endpoint’s identity and metadata.
EndpointSchemaInforecordSchema metadata for an endpoint, referencing schemas by ID.
EndpointsUpdatePayloadrecordPayload for the EndpointsUpdate frame sent by a microservice after the router requests a metadata replay.
FramerecordRepresents a protocol frame in the router transport layer.
HeartbeatPayloadrecordPayload for the Heartbeat frame sent periodically by microservices.
HelloPayloadrecordPayload for the Hello frame sent by microservices on connection.
InstanceDescriptorrecordDescribes a microservice instance’s identity.
PayloadLimitsclassConfiguration for payload and memory limits.
QueryParameterInforecordLightweight query parameter descriptor that can be serialized in the HELLO payload.
RegistrationResyncRequestPayloadrecordPayload for the ResyncRequest frame sent by the router when it needs a fresh endpoint metadata replay.
RouterTransportCapabilitiesclassCanonical capability identifiers advertised by router transport connections.
RoutingContextrecordNeutral routing context that does not depend on ASP.NET.
RoutingDecisionrecordRepresents the outcome of a routing decision.
SchemaDefinitionrecordA JSON Schema definition for request or response validation.
ServiceOpenApiInforecordOpenAPI metadata for a microservice.
StreamDataPayloadrecordPayload for streaming data frames (REQUEST_STREAM_DATA/RESPONSE_STREAM_DATA).
StreamingOptionsrecordConfiguration options for streaming operations.
TransportDefaultPortsclassThe default ports of the connection transports.

CancelPayload record

public sealed record CancelPayload

Payload for the Cancel frame.

CancelPayload() constructor

public CancelPayload()

Creates an instance of CancelPayload.

Reason property

public string? Reason { get; init; }

Gets the reason for cancellation.

CancelReasons class

public static class CancelReasons

Standard reasons for request cancellation.

ClientDisconnected constant

public const string ClientDisconnected = "ClientDisconnected"

The HTTP client disconnected before the request completed.

ConnectionClosed constant

public const string ConnectionClosed = "ConnectionClosed"

The transport connection was closed unexpectedly.

PayloadLimitExceeded constant

public const string PayloadLimitExceeded = "PayloadLimitExceeded"

The request or response payload exceeded configured limits.

Shutdown constant

public const string Shutdown = "Shutdown"

The gateway or microservice is shutting down.

Timeout constant

public const string Timeout = "Timeout"

The request exceeded its timeout.

ClaimRequirement record

public sealed record ClaimRequirement

Represents a claim requirement for endpoint authorization.

ClaimRequirement() constructor

public ClaimRequirement()

Creates an instance of ClaimRequirement.

AllowedValues property

public IReadOnlyList<string>? AllowedValues { get; init; }

When non-null and non-empty, the requirement is satisfied if the principal presents ANY one of these values for ClaimRequirement.Type. Used for any-of scope policies (e.g. orch:read OR script:read). Takes precedence over ClaimRequirement.Value.

Type property

public required string Type { get; init; }

Gets the claim type that must be present.

Value property

public string? Value { get; init; }

Gets the optional claim value that must match. Used for single-value AND-style requirements. Ignored when ClaimRequirement.AllowedValuesis set.

ConnectionState class

public sealed class ConnectionState

Represents the state of a connection between a microservice and the router.

ConnectionState() constructor

public ConnectionState()

Creates an instance of ConnectionState.

AveragePingMs property

public double AveragePingMs { get; set; }

Gets or sets the average ping time in milliseconds.

ConnectedAtUtc property

public DateTime ConnectedAtUtc { get; init; }

Gets the UTC timestamp when this connection was established.

ConnectionId property

public required string ConnectionId { get; init; }

Gets the unique identifier for this connection.

Endpoints property

public Dictionary<(string Method, string Path), EndpointDescriptor> Endpoints { get; }

Gets the endpoints served by this connection.

Instance property

public required InstanceDescriptor Instance { get; init; }

Gets the instance descriptor for the connected microservice.

LastHeartbeatUtc property

public DateTime LastHeartbeatUtc { get; set; }

Gets or sets the UTC timestamp of the last heartbeat.

OpenApiInfo property

public ServiceOpenApiInfo? OpenApiInfo { get; init; }

Gets the OpenAPI metadata for this connection’s service.

Schemas property

public IReadOnlyDictionary<string, SchemaDefinition> Schemas { get; init; }

Gets the schema definitions for this connection’s service. Keys are schema IDs referenced by EndpointDescriptor.SchemaInfo.

Status property

public InstanceHealthStatus Status { get; set; }

Gets or sets the health status of this connection.

TransportCapabilities property

public IReadOnlyList<string> TransportCapabilities { get; init; }

Gets the transport capabilities advertised by this exact connection.

TransportType property

public required TransportType TransportType { get; init; }

Gets the transport type used for this connection.

EndpointAuthorizationSemantics class

public static class EndpointAuthorizationSemantics

Resolves effective authorization semantics for endpoint descriptors.

ResolveRequiresAuthentication(EndpointDescriptor) method

public static bool ResolveRequiresAuthentication(EndpointDescriptor endpoint)

Resolves whether an endpoint should require an authenticated principal.

ResolveRequiresAuthentication(bool, bool, EndpointAuthorizationSource, IReadOnlyList<ClaimRequirement>, IReadOnlyList<string>, IReadOnlyList<string>) method

public static bool ResolveRequiresAuthentication(bool allowAnonymous, bool requiresAuthentication, EndpointAuthorizationSource source, IReadOnlyList<ClaimRequirement>? requiringClaims = null, IReadOnlyList<string>? authorizationPolicies = null, IReadOnlyList<string>? roles = null)

Resolves whether an endpoint should require an authenticated principal.

EndpointAuthorizationSource enum

public enum EndpointAuthorizationSource

Source of authorization metadata for an endpoint descriptor.

ValueDescription
None = 0No authorization metadata found.
AspNetMetadata = 1Authorization derived from ASP.NET metadata.
YamlOverride = 2Authorization defined by YAML endpoint overrides.
Hybrid = 3Authorization merged from ASP.NET metadata and YAML overrides.
AuthorityOverride = 4Authorization overridden by Authority.

EndpointDescriptor record

public sealed record EndpointDescriptor

Describes an endpoint’s identity and metadata.

EndpointDescriptor() constructor

public EndpointDescriptor()

Creates an instance of EndpointDescriptor.

AnyMethod constant

public const string AnyMethod = "*"

The EndpointDescriptor.Methodof an endpoint that accepts any HTTP method: an ASP.NET Core endpoint mapped without an HTTP method filter, or a wildcard. The gateway routes every request method to it, after an endpoint of the same path that names the method.

AllowAnonymous property

public bool AllowAnonymous { get; init; }

Gets a value indicating whether this endpoint explicitly allows anonymous access.

AuthorizationFullyMapped property

public bool AuthorizationFullyMapped { get; init; }

Gets a value indicating whether the publishing service resolved and translated EVERY authorization rule it declared on this endpoint.

Remarks

The gateway is the only enforcement point on the router-dispatched path (the ASP.NET Core bridge dispatches a request without the host’s authorization middleware), and it enforces exactly EndpointDescriptor.RequiringClaims. When that list is empty, the gateway cannot tell “this endpoint requires only authentication” from “this endpoint declared a rule the service could not translate”. This flag makes that distinction, and it is the service’s own assurance: false is the default, so the gateway refuses a request to an endpoint that declares a named authorization policy unless the service reports its authorization as fully mapped.

AuthorizationPolicies property

public IReadOnlyList<string> AuthorizationPolicies { get; init; }

Gets named authorization policies discovered for this endpoint.

AuthorizationSource property

public EndpointAuthorizationSource AuthorizationSource { get; init; }

Gets the source of the authorization metadata.

DefaultTimeout property

public TimeSpan DefaultTimeout { get; init; }

Gets the default timeout for this endpoint.

HandlerType property

public Type? HandlerType { get; init; }

Gets the handler type that processes requests for this endpoint. This is used by the Microservice SDK for handler resolution. It is a process-local reference: it is not serialized (System.Text.Json does not serialize Type), so a HELLO or an endpoints update never carries it.

Method property

public required string Method { get; init; }

Gets the HTTP method token as the endpoint configures it (GET, POST, PUT, PATCH, DELETE or another token), or EndpointDescriptor.AnyMethod.

Path property

public required string Path { get; init; }

Gets the path template (e.g., “/billing/invoices/{id}”), with its letter case, its slashes and its catch-all, optional and default-value markers as configured.

RequiresAuthentication property

public bool RequiresAuthentication { get; init; }

Gets a value indicating whether this endpoint requires an authenticated principal.

RequiringClaims property

public IReadOnlyList<ClaimRequirement> RequiringClaims { get; init; }

Gets the claim requirements for authorization.

Roles property

public IReadOnlyList<string> Roles { get; init; }

Gets role names required by endpoint metadata.

SchemaInfo property

public EndpointSchemaInfo? SchemaInfo { get; init; }

Gets the schema information for this endpoint. Contains references to request/response schemas and OpenAPI documentation.

ServiceName property

public required string ServiceName { get; init; }

Gets the name of the service that owns this endpoint.

SupportsStreaming property

public bool SupportsStreaming { get; init; }

Gets a value indicating whether this endpoint supports streaming.

UnmappedAuthorizationRequirements property

public IReadOnlyList<string> UnmappedAuthorizationRequirements { get; init; }

Gets the requirement type names the publishing service DECLARED and could not translate into a claim requirement — an AssertionRequirement from RequireAssertion(...), an unresolvable named policy, a custom requirement exposing no scope property.

Remarks

Diagnostic only: the gateway’s decision is driven by EndpointDescriptor.AuthorizationFullyMapped, so an old descriptor that carries neither field still fails closed. This list is what names the offending requirement in the refusal log.

Version property

public required string Version { get; init; }

Gets the semantic version of the service.

EndpointSchemaInfo record

public sealed record EndpointSchemaInfo

Schema metadata for an endpoint, referencing schemas by ID.

EndpointSchemaInfo() constructor

public EndpointSchemaInfo()

Creates an instance of EndpointSchemaInfo.

Deprecated property

public bool Deprecated { get; init; }

Gets a value indicating whether this endpoint is deprecated.

Description property

public string? Description { get; init; }

Gets the OpenAPI operation description.

QueryParameters property

public IReadOnlyList<QueryParameterInfo> QueryParameters { get; init; }

Gets the query parameter descriptors for this endpoint. Each entry contains the parameter name, JSON Schema type, and whether it is required. Propagated via HELLO and consumed by the gateway OpenAPI generator.

RequestSchemaId property

public string? RequestSchemaId { get; init; }

Gets the schema ID for request validation. References a key in HelloPayload.Schemas.

ResponseSchemaId property

public string? ResponseSchemaId { get; init; }

Gets the schema ID for response validation. References a key in HelloPayload.Schemas.

ResponseStatusCode property

public int? ResponseStatusCode { get; init; }

Gets the preferred success HTTP status code for the response schema.

Summary property

public string? Summary { get; init; }

Gets the OpenAPI operation summary.

Tags property

public IReadOnlyList<string> Tags { get; init; }

Gets the OpenAPI tags for this endpoint.

EndpointsUpdatePayload record

public sealed record EndpointsUpdatePayload

Payload for the EndpointsUpdate frame sent by a microservice after the router requests a metadata replay.

EndpointsUpdatePayload() constructor

public EndpointsUpdatePayload()

Creates an instance of EndpointsUpdatePayload.

Endpoints property

public required IReadOnlyList<EndpointDescriptor> Endpoints { get; init; }

Gets the endpoints registered by this instance.

OpenApiInfo property

public ServiceOpenApiInfo? OpenApiInfo { get; init; }

Gets the OpenAPI metadata for this service.

Schemas property

public IReadOnlyDictionary<string, SchemaDefinition> Schemas { get; init; }

Gets the schema definitions for request/response validation. Keys are schema IDs referenced by EndpointDescriptor.SchemaInfo.

Frame record

public sealed record Frame

Represents a protocol frame in the router transport layer.

Frame() constructor

public Frame()

Creates an instance of Frame.

CorrelationId property

public string? CorrelationId { get; init; }

Gets the correlation ID for request/response matching.

EnvelopeSeal property

public FrameEnvelopeSeal? EnvelopeSeal { get; init; }

Gets the gateway-issued envelope HMAC seal attached to this frame.

Remarks

Every frame leaving the gateway must carry a seal so that any transport — TCP, UDP, TLS, Messaging, RabbitMq, InMemory — can verify integrity at the application layer. Verifiers reject frames where this is null with rejection reason FrameEnvelopeRejectionReason.Missing.

Payload property

public ReadOnlyMemory<byte> Payload { get; init; }

Gets the raw payload bytes.

Type property

public required FrameType Type { get; init; }

Gets the type of this frame.

HeartbeatPayload record

public sealed record HeartbeatPayload

Payload for the Heartbeat frame sent periodically by microservices.

HeartbeatPayload() constructor

public HeartbeatPayload()

Creates an instance of HeartbeatPayload.

ErrorRate property

public double ErrorRate { get; init; }

Gets the error rate (0.0 to 1.0).

InFlightRequestCount property

public int InFlightRequestCount { get; init; }

Gets the current in-flight request count.

Instance property

public InstanceDescriptor? Instance { get; init; }

Gets the instance descriptor.

InstanceId property

public required string InstanceId { get; init; }

Gets the instance ID.

Status property

public required InstanceHealthStatus Status { get; init; }

Gets the health status.

TimestampUtc property

public DateTime TimestampUtc { get; init; }

Gets the timestamp when this heartbeat was created.

TransportCapabilities property

public IReadOnlyList<string> TransportCapabilities { get; init; }

Gets transport-specific capabilities supported by this connection. Heartbeats repeat capabilities so gateway state rebuilt after a restart does not lose rolling-upgrade delivery semantics.

HelloPayload record

public sealed record HelloPayload

Payload for the Hello frame sent by microservices on connection.

HelloPayload() constructor

public HelloPayload()

Creates an instance of HelloPayload.

Endpoints property

public required IReadOnlyList<EndpointDescriptor> Endpoints { get; init; }

Gets the endpoints registered by this instance.

Instance property

public required InstanceDescriptor Instance { get; init; }

Gets the instance descriptor.

OpenApiInfo property

public ServiceOpenApiInfo? OpenApiInfo { get; init; }

Gets the OpenAPI metadata for this service.

Schemas property

public IReadOnlyDictionary<string, SchemaDefinition> Schemas { get; init; }

Gets the schema definitions for request/response validation. Keys are schema IDs referenced by EndpointDescriptor.SchemaInfo.

TransportCapabilities property

public IReadOnlyList<string> TransportCapabilities { get; init; }

Gets transport-specific capabilities supported by this connection. Unknown values are ignored so mixed-version deployments remain compatible.

InstanceDescriptor record

public sealed record InstanceDescriptor

Describes a microservice instance’s identity.

InstanceDescriptor() constructor

public InstanceDescriptor()

Creates an instance of InstanceDescriptor.

InstanceId property

public required string InstanceId { get; init; }

Gets the unique identifier for this instance.

Region property

public required string Region { get; init; }

Gets the region where this instance is deployed.

ServiceName property

public required string ServiceName { get; init; }

Gets the name of the service.

Version property

public required string Version { get; init; }

Gets the semantic version of the service.

Weight property

public int Weight { get; init; }

Gets the routing weight used for intra-tier weighted canary selection.

PayloadLimits class

public sealed class PayloadLimits

Configuration for payload and memory limits.

PayloadLimits() constructor

public PayloadLimits()

Creates an instance of PayloadLimits.

Default field

public static readonly PayloadLimits Default

Default payload limits.

MaxAggregateInflightBytes property

public long MaxAggregateInflightBytes { get; set; }

Gets or sets the maximum aggregate in-flight bytes across all requests. Default: 1 GB.

MaxRequestBytesPerCall property

public long MaxRequestBytesPerCall { get; set; }

Gets or sets the maximum request bytes per call. Default: 10 MB.

MaxRequestBytesPerConnection property

public long MaxRequestBytesPerConnection { get; set; }

Gets or sets the maximum request bytes per connection. Default: 100 MB.

QueryParameterInfo record

public sealed record QueryParameterInfo

Lightweight query parameter descriptor that can be serialized in the HELLO payload.

QueryParameterInfo() constructor

public QueryParameterInfo()

Creates an instance of QueryParameterInfo.

Description property

public string? Description { get; init; }

Optional description for OpenAPI documentation.

Name property

public required string Name { get; init; }

Parameter name as it appears in the query string.

Required property

public bool Required { get; init; }

Whether the parameter is required.

Type property

public string Type { get; init; }

JSON Schema type (string, integer, boolean, array, etc.).

RegistrationResyncRequestPayload record

public sealed record RegistrationResyncRequestPayload

Payload for the ResyncRequest frame sent by the router when it needs a fresh endpoint metadata replay.

RegistrationResyncRequestPayload() constructor

public RegistrationResyncRequestPayload()

Creates an instance of RegistrationResyncRequestPayload.

Reason property

public string Reason { get; init; }

Gets the reason for the replay request.

RouterTransportCapabilities class

public static class RouterTransportCapabilities

Canonical capability identifiers advertised by router transport connections.

MessagingCancelControlV1 constant

public const string MessagingCancelControlV1 = "messaging.cancel-control.v1"

The messaging client consumes authenticated CANCEL frames from its connection-specific control queue independently of the request queue.

RoutingContext record

public sealed record RoutingContext

Neutral routing context that does not depend on ASP.NET. Gateway will adapt from HttpContext to this neutral model.

RoutingContext() constructor

public RoutingContext()

Creates an instance of RoutingContext.

AvailableConnections property

public IReadOnlyList<ConnectionState> AvailableConnections { get; init; }

Gets the available connections for routing.

CancellationToken property

public CancellationToken CancellationToken { get; init; }

Gets the cancellation token for the request.

Endpoint property

public EndpointDescriptor? Endpoint { get; init; }

Gets the resolved endpoint descriptor.

GatewayRegion property

public required string GatewayRegion { get; init; }

Gets the gateway’s region for routing decisions.

Headers property

public IReadOnlyDictionary<string, string> Headers { get; init; }

Gets the request headers.

Method property

public required string Method { get; init; }

Gets the HTTP method (GET, POST, PUT, PATCH, DELETE).

Path property

public required string Path { get; init; }

Gets the request path.

RequestedVersion property

public string? RequestedVersion { get; init; }

Gets the requested version, if specified.

RouteDefaultTimeout property

public TimeSpan? RouteDefaultTimeout { get; init; }

Gets the gateway route default timeout selected for this request path.

RoutingDecision record

public sealed record RoutingDecision

Represents the outcome of a routing decision.

RoutingDecision() constructor

public RoutingDecision()

Creates an instance of RoutingDecision.

Connection property

public required ConnectionState Connection { get; init; }

Gets the selected connection.

EffectiveTimeout property

public required TimeSpan EffectiveTimeout { get; init; }

Gets the effective timeout for the request: the gateway answers the caller with 504 when it elapses.

Remarks

The request frame carries it to the microservice in whole seconds, rounded up and at least one second; the Messaging transport’s service side stops the request at that rounded-up timeout.

Endpoint property

public required EndpointDescriptor Endpoint { get; init; }

Gets the selected endpoint.

TransportType property

public required TransportType TransportType { get; init; }

Gets the transport type to use.

SchemaDefinition record

public sealed record SchemaDefinition

A JSON Schema definition for request or response validation.

SchemaDefinition() constructor

public SchemaDefinition()

Creates an instance of SchemaDefinition.

ETag property

public string? ETag { get; init; }

Gets the ETag for cache validation (SHA256 truncated).

SchemaId property

public required string SchemaId { get; init; }

Gets the unique schema identifier (e.g., “CreateInvoiceRequest”).

SchemaJson property

public required string SchemaJson { get; init; }

Gets the JSON Schema document (draft 2020-12 compatible).

ServiceOpenApiInfo record

public sealed record ServiceOpenApiInfo

OpenAPI metadata for a microservice.

ServiceOpenApiInfo() constructor

public ServiceOpenApiInfo()

Creates an instance of ServiceOpenApiInfo.

Contact property

public string? Contact { get; init; }

Gets the contact information for the service.

Description property

public string? Description { get; init; }

Gets the service description for OpenAPI info.

License property

public string? License { get; init; }

Gets the license name for the service.

Title property

public string? Title { get; init; }

Gets the service title for OpenAPI info.

StreamDataPayload record

public sealed record StreamDataPayload

Payload for streaming data frames (REQUEST_STREAM_DATA/RESPONSE_STREAM_DATA).

StreamDataPayload() constructor

public StreamDataPayload()

Creates an instance of StreamDataPayload.

CorrelationId property

public required Guid CorrelationId { get; init; }

Gets the correlation ID linking stream data to the original request.

Data property

public byte[] Data { get; init; }

Gets the stream data chunk.

EndOfStream property

public bool EndOfStream { get; init; }

Gets a value indicating whether this is the final chunk.

SequenceNumber property

public int SequenceNumber { get; init; }

Gets the sequence number for ordering.

StreamingOptions record

public sealed record StreamingOptions

Configuration options for streaming operations.

StreamingOptions() constructor

public StreamingOptions()

Creates an instance of StreamingOptions.

Default field

public static readonly StreamingOptions Default

Gets the default streaming options.

ChannelCapacity property

public int ChannelCapacity { get; init; }

Gets the channel capacity for buffered stream data. Default: 16 chunks.

ChunkSize property

public int ChunkSize { get; init; }

Gets the size of each chunk when streaming data. Default: 64 KB.

MaxConcurrentStreams property

public int MaxConcurrentStreams { get; init; }

Gets the maximum number of concurrent streams per connection. Default: 100.

StreamIdleTimeout property

public TimeSpan StreamIdleTimeout { get; init; }

Gets the timeout for idle streams (no data flowing). Default: 5 minutes.

TransportDefaultPorts class

public static class TransportDefaultPorts

The default ports of the connection transports. The gateway’s listener options and the transports’ own options (which the transport plugins bind from the same configuration section) take their defaults from here, so a listener configured without a port uses the port the gateway’s options describe.

Tcp constant

public const int Tcp = 9100

The TCP transport’s default port.

Tls constant

public const int Tls = 9443

The TLS transport’s default port.

Udp constant

public const int Udp = 5102

The UDP transport’s default port.

StellaOps.Router.Common.Plugins namespace

TypeKindDescription
IRouterTransportPlugininterfacePlugin contract for router transport implementations.
RouterTransportConfigurationBinderclassBinding helpers for transport option values the configuration binder cannot convert.
RouterTransportModeenumTransport mode flags indicating whether to register server, client, or both capabilities.
RouterTransportPluginLoaderclassLoads and discovers router transport plugins from assemblies the host passes in (RouterTransportPluginLoader.LoadFromAssembly(Assembly)).
RouterTransportRegistrationContextclassContext provided to transport plugins during registration.

IRouterTransportPlugin interface

public interface IRouterTransportPlugin

Plugin contract for router transport implementations. A plugin provides one side of a transport (IRouterTransportPlugin.Mode): the client side that a microservice uses to connect, the server side that a gateway listens with, or both for an in-process transport. A network transport ships its client side in StellaOps.Router.Transport.<Name> and its server side in StellaOps.Router.Transport.<Name>.Server; both plugins carry the same IRouterTransportPlugin.TransportName, and RouterTransportPluginLoaderkeys plugins by name and mode.

DisplayName property

string DisplayName { get; }

Gets the human-readable display name for this transport.

Mode property

RouterTransportMode Mode { get; }

Gets the side of the transport this plugin registers: RouterTransportMode.Client, RouterTransportMode.Server, or RouterTransportMode.Both. IRouterTransportPlugin.Register(RouterTransportRegistrationContext)refuses a context that asks for a side outside this value (RouterTransportRegistrationContext.EnsureSupportedBy(IRouterTransportPlugin)).

TransportName property

string TransportName { get; }

Gets the transport name (e.g., “tcp”, “tls”, “udp”, “rabbitmq”, “inmemory”, “messaging”), shared by the client and the server plugin of one transport.

Register(RouterTransportRegistrationContext) method

void Register(RouterTransportRegistrationContext context)

Registers transport services into the DI container for the side the context asks for.

Parameters

Exceptions

RouterTransportConfigurationBinder class

public static class RouterTransportConfigurationBinder

Binding helpers for transport option values the configuration binder cannot convert.

BindIPAddress(IConfigurationSection, string, Action<IPAddress>) method

public static void BindIPAddress(IConfigurationSection section, string key, Action<IPAddress> apply)

Reads an IP address setting. The configuration binder has no converter from a string to IPAddress and leaves the default in place without an error, so a configured BindAddress such as 127.0.0.1 was ignored and the listener bound every interface. An absent or empty value keeps the default; a value that is not an IP address fails closed.

Parameters

Exceptions

RouterTransportMode enum

public enum RouterTransportMode

Transport mode flags indicating whether to register server, client, or both capabilities.

ValueDescription
None = 0No transport registration.
Server = 1Register server-side transport (listening for connections).
Client = 2Register client-side transport (connecting to remote services).
Both = 3Register both server and client transport capabilities.

RouterTransportPluginLoader class

public sealed class RouterTransportPluginLoader

Loads and discovers router transport plugins from assemblies the host passes in (RouterTransportPluginLoader.LoadFromAssembly(Assembly)).

Remarks

AppDomain-resident transports loaded by the build system live inside the gateway image, which is signed at build time (Authenticode on Windows, signed RPM/DEB on Linux), and so do not need a directory-level trust pipeline.

This library loads nothing from disk. Stella Ops hosts load a transport directory with a signed transports.signed.json manifest through RouterTransportSignedManifestLoader.LoadFromSignedManifestDirectoryAsync in StellaOps.Router.Plugins, which verifies the directory and then passes each admitted assembly to RouterTransportPluginLoader.LoadFromAssembly(Assembly).

RouterTransportPluginLoader() constructor

public RouterTransportPluginLoader()

Creates an instance of RouterTransportPluginLoader.

RouterTransportPluginLoader(ILogger<RouterTransportPluginLoader>) constructor

public RouterTransportPluginLoader(ILogger<RouterTransportPluginLoader>? logger = null)

Creates a loader.

Parameters

Plugins property

public IReadOnlyList<IRouterTransportPlugin> Plugins { get; }

Gets all loaded transport plugins.

DescribeLoadOutcome() method

public string DescribeLoadOutcome()

Describes what this loader holds, for the startup error a host raises when no plugin provides a transport: the loaded plugins with their sides, and each assembly whose types failed to load with its distinct load errors (for example a plugin built against an older IRouterTransportPlugin: “Method ‘get_Mode’ … does not have an implementation”). Assemblies are named by file name; rooted paths inside the runtime’s messages (quoted, or as a whole word) are reduced to file names.

Returns

One sentence for plugins and one for load failures.

GetPlugin(string, RouterTransportMode) method

public IRouterTransportPlugin? GetPlugin(string transportName, RouterTransportMode mode)

Gets the loaded plugin that provides mode for a transport name (case-insensitive): the client plugin for RouterTransportMode.Client, the server plugin for RouterTransportMode.Server. RouterTransportMode.Bothfinds only a plugin that provides both sides (an in-process transport).

Parameters

Returns

The plugin, or null when no loaded plugin provides that side.

LoadFromAssembly(Assembly) method

public void LoadFromAssembly(Assembly assembly)

Loads transport plugins from the specified assembly. Used for AppDomain-resident transports that ship inside the gateway image (the gateway image is the trust boundary for these).

Parameters

RecordLoadFailure(string, Exception) method

public void RecordLoadFailure(string assemblyFile, Exception exception)

Records an assembly the host could not hand to RouterTransportPluginLoader.LoadFromAssembly(Assembly), for example a signed transport file whose Assembly.LoadFrom failed. RouterTransportPluginLoader.DescribeLoadOutcome()reports it with the file name only.

Parameters

RouterTransportRegistrationContext class

public sealed class RouterTransportRegistrationContext

Context provided to transport plugins during registration.

RouterTransportRegistrationContext(IServiceCollection, IConfiguration, RouterTransportMode) constructor

public RouterTransportRegistrationContext(IServiceCollection services, IConfiguration configuration, RouterTransportMode mode)

Creates a new registration context.

Parameters

Configuration property

public IConfiguration Configuration { get; }

Gets the configuration root.

ConfigurationSection property

public string? ConfigurationSection { get; init; }

Gets or sets the configuration section path for this transport (e.g., “Router:Transports:Tcp”).

Mode property

public RouterTransportMode Mode { get; }

Gets the transport mode (server, client, or both).

Services property

public IServiceCollection Services { get; }

Gets the service collection for registering services.

EnsureSupportedBy(IRouterTransportPlugin) method

public void EnsureSupportedBy(IRouterTransportPlugin plugin)

Throws when RouterTransportRegistrationContext.Modeasks for a side of the transport that plugin does not provide. A network transport’s client plugin registers the client side only; its server side is a separate plugin in StellaOps.Router.Transport.<Name>.Server.

Parameters

Exceptions