StellaOps.Router.Transport.Tcp

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

PackageStellaOps.Router.Transport.Tcp
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.Tcp7

StellaOps.Router.Transport.Tcp namespace

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.

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

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

Exceptions

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

Exceptions

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

CancelRequest(Guid) method

public bool CancelRequest(Guid correlationId)

Cancels a pending request.

Parameters

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

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

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

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

WriteFrameAsync(Frame, CancellationToken) method

public Task WriteFrameAsync(Frame frame, CancellationToken cancellationToken = default)

Writes a frame to the connection.

Parameters

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

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

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

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

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

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

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

Exceptions

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

Exceptions