StellaOps.Router.Transport.Tcp

Router TCP transport, client side: connects a microservice to a gateway over TCP.

library
Component
Router
Licence
Apache-2.0
Target framework
net10.0
Latest release
1.0.1-20261117T070237Z

Install

dotnet add package StellaOps.Router.Transport.Tcp --version 1.0.1-20261117T070237Z

Namespaces

NamespaceTypes
StellaOps.Router.Transport.Tcp7

namespace StellaOps.Router.Transport.Tcp

TypeKindDescription
FrameProtocolclassHandles reading and writing length-prefixed frames over a stream.
PendingRequestTrackerclassTracks pending requests waiting for responses.
TcpConnectionclassRepresents a TCP connection to a microservice.
TcpTransportClientclassTCP transport client implementation for microservices.
TcpTransportClientServiceCollectionExtensionsclassExtension methods for registering TCP transport services.
TcpTransportOptionsclassConfiguration options for TCP transport.
TcpTransportPluginclassPlugin 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

MemberKindSummary
ReadFrameAsync(Stream, int, CancellationToken)methodReads a complete frame from the stream.
WriteFrameAsync(Stream, Frame, CancellationToken)methodWrites a frame to the stream without a size check.
WriteFrameAsync(Stream, Frame, int, CancellationToken)methodWrites a frame to the stream after checking its size against maxFrameSize.

method 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) #

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

method 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’s MaxFrameSize.
  • cancellationToken: Cancellation token.

Exceptions

class PendingRequestTracker

public sealed class PendingRequestTracker : IDisposable

Tracks pending requests waiting for responses. Enables multiplexing multiple concurrent requests on a single connection.

Members

MemberKindSummary
PendingRequestTracker()constructorCreates an instance of PendingRequestTracker.
CountpropertyGets the number of pending requests.
CancelAll(Exception)methodCancels all pending requests.
CancelRequest(Guid)methodCancels a pending request.
CompleteRequest(Guid, Frame)methodCompletes a pending request with the response.
Dispose()methodSee IDisposable.Dispose().
FailRequest(Guid, Exception)methodFails a pending request with an exception.
TrackRequest(Guid, CancellationToken)methodTracks a request and returns a task that completes when the response arrives.

constructor PendingRequestTracker() #

public PendingRequestTracker()

Creates an instance of PendingRequestTracker.

property Count #

public int Count { get; }

Gets the number of pending requests.

method CancelAll(Exception) #

public void CancelAll(Exception? exception = null)

Cancels all pending requests.

Parameters

  • exception: Optional exception to set.

method 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) #

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() #

public void Dispose()

See IDisposable.Dispose().

method 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) #

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

MemberKindSummary
TcpConnection(string, TcpClient, TcpTransportOptions, ILogger)constructorInitializes a new instance of the TcpConnectionclass.
ConnectionIdpropertyGets the connection ID.
ConnectionTokenpropertyGets the cancellation token for this connection.
IsConnectedpropertyGets a value indicating whether the connection is active.
RemoteEndpointpropertyGets the remote endpoint as a string.
StatepropertyGets the connection state.
OnDisconnectedeventEvent raised when the connection is closed.
OnFrameReceivedeventEvent raised when a frame is received.
Close()methodCloses the connection.
DisposeAsync()methodSee IAsyncDisposable.DisposeAsync().
ReadLoopAsync(CancellationToken)methodStarts the read loop to receive frames.
WriteFrameAsync(Frame, CancellationToken)methodWrites a frame to the connection.

constructor TcpConnection(string, TcpClient, TcpTransportOptions, ILogger) #

public TcpConnection(string connectionId, TcpClient client, TcpTransportOptions options, ILogger logger)

Initializes a new instance of the TcpConnectionclass.

property ConnectionId #

public string ConnectionId { get; }

Gets the connection ID.

property ConnectionToken #

public CancellationToken ConnectionToken { get; }

Gets the cancellation token for this connection.

property IsConnected #

public bool IsConnected { get; }

Gets a value indicating whether the connection is active.

property RemoteEndpoint #

public string RemoteEndpoint { get; }

Gets the remote endpoint as a string.

property State #

public ConnectionState? State { get; set; }

Gets the connection state.

event OnDisconnected #

public event Action<TcpConnection, Exception?>? OnDisconnected

Event raised when the connection is closed.

event OnFrameReceived #

public event Action<TcpConnection, Frame>? OnFrameReceived

Event raised when a frame is received.

method Close() #

public void Close()

Closes the connection.

method DisposeAsync() #

public ValueTask DisposeAsync()

See IAsyncDisposable.DisposeAsync().

method ReadLoopAsync(CancellationToken) #

public Task ReadLoopAsync(CancellationToken cancellationToken)

Starts the read loop to receive frames.

Parameters

  • cancellationToken: Cancellation token.

method 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

MemberKindSummary
TcpTransportClient(IOptions<TcpTransportOptions>, ILogger<TcpTransportClient>)constructorInitializes a new instance of the TcpTransportClientclass.
OnCancelReceivedeventEvent raised when a CANCEL frame is received.
OnRequestReceivedeventEvent raised when a REQUEST frame is received.
TransportDiedeventRaised once when the connection is lost and TcpTransportOptions.MaxReconnectAttemptsreconnects have failed.
CancelAllInflight(string)methodCancels all in-flight handlers.
ConnectAsync(InstanceDescriptor, IReadOnlyList<EndpointDescriptor>, CancellationToken)methodConnects to the gateway.
ConnectAsync(InstanceDescriptor, IReadOnlyList<EndpointDescriptor>, IReadOnlyDictionary<string, SchemaDefinition>, ServiceOpenApiInfo, CancellationToken)methodConnects to the gateway and registers the instance, its endpoints, schemas and OpenAPI metadata in the HELLO frame.
DisconnectAsync()methodDisconnects from the gateway.
DisposeAsync()methodSee IAsyncDisposable.DisposeAsync().
SendCancelAsync(ConnectionState, Guid, string)methodSends a cancellation request.
SendHeartbeatAsync(HeartbeatPayload, CancellationToken)methodSends a heartbeat.
SendRequestAsync(ConnectionState, Frame, TimeSpan, CancellationToken)methodSends a request and waits for a response.
SendStreamingAsync(ConnectionState, Frame, Stream, Func<ResponseFrame, Stream, Task>, PayloadLimits, CancellationToken)methodSends a request whose body is read from a stream and hands the microservice’s response to readResponse.

constructor TcpTransportClient(IOptions<TcpTransportOptions>, ILogger<TcpTransportClient>) #

public TcpTransportClient(IOptions<TcpTransportOptions> options, ILogger<TcpTransportClient> logger)

Initializes a new instance of the TcpTransportClientclass.

event OnCancelReceived #

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

Event raised when a CANCEL frame is received.

event OnRequestReceived #

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

Event raised when a REQUEST frame is received.

event TransportDied #

public event Action? TransportDied

Raised once when the connection is lost and TcpTransportOptions.MaxReconnectAttemptsreconnects 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) #

public void CancelAllInflight(string reason)

Cancels all in-flight handlers.

method 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) #

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() #

public Task DisconnectAsync()

Disconnects from the gateway.

method DisposeAsync() #

public ValueTask DisposeAsync()

See IAsyncDisposable.DisposeAsync().

method 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) #

public Task SendHeartbeatAsync(HeartbeatPayload heartbeat, CancellationToken cancellationToken)

Sends a heartbeat.

method 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) #

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

  • 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; its ResponseFrame.Payloadis empty) and the response body stream.
  • limits: Payload limits to enforce.
  • cancellationToken: Cancellation token.

Remarks

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

class TcpTransportClientServiceCollectionExtensions

public static class TcpTransportClientServiceCollectionExtensions

Extension methods for registering TCP transport services.

Members

MemberKindSummary
AddTcpTransportClient(IServiceCollection, Action<TcpTransportOptions>)extension methodAdds TCP transport client services to the service collection.

extension method 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

MemberKindSummary
TcpTransportOptions()constructorCreates an instance of TcpTransportOptions.
BindAddresspropertyGets or sets the address to bind to.
ConnectTimeoutpropertyGets or sets the connection timeout.
HostpropertyGets or sets the host for client connections.
KeepAliveIntervalpropertyGets 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.
MaxFrameSizepropertyGets or sets the maximum frame size in bytes.
MaxReconnectAttemptspropertyGets or sets the number of reconnection attempts after a lost connection, with the capped back-off of TcpTransportOptions.MaxReconnectBackoff.
MaxReconnectBackoffpropertyGets or sets the maximum reconnection backoff.
PortpropertyGets or sets the port to listen on, or the gateway port a client connects to.
ReceiveBufferSizepropertyGets or sets the receive buffer size.
SendBufferSizepropertyGets or sets the send buffer size.

constructor TcpTransportOptions() #

public TcpTransportOptions()

Creates an instance of TcpTransportOptions.

property BindAddress #

public IPAddress BindAddress { get; set; }

Gets or sets the address to bind to. Default: IPAddress.Any (0.0.0.0).

property ConnectTimeout #

public TimeSpan ConnectTimeout { get; set; }

Gets or sets the connection timeout. Default: 10 seconds.

property Host #

public string? Host { get; set; }

Gets or sets the host for client connections.

property 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 #

public int MaxFrameSize { get; set; }

Gets or sets the maximum frame size in bytes. Default: 16 MB.

property 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.MaxReconnectBackoff. When they all fail, the client raises TcpTransportClient.TransportDiedand 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 #

public TimeSpan MaxReconnectBackoff { get; set; }

Gets or sets the maximum reconnection backoff. Default: 1 minute.

property Port #

public int Port { get; set; }

Gets or sets the port to listen on, or the gateway port a client connects to. Default: TransportDefaultPorts.Tcp(9100), the gateway options’ default.

property ReceiveBufferSize #

public int ReceiveBufferSize { get; set; }

Gets or sets the receive buffer size. Default: 64 KB.

property 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 TcpTransportServerPlugin in StellaOps.Router.Transport.Tcp.Server; both carry the transport name tcp.

Members

MemberKindSummary
TcpTransportPlugin()constructorCreates an instance of TcpTransportPlugin.
AllowInsecureTransportsEnvVarconstantEnvironment variable that enables loading the TCP transport plugin.
DisplayNamepropertyGets the human-readable display name for this transport.
ModepropertyGets the side of the transport this plugin registers: RouterTransportMode.Client, RouterTransportMode.Server, or RouterTransportMode.Both.
TransportNamepropertyGets the transport name (e.g., “tcp”, “tls”, “udp”, “rabbitmq”, “inmemory”, “messaging”), shared by the client and the server plugin of one transport.
IsInsecureTransportsAllowed()methodReturns true when TcpTransportPlugin.AllowInsecureTransportsEnvVaris set to a truthy value (case-insensitive: true, 1, yes).
Register(RouterTransportRegistrationContext)methodRegisters transport services into the DI container for the side the context asks for.
RegisterShared(RouterTransportRegistrationContext, Type)methodThe registration the client and the server plugin of the TCP transport share: the insecure-transport guard (TcpTransportPlugin.AllowInsecureTransportsEnvVar) and the TcpTransportOptionsbinding of the context’s configuration section (Router:Transport:Tcp when the context names none).

constructor TcpTransportPlugin() #

public TcpTransportPlugin()

Creates an instance of TcpTransportPlugin.

constant 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 #

public string DisplayName { get; }

Gets the human-readable display name for this transport.

property Mode #

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)).

property 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() #

public static bool IsInsecureTransportsAllowed()

Returns true when TcpTransportPlugin.AllowInsecureTransportsEnvVaris set to a truthy value (case-insensitive: true, 1, yes).

method 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

  • InvalidOperationException: The context asks for a side this plugin does not provide.

method 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.AllowInsecureTransportsEnvVar) and the TcpTransportOptionsbinding of the context’s configuration section (Router:Transport:Tcp when the context names none). Both plugins call it from TcpTransportPlugin.Register(RouterTransportRegistrationContext); 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

  • InvalidOperationException: The insecure-transport guard is closed.