StellaOps.Router.Transport.Tcp
Router TCP transport, client side: connects a microservice to a gateway over TCP.
| Package | StellaOps.Router.Transport.Tcp |
| Component | Router |
| Licence | Apache-2.0 |
| Package kind | Library |
| Target framework | net10.0 |
To add the package to a project, see Installing Stella Ops packages.
Namespaces
| Namespace | Types |
|---|---|
StellaOps.Router.Transport.Tcp | 7 |
StellaOps.Router.Transport.Tcp namespace
| 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. |
FrameProtocol class
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.
ReadFrameAsync(Stream, int, CancellationToken) method
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.
WriteFrameAsync(Stream, Frame, CancellationToken) method
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.MaxCorrelationIdBytesUTF-8 bytes.
WriteFrameAsync(Stream, Frame, int, CancellationToken) method
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.
PendingRequestTracker class
public sealed class PendingRequestTracker : IDisposable
Tracks pending requests waiting for responses. Enables multiplexing multiple concurrent requests on a single connection.
PendingRequestTracker() constructor
public PendingRequestTracker()
Creates an instance of PendingRequestTracker.
Count property
public int Count { get; }
Gets the number of pending requests.
CancelAll(Exception) method
public void CancelAll(Exception? exception = null)
Cancels all pending requests.
Parameters
exception: Optional exception to set.
CancelRequest(Guid) method
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.
CompleteRequest(Guid, Frame) method
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.
Dispose() method
public void Dispose()
See IDisposable.Dispose().
FailRequest(Guid, Exception) method
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.
TrackRequest(Guid, CancellationToken) method
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.
TcpConnection class
public sealed class TcpConnection : IAsyncDisposable
Represents a TCP connection to a microservice.
TcpConnection(string, TcpClient, TcpTransportOptions, ILogger) constructor
public TcpConnection(string connectionId, TcpClient client, TcpTransportOptions options, ILogger logger)
Initializes a new instance of the TcpConnectionclass.
ConnectionId property
public string ConnectionId { get; }
Gets the connection ID.
ConnectionToken property
public CancellationToken ConnectionToken { get; }
Gets the cancellation token for this connection.
IsConnected property
public bool IsConnected { get; }
Gets a value indicating whether the connection is active.
RemoteEndpoint property
public string RemoteEndpoint { get; }
Gets the remote endpoint as a string.
State property
public ConnectionState? State { get; set; }
Gets the connection state.
OnDisconnected event
public event Action<TcpConnection, Exception?>? OnDisconnected
Event raised when the connection is closed.
OnFrameReceived event
public event Action<TcpConnection, Frame>? OnFrameReceived
Event raised when a frame is received.
Close() method
public void Close()
Closes the connection.
DisposeAsync() method
public ValueTask DisposeAsync()
See IAsyncDisposable.DisposeAsync().
ReadLoopAsync(CancellationToken) method
public Task ReadLoopAsync(CancellationToken cancellationToken)
Starts the read loop to receive frames.
Parameters
cancellationToken: Cancellation token.
WriteFrameAsync(Frame, CancellationToken) method
public Task WriteFrameAsync(Frame frame, CancellationToken cancellationToken = default)
Writes a frame to the connection.
Parameters
frame: The frame to write.cancellationToken: Cancellation token.
TcpTransportClient class
public sealed class TcpTransportClient : ITransportClient, IMicroserviceTransport, IAsyncDisposable
TCP transport client implementation for microservices.
TcpTransportClient(IOptions<TcpTransportOptions>, ILogger<TcpTransportClient>) constructor
public TcpTransportClient(IOptions<TcpTransportOptions> options, ILogger<TcpTransportClient> logger)
Initializes a new instance of the TcpTransportClientclass.
OnCancelReceived event
public event Func<Guid, string?, Task>? OnCancelReceived
Event raised when a CANCEL frame is received.
OnRequestReceived event
public event Func<Frame, CancellationToken, Task<Frame>>? OnRequestReceived
Event raised when a REQUEST frame is received.
TransportDied event
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.
CancelAllInflight(string) method
public void CancelAllInflight(string reason)
Cancels all in-flight handlers.
ConnectAsync(InstanceDescriptor, IReadOnlyList<EndpointDescriptor>, CancellationToken) method
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.
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 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.
DisconnectAsync() method
public Task DisconnectAsync()
Disconnects from the gateway.
DisposeAsync() method
public ValueTask DisposeAsync()
See IAsyncDisposable.DisposeAsync().
SendCancelAsync(ConnectionState, Guid, string) method
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.
SendHeartbeatAsync(HeartbeatPayload, CancellationToken) method
public Task SendHeartbeatAsync(HeartbeatPayload heartbeat, CancellationToken cancellationToken)
Sends a heartbeat.
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
connection: The connection to use.requestFrame: The request frame.timeout: The timeout for the request.cancellationToken: Cancellation token.
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
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.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)).
TcpTransportClientServiceCollectionExtensions class
public static class TcpTransportClientServiceCollectionExtensions
Extension methods for registering TCP transport services.
AddTcpTransportClient(IServiceCollection, Action<TcpTransportOptions>) extension method
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.
TcpTransportOptions class
public sealed class TcpTransportOptions
Configuration options for TCP transport.
TcpTransportOptions() constructor
public TcpTransportOptions()
Creates an instance of TcpTransportOptions.
BindAddress property
public IPAddress BindAddress { get; set; }
Gets or sets the address to bind to. Default: IPAddress.Any (0.0.0.0).
ConnectTimeout property
public TimeSpan ConnectTimeout { get; set; }
Gets or sets the connection timeout. Default: 10 seconds.
Host property
public string? Host { get; set; }
Gets or sets the host for client connections.
KeepAliveInterval property
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.
MaxFrameSize property
public int MaxFrameSize { get; set; }
Gets or sets the maximum frame size in bytes. Default: 16 MB.
MaxReconnectAttempts property
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.
MaxReconnectBackoff property
public TimeSpan MaxReconnectBackoff { get; set; }
Gets or sets the maximum reconnection backoff. Default: 1 minute.
Port property
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.
ReceiveBufferSize property
public int ReceiveBufferSize { get; set; }
Gets or sets the receive buffer size. Default: 64 KB.
SendBufferSize property
public int SendBufferSize { get; set; }
Gets or sets the send buffer size. Default: 64 KB.
TcpTransportPlugin class
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.
TcpTransportPlugin() constructor
public TcpTransportPlugin()
Creates an instance of TcpTransportPlugin.
AllowInsecureTransportsEnvVar constant
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.
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.
IsInsecureTransportsAllowed() method
public static bool IsInsecureTransportsAllowed()
Returns true when TcpTransportPlugin.AllowInsecureTransportsEnvVaris set to a truthy value (case-insensitive: true, 1, yes).
Register(RouterTransportRegistrationContext) method
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.
RegisterShared(RouterTransportRegistrationContext, Type) method
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.
