StellaOps.Router.Transport.Messaging

Router Messaging transport, client side: connects a microservice to a gateway through the request and response queues of a Messaging backend.

PackageStellaOps.Router.Transport.Messaging
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.Transport.Messaging3
StellaOps.Router.Transport.Messaging.Extensions1
StellaOps.Router.Transport.Messaging.Options1
StellaOps.Router.Transport.Messaging.Protocol4

StellaOps.Router.Transport.Messaging namespace

TypeKindDescription
MessagingTransportClientclassTransport client that communicates with the gateway via StellaOps.Messaging.
MessagingTransportPluginclassPlugin for the client side of the Messaging transport, which a microservice connects with.
MessagingTransportServiceCollectionExtensionsclassExtension methods for registering the client side of the messaging transport and the options both sides read.

MessagingTransportClient class

public sealed class MessagingTransportClient : ITransportClient, IMicroserviceTransport, IDisposable

Transport client that communicates with the gateway via StellaOps.Messaging. Implements both ITransportClient (for sending to microservices) and IMicroserviceTransport (for microservices connecting to gateway).

MessagingTransportClient(IMessageQueueFactory, IOptions<MessagingTransportOptions>, ILogger<MessagingTransportClient>, IFrameEnvelopeSigner, IFrameEnvelopeVerifier, TimeProvider) constructor

public MessagingTransportClient(IMessageQueueFactory queueFactory, IOptions<MessagingTransportOptions> options, ILogger<MessagingTransportClient> logger, IFrameEnvelopeSigner? envelopeSigner = null, IFrameEnvelopeVerifier? envelopeVerifier = null, TimeProvider? timeProvider = null)

Initializes a new instance of the MessagingTransportClientclass.

OnCancelReceived event

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

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

OnRequestReceived event

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

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

OnResyncRequested event

public event Func<RegistrationResyncRequestPayload, CancellationToken, Task>? OnResyncRequested

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

TransportDied event

public event Action? TransportDied

Raised when the messaging transport connection is permanently lost. The microservice’s router connection manager listens for this event and reconnects.

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

public 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

public 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

public Task DisconnectAsync()

Disconnects from the router.

Dispose() method

public void Dispose()

See IDisposable.Dispose().

SendCancelAsync(ConnectionState, Guid, string) method

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

Sends a cancellation request.

Parameters

Remarks

The signed per-connection control lane is the only cancellation path. A target that does not advertise RouterTransportCapabilities.MessagingCancelControlV1receives no cancellation; there is no fallback path.

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

public 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

public 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

public Task SendHeartbeatAsync(HeartbeatPayload heartbeat, CancellationToken cancellationToken)

Sends a heartbeat to the router.

Parameters

SendRequestAsync(ConnectionState, Frame, TimeSpan, CancellationToken) method

public 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

public 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

Remarks

Sends the request body in one request frame (TransportStreamingDispatch.SendBufferedAsync(ITransportClient, ConnectionState, Frame, Stream, Func<ResponseFrame, Stream, Task>, PayloadLimits, CancellationToken)).

MessagingTransportPlugin class

public sealed class MessagingTransportPlugin : IRouterTransportPlugin

Plugin for the client side of the Messaging transport, which a microservice connects with. The server side is MessagingTransportServerPlugin in StellaOps.Router.Transport.Messaging.Server; both carry the transport name messaging.

MessagingTransportPlugin() constructor

public MessagingTransportPlugin()

Creates an instance of MessagingTransportPlugin.

DisplayName property

public string DisplayName { get; }

Gets the human-readable display name for this transport.

Mode property

public 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

public 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

public void Register(RouterTransportRegistrationContext context)

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

Parameters

Exceptions

RegisterShared(RouterTransportRegistrationContext) method

public static void RegisterShared(RouterTransportRegistrationContext context)

The registration both sides share: frame envelope protection, the Messaging backend named at <section>:transport and the validated MessagingTransportOptionsbinding of the context’s section.

Parameters

MessagingTransportServiceCollectionExtensions class

public static class MessagingTransportServiceCollectionExtensions

Extension methods for registering the client side of the messaging transport and the options both sides read. The server side is AddMessagingTransportServer in StellaOps.Router.Transport.Messaging.Server.

AddMessagingTransportClient(IServiceCollection, Action<MessagingTransportOptions>) extension method

public static IServiceCollection AddMessagingTransportClient(this IServiceCollection services, Action<MessagingTransportOptions>? configure = null)

Adds the messaging transport client only (for Microservice SDK). Requires StellaOps.Messaging services to be registered.

Parameters

Returns

The service collection for chaining.

AddMessagingTransportOptions(IServiceCollection, Action<MessagingTransportOptions>) extension method

public static IServiceCollection AddMessagingTransportOptions(this IServiceCollection services, Action<MessagingTransportOptions>? configure = null)

Registers the validated MessagingTransportOptionsboth sides of the transport read, validated when the host starts.

Parameters

Returns

The service collection for chaining.

StellaOps.Router.Transport.Messaging.Extensions namespace

TypeKindDescription
QueueWaitExtensionsclassExtension to efficiently await new messages on a queue.

QueueWaitExtensions class

public static class QueueWaitExtensions

Extension to efficiently await new messages on a queue. Uses INotifiableQueue Pub/Sub wakeup when available, falls back to a delay for non-notifiable queue implementations.

Remarks

For Valkey queues the actual timeout is controlled by ValkeyTransportOptions.QueueWaitTimeoutSeconds (default 5s, 0 = pure event-driven). The timeout parameter passed here is used only as a hint for the queue implementation. Both sides of the Messaging transport wait with it.

WaitForMessagesAsync<TMessage>(IMessageQueue<TMessage>, CancellationToken) extension method

public static Task WaitForMessagesAsync<TMessage>(this IMessageQueue<TMessage> queue, CancellationToken cancellationToken) where TMessage : class

Waits for new messages to become available on the queue, with no timeout hint.

WaitForMessagesAsync<TMessage>(IMessageQueue<TMessage>, TimeSpan, CancellationToken) extension method

public static Task WaitForMessagesAsync<TMessage>(this IMessageQueue<TMessage> queue, TimeSpan heartbeatInterval, CancellationToken cancellationToken) where TMessage : class

Waits for new messages to become available on the queue.

StellaOps.Router.Transport.Messaging.Options namespace

TypeKindDescription
MessagingTransportOptionsclassConfiguration options for the messaging-based router transport.

MessagingTransportOptions class

public class MessagingTransportOptions

Configuration options for the messaging-based router transport.

MessagingTransportOptions() constructor

public MessagingTransportOptions()

Creates an instance of MessagingTransportOptions.

BatchSize property

public int BatchSize { get; set; }

Gets or sets the batch size for leasing messages.

CancelControlApproximateMaxLength property

public int CancelControlApproximateMaxLength { get; set; }

Gets or sets the approximate maximum number of entries retained in one connection-specific cancellation control stream.

CancelControlBatchSize property

public int CancelControlBatchSize { get; set; }

Gets or sets the batch size for leasing dedicated cancellation controls. This is independent from normal request and response leasing so a burst of abandoned requests can be cancelled in one control-loop wake.

CancelControlQueueTemplate property

public string CancelControlQueueTemplate { get; set; }

Gets or sets the queue template for the connection-specific cancellation control lane. Both {service} and {connection} placeholders are required.

CancelTombstoneTtl property

public TimeSpan CancelTombstoneTtl { get; set; }

Gets or sets how long an exact-correlation cancellation remains active when it overtakes the corresponding request on the independent lane. Must be at least MessagingTransportOptions.RequestTimeout.

ConsumerGroup property

public string ConsumerGroup { get; set; }

Gets or sets the consumer group name for request processing.

DeadLetterSuffix property

public string DeadLetterSuffix { get; set; }

Gets or sets the dead letter queue suffix.

GatewayControlQueueServiceName property

public string GatewayControlQueueServiceName { get; set; }

Gets or sets the logical queue segment reserved for gateway control traffic (HELLO, HEARTBEAT, and microservice-to-gateway responses).

Remarks

This must not overlap with any real microservice name. The default avoids collision with the “gateway” service.

HeartbeatInterval property

public TimeSpan HeartbeatInterval { get; set; }

Gets or sets the heartbeat interval. Default: 45 seconds.

LeaseDuration property

public TimeSpan LeaseDuration { get; set; }

Gets or sets the lease duration for message processing.

MaxConcurrentRequests property

public int MaxConcurrentRequests { get; set; }

Gets or sets the maximum number of messages processed concurrently per consumer loop iteration. Prevents head-of-line blocking where one slow handler blocks all other messages in the batch. Default: 10 (matches BatchSize).

MaxPendingCancellations property

public int MaxPendingCancellations { get; set; }

Gets or sets the maximum number of expiring pre-cancel correlations held by one messaging client.

RequestQueueTemplate property

public string RequestQueueTemplate { get; set; }

Gets or sets the queue name template for incoming requests. Use {service} placeholder for service-specific queues. Example: “router:requests:{service}”

RequestTimeout property

public TimeSpan RequestTimeout { get; set; }

Gets or sets how long a consumer loop waits for the handler of one queue message before it stops awaiting it and releases the message for retry. A request from the gateway is the exception: the service runs it until the request’s own timeout (the TimeoutSeconds of the request frame) and never releases it for a second run; this value applies to a request only when its frame carries no timeout.

ResponseQueueName property

public string ResponseQueueName { get; set; }

Gets or sets the queue name for gateway responses. Example: “router:responses”

GetCancelControlQueueName(string, string) method

public string GetCancelControlQueueName(string serviceName, string connectionId)

Gets the cancellation control queue for one logical service connection.

GetGatewayControlQueueName() method

public string GetGatewayControlQueueName()

Gets the queue name used for gateway control traffic.

GetRequestQueueName(string) method

public string GetRequestQueueName(string serviceName)

Gets the request queue name for a specific service.

StellaOps.Router.Transport.Messaging.Protocol namespace

TypeKindDescription
CancelControlPayloadrecordAuthenticated target binding carried by a dedicated cancellation-control frame: the JSON payload one side of the Messaging transport writes and the other reads.
CorrelationTrackerclassTracks pending request/response correlations for RPC-style messaging.
RpcRequestMessagerecordRepresents an RPC request message sent via the messaging transport.
RpcResponseMessagerecordRepresents an RPC response message sent via the messaging transport.

CancelControlPayload record

public sealed record CancelControlPayload

Authenticated target binding carried by a dedicated cancellation-control frame: the JSON payload one side of the Messaging transport writes and the other reads.

CancelControlPayload() constructor

public CancelControlPayload()

Creates an instance of CancelControlPayload.

OriginalPayloadBase64 property

public required string OriginalPayloadBase64 { get; init; }

The payload of the original CANCEL frame, Base64-encoded.

TargetConnectionId property

public required string TargetConnectionId { get; init; }

The connection identifier the cancellation is addressed to.

TargetService property

public required string TargetService { get; init; }

The service name the cancellation is addressed to.

CorrelationTracker class

public sealed class CorrelationTracker : IDisposable

Tracks pending request/response correlations for RPC-style messaging.

CorrelationTracker(TimeProvider) constructor

public CorrelationTracker(TimeProvider? timeProvider = null)

Initializes a new instance of the CorrelationTrackerclass.

PendingCount property

public int PendingCount { get; }

Gets the number of pending requests.

Dispose() method

public void Dispose()

See IDisposable.Dispose().

RegisterRequestAsync(string, TimeSpan, CancellationToken) method

public Task<Frame> RegisterRequestAsync(string correlationId, TimeSpan timeout, CancellationToken cancellationToken)

Registers a pending request and returns a task that completes when the response arrives.

TryCancelRequest(string) method

public bool TryCancelRequest(string correlationId)

Cancels a pending request.

TryCompleteRequest(string, Frame) method

public bool TryCompleteRequest(string correlationId, Frame response)

Completes a pending request with the given response.

TryFailRequest(string, Exception) method

public bool TryFailRequest(string correlationId, Exception exception)

Fails a pending request with an exception.

RpcRequestMessage record

public sealed record RpcRequestMessage

Represents an RPC request message sent via the messaging transport.

RpcRequestMessage() constructor

public RpcRequestMessage()

Creates an instance of RpcRequestMessage.

ConnectionId property

public required string ConnectionId { get; init; }

Gets the connection ID of the sender.

CorrelationId property

public required string CorrelationId { get; init; }

Gets the correlation ID for matching requests to responses.

CreatedAt property

public DateTimeOffset CreatedAt { get; init; }

Gets the timestamp when this request was created.

EnvelopeSeal property

public FrameEnvelopeSeal? EnvelopeSeal { get; init; }

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

Remarks

Messaging transports must carry the envelope seal alongside the payload so that MessagingTransportServer (StellaOps.Router.Transport.Messaging.Server) can verify before dispatch and dead-letter forged frames with reason envelope-invalid.

FrameType property

public required FrameType FrameType { get; init; }

Gets the frame type.

PayloadBase64 property

public required string PayloadBase64 { get; init; }

Gets the frame payload as base64-encoded bytes.

ReplyToQueue property

public string? ReplyToQueue { get; init; }

Gets the reply-to queue name for responses.

SenderInstanceId property

public string? SenderInstanceId { get; init; }

Gets the instance ID of the sender.

TargetService property

public required string TargetService { get; init; }

Gets the target service name.

Timeout property

public TimeSpan? Timeout { get; init; }

Gets the timeout for this request.

RpcResponseMessage record

public sealed record RpcResponseMessage

Represents an RPC response message sent via the messaging transport.

RpcResponseMessage() constructor

public RpcResponseMessage()

Creates an instance of RpcResponseMessage.

ConnectionId property

public required string ConnectionId { get; init; }

Gets the connection ID of the responder.

CorrelationId property

public required string CorrelationId { get; init; }

Gets the correlation ID matching the original request.

CreatedAt property

public DateTimeOffset CreatedAt { get; init; }

Gets the timestamp when this response was created.

EnvelopeSeal property

public FrameEnvelopeSeal? EnvelopeSeal { get; init; }

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

Remarks

Response messages carry the seal computed by the responding microservice’s signer so the gateway can verify before forwarding the response to the caller.

ErrorMessage property

public string? ErrorMessage { get; init; }

Gets the error message if the request failed.

FrameType property

public required FrameType FrameType { get; init; }

Gets the frame type.

IsSuccess property

public bool IsSuccess { get; init; }

Gets a value indicating whether the request was successful.

PayloadBase64 property

public required string PayloadBase64 { get; init; }

Gets the frame payload as base64-encoded bytes.

ResponderInstanceId property

public string? ResponderInstanceId { get; init; }

Gets the instance ID of the responder.