StellaOps.Router.Gateway
Router gateway core: the routing state of connected microservices, request routing and dispatch, and gateway rate limiting. Install Installing Stella Ops packagesRouter downloads and signaturesnet10.01.0.1-20261117T070237Zdotnet add package StellaOps.
Namespaces
namespace StellaOps.Router.Gateway
| Type | Kind | Description |
|---|---|---|
ApplicationBuilderExtensions | class | Extension methods for configuring the router gateway middleware pipeline. |
RouterHttpContextKeys | class | Well-known HttpContext.Items keys for router pipeline. |
class ApplicationBuilderExtensions
public static class ApplicationBuilderExtensions
Extension methods for configuring the router gateway middleware pipeline.
Members
| Member | Kind | Summary |
|---|---|---|
MapRouterOpenApi( | extension method | Maps OpenAPI endpoints to the application. |
UseRateLimiting( | extension method | Adds rate limiting middleware to the pipeline. |
UseRouterGateway( | extension method | Adds the router gateway middleware pipeline. |
UseRouterGatewayCore( | extension method | Adds the router gateway middleware pipeline without payload limiting. |
extension method MapRouterOpenApi(IEndpointRouteBuilder) #
MapRouterOpenApi(IEndpointRouteBuilder) #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
endpoints: The endpoint route builder.
Returns
The endpoint route builder for chaining.
extension method UseRateLimiting(IApplicationBuilder) #
UseRateLimiting(IApplicationBuilder) #public static IApplicationBuilder UseRateLimiting(this IApplicationBuilder app)
Adds rate limiting middleware to the pipeline.
Parameters
app: The application builder.
Returns
The application builder for chaining.
extension method UseRouterGateway(IApplicationBuilder) #
UseRouterGateway(IApplicationBuilder) #public static IApplicationBuilder UseRouterGateway(this IApplicationBuilder app)
Adds the router gateway middleware pipeline.
Parameters
app: The application builder.
Returns
The application builder for chaining.
extension method UseRouterGatewayCore(IApplicationBuilder) #
UseRouterGatewayCore(IApplicationBuilder) #public static IApplicationBuilder UseRouterGatewayCore(this IApplicationBuilder app)
Adds the router gateway middleware pipeline without payload limiting.
Parameters
app: The application builder.
Returns
The application builder for chaining.
class RouterHttpContextKeys
public static class RouterHttpContextKeys
Well-known HttpContext.Items keys for router pipeline.
Members
| Member | Kind | Summary |
|---|---|---|
EndpointDescriptor | constant | Key for the resolved EndpointDescriptor. |
PathParameters | constant | Key for path parameters extracted from route template matching. |
PreResolvedEndpoint | constant | Request-local resolution retained by SPA diversion. |
RawRequestTarget | constant | Key for the raw request target (IHttp: path plus query string with the wire percent-encoding intact) after Gateway route translation. |
RouteDefaultTimeout | constant | Key for the route-level default timeout (TimeSpan) resolved from Gateway route table. |
RouteTargetMicroservice | constant | Key for the route-level target microservice hint inferred from the gateway route entry. |
RoutingDecision | constant | Key for the RoutingDecision. |
TargetEndpointPathTemplate | constant | Key for the resolved endpoint path template (EndpointDescriptor.Path). |
TargetMicroservice | constant | Key for the resolved target microservice name (ServiceName). |
TranslatedRequestPath | constant | Key for the translated request path resolved from Gateway route translation. |
constant EndpointDescriptor #
EndpointDescriptor #public const string EndpointDescriptor = "Stella.EndpointDescriptor"
Key for the resolved EndpointDescriptor.
constant PathParameters #
PathParameters #public const string PathParameters = "Stella.PathParameters"
Key for path parameters extracted from route template matching.
constant PreResolvedEndpoint #
PreResolvedEndpoint #public const string PreResolvedEndpoint = "Stella.Router.PreResolvedEndpoint"
Request-local resolution retained by SPA diversion.
constant RawRequestTarget #
RawRequestTarget #public const string RawRequestTarget = "Stella.RawRequestTarget"
Key for the raw request target (IHttp: path plus query string with the wire percent-encoding intact) after Gateway route translation. Set only when a translation applied alongside RouterHttpContextKeys.; an untranslated request forwards the wire target verbatim without this key.
constant RouteDefaultTimeout #
RouteDefaultTimeout #public const string RouteDefaultTimeout = "Stella.RouteDefaultTimeout"
Key for the route-level default timeout (TimeSpan) resolved from Gateway route table.
constant RouteTargetMicroservice #
RouteTargetMicroservice #public const string RouteTargetMicroservice = "Stella.RouteTargetMicroservice"
Key for the route-level target microservice hint inferred from the gateway route entry.
constant RoutingDecision #
RoutingDecision #public const string RoutingDecision = "Stella.RoutingDecision"
Key for the RoutingDecision.
constant TargetEndpointPathTemplate #
TargetEndpointPathTemplate #public const string TargetEndpointPathTemplate = "Stella.TargetEndpointPathTemplate"
Key for the resolved endpoint path template (EndpointDescriptor.Path).
constant TargetMicroservice #
TargetMicroservice #public const string TargetMicroservice = "Stella.TargetMicroservice"
Key for the resolved target microservice name (ServiceName).
constant TranslatedRequestPath #
TranslatedRequestPath #public const string TranslatedRequestPath = "Stella.TranslatedRequestPath"
Key for the translated request path resolved from Gateway route translation.
namespace StellaOps.Router.Gateway.Authorization
| Type | Kind | Description |
|---|---|---|
AuthorityConnectionOptions | class | Configuration options for connecting to the Authority service. |
AuthorizationMiddleware | class | Middleware that enforces claims requirements for endpoints. |
AuthorizationMiddlewareExtensions | class | Extension methods for registering the authorization middleware. |
AuthorizationServiceCollectionExtensions | class | Extension methods for registering Authority integration services. |
ClaimsOverrideChangedEventArgs | class | Event arguments for claims override changes. |
EndpointKey | struct | Key for identifying an endpoint by service name, method, and path. |
IAuthorityClaimsProvider | interface | Provides claims overrides from the central Authority service. |
IEffectiveClaimsStore | interface | Stores and retrieves effective claims for endpoints. |
class AuthorityConnectionOptions
public sealed class AuthorityConnectionOptions
Configuration options for connecting to the Authority service.
Members
| Member | Kind | Summary |
|---|---|---|
AuthorityConnectionOptions( | constructor | Creates an instance of Authority. |
HttpClientName | constant | Name of the HttpClient the claims-overrides provider uses. |
SectionName | constant | Configuration section name. |
AuthorityUrl | property | Gets or sets the Authority service URL. |
Enabled | property | Gets or sets whether Authority integration is enabled. |
RefreshInterval | property | Gets or sets the interval at which to refresh claims from Authority. |
StartupTimeout | property | Gets or sets the startup timeout when waiting for Authority. |
UseAuthorityPushNotifications | property | Gets or sets whether to use push notifications from Authority. |
WaitForAuthorityOnStartup | property | Gets or sets whether to wait for Authority on startup. |
constructor AuthorityConnectionOptions() #
AuthorityConnectionOptions() #public AuthorityConnectionOptions()
Creates an instance of Authority.
constant HttpClientName #
HttpClientName #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. on GET /api/v1/claims/overrides) attaches its token handler to this name.
constant SectionName #
SectionName #public const string SectionName = "Router:Authority"
Configuration section name.
property AuthorityUrl #
AuthorityUrl #public string AuthorityUrl { get; set; }
Gets or sets the Authority service URL.
property Enabled #
Enabled #public bool Enabled { get; set; }
Gets or sets whether Authority integration is enabled.
property RefreshInterval #
RefreshInterval #public TimeSpan RefreshInterval { get; set; }
Gets or sets the interval at which to refresh claims from Authority.
property StartupTimeout #
StartupTimeout #public TimeSpan StartupTimeout { get; set; }
Gets or sets the startup timeout when waiting for Authority.
property UseAuthorityPushNotifications #
UseAuthorityPushNotifications #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.
property WaitForAuthorityOnStartup #
WaitForAuthorityOnStartup #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.
class AuthorizationMiddleware
public sealed class AuthorizationMiddleware
Middleware that enforces claims requirements for endpoints.
Members
| Member | Kind | Summary |
|---|---|---|
AuthorizationMiddleware( | constructor | Initializes a new instance of the AuthorizationMiddlewareclass. |
InvokeAsync( | method | Invokes the middleware. |
constructor AuthorizationMiddleware(RequestDelegate, IEffectiveClaimsStore, ILogger<AuthorizationMiddleware>) #
AuthorizationMiddleware(RequestDelegate, IEffectiveClaimsStore, ILogger<AuthorizationMiddleware>) #public AuthorizationMiddleware(RequestDelegate next, IEffectiveClaimsStore claimsStore, ILogger<AuthorizationMiddleware> logger)
Initializes a new instance of the AuthorizationMiddlewareclass.
method InvokeAsync(HttpContext) #
InvokeAsync(HttpContext) #public Task InvokeAsync(HttpContext context)
Invokes the middleware.
class AuthorizationMiddlewareExtensions
public static class AuthorizationMiddlewareExtensions
Extension methods for registering the authorization middleware.
Members
| Member | Kind | Summary |
|---|---|---|
UseClaimsAuthorization( | extension method | Adds the claims authorization middleware to the pipeline. |
extension method UseClaimsAuthorization(IApplicationBuilder) #
UseClaimsAuthorization(IApplicationBuilder) #public static IApplicationBuilder UseClaimsAuthorization(this IApplicationBuilder app)
Adds the claims authorization middleware to the pipeline.
Parameters
app: The application builder.
Returns
The application builder for chaining.
class AuthorizationServiceCollectionExtensions
public static class AuthorizationServiceCollectionExtensions
Extension methods for registering Authority integration services.
Members
| Member | Kind | Summary |
|---|---|---|
AddAuthorityIntegration( | extension method | Adds Authority integration services with custom options. |
AddAuthorityIntegration( | extension method | Adds Authority integration services to the service collection. |
AddNoOpAuthorityIntegration( | extension method | Adds a no-op Authority integration (no external Authority). |
extension method AddAuthorityIntegration(IServiceCollection, Action<AuthorityConnectionOptions>) #
AddAuthorityIntegration(IServiceCollection, Action<AuthorityConnectionOptions>) #public static IServiceCollection AddAuthorityIntegration(this IServiceCollection services, Action<AuthorityConnectionOptions>? configure = null)
Adds Authority integration services with custom options.
Parameters
services: The service collection.configure: Action to configure Authority options.
Returns
The service collection for chaining.
extension method AddAuthorityIntegration(IServiceCollection, IConfiguration) #
AddAuthorityIntegration(IServiceCollection, IConfiguration) #public static IServiceCollection AddAuthorityIntegration(this IServiceCollection services, IConfiguration configuration)
Adds Authority integration services to the service collection.
Parameters
services: The service collection.configuration: The configuration.
Returns
The service collection for chaining.
extension method AddNoOpAuthorityIntegration(IServiceCollection) #
AddNoOpAuthorityIntegration(IServiceCollection) #public static IServiceCollection AddNoOpAuthorityIntegration(this IServiceCollection services)
Adds a no-op Authority integration (no external Authority). Claims are only from microservices.
Parameters
services: The service collection.
Returns
The service collection for chaining.
class ClaimsOverrideChangedEventArgs
public sealed class ClaimsOverrideChangedEventArgs : EventArgs
Event arguments for claims override changes.
Members
| Member | Kind | Summary |
|---|---|---|
ClaimsOverrideChangedEventArgs( | constructor | Creates an instance of Claims. |
Overrides | property | Gets the updated claims overrides. |
constructor ClaimsOverrideChangedEventArgs() #
ClaimsOverrideChangedEventArgs() #public ClaimsOverrideChangedEventArgs()
Creates an instance of Claims.
property Overrides #
Overrides #public IReadOnlyDictionary<EndpointKey, IReadOnlyList<ClaimRequirement>> Overrides { get; init; }
Gets the updated claims overrides.
struct EndpointKey
public readonly struct EndpointKey : IEquatable<EndpointKey>
Key for identifying an endpoint by service name, method, and path.
Parameters
ServiceName: The name of the service.Method: The HTTP method.Path: The path template.
Members
| Member | Kind | Summary |
|---|---|---|
EndpointKey( | constructor | Key for identifying an endpoint by service name, method, and path. |
Method | property | The HTTP method. |
Path | property | The path template. |
ServiceName | property | The name of the service. |
Create( | method | Creates an endpoint key with normalized values. |
ToString( | method | See ValueType.ToString(). |
constructor EndpointKey(string, string, string) #
EndpointKey(string, string, string) #public EndpointKey(string ServiceName, string Method, string Path)
Key for identifying an endpoint by service name, method, and path.
Parameters
ServiceName: The name of the service.Method: The HTTP method.Path: The path template.
property Method #
Method #public string Method { get; init; }
The HTTP method.
property Path #
Path #public string Path { get; init; }
The path template.
property ServiceName #
ServiceName #public string ServiceName { get; init; }
The name of the service.
method Create(string, string, string) #
Create(string, string, string) #public static EndpointKey Create(string serviceName, string method, string path)
Creates an endpoint key with normalized values.
method ToString() #
ToString() #public override string ToString()
See ValueType.ToString().
interface IAuthorityClaimsProvider
public interface IAuthorityClaimsProvider
Provides claims overrides from the central Authority service.
Members
| Member | Kind | Summary |
|---|---|---|
IsAvailable | property | Gets a value indicating whether the Authority is currently available. |
OverridesChanged | event | Occurs when claims overrides change. |
GetOverridesAsync( | method | Gets all claims overrides from Authority. |
property IsAvailable #
IsAvailable #bool IsAvailable { get; }
Gets a value indicating whether the Authority is currently available.
event OverridesChanged #
OverridesChanged #event EventHandler<ClaimsOverrideChangedEventArgs>? OverridesChanged
Occurs when claims overrides change.
method GetOverridesAsync(CancellationToken) #
GetOverridesAsync(CancellationToken) #Task<IReadOnlyDictionary<EndpointKey, IReadOnlyList<ClaimRequirement>>> GetOverridesAsync(CancellationToken cancellationToken)
Gets all claims overrides from Authority.
Parameters
cancellationToken: The cancellation token.
Returns
A dictionary of endpoint keys to claim requirements.
interface IEffectiveClaimsStore
public interface IEffectiveClaimsStore
Stores and retrieves effective claims for endpoints. Handles merging of microservice defaults with Authority overrides.
Members
| Member | Kind | Summary |
|---|---|---|
GetEffectiveClaims( | method | Gets the effective claims for an endpoint of one version of a service. |
RemoveService( | method | Removes the claims of one version of a service. |
UpdateFromAuthority( | method | Updates claims from Authority overrides. |
UpdateFromMicroservice( | method | Updates the claims of one version of a service from its HELLO message; other versions keep theirs. |
method GetEffectiveClaims(string, string, string, string) #
GetEffectiveClaims(string, string, string, string) #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
serviceName: The service name.version: The service version whose claims apply.method: The HTTP method.path: The path template.
Returns
The effective claims for the endpoint.
method RemoveService(string, string) #
RemoveService(string, string) #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
serviceName: The service name.version: The service version.
method UpdateFromAuthority(IReadOnlyDictionary<EndpointKey, IReadOnlyList<ClaimRequirement>>) #
UpdateFromAuthority(IReadOnlyDictionary<EndpointKey, IReadOnlyList<ClaimRequirement>>) #void UpdateFromAuthority(IReadOnlyDictionary<EndpointKey, IReadOnlyList<ClaimRequirement>> overrides)
Updates claims from Authority overrides.
Parameters
overrides: The Authority claims overrides.
method UpdateFromMicroservice(string, string, IReadOnlyList<EndpointDescriptor>) #
UpdateFromMicroservice(string, string, IReadOnlyList<EndpointDescriptor>) #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
serviceName: The service name.version: The version of the instance that sent the HELLO.endpoints: The endpoint descriptors with claims.
namespace StellaOps.Router.Gateway.Configuration
| Type | Kind | Description |
|---|---|---|
HealthOptions | class | Configuration options for health monitoring. |
RouterNodeConfig | class | Static configuration for a router gateway node. |
RoutingOptions | class | Options for routing behavior. |
StellaOpsRoute | class | A static route of the gateway: a path and what the gateway does with the requests that match it. |
StellaOpsRouteType | enum | What a static route does with a matching request. |
TieBreakerMode | enum | Tie-breaker mode for routing when multiple instances have equal priority. |
class HealthOptions
public sealed class HealthOptions
Configuration options for health monitoring.
Members
| Member | Kind | Summary |
|---|---|---|
HealthOptions( | constructor | Creates an instance of HealthOptions. |
SectionName | constant | Gets the configuration section name. |
CheckInterval | property | Gets or sets the interval at which to check for stale connections. |
DegradedThreshold | property | Gets or sets the threshold after which a connection is considered degraded. |
PingHistorySize | property | Gets or sets the number of ping measurements to keep for averaging. |
StaleThreshold | property | Gets or sets the threshold after which a connection is considered stale (no heartbeat). |
constructor HealthOptions() #
HealthOptions() #public HealthOptions()
Creates an instance of HealthOptions.
constant SectionName #
SectionName #public const string SectionName = "Router:Health"
Gets the configuration section name.
property CheckInterval #
CheckInterval #public TimeSpan CheckInterval { get; set; }
Gets or sets the interval at which to check for stale connections. Default: 15 seconds.
property DegradedThreshold #
DegradedThreshold #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.
property PingHistorySize #
PingHistorySize #public int PingHistorySize { get; set; }
Gets or sets the number of ping measurements to keep for averaging. Default: 10.
property StaleThreshold #
StaleThreshold #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.
class RouterNodeConfig
public sealed class RouterNodeConfig
Static configuration for a router gateway node.
Members
| Member | Kind | Summary |
|---|---|---|
RouterNodeConfig( | constructor | Creates an instance of RouterNodeConfig. |
LegacySectionName | constant | The alternative configuration section name, read only when the RouterNodeConfig.section does not exist. |
SectionName | constant | Configuration section name for binding. |
Environment | property | Gets or sets the environment name (e.g., “prod”, “staging”, “dev”). |
NeighborRegions | property | Gets or sets the neighbor regions for fallback routing, in order of preference. |
NodeId | property | Gets or sets the unique identifier for this gateway node (e.g., “gw-eu1-01”). |
Region | property | Gets or sets the region where this gateway is deployed (e.g., “eu1”). |
Validate( | method | Validates the configuration. |
constructor RouterNodeConfig() #
RouterNodeConfig() #public RouterNodeConfig()
Creates an instance of RouterNodeConfig.
constant LegacySectionName #
LegacySectionName #public const string LegacySectionName = "Router:Node"
The alternative configuration section name, read only when the RouterNodeConfig.section does not exist.
constant SectionName #
SectionName #public const string SectionName = "GatewayNode"
Configuration section name for binding.
property Environment #
Environment #public string Environment { get; set; }
Gets or sets the environment name (e.g., “prod”, “staging”, “dev”).
property NeighborRegions #
NeighborRegions #public List<string> NeighborRegions { get; set; }
Gets or sets the neighbor regions for fallback routing, in order of preference.
property NodeId #
NodeId #public string NodeId { get; set; }
Gets or sets the unique identifier for this gateway node (e.g., “gw-eu1-01”).
property Region #
Region #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.
method Validate() #
Validate() #public void Validate()
Validates the configuration.
Exceptions
Invalid: Thrown when configuration is invalid.Operation Exception
class RoutingOptions
public sealed class RoutingOptions
Options for routing behavior.
Members
| Member | Kind | Summary |
|---|---|---|
RoutingOptions( | constructor | Creates an instance of RoutingOptions. |
SectionName | constant | Configuration section name for binding. |
AllowDegradedInstances | property | Gets or sets whether to allow routing to degraded instances when no healthy instances are available. |
DefaultVersion | property | Gets or sets the default version to use when no version is specified in the request. |
GlobalTimeoutCapMs | property | Gets or sets the global timeout cap in milliseconds. |
MaxWeightOverride | property | Gets or sets the maximum accepted runtime routing weight override. |
PingToleranceMs | property | Gets or sets the ping tolerance in milliseconds for considering instances “tied”. |
PreferLocalRegion | property | Gets or sets whether to prefer local region instances over neighbor regions. |
RoutingTimeoutMs | property | Gets or sets the gateway route default timeout in milliseconds. |
TieBreaker | property | Gets or sets the tie-breaker mode when multiple instances have equal priority. |
WeightOverrides | property | Gets or sets gateway-side routing weight overrides. |
constructor RoutingOptions() #
RoutingOptions() #public RoutingOptions()
Creates an instance of RoutingOptions.
constant SectionName #
SectionName #public const string SectionName = "Router:Routing"
Configuration section name for binding.
property AllowDegradedInstances #
AllowDegradedInstances #public bool AllowDegradedInstances { get; set; }
Gets or sets whether to allow routing to degraded instances when no healthy instances are available.
property DefaultVersion #
DefaultVersion #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.
property GlobalTimeoutCapMs #
GlobalTimeoutCapMs #public int GlobalTimeoutCapMs { get; set; }
Gets or sets the global timeout cap in milliseconds. Effective request timeout cannot exceed this value.
property MaxWeightOverride #
MaxWeightOverride #public int MaxWeightOverride { get; set; }
Gets or sets the maximum accepted runtime routing weight override.
property PingToleranceMs #
PingToleranceMs #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.
property PreferLocalRegion #
PreferLocalRegion #public bool PreferLocalRegion { get; set; }
Gets or sets whether to prefer local region instances over neighbor regions.
property RoutingTimeoutMs #
RoutingTimeoutMs #public int RoutingTimeoutMs { get; set; }
Gets or sets the gateway route default timeout in milliseconds.
property TieBreaker #
TieBreaker #public TieBreakerMode TieBreaker { get; set; }
Gets or sets the tie-breaker mode when multiple instances have equal priority.
property WeightOverrides #
WeightOverrides #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.
class StellaOpsRoute
public sealed class StellaOpsRoute
A static route of the gateway: a path and what the gateway does with the requests that match it.
Members
| Member | Kind | Summary |
|---|---|---|
StellaOpsRoute( | constructor | Creates an instance of StellaOpsRoute. |
DefaultTimeout | property | Optional route-level default timeout (for example “15s”, “2m”). |
Headers | property | Headers added to the forwarded request. |
IsRegex | property | Whether StellaOpsRoute.is a regular expression. |
Path | property | The path the route matches: a path and the paths below it, or a regular expression when StellaOpsRoute.is set. |
PreserveAuthHeaders | property | When true, the gateway preserves Authorization and DPoP headers instead of stripping them. |
TranslatesTo | property | 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 | What the route does with a matching request. |
constructor StellaOpsRoute() #
StellaOpsRoute() #public StellaOpsRoute()
Creates an instance of StellaOpsRoute.
property DefaultTimeout #
DefaultTimeout #public string? DefaultTimeout { get; set; }
Optional route-level default timeout (for example “15s”, “2m”). Applied when endpoint metadata does not provide a timeout.
property Headers #
Headers #public Dictionary<string, string> Headers { get; set; }
Headers added to the forwarded request.
property IsRegex #
IsRegex #public bool IsRegex { get; set; }
Whether StellaOpsRoute.is a regular expression.
property Path #
Path #public string Path { get; set; }
The path the route matches: a path and the paths below it, or a regular expression when StellaOpsRoute.is set.
property PreserveAuthHeaders #
PreserveAuthHeaders #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.
property TranslatesTo #
TranslatesTo #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.
property Type #
Type #public StellaOpsRouteType Type { get; set; }
What the route does with a matching request.
enum StellaOpsRouteType
public enum StellaOpsRouteType
What a static route does with a matching request.
| Value | Description |
|---|---|
Microservice = 0 | The request goes to a microservice through the Router. |
ReverseProxy = 1 | The request is proxied to the StellaOpsRoute.address. |
StaticFiles = 2 | The request is served from a directory of static files. |
StaticFile = 3 | The request is served with one static file. |
WebSocket = 4 | The request is a WebSocket proxied to the StellaOpsRoute.address. |
NotFoundPage = 5 | The page served for a request that no route matches. |
ServerErrorPage = 6 | The page served for a server error. |
enum TieBreakerMode
public enum TieBreakerMode
Tie-breaker mode for routing when multiple instances have equal priority.
| Value | Description |
|---|---|
Random = 0 | Select randomly among tied instances. |
RoundRobin = 1 | Rotate through tied instances in order. |
namespace StellaOps.Router.Gateway.DependencyInjection
| Type | Kind | Description |
|---|---|---|
RouterServiceCollectionExtensions | class | Extension methods for registering router gateway services. |
class RouterServiceCollectionExtensions
public static class RouterServiceCollectionExtensions
Extension methods for registering router gateway services.
Members
| Member | Kind | Summary |
|---|---|---|
AddRouterGateway( | extension method | Adds router gateway services with custom options. |
AddRouterGateway( | extension method | Adds router gateway services to the service collection. |
AddRouterGatewayCore( | extension method | Adds router gateway services with minimal defaults. |
AddRouterGatewayLocalHarness( | extension method | Adds the gateway lifecycle services required by an explicit process-local transport harness. |
extension method AddRouterGateway(IServiceCollection, Action<RouterNodeConfig>, Action<RoutingOptions>) #
AddRouterGateway(IServiceCollection, Action<RouterNodeConfig>, Action<RoutingOptions>) #public static IServiceCollection AddRouterGateway(this IServiceCollection services, Action<RouterNodeConfig>? configureNode = null, Action<RoutingOptions>? configureRouting = null)
Adds router gateway services with custom options.
Parameters
services: The service collection.configureNode: Action to configure router node options.configureRouting: Action to configure routing options.
Returns
The service collection for chaining.
extension method AddRouterGateway(IServiceCollection, IConfiguration) #
AddRouterGateway(IServiceCollection, IConfiguration) #public static IServiceCollection AddRouterGateway(this IServiceCollection services, IConfiguration configuration)
Adds router gateway services to the service collection.
Parameters
services: The service collection.configuration: The configuration.
Returns
The service collection for chaining.
extension method AddRouterGatewayCore(IServiceCollection) #
AddRouterGatewayCore(IServiceCollection) #public static IServiceCollection AddRouterGatewayCore(this IServiceCollection services)
Adds router gateway services with minimal defaults.
Parameters
services: The service collection.
Returns
The service collection for chaining.
extension method AddRouterGatewayLocalHarness(IServiceCollection, IHostEnvironment) #
AddRouterGatewayLocalHarness(IServiceCollection, IHostEnvironment) #public static IServiceCollection AddRouterGatewayLocalHarness(this IServiceCollection services, IHostEnvironment environment)
Adds the gateway lifecycle services required by an explicit process-local transport harness.
Parameters
services: The service collection.environment: The host environment used to gate local harness registration.
Returns
The service collection for chaining.
Exceptions
Invalid: Thrown when the host environment is not Development, Testing, or Local.Operation Exception
namespace StellaOps.Router.Gateway.Metrics
| Type | Kind | Description |
|---|---|---|
IRouterGatewayMetrics | interface | Records the routed requests and returns their counts and durations. |
RouterGatewayMetrics | class | Records the routed requests on the meter RouterGatewayMetrics.and keeps their totals for the Prometheus text of the gateway. |
RouterRequestDurationBucket | record | One cumulative histogram bucket. |
RouterRequestDurationMetricSample | record | The duration histogram of the requests of one service version and instance. |
RouterRequestMetricSample | record | The number of requests of one service version and instance with one status class. |
interface IRouterGatewayMetrics
public interface IRouterGatewayMetrics
Records the routed requests and returns their counts and durations.
Members
| Member | Kind | Summary |
|---|---|---|
GetRequestDurations( | method | Returns the request duration histograms so far, by service, version and instance. |
GetRequestTotals( | method | Returns the request counts so far, by service, version, instance and status class. |
RecordRequest( | method | Records one routed request. |
method GetRequestDurations() #
GetRequestDurations() #IReadOnlyList<RouterRequestDurationMetricSample> GetRequestDurations()
Returns the request duration histograms so far, by service, version and instance.
Returns
The duration histograms.
method GetRequestTotals() #
GetRequestTotals() #IReadOnlyList<RouterRequestMetricSample> GetRequestTotals()
Returns the request counts so far, by service, version, instance and status class.
Returns
The request counts.
method RecordRequest(RoutingDecision, int, TimeSpan) #
RecordRequest(RoutingDecision, int, TimeSpan) #void RecordRequest(RoutingDecision decision, int statusCode, TimeSpan duration)
Records one routed request.
Parameters
decision: The routing decision: service, version and instance.statusCode: The response status code.duration: How long the request took.
class RouterGatewayMetrics
public sealed class RouterGatewayMetrics : IRouterGatewayMetrics, IDisposable
Records the routed requests on the meter RouterGatewayMetrics.and keeps their totals for the Prometheus text of the gateway.
Members
| Member | Kind | Summary |
|---|---|---|
RouterGatewayMetrics( | constructor | Creates an instance of RouterGatewayMetrics. |
MeterName | constant | The name of the meter that carries the request counter and the duration histogram. |
Dispose( | method | Disposes the meter. |
GetRequestDurations( | method | Returns the request duration histograms so far, by service, version and instance. |
GetRequestTotals( | method | Returns the request counts so far, by service, version, instance and status class. |
RecordRequest( | method | Records one routed request. |
constructor RouterGatewayMetrics() #
RouterGatewayMetrics() #public RouterGatewayMetrics()
Creates an instance of RouterGatewayMetrics.
constant MeterName #
MeterName #public const string MeterName = "StellaOps.Router.Gateway"
The name of the meter that carries the request counter and the duration histogram.
method Dispose() #
Dispose() #public void Dispose()
Disposes the meter.
method GetRequestDurations() #
GetRequestDurations() #public IReadOnlyList<RouterRequestDurationMetricSample> GetRequestDurations()
Returns the request duration histograms so far, by service, version and instance.
Returns
The duration histograms.
method GetRequestTotals() #
GetRequestTotals() #public IReadOnlyList<RouterRequestMetricSample> GetRequestTotals()
Returns the request counts so far, by service, version, instance and status class.
Returns
The request counts.
method RecordRequest(RoutingDecision, int, TimeSpan) #
RecordRequest(RoutingDecision, int, TimeSpan) #public void RecordRequest(RoutingDecision decision, int statusCode, TimeSpan duration)
Records one routed request.
Parameters
decision: The routing decision: service, version and instance.statusCode: The response status code.duration: How long the request took.
record RouterRequestDurationBucket
public sealed record RouterRequestDurationBucket
One cumulative histogram bucket.
Parameters
UpperBound: The upper bound of the bucket, in seconds.Count: The requests at most that long.
Members
| Member | Kind | Summary |
|---|---|---|
RouterRequestDurationBucket( | constructor | One cumulative histogram bucket. |
Count | property | The requests at most that long. |
UpperBound | property | The upper bound of the bucket, in seconds. |
constructor RouterRequestDurationBucket(string, long) #
RouterRequestDurationBucket(string, long) #public RouterRequestDurationBucket(string UpperBound, long Count)
One cumulative histogram bucket.
Parameters
UpperBound: The upper bound of the bucket, in seconds.Count: The requests at most that long.
property Count #
Count #public long Count { get; init; }
The requests at most that long.
property UpperBound #
UpperBound #public string UpperBound { get; init; }
The upper bound of the bucket, in seconds.
record RouterRequestDurationMetricSample
public sealed record RouterRequestDurationMetricSample
The duration histogram of the requests of one service version and instance.
Parameters
Service: The service.Version: The service version.InstanceId: The instance.Buckets: The cumulative bucket counts.Count: The number of requests.SumSeconds: The sum of the request durations, in seconds.
Members
| Member | Kind | Summary |
|---|---|---|
RouterRequestDurationMetricSample( | constructor | The duration histogram of the requests of one service version and instance. |
Buckets | property | The cumulative bucket counts. |
Count | property | The number of requests. |
InstanceId | property | The instance. |
Service | property | The service. |
SumSeconds | property | The sum of the request durations, in seconds. |
Version | property | The service version. |
constructor RouterRequestDurationMetricSample(string, string, string, IReadOnlyList<RouterRequestDurationBucket>, long, double) #
RouterRequestDurationMetricSample(string, string, string, IReadOnlyList<RouterRequestDurationBucket>, long, double) #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
Service: The service.Version: The service version.InstanceId: The instance.Buckets: The cumulative bucket counts.Count: The number of requests.SumSeconds: The sum of the request durations, in seconds.
property Buckets #
Buckets #public IReadOnlyList<RouterRequestDurationBucket> Buckets { get; init; }
The cumulative bucket counts.
property Count #
Count #public long Count { get; init; }
The number of requests.
property InstanceId #
InstanceId #public string InstanceId { get; init; }
The instance.
property Service #
Service #public string Service { get; init; }
The service.
property SumSeconds #
SumSeconds #public double SumSeconds { get; init; }
The sum of the request durations, in seconds.
property Version #
Version #public string Version { get; init; }
The service version.
record RouterRequestMetricSample
public sealed record RouterRequestMetricSample
The number of requests of one service version and instance with one status class.
Parameters
Service: The service.Version: The service version.InstanceId: The instance.StatusClass: The status class, for example2xx.Count: The number of requests.
Members
| Member | Kind | Summary |
|---|---|---|
RouterRequestMetricSample( | constructor | The number of requests of one service version and instance with one status class. |
Count | property | The number of requests. |
InstanceId | property | The instance. |
Service | property | The service. |
StatusClass | property | The status class, for example 2xx. |
Version | property | The service version. |
constructor RouterRequestMetricSample(string, string, string, string, long) #
RouterRequestMetricSample(string, string, string, string, long) #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
Service: The service.Version: The service version.InstanceId: The instance.StatusClass: The status class, for example2xx.Count: The number of requests.
property Count #
Count #public long Count { get; init; }
The number of requests.
property InstanceId #
InstanceId #public string InstanceId { get; init; }
The instance.
property Service #
Service #public string Service { get; init; }
The service.
property StatusClass #
StatusClass #public string StatusClass { get; init; }
The status class, for example 2xx.
property Version #
Version #public string Version { get; init; }
The service version.
namespace StellaOps.Router.Gateway.Middleware
| Type | Kind | Description |
|---|---|---|
AttestationCheckResult | record | Result of an attestation check. |
AttestationMiddleware | class | Middleware that checks for attestations on artifact requests. |
AttestationMiddlewareExtensions | class | Extension methods for attestation middleware. |
AttestationMiddlewareOptions | class | Configuration for attestation middleware. |
ByteCountingStream | class | A stream wrapper that counts bytes read and enforces a limit. |
DefaultAttestationLookupService | class | Default implementation of attestation lookup service. |
EndpointResolutionMiddleware | class | Resolves incoming HTTP requests to endpoint descriptors using the routing state. |
GlobalErrorHandlerMiddleware | class | Catches unhandled exceptions and returns a structured JSON error response. |
IAttestationLookupService | interface | Service for looking up attestations. |
IPayloadTracker | interface | Tracks payload bytes across requests, connections, and globally. |
PayloadLimitExceededException | class | Exception thrown when a payload limit is exceeded during streaming. |
PayloadLimitsMiddleware | class | Middleware that enforces payload limits per-request, per-connection, and aggregate. |
PayloadTracker | class | Default implementation of IPayloadTracker. |
RequestLoggingMiddleware | class | Logs basic request/response information for gateway requests. |
RouterErrorWriter | class | The gateway’s single writer for error responses. |
RoutingDecisionMiddleware | class | Makes routing decisions for resolved endpoints. |
TransportDispatchMiddleware | class | Dispatches HTTP requests to microservices via the transport layer. |
record AttestationCheckResult
public sealed record AttestationCheckResult
Result of an attestation check.
Members
| Member | Kind | Summary |
|---|---|---|
AttestationCheckResult( | constructor | Creates an instance of Attestation. |
AllPresent | property | Whether all required attestations are present. |
CheckedAt | property | Timestamp of the check. |
Digest | property | Artifact digest that was checked. |
MissingTypes | property | List of missing attestation types. |
PresentTypes | property | List of present attestation types. |
RekorLogIndex | property | Rekor log index if verified. |
constructor AttestationCheckResult() #
AttestationCheckResult() #public AttestationCheckResult()
Creates an instance of Attestation.
property AllPresent #
AllPresent #public bool AllPresent { get; init; }
Whether all required attestations are present.
property CheckedAt #
CheckedAt #public DateTimeOffset CheckedAt { get; init; }
Timestamp of the check.
property Digest #
Digest #public required string Digest { get; init; }
Artifact digest that was checked.
property MissingTypes #
MissingTypes #public List<string> MissingTypes { get; init; }
List of missing attestation types.
property PresentTypes #
PresentTypes #public List<string> PresentTypes { get; init; }
List of present attestation types.
property RekorLogIndex #
RekorLogIndex #public long? RekorLogIndex { get; init; }
Rekor log index if verified.
class AttestationMiddleware
public sealed class AttestationMiddleware
Middleware that checks for attestations on artifact requests.
Members
| Member | Kind | Summary |
|---|---|---|
AttestationMiddleware( | constructor | Creates the middleware. |
InvokeAsync( | method | Checks the required attestations of an artifact request; a request whose artifact misses one can be refused with 403, depending on the options. |
constructor AttestationMiddleware(RequestDelegate, IAttestationLookupService, IMemoryCache, IOptions<AttestationMiddlewareOptions>, ILogger<AttestationMiddleware>) #
AttestationMiddleware(RequestDelegate, IAttestationLookupService, IMemoryCache, IOptions<AttestationMiddlewareOptions>, ILogger<AttestationMiddleware>) #public AttestationMiddleware(RequestDelegate next, IAttestationLookupService lookupService, IMemoryCache cache, IOptions<AttestationMiddlewareOptions> options, ILogger<AttestationMiddleware> logger)
Creates the middleware.
Parameters
next: The next middleware.lookupService: Looks up the attestations of an artifact.cache: Caches the lookups.options: The attestation checks.logger: Receives the diagnostics.
method InvokeAsync(HttpContext) #
InvokeAsync(HttpContext) #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
context: The HTTP context.
Returns
A task that completes when the request is handled.
class AttestationMiddlewareExtensions
public static class AttestationMiddlewareExtensions
Extension methods for attestation middleware.
Members
| Member | Kind | Summary |
|---|---|---|
UseAttestationMiddleware( | extension method | Adds attestation middleware to the pipeline. |
extension method UseAttestationMiddleware(IApplicationBuilder) #
UseAttestationMiddleware(IApplicationBuilder) #public static IApplicationBuilder UseAttestationMiddleware(this IApplicationBuilder app)
Adds attestation middleware to the pipeline.
class AttestationMiddlewareOptions
public sealed class AttestationMiddlewareOptions
Configuration for attestation middleware.
Members
| Member | Kind | Summary |
|---|---|---|
AttestationMiddlewareOptions( | constructor | Creates an instance of Attestation. |
CacheResults | property | Whether to cache attestation check results. |
CacheTtlSeconds | property | Cache TTL in seconds. |
Enabled | property | Whether attestation checking is enabled. |
Mode | property | Operation mode: “audit” (log only) or “enforce” (block if missing). |
RekorUrl | property | Rekor URL for transparency log verification. |
RequireTypes | property | Required attestation types (e.g., “sbom”, “vex”). |
SkipPaths | property | Skip attestation check for these paths (regex patterns). |
constructor AttestationMiddlewareOptions() #
AttestationMiddlewareOptions() #public AttestationMiddlewareOptions()
Creates an instance of Attestation.
property CacheResults #
CacheResults #public bool CacheResults { get; set; }
Whether to cache attestation check results.
property CacheTtlSeconds #
CacheTtlSeconds #public int CacheTtlSeconds { get; set; }
Cache TTL in seconds.
property Enabled #
Enabled #public bool Enabled { get; set; }
Whether attestation checking is enabled.
property Mode #
Mode #public string Mode { get; set; }
Operation mode: “audit” (log only) or “enforce” (block if missing).
property RekorUrl #
RekorUrl #public string? RekorUrl { get; set; }
Rekor URL for transparency log verification.
property RequireTypes #
RequireTypes #public List<string> RequireTypes { get; set; }
Required attestation types (e.g., “sbom”, “vex”).
property SkipPaths #
SkipPaths #public List<string> SkipPaths { get; set; }
Skip attestation check for these paths (regex patterns).
class ByteCountingStream
public sealed class ByteCountingStream : Stream
A stream wrapper that counts bytes read and enforces a limit.
Members
| Member | Kind | Summary |
|---|---|---|
ByteCountingStream( | constructor | Initializes a new instance of the ByteCountingStreamclass. |
BytesRead | property | Gets the total number of bytes read from this stream. |
CanRead | property | See Stream.CanRead. |
CanSeek | property | See Stream.CanSeek. |
CanWrite | property | See Stream.CanWrite. |
Length | property | See Stream.Length. |
Position | property | See Stream.Position. |
DisposeAsync( | method | See Stream.. |
Flush( | method | See Stream.Flush(). |
FlushAsync( | method | See Stream.. |
Read( | method | See Stream.. |
ReadAsync( | method | See Stream.. |
ReadAsync( | method | See Stream.. |
Seek( | method | See Stream.. |
SetLength( | method | See Stream.. |
Write( | method | See Stream.. |
constructor ByteCountingStream(Stream, long, Action) #
ByteCountingStream(Stream, long, Action) #public ByteCountingStream(Stream inner, long limit, Action? onLimitExceeded = null)
Initializes a new instance of the ByteCountingStreamclass.
Parameters
inner: The inner stream to wrap.limit: The maximum number of bytes that can be read.onLimitExceeded: Optional callback invoked when the limit is exceeded.
property BytesRead #
BytesRead #public long BytesRead { get; }
Gets the total number of bytes read from this stream.
property CanRead #
CanRead #public override bool CanRead { get; }
See Stream.CanRead.
property CanSeek #
CanSeek #public override bool CanSeek { get; }
See Stream.CanSeek.
property CanWrite #
CanWrite #public override bool CanWrite { get; }
See Stream.CanWrite.
property Length #
Length #public override long Length { get; }
See Stream.Length.
property Position #
Position #public override long Position { get; set; }
See Stream.Position.
method DisposeAsync() #
DisposeAsync() #public override ValueTask DisposeAsync()
See Stream..
method Flush() #
Flush() #public override void Flush()
See Stream.Flush().
method FlushAsync(CancellationToken) #
FlushAsync(CancellationToken) #public override Task FlushAsync(CancellationToken cancellationToken)
See Stream..
method Read(byte[], int, int) #
Read(byte[], int, int) #public override int Read(byte[] buffer, int offset, int count)
See Stream..
method ReadAsync(Memory<byte>, CancellationToken) #
ReadAsync(Memory<byte>, CancellationToken) #public override ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default)
See Stream..
method ReadAsync(byte[], int, int, CancellationToken) #
ReadAsync(byte[], int, int, CancellationToken) #public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
See Stream..
method Seek(long, SeekOrigin) #
Seek(long, SeekOrigin) #public override long Seek(long offset, SeekOrigin origin)
See Stream..
method SetLength(long) #
SetLength(long) #public override void SetLength(long value)
See Stream..
method Write(byte[], int, int) #
Write(byte[], int, int) #public override void Write(byte[] buffer, int offset, int count)
See Stream..
class DefaultAttestationLookupService
public sealed class DefaultAttestationLookupService : IAttestationLookupService
Default implementation of attestation lookup service.
Members
| Member | Kind | Summary |
|---|---|---|
DefaultAttestationLookupService( | constructor | Creates the lookup service. |
CheckAttestationsAsync( | method | Looks up attestations for an artifact digest. |
constructor DefaultAttestationLookupService(ILogger<DefaultAttestationLookupService>, HttpClient, string) #
DefaultAttestationLookupService(ILogger<DefaultAttestationLookupService>, HttpClient, string) #public DefaultAttestationLookupService(ILogger<DefaultAttestationLookupService> logger, HttpClient? httpClient = null, string? attestorUrl = null)
Creates the lookup service.
Parameters
logger: Receives the diagnostics.httpClient: The client that calls the attestor; none when not set.attestorUrl: The attestor address; none when not set.
method CheckAttestationsAsync(string, IEnumerable<string>, CancellationToken) #
CheckAttestationsAsync(string, IEnumerable<string>, CancellationToken) #public Task<AttestationCheckResult> CheckAttestationsAsync(string digest, IEnumerable<string> requiredTypes, CancellationToken ct = default)
Looks up attestations for an artifact digest.
class EndpointResolutionMiddleware
public sealed class EndpointResolutionMiddleware
Resolves incoming HTTP requests to endpoint descriptors using the routing state.
Members
| Member | Kind | Summary |
|---|---|---|
EndpointResolutionMiddleware( | constructor | Initializes a new instance of the EndpointResolutionMiddlewareclass. |
Invoke( | method | Invokes the middleware. |
constructor EndpointResolutionMiddleware(RequestDelegate, IOptions<RoutingOptions>) #
EndpointResolutionMiddleware(RequestDelegate, IOptions<RoutingOptions>) #public EndpointResolutionMiddleware(RequestDelegate next, IOptions<RoutingOptions>? routingOptions = null)
Initializes a new instance of the EndpointResolutionMiddlewareclass.
Parameters
next: The next middleware.routingOptions: The routing options; their default version applies to a request that names none.
method Invoke(HttpContext, IGlobalRoutingState) #
Invoke(HttpContext, IGlobalRoutingState) #public Task Invoke(HttpContext context, IGlobalRoutingState routingState)
Invokes the middleware.
class GlobalErrorHandlerMiddleware
public sealed class GlobalErrorHandlerMiddleware
Catches unhandled exceptions and returns a structured JSON error response.
Members
| Member | Kind | Summary |
|---|---|---|
GlobalErrorHandlerMiddleware( | constructor | Creates the middleware. |
Invoke( | method | Runs the rest of the pipeline and answers an unhandled exception with a 500 problem response. |
constructor GlobalErrorHandlerMiddleware(RequestDelegate, ILogger<GlobalErrorHandlerMiddleware>, IHostEnvironment) #
GlobalErrorHandlerMiddleware(RequestDelegate, ILogger<GlobalErrorHandlerMiddleware>, IHostEnvironment) #public GlobalErrorHandlerMiddleware(RequestDelegate next, ILogger<GlobalErrorHandlerMiddleware> logger, IHostEnvironment environment)
Creates the middleware.
Parameters
next: The next middleware.logger: Receives the diagnostics.environment: The host environment.
method Invoke(HttpContext) #
Invoke(HttpContext) #public Task Invoke(HttpContext context)
Runs the rest of the pipeline and answers an unhandled exception with a 500 problem response.
Parameters
context: The HTTP context.
Returns
A task that completes when the request is handled.
interface IAttestationLookupService
public interface IAttestationLookupService
Service for looking up attestations.
Members
| Member | Kind | Summary |
|---|---|---|
CheckAttestationsAsync( | method | Looks up attestations for an artifact digest. |
method CheckAttestationsAsync(string, IEnumerable<string>, CancellationToken) #
CheckAttestationsAsync(string, IEnumerable<string>, CancellationToken) #Task<AttestationCheckResult> CheckAttestationsAsync(string digest, IEnumerable<string> requiredTypes, CancellationToken ct = default)
Looks up attestations for an artifact digest.
interface IPayloadTracker
public interface IPayloadTracker
Tracks payload bytes across requests, connections, and globally.
Members
| Member | Kind | Summary |
|---|---|---|
CurrentInflightBytes | property | Gets the current total inflight bytes across all connections. |
IsOverloaded | property | Gets a value indicating whether the system is overloaded. |
GetConnectionInflightBytes( | method | Gets the current inflight bytes for a specific connection. |
Release( | method | Releases previously reserved capacity. |
TryReserve( | method | Tries to reserve capacity for an estimated payload size. |
property CurrentInflightBytes #
CurrentInflightBytes #long CurrentInflightBytes { get; }
Gets the current total inflight bytes across all connections.
property IsOverloaded #
IsOverloaded #bool IsOverloaded { get; }
Gets a value indicating whether the system is overloaded.
method GetConnectionInflightBytes(string) #
GetConnectionInflightBytes(string) #long GetConnectionInflightBytes(string connectionId)
Gets the current inflight bytes for a specific connection.
Parameters
connectionId: The connection identifier.
Returns
The current inflight bytes for the connection.
method Release(string, long) #
Release(string, long) #void Release(string connectionId, long actualBytes)
Releases previously reserved capacity.
Parameters
connectionId: The connection identifier.actualBytes: The actual bytes to release.
method TryReserve(string, long) #
TryReserve(string, long) #bool TryReserve(string connectionId, long estimatedBytes)
Tries to reserve capacity for an estimated payload size.
Parameters
connectionId: The connection identifier.estimatedBytes: The estimated bytes to reserve.
Returns
True if capacity was reserved; false if limits would be exceeded.
class PayloadLimitExceededException
public sealed class PayloadLimitExceededException : Exception
Exception thrown when a payload limit is exceeded during streaming.
Members
| Member | Kind | Summary |
|---|---|---|
PayloadLimitExceededException( | constructor | Initializes a new instance of the PayloadLimitExceededExceptionclass. |
BytesRead | property | Gets the number of bytes read before the limit was exceeded. |
Limit | property | Gets the limit that was exceeded. |
constructor PayloadLimitExceededException(long, long) #
PayloadLimitExceededException(long, long) #public PayloadLimitExceededException(long bytesRead, long limit)
Initializes a new instance of the PayloadLimitExceededExceptionclass.
Parameters
bytesRead: The number of bytes read before the limit was exceeded.limit: The limit that was exceeded.
property BytesRead #
BytesRead #public long BytesRead { get; }
Gets the number of bytes read before the limit was exceeded.
property Limit #
Limit #public long Limit { get; }
Gets the limit that was exceeded.
class PayloadLimitsMiddleware
public sealed class PayloadLimitsMiddleware
Middleware that enforces payload limits per-request, per-connection, and aggregate.
Members
| Member | Kind | Summary |
|---|---|---|
PayloadLimitsMiddleware( | constructor | Initializes a new instance of the PayloadLimitsMiddlewareclass. |
Invoke( | method | Invokes the middleware. |
constructor PayloadLimitsMiddleware(RequestDelegate, IOptions<PayloadLimits>, ILogger<PayloadLimitsMiddleware>) #
PayloadLimitsMiddleware(RequestDelegate, IOptions<PayloadLimits>, ILogger<PayloadLimitsMiddleware>) #public PayloadLimitsMiddleware(RequestDelegate next, IOptions<PayloadLimits> limits, ILogger<PayloadLimitsMiddleware> logger)
Initializes a new instance of the PayloadLimitsMiddlewareclass.
method Invoke(HttpContext, IPayloadTracker) #
Invoke(HttpContext, IPayloadTracker) #public Task Invoke(HttpContext context, IPayloadTracker tracker)
Invokes the middleware.
class PayloadTracker
public sealed class PayloadTracker : IPayloadTracker
Default implementation of IPayloadTracker.
Members
| Member | Kind | Summary |
|---|---|---|
PayloadTracker( | constructor | Initializes a new instance of the PayloadTrackerclass. |
CurrentInflightBytes | property | Gets the current total inflight bytes across all connections. |
IsOverloaded | property | Gets a value indicating whether the system is overloaded. |
GetConnectionInflightBytes( | method | Gets the current inflight bytes for a specific connection. |
Release( | method | Releases previously reserved capacity. |
TryReserve( | method | Tries to reserve capacity for an estimated payload size. |
constructor PayloadTracker(IOptions<PayloadLimits>, ILogger<PayloadTracker>) #
PayloadTracker(IOptions<PayloadLimits>, ILogger<PayloadTracker>) #public PayloadTracker(IOptions<PayloadLimits> limits, ILogger<PayloadTracker> logger)
Initializes a new instance of the PayloadTrackerclass.
property CurrentInflightBytes #
CurrentInflightBytes #public long CurrentInflightBytes { get; }
Gets the current total inflight bytes across all connections.
property IsOverloaded #
IsOverloaded #public bool IsOverloaded { get; }
Gets a value indicating whether the system is overloaded.
method GetConnectionInflightBytes(string) #
GetConnectionInflightBytes(string) #public long GetConnectionInflightBytes(string connectionId)
Gets the current inflight bytes for a specific connection.
Parameters
connectionId: The connection identifier.
Returns
The current inflight bytes for the connection.
method Release(string, long) #
Release(string, long) #public void Release(string connectionId, long actualBytes)
Releases previously reserved capacity.
Parameters
connectionId: The connection identifier.actualBytes: The actual bytes to release.
method TryReserve(string, long) #
TryReserve(string, long) #public bool TryReserve(string connectionId, long estimatedBytes)
Tries to reserve capacity for an estimated payload size.
Parameters
connectionId: The connection identifier.estimatedBytes: The estimated bytes to reserve.
Returns
True if capacity was reserved; false if limits would be exceeded.
class RequestLoggingMiddleware
public sealed class RequestLoggingMiddleware
Logs basic request/response information for gateway requests.
Members
| Member | Kind | Summary |
|---|---|---|
RequestLoggingMiddleware( | constructor | Creates the middleware. |
Invoke( | method | Runs the rest of the pipeline and logs the request with its status and duration. |
constructor RequestLoggingMiddleware(RequestDelegate, ILogger<RequestLoggingMiddleware>) #
RequestLoggingMiddleware(RequestDelegate, ILogger<RequestLoggingMiddleware>) #public RequestLoggingMiddleware(RequestDelegate next, ILogger<RequestLoggingMiddleware> logger)
Creates the middleware.
Parameters
next: The next middleware.logger: Receives the diagnostics.
method Invoke(HttpContext) #
Invoke(HttpContext) #public Task Invoke(HttpContext context)
Runs the rest of the pipeline and logs the request with its status and duration.
Parameters
context: The HTTP context.
Returns
A task that completes when the request is handled.
class RouterErrorWriter
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.
Members
| Member | Kind | Summary |
|---|---|---|
WriteAsync( | method | Writes an RFC 7807 problem response, unless the response has started. |
method WriteAsync(HttpContext, int, string, string, string, string, IReadOnlyDictionary<string, object>, CancellationToken) #
WriteAsync(HttpContext, int, string, string, string, string, IReadOnlyDictionary<string, object>, CancellationToken) #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
context: The HTTP context.statusCode: The status code.error: The error title.message: The detail.service: The service the request was for.version: The service version.details: Structured details.cancellationToken: Cancels the write.
Returns
A task that completes when the response is written.
class RoutingDecisionMiddleware
public sealed class RoutingDecisionMiddleware
Makes routing decisions for resolved endpoints.
Members
| Member | Kind | Summary |
|---|---|---|
RoutingDecisionMiddleware( | constructor | Initializes a new instance of the RoutingDecisionMiddlewareclass. |
Invoke( | method | Invokes the middleware. |
constructor RoutingDecisionMiddleware(RequestDelegate) #
RoutingDecisionMiddleware(RequestDelegate) #public RoutingDecisionMiddleware(RequestDelegate next)
Initializes a new instance of the RoutingDecisionMiddlewareclass.
method Invoke(HttpContext, IRoutingPlugin, IGlobalRoutingState, IOptions<RouterNodeConfig>, IOptions<RoutingOptions>) #
Invoke(HttpContext, IRoutingPlugin, IGlobalRoutingState, IOptions<RouterNodeConfig>, IOptions<RoutingOptions>) #public Task Invoke(HttpContext context, IRoutingPlugin routingPlugin, IGlobalRoutingState routingState, IOptions<RouterNodeConfig> gatewayConfig, IOptions<RoutingOptions> routingOptions)
Invokes the middleware.
class TransportDispatchMiddleware
public sealed class TransportDispatchMiddleware
Dispatches HTTP requests to microservices via the transport layer.
Members
| Member | Kind | Summary |
|---|---|---|
TransportDispatchMiddleware( | constructor | Initializes a new instance of the TransportDispatchMiddlewareclass. |
Invoke( | method | Invokes the middleware. |
constructor TransportDispatchMiddleware(RequestDelegate, ILogger<TransportDispatchMiddleware>, IHostEnvironment, IOptions<PayloadLimits>) #
TransportDispatchMiddleware(RequestDelegate, ILogger<TransportDispatchMiddleware>, IHostEnvironment, IOptions<PayloadLimits>) #public TransportDispatchMiddleware(RequestDelegate next, ILogger<TransportDispatchMiddleware> logger, IHostEnvironment environment, IOptions<PayloadLimits> limits)
Initializes a new instance of the TransportDispatchMiddlewareclass.
Parameters
next: The next middleware.logger: The logger.environment: The host environment.limits: The payload limits; the streaming dispatch reads the request body up toPayloadLimits..MaxRequestBytesPerCall
method Invoke(HttpContext, ITransportClient, IGlobalRoutingState, IRouterGatewayMetrics) #
Invoke(HttpContext, ITransportClient, IGlobalRoutingState, IRouterGatewayMetrics) #public Task Invoke(HttpContext context, ITransportClient transportClient, IGlobalRoutingState routingState, IRouterGatewayMetrics metrics)
Invokes the middleware.
namespace StellaOps.Router.Gateway.OpenApi
| Type | Kind | Description |
|---|---|---|
GatewayRouteCatalog | class | Provides the configured gateway route table for OpenAPI path projection. |
IOpenApiDocumentGenerator | interface | Generates OpenAPI documents from aggregated microservice schemas. |
IRouterOpenApiDocumentCache | interface | Caches the generated OpenAPI document with TTL-based expiration. |
OpenApiAggregationOptions | class | Configuration options for OpenAPI document aggregation. |
OpenApiDocumentGenerator | class | Generates OpenAPI 3.1.0 documents from aggregated microservice schemas. |
OpenApiEndpoints | class | Endpoints for serving OpenAPI documentation. |
OpenApiYaml | class | Writes an OpenAPI document given as JSON as YAML. |
RouterOpenApiDocumentCache | class | Caches the generated OpenAPI document with TTL-based expiration. |
class GatewayRouteCatalog
public sealed class GatewayRouteCatalog
Provides the configured gateway route table for OpenAPI path projection.
Members
| Member | Kind | Summary |
|---|---|---|
GatewayRouteCatalog( | constructor | Initializes a new instance of the GatewayRouteCatalogclass. |
Routes | property | Gets the configured gateway routes. |
constructor GatewayRouteCatalog(IEnumerable<StellaOpsRoute>) #
GatewayRouteCatalog(IEnumerable<StellaOpsRoute>) #public GatewayRouteCatalog(IEnumerable<StellaOpsRoute> routes)
Initializes a new instance of the GatewayRouteCatalogclass.
Parameters
routes: Configured gateway routes.
property Routes #
Routes #public IReadOnlyList<StellaOpsRoute> Routes { get; }
Gets the configured gateway routes.
interface IOpenApiDocumentGenerator
public interface IOpenApiDocumentGenerator
Generates OpenAPI documents from aggregated microservice schemas.
Members
| Member | Kind | Summary |
|---|---|---|
GenerateDocument( | method | Generates the OpenAPI 3.1.0 document as JSON. |
method GenerateDocument() #
GenerateDocument() #string GenerateDocument()
Generates the OpenAPI 3.1.0 document as JSON.
Returns
The OpenAPI document as a JSON string.
interface IRouterOpenApiDocumentCache
public interface IRouterOpenApiDocumentCache
Caches the generated OpenAPI document with TTL-based expiration.
Members
| Member | Kind | Summary |
|---|---|---|
GetDocument( | method | Gets the cached document or regenerates if expired. |
Invalidate( | method | Invalidates the cache, forcing regeneration on next access. |
method GetDocument() #
GetDocument() #(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.
method Invalidate() #
Invalidate() #void Invalidate()
Invalidates the cache, forcing regeneration on next access.
class OpenApiAggregationOptions
public sealed class OpenApiAggregationOptions
Configuration options for OpenAPI document aggregation.
Members
| Member | Kind | Summary |
|---|---|---|
OpenApiAggregationOptions( | constructor | Creates an instance of Open. |
SectionName | constant | The configuration section name. |
CacheTtlSeconds | property | Gets or sets the cache TTL in seconds. |
ContactEmail | property | Gets or sets the contact email. |
ContactName | property | Gets or sets the contact name. |
Description | property | Gets or sets the API description. |
Enabled | property | Gets or sets whether OpenAPI aggregation is enabled. |
LicenseName | property | Gets or sets the license name of the API the document describes (info.license.name). |
ServerUrl | property | Gets or sets the server URL. |
Title | property | Gets or sets the API title. |
TokenUrl | property | Gets or sets the OAuth2 token URL of the client-credentials flow that the scopes of the endpoints are obtained from. |
Version | property | Gets or sets the API version. |
constructor OpenApiAggregationOptions() #
OpenApiAggregationOptions() #public OpenApiAggregationOptions()
Creates an instance of Open.
constant SectionName #
SectionName #public const string SectionName = "Router:OpenApi"
The configuration section name.
property CacheTtlSeconds #
CacheTtlSeconds #public int CacheTtlSeconds { get; set; }
Gets or sets the cache TTL in seconds.
property ContactEmail #
ContactEmail #public string? ContactEmail { get; set; }
Gets or sets the contact email.
property ContactName #
ContactName #public string? ContactName { get; set; }
Gets or sets the contact name.
property Description #
Description #public string Description { get; set; }
Gets or sets the API description.
property Enabled #
Enabled #public bool Enabled { get; set; }
Gets or sets whether OpenAPI aggregation is enabled.
property LicenseName #
LicenseName #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.
property ServerUrl #
ServerUrl #public string ServerUrl { get; set; }
Gets or sets the server URL.
property Title #
Title #public string Title { get; set; }
Gets or sets the API title.
property TokenUrl #
TokenUrl #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.
property Version #
Version #public string Version { get; set; }
Gets or sets the API version.
class OpenApiDocumentGenerator
public sealed class OpenApiDocumentGenerator : IOpenApiDocumentGenerator
Generates OpenAPI 3.1.0 documents from aggregated microservice schemas.
Members
| Member | Kind | Summary |
|---|---|---|
OpenApiDocumentGenerator( | constructor | Creates the generator. |
GenerateDocument( | method | Generates the OpenAPI 3.1.0 document as JSON. |
constructor OpenApiDocumentGenerator(IGlobalRoutingState, IOptions<OpenApiAggregationOptions>, GatewayRouteCatalog, IOptions<RoutingOptions>, IEffectiveClaimsStore) #
OpenApiDocumentGenerator(IGlobalRoutingState, IOptions<OpenApiAggregationOptions>, GatewayRouteCatalog, IOptions<RoutingOptions>, IEffectiveClaimsStore) #public OpenApiDocumentGenerator(IGlobalRoutingState routingState, IOptions<OpenApiAggregationOptions> options, GatewayRouteCatalog? routeCatalog = null, IOptions<RoutingOptions>? routingOptions = null, IEffectiveClaimsStore? effectiveClaimsStore = null)
Creates the generator.
Parameters
routingState: The connected instances and their endpoints.options: The OpenAPI document settings.routeCatalog: The static routes, when there are any.routingOptions: The routing options, when given.effectiveClaimsStore: The effective claim requirements, when given.
method GenerateDocument() #
GenerateDocument() #public string GenerateDocument()
Generates the OpenAPI 3.1.0 document as JSON.
Returns
The OpenAPI document as a JSON string.
class OpenApiEndpoints
public static class OpenApiEndpoints
Endpoints for serving OpenAPI documentation.
Members
| Member | Kind | Summary |
|---|---|---|
MapRouterOpenApiEndpoints( | extension method | Maps OpenAPI endpoints to the application. |
extension method MapRouterOpenApiEndpoints(IEndpointRouteBuilder) #
MapRouterOpenApiEndpoints(IEndpointRouteBuilder) #public static IEndpointRouteBuilder MapRouterOpenApiEndpoints(this IEndpointRouteBuilder endpoints)
Maps OpenAPI endpoints to the application.
class OpenApiYaml
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.
Members
| Member | Kind | Summary |
|---|---|---|
FromJson( | method | Converts a parsed OpenAPI document to YAML; an empty string for null. |
FromJson( | method | Converts the JSON text of an OpenAPI document to YAML; an empty string for a JSON null. |
method FromJson(JsonNode) #
FromJson(JsonNode) #public static string FromJson(JsonNode? document)
Converts a parsed OpenAPI document to YAML; an empty string for null.
Parameters
document: The parsed document.
Returns
The document as YAML.
method FromJson(string) #
FromJson(string) #public static string FromJson(string documentJson)
Converts the JSON text of an OpenAPI document to YAML; an empty string for a JSON null.
Parameters
documentJson: The document as JSON.
Returns
The document as YAML.
class RouterOpenApiDocumentCache
public sealed class RouterOpenApiDocumentCache : IRouterOpenApiDocumentCache
Caches the generated OpenAPI document with TTL-based expiration.
Members
| Member | Kind | Summary |
|---|---|---|
RouterOpenApiDocumentCache( | constructor | Creates the cache. |
GetDocument( | method | Gets the cached document or regenerates if expired. |
Invalidate( | method | Invalidates the cache, forcing regeneration on next access. |
constructor RouterOpenApiDocumentCache(IOpenApiDocumentGenerator, IOptions<OpenApiAggregationOptions>) #
RouterOpenApiDocumentCache(IOpenApiDocumentGenerator, IOptions<OpenApiAggregationOptions>) #public RouterOpenApiDocumentCache(IOpenApiDocumentGenerator generator, IOptions<OpenApiAggregationOptions> options)
Creates the cache.
Parameters
generator: Builds the document.options: The OpenAPI settings, with the cache lifetime.
method GetDocument() #
GetDocument() #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.
method Invalidate() #
Invalidate() #public void Invalidate()
Invalidates the cache, forcing regeneration on next access.
namespace StellaOps.Router.Gateway.RateLimit
| Type | Kind | Description |
|---|---|---|
CircuitBreaker | class | Circuit breaker for Valkey operations. |
CircuitBreakerConfig | class | Circuit breaker configuration for Valkey resilience. |
CircuitState | enum | Circuit breaker state. |
EnvironmentLimitsConfig | class | Environment-level rate limit configuration (Valkey-backed). |
EnvironmentRateLimiter | class | Valkey-backed rate limiter for environment-level protection. |
IValkeyRateLimitStore | interface | Interface for Valkey rate limit store operations. |
InMemoryValkeyRateLimitStore | class | In-memory fixed-window rate limit store (primarily for tests). |
InstanceLimitsConfig | class | Instance-level rate limit configuration (in-memory). |
InstanceRateLimiter | class | In-memory rate limiter for instance-level protection. |
MicroserviceLimitsConfig | class | Per-microservice rate limit overrides. |
RateLimitConfig | class | Root configuration for Router rate limiting. |
RateLimitDecision | record | Result of a rate limit check. |
RateLimitMetrics | class | OpenTelemetry metrics for Router rate limiting. |
RateLimitMiddleware | class | Middleware that enforces rate limits on incoming requests. |
RateLimitRule | class | A single rate limit rule (window + max requests). |
RateLimitScope | enum | Rate limit scope. |
RateLimitService | class | Service that orchestrates rate limit checks across instance and environment scopes. |
RateLimitServiceCollectionExtensions | class | Extension methods for registering rate limiting services. |
RateLimitStoreResult | record | Result of a Valkey rate limit check. |
RouteLimitsConfig | class | Per-route rate limit configuration. |
RouteMatchType | enum | How a route rate limit pattern matches a request path. |
class CircuitBreaker
public sealed class CircuitBreaker
Circuit breaker for Valkey operations. Provides fail-open behavior when Valkey is unavailable.
Members
| Member | Kind | Summary |
|---|---|---|
CircuitBreaker( | constructor | Creates a closed circuit breaker. |
IsHalfOpen | property | Whether the circuit is half-open (testing recovery). |
IsOpen | property | Whether the circuit is open (requests should bypass Valkey). |
State | property | Current state of the circuit. |
RecordFailure( | method | Record a failed operation. |
RecordSuccess( | method | Record a successful operation. |
Reset( | method | Reset the circuit breaker. |
constructor CircuitBreaker(int, int, int) #
CircuitBreaker(int, int, int) #public CircuitBreaker(int failureThreshold, int timeoutSeconds, int halfOpenTimeout)
Creates a closed circuit breaker.
Parameters
failureThreshold: The failures that open the circuit, at least 1.timeoutSeconds: How long the circuit stays open, in seconds, at least 1.halfOpenTimeout: How long the circuit stays half open, in seconds, at least 1.
property IsHalfOpen #
IsHalfOpen #public bool IsHalfOpen { get; }
Whether the circuit is half-open (testing recovery).
property IsOpen #
IsOpen #public bool IsOpen { get; }
Whether the circuit is open (requests should bypass Valkey).
property State #
State #public CircuitState State { get; }
Current state of the circuit.
method RecordFailure() #
RecordFailure() #public void RecordFailure()
Record a failed operation.
method RecordSuccess() #
RecordSuccess() #public void RecordSuccess()
Record a successful operation.
method Reset() #
Reset() #public void Reset()
Reset the circuit breaker.
class CircuitBreakerConfig
public sealed class CircuitBreakerConfig
Circuit breaker configuration for Valkey resilience.
Members
| Member | Kind | Summary |
|---|---|---|
CircuitBreakerConfig( | constructor | Creates an instance of CircuitBreakerConfig. |
FailureThreshold | property | Number of failures before opening the circuit. |
HalfOpenTimeout | property | Seconds in half-open state before full reset. |
TimeoutSeconds | property | Seconds to keep circuit open. |
Validate( | method | Validate configuration. |
constructor CircuitBreakerConfig() #
CircuitBreakerConfig() #public CircuitBreakerConfig()
Creates an instance of CircuitBreakerConfig.
property FailureThreshold #
FailureThreshold #public int FailureThreshold { get; set; }
Number of failures before opening the circuit.
property HalfOpenTimeout #
HalfOpenTimeout #public int HalfOpenTimeout { get; set; }
Seconds in half-open state before full reset.
property TimeoutSeconds #
TimeoutSeconds #public int TimeoutSeconds { get; set; }
Seconds to keep circuit open.
method Validate(string) #
Validate(string) #public void Validate(string path)
Validate configuration.
enum CircuitState
public enum CircuitState
Circuit breaker state.
| Value | Description |
|---|---|
Closed = 0 | Circuit is closed, requests flow through. |
Open = 1 | Circuit is open, requests are blocked. |
HalfOpen = 2 | Circuit is testing recovery. |
class EnvironmentLimitsConfig
public sealed class EnvironmentLimitsConfig
Environment-level rate limit configuration (Valkey-backed).
Members
| Member | Kind | Summary |
|---|---|---|
EnvironmentLimitsConfig( | constructor | Creates an instance of Environment. |
AllowBurstForSeconds | property | Burst window in seconds. |
AllowMaxBurstRequests | property | Maximum burst requests. |
CircuitBreaker | property | Circuit breaker configuration. |
MaxRequests | property | Maximum requests in the time window. |
Microservices | property | Per-microservice overrides. |
PerSeconds | property | Time window in seconds. |
Rules | property | Multi-rule configuration (preferred). |
ValkeyBucket | property | Valkey bucket/prefix for rate limit keys. |
ValkeyConnection | property | Valkey connection string. |
GetEffectiveRules( | method | 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. |
Validate( | method | Validate configuration. |
constructor EnvironmentLimitsConfig() #
EnvironmentLimitsConfig() #public EnvironmentLimitsConfig()
Creates an instance of Environment.
property AllowBurstForSeconds #
AllowBurstForSeconds #public int AllowBurstForSeconds { get; set; }
Burst window in seconds.
property AllowMaxBurstRequests #
AllowMaxBurstRequests #public int AllowMaxBurstRequests { get; set; }
Maximum burst requests.
property CircuitBreaker #
CircuitBreaker #public CircuitBreakerConfig? CircuitBreaker { get; set; }
Circuit breaker configuration.
property MaxRequests #
MaxRequests #public int MaxRequests { get; set; }
Maximum requests in the time window.
property Microservices #
Microservices #public Dictionary<string, MicroserviceLimitsConfig>? Microservices { get; set; }
Per-microservice overrides.
property PerSeconds #
PerSeconds #public int PerSeconds { get; set; }
Time window in seconds.
property Rules #
Rules #public List<RateLimitRule> Rules { get; set; }
Multi-rule configuration (preferred). When specified, takes precedence over the single-window fields.
property ValkeyBucket #
ValkeyBucket #public string ValkeyBucket { get; set; }
Valkey bucket/prefix for rate limit keys.
property ValkeyConnection #
ValkeyConnection #public string ValkeyConnection { get; set; }
Valkey connection string.
method GetEffectiveRules() #
GetEffectiveRules() #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.
method Validate(string) #
Validate(string) #public void Validate(string path)
Validate configuration.
class EnvironmentRateLimiter
public sealed class EnvironmentRateLimiter : IDisposable
Valkey-backed rate limiter for environment-level protection. Uses fixed-window counters with atomic Lua operations.
Members
| Member | Kind | Summary |
|---|---|---|
EnvironmentRateLimiter( | constructor | Creates the limiter. |
Dispose( | method | Releases the limiter. |
TryAcquireAsync( | method | Try to acquire a request slot. |
constructor EnvironmentRateLimiter(IValkeyRateLimitStore, CircuitBreaker, ILogger<EnvironmentRateLimiter>) #
EnvironmentRateLimiter(IValkeyRateLimitStore, CircuitBreaker, ILogger<EnvironmentRateLimiter>) #public EnvironmentRateLimiter(IValkeyRateLimitStore store, CircuitBreaker circuitBreaker, ILogger<EnvironmentRateLimiter> logger)
Creates the limiter.
Parameters
store: The shared counter store.circuitBreaker: Stops calls to the store after repeated failures.logger: Receives the diagnostics.
method Dispose() #
Dispose() #public void Dispose()
Releases the limiter.
method TryAcquireAsync(string, string, IReadOnlyList<RateLimitRule>, CancellationToken) #
TryAcquireAsync(string, string, IReadOnlyList<RateLimitRule>, CancellationToken) #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).
interface IValkeyRateLimitStore
public interface IValkeyRateLimitStore
Interface for Valkey rate limit store operations.
Members
| Member | Kind | Summary |
|---|---|---|
IncrementAndCheckAsync( | method | Atomically increment counters for the provided rules and determine if the request is allowed. |
method IncrementAndCheckAsync(string, IReadOnlyList<RateLimitRule>, CancellationToken) #
IncrementAndCheckAsync(string, IReadOnlyList<RateLimitRule>, CancellationToken) #Task<RateLimitStoreResult> IncrementAndCheckAsync(string key, IReadOnlyList<RateLimitRule> rules, CancellationToken cancellationToken)
Atomically increment counters for the provided rules and determine if the request is allowed.
class InMemoryValkeyRateLimitStore
public sealed class InMemoryValkeyRateLimitStore : IValkeyRateLimitStore
In-memory fixed-window rate limit store (primarily for tests).
Members
| Member | Kind | Summary |
|---|---|---|
InMemoryValkeyRateLimitStore( | constructor | Creates an instance of In. |
IncrementAndCheckAsync( | method | Atomically increment counters for the provided rules and determine if the request is allowed. |
Reset( | method | Clears every counter. |
constructor InMemoryValkeyRateLimitStore() #
InMemoryValkeyRateLimitStore() #public InMemoryValkeyRateLimitStore()
Creates an instance of In.
method IncrementAndCheckAsync(string, IReadOnlyList<RateLimitRule>, CancellationToken) #
IncrementAndCheckAsync(string, IReadOnlyList<RateLimitRule>, CancellationToken) #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.
method Reset() #
Reset() #public void Reset()
Clears every counter.
class InstanceLimitsConfig
public sealed class InstanceLimitsConfig
Instance-level rate limit configuration (in-memory).
Members
| Member | Kind | Summary |
|---|---|---|
InstanceLimitsConfig( | constructor | Creates an instance of InstanceLimitsConfig. |
AllowBurstForSeconds | property | Burst window in seconds. |
AllowMaxBurstRequests | property | Maximum burst requests. |
MaxRequests | property | Maximum requests in the time window. |
PerSeconds | property | Time window in seconds. |
Rules | property | Multi-rule configuration (preferred). |
GetEffectiveRules( | method | 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. |
Validate( | method | Validate configuration. |
constructor InstanceLimitsConfig() #
InstanceLimitsConfig() #public InstanceLimitsConfig()
Creates an instance of InstanceLimitsConfig.
property AllowBurstForSeconds #
AllowBurstForSeconds #public int AllowBurstForSeconds { get; set; }
Burst window in seconds.
property AllowMaxBurstRequests #
AllowMaxBurstRequests #public int AllowMaxBurstRequests { get; set; }
Maximum burst requests.
property MaxRequests #
MaxRequests #public int MaxRequests { get; set; }
Maximum requests in the time window.
property PerSeconds #
PerSeconds #public int PerSeconds { get; set; }
Time window in seconds.
property Rules #
Rules #public List<RateLimitRule> Rules { get; set; }
Multi-rule configuration (preferred). When specified, takes precedence over the single-window fields.
method GetEffectiveRules() #
GetEffectiveRules() #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.
method Validate(string) #
Validate(string) #public void Validate(string path)
Validate configuration.
class InstanceRateLimiter
public sealed class InstanceRateLimiter : IDisposable
In-memory rate limiter for instance-level protection. Uses sliding window counters for fair rate limiting.
Members
| Member | Kind | Summary |
|---|---|---|
InstanceRateLimiter( | constructor | Create instance rate limiter with default limits. |
Dispose( | method | Releases the limiter. |
GetCurrentCount( | method | Get current request count for a microservice. |
Reset( | method | Reset counters (for testing). |
TryAcquire( | method | Try to acquire a request slot. |
constructor InstanceRateLimiter(IReadOnlyList<RateLimitRule>, TimeProvider) #
InstanceRateLimiter(IReadOnlyList<RateLimitRule>, TimeProvider) #public InstanceRateLimiter(IReadOnlyList<RateLimitRule> defaultRules, TimeProvider? timeProvider = null)
Create instance rate limiter with default limits.
method Dispose() #
Dispose() #public void Dispose()
Releases the limiter.
method GetCurrentCount(string) #
GetCurrentCount(string) #public long GetCurrentCount(string microservice)
Get current request count for a microservice.
method Reset() #
Reset() #public void Reset()
Reset counters (for testing).
method TryAcquire(string, IReadOnlyList<RateLimitRule>) #
TryAcquire(string, IReadOnlyList<RateLimitRule>) #public RateLimitDecision TryAcquire(string microservice, IReadOnlyList<RateLimitRule>? rules = null)
Try to acquire a request slot.
Parameters
microservice: Target microservice name.rules: Optional rule overrides.
Returns
Decision indicating whether request is allowed.
class MicroserviceLimitsConfig
public sealed class MicroserviceLimitsConfig
Per-microservice rate limit overrides.
Members
| Member | Kind | Summary |
|---|---|---|
MicroserviceLimitsConfig( | constructor | Creates an instance of Microservice. |
AllowBurstForSeconds | property | Burst window in seconds (optional). |
AllowMaxBurstRequests | property | Maximum burst requests (optional). |
MaxRequests | property | Maximum requests in the time window. |
PerSeconds | property | Time window in seconds. |
Routes | property | Per-route overrides (best match wins). |
Rules | property | Multi-rule configuration (preferred). |
GetEffectiveRules( | method | 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. |
Validate( | method | Validate configuration. |
constructor MicroserviceLimitsConfig() #
MicroserviceLimitsConfig() #public MicroserviceLimitsConfig()
Creates an instance of Microservice.
property AllowBurstForSeconds #
AllowBurstForSeconds #public int? AllowBurstForSeconds { get; set; }
Burst window in seconds (optional).
property AllowMaxBurstRequests #
AllowMaxBurstRequests #public int? AllowMaxBurstRequests { get; set; }
Maximum burst requests (optional).
property MaxRequests #
MaxRequests #public int? MaxRequests { get; set; }
Maximum requests in the time window.
property PerSeconds #
PerSeconds #public int? PerSeconds { get; set; }
Time window in seconds.
property Routes #
Routes #public Dictionary<string, RouteLimitsConfig> Routes { get; set; }
Per-route overrides (best match wins).
property Rules #
Rules #public List<RateLimitRule> Rules { get; set; }
Multi-rule configuration (preferred). When specified, takes precedence over the single-window fields.
method GetEffectiveRules() #
GetEffectiveRules() #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.
method Validate(string) #
Validate(string) #public void Validate(string path)
Validate configuration.
class RateLimitConfig
public sealed class RateLimitConfig
Root configuration for Router rate limiting.
Members
| Member | Kind | Summary |
|---|---|---|
RateLimitConfig( | constructor | Creates an instance of RateLimitConfig. |
ActivationThresholdPer5Min | property | Activation gate: only check Valkey when traffic exceeds this threshold per 5 minutes. |
ForEnvironment | property | Environment-level rate limits (Valkey-backed, across all router instances). |
ForInstance | property | Instance-level rate limits (in-memory, per router instance). |
IsEnabled | property | Whether rate limiting is enabled (at least one scope configured). |
Load( | method | Load configuration from IConfiguration. |
Validate( | method | Validate configuration values. |
constructor RateLimitConfig() #
RateLimitConfig() #public RateLimitConfig()
Creates an instance of RateLimitConfig.
property ActivationThresholdPer5Min #
ActivationThresholdPer5Min #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.
property ForEnvironment #
ForEnvironment #public EnvironmentLimitsConfig? ForEnvironment { get; set; }
Environment-level rate limits (Valkey-backed, across all router instances).
property ForInstance #
ForInstance #public InstanceLimitsConfig? ForInstance { get; set; }
Instance-level rate limits (in-memory, per router instance).
property IsEnabled #
IsEnabled #public bool IsEnabled { get; }
Whether rate limiting is enabled (at least one scope configured).
method Load(IConfiguration) #
Load(IConfiguration) #public static RateLimitConfig Load(IConfiguration configuration)
Load configuration from IConfiguration.
method Validate() #
Validate() #public RateLimitConfig Validate()
Validate configuration values.
record RateLimitDecision
public sealed record RateLimitDecision
Result of a rate limit check.
Parameters
Allowed: Whether the request is allowed.RetryAfterSeconds: Seconds to wait before retrying (if not allowed).Scope: Which scope triggered the limit (instance or environment).CurrentCount: Current request count in the window.Limit: The limit that was applied.WindowSeconds: The window size in seconds.Microservice: The microservice that was checked.
Members
| Member | Kind | Summary |
|---|---|---|
RateLimitDecision( | constructor | Result of a rate limit check. |
Allowed | property | Whether the request is allowed. |
CurrentCount | property | Current request count in the window. |
Limit | property | The limit that was applied. |
Microservice | property | The microservice that was checked. |
RetryAfterSeconds | property | Seconds to wait before retrying (if not allowed). |
RetryAt | property | Time remaining until the window resets. |
Scope | property | Which scope triggered the limit (instance or environment). |
WindowSeconds | property | The window size in seconds. |
Allow( | method | Create an “allowed” decision. |
Deny( | method | Create a “denied” decision. |
constructor RateLimitDecision(bool, int, RateLimitScope, long, long, int, string) #
RateLimitDecision(bool, int, RateLimitScope, long, long, int, string) #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: Whether the request is allowed.RetryAfterSeconds: Seconds to wait before retrying (if not allowed).Scope: Which scope triggered the limit (instance or environment).CurrentCount: Current request count in the window.Limit: The limit that was applied.WindowSeconds: The window size in seconds.Microservice: The microservice that was checked.
property Allowed #
Allowed #public bool Allowed { get; init; }
Whether the request is allowed.
property CurrentCount #
CurrentCount #public long CurrentCount { get; init; }
Current request count in the window.
property Limit #
Limit #public long Limit { get; init; }
The limit that was applied.
property Microservice #
Microservice #public string? Microservice { get; init; }
The microservice that was checked.
property RetryAfterSeconds #
RetryAfterSeconds #public int RetryAfterSeconds { get; init; }
Seconds to wait before retrying (if not allowed).
property RetryAt #
RetryAt #public DateTimeOffset RetryAt { get; }
Time remaining until the window resets.
property Scope #
Scope #public RateLimitScope Scope { get; init; }
Which scope triggered the limit (instance or environment).
property WindowSeconds #
WindowSeconds #public int WindowSeconds { get; init; }
The window size in seconds.
method Allow(RateLimitScope, long, long, int, string) #
Allow(RateLimitScope, long, long, int, string) #public static RateLimitDecision Allow(RateLimitScope scope, long currentCount, long limit, int windowSeconds, string? microservice = null)
Create an “allowed” decision.
method Deny(RateLimitScope, int, long, long, int, string) #
Deny(RateLimitScope, int, long, long, int, string) #public static RateLimitDecision Deny(RateLimitScope scope, int retryAfterSeconds, long currentCount, long limit, int windowSeconds, string? microservice = null)
Create a “denied” decision.
class RateLimitMetrics
public static class RateLimitMetrics
OpenTelemetry metrics for Router rate limiting.
Members
| Member | Kind | Summary |
|---|---|---|
MeasureLatency( | method | Measure check latency with a disposable scope. |
RecordCircuitBreakerTrip( | method | Record a circuit breaker trip. |
RecordDecision( | method | Record a rate limit decision. |
RecordDecision( | method | Record a rate limit decision with optional route tag. |
RecordLatency( | method | Record check latency. |
RecordRejection( | method | Record a rate limit rejection. |
RecordValkeyError( | method | Record a Valkey error. |
UpdateEnvironmentCount( | method | Update current environment count gauge. |
UpdateInstanceCount( | method | Update current instance count gauge. |
method MeasureLatency(RateLimitScope) #
MeasureLatency(RateLimitScope) #public static IDisposable MeasureLatency(RateLimitScope scope)
Measure check latency with a disposable scope.
method RecordCircuitBreakerTrip(string) #
RecordCircuitBreakerTrip(string) #public static void RecordCircuitBreakerTrip(string reason)
Record a circuit breaker trip.
method RecordDecision(RateLimitScope, string, bool) #
RecordDecision(RateLimitScope, string, bool) #public static void RecordDecision(RateLimitScope scope, string microservice, bool allowed)
Record a rate limit decision.
method RecordDecision(RateLimitScope, string, string, bool) #
RecordDecision(RateLimitScope, string, string, bool) #public static void RecordDecision(RateLimitScope scope, string microservice, string? routeName, bool allowed)
Record a rate limit decision with optional route tag.
method RecordLatency(RateLimitScope, double) #
RecordLatency(RateLimitScope, double) #public static void RecordLatency(RateLimitScope scope, double milliseconds)
Record check latency.
method RecordRejection(RateLimitScope, string) #
RecordRejection(RateLimitScope, string) #public static void RecordRejection(RateLimitScope scope, string microservice)
Record a rate limit rejection.
method RecordValkeyError(string) #
RecordValkeyError(string) #public static void RecordValkeyError(string errorType)
Record a Valkey error.
method UpdateEnvironmentCount(long) #
UpdateEnvironmentCount(long) #public static void UpdateEnvironmentCount(long count)
Update current environment count gauge.
method UpdateInstanceCount(long) #
UpdateInstanceCount(long) #public static void UpdateInstanceCount(long count)
Update current instance count gauge.
class RateLimitMiddleware
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.
Members
| Member | Kind | Summary |
|---|---|---|
RateLimitMiddleware( | constructor | Creates the middleware. |
InvokeAsync( | method | Checks the rate limits of the request and answers 429 when a limit is exceeded. |
constructor RateLimitMiddleware(RequestDelegate, RateLimitService, ILogger<RateLimitMiddleware>) #
RateLimitMiddleware(RequestDelegate, RateLimitService, ILogger<RateLimitMiddleware>) #public RateLimitMiddleware(RequestDelegate next, RateLimitService rateLimitService, ILogger<RateLimitMiddleware> logger)
Creates the middleware.
Parameters
next: The next middleware.rateLimitService: Checks the limits.logger: Receives the diagnostics.
method InvokeAsync(HttpContext) #
InvokeAsync(HttpContext) #public Task InvokeAsync(HttpContext context)
Checks the rate limits of the request and answers 429 when a limit is exceeded.
Parameters
context: The HTTP context.
Returns
A task that completes when the request is handled.
class RateLimitRule
public sealed class RateLimitRule
A single rate limit rule (window + max requests).
Members
| Member | Kind | Summary |
|---|---|---|
RateLimitRule( | constructor | Creates an instance of RateLimitRule. |
MaxRequests | property | The requests allowed in the window; positive (max_requests). |
Name | property | The rule name, for diagnostics (name). |
PerSeconds | property | The window, in seconds; positive (per_seconds). |
Validate( | method | Validates the rule. |
constructor RateLimitRule() #
RateLimitRule() #public RateLimitRule()
Creates an instance of RateLimitRule.
property MaxRequests #
MaxRequests #public int MaxRequests { get; set; }
The requests allowed in the window; positive (max_requests).
property Name #
Name #public string? Name { get; set; }
The rule name, for diagnostics (name).
property PerSeconds #
PerSeconds #public int PerSeconds { get; set; }
The window, in seconds; positive (per_seconds).
method Validate(string) #
Validate(string) #public void Validate(string path)
Validates the rule.
Parameters
path: The configuration path, for messages.
Exceptions
ArgumentException: A value is not positive.
enum RateLimitScope
public enum RateLimitScope
Rate limit scope.
| Value | Description |
|---|---|
Instance = 0 | Instance-level (in-memory). |
Environment = 1 | Environment-level (Valkey-backed). |
class RateLimitService
public sealed class RateLimitService
Service that orchestrates rate limit checks across instance and environment scopes.
Members
| Member | Kind | Summary |
|---|---|---|
RateLimitService( | constructor | Creates the service. |
CheckLimitAsync( | method | Check rate limits for a request. |
constructor RateLimitService(RateLimitConfig, InstanceRateLimiter, EnvironmentRateLimiter, ILogger<RateLimitService>) #
RateLimitService(RateLimitConfig, InstanceRateLimiter, EnvironmentRateLimiter, ILogger<RateLimitService>) #public RateLimitService(RateLimitConfig config, InstanceRateLimiter? instanceLimiter, EnvironmentRateLimiter? environmentLimiter, ILogger<RateLimitService> logger)
Creates the service.
Parameters
config: The rate limit configuration.instanceLimiter: The process-local limiter, when instance limits are set.environmentLimiter: The shared limiter, when environment limits are set.logger: Receives the diagnostics.
method CheckLimitAsync(string, string, string, CancellationToken) #
CheckLimitAsync(string, string, string, CancellationToken) #public Task<RateLimitDecision> CheckLimitAsync(string? microservice, string? requestPath, string? tenant, CancellationToken cancellationToken)
Check rate limits for a request.
Parameters
microservice: Target microservice.requestPath: HTTP request path.tenant: The caller’s tenant (thestellaops:tenantclaim), or null. Each tenant has its own counters; the service and route overrides and the metrics do not depend on it.cancellationToken: Cancellation token.
Returns
Decision indicating whether request is allowed.
class RateLimitServiceCollectionExtensions
public static class RateLimitServiceCollectionExtensions
Extension methods for registering rate limiting services.
Members
| Member | Kind | Summary |
|---|---|---|
AddRouterRateLimiting( | extension method | Adds rate limiting services to the DI container. |
AddRouterRateLimiting< | extension method | Adds rate limiting with a custom store for the environment rate limit. |
extension method AddRouterRateLimiting(IServiceCollection, IConfiguration) #
AddRouterRateLimiting(IServiceCollection, IConfiguration) #public static IServiceCollection AddRouterRateLimiting(this IServiceCollection services, IConfiguration configuration)
Adds rate limiting services to the DI container.
Parameters
services: The service collection.configuration: The configuration.
Returns
The service collection for chaining.
extension method AddRouterRateLimiting<TStore>(IServiceCollection, IConfiguration) #
AddRouterRateLimiting<TStore>(IServiceCollection, IConfiguration) #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
TStore: The store implementation.
Parameters
services: The service collection.configuration: The configuration.
Returns
The service collection for chaining.
record RateLimitStoreResult
public sealed record RateLimitStoreResult
Result of a Valkey rate limit check.
Parameters
Allowed: Whether the request is allowed.CurrentCount: The count in the window, this request included.Limit: The requests allowed in the window.WindowSeconds: The window, in seconds.RetryAfterSeconds: When the request may be retried, in seconds; 0 when it is allowed.
Members
| Member | Kind | Summary |
|---|---|---|
RateLimitStoreResult( | constructor | Result of a Valkey rate limit check. |
Allowed | property | Whether the request is allowed. |
CurrentCount | property | The count in the window, this request included. |
Limit | property | The requests allowed in the window. |
RetryAfterSeconds | property | When the request may be retried, in seconds; 0 when it is allowed. |
WindowSeconds | property | The window, in seconds. |
constructor RateLimitStoreResult(bool, long, int, int, int) #
RateLimitStoreResult(bool, long, int, int, int) #public RateLimitStoreResult(bool Allowed, long CurrentCount, int Limit, int WindowSeconds, int RetryAfterSeconds)
Result of a Valkey rate limit check.
Parameters
Allowed: Whether the request is allowed.CurrentCount: The count in the window, this request included.Limit: The requests allowed in the window.WindowSeconds: The window, in seconds.RetryAfterSeconds: When the request may be retried, in seconds; 0 when it is allowed.
property Allowed #
Allowed #public bool Allowed { get; init; }
Whether the request is allowed.
property CurrentCount #
CurrentCount #public long CurrentCount { get; init; }
The count in the window, this request included.
property Limit #
Limit #public int Limit { get; init; }
The requests allowed in the window.
property RetryAfterSeconds #
RetryAfterSeconds #public int RetryAfterSeconds { get; init; }
When the request may be retried, in seconds; 0 when it is allowed.
property WindowSeconds #
WindowSeconds #public int WindowSeconds { get; init; }
The window, in seconds.
class RouteLimitsConfig
public sealed class RouteLimitsConfig
Per-route rate limit configuration.
Members
| Member | Kind | Summary |
|---|---|---|
RouteLimitsConfig( | constructor | Creates an instance of RouteLimitsConfig. |
AllowBurstForSeconds | property | The window of the burst limit, in seconds (allow_). |
AllowMaxBurstRequests | property | The requests allowed in the burst window (allow_). |
MatchType | property | How RouteLimitsConfig.matches a path. |
MaxRequests | property | The requests allowed in the window (max_requests). |
Pattern | property | Route pattern: exact (“/api/scans”), prefix (“/api/scans/*”), or regex (“^/api/scans/[a-f0-9-]+$”). |
PerSeconds | property | The window of the single-window limit, in seconds (per_seconds). |
Rules | property | Multi-rule configuration (preferred). |
GetEffectiveRules( | method | 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. |
Validate( | method | Validates the route limits and compiles a regex pattern. |
constructor RouteLimitsConfig() #
RouteLimitsConfig() #public RouteLimitsConfig()
Creates an instance of RouteLimitsConfig.
property AllowBurstForSeconds #
AllowBurstForSeconds #public int? AllowBurstForSeconds { get; set; }
The window of the burst limit, in seconds (allow_).
property AllowMaxBurstRequests #
AllowMaxBurstRequests #public int? AllowMaxBurstRequests { get; set; }
The requests allowed in the burst window (allow_).
property MatchType #
MatchType #public RouteMatchType MatchType { get; set; }
How RouteLimitsConfig.matches a path. The default is RouteMatchType..
property MaxRequests #
MaxRequests #public int? MaxRequests { get; set; }
The requests allowed in the window (max_requests).
property Pattern #
Pattern #public string Pattern { get; set; }
Route pattern: exact (“/api/scans”), prefix (“/api/scans/*”), or regex (“^/api/scans/[a-f0-9-]+$”).
property PerSeconds #
PerSeconds #public int? PerSeconds { get; set; }
The window of the single-window limit, in seconds (per_seconds).
property Rules #
Rules #public List<RateLimitRule> Rules { get; set; }
Multi-rule configuration (preferred). When specified, takes precedence over the single-window fields.
method GetEffectiveRules() #
GetEffectiveRules() #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.
method Validate(string) #
Validate(string) #public void Validate(string path)
Validates the route limits and compiles a regex pattern.
Parameters
path: The configuration path, for messages.
Exceptions
ArgumentException: A setting is missing or invalid.
enum RouteMatchType
public enum RouteMatchType
How a route rate limit pattern matches a request path.
| Value | Description |
|---|---|
Exact = 0 | The path equals the pattern. |
Prefix = 1 | The path starts with the pattern. |
Regex = 2 | The path matches the pattern as a regular expression, ignoring case. |
namespace StellaOps.Router.Gateway.Services
| Type | Kind | Description |
|---|---|---|
IRekorSubmissionService | interface | Service for submitting DSSE envelopes to Rekor. |
IRouterGatewayLocalHarnessTransport | interface | Gateway-side adapter for process-local development and test transports. |
IRoutingWeightOverrideStore | interface | Process-local routing weight overrides used for live canary tuning. |
InMemoryRoutingWeightOverrideStore | class | Thread-safe in-memory implementation of IRoutingWeightOverrideStore. |
RekorLinkage | record | Rekor linkage record. |
RekorSubmissionOptions | class | Configuration for Rekor submission. |
RekorSubmissionResult | record | Rekor submission result. |
RekorSubmissionService | class | Default implementation of Rekor submission service. |
RoutingWeightOverride | record | One service/version or service/version/instance routing weight override. |
RoutingWeightResolution | record | Effective routing weight plus the source that supplied it. |
interface IRekorSubmissionService
public interface IRekorSubmissionService
Service for submitting DSSE envelopes to Rekor.
Members
| Member | Kind | Summary |
|---|---|---|
GetLinkageAsync( | method | Gets the Rekor linkage for a digest. |
QueueForSubmission( | method | Queues a DSSE envelope for async submission. |
SubmitDsseAsync( | method | Submits a DSSE envelope to Rekor. |
method GetLinkageAsync(string, CancellationToken) #
GetLinkageAsync(string, CancellationToken) #Task<RekorLinkage?> GetLinkageAsync(string digest, CancellationToken ct = default)
Gets the Rekor linkage for a digest.
method QueueForSubmission(string, byte[]) #
QueueForSubmission(string, byte[]) #void QueueForSubmission(string digest, byte[] dsseEnvelope)
Queues a DSSE envelope for async submission.
method SubmitDsseAsync(string, byte[], CancellationToken) #
SubmitDsseAsync(string, byte[], CancellationToken) #Task<RekorSubmissionResult> SubmitDsseAsync(string digest, byte[] dsseEnvelope, CancellationToken ct = default)
Submits a DSSE envelope to Rekor.
interface IRouterGatewayLocalHarnessTransport
public interface IRouterGatewayLocalHarnessTransport : ITransportServer
Gateway-side adapter for process-local development and test transports.
Members
| Member | Kind | Summary |
|---|---|---|
OnConnectionClosed | event | Raised when a local connection closes, with its identifier. |
OnHeartbeatReceived | event | Raised for each heartbeat of a local microservice. |
OnHelloReceived | event | Raised when a local microservice announces itself and its endpoints (a HELLO). |
RemoveConnection( | method | Removes a connection. |
StartListeningToConnection( | method | Starts reading the frames of a connection. |
event OnConnectionClosed #
OnConnectionClosed #event Func<string, Task>? OnConnectionClosed
Raised when a local connection closes, with its identifier.
event OnHeartbeatReceived #
OnHeartbeatReceived #event Func<ConnectionState, HeartbeatPayload, Task>? OnHeartbeatReceived
Raised for each heartbeat of a local microservice.
event OnHelloReceived #
OnHelloReceived #event Func<ConnectionState, HelloPayload, Task>? OnHelloReceived
Raised when a local microservice announces itself and its endpoints (a HELLO).
method RemoveConnection(string) #
RemoveConnection(string) #bool RemoveConnection(string connectionId)
Removes a connection.
Parameters
connectionId: The connection identifier.
Returns
true when the connection existed.
method StartListeningToConnection(string) #
StartListeningToConnection(string) #void StartListeningToConnection(string connectionId)
Starts reading the frames of a connection.
Parameters
connectionId: The connection identifier.
interface IRoutingWeightOverrideStore
public interface IRoutingWeightOverrideStore
Process-local routing weight overrides used for live canary tuning.
Members
| Member | Kind | Summary |
|---|---|---|
MaxWeight | property | Gets the maximum accepted runtime override weight. |
GetOverrides( | method | Gets the current runtime and startup-configured overrides. |
Resolve( | method | Resolves the effective weight for a live connection. |
Upsert( | method | Adds or replaces one routing weight override. |
property MaxWeight #
MaxWeight #int MaxWeight { get; }
Gets the maximum accepted runtime override weight.
method GetOverrides() #
GetOverrides() #IReadOnlyList<RoutingWeightOverride> GetOverrides()
Gets the current runtime and startup-configured overrides.
method Resolve(ConnectionState) #
Resolve(ConnectionState) #RoutingWeightResolution Resolve(ConnectionState connection)
Resolves the effective weight for a live connection.
method Upsert(RoutingWeightOverride) #
Upsert(RoutingWeightOverride) #RoutingWeightOverride Upsert(RoutingWeightOverride weightOverride)
Adds or replaces one routing weight override.
class InMemoryRoutingWeightOverrideStore
public sealed class InMemoryRoutingWeightOverrideStore : IRoutingWeightOverrideStore
Thread-safe in-memory implementation of IRoutingWeightOverrideStore.
Members
| Member | Kind | Summary |
|---|---|---|
InMemoryRoutingWeightOverrideStore( | constructor | Creates the store with the overrides the routing options configure at startup. |
MaxWeight | property | Gets the maximum accepted runtime override weight. |
GetOverrides( | method | Gets the current runtime and startup-configured overrides. |
Resolve( | method | Resolves the effective weight for a live connection. |
Upsert( | method | Adds or replaces one routing weight override. |
constructor InMemoryRoutingWeightOverrideStore(IOptions<RoutingOptions>) #
InMemoryRoutingWeightOverrideStore(IOptions<RoutingOptions>) #public InMemoryRoutingWeightOverrideStore(IOptions<RoutingOptions> options)
Creates the store with the overrides the routing options configure at startup.
Parameters
options: The routing options.
property MaxWeight #
MaxWeight #public int MaxWeight { get; }
Gets the maximum accepted runtime override weight.
method GetOverrides() #
GetOverrides() #public IReadOnlyList<RoutingWeightOverride> GetOverrides()
Gets the current runtime and startup-configured overrides.
method Resolve(ConnectionState) #
Resolve(ConnectionState) #public RoutingWeightResolution Resolve(ConnectionState connection)
Resolves the effective weight for a live connection.
method Upsert(RoutingWeightOverride) #
Upsert(RoutingWeightOverride) #public RoutingWeightOverride Upsert(RoutingWeightOverride weightOverride)
Adds or replaces one routing weight override.
record RekorLinkage
public sealed record RekorLinkage
Rekor linkage record.
Members
| Member | Kind | Summary |
|---|---|---|
RekorLinkage( | constructor | Creates an instance of RekorLinkage. |
CreatedAt | property | When this linkage was created. |
Digest | property | Artifact digest. |
EnvelopeHash | property | DSSE envelope hash. |
IntegratedAt | property | When the entry was integrated. |
LogIndex | property | Rekor log index. |
RekorUuid | property | Rekor UUID. |
constructor RekorLinkage() #
RekorLinkage() #public RekorLinkage()
Creates an instance of RekorLinkage.
property CreatedAt #
CreatedAt #public DateTimeOffset CreatedAt { get; init; }
When this linkage was created.
property Digest #
Digest #public required string Digest { get; init; }
Artifact digest.
property EnvelopeHash #
EnvelopeHash #public required string EnvelopeHash { get; init; }
DSSE envelope hash.
property IntegratedAt #
IntegratedAt #public DateTimeOffset IntegratedAt { get; init; }
When the entry was integrated.
property LogIndex #
LogIndex #public long LogIndex { get; init; }
Rekor log index.
property RekorUuid #
RekorUuid #public required string RekorUuid { get; init; }
Rekor UUID.
class RekorSubmissionOptions
public sealed class RekorSubmissionOptions
Configuration for Rekor submission.
Members
| Member | Kind | Summary |
|---|---|---|
RekorSubmissionOptions( | constructor | Creates an instance of Rekor. |
AsyncSubmission | property | Whether to submit asynchronously (don’t block push). |
CacheLinkage | property | Cache Rekor linkage results. |
CacheTtlSeconds | property | Cache TTL in seconds. |
RekorUrl | property | Rekor instance URL. |
RetryAttempts | property | Number of retry attempts. |
SubmitToRekor | property | Whether to submit attestations to Rekor. |
TimeoutSeconds | property | Timeout for Rekor submission in seconds. |
constructor RekorSubmissionOptions() #
RekorSubmissionOptions() #public RekorSubmissionOptions()
Creates an instance of Rekor.
property AsyncSubmission #
AsyncSubmission #public bool AsyncSubmission { get; set; }
Whether to submit asynchronously (don’t block push).
property CacheLinkage #
CacheLinkage #public bool CacheLinkage { get; set; }
Cache Rekor linkage results.
property CacheTtlSeconds #
CacheTtlSeconds #public int CacheTtlSeconds { get; set; }
Cache TTL in seconds.
property RekorUrl #
RekorUrl #public string RekorUrl { get; set; }
Rekor instance URL.
property RetryAttempts #
RetryAttempts #public int RetryAttempts { get; set; }
Number of retry attempts.
property SubmitToRekor #
SubmitToRekor #public bool SubmitToRekor { get; set; }
Whether to submit attestations to Rekor.
property TimeoutSeconds #
TimeoutSeconds #public int TimeoutSeconds { get; set; }
Timeout for Rekor submission in seconds.
record RekorSubmissionResult
public sealed record RekorSubmissionResult
Rekor submission result.
Members
| Member | Kind | Summary |
|---|---|---|
RekorSubmissionResult( | constructor | Creates an instance of Rekor. |
Error | property | Error message if failed. |
IntegratedAt | property | Integrated timestamp. |
LogIndex | property | Rekor log index. |
Success | property | Whether submission was successful. |
Uuid | property | Rekor entry UUID. |
constructor RekorSubmissionResult() #
RekorSubmissionResult() #public RekorSubmissionResult()
Creates an instance of Rekor.
property Error #
Error #public string? Error { get; init; }
Error message if failed.
property IntegratedAt #
IntegratedAt #public DateTimeOffset? IntegratedAt { get; init; }
Integrated timestamp.
property LogIndex #
LogIndex #public long? LogIndex { get; init; }
Rekor log index.
property Success #
Success #public bool Success { get; init; }
Whether submission was successful.
property Uuid #
Uuid #public string? Uuid { get; init; }
Rekor entry UUID.
class RekorSubmissionService
public sealed class RekorSubmissionService : IRekorSubmissionService, IDisposable
Default implementation of Rekor submission service.
Members
| Member | Kind | Summary |
|---|---|---|
RekorSubmissionService( | constructor | Creates the service. |
Dispose( | method | Releases the service. |
GetLinkageAsync( | method | Gets the Rekor linkage for a digest. |
QueueForSubmission( | method | Queues a DSSE envelope for async submission. |
SubmitDsseAsync( | method | Submits a DSSE envelope to Rekor. |
constructor RekorSubmissionService(HttpClient, IMemoryCache, IOptions<RekorSubmissionOptions>, ILogger<RekorSubmissionService>) #
RekorSubmissionService(HttpClient, IMemoryCache, IOptions<RekorSubmissionOptions>, ILogger<RekorSubmissionService>) #public RekorSubmissionService(HttpClient httpClient, IMemoryCache cache, IOptions<RekorSubmissionOptions> options, ILogger<RekorSubmissionService> logger)
Creates the service.
Parameters
httpClient: The client that calls the transparency log.cache: Caches the linkages.options: The transparency log settings.logger: Receives the diagnostics.
method Dispose() #
Dispose() #public void Dispose()
Releases the service.
method GetLinkageAsync(string, CancellationToken) #
GetLinkageAsync(string, CancellationToken) #public Task<RekorLinkage?> GetLinkageAsync(string digest, CancellationToken ct = default)
Gets the Rekor linkage for a digest.
method QueueForSubmission(string, byte[]) #
QueueForSubmission(string, byte[]) #public void QueueForSubmission(string digest, byte[] dsseEnvelope)
Queues a DSSE envelope for async submission.
method SubmitDsseAsync(string, byte[], CancellationToken) #
SubmitDsseAsync(string, byte[], CancellationToken) #public Task<RekorSubmissionResult> SubmitDsseAsync(string digest, byte[] dsseEnvelope, CancellationToken ct = default)
Submits a DSSE envelope to Rekor.
record RoutingWeightOverride
public sealed record RoutingWeightOverride
One service/version or service/version/instance routing weight override.
Parameters
Service: The service.Version: The service version.InstanceId: The instance; the override applies to the whole version when not set.Weight: The routing weight.
Members
| Member | Kind | Summary |
|---|---|---|
RoutingWeightOverride( | constructor | One service/version or service/version/instance routing weight override. |
InstanceId | property | The instance; the override applies to the whole version when not set. |
Service | property | The service. |
Version | property | The service version. |
Weight | property | The routing weight. |
constructor RoutingWeightOverride(string, string, string, int) #
RoutingWeightOverride(string, string, string, int) #public RoutingWeightOverride(string Service, string Version, string? InstanceId, int Weight)
One service/version or service/version/instance routing weight override.
Parameters
Service: The service.Version: The service version.InstanceId: The instance; the override applies to the whole version when not set.Weight: The routing weight.
property InstanceId #
InstanceId #public string? InstanceId { get; init; }
The instance; the override applies to the whole version when not set.
property Service #
Service #public string Service { get; init; }
The service.
property Version #
Version #public string Version { get; init; }
The service version.
property Weight #
Weight #public int Weight { get; init; }
The routing weight.
record RoutingWeightResolution
public sealed record RoutingWeightResolution
Effective routing weight plus the source that supplied it.
Parameters
Weight: The effective weight.Source: Where the weight comes from:instanceOverride,versionOverrideorinstance(the weight the instance announced).
Members
| Member | Kind | Summary |
|---|---|---|
RoutingWeightResolution( | constructor | Effective routing weight plus the source that supplied it. |
Source | property | Where the weight comes from: instanceOverride, versionOverride or instance (the weight the instance announced). |
Weight | property | The effective weight. |
constructor RoutingWeightResolution(int, string) #
RoutingWeightResolution(int, string) #public RoutingWeightResolution(int Weight, string Source)
Effective routing weight plus the source that supplied it.
Parameters
Weight: The effective weight.Source: Where the weight comes from:instanceOverride,versionOverrideorinstance(the weight the instance announced).
property Source #
Source #public string Source { get; init; }
Where the weight comes from: instanceOverride, versionOverride or instance (the weight the instance announced).
property Weight #
Weight #public int Weight { get; init; }
The effective weight.