StellaOps.Router.Gateway

Router gateway core: the routing state of connected microservices, request routing and dispatch, and gateway rate limiting.

PackageStellaOps.Router.Gateway
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.Gateway2
StellaOps.Router.Gateway.Authorization8
StellaOps.Router.Gateway.Configuration6
StellaOps.Router.Gateway.DependencyInjection1
StellaOps.Router.Gateway.Metrics5
StellaOps.Router.Gateway.Middleware17
StellaOps.Router.Gateway.OpenApi8
StellaOps.Router.Gateway.RateLimit21
StellaOps.Router.Gateway.Services10

StellaOps.Router.Gateway namespace

TypeKindDescription
ApplicationBuilderExtensionsclassExtension methods for configuring the router gateway middleware pipeline.
RouterHttpContextKeysclassWell-known HttpContext.Items keys for router pipeline.

ApplicationBuilderExtensions class

public static class ApplicationBuilderExtensions

Extension methods for configuring the router gateway middleware pipeline.

MapRouterOpenApi(IEndpointRouteBuilder) extension method

public static IEndpointRouteBuilder MapRouterOpenApi(this IEndpointRouteBuilder endpoints)

Maps OpenAPI endpoints to the application. Should be called before UseRouterGateway so OpenAPI requests are handled first.

Parameters

Returns

The endpoint route builder for chaining.

UseRateLimiting(IApplicationBuilder) extension method

public static IApplicationBuilder UseRateLimiting(this IApplicationBuilder app)

Adds rate limiting middleware to the pipeline.

Parameters

Returns

The application builder for chaining.

UseRouterGateway(IApplicationBuilder) extension method

public static IApplicationBuilder UseRouterGateway(this IApplicationBuilder app)

Adds the router gateway middleware pipeline.

Parameters

Returns

The application builder for chaining.

UseRouterGatewayCore(IApplicationBuilder) extension method

public static IApplicationBuilder UseRouterGatewayCore(this IApplicationBuilder app)

Adds the router gateway middleware pipeline without payload limiting.

Parameters

Returns

The application builder for chaining.

RouterHttpContextKeys class

public static class RouterHttpContextKeys

Well-known HttpContext.Items keys for router pipeline.

EndpointDescriptor constant

public const string EndpointDescriptor = "Stella.EndpointDescriptor"

Key for the resolved EndpointDescriptor.

PathParameters constant

public const string PathParameters = "Stella.PathParameters"

Key for path parameters extracted from route template matching.

PreResolvedEndpoint constant

public const string PreResolvedEndpoint = "Stella.Router.PreResolvedEndpoint"

Request-local resolution retained by SPA diversion.

RawRequestTarget constant

public const string RawRequestTarget = "Stella.RawRequestTarget"

Key for the raw request target (IHttpRequestFeature.RawTarget: path plus query string with the wire percent-encoding intact) after Gateway route translation. Set only when a translation applied alongside RouterHttpContextKeys.TranslatedRequestPath; an untranslated request forwards the wire target verbatim without this key.

RouteDefaultTimeout constant

public const string RouteDefaultTimeout = "Stella.RouteDefaultTimeout"

Key for the route-level default timeout (TimeSpan) resolved from Gateway route table.

RouteTargetMicroservice constant

public const string RouteTargetMicroservice = "Stella.RouteTargetMicroservice"

Key for the route-level target microservice hint inferred from the gateway route entry.

RoutingDecision constant

public const string RoutingDecision = "Stella.RoutingDecision"

Key for the RoutingDecision.

TargetEndpointPathTemplate constant

public const string TargetEndpointPathTemplate = "Stella.TargetEndpointPathTemplate"

Key for the resolved endpoint path template (EndpointDescriptor.Path).

TargetMicroservice constant

public const string TargetMicroservice = "Stella.TargetMicroservice"

Key for the resolved target microservice name (ServiceName).

TranslatedRequestPath constant

public const string TranslatedRequestPath = "Stella.TranslatedRequestPath"

Key for the translated request path resolved from Gateway route translation.

StellaOps.Router.Gateway.Authorization namespace

TypeKindDescription
AuthorityConnectionOptionsclassConfiguration options for connecting to the Authority service.
AuthorizationMiddlewareclassMiddleware that enforces claims requirements for endpoints.
AuthorizationMiddlewareExtensionsclassExtension methods for registering the authorization middleware.
AuthorizationServiceCollectionExtensionsclassExtension methods for registering Authority integration services.
ClaimsOverrideChangedEventArgsclassEvent arguments for claims override changes.
EndpointKeystructKey for identifying an endpoint by service name, method, and path.
IAuthorityClaimsProviderinterfaceProvides claims overrides from the central Authority service.
IEffectiveClaimsStoreinterfaceStores and retrieves effective claims for endpoints.

AuthorityConnectionOptions class

public sealed class AuthorityConnectionOptions

Configuration options for connecting to the Authority service.

AuthorityConnectionOptions() constructor

public AuthorityConnectionOptions()

Creates an instance of AuthorityConnectionOptions.

HttpClientName constant

public const string HttpClientName = "StellaOps.Router.Gateway.AuthorityClaims"

Name of the HttpClient the claims-overrides provider uses. A host that must authenticate the refresh (Authority requires authority:claims-overrides.read on GET /api/v1/claims/overrides) attaches its token handler to this name.

SectionName constant

public const string SectionName = "Router:Authority"

Configuration section name.

AuthorityUrl property

public string AuthorityUrl { get; set; }

Gets or sets the Authority service URL.

Enabled property

public bool Enabled { get; set; }

Gets or sets whether Authority integration is enabled.

RefreshInterval property

public TimeSpan RefreshInterval { get; set; }

Gets or sets the interval at which to refresh claims from Authority.

StartupTimeout property

public TimeSpan StartupTimeout { get; set; }

Gets or sets the startup timeout when waiting for Authority.

UseAuthorityPushNotifications property

public bool UseAuthorityPushNotifications { get; set; }

Gets or sets whether to use push notifications from Authority. If false, the gateway will poll at the refresh interval.

WaitForAuthorityOnStartup property

public bool WaitForAuthorityOnStartup { get; set; }

Gets or sets whether to wait for Authority on startup. If true, the gateway will delay handling traffic until Authority is available.

AuthorizationMiddleware class

public sealed class AuthorizationMiddleware

Middleware that enforces claims requirements for endpoints.

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

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

Initializes a new instance of the AuthorizationMiddlewareclass.

InvokeAsync(HttpContext) method

public Task InvokeAsync(HttpContext context)

Invokes the middleware.

AuthorizationMiddlewareExtensions class

public static class AuthorizationMiddlewareExtensions

Extension methods for registering the authorization middleware.

UseClaimsAuthorization(IApplicationBuilder) extension method

public static IApplicationBuilder UseClaimsAuthorization(this IApplicationBuilder app)

Adds the claims authorization middleware to the pipeline.

Parameters

Returns

The application builder for chaining.

AuthorizationServiceCollectionExtensions class

public static class AuthorizationServiceCollectionExtensions

Extension methods for registering Authority integration services.

AddAuthorityIntegration(IServiceCollection, Action<AuthorityConnectionOptions>) extension method

public static IServiceCollection AddAuthorityIntegration(this IServiceCollection services, Action<AuthorityConnectionOptions>? configure = null)

Adds Authority integration services with custom options.

Parameters

Returns

The service collection for chaining.

AddAuthorityIntegration(IServiceCollection, IConfiguration) extension method

public static IServiceCollection AddAuthorityIntegration(this IServiceCollection services, IConfiguration configuration)

Adds Authority integration services to the service collection.

Parameters

Returns

The service collection for chaining.

AddNoOpAuthorityIntegration(IServiceCollection) extension method

public static IServiceCollection AddNoOpAuthorityIntegration(this IServiceCollection services)

Adds a no-op Authority integration (no external Authority). Claims are only from microservices.

Parameters

Returns

The service collection for chaining.

ClaimsOverrideChangedEventArgs class

public sealed class ClaimsOverrideChangedEventArgs : EventArgs

Event arguments for claims override changes.

ClaimsOverrideChangedEventArgs() constructor

public ClaimsOverrideChangedEventArgs()

Creates an instance of ClaimsOverrideChangedEventArgs.

Overrides property

public IReadOnlyDictionary<EndpointKey, IReadOnlyList<ClaimRequirement>> Overrides { get; init; }

Gets the updated claims overrides.

EndpointKey struct

public readonly struct EndpointKey : IEquatable<EndpointKey>

Key for identifying an endpoint by service name, method, and path.

Parameters

EndpointKey(string, string, string) constructor

public EndpointKey(string ServiceName, string Method, string Path)

Key for identifying an endpoint by service name, method, and path.

Parameters

Method property

public string Method { get; init; }

The HTTP method.

Path property

public string Path { get; init; }

The path template.

ServiceName property

public string ServiceName { get; init; }

The name of the service.

Create(string, string, string) method

public static EndpointKey Create(string serviceName, string method, string path)

Creates an endpoint key with normalized values.

ToString() method

public override string ToString()

See ValueType.ToString().

IAuthorityClaimsProvider interface

public interface IAuthorityClaimsProvider

Provides claims overrides from the central Authority service.

IsAvailable property

bool IsAvailable { get; }

Gets a value indicating whether the Authority is currently available.

OverridesChanged event

event EventHandler<ClaimsOverrideChangedEventArgs>? OverridesChanged

Occurs when claims overrides change.

GetOverridesAsync(CancellationToken) method

Task<IReadOnlyDictionary<EndpointKey, IReadOnlyList<ClaimRequirement>>> GetOverridesAsync(CancellationToken cancellationToken)

Gets all claims overrides from Authority.

Parameters

Returns

A dictionary of endpoint keys to claim requirements.

IEffectiveClaimsStore interface

public interface IEffectiveClaimsStore

Stores and retrieves effective claims for endpoints. Handles merging of microservice defaults with Authority overrides.

GetEffectiveClaims(string, string, string, string) method

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.

RemoveService(string, string) method

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

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

Updates claims from Authority overrides.

Parameters

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

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

StellaOps.Router.Gateway.Configuration namespace

TypeKindDescription
HealthOptionsclassConfiguration options for health monitoring.
RouterNodeConfigclassStatic configuration for a router gateway node.
RoutingOptionsclassOptions for routing behavior.
StellaOpsRouteclassA static route of the gateway: a path and what the gateway does with the requests that match it.
StellaOpsRouteTypeenumWhat a static route does with a matching request.
TieBreakerModeenumTie-breaker mode for routing when multiple instances have equal priority.

HealthOptions class

public sealed class HealthOptions

Configuration options for health monitoring.

HealthOptions() constructor

public HealthOptions()

Creates an instance of HealthOptions.

SectionName constant

public const string SectionName = "Router:Health"

Gets the configuration section name.

CheckInterval property

public TimeSpan CheckInterval { get; set; }

Gets or sets the interval at which to check for stale connections. Default: 15 seconds.

DegradedThreshold property

public TimeSpan DegradedThreshold { get; set; }

Gets or sets the threshold after which a connection is considered degraded. Should be at least 2x the service heartbeat interval (the SDK default is 10 seconds). Default: 90 seconds.

PingHistorySize property

public int PingHistorySize { get; set; }

Gets or sets the number of ping measurements to keep for averaging. Default: 10.

StaleThreshold property

public TimeSpan StaleThreshold { get; set; }

Gets or sets the threshold after which a connection is considered stale (no heartbeat). Should be at least 3x the service heartbeat interval (the SDK default is 10 seconds). Default: 135 seconds.

RouterNodeConfig class

public sealed class RouterNodeConfig

Static configuration for a router gateway node.

RouterNodeConfig() constructor

public RouterNodeConfig()

Creates an instance of RouterNodeConfig.

LegacySectionName constant

public const string LegacySectionName = "Router:Node"

The alternative configuration section name, read only when the RouterNodeConfig.SectionNamesection does not exist.

SectionName constant

public const string SectionName = "GatewayNode"

Configuration section name for binding.

Environment property

public string Environment { get; set; }

Gets or sets the environment name (e.g., “prod”, “staging”, “dev”).

NeighborRegions property

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

Gets or sets the neighbor regions for fallback routing, in order of preference.

NodeId property

public string NodeId { get; set; }

Gets or sets the unique identifier for this gateway node (e.g., “gw-eu1-01”).

Region property

public string Region { get; set; }

Gets or sets the region where this gateway is deployed (e.g., “eu1”). Routing decisions use this value; it is never derived from headers or URLs.

Validate() method

public void Validate()

Validates the configuration.

Exceptions

RoutingOptions class

public sealed class RoutingOptions

Options for routing behavior.

RoutingOptions() constructor

public RoutingOptions()

Creates an instance of RoutingOptions.

SectionName constant

public const string SectionName = "Router:Routing"

Configuration section name for binding.

AllowDegradedInstances property

public bool AllowDegradedInstances { get; set; }

Gets or sets whether to allow routing to degraded instances when no healthy instances are available.

DefaultVersion property

public string? DefaultVersion { get; set; }

Gets or sets the default version to use when no version is specified in the request. If null, requests without version specification will match any available version.

GlobalTimeoutCapMs property

public int GlobalTimeoutCapMs { get; set; }

Gets or sets the global timeout cap in milliseconds. Effective request timeout cannot exceed this value.

MaxWeightOverride property

public int MaxWeightOverride { get; set; }

Gets or sets the maximum accepted runtime routing weight override.

PingToleranceMs property

public double PingToleranceMs { get; set; }

Gets or sets the ping tolerance in milliseconds for considering instances “tied”. Instances within this tolerance of each other are considered to have equal latency.

PreferLocalRegion property

public bool PreferLocalRegion { get; set; }

Gets or sets whether to prefer local region instances over neighbor regions.

RoutingTimeoutMs property

public int RoutingTimeoutMs { get; set; }

Gets or sets the gateway route default timeout in milliseconds.

TieBreaker property

public TieBreakerMode TieBreaker { get; set; }

Gets or sets the tie-breaker mode when multiple instances have equal priority.

WeightOverrides property

public Dictionary<string, int> WeightOverrides { get; set; }

Gets or sets gateway-side routing weight overrides. Keys are service/version/instanceId for one instance, or service/version for a version-wide override.

StellaOpsRoute class

public sealed class StellaOpsRoute

A static route of the gateway: a path and what the gateway does with the requests that match it.

StellaOpsRoute() constructor

public StellaOpsRoute()

Creates an instance of StellaOpsRoute.

DefaultTimeout property

public string? DefaultTimeout { get; set; }

Optional route-level default timeout (for example “15s”, “2m”). Applied when endpoint metadata does not provide a timeout.

Headers property

public Dictionary<string, string> Headers { get; set; }

Headers added to the forwarded request.

IsRegex property

public bool IsRegex { get; set; }

Whether StellaOpsRoute.Pathis a regular expression.

Path property

public string Path { get; set; }

The path the route matches: a path and the paths below it, or a regular expression when StellaOpsRoute.IsRegexis set.

PreserveAuthHeaders property

public bool PreserveAuthHeaders { get; set; }

When true, the gateway preserves Authorization and DPoP headers instead of stripping them. Use for upstream services that perform their own JWT validation.

TranslatesTo property

public string? TranslatesTo { get; set; }

The target: an HTTP or HTTPS URL for a proxy route, a ws or wss URL for a WebSocket route, a directory for a static files route, and a file for a static file route or an error page.

Type property

public StellaOpsRouteType Type { get; set; }

What the route does with a matching request.

StellaOpsRouteType enum

public enum StellaOpsRouteType

What a static route does with a matching request.

ValueDescription
Microservice = 0The request goes to a microservice through the Router.
ReverseProxy = 1The request is proxied to the StellaOpsRoute.TranslatesToaddress.
StaticFiles = 2The request is served from a directory of static files.
StaticFile = 3The request is served with one static file.
WebSocket = 4The request is a WebSocket proxied to the StellaOpsRoute.TranslatesToaddress.
NotFoundPage = 5The page served for a request that no route matches.
ServerErrorPage = 6The page served for a server error.

TieBreakerMode enum

public enum TieBreakerMode

Tie-breaker mode for routing when multiple instances have equal priority.

ValueDescription
Random = 0Select randomly among tied instances.
RoundRobin = 1Rotate through tied instances in order.

StellaOps.Router.Gateway.DependencyInjection namespace

TypeKindDescription
RouterServiceCollectionExtensionsclassExtension methods for registering router gateway services.

RouterServiceCollectionExtensions class

public static class RouterServiceCollectionExtensions

Extension methods for registering router gateway services.

AddRouterGateway(IServiceCollection, Action<RouterNodeConfig>, Action<RoutingOptions>) extension method

public static IServiceCollection AddRouterGateway(this IServiceCollection services, Action<RouterNodeConfig>? configureNode = null, Action<RoutingOptions>? configureRouting = null)

Adds router gateway services with custom options.

Parameters

Returns

The service collection for chaining.

AddRouterGateway(IServiceCollection, IConfiguration) extension method

public static IServiceCollection AddRouterGateway(this IServiceCollection services, IConfiguration configuration)

Adds router gateway services to the service collection.

Parameters

Returns

The service collection for chaining.

AddRouterGatewayCore(IServiceCollection) extension method

public static IServiceCollection AddRouterGatewayCore(this IServiceCollection services)

Adds router gateway services with minimal defaults.

Parameters

Returns

The service collection for chaining.

AddRouterGatewayLocalHarness(IServiceCollection, IHostEnvironment) extension method

public static IServiceCollection AddRouterGatewayLocalHarness(this IServiceCollection services, IHostEnvironment environment)

Adds the gateway lifecycle services required by an explicit process-local transport harness.

Parameters

Returns

The service collection for chaining.

Exceptions

StellaOps.Router.Gateway.Metrics namespace

TypeKindDescription
IRouterGatewayMetricsinterfaceRecords the routed requests and returns their counts and durations.
RouterGatewayMetricsclassRecords the routed requests on the meter RouterGatewayMetrics.MeterNameand keeps their totals for the Prometheus text of the gateway.
RouterRequestDurationBucketrecordOne cumulative histogram bucket.
RouterRequestDurationMetricSamplerecordThe duration histogram of the requests of one service version and instance.
RouterRequestMetricSamplerecordThe number of requests of one service version and instance with one status class.

IRouterGatewayMetrics interface

public interface IRouterGatewayMetrics

Records the routed requests and returns their counts and durations.

GetRequestDurations() method

IReadOnlyList<RouterRequestDurationMetricSample> GetRequestDurations()

Returns the request duration histograms so far, by service, version and instance.

Returns

The duration histograms.

GetRequestTotals() method

IReadOnlyList<RouterRequestMetricSample> GetRequestTotals()

Returns the request counts so far, by service, version, instance and status class.

Returns

The request counts.

RecordRequest(RoutingDecision, int, TimeSpan) method

void RecordRequest(RoutingDecision decision, int statusCode, TimeSpan duration)

Records one routed request.

Parameters

RouterGatewayMetrics class

public sealed class RouterGatewayMetrics : IRouterGatewayMetrics, IDisposable

Records the routed requests on the meter RouterGatewayMetrics.MeterNameand keeps their totals for the Prometheus text of the gateway.

RouterGatewayMetrics() constructor

public RouterGatewayMetrics()

Creates an instance of RouterGatewayMetrics.

MeterName constant

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

The name of the meter that carries the request counter and the duration histogram.

Dispose() method

public void Dispose()

Disposes the meter.

GetRequestDurations() method

public IReadOnlyList<RouterRequestDurationMetricSample> GetRequestDurations()

Returns the request duration histograms so far, by service, version and instance.

Returns

The duration histograms.

GetRequestTotals() method

public IReadOnlyList<RouterRequestMetricSample> GetRequestTotals()

Returns the request counts so far, by service, version, instance and status class.

Returns

The request counts.

RecordRequest(RoutingDecision, int, TimeSpan) method

public void RecordRequest(RoutingDecision decision, int statusCode, TimeSpan duration)

Records one routed request.

Parameters

RouterRequestDurationBucket record

public sealed record RouterRequestDurationBucket

One cumulative histogram bucket.

Parameters

RouterRequestDurationBucket(string, long) constructor

public RouterRequestDurationBucket(string UpperBound, long Count)

One cumulative histogram bucket.

Parameters

Count property

public long Count { get; init; }

The requests at most that long.

UpperBound property

public string UpperBound { get; init; }

The upper bound of the bucket, in seconds.

RouterRequestDurationMetricSample record

public sealed record RouterRequestDurationMetricSample

The duration histogram of the requests of one service version and instance.

Parameters

RouterRequestDurationMetricSample(string, string, string, IReadOnlyList<RouterRequestDurationBucket>, long, double) constructor

public RouterRequestDurationMetricSample(string Service, string Version, string InstanceId, IReadOnlyList<RouterRequestDurationBucket> Buckets, long Count, double SumSeconds)

The duration histogram of the requests of one service version and instance.

Parameters

Buckets property

public IReadOnlyList<RouterRequestDurationBucket> Buckets { get; init; }

The cumulative bucket counts.

Count property

public long Count { get; init; }

The number of requests.

InstanceId property

public string InstanceId { get; init; }

The instance.

Service property

public string Service { get; init; }

The service.

SumSeconds property

public double SumSeconds { get; init; }

The sum of the request durations, in seconds.

Version property

public string Version { get; init; }

The service version.

RouterRequestMetricSample record

public sealed record RouterRequestMetricSample

The number of requests of one service version and instance with one status class.

Parameters

RouterRequestMetricSample(string, string, string, string, long) constructor

public RouterRequestMetricSample(string Service, string Version, string InstanceId, string StatusClass, long Count)

The number of requests of one service version and instance with one status class.

Parameters

Count property

public long Count { get; init; }

The number of requests.

InstanceId property

public string InstanceId { get; init; }

The instance.

Service property

public string Service { get; init; }

The service.

StatusClass property

public string StatusClass { get; init; }

The status class, for example 2xx.

Version property

public string Version { get; init; }

The service version.

StellaOps.Router.Gateway.Middleware namespace

TypeKindDescription
AttestationCheckResultrecordResult of an attestation check.
AttestationMiddlewareclassMiddleware that checks for attestations on artifact requests.
AttestationMiddlewareExtensionsclassExtension methods for attestation middleware.
AttestationMiddlewareOptionsclassConfiguration for attestation middleware.
ByteCountingStreamclassA stream wrapper that counts bytes read and enforces a limit.
DefaultAttestationLookupServiceclassDefault implementation of attestation lookup service.
EndpointResolutionMiddlewareclassResolves incoming HTTP requests to endpoint descriptors using the routing state.
GlobalErrorHandlerMiddlewareclassCatches unhandled exceptions and returns a structured JSON error response.
IAttestationLookupServiceinterfaceService for looking up attestations.
IPayloadTrackerinterfaceTracks payload bytes across requests, connections, and globally.
PayloadLimitExceededExceptionclassException thrown when a payload limit is exceeded during streaming.
PayloadLimitsMiddlewareclassMiddleware that enforces payload limits per-request, per-connection, and aggregate.
PayloadTrackerclassDefault implementation of IPayloadTracker.
RequestLoggingMiddlewareclassLogs basic request/response information for gateway requests.
RouterErrorWriterclassThe gateway’s single writer for error responses.
RoutingDecisionMiddlewareclassMakes routing decisions for resolved endpoints.
TransportDispatchMiddlewareclassDispatches HTTP requests to microservices via the transport layer.

AttestationCheckResult record

public sealed record AttestationCheckResult

Result of an attestation check.

AttestationCheckResult() constructor

public AttestationCheckResult()

Creates an instance of AttestationCheckResult.

AllPresent property

public bool AllPresent { get; init; }

Whether all required attestations are present.

CheckedAt property

public DateTimeOffset CheckedAt { get; init; }

Timestamp of the check.

Digest property

public required string Digest { get; init; }

Artifact digest that was checked.

MissingTypes property

public List<string> MissingTypes { get; init; }

List of missing attestation types.

PresentTypes property

public List<string> PresentTypes { get; init; }

List of present attestation types.

RekorLogIndex property

public long? RekorLogIndex { get; init; }

Rekor log index if verified.

AttestationMiddleware class

public sealed class AttestationMiddleware

Middleware that checks for attestations on artifact requests.

AttestationMiddleware(RequestDelegate, IAttestationLookupService, IMemoryCache, IOptions<AttestationMiddlewareOptions>, ILogger<AttestationMiddleware>) constructor

public AttestationMiddleware(RequestDelegate next, IAttestationLookupService lookupService, IMemoryCache cache, IOptions<AttestationMiddlewareOptions> options, ILogger<AttestationMiddleware> logger)

Creates the middleware.

Parameters

InvokeAsync(HttpContext) method

public Task InvokeAsync(HttpContext context)

Checks the required attestations of an artifact request; a request whose artifact misses one can be refused with 403, depending on the options.

Parameters

Returns

A task that completes when the request is handled.

AttestationMiddlewareExtensions class

public static class AttestationMiddlewareExtensions

Extension methods for attestation middleware.

UseAttestationMiddleware(IApplicationBuilder) extension method

public static IApplicationBuilder UseAttestationMiddleware(this IApplicationBuilder app)

Adds attestation middleware to the pipeline.

AttestationMiddlewareOptions class

public sealed class AttestationMiddlewareOptions

Configuration for attestation middleware.

AttestationMiddlewareOptions() constructor

public AttestationMiddlewareOptions()

Creates an instance of AttestationMiddlewareOptions.

CacheResults property

public bool CacheResults { get; set; }

Whether to cache attestation check results.

CacheTtlSeconds property

public int CacheTtlSeconds { get; set; }

Cache TTL in seconds.

Enabled property

public bool Enabled { get; set; }

Whether attestation checking is enabled.

Mode property

public string Mode { get; set; }

Operation mode: “audit” (log only) or “enforce” (block if missing).

RekorUrl property

public string? RekorUrl { get; set; }

Rekor URL for transparency log verification.

RequireTypes property

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

Required attestation types (e.g., “sbom”, “vex”).

SkipPaths property

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

Skip attestation check for these paths (regex patterns).

ByteCountingStream class

public sealed class ByteCountingStream : Stream

A stream wrapper that counts bytes read and enforces a limit.

ByteCountingStream(Stream, long, Action) constructor

public ByteCountingStream(Stream inner, long limit, Action? onLimitExceeded = null)

Initializes a new instance of the ByteCountingStreamclass.

Parameters

BytesRead property

public long BytesRead { get; }

Gets the total number of bytes read from this stream.

CanRead property

public override bool CanRead { get; }

See Stream.CanRead.

CanSeek property

public override bool CanSeek { get; }

See Stream.CanSeek.

CanWrite property

public override bool CanWrite { get; }

See Stream.CanWrite.

Length property

public override long Length { get; }

See Stream.Length.

Position property

public override long Position { get; set; }

See Stream.Position.

DisposeAsync() method

public override ValueTask DisposeAsync()

See Stream.DisposeAsync().

Flush() method

public override void Flush()

See Stream.Flush().

FlushAsync(CancellationToken) method

public override Task FlushAsync(CancellationToken cancellationToken)

See Stream.FlushAsync(CancellationToken).

Read(byte[], int, int) method

public override int Read(byte[] buffer, int offset, int count)

See Stream.Read(byte[], int, int).

ReadAsync(Memory<byte>, CancellationToken) method

public override ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default)

See Stream.ReadAsync(Memory<byte>, CancellationToken).

ReadAsync(byte[], int, int, CancellationToken) method

public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)

See Stream.ReadAsync(byte[], int, int, CancellationToken).

Seek(long, SeekOrigin) method

public override long Seek(long offset, SeekOrigin origin)

See Stream.Seek(long, SeekOrigin).

SetLength(long) method

public override void SetLength(long value)

See Stream.SetLength(long).

Write(byte[], int, int) method

public override void Write(byte[] buffer, int offset, int count)

See Stream.Write(byte[], int, int).

DefaultAttestationLookupService class

public sealed class DefaultAttestationLookupService : IAttestationLookupService

Default implementation of attestation lookup service.

DefaultAttestationLookupService(ILogger<DefaultAttestationLookupService>, HttpClient, string) constructor

public DefaultAttestationLookupService(ILogger<DefaultAttestationLookupService> logger, HttpClient? httpClient = null, string? attestorUrl = null)

Creates the lookup service.

Parameters

CheckAttestationsAsync(string, IEnumerable<string>, CancellationToken) method

public Task<AttestationCheckResult> CheckAttestationsAsync(string digest, IEnumerable<string> requiredTypes, CancellationToken ct = default)

Looks up attestations for an artifact digest.

EndpointResolutionMiddleware class

public sealed class EndpointResolutionMiddleware

Resolves incoming HTTP requests to endpoint descriptors using the routing state.

EndpointResolutionMiddleware(RequestDelegate, IOptions<RoutingOptions>) constructor

public EndpointResolutionMiddleware(RequestDelegate next, IOptions<RoutingOptions>? routingOptions = null)

Initializes a new instance of the EndpointResolutionMiddlewareclass.

Parameters

Invoke(HttpContext, IGlobalRoutingState) method

public Task Invoke(HttpContext context, IGlobalRoutingState routingState)

Invokes the middleware.

GlobalErrorHandlerMiddleware class

public sealed class GlobalErrorHandlerMiddleware

Catches unhandled exceptions and returns a structured JSON error response.

GlobalErrorHandlerMiddleware(RequestDelegate, ILogger<GlobalErrorHandlerMiddleware>, IHostEnvironment) constructor

public GlobalErrorHandlerMiddleware(RequestDelegate next, ILogger<GlobalErrorHandlerMiddleware> logger, IHostEnvironment environment)

Creates the middleware.

Parameters

Invoke(HttpContext) method

public Task Invoke(HttpContext context)

Runs the rest of the pipeline and answers an unhandled exception with a 500 problem response.

Parameters

Returns

A task that completes when the request is handled.

IAttestationLookupService interface

public interface IAttestationLookupService

Service for looking up attestations.

CheckAttestationsAsync(string, IEnumerable<string>, CancellationToken) method

Task<AttestationCheckResult> CheckAttestationsAsync(string digest, IEnumerable<string> requiredTypes, CancellationToken ct = default)

Looks up attestations for an artifact digest.

IPayloadTracker interface

public interface IPayloadTracker

Tracks payload bytes across requests, connections, and globally.

CurrentInflightBytes property

long CurrentInflightBytes { get; }

Gets the current total inflight bytes across all connections.

IsOverloaded property

bool IsOverloaded { get; }

Gets a value indicating whether the system is overloaded.

GetConnectionInflightBytes(string) method

long GetConnectionInflightBytes(string connectionId)

Gets the current inflight bytes for a specific connection.

Parameters

Returns

The current inflight bytes for the connection.

Release(string, long) method

void Release(string connectionId, long actualBytes)

Releases previously reserved capacity.

Parameters

TryReserve(string, long) method

bool TryReserve(string connectionId, long estimatedBytes)

Tries to reserve capacity for an estimated payload size.

Parameters

Returns

True if capacity was reserved; false if limits would be exceeded.

PayloadLimitExceededException class

public sealed class PayloadLimitExceededException : Exception

Exception thrown when a payload limit is exceeded during streaming.

PayloadLimitExceededException(long, long) constructor

public PayloadLimitExceededException(long bytesRead, long limit)

Initializes a new instance of the PayloadLimitExceededExceptionclass.

Parameters

BytesRead property

public long BytesRead { get; }

Gets the number of bytes read before the limit was exceeded.

Limit property

public long Limit { get; }

Gets the limit that was exceeded.

PayloadLimitsMiddleware class

public sealed class PayloadLimitsMiddleware

Middleware that enforces payload limits per-request, per-connection, and aggregate.

PayloadLimitsMiddleware(RequestDelegate, IOptions<PayloadLimits>, ILogger<PayloadLimitsMiddleware>) constructor

public PayloadLimitsMiddleware(RequestDelegate next, IOptions<PayloadLimits> limits, ILogger<PayloadLimitsMiddleware> logger)

Initializes a new instance of the PayloadLimitsMiddlewareclass.

Invoke(HttpContext, IPayloadTracker) method

public Task Invoke(HttpContext context, IPayloadTracker tracker)

Invokes the middleware.

PayloadTracker class

public sealed class PayloadTracker : IPayloadTracker

Default implementation of IPayloadTracker.

PayloadTracker(IOptions<PayloadLimits>, ILogger<PayloadTracker>) constructor

public PayloadTracker(IOptions<PayloadLimits> limits, ILogger<PayloadTracker> logger)

Initializes a new instance of the PayloadTrackerclass.

CurrentInflightBytes property

public long CurrentInflightBytes { get; }

Gets the current total inflight bytes across all connections.

IsOverloaded property

public bool IsOverloaded { get; }

Gets a value indicating whether the system is overloaded.

GetConnectionInflightBytes(string) method

public long GetConnectionInflightBytes(string connectionId)

Gets the current inflight bytes for a specific connection.

Parameters

Returns

The current inflight bytes for the connection.

Release(string, long) method

public void Release(string connectionId, long actualBytes)

Releases previously reserved capacity.

Parameters

TryReserve(string, long) method

public bool TryReserve(string connectionId, long estimatedBytes)

Tries to reserve capacity for an estimated payload size.

Parameters

Returns

True if capacity was reserved; false if limits would be exceeded.

RequestLoggingMiddleware class

public sealed class RequestLoggingMiddleware

Logs basic request/response information for gateway requests.

RequestLoggingMiddleware(RequestDelegate, ILogger<RequestLoggingMiddleware>) constructor

public RequestLoggingMiddleware(RequestDelegate next, ILogger<RequestLoggingMiddleware> logger)

Creates the middleware.

Parameters

Invoke(HttpContext) method

public Task Invoke(HttpContext context)

Runs the rest of the pipeline and logs the request with its status and duration.

Parameters

Returns

A task that completes when the request is handled.

RouterErrorWriter class

public static class RouterErrorWriter

The gateway’s single writer for error responses. Public so the gateway host’s own middlewares (for example break-glass introspection) refuse with the same RFC 7807 envelope as the routing pipeline instead of an ad hoc JSON body.

WriteAsync(HttpContext, int, string, string, string, string, IReadOnlyDictionary<string, object>, CancellationToken) method

public static Task WriteAsync(HttpContext context, int statusCode, string error, string? message = null, string? service = null, string? version = null, IReadOnlyDictionary<string, object?>? details = null, CancellationToken cancellationToken = default)

Writes an RFC 7807 problem response, unless the response has started.

Parameters

Returns

A task that completes when the response is written.

RoutingDecisionMiddleware class

public sealed class RoutingDecisionMiddleware

Makes routing decisions for resolved endpoints.

RoutingDecisionMiddleware(RequestDelegate) constructor

public RoutingDecisionMiddleware(RequestDelegate next)

Initializes a new instance of the RoutingDecisionMiddlewareclass.

Invoke(HttpContext, IRoutingPlugin, IGlobalRoutingState, IOptions<RouterNodeConfig>, IOptions<RoutingOptions>) method

public Task Invoke(HttpContext context, IRoutingPlugin routingPlugin, IGlobalRoutingState routingState, IOptions<RouterNodeConfig> gatewayConfig, IOptions<RoutingOptions> routingOptions)

Invokes the middleware.

TransportDispatchMiddleware class

public sealed class TransportDispatchMiddleware

Dispatches HTTP requests to microservices via the transport layer.

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

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

Initializes a new instance of the TransportDispatchMiddlewareclass.

Parameters

Invoke(HttpContext, ITransportClient, IGlobalRoutingState, IRouterGatewayMetrics) method

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

Invokes the middleware.

StellaOps.Router.Gateway.OpenApi namespace

TypeKindDescription
GatewayRouteCatalogclassProvides the configured gateway route table for OpenAPI path projection.
IOpenApiDocumentGeneratorinterfaceGenerates OpenAPI documents from aggregated microservice schemas.
IRouterOpenApiDocumentCacheinterfaceCaches the generated OpenAPI document with TTL-based expiration.
OpenApiAggregationOptionsclassConfiguration options for OpenAPI document aggregation.
OpenApiDocumentGeneratorclassGenerates OpenAPI 3.1.0 documents from aggregated microservice schemas.
OpenApiEndpointsclassEndpoints for serving OpenAPI documentation.
OpenApiYamlclassWrites an OpenAPI document given as JSON as YAML.
RouterOpenApiDocumentCacheclassCaches the generated OpenAPI document with TTL-based expiration.

GatewayRouteCatalog class

public sealed class GatewayRouteCatalog

Provides the configured gateway route table for OpenAPI path projection.

GatewayRouteCatalog(IEnumerable<StellaOpsRoute>) constructor

public GatewayRouteCatalog(IEnumerable<StellaOpsRoute> routes)

Initializes a new instance of the GatewayRouteCatalogclass.

Parameters

Routes property

public IReadOnlyList<StellaOpsRoute> Routes { get; }

Gets the configured gateway routes.

IOpenApiDocumentGenerator interface

public interface IOpenApiDocumentGenerator

Generates OpenAPI documents from aggregated microservice schemas.

GenerateDocument() method

string GenerateDocument()

Generates the OpenAPI 3.1.0 document as JSON.

Returns

The OpenAPI document as a JSON string.

IRouterOpenApiDocumentCache interface

public interface IRouterOpenApiDocumentCache

Caches the generated OpenAPI document with TTL-based expiration.

GetDocument() method

(string DocumentJson, string ETag, DateTime GeneratedAt) GetDocument()

Gets the cached document or regenerates if expired.

Returns

A tuple containing the document JSON, ETag, and generation timestamp.

Invalidate() method

void Invalidate()

Invalidates the cache, forcing regeneration on next access.

OpenApiAggregationOptions class

public sealed class OpenApiAggregationOptions

Configuration options for OpenAPI document aggregation.

OpenApiAggregationOptions() constructor

public OpenApiAggregationOptions()

Creates an instance of OpenApiAggregationOptions.

SectionName constant

public const string SectionName = "Router:OpenApi"

The configuration section name.

CacheTtlSeconds property

public int CacheTtlSeconds { get; set; }

Gets or sets the cache TTL in seconds.

ContactEmail property

public string? ContactEmail { get; set; }

Gets or sets the contact email.

ContactName property

public string? ContactName { get; set; }

Gets or sets the contact name.

Description property

public string Description { get; set; }

Gets or sets the API description.

Enabled property

public bool Enabled { get; set; }

Gets or sets whether OpenAPI aggregation is enabled.

LicenseName property

public string? LicenseName { get; set; }

Gets or sets the license name of the API the document describes (info.license.name). Unset by default, so the document states no license.

ServerUrl property

public string ServerUrl { get; set; }

Gets or sets the server URL.

Title property

public string Title { get; set; }

Gets or sets the API title.

TokenUrl property

public string? TokenUrl { get; set; }

Gets or sets the OAuth2 token URL of the client-credentials flow that the scopes of the endpoints are obtained from. Unset by default: the document then declares the bearer scheme only, and lists no OAuth2 scheme or scopes in the operations’ security requirements.

Version property

public string Version { get; set; }

Gets or sets the API version.

OpenApiDocumentGenerator class

public sealed class OpenApiDocumentGenerator : IOpenApiDocumentGenerator

Generates OpenAPI 3.1.0 documents from aggregated microservice schemas.

OpenApiDocumentGenerator(IGlobalRoutingState, IOptions<OpenApiAggregationOptions>, GatewayRouteCatalog, IOptions<RoutingOptions>, IEffectiveClaimsStore) constructor

public OpenApiDocumentGenerator(IGlobalRoutingState routingState, IOptions<OpenApiAggregationOptions> options, GatewayRouteCatalog? routeCatalog = null, IOptions<RoutingOptions>? routingOptions = null, IEffectiveClaimsStore? effectiveClaimsStore = null)

Creates the generator.

Parameters

GenerateDocument() method

public string GenerateDocument()

Generates the OpenAPI 3.1.0 document as JSON.

Returns

The OpenAPI document as a JSON string.

OpenApiEndpoints class

public static class OpenApiEndpoints

Endpoints for serving OpenAPI documentation.

MapRouterOpenApiEndpoints(IEndpointRouteBuilder) extension method

public static IEndpointRouteBuilder MapRouterOpenApiEndpoints(this IEndpointRouteBuilder endpoints)

Maps OpenAPI endpoints to the application.

OpenApiYaml class

public static class OpenApiYaml

Writes an OpenAPI document given as JSON as YAML. Every JSON object becomes a mapping, every array a sequence and every scalar (string, number, boolean, null) a YAML scalar of the same value; a string that YAML would read as another type is quoted. Both gateway hosts serve /openapi.yaml with it.

FromJson(JsonNode) method

public static string FromJson(JsonNode? document)

Converts a parsed OpenAPI document to YAML; an empty string for null.

Parameters

Returns

The document as YAML.

FromJson(string) method

public static string FromJson(string documentJson)

Converts the JSON text of an OpenAPI document to YAML; an empty string for a JSON null.

Parameters

Returns

The document as YAML.

RouterOpenApiDocumentCache class

public sealed class RouterOpenApiDocumentCache : IRouterOpenApiDocumentCache

Caches the generated OpenAPI document with TTL-based expiration.

RouterOpenApiDocumentCache(IOpenApiDocumentGenerator, IOptions<OpenApiAggregationOptions>) constructor

public RouterOpenApiDocumentCache(IOpenApiDocumentGenerator generator, IOptions<OpenApiAggregationOptions> options)

Creates the cache.

Parameters

GetDocument() method

public (string DocumentJson, string ETag, DateTime GeneratedAt) GetDocument()

Gets the cached document or regenerates if expired.

Returns

A tuple containing the document JSON, ETag, and generation timestamp.

Invalidate() method

public void Invalidate()

Invalidates the cache, forcing regeneration on next access.

StellaOps.Router.Gateway.RateLimit namespace

TypeKindDescription
CircuitBreakerclassCircuit breaker for Valkey operations.
CircuitBreakerConfigclassCircuit breaker configuration for Valkey resilience.
CircuitStateenumCircuit breaker state.
EnvironmentLimitsConfigclassEnvironment-level rate limit configuration (Valkey-backed).
EnvironmentRateLimiterclassValkey-backed rate limiter for environment-level protection.
IValkeyRateLimitStoreinterfaceInterface for Valkey rate limit store operations.
InMemoryValkeyRateLimitStoreclassIn-memory fixed-window rate limit store (primarily for tests).
InstanceLimitsConfigclassInstance-level rate limit configuration (in-memory).
InstanceRateLimiterclassIn-memory rate limiter for instance-level protection.
MicroserviceLimitsConfigclassPer-microservice rate limit overrides.
RateLimitConfigclassRoot configuration for Router rate limiting.
RateLimitDecisionrecordResult of a rate limit check.
RateLimitMetricsclassOpenTelemetry metrics for Router rate limiting.
RateLimitMiddlewareclassMiddleware that enforces rate limits on incoming requests.
RateLimitRuleclassA single rate limit rule (window + max requests).
RateLimitScopeenumRate limit scope.
RateLimitServiceclassService that orchestrates rate limit checks across instance and environment scopes.
RateLimitServiceCollectionExtensionsclassExtension methods for registering rate limiting services.
RateLimitStoreResultrecordResult of a Valkey rate limit check.
RouteLimitsConfigclassPer-route rate limit configuration.
RouteMatchTypeenumHow a route rate limit pattern matches a request path.

CircuitBreaker class

public sealed class CircuitBreaker

Circuit breaker for Valkey operations. Provides fail-open behavior when Valkey is unavailable.

CircuitBreaker(int, int, int) constructor

public CircuitBreaker(int failureThreshold, int timeoutSeconds, int halfOpenTimeout)

Creates a closed circuit breaker.

Parameters

IsHalfOpen property

public bool IsHalfOpen { get; }

Whether the circuit is half-open (testing recovery).

IsOpen property

public bool IsOpen { get; }

Whether the circuit is open (requests should bypass Valkey).

State property

public CircuitState State { get; }

Current state of the circuit.

RecordFailure() method

public void RecordFailure()

Record a failed operation.

RecordSuccess() method

public void RecordSuccess()

Record a successful operation.

Reset() method

public void Reset()

Reset the circuit breaker.

CircuitBreakerConfig class

public sealed class CircuitBreakerConfig

Circuit breaker configuration for Valkey resilience.

CircuitBreakerConfig() constructor

public CircuitBreakerConfig()

Creates an instance of CircuitBreakerConfig.

FailureThreshold property

public int FailureThreshold { get; set; }

Number of failures before opening the circuit.

HalfOpenTimeout property

public int HalfOpenTimeout { get; set; }

Seconds in half-open state before full reset.

TimeoutSeconds property

public int TimeoutSeconds { get; set; }

Seconds to keep circuit open.

Validate(string) method

public void Validate(string path)

Validate configuration.

CircuitState enum

public enum CircuitState

Circuit breaker state.

ValueDescription
Closed = 0Circuit is closed, requests flow through.
Open = 1Circuit is open, requests are blocked.
HalfOpen = 2Circuit is testing recovery.

EnvironmentLimitsConfig class

public sealed class EnvironmentLimitsConfig

Environment-level rate limit configuration (Valkey-backed).

EnvironmentLimitsConfig() constructor

public EnvironmentLimitsConfig()

Creates an instance of EnvironmentLimitsConfig.

AllowBurstForSeconds property

public int AllowBurstForSeconds { get; set; }

Burst window in seconds.

AllowMaxBurstRequests property

public int AllowMaxBurstRequests { get; set; }

Maximum burst requests.

CircuitBreaker property

public CircuitBreakerConfig? CircuitBreaker { get; set; }

Circuit breaker configuration.

MaxRequests property

public int MaxRequests { get; set; }

Maximum requests in the time window.

Microservices property

public Dictionary<string, MicroserviceLimitsConfig>? Microservices { get; set; }

Per-microservice overrides.

PerSeconds property

public int PerSeconds { get; set; }

Time window in seconds.

Rules property

public List<RateLimitRule> Rules { get; set; }

Multi-rule configuration (preferred). When specified, takes precedence over the single-window fields.

ValkeyBucket property

public string ValkeyBucket { get; set; }

Valkey bucket/prefix for rate limit keys.

ValkeyConnection property

public string ValkeyConnection { get; set; }

Valkey connection string.

GetEffectiveRules() method

public IReadOnlyList<RateLimitRule> GetEffectiveRules()

The rules in effect: rules when it has any; otherwise a long rule from per_seconds and max_requests and a burst rule from the burst settings, each when both values are set.

Returns

The rules in effect.

Validate(string) method

public void Validate(string path)

Validate configuration.

EnvironmentRateLimiter class

public sealed class EnvironmentRateLimiter : IDisposable

Valkey-backed rate limiter for environment-level protection. Uses fixed-window counters with atomic Lua operations.

EnvironmentRateLimiter(IValkeyRateLimitStore, CircuitBreaker, ILogger<EnvironmentRateLimiter>) constructor

public EnvironmentRateLimiter(IValkeyRateLimitStore store, CircuitBreaker circuitBreaker, ILogger<EnvironmentRateLimiter> logger)

Creates the limiter.

Parameters

Dispose() method

public void Dispose()

Releases the limiter.

TryAcquireAsync(string, string, IReadOnlyList<RateLimitRule>, CancellationToken) method

public Task<RateLimitDecision?> TryAcquireAsync(string microservice, string targetKey, IReadOnlyList<RateLimitRule> rules, CancellationToken cancellationToken)

Try to acquire a request slot. Returns null if circuit breaker is open (fail-open behavior).

IValkeyRateLimitStore interface

public interface IValkeyRateLimitStore

Interface for Valkey rate limit store operations.

IncrementAndCheckAsync(string, IReadOnlyList<RateLimitRule>, CancellationToken) method

Task<RateLimitStoreResult> IncrementAndCheckAsync(string key, IReadOnlyList<RateLimitRule> rules, CancellationToken cancellationToken)

Atomically increment counters for the provided rules and determine if the request is allowed.

InMemoryValkeyRateLimitStore class

public sealed class InMemoryValkeyRateLimitStore : IValkeyRateLimitStore

In-memory fixed-window rate limit store (primarily for tests).

InMemoryValkeyRateLimitStore() constructor

public InMemoryValkeyRateLimitStore()

Creates an instance of InMemoryValkeyRateLimitStore.

IncrementAndCheckAsync(string, IReadOnlyList<RateLimitRule>, CancellationToken) method

public Task<RateLimitStoreResult> IncrementAndCheckAsync(string key, IReadOnlyList<RateLimitRule> rules, CancellationToken cancellationToken)

Atomically increment counters for the provided rules and determine if the request is allowed.

Reset() method

public void Reset()

Clears every counter.

InstanceLimitsConfig class

public sealed class InstanceLimitsConfig

Instance-level rate limit configuration (in-memory).

InstanceLimitsConfig() constructor

public InstanceLimitsConfig()

Creates an instance of InstanceLimitsConfig.

AllowBurstForSeconds property

public int AllowBurstForSeconds { get; set; }

Burst window in seconds.

AllowMaxBurstRequests property

public int AllowMaxBurstRequests { get; set; }

Maximum burst requests.

MaxRequests property

public int MaxRequests { get; set; }

Maximum requests in the time window.

PerSeconds property

public int PerSeconds { get; set; }

Time window in seconds.

Rules property

public List<RateLimitRule> Rules { get; set; }

Multi-rule configuration (preferred). When specified, takes precedence over the single-window fields.

GetEffectiveRules() method

public IReadOnlyList<RateLimitRule> GetEffectiveRules()

The rules in effect: rules when it has any; otherwise a long rule from per_seconds and max_requests and a burst rule from the burst settings, each when both values are set.

Returns

The rules in effect.

Validate(string) method

public void Validate(string path)

Validate configuration.

InstanceRateLimiter class

public sealed class InstanceRateLimiter : IDisposable

In-memory rate limiter for instance-level protection. Uses sliding window counters for fair rate limiting.

InstanceRateLimiter(IReadOnlyList<RateLimitRule>, TimeProvider) constructor

public InstanceRateLimiter(IReadOnlyList<RateLimitRule> defaultRules, TimeProvider? timeProvider = null)

Create instance rate limiter with default limits.

Dispose() method

public void Dispose()

Releases the limiter.

GetCurrentCount(string) method

public long GetCurrentCount(string microservice)

Get current request count for a microservice.

Reset() method

public void Reset()

Reset counters (for testing).

TryAcquire(string, IReadOnlyList<RateLimitRule>) method

public RateLimitDecision TryAcquire(string microservice, IReadOnlyList<RateLimitRule>? rules = null)

Try to acquire a request slot.

Parameters

Returns

Decision indicating whether request is allowed.

MicroserviceLimitsConfig class

public sealed class MicroserviceLimitsConfig

Per-microservice rate limit overrides.

MicroserviceLimitsConfig() constructor

public MicroserviceLimitsConfig()

Creates an instance of MicroserviceLimitsConfig.

AllowBurstForSeconds property

public int? AllowBurstForSeconds { get; set; }

Burst window in seconds (optional).

AllowMaxBurstRequests property

public int? AllowMaxBurstRequests { get; set; }

Maximum burst requests (optional).

MaxRequests property

public int? MaxRequests { get; set; }

Maximum requests in the time window.

PerSeconds property

public int? PerSeconds { get; set; }

Time window in seconds.

Routes property

public Dictionary<string, RouteLimitsConfig> Routes { get; set; }

Per-route overrides (best match wins).

Rules property

public List<RateLimitRule> Rules { get; set; }

Multi-rule configuration (preferred). When specified, takes precedence over the single-window fields.

GetEffectiveRules() method

public IReadOnlyList<RateLimitRule> GetEffectiveRules()

The rules in effect: rules when it has any; otherwise a long rule from per_seconds and max_requests and a burst rule from the burst settings, each when both values are set.

Returns

The rules in effect.

Validate(string) method

public void Validate(string path)

Validate configuration.

RateLimitConfig class

public sealed class RateLimitConfig

Root configuration for Router rate limiting.

RateLimitConfig() constructor

public RateLimitConfig()

Creates an instance of RateLimitConfig.

ActivationThresholdPer5Min property

public int ActivationThresholdPer5Min { get; set; }

Activation gate: only check Valkey when traffic exceeds this threshold per 5 minutes. Set to 0 to always check Valkey. Default: 5000.

ForEnvironment property

public EnvironmentLimitsConfig? ForEnvironment { get; set; }

Environment-level rate limits (Valkey-backed, across all router instances).

ForInstance property

public InstanceLimitsConfig? ForInstance { get; set; }

Instance-level rate limits (in-memory, per router instance).

IsEnabled property

public bool IsEnabled { get; }

Whether rate limiting is enabled (at least one scope configured).

Load(IConfiguration) method

public static RateLimitConfig Load(IConfiguration configuration)

Load configuration from IConfiguration.

Validate() method

public RateLimitConfig Validate()

Validate configuration values.

RateLimitDecision record

public sealed record RateLimitDecision

Result of a rate limit check.

Parameters

RateLimitDecision(bool, int, RateLimitScope, long, long, int, string) constructor

public RateLimitDecision(bool Allowed, int RetryAfterSeconds, RateLimitScope Scope, long CurrentCount, long Limit, int WindowSeconds, string? Microservice = null)

Result of a rate limit check.

Parameters

Allowed property

public bool Allowed { get; init; }

Whether the request is allowed.

CurrentCount property

public long CurrentCount { get; init; }

Current request count in the window.

Limit property

public long Limit { get; init; }

The limit that was applied.

Microservice property

public string? Microservice { get; init; }

The microservice that was checked.

RetryAfterSeconds property

public int RetryAfterSeconds { get; init; }

Seconds to wait before retrying (if not allowed).

RetryAt property

public DateTimeOffset RetryAt { get; }

Time remaining until the window resets.

Scope property

public RateLimitScope Scope { get; init; }

Which scope triggered the limit (instance or environment).

WindowSeconds property

public int WindowSeconds { get; init; }

The window size in seconds.

Allow(RateLimitScope, long, long, int, string) method

public static RateLimitDecision Allow(RateLimitScope scope, long currentCount, long limit, int windowSeconds, string? microservice = null)

Create an “allowed” decision.

Deny(RateLimitScope, int, long, long, int, string) method

public static RateLimitDecision Deny(RateLimitScope scope, int retryAfterSeconds, long currentCount, long limit, int windowSeconds, string? microservice = null)

Create a “denied” decision.

RateLimitMetrics class

public static class RateLimitMetrics

OpenTelemetry metrics for Router rate limiting.

MeasureLatency(RateLimitScope) method

public static IDisposable MeasureLatency(RateLimitScope scope)

Measure check latency with a disposable scope.

RecordCircuitBreakerTrip(string) method

public static void RecordCircuitBreakerTrip(string reason)

Record a circuit breaker trip.

RecordDecision(RateLimitScope, string, bool) method

public static void RecordDecision(RateLimitScope scope, string microservice, bool allowed)

Record a rate limit decision.

RecordDecision(RateLimitScope, string, string, bool) method

public static void RecordDecision(RateLimitScope scope, string microservice, string? routeName, bool allowed)

Record a rate limit decision with optional route tag.

RecordLatency(RateLimitScope, double) method

public static void RecordLatency(RateLimitScope scope, double milliseconds)

Record check latency.

RecordRejection(RateLimitScope, string) method

public static void RecordRejection(RateLimitScope scope, string microservice)

Record a rate limit rejection.

RecordValkeyError(string) method

public static void RecordValkeyError(string errorType)

Record a Valkey error.

UpdateEnvironmentCount(long) method

public static void UpdateEnvironmentCount(long count)

Update current environment count gauge.

UpdateInstanceCount(long) method

public static void UpdateInstanceCount(long count)

Update current instance count gauge.

RateLimitMiddleware class

public sealed class RateLimitMiddleware

Middleware that enforces rate limits on incoming requests. Returns 429 Too Many Requests with Retry-After header when limits are exceeded.

RateLimitMiddleware(RequestDelegate, RateLimitService, ILogger<RateLimitMiddleware>) constructor

public RateLimitMiddleware(RequestDelegate next, RateLimitService rateLimitService, ILogger<RateLimitMiddleware> logger)

Creates the middleware.

Parameters

InvokeAsync(HttpContext) method

public Task InvokeAsync(HttpContext context)

Checks the rate limits of the request and answers 429 when a limit is exceeded.

Parameters

Returns

A task that completes when the request is handled.

RateLimitRule class

public sealed class RateLimitRule

A single rate limit rule (window + max requests).

RateLimitRule() constructor

public RateLimitRule()

Creates an instance of RateLimitRule.

MaxRequests property

public int MaxRequests { get; set; }

The requests allowed in the window; positive (max_requests).

Name property

public string? Name { get; set; }

The rule name, for diagnostics (name).

PerSeconds property

public int PerSeconds { get; set; }

The window, in seconds; positive (per_seconds).

Validate(string) method

public void Validate(string path)

Validates the rule.

Parameters

Exceptions

RateLimitScope enum

public enum RateLimitScope

Rate limit scope.

ValueDescription
Instance = 0Instance-level (in-memory).
Environment = 1Environment-level (Valkey-backed).

RateLimitService class

public sealed class RateLimitService

Service that orchestrates rate limit checks across instance and environment scopes.

RateLimitService(RateLimitConfig, InstanceRateLimiter, EnvironmentRateLimiter, ILogger<RateLimitService>) constructor

public RateLimitService(RateLimitConfig config, InstanceRateLimiter? instanceLimiter, EnvironmentRateLimiter? environmentLimiter, ILogger<RateLimitService> logger)

Creates the service.

Parameters

CheckLimitAsync(string, string, string, CancellationToken) method

public Task<RateLimitDecision> CheckLimitAsync(string? microservice, string? requestPath, string? tenant, CancellationToken cancellationToken)

Check rate limits for a request.

Parameters

Returns

Decision indicating whether request is allowed.

RateLimitServiceCollectionExtensions class

public static class RateLimitServiceCollectionExtensions

Extension methods for registering rate limiting services.

AddRouterRateLimiting(IServiceCollection, IConfiguration) extension method

public static IServiceCollection AddRouterRateLimiting(this IServiceCollection services, IConfiguration configuration)

Adds rate limiting services to the DI container.

Parameters

Returns

The service collection for chaining.

AddRouterRateLimiting<TStore>(IServiceCollection, IConfiguration) extension method

public static IServiceCollection AddRouterRateLimiting<TStore>(this IServiceCollection services, IConfiguration configuration) where TStore : class, IValkeyRateLimitStore

Adds rate limiting with a custom store for the environment rate limit.

Type parameters

Parameters

Returns

The service collection for chaining.

RateLimitStoreResult record

public sealed record RateLimitStoreResult

Result of a Valkey rate limit check.

Parameters

RateLimitStoreResult(bool, long, int, int, int) constructor

public RateLimitStoreResult(bool Allowed, long CurrentCount, int Limit, int WindowSeconds, int RetryAfterSeconds)

Result of a Valkey rate limit check.

Parameters

Allowed property

public bool Allowed { get; init; }

Whether the request is allowed.

CurrentCount property

public long CurrentCount { get; init; }

The count in the window, this request included.

Limit property

public int Limit { get; init; }

The requests allowed in the window.

RetryAfterSeconds property

public int RetryAfterSeconds { get; init; }

When the request may be retried, in seconds; 0 when it is allowed.

WindowSeconds property

public int WindowSeconds { get; init; }

The window, in seconds.

RouteLimitsConfig class

public sealed class RouteLimitsConfig

Per-route rate limit configuration.

RouteLimitsConfig() constructor

public RouteLimitsConfig()

Creates an instance of RouteLimitsConfig.

AllowBurstForSeconds property

public int? AllowBurstForSeconds { get; set; }

The window of the burst limit, in seconds (allow_burst_for_seconds).

AllowMaxBurstRequests property

public int? AllowMaxBurstRequests { get; set; }

The requests allowed in the burst window (allow_max_burst_requests).

MatchType property

public RouteMatchType MatchType { get; set; }

How RouteLimitsConfig.Patternmatches a path. The default is RouteMatchType.Exact.

MaxRequests property

public int? MaxRequests { get; set; }

The requests allowed in the window (max_requests).

Pattern property

public string Pattern { get; set; }

Route pattern: exact (“/api/scans”), prefix (“/api/scans/*”), or regex (“^/api/scans/[a-f0-9-]+$”).

PerSeconds property

public int? PerSeconds { get; set; }

The window of the single-window limit, in seconds (per_seconds).

Rules property

public List<RateLimitRule> Rules { get; set; }

Multi-rule configuration (preferred). When specified, takes precedence over the single-window fields.

GetEffectiveRules() method

public IReadOnlyList<RateLimitRule> GetEffectiveRules()

The rules in effect: rules when it has any; otherwise a long rule from per_seconds and max_requests and a burst rule from the burst settings, each when both values are set.

Returns

The rules in effect.

Validate(string) method

public void Validate(string path)

Validates the route limits and compiles a regex pattern.

Parameters

Exceptions

RouteMatchType enum

public enum RouteMatchType

How a route rate limit pattern matches a request path.

ValueDescription
Exact = 0The path equals the pattern.
Prefix = 1The path starts with the pattern.
Regex = 2The path matches the pattern as a regular expression, ignoring case.

StellaOps.Router.Gateway.Services namespace

TypeKindDescription
IRekorSubmissionServiceinterfaceService for submitting DSSE envelopes to Rekor.
IRouterGatewayLocalHarnessTransportinterfaceGateway-side adapter for process-local development and test transports.
IRoutingWeightOverrideStoreinterfaceProcess-local routing weight overrides used for live canary tuning.
InMemoryRoutingWeightOverrideStoreclassThread-safe in-memory implementation of IRoutingWeightOverrideStore.
RekorLinkagerecordRekor linkage record.
RekorSubmissionOptionsclassConfiguration for Rekor submission.
RekorSubmissionResultrecordRekor submission result.
RekorSubmissionServiceclassDefault implementation of Rekor submission service.
RoutingWeightOverriderecordOne service/version or service/version/instance routing weight override.
RoutingWeightResolutionrecordEffective routing weight plus the source that supplied it.

IRekorSubmissionService interface

public interface IRekorSubmissionService

Service for submitting DSSE envelopes to Rekor.

GetLinkageAsync(string, CancellationToken) method

Task<RekorLinkage?> GetLinkageAsync(string digest, CancellationToken ct = default)

Gets the Rekor linkage for a digest.

QueueForSubmission(string, byte[]) method

void QueueForSubmission(string digest, byte[] dsseEnvelope)

Queues a DSSE envelope for async submission.

SubmitDsseAsync(string, byte[], CancellationToken) method

Task<RekorSubmissionResult> SubmitDsseAsync(string digest, byte[] dsseEnvelope, CancellationToken ct = default)

Submits a DSSE envelope to Rekor.

IRouterGatewayLocalHarnessTransport interface

public interface IRouterGatewayLocalHarnessTransport : ITransportServer

Gateway-side adapter for process-local development and test transports.

OnConnectionClosed event

event Func<string, Task>? OnConnectionClosed

Raised when a local connection closes, with its identifier.

OnHeartbeatReceived event

event Func<ConnectionState, HeartbeatPayload, Task>? OnHeartbeatReceived

Raised for each heartbeat of a local microservice.

OnHelloReceived event

event Func<ConnectionState, HelloPayload, Task>? OnHelloReceived

Raised when a local microservice announces itself and its endpoints (a HELLO).

RemoveConnection(string) method

bool RemoveConnection(string connectionId)

Removes a connection.

Parameters

Returns

true when the connection existed.

StartListeningToConnection(string) method

void StartListeningToConnection(string connectionId)

Starts reading the frames of a connection.

Parameters

IRoutingWeightOverrideStore interface

public interface IRoutingWeightOverrideStore

Process-local routing weight overrides used for live canary tuning.

MaxWeight property

int MaxWeight { get; }

Gets the maximum accepted runtime override weight.

GetOverrides() method

IReadOnlyList<RoutingWeightOverride> GetOverrides()

Gets the current runtime and startup-configured overrides.

Resolve(ConnectionState) method

RoutingWeightResolution Resolve(ConnectionState connection)

Resolves the effective weight for a live connection.

Upsert(RoutingWeightOverride) method

RoutingWeightOverride Upsert(RoutingWeightOverride weightOverride)

Adds or replaces one routing weight override.

InMemoryRoutingWeightOverrideStore class

public sealed class InMemoryRoutingWeightOverrideStore : IRoutingWeightOverrideStore

Thread-safe in-memory implementation of IRoutingWeightOverrideStore.

InMemoryRoutingWeightOverrideStore(IOptions<RoutingOptions>) constructor

public InMemoryRoutingWeightOverrideStore(IOptions<RoutingOptions> options)

Creates the store with the overrides the routing options configure at startup.

Parameters

MaxWeight property

public int MaxWeight { get; }

Gets the maximum accepted runtime override weight.

GetOverrides() method

public IReadOnlyList<RoutingWeightOverride> GetOverrides()

Gets the current runtime and startup-configured overrides.

Resolve(ConnectionState) method

public RoutingWeightResolution Resolve(ConnectionState connection)

Resolves the effective weight for a live connection.

Upsert(RoutingWeightOverride) method

public RoutingWeightOverride Upsert(RoutingWeightOverride weightOverride)

Adds or replaces one routing weight override.

RekorLinkage record

public sealed record RekorLinkage

Rekor linkage record.

RekorLinkage() constructor

public RekorLinkage()

Creates an instance of RekorLinkage.

CreatedAt property

public DateTimeOffset CreatedAt { get; init; }

When this linkage was created.

Digest property

public required string Digest { get; init; }

Artifact digest.

EnvelopeHash property

public required string EnvelopeHash { get; init; }

DSSE envelope hash.

IntegratedAt property

public DateTimeOffset IntegratedAt { get; init; }

When the entry was integrated.

LogIndex property

public long LogIndex { get; init; }

Rekor log index.

RekorUuid property

public required string RekorUuid { get; init; }

Rekor UUID.

RekorSubmissionOptions class

public sealed class RekorSubmissionOptions

Configuration for Rekor submission.

RekorSubmissionOptions() constructor

public RekorSubmissionOptions()

Creates an instance of RekorSubmissionOptions.

AsyncSubmission property

public bool AsyncSubmission { get; set; }

Whether to submit asynchronously (don’t block push).

CacheLinkage property

public bool CacheLinkage { get; set; }

Cache Rekor linkage results.

CacheTtlSeconds property

public int CacheTtlSeconds { get; set; }

Cache TTL in seconds.

RekorUrl property

public string RekorUrl { get; set; }

Rekor instance URL.

RetryAttempts property

public int RetryAttempts { get; set; }

Number of retry attempts.

SubmitToRekor property

public bool SubmitToRekor { get; set; }

Whether to submit attestations to Rekor.

TimeoutSeconds property

public int TimeoutSeconds { get; set; }

Timeout for Rekor submission in seconds.

RekorSubmissionResult record

public sealed record RekorSubmissionResult

Rekor submission result.

RekorSubmissionResult() constructor

public RekorSubmissionResult()

Creates an instance of RekorSubmissionResult.

Error property

public string? Error { get; init; }

Error message if failed.

IntegratedAt property

public DateTimeOffset? IntegratedAt { get; init; }

Integrated timestamp.

LogIndex property

public long? LogIndex { get; init; }

Rekor log index.

Success property

public bool Success { get; init; }

Whether submission was successful.

Uuid property

public string? Uuid { get; init; }

Rekor entry UUID.

RekorSubmissionService class

public sealed class RekorSubmissionService : IRekorSubmissionService, IDisposable

Default implementation of Rekor submission service.

RekorSubmissionService(HttpClient, IMemoryCache, IOptions<RekorSubmissionOptions>, ILogger<RekorSubmissionService>) constructor

public RekorSubmissionService(HttpClient httpClient, IMemoryCache cache, IOptions<RekorSubmissionOptions> options, ILogger<RekorSubmissionService> logger)

Creates the service.

Parameters

Dispose() method

public void Dispose()

Releases the service.

GetLinkageAsync(string, CancellationToken) method

public Task<RekorLinkage?> GetLinkageAsync(string digest, CancellationToken ct = default)

Gets the Rekor linkage for a digest.

QueueForSubmission(string, byte[]) method

public void QueueForSubmission(string digest, byte[] dsseEnvelope)

Queues a DSSE envelope for async submission.

SubmitDsseAsync(string, byte[], CancellationToken) method

public Task<RekorSubmissionResult> SubmitDsseAsync(string digest, byte[] dsseEnvelope, CancellationToken ct = default)

Submits a DSSE envelope to Rekor.

RoutingWeightOverride record

public sealed record RoutingWeightOverride

One service/version or service/version/instance routing weight override.

Parameters

RoutingWeightOverride(string, string, string, int) constructor

public RoutingWeightOverride(string Service, string Version, string? InstanceId, int Weight)

One service/version or service/version/instance routing weight override.

Parameters

InstanceId property

public string? InstanceId { get; init; }

The instance; the override applies to the whole version when not set.

Service property

public string Service { get; init; }

The service.

Version property

public string Version { get; init; }

The service version.

Weight property

public int Weight { get; init; }

The routing weight.

RoutingWeightResolution record

public sealed record RoutingWeightResolution

Effective routing weight plus the source that supplied it.

Parameters

RoutingWeightResolution(int, string) constructor

public RoutingWeightResolution(int Weight, string Source)

Effective routing weight plus the source that supplied it.

Parameters

Source property

public string Source { get; init; }

Where the weight comes from: instanceOverride, versionOverride or instance (the weight the instance announced).

Weight property

public int Weight { get; init; }

The effective weight.