StellaOps.Router.Transport.Tcp
Router TCP transport, client side: connects a microservice to a gateway over TCP. Install Installing Stella Ops packagesRouter downloads and signaturesnet10.01.0.1-20261117T070237Zdotnet add package StellaOps.
Namespaces
| Namespace | Types |
|---|---|
StellaOps. | 7 |
namespace StellaOps.Router.Transport.Tcp
| Type | Kind | Description |
|---|---|---|
FrameProtocol | class | Handles reading and writing length-prefixed frames over a stream. |
PendingRequestTracker | class | Tracks pending requests waiting for responses. |
TcpConnection | class | Represents a TCP connection to a microservice. |
TcpTransportClient | class | TCP transport client implementation for microservices. |
TcpTransportClientServiceCollectionExtensions | class | Extension methods for registering TCP transport services. |
TcpTransportOptions | class | Configuration options for TCP transport. |
TcpTransportPlugin | class | Plugin for the client side of the TCP transport, which a microservice connects with. |
class FrameProtocol
public static class FrameProtocol
Handles reading and writing length-prefixed frames over a stream. Frame format: [4-byte big-endian length][payload] Payload format: [1-byte frame type][1-byte correlation length N][N bytes UTF-8 correlation id][remaining data] (TransportFrameHeader). The correlation id travels unchanged, so the gateway’s ULID correlations survive the round trip.
Members
| Member | Kind | Summary |
|---|---|---|
ReadFrameAsync( | method | Reads a complete frame from the stream. |
WriteFrameAsync( | method | Writes a frame to the stream without a size check. |
WriteFrameAsync( | method | Writes a frame to the stream after checking its size against maxFrameSize. |
method ReadFrameAsync(Stream, int, CancellationToken) #
ReadFrameAsync(Stream, int, CancellationToken) #public static Task<Frame?> ReadFrameAsync(Stream stream, int maxFrameSize, CancellationToken cancellationToken)
Reads a complete frame from the stream.
Parameters
stream: The stream to read from.maxFrameSize: The maximum frame size allowed.cancellationToken: Cancellation token.
Returns
The frame read, or null if the stream is closed.
method WriteFrameAsync(Stream, Frame, CancellationToken) #
WriteFrameAsync(Stream, Frame, CancellationToken) #public static Task WriteFrameAsync(Stream stream, Frame frame, CancellationToken cancellationToken)
Writes a frame to the stream without a size check.
Parameters
stream: The stream to write to.frame: The frame to write.cancellationToken: Cancellation token.
Exceptions
ArgumentException: The correlation id is longer thanTransportFrameHeader.UTF-8 bytes.MaxCorrelationIdBytes
method WriteFrameAsync(Stream, Frame, int, CancellationToken) #
WriteFrameAsync(Stream, Frame, int, CancellationToken) #public static Task WriteFrameAsync(Stream stream, Frame frame, int maxFrameSize, CancellationToken cancellationToken)
Writes a frame to the stream after checking its size against maxFrameSize. A larger frame is refused before anything is written: the reader on the other side refuses it too, after the length prefix, and the stream would be left in the middle of the frame.
Parameters
stream: The stream to write to.frame: The frame to write.maxFrameSize: The maximum frame size, as the reader’sMaxFrameSize.cancellationToken: Cancellation token.
Exceptions
PayloadTooLargeException: The frame is larger thanmaxFrameSize.
class PendingRequestTracker
public sealed class PendingRequestTracker : IDisposable
Tracks pending requests waiting for responses. Enables multiplexing multiple concurrent requests on a single connection.
Members
| Member | Kind | Summary |
|---|---|---|
PendingRequestTracker( | constructor | Creates an instance of Pending. |
Count | property | Gets the number of pending requests. |
CancelAll( | method | Cancels all pending requests. |
CancelRequest( | method | Cancels a pending request. |
CompleteRequest( | method | Completes a pending request with the response. |
Dispose( | method | See IDisposable.. |
FailRequest( | method | Fails a pending request with an exception. |
TrackRequest( | method | Tracks a request and returns a task that completes when the response arrives. |
constructor PendingRequestTracker() #
PendingRequestTracker() #public PendingRequestTracker()
Creates an instance of Pending.
property Count #
Count #public int Count { get; }
Gets the number of pending requests.
method CancelAll(Exception) #
CancelAll(Exception) #public void CancelAll(Exception? exception = null)
Cancels all pending requests.
Parameters
exception: Optional exception to set.
method CancelRequest(Guid) #
CancelRequest(Guid) #public bool CancelRequest(Guid correlationId)
Cancels a pending request.
Parameters
correlationId: The correlation ID.
Returns
True if the request was found and cancelled; false otherwise.
method CompleteRequest(Guid, Frame) #
CompleteRequest(Guid, Frame) #public bool CompleteRequest(Guid correlationId, Frame response)
Completes a pending request with the response.
Parameters
correlationId: The correlation ID.response: The response frame.
Returns
True if the request was found and completed; false otherwise.
method Dispose() #
Dispose() #public void Dispose()
See IDisposable..
method FailRequest(Guid, Exception) #
FailRequest(Guid, Exception) #public bool FailRequest(Guid correlationId, Exception exception)
Fails a pending request with an exception.
Parameters
correlationId: The correlation ID.exception: The exception.
Returns
True if the request was found and failed; false otherwise.
method TrackRequest(Guid, CancellationToken) #
TrackRequest(Guid, CancellationToken) #public Task<Frame> TrackRequest(Guid correlationId, CancellationToken cancellationToken)
Tracks a request and returns a task that completes when the response arrives.
Parameters
correlationId: The correlation ID of the request.cancellationToken: Cancellation token.
Returns
A task that completes with the response frame.
class TcpConnection
public sealed class TcpConnection : IAsyncDisposable
Represents a TCP connection to a microservice.
Members
| Member | Kind | Summary |
|---|---|---|
TcpConnection( | constructor | Initializes a new instance of the TcpConnectionclass. |
ConnectionId | property | Gets the connection ID. |
ConnectionToken | property | Gets the cancellation token for this connection. |
IsConnected | property | Gets a value indicating whether the connection is active. |
RemoteEndpoint | property | Gets the remote endpoint as a string. |
State | property | Gets the connection state. |
OnDisconnected | event | Event raised when the connection is closed. |
OnFrameReceived | event | Event raised when a frame is received. |
Close( | method | Closes the connection. |
DisposeAsync( | method | See IAsync. |
ReadLoopAsync( | method | Starts the read loop to receive frames. |
WriteFrameAsync( | method | Writes a frame to the connection. |
constructor TcpConnection(string, TcpClient, TcpTransportOptions, ILogger) #
TcpConnection(string, TcpClient, TcpTransportOptions, ILogger) #public TcpConnection(string connectionId, TcpClient client, TcpTransportOptions options, ILogger logger)
Initializes a new instance of the TcpConnectionclass.
property ConnectionId #
ConnectionId #public string ConnectionId { get; }
Gets the connection ID.
property ConnectionToken #
ConnectionToken #public CancellationToken ConnectionToken { get; }
Gets the cancellation token for this connection.
property IsConnected #
IsConnected #public bool IsConnected { get; }
Gets a value indicating whether the connection is active.
property RemoteEndpoint #
RemoteEndpoint #public string RemoteEndpoint { get; }
Gets the remote endpoint as a string.
property State #
State #public ConnectionState? State { get; set; }
Gets the connection state.
event OnDisconnected #
OnDisconnected #public event Action<TcpConnection, Exception?>? OnDisconnected
Event raised when the connection is closed.
event OnFrameReceived #
OnFrameReceived #public event Action<TcpConnection, Frame>? OnFrameReceived
Event raised when a frame is received.
method Close() #
Close() #public void Close()
Closes the connection.
method DisposeAsync() #
DisposeAsync() #public ValueTask DisposeAsync()
See IAsync.
method ReadLoopAsync(CancellationToken) #
ReadLoopAsync(CancellationToken) #public Task ReadLoopAsync(CancellationToken cancellationToken)
Starts the read loop to receive frames.
Parameters
cancellationToken: Cancellation token.
method WriteFrameAsync(Frame, CancellationToken) #
WriteFrameAsync(Frame, CancellationToken) #public Task WriteFrameAsync(Frame frame, CancellationToken cancellationToken = default)
Writes a frame to the connection.
Parameters
frame: The frame to write.cancellationToken: Cancellation token.
class TcpTransportClient
public sealed class TcpTransportClient : ITransportClient, IMicroserviceTransport, IAsyncDisposable
TCP transport client implementation for microservices.
Members
constructor TcpTransportClient(IOptions<TcpTransportOptions>, ILogger<TcpTransportClient>) #
TcpTransportClient(IOptions<TcpTransportOptions>, ILogger<TcpTransportClient>) #public TcpTransportClient(IOptions<TcpTransportOptions> options, ILogger<TcpTransportClient> logger)
Initializes a new instance of the TcpTransportClientclass.
event OnCancelReceived #
OnCancelReceived #public event Func<Guid, string?, Task>? OnCancelReceived
Event raised when a CANCEL frame is received.
event OnRequestReceived #
OnRequestReceived #public event Func<Frame, CancellationToken, Task<Frame>>? OnRequestReceived
Event raised when a REQUEST frame is received.
event TransportDied #
TransportDied #public event Action? TransportDied
Raised once when the connection is lost and TcpTransportOptions.reconnects have failed. The service’s connection manager then connects again with its own back-off until the gateway answers or the service stops.
method CancelAllInflight(string) #
CancelAllInflight(string) #public void CancelAllInflight(string reason)
Cancels all in-flight handlers.
method ConnectAsync(InstanceDescriptor, IReadOnlyList<EndpointDescriptor>, CancellationToken) #
ConnectAsync(InstanceDescriptor, IReadOnlyList<EndpointDescriptor>, CancellationToken) #public Task ConnectAsync(InstanceDescriptor instance, IReadOnlyList<EndpointDescriptor> endpoints, CancellationToken cancellationToken)
Connects to the gateway.
Parameters
instance: The instance descriptor.endpoints: The endpoints to register.cancellationToken: Cancellation token.
method ConnectAsync(InstanceDescriptor, IReadOnlyList<EndpointDescriptor>, IReadOnlyDictionary<string, SchemaDefinition>, ServiceOpenApiInfo, CancellationToken) #
ConnectAsync(InstanceDescriptor, IReadOnlyList<EndpointDescriptor>, IReadOnlyDictionary<string, SchemaDefinition>, ServiceOpenApiInfo, CancellationToken) #public Task ConnectAsync(InstanceDescriptor instance, IReadOnlyList<EndpointDescriptor> endpoints, IReadOnlyDictionary<string, SchemaDefinition>? schemas, ServiceOpenApiInfo? openApiInfo, CancellationToken cancellationToken)
Connects to the gateway and registers the instance, its endpoints, schemas and OpenAPI metadata in the HELLO frame.
Parameters
instance: The instance descriptor.endpoints: The endpoints to register.schemas: Schema definitions referenced by the endpoints.openApiInfo: OpenAPI metadata for the service.cancellationToken: Cancellation token.
method DisconnectAsync() #
DisconnectAsync() #public Task DisconnectAsync()
Disconnects from the gateway.
method DisposeAsync() #
DisposeAsync() #public ValueTask DisposeAsync()
See IAsync.
method SendCancelAsync(ConnectionState, Guid, string) #
SendCancelAsync(ConnectionState, Guid, string) #public Task SendCancelAsync(ConnectionState connection, Guid correlationId, string? reason = null)
Sends a cancellation request.
Parameters
connection: The connection to use.correlationId: The correlation ID of the request to cancel.reason: Optional reason for cancellation.
method SendHeartbeatAsync(HeartbeatPayload, CancellationToken) #
SendHeartbeatAsync(HeartbeatPayload, CancellationToken) #public Task SendHeartbeatAsync(HeartbeatPayload heartbeat, CancellationToken cancellationToken)
Sends a heartbeat.
method SendRequestAsync(ConnectionState, Frame, TimeSpan, CancellationToken) #
SendRequestAsync(ConnectionState, Frame, TimeSpan, CancellationToken) #public Task<Frame> SendRequestAsync(ConnectionState connection, Frame requestFrame, TimeSpan timeout, CancellationToken cancellationToken)
Sends a request and waits for a response.
Parameters
connection: The connection to use.requestFrame: The request frame.timeout: The timeout for the request.cancellationToken: Cancellation token.
Returns
The response frame.
method SendStreamingAsync(ConnectionState, Frame, Stream, Func<ResponseFrame, Stream, Task>, PayloadLimits, CancellationToken) #
SendStreamingAsync(ConnectionState, Frame, Stream, Func<ResponseFrame, Stream, Task>, PayloadLimits, CancellationToken) #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.implements it for transports whose microservice side answers a request with one response frame.
Parameters
connection: The connection to use.requestHeader: The request header frame.requestBody: The request body stream.readResponse: Callback that receives the response head (the status code and headers of the microservice’s response; itsResponseFrame.is empty) and the response body stream.Payload limits: Payload limits to enforce.cancellationToken: Cancellation token.
Remarks
Sends the request body in one request frame (TransportStreamingDispatch.).
class TcpTransportClientServiceCollectionExtensions
public static class TcpTransportClientServiceCollectionExtensions
Extension methods for registering TCP transport services.
Members
| Member | Kind | Summary |
|---|---|---|
AddTcpTransportClient( | extension method | Adds TCP transport client services to the service collection. |
extension method AddTcpTransportClient(IServiceCollection, Action<TcpTransportOptions>) #
AddTcpTransportClient(IServiceCollection, Action<TcpTransportOptions>) #public static IServiceCollection AddTcpTransportClient(this IServiceCollection services, Action<TcpTransportOptions>? configure = null)
Adds TCP transport client services to the service collection.
Parameters
services: The service collection.configure: Optional configuration action.
Returns
The service collection.
class TcpTransportOptions
public sealed class TcpTransportOptions
Configuration options for TCP transport.
Members
| Member | Kind | Summary |
|---|---|---|
TcpTransportOptions( | constructor | Creates an instance of TcpTransportOptions. |
BindAddress | property | Gets or sets the address to bind to. |
ConnectTimeout | property | Gets or sets the connection timeout. |
Host | property | Gets or sets the host for client connections. |
KeepAliveInterval | property | Gets or sets the TCP keep-alive interval of the connection’s socket, on the service and on the gateway: after this long without traffic the operating system probes the peer, probes again every interval and closes the connection after three unanswered probes, so a peer that vanished without closing the connection is noticed. |
MaxFrameSize | property | Gets or sets the maximum frame size in bytes. |
MaxReconnectAttempts | property | Gets or sets the number of reconnection attempts after a lost connection, with the capped back-off of TcpTransportOptions.. |
MaxReconnectBackoff | property | Gets or sets the maximum reconnection backoff. |
Port | property | Gets or sets the port to listen on, or the gateway port a client connects to. |
ReceiveBufferSize | property | Gets or sets the receive buffer size. |
SendBufferSize | property | Gets or sets the send buffer size. |
constructor TcpTransportOptions() #
TcpTransportOptions() #public TcpTransportOptions()
Creates an instance of TcpTransportOptions.
property BindAddress #
BindAddress #public IPAddress BindAddress { get; set; }
Gets or sets the address to bind to. Default: IPAddress.Any (0.0.0.0).
property ConnectTimeout #
ConnectTimeout #public TimeSpan ConnectTimeout { get; set; }
Gets or sets the connection timeout. Default: 10 seconds.
property Host #
Host #public string? Host { get; set; }
Gets or sets the host for client connections.
property KeepAliveInterval #
KeepAliveInterval #public TimeSpan KeepAliveInterval { get; set; }
Gets or sets the TCP keep-alive interval of the connection’s socket, on the service and on the gateway: after this long without traffic the operating system probes the peer, probes again every interval and closes the connection after three unanswered probes, so a peer that vanished without closing the connection is noticed. Zero or a negative value turns keep-alive off. Whole seconds, rounded up. Default: 30 seconds.
property MaxFrameSize #
MaxFrameSize #public int MaxFrameSize { get; set; }
Gets or sets the maximum frame size in bytes. Default: 16 MB.
property MaxReconnectAttempts #
MaxReconnectAttempts #public int MaxReconnectAttempts { get; set; }
Gets or sets the number of reconnection attempts after a lost connection, with the capped back-off of TcpTransportOptions.. When they all fail, the client raises TcpTransportClient.and the service’s connection manager connects again with its own back-off until the gateway answers or the service stops; the service is never left disconnected. Default: 10.
property MaxReconnectBackoff #
MaxReconnectBackoff #public TimeSpan MaxReconnectBackoff { get; set; }
Gets or sets the maximum reconnection backoff. Default: 1 minute.
property Port #
Port #public int Port { get; set; }
Gets or sets the port to listen on, or the gateway port a client connects to. Default: TransportDefaultPorts.(9100), the gateway options’ default.
property ReceiveBufferSize #
ReceiveBufferSize #public int ReceiveBufferSize { get; set; }
Gets or sets the receive buffer size. Default: 64 KB.
property SendBufferSize #
SendBufferSize #public int SendBufferSize { get; set; }
Gets or sets the send buffer size. Default: 64 KB.
class TcpTransportPlugin
public sealed class TcpTransportPlugin : IRouterTransportPlugin
Plugin for the client side of the TCP transport, which a microservice connects with. The server side is Tcp in Stella; both carry the transport name tcp.
Members
| Member | Kind | Summary |
|---|---|---|
TcpTransportPlugin( | constructor | Creates an instance of TcpTransportPlugin. |
AllowInsecureTransportsEnvVar | constant | Environment variable that enables loading the TCP transport plugin. |
DisplayName | property | Gets the human-readable display name for this transport. |
Mode | property | Gets the side of the transport this plugin registers: RouterTransportMode., RouterTransportMode., or RouterTransportMode.. |
TransportName | property | Gets the transport name (e.g., “tcp”, “tls”, “udp”, “rabbitmq”, “inmemory”, “messaging”), shared by the client and the server plugin of one transport. |
IsInsecureTransportsAllowed( | method | Returns true when TcpTransportPlugin.is set to a truthy value (case-insensitive: true, 1, yes). |
Register( | method | Registers transport services into the DI container for the side the context asks for. |
RegisterShared( | method | The registration the client and the server plugin of the TCP transport share: the insecure-transport guard (TcpTransportPlugin.) and the TcpTransportOptionsbinding of the context’s configuration section (Router:Transport:Tcp when the context names none). |
constructor TcpTransportPlugin() #
TcpTransportPlugin() #public TcpTransportPlugin()
Creates an instance of TcpTransportPlugin.
constant AllowInsecureTransportsEnvVar #
AllowInsecureTransportsEnvVar #public const string AllowInsecureTransportsEnvVar = "STELLAOPS_ROUTER_ALLOW_INSECURE_TRANSPORTS"
Environment variable that enables loading the TCP transport plugin. TCP is unencrypted and unauthenticated at the network layer; the runtime guard refuses to register the plugin unless the operator explicitly opts in.
property DisplayName #
DisplayName #public string DisplayName { get; }
Gets the human-readable display name for this transport.
property Mode #
Mode #public RouterTransportMode Mode { get; }
Gets the side of the transport this plugin registers: RouterTransportMode., RouterTransportMode., or RouterTransportMode.. IRouterTransportPlugin.refuses a context that asks for a side outside this value (RouterTransportRegistrationContext.).
property TransportName #
TransportName #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.
method IsInsecureTransportsAllowed() #
IsInsecureTransportsAllowed() #public static bool IsInsecureTransportsAllowed()
Returns true when TcpTransportPlugin.is set to a truthy value (case-insensitive: true, 1, yes).
method Register(RouterTransportRegistrationContext) #
Register(RouterTransportRegistrationContext) #public void Register(RouterTransportRegistrationContext context)
Registers transport services into the DI container for the side the context asks for.
Parameters
context: The registration context containing services, configuration, and transport mode.
Exceptions
Invalid: The context asks for a side this plugin does not provide.Operation Exception
method RegisterShared(RouterTransportRegistrationContext, Type) #
RegisterShared(RouterTransportRegistrationContext, Type) #public static void RegisterShared(RouterTransportRegistrationContext context, Type loggerCategory)
The registration the client and the server plugin of the TCP transport share: the insecure-transport guard (TcpTransportPlugin.) and the TcpTransportOptionsbinding of the context’s configuration section (Router:Transport:Tcp when the context names none). Both plugins call it from TcpTransportPlugin.; a plugin for either side of the transport calls it the same way.
Parameters
context: The registration context of the plugin.loggerCategory: The logger category of the warning written when the guard is open.
Exceptions
Invalid: The insecure-transport guard is closed.Operation Exception