StellaOps.Router.Gateway.Hosting

Router gateway host: transport hosting, endpoint claims authorization, health and the router administration endpoints.

PackageStellaOps.Router.Gateway.Hosting
ComponentRouter
LicenceBUSL-1.1 (Router licence)
Package kindLibrary
Target frameworknet10.0

To add the package to a project, see Installing Stella Ops packages.

Namespaces

NamespaceTypes
StellaOps.Router.Gateway.Hosting2
StellaOps.Router.Gateway.Hosting.Authorization3
StellaOps.Router.Gateway.Hosting.Configuration13
StellaOps.Router.Gateway.Hosting.Endpoints4
StellaOps.Router.Gateway.Hosting.Licensing11
StellaOps.Router.Gateway.Hosting.Middleware4
StellaOps.Router.Gateway.Hosting.Routing1
StellaOps.Router.Gateway.Hosting.Services12

StellaOps.Router.Gateway.Hosting namespace

TypeKindDescription
GatewayPipelineExtensionsclassThe parts of the gateway composition that every gateway host shares: the request pipeline that resolves, authorizes and dispatches a request to a microservice, and the mapping of the Gateway configuration section onto the router library options.
RouterGatewayHostExtensionsclassComposes a router gateway host that needs no other Stella Ops service.

GatewayPipelineExtensions class

public static class GatewayPipelineExtensions

The parts of the gateway composition that every gateway host shares: the request pipeline that resolves, authorizes and dispatches a request to a microservice, and the mapping of the Gateway configuration section onto the router library options. Both StellaOps.Gateway.WebService and RouterGatewayHostExtensionscall these, so the two hosts run one pipeline.

AddGatewayOptionsMapping(IServiceCollection) extension method

public static IServiceCollection AddGatewayOptionsMapping(this IServiceCollection services)

Maps the bound GatewayOptionsonto the router library options (RouterNodeConfig, RoutingOptions, PayloadLimits, HealthOptionsand OpenApiAggregationOptions).

Parameters

Returns

The service collection for chaining.

UseGatewayRequestPipeline(IApplicationBuilder) extension method

public static IApplicationBuilder UseGatewayRequestPipeline(this IApplicationBuilder app)

Adds the request pipeline for a request that the host does not answer itself: request logging, error handling, payload limits, endpoint resolution from the routing state, the endpoint claims check (AuthorizationMiddleware), rate limiting, the routing decision and the transport dispatch.

Parameters

Returns

The application builder for chaining.

RouterGatewayHostExtensions class

public static class RouterGatewayHostExtensions

Composes a router gateway host that needs no other Stella Ops service. It runs the gateway pipeline (transport hosting, endpoint claims authorization, health, the router administration endpoints) and authenticates callers with standard JWT bearer tokens from any OpenID Connect issuer. It uses Valkey only when rate-limit rules or the Messaging transport are configured to use it, and it needs no crypto provider beyond the built-in default.

Remarks

Transports come from signed bundles and from assemblies deployed with the host. Signed bundles are the runtime-bundle.v2 bundles under Gateway:TransportPlugins:Directory, admitted by StellaOps.Plugin against the RS256 and ES256 public keys of the local trust-root directory Gateway:TransportPlugins:TrustRootDirectory; a refused bundle stops the host. They load first, so a transport side a bundle provides is used instead of one built into the host. Then come the assemblies the host passes to RouterGatewayHostExtensions.AddRouterGatewayHost(WebApplicationBuilder, params Assembly[]), every assembly named under Gateway:TransportPlugins:ImageResidentAssemblies, and every StellaOps.Router.Transport.* assembly already loaded into the default load context. The gateway registers the server side of each enabled transport, so the assemblies it needs are the StellaOps.Router.Transport.<Name>.Server ones; the in-process transport provides both sides in one assembly. The X.509-signed transport folders of the Stella Ops gateway (transports.signed.json) are not read here.

The composition includes the Router licence monitor (StellaOps:ComponentLicence): every host built with RouterGatewayHostExtensions.AddRouterGatewayHost(WebApplicationBuilder, params Assembly[])reports its licence status, registered after the transport host so it sees the connected microservices.

Settings that this host does not read (see RouterGatewayHostExtensions.PlatformOnlySections) stop the host at startup instead of being ignored.

Hosted services start in registration order. A hosted service registered after RouterGatewayHostExtensions.AddRouterGatewayHost(WebApplicationBuilder, params Assembly[])starts after the transport host, so it sees the routing state that the connected microservices populate.

IdentityEnvelopeSigningKeyKey constant

public const string IdentityEnvelopeSigningKeyKey = "Gateway:IdentityEnvelope:SigningKey"

The configuration key of the shared key that signs the identity envelope of every authenticated request routed to a microservice; the microservices verify the envelope with the same key (ASP.NET Core bridge: StellaRouterBridgeOptions.IdentityEnvelopeSigningKey). Optional: without it the gateway sends no caller identity. When set, at least 32 characters.

ImageResidentTransportAssembliesKey constant

public const string ImageResidentTransportAssembliesKey = "Gateway:TransportPlugins:ImageResidentAssemblies"

The configuration key that lists transport assemblies to load at startup.

JwtBearerSectionName constant

public const string JwtBearerSectionName = "Authentication:Schemes:Bearer"

The configuration section that the ASP.NET Core JWT bearer handler reads (Authority, MetadataAddress, RequireHttpsMetadata, ValidIssuer(s), ValidAudience(s), SigningKeys, MapInboundClaims).

PlatformOnlySections field

public static readonly IReadOnlyList<string> PlatformOnlySections

Configuration that only the Stella Ops gateway host reads. A host built with RouterGatewayHostExtensions.AddRouterGatewayHost(WebApplicationBuilder, params Assembly[])refuses to start while any of these is present.

AddRouterGatewayHost(WebApplicationBuilder, params Assembly[]) extension method

public static WebApplicationBuilder AddRouterGatewayHost(this WebApplicationBuilder builder, params Assembly[] transportAssemblies)

Registers the gateway services, the enabled transports, JWT bearer authentication and the authorization policies of the router administration endpoints.

Parameters

Returns

The builder for chaining.

Exceptions

UseRouterGatewayHost(WebApplication) extension method

public static WebApplication UseRouterGatewayHost(this WebApplication app)

Adds the gateway middleware and endpoints: authentication, health (/health, /health/live, /health/ready, /health/startup) and /metrics, the router administration endpoints, the generated OpenAPI document when Gateway:OpenApi:Enabled is true, and the routing pipeline for every other request. A request routed to a microservice loses every identity header the client sent (X-StellaOps-Actor, X-StellaOps-Scopes, the identity envelope headers and the others the Stella Ops gateway reserves); an authenticated caller’s identity travels only in the identity envelope signed with RouterGatewayHostExtensions.IdentityEnvelopeSigningKeyKey.

Parameters

Returns

The application for chaining.

StellaOps.Router.Gateway.Hosting.Authorization namespace

TypeKindDescription
AuthorizationMiddlewareclassEnforces the claim requirements of the endpoint a request is routed to.
EffectiveClaimsStoreclassThe process-local store of the effective claim requirements: those the microservices announce and those an authority overrides.
IEffectiveClaimsStoreinterfaceThe effective claim requirements of the endpoints, with the claims of sibling methods on the same path.

AuthorizationMiddleware class

public sealed class AuthorizationMiddleware

Enforces the claim requirements of the endpoint a request is routed to.

AuthorizationMiddleware(RequestDelegate, IEffectiveClaimsStore, ILogger<AuthorizationMiddleware>) constructor

public AuthorizationMiddleware(RequestDelegate next, IEffectiveClaimsStore claimsStore, ILogger<AuthorizationMiddleware> logger)

Creates the middleware.

Parameters

InvokeAsync(HttpContext) method

public Task InvokeAsync(HttpContext context)

Checks the caller against the endpoint the request was routed to: answers 401 when the endpoint requires an authenticated caller and the caller is anonymous, and 403 when a required claim is missing; a request without a resolved endpoint or to an anonymous endpoint passes.

Parameters

Returns

A task that completes when the request is handled.

EffectiveClaimsStore class

public sealed class EffectiveClaimsStore : IEffectiveClaimsStore

The process-local store of the effective claim requirements: those the microservices announce and those an authority overrides.

EffectiveClaimsStore(ILogger<EffectiveClaimsStore>) constructor

public EffectiveClaimsStore(ILogger<EffectiveClaimsStore> logger)

Creates an empty store.

Parameters

GetEffectiveClaims(string, string, string, string) method

public IReadOnlyList<ClaimRequirement> GetEffectiveClaims(string serviceName, string version, string method, string path)

Gets the effective claims for an endpoint of one version of a service. Authority overrides (which name no version) take precedence over the version’s own claims.

Parameters

Returns

The effective claims for the endpoint.

GetSiblingMethodClaims(string, string, string, string) method

public IReadOnlyList<ClaimRequirement> GetSiblingMethodClaims(string serviceName, string version, string path, string excludeMethod)

Returns the effective claim requirements registered for sibling HTTP methods on the same service + path template. Used to close asymmetric scope enforcement gaps where a state-changing method (POST/PUT/PATCH/DELETE) ships no claim requirements of its own but a sibling method (e.g. GET) is scope-protected. The result is the union of distinct claim requirements across all sibling methods except excludeMethod.

Parameters

Returns

The union of sibling-method claim requirements (possibly empty).

RemoveService(string, string) method

public void RemoveService(string serviceName, string version)

Removes the claims of one version of a service. Called when the last instance of that version disconnects.

Parameters

UpdateFromAuthority(IReadOnlyDictionary<EndpointKey, IReadOnlyList<ClaimRequirement>>) method

public void UpdateFromAuthority(IReadOnlyDictionary<EndpointKey, IReadOnlyList<ClaimRequirement>> overrides)

Updates claims from Authority overrides.

Parameters

UpdateFromMicroservice(string, string, IReadOnlyList<EndpointDescriptor>) method

public void UpdateFromMicroservice(string serviceName, string version, IReadOnlyList<EndpointDescriptor> endpoints)

Updates the claims of one version of a service from its HELLO message; other versions keep theirs.

Parameters

IEffectiveClaimsStore interface

public interface IEffectiveClaimsStore : IEffectiveClaimsStore

The effective claim requirements of the endpoints, with the claims of sibling methods on the same path.

GetSiblingMethodClaims(string, string, string, string) method

IReadOnlyList<ClaimRequirement> GetSiblingMethodClaims(string serviceName, string version, string path, string excludeMethod)

Returns the effective claim requirements registered for sibling HTTP methods on the same service + path template. Used to close asymmetric scope enforcement gaps where a state-changing method (POST/PUT/PATCH/DELETE) ships no claim requirements of its own but a sibling method (e.g. GET) is scope-protected. The result is the union of distinct claim requirements across all sibling methods except excludeMethod.

Parameters

Returns

The union of sibling-method claim requirements (possibly empty).

StellaOps.Router.Gateway.Hosting.Configuration namespace

TypeKindDescription
GatewayHealthOptionsclassWhen a connected instance counts as degraded or stale, how often the gateway checks, and which services readiness requires (Gateway:Health).
GatewayMessagingTransportOptionsclassThe Messaging transport section.
GatewayNodeOptionsclassThe identity of this gateway node (Gateway:Node), copied into the router node configuration.
GatewayOpenApiOptionsclassThe OpenAPI document the gateway generates from the connected microservices (OpenApiAggregationOptions).
GatewayOptionsclassThe Gateway section that the router gateway pipeline reads: node identity, transports, routing, OpenAPI and health.
GatewayOptionsValidatorclassValidates the GatewayOptionsof the router gateway pipeline at startup.
GatewayRabbitMqTransportOptionsclassRabbitMQ consumer for microservices.
GatewayRoutingOptionsclassHow the gateway routes a request (Gateway:Routing).
GatewayTcpTransportOptionsclassTCP listener for microservices (Gateway:Transports:Tcp).
GatewayTlsTransportOptionsclassTLS listener for microservices (Gateway:Transports:Tls).
GatewayTransportOptionsclassThe transport listeners of the gateway (Gateway:Transports).
GatewayUdpTransportOptionsclassUDP listener for microservices.
GatewayValueParserclassParses the duration and size strings of the gateway configuration, for example 30s and 100MB.

GatewayHealthOptions class

public sealed class GatewayHealthOptions

When a connected instance counts as degraded or stale, how often the gateway checks, and which services readiness requires (Gateway:Health). A duration is a TimeSpan string or a number with the unit ms, s, m or h (for example 30s); a number without a unit is seconds. The gateway raises the degraded threshold to at least twice, and the stale threshold to at least three times, the Messaging heartbeat interval.

GatewayHealthOptions() constructor

public GatewayHealthOptions()

Creates an instance of GatewayHealthOptions.

CheckInterval property

public string CheckInterval { get; set; }

How often the gateway checks the instances for missed heartbeats. The default is 5s.

DegradedThreshold property

public string DegradedThreshold { get; set; }

The time without a heartbeat after which an instance is degraded. The default is 15s; with the default Messaging heartbeat interval of 10 seconds, the minimum raises it to 20 seconds.

RequiredMicroservices property

public List<string> RequiredMicroservices { get; set; }

The services that must each have a healthy or degraded instance connected before the gateway reports ready. Empty by default.

ServiceNameSuffixes property

public List<string> ServiceNameSuffixes { get; set; }

Endings removed, each once and in this order, from a required service name and from a connected instance’s service name before readiness compares them (for example a DNS domain such as .example.internal). Empty by default: the names are compared as they are, ignoring case and a :port part.

StaleThreshold property

public string StaleThreshold { get; set; }

The time without a heartbeat after which an instance is stale. The default is 30s.

GatewayMessagingTransportOptions class

public sealed class GatewayMessagingTransportOptions

The Messaging transport section. The messaging backend the host registers for the section binds its own subsection, named after the backend (for example valkey:ConnectionString), and transport names that backend; this class carries the queue settings both sides share.

GatewayMessagingTransportOptions() constructor

public GatewayMessagingTransportOptions()

Creates an instance of GatewayMessagingTransportOptions.

BatchSize property

public int BatchSize { get; set; }

Batch size for leasing messages.

CancelControlApproximateMaxLength property

public int CancelControlApproximateMaxLength { get; set; }

Approximate maximum entries retained by one cancellation control stream.

CancelControlBatchSize property

public int CancelControlBatchSize { get; set; }

Batch size for the independent cancellation-control lane.

CancelControlQueueTemplate property

public string CancelControlQueueTemplate { get; set; }

Per-connection queue template for cancellation control traffic.

CancelTombstoneTtl property

public string CancelTombstoneTtl { get; set; }

Lifetime of cancel-before-request tombstones.

ConsumerGroup property

public string ConsumerGroup { get; set; }

Consumer group name for request processing.

Enabled property

public bool Enabled { get; set; }

Whether the Messaging transport is enabled.

GatewayControlQueueServiceName property

public string GatewayControlQueueServiceName { get; set; }

Reserved queue segment used for gateway control traffic. Must not overlap with a real microservice name.

HeartbeatInterval property

public string HeartbeatInterval { get; set; }

Heartbeat interval.

LeaseDuration property

public string LeaseDuration { get; set; }

Lease duration for message processing.

MaxConcurrentRequests property

public int MaxConcurrentRequests { get; set; }

Maximum request handlers held concurrently by one messaging client.

MaxPendingCancellations property

public int MaxPendingCancellations { get; set; }

Maximum pending cancellation tombstones per messaging client.

RequestQueueTemplate property

public string RequestQueueTemplate { get; set; }

Queue name template for incoming requests. Use {service} placeholder.

RequestTimeout property

public string RequestTimeout { get; set; }

Timeout for RPC requests.

ResponseQueueName property

public string ResponseQueueName { get; set; }

Queue name for gateway responses.

GatewayNodeOptions class

public sealed class GatewayNodeOptions

The identity of this gateway node (Gateway:Node), copied into the router node configuration.

GatewayNodeOptions() constructor

public GatewayNodeOptions()

Creates an instance of GatewayNodeOptions.

Environment property

public string Environment { get; set; }

The environment name of this node, for example prod or staging. The default is dev.

NeighborRegions property

public List<string> NeighborRegions { get; set; }

The regions to fall back to, in order of preference, when no instance of the local region can serve a request.

NodeId property

public string NodeId { get; set; }

The unique identifier of this gateway node, for example gw-eu1-01.

Region property

public string Region { get; set; }

The region this gateway serves. Required; the default is local. With GatewayRoutingOptions.PreferLocalRegionset, instances of this region are preferred.

GatewayOpenApiOptions class

public sealed class GatewayOpenApiOptions

The OpenAPI document the gateway generates from the connected microservices (OpenApiAggregationOptions).

GatewayOpenApiOptions() constructor

public GatewayOpenApiOptions()

Creates an instance of GatewayOpenApiOptions.

CacheTtlSeconds property

public int CacheTtlSeconds { get; set; }

How long the aggregated document is cached, in seconds. The default is 300.

Description property

public string Description { get; set; }

The description of the document.

Enabled property

public bool Enabled { get; set; }

Whether the gateway serves the aggregated OpenAPI document. The default is true.

ServerUrl property

public string ServerUrl { get; set; }

The server URL the document declares. The default is /.

Title property

public string Title { get; set; }

The title of the document. The default is Gateway API.

TokenUrl property

public string? TokenUrl { get; set; }

The OAuth2 token URL of the client-credentials flow the endpoint scopes are obtained from. Unset by default: the document declares the bearer scheme only.

Version property

public string Version { get; set; }

The version of the document. The default is 1.0.0.

GatewayOptions class

public sealed class GatewayOptions

The Gateway section that the router gateway pipeline reads: node identity, transports, routing, OpenAPI and health. The settings only the Stella Ops gateway reads (Auth, HttpClient, HttpsRedirect, Routes) bind into that host’s own options from the same section.

GatewayOptions() constructor

public GatewayOptions()

Creates an instance of GatewayOptions.

SectionName constant

public const string SectionName = "Gateway"

The configuration section the options bind from: Gateway.

Health property

public GatewayHealthOptions Health { get; set; }

When a connected instance counts as degraded or stale, and which services readiness requires.

Node property

public GatewayNodeOptions Node { get; set; }

The identity and region of this gateway node.

OpenApi property

public GatewayOpenApiOptions OpenApi { get; set; }

The OpenAPI document the gateway builds from the connected microservices.

Routing property

public GatewayRoutingOptions Routing { get; set; }

How the gateway routes a request: timeouts, the request body limit and instance selection.

Transports property

public GatewayTransportOptions Transports { get; set; }

The listeners that microservices connect to, one section per transport.

GatewayOptionsValidator class

public static class GatewayOptionsValidator

Validates the GatewayOptionsof the router gateway pipeline at startup. The Stella Ops gateway validates its own settings (route table, HTTPS redirect) separately.

Validate(GatewayOptions) method

public static void Validate(GatewayOptions options)

Validates the options: a node region, a positive port for each enabled listener, a TLS certificate path, a RabbitMQ host and node id when RabbitMQ is enabled, and parseable durations and sizes.

Parameters

Exceptions

GatewayRabbitMqTransportOptions class

public sealed class GatewayRabbitMqTransportOptions

RabbitMQ consumer for microservices. The RabbitMQ transport plugin binds this section into RabbitMqTransportOptions (credentials included). Microservices publish to the gateway’s GatewayRabbitMqTransportOptions.NodeId, so it is required.

GatewayRabbitMqTransportOptions() constructor

public GatewayRabbitMqTransportOptions()

Creates an instance of GatewayRabbitMqTransportOptions.

Enabled property

public bool Enabled { get; set; }

Whether the gateway consumes microservice traffic from RabbitMQ. The default is false.

HostName property

public string HostName { get; set; }

The RabbitMQ broker host name. Required when the transport is enabled; the default is localhost.

NodeId property

public string? NodeId { get; set; }

The gateway node identifier that microservices publish to. Required when the transport is enabled.

Port property

public int Port { get; set; }

The RabbitMQ broker port. The default is 5672.

GatewayRoutingOptions class

public sealed class GatewayRoutingOptions

How the gateway routes a request (Gateway:Routing). A duration is a TimeSpan string or a number with the unit ms, s, m or h (for example 30s); a number without a unit is seconds. A size is a number with the unit b, kb, mb or gb (for example 100MB).

GatewayRoutingOptions() constructor

public GatewayRoutingOptions()

Creates an instance of GatewayRoutingOptions.

AllowDegradedInstances property

public bool AllowDegradedInstances { get; set; }

Whether a request may go to a degraded instance when no healthy instance is available. The default is true.

DefaultTimeout property

public string DefaultTimeout { get; set; }

The default timeout of a routed request. The default is 30s.

GlobalTimeoutCap property

public string GlobalTimeoutCap { get; set; }

Global timeout cap applied after endpoint and route timeout resolution.

MaxRequestBodySize property

public string MaxRequestBodySize { get; set; }

The largest request body the gateway accepts for one call. The default is 100MB.

PreferLocalRegion property

public bool PreferLocalRegion { get; set; }

Whether instances in the gateway’s own region are preferred over neighbor regions. The default is true.

PublishedEndpointRouting property

public bool PublishedEndpointRouting { get; set; }

Reserved for routing by HELLO-published endpoints ahead of the SPA catch-all. The gateway that these packages build does not read this option, so setting it has no effect. The default is false.

GatewayTcpTransportOptions class

public sealed class GatewayTcpTransportOptions

TCP listener for microservices (Gateway:Transports:Tcp).

GatewayTcpTransportOptions() constructor

public GatewayTcpTransportOptions()

Creates an instance of GatewayTcpTransportOptions.

BindAddress property

public string BindAddress { get; set; }

The local address the listener binds to. The default is all IPv4 addresses (0.0.0.0).

Enabled property

public bool Enabled { get; set; }

Whether the gateway listens for microservices over TCP. The default is false.

MaxFrameSize property

public int MaxFrameSize { get; set; }

The largest frame the listener accepts, in bytes. The default is 16 MB.

Port property

public int Port { get; set; }

The port the listener binds to; greater than zero when the transport is enabled. The default is 9100.

ReceiveBufferSize property

public int ReceiveBufferSize { get; set; }

The socket receive buffer size in bytes. The default is 64 KB.

SendBufferSize property

public int SendBufferSize { get; set; }

The socket send buffer size in bytes. The default is 64 KB.

GatewayTlsTransportOptions class

public sealed class GatewayTlsTransportOptions

TLS listener for microservices (Gateway:Transports:Tls). The TLS transport plugin binds this whole section into its own transport options, so the certificate settings carry that type’s names.

GatewayTlsTransportOptions() constructor

public GatewayTlsTransportOptions()

Creates an instance of GatewayTlsTransportOptions.

AllowSelfSigned property

public bool AllowSelfSigned { get; set; }

Whether self-signed certificates are accepted. The default is false; set it for development only.

BindAddress property

public string BindAddress { get; set; }

The local address the listener binds to. The default is all IPv4 addresses (0.0.0.0).

Enabled property

public bool Enabled { get; set; }

Whether the gateway listens for microservices over TLS. The default is false.

MaxFrameSize property

public int MaxFrameSize { get; set; }

The largest frame the listener accepts, in bytes. The default is 16 MB.

Port property

public int Port { get; set; }

The port the listener binds to; greater than zero when the transport is enabled. The default is 9443.

ReceiveBufferSize property

public int ReceiveBufferSize { get; set; }

The socket receive buffer size in bytes. The default is 64 KB.

RequireClientCertificate property

public bool RequireClientCertificate { get; set; }

Whether a microservice must present a client certificate (mutual TLS). The default is false.

SendBufferSize property

public int SendBufferSize { get; set; }

The socket send buffer size in bytes. The default is 64 KB.

ServerCertificateKeyPath property

public string? ServerCertificateKeyPath { get; set; }

The private key file of a PEM server certificate.

ServerCertificatePassword property

public string? ServerCertificatePassword { get; set; }

The password of a PFX server certificate.

ServerCertificatePath property

public string? ServerCertificatePath { get; set; }

The server certificate file, PEM or PFX. Required when the transport is enabled.

GatewayTransportOptions class

public sealed class GatewayTransportOptions

The transport listeners of the gateway (Gateway:Transports). A transport starts only when its Enabled setting is true; the host fails at startup when an enabled transport has no server-side transport plugin loaded.

GatewayTransportOptions() constructor

public GatewayTransportOptions()

Creates an instance of GatewayTransportOptions.

Messaging property

public GatewayMessagingTransportOptions Messaging { get; set; }

The queue-backed Messaging transport, for example over Valkey.

RabbitMq property

public GatewayRabbitMqTransportOptions RabbitMq { get; set; }

The RabbitMQ consumer.

Tcp property

public GatewayTcpTransportOptions Tcp { get; set; }

The TCP listener.

Tls property

public GatewayTlsTransportOptions Tls { get; set; }

The TLS listener.

Udp property

public GatewayUdpTransportOptions Udp { get; set; }

The UDP listener.

GatewayUdpTransportOptions class

public sealed class GatewayUdpTransportOptions

UDP listener for microservices. The UDP transport plugin binds this section into UdpTransportOptions; a HELLO and every response must fit one datagram.

GatewayUdpTransportOptions() constructor

public GatewayUdpTransportOptions()

Creates an instance of GatewayUdpTransportOptions.

BindAddress property

public string BindAddress { get; set; }

The local address the listener binds to. The default is all IPv4 addresses (0.0.0.0).

Enabled property

public bool Enabled { get; set; }

Whether the gateway listens for microservices over UDP. The default is false.

MaxDatagramSize property

public int MaxDatagramSize { get; set; }

The largest datagram in bytes; greater than zero when the transport is enabled. The default is 8192.

Port property

public int Port { get; set; }

The port the listener binds to; greater than zero when the transport is enabled. The default is 5102.

GatewayValueParser class

public static class GatewayValueParser

Parses the duration and size strings of the gateway configuration, for example 30s and 100MB.

ParseDuration(string, TimeSpan) method

public static TimeSpan ParseDuration(string? value, TimeSpan fallback)

Parses a duration: a TimeSpan string, or a number with the unit ms, s, m or h; a number without a unit is seconds.

Parameters

Returns

The duration.

Exceptions

ParseSizeBytes(string, long) method

public static long ParseSizeBytes(string? value, long fallback)

Parses a size: a number with the unit b, kb, mb or gb (1024-based); a number without a unit is bytes.

Parameters

Returns

The size in bytes.

Exceptions

StellaOps.Router.Gateway.Hosting.Endpoints namespace

TypeKindDescription
RouterAdministrationEndpointsclassMaps the router administration endpoints of the gateway.
RouterEndpointInventoryEndpointsclassThe read-only list of the distinct Endpoints registered with this gateway, as the licence monitor counts them (RouterEndpointCount): one entry per method group and path template, with the method tokens, templates and services that register it.
RouterInstancesEndpointsclassExposes the gateway-local instance registry so operators and deployment tooling can discover the live service instances and their effective routing weights without scraping gateway logs.
RoutingWeightEndpointsclassMaps the routing weight endpoints: read and change the weight overrides of service instances.

RouterAdministrationEndpoints class

public static class RouterAdministrationEndpoints

Maps the router administration endpoints of the gateway.

ResyncPath constant

public const string ResyncPath = "/api/v1/gateway/administration/router/resync"

The path of the endpoint that asks connected microservices to replay their endpoint metadata.

RoutePrefix constant

public const string RoutePrefix = "/api/v1/gateway/administration"

The route prefix of the administration endpoints.

MapRouterAdministrationEndpoints(IEndpointRouteBuilder) extension method

public static IEndpointRouteBuilder MapRouterAdministrationEndpoints(this IEndpointRouteBuilder endpoints)

Maps POST RouterAdministrationEndpoints.ResyncPath, which asks one connection, or every connection when the request names none, to replay its endpoint metadata. The endpoint requires the RoutingWeightEndpoints.RouterRoutingWritePolicypolicy and answers 404 when no connection matches.

Parameters

Returns

The same endpoint route builder, for chaining.

RouterEndpointInventoryEndpoints class

public static class RouterEndpointInventoryEndpoints

The read-only list of the distinct Endpoints registered with this gateway, as the licence monitor counts them (RouterEndpointCount): one entry per method group and path template, with the method tokens, templates and services that register it. An operator with several gateways unions their lists to count the Installation’s Endpoints once. Behind the router:routing:read scope, like the instance list. The standalone gateway host maps it.

EndpointsPath constant

public const string EndpointsPath = "/api/v1/router/endpoints"

The path of the list.

MapRouterEndpointInventory(IEndpointRouteBuilder) extension method

public static IEndpointRouteBuilder MapRouterEndpointInventory(this IEndpointRouteBuilder endpoints)

Maps GET RouterEndpointInventoryEndpoints.EndpointsPath.

RouterInstancesEndpoints class

public static class RouterInstancesEndpoints

Exposes the gateway-local instance registry so operators and deployment tooling can discover the live service instances and their effective routing weights without scraping gateway logs.

This is the read-side discovery counterpart to RoutingWeightEndpoints; it reuses the same RoutingWeightEndpoints.RouterRoutingReadPolicy(admin-scoped router:routing:read) authorization gate.

InstancesPath constant

public const string InstancesPath = "/api/v1/router/instances"

The path of the instance list endpoint.

MapRouterInstancesEndpoints(IEndpointRouteBuilder) extension method

public static IEndpointRouteBuilder MapRouterInstancesEndpoints(this IEndpointRouteBuilder endpoints)

Maps GET RouterInstancesEndpoints.InstancesPath, which lists the connected service instances with their version, region, weight and health; the optional service query parameter filters by service. The endpoint requires the RoutingWeightEndpoints.RouterRoutingReadPolicypolicy.

Parameters

Returns

The same endpoint route builder, for chaining.

RoutingWeightEndpoints class

public static class RoutingWeightEndpoints

Maps the routing weight endpoints: read and change the weight overrides of service instances. The overrides are process-local: each gateway node keeps its own.

RouterRoutingReadPolicy constant

public const string RouterRoutingReadPolicy = "router.routing.read"

The authorization policy for reading the routing weights and the instance list.

RouterRoutingReadScope constant

public const string RouterRoutingReadScope = "router:routing:read"

The scope the read policy requires in the scope or scp claim of the router gateway host.

RouterRoutingWritePolicy constant

public const string RouterRoutingWritePolicy = "router.routing.write"

The authorization policy for changing routing weights and for requesting an endpoint metadata replay.

RouterRoutingWriteScope constant

public const string RouterRoutingWriteScope = "router:routing:write"

The scope the write policy requires in the scope or scp claim of the router gateway host.

WeightsPath constant

public const string WeightsPath = "/api/v1/router/routing/weights"

The path of the routing weight endpoints.

MapRoutingWeightEndpoints(IEndpointRouteBuilder) extension method

public static IEndpointRouteBuilder MapRoutingWeightEndpoints(this IEndpointRouteBuilder endpoints)

Maps GET RoutingWeightEndpoints.WeightsPath, which returns the weight overrides and the effective weight of each live instance (RoutingWeightEndpoints.RouterRoutingReadPolicy), and POST, which adds or updates one override for a service version or one of its instances (RoutingWeightEndpoints.RouterRoutingWritePolicy).

Parameters

Returns

The same endpoint route builder, for chaining.

StellaOps.Router.Gateway.Hosting.Licensing namespace

TypeKindDescription
IRouterLicenceReleaseContextinterfaceThe inputs of a licence evaluation that come from the release and the operator, not from the installation’s use: the running version’s first-publication date and the vendor trust roots.
RouterComponentLicenceOptionsclassConfiguration of the component licence reader, section StellaOps:ComponentLicence.
RouterCountedEndpointrecordOne counted Endpoint: a method group and a path template under the comparison rules, with the registrations that make it up.
RouterEndpointCountclassCounts the Endpoints registered with this gateway under the Endpoint definition of the Router licence (clause 1), as far as the gateway can observe them: each distinct combination of a method group and a path template, once, whatever the services, instances or versions that register it.
RouterEndpointMethodGroupenumThe method group of a counted Endpoint (Router licence, clause 1).
RouterLicenceAssessorclassEvaluates the gateway’s licence status: counts the distinct Endpoints registered with the gateway (RouterEndpointCount), reads the licence records offline (the file or directory of StellaOps:ComponentLicence:Path, or the licence key of StellaOps:ComponentLicence:Key) and runs the shared component licence evaluator against the running version’s first-publication date.
RouterLicenceMetricsclassThe licence gauge on the meter RouterLicenceMetrics.MeterName: the Endpoint count of the latest evaluation, tagged with its status name.
RouterLicenceMonitorclassEvaluates the gateway’s licence status once the host has started and then every RouterLicenceMonitor.EvaluationInterval, so the health detail and the gauge follow the Endpoints the microservices register as they connect, and the warning log appears at startup and hourly while the status warrants it (RouterLicenceAssessor).
RouterLicenceReleaseContextclassThe release context of the running gateway: the stamp of the StellaOps.Router.Gateway.Hosting assembly and the roots of ComponentLicenceTrustRoots.FromEnvironment(IEs256Verifier) (the embedded published root, or the set STELLAOPS_VENDOR_TRUST_ROOTS names).
RouterLicenceSnapshotrecordOne licence evaluation of the running gateway, as the health detail and the gauges report it.
RouterLicenceStateclassThe latest licence evaluation of this gateway, read by the health detail and the gauges.

IRouterLicenceReleaseContext interface

public interface IRouterLicenceReleaseContext

The inputs of a licence evaluation that come from the release and the operator, not from the installation’s use: the running version’s first-publication date and the vendor trust roots.

PublishedAt property

DateOnly? PublishedAt { get; }

The StellaOps.Component.PublishedAt stamp of the gateway’s source release; a build or adaptation of a released version keeps it, and its own build date is never used. null in a development build.

ResolveTrustRoots() method

ComponentLicenceTrustRoots ResolveTrustRoots()

The vendor-entitlement roots that licence file signatures are checked against, resolved per evaluation.

RouterComponentLicenceOptions class

public sealed class RouterComponentLicenceOptions

Configuration of the component licence reader, section StellaOps:ComponentLicence. Every value is optional: without a licence record the gateway reports the status of its count, and an invalid value never stops the host (the record is then not loaded, with the reason as a detail). Configure the record as a RouterComponentLicenceOptions.Pathor as a RouterComponentLicenceOptions.Key, not both: with both set, neither is read and the licence details report conflicting_sources.

RouterComponentLicenceOptions() constructor

public RouterComponentLicenceOptions()

Creates an instance of RouterComponentLicenceOptions.

SectionName constant

public const string SectionName = "StellaOps:ComponentLicence"

The configuration section.

InstallationId property

public string? InstallationId { get; set; }

The Installation identifier the licence records name: a lowercase UUID.

Key property

public string? Key { get; set; }

The licence key: the standard base64 encoding of one licence file, as one line. It is read and verified exactly as the file; base64 is an encoding, not a protection.

Path property

public string? Path { get; set; }

A licence file, or a directory whose *.dsse.json files are read. Local path only.

RouterCountedEndpoint record

public sealed record RouterCountedEndpoint

One counted Endpoint: a method group and a path template under the comparison rules, with the registrations that make it up.

Parameters

RouterCountedEndpoint(RouterEndpointMethodGroup, string, string, IReadOnlyList<string>, IReadOnlyList<string>, IReadOnlyList<string>, int) constructor

public RouterCountedEndpoint(RouterEndpointMethodGroup Group, string? Method, string Template, IReadOnlyList<string> RegisteredMethods, IReadOnlyList<string> RegisteredTemplates, IReadOnlyList<string> Services, int Instances)

One counted Endpoint: a method group and a path template under the comparison rules, with the registrations that make it up.

Parameters

Group property

public RouterEndpointMethodGroup Group { get; init; }

The method group.

Instances property

public int Instances { get; init; }

The connected instances that register it.

Method property

public string? Method { get; init; }

The individually counted method; null for the extension and any-method groups.

RegisteredMethods property

public IReadOnlyList<string> RegisteredMethods { get; init; }

The method tokens registered for it, in ordinal order.

RegisteredTemplates property

public IReadOnlyList<string> RegisteredTemplates { get; init; }

The templates registered for it, in ordinal order.

Services property

public IReadOnlyList<string> Services { get; init; }

The services that register it, in ordinal order.

Template property

public string Template { get; init; }

The template in its comparison form: literal text as registered, each parameter reduced to its structure.

RouterEndpointCount class

public static class RouterEndpointCount

Counts the Endpoints registered with this gateway under the Endpoint definition of the Router licence (clause 1), as far as the gateway can observe them: each distinct combination of a method group and a path template, once, whatever the services, instances or versions that register it.

Remarks

Method groups: GET, HEAD, POST, PUT, DELETE, CONNECT, OPTIONS and TRACE count individually (a frozen list); every other token, PATCH included, counts in one extension-method Endpoint per template; every entry that accepts any method (EndpointDescriptor.AnyMethod) counts in one any-method Endpoint per template. The three groups count separately. Method tokens compare case-sensitively, so get is an extension-method token. HEAD and OPTIONS count only where registered; they are not inferred from GET.

Templates: literal text, its letter case and its slashes compare as registered; within a parameter the name, the constraints and a default value itself are disregarded, and the catch-all form (* or **), the optional marker and the presence of a default value are kept. Templates are compared as written and never expanded.

Only what services register is counted: the gateway’s own health, metrics and API-description paths are answered by the gateway and never enter the routing state, so they are excluded by their provenance, and a service’s own route named /health counts. The count is the current set of registrations, not a running total. It is the displayed count, which is not conclusive: the licence counts the Endpoints configured for production routing, including routes the gateway does not see.

IndividuallyCountedMethods field

public static readonly FrozenSet<string> IndividuallyCountedMethods

The individually counted methods (Router licence, clause 1). The list is frozen.

ComparisonTemplate(string) method

public static string ComparisonTemplate(string template)

The comparison form of a path template: literal text unchanged; each parameter reduced to {, its catch-all stars, = when it has a default value, ? when it is optional, and }. So /files/{**path:nonfile} is /files/{**}, /items/{id:int?} is /items/{?} and /items/{itemId} is /items/{}. Doubled braces are literal braces.

Count(IEnumerable<ConnectionState>) method

public static int Count(IEnumerable<ConnectionState> connections)

The number of distinct Endpoints registered by connections.

Inventory(IEnumerable<ConnectionState>) method

public static IReadOnlyList<RouterCountedEndpoint> Inventory(IEnumerable<ConnectionState> connections)

The distinct Endpoints registered by connections, ordered by template, then method group (individual, extension, any), then method.

MethodGroup(string) method

public static (RouterEndpointMethodGroup Group, string? Method) MethodGroup(string method)

The method group of a registered method token, and the method for the individual group.

RouterEndpointMethodGroup enum

public enum RouterEndpointMethodGroup

The method group of a counted Endpoint (Router licence, clause 1).

ValueDescription
Individual = 0One of the individually counted methods: GET, HEAD, POST, PUT, DELETE, CONNECT, OPTIONS, TRACE.
Extension = 1Every other explicitly enabled method token of one template, PATCH included, counted together.
Any = 2Every entry of one template that accepts any method, counted together.

RouterLicenceAssessor class

public sealed class RouterLicenceAssessor

Evaluates the gateway’s licence status: counts the distinct Endpoints registered with the gateway (RouterEndpointCount), reads the licence records offline (the file or directory of StellaOps:ComponentLicence:Path, or the licence key of StellaOps:ComponentLicence:Key) and runs the shared component licence evaluator against the running version’s first-publication date. Informational only: it refuses, slows or stops nothing, makes no network call and sends nothing anywhere; a failure to read the records is reported as a detail, never thrown. Each evaluation also carries the licence notice (“Licensed to” the licensee of a covering record, or the message of its case), logged at startup and once per hour.

RouterLicenceAssessor(IGlobalRoutingState, IOptionsMonitor<RouterComponentLicenceOptions>, IRouterLicenceReleaseContext, RouterLicenceState, TimeProvider, ILogger<RouterLicenceAssessor>) constructor

public RouterLicenceAssessor(IGlobalRoutingState routingState, IOptionsMonitor<RouterComponentLicenceOptions> options, IRouterLicenceReleaseContext releaseContext, RouterLicenceState state, TimeProvider timeProvider, ILogger<RouterLicenceAssessor> logger)

Evaluates the gateway’s licence status: counts the distinct Endpoints registered with the gateway (RouterEndpointCount), reads the licence records offline (the file or directory of StellaOps:ComponentLicence:Path, or the licence key of StellaOps:ComponentLicence:Key) and runs the shared component licence evaluator against the running version’s first-publication date. Informational only: it refuses, slows or stops nothing, makes no network call and sends nothing anywhere; a failure to read the records is reported as a detail, never thrown. Each evaluation also carries the licence notice (“Licensed to” the licensee of a covering record, or the message of its case), logged at startup and once per hour.

NoticeInterval field

public static readonly TimeSpan NoticeInterval

The interval between two notice lines while the notice stays the same.

WarningInterval field

public static readonly TimeSpan WarningInterval

The interval between two warnings while a warning status persists.

EvaluateAsync(CancellationToken) method

public Task<RouterLicenceSnapshot> EvaluateAsync(CancellationToken cancellationToken = default)

Runs one evaluation and publishes it to RouterLicenceState. While the status warns (ComponentLicenceAssessment.Warns: above the notice level without a covering record, or above the free limit without a record that covers the version and the count), a warning is logged on the first evaluation, when the status changes and then once per RouterLicenceAssessor.WarningInterval; any other status is logged at information level on the first evaluation and when it changes. The licence notice is logged at information level before every status line, when it changes, and otherwise once per RouterLicenceAssessor.NoticeInterval, in every status.

RouterLicenceMetrics class

public sealed class RouterLicenceMetrics : IDisposable

The licence gauge on the meter RouterLicenceMetrics.MeterName: the Endpoint count of the latest evaluation, tagged with its status name. It reaches only the metrics pipeline the operator configures, and the gateway’s /metrics text; nothing is sent to the vendor.

RouterLicenceMetrics(RouterLicenceState, IMeterFactory) constructor

public RouterLicenceMetrics(RouterLicenceState state, IMeterFactory? meterFactory = null)

Creates the gauge.

Parameters

EndpointsGauge constant

public const string EndpointsGauge = "stellaops.router.licence.endpoints"

The gauge of the Endpoint count.

MeterName constant

public const string MeterName = "StellaOps.Router.Licence"

The meter name.

StatusTag constant

public const string StatusTag = "licence.status"

The status tag of the gauge.

Meter property

public Meter Meter { get; }

The meter of this instance.

Dispose() method

public void Dispose()

See IDisposable.Dispose().

RouterLicenceMonitor class

public sealed class RouterLicenceMonitor : BackgroundService

Evaluates the gateway’s licence status once the host has started and then every RouterLicenceMonitor.EvaluationInterval, so the health detail and the gauge follow the Endpoints the microservices register as they connect, and the warning log appears at startup and hourly while the status warrants it (RouterLicenceAssessor). It never stops, delays or degrades the gateway: a failed evaluation is logged and retried at the next interval.

RouterLicenceMonitor(RouterLicenceAssessor, RouterLicenceMetrics, TimeProvider, ILogger<RouterLicenceMonitor>, IHostApplicationLifetime) constructor

public RouterLicenceMonitor(RouterLicenceAssessor assessor, RouterLicenceMetrics metrics, TimeProvider timeProvider, ILogger<RouterLicenceMonitor> logger, IHostApplicationLifetime? lifetime = null)

Evaluates the gateway’s licence status once the host has started and then every RouterLicenceMonitor.EvaluationInterval, so the health detail and the gauge follow the Endpoints the microservices register as they connect, and the warning log appears at startup and hourly while the status warrants it (RouterLicenceAssessor). It never stops, delays or degrades the gateway: a failed evaluation is logged and retried at the next interval.

EvaluationInterval field

public static readonly TimeSpan EvaluationInterval

The interval between evaluations.

RouterLicenceReleaseContext class

public sealed class RouterLicenceReleaseContext : IRouterLicenceReleaseContext

The release context of the running gateway: the stamp of the StellaOps.Router.Gateway.Hosting assembly and the roots of ComponentLicenceTrustRoots.FromEnvironment(IEs256Verifier) (the embedded published root, or the set STELLAOPS_VENDOR_TRUST_ROOTS names). Local reads only.

RouterLicenceReleaseContext() constructor

public RouterLicenceReleaseContext()

Reads the stamp of the gateway hosting assembly.

PublishedAt property

public DateOnly? PublishedAt { get; }

The StellaOps.Component.PublishedAt stamp of the gateway’s source release; a build or adaptation of a released version keeps it, and its own build date is never used. null in a development build.

ResolveTrustRoots() method

public ComponentLicenceTrustRoots ResolveTrustRoots()

The vendor-entitlement roots that licence file signatures are checked against, resolved per evaluation.

RouterLicenceSnapshot record

public sealed record RouterLicenceSnapshot

One licence evaluation of the running gateway, as the health detail and the gauges report it.

RouterLicenceSnapshot() constructor

public RouterLicenceSnapshot()

Creates an instance of RouterLicenceSnapshot.

Assessment property

public required ComponentLicenceAssessment Assessment { get; init; }

The component licence evaluator’s result: status, message, counts and details.

InstallationIdConfigured property

public required bool InstallationIdConfigured { get; init; }

Whether an Installation identifier is configured.

LicenceFilesLoaded property

public required int LicenceFilesLoaded { get; init; }

Licence records (files, or the licence key) read and loaded.

LicenceFilesNotLoaded property

public required int LicenceFilesNotLoaded { get; init; }

Licence records read and not loaded (the reasons are in the assessment details).

Notice property

public ComponentLicenceNotice Notice { get; }

The licence notice of this evaluation, built from RouterLicenceSnapshot.Assessment: “Licensed to” the licensee of the record whose entry covers the running version, or the message of the case. The log line and the health detail write it with ComponentLicenceNoticeFormatter.Format(ComponentLicenceNotice).

Sequence property

public required long Sequence { get; init; }

The evaluation number in this process, from 1.

Warns property

public bool Warns { get; }

true while the status is one the monitor warns about (ComponentLicenceAssessment.Warns): every status but within-free-limit and record-matches.

RouterLicenceState class

public sealed class RouterLicenceState

The latest licence evaluation of this gateway, read by the health detail and the gauges. It is registered only with the licence monitor, which RouterGatewayHostExtensions.AddRouterGatewayHost(WebApplicationBuilder, params Assembly[])composes; a host without it (the Stella Ops gateway) reports no licence detail.

RouterLicenceState() constructor

public RouterLicenceState()

Creates an instance of RouterLicenceState.

EndpointCountNote constant

public const string EndpointCountNote = "The displayed count is not conclusive."

The note on the displayed Endpoint count (Router licence, clause 2): the licence counts the Endpoints configured for production routing, including routes the gateway does not see.

EndpointsMetric constant

public const string EndpointsMetric = "stellaops_router_licence_endpoints"

The gauge of the Endpoint count, in the Prometheus text of /metrics.

Current property

public RouterLicenceSnapshot? Current { get; }

The latest evaluation; null before the first one.

StellaOps.Router.Gateway.Hosting.Middleware namespace

TypeKindDescription
GatewayContextKeysclassThe HttpContext.Items keys under which the gateway pipeline keeps the caller’s identity.
GatewayRoutesclassThe paths the gateway answers itself (system paths), which are never routed to a microservice.
HealthCheckMiddlewareclassAnswers the gateway health and metrics paths.
RequestRoutingMiddlewareclassDispatches a routed request to a microservice instance.

GatewayContextKeys class

public static class GatewayContextKeys

The HttpContext.Items keys under which the gateway pipeline keeps the caller’s identity.

Actor constant

public const string Actor = "Gateway.Actor"

The acting user.

CnfJson constant

public const string CnfJson = "Gateway.CnfJson"

The confirmation claim of the caller’s token, as JSON.

DpopThumbprint constant

public const string DpopThumbprint = "Gateway.DpopThumbprint"

The thumbprint of the caller’s DPoP key.

IsAnonymous constant

public const string IsAnonymous = "Gateway.IsAnonymous"

Whether the caller is anonymous.

MtlsThumbprint constant

public const string MtlsThumbprint = "Gateway.MtlsThumbprint"

The thumbprint of the caller’s client certificate.

ProjectId constant

public const string ProjectId = "Gateway.ProjectId"

The project of the caller.

Scopes constant

public const string Scopes = "Gateway.Scopes"

The scopes of the caller, as a set of strings; the authorization middleware reads them.

TenantId constant

public const string TenantId = "Gateway.TenantId"

The tenant of the caller.

GatewayRoutes class

public static class GatewayRoutes

The paths the gateway answers itself (system paths), which are never routed to a microservice.

BuildInfoAggregatorPath constant

public const string BuildInfoAggregatorPath = "/buildinfo.json"

The path of the aggregated build information document.

OpenApiAggregatePath constant

public const string OpenApiAggregatePath = "/api/openapi/aggregate"

The path of the aggregated OpenAPI document.

OperatorVerifyPrefix constant

public const string OperatorVerifyPrefix = "/api/v1/operator/verify"

The path prefix of the operator verification endpoints.

PluginDiagnosticsPrefix constant

public const string PluginDiagnosticsPrefix = "/internal/plugins"

The path prefix of the transport plugin diagnostics.

ProductSecurityJsonPath constant

public const string ProductSecurityJsonPath = "/.well-known/stella-product-security.json"

The path of the product security document.

RouterAdministrationPrefix constant

public const string RouterAdministrationPrefix = "/api/v1/gateway/administration"

The route prefix of the router administration endpoints.

RouterAdministrationResyncPath constant

public const string RouterAdministrationResyncPath = "/api/v1/gateway/administration/router/resync"

The path of the endpoint metadata replay request.

RouterInstancesPath constant

public const string RouterInstancesPath = "/api/v1/router/instances"

The path of the instance list endpoint.

RouterRoutingWeightsPath constant

public const string RouterRoutingWeightsPath = "/api/v1/router/routing/weights"

The path of the routing weight endpoints.

SecurityTxtPath constant

public const string SecurityTxtPath = "/.well-known/security.txt"

The path of the security contact document.

SupportLifecyclePath constant

public const string SupportLifecyclePath = "/api/v1/product/support-lifecycle"

The path of the support lifecycle document.

IsHealthPath(PathString) method

public static bool IsHealthPath(PathString path)

Whether the path is a health path: it starts with /health.

Parameters

Returns

true for a health path.

IsMetricsPath(PathString) method

public static bool IsMetricsPath(PathString path)

Whether the path is /metrics.

Parameters

Returns

true for the metrics path.

IsOperatorVerifyPath(PathString) method

public static bool IsOperatorVerifyPath(PathString path)

Whether the path is an operator verification path.

Parameters

Returns

true for an operator verification path.

IsSystemPath(PathString) method

public static bool IsSystemPath(PathString path)

Whether the gateway answers the path itself and never routes it to a microservice.

Parameters

Returns

true for a system path.

HealthCheckMiddleware class

public sealed class HealthCheckMiddleware

Answers the gateway health and metrics paths.

HealthCheckMiddleware(RequestDelegate) constructor

public HealthCheckMiddleware(RequestDelegate next)

Creates the middleware.

Parameters

InvokeAsync(HttpContext, GatewayServiceStatus, GatewayMetrics, GatewayReadinessEvaluator) method

public Task InvokeAsync(HttpContext context, GatewayServiceStatus status, GatewayMetrics metrics, GatewayReadinessEvaluator readinessEvaluator)

Answers /metrics with the Prometheus text and /health, /health/live, /health/ready and /health/startup with the gateway status; /health/ready answers 503 until the gateway is ready, and /health/startup 503 until it has started. Every other request passes on.

Parameters

Returns

A task that completes when the request is handled.

RequestRoutingMiddleware class

public sealed class RequestRoutingMiddleware

Dispatches a routed request to a microservice instance.

RequestRoutingMiddleware(RequestDelegate, ILogger<RequestRoutingMiddleware>, ILogger<TransportDispatchMiddleware>, IHostEnvironment, IOptions<PayloadLimits>) constructor

public RequestRoutingMiddleware(RequestDelegate next, ILogger<RequestRoutingMiddleware> logger, ILogger<TransportDispatchMiddleware> dispatchLogger, IHostEnvironment environment, IOptions<PayloadLimits> limits)

Creates the middleware.

Parameters

InvokeAsync(HttpContext, ITransportClient, IGlobalRoutingState, IRouterGatewayMetrics) method

public Task InvokeAsync(HttpContext context, ITransportClient transportClient, IGlobalRoutingState routingState, IRouterGatewayMetrics metrics)

Dispatches the request to an instance of the resolved endpoint over its transport and writes the response.

Parameters

Returns

A task that completes when the request is handled.

StellaOps.Router.Gateway.Hosting.Routing namespace

TypeKindDescription
StellaOpsRouteResolverclassResolves a request path to a configured static route.

StellaOpsRouteResolver class

public sealed class StellaOpsRouteResolver

Resolves a request path to a configured static route.

StellaOpsRouteResolver(IEnumerable<StellaOpsRoute>) constructor

public StellaOpsRouteResolver(IEnumerable<StellaOpsRoute> routes)

Creates a resolver over routes, tried in order.

Parameters

FindSpaFallbackRoute() method

public StellaOpsRoute? FindSpaFallbackRoute()

Finds the StaticFiles route configured with x-spa-fallback: true. Used to serve index.html for browser navigation requests that would otherwise be intercepted by ReverseProxy routes.

MatchRoutePattern(StellaOpsRoute, string) method

public Match? MatchRoutePattern(StellaOpsRoute route, string pathValue)

Matches pathValue against the compiled pattern of a regex route this resolver returned from StellaOpsRouteResolver.Resolve(PathString), so a second form of the same request (the raw wire path) can be translated with the same captures. Null for a non-regex route, a route this resolver does not own, or a miss.

Resolve(PathString) method

public (StellaOpsRoute? Route, Match? RegexMatch) Resolve(PathString path)

Returns the first route that matches the path: a regex route by its pattern, any other route by its path or a path below it, ignoring case.

Parameters

Returns

The route and, for a regex route, its match; both null when no route matches.

StellaOps.Router.Gateway.Hosting.Services namespace

TypeKindDescription
GatewayHealthMonitorServiceclassChecks the connected instances at the check interval and marks those without a recent heartbeat degraded or stale.
GatewayHostedServiceclassRuns the gateway transport servers and handles the frames microservices send: HELLO, heartbeats, responses and cancellations.
GatewayMetricsclassThe gateway’s connection and routing-weight gauges, on the meter GatewayMetrics.MeterName, and the Prometheus text of the /metrics endpoint.
GatewayReadinessEvaluatorclassEvaluates GatewayReadinessReport.
GatewayReadinessReportrecordThe gateway’s readiness: started, transports ready, and every service named in Gateway:Health:RequiredMicroservices connected with a healthy or degraded instance.
GatewayRegistrationResyncRequestrecordThe body of an endpoint metadata replay request.
GatewayRegistrationResyncResultrecordThe result of an endpoint metadata replay request.
GatewayRegistrationResyncServiceclassAsks connected microservices to replay their endpoint metadata.
GatewayServiceStatusclassThe started and ready flags of the gateway, which the health endpoints report.
GatewayTransportClientclassSends frames to microservices over the transport of each connection and pairs the responses with the pending requests.
IGatewayHealthContributorinterfaceA section a host adds to the gateway’s health response (/health, /health/live, /health/ready and /health/startup).
IGatewayTransportClientinterfaceSends frames to microservices over the transport of each connection and pairs the responses with the pending requests.

GatewayHealthMonitorService class

public sealed class GatewayHealthMonitorService : BackgroundService

Checks the connected instances at the check interval and marks those without a recent heartbeat degraded or stale.

GatewayHealthMonitorService(IGlobalRoutingState, IOptions<HealthOptions>, ILogger<GatewayHealthMonitorService>) constructor

public GatewayHealthMonitorService(IGlobalRoutingState routingState, IOptions<HealthOptions> options, ILogger<GatewayHealthMonitorService> logger)

Creates the monitor.

Parameters

GatewayHostedService class

public sealed class GatewayHostedService : IHostedService

Runs the gateway transport servers and handles the frames microservices send: HELLO, heartbeats, responses and cancellations.

GatewayHostedService(IGlobalRoutingState, IGatewayTransportClient, GatewayRegistrationResyncService, IEffectiveClaimsStore, IOptions<GatewayOptions>, GatewayServiceStatus, ILogger<GatewayHostedService>, IEnumerable<IGatewayConnectionTransportServer>, IGatewayMessagingTransportServer, IRouterOpenApiDocumentCache) constructor

public GatewayHostedService(IGlobalRoutingState routingState, IGatewayTransportClient transportClient, GatewayRegistrationResyncService registrationResyncService, IEffectiveClaimsStore claimsStore, IOptions<GatewayOptions> options, GatewayServiceStatus status, ILogger<GatewayHostedService> logger, IEnumerable<IGatewayConnectionTransportServer>? connectionTransportServers = null, IGatewayMessagingTransportServer? messagingServer = null, IRouterOpenApiDocumentCache? openApiCache = null)

Creates the service.

Parameters

StartAsync(CancellationToken) method

public Task StartAsync(CancellationToken cancellationToken)

Starts the enabled transport servers and marks the gateway started and ready.

Parameters

Returns

A task that completes when the servers started.

StopAsync(CancellationToken) method

public Task StopAsync(CancellationToken cancellationToken)

Marks the gateway not ready and stops the transport servers.

Parameters

Returns

A task that completes when the servers stopped.

GatewayMetrics class

public sealed class GatewayMetrics

The gateway’s connection and routing-weight gauges, on the meter GatewayMetrics.MeterName, and the Prometheus text of the /metrics endpoint.

GatewayMetrics(IGlobalRoutingState, IRouterGatewayMetrics, IRoutingWeightOverrideStore) constructor

public GatewayMetrics(IGlobalRoutingState routingState, IRouterGatewayMetrics routerMetrics, IRoutingWeightOverrideStore weightOverrides)

Creates the metrics.

Parameters

MeterName constant

public const string MeterName = "StellaOps.Router.Gateway.Hosting"

The name of the meter that carries the gateway gauges.

GetActiveConnections() method

public long GetActiveConnections()

The number of connected instances.

Returns

The number of connections.

GetRegisteredEndpoints() method

public long GetRegisteredEndpoints()

The number of endpoints the connected instances announce.

Returns

The number of endpoints.

ToPrometheusText() method

public string ToPrometheusText()

The Prometheus text exposition of the gateway gauges and request metrics.

Returns

The metrics text.

GatewayReadinessEvaluator class

public sealed class GatewayReadinessEvaluator

Evaluates GatewayReadinessReport. A required name and a connected instance match when their keys are equal, ignoring case: the key is the service name (or the instance identifier without a trailing -<number>) without a :port part and without the endings listed in Gateway:Health:ServiceNameSuffixes, each removed once, in order.

GatewayReadinessEvaluator(IGlobalRoutingState, IOptions<GatewayOptions>) constructor

public GatewayReadinessEvaluator(IGlobalRoutingState routingState, IOptions<GatewayOptions> options)

Creates the evaluator.

Parameters

Evaluate(GatewayServiceStatus) method

public GatewayReadinessReport Evaluate(GatewayServiceStatus status)

Evaluates the readiness of the gateway.

Parameters

Returns

The readiness report.

GatewayReadinessReport record

public sealed record GatewayReadinessReport

The gateway’s readiness: started, transports ready, and every service named in Gateway:Health:RequiredMicroservices connected with a healthy or degraded instance.

GatewayReadinessReport() constructor

public GatewayReadinessReport()

Creates an instance of GatewayReadinessReport.

IsReady property

public required bool IsReady { get; init; }

Whether the gateway is ready: started, transports ready and every required service connected.

MissingMicroservices property

public IReadOnlyList<string> MissingMicroservices { get; init; }

The required services without a healthy or degraded instance.

RequiredMicroservices property

public IReadOnlyList<string> RequiredMicroservices { get; init; }

The services readiness requires.

Started property

public required bool Started { get; init; }

Whether the gateway has started.

TransportReady property

public required bool TransportReady { get; init; }

Whether the transport servers are ready.

GatewayRegistrationResyncRequest record

public sealed record GatewayRegistrationResyncRequest

The body of an endpoint metadata replay request.

Parameters

GatewayRegistrationResyncRequest(string, string) constructor

public GatewayRegistrationResyncRequest(string? ConnectionId, string? Reason)

The body of an endpoint metadata replay request.

Parameters

ConnectionId property

public string? ConnectionId { get; init; }

The connection to replay; every connection when not set.

Reason property

public string? Reason { get; init; }

Why the replay is requested; administration-request when not set.

GatewayRegistrationResyncResult record

public sealed record GatewayRegistrationResyncResult

The result of an endpoint metadata replay request.

GatewayRegistrationResyncResult() constructor

public GatewayRegistrationResyncResult()

Creates an instance of GatewayRegistrationResyncResult.

ConnectionId property

public string? ConnectionId { get; init; }

The requested connection; not set when every connection was asked.

MatchedCount property

public int MatchedCount { get; init; }

The connections the request matched.

Reason property

public required string Reason { get; init; }

Why the replay was requested.

RequestedCount property

public int RequestedCount { get; init; }

The connections asked to replay their endpoints.

SkippedCount property

public int SkippedCount { get; init; }

The connections skipped because they were asked less than 15 seconds before, without force.

GatewayRegistrationResyncService class

public sealed class GatewayRegistrationResyncService

Asks connected microservices to replay their endpoint metadata.

GatewayRegistrationResyncService(IGlobalRoutingState, IGatewayTransportClient, TimeProvider, ILogger<GatewayRegistrationResyncService>) constructor

public GatewayRegistrationResyncService(IGlobalRoutingState routingState, IGatewayTransportClient transportClient, TimeProvider timeProvider, ILogger<GatewayRegistrationResyncService> logger)

Creates the service.

Parameters

ClearPending(string) method

public void ClearPending(string connectionId)

Forgets when a connection was last asked, so it can be asked again at once.

Parameters

RequestResyncAsync(string, string, bool, CancellationToken) method

public Task<GatewayRegistrationResyncResult> RequestResyncAsync(string? connectionId, string reason, bool force, CancellationToken cancellationToken)

Asks one connection, or every connection when connectionId is not set, to replay its endpoint metadata. Without force, a connection asked less than 15 seconds before is skipped.

Parameters

Returns

How many connections matched, were asked and were skipped.

GatewayServiceStatus class

public sealed class GatewayServiceStatus

The started and ready flags of the gateway, which the health endpoints report.

GatewayServiceStatus() constructor

public GatewayServiceStatus()

Creates an instance of GatewayServiceStatus.

IsReady property

public bool IsReady { get; }

Whether the gateway is ready to route requests.

IsStarted property

public bool IsStarted { get; }

Whether the gateway has started.

MarkNotReady() method

public void MarkNotReady()

Marks the gateway not ready, for example while it stops.

MarkReady() method

public void MarkReady()

Marks the gateway ready.

MarkStarted() method

public void MarkStarted()

Marks the gateway started.

GatewayTransportClient class

public sealed class GatewayTransportClient : IGatewayTransportClient

Sends frames to microservices over the transport of each connection and pairs the responses with the pending requests.

GatewayTransportClient(ILogger<GatewayTransportClient>, IEnumerable<IGatewayConnectionTransportServer>, IGatewayMessagingTransportServer) constructor

public GatewayTransportClient(ILogger<GatewayTransportClient> logger, IEnumerable<IGatewayConnectionTransportServer>? connectionTransportServers = null, IGatewayMessagingTransportServer? messagingServer = null)

Creates the client over the transport servers the gateway runs.

Parameters

HandleResponseFrame(Frame) method

public void HandleResponseFrame(Frame frame)

Completes the pending request that a response frame answers, by its correlation id.

Parameters

SendCancelAsync(ConnectionState, Guid, string) method

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

Sends a cancellation request.

Parameters

SendFrameAsync(ConnectionState, Frame, CancellationToken) method

public Task SendFrameAsync(ConnectionState connection, Frame frame, CancellationToken cancellationToken)

Sends a frame to the microservice of a connection, without waiting for a response.

Parameters

Returns

A task that completes when the frame is sent.

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 the request body in one request frame and hands the microservice’s response head and body to readResponse (TransportStreamingDispatch.SendBufferedAsync(ITransportClient, ConnectionState, Frame, Stream, Func<ResponseFrame, Stream, Task>, PayloadLimits, CancellationToken)). The Microservice SDK answers a request with one response frame and does not assemble request stream-data frames, so the request is not sent in chunks.

IGatewayHealthContributor interface

public interface IGatewayHealthContributor

A section a host adds to the gateway’s health response (/health, /health/live, /health/ready and /health/startup). Each registered contributor adds one property after missingMicroservices, in registration order. A section is informational: the status code of the response never depends on it.

Name property

string Name { get; }

The property name of the section in the health response. It must be unique among the contributors and must not be one of the response’s own properties (status, started, ready, transportReady, requiredMicroservices, missingMicroservices, traceId, licence).

Describe() method

object Describe()

The value of the section, written with the response’s JSON options (camel-case property names). Called for every health request.

IGatewayTransportClient interface

public interface IGatewayTransportClient : ITransportClient

Sends frames to microservices over the transport of each connection and pairs the responses with the pending requests.

HandleResponseFrame(Frame) method

void HandleResponseFrame(Frame frame)

Completes the pending request that a response frame answers, by its correlation id.

Parameters

SendFrameAsync(ConnectionState, Frame, CancellationToken) method

Task SendFrameAsync(ConnectionState connection, Frame frame, CancellationToken cancellationToken)

Sends a frame to the microservice of a connection, without waiting for a response.

Parameters

Returns

A task that completes when the frame is sent.